@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,82 @@
1
+ import { type VerifyExportOptions } from './audit-export.js';
2
+ import { type ExportWalkInput, type ExportWalkResultBase, type SchemaChainExportPage } from './export-pages.js';
3
+ import { type VaultCheckpointsPage } from './walk-checkpoints.js';
4
+ export interface VerifySchemaChainExportOptions extends Pick<VerifyExportOptions, 'publicKeys' | 'requireKeyId' | 'requireSuppliedKeys' | 'trustAnchors' | 'distrustedKeys' | 'agentKeys' | 'federationKeys' | 'allowAfterRetirement' | 'expectedEntryCount'> {
5
+ /**
6
+ * Anchor documents from the Server's anchor bucket, compared with the
7
+ * chain as on a record export. On a walk that applies the first page's
8
+ * `checkpointEvidence`, anchors are judged through its
9
+ * `anchorsJudgedThroughIat` and its `acknowledgedRewinds` account for what
10
+ * they cover; otherwise through the walk's read time (`readTime.exportDate`,
11
+ * the latest page read time) less one second, with no acknowledgement in
12
+ * reach. On a slice, an anchor outside the run the walk
13
+ * holds reads `chain_held_in_part`. A document of another chain reads
14
+ * `chain_not_held`.
15
+ */
16
+ anchorDocuments?: VerifyExportOptions['anchorDocuments'];
17
+ /**
18
+ * Pages of `GET /v1/audit-vault/checkpoints`; the rows filed under the
19
+ * chain's checkpoint key are held to it as `VerifyBulkExportOptions.checkpoints` describes.
20
+ */
21
+ checkpoints?: ReadonlyArray<VaultCheckpointsPage>;
22
+ /**
23
+ * When the last page of the walk was read (RFC 3339). Anchors and listed
24
+ * checkpoints are judged through it, less one second, in place of the
25
+ * first page's `anchorsJudgedThroughIat` and the pages' own read times,
26
+ * none of which is signed; see `VerifyBulkExportOptions.exportDate`. For
27
+ * batched entries it dates the pages that state no read time of their own
28
+ * (`exportMetadata.exportDate`, which a Server from 4.0.0 writes on every
29
+ * page); a page that states none, with no option, is dated by the latest
30
+ * `chainMetadata.checkpointEvidence.evidenceReadAt` the pages state.
31
+ */
32
+ exportDate?: string;
33
+ /** Acknowledgements of lost history the walk does not carry; see `VerifyExportOptions.acknowledgements`. */
34
+ acknowledgements?: VerifyExportOptions['acknowledgements'];
35
+ }
36
+ /** The result of `verifySchemaChainExport`. */
37
+ export interface VerifySchemaChainExportResult extends ExportWalkResultBase {
38
+ kind: 'schema-chain';
39
+ /**
40
+ * The org the chain belongs to: the org id its entries sign
41
+ * (`orgIdSource: 'signed'`), null for the Server-wide chain. On a walk
42
+ * whose entries sign none, the one `chainMetadata.orgId` states.
43
+ */
44
+ orgId: string | null;
45
+ orgIdSource: 'signed' | 'stated';
46
+ /** The checkpoint key derived from `orgId`: the chain id its checkpoints, batch leaves and history-seal leaves carry. */
47
+ checkpointKey: string;
48
+ /**
49
+ * What the Server stated on the walk's first page about the whole chain
50
+ * (`chainIntegrity`, `chainIntegrityReason`, `brokenAtPosition`), and the
51
+ * chain length the walk began at (`total`). Unsigned, and no part of the
52
+ * verdict; null where the first page states none.
53
+ */
54
+ serverStatement: {
55
+ chainIntegrity: boolean | null;
56
+ chainIntegrityReason: string | null;
57
+ brokenAtPosition: number | null;
58
+ total: number | null;
59
+ };
60
+ }
61
+ /**
62
+ * The uuid a schema chain's checkpoints, batch leaves and history-seal leaves
63
+ * are filed under, derived from the org id (null for the Server-wide chain):
64
+ * the first 16 bytes of sha256(`agledger:schema-chain-checkpoint:v1|<org id
65
+ * or __platform__>`), with the version nibble 8 and the RFC 4122 variant.
66
+ */
67
+ export declare function schemaCheckpointKey(orgId: string | null): string;
68
+ /**
69
+ * Verify a walk of the schema-chain export offline.
70
+ *
71
+ * `pages` is the walk in page order: parsed JSON pages, or the NDJSON text
72
+ * of each page, or one string holding the NDJSON of every page. A single
73
+ * page is read as a walk of one.
74
+ *
75
+ * Throws `TypeError` when the input is not schema-chain export pages (a bulk
76
+ * export page names `verifyBulkExport`), when its pages name different
77
+ * chains, and on a malformed option. A malformed entry is a failure on the
78
+ * chain, never a throw. `expectedEntryCount` holds the chain's length as on a
79
+ * record export; on a walk read as a slice it holds nothing, and
80
+ * `walk.notes` says so.
81
+ */
82
+ export declare function verifySchemaChainExport(pages: ExportWalkInput<SchemaChainExportPage>, options?: VerifySchemaChainExportOptions): VerifySchemaChainExportResult;
@@ -0,0 +1,474 @@
1
+ /**
2
+ * Verify a walk of the schema-chain export,
3
+ * `GET /v1/audit-vault/schema-chain/export`: every page of one org's
4
+ * schema-registry chain (or the Server-wide one), from the first to the one
5
+ * whose `nextCursor` is null.
6
+ *
7
+ * The chain is signed, linked and batched as a record chain is, under the
8
+ * checkpoint key derived from its org id, so it is verified as a record
9
+ * export of its entries is, with that key as the chain id. Two things are
10
+ * held beside that: each entry is a schema-registry entry (entry type,
11
+ * predicate type, signed outcome, subject) of the org the chain belongs to,
12
+ * by the org id each entry signs, and the stated `checkpointKey` is the one
13
+ * derived from the stated org id. One page's checkpoint block is taken whole
14
+ * (the first page's, read with the chain's length the walk is held to).
15
+ *
16
+ * A walk that does not start at position 1, or does not reach its end, is a
17
+ * slice: its entries are verified, it is held to no count or checkpoint
18
+ * outside the positions it holds, and its verdict reads at best `unanchored`.
19
+ *
20
+ * A batched entry served without a proof is judged against the read time of
21
+ * its own page (`exportMetadata.exportDate`), as on a bulk walk.
22
+ */
23
+ import { createHash } from 'node:crypto';
24
+ import { decode as cborDecode } from 'cborg';
25
+ import { verifyExportChain } from './audit-export.js';
26
+ import { STRICT_CBOR_DECODE } from './cbor-strict.js';
27
+ import { rfc3339Ms } from './instant.js';
28
+ import { assertKnownOptions } from './options.js';
29
+ import { decodeCoseSign1, deepEqual, sha256HexString } from './primitives.js';
30
+ import { assertExportDate, capSlice, chainOptions, cursorLinkReasons, cursorsStated, decodeCursor, entryOfRow, heldByPages, isRecord, latestReadTime, mergePageMetadata, pageReadTimes, positionRange, readPages, walkResult, assertWalkReadAfterSigned, pageReadTimeFindings, } from './export-pages.js';
31
+ import { assertWalkAnchorDocuments, chainNotHeldVerdict, groupAnchorDocuments, judgedThroughOf, judgedThroughSourceOf, readCheckpointPages, walkAnchorsReport, } from './walk-anchors.js';
32
+ import { listedEnvelopeShas } from './walk-checkpoints.js';
33
+ const OPTIONS = ['publicKeys', 'requireKeyId', 'requireSuppliedKeys', 'trustAnchors', 'distrustedKeys', 'agentKeys', 'federationKeys', 'allowAfterRetirement', 'expectedEntryCount', 'anchorDocuments', 'checkpoints', 'exportDate', 'acknowledgements'];
34
+ const SCHEMA_CHECKPOINT_NAMESPACE = 'agledger:schema-chain-checkpoint:v1';
35
+ const SCHEMA_EVENT_PREDICATE = 'https://agledger.ai/predicates/schema-event/v1';
36
+ /**
37
+ * The payload keys of a schema-chain entry the signed schema-event predicate
38
+ * carries, each under the first of its names the payload holds: `orgId` as
39
+ * org_id, the schema type, version and manifest digest under any of their
40
+ * names, and `source`; with `on_behalf_of` and `traceparent`, which the
41
+ * envelope carries.
42
+ */
43
+ const SIGNED_PAYLOAD_KEYS = [
44
+ ['orgId'],
45
+ ['type', 'schemaType', 'schema_type'],
46
+ ['version', 'schemaVersion', 'schema_version'],
47
+ ['manifestDigest', 'manifest_digest'],
48
+ ['source'],
49
+ ['on_behalf_of'],
50
+ ['traceparent'],
51
+ ];
52
+ /**
53
+ * The payload keys the Server writes on each schema-chain entry type that
54
+ * nothing signs: the registry's own bookkeeping, kept in the row's payload
55
+ * and not in the predicate. Listed in `unsignedProjectionFields` as
56
+ * `payload.<key>`, so the report says a change to one is not detected.
57
+ */
58
+ const UNSIGNED_PAYLOAD_KEYS = {
59
+ SCHEMA_REGISTERED: new Set(['publisherId', 'compatibility', 'registeredBy']),
60
+ SCHEMA_IMPORTED: new Set(['publisherId', 'importedBy']),
61
+ SCHEMA_DIGEST_MISMATCH: new Set(['publisherId', 'peerDigest', 'localDigest', 'peerHubId', 'recordId', 'operation']),
62
+ };
63
+ /**
64
+ * A schema-chain row's payload keys outside what the entry signs and what the
65
+ * Server writes unsigned on its entry type: a key added to the payload, or a
66
+ * second name of a signed field beside the one the predicate reads.
67
+ */
68
+ function unexpectedPayloadKeys(entryType, payload) {
69
+ const allowed = new Set(UNSIGNED_PAYLOAD_KEYS[entryType] ?? []);
70
+ for (const names of SIGNED_PAYLOAD_KEYS) {
71
+ const used = names.find((n) => payload[n] !== undefined && payload[n] !== null) ?? names.find((n) => n in payload);
72
+ if (used !== undefined)
73
+ allowed.add(used);
74
+ }
75
+ return Object.keys(payload).filter((k) => !allowed.has(k));
76
+ }
77
+ /** The `payload.<key>` names of the unsigned payload keys the rows carry. */
78
+ function unsignedPayloadFields(rows) {
79
+ const out = new Set();
80
+ for (const row of rows) {
81
+ const known = typeof row.entryType === 'string' ? UNSIGNED_PAYLOAD_KEYS[row.entryType] : undefined;
82
+ if (known === undefined || !isRecord(row.payload))
83
+ continue;
84
+ for (const k of Object.keys(row.payload))
85
+ if (known.has(k))
86
+ out.add(`payload.${k}`);
87
+ }
88
+ return [...out].sort();
89
+ }
90
+ const OUTCOME = {
91
+ SCHEMA_REGISTERED: 'REGISTERED',
92
+ SCHEMA_IMPORTED: 'IMPORTED',
93
+ SCHEMA_DIGEST_MISMATCH: 'DIGEST_MISMATCH',
94
+ };
95
+ /**
96
+ * The uuid a schema chain's checkpoints, batch leaves and history-seal leaves
97
+ * are filed under, derived from the org id (null for the Server-wide chain):
98
+ * the first 16 bytes of sha256(`agledger:schema-chain-checkpoint:v1|<org id
99
+ * or __platform__>`), with the version nibble 8 and the RFC 4122 variant.
100
+ */
101
+ export function schemaCheckpointKey(orgId) {
102
+ const bytes = createHash('sha256').update(`${SCHEMA_CHECKPOINT_NAMESPACE}|${orgId ?? '__platform__'}`, 'utf8').digest().subarray(0, 16);
103
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x80;
104
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
105
+ const hex = bytes.toString('hex');
106
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
107
+ }
108
+ /**
109
+ * Verify a walk of the schema-chain export offline.
110
+ *
111
+ * `pages` is the walk in page order: parsed JSON pages, or the NDJSON text
112
+ * of each page, or one string holding the NDJSON of every page. A single
113
+ * page is read as a walk of one.
114
+ *
115
+ * Throws `TypeError` when the input is not schema-chain export pages (a bulk
116
+ * export page names `verifyBulkExport`), when its pages name different
117
+ * chains, and on a malformed option. A malformed entry is a failure on the
118
+ * chain, never a throw. `expectedEntryCount` holds the chain's length as on a
119
+ * record export; on a walk read as a slice it holds nothing, and
120
+ * `walk.notes` says so.
121
+ */
122
+ export function verifySchemaChainExport(pages, options = {}) {
123
+ assertKnownOptions('verifySchemaChainExport', options, OPTIONS);
124
+ assertExportDate('verifySchemaChainExport', options.exportDate);
125
+ assertWalkAnchorDocuments('verifySchemaChainExport', options.anchorDocuments);
126
+ const listed = readCheckpointPages('verifySchemaChainExport', options.checkpoints);
127
+ const read = readPages(pages, 'schema-chain', 'verifySchemaChainExport');
128
+ const first = read[0]?.page;
129
+ if (first === undefined)
130
+ throw new TypeError('verifySchemaChainExport: the input holds no page.');
131
+ assertWalkReadAfterSigned('verifySchemaChainExport', options.exportDate, read.map((r) => r.page));
132
+ const statedOrgId = typeof first.chainMetadata.orgId === 'string' ? first.chainMetadata.orgId : null;
133
+ read.forEach(({ page }, i) => {
134
+ const orgId = typeof page.chainMetadata.orgId === 'string' ? page.chainMetadata.orgId : null;
135
+ if ((orgId ?? '').toLowerCase() !== (statedOrgId ?? '').toLowerCase()) {
136
+ throw new TypeError(`verifySchemaChainExport: page ${i + 1} is of the schema chain of ${orgId === null ? 'the Server-wide registrations' : `org ${orgId}`}, and page 1 of ${statedOrgId === null ? 'the Server-wide registrations' : `org ${statedOrgId}`}: verify each chain's walk on its own.`);
137
+ }
138
+ });
139
+ const merged = mergePageMetadata(read.map((r) => r.page));
140
+ const findings = [...merged.findings, ...pageReadTimeFindings(read.map((r) => r.page))];
141
+ const incomplete = [];
142
+ const notes = [];
143
+ const derivedStated = schemaCheckpointKey(statedOrgId);
144
+ read.forEach(({ page }, i) => {
145
+ const stated = page.chainMetadata.checkpointKey;
146
+ if (typeof stated !== 'string' || stated.toLowerCase() !== derivedStated) {
147
+ findings.push({
148
+ code: 'CHAIN_PAYLOAD_BINDING_MISMATCH',
149
+ page: i + 1,
150
+ detail: `Page ${i + 1} states checkpointKey ${JSON.stringify(stated ?? null)}, and the key derived from its orgId ${JSON.stringify(statedOrgId)} is ${derivedStated}: the unsigned metadata was edited.`,
151
+ });
152
+ }
153
+ });
154
+ // The rows, each once, in walk order, with the page each was served on.
155
+ const rows = [];
156
+ const rowPage = [];
157
+ const byId = new Map();
158
+ const byPosition = new Map();
159
+ // The offset the walk's first page was read at: the position before its
160
+ // first row, so a walk begun past the first page is held to its own start.
161
+ const firstAt = read[0]?.page.data[0]?.chainPosition;
162
+ let held = Number.isSafeInteger(firstAt) && firstAt >= 1 ? firstAt - 1 : 0;
163
+ const walkTotal = typeof first.total === 'number' ? first.total : null;
164
+ const chainScope = statedOrgId ?? 'server-wide';
165
+ read.forEach(({ page }, i) => {
166
+ const n = i + 1;
167
+ for (const row of page.data) {
168
+ held++;
169
+ const id = typeof row.id === 'string' ? row.id.toLowerCase() : null;
170
+ if (id !== null) {
171
+ const seen = byId.get(id);
172
+ if (seen !== undefined) {
173
+ if (deepEqual(seen.row, row))
174
+ incomplete.push(`Entry ${row.id} is on page ${seen.page} and on page ${n}: the pages overlap, so they are not one walk.`);
175
+ else
176
+ 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}.` });
177
+ continue;
178
+ }
179
+ byId.set(id, { row, page: n });
180
+ }
181
+ if (Number.isSafeInteger(row.chainPosition)) {
182
+ const other = byPosition.get(row.chainPosition);
183
+ if (other !== undefined) {
184
+ findings.push({ code: 'EXPORT_PAGE_CONFLICT', page: n, detail: `The chain holds two different entries at position ${String(row.chainPosition)}: ${String(other.id)} and ${String(row.id)}.` });
185
+ continue;
186
+ }
187
+ byPosition.set(row.chainPosition, row);
188
+ }
189
+ rows.push(row);
190
+ rowPage.push(i);
191
+ }
192
+ const last = i === read.length - 1;
193
+ const ends = page.nextCursor === null && page.hasMore !== true;
194
+ if ((page.hasMore === true && page.nextCursor === null) || (page.hasMore === false && page.nextCursor !== null)) {
195
+ 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.`);
196
+ }
197
+ if (!last && ends) {
198
+ 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.`);
199
+ }
200
+ if (last && !ends)
201
+ incomplete.push('The last page has a nextCursor: more entries follow it. Request the pages that follow and verify the whole walk.');
202
+ if (walkTotal !== null && typeof page.total === 'number' && page.total !== walkTotal) {
203
+ incomplete.push(`Page ${n} states the walk began with ${page.total} entries, and page 1 ${walkTotal}: the pages are not one walk.`);
204
+ }
205
+ if (typeof page.nextCursor === 'string') {
206
+ const cursor = decodeCursor(page.nextCursor);
207
+ if (cursor === null || typeof cursor['offset'] !== 'number') {
208
+ notes.push(`Page ${n}'s nextCursor does not decode as the Server's offset cursor, so it was not compared with the entries read through page ${n}.`);
209
+ }
210
+ else {
211
+ if (cursor['offset'] !== held)
212
+ incomplete.push(`Page ${n}'s nextCursor resumes at offset ${String(cursor['offset'])}, and the pages through page ${n} end at offset ${held}: the pages are not one walk.`);
213
+ if (cursor['_schemaChain'] !== undefined && cursor['_schemaChain'] !== chainScope) {
214
+ incomplete.push(`Page ${n}'s nextCursor belongs to the walk of ${JSON.stringify(cursor['_schemaChain'])}, not of ${JSON.stringify(chainScope)}.`);
215
+ }
216
+ }
217
+ }
218
+ });
219
+ incomplete.push(...cursorLinkReasons(read.map((r) => r.page), notes));
220
+ const cursors = cursorsStated(read.map((r) => r.page));
221
+ const range = positionRange(rows);
222
+ const start = range?.first ?? 1;
223
+ // Any reason but a late start leaves the chain's tip unestablished.
224
+ const tipOpen = incomplete.length > 0;
225
+ if (start > 1)
226
+ incomplete.push(`The walk starts at position ${start}, not at the chain's first entry: the pages before it are not here.`);
227
+ const complete = incomplete.length === 0;
228
+ // The org the entries sign, which the chain is filed under.
229
+ const signedOrg = rows.map(signedOrgOf).find((o) => o !== undefined);
230
+ const orgId = signedOrg !== undefined ? signedOrg : statedOrgId;
231
+ const checkpointKey = schemaCheckpointKey(orgId);
232
+ const pageReads = read.map(({ page }) => page.chainMetadata.checkpointEvidence?.['evidenceReadAt']).filter((t) => typeof t === 'string' && !Number.isNaN(rfc3339Ms(t)));
233
+ const latestRead = pageReads.length === 0 ? null : pageReads.reduce((a, b) => (rfc3339Ms(b) > rfc3339Ms(a) ? b : a));
234
+ const readTimes = pageReadTimes(read.map((r) => r.page), options.exportDate, notes, latestRead === null ? null : { exportDate: latestRead, source: 'checkpoint_evidence' });
235
+ if (options.exportDate !== undefined && readTimes.every((t) => t.source === 'pages')) {
236
+ notes.push(`exportDate ${options.exportDate} was given, and every page states its own read time (exportMetadata.exportDate): each page was read at its own.`);
237
+ }
238
+ const walkRead = latestReadTime(readTimes);
239
+ const exportDate = walkRead.exportDate;
240
+ const rowReadTimes = rowPage.map((n) => readTimes[n] ?? { exportDate: null, source: null });
241
+ const chains = [];
242
+ let options$ = chainOptions(options);
243
+ const documents = groupAnchorDocuments(options.anchorDocuments);
244
+ // The caller's read time first: the pages' own, and the block's, are unsigned.
245
+ const readTimeGiven = options.exportDate !== undefined;
246
+ const walkJudged = judgedThroughOf(readTimeGiven ? options.exportDate : exportDate);
247
+ const verdicts = documents.unreadable.map((v) => ({ ...v, chainKey: null }));
248
+ let judgedThroughIat = walkJudged;
249
+ let judgedThroughSource = walkJudged === null ? null : readTimeGiven ? 'exportDate' : judgedThroughSourceOf(walkRead.latestSource);
250
+ let acknowledgements = { source: 'none', items: [], detail: 'The walk applies no checkpointEvidence block, so no acknowledgement of lost history is in reach and none accounts for a disagreement.' };
251
+ if (rows.length > 0) {
252
+ const slice = !complete;
253
+ const cm = first.chainMetadata;
254
+ // A slice is held to the checkpoint block only when it holds both the
255
+ // checkpoint's position and the tip the block was read at.
256
+ const checkpointAt = cm.checkpointEvidence?.checkpoint?.chainPosition;
257
+ const tipAt = cm.checkpointEvidence?.lastEntryPosition;
258
+ const evidenceHeld = typeof checkpointAt === 'number' && range !== null && checkpointAt >= range.first
259
+ && (typeof tipAt !== 'number' || tipAt <= range.last);
260
+ if (slice && !evidenceHeld && cm.checkpointEvidence !== undefined && cm.checkpointEvidence !== null) {
261
+ notes.push('chainMetadata.checkpointEvidence was not applied: the walk holds a slice of the chain that does not reach both the checkpoint\'s position and the tip the block was read at.');
262
+ }
263
+ if (slice && options$.expectedEntryCount !== undefined) {
264
+ const { expectedEntryCount: _count, ...rest } = options$;
265
+ options$ = rest;
266
+ notes.push('expectedEntryCount was not applied: the walk holds a slice of the chain, not the whole chain.');
267
+ }
268
+ const doc = {
269
+ exportMetadata: {
270
+ ...merged.meta,
271
+ recordId: checkpointKey,
272
+ // The first page's block, taken whole: read before that page read the
273
+ // whole chain, so the chain at the walk's start holds its position.
274
+ ...(slice
275
+ ? (evidenceHeld ? { checkpointEvidence: cm.checkpointEvidence } : {})
276
+ : {
277
+ ...(cm.checkpointEvidence !== undefined ? { checkpointEvidence: cm.checkpointEvidence } : {}),
278
+ ...(cm.expectedEntries !== undefined ? { expectedEntries: cm.expectedEntries } : {}),
279
+ ...(walkTotal !== null ? { totalEntries: walkTotal } : {}),
280
+ }),
281
+ },
282
+ entries: rows.map(entryOfRow),
283
+ verificationGuide: { unsignedFields: merged.unsignedFields },
284
+ };
285
+ const startHash = byPosition.get(start)?.previousHash;
286
+ const startLink = typeof startHash === 'string' ? startHash : null;
287
+ const first$ = range?.first ?? 0;
288
+ const last$ = range?.last ?? 0;
289
+ const sliceReason = slice
290
+ ? [
291
+ start > 1 ? `The walk holds positions ${start} to ${range?.last ?? start}; ${start === 2 ? 'position 1 is' : `positions 1 to ${start - 1} are`} not in it.` : null,
292
+ tipOpen ? '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.' : null,
293
+ ].filter((x) => x !== null).join(' ')
294
+ : undefined;
295
+ const evidence = doc.exportMetadata.checkpointEvidence;
296
+ const blockJudged = isRecord(evidence) && typeof evidence['anchorsJudgedThroughIat'] === 'number' && Number.isSafeInteger(evidence['anchorsJudgedThroughIat'])
297
+ ? evidence['anchorsJudgedThroughIat']
298
+ : null;
299
+ if (blockJudged !== null && !readTimeGiven) {
300
+ judgedThroughIat = blockJudged;
301
+ judgedThroughSource = 'checkpointEvidence';
302
+ }
303
+ if (isRecord(evidence)) {
304
+ acknowledgements = { source: 'checkpoint-evidence', items: [], detail: 'The acknowledgements of lost history are the ones the applied checkpointEvidence block lists; chains[0].result.acknowledgedRewinds reports each.' };
305
+ }
306
+ const rowsListed = listed?.get(checkpointKey) ?? [];
307
+ let heldTo = heldByPages(last$);
308
+ const reading = {
309
+ ...(slice ? { slice: { startPosition: start, previousHash: start > 1 ? startLink : null, openEnd: tipOpen } } : {}),
310
+ entryReadTimes: rowReadTimes.map((t) => t.exportDate),
311
+ identity: (list) => schemaChainIdentity(checkpointKey, statedOrgId, list),
312
+ anchors: {
313
+ judgedThroughIat: walkJudged,
314
+ readTimeGiven,
315
+ ...(sliceReason !== undefined ? { heldInPart: { ...(start > 1 ? { firstHeld: first$ } : {}), ...(tipOpen ? { lastHeld: last$ } : {}), reason: sliceReason } } : {}),
316
+ checkpoints: listedEnvelopeShas(rowsListed),
317
+ },
318
+ ...(rowsListed.length > 0
319
+ ? { listedCheckpoints: { rows: rowsListed, view: { firstHeld: first$, lastHeld: last$, tipEstablished: !tipOpen, judgedThroughIat: readTimeGiven ? walkJudged : blockJudged ?? walkJudged, readTimeGiven }, report: (h) => { heldTo = h; } } }
320
+ : {}),
321
+ };
322
+ const docs = documents.byChain.get(checkpointKey);
323
+ const result = verifyExportChain(doc, {
324
+ ...options$,
325
+ ...(docs !== undefined ? { anchorDocuments: docs } : {}),
326
+ ...(options.acknowledgements !== undefined ? { acknowledgements: options.acknowledgements } : {}),
327
+ ...(readTimeGiven ? { exportDate: options.exportDate } : {}),
328
+ }, reading);
329
+ for (const v of result.anchors.verdicts)
330
+ verdicts.push({ ...v, chainKey: checkpointKey });
331
+ // A run from position 1 that reaches a signed checkpoint is whole through it.
332
+ const whole = !slice || (start === 1 && heldTo.by === 'signed_checkpoint');
333
+ chains.push({
334
+ chainKey: checkpointKey,
335
+ chain: 'schema',
336
+ firstPosition: first$,
337
+ lastPosition: last$,
338
+ extent: whole ? 'whole' : 'slice',
339
+ ...(!whole && sliceReason !== undefined ? { sliceReason } : {}),
340
+ heldTo,
341
+ result: whole ? result : capSlice(result),
342
+ });
343
+ }
344
+ else {
345
+ // Options are refused the same way whether or not the walk holds an entry.
346
+ verifyExportChain({ exportMetadata: { recordId: checkpointKey, exportFormatVersion: '2.0', canonicalization: 'RFC8949-CDE' }, entries: [] }, chainOptions(options), {});
347
+ }
348
+ for (const [chainKey, docs] of documents.byChain) {
349
+ if (chainKey === checkpointKey && rows.length > 0)
350
+ continue;
351
+ for (const d of docs)
352
+ verdicts.push(chainNotHeldVerdict(chainKey, d, chainKey === checkpointKey ? 'The walk holds no entry of it.' : 'A schema-chain walk holds one chain.'));
353
+ }
354
+ if (listed !== null) {
355
+ const other = [...listed.entries()].filter(([key]) => key !== checkpointKey || rows.length === 0).reduce((sum, [, list]) => sum + list.length, 0);
356
+ if (other > 0)
357
+ notes.push(`${other} listed checkpoint${other === 1 ? ' is' : 's are'} filed under chains the walk holds no entry of, and ${other === 1 ? 'was' : 'were'} not compared.`);
358
+ }
359
+ const cm = first.chainMetadata;
360
+ return {
361
+ kind: 'schema-chain',
362
+ ...walkResult({
363
+ chains,
364
+ findings,
365
+ walk: { pages: read.length, entries: rows.length, endsAtNullCursor: complete, incomplete, notes, order: read.map((r) => r.given), cursors },
366
+ readTime: {
367
+ exportDate,
368
+ source: walkRead.source,
369
+ chains: chains.map((c) => {
370
+ const chain = latestReadTime(rowReadTimes);
371
+ return { chainKey: c.chainKey, exportDate: chain.exportDate, source: chain.source };
372
+ }),
373
+ },
374
+ anchors: walkAnchorsReport({ given: (options.anchorDocuments?.length ?? 0) > 0, judgedThroughIat, judgedThroughSource, acknowledgements, verdicts }),
375
+ unsignedFields: [...merged.unsignedFields, ...unsignedPayloadFields(rows)],
376
+ capped: complete ? [] : [{ reason: 'walk_not_read_to_end', detail: `The walk does not end at a null nextCursor, or shows a page missing: ${incomplete.join(' ')}` }],
377
+ }),
378
+ orgId,
379
+ orgIdSource: signedOrg !== undefined ? 'signed' : 'stated',
380
+ checkpointKey,
381
+ serverStatement: {
382
+ chainIntegrity: typeof cm.chainIntegrity === 'boolean' ? cm.chainIntegrity : null,
383
+ chainIntegrityReason: typeof cm.chainIntegrityReason === 'string' ? cm.chainIntegrityReason : null,
384
+ brokenAtPosition: typeof cm.brokenAtPosition === 'number' ? cm.brokenAtPosition : null,
385
+ total: walkTotal,
386
+ },
387
+ };
388
+ }
389
+ /** An entry's signed in-toto Statement, or null when the envelope does not decode. */
390
+ function signedStatement(coseSign1) {
391
+ if (typeof coseSign1 !== 'string')
392
+ return null;
393
+ const parts = decodeCoseSign1(Buffer.from(coseSign1, 'base64'));
394
+ if (parts === null)
395
+ return null;
396
+ try {
397
+ const statement = cborDecode(parts.payloadBstr, { ...STRICT_CBOR_DECODE, useMaps: false });
398
+ return isRecord(statement) ? statement : null;
399
+ }
400
+ catch {
401
+ return null;
402
+ }
403
+ }
404
+ /** The org id an entry signs (`predicate.org_id`, a string or null), or undefined when it signs none. */
405
+ function signedOrgOf(row) {
406
+ const predicate = signedStatement(row.coseSign1)?.['predicate'];
407
+ if (!isRecord(predicate) || !('org_id' in predicate))
408
+ return undefined;
409
+ const org = predicate['org_id'];
410
+ return typeof org === 'string' || org === null ? org : undefined;
411
+ }
412
+ /**
413
+ * The schema chain's entries held to being its entries: no record id, a
414
+ * schema-registry entry type whose outcome the entry signs, the schema-event
415
+ * predicate and subject, and the org the chain belongs to, by the org id each
416
+ * entry signs. The first disagreement is CHAIN_PAYLOAD_BINDING_MISMATCH at
417
+ * its entry's position.
418
+ */
419
+ function schemaChainIdentity(checkpointKey, statedOrgId, entries) {
420
+ const same = (a, b) => (a === null ? b === null : b !== null && a.toLowerCase() === b.toLowerCase());
421
+ const label = (o) => (o === null ? 'no org (the Server-wide chain)' : `org ${o}`);
422
+ let chainOrg;
423
+ for (const raw of entries) {
424
+ if (!isRecord(raw))
425
+ continue;
426
+ const position = typeof raw['chainPosition'] === 'number' ? raw['chainPosition'] : 0;
427
+ const fail = (detail) => ({ recordId: checkpointKey, finding: { position, code: 'CHAIN_PAYLOAD_BINDING_MISMATCH', detail } });
428
+ if (raw['recordId'] !== null && raw['recordId'] !== undefined) {
429
+ return fail(`The entry names record ${JSON.stringify(raw['recordId'])}; a schema-chain entry is on no record.`);
430
+ }
431
+ const entryType = raw['entryType'];
432
+ const outcome = typeof entryType === 'string' ? OUTCOME[entryType] : undefined;
433
+ if (outcome === undefined)
434
+ return fail(`The entry is a ${JSON.stringify(entryType ?? null)} entry; a schema chain holds SCHEMA_REGISTERED, SCHEMA_IMPORTED and SCHEMA_DIGEST_MISMATCH entries only.`);
435
+ const integrity = raw['integrity'];
436
+ const statement = signedStatement(isRecord(integrity) ? integrity['coseSign1'] : undefined);
437
+ // An envelope that does not decode fails the chain walk by itself.
438
+ if (statement === null)
439
+ continue;
440
+ const predicate = statement['predicate'];
441
+ if (statement['predicateType'] !== SCHEMA_EVENT_PREDICATE || !isRecord(predicate) || 'record_id' in predicate || !('org_id' in predicate)) {
442
+ return fail(`The entry signs a ${JSON.stringify(statement['predicateType'] ?? null)} statement, not a schema-registry event (${SCHEMA_EVENT_PREDICATE}).`);
443
+ }
444
+ if (predicate['outcome'] !== outcome) {
445
+ return fail(`The entry is a ${String(entryType)} entry and signs outcome ${JSON.stringify(predicate['outcome'] ?? null)}, where ${entryType} signs ${outcome}.`);
446
+ }
447
+ const org = predicate['org_id'];
448
+ if (org !== null && typeof org !== 'string')
449
+ return fail(`The entry signs org_id ${JSON.stringify(org)}, which is not an org id or null.`);
450
+ const subject = statement['subject'];
451
+ const s0 = Array.isArray(subject) && isRecord(subject[0]) ? subject[0] : undefined;
452
+ const digest = isRecord(s0?.['digest']) ? s0['digest']['sha256'] : undefined;
453
+ const expected = sha256HexString(`${String(predicate['schema_type'])}:${String(predicate['schema_version'])}`);
454
+ if (s0?.['name'] !== 'schema_artifact' || !(digest instanceof Uint8Array) || Buffer.from(digest).toString('hex') !== expected) {
455
+ return fail(`The entry's signed subject is not the schema_artifact digest of ${String(predicate['schema_type'])}:${String(predicate['schema_version'])}.`);
456
+ }
457
+ if (chainOrg === undefined)
458
+ chainOrg = { org, position };
459
+ else if (!same(chainOrg.org, org)) {
460
+ return fail(`The entry signs ${label(org)}, and the entry at position ${chainOrg.position} signs ${label(chainOrg.org)}: the chain holds two orgs' registrations.`);
461
+ }
462
+ if (!same(org, statedOrgId)) {
463
+ return fail(`The entry signs ${label(org)}, and chainMetadata.orgId states ${label(statedOrgId)}: the unsigned metadata was edited, or the entry is another chain's.`);
464
+ }
465
+ const payload = raw['payload'];
466
+ if (isRecord(payload)) {
467
+ const extra = unexpectedPayloadKeys(entryType, payload);
468
+ if (extra.length > 0) {
469
+ return fail(`The entry's payload carries ${extra.map((k) => JSON.stringify(k)).join(', ')}, which the signed statement does not carry and the Server does not write on a ${String(entryType)} entry: the payload was edited.`);
470
+ }
471
+ }
472
+ }
473
+ return { recordId: checkpointKey };
474
+ }