dsh-vigil 0.0.1

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.
Files changed (56) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +188 -0
  3. package/client.js +4652 -0
  4. package/cordis.patch.yml +7 -0
  5. package/docs/DETAIL.md +66 -0
  6. package/icon.png +0 -0
  7. package/illustrations/notice.png +0 -0
  8. package/illustrations/warning.png +0 -0
  9. package/locale/en.json +7 -0
  10. package/locale/zh.json +7 -0
  11. package/package.json +75 -0
  12. package/rules/audit.yaml +130 -0
  13. package/rules/manifest.json +7 -0
  14. package/rules/sentinel.yaml +289 -0
  15. package/src/alert-route.js +194 -0
  16. package/src/approval.js +398 -0
  17. package/src/artwork-route.js +87 -0
  18. package/src/audit/ast.js +213 -0
  19. package/src/audit/install-scan.js +127 -0
  20. package/src/audit/lexer.js +307 -0
  21. package/src/audit/narrative.js +320 -0
  22. package/src/audit/rules.js +1440 -0
  23. package/src/audit/scan.js +880 -0
  24. package/src/audit-clear-route.js +89 -0
  25. package/src/audit-feed.js +265 -0
  26. package/src/audit-log.js +887 -0
  27. package/src/config-schema.js +194 -0
  28. package/src/config.js +580 -0
  29. package/src/delete/command-kinds.js +46 -0
  30. package/src/delete/lex.js +46 -0
  31. package/src/delete/parser-posix.js +1427 -0
  32. package/src/delete/parser-pwsh.js +1729 -0
  33. package/src/delete/parser.js +2082 -0
  34. package/src/delete/policy.js +680 -0
  35. package/src/delete/quarantine.js +417 -0
  36. package/src/index.js +1134 -0
  37. package/src/install-scan-route.js +58 -0
  38. package/src/install-watch.js +389 -0
  39. package/src/integrity.js +509 -0
  40. package/src/live-config.js +88 -0
  41. package/src/quarantine-route.js +74 -0
  42. package/src/quarantine-view.js +44 -0
  43. package/src/rules/pack.js +423 -0
  44. package/src/rules/update.js +341 -0
  45. package/src/rules/yaml.js +186 -0
  46. package/src/sage-action-route.js +63 -0
  47. package/src/sage-provision.js +716 -0
  48. package/src/sentinel/guard.js +392 -0
  49. package/src/sentinel/hook.js +546 -0
  50. package/src/sentinel/rules.js +488 -0
  51. package/src/sentinel/sage-load.js +79 -0
  52. package/src/sentinel/sage.js +550 -0
  53. package/src/tools.js +727 -0
  54. package/src/update-check.js +339 -0
  55. package/src/util.js +400 -0
  56. package/threats/README.md +25 -0
@@ -0,0 +1,887 @@
1
+ /**
2
+ * Append-only, hash-chained audit log (FR-6).
3
+ *
4
+ * Every guard decision is recorded as one JSON line in
5
+ * `<DSH_HOME>/vigil/log/audit-NNNNNN.jsonl`. Each record carries the SHA-256 of
6
+ * the previous record (and of its own canonical body), so deleting or rewriting
7
+ * a middle record is detectable with `vigil_audit action=verify`.
8
+ *
9
+ * Privacy rules enforced here, not by callers:
10
+ * - the raw command/path is scrubbed of the home directory before logging;
11
+ * - long values are truncated;
12
+ * - common secret-shaped assignments are redacted;
13
+ * - with `auditLog.logArguments=false` only a digest and length are stored.
14
+ *
15
+ * The log is synchronous on purpose: a decision must not proceed before its
16
+ * record is durable, otherwise an attacker could race the log.
17
+ *
18
+ * @module dsh-vigil/audit-log
19
+ */
20
+
21
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
22
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
23
+ import { dirname, join } from 'node:path'
24
+ import { atomicWriteJson, ensureDir, formatBytes, nowIso, readJson, scrubHome, sha256, stableStringify, truncate } from './util.js'
25
+
26
+ /** Current on-disk record schema version. */
27
+ export const AUDIT_SCHEMA_VERSION = 1
28
+
29
+ /** Trade-off: good enough to spot tampering, cheap enough to run per call. */
30
+ const STATE_FILE = 'state.json'
31
+ const FILE_PATTERN = /^audit-(\d{6})\.jsonl$/
32
+
33
+ /** Constant-time comparison for the anchor MAC. */
34
+ function macEquals(left, right) {
35
+ if (typeof left !== 'string' || typeof right !== 'string' || left.length !== right.length) return false
36
+ try {
37
+ return timingSafeEqual(Buffer.from(left, 'utf8'), Buffer.from(right, 'utf8'))
38
+ } catch {
39
+ return false
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Redact values that look like credentials so the audit log itself never
45
+ * becomes a secret store.
46
+ * @param {string} text
47
+ * @returns {string}
48
+ */
49
+ export function redactSecrets(text) {
50
+ if (typeof text !== 'string' || text === '') return ''
51
+ return text
52
+ .replace(/\b(AKIA|ASIA)[A-Z0-9]{16}\b/g, '<redacted-aws-key>')
53
+ .replace(/(-----BEGIN [A-Z ]*PRIVATE KEY-----)[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----)/g, '<redacted-private-key>')
54
+ .replace(/((?:password|passwd|pwd|secret|token|api[_-]?key|apikey|access[_-]?key)\s*[=:]\s*)(["']?)[^\s"'`,;]{6,}/gi, (_m, prefix, quote) => `${prefix}${quote}<redacted>`)
55
+ .replace(/(Bearer\s+)[A-Za-z0-9._~+/-]{8,}=*/g, '$1<redacted>')
56
+ }
57
+
58
+ /**
59
+ * Build the argument summary stored in one record.
60
+ * @param {Record<string, unknown>} args
61
+ * @param {any} config
62
+ * @returns {{ digest: string, length: number, summary: string|null }}
63
+ */
64
+ export function summarizeArguments(args, config) {
65
+ let text = ''
66
+ try {
67
+ text = stableStringify(args ?? {})
68
+ } catch {
69
+ text = String(args)
70
+ }
71
+ const digest = sha256(text)
72
+ if (config?.auditLog?.logArguments === false) {
73
+ return { digest, length: text.length, summary: null }
74
+ }
75
+ const limit = Math.max(16, Number(config?.auditLog?.argumentChars) || 300)
76
+ return { digest, length: text.length, summary: truncate(redactSecrets(scrubHome(text)), limit) }
77
+ }
78
+
79
+ /**
80
+ * @typedef {object} AuditRecordInput
81
+ * @property {'decision'|'event'|'integrity'|'quarantine'} kind
82
+ * @property {string} event short machine id, e.g. `pre-execute`
83
+ * @property {string|null} [tool]
84
+ * @property {string|null} [session]
85
+ * @property {string} [decision] allow | ask | deny | none
86
+ * @property {string} [wouldBe] what the decision would have been in monitor mode
87
+ * @property {string[]} [ruleIds]
88
+ * @property {string} [reason]
89
+ * @property {{digest?: string, length?: number, summary?: string|null}} [args]
90
+ * @property {object} [sage] matched Sage rule metadata (attribution preserved)
91
+ * @property {object} [approval] in-conversation approval outcome ({ action, scope })
92
+ * @property {object} [extra]
93
+ */
94
+
95
+ /**
96
+ * One sink per log directory per process.
97
+ *
98
+ * A runtime rebuild (Settings save, Sage provisioning, plugin reload through
99
+ * HMR) creates a new generation, but two generations can briefly overlap. Two
100
+ * independent in-memory chain heads writing the same JSONL file interleave
101
+ * duplicate `seq` values and break the hash chain. The registry is process-global
102
+ * (keyed by the directory, stored on a well-known symbol) so every generation —
103
+ * and even a hot-replaced module instance — appends through the same object.
104
+ * @type {Map<string, ReturnType<typeof createAuditLog>>}
105
+ */
106
+ const SINKS = (() => {
107
+ const key = Symbol.for('dsh-vigil.audit-sinks')
108
+ if (!globalThis[key]) globalThis[key] = new Map()
109
+ return /** @type {Map<string, ReturnType<typeof createAuditLog>>} */ (globalThis[key])
110
+ })()
111
+
112
+ /**
113
+ * Bump whenever the record shape or the sink's own behaviour changes. A sink
114
+ * lives on a process-global map, so a plugin reload keeps using the *old
115
+ * module's* closure; without this revision check a schema change (e.g. the
116
+ * `approval` field) would silently never be written until the app restarts.
117
+ */
118
+ const SINK_REVISION = 3
119
+
120
+ /**
121
+ * Acquire the shared audit sink for the configured directory, applying live
122
+ * settings changes to it.
123
+ * @param {any} config resolved configuration
124
+ * @param {{ warn?: (message: string) => void }} [logger]
125
+ * @returns {AuditLog}
126
+ */
127
+ export function acquireAuditLog(config, logger) {
128
+ const dir = String(config?.paths?.auditDir ?? '')
129
+ const existing = SINKS.get(dir)
130
+ if (existing && /** @type {any} */ (existing).sinkRevision === SINK_REVISION) {
131
+ existing.configure(config)
132
+ // A sink created by an older module generation may predate this method.
133
+ if (typeof existing.adoptExternalState === 'function') existing.adoptExternalState()
134
+ return existing
135
+ }
136
+ const sink = createAuditLog(config, logger)
137
+ Object.defineProperty(sink, 'sinkRevision', { value: SINK_REVISION, enumerable: false })
138
+ try {
139
+ sink.adoptExternalState()
140
+ } catch {
141
+ // the fresh sink already recovered from disk; adopt is a consistency nudge
142
+ }
143
+ SINKS.set(dir, sink)
144
+ return sink
145
+ }
146
+
147
+ /**
148
+ * Create the audit log facade for one activation.
149
+ * @param {any} config resolved configuration
150
+ * @param {{ warn?: (message: string) => void }} [logger]
151
+ * @returns {AuditLog}
152
+ */
153
+ export function createAuditLog(config, logger) {
154
+ let enabled = config?.auditLog?.enabled !== false
155
+ const dir = config?.paths?.auditDir ?? ''
156
+ let maxBytes = Number(config?.auditLog?.maxBytes) || 8388608
157
+ let maxFiles = Math.max(1, Number(config?.auditLog?.maxFiles) || 5)
158
+ const warnings = []
159
+ // Optional HMAC anchor over the chain head. The key comes from the
160
+ // environment: a key stored next to the log would be rewritten with it.
161
+ const anchorEnabled = config?.auditLog?.anchor?.enabled === true
162
+ const anchorKeyEnv = typeof config?.auditLog?.anchor?.keyEnv === 'string' && config.auditLog.anchor.keyEnv.trim() !== ''
163
+ ? config.auditLog.anchor.keyEnv.trim()
164
+ : 'DSH_VIGIL_ANCHOR_KEY'
165
+ const anchorEveryN = Math.max(1, Number(config?.auditLog?.anchor?.everyN) || 100)
166
+ const anchorFile = typeof config?.auditLog?.anchor?.file === 'string' && config.auditLog.anchor.file.trim() !== ''
167
+ ? config.auditLog.anchor.file.trim()
168
+ : join(dir, 'anchor.json')
169
+ const anchorKey = () => {
170
+ const value = process.env[anchorKeyEnv]
171
+ return typeof value === 'string' ? value : ''
172
+ }
173
+
174
+ /** @type {{ seq: number, lastHash: string, count: number, updatedAt: string }} */
175
+ let state = { seq: 0, lastHash: '', count: 0, updatedAt: '' }
176
+
177
+ if (enabled) {
178
+ try {
179
+ ensureDir(dir)
180
+ state = recoverState(dir, maxFiles)
181
+ } catch (error) {
182
+ warnings.push(`审计日志不可用:${error instanceof Error ? error.message : String(error)}`)
183
+ logger?.warn?.(`[dsh-vigil] 审计日志不可用:${String(error)}`)
184
+ }
185
+ }
186
+
187
+ /**
188
+ * @param {AuditRecordInput} input
189
+ * @returns {{ seq: number, hash: string } | null}
190
+ */
191
+ function record(input) {
192
+ if (!enabled) return null
193
+ try {
194
+ const body = {
195
+ v: AUDIT_SCHEMA_VERSION,
196
+ seq: state.seq + 1,
197
+ ts: nowIso(),
198
+ prev: state.lastHash,
199
+ kind: input.kind,
200
+ event: input.event,
201
+ tool: input.tool ?? null,
202
+ session: input.session ?? null,
203
+ decision: input.decision ?? 'none',
204
+ ...(input.wouldBe !== undefined ? { wouldBe: input.wouldBe } : {}),
205
+ ruleIds: Array.isArray(input.ruleIds) ? input.ruleIds : [],
206
+ reason: truncate(redactSecrets(scrubHome(input.reason ?? '')), 600),
207
+ ...(input.args ? { args: input.args } : {}),
208
+ ...(input.approval ? { approval: input.approval } : {}),
209
+ ...(input.sage ? { sage: input.sage } : {}),
210
+ ...(input.extra ? { extra: input.extra } : {}),
211
+ }
212
+ const hash = sha256(`${body.prev}\n${stableStringify(body)}`)
213
+ const line = JSON.stringify({ ...body, hash })
214
+ appendLine(dir, Math.floor((body.seq - 1) / 2000) + 1, line, maxBytes, maxFiles)
215
+ state = { seq: body.seq, lastHash: hash, count: state.count + 1, updatedAt: body.ts }
216
+ persistState(dir, state)
217
+ if (anchorEnabled) writeAnchor(body.seq, hash)
218
+ return { seq: body.seq, hash }
219
+ } catch (error) {
220
+ // Logging must never break a decision path; report once per activation.
221
+ if (!warnings.includes('write-failed')) {
222
+ warnings.push('write-failed')
223
+ logger?.warn?.(`[dsh-vigil] 无法写入审计日志:${String(error)}`)
224
+ }
225
+ return null
226
+ }
227
+ }
228
+
229
+ /**
230
+ * Write the HMAC anchor for the current chain head. Only the key from the
231
+ * environment can make the anchor trustworthy: a key stored beside the log
232
+ * would be rewritten together with it.
233
+ * @param {number} seq
234
+ * @param {string} hash
235
+ * @returns {void}
236
+ */
237
+ function writeAnchor(seq, hash) {
238
+ try {
239
+ const key = anchorKey()
240
+ if (key === '') return
241
+ const existing = readJson(anchorFile)
242
+ // Always establish the first anchor; afterwards follow the interval.
243
+ if (existing && Number(existing.seq) > 0 && seq % anchorEveryN !== 0) return
244
+ const at = nowIso()
245
+ const mac = createHmac('sha256', key).update(`${seq}\n${hash}\n${at}`).digest('hex')
246
+ ensureDir(dirname(anchorFile))
247
+ if (!atomicWriteJson(anchorFile, { v: 1, alg: 'HMAC-SHA256', seq, hash, at, keyEnv: anchorKeyEnv, mac })) {
248
+ throw new Error('无法写入锚点文件')
249
+ }
250
+ } catch (error) {
251
+ if (!warnings.includes('anchor-write-failed')) {
252
+ warnings.push('anchor-write-failed')
253
+ logger?.warn?.(`[dsh-vigil] 无法写入审计锚点:${String(error)}`)
254
+ }
255
+ }
256
+ }
257
+
258
+ /**
259
+ * @returns {{ ok: boolean, entries: number, firstBad: object|null, reason: string|null }}
260
+ */
261
+ function verifyChain() {
262
+ const files = listFiles(dir)
263
+ let previousHash = ''
264
+ let entries = 0
265
+ let expectedSeq = 1
266
+ for (const file of files) {
267
+ let raw = ''
268
+ try {
269
+ raw = readFileSync(join(dir, file), 'utf8')
270
+ } catch {
271
+ continue
272
+ }
273
+ for (const line of raw.split('\n')) {
274
+ if (line.trim() === '') continue
275
+ try {
276
+ const parsed = JSON.parse(line)
277
+ const { hash, ...body } = parsed
278
+ entries += 1
279
+ if (body.seq !== expectedSeq) {
280
+ return { ok: false, entries, firstBad: { seq: body.seq, file }, reason: `序号不连续:期望 ${expectedSeq}` }
281
+ }
282
+ if (body.prev !== previousHash) {
283
+ return { ok: false, entries, firstBad: { seq: body.seq, file }, reason: '前序哈希不匹配(记录被删除或重排)' }
284
+ }
285
+ if (sha256(`${body.prev}\n${stableStringify(body)}`) !== hash) {
286
+ return { ok: false, entries, firstBad: { seq: body.seq, file }, reason: '记录哈希不匹配(内容被改写)' }
287
+ }
288
+ previousHash = hash
289
+ expectedSeq += 1
290
+ } catch {
291
+ return { ok: false, entries, firstBad: { seq: expectedSeq, file }, reason: '记录不是合法 JSON' }
292
+ }
293
+ }
294
+ }
295
+ return { ok: true, entries, firstBad: null, reason: null }
296
+ }
297
+
298
+ /**
299
+ * Verify the HMAC anchor against the chain: the MAC must be valid, the anchor
300
+ * must not point past the head (rollback), and the record at that seq must
301
+ * carry the anchored hash.
302
+ * @returns {{ enabled: boolean, state: string, seq?: number, headSeq?: number, error?: string }}
303
+ */
304
+ function verifyAnchor() {
305
+ if (!anchorEnabled) return { enabled: false, state: 'disabled' }
306
+ const key = anchorKey()
307
+ if (key === '') return { enabled: true, state: 'no-key', error: `环境变量 ${anchorKeyEnv} 未设置` }
308
+ const raw = readJson(anchorFile)
309
+ if (!raw || typeof raw !== 'object') {
310
+ return { enabled: true, state: existsSync(anchorFile) ? 'corrupt' : 'missing' }
311
+ }
312
+ const seq = Number(raw.seq)
313
+ if (!Number.isFinite(seq) || seq < 1 || typeof raw.hash !== 'string' || typeof raw.mac !== 'string') {
314
+ return { enabled: true, state: 'corrupt' }
315
+ }
316
+ const expected = createHmac('sha256', key).update(`${seq}\n${raw.hash}\n${raw.at}`).digest('hex')
317
+ if (!macEquals(expected, raw.mac)) return { enabled: true, state: 'bad-mac', seq }
318
+ const records = readAllRecords(dir)
319
+ const headSeq = Number(records[records.length - 1]?.seq) || 0
320
+ if (seq > headSeq) return { enabled: true, state: 'ahead', seq, headSeq }
321
+ const anchored = records.find(item => item.seq === seq)
322
+ if (!anchored) return { enabled: true, state: 'gap', seq, headSeq }
323
+ if (anchored.hash !== raw.hash) return { enabled: true, state: 'mismatch', seq, headSeq }
324
+ return { enabled: true, state: 'ok', seq, headSeq }
325
+ }
326
+
327
+ /**
328
+ * Append a body that was read from disk (archive restore), preserving its
329
+ * fields while re-chaining it into the current head.
330
+ * @param {Record<string, any>} input
331
+ * @returns {{ seq: number, hash: string } | null}
332
+ */
333
+ function appendRecordBody(input) {
334
+ if (!enabled || !input || typeof input !== 'object') return null
335
+ try {
336
+ const { seq: _ignoredSeq, prev: _ignoredPrev, hash: _ignoredHash, ...body } = input
337
+ body.v = AUDIT_SCHEMA_VERSION
338
+ body.seq = state.seq + 1
339
+ body.prev = state.lastHash
340
+ const hash = sha256(`${body.prev}\n${stableStringify(body)}`)
341
+ appendLine(dir, Math.floor((body.seq - 1) / 2000) + 1, JSON.stringify({ ...body, hash }), maxBytes, maxFiles)
342
+ state = { seq: body.seq, lastHash: hash, count: state.count + 1, updatedAt: String(body.ts ?? nowIso()) }
343
+ persistState(dir, state)
344
+ return { seq: body.seq, hash }
345
+ } catch {
346
+ return null
347
+ }
348
+ }
349
+
350
+ return {
351
+ get enabled() {
352
+ return enabled
353
+ }, dir,
354
+ get warnings() {
355
+ return [...warnings]
356
+ },
357
+ /**
358
+ * Apply a new resolved configuration to the *same* sink so the process keeps
359
+ * one writer per directory (and therefore one chain head).
360
+ * @param {any} nextConfig
361
+ */
362
+ configure(nextConfig) {
363
+ const nextEnabled = nextConfig?.auditLog?.enabled !== false
364
+ if (nextEnabled && !enabled) {
365
+ // Re-enabling mid-life must rejoin the existing chain, not restart at 1.
366
+ try {
367
+ state = recoverState(dir, Math.max(1, Number(nextConfig?.auditLog?.maxFiles) || 5))
368
+ } catch {
369
+ // keep the in-memory head; the next record reports a broken link
370
+ }
371
+ }
372
+ enabled = nextEnabled
373
+ maxBytes = Math.max(4096, Number(nextConfig?.auditLog?.maxBytes) || 8388608)
374
+ maxFiles = Math.max(1, Number(nextConfig?.auditLog?.maxFiles) || 5)
375
+ },
376
+ /**
377
+ * Detect a log directory that was cleared manually (the documented way to
378
+ * reset a broken chain): with no chunk files left, the in-memory head is
379
+ * stale, so the next record starts a fresh chain instead of appending a
380
+ * sequence number that a verifier can only report as a gap.
381
+ */
382
+ adoptExternalState() {
383
+ if (!enabled) return
384
+ try {
385
+ if (listFiles(dir).length === 0 && state.seq > 0) {
386
+ state = { seq: 0, lastHash: '', count: 0, updatedAt: '' }
387
+ }
388
+ } catch {
389
+ // an unreadable directory keeps the in-memory head
390
+ }
391
+ },
392
+ record,
393
+ /**
394
+ * Delete every record and start a fresh chain. The cleanup itself is
395
+ * written as the first event of the new chain so the reset stays auditable.
396
+ * @returns {{ removed: number, remaining: number }}
397
+ */
398
+ clearAll() {
399
+ if (!enabled) return { removed: 0, remaining: 0 }
400
+ const removed = readAllRecords(dir).length
401
+ clearChunks(dir)
402
+ state = { seq: 0, lastHash: '', count: 0, updatedAt: '' }
403
+ record({
404
+ kind: 'event',
405
+ event: 'audit-clear',
406
+ reason: `已清空所有会话审计日志(删除 ${removed} 条记录,日志链从新起点重建)`,
407
+ })
408
+ return { removed, remaining: state.count }
409
+ },
410
+ /**
411
+ * Drop only the records of one conversation session, re-hashing the
412
+ * survivors into a new valid chain plus one cleanup event for that session.
413
+ * @param {string} sessionId
414
+ * @returns {{ removed: number, remaining: number }}
415
+ */
416
+ clearSession(sessionId) {
417
+ const sid = typeof sessionId === 'string' ? sessionId : ''
418
+ if (!enabled || sid === '') return { removed: 0, remaining: 0 }
419
+ const all = readAllRecords(dir)
420
+ const kept = all.filter(entry => entry && typeof entry === 'object' && entry.session !== sid && typeof entry.ts === 'string')
421
+ const removed = all.length - kept.length
422
+ rewriteChain(dir, kept)
423
+ state = recoverState(dir, maxFiles)
424
+ record({
425
+ kind: 'event',
426
+ event: 'audit-clear',
427
+ session: sid,
428
+ reason: `已清空本会话审计日志(删除 ${removed} 条记录)`,
429
+ })
430
+ return { removed, remaining: state.count }
431
+ },
432
+ /**
433
+ * Move one session's records into `<log>/archive/` and leave a marker event
434
+ * in the rewritten active chain. Used when a conversation is archived.
435
+ * @param {string} sessionId
436
+ * @returns {{ archived: number, remaining: number, archiveFile: string|null }}
437
+ */
438
+ archiveSession(sessionId) {
439
+ const sid = typeof sessionId === 'string' ? sessionId : ''
440
+ if (!enabled || sid === '') return { archived: 0, remaining: 0, archiveFile: null }
441
+ const all = readAllRecords(dir)
442
+ const archived = all.filter(entry => entry && typeof entry === 'object' && entry.session === sid)
443
+ if (archived.length === 0) return { archived: 0, remaining: state.count, archiveFile: null }
444
+ const kept = all.filter(entry => entry && typeof entry === 'object' && entry.session !== sid && typeof entry.ts === 'string')
445
+ const archiveFile = writeArchive(dir, sid, archived)
446
+ rewriteChain(dir, kept)
447
+ state = recoverState(dir, maxFiles)
448
+ record({
449
+ kind: 'event',
450
+ event: 'audit-archive',
451
+ reason: `对话已归档,同步归档本会话审计日志(${archived.length} 条)`,
452
+ extra: { archive: archiveFile, records: archived.length },
453
+ })
454
+ return { archived: archived.length, remaining: state.count, archiveFile }
455
+ },
456
+ /**
457
+ * Restore a session's archived records back into the active chain (unarchive).
458
+ * @param {string} sessionId
459
+ * @returns {{ restored: number, remaining: number }}
460
+ */
461
+ restoreSession(sessionId) {
462
+ const sid = typeof sessionId === 'string' ? sessionId : ''
463
+ if (!enabled || sid === '') return { restored: 0, remaining: state.count }
464
+ const restored = restoreArchived(dir, sid, appendRecordBody)
465
+ if (restored === 0) return { restored: 0, remaining: state.count }
466
+ record({
467
+ kind: 'event',
468
+ event: 'audit-restore',
469
+ session: sid,
470
+ reason: `对话已取消归档,恢复本会话审计日志(${restored} 条)`,
471
+ extra: { records: restored },
472
+ })
473
+ return { restored, remaining: state.count }
474
+ },
475
+ /**
476
+ * Drop one session's records when its conversation is deleted.
477
+ * @param {string} sessionId
478
+ * @returns {{ removed: number, remaining: number }}
479
+ */
480
+ removeSession(sessionId) {
481
+ const sid = typeof sessionId === 'string' ? sessionId : ''
482
+ if (!enabled || sid === '') return { removed: 0, remaining: state.count }
483
+ const all = readAllRecords(dir)
484
+ const kept = all.filter(entry => entry && typeof entry === 'object' && entry.session !== sid && typeof entry.ts === 'string')
485
+ const removed = all.length - kept.length
486
+ if (removed === 0) return { removed: 0, remaining: state.count }
487
+ rewriteChain(dir, kept)
488
+ state = recoverState(dir, maxFiles)
489
+ record({
490
+ kind: 'event',
491
+ event: 'audit-delete',
492
+ reason: `对话已删除,同步删除本会话审计日志(${removed} 条)`,
493
+ extra: { records: removed },
494
+ })
495
+ return { removed, remaining: state.count }
496
+ },
497
+ /** @returns {{ total: number, files: string[], sizeBytes: number }} */
498
+ stats() {
499
+ if (!enabled) return { total: 0, files: [], sizeBytes: 0 }
500
+ const files = listFiles(dir)
501
+ let sizeBytes = 0
502
+ for (const file of files) {
503
+ try {
504
+ sizeBytes += statSync(join(dir, file)).size
505
+ } catch {
506
+ // ignore a file rotated under us
507
+ }
508
+ }
509
+ return { total: state.count, files, sizeBytes }
510
+ },
511
+ /**
512
+ * @param {{ limit?: number }} [options]
513
+ * @returns {object[]} newest-last records
514
+ */
515
+ read(options = {}) {
516
+ const limit = Math.max(1, Math.min(Number(options.limit) || 50, 5000))
517
+ const records = readAllRecords(dir)
518
+ return records.slice(Math.max(0, records.length - limit))
519
+ },
520
+ /**
521
+ * Verify the whole chain.
522
+ * @returns {{ ok: boolean, entries: number, firstBad: object|null, reason: string|null }}
523
+ */
524
+ verify() {
525
+ const chain = verifyChain()
526
+ const anchor = verifyAnchor()
527
+ const anchorFails = anchor.enabled && (
528
+ ['bad-mac', 'mismatch', 'ahead', 'gap', 'corrupt', 'no-key'].includes(anchor.state)
529
+ || (anchor.state === 'missing' && chain.entries > 0)
530
+ )
531
+ return {
532
+ ...chain,
533
+ ok: chain.ok && !anchorFails,
534
+ reason: chain.reason ?? (anchorFails ? `审计锚点校验失败:${anchor.state}` : null),
535
+ anchor,
536
+ }
537
+ },
538
+ /** @param {{ limit?: number }} [options] */
539
+ exportJson(options = {}) {
540
+ const limit = Math.max(1, Math.min(Number(options.limit) || 2000, 20000))
541
+ return { schema: AUDIT_SCHEMA_VERSION, exportedAt: nowIso(), entries: readAllRecords(dir).slice(-limit) }
542
+ },
543
+ /** @param {{ limit?: number }} [options] */
544
+ exportCsv(options = {}) {
545
+ const limit = Math.max(1, Math.min(Number(options.limit) || 2000, 20000))
546
+ const rows = [
547
+ 'seq,ts,event,tool,session,decision,wouldBe,ruleIds,argDigest,argLength,reason',
548
+ ]
549
+ for (const entry of readAllRecords(dir).slice(-limit)) {
550
+ rows.push([
551
+ entry.seq,
552
+ entry.ts,
553
+ entry.event,
554
+ entry.tool,
555
+ entry.session,
556
+ entry.decision,
557
+ entry.wouldBe ?? '',
558
+ (entry.ruleIds || []).join('|'),
559
+ entry.args?.digest ?? '',
560
+ entry.args?.length ?? '',
561
+ entry.reason ?? '',
562
+ ].map(csvCell).join(','))
563
+ }
564
+ return rows.join('\n')
565
+ },
566
+ /** Verify only the HMAC anchor (cheap; used by vigil_doctor). */
567
+ anchorState() {
568
+ return verifyAnchor()
569
+ },
570
+ /** Human readable state line. */
571
+ describe() {
572
+ if (!enabled) return '审计日志:已禁用'
573
+ const stats = this.stats()
574
+ const anchor = anchorEnabled ? ';已锚定' : ''
575
+ return `审计日志:${stats.total} 条,${stats.files.length} 个文件,${formatBytes(stats.sizeBytes)},目录 ${dir}${anchor}`
576
+ },
577
+ }
578
+ }
579
+
580
+ /** @typedef {ReturnType<typeof createAuditLog>} AuditLog */
581
+
582
+ /**
583
+ * @param {string} value
584
+ * @returns {string}
585
+ */
586
+ function csvCell(value) {
587
+ const text = value === undefined || value === null ? '' : String(value)
588
+ return /[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text
589
+ }
590
+
591
+ /**
592
+ * @param {string} dir
593
+ * @returns {string[]} files ordered by chunk sequence
594
+ */
595
+ function listFiles(dir) {
596
+ try {
597
+ return readdirSync(dir)
598
+ .filter(name => FILE_PATTERN.test(name))
599
+ .sort()
600
+ } catch {
601
+ return []
602
+ }
603
+ }
604
+
605
+ /**
606
+ * @param {string} dir
607
+ * @param {number} chunk
608
+ * @returns {string}
609
+ */
610
+ function chunkFile(dir, chunk) {
611
+ return join(dir, `audit-${String(chunk).padStart(6, '0')}.jsonl`)
612
+ }
613
+
614
+ /**
615
+ * Append one line, rotating the current chunk when it would exceed `maxBytes`.
616
+ * @param {string} dir
617
+ * @param {number} chunk
618
+ * @param {string} line
619
+ * @param {number} maxBytes
620
+ * @param {number} maxFiles
621
+ */
622
+ function appendLine(dir, chunk, line, maxBytes, maxFiles) {
623
+ let target = chunkFile(dir, chunk)
624
+ const size = existsSync(target) ? statSync(target).size : 0
625
+ if (size > 0 && size + line.length + 1 > maxBytes) {
626
+ target = chunkFile(dir, chunk + 1)
627
+ pruneOldFiles(dir, maxFiles)
628
+ }
629
+ appendFileSync(target, `${line}\n`)
630
+ }
631
+
632
+ /**
633
+ * Keep only the newest `maxFiles` chunks.
634
+ * @param {string} dir
635
+ * @param {number} maxFiles
636
+ */
637
+ function pruneOldFiles(dir, maxFiles) {
638
+ const files = listFiles(dir)
639
+ while (files.length > maxFiles) {
640
+ const oldest = files.shift()
641
+ try {
642
+ unlinkSync(join(dir, /** @type {string} */ (oldest)))
643
+ } catch {
644
+ // someone else rotated it
645
+ }
646
+ }
647
+ }
648
+
649
+ /**
650
+ * Delete every chunk file of the chain.
651
+ * @param {string} dir
652
+ */
653
+ function clearChunks(dir) {
654
+ for (const file of listFiles(dir)) {
655
+ try {
656
+ unlinkSync(join(dir, file))
657
+ } catch {
658
+ // already gone
659
+ }
660
+ }
661
+ }
662
+
663
+ /**
664
+ * Archive directory for records detached from the active chain.
665
+ * @param {string} dir
666
+ * @returns {string}
667
+ */
668
+ function archiveDir(dir) {
669
+ return join(dir, 'archive')
670
+ }
671
+
672
+ /**
673
+ * @param {string} dir
674
+ * @returns {string[]}
675
+ */
676
+ function listArchiveFiles(dir) {
677
+ try {
678
+ return readdirSync(archiveDir(dir)).filter(name => name.endsWith('.jsonl')).sort()
679
+ } catch {
680
+ return []
681
+ }
682
+ }
683
+
684
+ /**
685
+ * Write detached records to one archive file; returns the path stored in the
686
+ * marker event (relative to the log directory).
687
+ * @param {string} dir
688
+ * @param {string} sessionId
689
+ * @param {object[]} records
690
+ * @returns {string|null}
691
+ */
692
+ function writeArchive(dir, sessionId, records) {
693
+ try {
694
+ ensureDir(archiveDir(dir))
695
+ const safe = sessionId.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 80)
696
+ const name = `${safe}-${nowIso().replace(/[:.]/g, '-')}.jsonl`
697
+ writeFileSync(join(archiveDir(dir), name), `${records.map(record => JSON.stringify(record)).join('\n')}\n`)
698
+ return `archive/${name}`
699
+ } catch {
700
+ return null
701
+ }
702
+ }
703
+
704
+ /**
705
+ * Re-append archived records into the active chain via `append`, then remove
706
+ * the archive file once everything was written.
707
+ * @param {string} dir
708
+ * @param {string} sessionId
709
+ * @param {(body: Record<string, any>) => unknown} append
710
+ * @returns {number}
711
+ */
712
+ function restoreArchived(dir, sessionId, append) {
713
+ const safe = sessionId.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 80)
714
+ let restored = 0
715
+ for (const name of listArchiveFiles(dir)) {
716
+ if (!name.startsWith(`${safe}-`)) continue
717
+ let raw = ''
718
+ try {
719
+ raw = readFileSync(join(archiveDir(dir), name), 'utf8')
720
+ } catch {
721
+ continue
722
+ }
723
+ let complete = true
724
+ for (const line of raw.split('\n')) {
725
+ if (line.trim() === '') continue
726
+ let parsed
727
+ try {
728
+ parsed = JSON.parse(line)
729
+ } catch {
730
+ complete = false
731
+ continue
732
+ }
733
+ if (append(parsed) === null) complete = false
734
+ else restored += 1
735
+ }
736
+ if (complete) {
737
+ try {
738
+ unlinkSync(join(archiveDir(dir), name))
739
+ } catch {
740
+ // already gone
741
+ }
742
+ }
743
+ }
744
+ return restored
745
+ }
746
+
747
+ /**
748
+ * Rewrite surviving records into one new valid chain (fresh seq/prev/hash).
749
+ * Used by session-scoped cleanup so the chain stays verifiable afterwards.
750
+ * @param {string} dir
751
+ * @param {object[]} records
752
+ */
753
+ function rewriteChain(dir, records) {
754
+ let previousHash = ''
755
+ let seq = 0
756
+ const lines = []
757
+ for (const entry of records) {
758
+ const { hash: _ignored, ...body } = /** @type {any} */ (entry)
759
+ seq += 1
760
+ body.seq = seq
761
+ body.prev = previousHash
762
+ const hash = sha256(`${previousHash}\n${stableStringify(body)}`)
763
+ lines.push(JSON.stringify({ ...body, hash }))
764
+ previousHash = hash
765
+ }
766
+ const temp = join(dir, 'audit-000001.jsonl.tmp')
767
+ writeFileSync(temp, lines.length > 0 ? `${lines.join('\n')}\n` : '')
768
+ clearChunks(dir)
769
+ renameSync(temp, join(dir, 'audit-000001.jsonl'))
770
+ persistState(dir, { seq, lastHash: previousHash, count: seq, updatedAt: nowIso() })
771
+ }
772
+
773
+ /**
774
+ * Recover the chain head from `state.json`, falling back to the last line of the
775
+ * newest chunk when the state file is missing or stale.
776
+ * @param {string} dir
777
+ * @param {number} maxFiles
778
+ * @returns {{ seq: number, lastHash: string, count: number, updatedAt: string }}
779
+ */
780
+ function recoverState(dir, maxFiles) {
781
+ let persisted = readJson(join(dir, STATE_FILE))
782
+ if (!persisted || typeof persisted !== 'object') {
783
+ persisted = { seq: 0, lastHash: '', count: 0, updatedAt: '' }
784
+ }
785
+ const files = listFiles(dir)
786
+ if (files.length > 0) {
787
+ const lastFile = /** @type {string} */ (files[files.length - 1])
788
+ let raw = ''
789
+ try {
790
+ raw = readFileSync(join(dir, lastFile), 'utf8')
791
+ } catch {
792
+ raw = ''
793
+ }
794
+ const lines = raw.split('\n').filter(line => line.trim() !== '')
795
+ const lastLine = lines.length > 0 ? lines[lines.length - 1] : ''
796
+ if (lastLine !== '') {
797
+ try {
798
+ const last = JSON.parse(lastLine)
799
+ if (Number.isFinite(last.seq) && typeof last.hash === 'string' && last.seq > persisted.seq) {
800
+ persisted = { seq: last.seq, lastHash: last.hash, count: Math.max(persisted.count || 0, last.seq), updatedAt: last.ts || '' }
801
+ }
802
+ } catch {
803
+ // keep the persisted state; verification will report the bad tail
804
+ }
805
+ }
806
+ }
807
+ pruneOldFiles(dir, maxFiles)
808
+ return persisted
809
+ }
810
+
811
+ /**
812
+ * @param {string} dir
813
+ * @param {object} state
814
+ */
815
+ function persistState(dir, state) {
816
+ try {
817
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
818
+ atomicWriteJson(join(dir, STATE_FILE), state)
819
+ } catch {
820
+ // The chain head is also recoverable from the last JSON line, so a failed
821
+ // state write degrades performance, not integrity.
822
+ }
823
+ }
824
+
825
+ /**
826
+ * Read every record in append order.
827
+ * @param {string} dir
828
+ * @returns {object[]}
829
+ */
830
+ function readAllRecords(dir) {
831
+ /** @type {object[]} */
832
+ const records = []
833
+ for (const file of listFiles(dir)) {
834
+ let raw = ''
835
+ try {
836
+ raw = readFileSync(join(dir, file), 'utf8')
837
+ } catch {
838
+ continue
839
+ }
840
+ for (const line of raw.split('\n')) {
841
+ if (line.trim() === '') continue
842
+ try {
843
+ records.push(JSON.parse(line))
844
+ } catch {
845
+ // A torn tail line is possible after a crash; verification reports it.
846
+ }
847
+ }
848
+ }
849
+ return records
850
+ }
851
+
852
+ /**
853
+ * Export helper used by the `vigil_audit` tool.
854
+ * @param {AuditLog} log
855
+ * @param {'json'|'csv'|'verify'|'tail'} action
856
+ * @param {{ limit?: number }} [options]
857
+ * @returns {unknown}
858
+ */
859
+ export function runAuditAction(log, action, options = {}) {
860
+ switch (action) {
861
+ case 'verify':
862
+ return log.verify()
863
+ case 'json':
864
+ return log.exportJson(options)
865
+ case 'csv':
866
+ return log.exportCsv(options)
867
+ case 'tail':
868
+ default:
869
+ return { entries: log.read(options), describe: log.describe() }
870
+ }
871
+ }
872
+
873
+ /**
874
+ * Rename a chunk file aside (used by tests and by manual recovery).
875
+ * @param {string} dir
876
+ * @param {string} name
877
+ * @param {string} suffix
878
+ * @returns {boolean}
879
+ */
880
+ export function renameChunk(dir, name, suffix) {
881
+ try {
882
+ renameSync(join(dir, name), join(dir, `${name}.${suffix}`))
883
+ return true
884
+ } catch {
885
+ return false
886
+ }
887
+ }