dsh-skill-harbor 0.3.1 → 0.4.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dsh.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "dsh-external/dsh-skill-harbor",
3
- "version": "0.3.1",
3
+ "version": "0.4.0-rc.1",
4
4
  "main": "./lib/index.js",
5
5
  "description": "技能港湾:技能发现、遮蔽判定、审计与市场管理(基础骨架)",
6
6
  "engines": {
@@ -37,6 +37,14 @@ function injectStyles() {
37
37
  .dshh-verdict[data-v="warn"] { background: #ed6c0233; color: #ff9800; }
38
38
  .dshh-verdict[data-v="fail"] { background: #c6282833; color: #f44336; }
39
39
  .dshh-verdict[data-v="skipped"] { background: #9e9e9e33; color: #9e9e9e; }
40
+ .dshh-dup-panel { border: 1px solid var(--dsw-alias-border, #3334); border-radius: 6px; padding: 10px; margin-bottom: 12px; }
41
+ .dshh-dup-heading { font-weight: 600; margin-bottom: 8px; }
42
+ .dshh-dup-group { margin-bottom: 10px; }
43
+ .dshh-dup-group:last-child { margin-bottom: 0; }
44
+ .dshh-dup-title { font-size: 12px; opacity: 0.75; margin-bottom: 4px; }
45
+ .dshh-dup-row { display: flex; align-items: center; gap: 6px; padding: 3px 0; font-size: 12px; }
46
+ .dshh-dup-meta { opacity: 0.6; }
47
+ .dshh-dup-winner { color: #4caf50; font-weight: 600; }
40
48
  `
41
49
  document.head.appendChild(style)
42
50
  }
@@ -99,6 +107,52 @@ export function createPanel(options = {}) {
99
107
  return el('div', { className: 'dshh-empty', text: t.noSkills })
100
108
  }
101
109
 
110
+ return el('div', {}, [
111
+ // 同名冲突先给树状视图:谁的 rank 高、谁被压住
112
+ state.duplicates.length > 0 ? renderDuplicates() : el('span', {}),
113
+ renderTable(),
114
+ ])
115
+ }
116
+
117
+ /**
118
+ * 遮蔽关系树:一组同名技能按 rank 升序竖排,
119
+ * 胜者标「胜出」,其余标注被谁压住。
120
+ */
121
+ function renderDuplicates() {
122
+ const groups = state.duplicates.map(group => {
123
+ // 从 skills 里捞出该组的全部条目(list 已按 rank 排序)
124
+ const entries = state.skills
125
+ .filter(skill => skill.name.toLowerCase() === group.name.toLowerCase())
126
+ .sort((a, b) => a.rank - b.rank)
127
+
128
+ const rows = entries.map((skill, index) => {
129
+ const isWinner = index === 0
130
+ return el('div', {
131
+ className: isWinner ? 'dshh-dup-row' : 'dshh-dup-row dshh-shadowed',
132
+ style: `padding-left:${index * 16}px`,
133
+ }, [
134
+ el('span', { text: isWinner ? '▼ ' : ' └ ' }),
135
+ el('span', { text: `${skill.name} ` }),
136
+ el('span', { className: 'dshh-dup-meta', text: `${sourceLabel(t, skill.source)} (rank ${skill.rank})` }),
137
+ isWinner
138
+ ? el('span', { className: 'dshh-dup-winner', text: ` — ${t.winner}` })
139
+ : el('span', { className: 'dshh-shadow-tag', text: ` — ${t.shadowedBy}` }),
140
+ ])
141
+ })
142
+
143
+ return el('div', { className: 'dshh-dup-group' }, [
144
+ el('div', { className: 'dshh-dup-title', text: `${t.duplicateGroup}: ${group.name}` }),
145
+ ...rows,
146
+ ])
147
+ })
148
+
149
+ return el('div', { className: 'dshh-dup-panel' }, [
150
+ el('div', { className: 'dshh-dup-heading', text: t.duplicateGroup }),
151
+ ...groups,
152
+ ])
153
+ }
154
+
155
+ function renderTable() {
102
156
  const rows = state.skills.map(skill => {
103
157
  const shadowed = skill.shadowedBy !== null
104
158
  const cells = [
@@ -0,0 +1,94 @@
1
+ /**
2
+ * 仓库抓取与更新检查。
3
+ *
4
+ * 安全纪律:
5
+ * - 只接受 http(s),且只拼接受信主机(GitHub 系)——不跟随任意 URL
6
+ * - 归档下载后**不执行任何仓库代码**,只解包 + 审计
7
+ * - 更新检查只读 ref → sha 的映射,不改盘
8
+ */
9
+ import { createHash } from 'node:crypto'
10
+
11
+ import { isCommitSha, makeSource, checkUpdate, applySync } from './source.js'
12
+
13
+ /** 允许的主机白名单(不跟随任意 URL)。 */
14
+ export const ALLOWED_HOSTS = new Set([
15
+ 'github.com',
16
+ 'api.github.com',
17
+ 'codeload.github.com',
18
+ 'raw.githubusercontent.com',
19
+ ])
20
+
21
+ const FETCH_TIMEOUT_MS = 20_000
22
+ const MAX_ARCHIVE_BYTES = 8 * 1024 * 1024
23
+
24
+ /** 校验并构造一个 GitHub 归档 URL;非白名单主机一律拒绝。 */
25
+ export function archiveUrl({ owner, repo, sha }) {
26
+ if (!isCommitSha(sha)) return { ok: false, reason: 'invalid-sha' }
27
+ if (!/^[\w.-]+$/.test(owner) || !/^[\w.-]+$/.test(repo)) {
28
+ return { ok: false, reason: 'invalid-owner-or-repo' }
29
+ }
30
+ const host = 'codeload.github.com'
31
+ if (!ALLOWED_HOSTS.has(host)) return { ok: false, reason: 'host-not-allowed' }
32
+ return { ok: true, url: `https://${host}/${owner}/${repo}/zip/${sha}` }
33
+ }
34
+
35
+ /** 校验一个远端 URL 是否可信。 */
36
+ export function isAllowedUrl(raw) {
37
+ try {
38
+ const url = new URL(raw)
39
+ if (url.protocol !== 'https:') return false
40
+ return ALLOWED_HOSTS.has(url.hostname.toLowerCase())
41
+ } catch {
42
+ return false
43
+ }
44
+ }
45
+
46
+ /**
47
+ * 下载归档到内存(带超时与体积上限)。
48
+ * @returns {{ ok: true, buffer: Buffer, sha256: string } | { ok: false, reason: string }}
49
+ */
50
+ export async function fetchArchive(url, fetchImpl = globalThis.fetch) {
51
+ if (!isAllowedUrl(url)) return { ok: false, reason: 'url-not-allowed' }
52
+ if (typeof fetchImpl !== 'function') return { ok: false, reason: 'fetch-unavailable' }
53
+
54
+ const controller = new AbortController()
55
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
56
+ try {
57
+ const response = await fetchImpl(url, { signal: controller.signal, redirect: 'follow' })
58
+ if (!response.ok) return { ok: false, reason: `http-${response.status}` }
59
+
60
+ const declared = Number(response.headers?.get?.('content-length') ?? '0')
61
+ if (declared > MAX_ARCHIVE_BYTES) {
62
+ return { ok: false, reason: 'archive-too-large', declared }
63
+ }
64
+
65
+ const buffer = Buffer.from(await response.arrayBuffer())
66
+ if (buffer.length > MAX_ARCHIVE_BYTES) {
67
+ return { ok: false, reason: 'archive-too-large', actual: buffer.length }
68
+ }
69
+ return { ok: true, buffer, sha256: createHash('sha256').update(buffer).digest('hex') }
70
+ } catch (error) {
71
+ const reason = error?.name === 'AbortError' ? 'timeout' : 'fetch-failed'
72
+ return { ok: false, reason, message: String(error?.message ?? error) }
73
+ } finally {
74
+ clearTimeout(timer)
75
+ }
76
+ }
77
+
78
+ /** 解析 GitHub commit API 的响应,取出完整 sha。 */
79
+ export function parseCommitResponse(payload) {
80
+ if (payload === null || typeof payload !== 'object') {
81
+ return { ok: false, reason: 'not-an-object' }
82
+ }
83
+ const sha = payload.sha
84
+ if (!isCommitSha(sha)) return { ok: false, reason: 'invalid-sha' }
85
+ return { ok: true, sha: String(sha).toLowerCase() }
86
+ }
87
+
88
+ /** 由一次成功的 ref 解析生成钉死的源记录。 */
89
+ export function sourceFromResolve({ owner, repo, ref, sha }) {
90
+ if (!isCommitSha(sha)) return { ok: false, reason: 'invalid-sha' }
91
+ return { ok: true, source: makeSource({ owner, repo, ref, commitSha: sha }) }
92
+ }
93
+
94
+ export { checkUpdate, applySync }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * 仓库源模型(findings:ref + commitSha 双存,id 由 hash 推导)。
3
+ *
4
+ * 关键设计:
5
+ * - `ref` 是用户可读的(`main` / `v1.2.0`),`commitSha` 是钉死的实际提交。
6
+ * 只存 ref 会在上游推进后悄悄改变内容(浮动 ref 事故),只存 sha 又没法更新。
7
+ * - `id` 由内容 hash 推导而非随机 UUID:状态文件被篡改时 id 重算不出来,
8
+ * 加载即失败 —— 这正是我们想要的(宁可拒绝,不要静默接受被改过的状态)。
9
+ */
10
+ import { createHash } from 'node:crypto'
11
+
12
+ /** 一个仓库源的规范化形状。 */
13
+ export function makeSource({ owner, repo, ref, commitSha }) {
14
+ const normalized = {
15
+ owner: String(owner ?? '').trim(),
16
+ repo: String(repo ?? '').trim(),
17
+ ref: String(ref ?? 'HEAD').trim(),
18
+ commitSha: String(commitSha ?? '').trim().toLowerCase(),
19
+ }
20
+ return { ...normalized, id: deriveId(normalized) }
21
+ }
22
+
23
+ /** id = hash(owner/repo@ref#sha) 的前 16 位。改任一字段 id 就变。 */
24
+ export function deriveId({ owner, repo, ref, commitSha }) {
25
+ const material = `${owner}/${repo}@${ref}#${commitSha}`
26
+ return createHash('sha256').update(material).digest('hex').slice(0, 16)
27
+ }
28
+
29
+ /** sha 形状校验:完整 40 位或短 7-40 位十六进制。 */
30
+ export function isCommitSha(value) {
31
+ return typeof value === 'string' && /^[0-9a-f]{7,40}$/i.test(value)
32
+ }
33
+
34
+ /** 校验并解析一个持久化的源记录;id 不匹配即拒绝(篡改检测)。 */
35
+ export function loadSource(record) {
36
+ if (record === null || typeof record !== 'object') {
37
+ return { ok: false, reason: 'not-an-object' }
38
+ }
39
+ const { owner, repo, ref, commitSha, id } = record
40
+ if (typeof owner !== 'string' || owner === '') return { ok: false, reason: 'missing-owner' }
41
+ if (typeof repo !== 'string' || repo === '') return { ok: false, reason: 'missing-repo' }
42
+ if (!isCommitSha(commitSha)) return { ok: false, reason: 'invalid-sha' }
43
+
44
+ const expected = deriveId({ owner, repo, ref, commitSha })
45
+ if (id !== expected) {
46
+ return { ok: false, reason: 'id-mismatch', expected, actual: id }
47
+ }
48
+ return { ok: true, source: { owner, repo, ref, commitSha, id: expected } }
49
+ }
50
+
51
+ /** 序列化一组源(稳定排序,便于 diff)。 */
52
+ export function serializeSources(sources) {
53
+ return JSON.stringify(
54
+ [...sources].sort((a, b) => a.id.localeCompare(b.id)),
55
+ null,
56
+ 2,
57
+ )
58
+ }
59
+
60
+ /**
61
+ * 比较「已安装的钉死 sha」与「远端最新 sha」。
62
+ * 两者不同即视为有更新 —— 但**不自动同步**,由用户决定。
63
+ */
64
+ export function checkUpdate(installedSha, remoteSha) {
65
+ if (!isCommitSha(installedSha) || !isCommitSha(remoteSha)) {
66
+ return { ok: false, reason: 'invalid-sha', updateAvailable: null }
67
+ }
68
+ const installed = installedSha.toLowerCase()
69
+ const remote = remoteSha.toLowerCase()
70
+ return {
71
+ ok: true,
72
+ updateAvailable: installed !== remote,
73
+ installedSha: installed,
74
+ remoteSha: remote,
75
+ }
76
+ }
77
+
78
+ /** 同步:对齐到钉住的目标 sha,而不是跟随 ref 漂移。 */
79
+ export function applySync(source, remoteSha) {
80
+ if (!isCommitSha(remoteSha)) {
81
+ return { ok: false, reason: 'invalid-sha' }
82
+ }
83
+ const next = makeSource({
84
+ owner: source.owner,
85
+ repo: source.repo,
86
+ ref: source.ref,
87
+ commitSha: remoteSha,
88
+ })
89
+ return { ok: true, source: next, changed: next.id !== source.id }
90
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * 市场源持久化。
3
+ *
4
+ * 落在 `~/.dsh/skill-harbor/sources.json`(与前面所有路径同一套 base)。
5
+ * 读取时对每条记录做 `loadSource()` 校验:id 与内容 hash 不符即整条丢弃,
6
+ * 并回报丢弃原因 —— 宁可不显示,也不显示一条被篡改过的记录。
7
+ */
8
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs'
9
+ import { dirname, join } from 'node:path'
10
+
11
+ import { loadSource, serializeSources } from '../market/source.js'
12
+
13
+ /** 状态文件路径。 */
14
+ export function sourcesFile(config) {
15
+ const base = config.dshHome ?? join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh')
16
+ return join(base, 'skill-harbor', 'sources.json')
17
+ }
18
+
19
+ /**
20
+ * 读取全部源。返回对象同时带 `rejected`,便于 UI 提示「有条目被丢弃」。
21
+ */
22
+ export function readSources(config) {
23
+ const file = sourcesFile(config)
24
+ if (!existsSync(file)) return { sources: [], rejected: [] }
25
+
26
+ let parsed
27
+ try {
28
+ parsed = JSON.parse(readFileSync(file, 'utf8'))
29
+ } catch (error) {
30
+ return { sources: [], rejected: [{ reason: 'unreadable', message: String(error?.message ?? error) }] }
31
+ }
32
+ if (!Array.isArray(parsed)) {
33
+ return { sources: [], rejected: [{ reason: 'not-an-array' }] }
34
+ }
35
+
36
+ const sources = []
37
+ const rejected = []
38
+ for (const record of parsed) {
39
+ const result = loadSource(record)
40
+ if (result.ok) sources.push(result.source)
41
+ else rejected.push({ reason: result.reason, record })
42
+ }
43
+ return { sources, rejected }
44
+ }
45
+
46
+ /** 写入(原子 rename,避免半截文件)。 */
47
+ export function writeSources(config, sources) {
48
+ const file = sourcesFile(config)
49
+ mkdirSync(dirname(file), { recursive: true })
50
+ const temp = `${file}.tmp-${process.pid}`
51
+ writeFileSync(temp, serializeSources(sources), 'utf8')
52
+ renameSync(temp, file)
53
+ return file
54
+ }
55
+
56
+ /**
57
+ * 保存一个源:同 id 覆盖,否则追加。
58
+ * 若读取时发现有被丢弃的条目,**不写回**它们(丢弃是永久的,避免把坏数据带下去)。
59
+ */
60
+ export function saveSource(config, source) {
61
+ const { sources } = readSources(config)
62
+ const next = sources.filter(item => item.id !== source.id)
63
+ next.push(source)
64
+ writeSources(config, next)
65
+ return source
66
+ }
@@ -16,6 +16,12 @@ import { extractSkillMeta } from '../collect/frontmatter.js'
16
16
  import { auditSkillText } from '../audit/rules.js'
17
17
  import { budgetReport } from '../budget/announcement.js'
18
18
  import { parseSkillsFromArchive, decidePlacement, installSkill } from '../market/install.js'
19
+ import { makeSource, isCommitSha, checkUpdate, applySync } from '../market/source.js'
20
+ import { readSources, saveSource } from '../market/store.js'
21
+
22
+ function listSources(config) {
23
+ return readSources(config).sources
24
+ }
19
25
 
20
26
  /** 关闭/开启模型的 frontmatter 键。 */
21
27
  const DISABLE_KEY = 'disable-model-invocation'
@@ -370,6 +376,61 @@ export function registerRoutes(ctx, config = {}, deps = {}) {
370
376
  })
371
377
  })
372
378
 
379
+ // ---- 市场:列出已登记仓库源 ----
380
+ register('/market/sources', ['GET'], async (req, res) => {
381
+ sendJson(res, 200, { sources: listSources(config) })
382
+ })
383
+
384
+ // ---- 市场:登记一个仓库源(钉 commit) ----
385
+ register('/market/add-source', ['POST'], async (req, res, body) => {
386
+ const { owner, repo, ref, commitSha } = body ?? {}
387
+ if (typeof owner !== 'string' || typeof repo !== 'string') {
388
+ sendJson(res, 400, { error: 'owner-and-repo-required' })
389
+ return
390
+ }
391
+ if (!isCommitSha(commitSha)) {
392
+ // 浮动 ref 拒绝入库:必须先解析成 sha
393
+ sendJson(res, 400, { error: 'commit-sha-required', message: '仓库源必须钉死 commitSha,不接受浮动 ref' })
394
+ return
395
+ }
396
+ const source = makeSource({ owner, repo, ref: ref ?? 'HEAD', commitSha })
397
+ const saved = saveSource(config, source)
398
+ sendJson(res, 200, { ok: true, source: saved })
399
+ })
400
+
401
+ // ---- 市场:检查更新(只读,不落盘) ----
402
+ register('/market/check', ['POST'], async (req, res, body) => {
403
+ const { id, remoteSha } = body ?? {}
404
+ const source = listSources(config).find(item => item.id === id)
405
+ if (source === undefined) {
406
+ sendJson(res, 404, { error: 'source-not-found' })
407
+ return
408
+ }
409
+ const result = checkUpdate(source.commitSha, remoteSha)
410
+ if (!result.ok) {
411
+ sendJson(res, 400, { error: result.reason })
412
+ return
413
+ }
414
+ sendJson(res, 200, { ok: true, source: source.id, ...result })
415
+ })
416
+
417
+ // ---- 市场:同步到钉住的远端 sha ----
418
+ register('/market/sync', ['POST'], async (req, res, body) => {
419
+ const { id, remoteSha } = body ?? {}
420
+ const source = listSources(config).find(item => item.id === id)
421
+ if (source === undefined) {
422
+ sendJson(res, 404, { error: 'source-not-found' })
423
+ return
424
+ }
425
+ const result = applySync(source, remoteSha)
426
+ if (!result.ok) {
427
+ sendJson(res, 400, { error: result.reason })
428
+ return
429
+ }
430
+ saveSource(config, result.source)
431
+ sendJson(res, 200, { ok: true, changed: result.changed, source: result.source })
432
+ })
433
+
373
434
  return () => {
374
435
  for (const dispose of disposers) {
375
436
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-skill-harbor",
3
- "version": "0.3.1",
3
+ "version": "0.4.0-rc.1",
4
4
  "description": "DSH 技能港湾:技能发现、遮蔽判定、审计与市场管理插件(基础骨架)",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -37,6 +37,14 @@ function injectStyles() {
37
37
  .dshh-verdict[data-v="warn"] { background: #ed6c0233; color: #ff9800; }
38
38
  .dshh-verdict[data-v="fail"] { background: #c6282833; color: #f44336; }
39
39
  .dshh-verdict[data-v="skipped"] { background: #9e9e9e33; color: #9e9e9e; }
40
+ .dshh-dup-panel { border: 1px solid var(--dsw-alias-border, #3334); border-radius: 6px; padding: 10px; margin-bottom: 12px; }
41
+ .dshh-dup-heading { font-weight: 600; margin-bottom: 8px; }
42
+ .dshh-dup-group { margin-bottom: 10px; }
43
+ .dshh-dup-group:last-child { margin-bottom: 0; }
44
+ .dshh-dup-title { font-size: 12px; opacity: 0.75; margin-bottom: 4px; }
45
+ .dshh-dup-row { display: flex; align-items: center; gap: 6px; padding: 3px 0; font-size: 12px; }
46
+ .dshh-dup-meta { opacity: 0.6; }
47
+ .dshh-dup-winner { color: #4caf50; font-weight: 600; }
40
48
  `
41
49
  document.head.appendChild(style)
42
50
  }
@@ -99,6 +107,52 @@ export function createPanel(options = {}) {
99
107
  return el('div', { className: 'dshh-empty', text: t.noSkills })
100
108
  }
101
109
 
110
+ return el('div', {}, [
111
+ // 同名冲突先给树状视图:谁的 rank 高、谁被压住
112
+ state.duplicates.length > 0 ? renderDuplicates() : el('span', {}),
113
+ renderTable(),
114
+ ])
115
+ }
116
+
117
+ /**
118
+ * 遮蔽关系树:一组同名技能按 rank 升序竖排,
119
+ * 胜者标「胜出」,其余标注被谁压住。
120
+ */
121
+ function renderDuplicates() {
122
+ const groups = state.duplicates.map(group => {
123
+ // 从 skills 里捞出该组的全部条目(list 已按 rank 排序)
124
+ const entries = state.skills
125
+ .filter(skill => skill.name.toLowerCase() === group.name.toLowerCase())
126
+ .sort((a, b) => a.rank - b.rank)
127
+
128
+ const rows = entries.map((skill, index) => {
129
+ const isWinner = index === 0
130
+ return el('div', {
131
+ className: isWinner ? 'dshh-dup-row' : 'dshh-dup-row dshh-shadowed',
132
+ style: `padding-left:${index * 16}px`,
133
+ }, [
134
+ el('span', { text: isWinner ? '▼ ' : ' └ ' }),
135
+ el('span', { text: `${skill.name} ` }),
136
+ el('span', { className: 'dshh-dup-meta', text: `${sourceLabel(t, skill.source)} (rank ${skill.rank})` }),
137
+ isWinner
138
+ ? el('span', { className: 'dshh-dup-winner', text: ` — ${t.winner}` })
139
+ : el('span', { className: 'dshh-shadow-tag', text: ` — ${t.shadowedBy}` }),
140
+ ])
141
+ })
142
+
143
+ return el('div', { className: 'dshh-dup-group' }, [
144
+ el('div', { className: 'dshh-dup-title', text: `${t.duplicateGroup}: ${group.name}` }),
145
+ ...rows,
146
+ ])
147
+ })
148
+
149
+ return el('div', { className: 'dshh-dup-panel' }, [
150
+ el('div', { className: 'dshh-dup-heading', text: t.duplicateGroup }),
151
+ ...groups,
152
+ ])
153
+ }
154
+
155
+ function renderTable() {
102
156
  const rows = state.skills.map(skill => {
103
157
  const shadowed = skill.shadowedBy !== null
104
158
  const cells = [
@@ -0,0 +1,94 @@
1
+ /**
2
+ * 仓库抓取与更新检查。
3
+ *
4
+ * 安全纪律:
5
+ * - 只接受 http(s),且只拼接受信主机(GitHub 系)——不跟随任意 URL
6
+ * - 归档下载后**不执行任何仓库代码**,只解包 + 审计
7
+ * - 更新检查只读 ref → sha 的映射,不改盘
8
+ */
9
+ import { createHash } from 'node:crypto'
10
+
11
+ import { isCommitSha, makeSource, checkUpdate, applySync } from './source.js'
12
+
13
+ /** 允许的主机白名单(不跟随任意 URL)。 */
14
+ export const ALLOWED_HOSTS = new Set([
15
+ 'github.com',
16
+ 'api.github.com',
17
+ 'codeload.github.com',
18
+ 'raw.githubusercontent.com',
19
+ ])
20
+
21
+ const FETCH_TIMEOUT_MS = 20_000
22
+ const MAX_ARCHIVE_BYTES = 8 * 1024 * 1024
23
+
24
+ /** 校验并构造一个 GitHub 归档 URL;非白名单主机一律拒绝。 */
25
+ export function archiveUrl({ owner, repo, sha }) {
26
+ if (!isCommitSha(sha)) return { ok: false, reason: 'invalid-sha' }
27
+ if (!/^[\w.-]+$/.test(owner) || !/^[\w.-]+$/.test(repo)) {
28
+ return { ok: false, reason: 'invalid-owner-or-repo' }
29
+ }
30
+ const host = 'codeload.github.com'
31
+ if (!ALLOWED_HOSTS.has(host)) return { ok: false, reason: 'host-not-allowed' }
32
+ return { ok: true, url: `https://${host}/${owner}/${repo}/zip/${sha}` }
33
+ }
34
+
35
+ /** 校验一个远端 URL 是否可信。 */
36
+ export function isAllowedUrl(raw) {
37
+ try {
38
+ const url = new URL(raw)
39
+ if (url.protocol !== 'https:') return false
40
+ return ALLOWED_HOSTS.has(url.hostname.toLowerCase())
41
+ } catch {
42
+ return false
43
+ }
44
+ }
45
+
46
+ /**
47
+ * 下载归档到内存(带超时与体积上限)。
48
+ * @returns {{ ok: true, buffer: Buffer, sha256: string } | { ok: false, reason: string }}
49
+ */
50
+ export async function fetchArchive(url, fetchImpl = globalThis.fetch) {
51
+ if (!isAllowedUrl(url)) return { ok: false, reason: 'url-not-allowed' }
52
+ if (typeof fetchImpl !== 'function') return { ok: false, reason: 'fetch-unavailable' }
53
+
54
+ const controller = new AbortController()
55
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
56
+ try {
57
+ const response = await fetchImpl(url, { signal: controller.signal, redirect: 'follow' })
58
+ if (!response.ok) return { ok: false, reason: `http-${response.status}` }
59
+
60
+ const declared = Number(response.headers?.get?.('content-length') ?? '0')
61
+ if (declared > MAX_ARCHIVE_BYTES) {
62
+ return { ok: false, reason: 'archive-too-large', declared }
63
+ }
64
+
65
+ const buffer = Buffer.from(await response.arrayBuffer())
66
+ if (buffer.length > MAX_ARCHIVE_BYTES) {
67
+ return { ok: false, reason: 'archive-too-large', actual: buffer.length }
68
+ }
69
+ return { ok: true, buffer, sha256: createHash('sha256').update(buffer).digest('hex') }
70
+ } catch (error) {
71
+ const reason = error?.name === 'AbortError' ? 'timeout' : 'fetch-failed'
72
+ return { ok: false, reason, message: String(error?.message ?? error) }
73
+ } finally {
74
+ clearTimeout(timer)
75
+ }
76
+ }
77
+
78
+ /** 解析 GitHub commit API 的响应,取出完整 sha。 */
79
+ export function parseCommitResponse(payload) {
80
+ if (payload === null || typeof payload !== 'object') {
81
+ return { ok: false, reason: 'not-an-object' }
82
+ }
83
+ const sha = payload.sha
84
+ if (!isCommitSha(sha)) return { ok: false, reason: 'invalid-sha' }
85
+ return { ok: true, sha: String(sha).toLowerCase() }
86
+ }
87
+
88
+ /** 由一次成功的 ref 解析生成钉死的源记录。 */
89
+ export function sourceFromResolve({ owner, repo, ref, sha }) {
90
+ if (!isCommitSha(sha)) return { ok: false, reason: 'invalid-sha' }
91
+ return { ok: true, source: makeSource({ owner, repo, ref, commitSha: sha }) }
92
+ }
93
+
94
+ export { checkUpdate, applySync }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * 仓库源模型(findings:ref + commitSha 双存,id 由 hash 推导)。
3
+ *
4
+ * 关键设计:
5
+ * - `ref` 是用户可读的(`main` / `v1.2.0`),`commitSha` 是钉死的实际提交。
6
+ * 只存 ref 会在上游推进后悄悄改变内容(浮动 ref 事故),只存 sha 又没法更新。
7
+ * - `id` 由内容 hash 推导而非随机 UUID:状态文件被篡改时 id 重算不出来,
8
+ * 加载即失败 —— 这正是我们想要的(宁可拒绝,不要静默接受被改过的状态)。
9
+ */
10
+ import { createHash } from 'node:crypto'
11
+
12
+ /** 一个仓库源的规范化形状。 */
13
+ export function makeSource({ owner, repo, ref, commitSha }) {
14
+ const normalized = {
15
+ owner: String(owner ?? '').trim(),
16
+ repo: String(repo ?? '').trim(),
17
+ ref: String(ref ?? 'HEAD').trim(),
18
+ commitSha: String(commitSha ?? '').trim().toLowerCase(),
19
+ }
20
+ return { ...normalized, id: deriveId(normalized) }
21
+ }
22
+
23
+ /** id = hash(owner/repo@ref#sha) 的前 16 位。改任一字段 id 就变。 */
24
+ export function deriveId({ owner, repo, ref, commitSha }) {
25
+ const material = `${owner}/${repo}@${ref}#${commitSha}`
26
+ return createHash('sha256').update(material).digest('hex').slice(0, 16)
27
+ }
28
+
29
+ /** sha 形状校验:完整 40 位或短 7-40 位十六进制。 */
30
+ export function isCommitSha(value) {
31
+ return typeof value === 'string' && /^[0-9a-f]{7,40}$/i.test(value)
32
+ }
33
+
34
+ /** 校验并解析一个持久化的源记录;id 不匹配即拒绝(篡改检测)。 */
35
+ export function loadSource(record) {
36
+ if (record === null || typeof record !== 'object') {
37
+ return { ok: false, reason: 'not-an-object' }
38
+ }
39
+ const { owner, repo, ref, commitSha, id } = record
40
+ if (typeof owner !== 'string' || owner === '') return { ok: false, reason: 'missing-owner' }
41
+ if (typeof repo !== 'string' || repo === '') return { ok: false, reason: 'missing-repo' }
42
+ if (!isCommitSha(commitSha)) return { ok: false, reason: 'invalid-sha' }
43
+
44
+ const expected = deriveId({ owner, repo, ref, commitSha })
45
+ if (id !== expected) {
46
+ return { ok: false, reason: 'id-mismatch', expected, actual: id }
47
+ }
48
+ return { ok: true, source: { owner, repo, ref, commitSha, id: expected } }
49
+ }
50
+
51
+ /** 序列化一组源(稳定排序,便于 diff)。 */
52
+ export function serializeSources(sources) {
53
+ return JSON.stringify(
54
+ [...sources].sort((a, b) => a.id.localeCompare(b.id)),
55
+ null,
56
+ 2,
57
+ )
58
+ }
59
+
60
+ /**
61
+ * 比较「已安装的钉死 sha」与「远端最新 sha」。
62
+ * 两者不同即视为有更新 —— 但**不自动同步**,由用户决定。
63
+ */
64
+ export function checkUpdate(installedSha, remoteSha) {
65
+ if (!isCommitSha(installedSha) || !isCommitSha(remoteSha)) {
66
+ return { ok: false, reason: 'invalid-sha', updateAvailable: null }
67
+ }
68
+ const installed = installedSha.toLowerCase()
69
+ const remote = remoteSha.toLowerCase()
70
+ return {
71
+ ok: true,
72
+ updateAvailable: installed !== remote,
73
+ installedSha: installed,
74
+ remoteSha: remote,
75
+ }
76
+ }
77
+
78
+ /** 同步:对齐到钉住的目标 sha,而不是跟随 ref 漂移。 */
79
+ export function applySync(source, remoteSha) {
80
+ if (!isCommitSha(remoteSha)) {
81
+ return { ok: false, reason: 'invalid-sha' }
82
+ }
83
+ const next = makeSource({
84
+ owner: source.owner,
85
+ repo: source.repo,
86
+ ref: source.ref,
87
+ commitSha: remoteSha,
88
+ })
89
+ return { ok: true, source: next, changed: next.id !== source.id }
90
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * 市场源持久化。
3
+ *
4
+ * 落在 `~/.dsh/skill-harbor/sources.json`(与前面所有路径同一套 base)。
5
+ * 读取时对每条记录做 `loadSource()` 校验:id 与内容 hash 不符即整条丢弃,
6
+ * 并回报丢弃原因 —— 宁可不显示,也不显示一条被篡改过的记录。
7
+ */
8
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs'
9
+ import { dirname, join } from 'node:path'
10
+
11
+ import { loadSource, serializeSources } from '../market/source.js'
12
+
13
+ /** 状态文件路径。 */
14
+ export function sourcesFile(config) {
15
+ const base = config.dshHome ?? join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh')
16
+ return join(base, 'skill-harbor', 'sources.json')
17
+ }
18
+
19
+ /**
20
+ * 读取全部源。返回对象同时带 `rejected`,便于 UI 提示「有条目被丢弃」。
21
+ */
22
+ export function readSources(config) {
23
+ const file = sourcesFile(config)
24
+ if (!existsSync(file)) return { sources: [], rejected: [] }
25
+
26
+ let parsed
27
+ try {
28
+ parsed = JSON.parse(readFileSync(file, 'utf8'))
29
+ } catch (error) {
30
+ return { sources: [], rejected: [{ reason: 'unreadable', message: String(error?.message ?? error) }] }
31
+ }
32
+ if (!Array.isArray(parsed)) {
33
+ return { sources: [], rejected: [{ reason: 'not-an-array' }] }
34
+ }
35
+
36
+ const sources = []
37
+ const rejected = []
38
+ for (const record of parsed) {
39
+ const result = loadSource(record)
40
+ if (result.ok) sources.push(result.source)
41
+ else rejected.push({ reason: result.reason, record })
42
+ }
43
+ return { sources, rejected }
44
+ }
45
+
46
+ /** 写入(原子 rename,避免半截文件)。 */
47
+ export function writeSources(config, sources) {
48
+ const file = sourcesFile(config)
49
+ mkdirSync(dirname(file), { recursive: true })
50
+ const temp = `${file}.tmp-${process.pid}`
51
+ writeFileSync(temp, serializeSources(sources), 'utf8')
52
+ renameSync(temp, file)
53
+ return file
54
+ }
55
+
56
+ /**
57
+ * 保存一个源:同 id 覆盖,否则追加。
58
+ * 若读取时发现有被丢弃的条目,**不写回**它们(丢弃是永久的,避免把坏数据带下去)。
59
+ */
60
+ export function saveSource(config, source) {
61
+ const { sources } = readSources(config)
62
+ const next = sources.filter(item => item.id !== source.id)
63
+ next.push(source)
64
+ writeSources(config, next)
65
+ return source
66
+ }
@@ -16,6 +16,12 @@ import { extractSkillMeta } from '../collect/frontmatter.js'
16
16
  import { auditSkillText } from '../audit/rules.js'
17
17
  import { budgetReport } from '../budget/announcement.js'
18
18
  import { parseSkillsFromArchive, decidePlacement, installSkill } from '../market/install.js'
19
+ import { makeSource, isCommitSha, checkUpdate, applySync } from '../market/source.js'
20
+ import { readSources, saveSource } from '../market/store.js'
21
+
22
+ function listSources(config) {
23
+ return readSources(config).sources
24
+ }
19
25
 
20
26
  /** 关闭/开启模型的 frontmatter 键。 */
21
27
  const DISABLE_KEY = 'disable-model-invocation'
@@ -370,6 +376,61 @@ export function registerRoutes(ctx, config = {}, deps = {}) {
370
376
  })
371
377
  })
372
378
 
379
+ // ---- 市场:列出已登记仓库源 ----
380
+ register('/market/sources', ['GET'], async (req, res) => {
381
+ sendJson(res, 200, { sources: listSources(config) })
382
+ })
383
+
384
+ // ---- 市场:登记一个仓库源(钉 commit) ----
385
+ register('/market/add-source', ['POST'], async (req, res, body) => {
386
+ const { owner, repo, ref, commitSha } = body ?? {}
387
+ if (typeof owner !== 'string' || typeof repo !== 'string') {
388
+ sendJson(res, 400, { error: 'owner-and-repo-required' })
389
+ return
390
+ }
391
+ if (!isCommitSha(commitSha)) {
392
+ // 浮动 ref 拒绝入库:必须先解析成 sha
393
+ sendJson(res, 400, { error: 'commit-sha-required', message: '仓库源必须钉死 commitSha,不接受浮动 ref' })
394
+ return
395
+ }
396
+ const source = makeSource({ owner, repo, ref: ref ?? 'HEAD', commitSha })
397
+ const saved = saveSource(config, source)
398
+ sendJson(res, 200, { ok: true, source: saved })
399
+ })
400
+
401
+ // ---- 市场:检查更新(只读,不落盘) ----
402
+ register('/market/check', ['POST'], async (req, res, body) => {
403
+ const { id, remoteSha } = body ?? {}
404
+ const source = listSources(config).find(item => item.id === id)
405
+ if (source === undefined) {
406
+ sendJson(res, 404, { error: 'source-not-found' })
407
+ return
408
+ }
409
+ const result = checkUpdate(source.commitSha, remoteSha)
410
+ if (!result.ok) {
411
+ sendJson(res, 400, { error: result.reason })
412
+ return
413
+ }
414
+ sendJson(res, 200, { ok: true, source: source.id, ...result })
415
+ })
416
+
417
+ // ---- 市场:同步到钉住的远端 sha ----
418
+ register('/market/sync', ['POST'], async (req, res, body) => {
419
+ const { id, remoteSha } = body ?? {}
420
+ const source = listSources(config).find(item => item.id === id)
421
+ if (source === undefined) {
422
+ sendJson(res, 404, { error: 'source-not-found' })
423
+ return
424
+ }
425
+ const result = applySync(source, remoteSha)
426
+ if (!result.ok) {
427
+ sendJson(res, 400, { error: result.reason })
428
+ return
429
+ }
430
+ saveSource(config, result.source)
431
+ sendJson(res, 200, { ok: true, changed: result.changed, source: result.source })
432
+ })
433
+
373
434
  return () => {
374
435
  for (const dispose of disposers) {
375
436
  try {