dsh-skill-harbor 0.0.1 → 0.2.0
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/README.md +39 -7
- package/dsh.plugin.json +16 -16
- package/lib/client.js +7 -3
- package/lib/collect/frontmatter.js +169 -0
- package/lib/collect/observe.js +143 -0
- package/lib/collect/ranks.js +56 -0
- package/lib/collect/roots.js +92 -0
- package/lib/collect/shadow.js +68 -0
- package/lib/index.js +20 -8
- package/lib/provider/lifecycle.js +74 -0
- package/lib/routes/guard.js +156 -0
- package/lib/routes/index.js +255 -0
- package/lib/routes/safe-path.js +96 -0
- package/lib/routes/store.js +72 -0
- package/package.json +48 -47
- package/src/client.js +7 -3
- package/src/collect/frontmatter.js +169 -0
- package/src/collect/observe.js +143 -0
- package/src/collect/ranks.js +56 -0
- package/src/collect/roots.js +92 -0
- package/src/collect/shadow.js +68 -0
- package/src/index.js +20 -8
- package/src/provider/lifecycle.js +74 -0
- package/src/routes/guard.js +156 -0
- package/src/routes/index.js +255 -0
- package/src/routes/safe-path.js +96 -0
- package/src/routes/store.js +72 -0
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* provider 注册与生命周期。
|
|
3
|
+
*
|
|
4
|
+
* 两条硬约束(checklist Must Pass):
|
|
5
|
+
* 1. `registerProvider` 全部包在 `ctx.effect` 内 —— fiber 销毁时自动注销
|
|
6
|
+
* 2. `mounted()` 守卫覆盖全部异步续体 —— 防止 fiber 已销毁后仍有异步回调注册
|
|
7
|
+
* (这正是 #24 的形态:`already registered in this scope`)
|
|
8
|
+
*
|
|
9
|
+
* Phase 0 实测(findings):`registerProvider` 全线返回 `() => void`,可直接当 disposer;
|
|
10
|
+
* `ctx.fiber.uid` 在 dispose 时置 `null`,故用 `uid !== null` 判存活。
|
|
11
|
+
*/
|
|
12
|
+
import { collectRoots } from '../collect/roots.js'
|
|
13
|
+
import { observeSkills } from '../collect/observe.js'
|
|
14
|
+
import { applyShadowing } from '../collect/shadow.js'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 判断当前 fiber 是否仍挂载。
|
|
18
|
+
* Phase 0 实测:uid 类型是 `number | null`,**不是 optional**,
|
|
19
|
+
* 所以判 `!== null`;用 `=== undefined` 会永远 false(假死守卫)。
|
|
20
|
+
*/
|
|
21
|
+
export function isMounted(ctx) {
|
|
22
|
+
const fiber = ctx?.fiber
|
|
23
|
+
if (fiber === undefined || fiber === null) return true // 无 fiber 概念的环境放行
|
|
24
|
+
return fiber.uid !== null && fiber.uid !== undefined
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 注册 skill provider。
|
|
29
|
+
* @param {object} ctx cordis context
|
|
30
|
+
* @param {object} config 插件配置(customSkillDirs / bundledSkillDir / dshHome / agentsHome)
|
|
31
|
+
* @param {object} [deps] 注入点,便于单测
|
|
32
|
+
*/
|
|
33
|
+
export function installProvider(ctx, config = {}, deps = {}) {
|
|
34
|
+
const { collect = observeSkills, rootsFactory = collectRoots } = deps
|
|
35
|
+
const logger = ctx?.logger ?? console
|
|
36
|
+
|
|
37
|
+
const buildProvider = () => ({
|
|
38
|
+
name: 'dsh-skill-harbor',
|
|
39
|
+
async list() {
|
|
40
|
+
// 异步续体守卫:await 之后 fiber 可能已销毁
|
|
41
|
+
if (!isMounted(ctx)) return []
|
|
42
|
+
try {
|
|
43
|
+
const roots = rootsFactory({
|
|
44
|
+
cwd: config.cwd ?? process.cwd(),
|
|
45
|
+
dshHome: config.dshHome,
|
|
46
|
+
agentsHome: config.agentsHome,
|
|
47
|
+
customSkillDirs: config.customSkillDirs ?? [],
|
|
48
|
+
bundledSkillDir: config.bundledSkillDir,
|
|
49
|
+
})
|
|
50
|
+
const registrySummaries = typeof ctx?.skills?.list === 'function' ? await ctx.skills.list() : []
|
|
51
|
+
if (!isMounted(ctx)) return []
|
|
52
|
+
const observations = collect({ roots, registrySummaries })
|
|
53
|
+
return applyShadowing(observations).filter(o => o.shadowedBy === undefined)
|
|
54
|
+
} catch (error) {
|
|
55
|
+
logger.warn?.('[dsh-skill-harbor] provider.list failed', error)
|
|
56
|
+
return []
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
// 全部注册包在 effect 内:fiber 销毁 → 自动 dispose
|
|
62
|
+
const dispose = ctx.effect(() => {
|
|
63
|
+
const providerDisposer = ctx.skills.registerProvider(buildProvider)
|
|
64
|
+
return () => {
|
|
65
|
+
try {
|
|
66
|
+
providerDisposer()
|
|
67
|
+
} catch (error) {
|
|
68
|
+
logger.warn?.('[dsh-skill-harbor] provider dispose failed', error)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}, 'dsh-skill-harbor.registerProvider')
|
|
72
|
+
|
|
73
|
+
return dispose
|
|
74
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 统一路由闸 —— 全插件唯一 HTTP 入口。
|
|
3
|
+
*
|
|
4
|
+
* 顺序**固定**,不可调换(每一步的语义都依赖前一步已通过):
|
|
5
|
+
* 1. 信任栅栏:能力探测 `ctx.connection`,缺失时退化到「回环 + sec-fetch-site + Origin 同源」
|
|
6
|
+
* 2. 方法检查:在 CSRF **之前**,让 OPTIONS/PUT 得到语义正确的 405(而不是 403)
|
|
7
|
+
* 3. CSRF 头:写接口要求 `x-dsh-skill-harbor: 1`
|
|
8
|
+
* —— 跨站表单能用 text/plain 发 POST 绕过预检,但**设不了自定义头**
|
|
9
|
+
* 4. JSON body 解析
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export const CSRF_HEADER = 'x-dsh-skill-harbor'
|
|
13
|
+
export const CSRF_VALUE = '1'
|
|
14
|
+
|
|
15
|
+
/** 路由前缀。 */
|
|
16
|
+
export const ROUTE_PREFIX = '/dsh-skill-harbor/api'
|
|
17
|
+
|
|
18
|
+
function isLoopback(address) {
|
|
19
|
+
if (typeof address !== 'string') return false
|
|
20
|
+
return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1' || address === 'localhost'
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 同源判定:Origin 存在时必须与 Host 一致。 */
|
|
24
|
+
function isSameOrigin(req) {
|
|
25
|
+
const origin = req.headers?.origin
|
|
26
|
+
if (typeof origin !== 'string' || origin === '') return true // 无 Origin(同源导航/非浏览器)放行,靠后面的 CSRF 兜
|
|
27
|
+
try {
|
|
28
|
+
const parsed = new URL(origin)
|
|
29
|
+
const host = req.headers?.host
|
|
30
|
+
return typeof host === 'string' && parsed.host === host
|
|
31
|
+
} catch {
|
|
32
|
+
return false
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 第 1 步:信任栅栏。
|
|
38
|
+
* @returns {boolean} 是否允许继续
|
|
39
|
+
*/
|
|
40
|
+
export function passesTrustGate(ctx, req) {
|
|
41
|
+
// 能力探测:宿主若提供 connection 服务,用它判定(与 /api 同模型)
|
|
42
|
+
const connection = typeof ctx?.get === 'function' ? ctx.get('connection') : undefined
|
|
43
|
+
if (connection !== undefined && connection !== null) {
|
|
44
|
+
if (typeof connection.isTrusted === 'function') {
|
|
45
|
+
return connection.isTrusted(req) === true
|
|
46
|
+
}
|
|
47
|
+
if (typeof connection.trusted === 'boolean') {
|
|
48
|
+
return connection.trusted
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// 退化:回环 + sec-fetch-site + Origin 同源
|
|
53
|
+
const remote = req.socket?.remoteAddress
|
|
54
|
+
if (!isLoopback(remote)) return false
|
|
55
|
+
const site = req.headers?.['sec-fetch-site']
|
|
56
|
+
if (typeof site === 'string' && site !== 'same-origin' && site !== 'none') return false
|
|
57
|
+
return isSameOrigin(req)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 第 2 步:方法检查。
|
|
62
|
+
* OPTIONS / 非允许方法一律 405(在 CSRF 之前,语义正确)。
|
|
63
|
+
*/
|
|
64
|
+
export function checkMethod(req, allowed) {
|
|
65
|
+
const method = String(req.method ?? '').toUpperCase()
|
|
66
|
+
if (!allowed.includes(method)) {
|
|
67
|
+
return { ok: false, status: 405, reason: 'method-not-allowed', headers: { allow: allowed.join(', ') } }
|
|
68
|
+
}
|
|
69
|
+
return { ok: true, method }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 第 3 步:CSRF 自定义头(仅写方法)。 */
|
|
73
|
+
export function checkCsrf(req, method) {
|
|
74
|
+
if (method === 'GET' || method === 'HEAD') return { ok: true }
|
|
75
|
+
const value = req.headers?.[CSRF_HEADER]
|
|
76
|
+
if (value !== CSRF_VALUE) {
|
|
77
|
+
return { ok: false, status: 403, reason: 'missing-csrf-header' }
|
|
78
|
+
}
|
|
79
|
+
return { ok: true }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 第 4 步:读 JSON body(带上限,防内存打爆)。 */
|
|
83
|
+
export const MAX_BODY_BYTES = 1024 * 1024
|
|
84
|
+
|
|
85
|
+
export async function readJsonBody(req) {
|
|
86
|
+
const chunks = []
|
|
87
|
+
let total = 0
|
|
88
|
+
for await (const chunk of req) {
|
|
89
|
+
total += chunk.length
|
|
90
|
+
if (total > MAX_BODY_BYTES) {
|
|
91
|
+
return { ok: false, status: 413, reason: 'body-too-large' }
|
|
92
|
+
}
|
|
93
|
+
chunks.push(chunk)
|
|
94
|
+
}
|
|
95
|
+
if (total === 0) return { ok: true, value: {} }
|
|
96
|
+
try {
|
|
97
|
+
return { ok: true, value: JSON.parse(Buffer.concat(chunks).toString('utf8')) }
|
|
98
|
+
} catch {
|
|
99
|
+
return { ok: false, status: 400, reason: 'invalid-json' }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 统一响应写出。 */
|
|
104
|
+
export function sendJson(res, status, payload) {
|
|
105
|
+
const body = JSON.stringify(payload)
|
|
106
|
+
res.statusCode = status
|
|
107
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
108
|
+
res.setHeader('cache-control', 'no-store')
|
|
109
|
+
res.end(body)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 生成一个受闸保护的处理函数。
|
|
114
|
+
* @param {object} ctx
|
|
115
|
+
* @param {{ methods: string[], auth?: 'anonymous'|'required' }} options
|
|
116
|
+
* @param {(req, res, body, method) => Promise<void>|void} handler
|
|
117
|
+
*/
|
|
118
|
+
export function guarded(ctx, options, handler) {
|
|
119
|
+
const { methods } = options
|
|
120
|
+
|
|
121
|
+
return async function route(req, res) {
|
|
122
|
+
if (!passesTrustGate(ctx, req)) {
|
|
123
|
+
sendJson(res, 403, { error: 'untrusted-origin' })
|
|
124
|
+
return
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const methodCheck = checkMethod(req, methods)
|
|
128
|
+
if (!methodCheck.ok) {
|
|
129
|
+
for (const [key, value] of Object.entries(methodCheck.headers ?? {})) res.setHeader(key, value)
|
|
130
|
+
sendJson(res, methodCheck.status, { error: methodCheck.reason })
|
|
131
|
+
return
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const csrfCheck = checkCsrf(req, methodCheck.method)
|
|
135
|
+
if (!csrfCheck.ok) {
|
|
136
|
+
sendJson(res, csrfCheck.status, { error: csrfCheck.reason })
|
|
137
|
+
return
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
let body = {}
|
|
141
|
+
if (methodCheck.method !== 'GET' && methodCheck.method !== 'HEAD') {
|
|
142
|
+
const parsed = await readJsonBody(req)
|
|
143
|
+
if (!parsed.ok) {
|
|
144
|
+
sendJson(res, parsed.status, { error: parsed.reason })
|
|
145
|
+
return
|
|
146
|
+
}
|
|
147
|
+
body = parsed.value
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
try {
|
|
151
|
+
await handler(req, res, body, methodCheck.method)
|
|
152
|
+
} catch (error) {
|
|
153
|
+
sendJson(res, 500, { error: 'internal', message: String(error?.message ?? error) })
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 路由注册总装 —— 所有 HTTP 入口在这里一次性挂上。
|
|
3
|
+
*
|
|
4
|
+
* 设计要点:
|
|
5
|
+
* - 前缀统一 `/dsh-skill-harbor/api`,写操作全部要求 CSRF 头
|
|
6
|
+
* - 写路由只接受 `snapshot.allowlist` 里的路径(不是请求里带来的任意路径)
|
|
7
|
+
* - 面板席位在 Phase 2 是独立 api + 客户端渲染,不注册 settings tab
|
|
8
|
+
*/
|
|
9
|
+
import { writeFileSync, renameSync, unlinkSync, existsSync } from 'node:fs'
|
|
10
|
+
|
|
11
|
+
import { ROUTE_PREFIX, guarded, sendJson } from './guard.js'
|
|
12
|
+
import { buildSnapshot, readSkillBody } from './store.js'
|
|
13
|
+
import { isAllowedPath, safePath, isSkillMarkdown } from './safe-path.js'
|
|
14
|
+
import { FILE_STATE, isWritable } from '../collect/observe.js'
|
|
15
|
+
import { extractSkillMeta } from '../collect/frontmatter.js'
|
|
16
|
+
|
|
17
|
+
/** 关闭/开启模型的 frontmatter 键。 */
|
|
18
|
+
const DISABLE_KEY = 'disable-model-invocation'
|
|
19
|
+
|
|
20
|
+
/** 在正文里切换 `disable-model-invocation`,保留其余内容原样。 */
|
|
21
|
+
export function setModelInvocation(text, enabled) {
|
|
22
|
+
const line = enabled ? 'false' : 'true'
|
|
23
|
+
const prefixed = /^(---\r?\n)([\s\S]*?)(\r?\n---)/.exec(text)
|
|
24
|
+
|
|
25
|
+
if (prefixed === null) {
|
|
26
|
+
// 没有 frontmatter:新建一个
|
|
27
|
+
return `---\n${DISABLE_KEY}: ${line}\n---\n${text}`
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const head = prefixed[2]
|
|
31
|
+
const entry = `${DISABLE_KEY}: ${line}`
|
|
32
|
+
const existing = new RegExp(`^${DISABLE_KEY}\\s*:.*$`, 'm')
|
|
33
|
+
|
|
34
|
+
const nextHead = existing.test(head)
|
|
35
|
+
? head.replace(existing, entry)
|
|
36
|
+
: `${head}${head.trim() === '' ? '' : '\n'}${entry}`
|
|
37
|
+
|
|
38
|
+
return `${prefixed[1]}${nextHead}${prefixed[3]}${text.slice(prefixed[0].length)}`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 原子写:先写临时文件再 rename,避免半截文件。 */
|
|
42
|
+
function atomicWrite(path, content) {
|
|
43
|
+
const temp = `${path}.harbor-tmp-${process.pid}`
|
|
44
|
+
writeFileSync(temp, content, 'utf8')
|
|
45
|
+
try {
|
|
46
|
+
renameSync(temp, path)
|
|
47
|
+
} catch (error) {
|
|
48
|
+
try {
|
|
49
|
+
if (existsSync(temp)) unlinkSync(temp)
|
|
50
|
+
} catch {
|
|
51
|
+
/* ignore */
|
|
52
|
+
}
|
|
53
|
+
throw error
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 注册全部路由。
|
|
59
|
+
* @param {object} ctx
|
|
60
|
+
* @param {object} config
|
|
61
|
+
* @param {object} [deps] 注入点(便于单测不依赖真实 webServer)
|
|
62
|
+
*/
|
|
63
|
+
export function registerRoutes(ctx, config = {}, deps = {}) {
|
|
64
|
+
const webServer = deps.webServer ?? ctx.webServer
|
|
65
|
+
if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') {
|
|
66
|
+
// 没有 webserver(如纯 CLI 场景):不注册,但 provider 仍然工作
|
|
67
|
+
return () => {}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const logger = ctx?.logger ?? console
|
|
71
|
+
const disposers = []
|
|
72
|
+
|
|
73
|
+
/** 每次请求都重新扫描?否 —— 用短 TTL 缓存,写后立即失效。 */
|
|
74
|
+
let cached = null
|
|
75
|
+
let cacheAt = 0
|
|
76
|
+
const CACHE_MS = 1500
|
|
77
|
+
|
|
78
|
+
const snapshot = async () => {
|
|
79
|
+
const now = Date.now()
|
|
80
|
+
if (cached !== null && now - cacheAt < CACHE_MS) return cached
|
|
81
|
+
const registrySummaries = typeof ctx?.skills?.list === 'function' ? await ctx.skills.list() : []
|
|
82
|
+
cached = buildSnapshot(config, registrySummaries)
|
|
83
|
+
cacheAt = now
|
|
84
|
+
return cached
|
|
85
|
+
}
|
|
86
|
+
const invalidate = () => {
|
|
87
|
+
cached = null
|
|
88
|
+
cacheAt = 0
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const register = (path, methods, handler) => {
|
|
92
|
+
const dispose = webServer.register({
|
|
93
|
+
kind: 'handler',
|
|
94
|
+
path: `${ROUTE_PREFIX}${path}`,
|
|
95
|
+
auth: 'required',
|
|
96
|
+
handler: guarded(ctx, { methods }, handler),
|
|
97
|
+
})
|
|
98
|
+
disposers.push(dispose)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ---- 读:列表 ----
|
|
102
|
+
register('/list', ['GET'], async (req, res) => {
|
|
103
|
+
const snap = await snapshot()
|
|
104
|
+
sendJson(res, 200, {
|
|
105
|
+
takenAt: snap.takenAt,
|
|
106
|
+
skills: snap.observations.map(observation => ({
|
|
107
|
+
name: observation.name,
|
|
108
|
+
description: observation.description,
|
|
109
|
+
source: observation.source,
|
|
110
|
+
rank: observation.rank,
|
|
111
|
+
fileState: observation.fileState,
|
|
112
|
+
modelInvocable: observation.modelInvocable,
|
|
113
|
+
announcementChars: observation.announcementChars,
|
|
114
|
+
shadowedBy: observation.shadowedBy ?? null,
|
|
115
|
+
// 只有 editable 才暴露 path,且可写
|
|
116
|
+
path: observation.fileState === FILE_STATE.EDITABLE ? observation.path : null,
|
|
117
|
+
writable: isWritable(observation),
|
|
118
|
+
})),
|
|
119
|
+
duplicates: snap.duplicates.map(group => ({
|
|
120
|
+
name: group.name,
|
|
121
|
+
count: group.count,
|
|
122
|
+
winner: group.winner === null ? null : { source: group.winner.source, rank: group.winner.rank },
|
|
123
|
+
})),
|
|
124
|
+
totals: {
|
|
125
|
+
all: snap.observations.length,
|
|
126
|
+
editable: snap.observations.filter(o => o.fileState === FILE_STATE.EDITABLE).length,
|
|
127
|
+
providerFile: snap.observations.filter(o => o.fileState === FILE_STATE.PROVIDER_FILE).length,
|
|
128
|
+
virtual: snap.observations.filter(o => o.fileState === FILE_STATE.VIRTUAL).length,
|
|
129
|
+
shadowed: snap.observations.filter(o => o.shadowedBy !== undefined).length,
|
|
130
|
+
},
|
|
131
|
+
})
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
// ---- 读:单技能正文 ----
|
|
135
|
+
register('/read', ['GET'], async (req, res) => {
|
|
136
|
+
const snap = await snapshot()
|
|
137
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
138
|
+
const target = url.searchParams.get('path')
|
|
139
|
+
|
|
140
|
+
const allowed = isAllowedPath(target, snap.allowlist)
|
|
141
|
+
if (!allowed.ok) {
|
|
142
|
+
sendJson(res, 403, { error: allowed.reason })
|
|
143
|
+
return
|
|
144
|
+
}
|
|
145
|
+
const body = readSkillBody(target, snap.allowlist)
|
|
146
|
+
if (!body.ok) {
|
|
147
|
+
sendJson(res, 404, { error: body.reason })
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
sendJson(res, 200, { path: target, content: body.content, meta: extractSkillMeta(body.content) })
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
// ---- 写:启停模型调用 ----
|
|
154
|
+
register('/set-enabled', ['POST'], async (req, res, body) => {
|
|
155
|
+
const snap = await snapshot()
|
|
156
|
+
const target = body?.path
|
|
157
|
+
const enabled = body?.enabled
|
|
158
|
+
|
|
159
|
+
if (typeof enabled !== 'boolean') {
|
|
160
|
+
sendJson(res, 400, { error: 'enabled-must-be-boolean' })
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
const allowed = isAllowedPath(target, snap.allowlist)
|
|
164
|
+
if (!allowed.ok) {
|
|
165
|
+
sendJson(res, 403, { error: allowed.reason })
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
if (!isSkillMarkdown(target)) {
|
|
169
|
+
sendJson(res, 400, { error: 'not-a-skill-markdown' })
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
try {
|
|
174
|
+
const current = readSkillBody(target, snap.allowlist)
|
|
175
|
+
if (!current.ok) {
|
|
176
|
+
sendJson(res, 404, { error: current.reason })
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
atomicWrite(target, setModelInvocation(current.content, enabled))
|
|
180
|
+
invalidate()
|
|
181
|
+
sendJson(res, 200, { ok: true, path: target, enabled })
|
|
182
|
+
} catch (error) {
|
|
183
|
+
logger.warn?.('[dsh-skill-harbor] set-enabled failed', error)
|
|
184
|
+
sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
|
|
185
|
+
}
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
// ---- 写:整体更新正文 ----
|
|
189
|
+
register('/update', ['POST'], async (req, res, body) => {
|
|
190
|
+
const snap = await snapshot()
|
|
191
|
+
const target = body?.path
|
|
192
|
+
const content = body?.content
|
|
193
|
+
|
|
194
|
+
if (typeof content !== 'string') {
|
|
195
|
+
sendJson(res, 400, { error: 'content-must-be-string' })
|
|
196
|
+
return
|
|
197
|
+
}
|
|
198
|
+
const allowed = isAllowedPath(target, snap.allowlist)
|
|
199
|
+
if (!allowed.ok) {
|
|
200
|
+
sendJson(res, 403, { error: allowed.reason })
|
|
201
|
+
return
|
|
202
|
+
}
|
|
203
|
+
if (!isSkillMarkdown(target)) {
|
|
204
|
+
sendJson(res, 400, { error: 'not-a-skill-markdown' })
|
|
205
|
+
return
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
try {
|
|
209
|
+
atomicWrite(target, content)
|
|
210
|
+
invalidate()
|
|
211
|
+
sendJson(res, 200, { ok: true, path: target })
|
|
212
|
+
} catch (error) {
|
|
213
|
+
logger.warn?.('[dsh-skill-harbor] update failed', error)
|
|
214
|
+
sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
|
|
215
|
+
}
|
|
216
|
+
})
|
|
217
|
+
|
|
218
|
+
// ---- 写:删除 ----
|
|
219
|
+
register('/delete', ['POST'], async (req, res, body) => {
|
|
220
|
+
const snap = await snapshot()
|
|
221
|
+
const target = body?.path
|
|
222
|
+
|
|
223
|
+
const allowed = isAllowedPath(target, snap.allowlist)
|
|
224
|
+
if (!allowed.ok) {
|
|
225
|
+
sendJson(res, 403, { error: allowed.reason })
|
|
226
|
+
return
|
|
227
|
+
}
|
|
228
|
+
if (!isSkillMarkdown(target)) {
|
|
229
|
+
sendJson(res, 400, { error: 'not-a-skill-markdown' })
|
|
230
|
+
return
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
try {
|
|
234
|
+
unlinkSync(target)
|
|
235
|
+
invalidate()
|
|
236
|
+
sendJson(res, 200, { ok: true, path: target })
|
|
237
|
+
} catch (error) {
|
|
238
|
+
logger.warn?.('[dsh-skill-harbor] delete failed', error)
|
|
239
|
+
sendJson(res, 500, { error: 'delete-failed', message: String(error?.message ?? error) })
|
|
240
|
+
}
|
|
241
|
+
})
|
|
242
|
+
|
|
243
|
+
return () => {
|
|
244
|
+
for (const dispose of disposers) {
|
|
245
|
+
try {
|
|
246
|
+
dispose()
|
|
247
|
+
} catch {
|
|
248
|
+
/* ignore */
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
disposers.length = 0
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export { ROUTE_PREFIX, safePath }
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 路径安全校验 —— 写/导入路由的唯一入口。
|
|
3
|
+
*
|
|
4
|
+
* 两条独立防线:
|
|
5
|
+
* 1. **只接受证据层解析出的路径**(allowlist),拒绝任意路径 —— 调用方传 path 时
|
|
6
|
+
* 必须已经过 `isWritable()` 判定且命中本次扫描结果
|
|
7
|
+
* 2. **路径本身的结构校验** —— 即使来自扫描结果,也要挡掉 `..`、Windows 保留名、
|
|
8
|
+
* 结尾点/空格、过深路径
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Windows 保留设备名(不带扩展名时不可用作文件名)。 */
|
|
12
|
+
const WINDOWS_RESERVED = new Set([
|
|
13
|
+
'con', 'prn', 'aux', 'nul',
|
|
14
|
+
'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9',
|
|
15
|
+
'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9',
|
|
16
|
+
])
|
|
17
|
+
|
|
18
|
+
/** 路径最大段数(防病态深路径)。 */
|
|
19
|
+
export const MAX_SEGMENTS = 64
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 校验一个文件路径是否可以安全写入。
|
|
23
|
+
* @returns {{ ok: true } | { ok: false, reason: string }}
|
|
24
|
+
*/
|
|
25
|
+
export function safePath(input) {
|
|
26
|
+
if (typeof input !== 'string' || input === '') {
|
|
27
|
+
return { ok: false, reason: 'empty-path' }
|
|
28
|
+
}
|
|
29
|
+
if (input.includes('\0')) {
|
|
30
|
+
return { ok: false, reason: 'nul-byte' }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// 统一分隔符后按段检查
|
|
34
|
+
const normalized = input.replace(/\\/g, '/')
|
|
35
|
+
|
|
36
|
+
// 盘符前缀单独剥离再校验:`C:` 的冒号不是非法字符,
|
|
37
|
+
// 若连它一起过 illegal-char 检查,Windows 上所有绝对路径都会被拒。
|
|
38
|
+
const driveMatch = /^([A-Za-z]):(\/|$)/.exec(normalized)
|
|
39
|
+
const withoutDrive = driveMatch === null ? normalized : normalized.slice(driveMatch[1].length + 2)
|
|
40
|
+
|
|
41
|
+
const segments = withoutDrive.split('/').filter(seg => seg !== '' && seg !== '.')
|
|
42
|
+
|
|
43
|
+
for (const segment of segments) {
|
|
44
|
+
if (segment === '..') return { ok: false, reason: 'parent-traversal' }
|
|
45
|
+
// Windows 上结尾的点与空格会被静默剥掉 → 可用于绕过扩展名检查
|
|
46
|
+
if (/[. ]$/.test(segment)) return { ok: false, reason: 'trailing-dot-or-space' }
|
|
47
|
+
// 保留设备名(大小写不敏感;带扩展名同样被 Windows 视为设备)
|
|
48
|
+
const stem = segment.split('.')[0].toLowerCase()
|
|
49
|
+
if (WINDOWS_RESERVED.has(stem)) return { ok: false, reason: 'reserved-name' }
|
|
50
|
+
// 控制字符
|
|
51
|
+
if (/[\u0000-\u001f<>:"|?*]/.test(segment)) return { ok: false, reason: 'illegal-char' }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (segments.length > MAX_SEGMENTS) {
|
|
55
|
+
return { ok: false, reason: 'too-deep' }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return { ok: true }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 校验目标路径是否落在 allowlist 内。
|
|
63
|
+
* 写路由**只**接受本次扫描产出的路径 —— 这是防任意文件写入的核心。
|
|
64
|
+
*
|
|
65
|
+
* @param {string} target
|
|
66
|
+
* @param {Set<string>|string[]} allowed
|
|
67
|
+
* @param {{ caseInsensitive?: boolean }} [options]
|
|
68
|
+
*/
|
|
69
|
+
export function isAllowedPath(target, allowed, options = {}) {
|
|
70
|
+
const { caseInsensitive = process.platform === 'win32' } = options
|
|
71
|
+
const safe = safePath(target)
|
|
72
|
+
if (!safe.ok) return { ok: false, reason: safe.reason }
|
|
73
|
+
|
|
74
|
+
const set = allowed instanceof Set ? allowed : new Set(allowed)
|
|
75
|
+
if (set.size === 0) return { ok: false, reason: 'not-scanned' }
|
|
76
|
+
|
|
77
|
+
if (caseInsensitive) {
|
|
78
|
+
const lower = target.replace(/\\/g, '/').toLowerCase()
|
|
79
|
+
for (const candidate of set) {
|
|
80
|
+
if (candidate.replace(/\\/g, '/').toLowerCase() === lower) return { ok: true }
|
|
81
|
+
}
|
|
82
|
+
return { ok: false, reason: 'not-in-allowlist' }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const normalizedTarget = target.replace(/\\/g, '/')
|
|
86
|
+
for (const candidate of set) {
|
|
87
|
+
if (candidate.replace(/\\/g, '/') === normalizedTarget) return { ok: true }
|
|
88
|
+
}
|
|
89
|
+
return { ok: false, reason: 'not-in-allowlist' }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** 只允许 `.md` 技能文件的写入(防越权写任意扩展名)。 */
|
|
93
|
+
export function isSkillMarkdown(target) {
|
|
94
|
+
const name = String(target).replace(/\\/g, '/').split('/').pop() ?? ''
|
|
95
|
+
return name.toLowerCase().endsWith('.md')
|
|
96
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 证据层缓存与读取入口。
|
|
3
|
+
*
|
|
4
|
+
* 每次读取都可能被写路由变更,所以缓存带「代数」:写操作后 bump,
|
|
5
|
+
* 读接口总是先确认代数未变,避免把过期扫描结果当真相。
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync } from 'node:fs'
|
|
8
|
+
|
|
9
|
+
import { collectRoots } from '../collect/roots.js'
|
|
10
|
+
import { observeSkills, FILE_STATE } from '../collect/observe.js'
|
|
11
|
+
import { applyShadowing } from '../collect/shadow.js'
|
|
12
|
+
|
|
13
|
+
/** 建立一次扫描结果集,并冻结当次的 allowlist(写路由唯一合法来源)。 */
|
|
14
|
+
export function buildSnapshot(config, registrySummaries = []) {
|
|
15
|
+
const roots = collectRoots({
|
|
16
|
+
cwd: config.cwd ?? process.cwd(),
|
|
17
|
+
dshHome: config.dshHome,
|
|
18
|
+
agentsHome: config.agentsHome,
|
|
19
|
+
customSkillDirs: config.customSkillDirs ?? [],
|
|
20
|
+
bundledSkillDir: config.bundledSkillDir,
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
const observations = applyShadowing(observeSkills({ roots, registrySummaries }))
|
|
24
|
+
|
|
25
|
+
// allowlist:只有 editable 条目才算可写
|
|
26
|
+
const allowlist = new Set()
|
|
27
|
+
for (const observation of observations) {
|
|
28
|
+
if (observation.fileState === FILE_STATE.EDITABLE && typeof observation.path === 'string') {
|
|
29
|
+
allowlist.add(observation.path)
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return {
|
|
34
|
+
takenAt: Date.now(),
|
|
35
|
+
roots,
|
|
36
|
+
observations,
|
|
37
|
+
allowlist,
|
|
38
|
+
// 面板要看的派生视图
|
|
39
|
+
duplicates: findDuplicates(observations),
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 同名多源(遮蔽关系)分组,供面板展示「谁遮了谁」。 */
|
|
44
|
+
export function findDuplicates(observations) {
|
|
45
|
+
const groups = new Map()
|
|
46
|
+
for (const observation of observations) {
|
|
47
|
+
const key = observation.name.toLowerCase()
|
|
48
|
+
const list = groups.get(key) ?? []
|
|
49
|
+
list.push(observation)
|
|
50
|
+
groups.set(key, list)
|
|
51
|
+
}
|
|
52
|
+
return [...groups.values()]
|
|
53
|
+
.filter(list => list.length > 1)
|
|
54
|
+
.map(list => ({
|
|
55
|
+
name: list[0].name,
|
|
56
|
+
count: list.length,
|
|
57
|
+
winner: list.find(o => o.shadowedBy === undefined) ?? null,
|
|
58
|
+
entries: list,
|
|
59
|
+
}))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 读单个技能正文(只读路径也不接受任意路径)。 */
|
|
63
|
+
export function readSkillBody(path, allowlist) {
|
|
64
|
+
if (!allowlist.has(path)) {
|
|
65
|
+
return { ok: false, reason: 'not-in-allowlist' }
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
return { ok: true, content: readFileSync(path, 'utf8') }
|
|
69
|
+
} catch (error) {
|
|
70
|
+
return { ok: false, reason: 'read-failed', message: String(error?.message ?? error) }
|
|
71
|
+
}
|
|
72
|
+
}
|