@cardanowall/crypto-core 0.0.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/aead/errors.ts","../src/aead/chacha20-poly1305.ts","../src/aead/xchacha20-poly1305.ts","../src/kdf/hkdf.ts","../src/kem/mlkem768x25519.ts","../src/kem/x25519.ts","../src/sealed-poe/errors.ts","../src/cbor/canonical.ts","../src/sealed-poe/slots-codec.ts","../src/sealed-poe/wrap.ts","../src/util/compare-ct.ts","../src/sealed-poe/unwrap.ts","../src/sealed-poe/envelope-from-parsed.ts"],"names":["chacha20poly1305","xchacha20poly1305","hkdf","sha256","XWing","x25519","encode","sortCoreDeterministic","randomBytes","hmac","ZERO_NONCE_12","EMPTY_SALT","X25519_SECRET_KEY_LENGTH","X25519_PUBLIC_KEY_LENGTH","NONCE_LENGTH","WRAP_LENGTH","SLOTS_MAC_LENGTH","concat"],"mappings":";;;;;;;;;;;;;;;AAAO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EACtC,IAAA,GAAe,0BAAA;AAAA,EAExB,WAAA,CAAY,SAAiB,OAAA,EAA+B;AAC1D,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EACd;AACF,CAAA;;;ACWO,SAAS,wBAAwB,IAAA,EAA+C;AACrF,EAAA,OAAOA,0BAAA,CAAiB,IAAA,CAAK,GAAA,EAAK,IAAA,CAAK,KAAA,EAAO,KAAK,GAAG,CAAA,CAAE,OAAA,CAAQ,IAAA,CAAK,SAAS,CAAA;AAChF;AAEO,SAAS,wBAAwB,IAAA,EAA+C;AACrF,EAAA,IAAI;AACF,IAAA,OAAOA,0BAAA,CAAiB,IAAA,CAAK,GAAA,EAAK,IAAA,CAAK,KAAA,EAAO,KAAK,GAAG,CAAA,CAAE,OAAA,CAAQ,IAAA,CAAK,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AAO;AAAA,MACL,MAAA,EAAQ,CAAA;AAAA,MACR,IAAA,EAAM,oBAAA;AAAA,MACN,GAAA,EAAK,gBAAA;AAAA,MACL,OAAO,GAAA,CAAI,KAAA;AAAA,MACX,KAAA,EAAO,WAAA;AAAA,MACP,WAAW,GAAA,CAAI;AAAA,KACjB;AAAA,EACF;AAEA,EAAA,OAAO,IAAA;AACT","file":"sealed-poe.cjs","sourcesContent":["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 { 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 { 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 { 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","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","// 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","// 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","// 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"]}
1
+ {"version":3,"sources":["../src/aead/errors.ts","../src/aead/chacha20-poly1305.ts","../src/aead/xchacha20-poly1305.ts","../src/kdf/hkdf.ts","../src/kem/mlkem768x25519.ts","../src/kem/x25519.ts","../src/sealed-poe/errors.ts","../src/cbor/canonical.ts","../src/sealed-poe/slots-codec.ts","../src/sealed-poe/wrap.ts","../src/util/compare-ct.ts","../src/sealed-poe/unwrap.ts","../src/sealed-poe/envelope-from-parsed.ts"],"names":["chacha20poly1305","xchacha20poly1305","hkdf","sha256","XWing","x25519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IAAI,EAAE,GAAA,KAAQ,MAAA,IAAa,CAAA,CAAE,IAAA,KAAS,QAAW,OAAO,IAAA;AACxD,MAAA,WAAA,CAAY,IAAA,CAAK,EAAE,GAAA,EAAK,CAAA,CAAE,KAAK,IAAA,EAAM,CAAA,CAAE,MAAM,CAAA;AAAA,IAC/C;AACA,IAAA,OAAO;AAAA,MACL,MAAA,EAAQ,CAAA;AAAA,MACR,IAAA,EAAM,oBAAA;AAAA,MACN,GAAA,EAAK,QAAA;AAAA,MACL,OAAO,GAAA,CAAI,KAAA;AAAA,MACX,KAAA,EAAO,WAAA;AAAA,MACP,WAAW,GAAA,CAAI;AAAA,KACjB;AAAA,EACF;AAEA,EAAA,IAAI,GAAA,CAAI,QAAQ,gBAAA,EAAkB;AAChC,IAAA,MAAM,cAAoC,EAAC;AAC3C,IAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,MAAA,IAAI,EAAE,MAAA,KAAW,MAAA,IAAa,CAAA,CAAE,IAAA,KAAS,QAAW,OAAO,IAAA;AAC3D,MAAA,WAAA,CAAY,IAAA,CAAK,EAAE,MAAA,EAAQ,CAAA,CAAE,QAAQ,IAAA,EAAM,CAAA,CAAE,MAAM,CAAA;AAAA,IACrD;AACA,IAAA,OAAO;AAAA,MACL,MAAA,EAAQ,CAAA;AAAA,MACR,IAAA,EAAM,oBAAA;AAAA,MACN,GAAA,EAAK,gBAAA;AAAA,MACL,OAAO,GAAA,CAAI,KAAA;AAAA,MACX,KAAA,EAAO,WAAA;AAAA,MACP,WAAW,GAAA,CAAI;AAAA,KACjB;AAAA,EACF;AAEA,EAAA,OAAO,IAAA;AACT","file":"sealed-poe.cjs","sourcesContent":["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 { 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 { 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 { 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","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","// 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","// 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","// 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"]}