@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,7 @@
1
+ /**
2
+ * Throw `TypeError` on an options object that is not an object, or that
3
+ * carries a key `fn` does not read. A misspelt or renamed option that is
4
+ * dropped without a word switches off the check it named, and the result
5
+ * passes as if it had run.
6
+ */
7
+ export declare function assertKnownOptions(fn: string, options: unknown, known: readonly string[]): void;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Options renamed in a major release, by their old name. A caller upgrading
3
+ * with the old name would otherwise drop the check it asked for and still
4
+ * pass.
5
+ */
6
+ const RENAMED = {
7
+ requireOutOfBandKeys: 'requireSuppliedKeys',
8
+ };
9
+ /**
10
+ * Throw `TypeError` on an options object that is not an object, or that
11
+ * carries a key `fn` does not read. A misspelt or renamed option that is
12
+ * dropped without a word switches off the check it named, and the result
13
+ * passes as if it had run.
14
+ */
15
+ export function assertKnownOptions(fn, options, known) {
16
+ if (options === undefined)
17
+ return;
18
+ if (options === null || typeof options !== 'object' || Array.isArray(options)) {
19
+ throw new TypeError(`${fn}: options must be an object.`);
20
+ }
21
+ for (const key of Object.keys(options)) {
22
+ if (known.includes(key))
23
+ continue;
24
+ const renamed = RENAMED[key];
25
+ throw new TypeError(renamed !== undefined && known.includes(renamed)
26
+ ? `${fn}: the ${key} option is now ${renamed}; pass ${renamed} instead. It was renamed in 2.0.0, and an unknown option is refused rather than ignored.`
27
+ : `${fn}: unknown option ${key}. It reads ${known.join(', ')}.`);
28
+ }
29
+ }
@@ -191,6 +191,25 @@ export interface ChainClaim {
191
191
  previous_hash: string | null;
192
192
  }
193
193
  export declare function extractChainClaim(protectedBstr: Uint8Array): ChainClaim | null;
194
+ /**
195
+ * Extract the actor identity claim (`-65539`) from a COSE_Sign1 protected
196
+ * header. It is nested inside CWT_Claims (RFC 9597, label 15) rather than
197
+ * sitting at the outer header level, because it IS an identity statement: the
198
+ * engine keeps the outer level to IANA-known labels plus chain mechanics.
199
+ *
200
+ * `key_id` and `owner_id` are UUIDs the engine encodes as 16-byte CBOR byte
201
+ * strings, returned here in canonical lowercase-hyphenated form so they
202
+ * compare directly against the export's `actorId` / `actorOwnerId` columns.
203
+ * Returns null when the claim is missing or malformed (engines older than the
204
+ * claim, or an envelope that will not decode) so the caller can skip rather
205
+ * than fail an entry that never carried it.
206
+ */
207
+ export interface ActorClaim {
208
+ key_id: string;
209
+ role: string;
210
+ owner_id: string;
211
+ }
212
+ export declare function extractActorClaim(protectedBstr: Uint8Array): ActorClaim | null;
194
213
  /**
195
214
  * Extract the OIDC on-behalf-of context from a COSE_Sign1 payload bstr. The
196
215
  * payload IS the in-toto v1 Statement; `predicate.on_behalf_of` carries the RFC
@@ -204,6 +223,71 @@ export declare function extractOnBehalfOfClaim(payloadBstr: Uint8Array): Record<
204
223
  * partially-trusted string.
205
224
  */
206
225
  export declare function extractTraceparentClaim(payloadBstr: Uint8Array): string | null;
226
+ /**
227
+ * Domain-separation prefix the engine applies before verifying an agent's
228
+ * `X-Agent-Signature` at intake: the agent signs the UTF-8 bytes of this
229
+ * prefix followed by the lowercase hex sha256 of the raw request body (the
230
+ * hex string, not the digest bytes). Distinct from the cert proof-of-possession
231
+ * prefix, so one signature cannot be replayed as the other.
232
+ */
233
+ export declare const AGENT_SIGNATURE_CONTEXT = "agledger.agent.sig.v1\n";
234
+ /** An Ed25519 public key in JWK form, as sent in `publicKeyJwk` at cert exchange. */
235
+ export interface AgentPublicKeyJwk {
236
+ kty: 'OKP';
237
+ crv: 'Ed25519';
238
+ /** base64url of the raw 32-byte public key. */
239
+ x: string;
240
+ }
241
+ /**
242
+ * The agent-signature evidence the engine sealed into a chain entry, read from
243
+ * the signed payload. Fields are left `unknown` where the verifier must check
244
+ * their shape itself: a sealed value the engine never writes is a finding, not
245
+ * something to coerce.
246
+ */
247
+ export interface AgentSignatureClaim {
248
+ /** `on_behalf_of.validated === true`: the engine vouched for the identity. */
249
+ validated: boolean;
250
+ /** `on_behalf_of.cert.id`, when a cert is sealed beside the signature. */
251
+ certId: string | null;
252
+ /** `on_behalf_of.cert.thumbprint`: `sha256:<hex>` RFC 7638 thumbprint of the cert's bound key. */
253
+ certThumbprint: string | null;
254
+ alg: unknown;
255
+ signature: unknown;
256
+ contentHash: unknown;
257
+ }
258
+ /**
259
+ * Read `predicate.on_behalf_of.agent_signature` and the cert beside it from a
260
+ * COSE_Sign1 payload bstr. Returns null when the entry carries no agent
261
+ * signature.
262
+ */
263
+ export declare function extractAgentSignatureClaim(payloadBstr: Uint8Array): AgentSignatureClaim | null;
264
+ /**
265
+ * RFC 7638 thumbprint of an Ed25519 JWK in the engine's `sha256:<hex>` form,
266
+ * or null when the value is not an Ed25519 public-key JWK. The members are
267
+ * hashed in the RFC's lexicographic order (`crv`, `kty`, `x`), which is what
268
+ * the engine's thumbprint function produces for an OKP key.
269
+ */
270
+ export declare function ed25519JwkThumbprint(jwk: unknown): string | null;
271
+ /** SPKI DER (base64) for an Ed25519 JWK, or null when it is not one. */
272
+ export declare function ed25519JwkToSpki(jwk: unknown): string | null;
273
+ export type AgentSignatureOutcome = 'ok' | 'invalid' | 'malformed' | 'unsupported';
274
+ /**
275
+ * Verify a sealed agent signature against the cert's Ed25519 key.
276
+ *
277
+ * - `ok`: the signature verifies over `AGENT_SIGNATURE_CONTEXT + <hex>`.
278
+ * - `invalid`: well formed, does not verify under this key.
279
+ * - `malformed`: a shape the engine never writes (alg other than EdDSA, a
280
+ * content hash not `sha256:<hex64>`, a signature that is not 64 bytes of
281
+ * standard base64). Nothing can verify it, which the engine also treats as
282
+ * a break.
283
+ * - `unsupported`: this host cannot compute Ed25519 (an active OpenSSL FIPS
284
+ * provider). NOT verified and NOT tamper evidence.
285
+ *
286
+ * What it proves: the holder of the cert's private key signed that content
287
+ * hash. It does not re-hash a request body; the export carries the hash, not
288
+ * the body.
289
+ */
290
+ export declare function verifyAgentSignature(spkiBase64: string, claim: Pick<AgentSignatureClaim, 'alg' | 'signature' | 'contentHash'>): AgentSignatureOutcome;
207
291
  /**
208
292
  * Decode the predicate object from a COSE_Sign1 payload bstr. The payload IS
209
293
  * the in-toto v1 Statement; the predicate body lives at `payload.predicate`.
@@ -219,9 +303,10 @@ export declare function decodePredicate(payloadBstr: Uint8Array): Record<string,
219
303
  * build-vault-claim.ts). This is the verifier-side mirror.
220
304
  *
221
305
  * Returns null when the row's payload is structurally insufficient (e.g.
222
- * SCHEMA_REGISTERED missing manifestDigest); the caller surfaces null as a
223
- * binding mismatch rather than throwing, so an attacker who zeros out payload
224
- * can't crash the verifier.
306
+ * SCHEMA_REGISTERED missing manifestDigest) or is not a JSON object at all (a
307
+ * nulled or retyped column); the caller surfaces null as a binding mismatch
308
+ * rather than throwing, so an attacker who zeros out payload can't crash the
309
+ * verifier.
225
310
  */
226
311
  export declare function buildPredicateForRow(recordId: string | null, entryType: string, payload: Record<string, unknown>): Record<string, unknown> | null;
227
312
  /**
@@ -239,13 +324,36 @@ export declare function deepEqual(a: unknown, b: unknown): boolean;
239
324
  * signature and the OIDC-actor cross-check.
240
325
  */
241
326
  export declare function stripEnvelopeExtensions(predicate: Record<string, unknown>): Record<string, unknown>;
327
+ /**
328
+ * Whether the envelope extensions a row's payload carries are the ones the
329
+ * entry signed. When a writer puts `on_behalf_of` (an object) or
330
+ * `traceparent` (a W3C v00 string; any other value is dropped) at the top
331
+ * level of the row payload, the engine lifts it into `predicate.on_behalf_of`
332
+ * / `predicate.traceparent`, so a row copy must equal the signed value. The
333
+ * row copy is what a reader of an export or dump sees, and
334
+ * {@link stripEnvelopeExtensions} takes both sides out of the predicate
335
+ * comparison, so without this check a rewritten or added row copy would still
336
+ * verify.
337
+ *
338
+ * Anything else under those keys is ignored, as the engine ignores it: it
339
+ * lifts only an object `on_behalf_of` and a v00 `traceparent`, so a genuine
340
+ * older row holding another shape signed nothing for it.
341
+ *
342
+ * A row without them is not a mismatch: the engine also signs an
343
+ * `on_behalf_of` built from the request's authentication rather than from the
344
+ * payload, and that one never reaches the row payload. Its identity is held to
345
+ * the row's actor columns by the OIDC-actor check instead.
346
+ */
347
+ export declare function envelopeExtensionsMatch(rowPayload: Record<string, unknown>, signedPredicate: Record<string, unknown>): boolean;
242
348
  /** RFC 9162 §2.1.1 leaf hash: SHA-256(0x00 || d). */
243
349
  export declare function rfc9162LeafHash(leafData: Uint8Array): Uint8Array;
244
350
  /** RFC 9162 §2.1.1 internal-node hash: SHA-256(0x01 || left || right). */
245
351
  export declare function rfc9162NodeHash(left: Uint8Array, right: Uint8Array): Uint8Array;
246
352
  /**
247
353
  * Verify a RFC 9162 §2.1.3.2 inclusion proof. Mirrors the engine-side
248
- * implementation; reproduced here so the verifier stays engine-free.
354
+ * implementation; reproduced here so the verifier stays engine-free. False
355
+ * when `leafIndex` or `treeSize` is not a safe integer: the walk halves them,
356
+ * and a fraction, NaN or an unsafe integer would walk some other tree.
249
357
  */
250
358
  export declare function verifyRfc9162Inclusion(leafHashBytes: Uint8Array, leafIndex: number, treeSize: number, path: readonly Uint8Array[], expectedRoot: Uint8Array): boolean;
251
359
  export interface ReceiptInclusionProof {
@@ -275,5 +383,24 @@ export declare function extractReceiptInclusionProof(receiptBytes: Uint8Array):
275
383
  */
276
384
  export type ReceiptVerifyOutcome = 'ok' | 'decode-fail' | 'signature-invalid' | 'root-mismatch' | 'unsupported-algorithm';
277
385
  export declare function verifyReceipt(receiptBytes: Uint8Array, signedStatementBytes: Uint8Array, tsPublicKeyBase64: string): ReceiptVerifyOutcome;
278
- export declare function merkleRoot(leaves: readonly string[]): string;
279
- export declare function verifyInclusion(leafHash: string, leafIndex: number, treeSize: number, path: readonly string[], expectedRoot: string): boolean;
386
+ /**
387
+ * A read-log leaf's `leaf_hash`: hex(SHA-256(0x00 || cose_sign1)), the RFC
388
+ * 9162 leaf hash of the leaf's COSE_Sign1 bytes. It is also the next leaf
389
+ * claim's signed `previous_hash`.
390
+ */
391
+ export declare function orgReadLeafHash(coseSign1: Uint8Array): string;
392
+ /**
393
+ * RFC 9162 §2.1.1 Merkle Tree Hash over leaf hashes already computed with
394
+ * {@link orgReadLeafHash}, as hex. The empty tree is SHA-256(""). A leaf hash
395
+ * that is not 64 lowercase hex characters cannot be a stored `leaf_hash`, so
396
+ * the result is null rather than a root over bytes nobody wrote.
397
+ */
398
+ export declare function orgReadMerkleRoot(leafHashesHex: readonly string[]): string | null;
399
+ /**
400
+ * Verify an org_admin_reads inclusion proof (`GET
401
+ * /v1/audit/org-reads/checkpoints/{id}/proof`): the RFC 9162 §2.1.3.2 audit
402
+ * path walk over hex values. A one-leaf tree has an empty path. False on any
403
+ * value that is not 64 lowercase hex characters, and on a `leafIndex` or
404
+ * `treeSize` that is not a safe integer (a JSON number can be 0.5 or 1e300).
405
+ */
406
+ export declare function verifyOrgReadInclusion(leafHashHex: string, leafIndex: number, treeSize: number, pathHex: readonly string[], expectedRootHex: string): boolean;
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * Mirrors the AGLedger engine-side implementations:
5
5
  * - COSE_Sign1 verify (RFC 9052 §4.4): audit-vault/encoders/cose-sign1.ts
6
- * - Merkle: audit-vault/merkle.ts
6
+ * - RFC 9162 §2.1 Merkle tree, for SCITT Receipts and the org_admin_reads
7
+ * log alike: audit-vault/merkle-rfc9162.ts
7
8
  *
8
9
  * Re-implemented here (not imported from any engine/SDK code) so the verifier
9
10
  * has zero engine dependency, the load-bearing property of an offline
@@ -505,6 +506,44 @@ export function extractChainClaim(protectedBstr) {
505
506
  return null;
506
507
  }
507
508
  }
509
+ const COSE_HEADER_CWT_CLAIMS = 15;
510
+ const AGLEDGER_LABEL_ACTOR = -65539;
511
+ const ACTOR_SUBLABEL_KEY_ID = 1;
512
+ const ACTOR_SUBLABEL_ROLE = 2;
513
+ const ACTOR_SUBLABEL_OWNER_ID = 3;
514
+ /** 16 raw bytes to canonical lowercase-hyphenated UUID; null for any other length. */
515
+ function bytesToUuid(bytes) {
516
+ if (bytes.length !== 16)
517
+ return null;
518
+ const hex = Buffer.from(bytes).toString('hex');
519
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
520
+ }
521
+ export function extractActorClaim(protectedBstr) {
522
+ try {
523
+ const ph = cborDecode(protectedBstr, { useMaps: true });
524
+ const cwt = ph.get(COSE_HEADER_CWT_CLAIMS);
525
+ if (!(cwt instanceof Map))
526
+ return null;
527
+ const actor = cwt.get(AGLEDGER_LABEL_ACTOR);
528
+ if (!(actor instanceof Map))
529
+ return null;
530
+ const keyIdBytes = actor.get(ACTOR_SUBLABEL_KEY_ID);
531
+ const role = actor.get(ACTOR_SUBLABEL_ROLE);
532
+ const ownerIdBytes = actor.get(ACTOR_SUBLABEL_OWNER_ID);
533
+ if (!(keyIdBytes instanceof Uint8Array) || !(ownerIdBytes instanceof Uint8Array))
534
+ return null;
535
+ if (typeof role !== 'string')
536
+ return null;
537
+ const keyId = bytesToUuid(keyIdBytes);
538
+ const ownerId = bytesToUuid(ownerIdBytes);
539
+ if (keyId === null || ownerId === null)
540
+ return null;
541
+ return { key_id: keyId, role, owner_id: ownerId };
542
+ }
543
+ catch {
544
+ return null;
545
+ }
546
+ }
508
547
  // --- Optional envelope extensions (OIDC on-behalf-of, traceparent) ---
509
548
  const TRACEPARENT_REGEX = /^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
510
549
  /**
@@ -552,6 +591,104 @@ export function extractTraceparentClaim(payloadBstr) {
552
591
  return null;
553
592
  }
554
593
  }
594
+ // --- Agent signature (predicate.on_behalf_of.agent_signature) ---
595
+ /**
596
+ * Domain-separation prefix the engine applies before verifying an agent's
597
+ * `X-Agent-Signature` at intake: the agent signs the UTF-8 bytes of this
598
+ * prefix followed by the lowercase hex sha256 of the raw request body (the
599
+ * hex string, not the digest bytes). Distinct from the cert proof-of-possession
600
+ * prefix, so one signature cannot be replayed as the other.
601
+ */
602
+ export const AGENT_SIGNATURE_CONTEXT = 'agledger.agent.sig.v1\n';
603
+ /**
604
+ * Read `predicate.on_behalf_of.agent_signature` and the cert beside it from a
605
+ * COSE_Sign1 payload bstr. Returns null when the entry carries no agent
606
+ * signature.
607
+ */
608
+ export function extractAgentSignatureClaim(payloadBstr) {
609
+ const obo = extractOnBehalfOfClaim(payloadBstr);
610
+ if (obo === null)
611
+ return null;
612
+ const sig = obo['agent_signature'];
613
+ if (sig === undefined || sig === null)
614
+ return null;
615
+ const sigObj = typeof sig === 'object' && !Array.isArray(sig) ? sig : {};
616
+ const cert = obo['cert'];
617
+ const certObj = cert !== null && typeof cert === 'object' && !Array.isArray(cert)
618
+ ? cert
619
+ : {};
620
+ return {
621
+ validated: obo['validated'] === true,
622
+ certId: typeof certObj['id'] === 'string' ? certObj['id'] : null,
623
+ certThumbprint: typeof certObj['thumbprint'] === 'string' ? certObj['thumbprint'] : null,
624
+ alg: sigObj['alg'],
625
+ signature: sigObj['signature'],
626
+ contentHash: sigObj['content_hash'],
627
+ };
628
+ }
629
+ const BASE64URL_32_BYTES = /^[A-Za-z0-9_-]{43}$/;
630
+ /**
631
+ * RFC 7638 thumbprint of an Ed25519 JWK in the engine's `sha256:<hex>` form,
632
+ * or null when the value is not an Ed25519 public-key JWK. The members are
633
+ * hashed in the RFC's lexicographic order (`crv`, `kty`, `x`), which is what
634
+ * the engine's thumbprint function produces for an OKP key.
635
+ */
636
+ export function ed25519JwkThumbprint(jwk) {
637
+ if (jwk === null || typeof jwk !== 'object' || Array.isArray(jwk))
638
+ return null;
639
+ const { kty, crv, x } = jwk;
640
+ if (kty !== 'OKP' || crv !== 'Ed25519' || typeof x !== 'string' || !BASE64URL_32_BYTES.test(x)) {
641
+ return null;
642
+ }
643
+ if (Buffer.from(x, 'base64url').length !== 32)
644
+ return null;
645
+ return `sha256:${sha256HexString(JSON.stringify({ crv, kty, x }))}`;
646
+ }
647
+ /** SPKI DER (base64) for an Ed25519 JWK, or null when it is not one. */
648
+ export function ed25519JwkToSpki(jwk) {
649
+ if (ed25519JwkThumbprint(jwk) === null)
650
+ return null;
651
+ const raw = Buffer.from(jwk.x, 'base64url');
652
+ return Buffer.concat([ED25519_SPKI_PREFIX, raw]).toString('base64');
653
+ }
654
+ const CONTENT_HASH_PATTERN = /^sha256:([0-9a-f]{64})$/;
655
+ const STANDARD_BASE64_64_BYTES = /^[A-Za-z0-9+/]{86}(==)?$/;
656
+ /**
657
+ * Verify a sealed agent signature against the cert's Ed25519 key.
658
+ *
659
+ * - `ok`: the signature verifies over `AGENT_SIGNATURE_CONTEXT + <hex>`.
660
+ * - `invalid`: well formed, does not verify under this key.
661
+ * - `malformed`: a shape the engine never writes (alg other than EdDSA, a
662
+ * content hash not `sha256:<hex64>`, a signature that is not 64 bytes of
663
+ * standard base64). Nothing can verify it, which the engine also treats as
664
+ * a break.
665
+ * - `unsupported`: this host cannot compute Ed25519 (an active OpenSSL FIPS
666
+ * provider). NOT verified and NOT tamper evidence.
667
+ *
668
+ * What it proves: the holder of the cert's private key signed that content
669
+ * hash. It does not re-hash a request body; the export carries the hash, not
670
+ * the body.
671
+ */
672
+ export function verifyAgentSignature(spkiBase64, claim) {
673
+ if (claim.alg !== 'EdDSA')
674
+ return 'malformed';
675
+ if (typeof claim.contentHash !== 'string')
676
+ return 'malformed';
677
+ const hashMatch = CONTENT_HASH_PATTERN.exec(claim.contentHash);
678
+ if (!hashMatch)
679
+ return 'malformed';
680
+ if (typeof claim.signature !== 'string' || !STANDARD_BASE64_64_BYTES.test(claim.signature)) {
681
+ return 'malformed';
682
+ }
683
+ const sigBytes = Buffer.from(claim.signature, 'base64');
684
+ if (sigBytes.length !== 64)
685
+ return 'malformed';
686
+ const ed25519 = algorithmByName('Ed25519');
687
+ if (ed25519 === null || !runtimeCanCompute(ed25519))
688
+ return 'unsupported';
689
+ const input = Buffer.from(`${AGENT_SIGNATURE_CONTEXT}${hashMatch[1]}`, 'utf8');
690
+ return verifyEd25519Bytes(spkiBase64, input, sigBytes) ? 'ok' : 'invalid';
691
+ }
555
692
  // --- in-toto v1 predicate extraction + binding-integrity projection ---
556
693
  /**
557
694
  * Decode the predicate object from a COSE_Sign1 payload bstr. The payload IS
@@ -598,11 +735,14 @@ const RECORD_STATE_RESERVED_KEYS = new Set([
598
735
  * build-vault-claim.ts). This is the verifier-side mirror.
599
736
  *
600
737
  * Returns null when the row's payload is structurally insufficient (e.g.
601
- * SCHEMA_REGISTERED missing manifestDigest); the caller surfaces null as a
602
- * binding mismatch rather than throwing, so an attacker who zeros out payload
603
- * can't crash the verifier.
738
+ * SCHEMA_REGISTERED missing manifestDigest) or is not a JSON object at all (a
739
+ * nulled or retyped column); the caller surfaces null as a binding mismatch
740
+ * rather than throwing, so an attacker who zeros out payload can't crash the
741
+ * verifier.
604
742
  */
605
743
  export function buildPredicateForRow(recordId, entryType, payload) {
744
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload))
745
+ return null;
606
746
  if (SCHEMA_EVENT_TYPES.has(entryType)) {
607
747
  return buildSchemaEventPredicateForRow(entryType, payload);
608
748
  }
@@ -732,6 +872,38 @@ export function stripEnvelopeExtensions(predicate) {
732
872
  }
733
873
  return out;
734
874
  }
875
+ /**
876
+ * Whether the envelope extensions a row's payload carries are the ones the
877
+ * entry signed. When a writer puts `on_behalf_of` (an object) or
878
+ * `traceparent` (a W3C v00 string; any other value is dropped) at the top
879
+ * level of the row payload, the engine lifts it into `predicate.on_behalf_of`
880
+ * / `predicate.traceparent`, so a row copy must equal the signed value. The
881
+ * row copy is what a reader of an export or dump sees, and
882
+ * {@link stripEnvelopeExtensions} takes both sides out of the predicate
883
+ * comparison, so without this check a rewritten or added row copy would still
884
+ * verify.
885
+ *
886
+ * Anything else under those keys is ignored, as the engine ignores it: it
887
+ * lifts only an object `on_behalf_of` and a v00 `traceparent`, so a genuine
888
+ * older row holding another shape signed nothing for it.
889
+ *
890
+ * A row without them is not a mismatch: the engine also signs an
891
+ * `on_behalf_of` built from the request's authentication rather than from the
892
+ * payload, and that one never reaches the row payload. Its identity is held to
893
+ * the row's actor columns by the OIDC-actor check instead.
894
+ */
895
+ export function envelopeExtensionsMatch(rowPayload, signedPredicate) {
896
+ const obo = rowPayload['on_behalf_of'];
897
+ if (obo !== null && typeof obo === 'object' && !Array.isArray(obo)) {
898
+ if (!deepEqual(obo, signedPredicate['on_behalf_of']))
899
+ return false;
900
+ }
901
+ const tp = rowPayload['traceparent'];
902
+ if (typeof tp === 'string' && TRACEPARENT_REGEX.test(tp) && tp !== signedPredicate['traceparent']) {
903
+ return false;
904
+ }
905
+ return true;
906
+ }
735
907
  // --- RFC 9162 Merkle (SCITT Receipt verifiable data structure) ---
736
908
  const LEAF_PREFIX = new Uint8Array([0x00]);
737
909
  const NODE_PREFIX = new Uint8Array([0x01]);
@@ -766,13 +938,19 @@ export function rfc9162NodeHash(left, right) {
766
938
  }
767
939
  /**
768
940
  * Verify a RFC 9162 §2.1.3.2 inclusion proof. Mirrors the engine-side
769
- * implementation; reproduced here so the verifier stays engine-free.
941
+ * implementation; reproduced here so the verifier stays engine-free. False
942
+ * when `leafIndex` or `treeSize` is not a safe integer: the walk halves them,
943
+ * and a fraction, NaN or an unsafe integer would walk some other tree.
770
944
  */
771
945
  export function verifyRfc9162Inclusion(leafHashBytes, leafIndex, treeSize, path, expectedRoot) {
946
+ if (!Number.isSafeInteger(leafIndex) || !Number.isSafeInteger(treeSize))
947
+ return false;
772
948
  if (leafIndex < 0 || leafIndex >= treeSize)
773
949
  return false;
774
950
  if (treeSize === 1)
775
951
  return path.length === 0 && bytesEqual(leafHashBytes, expectedRoot);
952
+ // Arithmetic halving rather than `>>>`, which would wrap a size past 2^32.
953
+ const half = (n) => Math.floor(n / 2);
776
954
  let fn = leafIndex;
777
955
  let sn = treeSize - 1;
778
956
  let r = leafHashBytes;
@@ -781,18 +959,18 @@ export function verifyRfc9162Inclusion(leafHashBytes, leafIndex, treeSize, path,
781
959
  if (sn === 0)
782
960
  return false;
783
961
  const p = path[i];
784
- if ((fn & 1) === 1 || fn === sn) {
962
+ if (fn % 2 === 1 || fn === sn) {
785
963
  r = rfc9162NodeHash(p, r);
786
- while ((fn & 1) === 0 && fn !== 0) {
787
- fn >>>= 1;
788
- sn >>>= 1;
964
+ while (fn % 2 === 0 && fn !== 0) {
965
+ fn = half(fn);
966
+ sn = half(sn);
789
967
  }
790
968
  }
791
969
  else {
792
970
  r = rfc9162NodeHash(r, p);
793
971
  }
794
- fn >>>= 1;
795
- sn >>>= 1;
972
+ fn = half(fn);
973
+ sn = half(sn);
796
974
  if (sn === 0) {
797
975
  i += 1;
798
976
  break;
@@ -873,43 +1051,77 @@ export function verifyReceipt(receiptBytes, signedStatementBytes, tsPublicKeyBas
873
1051
  const ok = verifyRfc9162Inclusion(leaf, vdp.leafIndex, vdp.treeSize, vdp.auditPath, signedRoot);
874
1052
  return ok ? 'ok' : 'root-mismatch';
875
1053
  }
876
- // --- Merkle tree (org_admin_reads) ---
1054
+ // --- Merkle tree (org_admin_reads), RFC 9162 §2.1 over hex leaf hashes ---
877
1055
  /**
878
- * Tree shape mirrors the engine's merkle.ts: balance-by-duplicating-last-leaf,
879
- * sha256(hex(left) || hex(right)) over hex strings, no RFC 6962 leaf prefix.
1056
+ * The org_admin_reads log is the same RFC 9162 §2.1 SHA-256 tree the Receipts
1057
+ * above use. Its rows store and serve each hash as lowercase hex, so these are
1058
+ * hex forms of the byte functions: every hex string is decoded to the 32 bytes
1059
+ * it denotes before hashing, never hashed as text.
880
1060
  */
881
- function hashPair(left, right) {
882
- return hash('sha256', left + right, 'hex');
883
- }
884
- export function merkleRoot(leaves) {
885
- if (leaves.length === 0)
886
- return hash('sha256', '', 'hex');
887
- let level = [...leaves];
888
- while (level.length > 1) {
889
- const next = [];
890
- for (let i = 0; i < level.length; i += 2) {
891
- const left = level[i] ?? '';
892
- const right = level[i + 1] ?? left;
893
- next.push(hashPair(left, right));
894
- }
895
- level = next;
1061
+ const HEX_32_BYTES = /^[0-9a-f]{64}$/;
1062
+ function hexToBytes(hex) {
1063
+ return HEX_32_BYTES.test(hex) ? new Uint8Array(Buffer.from(hex, 'hex')) : null;
1064
+ }
1065
+ function bytesToHex(bytes) {
1066
+ return Buffer.from(bytes).toString('hex');
1067
+ }
1068
+ /**
1069
+ * A read-log leaf's `leaf_hash`: hex(SHA-256(0x00 || cose_sign1)), the RFC
1070
+ * 9162 leaf hash of the leaf's COSE_Sign1 bytes. It is also the next leaf
1071
+ * claim's signed `previous_hash`.
1072
+ */
1073
+ export function orgReadLeafHash(coseSign1) {
1074
+ return bytesToHex(rfc9162LeafHash(coseSign1));
1075
+ }
1076
+ /** Largest power of two strictly below n (n >= 2), the RFC 9162 §2.1.1 split point. */
1077
+ function splitPoint(n) {
1078
+ let k = 1;
1079
+ while (k * 2 < n)
1080
+ k *= 2;
1081
+ return k;
1082
+ }
1083
+ function rootOfLeafHashes(leafHashes, lo, hi) {
1084
+ if (hi - lo === 1)
1085
+ return leafHashes[lo];
1086
+ const k = splitPoint(hi - lo);
1087
+ return rfc9162NodeHash(rootOfLeafHashes(leafHashes, lo, lo + k), rootOfLeafHashes(leafHashes, lo + k, hi));
1088
+ }
1089
+ /**
1090
+ * RFC 9162 §2.1.1 Merkle Tree Hash over leaf hashes already computed with
1091
+ * {@link orgReadLeafHash}, as hex. The empty tree is SHA-256(""). A leaf hash
1092
+ * that is not 64 lowercase hex characters cannot be a stored `leaf_hash`, so
1093
+ * the result is null rather than a root over bytes nobody wrote.
1094
+ */
1095
+ export function orgReadMerkleRoot(leafHashesHex) {
1096
+ if (leafHashesHex.length === 0)
1097
+ return sha256Hex(new Uint8Array(0));
1098
+ const leaves = [];
1099
+ for (const h of leafHashesHex) {
1100
+ const b = hexToBytes(h);
1101
+ if (b === null)
1102
+ return null;
1103
+ leaves.push(b);
896
1104
  }
897
- return level[0] ?? '';
1105
+ return bytesToHex(rootOfLeafHashes(leaves, 0, leaves.length));
898
1106
  }
899
- export function verifyInclusion(leafHash, leafIndex, treeSize, path, expectedRoot) {
900
- if (leafIndex < 0 || leafIndex >= treeSize)
1107
+ /**
1108
+ * Verify an org_admin_reads inclusion proof (`GET
1109
+ * /v1/audit/org-reads/checkpoints/{id}/proof`): the RFC 9162 §2.1.3.2 audit
1110
+ * path walk over hex values. A one-leaf tree has an empty path. False on any
1111
+ * value that is not 64 lowercase hex characters, and on a `leafIndex` or
1112
+ * `treeSize` that is not a safe integer (a JSON number can be 0.5 or 1e300).
1113
+ */
1114
+ export function verifyOrgReadInclusion(leafHashHex, leafIndex, treeSize, pathHex, expectedRootHex) {
1115
+ const leaf = hexToBytes(leafHashHex);
1116
+ const root = hexToBytes(expectedRootHex);
1117
+ if (leaf === null || root === null)
901
1118
  return false;
902
- let current = leafHash;
903
- let index = leafIndex;
904
- let levelSize = treeSize;
905
- let pathPos = 0;
906
- while (levelSize > 1) {
907
- const sibling = path[pathPos++];
908
- if (sibling === undefined)
1119
+ const path = [];
1120
+ for (const p of pathHex) {
1121
+ const b = hexToBytes(p);
1122
+ if (b === null)
909
1123
  return false;
910
- current = index % 2 === 0 ? hashPair(current, sibling) : hashPair(sibling, current);
911
- index = Math.floor(index / 2);
912
- levelSize = Math.ceil(levelSize / 2);
1124
+ path.push(b);
913
1125
  }
914
- return current === expectedRoot && pathPos === path.length;
1126
+ return verifyRfc9162Inclusion(leaf, leafIndex, treeSize, path, root);
915
1127
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@agledger/verify-core",
3
- "version": "1.4.2",
4
- "description": "Shared offline verification core for AGLedger audit chains: COSE_Sign1 (RFC 9052) decode/verify, Ed25519 + ES256, hash-chain walk, Merkle proofs, and the canonical failure taxonomy. One dependency (cborg); no network. The single source of truth the SDK, CLI, MCP server, and @agledger/verify all build on.",
3
+ "version": "2.0.0",
4
+ "description": "Shared offline verification core for AGLedger audit chains: COSE_Sign1 (RFC 9052) decode/verify, Ed25519 + ES256, hash-chain walk, vault key-statement trust walk, RFC 9162 Merkle proofs, and the canonical failure taxonomy. One dependency (cborg); no network. The single source of truth the SDK, CLI, MCP server, and @agledger/verify all build on.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
7
7
  "engines": {
@@ -34,7 +34,7 @@
34
34
  "prepublishOnly": "npm run build && npm run lint:pkg"
35
35
  },
36
36
  "dependencies": {
37
- "cborg": "6.1.1"
37
+ "cborg": "6.1.2"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@arethetypeswrong/cli": "^0.18.3",