@agledger/verify-core 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chain.js CHANGED
@@ -19,7 +19,7 @@
19
19
  * inputs): binding-integrity, OIDC-actor cross-check, temporal
20
20
  * key-validity, the agent-signature re-check, and key anchoring (a
21
21
  * registry marked by `applyKeyTrust`). The first three run on
22
- * the dump and on any export from an engine that ships the row fields
22
+ * the dump and on any export from a Server that ships the row fields
23
23
  * (>= v0.26.x). The agent-signature check needs the cert's public key,
24
24
  * which neither surface carries, so it runs only when the caller passes
25
25
  * `agentKeys`. A check without its input is reported `skipped_no_input`,
@@ -29,12 +29,14 @@
29
29
  * branch comes LAST, after the binding/OIDC checks, so a row written without a
30
30
  * signing key is still subject to every structural check, and a tamper finding
31
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
32
+ * That branch grades the entry the way the Server does: an unsigned entry
33
33
  * after a signed one in its chain, or written at or after the earliest key
34
34
  * activation (`signingSince`), is CHAIN_ENTRY_UNSIGNED; an earlier one is a
35
35
  * `skipped` signature, reduced coverage rather than a break.
36
36
  */
37
37
  import { buildPredicateForRow, decodeCoseSign1, decodePredicate, deepEqual, describeUnsupportedAlgorithm, ed25519JwkThumbprint, ed25519JwkToSpki, extractAgentSignatureClaim, extractActorClaim, extractChainClaim, extractKid, extractOnBehalfOfClaim, resolveKeyAlgorithm, sha256Hex, stripEnvelopeExtensions, envelopeExtensionsMatch, verifyAgentSignature, verifyCoseSign1, } from './primitives.js';
38
+ import { canonicalizeJson, checkFederationWire, extractFederationWire } from './federation-wire.js';
39
+ import { createHash } from 'node:crypto';
38
40
  import { instantMs, rfc3339Ms } from './instant.js';
39
41
  import { assertKnownOptions } from './options.js';
40
42
  /**
@@ -89,9 +91,9 @@ export function chainOfScope(scopeId) {
89
91
  /**
90
92
  * The earliest `activatedAt` among `keys`, as the ISO string it was given in,
91
93
  * or `null` when no key carries a parseable one. This is the instant from
92
- * which the engine treats every chain entry and checkpoint as required to be
94
+ * which the Server treats every chain entry and checkpoint as required to be
93
95
  * signed; pass every key the verifier knows, retired ones included, since the
94
- * engine reads it as `min(activated_at)` over its whole key registry.
96
+ * Server reads it as `min(activated_at)` over its whole key registry.
95
97
  */
96
98
  export function earliestKeyActivation(keys) {
97
99
  let earliest = null;
@@ -115,7 +117,7 @@ export function earliestKeyActivation(keys) {
115
117
  *
116
118
  * False when `signingSince` is absent or unparseable: with no instant from
117
119
  * which the install signs, nothing has to be signed. True when `signingSince`
118
- * is known and `writtenAt` is missing or not strict RFC 3339: the engine times every
120
+ * is known and `writtenAt` is missing or not strict RFC 3339: the Server times every
119
121
  * row, so a row with no readable time was edited, and it cannot be placed
120
122
  * before signing began. It fails closed rather than reading as early history.
121
123
  */
@@ -148,7 +150,7 @@ function positionKey(position) {
148
150
  * validates the true chain; tampering surfaces through the hash links).
149
151
  */
150
152
  export function verifyChain(entries, keys, options = {}) {
151
- assertKnownOptions('verifyChain', options, ['requireKeyId', 'requireSuppliedKeys', 'agentKeys', 'signingSince']);
153
+ assertKnownOptions('verifyChain', options, ['requireKeyId', 'requireSuppliedKeys', 'agentKeys', 'federationKeys', 'allowAfterRetirement', 'signingSince']);
152
154
  const scopeId = entries[0]?.scopeId ?? '(empty)';
153
155
  const sorted = entries
154
156
  .map((entry, at) => ({ entry, at, key: positionKey(entry.chainPosition) }))
@@ -163,9 +165,13 @@ export function verifyChain(entries, keys, options = {}) {
163
165
  key_temporal: 'skipped_no_input',
164
166
  agent_signature: 'skipped_no_input',
165
167
  key_anchoring: 'skipped_no_input',
168
+ federation_wire: 'skipped_no_input',
169
+ evidence_binding: 'skipped_no_input',
166
170
  };
167
171
  const keyProvenance = { supplied: 0, embedded: 0 };
168
172
  const agentSignatures = { present: 0, verified: 0 };
173
+ const federationWire = { present: 0, verified: 0, failed: 0, afterRetirement: 0 };
174
+ const evidenceBinding = { present: 0, verified: 0, clientHashed: 0, failed: 0 };
169
175
  let verifiedEntries = 0;
170
176
  let brokenAt;
171
177
  const accounted = [];
@@ -182,6 +188,8 @@ export function verifyChain(entries, keys, options = {}) {
182
188
  optionalChecks,
183
189
  keyProvenance,
184
190
  agentSignatures,
191
+ federationWire,
192
+ evidenceBinding,
185
193
  };
186
194
  }
187
195
  let signingSince;
@@ -195,18 +203,31 @@ export function verifyChain(entries, keys, options = {}) {
195
203
  }
196
204
  }
197
205
  const mustSign = { signedBefore: false, signingSince };
206
+ const unbound = { payload: false, federation: false };
198
207
  let previousHash = null;
199
208
  for (let i = 0; i < sorted.length; i++) {
200
209
  const entry = sorted[i];
201
210
  const expectedPosition = i + 1;
202
211
  let result = verifyEntry(entry, expectedPosition, previousHash, keys, options, optionalChecks, mustSign);
203
- // As the engine's walk does: any earlier row naming a key, whatever its own
212
+ // As the Server's walk does: any earlier row naming a key, whatever its own
204
213
  // verdict, means this chain was already being signed.
205
214
  if (entry.signingKeyId !== null)
206
215
  mustSign.signedBefore = true;
207
216
  if (result.valid && result.accounted === undefined) {
208
217
  result = checkAgentSignature(entry, result, options.agentKeys, optionalChecks, agentSignatures);
209
218
  }
219
+ if (result.valid && result.accounted === undefined && entry.binding === undefined && entry.bindingRequired !== undefined) {
220
+ unbound.payload = true;
221
+ if (entry.bindingRequired.federationWire)
222
+ unbound.federation = true;
223
+ result = failAfterSignature(entry, result, 'CHAIN_PAYLOAD_BINDING_MISMATCH', entry.bindingRequired.detail);
224
+ }
225
+ if (result.valid && result.accounted === undefined && entry.binding !== undefined) {
226
+ result = checkSealedFederationWire(entry, result, options.federationKeys, optionalChecks, federationWire, options.allowAfterRetirement === true);
227
+ }
228
+ if (result.valid && result.accounted === undefined && entry.inlinedEvidence !== undefined) {
229
+ result = checkInlinedEvidence(entry, entry.inlinedEvidence.value, result, optionalChecks, evidenceBinding);
230
+ }
210
231
  entryResults.push(result);
211
232
  if (result.accounted !== undefined) {
212
233
  accounted.push({
@@ -240,9 +261,16 @@ export function verifyChain(entries, keys, options = {}) {
240
261
  // 'not-checked' / 'invalid' / 'decode-fail' / 'unsupported' are failure
241
262
  // states: the entry is already counted as broken, so it contributes to
242
263
  // no coverage bucket.
264
+ default:
265
+ break;
243
266
  }
244
267
  previousHash = entry.payloadHash;
245
268
  }
269
+ // A check some entry could not take part in is not a check that ran.
270
+ if (unbound.payload)
271
+ optionalChecks.payload_binding = 'not_checked';
272
+ if (unbound.federation)
273
+ optionalChecks.federation_wire = 'not_checked';
246
274
  // The caller walked the key statements (every key carries a verdict), but no
247
275
  // entry got as far as the anchoring check.
248
276
  if (optionalChecks.key_anchoring === 'skipped_no_input' && [...keys.values()].some((k) => k.trust !== undefined)) {
@@ -260,14 +288,93 @@ export function verifyChain(entries, keys, options = {}) {
260
288
  optionalChecks,
261
289
  keyProvenance,
262
290
  agentSignatures,
291
+ federationWire,
292
+ evidenceBinding,
263
293
  };
264
294
  }
295
+ /** The payload field each entry type signs an inlined evidence body's hash under. */
296
+ const EVIDENCE_HASH_FIELD = {
297
+ COMPLETION_SUBMITTED: 'evidenceHash',
298
+ DISPUTE_EVIDENCE: 'payloadHash',
299
+ };
300
+ /**
301
+ * Re-bind an inlined evidence body to the hash its entry signs, on an entry
302
+ * that already passed every other check (so `binding.payload` is what the
303
+ * Server signed): SHA-256 hex over the RFC 8785 form of the body, the
304
+ * Server's `hashPayload`, against `payload.evidenceHash` (completion) or
305
+ * `payload.payloadHash` (dispute evidence). An encrypted-mode completion
306
+ * signs a hash its submitter computed over the cleartext, and the export
307
+ * inlines the ciphertext, so it is counted and left unbound.
308
+ */
309
+ function checkInlinedEvidence(entry, body, result, optionalChecks, counts) {
310
+ optionalChecks.evidence_binding = 'applied';
311
+ counts.present++;
312
+ const failed = (detail) => {
313
+ counts.failed++;
314
+ return failAfterSignature(entry, result, 'CHAIN_EVIDENCE_BINDING_MISMATCH', detail);
315
+ };
316
+ if (entry.binding === undefined) {
317
+ return failed('The entry inlines an evidence body but carries no payload, so no signed hash binds the body to the chain.');
318
+ }
319
+ const { entryType, payload } = entry.binding;
320
+ const field = EVIDENCE_HASH_FIELD[entryType];
321
+ if (field === undefined) {
322
+ return failed(`A ${entryType} entry inlines an evidence body. The Server inlines evidence only on COMPLETION_SUBMITTED and DISPUTE_EVIDENCE entries, and nothing this entry signs binds a body.`);
323
+ }
324
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
325
+ return failed(`The inlined evidence is ${body === null ? 'null' : Array.isArray(body) ? 'an array' : typeof body}, not the JSON object the entry's payload.${field} was computed over.`);
326
+ }
327
+ const signed = payload[field];
328
+ if (typeof signed !== 'string' || !/^[0-9a-f]{64}$/i.test(signed)) {
329
+ return failed(`The entry inlines an evidence body but signs no payload.${field} to bind it to.`);
330
+ }
331
+ if (entryType === 'COMPLETION_SUBMITTED' && payload.verifiedBy === 'client') {
332
+ counts.clientHashed++;
333
+ return result;
334
+ }
335
+ const digest = createHash('sha256').update(canonicalizeJson(body), 'utf8').digest('hex');
336
+ if (digest !== signed.toLowerCase()) {
337
+ return failed(`The inlined evidence body hashes to ${digest} under RFC 8785 and SHA-256, and the entry signs payload.${field} ${signed.toLowerCase()}: the body was edited after export, or is not the one submitted.`);
338
+ }
339
+ counts.verified++;
340
+ return result;
341
+ }
342
+ /**
343
+ * The sealed federation message on an entry that already passed every other
344
+ * check (so `binding.payload` is what the receiver signed): its body hash,
345
+ * its agreement with the entry, and, under a supplied key for the sending
346
+ * hub, its signature. See `federation-wire.ts`.
347
+ */
348
+ function checkSealedFederationWire(entry, result, federationKeys, optionalChecks, counts, allowAfterRetirement) {
349
+ if (entry.binding === undefined)
350
+ return result;
351
+ const wire = extractFederationWire(entry.binding.payload);
352
+ if (wire === null)
353
+ return result;
354
+ optionalChecks.federation_wire = 'applied';
355
+ if (wire === 'malformed') {
356
+ return failAfterSignature(entry, result, 'CHAIN_FEDERATION_WIRE_INVALID', 'payload.wire is present but is not a sealed federation message (an object with scheme, senderHubId, senderPublicKey, recipientHubId, method, path, bodyHash, timestamp, nonce, signature and an object body).');
357
+ }
358
+ counts.present++;
359
+ const outcome = checkFederationWire(entry.binding.entryType, entry.binding.recordId, entry.binding.payload, wire, federationKeys, { allowAfterRetirement });
360
+ if (outcome.outcome === 'ok') {
361
+ if (outcome.signatureChecked)
362
+ counts.verified++;
363
+ if (outcome.afterRetirement)
364
+ counts.afterRetirement++;
365
+ return result;
366
+ }
367
+ if (outcome.outcome === 'unchecked')
368
+ return result;
369
+ counts.failed++;
370
+ return failAfterSignature(entry, result, outcome.outcome === 'unsupported' ? 'CHAIN_UNSUPPORTED_ALGORITHM' : 'CHAIN_FEDERATION_WIRE_INVALID', outcome.detail);
371
+ }
265
372
  /**
266
373
  * Offline re-check of a sealed agent signature, on an entry that already
267
- * passed every other check (so its payload is the engine's signed bytes).
374
+ * passed every other check (so its payload is the Server's signed bytes).
268
375
  *
269
- * Runs only on an engine-validated identity (`on_behalf_of.validated: true`).
270
- * On a caller-asserted one, entries written before the engine sealed these
376
+ * Runs only on a Server-validated identity (`on_behalf_of.validated: true`).
377
+ * On a caller-asserted one, entries written before the Server sealed these
271
378
  * fields itself carry them as caller passthrough, and the marker telling the
272
379
  * two apart is a column neither the export nor the dump publishes, so a
273
380
  * failure there could not be told from a claim nobody ever checked.
@@ -293,11 +400,11 @@ function checkAgentSignature(entry, result, agentKeys, optionalChecks, counts) {
293
400
  }
294
401
  const certLabel = claim.certId ?? claim.certThumbprint;
295
402
  if (outcome === 'unsupported') {
296
- return fail(entry.scopeId, result.position, 'CHAIN_UNSUPPORTED_ALGORITHM', `Agent signature for cert ${certLabel} could not be checked: this host cannot compute Ed25519 (an active OpenSSL FIPS provider carries no EdDSA). Not verified, and not tamper evidence.`, result.signature);
403
+ return failAfterSignature(entry, result, 'CHAIN_UNSUPPORTED_ALGORITHM', `Agent signature for cert ${certLabel} could not be checked: this host cannot compute Ed25519 (an active OpenSSL FIPS provider carries no EdDSA). Not verified, and not tamper evidence.`);
297
404
  }
298
- return fail(entry.scopeId, result.position, 'CHAIN_AGENT_SIGNATURE_INVALID', outcome === 'malformed'
405
+ return failAfterSignature(entry, result, 'CHAIN_AGENT_SIGNATURE_INVALID', outcome === 'malformed'
299
406
  ? `Sealed agent_signature for cert ${certLabel} has a shape nothing can verify (alg must be EdDSA, content_hash sha256:<hex64>, signature 64 bytes of standard base64).`
300
- : `Sealed agent_signature for cert ${certLabel} does not verify under the supplied key with thumbprint ${claim.certThumbprint}.`, result.signature);
407
+ : `Sealed agent_signature for cert ${certLabel} does not verify under the supplied key with thumbprint ${claim.certThumbprint}.`);
301
408
  }
302
409
  function accountedResult(scopeId, position, detail) {
303
410
  return { scopeId, position, valid: true, accounted: { code: ACCOUNTED_ENTRY_CODE, detail }, signature: 'accounted' };
@@ -309,8 +416,16 @@ function declaredAlgorithmLies(key) {
309
416
  const keyAlg = resolveKeyAlgorithm(key.spkiBase64);
310
417
  return typeof keyAlg === 'object' && keyAlg.name.toLowerCase() !== key.algorithm.toLowerCase();
311
418
  }
312
- function fail(scopeId, position, code, detail, signature = 'not-checked') {
313
- return { scopeId, position, valid: false, failure: { code, detail }, signature };
419
+ function fail(scopeId, position, code, detail, signature = 'not-checked', keySource) {
420
+ return { scopeId, position, valid: false, failure: { code, detail }, signature, ...(keySource !== undefined ? { keySource } : {}) };
421
+ }
422
+ /**
423
+ * Fail an entry a check after the signature check refused: it keeps the
424
+ * signature state and the key it verified under, so `keyProvenance` still
425
+ * counts every signed entry (`signed = supplied + embedded`).
426
+ */
427
+ function failAfterSignature(entry, result, code, detail) {
428
+ return fail(entry.scopeId, result.position, code, detail, result.signature, result.keySource);
314
429
  }
315
430
  function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, optionalChecks, mustSign) {
316
431
  const { scopeId } = entry;
@@ -344,14 +459,14 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
344
459
  return fail(scopeId, expectedPosition, 'CHAIN_COSE_HEADER_MISMATCH', `Signed protected-header chain claim (position=${chainClaim?.position ?? 'null'}, prev=${chainClaim?.previous_hash ?? 'null'}) diverges from row columns (position=${entry.chainPosition}, prev=${entry.previousHash ?? 'null'}).`);
345
460
  }
346
461
  // Input-gated: actor attribution. The row's actorId/actorOwnerId columns are
347
- // the projection a report displays as "who did this", and the engine's own
462
+ // the projection a report displays as "who did this", and the Server's own
348
463
  // export guide names them as the trustworthy attribution while listing only
349
464
  // actorDisplayName / actorOwnerType / humanReadableLabel as unsigned. They
350
465
  // are signature-covered, at CWT_Claims label 15 -> private label -65539, so
351
466
  // a rewritten column is a re-attribution of the action to another actor and
352
467
  // must not verify. Same shape as the signed-kid check above: compare the
353
468
  // column against the signed claim, and skip only when one side is absent
354
- // (an older engine that never carried the claim, or an artifact that does
469
+ // (an older Server that never carried the claim, or an artifact that does
355
470
  // not carry the columns).
356
471
  const attribution = entry.actorAttribution;
357
472
  if (attribution) {
@@ -374,7 +489,7 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
374
489
  }
375
490
  }
376
491
  // Input-gated: binding-integrity. Runs whenever the row payload is present:
377
- // the dump always carries it, and the export now carries it too (engine ≥ v0.26.x).
492
+ // the dump always carries it, and the export now carries it too (Server ≥ v0.26.x).
378
493
  if (entry.binding) {
379
494
  optionalChecks.payload_binding = 'applied';
380
495
  const decodedRaw = decodePredicate(parts.payloadBstr);
@@ -384,8 +499,8 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
384
499
  decoded === null ||
385
500
  rebuilt === null ||
386
501
  !deepEqual(rebuilt, decoded) ||
387
- !envelopeExtensionsMatch(entry.binding.payload, decodedRaw)) {
388
- return fail(scopeId, expectedPosition, 'CHAIN_PAYLOAD_BINDING_MISMATCH', 'Denormalised row payload no longer matches the canonical projection of the signed predicate.');
502
+ !envelopeExtensionsMatch(entry.binding.payload, decodedRaw, entry.binding.extensionsProjected === true)) {
503
+ return fail(scopeId, expectedPosition, 'CHAIN_PAYLOAD_BINDING_MISMATCH', 'Denormalised row payload does not match the canonical projection of the signed predicate.');
389
504
  }
390
505
  }
391
506
  // Input-gated: OIDC-actor cross-check. Only when the dump carried the columns.
@@ -396,12 +511,12 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
396
511
  return oidcFailure;
397
512
  }
398
513
  // Signature (last, so a null-key row still ran every structural check above).
399
- // Only a true null is the engine's unsigned-mode marker. Any other value,
400
- // including the empty string no engine emits, must resolve in the registry
514
+ // Only a true null is the Server's unsigned-mode marker. Any other value,
515
+ // including the empty string no Server emits, must resolve in the registry
401
516
  // and fails CHAIN_SIGNATURE_MISSING_KEY below: a truthiness shortcut here
402
517
  // would let a tampered signingKeyId:"" row skip its signature check.
403
518
  if (entry.signingKeyId === null) {
404
- // Engine mirror of `signature_missing`. An unsigned entry is reduced
519
+ // Server mirror of `signature_missing`. An unsigned entry is reduced
405
520
  // coverage only where the install had not yet begun to sign: before any
406
521
  // signed entry in this chain, and before the earliest key activation.
407
522
  // Anywhere else no process of the install could have written it; it is
@@ -411,7 +526,7 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
411
526
  if (mustSign.signedBefore) {
412
527
  return fail(scopeId, expectedPosition, 'CHAIN_ENTRY_UNSIGNED', 'Entry has no signingKeyId but follows a signed entry in the same chain.');
413
528
  }
414
- // The engine times every entry. Without a time the walk can read, an
529
+ // The Server times every entry. Without a time the walk can read, an
415
530
  // unsigned entry cannot be placed before signing began, so it is not
416
531
  // early history: it fails closed.
417
532
  if (mustSign.signingSince !== null && !isInstant(entry.createdAt)) {
@@ -439,8 +554,8 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
439
554
  if (options.requireSuppliedKeys && key.source !== 'supplied') {
440
555
  return fail(scopeId, expectedPosition, 'CHAIN_KEY_POLICY_VIOLATION', `Key ${entry.signingKeyId} is embedded in the artifact; this run requires supplied keys.`);
441
556
  }
442
- // Signed-kid binding (engine mirror: signing_key_drift), ahead of every
443
- // question about the key, as the engine orders it. The row's signingKeyId
557
+ // Signed-kid binding (Server mirror: signing_key_drift), ahead of every
558
+ // question about the key, as the Server orders it. The row's signingKeyId
444
559
  // column selected the key above, but the column is a denormalized
445
560
  // convenience; the kid at protected-header label 4 is signature-covered. A
446
561
  // divergence means the column was rewritten after signing, e.g. to point
@@ -451,7 +566,7 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
451
566
  if (signedKid !== null && signedKid !== entry.signingKeyId) {
452
567
  return fail(scopeId, expectedPosition, 'CHAIN_SIGNING_KEY_DRIFT', `Row signingKeyId=${entry.signingKeyId} does not match the signature-covered kid ${signedKid} in the protected header.`);
453
568
  }
454
- // Input-gated: key anchoring (engine mirror: signing_key_unanchored). Runs
569
+ // Input-gated: key anchoring (Server mirror: signing_key_unanchored). Runs
455
570
  // when a key-statement walk marked the registry. A key nothing signed links
456
571
  // to a pinned anchor is one anything with write access to the Server's
457
572
  // database can register, so an entry under it is a forgery until shown
@@ -476,7 +591,7 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
476
591
  }
477
592
  }
478
593
  // Registry self-consistency: when the input surface declares an algorithm for
479
- // this key (vault_signing_keys.algorithm), it must agree with what the SPKI
594
+ // this key, it must agree with what the SPKI
480
595
  // key material commits to. A registry row that lies about its own key is the
481
596
  // signature of a mis-registered key (the pre-guard P-256 corruption shape) or
482
597
  // a rewritten registry, and nothing verified against it can be trusted.
@@ -485,7 +600,7 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
485
600
  }
486
601
  // Input-gated: temporal key-validity, whenever the key carries a window.
487
602
  // Compared at millisecond precision, the precision of an entry's write time,
488
- // truncating a microsecond window edge the way the engine does. The engine
603
+ // truncating a microsecond window edge the way the Server does. The Server
489
604
  // times every entry, so an entry with no time the walk can read cannot be
490
605
  // placed inside the window, and fails closed rather than skipping it.
491
606
  if (typeof key.activatedAt === 'string' || typeof key.retiredAt === 'string' || typeof key.distrustCutoff === 'string') {
@@ -519,7 +634,7 @@ function verifyEntry(entry, expectedPosition, expectedPrevHash, keys, options, o
519
634
  const outcome = verifyCoseSign1(envelopeBytes, key.spkiBase64);
520
635
  if (outcome === 'unsigned') {
521
636
  // An all-zero signature slot on an entry that CLAIMS a signing key. The
522
- // engine writes a key id only beside a signature it made with that key,
637
+ // Server writes a key id only beside a signature it made with that key,
523
638
  // and fails this shape `signature_invalid`, so it is a forged or wiped
524
639
  // signature, never an unsigned entry. (A genuinely unsigned entry carries
525
640
  // a null signingKeyId and is graded above.)
@@ -556,21 +671,21 @@ function checkOidcActor(oidc, payloadBstr, scopeId, position) {
556
671
  }
557
672
  return null;
558
673
  }
559
- // synthesized=false: engine writers leave the columns null. Any populated
560
- // state is a DB-level CHECK-constraint bypass.
674
+ // synthesized=false: the Server leaves the columns null. Any populated
675
+ // state means the row was altered outside the Server.
561
676
  if (synthesized === false && (rowIss !== null || rowSub !== null)) {
562
677
  return fail(scopeId, position, 'CHAIN_OIDC_ACTOR_MISMATCH', `actor_oidc_synthesized=false but iss/sub populated (${rowIss ?? 'null'}/${rowSub ?? 'null'}).`);
563
678
  }
564
679
  return null;
565
680
  }
566
681
  /**
567
- * Temporal key-validity, split by direction. Both directions used to report
568
- * `CHAIN_KEY_EXPIRED`, so a consumer branching on the code saw "expired" for a
569
- * key that had not started yet and would reason about rotation or retention
570
- * when the real condition is clock skew or backdating. Those are different
571
- * investigations, and the activation side is the security-relevant one.
682
+ * Temporal key-validity, split by direction. A key not yet active reports
683
+ * `CHAIN_KEY_NOT_YET_ACTIVE` and a retired key reports `CHAIN_KEY_EXPIRED`, so a
684
+ * consumer branching on the code does not read clock skew or backdating as
685
+ * rotation or retention. Those are different investigations, and the
686
+ * activation side is the security-relevant one.
572
687
  */
573
- function temporalKeyFailure(createdAt, key) {
688
+ function temporalKeyFailure(createdAt, key, what = 'Entry') {
574
689
  const written = rfc3339Ms(createdAt);
575
690
  if (Number.isNaN(written))
576
691
  return null;
@@ -579,7 +694,7 @@ function temporalKeyFailure(createdAt, key) {
579
694
  if (!Number.isNaN(activated) && written < activated) {
580
695
  return {
581
696
  code: 'CHAIN_KEY_NOT_YET_ACTIVE',
582
- detail: `Entry written ${createdAt} predates key ${key.keyId} activation ${key.activatedAt}.`,
697
+ detail: `${what} written ${createdAt} predates key ${key.keyId} activation ${key.activatedAt}.`,
583
698
  };
584
699
  }
585
700
  }
@@ -588,7 +703,7 @@ function temporalKeyFailure(createdAt, key) {
588
703
  if (!Number.isNaN(cutoff) && written > cutoff) {
589
704
  return {
590
705
  code: 'CHAIN_KEY_EXPIRED',
591
- detail: `Entry written ${createdAt} postdates ${key.distrustCutoff}, the instant distrustedKeys (VAULT_DISTRUSTED_KEYS on the Server) gives for key ${key.keyId}; the key was not retired then.`,
706
+ detail: `${what} written ${createdAt} postdates ${key.distrustCutoff}, the instant distrustedKeys (VAULT_DISTRUSTED_KEYS on the Server) gives for key ${key.keyId}; the key was not retired then.`,
592
707
  };
593
708
  }
594
709
  }
@@ -597,9 +712,65 @@ function temporalKeyFailure(createdAt, key) {
597
712
  if (!Number.isNaN(retired) && written > retired) {
598
713
  return {
599
714
  code: 'CHAIN_KEY_EXPIRED',
600
- detail: `Entry written ${createdAt} postdates key ${key.keyId} retirement ${key.retiredAt}.`,
715
+ detail: `${what} written ${createdAt} postdates key ${key.keyId} retirement ${key.retiredAt}.`,
601
716
  };
602
717
  }
603
718
  }
604
719
  return null;
605
720
  }
721
+ /**
722
+ * Place a vault checkpoint, a read-log leaf or a read-log tree head in the
723
+ * signed window of its key, by the time its row was written. The rule is the
724
+ * one chain entries are held to (CHAIN_KEY_NOT_YET_ACTIVE, CHAIN_KEY_EXPIRED):
725
+ * each edge is checked only when the key carries it, at millisecond
726
+ * precision, and an artifact written exactly at the key's retirement is
727
+ * inside. `what` names the artifact in the detail ("Checkpoint", "Leaf").
728
+ *
729
+ * The caller verifies the signature first: the Server reports a signature
730
+ * that does not verify ahead of a window finding.
731
+ */
732
+ export function placeInKeyWindow(key, writtenAt, what) {
733
+ if (typeof key.activatedAt !== 'string' && typeof key.retiredAt !== 'string' && typeof key.distrustCutoff !== 'string') {
734
+ return { placement: 'inside' };
735
+ }
736
+ for (const [edge, value] of [['activatedAt', key.activatedAt], ['retiredAt', key.retiredAt], ['distrustCutoff', key.distrustCutoff]]) {
737
+ if (typeof value === 'string' && !isInstant(value)) {
738
+ return { placement: 'unplaceable', detail: `Key ${key.keyId}'s ${edge} ${JSON.stringify(value)} is not an RFC 3339 instant, so the ${what.toLowerCase()} cannot be placed inside its window.` };
739
+ }
740
+ }
741
+ if (!isInstant(writtenAt)) {
742
+ return { placement: 'unplaceable', detail: `${what} has no parseable write time, so it cannot be placed inside key ${key.keyId}'s window.` };
743
+ }
744
+ const temporal = temporalKeyFailure(writtenAt, key, what);
745
+ if (temporal === null)
746
+ return { placement: 'inside' };
747
+ const span = key.distrustSpan;
748
+ const written = rfc3339Ms(writtenAt);
749
+ if (temporal.code === 'CHAIN_KEY_EXPIRED' && span !== undefined && span.cutoff !== null && span.retiredAt !== null
750
+ && written >= instantMs(span.cutoff) && written < instantMs(span.retiredAt)) {
751
+ return { placement: 'accounted' };
752
+ }
753
+ return { placement: temporal.code === 'CHAIN_KEY_EXPIRED' ? 'expired' : 'not-yet-active', detail: temporal.detail };
754
+ }
755
+ /**
756
+ * Whether a `distrustedKeys` entry and the retirement a trusted key signed
757
+ * account for an artifact signed under `key` and written at `writtenAt`: the
758
+ * key is unanchored only because of the entry, or anchored and the artifact
759
+ * written at or after the entry's instant, and in both cases the artifact was
760
+ * written before that retirement. The same condition lists a chain entry as
761
+ * CHAIN_SIGNED_BY_DISTRUSTED_KEY.
762
+ *
763
+ * Such an artifact is listed, never verified, and never evidence for or
764
+ * against anything else. The caller still verifies its signature under the
765
+ * key before setting it aside: anything else under the key's id is bytes
766
+ * whoever writes to the database wrote.
767
+ */
768
+ export function distrustAccounts(key, writtenAt) {
769
+ if (key.trust === 'undecided' || declaredAlgorithmLies(key))
770
+ return false;
771
+ if (key.trust === 'unanchored') {
772
+ const bound = key.distrustSpan?.retiredAt ?? null;
773
+ return bound !== null && isInstant(writtenAt) && rfc3339Ms(writtenAt) < instantMs(bound);
774
+ }
775
+ return placeInKeyWindow(key, writtenAt, 'Artifact').placement === 'accounted';
776
+ }
@@ -41,48 +41,62 @@
41
41
  * verdict, never a silent pass.
42
42
  *
43
43
  * Later additions:
44
- * - CHAIN_ENTRY_UNSIGNED engine mirror of `signature_missing`: an entry with
44
+ * - CHAIN_ENTRY_UNSIGNED Server mirror of `signature_missing`: an entry with
45
45
  * no signing key id after a signed entry in its
46
46
  * chain, or written at or after the earliest
47
47
  * activatedAt in the key set. Earlier unsigned
48
48
  * entries stay reduced coverage.
49
- * - CHECKPOINT_UNSIGNED engine mirror of `checkpoint_unsigned`: the same
49
+ * - CHECKPOINT_UNSIGNED Server mirror of `checkpoint_unsigned`: the same
50
50
  * instant, applied to an unsigned checkpoint.
51
51
  * - TENANT_READ_LEAF_UNSIGNED and TENANT_CHECKPOINT_UNSIGNED the same two
52
- * rules on the org_admin_reads log (engine
52
+ * rules on the org_admin_reads log (Server
53
53
  * `leaf_signature_missing`, `checkpoint_unsigned`).
54
- * - CHAIN_SIGNING_KEY_UNANCHORED engine mirror of `signing_key_unanchored`:
54
+ * - CHAIN_SIGNING_KEY_UNANCHORED Server mirror of `signing_key_unanchored`:
55
55
  * the entry's key is not linked by signed key
56
56
  * statements to a pinned trust anchor. With
57
57
  * CHECKPOINT_KEY_UNANCHORED,
58
58
  * TENANT_READ_KEY_UNANCHORED and
59
59
  * TENANT_CHECKPOINT_KEY_UNANCHORED for the
60
- * engine's `checkpoint_key_unanchored` and
60
+ * Server's `checkpoint_key_unanchored` and
61
61
  * `leaf_key_unanchored`.
62
+ * - CHECKPOINT_KEY_NOT_YET_ACTIVE, CHECKPOINT_KEY_EXPIRED, and the
63
+ * TENANT_READ_KEY_* and TENANT_CHECKPOINT_KEY_* pairs Server mirror of
64
+ * `checkpoint_key_not_yet_active`,
65
+ * `checkpoint_key_expired`, `leaf_key_not_yet_active`
66
+ * and `leaf_key_expired`: a vault checkpoint, a
67
+ * read-log leaf or a read-log tree head written
68
+ * outside its signing key's signed window, by
69
+ * the rule CHAIN_KEY_NOT_YET_ACTIVE and
70
+ * CHAIN_KEY_EXPIRED apply to entries.
71
+ * - CHECKPOINT_ACCOUNTED_ONLY, CHECKPOINT_ACCOUNTED_RUN_EXCEEDED Server mirror
72
+ * of `accounted_checkpoint_only` and
73
+ * `checkpoint_accounted_run_exceeded`: what a
74
+ * chain is left with when the checkpoints a
75
+ * distrustedKeys entry accounts for are set aside.
62
76
  * - KEY_STATEMENT_INVALID, KEY_CLOSURE_INVALID, CHAIN_KEY_WINDOW_DRIFT
63
- * engine mirrors of the key registry findings
77
+ * Server mirrors of the key registry findings
64
78
  * `key_statement_invalid`, `key_closure_invalid`
65
79
  * and `key_window_drift`. They are about the
66
80
  * registry, not about any one entry.
67
81
  * - CHECKPOINT_CLAIM_MISMATCH, TENANT_READ_CLAIM_MISMATCH,
68
- * TENANT_CHECKPOINT_CLAIM_MISMATCH engine mirrors of the vault's
82
+ * TENANT_CHECKPOINT_CLAIM_MISMATCH Server mirrors of the vault's
69
83
  * `checkpoint_claim_mismatch` and the read log's
70
84
  * `leaf_claim_mismatch` and
71
85
  * `checkpoint_claim_mismatch`: the claim signed
72
86
  * inside the envelope does not decode, or says
73
87
  * something the row's columns do not.
74
88
  *
75
- * Server-side cert re-checks are not mirrored here. The engine's chain
89
+ * Server-side cert re-checks are not mirrored here. The Server's chain
76
90
  * verification also reports `cert_missing`, `cert_actor_drift`,
77
91
  * `cert_window_drift`, `cert_expired` and `agent_signature_invalid`, by
78
92
  * comparing what an entry sealed in `predicate.on_behalf_of.cert` against the
79
- * live `ephemeral_certs` row. Neither the export nor the dump carries that
80
- * table, so an offline verifier cannot reproduce those comparisons, and it
93
+ * Server's cert record. Neither the export nor the dump carries that
94
+ * record, so an offline verifier cannot reproduce those comparisons, and it
81
95
  * does not need to: it trusts only the signed bytes, which already fix the
82
96
  * sealed cert id, thumbprint and expiry. The one cert-related check that can
83
97
  * run offline is the agent signature, and only when the caller supplies the
84
98
  * cert's public key (CHAIN_AGENT_SIGNATURE_INVALID below).
85
99
  */
86
- export type FailureCode = 'UNSUPPORTED_FORMAT' | 'CHAIN_EMPTY' | 'CHAIN_POSITION_GAP' | 'CHAIN_GENESIS_INVALID' | 'CHAIN_LINK_BROKEN' | 'CHAIN_HASH_MISMATCH' | 'CHAIN_MALFORMED_ENTRY' | 'CHAIN_COSE_DECODE_FAILED' | 'CHAIN_COSE_HEADER_MISMATCH' | 'CHAIN_PAYLOAD_BINDING_MISMATCH' | 'CHAIN_OIDC_ACTOR_MISMATCH' | 'CHAIN_SIGNATURE_INVALID' | 'CHAIN_SIGNATURE_MISSING_KEY' | 'CHAIN_KEY_POLICY_VIOLATION' | 'CHAIN_KEY_EXPIRED' | 'CHAIN_KEY_NOT_YET_ACTIVE' | 'CHAIN_ALG_MISMATCH' | 'CHAIN_UNSUPPORTED_ALGORITHM' | 'CHAIN_SIGNING_KEY_DRIFT' | 'CHAIN_ACTOR_ATTRIBUTION_MISMATCH' | 'CHAIN_AGENT_SIGNATURE_INVALID' | 'CHAIN_ENTRY_UNSIGNED' | 'CHAIN_SIGNING_KEY_UNANCHORED' | 'CHAIN_KEY_WINDOW_DRIFT' | 'CHECKPOINT_ROW_MISSING' | 'CHECKPOINT_HASH_MISMATCH' | 'CHECKPOINT_SIGNATURE_INVALID' | 'CHECKPOINT_UNSIGNED' | 'CHECKPOINT_KEY_UNANCHORED' | 'CHECKPOINT_CLAIM_MISMATCH' | 'TENANT_READ_LEAF_HASH_MISMATCH' | 'TENANT_READ_LEAF_INDEX_GAP' | 'TENANT_READ_SIGNATURE_INVALID' | 'TENANT_READ_LEAF_UNSIGNED' | 'TENANT_READ_KEY_UNANCHORED' | 'TENANT_READ_CLAIM_MISMATCH' | 'TENANT_CHECKPOINT_LEAF_COUNT_MISMATCH' | 'TENANT_CHECKPOINT_ROOT_MISMATCH' | 'TENANT_CHECKPOINT_SIGNATURE_INVALID' | 'TENANT_CHECKPOINT_UNSIGNED' | 'TENANT_CHECKPOINT_KEY_UNANCHORED' | 'TENANT_CHECKPOINT_CLAIM_MISMATCH' | 'TENANT_CHECKPOINT_FORK' | 'KEY_STATEMENT_INVALID' | 'KEY_CLOSURE_INVALID';
100
+ export type FailureCode = 'UNSUPPORTED_FORMAT' | 'CHAIN_EMPTY' | 'CHAIN_POSITION_GAP' | 'CHAIN_GENESIS_INVALID' | 'CHAIN_LINK_BROKEN' | 'CHAIN_HASH_MISMATCH' | 'CHAIN_MALFORMED_ENTRY' | 'CHAIN_COSE_DECODE_FAILED' | 'CHAIN_COSE_HEADER_MISMATCH' | 'CHAIN_PAYLOAD_BINDING_MISMATCH' | 'CHAIN_OIDC_ACTOR_MISMATCH' | 'CHAIN_SIGNATURE_INVALID' | 'CHAIN_SIGNATURE_MISSING_KEY' | 'CHAIN_KEY_POLICY_VIOLATION' | 'CHAIN_KEY_EXPIRED' | 'CHAIN_KEY_NOT_YET_ACTIVE' | 'CHAIN_ALG_MISMATCH' | 'CHAIN_UNSUPPORTED_ALGORITHM' | 'CHAIN_SIGNING_KEY_DRIFT' | 'CHAIN_ACTOR_ATTRIBUTION_MISMATCH' | 'CHAIN_AGENT_SIGNATURE_INVALID' | 'CHAIN_FEDERATION_WIRE_INVALID' | 'CHAIN_EVIDENCE_BINDING_MISMATCH' | 'CHAIN_ENTRY_UNSIGNED' | 'CHAIN_SIGNING_KEY_UNANCHORED' | 'CHAIN_KEY_WINDOW_DRIFT' | 'CHECKPOINT_ROW_MISSING' | 'CHECKPOINT_HASH_MISMATCH' | 'CHECKPOINT_SIGNATURE_INVALID' | 'CHECKPOINT_UNSIGNED' | 'CHECKPOINT_KEY_UNANCHORED' | 'CHECKPOINT_CLAIM_MISMATCH' | 'CHECKPOINT_KEY_NOT_YET_ACTIVE' | 'CHECKPOINT_KEY_EXPIRED' | 'CHECKPOINT_ACCOUNTED_ONLY' | 'CHECKPOINT_ACCOUNTED_RUN_EXCEEDED' | 'TENANT_READ_LEAF_HASH_MISMATCH' | 'TENANT_READ_LEAF_INDEX_GAP' | 'TENANT_READ_SIGNATURE_INVALID' | 'TENANT_READ_LEAF_UNSIGNED' | 'TENANT_READ_KEY_UNANCHORED' | 'TENANT_READ_CLAIM_MISMATCH' | 'TENANT_READ_KEY_NOT_YET_ACTIVE' | 'TENANT_READ_KEY_EXPIRED' | 'TENANT_CHECKPOINT_LEAF_COUNT_MISMATCH' | 'TENANT_CHECKPOINT_ROOT_MISMATCH' | 'TENANT_CHECKPOINT_SIGNATURE_INVALID' | 'TENANT_CHECKPOINT_UNSIGNED' | 'TENANT_CHECKPOINT_KEY_UNANCHORED' | 'TENANT_CHECKPOINT_CLAIM_MISMATCH' | 'TENANT_CHECKPOINT_KEY_NOT_YET_ACTIVE' | 'TENANT_CHECKPOINT_KEY_EXPIRED' | 'TENANT_CHECKPOINT_FORK' | 'KEY_STATEMENT_INVALID' | 'KEY_CLOSURE_INVALID';
87
101
  /** The actionable next step for a failure code. */
88
102
  export declare function suggestion(code: FailureCode): string;