@cardanowall/crypto-core 0.1.0 → 0.3.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.
- package/README.md +9 -9
- package/dist/canonical-DHeJLYDR.d.cts +7 -0
- package/dist/canonical-DHeJLYDR.d.ts +7 -0
- package/dist/cbor.cjs +1 -1
- package/dist/cbor.cjs.map +1 -1
- package/dist/cbor.d.cts +2 -6
- package/dist/cbor.d.ts +2 -6
- package/dist/cbor.js +1 -1
- package/dist/cbor.js.map +1 -1
- package/dist/cose.cjs +11 -11
- package/dist/cose.cjs.map +1 -1
- package/dist/cose.d.cts +7 -7
- package/dist/cose.d.ts +7 -7
- package/dist/cose.js +9 -9
- package/dist/cose.js.map +1 -1
- package/dist/index.cjs +291 -121
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +270 -118
- package/dist/index.js.map +1 -1
- package/dist/kem.cjs.map +1 -1
- package/dist/kem.js.map +1 -1
- package/dist/merkle.cjs +1 -1
- package/dist/merkle.cjs.map +1 -1
- package/dist/merkle.js +1 -1
- package/dist/merkle.js.map +1 -1
- package/dist/sealed-poe.cjs +299 -118
- package/dist/sealed-poe.cjs.map +1 -1
- package/dist/sealed-poe.d.cts +55 -3
- package/dist/sealed-poe.d.ts +55 -3
- package/dist/sealed-poe.js +281 -118
- package/dist/sealed-poe.js.map +1 -1
- package/dist/seed-derive.cjs.map +1 -1
- package/dist/seed-derive.js.map +1 -1
- package/package.json +5 -5
package/dist/sealed-poe.cjs.map
CHANGED
|
@@ -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,UAAU,CAAA;AAAA,EACjF,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,IAAI,qBAAA,CAAsB,kCAAA,EAAoC,EAAE,OAAO,CAAA;AAAA,EAC/E;AACF;ACVO,SAAS,yBAAyB,IAAA,EAAgD;AACvF,EAAA,OAAOC,2BAAA,CAAkB,IAAA,CAAK,GAAA,EAAK,IAAA,CAAK,KAAA,EAAO,KAAK,GAAG,CAAA,CAAE,OAAA,CAAQ,IAAA,CAAK,SAAS,CAAA;AACjF;AAEO,SAAS,yBAAyB,IAAA,EAA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AA,CAAI,QAAQ,QAAA,EAAU;AACxB,IAAA,MAAM,cAA4B,EAAC;AACnC,IAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,MAAA,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 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/sealed-poe/slots-codec.ts","../src/cbor/canonical.ts","../src/sealed-poe/transcript.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,KA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,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-10.\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: the ML-KEM coins and the X25519\n // scalar are re-expanded from it via SHAKE-256 at decapsulation. (Later X-Wing\n // drafts also define an optional expanded decapsulation-key form; we keep the\n // seed-only key, which the draft-10 Appendix C vectors still pin.)\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 | 'ENC_SLOTS_DUPLICATE_KEM_MATERIAL'\n | 'ENC_SLOTS_TOO_MANY'\n | 'ENC_ENVELOPE_TOO_LARGE'\n | 'KEM_EPK_LENGTH_MISMATCH'\n | 'KEM_CT_LENGTH_MISMATCH'\n | 'INVALID_CEK_LENGTH'\n | 'NONCE_LENGTH_MISMATCH'\n | 'INVALID_EPHEMERAL_SECRET_LENGTH'\n | 'EPHEMERAL_SECRETS_COUNT_MISMATCH'\n | 'UNSUPPORTED_ENC_VERSION'\n | 'UNSUPPORTED_AEAD_ALG'\n | 'UNSUPPORTED_KEM_ALG'\n | 'INVALID_ENVELOPE_SHAPE'\n | 'INVALID_RECIPIENT_KEY'\n | 'WRAP_LENGTH_MISMATCH';\n\nexport class EciesSealedPoeError extends Error {\n readonly code: EciesSealedPoeErrorCode;\n\n constructor(code: EciesSealedPoeErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'EciesSealedPoeError';\n this.code = code;\n }\n}\n","// Single source of truth for two seams that wrap, unwrap, and the wire encoder\n// MUST agree on byte-for-byte:\n//\n// 1. How the 1120-byte X-Wing `enc` is split into the ≤ 64-byte byte-string\n// chunks the Cardano ledger requires (`kem_ct`), and the inverse join.\n// 2. The canonical slot-array structure the slots transcript commits to.\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 slot-set MAC\n// commits to — the single highest correctness risk for the hybrid branch, since\n// a divergence would leave the ML-KEM ciphertext unauthenticated.\n\nimport 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 canonical slot-array structure committed by the slots transcript.\n//\n// • x25519: each slot → { epk: bstr, wrap: bstr }\n// • mlkem768x25519: each slot → { kem_ct: [ bstr, ... ], wrap: bstr }\n//\n// The hybrid form re-chunks `kem_ct` into its canonical ≤ 64-byte sequence so\n// the transcript commits to the ciphertext BYTES, not the wire chunk boundaries.\n// The on-wire `kem_ct` array is a transport detail (the Cardano ledger's 64-byte\n// metadatum cap), and a hostile or non-canonical chunking ([1, 63, …] instead of\n// [64, …]) reassembles to the SAME bytes — so the commitment must be invariant to\n// it. Committing to the verbatim wire chunks would let an attacker re-chunk an\n// honest envelope and break the slots_mac match for an honest recipient. Honest\n// (already-64B-chunked) records are unchanged; a real byte flip still changes the\n// reassembled bytes and is still rejected.\n//\n// Returns the slot-array structure (NOT encoded) so the caller can embed it in\n// the larger slots-transcript map before a single canonical encode.\nexport function canonicalizeSlots(\n slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n kem: SealedKem,\n): CanonicalCborValue {\n if (kem === 'x25519') {\n return (slots as ReadonlyArray<X25519Slot>).map((s) => ({ epk: s.epk, wrap: s.wrap }));\n }\n return (slots as ReadonlyArray<Mlkem768X25519Slot>).map((s) => ({\n kem_ct: chunkKemCt(joinKemCt(s.kem_ct)),\n wrap: s.wrap,\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","// Shared, byte-critical pieces of the slots-path sealed-PoE construction that\n// the producer (wrap) and every verifier (unwrap, trial-decrypt) MUST compute\n// byte-for-byte identically:\n//\n// 1. The slots transcript and its SHA-256 hash `slots_hash`.\n// 2. The content-AEAD additional-authenticated-data object `AD_CONTENT_SLOTS`.\n// 3. The content `payload_key` derivation from the CEK.\n// 4. The hybrid (X-Wing) per-slot KEK salt.\n// 5. The single-shot XChaCha20-Poly1305 maximum-payload guard.\n//\n// Keeping these in one module is the interop guarantee: a single divergence in\n// the canonical encoding silently yields a `slots_mac` or AEAD tag that another\n// implementation cannot reproduce, with no typed error to localise the fault.\n// There is exactly one shared implementation, imported by both sides.\n\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { encodeCanonicalCbor, type CanonicalCborValue } from '../cbor/canonical';\nimport { hkdfSha256 } from '../kdf/hkdf';\n\nimport { canonicalizeSlots, type SealedKem } from './slots-codec';\nimport type { Mlkem768X25519Slot, X25519Slot } from './wrap';\n\n// Internal domain-separation labels. Each is exact ASCII with no terminator and\n// no length prefix; each is a fixed constant of the scheme, never serialised on\n// the wire and never registry-selectable. The byte-length invariants below keep\n// the SCREAMING_SNAKE constants in sync with the ASCII literals every conformant\n// verifier hashes against.\n\n// SHA-256 prefix for the slots-transcript hash `slots_hash`.\nexport const CARDANO_POE_SLOTS_TRANSCRIPT_PREFIX: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-slots-transcript-v1',\n);\n// HKDF info for the slots-path content `payload_key`.\nexport const CARDANO_POE_HKDF_INFO_PAYLOAD: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-payload-v1',\n);\n// HKDF info for the passphrase-path content `payload_key`.\nexport const CARDANO_POE_HKDF_INFO_PAYLOAD_PASSPHRASE: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-payload-passphrase-v1',\n);\n// SHA-256 prefix for the hybrid (X-Wing) per-slot KEK HKDF salt.\nexport const CARDANO_POE_XWING_KEK_SALT_PREFIX: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-xwing-kek-salt-v1',\n);\n\nif (CARDANO_POE_SLOTS_TRANSCRIPT_PREFIX.length !== 31) {\n throw new Error(\n 'CARDANO_POE_SLOTS_TRANSCRIPT_PREFIX byte-length invariant violated (expected 31)',\n );\n}\nif (CARDANO_POE_HKDF_INFO_PAYLOAD.length !== 22) {\n throw new Error('CARDANO_POE_HKDF_INFO_PAYLOAD byte-length invariant violated (expected 22)');\n}\nif (CARDANO_POE_HKDF_INFO_PAYLOAD_PASSPHRASE.length !== 33) {\n throw new Error(\n 'CARDANO_POE_HKDF_INFO_PAYLOAD_PASSPHRASE byte-length invariant violated (expected 33)',\n );\n}\nif (CARDANO_POE_XWING_KEK_SALT_PREFIX.length !== 29) {\n throw new Error('CARDANO_POE_XWING_KEK_SALT_PREFIX byte-length invariant violated (expected 29)');\n}\n\n// Scheme-fixed constant pinning the passphrase normalization profile the CEK was\n// derived under. Fed into the passphrase-path AAD; never serialised on the wire.\nexport const CARDANO_POE_PW_NORM_PROFILE = 'cardano-poe-pw-norm-v1' as const;\n\n// Verifier-side resource bounds a public parser MUST enforce BEFORE invoking any\n// KEM/AEAD primitive, so a malformed envelope cannot drive unbounded work. Both\n// are deployment-pinned reference constants (not wire fields); deployments MAY\n// tighten them. They sit far above the ~16 KiB Cardano transaction-metadata\n// ceiling that bounds honest records, so a conformant record never trips them.\n//\n// • MAX_SLOTS — the maximum slot count; an envelope with more slots is\n// rejected outright.\n// • MAX_DECODED_ENVELOPE_BYTES — a backstop on the decoded envelope's\n// aggregate byte size (nonce + slots_mac + every per-slot wire field),\n// bounding the work even before the slot-count cap would.\nexport const MAX_SLOTS = 1024;\nexport const MAX_DECODED_ENVELOPE_BYTES = 65536;\n\n// XChaCha20-Poly1305 is a single-shot AEAD over the whole plaintext; its 32-bit\n// internal block counter bounds one (key, nonce) invocation at 2^32 64-byte\n// ChaCha20 blocks, the first of which is consumed by the Poly1305 one-time key.\n// MAX_SEALED_PLAINTEXT is therefore (2^32 - 1) * 64 = 2^38 - 64 bytes; a plaintext\n// at or above it risks a counter-overflow keystream collision and MUST be\n// rejected before the AEAD is invoked on either side. This constant is identical\n// across all conformant implementations.\nexport const MAX_SEALED_PLAINTEXT = 274877906880; // 2^38 - 64\n// Poly1305 appends a 16-byte tag, so the corresponding ciphertext bound is + 16.\nexport const MAX_SEALED_CIPHERTEXT = MAX_SEALED_PLAINTEXT + 16;\n\nif (MAX_SEALED_PLAINTEXT !== 2 ** 38 - 64) {\n throw new Error('MAX_SEALED_PLAINTEXT invariant violated (expected 2^38 - 64)');\n}\n\n// Reject a slots-path plaintext at or above the single-shot keystream capacity,\n// before any AEAD call. Thrown on the producer side.\nexport function assertPlaintextWithinBound(plaintextLength: number): void {\n if (plaintextLength >= MAX_SEALED_PLAINTEXT) {\n throw new SealedPayloadTooLargeError(\n `plaintext length ${plaintextLength} is at or above the maximum sealed payload size ${MAX_SEALED_PLAINTEXT}`,\n );\n }\n}\n\n// Reject a slots-/passphrase-path ciphertext at or above the single-shot bound,\n// before any AEAD open. Thrown on the verifier side. The ciphertext carries the\n// plaintext plus a 16-byte Poly1305 tag.\nexport function assertCiphertextWithinBound(ciphertextLength: number): void {\n if (ciphertextLength >= MAX_SEALED_CIPHERTEXT) {\n throw new SealedPayloadTooLargeError(\n `ciphertext length ${ciphertextLength} is at or above the maximum sealed ciphertext size ${MAX_SEALED_CIPHERTEXT}`,\n );\n }\n}\n\nexport class SealedPayloadTooLargeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'SealedPayloadTooLargeError';\n }\n}\n\n// SHA-256(\"cardano-poe-slots-transcript-v1\" || canonicalEncode(SLOTS_TRANSCRIPT)).\n// SLOTS_TRANSCRIPT is the closed six-key map binding the cross-KEM header fields\n// (scheme, path, aead, kem, nonce) to the canonicalised slot set, so a relay\n// that flips any header field while leaving slot shapes valid yields a different\n// `slots_hash` and the MAC fails. Computed ONCE per envelope and held constant\n// across the recipient trial-decrypt loop. The map keys are a SET — their wire\n// order is fixed by the canonical-encode sort, never hand-arranged here.\nexport function computeSlotsHash(args: {\n kem: SealedKem;\n nonce: Uint8Array;\n slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>;\n}): Uint8Array {\n const transcript: CanonicalCborValue = {\n scheme: 1,\n path: 'slots',\n aead: 'xchacha20-poly1305',\n kem: args.kem,\n nonce: args.nonce,\n slots: canonicalizeSlots(args.slots, args.kem),\n };\n const encoded = encodeCanonicalCbor(transcript);\n const message = new Uint8Array(CARDANO_POE_SLOTS_TRANSCRIPT_PREFIX.length + encoded.length);\n message.set(CARDANO_POE_SLOTS_TRANSCRIPT_PREFIX, 0);\n message.set(encoded, CARDANO_POE_SLOTS_TRANSCRIPT_PREFIX.length);\n return sha256(message);\n}\n\n// canonicalEncode(AD_CONTENT_SLOTS): the closed seven-key content-AEAD AAD for\n// the slots path. It re-binds the slots-path header AND carries both `slots_hash`\n// (binding to the exact transcript) and `slots_mac` (tying the content layer to\n// the CEK-keyed MAC the recipient matched). Both are deliberate, not redundant.\nexport function adContentSlots(args: {\n kem: SealedKem;\n nonce: Uint8Array;\n slotsHash: Uint8Array;\n slotsMac: Uint8Array;\n}): Uint8Array {\n const ad: CanonicalCborValue = {\n scheme: 1,\n path: 'slots',\n aead: 'xchacha20-poly1305',\n kem: args.kem,\n nonce: args.nonce,\n slots_hash: args.slotsHash,\n slots_mac: args.slotsMac,\n };\n return encodeCanonicalCbor(ad);\n}\n\n// canonicalEncode(AD_CONTENT_PASSPHRASE): the closed content-AEAD AAD for the\n// passphrase path. It binds the passphrase KDF parameters into the content tag,\n// so tampering with `salt` or any `params` value after encryption changes the\n// AAD and makes the AEAD open fail. The `normalization` profile id is a\n// scheme-fixed constant pinned into the AAD, never serialised on the wire. There\n// is NO `kem` key on this path.\nexport function adContentPassphrase(args: {\n nonce: Uint8Array;\n passphrase: {\n alg: string;\n salt: Uint8Array;\n params: { m: number; t: number; p: number };\n };\n}): Uint8Array {\n const ad: CanonicalCborValue = {\n scheme: 1,\n path: 'passphrase',\n aead: 'xchacha20-poly1305',\n nonce: args.nonce,\n passphrase: {\n alg: args.passphrase.alg,\n salt: args.passphrase.salt,\n params: {\n m: args.passphrase.params.m,\n t: args.passphrase.params.t,\n p: args.passphrase.params.p,\n },\n normalization: CARDANO_POE_PW_NORM_PROFILE,\n },\n };\n return encodeCanonicalCbor(ad);\n}\n\n// Slots-path content key: HKDF-SHA-256(ikm=CEK, salt=nonce, info=payload-v1).\n// The content is encrypted under this leaf of the CEK, never under the CEK\n// directly, so the wrap layer and the content layer never key the same primitive\n// on the same bytes.\nexport function slotsPayloadKey(args: { cek: Uint8Array; nonce: Uint8Array }): Uint8Array {\n return hkdfSha256({\n ikm: args.cek,\n salt: args.nonce,\n info: CARDANO_POE_HKDF_INFO_PAYLOAD,\n length: 32,\n });\n}\n\n// Passphrase-path content key: HKDF-SHA-256(ikm=CEK, salt=nonce,\n// info=payload-passphrase-v1).\nexport function passphrasePayloadKey(args: { cek: Uint8Array; nonce: Uint8Array }): Uint8Array {\n return hkdfSha256({\n ikm: args.cek,\n salt: args.nonce,\n info: CARDANO_POE_HKDF_INFO_PAYLOAD_PASSPHRASE,\n length: 32,\n });\n}\n\n// Hybrid (mlkem768x25519) per-slot KEK salt:\n// SHA-256(\"cardano-poe-xwing-kek-salt-v1\" || kem_ct || pub_R). `kem_ct` is the\n// REASSEMBLED 1120-byte X-Wing ciphertext (the kem_ct anchors the KEK to a\n// slot-unique value) and `pub_R` the 1216-byte X-Wing recipient public key\n// (binding the KEK to the specific recipient) — the same two bindings the\n// classical `epk || pub_R` salt provides, expressed through a fixed-length\n// SHA-256 digest because the hybrid inputs are oversized.\nexport function xwingKekSalt(args: { kemCt: Uint8Array; pubR: Uint8Array }): Uint8Array {\n const message = new Uint8Array(\n CARDANO_POE_XWING_KEK_SALT_PREFIX.length + args.kemCt.length + args.pubR.length,\n );\n let offset = 0;\n message.set(CARDANO_POE_XWING_KEK_SALT_PREFIX, offset);\n offset += CARDANO_POE_XWING_KEK_SALT_PREFIX.length;\n message.set(args.kemCt, offset);\n offset += args.kemCt.length;\n message.set(args.pubR, offset);\n return sha256(message);\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, type SealedKem } from './slots-codec';\nimport {\n adContentSlots,\n assertPlaintextWithinBound,\n computeSlotsHash,\n slotsPayloadKey,\n xwingKekSalt,\n} from './transcript';\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 // The hybrid KEK salt binds the slot's own reassembled X-Wing ciphertext and\n // the recipient public key, mirroring the classical `epk || pub_R` salt: the\n // ciphertext anchors the KEK to a slot-unique value and `pub_R` binds it to\n // the specific recipient. It is computed outside the KEM, over the slot's wire\n // bytes, so it holds X-Wing as a black-box KEM.\n const kek = hkdfSha256({\n ikm: ss,\n salt: xwingKekSalt({ kemCt: enc, pubR: args.pubR }),\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 // Reject a plaintext at or above the single-shot keystream capacity before any\n // KEM or AEAD work, so an over-large input never reaches the content cipher.\n assertPlaintextWithinBound(plaintext.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 // `slots_hash` is the SHA-256 of the header-bound slots transcript. It is\n // computed once here, fed into both the slot-set MAC and the content AAD.\n let slotsHash: Uint8Array;\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). The transcript is built\n // AFTER the shuffle so the MAC binds the on-wire slot order.\n if (args.skipShuffle !== true) {\n csprngShuffle(slots);\n }\n slotsHash = computeSlotsHash({ kem: 'x25519', nonce, slots });\n envelope = {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'x25519',\n nonce,\n slots,\n slots_mac: computeSlotsMac(cek, slotsHash),\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 slotsHash = computeSlotsHash({ kem: 'mlkem768x25519', nonce, slots });\n envelope = {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'mlkem768x25519',\n nonce,\n slots,\n slots_mac: computeSlotsMac(cek, slotsHash),\n };\n }\n\n // Content is encrypted under a derived `payload_key` (a separate HKDF leaf of\n // the CEK keyed on the nonce), never under the CEK directly, so the wrap layer\n // and the content layer never key the same primitive on the same bytes. The\n // AAD re-binds the slots-path header and carries both `slots_hash` and\n // `slots_mac`.\n const payloadKey = slotsPayloadKey({ cek, nonce });\n const adContent = adContentSlots({\n kem: envelope.kem,\n nonce,\n slotsHash,\n slotsMac: envelope.slots_mac,\n });\n const ciphertext = xchacha20Poly1305Encrypt({\n key: payloadKey,\n nonce,\n aad: adContent,\n plaintext,\n });\n\n return { envelope, ciphertext };\n}\n\n// Slot-set MAC binds the slots transcript to the CEK. The transcript is pre-\n// hashed to a 32-byte `slots_hash` (header fields + canonicalised slot set,\n// including the entire chunked kem_ct on the hybrid path), and that hash is the\n// message of a CEK-keyed HMAC. Pre-hashing only changes the HMAC message from\n// the full transcript to its SHA-256, leaving the CEK-keyed commitment intact.\nfunction computeSlotsMac(cek: Uint8Array, slotsHash: Uint8Array): 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 slotsMac = hmac(sha256, hmacKey, slotsHash);\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 {\n mlkem768x25519Decapsulate,\n mlkem768x25519Keygen,\n MLKEM768X25519_ENC_LENGTH,\n} from '../kem/mlkem768x25519';\nimport { x25519Ecdh, X25519LowOrderPointError, x25519PublicKey } from '../kem/x25519';\nimport { compareCt } from '../util/compare-ct';\n\nimport { EciesSealedPoeError } from './errors';\nimport { joinKemCt } from './slots-codec';\nimport {\n adContentSlots,\n assertCiphertextWithinBound,\n computeSlotsHash,\n MAX_DECODED_ENVELOPE_BYTES,\n MAX_SLOTS,\n slotsPayloadKey,\n xwingKekSalt,\n} from './transcript';\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// Stable string key for a byte string, used only for the per-slot KEM-material\n// duplicate check (a structural pre-trial gate, not a constant-time comparison).\nfunction bytesKey(bytes: Uint8Array): string {\n let s = '';\n for (let i = 0; i < bytes.length; i++) {\n s += String.fromCharCode(bytes[i]!);\n }\n return s;\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 // Resource bound: reject an envelope with more than MAX_SLOTS slots before any\n // KEM/AEAD primitive runs, so a malformed record cannot drive unbounded\n // per-slot work. Checked before the per-slot length loop below.\n if (n > MAX_SLOTS) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_TOO_MANY',\n `envelope.slots.length=${n} exceeds MAX_SLOTS=${MAX_SLOTS}`,\n );\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 //\n // Per-slot KEK uniqueness is also enforced here. The zero-nonce per-slot wrap\n // is safe only because each slot draws fresh KEM randomness, so its KEK is\n // unique; two slots sharing the same KEM material derive the same KEK and\n // repeat a (KEK, zero-nonce) pair. The KEM material that fixes the KEK is the\n // `epk` (x25519) or the reassembled `kem_ct` (hybrid) — both bound into the\n // KEK salt — so a repeat of either across slots is rejected outright.\n const seenKemMaterial = new Set<string>();\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 const key = bytesKey(slot.epk);\n if (seenKemMaterial.has(key)) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_DUPLICATE_KEM_MATERIAL',\n `envelope.slots[${i}].epk duplicates an earlier slot — per-slot KEK uniqueness is violated`,\n );\n }\n seenKemMaterial.add(key);\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 const key = bytesKey(enc);\n if (seenKemMaterial.has(key)) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_DUPLICATE_KEM_MATERIAL',\n `envelope.slots[${i}].kem_ct duplicates an earlier slot — per-slot KEK uniqueness is violated`,\n );\n }\n seenKemMaterial.add(key);\n }\n }\n\n // Decoded-envelope byte backstop. Every per-slot field above is validated to a\n // fixed length, so the decoded envelope's aggregate size is determined here:\n // nonce + slots_mac + per-slot (epk|kem_ct + wrap). Reject before any KEM/AEAD\n // primitive when it exceeds the bound — a tighter resource cap than MAX_SLOTS\n // for honest records, and the bound a parser that can see the decoded size\n // enforces. (The slot-count cap above already bounds work; this is the byte\n // backstop the spec also pins.)\n const perSlotBytes =\n envelope.kem === 'x25519'\n ? X25519_PUBLIC_KEY_LENGTH + WRAP_LENGTH\n : MLKEM768X25519_ENC_LENGTH + WRAP_LENGTH;\n const decodedEnvelopeBytes = NONCE_LENGTH + SLOTS_MAC_LENGTH + n * perSlotBytes;\n if (decodedEnvelopeBytes > MAX_DECODED_ENVELOPE_BYTES) {\n throw new EciesSealedPoeError(\n 'ENC_ENVELOPE_TOO_LARGE',\n `decoded envelope size ${decodedEnvelopeBytes} exceeds MAX_DECODED_ENVELOPE_BYTES=${MAX_DECODED_ENVELOPE_BYTES}`,\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// All-zero IKM for the dummy KEK an invalid-ECDH slot derives so it pays the\n// same HKDF work as a live slot (see `tryX25519Slot`).\nconst ZERO_IKM_32: Uint8Array = new Uint8Array(32);\n\n// Classical (x25519) per-slot recovery body. Returns the candidate CEK on an\n// AEAD-tag success; null otherwise. The AEAD is attempted on EVERY slot (no\n// match-position-dependent skip), so a per-priv scan recovers a candidate CEK\n// from each slot the recipient is addressed in — which is what the inner loop's\n// CEK-conflict detection needs. Attempting the AEAD on every slot also makes the\n// per-slot timing more uniform, not less: every slot pays the identical\n// ECDH + HKDF + AEAD-open cost regardless of where the match lands.\n//\n// Acceptance is `kem_ok AND open_ok`. `kem_ok` is the X25519 validity bit: a\n// small-order `epk` drives the shared secret to all-zero, which RFC 7748 §6.1\n// rejects. @noble/curves signals this by THROWING from `getSharedSecret`, so a\n// fully branchless ct-select over the shared secret is not expressible against\n// this library API. The next-best, equivalent form is taken instead: on the\n// all-zero rejection the slot derives a DUMMY KEK from `ikm=0^32` (same\n// salt/info) so it performs the identical HKDF work, then returns a non-match\n// WITHOUT attempting the AEAD — so an invalid-ECDH slot can never be accepted\n// regardless of the wrap outcome (`kem_ok=false` ⟹ the AEAD is never reached),\n// while the failed path still costs the same per-slot KEK derivation as a live\n// one.\nfunction tryX25519Slot(args: {\n slot: X25519Slot;\n recipientSecretKey: Uint8Array;\n pubRLocal: Uint8Array;\n}): Uint8Array | null {\n const salt = concat(args.slot.epk, args.pubRLocal);\n let shared: Uint8Array;\n try {\n shared = x25519Ecdh({\n secretKey: args.recipientSecretKey,\n theirPublicKey: args.slot.epk,\n });\n } catch (e) {\n if (!(e instanceof X25519LowOrderPointError)) throw e;\n // kem_ok = false. Derive the dummy KEK so the failed slot pays the same\n // HKDF cost a live slot would, then short-circuit to a non-match: the AEAD\n // is never attempted, so this slot can never be accepted.\n hkdfSha256({ ikm: ZERO_IKM_32, salt, info: CARDANO_POE_HKDF_INFO_KEK, length: 32 });\n return null;\n }\n // kem_ok = true. Derive the real KEK and attempt the wrap AEAD.\n const kek = hkdfSha256({ ikm: shared, salt, info: CARDANO_POE_HKDF_INFO_KEK, length: 32 });\n try {\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)) throw e;\n return null;\n }\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// As in the classical body, the AEAD is attempted on EVERY slot (full\n// decapsulate + HKDF + AEAD-open) so matching and non-matching slots cost the\n// same X-Wing work and a per-priv scan recovers a candidate CEK from every slot\n// the recipient is addressed in.\nfunction tryMlkem768X25519Slot(args: {\n slot: Mlkem768X25519Slot;\n recipientSecretKey: Uint8Array;\n pubR: Uint8Array;\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 // The KEK salt binds the slot's own reassembled ciphertext and the recipient's\n // own X-Wing public key (recomputed from the held seed), exactly as the\n // producer bound them — see the wrap path.\n const kek = hkdfSha256({\n ikm: ss,\n salt: xwingKekSalt({ kemCt: enc, pubR: args.pubR }),\n info: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n length: 32,\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// The recovered CEK plus a defence-in-depth conflict flag. A producer may\n// legitimately address the same recipient (or wrap the same CEK) in several\n// slots, so multiple matching slots are PERMITTED and the first match's CEK is\n// selected. But two matching slots that recover DIFFERENT CEKs (both satisfying\n// their per-slot wrap AEAD) is a commitment collision the §G4 assumption rules\n// out; `cekConflict` flags it so the caller can fail closed. The compare is\n// constant-time; the inner loop visits every slot (constant-time-N), so the\n// flag does not leak match position.\ninterface InnerUnwrapResult {\n readonly cek: Uint8Array;\n readonly slotIdx: number;\n readonly cekConflict: boolean;\n}\n\n// Per-priv inner trial-decrypt loop with slot-index reporting and CEK-conflict\n// detection, KEM-driven. Enters every slot when constantTimeN; every slot\n// attempts the wrap AEAD, so a recipient addressed in multiple slots recovers a\n// candidate CEK from each. The first match's CEK is selected; any later match\n// recovering a CEK that differs (constant-time compare) from the selected one\n// sets `cekConflict`. This follows the spec loop shape:\n//\n// first = ok AND NOT found\n// cek_conflict = cek_conflict OR (ok AND found AND NOT ctEq(cand, selected))\n// selected_CEK = first ? cand : selected\n// found = found OR ok\n//\n// No early break is taken when constantTimeN, so the conflict scan is constant\n// across the whole slot set.\nfunction tryRecipientUnwrapWithIdx(\n envelope: SealedEnvelope,\n recipientSecretKey: Uint8Array,\n constantTimeN: boolean,\n slotsAttemptedOut: { count: number; perPrivCounts?: number[] } | undefined,\n): InnerUnwrapResult | null {\n const n = envelope.slots.length;\n let cek: Uint8Array | null = null;\n let matchedSlotIdx = -1;\n let cekConflict = false;\n\n const recordMatch = (candidate: Uint8Array | null, i: number): void => {\n if (candidate === null) return;\n if (cek === null) {\n // first = ok AND NOT found.\n cek = candidate;\n matchedSlotIdx = i;\n } else if (!compareCt(candidate, cek)) {\n // ok AND found AND NOT ctEq(cand, selected) — a later matching slot whose\n // recovered CEK differs from the already-selected one. Fail closed.\n cekConflict = true;\n }\n };\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 recordMatch(tryX25519Slot({ slot: envelope.slots[i]!, recipientSecretKey, pubRLocal }), i);\n if (cek !== null && !constantTimeN) break;\n }\n } else {\n // Recompute the recipient's own X-Wing public key from the held seed: the\n // hybrid KEK salt binds `pub_R`, so each private key in a multi-key scan\n // MUST re-derive it (a single shared pub_R would compute the wrong KEK for\n // every key but one).\n const pubR = mlkem768x25519Keygen(recipientSecretKey).publicKey;\n for (let i = 0; i < n; i++) {\n if (slotsAttemptedOut !== undefined) {\n slotsAttemptedOut.count = i + 1;\n }\n recordMatch(tryMlkem768X25519Slot({ slot: envelope.slots[i]!, recipientSecretKey, pubR }), i);\n if (cek !== null && !constantTimeN) break;\n }\n }\n return cek === null ? null : { cek, slotIdx: matchedSlotIdx, cekConflict };\n}\n\n// 32-byte slots-transcript hash. The transcript binds the cross-KEM header\n// fields (scheme, path, aead, kem, nonce) to the canonicalised slot set, so the\n// hybrid kem_ct is committed by its bytes (chunk-boundary-invariant). It depends\n// only on the header and the slots, so it is constant across the multi-priv\n// outer loop and the per-slot trial-decrypt loop — callers compute it ONCE and\n// re-key the HMAC from each candidate CEK over this same 32-byte message.\nfunction slotsHashBytes(envelope: SealedEnvelope): Uint8Array {\n return computeSlotsHash({\n kem: envelope.kem,\n nonce: envelope.nonce,\n slots: envelope.slots as ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\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 // Reject a ciphertext at or above the single-shot keystream capacity before\n // any KEM/AEAD work, so an over-large blob never reaches the content open.\n assertCiphertextWithinBound(ciphertext.length);\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 // The slots-transcript hash is constant across both the single-priv MAC check\n // and the multi-priv outer loop — compute it ONCE, then re-key the HMAC from\n // each candidate CEK over this same 32-byte message.\n const slotsHash = slotsHashBytes(envelope);\n\n let matchedCek: Uint8Array | null = null;\n let anyCandidateRecovered = false;\n\n if (hasSingle) {\n const recipientSecretKey = (args as UnwrapArgsSinglePriv).recipientSecretKey;\n const candidate = tryRecipientUnwrapWithIdx(\n envelope,\n recipientSecretKey,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (candidate === null) {\n return { matched: false, reason: 'WRONG_RECIPIENT_KEY' };\n }\n // CEK-conflict defence-in-depth: a later matching slot recovered a CEK that\n // differs from the selected one. Fail closed with the generic tampered-header\n // reason (a commitment collision is a broken/anomalous slot set, not a\n // recipient-key mismatch).\n if (candidate.cekConflict) {\n return { matched: false, reason: 'TAMPERED_HEADER' };\n }\n // Slot-set MAC verification. Use compareCt to\n // avoid leaking byte-position via early-exit on first mismatching byte.\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, slotsHash);\n if (!compareCt(slotsMacCalc, envelope.slots_mac)) {\n return { matched: false, reason: 'TAMPERED_HEADER' };\n }\n matchedCek = candidate.cek;\n } else {\n const recipientSecretKeys = multiPrivKeys!;\n let cekConflict = 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 // A per-priv CEK conflict (two of this priv's slots recovering different\n // CEKs) makes the whole record anomalous regardless of which priv matched\n // the MAC — record it and fail closed after the loop.\n if (candidate.cekConflict) cekConflict = true;\n const cek = candidate.cek;\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, slotsHash);\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 // A CEK conflict on the matching priv fails the record closed, even if its\n // first-slot CEK passed slots_mac.\n if (matchedCek !== null && cekConflict) {\n return { matched: false, reason: 'TAMPERED_HEADER' };\n }\n if (matchedCek === null) {\n return {\n matched: false,\n reason: anyCandidateRecovered ? 'TAMPERED_HEADER' : 'WRONG_RECIPIENT_KEY',\n };\n }\n }\n\n // Content is opened under the derived `payload_key`, with the structured\n // slots-path AAD re-binding the header plus `slots_hash` and `slots_mac`.\n const payloadKey = slotsPayloadKey({ cek: matchedCek, nonce: envelope.nonce });\n const adContent = adContentSlots({\n kem: envelope.kem,\n nonce: envelope.nonce,\n slotsHash,\n slotsMac: envelope.slots_mac,\n });\n try {\n const plaintext = xchacha20Poly1305Decrypt({\n key: payloadKey,\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 slotsHash = slotsHashBytes(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 // CEK-conflict defence-in-depth: this priv recovered different CEKs from two\n // matching slots — an anomalous slot set. Surface it as the generic\n // aead_pass_no_mac_match outcome (the trial-decrypt analogue of the unwrap\n // TAMPERED_HEADER rejection: a CEK opened but the slot set is not trusted),\n // never a clean match.\n if (candidate.cekConflict) {\n anyCandidateRecovered = true;\n continue;\n }\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, slotsHash);\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"]}
|
package/dist/sealed-poe.d.cts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
+
import { C as CanonicalCborValue } from './canonical-DHeJLYDR.cjs';
|
|
2
|
+
|
|
1
3
|
type SealedKem = 'x25519' | 'mlkem768x25519';
|
|
2
4
|
declare function chunkKemCt(value: Uint8Array): Uint8Array[];
|
|
3
5
|
declare function joinKemCt(chunks: ReadonlyArray<Uint8Array>): Uint8Array;
|
|
4
|
-
declare function
|
|
6
|
+
declare function canonicalizeSlots(slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>, kem: SealedKem): CanonicalCborValue;
|
|
5
7
|
|
|
6
8
|
declare const CARDANO_POE_HKDF_INFO_KEK: Uint8Array;
|
|
7
9
|
declare const CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519: Uint8Array;
|
|
@@ -108,7 +110,7 @@ type TrialDecryptOnlyResult = {
|
|
|
108
110
|
declare function eciesSealedPoeUnwrap(args: UnwrapArgs): UnwrapResult;
|
|
109
111
|
declare function eciesSealedPoeTrialDecrypt(args: TrialDecryptOnlyArgs): TrialDecryptOnlyResult;
|
|
110
112
|
|
|
111
|
-
type EciesSealedPoeErrorCode = 'ENC_SLOTS_EMPTY' | 'ENC_SLOTS_REQUIRED' | 'ENC_SLOTS_MAC_REQUIRED' | 'ENC_SLOTS_MAC_INVALID_LENGTH' | 'KEM_EPK_LENGTH_MISMATCH' | 'KEM_CT_LENGTH_MISMATCH' | 'INVALID_CEK_LENGTH' | 'NONCE_LENGTH_MISMATCH' | 'INVALID_EPHEMERAL_SECRET_LENGTH' | 'EPHEMERAL_SECRETS_COUNT_MISMATCH' | 'UNSUPPORTED_ENC_VERSION' | 'UNSUPPORTED_AEAD_ALG' | 'UNSUPPORTED_KEM_ALG' | 'INVALID_ENVELOPE_SHAPE' | 'INVALID_RECIPIENT_KEY' | 'WRAP_LENGTH_MISMATCH';
|
|
113
|
+
type EciesSealedPoeErrorCode = 'ENC_SLOTS_EMPTY' | 'ENC_SLOTS_REQUIRED' | 'ENC_SLOTS_MAC_REQUIRED' | 'ENC_SLOTS_MAC_INVALID_LENGTH' | 'ENC_SLOTS_DUPLICATE_KEM_MATERIAL' | 'ENC_SLOTS_TOO_MANY' | 'ENC_ENVELOPE_TOO_LARGE' | 'KEM_EPK_LENGTH_MISMATCH' | 'KEM_CT_LENGTH_MISMATCH' | 'INVALID_CEK_LENGTH' | 'NONCE_LENGTH_MISMATCH' | 'INVALID_EPHEMERAL_SECRET_LENGTH' | 'EPHEMERAL_SECRETS_COUNT_MISMATCH' | 'UNSUPPORTED_ENC_VERSION' | 'UNSUPPORTED_AEAD_ALG' | 'UNSUPPORTED_KEM_ALG' | 'INVALID_ENVELOPE_SHAPE' | 'INVALID_RECIPIENT_KEY' | 'WRAP_LENGTH_MISMATCH';
|
|
112
114
|
declare class EciesSealedPoeError extends Error {
|
|
113
115
|
readonly code: EciesSealedPoeErrorCode;
|
|
114
116
|
constructor(code: EciesSealedPoeErrorCode, message: string, options?: {
|
|
@@ -116,6 +118,56 @@ declare class EciesSealedPoeError extends Error {
|
|
|
116
118
|
});
|
|
117
119
|
}
|
|
118
120
|
|
|
121
|
+
declare const CARDANO_POE_SLOTS_TRANSCRIPT_PREFIX: Uint8Array;
|
|
122
|
+
declare const CARDANO_POE_HKDF_INFO_PAYLOAD: Uint8Array;
|
|
123
|
+
declare const CARDANO_POE_HKDF_INFO_PAYLOAD_PASSPHRASE: Uint8Array;
|
|
124
|
+
declare const CARDANO_POE_XWING_KEK_SALT_PREFIX: Uint8Array;
|
|
125
|
+
declare const CARDANO_POE_PW_NORM_PROFILE: "cardano-poe-pw-norm-v1";
|
|
126
|
+
declare const MAX_SLOTS = 1024;
|
|
127
|
+
declare const MAX_DECODED_ENVELOPE_BYTES = 65536;
|
|
128
|
+
declare const MAX_SEALED_PLAINTEXT = 274877906880;
|
|
129
|
+
declare const MAX_SEALED_CIPHERTEXT: number;
|
|
130
|
+
declare function assertPlaintextWithinBound(plaintextLength: number): void;
|
|
131
|
+
declare function assertCiphertextWithinBound(ciphertextLength: number): void;
|
|
132
|
+
declare class SealedPayloadTooLargeError extends Error {
|
|
133
|
+
constructor(message: string);
|
|
134
|
+
}
|
|
135
|
+
declare function computeSlotsHash(args: {
|
|
136
|
+
kem: SealedKem;
|
|
137
|
+
nonce: Uint8Array;
|
|
138
|
+
slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>;
|
|
139
|
+
}): Uint8Array;
|
|
140
|
+
declare function adContentSlots(args: {
|
|
141
|
+
kem: SealedKem;
|
|
142
|
+
nonce: Uint8Array;
|
|
143
|
+
slotsHash: Uint8Array;
|
|
144
|
+
slotsMac: Uint8Array;
|
|
145
|
+
}): Uint8Array;
|
|
146
|
+
declare function adContentPassphrase(args: {
|
|
147
|
+
nonce: Uint8Array;
|
|
148
|
+
passphrase: {
|
|
149
|
+
alg: string;
|
|
150
|
+
salt: Uint8Array;
|
|
151
|
+
params: {
|
|
152
|
+
m: number;
|
|
153
|
+
t: number;
|
|
154
|
+
p: number;
|
|
155
|
+
};
|
|
156
|
+
};
|
|
157
|
+
}): Uint8Array;
|
|
158
|
+
declare function slotsPayloadKey(args: {
|
|
159
|
+
cek: Uint8Array;
|
|
160
|
+
nonce: Uint8Array;
|
|
161
|
+
}): Uint8Array;
|
|
162
|
+
declare function passphrasePayloadKey(args: {
|
|
163
|
+
cek: Uint8Array;
|
|
164
|
+
nonce: Uint8Array;
|
|
165
|
+
}): Uint8Array;
|
|
166
|
+
declare function xwingKekSalt(args: {
|
|
167
|
+
kemCt: Uint8Array;
|
|
168
|
+
pubR: Uint8Array;
|
|
169
|
+
}): Uint8Array;
|
|
170
|
+
|
|
119
171
|
interface ParsedSlotShape {
|
|
120
172
|
readonly epk?: Uint8Array | undefined;
|
|
121
173
|
readonly kem_ct?: ReadonlyArray<Uint8Array> | undefined;
|
|
@@ -131,4 +183,4 @@ interface ParsedEnvelopeShape {
|
|
|
131
183
|
}
|
|
132
184
|
declare function sealedEnvelopeFromParsed(enc: ParsedEnvelopeShape): SealedEnvelope | null;
|
|
133
185
|
|
|
134
|
-
export { CARDANO_POE_HKDF_INFO_KEK, CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519, CARDANO_POE_HKDF_INFO_SLOTS_MAC, EciesSealedPoeError, type EciesSealedPoeErrorCode, type Mlkem768X25519Slot, type ParsedEnvelopeShape, type ParsedSlotShape, type RecipientKeyBundle, type SealedEnvelope, type SealedKem, type SealedPoeOutput, type TrialDecryptOnlyArgs, type TrialDecryptOnlyResult, type UnwrapArgs, type UnwrapArgsBundle, type UnwrapArgsMultiPriv, type UnwrapArgsSinglePriv, type UnwrapFailureReason, type UnwrapResult, type WrapArgs, type X25519Slot, chunkKemCt, eciesSealedPoeTrialDecrypt, eciesSealedPoeUnwrap, eciesSealedPoeWrap, joinKemCt, sealedEnvelopeFromParsed,
|
|
186
|
+
export { CARDANO_POE_HKDF_INFO_KEK, CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519, CARDANO_POE_HKDF_INFO_PAYLOAD, CARDANO_POE_HKDF_INFO_PAYLOAD_PASSPHRASE, CARDANO_POE_HKDF_INFO_SLOTS_MAC, CARDANO_POE_PW_NORM_PROFILE, CARDANO_POE_SLOTS_TRANSCRIPT_PREFIX, CARDANO_POE_XWING_KEK_SALT_PREFIX, EciesSealedPoeError, type EciesSealedPoeErrorCode, MAX_DECODED_ENVELOPE_BYTES, MAX_SEALED_CIPHERTEXT, MAX_SEALED_PLAINTEXT, MAX_SLOTS, type Mlkem768X25519Slot, type ParsedEnvelopeShape, type ParsedSlotShape, type RecipientKeyBundle, type SealedEnvelope, type SealedKem, SealedPayloadTooLargeError, type SealedPoeOutput, type TrialDecryptOnlyArgs, type TrialDecryptOnlyResult, type UnwrapArgs, type UnwrapArgsBundle, type UnwrapArgsMultiPriv, type UnwrapArgsSinglePriv, type UnwrapFailureReason, type UnwrapResult, type WrapArgs, type X25519Slot, adContentPassphrase, adContentSlots, assertCiphertextWithinBound, assertPlaintextWithinBound, canonicalizeSlots, chunkKemCt, computeSlotsHash, eciesSealedPoeTrialDecrypt, eciesSealedPoeUnwrap, eciesSealedPoeWrap, joinKemCt, passphrasePayloadKey, sealedEnvelopeFromParsed, slotsPayloadKey, uniformIndexBelow, xwingKekSalt };
|