dsh-skill-harbor 0.1.0 → 0.3.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.
@@ -0,0 +1,167 @@
1
+ /**
2
+ * 审计规则表:阻断级 + 警告级。
3
+ *
4
+ * 判定语义四值(dsh-plugin-dev §6):`ok` / `warn` / `fail` / `skipped`。
5
+ * 「无法判定」必须是 `skipped`,不能当 `warn` —— 否则全量假阳性。
6
+ *
7
+ * 设计纪律:
8
+ * - 外传形状只看**结构**(`curl -d @file`),不枚举来源命令、不做域名判断
9
+ * (域名判断必然失效且产生误报)
10
+ * - 每条规则一个正例 + 一个反例(单测钉死)
11
+ */
12
+ import { normalizeText, detectEncodingDisguise, charLength } from './normalize.js'
13
+
14
+ export const VERDICT = Object.freeze({
15
+ OK: 'ok',
16
+ WARN: 'warn',
17
+ FAIL: 'fail',
18
+ SKIPPED: 'skipped',
19
+ })
20
+
21
+ /** 体积/数量上限。 */
22
+ export const LIMITS = Object.freeze({
23
+ skillBytes: 256 * 1024,
24
+ bodyChars: 32_000,
25
+ lines: 4_000,
26
+ })
27
+
28
+ /** 凭据路径(出现在正文里 = 可能在读取用户机密)。 */
29
+ const CREDENTIAL_PATHS = [
30
+ /\.ssh\/(id_rsa|id_ed25519|id_ecdsa)/i,
31
+ /\.aws\/credentials/i,
32
+ /\.npmrc\b/i,
33
+ /\.netrc\b/i,
34
+ /\.git-credentials\b/i,
35
+ /AppData[\\/]Roaming[\\/]npm[\\/]etc[\\/]npmrc/i,
36
+ ]
37
+
38
+ /** 管道执行:`curl … | sh` / `wget … | bash` / `eval $(curl …)`。 */
39
+ const PIPE_EXEC = [
40
+ /\b(curl|wget|fetch)\b[^\n|]*\|\s*(sudo\s+)?(ba|z|k)?sh\b/i,
41
+ /\b(curl|wget)\b[^\n|]*\|\s*sudo\b/i,
42
+ /\beval\s+\$\(\s*(curl|wget)\b/i,
43
+ ]
44
+
45
+ /**
46
+ * 外传形状:只看「把文件内容塞进请求体」这个**结构**。
47
+ * 不判断域名、不枚举来源命令。
48
+ */
49
+ const EXFIL_SHAPES = [
50
+ // curl -d @file / --data @file / --data-binary @file
51
+ /\bcurl\b[^\n]*(?:-d|--data(?:-binary|-raw)?)\s*@[\w./\\-]+/i,
52
+ // curl -d @- (从 stdin 读,管道链的终点)
53
+ /\bcurl\b[^\n]*(?:-d|--data(?:-binary|-raw)?)\s*@-/i,
54
+ // 表单上传到变量/任意 host 的 --upload-file
55
+ /\bcurl\b[^\n]*--upload-file\s+[\w./\\-]+/i,
56
+ ]
57
+
58
+ /** URL 里带长 base64 查询串 = 数据塞 URL 外传。 */
59
+ const URL_PAYLOAD = /https?:\/\/[^\s"']+\?[^\s"']*=[A-Za-z0-9+/%]{120,}/
60
+
61
+ function fail(rule, message) {
62
+ return { rule, verdict: VERDICT.FAIL, message }
63
+ }
64
+ function warn(rule, message) {
65
+ return { rule, verdict: VERDICT.WARN, message }
66
+ }
67
+
68
+ /**
69
+ * 审计一个技能的文本。
70
+ * @param {string} raw 原始文件内容
71
+ * @param {{ name?: string }} [context]
72
+ * @returns {{ verdict: string, findings: Array<{rule:string,verdict:string,message:string}>, stats: object }}
73
+ */
74
+ export function auditSkillText(raw, context = {}) {
75
+ const findings = []
76
+
77
+ if (typeof raw !== 'string') {
78
+ return { verdict: VERDICT.SKIPPED, findings: [], stats: { reason: 'no-content', name: context.name } }
79
+ }
80
+
81
+ const { text, findings: disguiseHits } = normalizeText(raw)
82
+ const encodingHits = detectEncodingDisguise(raw)
83
+
84
+ // ---------- 阻断级 ----------
85
+ if (disguiseHits.includes('nul-byte') || disguiseHits.includes('c0-control')) {
86
+ findings.push(fail('SD001', `正文含控制字符:${disguiseHits.join(', ')}`))
87
+ }
88
+ if (disguiseHits.includes('invisible-format')) {
89
+ findings.push(fail('SD002', '正文含零宽/不可见格式字符(可隐藏指令)'))
90
+ }
91
+ if (disguiseHits.includes('unicode-tag')) {
92
+ findings.push(fail('SD003', '正文含 Unicode tag 字符(夹带隐藏文本)'))
93
+ }
94
+ if (disguiseHits.includes('bidi-control')) {
95
+ findings.push(fail('SD004', '正文含双向控制字符(显示与执行不一致)'))
96
+ }
97
+ if (encodingHits.length > 0) {
98
+ findings.push(fail('SD005', `编码伪装:${encodingHits.join(', ')}`))
99
+ }
100
+
101
+ const bytes = Buffer.byteLength(raw, 'utf8')
102
+ if (bytes > LIMITS.skillBytes) {
103
+ findings.push(fail('SD006', `体积 ${bytes}B 超过上限 ${LIMITS.skillBytes}B`))
104
+ }
105
+ const bodyChars = charLength(text)
106
+ if (bodyChars > LIMITS.bodyChars) {
107
+ findings.push(fail('SD007', `正文 ${bodyChars} 字符超过上限 ${LIMITS.bodyChars}`))
108
+ }
109
+ const lineCount = text.split('\n').length
110
+ if (lineCount > LIMITS.lines) {
111
+ findings.push(fail('SD008', `行数 ${lineCount} 超过上限 ${LIMITS.lines}`))
112
+ }
113
+
114
+ // ---------- 警告级 ----------
115
+ for (const pattern of PIPE_EXEC) {
116
+ if (pattern.test(text)) {
117
+ findings.push(warn('SD010', '检测到管道执行(curl/wget → shell)'))
118
+ break
119
+ }
120
+ }
121
+
122
+ for (const pattern of CREDENTIAL_PATHS) {
123
+ if (pattern.test(text)) {
124
+ findings.push(warn('SD011', '正文引用了凭据路径'))
125
+ break
126
+ }
127
+ }
128
+
129
+ for (const pattern of EXFIL_SHAPES) {
130
+ if (pattern.test(text)) {
131
+ findings.push(warn('SD012', '检测到外传形状(请求体读文件)'))
132
+ break
133
+ }
134
+ }
135
+
136
+ if (URL_PAYLOAD.test(text)) {
137
+ findings.push(warn('SD013', 'URL 查询串疑似携带编码载荷'))
138
+ }
139
+
140
+ return {
141
+ verdict: aggregate(findings),
142
+ findings,
143
+ stats: {
144
+ name: context.name,
145
+ bytes,
146
+ chars: bodyChars,
147
+ lines: lineCount,
148
+ disguise: disguiseHits,
149
+ encoding: encodingHits,
150
+ },
151
+ }
152
+ }
153
+
154
+ /**
155
+ * 聚合判定:任一 fail → fail;否则任一 warn → warn;否则 ok。
156
+ * 空 findings 是 **ok**(不是 skipped)—— 我们确实检查了,没发现问题。
157
+ */
158
+ export function aggregate(findings) {
159
+ if (findings.some(f => f.verdict === VERDICT.FAIL)) return VERDICT.FAIL
160
+ if (findings.some(f => f.verdict === VERDICT.WARN)) return VERDICT.WARN
161
+ return VERDICT.OK
162
+ }
163
+
164
+ /** 只有 warn / fail 可处置(共用一个谓词,防两处语义漂移)。 */
165
+ export function isActionable(verdict) {
166
+ return verdict === VERDICT.WARN || verdict === VERDICT.FAIL
167
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * 字符预算 —— 渐进披露第一层到底占多少上下文。
3
+ *
4
+ * 只算 `name + description + whenToUse` 三层字段,**正文不计入**:
5
+ * 正文是第二层(按需加载),把它算进公告预算会系统性高估。
6
+ */
7
+ import { charLength } from '../audit/normalize.js'
8
+
9
+ /** 单条技能的公告字符数。 */
10
+ export function announcementCharsOf(skill) {
11
+ if (skill === null || typeof skill !== 'object') return 0
12
+ return (
13
+ charLength(skill.name ?? '') +
14
+ charLength(skill.description ?? '') +
15
+ charLength(skill.whenToUse ?? '')
16
+ )
17
+ }
18
+
19
+ /**
20
+ * 整个目录的字符账。
21
+ * 分开统计「全部」与「模型可见」—— 遮蔽掉的与 disable-model-invocation
22
+ * 关掉的都不进模型上下文,混在一起会误导用户。
23
+ */
24
+ export function budgetReport(observations, options = {}) {
25
+ const { perSkillLimit = 4000 } = options
26
+
27
+ const rows = observations.map(observation => {
28
+ const chars = announcementCharsOf(observation)
29
+ return {
30
+ name: observation.name,
31
+ source: observation.source,
32
+ chars,
33
+ overLimit: chars > perSkillLimit,
34
+ modelInvocable: observation.modelInvocable === true,
35
+ shadowed: observation.shadowedBy !== undefined,
36
+ }
37
+ })
38
+
39
+ const announced = rows.filter(row => !row.shadowed && row.modelInvocable)
40
+ const skipped = rows.filter(row => row.shadowed || !row.modelInvocable)
41
+
42
+ return {
43
+ total: rows.reduce((sum, row) => sum + row.chars, 0),
44
+ announcedTotal: announced.reduce((sum, row) => sum + row.chars, 0),
45
+ skippedTotal: skipped.reduce((sum, row) => sum + row.chars, 0),
46
+ count: rows.length,
47
+ announcedCount: announced.length,
48
+ skippedCount: skipped.length,
49
+ perSkillLimit,
50
+ overLimit: announced.filter(row => row.overLimit),
51
+ rows,
52
+ }
53
+ }
package/src/index.js CHANGED
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * Phase 1(证据层):扫描 6 个约定根、解析 frontmatter、三态判定、遮蔽判定,
5
5
  * 通过 provider 把结果交给官方 skill registry。
6
+ * Phase 2(本地管理):受闸保护的 HTTP 路由(列表/读/启停/更新/删除)。
6
7
  *
7
8
  * Phase 0 实测结论(findings.md):
8
9
  * - `ctx.skills.registerProvider` 全线返回 `() => void`,可直接当 disposer
@@ -10,6 +11,7 @@
10
11
  * - `SkillSummary.path` 自 0.1.7-alpha.1 起存在(engines 下界依据)
11
12
  */
12
13
  import { installProvider } from './provider/lifecycle.js'
14
+ import { registerRoutes } from './routes/index.js'
13
15
 
14
16
  export const name = 'dsh-skill-harbor'
15
17
 
@@ -17,4 +19,8 @@ export const inject = ['skills']
17
19
 
18
20
  export function apply(ctx, config = {}) {
19
21
  installProvider(ctx, config)
22
+
23
+ // webServer 可能不存在(纯 CLI 场景)→ registerRoutes 内部自行降级
24
+ const disposeRoutes = registerRoutes(ctx, config)
25
+ ctx.effect(() => disposeRoutes, 'dsh-skill-harbor.routes')
20
26
  }
@@ -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
+ }