@agledger/verify-core 1.5.0 → 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.
@@ -19,10 +19,36 @@
19
19
  * Older exports without these fields stay `skipped_no_input`, surfaced in the
20
20
  * result so a caller never mistakes "not checked here" for "checked and passed".
21
21
  */
22
- import { buildAgentKeyRegistry, buildKeyRegistry, verifyChain, } from './chain.js';
22
+ import { buildAgentKeyRegistry, buildKeyRegistry, earliestKeyActivation, verifyChain, } from './chain.js';
23
+ import { instantMs } from './instant.js';
24
+ import { assertKnownOptions } from './options.js';
25
+ import { applyKeyTrust, assertNotPinnedAndDistrusted, computeKeyTrust, keyStatementsFromExport, statementsFromMap, reportKeyTrust, settleKeyTrust, verdictOf, } from './key-statements.js';
23
26
  const SUPPORTED_FORMAT_VERSION = '2.0';
24
27
  const SUPPORTED_CANONICALIZATION = 'RFC8949-CDE';
25
- export function verifyAuditExport(exportData, options = {}) {
28
+ function isRecord(value) {
29
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
30
+ }
31
+ /**
32
+ * Verify one record's `/audit-export` document offline.
33
+ *
34
+ * Throws `TypeError` when the document is not an export at all (no
35
+ * `exportMetadata` object, or `entries` that is not an array), on a malformed
36
+ * option, and on `distrustedKeys` without `trustAnchors`. A malformed entry
37
+ * inside a well-formed document is a failure code on that entry, never a throw.
38
+ */
39
+ export function verifyAuditExport(exportData, given = {}) {
40
+ assertKnownOptions('verifyAuditExport', given, EXPORT_OPTIONS);
41
+ // The `/v1/verification-keys` body as served, `{ data: [...] }`, is its array.
42
+ const options = isKeysEnvelope(given.publicKeys) ? { ...given, publicKeys: given.publicKeys.data } : given;
43
+ if (!isRecord(exportData) || !isRecord(exportData.exportMetadata)
44
+ || (exportData.entries !== undefined && exportData.entries !== null && !Array.isArray(exportData.entries))) {
45
+ throw new TypeError('Expected an /audit-export document: { exportMetadata: { recordId, ... }, entries: [...] }.');
46
+ }
47
+ if ((options.trustAnchors === undefined || options.trustAnchors.length === 0)
48
+ && options.distrustedKeys !== undefined && options.distrustedKeys.length > 0) {
49
+ throw new TypeError('distrustedKeys act only inside the key-statement walk, which runs from trustAnchors; pass trustAnchors as well.');
50
+ }
51
+ assertNotPinnedAndDistrusted(options.trustAnchors, options.distrustedKeys);
26
52
  const meta = exportData.exportMetadata;
27
53
  const entries = exportData.entries ?? [];
28
54
  if (meta.exportFormatVersion && meta.exportFormatVersion !== SUPPORTED_FORMAT_VERSION) {
@@ -31,16 +57,51 @@ export function verifyAuditExport(exportData, options = {}) {
31
57
  if (meta.canonicalization && meta.canonicalization !== SUPPORTED_CANONICALIZATION) {
32
58
  return earlyFailure(meta.recordId, entries.length, `Unsupported canonicalization ${meta.canonicalization} (only ${SUPPORTED_CANONICALIZATION} supported).`);
33
59
  }
34
- const keys = buildKeyRegistry(resolveKeys(exportData, options));
60
+ const resolvedKeys = resolveKeys(exportData, options);
61
+ let keys = buildKeyRegistry(resolvedKeys);
35
62
  const agentKeys = options.agentKeys !== undefined ? buildAgentKeyRegistry(options.agentKeys) : undefined;
36
- const normalized = entries.map((e) => {
63
+ // An empty trustAnchors is the same as none: no walk, keyTrust 'no_anchor'.
64
+ const trust = options.trustAnchors !== undefined && options.trustAnchors.length > 0
65
+ ? computeKeyTrust({
66
+ keys: trustKeysOf(exportData, options),
67
+ statements: trustStatementsOf(exportData, options),
68
+ trustAnchors: options.trustAnchors,
69
+ ...(options.distrustedKeys !== undefined ? { distrustedKeys: options.distrustedKeys } : {}),
70
+ })
71
+ : null;
72
+ if (trust !== null)
73
+ keys = applyKeyTrust(keys, trust);
74
+ // When the install began signing, for CHAIN_ENTRY_UNSIGNED. The engine reads
75
+ // it as min(activated_at) over its whole key registry, retired keys included,
76
+ // and `signingKeyWindows` publishes that whole registry. So the instant is
77
+ // taken over every key the verifier holds (with each key's window resolved
78
+ // under the trust hierarchy in resolveKeys) plus every window the export
79
+ // lists for a key it carries no public key for. Those windows are unsigned,
80
+ // and deleting them would move the instant later or clear it, so when the
81
+ // walk ran, every activation an anchored key's statements sign is taken as
82
+ // well: the earliest of all of them stands, and neither source can make the
83
+ // rule looser than the other. With no time anywhere (an older export, or
84
+ // caller keys without activatedAt, no export windows and no walk), it is null
85
+ // and only the signed-before half of the rule applies.
86
+ const windowOnly = Object.entries(meta.signingKeyWindows ?? {})
87
+ .filter(([keyId, window]) => !keys.has(keyId) && window !== null && typeof window === 'object')
88
+ .map(([, window]) => window);
89
+ const signedActivations = trust === null ? [] : [...trust.byDigest.values()].filter((k) => k.trusted);
90
+ const signingSince = earliestKeyActivation([...resolvedKeys, ...windowOnly, ...signedActivations]);
91
+ const walkReport = reportKeyTrust(keys, trust, meta.anchoredFrom ?? null);
92
+ const normalized = entries.map((raw) => {
93
+ // An entry or integrity block that is not an object carries none of the
94
+ // fields the walk reads, and fails CHAIN_MALFORMED_ENTRY there.
95
+ const e = isRecord(raw) ? raw : {};
96
+ const integrity = isRecord(e.integrity) ? e.integrity : {};
37
97
  const base = {
38
98
  scopeId: meta.recordId,
39
99
  chainPosition: e.chainPosition ?? e.position ?? -1,
40
- payloadHash: e.integrity.payloadHash,
41
- previousHash: e.integrity.previousHash,
42
- coseSign1: e.integrity.coseSign1,
43
- signingKeyId: e.integrity.signingKeyId,
100
+ payloadHash: integrity.payloadHash,
101
+ previousHash: integrity.previousHash,
102
+ coseSign1: integrity.coseSign1,
103
+ signingKeyId: integrity.signingKeyId,
104
+ createdAt: e.createdAt,
44
105
  };
45
106
  // Binding-integrity: when the export carries the denormalized row `payload`
46
107
  // (engine ≥ v0.26.x), cross-check it against the predicate decoded from the
@@ -70,8 +131,6 @@ export function verifyAuditExport(exportData, options = {}) {
70
131
  actorOwnerId: e.actorOwnerId ?? null,
71
132
  };
72
133
  }
73
- if (e.createdAt)
74
- base.createdAt = e.createdAt;
75
134
  // The synthesized flag is the marker that the export carries the OIDC
76
135
  // wire shape at all. Older exports omit it entirely; new exports always
77
136
  // include it (false/null/true). Setting `oidcActor` flips `oidc_actor`
@@ -87,16 +146,30 @@ export function verifyAuditExport(exportData, options = {}) {
87
146
  });
88
147
  const chain = verifyChain(normalized, keys, {
89
148
  requireKeyId: options.requireKeyId,
90
- requireOutOfBandKeys: options.requireOutOfBandKeys,
149
+ requireSuppliedKeys: options.requireSuppliedKeys,
91
150
  agentKeys,
151
+ signingSince,
92
152
  });
153
+ // Under a walk every key a signature verifies against is anchored, so the
154
+ // signed entries are the anchored signatures.
155
+ const keyTrust = settleKeyTrust(walkReport, chain.signatureCoverage.signed);
156
+ if (trust !== null && chain.optionalChecks.key_anchoring === 'skipped_no_input') {
157
+ chain.optionalChecks.key_anchoring = 'not_checked';
158
+ }
159
+ // A finding on the key statements has no chain position; it is reported
160
+ // at position 0, the place for findings that precede the walk.
161
+ const registryFinding = keyTrust.findings[0];
162
+ const brokenAt = chain.brokenAt
163
+ ? { position: chain.brokenAt.position, code: chain.brokenAt.code, detail: chain.brokenAt.detail }
164
+ : registryFinding
165
+ ? { position: 0, code: registryFinding.code, detail: registryFinding.detail }
166
+ : undefined;
167
+ const valid = chain.valid && keyTrust.findings.length === 0;
93
168
  return {
94
- valid: chain.valid,
169
+ valid,
95
170
  totalEntries: chain.totalEntries,
96
171
  verifiedEntries: chain.verifiedEntries,
97
- brokenAt: chain.brokenAt
98
- ? { position: chain.brokenAt.position, code: chain.brokenAt.code, detail: chain.brokenAt.detail }
99
- : undefined,
172
+ brokenAt,
100
173
  entries: chain.entries.map((r) => ({
101
174
  position: r.position,
102
175
  valid: r.valid,
@@ -110,8 +183,71 @@ export function verifyAuditExport(exportData, options = {}) {
110
183
  keyProvenance: chain.keyProvenance,
111
184
  unsignedProjectionFields: exportData.verificationGuide?.unsignedFields ?? [],
112
185
  agentSignatures: chain.agentSignatures,
186
+ keyTrust,
187
+ verdict: verdictOf({ valid, keyTrust }),
113
188
  };
114
189
  }
190
+ const EXPORT_OPTIONS = ['publicKeys', 'requireKeyId', 'requireSuppliedKeys', 'trustAnchors', 'distrustedKeys', 'agentKeys'];
191
+ function isKeysEnvelope(value) {
192
+ return isRecord(value) && Array.isArray(value.data);
193
+ }
194
+ /**
195
+ * The keys the walk reads: the export's own, with the windows it lists as the
196
+ * columns the drift check holds against the signed values, and the supplied
197
+ * keys as key material only (the caller's catalogue is not the artifact).
198
+ */
199
+ function trustKeysOf(exportData, options) {
200
+ const meta = exportData.exportMetadata;
201
+ const out = [];
202
+ for (const [keyId, publicKey] of Object.entries(meta.signingPublicKeys ?? {})) {
203
+ const window = meta.signingKeyWindows?.[keyId];
204
+ out.push(window && typeof window === 'object'
205
+ ? {
206
+ keyId,
207
+ publicKey,
208
+ activatedAt: window.activatedAt,
209
+ retiredAt: window.retiredAt,
210
+ status: window.retiredAt === null ? 'active' : 'retired',
211
+ ...(typeof window.distrustedFrom === 'string' ? { distrustedFrom: window.distrustedFrom } : {}),
212
+ }
213
+ : { keyId, publicKey });
214
+ }
215
+ for (const k of normalizeSuppliedKeys(options.publicKeys) ?? []) {
216
+ out.push({ keyId: k.keyId, publicKey: k.spkiBase64 });
217
+ }
218
+ return out;
219
+ }
220
+ /**
221
+ * The export's key statements, plus any a supplied key carries (a
222
+ * /v1/verification-keys `data[]`). A statement both carry is one row, which
223
+ * the walk reads once by its id and write time. When one source publishes
224
+ * write order and the other does not (an export and a key document from
225
+ * Servers on either side of that change), a statement without a write time
226
+ * that the other source carries with one is dropped as the same row; if any
227
+ * other remains, the walk falls back to the signed order for all of them,
228
+ * which `keyTrust.order` reports.
229
+ */
230
+ function trustStatementsOf(exportData, options) {
231
+ const own = keyStatementsFromExport(exportData.exportMetadata.signingKeyStatements);
232
+ if (!Array.isArray(options.publicKeys))
233
+ return own;
234
+ const byKey = {};
235
+ for (const k of options.publicKeys) {
236
+ if (k !== null && typeof k === 'object' && Array.isArray(k.statements))
237
+ byKey[k.keyId] = [...(byKey[k.keyId] ?? []), ...k.statements];
238
+ }
239
+ const supplied = statementsFromMap(Object.entries(byKey), 'signingKeyStatements', 'supplied:');
240
+ const all = [...own, ...supplied];
241
+ const timed = all.filter((s) => s.createdAt !== undefined);
242
+ if (timed.length === 0 || timed.length === all.length)
243
+ return all;
244
+ const bytesOf = (s) => s.cose.map((c) => (typeof c === 'string' ? c : Buffer.from(c).toString('base64'))).join('|');
245
+ const timedBytes = new Set(timed.map(bytesOf));
246
+ const rest = all.filter((s) => s.createdAt !== undefined || !timedBytes.has(bytesOf(s)));
247
+ if (rest.every((s) => s.createdAt !== undefined))
248
+ return rest;
249
+ return all.map(({ createdAt: _c, ...s }) => s);
250
+ }
115
251
  function earlyFailure(recordId, totalEntries, detail) {
116
252
  return {
117
253
  valid: false,
@@ -127,10 +263,13 @@ function earlyFailure(recordId, totalEntries, detail) {
127
263
  actor_attribution: 'skipped_no_input',
128
264
  key_temporal: 'skipped_no_input',
129
265
  agent_signature: 'skipped_no_input',
266
+ key_anchoring: 'skipped_no_input',
130
267
  },
131
- keyProvenance: { outOfBand: 0, embedded: 0 },
268
+ keyProvenance: { supplied: 0, embedded: 0 },
132
269
  unsignedProjectionFields: [],
133
270
  agentSignatures: { present: 0, verified: 0 },
271
+ keyTrust: reportKeyTrust(new Map(), null, null),
272
+ verdict: 'failed',
134
273
  };
135
274
  }
136
275
  function resolveKeys(exportData, options) {
@@ -141,19 +280,19 @@ function resolveKeys(exportData, options) {
141
280
  byId.set(keyId, { keyId, spkiBase64, source: 'embedded' });
142
281
  }
143
282
  }
144
- // Out-of-band keys override embedded keys of the same id, but inherit the
145
- // previously-seen activation/retirement window if the OOB entry didn't carry
146
- // its own.
147
- const oob = normalizeOutOfBandKeys(options.publicKeys);
148
- if (oob) {
149
- for (const entry of oob) {
283
+ // Supplied keys override embedded keys of the same id, but inherit the
284
+ // previously-seen activation/retirement window if the supplied entry didn't
285
+ // carry its own.
286
+ const supplied = normalizeSuppliedKeys(options.publicKeys);
287
+ if (supplied) {
288
+ for (const entry of supplied) {
150
289
  const existing = byId.get(entry.keyId);
151
290
  const activatedAt = entry.activatedAt ?? existing?.activatedAt;
152
291
  const retiredAt = entry.retiredAt !== undefined ? entry.retiredAt : existing?.retiredAt;
153
292
  byId.set(entry.keyId, {
154
293
  keyId: entry.keyId,
155
294
  spkiBase64: entry.spkiBase64,
156
- source: 'out-of-band',
295
+ source: 'supplied',
157
296
  ...(activatedAt !== undefined ? { activatedAt } : {}),
158
297
  ...(retiredAt !== undefined ? { retiredAt } : {}),
159
298
  });
@@ -166,19 +305,18 @@ function resolveKeys(exportData, options) {
166
305
  if (windows) {
167
306
  for (const [keyId, window] of Object.entries(windows)) {
168
307
  const existing = byId.get(keyId);
169
- if (!existing)
308
+ if (!existing || !isRecord(window))
170
309
  continue;
171
310
  // Trust hierarchy on the temporal axis: when the caller supplied this
172
- // key out-of-band AND brought their own activation/retirement window,
173
- // the export's (untrusted) signingKeyWindows MUST NOT overwrite it.
174
- // A compromised export could otherwise hide a retirement by setting
175
- // retiredAt:null, reopening the fallback on the temporal axis. When the OOB
176
- // caller did not carry a window, we still fall through to the export's
177
- // window, since most auditors trust the engine's published key-rotation log
178
- // even when they bring their own key catalogue.
179
- const oobCarriesWindow = existing.source === 'out-of-band' &&
311
+ // key AND brought their own activation/retirement window, the export's
312
+ // (untrusted) signingKeyWindows MUST NOT overwrite it. A compromised
313
+ // export could otherwise hide a retirement by setting retiredAt:null.
314
+ // When the caller did not carry a window, we fall through to the
315
+ // export's. With trustAnchors, an anchored key's window is the one its
316
+ // statements sign, whichever of these it carried.
317
+ const suppliedCarriesWindow = existing.source === 'supplied' &&
180
318
  (existing.activatedAt !== undefined || existing.retiredAt !== undefined);
181
- if (oobCarriesWindow)
319
+ if (suppliedCarriesWindow)
182
320
  continue;
183
321
  byId.set(keyId, {
184
322
  ...existing,
@@ -192,19 +330,19 @@ function resolveKeys(exportData, options) {
192
330
  /**
193
331
  * Normalize `options.publicKeys` into a uniform array of entries, or throw
194
332
  * `TypeError` at the boundary if the shape is wrong. Fail-closed by design:
195
- * an OOB-key argument that silently falls back to embedded keys would lie
196
- * about the audit-independence claim.
333
+ * a key argument that silently falls back to embedded keys would lie about
334
+ * which keys the verdict rests on.
197
335
  *
198
336
  * Accepts:
199
337
  * - `Record<keyId, base64SpkiDer>`: compact map (string-keyed object whose
200
338
  * values are all strings)
201
- * - `OutOfBandKeyEntry[]`: natural SDK shape from `verificationKeys.list()`,
339
+ * - `SuppliedKeyEntry[]`: natural SDK shape from `verificationKeys.list()`,
202
340
  * or COSE_KeySet shape from `/.well-known/scitt-keys`
203
341
  *
204
342
  * Returns `null` when no keys were supplied; otherwise an array of normalized
205
343
  * entries ready to merge into the registry.
206
344
  */
207
- function normalizeOutOfBandKeys(publicKeys) {
345
+ function normalizeSuppliedKeys(publicKeys) {
208
346
  if (publicKeys === undefined || publicKeys === null)
209
347
  return null;
210
348
  if (Array.isArray(publicKeys)) {
@@ -223,6 +361,14 @@ function normalizeOutOfBandKeys(publicKeys) {
223
361
  const out = { keyId, spkiBase64: publicKey };
224
362
  const activatedAt = entry.activatedAt;
225
363
  const retiredAt = entry.retiredAt;
364
+ // A window the caller supplies is held to RFC 3339, as distrustedKeys
365
+ // is: one that is not would be read by the host's clock or not at all.
366
+ for (const [edge, value] of [['activatedAt', activatedAt], ['retiredAt', retiredAt]]) {
367
+ if (value !== undefined && value !== null && (typeof value !== 'string' || Number.isNaN(instantMs(value)))) {
368
+ throw new TypeError(`verifyAuditExport: publicKeys[${i}] (key ${keyId}) has ${edge} ${JSON.stringify(value)}, which is not an RFC 3339 instant ` +
369
+ '(2026-09-01T00:00:00.000Z: a T, an offset or Z, a real calendar date).');
370
+ }
371
+ }
226
372
  if (typeof activatedAt === 'string')
227
373
  out.activatedAt = activatedAt;
228
374
  if (retiredAt === null || typeof retiredAt === 'string')
package/dist/chain.d.ts CHANGED
@@ -17,7 +17,8 @@
17
17
  * protected-header chain-claim cross-check, and the Ed25519 signature.
18
18
  * - INPUT-GATED (only when the normalized entry, or the caller, supplies the
19
19
  * inputs): binding-integrity, OIDC-actor cross-check, temporal
20
- * key-validity, and the agent-signature re-check. The first three run on
20
+ * key-validity, the agent-signature re-check, and key anchoring (a
21
+ * registry marked by `applyKeyTrust`). The first three run on
21
22
  * the dump and on any export from an engine that ships the row fields
22
23
  * (>= v0.26.x). The agent-signature check needs the cert's public key,
23
24
  * which neither surface carries, so it runs only when the caller passes
@@ -25,24 +26,44 @@
25
26
  * NEVER folded into a green verdict.
26
27
  *
27
28
  * Failure ordering is fixed so `brokenAt` is deterministic. The null-key
28
- * signature skip happens LAST, after the binding/OIDC checks, so a row written
29
- * without a signing key is still subject to every structural check.
29
+ * branch comes LAST, after the binding/OIDC checks, so a row written without a
30
+ * signing key is still subject to every structural check, and a tamper finding
31
+ * on it is reported under its own code rather than as CHAIN_ENTRY_UNSIGNED.
32
+ * That branch grades the entry the way the engine does: an unsigned entry
33
+ * after a signed one in its chain, or written at or after the earliest key
34
+ * activation (`signingSince`), is CHAIN_ENTRY_UNSIGNED; an earlier one is a
35
+ * `skipped` signature, reduced coverage rather than a break.
30
36
  */
31
37
  import { type AgentPublicKeyJwk } from './primitives.js';
32
38
  import type { FailureCode } from './failures.js';
33
- /** Where a verification key came from: the trust-anchor provenance. */
34
- export type KeySource = 'out-of-band' | 'embedded';
39
+ /**
40
+ * Where a verification key came from. `supplied`: the caller passed it (from
41
+ * `GET /v1/verification-keys`, `/.well-known/scitt-keys`, its own records).
42
+ * `embedded`: the artifact under verification shipped it. Neither says the key
43
+ * is trusted: a key the Server serves comes from its database, which is what
44
+ * a key-registry attacker writes to. Trust comes from walking the signed key
45
+ * statements from a pinned anchor (`trustAnchors`, see `computeKeyTrust`),
46
+ * reported per key as `trust`.
47
+ */
48
+ export type KeySource = 'supplied' | 'embedded';
49
+ /**
50
+ * What the key-statement walk concluded about a key (see `applyKeyTrust`).
51
+ * `anchored`: signed statements link it to a pinned anchor. `unanchored`:
52
+ * nothing signed does, so entries under it fail CHAIN_SIGNING_KEY_UNANCHORED.
53
+ * `undecided`: the only link runs through a signature this host cannot
54
+ * compute, so entries under it are CHAIN_UNSUPPORTED_ALGORITHM, not tamper.
55
+ */
56
+ export type KeyTrustState = 'anchored' | 'unanchored' | 'undecided';
35
57
  /** A public key the walk can verify signatures against. */
36
58
  export interface VerificationKey {
37
59
  keyId: string;
38
60
  /** SPKI DER, base64-encoded (the engine's vault_signing_keys.public_key shape). */
39
61
  spkiBase64: string;
40
62
  /**
41
- * `out-of-band` = supplied by the caller from a trusted source (e.g.
42
- * /v1/verification-keys, /.well-known/scitt-keys). `embedded` = shipped inside
43
- * the artifact being verified (the export/dump the engine produced). Surfaced
44
- * in the result so a caller can tell whether it verified the engine against an
45
- * independent key or against the engine's own answer key.
63
+ * `supplied` = passed by the caller. `embedded` = shipped inside the
64
+ * artifact being verified (the export or dump the engine produced). Surfaced
65
+ * in the result so a caller can tell whether it verified against a key it
66
+ * brought or against the artifact's own answer key.
46
67
  */
47
68
  source: KeySource;
48
69
  /**
@@ -54,11 +75,43 @@ export interface VerificationKey {
54
75
  * code path; only the key material does.
55
76
  */
56
77
  algorithm?: string;
57
- /** Optional temporal-validity window (present on the dump path only). */
78
+ /** Optional temporal-validity window. */
58
79
  activatedAt?: string;
59
80
  retiredAt?: string | null;
81
+ /**
82
+ * The instant from which `distrustedKeys` (`VAULT_DISTRUSTED_KEYS` on the
83
+ * Server) voids what this key signs, set by `applyKeyTrust` when it ends the
84
+ * window before `retiredAt`. Entries written after it fail CHAIN_KEY_EXPIRED
85
+ * worded as past the distrust cutoff: the key was not retired there.
86
+ */
87
+ distrustCutoff?: string;
88
+ /**
89
+ * Set by `applyKeyTrust` on a walk over a dump, for a key `distrustedKeys`
90
+ * names: the instant from which what it signs counts for nothing, and the
91
+ * earliest retirement a key the walk trusts signed for it (see the
92
+ * `DistrustSpan` of `computeKeyTrust`). An entry it signed outside its
93
+ * trust (the key unanchored, or the entry written at or after the cutoff),
94
+ * written before that retirement and whose signature verifies under it, is
95
+ * accounted for: listed as CHAIN_SIGNED_BY_DISTRUSTED_KEY, never a failure.
96
+ */
97
+ distrustSpan?: {
98
+ cutoff: string | null;
99
+ retiredAt: string | null;
100
+ };
101
+ /**
102
+ * The key-statement walk's verdict on this key, set by `applyKeyTrust`.
103
+ * Absent when no walk ran (no `trustAnchors`), and the result then reports
104
+ * `optionalChecks.key_anchoring: skipped_no_input`; with a walk and no
105
+ * entry reaching the check, `not_checked`.
106
+ */
107
+ trust?: KeyTrustState;
60
108
  }
61
109
  export type KeyRegistry = ReadonlyMap<string, VerificationKey>;
110
+ /**
111
+ * Index keys by key id. A key whose `spkiBase64` is not a non-empty string
112
+ * carries no key material (a registry row with its public key nulled), so it
113
+ * is left out: an entry naming it fails CHAIN_SIGNATURE_MISSING_KEY.
114
+ */
62
115
  export declare function buildKeyRegistry(keys: readonly VerificationKey[]): KeyRegistry;
63
116
  /**
64
117
  * Agent cert keys for the agent-signature check, indexed by the RFC 7638
@@ -84,8 +137,14 @@ export interface NormalizedEntry {
84
137
  /** Base64-encoded canonical COSE_Sign1 envelope. */
85
138
  coseSign1: string;
86
139
  signingKeyId: string | null;
87
- /** ISO-8601 write time, for temporal key-validity (dump path). */
88
- createdAt?: string;
140
+ /**
141
+ * ISO-8601 write time, for temporal key-validity and the unsigned-entry
142
+ * rule. The engine writes one on every entry, so wherever the walk needs it
143
+ * (the entry's key carries a window, or the entry is unsigned and the key
144
+ * set dates the start of signing) a missing or unparseable value fails
145
+ * CHAIN_MALFORMED_ENTRY rather than skipping the check.
146
+ */
147
+ createdAt?: string | null;
89
148
  /** Inputs for the binding-integrity check (dump path). */
90
149
  binding?: {
91
150
  recordId: string | null;
@@ -116,15 +175,26 @@ export interface NormalizedEntry {
116
175
  * had its cert key supplied by the caller (`agentKeys`); neither the export
117
176
  * nor the dump carries cert public keys.
118
177
  */
119
- export type OptionalCheck = 'payload_binding' | 'oidc_actor' | 'actor_attribution' | 'key_temporal' | 'agent_signature';
120
- export type CheckApplicability = 'applied' | 'skipped_no_input';
178
+ export type OptionalCheck = 'payload_binding' | 'oidc_actor' | 'actor_attribution' | 'key_temporal' | 'agent_signature' | 'key_anchoring';
179
+ /**
180
+ * `applied`: the check ran. `skipped_no_input`: the input it needs is absent.
181
+ * `not_checked`: the input was given but no entry reached the check, because
182
+ * the chain broke before it or no entry was signed. Only `key_anchoring` has
183
+ * a caller-level input and so can be `not_checked`.
184
+ */
185
+ export type CheckApplicability = 'applied' | 'skipped_no_input' | 'not_checked';
121
186
  export interface SignatureOutcome {
122
187
  /**
123
188
  * - `ok` / `invalid` / `decode-fail`: the signature was checked (and passed,
124
189
  * failed, or the envelope would not decode).
125
- * - `unsigned`: the entry carries no signature by design.
190
+ * - `unsigned`: retained for type compatibility; `verifyChain` no longer
191
+ * produces it. An all-zero signature on an entry that names a key is
192
+ * `invalid` (CHAIN_SIGNATURE_INVALID), as the engine grades it.
126
193
  * - `skipped`: the chain is intact but this entry has no signing key, so the
127
- * signature check was deliberately not run (engine booted without a key).
194
+ * signature check was deliberately not run. Only an entry written before
195
+ * the install began signing gets here: before any signed entry in its
196
+ * chain and before the earliest key activation. Any other unsigned entry
197
+ * fails CHAIN_ENTRY_UNSIGNED.
128
198
  * - `not-checked`: a structural/chain check failed at or before this entry,
129
199
  * so verification short-circuited before reaching the signature. Reads as a
130
200
  * consequence of an upstream break, never as a benign skip.
@@ -134,8 +204,12 @@ export interface SignatureOutcome {
134
204
  * CHAIN_UNSUPPORTED_ALGORITHM. A failure state, never a benign skip, and
135
205
  * never tamper evidence: distinguishing it from `invalid` is the whole
136
206
  * point, since only `invalid` means a signature was checked and failed.
207
+ * - `accounted`: the signature verifies under a key `distrustedKeys` names,
208
+ * outside what the key is trusted for, and the entry was written before a
209
+ * key the walk trusts retired it (dumps only). Not a failure and not a
210
+ * verified entry: see {@link AccountedEntry}.
137
211
  */
138
- state: 'ok' | 'invalid' | 'unsigned' | 'skipped' | 'not-checked' | 'decode-fail' | 'unsupported';
212
+ state: 'ok' | 'invalid' | 'unsigned' | 'skipped' | 'not-checked' | 'decode-fail' | 'unsupported' | 'accounted';
139
213
  /** Provenance of the key the signature was checked against ('ok' / 'invalid'). */
140
214
  keySource?: KeySource;
141
215
  }
@@ -147,9 +221,46 @@ export interface ChainEntryResult {
147
221
  code: FailureCode;
148
222
  detail: string;
149
223
  };
224
+ /** Set, with `valid: true` and signature `accounted`, on an entry the distrust entry accounts for. */
225
+ accounted?: {
226
+ code: AccountedEntryCode;
227
+ detail: string;
228
+ };
150
229
  signature: SignatureOutcome['state'];
151
230
  keySource?: KeySource;
152
231
  }
232
+ /** The code an {@link AccountedEntry} carries. Not a {@link FailureCode}: it never fails a verdict. */
233
+ export declare const ACCOUNTED_ENTRY_CODE = "CHAIN_SIGNED_BY_DISTRUSTED_KEY";
234
+ export type AccountedEntryCode = typeof ACCOUNTED_ENTRY_CODE;
235
+ /**
236
+ * A chain entry of a dump whose signature verifies under a key
237
+ * `distrustedKeys` names, that falls outside what the key is trusted for
238
+ * (the key is unanchored, or the entry was written at or after its cutoff),
239
+ * and that was written before a key the walk trusts retired it. The distrust
240
+ * entry and that retirement account for it, as the engine's scan lists it in
241
+ * `distrustedEntries`: it is listed, it is not verified, and it fails
242
+ * nothing. An entry written after that retirement, or under a distrusted key
243
+ * no trusted key has retired, fails as before (CHAIN_SIGNING_KEY_UNANCHORED
244
+ * or CHAIN_KEY_EXPIRED). An audit export never carries one.
245
+ *
246
+ * `chain` and `recordId`/`orgId` name the chain as the engine does: a record
247
+ * chain by its record id, the platform-ops chain (record id
248
+ * 00000000-0000-0000-0000-000000000000) as `admin`, and an org's schema chain
249
+ * (`schema:<orgId>`, `schema:__platform__` for the platform's) as `schema`.
250
+ */
251
+ export interface AccountedEntry {
252
+ code: AccountedEntryCode;
253
+ chain: 'record' | 'admin' | 'schema';
254
+ recordId: string | null;
255
+ orgId: string | null;
256
+ /** The chain's scope as the walk was given it (a record id, or a dump's `chain_key`). */
257
+ scopeId: string;
258
+ position: number;
259
+ keyId: string;
260
+ detail: string;
261
+ }
262
+ /** Name a chain scope (a record id or a dump `chain_key`) as {@link AccountedEntry} does. */
263
+ export declare function chainOfScope(scopeId: string): Pick<AccountedEntry, 'chain' | 'recordId' | 'orgId'>;
153
264
  export interface ChainResult {
154
265
  scopeId: string;
155
266
  valid: boolean;
@@ -161,6 +272,12 @@ export interface ChainResult {
161
272
  detail: string;
162
273
  };
163
274
  entries: ChainEntryResult[];
275
+ /**
276
+ * Entries the distrust entry accounts for (see {@link AccountedEntry}), in
277
+ * chain order. They count toward `valid` and not toward `verifiedEntries`
278
+ * or `signatureCoverage.signed`.
279
+ */
280
+ accounted: AccountedEntry[];
164
281
  signatureCoverage: {
165
282
  signed: number;
166
283
  unsigned: number;
@@ -169,9 +286,9 @@ export interface ChainResult {
169
286
  };
170
287
  /** Which input-gated checks actually ran on this chain vs were skipped for absent input. */
171
288
  optionalChecks: Record<OptionalCheck, CheckApplicability>;
172
- /** How many signature checks resolved against out-of-band vs embedded keys. */
289
+ /** How many signature checks resolved against supplied vs embedded keys. */
173
290
  keyProvenance: {
174
- outOfBand: number;
291
+ supplied: number;
175
292
  embedded: number;
176
293
  };
177
294
  /**
@@ -192,11 +309,13 @@ export interface VerifyChainOptions {
192
309
  /** Require every entry's signingKeyId to equal this id (else CHAIN_KEY_POLICY_VIOLATION). */
193
310
  requireKeyId?: string;
194
311
  /**
195
- * High-assurance auditor mode: refuse to verify against keys shipped inside
196
- * the artifact. An entry whose only available key is `embedded` fails
197
- * CHAIN_KEY_POLICY_VIOLATION. Forces the caller to supply keys out of band.
312
+ * Refuse to verify against keys shipped inside the artifact: an entry whose
313
+ * only available key is `embedded` fails CHAIN_KEY_POLICY_VIOLATION. This
314
+ * says where a key came from, not that it is trusted; a key the Server
315
+ * serves comes from its database. Anchor keys with `computeKeyTrust` /
316
+ * `applyKeyTrust` for that.
198
317
  */
199
- requireOutOfBandKeys?: boolean;
318
+ requireSuppliedKeys?: boolean;
200
319
  /**
201
320
  * Agent cert keys (see `buildAgentKeyRegistry`). When an entry's signed
202
321
  * payload carries an engine-validated `on_behalf_of.agent_signature` and its
@@ -204,7 +323,46 @@ export interface VerifyChainOptions {
204
323
  * offline; a failure is CHAIN_AGENT_SIGNATURE_INVALID.
205
324
  */
206
325
  agentKeys?: AgentKeyRegistry;
326
+ /**
327
+ * The instant this install began signing: the earliest `activatedAt` across
328
+ * its whole signing key set, retired keys included. An entry with a null
329
+ * `signingKeyId` whose `createdAt` is at or after it fails
330
+ * CHAIN_ENTRY_UNSIGNED.
331
+ *
332
+ * Omitted, it is derived from `keys` (`earliestKeyActivation`), which is
333
+ * right whenever `keys` is the whole key set, as it is on the dump path.
334
+ * Pass it when the caller knows windows for keys it has no public key for.
335
+ * `null` says the key set carries no activation time, so only the other
336
+ * half of the rule (an unsigned entry after a signed one) applies. A string
337
+ * that does not parse as a date throws `TypeError` rather than silently
338
+ * switching the check off.
339
+ */
340
+ signingSince?: string | null;
207
341
  }
342
+ /**
343
+ * The earliest `activatedAt` among `keys`, as the ISO string it was given in,
344
+ * or `null` when no key carries a parseable one. This is the instant from
345
+ * which the engine treats every chain entry and checkpoint as required to be
346
+ * signed; pass every key the verifier knows, retired ones included, since the
347
+ * engine reads it as `min(activated_at)` over its whole key registry.
348
+ */
349
+ export declare function earliestKeyActivation(keys: Iterable<{
350
+ activatedAt?: string | null;
351
+ }>): string | null;
352
+ /**
353
+ * Whether a row with no signing key id, written at `writtenAt`, falls inside
354
+ * the era in which the install signs everything: at or after `signingSince`
355
+ * (see `earliestKeyActivation`). This is the rule for an unsigned checkpoint
356
+ * (CHECKPOINT_UNSIGNED) and an unsigned read-log leaf or tree head, and the
357
+ * time half of the rule for an unsigned entry (CHAIN_ENTRY_UNSIGNED).
358
+ *
359
+ * False when `signingSince` is absent or unparseable: with no instant from
360
+ * which the install signs, nothing has to be signed. True when `signingSince`
361
+ * is known and `writtenAt` is missing or not strict RFC 3339: the engine times every
362
+ * row, so a row with no readable time was edited, and it cannot be placed
363
+ * before signing began. It fails closed rather than reading as early history.
364
+ */
365
+ export declare function writtenWhileSigning(writtenAt: unknown, signingSince: string | null | undefined): boolean;
208
366
  /**
209
367
  * Verify a single hash chain. `entries` are all the entries for one scope; they
210
368
  * are sorted by chainPosition internally (so a reordered export array still