@agledger/verify-core 1.4.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1325 @@
1
+ /**
2
+ * Vault key statements and the trust walk over them.
3
+ *
4
+ * A vault key is trusted only when signed key statements link it to a key the
5
+ * verifier pinned out of band (`trustAnchors`). The Server's database stores
6
+ * the statements and never vouches for them: anything with write access to it
7
+ * can add a `vault_signing_keys` row and a statement row, and neither makes a
8
+ * key trusted, because every edge below is a signature that writer cannot
9
+ * produce. This is the engine's `computeKeyTrust`
10
+ * (audit-vault/key-statements.ts), re-implemented so the verifier has no engine
11
+ * dependency. Where the two could disagree, this one must never trust a key the
12
+ * engine refuses.
13
+ *
14
+ * **Format.** Each statement is one or two COSE_Sign1 (RFC 9052, tag 18) over
15
+ * the SAME deterministic-CBOR (RFC 8949 §4.2.1) payload, protected header
16
+ * `{1: alg, 3: cty, 4: kid}` with `cty` = {@link KEY_STATEMENT_CTY}. The
17
+ * payload is a text-keyed map:
18
+ *
19
+ * typ 'succession' | 'closure' | 'genesis'
20
+ * iss the Server's issuer URL (informational)
21
+ * subject { kid, spkiSha256, alg, spki (bstr), activatedAt, retiredAt? }
22
+ * endorser { kid, spkiSha256 } absent on genesis
23
+ * iat epoch seconds, informational only, never used for ordering
24
+ * forced bool closure only
25
+ *
26
+ * `activatedAt` / `retiredAt` are RFC 3339 UTC instants at microsecond
27
+ * precision. A succession is signed by the endorser and then by the subject; a
28
+ * closure by a key other than its subject; a genesis by its subject alone, and
29
+ * it grants no trust.
30
+ *
31
+ * **Write order.** The rule orders statements by the database's write order,
32
+ * `created_at` then the row `id`, never by an instant a statement signs. A
33
+ * dump carries it (`created_at` at milliseconds, then the file's own row
34
+ * order, which the producer writes as `created_at, id`). Every key document
35
+ * (`GET /v1/verification-keys`, `/.well-known/agledger-vault-keys.json`, an
36
+ * export's `exportMetadata.signingKeyStatements`) carries it too, as each
37
+ * statement's `id` and `createdAt` at microseconds, and lists under a trusted
38
+ * key its admission, every later genesis or succession it signed, and its
39
+ * counting closures. A walk over a document therefore dates a window and
40
+ * cuts an edge back as the engine does, except where the document does not
41
+ * carry a key the engine verified a statement with (the endorser of a later
42
+ * succession, the signer of a closure): that statement is
43
+ * KEY_STATEMENT_INVALID or KEY_CLOSURE_INVALID here, the window is wider than
44
+ * the engine's, and the listed `activatedAt` or `retiredAt` reports it as
45
+ * CHAIN_KEY_WINDOW_DRIFT (a listed retirement no counting closure signs, as
46
+ * KEY_CLOSURE_INVALID).
47
+ *
48
+ * A document from a Server that published neither field is ordered by the
49
+ * instant each statement signs (a genesis or succession by
50
+ * `subject.activatedAt`, a closure by `subject.retiredAt`). For an honest
51
+ * document the two orders agree, because the Server signs the instant it
52
+ * writes. What the signed order cannot do is hold a leaked key to the time it
53
+ * actually wrote a statement: a key retired without `forced` whose private
54
+ * half later leaks can date a statement before its retirement. Such a
55
+ * statement is only ever in a document that did not come from the Server. A
56
+ * forced closure voids every edge out of its key whatever the order.
57
+ */
58
+ import { decode as cborDecode, encode as cborEncode, rfc8949EncodeOptions } from 'cborg';
59
+ import { algorithmByName, resolveKeyAlgorithm, runtimeCanCompute, sha256Hex, verifySignatureBytes, } from './primitives.js';
60
+ import { instantMs, instantUs, rfc3339Ms } from './instant.js';
61
+ import { assertKnownOptions } from './options.js';
62
+ /** Content type of a key statement's COSE_Sign1 (protected header label 3). */
63
+ export const KEY_STATEMENT_CTY = 'application/vnd.agledger.key-statement+cbor';
64
+ export const KEY_STATEMENT_KINDS = ['succession', 'closure', 'genesis'];
65
+ /**
66
+ * The COSE `alg` a statement signature must carry for its key's algorithm.
67
+ * Exactly one per algorithm, as the engine signs and checks them; the chain
68
+ * envelope's wider acceptance (RFC 9864 fully-specified code points) does not
69
+ * apply to statements.
70
+ */
71
+ const STATEMENT_COSE_ALG = Object.freeze({ Ed25519: -8, ES256: -7 });
72
+ const COSE_HEADER_ALG = 1;
73
+ const COSE_HEADER_CTY = 3;
74
+ const COSE_HEADER_KID = 4;
75
+ const COSE_SIGN1_TAG = 18;
76
+ const COSE_SIGN1_TAG_PREFIX = 0xd2;
77
+ const SIG_STRUCTURE_CONTEXT = 'Signature1';
78
+ const HEX64 = /^[0-9a-f]{64}$/;
79
+ const HEX16 = /^[0-9a-f]{16}$/;
80
+ /** RFC 3339 UTC at microsecond precision, the shape the statements sign. */
81
+ const INSTANT_US = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/;
82
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
83
+ // --- Parsing the out-of-band inputs ---
84
+ /** The full SHA-256 of a base64 SPKI DER, lowercase hex. */
85
+ export function spkiSha256(spkiBase64) {
86
+ return sha256Hex(Buffer.from(spkiBase64, 'base64'));
87
+ }
88
+ function listOf(raw) {
89
+ return (typeof raw === 'string' ? raw.split(',') : [...raw]).map((p) => {
90
+ if (typeof p !== 'string')
91
+ throw new TypeError(`expected a string entry (got ${typeof p}).`);
92
+ return p.trim();
93
+ }).filter((p) => p !== '');
94
+ }
95
+ /**
96
+ * Parse trust anchors: `sha256:<64 hex>` entries, as an array or a comma list
97
+ * (the Server's `VAULT_TRUST_ANCHORS` form). Returns the bare lowercase hex
98
+ * digests. Throws `TypeError` naming any entry in another shape.
99
+ */
100
+ export function parseTrustAnchors(raw) {
101
+ const out = [];
102
+ for (const entry of listOf(raw)) {
103
+ const digest = /^sha256:([0-9a-f]{64})$/.exec(entry.toLowerCase())?.[1];
104
+ if (digest === undefined) {
105
+ throw new TypeError(`trustAnchors entry "${entry}" is not sha256:<64 hex>. Each anchor is the full SHA-256 of a vault public key's SPKI DER, `
106
+ + 'taken out of band: the installer prints it, and the Server\'s signing-key-digest.js derives it from the key.');
107
+ }
108
+ if (!out.includes(digest))
109
+ out.push(digest);
110
+ }
111
+ return out;
112
+ }
113
+ /** RFC 3339 with a `Z` or numeric offset and up to microsecond fractions. */
114
+ const RFC3339 = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(\.\d{1,6}|)(Z|[+-]\d{2}:\d{2})$/;
115
+ /**
116
+ * Parse distrusted keys in the Server's `VAULT_DISTRUSTED_KEYS` form, as an
117
+ * array or a comma list: `sha256:<64 hex>`, each optionally `@<RFC 3339
118
+ * instant>`, the instant from which what the key signs counts for nothing.
119
+ * The instant comes back in UTC at microsecond precision. Throws `TypeError`
120
+ * naming any other entry, or a key named twice.
121
+ */
122
+ export function parseDistrustedKeys(raw) {
123
+ const out = [];
124
+ for (const entry of listOf(raw)) {
125
+ const at = entry.indexOf('@');
126
+ const digest = /^sha256:([0-9a-f]{64})$/.exec((at === -1 ? entry : entry.slice(0, at)).toLowerCase())?.[1];
127
+ const instant = at === -1 ? null : RFC3339.exec(entry.slice(at + 1).toUpperCase());
128
+ // Date.parse rolls an impossible date over (February 30 reads as March 2),
129
+ // so the fields must read back as written.
130
+ const fields = instant?.[1] === undefined ? NaN : Date.parse(`${instant[1]}Z`);
131
+ const calendar = instant?.[1] !== undefined && !Number.isNaN(fields) && new Date(fields).toISOString().startsWith(instant[1]);
132
+ const whole = instant && calendar ? Date.parse(`${instant[1]}${instant[3]}`) : NaN;
133
+ if (digest === undefined || (at !== -1 && (instant === null || Number.isNaN(whole)))) {
134
+ throw new TypeError(`distrustedKeys entry "${entry}" is not sha256:<64 hex>, optionally followed by @<RFC 3339 instant> `
135
+ + '(2026-09-01T00:00:00Z). Each entry is the full SHA-256 of a vault public key\'s SPKI DER, as in the Server\'s VAULT_DISTRUSTED_KEYS.');
136
+ }
137
+ const cutoff = instant ? `${new Date(whole).toISOString().slice(0, 19)}.${(instant[2] ?? '').slice(1).padEnd(6, '0')}Z` : null;
138
+ if (out.some((d) => d.spkiSha256 === digest)) {
139
+ throw new TypeError(`distrustedKeys names sha256:${digest} twice. Give each key one entry, with the earliest instant it may have leaked.`);
140
+ }
141
+ out.push({ spkiSha256: digest, cutoff });
142
+ }
143
+ return out;
144
+ }
145
+ /**
146
+ * Throw `TypeError` when a key is pinned and distrusted with no instant, as
147
+ * the Server refuses to boot on that pair (`VaultKeyDistrustedError`): an
148
+ * undated entry withdraws the key from before anything it signed, which
149
+ * leaves a pin nothing to vouch for. A pin beside a dated entry
150
+ * (`sha256:<hex>@<instant>`) is how a leaked key whose history is still
151
+ * needed is kept from signing anything new: the pin vouches for what it
152
+ * stored before the instant. `computeKeyTrust` itself walks any pair as the
153
+ * engine's walk does; a verifier calls this on what its caller passed before
154
+ * it walks.
155
+ */
156
+ export function assertNotPinnedAndDistrusted(trustAnchors, distrustedKeys) {
157
+ if (trustAnchors === undefined || distrustedKeys === undefined)
158
+ return;
159
+ const anchors = new Set(parseTrustAnchors(trustAnchors));
160
+ const both = normalizeDistrusted(distrustedKeys).find((d) => d.cutoff === null && anchors.has(d.spkiSha256));
161
+ if (both === undefined)
162
+ return;
163
+ throw new TypeError(`sha256:${both.spkiSha256} is a trust anchor and a distrusted key with no instant, which leaves the pin nothing to vouch for. `
164
+ + 'Give the distrust entry the instant the key leaked (sha256:<hex>@<RFC 3339 instant>, no later than its retirement) and keep the pin, which then vouches for what it signed before that instant only; '
165
+ + 'or, if you vouch for nothing it signed, keep the entry without an instant and drop the pin. The Server refuses to start with the same pair in VAULT_TRUST_ANCHORS and VAULT_DISTRUSTED_KEYS.');
166
+ }
167
+ function normalizeDistrusted(raw) {
168
+ if (raw === undefined)
169
+ return [];
170
+ if (!Array.isArray(raw))
171
+ throw new TypeError('distrustedKeys must be an array.');
172
+ const strings = raw.filter((d) => typeof d === 'string');
173
+ const parsed = parseDistrustedKeys(strings);
174
+ for (const d of raw) {
175
+ if (typeof d === 'string')
176
+ continue;
177
+ if (d === null || typeof d !== 'object' || typeof d.spkiSha256 !== 'string' || !HEX64.test(d.spkiSha256)
178
+ || (d.cutoff !== null && (typeof d.cutoff !== 'string' || !INSTANT_US.test(d.cutoff)))) {
179
+ throw new TypeError('distrustedKeys entry is not { spkiSha256: <64 lowercase hex>, cutoff: <microsecond RFC 3339 UTC instant> | null }.');
180
+ }
181
+ if (parsed.some((p) => p.spkiSha256 === d.spkiSha256)) {
182
+ throw new TypeError(`distrustedKeys names sha256:${d.spkiSha256} twice. Give each key one entry, with the earliest instant it may have leaked.`);
183
+ }
184
+ parsed.push({ spkiSha256: d.spkiSha256, cutoff: d.cutoff });
185
+ }
186
+ return parsed;
187
+ }
188
+ function toBytes(v) {
189
+ if (v instanceof Uint8Array)
190
+ return v;
191
+ if (typeof v === 'string' && BASE64.test(v))
192
+ return new Uint8Array(Buffer.from(v, 'base64'));
193
+ return null;
194
+ }
195
+ function decodeSign1(raw) {
196
+ const bytes = toBytes(raw);
197
+ if (bytes === null || bytes.length === 0 || bytes[0] !== COSE_SIGN1_TAG_PREFIX)
198
+ return null;
199
+ try {
200
+ const decoded = cborDecode(bytes, {
201
+ useMaps: true,
202
+ tags: { [COSE_SIGN1_TAG]: (control) => control() },
203
+ });
204
+ if (!Array.isArray(decoded) || decoded.length !== 4)
205
+ return null;
206
+ const [p, , payload, sig] = decoded;
207
+ if (!(p instanceof Uint8Array) || !(payload instanceof Uint8Array) || !(sig instanceof Uint8Array))
208
+ return null;
209
+ const header = cborDecode(p, { useMaps: true });
210
+ if (!(header instanceof Map))
211
+ return null;
212
+ const alg = header.get(COSE_HEADER_ALG);
213
+ const kid = header.get(COSE_HEADER_KID);
214
+ return {
215
+ protectedBstr: p,
216
+ payloadBstr: payload,
217
+ signature: sig,
218
+ alg: typeof alg === 'number' ? alg : null,
219
+ cty: header.get(COSE_HEADER_CTY),
220
+ kid: kid instanceof Uint8Array ? Buffer.from(kid).toString('hex') : null,
221
+ };
222
+ }
223
+ catch {
224
+ return null;
225
+ }
226
+ }
227
+ function asRecord(v) {
228
+ return v !== null && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Uint8Array)
229
+ ? v
230
+ : null;
231
+ }
232
+ function readKeyRef(v) {
233
+ const r = asRecord(v);
234
+ if (!r)
235
+ return null;
236
+ const kid = r['kid'];
237
+ const digest = r['spkiSha256'];
238
+ if (typeof kid !== 'string' || !HEX16.test(kid) || typeof digest !== 'string' || !HEX64.test(digest))
239
+ return null;
240
+ return { kid, spkiSha256: digest };
241
+ }
242
+ /**
243
+ * Decode and shape-check payload bytes. Null when anything is missing,
244
+ * mistyped, not canonical, or inconsistent (the subject's digest must be the
245
+ * SHA-256 of the spki it carries, and its kid the first 16 hex of that digest).
246
+ */
247
+ function decodeKeyStatementPayload(bytes) {
248
+ let raw;
249
+ try {
250
+ raw = cborDecode(bytes, { useMaps: false });
251
+ }
252
+ catch {
253
+ return null;
254
+ }
255
+ // Canonical bytes only: two encodings of one payload would carry two digests.
256
+ try {
257
+ if (Buffer.compare(Buffer.from(cborEncode(raw, rfc8949EncodeOptions)), Buffer.from(bytes)) !== 0)
258
+ return null;
259
+ }
260
+ catch {
261
+ return null;
262
+ }
263
+ const r = asRecord(raw);
264
+ if (!r)
265
+ return null;
266
+ const typ = r['typ'];
267
+ if (typeof typ !== 'string' || !KEY_STATEMENT_KINDS.includes(typ))
268
+ return null;
269
+ const iss = r['iss'];
270
+ const iat = r['iat'];
271
+ if (typeof iss !== 'string' || typeof iat !== 'number' || !Number.isInteger(iat))
272
+ return null;
273
+ const s = asRecord(r['subject']);
274
+ if (!s)
275
+ return null;
276
+ const ref = readKeyRef(s);
277
+ const spki = s['spki'];
278
+ const alg = s['alg'];
279
+ const activatedAt = s['activatedAt'];
280
+ const retiredAt = s['retiredAt'];
281
+ if (!ref || !(spki instanceof Uint8Array) || typeof alg !== 'string' || typeof activatedAt !== 'string' || !INSTANT_US.test(activatedAt))
282
+ return null;
283
+ if (retiredAt !== undefined && (typeof retiredAt !== 'string' || !INSTANT_US.test(retiredAt)))
284
+ return null;
285
+ if (sha256Hex(spki) !== ref.spkiSha256 || ref.kid !== ref.spkiSha256.slice(0, 16))
286
+ return null;
287
+ const payload = {
288
+ typ: typ,
289
+ iss,
290
+ iat,
291
+ subject: {
292
+ ...ref,
293
+ alg,
294
+ spki: Buffer.from(spki).toString('base64'),
295
+ activatedAt,
296
+ ...(retiredAt !== undefined ? { retiredAt: retiredAt } : {}),
297
+ },
298
+ };
299
+ if (r['endorser'] !== undefined) {
300
+ const e = readKeyRef(r['endorser']);
301
+ if (!e)
302
+ return null;
303
+ payload.endorser = e;
304
+ }
305
+ if (r['forced'] !== undefined) {
306
+ if (typeof r['forced'] !== 'boolean')
307
+ return null;
308
+ payload.forced = r['forced'];
309
+ }
310
+ return payload;
311
+ }
312
+ function sigStructure(protectedBstr, payloadBstr) {
313
+ return cborEncode([SIG_STRUCTURE_CONTEXT, protectedBstr, new Uint8Array(0), payloadBstr], rfc8949EncodeOptions);
314
+ }
315
+ /** The statement algorithm the key material commits to, when it is one statements are signed under. */
316
+ function statementAlgorithmOf(spki) {
317
+ const resolved = resolveKeyAlgorithm(spki);
318
+ return typeof resolved === 'object' && STATEMENT_COSE_ALG[resolved.name] !== undefined ? resolved : null;
319
+ }
320
+ /**
321
+ * The algorithm to verify a key's signatures under. The key material decides
322
+ * wherever it parses; `strict` is for a statement's own subject, whose signed
323
+ * `alg` must then agree with it. An endorser's declared algorithm comes from
324
+ * wherever its key was found and is consulted only when the material does not
325
+ * parse (an Ed25519 key on a FIPS host). A host that cannot compute the
326
+ * algorithm makes the key `unsupported`, never `invalid`.
327
+ */
328
+ function materialFor(spki, declared, strict = false) {
329
+ const derived = statementAlgorithmOf(spki);
330
+ if (derived) {
331
+ if (strict && declared !== derived.name)
332
+ return { spki, alg: 'invalid' };
333
+ return { spki, alg: runtimeCanCompute(derived) ? derived : 'unsupported' };
334
+ }
335
+ const named = declared !== null ? algorithmByName(declared) : null;
336
+ if (named && STATEMENT_COSE_ALG[named.name] !== undefined && !runtimeCanCompute(named))
337
+ return { spki, alg: 'unsupported' };
338
+ return { spki, alg: 'invalid' };
339
+ }
340
+ function checkSignature(sign1, key, expectKid) {
341
+ if (key.alg === 'unsupported')
342
+ return 'unsupported';
343
+ if (key.alg === 'invalid')
344
+ return 'bad';
345
+ if (sign1.cty !== KEY_STATEMENT_CTY || sign1.kid !== expectKid || sign1.alg !== STATEMENT_COSE_ALG[key.alg.name])
346
+ return 'bad';
347
+ if (sign1.signature.every((b) => b === 0))
348
+ return 'bad';
349
+ return verifySignatureBytes(key.spki, sigStructure(sign1.protectedBstr, sign1.payloadBstr), sign1.signature) ? 'ok' : 'bad';
350
+ }
351
+ function checkKeyStatement(input, keyByDigest) {
352
+ const id = input.id ?? null;
353
+ let digest = null;
354
+ const invalid = (detail, payload = null) => ({ input, id, verdict: 'invalid', detail, payload, digest: payload === null ? null : digest, subjectSigned: false, endorserSigned: false });
355
+ const cose = Array.isArray(input.cose) ? input.cose : [];
356
+ const sigs = cose.map((b) => decodeSign1(b));
357
+ if (sigs.length === 0 || sigs.some((s) => s === null))
358
+ return invalid('a signature does not decode as a tagged COSE_Sign1');
359
+ const parts = sigs.filter((x) => x !== null);
360
+ const first = parts[0];
361
+ if (!parts.every((p) => Buffer.from(p.payloadBstr).equals(Buffer.from(first.payloadBstr)))) {
362
+ return invalid('the signatures do not cover the same payload');
363
+ }
364
+ const payload = decodeKeyStatementPayload(first.payloadBstr);
365
+ if (!payload)
366
+ return invalid('the payload does not decode as a key statement');
367
+ digest = sha256Hex(first.payloadBstr);
368
+ if (payload.typ !== input.kind
369
+ || (input.subjectKeyId !== undefined && payload.subject.kid !== input.subjectKeyId)
370
+ || (input.endorserKeyId !== undefined && (payload.endorser?.kid ?? null) !== input.endorserKeyId)) {
371
+ return invalid('the row columns disagree with the signed payload', payload);
372
+ }
373
+ const subject = materialFor(payload.subject.spki, payload.subject.alg, true);
374
+ const endorserRef = payload.endorser ?? null;
375
+ let endorser = null;
376
+ if (endorserRef) {
377
+ const known = keyByDigest.get(endorserRef.spkiSha256);
378
+ if (!known)
379
+ return invalid('the endorser key is unknown to the registry and to every statement', payload);
380
+ if (endorserRef.kid !== endorserRef.spkiSha256.slice(0, 16))
381
+ return invalid('the endorser kid is not its key fingerprint', payload);
382
+ endorser = materialFor(known.spki, known.alg);
383
+ }
384
+ const expected = [];
385
+ switch (payload.typ) {
386
+ case 'genesis':
387
+ if (endorserRef)
388
+ return invalid('a genesis names an endorser', payload);
389
+ expected.push({ key: subject, kid: payload.subject.kid });
390
+ break;
391
+ case 'succession':
392
+ if (!endorser || !endorserRef)
393
+ return invalid('a succession names no endorser', payload);
394
+ if (endorserRef.spkiSha256 === payload.subject.spkiSha256)
395
+ return invalid('a succession endorses its own key', payload);
396
+ expected.push({ key: endorser, kid: endorserRef.kid }, { key: subject, kid: payload.subject.kid });
397
+ break;
398
+ case 'closure':
399
+ if (!endorser || !endorserRef)
400
+ return invalid('a closure names no signer', payload);
401
+ if (endorserRef.spkiSha256 === payload.subject.spkiSha256)
402
+ return invalid('a closure is signed by the key it closes', payload);
403
+ if (payload.subject.retiredAt === undefined || payload.forced === undefined) {
404
+ return invalid('a closure carries no retiredAt or forced', payload);
405
+ }
406
+ expected.push({ key: endorser, kid: endorserRef.kid });
407
+ break;
408
+ }
409
+ if (payload.typ !== 'closure' && payload.forced !== undefined)
410
+ return invalid('only a closure carries forced', payload);
411
+ if (parts.length !== expected.length) {
412
+ return invalid(`a ${payload.typ} carries ${expected.length} signature(s), this one carries ${parts.length}`, payload);
413
+ }
414
+ let unsupported = false;
415
+ let subjectSigned = false;
416
+ let endorserSigned = false;
417
+ for (const [i, want] of expected.entries()) {
418
+ const outcome = checkSignature(parts[i], want.key, want.kid);
419
+ if (outcome === 'bad')
420
+ return invalid(`signature ${i + 1} does not verify under the key it names`, payload);
421
+ if (outcome === 'unsupported')
422
+ unsupported = true;
423
+ const bySubject = payload.typ === 'genesis' || (payload.typ === 'succession' && i === 1);
424
+ if (outcome === 'ok' && bySubject)
425
+ subjectSigned = true;
426
+ if (outcome === 'ok' && !bySubject)
427
+ endorserSigned = true;
428
+ }
429
+ return { input, id, verdict: unsupported ? 'unverifiable' : 'valid', detail: null, payload, digest, subjectSigned, endorserSigned };
430
+ }
431
+ function reach(anchors, edges) {
432
+ const out = new Set(anchors);
433
+ for (let grew = true; grew;) {
434
+ grew = false;
435
+ for (const e of edges) {
436
+ if (out.has(e.from) && !out.has(e.to)) {
437
+ out.add(e.to);
438
+ grew = true;
439
+ }
440
+ }
441
+ }
442
+ return out;
443
+ }
444
+ /** A microsecond count as the RFC 3339 UTC instant the statements sign. */
445
+ function instantOfUs(us) {
446
+ const ms = Math.floor(us / 1000);
447
+ return `${new Date(ms).toISOString().slice(0, 23)}${String(us - ms * 1000).padStart(3, '0')}Z`;
448
+ }
449
+ /**
450
+ * Whether an instant a statement signs is later than when it was stored, at
451
+ * the precision its write time carries: a dump's millisecond `created_at`
452
+ * hides the microseconds, so an instant in the same millisecond is not later.
453
+ * False under the signed order, where nothing says when it was stored.
454
+ */
455
+ function signedAfterWrite(signed, s) {
456
+ if (s.written === null)
457
+ return false;
458
+ const at = instantUs(signed).us;
459
+ return s.written.micro ? at > s.written.us : Math.floor(at / 1000) > s.storedMs;
460
+ }
461
+ /** The earlier of an instant a statement signs and its write time (see {@link signedAfterWrite}). */
462
+ function notAfterWrite(signed, s) {
463
+ if (!signedAfterWrite(signed, s))
464
+ return signed;
465
+ return instantOfUs(s.written.micro ? s.written.us : s.storedMs * 1000);
466
+ }
467
+ /** The instant a statement signs, which orders it when the source carries no write time. */
468
+ function signedInstantOf(c) {
469
+ if (c.payload === null)
470
+ return null;
471
+ return c.payload.typ === 'closure' ? c.payload.subject.retiredAt ?? null : c.payload.subject.activatedAt;
472
+ }
473
+ /**
474
+ * Walk the key statements from `trustAnchors` and decide which keys are
475
+ * trusted and what window each carries. Two passes, no fixpoint:
476
+ *
477
+ * 1. Reach every key from the anchors over every edge, ignoring closures.
478
+ * 2. Apply every closure whose signer pass 1 reaches: a key's window ends at
479
+ * the earliest `retiredAt` among them, a forced one voids every edge out
480
+ * of the key, forward and back, and any edge out of the key stored after
481
+ * its first such closure is void.
482
+ * 3. Reach again without the void edges, taking a key's edge back only
483
+ * through its sole admission. That set is the trusted set.
484
+ *
485
+ * The edges: a succession E->K links E forward to K and K back to E. A key's
486
+ * admission is the first genesis or succession naming it; pass 3 takes K's
487
+ * edge back only when the succession is K's admission and K has exactly one.
488
+ *
489
+ * Closures only remove edges and shorten windows, so a closure signed by a
490
+ * leaked key is at worst a denial of service, never a key trusted that was
491
+ * not before. A distrusted key is the one thing that makes a closure stop
492
+ * counting: what it stores at or after its cutoff counts for nothing.
493
+ *
494
+ * Throws `TypeError` on malformed anchors or distrusted keys, on no anchors
495
+ * at all, and when some statements carry `createdAt` and others do not.
496
+ */
497
+ export function computeKeyTrust(input) {
498
+ assertKnownOptions('computeKeyTrust', input, ['keys', 'statements', 'trustAnchors', 'distrustedKeys']);
499
+ const anchorDigests = parseTrustAnchors(input.trustAnchors);
500
+ if (anchorDigests.length === 0) {
501
+ throw new TypeError('computeKeyTrust needs at least one trust anchor (sha256:<64 hex>). With none, no key can be trusted.');
502
+ }
503
+ const anchors = new Set(anchorDigests);
504
+ const distrustedKeys = normalizeDistrusted(input.distrustedKeys);
505
+ if (!Array.isArray(input.statements) || !Array.isArray(input.keys)) {
506
+ throw new TypeError('computeKeyTrust takes arrays of keys and statements.');
507
+ }
508
+ const withTime = input.statements.filter((s) => typeof s.createdAt === 'string').length;
509
+ if (withTime !== 0 && withTime !== input.statements.length) {
510
+ throw new TypeError('Key statements must all carry createdAt (a dump) or none (a key document); this input mixes them.');
511
+ }
512
+ // A listed key with no key material (a dump row whose public_key was nulled)
513
+ // vouches for nothing and is no endorser's fallback.
514
+ const listedKeys = input.keys.filter((k) => typeof k.publicKey === 'string' && k.publicKey !== '');
515
+ const order = input.statements.length > 0 && withTime === input.statements.length ? 'written' : 'signed';
516
+ // One stored row, read from two sources (an export and a key document), is
517
+ // one statement. With no write time and no row id, two identical
518
+ // statements are one; with them, a row is its id and write time, and a copy
519
+ // of a row under another id is a second row, as the engine reads it.
520
+ const seen = new Set();
521
+ const statementInputs = input.statements.filter((s) => {
522
+ const cose = Array.isArray(s.cose) ? s.cose : [];
523
+ const bytes = cose.map((c) => {
524
+ const b = toBytes(c);
525
+ return b === null ? `?${String(c)}` : Buffer.from(b).toString('base64');
526
+ }).join('|');
527
+ if (order === 'written' && typeof s.id !== 'string')
528
+ return true;
529
+ // The same row however its time and id are spelled: `Z` or `+00:00`, a
530
+ // uuid in either case.
531
+ const at = instantUs(s.createdAt ?? '');
532
+ const key = order === 'written' ? JSON.stringify([s.id.toLowerCase(), Number.isNaN(at.us) ? s.createdAt : at.us, bytes]) : bytes;
533
+ if (seen.has(key))
534
+ return false;
535
+ seen.add(key);
536
+ return true;
537
+ });
538
+ const findings = [];
539
+ // An endorser's key material, by digest. A statement's subject SPKI is bound
540
+ // to its digest by the payload check and its algorithm is signed, so it is
541
+ // taken first; a listed key is the fallback for a key no statement names as
542
+ // its subject (one anchored only by a pin). The listed algorithm is the
543
+ // source's word, and a statement never turns invalid because it was rewritten.
544
+ const keyByDigest = new Map();
545
+ for (const st of statementInputs) {
546
+ const sign1 = Array.isArray(st.cose) && st.cose.length > 0 ? decodeSign1(st.cose[0]) : null;
547
+ const payload = sign1 ? decodeKeyStatementPayload(sign1.payloadBstr) : null;
548
+ if (payload && !keyByDigest.has(payload.subject.spkiSha256)) {
549
+ keyByDigest.set(payload.subject.spkiSha256, { spki: payload.subject.spki, alg: payload.subject.alg });
550
+ }
551
+ }
552
+ for (const key of listedKeys) {
553
+ const digest = spkiSha256(key.publicKey);
554
+ if (!keyByDigest.has(digest))
555
+ keyByDigest.set(digest, { spki: key.publicKey, alg: typeof key.algorithm === 'string' ? key.algorithm : null });
556
+ }
557
+ // Under the write order a statement with no write time cannot be placed:
558
+ // the Server writes one on every row, so it was edited, and it admits nothing.
559
+ const checked = statementInputs.map((st) => {
560
+ const c = checkKeyStatement(st, keyByDigest);
561
+ if (order !== 'written' || !Number.isNaN(rfc3339Ms(st.createdAt)))
562
+ return c;
563
+ return { ...c, verdict: 'invalid', detail: 'the row has no parseable created_at to order it by' };
564
+ });
565
+ const place = (c, i) => {
566
+ if (order === 'written') {
567
+ const at = instantUs(c.input.createdAt);
568
+ return { c, i, k: Number.isNaN(at.us) ? Number.POSITIVE_INFINITY : at.us, micro: at.micro, r: 0 };
569
+ }
570
+ return { c, i, k: signedInstantOf(c) ?? '￿', micro: false, r: closureLast(c) };
571
+ };
572
+ const tieById = (a, b) => {
573
+ const x = a.c.input.id;
574
+ const y = b.c.input.id;
575
+ if (!a.micro || !b.micro || typeof x !== 'string' || typeof y !== 'string')
576
+ return 0;
577
+ const [lx, ly] = [x.toLowerCase(), y.toLowerCase()];
578
+ return lx < ly ? -1 : lx > ly ? 1 : 0;
579
+ };
580
+ // Under the signed order a closure sorts after every admission that signs
581
+ // the same instant, whatever order the document lists them in. A rotation
582
+ // signs the successor's activatedAt and the predecessor's retiredAt as one
583
+ // instant, and the Server writes the succession first. This lets no
584
+ // statement past a closure that the order did not already let through: the
585
+ // closure still voids every edge its key signs at any later instant, a
586
+ // forced one or a distrusted key voids them all, and a document that did
587
+ // not come from the Server could list the succession first anyway.
588
+ const closureLast = (c) => (order === 'signed' && c.payload?.typ === 'closure' ? 1 : 0);
589
+ // A dump row whose signed payload an earlier row already carries says
590
+ // nothing new: a copy of a row (anything with write access to the database
591
+ // can write one), or the same payload signed again. Only the first, in
592
+ // write order, takes part, as the engine reads it; the database stamps the
593
+ // write time, so a copy always lands after what it copies. A key document's
594
+ // write time is its holder's word, so there a copy dated earlier would push
595
+ // the published statement aside: on a document a copy stays a second
596
+ // statement, which only ever narrows trust, and the Server publishes none.
597
+ const seenPayload = new Set();
598
+ const inWriteOrder = checked
599
+ .map(place)
600
+ .sort((a, b) => (a.k < b.k ? -1 : a.k > b.k ? 1 : a.r - b.r || tieById(a, b) || a.i - b.i))
601
+ .filter(({ c }) => {
602
+ if (c.verdict === 'invalid' || c.payload === null || c.digest === null || c.input.source !== 'dump')
603
+ return true;
604
+ if (seenPayload.has(c.digest))
605
+ return false;
606
+ seenPayload.add(c.digest);
607
+ return true;
608
+ })
609
+ .flatMap(({ c, k, micro }, at) => c.verdict === 'invalid' || c.payload === null ? [] : [{
610
+ check: c,
611
+ payload: c.payload,
612
+ subject: c.payload.subject.spkiSha256,
613
+ endorser: c.payload.endorser?.spkiSha256 ?? null,
614
+ at,
615
+ storedMs: typeof k === 'number' ? rfc3339Ms(c.input.createdAt) : instantMs(k),
616
+ written: typeof k === 'number' ? { us: k, micro } : null,
617
+ }]);
618
+ const valid = inWriteOrder.filter((s) => s.check.verdict === 'valid');
619
+ // Each key's admission: the first genesis or succession naming it, over
620
+ // every statement whose signatures did not fail. A second admission is its
621
+ // private half in someone else's hands, so the edge back from a key runs
622
+ // only while it has exactly one, and its window opens at the latest
623
+ // instant any of them signs.
624
+ const admissions = new Map();
625
+ const admittedTwice = new Set();
626
+ const activatedAt = new Map();
627
+ for (const s of inWriteOrder) {
628
+ if (s.payload.typ === 'closure')
629
+ continue;
630
+ if (admissions.has(s.subject))
631
+ admittedTwice.add(s.subject);
632
+ else
633
+ admissions.set(s.subject, s);
634
+ const signed = s.payload.subject.activatedAt;
635
+ if (s.check.verdict === 'valid' && (activatedAt.get(s.subject) ?? signed) <= signed)
636
+ activatedAt.set(s.subject, signed);
637
+ }
638
+ const edgesOf = (s) => {
639
+ const e = s.endorser;
640
+ if (e === null || s.payload.typ !== 'succession')
641
+ return [];
642
+ return [
643
+ { from: e, to: s.subject, via: s, counts: true },
644
+ { from: s.subject, to: e, via: s, counts: admissions.get(s.subject) === s && !admittedTwice.has(s.subject) },
645
+ ];
646
+ };
647
+ const edges = valid.flatMap(edgesOf);
648
+ // Distrusted keys and the instant each one's statements stop counting from.
649
+ const distrust = new Set(distrustedKeys.map((d) => d.spkiSha256));
650
+ const cutoffs = new Map();
651
+ const distrustSpans = new Map();
652
+ if (distrust.size > 0) {
653
+ const clear = reach(anchors, edges.filter((e) => !distrust.has(e.from)));
654
+ for (const d of distrustedKeys) {
655
+ // The retirement a key the walk still trusts signed for it, no later
656
+ // than that closure's own write time: a retirement dated ahead must not
657
+ // stretch what the entry accounts for.
658
+ let retiredBy = null;
659
+ for (const s of valid) {
660
+ if (s.subject !== d.spkiSha256 || s.payload.typ !== 'closure')
661
+ continue;
662
+ const by = s.endorser;
663
+ const signed = s.payload.subject.retiredAt;
664
+ if (by === null || distrust.has(by) || !clear.has(by) || signed === undefined)
665
+ continue;
666
+ const retiredAt = notAfterWrite(signed, s);
667
+ if (retiredBy === null || retiredAt < retiredBy)
668
+ retiredBy = retiredAt;
669
+ }
670
+ const instant = d.cutoff ?? retiredBy;
671
+ cutoffs.set(d.spkiSha256, instant === null ? null : { at: instantMs(instant), instant });
672
+ distrustSpans.set(d.spkiSha256, { cutoff: instant, retiredAt: retiredBy });
673
+ }
674
+ }
675
+ /**
676
+ * A dump statement a distrusted key signed and stored before a key the walk
677
+ * still trusts retired it: the distrust entry and that retirement account
678
+ * for it.
679
+ */
680
+ const accountedFor = (s, signer) => {
681
+ const retiredAt = distrustSpans.get(signer)?.retiredAt ?? null;
682
+ return retiredAt !== null && s.check.input.source === 'dump' && s.written !== null && s.storedMs < instantMs(retiredAt);
683
+ };
684
+ /**
685
+ * Signed by a distrusted key at or after its cutoff: counts for nothing.
686
+ * Only a dump row's write time is held against the cutoff, and only as far
687
+ * as the dump came from the Server. A key document's `createdAt` is the
688
+ * word of whoever holds the file, and under the signed order the instant a
689
+ * statement signs is the leaked key's own word. So for any statement that
690
+ * is not a dump row, every edge out of a distrusted key is void whatever
691
+ * time it carries, and every closure it signed still counts: dropping an
692
+ * edge or keeping a closure only ever takes trust away. Narrower than the
693
+ * engine, never wider. The write order still orders such statements.
694
+ */
695
+ const distrusted = (s, signer) => {
696
+ if (signer === null || !cutoffs.has(signer))
697
+ return false;
698
+ if (order === 'signed' || s.check.input.source !== 'dump')
699
+ return s.payload.typ !== 'closure';
700
+ const cutoff = cutoffs.get(signer);
701
+ return cutoff === null || cutoff === undefined || s.storedMs >= cutoff.at;
702
+ };
703
+ /**
704
+ * What the engine would void: signed by a distrusted key with no cutoff, or
705
+ * stored at or after its cutoff. On a key document the stored time is the
706
+ * holder's word, so this decides only whether voiding it is a finding.
707
+ */
708
+ const voidedByStoredTime = (s, signer) => {
709
+ const cutoff = cutoffs.get(signer);
710
+ return cutoff === null || cutoff === undefined || (order === 'written' && s.storedMs >= cutoff.at);
711
+ };
712
+ const notes = [];
713
+ const accounted = [];
714
+ // Pass 1, then the closures it lets count.
715
+ const pass1 = reach(anchors, edges.filter((e) => !distrusted(e.via, e.from)));
716
+ const counting = valid.filter((s) => s.payload.typ === 'closure' && s.endorser !== null
717
+ && pass1.has(s.endorser) && !distrusted(s, s.endorser));
718
+ const closedAt = new Map();
719
+ const closedWindow = new Map();
720
+ const forced = new Set();
721
+ const closuresOf = new Map();
722
+ for (const c of counting) {
723
+ closuresOf.set(c.subject, [...closuresOf.get(c.subject) ?? [], c]);
724
+ if (!closedAt.has(c.subject))
725
+ closedAt.set(c.subject, c.at);
726
+ const retiredAt = c.payload.subject.retiredAt;
727
+ if (retiredAt !== undefined && (closedWindow.get(c.subject) ?? retiredAt) >= retiredAt)
728
+ closedWindow.set(c.subject, retiredAt);
729
+ if (c.payload.forced === true)
730
+ forced.add(c.subject);
731
+ }
732
+ const voided = (edge) => {
733
+ if (!edge.counts || forced.has(edge.from) || distrusted(edge.via, edge.from))
734
+ return true;
735
+ const closed = closedAt.get(edge.from);
736
+ return closed !== undefined && edge.via.at > closed;
737
+ };
738
+ // Pass 2: the trusted set.
739
+ const trusted = reach(anchors, edges.filter((e) => !voided(e)));
740
+ const untrusted = [...cutoffs].filter(([, c]) => c === null).map(([d]) => d);
741
+ for (const d of untrusted)
742
+ trusted.delete(d);
743
+ // What a distrust entry accounts for is bounded only by a retirement a key
744
+ // the walk trusts signed. Bounded by any key reached without a distrusted
745
+ // key, a forced closure's cut-off keys included, a key cut off from a
746
+ // leaked one could retire a distrusted key it also holds and have what that
747
+ // key forged read as accounted for. Only a signer the walk trusts and
748
+ // reaches without a distrusted key bounds it, as in the engine; the cutoff
749
+ // a bound gives an undated entry comes from the reach alone.
750
+ const clearOfDistrust = reach(anchors, edges.filter((e) => !distrust.has(e.from)));
751
+ for (const [d, span] of distrustSpans) {
752
+ let retiredBy = null;
753
+ for (const s of valid) {
754
+ if (s.subject !== d || s.payload.typ !== 'closure' || s.endorser === null || distrust.has(s.endorser)
755
+ || !clearOfDistrust.has(s.endorser) || !trusted.has(s.endorser))
756
+ continue;
757
+ const retiredAt = notAfterWrite(s.payload.subject.retiredAt, s);
758
+ if (retiredBy === null || retiredAt < retiredBy)
759
+ retiredBy = retiredAt;
760
+ }
761
+ distrustSpans.set(d, { cutoff: span.cutoff, retiredAt: retiredBy });
762
+ }
763
+ // Keys this host cannot decide: reached only through a statement signed
764
+ // under an algorithm it cannot compute, and of such an algorithm themselves.
765
+ // A key it can compute, reached only through a half it cannot check, is
766
+ // reached through bytes anyone with database access writes as easily as the
767
+ // Server: it is unanchored.
768
+ const undecided = new Set();
769
+ // The undecided keys one step from the trusted set, through the half of the
770
+ // statement this host verified. Past that step every signature on the path
771
+ // is one anything with database access could have written, so nothing
772
+ // further is vouched for. The Server publishes these with their admission.
773
+ const vouched = new Set();
774
+ const unverifiable = inWriteOrder.filter((s) => s.check.verdict === 'unverifiable');
775
+ if (unverifiable.length > 0) {
776
+ const all = [...edges, ...unverifiable.flatMap(edgesOf)].filter((e) => !voided(e));
777
+ for (const d of reach(anchors, all))
778
+ if (!trusted.has(d))
779
+ undecided.add(d);
780
+ for (const edge of unverifiable.flatMap(edgesOf)) {
781
+ if (!trusted.has(edge.from) || voided(edge) || trusted.has(edge.to))
782
+ continue;
783
+ const forward = edge.from === edge.via.endorser;
784
+ if (forward ? edge.via.check.endorserSigned : edge.via.check.subjectSigned)
785
+ vouched.add(edge.to);
786
+ }
787
+ for (const d of vouched)
788
+ undecided.add(d);
789
+ for (const d of untrusted)
790
+ undecided.delete(d);
791
+ for (const d of undecided) {
792
+ const known = keyByDigest.get(d);
793
+ if (!known || materialFor(known.spki, known.alg).alg !== 'unsupported') {
794
+ undecided.delete(d);
795
+ vouched.delete(d);
796
+ }
797
+ }
798
+ }
799
+ // Each trusted key's window. It opens at the latest `activatedAt` its
800
+ // verified admissions sign, so a statement added later only narrows it.
801
+ const byDigest = new Map();
802
+ const entryFor = (digest) => {
803
+ const existing = byDigest.get(digest);
804
+ if (existing)
805
+ return existing;
806
+ const created = {
807
+ keyId: digest.slice(0, 16), spkiSha256: digest, trusted: trusted.has(digest), undecided: undecided.has(digest), activatedAt: null, retiredAt: null, distrustCutoff: null,
808
+ };
809
+ byDigest.set(digest, created);
810
+ return created;
811
+ };
812
+ for (const key of listedKeys)
813
+ entryFor(spkiSha256(key.publicKey));
814
+ for (const d of undecided)
815
+ entryFor(d);
816
+ for (const d of trusted) {
817
+ const entry = entryFor(d);
818
+ entry.activatedAt = activatedAt.get(d) ?? null;
819
+ entry.retiredAt = closedWindow.get(d) ?? null;
820
+ const cutoff = cutoffs.get(d)?.instant;
821
+ if (cutoff !== undefined && (entry.retiredAt === null || cutoff < entry.retiredAt))
822
+ entry.distrustCutoff = cutoff;
823
+ }
824
+ // Findings on statements.
825
+ const finding = (code, s, detail) => findings.push({ code, keyId: s.payload.subject.kid, statementId: s.check.id, detail });
826
+ for (const c of checked) {
827
+ if (c.verdict === 'invalid') {
828
+ findings.push({
829
+ code: 'KEY_STATEMENT_INVALID',
830
+ keyId: c.payload?.subject.kid ?? c.input.subjectKeyId ?? null,
831
+ statementId: c.id,
832
+ detail: c.detail ?? 'invalid',
833
+ });
834
+ }
835
+ }
836
+ // The earliest activation any admission signs for a key: a later admission
837
+ // (the key's own half, leaked) can move the window's lower edge, and must not
838
+ // make an honest closure read as dated before it.
839
+ const firstActivation = new Map();
840
+ for (const s of valid) {
841
+ if (s.payload.typ === 'closure')
842
+ continue;
843
+ const from = s.payload.subject.activatedAt;
844
+ if ((firstActivation.get(s.subject) ?? from) >= from)
845
+ firstActivation.set(s.subject, from);
846
+ }
847
+ /** What to tell an auditor who holds no other evidence of a key leaking: pin it if honest, never once it is distrusted. */
848
+ const pinRemedy = (e, by) => (cutoffs.has(e)
849
+ ? ''
850
+ : ` If ${by} is honest, pin sha256:${e} in trustAnchors (VAULT_TRUST_ANCHORS on the Server, which publishes it).`);
851
+ for (const s of valid) {
852
+ const e = s.endorser;
853
+ const by = s.payload.endorser?.kid ?? '';
854
+ const voided = e !== null && distrusted(s, e);
855
+ // The admission of a key the walk trusts by another path (its own pin, as
856
+ // when a fresh key was staged with the leaked one as its predecessor after
857
+ // the leak), signed by a distrusted key from its cutoff on: the voided
858
+ // endorsement takes nothing away and grants nothing, so it is no finding.
859
+ // Only the key's first admission: a later one is a second admission,
860
+ // which cuts the key's edge back and redates it, and stays a finding.
861
+ if (voided && voidedByStoredTime(s, e) && s.payload.typ !== 'closure' && trusted.has(s.subject) && admissions.get(s.subject) === s)
862
+ continue;
863
+ if (voided && !voidedByStoredTime(s, e)) {
864
+ // Voided only because a key document's time is not held against the
865
+ // cutoff: it admits nothing, but a statement the engine would count is
866
+ // no finding. It still dates windows and cuts edges back, so it can
867
+ // only narrow trust. The checks below still apply to it.
868
+ const cutoff = cutoffs.get(e);
869
+ notes.push({
870
+ keyId: s.payload.subject.kid,
871
+ statementId: s.check.id,
872
+ detail: `a ${s.payload.typ} by ${by}, which distrustedKeys distrusts from ${cutoff.instant}; it admits nothing here, because a key document's write time${typeof s.check.input.createdAt === 'string' ? ` (${s.check.input.createdAt})` : ''} is not signed and is not held against the cutoff. A dump taken from the Server holds it to the time it was stored.`,
873
+ });
874
+ }
875
+ else if (voided) {
876
+ const cutoff = cutoffs.get(e);
877
+ const closed = s.payload.subject.retiredAt;
878
+ const now = byDigest.get(s.subject);
879
+ const ends = now?.distrustCutoff ?? now?.retiredAt ?? null;
880
+ // Dropping a closure the distrusted key signed reopens its subject.
881
+ const reopened = s.payload.typ === 'closure' && closed !== undefined && now?.trusted === true
882
+ && (ends === null || ends > closed)
883
+ ? ` It retired ${s.payload.subject.kid} at ${closed}, and no closure that counts retires it that early now; if ${s.payload.subject.kid} leaked as well, add sha256:${s.subject} to distrustedKeys too.`
884
+ : '';
885
+ const code = s.payload.typ === 'closure' ? 'KEY_CLOSURE_INVALID' : 'KEY_STATEMENT_INVALID';
886
+ const what = `a ${s.payload.typ} by ${by}, which distrustedKeys distrusts ${cutoff ? `from ${cutoff.instant}` : 'entirely'}; it counts for nothing.`;
887
+ if (s.check.input.source !== 'dump' || s.written === null) {
888
+ finding(code, s, `${what}${reopened}`);
889
+ }
890
+ else {
891
+ // A dump row: held to when the Server stored it.
892
+ const retiredBy = distrustSpans.get(e)?.retiredAt ?? null;
893
+ // A later admission of a trusted key that the key itself signed is
894
+ // the record of its own half leaking, whoever co-signed it: never
895
+ // accounted for, as in the engine.
896
+ const leakedSubject = s.payload.typ !== 'closure' && admissions.get(s.subject) !== s && s.check.subjectSigned && trusted.has(s.subject);
897
+ if (leakedSubject) {
898
+ finding(code, s, `${what} It is also a ${s.payload.typ} ${s.payload.subject.kid} signed after it was already admitted: ${s.payload.subject.kid}'s private half in other hands, which no distrust entry for ${by} accounts for. Move every Server process off ${s.payload.subject.kid}, retire it with force from the key they hold, and give distrustedKeys sha256:${s.subject}@<the instant it leaked> (VAULT_DISTRUSTED_KEYS on every Server process).`);
899
+ }
900
+ else if (reopened === '' && accountedFor(s, e)) {
901
+ accounted.push({
902
+ keyId: s.payload.subject.kid,
903
+ statementId: s.check.id,
904
+ detail: `${what} Stored before ${retiredBy ?? ''}, when a key the walk trusts retired ${by}, so the distrust entry accounts for it: evidence of what ${by} signed, not a finding.`,
905
+ });
906
+ }
907
+ else {
908
+ const after = retiredBy === null
909
+ ? ` No closure a key the walk trusts signs retires ${by}, so nothing bounds what the distrust entry accounts for: retire ${by} with force on the Server from a process on a key you hold.`
910
+ : !accountedFor(s, e) ? ` It was stored after ${retiredBy}, when a key the walk trusts retired ${by}: ${by}'s private half is still in use by someone with write access to the Server's database.` : '';
911
+ finding(code, s, `${what}${reopened}${after}`);
912
+ }
913
+ }
914
+ continue;
915
+ }
916
+ if (s.payload.typ === 'closure') {
917
+ const retiredAt = s.payload.subject.retiredAt ?? '';
918
+ const activated = byDigest.get(s.subject)?.trusted === true ? firstActivation.get(s.subject) ?? null : null;
919
+ const signerClosed = e === null ? undefined : closedAt.get(e);
920
+ const before = findings.length;
921
+ // The instant to suggest when nothing earlier is known: the signer's own
922
+ // retirement, each closure's signed instant capped at its write time (a
923
+ // closure dated ahead voids nothing), or else this closure's write time.
924
+ // A pin on the signer stays, since the entry is dated.
925
+ const own = e === null ? [] : closuresOf.get(e) ?? [];
926
+ let until = s.written === null ? null : instantOfUs(s.written.micro ? s.written.us : s.storedMs * 1000);
927
+ for (const c of own) {
928
+ const capped = notAfterWrite(c.payload.subject.retiredAt ?? '', c);
929
+ if (capped !== '' && (until === null || capped < until))
930
+ until = capped;
931
+ }
932
+ const known = until === null ? '' : `; if nothing earlier is known, ${until}, ${own.length > 0 ? 'its retirement' : 'when this closure was stored'}`;
933
+ const distrustHint = `If ${by} leaked, give distrustedKeys sha256:${e ?? ''}@<instant> (VAULT_DISTRUSTED_KEYS on every Server process), the instant being the earliest time ${by} may have leaked${known}. What it signed from that instant on, this closure included, counts for nothing. Keep a trustAnchors pin on ${by} if it has one, and date the entry no later than the leak: beside a pin, everything ${by} stored before the instant still counts.`;
934
+ if (e === null || !pass1.has(e))
935
+ finding('KEY_CLOSURE_INVALID', s, 'the closure is signed by a key that is not anchored');
936
+ else if (signerClosed !== undefined && s.at > signerClosed) {
937
+ finding('KEY_CLOSURE_INVALID', s, `the closure is signed by ${by} after its own retirement, and still counts: it ends ${s.payload.subject.kid}'s window at ${retiredAt}. ${distrustHint}`);
938
+ }
939
+ else if (activated !== null && retiredAt < activated) {
940
+ finding('KEY_CLOSURE_INVALID', s, `the closure retires ${s.payload.subject.kid} at ${retiredAt}, before the ${activated} it was activated, and still counts. ${distrustHint}`);
941
+ }
942
+ else if (!trusted.has(e) && (trusted.has(s.subject) || vouched.has(s.subject))) {
943
+ // The Server publishes only trusted and vouched keys, and every
944
+ // counting closure of a published key with it, so a walk over the
945
+ // subject's key document cannot verify this one: every document and
946
+ // every audit export carrying it fails offline, whether or not a
947
+ // published closure dates the window as early.
948
+ const published = (closuresOf.get(s.subject) ?? []).filter((c) => trusted.has(c.endorser ?? ''));
949
+ const earlier = published.every((c) => retiredAt < (c.payload.subject.retiredAt ?? ''));
950
+ const forcedAlone = s.payload.forced === true && !published.some((c) => c.payload.forced === true);
951
+ const effect = earlier
952
+ ? `: it ends ${s.payload.subject.kid}'s window at ${retiredAt}, earlier than any closure a published key signs`
953
+ : forcedAlone ? `: it retires ${s.payload.subject.kid} with force, which no closure a published key signs does` : '';
954
+ const at = typeof s.check.input.createdAt === 'string' ? `@${s.check.input.createdAt}` : '';
955
+ // A distrusted signer is never named as a pin. Its closure counts here
956
+ // only where it was stored before the cutoff, or is in a key document,
957
+ // where a closure only narrows trust.
958
+ const remedy = cutoffs.has(e)
959
+ ? ` ${by} is in distrustedKeys, and this closure still counts: ${s.check.input.source === 'dump' && s.written !== null ? `it was stored before the cutoff, so if ${by} leaked earlier, date its entry no later than ${s.check.input.createdAt ?? ''}` : 'a closure it signed in a key document still counts here, since a closure only narrows trust; the Server counts it for nothing only when it was stored at or after the cutoff'}.`
960
+ : `${pinRemedy(e, by)} If it leaked, distrustedKeys sha256:${e}${at} (VAULT_DISTRUSTED_KEYS on the Server) makes this closure, and what ${by} signed after it, count for nothing.`;
961
+ finding('KEY_CLOSURE_INVALID', s, `the closure is signed by ${by}, which is reached but not anchored, and still counts${effect}. No key surface publishes ${by}, so an offline walk over the published statements cannot verify it, and every audit export carrying them fails offline verification.${remedy}`);
962
+ }
963
+ // A retirement dated ahead of when it was stored: the Server never signs
964
+ // one, and it keeps its subject open until then.
965
+ if (e !== null && pass1.has(e) && signedAfterWrite(retiredAt, s) && findings.length === before) {
966
+ finding('KEY_CLOSURE_INVALID', s, `the closure dates ${s.payload.subject.kid}'s retirement at ${retiredAt}, after ${s.check.input.createdAt ?? ''} when it was stored, and still counts: ${s.payload.subject.kid}'s window ends then. The Server never signs a retirement ahead of the call; if ${by} did not sign this, ${distrustHint}`);
967
+ }
968
+ continue;
969
+ }
970
+ if (!trusted.has(s.subject) && (e === null || !trusted.has(e))) {
971
+ finding('KEY_STATEMENT_INVALID', s, `a ${s.payload.typ} that touches no anchored key`);
972
+ }
973
+ else if (s.at > (closedAt.get(s.subject) ?? Infinity)) {
974
+ finding('KEY_STATEMENT_INVALID', s, `a ${s.payload.typ} of a key stored after its closure; it admits nothing`);
975
+ }
976
+ else if (admissions.get(s.subject) !== s) {
977
+ // A key is admitted once. What it signs itself in with later is a
978
+ // leaked key naming a predecessor or redating itself.
979
+ finding('KEY_STATEMENT_INVALID', s, `a ${s.payload.typ} its subject signed after it was already admitted: ${s.payload.subject.kid}'s private half in other hands. It is the record of the leak, and no setting clears it: move every Server process off ${s.payload.subject.kid}, retire it with force from the key they hold, and give distrustedKeys sha256:${s.subject}@<the instant it leaked> (VAULT_DISTRUSTED_KEYS on every Server process), which stops what its leaked half signs from then on counting.`);
980
+ }
981
+ else if (e !== null && trusted.has(s.subject) && !trusted.has(e) && !vouched.has(e)) {
982
+ // The admission of a key trusted by another path (a pin, or the edge
983
+ // back from a key it admitted) whose endorser the walk does not trust:
984
+ // history a forced closure cut off. The Server publishes it with the
985
+ // key and does not publish its endorser, so no offline walk verifies it.
986
+ finding('KEY_STATEMENT_INVALID', s, `${s.payload.subject.kid} is trusted, and its admission is a ${s.payload.typ} signed by ${by}, which the walk does not trust (a forced closure cut it off, or it was never linked). No key surface publishes ${by}, so an offline walk over the published statements cannot verify it, and every audit export carrying them fails offline verification.${pinRemedy(e, by)}`);
987
+ }
988
+ else if (e !== null && trusted.has(e)) {
989
+ const closed = closedAt.get(e);
990
+ if (closed !== undefined && s.at > closed)
991
+ finding('KEY_STATEMENT_INVALID', s, `a ${s.payload.typ} by ${by} stored after its closure`);
992
+ }
993
+ }
994
+ // A vouched key is published with its admission, which this host cannot
995
+ // check. Where that admission's endorser is not published either, no
996
+ // verifier off-host can check it from what is published.
997
+ for (const d of vouched) {
998
+ const s = admissions.get(d);
999
+ const e = s?.endorser ?? null;
1000
+ if (!s || e === null || trusted.has(e) || vouched.has(e))
1001
+ continue;
1002
+ const by = s.payload.endorser?.kid ?? '';
1003
+ finding('KEY_STATEMENT_INVALID', s, `${s.payload.subject.kid} is reached through a trusted key's signature, and its admission is a ${s.payload.typ} signed by ${by}, which no key surface publishes, so an offline walk over the published statements cannot verify it, and every audit export carrying them fails offline verification.${pinRemedy(e, by)}`);
1004
+ }
1005
+ // Keys an admission names that this walk could not verify. A key document
1006
+ // carries a key's admissions but not every endorser, so the walk can date a
1007
+ // trusted key's window earlier than the engine did, or not at all.
1008
+ const unverifiedAdmission = new Set(checked
1009
+ .filter((c) => c.verdict === 'invalid' && c.payload !== null && c.payload.typ !== 'closure')
1010
+ .map((c) => c.payload.subject.spkiSha256));
1011
+ // A listed retirement the walk does not sign, read against the Server's own
1012
+ // distrust instant (`distrustedFrom`): where the listing was cut at that
1013
+ // instant and the walk signs a later retirement or none, the column is the
1014
+ // Server's distrust entry, which the caller either was not given or gave
1015
+ // another instant. Only the wording of a finding the check below makes
1016
+ // anyway, never whether it makes one: `distrustedFrom` is the source's word.
1017
+ const givenCutoff = new Map(distrustedKeys.map((d) => [d.spkiSha256, d.cutoff]));
1018
+ const sameInstant = (a, b) => instantUs(a).us === instantUs(b).us;
1019
+ const cutByServer = (key, entry) => {
1020
+ const from = key.distrustedFrom;
1021
+ if (typeof from !== 'string' || typeof key.retiredAt !== 'string')
1022
+ return null;
1023
+ const fromMs = instantMs(from);
1024
+ if (Number.isNaN(fromMs) || instantMs(key.retiredAt) !== fromMs)
1025
+ return null;
1026
+ if (entry.retiredAt !== null && !(instantMs(entry.retiredAt) > fromMs))
1027
+ return null;
1028
+ const signed = entry.retiredAt === null ? 'no closure this walk could verify retires it' : `the retirement its closures sign is ${entry.retiredAt}`;
1029
+ const lead = `retiredAt ${key.retiredAt} is listed as the Server's distrust cutoff for ${key.keyId} (distrustedFrom ${from}), and ${signed}`;
1030
+ const caution = `The listing's instant is its unsigned word, so until the Server's operator confirms the entry, read the listed retirement as unexplained. Off a dump the entry also voids every admission ${key.keyId} signed, so a key it admitted that nothing else reaches is no longer trusted and its window no longer graded.`;
1031
+ if (!givenCutoff.has(entry.spkiSha256)) {
1032
+ return `${lead}: the listing says the Server distrusts the key from that instant (VAULT_DISTRUSTED_KEYS), and this walk was given no distrust entry for it. If the operator confirms it, give distrustedKeys sha256:${entry.spkiSha256}@${from}. ${caution}`;
1033
+ }
1034
+ const given = givenCutoff.get(entry.spkiSha256) ?? null;
1035
+ if (given !== null && sameInstant(given, from))
1036
+ return null;
1037
+ return `${lead}: the distrust entry given for it (${given === null ? 'with no instant' : `from ${given}`}) and the one the listing says the Server applies (VAULT_DISTRUSTED_KEYS, from ${from}) disagree. Confirm the instant with the Server's operator. ${caution}`;
1038
+ };
1039
+ // Findings on listed keys: their columns against the signed values, compared
1040
+ // at millisecond precision, the precision a dump or key document carries.
1041
+ for (const key of listedKeys) {
1042
+ const entry = entryFor(spkiSha256(key.publicKey));
1043
+ const findingsBefore = findings.length;
1044
+ if (!entry.trusted || key.keyId !== entry.keyId)
1045
+ continue;
1046
+ if (entry.activatedAt !== null && typeof key.activatedAt === 'string' && instantMs(key.activatedAt) !== instantMs(entry.activatedAt)) {
1047
+ findings.push({ code: 'CHAIN_KEY_WINDOW_DRIFT', keyId: key.keyId, statementId: null, detail: `activatedAt ${key.activatedAt} differs from the signed ${entry.activatedAt}` });
1048
+ }
1049
+ else if (entry.activatedAt === null && typeof key.activatedAt === 'string' && unverifiedAdmission.has(entry.spkiSha256)) {
1050
+ // The window then has no lower edge here, which is wider than the
1051
+ // listed one: the same drift, read the other way.
1052
+ findings.push({ code: 'CHAIN_KEY_WINDOW_DRIFT', keyId: key.keyId, statementId: null, detail: `activatedAt ${key.activatedAt} is signed by no admission this walk could verify` });
1053
+ }
1054
+ if (entry.distrustCutoff !== null) {
1055
+ // The cutoff is no retirement, so a listed key left active is no drift;
1056
+ // one listed retired earlier than the cutoff is graded more loosely here
1057
+ // than where it was listed (a closure this walk could not verify).
1058
+ if (typeof key.retiredAt === 'string' && !(instantMs(key.retiredAt) >= instantMs(entry.distrustCutoff))) {
1059
+ findings.push({ code: 'CHAIN_KEY_WINDOW_DRIFT', keyId: key.keyId, statementId: null, detail: cutByServer(key, entry) ?? `retiredAt ${key.retiredAt} is earlier than ${entry.distrustCutoff}, the distrust cutoff this walk ends the key at, and no closure it could verify signs it` });
1060
+ }
1061
+ }
1062
+ else if (key.status === 'retired') {
1063
+ if (entry.retiredAt === null) {
1064
+ findings.push({ code: 'KEY_CLOSURE_INVALID', keyId: key.keyId, statementId: null, detail: cutByServer(key, entry) ?? 'the key is listed as retired and no counting closure signs its retirement' });
1065
+ }
1066
+ else if (typeof key.retiredAt !== 'string' || instantMs(key.retiredAt) !== instantMs(entry.retiredAt)) {
1067
+ findings.push({ code: 'CHAIN_KEY_WINDOW_DRIFT', keyId: key.keyId, statementId: null, detail: cutByServer(key, entry) ?? `retiredAt ${key.retiredAt ?? 'null'} differs from the signed ${entry.retiredAt}` });
1068
+ }
1069
+ }
1070
+ else if (key.status === 'active' && entry.retiredAt !== null) {
1071
+ findings.push({ code: 'CHAIN_KEY_WINDOW_DRIFT', keyId: key.keyId, statementId: null, detail: `the key is listed as active but a counting statement signs its retirement at ${entry.retiredAt}` });
1072
+ }
1073
+ // An entry given for the key at another instant than the Server's, which
1074
+ // no finding above names: the walk ends the key earlier than the Server
1075
+ // does (or the listing is cut elsewhere), so it fails what the Server
1076
+ // still counts. Said, never graded.
1077
+ const from = key.distrustedFrom;
1078
+ const given = givenCutoff.get(entry.spkiSha256) ?? null;
1079
+ if (findings.length === findingsBefore && typeof from === 'string' && given !== null && !Number.isNaN(instantMs(from)) && !sameInstant(given, from)) {
1080
+ notes.push({ keyId: key.keyId, statementId: null, detail: `distrustedKeys gives ${key.keyId} the instant ${given}, and the listing says the Server distrusts it from ${from} (distrustedFrom, VAULT_DISTRUSTED_KEYS): the auditor's entry and the one the listing gives disagree, so what the key signed between the two instants is graded differently here than on the Server. Confirm the instant with the Server's operator.` });
1081
+ }
1082
+ }
1083
+ // A distrusted key the dump's registry lists that no key the walk trusts
1084
+ // has retired: nothing bounds what its entry accounts for, so what it
1085
+ // signed stays unaccounted until a retirement does. A registry fact, so a
1086
+ // key document's listing leaves it out.
1087
+ for (const key of listedKeys) {
1088
+ const digest = spkiSha256(key.publicKey);
1089
+ const span = distrustSpans.get(digest);
1090
+ if (key.source !== 'dump' || span === undefined || span.retiredAt !== null || key.keyId !== digest.slice(0, 16))
1091
+ continue;
1092
+ findings.push({
1093
+ code: 'KEY_CLOSURE_INVALID',
1094
+ keyId: key.keyId,
1095
+ statementId: null,
1096
+ detail: `distrustedKeys names ${key.keyId} and no closure signed by a key the walk trusts retires it, so nothing bounds what the entry accounts for: chain entries ${key.keyId} signed fail until a retirement does. Retire it with force on the Server (POST /v1/admin/vault/signing-keys/${key.keyId}/retire with {"force": true}) from a process on a key you hold; what it signed before that retirement is then accounted for and listed, and anything it signs after it is reported.`,
1097
+ });
1098
+ }
1099
+ return {
1100
+ order,
1101
+ anchors: anchorDigests.map((d) => `sha256:${d}`),
1102
+ byDigest,
1103
+ trusted,
1104
+ undecided,
1105
+ findings,
1106
+ notes,
1107
+ accounted,
1108
+ distrustSpans,
1109
+ source: statementInputs.length > 0 && statementInputs.every((st) => st.source === 'dump') ? 'dump' : 'document',
1110
+ statements: {
1111
+ total: checked.length,
1112
+ valid: checked.filter((c) => c.verdict === 'valid').length,
1113
+ invalid: checked.filter((c) => c.verdict === 'invalid').length,
1114
+ unverifiable: checked.filter((c) => c.verdict === 'unverifiable').length,
1115
+ },
1116
+ };
1117
+ }
1118
+ /**
1119
+ * Map a dump statement row onto the walk's input, binding every column. The
1120
+ * Server writes `subject_key_id` and `created_at` on every row, so one that is
1121
+ * missing or not a string maps to `''`, which matches no signed key id and
1122
+ * places the statement nowhere: it is KEY_STATEMENT_INVALID.
1123
+ */
1124
+ export function keyStatementFromDumpRow(row) {
1125
+ return {
1126
+ id: row.id,
1127
+ kind: row.kind,
1128
+ subjectKeyId: typeof row.subject_key_id === 'string' ? row.subject_key_id : '',
1129
+ endorserKeyId: row.endorser_key_id,
1130
+ cose: Array.isArray(row.statement) ? row.statement : [],
1131
+ createdAt: typeof row.created_at === 'string' ? row.created_at : '',
1132
+ source: 'dump',
1133
+ };
1134
+ }
1135
+ /** Map a dump key row onto the walk's input. */
1136
+ export function trustKeyFromDumpRow(row) {
1137
+ return {
1138
+ keyId: row.key_id,
1139
+ publicKey: row.public_key,
1140
+ algorithm: typeof row.algorithm === 'string' ? row.algorithm : null,
1141
+ status: row.status === 'active' || row.status === 'retired' ? row.status : null,
1142
+ activatedAt: row.activated_at ?? null,
1143
+ retiredAt: row.retired_at ?? null,
1144
+ source: 'dump',
1145
+ };
1146
+ }
1147
+ /**
1148
+ * The statements of a document keyed by key id. When any statement of the
1149
+ * document carries `createdAt`, the document publishes write order, so one
1150
+ * without it (or with another type) maps to `''` and is KEY_STATEMENT_INVALID
1151
+ * rather than turning the whole document back to the signed order. A
1152
+ * statement with no `id` is named `<prefix><keyId>#<index>`. Internal: the
1153
+ * export path reads supplied keys' statements with it; not re-exported.
1154
+ */
1155
+ export function statementsFromMap(byKey, source, prefix = '') {
1156
+ const entries = [...byKey];
1157
+ for (const [keyId, list] of entries) {
1158
+ if (list !== undefined && list !== null && !Array.isArray(list))
1159
+ throw new TypeError(`${source}: the statements for key ${keyId} are not an array.`);
1160
+ }
1161
+ const timed = entries.some(([, list]) => Array.isArray(list) && list.some((st) => asRecord(st)?.['createdAt'] !== undefined));
1162
+ const out = [];
1163
+ for (const [keyId, list] of entries) {
1164
+ if (!Array.isArray(list))
1165
+ continue;
1166
+ list.forEach((st, i) => {
1167
+ const r = asRecord(st);
1168
+ if (!r || typeof r['kind'] !== 'string' || !Array.isArray(r['cose'])) {
1169
+ throw new TypeError(`${source}: statement ${i} for key ${keyId} is not { kind, cose: [base64...] }.`);
1170
+ }
1171
+ const id = typeof r['id'] === 'string' ? r['id'] : `${prefix}${keyId}#${i}`;
1172
+ const createdAt = r['createdAt'];
1173
+ out.push({
1174
+ id,
1175
+ kind: r['kind'],
1176
+ subjectKeyId: keyId,
1177
+ source: 'document',
1178
+ cose: r['cose'],
1179
+ ...(timed ? { createdAt: typeof createdAt === 'string' ? createdAt : '' } : {}),
1180
+ });
1181
+ });
1182
+ }
1183
+ return out;
1184
+ }
1185
+ /** The key statements of an audit export's `exportMetadata.signingKeyStatements`. */
1186
+ export function keyStatementsFromExport(signingKeyStatements) {
1187
+ if (signingKeyStatements === undefined || signingKeyStatements === null)
1188
+ return [];
1189
+ if (typeof signingKeyStatements !== 'object' || Array.isArray(signingKeyStatements)) {
1190
+ throw new TypeError('signingKeyStatements must be an object keyed by key id.');
1191
+ }
1192
+ return statementsFromMap(Object.entries(signingKeyStatements), 'signingKeyStatements');
1193
+ }
1194
+ /**
1195
+ * The walk's inputs from a `/v1/verification-keys` document: its keys and
1196
+ * the statements each carries. Throws `TypeError` when the document names a
1197
+ * statement format this verifier does not read.
1198
+ */
1199
+ export function keyStatementsFromVerificationKeys(doc) {
1200
+ if (doc === null || typeof doc !== 'object' || !Array.isArray(doc.data)) {
1201
+ throw new TypeError('Expected the /v1/verification-keys document: { data: [...], keyStatementFormat, anchoredFrom }.');
1202
+ }
1203
+ if (doc.keyStatementFormat !== undefined && doc.keyStatementFormat !== KEY_STATEMENT_CTY) {
1204
+ throw new TypeError(`keyStatementFormat ${JSON.stringify(doc.keyStatementFormat)} is not ${KEY_STATEMENT_CTY}; upgrade the verifier.`);
1205
+ }
1206
+ const keys = doc.data.map((k) => ({
1207
+ keyId: k.keyId,
1208
+ publicKey: k.publicKey,
1209
+ algorithm: k.algorithm ?? null,
1210
+ status: k.status === 'active' || k.status === 'retired' ? k.status : null,
1211
+ activatedAt: k.activatedAt ?? null,
1212
+ retiredAt: k.retiredAt ?? null,
1213
+ ...(typeof k.distrustedFrom === 'string' ? { distrustedFrom: k.distrustedFrom } : {}),
1214
+ }));
1215
+ const statements = statementsFromMap(doc.data.map((k) => [k.keyId, k.statements]), 'verification-keys');
1216
+ return { keys, statements };
1217
+ }
1218
+ /**
1219
+ * Mark every key of a registry with the walk's verdict, and give each anchored
1220
+ * key the window its statements sign in place of whatever window it carried,
1221
+ * as the engine grades entries. An anchored key no statement dates carries no
1222
+ * edge on that side. A key is anchored only when its key id is the
1223
+ * fingerprint of its own SPKI: a row filed under another key's id names that
1224
+ * key's entries, and is anchored to nothing. On a walk over a dump, a key a
1225
+ * `distrustedKeys` entry names also carries its {@link DistrustSpan}
1226
+ * (`distrustSpan`), which lets `verifyChain` account for what it signed.
1227
+ */
1228
+ export function applyKeyTrust(registry, trust) {
1229
+ const out = new Map();
1230
+ for (const [keyId, key] of registry) {
1231
+ const digest = typeof key.spkiBase64 === 'string' ? spkiSha256(key.spkiBase64) : '';
1232
+ const bound = keyId === digest.slice(0, 16) && key.keyId === keyId;
1233
+ const anchored = bound && trust.trusted.has(digest);
1234
+ const state = anchored ? 'anchored' : bound && trust.undecided.has(digest) ? 'undecided' : 'unanchored';
1235
+ const { activatedAt: _a, retiredAt: _r, ...rest } = key;
1236
+ const next = { ...rest, trust: state };
1237
+ const signed = trust.byDigest.get(digest);
1238
+ const span = bound && trust.source === 'dump' ? trust.distrustSpans.get(digest) : undefined;
1239
+ if (span !== undefined)
1240
+ next.distrustSpan = { cutoff: span.cutoff, retiredAt: span.retiredAt };
1241
+ if (anchored && signed) {
1242
+ if (signed.activatedAt !== null)
1243
+ next.activatedAt = signed.activatedAt;
1244
+ if (signed.retiredAt !== null)
1245
+ next.retiredAt = signed.retiredAt;
1246
+ if (signed.distrustCutoff !== null)
1247
+ next.distrustCutoff = signed.distrustCutoff;
1248
+ }
1249
+ else {
1250
+ if (_a !== undefined)
1251
+ next.activatedAt = _a;
1252
+ if (_r !== undefined)
1253
+ next.retiredAt = _r;
1254
+ }
1255
+ out.set(keyId, next);
1256
+ }
1257
+ return out;
1258
+ }
1259
+ /** The {@link Verdict} of a result that carries `valid` and a `keyTrust` report. */
1260
+ export function verdictOf(result) {
1261
+ if (!result.valid)
1262
+ return 'failed';
1263
+ return result.keyTrust.status === 'walked' ? 'trusted' : 'unanchored';
1264
+ }
1265
+ /**
1266
+ * Summarize a registry after `applyKeyTrust` (or with `trust` null when no
1267
+ * walk ran). A walked report says `walked` until the caller settles it with
1268
+ * {@link settleKeyTrust}, once it knows whether any signature verified under
1269
+ * an anchored key. `anchoredFrom` that is not a string is read as absent.
1270
+ */
1271
+ export function reportKeyTrust(registry, trust, anchoredFrom) {
1272
+ const ids = (state) => [...registry.values()].filter((k) => k.trust === state).map((k) => k.keyId).sort();
1273
+ if (typeof anchoredFrom !== 'string')
1274
+ anchoredFrom = null;
1275
+ if (trust === null) {
1276
+ return {
1277
+ status: 'no_anchor',
1278
+ detail: 'No trustAnchors were given, so no key was anchored and this is not a trusted verdict: every key was taken on the word of whoever embedded or supplied it, and a key written into the Server\'s database alone would verify. Pin the SPKI digest of a vault key you hold or took out of band (sha256:<hex>) as trustAnchors.',
1279
+ anchors: [],
1280
+ anchoredFrom,
1281
+ anchoredFromPinned: null,
1282
+ order: null,
1283
+ anchoredKeyIds: [],
1284
+ unanchoredKeyIds: [],
1285
+ undecidedKeyIds: [],
1286
+ findings: [],
1287
+ notes: [],
1288
+ accounted: [],
1289
+ };
1290
+ }
1291
+ const unanchored = ids('unanchored');
1292
+ return {
1293
+ status: 'walked',
1294
+ detail: unanchored.length === 0
1295
+ ? `Every key is linked by signed key statements to ${trust.anchors.join(', ')}.`
1296
+ : `Keys ${unanchored.join(', ')} are not linked by any signed key statement to ${trust.anchors.join(', ')}; entries they signed fail CHAIN_SIGNING_KEY_UNANCHORED.`,
1297
+ anchors: trust.anchors,
1298
+ anchoredFrom,
1299
+ anchoredFromPinned: anchoredFrom === null ? null : trust.anchors.includes(anchoredFrom.toLowerCase()),
1300
+ order: trust.order,
1301
+ anchoredKeyIds: ids('anchored'),
1302
+ unanchoredKeyIds: unanchored,
1303
+ undecidedKeyIds: ids('undecided'),
1304
+ findings: trust.findings,
1305
+ notes: trust.notes,
1306
+ accounted: trust.accounted,
1307
+ };
1308
+ }
1309
+ /**
1310
+ * Settle a walked report once the caller has counted the signatures that
1311
+ * verified under an anchored key (an export's or a dump's entries whose
1312
+ * signature checked out, since under a walk every such key is anchored).
1313
+ * With none, the report becomes `no_anchored_signature`: the pin was walked,
1314
+ * but nothing in the artifact is signed by a key it anchors, so a pass is not
1315
+ * a trusted verdict. Any other report is returned as it is.
1316
+ */
1317
+ export function settleKeyTrust(report, anchoredSignatures) {
1318
+ if (report.status !== 'walked' || anchoredSignatures > 0)
1319
+ return report;
1320
+ return {
1321
+ ...report,
1322
+ status: 'no_anchored_signature',
1323
+ detail: `The key statements were walked from ${report.anchors.join(', ')}, but no signature here verified under a key they anchor, so this is not a trusted verdict: an entry written before the install began signing carries no signature, and proves nothing about who wrote it.`,
1324
+ };
1325
+ }