@agledger/verify-core 2.1.0 → 4.0.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 (54) hide show
  1. package/LICENSE +18 -18
  2. package/README.md +869 -53
  3. package/dist/acknowledgements.d.ts +32 -0
  4. package/dist/acknowledgements.js +88 -0
  5. package/dist/anchors.d.ts +349 -0
  6. package/dist/anchors.js +654 -0
  7. package/dist/attestation.d.ts +98 -0
  8. package/dist/attestation.js +145 -0
  9. package/dist/audit-export.d.ts +404 -29
  10. package/dist/audit-export.js +547 -28
  11. package/dist/batch-head.d.ts +28 -0
  12. package/dist/batch-head.js +169 -0
  13. package/dist/batch.d.ts +69 -0
  14. package/dist/batch.js +99 -0
  15. package/dist/bulk-export.d.ts +161 -0
  16. package/dist/bulk-export.js +711 -0
  17. package/dist/cbor-strict.d.ts +9 -0
  18. package/dist/cbor-strict.js +14 -0
  19. package/dist/chain.d.ts +221 -31
  20. package/dist/chain.js +339 -65
  21. package/dist/claim.d.ts +23 -0
  22. package/dist/claim.js +100 -0
  23. package/dist/export-anchors.d.ts +84 -0
  24. package/dist/export-anchors.js +109 -0
  25. package/dist/export-evidence.d.ts +90 -0
  26. package/dist/export-evidence.js +186 -0
  27. package/dist/export-pages.d.ts +476 -0
  28. package/dist/export-pages.js +586 -0
  29. package/dist/failures.d.ts +44 -26
  30. package/dist/failures.js +81 -31
  31. package/dist/federation-wire.d.ts +106 -20
  32. package/dist/federation-wire.js +286 -76
  33. package/dist/history-seal.d.ts +100 -0
  34. package/dist/history-seal.js +301 -0
  35. package/dist/index.d.ts +37 -9
  36. package/dist/index.js +18 -5
  37. package/dist/instant.d.ts +1 -1
  38. package/dist/instant.js +1 -1
  39. package/dist/key-statements.d.ts +160 -11
  40. package/dist/key-statements.js +261 -60
  41. package/dist/ml-dsa-kats.d.ts +18 -0
  42. package/dist/ml-dsa-kats.js +241 -0
  43. package/dist/options.js +4 -4
  44. package/dist/primitives.d.ts +287 -47
  45. package/dist/primitives.js +673 -101
  46. package/dist/read-log.d.ts +350 -0
  47. package/dist/read-log.js +816 -0
  48. package/dist/schema-chain-export.d.ts +82 -0
  49. package/dist/schema-chain-export.js +474 -0
  50. package/dist/walk-anchors.d.ts +115 -0
  51. package/dist/walk-anchors.js +133 -0
  52. package/dist/walk-checkpoints.d.ts +125 -0
  53. package/dist/walk-checkpoints.js +118 -0
  54. package/package.json +9 -5
@@ -6,7 +6,7 @@
6
6
  * normalized entry and runs `verifyChain`.
7
7
  *
8
8
  * The three row-level input-gated checks run on the export path when the wire
9
- * carries their inputs (engine ≥ v0.26.x): the `actorOidcSynthesized` flag +
9
+ * carries their inputs (Server 0.26 and later): the `actorOidcSynthesized` flag +
10
10
  * `actorOidcIss/Sub` enable the OIDC-actor cross-check; `signingKeyWindows` +
11
11
  * per-entry `createdAt` enable temporal key-validity; and the per-entry
12
12
  * denormalized `payload` + `entryType` enable binding-integrity, the export's
@@ -14,21 +14,76 @@
14
14
  * tampering of the human-readable `payload`/`criteria` view: the verifier
15
15
  * re-decodes the signed predicate from `coseSign1` and deep-equals it against
16
16
  * the row `payload`, so a rewritten `payload` with an intact envelope fails
17
- * CHAIN_PAYLOAD_BINDING_MISMATCH (validated against a real engine v0.26.4
17
+ * CHAIN_PAYLOAD_BINDING_MISMATCH (validated against a real Server v0.26.4
18
18
  * export; `buildPredicateForRow` reconstructs the signed predicate exactly).
19
19
  * Older exports without these fields stay `skipped_no_input`, surfaced in the
20
20
  * result so a caller never mistakes "not checked here" for "checked and passed".
21
21
  */
22
22
  import { buildAgentKeyRegistry, buildKeyRegistry, earliestKeyActivation, verifyChain, } from './chain.js';
23
- import { instantMs } from './instant.js';
23
+ import { instantMs, rfc3339Ms } from './instant.js';
24
+ import { BATCH_PENDING_GRACE_SECONDS } from './batch.js';
25
+ import { buildBatchHeadRegistry } from './batch-head.js';
26
+ import { planHistorySeals } from './history-seal.js';
24
27
  import { assertKnownOptions } from './options.js';
28
+ import { verifyRewindAcknowledgements } from './anchors.js';
29
+ import { readAcknowledgementSources } from './acknowledgements.js';
30
+ import { decodeSignedClaim } from './claim.js';
31
+ import { readComplianceRecords, verifyAttestations } from './attestation.js';
32
+ import { verifyCheckpointCoverage, verifyExportAnchors } from './export-anchors.js';
33
+ import { judgeListedCheckpoints } from './walk-checkpoints.js';
34
+ import { decodeCoseSign1, decodePredicate, anchorAlgorithms, hasComputableAnchor, isVerifyingAsIfHostComputed, runtimeBelowFloor, uncomputableAlgorithms, verifyAsIfHostComputed } from './primitives.js';
25
35
  import { buildFederationKeyRegistry } from './federation-wire.js';
26
- import { applyKeyTrust, assertNotPinnedAndDistrusted, computeKeyTrust, keyStatementsFromExport, statementsFromMap, reportKeyTrust, settleKeyTrust, verdictOf, } from './key-statements.js';
36
+ import { verifyExportCheckpoint, verifyExportReceipts, } from './export-evidence.js';
37
+ import { applyKeyTrust, assertNotPinnedAndDistrusted, computeKeyTrust, keyStatementsFromExport, statementsFromMap, reportKeyTrust, settleKeyTrust, sealedVerdict, unverifiableVerdict, pinReachesNoKey, verdictOf, } from './key-statements.js';
38
+ /** One entry of a `/audit-export` document. */
39
+ /** 0000-01-01T00:00:00Z, the earliest instant an RFC 3339 string can spell. */
40
+ const YEAR_ZERO_MS = -62_167_219_200_000;
41
+ /** A verdict held at best `unanchored` when any cap applies. */
42
+ export function capVerdict(verdict, caps) {
43
+ return verdict === 'trusted' && caps.length > 0 ? 'unanchored' : verdict;
44
+ }
27
45
  const SUPPORTED_FORMAT_VERSION = '2.0';
28
46
  const SUPPORTED_CANONICALIZATION = 'RFC8949-CDE';
29
47
  function isRecord(value) {
30
48
  return value !== null && typeof value === 'object' && !Array.isArray(value);
31
49
  }
50
+ /**
51
+ * Which of the Server's cross-record exports a document is, or null: a page
52
+ * of `GET /v1/audit-vault/export` (`'bulk'`) or of
53
+ * `GET /v1/audit-vault/schema-chain/export` (`'schema-chain'`). Both carry
54
+ * their entries in `data` beside `chainMetadata`, where a record's audit
55
+ * export carries `entries`. `verifyAuditExport` reads a record's audit export
56
+ * and names the function that reads these: `verifyBulkExport` and
57
+ * `verifySchemaChainExport`. An NDJSON page parsed line by line is read by
58
+ * those functions as text.
59
+ */
60
+ export function auditVaultExportKind(value) {
61
+ if (!isRecord(value) || !Array.isArray(value.data) || !isRecord(value.chainMetadata) || 'entries' in value)
62
+ return null;
63
+ return 'chain' in value.chainMetadata || 'checkpointKey' in value.chainMetadata ? 'schema-chain' : 'bulk';
64
+ }
65
+ /** What reads a cross-record export page in place of `verifyAuditExport`. */
66
+ export const NOT_A_RECORD_EXPORT = {
67
+ bulk: 'This is a page of GET /v1/audit-vault/export, the export across records, not one record\'s audit export, and verifyAuditExport reached no verdict on it. Verify the walk, every page from the first to the one whose nextCursor is null, with verifyBulkExport (agledger-verify reads the page files or their directory).',
68
+ 'schema-chain': 'This is a page of GET /v1/audit-vault/schema-chain/export, a schema-registry chain, not a record\'s audit export, and verifyAuditExport reached no verdict on it. Verify the walk, every page from the first to the one whose nextCursor is null, with verifySchemaChainExport (agledger-verify reads the page files or their directory).',
69
+ };
70
+ const READINGS = new WeakMap();
71
+ /**
72
+ * The instant from which a batched entry with no proof, read at `readAt`, is
73
+ * still waiting for its head: `readAt` less `BATCH_PENDING_GRACE_SECONDS`.
74
+ * Null when `readAt` is not an RFC 3339 instant, or when the grace would carry
75
+ * it before year 0000.
76
+ */
77
+ function batchPendingSinceOf(readAt) {
78
+ const cutAt = typeof readAt === 'string' ? rfc3339Ms(readAt) : NaN;
79
+ const graceStart = cutAt - BATCH_PENDING_GRACE_SECONDS * 1000;
80
+ return Number.isNaN(cutAt) || graceStart < YEAR_ZERO_MS ? null : new Date(graceStart).toISOString();
81
+ }
82
+ /** `verifyAuditExport` on a document built for one chain of a cross-record export. Internal to this package. */
83
+ export function verifyExportChain(exportData, options, reading) {
84
+ READINGS.set(exportData, reading);
85
+ return verifyAuditExport(exportData, options);
86
+ }
32
87
  /**
33
88
  * Verify one record's `/audit-export` document offline.
34
89
  *
@@ -45,23 +100,42 @@ export function verifyAuditExport(exportData, given = {}) {
45
100
  || (exportData.entries !== undefined && exportData.entries !== null && !Array.isArray(exportData.entries))) {
46
101
  throw new TypeError('Expected an /audit-export document: { exportMetadata: { recordId, ... }, entries: [...] }.');
47
102
  }
103
+ const anchorDocuments = readAnchorDocumentsOption(options.anchorDocuments);
104
+ if (options.exportDate !== undefined && (typeof options.exportDate !== 'string' || Number.isNaN(rfc3339Ms(options.exportDate)))) {
105
+ throw new TypeError(`verifyAuditExport: exportDate must be an RFC 3339 instant such as 2026-12-04T10:00:00Z (got ${JSON.stringify(options.exportDate)}).`);
106
+ }
107
+ const suppliedSources = readAcknowledgementSources('verifyAuditExport', options.acknowledgements);
108
+ const complianceRecords = options.complianceRecords !== undefined ? readComplianceRecords(options.complianceRecords) : undefined;
109
+ const otherExport = auditVaultExportKind(exportData);
110
+ if (otherExport !== null)
111
+ throw new TypeError(NOT_A_RECORD_EXPORT[otherExport]);
48
112
  if ((options.trustAnchors === undefined || options.trustAnchors.length === 0)
49
113
  && options.distrustedKeys !== undefined && options.distrustedKeys.length > 0) {
50
114
  throw new TypeError('distrustedKeys act only inside the key-statement walk, which runs from trustAnchors; pass trustAnchors as well.');
51
115
  }
52
116
  assertNotPinnedAndDistrusted(options.trustAnchors, options.distrustedKeys);
117
+ if (options.expectedEntryCount !== undefined
118
+ && !(typeof options.expectedEntryCount === 'number' && Number.isInteger(options.expectedEntryCount) && options.expectedEntryCount >= 0)) {
119
+ throw new TypeError(`verifyAuditExport: expectedEntryCount must be a non-negative integer (got ${JSON.stringify(options.expectedEntryCount)}).`);
120
+ }
121
+ // Caller-supplied keys are refused before the export is read, so a bad option
122
+ // is reported as such whatever the input holds.
123
+ const agentKeys = options.agentKeys !== undefined ? buildAgentKeyRegistry(options.agentKeys) : undefined;
124
+ const federationKeys = options.federationKeys !== undefined ? buildFederationKeyRegistry(options.federationKeys) : undefined;
53
125
  const meta = exportData.exportMetadata;
54
126
  const entries = exportData.entries ?? [];
55
- if (meta.exportFormatVersion && meta.exportFormatVersion !== SUPPORTED_FORMAT_VERSION) {
56
- return earlyFailure(meta.recordId, entries.length, `Unsupported exportFormatVersion ${meta.exportFormatVersion} (this verifier reads ${SUPPORTED_FORMAT_VERSION}).`);
127
+ if (meta.exportFormatVersion !== SUPPORTED_FORMAT_VERSION) {
128
+ return earlyFailure(meta.recordId, entries.length, meta.exportFormatVersion === undefined || meta.exportFormatVersion === null || meta.exportFormatVersion === ''
129
+ ? `The export states no exportFormatVersion (this verifier reads ${SUPPORTED_FORMAT_VERSION}).`
130
+ : `Unsupported exportFormatVersion ${JSON.stringify(meta.exportFormatVersion)} (this verifier reads ${SUPPORTED_FORMAT_VERSION}).`);
57
131
  }
58
- if (meta.canonicalization && meta.canonicalization !== SUPPORTED_CANONICALIZATION) {
59
- return earlyFailure(meta.recordId, entries.length, `Unsupported canonicalization ${meta.canonicalization} (only ${SUPPORTED_CANONICALIZATION} supported).`);
132
+ if (meta.canonicalization !== SUPPORTED_CANONICALIZATION) {
133
+ return earlyFailure(meta.recordId, entries.length, meta.canonicalization === undefined || meta.canonicalization === null || meta.canonicalization === ''
134
+ ? `The export states no canonicalization (only ${SUPPORTED_CANONICALIZATION} supported).`
135
+ : `Unsupported canonicalization ${JSON.stringify(meta.canonicalization)} (only ${SUPPORTED_CANONICALIZATION} supported).`);
60
136
  }
61
137
  const resolvedKeys = resolveKeys(exportData, options);
62
138
  let keys = buildKeyRegistry(resolvedKeys);
63
- const agentKeys = options.agentKeys !== undefined ? buildAgentKeyRegistry(options.agentKeys) : undefined;
64
- const federationKeys = options.federationKeys !== undefined ? buildFederationKeyRegistry(options.federationKeys) : undefined;
65
139
  // An empty trustAnchors is the same as none: no walk, keyTrust 'no_anchor'.
66
140
  const trust = options.trustAnchors !== undefined && options.trustAnchors.length > 0
67
141
  ? computeKeyTrust({
@@ -73,7 +147,7 @@ export function verifyAuditExport(exportData, given = {}) {
73
147
  : null;
74
148
  if (trust !== null)
75
149
  keys = applyKeyTrust(keys, trust);
76
- // When the install began signing, for CHAIN_ENTRY_UNSIGNED. The engine reads
150
+ // When the install began signing, for CHAIN_ENTRY_UNSIGNED. The Server reads
77
151
  // it as min(activated_at) over its whole key registry, retired keys included,
78
152
  // and `signingKeyWindows` publishes that whole registry. So the instant is
79
153
  // taken over every key the verifier holds (with each key's window resolved
@@ -91,7 +165,16 @@ export function verifyAuditExport(exportData, given = {}) {
91
165
  const signedActivations = trust === null ? [] : [...trust.byDigest.values()].filter((k) => k.trusted);
92
166
  const signingSince = earliestKeyActivation([...resolvedKeys, ...windowOnly, ...signedActivations]);
93
167
  const walkReport = reportKeyTrust(keys, trust, meta.anchoredFrom ?? null);
94
- const normalized = entries.map((raw) => {
168
+ if (!isVerifyingAsIfHostComputed())
169
+ READINGS.get(exportData)?.keys?.(keys, signingSince);
170
+ // An entry's `payload` and `entryType` are what the binding check and the
171
+ // federation-wire check read. Once any entry carries them, or the caller
172
+ // supplied federation keys, an entry without them is a check that cannot
173
+ // run on it, which is a failure and not a skip.
174
+ const carriesBinding = (raw) => isRecord(raw) && (raw.payload !== undefined || raw.entryType !== undefined);
175
+ const bindingExpected = options.federationKeys !== undefined || entries.some(carriesBinding);
176
+ const entryReadTimes = READINGS.get(exportData)?.entryReadTimes;
177
+ const normalized = entries.map((raw, index) => {
95
178
  // An entry or integrity block that is not an object carries none of the
96
179
  // fields the walk reads, and fails CHAIN_MALFORMED_ENTRY there.
97
180
  const e = isRecord(raw) ? raw : {};
@@ -105,8 +188,12 @@ export function verifyAuditExport(exportData, given = {}) {
105
188
  signingKeyId: integrity.signingKeyId,
106
189
  createdAt: e.createdAt,
107
190
  };
191
+ if (integrity.batch !== undefined && integrity.batch !== null)
192
+ base.batch = integrity.batch;
193
+ if (entryReadTimes !== undefined)
194
+ base.batchPendingSince = batchPendingSinceOf(entryReadTimes[index] ?? null);
108
195
  // Binding-integrity: when the export carries the denormalized row `payload`
109
- // (engine ≥ v0.26.x), cross-check it against the predicate decoded from the
196
+ // (Server 0.26 and later), cross-check it against the predicate decoded from the
110
197
  // signed bytes, the export's own verificationGuide step 4. The threat is
111
198
  // post-export tampering of the human-readable `payload`/`criteria` view: an
112
199
  // attacker rewrites `payload` and leaves `coseSign1` intact. The verifier
@@ -118,6 +205,14 @@ export function verifyAuditExport(exportData, given = {}) {
118
205
  recordId: e.recordId ?? null,
119
206
  entryType: e.entryType,
120
207
  payload: e.payload,
208
+ extensionsProjected: true,
209
+ };
210
+ }
211
+ else if (bindingExpected) {
212
+ const missing = [e.payload === undefined ? 'payload' : null, e.entryType === undefined ? 'entryType' : null].filter((m) => m !== null).join(' and ');
213
+ base.bindingRequired = {
214
+ detail: `The entry carries no ${missing}, which the binding and federation-wire checks read: ${options.federationKeys !== undefined && !entries.some(carriesBinding) ? 'federationKeys were supplied' : 'other entries of this export carry it'}, so an entry without it cannot be checked.`,
215
+ federationWire: options.federationKeys !== undefined,
121
216
  };
122
217
  }
123
218
  // An inlined evidence body is unsigned; it is re-bound to the hash the
@@ -151,11 +246,40 @@ export function verifyAuditExport(exportData, given = {}) {
151
246
  }
152
247
  return base;
153
248
  });
249
+ // Batch heads are verified under the same keys as the entries. An entry
250
+ // with the batch marker and no proof is still waiting for its head only
251
+ // when it was written within the Server's grace of the export being cut;
252
+ // `exportDate` is the export's own word, so it can only excuse the last
253
+ // entries of a chain, which then read `pending` and count as unsigned.
254
+ const rawHeads = meta.batchHeads;
255
+ const batchHeads = buildBatchHeadRegistry(Array.isArray(rawHeads) ? rawHeads.filter(isRecord) : [], keys);
256
+ const batchPendingSince = batchPendingSinceOf(meta.exportDate);
257
+ // History seals: what an ML-DSA key signed over everything the classical
258
+ // keys before it wrote. Judged against the walk; with no walk, or a walk
259
+ // that trusts no ML-DSA key, no entry is held to one.
260
+ const rawSeals = meta.historySeals;
261
+ const sealRows = Array.isArray(rawSeals) ? rawSeals.filter(isRecord) : [];
262
+ const historySeals = planHistorySeals(sealRows, keys, trust);
263
+ const historySealProofs = new Map();
264
+ for (const row of sealRows) {
265
+ const id = row['id'];
266
+ if (typeof id !== 'string')
267
+ continue;
268
+ const proof = row['proof'];
269
+ historySealProofs.set(id.toLowerCase(), isRecord(proof) ? proof : null);
270
+ }
271
+ const reading = READINGS.get(exportData);
154
272
  const chain = verifyChain(normalized, keys, {
273
+ ...(reading?.slice !== undefined ? { slice: reading.slice } : {}),
274
+ batchHeads,
275
+ batchPendingSince,
276
+ historySeals,
277
+ historySealProofs,
155
278
  requireKeyId: options.requireKeyId,
156
279
  requireSuppliedKeys: options.requireSuppliedKeys,
157
280
  agentKeys,
158
281
  federationKeys,
282
+ allowAfterRetirement: options.allowAfterRetirement === true,
159
283
  signingSince,
160
284
  });
161
285
  // Under a walk every key a signature verifies against is anchored, so the
@@ -167,12 +291,124 @@ export function verifyAuditExport(exportData, given = {}) {
167
291
  // A finding on the key statements has no chain position; it is reported
168
292
  // at position 0, the place for findings that precede the walk.
169
293
  const registryFinding = keyTrust.findings[0];
170
- const brokenAt = chain.brokenAt
294
+ const count = statedEntryCount(meta, entries.length, options.expectedEntryCount);
295
+ const identity = reading?.identity !== undefined ? reading.identity(entries) : signedRecordId(meta.recordId, entries);
296
+ const checkpoint = verifyExportCheckpoint(meta.recordId, meta.checkpointEvidence, normalized, keys, signingSince);
297
+ const receipts = verifyExportReceipts(normalized.map((n, i) => {
298
+ const raw = entries[i];
299
+ const integrity = isRecord(raw) ? raw.integrity : undefined;
300
+ return { chainPosition: n.chainPosition, coseSign1: n.coseSign1, receipt: isRecord(integrity) ? integrity.receipt : undefined };
301
+ }), keys);
302
+ const positions = normalized.map((n) => n.chainPosition);
303
+ const coverage = verifyCheckpointCoverage(meta.checkpointEvidence, positions);
304
+ const supplied = verifyRewindAcknowledgements(suppliedSources.map((s) => s.item), identity.recordId, keys, signingSince, true);
305
+ const callerRead = options.exportDate !== undefined ? rfc3339Ms(options.exportDate) : null;
306
+ if (callerRead !== null)
307
+ assertReadAfterSigned(callerRead, options.exportDate, normalized, meta.checkpointEvidence);
308
+ const walkView = reading?.anchors !== undefined || supplied.acknowledgements.length > 0
309
+ ? { judgedThroughIat: null, ...reading?.anchors, acknowledgements: [...(reading?.anchors?.acknowledgements ?? []), ...supplied.acknowledgements] }
310
+ : undefined;
311
+ const bucket = verifyExportAnchors(identity.recordId, meta.checkpointEvidence, normalized, anchorDocuments, keys, signingSince, walkView, callerRead !== null ? { judgedThroughIat: Math.floor(callerRead / 1000) - 1 } : undefined);
312
+ const listed = reading?.listedCheckpoints !== undefined
313
+ ? judgeListedCheckpoints(identity.recordId, reading.listedCheckpoints.rows, normalized, keys, signingSince, reading.listedCheckpoints.view)
314
+ : null;
315
+ const readTimeFinding = statedReadTimeFinding(meta, normalized);
316
+ const attestation = verifyAttestations(identity.recordId, normalized.map((n, i) => {
317
+ const raw = entries[i];
318
+ const integrity = isRecord(raw) ? raw.integrity : undefined;
319
+ return { chainPosition: n.chainPosition, coseSign1: n.coseSign1, contentBinding: isRecord(integrity) ? integrity.contentBinding : undefined };
320
+ }), complianceRecords);
321
+ // Placed after every earlier export-level finding, so the break a result
322
+ // names on an export without these inputs is unchanged.
323
+ const evidenceFindings = [coverage.finding, readTimeFinding, ...supplied.findings, ...bucket.findings, ...attestation.findings, ...(listed?.findings ?? [])]
324
+ .flatMap((f) => (f !== undefined ? [{ position: f.position, code: f.code, detail: f.detail }] : []));
325
+ const firstBreak = chain.brokenAt
171
326
  ? { position: chain.brokenAt.position, code: chain.brokenAt.code, detail: chain.brokenAt.detail }
172
327
  : registryFinding
173
328
  ? { position: 0, code: registryFinding.code, detail: registryFinding.detail }
174
- : undefined;
175
- const valid = chain.valid && keyTrust.findings.length === 0;
329
+ : identity.finding ?? checkpoint.finding ?? count.finding ?? receipts.finding ?? evidenceFindings[0];
330
+ const valid = chain.valid && keyTrust.findings.length === 0 && count.finding === undefined && identity.finding === undefined
331
+ && checkpoint.finding === undefined && receipts.finding === undefined && evidenceFindings.length === 0;
332
+ const failureCodes = [
333
+ ...chain.entries.flatMap((r) => (r.failure !== undefined ? [r.failure.code] : [])),
334
+ ...keyTrust.findings.map((f) => f.code),
335
+ ...[identity.finding, checkpoint.finding, count.finding, receipts.finding].flatMap((f) => (f !== undefined ? [f.code] : [])),
336
+ ...evidenceFindings.map((f) => f.code),
337
+ ];
338
+ // Every signature check that could not be computed: the failures that say
339
+ // so, and the key statements the walk could not check (which are not
340
+ // failures of their own; what they leave unreached is).
341
+ const uncomputableCount = failureCodes.filter((c) => c === UNSUPPORTED).length + (trust?.statements.unverifiable ?? 0);
342
+ const algorithms = uncomputableCount === 0 ? [] : uncomputableAlgorithms([
343
+ ...[...keys.values()].map((k) => k.spkiBase64),
344
+ ...trustKeysOf(exportData, options).map((k) => k.publicKey),
345
+ ...(agentKeys?.values() ?? []),
346
+ ...[...(federationKeys?.values() ?? [])].flatMap((list) => list.map((k) => k.publicKey)),
347
+ ]);
348
+ // Under a pin this host can compute, a key is trusted only through
349
+ // signatures this host computed: the rerun assumes no key statement.
350
+ const anchorKeys = () => [
351
+ ...[...keys.values()].map((k) => k.spkiBase64),
352
+ ...trustKeysOf(exportData, options).map((k) => k.publicKey),
353
+ ];
354
+ const computableAnchor = () => hasComputableAnchor(options.trustAnchors ?? [], anchorKeys());
355
+ // A counterfactual rerun (see verifyAsIfHostComputed) reads only `valid`,
356
+ // so it takes no verdict of its own and runs no rerun of its own.
357
+ // The rerun's own result, when it ran: on a failed result its first break
358
+ // is one the host's refusals do not explain, by construction.
359
+ let rerun = null;
360
+ let pinUnmet = false;
361
+ const baseVerdict = isVerifyingAsIfHostComputed()
362
+ ? (valid ? 'unanchored' : 'failed')
363
+ : unverifiableVerdict({ valid, uncomputable: { count: uncomputableCount, algorithms }, passesIfComputed: () => {
364
+ rerun = verifyAsIfHostComputed(() => verifyAuditExport(exportData, given), { statements: !computableAnchor() });
365
+ if (rerun.valid)
366
+ return true;
367
+ // A pin that names no key here anchors nothing on any host. Where
368
+ // every check computes, that reads `unanchored` when the input
369
+ // passes without the pin (see verdictOf); where this host refused
370
+ // checks, it reads `unverifiable` when the input would pass without
371
+ // the pin had those checks verified. Nothing was refuted either way.
372
+ // An input that passes on this host without the pin is `unanchored`
373
+ // by verdictOf below, as on any host; this reading is for the one
374
+ // that does not.
375
+ const { trustAnchors: _pinned, distrustedKeys: _distrusted, ...unpinned } = given;
376
+ pinUnmet = !computableAnchor() && pinReachesNoKey(rerun.keyTrust)
377
+ && !verifyAuditExport(exportData, unpinned).valid
378
+ && verifyAsIfHostComputed(() => verifyAuditExport(exportData, unpinned).valid);
379
+ return pinUnmet;
380
+ } }, () => sealedVerdict(verdictOf({ valid, keyTrust }, () => {
381
+ const { trustAnchors: _pinned, distrustedKeys: _distrusted, ...unpinned } = options;
382
+ return verifyAuditExport(exportData, unpinned).valid;
383
+ }, (trustAnchors) => verifyAuditExport(exportData, { ...options, trustAnchors }).valid), chain.historySeal));
384
+ const capped = [...bucket.anchors.capped, ...(listed?.capped ?? [])].map((detail) => ({ reason: 'read_time_not_given', detail }));
385
+ const verdict = capVerdict(baseVerdict, capped);
386
+ // After every rerun above, so the outer run's report is the last one given.
387
+ if (listed !== null)
388
+ reading?.listedCheckpoints?.report(listed.heldTo);
389
+ const belowFloor = runtimeBelowFloor();
390
+ const uncomputable = {
391
+ count: uncomputableCount,
392
+ algorithms,
393
+ consequences: verdict === 'unverifiable' ? [...new Set(failureCodes.filter((c) => c !== UNSUPPORTED))] : [],
394
+ ...(verdict === 'unverifiable'
395
+ ? computableAnchor()
396
+ ? { assumed: 'data' }
397
+ : { assumed: 'data-and-key-statements', anchorAlgorithms: anchorAlgorithms(options.trustAnchors ?? [], anchorKeys()), ...(pinUnmet ? { pinUnmet: true } : {}) }
398
+ : {}),
399
+ };
400
+ // On a failed result the break named is the first one that is not a check
401
+ // this host or build could not compute; those are summed up in
402
+ // `uncomputable`. Where this run found none, the rerun's first break names
403
+ // what failed with the refused checks assumed; where neither did (a key of
404
+ // a type this build cannot compute, which the input alone asserts), the
405
+ // first of them stands.
406
+ const rerunBreak = rerun?.brokenAt;
407
+ const brokenAt = verdict === 'failed' && firstBreak?.code === UNSUPPORTED
408
+ ? firstRefutation(chain.entries, keyTrust.findings, [identity.finding, checkpoint.finding, count.finding, receipts.finding, ...evidenceFindings])
409
+ ?? (rerunBreak !== undefined && rerunBreak.code !== UNSUPPORTED ? rerunBreak : undefined)
410
+ ?? firstBreak
411
+ : firstBreak;
176
412
  return {
177
413
  valid,
178
414
  totalEntries: chain.totalEntries,
@@ -185,19 +421,200 @@ export function verifyAuditExport(exportData, given = {}) {
185
421
  detail: r.failure?.detail,
186
422
  signature: r.signature,
187
423
  })),
188
- recordId: meta.recordId,
424
+ recordId: identity.recordId,
189
425
  signatureCoverage: chain.signatureCoverage,
190
- optionalChecks: chain.optionalChecks,
426
+ optionalChecks: {
427
+ ...chain.optionalChecks,
428
+ entry_count: count.applied ? 'applied' : 'skipped_no_input',
429
+ checkpoint_evidence: checkpoint.applicability,
430
+ receipts: receipts.applicability,
431
+ anchors: bucket.anchors.applicability,
432
+ attestation_bodies: attestation.report.applicability,
433
+ },
191
434
  keyProvenance: chain.keyProvenance,
192
435
  unsignedProjectionFields: exportData.verificationGuide?.unsignedFields ?? [],
193
436
  agentSignatures: chain.agentSignatures,
194
437
  federationWire: chain.federationWire,
195
438
  evidenceBinding: chain.evidenceBinding,
439
+ historySeal: chain.historySeal,
440
+ entryCount: count.entryCount,
441
+ checkpointEvidence: checkpoint.report,
442
+ receipts: receipts.counts,
443
+ checkpointCoverage: coverage.report,
444
+ acknowledgedRewinds: bucket.acknowledgedRewinds,
445
+ anchors: bucket.anchors,
446
+ suppliedAcknowledgements: supplied.report,
447
+ capped,
448
+ attestations: attestation.report,
196
449
  keyTrust,
197
- verdict: verdictOf({ valid, keyTrust }),
450
+ uncomputable,
451
+ ...(belowFloor !== null ? { runtime: belowFloor } : {}),
452
+ verdict,
453
+ };
454
+ }
455
+ const UNSUPPORTED = 'CHAIN_UNSUPPORTED_ALGORITHM';
456
+ /**
457
+ * The first failure that is not a signature check this host or build could not
458
+ * compute: the first such entry, else the first such key-statement finding (at
459
+ * position 0), else the first such export-level finding. Undefined when every
460
+ * failure is one of those.
461
+ */
462
+ function firstRefutation(entries, findings, others) {
463
+ const entry = entries.find((e) => e.failure !== undefined && e.failure.code !== UNSUPPORTED);
464
+ if (entry?.failure !== undefined)
465
+ return { position: entry.position, code: entry.failure.code, detail: entry.failure.detail };
466
+ const finding = findings.find((f) => f.code !== UNSUPPORTED);
467
+ if (finding !== undefined)
468
+ return { position: 0, code: finding.code, detail: finding.detail };
469
+ return others.find((f) => f !== undefined && f.code !== UNSUPPORTED);
470
+ }
471
+ /**
472
+ * Hold the chain's length to the counts the export states. A chain that was
473
+ * cut from the end still links and verifies entry by entry, so its length is
474
+ * the only thing that shows the cut: against the latest checkpoint position
475
+ * (a chain shorter than its checkpoint lost rows below it) and against the number of
476
+ * entries the Server wrote. A count that is present and is not a non-negative
477
+ * integer is refused rather than skipped.
478
+ */
479
+ function statedEntryCount(meta, held, supplied) {
480
+ const read = (name) => {
481
+ const value = meta[name];
482
+ if (value === undefined || value === null)
483
+ return null;
484
+ return typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : 'malformed';
198
485
  };
486
+ const expected = read('expectedEntries');
487
+ const stated = read('totalEntries');
488
+ const entryCount = {
489
+ expectedEntries: expected === 'malformed' ? null : expected,
490
+ statedEntries: stated === 'malformed' ? null : stated,
491
+ };
492
+ for (const [name, value] of [['expectedEntries', expected], ['totalEntries', stated]]) {
493
+ if (value === 'malformed') {
494
+ return {
495
+ entryCount,
496
+ applied: true,
497
+ finding: { position: 0, code: 'UNSUPPORTED_FORMAT', detail: `exportMetadata.${name} is ${JSON.stringify(meta[name])}, not a non-negative integer or null, so the chain's length cannot be held to it.` },
498
+ };
499
+ }
500
+ }
501
+ if (supplied !== undefined && held !== supplied) {
502
+ return {
503
+ entryCount,
504
+ applied: true,
505
+ finding: {
506
+ position: Math.min(held, supplied) + 1,
507
+ code: 'CHAIN_POSITION_GAP',
508
+ detail: `The export carries ${held} ${held === 1 ? 'entry' : 'entries'} and expectedEntryCount, supplied by the caller, is ${supplied}: ${held < supplied ? 'entries were removed from the end' : 'entries were added past the end'} of the chain.`,
509
+ },
510
+ };
511
+ }
512
+ if (entryCount.expectedEntries !== null && held < entryCount.expectedEntries) {
513
+ return {
514
+ entryCount,
515
+ applied: true,
516
+ finding: {
517
+ position: entryCount.expectedEntries,
518
+ code: 'CHECKPOINT_ROW_MISSING',
519
+ detail: `The export states a signed checkpoint at position ${entryCount.expectedEntries} and carries ${held} ${held === 1 ? 'entry' : 'entries'}: the chain was cut below its checkpoint.`,
520
+ },
521
+ };
522
+ }
523
+ if (entryCount.statedEntries !== null && held < entryCount.statedEntries) {
524
+ return {
525
+ entryCount,
526
+ applied: true,
527
+ finding: {
528
+ position: held + 1,
529
+ code: 'CHAIN_POSITION_GAP',
530
+ detail: `The export states ${entryCount.statedEntries} entries and carries ${held}: entries were removed from the end after the Server wrote it.`,
531
+ },
532
+ };
533
+ }
534
+ return { entryCount, applied: supplied !== undefined || entryCount.expectedEntries !== null || entryCount.statedEntries !== null };
199
535
  }
200
- const EXPORT_OPTIONS = ['publicKeys', 'requireKeyId', 'requireSuppliedKeys', 'trustAnchors', 'distrustedKeys', 'agentKeys', 'federationKeys'];
536
+ /**
537
+ * The record id the export is about, taken from what it signs. The id in
538
+ * `exportMetadata` is unsigned, so it is held to the id each entry's signed
539
+ * predicate names and to the entry's own `recordId` column: any disagreement,
540
+ * among the entries or with the metadata, fails CHAIN_PAYLOAD_BINDING_MISMATCH,
541
+ * and the id reported is the signed one, never the metadata's.
542
+ */
543
+ export function signedRecordId(stated, entries) {
544
+ const seen = [];
545
+ entries.forEach((raw, i) => {
546
+ if (!isRecord(raw))
547
+ return;
548
+ const position = typeof raw.chainPosition === 'number' ? raw.chainPosition : typeof raw.position === 'number' ? raw.position : i + 1;
549
+ if (typeof raw.recordId === 'string')
550
+ seen.push({ id: raw.recordId, position, source: 'its recordId column' });
551
+ const integrity = raw.integrity;
552
+ if (!isRecord(integrity) || typeof integrity.coseSign1 !== 'string')
553
+ return;
554
+ const parts = decodeCoseSign1(Buffer.from(integrity.coseSign1, 'base64'));
555
+ const signed = parts === null ? null : decodePredicate(parts.payloadBstr)?.['record_id'];
556
+ if (typeof signed === 'string')
557
+ seen.push({ id: signed, position, source: 'its signed predicate' });
558
+ });
559
+ const statedId = typeof stated === 'string' ? stated : '';
560
+ const first = seen.find((s) => s.source === 'its signed predicate') ?? seen[0];
561
+ if (first === undefined)
562
+ return { recordId: statedId };
563
+ const same = (a, b) => a.toLowerCase() === b.toLowerCase();
564
+ const other = seen.find((s) => !same(s.id, first.id));
565
+ if (other === undefined && same(statedId, first.id))
566
+ return { recordId: first.id };
567
+ return {
568
+ recordId: first.id,
569
+ finding: {
570
+ position: (other ?? first).position,
571
+ code: 'CHAIN_PAYLOAD_BINDING_MISMATCH',
572
+ detail: other !== undefined
573
+ ? `The entries of this export name different records: ${first.id} (${first.source}) and ${other.id} (${other.source}).`
574
+ : `The entries of this export are about record ${first.id} (${first.source}) and exportMetadata.recordId says ${JSON.stringify(stated)}: the unsigned metadata was edited.`,
575
+ },
576
+ };
577
+ }
578
+ /**
579
+ * Resolve `publicKeys`, `trustAnchors` and `distrustedKeys` exactly as
580
+ * `verifyAuditExport` does for an export that embeds no key of its own: the
581
+ * same shapes accepted (the `/v1/verification-keys` body included), the same
582
+ * `TypeError`s at the boundary, the same walk from the anchors over the
583
+ * statements the supplied keys carry. Internal to this package: the read-log
584
+ * reader verifies documents that carry no keys with it.
585
+ */
586
+ export function suppliedKeyContext(fn, given) {
587
+ const options = isKeysEnvelope(given.publicKeys) ? { ...given, publicKeys: given.publicKeys.data } : { ...given };
588
+ if ((options.trustAnchors === undefined || options.trustAnchors.length === 0)
589
+ && options.distrustedKeys !== undefined && options.distrustedKeys.length > 0) {
590
+ throw new TypeError(`${fn}: distrustedKeys act only inside the key-statement walk, which runs from trustAnchors; pass trustAnchors as well.`);
591
+ }
592
+ assertNotPinnedAndDistrusted(options.trustAnchors, options.distrustedKeys);
593
+ // Refused here under the caller's own name, before the shared resolution reads them.
594
+ normalizeSuppliedKeys(options.publicKeys, fn);
595
+ const bare = { exportMetadata: { recordId: '' }, entries: [] };
596
+ const resolved = resolveKeys(bare, options);
597
+ let keys = buildKeyRegistry(resolved);
598
+ const trust = options.trustAnchors !== undefined && options.trustAnchors.length > 0
599
+ ? computeKeyTrust({
600
+ keys: trustKeysOf(bare, options),
601
+ statements: trustStatementsOf(bare, options),
602
+ trustAnchors: options.trustAnchors,
603
+ ...(options.distrustedKeys !== undefined ? { distrustedKeys: options.distrustedKeys } : {}),
604
+ })
605
+ : null;
606
+ if (trust !== null)
607
+ keys = applyKeyTrust(keys, trust);
608
+ const signedActivations = trust === null ? [] : [...trust.byDigest.values()].filter((k) => k.trusted);
609
+ return {
610
+ keys,
611
+ trust,
612
+ signingSince: earliestKeyActivation([...resolved, ...signedActivations]),
613
+ walkReport: reportKeyTrust(keys, trust, null),
614
+ publicKeys: resolved.map((k) => k.spkiBase64),
615
+ };
616
+ }
617
+ const EXPORT_OPTIONS = ['publicKeys', 'requireKeyId', 'requireSuppliedKeys', 'trustAnchors', 'distrustedKeys', 'agentKeys', 'federationKeys', 'allowAfterRetirement', 'expectedEntryCount', 'anchorDocuments', 'complianceRecords', 'exportDate', 'acknowledgements'];
201
618
  function isKeysEnvelope(value) {
202
619
  return isRecord(value) && Array.isArray(value.data);
203
620
  }
@@ -258,6 +675,91 @@ function trustStatementsOf(exportData, options) {
258
675
  return rest;
259
676
  return all.map(({ createdAt: _c, ...s }) => s);
260
677
  }
678
+ /** The `anchorDocuments` option, held to its shape at the boundary. */
679
+ function readAnchorDocumentsOption(value) {
680
+ if (value === undefined)
681
+ return undefined;
682
+ if (!Array.isArray(value))
683
+ throw new TypeError('verifyAuditExport: anchorDocuments must be an array of { source, document, objectKey? }.');
684
+ return value.map((d, i) => {
685
+ if (!isRecord(d) || typeof d.source !== 'string' || !('document' in d) || (d.objectKey !== undefined && typeof d.objectKey !== 'string')) {
686
+ throw new TypeError(`verifyAuditExport: anchorDocuments[${i}] is not { source: string, document: <parsed JSON>, objectKey?: string }.`);
687
+ }
688
+ return d;
689
+ });
690
+ }
691
+ /** The Server's margin under a read time: `anchorsJudgedThroughIat` is the whole second of `evidenceReadAt` less this. */
692
+ const ANCHOR_JUDGE_MARGIN_SECONDS = 1;
693
+ /** The signed iat of each entry and of the embedded checkpoint, in position order, where one decodes. */
694
+ function signedTimes(entries, evidence) {
695
+ const out = [];
696
+ for (const e of entries) {
697
+ if (typeof e.coseSign1 !== 'string' || !Number.isSafeInteger(e.chainPosition))
698
+ continue;
699
+ const iat = decodeSignedClaim(Buffer.from(e.coseSign1, 'base64'))?.iat;
700
+ if (typeof iat === 'number' && Number.isFinite(iat))
701
+ out.push({ what: `the entry at position ${e.chainPosition}`, position: e.chainPosition, iat });
702
+ }
703
+ const cp = isRecord(evidence) && isRecord(evidence['checkpoint']) ? evidence['checkpoint'] : null;
704
+ if (cp !== null && typeof cp['coseSign1'] === 'string' && Number.isSafeInteger(cp['chainPosition'])) {
705
+ const iat = decodeSignedClaim(Buffer.from(cp['coseSign1'], 'base64'))?.iat;
706
+ if (typeof iat === 'number' && Number.isFinite(iat))
707
+ out.push({ what: `the embedded checkpoint at position ${String(cp['chainPosition'])}`, position: cp['chainPosition'], iat });
708
+ }
709
+ return out.sort((a, b) => a.position - b.position);
710
+ }
711
+ const isoOfIat = (iat) => {
712
+ const ms = iat * 1000;
713
+ return Number.isFinite(ms) && Math.abs(ms) <= 8.64e15 ? new Date(ms).toISOString() : String(iat);
714
+ };
715
+ /**
716
+ * Throw `TypeError` when the caller's read time is earlier than the signed
717
+ * iat of an entry or of the embedded checkpoint: what the export holds was
718
+ * signed after it, so it is not when the export was read. The iat is the
719
+ * whole second, rounded down, so a read in that same second still holds.
720
+ */
721
+ function assertReadAfterSigned(readMs, given, entries, evidence) {
722
+ const late = signedTimes(entries, evidence).find((t) => t.iat * 1000 > readMs);
723
+ if (late !== undefined) {
724
+ throw new TypeError(`verifyAuditExport: exportDate ${given} is earlier than ${late.what}, signed at iat ${late.iat} (${isoOfIat(late.iat)}): the export was read after that. Give the time the export was read.`);
725
+ }
726
+ }
727
+ /**
728
+ * Hold the read times the export states about itself to the signed iat of
729
+ * what it holds: `exportMetadata.exportDate` against every entry and the
730
+ * embedded checkpoint; `checkpointEvidence.evidenceReadAt` and
731
+ * `anchorsJudgedThroughIat` against the entries up to the block's
732
+ * `lastEntryPosition` (the ones it read) and its checkpoint. A stated time
733
+ * earlier than one of them is EXPORT_READ_TIME_INVALID at that entry.
734
+ */
735
+ function statedReadTimeFinding(meta, entries) {
736
+ const times = signedTimes(entries, meta.checkpointEvidence);
737
+ if (times.length === 0)
738
+ return undefined;
739
+ const ev = isRecord(meta.checkpointEvidence) ? meta.checkpointEvidence : null;
740
+ const lastRead = ev !== null && Number.isSafeInteger(ev['lastEntryPosition']) ? ev['lastEntryPosition'] : Infinity;
741
+ const checks = [];
742
+ const exportMs = typeof meta.exportDate === 'string' ? rfc3339Ms(meta.exportDate) : NaN;
743
+ if (!Number.isNaN(exportMs))
744
+ checks.push({ field: `exportMetadata.exportDate ${meta.exportDate}`, latestIat: Math.floor(exportMs / 1000), scope: 'all' });
745
+ const readAt = ev !== null && typeof ev['evidenceReadAt'] === 'string' ? rfc3339Ms(ev['evidenceReadAt']) : NaN;
746
+ if (!Number.isNaN(readAt))
747
+ checks.push({ field: `checkpointEvidence.evidenceReadAt ${String(ev?.['evidenceReadAt'])}`, latestIat: Math.floor(readAt / 1000), scope: 'block' });
748
+ const judged = ev?.['anchorsJudgedThroughIat'];
749
+ if (typeof judged === 'number' && Number.isSafeInteger(judged))
750
+ checks.push({ field: `checkpointEvidence.anchorsJudgedThroughIat ${judged}`, latestIat: judged + ANCHOR_JUDGE_MARGIN_SECONDS, scope: 'block' });
751
+ for (const c of checks) {
752
+ const late = times.find((t) => (c.scope === 'all' || t.position <= lastRead) && t.iat > c.latestIat);
753
+ if (late !== undefined) {
754
+ return {
755
+ position: late.position,
756
+ code: 'EXPORT_READ_TIME_INVALID',
757
+ detail: `The export states ${c.field}, and ${late.what} is signed at iat ${late.iat} (${isoOfIat(late.iat)}), later: the stated read time was moved earlier than the read, which can set aside an anchor that shows a cut.`,
758
+ };
759
+ }
760
+ }
761
+ return undefined;
762
+ }
261
763
  function earlyFailure(recordId, totalEntries, detail) {
262
764
  return {
263
765
  valid: false,
@@ -266,7 +768,7 @@ function earlyFailure(recordId, totalEntries, detail) {
266
768
  brokenAt: { position: 0, code: 'UNSUPPORTED_FORMAT', detail },
267
769
  entries: [{ position: 0, valid: false, code: 'UNSUPPORTED_FORMAT', detail }],
268
770
  recordId,
269
- signatureCoverage: { signed: 0, unsigned: 0, skipped: 0, total: totalEntries },
771
+ signatureCoverage: { signed: 0, unsigned: 0, skipped: 0, total: totalEntries, pending: 0, batched: 0 },
270
772
  optionalChecks: {
271
773
  payload_binding: 'skipped_no_input',
272
774
  oidc_actor: 'skipped_no_input',
@@ -276,13 +778,30 @@ function earlyFailure(recordId, totalEntries, detail) {
276
778
  key_anchoring: 'skipped_no_input',
277
779
  federation_wire: 'skipped_no_input',
278
780
  evidence_binding: 'skipped_no_input',
781
+ history_seal: 'skipped_no_input',
782
+ entry_count: 'skipped_no_input',
783
+ checkpoint_evidence: 'skipped_no_input',
784
+ receipts: 'skipped_no_input',
785
+ anchors: 'skipped_no_input',
786
+ attestation_bodies: 'skipped_no_input',
279
787
  },
280
788
  keyProvenance: { supplied: 0, embedded: 0 },
281
789
  unsignedProjectionFields: [],
282
790
  agentSignatures: { present: 0, verified: 0 },
283
791
  federationWire: { present: 0, verified: 0, failed: 0, afterRetirement: 0 },
284
792
  evidenceBinding: { present: 0, verified: 0, clientHashed: 0, failed: 0 },
793
+ historySeal: { sealed: 0, unsealed: 0, unsealedKeys: [] },
794
+ entryCount: { expectedEntries: null, statedEntries: null },
795
+ checkpointEvidence: { position: null, state: 'absent' },
796
+ receipts: { present: 0, verified: 0 },
797
+ checkpointCoverage: { applicability: 'skipped_no_input', checked: [] },
798
+ acknowledgedRewinds: { applicability: 'skipped_no_input', present: 0, verified: 0, items: [], linkChecked: false },
799
+ anchors: { applicability: 'skipped_no_input', chainKey: recordId, judgedThroughIat: null, verdicts: [], counts: { agree: 0, disagree: 0, accounted: 0, notComparable: 0 }, findings: [], capped: [], embeddedCheckpoint: null },
800
+ suppliedAcknowledgements: { applicability: 'skipped_no_input', present: 0, verified: 0, items: [], linkChecked: false },
801
+ capped: [],
802
+ attestations: { applicability: 'skipped_no_input', entries: [], otherRecords: [] },
285
803
  keyTrust: reportKeyTrust(new Map(), null, null),
804
+ uncomputable: { count: 0, algorithms: [], consequences: [] },
286
805
  verdict: 'failed',
287
806
  };
288
807
  }
@@ -312,7 +831,7 @@ function resolveKeys(exportData, options) {
312
831
  });
313
832
  }
314
833
  }
315
- // Attach activation/retirement windows from exportMetadata (engine ≥ v0.26.x).
834
+ // Attach activation/retirement windows from exportMetadata (Server 0.26 and later).
316
835
  // Older exports omit signingKeyWindows; keys stay without a window and
317
836
  // verifyChain reports `key_temporal` as `skipped_no_input`.
318
837
  const windows = meta.signingKeyWindows;
@@ -356,19 +875,19 @@ function resolveKeys(exportData, options) {
356
875
  * Returns `null` when no keys were supplied; otherwise an array of normalized
357
876
  * entries ready to merge into the registry.
358
877
  */
359
- function normalizeSuppliedKeys(publicKeys) {
878
+ function normalizeSuppliedKeys(publicKeys, fn = 'verifyAuditExport') {
360
879
  if (publicKeys === undefined || publicKeys === null)
361
880
  return null;
362
881
  if (Array.isArray(publicKeys)) {
363
882
  return publicKeys.map((entry, i) => {
364
883
  if (entry === null || typeof entry !== 'object') {
365
- throw new TypeError(`verifyAuditExport: publicKeys[${i}] is not an object (got ${typeof entry}). ` +
884
+ throw new TypeError(`${fn}: publicKeys[${i}] is not an object (got ${typeof entry}). ` +
366
885
  `Expected { keyId, publicKey } entries, e.g. the .data[] from client.verificationKeys.list().`);
367
886
  }
368
887
  const keyId = entry.keyId;
369
888
  const publicKey = entry.publicKey;
370
889
  if (typeof keyId !== 'string' || typeof publicKey !== 'string') {
371
- throw new TypeError(`verifyAuditExport: publicKeys[${i}] is missing required string fields { keyId, publicKey } ` +
890
+ throw new TypeError(`${fn}: publicKeys[${i}] is missing required string fields { keyId, publicKey } ` +
372
891
  `(got keyId=${typeof keyId}, publicKey=${typeof publicKey}). ` +
373
892
  `Expected the SDK VerificationKey shape: publicKey must be SPKI DER base64.`);
374
893
  }
@@ -379,7 +898,7 @@ function normalizeSuppliedKeys(publicKeys) {
379
898
  // is: one that is not would be read by the host's clock or not at all.
380
899
  for (const [edge, value] of [['activatedAt', activatedAt], ['retiredAt', retiredAt]]) {
381
900
  if (value !== undefined && value !== null && (typeof value !== 'string' || Number.isNaN(instantMs(value)))) {
382
- throw new TypeError(`verifyAuditExport: publicKeys[${i}] (key ${keyId}) has ${edge} ${JSON.stringify(value)}, which is not an RFC 3339 instant ` +
901
+ throw new TypeError(`${fn}: publicKeys[${i}] (key ${keyId}) has ${edge} ${JSON.stringify(value)}, which is not an RFC 3339 instant ` +
383
902
  '(2026-09-01T00:00:00.000Z: a T, an offset or Z, a real calendar date).');
384
903
  }
385
904
  }
@@ -391,13 +910,13 @@ function normalizeSuppliedKeys(publicKeys) {
391
910
  });
392
911
  }
393
912
  if (typeof publicKeys !== 'object') {
394
- throw new TypeError(`verifyAuditExport: publicKeys must be a Record<keyId, base64SpkiDer> or an array of ` +
913
+ throw new TypeError(`${fn}: publicKeys must be a Record<keyId, base64SpkiDer> or an array of ` +
395
914
  `{ keyId, publicKey } entries (got ${typeof publicKeys}).`);
396
915
  }
397
916
  const entries = [];
398
917
  for (const [keyId, value] of Object.entries(publicKeys)) {
399
918
  if (typeof value !== 'string') {
400
- throw new TypeError(`verifyAuditExport: publicKeys["${keyId}"] is not a base64 string (got ${typeof value}). ` +
919
+ throw new TypeError(`${fn}: publicKeys["${keyId}"] is not a base64 string (got ${typeof value}). ` +
401
920
  `If you passed the .data[] from client.verificationKeys.list(), pass it as an array, ` +
402
921
  `not via Object.fromEntries on the raw list.`);
403
922
  }