@cardanowall/sdk-ts 0.1.0 → 0.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 +1 @@
1
- {"version":3,"sources":["../../src/verifier/types.ts","../../../poe-standard/src/schema.ts","../../../crypto-core/src/cbor/errors.ts","../../../crypto-core/src/cbor/canonical.ts","../../../crypto-core/src/cbor/permissive.ts","../../../poe-standard/src/encoder.ts","../../../crypto-core/src/hash/blake2b-256.ts","../../../crypto-core/src/sig/ed25519.ts","../../../crypto-core/src/util/compare-ct.ts","../../../crypto-core/src/cose/errors.ts","../../../crypto-core/src/cose/sign1.ts","../../../crypto-core/src/cose/cose-key.ts","../../../poe-standard/src/chunked.ts","../../../poe-standard/src/error-codes.ts","../../../poe-standard/src/validator.ts","../../../crypto-core/src/kdf/argon2id.ts","../../../crypto-core/src/aead/errors.ts","../../../crypto-core/src/aead/xchacha20-poly1305.ts","../../../crypto-core/src/hash/sha-256.ts","../../../crypto-core/src/hash/merkle-sha2-256.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/utils.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/_crystals.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/ml-kem.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/hybrid.ts","../../../crypto-core/src/aead/chacha20-poly1305.ts","../../../crypto-core/src/kdf/hkdf.ts","../../../crypto-core/src/kem/mlkem768x25519.ts","../../../crypto-core/src/kem/x25519.ts","../../../crypto-core/src/sealed-poe/errors.ts","../../../crypto-core/src/sealed-poe/slots-codec.ts","../../../crypto-core/src/sealed-poe/wrap.ts","../../../crypto-core/src/sealed-poe/unwrap.ts","../../../crypto-core/src/sealed-poe/envelope-from-parsed.ts","../../src/fetch/fetch-outbound.ts","../../src/verifier/fetch.ts","../../src/verifier/decrypt.ts","../../../crypto-core/src/merkle/leaves-list.ts","../../src/verifier/merkle.ts","../../src/verifier/profile.ts","../../src/verifier/cbor-walker.ts","../../src/verifier/resolve.ts","../../src/hex.ts","../../src/verifier/signatures.ts","../../src/verifier/tx-witnesses.ts","../../src/verifier/verify.ts","../../src/conformance/cli.ts"],"names":["decode","hashes","CanonicalCborError","encodeCanonicalCbor","encode","sortCoreDeterministic","decodeCanonicalCbor","cdeDecodeOptions","mapDecodeError","opts","UTF8_ENCODER","issue","j","sha256","nobleSha256","blake2b","blake2b224","randb","abytes_","N","Q","F","ROOT_OF_UNITY","z","shake256","abytes","sha3_256","concatBytes","AeadVerificationError","chacha20poly1305","xchacha20Poly1305Decrypt","xchacha20poly1305","hkdf","x25519","compareCt","ZERO_NONCE_12","EMPTY_SALT","X25519_SECRET_KEY_LENGTH","X25519_PUBLIC_KEY_LENGTH","NONCE_LENGTH","WRAP_LENGTH","SLOTS_MAC_LENGTH","concat","hmac","LEAF_PREFIX","NODE_PREFIX","DIGEST_LENGTH","validateLeaves","merkleSha2256Root","mthRecursive","largestPow2Lt","hashLeaf","hashNode","ED25519_PUBLIC_KEY_LENGTH","ed2","sha512","L","leBytesToBigInt","verifyEd25519","asMap"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8CO,IAAM,YAAA,GAAkD,OAAO,MAAA,CAAO;AAAA,EAC3E,IAAA,EAAM,CAAA;AAAA,EACN,MAAA,EAAQ,CAAA;AAAA,EACR,MAAA,EAAQ,CAAA;AAAA,EACR,kBAAA,EAAoB;AACtB,CAAC,CAAA;ACbM,IAAM,0BAA0B,CAAA,CACpC,KAAA;AAAA,EACC,CAAA,CAAE,UAAA,CAAW,UAAU,CAAA,CAAE,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,MAAA,IAAU,CAAA,IAAK,CAAA,CAAE,MAAA,IAAU,EAAA,EAAI;AAAA,IACtE,MAAA,EAAQ,EAAE,IAAA,EAAM,iBAAA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AS;AAAA,MAC5B,MAAA,EAAQ,MAAA,CAAO,MAAA,CAAO,WAAA,EAAY;AAAA,MAClC,mBAAA,EAAqB,QAAA;AAAA,MACrB,GAAI,OAAO,SAAA,KAAc,KAAA,CAAA,GAAY,EAAE,0BAAA,EAA4B,MAAA,CAAO,SAAA,EAAU,GAAI;AAAC,KAC1F,CAAA;AACD,IAAA,EAAA,CAAG,OAAO,IAAA,CAAK,SAAA,CAAU,QAAQ,IAAA,EAAM,CAAC,IAAI,IAAI,CAAA;AAChD,IAAA,OAAO,mBAAmB,MAAM,CAAA;AAAA,EAClC,SAAS,GAAA,EAAK;AACZ,IAAA,EAAA,CAAG,MAAA;AAAA,MACD,gDAAgD,GAAA,YAAe,KAAA,GAAQ,IAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC;AAAA;AAAA,KAClG;AACA,IAAA,OAAO,CAAA;AAAA,EACT;AACF;AAGA,IAAI,kBAAkB,IAAA,CAAK,OAAA,CAAQ,KAAK,CAAC,CAAA,IAAK,EAAE,CAAA,EAAG;AACjD,EAAA,KAAK,GAAA,CAAI,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,EAAG;AAAA,IAC9B,QAAQ,CAAC,IAAA,KAAS,OAAA,CAAQ,MAAA,CAAO,MAAM,IAAI,CAAA;AAAA,IAC3C,QAAQ,CAAC,IAAA,KAAS,OAAA,CAAQ,MAAA,CAAO,MAAM,IAAI;AAAA,GAC5C,EAAE,IAAA,CAAK,CAAC,SAAS,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA;AACtC","file":"cli.js","sourcesContent":["// Public types for the CIP-309 standalone verifier.\n//\n// The verifier is service-independent: it depends only on the operator-supplied\n// Cardano / Arweave / IPFS gateway chains and a `denyHosts` policy. Every\n// outbound network call routes through `fetchOutbound` (single egress point)\n// and lands in `VerifyReport.httpCalls` for audit.\n\nimport type { PoeRecord, ValidationIssue } from '@cardanowall/poe-standard';\n\nimport type { FetchOutbound, HttpCallRecord } from '../fetch/fetch-outbound';\n\n// -----------------------------------------------------------------------------\n// Verdict / exit-code\n// -----------------------------------------------------------------------------\n//\n// `'valid'` → exit 0 — every check returned ok.\n// `'pending'` → exit 3 — INSUFFICIENT_CONFIRMATIONS (record well-formed but\n// below the verifier's reorg-safety threshold).\n// `'failed'` → exit 1 — integrity / structural / signature class.\n// → exit 2 — network class (CONTENT_UNAVAILABLE, PROVIDER_UNAVAILABLE).\n\nexport type Verdict = 'valid' | 'pending' | 'failed';\nexport type ExitCode = 0 | 1 | 2 | 3;\n\n// -----------------------------------------------------------------------------\n// Conformance profile\n// -----------------------------------------------------------------------------\n//\n// Strict-superset order: each higher profile reads everything below it plus\n// one additional surface. A verifier of a LOWER profile that sees a field\n// belonging to a HIGHER profile MUST emit `OUT_OF_PROFILE_SKIPPED`\n// (info-severity) and continue — it MUST NOT report the record as invalid.\n\nexport type Profile = 'core' | 'signed' | 'sealed' | 'recipient-sealed';\n\n// -----------------------------------------------------------------------------\n// Network identifier — mainnet-only policy.\n// -----------------------------------------------------------------------------\n//\n// Cardano mainnet only; testnet is explicitly out-of-scope by project\n// policy. The literal `'cardano:mainnet'` is the wire-canonical\n// identifier surfaced in every VerifyReport so a downstream consumer never has\n// to infer which network the record was anchored on.\n\nexport type Network = 'cardano:mainnet';\n\nexport const PROFILE_RANK: Readonly<Record<Profile, number>> = Object.freeze({\n core: 0,\n signed: 1,\n sealed: 2,\n 'recipient-sealed': 3,\n});\n\n// -----------------------------------------------------------------------------\n// FetchOutbound (the verifier's only network egress point)\n// -----------------------------------------------------------------------------\n\nexport type {\n FetchOutbound,\n FetchOutboundOptions,\n FetchOutboundResult,\n HttpCallRecord,\n} from '../fetch/fetch-outbound';\n\n// -----------------------------------------------------------------------------\n// Verifier issue surface — re-exports the validator's `ValidationIssue` so\n// downstream consumers can dispatch on a single union (`ErrorCode` covers\n// both Part A and Part B per `@cardanowall/poe-standard`).\n// -----------------------------------------------------------------------------\n\nexport type { ValidationIssue } from '@cardanowall/poe-standard';\n\n// -----------------------------------------------------------------------------\n// VerifyTx input — discriminated decryption union.\n// -----------------------------------------------------------------------------\n\nexport interface VerifyTxInput {\n readonly txHash: string; // lowercase hex, no 0x prefix\n readonly profile?: Profile; // default 'recipient-sealed' (full pipeline)\n readonly cardanoGatewayChain?: ReadonlyArray<string>; // Koios-compatible URLs, in order\n readonly blockfrostProjectId?: string; // enables Blockfrost fallback\n readonly arweaveGatewayChain?: ReadonlyArray<string>;\n readonly ipfsGatewayChain?: ReadonlyArray<string>;\n readonly confirmationDepthThreshold?: number; // default 15; verifier-policy floor\n readonly denyHosts?: ReadonlyArray<string>; // service-independence guard\n // Master offline switch for the verifier's outbound URI fetches. When\n // `false`, the verifier neither fetches a sealed item's `uris[]` ciphertext\n // (decryption falls back to caller-supplied `ciphertextBytes` only) nor the\n // Merkle list-commitment leaves-list — so a Merkle-bearing or sealed record\n // verifies with ZERO egress beyond the chain/indexer resolve step. The\n // on-record `record.merkle[]` / `items[].uris[]` data round-trips through\n // `record` unchanged; only the verifier's defence-in-depth recompute and the\n // ciphertext download are suppressed. Defaults to `true` (full pipeline).\n // Server-rendered pages flip this to `false` so hash-only / merkle-only /\n // sealed records render from indexed CBOR alone, with the leaves-list and\n // ciphertext fetches deferred to a user-initiated client-side action.\n readonly verifyMerkle?: boolean;\n // Out-of-band sealed-PoE decryption attempts. The verifier dispatches by\n // inspecting `items[i].enc.slots` vs `items[i].enc.passphrase` presence; a\n // mismatched entry surfaces as WRONG_DECRYPTION_INPUT_SHAPE.\n readonly decryption?: ReadonlyArray<\n | { readonly itemIndex: number; readonly recipientSecretKey: Uint8Array }\n | { readonly itemIndex: number; readonly passphrase: string }\n >;\n // Out-of-band ciphertext bytes (keyed by item index). When supplied, takes\n // precedence over `items[i].uris[]` (no network fetch is issued).\n readonly ciphertextBytes?: Readonly<Record<number, Uint8Array>>;\n // Out-of-band Merkle leaves-list bytes (keyed by `record.merkle[i]` index).\n // CBOR is the normative wire form.\n readonly merkleLeaves?: Readonly<Record<number, Uint8Array>>;\n // For stake-address binding (path-2 wallet signatures). The\n // verifier recomputes `network_header || Blake2b-224(pubkey)` and compares\n // to the protected-header `address` field; mismatch emits\n // WALLET_ADDRESS_MISMATCH. Defaults to 'mainnet' when omitted; 'preprod' is\n // supplied only by callers running against the Cardano preprod testnet\n // (worker dev mode, future receiver-side scanner on preprod). The\n // wire-canonical `VerifyReport.network` field stays pinned to\n // 'cardano:mainnet' — this input only governs the stake-byte used for\n // path-2 address derivation.\n readonly cardanoNetwork?: 'mainnet' | 'preprod';\n // Injected for tests; defaults to fetchOutbound (the single egress point).\n readonly fetchOutbound?: FetchOutbound;\n}\n\n// -----------------------------------------------------------------------------\n// VerifyReport shape.\n// -----------------------------------------------------------------------------\n\nexport type SignatureVerdict = 'valid' | 'invalid' | 'unsupported' | 'unresolved';\nexport type SignatureFailureReason =\n | 'MALFORMED_SIG_COSE_SIGN1'\n | 'SIGNATURE_UNSUPPORTED'\n | 'SIGNER_KEY_UNRESOLVED'\n | 'SIGNATURE_INVALID'\n | 'WALLET_ADDRESS_MISMATCH';\n\nexport type SignerType = 'in-signature-kid' | 'wallet-inline-key';\n\nexport interface VerifyRecordSignature {\n readonly index: number;\n readonly verdict: SignatureVerdict;\n readonly signer_pub?: string; // lowercase hex of 32-byte Ed25519 pubkey when resolved\n readonly signer_type?: SignerType;\n readonly reason?: SignatureFailureReason;\n}\n\nexport type DecryptionVerdict =\n | 'decrypted'\n | 'wrong-key'\n | 'tampered-header'\n | 'tampered-ciphertext'\n | 'wrong-input-shape'\n | 'no-enc-envelope'\n | 'ciphertext-unavailable'\n | 'content-unavailable'\n | 'skipped'\n | 'kdf-failed';\n\nexport interface VerifyItemDecryption {\n readonly item_index: number;\n readonly verdict: DecryptionVerdict;\n // True iff every content-hash entry in `items[i].hashes` recomputes to the\n // recovered plaintext. Always a concrete boolean on `verdict === 'decrypted'`.\n readonly plaintext_hash_ok?: boolean;\n readonly reason?: string;\n}\n\nexport type ItemHashCheck = {\n readonly item_index: number;\n readonly alg: string;\n readonly ok: boolean;\n};\n\nexport type MerkleVerdict =\n | 'valid'\n | 'mismatch'\n | 'unavailable'\n | 'format-unsupported'\n | 'unsupported';\n\nexport interface VerifyMerkleCheck {\n readonly merkle_index: number;\n readonly alg: string;\n readonly verdict: MerkleVerdict;\n readonly root_recomputed?: Uint8Array;\n readonly reason?: string;\n}\n\nexport interface VerifyUriCheck {\n readonly item_index: number;\n readonly uri: string;\n readonly ok: boolean;\n readonly reason?: string;\n}\n\n// -----------------------------------------------------------------------------\n// Transaction-level description — DISTINCT from record-level authorship.\n// -----------------------------------------------------------------------------\n//\n// These surfaces describe the Cardano transaction that carried the PoE: which\n// wallet vkey(s) authorised/paid for it, the fee, and the outputs. This is the\n// \"who submitted and paid for this anchoring\" view — orthogonal to\n// `record_signatures`, which is the optional CIP-309 record-level authorship\n// claim. A failed `signature_valid` here is INFORMATIONAL: it never changes the\n// verifier's verdict (the content claim does not depend on who paid the fee).\n\nexport interface VerifyTxWitness {\n readonly type: 'vkey';\n readonly vkey: string; // hex 32B Ed25519 pubkey\n readonly key_hash: string; // hex 28B Blake2b-224(vkey)\n readonly signature_valid: boolean; // Ed25519.verify(sig, blake2b256(tx_body), vkey)\n}\n\nexport interface VerifyTxOutput {\n readonly address: string; // bech32\n readonly lovelace: string; // decimal string\n}\n\nexport interface VerifyTxSummary {\n readonly fee_lovelace: string; // decimal string\n readonly input_count: number;\n readonly output_count: number;\n readonly outputs: ReadonlyArray<VerifyTxOutput>;\n readonly total_output_lovelace: string; // decimal string\n readonly script_witness_count: number;\n readonly invalid_before?: number;\n readonly invalid_hereafter?: number;\n readonly required_signer_key_hashes?: ReadonlyArray<string>;\n readonly network_id?: number;\n}\n\n// VerifyReport is snake_case end-to-end: the wire shape, the SDK's in-memory\n// representation, and every consumer-facing field share the same identifier\n// grammar. No transformer layer between the verifier and the API response —\n// `VerifyReport` IS the wire body for `POST /api/v1/records/{tx_hash}/verify`.\nexport interface VerifyReport {\n readonly tx_hash: string;\n readonly network: Network;\n readonly verdict: Verdict;\n readonly exit_code: ExitCode;\n readonly profile: Profile;\n readonly num_confirmations: number;\n readonly confirmation_depth_threshold: number;\n readonly block_time?: number;\n readonly block_slot?: number;\n readonly metadata_present: boolean;\n readonly validation: {\n readonly valid: boolean;\n readonly issues?: ReadonlyArray<ValidationIssue>;\n readonly warnings?: ReadonlyArray<ValidationIssue>;\n readonly info?: ReadonlyArray<ValidationIssue>;\n };\n readonly record?: PoeRecord;\n readonly record_signatures?: ReadonlyArray<VerifyRecordSignature>;\n // Transaction-level description (present only when raw tx CBOR is available\n // to the pipeline — the live `verifyTx` path always has it; the DB-first\n // `verifyResolved` path has it only when the caller passes `txCbor`).\n readonly tx_witnesses?: ReadonlyArray<VerifyTxWitness>;\n readonly tx_summary?: VerifyTxSummary;\n readonly metadata_labels?: ReadonlyArray<number>; // sorted ascending; all aux metadata label keys\n readonly item_hash_checks?: ReadonlyArray<ItemHashCheck>;\n readonly item_decryptions?: ReadonlyArray<VerifyItemDecryption>;\n readonly merkle_checks?: ReadonlyArray<VerifyMerkleCheck>;\n readonly uri_checks?: ReadonlyArray<VerifyUriCheck>;\n readonly supersedes_resolved?: { readonly tx: string; readonly exists: boolean };\n readonly http_calls: ReadonlyArray<HttpCallRecord>;\n}\n","// CIP-309 v1 PoE record Zod schemas.\n//\n// Scope: structural shape gate. The schema enforces per-field types, length\n// bounds (chunk size, digest length, supersedes length, nonce length,\n// passphrase salt length), closed-map invariants (`sigs[i]`, `slot`,\n// `passphrase`, `merkle[i]`), and the `v == 1` literal. Cross-field rules\n// (item.hashes content-hash binding when `enc` present, slots/passphrase\n// exclusivity, `crit[]` shape, registry membership of algorithm\n// identifiers, COSE_Sign1 structural decode, URI per-scheme shape rules)\n// fire in `validator.ts` so the validator can emit the precise structural\n// codes (`UNSUPPORTED_*_ALG`, `ENC_*`, `SIG_*`, `INVALID_URI`,\n// `CRIT_SHAPE_INVALID`, …) rather than a generic schema-mismatch.\n//\n// Refinements that DO live in the schema (because the validator's domain\n// pass lifts these as `SCHEMA_*` / `*_LENGTH_MISMATCH` codes directly):\n// - chunk size `[1, 64]` → `CHUNK_TOO_LARGE`\n// - 32-byte digest / 32-byte root / 32-byte supersedes → `HASH_DIGEST_LENGTH_MISMATCH`\n// / `SUPERSEDES_TX_INVALID_LENGTH`\n// - 24-byte nonce / 32-byte slots_mac →\n// `NONCE_LENGTH_MISMATCH` / `ENC_SLOTS_MAC_INVALID_LENGTH`\n// - passphrase salt 16..64 bytes → `ENC_PASSPHRASE_SALT_TOO_SHORT` /\n// `ENC_PASSPHRASE_SALT_TOO_LONG`\n//\n// Per-slot recipient lengths (`epk`, `kem_ct`, `wrap`) are NOT enforced here:\n// the required slot shape depends on the envelope-level `kem`, which a slot\n// cannot see in isolation. The KEM-driven slot descriptor in `validator.ts`\n// emits the precise `KEM_EPK_LENGTH_MISMATCH` / `KEM_CT_LENGTH_MISMATCH` /\n// `WRAP_LENGTH_MISMATCH` / `ENC_SLOT_INVALID_SHAPE` codes instead.\n\nimport { z } from 'zod';\n\n// =============================================================================\n// Chunked-bytes / chunked-text arrays\n// =============================================================================\n\n// `[1* bstr .size (1..64)]`. A zero-length chunk (0 < 1) is rejected with the\n// SAME `CHUNK_TOO_LARGE` code as oversized chunks (any length outside\n// `[1, 64]`).\nexport const ChunkedBytesArraySchema = z\n .array(\n z.instanceof(Uint8Array).refine((b) => b.length >= 1 && b.length <= 64, {\n params: { code: 'CHUNK_TOO_LARGE' },\n }),\n )\n .min(1);\nexport type ChunkedBytesArray = z.infer<typeof ChunkedBytesArraySchema>;\n\n// `[1* tstr .size (1..64)]` — chunk byte length is the UTF-8-encoded length\n// (each `tstr` is wire-encoded as UTF-8). The `tstr .size (1..64)` pin is a\n// byte-count constraint, not a code-unit constraint.\nconst UTF8_ENCODER = new TextEncoder();\nexport const UriChunkArraySchema = z\n .array(\n z.string().refine(\n (s) => {\n const n = UTF8_ENCODER.encode(s).length;\n return n >= 1 && n <= 64;\n },\n { params: { code: 'CHUNK_TOO_LARGE' } },\n ),\n )\n .min(1);\nexport type UriChunkArray = z.infer<typeof UriChunkArraySchema>;\n\n// =============================================================================\n// Hashes map\n// =============================================================================\n//\n// `hashes` is a non-empty CBOR map keyed by content-hash algorithm identifier\n// (a CBOR text string from the content-hash registry) with the 32-byte digest\n// as value. cbor2 surfaces a text-keyed CBOR map as a plain JS object — z.record\n// admits any string key here. Both the registry-membership check\n// (`UNSUPPORTED_HASH_ALG`) and the per-algorithm digest-length check\n// (`HASH_DIGEST_LENGTH_MISMATCH`) live in the validator's domain pass so\n// each violation emits its precise code; the schema only enforces the\n// value is a CBOR byte string.\n\nexport const HashDigestSchema = z.instanceof(Uint8Array);\n\nexport const HashesMapSchema = z.record(z.string(), HashDigestSchema);\nexport type HashesMap = z.infer<typeof HashesMapSchema>;\n\n// =============================================================================\n// Top-level `merkle[]`\n// =============================================================================\n//\n// Each commit is a closed map `{alg, root, leaf_count, ? uris}`. `alg` is open\n// (registry membership is enforced in the validator's domain pass — unknown\n// identifiers emit `UNSUPPORTED_MERKLE_COMMIT_ALG`).\n\nexport const MerkleCommitSchema = z\n .object({\n alg: z.string(),\n root: z.instanceof(Uint8Array),\n leaf_count: z.number().int().min(1),\n uris: z.array(UriChunkArraySchema).min(1).optional(),\n })\n .strict();\nexport type MerkleCommit = z.infer<typeof MerkleCommitSchema>;\n\n// =============================================================================\n// Encryption envelope\n// =============================================================================\n\n// Per-slot recipient entry. The slot shape is KEM-driven:\n//\n// - x25519: `{ epk: bstr(32), wrap: bstr(48) }` — `epk` is the\n// ephemeral X25519 public key, `wrap` is the 32-byte CEK + 16-byte\n// ChaCha20-Poly1305 tag.\n// - mlkem768x25519: `{ kem_ct: [ bstr .size (1..64) ], wrap: bstr(48) }` —\n// `kem_ct` is the 1120-byte X-Wing `enc` carried as a chunked byte-string\n// array (the same `bytes-chunk-array` shape `sigs[i].cose_sign1` uses);\n// there is NO per-slot `epk` on the hybrid path.\n//\n// The `kem` identifier is hoisted to envelope scope (a per-slot `kem` would\n// be wire-bloat). The schema is deliberately PERMISSIVE:\n// `epk`, `kem_ct`, and `wrap` are all optional and `.strict()` is NOT applied.\n// Both the per-field length checks (`KEM_EPK_LENGTH_MISMATCH`,\n// `KEM_CT_LENGTH_MISMATCH`, `WRAP_LENGTH_MISMATCH`) and the KEM-driven\n// shape gate (which field MUST/MUST NOT be present for the declared `kem`,\n// emitting `ENC_SLOT_INVALID_SHAPE`) live in the validator's domain pass —\n// the structural schema cannot know the envelope `kem` from a slot in\n// isolation, and we want the precise KEM-aware code rather than a generic\n// schema mismatch. Because `.strict()` is dropped, the domain pass MUST\n// explicitly reject cross-KEM contamination (an x25519 slot carrying\n// `kem_ct`, or a hybrid slot carrying `epk`).\nexport const SlotSchema = z.object({\n epk: z.instanceof(Uint8Array).optional(),\n kem_ct: ChunkedBytesArraySchema.optional(),\n wrap: z.instanceof(Uint8Array).optional(),\n});\nexport type Slot = z.infer<typeof SlotSchema>;\n\n// Argon2id params `{m, t, p}` are a closed map. Each value MUST be a CBOR\n// unsigned integer; the FLOOR check (`m ≥ 65536`,\n// `t ≥ 3`, `p ≥ 1`) emits `ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW` in the\n// validator's domain pass — keeping it out of the schema lets us emit the\n// distinct salt-length code when salt itself is malformed too.\nexport const Argon2idParamsSchema = z\n .object({\n m: z.number().int(),\n t: z.number().int(),\n p: z.number().int(),\n })\n .strict();\nexport type Argon2idParams = z.infer<typeof Argon2idParamsSchema>;\n\n// Passphrase block. `alg` is open (registry membership checked in the\n// validator's domain pass → `ENC_PASSPHRASE_ALG_UNSUPPORTED`);\n// `params` is open here (validator narrows on the registered `alg` value and\n// emits `SCHEMA_UNKNOWN_FIELD` for extra keys, `ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW`\n// for sub-floor values). `salt` length floor/ceiling are schema-layer\n// refinements with the dedicated `ENC_PASSPHRASE_SALT_TOO_SHORT/TOO_LONG`\n// codes — they belong at the schema layer because a slot cannot otherwise\n// see the salt length.\nexport const PassphraseBlockSchema = z\n .object({\n alg: z.string(),\n salt: z.instanceof(Uint8Array).superRefine((bytes, ctx) => {\n if (bytes.length < 16) {\n ctx.addIssue({\n code: 'custom',\n path: [],\n message: `passphrase.salt length ${bytes.length} < 16`,\n params: { code: 'ENC_PASSPHRASE_SALT_TOO_SHORT' },\n });\n } else if (bytes.length > 64) {\n ctx.addIssue({\n code: 'custom',\n path: [],\n message: `passphrase.salt length ${bytes.length} > 64`,\n params: { code: 'ENC_PASSPHRASE_SALT_TOO_LONG' },\n });\n }\n }),\n params: z.record(z.string(), z.unknown()),\n })\n .strict();\nexport type PassphraseBlock = z.infer<typeof PassphraseBlockSchema>;\n\n// Sealed-PoE envelope. The wire format admits any combination of\n// `kem` / `slots` / `slots_mac` / `passphrase` keys (permissive superset);\n// cross-field invariants (slots ⊕ passphrase, slots ↔ slots_mac, slots\n// requires kem, content-hash binding, slots non-empty) are enforced in the\n// validator's domain pass so each violation emits its typed code rather\n// than a generic shape mismatch.\nexport const EncryptionEnvelopeSchema = z\n .object({\n scheme: z.unknown(),\n aead: z.string(),\n kem: z.string().optional(),\n nonce: z.instanceof(Uint8Array),\n slots: z.array(SlotSchema).optional(),\n slots_mac: z\n .instanceof(Uint8Array)\n .refine((b) => b.length === 32, {\n params: { code: 'ENC_SLOTS_MAC_INVALID_LENGTH' },\n })\n .optional(),\n passphrase: PassphraseBlockSchema.optional(),\n })\n .strict();\nexport type EncryptionEnvelope = z.infer<typeof EncryptionEnvelopeSchema>;\n\n// =============================================================================\n// Item entry\n// =============================================================================\n\nexport const ItemEntrySchema = z\n .object({\n hashes: HashesMapSchema,\n uris: z.array(UriChunkArraySchema).min(1).optional(),\n // Captured as `unknown` so the validator can run the\n // `ENC_REQUIRES_CONTENT_HASH` pre-check ahead of any inner-shape errors\n // and surface the most informative code first.\n enc: z.unknown().optional(),\n })\n .strict();\nexport type ItemEntry = z.infer<typeof ItemEntrySchema>;\n\n// =============================================================================\n// Sig entry\n// =============================================================================\n//\n// Closed CBOR map `{cose_sign1, ? cose_key}`. Canonical CBOR map-key sort\n// (RFC 8949 §4.2.1, bytewise lex on encoded keys) places `cose_key`\n// (length-8 tstr, `0x68`) BEFORE `cose_sign1` (length-10 tstr, `0x6a`); the\n// schema property-order is irrelevant — the canonical encoder handles it.\nexport const SigEntrySchema = z\n .object({\n cose_key: ChunkedBytesArraySchema.optional(),\n cose_sign1: ChunkedBytesArraySchema,\n })\n .strict();\nexport type SigEntry = z.infer<typeof SigEntrySchema>;\n\n// =============================================================================\n// Supersedence\n// =============================================================================\n\nexport const SupersedesSchema = z.instanceof(Uint8Array).refine((b) => b.length === 32, {\n params: { code: 'SUPERSEDES_TX_INVALID_LENGTH' },\n});\nexport type Supersedes = z.infer<typeof SupersedesSchema>;\n\n// =============================================================================\n// Top-level record\n// =============================================================================\n//\n// `v == 1` is a literal — a future major (`v: 2`) MUST be rejected with\n// `SCHEMA_INVALID_LITERAL`. `z.literal(1)` preserves the narrow `1` type for\n// the inferred `PoeRecord[\"v\"]` (so consumers can dispatch on it) and emits\n// Zod's `invalid_value` code which the validator's mapper lifts to\n// `SCHEMA_INVALID_LITERAL`.\n//\n// `looseObject` admits extension keys (matching `^x-.+` or `^[a-z]+-.+`); the\n// validator's domain pass rejects unknown keys that match neither pattern with\n// `SCHEMA_UNKNOWN_FIELD`.\nexport const VersionLiteralSchema = z.literal(1);\n\nexport const PoeRecordSchema = z.looseObject({\n v: VersionLiteralSchema,\n items: z.array(ItemEntrySchema).optional(),\n merkle: z.array(MerkleCommitSchema).optional(),\n supersedes: SupersedesSchema.optional(),\n sigs: z.array(SigEntrySchema).optional(),\n crit: z.array(z.string()).optional(),\n});\nexport type PoeRecord = z.infer<typeof PoeRecordSchema>;\n\n// =============================================================================\n// Closed top-level base-key registry\n// =============================================================================\n//\n// Used by the validator's domain pass to distinguish unknown-typo keys from\n// well-formed extension keys (`^x-.+` / `^[a-z]+-.+`).\nexport const TOP_LEVEL_BASE_KEYS: ReadonlySet<string> = new Set([\n 'v',\n 'items',\n 'merkle',\n 'supersedes',\n 'sigs',\n 'crit',\n]);\n\n// Extension-key namespaces. Anchored at both ends so an\n// embedded newline cannot smuggle a multi-segment key past the check: `.`\n// excludes `\\n` in JS, and the `\\n?$` tail tolerates exactly ONE trailing\n// newline (matching the Python validator's `re.fullmatch(r'^(x-.+|[a-z]+-.+)$')`\n// semantics, where `$` likewise admits a single trailing `\\n`). So `x-note\\n`\n// is an extension key, but `x-a\\nb`, `x-note\\n\\n`, and `x-\\n` are not.\nexport const EXTENSION_KEY_VENDOR_RE = /^x-.+\\n?$/;\nexport const EXTENSION_KEY_COMPANION_RE = /^[a-z]+-.+\\n?$/;\n\nexport function isExtensionKey(k: string): boolean {\n return EXTENSION_KEY_VENDOR_RE.test(k) || EXTENSION_KEY_COMPANION_RE.test(k);\n}\n","// Every canonical-CBOR decode violation collapses to the single public CIP-309\n// taxonomy code MALFORMED_CBOR: indefinite-length (streaming) items, duplicate\n// keys, unsorted keys, non-minimal integer encodings, and invalid UTF-8 in text\n// strings. The taxonomy intentionally has one code for all of these; the\n// specific cause survives in the human-readable error message, not as a\n// separate code.\nexport type CanonicalCborErrorCode = 'MALFORMED_CBOR';\n\nexport class CanonicalCborError extends Error {\n readonly code: CanonicalCborErrorCode;\n\n constructor(code: CanonicalCborErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'CanonicalCborError';\n this.code = code;\n }\n}\n","import { cdeDecodeOptions, decode, encode } from 'cbor2';\nimport { sortCoreDeterministic } from 'cbor2/sorts';\n\nimport { CanonicalCborError } from './errors';\n\nexport type CanonicalCborValue =\n | null\n | boolean\n | number\n | bigint\n | string\n | Uint8Array\n | readonly CanonicalCborValue[]\n | { readonly [key: string]: CanonicalCborValue }\n | ReadonlyMap<string | number, CanonicalCborValue>;\n\nexport function encodeCanonicalCbor(value: CanonicalCborValue): Uint8Array {\n return encode(value, {\n cde: true,\n collapseBigInts: true,\n rejectDuplicateKeys: true,\n sortKeys: sortCoreDeterministic,\n });\n}\n\nexport function decodeCanonicalCbor(bytes: Uint8Array): unknown {\n try {\n return decode(bytes, {\n ...cdeDecodeOptions,\n rejectStreaming: true,\n rejectDuplicateKeys: true,\n // A CIP-309 record carries integers, byte/text strings, arrays, maps and\n // `null` — and nothing else. Without these rejections the major-type-7\n // surface leaks into the decoder: a float16/32/64 that happens to hold an\n // integral value (e.g. 1.0) silently decodes to the integer 1 and passes\n // a `z.literal(1)` / Number.isInteger schema check, so two byte strings\n // that are NOT byte-identical canonicalise to the same record. That\n // breaks the cross-implementation parity invariant (the Python twin\n // already rejects non-integer `v` / `enc.scheme` outright). Reject the\n // whole non-record surface — floats, negative zero, undefined, and\n // non-{true,false,null} simple values — so any such input surfaces as\n // MALFORMED_CBOR via mapDecodeError rather than decoding to a look-alike.\n rejectFloats: true,\n rejectNegativeZero: true,\n rejectUndefined: true,\n rejectSimple: true,\n });\n } catch (cause) {\n throw mapDecodeError(cause);\n }\n}\n\nfunction mapDecodeError(cause: unknown): CanonicalCborError {\n const message = cause instanceof Error ? cause.message : String(cause);\n const lower = message.toLowerCase();\n // Every canonical-decode violation collapses to the single public taxonomy\n // code MALFORMED_CBOR: indefinite-length (streaming) items, duplicate keys,\n // non-canonical (unsorted) key ordering, non-minimal integer encodings, and\n // invalid UTF-8 in text strings. cbor2 raises the SAME \"Duplicate or out of\n // order key\" message for both true duplicates AND distinct-but-unsorted keys,\n // so the two are indistinguishable by message — and per the CIP-309 taxonomy\n // both belong under MALFORMED_CBOR anyway. The specific cause survives in the\n // human-readable message below; for indefinite-length we state it explicitly\n // so the diagnostic is not lost when the code is collapsed.\n const isIndefinite = lower.includes('streaming') || lower.includes('indefinite');\n const detail = isIndefinite\n ? `indefinite-length items are not permitted in canonical CBOR: ${message}`\n : message;\n return new CanonicalCborError('MALFORMED_CBOR', `cbor decode failed: ${detail}`, { cause });\n}\n","// Permissive (non-canonical) CBOR decoder for outer wire decode (e.g. Cardano tx CBOR),\n// where the input is not constrained to be canonical RFC 8949 §4.2.1 form.\n//\n// CIP-309 records themselves MUST be canonical and MUST go through\n// `decodeCanonicalCbor`. This decoder\n// exists to peel the outer Cardano tx structure ([body, witness_set, is_valid,\n// auxiliary_data]) so the label-309 byte string can be re-encoded canonically\n// for validator + signature verification.\n\nimport { decode } from 'cbor2';\n\nexport function decodeCbor(bytes: Uint8Array): unknown {\n return decode(bytes);\n}\n","// CIP-309 v1 record encoder.\n//\n// Produces canonical CBOR bytes per RFC 8949 §4.2.1 deterministic encoding —\n// definite-length, sorted bytewise lex map keys, no duplicates, preferred\n// integer/float form. The canonical layer (`@cardanowall/crypto-core/cbor`)\n// configures `cbor2` with `cde: true, rejectDuplicateKeys: true`, so the\n// encoder's only job is to translate the validator-typed record shape into\n// the `CanonicalCborValue` algebra.\n//\n// Wire-shape contract:\n// - `items[i].hashes` is a CBOR MAP (text-keyed) — not an array of `{alg,h}`.\n// - `merkle[]` is a top-level array, peer to `items` and `sigs`.\n// - Each `sigs[i]` is a CBOR MAP `{cose_sign1, ? cose_key}` (canonical\n// sort places the optional `cose_key` BEFORE `cose_sign1`).\n// - The encryption envelope uses `scheme` (NOT `v`), `aead` (NOT `alg`),\n// `nonce` (NOT `iv`), `slots` (NOT `recipients`), `slots_mac` (NOT\n// `hdr_mac`); the KEM identifier is hoisted to envelope scope as `kem`.\n// - The passphrase block uses key name `passphrase` and `alg = \"argon2id\"`.\n//\n// Round-trip property: for every record `R` that the validator accepts,\n// validate(encode(R)).ok === true\n// && validate(encode(R)).record ≡ R (modulo CBOR-canonical key sort)\n\nimport { encodeCanonicalCbor, type CanonicalCborValue } from '@cardanowall/crypto-core/cbor';\n\nimport type {\n EncryptionEnvelope,\n ItemEntry,\n MerkleCommit,\n PassphraseBlock,\n PoeRecord,\n SigEntry,\n Slot,\n} from './schema';\n\ntype CborMap = { [key: string]: CanonicalCborValue };\n\nexport function encodePoeRecord(record: PoeRecord): Uint8Array {\n return encodeCanonicalCbor(recordToCbor(record));\n}\n\n// Helper: build the canonical-CBOR `record_body` (the bytes that record-level\n// `sigs[i]` signs over). The body is the full record map MINUS the `sigs`\n// field; producers prepend the 25-byte UTF-8 domain prefix\n// `cardano-poe-record-sig-v1` before invoking Ed25519 (the crypto-core\n// helper `buildCip309SigStructure` handles the prefix and `Sig_structure`\n// wrapping).\nexport function encodeRecordBodyForSigning(record: PoeRecord): Uint8Array {\n const body: CborMap = recordToCborInternal(record, /* includeSigs */ false);\n return encodeCanonicalCbor(body);\n}\n\nfunction recordToCbor(record: PoeRecord): CanonicalCborValue {\n return recordToCborInternal(record, /* includeSigs */ true);\n}\n\nfunction recordToCborInternal(record: PoeRecord, includeSigs: boolean): CborMap {\n const out: CborMap = { v: record.v };\n if (record.items !== undefined) out['items'] = record.items.map(itemToCbor);\n if (record.merkle !== undefined) out['merkle'] = record.merkle.map(merkleToCbor);\n if (record.supersedes !== undefined) out['supersedes'] = record.supersedes;\n if (includeSigs && record.sigs !== undefined) out['sigs'] = record.sigs.map(sigEntryToCbor);\n if (record.crit !== undefined) out['crit'] = record.crit.slice();\n // Preserve extension keys verbatim — they are part of the signed\n // `record_body` and MUST round-trip byte-identical.\n for (const [k, v] of Object.entries(record)) {\n if (\n k === 'v' ||\n k === 'items' ||\n k === 'merkle' ||\n k === 'supersedes' ||\n k === 'sigs' ||\n k === 'crit'\n ) {\n continue;\n }\n out[k] = v as CanonicalCborValue;\n }\n return out;\n}\n\nfunction itemToCbor(item: ItemEntry): CanonicalCborValue {\n const out: CborMap = { hashes: hashesToCbor(item.hashes) };\n if (item.uris !== undefined) {\n out['uris'] = item.uris.map((chunks) => chunks.slice());\n }\n if (item.enc !== undefined) {\n out['enc'] = envelopeToCbor(item.enc as EncryptionEnvelope);\n }\n return out;\n}\n\nfunction hashesToCbor(hashes: Readonly<Record<string, Uint8Array>>): CanonicalCborValue {\n // text-keyed CBOR map — canonical sort orders by encoded-key bytewise lex\n // automatically (`sha2-256` `0x68` precedes `blake2b-256` `0x6b`).\n const out: CborMap = {};\n for (const [alg, digest] of Object.entries(hashes)) {\n out[alg] = digest;\n }\n return out;\n}\n\nfunction merkleToCbor(commit: MerkleCommit): CanonicalCborValue {\n const out: CborMap = {\n alg: commit.alg,\n root: commit.root,\n leaf_count: commit.leaf_count,\n };\n if (commit.uris !== undefined) {\n out['uris'] = commit.uris.map((chunks) => chunks.slice());\n }\n return out;\n}\n\nfunction envelopeToCbor(enc: EncryptionEnvelope): CanonicalCborValue {\n const out: CborMap = {\n scheme: enc.scheme as CanonicalCborValue,\n aead: enc.aead,\n nonce: enc.nonce,\n };\n if (enc.kem !== undefined) out['kem'] = enc.kem;\n if (enc.slots !== undefined) out['slots'] = enc.slots.map(slotToCbor);\n if (enc.slots_mac !== undefined) out['slots_mac'] = enc.slots_mac;\n if (enc.passphrase !== undefined) out['passphrase'] = passphraseToCbor(enc.passphrase);\n return out;\n}\n\nfunction slotToCbor(slot: Slot): CanonicalCborValue {\n // KEM-driven slot serialization. The canonical encoder sorts map keys by\n // length-then-bytewise (RFC 8949 §4.2.1), so it emits `wrap` (4-byte key)\n // before `kem_ct` (6-byte key) and `epk` (3-byte key) before `wrap`\n // automatically — insertion order here is irrelevant to the wire bytes.\n //\n // - x25519: `{ epk: bstr(32), wrap: bstr(48) }`\n // - mlkem768x25519: `{ kem_ct: [ bstr, ... ], wrap: bstr(48) }` — `kem_ct`\n // is the already-chunked array (NOT re-chunked here), so the bytes match\n // what crypto-core committed to `slots_mac` byte-for-byte.\n if (slot.kem_ct !== undefined) {\n return { kem_ct: slot.kem_ct.map((c) => c), wrap: slot.wrap! };\n }\n return { epk: slot.epk!, wrap: slot.wrap! };\n}\n\nfunction passphraseToCbor(pp: PassphraseBlock): CanonicalCborValue {\n return {\n alg: pp.alg,\n salt: pp.salt,\n params: pp.params as { readonly [key: string]: CanonicalCborValue },\n };\n}\n\nfunction sigEntryToCbor(entry: SigEntry): CanonicalCborValue {\n const out: CborMap = { cose_sign1: entry.cose_sign1.map((b) => b) };\n if (entry.cose_key !== undefined) {\n out['cose_key'] = entry.cose_key.map((b) => b);\n }\n return out;\n}\n","import { blake2b } from '@noble/hashes/blake2.js';\n\nexport function blake2b256(input: Uint8Array): Uint8Array {\n return blake2b(input, { dkLen: 32 });\n}\n\n// CIP-19 stake-address derivation, used for the wallet path-2 signer binding,\n// requires the 28-byte BLAKE2b digest of the signer's Ed25519 public key.\n// The Cardano ledger encodes stake addresses as\n// `network_header_byte || Blake2b-224(stake_vk)`\n// per CIP-19, so this output length is fixed by spec.\nexport function blake2b224(input: Uint8Array): Uint8Array {\n return blake2b(input, { dkLen: 28 });\n}\n","import * as ed from '@noble/ed25519';\nimport { sha512 } from '@noble/hashes/sha2.js';\n\ned.hashes.sha512 = sha512;\n\n// Ed25519 group order L (= 2^252 + 27742317777372353535851937790883648493).\nconst L = ed.Point.CURVE().n;\n\nexport interface SignEd25519Opts {\n readonly seed: Uint8Array;\n readonly message: Uint8Array;\n}\n\nexport interface VerifyEd25519Opts {\n readonly publicKey: Uint8Array;\n readonly message: Uint8Array;\n readonly signature: Uint8Array;\n}\n\nexport interface GetPublicKeyEd25519Opts {\n readonly seed: Uint8Array;\n}\n\nexport function signEd25519(opts: SignEd25519Opts): Uint8Array {\n return ed.sign(opts.message, opts.seed);\n}\n\n// Little-endian 32-byte scalar → bigint.\nfunction leBytesToBigInt(bytes: Uint8Array): bigint {\n let value = 0n;\n for (let i = bytes.length - 1; i >= 0; i--) {\n value = (value << 8n) | BigInt(bytes[i]!);\n }\n return value;\n}\n\n// Strict (non-cofactored) Ed25519 verification per RFC 8032 §5.1.7, matching\n// libsodium/PyNaCl `crypto_sign_verify_detached` and ed25519-dalek\n// `verify_strict`. The cofactor-less check rejects every small-order /\n// torsion-component edge case in the C2SP/CCTV corpus, which noble's\n// `{ zip215: false }` mode does NOT (it remains cofactored: it checks\n// `[8]([S]B - [k]A - R) == 0`, accepting torsion components).\n//\n// The verification equation is the unscaled `[S]B == R + [k]A`, rewritten as\n// `[S]B - [k]A - R == identity`. We reject S >= L (non-canonical scalar) and\n// any small-order A or R up front, so a torsion component can never be smuggled\n// through the cofactor multiplication the cofactored variant performs.\nexport function verifyEd25519(opts: VerifyEd25519Opts): boolean {\n const { signature, message, publicKey } = opts;\n if (signature.length !== 64 || publicKey.length !== 32) return false;\n\n // S = LE(sig[32..64]); reject if not a canonical scalar (S >= L).\n const S = leBytesToBigInt(signature.subarray(32, 64));\n if (S >= L) return false;\n\n // Decode A (public key) and R (sig[0..32]) with the canonical (non-zip215)\n // point encoding; a non-canonical encoding throws and rejects.\n let A: ed.Point;\n let R: ed.Point;\n try {\n A = ed.Point.fromBytes(publicKey);\n R = ed.Point.fromBytes(signature.subarray(0, 32));\n } catch {\n return false;\n }\n\n // Reject small-order (cofactor-torsion) A or R: this is exactly the strictness\n // that distinguishes verify_strict from the cofactored check.\n if (A.isSmallOrder() || R.isSmallOrder()) return false;\n\n // k = SHA-512(R || A || M) reduced mod L.\n const k =\n leBytesToBigInt(ed.hash(concatBytes(signature.subarray(0, 32), publicKey, message))) % L;\n\n // Accept iff [S]B - [k]A - R == identity. `multiplyUnsafe` returns the\n // identity for a 0 scalar, but guard explicitly to avoid relying on that.\n const sB = S === 0n ? ed.Point.ZERO : ed.Point.BASE.multiplyUnsafe(S);\n const kA = k === 0n ? ed.Point.ZERO : A.multiplyUnsafe(k);\n return sB.subtract(kA).subtract(R).is0();\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n let total = 0;\n for (const p of parts) total += p.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\nexport function getPublicKeyEd25519(opts: GetPublicKeyEd25519Opts): Uint8Array {\n return ed.getPublicKey(opts.seed);\n}\n","// Isomorphic constant-time byte-equality. crypto-core is browser-safe by\n// design, so we cannot import `node:crypto.timingSafeEqual` — webpack rejects\n// the `node:` scheme in the browser bundle. A pure-JS XOR loop is constant-time\n// for equal-length inputs; length mismatch is a deliberate early-return (the\n// API surface itself leaks length, same as node's timingSafeEqual which throws).\nexport function compareCt(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n // Lengths are equal and `i` stays in-bounds, so both indexes are always\n // defined — no nullish guard is needed (and one would read as a guard for\n // an impossible case).\n for (let i = 0; i < a.length; i++) diff |= (a[i] as number) ^ (b[i] as number);\n return diff === 0;\n}\n","export type CoseVerifyErrorCode =\n | 'MALFORMED_SIG_COSE'\n | 'MALFORMED_SIG_COSE_SIGN1'\n | 'UNSUPPORTED_SIG_ALG'\n | 'KID_UNRESOLVED'\n | 'SIGNATURE_INVALID';\n\nexport class CoseVerifyError extends Error {\n readonly code: CoseVerifyErrorCode;\n\n constructor(code: CoseVerifyErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'CoseVerifyError';\n this.code = code;\n }\n}\n\nexport type CoseVerifyResult =\n | { ok: true; signerKey: Uint8Array; alg: number }\n | { ok: false; error: { code: CoseVerifyErrorCode; message: string } };\n","import {\n decodeCanonicalCbor,\n encodeCanonicalCbor,\n type CanonicalCborValue,\n} from '../cbor/canonical';\nimport { CanonicalCborError } from '../cbor/errors';\nimport { blake2b224 } from '../hash/blake2b-256';\nimport { signEd25519, verifyEd25519 } from '../sig/ed25519';\nimport { compareCt } from '../util/compare-ct';\n\nimport { CoseVerifyError, type CoseVerifyResult } from './errors';\n\nexport type CoseHeader = Map<number | string, unknown>;\n\n// CIP-309 v1 domain separator embedded as a prefix on `Sig_structure[3]`\n// (`to_sign`). The separator is\n// NOT placed in `Sig_structure[2]` (`external_aad`) because CIP-30 `signData`\n// — the only realistic wallet-signing path on Cardano — explicitly forbids a\n// non-empty `external_aad`. Pinning the prefix into the payload preserves the\n// anti-replay property while keeping wallet-produced signatures byte-identical\n// to verifier-side recomputation.\nexport const CARDANO_POE_SIG_DOMAIN_PREFIX = 'cardano-poe-record-sig-v1' as const;\n// Composer path-2 wallet flow consumes the prefix bytes directly\n// to assemble `toSign = prefix || canonical_cbor(record_body)` BEFORE calling\n// `walletSignData` (the wallet's `signData()` receives this concatenation as\n// its `payload` argument verbatim per CIP-30). The bytes constant is exported\n// so a composer can build the input without re-encoding the prefix at every\n// call site.\nexport const CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES = new TextEncoder().encode(\n CARDANO_POE_SIG_DOMAIN_PREFIX,\n);\n\n// Fail-fast: the prefix length is byte-pinned at 25 UTF-8 bytes. A different\n// runtime encoding would silently break round-tripping\n// against the reference vectors.\nif (CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length !== 25) {\n throw new Error(\n `cardano-poe-record-sig-v1 prefix must encode to exactly 25 UTF-8 bytes, got ${CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length}`,\n );\n}\n\nconst EMPTY_BYTES = new Uint8Array(0);\n\nexport interface CoseSign1Decoded {\n readonly protectedHeader: CoseHeader;\n // preserved for Sig_structure reconstruction — never re-encode the decoded header map (RFC 9052 §4.4)\n readonly protectedBytes: Uint8Array;\n readonly unprotectedHeader: CoseHeader;\n readonly payload: Uint8Array | null;\n readonly signature: Uint8Array;\n}\n\nexport interface BuildSigStructureArgs {\n readonly context: 'Signature1';\n readonly bodyProtectedBytes: Uint8Array;\n readonly externalAad: Uint8Array;\n readonly payload: Uint8Array;\n}\n\n// Raw RFC 9052 §4.4 Sig_structure builder. General-purpose: callers control\n// `external_aad` and `payload` exactly. For CIP-309 record signing use\n// `buildCip309SigStructure` instead — it enforces the CIP-309 record-signature invariants.\nexport function buildSigStructure(args: BuildSigStructureArgs): Uint8Array {\n return encodeCanonicalCbor([\n args.context,\n args.bodyProtectedBytes,\n args.externalAad,\n args.payload,\n ] as readonly CanonicalCborValue[]);\n}\n\nexport interface BuildCip309SigStructureArgs {\n readonly bodyProtectedBytes: Uint8Array;\n // Canonical CBOR of the record body with `sigs` removed.\n readonly recordBodyCbor: Uint8Array;\n}\n\n// CIP-309 v1 specialisation of `Sig_structure` (RFC 9052 §4.4 base structure):\n// to_sign = utf8(\"cardano-poe-record-sig-v1\") || canonical_cbor(record_body_minus_sigs)\n// Sig_structure = [ \"Signature1\", body_protected, h'' (empty), to_sign ]\n// Always forces `external_aad = h''` (empty bstr) — the CIP-30 wallet path\n// cannot carry a non-empty `external_aad`, so the domain separator lives in\n// `Sig_structure[3]` rather than `Sig_structure[2]`.\nexport function buildCip309SigStructure(args: BuildCip309SigStructureArgs): Uint8Array {\n const toSign = new Uint8Array(\n CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length + args.recordBodyCbor.length,\n );\n toSign.set(CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES, 0);\n toSign.set(args.recordBodyCbor, CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length);\n return buildSigStructure({\n context: 'Signature1',\n bodyProtectedBytes: args.bodyProtectedBytes,\n externalAad: EMPTY_BYTES,\n payload: toSign,\n });\n}\n\nexport interface EncodeCoseSign1Args {\n readonly protectedHeader: CoseHeader;\n readonly unprotectedHeader: CoseHeader;\n readonly payload: Uint8Array | null;\n readonly signature: Uint8Array;\n}\n\nexport function encodeCoseSign1(args: EncodeCoseSign1Args): Uint8Array {\n const protectedBytes =\n args.protectedHeader.size === 0\n ? EMPTY_BYTES\n : encodeCanonicalCbor(args.protectedHeader as CanonicalCborValue);\n return encodeCanonicalCbor([\n protectedBytes,\n args.unprotectedHeader as CanonicalCborValue,\n args.payload,\n args.signature,\n ] as readonly CanonicalCborValue[]);\n}\n\n// cbor2's decoder returns Map for integer-keyed maps but plain Object for empty\n// or string-keyed maps; normalise both representations to Map.\nfunction asCoseHeader(value: unknown): CoseHeader | null {\n if (value instanceof Map) return value as CoseHeader;\n if (value !== null && typeof value === 'object' && (value as object).constructor === Object) {\n return new Map(Object.entries(value as Record<string, unknown>));\n }\n return null;\n}\n\nexport function decodeCoseSign1(bytes: Uint8Array): CoseSign1Decoded {\n let arr: unknown;\n try {\n arr = decodeCanonicalCbor(bytes);\n } catch (cause) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'cose decode failed', { cause });\n }\n if (!Array.isArray(arr) || arr.length !== 4) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'expected 4-element array');\n }\n const [protectedBytesRaw, unprotectedRaw, payloadRaw, signatureRaw] = arr;\n if (!(protectedBytesRaw instanceof Uint8Array)) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'protected_bytes must be bytes');\n }\n const unprotectedHeader = asCoseHeader(unprotectedRaw);\n if (unprotectedHeader === null) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'unprotected header must be map');\n }\n if (payloadRaw !== null && !(payloadRaw instanceof Uint8Array)) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'payload must be bytes or null');\n }\n if (!(signatureRaw instanceof Uint8Array) || signatureRaw.length !== 64) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'signature must be 64 bytes');\n }\n let protectedHeader: CoseHeader;\n if (protectedBytesRaw.length === 0) {\n protectedHeader = new Map();\n } else {\n let decodedProtected: unknown;\n try {\n decodedProtected = decodeCanonicalCbor(protectedBytesRaw);\n } catch (cause) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'protected header decode failed', { cause });\n }\n const ph = asCoseHeader(decodedProtected);\n if (ph === null) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'protected header must decode to map');\n }\n // Empty protected header MUST encode as the single byte 0x40 (zero-length bstr),\n // not 0x41 0xA0 (a 1-byte bstr containing an empty CBOR map). RFC 9052 §3 +\n // CIP-309 canonical-CBOR mandate.\n if (ph.size === 0) {\n throw new CoseVerifyError(\n 'MALFORMED_SIG_COSE',\n 'empty protected header must encode as 0x40 (zero-length bstr), not as an empty map',\n );\n }\n protectedHeader = ph;\n }\n return {\n protectedHeader,\n protectedBytes: protectedBytesRaw,\n unprotectedHeader,\n payload: payloadRaw,\n signature: signatureRaw,\n };\n}\n\nexport type CoseSign1BuildErrorCode = 'SIGNER_NOT_PROVIDED' | 'SIGNER_AND_SEED_BOTH_PROVIDED';\n\nexport class CoseSign1BuildError extends Error {\n readonly code: CoseSign1BuildErrorCode;\n\n constructor(code: CoseSign1BuildErrorCode, message: string) {\n super(message);\n this.name = 'CoseSign1BuildError';\n this.code = code;\n }\n}\n\nexport interface CoseSign1Cip309BuildArgs {\n readonly protectedHeader: CoseHeader;\n readonly unprotectedHeader: CoseHeader;\n // Canonical CBOR of the record body with `sigs` removed. The\n // builder prepends the 25-byte UTF-8 domain prefix `cardano-poe-record-sig-v1`\n // internally — callers MUST NOT pre-concatenate it.\n readonly recordBodyCbor: Uint8Array;\n // EITHER the raw 32-byte Ed25519 seed (used by KAT tests, Python parity, and\n // the off-host signing helper) OR an injected signer closure that signs the\n // assembled Sig_structure bytes (composer-side use — keeps the private key\n // inside the unlock-store closure so it never escapes scope).\n // Exactly one of the two MUST be provided; mutual exclusion enforced at\n // runtime via CoseSign1BuildError.\n readonly signerSecretKey?: Uint8Array;\n readonly signer?: (sigStructureBytes: Uint8Array) => Uint8Array;\n}\n\n// CIP-309 v1 record-signature builder:\n// 1. compute `to_sign = utf8(\"cardano-poe-record-sig-v1\") || recordBodyCbor`\n// 2. Sig_structure = [ \"Signature1\", bodyProtected, h'', to_sign ]\n// 3. Ed25519-sign Sig_structure (via seed OR injected closure)\n// 4. emit COSE_Sign1 with payload = CBOR null (detached signature, mandatory)\nexport function coseSign1Cip309Build(args: CoseSign1Cip309BuildArgs): Uint8Array {\n if (args.signerSecretKey === undefined && args.signer === undefined) {\n throw new CoseSign1BuildError(\n 'SIGNER_NOT_PROVIDED',\n 'coseSign1Cip309Build requires either signerSecretKey or signer',\n );\n }\n if (args.signerSecretKey !== undefined && args.signer !== undefined) {\n throw new CoseSign1BuildError(\n 'SIGNER_AND_SEED_BOTH_PROVIDED',\n 'coseSign1Cip309Build accepts signerSecretKey XOR signer (not both)',\n );\n }\n const protectedBytes =\n args.protectedHeader.size === 0\n ? EMPTY_BYTES\n : encodeCanonicalCbor(args.protectedHeader as CanonicalCborValue);\n const sigStructureBytes = buildCip309SigStructure({\n bodyProtectedBytes: protectedBytes,\n recordBodyCbor: args.recordBodyCbor,\n });\n let signature: Uint8Array;\n if (args.signer !== undefined) {\n signature = args.signer(sigStructureBytes);\n if (!(signature instanceof Uint8Array) || signature.length !== 64) {\n throw new CoseSign1BuildError(\n 'SIGNER_NOT_PROVIDED',\n `injected signer must return a 64-byte Uint8Array; got ${signature instanceof Uint8Array ? `${signature.length}-byte Uint8Array` : typeof signature}`,\n );\n }\n } else {\n signature = signEd25519({ seed: args.signerSecretKey!, message: sigStructureBytes });\n }\n return encodeCoseSign1({\n protectedHeader: args.protectedHeader,\n unprotectedHeader: args.unprotectedHeader,\n payload: null,\n signature,\n });\n}\n\nexport interface CoseSign1Cip309VerifyArgs {\n readonly message: Uint8Array;\n // Canonical CBOR of the record body with `sigs` removed (verifier-recomputed;\n // the 25-byte UTF-8 prefix is prepended internally — callers\n // MUST NOT pre-concatenate it).\n readonly detachedRecordBodyCbor: Uint8Array;\n // Optional out-of-band signer key (path-2 wallet path resolves the key from\n // `sigs[i].cose_key`). Path-1 records carry the 32-byte raw Ed25519 pubkey\n // in the protected header at label 4 (`kid`) and need no out-of-band hint.\n readonly expectedSignerKey?: Uint8Array;\n}\n\n// CIP-309 v1 record-signature verifier:\n// - Decode COSE_Sign1\n// - Reject COSE_Sign1[2] != CBOR null (attached payload — including h'') as\n// MALFORMED_SIG_COSE_SIGN1\n// - Recompute to_sign = utf8(\"cardano-poe-record-sig-v1\") || detachedRecordBodyCbor\n// - Sig_structure = [ \"Signature1\", protectedBytes, h'', to_sign ]\n// - Strict Ed25519 verify (RFC 8032 §5.1.7 — `zip215: false` per ed25519.ts)\n//\n// The verifier does NOT accept an `externalAad` argument: CIP-309 v1 pins\n// `external_aad = h''` and any deviation would either silently weaken the\n// domain separator or quietly accept malformed records. If a future CIP\n// revision re-enables external_aad, this helper takes a v-bump.\nexport function coseSign1Cip309Verify(args: CoseSign1Cip309VerifyArgs): CoseVerifyResult {\n let decoded: CoseSign1Decoded;\n try {\n decoded = decodeCoseSign1(args.message);\n } catch (e) {\n if (e instanceof CoseVerifyError) {\n return { ok: false, error: { code: e.code, message: 'errors.cose.malformed' } };\n }\n if (e instanceof CanonicalCborError) {\n return {\n ok: false,\n error: { code: 'MALFORMED_SIG_COSE', message: 'errors.cose.malformed_cbor' },\n };\n }\n throw e;\n }\n // CIP-309 v1 mandate: COSE_Sign1[2] (payload field) MUST be CBOR `null` (0xF6).\n // Any non-null payload — including a zero-length byte string `h''` — MUST\n // be rejected as MALFORMED_SIG_COSE_SIGN1.\n if (decoded.payload !== null) {\n return {\n ok: false,\n error: {\n code: 'MALFORMED_SIG_COSE_SIGN1',\n message: 'errors.cose.attached_payload_forbidden',\n },\n };\n }\n const alg = decoded.protectedHeader.get(1);\n if (typeof alg !== 'number' || alg !== -8) {\n return {\n ok: false,\n error: { code: 'UNSUPPORTED_SIG_ALG', message: 'errors.cose.unsupported_alg' },\n };\n }\n const kidRaw = decoded.protectedHeader.get(4);\n let signerKey: Uint8Array | undefined;\n if (kidRaw instanceof Uint8Array && kidRaw.length === 32) {\n signerKey = kidRaw;\n } else if (args.expectedSignerKey instanceof Uint8Array && args.expectedSignerKey.length === 32) {\n signerKey = args.expectedSignerKey;\n }\n if (signerKey === undefined) {\n return {\n ok: false,\n error: { code: 'KID_UNRESOLVED', message: 'errors.cose.kid_unresolved' },\n };\n }\n // When both a protected-header kid AND an expectedSignerKey are provided,\n // require they agree (constant-time). A protected kid that disagrees with\n // the caller's out-of-band binding is a misuse, not a transient mismatch.\n if (\n kidRaw instanceof Uint8Array &&\n kidRaw.length === 32 &&\n args.expectedSignerKey instanceof Uint8Array &&\n args.expectedSignerKey.length === 32 &&\n !compareCt(kidRaw, args.expectedSignerKey)\n ) {\n return {\n ok: false,\n error: { code: 'KID_UNRESOLVED', message: 'errors.cose.kid_mismatch' },\n };\n }\n // CIP-8 `hashed = true` mode (the wallet-signed path-2 variant). The unprotected\n // header carries the literal text key `\"hashed\"` with boolean value `true`\n // (text-keyed CBOR maps decode to `Map<string, unknown>` via cbor2). When\n // set, both producer and verifier build `Sig_structure[3] = Blake2b-224(to_sign)`\n // (28-byte digest of the FULL `to_sign` payload including the 25-byte\n // domain prefix). When absent or false, the standard non-hashed path\n // applies unchanged.\n const hashedFlag = decoded.unprotectedHeader.get('hashed');\n let sigStructureBytes: Uint8Array;\n if (hashedFlag === true) {\n const toSign = new Uint8Array(\n CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length + args.detachedRecordBodyCbor.length,\n );\n toSign.set(CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES, 0);\n toSign.set(args.detachedRecordBodyCbor, CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length);\n const hashedPayload = blake2b224(toSign);\n sigStructureBytes = buildSigStructure({\n context: 'Signature1',\n bodyProtectedBytes: decoded.protectedBytes,\n externalAad: EMPTY_BYTES,\n payload: hashedPayload,\n });\n } else {\n sigStructureBytes = buildCip309SigStructure({\n bodyProtectedBytes: decoded.protectedBytes,\n recordBodyCbor: args.detachedRecordBodyCbor,\n });\n }\n const valid = verifyEd25519({\n publicKey: signerKey,\n message: sigStructureBytes,\n signature: decoded.signature,\n });\n if (!valid) {\n return {\n ok: false,\n error: { code: 'SIGNATURE_INVALID', message: 'errors.cose.signature_invalid' },\n };\n }\n return { ok: true, signerKey, alg };\n}\n","// CIP-30 / RFC 9052 §7 COSE_Key extraction for the Ed25519 sig path.\n//\n// CIP-30 wallets that don't put a 32-byte raw Ed25519 pubkey in the COSE_Sign1\n// protected header instead deliver the signer key as a separate `cbor<COSE_Key>`\n// blob, surfaced in the CIP-309 record under the top-level `signer_keys` field.\n// This helper decodes one such blob and returns the underlying 32-byte Ed25519\n// pubkey, or `null` when the blob is malformed, uses an unexpected key type /\n// curve, or has the wrong `x` length.\n//\n// The expected COSE_Key shape (RFC 9053 §7.2 + RFC 8152 §13):\n// {\n// 1 (kty): 1 // OKP\n// 3 (alg): -8 // EdDSA — OPTIONAL but if present MUST be -8\n// -1 (crv): 6 // Ed25519\n// -2 (x): <32 byte raw public key>\n// }\n\nimport { decodeCanonicalCbor } from '../cbor/canonical';\n\nconst COSE_KEY_LABEL_KTY = 1;\nconst COSE_KEY_LABEL_ALG = 3;\nconst COSE_KEY_LABEL_CRV = -1;\nconst COSE_KEY_LABEL_X = -2;\n\nconst KTY_OKP = 1;\nconst ALG_EDDSA = -8;\nconst CRV_ED25519 = 6;\n\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\n\nfunction asMap(value: unknown): Map<unknown, unknown> | null {\n if (value instanceof Map) return value as Map<unknown, unknown>;\n if (value !== null && typeof value === 'object' && (value as object).constructor === Object) {\n return new Map(Object.entries(value as Record<string, unknown>));\n }\n return null;\n}\n\nexport function parseCoseKeyEd25519(blob: Uint8Array): Uint8Array | null {\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(blob);\n } catch {\n return null;\n }\n const map = asMap(decoded);\n if (map === null) return null;\n\n const kty = map.get(COSE_KEY_LABEL_KTY);\n if (typeof kty !== 'number' || kty !== KTY_OKP) return null;\n\n const crv = map.get(COSE_KEY_LABEL_CRV);\n if (typeof crv !== 'number' || crv !== CRV_ED25519) return null;\n\n if (map.has(COSE_KEY_LABEL_ALG)) {\n const alg = map.get(COSE_KEY_LABEL_ALG);\n if (typeof alg !== 'number' || alg !== ALG_EDDSA) return null;\n }\n\n const x = map.get(COSE_KEY_LABEL_X);\n if (!(x instanceof Uint8Array) || x.length !== ED25519_PUBLIC_KEY_LENGTH) return null;\n\n return x;\n}\n","// CIP-309 v1 chunked-bytes and chunked-text helpers.\n//\n// The Cardano ledger CDDL constrains every `transaction_metadatum` byte string\n// (`bstr`) and text string (`tstr`) to ≤ 64 bytes. CIP-309 therefore carries\n// any logical value larger than 64 bytes as an ARRAY of ≤ 64-byte chunks. Two\n// chunked shapes exist:\n//\n// * `bytes-chunk-array` — `[ 1* bstr .size (1..64) ]` — used for chunked\n// `COSE_Sign1` bytes (`sigs[i].cose_sign1`) and the chunked\n// `cbor<COSE_Key>` blob (`sigs[i].cose_key`).\n// * `uri-chunk-array` — `[ 1* tstr .size (1..64) ]` — used as the inner\n// element of `items[i].uris` and `merkle[i].uris`.\n//\n// Two reconstruction invariants are normative:\n//\n// 1. **Per-chunk size.** `[1, 64]` bytes (zero-length chunks rejected\n// identically to oversized chunks). The validator's schema layer enforces\n// this; the helpers here assume the schema gate has fired.\n// 2. **UTF-8 codepoint integrity (text only).** The reconstructed\n// concatenation MUST be valid UTF-8. The canonical-CBOR decoder already\n// rejects any `tstr` that is not valid UTF-8 (→ `MALFORMED_CBOR`) before\n// these helpers run, so each chunk arrives as a well-formed string; the\n// `TextDecoder({ fatal: true })` pass below is the residual structural\n// guard.\n\nconst CHUNK_MAX_BYTES = 64;\n\nconst UTF8_ENCODER = new TextEncoder();\n\n/**\n * Split a logical byte string into ≤ 64-byte CBOR-bytes chunks\n * (`bytes-chunk-array`). Always returns a non-empty array.\n *\n * For empty inputs, returns `[<empty>]` so the caller's schema gate fails\n * later via `CHUNK_TOO_LARGE` (zero-length chunks are rejected). Real callers\n * feed COSE_Sign1 / cbor<COSE_Key> byte strings, which are never empty.\n */\nexport function chunkBytes(value: Uint8Array): Uint8Array[] {\n if (value.length === 0) return [new Uint8Array(0)];\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < value.length; i += CHUNK_MAX_BYTES) {\n chunks.push(value.subarray(i, Math.min(i + CHUNK_MAX_BYTES, value.length)));\n }\n return chunks;\n}\n\n/**\n * Reverse of {@link chunkBytes}: concatenate chunked bytes (`sigs[i].cose_sign1`,\n * `sigs[i].cose_key`) into a single buffer for downstream CBOR/COSE decode.\n * The validator-layer schema enforces the per-chunk size + non-empty-array\n * invariants before this helper runs, so it makes no length checks.\n */\nexport function bytesChunkArrayConcat(chunks: ReadonlyArray<Uint8Array>): Uint8Array {\n let total = 0;\n for (const c of chunks) total += c.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const c of chunks) {\n out.set(c, offset);\n offset += c.length;\n }\n return out;\n}\n\nexport type ReconstructUriResult =\n | { ok: true; uri: string }\n | { ok: false; code: 'INVALID_URI'; reason: string };\n\n/**\n * Reconstruct a chunked URI (`uri-chunk-array`) into its logical string.\n *\n * The chunks arrive as JS strings produced by the canonical-CBOR decoder,\n * which already rejects any non-UTF-8 `tstr` (surfacing it upstream as\n * `MALFORMED_CBOR`) — so by the time this helper runs the only structural\n * task left is to byte-concatenate and decode. We re-encode each chunk to its\n * UTF-8 bytes, concatenate, and decode the whole with `{ fatal: true }`. A\n * conformant producer never splits a multi-byte codepoint across chunks (the\n * Cardano 64-byte cap is applied on codepoint boundaries), so this decode\n * succeeds for every well-formed record; the `INVALID_URI` branch is the\n * residual guard for a byte sequence that does not reconstruct to valid UTF-8.\n *\n * Per-scheme shape validation (the IPFS CID profile) and absolute-URI /\n * fragment-identifier / scheme-set checks fire in `validator.ts`, NOT here —\n * this helper is structural-only.\n */\nexport function reconstructChunkedUri(chunks: ReadonlyArray<string>): ReconstructUriResult {\n const merged = bytesChunkArrayConcat(chunks.map((c) => UTF8_ENCODER.encode(c)));\n try {\n const uri = new TextDecoder('utf-8', { fatal: true }).decode(merged);\n return { ok: true, uri };\n } catch (cause) {\n return {\n ok: false,\n code: 'INVALID_URI',\n reason: cause instanceof Error ? cause.message : String(cause),\n };\n }\n}\n\n/**\n * Chunk a URI string into `[ tstr .size (1..64) ]`, splitting on UTF-8 byte\n * boundaries so no multi-byte codepoint straddles a chunk.\n *\n * For pure-ASCII URIs (the common `ar://`, `ipfs://` cases) this collapses\n * to plain 64-byte byte-slice chunks. For URIs with non-ASCII path components\n * (rare but possible — RFC 3986 §2.5 IRIs / percent-encoded UTF-8) the\n * algorithm rewinds to the nearest codepoint boundary at each chunk break.\n */\nexport function chunkUri(uri: string): string[] {\n const bytes = UTF8_ENCODER.encode(uri);\n if (bytes.length === 0) return [''];\n if (bytes.length <= CHUNK_MAX_BYTES) return [uri];\n const decoder = new TextDecoder('utf-8', { fatal: true });\n const chunks: string[] = [];\n let cursor = 0;\n while (cursor < bytes.length) {\n let end = Math.min(cursor + CHUNK_MAX_BYTES, bytes.length);\n // Rewind to the start of the previous UTF-8 codepoint if we landed in\n // the middle of a multibyte sequence. UTF-8 continuation bytes match\n // 0b10xx_xxxx; rewind while the byte at `end` is a continuation.\n while (end < bytes.length && (bytes[end]! & 0xc0) === 0x80) end--;\n chunks.push(decoder.decode(bytes.subarray(cursor, end)));\n cursor = end;\n }\n return chunks;\n}\n","// CIP-309 v1 error-code catalogue — single source of truth for the\n// structural-validator codes (Part A) and the verifier-layer codes (Part B)\n// that downstream verifiers re-export from this package.\n//\n// The structural validator emits ONLY Part A codes. Part B codes are\n// re-exported so consumers can `import { ErrorCode } from '@cardanowall/poe-standard'`\n// and dispatch on a single union type without round-tripping through the\n// verifier package.\n//\n// Codes are SCREAMING_SNAKE_CASE and MUST match the canonical taxonomy\n// byte-exact across the TS/PY/RS implementations — no lowercase synonyms,\n// no `schema_*`-prefixed parser-internal codes.\n\n// =============================================================================\n// Part A — structural validator codes\n// =============================================================================\nexport const STRUCTURAL_ERROR_CODES = [\n // CBOR decode layer. A single code covers every canonical-decode failure —\n // malformed/truncated bytes, indefinite-length encodings, non-canonical\n // (unsorted) map-key ordering, duplicate map keys, non-minimal integers, and\n // invalid UTF-8 — by design (no separate duplicate-key code).\n 'MALFORMED_CBOR',\n // Generic schema-layer\n 'SCHEMA_TYPE_MISMATCH',\n 'SCHEMA_MISSING_REQUIRED',\n 'SCHEMA_UNKNOWN_FIELD',\n 'SCHEMA_INVALID_LITERAL',\n 'SCHEMA_EMPTY_RECORD',\n // Hash-map\n 'HASH_DIGEST_LENGTH_MISMATCH',\n 'UNSUPPORTED_HASH_ALG',\n // Top-level `merkle[]`\n 'UNSUPPORTED_MERKLE_COMMIT_ALG',\n // URI / chunking. A chunk whose bytes do not reconstruct to valid UTF-8\n // surfaces as MALFORMED_CBOR at decode (cbor2 rejects invalid-UTF-8 tstr)\n // or, in the residual reconstruct guard, as INVALID_URI — there is no\n // separate codepoint-split code.\n 'INVALID_URI',\n 'CHUNK_TOO_LARGE',\n // Encryption envelope\n 'UNAUTHENTICATED_CIPHER_FORBIDDEN',\n 'UNSUPPORTED_AEAD_ALG',\n 'NONCE_LENGTH_MISMATCH',\n 'UNSUPPORTED_ENVELOPE_SCHEME',\n 'ENC_SLOTS_EMPTY',\n 'ENC_SLOT_INVALID_SHAPE',\n 'UNSUPPORTED_KEM_ALG',\n 'ENC_KEM_REQUIRED',\n 'KEM_EPK_LENGTH_MISMATCH',\n 'KEM_CT_LENGTH_MISMATCH',\n 'WRAP_LENGTH_MISMATCH',\n 'ENC_SLOTS_MAC_INVALID_LENGTH',\n 'ENC_SLOTS_MAC_REQUIRED',\n 'ENC_SLOTS_REQUIRED',\n 'ENC_EXCLUSIVITY_VIOLATION',\n 'ENC_NO_KEY_PATH',\n 'ENC_REQUIRES_CONTENT_HASH',\n 'ENC_PASSPHRASE_ALG_UNSUPPORTED',\n 'ENC_PASSPHRASE_SALT_TOO_SHORT',\n 'ENC_PASSPHRASE_SALT_TOO_LONG',\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n 'ENC_PASSPHRASE_PARAMS_EXCEED_POLICY',\n // Signatures\n 'MALFORMED_SIG_COSE_SIGN1',\n 'SIGNATURE_UNSUPPORTED',\n 'SIG_ENTRY_INVALID_SHAPE',\n 'SIG_ENTRY_KID_COSE_KEY_CONFLICT',\n 'SIG_PRIVATE_KEY_LEAKED',\n // Supersedence\n 'SUPERSEDES_TX_INVALID_LENGTH',\n // Forward-compat critical extensions\n 'EXTENSION_UNSUPPORTED_CRITICAL',\n 'CRIT_SHAPE_INVALID',\n] as const;\n\n// =============================================================================\n// Part B — verifier-layer codes\n// Re-exported so downstream verifiers can dispatch on a single union.\n// The structural validator NEVER emits these.\n// =============================================================================\nexport const VERIFIER_ERROR_CODES = [\n 'METADATA_NOT_FOUND',\n 'INSUFFICIENT_CONFIRMATIONS',\n 'SIGNATURE_INVALID',\n 'SIGNER_KEY_UNRESOLVED',\n 'WALLET_ADDRESS_MISMATCH',\n 'URI_TARGET_FORBIDDEN',\n 'URI_INTEGRITY_MISMATCH',\n 'URI_FETCH_FAILED',\n 'CONTENT_UNAVAILABLE',\n 'CIPHERTEXT_UNAVAILABLE',\n 'PROVIDER_UNAVAILABLE',\n 'SERVICE_INDEPENDENCE_VIOLATION',\n 'WRONG_DECRYPTION_INPUT_SHAPE',\n 'WRONG_RECIPIENT_KEY',\n 'TAMPERED_HEADER',\n 'TAMPERED_CIPHERTEXT',\n 'KDF_DERIVATION_FAILED',\n 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED',\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'MERKLE_ROOT_MISMATCH',\n 'MERKLE_LEAVES_UNAVAILABLE',\n 'MERKLE_LEAVES_INFORMATIVE_FORM',\n 'MERKLE_UNSUPPORTED',\n 'OUT_OF_PROFILE_SKIPPED',\n] as const;\n\nexport const ERROR_CODES = [...STRUCTURAL_ERROR_CODES, ...VERIFIER_ERROR_CODES] as const;\n\nexport type StructuralErrorCode = (typeof STRUCTURAL_ERROR_CODES)[number];\nexport type VerifierErrorCode = (typeof VERIFIER_ERROR_CODES)[number];\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\n// Severity classification. Codes not listed are `error` by default.\n//\n// `info` — a deliberate non-check (algorithm out of profile, unrecognised\n// signature algorithm at the opt-in informational tier).\n//\n// `warning` — a non-fatal anomaly that occurred at runtime but did not\n// invalidate the record (e.g. a transient gateway failure, partial leaves\n// availability).\n//\n// `MERKLE_UNSUPPORTED` / `OUT_OF_PROFILE_SKIPPED` carry dual severity\n// (`info` when another commitment was validated; `error` for the\n// merkle-only / strict-mode case). The verifier emits the resolved severity\n// per-issue; this map records the default `info` reading.\nexport type Severity = 'error' | 'warning' | 'info';\n\nexport const SEVERITY: Readonly<Record<ErrorCode, Severity>> = Object.freeze({\n // --- Part A ---\n MALFORMED_CBOR: 'error',\n SCHEMA_TYPE_MISMATCH: 'error',\n SCHEMA_MISSING_REQUIRED: 'error',\n SCHEMA_UNKNOWN_FIELD: 'error',\n SCHEMA_INVALID_LITERAL: 'error',\n SCHEMA_EMPTY_RECORD: 'error',\n HASH_DIGEST_LENGTH_MISMATCH: 'error',\n UNSUPPORTED_HASH_ALG: 'error',\n UNSUPPORTED_MERKLE_COMMIT_ALG: 'error',\n INVALID_URI: 'error',\n CHUNK_TOO_LARGE: 'error',\n UNAUTHENTICATED_CIPHER_FORBIDDEN: 'error',\n UNSUPPORTED_AEAD_ALG: 'error',\n NONCE_LENGTH_MISMATCH: 'error',\n UNSUPPORTED_ENVELOPE_SCHEME: 'error',\n ENC_SLOTS_EMPTY: 'error',\n ENC_SLOT_INVALID_SHAPE: 'error',\n UNSUPPORTED_KEM_ALG: 'error',\n ENC_KEM_REQUIRED: 'error',\n KEM_EPK_LENGTH_MISMATCH: 'error',\n KEM_CT_LENGTH_MISMATCH: 'error',\n WRAP_LENGTH_MISMATCH: 'error',\n ENC_SLOTS_MAC_INVALID_LENGTH: 'error',\n ENC_SLOTS_MAC_REQUIRED: 'error',\n ENC_SLOTS_REQUIRED: 'error',\n ENC_EXCLUSIVITY_VIOLATION: 'error',\n ENC_NO_KEY_PATH: 'error',\n ENC_REQUIRES_CONTENT_HASH: 'error',\n ENC_PASSPHRASE_ALG_UNSUPPORTED: 'error',\n ENC_PASSPHRASE_SALT_TOO_SHORT: 'error',\n ENC_PASSPHRASE_SALT_TOO_LONG: 'error',\n ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW: 'error',\n ENC_PASSPHRASE_PARAMS_EXCEED_POLICY: 'error',\n MALFORMED_SIG_COSE_SIGN1: 'error',\n SIGNATURE_UNSUPPORTED: 'info',\n SIG_ENTRY_INVALID_SHAPE: 'error',\n SIG_ENTRY_KID_COSE_KEY_CONFLICT: 'error',\n SIG_PRIVATE_KEY_LEAKED: 'error',\n SUPERSEDES_TX_INVALID_LENGTH: 'error',\n EXTENSION_UNSUPPORTED_CRITICAL: 'error',\n CRIT_SHAPE_INVALID: 'error',\n // --- Part B ---\n METADATA_NOT_FOUND: 'error',\n INSUFFICIENT_CONFIRMATIONS: 'info',\n SIGNATURE_INVALID: 'error',\n SIGNER_KEY_UNRESOLVED: 'error',\n WALLET_ADDRESS_MISMATCH: 'error',\n URI_TARGET_FORBIDDEN: 'error',\n URI_INTEGRITY_MISMATCH: 'error',\n URI_FETCH_FAILED: 'warning',\n CONTENT_UNAVAILABLE: 'error',\n CIPHERTEXT_UNAVAILABLE: 'error',\n PROVIDER_UNAVAILABLE: 'error',\n SERVICE_INDEPENDENCE_VIOLATION: 'error',\n WRONG_DECRYPTION_INPUT_SHAPE: 'error',\n WRONG_RECIPIENT_KEY: 'error',\n TAMPERED_HEADER: 'error',\n TAMPERED_CIPHERTEXT: 'error',\n KDF_DERIVATION_FAILED: 'error',\n SCHEMA_MERKLE_LEAF_COUNT_MISMATCH: 'error',\n SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED: 'error',\n SCHEMA_MERKLE_LEAVES_MALFORMED: 'error',\n MERKLE_ROOT_MISMATCH: 'error',\n MERKLE_LEAVES_UNAVAILABLE: 'warning',\n MERKLE_LEAVES_INFORMATIVE_FORM: 'info',\n // Dual-severity — default reading is `info`; the verifier promotes to\n // `error` for merkle-only records (no `items[]` content claim was\n // validated in the same record).\n MERKLE_UNSUPPORTED: 'info',\n // Dual-severity — default reading is `info` (render mode); strict\n // end-to-end verifiers promote to `error`.\n OUT_OF_PROFILE_SKIPPED: 'info',\n});\n\nexport function severityOf(code: ErrorCode): Severity {\n return SEVERITY[code];\n}\n","// CIP-309 v1 structural validator (the Part A structural-validation role).\n//\n// Pure function over CBOR bytes — performs no I/O, opens no socket, decodes\n// no ciphertext. Cryptographic signature verification, chain resolution, URI\n// fetching, decryption, and confirmation-depth checks are the verifier's\n// concern (the Part B verifier role) and live in `@cardanowall/sdk-ts`.\n//\n// Pipeline:\n// Step 1 Resource boundary — n/a here (validator has no fixed cap;\n// transactions are bounded by maxTxSize\n// enforced at submission)\n// Step 2 Canonical CBOR decode — `decodeCanonicalCbor` from crypto-core\n// surfaces malformed / non-canonical /\n// duplicate-key inputs as typed errors.\n// Step 3 Schema parse — Zod schema in `./schema.ts`; the mapper\n// below lifts each Zod issue to a\n// SCREAMING_SNAKE structural code.\n// Step 4 Domain checks — cross-field rules, registry membership,\n// URI reconstruction + per-scheme shape\n// (the IPFS CID profile), `enc`\n// cross-field invariants, `sigs[i]`\n// closed-map check + COSE_Sign1 structural\n// decode (path-1/path-2 mutual exclusion,\n// `SIG_PRIVATE_KEY_LEAKED` guard).\n// Step 5 Result emission — `{ ok: true, record, info?, warnings? }`\n// or `{ ok: false, issues }`.\n//\n// The validator NEVER throws — failure paths route through the discriminated\n// `ValidateResult` union so callers handle errors as data.\n\nimport { z } from 'zod';\n\nimport { decodeCanonicalCbor } from '@cardanowall/crypto-core/cbor';\nimport { CoseVerifyError, decodeCoseSign1 } from '@cardanowall/crypto-core/cose';\n\nimport { bytesChunkArrayConcat, reconstructChunkedUri } from './chunked';\nimport { SEVERITY, type ErrorCode, type Severity } from './error-codes';\nimport {\n EncryptionEnvelopeSchema,\n isExtensionKey,\n PoeRecordSchema,\n TOP_LEVEL_BASE_KEYS,\n type ItemEntry,\n type MerkleCommit,\n type PoeRecord,\n type SigEntry,\n type Slot,\n} from './schema';\n\n// =============================================================================\n// Registries\n// =============================================================================\n\n// Content-hash algorithm registry. Map value = digest length.\nconst HASH_ALG_LENGTHS: Readonly<Record<string, number>> = {\n 'sha2-256': 32,\n 'blake2b-256': 32,\n};\n\n// Merkle list-commitment algorithm registry.\nconst MERKLE_COMMIT_ALG_LENGTHS: Readonly<Record<string, number>> = {\n 'rfc9162-sha256': 32,\n};\n\n// Content AEAD registry. Value = nonce length.\nconst AEAD_NONCE_LENGTHS: Readonly<Record<string, number>> = {\n 'xchacha20-poly1305': 24,\n};\n\n// Unauthenticated-cipher family. An `enc.aead` naming any of these is rejected\n// with `UNAUTHENTICATED_CIPHER_FORBIDDEN` (not the generic `UNSUPPORTED_AEAD_ALG`)\n// so the failure names the integrity hazard. Two arms:\n// - block-cipher modes with no integrity (`cbc`, `ctr`, `ecb`, `cfb`, `ofb`)\n// appearing as a delimited token, which matches every key-size spelling\n// (`aes-cbc`, `aes-256-cbc`, `aes-128-cbc`, `des-ede3-cbc`, …);\n// - legacy stream/block ciphers as a leading token (`rc4`, `des`, `3des`).\n// The token delimiters keep the authenticated AEADs (`aes-256-gcm`,\n// `chacha20-poly1305`, `xchacha20-poly1305`) from matching. The trailing\n// boundary tolerates a single trailing `\\n` (`\\n?$`) so a forbidden cipher\n// cannot evade the denylist by appending one newline (`aes-256-cbc\\n` /\n// `rc4\\n`), matching the Python/Rust validators.\nconst UNAUTHENTICATED_CIPHER_RE =\n /(?:^|[-_])(?:cbc|ctr|ecb|cfb|ofb)(?:[-_]|\\n?$)|^(?:rc4|des|3des)(?:[-_]|\\n?$)/i;\n\n// KEM registry, expressed as a per-KEM slot DESCRIPTOR.\n//\n// Each registered KEM pins the exact recipient-slot shape:\n//\n// - x25519: `{ epk: bstr(32), wrap: bstr(48) }` — classical\n// ephemeral-static X25519. The per-slot `epk` is the 32-byte ephemeral\n// public key.\n// - mlkem768x25519: `{ kem_ct: <1120-byte X-Wing enc>, wrap: bstr(48) }` —\n// the X-Wing hybrid (ML-KEM-768 + X25519). The ciphertext is carried as a\n// chunked byte-string array (`kem_ct`) that MUST reassemble to exactly\n// 1120 bytes; there is NO per-slot `epk` on the hybrid path.\n//\n// A descriptor declares the slot's *ciphertext-bearing* field (`epk` for a\n// classical KEM, `kem_ct` for a hybrid) and its expected reassembled byte\n// length. `wrap` is 48 bytes for every KEM (32-byte CEK + 16-byte AEAD tag).\n// The validator branches on the descriptor's `field` to know which field MUST\n// be present and which MUST be absent, so adding a future KEM is a one-line\n// registry edit, not a new code path.\ntype KemSlotField = 'epk' | 'kem_ct';\ninterface KemSlotDescriptor {\n /** The ciphertext-bearing slot field this KEM uses. */\n readonly field: KemSlotField;\n /** Expected length of that field (reassembled length for a chunked field). */\n readonly fieldLength: number;\n /** `wrap` length — 32-byte CEK + 16-byte AEAD tag. */\n readonly wrapLength: number;\n}\nconst KEM_SLOT_DESCRIPTORS: Readonly<Record<string, KemSlotDescriptor>> = {\n x25519: { field: 'epk', fieldLength: 32, wrapLength: 48 },\n mlkem768x25519: { field: 'kem_ct', fieldLength: 1120, wrapLength: 48 },\n};\n\n// The length-mismatch code emitted when a slot's ciphertext-bearing field has\n// the wrong (reassembled) length, keyed by the descriptor's `field`.\nconst KEM_FIELD_LENGTH_CODE: Readonly<Record<KemSlotField, ErrorCode>> = {\n epk: 'KEM_EPK_LENGTH_MISMATCH',\n kem_ct: 'KEM_CT_LENGTH_MISMATCH',\n};\n\n// Passphrase KDF registry.\nconst PASSPHRASE_KDF_ALGS: ReadonlySet<string> = new Set(['argon2id']);\n\n// Signature-algorithm baseline. `-8` (EdDSA, curve-agnostic — pinned to\n// Ed25519) is the mandatory baseline; `-19` (Ed25519 fully-specified) is\n// optional and verified identically under the Ed25519 primitive when\n// accepted. The reference validator accepts both; anything else surfaces as\n// `SIGNATURE_UNSUPPORTED` (info-severity).\nconst KNOWN_SIG_ALG_IDS: ReadonlySet<number> = new Set([-8, -19]);\n\n// =============================================================================\n// Result types\n// =============================================================================\n\nexport interface ValidationIssue {\n readonly code: ErrorCode;\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n readonly severity: Severity;\n}\n\nexport type ValidateResult =\n | {\n readonly ok: true;\n readonly record: PoeRecord;\n readonly warnings?: ReadonlyArray<ValidationIssue>;\n readonly info?: ReadonlyArray<ValidationIssue>;\n }\n | { readonly ok: false; readonly issues: ReadonlyArray<ValidationIssue> };\n\n// =============================================================================\n// Public entry point\n// =============================================================================\n\nexport function validatePoeRecord(bytes: Uint8Array): ValidateResult {\n // Step 2 — canonical CBOR decode. Every decode failure surfaces as the single\n // MALFORMED_CBOR code: malformed/truncated bytes, indefinite-length\n // (streaming) encodings, non-canonical map-key ordering, duplicate map keys,\n // non-minimal integers, and invalid UTF-8. The taxonomy has no finer-grained\n // CBOR-decode codes — the validator catches all of these at decode and\n // reports one error.\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(bytes);\n } catch (cause) {\n return {\n ok: false,\n issues: [\n {\n code: 'MALFORMED_CBOR',\n path: [],\n message: cause instanceof Error ? cause.message : String(cause),\n severity: 'error',\n },\n ],\n };\n }\n\n // Step 3 — schema parse\n const parse = PoeRecordSchema.safeParse(decoded);\n if (!parse.success) {\n const issues = parse.error.issues\n .map((issue) => mapZodIssue(issue, decoded))\n .sort(compareIssuePath);\n return { ok: false, issues };\n }\n\n // Step 4 — domain checks\n const record = parse.data;\n const errors: ValidationIssue[] = [];\n const warnings: ValidationIssue[] = [];\n const info: ValidationIssue[] = [];\n\n // 4a — content-commitment rule (`SCHEMA_EMPTY_RECORD`).\n const itemsLen = Array.isArray(record.items) ? record.items.length : 0;\n const merkleLen = Array.isArray(record.merkle) ? record.merkle.length : 0;\n if (itemsLen === 0 && merkleLen === 0) {\n errors.push(\n issue(\n 'SCHEMA_EMPTY_RECORD',\n [],\n 'record must carry at least one of items[] or merkle[] non-empty',\n ),\n );\n }\n\n // `crit[]` shape rules. Runs BEFORE the per-entry\n // `EXTENSION_UNSUPPORTED_CRITICAL` check.\n const decodedTopKeys = topLevelKeysOf(decoded);\n const critShapeInvalidIndices = checkCritShape(record, decodedTopKeys, errors);\n\n // Unknown top-level fields (typos like `supersedess`, `Sigs` that fall\n // outside both the base set and the extension-key namespaces).\n for (const k of decodedTopKeys) {\n if (TOP_LEVEL_BASE_KEYS.has(k)) continue;\n if (isExtensionKey(k)) continue;\n errors.push(issue('SCHEMA_UNKNOWN_FIELD', [k], `unknown top-level field: ${k}`));\n }\n\n // `EXTENSION_UNSUPPORTED_CRITICAL`: v1 reference validator implements no\n // extension keys, so every shape-valid `crit` entry is unsupported.\n if (Array.isArray(record.crit)) {\n for (let i = 0; i < record.crit.length; i++) {\n if (critShapeInvalidIndices.has(i)) continue;\n const critName = record.crit[i]!;\n errors.push(\n issue(\n 'EXTENSION_UNSUPPORTED_CRITICAL',\n ['crit', i],\n `crit lists extension '${critName}' that this validator does not implement`,\n ),\n );\n }\n }\n\n // 4b – 4e — per-item walk.\n for (let i = 0; i < (record.items ?? []).length; i++) {\n const item = record.items![i]!;\n checkItemHashes(item, i, errors);\n if (item.uris) checkItemUris(item.uris, ['items', i, 'uris'], errors);\n if (item.enc !== undefined) checkItemEnc(item, i, errors);\n }\n\n // 4i — top-level `merkle[]` walk.\n for (let i = 0; i < (record.merkle ?? []).length; i++) {\n const commit = record.merkle![i]!;\n checkMerkleCommit(commit, i, errors);\n }\n\n // 4h — supersedes length is enforced by the schema-layer refinement; this\n // step adds no further check.\n\n // 4f + 4g — `sigs[i]` closed map shape + COSE_Sign1 structural decode.\n if (record.sigs) {\n for (let i = 0; i < record.sigs.length; i++) {\n checkSigEntry(record.sigs[i]!, i, errors, info);\n }\n }\n\n // Step 5 — result emission. `info`-severity entries do NOT fail the record;\n // `warning`-severity entries (none among the structural codes) also remain\n // non-fatal.\n if (errors.length > 0) {\n return { ok: false, issues: errors.sort(compareIssuePath) };\n }\n const result: {\n ok: true;\n record: PoeRecord;\n warnings?: ReadonlyArray<ValidationIssue>;\n info?: ReadonlyArray<ValidationIssue>;\n } = {\n ok: true,\n record,\n };\n if (warnings.length > 0) result.warnings = warnings.sort(compareIssuePath);\n if (info.length > 0) result.info = info.sort(compareIssuePath);\n return result;\n}\n\n// =============================================================================\n// Step 3 helpers — Zod issue → structural-code mapping\n// =============================================================================\n\nfunction mapZodIssue(zissue: z.core.$ZodIssue, decoded?: unknown): ValidationIssue {\n const path = zissue.path as ReadonlyArray<string | number>;\n // Refinements with an explicit `params.code` win unconditionally — they\n // are the canonical taxonomy code attached at schema-definition time.\n const explicit = (zissue as { params?: { code?: string } }).params?.code as ErrorCode | undefined;\n if (explicit !== undefined) {\n return issue(explicit, path, zissue.message);\n }\n\n // Path-based dispatch:\n // `sigs[i].*` → `SIG_ENTRY_INVALID_SHAPE` (the sig-entry closed-map rule)\n // `items[i].enc.slots[j].(epk|wrap)` → `ENC_SLOT_INVALID_SHAPE`\n // (structurally malformed slots)\n // `v` literal mismatch / missing → `SCHEMA_INVALID_LITERAL` vs\n // `SCHEMA_MISSING_REQUIRED`.\n const inSigsEntry = path.length >= 2 && path[0] === 'sigs' && typeof path[1] === 'number';\n\n // Match either the absolute path (`items[i].enc.slots[j]…`) or the\n // relative-to-`enc` path (`slots[j]…`) — the latter is what\n // `EncryptionEnvelopeSchema.safeParse(item.enc)` emits before\n // `checkItemEnc` prefixes the `items[i].enc.` segment.\n //\n // The match includes the whole slot ELEMENT (path ending at `slots[j]`, no\n // trailing field) as well as a field WITHIN a slot (`slots[j].epk`). A\n // wrong-typed slot (`slots: [[1, 2]]` → array instead of `{epk, wrap}`) and\n // a slot carrying an extra key both classify as `ENC_SLOT_INVALID_SHAPE`,\n // matching the spec's \"a slot is not a 2-key map {epk, wrap}\".\n const isInSlotEntry = (() => {\n if (\n path.length >= 5 &&\n path[0] === 'items' &&\n typeof path[1] === 'number' &&\n path[2] === 'enc' &&\n path[3] === 'slots' &&\n typeof path[4] === 'number'\n ) {\n return true;\n }\n if (path.length >= 2 && path[0] === 'slots' && typeof path[1] === 'number') {\n return true;\n }\n return false;\n })();\n\n const valueAtIssue = valueAtPath(decoded, path);\n const isMissing = valueAtIssue === undefined;\n\n switch (zissue.code) {\n case 'invalid_type':\n if (isInSlotEntry) return issue('ENC_SLOT_INVALID_SHAPE', path, zissue.message);\n if (isMissing) {\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_MISSING_REQUIRED', path, zissue.message);\n }\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_TYPE_MISMATCH', path, zissue.message);\n case 'invalid_value':\n // Zod 4's `z.literal(1)` emits `invalid_value` for both a missing field\n // AND a present-but-wrong value. Disambiguate via the runtime value:\n // missing → `SCHEMA_MISSING_REQUIRED`; present-but-wrong → `SCHEMA_INVALID_LITERAL`.\n if (path.length === 1 && path[0] === 'v') {\n return issue(\n isMissing ? 'SCHEMA_MISSING_REQUIRED' : 'SCHEMA_INVALID_LITERAL',\n path,\n zissue.message,\n );\n }\n return issue('SCHEMA_INVALID_LITERAL', path, zissue.message);\n case 'unrecognized_keys':\n if (isInSlotEntry) return issue('ENC_SLOT_INVALID_SHAPE', path, zissue.message);\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_UNKNOWN_FIELD', path, zissue.message);\n case 'invalid_format':\n case 'too_big':\n case 'too_small':\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_TYPE_MISMATCH', path, zissue.message);\n case 'invalid_union':\n case 'invalid_key':\n case 'invalid_element':\n case 'custom':\n default:\n if (isInSlotEntry) return issue('ENC_SLOT_INVALID_SHAPE', path, zissue.message);\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_TYPE_MISMATCH', path, zissue.message);\n }\n}\n\n// =============================================================================\n// Step 4 helpers — domain checks\n// =============================================================================\n\n// 4b — hash-map registry membership + digest length per algorithm.\nfunction checkItemHashes(item: ItemEntry, idx: number, errors: ValidationIssue[]): void {\n const entries = Object.entries(item.hashes);\n if (entries.length === 0) {\n errors.push(\n issue(\n 'SCHEMA_TYPE_MISMATCH',\n ['items', idx, 'hashes'],\n 'hashes must be a non-empty CBOR map of <alg-id> -> <digest>',\n ),\n );\n return;\n }\n for (const [alg, digest] of entries) {\n if (!(alg in HASH_ALG_LENGTHS)) {\n errors.push(\n issue('UNSUPPORTED_HASH_ALG', ['items', idx, 'hashes', alg], `unknown hash alg: ${alg}`),\n );\n continue;\n }\n const expected = HASH_ALG_LENGTHS[alg]!;\n if (digest.length !== expected) {\n errors.push(\n issue(\n 'HASH_DIGEST_LENGTH_MISMATCH',\n ['items', idx, 'hashes', alg],\n `hashes['${alg}'] digest length ${digest.length} != ${expected}`,\n ),\n );\n }\n }\n}\n\n// 4c — URI chunk reconstruction + per-scheme shape.\nfunction checkItemUris(\n uris: ReadonlyArray<ReadonlyArray<string>>,\n basePath: ReadonlyArray<string | number>,\n errors: ValidationIssue[],\n): void {\n uris.forEach((chunks, ui) => validateOneUri(chunks, [...basePath, ui], errors));\n}\n\nfunction validateOneUri(\n chunks: ReadonlyArray<string>,\n path: ReadonlyArray<string | number>,\n errors: ValidationIssue[],\n): void {\n const reconstructed = reconstructChunkedUri(chunks);\n if (!reconstructed.ok) {\n errors.push(issue(reconstructed.code, path, reconstructed.reason));\n return;\n }\n const uri = reconstructed.uri;\n\n // Absolute URI, no fragment, scheme in `{ar://, ipfs://}`.\n if (uri.includes('#')) {\n errors.push(\n issue('INVALID_URI', path, \"URI contains a fragment identifier ('#'), which is forbidden\"),\n );\n return;\n }\n const sepIdx = uri.indexOf('://');\n if (sepIdx <= 0 || !/^[a-z][a-z0-9+.-]*$/i.test(uri.slice(0, sepIdx))) {\n errors.push(\n issue('INVALID_URI', path, 'URI is not absolute (missing scheme://hierarchical-part)'),\n );\n return;\n }\n // RFC 3986 §3.1: the scheme is case-insensitive, so case-fold the SCHEME ONLY,\n // then ALWAYS validate the body. The host / CID / txid is NOT case-folded — a\n // base64url Arweave txid and a base58btc CID are case-significant. An\n // uppercase scheme (`AR://`, `IPFS://`) is accepted iff its body passes the\n // same per-scheme shape check a lowercase scheme would.\n const scheme = uri.slice(0, sepIdx).toLowerCase();\n const rest = uri.slice(sepIdx + '://'.length);\n if (scheme === 'ar') {\n if (!/^ar:\\/\\/[A-Za-z0-9_-]{43}$/.test('ar://' + rest)) {\n errors.push(\n issue(\n 'INVALID_URI',\n path,\n 'ar:// URI does not match `^ar://[A-Za-z0-9_-]{43}$` (43-char base64url txid, no path/query/fragment)',\n ),\n );\n }\n return;\n }\n if (scheme === 'ipfs') {\n // The structural validator does a full CID parse (not just a prefix check).\n const slashIdx = rest.indexOf('/');\n const cid = slashIdx === -1 ? rest : rest.slice(0, slashIdx);\n if (!validateCidProfile(cid)) {\n errors.push(\n issue('INVALID_URI', path, 'ipfs:// URI is not a valid CID under the CIP-309 profile'),\n );\n }\n return;\n }\n // Scheme not in `{ar://, ipfs://}`.\n errors.push(\n issue('INVALID_URI', path, 'unsupported URI scheme; v1 PoE URI set is {ar://, ipfs://}'),\n );\n}\n\n// 4d — encryption envelope.\nfunction checkItemEnc(item: ItemEntry, idx: number, errors: ValidationIssue[]): void {\n // Pre-check: an `enc`-bearing item MUST commit to a content hash. The claim\n // is the *plaintext* digest, so the hashes map MUST carry at least one\n // registered content-hash entry (sha2-256 / blake2b-256). This is a PRESENCE\n // check, not merely a non-empty check: a `hashes` map that exists but carries\n // only a non-content algorithm (e.g. `{md5}`) still fails — there is no\n // content digest to bind the ciphertext to. The empty-map case is also caught\n // here (and additionally fails the CDDL `1*` cardinality in checkItemHashes).\n const hasContentHash = Object.keys(item.hashes).some((alg) => alg in HASH_ALG_LENGTHS);\n if (!hasContentHash) {\n errors.push(\n issue(\n 'ENC_REQUIRES_CONTENT_HASH',\n ['items', idx, 'enc'],\n 'item carries `enc` but `hashes` has no content-hash entry (sha2-256 or blake2b-256)',\n ),\n );\n return;\n }\n\n // Schema-parse the envelope independently so we can lift its issues with\n // the correct path prefix.\n const encParse = EncryptionEnvelopeSchema.safeParse(item.enc);\n if (!encParse.success) {\n for (const zissue of encParse.error.issues) {\n const mapped = mapZodIssue(zissue, item.enc);\n errors.push({\n ...mapped,\n path: ['items', idx, 'enc', ...mapped.path],\n });\n }\n return;\n }\n const enc = encParse.data;\n const basePath: ReadonlyArray<string | number> = ['items', idx, 'enc'];\n\n // `enc.scheme` MUST be the unsigned integer 1.\n if (typeof enc.scheme !== 'number' || !Number.isInteger(enc.scheme) || enc.scheme !== 1) {\n errors.push(\n issue(\n 'UNSUPPORTED_ENVELOPE_SCHEME',\n [...basePath, 'scheme'],\n `enc.scheme must be the unsigned integer 1; got ${String(enc.scheme)}`,\n ),\n );\n // Continue — other checks remain informative.\n }\n\n // AEAD checks (forbidden cipher first, then registry). The forbidden set is\n // the unauthenticated-cipher family — block-cipher modes that provide no\n // integrity (CBC, CTR, ECB, CFB, OFB) in any key-size spelling\n // (`aes-256-cbc`, `aes-128-cbc`, OpenSSL/JCA form) plus the legacy stream\n // ciphers (RC4, DES/3DES). Matching this family — rather than a generic\n // \"unknown alg\" fall-through to `UNSUPPORTED_AEAD_ALG` — names the security\n // hazard precisely: the record selected an authenticated-encryption-absent\n // cipher, not merely an unregistered one.\n if (UNAUTHENTICATED_CIPHER_RE.test(enc.aead)) {\n errors.push(\n issue(\n 'UNAUTHENTICATED_CIPHER_FORBIDDEN',\n [...basePath, 'aead'],\n `'${enc.aead}' is an unauthenticated cipher; CIP-309 mandates an authenticated (AEAD) cipher`,\n ),\n );\n return; // unrecoverable — nonce / kem / slot checks become noise\n }\n if (!(enc.aead in AEAD_NONCE_LENGTHS)) {\n errors.push(\n issue('UNSUPPORTED_AEAD_ALG', [...basePath, 'aead'], `unknown aead alg: ${enc.aead}`),\n );\n return;\n }\n const expectedNonceLen = AEAD_NONCE_LENGTHS[enc.aead]!;\n if (enc.nonce.length !== expectedNonceLen) {\n errors.push(\n issue(\n 'NONCE_LENGTH_MISMATCH',\n [...basePath, 'nonce'],\n `nonce length ${enc.nonce.length} != ${expectedNonceLen} for ${enc.aead}`,\n ),\n );\n }\n\n // Envelope-level KEM check (when present).\n if (enc.kem !== undefined && !(enc.kem in KEM_SLOT_DESCRIPTORS)) {\n errors.push(issue('UNSUPPORTED_KEM_ALG', [...basePath, 'kem'], `unknown kem alg: ${enc.kem}`));\n }\n\n // Key-path branching.\n const hasSlots = enc.slots !== undefined;\n const hasSlotsMac = enc.slots_mac !== undefined;\n const hasPassphrase = enc.passphrase !== undefined;\n\n if (hasSlots && hasPassphrase) {\n errors.push(\n issue('ENC_EXCLUSIVITY_VIOLATION', basePath, 'enc combines slots with passphrase; pick one'),\n );\n }\n if (hasSlots && !hasSlotsMac) {\n errors.push(\n issue('ENC_SLOTS_MAC_REQUIRED', basePath, 'enc.slots present but enc.slots_mac absent'),\n );\n }\n if (hasSlotsMac && !hasSlots) {\n errors.push(\n issue('ENC_SLOTS_REQUIRED', basePath, 'enc.slots_mac present but enc.slots absent'),\n );\n }\n if (hasSlots && enc.kem === undefined) {\n errors.push(issue('ENC_KEM_REQUIRED', basePath, 'enc.slots present but enc.kem absent'));\n }\n if (!hasSlots && !hasPassphrase) {\n errors.push(\n issue(\n 'ENC_NO_KEY_PATH',\n basePath,\n 'enc requires either slots or passphrase — no on-chain key path otherwise',\n ),\n );\n }\n\n // Slots shape checks. The slot shape is KEM-driven: the descriptor for the\n // declared `kem` pins which ciphertext-bearing field (`epk` for x25519,\n // `kem_ct` for mlkem768x25519) MUST be present and at what length, and\n // forbids the other KEM's field. Because the schema is permissive (no\n // `.strict()`), this domain pass is the ONLY thing rejecting cross-KEM\n // contamination — an x25519 slot carrying a stray `kem_ct`, or a hybrid slot\n // carrying a stray `epk`, surfaces as `ENC_SLOT_INVALID_SHAPE`.\n if (hasSlots) {\n if (enc.slots!.length < 1) {\n errors.push(\n issue('ENC_SLOTS_EMPTY', [...basePath, 'slots'], `slots length ${enc.slots!.length} < 1`),\n );\n }\n // Only validate slot shape when the KEM is known; an unknown / absent KEM\n // already emits its own code above, and we cannot pick a descriptor.\n const descriptor = enc.kem !== undefined ? KEM_SLOT_DESCRIPTORS[enc.kem] : undefined;\n if (descriptor !== undefined) {\n // The permissive `SlotSchema` strips unknown keys before they reach the\n // parsed slot, so the closed-map invariant (\"a slot is exactly {<ct\n // field>, wrap}\") is enforced against the RAW decoded slot key set here.\n const rawSlotKeys = rawSlotKeySets(item.enc);\n enc.slots!.forEach((slot, si) => {\n checkSlotShape(\n slot,\n rawSlotKeys[si] ?? new Set<string>(),\n descriptor,\n enc.kem!,\n [...basePath, 'slots', si],\n errors,\n );\n });\n }\n }\n\n // Passphrase block checks (registry membership + Argon2id closed-params + floor).\n if (hasPassphrase) {\n const pp = enc.passphrase!;\n const ppPath: ReadonlyArray<string | number> = [...basePath, 'passphrase'];\n if (!PASSPHRASE_KDF_ALGS.has(pp.alg)) {\n errors.push(\n issue(\n 'ENC_PASSPHRASE_ALG_UNSUPPORTED',\n [...ppPath, 'alg'],\n `unknown passphrase kdf alg: ${pp.alg}`,\n ),\n );\n return; // can't apply alg-specific params check\n }\n if (pp.alg === 'argon2id') {\n const allowed = new Set(['m', 't', 'p']);\n for (const k of Object.keys(pp.params)) {\n if (!allowed.has(k)) {\n errors.push(\n issue(\n 'SCHEMA_UNKNOWN_FIELD',\n [...ppPath, 'params', k],\n `unknown argon2id params field: ${k}`,\n ),\n );\n }\n }\n const p = pp.params as { m?: unknown; t?: unknown; p?: unknown };\n const argonInt = (val: unknown, name: 'm' | 't' | 'p'): number | null => {\n if (typeof val !== 'number' || !Number.isInteger(val)) {\n errors.push(\n issue(\n 'SCHEMA_TYPE_MISMATCH',\n [...ppPath, 'params', name],\n `argon2id params.${name} must be a CBOR unsigned integer`,\n ),\n );\n return null;\n }\n return val;\n };\n const mVal = argonInt(p.m, 'm');\n const tVal = argonInt(p.t, 't');\n const pVal = argonInt(p.p, 'p');\n if (mVal !== null && mVal < 65_536) {\n errors.push(\n issue(\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n [...ppPath, 'params', 'm'],\n 'argon2id requires m >= 65536 KiB',\n ),\n );\n }\n if (tVal !== null && tVal < 3) {\n errors.push(\n issue(\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n [...ppPath, 'params', 't'],\n 'argon2id requires t >= 3',\n ),\n );\n }\n if (pVal !== null && pVal < 1) {\n errors.push(\n issue(\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n [...ppPath, 'params', 'p'],\n 'argon2id requires p >= 1',\n ),\n );\n }\n }\n }\n}\n\n// KEM-driven per-slot shape gate (pure). Branches on the descriptor for the\n// declared envelope `kem`:\n//\n// - The descriptor's ciphertext-bearing field (`epk` for x25519, `kem_ct`\n// for mlkem768x25519) MUST be present at the expected (reassembled) length.\n// - The OTHER KEM's ciphertext field MUST be absent — its presence is\n// cross-KEM contamination and surfaces as `ENC_SLOT_INVALID_SHAPE` (the\n// hole that dropping `.strict()` on `SlotSchema` would otherwise open).\n// - `wrap` MUST be present at 48 bytes.\n//\n// This stays a pure function over already-decoded values: `kem_ct` reassembly\n// uses `bytesChunkArrayConcat` (byte concatenation only) — no crypto, no I/O.\n//\n// `rawKeys` is the slot's key set as it appeared on the wire (before the\n// permissive schema stripped unknowns); any key outside {<ct field>, wrap}\n// for this KEM is a closed-map violation.\nconst SLOT_KEY_UNIVERSE: ReadonlySet<string> = new Set(['epk', 'kem_ct', 'wrap']);\n\nfunction checkSlotShape(\n slot: Slot,\n rawKeys: ReadonlySet<string>,\n descriptor: KemSlotDescriptor,\n kem: string,\n slotPath: ReadonlyArray<string | number>,\n errors: ValidationIssue[],\n): void {\n // The ciphertext field that does NOT belong to this KEM. Its presence is a\n // shape violation regardless of length. Drive this off the RAW key set so a\n // future schema change cannot silently drop the foreign field before we see\n // it.\n const foreignField: KemSlotField = descriptor.field === 'epk' ? 'kem_ct' : 'epk';\n if (rawKeys.has(foreignField)) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, foreignField],\n `slot carries '${foreignField}' but kem='${kem}' expects '${descriptor.field}'`,\n ),\n );\n }\n\n // Any key outside the slot universe is a closed-map violation (the schema is\n // permissive and would otherwise strip it silently).\n for (const k of rawKeys) {\n if (!SLOT_KEY_UNIVERSE.has(k)) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, k],\n `slot carries unexpected key '${k}'; a slot is a 2-key map {${descriptor.field}, wrap}`,\n ),\n );\n }\n }\n\n // The required ciphertext-bearing field MUST be present at the expected\n // (reassembled) length.\n if (descriptor.field === 'epk') {\n if (slot.epk === undefined) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, 'epk'],\n `slot for kem='${kem}' is missing required 'epk'`,\n ),\n );\n } else if (slot.epk.length !== descriptor.fieldLength) {\n errors.push(\n issue(\n KEM_FIELD_LENGTH_CODE.epk,\n [...slotPath, 'epk'],\n `slot.epk length ${slot.epk.length} != ${descriptor.fieldLength} for ${kem}`,\n ),\n );\n }\n } else {\n if (slot.kem_ct === undefined) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, 'kem_ct'],\n `slot for kem='${kem}' is missing required 'kem_ct'`,\n ),\n );\n } else {\n const reassembled = bytesChunkArrayConcat(slot.kem_ct).length;\n if (reassembled !== descriptor.fieldLength) {\n errors.push(\n issue(\n KEM_FIELD_LENGTH_CODE.kem_ct,\n [...slotPath, 'kem_ct'],\n `slot.kem_ct reassembles to ${reassembled} bytes != ${descriptor.fieldLength} for ${kem}`,\n ),\n );\n }\n }\n }\n\n // `wrap` is 48 bytes for every KEM.\n if (slot.wrap === undefined) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, 'wrap'],\n `slot for kem='${kem}' is missing required 'wrap'`,\n ),\n );\n } else if (slot.wrap.length !== descriptor.wrapLength) {\n errors.push(\n issue(\n 'WRAP_LENGTH_MISMATCH',\n [...slotPath, 'wrap'],\n `slot.wrap length ${slot.wrap.length} != ${descriptor.wrapLength}`,\n ),\n );\n }\n}\n\n// Extract the per-slot RAW key sets from a decoded `enc` value, BEFORE the\n// permissive schema strips unknown slot keys. cbor2 surfaces a CBOR map either\n// as a `Map` (int/heterogeneous keys) or a plain object (text keys); slot maps\n// are text-keyed, so this reads string keys from whichever form. A slot that\n// is not a map at all yields an empty set — the slot's own type errors are\n// already emitted by the schema parse, so the shape gate simply finds no keys.\nfunction rawSlotKeySets(rawEnc: unknown): ReadonlyArray<ReadonlySet<string>> {\n const slots = mapLikeGet(rawEnc, 'slots');\n if (!Array.isArray(slots)) return [];\n return slots.map((slot) => {\n const keys = new Set<string>();\n if (slot instanceof Map) {\n for (const k of slot.keys()) if (typeof k === 'string') keys.add(k);\n } else if (typeof slot === 'object' && slot !== null) {\n for (const k of Object.keys(slot as Record<string, unknown>)) keys.add(k);\n }\n return keys;\n });\n}\n\nfunction mapLikeGet(value: unknown, key: string): unknown {\n if (value instanceof Map) return value.get(key);\n if (typeof value === 'object' && value !== null) {\n return (value as Record<string, unknown>)[key];\n }\n return undefined;\n}\n\n// 4i — `merkle[i]` walk.\nfunction checkMerkleCommit(commit: MerkleCommit, idx: number, errors: ValidationIssue[]): void {\n const basePath: ReadonlyArray<string | number> = ['merkle', idx];\n if (!(commit.alg in MERKLE_COMMIT_ALG_LENGTHS)) {\n errors.push(\n issue(\n 'UNSUPPORTED_MERKLE_COMMIT_ALG',\n [...basePath, 'alg'],\n `unknown merkle commitment alg: ${commit.alg}`,\n ),\n );\n return;\n }\n const expected = MERKLE_COMMIT_ALG_LENGTHS[commit.alg]!;\n if (commit.root.length !== expected) {\n errors.push(\n issue(\n 'HASH_DIGEST_LENGTH_MISMATCH',\n [...basePath, 'root'],\n `merkle entry root length ${commit.root.length} != ${expected} for ${commit.alg}`,\n ),\n );\n }\n if (commit.uris) {\n checkItemUris(commit.uris, [...basePath, 'uris'], errors);\n }\n}\n\n// 4f + 4g — record-level signature entries.\nfunction checkSigEntry(\n entry: SigEntry,\n idx: number,\n errors: ValidationIssue[],\n info: ValidationIssue[],\n): void {\n // Path-2 `cose_key` private-material guard runs FIRST.\n if (entry.cose_key !== undefined) {\n const keyIssue = inspectCoseKey(entry.cose_key, idx);\n if (keyIssue !== null) {\n errors.push(keyIssue);\n return;\n }\n }\n\n // 4g — COSE_Sign1 structural decode.\n const merged = bytesChunkArrayConcat(entry.cose_sign1);\n let cose: ReturnType<typeof decodeCoseSign1>;\n try {\n cose = decodeCoseSign1(merged);\n } catch (cause) {\n errors.push(\n issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', idx],\n cause instanceof CoseVerifyError || cause instanceof Error ? cause.message : String(cause),\n ),\n );\n return;\n }\n\n // Detached-only payload — the COSE_Sign1 payload MUST be null.\n if (cose.payload !== null) {\n errors.push(\n issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', idx],\n 'COSE_Sign1 payload must be null (detached); attached form forbidden',\n ),\n );\n return;\n }\n\n // Signature-algorithm registry check (info-severity — an unrecognised alg\n // does not fail the record).\n const alg = cose.protectedHeader.get(1);\n if (typeof alg !== 'number' || !KNOWN_SIG_ALG_IDS.has(alg)) {\n info.push(\n issue(\n 'SIGNATURE_UNSUPPORTED',\n ['sigs', idx],\n `COSE_Sign1 protected alg ${String(alg)} not in {-8, -19}`,\n ),\n );\n }\n\n // Path-1 (32-byte protected-header `kid`) and path-2 (`cose_key` sidecar)\n // are mutually exclusive — a sig entry must not carry both.\n const protectedKid = cose.protectedHeader.get(4);\n if (\n protectedKid instanceof Uint8Array &&\n protectedKid.length === 32 &&\n entry.cose_key !== undefined\n ) {\n errors.push(\n issue(\n 'SIG_ENTRY_KID_COSE_KEY_CONFLICT',\n ['sigs', idx],\n 'sigs[i] carries both a 32-byte protected `kid` (path 1) and an inline `cose_key` (path 2); paths are mutually exclusive',\n ),\n );\n }\n}\n\n// =============================================================================\n// COSE_Key inspector (path-2 `sigs[i].cose_key` blob)\n// =============================================================================\n//\n// Two structural checks:\n// 5a — Private-material guard (FIRST). COSE_Key label `-4` (the private\n// scalar `d` for OKP / EC2 per RFC 9052 §7.1) → `SIG_PRIVATE_KEY_LEAKED`.\n// This check is load-bearing producer-side preflight: publishing a\n// private key on the permanent ledger is catastrophic and irreversible.\n// 5b — Positive-shape guard. The decoded `cbor<COSE_Key>` map MUST carry\n// `kty=1` (OKP), `crv=6` (Ed25519), and a 32-byte `-2` (x). Any\n// failure → `MALFORMED_SIG_COSE_SIGN1`.\n\nfunction inspectCoseKey(keyChunks: ReadonlyArray<Uint8Array>, i: number): ValidationIssue | null {\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(bytesChunkArrayConcat(keyChunks));\n } catch (cause) {\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key failed to decode as cbor<COSE_Key>: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n }\n\n // cbor2 surfaces int-keyed COSE_Key maps as `Map`; string-keyed maps as\n // plain JS objects (a malformed COSE_Key would carry string keys).\n const getLabel = (label: number): unknown => {\n if (decoded instanceof Map) return decoded.get(label);\n if (typeof decoded === 'object' && decoded !== null) {\n return (decoded as Record<string, unknown>)[String(label)];\n }\n return undefined;\n };\n const hasLabel = (label: number): boolean => {\n if (decoded instanceof Map) return decoded.has(label);\n if (typeof decoded === 'object' && decoded !== null) {\n return Object.prototype.hasOwnProperty.call(decoded, String(label));\n }\n return false;\n };\n\n // 5a — Private-material guard.\n if (hasLabel(-4)) {\n return issue(\n 'SIG_PRIVATE_KEY_LEAKED',\n ['sigs', i, 'cose_key'],\n 'cose_key carries COSE_Key private-key material (label -4, the OKP/EC2 private scalar d); publishing a private key on the permanent ledger is forbidden',\n );\n }\n\n // 5b — Positive-shape guard.\n const kty = getLabel(1);\n if (kty !== 1) {\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key kty (label 1) must be 1 (OKP); got ${String(kty)}`,\n );\n }\n const crv = getLabel(-1);\n if (crv !== 6) {\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key crv (label -1) must be 6 (Ed25519); got ${String(crv)}`,\n );\n }\n if (!hasLabel(-2)) {\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key missing label -2 (Ed25519 public-key bytes)`,\n );\n }\n const x = getLabel(-2);\n if (!(x instanceof Uint8Array) || x.length !== 32) {\n const got = x instanceof Uint8Array ? `${x.length}-byte bstr` : typeof x;\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key label -2 must be a 32-byte byte string (Ed25519 public key); got ${got}`,\n );\n }\n return null;\n}\n\n// =============================================================================\n// CIP-309 CID profile\n// =============================================================================\n//\n// Accept CIDv0 (`Qm` prefix, 46-char base58btc, sha2-256 multihash) and\n// CIDv1 (multibase prefix + version 0x01 + codec + multihash) per the\n// closed profile:\n// - Multibase: b, B, f, F, z\n// - Multicodec: 0x55 (raw), 0x70 (dag-pb), 0x71 (dag-cbor)\n// - Multihash: 0x12 (sha2-256, 32 B), 0xb220 (blake2b-256, 32 B)\n//\n// Returns true iff the CID conforms to the CIP-309 profile.\n\nconst ACCEPTED_CIDV1_MULTIBASE: ReadonlySet<string> = new Set(['b', 'B', 'f', 'F', 'z']);\n\nconst ACCEPTED_MULTICODECS: ReadonlySet<number> = new Set([0x55, 0x70, 0x71]);\n\n// Multihash table: code → digest length (bytes).\n// `0x12` = sha2-256; `0xb220` = blake2b-256.\nconst ACCEPTED_MULTIHASHES: ReadonlyMap<number, number> = new Map([\n [0x12, 32],\n [0xb220, 32],\n]);\n\nexport function validateCidProfile(cid: string): boolean {\n if (cid.length === 0) return false;\n // CIDv0: a base58btc-encoded sha2-256 multihash. Decode the WHOLE string and\n // verify the multihash prefix (0x12 = sha2-256, 0x20 = 32-byte digest length)\n // and total length (34 bytes = 2-byte prefix + 32-byte digest). A `Qm`\n // prefix alone is not sufficient — a malformed body must be rejected.\n if (cid.startsWith('Qm')) {\n let decoded: Uint8Array;\n try {\n decoded = decodeBase58btc(cid);\n } catch {\n return false;\n }\n return decoded.length === 34 && decoded[0] === 0x12 && decoded[1] === 0x20;\n }\n // CIDv1: multibase + binary CID body.\n const mbPrefix = cid[0]!;\n if (!ACCEPTED_CIDV1_MULTIBASE.has(mbPrefix)) return false;\n let bytes: Uint8Array;\n try {\n bytes = decodeMultibase(mbPrefix, cid.slice(1));\n } catch {\n return false;\n }\n if (bytes.length < 4) return false;\n // CIDv1 layout: <version varint> <multicodec varint> <multihash>\n const versionParse = readVarint(bytes, 0);\n if (versionParse === null || versionParse.value !== 1) return false;\n const codecParse = readVarint(bytes, versionParse.next);\n if (codecParse === null) return false;\n if (!ACCEPTED_MULTICODECS.has(codecParse.value)) return false;\n const mhParse = readVarint(bytes, codecParse.next);\n if (mhParse === null) return false;\n const lenParse = readVarint(bytes, mhParse.next);\n if (lenParse === null) return false;\n const digestLen = lenParse.value;\n const expectedLen = ACCEPTED_MULTIHASHES.get(mhParse.value);\n if (expectedLen === undefined || digestLen !== expectedLen) return false;\n if (lenParse.next + digestLen !== bytes.length) return false;\n return true;\n}\n\nfunction readVarint(bytes: Uint8Array, start: number): { value: number; next: number } | null {\n let value = 0;\n let shift = 0;\n let i = start;\n while (i < bytes.length) {\n const b = bytes[i]!;\n value |= (b & 0x7f) << shift;\n i++;\n if ((b & 0x80) === 0) return { value, next: i };\n shift += 7;\n if (shift > 28) return null; // overflow guard; CIP-309 profile uses ≤ 16-bit codes\n }\n return null;\n}\n\n// Multibase decoders for the closed set the CID profile admits.\nfunction decodeMultibase(prefix: string, body: string): Uint8Array {\n switch (prefix) {\n case 'b':\n return decodeBase32(body.toLowerCase(), 'rfc4648-lower');\n case 'B':\n return decodeBase32(body.toUpperCase(), 'rfc4648-upper');\n case 'f':\n return decodeBase16(body.toLowerCase());\n case 'F':\n return decodeBase16(body.toUpperCase());\n case 'z':\n return decodeBase58btc(body);\n default:\n throw new Error(`unsupported multibase prefix ${prefix}`);\n }\n}\n\nconst BASE16_LOWER = '0123456789abcdef';\nconst BASE16_UPPER = '0123456789ABCDEF';\n\nfunction decodeBase16(s: string): Uint8Array {\n if (s.length % 2 !== 0) throw new Error('base16: odd-length');\n const out = new Uint8Array(s.length / 2);\n const alphabet = s === s.toLowerCase() ? BASE16_LOWER : BASE16_UPPER;\n for (let i = 0; i < out.length; i++) {\n const hi = alphabet.indexOf(s[i * 2]!);\n const lo = alphabet.indexOf(s[i * 2 + 1]!);\n if (hi < 0 || lo < 0) throw new Error(`base16: non-hex char at ${i * 2}`);\n out[i] = (hi << 4) | lo;\n }\n return out;\n}\n\nconst BASE32_RFC4648_LOWER = 'abcdefghijklmnopqrstuvwxyz234567';\nconst BASE32_RFC4648_UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';\n\nfunction decodeBase32(s: string, variant: 'rfc4648-lower' | 'rfc4648-upper'): Uint8Array {\n const alphabet = variant === 'rfc4648-lower' ? BASE32_RFC4648_LOWER : BASE32_RFC4648_UPPER;\n // Multibase strips padding per spec; we accept either form for robustness.\n const trimmed = s.replace(/=+$/, '');\n const out: number[] = [];\n let buf = 0;\n let bits = 0;\n for (const ch of trimmed) {\n const idx = alphabet.indexOf(ch);\n if (idx < 0) throw new Error(`base32: invalid char '${ch}'`);\n buf = (buf << 5) | idx;\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n out.push((buf >> bits) & 0xff);\n }\n }\n return Uint8Array.from(out);\n}\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\nfunction decodeBase58btc(s: string): Uint8Array {\n if (s.length === 0) return new Uint8Array(0);\n let zeros = 0;\n while (zeros < s.length && s[zeros] === '1') zeros++;\n const size = Math.floor(((s.length - zeros) * 733) / 1000) + 1;\n const b256 = new Uint8Array(size);\n let length = 0;\n for (let i = zeros; i < s.length; i++) {\n const ch = s[i]!;\n const carryIdx = BASE58_ALPHABET.indexOf(ch);\n if (carryIdx < 0) throw new Error(`base58: invalid char '${ch}'`);\n let carry = carryIdx;\n let k = 0;\n for (let j = size - 1; (carry !== 0 || k < length) && j >= 0; j--, k++) {\n carry += 58 * b256[j]!;\n b256[j] = carry % 256;\n carry = Math.floor(carry / 256);\n }\n length = k;\n }\n let it = size - length;\n while (it < size && b256[it] === 0) it++;\n const out = new Uint8Array(zeros + (size - it));\n let j = zeros;\n while (it < size) {\n out[j++] = b256[it++]!;\n }\n return out;\n}\n\n// =============================================================================\n// `crit[]` shape rule helper\n// =============================================================================\n\nfunction checkCritShape(\n record: PoeRecord,\n decodedTopKeys: ReadonlySet<string>,\n errors: ValidationIssue[],\n): Set<number> {\n const invalid = new Set<number>();\n if (!Array.isArray(record.crit)) return invalid;\n // `crit` has `1*` cardinality: when present it MUST carry at least one\n // entry. An empty array is a malformed shape — reject it here in the\n // domain pass (rather than via a schema `.min(1)`) so the emitted message\n // string is identical across the TS/PY/RS validators.\n if (record.crit.length === 0) {\n errors.push(\n issue('SCHEMA_TYPE_MISMATCH', ['crit'], 'crit[] must carry at least one entry when present'),\n );\n return invalid;\n }\n const seen = new Set<string>();\n for (let i = 0; i < record.crit.length; i++) {\n const critName = record.crit[i]!;\n let reason: string | null = null;\n if (TOP_LEVEL_BASE_KEYS.has(critName)) {\n reason = `'${critName}' is a base key and MUST NOT appear in crit[]`;\n } else if (!isExtensionKey(critName)) {\n reason = `'${critName}' does not match the extension-key regex (^x-.+ or ^[a-z]+-.+)`;\n } else if (!decodedTopKeys.has(critName)) {\n reason = `'${critName}' is named in crit but absent from the record map`;\n } else if (seen.has(critName)) {\n reason = `'${critName}' appears more than once in crit[]`;\n }\n seen.add(critName);\n if (reason !== null) {\n invalid.add(i);\n errors.push(issue('CRIT_SHAPE_INVALID', ['crit', i], reason));\n }\n }\n return invalid;\n}\n\nfunction topLevelKeysOf(decoded: unknown): Set<string> {\n if (decoded === null || typeof decoded !== 'object') return new Set();\n if (decoded instanceof Map) {\n const out = new Set<string>();\n for (const k of decoded.keys()) {\n if (typeof k === 'string') out.add(k);\n }\n return out;\n }\n return new Set(Object.keys(decoded as Record<string, unknown>));\n}\n\n// =============================================================================\n// Path / issue helpers\n// =============================================================================\n\nfunction issue(\n code: ErrorCode,\n path: ReadonlyArray<string | number>,\n message: string,\n): ValidationIssue {\n return { code, path, message, severity: SEVERITY[code] };\n}\n\nfunction compareIssuePath(a: ValidationIssue, b: ValidationIssue): number {\n return a.path.join('.').localeCompare(b.path.join('.'));\n}\n\nfunction valueAtPath(root: unknown, path: ReadonlyArray<string | number>): unknown {\n let cur: unknown = root;\n for (const seg of path) {\n if (cur === null || cur === undefined) return undefined;\n if (cur instanceof Map) {\n cur = cur.get(seg);\n continue;\n }\n if (typeof cur !== 'object') return undefined;\n cur = (cur as Record<string | number, unknown>)[seg];\n }\n return cur;\n}\n","import { argon2id } from 'hash-wasm';\n\nexport interface Argon2idParams {\n readonly memSizeKB: number;\n readonly iterations: number;\n readonly parallelism: number;\n readonly outBytes: number;\n}\n\nexport interface Argon2idV13Opts {\n readonly password: Uint8Array;\n readonly salt: Uint8Array;\n readonly memSizeKB: number;\n readonly iterations: number;\n readonly parallelism: number;\n readonly outBytes: number;\n}\n\nexport async function argon2idV13(opts: Argon2idV13Opts): Promise<Uint8Array> {\n return (await argon2id({\n password: opts.password,\n salt: opts.salt,\n parallelism: opts.parallelism,\n iterations: opts.iterations,\n memorySize: opts.memSizeKB,\n hashLength: opts.outBytes,\n outputType: 'binary',\n })) as Uint8Array;\n}\n","export class AeadVerificationError extends Error {\n readonly code: string = 'aead_verification_failed';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'AeadVerificationError';\n }\n}\n","import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';\n\nimport { AeadVerificationError } from './errors';\n\nexport interface XChaCha20Poly1305EncryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly plaintext: Uint8Array;\n}\n\nexport interface XChaCha20Poly1305DecryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly ciphertext: Uint8Array;\n}\n\nexport function xchacha20Poly1305Encrypt(opts: XChaCha20Poly1305EncryptOpts): Uint8Array {\n return xchacha20poly1305(opts.key, opts.nonce, opts.aad).encrypt(opts.plaintext);\n}\n\nexport function xchacha20Poly1305Decrypt(opts: XChaCha20Poly1305DecryptOpts): Uint8Array {\n try {\n return xchacha20poly1305(opts.key, opts.nonce, opts.aad).decrypt(opts.ciphertext);\n } catch (cause) {\n throw new AeadVerificationError('xchacha20-poly1305 decrypt failed', { cause });\n }\n}\n","import { sha256 as nobleSha256 } from '@noble/hashes/sha2.js';\n\nexport function sha256(input: Uint8Array): Uint8Array {\n return nobleSha256(input);\n}\n","// RFC 9162 §2.1.1 binary Merkle tree under SHA-256.\n// This implements the algorithm tier identified on the wire as the\n// `rfc9162-sha256` OPT-INFO; the record's `merkle[]` field carries the proof.\n//\n// Construction (RFC 9162 §2.1.1):\n// - Single leaf: MTH({d_0}) = SHA-256(0x00 || d_0)\n// - Internal node: MTH(L) = SHA-256(0x01 || MTH(L[0:k]) || MTH(L[k:n]))\n// where k = largest power of 2 strictly less than n.\n// - Empty trees (n == 0) are FORBIDDEN.\n// - The 0x00 leaf / 0x01 internal prefixes prevent the CVE-2012-2459\n// leaf-vs-internal collision family.\n\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { compareCt } from '../util/compare-ct';\n\nexport const MERKLE_ALG_ID = 'rfc9162-sha256' as const;\n\nconst LEAF_PREFIX = 0x00;\nconst NODE_PREFIX = 0x01;\nconst DIGEST_LENGTH = 32;\n\nfunction validateLeaves(leaves: ReadonlyArray<Uint8Array>, fnName: string): void {\n if (leaves.length === 0) {\n throw new Error(`${fnName}: empty leaf list (n == 0 is forbidden by RFC 9162 §2.1.1)`);\n }\n for (let i = 0; i < leaves.length; i++) {\n const leaf = leaves[i];\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) {\n throw new Error(\n `${fnName}: leaf[${i}] must be a Uint8Array(${DIGEST_LENGTH}); got length ${\n leaf instanceof Uint8Array ? leaf.length : 'non-Uint8Array'\n }`,\n );\n }\n }\n}\n\nexport function merkleSha2256Root(leaves: ReadonlyArray<Uint8Array>): Uint8Array {\n validateLeaves(leaves, 'merkleSha2256Root');\n return mthRecursive(leaves, 0, leaves.length);\n}\n\nexport function merkleSha2256InclusionProof(\n leaves: ReadonlyArray<Uint8Array>,\n index: number,\n): Uint8Array[] {\n validateLeaves(leaves, 'merkleSha2256InclusionProof');\n if (!Number.isInteger(index) || index < 0 || index >= leaves.length) {\n throw new Error(\n `merkleSha2256InclusionProof: index ${index} out of range [0, ${leaves.length})`,\n );\n }\n return auditPath(leaves, index, 0, leaves.length);\n}\n\n/**\n * Verify an inclusion proof per RFC 9162 §2.1.3.2 (iterative form).\n *\n * `proof` is ordered leaf-to-root: `proof[0]` is the sibling at the leaf\n * level, `proof[m-1]` is the top-level sibling. The fold uses the\n * `sn`/`fn` tracking from RFC 9162: `sn` is the leaf index within the\n * current subtree, `fn` is (subtree_size - 1). At each step, `sn` odd\n * OR `sn == fn` means the current node is a right child (sibling on\n * the left); otherwise it is a left child (sibling on the right).\n * Both shift right by one each iteration. This handles non-power-of-2\n * sizes including the \"promote a lone right subtree\" cases.\n */\nexport function merkleSha2256VerifyInclusion(\n leaf: Uint8Array,\n index: number,\n treeSize: number,\n proof: ReadonlyArray<Uint8Array>,\n root: Uint8Array,\n): boolean {\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) return false;\n if (!(root instanceof Uint8Array) || root.length !== DIGEST_LENGTH) return false;\n if (\n !Number.isInteger(index) ||\n !Number.isInteger(treeSize) ||\n treeSize < 1 ||\n index < 0 ||\n index >= treeSize\n ) {\n return false;\n }\n for (let i = 0; i < proof.length; i++) {\n const sibling = proof[i];\n if (!(sibling instanceof Uint8Array) || sibling.length !== DIGEST_LENGTH) {\n return false;\n }\n }\n\n if (treeSize === 1) {\n if (proof.length !== 0 || index !== 0) return false;\n return compareCt(hashLeaf(leaf), root);\n }\n\n let h = hashLeaf(leaf);\n let sn = index;\n let fn = treeSize - 1;\n for (let i = 0; i < proof.length; i++) {\n if (fn === 0) return false;\n const sibling = proof[i] as Uint8Array;\n if ((sn & 1) === 1 || sn === fn) {\n h = hashNode(sibling, h);\n while ((sn & 1) === 0 && sn !== 0) {\n sn >>>= 1;\n fn >>>= 1;\n }\n } else {\n h = hashNode(h, sibling);\n }\n sn >>>= 1;\n fn >>>= 1;\n }\n if (fn !== 0) return false;\n return compareCt(h, root);\n}\n\nfunction largestPow2Lt(n: number): number {\n let k = 1;\n while (k * 2 < n) k *= 2;\n return k;\n}\n\nfunction hashLeaf(d: Uint8Array): Uint8Array {\n const buf = new Uint8Array(1 + d.length);\n buf[0] = LEAF_PREFIX;\n buf.set(d, 1);\n return sha256(buf);\n}\n\nfunction hashNode(left: Uint8Array, right: Uint8Array): Uint8Array {\n const buf = new Uint8Array(1 + left.length + right.length);\n buf[0] = NODE_PREFIX;\n buf.set(left, 1);\n buf.set(right, 1 + left.length);\n return sha256(buf);\n}\n\nfunction mthRecursive(leaves: ReadonlyArray<Uint8Array>, start: number, end: number): Uint8Array {\n const n = end - start;\n if (n === 1) {\n return hashLeaf(leaves[start] as Uint8Array);\n }\n const k = largestPow2Lt(n);\n const left = mthRecursive(leaves, start, start + k);\n const right = mthRecursive(leaves, start + k, end);\n return hashNode(left, right);\n}\n\nfunction auditPath(\n leaves: ReadonlyArray<Uint8Array>,\n i: number,\n start: number,\n end: number,\n): Uint8Array[] {\n const n = end - start;\n if (n === 1) return [];\n const k = largestPow2Lt(n);\n if (i < k) {\n const subPath = auditPath(leaves, i, start, start + k);\n subPath.push(mthRecursive(leaves, start + k, end));\n return subPath;\n }\n const subPath = auditPath(leaves, i - k, start + k, end);\n subPath.push(mthRecursive(leaves, start, start + k));\n return subPath;\n}\n","/**\n * Utilities for hex, bytearray and number handling.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport {\n type CHash,\n type TypedArray,\n abytes,\n abytes as abytes_,\n concatBytes,\n isLE,\n randomBytes as randb,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Asserts that a value is a byte array and optionally checks its length.\n * Returns the original reference unchanged on success, and currently also accepts Node `Buffer`\n * values through the upstream validator.\n * This helper throws on malformed input, so APIs that must return `false` need to guard lengths\n * before decoding or before calling it.\n * @example\n * Validate that a value is a byte array with the expected length.\n * ```ts\n * abytes(new Uint8Array([1]), 1);\n * ```\n */\nconst abytesDoc: typeof abytes = abytes;\nexport { abytesDoc as abytes };\n/**\n * Concatenates byte arrays into a new `Uint8Array`.\n * Zero arguments return an empty `Uint8Array`.\n * Invalid segments throw before allocation because each argument is validated first.\n * @example\n * Concatenate two byte arrays into one result.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nconst concatBytesDoc: typeof concatBytes = concatBytes;\nexport { concatBytesDoc as concatBytes };\n/**\n * Returns cryptographically secure random bytes.\n * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable.\n * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation,\n * so negative and fractional values both throw instead of truncating through JS `ToIndex`.\n * @param bytesLength - Number of random bytes to generate.\n * @returns Fresh random bytes.\n * @example\n * Generate a fresh random seed.\n * ```ts\n * const seed = randomBytes(4);\n * ```\n */\nexport const randomBytes: typeof randb = randb;\n\n/**\n * Compares two byte arrays in a length-constant way for equal lengths.\n * Unequal lengths return `false` immediately, and there is no runtime type validation.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns Whether both arrays contain the same bytes.\n * @example\n * Compare two byte arrays for equality.\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies bytes into a fresh `Uint8Array`.\n * Returns a detached plain `Uint8Array` after validating that the input is real bytes.\n * @param bytes - Source bytes.\n * @returns Copy of the input bytes.\n * @example\n * Copy bytes into a fresh array.\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Byte-swaps each 64-bit lane in place.\n * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need\n * this boundary helper before aliasing them as host `Float64Array` lanes.\n * @param arr - Byte buffer whose length is a multiple of 8.\n * @returns The same buffer after in-place 64-bit lane byte swaps.\n * @example\n * Byte-swap one 64-bit lane in place.\n * ```ts\n * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport function byteSwap64<T extends ArrayBufferView>(arr: T): T {\n const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n for (let i = 0; i < bytes.length; i += 8) {\n const a0 = bytes[i + 0];\n const a1 = bytes[i + 1];\n const a2 = bytes[i + 2];\n const a3 = bytes[i + 3];\n bytes[i + 0] = bytes[i + 7];\n bytes[i + 1] = bytes[i + 6];\n bytes[i + 2] = bytes[i + 5];\n bytes[i + 3] = bytes[i + 4];\n bytes[i + 4] = a3;\n bytes[i + 5] = a2;\n bytes[i + 6] = a1;\n bytes[i + 7] = a0;\n }\n return arr;\n}\n/**\n * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian.\n * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as\n * `Float64Array` lanes on the current host.\n * @param arr - Buffer to pass through or swap in place.\n * @returns The same buffer, normalized for Falcon's little-endian table layout.\n * @example\n * Normalize one host-endian buffer for Falcon's float tables.\n * ```ts\n * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport const baswap64If: <T extends ArrayBufferView>(arr: T) => T = isLE\n ? (arr) => arr\n : byteSwap64;\n\n/** Shared key-generation surface for signers and KEMs. */\nexport type CryptoKeys = {\n /** Optional metadata about the algorithm family or variant. */\n info?: { type?: string };\n /** Public byte lengths for the exported key material. */\n lengths: { seed?: number; publicKey?: number; secretKey?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: TArg<Uint8Array>) => {\n secretKey: TRet<Uint8Array>;\n publicKey: TRet<Uint8Array>;\n };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/** Verification options shared by the signature APIs. */\nexport type VerOpts = {\n /** Optional application-defined context string. */\n context?: Uint8Array;\n};\n/** Signing options shared by the signature APIs. */\nexport type SigOpts = VerOpts & {\n // Compatibility with @noble/curves: false to disable, enabled by default, user can pass U8A\n /** Optional extra entropy or `false` to disable randomized signing. */\n extraEntropy?: Uint8Array | false;\n};\n\n/**\n * Validates that an options bag is a plain object.\n * @param opts - Options object to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate that an options bag is a plain object.\n * ```ts\n * validateOpts({});\n * ```\n */\nexport function validateOpts(opts: object): void {\n // Arrays silently passed here before, but these call sites expect named option-bag fields.\n if (Object.prototype.toString.call(opts) !== '[object Object]')\n throw new TypeError('expected valid options object');\n}\n\n/**\n * Validates common verification options.\n * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support\n * further after this shared plain-object gate.\n * @param opts - Verification options. See {@link VerOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common verification options.\n * ```ts\n * validateVerOpts({ context: new Uint8Array([1]) });\n * ```\n */\nexport function validateVerOpts(opts: TArg<VerOpts>): void {\n validateOpts(opts);\n if (opts.context !== undefined) abytes(opts.context, undefined, 'opts.context');\n}\n\n/**\n * Validates common signing options.\n * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific\n * restrictions are enforced later by callers.\n * @param opts - Signing options. See {@link SigOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common signing options.\n * ```ts\n * validateSigOpts({ extraEntropy: new Uint8Array([1]) });\n * ```\n */\nexport function validateSigOpts(opts: TArg<SigOpts>): void {\n validateVerOpts(opts);\n if (opts.extraEntropy !== false && opts.extraEntropy !== undefined)\n abytes(opts.extraEntropy, undefined, 'opts.extraEntropy');\n}\n\n/** Generic signature interface with key generation, signing, and verification. */\nexport type Signer = CryptoKeys & {\n /** Public byte lengths for signatures and signing randomness. */\n lengths: { signRand?: number; signature?: number };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing options.\n * @returns Signature bytes.\n */\n sign: (\n msg: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts?: TArg<SigOpts>\n ) => TRet<Uint8Array>;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @param opts - Optional verification options.\n * @returns `true` when the signature is valid, `false` when all inputs are well-formed but the\n * signature check does not pass. Some implementations also treat malformed signature encodings as\n * a verification failure and return `false`.\n * @throws On malformed API arguments or unsupported verification options.\n */\n verify: (\n sig: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n opts?: TArg<VerOpts>\n ) => boolean;\n};\n\n/** Generic key encapsulation mechanism interface. */\nexport type KEM = CryptoKeys & {\n /** Public byte lengths for ciphertexts and optional message randomness. */\n lengths: { cipherText?: number; msg?: number; msgRand?: number };\n /**\n * Encapsulate one shared secret to a recipient public key.\n * @param publicKey - Recipient public key bytes.\n * @param msg - Optional caller-provided randomness/message seed.\n * @returns Ciphertext plus shared secret.\n */\n encapsulate: (\n publicKey: TArg<Uint8Array>,\n msg?: TArg<Uint8Array>\n ) => {\n cipherText: TRet<Uint8Array>;\n sharedSecret: TRet<Uint8Array>;\n };\n /**\n * Recover the shared secret from a ciphertext and recipient secret key.\n * @param cipherText - Ciphertext bytes.\n * @param secretKey - Recipient secret key bytes.\n * @returns Decapsulated shared secret.\n */\n decapsulate: (cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/** Bidirectional encoder/decoder interface. */\nexport interface Coder<F, T> {\n /**\n * Serialize one value.\n * @param from - Value to encode.\n * @returns Encoded representation.\n */\n encode(from: F): T;\n /**\n * Parse one serialized value.\n * @param to - Encoded representation.\n * @returns Decoded value.\n */\n decode(to: T): F;\n}\n\n/** Encoder/decoder interface specialized for byte arrays. */\nexport interface BytesCoder<T> extends Coder<T, Uint8Array> {\n /**\n * Serialize one value into bytes.\n * @param data - Value to encode.\n * @returns Encoded bytes.\n */\n encode: (data: T) => Uint8Array;\n /**\n * Parse one byte array into a value.\n * @param bytes - Encoded bytes.\n * @returns Decoded value.\n */\n decode: (bytes: Uint8Array) => T;\n}\n\n/** Fixed-length byte encoder/decoder. */\nexport type BytesCoderLen<T> = BytesCoder<T> & { bytesLen: number };\n\n// nano-packed, because struct encoding is hard.\ntype UnCoder<T> = T extends BytesCoder<infer U> ? U : never;\ntype SplitOut<T extends (number | BytesCoderLen<any>)[]> = {\n [K in keyof T]: T[K] extends number ? Uint8Array : UnCoder<T[K]>;\n};\n/**\n * Builds a fixed-layout coder from byte lengths and nested coders.\n * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that\n * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder`\n * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards\n * caller-owned bytes, it must do so only after detaching them into a disposable copy.\n * @param label - Label used in validation errors.\n * @param lengths - Field lengths or nested coders.\n * @returns Composite fixed-length coder.\n * @example\n * Build a fixed-layout coder from byte lengths and nested coders.\n * ```ts\n * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]);\n * ```\n */\nexport function splitCoder<T extends (number | BytesCoderLen<any>)[]>(\n label: string,\n ...lengths: T\n): TRet<BytesCoder<SplitOut<T>> & { bytesLen: number }> {\n const getLength = (c: TArg<number | BytesCoderLen<any>>) =>\n typeof c === 'number' ? c : (c as BytesCoderLen<any>).bytesLen;\n const bytesLen: number = lengths.reduce((sum: number, a) => sum + getLength(a), 0);\n return {\n bytesLen,\n encode: (bufs: T) => {\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < lengths.length; i++) {\n const c = lengths[i];\n const l = getLength(c);\n const b: Uint8Array = typeof c === 'number' ? (bufs[i] as any) : c.encode(bufs[i]);\n abytes_(b, l, label);\n res.set(b, pos);\n if (typeof c !== 'number') b.fill(0); // clean\n pos += l;\n }\n return res;\n },\n decode: (buf: TArg<Uint8Array>) => {\n abytes_(buf, bytesLen, label);\n const res = [];\n for (const c of lengths) {\n const l = getLength(c);\n const b = buf.subarray(0, l);\n res.push(typeof c === 'number' ? b : c.decode(b));\n buf = buf.subarray(l);\n }\n return res as SplitOut<T>;\n },\n } as any;\n}\n// nano-packed.array (fixed size)\n/**\n * Builds a fixed-length vector coder from another fixed-length coder.\n * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder.\n * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into\n * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned\n * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts\n * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes.\n * @param c - Element coder.\n * @param vecLen - Number of elements in the vector.\n * @returns Fixed-length vector coder.\n * @example\n * Build a fixed-length vector coder from another fixed-length coder.\n * ```ts\n * vecCoder(\n * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 },\n * 2\n * ).encode([1, 2]);\n * ```\n */\nexport function vecCoder<T>(c: TArg<BytesCoderLen<T>>, vecLen: number): TRet<BytesCoderLen<T[]>> {\n const coder = c as BytesCoderLen<T>;\n const bytesLen = vecLen * coder.bytesLen;\n return {\n bytesLen,\n encode: (u: TArg<T[]>): TRet<Uint8Array> => {\n if (u.length !== vecLen)\n throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < u.length; i++) {\n const b = coder.encode(u[i] as T);\n res.set(b, pos);\n b.fill(0); // clean\n pos += b.length;\n }\n return res as TRet<Uint8Array>;\n },\n decode: (a: TArg<Uint8Array>): TRet<T[]> => {\n abytes_(a, bytesLen);\n const r: T[] = [];\n for (let i = 0; i < a.length; i += coder.bytesLen)\n r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));\n return r as TRet<T[]>;\n },\n } as any;\n}\n\n/**\n * Overwrites supported typed-array inputs with zeroes in place.\n * Accepts direct typed arrays and one-level arrays of them.\n * @param list - Typed arrays or one-level lists of typed arrays to clear.\n * @example\n * Overwrite typed arrays with zeroes.\n * ```ts\n * const buf = Uint8Array.of(1, 2, 3);\n * cleanBytes(buf);\n * ```\n */\nexport function cleanBytes(...list: (TypedArray | TypedArray[])[]): void {\n for (const t of list) {\n if (Array.isArray(t)) for (const b of t) b.fill(0);\n else t.fill(0);\n }\n}\n\n/**\n * Creates a 32-bit mask with the lowest `bits` bits set.\n * @param bits - Number of low bits to keep.\n * @returns Bit mask with `bits` ones.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Create a low-bit mask for packed-field operations.\n * ```ts\n * const mask = getMask(4);\n * ```\n */\nexport function getMask(bits: number): number {\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new RangeError(`expected bits in [0..32], got ${bits}`);\n // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask.\n return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0;\n}\n\n/** Shared empty byte array used as the default context. */\nexport const EMPTY: TRet<Uint8Array> = /* @__PURE__ */ Uint8Array.of();\n\n/**\n * Builds the domain-separated message payload for the pure sign/verify paths.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated message payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated payload before direct signing.\n * ```ts\n * const payload = getMessage(new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessage(msg: TArg<Uint8Array>, ctx: TArg<Uint8Array> = EMPTY): TRet<Uint8Array> {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);\n}\n\n// DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the\n// FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128,\n// SHAKE256, or another approved hash/XOF under that subtree.\n// 06 09 60 86 48 01 65 03 04 02\nconst oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]);\n\n/**\n * Validates that a hash exposes a NIST hash OID and enough collision resistance.\n * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST\n * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough.\n * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend\n * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes.\n * @param hash - Hash function to validate.\n * @param requiredStrength - Minimum required collision-resistance strength in bits.\n * @throws If the hash metadata or collision resistance is insufficient. {@link Error}\n * @example\n * Validate that a hash exposes a NIST hash OID and enough collision resistance.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { checkHash } from '@noble/post-quantum/utils.js';\n * checkHash(sha256, 128);\n * ```\n */\nexport function checkHash(hash: CHash, requiredStrength: number = 0): void {\n if (!hash.oid || !equalBytes(hash.oid.subarray(0, 10), oidNistP))\n throw new Error('hash.oid is invalid: expected NIST hash');\n // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST\n // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is\n // the tighter runtime check, so enforce that lower bound here.\n const collisionResistance = (hash.outputLen * 8) / 2;\n if (requiredStrength > collisionResistance) {\n throw new Error(\n 'Pre-hash security strength too low: ' +\n collisionResistance +\n ', required: ' +\n requiredStrength\n );\n }\n}\n\n/**\n * Builds the domain-separated prehash payload for the prehash sign/verify paths.\n * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper\n * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param hash - Prehash function.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated prehash payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated prehash payload for external hashing.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { getMessagePrehash } from '@noble/post-quantum/utils.js';\n * getMessagePrehash(sha256, new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessagePrehash(\n hash: CHash,\n msg: TArg<Uint8Array>,\n ctx: TArg<Uint8Array> = EMPTY\n): TRet<Uint8Array> {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n const hashed = hash(msg);\n return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid!, hashed);\n}\n","/**\n * Internal methods for lattice-based ML-KEM and ML-DSA.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { FFTCore, reverseBits } from '@noble/curves/abstract/fft.js';\nimport { shake128, shake256 } from '@noble/hashes/sha3.js';\nimport type { TypedArray } from '@noble/hashes/utils.js';\nimport {\n type BytesCoderLen,\n cleanBytes,\n type Coder,\n getMask,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/** Extendable-output reader used by the CRYSTALS implementations. */\nexport type XOF = (\n seed: Uint8Array,\n blockLen?: number\n) => {\n /**\n * Read diagnostic counters for the current XOF session.\n * @returns Current call and XOF block counters.\n */\n stats: () => { calls: number; xofs: number };\n /**\n * Select one `(x, y)` coordinate pair and get a block reader for it.\n * Only one coordinate stream is live at a time: a later `get(...)` call rebinds the shared\n * SHAKE state and invalidates older readers.\n * Each squeeze aliases one mutable internal output buffer, so callers must copy blocks they\n * want to retain before the next read.\n * @param x - First matrix coordinate.\n * @param y - Second matrix coordinate.\n * @returns Lazy block reader for that coordinate pair.\n */\n get: (x: number, y: number) => () => Uint8Array; // return block aligned to blockLen and 3\n /** Wipe any buffered state once the reader is no longer needed. */\n clean: () => void;\n};\n\n/** CRYSTALS (ml-kem, ml-dsa) options */\n/** Shared polynomial and NTT parameters for CRYSTALS algorithms. */\nexport type CrystalOpts<T extends TypedArray> = {\n /**\n * Allocate one zeroed polynomial/vector container.\n * @param n - Number of coefficients to allocate.\n * @returns Fresh typed container.\n */\n newPoly: TypedCons<T>;\n /** Polynomial size, typically `256`. */\n N: number;\n /** Prime modulus used for all coefficient arithmetic. */\n Q: number;\n /** Inverse transform normalization factor:\n * `256**-1 mod q` for Dilithium, `128**-1 mod q` for Kyber.\n */\n F: number;\n /** Principal root of unity for the transform domain. */\n ROOT_OF_UNITY: number;\n /** Number of bits used for bit-reversal ordering. */\n brvBits: number;\n /** `true` for Kyber/ML-KEM mode, `false` for Dilithium/ML-DSA mode. */\n isKyber: boolean;\n};\n\n/** Constructor function for typed polynomial containers. */\nexport type TypedCons<T extends TypedArray> = (n: number) => T;\n\ntype Crystals<T extends TypedArray> = {\n mod: (a: number, modulo?: number) => number;\n smod: (a: number, modulo?: number) => number;\n nttZetas: T;\n NTT: {\n /** Forward transform in place. Mutates and returns `r`. */\n encode: (r: T) => T;\n /** Inverse transform in place. Mutates and returns `r`. */\n decode: (r: T) => T;\n };\n bitsCoder: (d: number, c: Coder<number, number>) => BytesCoderLen<T>;\n};\n\n/**\n * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes.\n * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}.\n * @returns CRYSTALS arithmetic and encoding helpers.\n * @example\n * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set.\n * ```ts\n * const crystals = genCrystals({\n * newPoly: (n) => new Uint16Array(n),\n * N: 256,\n * Q: 3329,\n * F: 3303,\n * ROOT_OF_UNITY: 17,\n * brvBits: 7,\n * isKyber: true,\n * });\n * const reduced = crystals.mod(-1);\n * ```\n */\nexport const genCrystals = <T extends TypedArray>(opts: CrystalOpts<T>): TRet<Crystals<T>> => {\n // isKyber: true means Kyber, false means Dilithium\n const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;\n // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by\n // FIPS 203 §2.3 / FIPS 204 §2.3 before downstream mod-q arithmetic.\n const mod = (a: number, modulo = Q): number => {\n const result = a % modulo | 0;\n return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0;\n };\n // FIPS 204 §7.4 uses the centered `mod ±` representative for low bits, keeping the\n // positive midpoint when `modulo` is even.\n // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`.\n const smod = (a: number, modulo = Q): number => {\n const r = mod(a, modulo) | 0;\n return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0;\n };\n // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while\n // Dilithium uses the FIPS 204 §7.5 / Appendix B `BitRev_8` zetas table over all 256 entries.\n function getZettas() {\n const out = newPoly(N);\n for (let i = 0; i < N; i++) {\n const b = reverseBits(i, brvBits);\n const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);\n out[i] = Number(p) | 0;\n }\n return out;\n }\n const nttZetas = getZettas();\n\n // Number-Theoretic Transform\n // Explained: https://electricdusk.com/ntt.html\n\n // Kyber has slightly different params, since there is no 512th primitive root of unity mod q,\n // only 256th primitive root of unity mod. Which also complicates MultiplyNTT.\n\n const field = {\n add: (a: number, b: number) => mod((a | 0) + (b | 0)) | 0,\n sub: (a: number, b: number) => mod((a | 0) - (b | 0)) | 0,\n mul: (a: number, b: number) => mod((a | 0) * (b | 0)) | 0,\n inv: (_a: number) => {\n throw new Error('not implemented');\n },\n };\n const nttOpts = {\n N,\n roots: nttZetas as any,\n invertButterflies: true,\n skipStages: isKyber ? 1 : 0,\n brp: false,\n };\n const dif = FFTCore(field, { dit: false, ...nttOpts });\n const dit = FFTCore(field, { dit: true, ...nttOpts });\n const NTT = {\n encode: (r: T): T => {\n return dif(r) as any;\n },\n decode: (r: T): T => {\n dit(r as any);\n // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14\n // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`.\n // kyber uses 128 here, because brv && stuff\n for (let i = 0; i < r.length; i++) r[i] = mod(F * r[i]);\n return r;\n },\n };\n // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode /\n // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers.\n const bitsCoder = (d: number, c: Coder<number, number>): TRet<BytesCoderLen<T>> => {\n const mask = getMask(d);\n const bytesLen = d * (N / 8);\n return {\n bytesLen,\n encode: (poly_: TArg<T>): TRet<Uint8Array> => {\n const poly = poly_ as T;\n const r = new Uint8Array(bytesLen);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {\n buf |= (c.encode(poly[i]) & mask) << bufLen;\n bufLen += d;\n for (; bufLen >= 8; bufLen -= 8, buf >>= 8) r[pos++] = buf & getMask(bufLen);\n }\n return r as TRet<Uint8Array>;\n },\n decode: (bytes: TArg<Uint8Array>): TRet<T> => {\n const r = newPoly(N);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {\n buf |= bytes[i] << bufLen;\n bufLen += 8;\n for (; bufLen >= d; bufLen -= d, buf >>= d) r[pos++] = c.decode(buf & mask);\n }\n return r as TRet<T>;\n },\n } as TRet<BytesCoderLen<T>>;\n };\n\n return {\n mod,\n smod,\n nttZetas: nttZetas as TRet<T>,\n NTT: {\n encode: (r: TArg<T>): TRet<T> => NTT.encode(r as T) as TRet<T>,\n decode: (r: TArg<T>): TRet<T> => NTT.decode(r as T) as TRet<T>,\n },\n bitsCoder: bitsCoder as TRet<Crystals<T>>['bitsCoder'],\n };\n};\n\nconst createXofShake =\n (shake: typeof shake128): TRet<XOF> =>\n (seed: TArg<Uint8Array>, blockLen?: number) => {\n if (!blockLen) blockLen = shake.blockLen;\n // Optimizations that won't mater:\n // - cached seed update (two .update(), on start and on the end)\n // - another cache which cloned into working copy\n\n // Faster than multiple updates, since seed less than blockLen\n const _seed = new Uint8Array(seed.length + 2);\n _seed.set(seed);\n const seedLen = seed.length;\n const buf = new Uint8Array(blockLen); // == shake128.blockLen\n let h = shake.create({});\n let calls = 0;\n let xofs = 0;\n return {\n stats: () => ({ calls, xofs }),\n get: (x: number, y: number) => {\n // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate\n // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`.\n _seed[seedLen + 0] = x;\n _seed[seedLen + 1] = y;\n h.destroy();\n h = shake.create({}).update(_seed);\n calls++;\n return () => {\n xofs++;\n return h.xofInto(buf) as TRet<Uint8Array>;\n };\n },\n clean: () => {\n h.destroy();\n cleanBytes(buf, _seed);\n },\n };\n };\n\n/**\n * SHAKE128-based extendable-output reader factory used by ML-KEM.\n * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously\n * returned readers, and each squeeze reuses one mutable internal output buffer.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-KEM SHAKE128 matrix expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF128 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF128(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF128: TRet<XOF> = /* @__PURE__ */ createXofShake(shake128);\n/**\n * SHAKE256-based extendable-output reader factory used by ML-DSA.\n * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned\n * readers, and reuses one mutable internal output buffer for each squeeze.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-DSA SHAKE256 coefficient expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF256 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF256(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF256: TRet<XOF> = /* @__PURE__ */ createXofShake(shake256);\n","/**\n * ML-KEM: Module Lattice-based Key Encapsulation Mechanism from\n * [FIPS-203](https://csrc.nist.gov/pubs/fips/203/ipd). A.k.a. CRYSTALS-Kyber.\n *\n * Key encapsulation is similar to DH / ECDH (think X25519), with important differences:\n * * Unlike in ECDH, we can't verify if it was \"Bob\" who've sent the shared secret\n * * Unlike ECDH, it is probabalistic and relies on quality of randomness (CSPRNG).\n * * Decapsulation never throws an error, even when shared secret was\n * encrypted by a different public key. It will just return a different shared secret.\n *\n * There are some concerns with regards to security: see\n * [djb blog](https://blog.cr.yp.to/20231003-countcorrectly.html) and\n * [mailing list](https://groups.google.com/a/list.nist.gov/g/pqc-forum/c/W2VOzy0wz_E).\n *\n * Has similar internals to ML-DSA, but their keys and params are different.\n *\n * Check out [official site](https://www.pq-crystals.org/kyber/resources.shtml),\n * [repo](https://github.com/pq-crystals/kyber),\n * [spec](https://datatracker.ietf.org/doc/draft-cfrg-schwabe-kyber/).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { sha3_256, sha3_512, shake256 } from '@noble/hashes/sha3.js';\nimport { type CHash, swap32IfBE, u32 } from '@noble/hashes/utils.js';\nimport { genCrystals, type XOF, XOF128 } from './_crystals.ts';\nimport {\n abytes,\n cleanBytes,\n type Coder,\n copyBytes,\n equalBytes,\n getMask,\n type KEM,\n randomBytes,\n splitCoder,\n type TArg,\n type TRet,\n vecCoder,\n} from './utils.ts';\n\n/** Key encapsulation mechanism interface */\n\nconst N = 256; // Kyber (not FIPS-203) supports different lengths, but all std modes were using 256\nconst Q = 3329; // 13*(2**8)+1, modulo prime\nconst F = 3303; // 3303 ≡ 128**(−1) mod q (FIPS-203)\nconst ROOT_OF_UNITY = 17; // ζ = 17 ∈ Zq is a primitive 256-th root of unity modulo Q. ζ**128 ≡−1\n// treeshake: keep genCrystals behind the object so PARAMS-only bundles can drop it entirely.\n// Shared CRYSTALS helper in the ML-KEM branch: Kyber mode, 7-bit bit-reversal,\n// and Uint16Array polys because current coefficients stay reduced modulo q.\nconst crystals = /* @__PURE__ */ genCrystals({\n N,\n Q,\n F,\n ROOT_OF_UNITY,\n newPoly: (n: number): TRet<Uint16Array> => new Uint16Array(n) as TRet<Uint16Array>,\n brvBits: 7,\n isKyber: true,\n});\n\n/** FIPS 203: 7. Parameter Sets */\n/** Public ML-KEM parameter-set description. */\nexport type KEMParam = {\n /** Polynomial size. */\n N: number;\n /** Module rank. */\n K: number;\n /** Prime modulus. */\n Q: number;\n /** CBD parameter used for secret-key noise. */\n ETA1: number;\n /** CBD parameter used for error noise. */\n ETA2: number;\n /** Compression width for the `u` vector. */\n du: number;\n /** Compression width for the `v` polynomial. */\n dv: number;\n /** Required strength of the randomness source in bits. */\n RBGstrength: number;\n};\n/** Internal params of ML-KEM versions */\n// prettier-ignore\n/** Built-in ML-KEM parameter presets keyed by the public export names\n * `ml_kem512` / `ml_kem768` / `ml_kem1024`.\n * `RBGstrength` is Table 2's required randomness-source strength in bits,\n * not a generic security label.\n */\nexport const PARAMS: Record<string, KEMParam> = /* @__PURE__ */ (() =>\n Object.freeze({\n 512: Object.freeze({ N, Q, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),\n 768: Object.freeze({ N, Q, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),\n 1024: Object.freeze({ N, Q, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 }),\n } as const))();\n\n// FIPS-203: compress/decompress\nconst compress = (d: number): Coder<number, number> => {\n // d=12 is the ByteEncode12/ByteDecode12 path, not lossy compression.\n // ByteDecode12 interprets each 12-bit word modulo q; without that reduction the public-key\n // modulus check in encapsulate() becomes a no-op for malformed coefficients like 4095.\n if (d >= 12) return { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) };\n // Comments map to python implementation in RFC (draft-cfrg-schwabe-kyber)\n // const round = (i: number) => Math.floor(i + 0.5) | 0;\n const a = 2 ** (d - 1);\n return {\n // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).\n encode: (i: number) => ((i << d) + Q / 2) / Q,\n // const decompress = (i: number) => round((Q / 2 ** d) * i);\n decode: (i: number) => (i * Q + a) >>> d,\n };\n};\n\n// Raw ByteEncode_d / ByteDecode_d from FIPS 203 operate on d-bit words directly.\n// That differs from `polyCoder(d)` for d<12, where noble folds packing together with the lossy\n// ciphertext compression step used by u/v. Tests that exercise the spec's raw packing surface need\n// this exact non-lossy variant instead.\nconst byteCoder = (d: number) =>\n crystals.bitsCoder(\n d,\n d === 12\n ? { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) }\n : { encode: (i: number) => i, decode: (i: number) => i }\n );\n\n// NOTE: we merge encoding and compress because it is faster, also both require same d param\n// d=12 is the ByteEncode12/ByteDecode12 path rather than compression, and caller-side\n// public-key modulus checks route through this helper's decode/encode roundtrip.\n// Converts between bytes and d-bits compressed representation.\n// Kinda like convertRadix2 from @scure/base.\n// decode(encode(t)) == t, but there is loss of information on encode(decode(t))\nconst polyCoder = (d: number) => (d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d)));\n\n// Poly is mod Q, so 12 bits\ntype Poly = Uint16Array;\n\nfunction polyAdd(a_: TArg<Poly>, b_: TArg<Poly>) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] + b[i]); // a += b\n}\nfunction polySub(a_: TArg<Poly>, b_: TArg<Poly>) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] - b[i]); // a -= b\n}\n\n// FIPS-203: Computes the product of two degree-one polynomials with respect to a quadratic modulus\nfunction BaseCaseMultiply(a0: number, a1: number, b0: number, b1: number, zeta: number) {\n // `zeta` here is Algorithm 11's γ = ζ^(2BitRev_7(i)+1).\n const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);\n const c1 = crystals.mod(a0 * b1 + a1 * b0);\n return { c0, c1 };\n}\n\n// FIPS-203: Computes the product (in the ring Tq) of two NTT representations.\n// Works in place on `f`; `g` is read-only and both inputs must already be in NTT form.\nfunction MultiplyNTTs(f_: TArg<Poly>, g_: TArg<Poly>): TRet<Poly> {\n const f = f_ as Poly;\n const g = g_ as Poly;\n for (let i = 0; i < N / 2; i++) {\n let z = crystals.nttZetas[64 + (i >> 1)];\n if (i & 1) z = -z;\n const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);\n f[2 * i + 0] = c0;\n f[2 * i + 1] = c1;\n }\n return f as TRet<Poly>;\n}\n\ntype PRF = (l: number, key: Uint8Array, nonce: number) => Uint8Array;\n\ntype XofGet = ReturnType<ReturnType<XOF>['get']>;\n\ntype KyberOpts = KEMParam & {\n HASH256: CHash;\n HASH512: CHash;\n KDF: CHash<any, { dkLen?: number }>;\n XOF: XOF; // (seed: Uint8Array, len: number, x: number, y: number) => Uint8Array;\n PRF: PRF;\n};\n\n// Return poly in NTT representation\nfunction SampleNTT(xof_: TArg<XofGet>): TRet<Poly> {\n const xof = xof_ as XofGet;\n // The reader must already bind the Algorithm 7 seed||j||i bytes\n // and return block lengths divisible by 3.\n const r: Poly = new Uint16Array(N);\n for (let j = 0; j < N; ) {\n const b = xof();\n if (b.length % 3) throw new Error('SampleNTT: unaligned block');\n for (let i = 0; j < N && i + 3 <= b.length; i += 3) {\n const d1 = ((b[i + 0] >> 0) | (b[i + 1] << 8)) & 0xfff;\n const d2 = ((b[i + 1] >> 4) | (b[i + 2] << 4)) & 0xfff;\n if (d1 < Q) r[j++] = d1;\n if (j < N && d2 < Q) r[j++] = d2;\n }\n }\n return r as TRet<Poly>;\n}\n\n// Sampling from the centered binomial distribution\n// Returns poly with small coefficients (noise/errors) stored modulo q in ordinary coefficient form.\n// Current callers only use Table 2 eta values {2,3} and PRF outputs of exactly 64*eta bytes.\nconst sampleCBDBytes = (buf: TArg<Uint8Array>, eta: number): TRet<Poly> => {\n const r: Poly = new Uint16Array(N);\n // CBD consumes the PRF bitstream in little-endian byte order; normalize the word view on BE,\n // then swap it back so callers still observe `buf` as read-only.\n const b32 = u32(buf);\n swap32IfBE(b32);\n let len = 0;\n for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {\n let b = b32[i];\n for (let j = 0; j < 32; j++) {\n bb += b & 1;\n b >>= 1;\n len += 1;\n if (len === eta) {\n t0 = bb;\n bb = 0;\n } else if (len === 2 * eta) {\n r[p++] = crystals.mod(t0 - bb);\n bb = 0;\n len = 0;\n }\n }\n }\n swap32IfBE(b32);\n if (len) throw new Error(`sampleCBD: leftover bits: ${len}`);\n return r as TRet<Poly>;\n};\n\nfunction sampleCBD(\n PRF_: TArg<PRF>,\n seed: TArg<Uint8Array>,\n nonce: number,\n eta: number\n): TRet<Poly> {\n const PRF = PRF_ as PRF;\n return sampleCBDBytes(PRF((eta * N) / 4, seed, nonce), eta);\n}\n\n// K-PKE\n// Internal ML-KEM subroutine only: exact 32-byte `seed` / `msg` inputs\n// come from Algorithms 13-15, and the helper mutates decoded temporary\n// polynomials in place while leaving caller byte arrays unchanged.\nconst genKPKE = (opts_: TArg<KyberOpts>) => {\n const opts = opts_ as KyberOpts;\n const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts;\n const poly1 = polyCoder(1);\n const polyV = polyCoder(dv);\n const polyU = polyCoder(du);\n const publicCoder = splitCoder('publicKey', vecCoder(polyCoder(12), K), 32);\n const secretCoder = vecCoder(polyCoder(12), K);\n const cipherCoder = splitCoder('ciphertext', vecCoder(polyU, K), polyV);\n const seedCoder = splitCoder('seed', 32, 32);\n return {\n secretCoder,\n lengths: {\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n cipherText: cipherCoder.bytesLen,\n },\n keygen: (seed: TArg<Uint8Array>) => {\n abytes(seed, 32, 'seed');\n const seedDst = new Uint8Array(33);\n seedDst.set(seed);\n // FIPS 203 Algorithm 13 appends the parameter-set byte `k`\n // before `G(d || k)`, so expanding the same 32-byte seed\n // under a different ML-KEM parameter set yields unrelated keys.\n seedDst[32] = K;\n const seedHash = HASH512(seedDst);\n\n const [rho, sigma] = seedCoder.decode(seedHash);\n const sHat: Poly[] = [];\n const tHat: Poly[] = [];\n for (let i = 0; i < K; i++) sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));\n const x = XOF(rho);\n for (let i = 0; i < K; i++) {\n const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));\n for (let j = 0; j < K; j++) {\n const aji = SampleNTT(x.get(j, i)); // A[i][j], inplace\n polyAdd(e, MultiplyNTTs(aji, sHat[j]));\n }\n tHat.push(e); // t ← A ◦ s + e\n }\n x.clean();\n const res = {\n publicKey: publicCoder.encode([tHat, rho]),\n secretKey: secretCoder.encode(sHat),\n };\n cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);\n return res;\n },\n encrypt: (\n publicKey: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n seed: TArg<Uint8Array>\n ): TRet<Uint8Array> => {\n const [tHat, rho] = publicCoder.decode(publicKey);\n const rHat = [];\n for (let i = 0; i < K; i++) rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));\n const x = XOF(rho);\n const tmp2 = new Uint16Array(N);\n const u = [];\n for (let i = 0; i < K; i++) {\n const e1 = sampleCBD(PRF, seed, K + i, ETA2);\n const tmp = new Uint16Array(N);\n for (let j = 0; j < K; j++) {\n const aij = SampleNTT(x.get(i, j)); // A[j][i], inplace transpose access\n polyAdd(tmp, MultiplyNTTs(aij, rHat[j])); // t += aij * rHat[j]\n }\n polyAdd(e1, crystals.NTT.decode(tmp)); // e1 += tmp\n u.push(e1);\n polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i])); // t2 += tHat[i] * rHat[i]\n cleanBytes(tmp);\n }\n x.clean();\n const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);\n polyAdd(e2, crystals.NTT.decode(tmp2)); // e2 += tmp2\n const v = poly1.decode(msg); // encode plaintext m into polynomial v\n polyAdd(v, e2); // v += e2\n cleanBytes(tHat, rHat, tmp2, e2);\n return cipherCoder.encode([u, v]) as TRet<Uint8Array>;\n },\n decrypt: (cipherText: TArg<Uint8Array>, privateKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n const [u, v] = cipherCoder.decode(cipherText);\n const sk = secretCoder.decode(privateKey); // s ← ByteDecode_12(dkPKE)\n const tmp = new Uint16Array(N);\n // tmp += sk[i] * u[i]\n for (let i = 0; i < K; i++) polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));\n polySub(v, crystals.NTT.decode(tmp)); // w = v' - tmp\n cleanBytes(tmp, sk, u);\n return poly1.encode(v) as TRet<Uint8Array>;\n },\n };\n};\n\n/**\n * Public ML-KEM wrapper over the internal K-PKE subroutine.\n * `keygen(seed)` and `encapsulate(publicKey, msg)` are deterministic/test-oriented hooks that map\n * more directly to Algorithms 16-17 than to the pure no-input / random-internal Algorithms 19-20.\n * decapsulate() tries to follow the Algorithms 18/21 implicit-reject structure as closely as\n * practical here by re-encrypting, comparing ciphertexts, returning `Khat` on match or `Kbar` on\n * mismatch, and zeroizing the non-returned shared-secret candidate; JS/JIT still provides no\n * constant-time guarantees for that path.\n */\nfunction createKyber(opts: TArg<KyberOpts>): TRet<KEM> {\n const rawOpts = opts as KyberOpts;\n const KPKE = genKPKE(rawOpts);\n const { HASH256, HASH512, KDF } = rawOpts;\n const { secretCoder: KPKESecretCoder, lengths } = KPKE;\n const secretCoder = splitCoder('secretKey', lengths.secretKey, lengths.publicKey, 32, 32);\n const msgLen = 32;\n const seedLen = 64;\n const kemLengths = Object.freeze({\n ...lengths,\n seed: 64,\n msg: msgLen,\n msgRand: msgLen,\n secretKey: secretCoder.bytesLen,\n });\n return Object.freeze({\n info: Object.freeze({ type: 'ml-kem' }),\n lengths: kemLengths,\n keygen: (seed: TArg<Uint8Array> = randomBytes(seedLen)) => {\n abytes(seed, seedLen, 'seed');\n const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));\n const publicKeyHash = HASH256(publicKey);\n // (dkPKE||ek||H(ek)||z)\n const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);\n cleanBytes(sk, publicKeyHash);\n return {\n publicKey: publicKey as TRet<Uint8Array>,\n secretKey: secretKey as TRet<Uint8Array>,\n };\n },\n getPublicKey: (secretKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);\n return Uint8Array.from(publicKey) as TRet<Uint8Array>;\n },\n encapsulate: (publicKey: TArg<Uint8Array>, msg: TArg<Uint8Array> = randomBytes(msgLen)) => {\n abytes(publicKey, lengths.publicKey, 'publicKey');\n abytes(msg, msgLen, 'message');\n\n // FIPS-203 includes additional verification check for modulus\n const eke = publicKey.subarray(0, 384 * opts.K);\n // Copy because of inplace encoding\n const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));\n // (Modulus check.) Perform the computation ek ← ByteEncode12(ByteDecode12(eke)).\n // If ek = ̸ eke, the input is invalid. (See Section 4.2.1.)\n if (!equalBytes(ek, eke)) {\n cleanBytes(ek);\n throw new Error('ML-KEM.encapsulate: wrong publicKey modulus');\n }\n cleanBytes(ek);\n // derive randomness\n const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();\n const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n cleanBytes(kr.subarray(32));\n return {\n cipherText: cipherText as TRet<Uint8Array>,\n sharedSecret: kr.subarray(0, 32) as TRet<Uint8Array>,\n };\n },\n decapsulate: (cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n abytes(secretKey, secretCoder.bytesLen, 'secretKey'); // 768*k + 96\n abytes(cipherText, lengths.cipherText, 'cipherText'); // 32(du*k + dv)\n // test ← H(dk[384𝑘 ∶ 768𝑘 + 32])) .\n const k768 = secretCoder.bytesLen - 96;\n const start = k768 + 32;\n const test = HASH256(secretKey.subarray(k768 / 2, start));\n // If test ≠ dk[768𝑘 + 32 ∶ 768𝑘 + 64], then input checking has failed.\n if (!equalBytes(test, secretKey.subarray(start, start + 32)))\n throw new Error('invalid secretKey: hash check failed');\n const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);\n const msg = KPKE.decrypt(cipherText, sk);\n // derive randomness, Khat, rHat = G(mHat || h)\n const kr = HASH512.create().update(msg).update(publicKeyHash).digest();\n const Khat = kr.subarray(0, 32);\n // re-encrypt using the derived randomness\n const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n // if ciphertexts do not match, “implicitly reject”\n const isValid = equalBytes(cipherText, cipherText2);\n const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();\n cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);\n return (isValid ? Khat : Kbar) as TRet<Uint8Array>;\n },\n });\n}\n\n// FIPS 203's PRF_eta binding: current callers use only 32-byte keys, one-byte nonces,\n// and dkLen values {128, 192}; out-of-range nonce numbers still wrap modulo 256 here.\nfunction shakePRF(dkLen: number, key: TArg<Uint8Array>, nonce: number): TRet<Uint8Array> {\n return shake256\n .create({ dkLen })\n .update(key)\n .update(new Uint8Array([nonce]))\n .digest() as TRet<Uint8Array>;\n}\n\n// Fixed ML-KEM hash/XOF bindings. `KDF` here is the spec's fixed 32-byte `J` call,\n// and swapping any field changes the scheme rather than tuning an internal dependency.\nconst opts = /* @__PURE__ */ (() => ({\n HASH256: sha3_256,\n HASH512: sha3_512,\n KDF: shake256,\n XOF: XOF128,\n PRF: shakePRF,\n}))();\n// Parameter-set instantiation step for the spec's \"ML-KEM-x\" names; current correctness relies\n// on the internal PARAMS rows rather than local validation of arbitrary KEMParam objects.\nconst mk = (params: KEMParam) =>\n createKyber({\n ...opts,\n ...params,\n });\n\n/**\n * ML-KEM-512: Table 2 row `k=2, η1=3, η2=2, du=10, dv=4`; Table 3 sizes `800/1632/768/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem512: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[512]))();\n/**\n * ML-KEM-768: Table 2 row `k=3, η1=2, η2=2, du=10, dv=4`; Table 3 sizes `1184/2400/1088/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem768: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[768]))();\n/**\n * ML-KEM-1024: Table 2 row `k=4, η1=2, η2=2, du=11, dv=5`; Table 3 sizes `1568/3168/1568/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem1024: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[1024]))();\n\n// NOTE: for tests only, don't use. This keeps the exact internal ML-KEM math surfaces available\n// without re-implementing them in separate test code.\nexport const __tests: any = /* @__PURE__ */ (() =>\n Object.freeze({\n Compress_d: (x: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Compress_d: expected d in [1..11], got ${d}`);\n return compress(d).encode(x) & getMask(d);\n },\n Decompress_d: (y: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Decompress_d: expected d in [1..11], got ${d}`);\n return compress(d).decode(y);\n },\n ByteEncode_d: (F: TArg<Uint16Array>, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteEncode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).encode(F as TRet<Uint16Array>);\n },\n ByteDecode_d: (B: TArg<Uint8Array>, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteDecode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).decode(B);\n },\n NTT: (f: TArg<Uint16Array>) => crystals.NTT.encode(Uint16Array.from(f)),\n NTT_inv: (fHat: TArg<Uint16Array>) => crystals.NTT.decode(Uint16Array.from(fHat)),\n MultiplyNTTs: (fHat: TArg<Uint16Array>, gHat: TArg<Uint16Array>) =>\n MultiplyNTTs(Uint16Array.from(fHat), Uint16Array.from(gHat)),\n SamplePolyCBD: (B: TArg<Uint8Array>, eta: number) => {\n abytes(B, 64 * eta, 'B');\n return sampleCBDBytes(B, eta);\n },\n SampleNTT: (B: TArg<Uint8Array>) => {\n abytes(B, 34, 'B');\n const xof = XOF128(B.subarray(0, 32));\n try {\n return SampleNTT(xof.get(B[32], B[33]));\n } finally {\n xof.clean();\n }\n },\n }))();\n","/**\n * Post-Quantum Hybrid Cryptography\n *\n * The current implementation is flawed and likely redundant. We should offer\n * a small, generic API to compose hybrid schemes instead of reimplementing\n * protocol-specific logic (SSH, GPG, etc.) with ad hoc encodings.\n *\n * 1. Core Issues\n * - sign/verify: implemented as two separate operations with different keys.\n * - EC getSharedSecret: could be refactored into a proper KEM.\n * - Multiple calls: keys, signatures, and shared secrets could be\n * concatenated to reduce the number of API invocations.\n * - Reinvention: most libraries add strange domain separations and\n * encodings instead of simple byte concatenation.\n *\n * 2. API Goals\n * - Provide primitives to build hybrids generically.\n * - Avoid embedding SSH- or GPG-specific formats in the core API.\n *\n * 3. Edge Cases\n * • Variable-length signatures:\n * - DER-encoded (Weierstrass curves).\n * - Falcon (unpadded).\n * - Concatenation works only if length is fixed; otherwise a length\n * prefix is required (but that breaks compatibility).\n *\n * • getSharedSecret:\n * - Default: non-KEM (authenticated ECDH).\n * - KEM conversion: generate a random SK to remove implicit auth.\n *\n * 4. Common Pitfalls\n * - Seed expansion:\n * • Expanding a small seed into multiple keys reduces entropy.\n * • API should allow identity mapping (no expansion).\n *\n * - Skipping full point encoding:\n * • Some omit the compression byte (parity) for WebCrypto compatibility.\n * • Better: hash the raw secret; coordinate output is already non-uniform.\n * • Some curves (e.g., X448) produce secrets that must be re-hashed to match\n * symmetric-key lengths.\n *\n * - Combiner inconsistencies:\n * • Different domain separations and encodings across libraries.\n * • Should live at the application layer, since key lengths vary.\n *\n * 5. Protocol Examples\n * - SSH:\n * • Concatenate keys.\n * • Combiner: SHA-512.\n *\n * - GPG:\n * • Concatenate keys.\n * • Combiner:\n * SHA3-256(kemShare || ecdhShare || ciphertext || pubKey || algId || domSep || len(domSep))\n *\n * - TLS:\n * • Transcript-based derivation (HKDF).\n *\n * 6. Relevant Specs & Implementations\n * - IETF Hybrid KEM drafts:\n * • draft-irtf-cfrg-hybrid-kems\n * • draft-connolly-cfrg-xwing-kem\n * • draft-westerbaan-tls-xyber768d00\n *\n * - PQC Libraries:\n * • superdilithium (cyph/pqcrypto.js) – low adoption.\n * • hybrid-pqc (DogeProtocol, quantumcoinproject) – complex encodings.\n *\n * 7. Signatures\n * - Ed25519: fixed-size, easy to support.\n * - Variable-size: introduces custom format requirements; best left to\n * higher-level code.\n *\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { type EdDSA } from '@noble/curves/abstract/edwards.js';\nimport { type MontgomeryECDH } from '@noble/curves/abstract/montgomery.js';\nimport { type ECDSA } from '@noble/curves/abstract/weierstrass.js';\nimport { x25519 } from '@noble/curves/ed25519.js';\nimport { p256, p384 } from '@noble/curves/nist.js';\nimport {\n asciiToBytes,\n bytesToNumberBE,\n bytesToNumberLE,\n concatBytes,\n numberToBytesBE,\n} from '@noble/curves/utils.js';\nimport { expand, extract } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { sha3_256, shake256 } from '@noble/hashes/sha3.js';\nimport { abytes, ahash, anumber, type CHash, type CHashXOF } from '@noble/hashes/utils.js';\nimport { ml_kem1024, ml_kem768 } from './ml-kem.ts';\nimport {\n cleanBytes,\n copyBytes,\n randomBytes,\n splitCoder,\n validateSigOpts,\n validateVerOpts,\n type CryptoKeys,\n type KEM,\n type Signer,\n type TArg,\n type TRet,\n} from './utils.ts';\n\ntype CurveAll = ECDSA | EdDSA | MontgomeryECDH;\ntype CurveECDH = ECDSA | MontgomeryECDH;\ntype CurveSign = ECDSA | EdDSA;\n\n// Can re-use if decide to signatures support, on other hand getSecretKey is specific and ugly\nfunction ecKeygen(curve: CurveAll, allowZeroKey: boolean = false) {\n const lengths = curve.lengths;\n let keygen = curve.keygen;\n if (allowZeroKey) {\n // Only the ECDSA/Weierstrass branch uses raw scalar-byte secret keys here. Edwards seeds are\n // hashed/pruned and Montgomery keys are clamped byte strings, so forcing Point.Fn semantics on\n // those curves would change key construction instead of just relaxing scalar range handling.\n if (!('getSharedSecret' in curve && 'sign' in curve && 'verify' in curve))\n throw new Error('allowZeroKey requires a Weierstrass curve');\n // This legacy flag is really \"skip the +1 shift\" for vector matching, not \"accept scalar 0\".\n // It swaps seeded Weierstrass keygen from reduction into [1, ORDER) to direct reduction into\n // [0, ORDER), which preserves exact reduced bytes but still leaves scalar 0 invalid.\n // This is ugly, but we need to return exact results here.\n const wCurve = curve as ECDSA;\n const Fn = wCurve.Point.Fn;\n // Unlike noble-curves' seeded Weierstrass keygen, this path removes the post-reduction +1.\n // That is enough to match exact reduced-vector bytes, but an all-zero seed still reduces to\n // scalar 0 here and getPublicKey(secretKey) throws instead of \"allowing zero\".\n keygen = (seed: TArg<Uint8Array> = randomBytes(lengths.seed)) => {\n abytes(seed, lengths.seed!, 'seed');\n const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);\n // Reduce directly into [0, ORDER); scalar 0 still stays invalid.\n const secretKey = Fn.toBytes(Fn.create(seedScalar));\n return {\n secretKey: secretKey as TRet<Uint8Array>,\n publicKey: curve.getPublicKey(secretKey) as TRet<Uint8Array>,\n };\n };\n }\n return {\n lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed },\n keygen: (seed?: TArg<Uint8Array>) =>\n keygen(seed) as TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }>,\n getPublicKey: (secretKey: TArg<Uint8Array>) =>\n curve.getPublicKey(secretKey) as TRet<Uint8Array>,\n };\n}\n\n/**\n * Wraps an ECDH-capable curve as a KEM.\n * Shared secrets stay in the wrapped curve's raw ECDH byte format with no built-in KDF.\n * On SEC 1 / Weierstrass curves, that means the compressed shared-point body without the\n * 1-byte `0x02` / `0x03` prefix.\n * The X25519 path also leaves RFC 7748's optional all-zero shared-secret check to callers.\n * @param curve - Curve with `getSharedSecret`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns KEM wrapper over the curve.\n * @throws If the curve does not expose `getSharedSecret`. {@link Error}\n * @example\n * Wrap an ECDH-capable curve as a generic KEM.\n * ```ts\n * import { x25519 } from '@noble/curves/ed25519.js';\n * import { ecdhKem } from '@noble/post-quantum/hybrid.js';\n * const kem = ecdhKem(x25519);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function ecdhKem(curve: CurveECDH, allowZeroKey: boolean = false): TRet<KEM> {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.getSharedSecret) throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n encapsulate(\n publicKey: TArg<Uint8Array>,\n rand: TArg<Uint8Array> = randomBytes(curve.lengths.seed)\n ) {\n // Some curve.keygen(seed) paths reuse the provided seed buffer as secretKey; detach caller\n // randomness first so cleanBytes() only wipes wrapper-owned material.\n const seed = copyBytes(rand);\n let ek: Uint8Array | undefined = undefined;\n try {\n ek = this.keygen(seed).secretKey;\n const sharedSecret = this.decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek) as TRet<Uint8Array>;\n return { sharedSecret, cipherText };\n } finally {\n // Invalid peer public keys can make decapsulation throw; wipe both the detached seed and\n // derived ephemeral secret key even when encapsulation aborts before returning.\n cleanBytes(seed);\n if (ek) cleanBytes(ek);\n }\n },\n decapsulate(cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) {\n const res = curve.getSharedSecret(secretKey, cipherText);\n return (curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res) as TRet<Uint8Array>;\n },\n };\n}\n\n/**\n * Wraps a curve signer as a generic `Signer`.\n * Signatures stay in the wrapped curve's native byte encoding.\n * This wrapper does not normalize or document which per-curve signing options are meaningful.\n * @param curve - Curve with `sign` and `verify`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns Signer wrapper over the curve.\n * @throws If the curve does not expose `sign` and `verify`. {@link Error}\n * @example\n * Wrap a curve signer as a generic signer.\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { ecSigner } from '@noble/post-quantum/hybrid.js';\n * const signer = ecSigner(ed25519);\n * const sigLen = signer.lengths.signature;\n * ```\n */\nexport function ecSigner(curve: CurveSign, allowZeroKey: boolean = false): TRet<Signer> {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.sign || !curve.verify) throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, signature: curve.lengths.signature, signRand: 0 },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n sign: (message, secretKey, opts = {}) => {\n validateSigOpts(opts);\n // This generic wrapper intentionally keeps the Signer contract to message + key only.\n // Backend-specific knobs like ECDSA extraEntropy or Ed25519ctx context cannot be forwarded\n // uniformly through combineSigners(), so callers that need them must use the curve directly.\n if (opts.extraEntropy !== undefined)\n throw new Error(\n 'ecSigner does not support extraEntropy; use the underlying curve directly'\n );\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.sign(message, secretKey) as TRet<Uint8Array>;\n },\n /** Verify one wrapped curve signature.\n * Returns the wrapped curve's `verify()` result for well-formed inputs. Throws on unsupported\n * generic opts and lets wrapped-curve malformed-input errors escape unchanged.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.verify(signature, message, publicKey);\n },\n };\n}\n\nfunction splitLengths<K extends string, T extends { lengths: Partial<Record<K, number>> }>(\n lst: T[],\n name: K\n) {\n // Preserve caller order exactly; raw numeric fields still decode as splitCoder() subarray views.\n return splitCoder(\n name,\n ...lst.map((i) => {\n if (typeof i.lengths[name] !== 'number') throw new Error('wrong length: ' + name);\n return i.lengths[name];\n })\n );\n}\n\n/** Seed-expansion callback used by the hybrid combiners. */\nexport type ExpandSeed = (seed: TArg<Uint8Array>, len: number) => TRet<Uint8Array>;\ntype XOF = CHashXOF<any, { dkLen: number }>;\n\n// It is XOF for most cases, but can be more complex!\n/**\n * Adapts an XOF into an `ExpandSeed` callback.\n * The returned callback interprets its second argument as an output byte length passed as `dkLen`.\n * @param xof - Extendable-output hash function.\n * @returns Seed expander using `dkLen`.\n * @example\n * Adapt an XOF into a seed expander.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * const expandSeed = expandSeedXof(shake256);\n * const seed = expandSeed(new Uint8Array([1]), 4);\n * ```\n */\nexport function expandSeedXof(xof: TArg<XOF>): TRet<ExpandSeed> {\n // Forward the caller seed directly: XOFs are expected to treat inputs as read-only, and this\n // adapter only translates the requested byte length into the hash API's `dkLen` option.\n return ((seed: TArg<Uint8Array>, seedLen: number): TRet<Uint8Array> =>\n (xof as XOF)(seed, { dkLen: seedLen }) as TRet<Uint8Array>) as TRet<ExpandSeed>;\n}\n\n/** Combines public keys, ciphertexts, and shared secrets into one shared secret. */\nexport type Combiner = (\n publicKeys: TArg<Uint8Array[]>,\n cipherTexts: TArg<Uint8Array[]>,\n sharedSecrets: TArg<Uint8Array[]>\n) => TRet<Uint8Array>;\n\nfunction combineKeys(\n realSeedLen: number | undefined, // how much bytes expandSeed expects\n expandSeed_: TArg<ExpandSeed>,\n ...ck_: TArg<CryptoKeys[]>\n) {\n const expandSeed = expandSeed_ as ExpandSeed;\n const ck = ck_ as CryptoKeys[];\n const seedCoder = splitLengths(ck, 'seed');\n const pkCoder = splitLengths(ck, 'publicKey');\n // Allows to use identity functions for combiner/expandSeed\n if (realSeedLen === undefined) realSeedLen = seedCoder.bytesLen;\n anumber(realSeedLen);\n function expandDecapsulationKey(seed: TArg<Uint8Array>): TRet<{\n secretKey: Uint8Array[];\n publicKey: Uint8Array[];\n }> {\n abytes(seed, realSeedLen!);\n const expandedRaw = expandSeed(seed, seedCoder.bytesLen);\n // Identity/subarray expanders can hand back caller-owned seed storage. Detach those outputs so\n // later cleanup can wipe the expanded schedule without mutating the caller's root seed bytes.\n const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes(expandedRaw) : expandedRaw;\n const expanded: Uint8Array[] = [];\n const keySecret: Uint8Array[] = [];\n const secretKey: Uint8Array[] = [];\n const publicKey: Uint8Array[] = [];\n let ok = false;\n try {\n // seedCoder.decode() returns zero-copy slices into expandedSeed and can throw before child\n // keygen() runs, so keep the raw expanded buffer separate and copy each child seed before any\n // later cleanup wipes the shared backing bytes.\n for (const part of seedCoder.decode(expandedSeed)) expanded.push(copyBytes(part));\n for (let i = 0; i < ck.length; i++) {\n const keys = ck[i].keygen(expanded[i]);\n keySecret.push(keys.secretKey);\n secretKey.push(copyBytes(keys.secretKey));\n publicKey.push(keys.publicKey);\n }\n ok = true;\n return { secretKey, publicKey } as TRet<{\n secretKey: Uint8Array[];\n publicKey: Uint8Array[];\n }>;\n } finally {\n // Child keygen() can throw after deriving only a prefix of the composite key schedule. Keep\n // the exported copies on success, but wipe all temporary and partially built secret material\n // on either path so failures do not strand derived child seeds in memory.\n cleanBytes(expandedSeed, expanded, keySecret);\n if (!ok) cleanBytes(secretKey);\n }\n }\n return {\n info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },\n getPublicKey(secretKey: TArg<Uint8Array>) {\n // Composite secret keys are root seeds, so public-key derivation reruns key expansion from\n // that seed instead of decoding a packed child-secret-key structure.\n return this.keygen(secretKey).publicKey as TRet<Uint8Array>;\n },\n keygen(seed: TArg<Uint8Array> = randomBytes(realSeedLen)) {\n const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);\n try {\n const publicKey = pkCoder.encode(pk) as TRet<Uint8Array>;\n return { secretKey: seed as TRet<Uint8Array>, publicKey };\n } finally {\n cleanBytes(pk);\n // The exported secretKey is the caller/root seed itself; child secret keys are internal\n // expansion outputs that are cleaned whether encoding succeeds or throws.\n cleanBytes(secretKey);\n }\n },\n expandDecapsulationKey,\n realSeedLen,\n };\n}\n\n// This generic function that combines multiple KEMs into single one\n/**\n * Combines multiple KEMs into one composite KEM.\n * @param realSeedLen - Input seed length expected by `expandSeed`.\n * @param realMsgLen - Shared-secret length returned by `combiner`.\n * @param expandSeed - Seed expander used to derive per-KEM seeds.\n * @param combiner - Combines the per-KEM outputs into one shared secret.\n * @param kems - KEM implementations to combine.\n * @returns Composite KEM.\n * @example\n * Combine multiple KEMs into one composite KEM.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineKEMS, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const hybrid = combineKEMS(\n * 32,\n * 32,\n * expandSeedXof(shake256),\n * (_pk, _ct, sharedSecrets) => sharedSecrets[0],\n * ml_kem768,\n * ml_kem768\n * );\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineKEMS(\n realSeedLen: number | undefined, // how much bytes expandSeed expects\n realMsgLen: number | undefined, // how much bytes combiner returns\n expandSeed: TArg<ExpandSeed>,\n combiner: TArg<Combiner>,\n ...kems: TArg<KEM[]>\n): TRet<KEM> {\n const rawCombiner = combiner as Combiner;\n const rawKems = kems as KEM[];\n const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);\n const ctCoder = splitLengths(rawKems, 'cipherText');\n const pkCoder = splitLengths(rawKems, 'publicKey');\n const msgCoder = splitLengths(rawKems, 'msg');\n if (realMsgLen === undefined) realMsgLen = msgCoder.bytesLen;\n anumber(realMsgLen);\n const lengths = Object.freeze({\n ...keys.info.lengths,\n msg: realMsgLen,\n msgRand: msgCoder.bytesLen,\n cipherText: ctCoder.bytesLen,\n });\n return Object.freeze({\n lengths,\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n encapsulate(\n pk: TArg<Uint8Array>,\n randomness: TArg<Uint8Array> = randomBytes(msgCoder.bytesLen)\n ) {\n const pks = pkCoder.decode(pk);\n const rand = msgCoder.decode(randomness);\n const sharedSecret: Uint8Array[] = [];\n const cipherText: Uint8Array[] = [];\n try {\n for (let i = 0; i < rawKems.length; i++) {\n const enc = rawKems[i].encapsulate(pks[i], rand[i]);\n sharedSecret.push(enc.sharedSecret);\n cipherText.push(enc.cipherText);\n }\n return {\n // Detach the combiner result before cleanup: a caller-provided combiner may alias one of\n // the child sharedSecret buffers, and those child buffers are zeroized immediately below.\n sharedSecret: copyBytes(rawCombiner(pks, cipherText, sharedSecret)),\n cipherText: ctCoder.encode(cipherText) as TRet<Uint8Array>,\n };\n } finally {\n // Child encapsulation or combiner failures can happen after some components already\n // returned secret material; zeroize whatever was produced before propagating the error.\n cleanBytes(sharedSecret, cipherText);\n }\n },\n decapsulate(ct: TArg<Uint8Array>, seed: TArg<Uint8Array>) {\n const cts = ctCoder.decode(ct);\n const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);\n const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));\n try {\n // Detach the decapsulation result before cleanup: the combiner may hand back one of the\n // child shared-secret buffers, and those temporary buffers are zeroized below.\n return copyBytes(rawCombiner(publicKey, cts, sharedSecret));\n } finally {\n // Decapsulation only needs the expanded child secret keys and child shared secrets for this\n // call; keep the caller/root seed intact, but wipe all derived material even on errors.\n cleanBytes(secretKey, sharedSecret);\n }\n },\n });\n}\n// There is no specs for this, but can be useful\n// realSeedLen: how much bytes expandSeed expects.\n/**\n * Combines multiple signers into one composite signer.\n * @param realSeedLen - Input seed length expected by `expandSeed`.\n * @param expandSeed - Seed expander used to derive per-signer seeds.\n * @param signers - Signers to combine.\n * @returns Composite signer.\n * @example\n * Combine multiple signers into one composite signer.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineSigners, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js';\n * const hybrid = combineSigners(32, expandSeedXof(shake256), ml_dsa44, ml_dsa44);\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineSigners(\n realSeedLen: number | undefined,\n expandSeed: TArg<ExpandSeed>,\n ...signers: TArg<Signer[]>\n): TRet<Signer> {\n const rawSigners = signers as Signer[];\n const keys = combineKeys(realSeedLen, expandSeed, ...rawSigners);\n const sigCoder = splitLengths(rawSigners, 'signature');\n const pkCoder = splitLengths(rawSigners, 'publicKey');\n return {\n lengths: { ...keys.info.lengths, signature: sigCoder.bytesLen, signRand: 0 },\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n sign(message, seed, opts = {}) {\n validateSigOpts(opts);\n // This generic wrapper intentionally keeps the composite signer contract to message + root\n // seed only. Per-signer opts like context or extraEntropy cannot be preserved uniformly\n // across mixed backends, so callers that need them must use the underlying signer directly.\n if (opts.extraEntropy !== undefined)\n throw new Error(\n 'combineSigners does not support extraEntropy; use the underlying signer directly'\n );\n if (opts.context !== undefined)\n throw new Error(\n 'combineSigners does not support context; use the underlying signer directly'\n );\n const { secretKey } = keys.expandDecapsulationKey(seed);\n try {\n const sigs = rawSigners.map((i, j) => i.sign(message, secretKey[j]));\n return sigCoder.encode(sigs) as TRet<Uint8Array>;\n } finally {\n // Composite secret keys are root seeds; the per-signer child secret keys are temporary\n // expansion outputs and must not stay live after the combined signature is produced.\n cleanBytes(secretKey);\n }\n },\n /** Verify one combined signature.\n * Returns `false` when the aggregate signature/publicKey decode succeeds but any child verify\n * check fails. Throws on unsupported generic opts or malformed aggregate encodings.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error(\n 'combineSigners does not support context; use the underlying signer directly'\n );\n const pks = pkCoder.decode(publicKey);\n const sigs = sigCoder.decode(signature);\n for (let i = 0; i < rawSigners.length; i++) {\n if (!rawSigners[i].verify(sigs[i], message, pks[i])) return false;\n }\n return true;\n },\n };\n}\n\n/**\n * Builds a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * The combined shared-secret length follows `kdf.outputLen`; the built-in presets use 32-byte\n * SHA3-256 output, while custom `kdf` choices inherit their own digest size.\n * Its combiner hashes `ss0 || ss1 || ct1 || pk1 || label`, not the full\n * `(c1, c2, ek1, ek2)` example input shape from SP 800-227 equation (15).\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param kdf - Hash used for the final combiner.\n * @returns Hybrid KEM.\n * @example\n * Build a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * ```ts\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha3_256, shake256 } from '@noble/hashes/sha3.js';\n * import { QSF, ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const kem = QSF('example', ml_kem768, ecdhKem(p256, true), shake256, sha3_256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function QSF(\n label: string,\n pqc: TArg<KEM>,\n curveKEM: TArg<KEM>,\n xof: TArg<XOF>,\n kdf: CHash\n): TRet<KEM> {\n ahash(xof);\n ahash(kdf);\n return combineKEMS(\n 32,\n kdf.outputLen,\n expandSeedXof(xof),\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n kdf(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))),\n pqc,\n curveKEM\n );\n}\n\n/** QSF preset combining ML-KEM-768 with P-256. */\nexport const QSF_ml_kem768_p256: TRet<KEM> = /* @__PURE__ */ (() =>\n QSF(\n 'QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)',\n ml_kem768,\n ecdhKem(p256, true),\n shake256,\n sha3_256\n ))();\n/** QSF preset combining ML-KEM-1024 with P-384. */\nexport const QSF_ml_kem1024_p384: TRet<KEM> = /* @__PURE__ */ (() =>\n QSF(\n 'QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)',\n ml_kem1024,\n ecdhKem(p384, true),\n shake256,\n sha3_256\n ))();\n\n/**\n * Builds the \"KitchenSink\" hybrid KEM combiner.\n * The current builder always derives a fixed 32-byte output,\n * regardless of the hash's native output size.\n * Its HKDF extract step uses implicit zero salt with IKM\n * `hybrid_prk || ss0 || ss1 || ct0 || pk0 || ct1 || pk1 || label`.\n * Its HKDF expand step fixes `info` to `len || 'shared_secret' || ''`.\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param hash - Hash used for HKDF extraction and expansion.\n * @returns Hybrid KEM.\n * @example\n * Build the \"KitchenSink\" hybrid KEM combiner.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { createKitchenSink, ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const kem = createKitchenSink('example', ml_kem768, ecdhKem(x25519), shake256, sha256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function createKitchenSink(\n label: string,\n pqc: TArg<KEM>,\n curveKEM: TArg<KEM>,\n xof: TArg<XOF>,\n hash: CHash\n): TRet<KEM> {\n ahash(xof);\n ahash(hash);\n return combineKEMS(\n 32,\n 32,\n expandSeedXof(xof),\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) => {\n const preimage = concatBytes(ss[0], ss[1], ct[0], pk[0], ct[1], pk[1], asciiToBytes(label));\n const len = 32;\n const ikm = concatBytes(asciiToBytes('hybrid_prk'), preimage);\n const prk = extract(hash, ikm);\n const info = concatBytes(\n numberToBytesBE(len, 2),\n asciiToBytes('shared_secret'),\n asciiToBytes('')\n );\n const res = expand(hash, prk, info, len);\n cleanBytes(prk, info, ikm, preimage);\n return res;\n },\n pqc,\n curveKEM\n );\n}\n\n// Internal alias only: this stays exactly `ecdhKem(x25519)`\n// and inherits that wrapper's mutation/oracle behavior.\nconst x25519kem = /* @__PURE__ */ ecdhKem(x25519);\n/** KitchenSink preset combining ML-KEM-768 with X25519.\n * Caller randomness splits into 32 ML-KEM coins plus a 32-byte X25519 ephemeral-secret seed.\n */\nexport const KitchenSink_ml_kem768_x25519: TRet<KEM> = /* @__PURE__ */ (() =>\n createKitchenSink(\n 'KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)',\n ml_kem768,\n x25519kem,\n shake256,\n sha256\n ))();\n\n// Always X25519 and ML-KEM - 768, no point to export\n/** X25519 + ML-KEM-768 hybrid preset.\n * Uses the hard-coded domain-separation label `\\\\.//^\\\\` and hashes only `ct1 || pk1`\n * from the X25519 side in addition to the two component shared secrets.\n */\nexport const ml_kem768_x25519: TRet<KEM> = /* @__PURE__ */ (() =>\n combineKEMS(\n 32,\n 32,\n expandSeedXof(shake256),\n // Awesome label, so much escaping hell in a single line.\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes('\\\\.//^\\\\'))),\n ml_kem768,\n x25519kem\n ))();\n\n/**\n * Internal SEC 1-style KEM wrapper for NIST curves.\n * `nseed` is only the rejection-sampling byte budget for deriving one nonzero scalar:\n * current presets use `128` bytes for P-256 and `48` bytes for P-384.\n * `decapsulate()` returns the uncompressed shared point body `x || y` without the `0x04`\n * prefix, not the SEC 1 `x_P`-only primitive output, because current hybrid combiners hash\n * both coordinates.\n */\nfunction nistCurveKem(curve: ECDSA, scalarLen: number, elemLen: number, nseed: number): TRet<KEM> {\n const Fn = curve.Point.Fn;\n if (!Fn) throw new Error('no Point.Fn');\n // Scan scalar-sized windows until one decodes to a nonzero scalar in `[1, n-1]`; if every\n // window is zero or out of range, fail instead of silently reducing modulo `n`.\n function rejectionSampling(seed: TArg<Uint8Array>): TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }> {\n let sk: bigint;\n for (let start = 0, end = scalarLen; ; start = end, end += scalarLen) {\n if (end > seed.length) throw new Error('rejection sampling failed');\n sk = Fn.fromBytes(seed.subarray(start, end), true);\n if (Fn.isValidNot0(sk)) break;\n }\n const secretKey = Fn.toBytes(Fn.create(sk));\n const publicKey = curve.getPublicKey(secretKey, false);\n return { secretKey, publicKey } as TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }>;\n }\n\n return {\n lengths: {\n secretKey: scalarLen,\n publicKey: elemLen,\n seed: nseed,\n msg: nseed,\n cipherText: elemLen,\n },\n keygen(seed: TArg<Uint8Array> = randomBytes(nseed)) {\n abytes(seed, nseed, 'seed');\n return rejectionSampling(seed);\n },\n getPublicKey(secretKey: TArg<Uint8Array>) {\n return curve.getPublicKey(secretKey, false) as TRet<Uint8Array>;\n },\n encapsulate(publicKey: TArg<Uint8Array>, rand: TArg<Uint8Array> = randomBytes(nseed)) {\n abytes(rand, nseed, 'rand');\n let ek: Uint8Array | undefined = undefined;\n try {\n ek = rejectionSampling(rand).secretKey;\n const sharedSecret = this.decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek, false) as TRet<Uint8Array>;\n return { sharedSecret, cipherText };\n } finally {\n // Rejection-sampled NIST-curve ephemeral secret keys are temporary encapsulation state and\n // must be wiped even if peer-key validation or shared-secret derivation throws.\n if (ek) cleanBytes(ek);\n }\n },\n decapsulate(cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) {\n const full = curve.getSharedSecret(secretKey, cipherText);\n return full.subarray(1) as TRet<Uint8Array>;\n },\n };\n}\n\n/**\n * Internal ML-KEM + NIST-curve combiner.\n * `nseed` controls only the curve-side rejection-sampling budget; it is expanded from the\n * 32-byte root seed and is not itself part of the exported secret-key length.\n * The domain-separation `label` is used only in the final `sha3_256` combiner, not in\n * `shake256(seed, { dkLen: 64 + nseed })`,\n * and the combiner hashes `ss0 || ss1 || ct1 || pk1 || label`.\n */\nfunction concreteHybridKem(\n label: string,\n mlkem: TArg<KEM>,\n curve: ECDSA,\n nseed: number\n): TRet<KEM> {\n const { secretKey: scalarLen, publicKeyUncompressed: elemLen } = curve.lengths;\n if (!scalarLen || !elemLen) throw new Error('wrong curve');\n const curveKem = nistCurveKem(curve, scalarLen, elemLen, nseed);\n const mlkemSeedLen = 64;\n const totalSeedLen = mlkemSeedLen + nseed;\n\n return combineKEMS(\n 32,\n 32,\n (seed: TArg<Uint8Array>): TRet<Uint8Array> => {\n abytes(seed, 32);\n const expanded = shake256(seed, { dkLen: totalSeedLen });\n const mlkemSeed = expanded.subarray(0, mlkemSeedLen);\n const curveSeed = expanded.subarray(mlkemSeedLen, totalSeedLen);\n return concatBytes(mlkemSeed, curveSeed) as TRet<Uint8Array>;\n },\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))),\n mlkem,\n curveKem\n );\n}\n\n/** P-256 + ML-KEM-768 hybrid preset. */\nexport const ml_kem768_p256: TRet<KEM> = /* @__PURE__ */ (() =>\n concreteHybridKem('MLKEM768-P256', ml_kem768, p256, 128))();\n\n/** P-384 + ML-KEM-1024 hybrid preset. */\nexport const ml_kem1024_p384: TRet<KEM> = /* @__PURE__ */ (() =>\n concreteHybridKem('MLKEM1024-P384', ml_kem1024, p384, 48))();\n\n// Legacy aliases\n/** Legacy alias for `ml_kem768_x25519`. */\nexport const XWing: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_x25519)();\n/** Legacy alias for `ml_kem768_x25519`. */\nexport const MLKEM768X25519: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_x25519)();\n/** Legacy alias for `ml_kem768_p256`. */\nexport const MLKEM768P256: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_p256)();\n/** Legacy alias for `ml_kem1024_p384`. */\nexport const MLKEM1024P384: TRet<KEM> = /* @__PURE__ */ (() => ml_kem1024_p384)();\n/** Legacy alias for `QSF_ml_kem768_p256`. */\nexport const QSFMLKEM768P256: TRet<KEM> = /* @__PURE__ */ (() => QSF_ml_kem768_p256)();\n/** Legacy alias for `QSF_ml_kem1024_p384`. */\nexport const QSFMLKEM1024P384: TRet<KEM> = /* @__PURE__ */ (() => QSF_ml_kem1024_p384)();\n/** Legacy alias for `KitchenSink_ml_kem768_x25519`. */\nexport const KitchenSinkMLKEM768X25519: TRet<KEM> = /* @__PURE__ */ (() =>\n KitchenSink_ml_kem768_x25519)();\n","import { chacha20poly1305 } from '@noble/ciphers/chacha.js';\n\nimport { AeadVerificationError } from './errors';\n\nexport interface ChaCha20Poly1305EncryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly plaintext: Uint8Array;\n}\n\nexport interface ChaCha20Poly1305DecryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly ciphertext: Uint8Array;\n}\n\nexport function chacha20Poly1305Encrypt(opts: ChaCha20Poly1305EncryptOpts): Uint8Array {\n return chacha20poly1305(opts.key, opts.nonce, opts.aad).encrypt(opts.plaintext);\n}\n\nexport function chacha20Poly1305Decrypt(opts: ChaCha20Poly1305DecryptOpts): Uint8Array {\n try {\n return chacha20poly1305(opts.key, opts.nonce, opts.aad).decrypt(opts.ciphertext);\n } catch (cause) {\n throw new AeadVerificationError('chacha20-poly1305 decrypt failed', { cause });\n }\n}\n","import { hkdf } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nexport interface HkdfSha256Opts {\n readonly ikm: Uint8Array;\n readonly salt: Uint8Array;\n readonly info: Uint8Array;\n readonly length: number;\n}\n\nexport function hkdfSha256(opts: HkdfSha256Opts): Uint8Array {\n return hkdf(sha256, opts.ikm, opts.salt, opts.info, opts.length);\n}\n","import { XWing } from '@noble/post-quantum/hybrid.js';\n\n// X-Wing (ML-KEM-768 + X25519) hybrid KEM per draft-connolly-cfrg-xwing-kem-06.\n// `XWing` is @noble/post-quantum's alias for `ml_kem768_x25519`. We expose it\n// through opts-object wrappers that pin the wire lengths and map noble's field\n// names onto the project's vocabulary.\n//\n// Unlike the bare X25519 KEM, there is no contributory-behaviour rejection to\n// translate: X-Wing combines the ML-KEM and X25519 shared secrets through a\n// SHA3-256 combiner that also binds the X25519 ephemeral and recipient public\n// keys, and ML-KEM's implicit rejection already yields a constant-work\n// pseudorandom secret on a malformed ciphertext. Decapsulation therefore never\n// throws on attacker-supplied wire data — a wrong shared secret is the correct,\n// indistinguishable failure mode, and callers MUST treat it as a non-match\n// rather than expecting an exception.\n\nexport const MLKEM768X25519_PUBLIC_KEY_LENGTH = 1216 as const;\nexport const MLKEM768X25519_ENC_LENGTH = 1120 as const;\nexport const MLKEM768X25519_SHARED_SECRET_LENGTH = 32 as const;\nexport const MLKEM768X25519_SEED_LENGTH = 32 as const;\nexport const MLKEM768X25519_ESEED_LENGTH = 64 as const;\n\nexport interface Mlkem768X25519KeyPair {\n // The 32-byte root seed IS the secret key in draft-06: the ML-KEM coins and\n // the X25519 scalar are re-expanded from it via SHAKE-256 at decapsulation.\n readonly secretSeed: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nexport interface Mlkem768X25519EncapsulateOpts {\n readonly publicKey: Uint8Array;\n // Optional 64-byte encapsulation randomness (msgRand). When supplied the\n // ciphertext and shared secret are fully deterministic; a 32-byte value is\n // rejected by noble, so we pin the length here too.\n readonly eseed?: Uint8Array;\n}\n\nexport interface Mlkem768X25519Encapsulation {\n readonly enc: Uint8Array;\n readonly ss: Uint8Array;\n}\n\nexport interface Mlkem768X25519DecapsulateOpts {\n readonly secretSeed: Uint8Array;\n readonly enc: Uint8Array;\n}\n\nexport function mlkem768x25519Keygen(seed: Uint8Array): Mlkem768X25519KeyPair {\n if (seed.length !== MLKEM768X25519_SEED_LENGTH) {\n throw new Error(\n `mlkem768x25519 seed must be ${MLKEM768X25519_SEED_LENGTH} bytes, got ${seed.length}`,\n );\n }\n const { secretKey, publicKey } = XWing.keygen(seed);\n return { secretSeed: secretKey, publicKey };\n}\n\nexport function mlkem768x25519Encapsulate(\n opts: Mlkem768X25519EncapsulateOpts,\n): Mlkem768X25519Encapsulation {\n if (opts.publicKey.length !== MLKEM768X25519_PUBLIC_KEY_LENGTH) {\n throw new Error(\n `mlkem768x25519 public key must be ${MLKEM768X25519_PUBLIC_KEY_LENGTH} bytes, got ${opts.publicKey.length}`,\n );\n }\n if (opts.eseed !== undefined && opts.eseed.length !== MLKEM768X25519_ESEED_LENGTH) {\n throw new Error(\n `mlkem768x25519 eseed must be ${MLKEM768X25519_ESEED_LENGTH} bytes, got ${opts.eseed.length}`,\n );\n }\n const { cipherText, sharedSecret } = XWing.encapsulate(opts.publicKey, opts.eseed);\n return { enc: cipherText, ss: sharedSecret };\n}\n\nexport function mlkem768x25519Decapsulate(opts: Mlkem768X25519DecapsulateOpts): Uint8Array {\n // Pre-check both lengths before calling noble: decapsulation must perform a\n // constant amount of work for any caller-supplied ciphertext (implicit\n // rejection), which requires the inputs to be the exact expected sizes.\n if (opts.secretSeed.length !== MLKEM768X25519_SEED_LENGTH) {\n throw new Error(\n `mlkem768x25519 secret seed must be ${MLKEM768X25519_SEED_LENGTH} bytes, got ${opts.secretSeed.length}`,\n );\n }\n if (opts.enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new Error(\n `mlkem768x25519 enc must be ${MLKEM768X25519_ENC_LENGTH} bytes, got ${opts.enc.length}`,\n );\n }\n // noble's signature is decapsulate(cipherText, secretKey) — ciphertext first.\n return XWing.decapsulate(opts.enc, opts.secretSeed);\n}\n","import { x25519 } from '@noble/curves/ed25519.js';\n\n// RFC 7748 §6.1 contributory-behaviour rejection: a small-order (low-order)\n// Montgomery `u` coordinate makes the X25519 shared secret all-zero, which\n// @noble/curves refuses with `Error: invalid private or public key received`.\n// We rethrow that as a *typed* error so callers can distinguish a structurally\n// valid-but-malicious peer public key (a property of attacker-supplied wire\n// data — trial-decrypt MUST treat the slot as a non-match, not crash) from\n// genuine caller misuse such as a wrong-length key (which @noble raises as a\n// RangeError and which we deliberately let propagate untouched).\nexport class X25519LowOrderPointError extends Error {\n readonly code = 'X25519_LOW_ORDER_POINT' as const;\n constructor(options?: { cause?: unknown }) {\n super('x25519 ECDH rejected: peer public key is a small-order point', options);\n this.name = 'X25519LowOrderPointError';\n }\n}\n\n// @noble/curves v2 signals a small-order/all-zero shared secret with this exact\n// message. Matching on it (rather than the broad Error class) keeps unrelated\n// failures — e.g. a future internal assertion — surfacing as themselves.\nconst NOBLE_LOW_ORDER_MESSAGE = 'invalid private or public key received';\n\nexport interface X25519KeyPair {\n readonly secretKey: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nexport interface X25519PublicKeyOpts {\n readonly secretKey: Uint8Array;\n}\n\nexport interface X25519EcdhOpts {\n readonly secretKey: Uint8Array;\n readonly theirPublicKey: Uint8Array;\n}\n\nexport function x25519Keygen(): X25519KeyPair {\n return x25519.keygen();\n}\n\nexport function x25519PublicKey(opts: X25519PublicKeyOpts): Uint8Array {\n return x25519.getPublicKey(opts.secretKey);\n}\n\nexport function x25519Ecdh(opts: X25519EcdhOpts): Uint8Array {\n try {\n return x25519.getSharedSecret(opts.secretKey, opts.theirPublicKey);\n } catch (e) {\n // Translate ONLY the contributory-check rejection into our typed error.\n // A wrong-length key throws a RangeError from @noble's length assertion;\n // that is caller misuse, not malicious wire data, so it must propagate.\n if (e instanceof Error && e.message === NOBLE_LOW_ORDER_MESSAGE) {\n throw new X25519LowOrderPointError({ cause: e });\n }\n throw e;\n }\n}\n","// Sealed-PoE error taxonomy (wire-shape + partitioning-oracle pre-checks).\n\nexport type EciesSealedPoeErrorCode =\n | 'ENC_SLOTS_EMPTY'\n | 'ENC_SLOTS_REQUIRED'\n | 'ENC_SLOTS_MAC_REQUIRED'\n | 'ENC_SLOTS_MAC_INVALID_LENGTH'\n | 'KEM_EPK_LENGTH_MISMATCH'\n | 'KEM_CT_LENGTH_MISMATCH'\n | 'INVALID_CEK_LENGTH'\n | 'NONCE_LENGTH_MISMATCH'\n | 'INVALID_EPHEMERAL_SECRET_LENGTH'\n | 'EPHEMERAL_SECRETS_COUNT_MISMATCH'\n | 'UNSUPPORTED_ENC_VERSION'\n | 'UNSUPPORTED_AEAD_ALG'\n | 'UNSUPPORTED_KEM_ALG'\n | 'INVALID_ENVELOPE_SHAPE'\n | 'INVALID_RECIPIENT_KEY'\n | 'WRAP_LENGTH_MISMATCH';\n\nexport class EciesSealedPoeError extends Error {\n readonly code: EciesSealedPoeErrorCode;\n\n constructor(code: EciesSealedPoeErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'EciesSealedPoeError';\n this.code = code;\n }\n}\n","// Single source of truth for two seams that wrap, unwrap, and the wire encoder\n// MUST agree on byte-for-byte:\n//\n// 1. How the 1120-byte X-Wing `enc` is split into the ≤ 64-byte byte-string\n// chunks the Cardano ledger requires (`kem_ct`), and the inverse join.\n// 2. The canonical-CBOR serialization of the slot array that feeds slots_mac.\n//\n// Keeping both here means the producer (wrap) and the verifier (unwrap), as well\n// as the downstream record encoder, cannot diverge on the bytes the MAC commits\n// to — the single highest correctness risk for the hybrid branch, since a\n// divergence would leave the ML-KEM ciphertext unauthenticated.\n\nimport { encodeCanonicalCbor, type CanonicalCborValue } from '../cbor/canonical';\n\nimport type { Mlkem768X25519Slot, X25519Slot } from './wrap';\n\n// The envelope-level KEM discriminator.\nexport type SealedKem = 'x25519' | 'mlkem768x25519';\n\n// Cardano ledger CDDL caps every `transaction_metadatum` byte string at 64\n// bytes, so any value larger than 64 bytes is carried as an array of ≤ 64-byte\n// chunks (the `bytes-chunk-array` wire form). This is the identical split rule\n// the record encoder applies to chunked COSE bytes.\nconst CHUNK_MAX_BYTES = 64;\n\n// Split a logical byte string into ≤ 64-byte chunks. Used for the X-Wing\n// `enc` → `kem_ct` wire form. Subarrays are views over the input, never copies.\nexport function chunkKemCt(value: Uint8Array): Uint8Array[] {\n if (value.length === 0) {\n throw new Error('chunkKemCt: refusing to chunk an empty byte string');\n }\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < value.length; i += CHUNK_MAX_BYTES) {\n chunks.push(value.subarray(i, Math.min(i + CHUNK_MAX_BYTES, value.length)));\n }\n return chunks;\n}\n\n// Inverse of chunkKemCt: concatenate the chunked `kem_ct` back into the flat\n// X-Wing `enc`. Performs NO length validation — the caller (unwrap) gates the\n// reassembled length against MLKEM768X25519_ENC_LENGTH before any decapsulation.\nexport function joinKemCt(chunks: ReadonlyArray<Uint8Array>): Uint8Array {\n let total = 0;\n for (const c of chunks) total += c.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const c of chunks) {\n out.set(c, offset);\n offset += c.length;\n }\n return out;\n}\n\n// KEM-driven slot serialization for the slots_mac input.\n//\n// • x25519: each slot → { epk: bstr, wrap: bstr }\n// • mlkem768x25519: each slot → { kem_ct: [ bstr, ... ], wrap: bstr }\n//\n// The hybrid form uses the SAME chunked-array shape as the wire encoder, so the\n// MAC commits to the ciphertext exactly as it appears on-chain. Returns the\n// canonical-CBOR bytes ready for HMAC.\nexport function slotsToMacCbor(\n slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n kem: SealedKem,\n): Uint8Array {\n let value: CanonicalCborValue;\n if (kem === 'x25519') {\n value = (slots as ReadonlyArray<X25519Slot>).map((s) => ({ epk: s.epk, wrap: s.wrap }));\n } else {\n value = (slots as ReadonlyArray<Mlkem768X25519Slot>).map((s) => ({\n // Canonicalize the chunk boundaries before the MAC commits to them:\n // reassemble the logical ciphertext and re-split into canonical ≤ 64-byte\n // chunks. The on-wire `kem_ct` array is a transport detail (the Cardano\n // ledger's 64-byte metadatum cap), and a hostile or non-canonical chunking\n // ([1, 63, …] instead of [64, …]) reassembles to the SAME bytes — so the\n // MAC must be invariant to it. Committing to the verbatim wire chunks would\n // let an attacker re-chunk an honest envelope and break the slots_mac match\n // for an honest recipient. Honest (already-64B-chunked) records are\n // unchanged; a real byte flip still changes the reassembled bytes and is\n // still rejected.\n kem_ct: chunkKemCt(joinKemCt(s.kem_ct)),\n wrap: s.wrap,\n }));\n }\n return encodeCanonicalCbor(value);\n}\n","// Multi-recipient sealed-PoE wrap (age-style ECIES + AEAD-bound slots).\n// Wire-field names are fixed by the standard: scheme, aead, kem, nonce, slots, slots_mac.\n//\n// Two KEM branches share one envelope shape, discriminated on the envelope-level\n// `kem` field:\n//\n// • kem: 'x25519' — classical age-style ECIES. Per-slot epk(32) + wrap(48).\n// • kem: 'mlkem768x25519' — X-Wing hybrid (ML-KEM-768 + X25519). Per-slot the\n// 1120-byte X-Wing enc carried as a chunked byte-string\n// array (`kem_ct`) + wrap(48). No per-slot epk.\n//\n// The slot type is a discriminated union so every consumer is forced — at compile\n// time — to branch on the KEM before touching kem-specific fields.\n\nimport { randomBytes } from '@noble/ciphers/utils.js';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { chacha20Poly1305Encrypt } from '../aead/chacha20-poly1305';\nimport { xchacha20Poly1305Encrypt } from '../aead/xchacha20-poly1305';\nimport { hkdfSha256 } from '../kdf/hkdf';\nimport {\n mlkem768x25519Encapsulate,\n MLKEM768X25519_ENC_LENGTH,\n MLKEM768X25519_ESEED_LENGTH,\n MLKEM768X25519_PUBLIC_KEY_LENGTH,\n} from '../kem/mlkem768x25519';\nimport { x25519Ecdh, x25519PublicKey } from '../kem/x25519';\n\nimport { EciesSealedPoeError } from './errors';\nimport { chunkKemCt, slotsToMacCbor, type SealedKem } from './slots-codec';\n\n// HKDF info strings — fixed protocol labels for KEK derivation and the slot MAC.\n// Byte-length invariants enforce that the SCREAMING_SNAKE constants stay in sync\n// with the on-wire ASCII literals every conformant verifier hashes against.\nexport const CARDANO_POE_HKDF_INFO_KEK: Uint8Array = new TextEncoder().encode('cardano-poe-kek-v1');\n// Hybrid (X-Wing) per-slot KEK label. Distinct from the classical label so a\n// KEK derived under one KEM can never collide with the other. Reused verbatim as\n// the per-slot wrap AEAD AAD, exactly as the classical path reuses its own label.\nexport const CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-kek-mlkem768x25519-v1',\n);\nexport const CARDANO_POE_HKDF_INFO_SLOTS_MAC: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-slots-mac-v1',\n);\n\nconst ZERO_NONCE_12: Uint8Array = new Uint8Array(12);\nconst EMPTY_SALT: Uint8Array = new Uint8Array(0);\nconst X25519_PUBLIC_KEY_LENGTH = 32 as const;\nconst X25519_SECRET_KEY_LENGTH = 32 as const;\nconst CEK_LENGTH = 32 as const;\nconst NONCE_LENGTH = 24 as const;\nconst WRAP_LENGTH = 48 as const;\nconst SLOTS_MAC_LENGTH = 32 as const;\n\nif (CARDANO_POE_HKDF_INFO_KEK.length !== 18) {\n throw new Error('CARDANO_POE_HKDF_INFO_KEK byte-length invariant violated (expected 18)');\n}\nif (CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519.length !== 33) {\n throw new Error(\n 'CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519 byte-length invariant violated (expected 33)',\n );\n}\nif (CARDANO_POE_HKDF_INFO_SLOTS_MAC.length !== 24) {\n throw new Error('CARDANO_POE_HKDF_INFO_SLOTS_MAC byte-length invariant violated (expected 24)');\n}\nif (ZERO_NONCE_12.length !== 12) {\n throw new Error('ZERO_NONCE_12 byte-length invariant violated (expected 12)');\n}\n\n// Classical per-slot wire shape: { epk: bstr(32), wrap: bstr(48) }.\nexport interface X25519Slot {\n readonly epk: Uint8Array;\n readonly wrap: Uint8Array;\n}\n\n// Hybrid per-slot wire shape: { kem_ct: [ bstr .size (1..64) ], wrap: bstr(48) }.\n// `kem_ct` is the 1120-byte X-Wing enc carried as a chunked byte-string array\n// (the Cardano ledger caps any single metadatum bstr at 64 bytes). There is NO\n// per-slot epk and NO per-slot kem field — the KEM identifier is hoisted to\n// envelope scope (every slot shares it).\nexport interface Mlkem768X25519Slot {\n readonly kem_ct: ReadonlyArray<Uint8Array>;\n readonly wrap: Uint8Array;\n}\n\n// Back-compat alias retired: callers branch on the envelope `kem` and use the\n// concrete slot type. The discriminated `SealedEnvelope` below is the only\n// shape consumers should depend on.\n\n// Sealed envelope wire shape (discriminated on `kem`).\nexport type SealedEnvelope =\n | {\n readonly scheme: 1;\n readonly aead: 'xchacha20-poly1305';\n readonly kem: 'x25519';\n readonly nonce: Uint8Array;\n readonly slots: ReadonlyArray<X25519Slot>;\n readonly slots_mac: Uint8Array;\n }\n | {\n readonly scheme: 1;\n readonly aead: 'xchacha20-poly1305';\n readonly kem: 'mlkem768x25519';\n readonly nonce: Uint8Array;\n readonly slots: ReadonlyArray<Mlkem768X25519Slot>;\n readonly slots_mac: Uint8Array;\n };\n\nexport interface SealedPoeOutput {\n readonly envelope: SealedEnvelope;\n readonly ciphertext: Uint8Array;\n}\n\nexport interface WrapArgs {\n readonly plaintext: Uint8Array;\n readonly recipientPublicKeys: ReadonlyArray<Uint8Array>;\n // KEM branch selector. Defaults to 'x25519' for the classical path. The\n // recipient public-key length is validated against the chosen KEM.\n readonly kem?: SealedKem;\n readonly cek?: Uint8Array;\n readonly nonce?: Uint8Array;\n // Deterministic X25519 ephemeral scalars — x25519 branch only.\n readonly ephemeralSecrets?: ReadonlyArray<Uint8Array>;\n // Deterministic X-Wing encapsulation randomness (64 bytes each) — hybrid\n // branch only. One per recipient, parallel to recipientPublicKeys.\n readonly eseeds?: ReadonlyArray<Uint8Array>;\n readonly skipShuffle?: boolean;\n}\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n}\n\n// Anonymity invariant: wire ordering MUST NOT encode \"primary\n// recipient first\". A CSPRNG-keyed Fisher-Yates shuffle uniformly permutes the\n// slot array so trial-decrypt order leaks no recipient identity. The\n// slot-set HMAC is computed AFTER this shuffle, binding the on-wire order.\n//\n// Draw an unbiased index in [0, m) from a CSPRNG uint32 via rejection sampling.\n// A plain `u32 % m` skews toward the low residues whenever `m` does not divide\n// 2^32 evenly: the values [0, 2^32 mod m) each occur one extra time. This\n// function exists purely to produce a UNIFORM permutation, so the bias — though\n// cryptographically negligible — is exactly the property we cannot tolerate.\n// We reject any draw landing in the final partial block [limit, 2^32) and\n// redraw, leaving only the residues that map uniformly onto [0, m).\n// Exported so the rejection-bound arithmetic can be asserted directly in tests\n// without relying on a flaky statistical-distribution check.\nexport function uniformIndexBelow(m: number): number {\n // 2^32 mod m, computed without overflowing the 32-bit space.\n const limit = 0x1_0000_0000 - (0x1_0000_0000 % m);\n const buf = new Uint32Array(1);\n let x: number;\n do {\n crypto.getRandomValues(buf);\n x = buf[0] as number;\n } while (x >= limit);\n return x % m;\n}\n\nfunction csprngShuffle<T>(arr: T[]): void {\n for (let i = arr.length - 1; i > 0; i--) {\n const j = uniformIndexBelow(i + 1);\n const tmp = arr[i] as T;\n arr[i] = arr[j] as T;\n arr[j] = tmp;\n }\n}\n\n// Wrap the CEK for one classical recipient: age-style ECIES stanza.\nfunction wrapSlotX25519(args: {\n pubR: Uint8Array;\n privEph: Uint8Array | undefined;\n cek: Uint8Array;\n slotIdx: number;\n}): X25519Slot {\n const privEph = args.privEph ?? randomBytes(X25519_SECRET_KEY_LENGTH);\n if (privEph.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_EPHEMERAL_SECRET_LENGTH',\n `ephemeralSecrets[${args.slotIdx}] MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${privEph.length}`,\n );\n }\n const epk = x25519PublicKey({ secretKey: privEph });\n const shared = x25519Ecdh({ secretKey: privEph, theirPublicKey: args.pubR });\n // age v1 stanza salt is `epk || pub_R`.\n const kek = hkdfSha256({\n ikm: shared,\n salt: concat(epk, args.pubR),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n // Per-slot wrap AAD MUST be the 18-byte ASCII literal of the KEK info\n // string (never empty AAD).\n const wrap = chacha20Poly1305Encrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK,\n plaintext: args.cek,\n });\n if (wrap.length !== WRAP_LENGTH) {\n throw new Error(`internal: wrap.length=${wrap.length}, expected ${WRAP_LENGTH}`);\n }\n return { epk, wrap };\n}\n\n// Wrap the CEK for one hybrid recipient: X-Wing encapsulation → HKDF → AEAD.\n// The KEK info label doubles as the wrap AEAD AAD, mirroring the classical path.\nfunction wrapSlotMlkem768X25519(args: {\n pubR: Uint8Array;\n eseed: Uint8Array | undefined;\n cek: Uint8Array;\n}): Mlkem768X25519Slot {\n const { enc, ss } = mlkem768x25519Encapsulate({\n publicKey: args.pubR,\n ...(args.eseed !== undefined ? { eseed: args.eseed } : {}),\n });\n if (enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new Error(`internal: enc.length=${enc.length}, expected ${MLKEM768X25519_ENC_LENGTH}`);\n }\n const kek = hkdfSha256({\n ikm: ss,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n length: 32,\n });\n const wrap = chacha20Poly1305Encrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n plaintext: args.cek,\n });\n if (wrap.length !== WRAP_LENGTH) {\n throw new Error(`internal: wrap.length=${wrap.length}, expected ${WRAP_LENGTH}`);\n }\n return { kem_ct: chunkKemCt(enc), wrap };\n}\n\nexport function eciesSealedPoeWrap(args: WrapArgs): SealedPoeOutput {\n const { plaintext, recipientPublicKeys } = args;\n const kem: SealedKem = args.kem ?? 'x25519';\n const n = recipientPublicKeys.length;\n\n // There is no fixed upper bound on slot count; the producer SDK polices the\n // per-record byte budget. Only the lower bound is enforced here.\n if (n < 1) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_EMPTY',\n `recipientPublicKeys.length=${n} must be >= 1`,\n );\n }\n\n const expectedPubLen =\n kem === 'x25519' ? X25519_PUBLIC_KEY_LENGTH : MLKEM768X25519_PUBLIC_KEY_LENGTH;\n for (let i = 0; i < n; i++) {\n const pub = recipientPublicKeys[i];\n if (pub === undefined || pub.length !== expectedPubLen) {\n throw new EciesSealedPoeError(\n 'KEM_EPK_LENGTH_MISMATCH',\n `recipientPublicKeys[${i}] MUST be exactly ${expectedPubLen} bytes for kem='${kem}'`,\n );\n }\n }\n\n if (kem === 'x25519') {\n if (args.eseeds !== undefined) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n \"eseeds is an X-Wing (mlkem768x25519) override and MUST NOT be supplied for kem='x25519'\",\n );\n }\n if (args.ephemeralSecrets !== undefined && args.ephemeralSecrets.length !== n) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n `ephemeralSecrets.length=${args.ephemeralSecrets.length} must match recipientPublicKeys.length=${n}`,\n );\n }\n } else {\n if (args.ephemeralSecrets !== undefined) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n \"ephemeralSecrets is an X25519 override and MUST NOT be supplied for kem='mlkem768x25519'\",\n );\n }\n if (args.eseeds !== undefined) {\n if (args.eseeds.length !== n) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n `eseeds.length=${args.eseeds.length} must match recipientPublicKeys.length=${n}`,\n );\n }\n for (let i = 0; i < n; i++) {\n const eseed = args.eseeds[i]!;\n if (eseed.length !== MLKEM768X25519_ESEED_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_EPHEMERAL_SECRET_LENGTH',\n `eseeds[${i}] MUST be exactly ${MLKEM768X25519_ESEED_LENGTH} bytes, got ${eseed.length}`,\n );\n }\n }\n }\n }\n\n const cek = args.cek ?? randomBytes(CEK_LENGTH);\n const nonce = args.nonce ?? randomBytes(NONCE_LENGTH);\n if (cek.length !== CEK_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_CEK_LENGTH',\n `cek MUST be exactly ${CEK_LENGTH} bytes, got ${cek.length}`,\n );\n }\n if (nonce.length !== NONCE_LENGTH) {\n throw new EciesSealedPoeError(\n 'NONCE_LENGTH_MISMATCH',\n `nonce MUST be exactly ${NONCE_LENGTH} bytes, got ${nonce.length}`,\n );\n }\n\n let envelope: SealedEnvelope;\n if (kem === 'x25519') {\n const slots: X25519Slot[] = [];\n for (let i = 0; i < n; i++) {\n slots.push(\n wrapSlotX25519({\n pubR: recipientPublicKeys[i]!,\n privEph: args.ephemeralSecrets ? (args.ephemeralSecrets[i] as Uint8Array) : undefined,\n cek,\n slotIdx: i,\n }),\n );\n }\n // Anonymity invariant (see csprngShuffle comment).\n if (args.skipShuffle !== true) {\n csprngShuffle(slots);\n }\n const slotsMac = computeSlotsMac(cek, slots, 'x25519');\n envelope = {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'x25519',\n nonce,\n slots,\n slots_mac: slotsMac,\n };\n } else {\n const slots: Mlkem768X25519Slot[] = [];\n for (let i = 0; i < n; i++) {\n slots.push(\n wrapSlotMlkem768X25519({\n pubR: recipientPublicKeys[i]!,\n eseed: args.eseeds ? (args.eseeds[i] as Uint8Array) : undefined,\n cek,\n }),\n );\n }\n if (args.skipShuffle !== true) {\n csprngShuffle(slots);\n }\n const slotsMac = computeSlotsMac(cek, slots, 'mlkem768x25519');\n envelope = {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'mlkem768x25519',\n nonce,\n slots,\n slots_mac: slotsMac,\n };\n }\n\n // Content AEAD AAD is `nonce || slots_mac` (24 + 32 = 56 B).\n const adContent = concat(nonce, envelope.slots_mac);\n const ciphertext = xchacha20Poly1305Encrypt({\n key: cek,\n nonce,\n aad: adContent,\n plaintext,\n });\n\n return { envelope, ciphertext };\n}\n\n// Slot-set MAC binds canonical-CBOR(slots) to the CEK.\n// The slot→CBOR serialization is KEM-driven (`slotsToMacCbor`) so the hybrid\n// kem_ct is authenticated by slots_mac exactly as the classical epk is.\nfunction computeSlotsMac(\n cek: Uint8Array,\n slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n kem: SealedKem,\n): Uint8Array {\n const hmacKey = hkdfSha256({\n ikm: cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsCbor = slotsToMacCbor(slots, kem);\n const slotsMac = hmac(sha256, hmacKey, slotsCbor);\n if (slotsMac.length !== SLOTS_MAC_LENGTH) {\n throw new Error(`internal: slots_mac.length=${slotsMac.length}, expected ${SLOTS_MAC_LENGTH}`);\n }\n return slotsMac;\n}\n","// Multi-recipient sealed-PoE unwrap (age-style trial-decrypt\n// + constant-time slots_mac binding + partitioning-oracle length pre-checks).\n//\n// Two forms (mutually exclusive — exactly one MUST be supplied):\n//\n// • Single-priv form: `recipientSecretKey: Uint8Array` — the standalone-verifier\n// path. Runs the trial-decrypt loop over `envelope.slots` once.\n//\n// • Multi-priv form: `recipientSecretKeys: ReadonlyArray<Uint8Array>` — for the\n// trial-decrypt scan of a rotated identity holding `[currentPriv, ...archivedPrivs]`.\n// Caller supplies the order; the iterator runs outer-loop = privkey ×\n// inner-loop = slot, short-circuiting on the first cross-priv match that\n// passes slots_mac verification. The recommended caller order\n// is `[currentPriv, ...previousPrivsReversed]` (newest archive first).\n//\n// Constant-time-N (default `true`) applies PER PRIV (the inner loop): all slots\n// are entered regardless of match position. The outer loop short-circuits on\n// first cross-priv match — the cross-priv channel is intrinsic to trial-decrypt\n//\n// Both KEM branches share this control flow. The per-slot recovery body differs:\n// • x25519: X25519 ECDH → HKDF → AEAD-unwrap; may throw on a low-order\n// epk (RFC 7748 §6.1 contributory-check rejection), handled\n// as a non-match.\n// • mlkem768x25519: X-Wing decapsulate → HKDF → AEAD-unwrap; NEVER throws on\n// attacker wire data (ML-KEM implicit rejection yields a\n// pseudorandom shared secret), so no try/catch around it.\n\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { chacha20Poly1305Decrypt } from '../aead/chacha20-poly1305';\nimport { AeadVerificationError } from '../aead/errors';\nimport { xchacha20Poly1305Decrypt } from '../aead/xchacha20-poly1305';\nimport { hkdfSha256 } from '../kdf/hkdf';\nimport { mlkem768x25519Decapsulate, MLKEM768X25519_ENC_LENGTH } from '../kem/mlkem768x25519';\nimport { x25519Ecdh, X25519LowOrderPointError, x25519PublicKey } from '../kem/x25519';\nimport { compareCt } from '../util/compare-ct';\n\nimport { EciesSealedPoeError } from './errors';\nimport { joinKemCt, slotsToMacCbor } from './slots-codec';\nimport {\n CARDANO_POE_HKDF_INFO_KEK,\n CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n type Mlkem768X25519Slot,\n type SealedEnvelope,\n type X25519Slot,\n} from './wrap';\n\nexport type UnwrapFailureReason = 'WRONG_RECIPIENT_KEY' | 'TAMPERED_HEADER' | 'TAMPERED_CIPHERTEXT';\n\nexport type UnwrapResult =\n | { readonly matched: true; readonly plaintext: Uint8Array }\n | { readonly matched: false; readonly reason: UnwrapFailureReason };\n\n// Unified recipient key bundle. Callers hold BOTH the X25519\n// private-key chain (current + archived, for classical and rotation history)\n// AND the X-Wing secret seed(s) (for the hybrid KEM), without knowing which a\n// given record was sealed under. They pass the whole bundle; the unwrap /\n// trial-decrypt dispatch selects the correct secret list from `envelope.kem`:\n//\n// • kem === 'x25519' → bundle.x25519PrivateKeys\n// • kem === 'mlkem768x25519' → bundle.mlkem768x25519SecretSeeds\n//\n// Both lists are ordered newest-first (caller's responsibility — the outer\n// trial-decrypt loop scans them in order). A list MAY be empty when the\n// recipient holds no key for that KEM (e.g. archived-only X25519 identities\n// predate the hybrid KEM, so their hybrid seed list is empty); a bundle whose\n// selected list is empty unwraps to a clean WRONG_RECIPIENT_KEY / no_aead_pass\n// without touching any KEM primitive.\nexport interface RecipientKeyBundle {\n readonly x25519PrivateKeys: ReadonlyArray<Uint8Array>;\n readonly mlkem768x25519SecretSeeds: ReadonlyArray<Uint8Array>;\n}\n\n// Select the secret-key list a bundle contributes for the given envelope KEM.\n// The single dispatch seam — wrap and trial-decrypt both route through here so\n// the per-KEM selection lives in exactly one place.\nfunction selectBundleSecrets(\n envelope: SealedEnvelope,\n bundle: RecipientKeyBundle,\n): ReadonlyArray<Uint8Array> {\n return envelope.kem === 'x25519' ? bundle.x25519PrivateKeys : bundle.mlkem768x25519SecretSeeds;\n}\n\ninterface UnwrapArgsCommon {\n readonly envelope: SealedEnvelope;\n readonly ciphertext: Uint8Array;\n readonly constantTimeN?: boolean;\n // Test-only instrumentation for constant-time-N verification.\n // The unwrap fn bumps `count` once per inner-loop iteration entered. In the\n // multi-priv path, `count` is reset at the start of each outer iteration and\n // — when `perPrivCounts` is provided — the final per-priv inner count is\n // appended after that priv's inner loop completes. Production callers never\n // pass this.\n readonly _slotsAttemptedOut?: { count: number; perPrivCounts?: number[] };\n // Test-only multi-priv outer-loop iteration counter. Bumped to `k + 1` at\n // the start of each outer-loop iteration. Production callers never pass this.\n readonly _privsAttemptedOut?: { count: number };\n}\n\nexport interface UnwrapArgsSinglePriv extends UnwrapArgsCommon {\n readonly recipientSecretKey: Uint8Array;\n}\n\nexport interface UnwrapArgsMultiPriv extends UnwrapArgsCommon {\n readonly recipientSecretKeys: ReadonlyArray<Uint8Array>;\n}\n\n// Bundle form of the multi-priv path: the caller passes both KEMs' secret\n// lists and the dispatch picks the right one from `envelope.kem`. This is the\n// surface every read-path consumer (inbox decrypt, CLI decrypt, standalone\n// recipient verifier) should use — they hold the whole identity key bundle and\n// must NOT pre-select a list or rebuild slots themselves.\nexport interface UnwrapArgsBundle extends UnwrapArgsCommon {\n readonly recipientKeyBundle: RecipientKeyBundle;\n}\n\nexport type UnwrapArgs = UnwrapArgsSinglePriv | UnwrapArgsMultiPriv | UnwrapArgsBundle;\n\n// Trial-decrypt-only sibling of eciesSealedPoeUnwrap. Runs the\n// per-slot AEAD + slots_mac check but NEVER calls the content AEAD (which\n// requires the off-chain `ciphertext` blob, not available at trial-decrypt\n// time). Used by an inbox-scan agent to discover readable records before\n// fetching their ciphertext.\ninterface TrialDecryptOnlyArgsCommon {\n readonly envelope: SealedEnvelope;\n readonly constantTimeN?: boolean;\n readonly _slotsAttemptedOut?: { count: number; perPrivCounts?: number[] };\n readonly _privsAttemptedOut?: { count: number };\n}\n\n// Exactly one of `recipientSecretKeys` (flat, KEM-pre-selected) or\n// `recipientKeyBundle` (whole bundle, KEM dispatched from `envelope.kem`).\n// Inbox-scan consumers pass the bundle; the low-level / parity tests pass the\n// flat list directly.\nexport type TrialDecryptOnlyArgs = TrialDecryptOnlyArgsCommon &\n (\n | { readonly recipientSecretKeys: ReadonlyArray<Uint8Array> }\n | { readonly recipientKeyBundle: RecipientKeyBundle }\n );\n\nexport type TrialDecryptOnlyResult =\n | { readonly kind: 'match'; readonly slotIdx: number; readonly cek: Uint8Array }\n | { readonly kind: 'no_aead_pass' }\n | { readonly kind: 'aead_pass_no_mac_match' };\n\nconst ZERO_NONCE_12: Uint8Array = new Uint8Array(12);\nconst EMPTY_SALT: Uint8Array = new Uint8Array(0);\nconst X25519_SECRET_KEY_LENGTH = 32 as const;\nconst X25519_PUBLIC_KEY_LENGTH = 32 as const;\nconst NONCE_LENGTH = 24 as const;\nconst WRAP_LENGTH = 48 as const;\nconst SLOTS_MAC_LENGTH = 32 as const;\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n}\n\n// Partitioning-oracle defence: every wire\n// length MUST be validated before any KEM/AEAD primitive is invoked, so malformed\n// records cannot probe per-slot failure ordering. Shared between\n// `eciesSealedPoeUnwrap` (single- and multi-priv) and `eciesSealedPoeTrialDecrypt`\n// to guarantee byte-identical pre-trial behaviour and to keep the dispatch\n// invariant in one place. For the hybrid branch this includes reassembling each\n// slot's `kem_ct` and asserting the flat enc length BEFORE any decapsulation.\nfunction assertEnvelopeStructure(\n envelope: SealedEnvelope,\n multiPrivKeys?: ReadonlyArray<Uint8Array>,\n singlePrivKey?: Uint8Array,\n): void {\n if (envelope.scheme !== 1) {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_ENC_VERSION',\n `envelope.scheme=${String(envelope.scheme)} unsupported (expected 1)`,\n );\n }\n if (envelope.aead !== 'xchacha20-poly1305') {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_AEAD_ALG',\n `envelope.aead=${String(envelope.aead)} unsupported (expected 'xchacha20-poly1305')`,\n );\n }\n if (envelope.kem !== 'x25519' && envelope.kem !== 'mlkem768x25519') {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_KEM_ALG',\n `envelope.kem=${String((envelope as { kem: string }).kem)} unsupported (expected 'x25519' or 'mlkem768x25519')`,\n );\n }\n\n // Envelope-level length pre-checks in this exact order.\n const n = envelope.slots.length;\n if (n < 1) {\n throw new EciesSealedPoeError('ENC_SLOTS_EMPTY', `envelope.slots.length=${n} must be >= 1`);\n }\n if (envelope.nonce.length !== NONCE_LENGTH) {\n throw new EciesSealedPoeError(\n 'NONCE_LENGTH_MISMATCH',\n `envelope.nonce MUST be exactly ${NONCE_LENGTH} bytes, got ${envelope.nonce.length}`,\n );\n }\n if (envelope.slots_mac.length !== SLOTS_MAC_LENGTH) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_MAC_INVALID_LENGTH',\n `envelope.slots_mac MUST be exactly ${SLOTS_MAC_LENGTH} bytes, got ${envelope.slots_mac.length}`,\n );\n }\n\n // Per-slot length pre-checks — KEM-driven. ALL slots are validated here,\n // before any decapsulation, so the trial-decrypt loop never observes a\n // malformed slot (partitioning-oracle-safe ordering).\n if (envelope.kem === 'x25519') {\n for (let i = 0; i < n; i++) {\n const slot = envelope.slots[i]!;\n if (slot.epk.length !== X25519_PUBLIC_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'KEM_EPK_LENGTH_MISMATCH',\n `envelope.slots[${i}].epk MUST be exactly ${X25519_PUBLIC_KEY_LENGTH} bytes, got ${slot.epk.length}`,\n );\n }\n if (slot.wrap.length !== WRAP_LENGTH) {\n throw new EciesSealedPoeError(\n 'WRAP_LENGTH_MISMATCH',\n `envelope.slots[${i}].wrap MUST be exactly ${WRAP_LENGTH} bytes, got ${slot.wrap.length}`,\n );\n }\n }\n } else {\n for (let i = 0; i < n; i++) {\n const slot = envelope.slots[i]!;\n const enc = joinKemCt(slot.kem_ct);\n if (enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new EciesSealedPoeError(\n 'KEM_CT_LENGTH_MISMATCH',\n `envelope.slots[${i}].kem_ct MUST reassemble to exactly ${MLKEM768X25519_ENC_LENGTH} bytes, got ${enc.length}`,\n );\n }\n if (slot.wrap.length !== WRAP_LENGTH) {\n throw new EciesSealedPoeError(\n 'WRAP_LENGTH_MISMATCH',\n `envelope.slots[${i}].wrap MUST be exactly ${WRAP_LENGTH} bytes, got ${slot.wrap.length}`,\n );\n }\n }\n }\n\n if (multiPrivKeys !== undefined) {\n for (let i = 0; i < multiPrivKeys.length; i++) {\n if (multiPrivKeys[i]!.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n `recipientSecretKeys[${i}] MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${multiPrivKeys[i]!.length}`,\n );\n }\n }\n } else if (singlePrivKey !== undefined) {\n if (singlePrivKey.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n `recipientSecretKey MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${singlePrivKey.length}`,\n );\n }\n }\n}\n\n// Classical (x25519) per-slot recovery body. Returns the CEK on the first\n// AEAD-tag success; null otherwise. `liveSlot` distinguishes the real-work path\n// (attempt the AEAD unwrap) from the constant-time-N dummy path (do the ECDH +\n// HKDF but skip the AEAD, since a CEK is already in hand).\nfunction tryX25519Slot(args: {\n slot: X25519Slot;\n recipientSecretKey: Uint8Array;\n pubRLocal: Uint8Array;\n liveSlot: boolean;\n}): Uint8Array | null {\n // A slot's `epk` is attacker-influenceable wire data. A small-order\n // Montgomery point makes the X25519 shared secret all-zero, which the KEM\n // rejects per RFC 7748 §6.1. Such a slot can never have been produced by a\n // conformant wrap for THIS recipient, so it is a non-match — handled here\n // identically to an AEAD-tag failure (skip the slot, keep iterating so the\n // constant-time-N loop shape is preserved). Only the contributory-check\n // rejection is swallowed; any other error propagates.\n if (args.liveSlot) {\n try {\n const shared = x25519Ecdh({\n secretKey: args.recipientSecretKey,\n theirPublicKey: args.slot.epk,\n });\n const kek = hkdfSha256({\n ikm: shared,\n salt: concat(args.slot.epk, args.pubRLocal),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n return chacha20Poly1305Decrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK,\n ciphertext: args.slot.wrap,\n });\n } catch (e) {\n if (!(e instanceof AeadVerificationError) && !(e instanceof X25519LowOrderPointError)) {\n throw e;\n }\n return null;\n }\n }\n // Constant-time-N dummy path: mirror the real-work ECDH + HKDF, still\n // tolerating a low-order epk in a later slot so it cannot turn a successful\n // unwrap into a throw.\n try {\n const shared = x25519Ecdh({\n secretKey: args.recipientSecretKey,\n theirPublicKey: args.slot.epk,\n });\n hkdfSha256({\n ikm: shared,\n salt: concat(args.slot.epk, args.pubRLocal),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n } catch (e) {\n if (!(e instanceof X25519LowOrderPointError)) throw e;\n }\n return null;\n}\n\n// Hybrid (mlkem768x25519) per-slot recovery body. X-Wing decapsulate NEVER\n// throws on attacker wire data (ML-KEM implicit rejection), so there is no\n// try/catch: a wrong shared secret simply yields a KEK that fails the AEAD tag.\n// The dummy (constant-time-N) path runs a FULL decapsulate + HKDF so matching\n// and non-matching slots cost the same X-Wing work.\nfunction tryMlkem768X25519Slot(args: {\n slot: Mlkem768X25519Slot;\n recipientSecretKey: Uint8Array;\n liveSlot: boolean;\n}): Uint8Array | null {\n // kem_ct length was validated to reassemble to MLKEM768X25519_ENC_LENGTH in\n // assertEnvelopeStructure, so this join + decapsulate is constant-work.\n const enc = joinKemCt(args.slot.kem_ct);\n const ss = mlkem768x25519Decapsulate({ secretSeed: args.recipientSecretKey, enc });\n const kek = hkdfSha256({\n ikm: ss,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n length: 32,\n });\n if (!args.liveSlot) {\n // Dummy path: full decapsulate + HKDF already done above; skip only the\n // AEAD attempt (a CEK is already in hand).\n return null;\n }\n try {\n return chacha20Poly1305Decrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n ciphertext: args.slot.wrap,\n });\n } catch (e) {\n if (!(e instanceof AeadVerificationError)) throw e;\n return null;\n }\n}\n\n// Per-priv inner trial-decrypt loop with slot-index reporting, KEM-driven.\n// Enters every slot when constantTimeN; the dummy path keeps per-iteration cost\n// uniform regardless of which slot matched.\nfunction tryRecipientUnwrapWithIdx(\n envelope: SealedEnvelope,\n recipientSecretKey: Uint8Array,\n constantTimeN: boolean,\n slotsAttemptedOut: { count: number; perPrivCounts?: number[] } | undefined,\n): { cek: Uint8Array; slotIdx: number } | null {\n const n = envelope.slots.length;\n let cek: Uint8Array | null = null;\n let matchedSlotIdx = -1;\n\n if (envelope.kem === 'x25519') {\n const pubRLocal = x25519PublicKey({ secretKey: recipientSecretKey });\n for (let i = 0; i < n; i++) {\n if (slotsAttemptedOut !== undefined) {\n slotsAttemptedOut.count = i + 1;\n }\n const candidate = tryX25519Slot({\n slot: envelope.slots[i]!,\n recipientSecretKey,\n pubRLocal,\n liveSlot: cek === null,\n });\n if (cek === null && candidate !== null) {\n cek = candidate;\n matchedSlotIdx = i;\n }\n if (cek !== null && !constantTimeN) break;\n }\n } else {\n for (let i = 0; i < n; i++) {\n if (slotsAttemptedOut !== undefined) {\n slotsAttemptedOut.count = i + 1;\n }\n const candidate = tryMlkem768X25519Slot({\n slot: envelope.slots[i]!,\n recipientSecretKey,\n liveSlot: cek === null,\n });\n if (cek === null && candidate !== null) {\n cek = candidate;\n matchedSlotIdx = i;\n }\n if (cek !== null && !constantTimeN) break;\n }\n }\n return cek === null ? null : { cek, slotIdx: matchedSlotIdx };\n}\n\n// Back-compat wrapper preserved for callers that only care about the CEK\n// (single-priv path inside `eciesSealedPoeUnwrap`).\nfunction tryRecipientUnwrap(\n envelope: SealedEnvelope,\n recipientSecretKey: Uint8Array,\n constantTimeN: boolean,\n slotsAttemptedOut: { count: number; perPrivCounts?: number[] } | undefined,\n): Uint8Array | null {\n return (\n tryRecipientUnwrapWithIdx(envelope, recipientSecretKey, constantTimeN, slotsAttemptedOut)\n ?.cek ?? null\n );\n}\n\n// Slot-set MAC bytes, KEM-driven so the hybrid kem_ct is\n// committed exactly as it appears on-wire. Constant across the multi-priv outer\n// loop (depends only on envelope.slots), so callers compute it once.\nfunction slotsMacCborBytes(envelope: SealedEnvelope): Uint8Array {\n return slotsToMacCbor(\n envelope.slots as ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n envelope.kem,\n );\n}\n\nexport function eciesSealedPoeUnwrap(args: UnwrapArgs): UnwrapResult {\n const { envelope, ciphertext } = args;\n const constantTimeN = args.constantTimeN ?? true;\n\n // Exactly-one-of validation across the three UnwrapArgs forms (single-priv,\n // flat multi-priv, bundle). Runs before any AEAD / wire-shape work so a\n // malformed call cannot probe per-slot AEAD timing. The bundle form resolves\n // to a flat multi-priv list here by dispatching on `envelope.kem` — from this\n // point the loop is identical regardless of how the caller supplied keys.\n const hasSingle = 'recipientSecretKey' in args;\n const hasBundle = 'recipientKeyBundle' in args;\n const multiPrivKeys: ReadonlyArray<Uint8Array> | undefined = hasBundle\n ? selectBundleSecrets(envelope, (args as UnwrapArgsBundle).recipientKeyBundle)\n : 'recipientSecretKeys' in args\n ? (args as UnwrapArgsMultiPriv).recipientSecretKeys\n : undefined;\n const hasMulti = multiPrivKeys !== undefined;\n if (hasSingle === hasMulti) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'exactly one of recipientSecretKey / recipientSecretKeys / recipientKeyBundle MUST be supplied',\n );\n }\n // A bundle selecting an empty list for this KEM means the recipient holds no\n // key of the matching kind (e.g. an archived-only identity facing a hybrid\n // record). That is a legitimate non-match, NOT a malformed call — return a\n // clean WRONG_RECIPIENT_KEY without invoking any KEM primitive. The flat\n // multi-priv form keeps the original \"empty array is a programmer error\"\n // contract its callers (and step-3 tests) rely on.\n if (hasMulti && multiPrivKeys!.length === 0) {\n if (hasBundle) {\n return { matched: false, reason: 'WRONG_RECIPIENT_KEY' };\n }\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'recipientSecretKeys MUST be a non-empty array, got length=0',\n );\n }\n\n // Partitioning-oracle pre-checks; per-priv length validation happens\n // inside `assertEnvelopeStructure`.\n if (hasMulti) {\n assertEnvelopeStructure(envelope, multiPrivKeys, undefined);\n } else {\n assertEnvelopeStructure(envelope, undefined, (args as UnwrapArgsSinglePriv).recipientSecretKey);\n }\n\n // Trial-decrypt loop. With constantTimeN=true the loop\n // entries are uniform regardless of match position; the per-iteration body\n // does the same KEM + HKDF work in both branches.\n\n let matchedCek: Uint8Array | null = null;\n let anyCandidateRecovered = false;\n\n if (hasSingle) {\n const recipientSecretKey = (args as UnwrapArgsSinglePriv).recipientSecretKey;\n const cek = tryRecipientUnwrap(\n envelope,\n recipientSecretKey,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (cek === null) {\n return { matched: false, reason: 'WRONG_RECIPIENT_KEY' };\n }\n // Slot-set MAC verification. Use compareCt to\n // avoid leaking byte-position via early-exit on first mismatching byte.\n const slotsCbor = slotsMacCborBytes(envelope);\n const hmacKey = hkdfSha256({\n ikm: cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsMacCalc = hmac(sha256, hmacKey, slotsCbor);\n if (!compareCt(slotsMacCalc, envelope.slots_mac)) {\n return { matched: false, reason: 'TAMPERED_HEADER' };\n }\n matchedCek = cek;\n } else {\n // The slots-CBOR is constant across the outer loop (depends only on\n // envelope.slots) — compute once before the loop to keep per-priv cost\n // identical to the single-priv path.\n const slotsCbor = slotsMacCborBytes(envelope);\n const recipientSecretKeys = multiPrivKeys!;\n for (let k = 0; k < recipientSecretKeys.length; k++) {\n if (args._privsAttemptedOut !== undefined) {\n args._privsAttemptedOut.count = k + 1;\n }\n if (args._slotsAttemptedOut !== undefined) {\n args._slotsAttemptedOut.count = 0;\n }\n const cek = tryRecipientUnwrap(\n envelope,\n recipientSecretKeys[k]!,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (args._slotsAttemptedOut?.perPrivCounts !== undefined) {\n args._slotsAttemptedOut.perPrivCounts.push(args._slotsAttemptedOut.count);\n }\n if (cek === null) continue;\n // Slot-set MAC verification per priv that recovered a candidate CEK.\n const hmacKey = hkdfSha256({\n ikm: cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsMacCalc = hmac(sha256, hmacKey, slotsCbor);\n // The outer cross-priv loop short-circuits on the first priv whose\n // recovered CEK also passes slots_mac. This intentionally leaks \"which\n // priv matched\" → \"how many key rotations the recipient has performed\".\n // We accept it: trial-decrypt runs client-side, so this timing is only\n // locally observable, and the leak is a weak ordering signal, not a\n // key/plaintext oracle. Making the outer loop constant-work would cost a\n // FULL KEM decapsulation (an X25519 ECDH, or — for the hybrid branch — a\n // full X-Wing ML-KEM-768 + X25519 decapsulation) for EVERY archived priv\n // on EVERY record, which for the hybrid case is the dominant cost; the\n // benefit (hiding a count the user already knows) does not justify it.\n // The inner per-slot loop IS held constant-work (constant-time-N).\n if (compareCt(slotsMacCalc, envelope.slots_mac)) {\n matchedCek = cek;\n break;\n }\n anyCandidateRecovered = true;\n }\n if (matchedCek === null) {\n return {\n matched: false,\n reason: anyCandidateRecovered ? 'TAMPERED_HEADER' : 'WRONG_RECIPIENT_KEY',\n };\n }\n }\n\n // Content AEAD AAD is `nonce || slots_mac`.\n const adContent = concat(envelope.nonce, envelope.slots_mac);\n try {\n const plaintext = xchacha20Poly1305Decrypt({\n key: matchedCek,\n nonce: envelope.nonce,\n aad: adContent,\n ciphertext,\n });\n return { matched: true, plaintext };\n } catch (e) {\n if (!(e instanceof AeadVerificationError)) throw e;\n return { matched: false, reason: 'TAMPERED_CIPHERTEXT' };\n }\n}\n\n// Trial-decrypt half of the sealed-PoE unwrap algorithm:\n// recovers the CEK + slot index without touching the content AEAD. Used by an\n// inbox-scan agent where the on-chain `metadata_cbor` envelope is available but\n// the off-chain ciphertext blob is fetched lazily only when the user invokes\n// Decrypt.\n//\n// Mirrors the multi-priv branch of `eciesSealedPoeUnwrap`: same\n// partitioning-oracle pre-checks, same per-priv inner loop, same\n// constant-time-N invariant (default `true` — MANDATORY for untrusted scan\n// agents), same `compareCt` slots_mac check. Differs only\n// in the return shape: `{kind: 'match', slotIdx, cek}` instead of plaintext;\n// `{kind: 'aead_pass_no_mac_match'}`\n// instead of `TAMPERED_HEADER`; `{kind: 'no_aead_pass'}` instead of\n// `WRONG_RECIPIENT_KEY`. Cross-priv variable-time short-circuit is preserved\n// (leaks \"which priv matched\" → \"how many rotations\",\n// a documented weak ordering signal).\nexport function eciesSealedPoeTrialDecrypt(args: TrialDecryptOnlyArgs): TrialDecryptOnlyResult {\n const { envelope } = args;\n const constantTimeN = args.constantTimeN ?? true;\n\n // Bundle form selects the per-KEM list from `envelope.kem`; flat form is\n // already KEM-pre-selected. An empty bundle list for this KEM is a clean\n // no_aead_pass (the recipient holds no key of the matching kind), whereas an\n // empty flat list stays a programmer error (its callers / step-3 tests rely\n // on the throw).\n const hasBundle = 'recipientKeyBundle' in args;\n const recipientSecretKeys: ReadonlyArray<Uint8Array> = hasBundle\n ? selectBundleSecrets(envelope, args.recipientKeyBundle)\n : args.recipientSecretKeys;\n\n if (recipientSecretKeys.length === 0) {\n if (hasBundle) {\n return { kind: 'no_aead_pass' };\n }\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'recipientSecretKeys MUST be a non-empty array, got length=0',\n );\n }\n assertEnvelopeStructure(envelope, recipientSecretKeys, undefined);\n\n const slotsCbor = slotsMacCborBytes(envelope);\n\n let anyCandidateRecovered = false;\n for (let k = 0; k < recipientSecretKeys.length; k++) {\n if (args._privsAttemptedOut !== undefined) {\n args._privsAttemptedOut.count = k + 1;\n }\n if (args._slotsAttemptedOut !== undefined) {\n args._slotsAttemptedOut.count = 0;\n }\n const candidate = tryRecipientUnwrapWithIdx(\n envelope,\n recipientSecretKeys[k]!,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (args._slotsAttemptedOut?.perPrivCounts !== undefined) {\n args._slotsAttemptedOut.perPrivCounts.push(args._slotsAttemptedOut.count);\n }\n if (candidate === null) continue;\n const hmacKey = hkdfSha256({\n ikm: candidate.cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsMacCalc = hmac(sha256, hmacKey, slotsCbor);\n if (compareCt(slotsMacCalc, envelope.slots_mac)) {\n return { kind: 'match', slotIdx: candidate.slotIdx, cek: candidate.cek };\n }\n anyCandidateRecovered = true;\n }\n return anyCandidateRecovered ? { kind: 'aead_pass_no_mac_match' } : { kind: 'no_aead_pass' };\n}\n","// The single seam that turns a structurally-validated but permissive on-wire\n// `enc` block into the discriminated `SealedEnvelope` the unwrap / trial-decrypt\n// path consumes.\n//\n// Every read-path consumer (inbox trial-decrypt, inbox CEK recovery, the CLI\n// `inbox sync` / `inbox decrypt` orchestrators, the standalone recipient\n// verifier) used to do this inline with a HARDCODED `kem: 'x25519'` and an\n// unconditional `slots.map(s => ({ epk: s.epk, wrap: s.wrap }))`. With the\n// discriminated-union slot shape (classical `{epk, wrap}` vs hybrid\n// `{kem_ct, wrap}`) that inline build is both wrong (drops `kem_ct`) and\n// uncompilable (reads optional `epk` as required). This helper is the ONE place\n// the conversion lives: it dispatches on `enc.kem`, picks the matching per-slot\n// fields, and returns `null` for anything that is not a recognised sealed\n// envelope (passphrase-only blocks, missing slots, unknown KEM). Callers then\n// pass the whole returned envelope plus their `RecipientKeyBundle` straight to\n// `eciesSealedPoeUnwrap` / `eciesSealedPoeTrialDecrypt` — they never rebuild\n// slots or reassemble `kem_ct` themselves.\n//\n// crypto-core is a leaf package and must not depend on poe-standard's Zod\n// schema, so the input is a structural shape mirroring the fields the parsed\n// `EncryptionEnvelope` exposes. Anything narrower (per-slot length checks) is\n// re-asserted by `assertEnvelopeStructure` inside the unwrap path; this helper\n// is purely the KEM-driven shape projection.\n\nimport type { Mlkem768X25519Slot, SealedEnvelope, X25519Slot } from './wrap';\n\n// Structural mirror of the parsed-but-permissive on-wire slot. Each field is\n// `T | undefined` (not just optional) so the parsed `EncryptionEnvelope` from a\n// consumer compiled with `exactOptionalPropertyTypes` is assignable without a\n// cast: the schema layer cannot know the envelope `kem` from a slot in\n// isolation, so it leaves all three fields optional (see poe-standard\n// SlotSchema).\nexport interface ParsedSlotShape {\n readonly epk?: Uint8Array | undefined;\n readonly kem_ct?: ReadonlyArray<Uint8Array> | undefined;\n readonly wrap?: Uint8Array | undefined;\n}\n\n// Structural mirror of the parsed-but-permissive `enc` block.\nexport interface ParsedEnvelopeShape {\n readonly scheme?: unknown;\n readonly aead?: string | undefined;\n readonly kem?: string | undefined;\n readonly nonce?: Uint8Array | undefined;\n readonly slots?: ReadonlyArray<ParsedSlotShape> | undefined;\n readonly slots_mac?: Uint8Array | undefined;\n}\n\n// Build the discriminated `SealedEnvelope` from a parsed `enc` block, or return\n// `null` when the block is not a sealed-recipient envelope we can trial-decrypt\n// (passphrase-only, missing slots/nonce/slots_mac, unrecognised KEM, or a slot\n// missing the KEM's required field). Returning `null` keeps every consumer's\n// \"this item is not for the recipient path → no match, no crypto\" branch.\nexport function sealedEnvelopeFromParsed(enc: ParsedEnvelopeShape): SealedEnvelope | null {\n if (enc.scheme !== 1 || enc.aead !== 'xchacha20-poly1305') return null;\n if (enc.nonce === undefined || enc.slots_mac === undefined) return null;\n const slots = enc.slots;\n if (slots === undefined || slots.length < 1) return null;\n\n if (enc.kem === 'x25519') {\n const x25519Slots: X25519Slot[] = [];\n for (const s of slots) {\n if (s.epk === undefined || s.wrap === undefined) return null;\n x25519Slots.push({ epk: s.epk, wrap: s.wrap });\n }\n return {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'x25519',\n nonce: enc.nonce,\n slots: x25519Slots,\n slots_mac: enc.slots_mac,\n };\n }\n\n if (enc.kem === 'mlkem768x25519') {\n const hybridSlots: Mlkem768X25519Slot[] = [];\n for (const s of slots) {\n if (s.kem_ct === undefined || s.wrap === undefined) return null;\n hybridSlots.push({ kem_ct: s.kem_ct, wrap: s.wrap });\n }\n return {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'mlkem768x25519',\n nonce: enc.nonce,\n slots: hybridSlots,\n slots_mac: enc.slots_mac,\n };\n }\n\n return null;\n}\n","// Canonical outbound HTTP wrapper: deny-list short-circuit, protocol/method\n// allowlist, bounded timeout, exp-backoff retry with jitter, audit trail.\n\n// Universal loopback deny-host list a service-independent verifier MUST reject\n// so a record can never be made to \"verify\" only because it reached a loopback\n// address. This default carries no operator-specific entries: a deployment that\n// wants to forbid its own gateway/viewer hosts appends those at construction\n// time. Producers SHOULD pass this through `denyHosts` on every verifier\n// invocation; the wrapper accepts arbitrary lists but exports the canonical\n// loopback set so callers don't duplicate it inline. (RFC-1918 / link-local IP\n// ranges are blocked separately by the SSRF guard, not by this name list.)\nexport const DENY_HOSTS_DEFAULT: ReadonlyArray<string> = ['localhost', '127.0.0.1'];\n\n// Every outbound call carries a purpose tag from the closed set\n// `{cardano, arweave, ipfs}` (the three v1 gateway-chain purposes).\n// `https` is a transitional legacy tag for non-storage HTTPS\n// auxiliaries; new code SHOULD pick one of the three normative purposes.\n// `webhook` is the user-supplied-URL purpose: it triggers the SSRF guard\n// (DNS resolution + IP range check + connection pinning + redirect-chain\n// re-checking + body-size cap), and MUST be used for any fetch where the\n// target URL came from end-user input.\nexport type HttpPurpose = 'cardano' | 'arweave' | 'ipfs' | 'https' | 'webhook';\nexport type HttpMethod = 'GET' | 'POST';\n\nexport interface FetchOutboundOptions {\n readonly method: HttpMethod;\n readonly purpose: HttpPurpose;\n readonly headers?: Readonly<Record<string, string>>;\n readonly body?: string;\n // Hard cap on the response body the primitive will buffer. Gateway content\n // (ar:// / ipfs:// / https) is producer-chosen and therefore UNTRUSTED — the\n // verifier never trusts the producer — so a malicious gateway could otherwise\n // stream unbounded bytes into memory. Omit to use DEFAULT_OUTBOUND_MAX_BYTES.\n readonly maxBytes?: number;\n}\n\nexport interface FetchOutboundResult {\n readonly status: number;\n readonly bytes: Uint8Array;\n readonly durationMs: number;\n}\n\nexport type FetchOutbound = (\n url: string,\n opts: FetchOutboundOptions,\n) => Promise<FetchOutboundResult>;\n\n// Audit-log entry for one outbound HTTP fetch. Field names are snake_case so\n// the record can land directly on `VerifyReport.http_calls[]` (which IS the\n// wire shape) without a key-renaming pass.\nexport interface HttpCallRecord {\n readonly url: string;\n readonly method: HttpMethod;\n readonly status: number;\n readonly bytes: number;\n readonly duration_ms: number;\n readonly purpose: HttpPurpose;\n}\n\nexport interface RetryConfig {\n readonly timeoutMs?: number;\n readonly retries?: number;\n readonly retryableStatuses?: ReadonlyArray<number>;\n}\n\nexport interface WrapFetchOutboundConfig extends RetryConfig {\n readonly denyHosts?: ReadonlyArray<string>;\n}\n\nexport class DenyHostError extends Error {\n readonly code = 'SERVICE_INDEPENDENCE_VIOLATION';\n readonly host: string;\n readonly url: string;\n constructor(host: string, url: string) {\n super(`SERVICE_INDEPENDENCE_VIOLATION: host \"${host}\" is in denyHosts (url=${url})`);\n this.name = 'DenyHostError';\n this.host = host;\n this.url = url;\n }\n}\n\nexport class UnsupportedProtocolError extends Error {\n readonly code = 'UNSUPPORTED_PROTOCOL';\n readonly protocol: string;\n readonly url: string;\n constructor(protocol: string, url: string) {\n super(`UNSUPPORTED_PROTOCOL: \"${protocol}\" not in {http:, https:} (url=${url})`);\n this.name = 'UnsupportedProtocolError';\n this.protocol = protocol;\n this.url = url;\n }\n}\n\nexport class UnsupportedMethodError extends Error {\n readonly code = 'UNSUPPORTED_METHOD';\n readonly method: string;\n readonly url: string;\n constructor(method: string, url: string) {\n super(`UNSUPPORTED_METHOD: \"${method}\" not in {GET, POST} (url=${url})`);\n this.name = 'UnsupportedMethodError';\n this.method = method;\n this.url = url;\n }\n}\n\nexport class BodyTooLargeError extends Error {\n readonly code = 'OUTBOUND_BODY_TOO_LARGE';\n readonly url: string;\n readonly limitBytes: number;\n constructor(url: string, limitBytes: number) {\n super(`OUTBOUND_BODY_TOO_LARGE: response exceeded ${limitBytes} bytes (url=${url})`);\n this.name = 'BodyTooLargeError';\n this.url = url;\n this.limitBytes = limitBytes;\n }\n}\n\nexport class OutboundExhaustedError extends Error {\n readonly code = 'OUTBOUND_EXHAUSTED';\n readonly url: string;\n readonly attempts: number;\n readonly lastStatus: number | undefined;\n readonly lastError: Error | undefined;\n constructor(args: {\n url: string;\n attempts: number;\n lastStatus?: number | undefined;\n lastError?: Error | undefined;\n }) {\n super(\n `OUTBOUND_EXHAUSTED: ${args.attempts} attempts exhausted (url=${args.url}, lastStatus=${args.lastStatus ?? '-'})`,\n );\n this.name = 'OutboundExhaustedError';\n this.url = args.url;\n this.attempts = args.attempts;\n this.lastStatus = args.lastStatus;\n this.lastError = args.lastError;\n }\n}\n\nexport const DEFAULT_TIMEOUT_MS = 10_000;\n// Default response-body cap for the verifier's gateway fetches. 64 MiB sits\n// well above any single sealed-PoE ciphertext or merkle-leaf payload a verifier\n// would realistically recompute a hash over, while bounding the memory a hostile\n// gateway can force the verifier to allocate for one request. Callers that\n// legitimately handle larger content raise it per-call via `opts.maxBytes`.\nexport const DEFAULT_OUTBOUND_MAX_BYTES = 64 * 1024 * 1024;\nexport const DEFAULT_RETRYABLE_STATUSES: ReadonlyArray<number> = [502, 503, 504];\nconst BACKOFF_BASE_MS: ReadonlyArray<number> = [1000, 2000, 4000];\nconst JITTER_RATIO = 0.25;\n\nfunction canonicaliseHost(host: string): string {\n return host.replace(/^\\[/, '').replace(/\\]$/, '').replace(/\\.$/, '').toLowerCase();\n}\n\nexport function matchesDenyList(host: string, denyHosts: ReadonlyArray<string>): boolean {\n const h = canonicaliseHost(host);\n for (const raw of denyHosts) {\n const pattern = raw.replace(/\\.$/, '').toLowerCase();\n if (pattern.startsWith('*.')) {\n const suffix = pattern.slice(2);\n if (h.endsWith('.' + suffix)) return true;\n continue;\n }\n if (h === pattern) return true;\n if (pattern === 'localhost') {\n if (h === '::1' || h === '0.0.0.0' || h === '169.254.169.254') return true;\n }\n if (pattern === '127.0.0.1') {\n if (/^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n }\n }\n return false;\n}\n\nfunction parseProtocol(url: string): string | null {\n try {\n return new URL(url).protocol;\n } catch {\n return null;\n }\n}\n\nfunction isAllowedMethod(method: string): method is HttpMethod {\n return method === 'GET' || method === 'POST';\n}\n\nfunction backoffJitteredMs(attemptIndex: number): number {\n const idx = Math.min(attemptIndex, BACKOFF_BASE_MS.length - 1);\n const base = BACKOFF_BASE_MS[idx] ?? BACKOFF_BASE_MS[BACKOFF_BASE_MS.length - 1]!;\n const jitter = 1 + (Math.random() - 0.5) * 2 * JITTER_RATIO;\n return base * jitter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport const defaultFetchOutbound: FetchOutbound = async (url, opts) => {\n const t0 = Date.now();\n const maxBytes = opts.maxBytes ?? DEFAULT_OUTBOUND_MAX_BYTES;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);\n const init: RequestInit = {\n method: opts.method,\n signal: controller.signal,\n };\n if (opts.headers) init.headers = { ...opts.headers };\n if (opts.body !== undefined) init.body = opts.body;\n try {\n // allow-raw-fetch: canonical defaultFetchOutbound — single egress point\n const res = await fetch(url, init);\n\n // Fast path: a truthful Content-Length over the cap lets us bail before\n // reading a single body byte. A lying/absent header is still caught by the\n // streaming counter below — the header is an optimisation, not the guard.\n const declared = res.headers.get('content-length');\n if (declared !== null) {\n const declaredLen = Number(declared);\n if (Number.isFinite(declaredLen) && declaredLen > maxBytes) {\n controller.abort();\n throw new BodyTooLargeError(url, maxBytes);\n }\n }\n\n const bytes = await readBodyCapped(res, url, maxBytes, controller);\n return { status: res.status, bytes, durationMs: Date.now() - t0 };\n } finally {\n clearTimeout(timeout);\n }\n};\n\n// Stream the response body, aborting the underlying request the instant the\n// running byte count exceeds `maxBytes`. This is the actual OOM guard: a\n// gateway that withholds or lies about Content-Length still cannot make us\n// buffer more than the cap, because we stop reading and tear the socket down.\nasync function readBodyCapped(\n res: Response,\n url: string,\n maxBytes: number,\n controller: AbortController,\n): Promise<Uint8Array> {\n const body = res.body;\n if (body === null) {\n // No stream (e.g. a 204, or a fetch polyfill that buffered eagerly). Fall\n // back to arrayBuffer but still enforce the cap on the materialised length.\n const buf = await res.arrayBuffer();\n if (buf.byteLength > maxBytes) {\n throw new BodyTooLargeError(url, maxBytes);\n }\n return new Uint8Array(buf);\n }\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value === undefined) continue;\n total += value.byteLength;\n if (total > maxBytes) {\n controller.abort();\n throw new BodyTooLargeError(url, maxBytes);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n}\n\nexport function wrapFetchOutbound(\n inner: FetchOutbound,\n audit: HttpCallRecord[],\n config: WrapFetchOutboundConfig | ReadonlyArray<string> | undefined = undefined,\n): FetchOutbound {\n // Accept either a denyHosts array (positional) or the full config object.\n const normConfig: WrapFetchOutboundConfig =\n config === undefined\n ? {}\n : Array.isArray(config)\n ? { denyHosts: config as ReadonlyArray<string> }\n : (config as WrapFetchOutboundConfig);\n\n const denyHosts = normConfig.denyHosts ?? [];\n // Default retries=0 (single attempt). Callers opt in via explicit `retries`;\n // the top-level `fetchOutbound` entrypoint forwards caller config.\n const retries = normConfig.retries ?? 0;\n const retryableStatuses = normConfig.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES;\n\n return async (url, opts) => {\n // The `webhook` purpose has bespoke requirements (DNS pinning,\n // per-hop redirect re-checking, body-size cap) that the generic\n // wrapper cannot satisfy. Force callers to use `fetchWebhook`\n // instead of silently accepting the call here.\n if (opts.purpose === 'webhook') {\n audit.push({\n url,\n method: 'GET',\n status: 0,\n bytes: 0,\n duration_ms: 0,\n purpose: opts.purpose,\n });\n throw new Error(\n `webhook purpose must be sent via fetchWebhook, not fetchOutbound (url=${url})`,\n );\n }\n\n // Protocol allowlist.\n const protocol = parseProtocol(url);\n if (protocol !== 'http:' && protocol !== 'https:') {\n audit.push({\n url,\n method: 'GET',\n status: 0,\n bytes: 0,\n duration_ms: 0,\n purpose: opts.purpose,\n });\n throw new UnsupportedProtocolError(protocol ?? '', url);\n }\n\n // Method allowlist.\n if (!isAllowedMethod(opts.method)) {\n audit.push({\n url,\n method: 'GET',\n status: 0,\n bytes: 0,\n duration_ms: 0,\n purpose: opts.purpose,\n });\n throw new UnsupportedMethodError(opts.method, url);\n }\n\n // Deny-list short-circuit.\n if (denyHosts.length > 0) {\n const host = new URL(url).hostname;\n if (matchesDenyList(host, denyHosts)) {\n audit.push({\n url,\n method: opts.method,\n status: 0,\n bytes: 0,\n duration_ms: 0,\n purpose: opts.purpose,\n });\n throw new DenyHostError(canonicaliseHost(host), url);\n }\n }\n\n // Retry loop. retries=0 → single attempt, return-or-rethrow original.\n let lastStatus: number | undefined;\n let lastError: Error | undefined;\n const totalAttempts = retries + 1;\n for (let attempt = 1; attempt <= totalAttempts; attempt++) {\n const t0 = Date.now();\n try {\n const result = await inner(url, opts);\n audit.push({\n url,\n method: opts.method,\n status: result.status,\n bytes: result.bytes.byteLength,\n duration_ms: result.durationMs,\n purpose: opts.purpose,\n });\n if (retryableStatuses.includes(result.status) && retries > 0) {\n lastStatus = result.status;\n if (attempt < totalAttempts) {\n await sleep(backoffJitteredMs(attempt - 1));\n continue;\n }\n break;\n }\n return result;\n } catch (e) {\n const durationMs = Date.now() - t0;\n if (\n e instanceof DenyHostError ||\n e instanceof UnsupportedProtocolError ||\n e instanceof UnsupportedMethodError\n ) {\n audit.push({\n url,\n method: opts.method,\n status: 0,\n bytes: 0,\n duration_ms: durationMs,\n purpose: opts.purpose,\n });\n throw e;\n }\n audit.push({\n url,\n method: opts.method,\n status: 0,\n bytes: 0,\n duration_ms: durationMs,\n purpose: opts.purpose,\n });\n lastError = e as Error;\n if (attempt < totalAttempts) {\n await sleep(backoffJitteredMs(attempt - 1));\n continue;\n }\n break;\n }\n }\n // Single-attempt mode re-throws the original verbatim so callers can match\n // by identity; retry mode wraps the terminal failure in OutboundExhaustedError.\n if (retries === 0 && lastError !== undefined) {\n throw lastError;\n }\n throw new OutboundExhaustedError({ url, attempts: totalAttempts, lastStatus, lastError });\n };\n}\n\nexport async function fetchOutbound(\n url: string,\n opts: FetchOutboundOptions,\n audit: HttpCallRecord[],\n config: WrapFetchOutboundConfig = {},\n): Promise<FetchOutboundResult> {\n const wrapped = wrapFetchOutbound(defaultFetchOutbound, audit, config);\n return wrapped(url, opts);\n}\n","// Verifier-side URI fetching plus the canonical `fetchOutbound` re-exports.\n// Two concerns colocated:\n//\n// * `fetchItemCiphertext` — given a chunked `uris[]` from a record item or\n// merkle entry, reconstruct the URI, dispatch to the appropriate gateway\n// chain (ar:// → Arweave HTTPS rotation; ipfs:// → caller-supplied IPFS\n// rotation), and return the raw bytes. Per-attempt diagnostics surface\n// as `URI_FETCH_FAILED` warnings in the caller's sink; the chain-exhausted\n// terminal state throws `CONTENT_UNAVAILABLE` so the caller emits the\n// terminal verdict.\n//\n// * Canonical re-exports of `defaultFetchOutbound`, `wrapFetchOutbound`, et\n// al. from `../fetch/fetch-outbound.js`.\n\nimport type { FetchOutbound, VerifyUriCheck } from './types';\n\nexport {\n BodyTooLargeError,\n DEFAULT_OUTBOUND_MAX_BYTES,\n defaultFetchOutbound,\n DENY_HOSTS_DEFAULT,\n DenyHostError,\n fetchOutbound,\n OutboundExhaustedError,\n UnsupportedMethodError,\n UnsupportedProtocolError,\n wrapFetchOutbound,\n} from '../fetch/fetch-outbound';\nexport type { RetryConfig, WrapFetchOutboundConfig } from '../fetch/fetch-outbound';\n\n// Default Arweave gateway rotation.\nconst ARWEAVE_DEFAULTS: ReadonlyArray<string> = [\n 'https://arweave.net',\n 'https://ar-io.net',\n 'https://g8way.io',\n];\n\nconst ARWEAVE_TXID_RE = /^[A-Za-z0-9_-]{43}$/;\n\nexport interface FetchItemCiphertextArgs {\n // Reconstructed-from-chunks URI list (each entry is itself a chunk array).\n readonly uris: ReadonlyArray<ReadonlyArray<string>>;\n readonly arweaveGateways?: ReadonlyArray<string> | undefined;\n readonly ipfsGateways?: ReadonlyArray<string> | undefined;\n readonly fetchFn: FetchOutbound;\n // Caller-supplied sink for per-attempt URI diagnostics. Each gateway failure\n // appends a `{ok: false, reason}` entry; the successful gateway appends\n // `{ok: true}`.\n readonly uriChecksOut: VerifyUriCheck[];\n // Caller path: `items[i]` → `itemIndex`; `merkle[i]` → reuse the field for\n // mapping (the report's `uriChecks[]` is item-indexed for v1).\n readonly itemIndex: number;\n}\n\n// Returns the first gateway response whose status is 200. Individual gateway\n// failures are warnings; only chain-exhaustion raises the terminal\n// `CONTENT_UNAVAILABLE`. The closed v1 scheme set is `{ar://, ipfs://}`; any\n// other scheme has already been rejected by the structural validator as\n// `INVALID_URI` and is rejected here too as defence in depth\n// (`URI_TARGET_FORBIDDEN`).\nexport async function fetchItemCiphertext(args: FetchItemCiphertextArgs): Promise<Uint8Array> {\n const reconstructed = args.uris.map((chunks) => chunks.join(''));\n const candidate = reconstructed.find((u) => /^(ar|ipfs):\\/\\//.test(u));\n if (candidate === undefined) {\n // No in-set URI present — defence-in-depth rejection.\n for (const u of reconstructed) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: u,\n ok: false,\n reason: 'URI_TARGET_FORBIDDEN',\n });\n }\n throw new Error('URI_TARGET_FORBIDDEN');\n }\n\n if (candidate.startsWith('ar://')) {\n const txid = candidate.slice(5);\n if (!ARWEAVE_TXID_RE.test(txid)) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: 'INVALID_URI',\n });\n throw new Error('CONTENT_UNAVAILABLE');\n }\n const gateways =\n args.arweaveGateways && args.arweaveGateways.length > 0\n ? args.arweaveGateways\n : ARWEAVE_DEFAULTS;\n for (const gw of gateways) {\n try {\n const res = await args.fetchFn(`${gw}/${txid}`, { method: 'GET', purpose: 'arweave' });\n if (res.status === 200) {\n args.uriChecksOut.push({ item_index: args.itemIndex, uri: candidate, ok: true });\n return res.bytes;\n }\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: `URI_FETCH_FAILED:${gw}:${res.status}`,\n });\n } catch (e) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: `URI_FETCH_FAILED:${gw}:${e instanceof Error ? e.message : String(e)}`,\n });\n }\n }\n throw new Error('CONTENT_UNAVAILABLE');\n }\n\n // ipfs:// — caller MUST configure an IPFS gateway chain. No baked-in\n // defaults: IPFS gateways are not the producer's storage provider, and a\n // silent fallback would couple the verifier to an off-record gateway.\n const cidPart = candidate.slice('ipfs://'.length);\n const ipfsCid = cidPart.split('/')[0] ?? cidPart;\n const ipfsGateways = args.ipfsGateways;\n if (ipfsGateways === undefined || ipfsGateways.length === 0) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: 'CONTENT_UNAVAILABLE:no_ipfs_gateway',\n });\n throw new Error('CONTENT_UNAVAILABLE');\n }\n for (const gw of ipfsGateways) {\n try {\n const sep = gw.endsWith('/') ? '' : '/';\n const url = `${gw}${sep}ipfs/${ipfsCid}`;\n const res = await args.fetchFn(url, { method: 'GET', purpose: 'ipfs' });\n if (res.status === 200) {\n args.uriChecksOut.push({ item_index: args.itemIndex, uri: candidate, ok: true });\n return res.bytes;\n }\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: `URI_FETCH_FAILED:${gw}:${res.status}`,\n });\n } catch (e) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: `URI_FETCH_FAILED:${gw}:${e instanceof Error ? e.message : String(e)}`,\n });\n }\n }\n throw new Error('CONTENT_UNAVAILABLE');\n}\n","// Sealed-PoE decryption.\n//\n// Two mutually-exclusive on-wire paths:\n// * `enc.slots[]` (sealed-recipient, X25519 ECIES) — invokes\n// `eciesSealedPoeUnwrap` from `@cardanowall/crypto-core/sealed-poe`.\n// * `enc.passphrase` (Argon2id-derived CEK) — derives the CEK and runs\n// the AEAD primitive directly (empty AAD on the passphrase path).\n//\n// After successful unwrap (either path), the verifier recomputes every\n// content-hash entry in `item.hashes` and compares to the recovered plaintext.\n// Mismatch surfaces as `URI_INTEGRITY_MISMATCH`.\n\nimport { argon2idV13 } from '@cardanowall/crypto-core/kdf';\nimport { xchacha20Poly1305Decrypt, AeadVerificationError } from '@cardanowall/crypto-core/aead';\nimport { blake2b256, sha256 } from '@cardanowall/crypto-core/hash';\nimport {\n eciesSealedPoeUnwrap,\n sealedEnvelopeFromParsed,\n} from '@cardanowall/crypto-core/sealed-poe';\nimport { compareCt } from '@cardanowall/crypto-core/util';\nimport type { ItemEntry, PoeRecord } from '@cardanowall/poe-standard';\n\nimport { fetchItemCiphertext } from './fetch';\nimport type {\n DecryptionVerdict,\n FetchOutbound,\n HttpCallRecord,\n VerifyItemDecryption,\n VerifyTxInput,\n VerifyUriCheck,\n} from './types';\n\n// The v1 passphrase KDF registry has a single member.\nconst PASSPHRASE_KDF_ARGON2ID = 'argon2id' as const;\n\n// Content-AEAD AAD is an empty bstr on the passphrase path.\nconst EMPTY_AAD = new Uint8Array(0);\n\nexport interface TryDecryptionsArgs {\n readonly record: PoeRecord;\n readonly input: VerifyTxInput;\n readonly fetchFn: FetchOutbound;\n readonly httpCalls: HttpCallRecord[];\n readonly uriChecksOut: VerifyUriCheck[];\n // When `false`, the verifier is running offline: it MUST NOT fetch a sealed\n // item's on-record `uris[]` ciphertext. Decryption then succeeds only for\n // items whose ciphertext the caller supplied out-of-band (`ciphertextBytes`);\n // others surface as `ciphertext-unavailable` with no outbound egress.\n readonly allowUriFetch: boolean;\n}\n\nexport interface TryDecryptionsResult {\n readonly results: VerifyItemDecryption[];\n}\n\nexport async function tryDecryptions(args: TryDecryptionsArgs): Promise<TryDecryptionsResult> {\n const { record, input } = args;\n const items = (record.items ?? []) as ItemEntry[];\n const out: VerifyItemDecryption[] = [];\n const reqs = input.decryption ?? [];\n\n for (const req of reqs) {\n const idx = req.itemIndex;\n if (!Number.isInteger(idx) || idx < 0 || idx >= items.length) {\n out.push({\n item_index: idx,\n verdict: 'no-enc-envelope',\n reason: 'itemIndex out of range',\n });\n continue;\n }\n const item = items[idx]!;\n const enc = item.enc as unknown;\n if (enc === undefined || enc === null || typeof enc !== 'object') {\n out.push({ item_index: idx, verdict: 'no-enc-envelope' });\n continue;\n }\n const encShape = enc as {\n readonly slots?: unknown;\n readonly passphrase?: unknown;\n };\n const hasSlots = Array.isArray(encShape.slots);\n const hasPassphrase = encShape.passphrase !== undefined && encShape.passphrase !== null;\n const reqHasSecret = 'recipientSecretKey' in req;\n const reqHasPassphrase = 'passphrase' in req;\n if (hasSlots && !reqHasSecret) {\n out.push({\n item_index: idx,\n verdict: 'wrong-input-shape',\n reason: 'WRONG_DECRYPTION_INPUT_SHAPE',\n });\n continue;\n }\n if (hasPassphrase && !reqHasPassphrase) {\n out.push({\n item_index: idx,\n verdict: 'wrong-input-shape',\n reason: 'WRONG_DECRYPTION_INPUT_SHAPE',\n });\n continue;\n }\n\n // Ciphertext acquisition: out-of-band bytes first, then (when fetching is\n // allowed) on-record `item.uris[]`, then `CIPHERTEXT_UNAVAILABLE`. Offline\n // mode (`allowUriFetch === false`) never reaches the network branch.\n const oobBytes = input.ciphertextBytes?.[idx];\n let ciphertext: Uint8Array | null;\n if (oobBytes !== undefined) {\n ciphertext = oobBytes;\n } else if (args.allowUriFetch && Array.isArray(item.uris) && item.uris.length > 0) {\n try {\n ciphertext = await fetchItemCiphertext({\n uris: item.uris as ReadonlyArray<ReadonlyArray<string>>,\n arweaveGateways: input.arweaveGatewayChain,\n ipfsGateways: input.ipfsGatewayChain,\n fetchFn: args.fetchFn,\n uriChecksOut: args.uriChecksOut,\n itemIndex: idx,\n });\n } catch (e) {\n const code = e instanceof Error ? e.message : 'CONTENT_UNAVAILABLE';\n const verdict: DecryptionVerdict =\n code === 'URI_TARGET_FORBIDDEN' ? 'ciphertext-unavailable' : 'content-unavailable';\n out.push({ item_index: idx, verdict, reason: code });\n continue;\n }\n } else {\n out.push({\n item_index: idx,\n verdict: 'ciphertext-unavailable',\n reason: 'CIPHERTEXT_UNAVAILABLE',\n });\n continue;\n }\n if (ciphertext === null) {\n out.push({\n item_index: idx,\n verdict: 'ciphertext-unavailable',\n reason: 'CIPHERTEXT_UNAVAILABLE',\n });\n continue;\n }\n\n let plaintext: Uint8Array | null = null;\n let failure: { verdict: DecryptionVerdict; reason: string } | null = null;\n if (reqHasSecret) {\n // Build the discriminated SealedEnvelope from the on-wire `enc` block,\n // dispatching on `enc.kem` (classical `{epk, wrap}` vs hybrid\n // `{kem_ct, wrap}`). A null result means the envelope isn't a sealed\n // recipient envelope we can unwrap — surface it as wrong-input-shape.\n const envelope = sealedEnvelopeFromParsed(\n enc as Parameters<typeof sealedEnvelopeFromParsed>[0],\n );\n if (envelope === null) {\n out.push({\n item_index: idx,\n verdict: 'wrong-input-shape',\n reason: 'WRONG_DECRYPTION_INPUT_SHAPE',\n });\n continue;\n }\n // ECIES sealed-PoE unwrap. The single-priv standalone-verifier form takes\n // the one secret matching the envelope's KEM (X25519 priv for classical,\n // X-Wing secret seed for hybrid); the per-slot loop inside dispatches on\n // `envelope.kem`. The helper returns a discriminated result — never throws\n // on auth failure.\n const unwrap = eciesSealedPoeUnwrap({\n envelope,\n ciphertext,\n recipientSecretKey: (req as { recipientSecretKey: Uint8Array }).recipientSecretKey,\n });\n if (unwrap.matched) {\n plaintext = unwrap.plaintext;\n } else {\n const map: Record<string, { verdict: DecryptionVerdict; reason: string }> = {\n WRONG_RECIPIENT_KEY: { verdict: 'wrong-key', reason: 'WRONG_RECIPIENT_KEY' },\n TAMPERED_HEADER: { verdict: 'tampered-header', reason: 'TAMPERED_HEADER' },\n TAMPERED_CIPHERTEXT: { verdict: 'tampered-ciphertext', reason: 'TAMPERED_CIPHERTEXT' },\n };\n failure = map[unwrap.reason] ?? {\n verdict: 'tampered-ciphertext',\n reason: 'TAMPERED_CIPHERTEXT',\n };\n }\n } else {\n try {\n plaintext = await decryptPassphrase({\n enc: enc as PassphraseEncEnvelope,\n ciphertext,\n passphrase: (req as { passphrase: string }).passphrase,\n });\n } catch (e) {\n if (e instanceof AeadVerificationError) {\n failure = { verdict: 'tampered-ciphertext', reason: 'TAMPERED_CIPHERTEXT' };\n } else if (e instanceof Error && e.message.startsWith('KDF_')) {\n failure = { verdict: 'kdf-failed', reason: e.message };\n } else {\n failure = {\n verdict: 'tampered-ciphertext',\n reason: e instanceof Error ? e.message : 'TAMPERED_CIPHERTEXT',\n };\n }\n }\n }\n\n if (failure !== null) {\n out.push({ item_index: idx, verdict: failure.verdict, reason: failure.reason });\n continue;\n }\n if (plaintext === null) {\n // Defensive — failure path should already have returned above.\n out.push({ item_index: idx, verdict: 'tampered-ciphertext', reason: 'TAMPERED_CIPHERTEXT' });\n continue;\n }\n\n // Post-unwrap plaintext-hash recompute: re-hash the recovered plaintext\n // under every content-hash entry the item carries and compare. Every\n // `enc`-bearing item carries at least one content-hash entry (the\n // structural validator enforces ENC_REQUIRES_CONTENT_HASH), so this is a\n // concrete boolean on successful decryption.\n const plaintextHashOk = recomputeHashes(item, plaintext);\n out.push({ item_index: idx, verdict: 'decrypted', plaintext_hash_ok: plaintextHashOk });\n }\n\n return { results: out };\n}\n\ninterface PassphraseEncEnvelope {\n readonly scheme: number;\n readonly aead: string;\n readonly nonce: Uint8Array;\n readonly passphrase: {\n readonly alg: string;\n readonly salt: Uint8Array;\n readonly params: { readonly m: number; readonly t: number; readonly p: number };\n };\n}\n\nasync function decryptPassphrase(args: {\n enc: PassphraseEncEnvelope;\n ciphertext: Uint8Array;\n passphrase: string;\n}): Promise<Uint8Array> {\n const { enc, ciphertext, passphrase } = args;\n if (enc.passphrase.alg !== PASSPHRASE_KDF_ARGON2ID) {\n throw new Error(`KDF_DERIVATION_FAILED: unsupported passphrase alg ${enc.passphrase.alg}`);\n }\n // Passphrase normalisation: NFKC → collapse whitespace → trim → UTF-8. Must\n // match the producer's normalisation exactly or the derived CEK won't match.\n const normalised = passphrase.normalize('NFKC').replace(/\\s+/g, ' ').trim();\n const password = new TextEncoder().encode(normalised);\n let cek: Uint8Array;\n try {\n cek = await argon2idV13({\n password,\n salt: enc.passphrase.salt,\n memSizeKB: enc.passphrase.params.m,\n iterations: enc.passphrase.params.t,\n parallelism: enc.passphrase.params.p,\n outBytes: 32,\n });\n } catch (cause) {\n const reason = cause instanceof Error ? cause.message : String(cause);\n throw new Error(`KDF_DERIVATION_FAILED: ${reason}`, { cause });\n }\n if (enc.aead !== 'xchacha20-poly1305') {\n throw new Error(`KDF_DERIVATION_FAILED: unsupported aead ${enc.aead}`);\n }\n return xchacha20Poly1305Decrypt({\n key: cek,\n nonce: enc.nonce,\n aad: EMPTY_AAD,\n ciphertext,\n });\n}\n\nfunction recomputeHashes(item: ItemEntry, plaintext: Uint8Array): boolean {\n // `item.hashes` is a text-keyed map of algorithm id → expected digest;\n // cbor2 surfaces it as a plain JS object. The recovered plaintext is\n // \"hash-ok\" only when there is at least one entry AND every entry names a\n // hash we can recompute AND its digest matches. An empty map, or any entry\n // whose alg we don't recognise, is NOT silently treated as a pass: returning\n // `true` there would vacuously certify ciphertext whose integrity we never\n // actually checked. (Mirrors the CLI's `recomputeItemHashes`, which returns\n // `UNSUPPORTED_HASH_ALG` on an unknown alg.)\n const entries = Object.entries(item.hashes);\n if (entries.length === 0) return false;\n for (const [alg, digest] of entries) {\n if (alg === 'sha2-256') {\n if (!compareCt(sha256(plaintext), digest)) return false;\n } else if (alg === 'blake2b-256') {\n if (!compareCt(blake2b256(plaintext), digest)) return false;\n } else {\n // Unknown/unsupported hash alg — cannot certify integrity.\n return false;\n }\n }\n return true;\n}\n","// Canonical-CBOR codec for the off-chain Merkle leaves-list artefact.\n// The on-chain `merkle[]` field binds to this file via `uris[]` / `leaf_count`;\n// the file itself carries the full leaf set. Canonical CBOR is RFC 8949 §4.2.1.\n//\n// CDDL:\n//\n// leaves-list = {\n// \"format\": \"cardano-poe-merkle-leaves-v1\",\n// \"tree_alg\": \"rfc9162-sha256\",\n// \"root\": bytes .size 32,\n// \"leaves\": [ + bytes .size 32 ],\n// \"leaf_count\": uint,\n// ? \"leaf_alg\": tstr,\n// }\n//\n// Canonical ordering is bytewise-lexicographic on encoded map keys (RFC 8949\n// §4.2.1) so the wire-key order is fixed by `cde:true` regardless of insertion\n// order: root (4B) < format (6B) < leaves (6B) < leaf_alg (8B) < tree_alg (8B)\n// < leaf_count (10B).\n\nimport { decodeCanonicalCbor, encodeCanonicalCbor } from '../cbor/canonical';\nimport { compareCt } from '../util/compare-ct';\nimport { merkleSha2256Root } from '../hash/merkle-sha2-256';\n\nexport const LEAVES_LIST_FORMAT_V1 = 'cardano-poe-merkle-leaves-v1' as const;\nconst TREE_ALG_RFC9162 = 'rfc9162-sha256' as const;\nconst DIGEST_LENGTH = 32;\nconst REGISTERED_FORMATS = new Set<string>([LEAVES_LIST_FORMAT_V1]);\n\nexport type MerkleLeavesListErrorCode =\n | 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED'\n | 'SCHEMA_MERKLE_LEAVES_MALFORMED'\n | 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH'\n | 'MERKLE_ROOT_MISMATCH';\n\nexport class MerkleLeavesListError extends Error {\n readonly code: MerkleLeavesListErrorCode;\n constructor(code: MerkleLeavesListErrorCode, message?: string) {\n super(message ? `${code}: ${message}` : code);\n this.code = code;\n this.name = 'MerkleLeavesListError';\n }\n}\n\nexport interface EncodeLeavesListArgs {\n readonly leaves: ReadonlyArray<Uint8Array>;\n readonly root: Uint8Array;\n readonly leafAlg?: string;\n}\n\nexport interface DecodedLeavesList {\n readonly format: typeof LEAVES_LIST_FORMAT_V1;\n readonly treeAlg: typeof TREE_ALG_RFC9162;\n readonly root: Uint8Array;\n readonly leaves: Uint8Array[];\n readonly leafCount: number;\n readonly leafAlg?: string;\n}\n\nexport function encodeLeavesList(args: EncodeLeavesListArgs): Uint8Array {\n if (!(args.root instanceof Uint8Array) || args.root.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `root must be a Uint8Array(${DIGEST_LENGTH})`,\n );\n }\n if (args.leaves.length < 1) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaves array must be non-empty',\n );\n }\n const leavesCopy: Uint8Array[] = [];\n for (let i = 0; i < args.leaves.length; i++) {\n const leaf = args.leaves[i];\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `leaves[${i}] must be a Uint8Array(${DIGEST_LENGTH})`,\n );\n }\n leavesCopy.push(leaf);\n }\n if (args.leafAlg !== undefined && typeof args.leafAlg !== 'string') {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_alg must be a string when present',\n );\n }\n const map: Record<string, unknown> = {\n format: LEAVES_LIST_FORMAT_V1,\n tree_alg: TREE_ALG_RFC9162,\n root: args.root,\n leaves: leavesCopy,\n leaf_count: leavesCopy.length,\n };\n if (args.leafAlg !== undefined) {\n map['leaf_alg'] = args.leafAlg;\n }\n return encodeCanonicalCbor(map as never);\n}\n\nexport function decodeLeavesList(bytes: Uint8Array): DecodedLeavesList {\n const decoded = decodeCanonicalCbor(bytes);\n if (typeof decoded !== 'object' || decoded === null || Array.isArray(decoded)) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaves-list MUST be a CBOR map',\n );\n }\n const m = decoded as Record<string, unknown>;\n\n const format = m['format'];\n if (typeof format !== 'string') {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'format must be a text string',\n );\n }\n if (!REGISTERED_FORMATS.has(format)) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED',\n `format '${format}' is not in the registered set`,\n );\n }\n\n const treeAlg = m['tree_alg'];\n if (treeAlg !== TREE_ALG_RFC9162) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `tree_alg '${String(treeAlg)}' is not '${TREE_ALG_RFC9162}'`,\n );\n }\n\n const root = m['root'];\n if (!(root instanceof Uint8Array) || root.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `root must be a ${DIGEST_LENGTH}-byte byte string`,\n );\n }\n\n const leavesRaw = m['leaves'];\n if (!Array.isArray(leavesRaw) || leavesRaw.length < 1) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaves must be a non-empty array',\n );\n }\n const leaves: Uint8Array[] = [];\n for (let i = 0; i < leavesRaw.length; i++) {\n const leaf = leavesRaw[i];\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `leaves[${i}] must be a ${DIGEST_LENGTH}-byte byte string`,\n );\n }\n leaves.push(leaf);\n }\n\n const leafCountRaw = m['leaf_count'];\n let leafCount: number;\n if (typeof leafCountRaw === 'number' && Number.isInteger(leafCountRaw) && leafCountRaw >= 0) {\n leafCount = leafCountRaw;\n } else if (typeof leafCountRaw === 'bigint' && leafCountRaw >= 0n) {\n if (leafCountRaw > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_count exceeds Number.MAX_SAFE_INTEGER',\n );\n }\n leafCount = Number(leafCountRaw);\n } else {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_count must be a non-negative CBOR uint',\n );\n }\n if (leaves.length !== leafCount) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n `leaves.length (${leaves.length}) != leaf_count (${leafCount})`,\n );\n }\n\n let leafAlg: string | undefined;\n if (m['leaf_alg'] !== undefined) {\n if (typeof m['leaf_alg'] !== 'string') {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_alg must be a text string when present',\n );\n }\n leafAlg = m['leaf_alg'];\n }\n\n const recomputed = merkleSha2256Root(leaves);\n if (!compareCt(recomputed, root)) {\n throw new MerkleLeavesListError(\n 'MERKLE_ROOT_MISMATCH',\n 'leaves recompute does not match declared root',\n );\n }\n\n const out: DecodedLeavesList = {\n format: LEAVES_LIST_FORMAT_V1,\n treeAlg: TREE_ALG_RFC9162,\n root,\n leaves,\n leafCount,\n ...(leafAlg !== undefined ? { leafAlg } : {}),\n };\n return out;\n}\n","// Merkle list-commitment verification.\n//\n// For each `record.merkle[i]` the verifier:\n// 1. Acquires the leaves-list document (caller-supplied or fetched via the\n// first ar://-or-ipfs:// URI in `merkle[i].uris[]`).\n// 2. Decodes the normative CBOR leaves-list wire form via crypto-core's\n// `decodeLeavesList` (which also recomputes the canonical RFC 9162 root\n// defence-in-depth and surfaces `MERKLE_ROOT_MISMATCH` /\n// `SCHEMA_MERKLE_LEAF_COUNT_MISMATCH`).\n// 3. Compares the on-record `merkle[i].root` byte-exact to the recomputed\n// root via `compareCt`.\n//\n// Per-attempt URI failures are warnings (`URI_FETCH_FAILED`); the per-commit\n// verdict on chain-exhaustion is `MERKLE_LEAVES_UNAVAILABLE` — a warning, NOT\n// escalated to `'failed'`, because the on-chain root alone is structurally\n// valid.\n\nimport { merkleSha2256Root } from '@cardanowall/crypto-core/hash';\nimport { decodeLeavesList, MerkleLeavesListError } from '@cardanowall/crypto-core/merkle';\nimport { compareCt } from '@cardanowall/crypto-core/util';\nimport type { MerkleCommit, PoeRecord } from '@cardanowall/poe-standard';\n\nimport { fetchItemCiphertext } from './fetch';\nimport type { FetchOutbound, VerifyMerkleCheck, VerifyTxInput, VerifyUriCheck } from './types';\n\nexport interface VerifyMerkleArgs {\n readonly record: PoeRecord;\n readonly input: VerifyTxInput;\n readonly fetchFn: FetchOutbound;\n readonly uriChecksOut: VerifyUriCheck[];\n}\n\nexport interface VerifyMerkleResult {\n readonly checks: VerifyMerkleCheck[];\n}\n\nexport async function verifyMerkleCommitments(args: VerifyMerkleArgs): Promise<VerifyMerkleResult> {\n const merkleArr = (args.record.merkle ?? []) as MerkleCommit[];\n const out: VerifyMerkleCheck[] = [];\n for (let i = 0; i < merkleArr.length; i++) {\n out.push(await verifyOneCommit(i, merkleArr[i]!, args));\n }\n return { checks: out };\n}\n\nasync function verifyOneCommit(\n index: number,\n commit: MerkleCommit,\n args: VerifyMerkleArgs,\n): Promise<VerifyMerkleCheck> {\n // v1 registers exactly one Merkle commitment algorithm. The structural\n // validator already rejects unknown algs; this is defence-in-depth.\n if (commit.alg !== 'rfc9162-sha256') {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unsupported',\n reason: 'UNSUPPORTED_MERKLE_COMMIT_ALG',\n };\n }\n\n // Leaves-list acquisition: caller-supplied bytes first, then the first\n // ar://-or-ipfs:// URI in `merkle[i].uris[]`.\n let leavesBytes: Uint8Array | null = args.input.merkleLeaves?.[index] ?? null;\n if (leavesBytes === null) {\n const uris = commit.uris;\n if (uris === undefined || uris.length === 0) {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unavailable',\n reason: 'MERKLE_LEAVES_UNAVAILABLE',\n };\n }\n try {\n leavesBytes = await fetchItemCiphertext({\n uris,\n arweaveGateways: args.input.arweaveGatewayChain,\n ipfsGateways: args.input.ipfsGatewayChain,\n fetchFn: args.fetchFn,\n uriChecksOut: args.uriChecksOut,\n // Merkle commits are not item-indexed; reuse a sentinel index so\n // downstream UIs can distinguish them from item URIs.\n itemIndex: -1 - index,\n });\n } catch {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unavailable',\n reason: 'MERKLE_LEAVES_UNAVAILABLE',\n };\n }\n }\n\n // Decode the leaves-list document. `decodeLeavesList` enforces format,\n // tree_alg, leaf-count match, and recomputes the root for defence-in-depth;\n // any failure surfaces as a typed error code.\n try {\n const decoded = decodeLeavesList(leavesBytes);\n // Compare the on-record root to the recomputed root byte-exact.\n const recomputed = merkleSha2256Root(decoded.leaves);\n if (!compareCt(recomputed, commit.root)) {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'mismatch',\n reason: 'MERKLE_ROOT_MISMATCH',\n root_recomputed: recomputed,\n };\n }\n if (decoded.leafCount !== commit.leaf_count) {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'mismatch',\n reason: 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n };\n }\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'valid',\n root_recomputed: recomputed,\n };\n } catch (e) {\n if (e instanceof MerkleLeavesListError) {\n if (e.code === 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED') {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'format-unsupported',\n reason: 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED',\n };\n }\n if (e.code === 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH') {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'mismatch',\n reason: 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n };\n }\n if (e.code === 'MERKLE_ROOT_MISMATCH') {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'mismatch',\n reason: 'MERKLE_ROOT_MISMATCH',\n };\n }\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unavailable',\n reason: e.code,\n };\n }\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unavailable',\n reason: e instanceof Error ? e.message : String(e),\n };\n }\n}\n","// Conformance-profile helpers.\n//\n// A `core`-profile verifier reading a record that carries `sigs`, `enc`, or\n// `merkle` MUST emit `OUT_OF_PROFILE_SKIPPED` (info severity) per affected\n// field — NOT `SCHEMA_UNKNOWN_FIELD` (which applies only to fields outside\n// the v1 CDDL). This rule lets a block explorer shipping only the `core`\n// surface still surface every conformant v1 record regardless of which\n// extensions it carries.\n\nimport type { PoeRecord, ValidationIssue } from '@cardanowall/poe-standard';\n\nimport type { Profile } from './types';\nimport { PROFILE_RANK } from './types';\n\nexport const DEFAULT_PROFILE: Profile = 'recipient-sealed';\n\nexport function profileImplements(actual: Profile, required: Profile): boolean {\n return PROFILE_RANK[actual] >= PROFILE_RANK[required];\n}\n\nexport interface ProfileSkipsResult {\n // info-severity entries emitted when a field belongs to a higher profile\n // than the active one. Surfaces in `validation.info`.\n readonly skips: ValidationIssue[];\n // Convenience flags for the verifier pipeline (whether to enter each\n // sub-pipeline at all).\n readonly verifySignatures: boolean;\n readonly verifyDecrypt: boolean;\n}\n\n/**\n * Emit the minimum conformance profile a verifier MUST implement\n * to read this record end-to-end. The profiles form a strict superset chain\n * `core ⊂ signed ⊂ sealed ⊂ recipient-sealed`.\n *\n * The function classifies based on RECORD CONTENT only:\n * - `'core'` — no signatures, no sealed items.\n * - `'signed'` — `record.sigs[]` is present, no sealed items.\n * - `'sealed'` — any `record.items[i].enc` is present (with or without sigs).\n *\n * The function does NOT return `'recipient-sealed'`: that profile is about\n * VERIFIER CAPABILITY (whether the verifier decrypts with a recipient X25519\n * key), not about record content. A separate helper is required if a caller\n * needs to test whether a particular recipient key can unwrap any slot — see\n * `@cardanowall/crypto-core/sealed-poe` for that pathway.\n */\nexport function detectConformanceProfile(record: PoeRecord): 'core' | 'signed' | 'sealed' {\n const hasSealedItem =\n Array.isArray(record.items) && record.items.some((it) => it.enc !== undefined);\n if (hasSealedItem) return 'sealed';\n const hasSigs = Array.isArray(record.sigs) && record.sigs.length > 0;\n if (hasSigs) return 'signed';\n return 'core';\n}\n\nexport function planProfileSkips(profile: Profile, record: PoeRecord): ProfileSkipsResult {\n const skips: ValidationIssue[] = [];\n const has = (k: string): boolean => Object.prototype.hasOwnProperty.call(record, k);\n const verifySignatures = PROFILE_RANK[profile] >= PROFILE_RANK['signed'];\n // The `sealed` rank gates whether the verifier reads the enc envelope at all.\n // There is no separate `sealed`-only sub-pipeline distinct from decryption,\n // so this drives only the skip-emission below rather than a returned flag.\n const readsEnc = PROFILE_RANK[profile] >= PROFILE_RANK['sealed'];\n const verifyDecrypt = PROFILE_RANK[profile] >= PROFILE_RANK['recipient-sealed'];\n\n if (!verifySignatures && has('sigs')) {\n skips.push({\n code: 'OUT_OF_PROFILE_SKIPPED',\n path: ['sigs'],\n message: `sigs[] requires profile >= 'signed'; active profile is '${profile}'`,\n severity: 'info',\n });\n }\n if (!readsEnc && Array.isArray(record.items) && record.items.some((it) => it.enc !== undefined)) {\n skips.push({\n code: 'OUT_OF_PROFILE_SKIPPED',\n path: ['items', 'enc'],\n message: `items[].enc requires profile >= 'sealed'; active profile is '${profile}'`,\n severity: 'info',\n });\n }\n return { skips, verifySignatures, verifyDecrypt };\n}\n","// Position-aware CBOR walker for byte-faithful label-309 metadata extraction.\n//\n// The verifier MUST fetch raw transaction CBOR and extract the label-309\n// value VERBATIM (not via decode-then-re-encode). A\n// re-encode pass would silently launder a non-conformant on-chain record into\n// a conformant one because cbor2's decoder normalises non-canonical input\n// (sorts map keys, collapses indefinite-length encodings, etc.); the\n// structural validator's canonical-CBOR check (`decodeCanonicalCbor` +\n// cbor2 CDE options) only catches the violation if it sees the producer's\n// original bytes.\n//\n// Pure stdlib walker (no `cbor2` dependency for the slicing path). Rejects\n// indefinite-length encodings, which canonical CBOR forbids; the structural\n// validator downstream performs the rest of the deterministic-encoding checks.\n\ninterface CborHead {\n readonly mt: number;\n readonly ai: number;\n readonly payloadStart: number;\n readonly valueU64: number;\n}\n\nfunction readHead(bytes: Uint8Array, pos: number): CborHead {\n if (pos >= bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated input (no head byte)');\n }\n const head = bytes[pos]!;\n const mt = head >> 5;\n const ai = head & 0x1f;\n let p = pos + 1;\n let valueU64: number;\n\n if (ai < 24) {\n valueU64 = ai;\n } else if (ai === 24) {\n if (p + 1 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 1-byte argument');\n }\n valueU64 = bytes[p]!;\n p += 1;\n } else if (ai === 25) {\n if (p + 2 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 2-byte argument');\n }\n valueU64 = (bytes[p]! << 8) | bytes[p + 1]!;\n p += 2;\n } else if (ai === 26) {\n if (p + 4 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 4-byte argument');\n }\n valueU64 =\n bytes[p]! * 0x1000000 + ((bytes[p + 1]! << 16) | (bytes[p + 2]! << 8) | bytes[p + 3]!);\n p += 4;\n } else if (ai === 27) {\n if (p + 8 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 8-byte argument');\n }\n let n = 0;\n for (let k = 0; k < 8; k++) n = n * 256 + bytes[p + k]!;\n if (n > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('MALFORMED_CBOR: 8-byte argument exceeds JavaScript safe integer range');\n }\n valueU64 = n;\n p += 8;\n } else if (ai === 31) {\n throw new RangeError(\n 'MALFORMED_CBOR: indefinite-length encoding (ai=31) not allowed under canonical CBOR',\n );\n } else {\n throw new RangeError(`MALFORMED_CBOR: reserved additional info ai=${ai}`);\n }\n\n return { mt, ai, payloadStart: p, valueU64 };\n}\n\nfunction skipCborItem(bytes: Uint8Array, pos: number): number {\n const h = readHead(bytes, pos);\n let p = h.payloadStart;\n switch (h.mt) {\n case 0:\n case 1:\n return p;\n case 2:\n case 3:\n if (p + h.valueU64 > bytes.length) {\n throw new RangeError(\n `MALFORMED_CBOR: truncated ${h.mt === 2 ? 'byte' : 'text'} string payload`,\n );\n }\n return p + h.valueU64;\n case 4:\n for (let i = 0; i < h.valueU64; i++) p = skipCborItem(bytes, p);\n return p;\n case 5:\n for (let i = 0; i < h.valueU64 * 2; i++) p = skipCborItem(bytes, p);\n return p;\n case 6:\n return skipCborItem(bytes, p);\n case 7: {\n if (h.ai < 24) return p;\n if (h.ai === 24) {\n if (p + 1 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated simple value');\n }\n return p + 1;\n }\n if (h.ai === 25 || h.ai === 26 || h.ai === 27) return p;\n throw new RangeError(`MALFORMED_CBOR: unsupported major-7 ai=${h.ai}`);\n }\n default:\n throw new RangeError(`MALFORMED_CBOR: unknown major type ${h.mt}`);\n }\n}\n\n// CBOR tag 259 wraps post-Alonzo auxiliary_data (CIP-29).\nconst CARDANO_AUX_DATA_TAG = 259;\nconst POE_LABEL = 309;\n\n/**\n * Byte-faithful components of a Cardano transaction, located by walking the\n * tx CBOR without a decode-then-re-encode pass.\n *\n * `txBody` and `witnessSet` are EXACT on-chain byte slices: `blake2b256(txBody)`\n * equals the transaction hash, and the witness set decodes to the vkey\n * witnesses that authorised the transaction. The slices are produced by the\n * same position-aware walk that finds label 309, so they never round-trip\n * through a CBOR re-encoder.\n *\n * `label309` is the reassembled label-309 value (chunked-bytes concatenated;\n * see `reassembleLabel309Value`), `null` when auxiliary_data is null/undefined\n * or label 309 is absent. `auxMetadataLabels` is the ascending-sorted list of\n * every integer key in the auxiliary metadata map (`[]` when aux is null).\n */\nexport interface TxComponents {\n readonly label309: Uint8Array | null;\n readonly txBody: Uint8Array;\n readonly witnessSet: Uint8Array;\n readonly auxMetadataLabels: number[];\n}\n\n/**\n * Walk the transaction CBOR once and return its byte-faithful components.\n *\n * Throws `RangeError(\"MALFORMED_CBOR: …\")` on structural violations. The body\n * and witness-set slices are the producer's ORIGINAL bytes; `label309` carries\n * the same byte-faithful guarantee `sliceLabel309Value` documents (no\n * decode-then-re-encode, so non-canonical encodings reach the structural\n * validator unchanged).\n */\nexport function sliceTxComponents(txCbor: Uint8Array): TxComponents {\n const txHead = readHead(txCbor, 0);\n if (txHead.mt !== 4) {\n throw new RangeError(`MALFORMED_CBOR: tx CBOR is not a CBOR array (major type ${txHead.mt})`);\n }\n if (txHead.valueU64 < 4) {\n throw new RangeError(\n `MALFORMED_CBOR: tx CBOR array has ${txHead.valueU64} elements; expected >= 4 (post-Conway: [body, witness_set, is_valid, auxiliary_data])`,\n );\n }\n\n const bodyStart = txHead.payloadStart;\n const bodyEnd = skipCborItem(txCbor, bodyStart);\n const witnessSetStart = bodyEnd;\n const witnessSetEnd = skipCborItem(txCbor, witnessSetStart);\n const pos = skipCborItem(txCbor, witnessSetEnd); // skip is_valid\n\n const txBody = txCbor.slice(bodyStart, bodyEnd);\n const witnessSet = txCbor.slice(witnessSetStart, witnessSetEnd);\n\n if (pos >= txCbor.length) {\n throw new RangeError('MALFORMED_CBOR: truncated tx (auxiliary_data missing)');\n }\n const auxFirstByte = txCbor[pos]!;\n if (auxFirstByte === 0xf6 || auxFirstByte === 0xf7) {\n return { label309: null, txBody, witnessSet, auxMetadataLabels: [] };\n }\n\n let auxMapPos = pos;\n const auxHead = readHead(txCbor, pos);\n if (auxHead.mt === 6) {\n if (auxHead.valueU64 !== CARDANO_AUX_DATA_TAG) {\n throw new RangeError(\n `MALFORMED_CBOR: auxiliary_data carries unexpected CBOR tag ${auxHead.valueU64}; expected ${CARDANO_AUX_DATA_TAG} or bare map`,\n );\n }\n auxMapPos = auxHead.payloadStart;\n }\n\n const mapHead = readHead(txCbor, auxMapPos);\n if (mapHead.mt !== 5) {\n throw new RangeError(\n `MALFORMED_CBOR: auxiliary_data is not a CBOR map (major type ${mapHead.mt})`,\n );\n }\n\n // Disambiguate the tagged (post-Alonzo, `{0 → metadata, 1 → ...}`) and bare\n // (pre-Alonzo, the map IS the metadata map directly) auxiliary_data shapes\n // by walking the map keys: if any int key in `{0,1,2,3}` is present, treat\n // it as the post-Alonzo shape and find key 0; else treat the whole map as\n // metadata directly. Modern Cardano txs (Conway+) are always tag-259\n // wrapped, but synthetic test fixtures often emit the post-Alonzo shape\n // bare and we want to handle both without forcing producers to add the tag.\n let metadataMapPos: number | null;\n {\n let entryPos = mapHead.payloadStart;\n let sawAuxKey = false;\n let foundMetadataAt: number | null = null;\n for (let i = 0; i < mapHead.valueU64; i++) {\n const keyHead = readHead(txCbor, entryPos);\n if (keyHead.mt === 0 && keyHead.valueU64 <= 3) {\n sawAuxKey = true;\n if (keyHead.valueU64 === 0) {\n foundMetadataAt = keyHead.payloadStart;\n }\n }\n entryPos = skipCborItem(txCbor, entryPos); // skip key\n entryPos = skipCborItem(txCbor, entryPos); // skip value\n }\n if (sawAuxKey || auxHead.mt === 6) {\n metadataMapPos = foundMetadataAt;\n } else {\n // Bare pre-Alonzo metadata map.\n metadataMapPos = auxMapPos;\n }\n }\n\n if (metadataMapPos === null) {\n return { label309: null, txBody, witnessSet, auxMetadataLabels: [] };\n }\n\n const metaHead = readHead(txCbor, metadataMapPos);\n if (metaHead.mt !== 5) {\n throw new RangeError(`MALFORMED_CBOR: metadata is not a CBOR map (major type ${metaHead.mt})`);\n }\n const labels: number[] = [];\n let label309: Uint8Array | null = null;\n let pairPos = metaHead.payloadStart;\n for (let i = 0; i < metaHead.valueU64; i++) {\n const keyHead = readHead(txCbor, pairPos);\n const keyVal = decodeIntKey(keyHead);\n labels.push(keyVal);\n const valueStart = skipCborItem(txCbor, pairPos);\n const valueEnd = skipCborItem(txCbor, valueStart);\n if (keyVal === POE_LABEL) {\n label309 = reassembleLabel309Value(txCbor, valueStart, valueEnd);\n }\n pairPos = valueEnd;\n }\n labels.sort((a, b) => a - b);\n return { label309, txBody, witnessSet, auxMetadataLabels: labels };\n}\n\n/**\n * Extract the byte slice corresponding to the value under metadata label 309.\n * Returns `null` when auxiliary_data is null/undefined or when label 309 is\n * absent. Throws `RangeError(\"MALFORMED_CBOR: …\")` on structural violations.\n *\n * Returns the producer's ORIGINAL on-chain bytes — no decode-then-re-encode\n * pass. The structural validator MUST receive these bytes verbatim so\n * non-canonical encodings surface as `MALFORMED_CBOR` rather than being\n * silently laundered.\n */\nexport function sliceLabel309Value(txCbor: Uint8Array): Uint8Array | null {\n return sliceTxComponents(txCbor).label309;\n}\n\n/**\n * Cardano caps individual metadata `bstr` / `tstr` values at 64 bytes\n * (Cardano metadata spec). A CIP-309 PoE record's\n * canonical CBOR is typically several hundred bytes, so the producer emits\n * it as a `bytes-chunk-array` — `[ bstr .size (1..64), … ]` — at the\n * label-309 value position. The verifier MUST byte-concatenate the chunks\n * IN ORDER before passing the result to `validatePoeRecord`, otherwise\n * the canonical-CBOR decoder sees an outer CBOR array of byte strings\n * instead of the inner CBOR map and the record fails with\n * `SCHEMA_TYPE_MISMATCH` / `MALFORMED_CBOR`.\n *\n * Small records (≤ 64 bytes) MAY be emitted as a single `bstr` directly.\n * For backwards-compat we also accept a bare CBOR map value — older\n * producers and small synthetic fixtures use that shape.\n *\n * Returns the canonical-CBOR PoE record body (a `bstr`-free, map-rooted\n * byte sequence) ready for validation.\n */\nfunction reassembleLabel309Value(\n txCbor: Uint8Array,\n valueStart: number,\n valueEnd: number,\n): Uint8Array {\n const head = readHead(txCbor, valueStart);\n // Major type 4 = array → assume bytes-chunk-array; concatenate inner bstr items.\n if (head.mt === 4) {\n const out: Uint8Array[] = [];\n let totalLen = 0;\n let chunkPos = head.payloadStart;\n for (let i = 0; i < head.valueU64; i++) {\n const chunkHead = readHead(txCbor, chunkPos);\n if (chunkHead.mt !== 2) {\n throw new RangeError(\n `MALFORMED_CBOR: label-309 value is a CBOR array but element ${i} has major type ${chunkHead.mt}; expected byte string (chunked-bytes shape)`,\n );\n }\n const chunkValueStart = chunkHead.payloadStart;\n const chunkValueEnd = chunkValueStart + chunkHead.valueU64;\n out.push(txCbor.slice(chunkValueStart, chunkValueEnd));\n totalLen += chunkHead.valueU64;\n chunkPos = chunkValueEnd;\n }\n const concat = new Uint8Array(totalLen);\n let offset = 0;\n for (const c of out) {\n concat.set(c, offset);\n offset += c.length;\n }\n return concat;\n }\n // Major type 2 = single bstr value. The bstr CONTENTS are the canonical\n // CBOR record body — strip the bstr head so decodeCanonicalCbor sees the\n // map directly.\n if (head.mt === 2) {\n return txCbor.slice(head.payloadStart, head.payloadStart + head.valueU64);\n }\n // Major type 5 = map directly (bare-canonical shape; some synthetic\n // fixtures emit this when the record fits in one chunk and the producer\n // chose not to box it in a bstr). Pass through unchanged.\n if (head.mt === 5) {\n return txCbor.slice(valueStart, valueEnd);\n }\n throw new RangeError(\n `MALFORMED_CBOR: label-309 value has major type ${head.mt}; expected array (chunked), byte string, or map`,\n );\n}\n\nfunction decodeIntKey(h: CborHead): number {\n if (h.mt === 0) return h.valueU64;\n if (h.mt === 1) return -1 - h.valueU64;\n throw new RangeError(\n `MALFORMED_CBOR: metadata map key has major type ${h.mt}; expected unsigned integer`,\n );\n}\n","// Cardano gateway resolver — Koios first, then Blockfrost fallback if a\n// project ID is supplied. Returns the RAW on-chain transaction CBOR (NOT\n// the gateway's lossy JSON metadata projection — the verifier needs the\n// producer's original bytes to detect non-canonical encodings).\n\nimport { sliceLabel309Value } from './cbor-walker';\nimport type { FetchOutbound, VerifyTxInput } from './types';\n\nexport interface ResolvedTx {\n readonly txCbor: Uint8Array;\n readonly numConfirmations: number;\n readonly blockTime: number;\n readonly blockSlot: number;\n readonly provider: 'koios' | 'blockfrost';\n readonly providerUrl: string;\n}\n\nexport const KOIOS_MAINNET_URL = 'https://api.koios.rest/api/v1';\nexport const BLOCKFROST_MAINNET_HOST = 'https://cardano-mainnet.blockfrost.io/api/v0';\n\n// Distinct error class so the verifier can short-circuit the gateway-fallback\n// loop on a definitive \"this tx is not on chain / has no PoE metadata\"\n// response: a definitive negative from one gateway is authoritative, so there\n// is no point rotating to the next gateway.\nexport class NotACip309RecordError extends Error {\n readonly code = 'METADATA_NOT_FOUND' as const;\n constructor(message: string) {\n super(message);\n this.name = 'NotACip309RecordError';\n }\n}\n\nexport async function resolveCardanoTx(args: {\n readonly input: VerifyTxInput;\n readonly fetchFn: FetchOutbound;\n}): Promise<ResolvedTx> {\n const { input, fetchFn } = args;\n const koiosChain = input.cardanoGatewayChain ?? [KOIOS_MAINNET_URL];\n\n let lastErr: unknown;\n for (const koiosUrl of koiosChain) {\n try {\n return await resolveViaKoios(input.txHash, koiosUrl, fetchFn);\n } catch (e) {\n if (e instanceof NotACip309RecordError) throw e;\n lastErr = e;\n }\n }\n\n if (input.blockfrostProjectId !== undefined) {\n try {\n return await resolveViaBlockfrost(input.txHash, input.blockfrostProjectId, fetchFn);\n } catch (e) {\n if (e instanceof NotACip309RecordError) throw e;\n lastErr = e;\n }\n }\n\n throw new Error(`all_providers_failed: ${(lastErr as Error | undefined)?.message ?? 'unknown'}`);\n}\n\nasync function resolveViaKoios(\n txHash: string,\n koiosUrl: string,\n fetchFn: FetchOutbound,\n): Promise<ResolvedTx> {\n const cborRes = await fetchFn(`${koiosUrl}/tx_cbor`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ _tx_hashes: [txHash] }),\n purpose: 'cardano',\n });\n if (cborRes.status !== 200) {\n throw new Error(`koios_tx_cbor_${cborRes.status}`);\n }\n const cborJson = parseJson(cborRes.bytes);\n if (!Array.isArray(cborJson) || cborJson.length === 0) {\n throw new NotACip309RecordError('koios returned empty array for tx_cbor; tx may not exist');\n }\n const cborEntry = cborJson[0] as { tx_hash?: unknown; cbor?: unknown };\n if (typeof cborEntry.cbor !== 'string') {\n throw new Error('koios_tx_cbor_missing_cbor_field');\n }\n if (\n typeof cborEntry.tx_hash === 'string' &&\n cborEntry.tx_hash.toLowerCase() !== txHash.toLowerCase()\n ) {\n throw new Error(`koios_tx_cbor_hash_mismatch: requested ${txHash} got ${cborEntry.tx_hash}`);\n }\n const txCbor = hexToBytes(cborEntry.cbor);\n\n const infoRes = await fetchFn(`${koiosUrl}/tx_info`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ _tx_hashes: [txHash] }),\n purpose: 'cardano',\n });\n if (infoRes.status !== 200) {\n throw new Error(`koios_tx_info_${infoRes.status}`);\n }\n const infoJson = parseJson(infoRes.bytes);\n if (!Array.isArray(infoJson) || infoJson.length === 0) {\n throw new NotACip309RecordError('koios returned empty array for tx_info');\n }\n const infoEntry = infoJson[0] as {\n tx_hash?: unknown;\n num_confirmations?: unknown;\n block_height?: unknown;\n tx_timestamp?: unknown;\n absolute_slot?: unknown;\n };\n if (\n typeof infoEntry.tx_hash === 'string' &&\n infoEntry.tx_hash.toLowerCase() !== txHash.toLowerCase()\n ) {\n throw new Error(`koios_tx_info_hash_mismatch: requested ${txHash} got ${infoEntry.tx_hash}`);\n }\n\n // Koios v1 `/tx_info` no longer returns `num_confirmations` — only\n // `block_height` (verified live against `preprod.koios.rest/api/v1/tx_info`\n // and `api.koios.rest/api/v1/tx_info` on 2026-05-20: response keys do not\n // include num_confirmations). Compute manually as `tip - txBlockHeight + 1`,\n // mirroring the Blockfrost path. Fall back to a deprecated direct read of\n // `num_confirmations` for forward-compat against older Koios deployments.\n let numConfirmations: number;\n if (typeof infoEntry.num_confirmations === 'number') {\n numConfirmations = requireNonNegativeInt(infoEntry.num_confirmations, 'num_confirmations');\n } else {\n const txBlockHeight = requireNonNegativeInt(infoEntry.block_height, 'block_height');\n const tipRes = await fetchFn(`${koiosUrl}/tip`, {\n method: 'GET',\n headers: { accept: 'application/json' },\n purpose: 'cardano',\n });\n if (tipRes.status !== 200) {\n throw new Error(`koios_tip_${tipRes.status}`);\n }\n const tipJson = parseJson(tipRes.bytes);\n if (!Array.isArray(tipJson) || tipJson.length === 0) {\n throw new Error('koios_tip_empty');\n }\n const tipEntry = tipJson[0] as { block_height?: unknown };\n const tipHeight = requireNonNegativeInt(tipEntry.block_height, 'tip.block_height');\n numConfirmations = Math.max(0, tipHeight - txBlockHeight + 1);\n }\n\n return {\n txCbor,\n numConfirmations,\n blockTime: requireNonNegativeInt(infoEntry.tx_timestamp, 'tx_timestamp'),\n blockSlot: requireNonNegativeInt(infoEntry.absolute_slot, 'absolute_slot'),\n provider: 'koios',\n providerUrl: koiosUrl,\n };\n}\n\nasync function resolveViaBlockfrost(\n txHash: string,\n projectId: string,\n fetchFn: FetchOutbound,\n): Promise<ResolvedTx> {\n const base = BLOCKFROST_MAINNET_HOST;\n const headers = { project_id: projectId, accept: 'application/json' };\n\n const cborRes = await fetchFn(`${base}/txs/${txHash}/cbor`, {\n method: 'GET',\n headers,\n purpose: 'cardano',\n });\n if (cborRes.status !== 200) {\n throw new Error(`blockfrost_tx_cbor_${cborRes.status}`);\n }\n const cborJson = parseJson(cborRes.bytes) as { cbor?: unknown };\n if (typeof cborJson.cbor !== 'string') {\n throw new Error('blockfrost_tx_cbor_missing_cbor_field');\n }\n const txCbor = hexToBytes(cborJson.cbor);\n\n const txRes = await fetchFn(`${base}/txs/${txHash}`, {\n method: 'GET',\n headers,\n purpose: 'cardano',\n });\n if (txRes.status !== 200) {\n throw new Error(`blockfrost_tx_${txRes.status}`);\n }\n const txJson = parseJson(txRes.bytes) as {\n block_time?: unknown;\n slot?: unknown;\n block_height?: unknown;\n };\n const blockTime = requireNonNegativeInt(txJson.block_time, 'block_time');\n const txSlot = requireNonNegativeInt(txJson.slot, 'slot');\n // Confirmations are counted in BLOCKS, not slots. Cardano's active-slot\n // coefficient f=0.05 means only ~1 slot in 20 produces a block, so a\n // slot-difference count would inflate confirmations by ~20×. Blockfrost\n // returns `block_height` on `tx_content` and `height` on `/blocks/latest` —\n // both are the block-number field — so confirmations are\n // `tipHeight - blockHeight + 1`.\n const txBlockHeight = requireNonNegativeInt(txJson.block_height, 'block_height');\n\n const tipRes = await fetchFn(`${base}/blocks/latest`, {\n method: 'GET',\n headers,\n purpose: 'cardano',\n });\n if (tipRes.status !== 200) {\n throw new Error(`blockfrost_blocks_latest_${tipRes.status}`);\n }\n const tipJson = parseJson(tipRes.bytes) as { slot?: unknown; height?: unknown };\n const tipHeight = requireNonNegativeInt(tipJson.height, 'tip_height');\n const numConfirmations = Math.max(0, tipHeight - txBlockHeight + 1);\n\n return {\n txCbor,\n numConfirmations,\n blockTime,\n blockSlot: txSlot,\n provider: 'blockfrost',\n providerUrl: base,\n };\n}\n\n// Byte-faithful label-309 extraction (delegates to the position-aware\n// `cbor-walker`, which never decode-then-re-encodes).\nexport function extractLabel309Metadata(txCbor: Uint8Array): Uint8Array | null {\n return sliceLabel309Value(txCbor);\n}\n\nfunction parseJson(bytes: Uint8Array): unknown {\n return JSON.parse(new TextDecoder().decode(bytes));\n}\n\nfunction requireNonNegativeInt(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n throw new Error(`gateway_field_invalid: ${field} (got ${typeof value}=${String(value)})`);\n }\n return value;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const clean = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;\n if (clean.length % 2 !== 0) {\n throw new Error(`hex string has odd length (${clean.length})`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error('hex string contains non-hex characters');\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n","// Lowercase, no-`0x`-prefix hex encoder shared across the SDK. Single\n// implementation so the verifier, the wire serialiser, and the publish client\n// all emit byte-identical hex (the Python parity twin and the cross-language\n// fixtures depend on this exact form).\n\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n","// CIP-309 record-level signature verifier.\n//\n// One verification per `record.sigs[i]`. v1 has NO per-item signature slot —\n// the only signature surface is the record-level array. Two on-wire signer-key\n// paths (mutually exclusive on the wire, enforced by the structural\n// validator as `SIG_ENTRY_KID_COSE_KEY_CONFLICT`):\n//\n// Path 1 — protected-header `kid` is exactly 32 bytes (raw Ed25519 pubkey).\n// Path 2 — `sigs[i].cose_key` is a chunked `cbor<COSE_Key>` blob carrying\n// the wallet's public key. The protected header carries a 29-byte\n// CIP-19 stake address at label `\"address\"`; the verifier\n// recomputes `address_derived = network_header || Blake2b-224(pub)`\n// and rejects on mismatch (`WALLET_ADDRESS_MISMATCH`).\n//\n// The signed-payload construction (`Sig_structure[3] = \"cardano-poe-record-sig-v1\" ||\n// canonicalCbor(record_body)`, `Sig_structure[2] = h''`) is enforced by the\n// `coseSign1Cip309Verify` helper in `@cardanowall/crypto-core/cose` — this\n// verifier never sees the prefix directly.\n\nimport {\n bytesChunkArrayConcat,\n encodeRecordBodyForSigning,\n type PoeRecord,\n type SigEntry,\n} from '@cardanowall/poe-standard';\nimport {\n coseSign1Cip309Verify,\n decodeCoseSign1,\n parseCoseKeyEd25519,\n type CoseSign1Decoded,\n} from '@cardanowall/crypto-core/cose';\nimport { blake2b224 } from '@cardanowall/crypto-core/hash';\nimport { compareCt } from '@cardanowall/crypto-core/util';\n\nimport { bytesToHex } from '../hex';\nimport type { SignatureFailureReason, VerifyRecordSignature, VerifyTxInput } from './types';\n\n// v1 wallet-path constraint: stake (reward) addresses only. The 29-byte CIP-19\n// layout is `network_header_byte || Blake2b-224(stake_vk)`. CIP-19\n// stake-address network bytes: mainnet = 0xe1, testnet = 0xe0 (preprod and\n// preview share the testnet header). Product policy is mainnet-only; the\n// preprod branch exists only so dev environments can replay records anchored\n// on preprod against the same standalone verifier.\nconst CARDANO_MAINNET_STAKE_NETWORK_BYTE = 0xe1;\nconst CARDANO_PREPROD_STAKE_NETWORK_BYTE = 0xe0;\nconst CARDANO_STAKE_ADDRESS_LENGTH = 29;\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\nconst BLAKE2B_224_LENGTH = 28;\n\nexport interface VerifyRecordSignaturesArgs {\n readonly record: PoeRecord;\n readonly input: VerifyTxInput;\n}\n\nexport async function verifyRecordSignatures(\n args: VerifyRecordSignaturesArgs,\n): Promise<VerifyRecordSignature[]> {\n const { record, input } = args;\n // The signed payload is canonical-CBOR(record_body), where record_body =\n // record minus `sigs`. We use the encoder helper to keep the wire shape and\n // key sort in lockstep with producer-side signing.\n const recordBodyCbor = encodeRecordBodyForSigning(record);\n const list = record.sigs ?? [];\n const out: VerifyRecordSignature[] = [];\n for (let i = 0; i < list.length; i++) {\n out.push(await verifyOneSig(i, list[i]!, recordBodyCbor, input));\n }\n return out;\n}\n\nasync function verifyOneSig(\n index: number,\n entry: SigEntry,\n recordBodyCbor: Uint8Array,\n input: VerifyTxInput,\n): Promise<VerifyRecordSignature> {\n const coseBytes = bytesChunkArrayConcat(entry.cose_sign1);\n let cose: CoseSign1Decoded;\n try {\n cose = decodeCoseSign1(coseBytes);\n } catch {\n return { index, verdict: 'invalid', reason: 'MALFORMED_SIG_COSE_SIGN1' };\n }\n\n // Resolve the signer's 32-byte Ed25519 pubkey (path 1 vs path 2).\n const resolved = resolveSignerKey(cose, entry);\n if (resolved.kind === 'unresolved') {\n return { index, verdict: 'unresolved', reason: 'SIGNER_KEY_UNRESOLVED' };\n }\n const { pub, signerType } = resolved;\n\n // Strict Ed25519 verify via the CIP-309-pinned helper.\n const verifyResult = coseSign1Cip309Verify({\n message: coseBytes,\n detachedRecordBodyCbor: recordBodyCbor,\n expectedSignerKey: pub,\n });\n\n if (!verifyResult.ok) {\n const reason = mapVerifyError(verifyResult.error.code);\n if (reason === 'SIGNATURE_UNSUPPORTED') {\n return {\n index,\n verdict: 'unsupported',\n signer_type: signerType,\n signer_pub: bytesToHex(pub),\n reason,\n };\n }\n return {\n index,\n verdict: 'invalid',\n signer_type: signerType,\n signer_pub: bytesToHex(pub),\n reason,\n };\n }\n\n // Path-2 wallet `address` ↔ `cose_key` binding. Path-1 entries skip this\n // check entirely.\n if (signerType === 'wallet-inline-key') {\n const addressOk = checkWalletAddressBinding(cose, pub, input);\n if (!addressOk) {\n return {\n index,\n verdict: 'invalid',\n signer_type: signerType,\n signer_pub: bytesToHex(pub),\n reason: 'WALLET_ADDRESS_MISMATCH',\n };\n }\n }\n\n return {\n index,\n verdict: 'valid',\n signer_type: signerType,\n signer_pub: bytesToHex(pub),\n };\n}\n\ninterface ResolvedPathOne {\n readonly kind: 'in-signature-kid';\n readonly pub: Uint8Array;\n readonly signerType: 'in-signature-kid';\n}\ninterface ResolvedPathTwo {\n readonly kind: 'wallet-inline-key';\n readonly pub: Uint8Array;\n readonly signerType: 'wallet-inline-key';\n}\ntype ResolvedKey = ResolvedPathOne | ResolvedPathTwo | { readonly kind: 'unresolved' };\n\nfunction resolveSignerKey(cose: CoseSign1Decoded, entry: SigEntry): ResolvedKey {\n // Path 1 — protected-header label 4 (`kid`) as the 32-byte raw Ed25519\n // pubkey. Unprotected-header `kid` values are NEVER consulted: they sit\n // outside the COSE integrity envelope and an attacker could rewrite them.\n const protectedKid = cose.protectedHeader.get(4) as unknown;\n if (\n protectedKid instanceof Uint8Array &&\n protectedKid.length === ED25519_PUBLIC_KEY_LENGTH &&\n entry.cose_key === undefined\n ) {\n return {\n kind: 'in-signature-kid',\n pub: protectedKid,\n signerType: 'in-signature-kid',\n };\n }\n // Path 2 — chunked `cbor<COSE_Key>` carrying the wallet pubkey.\n if (entry.cose_key !== undefined) {\n const blob = bytesChunkArrayConcat(entry.cose_key);\n const pub = parseCoseKeyEd25519(blob);\n if (pub !== null && pub.length === ED25519_PUBLIC_KEY_LENGTH) {\n return { kind: 'wallet-inline-key', pub, signerType: 'wallet-inline-key' };\n }\n }\n return { kind: 'unresolved' };\n}\n\nfunction mapVerifyError(code: string): SignatureFailureReason {\n switch (code) {\n case 'MALFORMED_SIG_COSE':\n case 'MALFORMED_SIG_COSE_SIGN1':\n return 'MALFORMED_SIG_COSE_SIGN1';\n case 'UNSUPPORTED_SIG_ALG':\n return 'SIGNATURE_UNSUPPORTED';\n case 'KID_UNRESOLVED':\n return 'SIGNER_KEY_UNRESOLVED';\n case 'SIGNATURE_INVALID':\n return 'SIGNATURE_INVALID';\n default:\n return 'SIGNATURE_INVALID';\n }\n}\n\n// Recompute the 29-byte stake address from the resolved Ed25519 pubkey and\n// compare it byte-exact (constant-time) to the path-2 protected-header\n// `address` field. The wallet path binds to stake (reward) addresses only in\n// v1 — base/enterprise/pointer/payment addresses are rejected (the recomputed\n// 29-byte stake address fails the equality check against any other\n// format/length).\nfunction checkWalletAddressBinding(\n cose: CoseSign1Decoded,\n pub: Uint8Array,\n input: VerifyTxInput,\n): boolean {\n const networkByte =\n (input.cardanoNetwork ?? 'mainnet') === 'preprod'\n ? CARDANO_PREPROD_STAKE_NETWORK_BYTE\n : CARDANO_MAINNET_STAKE_NETWORK_BYTE;\n const rawAddress = cose.protectedHeader.get('address') as unknown;\n if (!(rawAddress instanceof Uint8Array)) {\n // Address-less path-2 records are non-conformant with CIP-30 signData\n // (a wallet signature without an address claim cannot be safely surfaced\n // as wallet-bound). Treat as WALLET_ADDRESS_MISMATCH.\n return false;\n }\n if (rawAddress.length !== CARDANO_STAKE_ADDRESS_LENGTH) return false;\n if (rawAddress[0] !== networkByte) return false;\n const stakeKeyHash = blake2b224(pub);\n if (stakeKeyHash.length !== BLAKE2B_224_LENGTH) {\n // Defensive guard — `blake2b224` is byte-pinned to 28 bytes.\n return false;\n }\n const derived = new Uint8Array(CARDANO_STAKE_ADDRESS_LENGTH);\n derived[0] = networkByte;\n derived.set(stakeKeyHash, 1);\n return compareCt(derived, rawAddress);\n}\n","// Transaction-level decode for the CIP-309 verifier.\n//\n// This module surfaces the Cardano TRANSACTION that carried a PoE record: which\n// wallet vkey(s) signed it, the fee, the outputs, and the co-published metadata\n// labels. It answers \"who authorised and paid for this anchoring\" — distinct\n// from the record-level COSE authorship signatures handled in `signatures.ts`.\n//\n// Unlike label-309 extraction, this decode is purely INFORMATIONAL: it is not\n// fed back into the structural validator, so it is not subject to the\n// canonical-CBOR byte-faithfulness concern that forces `cbor-walker` to slice\n// rather than decode. We therefore decode the body + witness-set slices with\n// the permissive CBOR decoder. The slices themselves are still byte-faithful —\n// `decodeTxWitnesses` verifies each signature against `blake2b256(txBody)`,\n// which only equals the on-chain transaction hash when the body bytes are\n// exactly as produced.\n\nimport { decodeCbor } from '@cardanowall/crypto-core/cbor';\nimport { blake2b224, blake2b256 } from '@cardanowall/crypto-core/hash';\nimport { verifyEd25519 } from '@cardanowall/crypto-core/sig';\n\nimport { bytesToHex } from '../hex';\nimport type { VerifyTxOutput, VerifyTxSummary, VerifyTxWitness } from './types';\n\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\nconst ED25519_SIGNATURE_LENGTH = 64;\n\n// Conway-era transaction body map keys (RFC-style integer keys).\nconst BODY_KEY_INPUTS = 0;\nconst BODY_KEY_OUTPUTS = 1;\nconst BODY_KEY_FEE = 2;\nconst BODY_KEY_INVALID_HEREAFTER = 3; // ttl\nconst BODY_KEY_INVALID_BEFORE = 8; // validity_interval_start\nconst BODY_KEY_REQUIRED_SIGNERS = 14;\nconst BODY_KEY_NETWORK_ID = 15;\n\n// Witness-set map keys. Key 0 is the vkey witness set; every other key\n// (native scripts, bootstrap witnesses, Plutus v1/v2/v3) is counted as a\n// \"script/other\" witness without being deep-decoded.\nconst WITNESS_KEY_VKEY = 0;\n\n// inputs, vkey_witnesses, and required_signers are CBOR sets (tag 258). The\n// permissive decoder may surface a set as a JS `Set` or an `Array` depending\n// on how the producer encoded it; normalise both to an array.\nfunction asArray(v: unknown): unknown[] {\n if (v instanceof Set) return [...v];\n if (Array.isArray(v)) return v;\n return [];\n}\n\nfunction asMap(v: unknown): Map<unknown, unknown> | null {\n return v instanceof Map ? v : null;\n}\n\n/**\n * Decode the vkey witnesses of a transaction and verify each signature against\n * the transaction body.\n *\n * Each Cardano vkey witness is `[vkey(32B), signature(64B)]`; the signed\n * message is `blake2b256(txBody)` (the transaction hash). A witness whose vkey\n * or signature is malformed, or whose signature does not verify, is reported\n * with `signature_valid: false` rather than dropped — the caller surfaces it\n * informationally and never fails the record on it.\n */\nexport function decodeTxWitnesses(\n witnessSetBytes: Uint8Array,\n txBodyBytes: Uint8Array,\n): VerifyTxWitness[] {\n const witnessSet = asMap(decodeCbor(witnessSetBytes));\n if (witnessSet === null) return [];\n const vkeyWitnesses = asArray(witnessSet.get(WITNESS_KEY_VKEY));\n const txHash = blake2b256(txBodyBytes);\n\n const out: VerifyTxWitness[] = [];\n for (const entry of vkeyWitnesses) {\n const pair = asArray(entry);\n const vkey = pair[0];\n const signature = pair[1];\n if (\n !(vkey instanceof Uint8Array) ||\n vkey.length !== ED25519_PUBLIC_KEY_LENGTH ||\n !(signature instanceof Uint8Array) ||\n signature.length !== ED25519_SIGNATURE_LENGTH\n ) {\n // A structurally malformed witness still describes an attempted\n // authorisation; surface what we can (when the vkey is a valid pubkey)\n // and mark the signature invalid.\n if (vkey instanceof Uint8Array && vkey.length === ED25519_PUBLIC_KEY_LENGTH) {\n out.push({\n type: 'vkey',\n vkey: bytesToHex(vkey),\n key_hash: bytesToHex(blake2b224(vkey)),\n signature_valid: false,\n });\n }\n continue;\n }\n let signatureValid: boolean;\n try {\n signatureValid = verifyEd25519({ publicKey: vkey, message: txHash, signature });\n } catch {\n signatureValid = false;\n }\n out.push({\n type: 'vkey',\n vkey: bytesToHex(vkey),\n key_hash: bytesToHex(blake2b224(vkey)),\n signature_valid: signatureValid,\n });\n }\n return out;\n}\n\n/**\n * Count the witness-set entries that are NOT vkey witnesses (native scripts,\n * bootstrap witnesses, Plutus v1/v2/v3). These are summed as a single\n * \"script/other\" count without deep-decoding their contents.\n */\nfunction countScriptWitnesses(witnessSetBytes: Uint8Array): number {\n const witnessSet = asMap(decodeCbor(witnessSetBytes));\n if (witnessSet === null) return 0;\n let count = 0;\n for (const [key, value] of witnessSet) {\n if (key === WITNESS_KEY_VKEY) continue;\n count += asArray(value).length;\n }\n return count;\n}\n\n/**\n * Decode a transaction body into a JSON-safe summary: fee, input/output counts,\n * the output addresses + lovelace amounts, validity interval, required signer\n * key hashes, and network id.\n *\n * All lovelace amounts are serialised as DECIMAL STRINGS so they survive JSON\n * round-trips exactly (Cardano coin values can exceed `Number.MAX_SAFE_INTEGER`\n * and BigInt is not JSON-native). Coin math is performed with BigInt internally.\n */\nexport function decodeTxSummary(\n txBodyBytes: Uint8Array,\n witnessSetBytes: Uint8Array,\n network: 'mainnet' | 'preprod',\n): VerifyTxSummary {\n const body = asMap(decodeCbor(txBodyBytes));\n if (body === null) {\n throw new RangeError('MALFORMED_CBOR: tx body is not a CBOR map');\n }\n\n const inputs = asArray(body.get(BODY_KEY_INPUTS));\n const outputsRaw = asArray(body.get(BODY_KEY_OUTPUTS));\n\n const outputs: VerifyTxOutput[] = [];\n let totalOutput = 0n;\n for (const o of outputsRaw) {\n const { addressBytes, lovelace } = readOutput(o);\n totalOutput += lovelace;\n outputs.push({\n address: encodeCardanoAddress(addressBytes, network),\n lovelace: lovelace.toString(),\n });\n }\n\n const requiredSigners = asArray(body.get(BODY_KEY_REQUIRED_SIGNERS))\n .filter((s): s is Uint8Array => s instanceof Uint8Array)\n .map((s) => bytesToHex(s));\n\n const summary: {\n -readonly [K in keyof VerifyTxSummary]: VerifyTxSummary[K];\n } = {\n fee_lovelace: coinToString(body.get(BODY_KEY_FEE)),\n input_count: inputs.length,\n output_count: outputs.length,\n outputs,\n total_output_lovelace: totalOutput.toString(),\n script_witness_count: countScriptWitnesses(witnessSetBytes),\n };\n\n const invalidBefore = body.get(BODY_KEY_INVALID_BEFORE);\n if (typeof invalidBefore === 'number') summary.invalid_before = invalidBefore;\n else if (typeof invalidBefore === 'bigint') summary.invalid_before = Number(invalidBefore);\n\n const invalidHereafter = body.get(BODY_KEY_INVALID_HEREAFTER);\n if (typeof invalidHereafter === 'number') summary.invalid_hereafter = invalidHereafter;\n else if (typeof invalidHereafter === 'bigint')\n summary.invalid_hereafter = Number(invalidHereafter);\n\n if (requiredSigners.length > 0) summary.required_signer_key_hashes = requiredSigners;\n\n const networkId = body.get(BODY_KEY_NETWORK_ID);\n if (typeof networkId === 'number') summary.network_id = networkId;\n else if (typeof networkId === 'bigint') summary.network_id = Number(networkId);\n\n return summary;\n}\n\n// A transaction output is EITHER a legacy array `[address, amount]` OR a map\n// `{0: address, 1: amount}` (post-Babbage). `amount` is either a bare coin\n// (uint) or a `[coin, multiasset]` pair — only the coin (lovelace) component is\n// summarised here.\nfunction readOutput(output: unknown): { addressBytes: Uint8Array; lovelace: bigint } {\n let address: unknown;\n let amount: unknown;\n if (Array.isArray(output)) {\n address = output[0];\n amount = output[1];\n } else if (output instanceof Map) {\n address = output.get(0);\n amount = output.get(1);\n } else {\n throw new RangeError('MALFORMED_CBOR: tx output is neither a CBOR array nor a CBOR map');\n }\n if (!(address instanceof Uint8Array)) {\n throw new RangeError('MALFORMED_CBOR: tx output address is not a byte string');\n }\n const lovelace = Array.isArray(amount) ? toBigInt(amount[0]) : toBigInt(amount);\n return { addressBytes: address, lovelace };\n}\n\nfunction coinToString(v: unknown): string {\n return toBigInt(v).toString();\n}\n\nfunction toBigInt(v: unknown): bigint {\n if (typeof v === 'bigint') return v;\n if (typeof v === 'number' && Number.isInteger(v)) return BigInt(v);\n throw new RangeError(`MALFORMED_CBOR: expected an integer coin value, got ${typeof v}`);\n}\n\n// -----------------------------------------------------------------------------\n// Cardano address bech32 encoding (BIP-173, the CIP-19 bech32 form).\n// -----------------------------------------------------------------------------\n//\n// Implemented inline so the published SDK keeps a minimal, auditable dependency\n// surface (the verifier's only third-party deps are the cryptographic core).\n// The header byte's high nibble is the address type and its low nibble is the\n// network id (0 = testnet, 1 = mainnet). Payment-address types 0–7 use the\n// `addr` HRP; stake/reward types 14–15 use the `stake` HRP. The header's\n// network nibble is authoritative for the `_test` suffix; the caller's\n// `network` argument is the fallback when a header is ambiguous.\n\nconst BECH32_CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';\n\nfunction encodeCardanoAddress(addressBytes: Uint8Array, network: 'mainnet' | 'preprod'): string {\n if (addressBytes.length === 0) {\n throw new RangeError('MALFORMED_CBOR: empty address byte string');\n }\n const header = addressBytes[0]!;\n const addressType = header >> 4;\n const networkNibble = header & 0x0f;\n const isStake = addressType === 14 || addressType === 15;\n // The header's network nibble is authoritative. Fall back to the caller's\n // network only when the nibble is not the canonical 0 (testnet) / 1 (mainnet).\n const isTestnet =\n networkNibble === 0 ? true : networkNibble === 1 ? false : network === 'preprod';\n const base = isStake ? 'stake' : 'addr';\n const hrp = isTestnet ? `${base}_test` : base;\n return bech32Encode(hrp, addressBytes);\n}\n\nfunction bech32Polymod(values: number[]): number {\n const generators = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n let chk = 1;\n for (const value of values) {\n const top = chk >> 25;\n chk = ((chk & 0x1ffffff) << 5) ^ value;\n for (let i = 0; i < 5; i++) {\n if ((top >> i) & 1) chk ^= generators[i]!;\n }\n }\n return chk;\n}\n\nfunction bech32HrpExpand(hrp: string): number[] {\n const out: number[] = [];\n for (let i = 0; i < hrp.length; i++) out.push(hrp.charCodeAt(i) >> 5);\n out.push(0);\n for (let i = 0; i < hrp.length; i++) out.push(hrp.charCodeAt(i) & 31);\n return out;\n}\n\n// 8-bit → 5-bit regrouping with zero-padding of the final group (the encode\n// direction always pads).\nfunction bech32ToWords(data: Uint8Array): number[] {\n let acc = 0;\n let bits = 0;\n const out: number[] = [];\n const maxv = (1 << 5) - 1;\n for (const value of data) {\n acc = (acc << 8) | value;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n out.push((acc >> bits) & maxv);\n }\n }\n if (bits > 0) out.push((acc << (5 - bits)) & maxv);\n return out;\n}\n\nfunction bech32Encode(hrp: string, data: Uint8Array): string {\n const words = bech32ToWords(data);\n const polymodInput = bech32HrpExpand(hrp).concat(words, [0, 0, 0, 0, 0, 0]);\n const polymod = bech32Polymod(polymodInput) ^ 1;\n const checksum: number[] = [];\n for (let i = 0; i < 6; i++) checksum.push((polymod >> (5 * (5 - i))) & 31);\n let result = `${hrp}1`;\n for (const w of words.concat(checksum)) result += BECH32_CHARSET.charAt(w);\n return result;\n}\n","// CIP-309 standalone verifier entry point.\n//\n// Pipeline (steps run sequentially; the verdict is the worst outcome across them):\n// 1. Resolve Cardano gateway + raw tx CBOR + confirmation depth.\n// 2. Byte-faithful extract of label-309 metadata.\n// 3. Structural validator (Part A; never throws).\n// 4. Confirmation-depth check → INSUFFICIENT_CONFIRMATIONS / verdict 'pending'.\n// 5. Profile-gated work (signed: signatures; sealed: enc structure;\n// recipient-sealed: decrypt). Out-of-profile fields emit\n// OUT_OF_PROFILE_SKIPPED (info) — not SCHEMA_UNKNOWN_FIELD.\n// 6. Merkle list-commitment verification (awaited after step 5).\n// 7. Three-state verdict emission with exit-code mapping.\n\nimport { SEVERITY, validatePoeRecord, type ValidationIssue } from '@cardanowall/poe-standard';\n\nimport { tryDecryptions } from './decrypt';\nimport { defaultFetchOutbound, wrapFetchOutbound } from './fetch';\nimport { verifyMerkleCommitments } from './merkle';\nimport { DEFAULT_PROFILE, planProfileSkips } from './profile';\nimport { extractLabel309Metadata, NotACip309RecordError, resolveCardanoTx } from './resolve';\nimport { verifyRecordSignatures } from './signatures';\nimport { sliceTxComponents } from './cbor-walker';\nimport { decodeTxSummary, decodeTxWitnesses } from './tx-witnesses';\nimport type {\n ExitCode,\n FetchOutbound,\n HttpCallRecord,\n Profile,\n VerifyItemDecryption,\n VerifyMerkleCheck,\n VerifyRecordSignature,\n VerifyReport,\n VerifyTxInput,\n VerifyUriCheck,\n Verdict,\n} from './types';\n\nexport const CONFIRMATION_DEPTH_THRESHOLD_DEFAULT = 15;\n\ntype MutableReport = { -readonly [K in keyof VerifyReport]: VerifyReport[K] };\n\nexport async function verifyTx(input: VerifyTxInput): Promise<VerifyReport> {\n const profile = input.profile ?? DEFAULT_PROFILE;\n const threshold = input.confirmationDepthThreshold ?? CONFIRMATION_DEPTH_THRESHOLD_DEFAULT;\n const httpCalls: HttpCallRecord[] = [];\n const fetchFn = wrapFetchOutbound(\n input.fetchOutbound ?? defaultFetchOutbound,\n httpCalls,\n input.denyHosts,\n );\n\n const base = (\n over: Partial<VerifyReport> & Pick<VerifyReport, 'verdict' | 'exit_code'>,\n ): VerifyReport => ({\n tx_hash: input.txHash,\n network: 'cardano:mainnet',\n profile,\n num_confirmations: 0,\n confirmation_depth_threshold: threshold,\n metadata_present: false,\n validation: { valid: false },\n http_calls: httpCalls,\n ...over,\n });\n\n // 1. Resolve Cardano gateway + raw tx CBOR.\n let resolved;\n try {\n resolved = await resolveCardanoTx({ input, fetchFn });\n } catch (e) {\n if (e instanceof NotACip309RecordError) {\n return base({\n verdict: 'failed',\n exit_code: 1,\n validation: {\n valid: false,\n issues: [issueOf('METADATA_NOT_FOUND', [], e.message)],\n },\n });\n }\n return base({\n verdict: 'failed',\n exit_code: 2,\n validation: {\n valid: false,\n issues: [issueOf('PROVIDER_UNAVAILABLE', [], (e as Error).message)],\n },\n });\n }\n\n // 2. Byte-faithful label-309 extraction.\n let metadataBytes: Uint8Array | null;\n try {\n metadataBytes = extractLabel309Metadata(resolved.txCbor);\n } catch (e) {\n return base({\n verdict: 'failed',\n exit_code: 1,\n num_confirmations: resolved.numConfirmations,\n block_time: resolved.blockTime,\n block_slot: resolved.blockSlot,\n validation: {\n valid: false,\n issues: [issueOf('MALFORMED_CBOR', [], (e as Error).message)],\n },\n });\n }\n if (metadataBytes === null) {\n return base({\n verdict: 'failed',\n exit_code: 1,\n num_confirmations: resolved.numConfirmations,\n block_time: resolved.blockTime,\n block_slot: resolved.blockSlot,\n metadata_present: false,\n validation: {\n valid: false,\n issues: [issueOf('METADATA_NOT_FOUND', [], 'no label-309 metadata on this tx')],\n },\n });\n }\n\n return verifyResolvedRecord({\n input,\n metadataBytes,\n txCbor: resolved.txCbor,\n numConfirmations: resolved.numConfirmations,\n blockTime: resolved.blockTime,\n blockSlot: resolved.blockSlot,\n httpCalls,\n fetchFn,\n });\n}\n\n/**\n * `verifyResolved` — same pipeline as `verifyTx` starting from step 3\n * (structural validator). The caller has already resolved the label-309\n * metadata bytes + block-info tuple from somewhere other than a live chain\n * fetch (typically an indexer database mirror).\n *\n * Use this when you trust an upstream indexer for the (metadataCbor,\n * blockTime, blockSlot, numConfirmations) tuple and want to skip the\n * /tx_cbor + /tx_info round-trip. The caller is responsible for the\n * confidence that the supplied bytes actually came from a CIP-309 label-309\n * metadata field of a confirmed Cardano transaction.\n */\nexport async function verifyResolved(input: {\n txHash: string;\n metadataCbor: Uint8Array;\n // Raw on-chain transaction CBOR. When supplied, the report also carries the\n // transaction-level description (tx_witnesses, tx_summary, metadata_labels);\n // when absent, those three fields are left undefined. The label-309 record\n // is always taken from `metadataCbor`, never re-derived from `txCbor`.\n txCbor?: Uint8Array;\n numConfirmations: number;\n blockTime?: number;\n blockSlot?: number;\n network?: VerifyReport['network'];\n cardanoNetwork?: VerifyTxInput['cardanoNetwork'];\n profile?: Profile;\n confirmationDepthThreshold?: number;\n fetchOutbound?: FetchOutbound;\n denyHosts?: ReadonlyArray<string>;\n decryption?: VerifyTxInput['decryption'];\n // Mirrors `VerifyTxInput.verifyMerkle`. SSR callers pass `false` so the\n // viewer renders from indexed CBOR alone with no Arweave/IPFS leaves-list\n // fetch (deferred to a user-initiated client-side action instead).\n verifyMerkle?: boolean;\n}): Promise<VerifyReport> {\n const httpCalls: HttpCallRecord[] = [];\n const fetchFn = wrapFetchOutbound(\n input.fetchOutbound ?? defaultFetchOutbound,\n httpCalls,\n input.denyHosts,\n );\n // Reuse the post-resolve pipeline by adapting the caller's args back into\n // the VerifyTxInput shape that signature/decryption/merkle helpers expect.\n const verifyTxInput: VerifyTxInput = {\n txHash: input.txHash,\n ...(input.profile !== undefined ? { profile: input.profile } : {}),\n ...(input.cardanoNetwork !== undefined ? { cardanoNetwork: input.cardanoNetwork } : {}),\n ...(input.confirmationDepthThreshold !== undefined\n ? { confirmationDepthThreshold: input.confirmationDepthThreshold }\n : {}),\n ...(input.fetchOutbound !== undefined ? { fetchOutbound: input.fetchOutbound } : {}),\n ...(input.denyHosts !== undefined ? { denyHosts: input.denyHosts } : {}),\n ...(input.decryption !== undefined ? { decryption: input.decryption } : {}),\n ...(input.verifyMerkle !== undefined ? { verifyMerkle: input.verifyMerkle } : {}),\n };\n const report = await verifyResolvedRecord({\n input: verifyTxInput,\n metadataBytes: input.metadataCbor,\n ...(input.txCbor !== undefined ? { txCbor: input.txCbor } : {}),\n numConfirmations: input.numConfirmations,\n ...(input.blockTime !== undefined ? { blockTime: input.blockTime } : {}),\n ...(input.blockSlot !== undefined ? { blockSlot: input.blockSlot } : {}),\n httpCalls,\n fetchFn,\n });\n if (input.network !== undefined) {\n return { ...report, network: input.network };\n }\n return report;\n}\n\nasync function verifyResolvedRecord(args: {\n input: VerifyTxInput;\n metadataBytes: Uint8Array;\n txCbor?: Uint8Array;\n numConfirmations: number;\n blockTime?: number;\n blockSlot?: number;\n httpCalls: HttpCallRecord[];\n fetchFn: ReturnType<typeof wrapFetchOutbound>;\n}): Promise<VerifyReport> {\n const {\n input,\n metadataBytes,\n txCbor,\n numConfirmations,\n blockTime,\n blockSlot,\n httpCalls,\n fetchFn,\n } = args;\n const profile = input.profile ?? DEFAULT_PROFILE;\n const threshold = input.confirmationDepthThreshold ?? CONFIRMATION_DEPTH_THRESHOLD_DEFAULT;\n\n // Transaction-level description — who authorised/paid for the anchoring,\n // distinct from record-level authorship. Decoded once when the raw tx CBOR\n // is available, then merged into every report shape below. This is pure\n // description: it never gates on profile and never changes the verdict.\n const txDescription = txCbor !== undefined ? decodeTxDescription(txCbor, input) : {};\n\n const base = (\n over: Partial<VerifyReport> & Pick<VerifyReport, 'verdict' | 'exit_code'>,\n ): VerifyReport => ({\n tx_hash: input.txHash,\n network: 'cardano:mainnet',\n profile,\n num_confirmations: 0,\n confirmation_depth_threshold: threshold,\n metadata_present: false,\n validation: { valid: false },\n http_calls: httpCalls,\n ...txDescription,\n ...over,\n });\n\n // 3. Structural validator (Part A).\n const validation = validatePoeRecord(metadataBytes);\n if (!validation.ok) {\n return base({\n verdict: 'failed',\n exit_code: 1,\n num_confirmations: numConfirmations,\n ...(blockTime !== undefined ? { block_time: blockTime } : {}),\n ...(blockSlot !== undefined ? { block_slot: blockSlot } : {}),\n metadata_present: true,\n validation: { valid: false, issues: validation.issues },\n });\n }\n const record = validation.record;\n\n // 4. Confirmation-depth — a record below the reorg-safety threshold is\n // well-formed but not yet final, so INSUFFICIENT_CONFIRMATIONS short-circuits\n // to verdict `'pending'` (exit 3), NOT `'failed'`.\n if (numConfirmations < threshold) {\n return base({\n verdict: 'pending',\n exit_code: 3,\n num_confirmations: numConfirmations,\n ...(blockTime !== undefined ? { block_time: blockTime } : {}),\n ...(blockSlot !== undefined ? { block_slot: blockSlot } : {}),\n metadata_present: true,\n record,\n validation: {\n valid: false,\n issues: [\n issueOf('INSUFFICIENT_CONFIRMATIONS', [], `${numConfirmations} < threshold ${threshold}`),\n ],\n },\n });\n }\n\n // 5. Build optimistic report; mutate verdict on per-check failure.\n const initialWarnings = (validation.warnings ?? []).slice();\n const initialInfo = (validation.info ?? []).slice();\n const plan = planProfileSkips(profile, record);\n initialInfo.push(...plan.skips);\n\n // (Note: a `MERKLE_UNSUPPORTED` escalation — a verifier reading a\n // merkle-only record without implementing Merkle — never fires here because\n // this reference verifier always runs the Merkle subsystem at every profile.\n // A future `core - merkle` opt-out would emit MERKLE_UNSUPPORTED at info\n // severity when items[] also commits content, error severity otherwise.)\n\n const reportShape: VerifyReport = {\n tx_hash: input.txHash,\n network: 'cardano:mainnet',\n profile,\n num_confirmations: numConfirmations,\n confirmation_depth_threshold: threshold,\n ...(blockTime !== undefined ? { block_time: blockTime } : {}),\n ...(blockSlot !== undefined ? { block_slot: blockSlot } : {}),\n metadata_present: true,\n validation: composeValidation(true, undefined, initialWarnings, initialInfo),\n record,\n ...txDescription,\n http_calls: httpCalls,\n verdict: 'valid',\n exit_code: 0,\n };\n const report: MutableReport = { ...reportShape };\n const uriChecks: VerifyUriCheck[] = [];\n\n // `verifyMerkle === false` is the offline switch: it suppresses EVERY\n // outbound URI fetch the verifier would otherwise issue past the\n // chain/indexer resolve step — both the sealed-item ciphertext download in\n // decryption (5b) and the Merkle leaves-list fetch (6). Offline callers\n // (server-rendered viewers, CLI `--no-fetch`) get a report built from\n // indexed CBOR plus any caller-supplied out-of-band bytes alone.\n const allowUriFetch = input.verifyMerkle ?? true;\n\n // 5a. Record-level signatures (profile >= 'signed').\n if (plan.verifySignatures && record.sigs && record.sigs.length > 0) {\n const sigOut: VerifyRecordSignature[] = await verifyRecordSignatures({ record, input });\n report.record_signatures = sigOut;\n if (recordSignaturesShouldFail(sigOut)) {\n report.verdict = 'failed';\n report.exit_code = 1;\n }\n }\n\n // 5b. Decryption (profile >= 'recipient-sealed' AND caller supplied keys).\n if (plan.verifyDecrypt && input.decryption && input.decryption.length > 0) {\n const dec = await tryDecryptions({\n record,\n input,\n fetchFn,\n httpCalls,\n uriChecksOut: uriChecks,\n allowUriFetch,\n });\n report.item_decryptions = dec.results;\n const decFailure = decryptionsShouldFail(dec.results);\n if (decFailure !== null) {\n report.verdict = 'failed';\n report.exit_code = decFailure === 'network' ? 2 : 1;\n }\n }\n\n // 6. Merkle commitments (always in `core` and above; only escalates verdict\n // to `'failed'` on `MERKLE_ROOT_MISMATCH` / leaf-count mismatch — leaves\n // unavailability stays at warning).\n //\n // Suppressed entirely when the offline switch is set (see `allowUriFetch`)\n // so a server-rendered viewer produces a VerifyReport from indexed CBOR\n // alone, with zero outbound fetches to Arweave/IPFS gateways. The on-record\n // `merkle[]` data (alg, root, leaf_count, uris) survives unchanged on\n // `report.record`; only the defence-in-depth re-root + leaf-count check is\n // suppressed. A user-initiated client-side flow performs the same\n // verification at click time.\n if (allowUriFetch && Array.isArray(record.merkle) && record.merkle.length > 0) {\n const merkle = await verifyMerkleCommitments({\n record,\n input,\n fetchFn,\n uriChecksOut: uriChecks,\n });\n report.merkle_checks = merkle.checks;\n const merkleFailure = merkleChecksShouldFail(merkle.checks);\n if (merkleFailure && report.verdict === 'valid') {\n report.verdict = 'failed';\n report.exit_code = 1;\n }\n }\n\n if (uriChecks.length > 0) {\n report.uri_checks = uriChecks;\n }\n\n return report;\n}\n\n// ─── Internals ────────────────────────────────────────────────────────────────\n\n// Decode the transaction-level description (witnesses, summary, co-published\n// metadata labels) from raw tx CBOR. This is purely informational, so a decode\n// failure must NOT propagate into the verdict — it degrades to omitting the\n// affected fields. The label-309 record is validated separately from\n// `metadataBytes`; this view only describes the carrying transaction.\ntype TxDescriptionFields = Pick<VerifyReport, 'tx_witnesses' | 'tx_summary' | 'metadata_labels'>;\nfunction decodeTxDescription(txCbor: Uint8Array, input: VerifyTxInput): TxDescriptionFields {\n const network = input.cardanoNetwork ?? 'mainnet';\n const out: { -readonly [K in keyof TxDescriptionFields]: TxDescriptionFields[K] } = {};\n let components;\n try {\n components = sliceTxComponents(txCbor);\n } catch {\n return out;\n }\n out.metadata_labels = components.auxMetadataLabels;\n try {\n out.tx_witnesses = decodeTxWitnesses(components.witnessSet, components.txBody);\n } catch {\n // leave tx_witnesses undefined\n }\n try {\n out.tx_summary = decodeTxSummary(components.txBody, components.witnessSet, network);\n } catch {\n // leave tx_summary undefined\n }\n return out;\n}\n\n// A public hash-only PoE stays valid even when every signature entry is\n// SIGNATURE_UNSUPPORTED — the content claim does not depend on signer identity,\n// so an unverifiable algorithm is informational, not fatal. Any OTHER failure\n// (MALFORMED_SIG_COSE_SIGN1, SIGNER_KEY_UNRESOLVED, SIGNATURE_INVALID,\n// WALLET_ADDRESS_MISMATCH) fails the record.\nfunction recordSignaturesShouldFail(sigs: ReadonlyArray<VerifyRecordSignature>): boolean {\n return sigs.some((s) => s.verdict === 'invalid' || s.verdict === 'unresolved');\n}\n\n// Returns null on success, 'network' for CONTENT_UNAVAILABLE / IPFS-no-gateway\n// (exit 2), or 'integrity' for any other failure (exit 1).\nfunction decryptionsShouldFail(\n results: ReadonlyArray<VerifyItemDecryption>,\n): 'network' | 'integrity' | null {\n let saw: 'network' | 'integrity' | null = null;\n for (const d of results) {\n if (d.verdict === 'decrypted' && d.plaintext_hash_ok !== false) continue;\n if (d.verdict === 'content-unavailable' || d.verdict === 'ciphertext-unavailable') {\n saw = saw === 'integrity' ? 'integrity' : 'network';\n continue;\n }\n saw = 'integrity';\n }\n return saw;\n}\n\nfunction merkleChecksShouldFail(checks: ReadonlyArray<VerifyMerkleCheck>): boolean {\n for (const c of checks) {\n if (c.verdict === 'mismatch') return true;\n // `unavailable`, `format-unsupported`, and `unsupported` are warning/\n // info-severity — the on-chain root is structurally valid on its own, so\n // they do NOT escalate to verdict 'failed'.\n }\n return false;\n}\n\nfunction issueOf(\n code: keyof typeof SEVERITY,\n path: ReadonlyArray<string | number>,\n message: string,\n): ValidationIssue {\n return { code, path, message, severity: SEVERITY[code] };\n}\n\nfunction composeValidation(\n valid: boolean,\n issues: ReadonlyArray<ValidationIssue> | undefined,\n warnings: ReadonlyArray<ValidationIssue>,\n info: ReadonlyArray<ValidationIssue>,\n): VerifyReport['validation'] {\n const out: {\n valid: boolean;\n issues?: ReadonlyArray<ValidationIssue>;\n warnings?: ReadonlyArray<ValidationIssue>;\n info?: ReadonlyArray<ValidationIssue>;\n } = { valid };\n if (issues !== undefined && issues.length > 0) out.issues = issues;\n if (warnings.length > 0) out.warnings = warnings;\n if (info.length > 0) out.info = info;\n return out;\n}\n\n// Convenience re-export so callers can map verdicts to exit codes without\n// importing the union shape.\nexport function exitCodeForVerdict(report: VerifyReport): ExitCode {\n return report.exit_code;\n}\n\nexport type { Verdict, ExitCode };\n","#!/usr/bin/env node\n// Conformance CLI: single-tx verification against the CIP-309 standalone\n// verifier.\n//\n// Exit codes (extended with 4 for CLI input errors):\n// 0 = valid, 1 = failed (integrity), 2 = failed (network),\n// 3 = pending, 4 = CLI input error\n\nimport { KOIOS_MAINNET_URL, exitCodeForVerdict, verifyTx } from '../verifier/index';\n\nconst VERSION = '0.1.0';\n\ninterface ParsedArgs {\n readonly txHash: string | undefined;\n readonly gateways: ReadonlyArray<string>;\n readonly threshold: number | undefined;\n readonly json: boolean;\n readonly showHelp: boolean;\n readonly showVersion: boolean;\n readonly error: string | undefined;\n}\n\nexport function parseArgs(args: ReadonlyArray<string>): ParsedArgs {\n let txHash: string | undefined;\n const gateways: string[] = [];\n let threshold: number | undefined;\n let json = true;\n let showHelp = false;\n let showVersion = false;\n let error: string | undefined;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]!;\n if (arg === '--help' || arg === '-h') {\n showHelp = true;\n } else if (arg === '--version' || arg === '-V') {\n showVersion = true;\n } else if (arg === '--json') {\n json = true;\n } else if (arg === '--gateway') {\n const v = args[++i];\n if (v === undefined) {\n error = '--gateway requires a value';\n break;\n }\n gateways.push(v);\n } else if (arg === '--threshold') {\n const v = args[++i];\n const n = Number(v);\n if (v === undefined || !Number.isFinite(n) || !Number.isInteger(n) || n < 0) {\n error = '--threshold requires a non-negative integer';\n break;\n }\n threshold = n;\n } else if (arg.startsWith('-')) {\n error = `unknown flag: ${arg}`;\n break;\n } else if (txHash === undefined) {\n txHash = arg;\n } else {\n error = `unexpected positional argument: ${arg}`;\n break;\n }\n }\n\n return { txHash, gateways, threshold, json, showHelp, showVersion, error };\n}\n\nconst USAGE = `Usage: cardanowall-sdk-conformance <tx-hash> [--gateway <url>] [--threshold <n>] [--json]\n cardanowall-sdk-conformance --version\n cardanowall-sdk-conformance --help\n\nRuns the @cardanowall/sdk-ts standalone CIP-309 verifier against a single\nCardano transaction. Exit codes:\n 0 = valid, 1 = failed (integrity), 2 = failed (network), 3 = pending,\n 4 = CLI input error.`;\n\nexport interface RunIO {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport async function run(args: ReadonlyArray<string>, io: RunIO): Promise<number> {\n const parsed = parseArgs(args);\n if (parsed.showHelp) {\n io.stdout(USAGE + '\\n');\n return 0;\n }\n if (parsed.showVersion) {\n io.stdout(`cardanowall-sdk-conformance ${VERSION}\\n`);\n return 0;\n }\n if (parsed.error !== undefined) {\n io.stderr(`cardanowall-sdk-conformance: ${parsed.error}\\n`);\n io.stderr(USAGE + '\\n');\n return 4;\n }\n if (parsed.txHash === undefined) {\n io.stderr('cardanowall-sdk-conformance: <tx-hash> is required\\n');\n io.stderr(USAGE + '\\n');\n return 4;\n }\n if (!/^[0-9a-f]{64}$/i.test(parsed.txHash)) {\n io.stderr(\n `cardanowall-sdk-conformance: invalid tx-hash (expected 64 hex chars): ${parsed.txHash}\\n`,\n );\n return 4;\n }\n\n const gateways = parsed.gateways.length > 0 ? parsed.gateways : [KOIOS_MAINNET_URL];\n\n try {\n const report = await verifyTx({\n txHash: parsed.txHash.toLowerCase(),\n cardanoGatewayChain: gateways,\n ...(parsed.threshold !== undefined ? { confirmationDepthThreshold: parsed.threshold } : {}),\n });\n io.stdout(JSON.stringify(report, null, 2) + '\\n');\n return exitCodeForVerdict(report);\n } catch (err) {\n io.stderr(\n `cardanowall-sdk-conformance: verifier error: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n return 2;\n }\n}\n\n// Only run as a script when invoked directly (not when imported by tests).\nif (/cli\\.(c?js|ts)$/.test(process.argv[1] ?? '')) {\n void run(process.argv.slice(2), {\n stdout: (text) => process.stdout.write(text),\n stderr: (text) => process.stderr.write(text),\n }).then((code) => process.exit(code));\n}\n"]}
1
+ {"version":3,"sources":["../../src/verifier/types.ts","../../../poe-standard/src/schema.ts","../../../crypto-core/src/cbor/errors.ts","../../../crypto-core/src/cbor/canonical.ts","../../../crypto-core/src/cbor/permissive.ts","../../../poe-standard/src/encoder.ts","../../../crypto-core/src/hash/blake2b-256.ts","../../../crypto-core/src/sig/ed25519.ts","../../../crypto-core/src/util/compare-ct.ts","../../../crypto-core/src/cose/errors.ts","../../../crypto-core/src/cose/sign1.ts","../../../crypto-core/src/cose/cose-key.ts","../../../poe-standard/src/chunked.ts","../../../poe-standard/src/error-codes.ts","../../../poe-standard/src/validator.ts","../../../crypto-core/src/kdf/argon2id.ts","../../../crypto-core/src/aead/errors.ts","../../../crypto-core/src/aead/xchacha20-poly1305.ts","../../../crypto-core/src/hash/sha-256.ts","../../../crypto-core/src/hash/merkle-sha2-256.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/utils.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/_crystals.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/ml-kem.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/hybrid.ts","../../../crypto-core/src/aead/chacha20-poly1305.ts","../../../crypto-core/src/kdf/hkdf.ts","../../../crypto-core/src/kem/mlkem768x25519.ts","../../../crypto-core/src/kem/x25519.ts","../../../crypto-core/src/sealed-poe/errors.ts","../../../crypto-core/src/sealed-poe/slots-codec.ts","../../../crypto-core/src/sealed-poe/wrap.ts","../../../crypto-core/src/sealed-poe/unwrap.ts","../../../crypto-core/src/sealed-poe/envelope-from-parsed.ts","../../src/fetch/fetch-outbound.ts","../../src/verifier/fetch.ts","../../src/verifier/decrypt.ts","../../../crypto-core/src/merkle/leaves-list.ts","../../src/verifier/merkle.ts","../../src/verifier/profile.ts","../../src/verifier/cbor-walker.ts","../../src/verifier/resolve.ts","../../src/hex.ts","../../src/verifier/signatures.ts","../../src/verifier/tx-witnesses.ts","../../src/verifier/verify.ts","../../src/conformance/cli.ts"],"names":["decode","hashes","CanonicalCborError","encodeCanonicalCbor","encode","sortCoreDeterministic","decodeCanonicalCbor","cdeDecodeOptions","mapDecodeError","opts","UTF8_ENCODER","issue","j","sha256","nobleSha256","blake2b","blake2b224","randb","abytes_","N","Q","F","ROOT_OF_UNITY","z","shake256","abytes","sha3_256","concatBytes","AeadVerificationError","chacha20poly1305","xchacha20Poly1305Decrypt","xchacha20poly1305","hkdf","x25519","compareCt","ZERO_NONCE_12","EMPTY_SALT","X25519_SECRET_KEY_LENGTH","X25519_PUBLIC_KEY_LENGTH","NONCE_LENGTH","WRAP_LENGTH","SLOTS_MAC_LENGTH","concat","hmac","LEAF_PREFIX","NODE_PREFIX","DIGEST_LENGTH","validateLeaves","merkleSha2256Root","mthRecursive","largestPow2Lt","hashLeaf","hashNode","ED25519_PUBLIC_KEY_LENGTH","ed2","sha512","L","leBytesToBigInt","verifyEd25519","asMap"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8CO,IAAM,YAAA,GAAkD,OAAO,MAAA,CAAO;AAAA,EAC3E,IAAA,EAAM,CAAA;AAAA,EACN,MAAA,EAAQ,CAAA;AAAA,EACR,MAAA,EAAQ,CAAA;AAAA,EACR,kBAAA,EAAoB;AACtB,CAAC,CAAA;ACbM,IAAM,0BAA0B,CAAA,CACpC,KAAA;AAAA,EACC,CAAA,CAAE,UAAA,CAAW,UAAU,CAAA,CAAE,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,MAAA,IAAU,CAAA,IAAK,CAAA,CAAE,MAAA,IAAU,EAAA,EAAI;AAAA,IACtE,MAAA,EAAQ,EAAE,IAAA,EAAM,iBAAA;AAAkB,GACnC;AACH,CAAA,CACC,IAAI,CAAC,CAAA;AAMR,IAAM,YAAA,GAAe,IAAI,WAAA,EAAY;AAC9B,IAAM,sBAAsB,CAAA,CAChC,KAAA;AAAA,EACC,CAAA,CAAE,QAAO,CAAE,MA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AA4B,MAAA,CAAO,SAAA,EAAU,GAAI;AAAC,KAC1F,CAAA;AACD,IAAA,EAAA,CAAG,OAAO,IAAA,CAAK,SAAA,CAAU,QAAQ,IAAA,EAAM,CAAC,IAAI,IAAI,CAAA;AAChD,IAAA,OAAO,mBAAmB,MAAM,CAAA;AAAA,EAClC,SAAS,GAAA,EAAK;AACZ,IAAA,EAAA,CAAG,MAAA;AAAA,MACD,gDAAgD,GAAA,YAAe,KAAA,GAAQ,IAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC;AAAA;AAAA,KAClG;AACA,IAAA,OAAO,CAAA;AAAA,EACT;AACF;AAGA,IAAI,kBAAkB,IAAA,CAAK,OAAA,CAAQ,KAAK,CAAC,CAAA,IAAK,EAAE,CAAA,EAAG;AACjD,EAAA,KAAK,GAAA,CAAI,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,EAAG;AAAA,IAC9B,QAAQ,CAAC,IAAA,KAAS,OAAA,CAAQ,MAAA,CAAO,MAAM,IAAI,CAAA;AAAA,IAC3C,QAAQ,CAAC,IAAA,KAAS,OAAA,CAAQ,MAAA,CAAO,MAAM,IAAI;AAAA,GAC5C,EAAE,IAAA,CAAK,CAAC,SAAS,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA;AACtC","file":"cli.js","sourcesContent":["// Public types for the Label 309 standalone verifier.\n//\n// The verifier is service-independent: it depends only on the operator-supplied\n// Cardano / Arweave / IPFS gateway chains and a `denyHosts` policy. Every\n// outbound network call routes through `fetchOutbound` (single egress point)\n// and lands in `VerifyReport.httpCalls` for audit.\n\nimport type { PoeRecord, ValidationIssue } from '@cardanowall/poe-standard';\n\nimport type { FetchOutbound, HttpCallRecord } from '../fetch/fetch-outbound';\n\n// -----------------------------------------------------------------------------\n// Verdict / exit-code\n// -----------------------------------------------------------------------------\n//\n// `'valid'` → exit 0 — every check returned ok.\n// `'pending'` → exit 3 — INSUFFICIENT_CONFIRMATIONS (record well-formed but\n// below the verifier's reorg-safety threshold).\n// `'failed'` → exit 1 — integrity / structural / signature class.\n// → exit 2 — network class (CONTENT_UNAVAILABLE, PROVIDER_UNAVAILABLE).\n\nexport type Verdict = 'valid' | 'pending' | 'failed';\nexport type ExitCode = 0 | 1 | 2 | 3;\n\n// -----------------------------------------------------------------------------\n// Conformance profile\n// -----------------------------------------------------------------------------\n//\n// Strict-superset order: each higher profile reads everything below it plus\n// one additional surface. A verifier of a LOWER profile that sees a field\n// belonging to a HIGHER profile MUST emit `OUT_OF_PROFILE_SKIPPED`\n// (info-severity) and continue — it MUST NOT report the record as invalid.\n\nexport type Profile = 'core' | 'signed' | 'sealed' | 'recipient-sealed';\n\n// -----------------------------------------------------------------------------\n// Network identifier — mainnet-only policy.\n// -----------------------------------------------------------------------------\n//\n// Cardano mainnet only; testnet is explicitly out-of-scope by project\n// policy. The literal `'cardano:mainnet'` is the wire-canonical\n// identifier surfaced in every VerifyReport so a downstream consumer never has\n// to infer which network the record was anchored on.\n\nexport type Network = 'cardano:mainnet';\n\nexport const PROFILE_RANK: Readonly<Record<Profile, number>> = Object.freeze({\n core: 0,\n signed: 1,\n sealed: 2,\n 'recipient-sealed': 3,\n});\n\n// -----------------------------------------------------------------------------\n// FetchOutbound (the verifier's only network egress point)\n// -----------------------------------------------------------------------------\n\nexport type {\n FetchOutbound,\n FetchOutboundOptions,\n FetchOutboundResult,\n HttpCallRecord,\n} from '../fetch/fetch-outbound';\n\n// -----------------------------------------------------------------------------\n// Verifier issue surface — re-exports the validator's `ValidationIssue` so\n// downstream consumers can dispatch on a single union (`ErrorCode` covers\n// both Part A and Part B per `@cardanowall/poe-standard`).\n// -----------------------------------------------------------------------------\n\nexport type { ValidationIssue } from '@cardanowall/poe-standard';\n\n// -----------------------------------------------------------------------------\n// VerifyTx input — discriminated decryption union.\n// -----------------------------------------------------------------------------\n\nexport interface VerifyTxInput {\n readonly txHash: string; // lowercase hex, no 0x prefix\n readonly profile?: Profile; // default 'recipient-sealed' (full pipeline)\n readonly cardanoGatewayChain?: ReadonlyArray<string>; // Koios-compatible URLs, in order\n readonly blockfrostProjectId?: string; // enables Blockfrost fallback\n readonly arweaveGatewayChain?: ReadonlyArray<string>;\n readonly ipfsGatewayChain?: ReadonlyArray<string>;\n readonly confirmationDepthThreshold?: number; // default 15; verifier-policy floor\n readonly denyHosts?: ReadonlyArray<string>; // service-independence guard\n // Master offline switch for the verifier's outbound URI fetches. When\n // `false`, the verifier neither fetches a sealed item's `uris[]` ciphertext\n // (decryption falls back to caller-supplied `ciphertextBytes` only) nor the\n // Merkle list-commitment leaves-list — so a Merkle-bearing or sealed record\n // verifies with ZERO egress beyond the chain/indexer resolve step. The\n // on-record `record.merkle[]` / `items[].uris[]` data round-trips through\n // `record` unchanged; only the verifier's defence-in-depth recompute and the\n // ciphertext download are suppressed. Defaults to `true` (full pipeline).\n // Server-rendered pages flip this to `false` so hash-only / merkle-only /\n // sealed records render from indexed CBOR alone, with the leaves-list and\n // ciphertext fetches deferred to a user-initiated client-side action.\n readonly verifyMerkle?: boolean;\n // Out-of-band sealed-PoE decryption attempts. The verifier dispatches by\n // inspecting `items[i].enc.slots` vs `items[i].enc.passphrase` presence; a\n // mismatched entry surfaces as WRONG_DECRYPTION_INPUT_SHAPE.\n readonly decryption?: ReadonlyArray<\n | { readonly itemIndex: number; readonly recipientSecretKey: Uint8Array }\n | { readonly itemIndex: number; readonly passphrase: string }\n >;\n // Out-of-band ciphertext bytes (keyed by item index). When supplied, takes\n // precedence over `items[i].uris[]` (no network fetch is issued).\n readonly ciphertextBytes?: Readonly<Record<number, Uint8Array>>;\n // Out-of-band Merkle leaves-list bytes (keyed by `record.merkle[i]` index).\n // CBOR is the normative wire form.\n readonly merkleLeaves?: Readonly<Record<number, Uint8Array>>;\n // For stake-address binding (path-2 wallet signatures). The\n // verifier recomputes `network_header || Blake2b-224(pubkey)` and compares\n // to the protected-header `address` field; mismatch emits\n // WALLET_ADDRESS_MISMATCH. Defaults to 'mainnet' when omitted; 'preprod' is\n // supplied only by callers running against the Cardano preprod testnet\n // (worker dev mode, future receiver-side scanner on preprod). The\n // wire-canonical `VerifyReport.network` field stays pinned to\n // 'cardano:mainnet' — this input only governs the stake-byte used for\n // path-2 address derivation.\n readonly cardanoNetwork?: 'mainnet' | 'preprod';\n // Injected for tests; defaults to fetchOutbound (the single egress point).\n readonly fetchOutbound?: FetchOutbound;\n}\n\n// -----------------------------------------------------------------------------\n// VerifyReport shape.\n// -----------------------------------------------------------------------------\n\nexport type SignatureVerdict = 'valid' | 'invalid' | 'unsupported' | 'unresolved';\nexport type SignatureFailureReason =\n | 'MALFORMED_SIG_COSE_SIGN1'\n | 'SIGNATURE_UNSUPPORTED'\n | 'SIGNER_KEY_UNRESOLVED'\n | 'SIGNATURE_INVALID'\n | 'WALLET_ADDRESS_MISMATCH';\n\nexport type SignerType = 'in-signature-kid' | 'wallet-inline-key';\n\nexport interface VerifyRecordSignature {\n readonly index: number;\n readonly verdict: SignatureVerdict;\n readonly signer_pub?: string; // lowercase hex of 32-byte Ed25519 pubkey when resolved\n readonly signer_type?: SignerType;\n readonly reason?: SignatureFailureReason;\n}\n\nexport type DecryptionVerdict =\n | 'decrypted'\n | 'wrong-key'\n | 'tampered-header'\n | 'tampered-ciphertext'\n | 'wrong-input-shape'\n | 'no-enc-envelope'\n | 'ciphertext-unavailable'\n | 'content-unavailable'\n | 'skipped'\n | 'kdf-failed';\n\nexport interface VerifyItemDecryption {\n readonly item_index: number;\n readonly verdict: DecryptionVerdict;\n // True iff every content-hash entry in `items[i].hashes` recomputes to the\n // recovered plaintext. Always a concrete boolean on `verdict === 'decrypted'`.\n readonly plaintext_hash_ok?: boolean;\n readonly reason?: string;\n}\n\nexport type ItemHashCheck = {\n readonly item_index: number;\n readonly alg: string;\n readonly ok: boolean;\n};\n\nexport type MerkleVerdict =\n | 'valid'\n | 'mismatch'\n | 'unavailable'\n | 'format-unsupported'\n | 'unsupported';\n\nexport interface VerifyMerkleCheck {\n readonly merkle_index: number;\n readonly alg: string;\n readonly verdict: MerkleVerdict;\n readonly root_recomputed?: Uint8Array;\n readonly reason?: string;\n}\n\nexport interface VerifyUriCheck {\n readonly item_index: number;\n readonly uri: string;\n readonly ok: boolean;\n readonly reason?: string;\n}\n\n// -----------------------------------------------------------------------------\n// Transaction-level description — DISTINCT from record-level authorship.\n// -----------------------------------------------------------------------------\n//\n// These surfaces describe the Cardano transaction that carried the PoE: which\n// wallet vkey(s) authorised/paid for it, the fee, and the outputs. This is the\n// \"who submitted and paid for this anchoring\" view — orthogonal to\n// `record_signatures`, which is the optional Label 309 record-level authorship\n// claim. A failed `signature_valid` here is INFORMATIONAL: it never changes the\n// verifier's verdict (the content claim does not depend on who paid the fee).\n\nexport interface VerifyTxWitness {\n readonly type: 'vkey';\n readonly vkey: string; // hex 32B Ed25519 pubkey\n readonly key_hash: string; // hex 28B Blake2b-224(vkey)\n readonly signature_valid: boolean; // Ed25519.verify(sig, blake2b256(tx_body), vkey)\n}\n\nexport interface VerifyTxOutput {\n readonly address: string; // bech32\n readonly lovelace: string; // decimal string\n}\n\nexport interface VerifyTxSummary {\n readonly fee_lovelace: string; // decimal string\n readonly input_count: number;\n readonly output_count: number;\n readonly outputs: ReadonlyArray<VerifyTxOutput>;\n readonly total_output_lovelace: string; // decimal string\n readonly script_witness_count: number;\n readonly invalid_before?: number;\n readonly invalid_hereafter?: number;\n readonly required_signer_key_hashes?: ReadonlyArray<string>;\n readonly network_id?: number;\n}\n\n// VerifyReport is snake_case end-to-end: the wire shape, the SDK's in-memory\n// representation, and every consumer-facing field share the same identifier\n// grammar. No transformer layer between the verifier and the API response —\n// `VerifyReport` IS the wire body for `POST /api/v1/records/{tx_hash}/verify`.\nexport interface VerifyReport {\n readonly tx_hash: string;\n readonly network: Network;\n readonly verdict: Verdict;\n readonly exit_code: ExitCode;\n readonly profile: Profile;\n readonly num_confirmations: number;\n readonly confirmation_depth_threshold: number;\n readonly block_time?: number;\n readonly block_slot?: number;\n readonly metadata_present: boolean;\n readonly validation: {\n readonly valid: boolean;\n readonly issues?: ReadonlyArray<ValidationIssue>;\n readonly warnings?: ReadonlyArray<ValidationIssue>;\n readonly info?: ReadonlyArray<ValidationIssue>;\n };\n readonly record?: PoeRecord;\n readonly record_signatures?: ReadonlyArray<VerifyRecordSignature>;\n // Transaction-level description (present only when raw tx CBOR is available\n // to the pipeline — the live `verifyTx` path always has it; the DB-first\n // `verifyResolved` path has it only when the caller passes `txCbor`).\n readonly tx_witnesses?: ReadonlyArray<VerifyTxWitness>;\n readonly tx_summary?: VerifyTxSummary;\n readonly metadata_labels?: ReadonlyArray<number>; // sorted ascending; all aux metadata label keys\n readonly item_hash_checks?: ReadonlyArray<ItemHashCheck>;\n readonly item_decryptions?: ReadonlyArray<VerifyItemDecryption>;\n readonly merkle_checks?: ReadonlyArray<VerifyMerkleCheck>;\n readonly uri_checks?: ReadonlyArray<VerifyUriCheck>;\n readonly supersedes_resolved?: { readonly tx: string; readonly exists: boolean };\n readonly http_calls: ReadonlyArray<HttpCallRecord>;\n}\n","// Label 309 v1 PoE record Zod schemas.\n//\n// Scope: structural shape gate. The schema enforces per-field types, length\n// bounds (chunk size, digest length, supersedes length, nonce length,\n// passphrase salt length), closed-map invariants (`sigs[i]`, `slot`,\n// `passphrase`, `merkle[i]`), and the `v == 1` literal. Cross-field rules\n// (item.hashes content-hash binding when `enc` present, slots/passphrase\n// exclusivity, `crit[]` shape, registry membership of algorithm\n// identifiers, COSE_Sign1 structural decode, URI per-scheme shape rules)\n// fire in `validator.ts` so the validator can emit the precise structural\n// codes (`UNSUPPORTED_*_ALG`, `ENC_*`, `SIG_*`, `INVALID_URI`,\n// `CRIT_SHAPE_INVALID`, …) rather than a generic schema-mismatch.\n//\n// Refinements that DO live in the schema (because the validator's domain\n// pass lifts these as `SCHEMA_*` / `*_LENGTH_MISMATCH` codes directly):\n// - chunk size `[1, 64]` → `CHUNK_TOO_LARGE`\n// - 32-byte digest / 32-byte root / 32-byte supersedes → `HASH_DIGEST_LENGTH_MISMATCH`\n// / `SUPERSEDES_TX_INVALID_LENGTH`\n// - 24-byte nonce / 32-byte slots_mac →\n// `NONCE_LENGTH_MISMATCH` / `ENC_SLOTS_MAC_INVALID_LENGTH`\n// - passphrase salt 16..64 bytes → `ENC_PASSPHRASE_SALT_TOO_SHORT` /\n// `ENC_PASSPHRASE_SALT_TOO_LONG`\n//\n// Per-slot recipient lengths (`epk`, `kem_ct`, `wrap`) are NOT enforced here:\n// the required slot shape depends on the envelope-level `kem`, which a slot\n// cannot see in isolation. The KEM-driven slot descriptor in `validator.ts`\n// emits the precise `KEM_EPK_LENGTH_MISMATCH` / `KEM_CT_LENGTH_MISMATCH` /\n// `WRAP_LENGTH_MISMATCH` / `ENC_SLOT_INVALID_SHAPE` codes instead.\n\nimport { z } from 'zod';\n\n// =============================================================================\n// Chunked-bytes / chunked-text arrays\n// =============================================================================\n\n// `[1* bstr .size (1..64)]`. A zero-length chunk (0 < 1) is rejected with the\n// SAME `CHUNK_TOO_LARGE` code as oversized chunks (any length outside\n// `[1, 64]`).\nexport const ChunkedBytesArraySchema = z\n .array(\n z.instanceof(Uint8Array).refine((b) => b.length >= 1 && b.length <= 64, {\n params: { code: 'CHUNK_TOO_LARGE' },\n }),\n )\n .min(1);\nexport type ChunkedBytesArray = z.infer<typeof ChunkedBytesArraySchema>;\n\n// `[1* tstr .size (1..64)]` — chunk byte length is the UTF-8-encoded length\n// (each `tstr` is wire-encoded as UTF-8). The `tstr .size (1..64)` pin is a\n// byte-count constraint, not a code-unit constraint.\nconst UTF8_ENCODER = new TextEncoder();\nexport const UriChunkArraySchema = z\n .array(\n z.string().refine(\n (s) => {\n const n = UTF8_ENCODER.encode(s).length;\n return n >= 1 && n <= 64;\n },\n { params: { code: 'CHUNK_TOO_LARGE' } },\n ),\n )\n .min(1);\nexport type UriChunkArray = z.infer<typeof UriChunkArraySchema>;\n\n// =============================================================================\n// Hashes map\n// =============================================================================\n//\n// `hashes` is a non-empty CBOR map keyed by content-hash algorithm identifier\n// (a CBOR text string from the content-hash registry) with the 32-byte digest\n// as value. cbor2 surfaces a text-keyed CBOR map as a plain JS object — z.record\n// admits any string key here. Both the registry-membership check\n// (`UNSUPPORTED_HASH_ALG`) and the per-algorithm digest-length check\n// (`HASH_DIGEST_LENGTH_MISMATCH`) live in the validator's domain pass so\n// each violation emits its precise code; the schema only enforces the\n// value is a CBOR byte string.\n\nexport const HashDigestSchema = z.instanceof(Uint8Array);\n\nexport const HashesMapSchema = z.record(z.string(), HashDigestSchema);\nexport type HashesMap = z.infer<typeof HashesMapSchema>;\n\n// =============================================================================\n// Top-level `merkle[]`\n// =============================================================================\n//\n// Each commit is a closed map `{alg, root, leaf_count, ? uris}`. `alg` is open\n// (registry membership is enforced in the validator's domain pass — unknown\n// identifiers emit `UNSUPPORTED_MERKLE_COMMIT_ALG`).\n\nexport const MerkleCommitSchema = z\n .object({\n alg: z.string(),\n root: z.instanceof(Uint8Array),\n leaf_count: z.number().int().min(1),\n uris: z.array(UriChunkArraySchema).min(1).optional(),\n })\n .strict();\nexport type MerkleCommit = z.infer<typeof MerkleCommitSchema>;\n\n// =============================================================================\n// Encryption envelope\n// =============================================================================\n\n// Per-slot recipient entry. The slot shape is KEM-driven:\n//\n// - x25519: `{ epk: bstr(32), wrap: bstr(48) }` — `epk` is the\n// ephemeral X25519 public key, `wrap` is the 32-byte CEK + 16-byte\n// ChaCha20-Poly1305 tag.\n// - mlkem768x25519: `{ kem_ct: [ bstr .size (1..64) ], wrap: bstr(48) }` —\n// `kem_ct` is the 1120-byte X-Wing `enc` carried as a chunked byte-string\n// array (the same `bytes-chunk-array` shape `sigs[i].cose_sign1` uses);\n// there is NO per-slot `epk` on the hybrid path.\n//\n// The `kem` identifier is hoisted to envelope scope (a per-slot `kem` would\n// be wire-bloat). The schema is deliberately PERMISSIVE:\n// `epk`, `kem_ct`, and `wrap` are all optional and `.strict()` is NOT applied.\n// Both the per-field length checks (`KEM_EPK_LENGTH_MISMATCH`,\n// `KEM_CT_LENGTH_MISMATCH`, `WRAP_LENGTH_MISMATCH`) and the KEM-driven\n// shape gate (which field MUST/MUST NOT be present for the declared `kem`,\n// emitting `ENC_SLOT_INVALID_SHAPE`) live in the validator's domain pass —\n// the structural schema cannot know the envelope `kem` from a slot in\n// isolation, and we want the precise KEM-aware code rather than a generic\n// schema mismatch. Because `.strict()` is dropped, the domain pass MUST\n// explicitly reject cross-KEM contamination (an x25519 slot carrying\n// `kem_ct`, or a hybrid slot carrying `epk`).\nexport const SlotSchema = z.object({\n epk: z.instanceof(Uint8Array).optional(),\n kem_ct: ChunkedBytesArraySchema.optional(),\n wrap: z.instanceof(Uint8Array).optional(),\n});\nexport type Slot = z.infer<typeof SlotSchema>;\n\n// Argon2id params `{m, t, p}` are a closed map. Each value MUST be a CBOR\n// unsigned integer; the FLOOR check (`m ≥ 65536`,\n// `t ≥ 3`, `p ≥ 1`) emits `ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW` in the\n// validator's domain pass — keeping it out of the schema lets us emit the\n// distinct salt-length code when salt itself is malformed too.\nexport const Argon2idParamsSchema = z\n .object({\n m: z.number().int(),\n t: z.number().int(),\n p: z.number().int(),\n })\n .strict();\nexport type Argon2idParams = z.infer<typeof Argon2idParamsSchema>;\n\n// Passphrase block. `alg` is open (registry membership checked in the\n// validator's domain pass → `ENC_PASSPHRASE_ALG_UNSUPPORTED`);\n// `params` is open here (validator narrows on the registered `alg` value and\n// emits `SCHEMA_UNKNOWN_FIELD` for extra keys, `ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW`\n// for sub-floor values). `salt` length floor/ceiling are schema-layer\n// refinements with the dedicated `ENC_PASSPHRASE_SALT_TOO_SHORT/TOO_LONG`\n// codes — they belong at the schema layer because a slot cannot otherwise\n// see the salt length.\nexport const PassphraseBlockSchema = z\n .object({\n alg: z.string(),\n salt: z.instanceof(Uint8Array).superRefine((bytes, ctx) => {\n if (bytes.length < 16) {\n ctx.addIssue({\n code: 'custom',\n path: [],\n message: `passphrase.salt length ${bytes.length} < 16`,\n params: { code: 'ENC_PASSPHRASE_SALT_TOO_SHORT' },\n });\n } else if (bytes.length > 64) {\n ctx.addIssue({\n code: 'custom',\n path: [],\n message: `passphrase.salt length ${bytes.length} > 64`,\n params: { code: 'ENC_PASSPHRASE_SALT_TOO_LONG' },\n });\n }\n }),\n params: z.record(z.string(), z.unknown()),\n })\n .strict();\nexport type PassphraseBlock = z.infer<typeof PassphraseBlockSchema>;\n\n// Sealed-PoE envelope. The wire format admits any combination of\n// `kem` / `slots` / `slots_mac` / `passphrase` keys (permissive superset);\n// cross-field invariants (slots ⊕ passphrase, slots ↔ slots_mac, slots\n// requires kem, content-hash binding, slots non-empty) are enforced in the\n// validator's domain pass so each violation emits its typed code rather\n// than a generic shape mismatch.\nexport const EncryptionEnvelopeSchema = z\n .object({\n scheme: z.unknown(),\n aead: z.string(),\n kem: z.string().optional(),\n nonce: z.instanceof(Uint8Array),\n slots: z.array(SlotSchema).optional(),\n slots_mac: z\n .instanceof(Uint8Array)\n .refine((b) => b.length === 32, {\n params: { code: 'ENC_SLOTS_MAC_INVALID_LENGTH' },\n })\n .optional(),\n passphrase: PassphraseBlockSchema.optional(),\n })\n .strict();\nexport type EncryptionEnvelope = z.infer<typeof EncryptionEnvelopeSchema>;\n\n// =============================================================================\n// Item entry\n// =============================================================================\n\nexport const ItemEntrySchema = z\n .object({\n hashes: HashesMapSchema,\n uris: z.array(UriChunkArraySchema).min(1).optional(),\n // Captured as `unknown` so the validator can run the\n // `ENC_REQUIRES_CONTENT_HASH` pre-check ahead of any inner-shape errors\n // and surface the most informative code first.\n enc: z.unknown().optional(),\n })\n .strict();\nexport type ItemEntry = z.infer<typeof ItemEntrySchema>;\n\n// =============================================================================\n// Sig entry\n// =============================================================================\n//\n// Closed CBOR map `{cose_sign1, ? cose_key}`. Canonical CBOR map-key sort\n// (RFC 8949 §4.2.1, bytewise lex on encoded keys) places `cose_key`\n// (length-8 tstr, `0x68`) BEFORE `cose_sign1` (length-10 tstr, `0x6a`); the\n// schema property-order is irrelevant — the canonical encoder handles it.\nexport const SigEntrySchema = z\n .object({\n cose_key: ChunkedBytesArraySchema.optional(),\n cose_sign1: ChunkedBytesArraySchema,\n })\n .strict();\nexport type SigEntry = z.infer<typeof SigEntrySchema>;\n\n// =============================================================================\n// Supersedence\n// =============================================================================\n\nexport const SupersedesSchema = z.instanceof(Uint8Array).refine((b) => b.length === 32, {\n params: { code: 'SUPERSEDES_TX_INVALID_LENGTH' },\n});\nexport type Supersedes = z.infer<typeof SupersedesSchema>;\n\n// =============================================================================\n// Top-level record\n// =============================================================================\n//\n// `v == 1` is a literal — a future major (`v: 2`) MUST be rejected with\n// `SCHEMA_INVALID_LITERAL`. `z.literal(1)` preserves the narrow `1` type for\n// the inferred `PoeRecord[\"v\"]` (so consumers can dispatch on it) and emits\n// Zod's `invalid_value` code which the validator's mapper lifts to\n// `SCHEMA_INVALID_LITERAL`.\n//\n// `looseObject` admits extension keys (matching `^x-.+` or `^[a-z]+-.+`); the\n// validator's domain pass rejects unknown keys that match neither pattern with\n// `SCHEMA_UNKNOWN_FIELD`.\nexport const VersionLiteralSchema = z.literal(1);\n\nexport const PoeRecordSchema = z.looseObject({\n v: VersionLiteralSchema,\n items: z.array(ItemEntrySchema).optional(),\n merkle: z.array(MerkleCommitSchema).optional(),\n supersedes: SupersedesSchema.optional(),\n sigs: z.array(SigEntrySchema).optional(),\n crit: z.array(z.string()).optional(),\n});\nexport type PoeRecord = z.infer<typeof PoeRecordSchema>;\n\n// =============================================================================\n// Closed top-level base-key registry\n// =============================================================================\n//\n// Used by the validator's domain pass to distinguish unknown-typo keys from\n// well-formed extension keys (`^x-.+` / `^[a-z]+-.+`).\nexport const TOP_LEVEL_BASE_KEYS: ReadonlySet<string> = new Set([\n 'v',\n 'items',\n 'merkle',\n 'supersedes',\n 'sigs',\n 'crit',\n]);\n\n// Extension-key namespaces. Anchored at both ends so an\n// embedded newline cannot smuggle a multi-segment key past the check: `.`\n// excludes `\\n` in JS, and the `\\n?$` tail tolerates exactly ONE trailing\n// newline (matching the Python validator's `re.fullmatch(r'^(x-.+|[a-z]+-.+)$')`\n// semantics, where `$` likewise admits a single trailing `\\n`). So `x-note\\n`\n// is an extension key, but `x-a\\nb`, `x-note\\n\\n`, and `x-\\n` are not.\nexport const EXTENSION_KEY_VENDOR_RE = /^x-.+\\n?$/;\nexport const EXTENSION_KEY_COMPANION_RE = /^[a-z]+-.+\\n?$/;\n\nexport function isExtensionKey(k: string): boolean {\n return EXTENSION_KEY_VENDOR_RE.test(k) || EXTENSION_KEY_COMPANION_RE.test(k);\n}\n","// Every canonical-CBOR decode violation collapses to the single public Label 309\n// taxonomy code MALFORMED_CBOR: indefinite-length (streaming) items, duplicate\n// keys, unsorted keys, non-minimal integer encodings, and invalid UTF-8 in text\n// strings. The taxonomy intentionally has one code for all of these; the\n// specific cause survives in the human-readable error message, not as a\n// separate code.\nexport type CanonicalCborErrorCode = 'MALFORMED_CBOR';\n\nexport class CanonicalCborError extends Error {\n readonly code: CanonicalCborErrorCode;\n\n constructor(code: CanonicalCborErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'CanonicalCborError';\n this.code = code;\n }\n}\n","import { cdeDecodeOptions, decode, encode } from 'cbor2';\nimport { sortCoreDeterministic } from 'cbor2/sorts';\n\nimport { CanonicalCborError } from './errors';\n\nexport type CanonicalCborValue =\n | null\n | boolean\n | number\n | bigint\n | string\n | Uint8Array\n | readonly CanonicalCborValue[]\n | { readonly [key: string]: CanonicalCborValue }\n | ReadonlyMap<string | number, CanonicalCborValue>;\n\nexport function encodeCanonicalCbor(value: CanonicalCborValue): Uint8Array {\n return encode(value, {\n cde: true,\n collapseBigInts: true,\n rejectDuplicateKeys: true,\n sortKeys: sortCoreDeterministic,\n });\n}\n\nexport function decodeCanonicalCbor(bytes: Uint8Array): unknown {\n try {\n return decode(bytes, {\n ...cdeDecodeOptions,\n rejectStreaming: true,\n rejectDuplicateKeys: true,\n // A Label 309 record carries integers, byte/text strings, arrays, maps and\n // `null` — and nothing else. Without these rejections the major-type-7\n // surface leaks into the decoder: a float16/32/64 that happens to hold an\n // integral value (e.g. 1.0) silently decodes to the integer 1 and passes\n // a `z.literal(1)` / Number.isInteger schema check, so two byte strings\n // that are NOT byte-identical canonicalise to the same record. That\n // breaks the cross-implementation parity invariant (the Python twin\n // already rejects non-integer `v` / `enc.scheme` outright). Reject the\n // whole non-record surface — floats, negative zero, undefined, and\n // non-{true,false,null} simple values — so any such input surfaces as\n // MALFORMED_CBOR via mapDecodeError rather than decoding to a look-alike.\n rejectFloats: true,\n rejectNegativeZero: true,\n rejectUndefined: true,\n rejectSimple: true,\n });\n } catch (cause) {\n throw mapDecodeError(cause);\n }\n}\n\nfunction mapDecodeError(cause: unknown): CanonicalCborError {\n const message = cause instanceof Error ? cause.message : String(cause);\n const lower = message.toLowerCase();\n // Every canonical-decode violation collapses to the single public taxonomy\n // code MALFORMED_CBOR: indefinite-length (streaming) items, duplicate keys,\n // non-canonical (unsorted) key ordering, non-minimal integer encodings, and\n // invalid UTF-8 in text strings. cbor2 raises the SAME \"Duplicate or out of\n // order key\" message for both true duplicates AND distinct-but-unsorted keys,\n // so the two are indistinguishable by message — and per the Label 309 taxonomy\n // both belong under MALFORMED_CBOR anyway. The specific cause survives in the\n // human-readable message below; for indefinite-length we state it explicitly\n // so the diagnostic is not lost when the code is collapsed.\n const isIndefinite = lower.includes('streaming') || lower.includes('indefinite');\n const detail = isIndefinite\n ? `indefinite-length items are not permitted in canonical CBOR: ${message}`\n : message;\n return new CanonicalCborError('MALFORMED_CBOR', `cbor decode failed: ${detail}`, { cause });\n}\n","// Permissive (non-canonical) CBOR decoder for outer wire decode (e.g. Cardano tx CBOR),\n// where the input is not constrained to be canonical RFC 8949 §4.2.1 form.\n//\n// Label 309 records themselves MUST be canonical and MUST go through\n// `decodeCanonicalCbor`. This decoder\n// exists to peel the outer Cardano tx structure ([body, witness_set, is_valid,\n// auxiliary_data]) so the label-309 byte string can be re-encoded canonically\n// for validator + signature verification.\n\nimport { decode } from 'cbor2';\n\nexport function decodeCbor(bytes: Uint8Array): unknown {\n return decode(bytes);\n}\n","// Label 309 v1 record encoder.\n//\n// Produces canonical CBOR bytes per RFC 8949 §4.2.1 deterministic encoding —\n// definite-length, sorted bytewise lex map keys, no duplicates, preferred\n// integer/float form. The canonical layer (`@cardanowall/crypto-core/cbor`)\n// configures `cbor2` with `cde: true, rejectDuplicateKeys: true`, so the\n// encoder's only job is to translate the validator-typed record shape into\n// the `CanonicalCborValue` algebra.\n//\n// Wire-shape contract:\n// - `items[i].hashes` is a CBOR MAP (text-keyed) — not an array of `{alg,h}`.\n// - `merkle[]` is a top-level array, peer to `items` and `sigs`.\n// - Each `sigs[i]` is a CBOR MAP `{cose_sign1, ? cose_key}` (canonical\n// sort places the optional `cose_key` BEFORE `cose_sign1`).\n// - The encryption envelope uses `scheme` (NOT `v`), `aead` (NOT `alg`),\n// `nonce` (NOT `iv`), `slots` (NOT `recipients`), `slots_mac` (NOT\n// `hdr_mac`); the KEM identifier is hoisted to envelope scope as `kem`.\n// - The passphrase block uses key name `passphrase` and `alg = \"argon2id\"`.\n//\n// Round-trip property: for every record `R` that the validator accepts,\n// validate(encode(R)).ok === true\n// && validate(encode(R)).record ≡ R (modulo CBOR-canonical key sort)\n\nimport { encodeCanonicalCbor, type CanonicalCborValue } from '@cardanowall/crypto-core/cbor';\n\nimport type {\n EncryptionEnvelope,\n ItemEntry,\n MerkleCommit,\n PassphraseBlock,\n PoeRecord,\n SigEntry,\n Slot,\n} from './schema';\n\ntype CborMap = { [key: string]: CanonicalCborValue };\n\nexport function encodePoeRecord(record: PoeRecord): Uint8Array {\n return encodeCanonicalCbor(recordToCbor(record));\n}\n\n// Helper: build the canonical-CBOR `record_body` (the bytes that record-level\n// `sigs[i]` signs over). The body is the full record map MINUS the `sigs`\n// field; producers prepend the 25-byte UTF-8 domain prefix\n// `cardano-poe-record-sig-v1` before invoking Ed25519 (the crypto-core\n// helper `buildLabel309SigStructure` handles the prefix and `Sig_structure`\n// wrapping).\nexport function encodeRecordBodyForSigning(record: PoeRecord): Uint8Array {\n const body: CborMap = recordToCborInternal(record, /* includeSigs */ false);\n return encodeCanonicalCbor(body);\n}\n\nfunction recordToCbor(record: PoeRecord): CanonicalCborValue {\n return recordToCborInternal(record, /* includeSigs */ true);\n}\n\nfunction recordToCborInternal(record: PoeRecord, includeSigs: boolean): CborMap {\n const out: CborMap = { v: record.v };\n if (record.items !== undefined) out['items'] = record.items.map(itemToCbor);\n if (record.merkle !== undefined) out['merkle'] = record.merkle.map(merkleToCbor);\n if (record.supersedes !== undefined) out['supersedes'] = record.supersedes;\n if (includeSigs && record.sigs !== undefined) out['sigs'] = record.sigs.map(sigEntryToCbor);\n if (record.crit !== undefined) out['crit'] = record.crit.slice();\n // Preserve extension keys verbatim — they are part of the signed\n // `record_body` and MUST round-trip byte-identical.\n for (const [k, v] of Object.entries(record)) {\n if (\n k === 'v' ||\n k === 'items' ||\n k === 'merkle' ||\n k === 'supersedes' ||\n k === 'sigs' ||\n k === 'crit'\n ) {\n continue;\n }\n out[k] = v as CanonicalCborValue;\n }\n return out;\n}\n\nfunction itemToCbor(item: ItemEntry): CanonicalCborValue {\n const out: CborMap = { hashes: hashesToCbor(item.hashes) };\n if (item.uris !== undefined) {\n out['uris'] = item.uris.map((chunks) => chunks.slice());\n }\n if (item.enc !== undefined) {\n out['enc'] = envelopeToCbor(item.enc as EncryptionEnvelope);\n }\n return out;\n}\n\nfunction hashesToCbor(hashes: Readonly<Record<string, Uint8Array>>): CanonicalCborValue {\n // text-keyed CBOR map — canonical sort orders by encoded-key bytewise lex\n // automatically (`sha2-256` `0x68` precedes `blake2b-256` `0x6b`).\n const out: CborMap = {};\n for (const [alg, digest] of Object.entries(hashes)) {\n out[alg] = digest;\n }\n return out;\n}\n\nfunction merkleToCbor(commit: MerkleCommit): CanonicalCborValue {\n const out: CborMap = {\n alg: commit.alg,\n root: commit.root,\n leaf_count: commit.leaf_count,\n };\n if (commit.uris !== undefined) {\n out['uris'] = commit.uris.map((chunks) => chunks.slice());\n }\n return out;\n}\n\nfunction envelopeToCbor(enc: EncryptionEnvelope): CanonicalCborValue {\n const out: CborMap = {\n scheme: enc.scheme as CanonicalCborValue,\n aead: enc.aead,\n nonce: enc.nonce,\n };\n if (enc.kem !== undefined) out['kem'] = enc.kem;\n if (enc.slots !== undefined) out['slots'] = enc.slots.map(slotToCbor);\n if (enc.slots_mac !== undefined) out['slots_mac'] = enc.slots_mac;\n if (enc.passphrase !== undefined) out['passphrase'] = passphraseToCbor(enc.passphrase);\n return out;\n}\n\nfunction slotToCbor(slot: Slot): CanonicalCborValue {\n // KEM-driven slot serialization. The canonical encoder sorts map keys by\n // length-then-bytewise (RFC 8949 §4.2.1), so it emits `wrap` (4-byte key)\n // before `kem_ct` (6-byte key) and `epk` (3-byte key) before `wrap`\n // automatically — insertion order here is irrelevant to the wire bytes.\n //\n // - x25519: `{ epk: bstr(32), wrap: bstr(48) }`\n // - mlkem768x25519: `{ kem_ct: [ bstr, ... ], wrap: bstr(48) }` — `kem_ct`\n // is the already-chunked array (NOT re-chunked here), so the bytes match\n // what crypto-core committed to `slots_mac` byte-for-byte.\n if (slot.kem_ct !== undefined) {\n return { kem_ct: slot.kem_ct.map((c) => c), wrap: slot.wrap! };\n }\n return { epk: slot.epk!, wrap: slot.wrap! };\n}\n\nfunction passphraseToCbor(pp: PassphraseBlock): CanonicalCborValue {\n return {\n alg: pp.alg,\n salt: pp.salt,\n params: pp.params as { readonly [key: string]: CanonicalCborValue },\n };\n}\n\nfunction sigEntryToCbor(entry: SigEntry): CanonicalCborValue {\n const out: CborMap = { cose_sign1: entry.cose_sign1.map((b) => b) };\n if (entry.cose_key !== undefined) {\n out['cose_key'] = entry.cose_key.map((b) => b);\n }\n return out;\n}\n","import { blake2b } from '@noble/hashes/blake2.js';\n\nexport function blake2b256(input: Uint8Array): Uint8Array {\n return blake2b(input, { dkLen: 32 });\n}\n\n// CIP-19 stake-address derivation, used for the wallet path-2 signer binding,\n// requires the 28-byte BLAKE2b digest of the signer's Ed25519 public key.\n// The Cardano ledger encodes stake addresses as\n// `network_header_byte || Blake2b-224(stake_vk)`\n// per CIP-19, so this output length is fixed by spec.\nexport function blake2b224(input: Uint8Array): Uint8Array {\n return blake2b(input, { dkLen: 28 });\n}\n","import * as ed from '@noble/ed25519';\nimport { sha512 } from '@noble/hashes/sha2.js';\n\ned.hashes.sha512 = sha512;\n\n// Ed25519 group order L (= 2^252 + 27742317777372353535851937790883648493).\nconst L = ed.Point.CURVE().n;\n\nexport interface SignEd25519Opts {\n readonly seed: Uint8Array;\n readonly message: Uint8Array;\n}\n\nexport interface VerifyEd25519Opts {\n readonly publicKey: Uint8Array;\n readonly message: Uint8Array;\n readonly signature: Uint8Array;\n}\n\nexport interface GetPublicKeyEd25519Opts {\n readonly seed: Uint8Array;\n}\n\nexport function signEd25519(opts: SignEd25519Opts): Uint8Array {\n return ed.sign(opts.message, opts.seed);\n}\n\n// Little-endian 32-byte scalar → bigint.\nfunction leBytesToBigInt(bytes: Uint8Array): bigint {\n let value = 0n;\n for (let i = bytes.length - 1; i >= 0; i--) {\n value = (value << 8n) | BigInt(bytes[i]!);\n }\n return value;\n}\n\n// Strict (non-cofactored) Ed25519 verification per RFC 8032 §5.1.7, matching\n// libsodium/PyNaCl `crypto_sign_verify_detached` and ed25519-dalek\n// `verify_strict`. The cofactor-less check rejects every small-order /\n// torsion-component edge case in the C2SP/CCTV corpus, which noble's\n// `{ zip215: false }` mode does NOT (it remains cofactored: it checks\n// `[8]([S]B - [k]A - R) == 0`, accepting torsion components).\n//\n// The verification equation is the unscaled `[S]B == R + [k]A`, rewritten as\n// `[S]B - [k]A - R == identity`. We reject S >= L (non-canonical scalar) and\n// any small-order A or R up front, so a torsion component can never be smuggled\n// through the cofactor multiplication the cofactored variant performs.\nexport function verifyEd25519(opts: VerifyEd25519Opts): boolean {\n const { signature, message, publicKey } = opts;\n if (signature.length !== 64 || publicKey.length !== 32) return false;\n\n // S = LE(sig[32..64]); reject if not a canonical scalar (S >= L).\n const S = leBytesToBigInt(signature.subarray(32, 64));\n if (S >= L) return false;\n\n // Decode A (public key) and R (sig[0..32]) with the canonical (non-zip215)\n // point encoding; a non-canonical encoding throws and rejects.\n let A: ed.Point;\n let R: ed.Point;\n try {\n A = ed.Point.fromBytes(publicKey);\n R = ed.Point.fromBytes(signature.subarray(0, 32));\n } catch {\n return false;\n }\n\n // Reject small-order (cofactor-torsion) A or R: this is exactly the strictness\n // that distinguishes verify_strict from the cofactored check.\n if (A.isSmallOrder() || R.isSmallOrder()) return false;\n\n // k = SHA-512(R || A || M) reduced mod L.\n const k =\n leBytesToBigInt(ed.hash(concatBytes(signature.subarray(0, 32), publicKey, message))) % L;\n\n // Accept iff [S]B - [k]A - R == identity. `multiplyUnsafe` returns the\n // identity for a 0 scalar, but guard explicitly to avoid relying on that.\n const sB = S === 0n ? ed.Point.ZERO : ed.Point.BASE.multiplyUnsafe(S);\n const kA = k === 0n ? ed.Point.ZERO : A.multiplyUnsafe(k);\n return sB.subtract(kA).subtract(R).is0();\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n let total = 0;\n for (const p of parts) total += p.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\nexport function getPublicKeyEd25519(opts: GetPublicKeyEd25519Opts): Uint8Array {\n return ed.getPublicKey(opts.seed);\n}\n","// Isomorphic constant-time byte-equality. crypto-core is browser-safe by\n// design, so we cannot import `node:crypto.timingSafeEqual` — webpack rejects\n// the `node:` scheme in the browser bundle. A pure-JS XOR loop is constant-time\n// for equal-length inputs; length mismatch is a deliberate early-return (the\n// API surface itself leaks length, same as node's timingSafeEqual which throws).\nexport function compareCt(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n // Lengths are equal and `i` stays in-bounds, so both indexes are always\n // defined — no nullish guard is needed (and one would read as a guard for\n // an impossible case).\n for (let i = 0; i < a.length; i++) diff |= (a[i] as number) ^ (b[i] as number);\n return diff === 0;\n}\n","export type CoseVerifyErrorCode =\n | 'MALFORMED_SIG_COSE'\n | 'MALFORMED_SIG_COSE_SIGN1'\n | 'UNSUPPORTED_SIG_ALG'\n | 'KID_UNRESOLVED'\n | 'SIGNATURE_INVALID';\n\nexport class CoseVerifyError extends Error {\n readonly code: CoseVerifyErrorCode;\n\n constructor(code: CoseVerifyErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'CoseVerifyError';\n this.code = code;\n }\n}\n\nexport type CoseVerifyResult =\n | { ok: true; signerKey: Uint8Array; alg: number }\n | { ok: false; error: { code: CoseVerifyErrorCode; message: string } };\n","import {\n decodeCanonicalCbor,\n encodeCanonicalCbor,\n type CanonicalCborValue,\n} from '../cbor/canonical';\nimport { CanonicalCborError } from '../cbor/errors';\nimport { blake2b224 } from '../hash/blake2b-256';\nimport { signEd25519, verifyEd25519 } from '../sig/ed25519';\nimport { compareCt } from '../util/compare-ct';\n\nimport { CoseVerifyError, type CoseVerifyResult } from './errors';\n\nexport type CoseHeader = Map<number | string, unknown>;\n\n// Label 309 v1 domain separator embedded as a prefix on `Sig_structure[3]`\n// (`to_sign`). The separator is\n// NOT placed in `Sig_structure[2]` (`external_aad`) because CIP-30 `signData`\n// — the only realistic wallet-signing path on Cardano — explicitly forbids a\n// non-empty `external_aad`. Pinning the prefix into the payload preserves the\n// anti-replay property while keeping wallet-produced signatures byte-identical\n// to verifier-side recomputation.\nexport const CARDANO_POE_SIG_DOMAIN_PREFIX = 'cardano-poe-record-sig-v1' as const;\n// Composer path-2 wallet flow consumes the prefix bytes directly\n// to assemble `toSign = prefix || canonical_cbor(record_body)` BEFORE calling\n// `walletSignData` (the wallet's `signData()` receives this concatenation as\n// its `payload` argument verbatim per CIP-30). The bytes constant is exported\n// so a composer can build the input without re-encoding the prefix at every\n// call site.\nexport const CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES = new TextEncoder().encode(\n CARDANO_POE_SIG_DOMAIN_PREFIX,\n);\n\n// Fail-fast: the prefix length is byte-pinned at 25 UTF-8 bytes. A different\n// runtime encoding would silently break round-tripping\n// against the reference vectors.\nif (CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length !== 25) {\n throw new Error(\n `cardano-poe-record-sig-v1 prefix must encode to exactly 25 UTF-8 bytes, got ${CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length}`,\n );\n}\n\nconst EMPTY_BYTES = new Uint8Array(0);\n\nexport interface CoseSign1Decoded {\n readonly protectedHeader: CoseHeader;\n // preserved for Sig_structure reconstruction — never re-encode the decoded header map (RFC 9052 §4.4)\n readonly protectedBytes: Uint8Array;\n readonly unprotectedHeader: CoseHeader;\n readonly payload: Uint8Array | null;\n readonly signature: Uint8Array;\n}\n\nexport interface BuildSigStructureArgs {\n readonly context: 'Signature1';\n readonly bodyProtectedBytes: Uint8Array;\n readonly externalAad: Uint8Array;\n readonly payload: Uint8Array;\n}\n\n// Raw RFC 9052 §4.4 Sig_structure builder. General-purpose: callers control\n// `external_aad` and `payload` exactly. For Label 309 record signing use\n// `buildLabel309SigStructure` instead — it enforces the Label 309 record-signature invariants.\nexport function buildSigStructure(args: BuildSigStructureArgs): Uint8Array {\n return encodeCanonicalCbor([\n args.context,\n args.bodyProtectedBytes,\n args.externalAad,\n args.payload,\n ] as readonly CanonicalCborValue[]);\n}\n\nexport interface BuildLabel309SigStructureArgs {\n readonly bodyProtectedBytes: Uint8Array;\n // Canonical CBOR of the record body with `sigs` removed.\n readonly recordBodyCbor: Uint8Array;\n}\n\n// Label 309 v1 specialisation of `Sig_structure` (RFC 9052 §4.4 base structure):\n// to_sign = utf8(\"cardano-poe-record-sig-v1\") || canonical_cbor(record_body_minus_sigs)\n// Sig_structure = [ \"Signature1\", body_protected, h'' (empty), to_sign ]\n// Always forces `external_aad = h''` (empty bstr) — the CIP-30 wallet path\n// cannot carry a non-empty `external_aad`, so the domain separator lives in\n// `Sig_structure[3]` rather than `Sig_structure[2]`.\nexport function buildLabel309SigStructure(args: BuildLabel309SigStructureArgs): Uint8Array {\n const toSign = new Uint8Array(\n CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length + args.recordBodyCbor.length,\n );\n toSign.set(CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES, 0);\n toSign.set(args.recordBodyCbor, CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length);\n return buildSigStructure({\n context: 'Signature1',\n bodyProtectedBytes: args.bodyProtectedBytes,\n externalAad: EMPTY_BYTES,\n payload: toSign,\n });\n}\n\nexport interface EncodeCoseSign1Args {\n readonly protectedHeader: CoseHeader;\n readonly unprotectedHeader: CoseHeader;\n readonly payload: Uint8Array | null;\n readonly signature: Uint8Array;\n}\n\nexport function encodeCoseSign1(args: EncodeCoseSign1Args): Uint8Array {\n const protectedBytes =\n args.protectedHeader.size === 0\n ? EMPTY_BYTES\n : encodeCanonicalCbor(args.protectedHeader as CanonicalCborValue);\n return encodeCanonicalCbor([\n protectedBytes,\n args.unprotectedHeader as CanonicalCborValue,\n args.payload,\n args.signature,\n ] as readonly CanonicalCborValue[]);\n}\n\n// cbor2's decoder returns Map for integer-keyed maps but plain Object for empty\n// or string-keyed maps; normalise both representations to Map.\nfunction asCoseHeader(value: unknown): CoseHeader | null {\n if (value instanceof Map) return value as CoseHeader;\n if (value !== null && typeof value === 'object' && (value as object).constructor === Object) {\n return new Map(Object.entries(value as Record<string, unknown>));\n }\n return null;\n}\n\nexport function decodeCoseSign1(bytes: Uint8Array): CoseSign1Decoded {\n let arr: unknown;\n try {\n arr = decodeCanonicalCbor(bytes);\n } catch (cause) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'cose decode failed', { cause });\n }\n if (!Array.isArray(arr) || arr.length !== 4) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'expected 4-element array');\n }\n const [protectedBytesRaw, unprotectedRaw, payloadRaw, signatureRaw] = arr;\n if (!(protectedBytesRaw instanceof Uint8Array)) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'protected_bytes must be bytes');\n }\n const unprotectedHeader = asCoseHeader(unprotectedRaw);\n if (unprotectedHeader === null) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'unprotected header must be map');\n }\n if (payloadRaw !== null && !(payloadRaw instanceof Uint8Array)) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'payload must be bytes or null');\n }\n if (!(signatureRaw instanceof Uint8Array) || signatureRaw.length !== 64) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'signature must be 64 bytes');\n }\n let protectedHeader: CoseHeader;\n if (protectedBytesRaw.length === 0) {\n protectedHeader = new Map();\n } else {\n let decodedProtected: unknown;\n try {\n decodedProtected = decodeCanonicalCbor(protectedBytesRaw);\n } catch (cause) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'protected header decode failed', { cause });\n }\n const ph = asCoseHeader(decodedProtected);\n if (ph === null) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'protected header must decode to map');\n }\n // Empty protected header MUST encode as the single byte 0x40 (zero-length bstr),\n // not 0x41 0xA0 (a 1-byte bstr containing an empty CBOR map). RFC 9052 §3 +\n // Label 309 canonical-CBOR mandate.\n if (ph.size === 0) {\n throw new CoseVerifyError(\n 'MALFORMED_SIG_COSE',\n 'empty protected header must encode as 0x40 (zero-length bstr), not as an empty map',\n );\n }\n protectedHeader = ph;\n }\n return {\n protectedHeader,\n protectedBytes: protectedBytesRaw,\n unprotectedHeader,\n payload: payloadRaw,\n signature: signatureRaw,\n };\n}\n\nexport type CoseSign1BuildErrorCode = 'SIGNER_NOT_PROVIDED' | 'SIGNER_AND_SEED_BOTH_PROVIDED';\n\nexport class CoseSign1BuildError extends Error {\n readonly code: CoseSign1BuildErrorCode;\n\n constructor(code: CoseSign1BuildErrorCode, message: string) {\n super(message);\n this.name = 'CoseSign1BuildError';\n this.code = code;\n }\n}\n\nexport interface CoseSign1Label309BuildArgs {\n readonly protectedHeader: CoseHeader;\n readonly unprotectedHeader: CoseHeader;\n // Canonical CBOR of the record body with `sigs` removed. The\n // builder prepends the 25-byte UTF-8 domain prefix `cardano-poe-record-sig-v1`\n // internally — callers MUST NOT pre-concatenate it.\n readonly recordBodyCbor: Uint8Array;\n // EITHER the raw 32-byte Ed25519 seed (used by KAT tests, Python parity, and\n // the off-host signing helper) OR an injected signer closure that signs the\n // assembled Sig_structure bytes (composer-side use — keeps the private key\n // inside the unlock-store closure so it never escapes scope).\n // Exactly one of the two MUST be provided; mutual exclusion enforced at\n // runtime via CoseSign1BuildError.\n readonly signerSecretKey?: Uint8Array;\n readonly signer?: (sigStructureBytes: Uint8Array) => Uint8Array;\n}\n\n// Label 309 v1 record-signature builder:\n// 1. compute `to_sign = utf8(\"cardano-poe-record-sig-v1\") || recordBodyCbor`\n// 2. Sig_structure = [ \"Signature1\", bodyProtected, h'', to_sign ]\n// 3. Ed25519-sign Sig_structure (via seed OR injected closure)\n// 4. emit COSE_Sign1 with payload = CBOR null (detached signature, mandatory)\nexport function coseSign1Label309Build(args: CoseSign1Label309BuildArgs): Uint8Array {\n if (args.signerSecretKey === undefined && args.signer === undefined) {\n throw new CoseSign1BuildError(\n 'SIGNER_NOT_PROVIDED',\n 'coseSign1Label309Build requires either signerSecretKey or signer',\n );\n }\n if (args.signerSecretKey !== undefined && args.signer !== undefined) {\n throw new CoseSign1BuildError(\n 'SIGNER_AND_SEED_BOTH_PROVIDED',\n 'coseSign1Label309Build accepts signerSecretKey XOR signer (not both)',\n );\n }\n const protectedBytes =\n args.protectedHeader.size === 0\n ? EMPTY_BYTES\n : encodeCanonicalCbor(args.protectedHeader as CanonicalCborValue);\n const sigStructureBytes = buildLabel309SigStructure({\n bodyProtectedBytes: protectedBytes,\n recordBodyCbor: args.recordBodyCbor,\n });\n let signature: Uint8Array;\n if (args.signer !== undefined) {\n signature = args.signer(sigStructureBytes);\n if (!(signature instanceof Uint8Array) || signature.length !== 64) {\n throw new CoseSign1BuildError(\n 'SIGNER_NOT_PROVIDED',\n `injected signer must return a 64-byte Uint8Array; got ${signature instanceof Uint8Array ? `${signature.length}-byte Uint8Array` : typeof signature}`,\n );\n }\n } else {\n signature = signEd25519({ seed: args.signerSecretKey!, message: sigStructureBytes });\n }\n return encodeCoseSign1({\n protectedHeader: args.protectedHeader,\n unprotectedHeader: args.unprotectedHeader,\n payload: null,\n signature,\n });\n}\n\nexport interface CoseSign1Label309VerifyArgs {\n readonly message: Uint8Array;\n // Canonical CBOR of the record body with `sigs` removed (verifier-recomputed;\n // the 25-byte UTF-8 prefix is prepended internally — callers\n // MUST NOT pre-concatenate it).\n readonly detachedRecordBodyCbor: Uint8Array;\n // Optional out-of-band signer key (path-2 wallet path resolves the key from\n // `sigs[i].cose_key`). Path-1 records carry the 32-byte raw Ed25519 pubkey\n // in the protected header at label 4 (`kid`) and need no out-of-band hint.\n readonly expectedSignerKey?: Uint8Array;\n}\n\n// Label 309 v1 record-signature verifier:\n// - Decode COSE_Sign1\n// - Reject COSE_Sign1[2] != CBOR null (attached payload — including h'') as\n// MALFORMED_SIG_COSE_SIGN1\n// - Recompute to_sign = utf8(\"cardano-poe-record-sig-v1\") || detachedRecordBodyCbor\n// - Sig_structure = [ \"Signature1\", protectedBytes, h'', to_sign ]\n// - Strict Ed25519 verify (RFC 8032 §5.1.7 — `zip215: false` per ed25519.ts)\n//\n// The verifier does NOT accept an `externalAad` argument: Label 309 v1 pins\n// `external_aad = h''` and any deviation would either silently weaken the\n// domain separator or quietly accept malformed records. If a future CIP\n// revision re-enables external_aad, this helper takes a v-bump.\nexport function coseSign1Label309Verify(args: CoseSign1Label309VerifyArgs): CoseVerifyResult {\n let decoded: CoseSign1Decoded;\n try {\n decoded = decodeCoseSign1(args.message);\n } catch (e) {\n if (e instanceof CoseVerifyError) {\n return { ok: false, error: { code: e.code, message: 'errors.cose.malformed' } };\n }\n if (e instanceof CanonicalCborError) {\n return {\n ok: false,\n error: { code: 'MALFORMED_SIG_COSE', message: 'errors.cose.malformed_cbor' },\n };\n }\n throw e;\n }\n // Label 309 v1 mandate: COSE_Sign1[2] (payload field) MUST be CBOR `null` (0xF6).\n // Any non-null payload — including a zero-length byte string `h''` — MUST\n // be rejected as MALFORMED_SIG_COSE_SIGN1.\n if (decoded.payload !== null) {\n return {\n ok: false,\n error: {\n code: 'MALFORMED_SIG_COSE_SIGN1',\n message: 'errors.cose.attached_payload_forbidden',\n },\n };\n }\n const alg = decoded.protectedHeader.get(1);\n if (typeof alg !== 'number' || alg !== -8) {\n return {\n ok: false,\n error: { code: 'UNSUPPORTED_SIG_ALG', message: 'errors.cose.unsupported_alg' },\n };\n }\n const kidRaw = decoded.protectedHeader.get(4);\n let signerKey: Uint8Array | undefined;\n if (kidRaw instanceof Uint8Array && kidRaw.length === 32) {\n signerKey = kidRaw;\n } else if (args.expectedSignerKey instanceof Uint8Array && args.expectedSignerKey.length === 32) {\n signerKey = args.expectedSignerKey;\n }\n if (signerKey === undefined) {\n return {\n ok: false,\n error: { code: 'KID_UNRESOLVED', message: 'errors.cose.kid_unresolved' },\n };\n }\n // When both a protected-header kid AND an expectedSignerKey are provided,\n // require they agree (constant-time). A protected kid that disagrees with\n // the caller's out-of-band binding is a misuse, not a transient mismatch.\n if (\n kidRaw instanceof Uint8Array &&\n kidRaw.length === 32 &&\n args.expectedSignerKey instanceof Uint8Array &&\n args.expectedSignerKey.length === 32 &&\n !compareCt(kidRaw, args.expectedSignerKey)\n ) {\n return {\n ok: false,\n error: { code: 'KID_UNRESOLVED', message: 'errors.cose.kid_mismatch' },\n };\n }\n // CIP-8 `hashed = true` mode (the wallet-signed path-2 variant). The unprotected\n // header carries the literal text key `\"hashed\"` with boolean value `true`\n // (text-keyed CBOR maps decode to `Map<string, unknown>` via cbor2). When\n // set, both producer and verifier build `Sig_structure[3] = Blake2b-224(to_sign)`\n // (28-byte digest of the FULL `to_sign` payload including the 25-byte\n // domain prefix). When absent or false, the standard non-hashed path\n // applies unchanged.\n const hashedFlag = decoded.unprotectedHeader.get('hashed');\n let sigStructureBytes: Uint8Array;\n if (hashedFlag === true) {\n const toSign = new Uint8Array(\n CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length + args.detachedRecordBodyCbor.length,\n );\n toSign.set(CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES, 0);\n toSign.set(args.detachedRecordBodyCbor, CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length);\n const hashedPayload = blake2b224(toSign);\n sigStructureBytes = buildSigStructure({\n context: 'Signature1',\n bodyProtectedBytes: decoded.protectedBytes,\n externalAad: EMPTY_BYTES,\n payload: hashedPayload,\n });\n } else {\n sigStructureBytes = buildLabel309SigStructure({\n bodyProtectedBytes: decoded.protectedBytes,\n recordBodyCbor: args.detachedRecordBodyCbor,\n });\n }\n const valid = verifyEd25519({\n publicKey: signerKey,\n message: sigStructureBytes,\n signature: decoded.signature,\n });\n if (!valid) {\n return {\n ok: false,\n error: { code: 'SIGNATURE_INVALID', message: 'errors.cose.signature_invalid' },\n };\n }\n return { ok: true, signerKey, alg };\n}\n","// CIP-30 / RFC 9052 §7 COSE_Key extraction for the Ed25519 sig path.\n//\n// CIP-30 wallets that don't put a 32-byte raw Ed25519 pubkey in the COSE_Sign1\n// protected header instead deliver the signer key as a separate `cbor<COSE_Key>`\n// blob, surfaced in the Label 309 record under the top-level `signer_keys` field.\n// This helper decodes one such blob and returns the underlying 32-byte Ed25519\n// pubkey, or `null` when the blob is malformed, uses an unexpected key type /\n// curve, or has the wrong `x` length.\n//\n// The expected COSE_Key shape (RFC 9053 §7.2 + RFC 8152 §13):\n// {\n// 1 (kty): 1 // OKP\n// 3 (alg): -8 // EdDSA — OPTIONAL but if present MUST be -8\n// -1 (crv): 6 // Ed25519\n// -2 (x): <32 byte raw public key>\n// }\n\nimport { decodeCanonicalCbor } from '../cbor/canonical';\n\nconst COSE_KEY_LABEL_KTY = 1;\nconst COSE_KEY_LABEL_ALG = 3;\nconst COSE_KEY_LABEL_CRV = -1;\nconst COSE_KEY_LABEL_X = -2;\n\nconst KTY_OKP = 1;\nconst ALG_EDDSA = -8;\nconst CRV_ED25519 = 6;\n\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\n\nfunction asMap(value: unknown): Map<unknown, unknown> | null {\n if (value instanceof Map) return value as Map<unknown, unknown>;\n if (value !== null && typeof value === 'object' && (value as object).constructor === Object) {\n return new Map(Object.entries(value as Record<string, unknown>));\n }\n return null;\n}\n\nexport function parseCoseKeyEd25519(blob: Uint8Array): Uint8Array | null {\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(blob);\n } catch {\n return null;\n }\n const map = asMap(decoded);\n if (map === null) return null;\n\n const kty = map.get(COSE_KEY_LABEL_KTY);\n if (typeof kty !== 'number' || kty !== KTY_OKP) return null;\n\n const crv = map.get(COSE_KEY_LABEL_CRV);\n if (typeof crv !== 'number' || crv !== CRV_ED25519) return null;\n\n if (map.has(COSE_KEY_LABEL_ALG)) {\n const alg = map.get(COSE_KEY_LABEL_ALG);\n if (typeof alg !== 'number' || alg !== ALG_EDDSA) return null;\n }\n\n const x = map.get(COSE_KEY_LABEL_X);\n if (!(x instanceof Uint8Array) || x.length !== ED25519_PUBLIC_KEY_LENGTH) return null;\n\n return x;\n}\n","// Label 309 v1 chunked-bytes and chunked-text helpers.\n//\n// The Cardano ledger CDDL constrains every `transaction_metadatum` byte string\n// (`bstr`) and text string (`tstr`) to ≤ 64 bytes. Label 309 therefore carries\n// any logical value larger than 64 bytes as an ARRAY of ≤ 64-byte chunks. Two\n// chunked shapes exist:\n//\n// * `bytes-chunk-array` — `[ 1* bstr .size (1..64) ]` — used for chunked\n// `COSE_Sign1` bytes (`sigs[i].cose_sign1`) and the chunked\n// `cbor<COSE_Key>` blob (`sigs[i].cose_key`).\n// * `uri-chunk-array` — `[ 1* tstr .size (1..64) ]` — used as the inner\n// element of `items[i].uris` and `merkle[i].uris`.\n//\n// Two reconstruction invariants are normative:\n//\n// 1. **Per-chunk size.** `[1, 64]` bytes (zero-length chunks rejected\n// identically to oversized chunks). The validator's schema layer enforces\n// this; the helpers here assume the schema gate has fired.\n// 2. **UTF-8 codepoint integrity (text only).** The reconstructed\n// concatenation MUST be valid UTF-8. The canonical-CBOR decoder already\n// rejects any `tstr` that is not valid UTF-8 (→ `MALFORMED_CBOR`) before\n// these helpers run, so each chunk arrives as a well-formed string; the\n// `TextDecoder({ fatal: true })` pass below is the residual structural\n// guard.\n\nconst CHUNK_MAX_BYTES = 64;\n\nconst UTF8_ENCODER = new TextEncoder();\n\n/**\n * Split a logical byte string into ≤ 64-byte CBOR-bytes chunks\n * (`bytes-chunk-array`). Always returns a non-empty array.\n *\n * For empty inputs, returns `[<empty>]` so the caller's schema gate fails\n * later via `CHUNK_TOO_LARGE` (zero-length chunks are rejected). Real callers\n * feed COSE_Sign1 / cbor<COSE_Key> byte strings, which are never empty.\n */\nexport function chunkBytes(value: Uint8Array): Uint8Array[] {\n if (value.length === 0) return [new Uint8Array(0)];\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < value.length; i += CHUNK_MAX_BYTES) {\n chunks.push(value.subarray(i, Math.min(i + CHUNK_MAX_BYTES, value.length)));\n }\n return chunks;\n}\n\n/**\n * Reverse of {@link chunkBytes}: concatenate chunked bytes (`sigs[i].cose_sign1`,\n * `sigs[i].cose_key`) into a single buffer for downstream CBOR/COSE decode.\n * The validator-layer schema enforces the per-chunk size + non-empty-array\n * invariants before this helper runs, so it makes no length checks.\n */\nexport function bytesChunkArrayConcat(chunks: ReadonlyArray<Uint8Array>): Uint8Array {\n let total = 0;\n for (const c of chunks) total += c.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const c of chunks) {\n out.set(c, offset);\n offset += c.length;\n }\n return out;\n}\n\nexport type ReconstructUriResult =\n | { ok: true; uri: string }\n | { ok: false; code: 'INVALID_URI'; reason: string };\n\n/**\n * Reconstruct a chunked URI (`uri-chunk-array`) into its logical string.\n *\n * The chunks arrive as JS strings produced by the canonical-CBOR decoder,\n * which already rejects any non-UTF-8 `tstr` (surfacing it upstream as\n * `MALFORMED_CBOR`) — so by the time this helper runs the only structural\n * task left is to byte-concatenate and decode. We re-encode each chunk to its\n * UTF-8 bytes, concatenate, and decode the whole with `{ fatal: true }`. A\n * conformant producer never splits a multi-byte codepoint across chunks (the\n * Cardano 64-byte cap is applied on codepoint boundaries), so this decode\n * succeeds for every well-formed record; the `INVALID_URI` branch is the\n * residual guard for a byte sequence that does not reconstruct to valid UTF-8.\n *\n * Per-scheme shape validation (the IPFS CID profile) and absolute-URI /\n * fragment-identifier / scheme-set checks fire in `validator.ts`, NOT here —\n * this helper is structural-only.\n */\nexport function reconstructChunkedUri(chunks: ReadonlyArray<string>): ReconstructUriResult {\n const merged = bytesChunkArrayConcat(chunks.map((c) => UTF8_ENCODER.encode(c)));\n try {\n const uri = new TextDecoder('utf-8', { fatal: true }).decode(merged);\n return { ok: true, uri };\n } catch (cause) {\n return {\n ok: false,\n code: 'INVALID_URI',\n reason: cause instanceof Error ? cause.message : String(cause),\n };\n }\n}\n\n/**\n * Chunk a URI string into `[ tstr .size (1..64) ]`, splitting on UTF-8 byte\n * boundaries so no multi-byte codepoint straddles a chunk.\n *\n * For pure-ASCII URIs (the common `ar://`, `ipfs://` cases) this collapses\n * to plain 64-byte byte-slice chunks. For URIs with non-ASCII path components\n * (rare but possible — RFC 3986 §2.5 IRIs / percent-encoded UTF-8) the\n * algorithm rewinds to the nearest codepoint boundary at each chunk break.\n */\nexport function chunkUri(uri: string): string[] {\n const bytes = UTF8_ENCODER.encode(uri);\n if (bytes.length === 0) return [''];\n if (bytes.length <= CHUNK_MAX_BYTES) return [uri];\n const decoder = new TextDecoder('utf-8', { fatal: true });\n const chunks: string[] = [];\n let cursor = 0;\n while (cursor < bytes.length) {\n let end = Math.min(cursor + CHUNK_MAX_BYTES, bytes.length);\n // Rewind to the start of the previous UTF-8 codepoint if we landed in\n // the middle of a multibyte sequence. UTF-8 continuation bytes match\n // 0b10xx_xxxx; rewind while the byte at `end` is a continuation.\n while (end < bytes.length && (bytes[end]! & 0xc0) === 0x80) end--;\n chunks.push(decoder.decode(bytes.subarray(cursor, end)));\n cursor = end;\n }\n return chunks;\n}\n","// Label 309 v1 error-code catalogue — single source of truth for the\n// structural-validator codes (Part A) and the verifier-layer codes (Part B)\n// that downstream verifiers re-export from this package.\n//\n// The structural validator emits ONLY Part A codes. Part B codes are\n// re-exported so consumers can `import { ErrorCode } from '@cardanowall/poe-standard'`\n// and dispatch on a single union type without round-tripping through the\n// verifier package.\n//\n// Codes are SCREAMING_SNAKE_CASE and MUST match the canonical taxonomy\n// byte-exact across the TS/PY/RS implementations — no lowercase synonyms,\n// no `schema_*`-prefixed parser-internal codes.\n\n// =============================================================================\n// Part A — structural validator codes\n// =============================================================================\nexport const STRUCTURAL_ERROR_CODES = [\n // CBOR decode layer. A single code covers every canonical-decode failure —\n // malformed/truncated bytes, indefinite-length encodings, non-canonical\n // (unsorted) map-key ordering, duplicate map keys, non-minimal integers, and\n // invalid UTF-8 — by design (no separate duplicate-key code).\n 'MALFORMED_CBOR',\n // Generic schema-layer\n 'SCHEMA_TYPE_MISMATCH',\n 'SCHEMA_MISSING_REQUIRED',\n 'SCHEMA_UNKNOWN_FIELD',\n 'SCHEMA_INVALID_LITERAL',\n 'SCHEMA_EMPTY_RECORD',\n // Hash-map\n 'HASH_DIGEST_LENGTH_MISMATCH',\n 'UNSUPPORTED_HASH_ALG',\n // Top-level `merkle[]`\n 'UNSUPPORTED_MERKLE_COMMIT_ALG',\n // URI / chunking. A chunk whose bytes do not reconstruct to valid UTF-8\n // surfaces as MALFORMED_CBOR at decode (cbor2 rejects invalid-UTF-8 tstr)\n // or, in the residual reconstruct guard, as INVALID_URI — there is no\n // separate codepoint-split code.\n 'INVALID_URI',\n 'CHUNK_TOO_LARGE',\n // Encryption envelope\n 'UNAUTHENTICATED_CIPHER_FORBIDDEN',\n 'UNSUPPORTED_AEAD_ALG',\n 'NONCE_LENGTH_MISMATCH',\n 'UNSUPPORTED_ENVELOPE_SCHEME',\n 'ENC_SLOTS_EMPTY',\n 'ENC_SLOT_INVALID_SHAPE',\n 'UNSUPPORTED_KEM_ALG',\n 'ENC_KEM_REQUIRED',\n 'KEM_EPK_LENGTH_MISMATCH',\n 'KEM_CT_LENGTH_MISMATCH',\n 'WRAP_LENGTH_MISMATCH',\n 'ENC_SLOTS_MAC_INVALID_LENGTH',\n 'ENC_SLOTS_MAC_REQUIRED',\n 'ENC_SLOTS_REQUIRED',\n 'ENC_EXCLUSIVITY_VIOLATION',\n 'ENC_NO_KEY_PATH',\n 'ENC_REQUIRES_CONTENT_HASH',\n 'ENC_PASSPHRASE_ALG_UNSUPPORTED',\n 'ENC_PASSPHRASE_SALT_TOO_SHORT',\n 'ENC_PASSPHRASE_SALT_TOO_LONG',\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n 'ENC_PASSPHRASE_PARAMS_EXCEED_POLICY',\n // Signatures\n 'MALFORMED_SIG_COSE_SIGN1',\n 'SIGNATURE_UNSUPPORTED',\n 'SIG_ENTRY_INVALID_SHAPE',\n 'SIG_ENTRY_KID_COSE_KEY_CONFLICT',\n 'SIG_PRIVATE_KEY_LEAKED',\n // Supersedence\n 'SUPERSEDES_TX_INVALID_LENGTH',\n // Forward-compat critical extensions\n 'EXTENSION_UNSUPPORTED_CRITICAL',\n 'CRIT_SHAPE_INVALID',\n] as const;\n\n// =============================================================================\n// Part B — verifier-layer codes\n// Re-exported so downstream verifiers can dispatch on a single union.\n// The structural validator NEVER emits these.\n// =============================================================================\nexport const VERIFIER_ERROR_CODES = [\n 'METADATA_NOT_FOUND',\n 'INSUFFICIENT_CONFIRMATIONS',\n 'SIGNATURE_INVALID',\n 'SIGNER_KEY_UNRESOLVED',\n 'WALLET_ADDRESS_MISMATCH',\n 'URI_TARGET_FORBIDDEN',\n 'URI_INTEGRITY_MISMATCH',\n 'URI_FETCH_FAILED',\n 'CONTENT_UNAVAILABLE',\n 'CIPHERTEXT_UNAVAILABLE',\n 'PROVIDER_UNAVAILABLE',\n 'SERVICE_INDEPENDENCE_VIOLATION',\n 'WRONG_DECRYPTION_INPUT_SHAPE',\n 'WRONG_RECIPIENT_KEY',\n 'TAMPERED_HEADER',\n 'TAMPERED_CIPHERTEXT',\n 'KDF_DERIVATION_FAILED',\n 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED',\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'MERKLE_ROOT_MISMATCH',\n 'MERKLE_LEAVES_UNAVAILABLE',\n 'MERKLE_LEAVES_INFORMATIVE_FORM',\n 'MERKLE_UNSUPPORTED',\n 'OUT_OF_PROFILE_SKIPPED',\n] as const;\n\nexport const ERROR_CODES = [...STRUCTURAL_ERROR_CODES, ...VERIFIER_ERROR_CODES] as const;\n\nexport type StructuralErrorCode = (typeof STRUCTURAL_ERROR_CODES)[number];\nexport type VerifierErrorCode = (typeof VERIFIER_ERROR_CODES)[number];\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\n// Severity classification. Codes not listed are `error` by default.\n//\n// `info` — a deliberate non-check (algorithm out of profile, unrecognised\n// signature algorithm at the opt-in informational tier).\n//\n// `warning` — a non-fatal anomaly that occurred at runtime but did not\n// invalidate the record (e.g. a transient gateway failure, partial leaves\n// availability).\n//\n// `MERKLE_UNSUPPORTED` / `OUT_OF_PROFILE_SKIPPED` carry dual severity\n// (`info` when another commitment was validated; `error` for the\n// merkle-only / strict-mode case). The verifier emits the resolved severity\n// per-issue; this map records the default `info` reading.\nexport type Severity = 'error' | 'warning' | 'info';\n\nexport const SEVERITY: Readonly<Record<ErrorCode, Severity>> = Object.freeze({\n // --- Part A ---\n MALFORMED_CBOR: 'error',\n SCHEMA_TYPE_MISMATCH: 'error',\n SCHEMA_MISSING_REQUIRED: 'error',\n SCHEMA_UNKNOWN_FIELD: 'error',\n SCHEMA_INVALID_LITERAL: 'error',\n SCHEMA_EMPTY_RECORD: 'error',\n HASH_DIGEST_LENGTH_MISMATCH: 'error',\n UNSUPPORTED_HASH_ALG: 'error',\n UNSUPPORTED_MERKLE_COMMIT_ALG: 'error',\n INVALID_URI: 'error',\n CHUNK_TOO_LARGE: 'error',\n UNAUTHENTICATED_CIPHER_FORBIDDEN: 'error',\n UNSUPPORTED_AEAD_ALG: 'error',\n NONCE_LENGTH_MISMATCH: 'error',\n UNSUPPORTED_ENVELOPE_SCHEME: 'error',\n ENC_SLOTS_EMPTY: 'error',\n ENC_SLOT_INVALID_SHAPE: 'error',\n UNSUPPORTED_KEM_ALG: 'error',\n ENC_KEM_REQUIRED: 'error',\n KEM_EPK_LENGTH_MISMATCH: 'error',\n KEM_CT_LENGTH_MISMATCH: 'error',\n WRAP_LENGTH_MISMATCH: 'error',\n ENC_SLOTS_MAC_INVALID_LENGTH: 'error',\n ENC_SLOTS_MAC_REQUIRED: 'error',\n ENC_SLOTS_REQUIRED: 'error',\n ENC_EXCLUSIVITY_VIOLATION: 'error',\n ENC_NO_KEY_PATH: 'error',\n ENC_REQUIRES_CONTENT_HASH: 'error',\n ENC_PASSPHRASE_ALG_UNSUPPORTED: 'error',\n ENC_PASSPHRASE_SALT_TOO_SHORT: 'error',\n ENC_PASSPHRASE_SALT_TOO_LONG: 'error',\n ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW: 'error',\n ENC_PASSPHRASE_PARAMS_EXCEED_POLICY: 'error',\n MALFORMED_SIG_COSE_SIGN1: 'error',\n SIGNATURE_UNSUPPORTED: 'info',\n SIG_ENTRY_INVALID_SHAPE: 'error',\n SIG_ENTRY_KID_COSE_KEY_CONFLICT: 'error',\n SIG_PRIVATE_KEY_LEAKED: 'error',\n SUPERSEDES_TX_INVALID_LENGTH: 'error',\n EXTENSION_UNSUPPORTED_CRITICAL: 'error',\n CRIT_SHAPE_INVALID: 'error',\n // --- Part B ---\n METADATA_NOT_FOUND: 'error',\n INSUFFICIENT_CONFIRMATIONS: 'info',\n SIGNATURE_INVALID: 'error',\n SIGNER_KEY_UNRESOLVED: 'error',\n WALLET_ADDRESS_MISMATCH: 'error',\n URI_TARGET_FORBIDDEN: 'error',\n URI_INTEGRITY_MISMATCH: 'error',\n URI_FETCH_FAILED: 'warning',\n CONTENT_UNAVAILABLE: 'error',\n CIPHERTEXT_UNAVAILABLE: 'error',\n PROVIDER_UNAVAILABLE: 'error',\n SERVICE_INDEPENDENCE_VIOLATION: 'error',\n WRONG_DECRYPTION_INPUT_SHAPE: 'error',\n WRONG_RECIPIENT_KEY: 'error',\n TAMPERED_HEADER: 'error',\n TAMPERED_CIPHERTEXT: 'error',\n KDF_DERIVATION_FAILED: 'error',\n SCHEMA_MERKLE_LEAF_COUNT_MISMATCH: 'error',\n SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED: 'error',\n SCHEMA_MERKLE_LEAVES_MALFORMED: 'error',\n MERKLE_ROOT_MISMATCH: 'error',\n MERKLE_LEAVES_UNAVAILABLE: 'warning',\n MERKLE_LEAVES_INFORMATIVE_FORM: 'info',\n // Dual-severity — default reading is `info`; the verifier promotes to\n // `error` for merkle-only records (no `items[]` content claim was\n // validated in the same record).\n MERKLE_UNSUPPORTED: 'info',\n // Dual-severity — default reading is `info` (render mode); strict\n // end-to-end verifiers promote to `error`.\n OUT_OF_PROFILE_SKIPPED: 'info',\n});\n\nexport function severityOf(code: ErrorCode): Severity {\n return SEVERITY[code];\n}\n","// Label 309 v1 structural validator (the Part A structural-validation role).\n//\n// Pure function over CBOR bytes — performs no I/O, opens no socket, decodes\n// no ciphertext. Cryptographic signature verification, chain resolution, URI\n// fetching, decryption, and confirmation-depth checks are the verifier's\n// concern (the Part B verifier role) and live in `@cardanowall/sdk-ts`.\n//\n// Pipeline:\n// Step 1 Resource boundary — n/a here (validator has no fixed cap;\n// transactions are bounded by maxTxSize\n// enforced at submission)\n// Step 2 Canonical CBOR decode — `decodeCanonicalCbor` from crypto-core\n// surfaces malformed / non-canonical /\n// duplicate-key inputs as typed errors.\n// Step 3 Schema parse — Zod schema in `./schema.ts`; the mapper\n// below lifts each Zod issue to a\n// SCREAMING_SNAKE structural code.\n// Step 4 Domain checks — cross-field rules, registry membership,\n// URI reconstruction + per-scheme shape\n// (the IPFS CID profile), `enc`\n// cross-field invariants, `sigs[i]`\n// closed-map check + COSE_Sign1 structural\n// decode (path-1/path-2 mutual exclusion,\n// `SIG_PRIVATE_KEY_LEAKED` guard).\n// Step 5 Result emission — `{ ok: true, record, info?, warnings? }`\n// or `{ ok: false, issues }`.\n//\n// The validator NEVER throws — failure paths route through the discriminated\n// `ValidateResult` union so callers handle errors as data.\n\nimport { z } from 'zod';\n\nimport { decodeCanonicalCbor } from '@cardanowall/crypto-core/cbor';\nimport { CoseVerifyError, decodeCoseSign1 } from '@cardanowall/crypto-core/cose';\n\nimport { bytesChunkArrayConcat, reconstructChunkedUri } from './chunked';\nimport { SEVERITY, type ErrorCode, type Severity } from './error-codes';\nimport {\n EncryptionEnvelopeSchema,\n isExtensionKey,\n PoeRecordSchema,\n TOP_LEVEL_BASE_KEYS,\n type ItemEntry,\n type MerkleCommit,\n type PoeRecord,\n type SigEntry,\n type Slot,\n} from './schema';\n\n// =============================================================================\n// Registries\n// =============================================================================\n\n// Content-hash algorithm registry. Map value = digest length.\nconst HASH_ALG_LENGTHS: Readonly<Record<string, number>> = {\n 'sha2-256': 32,\n 'blake2b-256': 32,\n};\n\n// Merkle list-commitment algorithm registry.\nconst MERKLE_COMMIT_ALG_LENGTHS: Readonly<Record<string, number>> = {\n 'rfc9162-sha256': 32,\n};\n\n// Content AEAD registry. Value = nonce length.\nconst AEAD_NONCE_LENGTHS: Readonly<Record<string, number>> = {\n 'xchacha20-poly1305': 24,\n};\n\n// Unauthenticated-cipher family. An `enc.aead` naming any of these is rejected\n// with `UNAUTHENTICATED_CIPHER_FORBIDDEN` (not the generic `UNSUPPORTED_AEAD_ALG`)\n// so the failure names the integrity hazard. Two arms:\n// - block-cipher modes with no integrity (`cbc`, `ctr`, `ecb`, `cfb`, `ofb`)\n// appearing as a delimited token, which matches every key-size spelling\n// (`aes-cbc`, `aes-256-cbc`, `aes-128-cbc`, `des-ede3-cbc`, …);\n// - legacy stream/block ciphers as a leading token (`rc4`, `des`, `3des`).\n// The token delimiters keep the authenticated AEADs (`aes-256-gcm`,\n// `chacha20-poly1305`, `xchacha20-poly1305`) from matching. The trailing\n// boundary tolerates a single trailing `\\n` (`\\n?$`) so a forbidden cipher\n// cannot evade the denylist by appending one newline (`aes-256-cbc\\n` /\n// `rc4\\n`), matching the Python/Rust validators.\nconst UNAUTHENTICATED_CIPHER_RE =\n /(?:^|[-_])(?:cbc|ctr|ecb|cfb|ofb)(?:[-_]|\\n?$)|^(?:rc4|des|3des)(?:[-_]|\\n?$)/i;\n\n// KEM registry, expressed as a per-KEM slot DESCRIPTOR.\n//\n// Each registered KEM pins the exact recipient-slot shape:\n//\n// - x25519: `{ epk: bstr(32), wrap: bstr(48) }` — classical\n// ephemeral-static X25519. The per-slot `epk` is the 32-byte ephemeral\n// public key.\n// - mlkem768x25519: `{ kem_ct: <1120-byte X-Wing enc>, wrap: bstr(48) }` —\n// the X-Wing hybrid (ML-KEM-768 + X25519). The ciphertext is carried as a\n// chunked byte-string array (`kem_ct`) that MUST reassemble to exactly\n// 1120 bytes; there is NO per-slot `epk` on the hybrid path.\n//\n// A descriptor declares the slot's *ciphertext-bearing* field (`epk` for a\n// classical KEM, `kem_ct` for a hybrid) and its expected reassembled byte\n// length. `wrap` is 48 bytes for every KEM (32-byte CEK + 16-byte AEAD tag).\n// The validator branches on the descriptor's `field` to know which field MUST\n// be present and which MUST be absent, so adding a future KEM is a one-line\n// registry edit, not a new code path.\ntype KemSlotField = 'epk' | 'kem_ct';\ninterface KemSlotDescriptor {\n /** The ciphertext-bearing slot field this KEM uses. */\n readonly field: KemSlotField;\n /** Expected length of that field (reassembled length for a chunked field). */\n readonly fieldLength: number;\n /** `wrap` length — 32-byte CEK + 16-byte AEAD tag. */\n readonly wrapLength: number;\n}\nconst KEM_SLOT_DESCRIPTORS: Readonly<Record<string, KemSlotDescriptor>> = {\n x25519: { field: 'epk', fieldLength: 32, wrapLength: 48 },\n mlkem768x25519: { field: 'kem_ct', fieldLength: 1120, wrapLength: 48 },\n};\n\n// The length-mismatch code emitted when a slot's ciphertext-bearing field has\n// the wrong (reassembled) length, keyed by the descriptor's `field`.\nconst KEM_FIELD_LENGTH_CODE: Readonly<Record<KemSlotField, ErrorCode>> = {\n epk: 'KEM_EPK_LENGTH_MISMATCH',\n kem_ct: 'KEM_CT_LENGTH_MISMATCH',\n};\n\n// Passphrase KDF registry.\nconst PASSPHRASE_KDF_ALGS: ReadonlySet<string> = new Set(['argon2id']);\n\n// Signature-algorithm baseline. `-8` (EdDSA, curve-agnostic — pinned to\n// Ed25519) is the mandatory baseline; `-19` (Ed25519 fully-specified) is\n// optional and verified identically under the Ed25519 primitive when\n// accepted. The reference validator accepts both; anything else surfaces as\n// `SIGNATURE_UNSUPPORTED` (info-severity).\nconst KNOWN_SIG_ALG_IDS: ReadonlySet<number> = new Set([-8, -19]);\n\n// =============================================================================\n// Result types\n// =============================================================================\n\nexport interface ValidationIssue {\n readonly code: ErrorCode;\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n readonly severity: Severity;\n}\n\nexport type ValidateResult =\n | {\n readonly ok: true;\n readonly record: PoeRecord;\n readonly warnings?: ReadonlyArray<ValidationIssue>;\n readonly info?: ReadonlyArray<ValidationIssue>;\n }\n | { readonly ok: false; readonly issues: ReadonlyArray<ValidationIssue> };\n\n// =============================================================================\n// Public entry point\n// =============================================================================\n\nexport function validatePoeRecord(bytes: Uint8Array): ValidateResult {\n // Step 2 — canonical CBOR decode. Every decode failure surfaces as the single\n // MALFORMED_CBOR code: malformed/truncated bytes, indefinite-length\n // (streaming) encodings, non-canonical map-key ordering, duplicate map keys,\n // non-minimal integers, and invalid UTF-8. The taxonomy has no finer-grained\n // CBOR-decode codes — the validator catches all of these at decode and\n // reports one error.\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(bytes);\n } catch (cause) {\n return {\n ok: false,\n issues: [\n {\n code: 'MALFORMED_CBOR',\n path: [],\n message: cause instanceof Error ? cause.message : String(cause),\n severity: 'error',\n },\n ],\n };\n }\n\n // Step 3 — schema parse\n const parse = PoeRecordSchema.safeParse(decoded);\n if (!parse.success) {\n const issues = parse.error.issues\n .map((issue) => mapZodIssue(issue, decoded))\n .sort(compareIssuePath);\n return { ok: false, issues };\n }\n\n // Step 4 — domain checks\n const record = parse.data;\n const errors: ValidationIssue[] = [];\n const warnings: ValidationIssue[] = [];\n const info: ValidationIssue[] = [];\n\n // 4a — content-commitment rule (`SCHEMA_EMPTY_RECORD`).\n const itemsLen = Array.isArray(record.items) ? record.items.length : 0;\n const merkleLen = Array.isArray(record.merkle) ? record.merkle.length : 0;\n if (itemsLen === 0 && merkleLen === 0) {\n errors.push(\n issue(\n 'SCHEMA_EMPTY_RECORD',\n [],\n 'record must carry at least one of items[] or merkle[] non-empty',\n ),\n );\n }\n\n // `crit[]` shape rules. Runs BEFORE the per-entry\n // `EXTENSION_UNSUPPORTED_CRITICAL` check.\n const decodedTopKeys = topLevelKeysOf(decoded);\n const critShapeInvalidIndices = checkCritShape(record, decodedTopKeys, errors);\n\n // Unknown top-level fields (typos like `supersedess`, `Sigs` that fall\n // outside both the base set and the extension-key namespaces).\n for (const k of decodedTopKeys) {\n if (TOP_LEVEL_BASE_KEYS.has(k)) continue;\n if (isExtensionKey(k)) continue;\n errors.push(issue('SCHEMA_UNKNOWN_FIELD', [k], `unknown top-level field: ${k}`));\n }\n\n // `EXTENSION_UNSUPPORTED_CRITICAL`: v1 reference validator implements no\n // extension keys, so every shape-valid `crit` entry is unsupported.\n if (Array.isArray(record.crit)) {\n for (let i = 0; i < record.crit.length; i++) {\n if (critShapeInvalidIndices.has(i)) continue;\n const critName = record.crit[i]!;\n errors.push(\n issue(\n 'EXTENSION_UNSUPPORTED_CRITICAL',\n ['crit', i],\n `crit lists extension '${critName}' that this validator does not implement`,\n ),\n );\n }\n }\n\n // 4b – 4e — per-item walk.\n for (let i = 0; i < (record.items ?? []).length; i++) {\n const item = record.items![i]!;\n checkItemHashes(item, i, errors);\n if (item.uris) checkItemUris(item.uris, ['items', i, 'uris'], errors);\n if (item.enc !== undefined) checkItemEnc(item, i, errors);\n }\n\n // 4i — top-level `merkle[]` walk.\n for (let i = 0; i < (record.merkle ?? []).length; i++) {\n const commit = record.merkle![i]!;\n checkMerkleCommit(commit, i, errors);\n }\n\n // 4h — supersedes length is enforced by the schema-layer refinement; this\n // step adds no further check.\n\n // 4f + 4g — `sigs[i]` closed map shape + COSE_Sign1 structural decode.\n if (record.sigs) {\n for (let i = 0; i < record.sigs.length; i++) {\n checkSigEntry(record.sigs[i]!, i, errors, info);\n }\n }\n\n // Step 5 — result emission. `info`-severity entries do NOT fail the record;\n // `warning`-severity entries (none among the structural codes) also remain\n // non-fatal.\n if (errors.length > 0) {\n return { ok: false, issues: errors.sort(compareIssuePath) };\n }\n const result: {\n ok: true;\n record: PoeRecord;\n warnings?: ReadonlyArray<ValidationIssue>;\n info?: ReadonlyArray<ValidationIssue>;\n } = {\n ok: true,\n record,\n };\n if (warnings.length > 0) result.warnings = warnings.sort(compareIssuePath);\n if (info.length > 0) result.info = info.sort(compareIssuePath);\n return result;\n}\n\n// =============================================================================\n// Step 3 helpers — Zod issue → structural-code mapping\n// =============================================================================\n\nfunction mapZodIssue(zissue: z.core.$ZodIssue, decoded?: unknown): ValidationIssue {\n const path = zissue.path as ReadonlyArray<string | number>;\n // Refinements with an explicit `params.code` win unconditionally — they\n // are the canonical taxonomy code attached at schema-definition time.\n const explicit = (zissue as { params?: { code?: string } }).params?.code as ErrorCode | undefined;\n if (explicit !== undefined) {\n return issue(explicit, path, zissue.message);\n }\n\n // Path-based dispatch:\n // `sigs[i].*` → `SIG_ENTRY_INVALID_SHAPE` (the sig-entry closed-map rule)\n // `items[i].enc.slots[j].(epk|wrap)` → `ENC_SLOT_INVALID_SHAPE`\n // (structurally malformed slots)\n // `v` literal mismatch / missing → `SCHEMA_INVALID_LITERAL` vs\n // `SCHEMA_MISSING_REQUIRED`.\n const inSigsEntry = path.length >= 2 && path[0] === 'sigs' && typeof path[1] === 'number';\n\n // Match either the absolute path (`items[i].enc.slots[j]…`) or the\n // relative-to-`enc` path (`slots[j]…`) — the latter is what\n // `EncryptionEnvelopeSchema.safeParse(item.enc)` emits before\n // `checkItemEnc` prefixes the `items[i].enc.` segment.\n //\n // The match includes the whole slot ELEMENT (path ending at `slots[j]`, no\n // trailing field) as well as a field WITHIN a slot (`slots[j].epk`). A\n // wrong-typed slot (`slots: [[1, 2]]` → array instead of `{epk, wrap}`) and\n // a slot carrying an extra key both classify as `ENC_SLOT_INVALID_SHAPE`,\n // matching the spec's \"a slot is not a 2-key map {epk, wrap}\".\n const isInSlotEntry = (() => {\n if (\n path.length >= 5 &&\n path[0] === 'items' &&\n typeof path[1] === 'number' &&\n path[2] === 'enc' &&\n path[3] === 'slots' &&\n typeof path[4] === 'number'\n ) {\n return true;\n }\n if (path.length >= 2 && path[0] === 'slots' && typeof path[1] === 'number') {\n return true;\n }\n return false;\n })();\n\n const valueAtIssue = valueAtPath(decoded, path);\n const isMissing = valueAtIssue === undefined;\n\n switch (zissue.code) {\n case 'invalid_type':\n if (isInSlotEntry) return issue('ENC_SLOT_INVALID_SHAPE', path, zissue.message);\n if (isMissing) {\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_MISSING_REQUIRED', path, zissue.message);\n }\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_TYPE_MISMATCH', path, zissue.message);\n case 'invalid_value':\n // Zod 4's `z.literal(1)` emits `invalid_value` for both a missing field\n // AND a present-but-wrong value. Disambiguate via the runtime value:\n // missing → `SCHEMA_MISSING_REQUIRED`; present-but-wrong → `SCHEMA_INVALID_LITERAL`.\n if (path.length === 1 && path[0] === 'v') {\n return issue(\n isMissing ? 'SCHEMA_MISSING_REQUIRED' : 'SCHEMA_INVALID_LITERAL',\n path,\n zissue.message,\n );\n }\n return issue('SCHEMA_INVALID_LITERAL', path, zissue.message);\n case 'unrecognized_keys':\n if (isInSlotEntry) return issue('ENC_SLOT_INVALID_SHAPE', path, zissue.message);\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_UNKNOWN_FIELD', path, zissue.message);\n case 'invalid_format':\n case 'too_big':\n case 'too_small':\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_TYPE_MISMATCH', path, zissue.message);\n case 'invalid_union':\n case 'invalid_key':\n case 'invalid_element':\n case 'custom':\n default:\n if (isInSlotEntry) return issue('ENC_SLOT_INVALID_SHAPE', path, zissue.message);\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_TYPE_MISMATCH', path, zissue.message);\n }\n}\n\n// =============================================================================\n// Step 4 helpers — domain checks\n// =============================================================================\n\n// 4b — hash-map registry membership + digest length per algorithm.\nfunction checkItemHashes(item: ItemEntry, idx: number, errors: ValidationIssue[]): void {\n const entries = Object.entries(item.hashes);\n if (entries.length === 0) {\n errors.push(\n issue(\n 'SCHEMA_TYPE_MISMATCH',\n ['items', idx, 'hashes'],\n 'hashes must be a non-empty CBOR map of <alg-id> -> <digest>',\n ),\n );\n return;\n }\n for (const [alg, digest] of entries) {\n if (!(alg in HASH_ALG_LENGTHS)) {\n errors.push(\n issue('UNSUPPORTED_HASH_ALG', ['items', idx, 'hashes', alg], `unknown hash alg: ${alg}`),\n );\n continue;\n }\n const expected = HASH_ALG_LENGTHS[alg]!;\n if (digest.length !== expected) {\n errors.push(\n issue(\n 'HASH_DIGEST_LENGTH_MISMATCH',\n ['items', idx, 'hashes', alg],\n `hashes['${alg}'] digest length ${digest.length} != ${expected}`,\n ),\n );\n }\n }\n}\n\n// 4c — URI chunk reconstruction + per-scheme shape.\nfunction checkItemUris(\n uris: ReadonlyArray<ReadonlyArray<string>>,\n basePath: ReadonlyArray<string | number>,\n errors: ValidationIssue[],\n): void {\n uris.forEach((chunks, ui) => validateOneUri(chunks, [...basePath, ui], errors));\n}\n\nfunction validateOneUri(\n chunks: ReadonlyArray<string>,\n path: ReadonlyArray<string | number>,\n errors: ValidationIssue[],\n): void {\n const reconstructed = reconstructChunkedUri(chunks);\n if (!reconstructed.ok) {\n errors.push(issue(reconstructed.code, path, reconstructed.reason));\n return;\n }\n const uri = reconstructed.uri;\n\n // Absolute URI, no fragment, scheme in `{ar://, ipfs://}`.\n if (uri.includes('#')) {\n errors.push(\n issue('INVALID_URI', path, \"URI contains a fragment identifier ('#'), which is forbidden\"),\n );\n return;\n }\n const sepIdx = uri.indexOf('://');\n if (sepIdx <= 0 || !/^[a-z][a-z0-9+.-]*$/i.test(uri.slice(0, sepIdx))) {\n errors.push(\n issue('INVALID_URI', path, 'URI is not absolute (missing scheme://hierarchical-part)'),\n );\n return;\n }\n // RFC 3986 §3.1: the scheme is case-insensitive, so case-fold the SCHEME ONLY,\n // then ALWAYS validate the body. The host / CID / txid is NOT case-folded — a\n // base64url Arweave txid and a base58btc CID are case-significant. An\n // uppercase scheme (`AR://`, `IPFS://`) is accepted iff its body passes the\n // same per-scheme shape check a lowercase scheme would.\n const scheme = uri.slice(0, sepIdx).toLowerCase();\n const rest = uri.slice(sepIdx + '://'.length);\n if (scheme === 'ar') {\n if (!/^ar:\\/\\/[A-Za-z0-9_-]{43}$/.test('ar://' + rest)) {\n errors.push(\n issue(\n 'INVALID_URI',\n path,\n 'ar:// URI does not match `^ar://[A-Za-z0-9_-]{43}$` (43-char base64url txid, no path/query/fragment)',\n ),\n );\n }\n return;\n }\n if (scheme === 'ipfs') {\n // The structural validator does a full CID parse (not just a prefix check).\n const slashIdx = rest.indexOf('/');\n const cid = slashIdx === -1 ? rest : rest.slice(0, slashIdx);\n if (!validateCidProfile(cid)) {\n errors.push(\n issue('INVALID_URI', path, 'ipfs:// URI is not a valid CID under the Label 309 profile'),\n );\n }\n return;\n }\n // Scheme not in `{ar://, ipfs://}`.\n errors.push(\n issue('INVALID_URI', path, 'unsupported URI scheme; v1 PoE URI set is {ar://, ipfs://}'),\n );\n}\n\n// 4d — encryption envelope.\nfunction checkItemEnc(item: ItemEntry, idx: number, errors: ValidationIssue[]): void {\n // Pre-check: an `enc`-bearing item MUST commit to a content hash. The claim\n // is the *plaintext* digest, so the hashes map MUST carry at least one\n // registered content-hash entry (sha2-256 / blake2b-256). This is a PRESENCE\n // check, not merely a non-empty check: a `hashes` map that exists but carries\n // only a non-content algorithm (e.g. `{md5}`) still fails — there is no\n // content digest to bind the ciphertext to. The empty-map case is also caught\n // here (and additionally fails the CDDL `1*` cardinality in checkItemHashes).\n const hasContentHash = Object.keys(item.hashes).some((alg) => alg in HASH_ALG_LENGTHS);\n if (!hasContentHash) {\n errors.push(\n issue(\n 'ENC_REQUIRES_CONTENT_HASH',\n ['items', idx, 'enc'],\n 'item carries `enc` but `hashes` has no content-hash entry (sha2-256 or blake2b-256)',\n ),\n );\n return;\n }\n\n // Schema-parse the envelope independently so we can lift its issues with\n // the correct path prefix.\n const encParse = EncryptionEnvelopeSchema.safeParse(item.enc);\n if (!encParse.success) {\n for (const zissue of encParse.error.issues) {\n const mapped = mapZodIssue(zissue, item.enc);\n errors.push({\n ...mapped,\n path: ['items', idx, 'enc', ...mapped.path],\n });\n }\n return;\n }\n const enc = encParse.data;\n const basePath: ReadonlyArray<string | number> = ['items', idx, 'enc'];\n\n // `enc.scheme` MUST be the unsigned integer 1.\n if (typeof enc.scheme !== 'number' || !Number.isInteger(enc.scheme) || enc.scheme !== 1) {\n errors.push(\n issue(\n 'UNSUPPORTED_ENVELOPE_SCHEME',\n [...basePath, 'scheme'],\n `enc.scheme must be the unsigned integer 1; got ${String(enc.scheme)}`,\n ),\n );\n // Continue — other checks remain informative.\n }\n\n // AEAD checks (forbidden cipher first, then registry). The forbidden set is\n // the unauthenticated-cipher family — block-cipher modes that provide no\n // integrity (CBC, CTR, ECB, CFB, OFB) in any key-size spelling\n // (`aes-256-cbc`, `aes-128-cbc`, OpenSSL/JCA form) plus the legacy stream\n // ciphers (RC4, DES/3DES). Matching this family — rather than a generic\n // \"unknown alg\" fall-through to `UNSUPPORTED_AEAD_ALG` — names the security\n // hazard precisely: the record selected an authenticated-encryption-absent\n // cipher, not merely an unregistered one.\n if (UNAUTHENTICATED_CIPHER_RE.test(enc.aead)) {\n errors.push(\n issue(\n 'UNAUTHENTICATED_CIPHER_FORBIDDEN',\n [...basePath, 'aead'],\n `'${enc.aead}' is an unauthenticated cipher; Label 309 mandates an authenticated (AEAD) cipher`,\n ),\n );\n return; // unrecoverable — nonce / kem / slot checks become noise\n }\n if (!(enc.aead in AEAD_NONCE_LENGTHS)) {\n errors.push(\n issue('UNSUPPORTED_AEAD_ALG', [...basePath, 'aead'], `unknown aead alg: ${enc.aead}`),\n );\n return;\n }\n const expectedNonceLen = AEAD_NONCE_LENGTHS[enc.aead]!;\n if (enc.nonce.length !== expectedNonceLen) {\n errors.push(\n issue(\n 'NONCE_LENGTH_MISMATCH',\n [...basePath, 'nonce'],\n `nonce length ${enc.nonce.length} != ${expectedNonceLen} for ${enc.aead}`,\n ),\n );\n }\n\n // Envelope-level KEM check (when present).\n if (enc.kem !== undefined && !(enc.kem in KEM_SLOT_DESCRIPTORS)) {\n errors.push(issue('UNSUPPORTED_KEM_ALG', [...basePath, 'kem'], `unknown kem alg: ${enc.kem}`));\n }\n\n // Key-path branching.\n const hasSlots = enc.slots !== undefined;\n const hasSlotsMac = enc.slots_mac !== undefined;\n const hasPassphrase = enc.passphrase !== undefined;\n\n if (hasSlots && hasPassphrase) {\n errors.push(\n issue('ENC_EXCLUSIVITY_VIOLATION', basePath, 'enc combines slots with passphrase; pick one'),\n );\n }\n if (hasSlots && !hasSlotsMac) {\n errors.push(\n issue('ENC_SLOTS_MAC_REQUIRED', basePath, 'enc.slots present but enc.slots_mac absent'),\n );\n }\n if (hasSlotsMac && !hasSlots) {\n errors.push(\n issue('ENC_SLOTS_REQUIRED', basePath, 'enc.slots_mac present but enc.slots absent'),\n );\n }\n if (hasSlots && enc.kem === undefined) {\n errors.push(issue('ENC_KEM_REQUIRED', basePath, 'enc.slots present but enc.kem absent'));\n }\n if (!hasSlots && !hasPassphrase) {\n errors.push(\n issue(\n 'ENC_NO_KEY_PATH',\n basePath,\n 'enc requires either slots or passphrase — no on-chain key path otherwise',\n ),\n );\n }\n\n // Slots shape checks. The slot shape is KEM-driven: the descriptor for the\n // declared `kem` pins which ciphertext-bearing field (`epk` for x25519,\n // `kem_ct` for mlkem768x25519) MUST be present and at what length, and\n // forbids the other KEM's field. Because the schema is permissive (no\n // `.strict()`), this domain pass is the ONLY thing rejecting cross-KEM\n // contamination — an x25519 slot carrying a stray `kem_ct`, or a hybrid slot\n // carrying a stray `epk`, surfaces as `ENC_SLOT_INVALID_SHAPE`.\n if (hasSlots) {\n if (enc.slots!.length < 1) {\n errors.push(\n issue('ENC_SLOTS_EMPTY', [...basePath, 'slots'], `slots length ${enc.slots!.length} < 1`),\n );\n }\n // Only validate slot shape when the KEM is known; an unknown / absent KEM\n // already emits its own code above, and we cannot pick a descriptor.\n const descriptor = enc.kem !== undefined ? KEM_SLOT_DESCRIPTORS[enc.kem] : undefined;\n if (descriptor !== undefined) {\n // The permissive `SlotSchema` strips unknown keys before they reach the\n // parsed slot, so the closed-map invariant (\"a slot is exactly {<ct\n // field>, wrap}\") is enforced against the RAW decoded slot key set here.\n const rawSlotKeys = rawSlotKeySets(item.enc);\n enc.slots!.forEach((slot, si) => {\n checkSlotShape(\n slot,\n rawSlotKeys[si] ?? new Set<string>(),\n descriptor,\n enc.kem!,\n [...basePath, 'slots', si],\n errors,\n );\n });\n }\n }\n\n // Passphrase block checks (registry membership + Argon2id closed-params + floor).\n if (hasPassphrase) {\n const pp = enc.passphrase!;\n const ppPath: ReadonlyArray<string | number> = [...basePath, 'passphrase'];\n if (!PASSPHRASE_KDF_ALGS.has(pp.alg)) {\n errors.push(\n issue(\n 'ENC_PASSPHRASE_ALG_UNSUPPORTED',\n [...ppPath, 'alg'],\n `unknown passphrase kdf alg: ${pp.alg}`,\n ),\n );\n return; // can't apply alg-specific params check\n }\n if (pp.alg === 'argon2id') {\n const allowed = new Set(['m', 't', 'p']);\n for (const k of Object.keys(pp.params)) {\n if (!allowed.has(k)) {\n errors.push(\n issue(\n 'SCHEMA_UNKNOWN_FIELD',\n [...ppPath, 'params', k],\n `unknown argon2id params field: ${k}`,\n ),\n );\n }\n }\n const p = pp.params as { m?: unknown; t?: unknown; p?: unknown };\n const argonInt = (val: unknown, name: 'm' | 't' | 'p'): number | null => {\n if (typeof val !== 'number' || !Number.isInteger(val)) {\n errors.push(\n issue(\n 'SCHEMA_TYPE_MISMATCH',\n [...ppPath, 'params', name],\n `argon2id params.${name} must be a CBOR unsigned integer`,\n ),\n );\n return null;\n }\n return val;\n };\n const mVal = argonInt(p.m, 'm');\n const tVal = argonInt(p.t, 't');\n const pVal = argonInt(p.p, 'p');\n if (mVal !== null && mVal < 65_536) {\n errors.push(\n issue(\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n [...ppPath, 'params', 'm'],\n 'argon2id requires m >= 65536 KiB',\n ),\n );\n }\n if (tVal !== null && tVal < 3) {\n errors.push(\n issue(\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n [...ppPath, 'params', 't'],\n 'argon2id requires t >= 3',\n ),\n );\n }\n if (pVal !== null && pVal < 1) {\n errors.push(\n issue(\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n [...ppPath, 'params', 'p'],\n 'argon2id requires p >= 1',\n ),\n );\n }\n }\n }\n}\n\n// KEM-driven per-slot shape gate (pure). Branches on the descriptor for the\n// declared envelope `kem`:\n//\n// - The descriptor's ciphertext-bearing field (`epk` for x25519, `kem_ct`\n// for mlkem768x25519) MUST be present at the expected (reassembled) length.\n// - The OTHER KEM's ciphertext field MUST be absent — its presence is\n// cross-KEM contamination and surfaces as `ENC_SLOT_INVALID_SHAPE` (the\n// hole that dropping `.strict()` on `SlotSchema` would otherwise open).\n// - `wrap` MUST be present at 48 bytes.\n//\n// This stays a pure function over already-decoded values: `kem_ct` reassembly\n// uses `bytesChunkArrayConcat` (byte concatenation only) — no crypto, no I/O.\n//\n// `rawKeys` is the slot's key set as it appeared on the wire (before the\n// permissive schema stripped unknowns); any key outside {<ct field>, wrap}\n// for this KEM is a closed-map violation.\nconst SLOT_KEY_UNIVERSE: ReadonlySet<string> = new Set(['epk', 'kem_ct', 'wrap']);\n\nfunction checkSlotShape(\n slot: Slot,\n rawKeys: ReadonlySet<string>,\n descriptor: KemSlotDescriptor,\n kem: string,\n slotPath: ReadonlyArray<string | number>,\n errors: ValidationIssue[],\n): void {\n // The ciphertext field that does NOT belong to this KEM. Its presence is a\n // shape violation regardless of length. Drive this off the RAW key set so a\n // future schema change cannot silently drop the foreign field before we see\n // it.\n const foreignField: KemSlotField = descriptor.field === 'epk' ? 'kem_ct' : 'epk';\n if (rawKeys.has(foreignField)) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, foreignField],\n `slot carries '${foreignField}' but kem='${kem}' expects '${descriptor.field}'`,\n ),\n );\n }\n\n // Any key outside the slot universe is a closed-map violation (the schema is\n // permissive and would otherwise strip it silently).\n for (const k of rawKeys) {\n if (!SLOT_KEY_UNIVERSE.has(k)) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, k],\n `slot carries unexpected key '${k}'; a slot is a 2-key map {${descriptor.field}, wrap}`,\n ),\n );\n }\n }\n\n // The required ciphertext-bearing field MUST be present at the expected\n // (reassembled) length.\n if (descriptor.field === 'epk') {\n if (slot.epk === undefined) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, 'epk'],\n `slot for kem='${kem}' is missing required 'epk'`,\n ),\n );\n } else if (slot.epk.length !== descriptor.fieldLength) {\n errors.push(\n issue(\n KEM_FIELD_LENGTH_CODE.epk,\n [...slotPath, 'epk'],\n `slot.epk length ${slot.epk.length} != ${descriptor.fieldLength} for ${kem}`,\n ),\n );\n }\n } else {\n if (slot.kem_ct === undefined) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, 'kem_ct'],\n `slot for kem='${kem}' is missing required 'kem_ct'`,\n ),\n );\n } else {\n const reassembled = bytesChunkArrayConcat(slot.kem_ct).length;\n if (reassembled !== descriptor.fieldLength) {\n errors.push(\n issue(\n KEM_FIELD_LENGTH_CODE.kem_ct,\n [...slotPath, 'kem_ct'],\n `slot.kem_ct reassembles to ${reassembled} bytes != ${descriptor.fieldLength} for ${kem}`,\n ),\n );\n }\n }\n }\n\n // `wrap` is 48 bytes for every KEM.\n if (slot.wrap === undefined) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, 'wrap'],\n `slot for kem='${kem}' is missing required 'wrap'`,\n ),\n );\n } else if (slot.wrap.length !== descriptor.wrapLength) {\n errors.push(\n issue(\n 'WRAP_LENGTH_MISMATCH',\n [...slotPath, 'wrap'],\n `slot.wrap length ${slot.wrap.length} != ${descriptor.wrapLength}`,\n ),\n );\n }\n}\n\n// Extract the per-slot RAW key sets from a decoded `enc` value, BEFORE the\n// permissive schema strips unknown slot keys. cbor2 surfaces a CBOR map either\n// as a `Map` (int/heterogeneous keys) or a plain object (text keys); slot maps\n// are text-keyed, so this reads string keys from whichever form. A slot that\n// is not a map at all yields an empty set — the slot's own type errors are\n// already emitted by the schema parse, so the shape gate simply finds no keys.\nfunction rawSlotKeySets(rawEnc: unknown): ReadonlyArray<ReadonlySet<string>> {\n const slots = mapLikeGet(rawEnc, 'slots');\n if (!Array.isArray(slots)) return [];\n return slots.map((slot) => {\n const keys = new Set<string>();\n if (slot instanceof Map) {\n for (const k of slot.keys()) if (typeof k === 'string') keys.add(k);\n } else if (typeof slot === 'object' && slot !== null) {\n for (const k of Object.keys(slot as Record<string, unknown>)) keys.add(k);\n }\n return keys;\n });\n}\n\nfunction mapLikeGet(value: unknown, key: string): unknown {\n if (value instanceof Map) return value.get(key);\n if (typeof value === 'object' && value !== null) {\n return (value as Record<string, unknown>)[key];\n }\n return undefined;\n}\n\n// 4i — `merkle[i]` walk.\nfunction checkMerkleCommit(commit: MerkleCommit, idx: number, errors: ValidationIssue[]): void {\n const basePath: ReadonlyArray<string | number> = ['merkle', idx];\n if (!(commit.alg in MERKLE_COMMIT_ALG_LENGTHS)) {\n errors.push(\n issue(\n 'UNSUPPORTED_MERKLE_COMMIT_ALG',\n [...basePath, 'alg'],\n `unknown merkle commitment alg: ${commit.alg}`,\n ),\n );\n return;\n }\n const expected = MERKLE_COMMIT_ALG_LENGTHS[commit.alg]!;\n if (commit.root.length !== expected) {\n errors.push(\n issue(\n 'HASH_DIGEST_LENGTH_MISMATCH',\n [...basePath, 'root'],\n `merkle entry root length ${commit.root.length} != ${expected} for ${commit.alg}`,\n ),\n );\n }\n if (commit.uris) {\n checkItemUris(commit.uris, [...basePath, 'uris'], errors);\n }\n}\n\n// 4f + 4g — record-level signature entries.\nfunction checkSigEntry(\n entry: SigEntry,\n idx: number,\n errors: ValidationIssue[],\n info: ValidationIssue[],\n): void {\n // Path-2 `cose_key` private-material guard runs FIRST.\n if (entry.cose_key !== undefined) {\n const keyIssue = inspectCoseKey(entry.cose_key, idx);\n if (keyIssue !== null) {\n errors.push(keyIssue);\n return;\n }\n }\n\n // 4g — COSE_Sign1 structural decode.\n const merged = bytesChunkArrayConcat(entry.cose_sign1);\n let cose: ReturnType<typeof decodeCoseSign1>;\n try {\n cose = decodeCoseSign1(merged);\n } catch (cause) {\n errors.push(\n issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', idx],\n cause instanceof CoseVerifyError || cause instanceof Error ? cause.message : String(cause),\n ),\n );\n return;\n }\n\n // Detached-only payload — the COSE_Sign1 payload MUST be null.\n if (cose.payload !== null) {\n errors.push(\n issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', idx],\n 'COSE_Sign1 payload must be null (detached); attached form forbidden',\n ),\n );\n return;\n }\n\n // Signature-algorithm registry check (info-severity — an unrecognised alg\n // does not fail the record).\n const alg = cose.protectedHeader.get(1);\n if (typeof alg !== 'number' || !KNOWN_SIG_ALG_IDS.has(alg)) {\n info.push(\n issue(\n 'SIGNATURE_UNSUPPORTED',\n ['sigs', idx],\n `COSE_Sign1 protected alg ${String(alg)} not in {-8, -19}`,\n ),\n );\n }\n\n // Path-1 (32-byte protected-header `kid`) and path-2 (`cose_key` sidecar)\n // are mutually exclusive — a sig entry must not carry both.\n const protectedKid = cose.protectedHeader.get(4);\n if (\n protectedKid instanceof Uint8Array &&\n protectedKid.length === 32 &&\n entry.cose_key !== undefined\n ) {\n errors.push(\n issue(\n 'SIG_ENTRY_KID_COSE_KEY_CONFLICT',\n ['sigs', idx],\n 'sigs[i] carries both a 32-byte protected `kid` (path 1) and an inline `cose_key` (path 2); paths are mutually exclusive',\n ),\n );\n }\n}\n\n// =============================================================================\n// COSE_Key inspector (path-2 `sigs[i].cose_key` blob)\n// =============================================================================\n//\n// Two structural checks:\n// 5a — Private-material guard (FIRST). COSE_Key label `-4` (the private\n// scalar `d` for OKP / EC2 per RFC 9052 §7.1) → `SIG_PRIVATE_KEY_LEAKED`.\n// This check is load-bearing producer-side preflight: publishing a\n// private key on the permanent ledger is catastrophic and irreversible.\n// 5b — Positive-shape guard. The decoded `cbor<COSE_Key>` map MUST carry\n// `kty=1` (OKP), `crv=6` (Ed25519), and a 32-byte `-2` (x). Any\n// failure → `MALFORMED_SIG_COSE_SIGN1`.\n\nfunction inspectCoseKey(keyChunks: ReadonlyArray<Uint8Array>, i: number): ValidationIssue | null {\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(bytesChunkArrayConcat(keyChunks));\n } catch (cause) {\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key failed to decode as cbor<COSE_Key>: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n }\n\n // cbor2 surfaces int-keyed COSE_Key maps as `Map`; string-keyed maps as\n // plain JS objects (a malformed COSE_Key would carry string keys).\n const getLabel = (label: number): unknown => {\n if (decoded instanceof Map) return decoded.get(label);\n if (typeof decoded === 'object' && decoded !== null) {\n return (decoded as Record<string, unknown>)[String(label)];\n }\n return undefined;\n };\n const hasLabel = (label: number): boolean => {\n if (decoded instanceof Map) return decoded.has(label);\n if (typeof decoded === 'object' && decoded !== null) {\n return Object.prototype.hasOwnProperty.call(decoded, String(label));\n }\n return false;\n };\n\n // 5a — Private-material guard.\n if (hasLabel(-4)) {\n return issue(\n 'SIG_PRIVATE_KEY_LEAKED',\n ['sigs', i, 'cose_key'],\n 'cose_key carries COSE_Key private-key material (label -4, the OKP/EC2 private scalar d); publishing a private key on the permanent ledger is forbidden',\n );\n }\n\n // 5b — Positive-shape guard.\n const kty = getLabel(1);\n if (kty !== 1) {\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key kty (label 1) must be 1 (OKP); got ${String(kty)}`,\n );\n }\n const crv = getLabel(-1);\n if (crv !== 6) {\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key crv (label -1) must be 6 (Ed25519); got ${String(crv)}`,\n );\n }\n if (!hasLabel(-2)) {\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key missing label -2 (Ed25519 public-key bytes)`,\n );\n }\n const x = getLabel(-2);\n if (!(x instanceof Uint8Array) || x.length !== 32) {\n const got = x instanceof Uint8Array ? `${x.length}-byte bstr` : typeof x;\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key label -2 must be a 32-byte byte string (Ed25519 public key); got ${got}`,\n );\n }\n return null;\n}\n\n// =============================================================================\n// Label 309 CID profile\n// =============================================================================\n//\n// Accept CIDv0 (`Qm` prefix, 46-char base58btc, sha2-256 multihash) and\n// CIDv1 (multibase prefix + version 0x01 + codec + multihash) per the\n// closed profile:\n// - Multibase: b, B, f, F, z\n// - Multicodec: 0x55 (raw), 0x70 (dag-pb), 0x71 (dag-cbor)\n// - Multihash: 0x12 (sha2-256, 32 B), 0xb220 (blake2b-256, 32 B)\n//\n// Returns true iff the CID conforms to the Label 309 profile.\n\nconst ACCEPTED_CIDV1_MULTIBASE: ReadonlySet<string> = new Set(['b', 'B', 'f', 'F', 'z']);\n\nconst ACCEPTED_MULTICODECS: ReadonlySet<number> = new Set([0x55, 0x70, 0x71]);\n\n// Multihash table: code → digest length (bytes).\n// `0x12` = sha2-256; `0xb220` = blake2b-256.\nconst ACCEPTED_MULTIHASHES: ReadonlyMap<number, number> = new Map([\n [0x12, 32],\n [0xb220, 32],\n]);\n\nexport function validateCidProfile(cid: string): boolean {\n if (cid.length === 0) return false;\n // CIDv0: a base58btc-encoded sha2-256 multihash. Decode the WHOLE string and\n // verify the multihash prefix (0x12 = sha2-256, 0x20 = 32-byte digest length)\n // and total length (34 bytes = 2-byte prefix + 32-byte digest). A `Qm`\n // prefix alone is not sufficient — a malformed body must be rejected.\n if (cid.startsWith('Qm')) {\n let decoded: Uint8Array;\n try {\n decoded = decodeBase58btc(cid);\n } catch {\n return false;\n }\n return decoded.length === 34 && decoded[0] === 0x12 && decoded[1] === 0x20;\n }\n // CIDv1: multibase + binary CID body.\n const mbPrefix = cid[0]!;\n if (!ACCEPTED_CIDV1_MULTIBASE.has(mbPrefix)) return false;\n let bytes: Uint8Array;\n try {\n bytes = decodeMultibase(mbPrefix, cid.slice(1));\n } catch {\n return false;\n }\n if (bytes.length < 4) return false;\n // CIDv1 layout: <version varint> <multicodec varint> <multihash>\n const versionParse = readVarint(bytes, 0);\n if (versionParse === null || versionParse.value !== 1) return false;\n const codecParse = readVarint(bytes, versionParse.next);\n if (codecParse === null) return false;\n if (!ACCEPTED_MULTICODECS.has(codecParse.value)) return false;\n const mhParse = readVarint(bytes, codecParse.next);\n if (mhParse === null) return false;\n const lenParse = readVarint(bytes, mhParse.next);\n if (lenParse === null) return false;\n const digestLen = lenParse.value;\n const expectedLen = ACCEPTED_MULTIHASHES.get(mhParse.value);\n if (expectedLen === undefined || digestLen !== expectedLen) return false;\n if (lenParse.next + digestLen !== bytes.length) return false;\n return true;\n}\n\nfunction readVarint(bytes: Uint8Array, start: number): { value: number; next: number } | null {\n let value = 0;\n let shift = 0;\n let i = start;\n while (i < bytes.length) {\n const b = bytes[i]!;\n value |= (b & 0x7f) << shift;\n i++;\n if ((b & 0x80) === 0) return { value, next: i };\n shift += 7;\n if (shift > 28) return null; // overflow guard; Label 309 profile uses ≤ 16-bit codes\n }\n return null;\n}\n\n// Multibase decoders for the closed set the CID profile admits.\nfunction decodeMultibase(prefix: string, body: string): Uint8Array {\n switch (prefix) {\n case 'b':\n return decodeBase32(body.toLowerCase(), 'rfc4648-lower');\n case 'B':\n return decodeBase32(body.toUpperCase(), 'rfc4648-upper');\n case 'f':\n return decodeBase16(body.toLowerCase());\n case 'F':\n return decodeBase16(body.toUpperCase());\n case 'z':\n return decodeBase58btc(body);\n default:\n throw new Error(`unsupported multibase prefix ${prefix}`);\n }\n}\n\nconst BASE16_LOWER = '0123456789abcdef';\nconst BASE16_UPPER = '0123456789ABCDEF';\n\nfunction decodeBase16(s: string): Uint8Array {\n if (s.length % 2 !== 0) throw new Error('base16: odd-length');\n const out = new Uint8Array(s.length / 2);\n const alphabet = s === s.toLowerCase() ? BASE16_LOWER : BASE16_UPPER;\n for (let i = 0; i < out.length; i++) {\n const hi = alphabet.indexOf(s[i * 2]!);\n const lo = alphabet.indexOf(s[i * 2 + 1]!);\n if (hi < 0 || lo < 0) throw new Error(`base16: non-hex char at ${i * 2}`);\n out[i] = (hi << 4) | lo;\n }\n return out;\n}\n\nconst BASE32_RFC4648_LOWER = 'abcdefghijklmnopqrstuvwxyz234567';\nconst BASE32_RFC4648_UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';\n\nfunction decodeBase32(s: string, variant: 'rfc4648-lower' | 'rfc4648-upper'): Uint8Array {\n const alphabet = variant === 'rfc4648-lower' ? BASE32_RFC4648_LOWER : BASE32_RFC4648_UPPER;\n // Multibase strips padding per spec; we accept either form for robustness.\n const trimmed = s.replace(/=+$/, '');\n const out: number[] = [];\n let buf = 0;\n let bits = 0;\n for (const ch of trimmed) {\n const idx = alphabet.indexOf(ch);\n if (idx < 0) throw new Error(`base32: invalid char '${ch}'`);\n buf = (buf << 5) | idx;\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n out.push((buf >> bits) & 0xff);\n }\n }\n return Uint8Array.from(out);\n}\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\nfunction decodeBase58btc(s: string): Uint8Array {\n if (s.length === 0) return new Uint8Array(0);\n let zeros = 0;\n while (zeros < s.length && s[zeros] === '1') zeros++;\n const size = Math.floor(((s.length - zeros) * 733) / 1000) + 1;\n const b256 = new Uint8Array(size);\n let length = 0;\n for (let i = zeros; i < s.length; i++) {\n const ch = s[i]!;\n const carryIdx = BASE58_ALPHABET.indexOf(ch);\n if (carryIdx < 0) throw new Error(`base58: invalid char '${ch}'`);\n let carry = carryIdx;\n let k = 0;\n for (let j = size - 1; (carry !== 0 || k < length) && j >= 0; j--, k++) {\n carry += 58 * b256[j]!;\n b256[j] = carry % 256;\n carry = Math.floor(carry / 256);\n }\n length = k;\n }\n let it = size - length;\n while (it < size && b256[it] === 0) it++;\n const out = new Uint8Array(zeros + (size - it));\n let j = zeros;\n while (it < size) {\n out[j++] = b256[it++]!;\n }\n return out;\n}\n\n// =============================================================================\n// `crit[]` shape rule helper\n// =============================================================================\n\nfunction checkCritShape(\n record: PoeRecord,\n decodedTopKeys: ReadonlySet<string>,\n errors: ValidationIssue[],\n): Set<number> {\n const invalid = new Set<number>();\n if (!Array.isArray(record.crit)) return invalid;\n // `crit` has `1*` cardinality: when present it MUST carry at least one\n // entry. An empty array is a malformed shape — reject it here in the\n // domain pass (rather than via a schema `.min(1)`) so the emitted message\n // string is identical across the TS/PY/RS validators.\n if (record.crit.length === 0) {\n errors.push(\n issue('SCHEMA_TYPE_MISMATCH', ['crit'], 'crit[] must carry at least one entry when present'),\n );\n return invalid;\n }\n const seen = new Set<string>();\n for (let i = 0; i < record.crit.length; i++) {\n const critName = record.crit[i]!;\n let reason: string | null = null;\n if (TOP_LEVEL_BASE_KEYS.has(critName)) {\n reason = `'${critName}' is a base key and MUST NOT appear in crit[]`;\n } else if (!isExtensionKey(critName)) {\n reason = `'${critName}' does not match the extension-key regex (^x-.+ or ^[a-z]+-.+)`;\n } else if (!decodedTopKeys.has(critName)) {\n reason = `'${critName}' is named in crit but absent from the record map`;\n } else if (seen.has(critName)) {\n reason = `'${critName}' appears more than once in crit[]`;\n }\n seen.add(critName);\n if (reason !== null) {\n invalid.add(i);\n errors.push(issue('CRIT_SHAPE_INVALID', ['crit', i], reason));\n }\n }\n return invalid;\n}\n\nfunction topLevelKeysOf(decoded: unknown): Set<string> {\n if (decoded === null || typeof decoded !== 'object') return new Set();\n if (decoded instanceof Map) {\n const out = new Set<string>();\n for (const k of decoded.keys()) {\n if (typeof k === 'string') out.add(k);\n }\n return out;\n }\n return new Set(Object.keys(decoded as Record<string, unknown>));\n}\n\n// =============================================================================\n// Path / issue helpers\n// =============================================================================\n\nfunction issue(\n code: ErrorCode,\n path: ReadonlyArray<string | number>,\n message: string,\n): ValidationIssue {\n return { code, path, message, severity: SEVERITY[code] };\n}\n\nfunction compareIssuePath(a: ValidationIssue, b: ValidationIssue): number {\n return a.path.join('.').localeCompare(b.path.join('.'));\n}\n\nfunction valueAtPath(root: unknown, path: ReadonlyArray<string | number>): unknown {\n let cur: unknown = root;\n for (const seg of path) {\n if (cur === null || cur === undefined) return undefined;\n if (cur instanceof Map) {\n cur = cur.get(seg);\n continue;\n }\n if (typeof cur !== 'object') return undefined;\n cur = (cur as Record<string | number, unknown>)[seg];\n }\n return cur;\n}\n","import { argon2id } from 'hash-wasm';\n\nexport interface Argon2idParams {\n readonly memSizeKB: number;\n readonly iterations: number;\n readonly parallelism: number;\n readonly outBytes: number;\n}\n\nexport interface Argon2idV13Opts {\n readonly password: Uint8Array;\n readonly salt: Uint8Array;\n readonly memSizeKB: number;\n readonly iterations: number;\n readonly parallelism: number;\n readonly outBytes: number;\n}\n\nexport async function argon2idV13(opts: Argon2idV13Opts): Promise<Uint8Array> {\n return (await argon2id({\n password: opts.password,\n salt: opts.salt,\n parallelism: opts.parallelism,\n iterations: opts.iterations,\n memorySize: opts.memSizeKB,\n hashLength: opts.outBytes,\n outputType: 'binary',\n })) as Uint8Array;\n}\n","export class AeadVerificationError extends Error {\n readonly code: string = 'aead_verification_failed';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'AeadVerificationError';\n }\n}\n","import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';\n\nimport { AeadVerificationError } from './errors';\n\nexport interface XChaCha20Poly1305EncryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly plaintext: Uint8Array;\n}\n\nexport interface XChaCha20Poly1305DecryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly ciphertext: Uint8Array;\n}\n\nexport function xchacha20Poly1305Encrypt(opts: XChaCha20Poly1305EncryptOpts): Uint8Array {\n return xchacha20poly1305(opts.key, opts.nonce, opts.aad).encrypt(opts.plaintext);\n}\n\nexport function xchacha20Poly1305Decrypt(opts: XChaCha20Poly1305DecryptOpts): Uint8Array {\n try {\n return xchacha20poly1305(opts.key, opts.nonce, opts.aad).decrypt(opts.ciphertext);\n } catch (cause) {\n throw new AeadVerificationError('xchacha20-poly1305 decrypt failed', { cause });\n }\n}\n","import { sha256 as nobleSha256 } from '@noble/hashes/sha2.js';\n\nexport function sha256(input: Uint8Array): Uint8Array {\n return nobleSha256(input);\n}\n","// RFC 9162 §2.1.1 binary Merkle tree under SHA-256.\n// This implements the algorithm tier identified on the wire as the\n// `rfc9162-sha256` OPT-INFO; the record's `merkle[]` field carries the proof.\n//\n// Construction (RFC 9162 §2.1.1):\n// - Single leaf: MTH({d_0}) = SHA-256(0x00 || d_0)\n// - Internal node: MTH(L) = SHA-256(0x01 || MTH(L[0:k]) || MTH(L[k:n]))\n// where k = largest power of 2 strictly less than n.\n// - Empty trees (n == 0) are FORBIDDEN.\n// - The 0x00 leaf / 0x01 internal prefixes prevent the CVE-2012-2459\n// leaf-vs-internal collision family.\n\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { compareCt } from '../util/compare-ct';\n\nexport const MERKLE_ALG_ID = 'rfc9162-sha256' as const;\n\nconst LEAF_PREFIX = 0x00;\nconst NODE_PREFIX = 0x01;\nconst DIGEST_LENGTH = 32;\n\nfunction validateLeaves(leaves: ReadonlyArray<Uint8Array>, fnName: string): void {\n if (leaves.length === 0) {\n throw new Error(`${fnName}: empty leaf list (n == 0 is forbidden by RFC 9162 §2.1.1)`);\n }\n for (let i = 0; i < leaves.length; i++) {\n const leaf = leaves[i];\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) {\n throw new Error(\n `${fnName}: leaf[${i}] must be a Uint8Array(${DIGEST_LENGTH}); got length ${\n leaf instanceof Uint8Array ? leaf.length : 'non-Uint8Array'\n }`,\n );\n }\n }\n}\n\nexport function merkleSha2256Root(leaves: ReadonlyArray<Uint8Array>): Uint8Array {\n validateLeaves(leaves, 'merkleSha2256Root');\n return mthRecursive(leaves, 0, leaves.length);\n}\n\nexport function merkleSha2256InclusionProof(\n leaves: ReadonlyArray<Uint8Array>,\n index: number,\n): Uint8Array[] {\n validateLeaves(leaves, 'merkleSha2256InclusionProof');\n if (!Number.isInteger(index) || index < 0 || index >= leaves.length) {\n throw new Error(\n `merkleSha2256InclusionProof: index ${index} out of range [0, ${leaves.length})`,\n );\n }\n return auditPath(leaves, index, 0, leaves.length);\n}\n\n/**\n * Verify an inclusion proof per RFC 9162 §2.1.3.2 (iterative form).\n *\n * `proof` is ordered leaf-to-root: `proof[0]` is the sibling at the leaf\n * level, `proof[m-1]` is the top-level sibling. The fold uses the\n * `sn`/`fn` tracking from RFC 9162: `sn` is the leaf index within the\n * current subtree, `fn` is (subtree_size - 1). At each step, `sn` odd\n * OR `sn == fn` means the current node is a right child (sibling on\n * the left); otherwise it is a left child (sibling on the right).\n * Both shift right by one each iteration. This handles non-power-of-2\n * sizes including the \"promote a lone right subtree\" cases.\n */\nexport function merkleSha2256VerifyInclusion(\n leaf: Uint8Array,\n index: number,\n treeSize: number,\n proof: ReadonlyArray<Uint8Array>,\n root: Uint8Array,\n): boolean {\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) return false;\n if (!(root instanceof Uint8Array) || root.length !== DIGEST_LENGTH) return false;\n if (\n !Number.isInteger(index) ||\n !Number.isInteger(treeSize) ||\n treeSize < 1 ||\n index < 0 ||\n index >= treeSize\n ) {\n return false;\n }\n for (let i = 0; i < proof.length; i++) {\n const sibling = proof[i];\n if (!(sibling instanceof Uint8Array) || sibling.length !== DIGEST_LENGTH) {\n return false;\n }\n }\n\n if (treeSize === 1) {\n if (proof.length !== 0 || index !== 0) return false;\n return compareCt(hashLeaf(leaf), root);\n }\n\n let h = hashLeaf(leaf);\n let sn = index;\n let fn = treeSize - 1;\n for (let i = 0; i < proof.length; i++) {\n if (fn === 0) return false;\n const sibling = proof[i] as Uint8Array;\n if ((sn & 1) === 1 || sn === fn) {\n h = hashNode(sibling, h);\n while ((sn & 1) === 0 && sn !== 0) {\n sn >>>= 1;\n fn >>>= 1;\n }\n } else {\n h = hashNode(h, sibling);\n }\n sn >>>= 1;\n fn >>>= 1;\n }\n if (fn !== 0) return false;\n return compareCt(h, root);\n}\n\nfunction largestPow2Lt(n: number): number {\n let k = 1;\n while (k * 2 < n) k *= 2;\n return k;\n}\n\nfunction hashLeaf(d: Uint8Array): Uint8Array {\n const buf = new Uint8Array(1 + d.length);\n buf[0] = LEAF_PREFIX;\n buf.set(d, 1);\n return sha256(buf);\n}\n\nfunction hashNode(left: Uint8Array, right: Uint8Array): Uint8Array {\n const buf = new Uint8Array(1 + left.length + right.length);\n buf[0] = NODE_PREFIX;\n buf.set(left, 1);\n buf.set(right, 1 + left.length);\n return sha256(buf);\n}\n\nfunction mthRecursive(leaves: ReadonlyArray<Uint8Array>, start: number, end: number): Uint8Array {\n const n = end - start;\n if (n === 1) {\n return hashLeaf(leaves[start] as Uint8Array);\n }\n const k = largestPow2Lt(n);\n const left = mthRecursive(leaves, start, start + k);\n const right = mthRecursive(leaves, start + k, end);\n return hashNode(left, right);\n}\n\nfunction auditPath(\n leaves: ReadonlyArray<Uint8Array>,\n i: number,\n start: number,\n end: number,\n): Uint8Array[] {\n const n = end - start;\n if (n === 1) return [];\n const k = largestPow2Lt(n);\n if (i < k) {\n const subPath = auditPath(leaves, i, start, start + k);\n subPath.push(mthRecursive(leaves, start + k, end));\n return subPath;\n }\n const subPath = auditPath(leaves, i - k, start + k, end);\n subPath.push(mthRecursive(leaves, start, start + k));\n return subPath;\n}\n","/**\n * Utilities for hex, bytearray and number handling.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport {\n type CHash,\n type TypedArray,\n abytes,\n abytes as abytes_,\n concatBytes,\n isLE,\n randomBytes as randb,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Asserts that a value is a byte array and optionally checks its length.\n * Returns the original reference unchanged on success, and currently also accepts Node `Buffer`\n * values through the upstream validator.\n * This helper throws on malformed input, so APIs that must return `false` need to guard lengths\n * before decoding or before calling it.\n * @example\n * Validate that a value is a byte array with the expected length.\n * ```ts\n * abytes(new Uint8Array([1]), 1);\n * ```\n */\nconst abytesDoc: typeof abytes = abytes;\nexport { abytesDoc as abytes };\n/**\n * Concatenates byte arrays into a new `Uint8Array`.\n * Zero arguments return an empty `Uint8Array`.\n * Invalid segments throw before allocation because each argument is validated first.\n * @example\n * Concatenate two byte arrays into one result.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nconst concatBytesDoc: typeof concatBytes = concatBytes;\nexport { concatBytesDoc as concatBytes };\n/**\n * Returns cryptographically secure random bytes.\n * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable.\n * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation,\n * so negative and fractional values both throw instead of truncating through JS `ToIndex`.\n * @param bytesLength - Number of random bytes to generate.\n * @returns Fresh random bytes.\n * @example\n * Generate a fresh random seed.\n * ```ts\n * const seed = randomBytes(4);\n * ```\n */\nexport const randomBytes: typeof randb = randb;\n\n/**\n * Compares two byte arrays in a length-constant way for equal lengths.\n * Unequal lengths return `false` immediately, and there is no runtime type validation.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns Whether both arrays contain the same bytes.\n * @example\n * Compare two byte arrays for equality.\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies bytes into a fresh `Uint8Array`.\n * Returns a detached plain `Uint8Array` after validating that the input is real bytes.\n * @param bytes - Source bytes.\n * @returns Copy of the input bytes.\n * @example\n * Copy bytes into a fresh array.\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Byte-swaps each 64-bit lane in place.\n * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need\n * this boundary helper before aliasing them as host `Float64Array` lanes.\n * @param arr - Byte buffer whose length is a multiple of 8.\n * @returns The same buffer after in-place 64-bit lane byte swaps.\n * @example\n * Byte-swap one 64-bit lane in place.\n * ```ts\n * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport function byteSwap64<T extends ArrayBufferView>(arr: T): T {\n const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n for (let i = 0; i < bytes.length; i += 8) {\n const a0 = bytes[i + 0];\n const a1 = bytes[i + 1];\n const a2 = bytes[i + 2];\n const a3 = bytes[i + 3];\n bytes[i + 0] = bytes[i + 7];\n bytes[i + 1] = bytes[i + 6];\n bytes[i + 2] = bytes[i + 5];\n bytes[i + 3] = bytes[i + 4];\n bytes[i + 4] = a3;\n bytes[i + 5] = a2;\n bytes[i + 6] = a1;\n bytes[i + 7] = a0;\n }\n return arr;\n}\n/**\n * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian.\n * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as\n * `Float64Array` lanes on the current host.\n * @param arr - Buffer to pass through or swap in place.\n * @returns The same buffer, normalized for Falcon's little-endian table layout.\n * @example\n * Normalize one host-endian buffer for Falcon's float tables.\n * ```ts\n * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport const baswap64If: <T extends ArrayBufferView>(arr: T) => T = isLE\n ? (arr) => arr\n : byteSwap64;\n\n/** Shared key-generation surface for signers and KEMs. */\nexport type CryptoKeys = {\n /** Optional metadata about the algorithm family or variant. */\n info?: { type?: string };\n /** Public byte lengths for the exported key material. */\n lengths: { seed?: number; publicKey?: number; secretKey?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: TArg<Uint8Array>) => {\n secretKey: TRet<Uint8Array>;\n publicKey: TRet<Uint8Array>;\n };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/** Verification options shared by the signature APIs. */\nexport type VerOpts = {\n /** Optional application-defined context string. */\n context?: Uint8Array;\n};\n/** Signing options shared by the signature APIs. */\nexport type SigOpts = VerOpts & {\n // Compatibility with @noble/curves: false to disable, enabled by default, user can pass U8A\n /** Optional extra entropy or `false` to disable randomized signing. */\n extraEntropy?: Uint8Array | false;\n};\n\n/**\n * Validates that an options bag is a plain object.\n * @param opts - Options object to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate that an options bag is a plain object.\n * ```ts\n * validateOpts({});\n * ```\n */\nexport function validateOpts(opts: object): void {\n // Arrays silently passed here before, but these call sites expect named option-bag fields.\n if (Object.prototype.toString.call(opts) !== '[object Object]')\n throw new TypeError('expected valid options object');\n}\n\n/**\n * Validates common verification options.\n * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support\n * further after this shared plain-object gate.\n * @param opts - Verification options. See {@link VerOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common verification options.\n * ```ts\n * validateVerOpts({ context: new Uint8Array([1]) });\n * ```\n */\nexport function validateVerOpts(opts: TArg<VerOpts>): void {\n validateOpts(opts);\n if (opts.context !== undefined) abytes(opts.context, undefined, 'opts.context');\n}\n\n/**\n * Validates common signing options.\n * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific\n * restrictions are enforced later by callers.\n * @param opts - Signing options. See {@link SigOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common signing options.\n * ```ts\n * validateSigOpts({ extraEntropy: new Uint8Array([1]) });\n * ```\n */\nexport function validateSigOpts(opts: TArg<SigOpts>): void {\n validateVerOpts(opts);\n if (opts.extraEntropy !== false && opts.extraEntropy !== undefined)\n abytes(opts.extraEntropy, undefined, 'opts.extraEntropy');\n}\n\n/** Generic signature interface with key generation, signing, and verification. */\nexport type Signer = CryptoKeys & {\n /** Public byte lengths for signatures and signing randomness. */\n lengths: { signRand?: number; signature?: number };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing options.\n * @returns Signature bytes.\n */\n sign: (\n msg: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts?: TArg<SigOpts>\n ) => TRet<Uint8Array>;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @param opts - Optional verification options.\n * @returns `true` when the signature is valid, `false` when all inputs are well-formed but the\n * signature check does not pass. Some implementations also treat malformed signature encodings as\n * a verification failure and return `false`.\n * @throws On malformed API arguments or unsupported verification options.\n */\n verify: (\n sig: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n opts?: TArg<VerOpts>\n ) => boolean;\n};\n\n/** Generic key encapsulation mechanism interface. */\nexport type KEM = CryptoKeys & {\n /** Public byte lengths for ciphertexts and optional message randomness. */\n lengths: { cipherText?: number; msg?: number; msgRand?: number };\n /**\n * Encapsulate one shared secret to a recipient public key.\n * @param publicKey - Recipient public key bytes.\n * @param msg - Optional caller-provided randomness/message seed.\n * @returns Ciphertext plus shared secret.\n */\n encapsulate: (\n publicKey: TArg<Uint8Array>,\n msg?: TArg<Uint8Array>\n ) => {\n cipherText: TRet<Uint8Array>;\n sharedSecret: TRet<Uint8Array>;\n };\n /**\n * Recover the shared secret from a ciphertext and recipient secret key.\n * @param cipherText - Ciphertext bytes.\n * @param secretKey - Recipient secret key bytes.\n * @returns Decapsulated shared secret.\n */\n decapsulate: (cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/** Bidirectional encoder/decoder interface. */\nexport interface Coder<F, T> {\n /**\n * Serialize one value.\n * @param from - Value to encode.\n * @returns Encoded representation.\n */\n encode(from: F): T;\n /**\n * Parse one serialized value.\n * @param to - Encoded representation.\n * @returns Decoded value.\n */\n decode(to: T): F;\n}\n\n/** Encoder/decoder interface specialized for byte arrays. */\nexport interface BytesCoder<T> extends Coder<T, Uint8Array> {\n /**\n * Serialize one value into bytes.\n * @param data - Value to encode.\n * @returns Encoded bytes.\n */\n encode: (data: T) => Uint8Array;\n /**\n * Parse one byte array into a value.\n * @param bytes - Encoded bytes.\n * @returns Decoded value.\n */\n decode: (bytes: Uint8Array) => T;\n}\n\n/** Fixed-length byte encoder/decoder. */\nexport type BytesCoderLen<T> = BytesCoder<T> & { bytesLen: number };\n\n// nano-packed, because struct encoding is hard.\ntype UnCoder<T> = T extends BytesCoder<infer U> ? U : never;\ntype SplitOut<T extends (number | BytesCoderLen<any>)[]> = {\n [K in keyof T]: T[K] extends number ? Uint8Array : UnCoder<T[K]>;\n};\n/**\n * Builds a fixed-layout coder from byte lengths and nested coders.\n * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that\n * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder`\n * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards\n * caller-owned bytes, it must do so only after detaching them into a disposable copy.\n * @param label - Label used in validation errors.\n * @param lengths - Field lengths or nested coders.\n * @returns Composite fixed-length coder.\n * @example\n * Build a fixed-layout coder from byte lengths and nested coders.\n * ```ts\n * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]);\n * ```\n */\nexport function splitCoder<T extends (number | BytesCoderLen<any>)[]>(\n label: string,\n ...lengths: T\n): TRet<BytesCoder<SplitOut<T>> & { bytesLen: number }> {\n const getLength = (c: TArg<number | BytesCoderLen<any>>) =>\n typeof c === 'number' ? c : (c as BytesCoderLen<any>).bytesLen;\n const bytesLen: number = lengths.reduce((sum: number, a) => sum + getLength(a), 0);\n return {\n bytesLen,\n encode: (bufs: T) => {\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < lengths.length; i++) {\n const c = lengths[i];\n const l = getLength(c);\n const b: Uint8Array = typeof c === 'number' ? (bufs[i] as any) : c.encode(bufs[i]);\n abytes_(b, l, label);\n res.set(b, pos);\n if (typeof c !== 'number') b.fill(0); // clean\n pos += l;\n }\n return res;\n },\n decode: (buf: TArg<Uint8Array>) => {\n abytes_(buf, bytesLen, label);\n const res = [];\n for (const c of lengths) {\n const l = getLength(c);\n const b = buf.subarray(0, l);\n res.push(typeof c === 'number' ? b : c.decode(b));\n buf = buf.subarray(l);\n }\n return res as SplitOut<T>;\n },\n } as any;\n}\n// nano-packed.array (fixed size)\n/**\n * Builds a fixed-length vector coder from another fixed-length coder.\n * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder.\n * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into\n * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned\n * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts\n * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes.\n * @param c - Element coder.\n * @param vecLen - Number of elements in the vector.\n * @returns Fixed-length vector coder.\n * @example\n * Build a fixed-length vector coder from another fixed-length coder.\n * ```ts\n * vecCoder(\n * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 },\n * 2\n * ).encode([1, 2]);\n * ```\n */\nexport function vecCoder<T>(c: TArg<BytesCoderLen<T>>, vecLen: number): TRet<BytesCoderLen<T[]>> {\n const coder = c as BytesCoderLen<T>;\n const bytesLen = vecLen * coder.bytesLen;\n return {\n bytesLen,\n encode: (u: TArg<T[]>): TRet<Uint8Array> => {\n if (u.length !== vecLen)\n throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < u.length; i++) {\n const b = coder.encode(u[i] as T);\n res.set(b, pos);\n b.fill(0); // clean\n pos += b.length;\n }\n return res as TRet<Uint8Array>;\n },\n decode: (a: TArg<Uint8Array>): TRet<T[]> => {\n abytes_(a, bytesLen);\n const r: T[] = [];\n for (let i = 0; i < a.length; i += coder.bytesLen)\n r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));\n return r as TRet<T[]>;\n },\n } as any;\n}\n\n/**\n * Overwrites supported typed-array inputs with zeroes in place.\n * Accepts direct typed arrays and one-level arrays of them.\n * @param list - Typed arrays or one-level lists of typed arrays to clear.\n * @example\n * Overwrite typed arrays with zeroes.\n * ```ts\n * const buf = Uint8Array.of(1, 2, 3);\n * cleanBytes(buf);\n * ```\n */\nexport function cleanBytes(...list: (TypedArray | TypedArray[])[]): void {\n for (const t of list) {\n if (Array.isArray(t)) for (const b of t) b.fill(0);\n else t.fill(0);\n }\n}\n\n/**\n * Creates a 32-bit mask with the lowest `bits` bits set.\n * @param bits - Number of low bits to keep.\n * @returns Bit mask with `bits` ones.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Create a low-bit mask for packed-field operations.\n * ```ts\n * const mask = getMask(4);\n * ```\n */\nexport function getMask(bits: number): number {\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new RangeError(`expected bits in [0..32], got ${bits}`);\n // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask.\n return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0;\n}\n\n/** Shared empty byte array used as the default context. */\nexport const EMPTY: TRet<Uint8Array> = /* @__PURE__ */ Uint8Array.of();\n\n/**\n * Builds the domain-separated message payload for the pure sign/verify paths.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated message payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated payload before direct signing.\n * ```ts\n * const payload = getMessage(new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessage(msg: TArg<Uint8Array>, ctx: TArg<Uint8Array> = EMPTY): TRet<Uint8Array> {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);\n}\n\n// DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the\n// FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128,\n// SHAKE256, or another approved hash/XOF under that subtree.\n// 06 09 60 86 48 01 65 03 04 02\nconst oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]);\n\n/**\n * Validates that a hash exposes a NIST hash OID and enough collision resistance.\n * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST\n * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough.\n * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend\n * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes.\n * @param hash - Hash function to validate.\n * @param requiredStrength - Minimum required collision-resistance strength in bits.\n * @throws If the hash metadata or collision resistance is insufficient. {@link Error}\n * @example\n * Validate that a hash exposes a NIST hash OID and enough collision resistance.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { checkHash } from '@noble/post-quantum/utils.js';\n * checkHash(sha256, 128);\n * ```\n */\nexport function checkHash(hash: CHash, requiredStrength: number = 0): void {\n if (!hash.oid || !equalBytes(hash.oid.subarray(0, 10), oidNistP))\n throw new Error('hash.oid is invalid: expected NIST hash');\n // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST\n // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is\n // the tighter runtime check, so enforce that lower bound here.\n const collisionResistance = (hash.outputLen * 8) / 2;\n if (requiredStrength > collisionResistance) {\n throw new Error(\n 'Pre-hash security strength too low: ' +\n collisionResistance +\n ', required: ' +\n requiredStrength\n );\n }\n}\n\n/**\n * Builds the domain-separated prehash payload for the prehash sign/verify paths.\n * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper\n * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param hash - Prehash function.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated prehash payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated prehash payload for external hashing.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { getMessagePrehash } from '@noble/post-quantum/utils.js';\n * getMessagePrehash(sha256, new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessagePrehash(\n hash: CHash,\n msg: TArg<Uint8Array>,\n ctx: TArg<Uint8Array> = EMPTY\n): TRet<Uint8Array> {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n const hashed = hash(msg);\n return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid!, hashed);\n}\n","/**\n * Internal methods for lattice-based ML-KEM and ML-DSA.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { FFTCore, reverseBits } from '@noble/curves/abstract/fft.js';\nimport { shake128, shake256 } from '@noble/hashes/sha3.js';\nimport type { TypedArray } from '@noble/hashes/utils.js';\nimport {\n type BytesCoderLen,\n cleanBytes,\n type Coder,\n getMask,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/** Extendable-output reader used by the CRYSTALS implementations. */\nexport type XOF = (\n seed: Uint8Array,\n blockLen?: number\n) => {\n /**\n * Read diagnostic counters for the current XOF session.\n * @returns Current call and XOF block counters.\n */\n stats: () => { calls: number; xofs: number };\n /**\n * Select one `(x, y)` coordinate pair and get a block reader for it.\n * Only one coordinate stream is live at a time: a later `get(...)` call rebinds the shared\n * SHAKE state and invalidates older readers.\n * Each squeeze aliases one mutable internal output buffer, so callers must copy blocks they\n * want to retain before the next read.\n * @param x - First matrix coordinate.\n * @param y - Second matrix coordinate.\n * @returns Lazy block reader for that coordinate pair.\n */\n get: (x: number, y: number) => () => Uint8Array; // return block aligned to blockLen and 3\n /** Wipe any buffered state once the reader is no longer needed. */\n clean: () => void;\n};\n\n/** CRYSTALS (ml-kem, ml-dsa) options */\n/** Shared polynomial and NTT parameters for CRYSTALS algorithms. */\nexport type CrystalOpts<T extends TypedArray> = {\n /**\n * Allocate one zeroed polynomial/vector container.\n * @param n - Number of coefficients to allocate.\n * @returns Fresh typed container.\n */\n newPoly: TypedCons<T>;\n /** Polynomial size, typically `256`. */\n N: number;\n /** Prime modulus used for all coefficient arithmetic. */\n Q: number;\n /** Inverse transform normalization factor:\n * `256**-1 mod q` for Dilithium, `128**-1 mod q` for Kyber.\n */\n F: number;\n /** Principal root of unity for the transform domain. */\n ROOT_OF_UNITY: number;\n /** Number of bits used for bit-reversal ordering. */\n brvBits: number;\n /** `true` for Kyber/ML-KEM mode, `false` for Dilithium/ML-DSA mode. */\n isKyber: boolean;\n};\n\n/** Constructor function for typed polynomial containers. */\nexport type TypedCons<T extends TypedArray> = (n: number) => T;\n\ntype Crystals<T extends TypedArray> = {\n mod: (a: number, modulo?: number) => number;\n smod: (a: number, modulo?: number) => number;\n nttZetas: T;\n NTT: {\n /** Forward transform in place. Mutates and returns `r`. */\n encode: (r: T) => T;\n /** Inverse transform in place. Mutates and returns `r`. */\n decode: (r: T) => T;\n };\n bitsCoder: (d: number, c: Coder<number, number>) => BytesCoderLen<T>;\n};\n\n/**\n * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes.\n * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}.\n * @returns CRYSTALS arithmetic and encoding helpers.\n * @example\n * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set.\n * ```ts\n * const crystals = genCrystals({\n * newPoly: (n) => new Uint16Array(n),\n * N: 256,\n * Q: 3329,\n * F: 3303,\n * ROOT_OF_UNITY: 17,\n * brvBits: 7,\n * isKyber: true,\n * });\n * const reduced = crystals.mod(-1);\n * ```\n */\nexport const genCrystals = <T extends TypedArray>(opts: CrystalOpts<T>): TRet<Crystals<T>> => {\n // isKyber: true means Kyber, false means Dilithium\n const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;\n // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by\n // FIPS 203 §2.3 / FIPS 204 §2.3 before downstream mod-q arithmetic.\n const mod = (a: number, modulo = Q): number => {\n const result = a % modulo | 0;\n return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0;\n };\n // FIPS 204 §7.4 uses the centered `mod ±` representative for low bits, keeping the\n // positive midpoint when `modulo` is even.\n // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`.\n const smod = (a: number, modulo = Q): number => {\n const r = mod(a, modulo) | 0;\n return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0;\n };\n // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while\n // Dilithium uses the FIPS 204 §7.5 / Appendix B `BitRev_8` zetas table over all 256 entries.\n function getZettas() {\n const out = newPoly(N);\n for (let i = 0; i < N; i++) {\n const b = reverseBits(i, brvBits);\n const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);\n out[i] = Number(p) | 0;\n }\n return out;\n }\n const nttZetas = getZettas();\n\n // Number-Theoretic Transform\n // Explained: https://electricdusk.com/ntt.html\n\n // Kyber has slightly different params, since there is no 512th primitive root of unity mod q,\n // only 256th primitive root of unity mod. Which also complicates MultiplyNTT.\n\n const field = {\n add: (a: number, b: number) => mod((a | 0) + (b | 0)) | 0,\n sub: (a: number, b: number) => mod((a | 0) - (b | 0)) | 0,\n mul: (a: number, b: number) => mod((a | 0) * (b | 0)) | 0,\n inv: (_a: number) => {\n throw new Error('not implemented');\n },\n };\n const nttOpts = {\n N,\n roots: nttZetas as any,\n invertButterflies: true,\n skipStages: isKyber ? 1 : 0,\n brp: false,\n };\n const dif = FFTCore(field, { dit: false, ...nttOpts });\n const dit = FFTCore(field, { dit: true, ...nttOpts });\n const NTT = {\n encode: (r: T): T => {\n return dif(r) as any;\n },\n decode: (r: T): T => {\n dit(r as any);\n // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14\n // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`.\n // kyber uses 128 here, because brv && stuff\n for (let i = 0; i < r.length; i++) r[i] = mod(F * r[i]);\n return r;\n },\n };\n // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode /\n // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers.\n const bitsCoder = (d: number, c: Coder<number, number>): TRet<BytesCoderLen<T>> => {\n const mask = getMask(d);\n const bytesLen = d * (N / 8);\n return {\n bytesLen,\n encode: (poly_: TArg<T>): TRet<Uint8Array> => {\n const poly = poly_ as T;\n const r = new Uint8Array(bytesLen);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {\n buf |= (c.encode(poly[i]) & mask) << bufLen;\n bufLen += d;\n for (; bufLen >= 8; bufLen -= 8, buf >>= 8) r[pos++] = buf & getMask(bufLen);\n }\n return r as TRet<Uint8Array>;\n },\n decode: (bytes: TArg<Uint8Array>): TRet<T> => {\n const r = newPoly(N);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {\n buf |= bytes[i] << bufLen;\n bufLen += 8;\n for (; bufLen >= d; bufLen -= d, buf >>= d) r[pos++] = c.decode(buf & mask);\n }\n return r as TRet<T>;\n },\n } as TRet<BytesCoderLen<T>>;\n };\n\n return {\n mod,\n smod,\n nttZetas: nttZetas as TRet<T>,\n NTT: {\n encode: (r: TArg<T>): TRet<T> => NTT.encode(r as T) as TRet<T>,\n decode: (r: TArg<T>): TRet<T> => NTT.decode(r as T) as TRet<T>,\n },\n bitsCoder: bitsCoder as TRet<Crystals<T>>['bitsCoder'],\n };\n};\n\nconst createXofShake =\n (shake: typeof shake128): TRet<XOF> =>\n (seed: TArg<Uint8Array>, blockLen?: number) => {\n if (!blockLen) blockLen = shake.blockLen;\n // Optimizations that won't mater:\n // - cached seed update (two .update(), on start and on the end)\n // - another cache which cloned into working copy\n\n // Faster than multiple updates, since seed less than blockLen\n const _seed = new Uint8Array(seed.length + 2);\n _seed.set(seed);\n const seedLen = seed.length;\n const buf = new Uint8Array(blockLen); // == shake128.blockLen\n let h = shake.create({});\n let calls = 0;\n let xofs = 0;\n return {\n stats: () => ({ calls, xofs }),\n get: (x: number, y: number) => {\n // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate\n // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`.\n _seed[seedLen + 0] = x;\n _seed[seedLen + 1] = y;\n h.destroy();\n h = shake.create({}).update(_seed);\n calls++;\n return () => {\n xofs++;\n return h.xofInto(buf) as TRet<Uint8Array>;\n };\n },\n clean: () => {\n h.destroy();\n cleanBytes(buf, _seed);\n },\n };\n };\n\n/**\n * SHAKE128-based extendable-output reader factory used by ML-KEM.\n * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously\n * returned readers, and each squeeze reuses one mutable internal output buffer.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-KEM SHAKE128 matrix expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF128 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF128(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF128: TRet<XOF> = /* @__PURE__ */ createXofShake(shake128);\n/**\n * SHAKE256-based extendable-output reader factory used by ML-DSA.\n * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned\n * readers, and reuses one mutable internal output buffer for each squeeze.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-DSA SHAKE256 coefficient expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF256 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF256(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF256: TRet<XOF> = /* @__PURE__ */ createXofShake(shake256);\n","/**\n * ML-KEM: Module Lattice-based Key Encapsulation Mechanism from\n * [FIPS-203](https://csrc.nist.gov/pubs/fips/203/ipd). A.k.a. CRYSTALS-Kyber.\n *\n * Key encapsulation is similar to DH / ECDH (think X25519), with important differences:\n * * Unlike in ECDH, we can't verify if it was \"Bob\" who've sent the shared secret\n * * Unlike ECDH, it is probabalistic and relies on quality of randomness (CSPRNG).\n * * Decapsulation never throws an error, even when shared secret was\n * encrypted by a different public key. It will just return a different shared secret.\n *\n * There are some concerns with regards to security: see\n * [djb blog](https://blog.cr.yp.to/20231003-countcorrectly.html) and\n * [mailing list](https://groups.google.com/a/list.nist.gov/g/pqc-forum/c/W2VOzy0wz_E).\n *\n * Has similar internals to ML-DSA, but their keys and params are different.\n *\n * Check out [official site](https://www.pq-crystals.org/kyber/resources.shtml),\n * [repo](https://github.com/pq-crystals/kyber),\n * [spec](https://datatracker.ietf.org/doc/draft-cfrg-schwabe-kyber/).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { sha3_256, sha3_512, shake256 } from '@noble/hashes/sha3.js';\nimport { type CHash, swap32IfBE, u32 } from '@noble/hashes/utils.js';\nimport { genCrystals, type XOF, XOF128 } from './_crystals.ts';\nimport {\n abytes,\n cleanBytes,\n type Coder,\n copyBytes,\n equalBytes,\n getMask,\n type KEM,\n randomBytes,\n splitCoder,\n type TArg,\n type TRet,\n vecCoder,\n} from './utils.ts';\n\n/** Key encapsulation mechanism interface */\n\nconst N = 256; // Kyber (not FIPS-203) supports different lengths, but all std modes were using 256\nconst Q = 3329; // 13*(2**8)+1, modulo prime\nconst F = 3303; // 3303 ≡ 128**(−1) mod q (FIPS-203)\nconst ROOT_OF_UNITY = 17; // ζ = 17 ∈ Zq is a primitive 256-th root of unity modulo Q. ζ**128 ≡−1\n// treeshake: keep genCrystals behind the object so PARAMS-only bundles can drop it entirely.\n// Shared CRYSTALS helper in the ML-KEM branch: Kyber mode, 7-bit bit-reversal,\n// and Uint16Array polys because current coefficients stay reduced modulo q.\nconst crystals = /* @__PURE__ */ genCrystals({\n N,\n Q,\n F,\n ROOT_OF_UNITY,\n newPoly: (n: number): TRet<Uint16Array> => new Uint16Array(n) as TRet<Uint16Array>,\n brvBits: 7,\n isKyber: true,\n});\n\n/** FIPS 203: 7. Parameter Sets */\n/** Public ML-KEM parameter-set description. */\nexport type KEMParam = {\n /** Polynomial size. */\n N: number;\n /** Module rank. */\n K: number;\n /** Prime modulus. */\n Q: number;\n /** CBD parameter used for secret-key noise. */\n ETA1: number;\n /** CBD parameter used for error noise. */\n ETA2: number;\n /** Compression width for the `u` vector. */\n du: number;\n /** Compression width for the `v` polynomial. */\n dv: number;\n /** Required strength of the randomness source in bits. */\n RBGstrength: number;\n};\n/** Internal params of ML-KEM versions */\n// prettier-ignore\n/** Built-in ML-KEM parameter presets keyed by the public export names\n * `ml_kem512` / `ml_kem768` / `ml_kem1024`.\n * `RBGstrength` is Table 2's required randomness-source strength in bits,\n * not a generic security label.\n */\nexport const PARAMS: Record<string, KEMParam> = /* @__PURE__ */ (() =>\n Object.freeze({\n 512: Object.freeze({ N, Q, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),\n 768: Object.freeze({ N, Q, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),\n 1024: Object.freeze({ N, Q, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 }),\n } as const))();\n\n// FIPS-203: compress/decompress\nconst compress = (d: number): Coder<number, number> => {\n // d=12 is the ByteEncode12/ByteDecode12 path, not lossy compression.\n // ByteDecode12 interprets each 12-bit word modulo q; without that reduction the public-key\n // modulus check in encapsulate() becomes a no-op for malformed coefficients like 4095.\n if (d >= 12) return { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) };\n // Comments map to python implementation in RFC (draft-cfrg-schwabe-kyber)\n // const round = (i: number) => Math.floor(i + 0.5) | 0;\n const a = 2 ** (d - 1);\n return {\n // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).\n encode: (i: number) => ((i << d) + Q / 2) / Q,\n // const decompress = (i: number) => round((Q / 2 ** d) * i);\n decode: (i: number) => (i * Q + a) >>> d,\n };\n};\n\n// Raw ByteEncode_d / ByteDecode_d from FIPS 203 operate on d-bit words directly.\n// That differs from `polyCoder(d)` for d<12, where noble folds packing together with the lossy\n// ciphertext compression step used by u/v. Tests that exercise the spec's raw packing surface need\n// this exact non-lossy variant instead.\nconst byteCoder = (d: number) =>\n crystals.bitsCoder(\n d,\n d === 12\n ? { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) }\n : { encode: (i: number) => i, decode: (i: number) => i }\n );\n\n// NOTE: we merge encoding and compress because it is faster, also both require same d param\n// d=12 is the ByteEncode12/ByteDecode12 path rather than compression, and caller-side\n// public-key modulus checks route through this helper's decode/encode roundtrip.\n// Converts between bytes and d-bits compressed representation.\n// Kinda like convertRadix2 from @scure/base.\n// decode(encode(t)) == t, but there is loss of information on encode(decode(t))\nconst polyCoder = (d: number) => (d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d)));\n\n// Poly is mod Q, so 12 bits\ntype Poly = Uint16Array;\n\nfunction polyAdd(a_: TArg<Poly>, b_: TArg<Poly>) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] + b[i]); // a += b\n}\nfunction polySub(a_: TArg<Poly>, b_: TArg<Poly>) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] - b[i]); // a -= b\n}\n\n// FIPS-203: Computes the product of two degree-one polynomials with respect to a quadratic modulus\nfunction BaseCaseMultiply(a0: number, a1: number, b0: number, b1: number, zeta: number) {\n // `zeta` here is Algorithm 11's γ = ζ^(2BitRev_7(i)+1).\n const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);\n const c1 = crystals.mod(a0 * b1 + a1 * b0);\n return { c0, c1 };\n}\n\n// FIPS-203: Computes the product (in the ring Tq) of two NTT representations.\n// Works in place on `f`; `g` is read-only and both inputs must already be in NTT form.\nfunction MultiplyNTTs(f_: TArg<Poly>, g_: TArg<Poly>): TRet<Poly> {\n const f = f_ as Poly;\n const g = g_ as Poly;\n for (let i = 0; i < N / 2; i++) {\n let z = crystals.nttZetas[64 + (i >> 1)];\n if (i & 1) z = -z;\n const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);\n f[2 * i + 0] = c0;\n f[2 * i + 1] = c1;\n }\n return f as TRet<Poly>;\n}\n\ntype PRF = (l: number, key: Uint8Array, nonce: number) => Uint8Array;\n\ntype XofGet = ReturnType<ReturnType<XOF>['get']>;\n\ntype KyberOpts = KEMParam & {\n HASH256: CHash;\n HASH512: CHash;\n KDF: CHash<any, { dkLen?: number }>;\n XOF: XOF; // (seed: Uint8Array, len: number, x: number, y: number) => Uint8Array;\n PRF: PRF;\n};\n\n// Return poly in NTT representation\nfunction SampleNTT(xof_: TArg<XofGet>): TRet<Poly> {\n const xof = xof_ as XofGet;\n // The reader must already bind the Algorithm 7 seed||j||i bytes\n // and return block lengths divisible by 3.\n const r: Poly = new Uint16Array(N);\n for (let j = 0; j < N; ) {\n const b = xof();\n if (b.length % 3) throw new Error('SampleNTT: unaligned block');\n for (let i = 0; j < N && i + 3 <= b.length; i += 3) {\n const d1 = ((b[i + 0] >> 0) | (b[i + 1] << 8)) & 0xfff;\n const d2 = ((b[i + 1] >> 4) | (b[i + 2] << 4)) & 0xfff;\n if (d1 < Q) r[j++] = d1;\n if (j < N && d2 < Q) r[j++] = d2;\n }\n }\n return r as TRet<Poly>;\n}\n\n// Sampling from the centered binomial distribution\n// Returns poly with small coefficients (noise/errors) stored modulo q in ordinary coefficient form.\n// Current callers only use Table 2 eta values {2,3} and PRF outputs of exactly 64*eta bytes.\nconst sampleCBDBytes = (buf: TArg<Uint8Array>, eta: number): TRet<Poly> => {\n const r: Poly = new Uint16Array(N);\n // CBD consumes the PRF bitstream in little-endian byte order; normalize the word view on BE,\n // then swap it back so callers still observe `buf` as read-only.\n const b32 = u32(buf);\n swap32IfBE(b32);\n let len = 0;\n for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {\n let b = b32[i];\n for (let j = 0; j < 32; j++) {\n bb += b & 1;\n b >>= 1;\n len += 1;\n if (len === eta) {\n t0 = bb;\n bb = 0;\n } else if (len === 2 * eta) {\n r[p++] = crystals.mod(t0 - bb);\n bb = 0;\n len = 0;\n }\n }\n }\n swap32IfBE(b32);\n if (len) throw new Error(`sampleCBD: leftover bits: ${len}`);\n return r as TRet<Poly>;\n};\n\nfunction sampleCBD(\n PRF_: TArg<PRF>,\n seed: TArg<Uint8Array>,\n nonce: number,\n eta: number\n): TRet<Poly> {\n const PRF = PRF_ as PRF;\n return sampleCBDBytes(PRF((eta * N) / 4, seed, nonce), eta);\n}\n\n// K-PKE\n// Internal ML-KEM subroutine only: exact 32-byte `seed` / `msg` inputs\n// come from Algorithms 13-15, and the helper mutates decoded temporary\n// polynomials in place while leaving caller byte arrays unchanged.\nconst genKPKE = (opts_: TArg<KyberOpts>) => {\n const opts = opts_ as KyberOpts;\n const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts;\n const poly1 = polyCoder(1);\n const polyV = polyCoder(dv);\n const polyU = polyCoder(du);\n const publicCoder = splitCoder('publicKey', vecCoder(polyCoder(12), K), 32);\n const secretCoder = vecCoder(polyCoder(12), K);\n const cipherCoder = splitCoder('ciphertext', vecCoder(polyU, K), polyV);\n const seedCoder = splitCoder('seed', 32, 32);\n return {\n secretCoder,\n lengths: {\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n cipherText: cipherCoder.bytesLen,\n },\n keygen: (seed: TArg<Uint8Array>) => {\n abytes(seed, 32, 'seed');\n const seedDst = new Uint8Array(33);\n seedDst.set(seed);\n // FIPS 203 Algorithm 13 appends the parameter-set byte `k`\n // before `G(d || k)`, so expanding the same 32-byte seed\n // under a different ML-KEM parameter set yields unrelated keys.\n seedDst[32] = K;\n const seedHash = HASH512(seedDst);\n\n const [rho, sigma] = seedCoder.decode(seedHash);\n const sHat: Poly[] = [];\n const tHat: Poly[] = [];\n for (let i = 0; i < K; i++) sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));\n const x = XOF(rho);\n for (let i = 0; i < K; i++) {\n const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));\n for (let j = 0; j < K; j++) {\n const aji = SampleNTT(x.get(j, i)); // A[i][j], inplace\n polyAdd(e, MultiplyNTTs(aji, sHat[j]));\n }\n tHat.push(e); // t ← A ◦ s + e\n }\n x.clean();\n const res = {\n publicKey: publicCoder.encode([tHat, rho]),\n secretKey: secretCoder.encode(sHat),\n };\n cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);\n return res;\n },\n encrypt: (\n publicKey: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n seed: TArg<Uint8Array>\n ): TRet<Uint8Array> => {\n const [tHat, rho] = publicCoder.decode(publicKey);\n const rHat = [];\n for (let i = 0; i < K; i++) rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));\n const x = XOF(rho);\n const tmp2 = new Uint16Array(N);\n const u = [];\n for (let i = 0; i < K; i++) {\n const e1 = sampleCBD(PRF, seed, K + i, ETA2);\n const tmp = new Uint16Array(N);\n for (let j = 0; j < K; j++) {\n const aij = SampleNTT(x.get(i, j)); // A[j][i], inplace transpose access\n polyAdd(tmp, MultiplyNTTs(aij, rHat[j])); // t += aij * rHat[j]\n }\n polyAdd(e1, crystals.NTT.decode(tmp)); // e1 += tmp\n u.push(e1);\n polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i])); // t2 += tHat[i] * rHat[i]\n cleanBytes(tmp);\n }\n x.clean();\n const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);\n polyAdd(e2, crystals.NTT.decode(tmp2)); // e2 += tmp2\n const v = poly1.decode(msg); // encode plaintext m into polynomial v\n polyAdd(v, e2); // v += e2\n cleanBytes(tHat, rHat, tmp2, e2);\n return cipherCoder.encode([u, v]) as TRet<Uint8Array>;\n },\n decrypt: (cipherText: TArg<Uint8Array>, privateKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n const [u, v] = cipherCoder.decode(cipherText);\n const sk = secretCoder.decode(privateKey); // s ← ByteDecode_12(dkPKE)\n const tmp = new Uint16Array(N);\n // tmp += sk[i] * u[i]\n for (let i = 0; i < K; i++) polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));\n polySub(v, crystals.NTT.decode(tmp)); // w = v' - tmp\n cleanBytes(tmp, sk, u);\n return poly1.encode(v) as TRet<Uint8Array>;\n },\n };\n};\n\n/**\n * Public ML-KEM wrapper over the internal K-PKE subroutine.\n * `keygen(seed)` and `encapsulate(publicKey, msg)` are deterministic/test-oriented hooks that map\n * more directly to Algorithms 16-17 than to the pure no-input / random-internal Algorithms 19-20.\n * decapsulate() tries to follow the Algorithms 18/21 implicit-reject structure as closely as\n * practical here by re-encrypting, comparing ciphertexts, returning `Khat` on match or `Kbar` on\n * mismatch, and zeroizing the non-returned shared-secret candidate; JS/JIT still provides no\n * constant-time guarantees for that path.\n */\nfunction createKyber(opts: TArg<KyberOpts>): TRet<KEM> {\n const rawOpts = opts as KyberOpts;\n const KPKE = genKPKE(rawOpts);\n const { HASH256, HASH512, KDF } = rawOpts;\n const { secretCoder: KPKESecretCoder, lengths } = KPKE;\n const secretCoder = splitCoder('secretKey', lengths.secretKey, lengths.publicKey, 32, 32);\n const msgLen = 32;\n const seedLen = 64;\n const kemLengths = Object.freeze({\n ...lengths,\n seed: 64,\n msg: msgLen,\n msgRand: msgLen,\n secretKey: secretCoder.bytesLen,\n });\n return Object.freeze({\n info: Object.freeze({ type: 'ml-kem' }),\n lengths: kemLengths,\n keygen: (seed: TArg<Uint8Array> = randomBytes(seedLen)) => {\n abytes(seed, seedLen, 'seed');\n const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));\n const publicKeyHash = HASH256(publicKey);\n // (dkPKE||ek||H(ek)||z)\n const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);\n cleanBytes(sk, publicKeyHash);\n return {\n publicKey: publicKey as TRet<Uint8Array>,\n secretKey: secretKey as TRet<Uint8Array>,\n };\n },\n getPublicKey: (secretKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);\n return Uint8Array.from(publicKey) as TRet<Uint8Array>;\n },\n encapsulate: (publicKey: TArg<Uint8Array>, msg: TArg<Uint8Array> = randomBytes(msgLen)) => {\n abytes(publicKey, lengths.publicKey, 'publicKey');\n abytes(msg, msgLen, 'message');\n\n // FIPS-203 includes additional verification check for modulus\n const eke = publicKey.subarray(0, 384 * opts.K);\n // Copy because of inplace encoding\n const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));\n // (Modulus check.) Perform the computation ek ← ByteEncode12(ByteDecode12(eke)).\n // If ek = ̸ eke, the input is invalid. (See Section 4.2.1.)\n if (!equalBytes(ek, eke)) {\n cleanBytes(ek);\n throw new Error('ML-KEM.encapsulate: wrong publicKey modulus');\n }\n cleanBytes(ek);\n // derive randomness\n const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();\n const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n cleanBytes(kr.subarray(32));\n return {\n cipherText: cipherText as TRet<Uint8Array>,\n sharedSecret: kr.subarray(0, 32) as TRet<Uint8Array>,\n };\n },\n decapsulate: (cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n abytes(secretKey, secretCoder.bytesLen, 'secretKey'); // 768*k + 96\n abytes(cipherText, lengths.cipherText, 'cipherText'); // 32(du*k + dv)\n // test ← H(dk[384𝑘 ∶ 768𝑘 + 32])) .\n const k768 = secretCoder.bytesLen - 96;\n const start = k768 + 32;\n const test = HASH256(secretKey.subarray(k768 / 2, start));\n // If test ≠ dk[768𝑘 + 32 ∶ 768𝑘 + 64], then input checking has failed.\n if (!equalBytes(test, secretKey.subarray(start, start + 32)))\n throw new Error('invalid secretKey: hash check failed');\n const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);\n const msg = KPKE.decrypt(cipherText, sk);\n // derive randomness, Khat, rHat = G(mHat || h)\n const kr = HASH512.create().update(msg).update(publicKeyHash).digest();\n const Khat = kr.subarray(0, 32);\n // re-encrypt using the derived randomness\n const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n // if ciphertexts do not match, “implicitly reject”\n const isValid = equalBytes(cipherText, cipherText2);\n const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();\n cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);\n return (isValid ? Khat : Kbar) as TRet<Uint8Array>;\n },\n });\n}\n\n// FIPS 203's PRF_eta binding: current callers use only 32-byte keys, one-byte nonces,\n// and dkLen values {128, 192}; out-of-range nonce numbers still wrap modulo 256 here.\nfunction shakePRF(dkLen: number, key: TArg<Uint8Array>, nonce: number): TRet<Uint8Array> {\n return shake256\n .create({ dkLen })\n .update(key)\n .update(new Uint8Array([nonce]))\n .digest() as TRet<Uint8Array>;\n}\n\n// Fixed ML-KEM hash/XOF bindings. `KDF` here is the spec's fixed 32-byte `J` call,\n// and swapping any field changes the scheme rather than tuning an internal dependency.\nconst opts = /* @__PURE__ */ (() => ({\n HASH256: sha3_256,\n HASH512: sha3_512,\n KDF: shake256,\n XOF: XOF128,\n PRF: shakePRF,\n}))();\n// Parameter-set instantiation step for the spec's \"ML-KEM-x\" names; current correctness relies\n// on the internal PARAMS rows rather than local validation of arbitrary KEMParam objects.\nconst mk = (params: KEMParam) =>\n createKyber({\n ...opts,\n ...params,\n });\n\n/**\n * ML-KEM-512: Table 2 row `k=2, η1=3, η2=2, du=10, dv=4`; Table 3 sizes `800/1632/768/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem512: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[512]))();\n/**\n * ML-KEM-768: Table 2 row `k=3, η1=2, η2=2, du=10, dv=4`; Table 3 sizes `1184/2400/1088/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem768: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[768]))();\n/**\n * ML-KEM-1024: Table 2 row `k=4, η1=2, η2=2, du=11, dv=5`; Table 3 sizes `1568/3168/1568/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem1024: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[1024]))();\n\n// NOTE: for tests only, don't use. This keeps the exact internal ML-KEM math surfaces available\n// without re-implementing them in separate test code.\nexport const __tests: any = /* @__PURE__ */ (() =>\n Object.freeze({\n Compress_d: (x: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Compress_d: expected d in [1..11], got ${d}`);\n return compress(d).encode(x) & getMask(d);\n },\n Decompress_d: (y: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Decompress_d: expected d in [1..11], got ${d}`);\n return compress(d).decode(y);\n },\n ByteEncode_d: (F: TArg<Uint16Array>, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteEncode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).encode(F as TRet<Uint16Array>);\n },\n ByteDecode_d: (B: TArg<Uint8Array>, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteDecode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).decode(B);\n },\n NTT: (f: TArg<Uint16Array>) => crystals.NTT.encode(Uint16Array.from(f)),\n NTT_inv: (fHat: TArg<Uint16Array>) => crystals.NTT.decode(Uint16Array.from(fHat)),\n MultiplyNTTs: (fHat: TArg<Uint16Array>, gHat: TArg<Uint16Array>) =>\n MultiplyNTTs(Uint16Array.from(fHat), Uint16Array.from(gHat)),\n SamplePolyCBD: (B: TArg<Uint8Array>, eta: number) => {\n abytes(B, 64 * eta, 'B');\n return sampleCBDBytes(B, eta);\n },\n SampleNTT: (B: TArg<Uint8Array>) => {\n abytes(B, 34, 'B');\n const xof = XOF128(B.subarray(0, 32));\n try {\n return SampleNTT(xof.get(B[32], B[33]));\n } finally {\n xof.clean();\n }\n },\n }))();\n","/**\n * Post-Quantum Hybrid Cryptography\n *\n * The current implementation is flawed and likely redundant. We should offer\n * a small, generic API to compose hybrid schemes instead of reimplementing\n * protocol-specific logic (SSH, GPG, etc.) with ad hoc encodings.\n *\n * 1. Core Issues\n * - sign/verify: implemented as two separate operations with different keys.\n * - EC getSharedSecret: could be refactored into a proper KEM.\n * - Multiple calls: keys, signatures, and shared secrets could be\n * concatenated to reduce the number of API invocations.\n * - Reinvention: most libraries add strange domain separations and\n * encodings instead of simple byte concatenation.\n *\n * 2. API Goals\n * - Provide primitives to build hybrids generically.\n * - Avoid embedding SSH- or GPG-specific formats in the core API.\n *\n * 3. Edge Cases\n * • Variable-length signatures:\n * - DER-encoded (Weierstrass curves).\n * - Falcon (unpadded).\n * - Concatenation works only if length is fixed; otherwise a length\n * prefix is required (but that breaks compatibility).\n *\n * • getSharedSecret:\n * - Default: non-KEM (authenticated ECDH).\n * - KEM conversion: generate a random SK to remove implicit auth.\n *\n * 4. Common Pitfalls\n * - Seed expansion:\n * • Expanding a small seed into multiple keys reduces entropy.\n * • API should allow identity mapping (no expansion).\n *\n * - Skipping full point encoding:\n * • Some omit the compression byte (parity) for WebCrypto compatibility.\n * • Better: hash the raw secret; coordinate output is already non-uniform.\n * • Some curves (e.g., X448) produce secrets that must be re-hashed to match\n * symmetric-key lengths.\n *\n * - Combiner inconsistencies:\n * • Different domain separations and encodings across libraries.\n * • Should live at the application layer, since key lengths vary.\n *\n * 5. Protocol Examples\n * - SSH:\n * • Concatenate keys.\n * • Combiner: SHA-512.\n *\n * - GPG:\n * • Concatenate keys.\n * • Combiner:\n * SHA3-256(kemShare || ecdhShare || ciphertext || pubKey || algId || domSep || len(domSep))\n *\n * - TLS:\n * • Transcript-based derivation (HKDF).\n *\n * 6. Relevant Specs & Implementations\n * - IETF Hybrid KEM drafts:\n * • draft-irtf-cfrg-hybrid-kems\n * • draft-connolly-cfrg-xwing-kem\n * • draft-westerbaan-tls-xyber768d00\n *\n * - PQC Libraries:\n * • superdilithium (cyph/pqcrypto.js) – low adoption.\n * • hybrid-pqc (DogeProtocol, quantumcoinproject) – complex encodings.\n *\n * 7. Signatures\n * - Ed25519: fixed-size, easy to support.\n * - Variable-size: introduces custom format requirements; best left to\n * higher-level code.\n *\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { type EdDSA } from '@noble/curves/abstract/edwards.js';\nimport { type MontgomeryECDH } from '@noble/curves/abstract/montgomery.js';\nimport { type ECDSA } from '@noble/curves/abstract/weierstrass.js';\nimport { x25519 } from '@noble/curves/ed25519.js';\nimport { p256, p384 } from '@noble/curves/nist.js';\nimport {\n asciiToBytes,\n bytesToNumberBE,\n bytesToNumberLE,\n concatBytes,\n numberToBytesBE,\n} from '@noble/curves/utils.js';\nimport { expand, extract } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { sha3_256, shake256 } from '@noble/hashes/sha3.js';\nimport { abytes, ahash, anumber, type CHash, type CHashXOF } from '@noble/hashes/utils.js';\nimport { ml_kem1024, ml_kem768 } from './ml-kem.ts';\nimport {\n cleanBytes,\n copyBytes,\n randomBytes,\n splitCoder,\n validateSigOpts,\n validateVerOpts,\n type CryptoKeys,\n type KEM,\n type Signer,\n type TArg,\n type TRet,\n} from './utils.ts';\n\ntype CurveAll = ECDSA | EdDSA | MontgomeryECDH;\ntype CurveECDH = ECDSA | MontgomeryECDH;\ntype CurveSign = ECDSA | EdDSA;\n\n// Can re-use if decide to signatures support, on other hand getSecretKey is specific and ugly\nfunction ecKeygen(curve: CurveAll, allowZeroKey: boolean = false) {\n const lengths = curve.lengths;\n let keygen = curve.keygen;\n if (allowZeroKey) {\n // Only the ECDSA/Weierstrass branch uses raw scalar-byte secret keys here. Edwards seeds are\n // hashed/pruned and Montgomery keys are clamped byte strings, so forcing Point.Fn semantics on\n // those curves would change key construction instead of just relaxing scalar range handling.\n if (!('getSharedSecret' in curve && 'sign' in curve && 'verify' in curve))\n throw new Error('allowZeroKey requires a Weierstrass curve');\n // This legacy flag is really \"skip the +1 shift\" for vector matching, not \"accept scalar 0\".\n // It swaps seeded Weierstrass keygen from reduction into [1, ORDER) to direct reduction into\n // [0, ORDER), which preserves exact reduced bytes but still leaves scalar 0 invalid.\n // This is ugly, but we need to return exact results here.\n const wCurve = curve as ECDSA;\n const Fn = wCurve.Point.Fn;\n // Unlike noble-curves' seeded Weierstrass keygen, this path removes the post-reduction +1.\n // That is enough to match exact reduced-vector bytes, but an all-zero seed still reduces to\n // scalar 0 here and getPublicKey(secretKey) throws instead of \"allowing zero\".\n keygen = (seed: TArg<Uint8Array> = randomBytes(lengths.seed)) => {\n abytes(seed, lengths.seed!, 'seed');\n const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);\n // Reduce directly into [0, ORDER); scalar 0 still stays invalid.\n const secretKey = Fn.toBytes(Fn.create(seedScalar));\n return {\n secretKey: secretKey as TRet<Uint8Array>,\n publicKey: curve.getPublicKey(secretKey) as TRet<Uint8Array>,\n };\n };\n }\n return {\n lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed },\n keygen: (seed?: TArg<Uint8Array>) =>\n keygen(seed) as TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }>,\n getPublicKey: (secretKey: TArg<Uint8Array>) =>\n curve.getPublicKey(secretKey) as TRet<Uint8Array>,\n };\n}\n\n/**\n * Wraps an ECDH-capable curve as a KEM.\n * Shared secrets stay in the wrapped curve's raw ECDH byte format with no built-in KDF.\n * On SEC 1 / Weierstrass curves, that means the compressed shared-point body without the\n * 1-byte `0x02` / `0x03` prefix.\n * The X25519 path also leaves RFC 7748's optional all-zero shared-secret check to callers.\n * @param curve - Curve with `getSharedSecret`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns KEM wrapper over the curve.\n * @throws If the curve does not expose `getSharedSecret`. {@link Error}\n * @example\n * Wrap an ECDH-capable curve as a generic KEM.\n * ```ts\n * import { x25519 } from '@noble/curves/ed25519.js';\n * import { ecdhKem } from '@noble/post-quantum/hybrid.js';\n * const kem = ecdhKem(x25519);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function ecdhKem(curve: CurveECDH, allowZeroKey: boolean = false): TRet<KEM> {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.getSharedSecret) throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n encapsulate(\n publicKey: TArg<Uint8Array>,\n rand: TArg<Uint8Array> = randomBytes(curve.lengths.seed)\n ) {\n // Some curve.keygen(seed) paths reuse the provided seed buffer as secretKey; detach caller\n // randomness first so cleanBytes() only wipes wrapper-owned material.\n const seed = copyBytes(rand);\n let ek: Uint8Array | undefined = undefined;\n try {\n ek = this.keygen(seed).secretKey;\n const sharedSecret = this.decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek) as TRet<Uint8Array>;\n return { sharedSecret, cipherText };\n } finally {\n // Invalid peer public keys can make decapsulation throw; wipe both the detached seed and\n // derived ephemeral secret key even when encapsulation aborts before returning.\n cleanBytes(seed);\n if (ek) cleanBytes(ek);\n }\n },\n decapsulate(cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) {\n const res = curve.getSharedSecret(secretKey, cipherText);\n return (curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res) as TRet<Uint8Array>;\n },\n };\n}\n\n/**\n * Wraps a curve signer as a generic `Signer`.\n * Signatures stay in the wrapped curve's native byte encoding.\n * This wrapper does not normalize or document which per-curve signing options are meaningful.\n * @param curve - Curve with `sign` and `verify`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns Signer wrapper over the curve.\n * @throws If the curve does not expose `sign` and `verify`. {@link Error}\n * @example\n * Wrap a curve signer as a generic signer.\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { ecSigner } from '@noble/post-quantum/hybrid.js';\n * const signer = ecSigner(ed25519);\n * const sigLen = signer.lengths.signature;\n * ```\n */\nexport function ecSigner(curve: CurveSign, allowZeroKey: boolean = false): TRet<Signer> {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.sign || !curve.verify) throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, signature: curve.lengths.signature, signRand: 0 },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n sign: (message, secretKey, opts = {}) => {\n validateSigOpts(opts);\n // This generic wrapper intentionally keeps the Signer contract to message + key only.\n // Backend-specific knobs like ECDSA extraEntropy or Ed25519ctx context cannot be forwarded\n // uniformly through combineSigners(), so callers that need them must use the curve directly.\n if (opts.extraEntropy !== undefined)\n throw new Error(\n 'ecSigner does not support extraEntropy; use the underlying curve directly'\n );\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.sign(message, secretKey) as TRet<Uint8Array>;\n },\n /** Verify one wrapped curve signature.\n * Returns the wrapped curve's `verify()` result for well-formed inputs. Throws on unsupported\n * generic opts and lets wrapped-curve malformed-input errors escape unchanged.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.verify(signature, message, publicKey);\n },\n };\n}\n\nfunction splitLengths<K extends string, T extends { lengths: Partial<Record<K, number>> }>(\n lst: T[],\n name: K\n) {\n // Preserve caller order exactly; raw numeric fields still decode as splitCoder() subarray views.\n return splitCoder(\n name,\n ...lst.map((i) => {\n if (typeof i.lengths[name] !== 'number') throw new Error('wrong length: ' + name);\n return i.lengths[name];\n })\n );\n}\n\n/** Seed-expansion callback used by the hybrid combiners. */\nexport type ExpandSeed = (seed: TArg<Uint8Array>, len: number) => TRet<Uint8Array>;\ntype XOF = CHashXOF<any, { dkLen: number }>;\n\n// It is XOF for most cases, but can be more complex!\n/**\n * Adapts an XOF into an `ExpandSeed` callback.\n * The returned callback interprets its second argument as an output byte length passed as `dkLen`.\n * @param xof - Extendable-output hash function.\n * @returns Seed expander using `dkLen`.\n * @example\n * Adapt an XOF into a seed expander.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * const expandSeed = expandSeedXof(shake256);\n * const seed = expandSeed(new Uint8Array([1]), 4);\n * ```\n */\nexport function expandSeedXof(xof: TArg<XOF>): TRet<ExpandSeed> {\n // Forward the caller seed directly: XOFs are expected to treat inputs as read-only, and this\n // adapter only translates the requested byte length into the hash API's `dkLen` option.\n return ((seed: TArg<Uint8Array>, seedLen: number): TRet<Uint8Array> =>\n (xof as XOF)(seed, { dkLen: seedLen }) as TRet<Uint8Array>) as TRet<ExpandSeed>;\n}\n\n/** Combines public keys, ciphertexts, and shared secrets into one shared secret. */\nexport type Combiner = (\n publicKeys: TArg<Uint8Array[]>,\n cipherTexts: TArg<Uint8Array[]>,\n sharedSecrets: TArg<Uint8Array[]>\n) => TRet<Uint8Array>;\n\nfunction combineKeys(\n realSeedLen: number | undefined, // how much bytes expandSeed expects\n expandSeed_: TArg<ExpandSeed>,\n ...ck_: TArg<CryptoKeys[]>\n) {\n const expandSeed = expandSeed_ as ExpandSeed;\n const ck = ck_ as CryptoKeys[];\n const seedCoder = splitLengths(ck, 'seed');\n const pkCoder = splitLengths(ck, 'publicKey');\n // Allows to use identity functions for combiner/expandSeed\n if (realSeedLen === undefined) realSeedLen = seedCoder.bytesLen;\n anumber(realSeedLen);\n function expandDecapsulationKey(seed: TArg<Uint8Array>): TRet<{\n secretKey: Uint8Array[];\n publicKey: Uint8Array[];\n }> {\n abytes(seed, realSeedLen!);\n const expandedRaw = expandSeed(seed, seedCoder.bytesLen);\n // Identity/subarray expanders can hand back caller-owned seed storage. Detach those outputs so\n // later cleanup can wipe the expanded schedule without mutating the caller's root seed bytes.\n const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes(expandedRaw) : expandedRaw;\n const expanded: Uint8Array[] = [];\n const keySecret: Uint8Array[] = [];\n const secretKey: Uint8Array[] = [];\n const publicKey: Uint8Array[] = [];\n let ok = false;\n try {\n // seedCoder.decode() returns zero-copy slices into expandedSeed and can throw before child\n // keygen() runs, so keep the raw expanded buffer separate and copy each child seed before any\n // later cleanup wipes the shared backing bytes.\n for (const part of seedCoder.decode(expandedSeed)) expanded.push(copyBytes(part));\n for (let i = 0; i < ck.length; i++) {\n const keys = ck[i].keygen(expanded[i]);\n keySecret.push(keys.secretKey);\n secretKey.push(copyBytes(keys.secretKey));\n publicKey.push(keys.publicKey);\n }\n ok = true;\n return { secretKey, publicKey } as TRet<{\n secretKey: Uint8Array[];\n publicKey: Uint8Array[];\n }>;\n } finally {\n // Child keygen() can throw after deriving only a prefix of the composite key schedule. Keep\n // the exported copies on success, but wipe all temporary and partially built secret material\n // on either path so failures do not strand derived child seeds in memory.\n cleanBytes(expandedSeed, expanded, keySecret);\n if (!ok) cleanBytes(secretKey);\n }\n }\n return {\n info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },\n getPublicKey(secretKey: TArg<Uint8Array>) {\n // Composite secret keys are root seeds, so public-key derivation reruns key expansion from\n // that seed instead of decoding a packed child-secret-key structure.\n return this.keygen(secretKey).publicKey as TRet<Uint8Array>;\n },\n keygen(seed: TArg<Uint8Array> = randomBytes(realSeedLen)) {\n const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);\n try {\n const publicKey = pkCoder.encode(pk) as TRet<Uint8Array>;\n return { secretKey: seed as TRet<Uint8Array>, publicKey };\n } finally {\n cleanBytes(pk);\n // The exported secretKey is the caller/root seed itself; child secret keys are internal\n // expansion outputs that are cleaned whether encoding succeeds or throws.\n cleanBytes(secretKey);\n }\n },\n expandDecapsulationKey,\n realSeedLen,\n };\n}\n\n// This generic function that combines multiple KEMs into single one\n/**\n * Combines multiple KEMs into one composite KEM.\n * @param realSeedLen - Input seed length expected by `expandSeed`.\n * @param realMsgLen - Shared-secret length returned by `combiner`.\n * @param expandSeed - Seed expander used to derive per-KEM seeds.\n * @param combiner - Combines the per-KEM outputs into one shared secret.\n * @param kems - KEM implementations to combine.\n * @returns Composite KEM.\n * @example\n * Combine multiple KEMs into one composite KEM.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineKEMS, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const hybrid = combineKEMS(\n * 32,\n * 32,\n * expandSeedXof(shake256),\n * (_pk, _ct, sharedSecrets) => sharedSecrets[0],\n * ml_kem768,\n * ml_kem768\n * );\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineKEMS(\n realSeedLen: number | undefined, // how much bytes expandSeed expects\n realMsgLen: number | undefined, // how much bytes combiner returns\n expandSeed: TArg<ExpandSeed>,\n combiner: TArg<Combiner>,\n ...kems: TArg<KEM[]>\n): TRet<KEM> {\n const rawCombiner = combiner as Combiner;\n const rawKems = kems as KEM[];\n const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);\n const ctCoder = splitLengths(rawKems, 'cipherText');\n const pkCoder = splitLengths(rawKems, 'publicKey');\n const msgCoder = splitLengths(rawKems, 'msg');\n if (realMsgLen === undefined) realMsgLen = msgCoder.bytesLen;\n anumber(realMsgLen);\n const lengths = Object.freeze({\n ...keys.info.lengths,\n msg: realMsgLen,\n msgRand: msgCoder.bytesLen,\n cipherText: ctCoder.bytesLen,\n });\n return Object.freeze({\n lengths,\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n encapsulate(\n pk: TArg<Uint8Array>,\n randomness: TArg<Uint8Array> = randomBytes(msgCoder.bytesLen)\n ) {\n const pks = pkCoder.decode(pk);\n const rand = msgCoder.decode(randomness);\n const sharedSecret: Uint8Array[] = [];\n const cipherText: Uint8Array[] = [];\n try {\n for (let i = 0; i < rawKems.length; i++) {\n const enc = rawKems[i].encapsulate(pks[i], rand[i]);\n sharedSecret.push(enc.sharedSecret);\n cipherText.push(enc.cipherText);\n }\n return {\n // Detach the combiner result before cleanup: a caller-provided combiner may alias one of\n // the child sharedSecret buffers, and those child buffers are zeroized immediately below.\n sharedSecret: copyBytes(rawCombiner(pks, cipherText, sharedSecret)),\n cipherText: ctCoder.encode(cipherText) as TRet<Uint8Array>,\n };\n } finally {\n // Child encapsulation or combiner failures can happen after some components already\n // returned secret material; zeroize whatever was produced before propagating the error.\n cleanBytes(sharedSecret, cipherText);\n }\n },\n decapsulate(ct: TArg<Uint8Array>, seed: TArg<Uint8Array>) {\n const cts = ctCoder.decode(ct);\n const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);\n const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));\n try {\n // Detach the decapsulation result before cleanup: the combiner may hand back one of the\n // child shared-secret buffers, and those temporary buffers are zeroized below.\n return copyBytes(rawCombiner(publicKey, cts, sharedSecret));\n } finally {\n // Decapsulation only needs the expanded child secret keys and child shared secrets for this\n // call; keep the caller/root seed intact, but wipe all derived material even on errors.\n cleanBytes(secretKey, sharedSecret);\n }\n },\n });\n}\n// There is no specs for this, but can be useful\n// realSeedLen: how much bytes expandSeed expects.\n/**\n * Combines multiple signers into one composite signer.\n * @param realSeedLen - Input seed length expected by `expandSeed`.\n * @param expandSeed - Seed expander used to derive per-signer seeds.\n * @param signers - Signers to combine.\n * @returns Composite signer.\n * @example\n * Combine multiple signers into one composite signer.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineSigners, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js';\n * const hybrid = combineSigners(32, expandSeedXof(shake256), ml_dsa44, ml_dsa44);\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineSigners(\n realSeedLen: number | undefined,\n expandSeed: TArg<ExpandSeed>,\n ...signers: TArg<Signer[]>\n): TRet<Signer> {\n const rawSigners = signers as Signer[];\n const keys = combineKeys(realSeedLen, expandSeed, ...rawSigners);\n const sigCoder = splitLengths(rawSigners, 'signature');\n const pkCoder = splitLengths(rawSigners, 'publicKey');\n return {\n lengths: { ...keys.info.lengths, signature: sigCoder.bytesLen, signRand: 0 },\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n sign(message, seed, opts = {}) {\n validateSigOpts(opts);\n // This generic wrapper intentionally keeps the composite signer contract to message + root\n // seed only. Per-signer opts like context or extraEntropy cannot be preserved uniformly\n // across mixed backends, so callers that need them must use the underlying signer directly.\n if (opts.extraEntropy !== undefined)\n throw new Error(\n 'combineSigners does not support extraEntropy; use the underlying signer directly'\n );\n if (opts.context !== undefined)\n throw new Error(\n 'combineSigners does not support context; use the underlying signer directly'\n );\n const { secretKey } = keys.expandDecapsulationKey(seed);\n try {\n const sigs = rawSigners.map((i, j) => i.sign(message, secretKey[j]));\n return sigCoder.encode(sigs) as TRet<Uint8Array>;\n } finally {\n // Composite secret keys are root seeds; the per-signer child secret keys are temporary\n // expansion outputs and must not stay live after the combined signature is produced.\n cleanBytes(secretKey);\n }\n },\n /** Verify one combined signature.\n * Returns `false` when the aggregate signature/publicKey decode succeeds but any child verify\n * check fails. Throws on unsupported generic opts or malformed aggregate encodings.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error(\n 'combineSigners does not support context; use the underlying signer directly'\n );\n const pks = pkCoder.decode(publicKey);\n const sigs = sigCoder.decode(signature);\n for (let i = 0; i < rawSigners.length; i++) {\n if (!rawSigners[i].verify(sigs[i], message, pks[i])) return false;\n }\n return true;\n },\n };\n}\n\n/**\n * Builds a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * The combined shared-secret length follows `kdf.outputLen`; the built-in presets use 32-byte\n * SHA3-256 output, while custom `kdf` choices inherit their own digest size.\n * Its combiner hashes `ss0 || ss1 || ct1 || pk1 || label`, not the full\n * `(c1, c2, ek1, ek2)` example input shape from SP 800-227 equation (15).\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param kdf - Hash used for the final combiner.\n * @returns Hybrid KEM.\n * @example\n * Build a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * ```ts\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha3_256, shake256 } from '@noble/hashes/sha3.js';\n * import { QSF, ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const kem = QSF('example', ml_kem768, ecdhKem(p256, true), shake256, sha3_256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function QSF(\n label: string,\n pqc: TArg<KEM>,\n curveKEM: TArg<KEM>,\n xof: TArg<XOF>,\n kdf: CHash\n): TRet<KEM> {\n ahash(xof);\n ahash(kdf);\n return combineKEMS(\n 32,\n kdf.outputLen,\n expandSeedXof(xof),\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n kdf(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))),\n pqc,\n curveKEM\n );\n}\n\n/** QSF preset combining ML-KEM-768 with P-256. */\nexport const QSF_ml_kem768_p256: TRet<KEM> = /* @__PURE__ */ (() =>\n QSF(\n 'QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)',\n ml_kem768,\n ecdhKem(p256, true),\n shake256,\n sha3_256\n ))();\n/** QSF preset combining ML-KEM-1024 with P-384. */\nexport const QSF_ml_kem1024_p384: TRet<KEM> = /* @__PURE__ */ (() =>\n QSF(\n 'QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)',\n ml_kem1024,\n ecdhKem(p384, true),\n shake256,\n sha3_256\n ))();\n\n/**\n * Builds the \"KitchenSink\" hybrid KEM combiner.\n * The current builder always derives a fixed 32-byte output,\n * regardless of the hash's native output size.\n * Its HKDF extract step uses implicit zero salt with IKM\n * `hybrid_prk || ss0 || ss1 || ct0 || pk0 || ct1 || pk1 || label`.\n * Its HKDF expand step fixes `info` to `len || 'shared_secret' || ''`.\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param hash - Hash used for HKDF extraction and expansion.\n * @returns Hybrid KEM.\n * @example\n * Build the \"KitchenSink\" hybrid KEM combiner.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { createKitchenSink, ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const kem = createKitchenSink('example', ml_kem768, ecdhKem(x25519), shake256, sha256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function createKitchenSink(\n label: string,\n pqc: TArg<KEM>,\n curveKEM: TArg<KEM>,\n xof: TArg<XOF>,\n hash: CHash\n): TRet<KEM> {\n ahash(xof);\n ahash(hash);\n return combineKEMS(\n 32,\n 32,\n expandSeedXof(xof),\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) => {\n const preimage = concatBytes(ss[0], ss[1], ct[0], pk[0], ct[1], pk[1], asciiToBytes(label));\n const len = 32;\n const ikm = concatBytes(asciiToBytes('hybrid_prk'), preimage);\n const prk = extract(hash, ikm);\n const info = concatBytes(\n numberToBytesBE(len, 2),\n asciiToBytes('shared_secret'),\n asciiToBytes('')\n );\n const res = expand(hash, prk, info, len);\n cleanBytes(prk, info, ikm, preimage);\n return res;\n },\n pqc,\n curveKEM\n );\n}\n\n// Internal alias only: this stays exactly `ecdhKem(x25519)`\n// and inherits that wrapper's mutation/oracle behavior.\nconst x25519kem = /* @__PURE__ */ ecdhKem(x25519);\n/** KitchenSink preset combining ML-KEM-768 with X25519.\n * Caller randomness splits into 32 ML-KEM coins plus a 32-byte X25519 ephemeral-secret seed.\n */\nexport const KitchenSink_ml_kem768_x25519: TRet<KEM> = /* @__PURE__ */ (() =>\n createKitchenSink(\n 'KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)',\n ml_kem768,\n x25519kem,\n shake256,\n sha256\n ))();\n\n// Always X25519 and ML-KEM - 768, no point to export\n/** X25519 + ML-KEM-768 hybrid preset.\n * Uses the hard-coded domain-separation label `\\\\.//^\\\\` and hashes only `ct1 || pk1`\n * from the X25519 side in addition to the two component shared secrets.\n */\nexport const ml_kem768_x25519: TRet<KEM> = /* @__PURE__ */ (() =>\n combineKEMS(\n 32,\n 32,\n expandSeedXof(shake256),\n // Awesome label, so much escaping hell in a single line.\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes('\\\\.//^\\\\'))),\n ml_kem768,\n x25519kem\n ))();\n\n/**\n * Internal SEC 1-style KEM wrapper for NIST curves.\n * `nseed` is only the rejection-sampling byte budget for deriving one nonzero scalar:\n * current presets use `128` bytes for P-256 and `48` bytes for P-384.\n * `decapsulate()` returns the uncompressed shared point body `x || y` without the `0x04`\n * prefix, not the SEC 1 `x_P`-only primitive output, because current hybrid combiners hash\n * both coordinates.\n */\nfunction nistCurveKem(curve: ECDSA, scalarLen: number, elemLen: number, nseed: number): TRet<KEM> {\n const Fn = curve.Point.Fn;\n if (!Fn) throw new Error('no Point.Fn');\n // Scan scalar-sized windows until one decodes to a nonzero scalar in `[1, n-1]`; if every\n // window is zero or out of range, fail instead of silently reducing modulo `n`.\n function rejectionSampling(seed: TArg<Uint8Array>): TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }> {\n let sk: bigint;\n for (let start = 0, end = scalarLen; ; start = end, end += scalarLen) {\n if (end > seed.length) throw new Error('rejection sampling failed');\n sk = Fn.fromBytes(seed.subarray(start, end), true);\n if (Fn.isValidNot0(sk)) break;\n }\n const secretKey = Fn.toBytes(Fn.create(sk));\n const publicKey = curve.getPublicKey(secretKey, false);\n return { secretKey, publicKey } as TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }>;\n }\n\n return {\n lengths: {\n secretKey: scalarLen,\n publicKey: elemLen,\n seed: nseed,\n msg: nseed,\n cipherText: elemLen,\n },\n keygen(seed: TArg<Uint8Array> = randomBytes(nseed)) {\n abytes(seed, nseed, 'seed');\n return rejectionSampling(seed);\n },\n getPublicKey(secretKey: TArg<Uint8Array>) {\n return curve.getPublicKey(secretKey, false) as TRet<Uint8Array>;\n },\n encapsulate(publicKey: TArg<Uint8Array>, rand: TArg<Uint8Array> = randomBytes(nseed)) {\n abytes(rand, nseed, 'rand');\n let ek: Uint8Array | undefined = undefined;\n try {\n ek = rejectionSampling(rand).secretKey;\n const sharedSecret = this.decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek, false) as TRet<Uint8Array>;\n return { sharedSecret, cipherText };\n } finally {\n // Rejection-sampled NIST-curve ephemeral secret keys are temporary encapsulation state and\n // must be wiped even if peer-key validation or shared-secret derivation throws.\n if (ek) cleanBytes(ek);\n }\n },\n decapsulate(cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) {\n const full = curve.getSharedSecret(secretKey, cipherText);\n return full.subarray(1) as TRet<Uint8Array>;\n },\n };\n}\n\n/**\n * Internal ML-KEM + NIST-curve combiner.\n * `nseed` controls only the curve-side rejection-sampling budget; it is expanded from the\n * 32-byte root seed and is not itself part of the exported secret-key length.\n * The domain-separation `label` is used only in the final `sha3_256` combiner, not in\n * `shake256(seed, { dkLen: 64 + nseed })`,\n * and the combiner hashes `ss0 || ss1 || ct1 || pk1 || label`.\n */\nfunction concreteHybridKem(\n label: string,\n mlkem: TArg<KEM>,\n curve: ECDSA,\n nseed: number\n): TRet<KEM> {\n const { secretKey: scalarLen, publicKeyUncompressed: elemLen } = curve.lengths;\n if (!scalarLen || !elemLen) throw new Error('wrong curve');\n const curveKem = nistCurveKem(curve, scalarLen, elemLen, nseed);\n const mlkemSeedLen = 64;\n const totalSeedLen = mlkemSeedLen + nseed;\n\n return combineKEMS(\n 32,\n 32,\n (seed: TArg<Uint8Array>): TRet<Uint8Array> => {\n abytes(seed, 32);\n const expanded = shake256(seed, { dkLen: totalSeedLen });\n const mlkemSeed = expanded.subarray(0, mlkemSeedLen);\n const curveSeed = expanded.subarray(mlkemSeedLen, totalSeedLen);\n return concatBytes(mlkemSeed, curveSeed) as TRet<Uint8Array>;\n },\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))),\n mlkem,\n curveKem\n );\n}\n\n/** P-256 + ML-KEM-768 hybrid preset. */\nexport const ml_kem768_p256: TRet<KEM> = /* @__PURE__ */ (() =>\n concreteHybridKem('MLKEM768-P256', ml_kem768, p256, 128))();\n\n/** P-384 + ML-KEM-1024 hybrid preset. */\nexport const ml_kem1024_p384: TRet<KEM> = /* @__PURE__ */ (() =>\n concreteHybridKem('MLKEM1024-P384', ml_kem1024, p384, 48))();\n\n// Legacy aliases\n/** Legacy alias for `ml_kem768_x25519`. */\nexport const XWing: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_x25519)();\n/** Legacy alias for `ml_kem768_x25519`. */\nexport const MLKEM768X25519: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_x25519)();\n/** Legacy alias for `ml_kem768_p256`. */\nexport const MLKEM768P256: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_p256)();\n/** Legacy alias for `ml_kem1024_p384`. */\nexport const MLKEM1024P384: TRet<KEM> = /* @__PURE__ */ (() => ml_kem1024_p384)();\n/** Legacy alias for `QSF_ml_kem768_p256`. */\nexport const QSFMLKEM768P256: TRet<KEM> = /* @__PURE__ */ (() => QSF_ml_kem768_p256)();\n/** Legacy alias for `QSF_ml_kem1024_p384`. */\nexport const QSFMLKEM1024P384: TRet<KEM> = /* @__PURE__ */ (() => QSF_ml_kem1024_p384)();\n/** Legacy alias for `KitchenSink_ml_kem768_x25519`. */\nexport const KitchenSinkMLKEM768X25519: TRet<KEM> = /* @__PURE__ */ (() =>\n KitchenSink_ml_kem768_x25519)();\n","import { chacha20poly1305 } from '@noble/ciphers/chacha.js';\n\nimport { AeadVerificationError } from './errors';\n\nexport interface ChaCha20Poly1305EncryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly plaintext: Uint8Array;\n}\n\nexport interface ChaCha20Poly1305DecryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly ciphertext: Uint8Array;\n}\n\nexport function chacha20Poly1305Encrypt(opts: ChaCha20Poly1305EncryptOpts): Uint8Array {\n return chacha20poly1305(opts.key, opts.nonce, opts.aad).encrypt(opts.plaintext);\n}\n\nexport function chacha20Poly1305Decrypt(opts: ChaCha20Poly1305DecryptOpts): Uint8Array {\n try {\n return chacha20poly1305(opts.key, opts.nonce, opts.aad).decrypt(opts.ciphertext);\n } catch (cause) {\n throw new AeadVerificationError('chacha20-poly1305 decrypt failed', { cause });\n }\n}\n","import { hkdf } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nexport interface HkdfSha256Opts {\n readonly ikm: Uint8Array;\n readonly salt: Uint8Array;\n readonly info: Uint8Array;\n readonly length: number;\n}\n\nexport function hkdfSha256(opts: HkdfSha256Opts): Uint8Array {\n return hkdf(sha256, opts.ikm, opts.salt, opts.info, opts.length);\n}\n","import { XWing } from '@noble/post-quantum/hybrid.js';\n\n// X-Wing (ML-KEM-768 + X25519) hybrid KEM per draft-connolly-cfrg-xwing-kem-06.\n// `XWing` is @noble/post-quantum's alias for `ml_kem768_x25519`. We expose it\n// through opts-object wrappers that pin the wire lengths and map noble's field\n// names onto the project's vocabulary.\n//\n// Unlike the bare X25519 KEM, there is no contributory-behaviour rejection to\n// translate: X-Wing combines the ML-KEM and X25519 shared secrets through a\n// SHA3-256 combiner that also binds the X25519 ephemeral and recipient public\n// keys, and ML-KEM's implicit rejection already yields a constant-work\n// pseudorandom secret on a malformed ciphertext. Decapsulation therefore never\n// throws on attacker-supplied wire data — a wrong shared secret is the correct,\n// indistinguishable failure mode, and callers MUST treat it as a non-match\n// rather than expecting an exception.\n\nexport const MLKEM768X25519_PUBLIC_KEY_LENGTH = 1216 as const;\nexport const MLKEM768X25519_ENC_LENGTH = 1120 as const;\nexport const MLKEM768X25519_SHARED_SECRET_LENGTH = 32 as const;\nexport const MLKEM768X25519_SEED_LENGTH = 32 as const;\nexport const MLKEM768X25519_ESEED_LENGTH = 64 as const;\n\nexport interface Mlkem768X25519KeyPair {\n // The 32-byte root seed IS the secret key in draft-06: the ML-KEM coins and\n // the X25519 scalar are re-expanded from it via SHAKE-256 at decapsulation.\n readonly secretSeed: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nexport interface Mlkem768X25519EncapsulateOpts {\n readonly publicKey: Uint8Array;\n // Optional 64-byte encapsulation randomness (msgRand). When supplied the\n // ciphertext and shared secret are fully deterministic; a 32-byte value is\n // rejected by noble, so we pin the length here too.\n readonly eseed?: Uint8Array;\n}\n\nexport interface Mlkem768X25519Encapsulation {\n readonly enc: Uint8Array;\n readonly ss: Uint8Array;\n}\n\nexport interface Mlkem768X25519DecapsulateOpts {\n readonly secretSeed: Uint8Array;\n readonly enc: Uint8Array;\n}\n\nexport function mlkem768x25519Keygen(seed: Uint8Array): Mlkem768X25519KeyPair {\n if (seed.length !== MLKEM768X25519_SEED_LENGTH) {\n throw new Error(\n `mlkem768x25519 seed must be ${MLKEM768X25519_SEED_LENGTH} bytes, got ${seed.length}`,\n );\n }\n const { secretKey, publicKey } = XWing.keygen(seed);\n return { secretSeed: secretKey, publicKey };\n}\n\nexport function mlkem768x25519Encapsulate(\n opts: Mlkem768X25519EncapsulateOpts,\n): Mlkem768X25519Encapsulation {\n if (opts.publicKey.length !== MLKEM768X25519_PUBLIC_KEY_LENGTH) {\n throw new Error(\n `mlkem768x25519 public key must be ${MLKEM768X25519_PUBLIC_KEY_LENGTH} bytes, got ${opts.publicKey.length}`,\n );\n }\n if (opts.eseed !== undefined && opts.eseed.length !== MLKEM768X25519_ESEED_LENGTH) {\n throw new Error(\n `mlkem768x25519 eseed must be ${MLKEM768X25519_ESEED_LENGTH} bytes, got ${opts.eseed.length}`,\n );\n }\n const { cipherText, sharedSecret } = XWing.encapsulate(opts.publicKey, opts.eseed);\n return { enc: cipherText, ss: sharedSecret };\n}\n\nexport function mlkem768x25519Decapsulate(opts: Mlkem768X25519DecapsulateOpts): Uint8Array {\n // Pre-check both lengths before calling noble: decapsulation must perform a\n // constant amount of work for any caller-supplied ciphertext (implicit\n // rejection), which requires the inputs to be the exact expected sizes.\n if (opts.secretSeed.length !== MLKEM768X25519_SEED_LENGTH) {\n throw new Error(\n `mlkem768x25519 secret seed must be ${MLKEM768X25519_SEED_LENGTH} bytes, got ${opts.secretSeed.length}`,\n );\n }\n if (opts.enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new Error(\n `mlkem768x25519 enc must be ${MLKEM768X25519_ENC_LENGTH} bytes, got ${opts.enc.length}`,\n );\n }\n // noble's signature is decapsulate(cipherText, secretKey) — ciphertext first.\n return XWing.decapsulate(opts.enc, opts.secretSeed);\n}\n","import { x25519 } from '@noble/curves/ed25519.js';\n\n// RFC 7748 §6.1 contributory-behaviour rejection: a small-order (low-order)\n// Montgomery `u` coordinate makes the X25519 shared secret all-zero, which\n// @noble/curves refuses with `Error: invalid private or public key received`.\n// We rethrow that as a *typed* error so callers can distinguish a structurally\n// valid-but-malicious peer public key (a property of attacker-supplied wire\n// data — trial-decrypt MUST treat the slot as a non-match, not crash) from\n// genuine caller misuse such as a wrong-length key (which @noble raises as a\n// RangeError and which we deliberately let propagate untouched).\nexport class X25519LowOrderPointError extends Error {\n readonly code = 'X25519_LOW_ORDER_POINT' as const;\n constructor(options?: { cause?: unknown }) {\n super('x25519 ECDH rejected: peer public key is a small-order point', options);\n this.name = 'X25519LowOrderPointError';\n }\n}\n\n// @noble/curves v2 signals a small-order/all-zero shared secret with this exact\n// message. Matching on it (rather than the broad Error class) keeps unrelated\n// failures — e.g. a future internal assertion — surfacing as themselves.\nconst NOBLE_LOW_ORDER_MESSAGE = 'invalid private or public key received';\n\nexport interface X25519KeyPair {\n readonly secretKey: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nexport interface X25519PublicKeyOpts {\n readonly secretKey: Uint8Array;\n}\n\nexport interface X25519EcdhOpts {\n readonly secretKey: Uint8Array;\n readonly theirPublicKey: Uint8Array;\n}\n\nexport function x25519Keygen(): X25519KeyPair {\n return x25519.keygen();\n}\n\nexport function x25519PublicKey(opts: X25519PublicKeyOpts): Uint8Array {\n return x25519.getPublicKey(opts.secretKey);\n}\n\nexport function x25519Ecdh(opts: X25519EcdhOpts): Uint8Array {\n try {\n return x25519.getSharedSecret(opts.secretKey, opts.theirPublicKey);\n } catch (e) {\n // Translate ONLY the contributory-check rejection into our typed error.\n // A wrong-length key throws a RangeError from @noble's length assertion;\n // that is caller misuse, not malicious wire data, so it must propagate.\n if (e instanceof Error && e.message === NOBLE_LOW_ORDER_MESSAGE) {\n throw new X25519LowOrderPointError({ cause: e });\n }\n throw e;\n }\n}\n","// Sealed-PoE error taxonomy (wire-shape + partitioning-oracle pre-checks).\n\nexport type EciesSealedPoeErrorCode =\n | 'ENC_SLOTS_EMPTY'\n | 'ENC_SLOTS_REQUIRED'\n | 'ENC_SLOTS_MAC_REQUIRED'\n | 'ENC_SLOTS_MAC_INVALID_LENGTH'\n | 'KEM_EPK_LENGTH_MISMATCH'\n | 'KEM_CT_LENGTH_MISMATCH'\n | 'INVALID_CEK_LENGTH'\n | 'NONCE_LENGTH_MISMATCH'\n | 'INVALID_EPHEMERAL_SECRET_LENGTH'\n | 'EPHEMERAL_SECRETS_COUNT_MISMATCH'\n | 'UNSUPPORTED_ENC_VERSION'\n | 'UNSUPPORTED_AEAD_ALG'\n | 'UNSUPPORTED_KEM_ALG'\n | 'INVALID_ENVELOPE_SHAPE'\n | 'INVALID_RECIPIENT_KEY'\n | 'WRAP_LENGTH_MISMATCH';\n\nexport class EciesSealedPoeError extends Error {\n readonly code: EciesSealedPoeErrorCode;\n\n constructor(code: EciesSealedPoeErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'EciesSealedPoeError';\n this.code = code;\n }\n}\n","// Single source of truth for two seams that wrap, unwrap, and the wire encoder\n// MUST agree on byte-for-byte:\n//\n// 1. How the 1120-byte X-Wing `enc` is split into the ≤ 64-byte byte-string\n// chunks the Cardano ledger requires (`kem_ct`), and the inverse join.\n// 2. The canonical-CBOR serialization of the slot array that feeds slots_mac.\n//\n// Keeping both here means the producer (wrap) and the verifier (unwrap), as well\n// as the downstream record encoder, cannot diverge on the bytes the MAC commits\n// to — the single highest correctness risk for the hybrid branch, since a\n// divergence would leave the ML-KEM ciphertext unauthenticated.\n\nimport { encodeCanonicalCbor, type CanonicalCborValue } from '../cbor/canonical';\n\nimport type { Mlkem768X25519Slot, X25519Slot } from './wrap';\n\n// The envelope-level KEM discriminator.\nexport type SealedKem = 'x25519' | 'mlkem768x25519';\n\n// Cardano ledger CDDL caps every `transaction_metadatum` byte string at 64\n// bytes, so any value larger than 64 bytes is carried as an array of ≤ 64-byte\n// chunks (the `bytes-chunk-array` wire form). This is the identical split rule\n// the record encoder applies to chunked COSE bytes.\nconst CHUNK_MAX_BYTES = 64;\n\n// Split a logical byte string into ≤ 64-byte chunks. Used for the X-Wing\n// `enc` → `kem_ct` wire form. Subarrays are views over the input, never copies.\nexport function chunkKemCt(value: Uint8Array): Uint8Array[] {\n if (value.length === 0) {\n throw new Error('chunkKemCt: refusing to chunk an empty byte string');\n }\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < value.length; i += CHUNK_MAX_BYTES) {\n chunks.push(value.subarray(i, Math.min(i + CHUNK_MAX_BYTES, value.length)));\n }\n return chunks;\n}\n\n// Inverse of chunkKemCt: concatenate the chunked `kem_ct` back into the flat\n// X-Wing `enc`. Performs NO length validation — the caller (unwrap) gates the\n// reassembled length against MLKEM768X25519_ENC_LENGTH before any decapsulation.\nexport function joinKemCt(chunks: ReadonlyArray<Uint8Array>): Uint8Array {\n let total = 0;\n for (const c of chunks) total += c.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const c of chunks) {\n out.set(c, offset);\n offset += c.length;\n }\n return out;\n}\n\n// KEM-driven slot serialization for the slots_mac input.\n//\n// • x25519: each slot → { epk: bstr, wrap: bstr }\n// • mlkem768x25519: each slot → { kem_ct: [ bstr, ... ], wrap: bstr }\n//\n// The hybrid form uses the SAME chunked-array shape as the wire encoder, so the\n// MAC commits to the ciphertext exactly as it appears on-chain. Returns the\n// canonical-CBOR bytes ready for HMAC.\nexport function slotsToMacCbor(\n slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n kem: SealedKem,\n): Uint8Array {\n let value: CanonicalCborValue;\n if (kem === 'x25519') {\n value = (slots as ReadonlyArray<X25519Slot>).map((s) => ({ epk: s.epk, wrap: s.wrap }));\n } else {\n value = (slots as ReadonlyArray<Mlkem768X25519Slot>).map((s) => ({\n // Canonicalize the chunk boundaries before the MAC commits to them:\n // reassemble the logical ciphertext and re-split into canonical ≤ 64-byte\n // chunks. The on-wire `kem_ct` array is a transport detail (the Cardano\n // ledger's 64-byte metadatum cap), and a hostile or non-canonical chunking\n // ([1, 63, …] instead of [64, …]) reassembles to the SAME bytes — so the\n // MAC must be invariant to it. Committing to the verbatim wire chunks would\n // let an attacker re-chunk an honest envelope and break the slots_mac match\n // for an honest recipient. Honest (already-64B-chunked) records are\n // unchanged; a real byte flip still changes the reassembled bytes and is\n // still rejected.\n kem_ct: chunkKemCt(joinKemCt(s.kem_ct)),\n wrap: s.wrap,\n }));\n }\n return encodeCanonicalCbor(value);\n}\n","// Multi-recipient sealed-PoE wrap (age-style ECIES + AEAD-bound slots).\n// Wire-field names are fixed by the standard: scheme, aead, kem, nonce, slots, slots_mac.\n//\n// Two KEM branches share one envelope shape, discriminated on the envelope-level\n// `kem` field:\n//\n// • kem: 'x25519' — classical age-style ECIES. Per-slot epk(32) + wrap(48).\n// • kem: 'mlkem768x25519' — X-Wing hybrid (ML-KEM-768 + X25519). Per-slot the\n// 1120-byte X-Wing enc carried as a chunked byte-string\n// array (`kem_ct`) + wrap(48). No per-slot epk.\n//\n// The slot type is a discriminated union so every consumer is forced — at compile\n// time — to branch on the KEM before touching kem-specific fields.\n\nimport { randomBytes } from '@noble/ciphers/utils.js';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { chacha20Poly1305Encrypt } from '../aead/chacha20-poly1305';\nimport { xchacha20Poly1305Encrypt } from '../aead/xchacha20-poly1305';\nimport { hkdfSha256 } from '../kdf/hkdf';\nimport {\n mlkem768x25519Encapsulate,\n MLKEM768X25519_ENC_LENGTH,\n MLKEM768X25519_ESEED_LENGTH,\n MLKEM768X25519_PUBLIC_KEY_LENGTH,\n} from '../kem/mlkem768x25519';\nimport { x25519Ecdh, x25519PublicKey } from '../kem/x25519';\n\nimport { EciesSealedPoeError } from './errors';\nimport { chunkKemCt, slotsToMacCbor, type SealedKem } from './slots-codec';\n\n// HKDF info strings — fixed protocol labels for KEK derivation and the slot MAC.\n// Byte-length invariants enforce that the SCREAMING_SNAKE constants stay in sync\n// with the on-wire ASCII literals every conformant verifier hashes against.\nexport const CARDANO_POE_HKDF_INFO_KEK: Uint8Array = new TextEncoder().encode('cardano-poe-kek-v1');\n// Hybrid (X-Wing) per-slot KEK label. Distinct from the classical label so a\n// KEK derived under one KEM can never collide with the other. Reused verbatim as\n// the per-slot wrap AEAD AAD, exactly as the classical path reuses its own label.\nexport const CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-kek-mlkem768x25519-v1',\n);\nexport const CARDANO_POE_HKDF_INFO_SLOTS_MAC: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-slots-mac-v1',\n);\n\nconst ZERO_NONCE_12: Uint8Array = new Uint8Array(12);\nconst EMPTY_SALT: Uint8Array = new Uint8Array(0);\nconst X25519_PUBLIC_KEY_LENGTH = 32 as const;\nconst X25519_SECRET_KEY_LENGTH = 32 as const;\nconst CEK_LENGTH = 32 as const;\nconst NONCE_LENGTH = 24 as const;\nconst WRAP_LENGTH = 48 as const;\nconst SLOTS_MAC_LENGTH = 32 as const;\n\nif (CARDANO_POE_HKDF_INFO_KEK.length !== 18) {\n throw new Error('CARDANO_POE_HKDF_INFO_KEK byte-length invariant violated (expected 18)');\n}\nif (CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519.length !== 33) {\n throw new Error(\n 'CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519 byte-length invariant violated (expected 33)',\n );\n}\nif (CARDANO_POE_HKDF_INFO_SLOTS_MAC.length !== 24) {\n throw new Error('CARDANO_POE_HKDF_INFO_SLOTS_MAC byte-length invariant violated (expected 24)');\n}\nif (ZERO_NONCE_12.length !== 12) {\n throw new Error('ZERO_NONCE_12 byte-length invariant violated (expected 12)');\n}\n\n// Classical per-slot wire shape: { epk: bstr(32), wrap: bstr(48) }.\nexport interface X25519Slot {\n readonly epk: Uint8Array;\n readonly wrap: Uint8Array;\n}\n\n// Hybrid per-slot wire shape: { kem_ct: [ bstr .size (1..64) ], wrap: bstr(48) }.\n// `kem_ct` is the 1120-byte X-Wing enc carried as a chunked byte-string array\n// (the Cardano ledger caps any single metadatum bstr at 64 bytes). There is NO\n// per-slot epk and NO per-slot kem field — the KEM identifier is hoisted to\n// envelope scope (every slot shares it).\nexport interface Mlkem768X25519Slot {\n readonly kem_ct: ReadonlyArray<Uint8Array>;\n readonly wrap: Uint8Array;\n}\n\n// Back-compat alias retired: callers branch on the envelope `kem` and use the\n// concrete slot type. The discriminated `SealedEnvelope` below is the only\n// shape consumers should depend on.\n\n// Sealed envelope wire shape (discriminated on `kem`).\nexport type SealedEnvelope =\n | {\n readonly scheme: 1;\n readonly aead: 'xchacha20-poly1305';\n readonly kem: 'x25519';\n readonly nonce: Uint8Array;\n readonly slots: ReadonlyArray<X25519Slot>;\n readonly slots_mac: Uint8Array;\n }\n | {\n readonly scheme: 1;\n readonly aead: 'xchacha20-poly1305';\n readonly kem: 'mlkem768x25519';\n readonly nonce: Uint8Array;\n readonly slots: ReadonlyArray<Mlkem768X25519Slot>;\n readonly slots_mac: Uint8Array;\n };\n\nexport interface SealedPoeOutput {\n readonly envelope: SealedEnvelope;\n readonly ciphertext: Uint8Array;\n}\n\nexport interface WrapArgs {\n readonly plaintext: Uint8Array;\n readonly recipientPublicKeys: ReadonlyArray<Uint8Array>;\n // KEM branch selector. Defaults to 'x25519' for the classical path. The\n // recipient public-key length is validated against the chosen KEM.\n readonly kem?: SealedKem;\n readonly cek?: Uint8Array;\n readonly nonce?: Uint8Array;\n // Deterministic X25519 ephemeral scalars — x25519 branch only.\n readonly ephemeralSecrets?: ReadonlyArray<Uint8Array>;\n // Deterministic X-Wing encapsulation randomness (64 bytes each) — hybrid\n // branch only. One per recipient, parallel to recipientPublicKeys.\n readonly eseeds?: ReadonlyArray<Uint8Array>;\n readonly skipShuffle?: boolean;\n}\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n}\n\n// Anonymity invariant: wire ordering MUST NOT encode \"primary\n// recipient first\". A CSPRNG-keyed Fisher-Yates shuffle uniformly permutes the\n// slot array so trial-decrypt order leaks no recipient identity. The\n// slot-set HMAC is computed AFTER this shuffle, binding the on-wire order.\n//\n// Draw an unbiased index in [0, m) from a CSPRNG uint32 via rejection sampling.\n// A plain `u32 % m` skews toward the low residues whenever `m` does not divide\n// 2^32 evenly: the values [0, 2^32 mod m) each occur one extra time. This\n// function exists purely to produce a UNIFORM permutation, so the bias — though\n// cryptographically negligible — is exactly the property we cannot tolerate.\n// We reject any draw landing in the final partial block [limit, 2^32) and\n// redraw, leaving only the residues that map uniformly onto [0, m).\n// Exported so the rejection-bound arithmetic can be asserted directly in tests\n// without relying on a flaky statistical-distribution check.\nexport function uniformIndexBelow(m: number): number {\n // 2^32 mod m, computed without overflowing the 32-bit space.\n const limit = 0x1_0000_0000 - (0x1_0000_0000 % m);\n const buf = new Uint32Array(1);\n let x: number;\n do {\n crypto.getRandomValues(buf);\n x = buf[0] as number;\n } while (x >= limit);\n return x % m;\n}\n\nfunction csprngShuffle<T>(arr: T[]): void {\n for (let i = arr.length - 1; i > 0; i--) {\n const j = uniformIndexBelow(i + 1);\n const tmp = arr[i] as T;\n arr[i] = arr[j] as T;\n arr[j] = tmp;\n }\n}\n\n// Wrap the CEK for one classical recipient: age-style ECIES stanza.\nfunction wrapSlotX25519(args: {\n pubR: Uint8Array;\n privEph: Uint8Array | undefined;\n cek: Uint8Array;\n slotIdx: number;\n}): X25519Slot {\n const privEph = args.privEph ?? randomBytes(X25519_SECRET_KEY_LENGTH);\n if (privEph.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_EPHEMERAL_SECRET_LENGTH',\n `ephemeralSecrets[${args.slotIdx}] MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${privEph.length}`,\n );\n }\n const epk = x25519PublicKey({ secretKey: privEph });\n const shared = x25519Ecdh({ secretKey: privEph, theirPublicKey: args.pubR });\n // age v1 stanza salt is `epk || pub_R`.\n const kek = hkdfSha256({\n ikm: shared,\n salt: concat(epk, args.pubR),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n // Per-slot wrap AAD MUST be the 18-byte ASCII literal of the KEK info\n // string (never empty AAD).\n const wrap = chacha20Poly1305Encrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK,\n plaintext: args.cek,\n });\n if (wrap.length !== WRAP_LENGTH) {\n throw new Error(`internal: wrap.length=${wrap.length}, expected ${WRAP_LENGTH}`);\n }\n return { epk, wrap };\n}\n\n// Wrap the CEK for one hybrid recipient: X-Wing encapsulation → HKDF → AEAD.\n// The KEK info label doubles as the wrap AEAD AAD, mirroring the classical path.\nfunction wrapSlotMlkem768X25519(args: {\n pubR: Uint8Array;\n eseed: Uint8Array | undefined;\n cek: Uint8Array;\n}): Mlkem768X25519Slot {\n const { enc, ss } = mlkem768x25519Encapsulate({\n publicKey: args.pubR,\n ...(args.eseed !== undefined ? { eseed: args.eseed } : {}),\n });\n if (enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new Error(`internal: enc.length=${enc.length}, expected ${MLKEM768X25519_ENC_LENGTH}`);\n }\n const kek = hkdfSha256({\n ikm: ss,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n length: 32,\n });\n const wrap = chacha20Poly1305Encrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n plaintext: args.cek,\n });\n if (wrap.length !== WRAP_LENGTH) {\n throw new Error(`internal: wrap.length=${wrap.length}, expected ${WRAP_LENGTH}`);\n }\n return { kem_ct: chunkKemCt(enc), wrap };\n}\n\nexport function eciesSealedPoeWrap(args: WrapArgs): SealedPoeOutput {\n const { plaintext, recipientPublicKeys } = args;\n const kem: SealedKem = args.kem ?? 'x25519';\n const n = recipientPublicKeys.length;\n\n // There is no fixed upper bound on slot count; the producer SDK polices the\n // per-record byte budget. Only the lower bound is enforced here.\n if (n < 1) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_EMPTY',\n `recipientPublicKeys.length=${n} must be >= 1`,\n );\n }\n\n const expectedPubLen =\n kem === 'x25519' ? X25519_PUBLIC_KEY_LENGTH : MLKEM768X25519_PUBLIC_KEY_LENGTH;\n for (let i = 0; i < n; i++) {\n const pub = recipientPublicKeys[i];\n if (pub === undefined || pub.length !== expectedPubLen) {\n throw new EciesSealedPoeError(\n 'KEM_EPK_LENGTH_MISMATCH',\n `recipientPublicKeys[${i}] MUST be exactly ${expectedPubLen} bytes for kem='${kem}'`,\n );\n }\n }\n\n if (kem === 'x25519') {\n if (args.eseeds !== undefined) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n \"eseeds is an X-Wing (mlkem768x25519) override and MUST NOT be supplied for kem='x25519'\",\n );\n }\n if (args.ephemeralSecrets !== undefined && args.ephemeralSecrets.length !== n) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n `ephemeralSecrets.length=${args.ephemeralSecrets.length} must match recipientPublicKeys.length=${n}`,\n );\n }\n } else {\n if (args.ephemeralSecrets !== undefined) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n \"ephemeralSecrets is an X25519 override and MUST NOT be supplied for kem='mlkem768x25519'\",\n );\n }\n if (args.eseeds !== undefined) {\n if (args.eseeds.length !== n) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n `eseeds.length=${args.eseeds.length} must match recipientPublicKeys.length=${n}`,\n );\n }\n for (let i = 0; i < n; i++) {\n const eseed = args.eseeds[i]!;\n if (eseed.length !== MLKEM768X25519_ESEED_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_EPHEMERAL_SECRET_LENGTH',\n `eseeds[${i}] MUST be exactly ${MLKEM768X25519_ESEED_LENGTH} bytes, got ${eseed.length}`,\n );\n }\n }\n }\n }\n\n const cek = args.cek ?? randomBytes(CEK_LENGTH);\n const nonce = args.nonce ?? randomBytes(NONCE_LENGTH);\n if (cek.length !== CEK_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_CEK_LENGTH',\n `cek MUST be exactly ${CEK_LENGTH} bytes, got ${cek.length}`,\n );\n }\n if (nonce.length !== NONCE_LENGTH) {\n throw new EciesSealedPoeError(\n 'NONCE_LENGTH_MISMATCH',\n `nonce MUST be exactly ${NONCE_LENGTH} bytes, got ${nonce.length}`,\n );\n }\n\n let envelope: SealedEnvelope;\n if (kem === 'x25519') {\n const slots: X25519Slot[] = [];\n for (let i = 0; i < n; i++) {\n slots.push(\n wrapSlotX25519({\n pubR: recipientPublicKeys[i]!,\n privEph: args.ephemeralSecrets ? (args.ephemeralSecrets[i] as Uint8Array) : undefined,\n cek,\n slotIdx: i,\n }),\n );\n }\n // Anonymity invariant (see csprngShuffle comment).\n if (args.skipShuffle !== true) {\n csprngShuffle(slots);\n }\n const slotsMac = computeSlotsMac(cek, slots, 'x25519');\n envelope = {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'x25519',\n nonce,\n slots,\n slots_mac: slotsMac,\n };\n } else {\n const slots: Mlkem768X25519Slot[] = [];\n for (let i = 0; i < n; i++) {\n slots.push(\n wrapSlotMlkem768X25519({\n pubR: recipientPublicKeys[i]!,\n eseed: args.eseeds ? (args.eseeds[i] as Uint8Array) : undefined,\n cek,\n }),\n );\n }\n if (args.skipShuffle !== true) {\n csprngShuffle(slots);\n }\n const slotsMac = computeSlotsMac(cek, slots, 'mlkem768x25519');\n envelope = {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'mlkem768x25519',\n nonce,\n slots,\n slots_mac: slotsMac,\n };\n }\n\n // Content AEAD AAD is `nonce || slots_mac` (24 + 32 = 56 B).\n const adContent = concat(nonce, envelope.slots_mac);\n const ciphertext = xchacha20Poly1305Encrypt({\n key: cek,\n nonce,\n aad: adContent,\n plaintext,\n });\n\n return { envelope, ciphertext };\n}\n\n// Slot-set MAC binds canonical-CBOR(slots) to the CEK.\n// The slot→CBOR serialization is KEM-driven (`slotsToMacCbor`) so the hybrid\n// kem_ct is authenticated by slots_mac exactly as the classical epk is.\nfunction computeSlotsMac(\n cek: Uint8Array,\n slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n kem: SealedKem,\n): Uint8Array {\n const hmacKey = hkdfSha256({\n ikm: cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsCbor = slotsToMacCbor(slots, kem);\n const slotsMac = hmac(sha256, hmacKey, slotsCbor);\n if (slotsMac.length !== SLOTS_MAC_LENGTH) {\n throw new Error(`internal: slots_mac.length=${slotsMac.length}, expected ${SLOTS_MAC_LENGTH}`);\n }\n return slotsMac;\n}\n","// Multi-recipient sealed-PoE unwrap (age-style trial-decrypt\n// + constant-time slots_mac binding + partitioning-oracle length pre-checks).\n//\n// Two forms (mutually exclusive — exactly one MUST be supplied):\n//\n// • Single-priv form: `recipientSecretKey: Uint8Array` — the standalone-verifier\n// path. Runs the trial-decrypt loop over `envelope.slots` once.\n//\n// • Multi-priv form: `recipientSecretKeys: ReadonlyArray<Uint8Array>` — for the\n// trial-decrypt scan of a rotated identity holding `[currentPriv, ...archivedPrivs]`.\n// Caller supplies the order; the iterator runs outer-loop = privkey ×\n// inner-loop = slot, short-circuiting on the first cross-priv match that\n// passes slots_mac verification. The recommended caller order\n// is `[currentPriv, ...previousPrivsReversed]` (newest archive first).\n//\n// Constant-time-N (default `true`) applies PER PRIV (the inner loop): all slots\n// are entered regardless of match position. The outer loop short-circuits on\n// first cross-priv match — the cross-priv channel is intrinsic to trial-decrypt\n//\n// Both KEM branches share this control flow. The per-slot recovery body differs:\n// • x25519: X25519 ECDH → HKDF → AEAD-unwrap; may throw on a low-order\n// epk (RFC 7748 §6.1 contributory-check rejection), handled\n// as a non-match.\n// • mlkem768x25519: X-Wing decapsulate → HKDF → AEAD-unwrap; NEVER throws on\n// attacker wire data (ML-KEM implicit rejection yields a\n// pseudorandom shared secret), so no try/catch around it.\n\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { chacha20Poly1305Decrypt } from '../aead/chacha20-poly1305';\nimport { AeadVerificationError } from '../aead/errors';\nimport { xchacha20Poly1305Decrypt } from '../aead/xchacha20-poly1305';\nimport { hkdfSha256 } from '../kdf/hkdf';\nimport { mlkem768x25519Decapsulate, MLKEM768X25519_ENC_LENGTH } from '../kem/mlkem768x25519';\nimport { x25519Ecdh, X25519LowOrderPointError, x25519PublicKey } from '../kem/x25519';\nimport { compareCt } from '../util/compare-ct';\n\nimport { EciesSealedPoeError } from './errors';\nimport { joinKemCt, slotsToMacCbor } from './slots-codec';\nimport {\n CARDANO_POE_HKDF_INFO_KEK,\n CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n type Mlkem768X25519Slot,\n type SealedEnvelope,\n type X25519Slot,\n} from './wrap';\n\nexport type UnwrapFailureReason = 'WRONG_RECIPIENT_KEY' | 'TAMPERED_HEADER' | 'TAMPERED_CIPHERTEXT';\n\nexport type UnwrapResult =\n | { readonly matched: true; readonly plaintext: Uint8Array }\n | { readonly matched: false; readonly reason: UnwrapFailureReason };\n\n// Unified recipient key bundle. Callers hold BOTH the X25519\n// private-key chain (current + archived, for classical and rotation history)\n// AND the X-Wing secret seed(s) (for the hybrid KEM), without knowing which a\n// given record was sealed under. They pass the whole bundle; the unwrap /\n// trial-decrypt dispatch selects the correct secret list from `envelope.kem`:\n//\n// • kem === 'x25519' → bundle.x25519PrivateKeys\n// • kem === 'mlkem768x25519' → bundle.mlkem768x25519SecretSeeds\n//\n// Both lists are ordered newest-first (caller's responsibility — the outer\n// trial-decrypt loop scans them in order). A list MAY be empty when the\n// recipient holds no key for that KEM (e.g. archived-only X25519 identities\n// predate the hybrid KEM, so their hybrid seed list is empty); a bundle whose\n// selected list is empty unwraps to a clean WRONG_RECIPIENT_KEY / no_aead_pass\n// without touching any KEM primitive.\nexport interface RecipientKeyBundle {\n readonly x25519PrivateKeys: ReadonlyArray<Uint8Array>;\n readonly mlkem768x25519SecretSeeds: ReadonlyArray<Uint8Array>;\n}\n\n// Select the secret-key list a bundle contributes for the given envelope KEM.\n// The single dispatch seam — wrap and trial-decrypt both route through here so\n// the per-KEM selection lives in exactly one place.\nfunction selectBundleSecrets(\n envelope: SealedEnvelope,\n bundle: RecipientKeyBundle,\n): ReadonlyArray<Uint8Array> {\n return envelope.kem === 'x25519' ? bundle.x25519PrivateKeys : bundle.mlkem768x25519SecretSeeds;\n}\n\ninterface UnwrapArgsCommon {\n readonly envelope: SealedEnvelope;\n readonly ciphertext: Uint8Array;\n readonly constantTimeN?: boolean;\n // Test-only instrumentation for constant-time-N verification.\n // The unwrap fn bumps `count` once per inner-loop iteration entered. In the\n // multi-priv path, `count` is reset at the start of each outer iteration and\n // — when `perPrivCounts` is provided — the final per-priv inner count is\n // appended after that priv's inner loop completes. Production callers never\n // pass this.\n readonly _slotsAttemptedOut?: { count: number; perPrivCounts?: number[] };\n // Test-only multi-priv outer-loop iteration counter. Bumped to `k + 1` at\n // the start of each outer-loop iteration. Production callers never pass this.\n readonly _privsAttemptedOut?: { count: number };\n}\n\nexport interface UnwrapArgsSinglePriv extends UnwrapArgsCommon {\n readonly recipientSecretKey: Uint8Array;\n}\n\nexport interface UnwrapArgsMultiPriv extends UnwrapArgsCommon {\n readonly recipientSecretKeys: ReadonlyArray<Uint8Array>;\n}\n\n// Bundle form of the multi-priv path: the caller passes both KEMs' secret\n// lists and the dispatch picks the right one from `envelope.kem`. This is the\n// surface every read-path consumer (inbox decrypt, CLI decrypt, standalone\n// recipient verifier) should use — they hold the whole identity key bundle and\n// must NOT pre-select a list or rebuild slots themselves.\nexport interface UnwrapArgsBundle extends UnwrapArgsCommon {\n readonly recipientKeyBundle: RecipientKeyBundle;\n}\n\nexport type UnwrapArgs = UnwrapArgsSinglePriv | UnwrapArgsMultiPriv | UnwrapArgsBundle;\n\n// Trial-decrypt-only sibling of eciesSealedPoeUnwrap. Runs the\n// per-slot AEAD + slots_mac check but NEVER calls the content AEAD (which\n// requires the off-chain `ciphertext` blob, not available at trial-decrypt\n// time). Used by an inbox-scan agent to discover readable records before\n// fetching their ciphertext.\ninterface TrialDecryptOnlyArgsCommon {\n readonly envelope: SealedEnvelope;\n readonly constantTimeN?: boolean;\n readonly _slotsAttemptedOut?: { count: number; perPrivCounts?: number[] };\n readonly _privsAttemptedOut?: { count: number };\n}\n\n// Exactly one of `recipientSecretKeys` (flat, KEM-pre-selected) or\n// `recipientKeyBundle` (whole bundle, KEM dispatched from `envelope.kem`).\n// Inbox-scan consumers pass the bundle; the low-level / parity tests pass the\n// flat list directly.\nexport type TrialDecryptOnlyArgs = TrialDecryptOnlyArgsCommon &\n (\n | { readonly recipientSecretKeys: ReadonlyArray<Uint8Array> }\n | { readonly recipientKeyBundle: RecipientKeyBundle }\n );\n\nexport type TrialDecryptOnlyResult =\n | { readonly kind: 'match'; readonly slotIdx: number; readonly cek: Uint8Array }\n | { readonly kind: 'no_aead_pass' }\n | { readonly kind: 'aead_pass_no_mac_match' };\n\nconst ZERO_NONCE_12: Uint8Array = new Uint8Array(12);\nconst EMPTY_SALT: Uint8Array = new Uint8Array(0);\nconst X25519_SECRET_KEY_LENGTH = 32 as const;\nconst X25519_PUBLIC_KEY_LENGTH = 32 as const;\nconst NONCE_LENGTH = 24 as const;\nconst WRAP_LENGTH = 48 as const;\nconst SLOTS_MAC_LENGTH = 32 as const;\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n}\n\n// Partitioning-oracle defence: every wire\n// length MUST be validated before any KEM/AEAD primitive is invoked, so malformed\n// records cannot probe per-slot failure ordering. Shared between\n// `eciesSealedPoeUnwrap` (single- and multi-priv) and `eciesSealedPoeTrialDecrypt`\n// to guarantee byte-identical pre-trial behaviour and to keep the dispatch\n// invariant in one place. For the hybrid branch this includes reassembling each\n// slot's `kem_ct` and asserting the flat enc length BEFORE any decapsulation.\nfunction assertEnvelopeStructure(\n envelope: SealedEnvelope,\n multiPrivKeys?: ReadonlyArray<Uint8Array>,\n singlePrivKey?: Uint8Array,\n): void {\n if (envelope.scheme !== 1) {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_ENC_VERSION',\n `envelope.scheme=${String(envelope.scheme)} unsupported (expected 1)`,\n );\n }\n if (envelope.aead !== 'xchacha20-poly1305') {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_AEAD_ALG',\n `envelope.aead=${String(envelope.aead)} unsupported (expected 'xchacha20-poly1305')`,\n );\n }\n if (envelope.kem !== 'x25519' && envelope.kem !== 'mlkem768x25519') {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_KEM_ALG',\n `envelope.kem=${String((envelope as { kem: string }).kem)} unsupported (expected 'x25519' or 'mlkem768x25519')`,\n );\n }\n\n // Envelope-level length pre-checks in this exact order.\n const n = envelope.slots.length;\n if (n < 1) {\n throw new EciesSealedPoeError('ENC_SLOTS_EMPTY', `envelope.slots.length=${n} must be >= 1`);\n }\n if (envelope.nonce.length !== NONCE_LENGTH) {\n throw new EciesSealedPoeError(\n 'NONCE_LENGTH_MISMATCH',\n `envelope.nonce MUST be exactly ${NONCE_LENGTH} bytes, got ${envelope.nonce.length}`,\n );\n }\n if (envelope.slots_mac.length !== SLOTS_MAC_LENGTH) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_MAC_INVALID_LENGTH',\n `envelope.slots_mac MUST be exactly ${SLOTS_MAC_LENGTH} bytes, got ${envelope.slots_mac.length}`,\n );\n }\n\n // Per-slot length pre-checks — KEM-driven. ALL slots are validated here,\n // before any decapsulation, so the trial-decrypt loop never observes a\n // malformed slot (partitioning-oracle-safe ordering).\n if (envelope.kem === 'x25519') {\n for (let i = 0; i < n; i++) {\n const slot = envelope.slots[i]!;\n if (slot.epk.length !== X25519_PUBLIC_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'KEM_EPK_LENGTH_MISMATCH',\n `envelope.slots[${i}].epk MUST be exactly ${X25519_PUBLIC_KEY_LENGTH} bytes, got ${slot.epk.length}`,\n );\n }\n if (slot.wrap.length !== WRAP_LENGTH) {\n throw new EciesSealedPoeError(\n 'WRAP_LENGTH_MISMATCH',\n `envelope.slots[${i}].wrap MUST be exactly ${WRAP_LENGTH} bytes, got ${slot.wrap.length}`,\n );\n }\n }\n } else {\n for (let i = 0; i < n; i++) {\n const slot = envelope.slots[i]!;\n const enc = joinKemCt(slot.kem_ct);\n if (enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new EciesSealedPoeError(\n 'KEM_CT_LENGTH_MISMATCH',\n `envelope.slots[${i}].kem_ct MUST reassemble to exactly ${MLKEM768X25519_ENC_LENGTH} bytes, got ${enc.length}`,\n );\n }\n if (slot.wrap.length !== WRAP_LENGTH) {\n throw new EciesSealedPoeError(\n 'WRAP_LENGTH_MISMATCH',\n `envelope.slots[${i}].wrap MUST be exactly ${WRAP_LENGTH} bytes, got ${slot.wrap.length}`,\n );\n }\n }\n }\n\n if (multiPrivKeys !== undefined) {\n for (let i = 0; i < multiPrivKeys.length; i++) {\n if (multiPrivKeys[i]!.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n `recipientSecretKeys[${i}] MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${multiPrivKeys[i]!.length}`,\n );\n }\n }\n } else if (singlePrivKey !== undefined) {\n if (singlePrivKey.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n `recipientSecretKey MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${singlePrivKey.length}`,\n );\n }\n }\n}\n\n// Classical (x25519) per-slot recovery body. Returns the CEK on the first\n// AEAD-tag success; null otherwise. `liveSlot` distinguishes the real-work path\n// (attempt the AEAD unwrap) from the constant-time-N dummy path (do the ECDH +\n// HKDF but skip the AEAD, since a CEK is already in hand).\nfunction tryX25519Slot(args: {\n slot: X25519Slot;\n recipientSecretKey: Uint8Array;\n pubRLocal: Uint8Array;\n liveSlot: boolean;\n}): Uint8Array | null {\n // A slot's `epk` is attacker-influenceable wire data. A small-order\n // Montgomery point makes the X25519 shared secret all-zero, which the KEM\n // rejects per RFC 7748 §6.1. Such a slot can never have been produced by a\n // conformant wrap for THIS recipient, so it is a non-match — handled here\n // identically to an AEAD-tag failure (skip the slot, keep iterating so the\n // constant-time-N loop shape is preserved). Only the contributory-check\n // rejection is swallowed; any other error propagates.\n if (args.liveSlot) {\n try {\n const shared = x25519Ecdh({\n secretKey: args.recipientSecretKey,\n theirPublicKey: args.slot.epk,\n });\n const kek = hkdfSha256({\n ikm: shared,\n salt: concat(args.slot.epk, args.pubRLocal),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n return chacha20Poly1305Decrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK,\n ciphertext: args.slot.wrap,\n });\n } catch (e) {\n if (!(e instanceof AeadVerificationError) && !(e instanceof X25519LowOrderPointError)) {\n throw e;\n }\n return null;\n }\n }\n // Constant-time-N dummy path: mirror the real-work ECDH + HKDF, still\n // tolerating a low-order epk in a later slot so it cannot turn a successful\n // unwrap into a throw.\n try {\n const shared = x25519Ecdh({\n secretKey: args.recipientSecretKey,\n theirPublicKey: args.slot.epk,\n });\n hkdfSha256({\n ikm: shared,\n salt: concat(args.slot.epk, args.pubRLocal),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n } catch (e) {\n if (!(e instanceof X25519LowOrderPointError)) throw e;\n }\n return null;\n}\n\n// Hybrid (mlkem768x25519) per-slot recovery body. X-Wing decapsulate NEVER\n// throws on attacker wire data (ML-KEM implicit rejection), so there is no\n// try/catch: a wrong shared secret simply yields a KEK that fails the AEAD tag.\n// The dummy (constant-time-N) path runs a FULL decapsulate + HKDF so matching\n// and non-matching slots cost the same X-Wing work.\nfunction tryMlkem768X25519Slot(args: {\n slot: Mlkem768X25519Slot;\n recipientSecretKey: Uint8Array;\n liveSlot: boolean;\n}): Uint8Array | null {\n // kem_ct length was validated to reassemble to MLKEM768X25519_ENC_LENGTH in\n // assertEnvelopeStructure, so this join + decapsulate is constant-work.\n const enc = joinKemCt(args.slot.kem_ct);\n const ss = mlkem768x25519Decapsulate({ secretSeed: args.recipientSecretKey, enc });\n const kek = hkdfSha256({\n ikm: ss,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n length: 32,\n });\n if (!args.liveSlot) {\n // Dummy path: full decapsulate + HKDF already done above; skip only the\n // AEAD attempt (a CEK is already in hand).\n return null;\n }\n try {\n return chacha20Poly1305Decrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n ciphertext: args.slot.wrap,\n });\n } catch (e) {\n if (!(e instanceof AeadVerificationError)) throw e;\n return null;\n }\n}\n\n// Per-priv inner trial-decrypt loop with slot-index reporting, KEM-driven.\n// Enters every slot when constantTimeN; the dummy path keeps per-iteration cost\n// uniform regardless of which slot matched.\nfunction tryRecipientUnwrapWithIdx(\n envelope: SealedEnvelope,\n recipientSecretKey: Uint8Array,\n constantTimeN: boolean,\n slotsAttemptedOut: { count: number; perPrivCounts?: number[] } | undefined,\n): { cek: Uint8Array; slotIdx: number } | null {\n const n = envelope.slots.length;\n let cek: Uint8Array | null = null;\n let matchedSlotIdx = -1;\n\n if (envelope.kem === 'x25519') {\n const pubRLocal = x25519PublicKey({ secretKey: recipientSecretKey });\n for (let i = 0; i < n; i++) {\n if (slotsAttemptedOut !== undefined) {\n slotsAttemptedOut.count = i + 1;\n }\n const candidate = tryX25519Slot({\n slot: envelope.slots[i]!,\n recipientSecretKey,\n pubRLocal,\n liveSlot: cek === null,\n });\n if (cek === null && candidate !== null) {\n cek = candidate;\n matchedSlotIdx = i;\n }\n if (cek !== null && !constantTimeN) break;\n }\n } else {\n for (let i = 0; i < n; i++) {\n if (slotsAttemptedOut !== undefined) {\n slotsAttemptedOut.count = i + 1;\n }\n const candidate = tryMlkem768X25519Slot({\n slot: envelope.slots[i]!,\n recipientSecretKey,\n liveSlot: cek === null,\n });\n if (cek === null && candidate !== null) {\n cek = candidate;\n matchedSlotIdx = i;\n }\n if (cek !== null && !constantTimeN) break;\n }\n }\n return cek === null ? null : { cek, slotIdx: matchedSlotIdx };\n}\n\n// Back-compat wrapper preserved for callers that only care about the CEK\n// (single-priv path inside `eciesSealedPoeUnwrap`).\nfunction tryRecipientUnwrap(\n envelope: SealedEnvelope,\n recipientSecretKey: Uint8Array,\n constantTimeN: boolean,\n slotsAttemptedOut: { count: number; perPrivCounts?: number[] } | undefined,\n): Uint8Array | null {\n return (\n tryRecipientUnwrapWithIdx(envelope, recipientSecretKey, constantTimeN, slotsAttemptedOut)\n ?.cek ?? null\n );\n}\n\n// Slot-set MAC bytes, KEM-driven so the hybrid kem_ct is\n// committed exactly as it appears on-wire. Constant across the multi-priv outer\n// loop (depends only on envelope.slots), so callers compute it once.\nfunction slotsMacCborBytes(envelope: SealedEnvelope): Uint8Array {\n return slotsToMacCbor(\n envelope.slots as ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n envelope.kem,\n );\n}\n\nexport function eciesSealedPoeUnwrap(args: UnwrapArgs): UnwrapResult {\n const { envelope, ciphertext } = args;\n const constantTimeN = args.constantTimeN ?? true;\n\n // Exactly-one-of validation across the three UnwrapArgs forms (single-priv,\n // flat multi-priv, bundle). Runs before any AEAD / wire-shape work so a\n // malformed call cannot probe per-slot AEAD timing. The bundle form resolves\n // to a flat multi-priv list here by dispatching on `envelope.kem` — from this\n // point the loop is identical regardless of how the caller supplied keys.\n const hasSingle = 'recipientSecretKey' in args;\n const hasBundle = 'recipientKeyBundle' in args;\n const multiPrivKeys: ReadonlyArray<Uint8Array> | undefined = hasBundle\n ? selectBundleSecrets(envelope, (args as UnwrapArgsBundle).recipientKeyBundle)\n : 'recipientSecretKeys' in args\n ? (args as UnwrapArgsMultiPriv).recipientSecretKeys\n : undefined;\n const hasMulti = multiPrivKeys !== undefined;\n if (hasSingle === hasMulti) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'exactly one of recipientSecretKey / recipientSecretKeys / recipientKeyBundle MUST be supplied',\n );\n }\n // A bundle selecting an empty list for this KEM means the recipient holds no\n // key of the matching kind (e.g. an archived-only identity facing a hybrid\n // record). That is a legitimate non-match, NOT a malformed call — return a\n // clean WRONG_RECIPIENT_KEY without invoking any KEM primitive. The flat\n // multi-priv form keeps the original \"empty array is a programmer error\"\n // contract its callers (and step-3 tests) rely on.\n if (hasMulti && multiPrivKeys!.length === 0) {\n if (hasBundle) {\n return { matched: false, reason: 'WRONG_RECIPIENT_KEY' };\n }\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'recipientSecretKeys MUST be a non-empty array, got length=0',\n );\n }\n\n // Partitioning-oracle pre-checks; per-priv length validation happens\n // inside `assertEnvelopeStructure`.\n if (hasMulti) {\n assertEnvelopeStructure(envelope, multiPrivKeys, undefined);\n } else {\n assertEnvelopeStructure(envelope, undefined, (args as UnwrapArgsSinglePriv).recipientSecretKey);\n }\n\n // Trial-decrypt loop. With constantTimeN=true the loop\n // entries are uniform regardless of match position; the per-iteration body\n // does the same KEM + HKDF work in both branches.\n\n let matchedCek: Uint8Array | null = null;\n let anyCandidateRecovered = false;\n\n if (hasSingle) {\n const recipientSecretKey = (args as UnwrapArgsSinglePriv).recipientSecretKey;\n const cek = tryRecipientUnwrap(\n envelope,\n recipientSecretKey,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (cek === null) {\n return { matched: false, reason: 'WRONG_RECIPIENT_KEY' };\n }\n // Slot-set MAC verification. Use compareCt to\n // avoid leaking byte-position via early-exit on first mismatching byte.\n const slotsCbor = slotsMacCborBytes(envelope);\n const hmacKey = hkdfSha256({\n ikm: cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsMacCalc = hmac(sha256, hmacKey, slotsCbor);\n if (!compareCt(slotsMacCalc, envelope.slots_mac)) {\n return { matched: false, reason: 'TAMPERED_HEADER' };\n }\n matchedCek = cek;\n } else {\n // The slots-CBOR is constant across the outer loop (depends only on\n // envelope.slots) — compute once before the loop to keep per-priv cost\n // identical to the single-priv path.\n const slotsCbor = slotsMacCborBytes(envelope);\n const recipientSecretKeys = multiPrivKeys!;\n for (let k = 0; k < recipientSecretKeys.length; k++) {\n if (args._privsAttemptedOut !== undefined) {\n args._privsAttemptedOut.count = k + 1;\n }\n if (args._slotsAttemptedOut !== undefined) {\n args._slotsAttemptedOut.count = 0;\n }\n const cek = tryRecipientUnwrap(\n envelope,\n recipientSecretKeys[k]!,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (args._slotsAttemptedOut?.perPrivCounts !== undefined) {\n args._slotsAttemptedOut.perPrivCounts.push(args._slotsAttemptedOut.count);\n }\n if (cek === null) continue;\n // Slot-set MAC verification per priv that recovered a candidate CEK.\n const hmacKey = hkdfSha256({\n ikm: cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsMacCalc = hmac(sha256, hmacKey, slotsCbor);\n // The outer cross-priv loop short-circuits on the first priv whose\n // recovered CEK also passes slots_mac. This intentionally leaks \"which\n // priv matched\" → \"how many key rotations the recipient has performed\".\n // We accept it: trial-decrypt runs client-side, so this timing is only\n // locally observable, and the leak is a weak ordering signal, not a\n // key/plaintext oracle. Making the outer loop constant-work would cost a\n // FULL KEM decapsulation (an X25519 ECDH, or — for the hybrid branch — a\n // full X-Wing ML-KEM-768 + X25519 decapsulation) for EVERY archived priv\n // on EVERY record, which for the hybrid case is the dominant cost; the\n // benefit (hiding a count the user already knows) does not justify it.\n // The inner per-slot loop IS held constant-work (constant-time-N).\n if (compareCt(slotsMacCalc, envelope.slots_mac)) {\n matchedCek = cek;\n break;\n }\n anyCandidateRecovered = true;\n }\n if (matchedCek === null) {\n return {\n matched: false,\n reason: anyCandidateRecovered ? 'TAMPERED_HEADER' : 'WRONG_RECIPIENT_KEY',\n };\n }\n }\n\n // Content AEAD AAD is `nonce || slots_mac`.\n const adContent = concat(envelope.nonce, envelope.slots_mac);\n try {\n const plaintext = xchacha20Poly1305Decrypt({\n key: matchedCek,\n nonce: envelope.nonce,\n aad: adContent,\n ciphertext,\n });\n return { matched: true, plaintext };\n } catch (e) {\n if (!(e instanceof AeadVerificationError)) throw e;\n return { matched: false, reason: 'TAMPERED_CIPHERTEXT' };\n }\n}\n\n// Trial-decrypt half of the sealed-PoE unwrap algorithm:\n// recovers the CEK + slot index without touching the content AEAD. Used by an\n// inbox-scan agent where the on-chain `metadata_cbor` envelope is available but\n// the off-chain ciphertext blob is fetched lazily only when the user invokes\n// Decrypt.\n//\n// Mirrors the multi-priv branch of `eciesSealedPoeUnwrap`: same\n// partitioning-oracle pre-checks, same per-priv inner loop, same\n// constant-time-N invariant (default `true` — MANDATORY for untrusted scan\n// agents), same `compareCt` slots_mac check. Differs only\n// in the return shape: `{kind: 'match', slotIdx, cek}` instead of plaintext;\n// `{kind: 'aead_pass_no_mac_match'}`\n// instead of `TAMPERED_HEADER`; `{kind: 'no_aead_pass'}` instead of\n// `WRONG_RECIPIENT_KEY`. Cross-priv variable-time short-circuit is preserved\n// (leaks \"which priv matched\" → \"how many rotations\",\n// a documented weak ordering signal).\nexport function eciesSealedPoeTrialDecrypt(args: TrialDecryptOnlyArgs): TrialDecryptOnlyResult {\n const { envelope } = args;\n const constantTimeN = args.constantTimeN ?? true;\n\n // Bundle form selects the per-KEM list from `envelope.kem`; flat form is\n // already KEM-pre-selected. An empty bundle list for this KEM is a clean\n // no_aead_pass (the recipient holds no key of the matching kind), whereas an\n // empty flat list stays a programmer error (its callers / step-3 tests rely\n // on the throw).\n const hasBundle = 'recipientKeyBundle' in args;\n const recipientSecretKeys: ReadonlyArray<Uint8Array> = hasBundle\n ? selectBundleSecrets(envelope, args.recipientKeyBundle)\n : args.recipientSecretKeys;\n\n if (recipientSecretKeys.length === 0) {\n if (hasBundle) {\n return { kind: 'no_aead_pass' };\n }\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'recipientSecretKeys MUST be a non-empty array, got length=0',\n );\n }\n assertEnvelopeStructure(envelope, recipientSecretKeys, undefined);\n\n const slotsCbor = slotsMacCborBytes(envelope);\n\n let anyCandidateRecovered = false;\n for (let k = 0; k < recipientSecretKeys.length; k++) {\n if (args._privsAttemptedOut !== undefined) {\n args._privsAttemptedOut.count = k + 1;\n }\n if (args._slotsAttemptedOut !== undefined) {\n args._slotsAttemptedOut.count = 0;\n }\n const candidate = tryRecipientUnwrapWithIdx(\n envelope,\n recipientSecretKeys[k]!,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (args._slotsAttemptedOut?.perPrivCounts !== undefined) {\n args._slotsAttemptedOut.perPrivCounts.push(args._slotsAttemptedOut.count);\n }\n if (candidate === null) continue;\n const hmacKey = hkdfSha256({\n ikm: candidate.cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsMacCalc = hmac(sha256, hmacKey, slotsCbor);\n if (compareCt(slotsMacCalc, envelope.slots_mac)) {\n return { kind: 'match', slotIdx: candidate.slotIdx, cek: candidate.cek };\n }\n anyCandidateRecovered = true;\n }\n return anyCandidateRecovered ? { kind: 'aead_pass_no_mac_match' } : { kind: 'no_aead_pass' };\n}\n","// The single seam that turns a structurally-validated but permissive on-wire\n// `enc` block into the discriminated `SealedEnvelope` the unwrap / trial-decrypt\n// path consumes.\n//\n// Every read-path consumer (inbox trial-decrypt, inbox CEK recovery, the CLI\n// `inbox sync` / `inbox decrypt` orchestrators, the standalone recipient\n// verifier) used to do this inline with a HARDCODED `kem: 'x25519'` and an\n// unconditional `slots.map(s => ({ epk: s.epk, wrap: s.wrap }))`. With the\n// discriminated-union slot shape (classical `{epk, wrap}` vs hybrid\n// `{kem_ct, wrap}`) that inline build is both wrong (drops `kem_ct`) and\n// uncompilable (reads optional `epk` as required). This helper is the ONE place\n// the conversion lives: it dispatches on `enc.kem`, picks the matching per-slot\n// fields, and returns `null` for anything that is not a recognised sealed\n// envelope (passphrase-only blocks, missing slots, unknown KEM). Callers then\n// pass the whole returned envelope plus their `RecipientKeyBundle` straight to\n// `eciesSealedPoeUnwrap` / `eciesSealedPoeTrialDecrypt` — they never rebuild\n// slots or reassemble `kem_ct` themselves.\n//\n// crypto-core is a leaf package and must not depend on poe-standard's Zod\n// schema, so the input is a structural shape mirroring the fields the parsed\n// `EncryptionEnvelope` exposes. Anything narrower (per-slot length checks) is\n// re-asserted by `assertEnvelopeStructure` inside the unwrap path; this helper\n// is purely the KEM-driven shape projection.\n\nimport type { Mlkem768X25519Slot, SealedEnvelope, X25519Slot } from './wrap';\n\n// Structural mirror of the parsed-but-permissive on-wire slot. Each field is\n// `T | undefined` (not just optional) so the parsed `EncryptionEnvelope` from a\n// consumer compiled with `exactOptionalPropertyTypes` is assignable without a\n// cast: the schema layer cannot know the envelope `kem` from a slot in\n// isolation, so it leaves all three fields optional (see poe-standard\n// SlotSchema).\nexport interface ParsedSlotShape {\n readonly epk?: Uint8Array | undefined;\n readonly kem_ct?: ReadonlyArray<Uint8Array> | undefined;\n readonly wrap?: Uint8Array | undefined;\n}\n\n// Structural mirror of the parsed-but-permissive `enc` block.\nexport interface ParsedEnvelopeShape {\n readonly scheme?: unknown;\n readonly aead?: string | undefined;\n readonly kem?: string | undefined;\n readonly nonce?: Uint8Array | undefined;\n readonly slots?: ReadonlyArray<ParsedSlotShape> | undefined;\n readonly slots_mac?: Uint8Array | undefined;\n}\n\n// Build the discriminated `SealedEnvelope` from a parsed `enc` block, or return\n// `null` when the block is not a sealed-recipient envelope we can trial-decrypt\n// (passphrase-only, missing slots/nonce/slots_mac, unrecognised KEM, or a slot\n// missing the KEM's required field). Returning `null` keeps every consumer's\n// \"this item is not for the recipient path → no match, no crypto\" branch.\nexport function sealedEnvelopeFromParsed(enc: ParsedEnvelopeShape): SealedEnvelope | null {\n if (enc.scheme !== 1 || enc.aead !== 'xchacha20-poly1305') return null;\n if (enc.nonce === undefined || enc.slots_mac === undefined) return null;\n const slots = enc.slots;\n if (slots === undefined || slots.length < 1) return null;\n\n if (enc.kem === 'x25519') {\n const x25519Slots: X25519Slot[] = [];\n for (const s of slots) {\n if (s.epk === undefined || s.wrap === undefined) return null;\n x25519Slots.push({ epk: s.epk, wrap: s.wrap });\n }\n return {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'x25519',\n nonce: enc.nonce,\n slots: x25519Slots,\n slots_mac: enc.slots_mac,\n };\n }\n\n if (enc.kem === 'mlkem768x25519') {\n const hybridSlots: Mlkem768X25519Slot[] = [];\n for (const s of slots) {\n if (s.kem_ct === undefined || s.wrap === undefined) return null;\n hybridSlots.push({ kem_ct: s.kem_ct, wrap: s.wrap });\n }\n return {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'mlkem768x25519',\n nonce: enc.nonce,\n slots: hybridSlots,\n slots_mac: enc.slots_mac,\n };\n }\n\n return null;\n}\n","// Canonical outbound HTTP wrapper: deny-list short-circuit, protocol/method\n// allowlist, bounded timeout, exp-backoff retry with jitter, audit trail.\n\n// Universal loopback deny-host list a service-independent verifier MUST reject\n// so a record can never be made to \"verify\" only because it reached a loopback\n// address. This default carries no operator-specific entries: a deployment that\n// wants to forbid its own gateway/viewer hosts appends those at construction\n// time. Producers SHOULD pass this through `denyHosts` on every verifier\n// invocation; the wrapper accepts arbitrary lists but exports the canonical\n// loopback set so callers don't duplicate it inline. (RFC-1918 / link-local IP\n// ranges are blocked separately by the SSRF guard, not by this name list.)\nexport const DENY_HOSTS_DEFAULT: ReadonlyArray<string> = ['localhost', '127.0.0.1'];\n\n// Every outbound call carries a purpose tag from the closed set\n// `{cardano, arweave, ipfs}` (the three v1 gateway-chain purposes).\n// `https` is a transitional legacy tag for non-storage HTTPS\n// auxiliaries; new code SHOULD pick one of the three normative purposes.\n// `webhook` is the user-supplied-URL purpose: it triggers the SSRF guard\n// (DNS resolution + IP range check + connection pinning + redirect-chain\n// re-checking + body-size cap), and MUST be used for any fetch where the\n// target URL came from end-user input.\nexport type HttpPurpose = 'cardano' | 'arweave' | 'ipfs' | 'https' | 'webhook';\nexport type HttpMethod = 'GET' | 'POST';\n\nexport interface FetchOutboundOptions {\n readonly method: HttpMethod;\n readonly purpose: HttpPurpose;\n readonly headers?: Readonly<Record<string, string>>;\n readonly body?: string;\n // Hard cap on the response body the primitive will buffer. Gateway content\n // (ar:// / ipfs:// / https) is producer-chosen and therefore UNTRUSTED — the\n // verifier never trusts the producer — so a malicious gateway could otherwise\n // stream unbounded bytes into memory. Omit to use DEFAULT_OUTBOUND_MAX_BYTES.\n readonly maxBytes?: number;\n}\n\nexport interface FetchOutboundResult {\n readonly status: number;\n readonly bytes: Uint8Array;\n readonly durationMs: number;\n}\n\nexport type FetchOutbound = (\n url: string,\n opts: FetchOutboundOptions,\n) => Promise<FetchOutboundResult>;\n\n// Audit-log entry for one outbound HTTP fetch. Field names are snake_case so\n// the record can land directly on `VerifyReport.http_calls[]` (which IS the\n// wire shape) without a key-renaming pass.\nexport interface HttpCallRecord {\n readonly url: string;\n readonly method: HttpMethod;\n readonly status: number;\n readonly bytes: number;\n readonly duration_ms: number;\n readonly purpose: HttpPurpose;\n}\n\nexport interface RetryConfig {\n readonly timeoutMs?: number;\n readonly retries?: number;\n readonly retryableStatuses?: ReadonlyArray<number>;\n}\n\nexport interface WrapFetchOutboundConfig extends RetryConfig {\n readonly denyHosts?: ReadonlyArray<string>;\n}\n\nexport class DenyHostError extends Error {\n readonly code = 'SERVICE_INDEPENDENCE_VIOLATION';\n readonly host: string;\n readonly url: string;\n constructor(host: string, url: string) {\n super(`SERVICE_INDEPENDENCE_VIOLATION: host \"${host}\" is in denyHosts (url=${url})`);\n this.name = 'DenyHostError';\n this.host = host;\n this.url = url;\n }\n}\n\nexport class UnsupportedProtocolError extends Error {\n readonly code = 'UNSUPPORTED_PROTOCOL';\n readonly protocol: string;\n readonly url: string;\n constructor(protocol: string, url: string) {\n super(`UNSUPPORTED_PROTOCOL: \"${protocol}\" not in {http:, https:} (url=${url})`);\n this.name = 'UnsupportedProtocolError';\n this.protocol = protocol;\n this.url = url;\n }\n}\n\nexport class UnsupportedMethodError extends Error {\n readonly code = 'UNSUPPORTED_METHOD';\n readonly method: string;\n readonly url: string;\n constructor(method: string, url: string) {\n super(`UNSUPPORTED_METHOD: \"${method}\" not in {GET, POST} (url=${url})`);\n this.name = 'UnsupportedMethodError';\n this.method = method;\n this.url = url;\n }\n}\n\nexport class BodyTooLargeError extends Error {\n readonly code = 'OUTBOUND_BODY_TOO_LARGE';\n readonly url: string;\n readonly limitBytes: number;\n constructor(url: string, limitBytes: number) {\n super(`OUTBOUND_BODY_TOO_LARGE: response exceeded ${limitBytes} bytes (url=${url})`);\n this.name = 'BodyTooLargeError';\n this.url = url;\n this.limitBytes = limitBytes;\n }\n}\n\nexport class OutboundExhaustedError extends Error {\n readonly code = 'OUTBOUND_EXHAUSTED';\n readonly url: string;\n readonly attempts: number;\n readonly lastStatus: number | undefined;\n readonly lastError: Error | undefined;\n constructor(args: {\n url: string;\n attempts: number;\n lastStatus?: number | undefined;\n lastError?: Error | undefined;\n }) {\n super(\n `OUTBOUND_EXHAUSTED: ${args.attempts} attempts exhausted (url=${args.url}, lastStatus=${args.lastStatus ?? '-'})`,\n );\n this.name = 'OutboundExhaustedError';\n this.url = args.url;\n this.attempts = args.attempts;\n this.lastStatus = args.lastStatus;\n this.lastError = args.lastError;\n }\n}\n\nexport const DEFAULT_TIMEOUT_MS = 10_000;\n// Default response-body cap for the verifier's gateway fetches. 64 MiB sits\n// well above any single sealed-PoE ciphertext or merkle-leaf payload a verifier\n// would realistically recompute a hash over, while bounding the memory a hostile\n// gateway can force the verifier to allocate for one request. Callers that\n// legitimately handle larger content raise it per-call via `opts.maxBytes`.\nexport const DEFAULT_OUTBOUND_MAX_BYTES = 64 * 1024 * 1024;\nexport const DEFAULT_RETRYABLE_STATUSES: ReadonlyArray<number> = [502, 503, 504];\nconst BACKOFF_BASE_MS: ReadonlyArray<number> = [1000, 2000, 4000];\nconst JITTER_RATIO = 0.25;\n\nfunction canonicaliseHost(host: string): string {\n return host.replace(/^\\[/, '').replace(/\\]$/, '').replace(/\\.$/, '').toLowerCase();\n}\n\nexport function matchesDenyList(host: string, denyHosts: ReadonlyArray<string>): boolean {\n const h = canonicaliseHost(host);\n for (const raw of denyHosts) {\n const pattern = raw.replace(/\\.$/, '').toLowerCase();\n if (pattern.startsWith('*.')) {\n const suffix = pattern.slice(2);\n if (h.endsWith('.' + suffix)) return true;\n continue;\n }\n if (h === pattern) return true;\n if (pattern === 'localhost') {\n if (h === '::1' || h === '0.0.0.0' || h === '169.254.169.254') return true;\n }\n if (pattern === '127.0.0.1') {\n if (/^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n }\n }\n return false;\n}\n\nfunction parseProtocol(url: string): string | null {\n try {\n return new URL(url).protocol;\n } catch {\n return null;\n }\n}\n\nfunction isAllowedMethod(method: string): method is HttpMethod {\n return method === 'GET' || method === 'POST';\n}\n\nfunction backoffJitteredMs(attemptIndex: number): number {\n const idx = Math.min(attemptIndex, BACKOFF_BASE_MS.length - 1);\n const base = BACKOFF_BASE_MS[idx] ?? BACKOFF_BASE_MS[BACKOFF_BASE_MS.length - 1]!;\n const jitter = 1 + (Math.random() - 0.5) * 2 * JITTER_RATIO;\n return base * jitter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport const defaultFetchOutbound: FetchOutbound = async (url, opts) => {\n const t0 = Date.now();\n const maxBytes = opts.maxBytes ?? DEFAULT_OUTBOUND_MAX_BYTES;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);\n const init: RequestInit = {\n method: opts.method,\n signal: controller.signal,\n };\n if (opts.headers) init.headers = { ...opts.headers };\n if (opts.body !== undefined) init.body = opts.body;\n try {\n // allow-raw-fetch: canonical defaultFetchOutbound — single egress point\n const res = await fetch(url, init);\n\n // Fast path: a truthful Content-Length over the cap lets us bail before\n // reading a single body byte. A lying/absent header is still caught by the\n // streaming counter below — the header is an optimisation, not the guard.\n const declared = res.headers.get('content-length');\n if (declared !== null) {\n const declaredLen = Number(declared);\n if (Number.isFinite(declaredLen) && declaredLen > maxBytes) {\n controller.abort();\n throw new BodyTooLargeError(url, maxBytes);\n }\n }\n\n const bytes = await readBodyCapped(res, url, maxBytes, controller);\n return { status: res.status, bytes, durationMs: Date.now() - t0 };\n } finally {\n clearTimeout(timeout);\n }\n};\n\n// Stream the response body, aborting the underlying request the instant the\n// running byte count exceeds `maxBytes`. This is the actual OOM guard: a\n// gateway that withholds or lies about Content-Length still cannot make us\n// buffer more than the cap, because we stop reading and tear the socket down.\nasync function readBodyCapped(\n res: Response,\n url: string,\n maxBytes: number,\n controller: AbortController,\n): Promise<Uint8Array> {\n const body = res.body;\n if (body === null) {\n // No stream (e.g. a 204, or a fetch polyfill that buffered eagerly). Fall\n // back to arrayBuffer but still enforce the cap on the materialised length.\n const buf = await res.arrayBuffer();\n if (buf.byteLength > maxBytes) {\n throw new BodyTooLargeError(url, maxBytes);\n }\n return new Uint8Array(buf);\n }\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value === undefined) continue;\n total += value.byteLength;\n if (total > maxBytes) {\n controller.abort();\n throw new BodyTooLargeError(url, maxBytes);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n}\n\nexport function wrapFetchOutbound(\n inner: FetchOutbound,\n audit: HttpCallRecord[],\n config: WrapFetchOutboundConfig | ReadonlyArray<string> | undefined = undefined,\n): FetchOutbound {\n // Accept either a denyHosts array (positional) or the full config object.\n const normConfig: WrapFetchOutboundConfig =\n config === undefined\n ? {}\n : Array.isArray(config)\n ? { denyHosts: config as ReadonlyArray<string> }\n : (config as WrapFetchOutboundConfig);\n\n const denyHosts = normConfig.denyHosts ?? [];\n // Default retries=0 (single attempt). Callers opt in via explicit `retries`;\n // the top-level `fetchOutbound` entrypoint forwards caller config.\n const retries = normConfig.retries ?? 0;\n const retryableStatuses = normConfig.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES;\n\n return async (url, opts) => {\n // The `webhook` purpose has bespoke requirements (DNS pinning,\n // per-hop redirect re-checking, body-size cap) that the generic\n // wrapper cannot satisfy. Force callers to use `fetchWebhook`\n // instead of silently accepting the call here.\n if (opts.purpose === 'webhook') {\n audit.push({\n url,\n method: 'GET',\n status: 0,\n bytes: 0,\n duration_ms: 0,\n purpose: opts.purpose,\n });\n throw new Error(\n `webhook purpose must be sent via fetchWebhook, not fetchOutbound (url=${url})`,\n );\n }\n\n // Protocol allowlist.\n const protocol = parseProtocol(url);\n if (protocol !== 'http:' && protocol !== 'https:') {\n audit.push({\n url,\n method: 'GET',\n status: 0,\n bytes: 0,\n duration_ms: 0,\n purpose: opts.purpose,\n });\n throw new UnsupportedProtocolError(protocol ?? '', url);\n }\n\n // Method allowlist.\n if (!isAllowedMethod(opts.method)) {\n audit.push({\n url,\n method: 'GET',\n status: 0,\n bytes: 0,\n duration_ms: 0,\n purpose: opts.purpose,\n });\n throw new UnsupportedMethodError(opts.method, url);\n }\n\n // Deny-list short-circuit.\n if (denyHosts.length > 0) {\n const host = new URL(url).hostname;\n if (matchesDenyList(host, denyHosts)) {\n audit.push({\n url,\n method: opts.method,\n status: 0,\n bytes: 0,\n duration_ms: 0,\n purpose: opts.purpose,\n });\n throw new DenyHostError(canonicaliseHost(host), url);\n }\n }\n\n // Retry loop. retries=0 → single attempt, return-or-rethrow original.\n let lastStatus: number | undefined;\n let lastError: Error | undefined;\n const totalAttempts = retries + 1;\n for (let attempt = 1; attempt <= totalAttempts; attempt++) {\n const t0 = Date.now();\n try {\n const result = await inner(url, opts);\n audit.push({\n url,\n method: opts.method,\n status: result.status,\n bytes: result.bytes.byteLength,\n duration_ms: result.durationMs,\n purpose: opts.purpose,\n });\n if (retryableStatuses.includes(result.status) && retries > 0) {\n lastStatus = result.status;\n if (attempt < totalAttempts) {\n await sleep(backoffJitteredMs(attempt - 1));\n continue;\n }\n break;\n }\n return result;\n } catch (e) {\n const durationMs = Date.now() - t0;\n if (\n e instanceof DenyHostError ||\n e instanceof UnsupportedProtocolError ||\n e instanceof UnsupportedMethodError\n ) {\n audit.push({\n url,\n method: opts.method,\n status: 0,\n bytes: 0,\n duration_ms: durationMs,\n purpose: opts.purpose,\n });\n throw e;\n }\n audit.push({\n url,\n method: opts.method,\n status: 0,\n bytes: 0,\n duration_ms: durationMs,\n purpose: opts.purpose,\n });\n lastError = e as Error;\n if (attempt < totalAttempts) {\n await sleep(backoffJitteredMs(attempt - 1));\n continue;\n }\n break;\n }\n }\n // Single-attempt mode re-throws the original verbatim so callers can match\n // by identity; retry mode wraps the terminal failure in OutboundExhaustedError.\n if (retries === 0 && lastError !== undefined) {\n throw lastError;\n }\n throw new OutboundExhaustedError({ url, attempts: totalAttempts, lastStatus, lastError });\n };\n}\n\nexport async function fetchOutbound(\n url: string,\n opts: FetchOutboundOptions,\n audit: HttpCallRecord[],\n config: WrapFetchOutboundConfig = {},\n): Promise<FetchOutboundResult> {\n const wrapped = wrapFetchOutbound(defaultFetchOutbound, audit, config);\n return wrapped(url, opts);\n}\n","// Verifier-side URI fetching plus the canonical `fetchOutbound` re-exports.\n// Two concerns colocated:\n//\n// * `fetchItemCiphertext` — given a chunked `uris[]` from a record item or\n// merkle entry, reconstruct the URI, dispatch to the appropriate gateway\n// chain (ar:// → Arweave HTTPS rotation; ipfs:// → caller-supplied IPFS\n// rotation), and return the raw bytes. Per-attempt diagnostics surface\n// as `URI_FETCH_FAILED` warnings in the caller's sink; the chain-exhausted\n// terminal state throws `CONTENT_UNAVAILABLE` so the caller emits the\n// terminal verdict.\n//\n// * Canonical re-exports of `defaultFetchOutbound`, `wrapFetchOutbound`, et\n// al. from `../fetch/fetch-outbound.js`.\n\nimport type { FetchOutbound, VerifyUriCheck } from './types';\n\nexport {\n BodyTooLargeError,\n DEFAULT_OUTBOUND_MAX_BYTES,\n defaultFetchOutbound,\n DENY_HOSTS_DEFAULT,\n DenyHostError,\n fetchOutbound,\n OutboundExhaustedError,\n UnsupportedMethodError,\n UnsupportedProtocolError,\n wrapFetchOutbound,\n} from '../fetch/fetch-outbound';\nexport type { RetryConfig, WrapFetchOutboundConfig } from '../fetch/fetch-outbound';\n\n// Default Arweave gateway rotation.\nconst ARWEAVE_DEFAULTS: ReadonlyArray<string> = [\n 'https://arweave.net',\n 'https://ar-io.net',\n 'https://g8way.io',\n];\n\nconst ARWEAVE_TXID_RE = /^[A-Za-z0-9_-]{43}$/;\n\nexport interface FetchItemCiphertextArgs {\n // Reconstructed-from-chunks URI list (each entry is itself a chunk array).\n readonly uris: ReadonlyArray<ReadonlyArray<string>>;\n readonly arweaveGateways?: ReadonlyArray<string> | undefined;\n readonly ipfsGateways?: ReadonlyArray<string> | undefined;\n readonly fetchFn: FetchOutbound;\n // Caller-supplied sink for per-attempt URI diagnostics. Each gateway failure\n // appends a `{ok: false, reason}` entry; the successful gateway appends\n // `{ok: true}`.\n readonly uriChecksOut: VerifyUriCheck[];\n // Caller path: `items[i]` → `itemIndex`; `merkle[i]` → reuse the field for\n // mapping (the report's `uriChecks[]` is item-indexed for v1).\n readonly itemIndex: number;\n}\n\n// Returns the first gateway response whose status is 200. Individual gateway\n// failures are warnings; only chain-exhaustion raises the terminal\n// `CONTENT_UNAVAILABLE`. The closed v1 scheme set is `{ar://, ipfs://}`; any\n// other scheme has already been rejected by the structural validator as\n// `INVALID_URI` and is rejected here too as defence in depth\n// (`URI_TARGET_FORBIDDEN`).\nexport async function fetchItemCiphertext(args: FetchItemCiphertextArgs): Promise<Uint8Array> {\n const reconstructed = args.uris.map((chunks) => chunks.join(''));\n const candidate = reconstructed.find((u) => /^(ar|ipfs):\\/\\//.test(u));\n if (candidate === undefined) {\n // No in-set URI present — defence-in-depth rejection.\n for (const u of reconstructed) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: u,\n ok: false,\n reason: 'URI_TARGET_FORBIDDEN',\n });\n }\n throw new Error('URI_TARGET_FORBIDDEN');\n }\n\n if (candidate.startsWith('ar://')) {\n const txid = candidate.slice(5);\n if (!ARWEAVE_TXID_RE.test(txid)) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: 'INVALID_URI',\n });\n throw new Error('CONTENT_UNAVAILABLE');\n }\n const gateways =\n args.arweaveGateways && args.arweaveGateways.length > 0\n ? args.arweaveGateways\n : ARWEAVE_DEFAULTS;\n for (const gw of gateways) {\n try {\n const res = await args.fetchFn(`${gw}/${txid}`, { method: 'GET', purpose: 'arweave' });\n if (res.status === 200) {\n args.uriChecksOut.push({ item_index: args.itemIndex, uri: candidate, ok: true });\n return res.bytes;\n }\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: `URI_FETCH_FAILED:${gw}:${res.status}`,\n });\n } catch (e) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: `URI_FETCH_FAILED:${gw}:${e instanceof Error ? e.message : String(e)}`,\n });\n }\n }\n throw new Error('CONTENT_UNAVAILABLE');\n }\n\n // ipfs:// — caller MUST configure an IPFS gateway chain. No baked-in\n // defaults: IPFS gateways are not the producer's storage provider, and a\n // silent fallback would couple the verifier to an off-record gateway.\n const cidPart = candidate.slice('ipfs://'.length);\n const ipfsCid = cidPart.split('/')[0] ?? cidPart;\n const ipfsGateways = args.ipfsGateways;\n if (ipfsGateways === undefined || ipfsGateways.length === 0) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: 'CONTENT_UNAVAILABLE:no_ipfs_gateway',\n });\n throw new Error('CONTENT_UNAVAILABLE');\n }\n for (const gw of ipfsGateways) {\n try {\n const sep = gw.endsWith('/') ? '' : '/';\n const url = `${gw}${sep}ipfs/${ipfsCid}`;\n const res = await args.fetchFn(url, { method: 'GET', purpose: 'ipfs' });\n if (res.status === 200) {\n args.uriChecksOut.push({ item_index: args.itemIndex, uri: candidate, ok: true });\n return res.bytes;\n }\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: `URI_FETCH_FAILED:${gw}:${res.status}`,\n });\n } catch (e) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: `URI_FETCH_FAILED:${gw}:${e instanceof Error ? e.message : String(e)}`,\n });\n }\n }\n throw new Error('CONTENT_UNAVAILABLE');\n}\n","// Sealed-PoE decryption.\n//\n// Two mutually-exclusive on-wire paths:\n// * `enc.slots[]` (sealed-recipient, X25519 ECIES) — invokes\n// `eciesSealedPoeUnwrap` from `@cardanowall/crypto-core/sealed-poe`.\n// * `enc.passphrase` (Argon2id-derived CEK) — derives the CEK and runs\n// the AEAD primitive directly (empty AAD on the passphrase path).\n//\n// After successful unwrap (either path), the verifier recomputes every\n// content-hash entry in `item.hashes` and compares to the recovered plaintext.\n// Mismatch surfaces as `URI_INTEGRITY_MISMATCH`.\n\nimport { argon2idV13 } from '@cardanowall/crypto-core/kdf';\nimport { xchacha20Poly1305Decrypt, AeadVerificationError } from '@cardanowall/crypto-core/aead';\nimport { blake2b256, sha256 } from '@cardanowall/crypto-core/hash';\nimport {\n eciesSealedPoeUnwrap,\n sealedEnvelopeFromParsed,\n} from '@cardanowall/crypto-core/sealed-poe';\nimport { compareCt } from '@cardanowall/crypto-core/util';\nimport type { ItemEntry, PoeRecord } from '@cardanowall/poe-standard';\n\nimport { fetchItemCiphertext } from './fetch';\nimport type {\n DecryptionVerdict,\n FetchOutbound,\n HttpCallRecord,\n VerifyItemDecryption,\n VerifyTxInput,\n VerifyUriCheck,\n} from './types';\n\n// The v1 passphrase KDF registry has a single member.\nconst PASSPHRASE_KDF_ARGON2ID = 'argon2id' as const;\n\n// Content-AEAD AAD is an empty bstr on the passphrase path.\nconst EMPTY_AAD = new Uint8Array(0);\n\nexport interface TryDecryptionsArgs {\n readonly record: PoeRecord;\n readonly input: VerifyTxInput;\n readonly fetchFn: FetchOutbound;\n readonly httpCalls: HttpCallRecord[];\n readonly uriChecksOut: VerifyUriCheck[];\n // When `false`, the verifier is running offline: it MUST NOT fetch a sealed\n // item's on-record `uris[]` ciphertext. Decryption then succeeds only for\n // items whose ciphertext the caller supplied out-of-band (`ciphertextBytes`);\n // others surface as `ciphertext-unavailable` with no outbound egress.\n readonly allowUriFetch: boolean;\n}\n\nexport interface TryDecryptionsResult {\n readonly results: VerifyItemDecryption[];\n}\n\nexport async function tryDecryptions(args: TryDecryptionsArgs): Promise<TryDecryptionsResult> {\n const { record, input } = args;\n const items = (record.items ?? []) as ItemEntry[];\n const out: VerifyItemDecryption[] = [];\n const reqs = input.decryption ?? [];\n\n for (const req of reqs) {\n const idx = req.itemIndex;\n if (!Number.isInteger(idx) || idx < 0 || idx >= items.length) {\n out.push({\n item_index: idx,\n verdict: 'no-enc-envelope',\n reason: 'itemIndex out of range',\n });\n continue;\n }\n const item = items[idx]!;\n const enc = item.enc as unknown;\n if (enc === undefined || enc === null || typeof enc !== 'object') {\n out.push({ item_index: idx, verdict: 'no-enc-envelope' });\n continue;\n }\n const encShape = enc as {\n readonly slots?: unknown;\n readonly passphrase?: unknown;\n };\n const hasSlots = Array.isArray(encShape.slots);\n const hasPassphrase = encShape.passphrase !== undefined && encShape.passphrase !== null;\n const reqHasSecret = 'recipientSecretKey' in req;\n const reqHasPassphrase = 'passphrase' in req;\n if (hasSlots && !reqHasSecret) {\n out.push({\n item_index: idx,\n verdict: 'wrong-input-shape',\n reason: 'WRONG_DECRYPTION_INPUT_SHAPE',\n });\n continue;\n }\n if (hasPassphrase && !reqHasPassphrase) {\n out.push({\n item_index: idx,\n verdict: 'wrong-input-shape',\n reason: 'WRONG_DECRYPTION_INPUT_SHAPE',\n });\n continue;\n }\n\n // Ciphertext acquisition: out-of-band bytes first, then (when fetching is\n // allowed) on-record `item.uris[]`, then `CIPHERTEXT_UNAVAILABLE`. Offline\n // mode (`allowUriFetch === false`) never reaches the network branch.\n const oobBytes = input.ciphertextBytes?.[idx];\n let ciphertext: Uint8Array | null;\n if (oobBytes !== undefined) {\n ciphertext = oobBytes;\n } else if (args.allowUriFetch && Array.isArray(item.uris) && item.uris.length > 0) {\n try {\n ciphertext = await fetchItemCiphertext({\n uris: item.uris as ReadonlyArray<ReadonlyArray<string>>,\n arweaveGateways: input.arweaveGatewayChain,\n ipfsGateways: input.ipfsGatewayChain,\n fetchFn: args.fetchFn,\n uriChecksOut: args.uriChecksOut,\n itemIndex: idx,\n });\n } catch (e) {\n const code = e instanceof Error ? e.message : 'CONTENT_UNAVAILABLE';\n const verdict: DecryptionVerdict =\n code === 'URI_TARGET_FORBIDDEN' ? 'ciphertext-unavailable' : 'content-unavailable';\n out.push({ item_index: idx, verdict, reason: code });\n continue;\n }\n } else {\n out.push({\n item_index: idx,\n verdict: 'ciphertext-unavailable',\n reason: 'CIPHERTEXT_UNAVAILABLE',\n });\n continue;\n }\n if (ciphertext === null) {\n out.push({\n item_index: idx,\n verdict: 'ciphertext-unavailable',\n reason: 'CIPHERTEXT_UNAVAILABLE',\n });\n continue;\n }\n\n let plaintext: Uint8Array | null = null;\n let failure: { verdict: DecryptionVerdict; reason: string } | null = null;\n if (reqHasSecret) {\n // Build the discriminated SealedEnvelope from the on-wire `enc` block,\n // dispatching on `enc.kem` (classical `{epk, wrap}` vs hybrid\n // `{kem_ct, wrap}`). A null result means the envelope isn't a sealed\n // recipient envelope we can unwrap — surface it as wrong-input-shape.\n const envelope = sealedEnvelopeFromParsed(\n enc as Parameters<typeof sealedEnvelopeFromParsed>[0],\n );\n if (envelope === null) {\n out.push({\n item_index: idx,\n verdict: 'wrong-input-shape',\n reason: 'WRONG_DECRYPTION_INPUT_SHAPE',\n });\n continue;\n }\n // ECIES sealed-PoE unwrap. The single-priv standalone-verifier form takes\n // the one secret matching the envelope's KEM (X25519 priv for classical,\n // X-Wing secret seed for hybrid); the per-slot loop inside dispatches on\n // `envelope.kem`. The helper returns a discriminated result — never throws\n // on auth failure.\n const unwrap = eciesSealedPoeUnwrap({\n envelope,\n ciphertext,\n recipientSecretKey: (req as { recipientSecretKey: Uint8Array }).recipientSecretKey,\n });\n if (unwrap.matched) {\n plaintext = unwrap.plaintext;\n } else {\n const map: Record<string, { verdict: DecryptionVerdict; reason: string }> = {\n WRONG_RECIPIENT_KEY: { verdict: 'wrong-key', reason: 'WRONG_RECIPIENT_KEY' },\n TAMPERED_HEADER: { verdict: 'tampered-header', reason: 'TAMPERED_HEADER' },\n TAMPERED_CIPHERTEXT: { verdict: 'tampered-ciphertext', reason: 'TAMPERED_CIPHERTEXT' },\n };\n failure = map[unwrap.reason] ?? {\n verdict: 'tampered-ciphertext',\n reason: 'TAMPERED_CIPHERTEXT',\n };\n }\n } else {\n try {\n plaintext = await decryptPassphrase({\n enc: enc as PassphraseEncEnvelope,\n ciphertext,\n passphrase: (req as { passphrase: string }).passphrase,\n });\n } catch (e) {\n if (e instanceof AeadVerificationError) {\n failure = { verdict: 'tampered-ciphertext', reason: 'TAMPERED_CIPHERTEXT' };\n } else if (e instanceof Error && e.message.startsWith('KDF_')) {\n failure = { verdict: 'kdf-failed', reason: e.message };\n } else {\n failure = {\n verdict: 'tampered-ciphertext',\n reason: e instanceof Error ? e.message : 'TAMPERED_CIPHERTEXT',\n };\n }\n }\n }\n\n if (failure !== null) {\n out.push({ item_index: idx, verdict: failure.verdict, reason: failure.reason });\n continue;\n }\n if (plaintext === null) {\n // Defensive — failure path should already have returned above.\n out.push({ item_index: idx, verdict: 'tampered-ciphertext', reason: 'TAMPERED_CIPHERTEXT' });\n continue;\n }\n\n // Post-unwrap plaintext-hash recompute: re-hash the recovered plaintext\n // under every content-hash entry the item carries and compare. Every\n // `enc`-bearing item carries at least one content-hash entry (the\n // structural validator enforces ENC_REQUIRES_CONTENT_HASH), so this is a\n // concrete boolean on successful decryption.\n const plaintextHashOk = recomputeHashes(item, plaintext);\n out.push({ item_index: idx, verdict: 'decrypted', plaintext_hash_ok: plaintextHashOk });\n }\n\n return { results: out };\n}\n\ninterface PassphraseEncEnvelope {\n readonly scheme: number;\n readonly aead: string;\n readonly nonce: Uint8Array;\n readonly passphrase: {\n readonly alg: string;\n readonly salt: Uint8Array;\n readonly params: { readonly m: number; readonly t: number; readonly p: number };\n };\n}\n\nasync function decryptPassphrase(args: {\n enc: PassphraseEncEnvelope;\n ciphertext: Uint8Array;\n passphrase: string;\n}): Promise<Uint8Array> {\n const { enc, ciphertext, passphrase } = args;\n if (enc.passphrase.alg !== PASSPHRASE_KDF_ARGON2ID) {\n throw new Error(`KDF_DERIVATION_FAILED: unsupported passphrase alg ${enc.passphrase.alg}`);\n }\n // Passphrase normalisation: NFKC → collapse whitespace → trim → UTF-8. Must\n // match the producer's normalisation exactly or the derived CEK won't match.\n const normalised = passphrase.normalize('NFKC').replace(/\\s+/g, ' ').trim();\n const password = new TextEncoder().encode(normalised);\n let cek: Uint8Array;\n try {\n cek = await argon2idV13({\n password,\n salt: enc.passphrase.salt,\n memSizeKB: enc.passphrase.params.m,\n iterations: enc.passphrase.params.t,\n parallelism: enc.passphrase.params.p,\n outBytes: 32,\n });\n } catch (cause) {\n const reason = cause instanceof Error ? cause.message : String(cause);\n throw new Error(`KDF_DERIVATION_FAILED: ${reason}`, { cause });\n }\n if (enc.aead !== 'xchacha20-poly1305') {\n throw new Error(`KDF_DERIVATION_FAILED: unsupported aead ${enc.aead}`);\n }\n return xchacha20Poly1305Decrypt({\n key: cek,\n nonce: enc.nonce,\n aad: EMPTY_AAD,\n ciphertext,\n });\n}\n\nfunction recomputeHashes(item: ItemEntry, plaintext: Uint8Array): boolean {\n // `item.hashes` is a text-keyed map of algorithm id → expected digest;\n // cbor2 surfaces it as a plain JS object. The recovered plaintext is\n // \"hash-ok\" only when there is at least one entry AND every entry names a\n // hash we can recompute AND its digest matches. An empty map, or any entry\n // whose alg we don't recognise, is NOT silently treated as a pass: returning\n // `true` there would vacuously certify ciphertext whose integrity we never\n // actually checked. (Mirrors the CLI's `recomputeItemHashes`, which returns\n // `UNSUPPORTED_HASH_ALG` on an unknown alg.)\n const entries = Object.entries(item.hashes);\n if (entries.length === 0) return false;\n for (const [alg, digest] of entries) {\n if (alg === 'sha2-256') {\n if (!compareCt(sha256(plaintext), digest)) return false;\n } else if (alg === 'blake2b-256') {\n if (!compareCt(blake2b256(plaintext), digest)) return false;\n } else {\n // Unknown/unsupported hash alg — cannot certify integrity.\n return false;\n }\n }\n return true;\n}\n","// Canonical-CBOR codec for the off-chain Merkle leaves-list artefact.\n// The on-chain `merkle[]` field binds to this file via `uris[]` / `leaf_count`;\n// the file itself carries the full leaf set. Canonical CBOR is RFC 8949 §4.2.1.\n//\n// CDDL:\n//\n// leaves-list = {\n// \"format\": \"cardano-poe-merkle-leaves-v1\",\n// \"tree_alg\": \"rfc9162-sha256\",\n// \"root\": bytes .size 32,\n// \"leaves\": [ + bytes .size 32 ],\n// \"leaf_count\": uint,\n// ? \"leaf_alg\": tstr,\n// }\n//\n// Canonical ordering is bytewise-lexicographic on encoded map keys (RFC 8949\n// §4.2.1) so the wire-key order is fixed by `cde:true` regardless of insertion\n// order: root (4B) < format (6B) < leaves (6B) < leaf_alg (8B) < tree_alg (8B)\n// < leaf_count (10B).\n\nimport { decodeCanonicalCbor, encodeCanonicalCbor } from '../cbor/canonical';\nimport { compareCt } from '../util/compare-ct';\nimport { merkleSha2256Root } from '../hash/merkle-sha2-256';\n\nexport const LEAVES_LIST_FORMAT_V1 = 'cardano-poe-merkle-leaves-v1' as const;\nconst TREE_ALG_RFC9162 = 'rfc9162-sha256' as const;\nconst DIGEST_LENGTH = 32;\nconst REGISTERED_FORMATS = new Set<string>([LEAVES_LIST_FORMAT_V1]);\n\nexport type MerkleLeavesListErrorCode =\n | 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED'\n | 'SCHEMA_MERKLE_LEAVES_MALFORMED'\n | 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH'\n | 'MERKLE_ROOT_MISMATCH';\n\nexport class MerkleLeavesListError extends Error {\n readonly code: MerkleLeavesListErrorCode;\n constructor(code: MerkleLeavesListErrorCode, message?: string) {\n super(message ? `${code}: ${message}` : code);\n this.code = code;\n this.name = 'MerkleLeavesListError';\n }\n}\n\nexport interface EncodeLeavesListArgs {\n readonly leaves: ReadonlyArray<Uint8Array>;\n readonly root: Uint8Array;\n readonly leafAlg?: string;\n}\n\nexport interface DecodedLeavesList {\n readonly format: typeof LEAVES_LIST_FORMAT_V1;\n readonly treeAlg: typeof TREE_ALG_RFC9162;\n readonly root: Uint8Array;\n readonly leaves: Uint8Array[];\n readonly leafCount: number;\n readonly leafAlg?: string;\n}\n\nexport function encodeLeavesList(args: EncodeLeavesListArgs): Uint8Array {\n if (!(args.root instanceof Uint8Array) || args.root.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `root must be a Uint8Array(${DIGEST_LENGTH})`,\n );\n }\n if (args.leaves.length < 1) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaves array must be non-empty',\n );\n }\n const leavesCopy: Uint8Array[] = [];\n for (let i = 0; i < args.leaves.length; i++) {\n const leaf = args.leaves[i];\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `leaves[${i}] must be a Uint8Array(${DIGEST_LENGTH})`,\n );\n }\n leavesCopy.push(leaf);\n }\n if (args.leafAlg !== undefined && typeof args.leafAlg !== 'string') {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_alg must be a string when present',\n );\n }\n const map: Record<string, unknown> = {\n format: LEAVES_LIST_FORMAT_V1,\n tree_alg: TREE_ALG_RFC9162,\n root: args.root,\n leaves: leavesCopy,\n leaf_count: leavesCopy.length,\n };\n if (args.leafAlg !== undefined) {\n map['leaf_alg'] = args.leafAlg;\n }\n return encodeCanonicalCbor(map as never);\n}\n\nexport function decodeLeavesList(bytes: Uint8Array): DecodedLeavesList {\n const decoded = decodeCanonicalCbor(bytes);\n if (typeof decoded !== 'object' || decoded === null || Array.isArray(decoded)) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaves-list MUST be a CBOR map',\n );\n }\n const m = decoded as Record<string, unknown>;\n\n const format = m['format'];\n if (typeof format !== 'string') {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'format must be a text string',\n );\n }\n if (!REGISTERED_FORMATS.has(format)) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED',\n `format '${format}' is not in the registered set`,\n );\n }\n\n const treeAlg = m['tree_alg'];\n if (treeAlg !== TREE_ALG_RFC9162) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `tree_alg '${String(treeAlg)}' is not '${TREE_ALG_RFC9162}'`,\n );\n }\n\n const root = m['root'];\n if (!(root instanceof Uint8Array) || root.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `root must be a ${DIGEST_LENGTH}-byte byte string`,\n );\n }\n\n const leavesRaw = m['leaves'];\n if (!Array.isArray(leavesRaw) || leavesRaw.length < 1) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaves must be a non-empty array',\n );\n }\n const leaves: Uint8Array[] = [];\n for (let i = 0; i < leavesRaw.length; i++) {\n const leaf = leavesRaw[i];\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `leaves[${i}] must be a ${DIGEST_LENGTH}-byte byte string`,\n );\n }\n leaves.push(leaf);\n }\n\n const leafCountRaw = m['leaf_count'];\n let leafCount: number;\n if (typeof leafCountRaw === 'number' && Number.isInteger(leafCountRaw) && leafCountRaw >= 0) {\n leafCount = leafCountRaw;\n } else if (typeof leafCountRaw === 'bigint' && leafCountRaw >= 0n) {\n if (leafCountRaw > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_count exceeds Number.MAX_SAFE_INTEGER',\n );\n }\n leafCount = Number(leafCountRaw);\n } else {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_count must be a non-negative CBOR uint',\n );\n }\n if (leaves.length !== leafCount) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n `leaves.length (${leaves.length}) != leaf_count (${leafCount})`,\n );\n }\n\n let leafAlg: string | undefined;\n if (m['leaf_alg'] !== undefined) {\n if (typeof m['leaf_alg'] !== 'string') {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_alg must be a text string when present',\n );\n }\n leafAlg = m['leaf_alg'];\n }\n\n const recomputed = merkleSha2256Root(leaves);\n if (!compareCt(recomputed, root)) {\n throw new MerkleLeavesListError(\n 'MERKLE_ROOT_MISMATCH',\n 'leaves recompute does not match declared root',\n );\n }\n\n const out: DecodedLeavesList = {\n format: LEAVES_LIST_FORMAT_V1,\n treeAlg: TREE_ALG_RFC9162,\n root,\n leaves,\n leafCount,\n ...(leafAlg !== undefined ? { leafAlg } : {}),\n };\n return out;\n}\n","// Merkle list-commitment verification.\n//\n// For each `record.merkle[i]` the verifier:\n// 1. Acquires the leaves-list document (caller-supplied or fetched via the\n// first ar://-or-ipfs:// URI in `merkle[i].uris[]`).\n// 2. Decodes the normative CBOR leaves-list wire form via crypto-core's\n// `decodeLeavesList` (which also recomputes the canonical RFC 9162 root\n// defence-in-depth and surfaces `MERKLE_ROOT_MISMATCH` /\n// `SCHEMA_MERKLE_LEAF_COUNT_MISMATCH`).\n// 3. Compares the on-record `merkle[i].root` byte-exact to the recomputed\n// root via `compareCt`.\n//\n// Per-attempt URI failures are warnings (`URI_FETCH_FAILED`); the per-commit\n// verdict on chain-exhaustion is `MERKLE_LEAVES_UNAVAILABLE` — a warning, NOT\n// escalated to `'failed'`, because the on-chain root alone is structurally\n// valid.\n\nimport { merkleSha2256Root } from '@cardanowall/crypto-core/hash';\nimport { decodeLeavesList, MerkleLeavesListError } from '@cardanowall/crypto-core/merkle';\nimport { compareCt } from '@cardanowall/crypto-core/util';\nimport type { MerkleCommit, PoeRecord } from '@cardanowall/poe-standard';\n\nimport { fetchItemCiphertext } from './fetch';\nimport type { FetchOutbound, VerifyMerkleCheck, VerifyTxInput, VerifyUriCheck } from './types';\n\nexport interface VerifyMerkleArgs {\n readonly record: PoeRecord;\n readonly input: VerifyTxInput;\n readonly fetchFn: FetchOutbound;\n readonly uriChecksOut: VerifyUriCheck[];\n}\n\nexport interface VerifyMerkleResult {\n readonly checks: VerifyMerkleCheck[];\n}\n\nexport async function verifyMerkleCommitments(args: VerifyMerkleArgs): Promise<VerifyMerkleResult> {\n const merkleArr = (args.record.merkle ?? []) as MerkleCommit[];\n const out: VerifyMerkleCheck[] = [];\n for (let i = 0; i < merkleArr.length; i++) {\n out.push(await verifyOneCommit(i, merkleArr[i]!, args));\n }\n return { checks: out };\n}\n\nasync function verifyOneCommit(\n index: number,\n commit: MerkleCommit,\n args: VerifyMerkleArgs,\n): Promise<VerifyMerkleCheck> {\n // v1 registers exactly one Merkle commitment algorithm. The structural\n // validator already rejects unknown algs; this is defence-in-depth.\n if (commit.alg !== 'rfc9162-sha256') {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unsupported',\n reason: 'UNSUPPORTED_MERKLE_COMMIT_ALG',\n };\n }\n\n // Leaves-list acquisition: caller-supplied bytes first, then the first\n // ar://-or-ipfs:// URI in `merkle[i].uris[]`.\n let leavesBytes: Uint8Array | null = args.input.merkleLeaves?.[index] ?? null;\n if (leavesBytes === null) {\n const uris = commit.uris;\n if (uris === undefined || uris.length === 0) {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unavailable',\n reason: 'MERKLE_LEAVES_UNAVAILABLE',\n };\n }\n try {\n leavesBytes = await fetchItemCiphertext({\n uris,\n arweaveGateways: args.input.arweaveGatewayChain,\n ipfsGateways: args.input.ipfsGatewayChain,\n fetchFn: args.fetchFn,\n uriChecksOut: args.uriChecksOut,\n // Merkle commits are not item-indexed; reuse a sentinel index so\n // downstream UIs can distinguish them from item URIs.\n itemIndex: -1 - index,\n });\n } catch {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unavailable',\n reason: 'MERKLE_LEAVES_UNAVAILABLE',\n };\n }\n }\n\n // Decode the leaves-list document. `decodeLeavesList` enforces format,\n // tree_alg, leaf-count match, and recomputes the root for defence-in-depth;\n // any failure surfaces as a typed error code.\n try {\n const decoded = decodeLeavesList(leavesBytes);\n // Compare the on-record root to the recomputed root byte-exact.\n const recomputed = merkleSha2256Root(decoded.leaves);\n if (!compareCt(recomputed, commit.root)) {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'mismatch',\n reason: 'MERKLE_ROOT_MISMATCH',\n root_recomputed: recomputed,\n };\n }\n if (decoded.leafCount !== commit.leaf_count) {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'mismatch',\n reason: 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n };\n }\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'valid',\n root_recomputed: recomputed,\n };\n } catch (e) {\n if (e instanceof MerkleLeavesListError) {\n if (e.code === 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED') {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'format-unsupported',\n reason: 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED',\n };\n }\n if (e.code === 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH') {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'mismatch',\n reason: 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n };\n }\n if (e.code === 'MERKLE_ROOT_MISMATCH') {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'mismatch',\n reason: 'MERKLE_ROOT_MISMATCH',\n };\n }\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unavailable',\n reason: e.code,\n };\n }\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unavailable',\n reason: e instanceof Error ? e.message : String(e),\n };\n }\n}\n","// Conformance-profile helpers.\n//\n// A `core`-profile verifier reading a record that carries `sigs`, `enc`, or\n// `merkle` MUST emit `OUT_OF_PROFILE_SKIPPED` (info severity) per affected\n// field — NOT `SCHEMA_UNKNOWN_FIELD` (which applies only to fields outside\n// the v1 CDDL). This rule lets a block explorer shipping only the `core`\n// surface still surface every conformant v1 record regardless of which\n// extensions it carries.\n\nimport type { PoeRecord, ValidationIssue } from '@cardanowall/poe-standard';\n\nimport type { Profile } from './types';\nimport { PROFILE_RANK } from './types';\n\nexport const DEFAULT_PROFILE: Profile = 'recipient-sealed';\n\nexport function profileImplements(actual: Profile, required: Profile): boolean {\n return PROFILE_RANK[actual] >= PROFILE_RANK[required];\n}\n\nexport interface ProfileSkipsResult {\n // info-severity entries emitted when a field belongs to a higher profile\n // than the active one. Surfaces in `validation.info`.\n readonly skips: ValidationIssue[];\n // Convenience flags for the verifier pipeline (whether to enter each\n // sub-pipeline at all).\n readonly verifySignatures: boolean;\n readonly verifyDecrypt: boolean;\n}\n\n/**\n * Emit the minimum conformance profile a verifier MUST implement\n * to read this record end-to-end. The profiles form a strict superset chain\n * `core ⊂ signed ⊂ sealed ⊂ recipient-sealed`.\n *\n * The function classifies based on RECORD CONTENT only:\n * - `'core'` — no signatures, no sealed items.\n * - `'signed'` — `record.sigs[]` is present, no sealed items.\n * - `'sealed'` — any `record.items[i].enc` is present (with or without sigs).\n *\n * The function does NOT return `'recipient-sealed'`: that profile is about\n * VERIFIER CAPABILITY (whether the verifier decrypts with a recipient X25519\n * key), not about record content. A separate helper is required if a caller\n * needs to test whether a particular recipient key can unwrap any slot — see\n * `@cardanowall/crypto-core/sealed-poe` for that pathway.\n */\nexport function detectConformanceProfile(record: PoeRecord): 'core' | 'signed' | 'sealed' {\n const hasSealedItem =\n Array.isArray(record.items) && record.items.some((it) => it.enc !== undefined);\n if (hasSealedItem) return 'sealed';\n const hasSigs = Array.isArray(record.sigs) && record.sigs.length > 0;\n if (hasSigs) return 'signed';\n return 'core';\n}\n\nexport function planProfileSkips(profile: Profile, record: PoeRecord): ProfileSkipsResult {\n const skips: ValidationIssue[] = [];\n const has = (k: string): boolean => Object.prototype.hasOwnProperty.call(record, k);\n const verifySignatures = PROFILE_RANK[profile] >= PROFILE_RANK['signed'];\n // The `sealed` rank gates whether the verifier reads the enc envelope at all.\n // There is no separate `sealed`-only sub-pipeline distinct from decryption,\n // so this drives only the skip-emission below rather than a returned flag.\n const readsEnc = PROFILE_RANK[profile] >= PROFILE_RANK['sealed'];\n const verifyDecrypt = PROFILE_RANK[profile] >= PROFILE_RANK['recipient-sealed'];\n\n if (!verifySignatures && has('sigs')) {\n skips.push({\n code: 'OUT_OF_PROFILE_SKIPPED',\n path: ['sigs'],\n message: `sigs[] requires profile >= 'signed'; active profile is '${profile}'`,\n severity: 'info',\n });\n }\n if (!readsEnc && Array.isArray(record.items) && record.items.some((it) => it.enc !== undefined)) {\n skips.push({\n code: 'OUT_OF_PROFILE_SKIPPED',\n path: ['items', 'enc'],\n message: `items[].enc requires profile >= 'sealed'; active profile is '${profile}'`,\n severity: 'info',\n });\n }\n return { skips, verifySignatures, verifyDecrypt };\n}\n","// Position-aware CBOR walker for byte-faithful label-309 metadata extraction.\n//\n// The verifier MUST fetch raw transaction CBOR and extract the label-309\n// value VERBATIM (not via decode-then-re-encode). A\n// re-encode pass would silently launder a non-conformant on-chain record into\n// a conformant one because cbor2's decoder normalises non-canonical input\n// (sorts map keys, collapses indefinite-length encodings, etc.); the\n// structural validator's canonical-CBOR check (`decodeCanonicalCbor` +\n// cbor2 CDE options) only catches the violation if it sees the producer's\n// original bytes.\n//\n// Pure stdlib walker (no `cbor2` dependency for the slicing path). Rejects\n// indefinite-length encodings, which canonical CBOR forbids; the structural\n// validator downstream performs the rest of the deterministic-encoding checks.\n\ninterface CborHead {\n readonly mt: number;\n readonly ai: number;\n readonly payloadStart: number;\n readonly valueU64: number;\n}\n\nfunction readHead(bytes: Uint8Array, pos: number): CborHead {\n if (pos >= bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated input (no head byte)');\n }\n const head = bytes[pos]!;\n const mt = head >> 5;\n const ai = head & 0x1f;\n let p = pos + 1;\n let valueU64: number;\n\n if (ai < 24) {\n valueU64 = ai;\n } else if (ai === 24) {\n if (p + 1 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 1-byte argument');\n }\n valueU64 = bytes[p]!;\n p += 1;\n } else if (ai === 25) {\n if (p + 2 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 2-byte argument');\n }\n valueU64 = (bytes[p]! << 8) | bytes[p + 1]!;\n p += 2;\n } else if (ai === 26) {\n if (p + 4 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 4-byte argument');\n }\n valueU64 =\n bytes[p]! * 0x1000000 + ((bytes[p + 1]! << 16) | (bytes[p + 2]! << 8) | bytes[p + 3]!);\n p += 4;\n } else if (ai === 27) {\n if (p + 8 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 8-byte argument');\n }\n let n = 0;\n for (let k = 0; k < 8; k++) n = n * 256 + bytes[p + k]!;\n if (n > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('MALFORMED_CBOR: 8-byte argument exceeds JavaScript safe integer range');\n }\n valueU64 = n;\n p += 8;\n } else if (ai === 31) {\n throw new RangeError(\n 'MALFORMED_CBOR: indefinite-length encoding (ai=31) not allowed under canonical CBOR',\n );\n } else {\n throw new RangeError(`MALFORMED_CBOR: reserved additional info ai=${ai}`);\n }\n\n return { mt, ai, payloadStart: p, valueU64 };\n}\n\nfunction skipCborItem(bytes: Uint8Array, pos: number): number {\n const h = readHead(bytes, pos);\n let p = h.payloadStart;\n switch (h.mt) {\n case 0:\n case 1:\n return p;\n case 2:\n case 3:\n if (p + h.valueU64 > bytes.length) {\n throw new RangeError(\n `MALFORMED_CBOR: truncated ${h.mt === 2 ? 'byte' : 'text'} string payload`,\n );\n }\n return p + h.valueU64;\n case 4:\n for (let i = 0; i < h.valueU64; i++) p = skipCborItem(bytes, p);\n return p;\n case 5:\n for (let i = 0; i < h.valueU64 * 2; i++) p = skipCborItem(bytes, p);\n return p;\n case 6:\n return skipCborItem(bytes, p);\n case 7: {\n if (h.ai < 24) return p;\n if (h.ai === 24) {\n if (p + 1 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated simple value');\n }\n return p + 1;\n }\n if (h.ai === 25 || h.ai === 26 || h.ai === 27) return p;\n throw new RangeError(`MALFORMED_CBOR: unsupported major-7 ai=${h.ai}`);\n }\n default:\n throw new RangeError(`MALFORMED_CBOR: unknown major type ${h.mt}`);\n }\n}\n\n// CBOR tag 259 wraps post-Alonzo auxiliary_data (CIP-29).\nconst CARDANO_AUX_DATA_TAG = 259;\nconst POE_LABEL = 309;\n\n/**\n * Byte-faithful components of a Cardano transaction, located by walking the\n * tx CBOR without a decode-then-re-encode pass.\n *\n * `txBody` and `witnessSet` are EXACT on-chain byte slices: `blake2b256(txBody)`\n * equals the transaction hash, and the witness set decodes to the vkey\n * witnesses that authorised the transaction. The slices are produced by the\n * same position-aware walk that finds label 309, so they never round-trip\n * through a CBOR re-encoder.\n *\n * `label309` is the reassembled label-309 value (chunked-bytes concatenated;\n * see `reassembleLabel309Value`), `null` when auxiliary_data is null/undefined\n * or label 309 is absent. `auxMetadataLabels` is the ascending-sorted list of\n * every integer key in the auxiliary metadata map (`[]` when aux is null).\n */\nexport interface TxComponents {\n readonly label309: Uint8Array | null;\n readonly txBody: Uint8Array;\n readonly witnessSet: Uint8Array;\n readonly auxMetadataLabels: number[];\n}\n\n/**\n * Walk the transaction CBOR once and return its byte-faithful components.\n *\n * Throws `RangeError(\"MALFORMED_CBOR: …\")` on structural violations. The body\n * and witness-set slices are the producer's ORIGINAL bytes; `label309` carries\n * the same byte-faithful guarantee `sliceLabel309Value` documents (no\n * decode-then-re-encode, so non-canonical encodings reach the structural\n * validator unchanged).\n */\nexport function sliceTxComponents(txCbor: Uint8Array): TxComponents {\n const txHead = readHead(txCbor, 0);\n if (txHead.mt !== 4) {\n throw new RangeError(`MALFORMED_CBOR: tx CBOR is not a CBOR array (major type ${txHead.mt})`);\n }\n if (txHead.valueU64 < 4) {\n throw new RangeError(\n `MALFORMED_CBOR: tx CBOR array has ${txHead.valueU64} elements; expected >= 4 (post-Conway: [body, witness_set, is_valid, auxiliary_data])`,\n );\n }\n\n const bodyStart = txHead.payloadStart;\n const bodyEnd = skipCborItem(txCbor, bodyStart);\n const witnessSetStart = bodyEnd;\n const witnessSetEnd = skipCborItem(txCbor, witnessSetStart);\n const pos = skipCborItem(txCbor, witnessSetEnd); // skip is_valid\n\n const txBody = txCbor.slice(bodyStart, bodyEnd);\n const witnessSet = txCbor.slice(witnessSetStart, witnessSetEnd);\n\n if (pos >= txCbor.length) {\n throw new RangeError('MALFORMED_CBOR: truncated tx (auxiliary_data missing)');\n }\n const auxFirstByte = txCbor[pos]!;\n if (auxFirstByte === 0xf6 || auxFirstByte === 0xf7) {\n return { label309: null, txBody, witnessSet, auxMetadataLabels: [] };\n }\n\n let auxMapPos = pos;\n const auxHead = readHead(txCbor, pos);\n if (auxHead.mt === 6) {\n if (auxHead.valueU64 !== CARDANO_AUX_DATA_TAG) {\n throw new RangeError(\n `MALFORMED_CBOR: auxiliary_data carries unexpected CBOR tag ${auxHead.valueU64}; expected ${CARDANO_AUX_DATA_TAG} or bare map`,\n );\n }\n auxMapPos = auxHead.payloadStart;\n }\n\n const mapHead = readHead(txCbor, auxMapPos);\n if (mapHead.mt !== 5) {\n throw new RangeError(\n `MALFORMED_CBOR: auxiliary_data is not a CBOR map (major type ${mapHead.mt})`,\n );\n }\n\n // Disambiguate the tagged (post-Alonzo, `{0 → metadata, 1 → ...}`) and bare\n // (pre-Alonzo, the map IS the metadata map directly) auxiliary_data shapes\n // by walking the map keys: if any int key in `{0,1,2,3}` is present, treat\n // it as the post-Alonzo shape and find key 0; else treat the whole map as\n // metadata directly. Modern Cardano txs (Conway+) are always tag-259\n // wrapped, but synthetic test fixtures often emit the post-Alonzo shape\n // bare and we want to handle both without forcing producers to add the tag.\n let metadataMapPos: number | null;\n {\n let entryPos = mapHead.payloadStart;\n let sawAuxKey = false;\n let foundMetadataAt: number | null = null;\n for (let i = 0; i < mapHead.valueU64; i++) {\n const keyHead = readHead(txCbor, entryPos);\n if (keyHead.mt === 0 && keyHead.valueU64 <= 3) {\n sawAuxKey = true;\n if (keyHead.valueU64 === 0) {\n foundMetadataAt = keyHead.payloadStart;\n }\n }\n entryPos = skipCborItem(txCbor, entryPos); // skip key\n entryPos = skipCborItem(txCbor, entryPos); // skip value\n }\n if (sawAuxKey || auxHead.mt === 6) {\n metadataMapPos = foundMetadataAt;\n } else {\n // Bare pre-Alonzo metadata map.\n metadataMapPos = auxMapPos;\n }\n }\n\n if (metadataMapPos === null) {\n return { label309: null, txBody, witnessSet, auxMetadataLabels: [] };\n }\n\n const metaHead = readHead(txCbor, metadataMapPos);\n if (metaHead.mt !== 5) {\n throw new RangeError(`MALFORMED_CBOR: metadata is not a CBOR map (major type ${metaHead.mt})`);\n }\n const labels: number[] = [];\n let label309: Uint8Array | null = null;\n let pairPos = metaHead.payloadStart;\n for (let i = 0; i < metaHead.valueU64; i++) {\n const keyHead = readHead(txCbor, pairPos);\n const keyVal = decodeIntKey(keyHead);\n labels.push(keyVal);\n const valueStart = skipCborItem(txCbor, pairPos);\n const valueEnd = skipCborItem(txCbor, valueStart);\n if (keyVal === POE_LABEL) {\n label309 = reassembleLabel309Value(txCbor, valueStart, valueEnd);\n }\n pairPos = valueEnd;\n }\n labels.sort((a, b) => a - b);\n return { label309, txBody, witnessSet, auxMetadataLabels: labels };\n}\n\n/**\n * Extract the byte slice corresponding to the value under metadata label 309.\n * Returns `null` when auxiliary_data is null/undefined or when label 309 is\n * absent. Throws `RangeError(\"MALFORMED_CBOR: …\")` on structural violations.\n *\n * Returns the producer's ORIGINAL on-chain bytes — no decode-then-re-encode\n * pass. The structural validator MUST receive these bytes verbatim so\n * non-canonical encodings surface as `MALFORMED_CBOR` rather than being\n * silently laundered.\n */\nexport function sliceLabel309Value(txCbor: Uint8Array): Uint8Array | null {\n return sliceTxComponents(txCbor).label309;\n}\n\n/**\n * Cardano caps individual metadata `bstr` / `tstr` values at 64 bytes\n * (Cardano metadata spec). A Label 309 PoE record's\n * canonical CBOR is typically several hundred bytes, so the producer emits\n * it as a `bytes-chunk-array` — `[ bstr .size (1..64), … ]` — at the\n * label-309 value position. The verifier MUST byte-concatenate the chunks\n * IN ORDER before passing the result to `validatePoeRecord`, otherwise\n * the canonical-CBOR decoder sees an outer CBOR array of byte strings\n * instead of the inner CBOR map and the record fails with\n * `SCHEMA_TYPE_MISMATCH` / `MALFORMED_CBOR`.\n *\n * Small records (≤ 64 bytes) MAY be emitted as a single `bstr` directly.\n * For backwards-compat we also accept a bare CBOR map value — older\n * producers and small synthetic fixtures use that shape.\n *\n * Returns the canonical-CBOR PoE record body (a `bstr`-free, map-rooted\n * byte sequence) ready for validation.\n */\nfunction reassembleLabel309Value(\n txCbor: Uint8Array,\n valueStart: number,\n valueEnd: number,\n): Uint8Array {\n const head = readHead(txCbor, valueStart);\n // Major type 4 = array → assume bytes-chunk-array; concatenate inner bstr items.\n if (head.mt === 4) {\n const out: Uint8Array[] = [];\n let totalLen = 0;\n let chunkPos = head.payloadStart;\n for (let i = 0; i < head.valueU64; i++) {\n const chunkHead = readHead(txCbor, chunkPos);\n if (chunkHead.mt !== 2) {\n throw new RangeError(\n `MALFORMED_CBOR: label-309 value is a CBOR array but element ${i} has major type ${chunkHead.mt}; expected byte string (chunked-bytes shape)`,\n );\n }\n const chunkValueStart = chunkHead.payloadStart;\n const chunkValueEnd = chunkValueStart + chunkHead.valueU64;\n out.push(txCbor.slice(chunkValueStart, chunkValueEnd));\n totalLen += chunkHead.valueU64;\n chunkPos = chunkValueEnd;\n }\n const concat = new Uint8Array(totalLen);\n let offset = 0;\n for (const c of out) {\n concat.set(c, offset);\n offset += c.length;\n }\n return concat;\n }\n // Major type 2 = single bstr value. The bstr CONTENTS are the canonical\n // CBOR record body — strip the bstr head so decodeCanonicalCbor sees the\n // map directly.\n if (head.mt === 2) {\n return txCbor.slice(head.payloadStart, head.payloadStart + head.valueU64);\n }\n // Major type 5 = map directly (bare-canonical shape; some synthetic\n // fixtures emit this when the record fits in one chunk and the producer\n // chose not to box it in a bstr). Pass through unchanged.\n if (head.mt === 5) {\n return txCbor.slice(valueStart, valueEnd);\n }\n throw new RangeError(\n `MALFORMED_CBOR: label-309 value has major type ${head.mt}; expected array (chunked), byte string, or map`,\n );\n}\n\nfunction decodeIntKey(h: CborHead): number {\n if (h.mt === 0) return h.valueU64;\n if (h.mt === 1) return -1 - h.valueU64;\n throw new RangeError(\n `MALFORMED_CBOR: metadata map key has major type ${h.mt}; expected unsigned integer`,\n );\n}\n","// Cardano gateway resolver — Koios first, then Blockfrost fallback if a\n// project ID is supplied. Returns the RAW on-chain transaction CBOR (NOT\n// the gateway's lossy JSON metadata projection — the verifier needs the\n// producer's original bytes to detect non-canonical encodings).\n\nimport { sliceLabel309Value } from './cbor-walker';\nimport type { FetchOutbound, VerifyTxInput } from './types';\n\nexport interface ResolvedTx {\n readonly txCbor: Uint8Array;\n readonly numConfirmations: number;\n readonly blockTime: number;\n readonly blockSlot: number;\n readonly provider: 'koios' | 'blockfrost';\n readonly providerUrl: string;\n}\n\nexport const KOIOS_MAINNET_URL = 'https://api.koios.rest/api/v1';\nexport const BLOCKFROST_MAINNET_HOST = 'https://cardano-mainnet.blockfrost.io/api/v0';\n\n// Distinct error class so the verifier can short-circuit the gateway-fallback\n// loop on a definitive \"this tx is not on chain / has no PoE metadata\"\n// response: a definitive negative from one gateway is authoritative, so there\n// is no point rotating to the next gateway.\nexport class NotALabel309RecordError extends Error {\n readonly code = 'METADATA_NOT_FOUND' as const;\n constructor(message: string) {\n super(message);\n this.name = 'NotALabel309RecordError';\n }\n}\n\nexport async function resolveCardanoTx(args: {\n readonly input: VerifyTxInput;\n readonly fetchFn: FetchOutbound;\n}): Promise<ResolvedTx> {\n const { input, fetchFn } = args;\n const koiosChain = input.cardanoGatewayChain ?? [KOIOS_MAINNET_URL];\n\n let lastErr: unknown;\n for (const koiosUrl of koiosChain) {\n try {\n return await resolveViaKoios(input.txHash, koiosUrl, fetchFn);\n } catch (e) {\n if (e instanceof NotALabel309RecordError) throw e;\n lastErr = e;\n }\n }\n\n if (input.blockfrostProjectId !== undefined) {\n try {\n return await resolveViaBlockfrost(input.txHash, input.blockfrostProjectId, fetchFn);\n } catch (e) {\n if (e instanceof NotALabel309RecordError) throw e;\n lastErr = e;\n }\n }\n\n throw new Error(`all_providers_failed: ${(lastErr as Error | undefined)?.message ?? 'unknown'}`);\n}\n\nasync function resolveViaKoios(\n txHash: string,\n koiosUrl: string,\n fetchFn: FetchOutbound,\n): Promise<ResolvedTx> {\n const cborRes = await fetchFn(`${koiosUrl}/tx_cbor`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ _tx_hashes: [txHash] }),\n purpose: 'cardano',\n });\n if (cborRes.status !== 200) {\n throw new Error(`koios_tx_cbor_${cborRes.status}`);\n }\n const cborJson = parseJson(cborRes.bytes);\n if (!Array.isArray(cborJson) || cborJson.length === 0) {\n throw new NotALabel309RecordError('koios returned empty array for tx_cbor; tx may not exist');\n }\n const cborEntry = cborJson[0] as { tx_hash?: unknown; cbor?: unknown };\n if (typeof cborEntry.cbor !== 'string') {\n throw new Error('koios_tx_cbor_missing_cbor_field');\n }\n if (\n typeof cborEntry.tx_hash === 'string' &&\n cborEntry.tx_hash.toLowerCase() !== txHash.toLowerCase()\n ) {\n throw new Error(`koios_tx_cbor_hash_mismatch: requested ${txHash} got ${cborEntry.tx_hash}`);\n }\n const txCbor = hexToBytes(cborEntry.cbor);\n\n const infoRes = await fetchFn(`${koiosUrl}/tx_info`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ _tx_hashes: [txHash] }),\n purpose: 'cardano',\n });\n if (infoRes.status !== 200) {\n throw new Error(`koios_tx_info_${infoRes.status}`);\n }\n const infoJson = parseJson(infoRes.bytes);\n if (!Array.isArray(infoJson) || infoJson.length === 0) {\n throw new NotALabel309RecordError('koios returned empty array for tx_info');\n }\n const infoEntry = infoJson[0] as {\n tx_hash?: unknown;\n num_confirmations?: unknown;\n block_height?: unknown;\n tx_timestamp?: unknown;\n absolute_slot?: unknown;\n };\n if (\n typeof infoEntry.tx_hash === 'string' &&\n infoEntry.tx_hash.toLowerCase() !== txHash.toLowerCase()\n ) {\n throw new Error(`koios_tx_info_hash_mismatch: requested ${txHash} got ${infoEntry.tx_hash}`);\n }\n\n // Koios v1 `/tx_info` no longer returns `num_confirmations` — only\n // `block_height` (verified live against `preprod.koios.rest/api/v1/tx_info`\n // and `api.koios.rest/api/v1/tx_info` on 2026-05-20: response keys do not\n // include num_confirmations). Compute manually as `tip - txBlockHeight + 1`,\n // mirroring the Blockfrost path. Fall back to a deprecated direct read of\n // `num_confirmations` for forward-compat against older Koios deployments.\n let numConfirmations: number;\n if (typeof infoEntry.num_confirmations === 'number') {\n numConfirmations = requireNonNegativeInt(infoEntry.num_confirmations, 'num_confirmations');\n } else {\n const txBlockHeight = requireNonNegativeInt(infoEntry.block_height, 'block_height');\n const tipRes = await fetchFn(`${koiosUrl}/tip`, {\n method: 'GET',\n headers: { accept: 'application/json' },\n purpose: 'cardano',\n });\n if (tipRes.status !== 200) {\n throw new Error(`koios_tip_${tipRes.status}`);\n }\n const tipJson = parseJson(tipRes.bytes);\n if (!Array.isArray(tipJson) || tipJson.length === 0) {\n throw new Error('koios_tip_empty');\n }\n const tipEntry = tipJson[0] as { block_height?: unknown };\n const tipHeight = requireNonNegativeInt(tipEntry.block_height, 'tip.block_height');\n numConfirmations = Math.max(0, tipHeight - txBlockHeight + 1);\n }\n\n return {\n txCbor,\n numConfirmations,\n blockTime: requireNonNegativeInt(infoEntry.tx_timestamp, 'tx_timestamp'),\n blockSlot: requireNonNegativeInt(infoEntry.absolute_slot, 'absolute_slot'),\n provider: 'koios',\n providerUrl: koiosUrl,\n };\n}\n\nasync function resolveViaBlockfrost(\n txHash: string,\n projectId: string,\n fetchFn: FetchOutbound,\n): Promise<ResolvedTx> {\n const base = BLOCKFROST_MAINNET_HOST;\n const headers = { project_id: projectId, accept: 'application/json' };\n\n const cborRes = await fetchFn(`${base}/txs/${txHash}/cbor`, {\n method: 'GET',\n headers,\n purpose: 'cardano',\n });\n if (cborRes.status !== 200) {\n throw new Error(`blockfrost_tx_cbor_${cborRes.status}`);\n }\n const cborJson = parseJson(cborRes.bytes) as { cbor?: unknown };\n if (typeof cborJson.cbor !== 'string') {\n throw new Error('blockfrost_tx_cbor_missing_cbor_field');\n }\n const txCbor = hexToBytes(cborJson.cbor);\n\n const txRes = await fetchFn(`${base}/txs/${txHash}`, {\n method: 'GET',\n headers,\n purpose: 'cardano',\n });\n if (txRes.status !== 200) {\n throw new Error(`blockfrost_tx_${txRes.status}`);\n }\n const txJson = parseJson(txRes.bytes) as {\n block_time?: unknown;\n slot?: unknown;\n block_height?: unknown;\n };\n const blockTime = requireNonNegativeInt(txJson.block_time, 'block_time');\n const txSlot = requireNonNegativeInt(txJson.slot, 'slot');\n // Confirmations are counted in BLOCKS, not slots. Cardano's active-slot\n // coefficient f=0.05 means only ~1 slot in 20 produces a block, so a\n // slot-difference count would inflate confirmations by ~20×. Blockfrost\n // returns `block_height` on `tx_content` and `height` on `/blocks/latest` —\n // both are the block-number field — so confirmations are\n // `tipHeight - blockHeight + 1`.\n const txBlockHeight = requireNonNegativeInt(txJson.block_height, 'block_height');\n\n const tipRes = await fetchFn(`${base}/blocks/latest`, {\n method: 'GET',\n headers,\n purpose: 'cardano',\n });\n if (tipRes.status !== 200) {\n throw new Error(`blockfrost_blocks_latest_${tipRes.status}`);\n }\n const tipJson = parseJson(tipRes.bytes) as { slot?: unknown; height?: unknown };\n const tipHeight = requireNonNegativeInt(tipJson.height, 'tip_height');\n const numConfirmations = Math.max(0, tipHeight - txBlockHeight + 1);\n\n return {\n txCbor,\n numConfirmations,\n blockTime,\n blockSlot: txSlot,\n provider: 'blockfrost',\n providerUrl: base,\n };\n}\n\n// Byte-faithful label-309 extraction (delegates to the position-aware\n// `cbor-walker`, which never decode-then-re-encodes).\nexport function extractLabel309Metadata(txCbor: Uint8Array): Uint8Array | null {\n return sliceLabel309Value(txCbor);\n}\n\nfunction parseJson(bytes: Uint8Array): unknown {\n return JSON.parse(new TextDecoder().decode(bytes));\n}\n\nfunction requireNonNegativeInt(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n throw new Error(`gateway_field_invalid: ${field} (got ${typeof value}=${String(value)})`);\n }\n return value;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const clean = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;\n if (clean.length % 2 !== 0) {\n throw new Error(`hex string has odd length (${clean.length})`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error('hex string contains non-hex characters');\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n","// Lowercase, no-`0x`-prefix hex encoder shared across the SDK. Single\n// implementation so the verifier, the wire serialiser, and the publish client\n// all emit byte-identical hex (the Python parity twin and the cross-language\n// fixtures depend on this exact form).\n\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n","// Label 309 record-level signature verifier.\n//\n// One verification per `record.sigs[i]`. v1 has NO per-item signature slot —\n// the only signature surface is the record-level array. Two on-wire signer-key\n// paths (mutually exclusive on the wire, enforced by the structural\n// validator as `SIG_ENTRY_KID_COSE_KEY_CONFLICT`):\n//\n// Path 1 — protected-header `kid` is exactly 32 bytes (raw Ed25519 pubkey).\n// Path 2 — `sigs[i].cose_key` is a chunked `cbor<COSE_Key>` blob carrying\n// the wallet's public key. The protected header carries a 29-byte\n// CIP-19 stake address at label `\"address\"`; the verifier\n// recomputes `address_derived = network_header || Blake2b-224(pub)`\n// and rejects on mismatch (`WALLET_ADDRESS_MISMATCH`).\n//\n// The signed-payload construction (`Sig_structure[3] = \"cardano-poe-record-sig-v1\" ||\n// canonicalCbor(record_body)`, `Sig_structure[2] = h''`) is enforced by the\n// `coseSign1Label309Verify` helper in `@cardanowall/crypto-core/cose` — this\n// verifier never sees the prefix directly.\n\nimport {\n bytesChunkArrayConcat,\n encodeRecordBodyForSigning,\n type PoeRecord,\n type SigEntry,\n} from '@cardanowall/poe-standard';\nimport {\n coseSign1Label309Verify,\n decodeCoseSign1,\n parseCoseKeyEd25519,\n type CoseSign1Decoded,\n} from '@cardanowall/crypto-core/cose';\nimport { blake2b224 } from '@cardanowall/crypto-core/hash';\nimport { compareCt } from '@cardanowall/crypto-core/util';\n\nimport { bytesToHex } from '../hex';\nimport type { SignatureFailureReason, VerifyRecordSignature, VerifyTxInput } from './types';\n\n// v1 wallet-path constraint: stake (reward) addresses only. The 29-byte CIP-19\n// layout is `network_header_byte || Blake2b-224(stake_vk)`. CIP-19\n// stake-address network bytes: mainnet = 0xe1, testnet = 0xe0 (preprod and\n// preview share the testnet header). Product policy is mainnet-only; the\n// preprod branch exists only so dev environments can replay records anchored\n// on preprod against the same standalone verifier.\nconst CARDANO_MAINNET_STAKE_NETWORK_BYTE = 0xe1;\nconst CARDANO_PREPROD_STAKE_NETWORK_BYTE = 0xe0;\nconst CARDANO_STAKE_ADDRESS_LENGTH = 29;\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\nconst BLAKE2B_224_LENGTH = 28;\n\nexport interface VerifyRecordSignaturesArgs {\n readonly record: PoeRecord;\n readonly input: VerifyTxInput;\n}\n\nexport async function verifyRecordSignatures(\n args: VerifyRecordSignaturesArgs,\n): Promise<VerifyRecordSignature[]> {\n const { record, input } = args;\n // The signed payload is canonical-CBOR(record_body), where record_body =\n // record minus `sigs`. We use the encoder helper to keep the wire shape and\n // key sort in lockstep with producer-side signing.\n const recordBodyCbor = encodeRecordBodyForSigning(record);\n const list = record.sigs ?? [];\n const out: VerifyRecordSignature[] = [];\n for (let i = 0; i < list.length; i++) {\n out.push(await verifyOneSig(i, list[i]!, recordBodyCbor, input));\n }\n return out;\n}\n\nasync function verifyOneSig(\n index: number,\n entry: SigEntry,\n recordBodyCbor: Uint8Array,\n input: VerifyTxInput,\n): Promise<VerifyRecordSignature> {\n const coseBytes = bytesChunkArrayConcat(entry.cose_sign1);\n let cose: CoseSign1Decoded;\n try {\n cose = decodeCoseSign1(coseBytes);\n } catch {\n return { index, verdict: 'invalid', reason: 'MALFORMED_SIG_COSE_SIGN1' };\n }\n\n // Resolve the signer's 32-byte Ed25519 pubkey (path 1 vs path 2).\n const resolved = resolveSignerKey(cose, entry);\n if (resolved.kind === 'unresolved') {\n return { index, verdict: 'unresolved', reason: 'SIGNER_KEY_UNRESOLVED' };\n }\n const { pub, signerType } = resolved;\n\n // Strict Ed25519 verify via the Label 309-pinned helper.\n const verifyResult = coseSign1Label309Verify({\n message: coseBytes,\n detachedRecordBodyCbor: recordBodyCbor,\n expectedSignerKey: pub,\n });\n\n if (!verifyResult.ok) {\n const reason = mapVerifyError(verifyResult.error.code);\n if (reason === 'SIGNATURE_UNSUPPORTED') {\n return {\n index,\n verdict: 'unsupported',\n signer_type: signerType,\n signer_pub: bytesToHex(pub),\n reason,\n };\n }\n return {\n index,\n verdict: 'invalid',\n signer_type: signerType,\n signer_pub: bytesToHex(pub),\n reason,\n };\n }\n\n // Path-2 wallet `address` ↔ `cose_key` binding. Path-1 entries skip this\n // check entirely.\n if (signerType === 'wallet-inline-key') {\n const addressOk = checkWalletAddressBinding(cose, pub, input);\n if (!addressOk) {\n return {\n index,\n verdict: 'invalid',\n signer_type: signerType,\n signer_pub: bytesToHex(pub),\n reason: 'WALLET_ADDRESS_MISMATCH',\n };\n }\n }\n\n return {\n index,\n verdict: 'valid',\n signer_type: signerType,\n signer_pub: bytesToHex(pub),\n };\n}\n\ninterface ResolvedPathOne {\n readonly kind: 'in-signature-kid';\n readonly pub: Uint8Array;\n readonly signerType: 'in-signature-kid';\n}\ninterface ResolvedPathTwo {\n readonly kind: 'wallet-inline-key';\n readonly pub: Uint8Array;\n readonly signerType: 'wallet-inline-key';\n}\ntype ResolvedKey = ResolvedPathOne | ResolvedPathTwo | { readonly kind: 'unresolved' };\n\nfunction resolveSignerKey(cose: CoseSign1Decoded, entry: SigEntry): ResolvedKey {\n // Path 1 — protected-header label 4 (`kid`) as the 32-byte raw Ed25519\n // pubkey. Unprotected-header `kid` values are NEVER consulted: they sit\n // outside the COSE integrity envelope and an attacker could rewrite them.\n const protectedKid = cose.protectedHeader.get(4) as unknown;\n if (\n protectedKid instanceof Uint8Array &&\n protectedKid.length === ED25519_PUBLIC_KEY_LENGTH &&\n entry.cose_key === undefined\n ) {\n return {\n kind: 'in-signature-kid',\n pub: protectedKid,\n signerType: 'in-signature-kid',\n };\n }\n // Path 2 — chunked `cbor<COSE_Key>` carrying the wallet pubkey.\n if (entry.cose_key !== undefined) {\n const blob = bytesChunkArrayConcat(entry.cose_key);\n const pub = parseCoseKeyEd25519(blob);\n if (pub !== null && pub.length === ED25519_PUBLIC_KEY_LENGTH) {\n return { kind: 'wallet-inline-key', pub, signerType: 'wallet-inline-key' };\n }\n }\n return { kind: 'unresolved' };\n}\n\nfunction mapVerifyError(code: string): SignatureFailureReason {\n switch (code) {\n case 'MALFORMED_SIG_COSE':\n case 'MALFORMED_SIG_COSE_SIGN1':\n return 'MALFORMED_SIG_COSE_SIGN1';\n case 'UNSUPPORTED_SIG_ALG':\n return 'SIGNATURE_UNSUPPORTED';\n case 'KID_UNRESOLVED':\n return 'SIGNER_KEY_UNRESOLVED';\n case 'SIGNATURE_INVALID':\n return 'SIGNATURE_INVALID';\n default:\n return 'SIGNATURE_INVALID';\n }\n}\n\n// Recompute the 29-byte stake address from the resolved Ed25519 pubkey and\n// compare it byte-exact (constant-time) to the path-2 protected-header\n// `address` field. The wallet path binds to stake (reward) addresses only in\n// v1 — base/enterprise/pointer/payment addresses are rejected (the recomputed\n// 29-byte stake address fails the equality check against any other\n// format/length).\nfunction checkWalletAddressBinding(\n cose: CoseSign1Decoded,\n pub: Uint8Array,\n input: VerifyTxInput,\n): boolean {\n const networkByte =\n (input.cardanoNetwork ?? 'mainnet') === 'preprod'\n ? CARDANO_PREPROD_STAKE_NETWORK_BYTE\n : CARDANO_MAINNET_STAKE_NETWORK_BYTE;\n const rawAddress = cose.protectedHeader.get('address') as unknown;\n if (!(rawAddress instanceof Uint8Array)) {\n // Address-less path-2 records are non-conformant with CIP-30 signData\n // (a wallet signature without an address claim cannot be safely surfaced\n // as wallet-bound). Treat as WALLET_ADDRESS_MISMATCH.\n return false;\n }\n if (rawAddress.length !== CARDANO_STAKE_ADDRESS_LENGTH) return false;\n if (rawAddress[0] !== networkByte) return false;\n const stakeKeyHash = blake2b224(pub);\n if (stakeKeyHash.length !== BLAKE2B_224_LENGTH) {\n // Defensive guard — `blake2b224` is byte-pinned to 28 bytes.\n return false;\n }\n const derived = new Uint8Array(CARDANO_STAKE_ADDRESS_LENGTH);\n derived[0] = networkByte;\n derived.set(stakeKeyHash, 1);\n return compareCt(derived, rawAddress);\n}\n","// Transaction-level decode for the Label 309 verifier.\n//\n// This module surfaces the Cardano TRANSACTION that carried a PoE record: which\n// wallet vkey(s) signed it, the fee, the outputs, and the co-published metadata\n// labels. It answers \"who authorised and paid for this anchoring\" — distinct\n// from the record-level COSE authorship signatures handled in `signatures.ts`.\n//\n// Unlike label-309 extraction, this decode is purely INFORMATIONAL: it is not\n// fed back into the structural validator, so it is not subject to the\n// canonical-CBOR byte-faithfulness concern that forces `cbor-walker` to slice\n// rather than decode. We therefore decode the body + witness-set slices with\n// the permissive CBOR decoder. The slices themselves are still byte-faithful —\n// `decodeTxWitnesses` verifies each signature against `blake2b256(txBody)`,\n// which only equals the on-chain transaction hash when the body bytes are\n// exactly as produced.\n\nimport { decodeCbor } from '@cardanowall/crypto-core/cbor';\nimport { blake2b224, blake2b256 } from '@cardanowall/crypto-core/hash';\nimport { verifyEd25519 } from '@cardanowall/crypto-core/sig';\n\nimport { bytesToHex } from '../hex';\nimport type { VerifyTxOutput, VerifyTxSummary, VerifyTxWitness } from './types';\n\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\nconst ED25519_SIGNATURE_LENGTH = 64;\n\n// Conway-era transaction body map keys (RFC-style integer keys).\nconst BODY_KEY_INPUTS = 0;\nconst BODY_KEY_OUTPUTS = 1;\nconst BODY_KEY_FEE = 2;\nconst BODY_KEY_INVALID_HEREAFTER = 3; // ttl\nconst BODY_KEY_INVALID_BEFORE = 8; // validity_interval_start\nconst BODY_KEY_REQUIRED_SIGNERS = 14;\nconst BODY_KEY_NETWORK_ID = 15;\n\n// Witness-set map keys. Key 0 is the vkey witness set; every other key\n// (native scripts, bootstrap witnesses, Plutus v1/v2/v3) is counted as a\n// \"script/other\" witness without being deep-decoded.\nconst WITNESS_KEY_VKEY = 0;\n\n// inputs, vkey_witnesses, and required_signers are CBOR sets (tag 258). The\n// permissive decoder may surface a set as a JS `Set` or an `Array` depending\n// on how the producer encoded it; normalise both to an array.\nfunction asArray(v: unknown): unknown[] {\n if (v instanceof Set) return [...v];\n if (Array.isArray(v)) return v;\n return [];\n}\n\nfunction asMap(v: unknown): Map<unknown, unknown> | null {\n return v instanceof Map ? v : null;\n}\n\n/**\n * Decode the vkey witnesses of a transaction and verify each signature against\n * the transaction body.\n *\n * Each Cardano vkey witness is `[vkey(32B), signature(64B)]`; the signed\n * message is `blake2b256(txBody)` (the transaction hash). A witness whose vkey\n * or signature is malformed, or whose signature does not verify, is reported\n * with `signature_valid: false` rather than dropped — the caller surfaces it\n * informationally and never fails the record on it.\n */\nexport function decodeTxWitnesses(\n witnessSetBytes: Uint8Array,\n txBodyBytes: Uint8Array,\n): VerifyTxWitness[] {\n const witnessSet = asMap(decodeCbor(witnessSetBytes));\n if (witnessSet === null) return [];\n const vkeyWitnesses = asArray(witnessSet.get(WITNESS_KEY_VKEY));\n const txHash = blake2b256(txBodyBytes);\n\n const out: VerifyTxWitness[] = [];\n for (const entry of vkeyWitnesses) {\n const pair = asArray(entry);\n const vkey = pair[0];\n const signature = pair[1];\n if (\n !(vkey instanceof Uint8Array) ||\n vkey.length !== ED25519_PUBLIC_KEY_LENGTH ||\n !(signature instanceof Uint8Array) ||\n signature.length !== ED25519_SIGNATURE_LENGTH\n ) {\n // A structurally malformed witness still describes an attempted\n // authorisation; surface what we can (when the vkey is a valid pubkey)\n // and mark the signature invalid.\n if (vkey instanceof Uint8Array && vkey.length === ED25519_PUBLIC_KEY_LENGTH) {\n out.push({\n type: 'vkey',\n vkey: bytesToHex(vkey),\n key_hash: bytesToHex(blake2b224(vkey)),\n signature_valid: false,\n });\n }\n continue;\n }\n let signatureValid: boolean;\n try {\n signatureValid = verifyEd25519({ publicKey: vkey, message: txHash, signature });\n } catch {\n signatureValid = false;\n }\n out.push({\n type: 'vkey',\n vkey: bytesToHex(vkey),\n key_hash: bytesToHex(blake2b224(vkey)),\n signature_valid: signatureValid,\n });\n }\n return out;\n}\n\n/**\n * Count the witness-set entries that are NOT vkey witnesses (native scripts,\n * bootstrap witnesses, Plutus v1/v2/v3). These are summed as a single\n * \"script/other\" count without deep-decoding their contents.\n */\nfunction countScriptWitnesses(witnessSetBytes: Uint8Array): number {\n const witnessSet = asMap(decodeCbor(witnessSetBytes));\n if (witnessSet === null) return 0;\n let count = 0;\n for (const [key, value] of witnessSet) {\n if (key === WITNESS_KEY_VKEY) continue;\n count += asArray(value).length;\n }\n return count;\n}\n\n/**\n * Decode a transaction body into a JSON-safe summary: fee, input/output counts,\n * the output addresses + lovelace amounts, validity interval, required signer\n * key hashes, and network id.\n *\n * All lovelace amounts are serialised as DECIMAL STRINGS so they survive JSON\n * round-trips exactly (Cardano coin values can exceed `Number.MAX_SAFE_INTEGER`\n * and BigInt is not JSON-native). Coin math is performed with BigInt internally.\n */\nexport function decodeTxSummary(\n txBodyBytes: Uint8Array,\n witnessSetBytes: Uint8Array,\n network: 'mainnet' | 'preprod',\n): VerifyTxSummary {\n const body = asMap(decodeCbor(txBodyBytes));\n if (body === null) {\n throw new RangeError('MALFORMED_CBOR: tx body is not a CBOR map');\n }\n\n const inputs = asArray(body.get(BODY_KEY_INPUTS));\n const outputsRaw = asArray(body.get(BODY_KEY_OUTPUTS));\n\n const outputs: VerifyTxOutput[] = [];\n let totalOutput = 0n;\n for (const o of outputsRaw) {\n const { addressBytes, lovelace } = readOutput(o);\n totalOutput += lovelace;\n outputs.push({\n address: encodeCardanoAddress(addressBytes, network),\n lovelace: lovelace.toString(),\n });\n }\n\n const requiredSigners = asArray(body.get(BODY_KEY_REQUIRED_SIGNERS))\n .filter((s): s is Uint8Array => s instanceof Uint8Array)\n .map((s) => bytesToHex(s));\n\n const summary: {\n -readonly [K in keyof VerifyTxSummary]: VerifyTxSummary[K];\n } = {\n fee_lovelace: coinToString(body.get(BODY_KEY_FEE)),\n input_count: inputs.length,\n output_count: outputs.length,\n outputs,\n total_output_lovelace: totalOutput.toString(),\n script_witness_count: countScriptWitnesses(witnessSetBytes),\n };\n\n const invalidBefore = body.get(BODY_KEY_INVALID_BEFORE);\n if (typeof invalidBefore === 'number') summary.invalid_before = invalidBefore;\n else if (typeof invalidBefore === 'bigint') summary.invalid_before = Number(invalidBefore);\n\n const invalidHereafter = body.get(BODY_KEY_INVALID_HEREAFTER);\n if (typeof invalidHereafter === 'number') summary.invalid_hereafter = invalidHereafter;\n else if (typeof invalidHereafter === 'bigint')\n summary.invalid_hereafter = Number(invalidHereafter);\n\n if (requiredSigners.length > 0) summary.required_signer_key_hashes = requiredSigners;\n\n const networkId = body.get(BODY_KEY_NETWORK_ID);\n if (typeof networkId === 'number') summary.network_id = networkId;\n else if (typeof networkId === 'bigint') summary.network_id = Number(networkId);\n\n return summary;\n}\n\n// A transaction output is EITHER a legacy array `[address, amount]` OR a map\n// `{0: address, 1: amount}` (post-Babbage). `amount` is either a bare coin\n// (uint) or a `[coin, multiasset]` pair — only the coin (lovelace) component is\n// summarised here.\nfunction readOutput(output: unknown): { addressBytes: Uint8Array; lovelace: bigint } {\n let address: unknown;\n let amount: unknown;\n if (Array.isArray(output)) {\n address = output[0];\n amount = output[1];\n } else if (output instanceof Map) {\n address = output.get(0);\n amount = output.get(1);\n } else {\n throw new RangeError('MALFORMED_CBOR: tx output is neither a CBOR array nor a CBOR map');\n }\n if (!(address instanceof Uint8Array)) {\n throw new RangeError('MALFORMED_CBOR: tx output address is not a byte string');\n }\n const lovelace = Array.isArray(amount) ? toBigInt(amount[0]) : toBigInt(amount);\n return { addressBytes: address, lovelace };\n}\n\nfunction coinToString(v: unknown): string {\n return toBigInt(v).toString();\n}\n\nfunction toBigInt(v: unknown): bigint {\n if (typeof v === 'bigint') return v;\n if (typeof v === 'number' && Number.isInteger(v)) return BigInt(v);\n throw new RangeError(`MALFORMED_CBOR: expected an integer coin value, got ${typeof v}`);\n}\n\n// -----------------------------------------------------------------------------\n// Cardano address bech32 encoding (BIP-173, the CIP-19 bech32 form).\n// -----------------------------------------------------------------------------\n//\n// Implemented inline so the published SDK keeps a minimal, auditable dependency\n// surface (the verifier's only third-party deps are the cryptographic core).\n// The header byte's high nibble is the address type and its low nibble is the\n// network id (0 = testnet, 1 = mainnet). Payment-address types 0–7 use the\n// `addr` HRP; stake/reward types 14–15 use the `stake` HRP. The header's\n// network nibble is authoritative for the `_test` suffix; the caller's\n// `network` argument is the fallback when a header is ambiguous.\n\nconst BECH32_CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';\n\nfunction encodeCardanoAddress(addressBytes: Uint8Array, network: 'mainnet' | 'preprod'): string {\n if (addressBytes.length === 0) {\n throw new RangeError('MALFORMED_CBOR: empty address byte string');\n }\n const header = addressBytes[0]!;\n const addressType = header >> 4;\n const networkNibble = header & 0x0f;\n const isStake = addressType === 14 || addressType === 15;\n // The header's network nibble is authoritative. Fall back to the caller's\n // network only when the nibble is not the canonical 0 (testnet) / 1 (mainnet).\n const isTestnet =\n networkNibble === 0 ? true : networkNibble === 1 ? false : network === 'preprod';\n const base = isStake ? 'stake' : 'addr';\n const hrp = isTestnet ? `${base}_test` : base;\n return bech32Encode(hrp, addressBytes);\n}\n\nfunction bech32Polymod(values: number[]): number {\n const generators = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n let chk = 1;\n for (const value of values) {\n const top = chk >> 25;\n chk = ((chk & 0x1ffffff) << 5) ^ value;\n for (let i = 0; i < 5; i++) {\n if ((top >> i) & 1) chk ^= generators[i]!;\n }\n }\n return chk;\n}\n\nfunction bech32HrpExpand(hrp: string): number[] {\n const out: number[] = [];\n for (let i = 0; i < hrp.length; i++) out.push(hrp.charCodeAt(i) >> 5);\n out.push(0);\n for (let i = 0; i < hrp.length; i++) out.push(hrp.charCodeAt(i) & 31);\n return out;\n}\n\n// 8-bit → 5-bit regrouping with zero-padding of the final group (the encode\n// direction always pads).\nfunction bech32ToWords(data: Uint8Array): number[] {\n let acc = 0;\n let bits = 0;\n const out: number[] = [];\n const maxv = (1 << 5) - 1;\n for (const value of data) {\n acc = (acc << 8) | value;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n out.push((acc >> bits) & maxv);\n }\n }\n if (bits > 0) out.push((acc << (5 - bits)) & maxv);\n return out;\n}\n\nfunction bech32Encode(hrp: string, data: Uint8Array): string {\n const words = bech32ToWords(data);\n const polymodInput = bech32HrpExpand(hrp).concat(words, [0, 0, 0, 0, 0, 0]);\n const polymod = bech32Polymod(polymodInput) ^ 1;\n const checksum: number[] = [];\n for (let i = 0; i < 6; i++) checksum.push((polymod >> (5 * (5 - i))) & 31);\n let result = `${hrp}1`;\n for (const w of words.concat(checksum)) result += BECH32_CHARSET.charAt(w);\n return result;\n}\n","// Label 309 standalone verifier entry point.\n//\n// Pipeline (steps run sequentially; the verdict is the worst outcome across them):\n// 1. Resolve Cardano gateway + raw tx CBOR + confirmation depth.\n// 2. Byte-faithful extract of label-309 metadata.\n// 3. Structural validator (Part A; never throws).\n// 4. Confirmation-depth check → INSUFFICIENT_CONFIRMATIONS / verdict 'pending'.\n// 5. Profile-gated work (signed: signatures; sealed: enc structure;\n// recipient-sealed: decrypt). Out-of-profile fields emit\n// OUT_OF_PROFILE_SKIPPED (info) — not SCHEMA_UNKNOWN_FIELD.\n// 6. Merkle list-commitment verification (awaited after step 5).\n// 7. Three-state verdict emission with exit-code mapping.\n\nimport { SEVERITY, validatePoeRecord, type ValidationIssue } from '@cardanowall/poe-standard';\n\nimport { tryDecryptions } from './decrypt';\nimport { defaultFetchOutbound, wrapFetchOutbound } from './fetch';\nimport { verifyMerkleCommitments } from './merkle';\nimport { DEFAULT_PROFILE, planProfileSkips } from './profile';\nimport { extractLabel309Metadata, NotALabel309RecordError, resolveCardanoTx } from './resolve';\nimport { verifyRecordSignatures } from './signatures';\nimport { sliceTxComponents } from './cbor-walker';\nimport { decodeTxSummary, decodeTxWitnesses } from './tx-witnesses';\nimport type {\n ExitCode,\n FetchOutbound,\n HttpCallRecord,\n Profile,\n VerifyItemDecryption,\n VerifyMerkleCheck,\n VerifyRecordSignature,\n VerifyReport,\n VerifyTxInput,\n VerifyUriCheck,\n Verdict,\n} from './types';\n\nexport const CONFIRMATION_DEPTH_THRESHOLD_DEFAULT = 15;\n\ntype MutableReport = { -readonly [K in keyof VerifyReport]: VerifyReport[K] };\n\nexport async function verifyTx(input: VerifyTxInput): Promise<VerifyReport> {\n const profile = input.profile ?? DEFAULT_PROFILE;\n const threshold = input.confirmationDepthThreshold ?? CONFIRMATION_DEPTH_THRESHOLD_DEFAULT;\n const httpCalls: HttpCallRecord[] = [];\n const fetchFn = wrapFetchOutbound(\n input.fetchOutbound ?? defaultFetchOutbound,\n httpCalls,\n input.denyHosts,\n );\n\n const base = (\n over: Partial<VerifyReport> & Pick<VerifyReport, 'verdict' | 'exit_code'>,\n ): VerifyReport => ({\n tx_hash: input.txHash,\n network: 'cardano:mainnet',\n profile,\n num_confirmations: 0,\n confirmation_depth_threshold: threshold,\n metadata_present: false,\n validation: { valid: false },\n http_calls: httpCalls,\n ...over,\n });\n\n // 1. Resolve Cardano gateway + raw tx CBOR.\n let resolved;\n try {\n resolved = await resolveCardanoTx({ input, fetchFn });\n } catch (e) {\n if (e instanceof NotALabel309RecordError) {\n return base({\n verdict: 'failed',\n exit_code: 1,\n validation: {\n valid: false,\n issues: [issueOf('METADATA_NOT_FOUND', [], e.message)],\n },\n });\n }\n return base({\n verdict: 'failed',\n exit_code: 2,\n validation: {\n valid: false,\n issues: [issueOf('PROVIDER_UNAVAILABLE', [], (e as Error).message)],\n },\n });\n }\n\n // 2. Byte-faithful label-309 extraction.\n let metadataBytes: Uint8Array | null;\n try {\n metadataBytes = extractLabel309Metadata(resolved.txCbor);\n } catch (e) {\n return base({\n verdict: 'failed',\n exit_code: 1,\n num_confirmations: resolved.numConfirmations,\n block_time: resolved.blockTime,\n block_slot: resolved.blockSlot,\n validation: {\n valid: false,\n issues: [issueOf('MALFORMED_CBOR', [], (e as Error).message)],\n },\n });\n }\n if (metadataBytes === null) {\n return base({\n verdict: 'failed',\n exit_code: 1,\n num_confirmations: resolved.numConfirmations,\n block_time: resolved.blockTime,\n block_slot: resolved.blockSlot,\n metadata_present: false,\n validation: {\n valid: false,\n issues: [issueOf('METADATA_NOT_FOUND', [], 'no label-309 metadata on this tx')],\n },\n });\n }\n\n return verifyResolvedRecord({\n input,\n metadataBytes,\n txCbor: resolved.txCbor,\n numConfirmations: resolved.numConfirmations,\n blockTime: resolved.blockTime,\n blockSlot: resolved.blockSlot,\n httpCalls,\n fetchFn,\n });\n}\n\n/**\n * `verifyResolved` — same pipeline as `verifyTx` starting from step 3\n * (structural validator). The caller has already resolved the label-309\n * metadata bytes + block-info tuple from somewhere other than a live chain\n * fetch (typically an indexer database mirror).\n *\n * Use this when you trust an upstream indexer for the (metadataCbor,\n * blockTime, blockSlot, numConfirmations) tuple and want to skip the\n * /tx_cbor + /tx_info round-trip. The caller is responsible for the\n * confidence that the supplied bytes actually came from the label-309\n * metadata field of a confirmed Cardano transaction.\n */\nexport async function verifyResolved(input: {\n txHash: string;\n metadataCbor: Uint8Array;\n // Raw on-chain transaction CBOR. When supplied, the report also carries the\n // transaction-level description (tx_witnesses, tx_summary, metadata_labels);\n // when absent, those three fields are left undefined. The label-309 record\n // is always taken from `metadataCbor`, never re-derived from `txCbor`.\n txCbor?: Uint8Array;\n numConfirmations: number;\n blockTime?: number;\n blockSlot?: number;\n network?: VerifyReport['network'];\n cardanoNetwork?: VerifyTxInput['cardanoNetwork'];\n profile?: Profile;\n confirmationDepthThreshold?: number;\n fetchOutbound?: FetchOutbound;\n denyHosts?: ReadonlyArray<string>;\n decryption?: VerifyTxInput['decryption'];\n // Mirrors `VerifyTxInput.verifyMerkle`. SSR callers pass `false` so the\n // viewer renders from indexed CBOR alone with no Arweave/IPFS leaves-list\n // fetch (deferred to a user-initiated client-side action instead).\n verifyMerkle?: boolean;\n}): Promise<VerifyReport> {\n const httpCalls: HttpCallRecord[] = [];\n const fetchFn = wrapFetchOutbound(\n input.fetchOutbound ?? defaultFetchOutbound,\n httpCalls,\n input.denyHosts,\n );\n // Reuse the post-resolve pipeline by adapting the caller's args back into\n // the VerifyTxInput shape that signature/decryption/merkle helpers expect.\n const verifyTxInput: VerifyTxInput = {\n txHash: input.txHash,\n ...(input.profile !== undefined ? { profile: input.profile } : {}),\n ...(input.cardanoNetwork !== undefined ? { cardanoNetwork: input.cardanoNetwork } : {}),\n ...(input.confirmationDepthThreshold !== undefined\n ? { confirmationDepthThreshold: input.confirmationDepthThreshold }\n : {}),\n ...(input.fetchOutbound !== undefined ? { fetchOutbound: input.fetchOutbound } : {}),\n ...(input.denyHosts !== undefined ? { denyHosts: input.denyHosts } : {}),\n ...(input.decryption !== undefined ? { decryption: input.decryption } : {}),\n ...(input.verifyMerkle !== undefined ? { verifyMerkle: input.verifyMerkle } : {}),\n };\n const report = await verifyResolvedRecord({\n input: verifyTxInput,\n metadataBytes: input.metadataCbor,\n ...(input.txCbor !== undefined ? { txCbor: input.txCbor } : {}),\n numConfirmations: input.numConfirmations,\n ...(input.blockTime !== undefined ? { blockTime: input.blockTime } : {}),\n ...(input.blockSlot !== undefined ? { blockSlot: input.blockSlot } : {}),\n httpCalls,\n fetchFn,\n });\n if (input.network !== undefined) {\n return { ...report, network: input.network };\n }\n return report;\n}\n\nasync function verifyResolvedRecord(args: {\n input: VerifyTxInput;\n metadataBytes: Uint8Array;\n txCbor?: Uint8Array;\n numConfirmations: number;\n blockTime?: number;\n blockSlot?: number;\n httpCalls: HttpCallRecord[];\n fetchFn: ReturnType<typeof wrapFetchOutbound>;\n}): Promise<VerifyReport> {\n const {\n input,\n metadataBytes,\n txCbor,\n numConfirmations,\n blockTime,\n blockSlot,\n httpCalls,\n fetchFn,\n } = args;\n const profile = input.profile ?? DEFAULT_PROFILE;\n const threshold = input.confirmationDepthThreshold ?? CONFIRMATION_DEPTH_THRESHOLD_DEFAULT;\n\n // Transaction-level description — who authorised/paid for the anchoring,\n // distinct from record-level authorship. Decoded once when the raw tx CBOR\n // is available, then merged into every report shape below. This is pure\n // description: it never gates on profile and never changes the verdict.\n const txDescription = txCbor !== undefined ? decodeTxDescription(txCbor, input) : {};\n\n const base = (\n over: Partial<VerifyReport> & Pick<VerifyReport, 'verdict' | 'exit_code'>,\n ): VerifyReport => ({\n tx_hash: input.txHash,\n network: 'cardano:mainnet',\n profile,\n num_confirmations: 0,\n confirmation_depth_threshold: threshold,\n metadata_present: false,\n validation: { valid: false },\n http_calls: httpCalls,\n ...txDescription,\n ...over,\n });\n\n // 3. Structural validator (Part A).\n const validation = validatePoeRecord(metadataBytes);\n if (!validation.ok) {\n return base({\n verdict: 'failed',\n exit_code: 1,\n num_confirmations: numConfirmations,\n ...(blockTime !== undefined ? { block_time: blockTime } : {}),\n ...(blockSlot !== undefined ? { block_slot: blockSlot } : {}),\n metadata_present: true,\n validation: { valid: false, issues: validation.issues },\n });\n }\n const record = validation.record;\n\n // 4. Confirmation-depth — a record below the reorg-safety threshold is\n // well-formed but not yet final, so INSUFFICIENT_CONFIRMATIONS short-circuits\n // to verdict `'pending'` (exit 3), NOT `'failed'`.\n if (numConfirmations < threshold) {\n return base({\n verdict: 'pending',\n exit_code: 3,\n num_confirmations: numConfirmations,\n ...(blockTime !== undefined ? { block_time: blockTime } : {}),\n ...(blockSlot !== undefined ? { block_slot: blockSlot } : {}),\n metadata_present: true,\n record,\n validation: {\n valid: false,\n issues: [\n issueOf('INSUFFICIENT_CONFIRMATIONS', [], `${numConfirmations} < threshold ${threshold}`),\n ],\n },\n });\n }\n\n // 5. Build optimistic report; mutate verdict on per-check failure.\n const initialWarnings = (validation.warnings ?? []).slice();\n const initialInfo = (validation.info ?? []).slice();\n const plan = planProfileSkips(profile, record);\n initialInfo.push(...plan.skips);\n\n // (Note: a `MERKLE_UNSUPPORTED` escalation — a verifier reading a\n // merkle-only record without implementing Merkle — never fires here because\n // this reference verifier always runs the Merkle subsystem at every profile.\n // A future `core - merkle` opt-out would emit MERKLE_UNSUPPORTED at info\n // severity when items[] also commits content, error severity otherwise.)\n\n const reportShape: VerifyReport = {\n tx_hash: input.txHash,\n network: 'cardano:mainnet',\n profile,\n num_confirmations: numConfirmations,\n confirmation_depth_threshold: threshold,\n ...(blockTime !== undefined ? { block_time: blockTime } : {}),\n ...(blockSlot !== undefined ? { block_slot: blockSlot } : {}),\n metadata_present: true,\n validation: composeValidation(true, undefined, initialWarnings, initialInfo),\n record,\n ...txDescription,\n http_calls: httpCalls,\n verdict: 'valid',\n exit_code: 0,\n };\n const report: MutableReport = { ...reportShape };\n const uriChecks: VerifyUriCheck[] = [];\n\n // `verifyMerkle === false` is the offline switch: it suppresses EVERY\n // outbound URI fetch the verifier would otherwise issue past the\n // chain/indexer resolve step — both the sealed-item ciphertext download in\n // decryption (5b) and the Merkle leaves-list fetch (6). Offline callers\n // (server-rendered viewers, CLI `--no-fetch`) get a report built from\n // indexed CBOR plus any caller-supplied out-of-band bytes alone.\n const allowUriFetch = input.verifyMerkle ?? true;\n\n // 5a. Record-level signatures (profile >= 'signed').\n if (plan.verifySignatures && record.sigs && record.sigs.length > 0) {\n const sigOut: VerifyRecordSignature[] = await verifyRecordSignatures({ record, input });\n report.record_signatures = sigOut;\n if (recordSignaturesShouldFail(sigOut)) {\n report.verdict = 'failed';\n report.exit_code = 1;\n }\n }\n\n // 5b. Decryption (profile >= 'recipient-sealed' AND caller supplied keys).\n if (plan.verifyDecrypt && input.decryption && input.decryption.length > 0) {\n const dec = await tryDecryptions({\n record,\n input,\n fetchFn,\n httpCalls,\n uriChecksOut: uriChecks,\n allowUriFetch,\n });\n report.item_decryptions = dec.results;\n const decFailure = decryptionsShouldFail(dec.results);\n if (decFailure !== null) {\n report.verdict = 'failed';\n report.exit_code = decFailure === 'network' ? 2 : 1;\n }\n }\n\n // 6. Merkle commitments (always in `core` and above; only escalates verdict\n // to `'failed'` on `MERKLE_ROOT_MISMATCH` / leaf-count mismatch — leaves\n // unavailability stays at warning).\n //\n // Suppressed entirely when the offline switch is set (see `allowUriFetch`)\n // so a server-rendered viewer produces a VerifyReport from indexed CBOR\n // alone, with zero outbound fetches to Arweave/IPFS gateways. The on-record\n // `merkle[]` data (alg, root, leaf_count, uris) survives unchanged on\n // `report.record`; only the defence-in-depth re-root + leaf-count check is\n // suppressed. A user-initiated client-side flow performs the same\n // verification at click time.\n if (allowUriFetch && Array.isArray(record.merkle) && record.merkle.length > 0) {\n const merkle = await verifyMerkleCommitments({\n record,\n input,\n fetchFn,\n uriChecksOut: uriChecks,\n });\n report.merkle_checks = merkle.checks;\n const merkleFailure = merkleChecksShouldFail(merkle.checks);\n if (merkleFailure && report.verdict === 'valid') {\n report.verdict = 'failed';\n report.exit_code = 1;\n }\n }\n\n if (uriChecks.length > 0) {\n report.uri_checks = uriChecks;\n }\n\n return report;\n}\n\n// ─── Internals ────────────────────────────────────────────────────────────────\n\n// Decode the transaction-level description (witnesses, summary, co-published\n// metadata labels) from raw tx CBOR. This is purely informational, so a decode\n// failure must NOT propagate into the verdict — it degrades to omitting the\n// affected fields. The label-309 record is validated separately from\n// `metadataBytes`; this view only describes the carrying transaction.\ntype TxDescriptionFields = Pick<VerifyReport, 'tx_witnesses' | 'tx_summary' | 'metadata_labels'>;\nfunction decodeTxDescription(txCbor: Uint8Array, input: VerifyTxInput): TxDescriptionFields {\n const network = input.cardanoNetwork ?? 'mainnet';\n const out: { -readonly [K in keyof TxDescriptionFields]: TxDescriptionFields[K] } = {};\n let components;\n try {\n components = sliceTxComponents(txCbor);\n } catch {\n return out;\n }\n out.metadata_labels = components.auxMetadataLabels;\n try {\n out.tx_witnesses = decodeTxWitnesses(components.witnessSet, components.txBody);\n } catch {\n // leave tx_witnesses undefined\n }\n try {\n out.tx_summary = decodeTxSummary(components.txBody, components.witnessSet, network);\n } catch {\n // leave tx_summary undefined\n }\n return out;\n}\n\n// A public hash-only PoE stays valid even when every signature entry is\n// SIGNATURE_UNSUPPORTED — the content claim does not depend on signer identity,\n// so an unverifiable algorithm is informational, not fatal. Any OTHER failure\n// (MALFORMED_SIG_COSE_SIGN1, SIGNER_KEY_UNRESOLVED, SIGNATURE_INVALID,\n// WALLET_ADDRESS_MISMATCH) fails the record.\nfunction recordSignaturesShouldFail(sigs: ReadonlyArray<VerifyRecordSignature>): boolean {\n return sigs.some((s) => s.verdict === 'invalid' || s.verdict === 'unresolved');\n}\n\n// Returns null on success, 'network' for CONTENT_UNAVAILABLE / IPFS-no-gateway\n// (exit 2), or 'integrity' for any other failure (exit 1).\nfunction decryptionsShouldFail(\n results: ReadonlyArray<VerifyItemDecryption>,\n): 'network' | 'integrity' | null {\n let saw: 'network' | 'integrity' | null = null;\n for (const d of results) {\n if (d.verdict === 'decrypted' && d.plaintext_hash_ok !== false) continue;\n if (d.verdict === 'content-unavailable' || d.verdict === 'ciphertext-unavailable') {\n saw = saw === 'integrity' ? 'integrity' : 'network';\n continue;\n }\n saw = 'integrity';\n }\n return saw;\n}\n\nfunction merkleChecksShouldFail(checks: ReadonlyArray<VerifyMerkleCheck>): boolean {\n for (const c of checks) {\n if (c.verdict === 'mismatch') return true;\n // `unavailable`, `format-unsupported`, and `unsupported` are warning/\n // info-severity — the on-chain root is structurally valid on its own, so\n // they do NOT escalate to verdict 'failed'.\n }\n return false;\n}\n\nfunction issueOf(\n code: keyof typeof SEVERITY,\n path: ReadonlyArray<string | number>,\n message: string,\n): ValidationIssue {\n return { code, path, message, severity: SEVERITY[code] };\n}\n\nfunction composeValidation(\n valid: boolean,\n issues: ReadonlyArray<ValidationIssue> | undefined,\n warnings: ReadonlyArray<ValidationIssue>,\n info: ReadonlyArray<ValidationIssue>,\n): VerifyReport['validation'] {\n const out: {\n valid: boolean;\n issues?: ReadonlyArray<ValidationIssue>;\n warnings?: ReadonlyArray<ValidationIssue>;\n info?: ReadonlyArray<ValidationIssue>;\n } = { valid };\n if (issues !== undefined && issues.length > 0) out.issues = issues;\n if (warnings.length > 0) out.warnings = warnings;\n if (info.length > 0) out.info = info;\n return out;\n}\n\n// Convenience re-export so callers can map verdicts to exit codes without\n// importing the union shape.\nexport function exitCodeForVerdict(report: VerifyReport): ExitCode {\n return report.exit_code;\n}\n\nexport type { Verdict, ExitCode };\n","#!/usr/bin/env node\n// Conformance CLI: single-tx verification against the Label 309 standalone\n// verifier.\n//\n// Exit codes (extended with 4 for CLI input errors):\n// 0 = valid, 1 = failed (integrity), 2 = failed (network),\n// 3 = pending, 4 = CLI input error\n\nimport { KOIOS_MAINNET_URL, exitCodeForVerdict, verifyTx } from '../verifier/index';\n\nconst VERSION = '0.1.0';\n\ninterface ParsedArgs {\n readonly txHash: string | undefined;\n readonly gateways: ReadonlyArray<string>;\n readonly threshold: number | undefined;\n readonly json: boolean;\n readonly showHelp: boolean;\n readonly showVersion: boolean;\n readonly error: string | undefined;\n}\n\nexport function parseArgs(args: ReadonlyArray<string>): ParsedArgs {\n let txHash: string | undefined;\n const gateways: string[] = [];\n let threshold: number | undefined;\n let json = true;\n let showHelp = false;\n let showVersion = false;\n let error: string | undefined;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]!;\n if (arg === '--help' || arg === '-h') {\n showHelp = true;\n } else if (arg === '--version' || arg === '-V') {\n showVersion = true;\n } else if (arg === '--json') {\n json = true;\n } else if (arg === '--gateway') {\n const v = args[++i];\n if (v === undefined) {\n error = '--gateway requires a value';\n break;\n }\n gateways.push(v);\n } else if (arg === '--threshold') {\n const v = args[++i];\n const n = Number(v);\n if (v === undefined || !Number.isFinite(n) || !Number.isInteger(n) || n < 0) {\n error = '--threshold requires a non-negative integer';\n break;\n }\n threshold = n;\n } else if (arg.startsWith('-')) {\n error = `unknown flag: ${arg}`;\n break;\n } else if (txHash === undefined) {\n txHash = arg;\n } else {\n error = `unexpected positional argument: ${arg}`;\n break;\n }\n }\n\n return { txHash, gateways, threshold, json, showHelp, showVersion, error };\n}\n\nconst USAGE = `Usage: cardanowall-sdk-conformance <tx-hash> [--gateway <url>] [--threshold <n>] [--json]\n cardanowall-sdk-conformance --version\n cardanowall-sdk-conformance --help\n\nRuns the @cardanowall/sdk-ts standalone Label 309 verifier against a single\nCardano transaction. Exit codes:\n 0 = valid, 1 = failed (integrity), 2 = failed (network), 3 = pending,\n 4 = CLI input error.`;\n\nexport interface RunIO {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport async function run(args: ReadonlyArray<string>, io: RunIO): Promise<number> {\n const parsed = parseArgs(args);\n if (parsed.showHelp) {\n io.stdout(USAGE + '\\n');\n return 0;\n }\n if (parsed.showVersion) {\n io.stdout(`cardanowall-sdk-conformance ${VERSION}\\n`);\n return 0;\n }\n if (parsed.error !== undefined) {\n io.stderr(`cardanowall-sdk-conformance: ${parsed.error}\\n`);\n io.stderr(USAGE + '\\n');\n return 4;\n }\n if (parsed.txHash === undefined) {\n io.stderr('cardanowall-sdk-conformance: <tx-hash> is required\\n');\n io.stderr(USAGE + '\\n');\n return 4;\n }\n if (!/^[0-9a-f]{64}$/i.test(parsed.txHash)) {\n io.stderr(\n `cardanowall-sdk-conformance: invalid tx-hash (expected 64 hex chars): ${parsed.txHash}\\n`,\n );\n return 4;\n }\n\n const gateways = parsed.gateways.length > 0 ? parsed.gateways : [KOIOS_MAINNET_URL];\n\n try {\n const report = await verifyTx({\n txHash: parsed.txHash.toLowerCase(),\n cardanoGatewayChain: gateways,\n ...(parsed.threshold !== undefined ? { confirmationDepthThreshold: parsed.threshold } : {}),\n });\n io.stdout(JSON.stringify(report, null, 2) + '\\n');\n return exitCodeForVerdict(report);\n } catch (err) {\n io.stderr(\n `cardanowall-sdk-conformance: verifier error: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n return 2;\n }\n}\n\n// Only run as a script when invoked directly (not when imported by tests).\nif (/cli\\.(c?js|ts)$/.test(process.argv[1] ?? '')) {\n void run(process.argv.slice(2), {\n stdout: (text) => process.stdout.write(text),\n stderr: (text) => process.stderr.write(text),\n }).then((code) => process.exit(code));\n}\n"]}