advisers 0.2.2 → 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.
Files changed (70) hide show
  1. package/LICENSE +0 -0
  2. package/NOTICE +0 -0
  3. package/README-zh.md +11 -7
  4. package/README.md +16 -8
  5. package/THIRD-PARTY-NOTICES.md +1 -1
  6. package/bin/advisers.js +6347 -542
  7. package/index.js +1 -1
  8. package/lib/agent.js +529 -80
  9. package/lib/attachments.js +0 -0
  10. package/lib/audit-anchor.js +683 -0
  11. package/lib/backup.js +1345 -0
  12. package/lib/capture.js +0 -0
  13. package/lib/context-window.js +0 -0
  14. package/lib/digest.js +0 -0
  15. package/lib/doc-review.js +0 -0
  16. package/lib/egress.js +0 -0
  17. package/lib/error-codes.js +1373 -0
  18. package/lib/evidence.js +352 -43
  19. package/lib/fs-safe.js +347 -0
  20. package/lib/ical.js +0 -0
  21. package/lib/imap.js +6 -2
  22. package/lib/importers.js +0 -0
  23. package/lib/learning.js +0 -0
  24. package/lib/ledger-read.js +608 -0
  25. package/lib/mcp-server.js +331 -50
  26. package/lib/model.js +73 -1
  27. package/lib/node-warning-filter.js +15 -0
  28. package/lib/notify.js +13 -3
  29. package/lib/nudge.js +0 -0
  30. package/lib/ocr.js +29 -9
  31. package/lib/pdf.js +0 -0
  32. package/lib/pet-brief-store.js +0 -0
  33. package/lib/pet-brief.js +126 -64
  34. package/lib/receipt-verify.js +213 -15
  35. package/lib/relative-date.js +0 -0
  36. package/lib/remind.js +91 -36
  37. package/lib/research.js +0 -0
  38. package/lib/review.js +0 -0
  39. package/lib/routine.js +0 -0
  40. package/lib/safety/classifier.js +55 -2
  41. package/lib/safety/explain.js +0 -0
  42. package/lib/safety/index.js +0 -0
  43. package/lib/safety/redact.js +0 -0
  44. package/lib/safety/rules.js +28 -0
  45. package/lib/scheduler.js +0 -0
  46. package/lib/source.js +0 -0
  47. package/lib/sqlite.js +2302 -55
  48. package/lib/sync.js +398 -71
  49. package/lib/text-safe.js +229 -0
  50. package/lib/timestamp.js +29 -9
  51. package/lib/tos/index.js +1 -1
  52. package/lib/tos/manifest.json +6 -6
  53. package/lib/tos/privacy.zh-CN.md +12 -9
  54. package/lib/tos/safety.zh-CN.md +4 -3
  55. package/lib/tos/summary.zh-CN.md +3 -3
  56. package/lib/tos/terms.zh-CN.md +8 -6
  57. package/lib/tui/color.js +164 -0
  58. package/lib/tui/index.js +33 -0
  59. package/lib/tui/json.js +124 -0
  60. package/lib/tui/labels.js +50 -0
  61. package/lib/tui/policy.js +108 -0
  62. package/lib/tui/render.js +371 -0
  63. package/lib/tui/sanitize.js +142 -0
  64. package/lib/tui/text-file.js +116 -0
  65. package/lib/tui/width.js +577 -0
  66. package/lib/ui.js +0 -0
  67. package/lib/undo.js +0 -0
  68. package/lib/untrusted.js +186 -0
  69. package/lib/vault.js +0 -0
  70. package/package.json +6 -5
File without changes
@@ -0,0 +1,683 @@
1
+ /**
2
+ * Audit tail anchor (Advisers 0.3.0 operations library).
3
+ *
4
+ * The audit table is a hash/MAC chain: every row commits to the previous row's
5
+ * hash, so editing or deleting a row in the middle makes verifyAudit() fail.
6
+ * A *tail* deletion is different: the remaining rows still form a valid chain.
7
+ * This module records a checkpoint that makes a later tail deletion detectable:
8
+ *
9
+ * $ADVISERS_HOME/audit-anchor.json
10
+ * {
11
+ * "format": "advisers-audit-anchor",
12
+ * "version": 1,
13
+ * "dbId": "sha256:...",
14
+ * "count": 1234,
15
+ * "lastSeq": 1234,
16
+ * "headHash": "<64 hex>",
17
+ * "createdAt": "2026-11-19T05:00:00.000Z",
18
+ * "generator": "advisers/0.3.0",
19
+ * "keyed": true,
20
+ * "hmac": "<64 hex|null>"
21
+ * }
22
+ *
23
+ * Detection semantics (deliberately narrow and honest, 04-0.3-research §4.7):
24
+ * - current count < anchor count -> E_AUDIT_TAIL_TRUNCATED (tail deleted or DB
25
+ * rolled back to an older snapshot);
26
+ * - current count == anchor count but the head hash differs ->
27
+ * E_AUDIT_HEAD_MISMATCH (last row rewritten, or delete+append);
28
+ * - current count > anchor count -> ok, status 'grown', caller should anchor
29
+ * again;
30
+ * - no anchor -> E_AUDIT_ANCHOR_ABSENT: a yellow state, not proof of
31
+ * tampering (no baseline was recorded).
32
+ *
33
+ * A local HMAC anchor reduces deniability for accidental edits and casual
34
+ * tampering. It is NOT third-party attestation: the same user who can edit the
35
+ * database can rewrite the anchor, and audit.key is readable by that user.
36
+ * Documentation must never call it tamper-proof / notarised / compliance-grade.
37
+ *
38
+ * The module never repairs, truncates or re-writes the audit chain. It refuses
39
+ * to write an anchor for a broken chain (E_AUDIT_CHAIN_BROKEN) so a bad state is
40
+ * never recorded as a good baseline. Library-only: no bin/ wiring (Wave 2), no
41
+ * network, no new dependency.
42
+ */
43
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto'
44
+ import { existsSync, readFileSync, statSync } from 'node:fs'
45
+ import { join } from 'node:path'
46
+ import { atomicWriteFileSync } from './fs-safe.js'
47
+
48
+ export const AUDIT_ANCHOR_FORMAT = 'advisers-audit-anchor'
49
+ export const AUDIT_ANCHOR_VERSION = 1
50
+ export const AUDIT_ANCHOR_FILE = 'audit-anchor.json'
51
+ export const AUDIT_ANCHOR_MAX_BYTES = 64 * 1024
52
+ export const AUDIT_ANCHOR_KEY_ENV = 'ADVISERS_AUDIT_KEY'
53
+ export const AUDIT_KEY_FILE_NAME = 'audit.key'
54
+ export const AUDIT_MIN_KEY_CHARS = 16
55
+
56
+ const HEX64_RE = /^[0-9a-f]{64}$/
57
+ const DB_ID_RE = /^sha256:[0-9a-f]{64}$/
58
+ const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/
59
+ /** Cheap count fallback cap for store-like objects without a raw db handle. */
60
+ const LIST_FALLBACK_MAX = 10000
61
+
62
+ function sha256Hex(value) {
63
+ return createHash('sha256').update(value).digest('hex')
64
+ }
65
+
66
+ function isPlainObject(value) {
67
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
68
+ }
69
+
70
+ function isNonNegativeInteger(value) {
71
+ return Number.isInteger(value) && value >= 0
72
+ }
73
+
74
+ function isHex64(value) {
75
+ return typeof value === 'string' && HEX64_RE.test(value)
76
+ }
77
+
78
+ function isIsoDate(value) {
79
+ if (typeof value !== 'string' || !ISO_DATE_RE.test(value)) return false
80
+ const date = new Date(value)
81
+ return !Number.isNaN(date.getTime()) && date.toISOString() === value
82
+ }
83
+
84
+ /**
85
+ * Stable database identity for anchor cross-checks.
86
+ *
87
+ * Derived from the genesis audit row hash, so every backup/restore of the same
88
+ * ledger shares it, while an anchor copied from a different database does not
89
+ * verify. When the audit is still empty there is no genesis row, hence the
90
+ * 'empty' sentinel; merging logic treats an anchor written at count 0 as
91
+ * compatible with any later non-empty state (its count comparison still holds).
92
+ */
93
+ export function computeAuditDbId(genesisHash) {
94
+ const seed = typeof genesisHash === 'string' && genesisHash ? genesisHash : 'empty'
95
+ return 'sha256:' + sha256Hex('advisers-audit-db\n' + seed)
96
+ }
97
+
98
+ /** Deterministic canonical payload covered by the anchor HMAC (hmac excluded). */
99
+ export function canonicalAuditAnchorPayload(anchor) {
100
+ const payload = {}
101
+ for (const key of Object.keys(anchor).sort()) {
102
+ if (key === 'hmac') continue
103
+ payload[key] = anchor[key]
104
+ }
105
+ return JSON.stringify(payload)
106
+ }
107
+
108
+ /** HMAC-SHA256(anchorKey, canonical anchor fields); null when no key is used. */
109
+ export function computeAuditAnchorHmac(anchor, key) {
110
+ if (typeof key !== 'string' || key.length === 0) return null
111
+ return createHmac('sha256', key).update(canonicalAuditAnchorPayload(anchor)).digest('hex')
112
+ }
113
+
114
+ function hmacMatches(anchor, key) {
115
+ const expected = computeAuditAnchorHmac(anchor, key)
116
+ if (typeof expected !== 'string' || typeof anchor?.hmac !== 'string') return false
117
+ const left = Buffer.from(expected, 'hex')
118
+ const right = Buffer.from(anchor.hmac, 'hex')
119
+ if (left.length === 0 || left.length !== right.length) return false
120
+ try { return timingSafeEqual(left, right) } catch { return false }
121
+ }
122
+
123
+ /** Raw DatabaseSync behind a SqliteStore, when the store exposes it. */
124
+ function rawDbOf(store) {
125
+ const db = store?.db
126
+ return db && typeof db.prepare === 'function' ? db : null
127
+ }
128
+
129
+ function readRow(db, sql, ...params) {
130
+ try { return db.prepare(sql).get(...params) ?? null } catch { return null }
131
+ }
132
+
133
+ /**
134
+ * Read the audit tail (count / lastSeq / headHash / genesisHash / dbId).
135
+ *
136
+ * @param {object} store SqliteStore (writable or read-only).
137
+ * @param {{verifyChain?: boolean, listFallbackMax?: number}} [options]
138
+ * verifyChain=true re-verifies the whole chain first and refuses to produce a
139
+ * head for a broken chain (default for 'audit --write-anchor'). Callers that
140
+ * already verified the chain (or cannot afford the O(n) pass for a backup
141
+ * sidecar) pass verifyChain=false: then only the last row is trusted for
142
+ * anchoring, and `chainVerified` stays false.
143
+ * @returns {{ok: boolean, code: string|null, count: number|null, lastSeq: number|null,
144
+ * headHash: string, genesisHash: string|null, dbId: string|null,
145
+ * chainVerified: boolean, brokenAt: number|null, errors: string[]}}
146
+ */
147
+ export function readAuditHead(store, { verifyChain = true, listFallbackMax = LIST_FALLBACK_MAX } = {}) {
148
+ const result = {
149
+ ok: false,
150
+ code: null,
151
+ count: null,
152
+ lastSeq: null,
153
+ headHash: '',
154
+ genesisHash: null,
155
+ dbId: null,
156
+ chainVerified: false,
157
+ brokenAt: null,
158
+ errors: [],
159
+ }
160
+ if (!store || typeof store.listAudit !== 'function') {
161
+ result.code = 'E_AUDIT_ANCHOR_STORE'
162
+ result.errors.push('readAuditHead requires a SqliteStore-like object with listAudit()/verifyAudit()')
163
+ return result
164
+ }
165
+ const db = rawDbOf(store)
166
+ let count = null
167
+ if (verifyChain) {
168
+ if (typeof store.verifyAudit !== 'function') {
169
+ result.code = 'E_AUDIT_ANCHOR_STORE'
170
+ result.errors.push('readAuditHead(verifyChain=true) requires store.verifyAudit()')
171
+ return result
172
+ }
173
+ let verify
174
+ try { verify = store.verifyAudit() } catch (error) {
175
+ result.code = 'E_AUDIT_CHAIN_BROKEN'
176
+ result.errors.push('cannot verify the audit chain: ' + String(error?.message ?? error).slice(0, 200))
177
+ return result
178
+ }
179
+ if (!verify || verify.ok !== true) {
180
+ result.code = 'E_AUDIT_CHAIN_BROKEN'
181
+ result.brokenAt = Number.isInteger(verify?.seq) ? verify.seq : null
182
+ result.errors.push('audit chain is broken' + (result.brokenAt === null ? '' : ' at seq ' + result.brokenAt) + '; refusing to anchor a broken chain')
183
+ return result
184
+ }
185
+ count = Number.isInteger(verify.count) ? verify.count : null
186
+ result.chainVerified = true
187
+ }
188
+ if (count === null) {
189
+ if (db) {
190
+ const row = readRow(db, 'SELECT COUNT(*) AS n FROM audit')
191
+ if (row && Number.isInteger(Number(row.n))) count = Number(row.n)
192
+ } else if (typeof store.verifyAudit === 'function') {
193
+ const verify = store.verifyAudit()
194
+ if (verify?.ok === true && Number.isInteger(verify.count)) {
195
+ count = verify.count
196
+ result.chainVerified = true
197
+ } else {
198
+ result.code = 'E_AUDIT_CHAIN_BROKEN'
199
+ result.brokenAt = Number.isInteger(verify?.seq) ? verify.seq : null
200
+ result.errors.push('audit chain is broken; refusing to anchor a broken chain')
201
+ return result
202
+ }
203
+ }
204
+ }
205
+ if (count === null) {
206
+ result.code = 'E_AUDIT_CHAIN_BROKEN'
207
+ result.errors.push('cannot determine the number of audit rows; refusing to anchor')
208
+ return result
209
+ }
210
+ result.count = count
211
+ let tail = null
212
+ if (db) {
213
+ const row = readRow(db, 'SELECT seq, hash FROM audit ORDER BY seq DESC LIMIT 1')
214
+ if (row) tail = { seq: Number(row.seq), hash: String(row.hash ?? '') }
215
+ } else {
216
+ try { tail = store.listAudit(1)[0] ?? null } catch { tail = null }
217
+ }
218
+ if (count > 0) {
219
+ if (!tail || !isHex64(tail.hash)) {
220
+ result.code = 'E_AUDIT_HEAD_INVALID'
221
+ result.errors.push('cannot read a valid last audit row hash; refusing to anchor')
222
+ return result
223
+ }
224
+ result.lastSeq = tail.seq
225
+ result.headHash = tail.hash
226
+ } else {
227
+ result.lastSeq = 0
228
+ result.headHash = ''
229
+ }
230
+ if (db) {
231
+ const genesis = readRow(db, 'SELECT hash FROM audit ORDER BY seq ASC LIMIT 1')
232
+ if (genesis && isHex64(String(genesis.hash ?? ''))) result.genesisHash = String(genesis.hash)
233
+ } else if (count > 0 && count <= listFallbackMax) {
234
+ try {
235
+ const rows = store.listAudit(count)
236
+ const oldest = rows[rows.length - 1]
237
+ if (oldest && isHex64(String(oldest.hash ?? ''))) result.genesisHash = String(oldest.hash)
238
+ } catch {}
239
+ }
240
+ result.dbId = computeAuditDbId(result.genesisHash)
241
+ result.ok = true
242
+ return result
243
+ }
244
+
245
+ /**
246
+ * Build an anchor object from a head snapshot. Pure: no filesystem, no DB.
247
+ *
248
+ * `key` is the audit HMAC key (usually $ADVISERS_HOME/audit.key loaded by
249
+ * bin/). With no key the anchor is written unkeyed (hmac:null, keyed:false) and
250
+ * verification reports a warning: a same-user attacker can then edit the anchor
251
+ * too, which is an honest limitation rather than a silent claim.
252
+ */
253
+ export function buildAuditAnchor({ head, key = null, generator = 'advisers', createdAt = new Date().toISOString(), dbId } = {}) {
254
+ if (!isPlainObject(head) || !isNonNegativeInteger(head.count)) {
255
+ throw new TypeError('buildAuditAnchor requires a head object with a non-negative integer count')
256
+ }
257
+ const resolvedDbId = typeof dbId === 'string' && DB_ID_RE.test(dbId)
258
+ ? dbId
259
+ : (typeof head.dbId === 'string' && DB_ID_RE.test(head.dbId)
260
+ ? head.dbId
261
+ : computeAuditDbId(head.genesisHash))
262
+ const anchor = {
263
+ format: AUDIT_ANCHOR_FORMAT,
264
+ version: AUDIT_ANCHOR_VERSION,
265
+ dbId: resolvedDbId,
266
+ count: head.count,
267
+ lastSeq: isNonNegativeInteger(head.lastSeq) ? head.lastSeq : head.count,
268
+ headHash: typeof head.headHash === 'string' ? head.headHash : '',
269
+ createdAt,
270
+ generator: typeof generator === 'string' && generator ? generator : 'advisers',
271
+ keyed: typeof key === 'string' && key.length > 0,
272
+ hmac: null,
273
+ }
274
+ if (anchor.count > 0 && !isHex64(anchor.headHash)) {
275
+ throw new TypeError('buildAuditAnchor requires a 64-hex headHash when count > 0')
276
+ }
277
+ if (!isIsoDate(anchor.createdAt)) throw new TypeError('buildAuditAnchor createdAt must be an ISO-8601 UTC timestamp')
278
+ anchor.hmac = computeAuditAnchorHmac(anchor, anchor.keyed ? key : null)
279
+ return anchor
280
+ }
281
+
282
+ /** Shape/schema validation for an anchor parsed from disk or JSON. */
283
+ export function validateAuditAnchor(anchor) {
284
+ const errors = []
285
+ if (!isPlainObject(anchor)) return { ok: false, errors: ['audit anchor must be a JSON object'] }
286
+ if (anchor.format !== AUDIT_ANCHOR_FORMAT) errors.push('anchor.format must be ' + AUDIT_ANCHOR_FORMAT)
287
+ if (anchor.version !== AUDIT_ANCHOR_VERSION) errors.push('anchor.version must be ' + AUDIT_ANCHOR_VERSION)
288
+ if (typeof anchor.dbId !== 'string' || !DB_ID_RE.test(anchor.dbId)) errors.push('anchor.dbId must be sha256:<64 lowercase hex>')
289
+ if (!isNonNegativeInteger(anchor.count)) errors.push('anchor.count must be a non-negative integer')
290
+ if (!isNonNegativeInteger(anchor.lastSeq)) errors.push('anchor.lastSeq must be a non-negative integer')
291
+ if (anchor.count === 0) {
292
+ if (anchor.headHash !== '') errors.push('anchor.headHash must be an empty string when count is 0')
293
+ } else if (!isHex64(anchor.headHash)) {
294
+ errors.push('anchor.headHash must be 64 lowercase hex characters')
295
+ }
296
+ if (typeof anchor.createdAt !== 'string' || !isIsoDate(anchor.createdAt)) errors.push('anchor.createdAt must be an ISO-8601 UTC timestamp')
297
+ if (typeof anchor.generator !== 'string' || !anchor.generator) errors.push('anchor.generator must be a non-empty string')
298
+ if (typeof anchor.keyed !== 'boolean') errors.push('anchor.keyed must be a boolean')
299
+ if (typeof anchor.keyed === 'boolean') {
300
+ if (anchor.keyed) {
301
+ if (!isHex64(anchor.hmac)) errors.push('anchor.hmac must be 64 lowercase hex characters when keyed is true')
302
+ } else if (anchor.hmac !== null) {
303
+ errors.push('anchor.hmac must be null when keyed is false')
304
+ }
305
+ }
306
+ return { ok: errors.length === 0, errors }
307
+ }
308
+
309
+ /**
310
+ * Resolve the HMAC key for anchor reads/writes.
311
+ *
312
+ * Precedence: explicit `key` option (undefined means 'not given', null means
313
+ * 'explicitly unkeyed'), then $ADVISERS_AUDIT_KEY, then $ADVISERS_HOME/audit.key
314
+ * (the file bin/ creates with mode 0600). Never throws: a missing key yields
315
+ * {key:null} so the caller can choose an unkeyed anchor with a warning.
316
+ */
317
+ export function resolveAuditAnchorKey({ home, key, env = process.env } = {}) {
318
+ if (key !== undefined) {
319
+ const value = typeof key === 'string' && key.length > 0 ? key : null
320
+ return { key: value, source: value ? 'argument' : 'argument-none' }
321
+ }
322
+ const fromEnv = env?.[AUDIT_ANCHOR_KEY_ENV]
323
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return { key: fromEnv, source: 'env' }
324
+ if (home) {
325
+ const file = join(home, AUDIT_KEY_FILE_NAME)
326
+ try {
327
+ if (existsSync(file)) {
328
+ const value = readFileSync(file, 'utf8').trim()
329
+ if (value.length > 0) return { key: value, source: 'file', path: file }
330
+ }
331
+ } catch (error) {
332
+ return { key: null, source: 'file-unreadable', path: file, warning: 'cannot read ' + file + ': ' + String(error?.message ?? error).slice(0, 160) }
333
+ }
334
+ }
335
+ return { key: null, source: 'none' }
336
+ }
337
+
338
+ /** Read and validate the anchor file. Missing file is {ok:true, found:false}. */
339
+ export function readAuditAnchor({ home, file, maxBytes = AUDIT_ANCHOR_MAX_BYTES, fs } = {}) {
340
+ const target = file ?? (home ? join(home, AUDIT_ANCHOR_FILE) : null)
341
+ const result = { ok: false, found: false, code: null, path: target, anchor: null, errors: [], warnings: [] }
342
+ if (!target) {
343
+ result.code = 'E_AUDIT_ANCHOR_PATH'
344
+ result.errors.push('readAuditAnchor requires {home} or {file}')
345
+ return result
346
+ }
347
+ const stat = fs?.statSync ?? statSync
348
+ const read = fs?.readFileSync ?? readFileSync
349
+ let info
350
+ try {
351
+ info = stat(target)
352
+ } catch (error) {
353
+ if (error?.code === 'ENOENT') { result.ok = true; result.found = false; return result }
354
+ result.code = 'E_AUDIT_ANCHOR_UNREADABLE'
355
+ result.errors.push('cannot stat ' + target + ': ' + String(error?.code ?? error?.message ?? error))
356
+ return result
357
+ }
358
+ result.found = true
359
+ if (!info.isFile()) {
360
+ result.code = 'E_AUDIT_ANCHOR_INVALID'
361
+ result.errors.push('audit anchor path is not a regular file: ' + target)
362
+ return result
363
+ }
364
+ if (Number.isFinite(maxBytes) && info.size > maxBytes) {
365
+ result.code = 'E_AUDIT_ANCHOR_TOO_LARGE'
366
+ result.errors.push('audit anchor is ' + info.size + ' bytes, over the ' + maxBytes + ' byte limit')
367
+ return result
368
+ }
369
+ let text
370
+ try { text = read(target, 'utf8') } catch (error) {
371
+ result.code = 'E_AUDIT_ANCHOR_UNREADABLE'
372
+ result.errors.push('cannot read ' + target + ': ' + String(error?.code ?? error?.message ?? error))
373
+ return result
374
+ }
375
+ let parsed
376
+ try { parsed = JSON.parse(text) } catch (error) {
377
+ result.code = 'E_AUDIT_ANCHOR_INVALID'
378
+ result.errors.push('audit anchor is not valid JSON: ' + String(error?.message ?? error).slice(0, 200))
379
+ return result
380
+ }
381
+ const shape = validateAuditAnchor(parsed)
382
+ if (!shape.ok) {
383
+ result.code = 'E_AUDIT_ANCHOR_INVALID'
384
+ for (const error of shape.errors) result.errors.push('schema: ' + error)
385
+ return result
386
+ }
387
+ result.ok = true
388
+ result.anchor = parsed
389
+ if (!parsed.keyed) result.warnings.push('audit anchor is not keyed (keyed:false): it cannot detect a same-user attacker who rewrites both the database and the anchor')
390
+ return result
391
+ }
392
+
393
+ /**
394
+ * Compare a live audit head against a recorded anchor (normal 'audit' path).
395
+ *
396
+ * allowBehind is for explicit time-travel/restore checks only; for a live
397
+ * database a count below the anchor is a tail truncation. Returns a structured
398
+ * result instead of throwing so bin/ can print yellow vs red and choose an exit
399
+ * code.
400
+ */
401
+ export function verifyAuditAnchor({ anchor, head, key, allowBehind = false } = {}) {
402
+ const result = {
403
+ ok: false,
404
+ status: 'invalid',
405
+ code: null,
406
+ keyed: Boolean(anchor?.keyed),
407
+ hmacVerified: false,
408
+ count: isNonNegativeInteger(head?.count) ? head.count : null,
409
+ anchorCount: isNonNegativeInteger(anchor?.count) ? anchor.count : null,
410
+ headHash: typeof head?.headHash === 'string' ? head.headHash : null,
411
+ anchorHeadHash: typeof anchor?.headHash === 'string' ? anchor.headHash : null,
412
+ lastSeq: isNonNegativeInteger(head?.lastSeq) ? head.lastSeq : null,
413
+ anchorLastSeq: isNonNegativeInteger(anchor?.lastSeq) ? anchor.lastSeq : null,
414
+ dbId: typeof head?.dbId === 'string' ? head.dbId : null,
415
+ anchorDbId: typeof anchor?.dbId === 'string' ? anchor.dbId : null,
416
+ needsReanchor: false,
417
+ errors: [],
418
+ warnings: [],
419
+ }
420
+ const shape = validateAuditAnchor(anchor)
421
+ if (!shape.ok) {
422
+ result.code = 'E_AUDIT_ANCHOR_INVALID'
423
+ for (const error of shape.errors) result.errors.push(error)
424
+ return result
425
+ }
426
+ if (!isPlainObject(head) || !isNonNegativeInteger(head.count)) {
427
+ result.code = 'E_AUDIT_ANCHOR_HEAD_INVALID'
428
+ result.errors.push('verifyAuditAnchor requires a head with a non-negative integer count (see readAuditHead)')
429
+ return result
430
+ }
431
+ if (anchor.keyed) {
432
+ if (typeof key !== 'string' || key.length === 0) {
433
+ result.code = 'E_AUDIT_ANCHOR_KEY_MISSING'
434
+ result.errors.push('the anchor is HMAC-keyed but no audit key is available; set ' + AUDIT_ANCHOR_KEY_ENV + ' or restore ' + AUDIT_KEY_FILE_NAME)
435
+ return result
436
+ }
437
+ if (!hmacMatches(anchor, key)) {
438
+ result.code = 'E_AUDIT_ANCHOR_HMAC_MISMATCH'
439
+ result.errors.push('audit anchor HMAC does not match: the anchor was edited, or it was written with a different audit key')
440
+ return result
441
+ }
442
+ result.hmacVerified = true
443
+ } else {
444
+ result.warnings.push('audit anchor is unkeyed: a same-user attacker can edit the database and the anchor together')
445
+ }
446
+ // dbId only identifies the ledger once a genesis row exists on both sides;
447
+ // an anchor written on an empty audit is compatible with later growth.
448
+ if (anchor.count > 0 && head.count > 0 && typeof head.dbId === 'string' && head.dbId !== anchor.dbId) {
449
+ result.code = 'E_AUDIT_ANCHOR_DB_MISMATCH'
450
+ result.errors.push('the anchor belongs to a different database (dbId mismatch); it cannot certify this ledger')
451
+ return result
452
+ }
453
+ if (head.count < anchor.count) {
454
+ if (!allowBehind) {
455
+ result.code = 'E_AUDIT_TAIL_TRUNCATED'
456
+ result.errors.push('audit has ' + head.count + ' rows but the anchor recorded ' + anchor.count + ': the audit tail was deleted or the database was rolled back to an older copy')
457
+ return result
458
+ }
459
+ result.ok = true
460
+ result.status = 'behind'
461
+ result.warnings.push('current audit is older than the anchor (' + head.count + ' < ' + anchor.count + ' rows); time-travel was explicitly allowed')
462
+ return result
463
+ }
464
+ if (head.count === anchor.count) {
465
+ if (head.headHash !== anchor.headHash || head.lastSeq !== anchor.lastSeq) {
466
+ result.code = 'E_AUDIT_HEAD_MISMATCH'
467
+ result.errors.push('audit count matches the anchor (' + anchor.count + ') but the head hash/seq does not: the last row was rewritten (or deleted and re-appended)')
468
+ return result
469
+ }
470
+ result.ok = true
471
+ result.status = 'match'
472
+ return result
473
+ }
474
+ if (typeof head.lastSeq === 'number' && head.lastSeq < anchor.lastSeq) {
475
+ result.code = 'E_AUDIT_TAIL_TRUNCATED'
476
+ result.errors.push('audit last seq ' + head.lastSeq + ' is behind the anchor lastSeq ' + anchor.lastSeq + ': the tail was deleted')
477
+ return result
478
+ }
479
+ result.ok = true
480
+ result.status = 'grown'
481
+ result.needsReanchor = true
482
+ result.warnings.push('audit grew from ' + anchor.count + ' to ' + head.count + ' rows since the anchor; write a fresh anchor (for example `advisers audit --write-anchor`)')
483
+ return result
484
+ }
485
+
486
+ /**
487
+ * Compare a backup's audit head against the current anchor (restore path).
488
+ *
489
+ * Direction is inverted compared to a live database: a backup OLDER than the
490
+ * anchor is legitimate time travel, so it is reported as 'behind' and accepted
491
+ * only when the caller explicitly passes allowAnchorBehind (bin:
492
+ * `restore --allow-anchor-behind`). A backup NEWER than the anchor is normal
493
+ * (the anchor was simply not refreshed); status 'ahead'.
494
+ */
495
+ export function verifyRestoreAnchor({ anchor, head, key, allowAnchorBehind = false } = {}) {
496
+ const result = verifyAuditAnchor({ anchor, head, key, allowBehind: true })
497
+ if (!result.ok) return result
498
+ if (head.count < anchor.count) {
499
+ if (!allowAnchorBehind) {
500
+ result.ok = false
501
+ result.status = 'behind'
502
+ result.code = 'E_AUDIT_ANCHOR_BEHIND'
503
+ result.errors.push('the backup is older than the audit anchor (' + head.count + ' < ' + anchor.count + ' rows); pass allowAnchorBehind / `restore --allow-anchor-behind` only if this time-travel is intended')
504
+ return result
505
+ }
506
+ result.status = 'behind'
507
+ result.warnings.push('restoring a backup older than the audit anchor was explicitly allowed; the restored ledger will look like a rollback until a fresh anchor is written')
508
+ return result
509
+ }
510
+ if (head.count === anchor.count) {
511
+ result.status = 'match'
512
+ return result
513
+ }
514
+ result.status = 'ahead'
515
+ result.warnings.push('the backup has more audit rows than the anchor (' + head.count + ' > ' + anchor.count + '); the anchor is stale, which is normal if audit writes happened after the anchor')
516
+ return result
517
+ }
518
+
519
+ /**
520
+ * Read the anchor (if any) and compare it with the live audit head.
521
+ * Returns {ok:false, code:'E_AUDIT_ANCHOR_ABSENT', status:'absent'} when no
522
+ * anchor exists: callers report that as yellow, not as a broken chain.
523
+ */
524
+ export function verifyAuditAgainstAnchor({ home, file, store, head, key, env, allowBehind = false, verifyChain = true } = {}) {
525
+ const target = file ?? (home ? join(home, AUDIT_ANCHOR_FILE) : null)
526
+ const read = readAuditAnchor({ file: target })
527
+ if (!read.found) {
528
+ return {
529
+ ok: false, found: false, status: 'absent', code: 'E_AUDIT_ANCHOR_ABSENT', path: target,
530
+ anchor: null, head: null, keySource: null,
531
+ errors: ['no audit anchor has been recorded yet; run `advisers audit --write-anchor` to create a baseline'],
532
+ warnings: [],
533
+ }
534
+ }
535
+ if (!read.ok) {
536
+ return { ok: false, found: true, status: 'invalid', code: read.code, path: target, anchor: null, head: null, keySource: null, errors: read.errors, warnings: read.warnings }
537
+ }
538
+ const keyInfo = resolveAuditAnchorKey({ home, key, env })
539
+ const headInfo = head ?? (store ? readAuditHead(store, { verifyChain }) : null)
540
+ if (!headInfo || headInfo.ok !== true) {
541
+ return {
542
+ ok: false, found: true, status: 'chain-broken', code: headInfo?.code ?? 'E_AUDIT_CHAIN_BROKEN', path: target,
543
+ anchor: read.anchor, head: headInfo ?? null, keySource: keyInfo.source,
544
+ errors: headInfo?.errors ?? ['no audit head available'], warnings: read.warnings,
545
+ }
546
+ }
547
+ const verified = verifyAuditAnchor({ anchor: read.anchor, head: headInfo, key: keyInfo.key, allowBehind })
548
+ return {
549
+ ...verified,
550
+ found: true,
551
+ path: target,
552
+ anchor: read.anchor,
553
+ head: headInfo,
554
+ keySource: keyInfo.source,
555
+ warnings: [...read.warnings, ...verified.warnings],
556
+ }
557
+ }
558
+
559
+ /**
560
+ * Explicit `audit --expect-count/--expect-head` check (works with no anchor).
561
+ * This is the A8 acceptance path: write an anchor, delete the last audit row,
562
+ * `audit --expect-head <old head>` must fail.
563
+ */
564
+ export function verifyExpectedAudit(store, { expectedCount = null, expectedHead = null } = {}) {
565
+ const head = readAuditHead(store, { verifyChain: false })
566
+ if (!head.ok) return { ok: false, code: head.code, count: head.count, headHash: head.headHash, errors: head.errors }
567
+ const errors = []
568
+ let count = null
569
+ let headWanted = null
570
+ if (expectedCount !== null && expectedCount !== undefined) {
571
+ count = Number(expectedCount)
572
+ if (!Number.isInteger(count) || count < 0) {
573
+ errors.push('expected audit count must be a non-negative integer')
574
+ count = null
575
+ } else if (head.count !== count) {
576
+ errors.push('audit has ' + head.count + ' rows but --expect-count is ' + count + ': the tail was deleted or the database was rolled back')
577
+ }
578
+ }
579
+ if (expectedHead !== null && expectedHead !== undefined) {
580
+ headWanted = String(expectedHead).trim().toLowerCase()
581
+ if (!isHex64(headWanted)) {
582
+ errors.push('expected audit head must be 64 lowercase hex characters')
583
+ headWanted = null
584
+ } else if (head.headHash !== headWanted) {
585
+ errors.push('audit head is ' + (head.headHash || '(empty)') + ' but --expect-head is ' + headWanted + ': the tail was rewritten or rolled back')
586
+ }
587
+ }
588
+ return {
589
+ ok: errors.length === 0,
590
+ code: errors.length === 0 ? null : 'E_AUDIT_EXPECT_MISMATCH',
591
+ count: head.count,
592
+ headHash: head.headHash,
593
+ lastSeq: head.lastSeq,
594
+ expectedCount: count,
595
+ expectedHead: headWanted,
596
+ errors,
597
+ }
598
+ }
599
+
600
+ /**
601
+ * Convenience for export/backup/sync/seal: return the anchor object for the
602
+ * current head WITHOUT writing a file, so `export --all` can embed a top-level
603
+ * `auditAnchor` and `sync push` can put it in the encrypted payload metadata.
604
+ * verifyChain=true by default (anchoring a broken chain is refused).
605
+ */
606
+ export function buildAuditAnchorForStore({ store, key, home, env, generator = 'advisers', createdAt = new Date().toISOString(), verifyChain = true } = {}) {
607
+ if (!store) return { ok: false, code: 'E_AUDIT_ANCHOR_STORE', errors: ['buildAuditAnchorForStore requires {store}'], warnings: [] }
608
+ const keyInfo = resolveAuditAnchorKey({ home, key, env })
609
+ const head = readAuditHead(store, { verifyChain })
610
+ const warnings = keyInfo.warning ? [keyInfo.warning] : []
611
+ if (!head.ok) return { ok: false, code: head.code, errors: [...head.errors], warnings }
612
+ let anchor
613
+ try {
614
+ anchor = buildAuditAnchor({ head, key: keyInfo.key, generator, createdAt })
615
+ } catch (error) {
616
+ return { ok: false, code: 'E_AUDIT_ANCHOR_INVALID', errors: [String(error?.message ?? error).slice(0, 200)], warnings }
617
+ }
618
+ if (!anchor.keyed) warnings.push('building an unkeyed audit anchor (no audit key available): it cannot detect a same-user attacker who rewrites the database and the anchor together')
619
+ return { ok: true, anchor, head, keyed: anchor.keyed, keySource: keyInfo.source, warnings }
620
+ }
621
+
622
+ /**
623
+ * Write $ADVISERS_HOME/audit-anchor.json atomically (same-directory temp +
624
+ * fsync + rename, mode 0600; Windows fsync uses the writable-handle path fixed
625
+ * in fs-safe.js).
626
+ *
627
+ * Either pass a `store` (chain is verified unless verifyChain:false) or a
628
+ * precomputed `head` from readAuditHead. A broken chain is refused
629
+ * (E_AUDIT_CHAIN_BROKEN) so a bad state never becomes a baseline.
630
+ */
631
+ export function writeAuditAnchor({ home, file, store, head, key, env, generator = 'advisers', createdAt = new Date().toISOString(), verifyChain = true, mode = 0o600, fs } = {}) {
632
+ const target = file ?? (home ? join(home, AUDIT_ANCHOR_FILE) : null)
633
+ if (!target) return { ok: false, code: 'E_AUDIT_ANCHOR_PATH', errors: ['writeAuditAnchor requires {home} or {file}'], warnings: [] }
634
+ const keyInfo = resolveAuditAnchorKey({ home, key, env })
635
+ let headInfo = head
636
+ if (!headInfo) {
637
+ if (!store) return { ok: false, code: 'E_AUDIT_ANCHOR_STORE', errors: ['writeAuditAnchor requires {store} or {head}'], warnings: [] }
638
+ headInfo = readAuditHead(store, { verifyChain })
639
+ }
640
+ if (!headInfo || headInfo.ok !== true) {
641
+ return {
642
+ ok: false, path: target,
643
+ code: headInfo?.code ?? 'E_AUDIT_CHAIN_BROKEN',
644
+ errors: headInfo?.errors ?? ['no audit head available'],
645
+ warnings: keyInfo.warning ? [keyInfo.warning] : [],
646
+ }
647
+ }
648
+ let anchor
649
+ try {
650
+ anchor = buildAuditAnchor({ head: headInfo, key: keyInfo.key, generator, createdAt })
651
+ } catch (error) {
652
+ return { ok: false, path: target, code: 'E_AUDIT_ANCHOR_INVALID', errors: [String(error?.message ?? error).slice(0, 200)], warnings: [] }
653
+ }
654
+ const warnings = []
655
+ if (keyInfo.warning) warnings.push(keyInfo.warning)
656
+ if (!anchor.keyed) warnings.push('writing an unkeyed audit anchor (no audit key available): it cannot detect a same-user attacker who rewrites the database and the anchor together')
657
+ try {
658
+ atomicWriteFileSync(target, JSON.stringify(anchor, null, 2) + '\n', { fs, mode })
659
+ } catch (error) {
660
+ return { ok: false, path: target, code: error?.code ?? 'E_AUDIT_ANCHOR_WRITE_FAILED', errors: [String(error?.message ?? error).slice(0, 300)], warnings }
661
+ }
662
+ return { ok: true, path: target, anchor, keySource: keyInfo.source, keyed: anchor.keyed, warnings }
663
+ }
664
+
665
+ /** One-line actionable hint per stable anchor error code (bin/ messages). */
666
+ export const AUDIT_ANCHOR_ERROR_HINTS = Object.freeze({
667
+ E_AUDIT_ANCHOR_ABSENT: 'no audit anchor has been recorded yet; run `advisers audit --write-anchor` to create a baseline',
668
+ E_AUDIT_ANCHOR_INVALID: 'the audit anchor file is malformed; inspect it and write a fresh anchor (never delete audit rows to make it match)',
669
+ E_AUDIT_ANCHOR_TOO_LARGE: 'the audit anchor file is unexpectedly large; inspect it before trusting it',
670
+ E_AUDIT_ANCHOR_UNREADABLE: 'the audit anchor file cannot be read; check permissions and the path',
671
+ E_AUDIT_ANCHOR_KEY_MISSING: 'the audit anchor is HMAC-keyed but the audit key is unavailable; restore $ADVISERS_HOME/audit.key (do not regenerate it, the existing chain would verify as BROKEN)',
672
+ E_AUDIT_ANCHOR_HMAC_MISMATCH: 'the audit anchor HMAC does not match; treat this as tampering or a changed audit key and restore from a trusted backup',
673
+ E_AUDIT_ANCHOR_DB_MISMATCH: 'the audit anchor belongs to a different database; do not use it to certify this ledger',
674
+ E_AUDIT_TAIL_TRUNCATED: 'the audit tail was deleted or the database was rolled back; do not delete or rebuild audit rows — restore from a trusted backup and investigate',
675
+ E_AUDIT_HEAD_MISMATCH: 'the audit last row was rewritten or rolled back; restore from a trusted backup and investigate',
676
+ E_AUDIT_CHAIN_BROKEN: 'the audit chain is broken (a middle row was edited or deleted); nothing will repair it automatically — export evidence and restore from a trusted backup',
677
+ E_AUDIT_ANCHOR_BEHIND: 'the backup is older than the audit anchor; pass --allow-anchor-behind only if this time-travel is intended',
678
+ E_AUDIT_EXPECT_MISMATCH: 'the audit does not match the expected count/head; the tail may have been deleted or rolled back',
679
+ })
680
+
681
+ export function describeAuditAnchorCode(code) {
682
+ return AUDIT_ANCHOR_ERROR_HINTS[code] ?? ('audit anchor check failed: ' + String(code ?? 'unknown error'))
683
+ }