dsh-vigil 0.0.1 → 0.0.2

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.
@@ -1,341 +1,341 @@
1
- /**
2
- * Remote rule-pack updates.
3
- *
4
- * Rule packs are data (`rules/*.yaml`), so an operator can host a newer pack
5
- * outside the plugin and let dsh-vigil pick it up without a release. The
6
- * manifest contract is deliberately tiny:
7
- *
8
- * {
9
- * "version": "2026.11.21",
10
- * "files": {
11
- * "sentinel.yaml": "https://example.com/rules/sentinel.yaml",
12
- * "audit.yaml": "https://example.com/rules/audit.yaml"
13
- * }
14
- * }
15
- *
16
- * Safety rules:
17
- * - HTTPS only (loopback HTTP is allowed for tests);
18
- * - bounded sizes, bounded file count, `.yaml`/`.yml` basenames only;
19
- * - every downloaded file is validated by loading it through the rule-pack
20
- * loader before it becomes active; a failure restores the previous files;
21
- * - the hash lock is refreshed only for a successful update, so `vigil_rules
22
- * verify` keeps describing what is actually loaded.
23
- *
24
- * @module rules/update
25
- */
26
-
27
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
28
- import { basename, dirname, join } from 'node:path'
29
- import { parseYaml } from './yaml.js'
30
- import { pinRulePack, reloadRulePack, verifyRulePack } from './pack.js'
31
-
32
- /** Authenticated browser fetch path for rule-pack updates. */
33
- export const RULES_UPDATE_PATH = '/api/dsh-vigil/rules-update'
34
-
35
- const MAX_MANIFEST_BYTES = 256 * 1024
36
- const MAX_PACK_BYTES = 512 * 1024
37
- const MAX_PACK_FILES = 8
38
- const FETCH_TIMEOUT_MS = 8000
39
-
40
- const SOURCE_SCHEME = /^https:\/\//i
41
- const LOOPBACK_HTTP = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d+)?\//i
42
- const PACK_NAME = /^[A-Za-z0-9._-]+\.ya?ml$/
43
-
44
- /**
45
- * @param {string} url
46
- * @returns {{ ok: true } | { ok: false, error: string }}
47
- */
48
- export function validateRulesSource(url) {
49
- if (typeof url !== 'string' || url.trim() === '') return { ok: false, error: '规则库更新源为空' }
50
- const value = url.trim()
51
- if (SOURCE_SCHEME.test(value) || LOOPBACK_HTTP.test(value)) return { ok: true }
52
- return { ok: false, error: '规则库更新源必须是 https:// 地址(测试可用 127.0.0.1 的 http)' }
53
- }
54
-
55
- /**
56
- * @param {any} value
57
- * @returns {{ ok: boolean, manifest?: { version: string, files: Record<string,string> }, error?: string }}
58
- */
59
- export function parseManifest(value) {
60
- if (!value || typeof value !== 'object' || Array.isArray(value)) return { ok: false, error: '清单必须是 JSON 对象' }
61
- const version = typeof value.version === 'string' ? value.version.trim() : ''
62
- if (version === '' || version.length > 120) return { ok: false, error: '清单缺少合法的 version' }
63
- const files = value.files
64
- if (!files || typeof files !== 'object' || Array.isArray(files)) return { ok: false, error: '清单缺少 files 对象' }
65
- const entries = Object.entries(files)
66
- if (entries.length === 0 || entries.length > MAX_PACK_FILES) {
67
- return { ok: false, error: `清单必须包含 1–${MAX_PACK_FILES} 个规则文件` }
68
- }
69
- /** @type {Record<string,string>} */
70
- const clean = {}
71
- for (const [name, url] of entries) {
72
- if (!PACK_NAME.test(name)) return { ok: false, error: `规则文件名不合法:${name}` }
73
- if (typeof url !== 'string') return { ok: false, error: `${name} 的地址不是字符串` }
74
- const source = validateRulesSource(url)
75
- if (!source.ok) return { ok: false, error: `${name}:${source.error}` }
76
- clean[name] = url.trim()
77
- }
78
- return { ok: true, manifest: { version, files: clean } }
79
- }
80
-
81
- /**
82
- * Fetch one URL with a byte cap, timeout and redirect policy.
83
- * @param {string} url
84
- * @param {{ maxBytes: number, fetchImpl?: typeof fetch, timeoutMs?: number }} options
85
- * @returns {Promise<{ ok: true, text: string } | { ok: false, error: string }>}
86
- */
87
- export async function fetchTextCapped(url, options) {
88
- const fetchImpl = options.fetchImpl ?? globalThis.fetch
89
- if (typeof fetchImpl !== 'function') return { ok: false, error: '当前运行时没有 fetch' }
90
- const controller = new AbortController()
91
- const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? FETCH_TIMEOUT_MS)
92
- try {
93
- const response = await fetchImpl(url, {
94
- signal: controller.signal,
95
- redirect: 'follow',
96
- headers: { accept: 'application/json, text/yaml, text/plain, */*' },
97
- })
98
- if (!response.ok) return { ok: false, error: `${url} → HTTP ${response.status}` }
99
- const length = Number(response.headers?.get?.('content-length'))
100
- if (Number.isFinite(length) && length > options.maxBytes) {
101
- return { ok: false, error: `${url} 超过大小上限(${options.maxBytes} 字节)` }
102
- }
103
- const text = await response.text()
104
- if (Buffer.byteLength(text, 'utf8') > options.maxBytes) {
105
- return { ok: false, error: `${url} 超过大小上限(${options.maxBytes} 字节)` }
106
- }
107
- return { ok: true, text }
108
- } catch (error) {
109
- const reason = error instanceof Error ? error.message : String(error)
110
- return { ok: false, error: `${url} 请求失败:${reason}` }
111
- } finally {
112
- clearTimeout(timer)
113
- }
114
- }
115
-
116
- /** @param {string} versionFile */
117
- export function readRulesVersion(versionFile) {
118
- try {
119
- const parsed = JSON.parse(readFileSync(versionFile, 'utf8'))
120
- return parsed && typeof parsed === 'object' ? parsed : null
121
- } catch {
122
- return null
123
- }
124
- }
125
-
126
- /** @param {string} versionFile @param {any} value */
127
- function writeRulesVersion(versionFile, value) {
128
- mkdirSync(dirname(versionFile), { recursive: true })
129
- const tmp = `${versionFile}.tmp`
130
- writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`)
131
- renameSync(tmp, versionFile)
132
- }
133
-
134
- /**
135
- * Rewrite a manifest file URL to the mirror matching the manifest source.
136
- * The shipped manifest lists jsDelivr URLs; when the operator selects the
137
- * GitHub raw manifest we must download the rule files from GitHub too,
138
- * otherwise a CDN-cached stale file would be installed under a newer version.
139
- * The reverse mapping keeps a custom jsDelivr manifest working when the
140
- * manifest itself lists GitHub raw URLs.
141
- *
142
- * @param {string} fileUrl
143
- * @param {string} sourceUrl
144
- * @returns {string}
145
- */
146
- export function resolveRuleFileUrl(fileUrl, sourceUrl) {
147
- const githubRaw = /^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/([^/]+)\/(.+)$/.exec(fileUrl)
148
- const jsdelivr = /^https:\/\/cdn\.jsdelivr\.net\/gh\/([^/@]+)\/([^@/]+)@([^/]+)\/(.+)$/.exec(fileUrl)
149
- let host = ''
150
- try {
151
- host = new URL(sourceUrl).hostname
152
- } catch {
153
- return fileUrl
154
- }
155
- if (host === 'raw.githubusercontent.com' && jsdelivr) {
156
- return `https://raw.githubusercontent.com/${jsdelivr[1]}/${jsdelivr[2]}/${jsdelivr[3]}/${jsdelivr[4]}`
157
- }
158
- if (host === 'cdn.jsdelivr.net' && githubRaw) {
159
- return `https://cdn.jsdelivr.net/gh/${githubRaw[1]}/${githubRaw[2]}@${githubRaw[3]}/${githubRaw[4]}`
160
- }
161
- return fileUrl
162
- }
163
-
164
- /**
165
- * Download a manifest and compare it with the locally installed version.
166
- * @param {{ source: string, versionFile: string, fetchImpl?: typeof fetch }} options
167
- */
168
- export async function checkRulesUpdate(options) {
169
- const source = validateRulesSource(options.source)
170
- if (!source.ok) return { ok: false, error: source.error }
171
- const manifestResult = await fetchTextCapped(options.source, {
172
- maxBytes: MAX_MANIFEST_BYTES,
173
- fetchImpl: options.fetchImpl,
174
- })
175
- if (!manifestResult.ok) return { ok: false, error: manifestResult.error }
176
- let parsed
177
- try {
178
- parsed = JSON.parse(manifestResult.text)
179
- } catch {
180
- return { ok: false, error: '清单不是合法 JSON' }
181
- }
182
- const manifest = parseManifest(parsed)
183
- if (!manifest.ok) return { ok: false, error: manifest.error }
184
- const current = readRulesVersion(options.versionFile)
185
- const currentVersion = typeof current?.version === 'string' ? current.version : null
186
- return {
187
- ok: true,
188
- currentVersion,
189
- latestVersion: manifest.manifest.version,
190
- available: currentVersion !== manifest.manifest.version,
191
- files: Object.keys(manifest.manifest.files),
192
- source: options.source,
193
- }
194
- }
195
-
196
- /**
197
- * Download, validate and install the manifest's rule files.
198
- *
199
- * @param {{
200
- * source: string,
201
- * targetDir: string,
202
- * versionFile: string,
203
- * lockPath: string,
204
- * fetchImpl?: typeof fetch,
205
- * logger?: { warn?: (message: string) => void },
206
- * }} options
207
- * @returns {Promise<{ ok: boolean, version?: string, files?: string[], error?: string, warnings?: string[] }>}
208
- */
209
- export async function applyRulesUpdate(options) {
210
- const source = validateRulesSource(options.source)
211
- if (!source.ok) return { ok: false, error: source.error }
212
- const manifestResult = await fetchTextCapped(options.source, { maxBytes: MAX_MANIFEST_BYTES, fetchImpl: options.fetchImpl })
213
- if (!manifestResult.ok) return { ok: false, error: manifestResult.error }
214
- let raw
215
- try {
216
- raw = JSON.parse(manifestResult.text)
217
- } catch {
218
- return { ok: false, error: '清单不是合法 JSON' }
219
- }
220
- const parsed = parseManifest(raw)
221
- if (!parsed.ok) return { ok: false, error: parsed.error }
222
- const { version, files } = parsed.manifest
223
-
224
- // Download and validate everything before touching the live directory.
225
- /** @type {Record<string,string>} */
226
- const downloaded = {}
227
- for (const [name, fileUrl] of Object.entries(files)) {
228
- const result = await fetchTextCapped(resolveRuleFileUrl(fileUrl, options.source), { maxBytes: MAX_PACK_BYTES, fetchImpl: options.fetchImpl })
229
- if (!result.ok) return { ok: false, error: result.error }
230
- try {
231
- const document = parseYaml(result.text)
232
- if (!document || typeof document !== 'object' || Array.isArray(document)) {
233
- return { ok: false, error: `${name} 不是 YAML 对象` }
234
- }
235
- downloaded[name] = result.text
236
- } catch (error) {
237
- return { ok: false, error: `${name} 解析失败:${error instanceof Error ? error.message : String(error)}` }
238
- }
239
- }
240
-
241
- mkdirSync(options.targetDir, { recursive: true })
242
- /** @type {Record<string, string|null>} */
243
- const before = {}
244
- for (const name of Object.keys(downloaded)) {
245
- const file = join(options.targetDir, name)
246
- try {
247
- before[name] = readFileSync(file, 'utf8')
248
- } catch {
249
- before[name] = null
250
- }
251
- const tmp = `${file}.tmp`
252
- writeFileSync(tmp, downloaded[name])
253
- renameSync(tmp, file)
254
- }
255
-
256
- // Load through the real loader *without* the lock first: the new files are
257
- // expected to differ from the pinned hashes, and the lock check would reject
258
- // them before parsing. A pack that fails to compile is rolled back below.
259
- const loaded = reloadRulePack({ externalDir: options.targetDir, logger: options.logger })
260
- const failed = loaded.warnings.filter(warning => Object.keys(downloaded).some(name => warning.includes(basename(name))))
261
- if (failed.length > 0) {
262
- for (const [name, content] of Object.entries(before)) {
263
- const file = join(options.targetDir, name)
264
- try {
265
- if (content === null) writeFileSync(file, '')
266
- else writeFileSync(file, content)
267
- } catch {
268
- // best effort restore
269
- }
270
- }
271
- reloadRulePack({ externalDir: options.targetDir, lockPath: options.lockPath, logger: options.logger })
272
- return { ok: false, error: `规则校验失败,已回滚:${failed[0]}`, warnings: failed }
273
- }
274
-
275
- const pinned = pinRulePack({ externalDir: options.targetDir, lockPath: options.lockPath })
276
- if (!pinned.ok) return { ok: false, error: pinned.error ?? '无法更新规则锁' }
277
- // Re-apply with the fresh lock so the loaded pack and the lock agree.
278
- reloadRulePack({ externalDir: options.targetDir, lockPath: options.lockPath, logger: options.logger })
279
- writeRulesVersion(options.versionFile, {
280
- source: options.source,
281
- version,
282
- updatedAt: new Date().toISOString(),
283
- files: Object.keys(downloaded),
284
- })
285
- return { ok: true, version, files: Object.keys(downloaded) }
286
- }
287
-
288
- /**
289
- * Compare the active files with the hash lock (used by the status route).
290
- * @param {{ targetDir: string, lockPath: string }} options
291
- */
292
- export function rulesDriftState(options) {
293
- return verifyRulePack({ externalDir: options.targetDir, lockPath: options.lockPath })
294
- }
295
-
296
- /** Ensure the target directory exists (updated packs are written there). */
297
- export function ensureRulesTargetDir(dir) {
298
- try {
299
- if (existsSync(dir)) return
300
- mkdirSync(dir, { recursive: true })
301
- } catch {
302
- // the update itself will report the failure
303
- }
304
- }
305
-
306
- /**
307
- * Authenticated browser route for rule-pack updates.
308
- *
309
- * GET /api/dsh-vigil/rules-update last known state (no network)
310
- * POST /api/dsh-vigil/rules-update { action: 'check' | 'update' }
311
- *
312
- * @param {{ getState: () => object, run: (options: { update?: boolean }) => Promise<any>, logger?: any }} deps
313
- */
314
- export function createRulesUpdateRoute(deps) {
315
- const json = (payload, status = 200) => new Response(`${JSON.stringify(payload)}\n`, {
316
- status,
317
- headers: {
318
- 'content-type': 'application/json; charset=utf-8',
319
- 'cache-control': 'no-store',
320
- 'x-content-type-options': 'nosniff',
321
- },
322
- })
323
- return {
324
- path: RULES_UPDATE_PATH,
325
- methods: ['GET', 'POST'],
326
- requestBody: 'buffered',
327
- fetch: async request => {
328
- const method = typeof request?.method === 'string' ? request.method.toUpperCase() : 'GET'
329
- if (method !== 'POST') return json({ ok: true, state: deps.getState?.() ?? null })
330
- let body
331
- try {
332
- body = typeof request.json === 'function' ? await request.json().catch(() => null) : null
333
- } catch {
334
- body = null
335
- }
336
- const action = body?.action === 'update' ? 'update' : 'check'
337
- const result = await deps.run({ update: action === 'update' })
338
- return json({ ok: result.ok !== false, action, ...result }, result.ok === false ? 500 : 200)
339
- },
340
- }
341
- }
1
+ /**
2
+ * Remote rule-pack updates.
3
+ *
4
+ * Rule packs are data (`rules/*.yaml`), so an operator can host a newer pack
5
+ * outside the plugin and let dsh-vigil pick it up without a release. The
6
+ * manifest contract is deliberately tiny:
7
+ *
8
+ * {
9
+ * "version": "2026.11.21",
10
+ * "files": {
11
+ * "sentinel.yaml": "https://example.com/rules/sentinel.yaml",
12
+ * "audit.yaml": "https://example.com/rules/audit.yaml"
13
+ * }
14
+ * }
15
+ *
16
+ * Safety rules:
17
+ * - HTTPS only (loopback HTTP is allowed for tests);
18
+ * - bounded sizes, bounded file count, `.yaml`/`.yml` basenames only;
19
+ * - every downloaded file is validated by loading it through the rule-pack
20
+ * loader before it becomes active; a failure restores the previous files;
21
+ * - the hash lock is refreshed only for a successful update, so `vigil_rules
22
+ * verify` keeps describing what is actually loaded.
23
+ *
24
+ * @module rules/update
25
+ */
26
+
27
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
28
+ import { basename, dirname, join } from 'node:path'
29
+ import { parseYaml } from './yaml.js'
30
+ import { pinRulePack, reloadRulePack, verifyRulePack } from './pack.js'
31
+
32
+ /** Authenticated browser fetch path for rule-pack updates. */
33
+ export const RULES_UPDATE_PATH = '/api/dsh-vigil/rules-update'
34
+
35
+ const MAX_MANIFEST_BYTES = 256 * 1024
36
+ const MAX_PACK_BYTES = 512 * 1024
37
+ const MAX_PACK_FILES = 8
38
+ const FETCH_TIMEOUT_MS = 8000
39
+
40
+ const SOURCE_SCHEME = /^https:\/\//i
41
+ const LOOPBACK_HTTP = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d+)?\//i
42
+ const PACK_NAME = /^[A-Za-z0-9._-]+\.ya?ml$/
43
+
44
+ /**
45
+ * @param {string} url
46
+ * @returns {{ ok: true } | { ok: false, error: string }}
47
+ */
48
+ export function validateRulesSource(url) {
49
+ if (typeof url !== 'string' || url.trim() === '') return { ok: false, error: '规则库更新源为空' }
50
+ const value = url.trim()
51
+ if (SOURCE_SCHEME.test(value) || LOOPBACK_HTTP.test(value)) return { ok: true }
52
+ return { ok: false, error: '规则库更新源必须是 https:// 地址(测试可用 127.0.0.1 的 http)' }
53
+ }
54
+
55
+ /**
56
+ * @param {any} value
57
+ * @returns {{ ok: boolean, manifest?: { version: string, files: Record<string,string> }, error?: string }}
58
+ */
59
+ export function parseManifest(value) {
60
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return { ok: false, error: '清单必须是 JSON 对象' }
61
+ const version = typeof value.version === 'string' ? value.version.trim() : ''
62
+ if (version === '' || version.length > 120) return { ok: false, error: '清单缺少合法的 version' }
63
+ const files = value.files
64
+ if (!files || typeof files !== 'object' || Array.isArray(files)) return { ok: false, error: '清单缺少 files 对象' }
65
+ const entries = Object.entries(files)
66
+ if (entries.length === 0 || entries.length > MAX_PACK_FILES) {
67
+ return { ok: false, error: `清单必须包含 1–${MAX_PACK_FILES} 个规则文件` }
68
+ }
69
+ /** @type {Record<string,string>} */
70
+ const clean = {}
71
+ for (const [name, url] of entries) {
72
+ if (!PACK_NAME.test(name)) return { ok: false, error: `规则文件名不合法:${name}` }
73
+ if (typeof url !== 'string') return { ok: false, error: `${name} 的地址不是字符串` }
74
+ const source = validateRulesSource(url)
75
+ if (!source.ok) return { ok: false, error: `${name}:${source.error}` }
76
+ clean[name] = url.trim()
77
+ }
78
+ return { ok: true, manifest: { version, files: clean } }
79
+ }
80
+
81
+ /**
82
+ * Fetch one URL with a byte cap, timeout and redirect policy.
83
+ * @param {string} url
84
+ * @param {{ maxBytes: number, fetchImpl?: typeof fetch, timeoutMs?: number }} options
85
+ * @returns {Promise<{ ok: true, text: string } | { ok: false, error: string }>}
86
+ */
87
+ export async function fetchTextCapped(url, options) {
88
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch
89
+ if (typeof fetchImpl !== 'function') return { ok: false, error: '当前运行时没有 fetch' }
90
+ const controller = new AbortController()
91
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? FETCH_TIMEOUT_MS)
92
+ try {
93
+ const response = await fetchImpl(url, {
94
+ signal: controller.signal,
95
+ redirect: 'follow',
96
+ headers: { accept: 'application/json, text/yaml, text/plain, */*' },
97
+ })
98
+ if (!response.ok) return { ok: false, error: `${url} → HTTP ${response.status}` }
99
+ const length = Number(response.headers?.get?.('content-length'))
100
+ if (Number.isFinite(length) && length > options.maxBytes) {
101
+ return { ok: false, error: `${url} 超过大小上限(${options.maxBytes} 字节)` }
102
+ }
103
+ const text = await response.text()
104
+ if (Buffer.byteLength(text, 'utf8') > options.maxBytes) {
105
+ return { ok: false, error: `${url} 超过大小上限(${options.maxBytes} 字节)` }
106
+ }
107
+ return { ok: true, text }
108
+ } catch (error) {
109
+ const reason = error instanceof Error ? error.message : String(error)
110
+ return { ok: false, error: `${url} 请求失败:${reason}` }
111
+ } finally {
112
+ clearTimeout(timer)
113
+ }
114
+ }
115
+
116
+ /** @param {string} versionFile */
117
+ export function readRulesVersion(versionFile) {
118
+ try {
119
+ const parsed = JSON.parse(readFileSync(versionFile, 'utf8'))
120
+ return parsed && typeof parsed === 'object' ? parsed : null
121
+ } catch {
122
+ return null
123
+ }
124
+ }
125
+
126
+ /** @param {string} versionFile @param {any} value */
127
+ function writeRulesVersion(versionFile, value) {
128
+ mkdirSync(dirname(versionFile), { recursive: true })
129
+ const tmp = `${versionFile}.tmp`
130
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`)
131
+ renameSync(tmp, versionFile)
132
+ }
133
+
134
+ /**
135
+ * Rewrite a manifest file URL to the mirror matching the manifest source.
136
+ * The shipped manifest lists jsDelivr URLs; when the operator selects the
137
+ * GitHub raw manifest we must download the rule files from GitHub too,
138
+ * otherwise a CDN-cached stale file would be installed under a newer version.
139
+ * The reverse mapping keeps a custom jsDelivr manifest working when the
140
+ * manifest itself lists GitHub raw URLs.
141
+ *
142
+ * @param {string} fileUrl
143
+ * @param {string} sourceUrl
144
+ * @returns {string}
145
+ */
146
+ export function resolveRuleFileUrl(fileUrl, sourceUrl) {
147
+ const githubRaw = /^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/([^/]+)\/(.+)$/.exec(fileUrl)
148
+ const jsdelivr = /^https:\/\/cdn\.jsdelivr\.net\/gh\/([^/@]+)\/([^@/]+)@([^/]+)\/(.+)$/.exec(fileUrl)
149
+ let host = ''
150
+ try {
151
+ host = new URL(sourceUrl).hostname
152
+ } catch {
153
+ return fileUrl
154
+ }
155
+ if (host === 'raw.githubusercontent.com' && jsdelivr) {
156
+ return `https://raw.githubusercontent.com/${jsdelivr[1]}/${jsdelivr[2]}/${jsdelivr[3]}/${jsdelivr[4]}`
157
+ }
158
+ if (host === 'cdn.jsdelivr.net' && githubRaw) {
159
+ return `https://cdn.jsdelivr.net/gh/${githubRaw[1]}/${githubRaw[2]}@${githubRaw[3]}/${githubRaw[4]}`
160
+ }
161
+ return fileUrl
162
+ }
163
+
164
+ /**
165
+ * Download a manifest and compare it with the locally installed version.
166
+ * @param {{ source: string, versionFile: string, fetchImpl?: typeof fetch }} options
167
+ */
168
+ export async function checkRulesUpdate(options) {
169
+ const source = validateRulesSource(options.source)
170
+ if (!source.ok) return { ok: false, error: source.error }
171
+ const manifestResult = await fetchTextCapped(options.source, {
172
+ maxBytes: MAX_MANIFEST_BYTES,
173
+ fetchImpl: options.fetchImpl,
174
+ })
175
+ if (!manifestResult.ok) return { ok: false, error: manifestResult.error }
176
+ let parsed
177
+ try {
178
+ parsed = JSON.parse(manifestResult.text)
179
+ } catch {
180
+ return { ok: false, error: '清单不是合法 JSON' }
181
+ }
182
+ const manifest = parseManifest(parsed)
183
+ if (!manifest.ok) return { ok: false, error: manifest.error }
184
+ const current = readRulesVersion(options.versionFile)
185
+ const currentVersion = typeof current?.version === 'string' ? current.version : null
186
+ return {
187
+ ok: true,
188
+ currentVersion,
189
+ latestVersion: manifest.manifest.version,
190
+ available: currentVersion !== manifest.manifest.version,
191
+ files: Object.keys(manifest.manifest.files),
192
+ source: options.source,
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Download, validate and install the manifest's rule files.
198
+ *
199
+ * @param {{
200
+ * source: string,
201
+ * targetDir: string,
202
+ * versionFile: string,
203
+ * lockPath: string,
204
+ * fetchImpl?: typeof fetch,
205
+ * logger?: { warn?: (message: string) => void },
206
+ * }} options
207
+ * @returns {Promise<{ ok: boolean, version?: string, files?: string[], error?: string, warnings?: string[] }>}
208
+ */
209
+ export async function applyRulesUpdate(options) {
210
+ const source = validateRulesSource(options.source)
211
+ if (!source.ok) return { ok: false, error: source.error }
212
+ const manifestResult = await fetchTextCapped(options.source, { maxBytes: MAX_MANIFEST_BYTES, fetchImpl: options.fetchImpl })
213
+ if (!manifestResult.ok) return { ok: false, error: manifestResult.error }
214
+ let raw
215
+ try {
216
+ raw = JSON.parse(manifestResult.text)
217
+ } catch {
218
+ return { ok: false, error: '清单不是合法 JSON' }
219
+ }
220
+ const parsed = parseManifest(raw)
221
+ if (!parsed.ok) return { ok: false, error: parsed.error }
222
+ const { version, files } = parsed.manifest
223
+
224
+ // Download and validate everything before touching the live directory.
225
+ /** @type {Record<string,string>} */
226
+ const downloaded = {}
227
+ for (const [name, fileUrl] of Object.entries(files)) {
228
+ const result = await fetchTextCapped(resolveRuleFileUrl(fileUrl, options.source), { maxBytes: MAX_PACK_BYTES, fetchImpl: options.fetchImpl })
229
+ if (!result.ok) return { ok: false, error: result.error }
230
+ try {
231
+ const document = parseYaml(result.text)
232
+ if (!document || typeof document !== 'object' || Array.isArray(document)) {
233
+ return { ok: false, error: `${name} 不是 YAML 对象` }
234
+ }
235
+ downloaded[name] = result.text
236
+ } catch (error) {
237
+ return { ok: false, error: `${name} 解析失败:${error instanceof Error ? error.message : String(error)}` }
238
+ }
239
+ }
240
+
241
+ mkdirSync(options.targetDir, { recursive: true })
242
+ /** @type {Record<string, string|null>} */
243
+ const before = {}
244
+ for (const name of Object.keys(downloaded)) {
245
+ const file = join(options.targetDir, name)
246
+ try {
247
+ before[name] = readFileSync(file, 'utf8')
248
+ } catch {
249
+ before[name] = null
250
+ }
251
+ const tmp = `${file}.tmp`
252
+ writeFileSync(tmp, downloaded[name])
253
+ renameSync(tmp, file)
254
+ }
255
+
256
+ // Load through the real loader *without* the lock first: the new files are
257
+ // expected to differ from the pinned hashes, and the lock check would reject
258
+ // them before parsing. A pack that fails to compile is rolled back below.
259
+ const loaded = reloadRulePack({ externalDir: options.targetDir, logger: options.logger })
260
+ const failed = loaded.warnings.filter(warning => Object.keys(downloaded).some(name => warning.includes(basename(name))))
261
+ if (failed.length > 0) {
262
+ for (const [name, content] of Object.entries(before)) {
263
+ const file = join(options.targetDir, name)
264
+ try {
265
+ if (content === null) writeFileSync(file, '')
266
+ else writeFileSync(file, content)
267
+ } catch {
268
+ // best effort restore
269
+ }
270
+ }
271
+ reloadRulePack({ externalDir: options.targetDir, lockPath: options.lockPath, logger: options.logger })
272
+ return { ok: false, error: `规则校验失败,已回滚:${failed[0]}`, warnings: failed }
273
+ }
274
+
275
+ const pinned = pinRulePack({ externalDir: options.targetDir, lockPath: options.lockPath })
276
+ if (!pinned.ok) return { ok: false, error: pinned.error ?? '无法更新规则锁' }
277
+ // Re-apply with the fresh lock so the loaded pack and the lock agree.
278
+ reloadRulePack({ externalDir: options.targetDir, lockPath: options.lockPath, logger: options.logger })
279
+ writeRulesVersion(options.versionFile, {
280
+ source: options.source,
281
+ version,
282
+ updatedAt: new Date().toISOString(),
283
+ files: Object.keys(downloaded),
284
+ })
285
+ return { ok: true, version, files: Object.keys(downloaded) }
286
+ }
287
+
288
+ /**
289
+ * Compare the active files with the hash lock (used by the status route).
290
+ * @param {{ targetDir: string, lockPath: string }} options
291
+ */
292
+ export function rulesDriftState(options) {
293
+ return verifyRulePack({ externalDir: options.targetDir, lockPath: options.lockPath })
294
+ }
295
+
296
+ /** Ensure the target directory exists (updated packs are written there). */
297
+ export function ensureRulesTargetDir(dir) {
298
+ try {
299
+ if (existsSync(dir)) return
300
+ mkdirSync(dir, { recursive: true })
301
+ } catch {
302
+ // the update itself will report the failure
303
+ }
304
+ }
305
+
306
+ /**
307
+ * Authenticated browser route for rule-pack updates.
308
+ *
309
+ * GET /api/dsh-vigil/rules-update last known state (no network)
310
+ * POST /api/dsh-vigil/rules-update { action: 'check' | 'update' }
311
+ *
312
+ * @param {{ getState: () => object, run: (options: { update?: boolean }) => Promise<any>, logger?: any }} deps
313
+ */
314
+ export function createRulesUpdateRoute(deps) {
315
+ const json = (payload, status = 200) => new Response(`${JSON.stringify(payload)}\n`, {
316
+ status,
317
+ headers: {
318
+ 'content-type': 'application/json; charset=utf-8',
319
+ 'cache-control': 'no-store',
320
+ 'x-content-type-options': 'nosniff',
321
+ },
322
+ })
323
+ return {
324
+ path: RULES_UPDATE_PATH,
325
+ methods: ['GET', 'POST'],
326
+ requestBody: 'buffered',
327
+ fetch: async request => {
328
+ const method = typeof request?.method === 'string' ? request.method.toUpperCase() : 'GET'
329
+ if (method !== 'POST') return json({ ok: true, state: deps.getState?.() ?? null })
330
+ let body
331
+ try {
332
+ body = typeof request.json === 'function' ? await request.json().catch(() => null) : null
333
+ } catch {
334
+ body = null
335
+ }
336
+ const action = body?.action === 'update' ? 'update' : 'check'
337
+ const result = await deps.run({ update: action === 'update' })
338
+ return json({ ok: result.ok !== false, action, ...result }, result.ok === false ? 500 : 200)
339
+ },
340
+ }
341
+ }