@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
@@ -15,7 +15,11 @@
15
15
  *
16
16
  * bodyHash = sha256 hex over the RFC 8785 (JCS) canonical JSON of `body`
17
17
  * signInput = `<scheme>:<recipientHubId>:<method>:<path>:<bodyHash>:<timestamp>:<nonce>`
18
- * verify `signature` (hex Ed25519) over the UTF-8 sign-input under `senderPublicKey`
18
+ * verify `signature` over the UTF-8 sign-input under `senderPublicKey`
19
+ *
20
+ * The algorithm is the key's own: ML-DSA-87 or ES384, the signature base64url
21
+ * without padding, or Ed25519 with a hex signature on a message a Server
22
+ * before 4.0.0 sealed.
19
23
  *
20
24
  * then the entry's own fields against the body it sealed (the state the entry
21
25
  * projects is the state the body carried, and so on). Entries from before the
@@ -24,17 +28,32 @@
24
28
  */
25
29
  import { createHash } from 'node:crypto';
26
30
  import { rfc3339Ms } from './instant.js';
27
- import { algorithmByName, runtimeCanCompute, verifyEd25519Bytes } from './primitives.js';
31
+ import { declaredKeyAlgorithm, hostRefusalCause, judgingKeyStatements, resolveKeyAlgorithm, runtimeCanCompute, signatureShape, verifySignatureBytes } from './primitives.js';
28
32
  export const FEDERATION_WIRE_SCHEME = 'agledger.federation.v2';
29
33
  /** The domain a federation key statement's signatures sign under. */
30
34
  export const FEDERATION_KEY_STATEMENT_DOMAIN = 'agledger.federation.key-statement.v1';
31
35
  /** The 12-byte SPKI prefix of an Ed25519 key: SEQUENCE { AlgorithmIdentifier(id-Ed25519), BIT STRING }. */
32
36
  const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
37
+ /** The algorithms a federation key signs messages with. Ed25519 signed them before Server 4.0.0. */
38
+ const FEDERATION_ALGORITHMS = new Set(['ML-DSA-87', 'ES384', 'Ed25519']);
39
+ /** The order of P-384, for the low-S form an ES384 federation signature takes. */
40
+ const P384_ORDER = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973');
41
+ /**
42
+ * The federation algorithm a base64 SPKI DER key is for, or null. Read from
43
+ * the key's structure first, so an ML-DSA or Ed25519 key reads as itself on a
44
+ * host that cannot load it.
45
+ */
46
+ function federationKeyAlgorithm(spkiBase64) {
47
+ const declared = declaredKeyAlgorithm(Buffer.from(spkiBase64, 'base64'));
48
+ const alg = declared ?? resolveKeyAlgorithm(spkiBase64);
49
+ return typeof alg === 'object' && FEDERATION_ALGORITHMS.has(alg.name) ? alg : null;
50
+ }
33
51
  /**
34
- * A federation key as base64 SPKI DER, from either form the Server's peer
35
- * table holds: SPKI DER, or the raw 32-byte key. Returns null for anything
36
- * that is neither (so a caller refuses it by name rather than verifying
37
- * nothing under it).
52
+ * A federation key as base64 SPKI DER: an ML-DSA-87 or ES384 key as it is,
53
+ * and an Ed25519 key (a Server before 4.0.0) from either form that Server's
54
+ * peer table held, SPKI DER or the raw 32-byte key. Returns null for anything
55
+ * else (so a caller refuses it by name rather than verifying nothing under
56
+ * it).
38
57
  */
39
58
  export function normalizeFederationKey(publicKeyBase64) {
40
59
  if (typeof publicKeyBase64 !== 'string' || publicKeyBase64.length === 0)
@@ -48,9 +67,40 @@ export function normalizeFederationKey(publicKeyBase64) {
48
67
  }
49
68
  if (bytes.length === 32)
50
69
  return Buffer.concat([ED25519_SPKI_PREFIX, bytes]).toString('base64');
51
- if (bytes.length === 44 && bytes.subarray(0, 12).equals(ED25519_SPKI_PREFIX))
52
- return bytes.toString('base64');
53
- return null;
70
+ const spki = bytes.toString('base64');
71
+ return federationKeyAlgorithm(spki) === null ? null : spki;
72
+ }
73
+ /**
74
+ * The bytes of a federation signature in the one spelling its key's algorithm
75
+ * takes, else null: 128 hex characters under an Ed25519 key; under ML-DSA-87
76
+ * or ES384, base64url without padding that decodes to exactly the algorithm's
77
+ * length and encodes back to the same characters, and for ES384 the low-S
78
+ * form of r||s.
79
+ */
80
+ function federationSignatureBytes(alg, signature) {
81
+ if (typeof signature !== 'string')
82
+ return null;
83
+ if (alg.name === 'Ed25519')
84
+ return HEX_SIG.test(signature) ? Buffer.from(signature, 'hex') : null;
85
+ if (signature.length !== Math.ceil((alg.signatureLength * 4) / 3))
86
+ return null;
87
+ const bytes = Buffer.from(signature, 'base64url');
88
+ if (bytes.length !== alg.signatureLength || bytes.toString('base64url') !== signature)
89
+ return null;
90
+ if (alg.name === 'ES384' && BigInt(`0x${bytes.subarray(bytes.length / 2).toString('hex')}`) > P384_ORDER / 2n)
91
+ return null;
92
+ return bytes;
93
+ }
94
+ /** How a signature under `alg` is spelled, for a failure line. */
95
+ function signatureSpelling(alg) {
96
+ return alg.name === 'Ed25519'
97
+ ? '64 bytes of hex'
98
+ : `${alg.signatureLength} bytes of base64url without padding${alg.name === 'ES384' ? ', r||s with low S' : ''}`;
99
+ }
100
+ /** Why this host cannot compute `alg`, for a line that says nothing was verified. */
101
+ function cannotCompute(alg) {
102
+ const cause = hostRefusalCause(alg.name);
103
+ return `this host cannot compute ${alg.name}${cause === null ? '' : ` (${cause})`}`;
54
104
  }
55
105
  const INSTANT_US = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/;
56
106
  const HEX64 = /^[0-9a-f]{64}$/;
@@ -70,16 +120,29 @@ function keyRef(value, extra) {
70
120
  return null;
71
121
  return value;
72
122
  }
73
- function verifyStatementSignature(publicKey, signature, payload) {
74
- if (!HEX_SIG.test(signature))
123
+ function verifyStatementSignature(publicKey, signature, payload, hubId) {
124
+ // A federation key's history decides which keys a peer hub signs with: a
125
+ // key statement, read as this host reads it in a rerun that assumes none.
126
+ return judgingKeyStatements(() => verifyStatementSignatureOnHost(publicKey, signature, payload, hubId));
127
+ }
128
+ function verifyStatementSignatureOnHost(publicKey, signature, payload, hubId) {
129
+ const alg = federationKeyAlgorithm(publicKey);
130
+ if (alg === null)
131
+ return false;
132
+ // Checks that need no computation run before this host's capability is asked.
133
+ const bytes = federationSignatureBytes(alg, signature);
134
+ if (bytes === null || signatureShape(alg, bytes) !== 'signature')
75
135
  return false;
76
- return verifyEd25519Bytes(publicKey, Buffer.from(`${FEDERATION_KEY_STATEMENT_DOMAIN}:${payload}`, 'utf8'), Buffer.from(signature, 'hex'));
136
+ if (!runtimeCanCompute(alg)) {
137
+ throw new TypeError(`The federation key history for hub ${hubId} cannot be checked: ${cannotCompute(alg)}.`);
138
+ }
139
+ return verifySignatureBytes(publicKey, Buffer.from(`${FEDERATION_KEY_STATEMENT_DOMAIN}:${payload}`, 'utf8'), bytes);
77
140
  }
78
141
  /**
79
142
  * The payload of one served key statement when it holds as the Server holds
80
143
  * it, else why not. Holds: the payload is its own JCS form with only the
81
144
  * statement fields, names `hubId`, its `typ` is the statement's `kind`, the
82
- * keys are Ed25519 SPKI DER matching their digests, the instants are
145
+ * keys are federation keys as SPKI DER matching their digests, the instants are
83
146
  * microsecond RFC 3339, a succession hands over at the instant its subject
84
147
  * takes over and carries the predecessor's signature, a genesis carries none,
85
148
  * and every signature verifies.
@@ -107,7 +170,7 @@ function verifyKeyStatement(stmt, hubId) {
107
170
  return `it names hub ${JSON.stringify(parsed.hubId)}`;
108
171
  const subject = keyRef(parsed.subject, 'activatedAt');
109
172
  if (subject === null)
110
- return 'its subject is not an Ed25519 key with its digest';
173
+ return 'its subject is not a federation key with its digest';
111
174
  const activatedAt = subject.activatedAt;
112
175
  if (!(activatedAt === null || (typeof activatedAt === 'string' && INSTANT_US.test(activatedAt))))
113
176
  return 'its subject.activatedAt is not a microsecond RFC 3339 instant or null';
@@ -115,7 +178,7 @@ function verifyKeyStatement(stmt, hubId) {
115
178
  if (parsed.predecessor !== undefined) {
116
179
  const pred = keyRef(parsed.predecessor, 'retiredAt');
117
180
  if (pred === null)
118
- return 'its predecessor is not an Ed25519 key with its digest';
181
+ return 'its predecessor is not a federation key with its digest';
119
182
  if (typeof pred.retiredAt !== 'string' || pred.retiredAt !== activatedAt)
120
183
  return 'its predecessor.retiredAt is not its subject.activatedAt';
121
184
  if (pred.spkiSha256 === subject.spkiSha256)
@@ -127,10 +190,10 @@ function verifyKeyStatement(stmt, hubId) {
127
190
  }
128
191
  if (typ === 'succession' && predecessor === undefined)
129
192
  return 'it is a succession with no predecessor';
130
- if (!verifyStatementSignature(subject.publicKey, String(stmt.subjectSignature), stmt.payload))
193
+ if (!verifyStatementSignature(subject.publicKey, stmt.subjectSignature, stmt.payload, hubId))
131
194
  return 'its subjectSignature does not verify under its subject key';
132
195
  if (typ === 'succession') {
133
- if (typeof stmt.predecessorSignature !== 'string' || !verifyStatementSignature(predecessor.publicKey, stmt.predecessorSignature, stmt.payload)) {
196
+ if (typeof stmt.predecessorSignature !== 'string' || predecessor === undefined || !verifyStatementSignature(predecessor.publicKey, stmt.predecessorSignature, stmt.payload, hubId)) {
134
197
  return 'its predecessorSignature does not verify under its predecessor key';
135
198
  }
136
199
  }
@@ -143,6 +206,20 @@ function verifyKeyStatement(stmt, hubId) {
143
206
  ...(predecessor ? { predecessor } : {}),
144
207
  };
145
208
  }
209
+ /**
210
+ * A federation key history that does not hold for the keys pinned beside it:
211
+ * the pin is not a key the history admits, the statement that admits it does
212
+ * not verify, or the document is another hub's or another domain's. A
213
+ * `TypeError`, as every refused `federationKeys` input is, carrying the
214
+ * canonical `code`.
215
+ */
216
+ export class FederationKeyHistoryError extends TypeError {
217
+ code = 'FEDERATION_KEY_HISTORY_INVALID';
218
+ constructor(message) {
219
+ super(message);
220
+ this.name = 'FederationKeyHistoryError';
221
+ }
222
+ }
146
223
  /**
147
224
  * The keys a pin and the histories given for its hub trust: the pin, and
148
225
  * every key a chain of successions links to it, each succession counted only
@@ -151,29 +228,30 @@ function verifyKeyStatement(stmt, hubId) {
151
228
  * signature, so it links nothing.
152
229
  */
153
230
  function trustedKeysFromHistory(hubId, pins, histories) {
154
- if (algorithmByName('Ed25519') === null || !runtimeCanCompute(algorithmByName('Ed25519'))) {
155
- throw new TypeError(`The federation key history for hub ${hubId} cannot be checked: this host cannot compute Ed25519 (an active OpenSSL FIPS provider carries no EdDSA).`);
156
- }
157
231
  const statements = [];
232
+ const dropped = [];
158
233
  const seenIds = new Set();
159
234
  for (const { doc, label } of histories) {
160
235
  if (!isRecord(doc) || !Array.isArray(doc.statements))
161
- throw new TypeError(`${label} is not a federation key-history document (no statements array).`);
236
+ throw new FederationKeyHistoryError(`${label} is not a federation key-history document (no statements array).`);
162
237
  if (doc.hubId !== hubId)
163
- throw new TypeError(`${label} is the key history of hub ${JSON.stringify(doc.hubId)}, not ${hubId}.`);
238
+ throw new FederationKeyHistoryError(`${label} is the key history of hub ${JSON.stringify(doc.hubId)}, not ${hubId}.`);
164
239
  if (doc.statementDomain !== FEDERATION_KEY_STATEMENT_DOMAIN) {
165
- throw new TypeError(`${label} signs under ${JSON.stringify(doc.statementDomain)}, not ${FEDERATION_KEY_STATEMENT_DOMAIN}.`);
240
+ throw new FederationKeyHistoryError(`${label} signs under ${JSON.stringify(doc.statementDomain)}, not ${FEDERATION_KEY_STATEMENT_DOMAIN}.`);
166
241
  }
167
242
  doc.statements.forEach((stmt, j) => {
168
243
  const id = isRecord(stmt) && typeof stmt.id === 'string' ? stmt.id : `#${j}`;
169
244
  if (seenIds.has(id))
170
245
  return;
171
246
  seenIds.add(id);
247
+ // A statement that does not verify takes no part in the walk, as on the
248
+ // Server: a row is not trust, and a statement the pinned key does not
249
+ // rest on cannot take the pin's own history down.
172
250
  const verified = verifyKeyStatement(stmt, hubId);
173
- if (typeof verified === 'string') {
174
- throw new TypeError(`${label}.statements[${j}] (${id}) does not hold: ${verified}. A served history lists only statements that verify, so this document was altered.`);
175
- }
176
- statements.push(verified);
251
+ if (typeof verified === 'string')
252
+ dropped.push(`${label}.statements[${j}] (${id}): ${verified}`);
253
+ else
254
+ statements.push(verified);
177
255
  });
178
256
  }
179
257
  const admission = new Map();
@@ -206,7 +284,8 @@ function trustedKeysFromHistory(hubId, pins, histories) {
206
284
  const listed = pins.filter((p) => publicKeyOf.has(spkiSha256(p.spki)));
207
285
  if (listed.length === 0) {
208
286
  const named = pins.map((p) => `${p.label} (${spkiSha256(p.spki).slice(0, 16)})`).join(', ');
209
- throw new TypeError(`${histories.map((h) => h.label).join(', ')}: no key pinned for hub ${hubId} appears in the key history given for it (${named}), so the history is not linked to anything you hold. Pin a key the history lists: its current key, or one you held before the change.`);
287
+ const unverified = dropped.length > 0 ? ` ${dropped.length} statement(s) do not verify and take no part: ${dropped.join('; ')}.` : '';
288
+ throw new FederationKeyHistoryError(`${histories.map((h) => h.label).join(', ')}: no key pinned for hub ${hubId} is a key the history given for it admits (${named}), so the history is not linked to anything you hold. Pin a key the history lists: its current key, or one you held before the change.${unverified}`);
210
289
  }
211
290
  const trusted = new Set();
212
291
  const standalone = new Set();
@@ -219,28 +298,39 @@ function trustedKeysFromHistory(hubId, pins, histories) {
219
298
  const queue = [digest];
220
299
  while (queue.length > 0) {
221
300
  const k = queue.pop();
222
- if (trusted.has(k))
301
+ if (k === undefined || trusted.has(k))
223
302
  continue;
224
303
  trusted.add(k);
225
304
  queue.push(...(links.get(k) ?? []));
226
305
  }
227
306
  }
307
+ // Newest first, whichever key the walk started from: a first key (no signed
308
+ // activation) is the oldest.
309
+ const linked = [...trusted].flatMap((digest) => {
310
+ const publicKey = publicKeyOf.get(digest);
311
+ // Every trusted digest was reached through publicKeyOf, so none is skipped.
312
+ if (publicKey === undefined)
313
+ return [];
314
+ return [{
315
+ publicKey,
316
+ activatedAt: admission.get(digest)?.subject.activatedAt ?? null,
317
+ retiredAt: retiredAt.get(digest) ?? null,
318
+ }];
319
+ }).sort((x, y) => (x.activatedAt === y.activatedAt ? 0 : x.activatedAt === null ? 1 : y.activatedAt === null ? -1 : x.activatedAt < y.activatedAt ? 1 : -1));
228
320
  return [
229
- ...[...trusted].map((digest) => ({
230
- publicKey: publicKeyOf.get(digest),
231
- activatedAt: admission.get(digest)?.subject.activatedAt ?? null,
232
- retiredAt: retiredAt.get(digest) ?? null,
233
- })),
321
+ ...linked,
234
322
  ...[...standalone].map((publicKey) => ({ publicKey, activatedAt: null, retiredAt: null })),
235
323
  ];
236
324
  }
237
325
  /**
238
326
  * Build the registry from `{ [hubId]: publicKey }` or
239
327
  * `[{ hubId, publicKey, history? }]`. Throws `TypeError` naming the entry on
240
- * any key that is not an Ed25519 key in one of the two forms, and on a history
241
- * that is another hub's, carries a statement that does not verify, or lists
242
- * none of the keys pinned for its hub, so a bad input is refused before any verification
243
- * runs rather than reported as a signature failure.
328
+ * any key that is not a federation key, and `FederationKeyHistoryError` (code
329
+ * `FEDERATION_KEY_HISTORY_INVALID`) on a history that is another hub's or
330
+ * admits none of the keys pinned for its hub, so a bad input is refused
331
+ * before any verification runs rather than reported as a signature failure.
332
+ * A statement that does not verify takes no part: the keys it alone would
333
+ * link are not trusted.
244
334
  */
245
335
  export function buildFederationKeyRegistry(input) {
246
336
  const entries = Array.isArray(input)
@@ -262,7 +352,7 @@ export function buildFederationKeyRegistry(input) {
262
352
  throw new TypeError(`${label} names no hubId.`);
263
353
  const spki = typeof key === 'string' ? normalizeFederationKey(key) : null;
264
354
  if (spki === null) {
265
- throw new TypeError(`${label} is not an Ed25519 public key (base64 SPKI DER, or base64 of the raw 32 bytes).`);
355
+ throw new TypeError(`${label} is not a federation public key: ML-DSA-87 or ES384 as base64 SPKI DER, or the Ed25519 key of a Server before 4.0.0 (base64 SPKI DER, or base64 of the raw 32 bytes).`);
266
356
  }
267
357
  const hub = byHub.get(hubId) ?? { pins: [], histories: [] };
268
358
  hub.pins.push({ spki, label });
@@ -337,40 +427,46 @@ export function extractFederationWire(payload) {
337
427
  return 'malformed';
338
428
  return w;
339
429
  }
340
- /**
341
- * Which entry payload fields must equal which body fields, per entry type.
342
- * The receiver projects these from the message, so a disagreement means the
343
- * entry says something the sender did not sign.
344
- */
430
+ /** A state sync with `kind: "dispute"` projects a dispute event, which carries no state. */
431
+ const isDisputeSync = (payload) => payload.kind === 'dispute';
345
432
  const FIELD_PAIRS = {
346
433
  FEDERATION_STATE_SYNC: [
347
- ['state', 'state'],
348
- ['recordType', 'type'],
349
- ['disputeId', 'disputeId'],
350
- ['action', 'action'],
434
+ ['state', 'state', (p) => !isDisputeSync(p)],
435
+ ['recordType', 'type', false],
436
+ ['disputeId', 'disputeId', isDisputeSync],
437
+ ['action', 'action', isDisputeSync],
351
438
  ],
352
- FEDERATION_SIGNAL_RECEIVED: [['recommendation', 'recommendation']],
439
+ FEDERATION_SIGNAL_RECEIVED: [['recommendation', 'recommendation', true]],
353
440
  FEDERATION_CO_SIGN_RESPONDED: [
354
- ['recommendation', 'recommendation'],
355
- ['state', 'state'],
356
- ['outcomeHash', 'outcomeHash'],
357
- ['idempotencyKey', 'idempotencyKey'],
441
+ ['recommendation', 'recommendation', true],
442
+ ['state', 'state', true],
443
+ ['outcomeHash', 'outcomeHash', false],
444
+ ['idempotencyKey', 'idempotencyKey', false],
358
445
  ],
359
446
  };
447
+ /**
448
+ * The allowance at both edges of a federation key's window, as the Server's
449
+ * receiver recipe gives it. `wire.timestamp` is the clock of the process that
450
+ * signed the message and the window's edges are the sender's database clock,
451
+ * so a message signed within this of a key change is on the right key.
452
+ */
453
+ export const FEDERATION_KEY_WINDOW_SKEW_MS = 300_000;
360
454
  /**
361
455
  * Check one sealed message against the entry that carries it, and under the
362
456
  * sender's key when `keys` has one for `wire.senderHubId`.
363
457
  *
364
458
  * Runs on an entry that already passed every other check, so `payload` is
365
459
  * what the receiver signed. `recordId` is the entry's record; the body names
366
- * the same record on every message type that carries one. When the sender's
460
+ * the same record on every message type that carries one, or, on an entry that
461
+ * signs `origin`, the record id `origin` names. When the sender's
367
462
  * keys came with a history, the message is placed in a key's window by
368
463
  * `wire.timestamp`: the sender signed it, the receiver sealed it under its own
369
464
  * signature after holding it to its clock-skew allowance, and it is read from
370
- * the sender's clock, the clock the history's windows are written by. The
465
+ * the sender's clock, the clock the history's windows are written by, with
466
+ * {@link FEDERATION_KEY_WINDOW_SKEW_MS} allowed at each edge. The
371
467
  * entry's `createdAt` is a column no signature covers, so it places nothing.
372
468
  */
373
- export function checkFederationWire(entryType, recordId, payload, wire, keys) {
469
+ export function checkFederationWire(entryType, recordId, payload, wire, keys, options = {}) {
374
470
  if (wire.scheme !== FEDERATION_WIRE_SCHEME) {
375
471
  return { outcome: 'invalid', detail: `Sealed message scheme is ${JSON.stringify(wire.scheme)}, not ${FEDERATION_WIRE_SCHEME}.` };
376
472
  }
@@ -381,15 +477,64 @@ export function checkFederationWire(entryType, recordId, payload, wire, keys) {
381
477
  if (typeof payload.peerHubId === 'string' && payload.peerHubId !== wire.senderHubId) {
382
478
  return { outcome: 'invalid', detail: `Entry names peer ${payload.peerHubId}, the sealed message was sent by ${wire.senderHubId}.` };
383
479
  }
480
+ // A projection is keyed by its sending Server and the record id that Server
481
+ // named. When the receiver already held that id, the projection lives under
482
+ // a fresh local id and its entries sign `origin`, the sender and the id it
483
+ // sent: the sealed body names `origin.recordId`, not the entry's record.
484
+ // Entries written before `origin` was signed name the entry's own record.
485
+ const origin = payload.origin;
486
+ let expectedRecordId = recordId;
487
+ if (origin !== undefined && origin !== null) {
488
+ if (typeof origin !== 'object' || Array.isArray(origin)) {
489
+ return { outcome: 'invalid', detail: `Entry origin is ${canonicalizeJson(origin)}, not an object naming the sending Server and the record id it sent.` };
490
+ }
491
+ const o = origin;
492
+ if (typeof o.peerHubId !== 'string' || typeof o.recordId !== 'string') {
493
+ return { outcome: 'invalid', detail: `Entry origin ${canonicalizeJson(origin)} does not name both peerHubId and recordId as strings.` };
494
+ }
495
+ if (o.peerHubId !== wire.senderHubId) {
496
+ return { outcome: 'invalid', detail: `Entry origin names peer ${o.peerHubId}, the sealed message was sent by ${wire.senderHubId}.` };
497
+ }
498
+ expectedRecordId = o.recordId;
499
+ }
384
500
  const bodyRecordId = wire.body.recordId;
385
- if (recordId !== null && typeof bodyRecordId === 'string' && bodyRecordId !== recordId) {
386
- return { outcome: 'invalid', detail: `Entry is on record ${recordId}, the sealed message names record ${bodyRecordId}.` };
501
+ const pairs = FIELD_PAIRS[entryType];
502
+ if (pairs !== undefined) {
503
+ // A message of these types is about one record, so a body that names none,
504
+ // or an entry that names none to compare it with, proves nothing.
505
+ if (typeof bodyRecordId !== 'string') {
506
+ return { outcome: 'invalid', detail: `A ${entryType} message must name its record, and the sealed body carries no string recordId.` };
507
+ }
508
+ if (expectedRecordId === null) {
509
+ return { outcome: 'invalid', detail: `A ${entryType} entry carries no record id, so the record the sealed message names (${bodyRecordId}) cannot be compared with it.` };
510
+ }
511
+ }
512
+ if (expectedRecordId !== null && typeof bodyRecordId === 'string' && bodyRecordId.toLowerCase() !== expectedRecordId.toLowerCase()) {
513
+ return {
514
+ outcome: 'invalid',
515
+ detail: origin === undefined || origin === null
516
+ ? `Entry is on record ${recordId}, the sealed message names record ${bodyRecordId}.`
517
+ : `Entry origin names record ${expectedRecordId}, the sealed message names record ${bodyRecordId}.`,
518
+ };
387
519
  }
388
- for (const [entryField, bodyField] of FIELD_PAIRS[entryType] ?? []) {
520
+ for (const [entryField, bodyField, required] of pairs ?? []) {
389
521
  const mine = payload[entryField];
390
522
  const theirs = wire.body[bodyField];
391
- if (mine === undefined || theirs === undefined || mine === null || theirs === null)
392
- continue;
523
+ const mineAbsent = mine === undefined || mine === null;
524
+ const theirsAbsent = theirs === undefined || theirs === null;
525
+ if (mineAbsent && theirsAbsent) {
526
+ if (!(typeof required === 'function' ? required(payload) : required))
527
+ continue;
528
+ return { outcome: 'invalid', detail: `A ${entryType} entry must carry ${entryField}, and neither the entry nor the sealed message's ${bodyField} does.` };
529
+ }
530
+ if (mineAbsent || theirsAbsent) {
531
+ return {
532
+ outcome: 'invalid',
533
+ detail: mineAbsent
534
+ ? `The sealed message's ${bodyField} is ${canonicalizeJson(theirs)} and the entry carries no ${entryField}: the entry leaves out what the sender signed.`
535
+ : `Entry ${entryField} is ${canonicalizeJson(mine)} and the sealed message carries no ${bodyField}: the entry asserts what the sender did not sign.`,
536
+ };
537
+ }
393
538
  if (canonicalizeJson(mine) !== canonicalizeJson(theirs)) {
394
539
  return {
395
540
  outcome: 'invalid',
@@ -417,31 +562,96 @@ export function checkFederationWire(entryType, recordId, payload, wire, keys) {
417
562
  if (Number.isNaN(at)) {
418
563
  return { outcome: 'invalid', detail: `Sealed message from ${wire.senderHubId} carries timestamp ${JSON.stringify(wire.timestamp)}, which is not an RFC 3339 instant, so it cannot be placed in its key's window.` };
419
564
  }
420
- if (key.activatedAt !== null && at < rfc3339Ms(key.activatedAt)) {
565
+ if (key.activatedAt !== null && at < rfc3339Ms(key.activatedAt) - FEDERATION_KEY_WINDOW_SKEW_MS) {
421
566
  return {
422
567
  outcome: 'invalid',
423
- detail: `Sealed message from ${wire.senderHubId} is signed at ${wire.timestamp} under a federation key its history activates at ${key.activatedAt}, after the sender signed it.`,
568
+ detail: `Sealed message from ${wire.senderHubId} is signed at ${wire.timestamp} under a federation key its history activates at ${key.activatedAt}, more than ${FEDERATION_KEY_WINDOW_SKEW_MS / 1000}s after the sender signed it.`,
569
+ };
570
+ }
571
+ afterRetirement = key.retiredAt !== null && at > rfc3339Ms(key.retiredAt) + FEDERATION_KEY_WINDOW_SKEW_MS;
572
+ if (afterRetirement && options.allowAfterRetirement !== true) {
573
+ return {
574
+ outcome: 'invalid',
575
+ detail: `Sealed message from ${wire.senderHubId} is signed at ${wire.timestamp} under a federation key its history retired at ${key.retiredAt}, more than ${FEDERATION_KEY_WINDOW_SKEW_MS / 1000}s before the sender signed it. A retired key signing is what a leaked key does; if the sender's publisher was only slow to restart onto its new key, pass allowAfterRetirement.`,
424
576
  };
425
577
  }
426
- afterRetirement = key.retiredAt !== null && at > rfc3339Ms(key.retiredAt);
427
- }
428
- const ed25519 = algorithmByName('Ed25519');
429
- if (ed25519 === null || !runtimeCanCompute(ed25519)) {
430
- return { outcome: 'unsupported', detail: `Sealed message from ${wire.senderHubId} could not be checked: this host cannot compute Ed25519 (an active OpenSSL FIPS provider carries no EdDSA). Not verified, and not tamper evidence.` };
431
578
  }
432
- let signature;
433
- try {
434
- signature = Buffer.from(wire.signature, 'hex');
579
+ const alg = federationKeyAlgorithm(key.publicKey);
580
+ if (alg === null) {
581
+ return { outcome: 'invalid', detail: `The federation key supplied for ${wire.senderHubId} is not an ML-DSA-87, ES384 or Ed25519 key.` };
435
582
  }
436
- catch {
437
- signature = Buffer.alloc(0);
583
+ // Checks that need no computation run before this host's capability is asked.
584
+ const signature = federationSignatureBytes(alg, wire.signature);
585
+ if (signature === null || signatureShape(alg, signature) !== 'signature') {
586
+ return { outcome: 'invalid', detail: `Sealed signature from ${wire.senderHubId} is not ${signatureSpelling(alg)} and not all zero, the form a signature under its ${alg.name} federation key takes.` };
438
587
  }
439
- if (signature.length !== 64 || !/^[0-9a-f]{128}$/i.test(wire.signature)) {
440
- return { outcome: 'invalid', detail: `Sealed signature from ${wire.senderHubId} is not 64 bytes of hex.` };
588
+ if (!runtimeCanCompute(alg)) {
589
+ return { outcome: 'unsupported', detail: `Sealed message from ${wire.senderHubId} could not be checked: ${cannotCompute(alg)}. Not verified, and not tamper evidence.` };
441
590
  }
442
- const ok = verifyEd25519Bytes(key.publicKey, Buffer.from(federationSignInput(wire), 'utf8'), signature);
591
+ const ok = verifySignatureBytes(key.publicKey, Buffer.from(federationSignInput(wire), 'utf8'), signature);
443
592
  if (!ok) {
444
593
  return { outcome: 'invalid', detail: `Sealed signature from ${wire.senderHubId} does not verify under that hub's federation key over the sign-input the entry seals.` };
445
594
  }
446
595
  return { outcome: 'ok', signatureChecked: true, afterRetirement };
447
596
  }
597
+ // --- Signatures a Server returns to its peer ---
598
+ /** Domain an acknowledgement signature covers. */
599
+ export const FEDERATION_ACK_DOMAIN = 'agledger.federation.ack.v1';
600
+ /** Domain a co-sign counter-signature covers. */
601
+ export const FEDERATION_CO_SIGN_DOMAIN = 'agledger.federation.co-sign.v1';
602
+ /** What an acknowledgement acknowledges: a state transition, a signal or a dispute leg. */
603
+ export const FEDERATION_ACK_KINDS = ['ack', 'signal', 'dispute'];
604
+ /** The members of a co-sign claim, exactly. */
605
+ export const FEDERATION_CO_SIGN_CLAIM_FIELDS = ['recordId', 'outcome', 'recommendation', 'outcomeHash', 'state', 'performerHubId', 'validUntil'];
606
+ function checkPeerSignature(what, signerPublicKey, signature, signInput) {
607
+ const invalid = (detail) => ({ state: 'invalid', code: 'FEDERATION_SIGNATURE_INVALID', detail });
608
+ const spki = typeof signerPublicKey === 'string' ? normalizeFederationKey(signerPublicKey) : null;
609
+ const alg = spki === null ? null : federationKeyAlgorithm(spki);
610
+ if (spki === null || alg === null) {
611
+ return invalid(`${what} names a signer key that is not a federation key: ML-DSA-87 or ES384 as base64 SPKI DER, or the Ed25519 key of a Server before 4.0.0.`);
612
+ }
613
+ // Checks that need no computation run before this host's capability is asked.
614
+ const bytes = typeof signature === 'string' ? federationSignatureBytes(alg, signature) : null;
615
+ if (bytes === null || signatureShape(alg, bytes) !== 'signature')
616
+ return invalid(`${what} is not a signature in the form of its ${alg.name} key: ${signatureSpelling(alg)}, not all zero.`);
617
+ if (!runtimeCanCompute(alg))
618
+ return { state: 'unsupported', detail: `${what} cannot be checked: ${cannotCompute(alg)}.` };
619
+ if (!verifySignatureBytes(spki, Buffer.from(signInput, 'utf8'), bytes))
620
+ return invalid(`${what} does not verify under the signer's ${alg.name} key.`);
621
+ return { state: 'ok' };
622
+ }
623
+ /**
624
+ * Verify the acknowledgement a receiving Server returned for a federated
625
+ * transition, signal or dispute leg (`serverSignature`). It covers
626
+ * `agledger.federation.ack.v1:<kind>:<recordId>:<value>:<serverTimestamp>`,
627
+ * so an acknowledgement made for one kind does not verify as another.
628
+ */
629
+ export function verifyFederationAck(ack) {
630
+ const invalid = (detail) => ({ state: 'invalid', code: 'FEDERATION_SIGNATURE_INVALID', detail });
631
+ if (!isRecord(ack))
632
+ return invalid('The acknowledgement is not an object.');
633
+ const { kind, recordId, value, serverTimestamp } = ack;
634
+ if (typeof kind !== 'string' || !FEDERATION_ACK_KINDS.includes(kind)) {
635
+ return invalid(`The acknowledgement's kind is ${JSON.stringify(kind)}, not one of ${FEDERATION_ACK_KINDS.join(', ')}.`);
636
+ }
637
+ if (typeof recordId !== 'string' || typeof value !== 'string' || typeof serverTimestamp !== 'string') {
638
+ return invalid('The acknowledgement carries no recordId, value or serverTimestamp string.');
639
+ }
640
+ return checkPeerSignature('The acknowledgement signature', ack.signerPublicKey, ack.serverSignature, `${FEDERATION_ACK_DOMAIN}:${kind}:${recordId}:${value}:${serverTimestamp}`);
641
+ }
642
+ /**
643
+ * Verify a co-sign counter-signature: the counterparty Server's signature
644
+ * over `agledger.federation.co-sign.v1:` and the RFC 8785 form of the claim.
645
+ * The claim holds exactly the fields in {@link FEDERATION_CO_SIGN_CLAIM_FIELDS}.
646
+ */
647
+ export function verifyFederationCoSign(input) {
648
+ const invalid = (detail) => ({ state: 'invalid', code: 'FEDERATION_SIGNATURE_INVALID', detail });
649
+ if (!isRecord(input) || !isRecord(input.claim))
650
+ return invalid('The co-sign input carries no claim object.');
651
+ const keys = Object.keys(input.claim);
652
+ const fields = FEDERATION_CO_SIGN_CLAIM_FIELDS;
653
+ if (keys.length !== fields.length || !fields.every((f) => f in input.claim)) {
654
+ return invalid(`The co-sign claim holds ${keys.sort().join(', ') || 'no fields'}; it holds exactly ${[...fields].sort().join(', ')}.`);
655
+ }
656
+ return checkPeerSignature('The counter-signature', input.signerPublicKey, input.counterSignature, `${FEDERATION_CO_SIGN_DOMAIN}:${canonicalizeJson(input.claim)}`);
657
+ }
@@ -0,0 +1,100 @@
1
+ import { type KeyRegistry } from './chain.js';
2
+ import { type KeyTrust } from './key-statements.js';
3
+ /** COSE content type (header label 3) of a signed history seal. */
4
+ export declare const HISTORY_SEAL_CTY = "application/vnd.agledger.history-seal+cbor";
5
+ /** The chain key the platform-ops chain's leaf carries. */
6
+ export declare const PLATFORM_OPS_CHAIN_KEY = "00000000-0000-0000-0000-000000000000";
7
+ /** A history seal as an artifact carries it: an export's `exportMetadata.historySeals[]`, a dump's `vault_history_seals.ndjson` row. */
8
+ export interface HistorySealInput {
9
+ id: string;
10
+ /** The key whose retirement wrote the seal. */
11
+ retiredKeyId: string;
12
+ signingKeyId: string;
13
+ /** The signed seal, base64 or bytes. */
14
+ coseSign1: string | Uint8Array;
15
+ /** When the Server stored the seal: what its key's window is held to. */
16
+ createdAt?: string | null;
17
+ /** The `treeSize` beside the seal, bound to the signed one when given. */
18
+ treeSize?: number;
19
+ /** The `rootHash` beside the seal (lowercase hex), bound to the signed root when given. */
20
+ rootHash?: string;
21
+ }
22
+ /** One chain's inclusion proof in one seal: an export's `historySeals[].proof`, a dump's `vault_history_seal_leaves.ndjson` row. */
23
+ export interface HistorySealProofInput {
24
+ leaf: {
25
+ chainKey: string;
26
+ chainPosition: number;
27
+ entryHash: string;
28
+ };
29
+ leafIndex: number;
30
+ /** Lowercase hex sibling hashes, from the leaf to the root. */
31
+ auditPath: readonly string[];
32
+ }
33
+ export interface HistorySealVerdict {
34
+ id: string;
35
+ /** `ok`: decodes, is bound to its closure and verifies under an anchored ML-DSA key. `unsupported`: this host cannot compute its key's algorithm. */
36
+ state: 'ok' | 'unsupported' | 'invalid';
37
+ detail: string;
38
+ /** The retired key the seal names, or the key it is filed for when its payload does not decode. */
39
+ subjectKeyId: string | null;
40
+ /** The retirement the seal signs for that key. */
41
+ subjectRetiredAt: string | null;
42
+ treeSize: number | null;
43
+ /** The signed root, lowercase hex. */
44
+ root: string | null;
45
+ signingKeyId: string | null;
46
+ }
47
+ /**
48
+ * Judge one history seal against the keys the artifact's entries are verified
49
+ * with (after `applyKeyTrust`) and the walk that anchored them. Never throws
50
+ * on a malformed seal: it is `invalid`, with the reason.
51
+ */
52
+ export declare function judgeHistorySeal(seal: HistorySealInput, keys: KeyRegistry, trust: KeyTrust): HistorySealVerdict;
53
+ /** How the seals of an artifact cover one classical signing key. */
54
+ export type HistorySealCover = {
55
+ state: 'sealed';
56
+ seal: HistorySealVerdict;
57
+ } | {
58
+ state: 'invalid';
59
+ detail: string;
60
+ } | {
61
+ state: 'unsupported';
62
+ detail: string;
63
+ } | {
64
+ state: 'unsealed';
65
+ detail: string;
66
+ };
67
+ /** The seals of one artifact, judged, and which seal covers which key. */
68
+ export interface HistorySealPlan {
69
+ /** Every seal the artifact carries, judged, by id (lowercase). */
70
+ seals: ReadonlyMap<string, HistorySealVerdict>;
71
+ /**
72
+ * How a signing key's entries are covered, or null when the key is held to
73
+ * no seal: an ML-DSA key, an unknown key, or any key on a walk that trusts
74
+ * no ML-DSA key.
75
+ */
76
+ coverOf(keyId: string): HistorySealCover | null;
77
+ }
78
+ /**
79
+ * Judge the seals an artifact carries and decide which one covers each
80
+ * classical key. `trust` is the key walk; null (no `trustAnchors`) holds no
81
+ * key to any seal.
82
+ */
83
+ export declare function planHistorySeals(seals: readonly HistorySealInput[], keys: KeyRegistry, trust: KeyTrust | null): HistorySealPlan;
84
+ /** One chain's leaf in one seal, once its proof reaches the signed root. */
85
+ export type HistorySealLeaf = {
86
+ state: 'ok';
87
+ chainPosition: number;
88
+ entryHash: string;
89
+ } | {
90
+ state: 'missing';
91
+ } | {
92
+ state: 'invalid';
93
+ detail: string;
94
+ };
95
+ /**
96
+ * Resolve a chain's leaf in a seal whose verdict is `ok`: the proof must be
97
+ * for this chain and reach the signed root. `proof` is null or undefined when
98
+ * the artifact carries none for this chain (the seal has no leaf for it).
99
+ */
100
+ export declare function resolveHistorySealLeaf(seal: HistorySealVerdict, chainKey: string, proof: HistorySealProofInput | null | undefined): HistorySealLeaf;