@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.
@@ -1,22 +1,25 @@
1
1
  /**
2
2
  * Self-contained crypto + canonicalization primitives.
3
3
  *
4
- * Mirrors the AGLedger engine-side implementations:
5
- * - COSE_Sign1 verify (RFC 9052 §4.4): audit-vault/encoders/cose-sign1.ts
4
+ * Mirrors what the AGLedger Server does when it signs and chains entries:
5
+ * - COSE_Sign1 verify (RFC 9052 §4.4), the envelope the Server signs
6
6
  * - RFC 9162 §2.1 Merkle tree, for SCITT Receipts and the org_admin_reads
7
- * log alike: audit-vault/merkle-rfc9162.ts
7
+ * log alike
8
8
  *
9
- * Re-implemented here (not imported from any engine/SDK code) so the verifier
10
- * has zero engine dependency, the load-bearing property of an offline
11
- * auditor: the engine could be compromised and this still verifies correctly.
9
+ * Re-implemented here (not imported from any Server or SDK code) so the
10
+ * verifier has zero Server dependency, the load-bearing property of an offline
11
+ * auditor: it runs no Server code, so a Server that holds no key you
12
+ * trust cannot make it return a `trusted` verdict: that needs `trustAnchors`
13
+ * linking the signing keys to a key you pinned.
12
14
  * The only runtime dependency is `cborg`, a general-purpose CBOR library (not
13
15
  * AGLedger code), and Node's built-in `crypto`. No network, no filesystem.
14
16
  *
15
- * If the engine-side primitives ever change shape, both implementations must be
16
- * updated together; the conformance corpus (real engine output) is the
17
+ * If the Server-side primitives ever change shape, both implementations must be
18
+ * updated together; the conformance corpus (real Server output) is the
17
19
  * regression net that catches divergence.
18
20
  */
19
21
  import { createPublicKey, getFips, hash, verify } from 'node:crypto';
22
+ import { STRICT_CBOR_DECODE } from './cbor-strict.js';
20
23
  import { decode as cborDecode, encode as cborEncode, rfc8949EncodeOptions } from 'cborg';
21
24
  // --- SHA-256 ---
22
25
  /** sha256 over arbitrary bytes -> lowercase hex. */
@@ -139,11 +142,11 @@ export function resolveKeyAlgorithm(publicKeyBase64) {
139
142
  /**
140
143
  * Verify an Ed25519 signature over raw bytes.
141
144
  * `publicKeyBase64` is the SPKI DER public key, base64-encoded
142
- * (matches the engine's vault_signing_keys.public_key column).
145
+ * (the shape the Server's key registry publishes).
143
146
  *
144
147
  * Refuses non-Ed25519 keys. Node's `verify(null, ...)` silently falls back to
145
148
  * ECDSA/SHA-256 for EC keys, which would accept a signature no conformant
146
- * EdDSA verifier accepts (the engine guards the signing side the same way),
149
+ * EdDSA verifier accepts (the Server guards the signing side the same way),
147
150
  * so the key type is asserted before any crypto runs.
148
151
  *
149
152
  * CAUTION for direct callers: as with `verifySignatureBytes`, `false` conflates
@@ -175,9 +178,9 @@ export function verifyEd25519Bytes(publicKeyBase64, input, signature) {
175
178
  * `runtimeCanCompute`). Collapsing those two into one boolean is what made a
176
179
  * FIPS-locked host report an intact Ed25519 chain as forged.
177
180
  *
178
- * ES256 mirrors the engine's `verifyWithAlgorithm`: SHA-256 digest passed
181
+ * ES256 mirrors how the Server verifies it: SHA-256 digest passed
179
182
  * positionally, `dsaEncoding: 'ieee-p1363'` (COSE raw r||s, 64 bytes). The
180
- * engine normalizes to low-S at sign time but, like the engine's verifier,
183
+ * Server normalizes to low-S at sign time but, like the Server's verifier,
181
184
  * high-S is accepted here: ECDSA malleability changes the envelope bytes,
182
185
  * which the hash-link layer already pins.
183
186
  */
@@ -346,9 +349,9 @@ function isFipsActive() {
346
349
  * the upgrade-vs-forgery distinction use `resolveKeyAlgorithm` first, as
347
350
  * `verifyCoseSign1` does).
348
351
  *
349
- * ES256 mirrors the engine's `verifyWithAlgorithm`: SHA-256 digest passed
352
+ * ES256 mirrors how the Server verifies it: SHA-256 digest passed
350
353
  * positionally, `dsaEncoding: 'ieee-p1363'` (COSE raw r||s, 64 bytes). The
351
- * engine normalizes to low-S at sign time but, like the engine's verifier,
354
+ * Server normalizes to low-S at sign time but, like the Server's verifier,
352
355
  * high-S is accepted here: ECDSA malleability changes the envelope bytes,
353
356
  * which the hash-link layer already pins.
354
357
  *
@@ -379,15 +382,16 @@ const SIG_STRUCTURE_CONTEXT = 'Signature1';
379
382
  const COSE_HEADER_ALG = 1;
380
383
  const COSE_HEADER_KID = 4;
381
384
  export function decodeCoseSign1(bytes) {
382
- // Tag 18 is required (short-form 0xd2, matching the engine's encoder).
385
+ // Tag 18 is required (short-form 0xd2, matching the Server's encoder).
383
386
  // cborg's tag handler unwraps tag 18 but also returns an UNTAGGED 4-element
384
- // array verbatim, and the engine rejects untagged envelopes: producer and
387
+ // array verbatim, and the Server rejects untagged envelopes: producer and
385
388
  // offline verifier must agree on what a COSE_Sign1 is, so gate on the
386
- // leading byte the same way the engine's decoder does.
389
+ // leading byte the same way the Server's decoder does.
387
390
  if (bytes.length === 0 || bytes[0] !== COSE_SIGN1_TAG_PREFIX)
388
391
  return null;
389
392
  try {
390
393
  const decoded = cborDecode(bytes, {
394
+ ...STRICT_CBOR_DECODE,
391
395
  useMaps: true,
392
396
  tags: { [COSE_SIGN1_TAG]: (control) => control() },
393
397
  });
@@ -449,7 +453,7 @@ export function verifyCoseSign1(coseSign1, publicKeyBase64) {
449
453
  /** Decode the protected header's `alg` (label 1); null when absent or not an int. */
450
454
  function extractHeaderAlg(protectedBstr) {
451
455
  try {
452
- const ph = cborDecode(protectedBstr, { useMaps: true });
456
+ const ph = cborDecode(protectedBstr, { ...STRICT_CBOR_DECODE, useMaps: true });
453
457
  const alg = ph.get(COSE_HEADER_ALG);
454
458
  if (typeof alg === 'number' && Number.isInteger(alg))
455
459
  return alg;
@@ -463,14 +467,14 @@ function extractHeaderAlg(protectedBstr) {
463
467
  }
464
468
  /**
465
469
  * Extract the signature-covered `kid` (protected header label 4) as lowercase
466
- * hex, matching the engine's `vault_signing_keys.key_id` shape. Returns null
470
+ * hex, matching the key id shape the Server's key registry uses. Returns null
467
471
  * when absent or malformed. The caller cross-checks it against the row's
468
472
  * `signingKeyId` column: the column is a denormalized convenience, the kid is
469
- * signed, so a rewritten column surfaces as drift (engine mirror: signing_key_drift).
473
+ * signed, so a rewritten column surfaces as drift (Server mirror: signing_key_drift).
470
474
  */
471
475
  export function extractKid(protectedBstr) {
472
476
  try {
473
- const ph = cborDecode(protectedBstr, { useMaps: true });
477
+ const ph = cborDecode(protectedBstr, { ...STRICT_CBOR_DECODE, useMaps: true });
474
478
  const kid = ph.get(COSE_HEADER_KID);
475
479
  if (!(kid instanceof Uint8Array))
476
480
  return null;
@@ -485,7 +489,7 @@ const CHAIN_SUBLABEL_POSITION = 1;
485
489
  const CHAIN_SUBLABEL_PREVIOUS_HASH = 2;
486
490
  export function extractChainClaim(protectedBstr) {
487
491
  try {
488
- const ph = cborDecode(protectedBstr, { useMaps: true });
492
+ const ph = cborDecode(protectedBstr, { ...STRICT_CBOR_DECODE, useMaps: true });
489
493
  const chain = ph.get(AGLEDGER_LABEL_CHAIN);
490
494
  if (!(chain instanceof Map))
491
495
  return null;
@@ -520,7 +524,7 @@ function bytesToUuid(bytes) {
520
524
  }
521
525
  export function extractActorClaim(protectedBstr) {
522
526
  try {
523
- const ph = cborDecode(protectedBstr, { useMaps: true });
527
+ const ph = cborDecode(protectedBstr, { ...STRICT_CBOR_DECODE, useMaps: true });
524
528
  const cwt = ph.get(COSE_HEADER_CWT_CLAIMS);
525
529
  if (!(cwt instanceof Map))
526
530
  return null;
@@ -553,7 +557,7 @@ const TRACEPARENT_REGEX = /^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
553
557
  */
554
558
  export function extractOnBehalfOfClaim(payloadBstr) {
555
559
  try {
556
- const stmt = cborDecode(payloadBstr, { useMaps: false });
560
+ const stmt = cborDecode(payloadBstr, { ...STRICT_CBOR_DECODE, useMaps: false });
557
561
  const predicate = stmt['predicate'];
558
562
  if (predicate === null || typeof predicate !== 'object' || Array.isArray(predicate)) {
559
563
  return null;
@@ -577,7 +581,7 @@ export function extractOnBehalfOfClaim(payloadBstr) {
577
581
  */
578
582
  export function extractTraceparentClaim(payloadBstr) {
579
583
  try {
580
- const stmt = cborDecode(payloadBstr, { useMaps: false });
584
+ const stmt = cborDecode(payloadBstr, { ...STRICT_CBOR_DECODE, useMaps: false });
581
585
  const predicate = stmt['predicate'];
582
586
  if (predicate === null || typeof predicate !== 'object' || Array.isArray(predicate)) {
583
587
  return null;
@@ -593,7 +597,7 @@ export function extractTraceparentClaim(payloadBstr) {
593
597
  }
594
598
  // --- Agent signature (predicate.on_behalf_of.agent_signature) ---
595
599
  /**
596
- * Domain-separation prefix the engine applies before verifying an agent's
600
+ * Domain-separation prefix the Server applies before verifying an agent's
597
601
  * `X-Agent-Signature` at intake: the agent signs the UTF-8 bytes of this
598
602
  * prefix followed by the lowercase hex sha256 of the raw request body (the
599
603
  * hex string, not the digest bytes). Distinct from the cert proof-of-possession
@@ -628,10 +632,10 @@ export function extractAgentSignatureClaim(payloadBstr) {
628
632
  }
629
633
  const BASE64URL_32_BYTES = /^[A-Za-z0-9_-]{43}$/;
630
634
  /**
631
- * RFC 7638 thumbprint of an Ed25519 JWK in the engine's `sha256:<hex>` form,
635
+ * RFC 7638 thumbprint of an Ed25519 JWK in the Server's `sha256:<hex>` form,
632
636
  * or null when the value is not an Ed25519 public-key JWK. The members are
633
637
  * hashed in the RFC's lexicographic order (`crv`, `kty`, `x`), which is what
634
- * the engine's thumbprint function produces for an OKP key.
638
+ * the Server's thumbprint function produces for an OKP key.
635
639
  */
636
640
  export function ed25519JwkThumbprint(jwk) {
637
641
  if (jwk === null || typeof jwk !== 'object' || Array.isArray(jwk))
@@ -658,9 +662,9 @@ const STANDARD_BASE64_64_BYTES = /^[A-Za-z0-9+/]{86}(==)?$/;
658
662
  *
659
663
  * - `ok`: the signature verifies over `AGENT_SIGNATURE_CONTEXT + <hex>`.
660
664
  * - `invalid`: well formed, does not verify under this key.
661
- * - `malformed`: a shape the engine never writes (alg other than EdDSA, a
665
+ * - `malformed`: a shape the Server never writes (alg other than EdDSA, a
662
666
  * 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
667
+ * standard base64). Nothing can verify it, which the Server also treats as
664
668
  * a break.
665
669
  * - `unsupported`: this host cannot compute Ed25519 (an active OpenSSL FIPS
666
670
  * provider). NOT verified and NOT tamper evidence.
@@ -694,13 +698,13 @@ export function verifyAgentSignature(spkiBase64, claim) {
694
698
  * Decode the predicate object from a COSE_Sign1 payload bstr. The payload IS
695
699
  * the in-toto v1 Statement; the predicate body lives at `payload.predicate`.
696
700
  * Returns null on any decode failure. Used by the binding-integrity check; the
697
- * row's denormalised `payload` jsonb is a convenience view projected from this
701
+ * entry's readable `payload` is a convenience view projected from this
698
702
  * predicate at write time; if the view was altered after signing,
699
703
  * `buildPredicateForRow(...) !== decodePredicate(...)`.
700
704
  */
701
705
  export function decodePredicate(payloadBstr) {
702
706
  try {
703
- const stmt = cborDecode(payloadBstr, { useMaps: false });
707
+ const stmt = cborDecode(payloadBstr, { ...STRICT_CBOR_DECODE, useMaps: false });
704
708
  const predicate = stmt['predicate'];
705
709
  if (predicate === null || typeof predicate !== 'object' || Array.isArray(predicate)) {
706
710
  return null;
@@ -731,8 +735,7 @@ const RECORD_STATE_RESERVED_KEYS = new Set([
731
735
  ]);
732
736
  /**
733
737
  * Re-project (record_id, entry_type, payload) -> predicate body using the SAME
734
- * logic the engine uses at write time (engine-side: audit-vault/
735
- * build-vault-claim.ts). This is the verifier-side mirror.
738
+ * logic the Server uses at write time. This is the verifier-side mirror.
736
739
  *
737
740
  * Returns null when the row's payload is structurally insufficient (e.g.
738
741
  * SCHEMA_REGISTERED missing manifestDigest) or is not a JSON object at all (a
@@ -858,7 +861,7 @@ export function deepEqual(a, b) {
858
861
  /**
859
862
  * Strip envelope-level sibling fields (`on_behalf_of`, `traceparent`) from a
860
863
  * decoded predicate. They ride alongside per-kind predicate fields on the wire
861
- * but the engine's `buildPredicateOnly` (and our `buildPredicateForRow`
864
+ * but the Server's own predicate builder (and our `buildPredicateForRow`
862
865
  * mirror) exclude them from the rebuilt predicate. Stripping here makes the
863
866
  * two shapes deep-equalable; envelope-level integrity is covered by the
864
867
  * signature and the OIDC-actor cross-check.
@@ -876,32 +879,43 @@ export function stripEnvelopeExtensions(predicate) {
876
879
  * Whether the envelope extensions a row's payload carries are the ones the
877
880
  * entry signed. When a writer puts `on_behalf_of` (an object) or
878
881
  * `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`
882
+ * level of the row payload, the Server lifts it into `predicate.on_behalf_of`
880
883
  * / `predicate.traceparent`, so a row copy must equal the signed value. The
881
884
  * row copy is what a reader of an export or dump sees, and
882
885
  * {@link stripEnvelopeExtensions} takes both sides out of the predicate
883
886
  * comparison, so without this check a rewritten or added row copy would still
884
887
  * verify.
885
888
  *
886
- * Anything else under those keys is ignored, as the engine ignores it: it
889
+ * Anything else under those keys is ignored, as the Server ignores it: it
887
890
  * lifts only an object `on_behalf_of` and a v00 `traceparent`, so a genuine
888
891
  * older row holding another shape signed nothing for it.
889
892
  *
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.
893
+ * `projected` says whether the payload is one the Server fills from the
894
+ * signed predicate. An export entry's is: the Server writes every
895
+ * `on_behalf_of` and v00 `traceparent` the entry signed into it, including an
896
+ * `on_behalf_of` built from the request's authentication, so a signed one the
897
+ * payload lacks was deleted after export. A vault row's payload never holds
898
+ * them (the Server keeps them only inside the signed envelope), so on a dump
899
+ * a row without them is not a mismatch, and the identity is held to the row's
900
+ * actor columns by the OIDC-actor check instead.
894
901
  */
895
- export function envelopeExtensionsMatch(rowPayload, signedPredicate) {
902
+ export function envelopeExtensionsMatch(rowPayload, signedPredicate, projected = false) {
896
903
  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
- }
904
+ const rowObo = obo !== null && typeof obo === 'object' && !Array.isArray(obo) ? obo : undefined;
905
+ const signedOboRaw = signedPredicate['on_behalf_of'];
906
+ const signedObo = signedOboRaw !== null && typeof signedOboRaw === 'object' && !Array.isArray(signedOboRaw) ? signedOboRaw : undefined;
907
+ if (rowObo !== undefined && !deepEqual(rowObo, signedPredicate['on_behalf_of']))
908
+ return false;
909
+ if (projected && signedObo !== undefined && rowObo === undefined)
910
+ return false;
901
911
  const tp = rowPayload['traceparent'];
902
- if (typeof tp === 'string' && TRACEPARENT_REGEX.test(tp) && tp !== signedPredicate['traceparent']) {
912
+ const rowTp = typeof tp === 'string' && TRACEPARENT_REGEX.test(tp) ? tp : undefined;
913
+ const signedTpRaw = signedPredicate['traceparent'];
914
+ const signedTp = typeof signedTpRaw === 'string' && TRACEPARENT_REGEX.test(signedTpRaw) ? signedTpRaw : undefined;
915
+ if (rowTp !== undefined && rowTp !== signedPredicate['traceparent'])
916
+ return false;
917
+ if (projected && signedTp !== undefined && rowTp === undefined)
903
918
  return false;
904
- }
905
919
  return true;
906
920
  }
907
921
  // --- RFC 9162 Merkle (SCITT Receipt verifiable data structure) ---
@@ -937,8 +951,8 @@ export function rfc9162NodeHash(left, right) {
937
951
  return sha256Bytes(concat(NODE_PREFIX, left, right));
938
952
  }
939
953
  /**
940
- * Verify a RFC 9162 §2.1.3.2 inclusion proof. Mirrors the engine-side
941
- * implementation; reproduced here so the verifier stays engine-free. False
954
+ * Verify a RFC 9162 §2.1.3.2 inclusion proof. Mirrors the Server-side
955
+ * implementation; reproduced here so the verifier stays Server-free. False
942
956
  * when `leafIndex` or `treeSize` is not a safe integer: the walk halves them,
943
957
  * and a fraction, NaN or an unsafe integer would walk some other tree.
944
958
  */
@@ -992,6 +1006,7 @@ const VDP_INCLUSION_PROOF_KEY = -1;
992
1006
  export function extractReceiptInclusionProof(receiptBytes) {
993
1007
  try {
994
1008
  const decoded = cborDecode(receiptBytes, {
1009
+ ...STRICT_CBOR_DECODE,
995
1010
  useMaps: true,
996
1011
  tags: { [COSE_SIGN1_TAG]: (control) => control() },
997
1012
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@agledger/verify-core",
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.",
3
+ "version": "2.2.0",
4
+ "description": "Shared offline verification core for AGLedger audit chains: COSE_Sign1 (RFC 9052), Ed25519 and ES256, hash-chain walk, key-statement trust walk, RFC 9162 Merkle proofs, canonical failure taxonomy. One dependency (cborg); no network. Patent pending.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
7
7
  "engines": {
@@ -24,9 +24,10 @@
24
24
  "scripts": {
25
25
  "prebuild": "rm -rf dist",
26
26
  "build": "tsc",
27
+ "prepack": "node -e \"fs.existsSync('tsconfig.json')&&child_process.execSync('npm run build',{stdio:'inherit'})\"",
27
28
  "typecheck": "tsc --noEmit",
28
29
  "clean": "rm -rf dist *.tsbuildinfo",
29
- "lint": "tsc --noEmit",
30
+ "lint": "oxlint --type-aware .",
30
31
  "test": "vitest run",
31
32
  "deps:lag": "node scripts/dep-lag.mjs",
32
33
  "deps:refresh": "npm update && node scripts/dep-lag.mjs",
@@ -34,11 +35,13 @@
34
35
  "prepublishOnly": "npm run build && npm run lint:pkg"
35
36
  },
36
37
  "dependencies": {
37
- "cborg": "6.1.2"
38
+ "cborg": "7.0.0"
38
39
  },
39
40
  "devDependencies": {
40
41
  "@arethetypeswrong/cli": "^0.18.3",
41
42
  "@types/node": "^24.13.3",
43
+ "oxlint": "1.94.0",
44
+ "oxlint-tsgolint": "7.0.2008",
42
45
  "publint": "^0.3.22",
43
46
  "typescript": "^7.0.2",
44
47
  "vitest": "^5.0.0"