dsh-skill-harbor 0.4.0 → 0.5.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/dsh.plugin.json +1 -1
- package/lib/audit/ruleset.js +104 -0
- package/lib/collect/watcher.js +86 -0
- package/lib/routes/index.js +71 -2
- package/lib/settings.js +83 -0
- package/package.json +1 -1
- package/src/audit/ruleset.js +104 -0
- package/src/collect/watcher.js +86 -0
- package/src/routes/index.js +71 -2
- package/src/settings.js +83 -0
package/dsh.plugin.json
CHANGED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 规则包导出 / 回灌 —— 为 Phase 4 铺路。
|
|
3
|
+
*
|
|
4
|
+
* 导出的是**规则描述**而不是代码:只有 rule id、级别、正则源串与说明。
|
|
5
|
+
* 回灌时逐条校验正则可编译、id 合法、级别在四值内;坏条目丢弃并报原因,
|
|
6
|
+
* 不因为一条坏规则让整包失效。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const RULE_LEVELS = ['fail', 'warn']
|
|
10
|
+
|
|
11
|
+
/** 内置规则的可导出清单(与 audit/rules.js 的 id 对齐)。 */
|
|
12
|
+
export const EXPORTABLE_RULES = Object.freeze([
|
|
13
|
+
// flags 必须随规则一起导出:`\u{E0000}` 这类码点转义在没有 u 标记时
|
|
14
|
+
// 连 RegExp 都构造不出来 —— 导出的包会回灌失败。
|
|
15
|
+
{ id: 'SD001', level: 'fail', title: '控制字符', pattern: '[\\u0000-\\u0008]', flags: 'g' },
|
|
16
|
+
{ id: 'SD002', level: 'fail', title: '零宽字符', pattern: '[\\u200B-\\u200F]', flags: 'g' },
|
|
17
|
+
{ id: 'SD003', level: 'fail', title: 'Unicode tag', pattern: '[\\u{E0000}-\\u{E007F}]', flags: 'gu' },
|
|
18
|
+
{ id: 'SD004', level: 'fail', title: '双向控制', pattern: '[\\u202A-\\u202E]', flags: 'g' },
|
|
19
|
+
{ id: 'SD010', level: 'warn', title: '管道执行', pattern: '\\b(curl|wget)\\b[^\\n|]*\\|\\s*(ba|z)?sh\\b', flags: 'i' },
|
|
20
|
+
{ id: 'SD011', level: 'warn', title: '凭据路径', pattern: '\\.ssh/(id_rsa|id_ed25519)', flags: 'i' },
|
|
21
|
+
{ id: 'SD012', level: 'warn', title: '外传形状', pattern: '\\bcurl\\b[^\\n]*(?:-d|--data)\\s*@[-\\w./]+', flags: 'i' },
|
|
22
|
+
])
|
|
23
|
+
|
|
24
|
+
/** 导出为可回灌的 JSON。 */
|
|
25
|
+
export function exportRulePack(meta = {}) {
|
|
26
|
+
return {
|
|
27
|
+
format: 'dsh-skill-harbor/ruleset',
|
|
28
|
+
version: 1,
|
|
29
|
+
exportedAt: new Date().toISOString(),
|
|
30
|
+
...meta,
|
|
31
|
+
rules: EXPORTABLE_RULES.map(rule => ({ ...rule })),
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 校验单条规则;不合法返回原因。 */
|
|
36
|
+
export function validateRule(rule) {
|
|
37
|
+
if (rule === null || typeof rule !== 'object') return { ok: false, reason: 'not-an-object' }
|
|
38
|
+
if (typeof rule.id !== 'string' || !/^[A-Z]{2}\d{3}$/.test(rule.id)) {
|
|
39
|
+
return { ok: false, reason: 'invalid-id' }
|
|
40
|
+
}
|
|
41
|
+
if (!RULE_LEVELS.includes(rule.level)) return { ok: false, reason: 'invalid-level' }
|
|
42
|
+
if (typeof rule.pattern !== 'string' || rule.pattern === '') return { ok: false, reason: 'missing-pattern' }
|
|
43
|
+
if (rule.flags !== undefined && typeof rule.flags !== 'string') return { ok: false, reason: 'invalid-flags' }
|
|
44
|
+
try {
|
|
45
|
+
// 只验证可编译,不在这里执行
|
|
46
|
+
new RegExp(rule.pattern, rule.flags ?? '')
|
|
47
|
+
} catch {
|
|
48
|
+
return { ok: false, reason: 'uncompilable-pattern' }
|
|
49
|
+
}
|
|
50
|
+
return { ok: true }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 回灌一个规则包。
|
|
55
|
+
* @returns {{ ok: boolean, rules: Array, rejected: Array<{reason:string, rule?:any}> }}
|
|
56
|
+
*/
|
|
57
|
+
export function importRulePack(pack) {
|
|
58
|
+
if (pack === null || typeof pack !== 'object') {
|
|
59
|
+
return { ok: false, rules: [], rejected: [{ reason: 'not-an-object' }] }
|
|
60
|
+
}
|
|
61
|
+
if (pack.format !== 'dsh-skill-harbor/ruleset') {
|
|
62
|
+
return { ok: false, rules: [], rejected: [{ reason: 'wrong-format', actual: pack.format }] }
|
|
63
|
+
}
|
|
64
|
+
if (!Array.isArray(pack.rules)) {
|
|
65
|
+
return { ok: false, rules: [], rejected: [{ reason: 'rules-not-array' }] }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const rules = []
|
|
69
|
+
const rejected = []
|
|
70
|
+
const seen = new Set()
|
|
71
|
+
|
|
72
|
+
for (const rule of pack.rules) {
|
|
73
|
+
const check = validateRule(rule)
|
|
74
|
+
if (!check.ok) {
|
|
75
|
+
rejected.push({ reason: check.reason, rule })
|
|
76
|
+
continue
|
|
77
|
+
}
|
|
78
|
+
if (seen.has(rule.id)) {
|
|
79
|
+
rejected.push({ reason: 'duplicate-id', rule })
|
|
80
|
+
continue
|
|
81
|
+
}
|
|
82
|
+
seen.add(rule.id)
|
|
83
|
+
rules.push({
|
|
84
|
+
id: rule.id,
|
|
85
|
+
level: rule.level,
|
|
86
|
+
title: String(rule.title ?? ''),
|
|
87
|
+
pattern: rule.pattern,
|
|
88
|
+
...rule.flags === undefined ? {} : { flags: rule.flags },
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return { ok: rejected.length === 0, rules, rejected }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 把导出的规则编译成可执行的谓词表。 */
|
|
96
|
+
export function compileRules(rules) {
|
|
97
|
+
const compiled = []
|
|
98
|
+
for (const rule of rules) {
|
|
99
|
+
const check = validateRule(rule)
|
|
100
|
+
if (!check.ok) continue
|
|
101
|
+
compiled.push({ ...rule, regex: new RegExp(rule.pattern, rule.flags ?? '') })
|
|
102
|
+
}
|
|
103
|
+
return compiled
|
|
104
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 技能目录 watcher —— 增量感知,替代「每次请求全量重扫」。
|
|
3
|
+
*
|
|
4
|
+
* 设计取舍:
|
|
5
|
+
* - 不做「精确到文件的 diff」:那需要维护一棵完整树,且 fs.watch 在 Windows 上
|
|
6
|
+
* 对深层目录的事件并不可靠。这里只做**代数(generation)递增**:
|
|
7
|
+
* 任何目录变动 → 代数 +1 → 快照缓存失效。
|
|
8
|
+
* - 事件做 debounce 合并:一次保存会触发多个事件(创建/重命名/写入),
|
|
9
|
+
* 不合并会连打多次重扫。
|
|
10
|
+
* - watcher 失败(目录不存在 / 权限)不致命:降级为「无 watcher」,
|
|
11
|
+
* 此时只靠 TTL 兜底,并把这个降级状态如实报告给调用方。
|
|
12
|
+
*/
|
|
13
|
+
import { watch } from 'node:fs'
|
|
14
|
+
import { existsSync } from 'node:fs'
|
|
15
|
+
|
|
16
|
+
export const DEBOUNCE_MS = 250
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 观察一组根目录。
|
|
20
|
+
* @param {Array<{path:string, source:string}>} roots
|
|
21
|
+
* @param {() => void} onInvalidate 变动时调用(已 debounce)
|
|
22
|
+
* @param {{ debounceMs?: number }} [options]
|
|
23
|
+
* @returns {{ generation: () => number, watching: string[], degraded: Array<{path:string,reason:string}>, close: () => void }}
|
|
24
|
+
*/
|
|
25
|
+
export function watchRoots(roots, onInvalidate, options = {}) {
|
|
26
|
+
const debounceMs = options.debounceMs ?? DEBOUNCE_MS
|
|
27
|
+
|
|
28
|
+
let generation = 0
|
|
29
|
+
let timer = null
|
|
30
|
+
const watchers = []
|
|
31
|
+
const watching = []
|
|
32
|
+
const degraded = []
|
|
33
|
+
|
|
34
|
+
const bump = () => {
|
|
35
|
+
if (timer !== null) clearTimeout(timer)
|
|
36
|
+
timer = setTimeout(() => {
|
|
37
|
+
timer = null
|
|
38
|
+
generation += 1
|
|
39
|
+
try {
|
|
40
|
+
onInvalidate(generation)
|
|
41
|
+
} catch {
|
|
42
|
+
/* 回调失败不应影响 watcher 本身 */
|
|
43
|
+
}
|
|
44
|
+
}, debounceMs)
|
|
45
|
+
// 允许进程退出,不被 timer 挂住
|
|
46
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
for (const root of roots) {
|
|
50
|
+
if (!existsSync(root.path)) {
|
|
51
|
+
degraded.push({ path: root.path, reason: 'not-exists' })
|
|
52
|
+
continue
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
const watcher = watch(root.path, { recursive: true, persistent: false }, bump)
|
|
56
|
+
watcher.on('error', error => {
|
|
57
|
+
degraded.push({ path: root.path, reason: String(error?.code ?? error?.message ?? error) })
|
|
58
|
+
})
|
|
59
|
+
watchers.push(watcher)
|
|
60
|
+
watching.push(root.path)
|
|
61
|
+
} catch (error) {
|
|
62
|
+
// recursive 在某些平台/网络盘不支持 → 记录降级,不抛
|
|
63
|
+
degraded.push({ path: root.path, reason: String(error?.code ?? error?.message ?? error) })
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return {
|
|
68
|
+
generation: () => generation,
|
|
69
|
+
watching,
|
|
70
|
+
degraded,
|
|
71
|
+
close() {
|
|
72
|
+
if (timer !== null) {
|
|
73
|
+
clearTimeout(timer)
|
|
74
|
+
timer = null
|
|
75
|
+
}
|
|
76
|
+
for (const watcher of watchers) {
|
|
77
|
+
try {
|
|
78
|
+
watcher.close()
|
|
79
|
+
} catch {
|
|
80
|
+
/* ignore */
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
watchers.length = 0
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
}
|
package/lib/routes/index.js
CHANGED
|
@@ -10,6 +10,8 @@ import { writeFileSync, renameSync, unlinkSync, existsSync } from 'node:fs'
|
|
|
10
10
|
|
|
11
11
|
import { ROUTE_PREFIX, guarded, sendJson } from './guard.js'
|
|
12
12
|
import { buildSnapshot, readSkillBody } from './store.js'
|
|
13
|
+
import { watchRoots } from '../collect/watcher.js'
|
|
14
|
+
import { collectRoots } from '../collect/roots.js'
|
|
13
15
|
import { isAllowedPath, safePath, isSkillMarkdown } from './safe-path.js'
|
|
14
16
|
import { FILE_STATE, isWritable } from '../collect/observe.js'
|
|
15
17
|
import { extractSkillMeta } from '../collect/frontmatter.js'
|
|
@@ -18,6 +20,8 @@ import { budgetReport } from '../budget/announcement.js'
|
|
|
18
20
|
import { parseSkillsFromArchive, decidePlacement, installSkill } from '../market/install.js'
|
|
19
21
|
import { makeSource, isCommitSha, checkUpdate, applySync } from '../market/source.js'
|
|
20
22
|
import { readSources, saveSource } from '../market/store.js'
|
|
23
|
+
import { readSettings, writeSettings } from '../settings.js'
|
|
24
|
+
import { exportRulePack, importRulePack } from '../audit/ruleset.js'
|
|
21
25
|
|
|
22
26
|
function listSources(config) {
|
|
23
27
|
return readSources(config).sources
|
|
@@ -79,22 +83,55 @@ export function registerRoutes(ctx, config = {}, deps = {}) {
|
|
|
79
83
|
const logger = ctx?.logger ?? console
|
|
80
84
|
const disposers = []
|
|
81
85
|
|
|
82
|
-
/**
|
|
86
|
+
/**
|
|
87
|
+
* 快照缓存:watcher 代数 + TTL 双判据。
|
|
88
|
+
*
|
|
89
|
+
* - 有 watcher 时:代数变了立刻失效(增量感知),代数不变则可长期复用。
|
|
90
|
+
* - watcher 降级(目录不存在 / 平台不支持 recursive)时:回落到 TTL。
|
|
91
|
+
* - 写操作后显式 invalidate(本地写不经过文件事件,等不到 watcher)。
|
|
92
|
+
*/
|
|
83
93
|
let cached = null
|
|
84
94
|
let cacheAt = 0
|
|
95
|
+
let cachedGeneration = -1
|
|
85
96
|
const CACHE_MS = 1500
|
|
86
97
|
|
|
87
98
|
const snapshot = async () => {
|
|
88
99
|
const now = Date.now()
|
|
89
|
-
|
|
100
|
+
const generation = watcherState === null ? -1 : watcherState.generation()
|
|
101
|
+
|
|
102
|
+
if (cached !== null) {
|
|
103
|
+
if (watcherState === null) {
|
|
104
|
+
if (now - cacheAt < CACHE_MS) return cached
|
|
105
|
+
} else if (generation === cachedGeneration) {
|
|
106
|
+
return cached
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
90
110
|
const registrySummaries = typeof ctx?.skills?.list === 'function' ? await ctx.skills.list() : []
|
|
91
111
|
cached = buildSnapshot(config, registrySummaries)
|
|
92
112
|
cacheAt = now
|
|
113
|
+
cachedGeneration = generation
|
|
93
114
|
return cached
|
|
94
115
|
}
|
|
95
116
|
const invalidate = () => {
|
|
96
117
|
cached = null
|
|
97
118
|
cacheAt = 0
|
|
119
|
+
cachedGeneration = -1
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// watcher:任何目录变动 → 代数 +1 → 下次请求重扫
|
|
123
|
+
let watcherState = null
|
|
124
|
+
try {
|
|
125
|
+
const initialRoots = collectRoots({
|
|
126
|
+
cwd: config.cwd ?? process.cwd(),
|
|
127
|
+
dshHome: config.dshHome,
|
|
128
|
+
agentsHome: config.agentsHome,
|
|
129
|
+
customSkillDirs: config.customSkillDirs ?? [],
|
|
130
|
+
bundledSkillDir: config.bundledSkillDir,
|
|
131
|
+
})
|
|
132
|
+
watcherState = watchRoots(initialRoots, invalidate)
|
|
133
|
+
} catch (error) {
|
|
134
|
+
logger.warn?.('[dsh-skill-harbor] watcher unavailable, falling back to TTL', error)
|
|
98
135
|
}
|
|
99
136
|
|
|
100
137
|
const register = (path, methods, handler) => {
|
|
@@ -431,7 +468,39 @@ export function registerRoutes(ctx, config = {}, deps = {}) {
|
|
|
431
468
|
sendJson(res, 200, { ok: true, changed: result.changed, source: result.source })
|
|
432
469
|
})
|
|
433
470
|
|
|
471
|
+
// ---- 偏好:GET 读 / POST 部分更新 ----
|
|
472
|
+
// 同一路径只能注册一次(宿主按绝对路径去重),方法在这里分派。
|
|
473
|
+
register('/settings', ['GET', 'POST'], async (req, res, body, method) => {
|
|
474
|
+
if (method === 'GET') {
|
|
475
|
+
const { settings, degraded, reason } = readSettings(config)
|
|
476
|
+
sendJson(res, 200, { settings, degraded, ...(reason === undefined ? {} : { reason }) })
|
|
477
|
+
return
|
|
478
|
+
}
|
|
479
|
+
try {
|
|
480
|
+
const next = writeSettings(config, body ?? {})
|
|
481
|
+
sendJson(res, 200, { ok: true, settings: next })
|
|
482
|
+
} catch (error) {
|
|
483
|
+
logger.warn?.('[dsh-skill-harbor] settings write failed', error)
|
|
484
|
+
sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
|
|
485
|
+
}
|
|
486
|
+
})
|
|
487
|
+
|
|
488
|
+
// ---- 规则包:导出 ----
|
|
489
|
+
register('/rules/export', ['GET'], async (req, res) => {
|
|
490
|
+
sendJson(res, 200, exportRulePack({ plugin: 'dsh-skill-harbor' }))
|
|
491
|
+
})
|
|
492
|
+
|
|
493
|
+
// ---- 规则包:回灌 ----
|
|
494
|
+
register('/rules/import', ['POST'], async (req, res, body) => {
|
|
495
|
+
const result = importRulePack(body)
|
|
496
|
+
sendJson(res, result.ok ? 200 : 422, result)
|
|
497
|
+
})
|
|
498
|
+
|
|
434
499
|
return () => {
|
|
500
|
+
if (watcherState !== null) {
|
|
501
|
+
watcherState.close()
|
|
502
|
+
watcherState = null
|
|
503
|
+
}
|
|
435
504
|
for (const dispose of disposers) {
|
|
436
505
|
try {
|
|
437
506
|
dispose()
|
package/lib/settings.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 面板偏好持久化。
|
|
3
|
+
*
|
|
4
|
+
* 落 `~/.dsh/skill-harbor/settings.json`。与市场源同一个 base 目录,
|
|
5
|
+
* 但**分开文件**:源列表和 UI 偏好生命周期不同(前者被安装/卸载改,后者被用户点改)。
|
|
6
|
+
*
|
|
7
|
+
* 读取做「字段级白名单 + 类型校验」:文件被手改成乱七八糟的值时,
|
|
8
|
+
* 逐字段回落默认值,而不是整份丢弃(UI 偏好丢了不该影响使用)。
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs'
|
|
11
|
+
import { dirname, join } from 'node:path'
|
|
12
|
+
|
|
13
|
+
import { DEFAULT_BUDGET_LIMIT, ANNOUNCEMENT_HARD_LIMIT } from './config.js'
|
|
14
|
+
|
|
15
|
+
export const SUPPORTED_LANGS = ['zh', 'en', 'ja', 'ko', 'fr', 'de', 'it', 'ru', 'es', 'pt']
|
|
16
|
+
export const SUPPORTED_TABS = ['overview', 'audit', 'budget']
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_SETTINGS = Object.freeze({
|
|
19
|
+
lang: 'zh',
|
|
20
|
+
tab: 'overview',
|
|
21
|
+
budgetLimit: DEFAULT_BUDGET_LIMIT,
|
|
22
|
+
announceToSystemPrompt: false,
|
|
23
|
+
pageSize: 50,
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
export function settingsFile(config) {
|
|
27
|
+
const base = config.dshHome ?? join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh')
|
|
28
|
+
return join(base, 'skill-harbor', 'settings.json')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 逐字段校验 + 归一化;任何非法字段回落默认值。 */
|
|
32
|
+
export function normalizeSettings(input) {
|
|
33
|
+
const raw = input !== null && typeof input === 'object' ? input : {}
|
|
34
|
+
const out = { ...DEFAULT_SETTINGS }
|
|
35
|
+
|
|
36
|
+
if (SUPPORTED_LANGS.includes(raw.lang)) out.lang = raw.lang
|
|
37
|
+
if (SUPPORTED_TABS.includes(raw.tab)) out.tab = raw.tab
|
|
38
|
+
|
|
39
|
+
if (Number.isFinite(raw.budgetLimit) && raw.budgetLimit > 0) {
|
|
40
|
+
out.budgetLimit = Math.min(raw.budgetLimit, 1_000_000)
|
|
41
|
+
}
|
|
42
|
+
if (typeof raw.announceToSystemPrompt === 'boolean') {
|
|
43
|
+
out.announceToSystemPrompt = raw.announceToSystemPrompt
|
|
44
|
+
}
|
|
45
|
+
if (Number.isFinite(raw.pageSize) && raw.pageSize > 0) {
|
|
46
|
+
out.pageSize = Math.min(Math.round(raw.pageSize), 500)
|
|
47
|
+
}
|
|
48
|
+
return out
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 读取偏好。返回 `{ settings, degraded }`:
|
|
53
|
+
* 文件损坏时 `degraded=true` 并给默认值 —— 用户至少还能用面板。
|
|
54
|
+
*/
|
|
55
|
+
export function readSettings(config) {
|
|
56
|
+
const file = settingsFile(config)
|
|
57
|
+
if (!existsSync(file)) return { settings: { ...DEFAULT_SETTINGS }, degraded: false }
|
|
58
|
+
|
|
59
|
+
let parsed
|
|
60
|
+
try {
|
|
61
|
+
parsed = JSON.parse(readFileSync(file, 'utf8'))
|
|
62
|
+
} catch {
|
|
63
|
+
return { settings: { ...DEFAULT_SETTINGS }, degraded: true, reason: 'unreadable' }
|
|
64
|
+
}
|
|
65
|
+
return { settings: normalizeSettings(parsed), degraded: false }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 原子写入。 */
|
|
69
|
+
export function writeSettings(config, patch) {
|
|
70
|
+
const current = readSettings(config).settings
|
|
71
|
+
const next = normalizeSettings({ ...current, ...patch })
|
|
72
|
+
const file = settingsFile(config)
|
|
73
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
74
|
+
const temp = `${file}.tmp-${process.pid}`
|
|
75
|
+
writeFileSync(temp, JSON.stringify(next, null, 2), 'utf8')
|
|
76
|
+
renameSync(temp, file)
|
|
77
|
+
return next
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 公告文本是否超过硬上限(UI 提示用)。 */
|
|
81
|
+
export function announcementOverHardLimit(text) {
|
|
82
|
+
return [...String(text ?? '')].length > ANNOUNCEMENT_HARD_LIMIT
|
|
83
|
+
}
|
package/package.json
CHANGED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 规则包导出 / 回灌 —— 为 Phase 4 铺路。
|
|
3
|
+
*
|
|
4
|
+
* 导出的是**规则描述**而不是代码:只有 rule id、级别、正则源串与说明。
|
|
5
|
+
* 回灌时逐条校验正则可编译、id 合法、级别在四值内;坏条目丢弃并报原因,
|
|
6
|
+
* 不因为一条坏规则让整包失效。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const RULE_LEVELS = ['fail', 'warn']
|
|
10
|
+
|
|
11
|
+
/** 内置规则的可导出清单(与 audit/rules.js 的 id 对齐)。 */
|
|
12
|
+
export const EXPORTABLE_RULES = Object.freeze([
|
|
13
|
+
// flags 必须随规则一起导出:`\u{E0000}` 这类码点转义在没有 u 标记时
|
|
14
|
+
// 连 RegExp 都构造不出来 —— 导出的包会回灌失败。
|
|
15
|
+
{ id: 'SD001', level: 'fail', title: '控制字符', pattern: '[\\u0000-\\u0008]', flags: 'g' },
|
|
16
|
+
{ id: 'SD002', level: 'fail', title: '零宽字符', pattern: '[\\u200B-\\u200F]', flags: 'g' },
|
|
17
|
+
{ id: 'SD003', level: 'fail', title: 'Unicode tag', pattern: '[\\u{E0000}-\\u{E007F}]', flags: 'gu' },
|
|
18
|
+
{ id: 'SD004', level: 'fail', title: '双向控制', pattern: '[\\u202A-\\u202E]', flags: 'g' },
|
|
19
|
+
{ id: 'SD010', level: 'warn', title: '管道执行', pattern: '\\b(curl|wget)\\b[^\\n|]*\\|\\s*(ba|z)?sh\\b', flags: 'i' },
|
|
20
|
+
{ id: 'SD011', level: 'warn', title: '凭据路径', pattern: '\\.ssh/(id_rsa|id_ed25519)', flags: 'i' },
|
|
21
|
+
{ id: 'SD012', level: 'warn', title: '外传形状', pattern: '\\bcurl\\b[^\\n]*(?:-d|--data)\\s*@[-\\w./]+', flags: 'i' },
|
|
22
|
+
])
|
|
23
|
+
|
|
24
|
+
/** 导出为可回灌的 JSON。 */
|
|
25
|
+
export function exportRulePack(meta = {}) {
|
|
26
|
+
return {
|
|
27
|
+
format: 'dsh-skill-harbor/ruleset',
|
|
28
|
+
version: 1,
|
|
29
|
+
exportedAt: new Date().toISOString(),
|
|
30
|
+
...meta,
|
|
31
|
+
rules: EXPORTABLE_RULES.map(rule => ({ ...rule })),
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 校验单条规则;不合法返回原因。 */
|
|
36
|
+
export function validateRule(rule) {
|
|
37
|
+
if (rule === null || typeof rule !== 'object') return { ok: false, reason: 'not-an-object' }
|
|
38
|
+
if (typeof rule.id !== 'string' || !/^[A-Z]{2}\d{3}$/.test(rule.id)) {
|
|
39
|
+
return { ok: false, reason: 'invalid-id' }
|
|
40
|
+
}
|
|
41
|
+
if (!RULE_LEVELS.includes(rule.level)) return { ok: false, reason: 'invalid-level' }
|
|
42
|
+
if (typeof rule.pattern !== 'string' || rule.pattern === '') return { ok: false, reason: 'missing-pattern' }
|
|
43
|
+
if (rule.flags !== undefined && typeof rule.flags !== 'string') return { ok: false, reason: 'invalid-flags' }
|
|
44
|
+
try {
|
|
45
|
+
// 只验证可编译,不在这里执行
|
|
46
|
+
new RegExp(rule.pattern, rule.flags ?? '')
|
|
47
|
+
} catch {
|
|
48
|
+
return { ok: false, reason: 'uncompilable-pattern' }
|
|
49
|
+
}
|
|
50
|
+
return { ok: true }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 回灌一个规则包。
|
|
55
|
+
* @returns {{ ok: boolean, rules: Array, rejected: Array<{reason:string, rule?:any}> }}
|
|
56
|
+
*/
|
|
57
|
+
export function importRulePack(pack) {
|
|
58
|
+
if (pack === null || typeof pack !== 'object') {
|
|
59
|
+
return { ok: false, rules: [], rejected: [{ reason: 'not-an-object' }] }
|
|
60
|
+
}
|
|
61
|
+
if (pack.format !== 'dsh-skill-harbor/ruleset') {
|
|
62
|
+
return { ok: false, rules: [], rejected: [{ reason: 'wrong-format', actual: pack.format }] }
|
|
63
|
+
}
|
|
64
|
+
if (!Array.isArray(pack.rules)) {
|
|
65
|
+
return { ok: false, rules: [], rejected: [{ reason: 'rules-not-array' }] }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const rules = []
|
|
69
|
+
const rejected = []
|
|
70
|
+
const seen = new Set()
|
|
71
|
+
|
|
72
|
+
for (const rule of pack.rules) {
|
|
73
|
+
const check = validateRule(rule)
|
|
74
|
+
if (!check.ok) {
|
|
75
|
+
rejected.push({ reason: check.reason, rule })
|
|
76
|
+
continue
|
|
77
|
+
}
|
|
78
|
+
if (seen.has(rule.id)) {
|
|
79
|
+
rejected.push({ reason: 'duplicate-id', rule })
|
|
80
|
+
continue
|
|
81
|
+
}
|
|
82
|
+
seen.add(rule.id)
|
|
83
|
+
rules.push({
|
|
84
|
+
id: rule.id,
|
|
85
|
+
level: rule.level,
|
|
86
|
+
title: String(rule.title ?? ''),
|
|
87
|
+
pattern: rule.pattern,
|
|
88
|
+
...rule.flags === undefined ? {} : { flags: rule.flags },
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return { ok: rejected.length === 0, rules, rejected }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 把导出的规则编译成可执行的谓词表。 */
|
|
96
|
+
export function compileRules(rules) {
|
|
97
|
+
const compiled = []
|
|
98
|
+
for (const rule of rules) {
|
|
99
|
+
const check = validateRule(rule)
|
|
100
|
+
if (!check.ok) continue
|
|
101
|
+
compiled.push({ ...rule, regex: new RegExp(rule.pattern, rule.flags ?? '') })
|
|
102
|
+
}
|
|
103
|
+
return compiled
|
|
104
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 技能目录 watcher —— 增量感知,替代「每次请求全量重扫」。
|
|
3
|
+
*
|
|
4
|
+
* 设计取舍:
|
|
5
|
+
* - 不做「精确到文件的 diff」:那需要维护一棵完整树,且 fs.watch 在 Windows 上
|
|
6
|
+
* 对深层目录的事件并不可靠。这里只做**代数(generation)递增**:
|
|
7
|
+
* 任何目录变动 → 代数 +1 → 快照缓存失效。
|
|
8
|
+
* - 事件做 debounce 合并:一次保存会触发多个事件(创建/重命名/写入),
|
|
9
|
+
* 不合并会连打多次重扫。
|
|
10
|
+
* - watcher 失败(目录不存在 / 权限)不致命:降级为「无 watcher」,
|
|
11
|
+
* 此时只靠 TTL 兜底,并把这个降级状态如实报告给调用方。
|
|
12
|
+
*/
|
|
13
|
+
import { watch } from 'node:fs'
|
|
14
|
+
import { existsSync } from 'node:fs'
|
|
15
|
+
|
|
16
|
+
export const DEBOUNCE_MS = 250
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 观察一组根目录。
|
|
20
|
+
* @param {Array<{path:string, source:string}>} roots
|
|
21
|
+
* @param {() => void} onInvalidate 变动时调用(已 debounce)
|
|
22
|
+
* @param {{ debounceMs?: number }} [options]
|
|
23
|
+
* @returns {{ generation: () => number, watching: string[], degraded: Array<{path:string,reason:string}>, close: () => void }}
|
|
24
|
+
*/
|
|
25
|
+
export function watchRoots(roots, onInvalidate, options = {}) {
|
|
26
|
+
const debounceMs = options.debounceMs ?? DEBOUNCE_MS
|
|
27
|
+
|
|
28
|
+
let generation = 0
|
|
29
|
+
let timer = null
|
|
30
|
+
const watchers = []
|
|
31
|
+
const watching = []
|
|
32
|
+
const degraded = []
|
|
33
|
+
|
|
34
|
+
const bump = () => {
|
|
35
|
+
if (timer !== null) clearTimeout(timer)
|
|
36
|
+
timer = setTimeout(() => {
|
|
37
|
+
timer = null
|
|
38
|
+
generation += 1
|
|
39
|
+
try {
|
|
40
|
+
onInvalidate(generation)
|
|
41
|
+
} catch {
|
|
42
|
+
/* 回调失败不应影响 watcher 本身 */
|
|
43
|
+
}
|
|
44
|
+
}, debounceMs)
|
|
45
|
+
// 允许进程退出,不被 timer 挂住
|
|
46
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
for (const root of roots) {
|
|
50
|
+
if (!existsSync(root.path)) {
|
|
51
|
+
degraded.push({ path: root.path, reason: 'not-exists' })
|
|
52
|
+
continue
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
const watcher = watch(root.path, { recursive: true, persistent: false }, bump)
|
|
56
|
+
watcher.on('error', error => {
|
|
57
|
+
degraded.push({ path: root.path, reason: String(error?.code ?? error?.message ?? error) })
|
|
58
|
+
})
|
|
59
|
+
watchers.push(watcher)
|
|
60
|
+
watching.push(root.path)
|
|
61
|
+
} catch (error) {
|
|
62
|
+
// recursive 在某些平台/网络盘不支持 → 记录降级,不抛
|
|
63
|
+
degraded.push({ path: root.path, reason: String(error?.code ?? error?.message ?? error) })
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return {
|
|
68
|
+
generation: () => generation,
|
|
69
|
+
watching,
|
|
70
|
+
degraded,
|
|
71
|
+
close() {
|
|
72
|
+
if (timer !== null) {
|
|
73
|
+
clearTimeout(timer)
|
|
74
|
+
timer = null
|
|
75
|
+
}
|
|
76
|
+
for (const watcher of watchers) {
|
|
77
|
+
try {
|
|
78
|
+
watcher.close()
|
|
79
|
+
} catch {
|
|
80
|
+
/* ignore */
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
watchers.length = 0
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
}
|
package/src/routes/index.js
CHANGED
|
@@ -10,6 +10,8 @@ import { writeFileSync, renameSync, unlinkSync, existsSync } from 'node:fs'
|
|
|
10
10
|
|
|
11
11
|
import { ROUTE_PREFIX, guarded, sendJson } from './guard.js'
|
|
12
12
|
import { buildSnapshot, readSkillBody } from './store.js'
|
|
13
|
+
import { watchRoots } from '../collect/watcher.js'
|
|
14
|
+
import { collectRoots } from '../collect/roots.js'
|
|
13
15
|
import { isAllowedPath, safePath, isSkillMarkdown } from './safe-path.js'
|
|
14
16
|
import { FILE_STATE, isWritable } from '../collect/observe.js'
|
|
15
17
|
import { extractSkillMeta } from '../collect/frontmatter.js'
|
|
@@ -18,6 +20,8 @@ import { budgetReport } from '../budget/announcement.js'
|
|
|
18
20
|
import { parseSkillsFromArchive, decidePlacement, installSkill } from '../market/install.js'
|
|
19
21
|
import { makeSource, isCommitSha, checkUpdate, applySync } from '../market/source.js'
|
|
20
22
|
import { readSources, saveSource } from '../market/store.js'
|
|
23
|
+
import { readSettings, writeSettings } from '../settings.js'
|
|
24
|
+
import { exportRulePack, importRulePack } from '../audit/ruleset.js'
|
|
21
25
|
|
|
22
26
|
function listSources(config) {
|
|
23
27
|
return readSources(config).sources
|
|
@@ -79,22 +83,55 @@ export function registerRoutes(ctx, config = {}, deps = {}) {
|
|
|
79
83
|
const logger = ctx?.logger ?? console
|
|
80
84
|
const disposers = []
|
|
81
85
|
|
|
82
|
-
/**
|
|
86
|
+
/**
|
|
87
|
+
* 快照缓存:watcher 代数 + TTL 双判据。
|
|
88
|
+
*
|
|
89
|
+
* - 有 watcher 时:代数变了立刻失效(增量感知),代数不变则可长期复用。
|
|
90
|
+
* - watcher 降级(目录不存在 / 平台不支持 recursive)时:回落到 TTL。
|
|
91
|
+
* - 写操作后显式 invalidate(本地写不经过文件事件,等不到 watcher)。
|
|
92
|
+
*/
|
|
83
93
|
let cached = null
|
|
84
94
|
let cacheAt = 0
|
|
95
|
+
let cachedGeneration = -1
|
|
85
96
|
const CACHE_MS = 1500
|
|
86
97
|
|
|
87
98
|
const snapshot = async () => {
|
|
88
99
|
const now = Date.now()
|
|
89
|
-
|
|
100
|
+
const generation = watcherState === null ? -1 : watcherState.generation()
|
|
101
|
+
|
|
102
|
+
if (cached !== null) {
|
|
103
|
+
if (watcherState === null) {
|
|
104
|
+
if (now - cacheAt < CACHE_MS) return cached
|
|
105
|
+
} else if (generation === cachedGeneration) {
|
|
106
|
+
return cached
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
90
110
|
const registrySummaries = typeof ctx?.skills?.list === 'function' ? await ctx.skills.list() : []
|
|
91
111
|
cached = buildSnapshot(config, registrySummaries)
|
|
92
112
|
cacheAt = now
|
|
113
|
+
cachedGeneration = generation
|
|
93
114
|
return cached
|
|
94
115
|
}
|
|
95
116
|
const invalidate = () => {
|
|
96
117
|
cached = null
|
|
97
118
|
cacheAt = 0
|
|
119
|
+
cachedGeneration = -1
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// watcher:任何目录变动 → 代数 +1 → 下次请求重扫
|
|
123
|
+
let watcherState = null
|
|
124
|
+
try {
|
|
125
|
+
const initialRoots = collectRoots({
|
|
126
|
+
cwd: config.cwd ?? process.cwd(),
|
|
127
|
+
dshHome: config.dshHome,
|
|
128
|
+
agentsHome: config.agentsHome,
|
|
129
|
+
customSkillDirs: config.customSkillDirs ?? [],
|
|
130
|
+
bundledSkillDir: config.bundledSkillDir,
|
|
131
|
+
})
|
|
132
|
+
watcherState = watchRoots(initialRoots, invalidate)
|
|
133
|
+
} catch (error) {
|
|
134
|
+
logger.warn?.('[dsh-skill-harbor] watcher unavailable, falling back to TTL', error)
|
|
98
135
|
}
|
|
99
136
|
|
|
100
137
|
const register = (path, methods, handler) => {
|
|
@@ -431,7 +468,39 @@ export function registerRoutes(ctx, config = {}, deps = {}) {
|
|
|
431
468
|
sendJson(res, 200, { ok: true, changed: result.changed, source: result.source })
|
|
432
469
|
})
|
|
433
470
|
|
|
471
|
+
// ---- 偏好:GET 读 / POST 部分更新 ----
|
|
472
|
+
// 同一路径只能注册一次(宿主按绝对路径去重),方法在这里分派。
|
|
473
|
+
register('/settings', ['GET', 'POST'], async (req, res, body, method) => {
|
|
474
|
+
if (method === 'GET') {
|
|
475
|
+
const { settings, degraded, reason } = readSettings(config)
|
|
476
|
+
sendJson(res, 200, { settings, degraded, ...(reason === undefined ? {} : { reason }) })
|
|
477
|
+
return
|
|
478
|
+
}
|
|
479
|
+
try {
|
|
480
|
+
const next = writeSettings(config, body ?? {})
|
|
481
|
+
sendJson(res, 200, { ok: true, settings: next })
|
|
482
|
+
} catch (error) {
|
|
483
|
+
logger.warn?.('[dsh-skill-harbor] settings write failed', error)
|
|
484
|
+
sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
|
|
485
|
+
}
|
|
486
|
+
})
|
|
487
|
+
|
|
488
|
+
// ---- 规则包:导出 ----
|
|
489
|
+
register('/rules/export', ['GET'], async (req, res) => {
|
|
490
|
+
sendJson(res, 200, exportRulePack({ plugin: 'dsh-skill-harbor' }))
|
|
491
|
+
})
|
|
492
|
+
|
|
493
|
+
// ---- 规则包:回灌 ----
|
|
494
|
+
register('/rules/import', ['POST'], async (req, res, body) => {
|
|
495
|
+
const result = importRulePack(body)
|
|
496
|
+
sendJson(res, result.ok ? 200 : 422, result)
|
|
497
|
+
})
|
|
498
|
+
|
|
434
499
|
return () => {
|
|
500
|
+
if (watcherState !== null) {
|
|
501
|
+
watcherState.close()
|
|
502
|
+
watcherState = null
|
|
503
|
+
}
|
|
435
504
|
for (const dispose of disposers) {
|
|
436
505
|
try {
|
|
437
506
|
dispose()
|
package/src/settings.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 面板偏好持久化。
|
|
3
|
+
*
|
|
4
|
+
* 落 `~/.dsh/skill-harbor/settings.json`。与市场源同一个 base 目录,
|
|
5
|
+
* 但**分开文件**:源列表和 UI 偏好生命周期不同(前者被安装/卸载改,后者被用户点改)。
|
|
6
|
+
*
|
|
7
|
+
* 读取做「字段级白名单 + 类型校验」:文件被手改成乱七八糟的值时,
|
|
8
|
+
* 逐字段回落默认值,而不是整份丢弃(UI 偏好丢了不该影响使用)。
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs'
|
|
11
|
+
import { dirname, join } from 'node:path'
|
|
12
|
+
|
|
13
|
+
import { DEFAULT_BUDGET_LIMIT, ANNOUNCEMENT_HARD_LIMIT } from './config.js'
|
|
14
|
+
|
|
15
|
+
export const SUPPORTED_LANGS = ['zh', 'en', 'ja', 'ko', 'fr', 'de', 'it', 'ru', 'es', 'pt']
|
|
16
|
+
export const SUPPORTED_TABS = ['overview', 'audit', 'budget']
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_SETTINGS = Object.freeze({
|
|
19
|
+
lang: 'zh',
|
|
20
|
+
tab: 'overview',
|
|
21
|
+
budgetLimit: DEFAULT_BUDGET_LIMIT,
|
|
22
|
+
announceToSystemPrompt: false,
|
|
23
|
+
pageSize: 50,
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
export function settingsFile(config) {
|
|
27
|
+
const base = config.dshHome ?? join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh')
|
|
28
|
+
return join(base, 'skill-harbor', 'settings.json')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 逐字段校验 + 归一化;任何非法字段回落默认值。 */
|
|
32
|
+
export function normalizeSettings(input) {
|
|
33
|
+
const raw = input !== null && typeof input === 'object' ? input : {}
|
|
34
|
+
const out = { ...DEFAULT_SETTINGS }
|
|
35
|
+
|
|
36
|
+
if (SUPPORTED_LANGS.includes(raw.lang)) out.lang = raw.lang
|
|
37
|
+
if (SUPPORTED_TABS.includes(raw.tab)) out.tab = raw.tab
|
|
38
|
+
|
|
39
|
+
if (Number.isFinite(raw.budgetLimit) && raw.budgetLimit > 0) {
|
|
40
|
+
out.budgetLimit = Math.min(raw.budgetLimit, 1_000_000)
|
|
41
|
+
}
|
|
42
|
+
if (typeof raw.announceToSystemPrompt === 'boolean') {
|
|
43
|
+
out.announceToSystemPrompt = raw.announceToSystemPrompt
|
|
44
|
+
}
|
|
45
|
+
if (Number.isFinite(raw.pageSize) && raw.pageSize > 0) {
|
|
46
|
+
out.pageSize = Math.min(Math.round(raw.pageSize), 500)
|
|
47
|
+
}
|
|
48
|
+
return out
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 读取偏好。返回 `{ settings, degraded }`:
|
|
53
|
+
* 文件损坏时 `degraded=true` 并给默认值 —— 用户至少还能用面板。
|
|
54
|
+
*/
|
|
55
|
+
export function readSettings(config) {
|
|
56
|
+
const file = settingsFile(config)
|
|
57
|
+
if (!existsSync(file)) return { settings: { ...DEFAULT_SETTINGS }, degraded: false }
|
|
58
|
+
|
|
59
|
+
let parsed
|
|
60
|
+
try {
|
|
61
|
+
parsed = JSON.parse(readFileSync(file, 'utf8'))
|
|
62
|
+
} catch {
|
|
63
|
+
return { settings: { ...DEFAULT_SETTINGS }, degraded: true, reason: 'unreadable' }
|
|
64
|
+
}
|
|
65
|
+
return { settings: normalizeSettings(parsed), degraded: false }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 原子写入。 */
|
|
69
|
+
export function writeSettings(config, patch) {
|
|
70
|
+
const current = readSettings(config).settings
|
|
71
|
+
const next = normalizeSettings({ ...current, ...patch })
|
|
72
|
+
const file = settingsFile(config)
|
|
73
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
74
|
+
const temp = `${file}.tmp-${process.pid}`
|
|
75
|
+
writeFileSync(temp, JSON.stringify(next, null, 2), 'utf8')
|
|
76
|
+
renameSync(temp, file)
|
|
77
|
+
return next
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 公告文本是否超过硬上限(UI 提示用)。 */
|
|
81
|
+
export function announcementOverHardLimit(text) {
|
|
82
|
+
return [...String(text ?? '')].length > ANNOUNCEMENT_HARD_LIMIT
|
|
83
|
+
}
|