@agledger/verify-core 2.2.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +18 -18
  2. package/README.md +797 -29
  3. package/dist/acknowledgements.d.ts +32 -0
  4. package/dist/acknowledgements.js +88 -0
  5. package/dist/anchors.d.ts +349 -0
  6. package/dist/anchors.js +654 -0
  7. package/dist/attestation.d.ts +98 -0
  8. package/dist/attestation.js +145 -0
  9. package/dist/audit-export.d.ts +343 -20
  10. package/dist/audit-export.js +400 -22
  11. package/dist/batch-head.d.ts +28 -0
  12. package/dist/batch-head.js +169 -0
  13. package/dist/batch.d.ts +69 -0
  14. package/dist/batch.js +99 -0
  15. package/dist/bulk-export.d.ts +161 -0
  16. package/dist/bulk-export.js +711 -0
  17. package/dist/chain.d.ts +135 -13
  18. package/dist/chain.js +229 -24
  19. package/dist/claim.d.ts +23 -0
  20. package/dist/claim.js +100 -0
  21. package/dist/export-anchors.d.ts +84 -0
  22. package/dist/export-anchors.js +109 -0
  23. package/dist/export-evidence.d.ts +90 -0
  24. package/dist/export-evidence.js +186 -0
  25. package/dist/export-pages.d.ts +476 -0
  26. package/dist/export-pages.js +586 -0
  27. package/dist/failures.d.ts +20 -16
  28. package/dist/failures.js +44 -16
  29. package/dist/federation-wire.d.ts +78 -11
  30. package/dist/federation-wire.js +199 -57
  31. package/dist/history-seal.d.ts +100 -0
  32. package/dist/history-seal.js +301 -0
  33. package/dist/index.d.ts +36 -8
  34. package/dist/index.js +17 -4
  35. package/dist/key-statements.d.ts +138 -5
  36. package/dist/key-statements.js +191 -20
  37. package/dist/ml-dsa-kats.d.ts +18 -0
  38. package/dist/ml-dsa-kats.js +241 -0
  39. package/dist/primitives.d.ts +255 -18
  40. package/dist/primitives.js +612 -55
  41. package/dist/read-log.d.ts +350 -0
  42. package/dist/read-log.js +816 -0
  43. package/dist/schema-chain-export.d.ts +82 -0
  44. package/dist/schema-chain-export.js +474 -0
  45. package/dist/walk-anchors.d.ts +115 -0
  46. package/dist/walk-anchors.js +133 -0
  47. package/dist/walk-checkpoints.d.ts +125 -0
  48. package/dist/walk-checkpoints.js +118 -0
  49. package/package.json +6 -5
@@ -19,6 +19,7 @@
19
19
  * regression net that catches divergence.
20
20
  */
21
21
  import { createPublicKey, getFips, hash, verify } from 'node:crypto';
22
+ import { ML_DSA_44_KAT, ML_DSA_65_KAT, ML_DSA_87_KAT } from './ml-dsa-kats.js';
22
23
  import { STRICT_CBOR_DECODE } from './cbor-strict.js';
23
24
  import { decode as cborDecode, encode as cborEncode, rfc8949EncodeOptions } from 'cborg';
24
25
  // --- SHA-256 ---
@@ -41,9 +42,17 @@ export function sha256HexString(s) {
41
42
  const KEY_ALGORITHMS = {
42
43
  ed25519: Object.freeze({ name: 'Ed25519', coseAlgs: Object.freeze([-8, -19]), signatureLength: 64, verifiable: true, nodeKeyType: 'ed25519', namedCurve: null, digest: null, dsaEncoding: null }),
43
44
  'ec:prime256v1': Object.freeze({ name: 'ES256', coseAlgs: Object.freeze([-7, -9]), signatureLength: 64, verifiable: true, nodeKeyType: 'ec', namedCurve: 'prime256v1', digest: 'sha256', dsaEncoding: 'ieee-p1363' }),
44
- 'ec:secp384r1': Object.freeze({ name: 'ES384', coseAlgs: Object.freeze([-35]), signatureLength: 96, verifiable: false, nodeKeyType: 'ec', namedCurve: 'secp384r1', digest: null, dsaEncoding: null }),
45
+ // ES384 keeps the one label the Server writes, -35: dispatch is bound to the
46
+ // key, so the RFC 9864 ESP384 label (-51) is not needed and is not accepted.
47
+ 'ec:secp384r1': Object.freeze({ name: 'ES384', coseAlgs: Object.freeze([-35]), signatureLength: 96, verifiable: true, nodeKeyType: 'ec', namedCurve: 'secp384r1', digest: 'sha384', dsaEncoding: 'ieee-p1363' }),
45
48
  'ec:secp521r1': Object.freeze({ name: 'ES512', coseAlgs: Object.freeze([-36]), signatureLength: 132, verifiable: false, nodeKeyType: 'ec', namedCurve: 'secp521r1', digest: null, dsaEncoding: null }),
46
49
  'ec:secp256k1': Object.freeze({ name: 'ES256K', coseAlgs: Object.freeze([-47]), signatureLength: 64, verifiable: false, nodeKeyType: 'ec', namedCurve: 'secp256k1', digest: null, dsaEncoding: null }),
50
+ // ML-DSA (FIPS 204), pure, empty context, COSE labels from
51
+ // draft-ietf-cose-dilithium. The signature is over the Sig_structure itself,
52
+ // as with Ed25519, so the dispatch is the same `verify(null, ...)`.
53
+ 'ml-dsa-44': Object.freeze({ name: 'ML-DSA-44', coseAlgs: Object.freeze([-48]), signatureLength: 2420, verifiable: true, nodeKeyType: 'ml-dsa-44', namedCurve: null, digest: null, dsaEncoding: null }),
54
+ 'ml-dsa-65': Object.freeze({ name: 'ML-DSA-65', coseAlgs: Object.freeze([-49]), signatureLength: 3309, verifiable: true, nodeKeyType: 'ml-dsa-65', namedCurve: null, digest: null, dsaEncoding: null }),
55
+ 'ml-dsa-87': Object.freeze({ name: 'ML-DSA-87', coseAlgs: Object.freeze([-50]), signatureLength: 4627, verifiable: true, nodeKeyType: 'ml-dsa-87', namedCurve: null, digest: null, dsaEncoding: null }),
47
56
  };
48
57
  /**
49
58
  * Look up a table entry by its registry name (`Ed25519`, `ES256`, ...).
@@ -87,20 +96,89 @@ export function looksLikeEd25519Key(spkiDer) {
87
96
  return false;
88
97
  return Buffer.from(spkiDer).subarray(0, ED25519_SPKI_PREFIX.length).equals(ED25519_SPKI_PREFIX);
89
98
  }
99
+ /**
100
+ * SPKI DER prefix and total length for each ML-DSA parameter set: SEQUENCE {
101
+ * SEQUENCE { OID 2.16.840.1.101.3.4.3.17/18/19 } BIT STRING { key } }, with
102
+ * no parameters, so every key of a set is these bytes followed by its raw key.
103
+ */
104
+ const ML_DSA_SPKI = [
105
+ { table: 'ml-dsa-44', prefix: Buffer.from('30820532300b06096086480165030403110382052100', 'hex'), length: 1334 },
106
+ { table: 'ml-dsa-65', prefix: Buffer.from('308207b2300b0609608648016503040312038207a100', 'hex'), length: 1974 },
107
+ { table: 'ml-dsa-87', prefix: Buffer.from('30820a32300b060960864801650304031303820a2100', 'hex'), length: 2614 },
108
+ ];
109
+ /**
110
+ * The table entry these bytes DECLARE by their SPKI structure, without asking
111
+ * node:crypto to load them: Ed25519 or an ML-DSA parameter set, else null.
112
+ * Same purpose as `looksLikeEd25519Key`, widened to every algorithm a host
113
+ * can refuse at load: a Node.js build without ML-DSA cannot load an ML-DSA
114
+ * key, and that must read as "not verified here", not as tamper.
115
+ */
116
+ export function declaredKeyAlgorithm(spkiDer) {
117
+ if (looksLikeEd25519Key(spkiDer))
118
+ return KEY_ALGORITHMS['ed25519'] ?? null;
119
+ const bytes = Buffer.from(spkiDer);
120
+ for (const { table, prefix, length } of ML_DSA_SPKI) {
121
+ if (bytes.length === length && bytes.subarray(0, prefix.length).equals(prefix))
122
+ return KEY_ALGORITHMS[table] ?? null;
123
+ }
124
+ return null;
125
+ }
126
+ /** AlgorithmIdentifier contents (OID, then the curve OID for EC) for each table entry, hex. */
127
+ const SPKI_ALGORITHM_IDS = [
128
+ { table: 'ed25519', id: '06032b6570' },
129
+ { table: 'ec:prime256v1', id: '06072a8648ce3d020106082a8648ce3d030107' },
130
+ { table: 'ec:secp384r1', id: '06072a8648ce3d020106052b81040022' },
131
+ { table: 'ml-dsa-44', id: '0609608648016503040311' },
132
+ { table: 'ml-dsa-65', id: '0609608648016503040312' },
133
+ { table: 'ml-dsa-87', id: '0609608648016503040313' },
134
+ ];
135
+ /** The header length and content length of the DER element at `at`, or null. */
136
+ function derElement(der, at, tag) {
137
+ if (der[at] !== tag || at + 1 >= der.length)
138
+ return null;
139
+ const first = der[at + 1] ?? 0;
140
+ let length = first;
141
+ let start = at + 2;
142
+ if (first >= 0x80) {
143
+ const lengthBytes = first & 0x7f;
144
+ if (lengthBytes === 0 || lengthBytes > 4)
145
+ return null;
146
+ length = 0;
147
+ for (let i = 0; i < lengthBytes; i++)
148
+ length = length * 256 + (der[start + i] ?? 0);
149
+ start += lengthBytes;
150
+ }
151
+ const end = start + length;
152
+ return end <= der.length ? { start, end } : null;
153
+ }
154
+ /**
155
+ * The table key the SPKI AlgorithmIdentifier of these bytes names (its OID,
156
+ * and its curve for EC), read without node:crypto; null for any other
157
+ * algorithm or for bytes that are not an SPKI. What the key IS, so that what
158
+ * the host made of it can be checked against it.
159
+ */
160
+ function spkiAlgorithmTableKey(der) {
161
+ const outer = derElement(der, 0, 0x30);
162
+ if (outer === null)
163
+ return null;
164
+ const algorithmId = derElement(der, outer.start, 0x30);
165
+ if (algorithmId === null)
166
+ return null;
167
+ const id = Buffer.from(der.subarray(algorithmId.start, algorithmId.end)).toString('hex');
168
+ return SPKI_ALGORITHM_IDS.find((entry) => entry.id === id)?.table ?? null;
169
+ }
90
170
  /**
91
171
  * The narrow case where a key that would not LOAD must not read as tamper: the
92
- * bytes declare Ed25519 by OID and this host cannot compute Ed25519 at all.
172
+ * bytes declare Ed25519 or ML-DSA by OID and this host cannot compute it.
93
173
  *
94
174
  * Judged from the OID rather than from capability alone, so genuinely tampered
95
175
  * key material still reads as tamper on every host, and both verifiers agree on
96
176
  * garbage bytes. On a host that CAN compute Ed25519 this is always false, so an
97
177
  * unloadable key there stays a signature failure exactly as before.
98
178
  */
99
- function isRuntimeRefusedEd25519Key(publicKeyBase64) {
100
- const ed = KEY_ALGORITHMS['ed25519'];
101
- if (!ed)
102
- return false;
103
- return looksLikeEd25519Key(Buffer.from(publicKeyBase64, 'base64')) && !runtimeCanCompute(ed);
179
+ function runtimeRefusedKey(publicKeyBase64) {
180
+ const declared = declaredKeyAlgorithm(Buffer.from(publicKeyBase64, 'base64'));
181
+ return declared !== null && !hostComputes(declared) ? declared : null;
104
182
  }
105
183
  /** Small memo: a registry holds a handful of keys but chains hold millions of entries. */
106
184
  const KEY_ALG_CACHE = new Map();
@@ -116,18 +194,70 @@ const KEY_ALG_CACHE_MAX = 256;
116
194
  * - `'unparseable'` when the bytes are not a public key at all.
117
195
  */
118
196
  export function resolveKeyAlgorithm(publicKeyBase64) {
197
+ const resolved = resolveOnHost(publicKeyBase64);
198
+ // Inside verifyAsIfHostComputed, a key this host refused to load resolves to
199
+ // the algorithm its bytes declare (Ed25519 or ML-DSA, by structure). Never
200
+ // cached: the cache holds only what the host itself answered.
201
+ if (resolved === 'unparseable' && assumingHostRefusals())
202
+ return runtimeRefusedKey(publicKeyBase64) ?? resolved;
203
+ return resolved;
204
+ }
205
+ /**
206
+ * {@link resolveKeyAlgorithm}, with a key this host refused to LOAD read as
207
+ * the algorithm its bytes declare (Ed25519 or ML-DSA, by structure, on a host
208
+ * whose own known-answer test says it does not compute that algorithm). For a
209
+ * site that judges a key before computing anything under it (a batched
210
+ * entry's own key, a batch head's key, a history seal's key), so a host
211
+ * refusal there reads as one, as it does for an entry's signature, and never
212
+ * as a malformed key. Garbage bytes still resolve `'unparseable'`, and a key
213
+ * of a type this build cannot compute still resolves `'unrecognized'`.
214
+ */
215
+ export function resolveKeyAlgorithmOrHostRefused(publicKeyBase64) {
216
+ const resolved = resolveKeyAlgorithm(publicKeyBase64);
217
+ return resolved === 'unparseable' ? runtimeRefusedKey(publicKeyBase64) ?? resolved : resolved;
218
+ }
219
+ /** Whether `der` is exactly one DER element: a definite length that ends where the buffer does. */
220
+ function isOneDerElement(der) {
221
+ if (der.length < 2)
222
+ return false;
223
+ const first = der[1] ?? 0;
224
+ if (first < 0x80)
225
+ return der.length === 2 + first;
226
+ const lengthBytes = first & 0x7f;
227
+ if (lengthBytes === 0 || lengthBytes > 4 || der.length < 2 + lengthBytes)
228
+ return false;
229
+ let length = 0;
230
+ for (let i = 0; i < lengthBytes; i++)
231
+ length = length * 256 + (der[2 + i] ?? 0);
232
+ return der.length === 2 + lengthBytes + length;
233
+ }
234
+ function resolveOnHost(publicKeyBase64) {
119
235
  const cached = KEY_ALG_CACHE.get(publicKeyBase64);
120
236
  if (cached !== undefined)
121
237
  return cached;
122
238
  let resolved;
123
239
  try {
240
+ const der = Buffer.from(publicKeyBase64, 'base64');
241
+ // OpenSSL loads a key and ignores whatever follows it. Bytes after the
242
+ // SPKI structure are not part of any key the Server published, so such
243
+ // input is not a public key here.
244
+ if (!isOneDerElement(der))
245
+ throw new TypeError('trailing bytes after the SPKI structure');
124
246
  const keyObj = createPublicKey({
125
- key: Buffer.from(publicKeyBase64, 'base64'),
247
+ key: der,
126
248
  format: 'der',
127
249
  type: 'spki',
128
250
  });
129
251
  const type = keyObj.asymmetricKeyType;
130
252
  const tableKey = type === 'ec' ? `ec:${keyObj.asymmetricKeyDetails?.namedCurve ?? 'unknown'}` : (type ?? '');
253
+ // A host can load a key without knowing its type: Node.js 24.5 loads an
254
+ // ML-DSA key with `asymmetricKeyType` undefined, and computes nothing
255
+ // under it. A key the host does not type as its own OID says is one the
256
+ // host did not load, so it reads as the refused load does: the algorithm
257
+ // its bytes declare, if this host cannot compute that, else not a key.
258
+ const declared = spkiAlgorithmTableKey(der);
259
+ if (declared !== null && declared !== tableKey)
260
+ throw new TypeError('the host did not type this key as its SPKI algorithm');
131
261
  resolved = KEY_ALGORITHMS[tableKey] ?? 'unrecognized';
132
262
  }
133
263
  catch {
@@ -155,6 +285,8 @@ export function resolveKeyAlgorithm(publicKeyBase64) {
155
285
  */
156
286
  export function verifyEd25519Bytes(publicKeyBase64, input, signature) {
157
287
  try {
288
+ if (!isOneDerElement(Buffer.from(publicKeyBase64, 'base64')))
289
+ return false;
158
290
  const publicKeyObj = createPublicKey({
159
291
  key: Buffer.from(publicKeyBase64, 'base64'),
160
292
  format: 'der',
@@ -168,7 +300,7 @@ export function verifyEd25519Bytes(publicKeyBase64, input, signature) {
168
300
  return false;
169
301
  }
170
302
  }
171
- // --- Key-dispatched signature verification (Ed25519 + ES256) ---
303
+ // --- Key-dispatched signature verification ---
172
304
  /**
173
305
  * Perform the actual verify() call for a resolved algorithm, WITHOUT catching.
174
306
  *
@@ -178,13 +310,21 @@ export function verifyEd25519Bytes(publicKeyBase64, input, signature) {
178
310
  * `runtimeCanCompute`). Collapsing those two into one boolean is what made a
179
311
  * FIPS-locked host report an intact Ed25519 chain as forged.
180
312
  *
181
- * ES256 mirrors how the Server verifies it: SHA-256 digest passed
182
- * positionally, `dsaEncoding: 'ieee-p1363'` (COSE raw r||s, 64 bytes). The
313
+ * ES256 and ES384 mirror how the Server verifies them: the SHA-256 or SHA-384
314
+ * digest passed positionally, `dsaEncoding: 'ieee-p1363'` (COSE raw r||s, 64
315
+ * or 96 bytes). The
183
316
  * Server normalizes to low-S at sign time but, like the Server's verifier,
184
317
  * high-S is accepted here: ECDSA malleability changes the envelope bytes,
185
318
  * which the hash-link layer already pins.
186
319
  */
187
320
  function dispatchVerify(keyAlg, publicKeyBase64, input, signature) {
321
+ // Inside verifyAsIfHostComputed, a check this host refused (its known-answer
322
+ // test already ran and failed) reads as verified. The known-answer test
323
+ // itself never lands here: it runs only while the cache holds no answer.
324
+ if (assumingHostRefusals() && keyAlg.verifiable && RUNTIME_SUPPORT_CACHE.get(keyAlg) === false)
325
+ return true;
326
+ if (!isOneDerElement(Buffer.from(publicKeyBase64, 'base64')))
327
+ return false;
188
328
  const keyObj = createPublicKey({
189
329
  key: Buffer.from(publicKeyBase64, 'base64'),
190
330
  format: 'der',
@@ -245,6 +385,16 @@ const ALGORITHM_KATS = new Map([
245
385
  signatureBase64: 'eQ8fKfXT5GuBUz7gueqcq9hTmzrJlSuaoF/ukCPtKJsxqrynVgIREn/XMPKbdSHp7wMyFOEAgmbVfoMDnR5x/Q==',
246
386
  },
247
387
  ],
388
+ [
389
+ KEY_ALGORITHMS['ec:secp384r1'],
390
+ {
391
+ spkiBase64: 'MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEnBY5YY4NaY21MROLzLa8e3jw6c5j1ebNFv29jDnB+aNAGuxk1dGLJptcDTnsgpw45lR2hCjiKUseIf95Tao2LR9SrdhFajS4kU67c8kjg/pes9LO69ot8cQIfu+yToni',
392
+ signatureBase64: 'UevJXyi6EMz+GTK52SSfBb1A+Z8e4rojB/8AYjR9WaVvwU65cd8ih1hBWA3NuGsCPFryTiHQ+o6GQT8hg7XbIBrK/24XJwR9QnPAlojJM2GdAIiTstx+xkKYOmA5TnVQ',
393
+ },
394
+ ],
395
+ [KEY_ALGORITHMS['ml-dsa-44'], ML_DSA_44_KAT],
396
+ [KEY_ALGORITHMS['ml-dsa-65'], ML_DSA_65_KAT],
397
+ [KEY_ALGORITHMS['ml-dsa-87'], ML_DSA_87_KAT],
248
398
  ]);
249
399
  // Every algorithm this build claims to compute must carry a vector proving the
250
400
  // host can compute it. Failing at import is the point: a packaging slip here
@@ -267,6 +417,42 @@ const RUNTIME_SUPPORT_CACHE = new Map();
267
417
  * as tamper evidence.
268
418
  */
269
419
  export function runtimeCanCompute(keyAlg) {
420
+ if (hostComputes(keyAlg))
421
+ return true;
422
+ return assumingHostRefusals() && keyAlg.verifiable && ALGORITHM_KATS.has(keyAlg);
423
+ }
424
+ /** The lowest Node.js release this package verifies on: the first that computes ML-DSA, the Server's default signing algorithm. */
425
+ export const NODE_FLOOR = '24.6.0';
426
+ /**
427
+ * Whether the running Node.js is older than {@link NODE_FLOOR}; null when it
428
+ * is not. Node.js releases before the floor do not compute ML-DSA, so a
429
+ * verdict reached there on a record a current Server signed is not one to
430
+ * act on. The command-line verifiers stop here and reach no verdict; a
431
+ * library caller reads this, or `runtime` on a result, and does the same.
432
+ */
433
+ export function runtimeBelowFloor() {
434
+ const parse = (v) => v.replace(/^v/, '').split('.').map((n) => Number.parseInt(n, 10) || 0);
435
+ const running = parse(process.version);
436
+ const floor = parse(NODE_FLOOR);
437
+ for (let i = 0; i < 3; i++) {
438
+ const a = running[i] ?? 0;
439
+ const b = floor[i] ?? 0;
440
+ if (a > b)
441
+ return null;
442
+ if (a < b)
443
+ return { belowFloor: true, nodeVersion: process.version, floor: NODE_FLOOR };
444
+ }
445
+ return null;
446
+ }
447
+ /** The sentence to show first when {@link runtimeBelowFloor} is not null. */
448
+ export function belowFloorNotice(runtime) {
449
+ return `This Node.js runtime (${runtime.nodeVersion}) does not compute ML-DSA, the Server's default signing algorithm: verification needs Node.js ${runtime.floor} or later. Run it again on Node.js ${runtime.floor} or later before acting on any result from this runtime.`;
450
+ }
451
+ /**
452
+ * The host's own answer for `keyAlg`, from the known-answer test, whatever
453
+ * {@link verifyAsIfHostComputed} assumes.
454
+ */
455
+ function hostComputes(keyAlg) {
270
456
  if (!keyAlg.verifiable)
271
457
  return false;
272
458
  const kat = ALGORITHM_KATS.get(keyAlg);
@@ -301,9 +487,9 @@ export function describeUnsupportedAlgorithm(publicKeyBase64) {
301
487
  // exists for, the key never loaded, so there is no algorithm to resolve and
302
488
  // the generic "upgrade the verifier" text would send an auditor after a build
303
489
  // that is fine. Answer from the OID instead.
304
- if (typeof keyAlg !== 'object' && isRuntimeRefusedEd25519Key(publicKeyBase64)) {
305
- return describeRuntimeRefusal(KEY_ALGORITHMS['ed25519']);
306
- }
490
+ const refused = typeof keyAlg !== 'object' ? runtimeRefusedKey(publicKeyBase64) : null;
491
+ if (refused)
492
+ return describeRuntimeRefusal(refused);
307
493
  if (typeof keyAlg !== 'object') {
308
494
  return 'commits to an algorithm this verifier build cannot compute. The chain is NOT verified; upgrade the verifier.';
309
495
  }
@@ -321,19 +507,287 @@ export function describeUnsupportedAlgorithm(publicKeyBase64) {
321
507
  }
322
508
  /** The host-refused-this-algorithm sentence, shared by both ways of reaching it. */
323
509
  function describeRuntimeRefusal(keyAlg) {
510
+ return (`commits to ${keyAlg.name}, which this verifier build supports but this HOST RUNTIME refused to compute` +
511
+ runtimeRefusalCause(keyAlg.name) +
512
+ ' This is NOT tamper evidence: the signature was never checked, so the chain is neither verified nor refuted.' +
513
+ ' Re-run the verification on a host without that restriction.');
514
+ }
515
+ /** Why the host refused `name`, as the clause that ends the refusal sentence. */
516
+ /**
517
+ * What a signature's bytes are under `keyAlg`, before anything is computed:
518
+ * the all-zero sentinel of the algorithm's length, a length no signature
519
+ * under it has, or a candidate signature. Read the same on every host, so a
520
+ * site asks it before asking whether this host computes the algorithm.
521
+ */
522
+ export function signatureShape(keyAlg, signature) {
523
+ if (signature.length !== keyAlg.signatureLength)
524
+ return 'wrong-length';
525
+ return signature.every((b) => b === 0) ? 'zero' : 'signature';
526
+ }
527
+ /**
528
+ * Why this host refused to compute `name`, when that is known, as a clause:
529
+ * an active OpenSSL FIPS provider for Ed25519 (it carries no EdDSA) or for
530
+ * ML-DSA, or a Node.js runtime older than ML-DSA's for ML-DSA. Null when no
531
+ * cause is known: the line then names the algorithm and claims no cause.
532
+ */
533
+ export function hostRefusalCause(name) {
534
+ if (name === 'Ed25519')
535
+ return isFipsActive() ? 'the OpenSSL FIPS provider is active, and it carries no EdDSA' : null;
536
+ if (name.startsWith('ML-DSA-')) {
537
+ return isFipsActive()
538
+ ? 'the OpenSSL FIPS provider active on this host did not compute it'
539
+ : `this Node.js runtime (${process.version}) does not compute it; Node.js computes ML-DSA from 24.6.0`;
540
+ }
541
+ return null;
542
+ }
543
+ function runtimeRefusalCause(name) {
324
544
  // The FIPS clause names a missing EdDSA implementation, so it belongs only
325
545
  // to EdDSA. A FIPS provider carries ECDSA P-256 quite happily, and telling
326
546
  // an ES256 auditor that EdDSA is absent sends them somewhere useless.
327
- const cause = isFipsActive() && keyAlg.name === 'Ed25519'
547
+ return isFipsActive() && name === 'Ed25519'
328
548
  ? ' because the OpenSSL FIPS provider is active, and it carries no EdDSA.'
329
- : '.';
330
- return (`commits to ${keyAlg.name}, which this verifier build supports but this HOST RUNTIME refused to compute` +
331
- cause +
332
- ' This is NOT tamper evidence: the signature was never checked, so the chain is neither verified nor refuted.' +
333
- ' Re-run the verification on a host without that restriction.');
549
+ : name.startsWith('ML-DSA-')
550
+ ? isFipsActive()
551
+ ? ' because the OpenSSL FIPS provider active on this host did not compute it.'
552
+ : ` because this Node.js runtime (${process.version}) does not compute it; Node.js computes ML-DSA from 24.6.0, so upgrade Node.js.`
553
+ : '.';
554
+ }
555
+ /**
556
+ * The {@link UncomputableAlgorithm} of a key, given its SPKI DER base64, or
557
+ * null when this build and this host can both compute it, or when the bytes
558
+ * are not a public key at all (which is tamper class, not a gap).
559
+ */
560
+ export function uncomputableAlgorithm(publicKeyBase64) {
561
+ const keyAlg = resolveOnHost(publicKeyBase64);
562
+ if (typeof keyAlg !== 'object') {
563
+ const refused = runtimeRefusedKey(publicKeyBase64);
564
+ if (refused)
565
+ return { algorithm: refused.name, cause: 'host' };
566
+ return keyAlg === 'unrecognized' ? { algorithm: null, cause: 'build' } : null;
567
+ }
568
+ if (!keyAlg.verifiable)
569
+ return { algorithm: keyAlg.name, cause: 'build' };
570
+ return hostComputes(keyAlg) ? null : { algorithm: keyAlg.name, cause: 'host' };
571
+ }
572
+ /**
573
+ * Set only for the duration of {@link verifyAsIfHostComputed}. Module state,
574
+ * which is sound because every verifier in this package, and in
575
+ * `@agledger/verify`, is synchronous: nothing else runs while it is set.
576
+ */
577
+ let rerun = null;
578
+ /**
579
+ * Set while a key statement's signature is judged (see {@link judgingKeyStatements}).
580
+ * Inside a rerun that does not assume key statements, the host's refusals are
581
+ * not assumed there.
582
+ */
583
+ let judgingStatements = false;
584
+ /** Whether a check this host refused counts as verified right here. */
585
+ function assumingHostRefusals() {
586
+ return rerun !== null && (rerun.statements || !judgingStatements);
587
+ }
588
+ /**
589
+ * Run `run` as though the signature checks this host refused under an
590
+ * algorithm this build supports had verified, and return what it returns.
591
+ * The counterfactual behind the `unverifiable` verdict (see
592
+ * `unverifiableVerdict`): a result is unverifiable only when the same input,
593
+ * re-verified this way, is valid.
594
+ *
595
+ * Only the host's refusals change. "Refused" is this build's own known-answer
596
+ * test of the algorithm on this host, which nothing in an artifact can change,
597
+ * so on a host that computes every algorithm this build supports, `run`
598
+ * behaves exactly as it would outside. A key of a type this build cannot
599
+ * compute still cannot be computed, a signature that was checked and did not
600
+ * verify still does not, and hash, link and count checks run as they are.
601
+ *
602
+ * With `statements: false`, a refused check over a key statement (a vault
603
+ * key's genesis, succession or closure, a federation key's history) is not
604
+ * assumed: it reads exactly as it does outside, so no key reaches trust
605
+ * through a signature this host did not compute. That is the rerun for a run
606
+ * with a trust anchor this host can compute (see `hasComputableAnchor`).
607
+ *
608
+ * For verifiers built on this package. `run` must be synchronous; the
609
+ * assumption is withdrawn when it returns or throws, and never outlives it. A
610
+ * result read inside it is a counterfactual and must never be reported as a
611
+ * verification.
612
+ */
613
+ export function verifyAsIfHostComputed(run, options = { statements: true }) {
614
+ const outer = rerun;
615
+ rerun = { statements: options.statements };
616
+ try {
617
+ return run();
618
+ }
619
+ finally {
620
+ rerun = outer;
621
+ }
622
+ }
623
+ /** Whether the caller is inside {@link verifyAsIfHostComputed}. */
624
+ export function isVerifyingAsIfHostComputed() {
625
+ return rerun !== null;
626
+ }
627
+ /**
628
+ * Whether this is a rerun that assumes only the refused signatures over data:
629
+ * one under a trust anchor this host computes, where a key is trusted only
630
+ * through signatures this host computed.
631
+ */
632
+ export function isDataOnlyRerun() {
633
+ return rerun !== null && !rerun.statements;
634
+ }
635
+ /**
636
+ * Run `run`, which judges key statement signatures, so that a rerun that does
637
+ * not assume key statements reads them as this host does. Every site that
638
+ * decides key trust from a signature runs inside it.
639
+ */
640
+ export function judgingKeyStatements(run) {
641
+ const outer = judgingStatements;
642
+ judgingStatements = true;
643
+ try {
644
+ return run();
645
+ }
646
+ finally {
647
+ judgingStatements = outer;
648
+ }
649
+ }
650
+ /** The keys among `publicKeys` (SPKI DER base64) whose digest is one of `anchors` (`sha256:<hex>` or bare hex). */
651
+ function anchoredAmong(anchors, publicKeys) {
652
+ const wanted = new Set(anchors.map((a) => a.toLowerCase().replace(/^sha256:/, '')));
653
+ const out = new Set();
654
+ if (wanted.size === 0)
655
+ return [];
656
+ for (const spki of publicKeys) {
657
+ if (wanted.has(hash('sha256', Buffer.from(spki, 'base64'), 'hex')))
658
+ out.add(spki);
659
+ }
660
+ return [...out];
661
+ }
662
+ /** The algorithm a key is, as this host reads it: a key it refused to load is the algorithm its bytes declare. */
663
+ function hostAlgorithmOf(spki) {
664
+ const keyAlg = resolveOnHost(spki);
665
+ if (typeof keyAlg === 'object')
666
+ return keyAlg;
667
+ return keyAlg === 'unparseable' ? runtimeRefusedKey(spki) : null;
668
+ }
669
+ /**
670
+ * Whether one of `anchors` is the digest of one of `publicKeys` (SPKI DER
671
+ * base64) whose algorithm this host computes, by its own known-answer test.
672
+ * With such an anchor this host can establish key trust itself, and the
673
+ * counterfactual rerun assumes no key statement. Read from the host alone,
674
+ * never from inside a rerun.
675
+ */
676
+ export function hasComputableAnchor(anchors, publicKeys) {
677
+ return anchoredAmong(anchors, publicKeys).some((spki) => {
678
+ const keyAlg = hostAlgorithmOf(spki);
679
+ return keyAlg !== null && keyAlg.verifiable && hostComputes(keyAlg);
680
+ });
681
+ }
682
+ /** The algorithms of the keys among `publicKeys` that `anchors` name, each once. */
683
+ export function anchorAlgorithms(anchors, publicKeys) {
684
+ return [...new Set(anchoredAmong(anchors, publicKeys).flatMap((spki) => {
685
+ const keyAlg = hostAlgorithmOf(spki);
686
+ return keyAlg === null ? [] : [keyAlg.name];
687
+ }))];
688
+ }
689
+ /**
690
+ * The algorithms among `publicKeys` (SPKI DER base64) this host or build
691
+ * cannot compute, each once, in the order first met.
692
+ */
693
+ export function uncomputableAlgorithms(publicKeys) {
694
+ const seen = new Map();
695
+ for (const spki of publicKeys) {
696
+ const found = uncomputableAlgorithm(spki);
697
+ if (found === null)
698
+ continue;
699
+ const id = `${found.cause}:${found.algorithm ?? ''}`;
700
+ if (!seen.has(id))
701
+ seen.set(id, found);
702
+ }
703
+ return [...seen.values()];
704
+ }
705
+ /**
706
+ * What to tell the holder of a result whose verdict is `unverifiable`: how
707
+ * many signature checks could not be computed and under which algorithms,
708
+ * that nothing was found wrong and the refused signatures were never
709
+ * checked, that it is neither
710
+ * evidence of tampering nor a pass, and the remedy for each cause. Built from
711
+ * the same claims as the `CHAIN_UNSUPPORTED_ALGORITHM` detail lines. Show it
712
+ * only where the verdict is `unverifiable`: it says nothing was found wrong,
713
+ * which a `failed` result does not support.
714
+ */
715
+ export function unverifiableDetail(uncomputable) {
716
+ const { count, algorithms } = uncomputable;
717
+ const name = (a) => a.algorithm ?? 'an algorithm this build does not recognize';
718
+ const host = algorithms.filter((a) => a.cause === 'host');
719
+ const build = algorithms.filter((a) => a.cause === 'build');
720
+ const where = host.length > 0 && build.length > 0
721
+ ? 'on this host or by this verifier build'
722
+ : build.length > 0 ? 'by this verifier build' : host.length > 0 ? 'on this host' : 'on this host or by this verifier build';
723
+ const under = algorithms.length > 0 ? ` under ${listOf(algorithms.map(name))}` : '';
724
+ const parts = [`${count} signature check${count === 1 ? '' : 's'}${under} could not be computed ${where}.`];
725
+ for (const a of host) {
726
+ parts.push(`This verifier build supports ${name(a)}, but this HOST RUNTIME refused to compute it${runtimeRefusalCause(name(a))}`);
727
+ }
728
+ if (build.length > 0)
729
+ parts.push(`This verifier build cannot compute ${listOf(build.map(name))}.`);
730
+ const { consequences = [] } = uncomputable;
731
+ const refused = listOf(host.map(name)) || 'the algorithm';
732
+ if (uncomputable.assumed === 'data-and-key-statements') {
733
+ // No anchor this host computes: the keys here rest on key statements this
734
+ // host could not check, so the result reads the same for a forgery.
735
+ const anchors = uncomputable.anchorAlgorithms ?? [];
736
+ parts.push(anchors.length > 0
737
+ ? `The trust anchor given is ${listOf(anchors.map((a) => `an ${a} key`))}, which this host cannot use: the key statements that would link the keys here to it could not be checked, so no key was established on this host.`
738
+ : uncomputable.pinUnmet === true
739
+ ? 'The trust anchor given names no key in this input, so it anchored nothing, and no key was established on this host.'
740
+ : 'No trust anchor this host can use was given, so no key was established on this host.');
741
+ if (consequences.length > 0) {
742
+ parts.push(`The other findings listed (${listOf(consequences)}) rest on key statements this host could not check.`);
743
+ }
744
+ parts.push('No signature here was verified under an established key: the record is neither verified nor refuted, and this is not a pass.');
745
+ parts.push(`To verify it, pin the Server's current key of an algorithm this host computes (confirm it with the Server's operator), or re-run the verification on a host whose runtime computes ${refused}; the input is portable and the verification is offline.`);
746
+ if (build.length > 0)
747
+ parts.push('Upgrade the verifier to a build that computes it, and verify again.');
748
+ return parts.join(' ');
749
+ }
750
+ if (consequences.length > 0) {
751
+ parts.push(`The other findings listed (${listOf(consequences)}) follow from those checks: with them verified, nothing fails. They are listed, and they are not evidence of tampering.`);
752
+ }
753
+ const anchored = uncomputable.assumed === 'data' ? ' Every key a signature here was checked under was trusted through signatures this host computed; only signatures over data were left unchecked.' : '';
754
+ parts.push(`Nothing was found wrong, and the signatures this host refused were never checked, so the chain is neither verified nor refuted.${anchored} This is NOT tamper evidence, and it is not a pass.`);
755
+ if (host.length > 0)
756
+ parts.push(`Re-run the verification on a host whose runtime computes ${refused}; the input is portable and the verification is offline.`);
757
+ if (build.length > 0)
758
+ parts.push('Upgrade the verifier to a build that computes it, and verify again.');
759
+ if (algorithms.length === 0)
760
+ parts.push('Re-run the verification on a host whose runtime computes the algorithm, or upgrade the verifier or Node.js.');
761
+ return parts.join(' ');
762
+ }
763
+ /**
764
+ * The line a `failed` result shows for the signature checks it could not
765
+ * compute, beside the failure it names: how many, under which algorithms, and
766
+ * that they were not checked here. Empty when there were none. A `failed`
767
+ * result has a real failure, so this line never says nothing was found wrong.
768
+ */
769
+ export function uncomputableNote(uncomputable) {
770
+ const { count, algorithms } = uncomputable;
771
+ if (count === 0)
772
+ return '';
773
+ const name = (a) => a.algorithm ?? 'an algorithm this build does not recognize';
774
+ const under = algorithms.length > 0 ? ` under ${listOf(algorithms.map(name))}` : '';
775
+ const host = algorithms.some((a) => a.cause === 'host');
776
+ const build = algorithms.some((a) => a.cause === 'build');
777
+ const where = host && build ? 'on this host or by this verifier build' : build ? 'by this verifier build' : 'on this host';
778
+ const mlDsa = !isFipsActive() && algorithms.some((a) => a.cause === 'host' && a.algorithm?.startsWith('ML-DSA-') === true);
779
+ const upgrade = mlDsa
780
+ ? ` This Node.js runtime (${process.version}) does not compute ML-DSA; Node.js computes it from 24.6.0, so upgrade Node.js and verify again.`
781
+ : '';
782
+ return `Beside that, ${count} signature check${count === 1 ? '' : 's'}${under} could not be computed ${where} (CHAIN_UNSUPPORTED_ALGORITHM): not checked here, so neither verified nor refuted.${upgrade}`;
783
+ }
784
+ function listOf(items) {
785
+ if (items.length <= 1)
786
+ return items.join('');
787
+ return `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`;
334
788
  }
335
789
  /** Best-effort FIPS detection, used only to explain a failure, never to gate one. */
336
- function isFipsActive() {
790
+ export function isFipsActive() {
337
791
  try {
338
792
  return getFips() === 1;
339
793
  }
@@ -349,8 +803,9 @@ function isFipsActive() {
349
803
  * the upgrade-vs-forgery distinction use `resolveKeyAlgorithm` first, as
350
804
  * `verifyCoseSign1` does).
351
805
  *
352
- * ES256 mirrors how the Server verifies it: SHA-256 digest passed
353
- * positionally, `dsaEncoding: 'ieee-p1363'` (COSE raw r||s, 64 bytes). The
806
+ * ES256 and ES384 mirror how the Server verifies them: the SHA-256 or SHA-384
807
+ * digest passed positionally, `dsaEncoding: 'ieee-p1363'` (COSE raw r||s, 64
808
+ * or 96 bytes). The
354
809
  * Server normalizes to low-S at sign time but, like the Server's verifier,
355
810
  * high-S is accepted here: ECDSA malleability changes the envelope bytes,
356
811
  * which the hash-link layer already pins.
@@ -414,33 +869,37 @@ export function verifyCoseSign1(coseSign1, publicKeyBase64) {
414
869
  const parts = decodeCoseSign1(coseSign1);
415
870
  if (!parts)
416
871
  return 'decode-fail';
417
- const keyAlg = resolveKeyAlgorithm(publicKeyBase64);
418
872
  // A key that does not parse can verify nothing; preserve the historical
419
873
  // 'invalid' rather than misreporting garbage bytes as an algorithm gap.
420
874
  //
421
875
  // One exception, and it is deliberately narrow: bytes that DECLARE themselves
422
- // an Ed25519 key (by OID) on a host that cannot compute EdDSA. A FIPS-locked
423
- // runtime refuses such a key at LOAD, so "did not parse" there means "this
424
- // host will not touch it", not "someone forged it". Without this, the whole
425
- // runtime-capability gate below is unreachable on the one path it was
426
- // written for, and an intact chain still reads as tamper.
427
- if (keyAlg === 'unparseable') {
428
- return isRuntimeRefusedEd25519Key(publicKeyBase64) ? 'unsupported-key-algorithm' : 'invalid';
429
- }
876
+ // an Ed25519 or ML-DSA key (by structure) on a host that cannot compute it.
877
+ // Such a runtime refuses the key at LOAD, so "did not parse" there means
878
+ // "this host will not touch it", not "someone forged it", and the key is
879
+ // read as the algorithm it declares.
880
+ const keyAlg = resolveKeyAlgorithmOrHostRefused(publicKeyBase64);
881
+ if (keyAlg === 'unparseable')
882
+ return 'invalid';
430
883
  if (keyAlg === 'unrecognized')
431
884
  return 'unsupported-key-algorithm';
432
885
  const headerAlg = extractHeaderAlg(parts.protectedBstr);
433
886
  if (headerAlg === null || !keyAlg.coseAlgs.includes(headerAlg))
434
887
  return 'alg-mismatch';
435
- // Two independent reasons the signature cannot be checked: this build does
436
- // not implement the algorithm, or the host runtime refuses to compute it.
437
- // Both must read as "not verified", never as "did not verify".
438
- if (!keyAlg.verifiable || !runtimeCanCompute(keyAlg))
888
+ // This build does not implement the algorithm: not verified, never "did not verify".
889
+ if (!keyAlg.verifiable)
439
890
  return 'unsupported-key-algorithm';
440
- if (parts.signature.length === keyAlg.signatureLength &&
441
- parts.signature.every((b) => b === 0)) {
891
+ // Checks that need no computation run before the host's capability is
892
+ // asked, so they read the same on every host: an all-zero signature of the
893
+ // algorithm's length is the unsigned sentinel, and any other length cannot
894
+ // be a signature under this key.
895
+ const shape = signatureShape(keyAlg, parts.signature);
896
+ if (shape === 'zero')
442
897
  return 'unsigned';
443
- }
898
+ if (shape === 'wrong-length')
899
+ return 'invalid';
900
+ // The host runtime refuses to compute it: not verified, never "did not verify".
901
+ if (!runtimeCanCompute(keyAlg))
902
+ return 'unsupported-key-algorithm';
444
903
  const sigStructure = [
445
904
  SIG_STRUCTURE_CONTEXT,
446
905
  parts.protectedBstr,
@@ -451,7 +910,7 @@ export function verifyCoseSign1(coseSign1, publicKeyBase64) {
451
910
  return verifySignatureBytes(publicKeyBase64, toBeSigned, parts.signature) ? 'ok' : 'invalid';
452
911
  }
453
912
  /** Decode the protected header's `alg` (label 1); null when absent or not an int. */
454
- function extractHeaderAlg(protectedBstr) {
913
+ export function extractHeaderAlg(protectedBstr) {
455
914
  try {
456
915
  const ph = cborDecode(protectedBstr, { ...STRICT_CBOR_DECODE, useMaps: true });
457
916
  const alg = ph.get(COSE_HEADER_ALG);
@@ -655,43 +1114,132 @@ export function ed25519JwkToSpki(jwk) {
655
1114
  const raw = Buffer.from(jwk.x, 'base64url');
656
1115
  return Buffer.concat([ED25519_SPKI_PREFIX, raw]).toString('base64');
657
1116
  }
1117
+ /** SPKI DER prefix of an uncompressed P-384 point: SEQUENCE { SEQUENCE { id-ecPublicKey, secp384r1 }, BIT STRING { 04 || x || y } }. */
1118
+ const P384_SPKI_PREFIX = Buffer.from('3076301006072a8648ce3d020106052b8104002203620004', 'hex');
1119
+ const P384_COORDINATE_BYTES = 48;
1120
+ /** The bytes of a base64url member in its one spelling at `length` bytes, else null. */
1121
+ function base64urlMember(value, length) {
1122
+ if (typeof value !== 'string')
1123
+ return null;
1124
+ const bytes = Buffer.from(value, 'base64url');
1125
+ return bytes.length === length && bytes.toString('base64url') === value ? bytes : null;
1126
+ }
1127
+ /** An agent JWK read into the members its thumbprint hashes and its SPKI DER, or null. */
1128
+ function readAgentJwk(jwk) {
1129
+ if (jwk === null || typeof jwk !== 'object' || Array.isArray(jwk))
1130
+ return null;
1131
+ const { kty, crv, alg, x, y, pub } = jwk;
1132
+ if (kty === 'OKP') {
1133
+ const spki = ed25519JwkToSpki(jwk);
1134
+ return spki === null ? null : { members: { crv: 'Ed25519', kty, x: x }, spki: Buffer.from(spki, 'base64') };
1135
+ }
1136
+ if (kty === 'AKP') {
1137
+ if (alg !== 'ML-DSA-87' && alg !== 'ML-DSA-65')
1138
+ return null;
1139
+ const set = ML_DSA_SPKI.find((entry) => entry.table === alg.toLowerCase());
1140
+ if (set === undefined)
1141
+ return null;
1142
+ const raw = base64urlMember(pub, set.length - set.prefix.length);
1143
+ return raw === null ? null : { members: { alg, kty, pub: pub }, spki: Buffer.concat([set.prefix, raw]) };
1144
+ }
1145
+ if (kty === 'EC') {
1146
+ if (crv !== 'P-384')
1147
+ return null;
1148
+ const xBytes = base64urlMember(x, P384_COORDINATE_BYTES);
1149
+ const yBytes = base64urlMember(y, P384_COORDINATE_BYTES);
1150
+ if (xBytes === null || yBytes === null)
1151
+ return null;
1152
+ return { members: { crv, kty, x: x, y: y }, spki: Buffer.concat([P384_SPKI_PREFIX, xBytes, yBytes]) };
1153
+ }
1154
+ return null;
1155
+ }
1156
+ /**
1157
+ * JWK thumbprint of an agent cert key in the Server's `sha256:<hex>` form, or
1158
+ * null when the value is not one (see {@link AgentPublicKeyJwk}). The members
1159
+ * hashed are the required ones in lexicographic order: `alg`, `kty`, `pub`
1160
+ * for an AKP key (RFC 9964), `crv`, `kty`, `x`, `y` for P-384 and `crv`,
1161
+ * `kty`, `x` for Ed25519 (RFC 7638). Other members (`use`, `kid`) are not
1162
+ * hashed.
1163
+ */
1164
+ export function agentJwkThumbprint(jwk) {
1165
+ const read = readAgentJwk(jwk);
1166
+ // Built in the order above; JSON.stringify keeps insertion order.
1167
+ return read === null ? null : `sha256:${sha256HexString(JSON.stringify(read.members))}`;
1168
+ }
1169
+ /** SPKI DER (base64) for an agent cert key, or null when the value is not one. */
1170
+ export function agentJwkToSpki(jwk) {
1171
+ return readAgentJwk(jwk)?.spki.toString('base64') ?? null;
1172
+ }
658
1173
  const CONTENT_HASH_PATTERN = /^sha256:([0-9a-f]{64})$/;
659
1174
  const STANDARD_BASE64_64_BYTES = /^[A-Za-z0-9+/]{86}(==)?$/;
1175
+ /** The `agent_signature.alg` label the Server seals for a cert key of each algorithm. */
1176
+ const AGENT_SIGNATURE_ALG = {
1177
+ 'ML-DSA-87': 'ML-DSA-87',
1178
+ 'ML-DSA-65': 'ML-DSA-65',
1179
+ ES384: 'ES384',
1180
+ Ed25519: 'EdDSA',
1181
+ };
660
1182
  /**
661
- * Verify a sealed agent signature against the cert's Ed25519 key.
1183
+ * The algorithm an agent cert key signs with, or null when the key is not an
1184
+ * agent key. Read from the key's structure first, so an ML-DSA or Ed25519 key
1185
+ * reads as itself on a host that cannot load it.
1186
+ */
1187
+ export function agentKeyAlgorithm(spkiBase64) {
1188
+ const alg = declaredKeyAlgorithm(Buffer.from(spkiBase64, 'base64')) ?? resolveKeyAlgorithm(spkiBase64);
1189
+ return typeof alg === 'object' && alg.name in AGENT_SIGNATURE_ALG ? alg : null;
1190
+ }
1191
+ /**
1192
+ * Verify a sealed agent signature against the cert's key. The algorithm is
1193
+ * the key's own: ML-DSA-87 or ML-DSA-65 (pure, empty context), ES384 (the
1194
+ * 96-byte `r||s`, either S half), or Ed25519 on an entry sealed before
1195
+ * Server 4.0.0.
662
1196
  *
663
1197
  * - `ok`: the signature verifies over `AGENT_SIGNATURE_CONTEXT + <hex>`.
664
- * - `invalid`: well formed, does not verify under this key.
665
- * - `malformed`: a shape the Server never writes (alg other than EdDSA, a
666
- * content hash not `sha256:<hex64>`, a signature that is not 64 bytes of
667
- * standard base64). Nothing can verify it, which the Server also treats as
668
- * a break.
669
- * - `unsupported`: this host cannot compute Ed25519 (an active OpenSSL FIPS
670
- * provider). NOT verified and NOT tamper evidence.
1198
+ * - `invalid`: well formed, and does not verify under this key, or the sealed
1199
+ * `alg` names another algorithm than the key's.
1200
+ * - `malformed`: a shape the Server never writes (an `alg` it does not seal,
1201
+ * a content hash not `sha256:<hex64>`, a signature that is not standard
1202
+ * base64 at the algorithm's length). Nothing can verify it, which the Server
1203
+ * also treats as a break.
1204
+ * - `unsupported`: this host cannot compute the key's algorithm. NOT verified
1205
+ * and NOT tamper evidence.
671
1206
  *
672
1207
  * What it proves: the holder of the cert's private key signed that content
673
1208
  * hash. It does not re-hash a request body; the export carries the hash, not
674
1209
  * the body.
675
1210
  */
676
1211
  export function verifyAgentSignature(spkiBase64, claim) {
677
- if (claim.alg !== 'EdDSA')
1212
+ if (typeof claim.alg !== 'string' || !Object.values(AGENT_SIGNATURE_ALG).includes(claim.alg))
678
1213
  return 'malformed';
679
1214
  if (typeof claim.contentHash !== 'string')
680
1215
  return 'malformed';
681
1216
  const hashMatch = CONTENT_HASH_PATTERN.exec(claim.contentHash);
682
1217
  if (!hashMatch)
683
1218
  return 'malformed';
684
- if (typeof claim.signature !== 'string' || !STANDARD_BASE64_64_BYTES.test(claim.signature)) {
1219
+ const keyAlg = agentKeyAlgorithm(spkiBase64);
1220
+ if (keyAlg === null)
1221
+ return 'malformed';
1222
+ // The label is checked against the key, never used to choose the algorithm.
1223
+ if (AGENT_SIGNATURE_ALG[keyAlg.name] !== claim.alg)
1224
+ return 'invalid';
1225
+ if (typeof claim.signature !== 'string')
685
1226
  return 'malformed';
686
- }
687
1227
  const sigBytes = Buffer.from(claim.signature, 'base64');
688
- if (sigBytes.length !== 64)
1228
+ if (sigBytes.length !== keyAlg.signatureLength)
689
1229
  return 'malformed';
690
- const ed25519 = algorithmByName('Ed25519');
691
- if (ed25519 === null || !runtimeCanCompute(ed25519))
1230
+ // Ed25519 signatures were sealed with or without padding; the rest are padded.
1231
+ const spelled = keyAlg.name === 'Ed25519'
1232
+ ? STANDARD_BASE64_64_BYTES.test(claim.signature)
1233
+ : sigBytes.toString('base64') === claim.signature;
1234
+ if (!spelled)
1235
+ return 'malformed';
1236
+ // An all-zero signature verifies under no key, on any host.
1237
+ if (signatureShape(keyAlg, sigBytes) === 'zero')
1238
+ return 'invalid';
1239
+ if (!runtimeCanCompute(keyAlg))
692
1240
  return 'unsupported';
693
1241
  const input = Buffer.from(`${AGENT_SIGNATURE_CONTEXT}${hashMatch[1]}`, 'utf8');
694
- return verifyEd25519Bytes(spkiBase64, input, sigBytes) ? 'ok' : 'invalid';
1242
+ return verifySignatureBytes(spkiBase64, input, sigBytes) ? 'ok' : 'invalid';
695
1243
  }
696
1244
  // --- in-toto v1 predicate extraction + binding-integrity projection ---
697
1245
  /**
@@ -1140,3 +1688,12 @@ export function verifyOrgReadInclusion(leafHashHex, leafIndex, treeSize, pathHex
1140
1688
  }
1141
1689
  return verifyRfc9162Inclusion(leaf, leafIndex, treeSize, path, root);
1142
1690
  }
1691
+ /**
1692
+ * A run of chain positions in prose: `entry 4 was` for one position, `entries
1693
+ * 4 through 9 were` for more. `verb` is the plural form (`were`, `are`).
1694
+ */
1695
+ export function entryRun(from, through, verb) {
1696
+ if (from === through)
1697
+ return `entry ${from} ${verb === 'were' ? 'was' : 'is'}`;
1698
+ return `entries ${from} through ${through} ${verb}`;
1699
+ }