@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
@@ -4,12 +4,11 @@
4
4
  * A vault key is trusted only when signed key statements link it to a key the
5
5
  * verifier pinned out of band (`trustAnchors`). The Server's database stores
6
6
  * the statements and never vouches for them: anything with write access to it
7
- * can add a `vault_signing_keys` row and a statement row, and neither makes a
7
+ * can add a key row and a statement row, and neither makes a
8
8
  * key trusted, because every edge below is a signature that writer cannot
9
- * produce. This is the engine's `computeKeyTrust`
10
- * (audit-vault/key-statements.ts), re-implemented so the verifier has no engine
11
- * dependency. Where the two could disagree, this one must never trust a key the
12
- * engine refuses.
9
+ * produce. This is the same walk the Server runs over its own
10
+ * key registry, re-implemented so the verifier has no Server dependency. Where the two could disagree, this one must never trust a key the
11
+ * Server refuses.
13
12
  *
14
13
  * **Format.** Each statement is one or two COSE_Sign1 (RFC 9052, tag 18) over
15
14
  * the SAME deterministic-CBOR (RFC 8949 §4.2.1) payload, protected header
@@ -37,11 +36,11 @@
37
36
  * statement's `id` and `createdAt` at microseconds, and lists under a trusted
38
37
  * key its admission, every later genesis or succession it signed, and its
39
38
  * counting closures. A walk over a document therefore dates a window and
40
- * cuts an edge back as the engine does, except where the document does not
41
- * carry a key the engine verified a statement with (the endorser of a later
39
+ * cuts an edge back as the Server does, except where the document does not
40
+ * carry a key the Server verified a statement with (the endorser of a later
42
41
  * succession, the signer of a closure): that statement is
43
42
  * KEY_STATEMENT_INVALID or KEY_CLOSURE_INVALID here, the window is wider than
44
- * the engine's, and the listed `activatedAt` or `retiredAt` reports it as
43
+ * the Server's, and the listed `activatedAt` or `retiredAt` reports it as
45
44
  * CHAIN_KEY_WINDOW_DRIFT (a listed retirement no counting closure signs, as
46
45
  * KEY_CLOSURE_INVALID).
47
46
  *
@@ -55,8 +54,9 @@
55
54
  * statement is only ever in a document that did not come from the Server. A
56
55
  * forced closure voids every edge out of its key whatever the order.
57
56
  */
57
+ import { STRICT_CBOR_DECODE } from './cbor-strict.js';
58
58
  import { decode as cborDecode, encode as cborEncode, rfc8949EncodeOptions } from 'cborg';
59
- import { algorithmByName, resolveKeyAlgorithm, runtimeCanCompute, sha256Hex, verifySignatureBytes, } from './primitives.js';
59
+ import { algorithmByName, isDataOnlyRerun, judgingKeyStatements, resolveKeyAlgorithm, runtimeCanCompute, sha256Hex, signatureShape, verifySignatureBytes, } from './primitives.js';
60
60
  import { instantMs, instantUs, rfc3339Ms } from './instant.js';
61
61
  import { assertKnownOptions } from './options.js';
62
62
  /** Content type of a key statement's COSE_Sign1 (protected header label 3). */
@@ -64,11 +64,18 @@ export const KEY_STATEMENT_CTY = 'application/vnd.agledger.key-statement+cbor';
64
64
  export const KEY_STATEMENT_KINDS = ['succession', 'closure', 'genesis'];
65
65
  /**
66
66
  * The COSE `alg` a statement signature must carry for its key's algorithm.
67
- * Exactly one per algorithm, as the engine signs and checks them; the chain
67
+ * Exactly one per algorithm, as the Server signs and checks them; the chain
68
68
  * envelope's wider acceptance (RFC 9864 fully-specified code points) does not
69
69
  * apply to statements.
70
70
  */
71
- const STATEMENT_COSE_ALG = Object.freeze({ Ed25519: -8, ES256: -7 });
71
+ export const STATEMENT_COSE_ALG = Object.freeze({
72
+ Ed25519: -8,
73
+ ES256: -7,
74
+ ES384: -35,
75
+ 'ML-DSA-44': -48,
76
+ 'ML-DSA-65': -49,
77
+ 'ML-DSA-87': -50,
78
+ });
72
79
  const COSE_HEADER_ALG = 1;
73
80
  const COSE_HEADER_CTY = 3;
74
81
  const COSE_HEADER_KID = 4;
@@ -150,7 +157,7 @@ export function parseDistrustedKeys(raw) {
150
157
  * (`sha256:<hex>@<instant>`) is how a leaked key whose history is still
151
158
  * needed is kept from signing anything new: the pin vouches for what it
152
159
  * stored before the instant. `computeKeyTrust` itself walks any pair as the
153
- * engine's walk does; a verifier calls this on what its caller passed before
160
+ * Server's walk does; a verifier calls this on what its caller passed before
154
161
  * it walks.
155
162
  */
156
163
  export function assertNotPinnedAndDistrusted(trustAnchors, distrustedKeys) {
@@ -171,17 +178,20 @@ function normalizeDistrusted(raw) {
171
178
  throw new TypeError('distrustedKeys must be an array.');
172
179
  const strings = raw.filter((d) => typeof d === 'string');
173
180
  const parsed = parseDistrustedKeys(strings);
174
- for (const d of raw) {
175
- if (typeof d === 'string')
181
+ const entries = raw;
182
+ for (const item of entries) {
183
+ if (typeof item === 'string')
176
184
  continue;
177
- if (d === null || typeof d !== 'object' || typeof d.spkiSha256 !== 'string' || !HEX64.test(d.spkiSha256)
178
- || (d.cutoff !== null && (typeof d.cutoff !== 'string' || !INSTANT_US.test(d.cutoff)))) {
185
+ const d = item !== null && typeof item === 'object' ? item : {};
186
+ const { spkiSha256, cutoff } = d;
187
+ if (typeof spkiSha256 !== 'string' || !HEX64.test(spkiSha256)
188
+ || (cutoff !== null && (typeof cutoff !== 'string' || !INSTANT_US.test(cutoff)))) {
179
189
  throw new TypeError('distrustedKeys entry is not { spkiSha256: <64 lowercase hex>, cutoff: <microsecond RFC 3339 UTC instant> | null }.');
180
190
  }
181
- if (parsed.some((p) => p.spkiSha256 === d.spkiSha256)) {
182
- throw new TypeError(`distrustedKeys names sha256:${d.spkiSha256} twice. Give each key one entry, with the earliest instant it may have leaked.`);
191
+ if (parsed.some((p) => p.spkiSha256 === spkiSha256)) {
192
+ throw new TypeError(`distrustedKeys names sha256:${spkiSha256} twice. Give each key one entry, with the earliest instant it may have leaked.`);
183
193
  }
184
- parsed.push({ spkiSha256: d.spkiSha256, cutoff: d.cutoff });
194
+ parsed.push({ spkiSha256, cutoff });
185
195
  }
186
196
  return parsed;
187
197
  }
@@ -192,12 +202,14 @@ function toBytes(v) {
192
202
  return new Uint8Array(Buffer.from(v, 'base64'));
193
203
  return null;
194
204
  }
195
- function decodeSign1(raw) {
205
+ /** Internal: not re-exported from the package. */
206
+ export function decodeSign1(raw) {
196
207
  const bytes = toBytes(raw);
197
208
  if (bytes === null || bytes.length === 0 || bytes[0] !== COSE_SIGN1_TAG_PREFIX)
198
209
  return null;
199
210
  try {
200
211
  const decoded = cborDecode(bytes, {
212
+ ...STRICT_CBOR_DECODE,
201
213
  useMaps: true,
202
214
  tags: { [COSE_SIGN1_TAG]: (control) => control() },
203
215
  });
@@ -206,7 +218,7 @@ function decodeSign1(raw) {
206
218
  const [p, , payload, sig] = decoded;
207
219
  if (!(p instanceof Uint8Array) || !(payload instanceof Uint8Array) || !(sig instanceof Uint8Array))
208
220
  return null;
209
- const header = cborDecode(p, { useMaps: true });
221
+ const header = cborDecode(p, { ...STRICT_CBOR_DECODE, useMaps: true });
210
222
  if (!(header instanceof Map))
211
223
  return null;
212
224
  const alg = header.get(COSE_HEADER_ALG);
@@ -247,7 +259,7 @@ function readKeyRef(v) {
247
259
  function decodeKeyStatementPayload(bytes) {
248
260
  let raw;
249
261
  try {
250
- raw = cborDecode(bytes, { useMaps: false });
262
+ raw = cborDecode(bytes, { ...STRICT_CBOR_DECODE, useMaps: false });
251
263
  }
252
264
  catch {
253
265
  return null;
@@ -293,7 +305,7 @@ function decodeKeyStatementPayload(bytes) {
293
305
  alg,
294
306
  spki: Buffer.from(spki).toString('base64'),
295
307
  activatedAt,
296
- ...(retiredAt !== undefined ? { retiredAt: retiredAt } : {}),
308
+ ...(retiredAt !== undefined ? { retiredAt } : {}),
297
309
  },
298
310
  };
299
311
  if (r['endorser'] !== undefined) {
@@ -307,11 +319,27 @@ function decodeKeyStatementPayload(bytes) {
307
319
  return null;
308
320
  payload.forced = r['forced'];
309
321
  }
322
+ if (r['history'] !== undefined) {
323
+ const h = asRecord(r['history']);
324
+ const seal = h?.['seal'];
325
+ const root = h?.['root'];
326
+ const treeSize = h?.['treeSize'];
327
+ if (!h || typ !== 'closure' || typeof seal !== 'string' || !(root instanceof Uint8Array) || root.length !== 32
328
+ || typeof treeSize !== 'number' || !Number.isSafeInteger(treeSize) || treeSize < 0 || Object.keys(h).length !== 3)
329
+ return null;
330
+ payload.history = { seal, root: Buffer.from(root).toString('hex'), treeSize };
331
+ }
310
332
  return payload;
311
333
  }
312
- function sigStructure(protectedBstr, payloadBstr) {
334
+ /** Internal: not re-exported from the package. */
335
+ export function sigStructure(protectedBstr, payloadBstr) {
313
336
  return cborEncode([SIG_STRUCTURE_CONTEXT, protectedBstr, new Uint8Array(0), payloadBstr], rfc8949EncodeOptions);
314
337
  }
338
+ /** Whether a key (base64 SPKI DER) is an ML-DSA key. */
339
+ export function isPostQuantumKey(spkiBase64) {
340
+ const resolved = resolveKeyAlgorithm(spkiBase64);
341
+ return typeof resolved === 'object' && resolved.name.startsWith('ML-DSA');
342
+ }
315
343
  /** The statement algorithm the key material commits to, when it is one statements are signed under. */
316
344
  function statementAlgorithmOf(spki) {
317
345
  const resolved = resolveKeyAlgorithm(spki);
@@ -330,22 +358,27 @@ function materialFor(spki, declared, strict = false) {
330
358
  if (derived) {
331
359
  if (strict && declared !== derived.name)
332
360
  return { spki, alg: 'invalid' };
333
- return { spki, alg: runtimeCanCompute(derived) ? derived : 'unsupported' };
361
+ return runtimeCanCompute(derived) ? { spki, alg: derived } : { spki, alg: 'unsupported', refused: derived };
334
362
  }
335
363
  const named = declared !== null ? algorithmByName(declared) : null;
336
364
  if (named && STATEMENT_COSE_ALG[named.name] !== undefined && !runtimeCanCompute(named))
337
- return { spki, alg: 'unsupported' };
365
+ return { spki, alg: 'unsupported', refused: named };
338
366
  return { spki, alg: 'invalid' };
339
367
  }
340
368
  function checkSignature(sign1, key, expectKid) {
341
- if (key.alg === 'unsupported')
342
- return 'unsupported';
343
369
  if (key.alg === 'invalid')
344
370
  return 'bad';
345
- if (sign1.cty !== KEY_STATEMENT_CTY || sign1.kid !== expectKid || sign1.alg !== STATEMENT_COSE_ALG[key.alg.name])
346
- return 'bad';
347
- if (sign1.signature.every((b) => b === 0))
348
- return 'bad';
371
+ // Checks that need no computation run before the host's capability is
372
+ // asked, so a malformed half reads `bad` on every host.
373
+ const alg = key.alg === 'unsupported' ? key.refused : key.alg;
374
+ if (alg !== undefined) {
375
+ if (sign1.cty !== KEY_STATEMENT_CTY || sign1.kid !== expectKid || sign1.alg !== STATEMENT_COSE_ALG[alg.name])
376
+ return 'bad';
377
+ if (signatureShape(alg, sign1.signature) !== 'signature')
378
+ return 'bad';
379
+ }
380
+ if (key.alg === 'unsupported')
381
+ return 'unsupported';
349
382
  return verifySignatureBytes(key.spki, sigStructure(sign1.protectedBstr, sign1.payloadBstr), sign1.signature) ? 'ok' : 'bad';
350
383
  }
351
384
  function checkKeyStatement(input, keyByDigest) {
@@ -460,7 +493,7 @@ function signedAfterWrite(signed, s) {
460
493
  }
461
494
  /** The earlier of an instant a statement signs and its write time (see {@link signedAfterWrite}). */
462
495
  function notAfterWrite(signed, s) {
463
- if (!signedAfterWrite(signed, s))
496
+ if (s.written === null || !signedAfterWrite(signed, s))
464
497
  return signed;
465
498
  return instantOfUs(s.written.micro ? s.written.us : s.storedMs * 1000);
466
499
  }
@@ -495,6 +528,11 @@ function signedInstantOf(c) {
495
528
  * at all, and when some statements carry `createdAt` and others do not.
496
529
  */
497
530
  export function computeKeyTrust(input) {
531
+ // Every statement signature is judged in here, so a counterfactual rerun
532
+ // that assumes no key statement reads each one as this host does.
533
+ return judgingKeyStatements(() => computeKeyTrustOnHost(input));
534
+ }
535
+ function computeKeyTrustOnHost(input) {
498
536
  assertKnownOptions('computeKeyTrust', input, ['keys', 'statements', 'trustAnchors', 'distrustedKeys']);
499
537
  const anchorDigests = parseTrustAnchors(input.trustAnchors);
500
538
  if (anchorDigests.length === 0) {
@@ -502,7 +540,10 @@ export function computeKeyTrust(input) {
502
540
  }
503
541
  const anchors = new Set(anchorDigests);
504
542
  const distrustedKeys = normalizeDistrusted(input.distrustedKeys);
505
- if (!Array.isArray(input.statements) || !Array.isArray(input.keys)) {
543
+ // Checked through `unknown` copies so the guard does not retype `input.statements` and `input.keys` as `any[]`.
544
+ const rawStatements = input.statements;
545
+ const rawKeys = input.keys;
546
+ if (!Array.isArray(rawStatements) || !Array.isArray(rawKeys)) {
506
547
  throw new TypeError('computeKeyTrust takes arrays of keys and statements.');
507
548
  }
508
549
  const withTime = input.statements.filter((s) => typeof s.createdAt === 'string').length;
@@ -516,7 +557,7 @@ export function computeKeyTrust(input) {
516
557
  // One stored row, read from two sources (an export and a key document), is
517
558
  // one statement. With no write time and no row id, two identical
518
559
  // statements are one; with them, a row is its id and write time, and a copy
519
- // of a row under another id is a second row, as the engine reads it.
560
+ // of a row under another id is a second row, as the Server reads it.
520
561
  const seen = new Set();
521
562
  const statementInputs = input.statements.filter((s) => {
522
563
  const cose = Array.isArray(s.cose) ? s.cose : [];
@@ -529,7 +570,7 @@ export function computeKeyTrust(input) {
529
570
  // The same row however its time and id are spelled: `Z` or `+00:00`, a
530
571
  // uuid in either case.
531
572
  const at = instantUs(s.createdAt ?? '');
532
- const key = order === 'written' ? JSON.stringify([s.id.toLowerCase(), Number.isNaN(at.us) ? s.createdAt : at.us, bytes]) : bytes;
573
+ const key = order === 'written' && typeof s.id === 'string' ? JSON.stringify([s.id.toLowerCase(), Number.isNaN(at.us) ? s.createdAt : at.us, bytes]) : bytes;
533
574
  if (seen.has(key))
534
575
  return false;
535
576
  seen.add(key);
@@ -558,13 +599,13 @@ export function computeKeyTrust(input) {
558
599
  // the Server writes one on every row, so it was edited, and it admits nothing.
559
600
  const checked = statementInputs.map((st) => {
560
601
  const c = checkKeyStatement(st, keyByDigest);
561
- if (order !== 'written' || !Number.isNaN(rfc3339Ms(st.createdAt)))
602
+ if (order !== 'written' || !Number.isNaN(rfc3339Ms(st.createdAt ?? '')))
562
603
  return c;
563
604
  return { ...c, verdict: 'invalid', detail: 'the row has no parseable created_at to order it by' };
564
605
  });
565
606
  const place = (c, i) => {
566
607
  if (order === 'written') {
567
- const at = instantUs(c.input.createdAt);
608
+ const at = instantUs(c.input.createdAt ?? '');
568
609
  return { c, i, k: Number.isNaN(at.us) ? Number.POSITIVE_INFINITY : at.us, micro: at.micro, r: 0 };
569
610
  }
570
611
  return { c, i, k: signedInstantOf(c) ?? '￿', micro: false, r: closureLast(c) };
@@ -589,7 +630,7 @@ export function computeKeyTrust(input) {
589
630
  // A dump row whose signed payload an earlier row already carries says
590
631
  // nothing new: a copy of a row (anything with write access to the database
591
632
  // can write one), or the same payload signed again. Only the first, in
592
- // write order, takes part, as the engine reads it; the database stamps the
633
+ // write order, takes part, as the Server reads it; the database stamps the
593
634
  // write time, so a copy always lands after what it copies. A key document's
594
635
  // write time is its holder's word, so there a copy dated earlier would push
595
636
  // the published statement aside: on a document a copy stays a second
@@ -612,7 +653,7 @@ export function computeKeyTrust(input) {
612
653
  subject: c.payload.subject.spkiSha256,
613
654
  endorser: c.payload.endorser?.spkiSha256 ?? null,
614
655
  at,
615
- storedMs: typeof k === 'number' ? rfc3339Ms(c.input.createdAt) : instantMs(k),
656
+ storedMs: typeof k === 'number' ? rfc3339Ms(c.input.createdAt ?? '') : instantMs(k),
616
657
  written: typeof k === 'number' ? { us: k, micro } : null,
617
658
  }]);
618
659
  const valid = inWriteOrder.filter((s) => s.check.verdict === 'valid');
@@ -635,16 +676,41 @@ export function computeKeyTrust(input) {
635
676
  if (s.check.verdict === 'valid' && (activatedAt.get(s.subject) ?? signed) <= signed)
636
677
  activatedAt.set(s.subject, signed);
637
678
  }
679
+ // An ML-DSA key is reached only through an ML-DSA signature. A succession's
680
+ // forward edge is carried by the endorser's half and its edge back by the
681
+ // subject's half, so a classical endorser never admits an ML-DSA subject,
682
+ // while an ML-DSA subject still reaches its classical predecessor through
683
+ // its own half. What a classical key signs is forgeable by whoever breaks
684
+ // the classical algorithm; this keeps that from ever conferring trust on a
685
+ // key whose own signatures are not.
686
+ const postQuantum = (digest) => {
687
+ const known = keyByDigest.get(digest);
688
+ return known !== undefined && isPostQuantumKey(known.spki);
689
+ };
690
+ const carries = (from, to) => !postQuantum(to) || postQuantum(from);
638
691
  const edgesOf = (s) => {
639
692
  const e = s.endorser;
640
693
  if (e === null || s.payload.typ !== 'succession')
641
694
  return [];
642
695
  return [
643
- { from: e, to: s.subject, via: s, counts: true },
644
- { from: s.subject, to: e, via: s, counts: admissions.get(s.subject) === s && !admittedTwice.has(s.subject) },
696
+ ...(carries(e, s.subject) ? [{ from: e, to: s.subject, via: s, counts: true }] : []),
697
+ ...(carries(s.subject, e) ? [{ from: s.subject, to: e, via: s, counts: admissions.get(s.subject) === s && !admittedTwice.has(s.subject) }] : []),
645
698
  ];
646
699
  };
647
- const edges = valid.flatMap(edgesOf);
700
+ // In a rerun that assumes only refused signatures over data, a statement
701
+ // with a half this host refused still carries the edges whose own half this
702
+ // host computed and found valid; nothing is assumed about the refused half.
703
+ // Every check that needs no computation passed (or the statement would be
704
+ // invalid), `carries` still holds, and `reach` follows such an edge only
705
+ // out of a key already trusted. So a Server's ES384 key, pinned, reaches the
706
+ // Ed25519 key it succeeded through its own half of the succession, while a
707
+ // forged succession into another key, carried only by its refused Ed25519
708
+ // half, admits nothing.
709
+ const computedHalf = (edge) => edge.from === edge.via.endorser ? edge.via.check.endorserSigned : edge.via.check.subjectSigned;
710
+ const partlyComputed = isDataOnlyRerun()
711
+ ? inWriteOrder.filter((s) => s.check.verdict === 'unverifiable').flatMap(edgesOf).filter(computedHalf)
712
+ : [];
713
+ const edges = [...valid.flatMap(edgesOf), ...partlyComputed];
648
714
  // Distrusted keys and the instant each one's statements stop counting from.
649
715
  const distrust = new Set(distrustedKeys.map((d) => d.spkiSha256));
650
716
  const cutoffs = new Map();
@@ -690,7 +756,7 @@ export function computeKeyTrust(input) {
690
756
  * is not a dump row, every edge out of a distrusted key is void whatever
691
757
  * time it carries, and every closure it signed still counts: dropping an
692
758
  * edge or keeping a closure only ever takes trust away. Narrower than the
693
- * engine, never wider. The write order still orders such statements.
759
+ * Server, never wider. The write order still orders such statements.
694
760
  */
695
761
  const distrusted = (s, signer) => {
696
762
  if (signer === null || !cutoffs.has(signer))
@@ -701,7 +767,7 @@ export function computeKeyTrust(input) {
701
767
  return cutoff === null || cutoff === undefined || s.storedMs >= cutoff.at;
702
768
  };
703
769
  /**
704
- * What the engine would void: signed by a distrusted key with no cutoff, or
770
+ * What the Server would void: signed by a distrusted key with no cutoff, or
705
771
  * stored at or after its cutoff. On a key document the stored time is the
706
772
  * holder's word, so this decides only whether voiding it is a finding.
707
773
  */
@@ -710,6 +776,7 @@ export function computeKeyTrust(input) {
710
776
  return cutoff === null || cutoff === undefined || (order === 'written' && s.storedMs >= cutoff.at);
711
777
  };
712
778
  const notes = [];
779
+ const successorPins = new Set();
713
780
  const accounted = [];
714
781
  // Pass 1, then the closures it lets count.
715
782
  const pass1 = reach(anchors, edges.filter((e) => !distrusted(e.via, e.from)));
@@ -745,7 +812,7 @@ export function computeKeyTrust(input) {
745
812
  // key, a forced closure's cut-off keys included, a key cut off from a
746
813
  // leaked one could retire a distrusted key it also holds and have what that
747
814
  // key forged read as accounted for. Only a signer the walk trusts and
748
- // reaches without a distrusted key bounds it, as in the engine; the cutoff
815
+ // reaches without a distrusted key bounds it, as in the Server; the cutoff
749
816
  // a bound gives an undated entry comes from the reach alone.
750
817
  const clearOfDistrust = reach(anchors, edges.filter((e) => !distrust.has(e.from)));
751
818
  for (const [d, span] of distrustSpans) {
@@ -754,7 +821,10 @@ export function computeKeyTrust(input) {
754
821
  if (s.subject !== d || s.payload.typ !== 'closure' || s.endorser === null || distrust.has(s.endorser)
755
822
  || !clearOfDistrust.has(s.endorser) || !trusted.has(s.endorser))
756
823
  continue;
757
- const retiredAt = notAfterWrite(s.payload.subject.retiredAt, s);
824
+ const signedRetiredAt = s.payload.subject.retiredAt;
825
+ if (signedRetiredAt === undefined)
826
+ continue;
827
+ const retiredAt = notAfterWrite(signedRetiredAt, s);
758
828
  if (retiredBy === null || retiredAt < retiredBy)
759
829
  retiredBy = retiredAt;
760
830
  }
@@ -862,10 +932,13 @@ export function computeKeyTrust(input) {
862
932
  continue;
863
933
  if (voided && !voidedByStoredTime(s, e)) {
864
934
  // Voided only because a key document's time is not held against the
865
- // cutoff: it admits nothing, but a statement the engine would count is
935
+ // cutoff: it admits nothing, but a statement the Server would count is
866
936
  // no finding. It still dates windows and cuts edges back, so it can
867
937
  // only narrow trust. The checks below still apply to it.
868
938
  const cutoff = cutoffs.get(e);
939
+ // Unreachable: a signer voided here has a cutoff with an instant (see voidedByStoredTime).
940
+ if (cutoff === null || cutoff === undefined)
941
+ throw new TypeError(`The distrusted key ${e} has no cutoff instant.`);
869
942
  notes.push({
870
943
  keyId: s.payload.subject.kid,
871
944
  statementId: s.check.id,
@@ -892,7 +965,7 @@ export function computeKeyTrust(input) {
892
965
  const retiredBy = distrustSpans.get(e)?.retiredAt ?? null;
893
966
  // A later admission of a trusted key that the key itself signed is
894
967
  // the record of its own half leaking, whoever co-signed it: never
895
- // accounted for, as in the engine.
968
+ // accounted for, as in the Server.
896
969
  const leakedSubject = s.payload.typ !== 'closure' && admissions.get(s.subject) !== s && s.check.subjectSigned && trusted.has(s.subject);
897
970
  if (leakedSubject) {
898
971
  finding(code, s, `${what} It is also a ${s.payload.typ} ${s.payload.subject.kid} signed after it was already admitted: ${s.payload.subject.kid}'s private half in other hands, which no distrust entry for ${by} accounts for. Move every Server process off ${s.payload.subject.kid}, retire it with force from the key they hold, and give distrustedKeys sha256:${s.subject}@<the instant it leaked> (VAULT_DISTRUSTED_KEYS on every Server process).`);
@@ -967,7 +1040,17 @@ export function computeKeyTrust(input) {
967
1040
  }
968
1041
  continue;
969
1042
  }
970
- if (!trusted.has(s.subject) && (e === null || !trusted.has(e))) {
1043
+ if (e !== null && trusted.has(e) && !trusted.has(s.subject) && !carries(e, s.subject)) {
1044
+ // Not a finding: the Server wrote an honest succession. The walk was
1045
+ // started from the wrong side of it.
1046
+ successorPins.add(`sha256:${s.subject}`);
1047
+ notes.push({
1048
+ keyId: s.payload.subject.kid,
1049
+ statementId: s.check.id,
1050
+ detail: `${s.payload.subject.kid} is an ${s.payload.subject.alg} key, and its succession from ${by} is signed on ${by}'s side under a classical algorithm, which admits no ML-DSA key. Pin sha256:${s.subject} in trustAnchors: from it the walk reaches ${by} and the keys before it through ${s.payload.subject.kid}'s own signature.`,
1051
+ });
1052
+ }
1053
+ else if (!trusted.has(s.subject) && (e === null || !trusted.has(e))) {
971
1054
  finding('KEY_STATEMENT_INVALID', s, `a ${s.payload.typ} that touches no anchored key`);
972
1055
  }
973
1056
  else if (s.at > (closedAt.get(s.subject) ?? Infinity)) {
@@ -1004,10 +1087,8 @@ export function computeKeyTrust(input) {
1004
1087
  }
1005
1088
  // Keys an admission names that this walk could not verify. A key document
1006
1089
  // carries a key's admissions but not every endorser, so the walk can date a
1007
- // trusted key's window earlier than the engine did, or not at all.
1008
- const unverifiedAdmission = new Set(checked
1009
- .filter((c) => c.verdict === 'invalid' && c.payload !== null && c.payload.typ !== 'closure')
1010
- .map((c) => c.payload.subject.spkiSha256));
1090
+ // trusted key's window earlier than the Server did, or not at all.
1091
+ const unverifiedAdmission = new Set(checked.flatMap((c) => (c.verdict === 'invalid' && c.payload !== null && c.payload.typ !== 'closure' ? [c.payload.subject.spkiSha256] : [])));
1011
1092
  // A listed retirement the walk does not sign, read against the Server's own
1012
1093
  // distrust instant (`distrustedFrom`): where the listing was cut at that
1013
1094
  // instant and the walk signs a later retirement or none, the column is the
@@ -1096,14 +1177,24 @@ export function computeKeyTrust(input) {
1096
1177
  detail: `distrustedKeys names ${key.keyId} and no closure signed by a key the walk trusts retires it, so nothing bounds what the entry accounts for: chain entries ${key.keyId} signed fail until a retirement does. Retire it with force on the Server (POST /v1/admin/vault/signing-keys/${key.keyId}/retire with {"force": true}) from a process on a key you hold; what it signed before that retirement is then accounted for and listed, and anything it signs after it is reported.`,
1097
1178
  });
1098
1179
  }
1180
+ const closures = new Map();
1181
+ for (const [subject, list] of closuresOf) {
1182
+ const kept = list.flatMap((c) => (c.endorser !== null && trusted.has(c.endorser) && c.check.digest !== null
1183
+ ? [{ digest: c.check.digest, endorserKeyId: c.endorser.slice(0, 16), retiredAt: c.payload.subject.retiredAt ?? '', history: c.payload.history ?? null }]
1184
+ : []));
1185
+ if (kept.length > 0)
1186
+ closures.set(subject, kept);
1187
+ }
1099
1188
  return {
1100
1189
  order,
1101
1190
  anchors: anchorDigests.map((d) => `sha256:${d}`),
1191
+ closures,
1102
1192
  byDigest,
1103
1193
  trusted,
1104
1194
  undecided,
1105
1195
  findings,
1106
1196
  notes,
1197
+ successorPins: [...successorPins].sort(),
1107
1198
  accounted,
1108
1199
  distrustSpans,
1109
1200
  source: statementInputs.length > 0 && statementInputs.every((st) => st.source === 'dump') ? 'dump' : 'document',
@@ -1197,7 +1288,9 @@ export function keyStatementsFromExport(signingKeyStatements) {
1197
1288
  * statement format this verifier does not read.
1198
1289
  */
1199
1290
  export function keyStatementsFromVerificationKeys(doc) {
1200
- if (doc === null || typeof doc !== 'object' || !Array.isArray(doc.data)) {
1291
+ // Checked through an `unknown` copy so the guard does not retype `doc.data` as `any[]`.
1292
+ const rawData = doc?.data;
1293
+ if (doc === null || typeof doc !== 'object' || !Array.isArray(rawData)) {
1201
1294
  throw new TypeError('Expected the /v1/verification-keys document: { data: [...], keyStatementFormat, anchoredFrom }.');
1202
1295
  }
1203
1296
  if (doc.keyStatementFormat !== undefined && doc.keyStatementFormat !== KEY_STATEMENT_CTY) {
@@ -1218,7 +1311,7 @@ export function keyStatementsFromVerificationKeys(doc) {
1218
1311
  /**
1219
1312
  * Mark every key of a registry with the walk's verdict, and give each anchored
1220
1313
  * key the window its statements sign in place of whatever window it carried,
1221
- * as the engine grades entries. An anchored key no statement dates carries no
1314
+ * as the Server grades entries. An anchored key no statement dates carries no
1222
1315
  * edge on that side. A key is anchored only when its key id is the
1223
1316
  * fingerprint of its own SPKI: a row filed under another key's id names that
1224
1317
  * key's entries, and is anchored to nothing. On a walk over a dump, a key a
@@ -1256,12 +1349,118 @@ export function applyKeyTrust(registry, trust) {
1256
1349
  }
1257
1350
  return out;
1258
1351
  }
1259
- /** The {@link Verdict} of a result that carries `valid` and a `keyTrust` report. */
1260
- export function verdictOf(result) {
1261
- if (!result.valid)
1262
- return 'failed';
1352
+ /**
1353
+ * Whether a result is `unverifiable`: it is not valid, at least one signature
1354
+ * check could not be computed (`uncomputable.count`), this host refused an
1355
+ * algorithm this build supports (an `uncomputable.algorithms` entry with cause
1356
+ * `host`), and the same input with the same options would be valid if the
1357
+ * checks this host refused had verified (`passesIfComputed`, a rerun inside
1358
+ * `verifyAsIfHostComputed`, called only when the rest holds).
1359
+ *
1360
+ * Nothing else is assumed in that rerun: a check under a key of a type this
1361
+ * build cannot compute still fails, a signature that was checked and did not
1362
+ * verify still fails, and hash, link and count checks run as they are. So a
1363
+ * finding that follows only from a refused check (a key closure the refused
1364
+ * key signed, an entry under a key the walk could not reach past it) leaves
1365
+ * the result `unverifiable`, and any other failure makes it `failed`.
1366
+ *
1367
+ * The verdict is reserved for a refusal the verifier establishes on this host
1368
+ * itself: cause `host` rests on this build's own known-answer test of the
1369
+ * algorithm (`runtimeCanCompute`), which nothing in an artifact can change.
1370
+ * On a host that computes every algorithm this build supports there is no such
1371
+ * cause, the rerun never runs, and no artifact reads `unverifiable`.
1372
+ */
1373
+ export function isUnverifiable(result) {
1374
+ if (result.valid || result.uncomputable.count === 0)
1375
+ return false;
1376
+ if (!result.uncomputable.algorithms.some((a) => a.cause === 'host'))
1377
+ return false;
1378
+ return result.passesIfComputed();
1379
+ }
1380
+ /**
1381
+ * The {@link Verdict} of a result, with the could-not-compute rule first:
1382
+ * `unverifiable` when {@link isUnverifiable} holds, and otherwise whatever
1383
+ * `otherwise` gives (`sealedVerdict(verdictOf(...))`, which is called only
1384
+ * then, so its reruns cost nothing on an unverifiable result). So a real
1385
+ * failure anywhere is `failed`, a result that would be valid had this host
1386
+ * computed the algorithms it refused is `unverifiable`, and the `unanchored`
1387
+ * readings of a pin that was not met or that predates the move to ML-DSA
1388
+ * apply only to a result that is not. `valid` is unchanged: an unverifiable
1389
+ * result is not valid.
1390
+ */
1391
+ export function unverifiableVerdict(result, otherwise) {
1392
+ return isUnverifiable(result) ? 'unverifiable' : otherwise();
1393
+ }
1394
+ /**
1395
+ * The {@link Verdict} of a result that carries `valid` and a `keyTrust` report.
1396
+ *
1397
+ * Pass `passesUnpinned` on a run that supplied trustAnchors: it reruns the
1398
+ * same input with the same options minus `trustAnchors` and `distrustedKeys`
1399
+ * and says whether that run is valid. A pinned run that failed, whose walk
1400
+ * anchored no key at all, and whose unpinned rerun passes, is `unanchored`
1401
+ * rather than `failed`: the only thing wrong is that the pin reaches nothing
1402
+ * in the artifact (the key-statement findings and CHAIN_SIGNING_KEY_UNANCHORED
1403
+ * entries such a walk reports all follow from that). That is an export checked
1404
+ * against another Server's pin, and equally one re-signed wholesale under keys
1405
+ * of its own; neither is trusted, and the result keeps `valid: false`. An
1406
+ * artifact in which the pin anchors even one key stays `failed`, since an
1407
+ * entry beside it under an unanchored key is a substitution.
1408
+ *
1409
+ * Pass `passesPinnedOn` as well: it reruns the same input with `trustAnchors`
1410
+ * replaced by the list it is given and says whether that run is valid. A
1411
+ * pinned run that failed, whose pin is a classical key that handed over to an
1412
+ * ML-DSA key (`keyTrust.successorPins`), and whose rerun with those keys
1413
+ * pinned beside it passes, is `unanchored` too: the pin predates the move to
1414
+ * ML-DSA, and the only thing wrong is that a classical pin does not reach the
1415
+ * keys after it. The pinned key itself signed the handover, so this is not a
1416
+ * key from elsewhere; it is still not a trusted verdict, since nothing
1417
+ * post-quantum links the pin to them. The result keeps `valid: false`.
1418
+ *
1419
+ * This never returns `unverifiable`: wrap it in {@link unverifiableVerdict},
1420
+ * which takes precedence over both `unanchored` readings of a failed run.
1421
+ */
1422
+ export function verdictOf(result, passesUnpinned, passesPinnedOn) {
1423
+ if (!result.valid) {
1424
+ const pinNotMet = pinReachesNoKey(result.keyTrust) && passesUnpinned !== undefined && passesUnpinned();
1425
+ if (pinNotMet)
1426
+ return 'unanchored';
1427
+ return pinPredatesSuccessors(result.keyTrust, passesPinnedOn) ? 'unanchored' : 'failed';
1428
+ }
1263
1429
  return result.keyTrust.status === 'walked' ? 'trusted' : 'unanchored';
1264
1430
  }
1431
+ /** Whether a pinned walk anchored no key at all: the pin names nothing this input holds or links to. */
1432
+ export function pinReachesNoKey(keyTrust) {
1433
+ return keyTrust.status === 'no_anchored_signature' && keyTrust.anchoredKeyIds.length === 0;
1434
+ }
1435
+ /**
1436
+ * Whether a failed pinned run failed only because its pin predates the move to
1437
+ * ML-DSA: the walk names successor keys, and the same input passes with them
1438
+ * pinned beside the anchors given.
1439
+ */
1440
+ export function pinPredatesSuccessors(keyTrust, passesPinnedOn) {
1441
+ const successors = keyTrust.successorPins ?? [];
1442
+ return successors.length > 0 && passesPinnedOn !== undefined
1443
+ && passesPinnedOn([...new Set([...(keyTrust.anchors ?? []), ...successors])]);
1444
+ }
1445
+ /**
1446
+ * What to tell the holder of a pin that predates the move to ML-DSA (a result
1447
+ * whose verdict is `unanchored`, `valid` false and `keyTrust.successorPins`
1448
+ * not empty): what happened, that it is not evidence of tampering, and which
1449
+ * key to confirm and pin.
1450
+ */
1451
+ export function pinPredatesDetail(successorPins) {
1452
+ const keys = successorPins.join(', ');
1453
+ return `The trust anchor given is a key from before this Server moved to ML-DSA. It signed the handover to ${keys}, and a classical signature does not anchor an ML-DSA key, so the keys after it, and what they signed or retired, are not anchored from this pin. Nothing else failed: with ${successorPins.length === 1 ? 'that key' : 'those keys'} pinned as well, everything here verifies. This is not a trusted verdict and not evidence of tampering. Confirm the Server's current pin with its operator (the installer prints it) and verify again with it.`;
1454
+ }
1455
+ /**
1456
+ * A verdict, given how the entries classical keys signed stand against the
1457
+ * history seals: `trusted` becomes `unanchored` when any such entry is
1458
+ * unsealed, since it then rests on a classical signature no ML-DSA key vouches
1459
+ * for. Every other verdict is unchanged.
1460
+ */
1461
+ export function sealedVerdict(verdict, historySeal) {
1462
+ return verdict === 'trusted' && historySeal.unsealed > 0 ? 'unanchored' : verdict;
1463
+ }
1265
1464
  /**
1266
1465
  * Summarize a registry after `applyKeyTrust` (or with `trust` null when no
1267
1466
  * walk ran). A walked report says `walked` until the caller settles it with
@@ -1285,6 +1484,7 @@ export function reportKeyTrust(registry, trust, anchoredFrom) {
1285
1484
  undecidedKeyIds: [],
1286
1485
  findings: [],
1287
1486
  notes: [],
1487
+ successorPins: [],
1288
1488
  accounted: [],
1289
1489
  };
1290
1490
  }
@@ -1303,6 +1503,7 @@ export function reportKeyTrust(registry, trust, anchoredFrom) {
1303
1503
  undecidedKeyIds: ids('undecided'),
1304
1504
  findings: trust.findings,
1305
1505
  notes: trust.notes,
1506
+ successorPins: trust.successorPins,
1306
1507
  accounted: trust.accounted,
1307
1508
  };
1308
1509
  }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Known-answer vectors for ML-DSA (FIPS 204, pure, empty context): one fixed
3
+ * (SPKI key, signature) pair per parameter set over the shared KAT message in
4
+ * primitives.ts. Generated once with node:crypto and checked in; the Python
5
+ * verifier carries the same bytes. Kept apart only for size.
6
+ */
7
+ export declare const ML_DSA_44_KAT: {
8
+ readonly spkiBase64: string;
9
+ readonly signatureBase64: string;
10
+ };
11
+ export declare const ML_DSA_65_KAT: {
12
+ readonly spkiBase64: string;
13
+ readonly signatureBase64: string;
14
+ };
15
+ export declare const ML_DSA_87_KAT: {
16
+ readonly spkiBase64: string;
17
+ readonly signatureBase64: string;
18
+ };