dsh-skill-harbor 0.5.4 → 0.6.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/LICENSE +21 -21
- package/README.md +44 -44
- package/cordis.patch.yml +4 -4
- package/dsh.plugin.json +1 -1
- package/package.json +2 -1
- package/src/audit/normalize.js +77 -77
- package/src/audit/rules.js +167 -167
- package/src/budget/announcement.js +53 -53
- package/src/client/api.js +79 -79
- package/src/client/labels.js +6 -6
- package/src/client/locales.js +688 -688
- package/src/collect/frontmatter.js +169 -169
- package/src/collect/observe.js +143 -143
- package/src/collect/ranks.js +56 -56
- package/src/collect/roots.js +92 -92
- package/src/collect/shadow.js +68 -68
- package/src/collect/watcher.js +86 -86
- package/src/config.js +42 -42
- package/src/market/fetch.js +94 -94
- package/src/market/install.js +169 -169
- package/src/market/source.js +90 -90
- package/src/market/store.js +66 -66
- package/src/market/zip.js +201 -201
- package/src/provider/lifecycle.js +74 -74
- package/src/routes/guard.js +156 -156
- package/src/routes/safe-path.js +96 -96
- package/src/routes/store.js +72 -72
- package/src/settings.js +83 -83
package/src/routes/guard.js
CHANGED
|
@@ -1,156 +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
|
-
}
|
|
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
|
+
}
|
package/src/routes/safe-path.js
CHANGED
|
@@ -1,96 +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
|
-
}
|
|
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
|
+
}
|
package/src/routes/store.js
CHANGED
|
@@ -1,72 +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
|
-
}
|
|
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
|
+
}
|