@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,816 @@
1
+ /**
2
+ * The cross-party read log as the Server serves it over its API, verified
3
+ * offline: the signed tree heads of `GET /v1/audit/org-reads/checkpoints` and
4
+ * `GET /v1/audit/org-reads/checkpoints/{id}` (the cosign response included),
5
+ * the inclusion proofs of `GET /v1/audit/org-reads/checkpoints/{id}/proof`,
6
+ * and the leaves of `GET /v1/audit/org-reads`.
7
+ *
8
+ * Each tree head is a COSE_Sign1 envelope over a vault-checkpoint in-toto
9
+ * Statement: the RFC 9162 Merkle root over leaves [0, treeSize) as subject and
10
+ * as `chain_tip_hash`, the tree size as chain position and `count`, the range
11
+ * 0 to treeSize - 1, the org as CWT `sub`, the time as CWT `iat`, and the
12
+ * signing key as the protected-header kid. Every one of those is held to the
13
+ * field the document serves beside it, under the codes a dump's read log is
14
+ * held to (TENANT_CHECKPOINT_*), and the signature is verified under a key
15
+ * resolved and walked from the caller's anchors as `verifyAuditExport`
16
+ * resolves an export's keys.
17
+ *
18
+ * A leaf as the API lists it carries its leaf hash and the columns of its
19
+ * row, not the envelope that hash is taken over, so its columns are bound to
20
+ * nothing signed: what a listing establishes is the leaf hashes. A leaf as a
21
+ * dump's `org_admin_reads` row carries the envelope (`cose_sign1`), and is
22
+ * held to it as the dump verifier holds it (TENANT_READ_*).
23
+ */
24
+ import { suppliedKeyContext } from './audit-export.js';
25
+ import { placeInKeyWindow, writtenWhileSigning } from './chain.js';
26
+ import { KEY_WINDOW_CLOCK_SKEW_SECONDS, VAULT_CHECKPOINT_PREDICATE_TYPE } from './anchors.js';
27
+ import { decodeSignedClaim, UNSIGNED_KID, uuidSubjectDigest } from './claim.js';
28
+ import { rfc3339Ms } from './instant.js';
29
+ import { assertKnownOptions } from './options.js';
30
+ import { decodeCoseSign1, extractActorClaim, hasComputableAnchor, isVerifyingAsIfHostComputed, orgReadLeafHash, orgReadMerkleRoot, resolveKeyAlgorithmOrHostRefused, runtimeBelowFloor, runtimeCanCompute, uncomputableAlgorithms, verifyAsIfHostComputed, verifyCoseSign1, verifyOrgReadInclusion, verifySignatureBytes, anchorAlgorithms, } from './primitives.js';
31
+ import { pinReachesNoKey, settleKeyTrust, unverifiableVerdict, verdictOf, } from './key-statements.js';
32
+ // --- Detection ---
33
+ const HEX64 = /^[0-9a-f]{64}$/;
34
+ function isRecord(value) {
35
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
36
+ }
37
+ function isCheckpoint(v) {
38
+ return isRecord(v) && typeof v['coseSign1Base64'] === 'string' && 'treeSize' in v && 'rootHash' in v;
39
+ }
40
+ function isProof(v) {
41
+ return isRecord(v) && Array.isArray(v['path']) && 'leafIndex' in v && 'leafHash' in v && 'rootHash' in v && !('coseSign1Base64' in v);
42
+ }
43
+ function isEntry(v) {
44
+ return isRecord(v) && 'leafIndex' in v && 'leafHash' in v && 'recordId' in v;
45
+ }
46
+ function isDumpRow(v) {
47
+ return isRecord(v) && 'leaf_index' in v && 'leaf_hash' in v && 'cose_sign1' in v;
48
+ }
49
+ /**
50
+ * Which read-log document a parsed JSON value is, or null:
51
+ * `org-read-checkpoint` (one tree head, or the cosign response),
52
+ * `org-read-checkpoints` (a page of the checkpoint listing),
53
+ * `org-read-proof`, `org-read-entries` (a page of `GET /v1/audit/org-reads`),
54
+ * `org-read-entry` (one row of it, or a dump's `org_admin_reads` row).
55
+ */
56
+ export function orgReadDocumentKind(value) {
57
+ if (isCheckpoint(value))
58
+ return 'org-read-checkpoint';
59
+ if (isProof(value))
60
+ return 'org-read-proof';
61
+ if (isEntry(value) || isDumpRow(value))
62
+ return 'org-read-entry';
63
+ if (isRecord(value) && Array.isArray(value['data'])) {
64
+ const rows = value['data'];
65
+ if ('checkpointing' in value && rows.every(isCheckpoint))
66
+ return 'org-read-checkpoints';
67
+ if (rows.length > 0 && rows.every(isCheckpoint))
68
+ return 'org-read-checkpoints';
69
+ if (rows.length > 0 && rows.every((r) => isEntry(r) || isDumpRow(r)))
70
+ return 'org-read-entries';
71
+ }
72
+ return null;
73
+ }
74
+ // --- Shared judging ---
75
+ const OPTIONS = ['publicKeys', 'trustAnchors', 'distrustedKeys', 'cosignerKeys', 'requireCosignature'];
76
+ const UNSUPPORTED = 'CHAIN_UNSUPPORTED_ALGORITHM';
77
+ function contextOf(fn, options) {
78
+ assertKnownOptions(fn, options, OPTIONS);
79
+ if (options.requireCosignature !== undefined && typeof options.requireCosignature !== 'boolean') {
80
+ throw new TypeError(`${fn}: requireCosignature must be a boolean.`);
81
+ }
82
+ return {
83
+ ...suppliedKeyContext(fn, options),
84
+ cosigners: cosignerRegistry(fn, options.cosignerKeys),
85
+ requireCosignature: options.requireCosignature === true,
86
+ };
87
+ }
88
+ function cosignerRegistry(fn, given) {
89
+ const out = new Map();
90
+ if (given === undefined)
91
+ return out;
92
+ const entries = Array.isArray(given)
93
+ ? given.map((e) => (isRecord(e) ? [e['keyId'], e['publicKey']] : [undefined, undefined]))
94
+ : isRecord(given) ? Object.entries(given) : [];
95
+ if (!Array.isArray(given) && !isRecord(given)) {
96
+ throw new TypeError(`${fn}: cosignerKeys must be { [witnessKeyId]: base64 SPKI DER } or [{ keyId, publicKey }].`);
97
+ }
98
+ entries.forEach(([keyId, publicKey], i) => {
99
+ if (typeof keyId !== 'string' || keyId === '' || typeof publicKey !== 'string') {
100
+ throw new TypeError(`${fn}: cosignerKeys entry ${i} is not { keyId: string, publicKey: base64 SPKI DER }.`);
101
+ }
102
+ if (resolveKeyAlgorithmOrHostRefused(publicKey) === 'unparseable') {
103
+ throw new TypeError(`${fn}: cosignerKeys entry ${JSON.stringify(keyId)} is not a public key (SPKI DER, base64).`);
104
+ }
105
+ out.set(keyId, publicKey);
106
+ });
107
+ return out;
108
+ }
109
+ /**
110
+ * How far before the signed iat the time the Server stamps on a read-log row
111
+ * (`read_at`, `checkpoint_at`) may fall: the same clock skew a key window
112
+ * allows. The Server signs the claim at its own clock and the database stamps
113
+ * the column when it writes the row, after it signed (a batch read signs
114
+ * every leaf before it writes any), so the stamp may run seconds past the
115
+ * iat and is never earlier, beyond the two clocks' skew.
116
+ */
117
+ export const READ_LOG_STAMP_SKEW_SECONDS = KEY_WINDOW_CLOCK_SKEW_SECONDS;
118
+ /**
119
+ * Hold the time the Server stamped on a read-log row (`read_at` of a leaf,
120
+ * `checkpointAt` of a tree head) to the claim's signed iat: the stamp is not
121
+ * earlier than the iat by more than {@link READ_LOG_STAMP_SKEW_SECONDS}. The
122
+ * reason it is not held, or null. The dump verifier holds a dump's rows to the
123
+ * same rule.
124
+ */
125
+ export function readLogStampDisagreement(field, signedIat, stamped) {
126
+ const ms = typeof stamped === 'string' ? rfc3339Ms(stamped) : Number.NaN;
127
+ if (Number.isNaN(ms))
128
+ return `the served ${field} ${JSON.stringify(stamped ?? null)} is not an RFC 3339 instant`;
129
+ if (typeof signedIat !== 'number' || !Number.isSafeInteger(signedIat))
130
+ return `the signed iat ${JSON.stringify(signedIat ?? null)} is not a whole number of seconds`;
131
+ if (Math.floor(ms / 1000) >= signedIat - READ_LOG_STAMP_SKEW_SECONDS)
132
+ return null;
133
+ return `the served ${field} ${String(stamped)} is more than ${READ_LOG_STAMP_SKEW_SECONDS} seconds before the signed iat ${signedIat} (${new Date(signedIat * 1000).toISOString()}), and the Server stamps it when it writes the row, after it signs the claim`;
134
+ }
135
+ function firstDisagreement(fields) {
136
+ for (const [field, signed, served] of fields) {
137
+ if (signed !== served)
138
+ return `the signed ${field} ${JSON.stringify(signed ?? null)} is not the served ${JSON.stringify(served ?? null)}`;
139
+ }
140
+ return null;
141
+ }
142
+ function bytesOf(base64) {
143
+ return typeof base64 === 'string' ? Buffer.from(base64, 'base64') : Buffer.alloc(0);
144
+ }
145
+ /** The signature bytes a witness's text can denote: hex when it reads as hex, base64 (either alphabet) when it reads as that. */
146
+ function witnessSignatureCandidates(text) {
147
+ const out = [];
148
+ const t = text.trim();
149
+ if (/^[0-9a-fA-F]+$/.test(t) && t.length % 2 === 0)
150
+ out.push({ encoding: 'hex', bytes: Buffer.from(t, 'hex') });
151
+ if (/^[A-Za-z0-9+/_-]+={0,2}$/.test(t))
152
+ out.push({ encoding: 'base64', bytes: Buffer.from(t.replaceAll('-', '+').replaceAll('_', '/'), 'base64') });
153
+ return out;
154
+ }
155
+ /** An ECDSA signature in DER (SEQUENCE of two INTEGERs) as raw r||s of `half` bytes each; null when it is not one. */
156
+ function derToRaw(sig, half) {
157
+ const b = Buffer.from(sig);
158
+ let at = 0;
159
+ if (b[at++] !== 0x30)
160
+ return null;
161
+ let len = b[at++] ?? 0;
162
+ if (len & 0x80) {
163
+ const n = len & 0x7f;
164
+ if (n !== 1)
165
+ return null;
166
+ len = b[at++] ?? 0;
167
+ }
168
+ if (at + len !== b.length)
169
+ return null;
170
+ const parts = [];
171
+ for (let i = 0; i < 2; i++) {
172
+ if (b[at++] !== 0x02)
173
+ return null;
174
+ const l = b[at++] ?? 0;
175
+ let v = b.subarray(at, at + l);
176
+ at += l;
177
+ while (v.length > half && v[0] === 0)
178
+ v = v.subarray(1);
179
+ if (v.length > half)
180
+ return null;
181
+ parts.push(Buffer.concat([Buffer.alloc(half - v.length), v]));
182
+ }
183
+ return at === b.length ? Buffer.concat(parts) : null;
184
+ }
185
+ const ECDSA_HALF = { ES256: 32, ES384: 48 };
186
+ /**
187
+ * Judge a witness co-signature: over the checkpoint's COSE_Sign1 bytes, under
188
+ * the key the caller gave for its `witnessKeyId`. A key whose algorithm this
189
+ * host or build cannot compute leaves it `not_checked`, never verified and
190
+ * never failed.
191
+ */
192
+ function judgeCosignature(cp, envelope, ctx) {
193
+ const witnessKeyId = typeof cp['witnessKeyId'] === 'string' ? cp['witnessKeyId'] : null;
194
+ const witnessCosignedAt = typeof cp['witnessCosignedAt'] === 'string' ? cp['witnessCosignedAt'] : null;
195
+ const signature = typeof cp['witnessSignature'] === 'string' ? cp['witnessSignature'] : null;
196
+ const report = (state, detail, encoding) => ({
197
+ state, witnessKeyId, witnessCosignedAt, ...(encoding !== undefined ? { encoding } : {}), detail,
198
+ });
199
+ const required = (r, why) => (ctx.requireCosignature
200
+ ? { report: { ...r, state: 'failed' }, finding: `${why}, and requireCosignature was given.`, uncomputable: false }
201
+ : { report: r, uncomputable: false });
202
+ if (signature === null && witnessKeyId === null) {
203
+ return required(report('absent', 'The checkpoint carries no witness co-signature.'), 'The checkpoint carries no witness co-signature');
204
+ }
205
+ if (signature === null || witnessKeyId === null) {
206
+ return { report: report('failed', 'The checkpoint carries one of witnessKeyId and witnessSignature without the other; the Server stores both together.'), finding: 'The checkpoint carries one of witnessKeyId and witnessSignature without the other; the Server stores both together.', uncomputable: false };
207
+ }
208
+ const key = ctx.cosigners.get(witnessKeyId);
209
+ if (key === undefined) {
210
+ return required(report('no_key', `Co-signed by witness key ${JSON.stringify(witnessKeyId)}, which cosignerKeys does not give, so the co-signature was not checked.`), `The co-signature is under witness key ${JSON.stringify(witnessKeyId)}, which cosignerKeys does not give`);
211
+ }
212
+ const alg = resolveKeyAlgorithmOrHostRefused(key);
213
+ if (typeof alg !== 'object' || !alg.verifiable || !runtimeCanCompute(alg)) {
214
+ const name = typeof alg === 'object' ? alg.name : 'an algorithm this build does not recognize';
215
+ const detail = `The co-signature under witness key ${JSON.stringify(witnessKeyId)} could NOT BE CHECKED: its key is ${name}, which ${typeof alg === 'object' && alg.verifiable ? 'this host runtime refused to compute' : 'this verifier build cannot compute'}. It is neither verified nor refuted.`;
216
+ // Required, it is a check this host could not compute: never a pass, never tamper.
217
+ return { report: report('not_checked', detail), ...(ctx.requireCosignature ? { finding: detail, uncomputableFinding: true } : {}), uncomputable: true };
218
+ }
219
+ for (const candidate of witnessSignatureCandidates(signature)) {
220
+ const half = ECDSA_HALF[alg.name];
221
+ const forms = half === undefined ? [candidate.bytes] : [candidate.bytes, derToRaw(candidate.bytes, half)].filter((f) => f !== null);
222
+ if (forms.some((f) => verifySignatureBytes(key, envelope, f))) {
223
+ return { report: report('verified', `The co-signature verifies under witness key ${JSON.stringify(witnessKeyId)} (${alg.name}) over the checkpoint's COSE_Sign1 bytes.`, candidate.encoding), uncomputable: false };
224
+ }
225
+ }
226
+ const detail = `The co-signature does not verify under witness key ${JSON.stringify(witnessKeyId)} (${alg.name}) over the checkpoint's COSE_Sign1 bytes, read as hex or base64.`;
227
+ return { report: report('failed', detail), finding: detail, uncomputable: false };
228
+ }
229
+ /**
230
+ * Hold one tree head to its fields and its key, in the order the dump's read
231
+ * log is held: its claim against the fields served beside it, then unsigned
232
+ * after signing began, the key and the walk's verdict on it, the signature,
233
+ * and the key's window at the time served beside it, as the Server's own scan
234
+ * places a tree head (the claim binds that time to the signed iat, to the
235
+ * second).
236
+ */
237
+ function judgeCheckpoint(cp, ctx, label) {
238
+ const id = typeof cp['id'] === 'string' ? cp['id'] : null;
239
+ const orgId = typeof cp['orgId'] === 'string' ? cp['orgId'] : null;
240
+ const treeSize = Number.isSafeInteger(cp['treeSize']) && cp['treeSize'] >= 0 ? cp['treeSize'] : null;
241
+ const rootHash = typeof cp['rootHash'] === 'string' ? cp['rootHash'] : null;
242
+ const signingKeyId = typeof cp['signingKeyId'] === 'string' ? cp['signingKeyId'] : null;
243
+ const envelope = bytesOf(cp['coseSign1Base64']);
244
+ const claim = decodeSignedClaim(envelope);
245
+ const base = {
246
+ id, orgId, treeSize, rootHash, signingKeyId, signedIat: claim?.iat ?? null, state: 'failed',
247
+ cosignature: { state: 'absent', witnessKeyId: null, witnessCosignedAt: null, detail: 'Not read: the tree head failed first.' },
248
+ };
249
+ const at = treeSize ?? 0;
250
+ const fail = (code, detail, uncomputable = 0) => ({
251
+ report: { ...base, state: code === UNSUPPORTED ? 'not_checked' : 'failed' },
252
+ finding: { code, detail: `${label}: ${detail}`, treeSize: at },
253
+ anchored: 0,
254
+ uncomputable,
255
+ signedRoot: null,
256
+ });
257
+ if (treeSize === null)
258
+ return fail('TENANT_CHECKPOINT_CLAIM_MISMATCH', `treeSize ${JSON.stringify(cp['treeSize'] ?? null)} is not a non-negative integer.`);
259
+ if (rootHash === null || !HEX64.test(rootHash))
260
+ return fail('TENANT_CHECKPOINT_CLAIM_MISMATCH', `rootHash ${JSON.stringify(cp['rootHash'] ?? null)} is not 64 lowercase hex characters.`);
261
+ if (cp['signingKeyId'] !== null && signingKeyId === null)
262
+ return fail('TENANT_CHECKPOINT_CLAIM_MISMATCH', 'signingKeyId is neither a key id nor null.');
263
+ const range = isRecord(claim?.predicate['range']) ? claim.predicate['range'] : undefined;
264
+ const disagreement = claim === null
265
+ ? 'coseSign1Base64 does not decode as a signed AGLedger claim'
266
+ : firstDisagreement([
267
+ ['predicateType', claim.predicateType, VAULT_CHECKPOINT_PREDICATE_TYPE],
268
+ ['position', claim.position, treeSize],
269
+ ['count', claim.predicate['count'], treeSize],
270
+ ['range.start', range?.['start'], 0],
271
+ ['range.end', range?.['end'], treeSize > 0 ? treeSize - 1 : 0],
272
+ ['chain_tip_hash', claim.predicate['chain_tip_hash'], `sha256:${rootHash}`],
273
+ ['subject digest', claim.subjectSha256, rootHash],
274
+ ['kid', claim.kid, signingKeyId ?? UNSIGNED_KID],
275
+ ['sub (the log)', claim.sub, cp['logId']],
276
+ ['sub (the org)', claim.sub, orgId],
277
+ ]) ?? readLogStampDisagreement('checkpointAt', claim.iat, cp['checkpointAt']);
278
+ if (disagreement !== null)
279
+ return fail('TENANT_CHECKPOINT_CLAIM_MISMATCH', `the tree head's claim does not match its fields: ${disagreement}.`);
280
+ const cosign = judgeCosignature(cp, envelope, ctx);
281
+ const withCosign = (j) => ({
282
+ ...j,
283
+ report: { ...j.report, cosignature: cosign.report },
284
+ uncomputable: j.uncomputable + (cosign.uncomputable ? 1 : 0),
285
+ ...(cosign.finding !== undefined
286
+ ? { cosignFinding: { code: cosign.uncomputableFinding === true ? UNSUPPORTED : 'TENANT_CHECKPOINT_COSIGNATURE_INVALID', detail: `${label}: ${cosign.finding}`, treeSize } }
287
+ : {}),
288
+ });
289
+ if (signingKeyId === null) {
290
+ if (writtenWhileSigning(cp['checkpointAt'], ctx.signingSince)) {
291
+ return fail('TENANT_CHECKPOINT_UNSIGNED', `the tree head has no signingKeyId but was written ${String(cp['checkpointAt'])}, at or after the earliest signing key activation ${String(ctx.signingSince)}.`);
292
+ }
293
+ return withCosign({ report: { ...base, state: 'unsigned' }, anchored: 0, uncomputable: 0, signedRoot: rootHash });
294
+ }
295
+ const key = ctx.keys.get(signingKeyId);
296
+ if (key === undefined) {
297
+ return fail('CHAIN_SIGNATURE_MISSING_KEY', `signingKeyId "${signingKeyId}" is not among the keys given (publicKeys: the /v1/verification-keys document).`);
298
+ }
299
+ if (key.trust === 'unanchored') {
300
+ return fail('TENANT_CHECKPOINT_KEY_UNANCHORED', `key ${key.keyId} is given, but no signed key statement links it to a trust anchor.`);
301
+ }
302
+ // In the order the Server's scan and the dump verifier judge a signed row:
303
+ // a signature that fails on its own bytes, then the key's window at the
304
+ // time served beside it (held above to the signed iat),
305
+ // and only then a signature this host could not compute.
306
+ const outcome = verifyCoseSign1(envelope, key.spkiBase64);
307
+ if (outcome !== 'ok' && outcome !== 'unsupported-key-algorithm') {
308
+ return fail('TENANT_CHECKPOINT_SIGNATURE_INVALID', `the tree head's COSE_Sign1 signature does not verify under key ${key.keyId} (${outcome}).`);
309
+ }
310
+ const placed = placeInKeyWindow(key, cp['checkpointAt'], 'Tree head');
311
+ if (placed.placement === 'not-yet-active')
312
+ return fail('TENANT_CHECKPOINT_KEY_NOT_YET_ACTIVE', placed.detail);
313
+ if (placed.placement === 'expired')
314
+ return fail('TENANT_CHECKPOINT_KEY_EXPIRED', placed.detail);
315
+ if (placed.placement === 'unplaceable')
316
+ return fail('CHAIN_MALFORMED_ENTRY', placed.detail);
317
+ if (key.trust === 'undecided') {
318
+ return fail(UNSUPPORTED, `the signature could NOT BE CHECKED. Key ${key.keyId} is reached only through a key statement signed under an algorithm this host cannot compute.`, 1);
319
+ }
320
+ if (outcome === 'unsupported-key-algorithm') {
321
+ return fail(UNSUPPORTED, `the tree head's signature could NOT BE CHECKED: key ${key.keyId} commits to an algorithm this host cannot compute.`, 1);
322
+ }
323
+ return withCosign({ report: { ...base, state: 'verified' }, anchored: 1, uncomputable: 0, signedRoot: rootHash });
324
+ }
325
+ function leafView(raw, source) {
326
+ if (isDumpRow(raw)) {
327
+ return {
328
+ index: Number.isSafeInteger(raw['leaf_index']) ? raw['leaf_index'] : null,
329
+ hash: typeof raw['leaf_hash'] === 'string' ? raw['leaf_hash'] : null,
330
+ orgId: typeof raw['org_id'] === 'string' ? raw['org_id'] : null,
331
+ source,
332
+ row: raw,
333
+ entry: null,
334
+ };
335
+ }
336
+ if (isEntry(raw)) {
337
+ return {
338
+ index: Number.isSafeInteger(raw['leafIndex']) ? raw['leafIndex'] : null,
339
+ hash: typeof raw['leafHash'] === 'string' ? raw['leafHash'] : null,
340
+ orgId: typeof raw['orgId'] === 'string' ? raw['orgId'] : null,
341
+ source,
342
+ row: null,
343
+ entry: raw,
344
+ };
345
+ }
346
+ throw new TypeError(`${source} is not a read-log leaf: a row of GET /v1/audit/org-reads ({ leafIndex, leafHash, recordId, ... }) or of a dump's org_admin_reads ({ leaf_index, leaf_hash, cose_sign1, ... }).`);
347
+ }
348
+ /** The person a leaf signs as `predicate.on_behalf_of.oidc`, as `iss`/`sub` (each null when absent). */
349
+ function signedReader(claim) {
350
+ const onBehalfOf = claim.predicate['on_behalf_of'];
351
+ const oidc = isRecord(onBehalfOf) ? onBehalfOf['oidc'] : undefined;
352
+ return {
353
+ iss: isRecord(oidc) && typeof oidc['iss'] === 'string' ? oidc['iss'] : null,
354
+ sub: isRecord(oidc) && typeof oidc['sub'] === 'string' ? oidc['sub'] : null,
355
+ };
356
+ }
357
+ /**
358
+ * Hold a leaf that carries its envelope to it, as the dump's read log is
359
+ * held: the leaf hash recomputed from the envelope bytes, the signed claim
360
+ * against the row (position, the previous leaf's hash where the walk holds
361
+ * it, record, subject digest, and the read's context, filter, export batch,
362
+ * reader key, org and time), the signature and its key's window at the
363
+ * row's time, and the signed reader against the row's OIDC columns.
364
+ */
365
+ /** A leaf failed with one of these had its signature computed, and it did not hold. */
366
+ const SIGNATURE_FAILED = new Set(['TENANT_READ_SIGNATURE_INVALID', 'TENANT_READ_KEY_NOT_YET_ACTIVE', 'TENANT_READ_KEY_EXPIRED']);
367
+ function judgeLeafEnvelope(leaf, previousHash, ctx, mustSign) {
368
+ const row = leaf.row;
369
+ const i = leaf.index ?? 0;
370
+ const label = `${leaf.source} (leaf ${i})`;
371
+ // `failed` only once the signature was computed: a leaf whose bytes, claim
372
+ // or key fail first never reaches it, and its signature is `not_checked`.
373
+ const fail = (code, detail, uncomputable = 0) => ({
374
+ signature: SIGNATURE_FAILED.has(code) ? 'failed' : 'not_checked',
375
+ finding: { code, detail: `${label}: ${detail}`, leafIndex: i },
376
+ anchored: 0,
377
+ uncomputable,
378
+ });
379
+ const bytes = bytesOf(row['cose_sign1']);
380
+ if (leaf.hash === null || orgReadLeafHash(bytes) !== leaf.hash) {
381
+ return fail('TENANT_READ_LEAF_HASH_MISMATCH', 'the RFC 9162 leaf hash of cose_sign1, sha256(0x00 || bytes), is not the leaf_hash served beside it.');
382
+ }
383
+ const claim = decodeSignedClaim(bytes);
384
+ const parts = decodeCoseSign1(bytes);
385
+ const actor = parts === null ? null : extractActorClaim(parts.protectedBstr);
386
+ const traces = isRecord(claim?.predicate['traces']) ? claim.predicate['traces'] : {};
387
+ const callerKeyId = typeof row['caller_key_id'] === 'string' ? row['caller_key_id'].toLowerCase() : null;
388
+ const readerKeyId = callerKeyId === null ? null : uuidSubjectDigest(callerKeyId)?.slice(0, 32) ?? null;
389
+ const disagreement = claim === null
390
+ ? 'cose_sign1 does not decode as a signed AGLedger claim'
391
+ : firstDisagreement([
392
+ ['position', claim.position, i + 1],
393
+ ...(previousHash !== undefined ? [['previous_hash', claim.previousHash, previousHash]] : []),
394
+ ['record_id', claim.predicate['record_id'], row['record_id']],
395
+ ['subject digest', claim.subjectSha256, uuidSubjectDigest(row['record_id'])],
396
+ ['read_context', traces['read_context'], row['read_context']],
397
+ ['filter_applied', traces['filter_applied'], row['filter_applied']],
398
+ ['export_batch_id', traces['export_batch_id'] ?? null, row['export_batch_id'] ?? null],
399
+ ['reader_key_id', claim.predicate['reader_key_id'], readerKeyId],
400
+ ['actor key_id', actor?.key_id, callerKeyId],
401
+ ['actor owner_id (the org)', actor?.owner_id, typeof row['org_id'] === 'string' ? row['org_id'].toLowerCase() : row['org_id']],
402
+ ]) ?? readLogStampDisagreement('read_at', claim.iat, row['read_at']);
403
+ if (disagreement !== null)
404
+ return fail('TENANT_READ_CLAIM_MISMATCH', `the leaf's claim does not match its row: ${disagreement}.`);
405
+ const signed = claim;
406
+ const oidcGiven = row['actor_oidc_iss'] !== undefined || row['actor_oidc_sub'] !== undefined;
407
+ const reader = signedReader(signed);
408
+ const oidc = oidcGiven && ((row['actor_oidc_iss'] ?? null) !== reader.iss || (row['actor_oidc_sub'] ?? null) !== reader.sub)
409
+ ? `row actor_oidc_iss/sub (${JSON.stringify(row['actor_oidc_iss'] ?? null)}/${JSON.stringify(row['actor_oidc_sub'] ?? null)}) is not the person the leaf signs as predicate.on_behalf_of.oidc (${String(reader.iss)}/${String(reader.sub)}).`
410
+ : null;
411
+ const kid = signed.kid;
412
+ let judged;
413
+ if (kid === UNSIGNED_KID) {
414
+ const why = mustSign.signedBefore
415
+ ? 'follows a signed leaf in the leaves given'
416
+ : writtenWhileSigning(row['read_at'], ctx.signingSince)
417
+ ? `was written ${String(row['read_at'])}, at or after the earliest signing key activation ${String(ctx.signingSince)}`
418
+ : null;
419
+ if (why !== null)
420
+ return fail('TENANT_READ_LEAF_UNSIGNED', `the leaf is unsigned (kid ${UNSIGNED_KID}) but ${why}.`);
421
+ judged = { signature: 'unsigned', anchored: 0, uncomputable: 0 };
422
+ }
423
+ else {
424
+ mustSign.signedBefore = true;
425
+ const key = ctx.keys.get(kid);
426
+ if (key === undefined)
427
+ return fail('CHAIN_SIGNATURE_MISSING_KEY', `leaf kid "${kid}" is not among the keys given (publicKeys: the /v1/verification-keys document).`);
428
+ if (key.trust === 'unanchored')
429
+ return fail('TENANT_READ_KEY_UNANCHORED', `key ${key.keyId} is given, but no signed key statement links it to a trust anchor.`);
430
+ const outcome = verifyCoseSign1(bytes, key.spkiBase64);
431
+ if (outcome !== 'ok' && outcome !== 'unsupported-key-algorithm')
432
+ return fail('TENANT_READ_SIGNATURE_INVALID', `the leaf's COSE_Sign1 signature does not verify under key ${key.keyId} (${outcome}).`);
433
+ const placed = placeInKeyWindow(key, row['read_at'], 'Leaf');
434
+ if (placed.placement === 'not-yet-active')
435
+ return fail('TENANT_READ_KEY_NOT_YET_ACTIVE', placed.detail);
436
+ if (placed.placement === 'expired')
437
+ return fail('TENANT_READ_KEY_EXPIRED', placed.detail);
438
+ if (placed.placement === 'unplaceable')
439
+ return fail('CHAIN_MALFORMED_ENTRY', placed.detail);
440
+ if (key.trust === 'undecided')
441
+ return fail(UNSUPPORTED, `the signature could NOT BE CHECKED. Key ${key.keyId} is reached only through a key statement signed under an algorithm this host cannot compute.`, 1);
442
+ if (outcome === 'unsupported-key-algorithm')
443
+ return fail(UNSUPPORTED, `the leaf's signature could NOT BE CHECKED: key ${key.keyId} commits to an algorithm this host cannot compute.`, 1);
444
+ judged = { signature: 'verified', anchored: 1, uncomputable: 0 };
445
+ }
446
+ if (oidc !== null)
447
+ return { ...judged, finding: { code: 'TENANT_READ_OIDC_MISMATCH', detail: `${label}: ${oidc}`, leafIndex: i }, anchored: 0 };
448
+ return judged;
449
+ }
450
+ /**
451
+ * The verdict, the could-not-compute accounting and the break to name, as
452
+ * `verifyAuditExport` reaches them: a result that would pass had the checks
453
+ * this host refused verified is `unverifiable`; a failed one names its first
454
+ * finding that is not one of those.
455
+ */
456
+ function conclude(self, ctx, options, again) {
457
+ const { valid, keyTrust, findings } = self;
458
+ const count = self.uncomputable + (ctx.trust?.statements.unverifiable ?? 0);
459
+ const keysHere = [...ctx.publicKeys, ...ctx.cosigners.values()];
460
+ const algorithms = count === 0 ? [] : uncomputableAlgorithms(keysHere);
461
+ const computableAnchor = () => hasComputableAnchor(options.trustAnchors ?? [], ctx.publicKeys);
462
+ const { trustAnchors: _pinned, distrustedKeys: _distrusted, ...unpinned } = options;
463
+ let rerun = null;
464
+ let pinUnmet = false;
465
+ const verdict = isVerifyingAsIfHostComputed()
466
+ ? (valid ? 'unanchored' : 'failed')
467
+ : unverifiableVerdict({ valid, uncomputable: { count, algorithms }, passesIfComputed: () => {
468
+ rerun = verifyAsIfHostComputed(() => again(options), { statements: !computableAnchor() });
469
+ if (rerun.valid)
470
+ return true;
471
+ pinUnmet = !computableAnchor() && pinReachesNoKey(rerun.keyTrust)
472
+ && !again(unpinned).valid
473
+ && verifyAsIfHostComputed(() => again(unpinned).valid);
474
+ return pinUnmet;
475
+ } }, () => verdictOf({ valid, keyTrust }, () => again(unpinned).valid, (trustAnchors) => again({ ...options, trustAnchors }).valid));
476
+ const codes = findings.map((f) => f.code);
477
+ const uncomputable = {
478
+ count,
479
+ algorithms,
480
+ consequences: verdict === 'unverifiable' ? [...new Set(codes.filter((c) => c !== UNSUPPORTED))] : [],
481
+ ...(verdict === 'unverifiable'
482
+ ? computableAnchor()
483
+ ? { assumed: 'data' }
484
+ : { assumed: 'data-and-key-statements', anchorAlgorithms: anchorAlgorithms(options.trustAnchors ?? [], ctx.publicKeys), ...(pinUnmet ? { pinUnmet: true } : {}) }
485
+ : {}),
486
+ };
487
+ const first = findings[0];
488
+ const rerunBreak = rerun?.brokenAt;
489
+ const brokenAt = verdict === 'failed' && first?.code === UNSUPPORTED
490
+ ? findings.find((f) => f.code !== UNSUPPORTED) ?? (rerunBreak !== undefined && rerunBreak.code !== UNSUPPORTED ? rerunBreak : undefined) ?? first
491
+ : first;
492
+ const belowFloor = runtimeBelowFloor();
493
+ return {
494
+ verdict,
495
+ uncomputable,
496
+ ...(brokenAt !== undefined ? { brokenAt } : {}),
497
+ ...(belowFloor !== null ? { runtime: belowFloor } : {}),
498
+ };
499
+ }
500
+ function keyFindings(ctx) {
501
+ return ctx.walkReport.findings.map((f) => ({ code: f.code, detail: f.detail }));
502
+ }
503
+ function asCheckpoint(fn, value, what = 'checkpoint') {
504
+ if (!isCheckpoint(value)) {
505
+ throw new TypeError(`${fn}: the ${what} is not a read-log checkpoint: GET /v1/audit/org-reads/checkpoints/{id} ({ id, orgId, treeSize, rootHash, checkpointAt, logId, coseSign1Base64, signingKeyId, witnessSignature, witnessKeyId, witnessCosignedAt }).`);
506
+ }
507
+ return value;
508
+ }
509
+ // --- The three readers ---
510
+ /**
511
+ * Verify one signed tree head of the read log offline. Its envelope must
512
+ * decode, its signed claim must match the fields served beside it (tree
513
+ * size, root, org, log, kid, time), its signature must verify under the key
514
+ * `publicKeys` gives for its `signingKeyId` (walked from `trustAnchors` when
515
+ * given, `distrustedKeys` applied), inside that key's window at its
516
+ * `checkpointAt`, which is not earlier than the signed iat beyond the clock
517
+ * skew {@link READ_LOG_STAMP_SKEW_SECONDS} allows. A
518
+ * witness co-signature is verified under `cosignerKeys`.
519
+ *
520
+ * Throws `TypeError` when the input is not a checkpoint document, and on a
521
+ * malformed option.
522
+ */
523
+ export function verifyOrgReadCheckpoint(checkpoint, options = {}) {
524
+ const fn = 'verifyOrgReadCheckpoint';
525
+ const ctx = contextOf(fn, options);
526
+ const cp = asCheckpoint(fn, checkpoint);
527
+ const judged = judgeCheckpoint(cp, ctx, `Checkpoint ${JSON.stringify(cp['id'] ?? null)} at tree size ${JSON.stringify(cp['treeSize'] ?? null)}`);
528
+ const findings = [
529
+ ...(judged.finding !== undefined ? [judged.finding] : []),
530
+ ...keyFindings(ctx),
531
+ ...(judged.cosignFinding !== undefined ? [judged.cosignFinding] : []),
532
+ ];
533
+ const valid = findings.length === 0;
534
+ const keyTrust = settleKeyTrust(ctx.walkReport, judged.anchored);
535
+ const settled = conclude({ valid, findings, uncomputable: judged.uncomputable, keyTrust }, ctx, options, (o) => verifyOrgReadCheckpoint(checkpoint, o));
536
+ return { valid, ...settled, findings, keyTrust, checkpoint: judged.report };
537
+ }
538
+ /**
539
+ * Verify an inclusion proof offline: the tree head it is for (as
540
+ * `verifyOrgReadCheckpoint` does), the proof's tree size and root against
541
+ * that tree head's, and the RFC 9162 audit path from the leaf hash at the
542
+ * leaf's index to the signed root.
543
+ *
544
+ * `leaf` is what the path is walked from. A dump's `org_admin_reads` row
545
+ * carries the envelope: its hash is recomputed from the bytes, and its claim
546
+ * and signature are held to its row, so its columns are bound. A row of
547
+ * `GET /v1/audit/org-reads` carries the hash alone: the hash is walked, and
548
+ * its other columns are bound to nothing signed. Without a leaf, the proof's
549
+ * own `leafHash` is walked, which establishes only that some leaf with that
550
+ * hash sits at that index.
551
+ */
552
+ export function verifyOrgReadProof(proof, checkpoint, leaf, options = {}) {
553
+ const fn = 'verifyOrgReadProof';
554
+ const ctx = contextOf(fn, options);
555
+ if (!isProof(proof)) {
556
+ throw new TypeError(`${fn}: the proof is not GET /v1/audit/org-reads/checkpoints/{id}/proof ({ leafIndex, leafHash, treeSize, rootHash, path }).`);
557
+ }
558
+ const cp = asCheckpoint(fn, checkpoint);
559
+ const view = leaf === undefined || leaf === null ? null : leafView(leaf, 'leaf');
560
+ const judged = judgeCheckpoint(cp, ctx, `Checkpoint ${JSON.stringify(cp['id'] ?? null)} at tree size ${JSON.stringify(cp['treeSize'] ?? null)}`);
561
+ const findings = judged.finding !== undefined ? [judged.finding] : [];
562
+ let anchored = judged.anchored;
563
+ let uncomputable = judged.uncomputable;
564
+ const p = proof;
565
+ const index = Number.isSafeInteger(p['leafIndex']) ? p['leafIndex'] : null;
566
+ const proofFail = (detail) => {
567
+ findings.push({ code: 'TENANT_READ_PROOF_INVALID', detail: `Proof for leaf ${String(p['leafIndex'])}: ${detail}`, ...(index !== null ? { leafIndex: index } : {}) });
568
+ };
569
+ let leafReport = {
570
+ leafIndex: index,
571
+ leafHash: typeof p['leafHash'] === 'string' ? p['leafHash'] : null,
572
+ source: 'proof',
573
+ signature: 'not_checked',
574
+ fieldsBound: false,
575
+ };
576
+ let walkFrom = leafReport.leafHash;
577
+ if (view !== null) {
578
+ leafReport = { leafIndex: view.index, leafHash: view.hash, source: view.row !== null ? 'envelope' : 'entry', signature: 'not_checked', fieldsBound: false };
579
+ if (view.row !== null) {
580
+ const leafJudged = judgeLeafEnvelope(view, undefined, ctx, { signedBefore: false });
581
+ leafReport.signature = leafJudged.signature;
582
+ anchored += leafJudged.anchored;
583
+ uncomputable += leafJudged.uncomputable;
584
+ if (leafJudged.finding !== undefined)
585
+ findings.push(leafJudged.finding);
586
+ else
587
+ leafReport.fieldsBound = true;
588
+ }
589
+ walkFrom = view.hash;
590
+ if (view.orgId !== null && view.orgId !== cp['orgId']) {
591
+ proofFail(`the leaf is in org ${view.orgId}'s log and the checkpoint is ${String(cp['orgId'])}'s.`);
592
+ }
593
+ else if (view.index !== index) {
594
+ proofFail(`the proof is for leaf ${String(p['leafIndex'])} and the leaf given is leaf ${String(view.index)}.`);
595
+ }
596
+ else if (view.hash !== p['leafHash']) {
597
+ proofFail(`the proof's leafHash ${JSON.stringify(p['leafHash'])} is not the leaf's ${JSON.stringify(view.hash)}.`);
598
+ }
599
+ }
600
+ let inclusion = 'failed';
601
+ if (p['treeSize'] !== cp['treeSize'] || p['rootHash'] !== cp['rootHash']) {
602
+ proofFail(`the proof is for a tree of ${String(p['treeSize'])} leaves with root ${JSON.stringify(p['rootHash'])}, and the checkpoint signs ${String(cp['treeSize'])} leaves with root ${JSON.stringify(cp['rootHash'])}.`);
603
+ }
604
+ else if (index === null || !Number.isSafeInteger(p['treeSize']) || !Array.isArray(p['path']) || !p['path'].every((h) => typeof h === 'string')) {
605
+ proofFail('leafIndex, treeSize or path is not in the shape the Server serves.');
606
+ }
607
+ else if (typeof walkFrom !== 'string' || !verifyOrgReadInclusion(walkFrom, index, p['treeSize'], p['path'], cp['rootHash'])) {
608
+ proofFail(`the audit path does not walk leaf hash ${JSON.stringify(walkFrom)} at index ${index} to the signed root ${String(cp['rootHash'])} of the ${String(cp['treeSize'])}-leaf tree.`);
609
+ }
610
+ else {
611
+ inclusion = 'included';
612
+ }
613
+ findings.push(...keyFindings(ctx));
614
+ if (judged.cosignFinding !== undefined)
615
+ findings.push(judged.cosignFinding);
616
+ const valid = findings.length === 0;
617
+ const keyTrust = settleKeyTrust(ctx.walkReport, anchored);
618
+ const settled = conclude({ valid, findings, uncomputable, keyTrust }, ctx, options, (o) => verifyOrgReadProof(proof, checkpoint, leaf, o));
619
+ return { valid, ...settled, findings, keyTrust, checkpoint: judged.report, leaf: leafReport, inclusion };
620
+ }
621
+ /** The rows a list of documents carries: pages read as their `data`, arrays flattened. */
622
+ function rowsOf(input, what, fn) {
623
+ const one = (v) => (isRecord(v) && Array.isArray(v['data']) && !isCheckpoint(v) ? v['data'] : [v]);
624
+ if (Array.isArray(input))
625
+ return input.flatMap(one);
626
+ if (isRecord(input))
627
+ return one(input);
628
+ throw new TypeError(`${fn}: ${what} must be a page, an array of pages, or an array of rows.`);
629
+ }
630
+ /**
631
+ * Verify a walk over the read log offline: the leaves given (rows of
632
+ * `GET /v1/audit/org-reads`, or a dump's `org_admin_reads` rows) and the tree
633
+ * heads given (pages or rows of `GET /v1/audit/org-reads/checkpoints`), all
634
+ * of one org.
635
+ *
636
+ * Every tree head is verified as `verifyOrgReadCheckpoint` verifies it, and
637
+ * two at one tree size with different roots fail TENANT_CHECKPOINT_FORK. The
638
+ * leaves must be contiguous (TENANT_READ_LEAF_INDEX_GAP); two different rows
639
+ * at one index fail EXPORT_PAGE_CONFLICT. When the leaves start at index 0,
640
+ * the root over leaves [0, treeSize) is recomputed for every tree head whose
641
+ * size they reach and held to its signed root (TENANT_CHECKPOINT_ROOT_MISMATCH):
642
+ * that establishes the leaf hashes a tree head signs, in order. A tree head
643
+ * above the last leaf given, and every tree head when the leaves do not start
644
+ * at 0, is verified on its own and reported `not_comparable`. A leaf that
645
+ * carries its envelope is held to it as a dump's is, linked to the leaf
646
+ * before it; a listing row's other columns are bound to nothing signed.
647
+ */
648
+ export function verifyOrgReadLog(entries, checkpoints, options = {}) {
649
+ const fn = 'verifyOrgReadLog';
650
+ const ctx = contextOf(fn, options);
651
+ const leafRows = entries === undefined || entries === null ? [] : rowsOf(entries, 'entries', fn);
652
+ const cpRows = checkpoints === undefined || checkpoints === null ? [] : rowsOf(checkpoints, 'checkpoints', fn);
653
+ const leaves = leafRows.map((r, i) => leafView(r, `entries[${i}]`));
654
+ cpRows.forEach((r, i) => asCheckpoint(fn, r, `checkpoints[${i}]`));
655
+ const orgs = new Set([...leaves.map((l) => l.orgId), ...cpRows.map((r) => r['orgId'])].filter((o) => typeof o === 'string'));
656
+ if (orgs.size > 1)
657
+ throw new TypeError(`${fn}: the leaves and checkpoints given are of ${orgs.size} orgs (${[...orgs].join(', ')}); a walk reads one org's log.`);
658
+ const orgId = orgs.size === 1 ? [...orgs][0] ?? null : null;
659
+ const findings = [];
660
+ let anchored = 0;
661
+ let uncomputable = 0;
662
+ // The leaves, by index, once each.
663
+ const byIndex = new Map();
664
+ for (const leaf of leaves) {
665
+ if (leaf.index === null || leaf.index < 0) {
666
+ findings.push({ code: 'TENANT_READ_LEAF_INDEX_GAP', detail: `${leaf.source}: leafIndex is not a non-negative integer.` });
667
+ continue;
668
+ }
669
+ const prior = byIndex.get(leaf.index);
670
+ if (prior === undefined) {
671
+ byIndex.set(leaf.index, leaf);
672
+ }
673
+ else if (prior.hash !== leaf.hash || (prior.row !== null && leaf.row !== null && prior.row['cose_sign1'] !== leaf.row['cose_sign1'])) {
674
+ findings.push({ code: 'EXPORT_PAGE_CONFLICT', detail: `${prior.source} and ${leaf.source} are two different leaves at index ${leaf.index}: one of the pages was edited after the Server served it.`, leafIndex: leaf.index });
675
+ }
676
+ else if (prior.row === null && leaf.row !== null) {
677
+ byIndex.set(leaf.index, leaf);
678
+ }
679
+ }
680
+ const ordered = [...byIndex.values()].sort((a, b) => a.index - b.index);
681
+ const firstIndex = ordered[0]?.index ?? null;
682
+ const lastIndex = ordered.at(-1)?.index ?? null;
683
+ // Contiguous from the first index given; the held run stops at the first gap.
684
+ const run = [];
685
+ for (const leaf of ordered) {
686
+ const expected = firstIndex + run.length;
687
+ if (leaf.index !== expected) {
688
+ findings.push({ code: 'TENANT_READ_LEAF_INDEX_GAP', detail: `The leaves given skip from index ${expected - 1} to ${String(leaf.index)}: leaf ${expected} is missing from the log, or a page of the listing was left out.`, leafIndex: expected });
689
+ break;
690
+ }
691
+ run.push(leaf);
692
+ }
693
+ const mustSign = { signedBefore: false };
694
+ let withEnvelope = 0;
695
+ let signedLeaves = 0;
696
+ let leafFailed = false;
697
+ for (const [k, leaf] of run.entries()) {
698
+ if (leaf.hash === null || !HEX64.test(leaf.hash)) {
699
+ findings.push({ code: 'TENANT_READ_LEAF_HASH_MISMATCH', detail: `${leaf.source} (leaf ${String(leaf.index)}): leafHash ${JSON.stringify(leaf.hash)} is not 64 lowercase hex characters.`, leafIndex: leaf.index });
700
+ leafFailed = true;
701
+ break;
702
+ }
703
+ if (leaf.row === null)
704
+ continue;
705
+ withEnvelope++;
706
+ const prior = k > 0 ? run[k - 1] : undefined;
707
+ const previousHash = leaf.index === 0 ? null : prior !== undefined ? prior.hash : undefined;
708
+ const judged = judgeLeafEnvelope(leaf, previousHash, ctx, mustSign);
709
+ anchored += judged.anchored;
710
+ uncomputable += judged.uncomputable;
711
+ if (judged.signature === 'verified')
712
+ signedLeaves++;
713
+ if (judged.finding !== undefined) {
714
+ findings.push(judged.finding);
715
+ if (judged.finding.code !== UNSUPPORTED) {
716
+ leafFailed = true;
717
+ break;
718
+ }
719
+ }
720
+ }
721
+ const fromZero = firstIndex === 0;
722
+ const heldHashes = fromZero && !leafFailed ? run.map((l) => l.hash) : null;
723
+ // The tree heads. Two at one size with different roots are a fork, read
724
+ // from the fields served before anything else, as the dump reads them.
725
+ const rootsBySize = new Map();
726
+ cpRows.forEach((raw, i) => {
727
+ const cp = raw;
728
+ const size = cp['treeSize'];
729
+ if (!Number.isSafeInteger(size))
730
+ return;
731
+ const prior = rootsBySize.get(size);
732
+ if (prior === undefined)
733
+ rootsBySize.set(size, { root: cp['rootHash'], source: `checkpoints[${i}]` });
734
+ else if (prior.root !== cp['rootHash']) {
735
+ findings.push({ code: 'TENANT_CHECKPOINT_FORK', detail: `${prior.source} and checkpoints[${i}] both sign tree size ${String(size)} with different roots: a Server fork or a signing-key compromise.`, treeSize: size });
736
+ }
737
+ });
738
+ const listed = [];
739
+ let best = null;
740
+ for (const [i, raw] of cpRows.entries()) {
741
+ const cp = raw;
742
+ const source = `checkpoints[${i}]`;
743
+ const size = Number.isSafeInteger(cp['treeSize']) && cp['treeSize'] >= 0 ? cp['treeSize'] : null;
744
+ // The root over the leaves held, compared before the tree head's claim
745
+ // and key are read, as the Server's scan and the dump order them.
746
+ const comparable = heldHashes !== null && size !== null && size <= heldHashes.length;
747
+ const recomputed = heldHashes !== null && size !== null && comparable ? orgReadMerkleRoot(heldHashes.slice(0, size)) : null;
748
+ if (comparable && size !== null && recomputed !== cp['rootHash']) {
749
+ const detail = `The root over leaves 0 to ${size - 1} given is ${String(recomputed)}, and the tree head serves ${JSON.stringify(cp['rootHash'] ?? null)}.`;
750
+ findings.push({ code: 'TENANT_CHECKPOINT_ROOT_MISMATCH', detail: `${source}: ${detail} The leaves served are not the ones the tree head was taken over.`, treeSize: size });
751
+ const judged = judgeCheckpoint(cp, ctx, `${source} (tree size ${String(cp['treeSize'])})`);
752
+ listed.push({ ...judged.report, source, leaves: 'root_mismatch', detail });
753
+ continue;
754
+ }
755
+ const judged = judgeCheckpoint(cp, ctx, `${source} (tree size ${String(cp['treeSize'])})`);
756
+ anchored += judged.anchored;
757
+ uncomputable += judged.uncomputable;
758
+ if (judged.finding !== undefined)
759
+ findings.push(judged.finding);
760
+ if (judged.cosignFinding !== undefined)
761
+ findings.push(judged.cosignFinding);
762
+ let comparison = 'not_comparable';
763
+ let detail;
764
+ if (judged.finding !== undefined || size === null) {
765
+ detail = judged.finding?.detail ?? 'not a tree head.';
766
+ }
767
+ else if (comparable) {
768
+ comparison = 'root_recomputed';
769
+ detail = `The root over leaves 0 to ${size - 1} given is the signed root.`;
770
+ if (judged.report.state === 'verified' && (best === null || size > best.treeSize))
771
+ best = { treeSize: size, id: judged.report.id };
772
+ }
773
+ else if (heldHashes === null) {
774
+ detail = fromZero
775
+ ? 'Not compared: the leaves given failed before a root could be taken over them.'
776
+ : leaves.length === 0
777
+ ? 'Not compared: no leaves were given.'
778
+ : `Not compared: the leaves given start at index ${String(firstIndex)}, and a root is taken over leaves from index 0.`;
779
+ }
780
+ else {
781
+ detail = `Not compared: the tree head signs ${size} leaves and the leaves given hold ${heldHashes.length}.`;
782
+ }
783
+ listed.push({ ...judged.report, source, leaves: comparison, detail });
784
+ }
785
+ findings.push(...keyFindings(ctx));
786
+ const valid = findings.length === 0;
787
+ const keyTrust = settleKeyTrust(ctx.walkReport, anchored);
788
+ const settled = conclude({ valid, findings, uncomputable, keyTrust }, ctx, options, (o) => verifyOrgReadLog(entries, checkpoints, o));
789
+ const held = run.length;
790
+ const heldTo = best !== null
791
+ ? {
792
+ by: 'signed_checkpoint',
793
+ treeSize: best.treeSize,
794
+ checkpointId: best.id,
795
+ detail: best.treeSize === held
796
+ ? `Leaves 0 to ${held - 1} are the ones signed tree head ${String(best.id)} commits to.`
797
+ : `Leaves 0 to ${best.treeSize - 1} are the ones signed tree head ${String(best.id)} commits to; leaves ${best.treeSize} to ${held - 1} are held by the listing alone.`,
798
+ }
799
+ : {
800
+ by: 'listing',
801
+ treeSize: 0,
802
+ checkpointId: null,
803
+ detail: held === 0 ? 'No leaves were given.' : 'No signed tree head was recomputed from the leaves given: they are held by the listing alone.',
804
+ };
805
+ return {
806
+ valid,
807
+ ...settled,
808
+ findings,
809
+ keyTrust,
810
+ orgId,
811
+ leaves: { held, firstIndex, lastIndex, fromZero, withEnvelope, signed: signedLeaves },
812
+ checkpoints: listed,
813
+ heldTo,
814
+ fieldsBound: held > 0 && withEnvelope === held,
815
+ };
816
+ }