@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
package/dist/chain.js CHANGED
@@ -19,7 +19,7 @@
19
19
  * inputs): binding-integrity, OIDC-actor cross-check, temporal
20
20
  * key-validity, the agent-signature re-check, and key anchoring (a
21
21
  * registry marked by `applyKeyTrust`). The first three run on
22
- * the dump and on any export from an engine that ships the row fields
22
+ * the dump and on any export from a Server that ships the row fields
23
23
  * (>= v0.26.x). The agent-signature check needs the cert's public key,
24
24
  * which neither surface carries, so it runs only when the caller passes
25
25
  * `agentKeys`. A check without its input is reported `skipped_no_input`,
@@ -29,14 +29,16 @@
29
29
  * branch comes LAST, after the binding/OIDC checks, so a row written without a
30
30
  * signing key is still subject to every structural check, and a tamper finding
31
31
  * on it is reported under its own code rather than as CHAIN_ENTRY_UNSIGNED.
32
- * That branch grades the entry the way the engine does: an unsigned entry
32
+ * That branch grades the entry the way the Server does: an unsigned entry
33
33
  * after a signed one in its chain, or written at or after the earliest key
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
  });
@@ -91,9 +98,9 @@ export function chainOfScope(scopeId) {
91
98
  /**
92
99
  * The earliest `activatedAt` among `keys`, as the ISO string it was given in,
93
100
  * or `null` when no key carries a parseable one. This is the instant from
94
- * which the engine treats every chain entry and checkpoint as required to be
101
+ * which the Server treats every chain entry and checkpoint as required to be
95
102
  * signed; pass every key the verifier knows, retired ones included, since the
96
- * engine reads it as `min(activated_at)` over its whole key registry.
103
+ * Server reads it as `min(activated_at)` over its whole key registry.
97
104
  */
98
105
  export function earliestKeyActivation(keys) {
99
106
  let earliest = null;
@@ -117,7 +124,7 @@ export function earliestKeyActivation(keys) {
117
124
  *
118
125
  * False when `signingSince` is absent or unparseable: with no instant from
119
126
  * which the install signs, nothing has to be signed. True when `signingSince`
120
- * is known and `writtenAt` is missing or not strict RFC 3339: the engine times every
127
+ * is known and `writtenAt` is missing or not strict RFC 3339: the Server times every
121
128
  * row, so a row with no readable time was edited, and it cannot be placed
122
129
  * before signing began. It fails closed rather than reading as early history.
123
130
  */
@@ -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', '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,23 +221,106 @@ export function verifyChain(entries, keys, options = {}) {
203
221
  }
204
222
  }
205
223
  const mustSign = { signedBefore: false, signingSince };
206
- let previousHash = null;
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
+ };
264
+ const unbound = { payload: false, federation: false };
265
+ let previousHash = options.slice?.previousHash ?? null;
207
266
  for (let i = 0; i < sorted.length; i++) {
208
267
  const entry = sorted[i];
209
- const expectedPosition = i + 1;
210
- let result = verifyEntry(entry, expectedPosition, previousHash, keys, options, optionalChecks, mustSign);
211
- // As the engine's walk does: any earlier row naming a key, whatever its own
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);
272
+ // As the Server's walk does: any earlier row naming a key, whatever its own
212
273
  // verdict, means this chain was already being signed.
213
274
  if (entry.signingKeyId !== null)
214
275
  mustSign.signedBefore = true;
215
276
  if (result.valid && result.accounted === undefined) {
216
277
  result = checkAgentSignature(entry, result, options.agentKeys, optionalChecks, agentSignatures);
217
278
  }
279
+ if (result.valid && result.accounted === undefined && entry.binding === undefined && entry.bindingRequired !== undefined) {
280
+ unbound.payload = true;
281
+ if (entry.bindingRequired.federationWire)
282
+ unbound.federation = true;
283
+ result = failAfterSignature(entry, result, 'CHAIN_PAYLOAD_BINDING_MISMATCH', entry.bindingRequired.detail);
284
+ }
218
285
  if (result.valid && result.accounted === undefined && entry.binding !== undefined) {
219
- result = checkSealedFederationWire(entry, result, options.federationKeys, optionalChecks, federationWire);
286
+ result = checkSealedFederationWire(entry, result, options.federationKeys, optionalChecks, federationWire, options.allowAfterRetirement === true);
220
287
  }
221
288
  if (result.valid && result.accounted === undefined && entry.inlinedEvidence !== undefined) {
222
- result = checkInlinedEvidence(entry, result, optionalChecks, evidenceBinding);
289
+ result = checkInlinedEvidence(entry, entry.inlinedEvidence.value, result, optionalChecks, evidenceBinding);
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
+ }
223
324
  }
224
325
  entryResults.push(result);
225
326
  if (result.accounted !== undefined) {
@@ -232,14 +333,20 @@ export function verifyChain(entries, keys, options = {}) {
232
333
  detail: result.accounted.detail,
233
334
  });
234
335
  }
235
- else if (result.valid)
236
- verifiedEntries++;
336
+ else if (result.valid) {
337
+ if (result.signature === 'pending')
338
+ awaitingHead++;
339
+ else
340
+ verifiedEntries++;
341
+ }
237
342
  else if (!brokenAt && result.failure) {
238
343
  brokenAt = { position: result.position, code: result.failure.code, detail: result.failure.detail };
239
344
  }
240
345
  switch (result.signature) {
241
346
  case 'ok':
242
347
  coverage.signed++;
348
+ if (result.batched === true)
349
+ coverage.batched++;
243
350
  if (result.keySource === 'supplied')
244
351
  keyProvenance.supplied++;
245
352
  else if (result.keySource === 'embedded')
@@ -251,12 +358,22 @@ export function verifyChain(entries, keys, options = {}) {
251
358
  case 'skipped':
252
359
  coverage.skipped++;
253
360
  break;
361
+ case 'pending':
362
+ coverage.pending++;
363
+ break;
254
364
  // 'not-checked' / 'invalid' / 'decode-fail' / 'unsupported' are failure
255
365
  // states: the entry is already counted as broken, so it contributes to
256
366
  // no coverage bucket.
367
+ default:
368
+ break;
257
369
  }
258
370
  previousHash = entry.payloadHash;
259
371
  }
372
+ // A check some entry could not take part in is not a check that ran.
373
+ if (unbound.payload)
374
+ optionalChecks.payload_binding = 'not_checked';
375
+ if (unbound.federation)
376
+ optionalChecks.federation_wire = 'not_checked';
260
377
  // The caller walked the key statements (every key carries a verdict), but no
261
378
  // entry got as far as the anchoring check.
262
379
  if (optionalChecks.key_anchoring === 'skipped_no_input' && [...keys.values()].some((k) => k.trust !== undefined)) {
@@ -264,7 +381,7 @@ export function verifyChain(entries, keys, options = {}) {
264
381
  }
265
382
  return {
266
383
  scopeId,
267
- valid: verifiedEntries + accounted.length === sorted.length,
384
+ valid: verifiedEntries + accounted.length + awaitingHead === sorted.length,
268
385
  totalEntries: sorted.length,
269
386
  verifiedEntries,
270
387
  brokenAt,
@@ -276,6 +393,7 @@ export function verifyChain(entries, keys, options = {}) {
276
393
  agentSignatures,
277
394
  federationWire,
278
395
  evidenceBinding,
396
+ historySeal,
279
397
  };
280
398
  }
281
399
  /** The payload field each entry type signs an inlined evidence body's hash under. */
@@ -292,14 +410,13 @@ const EVIDENCE_HASH_FIELD = {
292
410
  * signs a hash its submitter computed over the cleartext, and the export
293
411
  * inlines the ciphertext, so it is counted and left unbound.
294
412
  */
295
- function checkInlinedEvidence(entry, result, optionalChecks, counts) {
413
+ function checkInlinedEvidence(entry, body, result, optionalChecks, counts) {
296
414
  optionalChecks.evidence_binding = 'applied';
297
415
  counts.present++;
298
416
  const failed = (detail) => {
299
417
  counts.failed++;
300
418
  return failAfterSignature(entry, result, 'CHAIN_EVIDENCE_BINDING_MISMATCH', detail);
301
419
  };
302
- const body = entry.inlinedEvidence.value;
303
420
  if (entry.binding === undefined) {
304
421
  return failed('The entry inlines an evidence body but carries no payload, so no signed hash binds the body to the chain.');
305
422
  }
@@ -332,7 +449,7 @@ function checkInlinedEvidence(entry, result, optionalChecks, counts) {
332
449
  * its agreement with the entry, and, under a supplied key for the sending
333
450
  * hub, its signature. See `federation-wire.ts`.
334
451
  */
335
- function checkSealedFederationWire(entry, result, federationKeys, optionalChecks, counts) {
452
+ function checkSealedFederationWire(entry, result, federationKeys, optionalChecks, counts, allowAfterRetirement) {
336
453
  if (entry.binding === undefined)
337
454
  return result;
338
455
  const wire = extractFederationWire(entry.binding.payload);
@@ -343,7 +460,7 @@ function checkSealedFederationWire(entry, result, federationKeys, optionalChecks
343
460
  return failAfterSignature(entry, result, 'CHAIN_FEDERATION_WIRE_INVALID', 'payload.wire is present but is not a sealed federation message (an object with scheme, senderHubId, senderPublicKey, recipientHubId, method, path, bodyHash, timestamp, nonce, signature and an object body).');
344
461
  }
345
462
  counts.present++;
346
- const outcome = checkFederationWire(entry.binding.entryType, entry.binding.recordId, entry.binding.payload, wire, federationKeys);
463
+ const outcome = checkFederationWire(entry.binding.entryType, entry.binding.recordId, entry.binding.payload, wire, federationKeys, { allowAfterRetirement });
347
464
  if (outcome.outcome === 'ok') {
348
465
  if (outcome.signatureChecked)
349
466
  counts.verified++;
@@ -356,12 +473,17 @@ function checkSealedFederationWire(entry, result, federationKeys, optionalChecks
356
473
  counts.failed++;
357
474
  return failAfterSignature(entry, result, outcome.outcome === 'unsupported' ? 'CHAIN_UNSUPPORTED_ALGORITHM' : 'CHAIN_FEDERATION_WIRE_INVALID', outcome.detail);
358
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
+ }
359
481
  /**
360
482
  * Offline re-check of a sealed agent signature, on an entry that already
361
- * passed every other check (so its payload is the engine's signed bytes).
483
+ * passed every other check (so its payload is the Server's signed bytes).
362
484
  *
363
- * Runs only on an engine-validated identity (`on_behalf_of.validated: true`).
364
- * On a caller-asserted one, entries written before the engine sealed these
485
+ * Runs only on a Server-validated identity (`on_behalf_of.validated: true`).
486
+ * On a caller-asserted one, entries written before the Server sealed these
365
487
  * fields itself carry them as caller passthrough, and the marker telling the
366
488
  * two apart is a column neither the export nor the dump publishes, so a
367
489
  * failure there could not be told from a claim nobody ever checked.
@@ -387,11 +509,11 @@ function checkAgentSignature(entry, result, agentKeys, optionalChecks, counts) {
387
509
  }
388
510
  const certLabel = claim.certId ?? claim.certThumbprint;
389
511
  if (outcome === 'unsupported') {
390
- 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.`);
391
513
  }
392
514
  return failAfterSignature(entry, result, 'CHAIN_AGENT_SIGNATURE_INVALID', outcome === 'malformed'
393
- ? `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).`
394
- : `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'}` : ''}.`);
395
517
  }
396
518
  function accountedResult(scopeId, position, detail) {
397
519
  return { scopeId, position, valid: true, accounted: { code: ACCOUNTED_ENTRY_CODE, detail }, signature: 'accounted' };
@@ -412,9 +534,11 @@ function fail(scopeId, position, code, detail, signature = 'not-checked', keySou
412
534
  * counts every signed entry (`signed = supplied + embedded`).
413
535
  */
414
536
  function failAfterSignature(entry, result, code, detail) {
415
- 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;
416
540
  }
417
- function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, optionalChecks, mustSign) {
541
+ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, optionalChecks, mustSign, batchContext) {
418
542
  const { scopeId } = entry;
419
543
  if (entry.chainPosition !== expectedPosition) {
420
544
  return fail(scopeId, entry.chainPosition, 'CHAIN_POSITION_GAP', `Expected chainPosition ${expectedPosition}, got ${entry.chainPosition}.`);
@@ -446,14 +570,14 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
446
570
  return fail(scopeId, expectedPosition, 'CHAIN_COSE_HEADER_MISMATCH', `Signed protected-header chain claim (position=${chainClaim?.position ?? 'null'}, prev=${chainClaim?.previous_hash ?? 'null'}) diverges from row columns (position=${entry.chainPosition}, prev=${entry.previousHash ?? 'null'}).`);
447
571
  }
448
572
  // Input-gated: actor attribution. The row's actorId/actorOwnerId columns are
449
- // the projection a report displays as "who did this", and the engine's own
573
+ // the projection a report displays as "who did this", and the Server's own
450
574
  // export guide names them as the trustworthy attribution while listing only
451
575
  // actorDisplayName / actorOwnerType / humanReadableLabel as unsigned. They
452
576
  // are signature-covered, at CWT_Claims label 15 -> private label -65539, so
453
577
  // a rewritten column is a re-attribution of the action to another actor and
454
578
  // must not verify. Same shape as the signed-kid check above: compare the
455
579
  // column against the signed claim, and skip only when one side is absent
456
- // (an older engine that never carried the claim, or an artifact that does
580
+ // (an older Server that never carried the claim, or an artifact that does
457
581
  // not carry the columns).
458
582
  const attribution = entry.actorAttribution;
459
583
  if (attribution) {
@@ -476,7 +600,7 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
476
600
  }
477
601
  }
478
602
  // Input-gated: binding-integrity. Runs whenever the row payload is present:
479
- // the dump always carries it, and the export now carries it too (engine ≥ v0.26.x).
603
+ // the dump always carries it, and the export now carries it too (Server ≥ v0.26.x).
480
604
  if (entry.binding) {
481
605
  optionalChecks.payload_binding = 'applied';
482
606
  const decodedRaw = decodePredicate(parts.payloadBstr);
@@ -486,8 +610,8 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
486
610
  decoded === null ||
487
611
  rebuilt === null ||
488
612
  !deepEqual(rebuilt, decoded) ||
489
- !envelopeExtensionsMatch(entry.binding.payload, decodedRaw)) {
490
- return fail(scopeId, expectedPosition, 'CHAIN_PAYLOAD_BINDING_MISMATCH', 'Denormalised row payload no longer matches the canonical projection of the signed predicate.');
613
+ !envelopeExtensionsMatch(entry.binding.payload, decodedRaw, entry.binding.extensionsProjected === true)) {
614
+ return fail(scopeId, expectedPosition, 'CHAIN_PAYLOAD_BINDING_MISMATCH', 'Denormalised row payload does not match the canonical projection of the signed predicate.');
491
615
  }
492
616
  }
493
617
  // Input-gated: OIDC-actor cross-check. Only when the dump carried the columns.
@@ -498,12 +622,12 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
498
622
  return oidcFailure;
499
623
  }
500
624
  // Signature (last, so a null-key row still ran every structural check above).
501
- // Only a true null is the engine's unsigned-mode marker. Any other value,
502
- // including the empty string no engine emits, must resolve in the registry
625
+ // Only a true null is the Server's unsigned-mode marker. Any other value,
626
+ // including the empty string no Server emits, must resolve in the registry
503
627
  // and fails CHAIN_SIGNATURE_MISSING_KEY below: a truthiness shortcut here
504
628
  // would let a tampered signingKeyId:"" row skip its signature check.
505
629
  if (entry.signingKeyId === null) {
506
- // Engine mirror of `signature_missing`. An unsigned entry is reduced
630
+ // Server mirror of `signature_missing`. An unsigned entry is reduced
507
631
  // coverage only where the install had not yet begun to sign: before any
508
632
  // signed entry in this chain, and before the earliest key activation.
509
633
  // Anywhere else no process of the install could have written it; it is
@@ -513,7 +637,7 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
513
637
  if (mustSign.signedBefore) {
514
638
  return fail(scopeId, expectedPosition, 'CHAIN_ENTRY_UNSIGNED', 'Entry has no signingKeyId but follows a signed entry in the same chain.');
515
639
  }
516
- // The engine times every entry. Without a time the walk can read, an
640
+ // The Server times every entry. Without a time the walk can read, an
517
641
  // unsigned entry cannot be placed before signing began, so it is not
518
642
  // early history: it fails closed.
519
643
  if (mustSign.signingSince !== null && !isInstant(entry.createdAt)) {
@@ -541,8 +665,8 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
541
665
  if (options.requireSuppliedKeys && key.source !== 'supplied') {
542
666
  return fail(scopeId, expectedPosition, 'CHAIN_KEY_POLICY_VIOLATION', `Key ${entry.signingKeyId} is embedded in the artifact; this run requires supplied keys.`);
543
667
  }
544
- // Signed-kid binding (engine mirror: signing_key_drift), ahead of every
545
- // question about the key, as the engine orders it. The row's signingKeyId
668
+ // Signed-kid binding (Server mirror: signing_key_drift), ahead of every
669
+ // question about the key, as the Server orders it. The row's signingKeyId
546
670
  // column selected the key above, but the column is a denormalized
547
671
  // convenience; the kid at protected-header label 4 is signature-covered. A
548
672
  // divergence means the column was rewritten after signing, e.g. to point
@@ -553,7 +677,7 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
553
677
  if (signedKid !== null && signedKid !== entry.signingKeyId) {
554
678
  return fail(scopeId, expectedPosition, 'CHAIN_SIGNING_KEY_DRIFT', `Row signingKeyId=${entry.signingKeyId} does not match the signature-covered kid ${signedKid} in the protected header.`);
555
679
  }
556
- // Input-gated: key anchoring (engine mirror: signing_key_unanchored). Runs
680
+ // Input-gated: key anchoring (Server mirror: signing_key_unanchored). Runs
557
681
  // when a key-statement walk marked the registry. A key nothing signed links
558
682
  // to a pinned anchor is one anything with write access to the Server's
559
683
  // database can register, so an entry under it is a forgery until shown
@@ -567,18 +691,31 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
567
691
  // key material the registry does not lie about: anything else under
568
692
  // its id is bytes the database's writer wrote.
569
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
+ };
570
702
  if (bound !== null && isInstant(entry.createdAt) && rfc3339Ms(entry.createdAt) < instantMs(bound)
571
- && !declaredAlgorithmLies(key) && verifyCoseSign1(envelopeBytes, key.spkiBase64) === 'ok') {
703
+ && !declaredAlgorithmLies(key) && holds()) {
572
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.`);
573
705
  }
574
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.`);
575
707
  }
576
- if (key.trust === 'undecided') {
577
- 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');
578
- }
579
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;
580
717
  // Registry self-consistency: when the input surface declares an algorithm for
581
- // this key (vault_signing_keys.algorithm), it must agree with what the SPKI
718
+ // this key, it must agree with what the SPKI
582
719
  // key material commits to. A registry row that lies about its own key is the
583
720
  // signature of a mis-registered key (the pre-guard P-256 corruption shape) or
584
721
  // a rewritten registry, and nothing verified against it can be trusted.
@@ -587,7 +724,7 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
587
724
  }
588
725
  // Input-gated: temporal key-validity, whenever the key carries a window.
589
726
  // Compared at millisecond precision, the precision of an entry's write time,
590
- // truncating a microsecond window edge the way the engine does. The engine
727
+ // truncating a microsecond window edge the way the Server does. The Server
591
728
  // times every entry, so an entry with no time the walk can read cannot be
592
729
  // placed inside the window, and fails closed rather than skipping it.
593
730
  if (typeof key.activatedAt === 'string' || typeof key.retiredAt === 'string' || typeof key.distrustCutoff === 'string') {
@@ -618,10 +755,34 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
618
755
  }
619
756
  }
620
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
+ }
621
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();
622
783
  if (outcome === 'unsigned') {
623
784
  // An all-zero signature slot on an entry that CLAIMS a signing key. The
624
- // engine writes a key id only beside a signature it made with that key,
785
+ // Server writes a key id only beside a signature it made with that key,
625
786
  // and fails this shape `signature_invalid`, so it is a forged or wiped
626
787
  // signature, never an unsigned entry. (A genuinely unsigned entry carries
627
788
  // a null signingKeyId and is graded above.)
@@ -640,6 +801,55 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
640
801
  }
641
802
  return fail(scopeId, expectedPosition, 'CHAIN_SIGNATURE_INVALID', `COSE_Sign1 signature did not verify against key ${entry.signingKeyId}.`, outcome === 'decode-fail' ? 'decode-fail' : 'invalid');
642
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
+ }
643
853
  function checkOidcActor(oidc, payloadBstr, scopeId, position) {
644
854
  const rowIss = oidc.iss ?? null;
645
855
  const rowSub = oidc.sub ?? null;
@@ -658,21 +868,21 @@ function checkOidcActor(oidc, payloadBstr, scopeId, position) {
658
868
  }
659
869
  return null;
660
870
  }
661
- // synthesized=false: engine writers leave the columns null. Any populated
662
- // state is a DB-level CHECK-constraint bypass.
871
+ // synthesized=false: the Server leaves the columns null. Any populated
872
+ // state means the row was altered outside the Server.
663
873
  if (synthesized === false && (rowIss !== null || rowSub !== null)) {
664
874
  return fail(scopeId, position, 'CHAIN_OIDC_ACTOR_MISMATCH', `actor_oidc_synthesized=false but iss/sub populated (${rowIss ?? 'null'}/${rowSub ?? 'null'}).`);
665
875
  }
666
876
  return null;
667
877
  }
668
878
  /**
669
- * Temporal key-validity, split by direction. Both directions used to report
670
- * `CHAIN_KEY_EXPIRED`, so a consumer branching on the code saw "expired" for a
671
- * key that had not started yet and would reason about rotation or retention
672
- * when the real condition is clock skew or backdating. Those are different
673
- * investigations, and the activation side is the security-relevant one.
879
+ * Temporal key-validity, split by direction. A key not yet active reports
880
+ * `CHAIN_KEY_NOT_YET_ACTIVE` and a retired key reports `CHAIN_KEY_EXPIRED`, so a
881
+ * consumer branching on the code does not read clock skew or backdating as
882
+ * rotation or retention. Those are different investigations, and the
883
+ * activation side is the security-relevant one.
674
884
  */
675
- function temporalKeyFailure(createdAt, key) {
885
+ function temporalKeyFailure(createdAt, key, what = 'Entry') {
676
886
  const written = rfc3339Ms(createdAt);
677
887
  if (Number.isNaN(written))
678
888
  return null;
@@ -681,7 +891,7 @@ function temporalKeyFailure(createdAt, key) {
681
891
  if (!Number.isNaN(activated) && written < activated) {
682
892
  return {
683
893
  code: 'CHAIN_KEY_NOT_YET_ACTIVE',
684
- detail: `Entry written ${createdAt} predates key ${key.keyId} activation ${key.activatedAt}.`,
894
+ detail: `${what} written ${createdAt} predates key ${key.keyId} activation ${key.activatedAt}.`,
685
895
  };
686
896
  }
687
897
  }
@@ -690,7 +900,7 @@ function temporalKeyFailure(createdAt, key) {
690
900
  if (!Number.isNaN(cutoff) && written > cutoff) {
691
901
  return {
692
902
  code: 'CHAIN_KEY_EXPIRED',
693
- detail: `Entry written ${createdAt} postdates ${key.distrustCutoff}, the instant distrustedKeys (VAULT_DISTRUSTED_KEYS on the Server) gives for key ${key.keyId}; the key was not retired then.`,
903
+ detail: `${what} written ${createdAt} postdates ${key.distrustCutoff}, the instant distrustedKeys (VAULT_DISTRUSTED_KEYS on the Server) gives for key ${key.keyId}; the key was not retired then.`,
694
904
  };
695
905
  }
696
906
  }
@@ -699,9 +909,73 @@ function temporalKeyFailure(createdAt, key) {
699
909
  if (!Number.isNaN(retired) && written > retired) {
700
910
  return {
701
911
  code: 'CHAIN_KEY_EXPIRED',
702
- detail: `Entry written ${createdAt} postdates key ${key.keyId} retirement ${key.retiredAt}.`,
912
+ detail: `${what} written ${createdAt} postdates key ${key.keyId} retirement ${key.retiredAt}.`,
703
913
  };
704
914
  }
705
915
  }
706
916
  return null;
707
917
  }
918
+ /**
919
+ * Place a vault checkpoint, a read-log leaf or a read-log tree head in the
920
+ * signed window of its key, by the time its row was written. The rule is the
921
+ * one chain entries are held to (CHAIN_KEY_NOT_YET_ACTIVE, CHAIN_KEY_EXPIRED):
922
+ * each edge is checked only when the key carries it, at millisecond
923
+ * precision, and an artifact written exactly at the key's retirement is
924
+ * inside. `what` names the artifact in the detail ("Checkpoint", "Leaf").
925
+ *
926
+ * The caller verifies the signature first: the Server reports a signature
927
+ * that does not verify ahead of a window finding.
928
+ */
929
+ export function placeInKeyWindow(key, writtenAt, what) {
930
+ if (typeof key.activatedAt !== 'string' && typeof key.retiredAt !== 'string' && typeof key.distrustCutoff !== 'string') {
931
+ return { placement: 'inside' };
932
+ }
933
+ for (const [edge, value] of [['activatedAt', key.activatedAt], ['retiredAt', key.retiredAt], ['distrustCutoff', key.distrustCutoff]]) {
934
+ if (typeof value === 'string' && !isInstant(value)) {
935
+ return { placement: 'unplaceable', detail: `Key ${key.keyId}'s ${edge} ${JSON.stringify(value)} is not an RFC 3339 instant, so the ${what.toLowerCase()} cannot be placed inside its window.` };
936
+ }
937
+ }
938
+ if (!isInstant(writtenAt)) {
939
+ return { placement: 'unplaceable', detail: `${what} has no parseable write time, so it cannot be placed inside key ${key.keyId}'s window.` };
940
+ }
941
+ const temporal = temporalKeyFailure(writtenAt, key, what);
942
+ if (temporal === null)
943
+ return { placement: 'inside' };
944
+ const span = key.distrustSpan;
945
+ const written = rfc3339Ms(writtenAt);
946
+ if (temporal.code === 'CHAIN_KEY_EXPIRED' && span !== undefined && span.cutoff !== null && span.retiredAt !== null
947
+ && written >= instantMs(span.cutoff) && written < instantMs(span.retiredAt)) {
948
+ return { placement: 'accounted' };
949
+ }
950
+ return { placement: temporal.code === 'CHAIN_KEY_EXPIRED' ? 'expired' : 'not-yet-active', detail: temporal.detail };
951
+ }
952
+ /**
953
+ * Whether a `distrustedKeys` entry and the retirement a trusted key signed
954
+ * account for an artifact signed under `key` and written at `writtenAt`: the
955
+ * key is unanchored only because of the entry, or anchored and the artifact
956
+ * written at or after the entry's instant, and in both cases the artifact was
957
+ * written before that retirement. The same condition lists a chain entry as
958
+ * CHAIN_SIGNED_BY_DISTRUSTED_KEY.
959
+ *
960
+ * Such an artifact is listed, never verified, and never evidence for or
961
+ * against anything else. The caller still verifies its signature under the
962
+ * key before setting it aside: anything else under the key's id is bytes
963
+ * whoever writes to the database wrote.
964
+ */
965
+ export function distrustAccounts(key, writtenAt) {
966
+ if (key.trust === 'undecided' || declaredAlgorithmLies(key))
967
+ return false;
968
+ if (key.trust === 'unanchored') {
969
+ const bound = key.distrustSpan?.retiredAt ?? null;
970
+ return bound !== null && isInstant(writtenAt) && rfc3339Ms(writtenAt) < instantMs(bound);
971
+ }
972
+ return placeInKeyWindow(key, writtenAt, 'Artifact').placement === 'accounted';
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
+ }