{"version":3,"file":"wrapped-CdwPPcLY.mjs","names":[],"sources":["../src/codecs/wrapped/layout.ts","../src/codecs/wrapped/key.ts","../src/codecs/wrapped/index.ts"],"sourcesContent":["import type { webcrypto } from \"node:crypto\";\nimport type { Id, Prefix } from \"../../types.js\";\nimport {\n  decryptPayload,\n  encryptPayload,\n  hmacSignTruncated,\n  timingSafeEqual,\n} from \"../_kernel/crypto.js\";\nimport { len32ByteLength, writeLen32 } from \"../_kernel/bytes.js\";\nimport { payloadBytesFromId, toWireId } from \"../../wire/envelope.js\";\nimport { payloadByteLength } from \"../../wire/invariants.js\";\n\nconst laneByteLength = 8;\nconst tagByteLength = 8;\n// Runtime guard: laneByteLength + tagByteLength must equal payloadByteLength.\n/* v8 ignore start -- only fires if layout constants are misconfigured */\nif (laneByteLength + tagByteLength !== payloadByteLength) {\n  throw new Error(\n    `wrapped layout invariant violated: ${laneByteLength} + ${tagByteLength} !== ${payloadByteLength}`,\n  );\n}\n/* v8 ignore stop */\nconst laneHalfByteLength = laneByteLength / 2;\n\ntype LayoutWrappingKey = {\n  aesKey: webcrypto.CryptoKey;\n  hmacKey: webcrypto.CryptoKey;\n};\n\ntype LayoutWrappedKind = \"u32\" | \"i32\" | \"u64\" | \"i64\";\ntype LayoutLookupKey<K extends LayoutWrappedKind> = K extends \"u32\" | \"i32\" ? number : bigint;\n\nfunction writeU32Lane(value: number, lane: Uint8Array): void {\n  lane[0] = 0;\n  lane[1] = 0;\n  lane[2] = 0;\n  lane[3] = 0;\n  lane[4] = (value >>> 24) & 0xff;\n  lane[5] = (value >>> 16) & 0xff;\n  lane[6] = (value >>> 8) & 0xff;\n  lane[7] = value & 0xff;\n}\n\nfunction readU32Lane(lane: Uint8Array): number | null {\n  for (let i = 0; i < laneHalfByteLength; i++) {\n    if (lane[i] !== 0) return null;\n  }\n  return ((lane[4]! << 24) | (lane[5]! << 16) | (lane[6]! << 8) | lane[7]!) >>> 0;\n}\n\nfunction writeI32Lane(value: number, lane: Uint8Array): void {\n  lane.fill(value < 0 ? 0xff : 0x00, 0, laneHalfByteLength);\n  new DataView(lane.buffer, lane.byteOffset, lane.byteLength).setInt32(4, value, false);\n}\n\nfunction readI32Lane(lane: Uint8Array): number | null {\n  const signExtension = (lane[laneHalfByteLength]! & 0x80) === 0 ? 0x00 : 0xff;\n  for (let i = 0; i < laneHalfByteLength; i++) {\n    if (lane[i] !== signExtension) return null;\n  }\n  return new DataView(lane.buffer, lane.byteOffset, lane.byteLength).getInt32(4, false);\n}\n\nfunction writeU64Lane(value: bigint, lane: Uint8Array): void {\n  new DataView(lane.buffer, lane.byteOffset, lane.byteLength).setBigUint64(0, value, false);\n}\n\nfunction readU64Lane(lane: Uint8Array): bigint {\n  return new DataView(lane.buffer, lane.byteOffset, lane.byteLength).getBigUint64(0, false);\n}\n\nfunction writeI64Lane(value: bigint, lane: Uint8Array): void {\n  new DataView(lane.buffer, lane.byteOffset, lane.byteLength).setBigInt64(0, value, false);\n}\n\nfunction readI64Lane(lane: Uint8Array): bigint {\n  return new DataView(lane.buffer, lane.byteOffset, lane.byteLength).getBigInt64(0, false);\n}\n\nfunction writeLane<K extends LayoutWrappedKind>(\n  kind: K,\n  value: LayoutLookupKey<K>,\n  lane: Uint8Array,\n): void {\n  if (kind === \"i32\") {\n    writeI32Lane(value as number, lane);\n    return;\n  }\n  if (kind === \"u64\") {\n    writeU64Lane(value as bigint, lane);\n    return;\n  }\n  if (kind === \"i64\") {\n    writeI64Lane(value as bigint, lane);\n    return;\n  }\n  writeU32Lane(value as number, lane);\n}\n\nfunction readLane<K extends LayoutWrappedKind>(\n  kind: K,\n  lane: Uint8Array,\n): LayoutLookupKey<K> | null {\n  if (kind === \"u64\") return readU64Lane(lane) as LayoutLookupKey<K>;\n  if (kind === \"i64\") return readI64Lane(lane) as LayoutLookupKey<K>;\n  const value = kind === \"i32\" ? readI32Lane(lane) : readU32Lane(lane);\n  return value as LayoutLookupKey<K> | null;\n}\n\n/**\n * Precomputed HMAC-message template for a fixed (brand, kind) pair.\n *\n * The message is `len32(brand) ‖ brand ‖ len32(kind) ‖ kind ‖ lane`. Everything\n * except the trailing 8-byte lane is constant for the life of the codec, so we\n * build it once at construction. `brand`/`kind` are never re-encoded and no\n * `TextEncoder` is allocated on the `wrap` / `unwrap` hot paths.\n */\ntype HmacMessageTemplate = {\n  /** Full-length buffer with the constant prefix written and the lane region zeroed. */\n  readonly buffer: Uint8Array;\n  /** Byte offset where the lane is copied in on each call. */\n  readonly laneOffset: number;\n};\n\nfunction createHmacMessageTemplate(brand: string, kind: LayoutWrappedKind): HmacMessageTemplate {\n  const encoder = new TextEncoder();\n  const brandBytes = encoder.encode(brand);\n  const kindBytes = encoder.encode(kind);\n  const laneOffset = len32ByteLength + brandBytes.length + len32ByteLength + kindBytes.length;\n  const buffer = new Uint8Array(laneOffset + laneByteLength);\n  let offset = 0;\n  writeLen32(brandBytes.length, buffer, offset);\n  offset += len32ByteLength;\n  buffer.set(brandBytes, offset);\n  offset += brandBytes.length;\n  writeLen32(kindBytes.length, buffer, offset);\n  offset += len32ByteLength;\n  buffer.set(kindBytes, offset);\n  return { buffer, laneOffset };\n}\n\n/** Materialise the HMAC message for `lane`. Fresh buffer per call → safe under concurrent async signs. */\nfunction hmacMessage(template: HmacMessageTemplate, lane: Uint8Array): Uint8Array {\n  const message = template.buffer.slice();\n  message.set(lane, template.laneOffset);\n  return message;\n}\n\nasync function computeTag(\n  key: LayoutWrappingKey,\n  template: HmacMessageTemplate,\n  lane: Uint8Array,\n): Promise<Uint8Array> {\n  return hmacSignTruncated(key.hmacKey, hmacMessage(template, lane), tagByteLength);\n}\n\nfunction buildPlaintext(lane: Uint8Array, tag: Uint8Array): Uint8Array {\n  const plaintext = new Uint8Array(payloadByteLength);\n  plaintext.set(lane, 0);\n  plaintext.set(tag, laneByteLength);\n  return plaintext;\n}\n\nasync function wrapLookupKey<Brand extends string, Kind extends LayoutWrappedKind>(\n  prefix: Prefix<Brand>,\n  template: HmacMessageTemplate,\n  key: LayoutWrappingKey,\n  kind: Kind,\n  lookupKey: LayoutLookupKey<Kind>,\n): Promise<Id<Brand>> {\n  const lane = new Uint8Array(laneByteLength);\n  writeLane(kind, lookupKey, lane);\n  const tag = await computeTag(key, template, lane);\n  const encrypted = await encryptPayload(key.aesKey, buildPlaintext(lane, tag));\n  return toWireId(prefix, encrypted);\n}\n\nasync function tryUnwrapLookupKey<Brand extends string, Kind extends LayoutWrappedKind>(\n  prefix: Prefix<Brand>,\n  template: HmacMessageTemplate,\n  key: LayoutWrappingKey,\n  kind: Kind,\n  id: Id<Brand>,\n): Promise<LayoutLookupKey<Kind> | null> {\n  const plaintext = await decryptPayload(key.aesKey, payloadBytesFromId(prefix, id));\n  const lane = plaintext.subarray(0, laneByteLength);\n  const tag = plaintext.subarray(laneByteLength, payloadByteLength);\n  const expected = await computeTag(key, template, lane);\n  if (!timingSafeEqual(tag, expected)) return null;\n  return readLane(kind, lane);\n}\n\nexport function createWrappedLayoutOps<Brand extends string, Kind extends LayoutWrappedKind>(\n  prefix: Prefix<Brand>,\n  brand: Brand,\n  kind: Kind,\n  keys: readonly LayoutWrappingKey[],\n): {\n  wrap(lookupKey: LayoutLookupKey<Kind>): Promise<Id<Brand>>;\n  tryUnwrap(id: Id<Brand>): Promise<LayoutLookupKey<Kind> | null>;\n} {\n  const wrapKey = keys[0]!;\n  // brand + kind are fixed for the codec's lifetime; encode them and build the\n  // HMAC-message prefix once instead of on every wrap / unwrap-trial.\n  const template = createHmacMessageTemplate(brand, kind);\n  return {\n    wrap: (lookupKey: LayoutLookupKey<Kind>): Promise<Id<Brand>> =>\n      wrapLookupKey(prefix, template, wrapKey, kind, lookupKey),\n    tryUnwrap: async (id: Id<Brand>): Promise<LayoutLookupKey<Kind> | null> => {\n      // Accepted timing leak: early-return on first keyring match reveals the\n      // matching key's position (rotation epoch). This is inherent to ordered-ring\n      // trial and accepted — see docs/adr/0009-wrapped-key-compact-construction.md.\n      for (const key of keys) {\n        const lookupKey = await tryUnwrapLookupKey(prefix, template, key, kind, id);\n        if (lookupKey !== null) return lookupKey;\n      }\n      return null;\n    },\n  };\n}\n","import type { webcrypto } from \"node:crypto\";\nimport { deriveKey, timingSafeEqual } from \"../_kernel/crypto.js\";\nimport {\n  assertValidKeyMaterialByteLength,\n  assertValidKeyring,\n  createKeyHandleStore,\n  decodeKeyMaterial,\n  encodeKeyMaterial,\n} from \"../_kernel/key-material.js\";\n\nexport { assertValidKeyring };\n\n/** Wire encoding for wrapping operator secret bytes (not Crockford base32). */\nexport type WrappingKeyFormat = \"hex\" | \"base64url\";\n\nconst aesInfo = new TextEncoder().encode(\"@smonn/ids/wrapped/aes\");\nconst hmacInfo = new TextEncoder().encode(\"@smonn/ids/wrapped/hmac\");\n\ndeclare const wrappingKeyBrand: unique symbol;\n\n/**\n * Opaque imported handle for one operator wrapping secret.\n *\n * Holds derived AES and HMAC subkeys internally; callers never access subkeys\n * or raw `webcrypto.CryptoKey` values directly. Obtain handles via {@link importWrappingKey}\n * and pass them to `createWrappedKeyId` as the `keys` wrapping keyring.\n *\n * Distinct from the **Opaque key** used by `@smonn/ids/opaque` — one raw\n * secret must not silently serve both codecs without an explicit import.\n */\nexport type WrappingKey = {\n  readonly [wrappingKeyBrand]: \"WrappingKey\";\n};\n\ntype WrappingKeyInternals = {\n  keyDigest: Uint8Array;\n  aesKey: webcrypto.CryptoKey;\n  hmacKey: webcrypto.CryptoKey;\n};\n\nexport type WrappingKeyMaterial = {\n  aesKey: webcrypto.CryptoKey;\n  hmacKey: webcrypto.CryptoKey;\n};\n\nconst wrappingKeyStore = createKeyHandleStore<WrappingKey, WrappingKeyInternals>(\"wrapping\");\n\n/**\n * Import raw operator secret bytes into a {@link WrappingKey} handle.\n *\n * The bytes are HKDF **input keying material**, not raw AES or HMAC keys: the\n * codec derives an **AES-256** subkey and an **HMAC-SHA-256** subkey via HKDF\n * under the labels `@smonn/ids/wrapped/aes` and `@smonn/ids/wrapped/hmac`.\n * Accepts 16, 24, or 32 bytes; the input size sets the entropy floor only — a\n * 16-byte handle still yields AES-256 and HMAC-SHA-256 subkeys with a 128-bit\n * entropy floor. To store or transport key material, use {@link encodeWrappingKey} /\n * {@link decodeWrappingKey} (`\"hex\"` or `\"base64url\"` — not Crockford base32).\n *\n * @param bytes - 16, 24, or 32 raw key bytes.\n * @throws {IdsError} `invalid_key_length` if `bytes.length` is not 16, 24, or 32.\n */\nexport async function importWrappingKey(bytes: Uint8Array): Promise<WrappingKey> {\n  assertValidKeyMaterialByteLength(bytes.length, \"wrapping\");\n  const [aesKey, hmacKey, digestBuffer] = await Promise.all([\n    deriveKey(bytes, aesInfo, { name: \"AES-CBC\", length: 256 }, [\"encrypt\", \"decrypt\"]),\n    deriveKey(bytes, hmacInfo, { name: \"HMAC\", hash: \"SHA-256\", length: 256 }, [\"sign\"]),\n    crypto.subtle.digest(\"SHA-256\", bytes as Uint8Array<ArrayBuffer>),\n  ]);\n  return wrappingKeyStore.make({\n    keyDigest: new Uint8Array(digestBuffer),\n    aesKey,\n    hmacKey,\n  });\n}\n\n/**\n * Encode raw wrapping operator secret bytes for storage in env vars or secret managers.\n *\n * Supports `\"hex\"` (lowercase) and `\"base64url\"`. Output round-trips through\n * {@link decodeWrappingKey} back to the original bytes.\n *\n * @throws {IdsError} `invalid_key_format` if `format` is not `\"hex\"` or `\"base64url\"`.\n * @throws {IdsError} `invalid_key_length` if `bytes.length` is not 16, 24, or 32.\n */\nexport function encodeWrappingKey(bytes: Uint8Array, format: WrappingKeyFormat): string {\n  return encodeKeyMaterial(bytes, format, \"wrapping\", \"wrapping\");\n}\n\n/**\n * Decode key material emitted by {@link encodeWrappingKey} back to raw bytes.\n *\n * The result can be passed directly to {@link importWrappingKey}.\n *\n * @throws {IdsError} `invalid_key_format` if `format` is not `\"hex\"` or `\"base64url\"`.\n * @throws {IdsError} `invalid_key_encoding` if the string is malformed for its format.\n * @throws {IdsError} `invalid_key_length` if the decoded bytes are not 16, 24, or 32 bytes.\n */\nexport function decodeWrappingKey(encoded: string, format: WrappingKeyFormat): Uint8Array {\n  return decodeKeyMaterial(encoded, format, \"wrapping\", \"wrapping\");\n}\n\n/**\n * Returns true when two handles were imported from the same raw operator secret.\n *\n * Uses a constant-time comparison so duplicate detection over key material does\n * not leak the position of the first differing byte through a timing side channel.\n */\nexport function wrappingKeysEqual(a: WrappingKey, b: WrappingKey): boolean {\n  return timingSafeEqual(\n    getWrappingKeyInternals(a).keyDigest,\n    getWrappingKeyInternals(b).keyDigest,\n  );\n}\n\nexport function getWrappingKeyMaterial(key: WrappingKey): WrappingKeyMaterial {\n  const keyInternals = getWrappingKeyInternals(key);\n  return {\n    aesKey: keyInternals.aesKey,\n    hmacKey: keyInternals.hmacKey,\n  };\n}\n\nfunction getWrappingKeyInternals(key: WrappingKey): WrappingKeyInternals {\n  return wrappingKeyStore.get(key);\n}\n","import { validateBrand } from \"../_kernel/brand.js\";\nimport { IdsError } from \"../../error.js\";\nimport { createWrappedLayoutOps } from \"./layout.js\";\nimport { registerBrand } from \"../_kernel/registry.js\";\nimport type {\n  Id,\n  JsonSchema,\n  ParseError,\n  ParseResult,\n  Prefix,\n  StandardSchemaProps,\n  ValidBrand,\n} from \"../../types.js\";\nimport { wireMethods } from \"../../wire/codec-shell.js\";\nimport {\n  assertValidKeyring,\n  decodeWrappingKey,\n  encodeWrappingKey,\n  getWrappingKeyMaterial,\n  importWrappingKey,\n  type WrappingKey,\n  type WrappingKeyFormat,\n  wrappingKeysEqual,\n} from \"./key.js\";\n\nexport {\n  decodeWrappingKey,\n  encodeWrappingKey,\n  importWrappingKey,\n  type WrappingKey,\n  type WrappingKeyFormat,\n};\n\n/**\n * Integer kind for a {@link WrappedKeyCodec}, fixed at construction time.\n *\n * - `\"u32\"` — unsigned 32-bit integer; JS type `number`, range `[0, 4 294 967 295]`.\n * - `\"i32\"` — signed 32-bit integer; JS type `number`, range `[-2 147 483 648, 2 147 483 647]`.\n * - `\"u64\"` — unsigned 64-bit integer; JS type `bigint`, range `[0n, 18 446 744 073 709 551 615n]`.\n * - `\"i64\"` — signed 64-bit integer; JS type `bigint`, range `[-9 223 372 036 854 775 808n, 9 223 372 036 854 775 807n]`.\n *\n * 32-bit kinds use safe JavaScript `number` values; 64-bit kinds always use `bigint`\n * even when the magnitude would fit in a `number`, preventing silent truncation or sign erasure.\n */\nexport type WrappedKind = \"u32\" | \"i32\" | \"u64\" | \"i64\";\n\ntype LookupKeyForKind<K extends WrappedKind> = K extends \"u32\" | \"i32\" ? number : bigint;\n\n/** Error vocabulary shared by {@link UnwrapResult} and {@link SafeVerifyResult}'s failure branches. */\nexport type UnwrapError = ParseError | \"verification_failed\";\n\n/**\n * Result returned by {@link WrappedKeyCodec.safeUnwrap}.\n *\n * On success, `id` is the canonical {@link Id} and `lookupKey` is the recovered\n * integer (`number` for 32-bit kinds, `bigint` for 64-bit kinds).\n * On failure, `error` is a {@link ParseError} for structural problems or\n * `\"verification_failed\"` when the payload is structurally valid but the\n * verification tag does not match any entry in the wrapping keyring.\n */\nexport type UnwrapResult<Brand extends string, Kind extends WrappedKind> =\n  | { ok: true; id: Id<Brand>; lookupKey: LookupKeyForKind<Kind> }\n  | { ok: false; error: UnwrapError };\n\n/**\n * Result returned by {@link WrappedKeyCodec.safeVerify}.\n *\n * A verify-only view of {@link UnwrapResult}: the success branch carries only the\n * canonical `id`, dropping the recovered `lookupKey`. The failure branch is\n * identical to {@link UnwrapResult}'s. This shape lets the Wrapped key codec\n * satisfy the HTTP adapters' `IdVerifiableCodec` structural interface. See ADR-0036.\n */\nexport type SafeVerifyResult<Brand extends string> =\n  | { ok: true; id: Id<Brand> }\n  | { ok: false; error: UnwrapError };\n\n/**\n * Codec returned by {@link createWrappedKeyId}.\n *\n * Wraps a caller-owned integer **lookup key** into a public {@link Id} and\n * recovers it on unwrap. The codec is deterministic under fixed key material:\n * the same lookup key always yields the same public ID (**equality leakage**).\n *\n * - `wrap` / `unwrap` / `safeUnwrap` / `safeVerify` are async (WebCrypto).\n * - `is`, `parse`, `safeParse`, and `toJsonSchema` are synchronous and require\n *   no key material — they validate prefix and base32 shape only.\n * - The `Kind` type parameter drives value types at the TypeScript boundary:\n *   `u32` / `i32` → `number`; `u64` / `i64` → `bigint`.\n *\n * @remarks\n * **Security properties (correctness-grade verification, not AEAD):**\n *\n * - The construction is deterministic — the same lookup key always yields the\n *   same public ID (**equality leakage**).\n * - The verification tag is a fixed **64-bit (8-byte) truncation** of a\n *   domain-separated HMAC over the brand, kind, and lookup key lane.\n * - False-accept rate is approximately `keyring_size / 2^64` per `unwrap`\n *   trial — correctness-grade verification, not AEAD-strength origin\n *   authentication.\n * - Consumers requiring full AEAD guarantees must use a different construction.\n */\nexport type WrappedKeyCodec<Brand extends string, Kind extends WrappedKind> = {\n  /**\n   * Wrap `lookupKey` into a public ID using the current (first) wrapping key.\n   *\n   * Throws if `lookupKey` is out of range or the wrong JS type for `Kind`.\n   */\n  wrap(lookupKey: LookupKeyForKind<Kind>): Promise<Id<Brand>>;\n  /**\n   * Verify the payload of a trusted `Id<Brand>` and return the lookup key.\n   *\n   * Throws `IdsError` with `code: \"verification_failed\"` if no entry in the\n   * wrapping keyring matches the payload tag. Use {@link safeUnwrap} for\n   * untrusted input.\n   */\n  unwrap(id: Id<Brand>): Promise<LookupKeyForKind<Kind>>;\n  /**\n   * Non-throwing path for untrusted input.\n   *\n   * Structurally parses `input` first (same rules as {@link safeParse}), then\n   * verifies the payload. Returns `{ ok: false, error }` on any failure —\n   * `ParseError` for structural problems or `\"verification_failed\"` for tag\n   * mismatch — without throwing. Tamper, wrong keyring, and revoked-key cases\n   * all surface as `\"verification_failed\"`.\n   */\n  safeUnwrap(input: unknown): Promise<UnwrapResult<Brand, Kind>>;\n  /**\n   * Verify-only alias of {@link safeUnwrap} for untrusted input.\n   *\n   * Structurally parses `input`, then verifies the payload — returning\n   * `{ ok: true, id }` on success (dropping the recovered `lookupKey`) or\n   * `{ ok: false, error }` on any failure, without throwing. Deliberately\n   * redundant with {@link safeUnwrap} (a wrapped ID cannot be verified without\n   * unwrapping it): use {@link safeUnwrap} when the lookup key is needed, and\n   * `safeVerify` to gate on authenticity alone. This is the method that lets the\n   * codec satisfy the HTTP adapters' `IdVerifiableCodec` interface under\n   * `verify: true`. See ADR-0036.\n   */\n  safeVerify(input: unknown): Promise<SafeVerifyResult<Brand>>;\n  /** Strict type guard: `true` only for already-canonical `Id<Brand>` strings. */\n  is(value: unknown): value is Id<Brand>;\n  /** Normalise to canonical form, or throw on parse failure. */\n  parse(value: unknown): Id<Brand>;\n  /** Normalise to canonical form, or return `{ ok: false, error }`. */\n  safeParse(value: unknown): ParseResult<Brand>;\n  toJsonSchema(): JsonSchema;\n  readonly \"~standard\": StandardSchemaProps<Brand>;\n  /**\n   * Converts a trusted `Id<Brand>` to an RFC 9562 canonical (lowercase, hyphenated)\n   * UUID string by reinterpreting the 16-byte payload verbatim. Total — cannot fail.\n   * Returns a plain `string` (brand is shed). See ADR-0024.\n   */\n  toUUID(id: Id<Brand>): string;\n  /**\n   * Parses a UUID string into an `Id<Brand>`. Accepts case-insensitive `8-4-4-4-12`\n   * hyphenated form only. Throws `IdsError` with `code: \"invalid_id\"` on bad input.\n   * See ADR-0024.\n   */\n  fromUUID(value: string): Id<Brand>;\n  /**\n   * Non-throwing UUID parse. Returns `{ ok: true, id }` or\n   * `{ ok: false, error: \"not_string\" | \"invalid_uuid\" }`. See ADR-0024.\n   */\n  safeFromUUID(value: unknown): ParseResult<Brand>;\n};\n\n/**\n * Construction options for {@link createWrappedKeyId}.\n */\nexport type WrappedKeyOptions<K extends WrappedKind> = {\n  /** Integer kind for the codec — fixed for the lifetime of the codec. Drives the JS value type (`number` for 32-bit, `bigint` for 64-bit). */\n  kind: K;\n  /** Non-empty ordered wrapping keyring. The first entry is current (used by `wrap`); all entries are tried on `unwrap`. Duplicate operator secrets are rejected at construction. */\n  keys: [WrappingKey, ...WrappingKey[]];\n  /** If true, silences the duplicate-brand warning in non-production environments. */\n  allowDuplicateBrand?: boolean;\n};\n\nconst u32Max = 0xffff_ffff;\nconst i32Min = -0x8000_0000;\nconst i32Max = 0x7fff_ffff;\nconst u64Max = 0xffff_ffff_ffff_ffffn;\nconst i64Min = -(1n << 63n);\nconst i64Max = (1n << 63n) - 1n;\n\nfunction assertSupportedKind(kind: WrappedKind): asserts kind is WrappedKind {\n  if (kind !== \"u32\" && kind !== \"i32\" && kind !== \"u64\" && kind !== \"i64\") {\n    throw new IdsError(\"invalid_kind\", \"invalid wrapped key kind: expected u32, i32, u64, or i64\");\n  }\n}\n\nfunction assertU32LookupKey(lookupKey: unknown): asserts lookupKey is number {\n  if (\n    typeof lookupKey !== \"number\" ||\n    !Number.isInteger(lookupKey) ||\n    Object.is(lookupKey, -0) ||\n    lookupKey < 0 ||\n    lookupKey > u32Max\n  ) {\n    throw new IdsError(\n      \"invalid_lookup_key\",\n      `invalid u32 lookup key: expected integer in [0, ${u32Max}], got ${lookupKey}`,\n    );\n  }\n}\n\nfunction assertI32LookupKey(lookupKey: unknown): asserts lookupKey is number {\n  if (\n    typeof lookupKey !== \"number\" ||\n    !Number.isInteger(lookupKey) ||\n    Object.is(lookupKey, -0) ||\n    lookupKey < i32Min ||\n    lookupKey > i32Max\n  ) {\n    throw new IdsError(\n      \"invalid_lookup_key\",\n      `invalid i32 lookup key: expected integer in [${i32Min}, ${i32Max}], got ${lookupKey}`,\n    );\n  }\n}\n\nfunction assertU64LookupKey(lookupKey: unknown): asserts lookupKey is bigint {\n  if (typeof lookupKey !== \"bigint\" || lookupKey < 0n || lookupKey > u64Max) {\n    throw new IdsError(\n      \"invalid_lookup_key\",\n      `invalid u64 lookup key: expected bigint in [0, ${u64Max}], got ${lookupKey}`,\n    );\n  }\n}\n\nfunction assertI64LookupKey(lookupKey: unknown): asserts lookupKey is bigint {\n  if (typeof lookupKey !== \"bigint\" || lookupKey < i64Min || lookupKey > i64Max) {\n    throw new IdsError(\n      \"invalid_lookup_key\",\n      `invalid i64 lookup key: expected bigint in [${i64Min}, ${i64Max}], got ${lookupKey}`,\n    );\n  }\n}\n\nfunction assertLookupKey<Kind extends WrappedKind>(\n  kind: Kind,\n  lookupKey: unknown,\n): asserts lookupKey is LookupKeyForKind<Kind> {\n  if (kind === \"i32\") {\n    assertI32LookupKey(lookupKey);\n    return;\n  }\n  if (kind === \"u64\") {\n    assertU64LookupKey(lookupKey);\n    return;\n  }\n  if (kind === \"i64\") {\n    assertI64LookupKey(lookupKey);\n    return;\n  }\n  assertU32LookupKey(lookupKey);\n}\n\n/**\n * Construct a {@link WrappedKeyCodec} for `brand` and the given `kind`.\n *\n * `opts.kind` fixes the integer type at construction time — one brand, one\n * kind. `opts.keys` is a non-empty ordered wrapping keyring: the first entry\n * is current (used by `wrap`); all entries are tried on `unwrap`; duplicate\n * operator secrets are rejected at construction.\n *\n * @example\n * ```ts\n * const key = await importWrappingKey(new Uint8Array(32));\n * const invoices = createWrappedKeyId(\"inv\", { kind: \"u32\", keys: [key] });\n *\n * const id = await invoices.wrap(42);      // Id<\"inv\">\n * await invoices.unwrap(id);               // 42\n * ```\n */\nexport function createWrappedKeyId<Brand extends string, Kind extends WrappedKind>(\n  brand: Brand & ValidBrand<Brand>,\n  opts: WrappedKeyOptions<Kind>,\n): WrappedKeyCodec<Brand, Kind> {\n  validateBrand(brand);\n  registerBrand(brand, opts.allowDuplicateBrand);\n  assertSupportedKind(opts.kind);\n  assertValidKeyring(opts.keys, wrappingKeysEqual, \"wrapping\");\n  const layoutKeys = opts.keys.map(getWrappingKeyMaterial);\n\n  const prefix: Prefix<Brand> = `${brand}_`;\n  const wire = wireMethods(prefix);\n  const layout = createWrappedLayoutOps(prefix, brand, opts.kind, layoutKeys);\n\n  const safeUnwrap = async (input: unknown): Promise<UnwrapResult<Brand, Kind>> => {\n    const parsed = wire.safeParse(input);\n    if (!parsed.ok) return parsed;\n    const lookupKey = await layout.tryUnwrap(parsed.id);\n    if (lookupKey === null) return { ok: false, error: \"verification_failed\" };\n    return { ok: true, id: parsed.id, lookupKey };\n  };\n\n  return {\n    wrap: async (lookupKey) => {\n      assertLookupKey(opts.kind, lookupKey);\n      return layout.wrap(lookupKey);\n    },\n    unwrap: async (id) => {\n      const lookupKey = await layout.tryUnwrap(id);\n      if (lookupKey === null) {\n        throw new IdsError(\"verification_failed\", \"verification failed\");\n      }\n      return lookupKey;\n    },\n    safeUnwrap,\n    // Verify-only alias: delegates to safeUnwrap and drops the recovered lookupKey\n    // so the codec satisfies IdVerifiableCodec. Single source of truth — see ADR-0036.\n    safeVerify: async (input) => {\n      const result = await safeUnwrap(input);\n      return result.ok ? { ok: true, id: result.id } : result;\n    },\n    is: wire.is,\n    parse: wire.parse,\n    safeParse: wire.safeParse,\n    toJsonSchema: wire.toJsonSchema,\n    \"~standard\": wire[\"~standard\"],\n    toUUID: wire.toUUID,\n    fromUUID: wire.fromUUID,\n    safeFromUUID: wire.safeFromUUID,\n  };\n}\n"],"mappings":";;;;AAYA,MAAM,iBAAiB;AACvB,MAAM,gBAAgB;;AAStB,MAAM,qBAAqB,iBAAiB;AAU5C,SAAS,aAAa,OAAe,MAAwB;CAC3D,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAK;CACV,KAAK,KAAM,UAAU,KAAM;CAC3B,KAAK,KAAM,UAAU,KAAM;CAC3B,KAAK,KAAM,UAAU,IAAK;CAC1B,KAAK,KAAK,QAAQ;AACpB;AAEA,SAAS,YAAY,MAAiC;CACpD,KAAK,IAAI,IAAI,GAAG,IAAI,oBAAoB,KACtC,IAAI,KAAK,OAAO,GAAG,OAAO;CAE5B,QAAS,KAAK,MAAO,KAAO,KAAK,MAAO,KAAO,KAAK,MAAO,IAAK,KAAK,QAAS;AAChF;AAEA,SAAS,aAAa,OAAe,MAAwB;CAC3D,KAAK,KAAK,QAAQ,IAAI,MAAO,GAAM,GAAG,kBAAkB;CACxD,IAAI,SAAS,KAAK,QAAQ,KAAK,YAAY,KAAK,UAAU,CAAC,CAAC,SAAS,GAAG,OAAO,KAAK;AACtF;AAEA,SA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