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,317 @@
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
+ import { auditSkillText } from '../audit/rules.js'
17
+ import { budgetReport } from '../budget/announcement.js'
18
+
19
+ /** 关闭/开启模型的 frontmatter 键。 */
20
+ const DISABLE_KEY = 'disable-model-invocation'
21
+
22
+ /** 在正文里切换 `disable-model-invocation`,保留其余内容原样。 */
23
+ export function setModelInvocation(text, enabled) {
24
+ const line = enabled ? 'false' : 'true'
25
+ const prefixed = /^(---\r?\n)([\s\S]*?)(\r?\n---)/.exec(text)
26
+
27
+ if (prefixed === null) {
28
+ // 没有 frontmatter:新建一个
29
+ return `---\n${DISABLE_KEY}: ${line}\n---\n${text}`
30
+ }
31
+
32
+ const head = prefixed[2]
33
+ const entry = `${DISABLE_KEY}: ${line}`
34
+ const existing = new RegExp(`^${DISABLE_KEY}\\s*:.*$`, 'm')
35
+
36
+ const nextHead = existing.test(head)
37
+ ? head.replace(existing, entry)
38
+ : `${head}${head.trim() === '' ? '' : '\n'}${entry}`
39
+
40
+ return `${prefixed[1]}${nextHead}${prefixed[3]}${text.slice(prefixed[0].length)}`
41
+ }
42
+
43
+ /** 原子写:先写临时文件再 rename,避免半截文件。 */
44
+ function atomicWrite(path, content) {
45
+ const temp = `${path}.harbor-tmp-${process.pid}`
46
+ writeFileSync(temp, content, 'utf8')
47
+ try {
48
+ renameSync(temp, path)
49
+ } catch (error) {
50
+ try {
51
+ if (existsSync(temp)) unlinkSync(temp)
52
+ } catch {
53
+ /* ignore */
54
+ }
55
+ throw error
56
+ }
57
+ }
58
+
59
+ /**
60
+ * 注册全部路由。
61
+ * @param {object} ctx
62
+ * @param {object} config
63
+ * @param {object} [deps] 注入点(便于单测不依赖真实 webServer)
64
+ */
65
+ export function registerRoutes(ctx, config = {}, deps = {}) {
66
+ const webServer = deps.webServer ?? ctx.webServer
67
+ if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') {
68
+ // 没有 webserver(如纯 CLI 场景):不注册,但 provider 仍然工作
69
+ return () => {}
70
+ }
71
+
72
+ const logger = ctx?.logger ?? console
73
+ const disposers = []
74
+
75
+ /** 每次请求都重新扫描?否 —— 用短 TTL 缓存,写后立即失效。 */
76
+ let cached = null
77
+ let cacheAt = 0
78
+ const CACHE_MS = 1500
79
+
80
+ const snapshot = async () => {
81
+ const now = Date.now()
82
+ if (cached !== null && now - cacheAt < CACHE_MS) return cached
83
+ const registrySummaries = typeof ctx?.skills?.list === 'function' ? await ctx.skills.list() : []
84
+ cached = buildSnapshot(config, registrySummaries)
85
+ cacheAt = now
86
+ return cached
87
+ }
88
+ const invalidate = () => {
89
+ cached = null
90
+ cacheAt = 0
91
+ }
92
+
93
+ const register = (path, methods, handler) => {
94
+ const dispose = webServer.register({
95
+ kind: 'handler',
96
+ path: `${ROUTE_PREFIX}${path}`,
97
+ auth: 'required',
98
+ handler: guarded(ctx, { methods }, handler),
99
+ })
100
+ disposers.push(dispose)
101
+ }
102
+
103
+ // ---- 读:列表 ----
104
+ register('/list', ['GET'], async (req, res) => {
105
+ const snap = await snapshot()
106
+ sendJson(res, 200, {
107
+ takenAt: snap.takenAt,
108
+ skills: snap.observations.map(observation => ({
109
+ name: observation.name,
110
+ description: observation.description,
111
+ source: observation.source,
112
+ rank: observation.rank,
113
+ fileState: observation.fileState,
114
+ modelInvocable: observation.modelInvocable,
115
+ announcementChars: observation.announcementChars,
116
+ shadowedBy: observation.shadowedBy ?? null,
117
+ // 只有 editable 才暴露 path,且可写
118
+ path: observation.fileState === FILE_STATE.EDITABLE ? observation.path : null,
119
+ writable: isWritable(observation),
120
+ })),
121
+ duplicates: snap.duplicates.map(group => ({
122
+ name: group.name,
123
+ count: group.count,
124
+ winner: group.winner === null ? null : { source: group.winner.source, rank: group.winner.rank },
125
+ })),
126
+ totals: {
127
+ all: snap.observations.length,
128
+ editable: snap.observations.filter(o => o.fileState === FILE_STATE.EDITABLE).length,
129
+ providerFile: snap.observations.filter(o => o.fileState === FILE_STATE.PROVIDER_FILE).length,
130
+ virtual: snap.observations.filter(o => o.fileState === FILE_STATE.VIRTUAL).length,
131
+ shadowed: snap.observations.filter(o => o.shadowedBy !== undefined).length,
132
+ },
133
+ })
134
+ })
135
+
136
+ // ---- 读:单技能正文 ----
137
+ register('/read', ['GET'], async (req, res) => {
138
+ const snap = await snapshot()
139
+ const url = new URL(req.url ?? '/', 'http://localhost')
140
+ const target = url.searchParams.get('path')
141
+
142
+ const allowed = isAllowedPath(target, snap.allowlist)
143
+ if (!allowed.ok) {
144
+ sendJson(res, 403, { error: allowed.reason })
145
+ return
146
+ }
147
+ const body = readSkillBody(target, snap.allowlist)
148
+ if (!body.ok) {
149
+ sendJson(res, 404, { error: body.reason })
150
+ return
151
+ }
152
+ sendJson(res, 200, { path: target, content: body.content, meta: extractSkillMeta(body.content) })
153
+ })
154
+
155
+ // ---- 写:启停模型调用 ----
156
+ register('/set-enabled', ['POST'], async (req, res, body) => {
157
+ const snap = await snapshot()
158
+ const target = body?.path
159
+ const enabled = body?.enabled
160
+
161
+ if (typeof enabled !== 'boolean') {
162
+ sendJson(res, 400, { error: 'enabled-must-be-boolean' })
163
+ return
164
+ }
165
+ const allowed = isAllowedPath(target, snap.allowlist)
166
+ if (!allowed.ok) {
167
+ sendJson(res, 403, { error: allowed.reason })
168
+ return
169
+ }
170
+ if (!isSkillMarkdown(target)) {
171
+ sendJson(res, 400, { error: 'not-a-skill-markdown' })
172
+ return
173
+ }
174
+
175
+ try {
176
+ const current = readSkillBody(target, snap.allowlist)
177
+ if (!current.ok) {
178
+ sendJson(res, 404, { error: current.reason })
179
+ return
180
+ }
181
+ atomicWrite(target, setModelInvocation(current.content, enabled))
182
+ invalidate()
183
+ sendJson(res, 200, { ok: true, path: target, enabled })
184
+ } catch (error) {
185
+ logger.warn?.('[dsh-skill-harbor] set-enabled failed', error)
186
+ sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
187
+ }
188
+ })
189
+
190
+ // ---- 写:整体更新正文 ----
191
+ register('/update', ['POST'], async (req, res, body) => {
192
+ const snap = await snapshot()
193
+ const target = body?.path
194
+ const content = body?.content
195
+
196
+ if (typeof content !== 'string') {
197
+ sendJson(res, 400, { error: 'content-must-be-string' })
198
+ return
199
+ }
200
+ const allowed = isAllowedPath(target, snap.allowlist)
201
+ if (!allowed.ok) {
202
+ sendJson(res, 403, { error: allowed.reason })
203
+ return
204
+ }
205
+ if (!isSkillMarkdown(target)) {
206
+ sendJson(res, 400, { error: 'not-a-skill-markdown' })
207
+ return
208
+ }
209
+
210
+ try {
211
+ atomicWrite(target, content)
212
+ invalidate()
213
+ sendJson(res, 200, { ok: true, path: target })
214
+ } catch (error) {
215
+ logger.warn?.('[dsh-skill-harbor] update failed', error)
216
+ sendJson(res, 500, { error: 'write-failed', message: String(error?.message ?? error) })
217
+ }
218
+ })
219
+
220
+ // ---- 写:删除 ----
221
+ register('/delete', ['POST'], async (req, res, body) => {
222
+ const snap = await snapshot()
223
+ const target = body?.path
224
+
225
+ const allowed = isAllowedPath(target, snap.allowlist)
226
+ if (!allowed.ok) {
227
+ sendJson(res, 403, { error: allowed.reason })
228
+ return
229
+ }
230
+ if (!isSkillMarkdown(target)) {
231
+ sendJson(res, 400, { error: 'not-a-skill-markdown' })
232
+ return
233
+ }
234
+
235
+ try {
236
+ unlinkSync(target)
237
+ invalidate()
238
+ sendJson(res, 200, { ok: true, path: target })
239
+ } catch (error) {
240
+ logger.warn?.('[dsh-skill-harbor] delete failed', error)
241
+ sendJson(res, 500, { error: 'delete-failed', message: String(error?.message ?? error) })
242
+ }
243
+ })
244
+
245
+ // ---- 读:审计全量 ----
246
+ register('/audit', ['GET'], async (req, res) => {
247
+ const snap = await snapshot()
248
+ const results = []
249
+ for (const observation of snap.observations) {
250
+ if (observation.fileState !== FILE_STATE.EDITABLE) {
251
+ // provider-file / virtual 没有可信路径 → 明确是 skipped,不是 ok
252
+ results.push({
253
+ name: observation.name,
254
+ source: observation.source,
255
+ fileState: observation.fileState,
256
+ verdict: 'skipped',
257
+ reason: observation.fileState === FILE_STATE.PROVIDER_FILE
258
+ ? 'file-exists-but-not-scanned'
259
+ : 'no-instruction-file',
260
+ findings: [],
261
+ })
262
+ continue
263
+ }
264
+ const body = readSkillBody(observation.path, snap.allowlist)
265
+ if (!body.ok) {
266
+ results.push({
267
+ name: observation.name,
268
+ source: observation.source,
269
+ fileState: observation.fileState,
270
+ verdict: 'skipped',
271
+ reason: body.reason,
272
+ findings: [],
273
+ })
274
+ continue
275
+ }
276
+ const audit = auditSkillText(body.content, { name: observation.name })
277
+ results.push({
278
+ name: observation.name,
279
+ source: observation.source,
280
+ fileState: observation.fileState,
281
+ verdict: audit.verdict,
282
+ findings: audit.findings,
283
+ stats: audit.stats,
284
+ })
285
+ }
286
+
287
+ sendJson(res, 200, {
288
+ takenAt: snap.takenAt,
289
+ totals: {
290
+ ok: results.filter(r => r.verdict === 'ok').length,
291
+ warn: results.filter(r => r.verdict === 'warn').length,
292
+ fail: results.filter(r => r.verdict === 'fail').length,
293
+ skipped: results.filter(r => r.verdict === 'skipped').length,
294
+ },
295
+ results,
296
+ })
297
+ })
298
+
299
+ // ---- 读:字符预算 ----
300
+ register('/budget', ['GET'], async (req, res) => {
301
+ const snap = await snapshot()
302
+ sendJson(res, 200, { takenAt: snap.takenAt, ...budgetReport(snap.observations) })
303
+ })
304
+
305
+ return () => {
306
+ for (const dispose of disposers) {
307
+ try {
308
+ dispose()
309
+ } catch {
310
+ /* ignore */
311
+ }
312
+ }
313
+ disposers.length = 0
314
+ }
315
+ }
316
+
317
+ 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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-skill-harbor",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "DSH 技能港湾:技能发现、遮蔽判定、审计与市场管理插件(基础骨架)",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,77 @@
1
+ /**
2
+ * 唯一文本归一化函数 —— **所有审计入口共用这一份**。
3
+ *
4
+ * 为什么必须先归一化:恶意技能可以把 NUL/零宽字符插进 `curl` 之类的词里,
5
+ * 让正则匹配不到,但 shell 执行时照样生效。剥掉伪装层再判定,才有意义。
6
+ *
7
+ * 保留:tab(0x09) LF(0x0A) CR(0x0D) ESC(0x1B)
8
+ * 剥除:NUL(0x00)、其余 C0 控制字符、零宽字符、双向控制字符、替换字符 U+FFFD
9
+ */
10
+
11
+ /** 零宽与不可见格式字符。 */
12
+ const INVISIBLE = /[\u200B-\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\uFEFF\u00AD]/g
13
+
14
+ /** Unicode tag 字符(U+E0000–E007F),常被用来夹带隐藏指令。 */
15
+ const UNICODE_TAGS = /[\u{E0000}-\u{E007F}]/gu
16
+
17
+ /** 替换字符。 */
18
+ const REPLACEMENT = /\uFFFD/g
19
+
20
+ /** C0 控制字符,保留 tab/LF/CR/ESC。 */
21
+ const C0 = /[\u0000-\u0008\u000B\u000C\u000E-\u001A\u001C-\u001F]/g
22
+
23
+ /** 归一化结果,同时报告发现了哪种伪装(供规则层直接用)。 */
24
+ export function normalizeText(input) {
25
+ if (typeof input !== 'string') return { text: '', findings: [] }
26
+
27
+ const findings = []
28
+
29
+ let text = input
30
+ if (C0.test(text)) findings.push('c0-control')
31
+ if (/\u0000/.test(text)) findings.push('nul-byte')
32
+ if (INVISIBLE.test(text)) findings.push('invisible-format')
33
+ if (UNICODE_TAGS.test(text)) findings.push('unicode-tag')
34
+ if (REPLACEMENT.test(text)) findings.push('replacement-char')
35
+ // 双向控制符单独标记:它能让显示顺序与实际执行顺序不一致
36
+ if (/[\u202A-\u202E\u2066-\u2069]/.test(text)) findings.push('bidi-control')
37
+
38
+ // 重置 lastIndex(这些正则带 g 或只用 test,安全起见重建)
39
+ text = input
40
+ .replace(/\u0000/g, '')
41
+ .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001A\u001C-\u001F]/g, '')
42
+ .replace(INVISIBLE, '')
43
+ .replace(UNICODE_TAGS, '')
44
+ .replace(/\uFFFD/g, '')
45
+
46
+ // 统一换行,便于规则按行工作
47
+ text = text.replace(/\r\n?/g, '\n')
48
+
49
+ return { text, findings: [...new Set(findings)] }
50
+ }
51
+
52
+ /**
53
+ * 编码伪装检测:UTF-16 / 换轮替代 / 大量 base64 块。
54
+ * 返回命中的伪装类型列表。
55
+ */
56
+ export function detectEncodingDisguise(raw) {
57
+ const hits = []
58
+
59
+ // UTF-16 BOM
60
+ if (/^\u00EF\u00BB\u00BF/.test(raw) === false && /^\u00FF\u00FE|^\u00FE\u00FF/.test(raw)) {
61
+ hits.push('utf16-bom')
62
+ }
63
+ // 文本里夹着大量 NUL(UTF-16 被当 UTF-8 读的典型形态)
64
+ const nulCount = (raw.match(/\u0000/g) ?? []).length
65
+ if (nulCount > 8) hits.push('utf16-pattern')
66
+
67
+ // 连续超长 base64 块(可能是被编码的载荷)
68
+ const b64 = raw.match(/[A-Za-z0-9+/]{200,}={0,2}/g)
69
+ if (b64 !== null) hits.push('base64-blob')
70
+
71
+ return hits
72
+ }
73
+
74
+ /** 字符数(按码点,不按 UTF-16 code unit)。 */
75
+ export function charLength(text) {
76
+ return typeof text === 'string' ? [...text].length : 0
77
+ }