@agledger/verify-core 2.2.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 (49) hide show
  1. package/LICENSE +18 -18
  2. package/README.md +797 -29
  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 +343 -20
  10. package/dist/audit-export.js +400 -22
  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/chain.d.ts +135 -13
  18. package/dist/chain.js +229 -24
  19. package/dist/claim.d.ts +23 -0
  20. package/dist/claim.js +100 -0
  21. package/dist/export-anchors.d.ts +84 -0
  22. package/dist/export-anchors.js +109 -0
  23. package/dist/export-evidence.d.ts +90 -0
  24. package/dist/export-evidence.js +186 -0
  25. package/dist/export-pages.d.ts +476 -0
  26. package/dist/export-pages.js +586 -0
  27. package/dist/failures.d.ts +20 -16
  28. package/dist/failures.js +44 -16
  29. package/dist/federation-wire.d.ts +78 -11
  30. package/dist/federation-wire.js +199 -57
  31. package/dist/history-seal.d.ts +100 -0
  32. package/dist/history-seal.js +301 -0
  33. package/dist/index.d.ts +36 -8
  34. package/dist/index.js +17 -4
  35. package/dist/key-statements.d.ts +138 -5
  36. package/dist/key-statements.js +191 -20
  37. package/dist/ml-dsa-kats.d.ts +18 -0
  38. package/dist/ml-dsa-kats.js +241 -0
  39. package/dist/primitives.d.ts +255 -18
  40. package/dist/primitives.js +612 -55
  41. package/dist/read-log.d.ts +350 -0
  42. package/dist/read-log.js +816 -0
  43. package/dist/schema-chain-export.d.ts +82 -0
  44. package/dist/schema-chain-export.js +474 -0
  45. package/dist/walk-anchors.d.ts +115 -0
  46. package/dist/walk-anchors.js +133 -0
  47. package/dist/walk-checkpoints.d.ts +125 -0
  48. package/dist/walk-checkpoints.js +118 -0
  49. package/package.json +6 -5
package/dist/chain.d.ts CHANGED
@@ -36,6 +36,8 @@
36
36
  */
37
37
  import { type AgentPublicKeyJwk } from './primitives.js';
38
38
  import { type FederationKeyRegistry } from './federation-wire.js';
39
+ import { type BatchHeadRegistry, type BatchProofInput } from './batch.js';
40
+ import { type HistorySealPlan, type HistorySealProofInput } from './history-seal.js';
39
41
  import type { FailureCode } from './failures.js';
40
42
  /**
41
43
  * Where a verification key came from. `supplied`: the caller passed it (from
@@ -120,14 +122,24 @@ export declare function buildKeyRegistry(keys: readonly VerificationKey[]): KeyR
120
122
  * `predicate.on_behalf_of.cert.thumbprint`. Values are SPKI DER, base64.
121
123
  */
122
124
  export type AgentKeyRegistry = ReadonlyMap<string, string>;
125
+ /**
126
+ * An agent cert key as an agent records it: the JWK under `publicKeyJwk`,
127
+ * beside whatever else the record keeps (`certId`, `agentId`). Only the JWK is
128
+ * read.
129
+ */
130
+ export interface AgentKeyEntry {
131
+ publicKeyJwk: AgentPublicKeyJwk;
132
+ [field: string]: unknown;
133
+ }
123
134
  /**
124
135
  * Index caller-supplied agent cert keys by thumbprint. A key is matched to an
125
136
  * entry only through the thumbprint that entry signed, so a key supplied for
126
137
  * the wrong cert is never checked against it: it simply matches nothing.
127
138
  * That is also why the source of a key needs no trust: the signed thumbprint
128
- * is what binds it. Throws `TypeError` on anything that is not an Ed25519 JWK.
139
+ * is what binds it. Throws `TypeError` on anything that is not an agent cert
140
+ * key JWK (see `AgentPublicKeyJwk`).
129
141
  */
130
- export declare function buildAgentKeyRegistry(jwks: readonly AgentPublicKeyJwk[]): AgentKeyRegistry;
142
+ export declare function buildAgentKeyRegistry(jwks: ReadonlyArray<AgentPublicKeyJwk | AgentKeyEntry>): AgentKeyRegistry;
131
143
  /** One chain entry, plus the inputs the input-gated checks consume when the surface carries them. */
132
144
  export interface NormalizedEntry {
133
145
  /** Identity for messages: recordId (export) or chainKey (dump). */
@@ -171,6 +183,16 @@ export interface NormalizedEntry {
171
183
  detail: string;
172
184
  federationWire: boolean;
173
185
  };
186
+ /**
187
+ * The read time this entry is judged against when it carries the batch
188
+ * marker and no inclusion proof, as `batchPendingSince` is for the whole
189
+ * walk: set on an entry of a page walk, from the read time of the page it
190
+ * was served on. Present (a string or null), it takes the place of
191
+ * `batchPendingSince` for this entry; null reads as nothing dating it.
192
+ * Throws `TypeError` from `verifyChain` when it is a string that does not
193
+ * parse.
194
+ */
195
+ batchPendingSince?: string | null;
174
196
  /** Inputs for the OIDC-actor cross-check (dump path). */
175
197
  oidcActor?: {
176
198
  iss: string | null;
@@ -197,6 +219,19 @@ export interface NormalizedEntry {
197
219
  inlinedEvidence?: {
198
220
  value: unknown;
199
221
  };
222
+ /**
223
+ * The inclusion proof the artifact carries for an entry written under the
224
+ * batched signing cadence (an export's `integrity.batch`, a dump's
225
+ * `vault_batch_leaves.ndjson` row). Read only on an entry whose protected
226
+ * header carries the batch marker.
227
+ */
228
+ batch?: BatchProofInput | null;
229
+ /**
230
+ * The chain key a batch leaf names for this entry's chain: the record id on
231
+ * a record chain, the schema chain's checkpoint key on a schema chain. When
232
+ * absent, `scopeId` is used, which is right for a record export.
233
+ */
234
+ batchChainKey?: string;
200
235
  }
201
236
  /**
202
237
  * Checks that run only when their input is present. `agent_signature` is
@@ -204,7 +239,7 @@ export interface NormalizedEntry {
204
239
  * had its cert key supplied by the caller (`agentKeys`); neither the export
205
240
  * nor the dump carries cert public keys.
206
241
  */
207
- export type OptionalCheck = 'payload_binding' | 'oidc_actor' | 'actor_attribution' | 'key_temporal' | 'agent_signature' | 'key_anchoring' | 'federation_wire' | 'evidence_binding';
242
+ export type OptionalCheck = 'payload_binding' | 'oidc_actor' | 'actor_attribution' | 'key_temporal' | 'agent_signature' | 'key_anchoring' | 'federation_wire' | 'evidence_binding' | 'history_seal';
208
243
  /**
209
244
  * `applied`: the check ran. `skipped_no_input`: the input it needs is absent.
210
245
  * `not_checked`: the input was given but no entry reached the check, because
@@ -230,15 +265,22 @@ export interface SignatureOutcome {
230
265
  * - `unsupported`: the signature could not be computed at all, either
231
266
  * because this build does not implement the algorithm or because the host
232
267
  * runtime refused it (an active OpenSSL FIPS provider carries no EdDSA).
233
- * CHAIN_UNSUPPORTED_ALGORITHM. A failure state, never a benign skip, and
234
- * never tamper evidence: distinguishing it from `invalid` is the whole
235
- * point, since only `invalid` means a signature was checked and failed.
268
+ * CHAIN_UNSUPPORTED_ALGORITHM. Never a benign skip and never a pass: the
269
+ * entry is not verified and the result is not valid. Never tamper
270
+ * evidence either: distinguishing it from `invalid` is the whole point,
271
+ * since only `invalid` means a signature was checked and failed. A result
272
+ * that would be valid had the checks this host refused, under algorithms
273
+ * this build supports, verified reads `unverifiable`, not `failed` (see
274
+ * `isUnverifiable`).
275
+ * - `pending`: the entry was written under the batched signing cadence and
276
+ * no batch head covers it yet, inside the time the Server lets one wait.
277
+ * Nothing signs it so far. Not a failure and not a verified signature.
236
278
  * - `accounted`: the signature verifies under a key `distrustedKeys` names,
237
279
  * outside what the key is trusted for, and the entry was written before a
238
280
  * key the walk trusts retired it (dumps only). Not a failure and not a
239
281
  * verified entry: see {@link AccountedEntry}.
240
282
  */
241
- state: 'ok' | 'invalid' | 'unsigned' | 'skipped' | 'not-checked' | 'decode-fail' | 'unsupported' | 'accounted';
283
+ state: 'ok' | 'invalid' | 'unsigned' | 'skipped' | 'not-checked' | 'decode-fail' | 'unsupported' | 'accounted' | 'pending';
242
284
  /** Provenance of the key the signature was checked against ('ok' / 'invalid'). */
243
285
  keySource?: KeySource;
244
286
  }
@@ -257,6 +299,15 @@ export interface ChainEntryResult {
257
299
  };
258
300
  signature: SignatureOutcome['state'];
259
301
  keySource?: KeySource;
302
+ /** True on an entry signed through a batch head rather than by its own signature. */
303
+ batched?: boolean;
304
+ /**
305
+ * On an entry an Ed25519, ES256 or ES384 key signed, when the walk trusts an
306
+ * ML-DSA key: `sealed` when it sits at or below its chain's leaf in the
307
+ * history seal covering that key, `unsealed` when no seal covers the key.
308
+ * An unsealed entry is valid and rests on its classical signature alone.
309
+ */
310
+ historySeal?: 'sealed' | 'unsealed';
260
311
  }
261
312
  /** The code an {@link AccountedEntry} carries. Not a {@link FailureCode}: it never fails a verdict. */
262
313
  export declare const ACCOUNTED_ENTRY_CODE = "CHAIN_SIGNED_BY_DISTRUSTED_KEY";
@@ -294,6 +345,11 @@ export interface ChainResult {
294
345
  scopeId: string;
295
346
  valid: boolean;
296
347
  totalEntries: number;
348
+ /**
349
+ * Entries that passed every check. A batched entry no head covers yet
350
+ * (`signature: 'pending'`) is not one: it counts toward `valid` and in
351
+ * `signatureCoverage.pending`, and not here.
352
+ */
297
353
  verifiedEntries: number;
298
354
  brokenAt?: {
299
355
  position: number;
@@ -307,12 +363,7 @@ export interface ChainResult {
307
363
  * or `signatureCoverage.signed`.
308
364
  */
309
365
  accounted: AccountedEntry[];
310
- signatureCoverage: {
311
- signed: number;
312
- unsigned: number;
313
- skipped: number;
314
- total: number;
315
- };
366
+ signatureCoverage: SignatureCoverage;
316
367
  /** Which input-gated checks actually ran on this chain vs were skipped for absent input. */
317
368
  optionalChecks: Record<OptionalCheck, CheckApplicability>;
318
369
  /** How many signature checks resolved against supplied vs embedded keys. */
@@ -365,6 +416,23 @@ export interface ChainResult {
365
416
  * nothing signed binds a body. Always zero on a dump, which carries none.
366
417
  */
367
418
  evidenceBinding: EvidenceBindingCounts;
419
+ /** How entries classical keys signed stand against the artifact's history seals; all zero when no seal policy applies. */
420
+ historySeal: HistorySealCounts;
421
+ }
422
+ /**
423
+ * How many entries carried a verified signature (`signed`), none by design
424
+ * (`skipped`: written before the install began signing), or none yet
425
+ * (`pending`: a batched entry still waiting for its batch head). `batched`
426
+ * counts the `signed` entries that are signed through a batch head rather
427
+ * than by a signature of their own.
428
+ */
429
+ export interface SignatureCoverage {
430
+ signed: number;
431
+ unsigned: number;
432
+ skipped: number;
433
+ total: number;
434
+ pending: number;
435
+ batched: number;
368
436
  }
369
437
  /** See {@link ChainResult.evidenceBinding}. */
370
438
  export interface EvidenceBindingCounts {
@@ -422,6 +490,48 @@ export interface VerifyChainOptions {
422
490
  * switching the check off.
423
491
  */
424
492
  signingSince?: string | null;
493
+ /**
494
+ * The artifact's batch heads, judged (see `buildBatchHeadRegistry`). An
495
+ * entry carrying the batch marker is verified through its inclusion proof
496
+ * and the head it names here.
497
+ */
498
+ batchHeads?: BatchHeadRegistry;
499
+ /**
500
+ * The instant from which a batched entry with no inclusion proof is still
501
+ * inside the time the Server lets it wait for a head: the instant the
502
+ * artifact was cut, less `BATCH_PENDING_GRACE_SECONDS`. An unattested entry
503
+ * written at or after it is `pending`; one written before it, or when this
504
+ * is absent or null, fails BATCH_UNATTESTED. Throws `TypeError` when it is
505
+ * a string that does not parse.
506
+ */
507
+ batchPendingSince?: string | null;
508
+ /**
509
+ * The artifact's history seals, judged (see `planHistorySeals`). With it,
510
+ * every entry a classical key signed is held to the seal covering that key.
511
+ */
512
+ historySeals?: HistorySealPlan;
513
+ /**
514
+ * This chain's inclusion proof in each seal, by seal id (lowercase); null or
515
+ * absent where the seal has no leaf for the chain.
516
+ */
517
+ historySealProofs?: ReadonlyMap<string, HistorySealProofInput | null>;
518
+ /**
519
+ * Walk the entries as a run of positions inside a longer chain rather than
520
+ * as the whole chain: the first entry is expected at `startPosition` and
521
+ * links to `previousHash`, the hash of the entry before it, which the
522
+ * artifact does not carry. Every entry is held to the same checks as on a
523
+ * whole chain; what lies below `startPosition` is not examined. A run that
524
+ * starts above position 1 with a null `previousHash` fails its first entry
525
+ * CHAIN_LINK_BROKEN. `openEnd` says the artifact does not establish the
526
+ * chain's tip, so a history seal whose sealed position lies above the last
527
+ * entry is not compared with an entry. Omitted, the chain starts at
528
+ * position 1 and its last entry is its tip.
529
+ */
530
+ slice?: {
531
+ startPosition: number;
532
+ previousHash: string | null;
533
+ openEnd?: boolean;
534
+ };
425
535
  }
426
536
  /**
427
537
  * The earliest `activatedAt` among `keys`, as the ISO string it was given in,
@@ -447,6 +557,18 @@ export declare function earliestKeyActivation(keys: Iterable<{
447
557
  * before signing began. It fails closed rather than reading as early history.
448
558
  */
449
559
  export declare function writtenWhileSigning(writtenAt: unknown, signingSince: string | null | undefined): boolean;
560
+ /** How the entries classical keys signed stand against the history seals. */
561
+ export interface HistorySealCounts {
562
+ /** Entries at or below their chain's leaf in the seal covering their key. */
563
+ sealed: number;
564
+ /** Valid entries under a classical key that no seal covers. */
565
+ unsealed: number;
566
+ /** Each such key, once, with what would seal it. */
567
+ unsealedKeys: Array<{
568
+ keyId: string;
569
+ detail: string;
570
+ }>;
571
+ }
450
572
  /**
451
573
  * Verify a single hash chain. `entries` are all the entries for one scope; they
452
574
  * are sorted by chainPosition internally (so a reordered export array still
package/dist/chain.js CHANGED
@@ -34,9 +34,11 @@
34
34
  * activation (`signingSince`), is CHAIN_ENTRY_UNSIGNED; an earlier one is a
35
35
  * `skipped` signature, reduced coverage rather than a break.
36
36
  */
37
- import { buildPredicateForRow, decodeCoseSign1, decodePredicate, deepEqual, describeUnsupportedAlgorithm, ed25519JwkThumbprint, ed25519JwkToSpki, extractAgentSignatureClaim, extractActorClaim, extractChainClaim, extractKid, extractOnBehalfOfClaim, resolveKeyAlgorithm, sha256Hex, stripEnvelopeExtensions, envelopeExtensionsMatch, verifyAgentSignature, verifyCoseSign1, } from './primitives.js';
37
+ import { hostRefusalCause, buildPredicateForRow, decodeCoseSign1, decodePredicate, deepEqual, describeUnsupportedAlgorithm, resolveKeyAlgorithmOrHostRefused, agentJwkThumbprint, agentJwkToSpki, agentKeyAlgorithm, extractAgentSignatureClaim, extractActorClaim, extractChainClaim, extractHeaderAlg, extractKid, extractOnBehalfOfClaim, resolveKeyAlgorithm, sha256Hex, stripEnvelopeExtensions, envelopeExtensionsMatch, verifyAgentSignature, verifyCoseSign1, } from './primitives.js';
38
38
  import { canonicalizeJson, checkFederationWire, extractFederationWire } from './federation-wire.js';
39
39
  import { createHash } from 'node:crypto';
40
+ import { checkBatchProof, isBatchedProtectedHeader } from './batch.js';
41
+ import { resolveHistorySealLeaf } from './history-seal.js';
40
42
  import { instantMs, rfc3339Ms } from './instant.js';
41
43
  import { assertKnownOptions } from './options.js';
42
44
  /**
@@ -53,23 +55,28 @@ export function buildKeyRegistry(keys) {
53
55
  }
54
56
  return map;
55
57
  }
58
+ const AGENT_JWK_SHAPES = 'Expected { kty: "AKP", alg: "ML-DSA-87" | "ML-DSA-65", pub }, { kty: "EC", crv: "P-384", x, y }, or for a cert issued before Server 4.0.0 { kty: "OKP", crv: "Ed25519", x }, each member base64url.';
56
59
  /**
57
60
  * Index caller-supplied agent cert keys by thumbprint. A key is matched to an
58
61
  * entry only through the thumbprint that entry signed, so a key supplied for
59
62
  * the wrong cert is never checked against it: it simply matches nothing.
60
63
  * That is also why the source of a key needs no trust: the signed thumbprint
61
- * is what binds it. Throws `TypeError` on anything that is not an Ed25519 JWK.
64
+ * is what binds it. Throws `TypeError` on anything that is not an agent cert
65
+ * key JWK (see `AgentPublicKeyJwk`).
62
66
  */
63
67
  export function buildAgentKeyRegistry(jwks) {
64
68
  if (!Array.isArray(jwks)) {
65
- throw new TypeError('agentKeys must be an array of Ed25519 JWKs ({ kty: "OKP", crv: "Ed25519", x }).');
69
+ throw new TypeError(`agentKeys must be an array of agent cert key JWKs. ${AGENT_JWK_SHAPES}`);
66
70
  }
67
71
  const map = new Map();
68
- jwks.forEach((jwk, i) => {
69
- const thumbprint = ed25519JwkThumbprint(jwk);
70
- const spki = ed25519JwkToSpki(jwk);
72
+ jwks.forEach((given, i) => {
73
+ // An entry of the keys file an agent keeps: the JWK under `publicKeyJwk`.
74
+ const entry = given;
75
+ const jwk = (typeof entry === 'object' && entry !== null && 'publicKeyJwk' in entry ? entry.publicKeyJwk : entry);
76
+ const thumbprint = agentJwkThumbprint(jwk);
77
+ const spki = agentJwkToSpki(jwk);
71
78
  if (thumbprint === null || spki === null) {
72
- throw new TypeError(`agentKeys[${i}] is not an Ed25519 public-key JWK. Expected { kty: "OKP", crv: "Ed25519", x: <base64url of 32 bytes> }, the publicKeyJwk sent at cert exchange (also the cnf.jwk claim inside the certJws).`);
79
+ throw new TypeError(`agentKeys[${i}] is not an agent cert key JWK. ${AGENT_JWK_SHAPES} It is the publicKeyJwk sent at cert exchange (also the cnf.jwk claim inside the certJws), bare or as { publicKeyJwk: {...} }.`);
73
80
  }
74
81
  map.set(thumbprint, spki);
75
82
  });
@@ -150,14 +157,20 @@ function positionKey(position) {
150
157
  * validates the true chain; tampering surfaces through the hash links).
151
158
  */
152
159
  export function verifyChain(entries, keys, options = {}) {
153
- assertKnownOptions('verifyChain', options, ['requireKeyId', 'requireSuppliedKeys', 'agentKeys', 'federationKeys', 'allowAfterRetirement', 'signingSince']);
160
+ assertKnownOptions('verifyChain', options, ['requireKeyId', 'requireSuppliedKeys', 'agentKeys', 'federationKeys', 'allowAfterRetirement', 'signingSince', 'batchHeads', 'batchPendingSince', 'historySeals', 'historySealProofs', 'slice']);
161
+ const start = options.slice?.startPosition ?? 1;
162
+ if (!Number.isSafeInteger(start) || start < 1
163
+ || (options.slice !== undefined && options.slice.previousHash !== null && typeof options.slice.previousHash !== 'string')
164
+ || (options.slice?.openEnd !== undefined && typeof options.slice.openEnd !== 'boolean')) {
165
+ throw new TypeError(`slice must be { startPosition: a positive integer, previousHash: a string or null, openEnd?: a boolean } (got ${JSON.stringify(options.slice)}).`);
166
+ }
154
167
  const scopeId = entries[0]?.scopeId ?? '(empty)';
155
168
  const sorted = entries
156
169
  .map((entry, at) => ({ entry, at, key: positionKey(entry.chainPosition) }))
157
170
  .sort((a, b) => (a.key === b.key ? a.at - b.at : a.key < b.key ? -1 : 1))
158
171
  .map(({ entry }) => entry);
159
172
  const entryResults = [];
160
- const coverage = { signed: 0, unsigned: 0, skipped: 0, total: sorted.length };
173
+ const coverage = { signed: 0, unsigned: 0, skipped: 0, total: sorted.length, pending: 0, batched: 0 };
161
174
  const optionalChecks = {
162
175
  payload_binding: 'skipped_no_input',
163
176
  oidc_actor: 'skipped_no_input',
@@ -167,12 +180,16 @@ export function verifyChain(entries, keys, options = {}) {
167
180
  key_anchoring: 'skipped_no_input',
168
181
  federation_wire: 'skipped_no_input',
169
182
  evidence_binding: 'skipped_no_input',
183
+ history_seal: 'skipped_no_input',
170
184
  };
171
185
  const keyProvenance = { supplied: 0, embedded: 0 };
172
186
  const agentSignatures = { present: 0, verified: 0 };
173
187
  const federationWire = { present: 0, verified: 0, failed: 0, afterRetirement: 0 };
174
188
  const evidenceBinding = { present: 0, verified: 0, clientHashed: 0, failed: 0 };
189
+ const historySeal = { sealed: 0, unsealed: 0, unsealedKeys: [] };
175
190
  let verifiedEntries = 0;
191
+ // Batched entries no head covers yet that passed every other check.
192
+ let awaitingHead = 0;
176
193
  let brokenAt;
177
194
  const accounted = [];
178
195
  if (sorted.length === 0) {
@@ -190,6 +207,7 @@ export function verifyChain(entries, keys, options = {}) {
190
207
  agentSignatures,
191
208
  federationWire,
192
209
  evidenceBinding,
210
+ historySeal,
193
211
  };
194
212
  }
195
213
  let signingSince;
@@ -203,12 +221,54 @@ export function verifyChain(entries, keys, options = {}) {
203
221
  }
204
222
  }
205
223
  const mustSign = { signedBefore: false, signingSince };
224
+ const pendingSince = options.batchPendingSince ?? null;
225
+ if (pendingSince !== null && Number.isNaN(instantMs(pendingSince))) {
226
+ throw new TypeError(`batchPendingSince must be an RFC 3339 instant or null (got ${JSON.stringify(pendingSince)}).`);
227
+ }
228
+ for (const entry of entries) {
229
+ const own = entry.batchPendingSince;
230
+ if (own !== undefined && own !== null && (typeof own !== 'string' || Number.isNaN(instantMs(own)))) {
231
+ throw new TypeError(`An entry's batchPendingSince must be an RFC 3339 instant or null (got ${JSON.stringify(own)}).`);
232
+ }
233
+ }
234
+ const batchContext = { heads: options.batchHeads ?? new Map(), pendingSince };
235
+ // This chain's leaf in each seal, resolved once: the proof must reach the
236
+ // signed root, and the entry this chain holds at the sealed position must be
237
+ // the one the leaf names. That second half is what binds the entries below
238
+ // the tip, through the hash chain, to the ML-DSA-signed root.
239
+ const sealChainKey = sorted[0]?.batchChainKey ?? scopeId;
240
+ const sealLeaves = new Map();
241
+ const sealLeafOf = (seal) => {
242
+ const id = seal.id.toLowerCase();
243
+ const known = sealLeaves.get(id);
244
+ if (known)
245
+ return known;
246
+ let leaf = resolveHistorySealLeaf(seal, sealChainKey, options.historySealProofs?.get(id));
247
+ // A sealed tip below a run that starts above position 1, or above the
248
+ // last entry of a run whose tip is not established, is outside the run:
249
+ // there is nothing here to compare it with, and the caller reads such a
250
+ // run as a slice of its chain.
251
+ const outside = leaf.state === 'ok' && (leaf.chainPosition < start || (options.slice?.openEnd === true && leaf.chainPosition - start >= sorted.length));
252
+ if (leaf.state === 'ok' && !outside) {
253
+ const tip = sorted[leaf.chainPosition - start];
254
+ if (!tip) {
255
+ leaf = { state: 'invalid', detail: `History seal ${seal.id} seals this chain at position ${leaf.chainPosition}, and the artifact carries ${sorted.length} entries: the sealed entry is not here to compare.` };
256
+ }
257
+ else if (tip.payloadHash !== leaf.entryHash) {
258
+ leaf = { state: 'invalid', detail: `History seal ${seal.id} seals this chain at position ${leaf.chainPosition} with entry hash ${leaf.entryHash.slice(0, 16)}..., and the entry at that position hashes to ${String(tip.payloadHash).slice(0, 16)}...` };
259
+ }
260
+ }
261
+ sealLeaves.set(id, leaf);
262
+ return leaf;
263
+ };
206
264
  const unbound = { payload: false, federation: false };
207
- let previousHash = null;
265
+ let previousHash = options.slice?.previousHash ?? null;
208
266
  for (let i = 0; i < sorted.length; i++) {
209
267
  const entry = sorted[i];
210
- const expectedPosition = i + 1;
211
- let result = verifyEntry(entry, expectedPosition, previousHash, keys, options, optionalChecks, mustSign);
268
+ const expectedPosition = start + i;
269
+ let result = i === 0 && start > 1 && previousHash === null
270
+ ? fail(scopeId, start, 'CHAIN_LINK_BROKEN', `The run starts at position ${start} and its first entry names no previous entry: only position 1 links to nothing.`)
271
+ : verifyEntry(entry, expectedPosition, previousHash, keys, options, optionalChecks, mustSign, batchContext);
212
272
  // As the Server's walk does: any earlier row naming a key, whatever its own
213
273
  // verdict, means this chain was already being signed.
214
274
  if (entry.signingKeyId !== null)
@@ -228,6 +288,40 @@ export function verifyChain(entries, keys, options = {}) {
228
288
  if (result.valid && result.accounted === undefined && entry.inlinedEvidence !== undefined) {
229
289
  result = checkInlinedEvidence(entry, entry.inlinedEvidence.value, result, optionalChecks, evidenceBinding);
230
290
  }
291
+ if (result.valid && result.accounted === undefined && entry.signingKeyId !== null && options.historySeals !== undefined) {
292
+ const cover = options.historySeals.coverOf(entry.signingKeyId);
293
+ if (cover !== null) {
294
+ optionalChecks.history_seal = 'applied';
295
+ if (cover.state === 'unsealed') {
296
+ result = { ...result, historySeal: 'unsealed' };
297
+ historySeal.unsealed++;
298
+ if (!historySeal.unsealedKeys.some((k) => k.keyId === entry.signingKeyId))
299
+ historySeal.unsealedKeys.push({ keyId: entry.signingKeyId, detail: cover.detail });
300
+ }
301
+ else if (cover.state === 'unsupported') {
302
+ result = failAfterSignature(entry, result, 'CHAIN_UNSUPPORTED_ALGORITHM', cover.detail);
303
+ }
304
+ else if (cover.state === 'invalid') {
305
+ result = failAfterSignature(entry, result, 'HISTORY_SEAL_INVALID', cover.detail);
306
+ }
307
+ else {
308
+ const leaf = sealLeafOf(cover.seal);
309
+ if (leaf.state === 'missing') {
310
+ result = failAfterSignature(entry, result, 'HISTORY_SEAL_MISSING_CHAIN', `Entry is signed by key ${entry.signingKeyId}, and history seal ${cover.seal.id}, which covers that key, has no leaf for this chain.`);
311
+ }
312
+ else if (leaf.state === 'invalid') {
313
+ result = failAfterSignature(entry, result, 'HISTORY_SEAL_INVALID', leaf.detail);
314
+ }
315
+ else if (expectedPosition > leaf.chainPosition) {
316
+ result = failAfterSignature(entry, result, 'HISTORY_SEAL_EXCEEDED', `Entry at position ${expectedPosition} is signed by key ${entry.signingKeyId}, and history seal ${cover.seal.id}, which covers that key, sealed this chain at position ${leaf.chainPosition}.`);
317
+ }
318
+ else {
319
+ result = { ...result, historySeal: 'sealed' };
320
+ historySeal.sealed++;
321
+ }
322
+ }
323
+ }
324
+ }
231
325
  entryResults.push(result);
232
326
  if (result.accounted !== undefined) {
233
327
  accounted.push({
@@ -239,14 +333,20 @@ export function verifyChain(entries, keys, options = {}) {
239
333
  detail: result.accounted.detail,
240
334
  });
241
335
  }
242
- else if (result.valid)
243
- verifiedEntries++;
336
+ else if (result.valid) {
337
+ if (result.signature === 'pending')
338
+ awaitingHead++;
339
+ else
340
+ verifiedEntries++;
341
+ }
244
342
  else if (!brokenAt && result.failure) {
245
343
  brokenAt = { position: result.position, code: result.failure.code, detail: result.failure.detail };
246
344
  }
247
345
  switch (result.signature) {
248
346
  case 'ok':
249
347
  coverage.signed++;
348
+ if (result.batched === true)
349
+ coverage.batched++;
250
350
  if (result.keySource === 'supplied')
251
351
  keyProvenance.supplied++;
252
352
  else if (result.keySource === 'embedded')
@@ -258,6 +358,9 @@ export function verifyChain(entries, keys, options = {}) {
258
358
  case 'skipped':
259
359
  coverage.skipped++;
260
360
  break;
361
+ case 'pending':
362
+ coverage.pending++;
363
+ break;
261
364
  // 'not-checked' / 'invalid' / 'decode-fail' / 'unsupported' are failure
262
365
  // states: the entry is already counted as broken, so it contributes to
263
366
  // no coverage bucket.
@@ -278,7 +381,7 @@ export function verifyChain(entries, keys, options = {}) {
278
381
  }
279
382
  return {
280
383
  scopeId,
281
- valid: verifiedEntries + accounted.length === sorted.length,
384
+ valid: verifiedEntries + accounted.length + awaitingHead === sorted.length,
282
385
  totalEntries: sorted.length,
283
386
  verifiedEntries,
284
387
  brokenAt,
@@ -290,6 +393,7 @@ export function verifyChain(entries, keys, options = {}) {
290
393
  agentSignatures,
291
394
  federationWire,
292
395
  evidenceBinding,
396
+ historySeal,
293
397
  };
294
398
  }
295
399
  /** The payload field each entry type signs an inlined evidence body's hash under. */
@@ -369,6 +473,11 @@ function checkSealedFederationWire(entry, result, federationKeys, optionalChecks
369
473
  counts.failed++;
370
474
  return failAfterSignature(entry, result, outcome.outcome === 'unsupported' ? 'CHAIN_UNSUPPORTED_ALGORITHM' : 'CHAIN_FEDERATION_WIRE_INVALID', outcome.detail);
371
475
  }
476
+ /** Whether a sealed `alg` names another algorithm than the cert key's own. */
477
+ function agentSignatureLabelDiffers(spki, alg) {
478
+ const name = agentKeyAlgorithm(spki)?.name;
479
+ return name !== undefined && alg !== (name === 'Ed25519' ? 'EdDSA' : name);
480
+ }
372
481
  /**
373
482
  * Offline re-check of a sealed agent signature, on an entry that already
374
483
  * passed every other check (so its payload is the Server's signed bytes).
@@ -400,11 +509,11 @@ function checkAgentSignature(entry, result, agentKeys, optionalChecks, counts) {
400
509
  }
401
510
  const certLabel = claim.certId ?? claim.certThumbprint;
402
511
  if (outcome === 'unsupported') {
403
- return failAfterSignature(entry, result, 'CHAIN_UNSUPPORTED_ALGORITHM', `Agent signature for cert ${certLabel} could not be checked: this host cannot compute Ed25519 (an active OpenSSL FIPS provider carries no EdDSA). Not verified, and not tamper evidence.`);
512
+ return failAfterSignature(entry, result, 'CHAIN_UNSUPPORTED_ALGORITHM', `Agent signature for cert ${certLabel} could not be checked: this host cannot compute ${refusedAgentAlgorithm(spki)}. Not verified, and not tamper evidence.`);
404
513
  }
405
514
  return failAfterSignature(entry, result, 'CHAIN_AGENT_SIGNATURE_INVALID', outcome === 'malformed'
406
- ? `Sealed agent_signature for cert ${certLabel} has a shape nothing can verify (alg must be EdDSA, content_hash sha256:<hex64>, signature 64 bytes of standard base64).`
407
- : `Sealed agent_signature for cert ${certLabel} does not verify under the supplied key with thumbprint ${claim.certThumbprint}.`);
515
+ ? `Sealed agent_signature for cert ${certLabel} has a shape nothing can verify (alg must be ML-DSA-87, ML-DSA-65, ES384 or EdDSA, content_hash sha256:<hex64>, signature standard base64 at the algorithm's length).`
516
+ : `Sealed agent_signature for cert ${certLabel} does not verify under the supplied key with thumbprint ${claim.certThumbprint}${agentSignatureLabelDiffers(spki, claim.alg) ? `: it is sealed as ${String(claim.alg)}, and that key is ${agentKeyAlgorithm(spki)?.name ?? 'another algorithm'}` : ''}.`);
408
517
  }
409
518
  function accountedResult(scopeId, position, detail) {
410
519
  return { scopeId, position, valid: true, accounted: { code: ACCOUNTED_ENTRY_CODE, detail }, signature: 'accounted' };
@@ -425,9 +534,11 @@ function fail(scopeId, position, code, detail, signature = 'not-checked', keySou
425
534
  * counts every signed entry (`signed = supplied + embedded`).
426
535
  */
427
536
  function failAfterSignature(entry, result, code, detail) {
428
- return fail(entry.scopeId, result.position, code, detail, result.signature, result.keySource);
537
+ const failed = fail(entry.scopeId, result.position, code, detail, result.signature, result.keySource);
538
+ // The signature state survives a later failure, so how it was signed does too.
539
+ return result.batched === true ? { ...failed, batched: true } : failed;
429
540
  }
430
- function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, optionalChecks, mustSign) {
541
+ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, optionalChecks, mustSign, batchContext) {
431
542
  const { scopeId } = entry;
432
543
  if (entry.chainPosition !== expectedPosition) {
433
544
  return fail(scopeId, entry.chainPosition, 'CHAIN_POSITION_GAP', `Expected chainPosition ${expectedPosition}, got ${entry.chainPosition}.`);
@@ -580,16 +691,29 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
580
691
  // key material the registry does not lie about: anything else under
581
692
  // its id is bytes the database's writer wrote.
582
693
  const bound = key.distrustSpan?.retiredAt ?? null;
694
+ // A batched entry carries no signature of its own: the head that covers
695
+ // it is what has to hold.
696
+ const holds = () => {
697
+ if (!isBatchedProtectedHeader(parts.protectedBstr))
698
+ return verifyCoseSign1(envelopeBytes, key.spkiBase64) === 'ok';
699
+ const judged = judgeBatchedEntry(entry, expectedPosition, parts, key, batchContext);
700
+ return judged.state === 'ok' || judged.state === 'accounted';
701
+ };
583
702
  if (bound !== null && isInstant(entry.createdAt) && rfc3339Ms(entry.createdAt) < instantMs(bound)
584
- && !declaredAlgorithmLies(key) && verifyCoseSign1(envelopeBytes, key.spkiBase64) === 'ok') {
703
+ && !declaredAlgorithmLies(key) && holds()) {
585
704
  return accountedResult(scopeId, expectedPosition, `Entry written ${entry.createdAt} is signed by key ${entry.signingKeyId}, which distrustedKeys names and no signed key statement links to a pinned trust anchor, before ${bound}, when a key the walk trusts retired it: the distrust entry accounts for it. Not verified, and not a failure.`);
586
705
  }
587
706
  return fail(scopeId, expectedPosition, 'CHAIN_SIGNING_KEY_UNANCHORED', `Key ${entry.signingKeyId} is not linked by any signed key statement to a pinned trust anchor.`);
588
707
  }
589
- if (key.trust === 'undecided') {
590
- return fail(scopeId, expectedPosition, 'CHAIN_UNSUPPORTED_ALGORITHM', `Key ${entry.signingKeyId} is linked to a pinned anchor only through a key statement signed under an algorithm this host cannot compute, and ${describeUnsupportedAlgorithm(key.spkiBase64)}`, 'unsupported');
591
- }
592
708
  }
709
+ // A key linked to a pin only through a statement this host could not check.
710
+ // The checks that need no computation (the registry's own consistency, the
711
+ // window, the signature's shape) still run first, so a failure they find is
712
+ // named whatever this host can compute; only an entry that passes them reads
713
+ // as could-not-compute.
714
+ const undecided = key.trust === 'undecided'
715
+ ? () => fail(scopeId, expectedPosition, 'CHAIN_UNSUPPORTED_ALGORITHM', `Key ${entry.signingKeyId} is linked to a pinned anchor only through a key statement signed under an algorithm this host cannot compute, and ${describeUnsupportedAlgorithm(key.spkiBase64)}`, 'unsupported')
716
+ : null;
593
717
  // Registry self-consistency: when the input surface declares an algorithm for
594
718
  // this key, it must agree with what the SPKI
595
719
  // key material commits to. A registry row that lies about its own key is the
@@ -631,7 +755,31 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
631
755
  }
632
756
  }
633
757
  }
758
+ // The batched cadence: the marker in the protected header says the entry is
759
+ // signed through a batch head. An entry without the marker is held to its
760
+ // own signature below, where an empty one fails CHAIN_SIGNATURE_INVALID.
761
+ if (undecided !== null && isBatchedProtectedHeader(parts.protectedBstr))
762
+ return undecided();
763
+ if (isBatchedProtectedHeader(parts.protectedBstr)) {
764
+ const judged = judgeBatchedEntry(entry, expectedPosition, parts, key, batchContext);
765
+ if (judged.state === 'failed')
766
+ return judged.result;
767
+ if (judged.state === 'pending')
768
+ return { scopeId, position: expectedPosition, valid: true, signature: 'pending', batched: true };
769
+ if (accountedPastCutoff !== null)
770
+ return accountedResult(scopeId, expectedPosition, accountedPastCutoff);
771
+ if (judged.state === 'accounted') {
772
+ return accountedResult(scopeId, expectedPosition, `Entry written ${entry.createdAt ?? ''} under key ${entry.signingKeyId} is covered by a batch head the distrust entry accounts for: ${judged.detail} Not verified, and not a failure.`);
773
+ }
774
+ return { scopeId, position: expectedPosition, valid: true, signature: 'ok', keySource: judged.keySource ?? key.source, batched: true };
775
+ }
634
776
  const outcome = verifyCoseSign1(envelopeBytes, key.spkiBase64);
777
+ // Under an undecided key only a failure that needed no computation stands
778
+ // on its own (a malformed envelope, the all-zero sentinel, a wrong length,
779
+ // a header alg the key cannot produce); anything else, a signature a rerun
780
+ // assumes included, is the could-not-compute reading.
781
+ if (undecided !== null && outcome !== 'unsigned' && outcome !== 'alg-mismatch' && outcome !== 'invalid')
782
+ return undecided();
635
783
  if (outcome === 'unsigned') {
636
784
  // An all-zero signature slot on an entry that CLAIMS a signing key. The
637
785
  // Server writes a key id only beside a signature it made with that key,
@@ -653,6 +801,55 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
653
801
  }
654
802
  return fail(scopeId, expectedPosition, 'CHAIN_SIGNATURE_INVALID', `COSE_Sign1 signature did not verify against key ${entry.signingKeyId}.`, outcome === 'decode-fail' ? 'decode-fail' : 'invalid');
655
803
  }
804
+ /**
805
+ * Judge an entry that carries the batch marker: its envelope (the writer's
806
+ * `alg`, an empty signature), then its inclusion proof and the head it names.
807
+ * The caller has already resolved, anchored and placed the entry's own key.
808
+ */
809
+ function judgeBatchedEntry(entry, position, parts, key, context) {
810
+ const { scopeId } = entry;
811
+ const failed = (code, detail, state) => ({ state: 'failed', result: fail(scopeId, position, code, detail, state) });
812
+ // Nothing is computed under the entry's own key here (its head is), so a
813
+ // key this host refused to load reads as the algorithm its bytes declare.
814
+ const keyAlg = resolveKeyAlgorithmOrHostRefused(key.spkiBase64);
815
+ if (typeof keyAlg !== 'object') {
816
+ return keyAlg === 'unrecognized'
817
+ ? failed('CHAIN_UNSUPPORTED_ALGORITHM', `Key ${entry.signingKeyId} ${describeUnsupportedAlgorithm(key.spkiBase64)}`, 'unsupported')
818
+ : failed('CHAIN_SIGNATURE_INVALID', `Key ${entry.signingKeyId} is not a public key, so nothing can be read under it.`, 'invalid');
819
+ }
820
+ const headerAlg = extractHeaderAlg(parts.protectedBstr);
821
+ if (headerAlg === null || !keyAlg.coseAlgs.includes(headerAlg)) {
822
+ return failed('CHAIN_ALG_MISMATCH', `Protected-header alg (label 1) is absent or is not an algorithm key ${entry.signingKeyId} can produce. Tamper class: a rewritten alg must read as forgery, never as an upgrade notice.`, 'invalid');
823
+ }
824
+ if (parts.signature.length !== 0) {
825
+ return failed('CHAIN_SIGNATURE_INVALID', `Entry carries the batch marker and a signature of ${parts.signature.length} bytes; a batched entry's signature is empty.`, 'invalid');
826
+ }
827
+ const proof = entry.batch;
828
+ if (proof === undefined || proof === null) {
829
+ const pendingSince = entry.batchPendingSince !== undefined ? entry.batchPendingSince : context.pendingSince;
830
+ if (pendingSince !== null && isInstant(entry.createdAt) && rfc3339Ms(entry.createdAt) >= instantMs(pendingSince)) {
831
+ return { state: 'pending' };
832
+ }
833
+ return failed('BATCH_UNATTESTED', pendingSince === null
834
+ ? 'Entry carries the batch marker and no inclusion proof, and nothing dates when this artifact was cut, so it cannot be read as still waiting for its batch head.'
835
+ : `Entry carries the batch marker and no inclusion proof, and was written ${entry.createdAt ?? '(no createdAt)'}, before ${pendingSince}: longer before the artifact was cut than an entry waits for its batch head.`);
836
+ }
837
+ if (typeof proof !== 'object' || typeof proof.batchId !== 'string') {
838
+ return failed('BATCH_LEAF_MISMATCH', 'The entry\'s batch proof is not { batchId, leafIndex, treeSize, auditPath }.');
839
+ }
840
+ const head = context.heads.get(proof.batchId.toLowerCase());
841
+ if (head === undefined) {
842
+ return failed('BATCH_HEAD_INVALID', `Entry names batch head ${proof.batchId}, which the artifact does not carry.`);
843
+ }
844
+ if (head.state === 'unsupported')
845
+ return failed('CHAIN_UNSUPPORTED_ALGORITHM', head.detail, 'unsupported');
846
+ if (head.state === 'invalid')
847
+ return failed('BATCH_HEAD_INVALID', head.detail);
848
+ const wrong = checkBatchProof(entry.batchChainKey ?? scopeId, position, entry.payloadHash, proof, head);
849
+ if (wrong !== null)
850
+ return failed('BATCH_LEAF_MISMATCH', wrong);
851
+ return head.state === 'accounted' ? { state: 'accounted', detail: head.detail } : { state: 'ok', keySource: head.keySource };
852
+ }
656
853
  function checkOidcActor(oidc, payloadBstr, scopeId, position) {
657
854
  const rowIss = oidc.iss ?? null;
658
855
  const rowSub = oidc.sub ?? null;
@@ -774,3 +971,11 @@ export function distrustAccounts(key, writtenAt) {
774
971
  }
775
972
  return placeInKeyWindow(key, writtenAt, 'Artifact').placement === 'accounted';
776
973
  }
974
+ /** The cert key's algorithm this host refused, with why when that is known. */
975
+ function refusedAgentAlgorithm(spki) {
976
+ const name = agentKeyAlgorithm(spki)?.name;
977
+ if (name === undefined)
978
+ return 'the cert key\'s algorithm';
979
+ const cause = hostRefusalCause(name);
980
+ return cause === null ? name : `${name} (${cause})`;
981
+ }