@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
@@ -0,0 +1,711 @@
1
+ /**
2
+ * Verify a walk of the bulk export, `GET /v1/audit-vault/export`: every page
3
+ * of one query, from the first to the one whose `nextCursor` is null.
4
+ *
5
+ * A page carries a slice of the vault in insertion order, the record chains
6
+ * interleaved, so one page usually ends inside several chains. The walk is
7
+ * the unit: its rows are grouped by `recordId`, each group is put in chain
8
+ * order and verified as a record export of those entries is (keys and their
9
+ * trust walk, signatures, links, signed claims, batch proofs, the payload
10
+ * binding with `on_behalf_of` and `traceparent` restored from the envelope,
11
+ * and the signed record id), with the key material of every page merged.
12
+ *
13
+ * A chain the walk holds from position 1, in a walk read to its end, gets
14
+ * the record export's verdict. One that starts above position 1 (a `from`
15
+ * filter, or a walk begun past its first page), or whose tip the walk does
16
+ * not establish (a walk that stops before its end), is a slice: its entries
17
+ * and the links between them are verified, the first entry's link to the
18
+ * entry before it is taken from the row, and the verdict reads at best
19
+ * `unanchored`. A query with a `to` bound ends every chain at that instant,
20
+ * so its chains are slices too. The bound is read from the walk's cursors,
21
+ * or from the page's `queryHash` (the hash of the query's filter) on a walk
22
+ * of one page, which carries no cursor; a walk whose pages establish neither
23
+ * holds every chain as a slice. A missing position inside the run is
24
+ * CHAIN_POSITION_GAP, as on a record export.
25
+ *
26
+ * Every chain is verified through the last position the walk holds of it,
27
+ * held there by the page content, or by a listed signed checkpoint of that
28
+ * position (`checkpoints`). A slice from position 1 whose last position such
29
+ * a checkpoint signs is whole through it.
30
+ *
31
+ * Each page states the instant the Server read it (`exportMetadata.exportDate`,
32
+ * taken after its entries and their batch proofs). A batched row served
33
+ * without a proof is judged against the read time of its own page, and
34
+ * anchors are judged through the latest page's.
35
+ */
36
+ import { createHash } from 'node:crypto';
37
+ import { anchorDocumentIat, compareCheckpointAnchors, pageAcknowledgementCopyDisagreement, verifyRewindAcknowledgements } from './anchors.js';
38
+ import { readAcknowledgementSources } from './acknowledgements.js';
39
+ import { signedRecordId, verifyExportChain } from './audit-export.js';
40
+ import { decodeSignedClaim } from './claim.js';
41
+ import { rfc3339Ms } from './instant.js';
42
+ import { schemaCheckpointKey } from './schema-chain-export.js';
43
+ import { PLATFORM_OPS_CHAIN_KEY } from './history-seal.js';
44
+ import { assertKnownOptions } from './options.js';
45
+ import { deepEqual } from './primitives.js';
46
+ import { assertWalkAnchorDocuments, groupAnchorDocuments, judgedThroughOf, judgedThroughSourceOf, platformOpsAcknowledgements, readCheckpointPages, walkAnchorsReport, } from './walk-anchors.js';
47
+ import { judgeListedCheckpoints, listedEnvelopeShas } from './walk-checkpoints.js';
48
+ import { assertExportDate, capSlice, chainOptions, cursorLinkReasons, cursorsStated, decodeCursor, entryOfRow, heldByPages, isRecord, latestReadTime, mergePageMetadata, assertWalkReadAfterSigned, pageReadTimeFindings, pageReadTimes, positionRange, readPages, walkResult, } from './export-pages.js';
49
+ const OPTIONS = ['publicKeys', 'requireKeyId', 'requireSuppliedKeys', 'trustAnchors', 'distrustedKeys', 'agentKeys', 'federationKeys', 'allowAfterRetirement', 'anchorDocuments', 'checkpoints', 'exportDate', 'acknowledgements'];
50
+ /** The keyset position before every entry: the cursor an empty first page returns. */
51
+ const UUIDV7_ORIGIN = '00000000-0000-7000-8000-000000000000';
52
+ const SCHEMA_ENTRY_TYPES = new Set(['SCHEMA_REGISTERED', 'SCHEMA_IMPORTED', 'SCHEMA_DIGEST_MISMATCH']);
53
+ /**
54
+ * Verify a walk of the bulk export offline.
55
+ *
56
+ * `pages` is the walk in page order: parsed JSON pages, or the NDJSON text
57
+ * of each page (`?format=ndjson`), or one string holding the NDJSON of every
58
+ * page one after another. A single page is read as a walk of one.
59
+ *
60
+ * Throws `TypeError` when the input holds no page or is not bulk export
61
+ * pages (a page of the schema-chain export names `verifySchemaChainExport`),
62
+ * on a malformed option, and on `expectedEntryCount`, which holds one chain and a walk holds
63
+ * many. A malformed entry inside a well-formed page is a failure on its
64
+ * chain, never a throw.
65
+ */
66
+ export function verifyBulkExport(pages, options = {}) {
67
+ if (isRecord(options) && 'expectedEntryCount' in options) {
68
+ throw new TypeError('verifyBulkExport: expectedEntryCount holds one chain\'s length, and a bulk walk holds many. Hold a record\'s chain to a count with its GET /v1/records/{id}/audit-export document and verifyAuditExport.');
69
+ }
70
+ assertKnownOptions('verifyBulkExport', options, OPTIONS);
71
+ assertExportDate('verifyBulkExport', options.exportDate);
72
+ assertWalkAnchorDocuments('verifyBulkExport', options.anchorDocuments);
73
+ const listed = readCheckpointPages('verifyBulkExport', options.checkpoints);
74
+ const givenSources = readAcknowledgementSources('verifyBulkExport', options.acknowledgements);
75
+ const read = readPages(pages, 'bulk', 'verifyBulkExport');
76
+ // The acknowledgements the pages carry (Server 4.0.0, to every caller),
77
+ // then those the caller gave, each once by entryId. A page's item whose
78
+ // unsigned coveredRanges are not its signed coveredFindings for the chains
79
+ // that page holds fails, as on a record export, and covers nothing.
80
+ const copyFindings = [];
81
+ const badCopies = new Set();
82
+ read.forEach(({ page }, i) => {
83
+ const items = page.exportMetadata.acknowledgedRewinds;
84
+ if (!Array.isArray(items))
85
+ return;
86
+ const onPage = new Set(page.data.map((r) => (typeof r.recordId === 'string' ? r.recordId.toLowerCase() : '')).filter((k) => k !== ''));
87
+ items.forEach((item, j) => {
88
+ const why = pageAcknowledgementCopyDisagreement(item, onPage);
89
+ if (why === null)
90
+ return;
91
+ const entryId = isRecord(item) && typeof item['entryId'] === 'string' ? item['entryId'] : null;
92
+ if (entryId !== null)
93
+ badCopies.add(entryId.toLowerCase());
94
+ copyFindings.push({ code: 'REWIND_ACKNOWLEDGEMENT_INVALID', page: i + 1, detail: `Page ${i + 1} exportMetadata.acknowledgedRewinds[${j}] (RESTORE_EPOCH ${entryId ?? 'with no entryId'}): ${why}. It covers nothing.` });
95
+ });
96
+ });
97
+ const pageSources = readAcknowledgementSources('verifyBulkExport', read.flatMap(({ page }) => Array.isArray(page.exportMetadata.acknowledgedRewinds) ? [page.exportMetadata.acknowledgedRewinds] : []))
98
+ .filter((x) => !badCopies.has(String(x.item.entryId).toLowerCase()));
99
+ const pageAckIds = new Set(pageSources.map((x) => String(x.item.entryId).toLowerCase()));
100
+ const suppliedSources = [...pageSources, ...givenSources.filter((x) => !pageAckIds.has(String(x.item.entryId).toLowerCase()))];
101
+ const givenCount = suppliedSources.length - pageSources.length;
102
+ if (read.length === 0)
103
+ throw new TypeError('verifyBulkExport: the input holds no page.');
104
+ assertWalkReadAfterSigned('verifyBulkExport', options.exportDate, read.map((r) => r.page));
105
+ const merged = mergePageMetadata(read.map((r) => r.page));
106
+ const findings = [...merged.findings, ...pageReadTimeFindings(read.map((r) => r.page)), ...copyFindings];
107
+ const incomplete = [];
108
+ const notes = [];
109
+ // The rows, each once, by chain in the order the walk first reaches it.
110
+ const byId = new Map();
111
+ // The page each row kept was served on (0-based), for its read time.
112
+ const rowPage = new Map();
113
+ const groups = new Map();
114
+ let lastId = null;
115
+ let cursorScope = null;
116
+ // An upper time bound on the query (its `to`, which every cursor of the
117
+ // walk carries) ends each chain at an instant rather than at its tip.
118
+ let upTo = null;
119
+ read.forEach(({ page }, i) => {
120
+ const n = i + 1;
121
+ let outOfOrder = false;
122
+ page.data.forEach((row, j) => {
123
+ const id = typeof row.id === 'string' ? row.id.toLowerCase() : null;
124
+ if (id !== null) {
125
+ const seen = byId.get(id);
126
+ if (seen !== undefined) {
127
+ if (deepEqual(seen.row, row))
128
+ incomplete.push(`Entry ${row.id} is on page ${seen.page} and on page ${n}: the pages overlap, so they are not one walk.`);
129
+ else
130
+ findings.push({ code: 'EXPORT_PAGE_CONFLICT', page: n, detail: `Entry ${row.id} on page ${n} differs from the entry with that id on page ${seen.page}.` });
131
+ return;
132
+ }
133
+ byId.set(id, { row, page: n });
134
+ if (lastId !== null && id <= lastId)
135
+ outOfOrder = true;
136
+ lastId = id;
137
+ }
138
+ if (typeof row.recordId !== 'string' || row.recordId === '') {
139
+ findings.push({ code: 'CHAIN_MALFORMED_ENTRY', page: n, detail: `Page ${n} data[${j}]${id === null ? '' : ` (entry ${row.id})`} carries no recordId, so it is on no record chain.` });
140
+ return;
141
+ }
142
+ const key = row.recordId.toLowerCase();
143
+ const group = groups.get(key) ?? new Map();
144
+ groups.set(key, group);
145
+ const at = Number.isSafeInteger(row.chainPosition) ? row.chainPosition : `row ${n}:${j}`;
146
+ const other = group.get(at);
147
+ if (other !== undefined) {
148
+ findings.push({ code: 'EXPORT_PAGE_CONFLICT', page: n, detail: `Record ${row.recordId} holds two different entries at position ${String(at)}: ${String(other.id)} and ${String(row.id)}.` });
149
+ return;
150
+ }
151
+ group.set(at, row);
152
+ rowPage.set(row, i);
153
+ });
154
+ if (outOfOrder)
155
+ incomplete.push(`The entries through page ${n} are not in the order the Server serves them (ascending entry id): the pages are out of order or not from one walk.`);
156
+ const last = i === read.length - 1;
157
+ const ends = page.nextCursor === null && page.hasMore !== true && page.heldBack !== true;
158
+ if ((page.hasMore === true && page.nextCursor === null) || (page.hasMore === false && page.nextCursor !== null)) {
159
+ incomplete.push(`Page ${n} states hasMore ${String(page.hasMore)} with nextCursor ${page.nextCursor === null ? 'null' : 'set'}; the Server sets nextCursor exactly when more entries follow.`);
160
+ }
161
+ if (!last && ends) {
162
+ incomplete.push(`Page ${n} ends the walk (nextCursor null), and ${read.length - n} more page${read.length - n === 1 ? '' : 's'} follow${read.length - n === 1 ? 's' : ''} it: they are not one walk.`);
163
+ }
164
+ if (last && !ends) {
165
+ incomplete.push(page.heldBack === true
166
+ ? `The last page was held back: entries were written above the Server's visibility ceiling and were not yet readable. Request its nextCursor again${typeof page.retryAfterSeconds === 'number' ? ` after ${page.retryAfterSeconds} seconds` : ''} and add the pages that follow.`
167
+ : 'The last page has a nextCursor: more entries follow it. Request the pages that follow and verify the whole walk.');
168
+ }
169
+ if (typeof page.nextCursor === 'string') {
170
+ const cursor = decodeCursor(page.nextCursor);
171
+ if (cursor === null || typeof cursor['after_id'] !== 'string') {
172
+ notes.push(`Page ${n}'s nextCursor does not decode as the Server's keyset cursor, so it was not compared with the page's last entry.`);
173
+ }
174
+ else {
175
+ const expected = lastId ?? UUIDV7_ORIGIN;
176
+ if (cursor['after_id'].toLowerCase() !== expected) {
177
+ incomplete.push(`Page ${n}'s nextCursor resumes after entry ${cursor['after_id']}, and the last entry read through page ${n} is ${expected}: the pages are not one walk.`);
178
+ }
179
+ const { after_id: _position, ...rest } = cursor;
180
+ if (typeof rest['to'] === 'string')
181
+ upTo = rest['to'];
182
+ const scope = JSON.stringify(Object.keys(rest).sort().map((k) => [k, rest[k]]));
183
+ if (cursorScope === null)
184
+ cursorScope = { page: n, scope };
185
+ else if (cursorScope.scope !== scope) {
186
+ incomplete.push(`Page ${n}'s nextCursor was issued for another query than page ${cursorScope.page}'s: the pages are not one walk.`);
187
+ }
188
+ }
189
+ }
190
+ });
191
+ incomplete.push(...cursorLinkReasons(read.map((r) => r.page), notes));
192
+ const cursors = cursorsStated(read.map((r) => r.page));
193
+ const query = walkQuery(read.map((r) => r.page), groups);
194
+ // Whether the walk reaches its end as one walk: what establishes each
195
+ // chain's tip.
196
+ const tailComplete = incomplete.length === 0;
197
+ // A chain that starts above position 1 on a walk with no from bound shows
198
+ // a page missing before the one it starts on. That leaves the tips of the
199
+ // other chains where they were, and the walk is still not every page.
200
+ if (query.established && query.filter?.from == null) {
201
+ for (const [chainKey, group] of groups) {
202
+ const first = positionRange([...group.values()])?.first ?? 1;
203
+ if (first > 1)
204
+ incomplete.push(`Chain ${chainKey} starts at position ${first} on a walk with no from bound: the page${first === 2 ? '' : 's'} holding position${first === 2 ? '' : 's'} 1${first === 2 ? '' : ` to ${first - 1}`} of it ${first === 2 ? 'is' : 'are'} missing.`);
205
+ }
206
+ }
207
+ const complete = incomplete.length === 0;
208
+ const entries = [...groups.values()].reduce((sum, g) => sum + g.size, 0);
209
+ const readTimes = pageReadTimes(read.map((r) => r.page), options.exportDate, notes);
210
+ const walkRead = latestReadTime(readTimes);
211
+ if (options.exportDate !== undefined && readTimes.every((t) => t.source === 'pages')) {
212
+ notes.push(`exportDate ${options.exportDate} was given, and every page states its own read time (exportMetadata.exportDate): each page was read at its own.`);
213
+ }
214
+ const rowReadTimes = (rows) => rows.map((r) => readTimes[rowPage.get(r) ?? -1] ?? { exportDate: null, source: null });
215
+ if (query.filter?.to != null)
216
+ upTo = query.filter.to;
217
+ const plans = [];
218
+ for (const [chainKey, group] of groups) {
219
+ const rows = [...group.values()];
220
+ const range = positionRange(rows);
221
+ const start = range?.first ?? 1;
222
+ const tip = !tailComplete
223
+ ? 'The walk does not end at a null nextCursor, or shows a page missing (see walk.incomplete), so the chain\'s tip is not established.'
224
+ : upTo !== null
225
+ ? `The query reads entries written up to ${upTo} (its to filter), so the chain's tip is not established.`
226
+ : !query.established
227
+ ? 'The pages do not establish the query (see query), and a to bound ends every chain at an instant, so the chain\'s tip is not established.'
228
+ : null;
229
+ const sliceReason = start > 1
230
+ ? `The walk holds positions ${start} to ${range?.last ?? start} of this chain; ${start === 2 ? 'position 1 is' : `positions 1 to ${start - 1} are`} not in it (a from filter, or a walk begun past its first page).${tip === null ? '' : ` ${tip}`}`
231
+ : tip ?? undefined;
232
+ const startRow = rows.find((r) => r.chainPosition === start);
233
+ plans.push({
234
+ chainKey,
235
+ rows,
236
+ first: range?.first ?? 0,
237
+ last: range?.last ?? 0,
238
+ tipOpen: tip !== null,
239
+ sliceReason,
240
+ doc: {
241
+ exportMetadata: {
242
+ ...merged.meta,
243
+ recordId: rows[0]?.recordId ?? chainKey,
244
+ },
245
+ entries: rows.map(entryOfRow),
246
+ verificationGuide: { unsignedFields: merged.unsignedFields },
247
+ },
248
+ slice: start > 1 || tip !== null ? { startPosition: start, previousHash: start > 1 && typeof startRow?.previousHash === 'string' ? startRow.previousHash : null, openEnd: tip !== null } : undefined,
249
+ });
250
+ }
251
+ const documents = groupAnchorDocuments(options.anchorDocuments);
252
+ // The caller's read time first: the pages' own is unsigned.
253
+ const readTimeGiven = options.exportDate !== undefined;
254
+ const judgedThroughIat = judgedThroughOf(readTimeGiven ? options.exportDate : walkRead.exportDate);
255
+ const options$ = chainOptions(options);
256
+ let registry = null;
257
+ const captureKeys = (keys, signingSince) => {
258
+ registry ??= { keys, signingSince };
259
+ };
260
+ const verifyPlan = (plan, acknowledgements) => {
261
+ const docs = documents.byChain.get(plan.chainKey);
262
+ const rowsListed = listed?.get(plan.chainKey) ?? [];
263
+ let heldTo = heldByPages(plan.last);
264
+ const reading = {
265
+ ...(plan.slice !== undefined ? { slice: plan.slice } : {}),
266
+ entryReadTimes: rowReadTimes(plan.rows).map((t) => t.exportDate),
267
+ identity: (list) => recordChainIdentity(plan.doc.exportMetadata.recordId, list),
268
+ keys: captureKeys,
269
+ anchors: {
270
+ judgedThroughIat,
271
+ readTimeGiven,
272
+ ...(plan.sliceReason !== undefined ? { heldInPart: { ...(plan.first > 1 ? { firstHeld: plan.first } : {}), ...(plan.tipOpen ? { lastHeld: plan.last } : {}), reason: plan.sliceReason } } : {}),
273
+ acknowledgements,
274
+ checkpoints: listedEnvelopeShas(rowsListed),
275
+ },
276
+ ...(rowsListed.length > 0
277
+ ? { listedCheckpoints: { rows: rowsListed, view: { firstHeld: plan.first, lastHeld: plan.last, tipEstablished: !plan.tipOpen, judgedThroughIat, readTimeGiven }, report: (h) => { heldTo = h; } } }
278
+ : {}),
279
+ };
280
+ const result = verifyExportChain(plan.doc, { ...options$, ...(docs !== undefined ? { anchorDocuments: docs } : {}) }, reading);
281
+ return { result, heldTo };
282
+ };
283
+ // The platform-ops chain first: a walk that holds it whole holds the
284
+ // acknowledgements of lost history every other chain's anchors are read with.
285
+ const results = new Map();
286
+ let acknowledgements = [];
287
+ let ackSource;
288
+ const ops = plans.find((p) => p.chainKey === PLATFORM_OPS_CHAIN_KEY);
289
+ // Acknowledgements the caller gave, verified once under the walk's keys.
290
+ let supplied = verifyRewindAcknowledgements(undefined, PLATFORM_OPS_CHAIN_KEY, new Map(), null, true);
291
+ supplied = { ...supplied, report: { ...supplied.report, applicability: 'skipped_no_input' } };
292
+ const firstPlan = plans[0];
293
+ if (suppliedSources.length > 0 && firstPlan !== undefined) {
294
+ if (registry === null)
295
+ verifyPlan(firstPlan, []);
296
+ const reg = registry;
297
+ if (reg !== null)
298
+ supplied = verifyRewindAcknowledgements(suppliedSources.map((x) => x.item), PLATFORM_OPS_CHAIN_KEY, reg.keys, reg.signingSince, true);
299
+ }
300
+ if (ops === undefined) {
301
+ ackSource = { source: 'none', items: [], detail: 'The walk holds no platform-ops chain (a walk under an org admin key leaves it out), so no acknowledgement of lost history is in reach and none accounts for a disagreement.' };
302
+ }
303
+ else {
304
+ const firstRun = verifyPlan(ops, []);
305
+ const whole = ops.first === 1 && (!ops.tipOpen || (firstRun.heldTo.by === 'signed_checkpoint'));
306
+ if (!whole) {
307
+ ackSource = { source: 'none', items: [], detail: `The walk holds the platform-ops chain in part (positions ${ops.first} to ${ops.last}), so its acknowledgements of lost history are not established and none accounts for a disagreement.` };
308
+ results.set(ops.chainKey, firstRun);
309
+ }
310
+ else {
311
+ acknowledgements = platformOpsAcknowledgements(ops.rows, firstRun.result);
312
+ ackSource = {
313
+ source: 'platform-ops-chain',
314
+ items: acknowledgements.map((a) => ({ entryId: a.entryId, chainPosition: a.chainPosition, state: a.state, iat: a.iat })),
315
+ detail: `The walk holds the platform-ops chain whole (positions 1 to ${ops.last}); its RESTORE_EPOCH entries that verified with their links are the acknowledgements of lost history (${acknowledgements.length}).`,
316
+ };
317
+ results.set(ops.chainKey, documents.byChain.has(ops.chainKey) && acknowledgements.length > 0 ? verifyPlan(ops, acknowledgements) : firstRun);
318
+ }
319
+ }
320
+ const held = new Set(acknowledgements.map((a) => String(a.entryId).toLowerCase()));
321
+ const extra = supplied.acknowledgements.filter((a) => !held.has(String(a.entryId).toLowerCase()));
322
+ if (extra.length > 0) {
323
+ acknowledgements = [...acknowledgements, ...extra];
324
+ const fromPages = pageSources.length > 0;
325
+ const what = fromPages && givenCount > 0
326
+ ? 'carried on the pages (exportMetadata.acknowledgedRewinds) or given (acknowledgements)'
327
+ : fromPages ? 'carried on the pages (exportMetadata.acknowledgedRewinds)' : 'given (acknowledgements)';
328
+ const given = `${extra.length} acknowledgement${extra.length === 1 ? '' : 's'} ${what}, each verified from its own envelope; ${extra.length === 1 ? 'its' : 'their'} link in the platform-ops chain is established only by a dump of that chain.`;
329
+ ackSource = {
330
+ source: ackSource.source === 'none' ? (fromPages ? 'pages' : 'given') : ackSource.source,
331
+ items: [...ackSource.items, ...extra.map((a) => ({ entryId: a.entryId, chainPosition: a.chainPosition, state: a.state, iat: a.iat }))],
332
+ detail: ackSource.source === 'none' ? given : `${ackSource.detail} ${given}`,
333
+ };
334
+ }
335
+ findings.push(...supplied.findings.map((f) => ({ code: f.code, page: 0, detail: f.detail })));
336
+ const chains = [];
337
+ const verdicts = documents.unreadable.map((v) => ({ ...v, chainKey: null }));
338
+ for (const plan of plans) {
339
+ const { result, heldTo } = results.get(plan.chainKey) ?? verifyPlan(plan, acknowledgements);
340
+ // A run from position 1 that reaches a signed checkpoint is whole through it.
341
+ const wholeThrough = plan.first === 1 && plan.tipOpen && heldTo.by === 'signed_checkpoint';
342
+ const sliceReason = wholeThrough ? undefined : plan.sliceReason;
343
+ for (const v of result.anchors.verdicts)
344
+ verdicts.push({ ...v, chainKey: plan.doc.exportMetadata.recordId });
345
+ chains.push({
346
+ chainKey: plan.doc.exportMetadata.recordId,
347
+ chain: plan.chainKey === PLATFORM_OPS_CHAIN_KEY ? 'platform-ops' : 'record',
348
+ firstPosition: plan.first,
349
+ lastPosition: plan.last,
350
+ extent: sliceReason === undefined ? 'whole' : 'slice',
351
+ ...(sliceReason !== undefined ? { sliceReason } : {}),
352
+ heldTo,
353
+ result: sliceReason === undefined ? result : capSlice(result),
354
+ });
355
+ }
356
+ const walkCaps = [];
357
+ if (!complete) {
358
+ walkCaps.push({ reason: 'walk_not_read_to_end', detail: `The walk does not end at a null nextCursor, or shows a page missing: ${incomplete.join(' ')}` });
359
+ }
360
+ const chainSet = judgeUnheldChains({
361
+ pages: read.map((r) => r.page),
362
+ groups,
363
+ listed,
364
+ documents: documents.byChain,
365
+ query,
366
+ registry,
367
+ judgedThroughIat,
368
+ readTimeGiven,
369
+ acknowledgements,
370
+ holdsPlatformOps: ops !== undefined,
371
+ });
372
+ findings.push(...chainSet.findings);
373
+ verdicts.push(...chainSet.verdicts);
374
+ walkCaps.push(...chainSet.caps);
375
+ // Options are refused the same way whether or not the walk holds an entry.
376
+ if (chains.length === 0)
377
+ verifyExportChain({ exportMetadata: { recordId: UUIDV7_ORIGIN, exportFormatVersion: '2.0', canonicalization: 'RFC8949-CDE' }, entries: [] }, options$, {});
378
+ return {
379
+ kind: 'bulk',
380
+ ...walkResult({
381
+ chains,
382
+ findings,
383
+ walk: { pages: read.length, entries, endsAtNullCursor: complete, incomplete, notes, order: read.map((r) => r.given), cursors },
384
+ readTime: {
385
+ exportDate: walkRead.exportDate,
386
+ source: walkRead.source,
387
+ chains: plans.map((plan) => {
388
+ const { exportDate, source } = latestReadTime(rowReadTimes(plan.rows));
389
+ return { chainKey: plan.doc.exportMetadata.recordId, exportDate, source };
390
+ }),
391
+ },
392
+ anchors: walkAnchorsReport({
393
+ given: (options.anchorDocuments?.length ?? 0) > 0,
394
+ judgedThroughIat,
395
+ judgedThroughSource: judgedThroughIat === null ? null : readTimeGiven ? 'exportDate' : judgedThroughSourceOf(walkRead.latestSource),
396
+ acknowledgements: ackSource,
397
+ verdicts,
398
+ }),
399
+ unsignedFields: merged.unsignedFields,
400
+ capped: walkCaps,
401
+ }),
402
+ chainSet: chainSet.report,
403
+ suppliedAcknowledgements: supplied.report,
404
+ serverStatement: { hashChainValid: read.map(({ page }) => (typeof page.chainMetadata.hashChainValid === 'boolean' ? page.chainMetadata.hashChainValid : null)) },
405
+ query,
406
+ };
407
+ }
408
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
409
+ /** The window either side of a key's validity the Server's clock may stray by; a checkpoint signed this close to a to bound may cover entries after it. */
410
+ const TO_BOUND_SKEW_SECONDS = 300;
411
+ /** A chain key's kind, from the uuid the checkpoints sign: a version-8 uuid is a derived schema-chain key (record ids are UUIDv7). */
412
+ function chainKindOf(chainKey) {
413
+ if (chainKey === PLATFORM_OPS_CHAIN_KEY)
414
+ return 'platform-ops';
415
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-8/i.test(chainKey) ? 'schema' : 'record';
416
+ }
417
+ /**
418
+ * Hold the listed checkpoints and anchor documents of chains the walk holds
419
+ * no entry of to the walk's query.
420
+ *
421
+ * Whose chains the walk serves: a walk under a platform key (its pages carry
422
+ * `bulkExports`, or it holds the platform-ops chain) serves every record
423
+ * chain and the platform-ops chain; a walk under an org admin key (`bulkExport`)
424
+ * serves that org's record chains, which an org admin's listing of
425
+ * `GET /v1/audit-vault/checkpoints` names (a listing naming no platform-ops
426
+ * checkpoint and one schema chain); schema chains are never in the bulk
427
+ * export. A `recordId` filter serves that chain alone. The filters below
428
+ * apply to every chain served, the platform-ops chain as much as a record
429
+ * chain. Then each checkpoint:
430
+ * under a `to` bound, one signed more than `TO_BOUND_SKEW_SECONDS` before it
431
+ * is inside the query, one signed later cannot be placed; an `agentId` or
432
+ * `from` filter, or a query the pages do not establish, places none.
433
+ *
434
+ * Inside the query, a listed checkpoint is judged as one above the last
435
+ * position of a chain the walk holds whole would be (`judgeListedCheckpoints`
436
+ * at last position 0), and an anchor document is compared as with a chain of
437
+ * which nothing is held. One the walk cannot place: an acknowledgement that
438
+ * accounts for it still does; otherwise the verdict reads at best
439
+ * `unanchored`. A check this host refused to compute is one it cannot place.
440
+ */
441
+ function judgeUnheldChains(input) {
442
+ const { listed, documents, query, registry } = input;
443
+ const findings = [];
444
+ const verdicts = [];
445
+ const caps = [];
446
+ const missing = new Set();
447
+ const undecided = new Map();
448
+ const outside = new Map();
449
+ const keys = new Set([...(listed?.keys() ?? []), ...documents.keys()].filter((k) => k !== '' && !input.groups.has(k)));
450
+ if (listed === null && documents.size === 0) {
451
+ return { report: { state: 'pages_only', detail: 'No checkpoint listing or anchor document was given, so the chains of the walk are the ones these pages hold: a chain whose every page is missing shows only where something signed names it.', missing: [], undecided: [], outside: [] }, findings, verdicts, caps };
452
+ }
453
+ // Whose chains the walk serves.
454
+ const platformWalk = input.holdsPlatformOps || input.pages.some((p) => Array.isArray(p.bulkExports));
455
+ const orgWalk = !platformWalk && input.pages.some((p) => isRecord(p.bulkExport));
456
+ const listingRows = listed === null ? [] : [...listed.entries()];
457
+ const schemaKeys = new Set(listingRows.map(([k]) => k).filter((k) => chainKindOf(k) === 'schema'));
458
+ const platformListing = listingRows.some(([k, rows]) => k === PLATFORM_OPS_CHAIN_KEY || rows.some((r) => r.row.chain === 'admin')) || schemaKeys.size > 1;
459
+ const orgListing = listed !== null && !platformListing;
460
+ let walkOrg = null;
461
+ for (const p of input.pages) {
462
+ const c = decodeCursor(p.nextCursor);
463
+ if (c !== null && typeof c['_org'] === 'string') {
464
+ walkOrg = c['_org'];
465
+ break;
466
+ }
467
+ }
468
+ const listingOfAnotherOrg = orgListing && walkOrg !== null && schemaKeys.size === 1 && !schemaKeys.has(schemaCheckpointKey(walkOrg).toLowerCase());
469
+ const filter = query.filter;
470
+ const toMs = filter?.to != null ? rfc3339Ms(filter.to) : NaN;
471
+ /** Where one chain stands before any one checkpoint's time is read. */
472
+ const chainPlace = (chainKey) => {
473
+ const kind = chainKindOf(chainKey);
474
+ if (kind === 'schema')
475
+ return { place: 'out', why: 'a schema chain, which the bulk export does not serve' };
476
+ if (!query.established || filter === null)
477
+ return { place: 'undecided', why: 'the pages do not establish the walk\'s query' };
478
+ if (filter.recordId !== null) {
479
+ return chainKey === filter.recordId.toLowerCase() ? { place: 'in', why: '' } : { place: 'out', why: `the walk's query reads record ${filter.recordId} alone` };
480
+ }
481
+ if (kind === 'platform-ops' && !platformWalk) {
482
+ return orgWalk ? { place: 'out', why: 'the platform-ops chain, which a walk under an org admin key does not serve' } : { place: 'undecided', why: 'the pages do not show whether the walk was read under a platform key, which serves the platform-ops chain' };
483
+ }
484
+ if (!platformWalk) {
485
+ if (!orgListing)
486
+ return { place: 'undecided', why: 'the walk is not shown to be under a platform key, and the listing given is not one org\'s, so whether the walk serves this chain is not established' };
487
+ if (listingOfAnotherOrg)
488
+ return { place: 'undecided', why: 'the listing given is of another org than the walk' };
489
+ if (!listed?.has(chainKey))
490
+ return { place: 'undecided', why: 'an anchor document of a chain the org listing does not name, which may be another org\'s' };
491
+ }
492
+ if (filter.agentId !== null)
493
+ return { place: 'undecided', why: `the walk's query reads entries of agent ${filter.agentId} alone, and the pages do not show whose this chain's are` };
494
+ if (filter.from !== null)
495
+ return { place: 'undecided', why: `the walk's query reads entries written from ${filter.from}, and a checkpoint does not say when the entries it signs were written` };
496
+ return { place: 'in', why: '' };
497
+ };
498
+ /** One checkpoint, by its signed iat, under a to bound. */
499
+ const timePlace = (iat) => {
500
+ if (Number.isNaN(toMs))
501
+ return { place: 'in', why: '' };
502
+ if (iat !== null && (iat + TO_BOUND_SKEW_SECONDS) * 1000 < toMs)
503
+ return { place: 'in', why: '' };
504
+ return { place: 'undecided', why: `the walk's query reads entries written before ${String(filter?.to)}, and the checkpoint was signed at iat ${String(iat)}, too close to it or after it to tell whether it signs entries the query leaves out` };
505
+ };
506
+ for (const chainKey of keys) {
507
+ const place = chainPlace(chainKey);
508
+ const rows = listed?.get(chainKey) ?? [];
509
+ const docs = documents.get(chainKey) ?? [];
510
+ if (place.place === 'out') {
511
+ outside.set(chainKey, place.why);
512
+ for (const d of docs)
513
+ verdicts.push({ chainKey, kind: 'not_comparable', reason: 'chain_not_held', source: d.source, ...(d.objectKey !== undefined ? { objectKey: d.objectKey } : {}), position: null, iat: null, keyId: null, unsignedDisagreements: [], detail: `${d.source}: a checkpoint of chain ${chainKey}, which the walk holds no entry of: ${place.why}.` });
514
+ continue;
515
+ }
516
+ if (registry === null) {
517
+ undecided.set(chainKey, 'the walk holds no entry, so no key was read to verify its checkpoints under');
518
+ continue;
519
+ }
520
+ // Split by each checkpoint's time under a to bound.
521
+ const split = (items, iatOf) => {
522
+ const inside = [];
523
+ const unplaced = [];
524
+ let why = place.why;
525
+ for (const it of items) {
526
+ const t = place.place === 'in' ? timePlace(iatOf(it)) : { place: 'undecided', why: place.why };
527
+ if (t.place === 'in')
528
+ inside.push(it);
529
+ else {
530
+ unplaced.push(it);
531
+ why = t.why;
532
+ }
533
+ }
534
+ return { inside, unplaced, why };
535
+ };
536
+ const rowIat = (r) => (typeof r.row.coseSign1 === 'string' ? decodeSignedClaim(Buffer.from(r.row.coseSign1, 'base64'))?.iat ?? null : null);
537
+ const rowSplit = split(rows, rowIat);
538
+ const docSplit = split(docs, anchorDocumentIat);
539
+ const view = { firstHeld: 1, lastHeld: 0, tipEstablished: true, judgedThroughIat: input.judgedThroughIat, readTimeGiven: input.readTimeGiven };
540
+ const refused = (code) => code === 'CHAIN_UNSUPPORTED_ALGORITHM';
541
+ let unplacedHere = false;
542
+ // Listed checkpoints.
543
+ for (const [part, list] of [['in', rowSplit.inside], ['undecided', rowSplit.unplaced]]) {
544
+ if (list.length === 0)
545
+ continue;
546
+ const judged = judgeListedCheckpoints(chainKey, list, [], registry.keys, registry.signingSince, view);
547
+ if (part === 'in')
548
+ for (const c of judged.capped)
549
+ caps.push({ reason: 'read_time_not_given', detail: c });
550
+ else if (judged.capped.length > 0)
551
+ unplacedHere = true;
552
+ for (const f of judged.findings) {
553
+ if (part === 'in' && !refused(f.code)) {
554
+ if (f.code === 'CHECKPOINT_ROW_MISSING' || f.code === 'ANCHOR_CHAIN_CUT')
555
+ missing.add(chainKey);
556
+ findings.push({ code: f.code, page: 0, detail: `${f.detail} The walk holds no entry of chain ${chainKey}, and its query serves it.` });
557
+ }
558
+ else
559
+ unplacedHere = true;
560
+ }
561
+ }
562
+ // Anchor documents.
563
+ for (const [part, list] of [['in', docSplit.inside], ['undecided', docSplit.unplaced]]) {
564
+ if (list.length === 0)
565
+ continue;
566
+ const cmp = compareCheckpointAnchors(list, { chainKey, entries: [], lastEntryPosition: null, judgedThroughIat: input.judgedThroughIat, readTimeGiven: input.readTimeGiven }, registry.keys, input.acknowledgements);
567
+ // On a chain the walk cannot place, what holds the verdict is that, not the read time.
568
+ if (part === 'in')
569
+ for (const c of cmp.capped)
570
+ caps.push({ reason: 'read_time_not_given', detail: c });
571
+ for (const v of cmp.verdicts) {
572
+ const unplaced = v.kind === 'disagree'
573
+ || (v.kind === 'not_comparable' && (v.reason === 'no_read_time' || (v.reason === 'signed_after_read' && !input.readTimeGiven)));
574
+ if (unplaced && part === 'undecided') {
575
+ unplacedHere = true;
576
+ verdicts.push({ chainKey, kind: 'not_comparable', reason: 'chain_not_held', source: v.source, ...(v.objectKey !== undefined ? { objectKey: v.objectKey } : {}), position: v.position, iat: v.iat, keyId: v.keyId, unsignedDisagreements: v.unsignedDisagreements, detail: `${v.source}: a checkpoint of chain ${chainKey}, which the walk holds no entry of, and which the walk cannot place inside or outside its query (${docSplit.why}); were it inside, ${v.detail.replace(/^[^:]*: /, '')}` });
577
+ }
578
+ else {
579
+ verdicts.push({ ...v, chainKey });
580
+ }
581
+ }
582
+ for (const f of cmp.findings) {
583
+ if (part === 'in' && !refused(f.code)) {
584
+ if (f.code === 'CHECKPOINT_ROW_MISSING' || f.code === 'ANCHOR_CHAIN_CUT')
585
+ missing.add(chainKey);
586
+ findings.push({ code: f.code, page: 0, detail: `${f.detail} The walk holds no entry of chain ${chainKey}, and its query serves it.` });
587
+ }
588
+ else
589
+ unplacedHere = true;
590
+ }
591
+ }
592
+ if (unplacedHere)
593
+ undecided.set(chainKey, rowSplit.unplaced.length > 0 ? rowSplit.why : docSplit.unplaced.length > 0 ? docSplit.why : 'a check of its checkpoint this host could not compute');
594
+ }
595
+ for (const [chainKey, why] of undecided) {
596
+ caps.push({ reason: 'chain_set_undecided', detail: `The walk holds no entry of chain ${chainKey}, and a checkpoint signs entries of it that the walk cannot place inside or outside its query: ${why}.` });
597
+ }
598
+ const state = undecided.size > 0 ? 'undecided' : 'held_to_listing';
599
+ const counted = keys.size;
600
+ const detail = state === 'undecided'
601
+ ? `${undecided.size} of the ${counted} chain${counted === 1 ? '' : 's'} named by a listed checkpoint or anchor document that the walk holds no entry of could not be placed inside or outside the walk's query, so the set of chains the walk holds is not established.`
602
+ : missing.size > 0
603
+ ? `${missing.size} chain${missing.size === 1 ? '' : 's'} inside the walk's query ${missing.size === 1 ? 'has' : 'have'} a signed checkpoint and no entry in the walk: the walk left ${missing.size === 1 ? 'it' : 'them'} out.`
604
+ : counted === 0
605
+ ? 'Every chain named by a listed checkpoint or anchor document is one the walk holds.'
606
+ : `Every chain named by a listed checkpoint or anchor document that the walk holds no entry of is outside its query, or has no checkpoint signed before the read (${counted} chain${counted === 1 ? '' : 's'}).`;
607
+ return {
608
+ report: {
609
+ state,
610
+ detail,
611
+ missing: [...missing],
612
+ undecided: [...undecided].map(([chainKey, reason]) => ({ chainKey, reason })),
613
+ outside: [...outside].map(([chainKey, reason]) => ({ chainKey, reason })),
614
+ },
615
+ findings,
616
+ verdicts,
617
+ caps,
618
+ };
619
+ }
620
+ /** The bulk export's largest page. */
621
+ const MAX_LIMIT = 500;
622
+ /** The RFC 8785 form of the filter a bulk page's read-transparency manifest hashes. */
623
+ function filterHash(filter) {
624
+ const ordered = { agentId: filter.agentId, cursor: filter.cursor, from: filter.from, limit: filter.limit, recordId: filter.recordId, to: filter.to };
625
+ return createHash('sha256').update(JSON.stringify(ordered), 'utf8').digest('hex');
626
+ }
627
+ /**
628
+ * The query the pages were served under. A page logged as a read carries the
629
+ * hash of its filter (`queryHash`); the filter is found by hashing the ones
630
+ * the pages make possible: the scope the walk's cursors carry, or, on a walk
631
+ * whose cursors carry none, no time bound with no record or agent filter, the
632
+ * one record every row is on, or an agent some row names, each at every page
633
+ * size. A query a filter outside these was served under (a time bound on a
634
+ * walk of one page) is not established.
635
+ */
636
+ function walkQuery(pages, groups) {
637
+ let scope = null;
638
+ for (const page of pages) {
639
+ const cursor = decodeCursor(page.nextCursor);
640
+ if (cursor !== null && typeof cursor['after_id'] === 'string') {
641
+ scope = cursor;
642
+ break;
643
+ }
644
+ }
645
+ const text = (v) => (typeof v === 'string' ? v : null);
646
+ const scopes = [];
647
+ if (scope !== null) {
648
+ scopes.push({ from: text(scope['from']), to: text(scope['to']), recordId: text(scope['recordId']), agentId: text(scope['agentId']) });
649
+ }
650
+ else {
651
+ const records = groups.size === 1 ? [null, ...pages.flatMap((p) => p.data.map((r) => text(r.recordId))).slice(0, 1)] : [null];
652
+ const agents = new Set();
653
+ for (const p of pages)
654
+ for (const r of p.data)
655
+ if (typeof r.actorOwnerId === 'string' && UUID.test(r.actorOwnerId))
656
+ agents.add(r.actorOwnerId);
657
+ for (const recordId of records)
658
+ for (const agentId of [null, ...agents])
659
+ scopes.push({ from: null, to: null, recordId, agentId });
660
+ }
661
+ for (let i = 0; i < pages.length; i++) {
662
+ const page = pages[i];
663
+ const hashes = new Set([page.bulkExport?.queryHash, ...(Array.isArray(page.bulkExports) ? page.bulkExports.map((b) => b.queryHash) : [])].filter((h) => typeof h === 'string'));
664
+ if (hashes.size === 0)
665
+ continue;
666
+ const cursor = i === 0 ? null : text(pages[i - 1]?.nextCursor);
667
+ for (const s of scopes) {
668
+ for (let limit = 1; limit <= MAX_LIMIT; limit++) {
669
+ if (!hashes.has(filterHash({ ...s, cursor, limit })))
670
+ continue;
671
+ return {
672
+ established: true,
673
+ source: 'query_hash',
674
+ filter: { ...s, limit },
675
+ detail: `Page ${i + 1}'s queryHash is the hash of this filter${s.to === null ? ': the query has no to bound' : `: the query reads entries written before ${s.to}`}.`,
676
+ };
677
+ }
678
+ }
679
+ }
680
+ if (scope !== null) {
681
+ const s = scopes[0];
682
+ return { established: true, source: 'cursor', filter: { ...s, limit: null }, detail: 'The walk\'s cursors carry the query\'s scope.' };
683
+ }
684
+ return {
685
+ established: false,
686
+ source: null,
687
+ filter: null,
688
+ detail: 'No page carries a cursor with the query\'s scope, and no page\'s queryHash is the hash of a filter with no time bound (a page read by a key whose reads are not logged carries none). The query may carry a to bound, so the chains\' tips are not established: each chain is verified through the last position the walk holds.',
689
+ };
690
+ }
691
+ /**
692
+ * A record chain's entries held to the record they are filed under, as on a
693
+ * record export, and to being record entries: a schema-registry entry type
694
+ * belongs on a schema chain.
695
+ */
696
+ function recordChainIdentity(recordId, entries) {
697
+ const own = signedRecordId(recordId, entries);
698
+ if (own.finding !== undefined)
699
+ return own;
700
+ const schema = entries.find((e) => isRecord(e) && typeof e['entryType'] === 'string' && SCHEMA_ENTRY_TYPES.has(e['entryType']));
701
+ if (schema === undefined || !isRecord(schema))
702
+ return own;
703
+ return {
704
+ recordId: own.recordId,
705
+ finding: {
706
+ position: typeof schema['chainPosition'] === 'number' ? schema['chainPosition'] : 0,
707
+ code: 'CHAIN_PAYLOAD_BINDING_MISMATCH',
708
+ detail: `The entry is a ${String(schema['entryType'])} entry, which the Server writes on a schema chain, on record ${recordId}'s chain.`,
709
+ },
710
+ };
711
+ }