@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
@@ -1,22 +1,26 @@
1
1
  /**
2
2
  * Self-contained crypto + canonicalization primitives.
3
3
  *
4
- * Mirrors the AGLedger engine-side implementations:
5
- * - COSE_Sign1 verify (RFC 9052 §4.4): audit-vault/encoders/cose-sign1.ts
4
+ * Mirrors what the AGLedger Server does when it signs and chains entries:
5
+ * - COSE_Sign1 verify (RFC 9052 §4.4), the envelope the Server signs
6
6
  * - RFC 9162 §2.1 Merkle tree, for SCITT Receipts and the org_admin_reads
7
- * log alike: audit-vault/merkle-rfc9162.ts
7
+ * log alike
8
8
  *
9
- * Re-implemented here (not imported from any engine/SDK code) so the verifier
10
- * has zero engine dependency, the load-bearing property of an offline
11
- * auditor: the engine could be compromised and this still verifies correctly.
9
+ * Re-implemented here (not imported from any Server or SDK code) so the
10
+ * verifier has zero Server dependency, the load-bearing property of an offline
11
+ * auditor: it runs no Server code, so a Server that holds no key you
12
+ * trust cannot make it return a `trusted` verdict: that needs `trustAnchors`
13
+ * linking the signing keys to a key you pinned.
12
14
  * The only runtime dependency is `cborg`, a general-purpose CBOR library (not
13
15
  * AGLedger code), and Node's built-in `crypto`. No network, no filesystem.
14
16
  *
15
- * If the engine-side primitives ever change shape, both implementations must be
16
- * updated together; the conformance corpus (real engine output) is the
17
+ * If the Server-side primitives ever change shape, both implementations must be
18
+ * updated together; the conformance corpus (real Server output) is the
17
19
  * regression net that catches divergence.
18
20
  */
19
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';
23
+ import { STRICT_CBOR_DECODE } from './cbor-strict.js';
20
24
  import { decode as cborDecode, encode as cborEncode, rfc8949EncodeOptions } from 'cborg';
21
25
  // --- SHA-256 ---
22
26
  /** sha256 over arbitrary bytes -> lowercase hex. */
@@ -38,9 +42,17 @@ export function sha256HexString(s) {
38
42
  const KEY_ALGORITHMS = {
39
43
  ed25519: Object.freeze({ name: 'Ed25519', coseAlgs: Object.freeze([-8, -19]), signatureLength: 64, verifiable: true, nodeKeyType: 'ed25519', namedCurve: null, digest: null, dsaEncoding: null }),
40
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' }),
41
- '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' }),
42
48
  'ec:secp521r1': Object.freeze({ name: 'ES512', coseAlgs: Object.freeze([-36]), signatureLength: 132, verifiable: false, nodeKeyType: 'ec', namedCurve: 'secp521r1', digest: null, dsaEncoding: null }),
43
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 }),
44
56
  };
45
57
  /**
46
58
  * Look up a table entry by its registry name (`Ed25519`, `ES256`, ...).
@@ -84,20 +96,89 @@ export function looksLikeEd25519Key(spkiDer) {
84
96
  return false;
85
97
  return Buffer.from(spkiDer).subarray(0, ED25519_SPKI_PREFIX.length).equals(ED25519_SPKI_PREFIX);
86
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
+ }
87
170
  /**
88
171
  * The narrow case where a key that would not LOAD must not read as tamper: the
89
- * 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.
90
173
  *
91
174
  * Judged from the OID rather than from capability alone, so genuinely tampered
92
175
  * key material still reads as tamper on every host, and both verifiers agree on
93
176
  * garbage bytes. On a host that CAN compute Ed25519 this is always false, so an
94
177
  * unloadable key there stays a signature failure exactly as before.
95
178
  */
96
- function isRuntimeRefusedEd25519Key(publicKeyBase64) {
97
- const ed = KEY_ALGORITHMS['ed25519'];
98
- if (!ed)
99
- return false;
100
- 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;
101
182
  }
102
183
  /** Small memo: a registry holds a handful of keys but chains hold millions of entries. */
103
184
  const KEY_ALG_CACHE = new Map();
@@ -113,18 +194,70 @@ const KEY_ALG_CACHE_MAX = 256;
113
194
  * - `'unparseable'` when the bytes are not a public key at all.
114
195
  */
115
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) {
116
235
  const cached = KEY_ALG_CACHE.get(publicKeyBase64);
117
236
  if (cached !== undefined)
118
237
  return cached;
119
238
  let resolved;
120
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');
121
246
  const keyObj = createPublicKey({
122
- key: Buffer.from(publicKeyBase64, 'base64'),
247
+ key: der,
123
248
  format: 'der',
124
249
  type: 'spki',
125
250
  });
126
251
  const type = keyObj.asymmetricKeyType;
127
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');
128
261
  resolved = KEY_ALGORITHMS[tableKey] ?? 'unrecognized';
129
262
  }
130
263
  catch {
@@ -139,11 +272,11 @@ export function resolveKeyAlgorithm(publicKeyBase64) {
139
272
  /**
140
273
  * Verify an Ed25519 signature over raw bytes.
141
274
  * `publicKeyBase64` is the SPKI DER public key, base64-encoded
142
- * (matches the engine's vault_signing_keys.public_key column).
275
+ * (the shape the Server's key registry publishes).
143
276
  *
144
277
  * Refuses non-Ed25519 keys. Node's `verify(null, ...)` silently falls back to
145
278
  * ECDSA/SHA-256 for EC keys, which would accept a signature no conformant
146
- * EdDSA verifier accepts (the engine guards the signing side the same way),
279
+ * EdDSA verifier accepts (the Server guards the signing side the same way),
147
280
  * so the key type is asserted before any crypto runs.
148
281
  *
149
282
  * CAUTION for direct callers: as with `verifySignatureBytes`, `false` conflates
@@ -152,6 +285,8 @@ export function resolveKeyAlgorithm(publicKeyBase64) {
152
285
  */
153
286
  export function verifyEd25519Bytes(publicKeyBase64, input, signature) {
154
287
  try {
288
+ if (!isOneDerElement(Buffer.from(publicKeyBase64, 'base64')))
289
+ return false;
155
290
  const publicKeyObj = createPublicKey({
156
291
  key: Buffer.from(publicKeyBase64, 'base64'),
157
292
  format: 'der',
@@ -165,7 +300,7 @@ export function verifyEd25519Bytes(publicKeyBase64, input, signature) {
165
300
  return false;
166
301
  }
167
302
  }
168
- // --- Key-dispatched signature verification (Ed25519 + ES256) ---
303
+ // --- Key-dispatched signature verification ---
169
304
  /**
170
305
  * Perform the actual verify() call for a resolved algorithm, WITHOUT catching.
171
306
  *
@@ -175,13 +310,21 @@ export function verifyEd25519Bytes(publicKeyBase64, input, signature) {
175
310
  * `runtimeCanCompute`). Collapsing those two into one boolean is what made a
176
311
  * FIPS-locked host report an intact Ed25519 chain as forged.
177
312
  *
178
- * ES256 mirrors the engine's `verifyWithAlgorithm`: SHA-256 digest passed
179
- * positionally, `dsaEncoding: 'ieee-p1363'` (COSE raw r||s, 64 bytes). The
180
- * engine normalizes to low-S at sign time but, like the engine's verifier,
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
316
+ * Server normalizes to low-S at sign time but, like the Server's verifier,
181
317
  * high-S is accepted here: ECDSA malleability changes the envelope bytes,
182
318
  * which the hash-link layer already pins.
183
319
  */
184
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;
185
328
  const keyObj = createPublicKey({
186
329
  key: Buffer.from(publicKeyBase64, 'base64'),
187
330
  format: 'der',
@@ -242,6 +385,16 @@ const ALGORITHM_KATS = new Map([
242
385
  signatureBase64: 'eQ8fKfXT5GuBUz7gueqcq9hTmzrJlSuaoF/ukCPtKJsxqrynVgIREn/XMPKbdSHp7wMyFOEAgmbVfoMDnR5x/Q==',
243
386
  },
244
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],
245
398
  ]);
246
399
  // Every algorithm this build claims to compute must carry a vector proving the
247
400
  // host can compute it. Failing at import is the point: a packaging slip here
@@ -264,6 +417,42 @@ const RUNTIME_SUPPORT_CACHE = new Map();
264
417
  * as tamper evidence.
265
418
  */
266
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) {
267
456
  if (!keyAlg.verifiable)
268
457
  return false;
269
458
  const kat = ALGORITHM_KATS.get(keyAlg);
@@ -298,9 +487,9 @@ export function describeUnsupportedAlgorithm(publicKeyBase64) {
298
487
  // exists for, the key never loaded, so there is no algorithm to resolve and
299
488
  // the generic "upgrade the verifier" text would send an auditor after a build
300
489
  // that is fine. Answer from the OID instead.
301
- if (typeof keyAlg !== 'object' && isRuntimeRefusedEd25519Key(publicKeyBase64)) {
302
- return describeRuntimeRefusal(KEY_ALGORITHMS['ed25519']);
303
- }
490
+ const refused = typeof keyAlg !== 'object' ? runtimeRefusedKey(publicKeyBase64) : null;
491
+ if (refused)
492
+ return describeRuntimeRefusal(refused);
304
493
  if (typeof keyAlg !== 'object') {
305
494
  return 'commits to an algorithm this verifier build cannot compute. The chain is NOT verified; upgrade the verifier.';
306
495
  }
@@ -318,19 +507,287 @@ export function describeUnsupportedAlgorithm(publicKeyBase64) {
318
507
  }
319
508
  /** The host-refused-this-algorithm sentence, shared by both ways of reaching it. */
320
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) {
321
544
  // The FIPS clause names a missing EdDSA implementation, so it belongs only
322
545
  // to EdDSA. A FIPS provider carries ECDSA P-256 quite happily, and telling
323
546
  // an ES256 auditor that EdDSA is absent sends them somewhere useless.
324
- const cause = isFipsActive() && keyAlg.name === 'Ed25519'
547
+ return isFipsActive() && name === 'Ed25519'
325
548
  ? ' because the OpenSSL FIPS provider is active, and it carries no EdDSA.'
326
- : '.';
327
- return (`commits to ${keyAlg.name}, which this verifier build supports but this HOST RUNTIME refused to compute` +
328
- cause +
329
- ' This is NOT tamper evidence: the signature was never checked, so the chain is neither verified nor refuted.' +
330
- ' 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)}`;
331
788
  }
332
789
  /** Best-effort FIPS detection, used only to explain a failure, never to gate one. */
333
- function isFipsActive() {
790
+ export function isFipsActive() {
334
791
  try {
335
792
  return getFips() === 1;
336
793
  }
@@ -346,9 +803,10 @@ function isFipsActive() {
346
803
  * the upgrade-vs-forgery distinction use `resolveKeyAlgorithm` first, as
347
804
  * `verifyCoseSign1` does).
348
805
  *
349
- * ES256 mirrors the engine's `verifyWithAlgorithm`: SHA-256 digest passed
350
- * positionally, `dsaEncoding: 'ieee-p1363'` (COSE raw r||s, 64 bytes). The
351
- * engine normalizes to low-S at sign time but, like the engine's verifier,
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
809
+ * Server normalizes to low-S at sign time but, like the Server's verifier,
352
810
  * high-S is accepted here: ECDSA malleability changes the envelope bytes,
353
811
  * which the hash-link layer already pins.
354
812
  *
@@ -379,15 +837,16 @@ const SIG_STRUCTURE_CONTEXT = 'Signature1';
379
837
  const COSE_HEADER_ALG = 1;
380
838
  const COSE_HEADER_KID = 4;
381
839
  export function decodeCoseSign1(bytes) {
382
- // Tag 18 is required (short-form 0xd2, matching the engine's encoder).
840
+ // Tag 18 is required (short-form 0xd2, matching the Server's encoder).
383
841
  // cborg's tag handler unwraps tag 18 but also returns an UNTAGGED 4-element
384
- // array verbatim, and the engine rejects untagged envelopes: producer and
842
+ // array verbatim, and the Server rejects untagged envelopes: producer and
385
843
  // offline verifier must agree on what a COSE_Sign1 is, so gate on the
386
- // leading byte the same way the engine's decoder does.
844
+ // leading byte the same way the Server's decoder does.
387
845
  if (bytes.length === 0 || bytes[0] !== COSE_SIGN1_TAG_PREFIX)
388
846
  return null;
389
847
  try {
390
848
  const decoded = cborDecode(bytes, {
849
+ ...STRICT_CBOR_DECODE,
391
850
  useMaps: true,
392
851
  tags: { [COSE_SIGN1_TAG]: (control) => control() },
393
852
  });
@@ -410,33 +869,37 @@ export function verifyCoseSign1(coseSign1, publicKeyBase64) {
410
869
  const parts = decodeCoseSign1(coseSign1);
411
870
  if (!parts)
412
871
  return 'decode-fail';
413
- const keyAlg = resolveKeyAlgorithm(publicKeyBase64);
414
872
  // A key that does not parse can verify nothing; preserve the historical
415
873
  // 'invalid' rather than misreporting garbage bytes as an algorithm gap.
416
874
  //
417
875
  // One exception, and it is deliberately narrow: bytes that DECLARE themselves
418
- // an Ed25519 key (by OID) on a host that cannot compute EdDSA. A FIPS-locked
419
- // runtime refuses such a key at LOAD, so "did not parse" there means "this
420
- // host will not touch it", not "someone forged it". Without this, the whole
421
- // runtime-capability gate below is unreachable on the one path it was
422
- // written for, and an intact chain still reads as tamper.
423
- if (keyAlg === 'unparseable') {
424
- return isRuntimeRefusedEd25519Key(publicKeyBase64) ? 'unsupported-key-algorithm' : 'invalid';
425
- }
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';
426
883
  if (keyAlg === 'unrecognized')
427
884
  return 'unsupported-key-algorithm';
428
885
  const headerAlg = extractHeaderAlg(parts.protectedBstr);
429
886
  if (headerAlg === null || !keyAlg.coseAlgs.includes(headerAlg))
430
887
  return 'alg-mismatch';
431
- // Two independent reasons the signature cannot be checked: this build does
432
- // not implement the algorithm, or the host runtime refuses to compute it.
433
- // Both must read as "not verified", never as "did not verify".
434
- if (!keyAlg.verifiable || !runtimeCanCompute(keyAlg))
888
+ // This build does not implement the algorithm: not verified, never "did not verify".
889
+ if (!keyAlg.verifiable)
435
890
  return 'unsupported-key-algorithm';
436
- if (parts.signature.length === keyAlg.signatureLength &&
437
- 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')
438
897
  return 'unsigned';
439
- }
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';
440
903
  const sigStructure = [
441
904
  SIG_STRUCTURE_CONTEXT,
442
905
  parts.protectedBstr,
@@ -447,9 +910,9 @@ export function verifyCoseSign1(coseSign1, publicKeyBase64) {
447
910
  return verifySignatureBytes(publicKeyBase64, toBeSigned, parts.signature) ? 'ok' : 'invalid';
448
911
  }
449
912
  /** Decode the protected header's `alg` (label 1); null when absent or not an int. */
450
- function extractHeaderAlg(protectedBstr) {
913
+ export function extractHeaderAlg(protectedBstr) {
451
914
  try {
452
- const ph = cborDecode(protectedBstr, { useMaps: true });
915
+ const ph = cborDecode(protectedBstr, { ...STRICT_CBOR_DECODE, useMaps: true });
453
916
  const alg = ph.get(COSE_HEADER_ALG);
454
917
  if (typeof alg === 'number' && Number.isInteger(alg))
455
918
  return alg;
@@ -463,14 +926,14 @@ function extractHeaderAlg(protectedBstr) {
463
926
  }
464
927
  /**
465
928
  * Extract the signature-covered `kid` (protected header label 4) as lowercase
466
- * hex, matching the engine's `vault_signing_keys.key_id` shape. Returns null
929
+ * hex, matching the key id shape the Server's key registry uses. Returns null
467
930
  * when absent or malformed. The caller cross-checks it against the row's
468
931
  * `signingKeyId` column: the column is a denormalized convenience, the kid is
469
- * signed, so a rewritten column surfaces as drift (engine mirror: signing_key_drift).
932
+ * signed, so a rewritten column surfaces as drift (Server mirror: signing_key_drift).
470
933
  */
471
934
  export function extractKid(protectedBstr) {
472
935
  try {
473
- const ph = cborDecode(protectedBstr, { useMaps: true });
936
+ const ph = cborDecode(protectedBstr, { ...STRICT_CBOR_DECODE, useMaps: true });
474
937
  const kid = ph.get(COSE_HEADER_KID);
475
938
  if (!(kid instanceof Uint8Array))
476
939
  return null;
@@ -485,7 +948,7 @@ const CHAIN_SUBLABEL_POSITION = 1;
485
948
  const CHAIN_SUBLABEL_PREVIOUS_HASH = 2;
486
949
  export function extractChainClaim(protectedBstr) {
487
950
  try {
488
- const ph = cborDecode(protectedBstr, { useMaps: true });
951
+ const ph = cborDecode(protectedBstr, { ...STRICT_CBOR_DECODE, useMaps: true });
489
952
  const chain = ph.get(AGLEDGER_LABEL_CHAIN);
490
953
  if (!(chain instanceof Map))
491
954
  return null;
@@ -520,7 +983,7 @@ function bytesToUuid(bytes) {
520
983
  }
521
984
  export function extractActorClaim(protectedBstr) {
522
985
  try {
523
- const ph = cborDecode(protectedBstr, { useMaps: true });
986
+ const ph = cborDecode(protectedBstr, { ...STRICT_CBOR_DECODE, useMaps: true });
524
987
  const cwt = ph.get(COSE_HEADER_CWT_CLAIMS);
525
988
  if (!(cwt instanceof Map))
526
989
  return null;
@@ -553,7 +1016,7 @@ const TRACEPARENT_REGEX = /^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
553
1016
  */
554
1017
  export function extractOnBehalfOfClaim(payloadBstr) {
555
1018
  try {
556
- const stmt = cborDecode(payloadBstr, { useMaps: false });
1019
+ const stmt = cborDecode(payloadBstr, { ...STRICT_CBOR_DECODE, useMaps: false });
557
1020
  const predicate = stmt['predicate'];
558
1021
  if (predicate === null || typeof predicate !== 'object' || Array.isArray(predicate)) {
559
1022
  return null;
@@ -577,7 +1040,7 @@ export function extractOnBehalfOfClaim(payloadBstr) {
577
1040
  */
578
1041
  export function extractTraceparentClaim(payloadBstr) {
579
1042
  try {
580
- const stmt = cborDecode(payloadBstr, { useMaps: false });
1043
+ const stmt = cborDecode(payloadBstr, { ...STRICT_CBOR_DECODE, useMaps: false });
581
1044
  const predicate = stmt['predicate'];
582
1045
  if (predicate === null || typeof predicate !== 'object' || Array.isArray(predicate)) {
583
1046
  return null;
@@ -593,7 +1056,7 @@ export function extractTraceparentClaim(payloadBstr) {
593
1056
  }
594
1057
  // --- Agent signature (predicate.on_behalf_of.agent_signature) ---
595
1058
  /**
596
- * Domain-separation prefix the engine applies before verifying an agent's
1059
+ * Domain-separation prefix the Server applies before verifying an agent's
597
1060
  * `X-Agent-Signature` at intake: the agent signs the UTF-8 bytes of this
598
1061
  * prefix followed by the lowercase hex sha256 of the raw request body (the
599
1062
  * hex string, not the digest bytes). Distinct from the cert proof-of-possession
@@ -628,10 +1091,10 @@ export function extractAgentSignatureClaim(payloadBstr) {
628
1091
  }
629
1092
  const BASE64URL_32_BYTES = /^[A-Za-z0-9_-]{43}$/;
630
1093
  /**
631
- * RFC 7638 thumbprint of an Ed25519 JWK in the engine's `sha256:<hex>` form,
1094
+ * RFC 7638 thumbprint of an Ed25519 JWK in the Server's `sha256:<hex>` form,
632
1095
  * or null when the value is not an Ed25519 public-key JWK. The members are
633
1096
  * hashed in the RFC's lexicographic order (`crv`, `kty`, `x`), which is what
634
- * the engine's thumbprint function produces for an OKP key.
1097
+ * the Server's thumbprint function produces for an OKP key.
635
1098
  */
636
1099
  export function ed25519JwkThumbprint(jwk) {
637
1100
  if (jwk === null || typeof jwk !== 'object' || Array.isArray(jwk))
@@ -651,56 +1114,145 @@ export function ed25519JwkToSpki(jwk) {
651
1114
  const raw = Buffer.from(jwk.x, 'base64url');
652
1115
  return Buffer.concat([ED25519_SPKI_PREFIX, raw]).toString('base64');
653
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
+ }
654
1173
  const CONTENT_HASH_PATTERN = /^sha256:([0-9a-f]{64})$/;
655
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
+ };
1182
+ /**
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
+ }
656
1191
  /**
657
- * Verify a sealed agent signature against the cert's Ed25519 key.
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.
658
1196
  *
659
1197
  * - `ok`: the signature verifies over `AGENT_SIGNATURE_CONTEXT + <hex>`.
660
- * - `invalid`: well formed, does not verify under this key.
661
- * - `malformed`: a shape the engine never writes (alg other than EdDSA, a
662
- * content hash not `sha256:<hex64>`, a signature that is not 64 bytes of
663
- * standard base64). Nothing can verify it, which the engine also treats as
664
- * a break.
665
- * - `unsupported`: this host cannot compute Ed25519 (an active OpenSSL FIPS
666
- * 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.
667
1206
  *
668
1207
  * What it proves: the holder of the cert's private key signed that content
669
1208
  * hash. It does not re-hash a request body; the export carries the hash, not
670
1209
  * the body.
671
1210
  */
672
1211
  export function verifyAgentSignature(spkiBase64, claim) {
673
- if (claim.alg !== 'EdDSA')
1212
+ if (typeof claim.alg !== 'string' || !Object.values(AGENT_SIGNATURE_ALG).includes(claim.alg))
674
1213
  return 'malformed';
675
1214
  if (typeof claim.contentHash !== 'string')
676
1215
  return 'malformed';
677
1216
  const hashMatch = CONTENT_HASH_PATTERN.exec(claim.contentHash);
678
1217
  if (!hashMatch)
679
1218
  return 'malformed';
680
- 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')
681
1226
  return 'malformed';
682
- }
683
1227
  const sigBytes = Buffer.from(claim.signature, 'base64');
684
- if (sigBytes.length !== 64)
1228
+ if (sigBytes.length !== keyAlg.signatureLength)
1229
+ return 'malformed';
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)
685
1235
  return 'malformed';
686
- const ed25519 = algorithmByName('Ed25519');
687
- if (ed25519 === null || !runtimeCanCompute(ed25519))
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))
688
1240
  return 'unsupported';
689
1241
  const input = Buffer.from(`${AGENT_SIGNATURE_CONTEXT}${hashMatch[1]}`, 'utf8');
690
- return verifyEd25519Bytes(spkiBase64, input, sigBytes) ? 'ok' : 'invalid';
1242
+ return verifySignatureBytes(spkiBase64, input, sigBytes) ? 'ok' : 'invalid';
691
1243
  }
692
1244
  // --- in-toto v1 predicate extraction + binding-integrity projection ---
693
1245
  /**
694
1246
  * Decode the predicate object from a COSE_Sign1 payload bstr. The payload IS
695
1247
  * the in-toto v1 Statement; the predicate body lives at `payload.predicate`.
696
1248
  * Returns null on any decode failure. Used by the binding-integrity check; the
697
- * row's denormalised `payload` jsonb is a convenience view projected from this
1249
+ * entry's readable `payload` is a convenience view projected from this
698
1250
  * predicate at write time; if the view was altered after signing,
699
1251
  * `buildPredicateForRow(...) !== decodePredicate(...)`.
700
1252
  */
701
1253
  export function decodePredicate(payloadBstr) {
702
1254
  try {
703
- const stmt = cborDecode(payloadBstr, { useMaps: false });
1255
+ const stmt = cborDecode(payloadBstr, { ...STRICT_CBOR_DECODE, useMaps: false });
704
1256
  const predicate = stmt['predicate'];
705
1257
  if (predicate === null || typeof predicate !== 'object' || Array.isArray(predicate)) {
706
1258
  return null;
@@ -731,8 +1283,7 @@ const RECORD_STATE_RESERVED_KEYS = new Set([
731
1283
  ]);
732
1284
  /**
733
1285
  * Re-project (record_id, entry_type, payload) -> predicate body using the SAME
734
- * logic the engine uses at write time (engine-side: audit-vault/
735
- * build-vault-claim.ts). This is the verifier-side mirror.
1286
+ * logic the Server uses at write time. This is the verifier-side mirror.
736
1287
  *
737
1288
  * Returns null when the row's payload is structurally insufficient (e.g.
738
1289
  * SCHEMA_REGISTERED missing manifestDigest) or is not a JSON object at all (a
@@ -858,7 +1409,7 @@ export function deepEqual(a, b) {
858
1409
  /**
859
1410
  * Strip envelope-level sibling fields (`on_behalf_of`, `traceparent`) from a
860
1411
  * decoded predicate. They ride alongside per-kind predicate fields on the wire
861
- * but the engine's `buildPredicateOnly` (and our `buildPredicateForRow`
1412
+ * but the Server's own predicate builder (and our `buildPredicateForRow`
862
1413
  * mirror) exclude them from the rebuilt predicate. Stripping here makes the
863
1414
  * two shapes deep-equalable; envelope-level integrity is covered by the
864
1415
  * signature and the OIDC-actor cross-check.
@@ -876,32 +1427,43 @@ export function stripEnvelopeExtensions(predicate) {
876
1427
  * Whether the envelope extensions a row's payload carries are the ones the
877
1428
  * entry signed. When a writer puts `on_behalf_of` (an object) or
878
1429
  * `traceparent` (a W3C v00 string; any other value is dropped) at the top
879
- * level of the row payload, the engine lifts it into `predicate.on_behalf_of`
1430
+ * level of the row payload, the Server lifts it into `predicate.on_behalf_of`
880
1431
  * / `predicate.traceparent`, so a row copy must equal the signed value. The
881
1432
  * row copy is what a reader of an export or dump sees, and
882
1433
  * {@link stripEnvelopeExtensions} takes both sides out of the predicate
883
1434
  * comparison, so without this check a rewritten or added row copy would still
884
1435
  * verify.
885
1436
  *
886
- * Anything else under those keys is ignored, as the engine ignores it: it
1437
+ * Anything else under those keys is ignored, as the Server ignores it: it
887
1438
  * lifts only an object `on_behalf_of` and a v00 `traceparent`, so a genuine
888
1439
  * older row holding another shape signed nothing for it.
889
1440
  *
890
- * A row without them is not a mismatch: the engine also signs an
891
- * `on_behalf_of` built from the request's authentication rather than from the
892
- * payload, and that one never reaches the row payload. Its identity is held to
893
- * the row's actor columns by the OIDC-actor check instead.
1441
+ * `projected` says whether the payload is one the Server fills from the
1442
+ * signed predicate. An export entry's is: the Server writes every
1443
+ * `on_behalf_of` and v00 `traceparent` the entry signed into it, including an
1444
+ * `on_behalf_of` built from the request's authentication, so a signed one the
1445
+ * payload lacks was deleted after export. A vault row's payload never holds
1446
+ * them (the Server keeps them only inside the signed envelope), so on a dump
1447
+ * a row without them is not a mismatch, and the identity is held to the row's
1448
+ * actor columns by the OIDC-actor check instead.
894
1449
  */
895
- export function envelopeExtensionsMatch(rowPayload, signedPredicate) {
1450
+ export function envelopeExtensionsMatch(rowPayload, signedPredicate, projected = false) {
896
1451
  const obo = rowPayload['on_behalf_of'];
897
- if (obo !== null && typeof obo === 'object' && !Array.isArray(obo)) {
898
- if (!deepEqual(obo, signedPredicate['on_behalf_of']))
899
- return false;
900
- }
1452
+ const rowObo = obo !== null && typeof obo === 'object' && !Array.isArray(obo) ? obo : undefined;
1453
+ const signedOboRaw = signedPredicate['on_behalf_of'];
1454
+ const signedObo = signedOboRaw !== null && typeof signedOboRaw === 'object' && !Array.isArray(signedOboRaw) ? signedOboRaw : undefined;
1455
+ if (rowObo !== undefined && !deepEqual(rowObo, signedPredicate['on_behalf_of']))
1456
+ return false;
1457
+ if (projected && signedObo !== undefined && rowObo === undefined)
1458
+ return false;
901
1459
  const tp = rowPayload['traceparent'];
902
- if (typeof tp === 'string' && TRACEPARENT_REGEX.test(tp) && tp !== signedPredicate['traceparent']) {
1460
+ const rowTp = typeof tp === 'string' && TRACEPARENT_REGEX.test(tp) ? tp : undefined;
1461
+ const signedTpRaw = signedPredicate['traceparent'];
1462
+ const signedTp = typeof signedTpRaw === 'string' && TRACEPARENT_REGEX.test(signedTpRaw) ? signedTpRaw : undefined;
1463
+ if (rowTp !== undefined && rowTp !== signedPredicate['traceparent'])
1464
+ return false;
1465
+ if (projected && signedTp !== undefined && rowTp === undefined)
903
1466
  return false;
904
- }
905
1467
  return true;
906
1468
  }
907
1469
  // --- RFC 9162 Merkle (SCITT Receipt verifiable data structure) ---
@@ -937,8 +1499,8 @@ export function rfc9162NodeHash(left, right) {
937
1499
  return sha256Bytes(concat(NODE_PREFIX, left, right));
938
1500
  }
939
1501
  /**
940
- * Verify a RFC 9162 §2.1.3.2 inclusion proof. Mirrors the engine-side
941
- * implementation; reproduced here so the verifier stays engine-free. False
1502
+ * Verify a RFC 9162 §2.1.3.2 inclusion proof. Mirrors the Server-side
1503
+ * implementation; reproduced here so the verifier stays Server-free. False
942
1504
  * when `leafIndex` or `treeSize` is not a safe integer: the walk halves them,
943
1505
  * and a fraction, NaN or an unsafe integer would walk some other tree.
944
1506
  */
@@ -992,6 +1554,7 @@ const VDP_INCLUSION_PROOF_KEY = -1;
992
1554
  export function extractReceiptInclusionProof(receiptBytes) {
993
1555
  try {
994
1556
  const decoded = cborDecode(receiptBytes, {
1557
+ ...STRICT_CBOR_DECODE,
995
1558
  useMaps: true,
996
1559
  tags: { [COSE_SIGN1_TAG]: (control) => control() },
997
1560
  });
@@ -1125,3 +1688,12 @@ export function verifyOrgReadInclusion(leafHashHex, leafIndex, treeSize, pathHex
1125
1688
  }
1126
1689
  return verifyRfc9162Inclusion(leaf, leafIndex, treeSize, path, root);
1127
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
+ }