@forestrie/receipt-verify 3.0.1 → 3.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.
Files changed (60) hide show
  1. package/dist/checkpoint-chain-receipt-outcome.d.ts +56 -0
  2. package/dist/checkpoint-chain-receipt-outcome.d.ts.map +1 -0
  3. package/dist/checkpoint-chain-receipt-outcome.js +1 -0
  4. package/dist/checkpoint-link-record.d.ts +69 -0
  5. package/dist/checkpoint-link-record.d.ts.map +1 -0
  6. package/dist/checkpoint-link-record.js +1 -0
  7. package/dist/checkpoint-link-verifier.d.ts +80 -0
  8. package/dist/checkpoint-link-verifier.d.ts.map +1 -0
  9. package/dist/checkpoint-link-verifier.js +181 -0
  10. package/dist/decode-trust-root-cbor.d.ts +8 -1
  11. package/dist/decode-trust-root-cbor.d.ts.map +1 -1
  12. package/dist/decode-trust-root-cbor.js +10 -1
  13. package/dist/inclusion-walk-end.d.ts +6 -0
  14. package/dist/inclusion-walk-end.d.ts.map +1 -0
  15. package/dist/inclusion-walk-end.js +35 -0
  16. package/dist/index.d.ts +29 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +23 -0
  19. package/dist/known-accumulator.d.ts.map +1 -1
  20. package/dist/known-accumulator.js +25 -9
  21. package/dist/known-log-key.d.ts +15 -0
  22. package/dist/known-log-key.d.ts.map +1 -0
  23. package/dist/known-log-key.js +20 -0
  24. package/dist/ks256-attestation-usage.d.ts +50 -0
  25. package/dist/ks256-attestation-usage.d.ts.map +1 -0
  26. package/dist/ks256-attestation-usage.js +51 -0
  27. package/dist/ks256-attestation.d.ts +50 -0
  28. package/dist/ks256-attestation.d.ts.map +1 -0
  29. package/dist/ks256-attestation.js +104 -0
  30. package/dist/resolve-delegated-verify-key.d.ts +18 -9
  31. package/dist/resolve-delegated-verify-key.d.ts.map +1 -1
  32. package/dist/resolve-delegated-verify-key.js +26 -9
  33. package/dist/select-ks256-attestation.d.ts +57 -0
  34. package/dist/select-ks256-attestation.d.ts.map +1 -0
  35. package/dist/select-ks256-attestation.js +119 -0
  36. package/dist/verify-grant-receipt-offline.d.ts +31 -6
  37. package/dist/verify-grant-receipt-offline.d.ts.map +1 -1
  38. package/dist/verify-grant-receipt-offline.js +63 -12
  39. package/dist/verify-ks256-delegation.d.ts +56 -0
  40. package/dist/verify-ks256-delegation.d.ts.map +1 -0
  41. package/dist/verify-ks256-delegation.js +95 -0
  42. package/dist/verify-receipt-against-checkpoint-chain.d.ts +42 -0
  43. package/dist/verify-receipt-against-checkpoint-chain.d.ts.map +1 -0
  44. package/dist/verify-receipt-against-checkpoint-chain.js +205 -0
  45. package/package.json +4 -2
  46. package/src/checkpoint-chain-receipt-outcome.ts +67 -0
  47. package/src/checkpoint-link-record.ts +74 -0
  48. package/src/checkpoint-link-verifier.ts +241 -0
  49. package/src/decode-trust-root-cbor.ts +10 -1
  50. package/src/inclusion-walk-end.ts +38 -0
  51. package/src/index.ts +53 -0
  52. package/src/known-accumulator.ts +30 -8
  53. package/src/known-log-key.ts +28 -0
  54. package/src/ks256-attestation-usage.ts +103 -0
  55. package/src/ks256-attestation.ts +144 -0
  56. package/src/resolve-delegated-verify-key.ts +37 -11
  57. package/src/select-ks256-attestation.ts +151 -0
  58. package/src/verify-grant-receipt-offline.ts +109 -20
  59. package/src/verify-ks256-delegation.ts +120 -0
  60. package/src/verify-receipt-against-checkpoint-chain.ts +256 -0
@@ -29,8 +29,9 @@
29
29
  * the operator trust this anchor exists to remove.
30
30
  */
31
31
  import { decodeCborDeterministic, encodeCborDeterministic, } from "@forestrie/encoding";
32
- import { calculateRoot } from "@forestrie/merklelog";
32
+ import { calculateRoot, peakMMRIndexes, } from "@forestrie/merklelog";
33
33
  import { normalizeHexAddress } from "@forestrie/chain-rpc";
34
+ import { inclusionWalkEndIndex } from "./inclusion-walk-end.js";
34
35
  import { parseReceipt } from "./parse-receipt.js";
35
36
  import { univocityLeafHash } from "./leaf-commitment.js";
36
37
  import { SubtleHasher } from "./subtle-hasher.js";
@@ -190,18 +191,33 @@ export async function verifyReceiptOfflineAgainstKnownAccumulator(input) {
190
191
  reason: "receipt_newer_than_known_accumulator",
191
192
  };
192
193
  }
194
+ // The leaf (idtimestamp ‖ inner) and inclusion path ALWAYS decide the
195
+ // peak. An attached payload is only a claim of what that peak is: taken on
196
+ // its own, any receipt attaching a real anchored peak would "verify" for
197
+ // any payload and idtimestamp. Same stage and reason as the main offline
198
+ // path's inclusion check (verifySignatureAndInclusion).
193
199
  let recomputedPeak;
194
- if (parsed.explicitPeak !== null) {
195
- recomputedPeak = parsed.explicitPeak;
196
- }
197
- else {
198
- const hasher = new SubtleHasher();
200
+ try {
199
201
  const leafHash = await univocityLeafHash(input.idtimestampBe8, input.inner);
200
- recomputedPeak = await calculateRoot(hasher, leafHash, parsed.proof, leafIdx);
202
+ recomputedPeak = await calculateRoot(new SubtleHasher(), leafHash, parsed.proof, leafIdx);
203
+ }
204
+ catch {
205
+ return { ok: false, stage: "inclusion", reason: "inclusion_failed" };
206
+ }
207
+ if (parsed.explicitPeak !== null &&
208
+ !bytesEqual(parsed.explicitPeak, recomputedPeak)) {
209
+ return { ok: false, stage: "inclusion", reason: "inclusion_failed" };
201
210
  }
202
211
  // 2. Exact peak match — receipt state is a snapshot-covered accumulator.
203
- for (const peak of input.accumulator) {
204
- if (bytesEqual(recomputedPeak, peak)) {
212
+ // The peak must also sit at the node the inclusion walk reaches (contract
213
+ // order is ascending MMR index, as peakMMRIndexes lists them): a leaf hash
214
+ // does not commit its position, so a value match alone would leave the
215
+ // mmrIndex the freshness check above relies on a caller claim.
216
+ const peakIndex = inclusionWalkEndIndex(leafIdx, parsed.proof.path.length);
217
+ const p = peakMMRIndexes(input.size - 1n).indexOf(peakIndex);
218
+ if (p >= 0) {
219
+ const anchored = input.accumulator[p];
220
+ if (anchored !== undefined && bytesEqual(recomputedPeak, anchored)) {
205
221
  return { ok: true, stage: "binding" };
206
222
  }
207
223
  }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Caller-known log key bytes → trust key (FOR-297 "known log key"; plan-2610-03
3
+ * D6). The bytes alone decide the type, as univocity's
4
+ * `GrantDataInvalidKeyLength` and arbor's `grantDataIdentity` do: 64 bytes is
5
+ * an ES256 x||y public key, 20 bytes a KS256 address, anything else is
6
+ * refused. Either way the caller ASSERTS, and does not prove, that the key
7
+ * owns the log — see `verifyReceiptOfflineWithKeys`.
8
+ */
9
+ import type { RootVerifyKey } from "./root-verify-key.js";
10
+ /**
11
+ * @param bytes - 64-byte ES256 x||y or 20-byte KS256 address.
12
+ * @throws When the length is neither.
13
+ */
14
+ export declare function knownLogKeyFromBytes(bytes: Uint8Array): Promise<RootVerifyKey>;
15
+ //# sourceMappingURL=known-log-key.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"known-log-key.d.ts","sourceRoot":"","sources":["../src/known-log-key.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAE1D;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,aAAa,CAAC,CAMxB"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Caller-known log key bytes → trust key (FOR-297 "known log key"; plan-2610-03
3
+ * D6). The bytes alone decide the type, as univocity's
4
+ * `GrantDataInvalidKeyLength` and arbor's `grantDataIdentity` do: 64 bytes is
5
+ * an ES256 x||y public key, 20 bytes a KS256 address, anything else is
6
+ * refused. Either way the caller ASSERTS, and does not prove, that the key
7
+ * owns the log — see `verifyReceiptOfflineWithKeys`.
8
+ */
9
+ import { importEs256PublicKeyFromGrantDataXy64, ks256RootFromAddress, } from "./decode-trust-root-cbor.js";
10
+ /**
11
+ * @param bytes - 64-byte ES256 x||y or 20-byte KS256 address.
12
+ * @throws When the length is neither.
13
+ */
14
+ export async function knownLogKeyFromBytes(bytes) {
15
+ if (bytes.length === 64)
16
+ return importEs256PublicKeyFromGrantDataXy64(bytes);
17
+ if (bytes.length === 20)
18
+ return ks256RootFromAddress(bytes);
19
+ throw new Error(`known log key must be 64 bytes (ES256 x||y) or 20 bytes (KS256 address), got ${bytes.length}`);
20
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Accounting for a LIST of ERC-1271 attestations over a checkpoint chain
3
+ * (owner ruling D8): every supplied attestation is reported as used or as
4
+ * unused with a reason, never silently ignored.
5
+ */
6
+ import type { Ks256Attestation } from "./ks256-attestation.js";
7
+ import type { CheckpointLinkFailure, CheckpointLinkRecord } from "./checkpoint-link-record.js";
8
+ /**
9
+ * Why a supplied attestation contributed nothing:
10
+ * - `no_matching_certificate`: no link's certificate has its digest and
11
+ * signature hash.
12
+ * - `not_needed`: it matched a certificate that verified without it
13
+ * (ecrecover, or an ES256 root also vouched).
14
+ * - `duplicate`: another supplied attestation for the same certificate
15
+ * (same digest and signature hash) was used, selected or rejected first,
16
+ * so this one was never tried.
17
+ */
18
+ export type Ks256AttestationUnusedReason = "no_matching_certificate" | "not_needed" | "duplicate";
19
+ /**
20
+ * Which supplied attestations carried which links. An attestation may be
21
+ * in both `used` and `rejected` (used on earlier links, refused on a later
22
+ * one); it is in `unused` only when it is in neither.
23
+ */
24
+ export type Ks256AttestationUsage = {
25
+ used: {
26
+ index: number;
27
+ digestHex: string;
28
+ links: number[];
29
+ }[];
30
+ /** Tried for a link's certificate and failed its own checks there. */
31
+ rejected: {
32
+ index: number;
33
+ digestHex: string;
34
+ links: number[];
35
+ }[];
36
+ unused: {
37
+ index: number;
38
+ digestHex: string;
39
+ reason: Ks256AttestationUnusedReason;
40
+ }[];
41
+ };
42
+ /**
43
+ * Classify each supplied attestation against the per-link records.
44
+ *
45
+ * @param attestations - The list the verifier was given, in order.
46
+ * @param records - Records of the links that verified.
47
+ * @param failure - The link the verifier refused, if any.
48
+ */
49
+ export declare function summarizeKs256AttestationUsage(attestations: readonly Ks256Attestation[], records: readonly CheckpointLinkRecord[], failure?: CheckpointLinkFailure): Ks256AttestationUsage;
50
+ //# sourceMappingURL=ks256-attestation-usage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ks256-attestation-usage.d.ts","sourceRoot":"","sources":["../src/ks256-attestation-usage.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,KAAK,EACV,qBAAqB,EACrB,oBAAoB,EACrB,MAAM,6BAA6B,CAAC;AAErC;;;;;;;;;GASG;AACH,MAAM,MAAM,4BAA4B,GACpC,yBAAyB,GACzB,YAAY,GACZ,WAAW,CAAC;AAEhB;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,EAAE,CAAA;KAAE,EAAE,CAAC;IAC9D,sEAAsE;IACtE,QAAQ,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,EAAE,CAAA;KAAE,EAAE,CAAC;IAClE,MAAM,EAAE;QACN,KAAK,EAAE,MAAM,CAAC;QACd,SAAS,EAAE,MAAM,CAAC;QAClB,MAAM,EAAE,4BAA4B,CAAC;KACtC,EAAE,CAAC;CACL,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,8BAA8B,CAC5C,YAAY,EAAE,SAAS,gBAAgB,EAAE,EACzC,OAAO,EAAE,SAAS,oBAAoB,EAAE,EACxC,OAAO,CAAC,EAAE,qBAAqB,GAC9B,qBAAqB,CAsCvB"}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Classify each supplied attestation against the per-link records.
3
+ *
4
+ * @param attestations - The list the verifier was given, in order.
5
+ * @param records - Records of the links that verified.
6
+ * @param failure - The link the verifier refused, if any.
7
+ */
8
+ export function summarizeKs256AttestationUsage(attestations, records, failure) {
9
+ const usage = { used: [], rejected: [], unused: [] };
10
+ const seen = [...records, ...(failure !== undefined ? [failure] : [])];
11
+ const tried = (i) => seen.some((r) => r.attestationIndex === i || (r.attestationsRejected ?? []).includes(i));
12
+ attestations.forEach((a, index) => {
13
+ const digestHex = bytesToHex(a.digest);
14
+ const used = records
15
+ .filter((r) => r.attestationIndex === index && r.attestationNeeded)
16
+ .map((r) => r.index);
17
+ const rejected = seen
18
+ .filter((r) => (r.attestationsRejected ?? []).includes(index))
19
+ .map((r) => r.index);
20
+ if (used.length > 0)
21
+ usage.used.push({ index, digestHex, links: used });
22
+ if (rejected.length > 0) {
23
+ usage.rejected.push({ index, digestHex, links: rejected });
24
+ }
25
+ if (used.length > 0 || rejected.length > 0)
26
+ return;
27
+ let reason = "no_matching_certificate";
28
+ if (seen.some((r) => r.attestationIndex === index)) {
29
+ reason = "not_needed";
30
+ }
31
+ else if (attestations.some((b, j) => j !== index &&
32
+ tried(j) &&
33
+ bytesEqual(a.digest, b.digest) &&
34
+ bytesEqual(a.signatureHash, b.signatureHash))) {
35
+ reason = "duplicate";
36
+ }
37
+ usage.unused.push({ index, digestHex, reason });
38
+ });
39
+ return usage;
40
+ }
41
+ function bytesEqual(a, b) {
42
+ if (a.length !== b.length)
43
+ return false;
44
+ let x = 0;
45
+ for (let i = 0; i < a.length; i++)
46
+ x |= a[i] ^ b[i];
47
+ return x === 0;
48
+ }
49
+ function bytesToHex(bytes) {
50
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
51
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * ERC-1271 attestation (plan-2610-03 D4, protocol ADR-0045 amendment
3
+ * 2026-10-18): a caller-supplied record that a contract KS256 root (a Safe)
4
+ * answered `isValidSignature(digest, signature)` with the ERC-1271 magic value
5
+ * at a given block. It lets a contract-rooted delegation certificate verify
6
+ * offline with the narrower guarantee "valid under the contract's signers at
7
+ * the attested block".
8
+ *
9
+ * Same trust model as the known-accumulator snapshot (known-accumulator.ts):
10
+ * the record is the fetching party's chain read, made explicit and auditable.
11
+ * It binds `(chainId, address, digest, signature hash, block)`, so anyone with
12
+ * RPC can re-run exactly that call at that block (the signature itself is in
13
+ * the receipt's certificate) and confirm or disprove it. This package never makes
14
+ * that call; forestrie-cli and mcp-resolve fetch it (slice 04).
15
+ *
16
+ * The verifier accepts an attestation only for the exact root address and
17
+ * certificate digest, and only when `chainId` equals the forest's genesis
18
+ * chain: the same Safe address on another chain can have other owners (D6).
19
+ */
20
+ /** ERC-1271 `isValidSignature` success value, `bytes4(0x1626ba7e)`. */
21
+ export declare const ERC1271_MAGIC_VALUE: Uint8Array<ArrayBuffer>;
22
+ /** A block-bound ERC-1271 `isValidSignature` result for one digest. */
23
+ export type Ks256Attestation = {
24
+ version: number;
25
+ /** Chain the call was made on; must equal the forest's genesis chain. */
26
+ chainId: bigint;
27
+ /** Contract root address (20 bytes) the call was made to. */
28
+ address: Uint8Array;
29
+ /** keccak256(Sig_structure) of the delegation certificate (32 bytes). */
30
+ digest: Uint8Array;
31
+ /**
32
+ * keccak256 of the signature bytes `isValidSignature` was called with
33
+ * (32 bytes); must match the certificate's signature.
34
+ */
35
+ signatureHash: Uint8Array;
36
+ /** Block the call was made at. */
37
+ blockNumber: bigint;
38
+ /** Hash of that block (32 bytes): the falsifiability handle. */
39
+ blockHash: Uint8Array;
40
+ /** The call's 4-byte return; only {@link ERC1271_MAGIC_VALUE} attests. */
41
+ magic: Uint8Array;
42
+ };
43
+ /** Encode an attestation as canonical CBOR (RFC 8949 §4.2, hard policy). */
44
+ export declare function encodeKs256Attestation(attestation: Ks256Attestation): Uint8Array;
45
+ /**
46
+ * Strict decode and shape validation of an attestation artifact: canonical
47
+ * CBOR, known labels only, version 1, exact types and lengths.
48
+ */
49
+ export declare function decodeKs256Attestation(bytes: Uint8Array): Ks256Attestation;
50
+ //# sourceMappingURL=ks256-attestation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ks256-attestation.d.ts","sourceRoot":"","sources":["../src/ks256-attestation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAOH,uEAAuE;AACvE,eAAO,MAAM,mBAAmB,yBAA2C,CAAC;AAyB5E,uEAAuE;AACvE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,yEAAyE;IACzE,OAAO,EAAE,MAAM,CAAC;IAChB,6DAA6D;IAC7D,OAAO,EAAE,UAAU,CAAC;IACpB,yEAAyE;IACzE,MAAM,EAAE,UAAU,CAAC;IACnB;;;OAGG;IACH,aAAa,EAAE,UAAU,CAAC;IAC1B,kCAAkC;IAClC,WAAW,EAAE,MAAM,CAAC;IACpB,gEAAgE;IAChE,SAAS,EAAE,UAAU,CAAC;IACtB,0EAA0E;IAC1E,KAAK,EAAE,UAAU,CAAC;CACnB,CAAC;AAEF,4EAA4E;AAC5E,wBAAgB,sBAAsB,CACpC,WAAW,EAAE,gBAAgB,GAC5B,UAAU,CAaZ;AAgBD;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,UAAU,GAAG,gBAAgB,CAkC1E"}
@@ -0,0 +1,104 @@
1
+ /**
2
+ * ERC-1271 attestation (plan-2610-03 D4, protocol ADR-0045 amendment
3
+ * 2026-10-18): a caller-supplied record that a contract KS256 root (a Safe)
4
+ * answered `isValidSignature(digest, signature)` with the ERC-1271 magic value
5
+ * at a given block. It lets a contract-rooted delegation certificate verify
6
+ * offline with the narrower guarantee "valid under the contract's signers at
7
+ * the attested block".
8
+ *
9
+ * Same trust model as the known-accumulator snapshot (known-accumulator.ts):
10
+ * the record is the fetching party's chain read, made explicit and auditable.
11
+ * It binds `(chainId, address, digest, signature hash, block)`, so anyone with
12
+ * RPC can re-run exactly that call at that block (the signature itself is in
13
+ * the receipt's certificate) and confirm or disprove it. This package never makes
14
+ * that call; forestrie-cli and mcp-resolve fetch it (slice 04).
15
+ *
16
+ * The verifier accepts an attestation only for the exact root address and
17
+ * certificate digest, and only when `chainId` equals the forest's genesis
18
+ * chain: the same Safe address on another chain can have other owners (D6).
19
+ */
20
+ import { decodeCborDeterministic, encodeCborDeterministic, } from "@forestrie/encoding";
21
+ /** ERC-1271 `isValidSignature` success value, `bytes4(0x1626ba7e)`. */
22
+ export const ERC1271_MAGIC_VALUE = new Uint8Array([0x16, 0x26, 0xba, 0x7e]);
23
+ /** CBOR map labels for the attestation artifact (strict RFC 8949 §4.2). */
24
+ const LABEL_VERSION = 1;
25
+ const LABEL_CHAIN_ID = 2;
26
+ const LABEL_ADDRESS = 3;
27
+ const LABEL_DIGEST = 4;
28
+ const LABEL_BLOCK_NUMBER = 5;
29
+ const LABEL_BLOCK_HASH = 6;
30
+ const LABEL_MAGIC = 7;
31
+ const LABEL_SIGNATURE_HASH = 8;
32
+ const KNOWN_LABELS = new Set([
33
+ LABEL_VERSION,
34
+ LABEL_CHAIN_ID,
35
+ LABEL_ADDRESS,
36
+ LABEL_DIGEST,
37
+ LABEL_BLOCK_NUMBER,
38
+ LABEL_BLOCK_HASH,
39
+ LABEL_MAGIC,
40
+ LABEL_SIGNATURE_HASH,
41
+ ]);
42
+ const ATTESTATION_VERSION = 1;
43
+ /** Encode an attestation as canonical CBOR (RFC 8949 §4.2, hard policy). */
44
+ export function encodeKs256Attestation(attestation) {
45
+ return encodeCborDeterministic(new Map([
46
+ [LABEL_VERSION, attestation.version],
47
+ [LABEL_CHAIN_ID, attestation.chainId],
48
+ [LABEL_ADDRESS, attestation.address],
49
+ [LABEL_DIGEST, attestation.digest],
50
+ [LABEL_BLOCK_NUMBER, attestation.blockNumber],
51
+ [LABEL_BLOCK_HASH, attestation.blockHash],
52
+ [LABEL_MAGIC, attestation.magic],
53
+ [LABEL_SIGNATURE_HASH, attestation.signatureHash],
54
+ ]));
55
+ }
56
+ function asBigint(v, what) {
57
+ if (typeof v === "bigint")
58
+ return v;
59
+ if (typeof v === "number" && Number.isSafeInteger(v) && v >= 0)
60
+ return BigInt(v);
61
+ throw new Error(`ks256 attestation: ${what} must be an unsigned integer`);
62
+ }
63
+ function asBytes(v, length, what) {
64
+ if (!(v instanceof Uint8Array) || v.length !== length) {
65
+ throw new Error(`ks256 attestation: ${what} must be ${length} bytes`);
66
+ }
67
+ return v;
68
+ }
69
+ /**
70
+ * Strict decode and shape validation of an attestation artifact: canonical
71
+ * CBOR, known labels only, version 1, exact types and lengths.
72
+ */
73
+ export function decodeKs256Attestation(bytes) {
74
+ let decoded;
75
+ try {
76
+ decoded = decodeCborDeterministic(bytes);
77
+ }
78
+ catch (err) {
79
+ const message = err instanceof Error ? err.message : String(err);
80
+ throw new Error(`ks256 attestation is not canonical CBOR: ${message}`);
81
+ }
82
+ if (!(decoded instanceof Map)) {
83
+ throw new Error("ks256 attestation must be a CBOR map");
84
+ }
85
+ for (const label of decoded.keys()) {
86
+ if (!KNOWN_LABELS.has(label)) {
87
+ throw new Error(`ks256 attestation: unknown label ${String(label)}`);
88
+ }
89
+ }
90
+ const version = Number(asBigint(decoded.get(LABEL_VERSION), "version"));
91
+ if (version !== ATTESTATION_VERSION) {
92
+ throw new Error(`ks256 attestation version ${version} not supported`);
93
+ }
94
+ return {
95
+ version,
96
+ chainId: asBigint(decoded.get(LABEL_CHAIN_ID), "chainId"),
97
+ address: asBytes(decoded.get(LABEL_ADDRESS), 20, "address"),
98
+ digest: asBytes(decoded.get(LABEL_DIGEST), 32, "digest"),
99
+ blockNumber: asBigint(decoded.get(LABEL_BLOCK_NUMBER), "blockNumber"),
100
+ blockHash: asBytes(decoded.get(LABEL_BLOCK_HASH), 32, "blockHash"),
101
+ magic: asBytes(decoded.get(LABEL_MAGIC), 4, "magic"),
102
+ signatureHash: asBytes(decoded.get(LABEL_SIGNATURE_HASH), 32, "signatureHash"),
103
+ };
104
+ }
@@ -6,12 +6,13 @@
6
6
  * trust root and returns the delegated public key as an additional verify
7
7
  * candidate — the offline port of canopy-api's `resolveReceiptVerifyKey`.
8
8
  *
9
- * P-256 roots only: the genesis alg is ES256 and sealer delegate keys are
10
- * always secp256r1; KS256-rooted delegation is a server-only concern. A
11
- * passkey (WebAuthn) root signs the certificate with alg -65800 and the
12
- * ADR-0063 unprotected-header envelope — `verifyCoseSign1WithParsedKey`
13
- * verifies that envelope against the same P-256 root keys, so the chain walk
14
- * here is alg-agnostic (plan-2608-13 1.4).
9
+ * Sealer delegate keys are always secp256r1. A P-256 root's certificate is
10
+ * checked here; a passkey (WebAuthn) root signs the certificate with alg
11
+ * -65800 and the ADR-0063 unprotected-header envelope, which
12
+ * `verifyCoseSign1WithParsedKey` verifies against the same P-256 root keys
13
+ * (plan-2608-13 1.4). A KS256 root's certificate is checked by
14
+ * {@link verifyKs256DelegationCert}: ecrecover for an EOA, or a caller-supplied
15
+ * ERC-1271 attestation for a contract (plan-2610-03 D4).
15
16
  *
16
17
  * Trust anchors (FOR-297 trust ladder): `rootKeys` need not be genesis-derived
17
18
  * — a caller-known log OWNER key works identically (see
@@ -34,6 +35,8 @@
34
35
  * `issuedAt` lower bound are NOT enforced (see that function). This replaces the
35
36
  * earlier "does not yet enforce the window" gap.
36
37
  */
38
+ import { type RootVerifyKey } from "./root-verify-key.js";
39
+ import { type Ks256DelegationEvidence } from "./verify-ks256-delegation.js";
37
40
  export declare function idtimestampToUnixSeconds(idtimestamp: bigint): number;
38
41
  /**
39
42
  * Snowflake idtimestamp → Unix milliseconds: the time component an
@@ -58,7 +61,8 @@ export type DelegationConstraints = {
58
61
  * `constraints` carries the cert's coverage/validity window when the payload
59
62
  * declares it (null for legacy certs that predate labels 3/4/8/9).
60
63
  * broken: a cert is present but did not verify under the root, or its delegated
61
- * key could not be parsed — the delegation chain is invalid.
64
+ * key could not be parsed — the delegation chain is invalid. `reason` is set
65
+ * when a KS256 root gives a more specific one than `delegation_invalid`.
62
66
  */
63
67
  export type DelegatedResolution = {
64
68
  kind: "root-only";
@@ -68,6 +72,7 @@ export type DelegatedResolution = {
68
72
  constraints: DelegationConstraints | null;
69
73
  } | {
70
74
  kind: "broken";
75
+ reason?: string;
71
76
  };
72
77
  /**
73
78
  * Enforce a resolved cert's constraints against the verified leaf (FOR-420).
@@ -107,7 +112,11 @@ export declare function checkDelegationConstraints(constraints: DelegationConstr
107
112
  * Resolve the delegated verify key from a receipt's delegation certificate.
108
113
  *
109
114
  * @param receiptCbor - the COSE_Sign1 receipt bytes.
110
- * @param rootKeys - genesis-derived ES256 root verify keys.
115
+ * @param rootKeys - trust roots: ES256 keys and KS256 addresses, from genesis
116
+ * or caller-known log keys. A KS256 root never comes from the coordinator
117
+ * (its public roots are last-write-wins, FOR-601/FOR-603).
118
+ * @param ks256Evidence - optional ERC-1271 attestation for a KS256 contract
119
+ * root, with the forest's genesis chain id it must match.
111
120
  */
112
- export declare function resolveDelegatedVerifyKey(receiptCbor: Uint8Array, rootKeys: CryptoKey[]): Promise<DelegatedResolution>;
121
+ export declare function resolveDelegatedVerifyKey(receiptCbor: Uint8Array, rootKeys: RootVerifyKey[], ks256Evidence?: Ks256DelegationEvidence): Promise<DelegatedResolution>;
113
122
  //# sourceMappingURL=resolve-delegated-verify-key.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-delegated-verify-key.d.ts","sourceRoot":"","sources":["../src/resolve-delegated-verify-key.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAqCH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAEpE;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAK/D;AAED;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,GAC3B;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,GACrB;IACE,IAAI,EAAE,UAAU,CAAC;IACjB,YAAY,EAAE,SAAS,CAAC;IACxB,WAAW,EAAE,qBAAqB,GAAG,IAAI,CAAC;CAC3C,GACD;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,CAAC;AAsGvB;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,0BAA0B,CACxC,WAAW,EAAE,qBAAqB,EAClC,YAAY,EAAE,MAAM,EACpB,eAAe,EAAE,MAAM,GACtB;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAS9C;AAED;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAC7C,WAAW,EAAE,UAAU,EACvB,QAAQ,EAAE,SAAS,EAAE,GACpB,OAAO,CAAC,mBAAmB,CAAC,CAgC9B"}
1
+ {"version":3,"file":"resolve-delegated-verify-key.d.ts","sourceRoot":"","sources":["../src/resolve-delegated-verify-key.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAQH,OAAO,EAAwB,KAAK,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAChF,OAAO,EAEL,KAAK,uBAAuB,EAC7B,MAAM,8BAA8B,CAAC;AA8BtC,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAEpE;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAK/D;AAED;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,MAAM,mBAAmB,GAC3B;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,GACrB;IACE,IAAI,EAAE,UAAU,CAAC;IACjB,YAAY,EAAE,SAAS,CAAC;IACxB,WAAW,EAAE,qBAAqB,GAAG,IAAI,CAAC;CAC3C,GACD;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAsGxC;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,0BAA0B,CACxC,WAAW,EAAE,qBAAqB,EAClC,YAAY,EAAE,MAAM,EACpB,eAAe,EAAE,MAAM,GACtB;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAS9C;AAED;;;;;;;;;GASG;AACH,wBAAsB,yBAAyB,CAC7C,WAAW,EAAE,UAAU,EACvB,QAAQ,EAAE,aAAa,EAAE,EACzB,aAAa,GAAE,uBAA4B,GAC1C,OAAO,CAAC,mBAAmB,CAAC,CA8C9B"}
@@ -6,12 +6,13 @@
6
6
  * trust root and returns the delegated public key as an additional verify
7
7
  * candidate — the offline port of canopy-api's `resolveReceiptVerifyKey`.
8
8
  *
9
- * P-256 roots only: the genesis alg is ES256 and sealer delegate keys are
10
- * always secp256r1; KS256-rooted delegation is a server-only concern. A
11
- * passkey (WebAuthn) root signs the certificate with alg -65800 and the
12
- * ADR-0063 unprotected-header envelope — `verifyCoseSign1WithParsedKey`
13
- * verifies that envelope against the same P-256 root keys, so the chain walk
14
- * here is alg-agnostic (plan-2608-13 1.4).
9
+ * Sealer delegate keys are always secp256r1. A P-256 root's certificate is
10
+ * checked here; a passkey (WebAuthn) root signs the certificate with alg
11
+ * -65800 and the ADR-0063 unprotected-header envelope, which
12
+ * `verifyCoseSign1WithParsedKey` verifies against the same P-256 root keys
13
+ * (plan-2608-13 1.4). A KS256 root's certificate is checked by
14
+ * {@link verifyKs256DelegationCert}: ecrecover for an EOA, or a caller-supplied
15
+ * ERC-1271 attestation for a contract (plan-2610-03 D4).
15
16
  *
16
17
  * Trust anchors (FOR-297 trust ladder): `rootKeys` need not be genesis-derived
17
18
  * — a caller-known log OWNER key works identically (see
@@ -35,6 +36,8 @@
35
36
  * earlier "does not yet enforce the window" gap.
36
37
  */
37
38
  import { coseUnprotectedToMap, decodeCborDeterministic, decodeCoseSign1, verifyCoseSign1WithParsedKey, } from "@forestrie/encoding";
39
+ import { isParsedKs256RootKey } from "./root-verify-key.js";
40
+ import { verifyKs256DelegationCert, } from "./verify-ks256-delegation.js";
38
41
  /** Unprotected header label carrying the delegation certificate. */
39
42
  const DELEGATION_CERT_LABEL = 1000;
40
43
  /** COSE_Key labels (RFC 9052) and EC2/P-256 constants. */
@@ -207,9 +210,13 @@ export function checkDelegationConstraints(constraints, leafMmrIndex, leafIdtime
207
210
  * Resolve the delegated verify key from a receipt's delegation certificate.
208
211
  *
209
212
  * @param receiptCbor - the COSE_Sign1 receipt bytes.
210
- * @param rootKeys - genesis-derived ES256 root verify keys.
213
+ * @param rootKeys - trust roots: ES256 keys and KS256 addresses, from genesis
214
+ * or caller-known log keys. A KS256 root never comes from the coordinator
215
+ * (its public roots are last-write-wins, FOR-601/FOR-603).
216
+ * @param ks256Evidence - optional ERC-1271 attestation for a KS256 contract
217
+ * root, with the forest's genesis chain id it must match.
211
218
  */
212
- export async function resolveDelegatedVerifyKey(receiptCbor, rootKeys) {
219
+ export async function resolveDelegatedVerifyKey(receiptCbor, rootKeys, ks256Evidence = {}) {
213
220
  const decoded = decodeCoseSign1(receiptCbor);
214
221
  if (!decoded)
215
222
  return { kind: "root-only" };
@@ -217,7 +224,17 @@ export async function resolveDelegatedVerifyKey(receiptCbor, rootKeys) {
217
224
  if (!certBytes)
218
225
  return { kind: "root-only" };
219
226
  let verified = false;
227
+ let ks256Reason;
220
228
  for (const rootKey of rootKeys) {
229
+ if (isParsedKs256RootKey(rootKey)) {
230
+ const check = await verifyKs256DelegationCert(certBytes, rootKey.address, ks256Evidence);
231
+ if (check.ok) {
232
+ verified = true;
233
+ break;
234
+ }
235
+ ks256Reason ??= check.reason;
236
+ continue;
237
+ }
221
238
  if (await verifyCoseSign1WithParsedKey(certBytes, rootKey, {
222
239
  logPrefix: "delegation-cert-offline",
223
240
  })) {
@@ -226,7 +243,7 @@ export async function resolveDelegatedVerifyKey(receiptCbor, rootKeys) {
226
243
  }
227
244
  }
228
245
  if (!verified)
229
- return { kind: "broken" };
246
+ return { kind: "broken", reason: ks256Reason };
230
247
  const certDecoded = decodeCoseSign1(certBytes);
231
248
  if (!certDecoded)
232
249
  return { kind: "broken" };
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Choosing an ERC-1271 attestation from several (owner ruling D8,
3
+ * 2026-10-19). A contract KS256 root (a Safe) that rotated its delegate
4
+ * signs one certificate per delegate, and each certificate needs its own
5
+ * attestation; a caller holding a checkpoint chain or several receipts
6
+ * supplies them as a list. Each certificate takes the attestation whose
7
+ * `digest` AND `signatureHash` are that certificate's: keccak256 of its
8
+ * Sig_structure and keccak256 of its signature bytes.
9
+ *
10
+ * Selection never makes an attestation acceptable on its own:
11
+ * `verifyKs256DelegationCert` still checks address, digest, signature hash,
12
+ * genesis chain id and magic.
13
+ */
14
+ import type { Ks256CertificateDigest } from "@forestrie/delegation-cose";
15
+ import type { Ks256Attestation } from "./ks256-attestation.js";
16
+ import { type DelegatedResolution } from "./resolve-delegated-verify-key.js";
17
+ import type { RootVerifyKey } from "./root-verify-key.js";
18
+ /**
19
+ * The attestation in `attestations` made for this certificate: the first
20
+ * whose `digest` equals the certificate digest and whose `signatureHash`
21
+ * equals keccak256 of the certificate signature.
22
+ *
23
+ * @param cert - From `extractKs256CertificateDigest` (delegation-cose) or
24
+ * {@link extractKs256DelegationDigest}.
25
+ * @returns The first matching attestation, or `undefined` when none
26
+ * matches. The verifiers go further: they try EVERY match in order and
27
+ * keep the first that passes its own checks.
28
+ */
29
+ export declare function selectKs256Attestation(cert: Ks256CertificateDigest, attestations: readonly Ks256Attestation[]): Ks256Attestation | undefined;
30
+ /**
31
+ * Resolve a COSE_Sign1's label-1000 certificate (a receipt or a checkpoint)
32
+ * under `rootKeys`, trying the supplied attestations made for it.
33
+ *
34
+ * Every attestation whose digest and signature hash match the certificate
35
+ * is tried in list order, and the first that resolves wins: a stale or
36
+ * wrong-chain copy listed before a good one must not mask it. When none
37
+ * resolves, the first failure is returned. When none matches at all, a
38
+ * DIAGNOSTIC stand-in (one with the right digest if any, else the first) is
39
+ * passed so a contract root fails with the precise
40
+ * `ks256_attestation_*_mismatch` reason rather than a bare
41
+ * `ks256_root_not_recovered`; a stand-in can never verify, because
42
+ * `verifyKs256DelegationCert` checks digest and signature hash. With one
43
+ * attestation supplied this is exactly the 3.1.0 behaviour of the singular
44
+ * `ks256Attestation` input.
45
+ *
46
+ * @returns The resolution; `selected`, the index of the attestation it was
47
+ * resolved with (whether or not ecrecover made it unnecessary); and
48
+ * `rejected`, the matching attestations tried that failed their own
49
+ * checks (address, chain id, magic).
50
+ * @internal
51
+ */
52
+ export declare function resolveWithKs256Attestations(coseSign1Bytes: Uint8Array, rootKeys: RootVerifyKey[], attestations: readonly Ks256Attestation[], forestChainId: bigint | undefined): Promise<{
53
+ resolution: DelegatedResolution;
54
+ selected?: number;
55
+ rejected: number[];
56
+ }>;
57
+ //# sourceMappingURL=select-ks256-attestation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"select-ks256-attestation.d.ts","sourceRoot":"","sources":["../src/select-ks256-attestation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAEL,KAAK,mBAAmB,EACzB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAG1D;;;;;;;;;;GAUG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,sBAAsB,EAC5B,YAAY,EAAE,SAAS,gBAAgB,EAAE,GACxC,gBAAgB,GAAG,SAAS,CAG9B;AASD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,4BAA4B,CAChD,cAAc,EAAE,UAAU,EAC1B,QAAQ,EAAE,aAAa,EAAE,EACzB,YAAY,EAAE,SAAS,gBAAgB,EAAE,EACzC,aAAa,EAAE,MAAM,GAAG,SAAS,GAChC,OAAO,CAAC;IACT,UAAU,EAAE,mBAAmB,CAAC;IAChC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB,CAAC,CA6CD"}