@agledger/verify-core 2.0.0 → 2.1.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.
- package/README.md +71 -0
- package/dist/audit-export.d.ts +57 -1
- package/dist/audit-export.js +15 -1
- package/dist/chain.d.ts +58 -1
- package/dist/chain.js +108 -6
- package/dist/failures.d.ts +1 -1
- package/dist/failures.js +2 -0
- package/dist/federation-wire.d.ts +152 -0
- package/dist/federation-wire.js +447 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -6,6 +6,8 @@ Statement payloads, walks the per-record hash chain, and verifies the
|
|
|
6
6
|
signature over each `Sig_structure` under the algorithm the verification key
|
|
7
7
|
commits to (Ed25519 or ES256), with no engine, no database, and no network.
|
|
8
8
|
|
|
9
|
+
Reads exports and dumps from an AGLedger Server 2.0 or later. For a 1.x Server's, use `npm i @agledger/verify-core@1.5.0`, the last release that reads them.
|
|
10
|
+
|
|
9
11
|
This is the single body of logic that underpins the SDK `/verify` subpath
|
|
10
12
|
(`@agledger/sdk/verify`), the [`@agledger/cli`](https://github.com/agledger-ai/cli)
|
|
11
13
|
`verify` command, the
|
|
@@ -92,6 +94,13 @@ check off without a word.
|
|
|
92
94
|
activation window. With `trustAnchors`, the window is the one the key
|
|
93
95
|
statements sign.
|
|
94
96
|
- **Agent signatures**, when you supply the agent's cert key (below).
|
|
97
|
+
- **Inlined evidence**, on an export taken with `?evidence=true`: each
|
|
98
|
+
completion's evidence body and each dispute's filed payload hashes (SHA-256
|
|
99
|
+
over its RFC 8785 form) to the `payload.evidenceHash` or `payload.payloadHash`
|
|
100
|
+
its entry signs, or the entry fails `CHAIN_EVIDENCE_BINDING_MISMATCH`.
|
|
101
|
+
`result.evidenceBinding` counts them. An encrypted-mode completion signs a
|
|
102
|
+
hash over a cleartext the export does not carry, so its ciphertext is counted
|
|
103
|
+
as `clientHashed`, not re-bound.
|
|
95
104
|
|
|
96
105
|
The payload, OIDC, attribution and key-window checks run when the export
|
|
97
106
|
carries their inputs, which every current Server does. The result's `optionalChecks` says
|
|
@@ -338,6 +347,68 @@ verify fails `CHAIN_AGENT_SIGNATURE_INVALID`. The check runs only where
|
|
|
338
347
|
`on_behalf_of.validated` is `true`: on a caller-asserted identity the two fields
|
|
339
348
|
may be passthrough from an older Server, and the export cannot tell which.
|
|
340
349
|
|
|
350
|
+
### Messages sealed from a federated peer
|
|
351
|
+
|
|
352
|
+
A receiving Server seals each peer message it accepts on the chain entry it
|
|
353
|
+
writes for it (`payload.wire` on its `FEDERATION_*` entries): the body as the
|
|
354
|
+
peer signed it, the peer's registered key, the hub ids, the body hash, the
|
|
355
|
+
timestamp, the nonce and the signature. Every sealed message is held to its
|
|
356
|
+
body hash and to the entry that carries it (`federation_wire` in
|
|
357
|
+
`optionalChecks`, `applied` once one was seen). Pass the peer's federation key,
|
|
358
|
+
as its operator gives it (base64 SPKI DER or base64 of the raw 32 bytes), to
|
|
359
|
+
also re-verify the peer's signature:
|
|
360
|
+
|
|
361
|
+
```ts
|
|
362
|
+
import { verifyAuditExport } from '@agledger/verify-core';
|
|
363
|
+
|
|
364
|
+
const result = verifyAuditExport(exportDocument, { federationKeys: { 'hub-b': 'MCowBQYDK2VwAyEA...' } });
|
|
365
|
+
|
|
366
|
+
console.log(result.federationWire); // e.g. { present: 2, verified: 2, failed: 0, afterRetirement: 0 }
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
A peer that changed its federation key signed its earlier messages under the
|
|
370
|
+
earlier key. Pass its key history (`GET /.well-known/agledger-federation-keys.json`
|
|
371
|
+
on the peer, no auth) beside the key you pinned for it, and every key the
|
|
372
|
+
history links to the pin through successions both keys signed is trusted
|
|
373
|
+
inside its window:
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
import { verifyAuditExport, type FederationKeyHistoryDocument } from '@agledger/verify-core';
|
|
377
|
+
|
|
378
|
+
const response = await fetch('https://hub-b.example.com/.well-known/agledger-federation-keys.json');
|
|
379
|
+
const history = (await response.json()) as FederationKeyHistoryDocument;
|
|
380
|
+
|
|
381
|
+
const result = verifyAuditExport(exportDocument, {
|
|
382
|
+
federationKeys: [{ hubId: 'hub-b', publicKey: 'MCowBQYDK2VwAyEA...', history }],
|
|
383
|
+
});
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
The windows come from the signed statements, not the document's `keys`
|
|
387
|
+
summary. Each message is placed by its sealed `wire.timestamp`, which the peer
|
|
388
|
+
signed and the receiver sealed under its own signature, and which comes from
|
|
389
|
+
the peer's clock, the same clock its windows are written by. The entry's
|
|
390
|
+
`createdAt` is not signed, so it places nothing. A message signed under a key
|
|
391
|
+
before that key's activation fails. One signed under a key after the key's
|
|
392
|
+
retirement verifies and is counted in `federationWire.afterRetirement`: a peer
|
|
393
|
+
process not yet restarted onto the new key sends exactly that, and it is in
|
|
394
|
+
order when the receiver's `federation.peer_revoked` audit row for the peer
|
|
395
|
+
comes after it. A key behind a genesis that named it only by digest
|
|
396
|
+
(`linked: false`) is not linked to the newer keys; name the hub a second time
|
|
397
|
+
with that key once its operator confirms it. The same goes for a key the
|
|
398
|
+
history does not list at all, such as the key in use before a change made with
|
|
399
|
+
neither predecessor setting: a second entry for the hub pins it, and it is
|
|
400
|
+
trusted on its own. A history that is another hub's, carries a statement that
|
|
401
|
+
does not verify, or lists none of the keys pinned for its hub throws
|
|
402
|
+
`TypeError` before anything is verified.
|
|
403
|
+
|
|
404
|
+
A sealed signature that does not verify, a sealed key that is not the one
|
|
405
|
+
supplied for that hub, a body that no longer hashes to what was signed, or an
|
|
406
|
+
entry that asserts a state the sealed body does not carry fails
|
|
407
|
+
`CHAIN_FEDERATION_WIRE_INVALID`. The pieces are exported for a caller that
|
|
408
|
+
reads the sealed message itself: `extractFederationWire`,
|
|
409
|
+
`checkFederationWire`, `federationSignInput`, `canonicalizeJson` (RFC 8785)
|
|
410
|
+
and `normalizeFederationKey`.
|
|
411
|
+
|
|
341
412
|
The Server's own chain verification also compares each sealed cert against its
|
|
342
413
|
live cert record (`cert_missing`, `cert_actor_drift`, `cert_window_drift`,
|
|
343
414
|
`cert_expired`). That record is not exported, so those checks have no offline
|
package/dist/audit-export.d.ts
CHANGED
|
@@ -19,9 +19,10 @@
|
|
|
19
19
|
* Older exports without these fields stay `skipped_no_input`, surfaced in the
|
|
20
20
|
* result so a caller never mistakes "not checked here" for "checked and passed".
|
|
21
21
|
*/
|
|
22
|
-
import { type CheckApplicability, type OptionalCheck, type SignatureOutcome } from './chain.js';
|
|
22
|
+
import { type CheckApplicability, type EvidenceBindingCounts, type OptionalCheck, type SignatureOutcome } from './chain.js';
|
|
23
23
|
import type { FailureCode } from './failures.js';
|
|
24
24
|
import type { AgentPublicKeyJwk } from './primitives.js';
|
|
25
|
+
import { type FederationKeyEntry } from './federation-wire.js';
|
|
25
26
|
import { type DistrustedKey, type KeyTrustReport, type PublishedKeyStatement, type Verdict } from './key-statements.js';
|
|
26
27
|
/** One entry of a `/audit-export` document. */
|
|
27
28
|
export interface AuditExportEntryInput {
|
|
@@ -57,6 +58,13 @@ export interface AuditExportEntryInput {
|
|
|
57
58
|
entryType?: string;
|
|
58
59
|
/** Denormalized row `payload` jsonb. Present → the binding-integrity check runs (verificationGuide step 4). */
|
|
59
60
|
payload?: Record<string, unknown>;
|
|
61
|
+
/**
|
|
62
|
+
* The evidence body `?evidence=true` inlines: the completion evidence on a
|
|
63
|
+
* COMPLETION_SUBMITTED entry, the filed payload on a DISPUTE_EVIDENCE entry.
|
|
64
|
+
* Unsigned. Present → the evidence-binding check re-hashes it against the
|
|
65
|
+
* signed `payload.evidenceHash` / `payload.payloadHash`.
|
|
66
|
+
*/
|
|
67
|
+
evidence?: Record<string, unknown>;
|
|
60
68
|
integrity: {
|
|
61
69
|
payloadHash: string;
|
|
62
70
|
previousHash: string | null;
|
|
@@ -195,6 +203,32 @@ export interface VerifyExportOptions {
|
|
|
195
203
|
* Anything that is not an Ed25519 JWK throws `TypeError`.
|
|
196
204
|
*/
|
|
197
205
|
agentKeys?: ReadonlyArray<AgentPublicKeyJwk>;
|
|
206
|
+
/**
|
|
207
|
+
* Federation keys of the Servers this one peers with, keyed by their hub id:
|
|
208
|
+
* `{ [hubId]: publicKey }` or `[{ hubId, publicKey }]`, each key as base64
|
|
209
|
+
* SPKI DER or base64 of the raw 32 bytes, as the peer registered it at
|
|
210
|
+
* handshake. Take them from the peer's operator, not from this Server.
|
|
211
|
+
*
|
|
212
|
+
* A receiving Server's FEDERATION_* entries seal the peer's message as the
|
|
213
|
+
* peer signed it (`payload.wire`). Every sealed message is held to its own
|
|
214
|
+
* body hash and to the entry that carries it; one from a hub listed here also
|
|
215
|
+
* has its signature re-verified under that key, which proves what the peer
|
|
216
|
+
* asserted from this export alone. A failure is
|
|
217
|
+
* CHAIN_FEDERATION_WIRE_INVALID. `result.federationWire` counts how many were
|
|
218
|
+
* present, how many were verified under a key, and how many failed. A key that is not an
|
|
219
|
+
* Ed25519 key throws `TypeError`.
|
|
220
|
+
*
|
|
221
|
+
* After a sender changes its federation key, entries from before the change
|
|
222
|
+
* seal the earlier key. Give the list form an entry's `history`, the
|
|
223
|
+
* sender's `GET /.well-known/agledger-federation-keys.json`, beside the key
|
|
224
|
+
* you pinned: every key the history links to the pin through successions
|
|
225
|
+
* both keys signed is trusted inside its window, placed by the message's
|
|
226
|
+
* signed `wire.timestamp`. A second entry for the hub may pin a key the
|
|
227
|
+
* history does not list, trusted on its own. A history that is another
|
|
228
|
+
* hub's, carries a statement that does not verify, or lists none of the
|
|
229
|
+
* hub's pins throws `TypeError`.
|
|
230
|
+
*/
|
|
231
|
+
federationKeys?: Readonly<Record<string, string>> | ReadonlyArray<FederationKeyEntry>;
|
|
198
232
|
}
|
|
199
233
|
export interface EntryVerificationResult {
|
|
200
234
|
position: number;
|
|
@@ -271,6 +305,28 @@ export interface VerifyExportResult {
|
|
|
271
305
|
present: number;
|
|
272
306
|
verified: number;
|
|
273
307
|
};
|
|
308
|
+
/**
|
|
309
|
+
* Federation messages sealed on the chain (`payload.wire`) vs re-verified
|
|
310
|
+
* under a `federationKeys` entry for their sender. Every present one held
|
|
311
|
+
* to its body hash and to its entry; `failed` counts those that failed a
|
|
312
|
+
* check, and `present - verified - failed` is the ones from a hub with no
|
|
313
|
+
* key supplied. `afterRetirement` counts verified ones sealed under a key
|
|
314
|
+
* the sender's history retired before the sender signed the message.
|
|
315
|
+
*/
|
|
316
|
+
federationWire: {
|
|
317
|
+
present: number;
|
|
318
|
+
verified: number;
|
|
319
|
+
failed: number;
|
|
320
|
+
afterRetirement: number;
|
|
321
|
+
};
|
|
322
|
+
/**
|
|
323
|
+
* Inlined evidence bodies (`?evidence=true`) vs re-bound to the hash their
|
|
324
|
+
* entry signs. A body that does not hash to it fails
|
|
325
|
+
* CHAIN_EVIDENCE_BINDING_MISMATCH; `clientHashed` counts encrypted-mode
|
|
326
|
+
* completions, whose signed hash covers a cleartext the export does not
|
|
327
|
+
* carry. See `ChainResult.evidenceBinding`.
|
|
328
|
+
*/
|
|
329
|
+
evidenceBinding: EvidenceBindingCounts;
|
|
274
330
|
/**
|
|
275
331
|
* `trusted`, `unanchored` or `failed` (see `Verdict`). Read this rather
|
|
276
332
|
* than `valid` alone: a valid result with no `trustAnchors`, or none that
|
package/dist/audit-export.js
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
import { buildAgentKeyRegistry, buildKeyRegistry, earliestKeyActivation, verifyChain, } from './chain.js';
|
|
23
23
|
import { instantMs } from './instant.js';
|
|
24
24
|
import { assertKnownOptions } from './options.js';
|
|
25
|
+
import { buildFederationKeyRegistry } from './federation-wire.js';
|
|
25
26
|
import { applyKeyTrust, assertNotPinnedAndDistrusted, computeKeyTrust, keyStatementsFromExport, statementsFromMap, reportKeyTrust, settleKeyTrust, verdictOf, } from './key-statements.js';
|
|
26
27
|
const SUPPORTED_FORMAT_VERSION = '2.0';
|
|
27
28
|
const SUPPORTED_CANONICALIZATION = 'RFC8949-CDE';
|
|
@@ -60,6 +61,7 @@ export function verifyAuditExport(exportData, given = {}) {
|
|
|
60
61
|
const resolvedKeys = resolveKeys(exportData, options);
|
|
61
62
|
let keys = buildKeyRegistry(resolvedKeys);
|
|
62
63
|
const agentKeys = options.agentKeys !== undefined ? buildAgentKeyRegistry(options.agentKeys) : undefined;
|
|
64
|
+
const federationKeys = options.federationKeys !== undefined ? buildFederationKeyRegistry(options.federationKeys) : undefined;
|
|
63
65
|
// An empty trustAnchors is the same as none: no walk, keyTrust 'no_anchor'.
|
|
64
66
|
const trust = options.trustAnchors !== undefined && options.trustAnchors.length > 0
|
|
65
67
|
? computeKeyTrust({
|
|
@@ -118,6 +120,11 @@ export function verifyAuditExport(exportData, given = {}) {
|
|
|
118
120
|
payload: e.payload,
|
|
119
121
|
};
|
|
120
122
|
}
|
|
123
|
+
// An inlined evidence body is unsigned; it is re-bound to the hash the
|
|
124
|
+
// entry signs, so a null or a non-object there fails rather than reading
|
|
125
|
+
// as no body at all.
|
|
126
|
+
if (e.evidence !== undefined && e.evidence !== null)
|
|
127
|
+
base.inlinedEvidence = { value: e.evidence };
|
|
121
128
|
// Actor attribution: the export's own guide tells an auditor that
|
|
122
129
|
// `actorId`/`actorOwnerId` ARE the trustworthy attribution (only
|
|
123
130
|
// actorDisplayName / actorOwnerType / humanReadableLabel are listed as
|
|
@@ -148,6 +155,7 @@ export function verifyAuditExport(exportData, given = {}) {
|
|
|
148
155
|
requireKeyId: options.requireKeyId,
|
|
149
156
|
requireSuppliedKeys: options.requireSuppliedKeys,
|
|
150
157
|
agentKeys,
|
|
158
|
+
federationKeys,
|
|
151
159
|
signingSince,
|
|
152
160
|
});
|
|
153
161
|
// Under a walk every key a signature verifies against is anchored, so the
|
|
@@ -183,11 +191,13 @@ export function verifyAuditExport(exportData, given = {}) {
|
|
|
183
191
|
keyProvenance: chain.keyProvenance,
|
|
184
192
|
unsignedProjectionFields: exportData.verificationGuide?.unsignedFields ?? [],
|
|
185
193
|
agentSignatures: chain.agentSignatures,
|
|
194
|
+
federationWire: chain.federationWire,
|
|
195
|
+
evidenceBinding: chain.evidenceBinding,
|
|
186
196
|
keyTrust,
|
|
187
197
|
verdict: verdictOf({ valid, keyTrust }),
|
|
188
198
|
};
|
|
189
199
|
}
|
|
190
|
-
const EXPORT_OPTIONS = ['publicKeys', 'requireKeyId', 'requireSuppliedKeys', 'trustAnchors', 'distrustedKeys', 'agentKeys'];
|
|
200
|
+
const EXPORT_OPTIONS = ['publicKeys', 'requireKeyId', 'requireSuppliedKeys', 'trustAnchors', 'distrustedKeys', 'agentKeys', 'federationKeys'];
|
|
191
201
|
function isKeysEnvelope(value) {
|
|
192
202
|
return isRecord(value) && Array.isArray(value.data);
|
|
193
203
|
}
|
|
@@ -264,10 +274,14 @@ function earlyFailure(recordId, totalEntries, detail) {
|
|
|
264
274
|
key_temporal: 'skipped_no_input',
|
|
265
275
|
agent_signature: 'skipped_no_input',
|
|
266
276
|
key_anchoring: 'skipped_no_input',
|
|
277
|
+
federation_wire: 'skipped_no_input',
|
|
278
|
+
evidence_binding: 'skipped_no_input',
|
|
267
279
|
},
|
|
268
280
|
keyProvenance: { supplied: 0, embedded: 0 },
|
|
269
281
|
unsignedProjectionFields: [],
|
|
270
282
|
agentSignatures: { present: 0, verified: 0 },
|
|
283
|
+
federationWire: { present: 0, verified: 0, failed: 0, afterRetirement: 0 },
|
|
284
|
+
evidenceBinding: { present: 0, verified: 0, clientHashed: 0, failed: 0 },
|
|
271
285
|
keyTrust: reportKeyTrust(new Map(), null, null),
|
|
272
286
|
verdict: 'failed',
|
|
273
287
|
};
|
package/dist/chain.d.ts
CHANGED
|
@@ -35,6 +35,7 @@
|
|
|
35
35
|
* `skipped` signature, reduced coverage rather than a break.
|
|
36
36
|
*/
|
|
37
37
|
import { type AgentPublicKeyJwk } from './primitives.js';
|
|
38
|
+
import { type FederationKeyRegistry } from './federation-wire.js';
|
|
38
39
|
import type { FailureCode } from './failures.js';
|
|
39
40
|
/**
|
|
40
41
|
* Where a verification key came from. `supplied`: the caller passed it (from
|
|
@@ -168,6 +169,15 @@ export interface NormalizedEntry {
|
|
|
168
169
|
actorRole: string | null;
|
|
169
170
|
actorOwnerId: string | null;
|
|
170
171
|
};
|
|
172
|
+
/**
|
|
173
|
+
* The evidence body an `?evidence=true` export inlines at the entry's
|
|
174
|
+
* `evidence` (export path). Present on the entry, however it is spelled, →
|
|
175
|
+
* the evidence-binding check runs: the body is an unsigned projection, and
|
|
176
|
+
* its authority comes only from hashing to the hash the entry signs.
|
|
177
|
+
*/
|
|
178
|
+
inlinedEvidence?: {
|
|
179
|
+
value: unknown;
|
|
180
|
+
};
|
|
171
181
|
}
|
|
172
182
|
/**
|
|
173
183
|
* Checks that run only when their input is present. `agent_signature` is
|
|
@@ -175,7 +185,7 @@ export interface NormalizedEntry {
|
|
|
175
185
|
* had its cert key supplied by the caller (`agentKeys`); neither the export
|
|
176
186
|
* nor the dump carries cert public keys.
|
|
177
187
|
*/
|
|
178
|
-
export type OptionalCheck = 'payload_binding' | 'oidc_actor' | 'actor_attribution' | 'key_temporal' | 'agent_signature' | 'key_anchoring';
|
|
188
|
+
export type OptionalCheck = 'payload_binding' | 'oidc_actor' | 'actor_attribution' | 'key_temporal' | 'agent_signature' | 'key_anchoring' | 'federation_wire' | 'evidence_binding';
|
|
179
189
|
/**
|
|
180
190
|
* `applied`: the check ran. `skipped_no_input`: the input it needs is absent.
|
|
181
191
|
* `not_checked`: the input was given but no entry reached the check, because
|
|
@@ -304,6 +314,45 @@ export interface ChainResult {
|
|
|
304
314
|
present: number;
|
|
305
315
|
verified: number;
|
|
306
316
|
};
|
|
317
|
+
/**
|
|
318
|
+
* Federation messages sealed on this chain (`payload.wire` on a receiving
|
|
319
|
+
* Server's FEDERATION_* entries). `present` counts entries that passed every
|
|
320
|
+
* other check and carry one, each held to its own body hash and to the entry
|
|
321
|
+
* that carries it; `verified` counts those whose sealed signature was also
|
|
322
|
+
* checked under a `federationKeys` entry for the sending hub and found good;
|
|
323
|
+
* `failed` counts those that failed a check (a body hash, the entry, or the
|
|
324
|
+
* signature under the key given for the hub). `present - verified - failed`
|
|
325
|
+
* is the messages from a hub with no key supplied. `afterRetirement`
|
|
326
|
+
* counts verified ones sealed under a key the sender's history retired
|
|
327
|
+
* before the sender signed the message (see `FederationWireOutcome`): in
|
|
328
|
+
* order when the receiver revoked the peer after them, so check its
|
|
329
|
+
* `federation.peer_revoked` audit row.
|
|
330
|
+
*/
|
|
331
|
+
federationWire: {
|
|
332
|
+
present: number;
|
|
333
|
+
verified: number;
|
|
334
|
+
failed: number;
|
|
335
|
+
afterRetirement: number;
|
|
336
|
+
};
|
|
337
|
+
/**
|
|
338
|
+
* Evidence bodies an `?evidence=true` export inlines (`entries[].evidence`
|
|
339
|
+
* on COMPLETION_SUBMITTED and DISPUTE_EVIDENCE). `present` counts entries
|
|
340
|
+
* that passed every other check and carry one; `verified` those whose body
|
|
341
|
+
* hashes, under RFC 8785 and SHA-256, to the signed `payload.evidenceHash`
|
|
342
|
+
* or `payload.payloadHash`; `clientHashed` those on an encrypted-mode
|
|
343
|
+
* completion (`payload.verifiedBy: "client"`), whose signed hash covers a
|
|
344
|
+
* cleartext the export does not carry, so the inlined ciphertext cannot be
|
|
345
|
+
* re-bound offline; `failed` those that did not hash to it, or sit where
|
|
346
|
+
* nothing signed binds a body. Always zero on a dump, which carries none.
|
|
347
|
+
*/
|
|
348
|
+
evidenceBinding: EvidenceBindingCounts;
|
|
349
|
+
}
|
|
350
|
+
/** See {@link ChainResult.evidenceBinding}. */
|
|
351
|
+
export interface EvidenceBindingCounts {
|
|
352
|
+
present: number;
|
|
353
|
+
verified: number;
|
|
354
|
+
clientHashed: number;
|
|
355
|
+
failed: number;
|
|
307
356
|
}
|
|
308
357
|
export interface VerifyChainOptions {
|
|
309
358
|
/** Require every entry's signingKeyId to equal this id (else CHAIN_KEY_POLICY_VIOLATION). */
|
|
@@ -323,6 +372,14 @@ export interface VerifyChainOptions {
|
|
|
323
372
|
* offline; a failure is CHAIN_AGENT_SIGNATURE_INVALID.
|
|
324
373
|
*/
|
|
325
374
|
agentKeys?: AgentKeyRegistry;
|
|
375
|
+
/**
|
|
376
|
+
* Sending hubs' federation keys (see `buildFederationKeyRegistry`). An entry
|
|
377
|
+
* that seals a peer's message (`payload.wire`) from a hub listed here has
|
|
378
|
+
* that message's signature re-verified under the key; a failure is
|
|
379
|
+
* CHAIN_FEDERATION_WIRE_INVALID. The hash and the entry's agreement with
|
|
380
|
+
* the sealed body are checked on every sealed message, with or without a key.
|
|
381
|
+
*/
|
|
382
|
+
federationKeys?: FederationKeyRegistry;
|
|
326
383
|
/**
|
|
327
384
|
* The instant this install began signing: the earliest `activatedAt` across
|
|
328
385
|
* its whole signing key set, retired keys included. An entry with a null
|
package/dist/chain.js
CHANGED
|
@@ -35,6 +35,8 @@
|
|
|
35
35
|
* `skipped` signature, reduced coverage rather than a break.
|
|
36
36
|
*/
|
|
37
37
|
import { buildPredicateForRow, decodeCoseSign1, decodePredicate, deepEqual, describeUnsupportedAlgorithm, ed25519JwkThumbprint, ed25519JwkToSpki, extractAgentSignatureClaim, extractActorClaim, extractChainClaim, extractKid, extractOnBehalfOfClaim, resolveKeyAlgorithm, sha256Hex, stripEnvelopeExtensions, envelopeExtensionsMatch, verifyAgentSignature, verifyCoseSign1, } from './primitives.js';
|
|
38
|
+
import { canonicalizeJson, checkFederationWire, extractFederationWire } from './federation-wire.js';
|
|
39
|
+
import { createHash } from 'node:crypto';
|
|
38
40
|
import { instantMs, rfc3339Ms } from './instant.js';
|
|
39
41
|
import { assertKnownOptions } from './options.js';
|
|
40
42
|
/**
|
|
@@ -148,7 +150,7 @@ function positionKey(position) {
|
|
|
148
150
|
* validates the true chain; tampering surfaces through the hash links).
|
|
149
151
|
*/
|
|
150
152
|
export function verifyChain(entries, keys, options = {}) {
|
|
151
|
-
assertKnownOptions('verifyChain', options, ['requireKeyId', 'requireSuppliedKeys', 'agentKeys', 'signingSince']);
|
|
153
|
+
assertKnownOptions('verifyChain', options, ['requireKeyId', 'requireSuppliedKeys', 'agentKeys', 'federationKeys', 'signingSince']);
|
|
152
154
|
const scopeId = entries[0]?.scopeId ?? '(empty)';
|
|
153
155
|
const sorted = entries
|
|
154
156
|
.map((entry, at) => ({ entry, at, key: positionKey(entry.chainPosition) }))
|
|
@@ -163,9 +165,13 @@ export function verifyChain(entries, keys, options = {}) {
|
|
|
163
165
|
key_temporal: 'skipped_no_input',
|
|
164
166
|
agent_signature: 'skipped_no_input',
|
|
165
167
|
key_anchoring: 'skipped_no_input',
|
|
168
|
+
federation_wire: 'skipped_no_input',
|
|
169
|
+
evidence_binding: 'skipped_no_input',
|
|
166
170
|
};
|
|
167
171
|
const keyProvenance = { supplied: 0, embedded: 0 };
|
|
168
172
|
const agentSignatures = { present: 0, verified: 0 };
|
|
173
|
+
const federationWire = { present: 0, verified: 0, failed: 0, afterRetirement: 0 };
|
|
174
|
+
const evidenceBinding = { present: 0, verified: 0, clientHashed: 0, failed: 0 };
|
|
169
175
|
let verifiedEntries = 0;
|
|
170
176
|
let brokenAt;
|
|
171
177
|
const accounted = [];
|
|
@@ -182,6 +188,8 @@ export function verifyChain(entries, keys, options = {}) {
|
|
|
182
188
|
optionalChecks,
|
|
183
189
|
keyProvenance,
|
|
184
190
|
agentSignatures,
|
|
191
|
+
federationWire,
|
|
192
|
+
evidenceBinding,
|
|
185
193
|
};
|
|
186
194
|
}
|
|
187
195
|
let signingSince;
|
|
@@ -207,6 +215,12 @@ export function verifyChain(entries, keys, options = {}) {
|
|
|
207
215
|
if (result.valid && result.accounted === undefined) {
|
|
208
216
|
result = checkAgentSignature(entry, result, options.agentKeys, optionalChecks, agentSignatures);
|
|
209
217
|
}
|
|
218
|
+
if (result.valid && result.accounted === undefined && entry.binding !== undefined) {
|
|
219
|
+
result = checkSealedFederationWire(entry, result, options.federationKeys, optionalChecks, federationWire);
|
|
220
|
+
}
|
|
221
|
+
if (result.valid && result.accounted === undefined && entry.inlinedEvidence !== undefined) {
|
|
222
|
+
result = checkInlinedEvidence(entry, result, optionalChecks, evidenceBinding);
|
|
223
|
+
}
|
|
210
224
|
entryResults.push(result);
|
|
211
225
|
if (result.accounted !== undefined) {
|
|
212
226
|
accounted.push({
|
|
@@ -260,7 +274,87 @@ export function verifyChain(entries, keys, options = {}) {
|
|
|
260
274
|
optionalChecks,
|
|
261
275
|
keyProvenance,
|
|
262
276
|
agentSignatures,
|
|
277
|
+
federationWire,
|
|
278
|
+
evidenceBinding,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
/** The payload field each entry type signs an inlined evidence body's hash under. */
|
|
282
|
+
const EVIDENCE_HASH_FIELD = {
|
|
283
|
+
COMPLETION_SUBMITTED: 'evidenceHash',
|
|
284
|
+
DISPUTE_EVIDENCE: 'payloadHash',
|
|
285
|
+
};
|
|
286
|
+
/**
|
|
287
|
+
* Re-bind an inlined evidence body to the hash its entry signs, on an entry
|
|
288
|
+
* that already passed every other check (so `binding.payload` is what the
|
|
289
|
+
* Server signed): SHA-256 hex over the RFC 8785 form of the body, the
|
|
290
|
+
* Server's `hashPayload`, against `payload.evidenceHash` (completion) or
|
|
291
|
+
* `payload.payloadHash` (dispute evidence). An encrypted-mode completion
|
|
292
|
+
* signs a hash its submitter computed over the cleartext, and the export
|
|
293
|
+
* inlines the ciphertext, so it is counted and left unbound.
|
|
294
|
+
*/
|
|
295
|
+
function checkInlinedEvidence(entry, result, optionalChecks, counts) {
|
|
296
|
+
optionalChecks.evidence_binding = 'applied';
|
|
297
|
+
counts.present++;
|
|
298
|
+
const failed = (detail) => {
|
|
299
|
+
counts.failed++;
|
|
300
|
+
return failAfterSignature(entry, result, 'CHAIN_EVIDENCE_BINDING_MISMATCH', detail);
|
|
263
301
|
};
|
|
302
|
+
const body = entry.inlinedEvidence.value;
|
|
303
|
+
if (entry.binding === undefined) {
|
|
304
|
+
return failed('The entry inlines an evidence body but carries no payload, so no signed hash binds the body to the chain.');
|
|
305
|
+
}
|
|
306
|
+
const { entryType, payload } = entry.binding;
|
|
307
|
+
const field = EVIDENCE_HASH_FIELD[entryType];
|
|
308
|
+
if (field === undefined) {
|
|
309
|
+
return failed(`A ${entryType} entry inlines an evidence body. The Server inlines evidence only on COMPLETION_SUBMITTED and DISPUTE_EVIDENCE entries, and nothing this entry signs binds a body.`);
|
|
310
|
+
}
|
|
311
|
+
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
|
|
312
|
+
return failed(`The inlined evidence is ${body === null ? 'null' : Array.isArray(body) ? 'an array' : typeof body}, not the JSON object the entry's payload.${field} was computed over.`);
|
|
313
|
+
}
|
|
314
|
+
const signed = payload[field];
|
|
315
|
+
if (typeof signed !== 'string' || !/^[0-9a-f]{64}$/i.test(signed)) {
|
|
316
|
+
return failed(`The entry inlines an evidence body but signs no payload.${field} to bind it to.`);
|
|
317
|
+
}
|
|
318
|
+
if (entryType === 'COMPLETION_SUBMITTED' && payload.verifiedBy === 'client') {
|
|
319
|
+
counts.clientHashed++;
|
|
320
|
+
return result;
|
|
321
|
+
}
|
|
322
|
+
const digest = createHash('sha256').update(canonicalizeJson(body), 'utf8').digest('hex');
|
|
323
|
+
if (digest !== signed.toLowerCase()) {
|
|
324
|
+
return failed(`The inlined evidence body hashes to ${digest} under RFC 8785 and SHA-256, and the entry signs payload.${field} ${signed.toLowerCase()}: the body was edited after export, or is not the one submitted.`);
|
|
325
|
+
}
|
|
326
|
+
counts.verified++;
|
|
327
|
+
return result;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* The sealed federation message on an entry that already passed every other
|
|
331
|
+
* check (so `binding.payload` is what the receiver signed): its body hash,
|
|
332
|
+
* its agreement with the entry, and, under a supplied key for the sending
|
|
333
|
+
* hub, its signature. See `federation-wire.ts`.
|
|
334
|
+
*/
|
|
335
|
+
function checkSealedFederationWire(entry, result, federationKeys, optionalChecks, counts) {
|
|
336
|
+
if (entry.binding === undefined)
|
|
337
|
+
return result;
|
|
338
|
+
const wire = extractFederationWire(entry.binding.payload);
|
|
339
|
+
if (wire === null)
|
|
340
|
+
return result;
|
|
341
|
+
optionalChecks.federation_wire = 'applied';
|
|
342
|
+
if (wire === 'malformed') {
|
|
343
|
+
return failAfterSignature(entry, result, 'CHAIN_FEDERATION_WIRE_INVALID', 'payload.wire is present but is not a sealed federation message (an object with scheme, senderHubId, senderPublicKey, recipientHubId, method, path, bodyHash, timestamp, nonce, signature and an object body).');
|
|
344
|
+
}
|
|
345
|
+
counts.present++;
|
|
346
|
+
const outcome = checkFederationWire(entry.binding.entryType, entry.binding.recordId, entry.binding.payload, wire, federationKeys);
|
|
347
|
+
if (outcome.outcome === 'ok') {
|
|
348
|
+
if (outcome.signatureChecked)
|
|
349
|
+
counts.verified++;
|
|
350
|
+
if (outcome.afterRetirement)
|
|
351
|
+
counts.afterRetirement++;
|
|
352
|
+
return result;
|
|
353
|
+
}
|
|
354
|
+
if (outcome.outcome === 'unchecked')
|
|
355
|
+
return result;
|
|
356
|
+
counts.failed++;
|
|
357
|
+
return failAfterSignature(entry, result, outcome.outcome === 'unsupported' ? 'CHAIN_UNSUPPORTED_ALGORITHM' : 'CHAIN_FEDERATION_WIRE_INVALID', outcome.detail);
|
|
264
358
|
}
|
|
265
359
|
/**
|
|
266
360
|
* Offline re-check of a sealed agent signature, on an entry that already
|
|
@@ -293,11 +387,11 @@ function checkAgentSignature(entry, result, agentKeys, optionalChecks, counts) {
|
|
|
293
387
|
}
|
|
294
388
|
const certLabel = claim.certId ?? claim.certThumbprint;
|
|
295
389
|
if (outcome === 'unsupported') {
|
|
296
|
-
return
|
|
390
|
+
return failAfterSignature(entry, result, 'CHAIN_UNSUPPORTED_ALGORITHM', `Agent signature for cert ${certLabel} could not be checked: this host cannot compute Ed25519 (an active OpenSSL FIPS provider carries no EdDSA). Not verified, and not tamper evidence.`);
|
|
297
391
|
}
|
|
298
|
-
return
|
|
392
|
+
return failAfterSignature(entry, result, 'CHAIN_AGENT_SIGNATURE_INVALID', outcome === 'malformed'
|
|
299
393
|
? `Sealed agent_signature for cert ${certLabel} has a shape nothing can verify (alg must be EdDSA, content_hash sha256:<hex64>, signature 64 bytes of standard base64).`
|
|
300
|
-
: `Sealed agent_signature for cert ${certLabel} does not verify under the supplied key with thumbprint ${claim.certThumbprint}
|
|
394
|
+
: `Sealed agent_signature for cert ${certLabel} does not verify under the supplied key with thumbprint ${claim.certThumbprint}.`);
|
|
301
395
|
}
|
|
302
396
|
function accountedResult(scopeId, position, detail) {
|
|
303
397
|
return { scopeId, position, valid: true, accounted: { code: ACCOUNTED_ENTRY_CODE, detail }, signature: 'accounted' };
|
|
@@ -309,8 +403,16 @@ function declaredAlgorithmLies(key) {
|
|
|
309
403
|
const keyAlg = resolveKeyAlgorithm(key.spkiBase64);
|
|
310
404
|
return typeof keyAlg === 'object' && keyAlg.name.toLowerCase() !== key.algorithm.toLowerCase();
|
|
311
405
|
}
|
|
312
|
-
function fail(scopeId, position, code, detail, signature = 'not-checked') {
|
|
313
|
-
return { scopeId, position, valid: false, failure: { code, detail }, signature };
|
|
406
|
+
function fail(scopeId, position, code, detail, signature = 'not-checked', keySource) {
|
|
407
|
+
return { scopeId, position, valid: false, failure: { code, detail }, signature, ...(keySource !== undefined ? { keySource } : {}) };
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Fail an entry a check after the signature check refused: it keeps the
|
|
411
|
+
* signature state and the key it verified under, so `keyProvenance` still
|
|
412
|
+
* counts every signed entry (`signed = supplied + embedded`).
|
|
413
|
+
*/
|
|
414
|
+
function failAfterSignature(entry, result, code, detail) {
|
|
415
|
+
return fail(entry.scopeId, result.position, code, detail, result.signature, result.keySource);
|
|
314
416
|
}
|
|
315
417
|
function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, optionalChecks, mustSign) {
|
|
316
418
|
const { scopeId } = entry;
|
package/dist/failures.d.ts
CHANGED
|
@@ -83,6 +83,6 @@
|
|
|
83
83
|
* run offline is the agent signature, and only when the caller supplies the
|
|
84
84
|
* cert's public key (CHAIN_AGENT_SIGNATURE_INVALID below).
|
|
85
85
|
*/
|
|
86
|
-
export type FailureCode = 'UNSUPPORTED_FORMAT' | 'CHAIN_EMPTY' | 'CHAIN_POSITION_GAP' | 'CHAIN_GENESIS_INVALID' | 'CHAIN_LINK_BROKEN' | 'CHAIN_HASH_MISMATCH' | 'CHAIN_MALFORMED_ENTRY' | 'CHAIN_COSE_DECODE_FAILED' | 'CHAIN_COSE_HEADER_MISMATCH' | 'CHAIN_PAYLOAD_BINDING_MISMATCH' | 'CHAIN_OIDC_ACTOR_MISMATCH' | 'CHAIN_SIGNATURE_INVALID' | 'CHAIN_SIGNATURE_MISSING_KEY' | 'CHAIN_KEY_POLICY_VIOLATION' | 'CHAIN_KEY_EXPIRED' | 'CHAIN_KEY_NOT_YET_ACTIVE' | 'CHAIN_ALG_MISMATCH' | 'CHAIN_UNSUPPORTED_ALGORITHM' | 'CHAIN_SIGNING_KEY_DRIFT' | 'CHAIN_ACTOR_ATTRIBUTION_MISMATCH' | 'CHAIN_AGENT_SIGNATURE_INVALID' | 'CHAIN_ENTRY_UNSIGNED' | 'CHAIN_SIGNING_KEY_UNANCHORED' | 'CHAIN_KEY_WINDOW_DRIFT' | 'CHECKPOINT_ROW_MISSING' | 'CHECKPOINT_HASH_MISMATCH' | 'CHECKPOINT_SIGNATURE_INVALID' | 'CHECKPOINT_UNSIGNED' | 'CHECKPOINT_KEY_UNANCHORED' | 'CHECKPOINT_CLAIM_MISMATCH' | 'TENANT_READ_LEAF_HASH_MISMATCH' | 'TENANT_READ_LEAF_INDEX_GAP' | 'TENANT_READ_SIGNATURE_INVALID' | 'TENANT_READ_LEAF_UNSIGNED' | 'TENANT_READ_KEY_UNANCHORED' | 'TENANT_READ_CLAIM_MISMATCH' | 'TENANT_CHECKPOINT_LEAF_COUNT_MISMATCH' | 'TENANT_CHECKPOINT_ROOT_MISMATCH' | 'TENANT_CHECKPOINT_SIGNATURE_INVALID' | 'TENANT_CHECKPOINT_UNSIGNED' | 'TENANT_CHECKPOINT_KEY_UNANCHORED' | 'TENANT_CHECKPOINT_CLAIM_MISMATCH' | 'TENANT_CHECKPOINT_FORK' | 'KEY_STATEMENT_INVALID' | 'KEY_CLOSURE_INVALID';
|
|
86
|
+
export type FailureCode = 'UNSUPPORTED_FORMAT' | 'CHAIN_EMPTY' | 'CHAIN_POSITION_GAP' | 'CHAIN_GENESIS_INVALID' | 'CHAIN_LINK_BROKEN' | 'CHAIN_HASH_MISMATCH' | 'CHAIN_MALFORMED_ENTRY' | 'CHAIN_COSE_DECODE_FAILED' | 'CHAIN_COSE_HEADER_MISMATCH' | 'CHAIN_PAYLOAD_BINDING_MISMATCH' | 'CHAIN_OIDC_ACTOR_MISMATCH' | 'CHAIN_SIGNATURE_INVALID' | 'CHAIN_SIGNATURE_MISSING_KEY' | 'CHAIN_KEY_POLICY_VIOLATION' | 'CHAIN_KEY_EXPIRED' | 'CHAIN_KEY_NOT_YET_ACTIVE' | 'CHAIN_ALG_MISMATCH' | 'CHAIN_UNSUPPORTED_ALGORITHM' | 'CHAIN_SIGNING_KEY_DRIFT' | 'CHAIN_ACTOR_ATTRIBUTION_MISMATCH' | 'CHAIN_AGENT_SIGNATURE_INVALID' | 'CHAIN_FEDERATION_WIRE_INVALID' | 'CHAIN_EVIDENCE_BINDING_MISMATCH' | 'CHAIN_ENTRY_UNSIGNED' | 'CHAIN_SIGNING_KEY_UNANCHORED' | 'CHAIN_KEY_WINDOW_DRIFT' | 'CHECKPOINT_ROW_MISSING' | 'CHECKPOINT_HASH_MISMATCH' | 'CHECKPOINT_SIGNATURE_INVALID' | 'CHECKPOINT_UNSIGNED' | 'CHECKPOINT_KEY_UNANCHORED' | 'CHECKPOINT_CLAIM_MISMATCH' | 'TENANT_READ_LEAF_HASH_MISMATCH' | 'TENANT_READ_LEAF_INDEX_GAP' | 'TENANT_READ_SIGNATURE_INVALID' | 'TENANT_READ_LEAF_UNSIGNED' | 'TENANT_READ_KEY_UNANCHORED' | 'TENANT_READ_CLAIM_MISMATCH' | 'TENANT_CHECKPOINT_LEAF_COUNT_MISMATCH' | 'TENANT_CHECKPOINT_ROOT_MISMATCH' | 'TENANT_CHECKPOINT_SIGNATURE_INVALID' | 'TENANT_CHECKPOINT_UNSIGNED' | 'TENANT_CHECKPOINT_KEY_UNANCHORED' | 'TENANT_CHECKPOINT_CLAIM_MISMATCH' | 'TENANT_CHECKPOINT_FORK' | 'KEY_STATEMENT_INVALID' | 'KEY_CLOSURE_INVALID';
|
|
87
87
|
/** The actionable next step for a failure code. */
|
|
88
88
|
export declare function suggestion(code: FailureCode): string;
|
package/dist/failures.js
CHANGED
|
@@ -109,6 +109,8 @@ const SUGGESTIONS = {
|
|
|
109
109
|
CHAIN_SIGNING_KEY_DRIFT: 'The entry\'s signingKeyId column names a different key than the signature-covered kid in the COSE protected header. The column is a denormalized convenience and was rewritten after signing (possibly to point verification at another key). Trust the signed kid; treat the row as tampered.',
|
|
110
110
|
CHAIN_ACTOR_ATTRIBUTION_MISMATCH: 'The entry\'s actorId / actorOwnerId columns name a different actor than the signature-covered actor claim in the COSE protected header (CWT_Claims label 15, private label -65539). The columns are the projection a report displays and they were rewritten after signing, re-attributing the action to another actor. Trust the signed claim; treat the row as tampered and re-obtain the export from the operator.',
|
|
111
111
|
CHAIN_AGENT_SIGNATURE_INVALID: 'The agent signature sealed in predicate.on_behalf_of.agent_signature does not verify under the supplied key whose RFC 7638 thumbprint the entry itself names, or is sealed in a shape nothing can verify. The engine checks this signature at intake and the envelope signature says the engine wrote it, so this is not a caller mistake: treat the agent attribution of this entry as unproven and escalate to the operator.',
|
|
112
|
+
CHAIN_FEDERATION_WIRE_INVALID: 'The federation message sealed in payload.wire does not hold: its body no longer hashes to the bodyHash the sender signed, the entry asserts a state, type, recommendation or dispute the sealed body does not carry, or (under the sender\'s federation key you supplied) the signature does not verify or the sealed senderPublicKey is not that key. The receiving Server verified the message at intake and signed this entry, so this is not a caller mistake: treat what the entry says the peer asserted as unproven and escalate to both operators.',
|
|
113
|
+
CHAIN_EVIDENCE_BINDING_MISMATCH: 'An evidence body inlined in the export (entries[].evidence, from ?evidence=true) does not hash to the payload.evidenceHash or payload.payloadHash its entry signs, or sits on an entry that signs no such hash. The body is an unsigned projection whose only authority is that hash, so it was edited after export or attached where it does not belong. Trust the signed hash, not the body: re-obtain the evidence from the operator and re-bind it (SHA-256 over its RFC 8785 form).',
|
|
112
114
|
CHAIN_ENTRY_UNSIGNED: 'The entry carries no signing key id where the install could not have written an unsigned entry: after a signed entry in the same chain, or at or after the earliest activation time in the signing key set (retired keys included). From that instant every writer holds a registered key, so this is what a writer without one leaves on the chain, or a signed row whose key id was nulled. Treat the entry as forged and escalate to the operator. Unsigned entries from before the first key activation stay reduced signature coverage, not a break.',
|
|
113
115
|
CHAIN_SIGNING_KEY_UNANCHORED: 'The entry is signed by a key that no signed key statement links to a trust anchor you pinned. Anything with write access to the Server\'s database can register a key and sign entries with it; what it cannot write is a statement signed by a key you trust. Treat the entry as forged. If the key is one you vouch for, pin it (trustAnchors) from a source outside the Server, never from the document that served it.',
|
|
114
116
|
CHAIN_KEY_WINDOW_DRIFT: 'A key registry column (activatedAt, retiredAt or status in a dump row or key document) differs from the value its signed key statements carry. The signed value is the one entries are graded against; the column was rewritten, or the retirement was written without its closure statement. Treat the registry as tampered and compare it with the Server\'s own scan (key_window_drift). Where the detail names a distrust entry the listing says the Server applies (distrustedFrom, VAULT_DISTRUSTED_KEYS), the listed retirement may be that entry\'s cut, which the verifier was not given or was given at another instant; the listing\'s word is unsigned, so it stays tampering until the Server\'s operator confirms the entry.',
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
export declare const FEDERATION_WIRE_SCHEME = "agledger.federation.v2";
|
|
2
|
+
/** The sealed message as the receiver stores it under `payload.wire`. */
|
|
3
|
+
export interface FederationWire {
|
|
4
|
+
scheme: string;
|
|
5
|
+
senderHubId: string;
|
|
6
|
+
/** The sender's Ed25519 key as registered at handshake: base64 SPKI DER, or base64 of the raw 32 bytes. */
|
|
7
|
+
senderPublicKey: string;
|
|
8
|
+
recipientHubId: string;
|
|
9
|
+
method: string;
|
|
10
|
+
path: string;
|
|
11
|
+
/** SHA-256 hex over the RFC 8785 canonical JSON of `body`. */
|
|
12
|
+
bodyHash: string;
|
|
13
|
+
timestamp: string;
|
|
14
|
+
nonce: string;
|
|
15
|
+
/** Hex Ed25519 signature over the sign-input. */
|
|
16
|
+
signature: string;
|
|
17
|
+
/** The request body as received, the bytes `bodyHash` covers. */
|
|
18
|
+
body: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
/** The domain a federation key statement's signatures sign under. */
|
|
21
|
+
export declare const FEDERATION_KEY_STATEMENT_DOMAIN = "agledger.federation.key-statement.v1";
|
|
22
|
+
/** One statement of a {@link FederationKeyHistoryDocument}, as served. */
|
|
23
|
+
export interface FederationKeyHistoryStatement {
|
|
24
|
+
id: string;
|
|
25
|
+
kind: string;
|
|
26
|
+
/** The RFC 8785 (JCS) bytes both signatures cover, after the domain and a colon. */
|
|
27
|
+
payload: string;
|
|
28
|
+
subjectSignature: string;
|
|
29
|
+
predecessorSignature: string | null;
|
|
30
|
+
createdAt?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A publisher's `GET /.well-known/agledger-federation-keys.json`, as served.
|
|
34
|
+
* Only `hubId`, `statementDomain` and the signed `statements` are read: the
|
|
35
|
+
* `keys` summary is the publisher's own unsigned reading of them, so the
|
|
36
|
+
* windows are taken from the statements instead.
|
|
37
|
+
*/
|
|
38
|
+
export interface FederationKeyHistoryDocument {
|
|
39
|
+
hubId: string | null;
|
|
40
|
+
statementDomain: string;
|
|
41
|
+
statements: ReadonlyArray<FederationKeyHistoryStatement>;
|
|
42
|
+
anchoredFrom?: string | null;
|
|
43
|
+
keys?: unknown;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* One federation key a sender hub is trusted under, base64 SPKI DER, with the
|
|
47
|
+
* window its signed statements give it. Both bounds are null for a key given
|
|
48
|
+
* without a history: it is trusted at any time, as before histories existed.
|
|
49
|
+
*/
|
|
50
|
+
export interface FederationTrustedKey {
|
|
51
|
+
publicKey: string;
|
|
52
|
+
/** When the key took over; null when no signed statement bounds it from below. */
|
|
53
|
+
activatedAt: string | null;
|
|
54
|
+
/** When the next key took over; null while no succession signed by this key and its successor ends it. */
|
|
55
|
+
retiredAt: string | null;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Sender hub id to the federation keys its messages are trusted under, as
|
|
59
|
+
* `buildFederationKeyRegistry` builds it: each pinned key, and with a history
|
|
60
|
+
* every key linked to a pin by successions both keys signed.
|
|
61
|
+
*/
|
|
62
|
+
export type FederationKeyRegistry = ReadonlyMap<string, ReadonlyArray<FederationTrustedKey>>;
|
|
63
|
+
/**
|
|
64
|
+
* One sender's federation key, the list shape `buildFederationKeyRegistry`
|
|
65
|
+
* takes. `publicKey` is a key you hold for the hub by other means (the
|
|
66
|
+
* `signingPublicKey` your peer row holds, or one its operator confirmed);
|
|
67
|
+
* with `history`, the publisher's key-history document, every earlier or later
|
|
68
|
+
* key a chain of successions links to it is trusted too, inside its window. A
|
|
69
|
+
* hub may be named more than once, to pin keys no succession links: a key
|
|
70
|
+
* listed `linked: false`, or a key the history does not list at all (one in
|
|
71
|
+
* use before a change made with neither predecessor setting), which is then
|
|
72
|
+
* trusted on its own at any time. At least one pin for a hub with a history
|
|
73
|
+
* must be a key that history lists.
|
|
74
|
+
*/
|
|
75
|
+
export interface FederationKeyEntry {
|
|
76
|
+
hubId: string;
|
|
77
|
+
publicKey: string;
|
|
78
|
+
history?: FederationKeyHistoryDocument;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* A federation key as base64 SPKI DER, from either form the Server's peer
|
|
82
|
+
* table holds: SPKI DER, or the raw 32-byte key. Returns null for anything
|
|
83
|
+
* that is neither (so a caller refuses it by name rather than verifying
|
|
84
|
+
* nothing under it).
|
|
85
|
+
*/
|
|
86
|
+
export declare function normalizeFederationKey(publicKeyBase64: string): string | null;
|
|
87
|
+
/**
|
|
88
|
+
* Build the registry from `{ [hubId]: publicKey }` or
|
|
89
|
+
* `[{ hubId, publicKey, history? }]`. Throws `TypeError` naming the entry on
|
|
90
|
+
* any key that is not an Ed25519 key in one of the two forms, and on a history
|
|
91
|
+
* that is another hub's, carries a statement that does not verify, or lists
|
|
92
|
+
* none of the keys pinned for its hub, so a bad input is refused before any verification
|
|
93
|
+
* runs rather than reported as a signature failure.
|
|
94
|
+
*/
|
|
95
|
+
export declare function buildFederationKeyRegistry(input: Readonly<Record<string, string>> | ReadonlyArray<FederationKeyEntry>): FederationKeyRegistry;
|
|
96
|
+
/**
|
|
97
|
+
* RFC 8785 (JCS) canonical JSON, as the Server's `canonicalize` writes it:
|
|
98
|
+
* object keys sorted by code unit, no whitespace, `undefined` members dropped
|
|
99
|
+
* (an array element that is `undefined` serializes as `null`), `-0` as `0`,
|
|
100
|
+
* non-finite numbers as `null`. Numbers take JavaScript's own shortest form,
|
|
101
|
+
* which is what RFC 8785 specifies.
|
|
102
|
+
*/
|
|
103
|
+
export declare function canonicalizeJson(value: unknown): string;
|
|
104
|
+
/** The sign-input the Server builds, a colon-joined line under the scheme. */
|
|
105
|
+
export declare function federationSignInput(wire: FederationWire): string;
|
|
106
|
+
/**
|
|
107
|
+
* The `wire` a row payload carries, or null when it carries none. A `wire`
|
|
108
|
+
* that is present but is not an object is returned as `malformed`, so the
|
|
109
|
+
* caller fails it rather than reading an edited row as one with no message.
|
|
110
|
+
*/
|
|
111
|
+
export declare function extractFederationWire(payload: Record<string, unknown>): FederationWire | 'malformed' | null;
|
|
112
|
+
export type FederationWireOutcome =
|
|
113
|
+
/**
|
|
114
|
+
* The hash, the entry's fields and, under a supplied key, the signature all
|
|
115
|
+
* hold. `afterRetirement`: the key the message is sealed under was retired,
|
|
116
|
+
* by a succession it signed, before the sender signed the message. The
|
|
117
|
+
* receiver accepts the old key until it revokes the peer, so a publisher
|
|
118
|
+
* process not yet restarted onto the new key sends exactly this; it is in
|
|
119
|
+
* order when the receiver's `federation.peer_revoked` audit row for the
|
|
120
|
+
* publisher comes after the entry.
|
|
121
|
+
*/
|
|
122
|
+
{
|
|
123
|
+
outcome: 'ok';
|
|
124
|
+
signatureChecked: boolean;
|
|
125
|
+
afterRetirement: boolean;
|
|
126
|
+
}
|
|
127
|
+
/** No key was supplied for `senderHubId`; the hash and the entry's fields hold, the signature was not checked. */
|
|
128
|
+
| {
|
|
129
|
+
outcome: 'unchecked';
|
|
130
|
+
} | {
|
|
131
|
+
outcome: 'invalid';
|
|
132
|
+
detail: string;
|
|
133
|
+
}
|
|
134
|
+
/** A key was supplied but this host cannot compute Ed25519. */
|
|
135
|
+
| {
|
|
136
|
+
outcome: 'unsupported';
|
|
137
|
+
detail: string;
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* Check one sealed message against the entry that carries it, and under the
|
|
141
|
+
* sender's key when `keys` has one for `wire.senderHubId`.
|
|
142
|
+
*
|
|
143
|
+
* Runs on an entry that already passed every other check, so `payload` is
|
|
144
|
+
* what the receiver signed. `recordId` is the entry's record; the body names
|
|
145
|
+
* the same record on every message type that carries one. When the sender's
|
|
146
|
+
* keys came with a history, the message is placed in a key's window by
|
|
147
|
+
* `wire.timestamp`: the sender signed it, the receiver sealed it under its own
|
|
148
|
+
* signature after holding it to its clock-skew allowance, and it is read from
|
|
149
|
+
* the sender's clock, the clock the history's windows are written by. The
|
|
150
|
+
* entry's `createdAt` is a column no signature covers, so it places nothing.
|
|
151
|
+
*/
|
|
152
|
+
export declare function checkFederationWire(entryType: string, recordId: string | null, payload: Record<string, unknown>, wire: FederationWire, keys: FederationKeyRegistry | undefined): FederationWireOutcome;
|
|
@@ -0,0 +1,447 @@
|
|
|
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' || !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
|
+
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
|
+
const statements = [];
|
|
158
|
+
const seenIds = new Set();
|
|
159
|
+
for (const { doc, label } of histories) {
|
|
160
|
+
if (!isRecord(doc) || !Array.isArray(doc.statements))
|
|
161
|
+
throw new TypeError(`${label} is not a federation key-history document (no statements array).`);
|
|
162
|
+
if (doc.hubId !== hubId)
|
|
163
|
+
throw new TypeError(`${label} is the key history of hub ${JSON.stringify(doc.hubId)}, not ${hubId}.`);
|
|
164
|
+
if (doc.statementDomain !== FEDERATION_KEY_STATEMENT_DOMAIN) {
|
|
165
|
+
throw new TypeError(`${label} signs under ${JSON.stringify(doc.statementDomain)}, not ${FEDERATION_KEY_STATEMENT_DOMAIN}.`);
|
|
166
|
+
}
|
|
167
|
+
doc.statements.forEach((stmt, j) => {
|
|
168
|
+
const id = isRecord(stmt) && typeof stmt.id === 'string' ? stmt.id : `#${j}`;
|
|
169
|
+
if (seenIds.has(id))
|
|
170
|
+
return;
|
|
171
|
+
seenIds.add(id);
|
|
172
|
+
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);
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
const admission = new Map();
|
|
180
|
+
for (const st of statements)
|
|
181
|
+
if (!admission.has(st.subject.spkiSha256))
|
|
182
|
+
admission.set(st.subject.spkiSha256, st);
|
|
183
|
+
const publicKeyOf = new Map();
|
|
184
|
+
for (const st of statements) {
|
|
185
|
+
publicKeyOf.set(st.subject.spkiSha256, st.subject.publicKey);
|
|
186
|
+
if (st.predecessor)
|
|
187
|
+
publicKeyOf.set(st.predecessor.spkiSha256, st.predecessor.publicKey);
|
|
188
|
+
}
|
|
189
|
+
const links = new Map();
|
|
190
|
+
const retiredAt = new Map();
|
|
191
|
+
for (const st of statements) {
|
|
192
|
+
if (st.typ !== 'succession' || admission.get(st.subject.spkiSha256) !== st || !st.predecessor)
|
|
193
|
+
continue;
|
|
194
|
+
const a = st.predecessor.spkiSha256;
|
|
195
|
+
const b = st.subject.spkiSha256;
|
|
196
|
+
links.set(a, [...(links.get(a) ?? []), b]);
|
|
197
|
+
links.set(b, [...(links.get(b) ?? []), a]);
|
|
198
|
+
if (!retiredAt.has(a))
|
|
199
|
+
retiredAt.set(a, st.predecessor.retiredAt);
|
|
200
|
+
}
|
|
201
|
+
// A pin the histories list roots a walk through its successions. A pin they
|
|
202
|
+
// do not list (a key from before a change made with neither predecessor
|
|
203
|
+
// setting, which no history names) is trusted on its own, at any time, as a
|
|
204
|
+
// pin is without a history. At least one pin must be listed, or nothing
|
|
205
|
+
// links the histories to a key you hold.
|
|
206
|
+
const listed = pins.filter((p) => publicKeyOf.has(spkiSha256(p.spki)));
|
|
207
|
+
if (listed.length === 0) {
|
|
208
|
+
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.`);
|
|
210
|
+
}
|
|
211
|
+
const trusted = new Set();
|
|
212
|
+
const standalone = new Set();
|
|
213
|
+
for (const { spki } of pins) {
|
|
214
|
+
const digest = spkiSha256(spki);
|
|
215
|
+
if (!publicKeyOf.has(digest)) {
|
|
216
|
+
standalone.add(spki);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const queue = [digest];
|
|
220
|
+
while (queue.length > 0) {
|
|
221
|
+
const k = queue.pop();
|
|
222
|
+
if (trusted.has(k))
|
|
223
|
+
continue;
|
|
224
|
+
trusted.add(k);
|
|
225
|
+
queue.push(...(links.get(k) ?? []));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
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
|
+
})),
|
|
234
|
+
...[...standalone].map((publicKey) => ({ publicKey, activatedAt: null, retiredAt: null })),
|
|
235
|
+
];
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Build the registry from `{ [hubId]: publicKey }` or
|
|
239
|
+
* `[{ 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.
|
|
244
|
+
*/
|
|
245
|
+
export function buildFederationKeyRegistry(input) {
|
|
246
|
+
const entries = Array.isArray(input)
|
|
247
|
+
? input.map((e, i) => ({
|
|
248
|
+
hubId: typeof e?.hubId === 'string' ? e.hubId : '',
|
|
249
|
+
key: e?.publicKey,
|
|
250
|
+
history: e?.history,
|
|
251
|
+
label: `federationKeys[${i}]`,
|
|
252
|
+
}))
|
|
253
|
+
: Object.entries(input).map(([hubId, key]) => ({
|
|
254
|
+
hubId,
|
|
255
|
+
key,
|
|
256
|
+
history: undefined,
|
|
257
|
+
label: `federationKeys[${JSON.stringify(hubId)}]`,
|
|
258
|
+
}));
|
|
259
|
+
const byHub = new Map();
|
|
260
|
+
for (const { hubId, key, history, label } of entries) {
|
|
261
|
+
if (hubId.length === 0)
|
|
262
|
+
throw new TypeError(`${label} names no hubId.`);
|
|
263
|
+
const spki = typeof key === 'string' ? normalizeFederationKey(key) : null;
|
|
264
|
+
if (spki === null) {
|
|
265
|
+
throw new TypeError(`${label} is not an Ed25519 public key (base64 SPKI DER, or base64 of the raw 32 bytes).`);
|
|
266
|
+
}
|
|
267
|
+
const hub = byHub.get(hubId) ?? { pins: [], histories: [] };
|
|
268
|
+
hub.pins.push({ spki, label });
|
|
269
|
+
if (history !== undefined)
|
|
270
|
+
hub.histories.push({ doc: history, label: `${label}.history` });
|
|
271
|
+
byHub.set(hubId, hub);
|
|
272
|
+
}
|
|
273
|
+
const out = new Map();
|
|
274
|
+
for (const [hubId, { pins, histories }] of byHub) {
|
|
275
|
+
if (histories.length === 0) {
|
|
276
|
+
out.set(hubId, [...new Set(pins.map((p) => p.spki))].map((publicKey) => ({ publicKey, activatedAt: null, retiredAt: null })));
|
|
277
|
+
}
|
|
278
|
+
else {
|
|
279
|
+
out.set(hubId, trustedKeysFromHistory(hubId, pins, histories));
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return out;
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* RFC 8785 (JCS) canonical JSON, as the Server's `canonicalize` writes it:
|
|
286
|
+
* object keys sorted by code unit, no whitespace, `undefined` members dropped
|
|
287
|
+
* (an array element that is `undefined` serializes as `null`), `-0` as `0`,
|
|
288
|
+
* non-finite numbers as `null`. Numbers take JavaScript's own shortest form,
|
|
289
|
+
* which is what RFC 8785 specifies.
|
|
290
|
+
*/
|
|
291
|
+
export function canonicalizeJson(value) {
|
|
292
|
+
if (value === null || value === undefined)
|
|
293
|
+
return 'null';
|
|
294
|
+
if (typeof value === 'boolean')
|
|
295
|
+
return value ? 'true' : 'false';
|
|
296
|
+
if (typeof value === 'number') {
|
|
297
|
+
if (!Number.isFinite(value))
|
|
298
|
+
return 'null';
|
|
299
|
+
if (Object.is(value, -0))
|
|
300
|
+
return '0';
|
|
301
|
+
return JSON.stringify(value);
|
|
302
|
+
}
|
|
303
|
+
if (typeof value === 'string')
|
|
304
|
+
return JSON.stringify(value);
|
|
305
|
+
if (Array.isArray(value))
|
|
306
|
+
return '[' + value.map(canonicalizeJson).join(',') + ']';
|
|
307
|
+
if (typeof value === 'object') {
|
|
308
|
+
const obj = value;
|
|
309
|
+
const keys = Object.keys(obj).filter((k) => obj[k] !== undefined).sort();
|
|
310
|
+
return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalizeJson(obj[k])).join(',') + '}';
|
|
311
|
+
}
|
|
312
|
+
return 'null';
|
|
313
|
+
}
|
|
314
|
+
/** The sign-input the Server builds, a colon-joined line under the scheme. */
|
|
315
|
+
export function federationSignInput(wire) {
|
|
316
|
+
return `${wire.scheme}:${wire.recipientHubId}:${wire.method}:${wire.path}:${wire.bodyHash}:${wire.timestamp}:${wire.nonce}`;
|
|
317
|
+
}
|
|
318
|
+
function isRecord(value) {
|
|
319
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* The `wire` a row payload carries, or null when it carries none. A `wire`
|
|
323
|
+
* that is present but is not an object is returned as `malformed`, so the
|
|
324
|
+
* caller fails it rather than reading an edited row as one with no message.
|
|
325
|
+
*/
|
|
326
|
+
export function extractFederationWire(payload) {
|
|
327
|
+
if (!('wire' in payload) || payload.wire === undefined)
|
|
328
|
+
return null;
|
|
329
|
+
const w = payload.wire;
|
|
330
|
+
if (!isRecord(w))
|
|
331
|
+
return 'malformed';
|
|
332
|
+
for (const k of ['scheme', 'senderHubId', 'senderPublicKey', 'recipientHubId', 'method', 'path', 'bodyHash', 'timestamp', 'nonce', 'signature']) {
|
|
333
|
+
if (typeof w[k] !== 'string')
|
|
334
|
+
return 'malformed';
|
|
335
|
+
}
|
|
336
|
+
if (!isRecord(w.body))
|
|
337
|
+
return 'malformed';
|
|
338
|
+
return w;
|
|
339
|
+
}
|
|
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
|
+
*/
|
|
345
|
+
const FIELD_PAIRS = {
|
|
346
|
+
FEDERATION_STATE_SYNC: [
|
|
347
|
+
['state', 'state'],
|
|
348
|
+
['recordType', 'type'],
|
|
349
|
+
['disputeId', 'disputeId'],
|
|
350
|
+
['action', 'action'],
|
|
351
|
+
],
|
|
352
|
+
FEDERATION_SIGNAL_RECEIVED: [['recommendation', 'recommendation']],
|
|
353
|
+
FEDERATION_CO_SIGN_RESPONDED: [
|
|
354
|
+
['recommendation', 'recommendation'],
|
|
355
|
+
['state', 'state'],
|
|
356
|
+
['outcomeHash', 'outcomeHash'],
|
|
357
|
+
['idempotencyKey', 'idempotencyKey'],
|
|
358
|
+
],
|
|
359
|
+
};
|
|
360
|
+
/**
|
|
361
|
+
* Check one sealed message against the entry that carries it, and under the
|
|
362
|
+
* sender's key when `keys` has one for `wire.senderHubId`.
|
|
363
|
+
*
|
|
364
|
+
* Runs on an entry that already passed every other check, so `payload` is
|
|
365
|
+
* 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
|
|
367
|
+
* keys came with a history, the message is placed in a key's window by
|
|
368
|
+
* `wire.timestamp`: the sender signed it, the receiver sealed it under its own
|
|
369
|
+
* 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
|
|
371
|
+
* entry's `createdAt` is a column no signature covers, so it places nothing.
|
|
372
|
+
*/
|
|
373
|
+
export function checkFederationWire(entryType, recordId, payload, wire, keys) {
|
|
374
|
+
if (wire.scheme !== FEDERATION_WIRE_SCHEME) {
|
|
375
|
+
return { outcome: 'invalid', detail: `Sealed message scheme is ${JSON.stringify(wire.scheme)}, not ${FEDERATION_WIRE_SCHEME}.` };
|
|
376
|
+
}
|
|
377
|
+
const bodyHash = createHash('sha256').update(canonicalizeJson(wire.body), 'utf8').digest('hex');
|
|
378
|
+
if (bodyHash !== wire.bodyHash.toLowerCase()) {
|
|
379
|
+
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.' };
|
|
380
|
+
}
|
|
381
|
+
if (typeof payload.peerHubId === 'string' && payload.peerHubId !== wire.senderHubId) {
|
|
382
|
+
return { outcome: 'invalid', detail: `Entry names peer ${payload.peerHubId}, the sealed message was sent by ${wire.senderHubId}.` };
|
|
383
|
+
}
|
|
384
|
+
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}.` };
|
|
387
|
+
}
|
|
388
|
+
for (const [entryField, bodyField] of FIELD_PAIRS[entryType] ?? []) {
|
|
389
|
+
const mine = payload[entryField];
|
|
390
|
+
const theirs = wire.body[bodyField];
|
|
391
|
+
if (mine === undefined || theirs === undefined || mine === null || theirs === null)
|
|
392
|
+
continue;
|
|
393
|
+
if (canonicalizeJson(mine) !== canonicalizeJson(theirs)) {
|
|
394
|
+
return {
|
|
395
|
+
outcome: 'invalid',
|
|
396
|
+
detail: `Entry ${entryField} is ${canonicalizeJson(mine)}, the sealed message's ${bodyField} is ${canonicalizeJson(theirs)}: the entry asserts what the sender did not sign.`,
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
const trusted = keys?.get(wire.senderHubId);
|
|
401
|
+
if (trusted === undefined)
|
|
402
|
+
return { outcome: 'unchecked' };
|
|
403
|
+
const sealed = normalizeFederationKey(wire.senderPublicKey);
|
|
404
|
+
const key = trusted.find((k) => k.publicKey === sealed);
|
|
405
|
+
if (key === undefined) {
|
|
406
|
+
const withHistory = trusted.some((k) => k.activatedAt !== null || k.retiredAt !== null);
|
|
407
|
+
return {
|
|
408
|
+
outcome: 'invalid',
|
|
409
|
+
detail: withHistory
|
|
410
|
+
? `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.`
|
|
411
|
+
: `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.`,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
let afterRetirement = false;
|
|
415
|
+
if (key.activatedAt !== null || key.retiredAt !== null) {
|
|
416
|
+
const at = rfc3339Ms(wire.timestamp);
|
|
417
|
+
if (Number.isNaN(at)) {
|
|
418
|
+
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
|
+
}
|
|
420
|
+
if (key.activatedAt !== null && at < rfc3339Ms(key.activatedAt)) {
|
|
421
|
+
return {
|
|
422
|
+
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.`,
|
|
424
|
+
};
|
|
425
|
+
}
|
|
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
|
+
}
|
|
432
|
+
let signature;
|
|
433
|
+
try {
|
|
434
|
+
signature = Buffer.from(wire.signature, 'hex');
|
|
435
|
+
}
|
|
436
|
+
catch {
|
|
437
|
+
signature = Buffer.alloc(0);
|
|
438
|
+
}
|
|
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.` };
|
|
441
|
+
}
|
|
442
|
+
const ok = verifyEd25519Bytes(key.publicKey, Buffer.from(federationSignInput(wire), 'utf8'), signature);
|
|
443
|
+
if (!ok) {
|
|
444
|
+
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
|
+
}
|
|
446
|
+
return { outcome: 'ok', signatureChecked: true, afterRetirement };
|
|
447
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -6,11 +6,13 @@
|
|
|
6
6
|
export { suggestion } from './failures.js';
|
|
7
7
|
export type { FailureCode } from './failures.js';
|
|
8
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';
|
|
9
|
+
export type { AccountedEntry, AccountedEntryCode, AgentKeyRegistry, KeySource, KeyTrustState, VerificationKey, KeyRegistry, NormalizedEntry, OptionalCheck, CheckApplicability, SignatureOutcome, ChainEntryResult, ChainResult, EvidenceBindingCounts, VerifyChainOptions, } from './chain.js';
|
|
10
10
|
export { verifyAuditExport } from './audit-export.js';
|
|
11
11
|
export type { AuditExportEntryInput, RecordAuditExportInput, SigningKeyWindow, VerifyExportOptions, SuppliedKeyEntry, EntryVerificationResult, VerifyExportResult, } 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, } from './federation-wire.js';
|
|
15
|
+
export type { FederationKeyEntry, FederationKeyHistoryDocument, FederationKeyHistoryStatement, FederationKeyRegistry, FederationTrustedKey, FederationWire, FederationWireOutcome, } 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
|
@@ -7,6 +7,7 @@ export { suggestion } from './failures.js';
|
|
|
7
7
|
export { ACCOUNTED_ENTRY_CODE, buildAgentKeyRegistry, buildKeyRegistry, chainOfScope, earliestKeyActivation, 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, } 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/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agledger/verify-core",
|
|
3
|
-
"version": "2.
|
|
4
|
-
"description": "Shared offline verification core for AGLedger audit chains: COSE_Sign1 (RFC 9052)
|
|
3
|
+
"version": "2.1.0",
|
|
4
|
+
"description": "Shared offline verification core for AGLedger audit chains: COSE_Sign1 (RFC 9052), Ed25519 and ES256, hash-chain walk, key-statement trust walk, RFC 9162 Merkle proofs, canonical failure taxonomy. One dependency (cborg); no network.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"engines": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"prepublishOnly": "npm run build && npm run lint:pkg"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"cborg": "6.1.
|
|
37
|
+
"cborg": "6.1.3"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@arethetypeswrong/cli": "^0.18.3",
|