@agledger/verify-core 2.0.0 → 2.2.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.
@@ -0,0 +1,515 @@
1
+ /**
2
+ * The sealed federation message on a receiving Server's chain entry.
3
+ *
4
+ * When a peer's signed message (a state transition, a settlement signal, a
5
+ * dispute leg, a co-sign request) is accepted, the receiver's chain entry for
6
+ * it carries `payload.wire`: the message as the sender signed it, with the
7
+ * sender's registered key, the recipient hub id, the method, path, body hash,
8
+ * timestamp, nonce, signature, and a copy of the body the hash covers. The
9
+ * receiver's own vault signature covers all of that, so the entry proves what
10
+ * the receiver accepted; verifying the sealed signature under the sender's
11
+ * federation key proves what the sender asserted, from the receiver's export
12
+ * alone.
13
+ *
14
+ * The recipe is the Server's `federationPeerAuth` check, re-run offline:
15
+ *
16
+ * bodyHash = sha256 hex over the RFC 8785 (JCS) canonical JSON of `body`
17
+ * signInput = `<scheme>:<recipientHubId>:<method>:<path>:<bodyHash>:<timestamp>:<nonce>`
18
+ * verify `signature` (hex Ed25519) over the UTF-8 sign-input under `senderPublicKey`
19
+ *
20
+ * then the entry's own fields against the body it sealed (the state the entry
21
+ * projects is the state the body carried, and so on). Entries from before the
22
+ * Server sealed messages, and entries a direct projection wrote, carry no
23
+ * `wire`; absent is not a failure.
24
+ */
25
+ import { createHash } from 'node:crypto';
26
+ import { rfc3339Ms } from './instant.js';
27
+ import { algorithmByName, runtimeCanCompute, verifyEd25519Bytes } from './primitives.js';
28
+ export const FEDERATION_WIRE_SCHEME = 'agledger.federation.v2';
29
+ /** The domain a federation key statement's signatures sign under. */
30
+ export const FEDERATION_KEY_STATEMENT_DOMAIN = 'agledger.federation.key-statement.v1';
31
+ /** The 12-byte SPKI prefix of an Ed25519 key: SEQUENCE { AlgorithmIdentifier(id-Ed25519), BIT STRING }. */
32
+ const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
33
+ /**
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).
38
+ */
39
+ export function normalizeFederationKey(publicKeyBase64) {
40
+ if (typeof publicKeyBase64 !== 'string' || publicKeyBase64.length === 0)
41
+ return null;
42
+ let bytes;
43
+ try {
44
+ bytes = Buffer.from(publicKeyBase64, 'base64');
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ if (bytes.length === 32)
50
+ 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;
54
+ }
55
+ const INSTANT_US = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/;
56
+ const HEX64 = /^[0-9a-f]{64}$/;
57
+ const HEX_SIG = /^[0-9a-f]{128}$/i;
58
+ function spkiSha256(spkiBase64) {
59
+ return createHash('sha256').update(Buffer.from(spkiBase64, 'base64')).digest('hex');
60
+ }
61
+ function keyRef(value, extra) {
62
+ if (!isRecord(value))
63
+ return null;
64
+ if (Object.keys(value).some((k) => k !== 'publicKey' && k !== 'spkiSha256' && k !== extra))
65
+ return null;
66
+ const { publicKey, spkiSha256: digest } = value;
67
+ if (typeof publicKey !== 'string' || typeof digest !== 'string' || !HEX64.test(digest))
68
+ return null;
69
+ if (normalizeFederationKey(publicKey) !== publicKey || spkiSha256(publicKey) !== digest)
70
+ return null;
71
+ return value;
72
+ }
73
+ function verifyStatementSignature(publicKey, signature, payload) {
74
+ if (!HEX_SIG.test(signature))
75
+ return false;
76
+ return verifyEd25519Bytes(publicKey, Buffer.from(`${FEDERATION_KEY_STATEMENT_DOMAIN}:${payload}`, 'utf8'), Buffer.from(signature, 'hex'));
77
+ }
78
+ /**
79
+ * The payload of one served key statement when it holds as the Server holds
80
+ * it, else why not. Holds: the payload is its own JCS form with only the
81
+ * statement fields, names `hubId`, its `typ` is the statement's `kind`, the
82
+ * keys are Ed25519 SPKI DER matching their digests, the instants are
83
+ * microsecond RFC 3339, a succession hands over at the instant its subject
84
+ * takes over and carries the predecessor's signature, a genesis carries none,
85
+ * and every signature verifies.
86
+ */
87
+ function verifyKeyStatement(stmt, hubId) {
88
+ if (!isRecord(stmt) || typeof stmt.payload !== 'string')
89
+ return 'it carries no payload string';
90
+ let parsed;
91
+ try {
92
+ parsed = JSON.parse(stmt.payload);
93
+ }
94
+ catch {
95
+ return 'its payload is not JSON';
96
+ }
97
+ if (!isRecord(parsed) || canonicalizeJson(parsed) !== stmt.payload)
98
+ return 'its payload is not in its RFC 8785 canonical form';
99
+ if (Object.keys(parsed).some((k) => !['typ', 'hubId', 'subject', 'predecessor'].includes(k)))
100
+ return 'its payload carries a field a statement does not';
101
+ const typ = parsed.typ;
102
+ if (typ !== 'genesis' && typ !== 'succession')
103
+ return `its typ is ${JSON.stringify(typ)}`;
104
+ if (stmt.kind !== typ)
105
+ return `its kind ${JSON.stringify(stmt.kind)} is not its payload's typ ${typ}`;
106
+ if (parsed.hubId !== hubId)
107
+ return `it names hub ${JSON.stringify(parsed.hubId)}`;
108
+ const subject = keyRef(parsed.subject, 'activatedAt');
109
+ if (subject === null)
110
+ return 'its subject is not an Ed25519 key with its digest';
111
+ const activatedAt = subject.activatedAt;
112
+ if (!(activatedAt === null || (typeof activatedAt === 'string' && INSTANT_US.test(activatedAt))))
113
+ return 'its subject.activatedAt is not a microsecond RFC 3339 instant or null';
114
+ let predecessor;
115
+ if (parsed.predecessor !== undefined) {
116
+ const pred = keyRef(parsed.predecessor, 'retiredAt');
117
+ if (pred === null)
118
+ return 'its predecessor is not an Ed25519 key with its digest';
119
+ if (typeof pred.retiredAt !== 'string' || pred.retiredAt !== activatedAt)
120
+ return 'its predecessor.retiredAt is not its subject.activatedAt';
121
+ if (pred.spkiSha256 === subject.spkiSha256)
122
+ return 'it names one key as its own predecessor';
123
+ predecessor = { publicKey: pred.publicKey, spkiSha256: pred.spkiSha256, retiredAt: pred.retiredAt };
124
+ }
125
+ else if (activatedAt !== null) {
126
+ return 'it activates a key at a signed instant without naming a predecessor';
127
+ }
128
+ if (typ === 'succession' && predecessor === undefined)
129
+ return 'it is a succession with no predecessor';
130
+ if (!verifyStatementSignature(subject.publicKey, String(stmt.subjectSignature), stmt.payload))
131
+ return 'its subjectSignature does not verify under its subject key';
132
+ if (typ === 'succession') {
133
+ if (typeof stmt.predecessorSignature !== 'string' || predecessor === undefined || !verifyStatementSignature(predecessor.publicKey, stmt.predecessorSignature, stmt.payload)) {
134
+ return 'its predecessorSignature does not verify under its predecessor key';
135
+ }
136
+ }
137
+ else if (stmt.predecessorSignature !== null && stmt.predecessorSignature !== undefined) {
138
+ return 'it is a genesis carrying a predecessorSignature';
139
+ }
140
+ return {
141
+ typ,
142
+ subject: { publicKey: subject.publicKey, spkiSha256: subject.spkiSha256, activatedAt },
143
+ ...(predecessor ? { predecessor } : {}),
144
+ };
145
+ }
146
+ /**
147
+ * The keys a pin and the histories given for its hub trust: the pin, and
148
+ * every key a chain of successions links to it, each succession counted only
149
+ * when it is the statement admitting its subject (the first in write order),
150
+ * as the Server walks it. A genesis names its predecessor without that key's
151
+ * signature, so it links nothing.
152
+ */
153
+ function trustedKeysFromHistory(hubId, pins, histories) {
154
+ const ed25519 = algorithmByName('Ed25519');
155
+ if (ed25519 === null || !runtimeCanCompute(ed25519)) {
156
+ 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).`);
157
+ }
158
+ const statements = [];
159
+ const seenIds = new Set();
160
+ for (const { doc, label } of histories) {
161
+ if (!isRecord(doc) || !Array.isArray(doc.statements))
162
+ throw new TypeError(`${label} is not a federation key-history document (no statements array).`);
163
+ if (doc.hubId !== hubId)
164
+ throw new TypeError(`${label} is the key history of hub ${JSON.stringify(doc.hubId)}, not ${hubId}.`);
165
+ if (doc.statementDomain !== FEDERATION_KEY_STATEMENT_DOMAIN) {
166
+ throw new TypeError(`${label} signs under ${JSON.stringify(doc.statementDomain)}, not ${FEDERATION_KEY_STATEMENT_DOMAIN}.`);
167
+ }
168
+ doc.statements.forEach((stmt, j) => {
169
+ const id = isRecord(stmt) && typeof stmt.id === 'string' ? stmt.id : `#${j}`;
170
+ if (seenIds.has(id))
171
+ return;
172
+ seenIds.add(id);
173
+ const verified = verifyKeyStatement(stmt, hubId);
174
+ if (typeof verified === 'string') {
175
+ throw new TypeError(`${label}.statements[${j}] (${id}) does not hold: ${verified}. A served history lists only statements that verify, so this document was altered.`);
176
+ }
177
+ statements.push(verified);
178
+ });
179
+ }
180
+ const admission = new Map();
181
+ for (const st of statements)
182
+ if (!admission.has(st.subject.spkiSha256))
183
+ admission.set(st.subject.spkiSha256, st);
184
+ const publicKeyOf = new Map();
185
+ for (const st of statements) {
186
+ publicKeyOf.set(st.subject.spkiSha256, st.subject.publicKey);
187
+ if (st.predecessor)
188
+ publicKeyOf.set(st.predecessor.spkiSha256, st.predecessor.publicKey);
189
+ }
190
+ const links = new Map();
191
+ const retiredAt = new Map();
192
+ for (const st of statements) {
193
+ if (st.typ !== 'succession' || admission.get(st.subject.spkiSha256) !== st || !st.predecessor)
194
+ continue;
195
+ const a = st.predecessor.spkiSha256;
196
+ const b = st.subject.spkiSha256;
197
+ links.set(a, [...(links.get(a) ?? []), b]);
198
+ links.set(b, [...(links.get(b) ?? []), a]);
199
+ if (!retiredAt.has(a))
200
+ retiredAt.set(a, st.predecessor.retiredAt);
201
+ }
202
+ // A pin the histories list roots a walk through its successions. A pin they
203
+ // do not list (a key from before a change made with neither predecessor
204
+ // setting, which no history names) is trusted on its own, at any time, as a
205
+ // pin is without a history. At least one pin must be listed, or nothing
206
+ // links the histories to a key you hold.
207
+ const listed = pins.filter((p) => publicKeyOf.has(spkiSha256(p.spki)));
208
+ if (listed.length === 0) {
209
+ const named = pins.map((p) => `${p.label} (${spkiSha256(p.spki).slice(0, 16)})`).join(', ');
210
+ 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.`);
211
+ }
212
+ const trusted = new Set();
213
+ const standalone = new Set();
214
+ for (const { spki } of pins) {
215
+ const digest = spkiSha256(spki);
216
+ if (!publicKeyOf.has(digest)) {
217
+ standalone.add(spki);
218
+ continue;
219
+ }
220
+ const queue = [digest];
221
+ while (queue.length > 0) {
222
+ const k = queue.pop();
223
+ if (k === undefined || trusted.has(k))
224
+ continue;
225
+ trusted.add(k);
226
+ queue.push(...(links.get(k) ?? []));
227
+ }
228
+ }
229
+ return [
230
+ ...[...trusted].flatMap((digest) => {
231
+ const publicKey = publicKeyOf.get(digest);
232
+ // Every trusted digest was reached through publicKeyOf, so none is skipped.
233
+ if (publicKey === undefined)
234
+ return [];
235
+ return [{
236
+ publicKey,
237
+ activatedAt: admission.get(digest)?.subject.activatedAt ?? null,
238
+ retiredAt: retiredAt.get(digest) ?? null,
239
+ }];
240
+ }),
241
+ ...[...standalone].map((publicKey) => ({ publicKey, activatedAt: null, retiredAt: null })),
242
+ ];
243
+ }
244
+ /**
245
+ * Build the registry from `{ [hubId]: publicKey }` or
246
+ * `[{ hubId, publicKey, history? }]`. Throws `TypeError` naming the entry on
247
+ * any key that is not an Ed25519 key in one of the two forms, and on a history
248
+ * that is another hub's, carries a statement that does not verify, or lists
249
+ * none of the keys pinned for its hub, so a bad input is refused before any verification
250
+ * runs rather than reported as a signature failure.
251
+ */
252
+ export function buildFederationKeyRegistry(input) {
253
+ const entries = Array.isArray(input)
254
+ ? input.map((e, i) => ({
255
+ hubId: typeof e?.hubId === 'string' ? e.hubId : '',
256
+ key: e?.publicKey,
257
+ history: e?.history,
258
+ label: `federationKeys[${i}]`,
259
+ }))
260
+ : Object.entries(input).map(([hubId, key]) => ({
261
+ hubId,
262
+ key,
263
+ history: undefined,
264
+ label: `federationKeys[${JSON.stringify(hubId)}]`,
265
+ }));
266
+ const byHub = new Map();
267
+ for (const { hubId, key, history, label } of entries) {
268
+ if (hubId.length === 0)
269
+ throw new TypeError(`${label} names no hubId.`);
270
+ const spki = typeof key === 'string' ? normalizeFederationKey(key) : null;
271
+ if (spki === null) {
272
+ throw new TypeError(`${label} is not an Ed25519 public key (base64 SPKI DER, or base64 of the raw 32 bytes).`);
273
+ }
274
+ const hub = byHub.get(hubId) ?? { pins: [], histories: [] };
275
+ hub.pins.push({ spki, label });
276
+ if (history !== undefined)
277
+ hub.histories.push({ doc: history, label: `${label}.history` });
278
+ byHub.set(hubId, hub);
279
+ }
280
+ const out = new Map();
281
+ for (const [hubId, { pins, histories }] of byHub) {
282
+ if (histories.length === 0) {
283
+ out.set(hubId, [...new Set(pins.map((p) => p.spki))].map((publicKey) => ({ publicKey, activatedAt: null, retiredAt: null })));
284
+ }
285
+ else {
286
+ out.set(hubId, trustedKeysFromHistory(hubId, pins, histories));
287
+ }
288
+ }
289
+ return out;
290
+ }
291
+ /**
292
+ * RFC 8785 (JCS) canonical JSON, as the Server's `canonicalize` writes it:
293
+ * object keys sorted by code unit, no whitespace, `undefined` members dropped
294
+ * (an array element that is `undefined` serializes as `null`), `-0` as `0`,
295
+ * non-finite numbers as `null`. Numbers take JavaScript's own shortest form,
296
+ * which is what RFC 8785 specifies.
297
+ */
298
+ export function canonicalizeJson(value) {
299
+ if (value === null || value === undefined)
300
+ return 'null';
301
+ if (typeof value === 'boolean')
302
+ return value ? 'true' : 'false';
303
+ if (typeof value === 'number') {
304
+ if (!Number.isFinite(value))
305
+ return 'null';
306
+ if (Object.is(value, -0))
307
+ return '0';
308
+ return JSON.stringify(value);
309
+ }
310
+ if (typeof value === 'string')
311
+ return JSON.stringify(value);
312
+ if (Array.isArray(value))
313
+ return '[' + value.map(canonicalizeJson).join(',') + ']';
314
+ if (typeof value === 'object') {
315
+ const obj = value;
316
+ const keys = Object.keys(obj).filter((k) => obj[k] !== undefined).sort();
317
+ return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalizeJson(obj[k])).join(',') + '}';
318
+ }
319
+ return 'null';
320
+ }
321
+ /** The sign-input the Server builds, a colon-joined line under the scheme. */
322
+ export function federationSignInput(wire) {
323
+ return `${wire.scheme}:${wire.recipientHubId}:${wire.method}:${wire.path}:${wire.bodyHash}:${wire.timestamp}:${wire.nonce}`;
324
+ }
325
+ function isRecord(value) {
326
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
327
+ }
328
+ /**
329
+ * The `wire` a row payload carries, or null when it carries none. A `wire`
330
+ * that is present but is not an object is returned as `malformed`, so the
331
+ * caller fails it rather than reading an edited row as one with no message.
332
+ */
333
+ export function extractFederationWire(payload) {
334
+ if (!('wire' in payload) || payload.wire === undefined)
335
+ return null;
336
+ const w = payload.wire;
337
+ if (!isRecord(w))
338
+ return 'malformed';
339
+ for (const k of ['scheme', 'senderHubId', 'senderPublicKey', 'recipientHubId', 'method', 'path', 'bodyHash', 'timestamp', 'nonce', 'signature']) {
340
+ if (typeof w[k] !== 'string')
341
+ return 'malformed';
342
+ }
343
+ if (!isRecord(w.body))
344
+ return 'malformed';
345
+ return w;
346
+ }
347
+ /** A state sync with `kind: "dispute"` projects a dispute event, which carries no state. */
348
+ const isDisputeSync = (payload) => payload.kind === 'dispute';
349
+ const FIELD_PAIRS = {
350
+ FEDERATION_STATE_SYNC: [
351
+ ['state', 'state', (p) => !isDisputeSync(p)],
352
+ ['recordType', 'type', false],
353
+ ['disputeId', 'disputeId', isDisputeSync],
354
+ ['action', 'action', isDisputeSync],
355
+ ],
356
+ FEDERATION_SIGNAL_RECEIVED: [['recommendation', 'recommendation', true]],
357
+ FEDERATION_CO_SIGN_RESPONDED: [
358
+ ['recommendation', 'recommendation', true],
359
+ ['state', 'state', true],
360
+ ['outcomeHash', 'outcomeHash', false],
361
+ ['idempotencyKey', 'idempotencyKey', false],
362
+ ],
363
+ };
364
+ /**
365
+ * The allowance at both edges of a federation key's window, as the Server's
366
+ * receiver recipe gives it. `wire.timestamp` is the clock of the process that
367
+ * signed the message and the window's edges are the sender's database clock,
368
+ * so a message signed within this of a key change is on the right key.
369
+ */
370
+ export const FEDERATION_KEY_WINDOW_SKEW_MS = 300_000;
371
+ /**
372
+ * Check one sealed message against the entry that carries it, and under the
373
+ * sender's key when `keys` has one for `wire.senderHubId`.
374
+ *
375
+ * Runs on an entry that already passed every other check, so `payload` is
376
+ * what the receiver signed. `recordId` is the entry's record; the body names
377
+ * the same record on every message type that carries one, or, on an entry that
378
+ * signs `origin`, the record id `origin` names. When the sender's
379
+ * keys came with a history, the message is placed in a key's window by
380
+ * `wire.timestamp`: the sender signed it, the receiver sealed it under its own
381
+ * signature after holding it to its clock-skew allowance, and it is read from
382
+ * the sender's clock, the clock the history's windows are written by, with
383
+ * {@link FEDERATION_KEY_WINDOW_SKEW_MS} allowed at each edge. The
384
+ * entry's `createdAt` is a column no signature covers, so it places nothing.
385
+ */
386
+ export function checkFederationWire(entryType, recordId, payload, wire, keys, options = {}) {
387
+ if (wire.scheme !== FEDERATION_WIRE_SCHEME) {
388
+ return { outcome: 'invalid', detail: `Sealed message scheme is ${JSON.stringify(wire.scheme)}, not ${FEDERATION_WIRE_SCHEME}.` };
389
+ }
390
+ const bodyHash = createHash('sha256').update(canonicalizeJson(wire.body), 'utf8').digest('hex');
391
+ if (bodyHash !== wire.bodyHash.toLowerCase()) {
392
+ return { outcome: 'invalid', detail: 'Sealed body does not hash to the bodyHash the sender signed: the body copy was edited after the message was verified.' };
393
+ }
394
+ if (typeof payload.peerHubId === 'string' && payload.peerHubId !== wire.senderHubId) {
395
+ return { outcome: 'invalid', detail: `Entry names peer ${payload.peerHubId}, the sealed message was sent by ${wire.senderHubId}.` };
396
+ }
397
+ // A projection is keyed by its sending Server and the record id that Server
398
+ // named. When the receiver already held that id, the projection lives under
399
+ // a fresh local id and its entries sign `origin`, the sender and the id it
400
+ // sent: the sealed body names `origin.recordId`, not the entry's record.
401
+ // Entries written before `origin` was signed name the entry's own record.
402
+ const origin = payload.origin;
403
+ let expectedRecordId = recordId;
404
+ if (origin !== undefined && origin !== null) {
405
+ if (typeof origin !== 'object' || Array.isArray(origin)) {
406
+ return { outcome: 'invalid', detail: `Entry origin is ${canonicalizeJson(origin)}, not an object naming the sending Server and the record id it sent.` };
407
+ }
408
+ const o = origin;
409
+ if (typeof o.peerHubId !== 'string' || typeof o.recordId !== 'string') {
410
+ return { outcome: 'invalid', detail: `Entry origin ${canonicalizeJson(origin)} does not name both peerHubId and recordId as strings.` };
411
+ }
412
+ if (o.peerHubId !== wire.senderHubId) {
413
+ return { outcome: 'invalid', detail: `Entry origin names peer ${o.peerHubId}, the sealed message was sent by ${wire.senderHubId}.` };
414
+ }
415
+ expectedRecordId = o.recordId;
416
+ }
417
+ const bodyRecordId = wire.body.recordId;
418
+ const pairs = FIELD_PAIRS[entryType];
419
+ if (pairs !== undefined) {
420
+ // A message of these types is about one record, so a body that names none,
421
+ // or an entry that names none to compare it with, proves nothing.
422
+ if (typeof bodyRecordId !== 'string') {
423
+ return { outcome: 'invalid', detail: `A ${entryType} message must name its record, and the sealed body carries no string recordId.` };
424
+ }
425
+ if (expectedRecordId === null) {
426
+ return { outcome: 'invalid', detail: `A ${entryType} entry carries no record id, so the record the sealed message names (${bodyRecordId}) cannot be compared with it.` };
427
+ }
428
+ }
429
+ if (expectedRecordId !== null && typeof bodyRecordId === 'string' && bodyRecordId.toLowerCase() !== expectedRecordId.toLowerCase()) {
430
+ return {
431
+ outcome: 'invalid',
432
+ detail: origin === undefined || origin === null
433
+ ? `Entry is on record ${recordId}, the sealed message names record ${bodyRecordId}.`
434
+ : `Entry origin names record ${expectedRecordId}, the sealed message names record ${bodyRecordId}.`,
435
+ };
436
+ }
437
+ for (const [entryField, bodyField, required] of pairs ?? []) {
438
+ const mine = payload[entryField];
439
+ const theirs = wire.body[bodyField];
440
+ const mineAbsent = mine === undefined || mine === null;
441
+ const theirsAbsent = theirs === undefined || theirs === null;
442
+ if (mineAbsent && theirsAbsent) {
443
+ if (!(typeof required === 'function' ? required(payload) : required))
444
+ continue;
445
+ return { outcome: 'invalid', detail: `A ${entryType} entry must carry ${entryField}, and neither the entry nor the sealed message's ${bodyField} does.` };
446
+ }
447
+ if (mineAbsent || theirsAbsent) {
448
+ return {
449
+ outcome: 'invalid',
450
+ detail: mineAbsent
451
+ ? `The sealed message's ${bodyField} is ${canonicalizeJson(theirs)} and the entry carries no ${entryField}: the entry leaves out what the sender signed.`
452
+ : `Entry ${entryField} is ${canonicalizeJson(mine)} and the sealed message carries no ${bodyField}: the entry asserts what the sender did not sign.`,
453
+ };
454
+ }
455
+ if (canonicalizeJson(mine) !== canonicalizeJson(theirs)) {
456
+ return {
457
+ outcome: 'invalid',
458
+ detail: `Entry ${entryField} is ${canonicalizeJson(mine)}, the sealed message's ${bodyField} is ${canonicalizeJson(theirs)}: the entry asserts what the sender did not sign.`,
459
+ };
460
+ }
461
+ }
462
+ const trusted = keys?.get(wire.senderHubId);
463
+ if (trusted === undefined)
464
+ return { outcome: 'unchecked' };
465
+ const sealed = normalizeFederationKey(wire.senderPublicKey);
466
+ const key = trusted.find((k) => k.publicKey === sealed);
467
+ if (key === undefined) {
468
+ const withHistory = trusted.some((k) => k.activatedAt !== null || k.retiredAt !== null);
469
+ return {
470
+ outcome: 'invalid',
471
+ detail: withHistory
472
+ ? `The sealed senderPublicKey for ${wire.senderHubId} is not a federation key its history links to the key you pinned: the receiver verified this message under a key no succession from your pin reaches. A key listed linked: false sits behind a genesis that named it without its signature; pin it too once its operator confirms it.`
473
+ : `The sealed senderPublicKey for ${wire.senderHubId} is not the federation key supplied for that hub: the receiver verified this message under a key the sender's operator did not give you. If the sender changed its federation key, supply its key history (GET /.well-known/agledger-federation-keys.json on the sender) with the key you pinned.`,
474
+ };
475
+ }
476
+ let afterRetirement = false;
477
+ if (key.activatedAt !== null || key.retiredAt !== null) {
478
+ const at = rfc3339Ms(wire.timestamp);
479
+ if (Number.isNaN(at)) {
480
+ 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.` };
481
+ }
482
+ if (key.activatedAt !== null && at < rfc3339Ms(key.activatedAt) - FEDERATION_KEY_WINDOW_SKEW_MS) {
483
+ return {
484
+ outcome: 'invalid',
485
+ 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.`,
486
+ };
487
+ }
488
+ afterRetirement = key.retiredAt !== null && at > rfc3339Ms(key.retiredAt) + FEDERATION_KEY_WINDOW_SKEW_MS;
489
+ if (afterRetirement && options.allowAfterRetirement !== true) {
490
+ return {
491
+ outcome: 'invalid',
492
+ 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.`,
493
+ };
494
+ }
495
+ }
496
+ const ed25519 = algorithmByName('Ed25519');
497
+ if (ed25519 === null || !runtimeCanCompute(ed25519)) {
498
+ 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.` };
499
+ }
500
+ let signature;
501
+ try {
502
+ signature = Buffer.from(wire.signature, 'hex');
503
+ }
504
+ catch {
505
+ signature = Buffer.alloc(0);
506
+ }
507
+ if (signature.length !== 64 || !/^[0-9a-f]{128}$/i.test(wire.signature)) {
508
+ return { outcome: 'invalid', detail: `Sealed signature from ${wire.senderHubId} is not 64 bytes of hex.` };
509
+ }
510
+ const ok = verifyEd25519Bytes(key.publicKey, Buffer.from(federationSignInput(wire), 'utf8'), signature);
511
+ if (!ok) {
512
+ 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.` };
513
+ }
514
+ return { outcome: 'ok', signatureChecked: true, afterRetirement };
515
+ }
package/dist/index.d.ts CHANGED
@@ -5,12 +5,14 @@
5
5
  */
6
6
  export { suggestion } from './failures.js';
7
7
  export type { FailureCode } from './failures.js';
8
- export { ACCOUNTED_ENTRY_CODE, buildAgentKeyRegistry, buildKeyRegistry, chainOfScope, earliestKeyActivation, verifyChain, writtenWhileSigning, } from './chain.js';
9
- export type { AccountedEntry, AccountedEntryCode, AgentKeyRegistry, KeySource, KeyTrustState, VerificationKey, KeyRegistry, NormalizedEntry, OptionalCheck, CheckApplicability, SignatureOutcome, ChainEntryResult, ChainResult, VerifyChainOptions, } from './chain.js';
8
+ export { ACCOUNTED_ENTRY_CODE, buildAgentKeyRegistry, buildKeyRegistry, chainOfScope, distrustAccounts, earliestKeyActivation, placeInKeyWindow, verifyChain, writtenWhileSigning, } from './chain.js';
9
+ export type { AccountedEntry, AccountedEntryCode, AgentKeyRegistry, KeySource, KeyTrustState, KeyWindowPlacement, VerificationKey, KeyRegistry, NormalizedEntry, OptionalCheck, CheckApplicability, SignatureOutcome, ChainEntryResult, ChainResult, EvidenceBindingCounts, VerifyChainOptions, } from './chain.js';
10
10
  export { verifyAuditExport } from './audit-export.js';
11
- export type { AuditExportEntryInput, RecordAuditExportInput, SigningKeyWindow, VerifyExportOptions, SuppliedKeyEntry, EntryVerificationResult, VerifyExportResult, } from './audit-export.js';
11
+ export type { AuditExportEntryInput, RecordAuditExportInput, SigningKeyWindow, VerifyExportOptions, SuppliedKeyEntry, EntryVerificationResult, VerifyExportResult, ExportOptionalCheck, } from './audit-export.js';
12
12
  export { KEY_STATEMENT_CTY, KEY_STATEMENT_KINDS, applyKeyTrust, assertNotPinnedAndDistrusted, computeKeyTrust, keyStatementFromDumpRow, keyStatementsFromExport, keyStatementsFromVerificationKeys, parseDistrustedKeys, parseTrustAnchors, reportKeyTrust, settleKeyTrust, spkiSha256, verdictOf, trustKeyFromDumpRow, } from './key-statements.js';
13
13
  export type { ComputeKeyTrustInput, DistrustedKey, DistrustSpan, DumpKeyStatementRow, DumpSigningKeyRow, KeyRegistryFinding, KeyRegistryFindingCode, KeyStatementInput, KeyStatementKind, KeyTrust, KeyTrustEntry, KeyTrustNote, KeyTrustReport, KeyTrustStatus, PublishedKeyStatement, TrustKeyInput, Verdict, VerificationKeysDocument, } from './key-statements.js';
14
+ export { FEDERATION_KEY_STATEMENT_DOMAIN, FEDERATION_WIRE_SCHEME, buildFederationKeyRegistry, canonicalizeJson, checkFederationWire, extractFederationWire, federationSignInput, normalizeFederationKey, FEDERATION_KEY_WINDOW_SKEW_MS, } from './federation-wire.js';
15
+ export type { FederationKeyEntry, FederationKeyHistoryDocument, FederationKeyHistoryStatement, FederationKeyRegistry, FederationTrustedKey, FederationWire, FederationWireOutcome, CheckFederationWireOptions, } from './federation-wire.js';
14
16
  export { instantMs } from './instant.js';
15
17
  export { assertKnownOptions } from './options.js';
16
18
  export { sha256Hex, sha256HexString, verifyEd25519Bytes, verifySignatureBytes, resolveKeyAlgorithm, algorithmByName, runtimeCanCompute, looksLikeEd25519Key, describeUnsupportedAlgorithm, decodeCoseSign1, verifyCoseSign1, extractActorClaim, extractChainClaim, extractKid, extractOnBehalfOfClaim, extractTraceparentClaim, extractAgentSignatureClaim, ed25519JwkThumbprint, ed25519JwkToSpki, verifyAgentSignature, AGENT_SIGNATURE_CONTEXT, decodePredicate, buildPredicateForRow, stripEnvelopeExtensions, deepEqual, orgReadLeafHash, orgReadMerkleRoot, verifyOrgReadInclusion, rfc9162LeafHash, rfc9162NodeHash, verifyRfc9162Inclusion, extractReceiptInclusionProof, verifyReceipt, } from './primitives.js';
package/dist/index.js CHANGED
@@ -4,9 +4,10 @@
4
4
  * the MCP server, and @agledger/verify all build on this single body of logic.
5
5
  */
6
6
  export { suggestion } from './failures.js';
7
- export { ACCOUNTED_ENTRY_CODE, buildAgentKeyRegistry, buildKeyRegistry, chainOfScope, earliestKeyActivation, verifyChain, writtenWhileSigning, } from './chain.js';
7
+ export { ACCOUNTED_ENTRY_CODE, buildAgentKeyRegistry, buildKeyRegistry, chainOfScope, distrustAccounts, earliestKeyActivation, placeInKeyWindow, verifyChain, writtenWhileSigning, } from './chain.js';
8
8
  export { verifyAuditExport } from './audit-export.js';
9
9
  export { KEY_STATEMENT_CTY, KEY_STATEMENT_KINDS, applyKeyTrust, assertNotPinnedAndDistrusted, computeKeyTrust, keyStatementFromDumpRow, keyStatementsFromExport, keyStatementsFromVerificationKeys, parseDistrustedKeys, parseTrustAnchors, reportKeyTrust, settleKeyTrust, spkiSha256, verdictOf, trustKeyFromDumpRow, } from './key-statements.js';
10
+ export { FEDERATION_KEY_STATEMENT_DOMAIN, FEDERATION_WIRE_SCHEME, buildFederationKeyRegistry, canonicalizeJson, checkFederationWire, extractFederationWire, federationSignInput, normalizeFederationKey, FEDERATION_KEY_WINDOW_SKEW_MS, } from './federation-wire.js';
10
11
  export { instantMs } from './instant.js';
11
12
  export { assertKnownOptions } from './options.js';
12
13
  export { sha256Hex, sha256HexString, verifyEd25519Bytes, verifySignatureBytes, resolveKeyAlgorithm, algorithmByName, runtimeCanCompute, looksLikeEd25519Key, describeUnsupportedAlgorithm, decodeCoseSign1, verifyCoseSign1, extractActorClaim, extractChainClaim, extractKid, extractOnBehalfOfClaim, extractTraceparentClaim, extractAgentSignatureClaim, ed25519JwkThumbprint, ed25519JwkToSpki, verifyAgentSignature, AGENT_SIGNATURE_CONTEXT, decodePredicate, buildPredicateForRow, stripEnvelopeExtensions, deepEqual, orgReadLeafHash, orgReadMerkleRoot, verifyOrgReadInclusion, rfc9162LeafHash, rfc9162NodeHash, verifyRfc9162Inclusion, extractReceiptInclusionProof, verifyReceipt, } from './primitives.js';
package/dist/instant.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Milliseconds of an RFC 3339 instant, truncating any finer fraction the way
3
- * the engine reads a microsecond instant (its `instantToDate`). Key statements
3
+ * the Server reads a microsecond instant. Key statements
4
4
  * sign microsecond instants; entry write times, dump columns and key documents
5
5
  * carry milliseconds, so every comparison between them is made here. Strict:
6
6
  * a `T`, an offset or `Z`, a real calendar date and time of day; NaN for
package/dist/instant.js CHANGED
@@ -2,7 +2,7 @@
2
2
  const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?([Zz]|([+-])(\d{2}):(\d{2}))$/;
3
3
  /**
4
4
  * Milliseconds of an RFC 3339 instant, truncating any finer fraction the way
5
- * the engine reads a microsecond instant (its `instantToDate`). Key statements
5
+ * the Server reads a microsecond instant. Key statements
6
6
  * sign microsecond instants; entry write times, dump columns and key documents
7
7
  * carry milliseconds, so every comparison between them is made here. Strict:
8
8
  * a `T`, an offset or `Z`, a real calendar date and time of day; NaN for
@@ -13,7 +13,7 @@ export interface KeyStatementInput {
13
13
  /**
14
14
  * Row id (the dump's or a key document's `id`), named in findings. Under the
15
15
  * write order it breaks a tie between two statements whose `createdAt` are
16
- * the same microsecond, as the engine's `created_at, id` does.
16
+ * the same microsecond, as the Server's `created_at, id` does.
17
17
  */
18
18
  id?: string | null;
19
19
  /** The source's own `kind` column, bound to the signed `typ`. */
@@ -30,7 +30,7 @@ export interface KeyStatementInput {
30
30
  * Where the statement was read from. `dump`: a row of a dump's
31
31
  * `vault_key_statements.ndjson` ({@link keyStatementFromDumpRow} sets it),
32
32
  * whose `created_at` the walk holds a distrusted key's statements to, as the
33
- * engine does. Anything else, absent included, is a key document's (an
33
+ * Server does. Anything else, absent included, is a key document's (an
34
34
  * export's or a supplied `/v1/verification-keys` entry's): its `createdAt`
35
35
  * orders it but never keeps an edge out of a distrusted key.
36
36
  */
@@ -120,7 +120,7 @@ export interface KeyRegistryFinding {
120
120
  * Something the walk did that is not a finding and does not fail a verdict:
121
121
  * a statement from a key document signed by a distrusted key that admits
122
122
  * nothing here, because the document's write time is the holder's word and is
123
- * never held against the key's cutoff, though the engine, holding it to the
123
+ * never held against the key's cutoff, though the Server, holding it to the
124
124
  * time it was stored, counts it. It still dates windows and cuts edges back.
125
125
  * Also a listed key whose `distrustedFrom` differs from the instant the
126
126
  * caller's `distrustedKeys` entry gives it, where no finding on its window
@@ -200,7 +200,7 @@ export interface KeyTrust {
200
200
  };
201
201
  }
202
202
  /**
203
- * What a `distrustedKeys` entry covers for one key, as the engine's
203
+ * What a `distrustedKeys` entry covers for one key, as the Server's
204
204
  * `distrustSpans` gives it. `cutoff`: the instant from which what the key
205
205
  * signs counts for nothing (the entry's own, else `retiredAt`; null: trusted
206
206
  * for nothing). `retiredAt`: the earliest retirement of the key that a key
@@ -238,7 +238,7 @@ export declare function parseDistrustedKeys(raw: string | readonly string[]): Di
238
238
  * (`sha256:<hex>@<instant>`) is how a leaked key whose history is still
239
239
  * needed is kept from signing anything new: the pin vouches for what it
240
240
  * stored before the instant. `computeKeyTrust` itself walks any pair as the
241
- * engine's walk does; a verifier calls this on what its caller passed before
241
+ * Server's walk does; a verifier calls this on what its caller passed before
242
242
  * it walks.
243
243
  */
244
244
  export declare function assertNotPinnedAndDistrusted(trustAnchors: string | readonly string[] | undefined, distrustedKeys: ReadonlyArray<string | DistrustedKey> | undefined): void;
@@ -346,7 +346,7 @@ export declare function keyStatementsFromVerificationKeys(doc: VerificationKeysD
346
346
  /**
347
347
  * Mark every key of a registry with the walk's verdict, and give each anchored
348
348
  * key the window its statements sign in place of whatever window it carried,
349
- * as the engine grades entries. An anchored key no statement dates carries no
349
+ * as the Server grades entries. An anchored key no statement dates carries no
350
350
  * edge on that side. A key is anchored only when its key id is the
351
351
  * fingerprint of its own SPKI: a row filed under another key's id names that
352
352
  * key's entries, and is anchored to nothing. On a walk over a dump, a key a
@@ -376,15 +376,31 @@ export type KeyTrustStatus = 'walked' | 'no_anchor' | 'no_anchored_signature';
376
376
  * The one-word reading of a verification result, as every surface prints it:
377
377
  * `failed` when it is not valid, `trusted` when it is valid and the walk
378
378
  * anchored a signature (`keyTrust.status: 'walked'`), and `unanchored` when it
379
- * is valid but rests on nothing pinned. Read this rather than `valid` alone: a
380
- * valid result with no `trustAnchors` is `unanchored`.
379
+ * is valid but rests on nothing pinned, or when the only thing that failed is
380
+ * that nothing is signed by a key the pinned trustAnchors anchor (see
381
+ * {@link verdictOf}). Read this rather than `valid` alone: a valid result with
382
+ * no `trustAnchors` is `unanchored`.
381
383
  */
382
384
  export type Verdict = 'trusted' | 'unanchored' | 'failed';
383
- /** The {@link Verdict} of a result that carries `valid` and a `keyTrust` report. */
385
+ /**
386
+ * The {@link Verdict} of a result that carries `valid` and a `keyTrust` report.
387
+ *
388
+ * Pass `passesUnpinned` on a run that supplied trustAnchors: it reruns the
389
+ * same input with the same options minus `trustAnchors` and `distrustedKeys`
390
+ * and says whether that run is valid. A pinned run that failed, whose walk
391
+ * anchored no key at all, and whose unpinned rerun passes, is `unanchored`
392
+ * rather than `failed`: the only thing wrong is that the pin reaches nothing
393
+ * in the artifact (the key-statement findings and CHAIN_SIGNING_KEY_UNANCHORED
394
+ * entries such a walk reports all follow from that). That is an export checked
395
+ * against another Server's pin, and equally one re-signed wholesale under keys
396
+ * of its own; neither is trusted, and the result keeps `valid: false`. An
397
+ * artifact in which the pin anchors even one key stays `failed`, since an
398
+ * entry beside it under an unanchored key is a substitution.
399
+ */
384
400
  export declare function verdictOf(result: {
385
401
  valid: boolean;
386
- keyTrust: Pick<KeyTrustReport, 'status'>;
387
- }): Verdict;
402
+ keyTrust: Pick<KeyTrustReport, 'status' | 'anchoredKeyIds'>;
403
+ }, passesUnpinned?: () => boolean): Verdict;
388
404
  /** What a verification result says about key anchoring. */
389
405
  export interface KeyTrustReport {
390
406
  /** See {@link KeyTrustStatus}. */