advisers 0.2.0-preview.71 → 0.2.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.
@@ -0,0 +1,644 @@
1
+ /**
2
+ * Offline verifier for Advisers delivery receipt packs (format v1.1).
3
+ *
4
+ * A receipt pack is a directory produced by buildReceiptPack in lib/evidence.js:
5
+ *
6
+ * manifest.json deliveries (relative path / size / SHA-256), generator
7
+ * environment, verify results, recipient, anchors, evidence
8
+ * README.txt human summary + verification instructions
9
+ * receipt.docx generated delivery receipt (DOCX)
10
+ * SHA256SUMS lowercase sha256 + two spaces + relative path, for every
11
+ * file above and every deliveries/... artifact
12
+ * deliveries/... byte-for-byte copies of the delivered artifacts
13
+ *
14
+ * verifyReceiptPackDir() needs no network and no ~/.advisers database: it reads
15
+ * only the given directory. It detects edits, missing files, extra files,
16
+ * duplicate/unsafe SHA256SUMS entries, bad paths, malformed JSON and schema
17
+ * drift. It cannot detect a forger who rewrites the whole pack and recomputes
18
+ * every checksum — that is what an external signature/anchor would add, and the
19
+ * README must disclose when there is none.
20
+ *
21
+ * Anchors (manifest.anchors) are NOT verified by this tool (security audit
22
+ * SEC2-05, 2026-11-17): only their shape and their file digest cross-check are
23
+ * validated, and the proof itself is opaque. A pack with recorded anchors is
24
+ * therefore reported as anchorsVerified:false / anchored:false with an explicit
25
+ * warning; the adapter named in each anchor must verify its proof out of band.
26
+ *
27
+ * The verifier deliberately does not trust manifest.json before SHA256SUMS
28
+ * matches: checksums are verified first, then the manifest schema is checked.
29
+ */
30
+
31
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
32
+ import { join, resolve } from 'node:path'
33
+ import {
34
+ MAX_QUOTE_CHARS,
35
+ RECEIPT_DELIVERIES_PREFIX,
36
+ RECEIPT_MANIFEST_FORMAT,
37
+ RECEIPT_MANIFEST_VERSION,
38
+ RECEIPT_REQUIRED_FILES,
39
+ RECEIPT_SHA256SUMS_FILE,
40
+ isUnsafePackPath,
41
+ sha256Hex,
42
+ } from './evidence.js'
43
+
44
+ const MAX_ERRORS = 300
45
+ const SUMS_LINE_RE = /^([0-9a-f]{64}) (.+)$/
46
+ const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/
47
+
48
+ function addError(errors, message) {
49
+ if (errors.length < MAX_ERRORS) errors.push(message)
50
+ else if (errors.length === MAX_ERRORS) errors.push('... too many errors; further details suppressed')
51
+ }
52
+
53
+ function isPlainObject(value) {
54
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
55
+ }
56
+
57
+ function isSha256Hex(value) {
58
+ return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value)
59
+ }
60
+
61
+ function isIsoDate(value) {
62
+ if (typeof value !== 'string' || !ISO_DATE_RE.test(value)) return false
63
+ const date = new Date(value)
64
+ return !Number.isNaN(date.getTime()) && date.toISOString() === value
65
+ }
66
+
67
+ function isNonNegativeInteger(value) {
68
+ return Number.isInteger(value) && value >= 0
69
+ }
70
+
71
+ /**
72
+ * Parse the strict receipt-pack SHA256SUMS format. SHA256SUMS must not list
73
+ * itself (it cannot contain its own digest).
74
+ *
75
+ * @returns {{entries: Map<string, string>, errors: string[]}}
76
+ */
77
+ export function parseReceiptSums(text) {
78
+ const entries = new Map()
79
+ const errors = []
80
+ if (typeof text !== 'string') {
81
+ addError(errors, 'SHA256SUMS is missing or unreadable')
82
+ return { entries, errors }
83
+ }
84
+ const lines = text.split(/\r?\n/)
85
+ lines.forEach((raw, index) => {
86
+ const lineNumber = index + 1
87
+ if (raw === '') return
88
+ if (raw.trim() !== raw) {
89
+ addError(errors, 'SHA256SUMS line ' + lineNumber + ': leading/trailing whitespace')
90
+ return
91
+ }
92
+ const match = SUMS_LINE_RE.exec(raw)
93
+ if (!match) {
94
+ addError(errors, 'malformed SHA256SUMS line ' + lineNumber + ': ' + raw.slice(0, 80))
95
+ return
96
+ }
97
+ const name = match[2]
98
+ if (name === RECEIPT_SHA256SUMS_FILE) {
99
+ addError(errors, 'SHA256SUMS must not list itself')
100
+ return
101
+ }
102
+ if (isUnsafePackPath(name)) {
103
+ addError(errors, 'unsafe path in SHA256SUMS: ' + name)
104
+ return
105
+ }
106
+ if (entries.has(name)) {
107
+ addError(errors, 'duplicate entry in SHA256SUMS: ' + name)
108
+ return
109
+ }
110
+ entries.set(name, match[1])
111
+ })
112
+ return { entries, errors }
113
+ }
114
+
115
+ function walkPackFiles(root) {
116
+ const files = []
117
+ const errors = []
118
+ const stack = ['']
119
+ while (stack.length) {
120
+ const relativeDir = stack.pop()
121
+ const directory = relativeDir ? join(root, ...relativeDir.split('/')) : root
122
+ let dirents
123
+ try {
124
+ dirents = readdirSync(directory, { withFileTypes: true })
125
+ } catch (error) {
126
+ addError(errors, 'cannot read directory ' + (relativeDir || '.') + ': ' + (error.code || error.message))
127
+ continue
128
+ }
129
+ for (const dirent of dirents) {
130
+ const relativePath = relativeDir ? relativeDir + '/' + dirent.name : dirent.name
131
+ if (dirent.isSymbolicLink()) {
132
+ addError(errors, 'symbolic links are not allowed in a receipt pack: ' + relativePath)
133
+ continue
134
+ }
135
+ if (dirent.isDirectory()) {
136
+ stack.push(relativePath)
137
+ continue
138
+ }
139
+ if (!dirent.isFile()) {
140
+ addError(errors, 'unsupported file type in receipt pack: ' + relativePath)
141
+ continue
142
+ }
143
+ files.push(relativePath)
144
+ }
145
+ }
146
+ files.sort()
147
+ return { files, errors }
148
+ }
149
+
150
+ // --- manifest schema (format v1; keep it in sync with buildReceiptPack) ------
151
+
152
+ function validateGenerator(generator, errors) {
153
+ if (!isPlainObject(generator)) {
154
+ addError(errors, 'schema: manifest.generator must be an object')
155
+ return
156
+ }
157
+ for (const key of ['advisersVersion', 'templateName', 'templateVersion', 'command']) {
158
+ if (!(key in generator)) addError(errors, 'schema: manifest.generator.' + key + ' is missing')
159
+ else if (!(generator[key] === null || typeof generator[key] === 'string')) {
160
+ addError(errors, 'schema: manifest.generator.' + key + ' must be a string or null')
161
+ }
162
+ }
163
+ if (typeof generator.nodeVersion !== 'string' || !generator.nodeVersion) {
164
+ addError(errors, 'schema: manifest.generator.nodeVersion must be a non-empty string')
165
+ }
166
+ if (typeof generator.platform !== 'string' || !generator.platform) {
167
+ addError(errors, 'schema: manifest.generator.platform must be a non-empty string')
168
+ }
169
+ }
170
+
171
+ function validateRecipient(recipient, errors) {
172
+ if (recipient === null) return
173
+ if (!isPlainObject(recipient)) {
174
+ addError(errors, 'schema: manifest.recipient must be null or an object')
175
+ return
176
+ }
177
+ for (const key of ['name', 'email', 'note']) {
178
+ if (!(key in recipient)) addError(errors, 'schema: manifest.recipient.' + key + ' is missing')
179
+ else if (!(recipient[key] === null || typeof recipient[key] === 'string')) {
180
+ addError(errors, 'schema: manifest.recipient.' + key + ' must be a string or null')
181
+ }
182
+ }
183
+ }
184
+
185
+ function validateDelivery(delivery, index, sums, deliveryFiles, errors) {
186
+ const where = 'manifest.deliveries[' + index + ']'
187
+ if (!isPlainObject(delivery)) {
188
+ addError(errors, 'schema: ' + where + ' must be an object')
189
+ return
190
+ }
191
+ if (typeof delivery.id !== 'string' || !delivery.id) addError(errors, 'schema: ' + where + '.id must be a non-empty string')
192
+ if (!('title' in delivery) || !(delivery.title === null || typeof delivery.title === 'string')) {
193
+ addError(errors, 'schema: ' + where + '.title must be a string or null')
194
+ }
195
+ if (!('tool' in delivery) || !(delivery.tool === null || typeof delivery.tool === 'string')) {
196
+ addError(errors, 'schema: ' + where + '.tool must be a string or null')
197
+ }
198
+ if (!('validation' in delivery) || !(delivery.validation === null || typeof delivery.validation === 'string')) {
199
+ addError(errors, 'schema: ' + where + '.validation must be a string or null')
200
+ }
201
+ if (!('createdAt' in delivery) || !(delivery.createdAt === null || isIsoDate(delivery.createdAt))) {
202
+ addError(errors, 'schema: ' + where + '.createdAt must be null or an ISO-8601 UTC timestamp')
203
+ }
204
+ if (!Array.isArray(delivery.files) || delivery.files.length === 0) {
205
+ addError(errors, 'schema: ' + where + '.files must be a non-empty array')
206
+ return
207
+ }
208
+ delivery.files.forEach((file, fileIndex) => {
209
+ const fileWhere = where + '.files[' + fileIndex + ']'
210
+ if (!isPlainObject(file)) {
211
+ addError(errors, 'schema: ' + fileWhere + ' must be an object')
212
+ return
213
+ }
214
+ if (typeof file.path !== 'string' || isUnsafePackPath(file.path)) {
215
+ addError(errors, 'schema: ' + fileWhere + '.path must be a safe relative path')
216
+ return
217
+ }
218
+ if (!file.path.startsWith(RECEIPT_DELIVERIES_PREFIX)) {
219
+ addError(errors, 'schema: ' + fileWhere + '.path must start with ' + RECEIPT_DELIVERIES_PREFIX)
220
+ }
221
+ if (typeof file.name !== 'string' || !file.name) addError(errors, 'schema: ' + fileWhere + '.name must be a non-empty string')
222
+ if (!isNonNegativeInteger(file.size)) addError(errors, 'schema: ' + fileWhere + '.size must be a non-negative integer')
223
+ if (!isSha256Hex(file.sha256)) addError(errors, 'schema: ' + fileWhere + '.sha256 must be 64 lowercase hex characters')
224
+ const listed = sums.get(file.path)
225
+ if (listed === undefined) addError(errors, 'file referenced by manifest is not covered by SHA256SUMS: ' + file.path)
226
+ else if (isSha256Hex(file.sha256) && listed !== file.sha256) {
227
+ addError(errors, 'manifest digest disagrees with SHA256SUMS for ' + file.path)
228
+ }
229
+ if (deliveryFiles.has(file.path)) addError(errors, 'duplicate delivery file path in manifest: ' + file.path)
230
+ else deliveryFiles.set(file.path, file.sha256)
231
+ })
232
+ }
233
+
234
+ function validateVerifyResult(result, where, errors) {
235
+ if (!isPlainObject(result)) {
236
+ addError(errors, 'schema: ' + where + ' must be an object')
237
+ return false
238
+ }
239
+ if (!(result.source === null || typeof result.source === 'string')) addError(errors, 'schema: ' + where + '.source must be a string or null')
240
+ if (typeof result.ok !== 'boolean') addError(errors, 'schema: ' + where + '.ok must be a boolean')
241
+ if (!(result.checkedAt === null || isIsoDate(result.checkedAt))) addError(errors, 'schema: ' + where + '.checkedAt must be null or an ISO-8601 UTC timestamp')
242
+ if (!Array.isArray(result.errors) || result.errors.some((item) => typeof item !== 'string')) {
243
+ addError(errors, 'schema: ' + where + '.errors must be an array of strings')
244
+ }
245
+ if (!Array.isArray(result.checks)) {
246
+ addError(errors, 'schema: ' + where + '.checks must be an array')
247
+ } else {
248
+ result.checks.forEach((check, checkIndex) => {
249
+ const checkWhere = where + '.checks[' + checkIndex + ']'
250
+ if (!isPlainObject(check)) {
251
+ addError(errors, 'schema: ' + checkWhere + ' must be an object')
252
+ return
253
+ }
254
+ if (typeof check.id !== 'string' || !check.id) addError(errors, 'schema: ' + checkWhere + '.id must be a non-empty string')
255
+ if (typeof check.ok !== 'boolean') addError(errors, 'schema: ' + checkWhere + '.ok must be a boolean')
256
+ for (const key of ['severity', 'detail']) {
257
+ if (key in check && typeof check[key] !== 'string') addError(errors, 'schema: ' + checkWhere + '.' + key + ' must be a string')
258
+ }
259
+ if ('skipped' in check && typeof check.skipped !== 'boolean') addError(errors, 'schema: ' + checkWhere + '.skipped must be a boolean')
260
+ })
261
+ }
262
+ if (!(result.summary === null || typeof result.summary === 'string')) addError(errors, 'schema: ' + where + '.summary must be a string or null')
263
+ return result.ok === true
264
+ }
265
+
266
+ function validateAnchor(anchor, index, sums, errors) {
267
+ const where = 'manifest.anchors[' + index + ']'
268
+ if (!isPlainObject(anchor)) {
269
+ addError(errors, 'schema: ' + where + ' must be an object')
270
+ return
271
+ }
272
+ if (typeof anchor.file !== 'string' || isUnsafePackPath(anchor.file)) addError(errors, 'schema: ' + where + '.file must be a safe relative path')
273
+ if (!isSha256Hex(anchor.fileSha256)) addError(errors, 'schema: ' + where + '.fileSha256 must be 64 lowercase hex characters')
274
+ if (typeof anchor.adapterId !== 'string' || !anchor.adapterId) addError(errors, 'schema: ' + where + '.adapterId must be a non-empty string')
275
+ if (!(anchor.issuedAt === null || isIsoDate(anchor.issuedAt))) addError(errors, 'schema: ' + where + '.issuedAt must be null or an ISO-8601 UTC timestamp')
276
+ if (typeof anchor.proof !== 'string' || !anchor.proof.length) addError(errors, 'schema: ' + where + '.proof must be a non-empty string')
277
+ if (typeof anchor.file === 'string' && !isUnsafePackPath(anchor.file)) {
278
+ const listed = sums.get(anchor.file)
279
+ if (listed === undefined) addError(errors, 'anchor file is not covered by SHA256SUMS: ' + anchor.file)
280
+ else if (isSha256Hex(anchor.fileSha256) && listed !== anchor.fileSha256) {
281
+ addError(errors, 'anchor fileSha256 disagrees with SHA256SUMS for ' + anchor.file)
282
+ }
283
+ }
284
+ }
285
+
286
+ function validateEvidenceSource(source, where, errors) {
287
+ if (!isPlainObject(source)) {
288
+ addError(errors, 'schema: ' + where + ' must be an object')
289
+ return
290
+ }
291
+ if (typeof source.sessionId !== 'string') addError(errors, 'schema: ' + where + '.sessionId must be a string')
292
+ if (typeof source.turnId !== 'string') addError(errors, 'schema: ' + where + '.turnId must be a string')
293
+ if (typeof source.quote !== 'string') addError(errors, 'schema: ' + where + '.quote must be a string')
294
+ else {
295
+ if (Array.from(source.quote).length > MAX_QUOTE_CHARS) {
296
+ addError(errors, 'schema: ' + where + '.quote is longer than ' + MAX_QUOTE_CHARS + ' characters')
297
+ }
298
+ if (!isSha256Hex(source.quoteSha256)) addError(errors, 'schema: ' + where + '.quoteSha256 must be 64 lowercase hex characters')
299
+ else if (typeof source.quote === 'string' && sha256Hex(source.quote) !== source.quoteSha256) {
300
+ addError(errors, 'evidence quoteSha256 mismatch at ' + where)
301
+ }
302
+ }
303
+ if (!isNonNegativeInteger(source.quoteChars)) addError(errors, 'schema: ' + where + '.quoteChars must be a non-negative integer')
304
+ else if (typeof source.quote === 'string' && source.quoteChars < Array.from(source.quote).length) {
305
+ addError(errors, 'schema: ' + where + '.quoteChars is smaller than the stored quote')
306
+ }
307
+ if (typeof source.truncated !== 'boolean') addError(errors, 'schema: ' + where + '.truncated must be a boolean')
308
+ if ('turnSeq' in source && !Number.isInteger(source.turnSeq)) addError(errors, 'schema: ' + where + '.turnSeq must be an integer')
309
+ if ('turnRole' in source && typeof source.turnRole !== 'string') addError(errors, 'schema: ' + where + '.turnRole must be a string')
310
+ }
311
+
312
+ function validateEvidenceEntry(entry, index, errors) {
313
+ const where = 'manifest.evidence.entries[' + index + ']'
314
+ if (!isPlainObject(entry)) {
315
+ addError(errors, 'schema: ' + where + ' must be an object')
316
+ return
317
+ }
318
+ if (typeof entry.kind !== 'string' || !entry.kind) addError(errors, 'schema: ' + where + '.kind must be a non-empty string')
319
+ if (typeof entry.id !== 'string') addError(errors, 'schema: ' + where + '.id must be a string')
320
+ if (typeof entry.found !== 'boolean') addError(errors, 'schema: ' + where + '.found must be a boolean')
321
+ if (!Array.isArray(entry.sources)) addError(errors, 'schema: ' + where + '.sources must be an array')
322
+ else entry.sources.forEach((source, sourceIndex) => validateEvidenceSource(source, where + '.sources[' + sourceIndex + ']', errors))
323
+ if (!Array.isArray(entry.missing)) addError(errors, 'schema: ' + where + '.missing must be an array')
324
+ else {
325
+ entry.missing.forEach((item, itemIndex) => {
326
+ const itemWhere = where + '.missing[' + itemIndex + ']'
327
+ if (!isPlainObject(item)) {
328
+ addError(errors, 'schema: ' + itemWhere + ' must be an object')
329
+ return
330
+ }
331
+ if (typeof item.reason !== 'string' || !item.reason) addError(errors, 'schema: ' + itemWhere + '.reason must be a non-empty string')
332
+ for (const key of ['id', 'ref', 'sessionId', 'turnId']) {
333
+ if (key in item && typeof item[key] !== 'string') addError(errors, 'schema: ' + itemWhere + '.' + key + ' must be a string')
334
+ }
335
+ if ('quote' in item) {
336
+ if (typeof item.quote !== 'string') addError(errors, 'schema: ' + itemWhere + '.quote must be a string')
337
+ else {
338
+ if (Array.from(item.quote).length > MAX_QUOTE_CHARS) {
339
+ addError(errors, 'schema: ' + itemWhere + '.quote is longer than ' + MAX_QUOTE_CHARS + ' characters')
340
+ }
341
+ if (!isSha256Hex(item.quoteSha256) || sha256Hex(item.quote) !== item.quoteSha256) {
342
+ addError(errors, 'evidence quoteSha256 mismatch at ' + itemWhere)
343
+ }
344
+ }
345
+ }
346
+ })
347
+ }
348
+ }
349
+
350
+ function validateEvidence(evidence, errors) {
351
+ if (!isPlainObject(evidence)) {
352
+ addError(errors, 'schema: manifest.evidence must be an object')
353
+ return
354
+ }
355
+ if (typeof evidence.format !== 'string' || !evidence.format) addError(errors, 'schema: manifest.evidence.format must be a non-empty string')
356
+ if (!Number.isInteger(evidence.version) || evidence.version < 1) addError(errors, 'schema: manifest.evidence.version must be a positive integer')
357
+ if (!Array.isArray(evidence.entries)) {
358
+ addError(errors, 'schema: manifest.evidence.entries must be an array')
359
+ return
360
+ }
361
+ evidence.entries.forEach((entry, index) => validateEvidenceEntry(entry, index, errors))
362
+ if (evidence.entryCount !== evidence.entries.length) {
363
+ addError(errors, 'schema: manifest.evidence.entryCount must equal the number of entries')
364
+ }
365
+ if (!isNonNegativeInteger(evidence.sourceCount)) addError(errors, 'schema: manifest.evidence.sourceCount must be a non-negative integer')
366
+ if (!isNonNegativeInteger(evidence.missingCount)) addError(errors, 'schema: manifest.evidence.missingCount must be a non-negative integer')
367
+ const actualCounts = {}
368
+ let sourceCount = 0
369
+ let missingCount = 0
370
+ for (const entry of evidence.entries) {
371
+ if (!isPlainObject(entry)) continue
372
+ actualCounts[entry.kind] = (actualCounts[entry.kind] || 0) + 1
373
+ if (Array.isArray(entry.sources)) sourceCount += entry.sources.length
374
+ if (Array.isArray(entry.missing)) missingCount += entry.missing.length
375
+ }
376
+ if (isNonNegativeInteger(evidence.sourceCount) && evidence.sourceCount !== sourceCount) {
377
+ addError(errors, 'schema: manifest.evidence.sourceCount disagrees with the entries')
378
+ }
379
+ if (isNonNegativeInteger(evidence.missingCount) && evidence.missingCount !== missingCount) {
380
+ addError(errors, 'schema: manifest.evidence.missingCount disagrees with the entries')
381
+ }
382
+ if (!isPlainObject(evidence.counts)) {
383
+ addError(errors, 'schema: manifest.evidence.counts must be an object')
384
+ } else {
385
+ let declared = 0
386
+ for (const [kind, value] of Object.entries(actualCounts)) {
387
+ if (evidence.counts[kind] !== value) addError(errors, 'schema: manifest.evidence.counts.' + kind + ' disagrees with the entries')
388
+ }
389
+ for (const value of Object.values(evidence.counts)) {
390
+ if (!isNonNegativeInteger(value)) {
391
+ addError(errors, 'schema: manifest.evidence.counts values must be non-negative integers')
392
+ break
393
+ }
394
+ declared += value
395
+ }
396
+ if (declared !== evidence.entries.length) addError(errors, 'schema: manifest.evidence.counts do not sum to entryCount')
397
+ }
398
+ }
399
+
400
+ function validateReceiptManifest(manifest, sums, errors, result) {
401
+ if (!isPlainObject(manifest)) {
402
+ addError(errors, 'schema: manifest.json must be a JSON object')
403
+ return
404
+ }
405
+ if (manifest.format !== RECEIPT_MANIFEST_FORMAT) {
406
+ addError(errors, 'schema: manifest.format must be ' + RECEIPT_MANIFEST_FORMAT)
407
+ }
408
+ if (manifest.version !== RECEIPT_MANIFEST_VERSION) {
409
+ addError(errors, 'schema: manifest.version must be ' + RECEIPT_MANIFEST_VERSION)
410
+ }
411
+ if (!isIsoDate(manifest.createdAt)) addError(errors, 'schema: manifest.createdAt must be an ISO-8601 UTC timestamp')
412
+ validateGenerator(manifest.generator, errors)
413
+ validateRecipient(manifest.recipient, errors)
414
+
415
+ const deliveryFiles = new Map()
416
+ if (!Array.isArray(manifest.deliveries) || manifest.deliveries.length === 0) {
417
+ addError(errors, 'schema: manifest.deliveries must be a non-empty array')
418
+ } else {
419
+ const ids = new Set()
420
+ manifest.deliveries.forEach((delivery, index) => {
421
+ if (isPlainObject(delivery) && typeof delivery.id === 'string' && delivery.id) {
422
+ if (ids.has(delivery.id)) addError(errors, 'schema: manifest.deliveries[' + index + '].id is duplicated: ' + delivery.id)
423
+ else ids.add(delivery.id)
424
+ }
425
+ validateDelivery(delivery, index, sums, deliveryFiles, errors)
426
+ })
427
+ }
428
+
429
+ if (!isPlainObject(manifest.receipt)) {
430
+ addError(errors, 'schema: manifest.receipt must be an object')
431
+ } else {
432
+ if (manifest.receipt.path !== 'receipt.docx') addError(errors, 'schema: manifest.receipt.path must be "receipt.docx"')
433
+ if (!isNonNegativeInteger(manifest.receipt.size)) addError(errors, 'schema: manifest.receipt.size must be a non-negative integer')
434
+ if (!isSha256Hex(manifest.receipt.sha256)) addError(errors, 'schema: manifest.receipt.sha256 must be 64 lowercase hex characters')
435
+ const listed = sums.get('receipt.docx')
436
+ if (listed === undefined) addError(errors, 'receipt.docx is not covered by SHA256SUMS')
437
+ else if (isSha256Hex(manifest.receipt.sha256) && listed !== manifest.receipt.sha256) {
438
+ addError(errors, 'manifest digest disagrees with SHA256SUMS for receipt.docx')
439
+ }
440
+ }
441
+
442
+ let expectedStatus = 'not-recorded'
443
+ if (!Array.isArray(manifest.verify)) {
444
+ addError(errors, 'schema: manifest.verify must be an array')
445
+ } else {
446
+ let allOk = true
447
+ manifest.verify.forEach((result, index) => {
448
+ if (isPlainObject(result) && result.ok === true) {
449
+ validateVerifyResult(result, 'manifest.verify[' + index + ']', errors)
450
+ } else {
451
+ allOk = false
452
+ validateVerifyResult(result, 'manifest.verify[' + index + ']', errors)
453
+ }
454
+ })
455
+ if (manifest.verify.length) expectedStatus = allOk ? 'passed' : 'failed'
456
+ }
457
+ if (manifest.verifyStatus !== expectedStatus) {
458
+ addError(errors, 'schema: manifest.verifyStatus is ' + JSON.stringify(manifest.verifyStatus) + ' but the verify array implies ' + JSON.stringify(expectedStatus))
459
+ }
460
+
461
+ if (!Array.isArray(manifest.anchors)) addError(errors, 'schema: manifest.anchors must be an array')
462
+ else {
463
+ result.anchorsRecorded = manifest.anchors.length
464
+ manifest.anchors.forEach((anchor, index) => validateAnchor(anchor, index, sums, errors))
465
+ if (manifest.anchors.length > 0) {
466
+ // Never present a recorded anchor as verified: the proof was not checked
467
+ // against the named adapter (SEC2-05).
468
+ result.warnings.push('anchors are recorded but NOT cryptographically verified by this tool; verify each proof with the adapter that issued it and do not treat this pack as externally anchored')
469
+ }
470
+ }
471
+
472
+ validateEvidence(manifest.evidence, errors)
473
+
474
+ const expectedFileCount = RECEIPT_REQUIRED_FILES.length + deliveryFiles.size
475
+ if (manifest.fileCount !== expectedFileCount) {
476
+ addError(errors, 'schema: manifest.fileCount is ' + manifest.fileCount + ' but manifest lists ' + expectedFileCount + ' files')
477
+ }
478
+ if (manifest.fileCount !== sums.size) {
479
+ addError(errors, 'schema: manifest.fileCount is ' + manifest.fileCount + ' but SHA256SUMS has ' + sums.size + ' entries')
480
+ }
481
+ for (const required of RECEIPT_REQUIRED_FILES) {
482
+ if (!sums.has(required)) addError(errors, 'SHA256SUMS does not cover ' + required)
483
+ }
484
+ }
485
+
486
+ // --- directory verifier ------------------------------------------------------
487
+
488
+ /**
489
+ * Verify a receipt pack directory offline.
490
+ *
491
+ * @param {string} dir pack directory produced by buildReceiptPack({outDir})
492
+ * @returns {{ok: boolean, errors: string[], warnings: string[], dir: string,
493
+ * fileCount: number, checksumCount: number, files: string[],
494
+ * checksums: Record<string, string>, manifest: object|null,
495
+ * anchorsRecorded: number, anchorsVerified: boolean, anchored: boolean}}
496
+ */
497
+ export function verifyReceiptPackDir(dir) {
498
+ const errors = []
499
+ const warnings = []
500
+ const files = []
501
+ const result = {
502
+ ok: false,
503
+ errors,
504
+ warnings,
505
+ dir: String(dir),
506
+ fileCount: 0,
507
+ checksumCount: 0,
508
+ files,
509
+ checksums: {},
510
+ manifest: null,
511
+ // Anchors are recorded, never verified, by this offline tool (SEC2-05).
512
+ // `ok` covers pack integrity only; it must not be read as "anchored".
513
+ anchorsRecorded: 0,
514
+ anchorsVerified: false,
515
+ anchored: false,
516
+ }
517
+ let root
518
+ try {
519
+ root = resolve(String(dir))
520
+ } catch (error) {
521
+ addError(errors, 'invalid receipt pack path: ' + (error.message || error))
522
+ return result
523
+ }
524
+ result.dir = root
525
+ if (!existsSync(root)) {
526
+ addError(errors, 'receipt pack directory not found: ' + root)
527
+ return result
528
+ }
529
+ let rootStat
530
+ try {
531
+ rootStat = statSync(root)
532
+ } catch (error) {
533
+ addError(errors, 'cannot stat receipt pack directory: ' + (error.code || error.message))
534
+ return result
535
+ }
536
+ if (!rootStat.isDirectory()) {
537
+ addError(errors, 'receipt pack path is not a directory: ' + root)
538
+ return result
539
+ }
540
+
541
+ const walked = walkPackFiles(root)
542
+ for (const error of walked.errors) addError(errors, error)
543
+ for (const file of walked.files) files.push(file)
544
+ result.fileCount = files.length
545
+ const fileSet = new Set(files)
546
+
547
+ const sumsPath = join(root, RECEIPT_SHA256SUMS_FILE)
548
+ if (!fileSet.has(RECEIPT_SHA256SUMS_FILE)) {
549
+ addError(errors, 'missing file: ' + RECEIPT_SHA256SUMS_FILE)
550
+ return result
551
+ }
552
+ let sumsText
553
+ try {
554
+ sumsText = readFileSync(sumsPath, 'utf8')
555
+ } catch (error) {
556
+ addError(errors, 'cannot read SHA256SUMS: ' + (error.code || error.message))
557
+ return result
558
+ }
559
+ const parsed = parseReceiptSums(sumsText)
560
+ for (const error of parsed.errors) addError(errors, error)
561
+ result.checksumCount = parsed.entries.size
562
+ result.checksums = Object.fromEntries([...parsed.entries.entries()].sort((left, right) => (left[0] < right[0] ? -1 : 1)))
563
+
564
+ for (const required of RECEIPT_REQUIRED_FILES) {
565
+ if (!parsed.entries.has(required)) addError(errors, 'SHA256SUMS does not cover ' + required)
566
+ if (!fileSet.has(required)) addError(errors, 'missing file: ' + required)
567
+ }
568
+ for (const name of parsed.entries.keys()) {
569
+ if (!fileSet.has(name)) addError(errors, 'missing file: ' + name)
570
+ }
571
+ for (const name of fileSet) {
572
+ if (name === RECEIPT_SHA256SUMS_FILE) continue
573
+ if (!parsed.entries.has(name)) addError(errors, 'file not covered by SHA256SUMS: ' + name)
574
+ }
575
+
576
+ for (const [name, expected] of parsed.entries) {
577
+ if (!fileSet.has(name)) continue
578
+ const full = join(root, ...name.split('/'))
579
+ try {
580
+ const actual = sha256Hex(readFileSync(full))
581
+ if (actual !== expected) {
582
+ addError(errors, 'hash mismatch: ' + name + ' (expected ' + expected.slice(0, 12) + '..., computed ' + actual.slice(0, 12) + '...)')
583
+ }
584
+ } catch (error) {
585
+ addError(errors, 'cannot read file ' + name + ': ' + (error.code || error.message))
586
+ }
587
+ }
588
+
589
+ // receipt.docx structural smoke check (never call Office/WPS to verify it).
590
+ if (fileSet.has('receipt.docx')) {
591
+ try {
592
+ const bytes = readFileSync(join(root, 'receipt.docx'))
593
+ if (bytes.length < 4 || bytes[0] !== 0x50 || bytes[1] !== 0x4b) {
594
+ addError(errors, 'receipt.docx is not a ZIP/DOCX file')
595
+ } else if (!bytes.includes(Buffer.from('word/document.xml', 'utf8'))) {
596
+ addError(errors, 'receipt.docx is missing word/document.xml')
597
+ }
598
+ } catch (error) {
599
+ addError(errors, 'cannot read receipt.docx: ' + (error.code || error.message))
600
+ }
601
+ }
602
+
603
+ if (!fileSet.has('manifest.json')) return result
604
+ let manifest = null
605
+ try {
606
+ manifest = JSON.parse(readFileSync(join(root, 'manifest.json'), 'utf8'))
607
+ } catch (error) {
608
+ addError(errors, 'manifest.json is not valid JSON: ' + (error.message || error))
609
+ return result
610
+ }
611
+ result.manifest = manifest
612
+ validateReceiptManifest(manifest, parsed.entries, errors, result)
613
+
614
+ // Size statements in the manifest must match the bytes on disk.
615
+ if (isPlainObject(manifest)) {
616
+ const sizeRecords = []
617
+ if (Array.isArray(manifest.deliveries)) {
618
+ for (const delivery of manifest.deliveries) {
619
+ if (isPlainObject(delivery) && Array.isArray(delivery.files)) {
620
+ for (const file of delivery.files) if (isPlainObject(file)) sizeRecords.push(file)
621
+ }
622
+ }
623
+ }
624
+ if (isPlainObject(manifest.receipt)) sizeRecords.push(manifest.receipt)
625
+ for (const record of sizeRecords) {
626
+ if (typeof record.path !== 'string' || isUnsafePackPath(record.path) || !fileSet.has(record.path)) continue
627
+ try {
628
+ const size = statSync(join(root, ...record.path.split('/'))).size
629
+ if (isNonNegativeInteger(record.size) && size !== record.size) {
630
+ addError(errors, 'schema: manifest size disagrees with the file on disk for ' + record.path)
631
+ }
632
+ } catch (error) {
633
+ addError(errors, 'cannot stat ' + record.path + ': ' + (error.code || error.message))
634
+ }
635
+ }
636
+ if (Array.isArray(manifest.anchors) && manifest.anchors.length === 0) {
637
+ warnings.push('pack is not externally anchored: SHA-256 proves internal consistency only')
638
+ }
639
+ if (manifest.verifyStatus === 'not-recorded') warnings.push('no verify results were recorded in this pack')
640
+ }
641
+
642
+ result.ok = errors.length === 0
643
+ return result
644
+ }