@agledger/verify-core 1.5.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 +333 -14
- package/dist/audit-export.d.ts +156 -24
- package/dist/audit-export.js +197 -37
- package/dist/chain.d.ts +239 -24
- package/dist/chain.js +367 -57
- package/dist/failures.d.ts +36 -2
- package/dist/failures.js +56 -6
- package/dist/federation-wire.d.ts +152 -0
- package/dist/federation-wire.js +447 -0
- package/dist/index.d.ts +10 -4
- package/dist/index.js +6 -2
- package/dist/instant.d.ts +23 -0
- package/dist/instant.js +50 -0
- package/dist/key-statements.d.ts +429 -0
- package/dist/key-statements.js +1325 -0
- package/dist/options.d.ts +7 -0
- package/dist/options.js +29 -0
- package/dist/primitives.d.ts +28 -6
- package/dist/primitives.js +86 -42
- package/package.json +3 -3
|
@@ -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
|
@@ -5,9 +5,15 @@
|
|
|
5
5
|
*/
|
|
6
6
|
export { suggestion } from './failures.js';
|
|
7
7
|
export type { FailureCode } from './failures.js';
|
|
8
|
-
export { buildAgentKeyRegistry, buildKeyRegistry, verifyChain, } from './chain.js';
|
|
9
|
-
export type { AgentKeyRegistry, KeySource, VerificationKey, KeyRegistry, NormalizedEntry, OptionalCheck, CheckApplicability, SignatureOutcome, ChainEntryResult, ChainResult, VerifyChainOptions, } from './chain.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, EvidenceBindingCounts, VerifyChainOptions, } from './chain.js';
|
|
10
10
|
export { verifyAuditExport } from './audit-export.js';
|
|
11
|
-
export type { AuditExportEntryInput, RecordAuditExportInput, SigningKeyWindow, VerifyExportOptions,
|
|
12
|
-
export {
|
|
11
|
+
export type { AuditExportEntryInput, RecordAuditExportInput, SigningKeyWindow, VerifyExportOptions, SuppliedKeyEntry, EntryVerificationResult, VerifyExportResult, } from './audit-export.js';
|
|
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
|
+
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';
|
|
16
|
+
export { instantMs } from './instant.js';
|
|
17
|
+
export { assertKnownOptions } from './options.js';
|
|
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';
|
|
13
19
|
export type { CoseSign1Parts, CoseVerifyOutcome, KeyAlgorithm, ActorClaim, ChainClaim, AgentPublicKeyJwk, AgentSignatureClaim, AgentSignatureOutcome, ReceiptInclusionProof, ReceiptVerifyOutcome, } from './primitives.js';
|
package/dist/index.js
CHANGED
|
@@ -4,6 +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 { buildAgentKeyRegistry, buildKeyRegistry, verifyChain, } from './chain.js';
|
|
7
|
+
export { ACCOUNTED_ENTRY_CODE, buildAgentKeyRegistry, buildKeyRegistry, chainOfScope, earliestKeyActivation, verifyChain, writtenWhileSigning, } from './chain.js';
|
|
8
8
|
export { verifyAuditExport } from './audit-export.js';
|
|
9
|
-
export {
|
|
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';
|
|
11
|
+
export { instantMs } from './instant.js';
|
|
12
|
+
export { assertKnownOptions } from './options.js';
|
|
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';
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Milliseconds of an RFC 3339 instant, truncating any finer fraction the way
|
|
3
|
+
* the engine reads a microsecond instant (its `instantToDate`). Key statements
|
|
4
|
+
* sign microsecond instants; entry write times, dump columns and key documents
|
|
5
|
+
* carry milliseconds, so every comparison between them is made here. Strict:
|
|
6
|
+
* a `T`, an offset or `Z`, a real calendar date and time of day; NaN for
|
|
7
|
+
* anything else, so no instant is ever placed by how the host's `Date.parse`
|
|
8
|
+
* reads a date with no offset, a space separator or an impossible day.
|
|
9
|
+
*/
|
|
10
|
+
export declare function instantMs(instant: string): number;
|
|
11
|
+
/** {@link instantMs}, under the name the strictness is the point of. */
|
|
12
|
+
export declare function rfc3339Ms(instant: string): number;
|
|
13
|
+
/**
|
|
14
|
+
* Microseconds of a strict RFC 3339 instant, and whether it carries a full
|
|
15
|
+
* microsecond fraction. The key surfaces publish a statement's write time at
|
|
16
|
+
* microsecond precision and a dump at milliseconds, so two dump rows in one
|
|
17
|
+
* millisecond tie here without being simultaneous. NaN when the string is not
|
|
18
|
+
* strict RFC 3339 (see {@link rfc3339Ms}).
|
|
19
|
+
*/
|
|
20
|
+
export declare function instantUs(instant: string): {
|
|
21
|
+
us: number;
|
|
22
|
+
micro: boolean;
|
|
23
|
+
};
|
package/dist/instant.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** RFC 3339 date-time: a `T`, a numeric offset or `Z`, any fraction. */
|
|
2
|
+
const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?([Zz]|([+-])(\d{2}):(\d{2}))$/;
|
|
3
|
+
/**
|
|
4
|
+
* Milliseconds of an RFC 3339 instant, truncating any finer fraction the way
|
|
5
|
+
* the engine reads a microsecond instant (its `instantToDate`). Key statements
|
|
6
|
+
* sign microsecond instants; entry write times, dump columns and key documents
|
|
7
|
+
* carry milliseconds, so every comparison between them is made here. Strict:
|
|
8
|
+
* a `T`, an offset or `Z`, a real calendar date and time of day; NaN for
|
|
9
|
+
* anything else, so no instant is ever placed by how the host's `Date.parse`
|
|
10
|
+
* reads a date with no offset, a space separator or an impossible day.
|
|
11
|
+
*/
|
|
12
|
+
export function instantMs(instant) {
|
|
13
|
+
return rfc3339Ms(instant);
|
|
14
|
+
}
|
|
15
|
+
/** {@link instantMs}, under the name the strictness is the point of. */
|
|
16
|
+
export function rfc3339Ms(instant) {
|
|
17
|
+
return parse(instant)?.ms ?? Number.NaN;
|
|
18
|
+
}
|
|
19
|
+
function parse(instant) {
|
|
20
|
+
if (typeof instant !== 'string')
|
|
21
|
+
return null;
|
|
22
|
+
const m = RFC3339.exec(instant);
|
|
23
|
+
if (!m)
|
|
24
|
+
return null;
|
|
25
|
+
const [, y, mo, d, h, mi, s, frac = '', zone, sign, oh, om] = m;
|
|
26
|
+
if (Number(h) > 23 || Number(mi) > 59 || Number(s) > 59)
|
|
27
|
+
return null;
|
|
28
|
+
if (sign !== undefined && (Number(oh) > 23 || Number(om) > 59))
|
|
29
|
+
return null;
|
|
30
|
+
const fields = `${y}-${mo}-${d}T${h}:${mi}:${s}`;
|
|
31
|
+
const local = Date.parse(`${fields}Z`);
|
|
32
|
+
// Date.parse rolls an impossible date over (February 30 reads as March 2).
|
|
33
|
+
if (Number.isNaN(local) || !new Date(local).toISOString().startsWith(fields))
|
|
34
|
+
return null;
|
|
35
|
+
const offset = zone === 'Z' || zone === 'z' ? 0 : (sign === '-' ? -1 : 1) * (Number(oh) * 60 + Number(om)) * 60_000;
|
|
36
|
+
return { ms: local + Number(frac.slice(0, 3).padEnd(3, '0')) - offset, frac };
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Microseconds of a strict RFC 3339 instant, and whether it carries a full
|
|
40
|
+
* microsecond fraction. The key surfaces publish a statement's write time at
|
|
41
|
+
* microsecond precision and a dump at milliseconds, so two dump rows in one
|
|
42
|
+
* millisecond tie here without being simultaneous. NaN when the string is not
|
|
43
|
+
* strict RFC 3339 (see {@link rfc3339Ms}).
|
|
44
|
+
*/
|
|
45
|
+
export function instantUs(instant) {
|
|
46
|
+
const p = parse(instant);
|
|
47
|
+
if (p === null)
|
|
48
|
+
return { us: Number.NaN, micro: false };
|
|
49
|
+
return { us: p.ms * 1000 + Number(p.frac.slice(3, 6).padEnd(3, '0')), micro: p.frac.length >= 6 };
|
|
50
|
+
}
|