@cardanowall/sdk-ts 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/utils.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/_crystals.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/ml-kem.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/hybrid.ts","../../../crypto-core/src/kdf/hkdf.ts","../../../crypto-core/src/kem/mlkem768x25519.ts","../../../crypto-core/src/kem/x25519.ts","../../../crypto-core/src/sig/ed25519.ts","../../../crypto-core/src/seed-derive/errors.ts","../../../crypto-core/src/seed-derive/derive.ts","../../../crypto-core/src/recipient/bech32.ts","../../../crypto-core/src/recipient/age-recipient.ts","../../../crypto-core/src/aead/errors.ts","../../../crypto-core/src/aead/chacha20-poly1305.ts","../../../crypto-core/src/aead/xchacha20-poly1305.ts","../../../crypto-core/src/sealed-poe/errors.ts","../../../crypto-core/src/cbor/canonical.ts","../../../crypto-core/src/sealed-poe/slots-codec.ts","../../../crypto-core/src/sealed-poe/wrap.ts","../../../crypto-core/src/util/compare-ct.ts","../../../crypto-core/src/sealed-poe/unwrap.ts","../../src/identity/seed-identity.ts"],"names":["randb","abytes_","opts","N","Q","F","ROOT_OF_UNITY","shake256","abytes","sha3_256","concatBytes","sha256","x25519","hkdfSha256","hkdf","MLKEM768X25519_SEED_LENGTH","x25519PublicKey","ZERO_NONCE_12","EMPTY_SALT","X25519_SECRET_KEY_LENGTH","X25519_PUBLIC_KEY_LENGTH","NONCE_LENGTH","WRAP_LENGTH","SLOTS_MAC_LENGTH","concat","hmac","ed2","sha512"],"mappings":";;;;;;;;;;;;;;;;;;;AAmIA,IAAM,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AACnF,EAAA,OAAO,oBAAA,CAAqB;AAAA,IAC1B,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,YAAY,IAAA,CAAK,UAAA;AAAA,IACjB,kBAAA,EAAoB,0BAAA,CAA2B,IAAA,CAAK,IAAI;AAAA,GACzD,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * Utilities for hex, bytearray and number handling.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport {\n type CHash,\n type TypedArray,\n abytes,\n abytes as abytes_,\n concatBytes,\n isLE,\n randomBytes as randb,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Asserts that a value is a byte array and optionally checks its length.\n * Returns the original reference unchanged on success, and currently also accepts Node `Buffer`\n * values through the upstream validator.\n * This helper throws on malformed input, so APIs that must return `false` need to guard lengths\n * before decoding or before calling it.\n * @example\n * Validate that a value is a byte array with the expected length.\n * ```ts\n * abytes(new Uint8Array([1]), 1);\n * ```\n */\nconst abytesDoc: typeof abytes = abytes;\nexport { abytesDoc as abytes };\n/**\n * Concatenates byte arrays into a new `Uint8Array`.\n * Zero arguments return an empty `Uint8Array`.\n * Invalid segments throw before allocation because each argument is validated first.\n * @example\n * Concatenate two byte arrays into one result.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nconst concatBytesDoc: typeof concatBytes = concatBytes;\nexport { concatBytesDoc as concatBytes };\n/**\n * Returns cryptographically secure random bytes.\n * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable.\n * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation,\n * so negative and fractional values both throw instead of truncating through JS `ToIndex`.\n * @param bytesLength - Number of random bytes to generate.\n * @returns Fresh random bytes.\n * @example\n * Generate a fresh random seed.\n * ```ts\n * const seed = randomBytes(4);\n * ```\n */\nexport const randomBytes: typeof randb = randb;\n\n/**\n * Compares two byte arrays in a length-constant way for equal lengths.\n * Unequal lengths return `false` immediately, and there is no runtime type validation.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns Whether both arrays contain the same bytes.\n * @example\n * Compare two byte arrays for equality.\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies bytes into a fresh `Uint8Array`.\n * Returns a detached plain `Uint8Array` after validating that the input is real bytes.\n * @param bytes - Source bytes.\n * @returns Copy of the input bytes.\n * @example\n * Copy bytes into a fresh array.\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Byte-swaps each 64-bit lane in place.\n * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need\n * this boundary helper before aliasing them as host `Float64Array` lanes.\n * @param arr - Byte buffer whose length is a multiple of 8.\n * @returns The same buffer after in-place 64-bit lane byte swaps.\n * @example\n * Byte-swap one 64-bit lane in place.\n * ```ts\n * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport function byteSwap64<T extends ArrayBufferView>(arr: T): T {\n const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n for (let i = 0; i < bytes.length; i += 8) {\n const a0 = bytes[i + 0];\n const a1 = bytes[i + 1];\n const a2 = bytes[i + 2];\n const a3 = bytes[i + 3];\n bytes[i + 0] = bytes[i + 7];\n bytes[i + 1] = bytes[i + 6];\n bytes[i + 2] = bytes[i + 5];\n bytes[i + 3] = bytes[i + 4];\n bytes[i + 4] = a3;\n bytes[i + 5] = a2;\n bytes[i + 6] = a1;\n bytes[i + 7] = a0;\n }\n return arr;\n}\n/**\n * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian.\n * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as\n * `Float64Array` lanes on the current host.\n * @param arr - Buffer to pass through or swap in place.\n * @returns The same buffer, normalized for Falcon's little-endian table layout.\n * @example\n * Normalize one host-endian buffer for Falcon's float tables.\n * ```ts\n * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport const baswap64If: <T extends ArrayBufferView>(arr: T) => T = isLE\n ? (arr) => arr\n : byteSwap64;\n\n/** Shared key-generation surface for signers and KEMs. */\nexport type CryptoKeys = {\n /** Optional metadata about the algorithm family or variant. */\n info?: { type?: string };\n /** Public byte lengths for the exported key material. */\n lengths: { seed?: number; publicKey?: number; secretKey?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: TArg<Uint8Array>) => {\n secretKey: TRet<Uint8Array>;\n publicKey: TRet<Uint8Array>;\n };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/** Verification options shared by the signature APIs. */\nexport type VerOpts = {\n /** Optional application-defined context string. */\n context?: Uint8Array;\n};\n/** Signing options shared by the signature APIs. */\nexport type SigOpts = VerOpts & {\n // Compatibility with @noble/curves: false to disable, enabled by default, user can pass U8A\n /** Optional extra entropy or `false` to disable randomized signing. */\n extraEntropy?: Uint8Array | false;\n};\n\n/**\n * Validates that an options bag is a plain object.\n * @param opts - Options object to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate that an options bag is a plain object.\n * ```ts\n * validateOpts({});\n * ```\n */\nexport function validateOpts(opts: object): void {\n // Arrays silently passed here before, but these call sites expect named option-bag fields.\n if (Object.prototype.toString.call(opts) !== '[object Object]')\n throw new TypeError('expected valid options object');\n}\n\n/**\n * Validates common verification options.\n * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support\n * further after this shared plain-object gate.\n * @param opts - Verification options. See {@link VerOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common verification options.\n * ```ts\n * validateVerOpts({ context: new Uint8Array([1]) });\n * ```\n */\nexport function validateVerOpts(opts: TArg<VerOpts>): void {\n validateOpts(opts);\n if (opts.context !== undefined) abytes(opts.context, undefined, 'opts.context');\n}\n\n/**\n * Validates common signing options.\n * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific\n * restrictions are enforced later by callers.\n * @param opts - Signing options. See {@link SigOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common signing options.\n * ```ts\n * validateSigOpts({ extraEntropy: new Uint8Array([1]) });\n * ```\n */\nexport function validateSigOpts(opts: TArg<SigOpts>): void {\n validateVerOpts(opts);\n if (opts.extraEntropy !== false && opts.extraEntropy !== undefined)\n abytes(opts.extraEntropy, undefined, 'opts.extraEntropy');\n}\n\n/** Generic signature interface with key generation, signing, and verification. */\nexport type Signer = CryptoKeys & {\n /** Public byte lengths for signatures and signing randomness. */\n lengths: { signRand?: number; signature?: number };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing options.\n * @returns Signature bytes.\n */\n sign: (\n msg: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts?: TArg<SigOpts>\n ) => TRet<Uint8Array>;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @param opts - Optional verification options.\n * @returns `true` when the signature is valid, `false` when all inputs are well-formed but the\n * signature check does not pass. Some implementations also treat malformed signature encodings as\n * a verification failure and return `false`.\n * @throws On malformed API arguments or unsupported verification options.\n */\n verify: (\n sig: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n opts?: TArg<VerOpts>\n ) => boolean;\n};\n\n/** Generic key encapsulation mechanism interface. */\nexport type KEM = CryptoKeys & {\n /** Public byte lengths for ciphertexts and optional message randomness. */\n lengths: { cipherText?: number; msg?: number; msgRand?: number };\n /**\n * Encapsulate one shared secret to a recipient public key.\n * @param publicKey - Recipient public key bytes.\n * @param msg - Optional caller-provided randomness/message seed.\n * @returns Ciphertext plus shared secret.\n */\n encapsulate: (\n publicKey: TArg<Uint8Array>,\n msg?: TArg<Uint8Array>\n ) => {\n cipherText: TRet<Uint8Array>;\n sharedSecret: TRet<Uint8Array>;\n };\n /**\n * Recover the shared secret from a ciphertext and recipient secret key.\n * @param cipherText - Ciphertext bytes.\n * @param secretKey - Recipient secret key bytes.\n * @returns Decapsulated shared secret.\n */\n decapsulate: (cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/** Bidirectional encoder/decoder interface. */\nexport interface Coder<F, T> {\n /**\n * Serialize one value.\n * @param from - Value to encode.\n * @returns Encoded representation.\n */\n encode(from: F): T;\n /**\n * Parse one serialized value.\n * @param to - Encoded representation.\n * @returns Decoded value.\n */\n decode(to: T): F;\n}\n\n/** Encoder/decoder interface specialized for byte arrays. */\nexport interface BytesCoder<T> extends Coder<T, Uint8Array> {\n /**\n * Serialize one value into bytes.\n * @param data - Value to encode.\n * @returns Encoded bytes.\n */\n encode: (data: T) => Uint8Array;\n /**\n * Parse one byte array into a value.\n * @param bytes - Encoded bytes.\n * @returns Decoded value.\n */\n decode: (bytes: Uint8Array) => T;\n}\n\n/** Fixed-length byte encoder/decoder. */\nexport type BytesCoderLen<T> = BytesCoder<T> & { bytesLen: number };\n\n// nano-packed, because struct encoding is hard.\ntype UnCoder<T> = T extends BytesCoder<infer U> ? U : never;\ntype SplitOut<T extends (number | BytesCoderLen<any>)[]> = {\n [K in keyof T]: T[K] extends number ? Uint8Array : UnCoder<T[K]>;\n};\n/**\n * Builds a fixed-layout coder from byte lengths and nested coders.\n * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that\n * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder`\n * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards\n * caller-owned bytes, it must do so only after detaching them into a disposable copy.\n * @param label - Label used in validation errors.\n * @param lengths - Field lengths or nested coders.\n * @returns Composite fixed-length coder.\n * @example\n * Build a fixed-layout coder from byte lengths and nested coders.\n * ```ts\n * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]);\n * ```\n */\nexport function splitCoder<T extends (number | BytesCoderLen<any>)[]>(\n label: string,\n ...lengths: T\n): TRet<BytesCoder<SplitOut<T>> & { bytesLen: number }> {\n const getLength = (c: TArg<number | BytesCoderLen<any>>) =>\n typeof c === 'number' ? c : (c as BytesCoderLen<any>).bytesLen;\n const bytesLen: number = lengths.reduce((sum: number, a) => sum + getLength(a), 0);\n return {\n bytesLen,\n encode: (bufs: T) => {\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < lengths.length; i++) {\n const c = lengths[i];\n const l = getLength(c);\n const b: Uint8Array = typeof c === 'number' ? (bufs[i] as any) : c.encode(bufs[i]);\n abytes_(b, l, label);\n res.set(b, pos);\n if (typeof c !== 'number') b.fill(0); // clean\n pos += l;\n }\n return res;\n },\n decode: (buf: TArg<Uint8Array>) => {\n abytes_(buf, bytesLen, label);\n const res = [];\n for (const c of lengths) {\n const l = getLength(c);\n const b = buf.subarray(0, l);\n res.push(typeof c === 'number' ? b : c.decode(b));\n buf = buf.subarray(l);\n }\n return res as SplitOut<T>;\n },\n } as any;\n}\n// nano-packed.array (fixed size)\n/**\n * Builds a fixed-length vector coder from another fixed-length coder.\n * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder.\n * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into\n * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned\n * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts\n * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes.\n * @param c - Element coder.\n * @param vecLen - Number of elements in the vector.\n * @returns Fixed-length vector coder.\n * @example\n * Build a fixed-length vector coder from another fixed-length coder.\n * ```ts\n * vecCoder(\n * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 },\n * 2\n * ).encode([1, 2]);\n * ```\n */\nexport function vecCoder<T>(c: TArg<BytesCoderLen<T>>, vecLen: number): TRet<BytesCoderLen<T[]>> {\n const coder = c as BytesCoderLen<T>;\n const bytesLen = vecLen * coder.bytesLen;\n return {\n bytesLen,\n encode: (u: TArg<T[]>): TRet<Uint8Array> => {\n if (u.length !== vecLen)\n throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < u.length; i++) {\n const b = coder.encode(u[i] as T);\n res.set(b, pos);\n b.fill(0); // clean\n pos += b.length;\n }\n return res as TRet<Uint8Array>;\n },\n decode: (a: TArg<Uint8Array>): TRet<T[]> => {\n abytes_(a, bytesLen);\n const r: T[] = [];\n for (let i = 0; i < a.length; i += coder.bytesLen)\n r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));\n return r as TRet<T[]>;\n },\n } as any;\n}\n\n/**\n * Overwrites supported typed-array inputs with zeroes in place.\n * Accepts direct typed arrays and one-level arrays of them.\n * @param list - Typed arrays or one-level lists of typed arrays to clear.\n * @example\n * Overwrite typed arrays with zeroes.\n * ```ts\n * const buf = Uint8Array.of(1, 2, 3);\n * cleanBytes(buf);\n * ```\n */\nexport function cleanBytes(...list: (TypedArray | TypedArray[])[]): void {\n for (const t of list) {\n if (Array.isArray(t)) for (const b of t) b.fill(0);\n else t.fill(0);\n }\n}\n\n/**\n * Creates a 32-bit mask with the lowest `bits` bits set.\n * @param bits - Number of low bits to keep.\n * @returns Bit mask with `bits` ones.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Create a low-bit mask for packed-field operations.\n * ```ts\n * const mask = getMask(4);\n * ```\n */\nexport function getMask(bits: number): number {\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new RangeError(`expected bits in [0..32], got ${bits}`);\n // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask.\n return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0;\n}\n\n/** Shared empty byte array used as the default context. */\nexport const EMPTY: TRet<Uint8Array> = /* @__PURE__ */ Uint8Array.of();\n\n/**\n * Builds the domain-separated message payload for the pure sign/verify paths.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated message payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated payload before direct signing.\n * ```ts\n * const payload = getMessage(new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessage(msg: TArg<Uint8Array>, ctx: TArg<Uint8Array> = EMPTY): TRet<Uint8Array> {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);\n}\n\n// DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the\n// FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128,\n// SHAKE256, or another approved hash/XOF under that subtree.\n// 06 09 60 86 48 01 65 03 04 02\nconst oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]);\n\n/**\n * Validates that a hash exposes a NIST hash OID and enough collision resistance.\n * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST\n * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough.\n * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend\n * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes.\n * @param hash - Hash function to validate.\n * @param requiredStrength - Minimum required collision-resistance strength in bits.\n * @throws If the hash metadata or collision resistance is insufficient. {@link Error}\n * @example\n * Validate that a hash exposes a NIST hash OID and enough collision resistance.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { checkHash } from '@noble/post-quantum/utils.js';\n * checkHash(sha256, 128);\n * ```\n */\nexport function checkHash(hash: CHash, requiredStrength: number = 0): void {\n if (!hash.oid || !equalBytes(hash.oid.subarray(0, 10), oidNistP))\n throw new Error('hash.oid is invalid: expected NIST hash');\n // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST\n // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is\n // the tighter runtime check, so enforce that lower bound here.\n const collisionResistance = (hash.outputLen * 8) / 2;\n if (requiredStrength > collisionResistance) {\n throw new Error(\n 'Pre-hash security strength too low: ' +\n collisionResistance +\n ', required: ' +\n requiredStrength\n );\n }\n}\n\n/**\n * Builds the domain-separated prehash payload for the prehash sign/verify paths.\n * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper\n * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param hash - Prehash function.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated prehash payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated prehash payload for external hashing.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { getMessagePrehash } from '@noble/post-quantum/utils.js';\n * getMessagePrehash(sha256, new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessagePrehash(\n hash: CHash,\n msg: TArg<Uint8Array>,\n ctx: TArg<Uint8Array> = EMPTY\n): TRet<Uint8Array> {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n const hashed = hash(msg);\n return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid!, hashed);\n}\n","/**\n * Internal methods for lattice-based ML-KEM and ML-DSA.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { FFTCore, reverseBits } from '@noble/curves/abstract/fft.js';\nimport { shake128, shake256 } from '@noble/hashes/sha3.js';\nimport type { TypedArray } from '@noble/hashes/utils.js';\nimport {\n type BytesCoderLen,\n cleanBytes,\n type Coder,\n getMask,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/** Extendable-output reader used by the CRYSTALS implementations. */\nexport type XOF = (\n seed: Uint8Array,\n blockLen?: number\n) => {\n /**\n * Read diagnostic counters for the current XOF session.\n * @returns Current call and XOF block counters.\n */\n stats: () => { calls: number; xofs: number };\n /**\n * Select one `(x, y)` coordinate pair and get a block reader for it.\n * Only one coordinate stream is live at a time: a later `get(...)` call rebinds the shared\n * SHAKE state and invalidates older readers.\n * Each squeeze aliases one mutable internal output buffer, so callers must copy blocks they\n * want to retain before the next read.\n * @param x - First matrix coordinate.\n * @param y - Second matrix coordinate.\n * @returns Lazy block reader for that coordinate pair.\n */\n get: (x: number, y: number) => () => Uint8Array; // return block aligned to blockLen and 3\n /** Wipe any buffered state once the reader is no longer needed. */\n clean: () => void;\n};\n\n/** CRYSTALS (ml-kem, ml-dsa) options */\n/** Shared polynomial and NTT parameters for CRYSTALS algorithms. */\nexport type CrystalOpts<T extends TypedArray> = {\n /**\n * Allocate one zeroed polynomial/vector container.\n * @param n - Number of coefficients to allocate.\n * @returns Fresh typed container.\n */\n newPoly: TypedCons<T>;\n /** Polynomial size, typically `256`. */\n N: number;\n /** Prime modulus used for all coefficient arithmetic. */\n Q: number;\n /** Inverse transform normalization factor:\n * `256**-1 mod q` for Dilithium, `128**-1 mod q` for Kyber.\n */\n F: number;\n /** Principal root of unity for the transform domain. */\n ROOT_OF_UNITY: number;\n /** Number of bits used for bit-reversal ordering. */\n brvBits: number;\n /** `true` for Kyber/ML-KEM mode, `false` for Dilithium/ML-DSA mode. */\n isKyber: boolean;\n};\n\n/** Constructor function for typed polynomial containers. */\nexport type TypedCons<T extends TypedArray> = (n: number) => T;\n\ntype Crystals<T extends TypedArray> = {\n mod: (a: number, modulo?: number) => number;\n smod: (a: number, modulo?: number) => number;\n nttZetas: T;\n NTT: {\n /** Forward transform in place. Mutates and returns `r`. */\n encode: (r: T) => T;\n /** Inverse transform in place. Mutates and returns `r`. */\n decode: (r: T) => T;\n };\n bitsCoder: (d: number, c: Coder<number, number>) => BytesCoderLen<T>;\n};\n\n/**\n * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes.\n * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}.\n * @returns CRYSTALS arithmetic and encoding helpers.\n * @example\n * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set.\n * ```ts\n * const crystals = genCrystals({\n * newPoly: (n) => new Uint16Array(n),\n * N: 256,\n * Q: 3329,\n * F: 3303,\n * ROOT_OF_UNITY: 17,\n * brvBits: 7,\n * isKyber: true,\n * });\n * const reduced = crystals.mod(-1);\n * ```\n */\nexport const genCrystals = <T extends TypedArray>(opts: CrystalOpts<T>): TRet<Crystals<T>> => {\n // isKyber: true means Kyber, false means Dilithium\n const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;\n // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by\n // FIPS 203 §2.3 / FIPS 204 §2.3 before downstream mod-q arithmetic.\n const mod = (a: number, modulo = Q): number => {\n const result = a % modulo | 0;\n return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0;\n };\n // FIPS 204 §7.4 uses the centered `mod ±` representative for low bits, keeping the\n // positive midpoint when `modulo` is even.\n // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`.\n const smod = (a: number, modulo = Q): number => {\n const r = mod(a, modulo) | 0;\n return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0;\n };\n // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while\n // Dilithium uses the FIPS 204 §7.5 / Appendix B `BitRev_8` zetas table over all 256 entries.\n function getZettas() {\n const out = newPoly(N);\n for (let i = 0; i < N; i++) {\n const b = reverseBits(i, brvBits);\n const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);\n out[i] = Number(p) | 0;\n }\n return out;\n }\n const nttZetas = getZettas();\n\n // Number-Theoretic Transform\n // Explained: https://electricdusk.com/ntt.html\n\n // Kyber has slightly different params, since there is no 512th primitive root of unity mod q,\n // only 256th primitive root of unity mod. Which also complicates MultiplyNTT.\n\n const field = {\n add: (a: number, b: number) => mod((a | 0) + (b | 0)) | 0,\n sub: (a: number, b: number) => mod((a | 0) - (b | 0)) | 0,\n mul: (a: number, b: number) => mod((a | 0) * (b | 0)) | 0,\n inv: (_a: number) => {\n throw new Error('not implemented');\n },\n };\n const nttOpts = {\n N,\n roots: nttZetas as any,\n invertButterflies: true,\n skipStages: isKyber ? 1 : 0,\n brp: false,\n };\n const dif = FFTCore(field, { dit: false, ...nttOpts });\n const dit = FFTCore(field, { dit: true, ...nttOpts });\n const NTT = {\n encode: (r: T): T => {\n return dif(r) as any;\n },\n decode: (r: T): T => {\n dit(r as any);\n // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14\n // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`.\n // kyber uses 128 here, because brv && stuff\n for (let i = 0; i < r.length; i++) r[i] = mod(F * r[i]);\n return r;\n },\n };\n // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode /\n // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers.\n const bitsCoder = (d: number, c: Coder<number, number>): TRet<BytesCoderLen<T>> => {\n const mask = getMask(d);\n const bytesLen = d * (N / 8);\n return {\n bytesLen,\n encode: (poly_: TArg<T>): TRet<Uint8Array> => {\n const poly = poly_ as T;\n const r = new Uint8Array(bytesLen);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {\n buf |= (c.encode(poly[i]) & mask) << bufLen;\n bufLen += d;\n for (; bufLen >= 8; bufLen -= 8, buf >>= 8) r[pos++] = buf & getMask(bufLen);\n }\n return r as TRet<Uint8Array>;\n },\n decode: (bytes: TArg<Uint8Array>): TRet<T> => {\n const r = newPoly(N);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {\n buf |= bytes[i] << bufLen;\n bufLen += 8;\n for (; bufLen >= d; bufLen -= d, buf >>= d) r[pos++] = c.decode(buf & mask);\n }\n return r as TRet<T>;\n },\n } as TRet<BytesCoderLen<T>>;\n };\n\n return {\n mod,\n smod,\n nttZetas: nttZetas as TRet<T>,\n NTT: {\n encode: (r: TArg<T>): TRet<T> => NTT.encode(r as T) as TRet<T>,\n decode: (r: TArg<T>): TRet<T> => NTT.decode(r as T) as TRet<T>,\n },\n bitsCoder: bitsCoder as TRet<Crystals<T>>['bitsCoder'],\n };\n};\n\nconst createXofShake =\n (shake: typeof shake128): TRet<XOF> =>\n (seed: TArg<Uint8Array>, blockLen?: number) => {\n if (!blockLen) blockLen = shake.blockLen;\n // Optimizations that won't mater:\n // - cached seed update (two .update(), on start and on the end)\n // - another cache which cloned into working copy\n\n // Faster than multiple updates, since seed less than blockLen\n const _seed = new Uint8Array(seed.length + 2);\n _seed.set(seed);\n const seedLen = seed.length;\n const buf = new Uint8Array(blockLen); // == shake128.blockLen\n let h = shake.create({});\n let calls = 0;\n let xofs = 0;\n return {\n stats: () => ({ calls, xofs }),\n get: (x: number, y: number) => {\n // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate\n // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`.\n _seed[seedLen + 0] = x;\n _seed[seedLen + 1] = y;\n h.destroy();\n h = shake.create({}).update(_seed);\n calls++;\n return () => {\n xofs++;\n return h.xofInto(buf) as TRet<Uint8Array>;\n };\n },\n clean: () => {\n h.destroy();\n cleanBytes(buf, _seed);\n },\n };\n };\n\n/**\n * SHAKE128-based extendable-output reader factory used by ML-KEM.\n * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously\n * returned readers, and each squeeze reuses one mutable internal output buffer.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-KEM SHAKE128 matrix expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF128 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF128(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF128: TRet<XOF> = /* @__PURE__ */ createXofShake(shake128);\n/**\n * SHAKE256-based extendable-output reader factory used by ML-DSA.\n * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned\n * readers, and reuses one mutable internal output buffer for each squeeze.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-DSA SHAKE256 coefficient expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF256 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF256(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF256: TRet<XOF> = /* @__PURE__ */ createXofShake(shake256);\n","/**\n * ML-KEM: Module Lattice-based Key Encapsulation Mechanism from\n * [FIPS-203](https://csrc.nist.gov/pubs/fips/203/ipd). A.k.a. CRYSTALS-Kyber.\n *\n * Key encapsulation is similar to DH / ECDH (think X25519), with important differences:\n * * Unlike in ECDH, we can't verify if it was \"Bob\" who've sent the shared secret\n * * Unlike ECDH, it is probabalistic and relies on quality of randomness (CSPRNG).\n * * Decapsulation never throws an error, even when shared secret was\n * encrypted by a different public key. It will just return a different shared secret.\n *\n * There are some concerns with regards to security: see\n * [djb blog](https://blog.cr.yp.to/20231003-countcorrectly.html) and\n * [mailing list](https://groups.google.com/a/list.nist.gov/g/pqc-forum/c/W2VOzy0wz_E).\n *\n * Has similar internals to ML-DSA, but their keys and params are different.\n *\n * Check out [official site](https://www.pq-crystals.org/kyber/resources.shtml),\n * [repo](https://github.com/pq-crystals/kyber),\n * [spec](https://datatracker.ietf.org/doc/draft-cfrg-schwabe-kyber/).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { sha3_256, sha3_512, shake256 } from '@noble/hashes/sha3.js';\nimport { type CHash, swap32IfBE, u32 } from '@noble/hashes/utils.js';\nimport { genCrystals, type XOF, XOF128 } from './_crystals.ts';\nimport {\n abytes,\n cleanBytes,\n type Coder,\n copyBytes,\n equalBytes,\n getMask,\n type KEM,\n randomBytes,\n splitCoder,\n type TArg,\n type TRet,\n vecCoder,\n} from './utils.ts';\n\n/** Key encapsulation mechanism interface */\n\nconst N = 256; // Kyber (not FIPS-203) supports different lengths, but all std modes were using 256\nconst Q = 3329; // 13*(2**8)+1, modulo prime\nconst F = 3303; // 3303 ≡ 128**(−1) mod q (FIPS-203)\nconst ROOT_OF_UNITY = 17; // ζ = 17 ∈ Zq is a primitive 256-th root of unity modulo Q. ζ**128 ≡−1\n// treeshake: keep genCrystals behind the object so PARAMS-only bundles can drop it entirely.\n// Shared CRYSTALS helper in the ML-KEM branch: Kyber mode, 7-bit bit-reversal,\n// and Uint16Array polys because current coefficients stay reduced modulo q.\nconst crystals = /* @__PURE__ */ genCrystals({\n N,\n Q,\n F,\n ROOT_OF_UNITY,\n newPoly: (n: number): TRet<Uint16Array> => new Uint16Array(n) as TRet<Uint16Array>,\n brvBits: 7,\n isKyber: true,\n});\n\n/** FIPS 203: 7. Parameter Sets */\n/** Public ML-KEM parameter-set description. */\nexport type KEMParam = {\n /** Polynomial size. */\n N: number;\n /** Module rank. */\n K: number;\n /** Prime modulus. */\n Q: number;\n /** CBD parameter used for secret-key noise. */\n ETA1: number;\n /** CBD parameter used for error noise. */\n ETA2: number;\n /** Compression width for the `u` vector. */\n du: number;\n /** Compression width for the `v` polynomial. */\n dv: number;\n /** Required strength of the randomness source in bits. */\n RBGstrength: number;\n};\n/** Internal params of ML-KEM versions */\n// prettier-ignore\n/** Built-in ML-KEM parameter presets keyed by the public export names\n * `ml_kem512` / `ml_kem768` / `ml_kem1024`.\n * `RBGstrength` is Table 2's required randomness-source strength in bits,\n * not a generic security label.\n */\nexport const PARAMS: Record<string, KEMParam> = /* @__PURE__ */ (() =>\n Object.freeze({\n 512: Object.freeze({ N, Q, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),\n 768: Object.freeze({ N, Q, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),\n 1024: Object.freeze({ N, Q, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 }),\n } as const))();\n\n// FIPS-203: compress/decompress\nconst compress = (d: number): Coder<number, number> => {\n // d=12 is the ByteEncode12/ByteDecode12 path, not lossy compression.\n // ByteDecode12 interprets each 12-bit word modulo q; without that reduction the public-key\n // modulus check in encapsulate() becomes a no-op for malformed coefficients like 4095.\n if (d >= 12) return { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) };\n // Comments map to python implementation in RFC (draft-cfrg-schwabe-kyber)\n // const round = (i: number) => Math.floor(i + 0.5) | 0;\n const a = 2 ** (d - 1);\n return {\n // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).\n encode: (i: number) => ((i << d) + Q / 2) / Q,\n // const decompress = (i: number) => round((Q / 2 ** d) * i);\n decode: (i: number) => (i * Q + a) >>> d,\n };\n};\n\n// Raw ByteEncode_d / ByteDecode_d from FIPS 203 operate on d-bit words directly.\n// That differs from `polyCoder(d)` for d<12, where noble folds packing together with the lossy\n// ciphertext compression step used by u/v. Tests that exercise the spec's raw packing surface need\n// this exact non-lossy variant instead.\nconst byteCoder = (d: number) =>\n crystals.bitsCoder(\n d,\n d === 12\n ? { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) }\n : { encode: (i: number) => i, decode: (i: number) => i }\n );\n\n// NOTE: we merge encoding and compress because it is faster, also both require same d param\n// d=12 is the ByteEncode12/ByteDecode12 path rather than compression, and caller-side\n// public-key modulus checks route through this helper's decode/encode roundtrip.\n// Converts between bytes and d-bits compressed representation.\n// Kinda like convertRadix2 from @scure/base.\n// decode(encode(t)) == t, but there is loss of information on encode(decode(t))\nconst polyCoder = (d: number) => (d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d)));\n\n// Poly is mod Q, so 12 bits\ntype Poly = Uint16Array;\n\nfunction polyAdd(a_: TArg<Poly>, b_: TArg<Poly>) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] + b[i]); // a += b\n}\nfunction polySub(a_: TArg<Poly>, b_: TArg<Poly>) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] - b[i]); // a -= b\n}\n\n// FIPS-203: Computes the product of two degree-one polynomials with respect to a quadratic modulus\nfunction BaseCaseMultiply(a0: number, a1: number, b0: number, b1: number, zeta: number) {\n // `zeta` here is Algorithm 11's γ = ζ^(2BitRev_7(i)+1).\n const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);\n const c1 = crystals.mod(a0 * b1 + a1 * b0);\n return { c0, c1 };\n}\n\n// FIPS-203: Computes the product (in the ring Tq) of two NTT representations.\n// Works in place on `f`; `g` is read-only and both inputs must already be in NTT form.\nfunction MultiplyNTTs(f_: TArg<Poly>, g_: TArg<Poly>): TRet<Poly> {\n const f = f_ as Poly;\n const g = g_ as Poly;\n for (let i = 0; i < N / 2; i++) {\n let z = crystals.nttZetas[64 + (i >> 1)];\n if (i & 1) z = -z;\n const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);\n f[2 * i + 0] = c0;\n f[2 * i + 1] = c1;\n }\n return f as TRet<Poly>;\n}\n\ntype PRF = (l: number, key: Uint8Array, nonce: number) => Uint8Array;\n\ntype XofGet = ReturnType<ReturnType<XOF>['get']>;\n\ntype KyberOpts = KEMParam & {\n HASH256: CHash;\n HASH512: CHash;\n KDF: CHash<any, { dkLen?: number }>;\n XOF: XOF; // (seed: Uint8Array, len: number, x: number, y: number) => Uint8Array;\n PRF: PRF;\n};\n\n// Return poly in NTT representation\nfunction SampleNTT(xof_: TArg<XofGet>): TRet<Poly> {\n const xof = xof_ as XofGet;\n // The reader must already bind the Algorithm 7 seed||j||i bytes\n // and return block lengths divisible by 3.\n const r: Poly = new Uint16Array(N);\n for (let j = 0; j < N; ) {\n const b = xof();\n if (b.length % 3) throw new Error('SampleNTT: unaligned block');\n for (let i = 0; j < N && i + 3 <= b.length; i += 3) {\n const d1 = ((b[i + 0] >> 0) | (b[i + 1] << 8)) & 0xfff;\n const d2 = ((b[i + 1] >> 4) | (b[i + 2] << 4)) & 0xfff;\n if (d1 < Q) r[j++] = d1;\n if (j < N && d2 < Q) r[j++] = d2;\n }\n }\n return r as TRet<Poly>;\n}\n\n// Sampling from the centered binomial distribution\n// Returns poly with small coefficients (noise/errors) stored modulo q in ordinary coefficient form.\n// Current callers only use Table 2 eta values {2,3} and PRF outputs of exactly 64*eta bytes.\nconst sampleCBDBytes = (buf: TArg<Uint8Array>, eta: number): TRet<Poly> => {\n const r: Poly = new Uint16Array(N);\n // CBD consumes the PRF bitstream in little-endian byte order; normalize the word view on BE,\n // then swap it back so callers still observe `buf` as read-only.\n const b32 = u32(buf);\n swap32IfBE(b32);\n let len = 0;\n for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {\n let b = b32[i];\n for (let j = 0; j < 32; j++) {\n bb += b & 1;\n b >>= 1;\n len += 1;\n if (len === eta) {\n t0 = bb;\n bb = 0;\n } else if (len === 2 * eta) {\n r[p++] = crystals.mod(t0 - bb);\n bb = 0;\n len = 0;\n }\n }\n }\n swap32IfBE(b32);\n if (len) throw new Error(`sampleCBD: leftover bits: ${len}`);\n return r as TRet<Poly>;\n};\n\nfunction sampleCBD(\n PRF_: TArg<PRF>,\n seed: TArg<Uint8Array>,\n nonce: number,\n eta: number\n): TRet<Poly> {\n const PRF = PRF_ as PRF;\n return sampleCBDBytes(PRF((eta * N) / 4, seed, nonce), eta);\n}\n\n// K-PKE\n// Internal ML-KEM subroutine only: exact 32-byte `seed` / `msg` inputs\n// come from Algorithms 13-15, and the helper mutates decoded temporary\n// polynomials in place while leaving caller byte arrays unchanged.\nconst genKPKE = (opts_: TArg<KyberOpts>) => {\n const opts = opts_ as KyberOpts;\n const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts;\n const poly1 = polyCoder(1);\n const polyV = polyCoder(dv);\n const polyU = polyCoder(du);\n const publicCoder = splitCoder('publicKey', vecCoder(polyCoder(12), K), 32);\n const secretCoder = vecCoder(polyCoder(12), K);\n const cipherCoder = splitCoder('ciphertext', vecCoder(polyU, K), polyV);\n const seedCoder = splitCoder('seed', 32, 32);\n return {\n secretCoder,\n lengths: {\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n cipherText: cipherCoder.bytesLen,\n },\n keygen: (seed: TArg<Uint8Array>) => {\n abytes(seed, 32, 'seed');\n const seedDst = new Uint8Array(33);\n seedDst.set(seed);\n // FIPS 203 Algorithm 13 appends the parameter-set byte `k`\n // before `G(d || k)`, so expanding the same 32-byte seed\n // under a different ML-KEM parameter set yields unrelated keys.\n seedDst[32] = K;\n const seedHash = HASH512(seedDst);\n\n const [rho, sigma] = seedCoder.decode(seedHash);\n const sHat: Poly[] = [];\n const tHat: Poly[] = [];\n for (let i = 0; i < K; i++) sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));\n const x = XOF(rho);\n for (let i = 0; i < K; i++) {\n const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));\n for (let j = 0; j < K; j++) {\n const aji = SampleNTT(x.get(j, i)); // A[i][j], inplace\n polyAdd(e, MultiplyNTTs(aji, sHat[j]));\n }\n tHat.push(e); // t ← A ◦ s + e\n }\n x.clean();\n const res = {\n publicKey: publicCoder.encode([tHat, rho]),\n secretKey: secretCoder.encode(sHat),\n };\n cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);\n return res;\n },\n encrypt: (\n publicKey: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n seed: TArg<Uint8Array>\n ): TRet<Uint8Array> => {\n const [tHat, rho] = publicCoder.decode(publicKey);\n const rHat = [];\n for (let i = 0; i < K; i++) rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));\n const x = XOF(rho);\n const tmp2 = new Uint16Array(N);\n const u = [];\n for (let i = 0; i < K; i++) {\n const e1 = sampleCBD(PRF, seed, K + i, ETA2);\n const tmp = new Uint16Array(N);\n for (let j = 0; j < K; j++) {\n const aij = SampleNTT(x.get(i, j)); // A[j][i], inplace transpose access\n polyAdd(tmp, MultiplyNTTs(aij, rHat[j])); // t += aij * rHat[j]\n }\n polyAdd(e1, crystals.NTT.decode(tmp)); // e1 += tmp\n u.push(e1);\n polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i])); // t2 += tHat[i] * rHat[i]\n cleanBytes(tmp);\n }\n x.clean();\n const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);\n polyAdd(e2, crystals.NTT.decode(tmp2)); // e2 += tmp2\n const v = poly1.decode(msg); // encode plaintext m into polynomial v\n polyAdd(v, e2); // v += e2\n cleanBytes(tHat, rHat, tmp2, e2);\n return cipherCoder.encode([u, v]) as TRet<Uint8Array>;\n },\n decrypt: (cipherText: TArg<Uint8Array>, privateKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n const [u, v] = cipherCoder.decode(cipherText);\n const sk = secretCoder.decode(privateKey); // s ← ByteDecode_12(dkPKE)\n const tmp = new Uint16Array(N);\n // tmp += sk[i] * u[i]\n for (let i = 0; i < K; i++) polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));\n polySub(v, crystals.NTT.decode(tmp)); // w = v' - tmp\n cleanBytes(tmp, sk, u);\n return poly1.encode(v) as TRet<Uint8Array>;\n },\n };\n};\n\n/**\n * Public ML-KEM wrapper over the internal K-PKE subroutine.\n * `keygen(seed)` and `encapsulate(publicKey, msg)` are deterministic/test-oriented hooks that map\n * more directly to Algorithms 16-17 than to the pure no-input / random-internal Algorithms 19-20.\n * decapsulate() tries to follow the Algorithms 18/21 implicit-reject structure as closely as\n * practical here by re-encrypting, comparing ciphertexts, returning `Khat` on match or `Kbar` on\n * mismatch, and zeroizing the non-returned shared-secret candidate; JS/JIT still provides no\n * constant-time guarantees for that path.\n */\nfunction createKyber(opts: TArg<KyberOpts>): TRet<KEM> {\n const rawOpts = opts as KyberOpts;\n const KPKE = genKPKE(rawOpts);\n const { HASH256, HASH512, KDF } = rawOpts;\n const { secretCoder: KPKESecretCoder, lengths } = KPKE;\n const secretCoder = splitCoder('secretKey', lengths.secretKey, lengths.publicKey, 32, 32);\n const msgLen = 32;\n const seedLen = 64;\n const kemLengths = Object.freeze({\n ...lengths,\n seed: 64,\n msg: msgLen,\n msgRand: msgLen,\n secretKey: secretCoder.bytesLen,\n });\n return Object.freeze({\n info: Object.freeze({ type: 'ml-kem' }),\n lengths: kemLengths,\n keygen: (seed: TArg<Uint8Array> = randomBytes(seedLen)) => {\n abytes(seed, seedLen, 'seed');\n const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));\n const publicKeyHash = HASH256(publicKey);\n // (dkPKE||ek||H(ek)||z)\n const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);\n cleanBytes(sk, publicKeyHash);\n return {\n publicKey: publicKey as TRet<Uint8Array>,\n secretKey: secretKey as TRet<Uint8Array>,\n };\n },\n getPublicKey: (secretKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);\n return Uint8Array.from(publicKey) as TRet<Uint8Array>;\n },\n encapsulate: (publicKey: TArg<Uint8Array>, msg: TArg<Uint8Array> = randomBytes(msgLen)) => {\n abytes(publicKey, lengths.publicKey, 'publicKey');\n abytes(msg, msgLen, 'message');\n\n // FIPS-203 includes additional verification check for modulus\n const eke = publicKey.subarray(0, 384 * opts.K);\n // Copy because of inplace encoding\n const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));\n // (Modulus check.) Perform the computation ek ← ByteEncode12(ByteDecode12(eke)).\n // If ek = ̸ eke, the input is invalid. (See Section 4.2.1.)\n if (!equalBytes(ek, eke)) {\n cleanBytes(ek);\n throw new Error('ML-KEM.encapsulate: wrong publicKey modulus');\n }\n cleanBytes(ek);\n // derive randomness\n const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();\n const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n cleanBytes(kr.subarray(32));\n return {\n cipherText: cipherText as TRet<Uint8Array>,\n sharedSecret: kr.subarray(0, 32) as TRet<Uint8Array>,\n };\n },\n decapsulate: (cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n abytes(secretKey, secretCoder.bytesLen, 'secretKey'); // 768*k + 96\n abytes(cipherText, lengths.cipherText, 'cipherText'); // 32(du*k + dv)\n // test ← H(dk[384𝑘 ∶ 768𝑘 + 32])) .\n const k768 = secretCoder.bytesLen - 96;\n const start = k768 + 32;\n const test = HASH256(secretKey.subarray(k768 / 2, start));\n // If test ≠ dk[768𝑘 + 32 ∶ 768𝑘 + 64], then input checking has failed.\n if (!equalBytes(test, secretKey.subarray(start, start + 32)))\n throw new Error('invalid secretKey: hash check failed');\n const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);\n const msg = KPKE.decrypt(cipherText, sk);\n // derive randomness, Khat, rHat = G(mHat || h)\n const kr = HASH512.create().update(msg).update(publicKeyHash).digest();\n const Khat = kr.subarray(0, 32);\n // re-encrypt using the derived randomness\n const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n // if ciphertexts do not match, “implicitly reject”\n const isValid = equalBytes(cipherText, cipherText2);\n const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();\n cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);\n return (isValid ? Khat : Kbar) as TRet<Uint8Array>;\n },\n });\n}\n\n// FIPS 203's PRF_eta binding: current callers use only 32-byte keys, one-byte nonces,\n// and dkLen values {128, 192}; out-of-range nonce numbers still wrap modulo 256 here.\nfunction shakePRF(dkLen: number, key: TArg<Uint8Array>, nonce: number): TRet<Uint8Array> {\n return shake256\n .create({ dkLen })\n .update(key)\n .update(new Uint8Array([nonce]))\n .digest() as TRet<Uint8Array>;\n}\n\n// Fixed ML-KEM hash/XOF bindings. `KDF` here is the spec's fixed 32-byte `J` call,\n// and swapping any field changes the scheme rather than tuning an internal dependency.\nconst opts = /* @__PURE__ */ (() => ({\n HASH256: sha3_256,\n HASH512: sha3_512,\n KDF: shake256,\n XOF: XOF128,\n PRF: shakePRF,\n}))();\n// Parameter-set instantiation step for the spec's \"ML-KEM-x\" names; current correctness relies\n// on the internal PARAMS rows rather than local validation of arbitrary KEMParam objects.\nconst mk = (params: KEMParam) =>\n createKyber({\n ...opts,\n ...params,\n });\n\n/**\n * ML-KEM-512: Table 2 row `k=2, η1=3, η2=2, du=10, dv=4`; Table 3 sizes `800/1632/768/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem512: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[512]))();\n/**\n * ML-KEM-768: Table 2 row `k=3, η1=2, η2=2, du=10, dv=4`; Table 3 sizes `1184/2400/1088/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem768: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[768]))();\n/**\n * ML-KEM-1024: Table 2 row `k=4, η1=2, η2=2, du=11, dv=5`; Table 3 sizes `1568/3168/1568/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem1024: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[1024]))();\n\n// NOTE: for tests only, don't use. This keeps the exact internal ML-KEM math surfaces available\n// without re-implementing them in separate test code.\nexport const __tests: any = /* @__PURE__ */ (() =>\n Object.freeze({\n Compress_d: (x: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Compress_d: expected d in [1..11], got ${d}`);\n return compress(d).encode(x) & getMask(d);\n },\n Decompress_d: (y: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Decompress_d: expected d in [1..11], got ${d}`);\n return compress(d).decode(y);\n },\n ByteEncode_d: (F: TArg<Uint16Array>, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteEncode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).encode(F as TRet<Uint16Array>);\n },\n ByteDecode_d: (B: TArg<Uint8Array>, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteDecode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).decode(B);\n },\n NTT: (f: TArg<Uint16Array>) => crystals.NTT.encode(Uint16Array.from(f)),\n NTT_inv: (fHat: TArg<Uint16Array>) => crystals.NTT.decode(Uint16Array.from(fHat)),\n MultiplyNTTs: (fHat: TArg<Uint16Array>, gHat: TArg<Uint16Array>) =>\n MultiplyNTTs(Uint16Array.from(fHat), Uint16Array.from(gHat)),\n SamplePolyCBD: (B: TArg<Uint8Array>, eta: number) => {\n abytes(B, 64 * eta, 'B');\n return sampleCBDBytes(B, eta);\n },\n SampleNTT: (B: TArg<Uint8Array>) => {\n abytes(B, 34, 'B');\n const xof = XOF128(B.subarray(0, 32));\n try {\n return SampleNTT(xof.get(B[32], B[33]));\n } finally {\n xof.clean();\n }\n },\n }))();\n","/**\n * Post-Quantum Hybrid Cryptography\n *\n * The current implementation is flawed and likely redundant. We should offer\n * a small, generic API to compose hybrid schemes instead of reimplementing\n * protocol-specific logic (SSH, GPG, etc.) with ad hoc encodings.\n *\n * 1. Core Issues\n * - sign/verify: implemented as two separate operations with different keys.\n * - EC getSharedSecret: could be refactored into a proper KEM.\n * - Multiple calls: keys, signatures, and shared secrets could be\n * concatenated to reduce the number of API invocations.\n * - Reinvention: most libraries add strange domain separations and\n * encodings instead of simple byte concatenation.\n *\n * 2. API Goals\n * - Provide primitives to build hybrids generically.\n * - Avoid embedding SSH- or GPG-specific formats in the core API.\n *\n * 3. Edge Cases\n * • Variable-length signatures:\n * - DER-encoded (Weierstrass curves).\n * - Falcon (unpadded).\n * - Concatenation works only if length is fixed; otherwise a length\n * prefix is required (but that breaks compatibility).\n *\n * • getSharedSecret:\n * - Default: non-KEM (authenticated ECDH).\n * - KEM conversion: generate a random SK to remove implicit auth.\n *\n * 4. Common Pitfalls\n * - Seed expansion:\n * • Expanding a small seed into multiple keys reduces entropy.\n * • API should allow identity mapping (no expansion).\n *\n * - Skipping full point encoding:\n * • Some omit the compression byte (parity) for WebCrypto compatibility.\n * • Better: hash the raw secret; coordinate output is already non-uniform.\n * • Some curves (e.g., X448) produce secrets that must be re-hashed to match\n * symmetric-key lengths.\n *\n * - Combiner inconsistencies:\n * • Different domain separations and encodings across libraries.\n * • Should live at the application layer, since key lengths vary.\n *\n * 5. Protocol Examples\n * - SSH:\n * • Concatenate keys.\n * • Combiner: SHA-512.\n *\n * - GPG:\n * • Concatenate keys.\n * • Combiner:\n * SHA3-256(kemShare || ecdhShare || ciphertext || pubKey || algId || domSep || len(domSep))\n *\n * - TLS:\n * • Transcript-based derivation (HKDF).\n *\n * 6. Relevant Specs & Implementations\n * - IETF Hybrid KEM drafts:\n * • draft-irtf-cfrg-hybrid-kems\n * • draft-connolly-cfrg-xwing-kem\n * • draft-westerbaan-tls-xyber768d00\n *\n * - PQC Libraries:\n * • superdilithium (cyph/pqcrypto.js) – low adoption.\n * • hybrid-pqc (DogeProtocol, quantumcoinproject) – complex encodings.\n *\n * 7. Signatures\n * - Ed25519: fixed-size, easy to support.\n * - Variable-size: introduces custom format requirements; best left to\n * higher-level code.\n *\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { type EdDSA } from '@noble/curves/abstract/edwards.js';\nimport { type MontgomeryECDH } from '@noble/curves/abstract/montgomery.js';\nimport { type ECDSA } from '@noble/curves/abstract/weierstrass.js';\nimport { x25519 } from '@noble/curves/ed25519.js';\nimport { p256, p384 } from '@noble/curves/nist.js';\nimport {\n asciiToBytes,\n bytesToNumberBE,\n bytesToNumberLE,\n concatBytes,\n numberToBytesBE,\n} from '@noble/curves/utils.js';\nimport { expand, extract } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { sha3_256, shake256 } from '@noble/hashes/sha3.js';\nimport { abytes, ahash, anumber, type CHash, type CHashXOF } from '@noble/hashes/utils.js';\nimport { ml_kem1024, ml_kem768 } from './ml-kem.ts';\nimport {\n cleanBytes,\n copyBytes,\n randomBytes,\n splitCoder,\n validateSigOpts,\n validateVerOpts,\n type CryptoKeys,\n type KEM,\n type Signer,\n type TArg,\n type TRet,\n} from './utils.ts';\n\ntype CurveAll = ECDSA | EdDSA | MontgomeryECDH;\ntype CurveECDH = ECDSA | MontgomeryECDH;\ntype CurveSign = ECDSA | EdDSA;\n\n// Can re-use if decide to signatures support, on other hand getSecretKey is specific and ugly\nfunction ecKeygen(curve: CurveAll, allowZeroKey: boolean = false) {\n const lengths = curve.lengths;\n let keygen = curve.keygen;\n if (allowZeroKey) {\n // Only the ECDSA/Weierstrass branch uses raw scalar-byte secret keys here. Edwards seeds are\n // hashed/pruned and Montgomery keys are clamped byte strings, so forcing Point.Fn semantics on\n // those curves would change key construction instead of just relaxing scalar range handling.\n if (!('getSharedSecret' in curve && 'sign' in curve && 'verify' in curve))\n throw new Error('allowZeroKey requires a Weierstrass curve');\n // This legacy flag is really \"skip the +1 shift\" for vector matching, not \"accept scalar 0\".\n // It swaps seeded Weierstrass keygen from reduction into [1, ORDER) to direct reduction into\n // [0, ORDER), which preserves exact reduced bytes but still leaves scalar 0 invalid.\n // This is ugly, but we need to return exact results here.\n const wCurve = curve as ECDSA;\n const Fn = wCurve.Point.Fn;\n // Unlike noble-curves' seeded Weierstrass keygen, this path removes the post-reduction +1.\n // That is enough to match exact reduced-vector bytes, but an all-zero seed still reduces to\n // scalar 0 here and getPublicKey(secretKey) throws instead of \"allowing zero\".\n keygen = (seed: TArg<Uint8Array> = randomBytes(lengths.seed)) => {\n abytes(seed, lengths.seed!, 'seed');\n const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);\n // Reduce directly into [0, ORDER); scalar 0 still stays invalid.\n const secretKey = Fn.toBytes(Fn.create(seedScalar));\n return {\n secretKey: secretKey as TRet<Uint8Array>,\n publicKey: curve.getPublicKey(secretKey) as TRet<Uint8Array>,\n };\n };\n }\n return {\n lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed },\n keygen: (seed?: TArg<Uint8Array>) =>\n keygen(seed) as TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }>,\n getPublicKey: (secretKey: TArg<Uint8Array>) =>\n curve.getPublicKey(secretKey) as TRet<Uint8Array>,\n };\n}\n\n/**\n * Wraps an ECDH-capable curve as a KEM.\n * Shared secrets stay in the wrapped curve's raw ECDH byte format with no built-in KDF.\n * On SEC 1 / Weierstrass curves, that means the compressed shared-point body without the\n * 1-byte `0x02` / `0x03` prefix.\n * The X25519 path also leaves RFC 7748's optional all-zero shared-secret check to callers.\n * @param curve - Curve with `getSharedSecret`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns KEM wrapper over the curve.\n * @throws If the curve does not expose `getSharedSecret`. {@link Error}\n * @example\n * Wrap an ECDH-capable curve as a generic KEM.\n * ```ts\n * import { x25519 } from '@noble/curves/ed25519.js';\n * import { ecdhKem } from '@noble/post-quantum/hybrid.js';\n * const kem = ecdhKem(x25519);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function ecdhKem(curve: CurveECDH, allowZeroKey: boolean = false): TRet<KEM> {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.getSharedSecret) throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n encapsulate(\n publicKey: TArg<Uint8Array>,\n rand: TArg<Uint8Array> = randomBytes(curve.lengths.seed)\n ) {\n // Some curve.keygen(seed) paths reuse the provided seed buffer as secretKey; detach caller\n // randomness first so cleanBytes() only wipes wrapper-owned material.\n const seed = copyBytes(rand);\n let ek: Uint8Array | undefined = undefined;\n try {\n ek = this.keygen(seed).secretKey;\n const sharedSecret = this.decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek) as TRet<Uint8Array>;\n return { sharedSecret, cipherText };\n } finally {\n // Invalid peer public keys can make decapsulation throw; wipe both the detached seed and\n // derived ephemeral secret key even when encapsulation aborts before returning.\n cleanBytes(seed);\n if (ek) cleanBytes(ek);\n }\n },\n decapsulate(cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) {\n const res = curve.getSharedSecret(secretKey, cipherText);\n return (curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res) as TRet<Uint8Array>;\n },\n };\n}\n\n/**\n * Wraps a curve signer as a generic `Signer`.\n * Signatures stay in the wrapped curve's native byte encoding.\n * This wrapper does not normalize or document which per-curve signing options are meaningful.\n * @param curve - Curve with `sign` and `verify`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns Signer wrapper over the curve.\n * @throws If the curve does not expose `sign` and `verify`. {@link Error}\n * @example\n * Wrap a curve signer as a generic signer.\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { ecSigner } from '@noble/post-quantum/hybrid.js';\n * const signer = ecSigner(ed25519);\n * const sigLen = signer.lengths.signature;\n * ```\n */\nexport function ecSigner(curve: CurveSign, allowZeroKey: boolean = false): TRet<Signer> {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.sign || !curve.verify) throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, signature: curve.lengths.signature, signRand: 0 },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n sign: (message, secretKey, opts = {}) => {\n validateSigOpts(opts);\n // This generic wrapper intentionally keeps the Signer contract to message + key only.\n // Backend-specific knobs like ECDSA extraEntropy or Ed25519ctx context cannot be forwarded\n // uniformly through combineSigners(), so callers that need them must use the curve directly.\n if (opts.extraEntropy !== undefined)\n throw new Error(\n 'ecSigner does not support extraEntropy; use the underlying curve directly'\n );\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.sign(message, secretKey) as TRet<Uint8Array>;\n },\n /** Verify one wrapped curve signature.\n * Returns the wrapped curve's `verify()` result for well-formed inputs. Throws on unsupported\n * generic opts and lets wrapped-curve malformed-input errors escape unchanged.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.verify(signature, message, publicKey);\n },\n };\n}\n\nfunction splitLengths<K extends string, T extends { lengths: Partial<Record<K, number>> }>(\n lst: T[],\n name: K\n) {\n // Preserve caller order exactly; raw numeric fields still decode as splitCoder() subarray views.\n return splitCoder(\n name,\n ...lst.map((i) => {\n if (typeof i.lengths[name] !== 'number') throw new Error('wrong length: ' + name);\n return i.lengths[name];\n })\n );\n}\n\n/** Seed-expansion callback used by the hybrid combiners. */\nexport type ExpandSeed = (seed: TArg<Uint8Array>, len: number) => TRet<Uint8Array>;\ntype XOF = CHashXOF<any, { dkLen: number }>;\n\n// It is XOF for most cases, but can be more complex!\n/**\n * Adapts an XOF into an `ExpandSeed` callback.\n * The returned callback interprets its second argument as an output byte length passed as `dkLen`.\n * @param xof - Extendable-output hash function.\n * @returns Seed expander using `dkLen`.\n * @example\n * Adapt an XOF into a seed expander.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * const expandSeed = expandSeedXof(shake256);\n * const seed = expandSeed(new Uint8Array([1]), 4);\n * ```\n */\nexport function expandSeedXof(xof: TArg<XOF>): TRet<ExpandSeed> {\n // Forward the caller seed directly: XOFs are expected to treat inputs as read-only, and this\n // adapter only translates the requested byte length into the hash API's `dkLen` option.\n return ((seed: TArg<Uint8Array>, seedLen: number): TRet<Uint8Array> =>\n (xof as XOF)(seed, { dkLen: seedLen }) as TRet<Uint8Array>) as TRet<ExpandSeed>;\n}\n\n/** Combines public keys, ciphertexts, and shared secrets into one shared secret. */\nexport type Combiner = (\n publicKeys: TArg<Uint8Array[]>,\n cipherTexts: TArg<Uint8Array[]>,\n sharedSecrets: TArg<Uint8Array[]>\n) => TRet<Uint8Array>;\n\nfunction combineKeys(\n realSeedLen: number | undefined, // how much bytes expandSeed expects\n expandSeed_: TArg<ExpandSeed>,\n ...ck_: TArg<CryptoKeys[]>\n) {\n const expandSeed = expandSeed_ as ExpandSeed;\n const ck = ck_ as CryptoKeys[];\n const seedCoder = splitLengths(ck, 'seed');\n const pkCoder = splitLengths(ck, 'publicKey');\n // Allows to use identity functions for combiner/expandSeed\n if (realSeedLen === undefined) realSeedLen = seedCoder.bytesLen;\n anumber(realSeedLen);\n function expandDecapsulationKey(seed: TArg<Uint8Array>): TRet<{\n secretKey: Uint8Array[];\n publicKey: Uint8Array[];\n }> {\n abytes(seed, realSeedLen!);\n const expandedRaw = expandSeed(seed, seedCoder.bytesLen);\n // Identity/subarray expanders can hand back caller-owned seed storage. Detach those outputs so\n // later cleanup can wipe the expanded schedule without mutating the caller's root seed bytes.\n const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes(expandedRaw) : expandedRaw;\n const expanded: Uint8Array[] = [];\n const keySecret: Uint8Array[] = [];\n const secretKey: Uint8Array[] = [];\n const publicKey: Uint8Array[] = [];\n let ok = false;\n try {\n // seedCoder.decode() returns zero-copy slices into expandedSeed and can throw before child\n // keygen() runs, so keep the raw expanded buffer separate and copy each child seed before any\n // later cleanup wipes the shared backing bytes.\n for (const part of seedCoder.decode(expandedSeed)) expanded.push(copyBytes(part));\n for (let i = 0; i < ck.length; i++) {\n const keys = ck[i].keygen(expanded[i]);\n keySecret.push(keys.secretKey);\n secretKey.push(copyBytes(keys.secretKey));\n publicKey.push(keys.publicKey);\n }\n ok = true;\n return { secretKey, publicKey } as TRet<{\n secretKey: Uint8Array[];\n publicKey: Uint8Array[];\n }>;\n } finally {\n // Child keygen() can throw after deriving only a prefix of the composite key schedule. Keep\n // the exported copies on success, but wipe all temporary and partially built secret material\n // on either path so failures do not strand derived child seeds in memory.\n cleanBytes(expandedSeed, expanded, keySecret);\n if (!ok) cleanBytes(secretKey);\n }\n }\n return {\n info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },\n getPublicKey(secretKey: TArg<Uint8Array>) {\n // Composite secret keys are root seeds, so public-key derivation reruns key expansion from\n // that seed instead of decoding a packed child-secret-key structure.\n return this.keygen(secretKey).publicKey as TRet<Uint8Array>;\n },\n keygen(seed: TArg<Uint8Array> = randomBytes(realSeedLen)) {\n const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);\n try {\n const publicKey = pkCoder.encode(pk) as TRet<Uint8Array>;\n return { secretKey: seed as TRet<Uint8Array>, publicKey };\n } finally {\n cleanBytes(pk);\n // The exported secretKey is the caller/root seed itself; child secret keys are internal\n // expansion outputs that are cleaned whether encoding succeeds or throws.\n cleanBytes(secretKey);\n }\n },\n expandDecapsulationKey,\n realSeedLen,\n };\n}\n\n// This generic function that combines multiple KEMs into single one\n/**\n * Combines multiple KEMs into one composite KEM.\n * @param realSeedLen - Input seed length expected by `expandSeed`.\n * @param realMsgLen - Shared-secret length returned by `combiner`.\n * @param expandSeed - Seed expander used to derive per-KEM seeds.\n * @param combiner - Combines the per-KEM outputs into one shared secret.\n * @param kems - KEM implementations to combine.\n * @returns Composite KEM.\n * @example\n * Combine multiple KEMs into one composite KEM.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineKEMS, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const hybrid = combineKEMS(\n * 32,\n * 32,\n * expandSeedXof(shake256),\n * (_pk, _ct, sharedSecrets) => sharedSecrets[0],\n * ml_kem768,\n * ml_kem768\n * );\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineKEMS(\n realSeedLen: number | undefined, // how much bytes expandSeed expects\n realMsgLen: number | undefined, // how much bytes combiner returns\n expandSeed: TArg<ExpandSeed>,\n combiner: TArg<Combiner>,\n ...kems: TArg<KEM[]>\n): TRet<KEM> {\n const rawCombiner = combiner as Combiner;\n const rawKems = kems as KEM[];\n const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);\n const ctCoder = splitLengths(rawKems, 'cipherText');\n const pkCoder = splitLengths(rawKems, 'publicKey');\n const msgCoder = splitLengths(rawKems, 'msg');\n if (realMsgLen === undefined) realMsgLen = msgCoder.bytesLen;\n anumber(realMsgLen);\n const lengths = Object.freeze({\n ...keys.info.lengths,\n msg: realMsgLen,\n msgRand: msgCoder.bytesLen,\n cipherText: ctCoder.bytesLen,\n });\n return Object.freeze({\n lengths,\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n encapsulate(\n pk: TArg<Uint8Array>,\n randomness: TArg<Uint8Array> = randomBytes(msgCoder.bytesLen)\n ) {\n const pks = pkCoder.decode(pk);\n const rand = msgCoder.decode(randomness);\n const sharedSecret: Uint8Array[] = [];\n const cipherText: Uint8Array[] = [];\n try {\n for (let i = 0; i < rawKems.length; i++) {\n const enc = rawKems[i].encapsulate(pks[i], rand[i]);\n sharedSecret.push(enc.sharedSecret);\n cipherText.push(enc.cipherText);\n }\n return {\n // Detach the combiner result before cleanup: a caller-provided combiner may alias one of\n // the child sharedSecret buffers, and those child buffers are zeroized immediately below.\n sharedSecret: copyBytes(rawCombiner(pks, cipherText, sharedSecret)),\n cipherText: ctCoder.encode(cipherText) as TRet<Uint8Array>,\n };\n } finally {\n // Child encapsulation or combiner failures can happen after some components already\n // returned secret material; zeroize whatever was produced before propagating the error.\n cleanBytes(sharedSecret, cipherText);\n }\n },\n decapsulate(ct: TArg<Uint8Array>, seed: TArg<Uint8Array>) {\n const cts = ctCoder.decode(ct);\n const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);\n const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));\n try {\n // Detach the decapsulation result before cleanup: the combiner may hand back one of the\n // child shared-secret buffers, and those temporary buffers are zeroized below.\n return copyBytes(rawCombiner(publicKey, cts, sharedSecret));\n } finally {\n // Decapsulation only needs the expanded child secret keys and child shared secrets for this\n // call; keep the caller/root seed intact, but wipe all derived material even on errors.\n cleanBytes(secretKey, sharedSecret);\n }\n },\n });\n}\n// There is no specs for this, but can be useful\n// realSeedLen: how much bytes expandSeed expects.\n/**\n * Combines multiple signers into one composite signer.\n * @param realSeedLen - Input seed length expected by `expandSeed`.\n * @param expandSeed - Seed expander used to derive per-signer seeds.\n * @param signers - Signers to combine.\n * @returns Composite signer.\n * @example\n * Combine multiple signers into one composite signer.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineSigners, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js';\n * const hybrid = combineSigners(32, expandSeedXof(shake256), ml_dsa44, ml_dsa44);\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineSigners(\n realSeedLen: number | undefined,\n expandSeed: TArg<ExpandSeed>,\n ...signers: TArg<Signer[]>\n): TRet<Signer> {\n const rawSigners = signers as Signer[];\n const keys = combineKeys(realSeedLen, expandSeed, ...rawSigners);\n const sigCoder = splitLengths(rawSigners, 'signature');\n const pkCoder = splitLengths(rawSigners, 'publicKey');\n return {\n lengths: { ...keys.info.lengths, signature: sigCoder.bytesLen, signRand: 0 },\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n sign(message, seed, opts = {}) {\n validateSigOpts(opts);\n // This generic wrapper intentionally keeps the composite signer contract to message + root\n // seed only. Per-signer opts like context or extraEntropy cannot be preserved uniformly\n // across mixed backends, so callers that need them must use the underlying signer directly.\n if (opts.extraEntropy !== undefined)\n throw new Error(\n 'combineSigners does not support extraEntropy; use the underlying signer directly'\n );\n if (opts.context !== undefined)\n throw new Error(\n 'combineSigners does not support context; use the underlying signer directly'\n );\n const { secretKey } = keys.expandDecapsulationKey(seed);\n try {\n const sigs = rawSigners.map((i, j) => i.sign(message, secretKey[j]));\n return sigCoder.encode(sigs) as TRet<Uint8Array>;\n } finally {\n // Composite secret keys are root seeds; the per-signer child secret keys are temporary\n // expansion outputs and must not stay live after the combined signature is produced.\n cleanBytes(secretKey);\n }\n },\n /** Verify one combined signature.\n * Returns `false` when the aggregate signature/publicKey decode succeeds but any child verify\n * check fails. Throws on unsupported generic opts or malformed aggregate encodings.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error(\n 'combineSigners does not support context; use the underlying signer directly'\n );\n const pks = pkCoder.decode(publicKey);\n const sigs = sigCoder.decode(signature);\n for (let i = 0; i < rawSigners.length; i++) {\n if (!rawSigners[i].verify(sigs[i], message, pks[i])) return false;\n }\n return true;\n },\n };\n}\n\n/**\n * Builds a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * The combined shared-secret length follows `kdf.outputLen`; the built-in presets use 32-byte\n * SHA3-256 output, while custom `kdf` choices inherit their own digest size.\n * Its combiner hashes `ss0 || ss1 || ct1 || pk1 || label`, not the full\n * `(c1, c2, ek1, ek2)` example input shape from SP 800-227 equation (15).\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param kdf - Hash used for the final combiner.\n * @returns Hybrid KEM.\n * @example\n * Build a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * ```ts\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha3_256, shake256 } from '@noble/hashes/sha3.js';\n * import { QSF, ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const kem = QSF('example', ml_kem768, ecdhKem(p256, true), shake256, sha3_256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function QSF(\n label: string,\n pqc: TArg<KEM>,\n curveKEM: TArg<KEM>,\n xof: TArg<XOF>,\n kdf: CHash\n): TRet<KEM> {\n ahash(xof);\n ahash(kdf);\n return combineKEMS(\n 32,\n kdf.outputLen,\n expandSeedXof(xof),\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n kdf(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))),\n pqc,\n curveKEM\n );\n}\n\n/** QSF preset combining ML-KEM-768 with P-256. */\nexport const QSF_ml_kem768_p256: TRet<KEM> = /* @__PURE__ */ (() =>\n QSF(\n 'QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)',\n ml_kem768,\n ecdhKem(p256, true),\n shake256,\n sha3_256\n ))();\n/** QSF preset combining ML-KEM-1024 with P-384. */\nexport const QSF_ml_kem1024_p384: TRet<KEM> = /* @__PURE__ */ (() =>\n QSF(\n 'QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)',\n ml_kem1024,\n ecdhKem(p384, true),\n shake256,\n sha3_256\n ))();\n\n/**\n * Builds the \"KitchenSink\" hybrid KEM combiner.\n * The current builder always derives a fixed 32-byte output,\n * regardless of the hash's native output size.\n * Its HKDF extract step uses implicit zero salt with IKM\n * `hybrid_prk || ss0 || ss1 || ct0 || pk0 || ct1 || pk1 || label`.\n * Its HKDF expand step fixes `info` to `len || 'shared_secret' || ''`.\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param hash - Hash used for HKDF extraction and expansion.\n * @returns Hybrid KEM.\n * @example\n * Build the \"KitchenSink\" hybrid KEM combiner.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { createKitchenSink, ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const kem = createKitchenSink('example', ml_kem768, ecdhKem(x25519), shake256, sha256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function createKitchenSink(\n label: string,\n pqc: TArg<KEM>,\n curveKEM: TArg<KEM>,\n xof: TArg<XOF>,\n hash: CHash\n): TRet<KEM> {\n ahash(xof);\n ahash(hash);\n return combineKEMS(\n 32,\n 32,\n expandSeedXof(xof),\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) => {\n const preimage = concatBytes(ss[0], ss[1], ct[0], pk[0], ct[1], pk[1], asciiToBytes(label));\n const len = 32;\n const ikm = concatBytes(asciiToBytes('hybrid_prk'), preimage);\n const prk = extract(hash, ikm);\n const info = concatBytes(\n numberToBytesBE(len, 2),\n asciiToBytes('shared_secret'),\n asciiToBytes('')\n );\n const res = expand(hash, prk, info, len);\n cleanBytes(prk, info, ikm, preimage);\n return res;\n },\n pqc,\n curveKEM\n );\n}\n\n// Internal alias only: this stays exactly `ecdhKem(x25519)`\n// and inherits that wrapper's mutation/oracle behavior.\nconst x25519kem = /* @__PURE__ */ ecdhKem(x25519);\n/** KitchenSink preset combining ML-KEM-768 with X25519.\n * Caller randomness splits into 32 ML-KEM coins plus a 32-byte X25519 ephemeral-secret seed.\n */\nexport const KitchenSink_ml_kem768_x25519: TRet<KEM> = /* @__PURE__ */ (() =>\n createKitchenSink(\n 'KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)',\n ml_kem768,\n x25519kem,\n shake256,\n sha256\n ))();\n\n// Always X25519 and ML-KEM - 768, no point to export\n/** X25519 + ML-KEM-768 hybrid preset.\n * Uses the hard-coded domain-separation label `\\\\.//^\\\\` and hashes only `ct1 || pk1`\n * from the X25519 side in addition to the two component shared secrets.\n */\nexport const ml_kem768_x25519: TRet<KEM> = /* @__PURE__ */ (() =>\n combineKEMS(\n 32,\n 32,\n expandSeedXof(shake256),\n // Awesome label, so much escaping hell in a single line.\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes('\\\\.//^\\\\'))),\n ml_kem768,\n x25519kem\n ))();\n\n/**\n * Internal SEC 1-style KEM wrapper for NIST curves.\n * `nseed` is only the rejection-sampling byte budget for deriving one nonzero scalar:\n * current presets use `128` bytes for P-256 and `48` bytes for P-384.\n * `decapsulate()` returns the uncompressed shared point body `x || y` without the `0x04`\n * prefix, not the SEC 1 `x_P`-only primitive output, because current hybrid combiners hash\n * both coordinates.\n */\nfunction nistCurveKem(curve: ECDSA, scalarLen: number, elemLen: number, nseed: number): TRet<KEM> {\n const Fn = curve.Point.Fn;\n if (!Fn) throw new Error('no Point.Fn');\n // Scan scalar-sized windows until one decodes to a nonzero scalar in `[1, n-1]`; if every\n // window is zero or out of range, fail instead of silently reducing modulo `n`.\n function rejectionSampling(seed: TArg<Uint8Array>): TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }> {\n let sk: bigint;\n for (let start = 0, end = scalarLen; ; start = end, end += scalarLen) {\n if (end > seed.length) throw new Error('rejection sampling failed');\n sk = Fn.fromBytes(seed.subarray(start, end), true);\n if (Fn.isValidNot0(sk)) break;\n }\n const secretKey = Fn.toBytes(Fn.create(sk));\n const publicKey = curve.getPublicKey(secretKey, false);\n return { secretKey, publicKey } as TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }>;\n }\n\n return {\n lengths: {\n secretKey: scalarLen,\n publicKey: elemLen,\n seed: nseed,\n msg: nseed,\n cipherText: elemLen,\n },\n keygen(seed: TArg<Uint8Array> = randomBytes(nseed)) {\n abytes(seed, nseed, 'seed');\n return rejectionSampling(seed);\n },\n getPublicKey(secretKey: TArg<Uint8Array>) {\n return curve.getPublicKey(secretKey, false) as TRet<Uint8Array>;\n },\n encapsulate(publicKey: TArg<Uint8Array>, rand: TArg<Uint8Array> = randomBytes(nseed)) {\n abytes(rand, nseed, 'rand');\n let ek: Uint8Array | undefined = undefined;\n try {\n ek = rejectionSampling(rand).secretKey;\n const sharedSecret = this.decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek, false) as TRet<Uint8Array>;\n return { sharedSecret, cipherText };\n } finally {\n // Rejection-sampled NIST-curve ephemeral secret keys are temporary encapsulation state and\n // must be wiped even if peer-key validation or shared-secret derivation throws.\n if (ek) cleanBytes(ek);\n }\n },\n decapsulate(cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) {\n const full = curve.getSharedSecret(secretKey, cipherText);\n return full.subarray(1) as TRet<Uint8Array>;\n },\n };\n}\n\n/**\n * Internal ML-KEM + NIST-curve combiner.\n * `nseed` controls only the curve-side rejection-sampling budget; it is expanded from the\n * 32-byte root seed and is not itself part of the exported secret-key length.\n * The domain-separation `label` is used only in the final `sha3_256` combiner, not in\n * `shake256(seed, { dkLen: 64 + nseed })`,\n * and the combiner hashes `ss0 || ss1 || ct1 || pk1 || label`.\n */\nfunction concreteHybridKem(\n label: string,\n mlkem: TArg<KEM>,\n curve: ECDSA,\n nseed: number\n): TRet<KEM> {\n const { secretKey: scalarLen, publicKeyUncompressed: elemLen } = curve.lengths;\n if (!scalarLen || !elemLen) throw new Error('wrong curve');\n const curveKem = nistCurveKem(curve, scalarLen, elemLen, nseed);\n const mlkemSeedLen = 64;\n const totalSeedLen = mlkemSeedLen + nseed;\n\n return combineKEMS(\n 32,\n 32,\n (seed: TArg<Uint8Array>): TRet<Uint8Array> => {\n abytes(seed, 32);\n const expanded = shake256(seed, { dkLen: totalSeedLen });\n const mlkemSeed = expanded.subarray(0, mlkemSeedLen);\n const curveSeed = expanded.subarray(mlkemSeedLen, totalSeedLen);\n return concatBytes(mlkemSeed, curveSeed) as TRet<Uint8Array>;\n },\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))),\n mlkem,\n curveKem\n );\n}\n\n/** P-256 + ML-KEM-768 hybrid preset. */\nexport const ml_kem768_p256: TRet<KEM> = /* @__PURE__ */ (() =>\n concreteHybridKem('MLKEM768-P256', ml_kem768, p256, 128))();\n\n/** P-384 + ML-KEM-1024 hybrid preset. */\nexport const ml_kem1024_p384: TRet<KEM> = /* @__PURE__ */ (() =>\n concreteHybridKem('MLKEM1024-P384', ml_kem1024, p384, 48))();\n\n// Legacy aliases\n/** Legacy alias for `ml_kem768_x25519`. */\nexport const XWing: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_x25519)();\n/** Legacy alias for `ml_kem768_x25519`. */\nexport const MLKEM768X25519: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_x25519)();\n/** Legacy alias for `ml_kem768_p256`. */\nexport const MLKEM768P256: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_p256)();\n/** Legacy alias for `ml_kem1024_p384`. */\nexport const MLKEM1024P384: TRet<KEM> = /* @__PURE__ */ (() => ml_kem1024_p384)();\n/** Legacy alias for `QSF_ml_kem768_p256`. */\nexport const QSFMLKEM768P256: TRet<KEM> = /* @__PURE__ */ (() => QSF_ml_kem768_p256)();\n/** Legacy alias for `QSF_ml_kem1024_p384`. */\nexport const QSFMLKEM1024P384: TRet<KEM> = /* @__PURE__ */ (() => QSF_ml_kem1024_p384)();\n/** Legacy alias for `KitchenSink_ml_kem768_x25519`. */\nexport const KitchenSinkMLKEM768X25519: TRet<KEM> = /* @__PURE__ */ (() =>\n KitchenSink_ml_kem768_x25519)();\n","import { 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","import * as ed from '@noble/ed25519';\nimport { sha512 } from '@noble/hashes/sha2.js';\n\ned.hashes.sha512 = sha512;\n\n// Ed25519 group order L (= 2^252 + 27742317777372353535851937790883648493).\nconst L = ed.Point.CURVE().n;\n\nexport interface SignEd25519Opts {\n readonly seed: Uint8Array;\n readonly message: Uint8Array;\n}\n\nexport interface VerifyEd25519Opts {\n readonly publicKey: Uint8Array;\n readonly message: Uint8Array;\n readonly signature: Uint8Array;\n}\n\nexport interface GetPublicKeyEd25519Opts {\n readonly seed: Uint8Array;\n}\n\nexport function signEd25519(opts: SignEd25519Opts): Uint8Array {\n return ed.sign(opts.message, opts.seed);\n}\n\n// Little-endian 32-byte scalar → bigint.\nfunction leBytesToBigInt(bytes: Uint8Array): bigint {\n let value = 0n;\n for (let i = bytes.length - 1; i >= 0; i--) {\n value = (value << 8n) | BigInt(bytes[i]!);\n }\n return value;\n}\n\n// Strict (non-cofactored) Ed25519 verification per RFC 8032 §5.1.7, matching\n// libsodium/PyNaCl `crypto_sign_verify_detached` and ed25519-dalek\n// `verify_strict`. The cofactor-less check rejects every small-order /\n// torsion-component edge case in the C2SP/CCTV corpus, which noble's\n// `{ zip215: false }` mode does NOT (it remains cofactored: it checks\n// `[8]([S]B - [k]A - R) == 0`, accepting torsion components).\n//\n// The verification equation is the unscaled `[S]B == R + [k]A`, rewritten as\n// `[S]B - [k]A - R == identity`. We reject S >= L (non-canonical scalar) and\n// any small-order A or R up front, so a torsion component can never be smuggled\n// through the cofactor multiplication the cofactored variant performs.\nexport function verifyEd25519(opts: VerifyEd25519Opts): boolean {\n const { signature, message, publicKey } = opts;\n if (signature.length !== 64 || publicKey.length !== 32) return false;\n\n // S = LE(sig[32..64]); reject if not a canonical scalar (S >= L).\n const S = leBytesToBigInt(signature.subarray(32, 64));\n if (S >= L) return false;\n\n // Decode A (public key) and R (sig[0..32]) with the canonical (non-zip215)\n // point encoding; a non-canonical encoding throws and rejects.\n let A: ed.Point;\n let R: ed.Point;\n try {\n A = ed.Point.fromBytes(publicKey);\n R = ed.Point.fromBytes(signature.subarray(0, 32));\n } catch {\n return false;\n }\n\n // Reject small-order (cofactor-torsion) A or R: this is exactly the strictness\n // that distinguishes verify_strict from the cofactored check.\n if (A.isSmallOrder() || R.isSmallOrder()) return false;\n\n // k = SHA-512(R || A || M) reduced mod L.\n const k =\n leBytesToBigInt(ed.hash(concatBytes(signature.subarray(0, 32), publicKey, message))) % L;\n\n // Accept iff [S]B - [k]A - R == identity. `multiplyUnsafe` returns the\n // identity for a 0 scalar, but guard explicitly to avoid relying on that.\n const sB = S === 0n ? ed.Point.ZERO : ed.Point.BASE.multiplyUnsafe(S);\n const kA = k === 0n ? ed.Point.ZERO : A.multiplyUnsafe(k);\n return sB.subtract(kA).subtract(R).is0();\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n let total = 0;\n for (const p of parts) total += p.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\nexport function getPublicKeyEd25519(opts: GetPublicKeyEd25519Opts): Uint8Array {\n return ed.getPublicKey(opts.seed);\n}\n","export type SeedDeriveErrorCode = 'INVALID_SEED_LENGTH';\n\nexport class SeedDeriveError extends Error {\n readonly code: SeedDeriveErrorCode;\n\n constructor(code: SeedDeriveErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'SeedDeriveError';\n this.code = code;\n }\n}\n","import { hkdfSha256 } from '../kdf/hkdf';\nimport { mlkem768x25519Keygen } from '../kem/mlkem768x25519';\nimport { x25519PublicKey } from '../kem/x25519';\nimport { getPublicKeyEd25519 } from '../sig/ed25519';\n\nimport { SeedDeriveError } from './errors';\n\n// HKDF info constants for the long-term identity keypairs.\n// These literal byte sequences are part of the on-wire protocol; every\n// conformant implementation MUST hash against these exact ASCII bytes (the\n// Python parity twin pins the identical labels).\nexport const INFO_ED25519: Uint8Array = new TextEncoder().encode('cardano-poe-ed25519-v1');\nexport const INFO_X25519: Uint8Array = new TextEncoder().encode('cardano-poe-x25519-v1');\nexport const INFO_MLKEM768X25519: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-mlkem768x25519-v1',\n);\n\nif (INFO_ED25519.length !== 22) {\n throw new Error('INFO_ED25519 byte-length invariant violated (expected 22)');\n}\nif (INFO_X25519.length !== 21) {\n throw new Error('INFO_X25519 byte-length invariant violated (expected 21)');\n}\nif (INFO_MLKEM768X25519.length !== 29) {\n throw new Error('INFO_MLKEM768X25519 byte-length invariant violated (expected 29)');\n}\n\nconst EMPTY_SALT: Uint8Array = new Uint8Array(0);\nconst SEED_LENGTH = 32;\nconst DERIVED_LENGTH = 32;\n\nexport interface DerivedEd25519KeyPair {\n readonly secretKey: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nexport interface DerivedX25519KeyPair {\n readonly secretKey: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nexport interface DerivedMlKem768X25519KeyPair {\n readonly secretSeed: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nfunction assertSeedLength(seed: Uint8Array): void {\n if (seed.length !== SEED_LENGTH) {\n throw new SeedDeriveError(\n 'INVALID_SEED_LENGTH',\n `seed must be exactly 32 bytes, got ${seed.length}`,\n );\n }\n}\n\nexport function deriveEd25519KeypairFromSeed(seed: Uint8Array): DerivedEd25519KeyPair {\n assertSeedLength(seed);\n const secretKey = hkdfSha256({\n ikm: seed,\n salt: EMPTY_SALT,\n info: INFO_ED25519,\n length: DERIVED_LENGTH,\n });\n const publicKey = getPublicKeyEd25519({ seed: secretKey });\n return { secretKey, publicKey };\n}\n\nexport function deriveX25519KeypairFromSeed(seed: Uint8Array): DerivedX25519KeyPair {\n assertSeedLength(seed);\n const secretKey = hkdfSha256({\n ikm: seed,\n salt: EMPTY_SALT,\n info: INFO_X25519,\n length: DERIVED_LENGTH,\n });\n const publicKey = x25519PublicKey({ secretKey });\n return { secretKey, publicKey };\n}\n\nexport function deriveMlKem768X25519KeypairFromSeed(\n seed: Uint8Array,\n): DerivedMlKem768X25519KeyPair {\n assertSeedLength(seed);\n // The 32-byte HKDF output IS the X-Wing root seed: keygen re-expands the\n // ML-KEM coins and the X25519 scalar from it, so the derived keypair's\n // secretSeed equals this value.\n const xwingSeed = hkdfSha256({\n ikm: seed,\n salt: EMPTY_SALT,\n info: INFO_MLKEM768X25519,\n length: DERIVED_LENGTH,\n });\n return mlkem768x25519Keygen(xwingSeed);\n}\n","// Minimal BIP-173 bech32 encoder used to format age-style recipient strings.\n//\n// This package's dependency policy keeps the runtime import graph to a small,\n// audited set of cryptographic libraries, so we inline the exact bech32\n// algorithm here rather than pull in a general-purpose base-encoding library.\n// Output is byte-identical to the no-length-limit form of a standard bech32\n// encoder (`encode(hrp, toWords(bytes))` with the 90-char BIP-173 cap\n// disabled): age recipients exceed that cap — an X-Wing recipient is ~1960\n// characters — so the limit must be off.\n\nconst BECH32_ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nconst ENCODING_CONST = 1; // BIP-173 bech32 (not bech32m).\n\nfunction polymodStep(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\n// 8-bit bytes → 5-bit words, padding the final partial group with zero bits.\nfunction bytesToWords(bytes: Uint8Array): number[] {\n const words: number[] = [];\n let carry = 0;\n let pos = 0;\n const mask = (1 << 5) - 1;\n for (const n of bytes) {\n carry = (carry << 8) | n;\n pos += 8;\n for (; pos >= 5; pos -= 5) words.push((carry >> (pos - 5)) & mask);\n carry &= (1 << pos) - 1;\n }\n if (pos > 0) words.push((carry << (5 - pos)) & mask);\n return words;\n}\n\nfunction checksum(prefix: string, words: number[]): string {\n let chk = 1;\n for (let i = 0; i < prefix.length; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`bech32: invalid prefix (${prefix})`);\n chk = polymodStep(chk) ^ (c >> 5);\n }\n chk = polymodStep(chk);\n for (let i = 0; i < prefix.length; i++) chk = polymodStep(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (const v of words) chk = polymodStep(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = polymodStep(chk);\n chk ^= ENCODING_CONST;\n let out = '';\n for (let i = 0; i < 6; i++) out += BECH32_ALPHABET[(chk >> (5 * (5 - i))) & 31];\n return out;\n}\n\n// Encode raw bytes to a bech32 string with NO length limit. `prefix` is the HRP.\nexport function bech32EncodeNoLimit(prefix: string, bytes: Uint8Array): string {\n if (prefix.length === 0) throw new Error('bech32: empty prefix');\n const words = bytesToWords(bytes);\n let payload = '';\n for (const w of words) payload += BECH32_ALPHABET[w];\n const lowered = prefix.toLowerCase();\n return `${lowered}1${payload}${checksum(lowered, words)}`;\n}\n\n// Recompute the polymod over the HRP + every data word (the trailing six being\n// the checksum) and test it against the encoding constant. True iff the string\n// carries a valid bech32 checksum.\nfunction checksumValid(prefix: string, words: number[]): boolean {\n let chk = 1;\n for (let i = 0; i < prefix.length; i++) chk = polymodStep(chk) ^ (prefix.charCodeAt(i) >> 5);\n chk = polymodStep(chk);\n for (let i = 0; i < prefix.length; i++) chk = polymodStep(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (const v of words) chk = polymodStep(chk) ^ v;\n return chk === ENCODING_CONST;\n}\n\n// 5-bit words → 8-bit bytes (the inverse of `bytesToWords`). Rejects\n// non-canonical padding: any leftover must be fewer than 5 bits and all zero,\n// matching the zero-fill `bytesToWords` applies to a final partial group.\nfunction wordsToBytes(words: number[]): Uint8Array {\n const out: number[] = [];\n let carry = 0;\n let pos = 0;\n for (const w of words) {\n carry = (carry << 5) | w;\n pos += 5;\n for (; pos >= 8; pos -= 8) out.push((carry >> (pos - 8)) & 0xff);\n carry &= (1 << pos) - 1;\n }\n if (pos >= 5 || carry !== 0) throw new Error('bech32: non-canonical padding');\n return Uint8Array.from(out);\n}\n\n// Decode a bech32 string with NO length limit, verifying the checksum. Returns\n// the lower-cased HRP and the decoded data bytes. The inverse of\n// `bech32EncodeNoLimit`. The separator is the last `1` in the string, so HRPs\n// that themselves contain a `1` (e.g. the `age1pqc` recipient prefix) round-trip\n// correctly.\nexport function bech32DecodeNoLimit(input: string): { hrp: string; bytes: Uint8Array } {\n if (input.length === 0) throw new Error('bech32: empty string');\n const hasLower = input !== input.toUpperCase();\n const hasUpper = input !== input.toLowerCase();\n if (hasLower && hasUpper) throw new Error('bech32: mixed-case string');\n const s = input.toLowerCase();\n const sep = s.lastIndexOf('1');\n if (sep < 1) throw new Error('bech32: missing human-readable prefix');\n if (s.length - sep - 1 < 6) throw new Error('bech32: data too short for checksum');\n const hrp = s.slice(0, sep);\n for (let i = 0; i < hrp.length; i++) {\n const c = hrp.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error('bech32: invalid prefix character');\n }\n const words: number[] = [];\n for (let i = sep + 1; i < s.length; i++) {\n const v = BECH32_ALPHABET.indexOf(s[i]!);\n if (v === -1) throw new Error('bech32: invalid data character');\n words.push(v);\n }\n if (!checksumValid(hrp, words)) throw new Error('bech32: bad checksum');\n return { hrp, bytes: wordsToBytes(words.slice(0, words.length - 6)) };\n}\n","// Encodes a raw KEM public key to a bech32 age-style recipient string — the\n// form a sender uses to address a sealed PoE record.\n//\n// • X25519 (32 bytes) → \"age1…\"\n// • X-Wing / ML-KEM-768 + X25519 (1216 bytes) → \"age1pqc…\"\n//\n// The two HRPs make a recipient self-describing: a parser routes to the right\n// KEM purely from the bech32 prefix. We use the `age1pqc` HRP for the hybrid\n// key (upstream age v1.3.0 claims the shorter `age1pq` HRP for the same X-Wing\n// primitive; `age1pqc` avoids colliding with that wire identifier).\n//\n// The X-Wing public key derives for free from the same identity seed via\n// `deriveMlKem768X25519KeypairFromSeed`, so every identity always has one and\n// can RECEIVE hybrid sealed records even when it publishes via the classical\n// X25519 path.\n\nimport { bech32DecodeNoLimit, bech32EncodeNoLimit } from './bech32';\n\nconst X25519_HRP = 'age';\nconst XWING_HRP = 'age1pqc';\nconst X25519_PUBLIC_KEY_BYTES = 32;\nconst XWING_PUBLIC_KEY_BYTES = 1216;\n\n// The KEM a recipient string addresses, inferred from its bech32 HRP.\nexport type RecipientKem = 'x25519' | 'mlkem768x25519';\n\nexport interface ParsedAgeRecipient {\n readonly kem: RecipientKem;\n readonly publicKey: Uint8Array;\n}\n\nexport function encodeAgeX25519Recipient(publicKey: Uint8Array): string {\n if (publicKey.length !== X25519_PUBLIC_KEY_BYTES) {\n throw new Error('encodeAgeX25519Recipient: publicKey must be exactly 32 bytes');\n }\n return bech32EncodeNoLimit(X25519_HRP, publicKey);\n}\n\nexport function encodeAgeXWingRecipient(publicKey: Uint8Array): string {\n if (publicKey.length !== XWING_PUBLIC_KEY_BYTES) {\n throw new Error('encodeAgeXWingRecipient: publicKey must be exactly 1216 bytes');\n }\n return bech32EncodeNoLimit(XWING_HRP, publicKey);\n}\n\n// Decode an age-style recipient string back to its raw KEM public key, routing\n// on the bech32 HRP. The inverse of `encodeAgeX25519Recipient` /\n// `encodeAgeXWingRecipient`: a sender can take a recipient string a peer shared\n// and recover the exact public key (and which KEM it belongs to) needed to seal\n// a record to them. Surrounding whitespace is tolerated so pasted strings parse.\n// Throws on an unknown HRP, a bad checksum, or a key length that does not match\n// the HRP's KEM.\nexport function parseAgeRecipient(recipient: string): ParsedAgeRecipient {\n if (typeof recipient !== 'string') {\n throw new Error('parseAgeRecipient: recipient must be a string');\n }\n const { hrp, bytes } = bech32DecodeNoLimit(recipient.trim());\n if (hrp === X25519_HRP) {\n if (bytes.length !== X25519_PUBLIC_KEY_BYTES) {\n throw new Error('parseAgeRecipient: age recipient must carry a 32-byte X25519 key');\n }\n return { kem: 'x25519', publicKey: bytes };\n }\n if (hrp === XWING_HRP) {\n if (bytes.length !== XWING_PUBLIC_KEY_BYTES) {\n throw new Error('parseAgeRecipient: age1pqc recipient must carry a 1216-byte X-Wing key');\n }\n return { kem: 'mlkem768x25519', publicKey: bytes };\n }\n throw new Error(`parseAgeRecipient: unrecognized recipient prefix \"${hrp}\"`);\n}\n","export class AeadVerificationError extends Error {\n readonly code: string = 'aead_verification_failed';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'AeadVerificationError';\n }\n}\n","import { 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","// 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","// Raw-seed identity surface. A developer holding a 32-byte seed (e.g. the\n// decoded hex of a key exported from another tool) can derive every keypair,\n// obtain their age recipient strings, get a path-1 Signer, build the\n// RecipientKeyBundle the unwrap dispatch consumes, and decrypt a sealed PoE —\n// all from the public SDK, without a web account envelope.\n//\n// The seed is the only secret this module touches. Callers are responsible for\n// sourcing it securely; the SDK never persists or logs it.\n\nimport {\n deriveEd25519KeypairFromSeed,\n deriveX25519KeypairFromSeed,\n deriveMlKem768X25519KeypairFromSeed,\n type DerivedEd25519KeyPair,\n type DerivedX25519KeyPair,\n type DerivedMlKem768X25519KeyPair,\n} from '@cardanowall/crypto-core/seed-derive';\nimport {\n encodeAgeX25519Recipient,\n encodeAgeXWingRecipient,\n} from '@cardanowall/crypto-core/recipient';\nimport {\n eciesSealedPoeUnwrap,\n type RecipientKeyBundle,\n type SealedEnvelope,\n type UnwrapResult,\n} from '@cardanowall/crypto-core/sealed-poe';\nimport { signEd25519 } from '@cardanowall/crypto-core/sig';\n\nimport type { Signer } from '../client/types';\n\nexport interface SeedKeys {\n readonly ed25519: DerivedEd25519KeyPair;\n readonly x25519: DerivedX25519KeyPair;\n readonly mlkem768x25519: DerivedMlKem768X25519KeyPair;\n}\n\n// Derive the three identity keypairs from a 32-byte seed: Ed25519 (record\n// signing), X25519 (classical KEM), and ML-KEM-768 + X25519 / X-Wing (hybrid\n// post-quantum KEM). Each keypair is the same byte-for-byte value the account\n// envelope would expose — the seed alone fully determines the identity.\nexport function deriveKeysFromSeed(seed: Uint8Array): SeedKeys {\n return {\n ed25519: deriveEd25519KeypairFromSeed(seed),\n x25519: deriveX25519KeypairFromSeed(seed),\n mlkem768x25519: deriveMlKem768X25519KeypairFromSeed(seed),\n };\n}\n\nexport interface SeedRecipients {\n /** Classical age recipient (\"age1…\") for the X25519 KEM. */\n readonly age: string;\n /** X-Wing hybrid recipient (\"age1pqc…\") for the ML-KEM-768 + X25519 KEM. */\n readonly age1pqc: string;\n}\n\n// The recipient strings other senders use to address this identity. Both\n// always exist for any seed: the X-Wing keypair derives for free, so every\n// identity can receive hybrid sealed records even when it publishes via the\n// classical X25519 path.\nexport function recipientsFromSeed(seed: Uint8Array): SeedRecipients {\n const keys = deriveKeysFromSeed(seed);\n return {\n age: encodeAgeX25519Recipient(keys.x25519.publicKey),\n age1pqc: encodeAgeXWingRecipient(keys.mlkem768x25519.publicKey),\n };\n}\n\n// An in-memory path-1 Signer for the publish helpers / off-host signing\n// surface. The derived Ed25519 secret lives only inside this closure; the\n// SDK's publish path touches just `signerPubkey` (public) and the 64-byte\n// signature (public). The 32-byte HKDF output IS the noble Ed25519 seed, so it\n// feeds `signEd25519` directly.\nexport function signerFromSeed(seed: Uint8Array): Signer {\n const { secretKey, publicKey } = deriveEd25519KeypairFromSeed(seed);\n return {\n signerPubkey: publicKey,\n async sign(sigStructureBytes: Uint8Array): Promise<Uint8Array> {\n return signEd25519({ seed: secretKey, message: sigStructureBytes });\n },\n };\n}\n\n// The unified RecipientKeyBundle for the trial-decrypt / unwrap dispatch. A\n// single active identity contributes a one-element X25519 private-key chain and\n// a one-element X-Wing secret-seed list; the unwrap dispatch selects the right\n// list from `envelope.kem`.\nexport function recipientKeyBundleFromSeed(seed: Uint8Array): RecipientKeyBundle {\n const keys = deriveKeysFromSeed(seed);\n return {\n x25519PrivateKeys: [keys.x25519.secretKey],\n mlkem768x25519SecretSeeds: [keys.mlkem768x25519.secretSeed],\n };\n}\n\nexport interface DecryptSealedFromSeedArgs {\n readonly seed: Uint8Array;\n readonly envelope: SealedEnvelope;\n readonly ciphertext: Uint8Array;\n}\n\n// Decrypt a sealed PoE envelope + ciphertext from the seed. Builds the bundle\n// and routes through the existing unwrap dispatch, which selects the correct\n// secret list from `envelope.kem` — so the same call decrypts both classical\n// (x25519) and hybrid (mlkem768x25519) records. Returns the discriminated\n// UnwrapResult; it never throws on an authentication failure (wrong key,\n// tampered header, tampered ciphertext) — callers branch on `result.matched`.\nexport function decryptSealedFromSeed(args: DecryptSealedFromSeedArgs): UnwrapResult {\n return eciesSealedPoeUnwrap({\n envelope: args.envelope,\n ciphertext: args.ciphertext,\n recipientKeyBundle: recipientKeyBundleFromSeed(args.seed),\n });\n}\n"]}
1
+ {"version":3,"sources":["../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/utils.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/_crystals.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/ml-kem.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/hybrid.ts","../../../crypto-core/src/kdf/hkdf.ts","../../../crypto-core/src/kem/mlkem768x25519.ts","../../../crypto-core/src/kem/x25519.ts","../../../crypto-core/src/sig/ed25519.ts","../../../crypto-core/src/seed-derive/errors.ts","../../../crypto-core/src/seed-derive/derive.ts","../../../crypto-core/src/recipient/bech32.ts","../../../crypto-core/src/recipient/age-recipient.ts","../../../crypto-core/src/aead/errors.ts","../../../crypto-core/src/aead/chacha20-poly1305.ts","../../../crypto-core/src/aead/xchacha20-poly1305.ts","../../../crypto-core/src/sealed-poe/errors.ts","../../../crypto-core/src/cbor/canonical.ts","../../../crypto-core/src/sealed-poe/slots-codec.ts","../../../crypto-core/src/sealed-poe/wrap.ts","../../../crypto-core/src/util/compare-ct.ts","../../../crypto-core/src/sealed-poe/unwrap.ts","../../src/identity/seed-identity.ts"],"names":["randb","abytes_","opts","N","Q","F","ROOT_OF_UNITY","shake256","abytes","sha3_256","concatBytes","sha256","x25519","hkdfSha256","hkdf","MLKEM768X25519_SEED_LENGTH","x25519PublicKey","ZERO_NONCE_12","EMPTY_SALT","X25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C,IAAA,CAAK,MAAA,CAAO,SAAS,CAAA;AAAA,IACzC,yBAAA,EAA2B,CAAC,IAAA,CAAK,cAAA,CAAe,UAAU;AAAA,GAC5D;AACF;AAcO,SAAS,sBAAsB,IAAA,EAA+C;AACnF,EAAA,OAAO,oBAAA,CAAqB;AAAA,IAC1B,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,YAAY,IAAA,CAAK,UAAA;AAAA,IACjB,kBAAA,EAAoB,0BAAA,CAA2B,IAAA,CAAK,IAAI;AAAA,GACzD,CAAA;AACH","file":"index.js","sourcesContent":["/**\n * Utilities for hex, bytearray and number handling.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport {\n type CHash,\n type TypedArray,\n abytes,\n abytes as abytes_,\n concatBytes,\n isLE,\n randomBytes as randb,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Asserts that a value is a byte array and optionally checks its length.\n * Returns the original reference unchanged on success, and currently also accepts Node `Buffer`\n * values through the upstream validator.\n * This helper throws on malformed input, so APIs that must return `false` need to guard lengths\n * before decoding or before calling it.\n * @example\n * Validate that a value is a byte array with the expected length.\n * ```ts\n * abytes(new Uint8Array([1]), 1);\n * ```\n */\nconst abytesDoc: typeof abytes = abytes;\nexport { abytesDoc as abytes };\n/**\n * Concatenates byte arrays into a new `Uint8Array`.\n * Zero arguments return an empty `Uint8Array`.\n * Invalid segments throw before allocation because each argument is validated first.\n * @example\n * Concatenate two byte arrays into one result.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nconst concatBytesDoc: typeof concatBytes = concatBytes;\nexport { concatBytesDoc as concatBytes };\n/**\n * Returns cryptographically secure random bytes.\n * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable.\n * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation,\n * so negative and fractional values both throw instead of truncating through JS `ToIndex`.\n * @param bytesLength - Number of random bytes to generate.\n * @returns Fresh random bytes.\n * @example\n * Generate a fresh random seed.\n * ```ts\n * const seed = randomBytes(4);\n * ```\n */\nexport const randomBytes: typeof randb = randb;\n\n/**\n * Compares two byte arrays in a length-constant way for equal lengths.\n * Unequal lengths return `false` immediately, and there is no runtime type validation.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns Whether both arrays contain the same bytes.\n * @example\n * Compare two byte arrays for equality.\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies bytes into a fresh `Uint8Array`.\n * Returns a detached plain `Uint8Array` after validating that the input is real bytes.\n * @param bytes - Source bytes.\n * @returns Copy of the input bytes.\n * @example\n * Copy bytes into a fresh array.\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Byte-swaps each 64-bit lane in place.\n * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need\n * this boundary helper before aliasing them as host `Float64Array` lanes.\n * @param arr - Byte buffer whose length is a multiple of 8.\n * @returns The same buffer after in-place 64-bit lane byte swaps.\n * @example\n * Byte-swap one 64-bit lane in place.\n * ```ts\n * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport function byteSwap64<T extends ArrayBufferView>(arr: T): T {\n const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n for (let i = 0; i < bytes.length; i += 8) {\n const a0 = bytes[i + 0];\n const a1 = bytes[i + 1];\n const a2 = bytes[i + 2];\n const a3 = bytes[i + 3];\n bytes[i + 0] = bytes[i + 7];\n bytes[i + 1] = bytes[i + 6];\n bytes[i + 2] = bytes[i + 5];\n bytes[i + 3] = bytes[i + 4];\n bytes[i + 4] = a3;\n bytes[i + 5] = a2;\n bytes[i + 6] = a1;\n bytes[i + 7] = a0;\n }\n return arr;\n}\n/**\n * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian.\n * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as\n * `Float64Array` lanes on the current host.\n * @param arr - Buffer to pass through or swap in place.\n * @returns The same buffer, normalized for Falcon's little-endian table layout.\n * @example\n * Normalize one host-endian buffer for Falcon's float tables.\n * ```ts\n * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport const baswap64If: <T extends ArrayBufferView>(arr: T) => T = isLE\n ? (arr) => arr\n : byteSwap64;\n\n/** Shared key-generation surface for signers and KEMs. */\nexport type CryptoKeys = {\n /** Optional metadata about the algorithm family or variant. */\n info?: { type?: string };\n /** Public byte lengths for the exported key material. */\n lengths: { seed?: number; publicKey?: number; secretKey?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: TArg<Uint8Array>) => {\n secretKey: TRet<Uint8Array>;\n publicKey: TRet<Uint8Array>;\n };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/** Verification options shared by the signature APIs. */\nexport type VerOpts = {\n /** Optional application-defined context string. */\n context?: Uint8Array;\n};\n/** Signing options shared by the signature APIs. */\nexport type SigOpts = VerOpts & {\n // Compatibility with @noble/curves: false to disable, enabled by default, user can pass U8A\n /** Optional extra entropy or `false` to disable randomized signing. */\n extraEntropy?: Uint8Array | false;\n};\n\n/**\n * Validates that an options bag is a plain object.\n * @param opts - Options object to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate that an options bag is a plain object.\n * ```ts\n * validateOpts({});\n * ```\n */\nexport function validateOpts(opts: object): void {\n // Arrays silently passed here before, but these call sites expect named option-bag fields.\n if (Object.prototype.toString.call(opts) !== '[object Object]')\n throw new TypeError('expected valid options object');\n}\n\n/**\n * Validates common verification options.\n * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support\n * further after this shared plain-object gate.\n * @param opts - Verification options. See {@link VerOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common verification options.\n * ```ts\n * validateVerOpts({ context: new Uint8Array([1]) });\n * ```\n */\nexport function validateVerOpts(opts: TArg<VerOpts>): void {\n validateOpts(opts);\n if (opts.context !== undefined) abytes(opts.context, undefined, 'opts.context');\n}\n\n/**\n * Validates common signing options.\n * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific\n * restrictions are enforced later by callers.\n * @param opts - Signing options. See {@link SigOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common signing options.\n * ```ts\n * validateSigOpts({ extraEntropy: new Uint8Array([1]) });\n * ```\n */\nexport function validateSigOpts(opts: TArg<SigOpts>): void {\n validateVerOpts(opts);\n if (opts.extraEntropy !== false && opts.extraEntropy !== undefined)\n abytes(opts.extraEntropy, undefined, 'opts.extraEntropy');\n}\n\n/** Generic signature interface with key generation, signing, and verification. */\nexport type Signer = CryptoKeys & {\n /** Public byte lengths for signatures and signing randomness. */\n lengths: { signRand?: number; signature?: number };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing options.\n * @returns Signature bytes.\n */\n sign: (\n msg: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts?: TArg<SigOpts>\n ) => TRet<Uint8Array>;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @param opts - Optional verification options.\n * @returns `true` when the signature is valid, `false` when all inputs are well-formed but the\n * signature check does not pass. Some implementations also treat malformed signature encodings as\n * a verification failure and return `false`.\n * @throws On malformed API arguments or unsupported verification options.\n */\n verify: (\n sig: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n opts?: TArg<VerOpts>\n ) => boolean;\n};\n\n/** Generic key encapsulation mechanism interface. */\nexport type KEM = CryptoKeys & {\n /** Public byte lengths for ciphertexts and optional message randomness. */\n lengths: { cipherText?: number; msg?: number; msgRand?: number };\n /**\n * Encapsulate one shared secret to a recipient public key.\n * @param publicKey - Recipient public key bytes.\n * @param msg - Optional caller-provided randomness/message seed.\n * @returns Ciphertext plus shared secret.\n */\n encapsulate: (\n publicKey: TArg<Uint8Array>,\n msg?: TArg<Uint8Array>\n ) => {\n cipherText: TRet<Uint8Array>;\n sharedSecret: TRet<Uint8Array>;\n };\n /**\n * Recover the shared secret from a ciphertext and recipient secret key.\n * @param cipherText - Ciphertext bytes.\n * @param secretKey - Recipient secret key bytes.\n * @returns Decapsulated shared secret.\n */\n decapsulate: (cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/** Bidirectional encoder/decoder interface. */\nexport interface Coder<F, T> {\n /**\n * Serialize one value.\n * @param from - Value to encode.\n * @returns Encoded representation.\n */\n encode(from: F): T;\n /**\n * Parse one serialized value.\n * @param to - Encoded representation.\n * @returns Decoded value.\n */\n decode(to: T): F;\n}\n\n/** Encoder/decoder interface specialized for byte arrays. */\nexport interface BytesCoder<T> extends Coder<T, Uint8Array> {\n /**\n * Serialize one value into bytes.\n * @param data - Value to encode.\n * @returns Encoded bytes.\n */\n encode: (data: T) => Uint8Array;\n /**\n * Parse one byte array into a value.\n * @param bytes - Encoded bytes.\n * @returns Decoded value.\n */\n decode: (bytes: Uint8Array) => T;\n}\n\n/** Fixed-length byte encoder/decoder. */\nexport type BytesCoderLen<T> = BytesCoder<T> & { bytesLen: number };\n\n// nano-packed, because struct encoding is hard.\ntype UnCoder<T> = T extends BytesCoder<infer U> ? U : never;\ntype SplitOut<T extends (number | BytesCoderLen<any>)[]> = {\n [K in keyof T]: T[K] extends number ? Uint8Array : UnCoder<T[K]>;\n};\n/**\n * Builds a fixed-layout coder from byte lengths and nested coders.\n * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that\n * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder`\n * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards\n * caller-owned bytes, it must do so only after detaching them into a disposable copy.\n * @param label - Label used in validation errors.\n * @param lengths - Field lengths or nested coders.\n * @returns Composite fixed-length coder.\n * @example\n * Build a fixed-layout coder from byte lengths and nested coders.\n * ```ts\n * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]);\n * ```\n */\nexport function splitCoder<T extends (number | BytesCoderLen<any>)[]>(\n label: string,\n ...lengths: T\n): TRet<BytesCoder<SplitOut<T>> & { bytesLen: number }> {\n const getLength = (c: TArg<number | BytesCoderLen<any>>) =>\n typeof c === 'number' ? c : (c as BytesCoderLen<any>).bytesLen;\n const bytesLen: number = lengths.reduce((sum: number, a) => sum + getLength(a), 0);\n return {\n bytesLen,\n encode: (bufs: T) => {\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < lengths.length; i++) {\n const c = lengths[i];\n const l = getLength(c);\n const b: Uint8Array = typeof c === 'number' ? (bufs[i] as any) : c.encode(bufs[i]);\n abytes_(b, l, label);\n res.set(b, pos);\n if (typeof c !== 'number') b.fill(0); // clean\n pos += l;\n }\n return res;\n },\n decode: (buf: TArg<Uint8Array>) => {\n abytes_(buf, bytesLen, label);\n const res = [];\n for (const c of lengths) {\n const l = getLength(c);\n const b = buf.subarray(0, l);\n res.push(typeof c === 'number' ? b : c.decode(b));\n buf = buf.subarray(l);\n }\n return res as SplitOut<T>;\n },\n } as any;\n}\n// nano-packed.array (fixed size)\n/**\n * Builds a fixed-length vector coder from another fixed-length coder.\n * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder.\n * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into\n * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned\n * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts\n * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes.\n * @param c - Element coder.\n * @param vecLen - Number of elements in the vector.\n * @returns Fixed-length vector coder.\n * @example\n * Build a fixed-length vector coder from another fixed-length coder.\n * ```ts\n * vecCoder(\n * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 },\n * 2\n * ).encode([1, 2]);\n * ```\n */\nexport function vecCoder<T>(c: TArg<BytesCoderLen<T>>, vecLen: number): TRet<BytesCoderLen<T[]>> {\n const coder = c as BytesCoderLen<T>;\n const bytesLen = vecLen * coder.bytesLen;\n return {\n bytesLen,\n encode: (u: TArg<T[]>): TRet<Uint8Array> => {\n if (u.length !== vecLen)\n throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < u.length; i++) {\n const b = coder.encode(u[i] as T);\n res.set(b, pos);\n b.fill(0); // clean\n pos += b.length;\n }\n return res as TRet<Uint8Array>;\n },\n decode: (a: TArg<Uint8Array>): TRet<T[]> => {\n abytes_(a, bytesLen);\n const r: T[] = [];\n for (let i = 0; i < a.length; i += coder.bytesLen)\n r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));\n return r as TRet<T[]>;\n },\n } as any;\n}\n\n/**\n * Overwrites supported typed-array inputs with zeroes in place.\n * Accepts direct typed arrays and one-level arrays of them.\n * @param list - Typed arrays or one-level lists of typed arrays to clear.\n * @example\n * Overwrite typed arrays with zeroes.\n * ```ts\n * const buf = Uint8Array.of(1, 2, 3);\n * cleanBytes(buf);\n * ```\n */\nexport function cleanBytes(...list: (TypedArray | TypedArray[])[]): void {\n for (const t of list) {\n if (Array.isArray(t)) for (const b of t) b.fill(0);\n else t.fill(0);\n }\n}\n\n/**\n * Creates a 32-bit mask with the lowest `bits` bits set.\n * @param bits - Number of low bits to keep.\n * @returns Bit mask with `bits` ones.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Create a low-bit mask for packed-field operations.\n * ```ts\n * const mask = getMask(4);\n * ```\n */\nexport function getMask(bits: number): number {\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new RangeError(`expected bits in [0..32], got ${bits}`);\n // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask.\n return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0;\n}\n\n/** Shared empty byte array used as the default context. */\nexport const EMPTY: TRet<Uint8Array> = /* @__PURE__ */ Uint8Array.of();\n\n/**\n * Builds the domain-separated message payload for the pure sign/verify paths.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated message payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated payload before direct signing.\n * ```ts\n * const payload = getMessage(new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessage(msg: TArg<Uint8Array>, ctx: TArg<Uint8Array> = EMPTY): TRet<Uint8Array> {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);\n}\n\n// DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the\n// FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128,\n// SHAKE256, or another approved hash/XOF under that subtree.\n// 06 09 60 86 48 01 65 03 04 02\nconst oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]);\n\n/**\n * Validates that a hash exposes a NIST hash OID and enough collision resistance.\n * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST\n * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough.\n * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend\n * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes.\n * @param hash - Hash function to validate.\n * @param requiredStrength - Minimum required collision-resistance strength in bits.\n * @throws If the hash metadata or collision resistance is insufficient. {@link Error}\n * @example\n * Validate that a hash exposes a NIST hash OID and enough collision resistance.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { checkHash } from '@noble/post-quantum/utils.js';\n * checkHash(sha256, 128);\n * ```\n */\nexport function checkHash(hash: CHash, requiredStrength: number = 0): void {\n if (!hash.oid || !equalBytes(hash.oid.subarray(0, 10), oidNistP))\n throw new Error('hash.oid is invalid: expected NIST hash');\n // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST\n // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is\n // the tighter runtime check, so enforce that lower bound here.\n const collisionResistance = (hash.outputLen * 8) / 2;\n if (requiredStrength > collisionResistance) {\n throw new Error(\n 'Pre-hash security strength too low: ' +\n collisionResistance +\n ', required: ' +\n requiredStrength\n );\n }\n}\n\n/**\n * Builds the domain-separated prehash payload for the prehash sign/verify paths.\n * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper\n * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param hash - Prehash function.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated prehash payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated prehash payload for external hashing.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { getMessagePrehash } from '@noble/post-quantum/utils.js';\n * getMessagePrehash(sha256, new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessagePrehash(\n hash: CHash,\n msg: TArg<Uint8Array>,\n ctx: TArg<Uint8Array> = EMPTY\n): TRet<Uint8Array> {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n const hashed = hash(msg);\n return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid!, hashed);\n}\n","/**\n * Internal methods for lattice-based ML-KEM and ML-DSA.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { FFTCore, reverseBits } from '@noble/curves/abstract/fft.js';\nimport { shake128, shake256 } from '@noble/hashes/sha3.js';\nimport type { TypedArray } from '@noble/hashes/utils.js';\nimport {\n type BytesCoderLen,\n cleanBytes,\n type Coder,\n getMask,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/** Extendable-output reader used by the CRYSTALS implementations. */\nexport type XOF = (\n seed: Uint8Array,\n blockLen?: number\n) => {\n /**\n * Read diagnostic counters for the current XOF session.\n * @returns Current call and XOF block counters.\n */\n stats: () => { calls: number; xofs: number };\n /**\n * Select one `(x, y)` coordinate pair and get a block reader for it.\n * Only one coordinate stream is live at a time: a later `get(...)` call rebinds the shared\n * SHAKE state and invalidates older readers.\n * Each squeeze aliases one mutable internal output buffer, so callers must copy blocks they\n * want to retain before the next read.\n * @param x - First matrix coordinate.\n * @param y - Second matrix coordinate.\n * @returns Lazy block reader for that coordinate pair.\n */\n get: (x: number, y: number) => () => Uint8Array; // return block aligned to blockLen and 3\n /** Wipe any buffered state once the reader is no longer needed. */\n clean: () => void;\n};\n\n/** CRYSTALS (ml-kem, ml-dsa) options */\n/** Shared polynomial and NTT parameters for CRYSTALS algorithms. */\nexport type CrystalOpts<T extends TypedArray> = {\n /**\n * Allocate one zeroed polynomial/vector container.\n * @param n - Number of coefficients to allocate.\n * @returns Fresh typed container.\n */\n newPoly: TypedCons<T>;\n /** Polynomial size, typically `256`. */\n N: number;\n /** Prime modulus used for all coefficient arithmetic. */\n Q: number;\n /** Inverse transform normalization factor:\n * `256**-1 mod q` for Dilithium, `128**-1 mod q` for Kyber.\n */\n F: number;\n /** Principal root of unity for the transform domain. */\n ROOT_OF_UNITY: number;\n /** Number of bits used for bit-reversal ordering. */\n brvBits: number;\n /** `true` for Kyber/ML-KEM mode, `false` for Dilithium/ML-DSA mode. */\n isKyber: boolean;\n};\n\n/** Constructor function for typed polynomial containers. */\nexport type TypedCons<T extends TypedArray> = (n: number) => T;\n\ntype Crystals<T extends TypedArray> = {\n mod: (a: number, modulo?: number) => number;\n smod: (a: number, modulo?: number) => number;\n nttZetas: T;\n NTT: {\n /** Forward transform in place. Mutates and returns `r`. */\n encode: (r: T) => T;\n /** Inverse transform in place. Mutates and returns `r`. */\n decode: (r: T) => T;\n };\n bitsCoder: (d: number, c: Coder<number, number>) => BytesCoderLen<T>;\n};\n\n/**\n * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes.\n * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}.\n * @returns CRYSTALS arithmetic and encoding helpers.\n * @example\n * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set.\n * ```ts\n * const crystals = genCrystals({\n * newPoly: (n) => new Uint16Array(n),\n * N: 256,\n * Q: 3329,\n * F: 3303,\n * ROOT_OF_UNITY: 17,\n * brvBits: 7,\n * isKyber: true,\n * });\n * const reduced = crystals.mod(-1);\n * ```\n */\nexport const genCrystals = <T extends TypedArray>(opts: CrystalOpts<T>): TRet<Crystals<T>> => {\n // isKyber: true means Kyber, false means Dilithium\n const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;\n // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by\n // FIPS 203 §2.3 / FIPS 204 §2.3 before downstream mod-q arithmetic.\n const mod = (a: number, modulo = Q): number => {\n const result = a % modulo | 0;\n return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0;\n };\n // FIPS 204 §7.4 uses the centered `mod ±` representative for low bits, keeping the\n // positive midpoint when `modulo` is even.\n // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`.\n const smod = (a: number, modulo = Q): number => {\n const r = mod(a, modulo) | 0;\n return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0;\n };\n // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while\n // Dilithium uses the FIPS 204 §7.5 / Appendix B `BitRev_8` zetas table over all 256 entries.\n function getZettas() {\n const out = newPoly(N);\n for (let i = 0; i < N; i++) {\n const b = reverseBits(i, brvBits);\n const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);\n out[i] = Number(p) | 0;\n }\n return out;\n }\n const nttZetas = getZettas();\n\n // Number-Theoretic Transform\n // Explained: https://electricdusk.com/ntt.html\n\n // Kyber has slightly different params, since there is no 512th primitive root of unity mod q,\n // only 256th primitive root of unity mod. Which also complicates MultiplyNTT.\n\n const field = {\n add: (a: number, b: number) => mod((a | 0) + (b | 0)) | 0,\n sub: (a: number, b: number) => mod((a | 0) - (b | 0)) | 0,\n mul: (a: number, b: number) => mod((a | 0) * (b | 0)) | 0,\n inv: (_a: number) => {\n throw new Error('not implemented');\n },\n };\n const nttOpts = {\n N,\n roots: nttZetas as any,\n invertButterflies: true,\n skipStages: isKyber ? 1 : 0,\n brp: false,\n };\n const dif = FFTCore(field, { dit: false, ...nttOpts });\n const dit = FFTCore(field, { dit: true, ...nttOpts });\n const NTT = {\n encode: (r: T): T => {\n return dif(r) as any;\n },\n decode: (r: T): T => {\n dit(r as any);\n // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14\n // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`.\n // kyber uses 128 here, because brv && stuff\n for (let i = 0; i < r.length; i++) r[i] = mod(F * r[i]);\n return r;\n },\n };\n // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode /\n // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers.\n const bitsCoder = (d: number, c: Coder<number, number>): TRet<BytesCoderLen<T>> => {\n const mask = getMask(d);\n const bytesLen = d * (N / 8);\n return {\n bytesLen,\n encode: (poly_: TArg<T>): TRet<Uint8Array> => {\n const poly = poly_ as T;\n const r = new Uint8Array(bytesLen);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {\n buf |= (c.encode(poly[i]) & mask) << bufLen;\n bufLen += d;\n for (; bufLen >= 8; bufLen -= 8, buf >>= 8) r[pos++] = buf & getMask(bufLen);\n }\n return r as TRet<Uint8Array>;\n },\n decode: (bytes: TArg<Uint8Array>): TRet<T> => {\n const r = newPoly(N);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {\n buf |= bytes[i] << bufLen;\n bufLen += 8;\n for (; bufLen >= d; bufLen -= d, buf >>= d) r[pos++] = c.decode(buf & mask);\n }\n return r as TRet<T>;\n },\n } as TRet<BytesCoderLen<T>>;\n };\n\n return {\n mod,\n smod,\n nttZetas: nttZetas as TRet<T>,\n NTT: {\n encode: (r: TArg<T>): TRet<T> => NTT.encode(r as T) as TRet<T>,\n decode: (r: TArg<T>): TRet<T> => NTT.decode(r as T) as TRet<T>,\n },\n bitsCoder: bitsCoder as TRet<Crystals<T>>['bitsCoder'],\n };\n};\n\nconst createXofShake =\n (shake: typeof shake128): TRet<XOF> =>\n (seed: TArg<Uint8Array>, blockLen?: number) => {\n if (!blockLen) blockLen = shake.blockLen;\n // Optimizations that won't mater:\n // - cached seed update (two .update(), on start and on the end)\n // - another cache which cloned into working copy\n\n // Faster than multiple updates, since seed less than blockLen\n const _seed = new Uint8Array(seed.length + 2);\n _seed.set(seed);\n const seedLen = seed.length;\n const buf = new Uint8Array(blockLen); // == shake128.blockLen\n let h = shake.create({});\n let calls = 0;\n let xofs = 0;\n return {\n stats: () => ({ calls, xofs }),\n get: (x: number, y: number) => {\n // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate\n // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`.\n _seed[seedLen + 0] = x;\n _seed[seedLen + 1] = y;\n h.destroy();\n h = shake.create({}).update(_seed);\n calls++;\n return () => {\n xofs++;\n return h.xofInto(buf) as TRet<Uint8Array>;\n };\n },\n clean: () => {\n h.destroy();\n cleanBytes(buf, _seed);\n },\n };\n };\n\n/**\n * SHAKE128-based extendable-output reader factory used by ML-KEM.\n * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously\n * returned readers, and each squeeze reuses one mutable internal output buffer.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-KEM SHAKE128 matrix expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF128 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF128(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF128: TRet<XOF> = /* @__PURE__ */ createXofShake(shake128);\n/**\n * SHAKE256-based extendable-output reader factory used by ML-DSA.\n * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned\n * readers, and reuses one mutable internal output buffer for each squeeze.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-DSA SHAKE256 coefficient expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF256 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF256(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF256: TRet<XOF> = /* @__PURE__ */ createXofShake(shake256);\n","/**\n * ML-KEM: Module Lattice-based Key Encapsulation Mechanism from\n * [FIPS-203](https://csrc.nist.gov/pubs/fips/203/ipd). A.k.a. CRYSTALS-Kyber.\n *\n * Key encapsulation is similar to DH / ECDH (think X25519), with important differences:\n * * Unlike in ECDH, we can't verify if it was \"Bob\" who've sent the shared secret\n * * Unlike ECDH, it is probabalistic and relies on quality of randomness (CSPRNG).\n * * Decapsulation never throws an error, even when shared secret was\n * encrypted by a different public key. It will just return a different shared secret.\n *\n * There are some concerns with regards to security: see\n * [djb blog](https://blog.cr.yp.to/20231003-countcorrectly.html) and\n * [mailing list](https://groups.google.com/a/list.nist.gov/g/pqc-forum/c/W2VOzy0wz_E).\n *\n * Has similar internals to ML-DSA, but their keys and params are different.\n *\n * Check out [official site](https://www.pq-crystals.org/kyber/resources.shtml),\n * [repo](https://github.com/pq-crystals/kyber),\n * [spec](https://datatracker.ietf.org/doc/draft-cfrg-schwabe-kyber/).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { sha3_256, sha3_512, shake256 } from '@noble/hashes/sha3.js';\nimport { type CHash, swap32IfBE, u32 } from '@noble/hashes/utils.js';\nimport { genCrystals, type XOF, XOF128 } from './_crystals.ts';\nimport {\n abytes,\n cleanBytes,\n type Coder,\n copyBytes,\n equalBytes,\n getMask,\n type KEM,\n randomBytes,\n splitCoder,\n type TArg,\n type TRet,\n vecCoder,\n} from './utils.ts';\n\n/** Key encapsulation mechanism interface */\n\nconst N = 256; // Kyber (not FIPS-203) supports different lengths, but all std modes were using 256\nconst Q = 3329; // 13*(2**8)+1, modulo prime\nconst F = 3303; // 3303 ≡ 128**(−1) mod q (FIPS-203)\nconst ROOT_OF_UNITY = 17; // ζ = 17 ∈ Zq is a primitive 256-th root of unity modulo Q. ζ**128 ≡−1\n// treeshake: keep genCrystals behind the object so PARAMS-only bundles can drop it entirely.\n// Shared CRYSTALS helper in the ML-KEM branch: Kyber mode, 7-bit bit-reversal,\n// and Uint16Array polys because current coefficients stay reduced modulo q.\nconst crystals = /* @__PURE__ */ genCrystals({\n N,\n Q,\n F,\n ROOT_OF_UNITY,\n newPoly: (n: number): TRet<Uint16Array> => new Uint16Array(n) as TRet<Uint16Array>,\n brvBits: 7,\n isKyber: true,\n});\n\n/** FIPS 203: 7. Parameter Sets */\n/** Public ML-KEM parameter-set description. */\nexport type KEMParam = {\n /** Polynomial size. */\n N: number;\n /** Module rank. */\n K: number;\n /** Prime modulus. */\n Q: number;\n /** CBD parameter used for secret-key noise. */\n ETA1: number;\n /** CBD parameter used for error noise. */\n ETA2: number;\n /** Compression width for the `u` vector. */\n du: number;\n /** Compression width for the `v` polynomial. */\n dv: number;\n /** Required strength of the randomness source in bits. */\n RBGstrength: number;\n};\n/** Internal params of ML-KEM versions */\n// prettier-ignore\n/** Built-in ML-KEM parameter presets keyed by the public export names\n * `ml_kem512` / `ml_kem768` / `ml_kem1024`.\n * `RBGstrength` is Table 2's required randomness-source strength in bits,\n * not a generic security label.\n */\nexport const PARAMS: Record<string, KEMParam> = /* @__PURE__ */ (() =>\n Object.freeze({\n 512: Object.freeze({ N, Q, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),\n 768: Object.freeze({ N, Q, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),\n 1024: Object.freeze({ N, Q, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 }),\n } as const))();\n\n// FIPS-203: compress/decompress\nconst compress = (d: number): Coder<number, number> => {\n // d=12 is the ByteEncode12/ByteDecode12 path, not lossy compression.\n // ByteDecode12 interprets each 12-bit word modulo q; without that reduction the public-key\n // modulus check in encapsulate() becomes a no-op for malformed coefficients like 4095.\n if (d >= 12) return { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) };\n // Comments map to python implementation in RFC (draft-cfrg-schwabe-kyber)\n // const round = (i: number) => Math.floor(i + 0.5) | 0;\n const a = 2 ** (d - 1);\n return {\n // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).\n encode: (i: number) => ((i << d) + Q / 2) / Q,\n // const decompress = (i: number) => round((Q / 2 ** d) * i);\n decode: (i: number) => (i * Q + a) >>> d,\n };\n};\n\n// Raw ByteEncode_d / ByteDecode_d from FIPS 203 operate on d-bit words directly.\n// That differs from `polyCoder(d)` for d<12, where noble folds packing together with the lossy\n// ciphertext compression step used by u/v. Tests that exercise the spec's raw packing surface need\n// this exact non-lossy variant instead.\nconst byteCoder = (d: number) =>\n crystals.bitsCoder(\n d,\n d === 12\n ? { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) }\n : { encode: (i: number) => i, decode: (i: number) => i }\n );\n\n// NOTE: we merge encoding and compress because it is faster, also both require same d param\n// d=12 is the ByteEncode12/ByteDecode12 path rather than compression, and caller-side\n// public-key modulus checks route through this helper's decode/encode roundtrip.\n// Converts between bytes and d-bits compressed representation.\n// Kinda like convertRadix2 from @scure/base.\n// decode(encode(t)) == t, but there is loss of information on encode(decode(t))\nconst polyCoder = (d: number) => (d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d)));\n\n// Poly is mod Q, so 12 bits\ntype Poly = Uint16Array;\n\nfunction polyAdd(a_: TArg<Poly>, b_: TArg<Poly>) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] + b[i]); // a += b\n}\nfunction polySub(a_: TArg<Poly>, b_: TArg<Poly>) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] - b[i]); // a -= b\n}\n\n// FIPS-203: Computes the product of two degree-one polynomials with respect to a quadratic modulus\nfunction BaseCaseMultiply(a0: number, a1: number, b0: number, b1: number, zeta: number) {\n // `zeta` here is Algorithm 11's γ = ζ^(2BitRev_7(i)+1).\n const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);\n const c1 = crystals.mod(a0 * b1 + a1 * b0);\n return { c0, c1 };\n}\n\n// FIPS-203: Computes the product (in the ring Tq) of two NTT representations.\n// Works in place on `f`; `g` is read-only and both inputs must already be in NTT form.\nfunction MultiplyNTTs(f_: TArg<Poly>, g_: TArg<Poly>): TRet<Poly> {\n const f = f_ as Poly;\n const g = g_ as Poly;\n for (let i = 0; i < N / 2; i++) {\n let z = crystals.nttZetas[64 + (i >> 1)];\n if (i & 1) z = -z;\n const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);\n f[2 * i + 0] = c0;\n f[2 * i + 1] = c1;\n }\n return f as TRet<Poly>;\n}\n\ntype PRF = (l: number, key: Uint8Array, nonce: number) => Uint8Array;\n\ntype XofGet = ReturnType<ReturnType<XOF>['get']>;\n\ntype KyberOpts = KEMParam & {\n HASH256: CHash;\n HASH512: CHash;\n KDF: CHash<any, { dkLen?: number }>;\n XOF: XOF; // (seed: Uint8Array, len: number, x: number, y: number) => Uint8Array;\n PRF: PRF;\n};\n\n// Return poly in NTT representation\nfunction SampleNTT(xof_: TArg<XofGet>): TRet<Poly> {\n const xof = xof_ as XofGet;\n // The reader must already bind the Algorithm 7 seed||j||i bytes\n // and return block lengths divisible by 3.\n const r: Poly = new Uint16Array(N);\n for (let j = 0; j < N; ) {\n const b = xof();\n if (b.length % 3) throw new Error('SampleNTT: unaligned block');\n for (let i = 0; j < N && i + 3 <= b.length; i += 3) {\n const d1 = ((b[i + 0] >> 0) | (b[i + 1] << 8)) & 0xfff;\n const d2 = ((b[i + 1] >> 4) | (b[i + 2] << 4)) & 0xfff;\n if (d1 < Q) r[j++] = d1;\n if (j < N && d2 < Q) r[j++] = d2;\n }\n }\n return r as TRet<Poly>;\n}\n\n// Sampling from the centered binomial distribution\n// Returns poly with small coefficients (noise/errors) stored modulo q in ordinary coefficient form.\n// Current callers only use Table 2 eta values {2,3} and PRF outputs of exactly 64*eta bytes.\nconst sampleCBDBytes = (buf: TArg<Uint8Array>, eta: number): TRet<Poly> => {\n const r: Poly = new Uint16Array(N);\n // CBD consumes the PRF bitstream in little-endian byte order; normalize the word view on BE,\n // then swap it back so callers still observe `buf` as read-only.\n const b32 = u32(buf);\n swap32IfBE(b32);\n let len = 0;\n for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {\n let b = b32[i];\n for (let j = 0; j < 32; j++) {\n bb += b & 1;\n b >>= 1;\n len += 1;\n if (len === eta) {\n t0 = bb;\n bb = 0;\n } else if (len === 2 * eta) {\n r[p++] = crystals.mod(t0 - bb);\n bb = 0;\n len = 0;\n }\n }\n }\n swap32IfBE(b32);\n if (len) throw new Error(`sampleCBD: leftover bits: ${len}`);\n return r as TRet<Poly>;\n};\n\nfunction sampleCBD(\n PRF_: TArg<PRF>,\n seed: TArg<Uint8Array>,\n nonce: number,\n eta: number\n): TRet<Poly> {\n const PRF = PRF_ as PRF;\n return sampleCBDBytes(PRF((eta * N) / 4, seed, nonce), eta);\n}\n\n// K-PKE\n// Internal ML-KEM subroutine only: exact 32-byte `seed` / `msg` inputs\n// come from Algorithms 13-15, and the helper mutates decoded temporary\n// polynomials in place while leaving caller byte arrays unchanged.\nconst genKPKE = (opts_: TArg<KyberOpts>) => {\n const opts = opts_ as KyberOpts;\n const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts;\n const poly1 = polyCoder(1);\n const polyV = polyCoder(dv);\n const polyU = polyCoder(du);\n const publicCoder = splitCoder('publicKey', vecCoder(polyCoder(12), K), 32);\n const secretCoder = vecCoder(polyCoder(12), K);\n const cipherCoder = splitCoder('ciphertext', vecCoder(polyU, K), polyV);\n const seedCoder = splitCoder('seed', 32, 32);\n return {\n secretCoder,\n lengths: {\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n cipherText: cipherCoder.bytesLen,\n },\n keygen: (seed: TArg<Uint8Array>) => {\n abytes(seed, 32, 'seed');\n const seedDst = new Uint8Array(33);\n seedDst.set(seed);\n // FIPS 203 Algorithm 13 appends the parameter-set byte `k`\n // before `G(d || k)`, so expanding the same 32-byte seed\n // under a different ML-KEM parameter set yields unrelated keys.\n seedDst[32] = K;\n const seedHash = HASH512(seedDst);\n\n const [rho, sigma] = seedCoder.decode(seedHash);\n const sHat: Poly[] = [];\n const tHat: Poly[] = [];\n for (let i = 0; i < K; i++) sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));\n const x = XOF(rho);\n for (let i = 0; i < K; i++) {\n const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));\n for (let j = 0; j < K; j++) {\n const aji = SampleNTT(x.get(j, i)); // A[i][j], inplace\n polyAdd(e, MultiplyNTTs(aji, sHat[j]));\n }\n tHat.push(e); // t ← A ◦ s + e\n }\n x.clean();\n const res = {\n publicKey: publicCoder.encode([tHat, rho]),\n secretKey: secretCoder.encode(sHat),\n };\n cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);\n return res;\n },\n encrypt: (\n publicKey: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n seed: TArg<Uint8Array>\n ): TRet<Uint8Array> => {\n const [tHat, rho] = publicCoder.decode(publicKey);\n const rHat = [];\n for (let i = 0; i < K; i++) rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));\n const x = XOF(rho);\n const tmp2 = new Uint16Array(N);\n const u = [];\n for (let i = 0; i < K; i++) {\n const e1 = sampleCBD(PRF, seed, K + i, ETA2);\n const tmp = new Uint16Array(N);\n for (let j = 0; j < K; j++) {\n const aij = SampleNTT(x.get(i, j)); // A[j][i], inplace transpose access\n polyAdd(tmp, MultiplyNTTs(aij, rHat[j])); // t += aij * rHat[j]\n }\n polyAdd(e1, crystals.NTT.decode(tmp)); // e1 += tmp\n u.push(e1);\n polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i])); // t2 += tHat[i] * rHat[i]\n cleanBytes(tmp);\n }\n x.clean();\n const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);\n polyAdd(e2, crystals.NTT.decode(tmp2)); // e2 += tmp2\n const v = poly1.decode(msg); // encode plaintext m into polynomial v\n polyAdd(v, e2); // v += e2\n cleanBytes(tHat, rHat, tmp2, e2);\n return cipherCoder.encode([u, v]) as TRet<Uint8Array>;\n },\n decrypt: (cipherText: TArg<Uint8Array>, privateKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n const [u, v] = cipherCoder.decode(cipherText);\n const sk = secretCoder.decode(privateKey); // s ← ByteDecode_12(dkPKE)\n const tmp = new Uint16Array(N);\n // tmp += sk[i] * u[i]\n for (let i = 0; i < K; i++) polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));\n polySub(v, crystals.NTT.decode(tmp)); // w = v' - tmp\n cleanBytes(tmp, sk, u);\n return poly1.encode(v) as TRet<Uint8Array>;\n },\n };\n};\n\n/**\n * Public ML-KEM wrapper over the internal K-PKE subroutine.\n * `keygen(seed)` and `encapsulate(publicKey, msg)` are deterministic/test-oriented hooks that map\n * more directly to Algorithms 16-17 than to the pure no-input / random-internal Algorithms 19-20.\n * decapsulate() tries to follow the Algorithms 18/21 implicit-reject structure as closely as\n * practical here by re-encrypting, comparing ciphertexts, returning `Khat` on match or `Kbar` on\n * mismatch, and zeroizing the non-returned shared-secret candidate; JS/JIT still provides no\n * constant-time guarantees for that path.\n */\nfunction createKyber(opts: TArg<KyberOpts>): TRet<KEM> {\n const rawOpts = opts as KyberOpts;\n const KPKE = genKPKE(rawOpts);\n const { HASH256, HASH512, KDF } = rawOpts;\n const { secretCoder: KPKESecretCoder, lengths } = KPKE;\n const secretCoder = splitCoder('secretKey', lengths.secretKey, lengths.publicKey, 32, 32);\n const msgLen = 32;\n const seedLen = 64;\n const kemLengths = Object.freeze({\n ...lengths,\n seed: 64,\n msg: msgLen,\n msgRand: msgLen,\n secretKey: secretCoder.bytesLen,\n });\n return Object.freeze({\n info: Object.freeze({ type: 'ml-kem' }),\n lengths: kemLengths,\n keygen: (seed: TArg<Uint8Array> = randomBytes(seedLen)) => {\n abytes(seed, seedLen, 'seed');\n const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));\n const publicKeyHash = HASH256(publicKey);\n // (dkPKE||ek||H(ek)||z)\n const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);\n cleanBytes(sk, publicKeyHash);\n return {\n publicKey: publicKey as TRet<Uint8Array>,\n secretKey: secretKey as TRet<Uint8Array>,\n };\n },\n getPublicKey: (secretKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);\n return Uint8Array.from(publicKey) as TRet<Uint8Array>;\n },\n encapsulate: (publicKey: TArg<Uint8Array>, msg: TArg<Uint8Array> = randomBytes(msgLen)) => {\n abytes(publicKey, lengths.publicKey, 'publicKey');\n abytes(msg, msgLen, 'message');\n\n // FIPS-203 includes additional verification check for modulus\n const eke = publicKey.subarray(0, 384 * opts.K);\n // Copy because of inplace encoding\n const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));\n // (Modulus check.) Perform the computation ek ← ByteEncode12(ByteDecode12(eke)).\n // If ek = ̸ eke, the input is invalid. (See Section 4.2.1.)\n if (!equalBytes(ek, eke)) {\n cleanBytes(ek);\n throw new Error('ML-KEM.encapsulate: wrong publicKey modulus');\n }\n cleanBytes(ek);\n // derive randomness\n const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();\n const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n cleanBytes(kr.subarray(32));\n return {\n cipherText: cipherText as TRet<Uint8Array>,\n sharedSecret: kr.subarray(0, 32) as TRet<Uint8Array>,\n };\n },\n decapsulate: (cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n abytes(secretKey, secretCoder.bytesLen, 'secretKey'); // 768*k + 96\n abytes(cipherText, lengths.cipherText, 'cipherText'); // 32(du*k + dv)\n // test ← H(dk[384𝑘 ∶ 768𝑘 + 32])) .\n const k768 = secretCoder.bytesLen - 96;\n const start = k768 + 32;\n const test = HASH256(secretKey.subarray(k768 / 2, start));\n // If test ≠ dk[768𝑘 + 32 ∶ 768𝑘 + 64], then input checking has failed.\n if (!equalBytes(test, secretKey.subarray(start, start + 32)))\n throw new Error('invalid secretKey: hash check failed');\n const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);\n const msg = KPKE.decrypt(cipherText, sk);\n // derive randomness, Khat, rHat = G(mHat || h)\n const kr = HASH512.create().update(msg).update(publicKeyHash).digest();\n const Khat = kr.subarray(0, 32);\n // re-encrypt using the derived randomness\n const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n // if ciphertexts do not match, “implicitly reject”\n const isValid = equalBytes(cipherText, cipherText2);\n const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();\n cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);\n return (isValid ? Khat : Kbar) as TRet<Uint8Array>;\n },\n });\n}\n\n// FIPS 203's PRF_eta binding: current callers use only 32-byte keys, one-byte nonces,\n// and dkLen values {128, 192}; out-of-range nonce numbers still wrap modulo 256 here.\nfunction shakePRF(dkLen: number, key: TArg<Uint8Array>, nonce: number): TRet<Uint8Array> {\n return shake256\n .create({ dkLen })\n .update(key)\n .update(new Uint8Array([nonce]))\n .digest() as TRet<Uint8Array>;\n}\n\n// Fixed ML-KEM hash/XOF bindings. `KDF` here is the spec's fixed 32-byte `J` call,\n// and swapping any field changes the scheme rather than tuning an internal dependency.\nconst opts = /* @__PURE__ */ (() => ({\n HASH256: sha3_256,\n HASH512: sha3_512,\n KDF: shake256,\n XOF: XOF128,\n PRF: shakePRF,\n}))();\n// Parameter-set instantiation step for the spec's \"ML-KEM-x\" names; current correctness relies\n// on the internal PARAMS rows rather than local validation of arbitrary KEMParam objects.\nconst mk = (params: KEMParam) =>\n createKyber({\n ...opts,\n ...params,\n });\n\n/**\n * ML-KEM-512: Table 2 row `k=2, η1=3, η2=2, du=10, dv=4`; Table 3 sizes `800/1632/768/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem512: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[512]))();\n/**\n * ML-KEM-768: Table 2 row `k=3, η1=2, η2=2, du=10, dv=4`; Table 3 sizes `1184/2400/1088/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem768: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[768]))();\n/**\n * ML-KEM-1024: Table 2 row `k=4, η1=2, η2=2, du=11, dv=5`; Table 3 sizes `1568/3168/1568/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem1024: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[1024]))();\n\n// NOTE: for tests only, don't use. This keeps the exact internal ML-KEM math surfaces available\n// without re-implementing them in separate test code.\nexport const __tests: any = /* @__PURE__ */ (() =>\n Object.freeze({\n Compress_d: (x: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Compress_d: expected d in [1..11], got ${d}`);\n return compress(d).encode(x) & getMask(d);\n },\n Decompress_d: (y: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Decompress_d: expected d in [1..11], got ${d}`);\n return compress(d).decode(y);\n },\n ByteEncode_d: (F: TArg<Uint16Array>, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteEncode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).encode(F as TRet<Uint16Array>);\n },\n ByteDecode_d: (B: TArg<Uint8Array>, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteDecode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).decode(B);\n },\n NTT: (f: TArg<Uint16Array>) => crystals.NTT.encode(Uint16Array.from(f)),\n NTT_inv: (fHat: TArg<Uint16Array>) => crystals.NTT.decode(Uint16Array.from(fHat)),\n MultiplyNTTs: (fHat: TArg<Uint16Array>, gHat: TArg<Uint16Array>) =>\n MultiplyNTTs(Uint16Array.from(fHat), Uint16Array.from(gHat)),\n SamplePolyCBD: (B: TArg<Uint8Array>, eta: number) => {\n abytes(B, 64 * eta, 'B');\n return sampleCBDBytes(B, eta);\n },\n SampleNTT: (B: TArg<Uint8Array>) => {\n abytes(B, 34, 'B');\n const xof = XOF128(B.subarray(0, 32));\n try {\n return SampleNTT(xof.get(B[32], B[33]));\n } finally {\n xof.clean();\n }\n },\n }))();\n","/**\n * Post-Quantum Hybrid Cryptography\n *\n * The current implementation is flawed and likely redundant. We should offer\n * a small, generic API to compose hybrid schemes instead of reimplementing\n * protocol-specific logic (SSH, GPG, etc.) with ad hoc encodings.\n *\n * 1. Core Issues\n * - sign/verify: implemented as two separate operations with different keys.\n * - EC getSharedSecret: could be refactored into a proper KEM.\n * - Multiple calls: keys, signatures, and shared secrets could be\n * concatenated to reduce the number of API invocations.\n * - Reinvention: most libraries add strange domain separations and\n * encodings instead of simple byte concatenation.\n *\n * 2. API Goals\n * - Provide primitives to build hybrids generically.\n * - Avoid embedding SSH- or GPG-specific formats in the core API.\n *\n * 3. Edge Cases\n * • Variable-length signatures:\n * - DER-encoded (Weierstrass curves).\n * - Falcon (unpadded).\n * - Concatenation works only if length is fixed; otherwise a length\n * prefix is required (but that breaks compatibility).\n *\n * • getSharedSecret:\n * - Default: non-KEM (authenticated ECDH).\n * - KEM conversion: generate a random SK to remove implicit auth.\n *\n * 4. Common Pitfalls\n * - Seed expansion:\n * • Expanding a small seed into multiple keys reduces entropy.\n * • API should allow identity mapping (no expansion).\n *\n * - Skipping full point encoding:\n * • Some omit the compression byte (parity) for WebCrypto compatibility.\n * • Better: hash the raw secret; coordinate output is already non-uniform.\n * • Some curves (e.g., X448) produce secrets that must be re-hashed to match\n * symmetric-key lengths.\n *\n * - Combiner inconsistencies:\n * • Different domain separations and encodings across libraries.\n * • Should live at the application layer, since key lengths vary.\n *\n * 5. Protocol Examples\n * - SSH:\n * • Concatenate keys.\n * • Combiner: SHA-512.\n *\n * - GPG:\n * • Concatenate keys.\n * • Combiner:\n * SHA3-256(kemShare || ecdhShare || ciphertext || pubKey || algId || domSep || len(domSep))\n *\n * - TLS:\n * • Transcript-based derivation (HKDF).\n *\n * 6. Relevant Specs & Implementations\n * - IETF Hybrid KEM drafts:\n * • draft-irtf-cfrg-hybrid-kems\n * • draft-connolly-cfrg-xwing-kem\n * • draft-westerbaan-tls-xyber768d00\n *\n * - PQC Libraries:\n * • superdilithium (cyph/pqcrypto.js) – low adoption.\n * • hybrid-pqc (DogeProtocol, quantumcoinproject) – complex encodings.\n *\n * 7. Signatures\n * - Ed25519: fixed-size, easy to support.\n * - Variable-size: introduces custom format requirements; best left to\n * higher-level code.\n *\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { type EdDSA } from '@noble/curves/abstract/edwards.js';\nimport { type MontgomeryECDH } from '@noble/curves/abstract/montgomery.js';\nimport { type ECDSA } from '@noble/curves/abstract/weierstrass.js';\nimport { x25519 } from '@noble/curves/ed25519.js';\nimport { p256, p384 } from '@noble/curves/nist.js';\nimport {\n asciiToBytes,\n bytesToNumberBE,\n bytesToNumberLE,\n concatBytes,\n numberToBytesBE,\n} from '@noble/curves/utils.js';\nimport { expand, extract } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { sha3_256, shake256 } from '@noble/hashes/sha3.js';\nimport { abytes, ahash, anumber, type CHash, type CHashXOF } from '@noble/hashes/utils.js';\nimport { ml_kem1024, ml_kem768 } from './ml-kem.ts';\nimport {\n cleanBytes,\n copyBytes,\n randomBytes,\n splitCoder,\n validateSigOpts,\n validateVerOpts,\n type CryptoKeys,\n type KEM,\n type Signer,\n type TArg,\n type TRet,\n} from './utils.ts';\n\ntype CurveAll = ECDSA | EdDSA | MontgomeryECDH;\ntype CurveECDH = ECDSA | MontgomeryECDH;\ntype CurveSign = ECDSA | EdDSA;\n\n// Can re-use if decide to signatures support, on other hand getSecretKey is specific and ugly\nfunction ecKeygen(curve: CurveAll, allowZeroKey: boolean = false) {\n const lengths = curve.lengths;\n let keygen = curve.keygen;\n if (allowZeroKey) {\n // Only the ECDSA/Weierstrass branch uses raw scalar-byte secret keys here. Edwards seeds are\n // hashed/pruned and Montgomery keys are clamped byte strings, so forcing Point.Fn semantics on\n // those curves would change key construction instead of just relaxing scalar range handling.\n if (!('getSharedSecret' in curve && 'sign' in curve && 'verify' in curve))\n throw new Error('allowZeroKey requires a Weierstrass curve');\n // This legacy flag is really \"skip the +1 shift\" for vector matching, not \"accept scalar 0\".\n // It swaps seeded Weierstrass keygen from reduction into [1, ORDER) to direct reduction into\n // [0, ORDER), which preserves exact reduced bytes but still leaves scalar 0 invalid.\n // This is ugly, but we need to return exact results here.\n const wCurve = curve as ECDSA;\n const Fn = wCurve.Point.Fn;\n // Unlike noble-curves' seeded Weierstrass keygen, this path removes the post-reduction +1.\n // That is enough to match exact reduced-vector bytes, but an all-zero seed still reduces to\n // scalar 0 here and getPublicKey(secretKey) throws instead of \"allowing zero\".\n keygen = (seed: TArg<Uint8Array> = randomBytes(lengths.seed)) => {\n abytes(seed, lengths.seed!, 'seed');\n const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);\n // Reduce directly into [0, ORDER); scalar 0 still stays invalid.\n const secretKey = Fn.toBytes(Fn.create(seedScalar));\n return {\n secretKey: secretKey as TRet<Uint8Array>,\n publicKey: curve.getPublicKey(secretKey) as TRet<Uint8Array>,\n };\n };\n }\n return {\n lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed },\n keygen: (seed?: TArg<Uint8Array>) =>\n keygen(seed) as TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }>,\n getPublicKey: (secretKey: TArg<Uint8Array>) =>\n curve.getPublicKey(secretKey) as TRet<Uint8Array>,\n };\n}\n\n/**\n * Wraps an ECDH-capable curve as a KEM.\n * Shared secrets stay in the wrapped curve's raw ECDH byte format with no built-in KDF.\n * On SEC 1 / Weierstrass curves, that means the compressed shared-point body without the\n * 1-byte `0x02` / `0x03` prefix.\n * The X25519 path also leaves RFC 7748's optional all-zero shared-secret check to callers.\n * @param curve - Curve with `getSharedSecret`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns KEM wrapper over the curve.\n * @throws If the curve does not expose `getSharedSecret`. {@link Error}\n * @example\n * Wrap an ECDH-capable curve as a generic KEM.\n * ```ts\n * import { x25519 } from '@noble/curves/ed25519.js';\n * import { ecdhKem } from '@noble/post-quantum/hybrid.js';\n * const kem = ecdhKem(x25519);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function ecdhKem(curve: CurveECDH, allowZeroKey: boolean = false): TRet<KEM> {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.getSharedSecret) throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n encapsulate(\n publicKey: TArg<Uint8Array>,\n rand: TArg<Uint8Array> = randomBytes(curve.lengths.seed)\n ) {\n // Some curve.keygen(seed) paths reuse the provided seed buffer as secretKey; detach caller\n // randomness first so cleanBytes() only wipes wrapper-owned material.\n const seed = copyBytes(rand);\n let ek: Uint8Array | undefined = undefined;\n try {\n ek = this.keygen(seed).secretKey;\n const sharedSecret = this.decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek) as TRet<Uint8Array>;\n return { sharedSecret, cipherText };\n } finally {\n // Invalid peer public keys can make decapsulation throw; wipe both the detached seed and\n // derived ephemeral secret key even when encapsulation aborts before returning.\n cleanBytes(seed);\n if (ek) cleanBytes(ek);\n }\n },\n decapsulate(cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) {\n const res = curve.getSharedSecret(secretKey, cipherText);\n return (curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res) as TRet<Uint8Array>;\n },\n };\n}\n\n/**\n * Wraps a curve signer as a generic `Signer`.\n * Signatures stay in the wrapped curve's native byte encoding.\n * This wrapper does not normalize or document which per-curve signing options are meaningful.\n * @param curve - Curve with `sign` and `verify`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns Signer wrapper over the curve.\n * @throws If the curve does not expose `sign` and `verify`. {@link Error}\n * @example\n * Wrap a curve signer as a generic signer.\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { ecSigner } from '@noble/post-quantum/hybrid.js';\n * const signer = ecSigner(ed25519);\n * const sigLen = signer.lengths.signature;\n * ```\n */\nexport function ecSigner(curve: CurveSign, allowZeroKey: boolean = false): TRet<Signer> {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.sign || !curve.verify) throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, signature: curve.lengths.signature, signRand: 0 },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n sign: (message, secretKey, opts = {}) => {\n validateSigOpts(opts);\n // This generic wrapper intentionally keeps the Signer contract to message + key only.\n // Backend-specific knobs like ECDSA extraEntropy or Ed25519ctx context cannot be forwarded\n // uniformly through combineSigners(), so callers that need them must use the curve directly.\n if (opts.extraEntropy !== undefined)\n throw new Error(\n 'ecSigner does not support extraEntropy; use the underlying curve directly'\n );\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.sign(message, secretKey) as TRet<Uint8Array>;\n },\n /** Verify one wrapped curve signature.\n * Returns the wrapped curve's `verify()` result for well-formed inputs. Throws on unsupported\n * generic opts and lets wrapped-curve malformed-input errors escape unchanged.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.verify(signature, message, publicKey);\n },\n };\n}\n\nfunction splitLengths<K extends string, T extends { lengths: Partial<Record<K, number>> }>(\n lst: T[],\n name: K\n) {\n // Preserve caller order exactly; raw numeric fields still decode as splitCoder() subarray views.\n return splitCoder(\n name,\n ...lst.map((i) => {\n if (typeof i.lengths[name] !== 'number') throw new Error('wrong length: ' + name);\n return i.lengths[name];\n })\n );\n}\n\n/** Seed-expansion callback used by the hybrid combiners. */\nexport type ExpandSeed = (seed: TArg<Uint8Array>, len: number) => TRet<Uint8Array>;\ntype XOF = CHashXOF<any, { dkLen: number }>;\n\n// It is XOF for most cases, but can be more complex!\n/**\n * Adapts an XOF into an `ExpandSeed` callback.\n * The returned callback interprets its second argument as an output byte length passed as `dkLen`.\n * @param xof - Extendable-output hash function.\n * @returns Seed expander using `dkLen`.\n * @example\n * Adapt an XOF into a seed expander.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * const expandSeed = expandSeedXof(shake256);\n * const seed = expandSeed(new Uint8Array([1]), 4);\n * ```\n */\nexport function expandSeedXof(xof: TArg<XOF>): TRet<ExpandSeed> {\n // Forward the caller seed directly: XOFs are expected to treat inputs as read-only, and this\n // adapter only translates the requested byte length into the hash API's `dkLen` option.\n return ((seed: TArg<Uint8Array>, seedLen: number): TRet<Uint8Array> =>\n (xof as XOF)(seed, { dkLen: seedLen }) as TRet<Uint8Array>) as TRet<ExpandSeed>;\n}\n\n/** Combines public keys, ciphertexts, and shared secrets into one shared secret. */\nexport type Combiner = (\n publicKeys: TArg<Uint8Array[]>,\n cipherTexts: TArg<Uint8Array[]>,\n sharedSecrets: TArg<Uint8Array[]>\n) => TRet<Uint8Array>;\n\nfunction combineKeys(\n realSeedLen: number | undefined, // how much bytes expandSeed expects\n expandSeed_: TArg<ExpandSeed>,\n ...ck_: TArg<CryptoKeys[]>\n) {\n const expandSeed = expandSeed_ as ExpandSeed;\n const ck = ck_ as CryptoKeys[];\n const seedCoder = splitLengths(ck, 'seed');\n const pkCoder = splitLengths(ck, 'publicKey');\n // Allows to use identity functions for combiner/expandSeed\n if (realSeedLen === undefined) realSeedLen = seedCoder.bytesLen;\n anumber(realSeedLen);\n function expandDecapsulationKey(seed: TArg<Uint8Array>): TRet<{\n secretKey: Uint8Array[];\n publicKey: Uint8Array[];\n }> {\n abytes(seed, realSeedLen!);\n const expandedRaw = expandSeed(seed, seedCoder.bytesLen);\n // Identity/subarray expanders can hand back caller-owned seed storage. Detach those outputs so\n // later cleanup can wipe the expanded schedule without mutating the caller's root seed bytes.\n const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes(expandedRaw) : expandedRaw;\n const expanded: Uint8Array[] = [];\n const keySecret: Uint8Array[] = [];\n const secretKey: Uint8Array[] = [];\n const publicKey: Uint8Array[] = [];\n let ok = false;\n try {\n // seedCoder.decode() returns zero-copy slices into expandedSeed and can throw before child\n // keygen() runs, so keep the raw expanded buffer separate and copy each child seed before any\n // later cleanup wipes the shared backing bytes.\n for (const part of seedCoder.decode(expandedSeed)) expanded.push(copyBytes(part));\n for (let i = 0; i < ck.length; i++) {\n const keys = ck[i].keygen(expanded[i]);\n keySecret.push(keys.secretKey);\n secretKey.push(copyBytes(keys.secretKey));\n publicKey.push(keys.publicKey);\n }\n ok = true;\n return { secretKey, publicKey } as TRet<{\n secretKey: Uint8Array[];\n publicKey: Uint8Array[];\n }>;\n } finally {\n // Child keygen() can throw after deriving only a prefix of the composite key schedule. Keep\n // the exported copies on success, but wipe all temporary and partially built secret material\n // on either path so failures do not strand derived child seeds in memory.\n cleanBytes(expandedSeed, expanded, keySecret);\n if (!ok) cleanBytes(secretKey);\n }\n }\n return {\n info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },\n getPublicKey(secretKey: TArg<Uint8Array>) {\n // Composite secret keys are root seeds, so public-key derivation reruns key expansion from\n // that seed instead of decoding a packed child-secret-key structure.\n return this.keygen(secretKey).publicKey as TRet<Uint8Array>;\n },\n keygen(seed: TArg<Uint8Array> = randomBytes(realSeedLen)) {\n const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);\n try {\n const publicKey = pkCoder.encode(pk) as TRet<Uint8Array>;\n return { secretKey: seed as TRet<Uint8Array>, publicKey };\n } finally {\n cleanBytes(pk);\n // The exported secretKey is the caller/root seed itself; child secret keys are internal\n // expansion outputs that are cleaned whether encoding succeeds or throws.\n cleanBytes(secretKey);\n }\n },\n expandDecapsulationKey,\n realSeedLen,\n };\n}\n\n// This generic function that combines multiple KEMs into single one\n/**\n * Combines multiple KEMs into one composite KEM.\n * @param realSeedLen - Input seed length expected by `expandSeed`.\n * @param realMsgLen - Shared-secret length returned by `combiner`.\n * @param expandSeed - Seed expander used to derive per-KEM seeds.\n * @param combiner - Combines the per-KEM outputs into one shared secret.\n * @param kems - KEM implementations to combine.\n * @returns Composite KEM.\n * @example\n * Combine multiple KEMs into one composite KEM.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineKEMS, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const hybrid = combineKEMS(\n * 32,\n * 32,\n * expandSeedXof(shake256),\n * (_pk, _ct, sharedSecrets) => sharedSecrets[0],\n * ml_kem768,\n * ml_kem768\n * );\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineKEMS(\n realSeedLen: number | undefined, // how much bytes expandSeed expects\n realMsgLen: number | undefined, // how much bytes combiner returns\n expandSeed: TArg<ExpandSeed>,\n combiner: TArg<Combiner>,\n ...kems: TArg<KEM[]>\n): TRet<KEM> {\n const rawCombiner = combiner as Combiner;\n const rawKems = kems as KEM[];\n const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);\n const ctCoder = splitLengths(rawKems, 'cipherText');\n const pkCoder = splitLengths(rawKems, 'publicKey');\n const msgCoder = splitLengths(rawKems, 'msg');\n if (realMsgLen === undefined) realMsgLen = msgCoder.bytesLen;\n anumber(realMsgLen);\n const lengths = Object.freeze({\n ...keys.info.lengths,\n msg: realMsgLen,\n msgRand: msgCoder.bytesLen,\n cipherText: ctCoder.bytesLen,\n });\n return Object.freeze({\n lengths,\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n encapsulate(\n pk: TArg<Uint8Array>,\n randomness: TArg<Uint8Array> = randomBytes(msgCoder.bytesLen)\n ) {\n const pks = pkCoder.decode(pk);\n const rand = msgCoder.decode(randomness);\n const sharedSecret: Uint8Array[] = [];\n const cipherText: Uint8Array[] = [];\n try {\n for (let i = 0; i < rawKems.length; i++) {\n const enc = rawKems[i].encapsulate(pks[i], rand[i]);\n sharedSecret.push(enc.sharedSecret);\n cipherText.push(enc.cipherText);\n }\n return {\n // Detach the combiner result before cleanup: a caller-provided combiner may alias one of\n // the child sharedSecret buffers, and those child buffers are zeroized immediately below.\n sharedSecret: copyBytes(rawCombiner(pks, cipherText, sharedSecret)),\n cipherText: ctCoder.encode(cipherText) as TRet<Uint8Array>,\n };\n } finally {\n // Child encapsulation or combiner failures can happen after some components already\n // returned secret material; zeroize whatever was produced before propagating the error.\n cleanBytes(sharedSecret, cipherText);\n }\n },\n decapsulate(ct: TArg<Uint8Array>, seed: TArg<Uint8Array>) {\n const cts = ctCoder.decode(ct);\n const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);\n const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));\n try {\n // Detach the decapsulation result before cleanup: the combiner may hand back one of the\n // child shared-secret buffers, and those temporary buffers are zeroized below.\n return copyBytes(rawCombiner(publicKey, cts, sharedSecret));\n } finally {\n // Decapsulation only needs the expanded child secret keys and child shared secrets for this\n // call; keep the caller/root seed intact, but wipe all derived material even on errors.\n cleanBytes(secretKey, sharedSecret);\n }\n },\n });\n}\n// There is no specs for this, but can be useful\n// realSeedLen: how much bytes expandSeed expects.\n/**\n * Combines multiple signers into one composite signer.\n * @param realSeedLen - Input seed length expected by `expandSeed`.\n * @param expandSeed - Seed expander used to derive per-signer seeds.\n * @param signers - Signers to combine.\n * @returns Composite signer.\n * @example\n * Combine multiple signers into one composite signer.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineSigners, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js';\n * const hybrid = combineSigners(32, expandSeedXof(shake256), ml_dsa44, ml_dsa44);\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineSigners(\n realSeedLen: number | undefined,\n expandSeed: TArg<ExpandSeed>,\n ...signers: TArg<Signer[]>\n): TRet<Signer> {\n const rawSigners = signers as Signer[];\n const keys = combineKeys(realSeedLen, expandSeed, ...rawSigners);\n const sigCoder = splitLengths(rawSigners, 'signature');\n const pkCoder = splitLengths(rawSigners, 'publicKey');\n return {\n lengths: { ...keys.info.lengths, signature: sigCoder.bytesLen, signRand: 0 },\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n sign(message, seed, opts = {}) {\n validateSigOpts(opts);\n // This generic wrapper intentionally keeps the composite signer contract to message + root\n // seed only. Per-signer opts like context or extraEntropy cannot be preserved uniformly\n // across mixed backends, so callers that need them must use the underlying signer directly.\n if (opts.extraEntropy !== undefined)\n throw new Error(\n 'combineSigners does not support extraEntropy; use the underlying signer directly'\n );\n if (opts.context !== undefined)\n throw new Error(\n 'combineSigners does not support context; use the underlying signer directly'\n );\n const { secretKey } = keys.expandDecapsulationKey(seed);\n try {\n const sigs = rawSigners.map((i, j) => i.sign(message, secretKey[j]));\n return sigCoder.encode(sigs) as TRet<Uint8Array>;\n } finally {\n // Composite secret keys are root seeds; the per-signer child secret keys are temporary\n // expansion outputs and must not stay live after the combined signature is produced.\n cleanBytes(secretKey);\n }\n },\n /** Verify one combined signature.\n * Returns `false` when the aggregate signature/publicKey decode succeeds but any child verify\n * check fails. Throws on unsupported generic opts or malformed aggregate encodings.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error(\n 'combineSigners does not support context; use the underlying signer directly'\n );\n const pks = pkCoder.decode(publicKey);\n const sigs = sigCoder.decode(signature);\n for (let i = 0; i < rawSigners.length; i++) {\n if (!rawSigners[i].verify(sigs[i], message, pks[i])) return false;\n }\n return true;\n },\n };\n}\n\n/**\n * Builds a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * The combined shared-secret length follows `kdf.outputLen`; the built-in presets use 32-byte\n * SHA3-256 output, while custom `kdf` choices inherit their own digest size.\n * Its combiner hashes `ss0 || ss1 || ct1 || pk1 || label`, not the full\n * `(c1, c2, ek1, ek2)` example input shape from SP 800-227 equation (15).\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param kdf - Hash used for the final combiner.\n * @returns Hybrid KEM.\n * @example\n * Build a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * ```ts\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha3_256, shake256 } from '@noble/hashes/sha3.js';\n * import { QSF, ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const kem = QSF('example', ml_kem768, ecdhKem(p256, true), shake256, sha3_256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function QSF(\n label: string,\n pqc: TArg<KEM>,\n curveKEM: TArg<KEM>,\n xof: TArg<XOF>,\n kdf: CHash\n): TRet<KEM> {\n ahash(xof);\n ahash(kdf);\n return combineKEMS(\n 32,\n kdf.outputLen,\n expandSeedXof(xof),\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n kdf(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))),\n pqc,\n curveKEM\n );\n}\n\n/** QSF preset combining ML-KEM-768 with P-256. */\nexport const QSF_ml_kem768_p256: TRet<KEM> = /* @__PURE__ */ (() =>\n QSF(\n 'QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)',\n ml_kem768,\n ecdhKem(p256, true),\n shake256,\n sha3_256\n ))();\n/** QSF preset combining ML-KEM-1024 with P-384. */\nexport const QSF_ml_kem1024_p384: TRet<KEM> = /* @__PURE__ */ (() =>\n QSF(\n 'QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)',\n ml_kem1024,\n ecdhKem(p384, true),\n shake256,\n sha3_256\n ))();\n\n/**\n * Builds the \"KitchenSink\" hybrid KEM combiner.\n * The current builder always derives a fixed 32-byte output,\n * regardless of the hash's native output size.\n * Its HKDF extract step uses implicit zero salt with IKM\n * `hybrid_prk || ss0 || ss1 || ct0 || pk0 || ct1 || pk1 || label`.\n * Its HKDF expand step fixes `info` to `len || 'shared_secret' || ''`.\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param hash - Hash used for HKDF extraction and expansion.\n * @returns Hybrid KEM.\n * @example\n * Build the \"KitchenSink\" hybrid KEM combiner.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { createKitchenSink, ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const kem = createKitchenSink('example', ml_kem768, ecdhKem(x25519), shake256, sha256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function createKitchenSink(\n label: string,\n pqc: TArg<KEM>,\n curveKEM: TArg<KEM>,\n xof: TArg<XOF>,\n hash: CHash\n): TRet<KEM> {\n ahash(xof);\n ahash(hash);\n return combineKEMS(\n 32,\n 32,\n expandSeedXof(xof),\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) => {\n const preimage = concatBytes(ss[0], ss[1], ct[0], pk[0], ct[1], pk[1], asciiToBytes(label));\n const len = 32;\n const ikm = concatBytes(asciiToBytes('hybrid_prk'), preimage);\n const prk = extract(hash, ikm);\n const info = concatBytes(\n numberToBytesBE(len, 2),\n asciiToBytes('shared_secret'),\n asciiToBytes('')\n );\n const res = expand(hash, prk, info, len);\n cleanBytes(prk, info, ikm, preimage);\n return res;\n },\n pqc,\n curveKEM\n );\n}\n\n// Internal alias only: this stays exactly `ecdhKem(x25519)`\n// and inherits that wrapper's mutation/oracle behavior.\nconst x25519kem = /* @__PURE__ */ ecdhKem(x25519);\n/** KitchenSink preset combining ML-KEM-768 with X25519.\n * Caller randomness splits into 32 ML-KEM coins plus a 32-byte X25519 ephemeral-secret seed.\n */\nexport const KitchenSink_ml_kem768_x25519: TRet<KEM> = /* @__PURE__ */ (() =>\n createKitchenSink(\n 'KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)',\n ml_kem768,\n x25519kem,\n shake256,\n sha256\n ))();\n\n// Always X25519 and ML-KEM - 768, no point to export\n/** X25519 + ML-KEM-768 hybrid preset.\n * Uses the hard-coded domain-separation label `\\\\.//^\\\\` and hashes only `ct1 || pk1`\n * from the X25519 side in addition to the two component shared secrets.\n */\nexport const ml_kem768_x25519: TRet<KEM> = /* @__PURE__ */ (() =>\n combineKEMS(\n 32,\n 32,\n expandSeedXof(shake256),\n // Awesome label, so much escaping hell in a single line.\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes('\\\\.//^\\\\'))),\n ml_kem768,\n x25519kem\n ))();\n\n/**\n * Internal SEC 1-style KEM wrapper for NIST curves.\n * `nseed` is only the rejection-sampling byte budget for deriving one nonzero scalar:\n * current presets use `128` bytes for P-256 and `48` bytes for P-384.\n * `decapsulate()` returns the uncompressed shared point body `x || y` without the `0x04`\n * prefix, not the SEC 1 `x_P`-only primitive output, because current hybrid combiners hash\n * both coordinates.\n */\nfunction nistCurveKem(curve: ECDSA, scalarLen: number, elemLen: number, nseed: number): TRet<KEM> {\n const Fn = curve.Point.Fn;\n if (!Fn) throw new Error('no Point.Fn');\n // Scan scalar-sized windows until one decodes to a nonzero scalar in `[1, n-1]`; if every\n // window is zero or out of range, fail instead of silently reducing modulo `n`.\n function rejectionSampling(seed: TArg<Uint8Array>): TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }> {\n let sk: bigint;\n for (let start = 0, end = scalarLen; ; start = end, end += scalarLen) {\n if (end > seed.length) throw new Error('rejection sampling failed');\n sk = Fn.fromBytes(seed.subarray(start, end), true);\n if (Fn.isValidNot0(sk)) break;\n }\n const secretKey = Fn.toBytes(Fn.create(sk));\n const publicKey = curve.getPublicKey(secretKey, false);\n return { secretKey, publicKey } as TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }>;\n }\n\n return {\n lengths: {\n secretKey: scalarLen,\n publicKey: elemLen,\n seed: nseed,\n msg: nseed,\n cipherText: elemLen,\n },\n keygen(seed: TArg<Uint8Array> = randomBytes(nseed)) {\n abytes(seed, nseed, 'seed');\n return rejectionSampling(seed);\n },\n getPublicKey(secretKey: TArg<Uint8Array>) {\n return curve.getPublicKey(secretKey, false) as TRet<Uint8Array>;\n },\n encapsulate(publicKey: TArg<Uint8Array>, rand: TArg<Uint8Array> = randomBytes(nseed)) {\n abytes(rand, nseed, 'rand');\n let ek: Uint8Array | undefined = undefined;\n try {\n ek = rejectionSampling(rand).secretKey;\n const sharedSecret = this.decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek, false) as TRet<Uint8Array>;\n return { sharedSecret, cipherText };\n } finally {\n // Rejection-sampled NIST-curve ephemeral secret keys are temporary encapsulation state and\n // must be wiped even if peer-key validation or shared-secret derivation throws.\n if (ek) cleanBytes(ek);\n }\n },\n decapsulate(cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) {\n const full = curve.getSharedSecret(secretKey, cipherText);\n return full.subarray(1) as TRet<Uint8Array>;\n },\n };\n}\n\n/**\n * Internal ML-KEM + NIST-curve combiner.\n * `nseed` controls only the curve-side rejection-sampling budget; it is expanded from the\n * 32-byte root seed and is not itself part of the exported secret-key length.\n * The domain-separation `label` is used only in the final `sha3_256` combiner, not in\n * `shake256(seed, { dkLen: 64 + nseed })`,\n * and the combiner hashes `ss0 || ss1 || ct1 || pk1 || label`.\n */\nfunction concreteHybridKem(\n label: string,\n mlkem: TArg<KEM>,\n curve: ECDSA,\n nseed: number\n): TRet<KEM> {\n const { secretKey: scalarLen, publicKeyUncompressed: elemLen } = curve.lengths;\n if (!scalarLen || !elemLen) throw new Error('wrong curve');\n const curveKem = nistCurveKem(curve, scalarLen, elemLen, nseed);\n const mlkemSeedLen = 64;\n const totalSeedLen = mlkemSeedLen + nseed;\n\n return combineKEMS(\n 32,\n 32,\n (seed: TArg<Uint8Array>): TRet<Uint8Array> => {\n abytes(seed, 32);\n const expanded = shake256(seed, { dkLen: totalSeedLen });\n const mlkemSeed = expanded.subarray(0, mlkemSeedLen);\n const curveSeed = expanded.subarray(mlkemSeedLen, totalSeedLen);\n return concatBytes(mlkemSeed, curveSeed) as TRet<Uint8Array>;\n },\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))),\n mlkem,\n curveKem\n );\n}\n\n/** P-256 + ML-KEM-768 hybrid preset. */\nexport const ml_kem768_p256: TRet<KEM> = /* @__PURE__ */ (() =>\n concreteHybridKem('MLKEM768-P256', ml_kem768, p256, 128))();\n\n/** P-384 + ML-KEM-1024 hybrid preset. */\nexport const ml_kem1024_p384: TRet<KEM> = /* @__PURE__ */ (() =>\n concreteHybridKem('MLKEM1024-P384', ml_kem1024, p384, 48))();\n\n// Legacy aliases\n/** Legacy alias for `ml_kem768_x25519`. */\nexport const XWing: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_x25519)();\n/** Legacy alias for `ml_kem768_x25519`. */\nexport const MLKEM768X25519: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_x25519)();\n/** Legacy alias for `ml_kem768_p256`. */\nexport const MLKEM768P256: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_p256)();\n/** Legacy alias for `ml_kem1024_p384`. */\nexport const MLKEM1024P384: TRet<KEM> = /* @__PURE__ */ (() => ml_kem1024_p384)();\n/** Legacy alias for `QSF_ml_kem768_p256`. */\nexport const QSFMLKEM768P256: TRet<KEM> = /* @__PURE__ */ (() => QSF_ml_kem768_p256)();\n/** Legacy alias for `QSF_ml_kem1024_p384`. */\nexport const QSFMLKEM1024P384: TRet<KEM> = /* @__PURE__ */ (() => QSF_ml_kem1024_p384)();\n/** Legacy alias for `KitchenSink_ml_kem768_x25519`. */\nexport const KitchenSinkMLKEM768X25519: TRet<KEM> = /* @__PURE__ */ (() =>\n KitchenSink_ml_kem768_x25519)();\n","import { 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","import * as ed from '@noble/ed25519';\nimport { sha512 } from '@noble/hashes/sha2.js';\n\ned.hashes.sha512 = sha512;\n\n// Ed25519 group order L (= 2^252 + 27742317777372353535851937790883648493).\nconst L = ed.Point.CURVE().n;\n\nexport interface SignEd25519Opts {\n readonly seed: Uint8Array;\n readonly message: Uint8Array;\n}\n\nexport interface VerifyEd25519Opts {\n readonly publicKey: Uint8Array;\n readonly message: Uint8Array;\n readonly signature: Uint8Array;\n}\n\nexport interface GetPublicKeyEd25519Opts {\n readonly seed: Uint8Array;\n}\n\nexport function signEd25519(opts: SignEd25519Opts): Uint8Array {\n return ed.sign(opts.message, opts.seed);\n}\n\n// Little-endian 32-byte scalar → bigint.\nfunction leBytesToBigInt(bytes: Uint8Array): bigint {\n let value = 0n;\n for (let i = bytes.length - 1; i >= 0; i--) {\n value = (value << 8n) | BigInt(bytes[i]!);\n }\n return value;\n}\n\n// Strict (non-cofactored) Ed25519 verification per RFC 8032 §5.1.7, matching\n// libsodium/PyNaCl `crypto_sign_verify_detached` and ed25519-dalek\n// `verify_strict`. The cofactor-less check rejects every small-order /\n// torsion-component edge case in the C2SP/CCTV corpus, which noble's\n// `{ zip215: false }` mode does NOT (it remains cofactored: it checks\n// `[8]([S]B - [k]A - R) == 0`, accepting torsion components).\n//\n// The verification equation is the unscaled `[S]B == R + [k]A`, rewritten as\n// `[S]B - [k]A - R == identity`. We reject S >= L (non-canonical scalar) and\n// any small-order A or R up front, so a torsion component can never be smuggled\n// through the cofactor multiplication the cofactored variant performs.\nexport function verifyEd25519(opts: VerifyEd25519Opts): boolean {\n const { signature, message, publicKey } = opts;\n if (signature.length !== 64 || publicKey.length !== 32) return false;\n\n // S = LE(sig[32..64]); reject if not a canonical scalar (S >= L).\n const S = leBytesToBigInt(signature.subarray(32, 64));\n if (S >= L) return false;\n\n // Decode A (public key) and R (sig[0..32]) with the canonical (non-zip215)\n // point encoding; a non-canonical encoding throws and rejects.\n let A: ed.Point;\n let R: ed.Point;\n try {\n A = ed.Point.fromBytes(publicKey);\n R = ed.Point.fromBytes(signature.subarray(0, 32));\n } catch {\n return false;\n }\n\n // Reject small-order (cofactor-torsion) A or R: this is exactly the strictness\n // that distinguishes verify_strict from the cofactored check.\n if (A.isSmallOrder() || R.isSmallOrder()) return false;\n\n // k = SHA-512(R || A || M) reduced mod L.\n const k =\n leBytesToBigInt(ed.hash(concatBytes(signature.subarray(0, 32), publicKey, message))) % L;\n\n // Accept iff [S]B - [k]A - R == identity. `multiplyUnsafe` returns the\n // identity for a 0 scalar, but guard explicitly to avoid relying on that.\n const sB = S === 0n ? ed.Point.ZERO : ed.Point.BASE.multiplyUnsafe(S);\n const kA = k === 0n ? ed.Point.ZERO : A.multiplyUnsafe(k);\n return sB.subtract(kA).subtract(R).is0();\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n let total = 0;\n for (const p of parts) total += p.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\nexport function getPublicKeyEd25519(opts: GetPublicKeyEd25519Opts): Uint8Array {\n return ed.getPublicKey(opts.seed);\n}\n","export type SeedDeriveErrorCode = 'INVALID_SEED_LENGTH';\n\nexport class SeedDeriveError extends Error {\n readonly code: SeedDeriveErrorCode;\n\n constructor(code: SeedDeriveErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'SeedDeriveError';\n this.code = code;\n }\n}\n","import { hkdfSha256 } from '../kdf/hkdf';\nimport { mlkem768x25519Keygen } from '../kem/mlkem768x25519';\nimport { x25519PublicKey } from '../kem/x25519';\nimport { getPublicKeyEd25519 } from '../sig/ed25519';\n\nimport { SeedDeriveError } from './errors';\n\n// HKDF info constants for the long-term identity keypairs.\n// These literal byte sequences are part of the on-wire protocol; every\n// conformant implementation MUST hash against these exact ASCII bytes (the\n// Python parity twin pins the identical labels).\nexport const INFO_ED25519: Uint8Array = new TextEncoder().encode('cardano-poe-ed25519-v1');\nexport const INFO_X25519: Uint8Array = new TextEncoder().encode('cardano-poe-x25519-v1');\nexport const INFO_MLKEM768X25519: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-mlkem768x25519-v1',\n);\n\nif (INFO_ED25519.length !== 22) {\n throw new Error('INFO_ED25519 byte-length invariant violated (expected 22)');\n}\nif (INFO_X25519.length !== 21) {\n throw new Error('INFO_X25519 byte-length invariant violated (expected 21)');\n}\nif (INFO_MLKEM768X25519.length !== 29) {\n throw new Error('INFO_MLKEM768X25519 byte-length invariant violated (expected 29)');\n}\n\nconst EMPTY_SALT: Uint8Array = new Uint8Array(0);\nconst SEED_LENGTH = 32;\nconst DERIVED_LENGTH = 32;\n\nexport interface DerivedEd25519KeyPair {\n readonly secretKey: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nexport interface DerivedX25519KeyPair {\n readonly secretKey: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nexport interface DerivedMlKem768X25519KeyPair {\n readonly secretSeed: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nfunction assertSeedLength(seed: Uint8Array): void {\n if (seed.length !== SEED_LENGTH) {\n throw new SeedDeriveError(\n 'INVALID_SEED_LENGTH',\n `seed must be exactly 32 bytes, got ${seed.length}`,\n );\n }\n}\n\nexport function deriveEd25519KeypairFromSeed(seed: Uint8Array): DerivedEd25519KeyPair {\n assertSeedLength(seed);\n const secretKey = hkdfSha256({\n ikm: seed,\n salt: EMPTY_SALT,\n info: INFO_ED25519,\n length: DERIVED_LENGTH,\n });\n const publicKey = getPublicKeyEd25519({ seed: secretKey });\n return { secretKey, publicKey };\n}\n\nexport function deriveX25519KeypairFromSeed(seed: Uint8Array): DerivedX25519KeyPair {\n assertSeedLength(seed);\n const secretKey = hkdfSha256({\n ikm: seed,\n salt: EMPTY_SALT,\n info: INFO_X25519,\n length: DERIVED_LENGTH,\n });\n const publicKey = x25519PublicKey({ secretKey });\n return { secretKey, publicKey };\n}\n\nexport function deriveMlKem768X25519KeypairFromSeed(\n seed: Uint8Array,\n): DerivedMlKem768X25519KeyPair {\n assertSeedLength(seed);\n // The 32-byte HKDF output IS the X-Wing root seed: keygen re-expands the\n // ML-KEM coins and the X25519 scalar from it, so the derived keypair's\n // secretSeed equals this value.\n const xwingSeed = hkdfSha256({\n ikm: seed,\n salt: EMPTY_SALT,\n info: INFO_MLKEM768X25519,\n length: DERIVED_LENGTH,\n });\n return mlkem768x25519Keygen(xwingSeed);\n}\n","// Minimal BIP-173 bech32 encoder used to format age-style recipient strings.\n//\n// This package's dependency policy keeps the runtime import graph to a small,\n// audited set of cryptographic libraries, so we inline the exact bech32\n// algorithm here rather than pull in a general-purpose base-encoding library.\n// Output is byte-identical to the no-length-limit form of a standard bech32\n// encoder (`encode(hrp, toWords(bytes))` with the 90-char BIP-173 cap\n// disabled): age recipients exceed that cap — an X-Wing recipient is ~1960\n// characters — so the limit must be off.\n\nconst BECH32_ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nconst ENCODING_CONST = 1; // BIP-173 bech32 (not bech32m).\n\nfunction polymodStep(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\n// 8-bit bytes → 5-bit words, padding the final partial group with zero bits.\nfunction bytesToWords(bytes: Uint8Array): number[] {\n const words: number[] = [];\n let carry = 0;\n let pos = 0;\n const mask = (1 << 5) - 1;\n for (const n of bytes) {\n carry = (carry << 8) | n;\n pos += 8;\n for (; pos >= 5; pos -= 5) words.push((carry >> (pos - 5)) & mask);\n carry &= (1 << pos) - 1;\n }\n if (pos > 0) words.push((carry << (5 - pos)) & mask);\n return words;\n}\n\nfunction checksum(prefix: string, words: number[]): string {\n let chk = 1;\n for (let i = 0; i < prefix.length; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`bech32: invalid prefix (${prefix})`);\n chk = polymodStep(chk) ^ (c >> 5);\n }\n chk = polymodStep(chk);\n for (let i = 0; i < prefix.length; i++) chk = polymodStep(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (const v of words) chk = polymodStep(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = polymodStep(chk);\n chk ^= ENCODING_CONST;\n let out = '';\n for (let i = 0; i < 6; i++) out += BECH32_ALPHABET[(chk >> (5 * (5 - i))) & 31];\n return out;\n}\n\n// Encode raw bytes to a bech32 string with NO length limit. `prefix` is the HRP.\nexport function bech32EncodeNoLimit(prefix: string, bytes: Uint8Array): string {\n if (prefix.length === 0) throw new Error('bech32: empty prefix');\n const words = bytesToWords(bytes);\n let payload = '';\n for (const w of words) payload += BECH32_ALPHABET[w];\n const lowered = prefix.toLowerCase();\n return `${lowered}1${payload}${checksum(lowered, words)}`;\n}\n\n// Recompute the polymod over the HRP + every data word (the trailing six being\n// the checksum) and test it against the encoding constant. True iff the string\n// carries a valid bech32 checksum.\nfunction checksumValid(prefix: string, words: number[]): boolean {\n let chk = 1;\n for (let i = 0; i < prefix.length; i++) chk = polymodStep(chk) ^ (prefix.charCodeAt(i) >> 5);\n chk = polymodStep(chk);\n for (let i = 0; i < prefix.length; i++) chk = polymodStep(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (const v of words) chk = polymodStep(chk) ^ v;\n return chk === ENCODING_CONST;\n}\n\n// 5-bit words → 8-bit bytes (the inverse of `bytesToWords`). Rejects\n// non-canonical padding: any leftover must be fewer than 5 bits and all zero,\n// matching the zero-fill `bytesToWords` applies to a final partial group.\nfunction wordsToBytes(words: number[]): Uint8Array {\n const out: number[] = [];\n let carry = 0;\n let pos = 0;\n for (const w of words) {\n carry = (carry << 5) | w;\n pos += 5;\n for (; pos >= 8; pos -= 8) out.push((carry >> (pos - 8)) & 0xff);\n carry &= (1 << pos) - 1;\n }\n if (pos >= 5 || carry !== 0) throw new Error('bech32: non-canonical padding');\n return Uint8Array.from(out);\n}\n\n// Decode a bech32 string with NO length limit, verifying the checksum. Returns\n// the lower-cased HRP and the decoded data bytes. The inverse of\n// `bech32EncodeNoLimit`. The separator is the last `1` in the string, so HRPs\n// that themselves contain a `1` (e.g. the `age1pqc` recipient prefix) round-trip\n// correctly.\nexport function bech32DecodeNoLimit(input: string): { hrp: string; bytes: Uint8Array } {\n if (input.length === 0) throw new Error('bech32: empty string');\n const hasLower = input !== input.toUpperCase();\n const hasUpper = input !== input.toLowerCase();\n if (hasLower && hasUpper) throw new Error('bech32: mixed-case string');\n const s = input.toLowerCase();\n const sep = s.lastIndexOf('1');\n if (sep < 1) throw new Error('bech32: missing human-readable prefix');\n if (s.length - sep - 1 < 6) throw new Error('bech32: data too short for checksum');\n const hrp = s.slice(0, sep);\n for (let i = 0; i < hrp.length; i++) {\n const c = hrp.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error('bech32: invalid prefix character');\n }\n const words: number[] = [];\n for (let i = sep + 1; i < s.length; i++) {\n const v = BECH32_ALPHABET.indexOf(s[i]!);\n if (v === -1) throw new Error('bech32: invalid data character');\n words.push(v);\n }\n if (!checksumValid(hrp, words)) throw new Error('bech32: bad checksum');\n return { hrp, bytes: wordsToBytes(words.slice(0, words.length - 6)) };\n}\n","// Encodes a raw KEM public key to a bech32 age-style recipient string — the\n// form a sender uses to address a sealed PoE record.\n//\n// • X25519 (32 bytes) → \"age1…\"\n// • X-Wing / ML-KEM-768 + X25519 (1216 bytes) → \"age1pqc…\"\n//\n// The two HRPs make a recipient self-describing: a parser routes to the right\n// KEM purely from the bech32 prefix. We use the `age1pqc` HRP for the hybrid\n// key (upstream age v1.3.0 claims the shorter `age1pq` HRP for the same X-Wing\n// primitive; `age1pqc` avoids colliding with that wire identifier).\n//\n// The X-Wing public key derives for free from the same identity seed via\n// `deriveMlKem768X25519KeypairFromSeed`, so every identity always has one and\n// can RECEIVE hybrid sealed records even when it publishes via the classical\n// X25519 path.\n\nimport { bech32DecodeNoLimit, bech32EncodeNoLimit } from './bech32';\n\nconst X25519_HRP = 'age';\nconst XWING_HRP = 'age1pqc';\nconst X25519_PUBLIC_KEY_BYTES = 32;\nconst XWING_PUBLIC_KEY_BYTES = 1216;\n\n// The KEM a recipient string addresses, inferred from its bech32 HRP.\nexport type RecipientKem = 'x25519' | 'mlkem768x25519';\n\nexport interface ParsedAgeRecipient {\n readonly kem: RecipientKem;\n readonly publicKey: Uint8Array;\n}\n\nexport function encodeAgeX25519Recipient(publicKey: Uint8Array): string {\n if (publicKey.length !== X25519_PUBLIC_KEY_BYTES) {\n throw new Error('encodeAgeX25519Recipient: publicKey must be exactly 32 bytes');\n }\n return bech32EncodeNoLimit(X25519_HRP, publicKey);\n}\n\nexport function encodeAgeXWingRecipient(publicKey: Uint8Array): string {\n if (publicKey.length !== XWING_PUBLIC_KEY_BYTES) {\n throw new Error('encodeAgeXWingRecipient: publicKey must be exactly 1216 bytes');\n }\n return bech32EncodeNoLimit(XWING_HRP, publicKey);\n}\n\n// Decode an age-style recipient string back to its raw KEM public key, routing\n// on the bech32 HRP. The inverse of `encodeAgeX25519Recipient` /\n// `encodeAgeXWingRecipient`: a sender can take a recipient string a peer shared\n// and recover the exact public key (and which KEM it belongs to) needed to seal\n// a record to them. Surrounding whitespace is tolerated so pasted strings parse.\n// Throws on an unknown HRP, a bad checksum, or a key length that does not match\n// the HRP's KEM.\nexport function parseAgeRecipient(recipient: string): ParsedAgeRecipient {\n if (typeof recipient !== 'string') {\n throw new Error('parseAgeRecipient: recipient must be a string');\n }\n const { hrp, bytes } = bech32DecodeNoLimit(recipient.trim());\n if (hrp === X25519_HRP) {\n if (bytes.length !== X25519_PUBLIC_KEY_BYTES) {\n throw new Error('parseAgeRecipient: age recipient must carry a 32-byte X25519 key');\n }\n return { kem: 'x25519', publicKey: bytes };\n }\n if (hrp === XWING_HRP) {\n if (bytes.length !== XWING_PUBLIC_KEY_BYTES) {\n throw new Error('parseAgeRecipient: age1pqc recipient must carry a 1216-byte X-Wing key');\n }\n return { kem: 'mlkem768x25519', publicKey: bytes };\n }\n throw new Error(`parseAgeRecipient: unrecognized recipient prefix \"${hrp}\"`);\n}\n","export class AeadVerificationError extends Error {\n readonly code: string = 'aead_verification_failed';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'AeadVerificationError';\n }\n}\n","import { 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","// Sealed-PoE error taxonomy (wire-shape + partitioning-oracle pre-checks).\n\nexport type EciesSealedPoeErrorCode =\n | 'ENC_SLOTS_EMPTY'\n | 'ENC_SLOTS_REQUIRED'\n | 'ENC_SLOTS_MAC_REQUIRED'\n | 'ENC_SLOTS_MAC_INVALID_LENGTH'\n | 'KEM_EPK_LENGTH_MISMATCH'\n | 'KEM_CT_LENGTH_MISMATCH'\n | 'INVALID_CEK_LENGTH'\n | 'NONCE_LENGTH_MISMATCH'\n | 'INVALID_EPHEMERAL_SECRET_LENGTH'\n | 'EPHEMERAL_SECRETS_COUNT_MISMATCH'\n | 'UNSUPPORTED_ENC_VERSION'\n | 'UNSUPPORTED_AEAD_ALG'\n | 'UNSUPPORTED_KEM_ALG'\n | 'INVALID_ENVELOPE_SHAPE'\n | 'INVALID_RECIPIENT_KEY'\n | 'WRAP_LENGTH_MISMATCH';\n\nexport class EciesSealedPoeError extends Error {\n readonly code: EciesSealedPoeErrorCode;\n\n constructor(code: EciesSealedPoeErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'EciesSealedPoeError';\n this.code = code;\n }\n}\n","import { cdeDecodeOptions, decode, encode } from 'cbor2';\nimport { sortCoreDeterministic } from 'cbor2/sorts';\n\nimport { CanonicalCborError } from './errors';\n\nexport type CanonicalCborValue =\n | null\n | boolean\n | number\n | bigint\n | string\n | Uint8Array\n | readonly CanonicalCborValue[]\n | { readonly [key: string]: CanonicalCborValue }\n | ReadonlyMap<string | number, CanonicalCborValue>;\n\nexport function encodeCanonicalCbor(value: CanonicalCborValue): Uint8Array {\n return encode(value, {\n cde: true,\n collapseBigInts: true,\n rejectDuplicateKeys: true,\n sortKeys: sortCoreDeterministic,\n });\n}\n\nexport function decodeCanonicalCbor(bytes: Uint8Array): unknown {\n try {\n return decode(bytes, {\n ...cdeDecodeOptions,\n rejectStreaming: true,\n rejectDuplicateKeys: true,\n // A Label 309 record carries integers, byte/text strings, arrays, maps and\n // `null` — and nothing else. Without these rejections the major-type-7\n // surface leaks into the decoder: a float16/32/64 that happens to hold an\n // integral value (e.g. 1.0) silently decodes to the integer 1 and passes\n // a `z.literal(1)` / Number.isInteger schema check, so two byte strings\n // that are NOT byte-identical canonicalise to the same record. That\n // breaks the cross-implementation parity invariant (the Python twin\n // already rejects non-integer `v` / `enc.scheme` outright). Reject the\n // whole non-record surface — floats, negative zero, undefined, and\n // non-{true,false,null} simple values — so any such input surfaces as\n // MALFORMED_CBOR via mapDecodeError rather than decoding to a look-alike.\n rejectFloats: true,\n rejectNegativeZero: true,\n rejectUndefined: true,\n rejectSimple: true,\n });\n } catch (cause) {\n throw mapDecodeError(cause);\n }\n}\n\nfunction mapDecodeError(cause: unknown): CanonicalCborError {\n const message = cause instanceof Error ? cause.message : String(cause);\n const lower = message.toLowerCase();\n // Every canonical-decode violation collapses to the single public taxonomy\n // code MALFORMED_CBOR: indefinite-length (streaming) items, duplicate keys,\n // non-canonical (unsorted) key ordering, non-minimal integer encodings, and\n // invalid UTF-8 in text strings. cbor2 raises the SAME \"Duplicate or out of\n // order key\" message for both true duplicates AND distinct-but-unsorted keys,\n // so the two are indistinguishable by message — and per the Label 309 taxonomy\n // both belong under MALFORMED_CBOR anyway. The specific cause survives in the\n // human-readable message below; for indefinite-length we state it explicitly\n // so the diagnostic is not lost when the code is collapsed.\n const isIndefinite = lower.includes('streaming') || lower.includes('indefinite');\n const detail = isIndefinite\n ? `indefinite-length items are not permitted in canonical CBOR: ${message}`\n : message;\n return new CanonicalCborError('MALFORMED_CBOR', `cbor decode failed: ${detail}`, { cause });\n}\n","// Single source of truth for two seams that wrap, unwrap, and the wire encoder\n// MUST agree on byte-for-byte:\n//\n// 1. How the 1120-byte X-Wing `enc` is split into the ≤ 64-byte byte-string\n// chunks the Cardano ledger requires (`kem_ct`), and the inverse join.\n// 2. The canonical-CBOR serialization of the slot array that feeds slots_mac.\n//\n// Keeping both here means the producer (wrap) and the verifier (unwrap), as well\n// as the downstream record encoder, cannot diverge on the bytes the MAC commits\n// to — the single highest correctness risk for the hybrid branch, since a\n// divergence would leave the ML-KEM ciphertext unauthenticated.\n\nimport { encodeCanonicalCbor, type CanonicalCborValue } from '../cbor/canonical';\n\nimport type { Mlkem768X25519Slot, X25519Slot } from './wrap';\n\n// The envelope-level KEM discriminator.\nexport type SealedKem = 'x25519' | 'mlkem768x25519';\n\n// Cardano ledger CDDL caps every `transaction_metadatum` byte string at 64\n// bytes, so any value larger than 64 bytes is carried as an array of ≤ 64-byte\n// chunks (the `bytes-chunk-array` wire form). This is the identical split rule\n// the record encoder applies to chunked COSE bytes.\nconst CHUNK_MAX_BYTES = 64;\n\n// Split a logical byte string into ≤ 64-byte chunks. Used for the X-Wing\n// `enc` → `kem_ct` wire form. Subarrays are views over the input, never copies.\nexport function chunkKemCt(value: Uint8Array): Uint8Array[] {\n if (value.length === 0) {\n throw new Error('chunkKemCt: refusing to chunk an empty byte string');\n }\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < value.length; i += CHUNK_MAX_BYTES) {\n chunks.push(value.subarray(i, Math.min(i + CHUNK_MAX_BYTES, value.length)));\n }\n return chunks;\n}\n\n// Inverse of chunkKemCt: concatenate the chunked `kem_ct` back into the flat\n// X-Wing `enc`. Performs NO length validation — the caller (unwrap) gates the\n// reassembled length against MLKEM768X25519_ENC_LENGTH before any decapsulation.\nexport function joinKemCt(chunks: ReadonlyArray<Uint8Array>): Uint8Array {\n let total = 0;\n for (const c of chunks) total += c.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const c of chunks) {\n out.set(c, offset);\n offset += c.length;\n }\n return out;\n}\n\n// KEM-driven slot serialization for the slots_mac input.\n//\n// • x25519: each slot → { epk: bstr, wrap: bstr }\n// • mlkem768x25519: each slot → { kem_ct: [ bstr, ... ], wrap: bstr }\n//\n// The hybrid form uses the SAME chunked-array shape as the wire encoder, so the\n// MAC commits to the ciphertext exactly as it appears on-chain. Returns the\n// canonical-CBOR bytes ready for HMAC.\nexport function slotsToMacCbor(\n slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n kem: SealedKem,\n): Uint8Array {\n let value: CanonicalCborValue;\n if (kem === 'x25519') {\n value = (slots as ReadonlyArray<X25519Slot>).map((s) => ({ epk: s.epk, wrap: s.wrap }));\n } else {\n value = (slots as ReadonlyArray<Mlkem768X25519Slot>).map((s) => ({\n // Canonicalize the chunk boundaries before the MAC commits to them:\n // reassemble the logical ciphertext and re-split into canonical ≤ 64-byte\n // chunks. The on-wire `kem_ct` array is a transport detail (the Cardano\n // ledger's 64-byte metadatum cap), and a hostile or non-canonical chunking\n // ([1, 63, …] instead of [64, …]) reassembles to the SAME bytes — so the\n // MAC must be invariant to it. Committing to the verbatim wire chunks would\n // let an attacker re-chunk an honest envelope and break the slots_mac match\n // for an honest recipient. Honest (already-64B-chunked) records are\n // unchanged; a real byte flip still changes the reassembled bytes and is\n // still rejected.\n kem_ct: chunkKemCt(joinKemCt(s.kem_ct)),\n wrap: s.wrap,\n }));\n }\n return encodeCanonicalCbor(value);\n}\n","// Multi-recipient sealed-PoE wrap (age-style ECIES + AEAD-bound slots).\n// Wire-field names are fixed by the standard: scheme, aead, kem, nonce, slots, slots_mac.\n//\n// Two KEM branches share one envelope shape, discriminated on the envelope-level\n// `kem` field:\n//\n// • kem: 'x25519' — classical age-style ECIES. Per-slot epk(32) + wrap(48).\n// • kem: 'mlkem768x25519' — X-Wing hybrid (ML-KEM-768 + X25519). Per-slot the\n// 1120-byte X-Wing enc carried as a chunked byte-string\n// array (`kem_ct`) + wrap(48). No per-slot epk.\n//\n// The slot type is a discriminated union so every consumer is forced — at compile\n// time — to branch on the KEM before touching kem-specific fields.\n\nimport { randomBytes } from '@noble/ciphers/utils.js';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { chacha20Poly1305Encrypt } from '../aead/chacha20-poly1305';\nimport { xchacha20Poly1305Encrypt } from '../aead/xchacha20-poly1305';\nimport { hkdfSha256 } from '../kdf/hkdf';\nimport {\n mlkem768x25519Encapsulate,\n MLKEM768X25519_ENC_LENGTH,\n MLKEM768X25519_ESEED_LENGTH,\n MLKEM768X25519_PUBLIC_KEY_LENGTH,\n} from '../kem/mlkem768x25519';\nimport { x25519Ecdh, x25519PublicKey } from '../kem/x25519';\n\nimport { EciesSealedPoeError } from './errors';\nimport { chunkKemCt, slotsToMacCbor, type SealedKem } from './slots-codec';\n\n// HKDF info strings — fixed protocol labels for KEK derivation and the slot MAC.\n// Byte-length invariants enforce that the SCREAMING_SNAKE constants stay in sync\n// with the on-wire ASCII literals every conformant verifier hashes against.\nexport const CARDANO_POE_HKDF_INFO_KEK: Uint8Array = new TextEncoder().encode('cardano-poe-kek-v1');\n// Hybrid (X-Wing) per-slot KEK label. Distinct from the classical label so a\n// KEK derived under one KEM can never collide with the other. Reused verbatim as\n// the per-slot wrap AEAD AAD, exactly as the classical path reuses its own label.\nexport const CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-kek-mlkem768x25519-v1',\n);\nexport const CARDANO_POE_HKDF_INFO_SLOTS_MAC: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-slots-mac-v1',\n);\n\nconst ZERO_NONCE_12: Uint8Array = new Uint8Array(12);\nconst EMPTY_SALT: Uint8Array = new Uint8Array(0);\nconst X25519_PUBLIC_KEY_LENGTH = 32 as const;\nconst X25519_SECRET_KEY_LENGTH = 32 as const;\nconst CEK_LENGTH = 32 as const;\nconst NONCE_LENGTH = 24 as const;\nconst WRAP_LENGTH = 48 as const;\nconst SLOTS_MAC_LENGTH = 32 as const;\n\nif (CARDANO_POE_HKDF_INFO_KEK.length !== 18) {\n throw new Error('CARDANO_POE_HKDF_INFO_KEK byte-length invariant violated (expected 18)');\n}\nif (CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519.length !== 33) {\n throw new Error(\n 'CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519 byte-length invariant violated (expected 33)',\n );\n}\nif (CARDANO_POE_HKDF_INFO_SLOTS_MAC.length !== 24) {\n throw new Error('CARDANO_POE_HKDF_INFO_SLOTS_MAC byte-length invariant violated (expected 24)');\n}\nif (ZERO_NONCE_12.length !== 12) {\n throw new Error('ZERO_NONCE_12 byte-length invariant violated (expected 12)');\n}\n\n// Classical per-slot wire shape: { epk: bstr(32), wrap: bstr(48) }.\nexport interface X25519Slot {\n readonly epk: Uint8Array;\n readonly wrap: Uint8Array;\n}\n\n// Hybrid per-slot wire shape: { kem_ct: [ bstr .size (1..64) ], wrap: bstr(48) }.\n// `kem_ct` is the 1120-byte X-Wing enc carried as a chunked byte-string array\n// (the Cardano ledger caps any single metadatum bstr at 64 bytes). There is NO\n// per-slot epk and NO per-slot kem field — the KEM identifier is hoisted to\n// envelope scope (every slot shares it).\nexport interface Mlkem768X25519Slot {\n readonly kem_ct: ReadonlyArray<Uint8Array>;\n readonly wrap: Uint8Array;\n}\n\n// Back-compat alias retired: callers branch on the envelope `kem` and use the\n// concrete slot type. The discriminated `SealedEnvelope` below is the only\n// shape consumers should depend on.\n\n// Sealed envelope wire shape (discriminated on `kem`).\nexport type SealedEnvelope =\n | {\n readonly scheme: 1;\n readonly aead: 'xchacha20-poly1305';\n readonly kem: 'x25519';\n readonly nonce: Uint8Array;\n readonly slots: ReadonlyArray<X25519Slot>;\n readonly slots_mac: Uint8Array;\n }\n | {\n readonly scheme: 1;\n readonly aead: 'xchacha20-poly1305';\n readonly kem: 'mlkem768x25519';\n readonly nonce: Uint8Array;\n readonly slots: ReadonlyArray<Mlkem768X25519Slot>;\n readonly slots_mac: Uint8Array;\n };\n\nexport interface SealedPoeOutput {\n readonly envelope: SealedEnvelope;\n readonly ciphertext: Uint8Array;\n}\n\nexport interface WrapArgs {\n readonly plaintext: Uint8Array;\n readonly recipientPublicKeys: ReadonlyArray<Uint8Array>;\n // KEM branch selector. Defaults to 'x25519' for the classical path. The\n // recipient public-key length is validated against the chosen KEM.\n readonly kem?: SealedKem;\n readonly cek?: Uint8Array;\n readonly nonce?: Uint8Array;\n // Deterministic X25519 ephemeral scalars — x25519 branch only.\n readonly ephemeralSecrets?: ReadonlyArray<Uint8Array>;\n // Deterministic X-Wing encapsulation randomness (64 bytes each) — hybrid\n // branch only. One per recipient, parallel to recipientPublicKeys.\n readonly eseeds?: ReadonlyArray<Uint8Array>;\n readonly skipShuffle?: boolean;\n}\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n}\n\n// Anonymity invariant: wire ordering MUST NOT encode \"primary\n// recipient first\". A CSPRNG-keyed Fisher-Yates shuffle uniformly permutes the\n// slot array so trial-decrypt order leaks no recipient identity. The\n// slot-set HMAC is computed AFTER this shuffle, binding the on-wire order.\n//\n// Draw an unbiased index in [0, m) from a CSPRNG uint32 via rejection sampling.\n// A plain `u32 % m` skews toward the low residues whenever `m` does not divide\n// 2^32 evenly: the values [0, 2^32 mod m) each occur one extra time. This\n// function exists purely to produce a UNIFORM permutation, so the bias — though\n// cryptographically negligible — is exactly the property we cannot tolerate.\n// We reject any draw landing in the final partial block [limit, 2^32) and\n// redraw, leaving only the residues that map uniformly onto [0, m).\n// Exported so the rejection-bound arithmetic can be asserted directly in tests\n// without relying on a flaky statistical-distribution check.\nexport function uniformIndexBelow(m: number): number {\n // 2^32 mod m, computed without overflowing the 32-bit space.\n const limit = 0x1_0000_0000 - (0x1_0000_0000 % m);\n const buf = new Uint32Array(1);\n let x: number;\n do {\n crypto.getRandomValues(buf);\n x = buf[0] as number;\n } while (x >= limit);\n return x % m;\n}\n\nfunction csprngShuffle<T>(arr: T[]): void {\n for (let i = arr.length - 1; i > 0; i--) {\n const j = uniformIndexBelow(i + 1);\n const tmp = arr[i] as T;\n arr[i] = arr[j] as T;\n arr[j] = tmp;\n }\n}\n\n// Wrap the CEK for one classical recipient: age-style ECIES stanza.\nfunction wrapSlotX25519(args: {\n pubR: Uint8Array;\n privEph: Uint8Array | undefined;\n cek: Uint8Array;\n slotIdx: number;\n}): X25519Slot {\n const privEph = args.privEph ?? randomBytes(X25519_SECRET_KEY_LENGTH);\n if (privEph.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_EPHEMERAL_SECRET_LENGTH',\n `ephemeralSecrets[${args.slotIdx}] MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${privEph.length}`,\n );\n }\n const epk = x25519PublicKey({ secretKey: privEph });\n const shared = x25519Ecdh({ secretKey: privEph, theirPublicKey: args.pubR });\n // age v1 stanza salt is `epk || pub_R`.\n const kek = hkdfSha256({\n ikm: shared,\n salt: concat(epk, args.pubR),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n // Per-slot wrap AAD MUST be the 18-byte ASCII literal of the KEK info\n // string (never empty AAD).\n const wrap = chacha20Poly1305Encrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK,\n plaintext: args.cek,\n });\n if (wrap.length !== WRAP_LENGTH) {\n throw new Error(`internal: wrap.length=${wrap.length}, expected ${WRAP_LENGTH}`);\n }\n return { epk, wrap };\n}\n\n// Wrap the CEK for one hybrid recipient: X-Wing encapsulation → HKDF → AEAD.\n// The KEK info label doubles as the wrap AEAD AAD, mirroring the classical path.\nfunction wrapSlotMlkem768X25519(args: {\n pubR: Uint8Array;\n eseed: Uint8Array | undefined;\n cek: Uint8Array;\n}): Mlkem768X25519Slot {\n const { enc, ss } = mlkem768x25519Encapsulate({\n publicKey: args.pubR,\n ...(args.eseed !== undefined ? { eseed: args.eseed } : {}),\n });\n if (enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new Error(`internal: enc.length=${enc.length}, expected ${MLKEM768X25519_ENC_LENGTH}`);\n }\n const kek = hkdfSha256({\n ikm: ss,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n length: 32,\n });\n const wrap = chacha20Poly1305Encrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n plaintext: args.cek,\n });\n if (wrap.length !== WRAP_LENGTH) {\n throw new Error(`internal: wrap.length=${wrap.length}, expected ${WRAP_LENGTH}`);\n }\n return { kem_ct: chunkKemCt(enc), wrap };\n}\n\nexport function eciesSealedPoeWrap(args: WrapArgs): SealedPoeOutput {\n const { plaintext, recipientPublicKeys } = args;\n const kem: SealedKem = args.kem ?? 'x25519';\n const n = recipientPublicKeys.length;\n\n // There is no fixed upper bound on slot count; the producer SDK polices the\n // per-record byte budget. Only the lower bound is enforced here.\n if (n < 1) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_EMPTY',\n `recipientPublicKeys.length=${n} must be >= 1`,\n );\n }\n\n const expectedPubLen =\n kem === 'x25519' ? X25519_PUBLIC_KEY_LENGTH : MLKEM768X25519_PUBLIC_KEY_LENGTH;\n for (let i = 0; i < n; i++) {\n const pub = recipientPublicKeys[i];\n if (pub === undefined || pub.length !== expectedPubLen) {\n throw new EciesSealedPoeError(\n 'KEM_EPK_LENGTH_MISMATCH',\n `recipientPublicKeys[${i}] MUST be exactly ${expectedPubLen} bytes for kem='${kem}'`,\n );\n }\n }\n\n if (kem === 'x25519') {\n if (args.eseeds !== undefined) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n \"eseeds is an X-Wing (mlkem768x25519) override and MUST NOT be supplied for kem='x25519'\",\n );\n }\n if (args.ephemeralSecrets !== undefined && args.ephemeralSecrets.length !== n) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n `ephemeralSecrets.length=${args.ephemeralSecrets.length} must match recipientPublicKeys.length=${n}`,\n );\n }\n } else {\n if (args.ephemeralSecrets !== undefined) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n \"ephemeralSecrets is an X25519 override and MUST NOT be supplied for kem='mlkem768x25519'\",\n );\n }\n if (args.eseeds !== undefined) {\n if (args.eseeds.length !== n) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n `eseeds.length=${args.eseeds.length} must match recipientPublicKeys.length=${n}`,\n );\n }\n for (let i = 0; i < n; i++) {\n const eseed = args.eseeds[i]!;\n if (eseed.length !== MLKEM768X25519_ESEED_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_EPHEMERAL_SECRET_LENGTH',\n `eseeds[${i}] MUST be exactly ${MLKEM768X25519_ESEED_LENGTH} bytes, got ${eseed.length}`,\n );\n }\n }\n }\n }\n\n const cek = args.cek ?? randomBytes(CEK_LENGTH);\n const nonce = args.nonce ?? randomBytes(NONCE_LENGTH);\n if (cek.length !== CEK_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_CEK_LENGTH',\n `cek MUST be exactly ${CEK_LENGTH} bytes, got ${cek.length}`,\n );\n }\n if (nonce.length !== NONCE_LENGTH) {\n throw new EciesSealedPoeError(\n 'NONCE_LENGTH_MISMATCH',\n `nonce MUST be exactly ${NONCE_LENGTH} bytes, got ${nonce.length}`,\n );\n }\n\n let envelope: SealedEnvelope;\n if (kem === 'x25519') {\n const slots: X25519Slot[] = [];\n for (let i = 0; i < n; i++) {\n slots.push(\n wrapSlotX25519({\n pubR: recipientPublicKeys[i]!,\n privEph: args.ephemeralSecrets ? (args.ephemeralSecrets[i] as Uint8Array) : undefined,\n cek,\n slotIdx: i,\n }),\n );\n }\n // Anonymity invariant (see csprngShuffle comment).\n if (args.skipShuffle !== true) {\n csprngShuffle(slots);\n }\n const slotsMac = computeSlotsMac(cek, slots, 'x25519');\n envelope = {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'x25519',\n nonce,\n slots,\n slots_mac: slotsMac,\n };\n } else {\n const slots: Mlkem768X25519Slot[] = [];\n for (let i = 0; i < n; i++) {\n slots.push(\n wrapSlotMlkem768X25519({\n pubR: recipientPublicKeys[i]!,\n eseed: args.eseeds ? (args.eseeds[i] as Uint8Array) : undefined,\n cek,\n }),\n );\n }\n if (args.skipShuffle !== true) {\n csprngShuffle(slots);\n }\n const slotsMac = computeSlotsMac(cek, slots, 'mlkem768x25519');\n envelope = {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'mlkem768x25519',\n nonce,\n slots,\n slots_mac: slotsMac,\n };\n }\n\n // Content AEAD AAD is `nonce || slots_mac` (24 + 32 = 56 B).\n const adContent = concat(nonce, envelope.slots_mac);\n const ciphertext = xchacha20Poly1305Encrypt({\n key: cek,\n nonce,\n aad: adContent,\n plaintext,\n });\n\n return { envelope, ciphertext };\n}\n\n// Slot-set MAC binds canonical-CBOR(slots) to the CEK.\n// The slot→CBOR serialization is KEM-driven (`slotsToMacCbor`) so the hybrid\n// kem_ct is authenticated by slots_mac exactly as the classical epk is.\nfunction computeSlotsMac(\n cek: Uint8Array,\n slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n kem: SealedKem,\n): Uint8Array {\n const hmacKey = hkdfSha256({\n ikm: cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsCbor = slotsToMacCbor(slots, kem);\n const slotsMac = hmac(sha256, hmacKey, slotsCbor);\n if (slotsMac.length !== SLOTS_MAC_LENGTH) {\n throw new Error(`internal: slots_mac.length=${slotsMac.length}, expected ${SLOTS_MAC_LENGTH}`);\n }\n return slotsMac;\n}\n","// Isomorphic constant-time byte-equality. crypto-core is browser-safe by\n// design, so we cannot import `node:crypto.timingSafeEqual` — webpack rejects\n// the `node:` scheme in the browser bundle. A pure-JS XOR loop is constant-time\n// for equal-length inputs; length mismatch is a deliberate early-return (the\n// API surface itself leaks length, same as node's timingSafeEqual which throws).\nexport function compareCt(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n // Lengths are equal and `i` stays in-bounds, so both indexes are always\n // defined — no nullish guard is needed (and one would read as a guard for\n // an impossible case).\n for (let i = 0; i < a.length; i++) diff |= (a[i] as number) ^ (b[i] as number);\n return diff === 0;\n}\n","// Multi-recipient sealed-PoE unwrap (age-style trial-decrypt\n// + constant-time slots_mac binding + partitioning-oracle length pre-checks).\n//\n// Two forms (mutually exclusive — exactly one MUST be supplied):\n//\n// • Single-priv form: `recipientSecretKey: Uint8Array` — the standalone-verifier\n// path. Runs the trial-decrypt loop over `envelope.slots` once.\n//\n// • Multi-priv form: `recipientSecretKeys: ReadonlyArray<Uint8Array>` — for the\n// trial-decrypt scan of a rotated identity holding `[currentPriv, ...archivedPrivs]`.\n// Caller supplies the order; the iterator runs outer-loop = privkey ×\n// inner-loop = slot, short-circuiting on the first cross-priv match that\n// passes slots_mac verification. The recommended caller order\n// is `[currentPriv, ...previousPrivsReversed]` (newest archive first).\n//\n// Constant-time-N (default `true`) applies PER PRIV (the inner loop): all slots\n// are entered regardless of match position. The outer loop short-circuits on\n// first cross-priv match — the cross-priv channel is intrinsic to trial-decrypt\n//\n// Both KEM branches share this control flow. The per-slot recovery body differs:\n// • x25519: X25519 ECDH → HKDF → AEAD-unwrap; may throw on a low-order\n// epk (RFC 7748 §6.1 contributory-check rejection), handled\n// as a non-match.\n// • mlkem768x25519: X-Wing decapsulate → HKDF → AEAD-unwrap; NEVER throws on\n// attacker wire data (ML-KEM implicit rejection yields a\n// pseudorandom shared secret), so no try/catch around it.\n\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { chacha20Poly1305Decrypt } from '../aead/chacha20-poly1305';\nimport { AeadVerificationError } from '../aead/errors';\nimport { xchacha20Poly1305Decrypt } from '../aead/xchacha20-poly1305';\nimport { hkdfSha256 } from '../kdf/hkdf';\nimport { mlkem768x25519Decapsulate, MLKEM768X25519_ENC_LENGTH } from '../kem/mlkem768x25519';\nimport { x25519Ecdh, X25519LowOrderPointError, x25519PublicKey } from '../kem/x25519';\nimport { compareCt } from '../util/compare-ct';\n\nimport { EciesSealedPoeError } from './errors';\nimport { joinKemCt, slotsToMacCbor } from './slots-codec';\nimport {\n CARDANO_POE_HKDF_INFO_KEK,\n CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n type Mlkem768X25519Slot,\n type SealedEnvelope,\n type X25519Slot,\n} from './wrap';\n\nexport type UnwrapFailureReason = 'WRONG_RECIPIENT_KEY' | 'TAMPERED_HEADER' | 'TAMPERED_CIPHERTEXT';\n\nexport type UnwrapResult =\n | { readonly matched: true; readonly plaintext: Uint8Array }\n | { readonly matched: false; readonly reason: UnwrapFailureReason };\n\n// Unified recipient key bundle. Callers hold BOTH the X25519\n// private-key chain (current + archived, for classical and rotation history)\n// AND the X-Wing secret seed(s) (for the hybrid KEM), without knowing which a\n// given record was sealed under. They pass the whole bundle; the unwrap /\n// trial-decrypt dispatch selects the correct secret list from `envelope.kem`:\n//\n// • kem === 'x25519' → bundle.x25519PrivateKeys\n// • kem === 'mlkem768x25519' → bundle.mlkem768x25519SecretSeeds\n//\n// Both lists are ordered newest-first (caller's responsibility — the outer\n// trial-decrypt loop scans them in order). A list MAY be empty when the\n// recipient holds no key for that KEM (e.g. archived-only X25519 identities\n// predate the hybrid KEM, so their hybrid seed list is empty); a bundle whose\n// selected list is empty unwraps to a clean WRONG_RECIPIENT_KEY / no_aead_pass\n// without touching any KEM primitive.\nexport interface RecipientKeyBundle {\n readonly x25519PrivateKeys: ReadonlyArray<Uint8Array>;\n readonly mlkem768x25519SecretSeeds: ReadonlyArray<Uint8Array>;\n}\n\n// Select the secret-key list a bundle contributes for the given envelope KEM.\n// The single dispatch seam — wrap and trial-decrypt both route through here so\n// the per-KEM selection lives in exactly one place.\nfunction selectBundleSecrets(\n envelope: SealedEnvelope,\n bundle: RecipientKeyBundle,\n): ReadonlyArray<Uint8Array> {\n return envelope.kem === 'x25519' ? bundle.x25519PrivateKeys : bundle.mlkem768x25519SecretSeeds;\n}\n\ninterface UnwrapArgsCommon {\n readonly envelope: SealedEnvelope;\n readonly ciphertext: Uint8Array;\n readonly constantTimeN?: boolean;\n // Test-only instrumentation for constant-time-N verification.\n // The unwrap fn bumps `count` once per inner-loop iteration entered. In the\n // multi-priv path, `count` is reset at the start of each outer iteration and\n // — when `perPrivCounts` is provided — the final per-priv inner count is\n // appended after that priv's inner loop completes. Production callers never\n // pass this.\n readonly _slotsAttemptedOut?: { count: number; perPrivCounts?: number[] };\n // Test-only multi-priv outer-loop iteration counter. Bumped to `k + 1` at\n // the start of each outer-loop iteration. Production callers never pass this.\n readonly _privsAttemptedOut?: { count: number };\n}\n\nexport interface UnwrapArgsSinglePriv extends UnwrapArgsCommon {\n readonly recipientSecretKey: Uint8Array;\n}\n\nexport interface UnwrapArgsMultiPriv extends UnwrapArgsCommon {\n readonly recipientSecretKeys: ReadonlyArray<Uint8Array>;\n}\n\n// Bundle form of the multi-priv path: the caller passes both KEMs' secret\n// lists and the dispatch picks the right one from `envelope.kem`. This is the\n// surface every read-path consumer (inbox decrypt, CLI decrypt, standalone\n// recipient verifier) should use — they hold the whole identity key bundle and\n// must NOT pre-select a list or rebuild slots themselves.\nexport interface UnwrapArgsBundle extends UnwrapArgsCommon {\n readonly recipientKeyBundle: RecipientKeyBundle;\n}\n\nexport type UnwrapArgs = UnwrapArgsSinglePriv | UnwrapArgsMultiPriv | UnwrapArgsBundle;\n\n// Trial-decrypt-only sibling of eciesSealedPoeUnwrap. Runs the\n// per-slot AEAD + slots_mac check but NEVER calls the content AEAD (which\n// requires the off-chain `ciphertext` blob, not available at trial-decrypt\n// time). Used by an inbox-scan agent to discover readable records before\n// fetching their ciphertext.\ninterface TrialDecryptOnlyArgsCommon {\n readonly envelope: SealedEnvelope;\n readonly constantTimeN?: boolean;\n readonly _slotsAttemptedOut?: { count: number; perPrivCounts?: number[] };\n readonly _privsAttemptedOut?: { count: number };\n}\n\n// Exactly one of `recipientSecretKeys` (flat, KEM-pre-selected) or\n// `recipientKeyBundle` (whole bundle, KEM dispatched from `envelope.kem`).\n// Inbox-scan consumers pass the bundle; the low-level / parity tests pass the\n// flat list directly.\nexport type TrialDecryptOnlyArgs = TrialDecryptOnlyArgsCommon &\n (\n | { readonly recipientSecretKeys: ReadonlyArray<Uint8Array> }\n | { readonly recipientKeyBundle: RecipientKeyBundle }\n );\n\nexport type TrialDecryptOnlyResult =\n | { readonly kind: 'match'; readonly slotIdx: number; readonly cek: Uint8Array }\n | { readonly kind: 'no_aead_pass' }\n | { readonly kind: 'aead_pass_no_mac_match' };\n\nconst ZERO_NONCE_12: Uint8Array = new Uint8Array(12);\nconst EMPTY_SALT: Uint8Array = new Uint8Array(0);\nconst X25519_SECRET_KEY_LENGTH = 32 as const;\nconst X25519_PUBLIC_KEY_LENGTH = 32 as const;\nconst NONCE_LENGTH = 24 as const;\nconst WRAP_LENGTH = 48 as const;\nconst SLOTS_MAC_LENGTH = 32 as const;\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n}\n\n// Partitioning-oracle defence: every wire\n// length MUST be validated before any KEM/AEAD primitive is invoked, so malformed\n// records cannot probe per-slot failure ordering. Shared between\n// `eciesSealedPoeUnwrap` (single- and multi-priv) and `eciesSealedPoeTrialDecrypt`\n// to guarantee byte-identical pre-trial behaviour and to keep the dispatch\n// invariant in one place. For the hybrid branch this includes reassembling each\n// slot's `kem_ct` and asserting the flat enc length BEFORE any decapsulation.\nfunction assertEnvelopeStructure(\n envelope: SealedEnvelope,\n multiPrivKeys?: ReadonlyArray<Uint8Array>,\n singlePrivKey?: Uint8Array,\n): void {\n if (envelope.scheme !== 1) {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_ENC_VERSION',\n `envelope.scheme=${String(envelope.scheme)} unsupported (expected 1)`,\n );\n }\n if (envelope.aead !== 'xchacha20-poly1305') {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_AEAD_ALG',\n `envelope.aead=${String(envelope.aead)} unsupported (expected 'xchacha20-poly1305')`,\n );\n }\n if (envelope.kem !== 'x25519' && envelope.kem !== 'mlkem768x25519') {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_KEM_ALG',\n `envelope.kem=${String((envelope as { kem: string }).kem)} unsupported (expected 'x25519' or 'mlkem768x25519')`,\n );\n }\n\n // Envelope-level length pre-checks in this exact order.\n const n = envelope.slots.length;\n if (n < 1) {\n throw new EciesSealedPoeError('ENC_SLOTS_EMPTY', `envelope.slots.length=${n} must be >= 1`);\n }\n if (envelope.nonce.length !== NONCE_LENGTH) {\n throw new EciesSealedPoeError(\n 'NONCE_LENGTH_MISMATCH',\n `envelope.nonce MUST be exactly ${NONCE_LENGTH} bytes, got ${envelope.nonce.length}`,\n );\n }\n if (envelope.slots_mac.length !== SLOTS_MAC_LENGTH) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_MAC_INVALID_LENGTH',\n `envelope.slots_mac MUST be exactly ${SLOTS_MAC_LENGTH} bytes, got ${envelope.slots_mac.length}`,\n );\n }\n\n // Per-slot length pre-checks — KEM-driven. ALL slots are validated here,\n // before any decapsulation, so the trial-decrypt loop never observes a\n // malformed slot (partitioning-oracle-safe ordering).\n if (envelope.kem === 'x25519') {\n for (let i = 0; i < n; i++) {\n const slot = envelope.slots[i]!;\n if (slot.epk.length !== X25519_PUBLIC_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'KEM_EPK_LENGTH_MISMATCH',\n `envelope.slots[${i}].epk MUST be exactly ${X25519_PUBLIC_KEY_LENGTH} bytes, got ${slot.epk.length}`,\n );\n }\n if (slot.wrap.length !== WRAP_LENGTH) {\n throw new EciesSealedPoeError(\n 'WRAP_LENGTH_MISMATCH',\n `envelope.slots[${i}].wrap MUST be exactly ${WRAP_LENGTH} bytes, got ${slot.wrap.length}`,\n );\n }\n }\n } else {\n for (let i = 0; i < n; i++) {\n const slot = envelope.slots[i]!;\n const enc = joinKemCt(slot.kem_ct);\n if (enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new EciesSealedPoeError(\n 'KEM_CT_LENGTH_MISMATCH',\n `envelope.slots[${i}].kem_ct MUST reassemble to exactly ${MLKEM768X25519_ENC_LENGTH} bytes, got ${enc.length}`,\n );\n }\n if (slot.wrap.length !== WRAP_LENGTH) {\n throw new EciesSealedPoeError(\n 'WRAP_LENGTH_MISMATCH',\n `envelope.slots[${i}].wrap MUST be exactly ${WRAP_LENGTH} bytes, got ${slot.wrap.length}`,\n );\n }\n }\n }\n\n if (multiPrivKeys !== undefined) {\n for (let i = 0; i < multiPrivKeys.length; i++) {\n if (multiPrivKeys[i]!.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n `recipientSecretKeys[${i}] MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${multiPrivKeys[i]!.length}`,\n );\n }\n }\n } else if (singlePrivKey !== undefined) {\n if (singlePrivKey.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n `recipientSecretKey MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${singlePrivKey.length}`,\n );\n }\n }\n}\n\n// Classical (x25519) per-slot recovery body. Returns the CEK on the first\n// AEAD-tag success; null otherwise. `liveSlot` distinguishes the real-work path\n// (attempt the AEAD unwrap) from the constant-time-N dummy path (do the ECDH +\n// HKDF but skip the AEAD, since a CEK is already in hand).\nfunction tryX25519Slot(args: {\n slot: X25519Slot;\n recipientSecretKey: Uint8Array;\n pubRLocal: Uint8Array;\n liveSlot: boolean;\n}): Uint8Array | null {\n // A slot's `epk` is attacker-influenceable wire data. A small-order\n // Montgomery point makes the X25519 shared secret all-zero, which the KEM\n // rejects per RFC 7748 §6.1. Such a slot can never have been produced by a\n // conformant wrap for THIS recipient, so it is a non-match — handled here\n // identically to an AEAD-tag failure (skip the slot, keep iterating so the\n // constant-time-N loop shape is preserved). Only the contributory-check\n // rejection is swallowed; any other error propagates.\n if (args.liveSlot) {\n try {\n const shared = x25519Ecdh({\n secretKey: args.recipientSecretKey,\n theirPublicKey: args.slot.epk,\n });\n const kek = hkdfSha256({\n ikm: shared,\n salt: concat(args.slot.epk, args.pubRLocal),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n return chacha20Poly1305Decrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK,\n ciphertext: args.slot.wrap,\n });\n } catch (e) {\n if (!(e instanceof AeadVerificationError) && !(e instanceof X25519LowOrderPointError)) {\n throw e;\n }\n return null;\n }\n }\n // Constant-time-N dummy path: mirror the real-work ECDH + HKDF, still\n // tolerating a low-order epk in a later slot so it cannot turn a successful\n // unwrap into a throw.\n try {\n const shared = x25519Ecdh({\n secretKey: args.recipientSecretKey,\n theirPublicKey: args.slot.epk,\n });\n hkdfSha256({\n ikm: shared,\n salt: concat(args.slot.epk, args.pubRLocal),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n } catch (e) {\n if (!(e instanceof X25519LowOrderPointError)) throw e;\n }\n return null;\n}\n\n// Hybrid (mlkem768x25519) per-slot recovery body. X-Wing decapsulate NEVER\n// throws on attacker wire data (ML-KEM implicit rejection), so there is no\n// try/catch: a wrong shared secret simply yields a KEK that fails the AEAD tag.\n// The dummy (constant-time-N) path runs a FULL decapsulate + HKDF so matching\n// and non-matching slots cost the same X-Wing work.\nfunction tryMlkem768X25519Slot(args: {\n slot: Mlkem768X25519Slot;\n recipientSecretKey: Uint8Array;\n liveSlot: boolean;\n}): Uint8Array | null {\n // kem_ct length was validated to reassemble to MLKEM768X25519_ENC_LENGTH in\n // assertEnvelopeStructure, so this join + decapsulate is constant-work.\n const enc = joinKemCt(args.slot.kem_ct);\n const ss = mlkem768x25519Decapsulate({ secretSeed: args.recipientSecretKey, enc });\n const kek = hkdfSha256({\n ikm: ss,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n length: 32,\n });\n if (!args.liveSlot) {\n // Dummy path: full decapsulate + HKDF already done above; skip only the\n // AEAD attempt (a CEK is already in hand).\n return null;\n }\n try {\n return chacha20Poly1305Decrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n ciphertext: args.slot.wrap,\n });\n } catch (e) {\n if (!(e instanceof AeadVerificationError)) throw e;\n return null;\n }\n}\n\n// Per-priv inner trial-decrypt loop with slot-index reporting, KEM-driven.\n// Enters every slot when constantTimeN; the dummy path keeps per-iteration cost\n// uniform regardless of which slot matched.\nfunction tryRecipientUnwrapWithIdx(\n envelope: SealedEnvelope,\n recipientSecretKey: Uint8Array,\n constantTimeN: boolean,\n slotsAttemptedOut: { count: number; perPrivCounts?: number[] } | undefined,\n): { cek: Uint8Array; slotIdx: number } | null {\n const n = envelope.slots.length;\n let cek: Uint8Array | null = null;\n let matchedSlotIdx = -1;\n\n if (envelope.kem === 'x25519') {\n const pubRLocal = x25519PublicKey({ secretKey: recipientSecretKey });\n for (let i = 0; i < n; i++) {\n if (slotsAttemptedOut !== undefined) {\n slotsAttemptedOut.count = i + 1;\n }\n const candidate = tryX25519Slot({\n slot: envelope.slots[i]!,\n recipientSecretKey,\n pubRLocal,\n liveSlot: cek === null,\n });\n if (cek === null && candidate !== null) {\n cek = candidate;\n matchedSlotIdx = i;\n }\n if (cek !== null && !constantTimeN) break;\n }\n } else {\n for (let i = 0; i < n; i++) {\n if (slotsAttemptedOut !== undefined) {\n slotsAttemptedOut.count = i + 1;\n }\n const candidate = tryMlkem768X25519Slot({\n slot: envelope.slots[i]!,\n recipientSecretKey,\n liveSlot: cek === null,\n });\n if (cek === null && candidate !== null) {\n cek = candidate;\n matchedSlotIdx = i;\n }\n if (cek !== null && !constantTimeN) break;\n }\n }\n return cek === null ? null : { cek, slotIdx: matchedSlotIdx };\n}\n\n// Back-compat wrapper preserved for callers that only care about the CEK\n// (single-priv path inside `eciesSealedPoeUnwrap`).\nfunction tryRecipientUnwrap(\n envelope: SealedEnvelope,\n recipientSecretKey: Uint8Array,\n constantTimeN: boolean,\n slotsAttemptedOut: { count: number; perPrivCounts?: number[] } | undefined,\n): Uint8Array | null {\n return (\n tryRecipientUnwrapWithIdx(envelope, recipientSecretKey, constantTimeN, slotsAttemptedOut)\n ?.cek ?? null\n );\n}\n\n// Slot-set MAC bytes, KEM-driven so the hybrid kem_ct is\n// committed exactly as it appears on-wire. Constant across the multi-priv outer\n// loop (depends only on envelope.slots), so callers compute it once.\nfunction slotsMacCborBytes(envelope: SealedEnvelope): Uint8Array {\n return slotsToMacCbor(\n envelope.slots as ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n envelope.kem,\n );\n}\n\nexport function eciesSealedPoeUnwrap(args: UnwrapArgs): UnwrapResult {\n const { envelope, ciphertext } = args;\n const constantTimeN = args.constantTimeN ?? true;\n\n // Exactly-one-of validation across the three UnwrapArgs forms (single-priv,\n // flat multi-priv, bundle). Runs before any AEAD / wire-shape work so a\n // malformed call cannot probe per-slot AEAD timing. The bundle form resolves\n // to a flat multi-priv list here by dispatching on `envelope.kem` — from this\n // point the loop is identical regardless of how the caller supplied keys.\n const hasSingle = 'recipientSecretKey' in args;\n const hasBundle = 'recipientKeyBundle' in args;\n const multiPrivKeys: ReadonlyArray<Uint8Array> | undefined = hasBundle\n ? selectBundleSecrets(envelope, (args as UnwrapArgsBundle).recipientKeyBundle)\n : 'recipientSecretKeys' in args\n ? (args as UnwrapArgsMultiPriv).recipientSecretKeys\n : undefined;\n const hasMulti = multiPrivKeys !== undefined;\n if (hasSingle === hasMulti) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'exactly one of recipientSecretKey / recipientSecretKeys / recipientKeyBundle MUST be supplied',\n );\n }\n // A bundle selecting an empty list for this KEM means the recipient holds no\n // key of the matching kind (e.g. an archived-only identity facing a hybrid\n // record). That is a legitimate non-match, NOT a malformed call — return a\n // clean WRONG_RECIPIENT_KEY without invoking any KEM primitive. The flat\n // multi-priv form keeps the original \"empty array is a programmer error\"\n // contract its callers (and step-3 tests) rely on.\n if (hasMulti && multiPrivKeys!.length === 0) {\n if (hasBundle) {\n return { matched: false, reason: 'WRONG_RECIPIENT_KEY' };\n }\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'recipientSecretKeys MUST be a non-empty array, got length=0',\n );\n }\n\n // Partitioning-oracle pre-checks; per-priv length validation happens\n // inside `assertEnvelopeStructure`.\n if (hasMulti) {\n assertEnvelopeStructure(envelope, multiPrivKeys, undefined);\n } else {\n assertEnvelopeStructure(envelope, undefined, (args as UnwrapArgsSinglePriv).recipientSecretKey);\n }\n\n // Trial-decrypt loop. With constantTimeN=true the loop\n // entries are uniform regardless of match position; the per-iteration body\n // does the same KEM + HKDF work in both branches.\n\n let matchedCek: Uint8Array | null = null;\n let anyCandidateRecovered = false;\n\n if (hasSingle) {\n const recipientSecretKey = (args as UnwrapArgsSinglePriv).recipientSecretKey;\n const cek = tryRecipientUnwrap(\n envelope,\n recipientSecretKey,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (cek === null) {\n return { matched: false, reason: 'WRONG_RECIPIENT_KEY' };\n }\n // Slot-set MAC verification. Use compareCt to\n // avoid leaking byte-position via early-exit on first mismatching byte.\n const slotsCbor = slotsMacCborBytes(envelope);\n const hmacKey = hkdfSha256({\n ikm: cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsMacCalc = hmac(sha256, hmacKey, slotsCbor);\n if (!compareCt(slotsMacCalc, envelope.slots_mac)) {\n return { matched: false, reason: 'TAMPERED_HEADER' };\n }\n matchedCek = cek;\n } else {\n // The slots-CBOR is constant across the outer loop (depends only on\n // envelope.slots) — compute once before the loop to keep per-priv cost\n // identical to the single-priv path.\n const slotsCbor = slotsMacCborBytes(envelope);\n const recipientSecretKeys = multiPrivKeys!;\n for (let k = 0; k < recipientSecretKeys.length; k++) {\n if (args._privsAttemptedOut !== undefined) {\n args._privsAttemptedOut.count = k + 1;\n }\n if (args._slotsAttemptedOut !== undefined) {\n args._slotsAttemptedOut.count = 0;\n }\n const cek = tryRecipientUnwrap(\n envelope,\n recipientSecretKeys[k]!,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (args._slotsAttemptedOut?.perPrivCounts !== undefined) {\n args._slotsAttemptedOut.perPrivCounts.push(args._slotsAttemptedOut.count);\n }\n if (cek === null) continue;\n // Slot-set MAC verification per priv that recovered a candidate CEK.\n const hmacKey = hkdfSha256({\n ikm: cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsMacCalc = hmac(sha256, hmacKey, slotsCbor);\n // The outer cross-priv loop short-circuits on the first priv whose\n // recovered CEK also passes slots_mac. This intentionally leaks \"which\n // priv matched\" → \"how many key rotations the recipient has performed\".\n // We accept it: trial-decrypt runs client-side, so this timing is only\n // locally observable, and the leak is a weak ordering signal, not a\n // key/plaintext oracle. Making the outer loop constant-work would cost a\n // FULL KEM decapsulation (an X25519 ECDH, or — for the hybrid branch — a\n // full X-Wing ML-KEM-768 + X25519 decapsulation) for EVERY archived priv\n // on EVERY record, which for the hybrid case is the dominant cost; the\n // benefit (hiding a count the user already knows) does not justify it.\n // The inner per-slot loop IS held constant-work (constant-time-N).\n if (compareCt(slotsMacCalc, envelope.slots_mac)) {\n matchedCek = cek;\n break;\n }\n anyCandidateRecovered = true;\n }\n if (matchedCek === null) {\n return {\n matched: false,\n reason: anyCandidateRecovered ? 'TAMPERED_HEADER' : 'WRONG_RECIPIENT_KEY',\n };\n }\n }\n\n // Content AEAD AAD is `nonce || slots_mac`.\n const adContent = concat(envelope.nonce, envelope.slots_mac);\n try {\n const plaintext = xchacha20Poly1305Decrypt({\n key: matchedCek,\n nonce: envelope.nonce,\n aad: adContent,\n ciphertext,\n });\n return { matched: true, plaintext };\n } catch (e) {\n if (!(e instanceof AeadVerificationError)) throw e;\n return { matched: false, reason: 'TAMPERED_CIPHERTEXT' };\n }\n}\n\n// Trial-decrypt half of the sealed-PoE unwrap algorithm:\n// recovers the CEK + slot index without touching the content AEAD. Used by an\n// inbox-scan agent where the on-chain `metadata_cbor` envelope is available but\n// the off-chain ciphertext blob is fetched lazily only when the user invokes\n// Decrypt.\n//\n// Mirrors the multi-priv branch of `eciesSealedPoeUnwrap`: same\n// partitioning-oracle pre-checks, same per-priv inner loop, same\n// constant-time-N invariant (default `true` — MANDATORY for untrusted scan\n// agents), same `compareCt` slots_mac check. Differs only\n// in the return shape: `{kind: 'match', slotIdx, cek}` instead of plaintext;\n// `{kind: 'aead_pass_no_mac_match'}`\n// instead of `TAMPERED_HEADER`; `{kind: 'no_aead_pass'}` instead of\n// `WRONG_RECIPIENT_KEY`. Cross-priv variable-time short-circuit is preserved\n// (leaks \"which priv matched\" → \"how many rotations\",\n// a documented weak ordering signal).\nexport function eciesSealedPoeTrialDecrypt(args: TrialDecryptOnlyArgs): TrialDecryptOnlyResult {\n const { envelope } = args;\n const constantTimeN = args.constantTimeN ?? true;\n\n // Bundle form selects the per-KEM list from `envelope.kem`; flat form is\n // already KEM-pre-selected. An empty bundle list for this KEM is a clean\n // no_aead_pass (the recipient holds no key of the matching kind), whereas an\n // empty flat list stays a programmer error (its callers / step-3 tests rely\n // on the throw).\n const hasBundle = 'recipientKeyBundle' in args;\n const recipientSecretKeys: ReadonlyArray<Uint8Array> = hasBundle\n ? selectBundleSecrets(envelope, args.recipientKeyBundle)\n : args.recipientSecretKeys;\n\n if (recipientSecretKeys.length === 0) {\n if (hasBundle) {\n return { kind: 'no_aead_pass' };\n }\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'recipientSecretKeys MUST be a non-empty array, got length=0',\n );\n }\n assertEnvelopeStructure(envelope, recipientSecretKeys, undefined);\n\n const slotsCbor = slotsMacCborBytes(envelope);\n\n let anyCandidateRecovered = false;\n for (let k = 0; k < recipientSecretKeys.length; k++) {\n if (args._privsAttemptedOut !== undefined) {\n args._privsAttemptedOut.count = k + 1;\n }\n if (args._slotsAttemptedOut !== undefined) {\n args._slotsAttemptedOut.count = 0;\n }\n const candidate = tryRecipientUnwrapWithIdx(\n envelope,\n recipientSecretKeys[k]!,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (args._slotsAttemptedOut?.perPrivCounts !== undefined) {\n args._slotsAttemptedOut.perPrivCounts.push(args._slotsAttemptedOut.count);\n }\n if (candidate === null) continue;\n const hmacKey = hkdfSha256({\n ikm: candidate.cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsMacCalc = hmac(sha256, hmacKey, slotsCbor);\n if (compareCt(slotsMacCalc, envelope.slots_mac)) {\n return { kind: 'match', slotIdx: candidate.slotIdx, cek: candidate.cek };\n }\n anyCandidateRecovered = true;\n }\n return anyCandidateRecovered ? { kind: 'aead_pass_no_mac_match' } : { kind: 'no_aead_pass' };\n}\n","// Raw-seed identity surface. A developer holding a 32-byte seed (e.g. the\n// decoded hex of a key exported from another tool) can derive every keypair,\n// obtain their age recipient strings, get a path-1 Signer, build the\n// RecipientKeyBundle the unwrap dispatch consumes, and decrypt a sealed PoE —\n// all from the public SDK, without a web account envelope.\n//\n// The seed is the only secret this module touches. Callers are responsible for\n// sourcing it securely; the SDK never persists or logs it.\n\nimport {\n deriveEd25519KeypairFromSeed,\n deriveX25519KeypairFromSeed,\n deriveMlKem768X25519KeypairFromSeed,\n type DerivedEd25519KeyPair,\n type DerivedX25519KeyPair,\n type DerivedMlKem768X25519KeyPair,\n} from '@cardanowall/crypto-core/seed-derive';\nimport {\n encodeAgeX25519Recipient,\n encodeAgeXWingRecipient,\n} from '@cardanowall/crypto-core/recipient';\nimport {\n eciesSealedPoeUnwrap,\n type RecipientKeyBundle,\n type SealedEnvelope,\n type UnwrapResult,\n} from '@cardanowall/crypto-core/sealed-poe';\nimport { signEd25519 } from '@cardanowall/crypto-core/sig';\n\nimport type { Signer } from '../client/types';\n\nexport interface SeedKeys {\n readonly ed25519: DerivedEd25519KeyPair;\n readonly x25519: DerivedX25519KeyPair;\n readonly mlkem768x25519: DerivedMlKem768X25519KeyPair;\n}\n\n// Derive the three identity keypairs from a 32-byte seed: Ed25519 (record\n// signing), X25519 (classical KEM), and ML-KEM-768 + X25519 / X-Wing (hybrid\n// post-quantum KEM). Each keypair is the same byte-for-byte value the account\n// envelope would expose — the seed alone fully determines the identity.\nexport function deriveKeysFromSeed(seed: Uint8Array): SeedKeys {\n return {\n ed25519: deriveEd25519KeypairFromSeed(seed),\n x25519: deriveX25519KeypairFromSeed(seed),\n mlkem768x25519: deriveMlKem768X25519KeypairFromSeed(seed),\n };\n}\n\nexport interface SeedRecipients {\n /** Classical age recipient (\"age1…\") for the X25519 KEM. */\n readonly age: string;\n /** X-Wing hybrid recipient (\"age1pqc…\") for the ML-KEM-768 + X25519 KEM. */\n readonly age1pqc: string;\n}\n\n// The recipient strings other senders use to address this identity. Both\n// always exist for any seed: the X-Wing keypair derives for free, so every\n// identity can receive hybrid sealed records even when it publishes via the\n// classical X25519 path.\nexport function recipientsFromSeed(seed: Uint8Array): SeedRecipients {\n const keys = deriveKeysFromSeed(seed);\n return {\n age: encodeAgeX25519Recipient(keys.x25519.publicKey),\n age1pqc: encodeAgeXWingRecipient(keys.mlkem768x25519.publicKey),\n };\n}\n\n// An in-memory path-1 Signer for the publish helpers / off-host signing\n// surface. The derived Ed25519 secret lives only inside this closure; the\n// SDK's publish path touches just `signerPubkey` (public) and the 64-byte\n// signature (public). The 32-byte HKDF output IS the noble Ed25519 seed, so it\n// feeds `signEd25519` directly.\nexport function signerFromSeed(seed: Uint8Array): Signer {\n const { secretKey, publicKey } = deriveEd25519KeypairFromSeed(seed);\n return {\n signerPubkey: publicKey,\n async sign(sigStructureBytes: Uint8Array): Promise<Uint8Array> {\n return signEd25519({ seed: secretKey, message: sigStructureBytes });\n },\n };\n}\n\n// The unified RecipientKeyBundle for the trial-decrypt / unwrap dispatch. A\n// single active identity contributes a one-element X25519 private-key chain and\n// a one-element X-Wing secret-seed list; the unwrap dispatch selects the right\n// list from `envelope.kem`.\nexport function recipientKeyBundleFromSeed(seed: Uint8Array): RecipientKeyBundle {\n const keys = deriveKeysFromSeed(seed);\n return {\n x25519PrivateKeys: [keys.x25519.secretKey],\n mlkem768x25519SecretSeeds: [keys.mlkem768x25519.secretSeed],\n };\n}\n\nexport interface DecryptSealedFromSeedArgs {\n readonly seed: Uint8Array;\n readonly envelope: SealedEnvelope;\n readonly ciphertext: Uint8Array;\n}\n\n// Decrypt a sealed PoE envelope + ciphertext from the seed. Builds the bundle\n// and routes through the existing unwrap dispatch, which selects the correct\n// secret list from `envelope.kem` — so the same call decrypts both classical\n// (x25519) and hybrid (mlkem768x25519) records. Returns the discriminated\n// UnwrapResult; it never throws on an authentication failure (wrong key,\n// tampered header, tampered ciphertext) — callers branch on `result.matched`.\nexport function decryptSealedFromSeed(args: DecryptSealedFromSeedArgs): UnwrapResult {\n return eciesSealedPoeUnwrap({\n envelope: args.envelope,\n ciphertext: args.ciphertext,\n recipientKeyBundle: recipientKeyBundleFromSeed(args.seed),\n });\n}\n"]}