{"version":3,"file":"opaque-BGUeOejE.mjs","names":[],"sources":["../src/codecs/opaque/layout.ts","../src/codecs/opaque/key.ts","../src/codecs/opaque/index.ts"],"sourcesContent":["import type { webcrypto } from \"node:crypto\";\nimport type { Id, Prefix } from \"../../types.js\";\nimport { decryptPayload, encryptPayload } from \"../_kernel/crypto.js\";\nimport { payloadBytesFromId, toWireId } from \"../../wire/envelope.js\";\nimport { payloadByteLength } from \"../../wire/invariants.js\";\nimport {\n  readTimestampMs,\n  timestampByteLength,\n  writeTimestamp,\n} from \"../../wire/timestamp-bytes.js\";\n\nfunction buildPlaintext(ms: number, rng: (target: Uint8Array) => void): Uint8Array {\n  const plaintext = new Uint8Array(payloadByteLength);\n  writeTimestamp(ms, plaintext);\n  rng(plaintext.subarray(timestampByteLength, payloadByteLength));\n  return plaintext;\n}\n\nasync function extractTimestampFromId<Brand extends string>(\n  prefix: Prefix<Brand>,\n  key: webcrypto.CryptoKey,\n  id: Id<Brand>,\n): Promise<Date> {\n  const plaintext = await decryptPayload(key, payloadBytesFromId(prefix, id));\n  return new Date(readTimestampMs(plaintext));\n}\n\n/** Produces a canonical encrypted wire ID. Per-call plaintext/ciphertext buffers —\n * subtle dominates this path; reuse would be safe but not worth pinning to spec detail. */\nasync function generateWireId<Brand extends string>(\n  prefix: Prefix<Brand>,\n  key: webcrypto.CryptoKey,\n  rng: (target: Uint8Array) => void,\n  ms: number,\n): Promise<Id<Brand>> {\n  const plaintext = buildPlaintext(ms, rng);\n  const encrypted = await encryptPayload(key, plaintext);\n  return toWireId(prefix, encrypted);\n}\n\n/** Layout ops binder for the Opaque Timestamp variant. `extractTimestampFromId` is module-private; the binder exposes `extractTimestamp` for the codec constructor. */\nexport function createOpaqueLayoutOps<Brand extends string>(\n  prefix: Prefix<Brand>,\n  key: webcrypto.CryptoKey,\n  rng: (target: Uint8Array) => void,\n): {\n  generateAt(ms: number): Promise<Id<Brand>>;\n  extractTimestamp(id: Id<Brand>): Promise<Date>;\n} {\n  return {\n    generateAt: (ms: number): Promise<Id<Brand>> => generateWireId(prefix, key, rng, ms),\n    extractTimestamp: (id: Id<Brand>): Promise<Date> => extractTimestampFromId(prefix, key, id),\n  };\n}\n","import type { webcrypto } from \"node:crypto\";\nimport { deriveKey } from \"../_kernel/crypto.js\";\nimport {\n  assertValidKeyMaterialByteLength,\n  createKeyHandleStore,\n  decodeKeyMaterial,\n  encodeKeyMaterial,\n} from \"../_kernel/key-material.js\";\n\n/** Wire encoding for opaque AES key material (not Crockford base32). */\nexport type OpaqueKeyFormat = \"hex\" | \"base64url\";\n\n// HKDF domain-separation label for the Opaque AES key; see ADR-0019 / ADR-0027.\nconst aesInfo = new TextEncoder().encode(\"@smonn/ids/opaque/aes\");\n\ndeclare const opaqueKeyBrand: unique symbol;\n\n/**\n * Opaque imported handle for the Opaque Timestamp codec's AES-256 key.\n *\n * Holds the underlying `webcrypto.CryptoKey` internally; callers never access it directly.\n * Obtain handles via {@link importOpaqueKey} and pass them to\n * `createOpaqueTimestampId` as the `key` option.\n *\n * The same raw secret may safely back an `OpaqueKey` and any other codec's\n * handle (a **primary secret**): each codec derives its key under a distinct\n * HKDF label, so the derived keys are independent — but each codec needs its\n * own explicit import. See ADR-0027.\n */\nexport type OpaqueKey = {\n  readonly [opaqueKeyBrand]: \"OpaqueKey\";\n};\n\nconst opaqueKeyStore = createKeyHandleStore<OpaqueKey, webcrypto.CryptoKey>(\"opaque\");\n\n/**\n * Imports operator key material into an {@link OpaqueKey} handle for the Opaque\n * Timestamp codec.\n *\n * The bytes are HKDF **input keying material**, not the AES key itself: the\n * codec derives an **AES-256** key from them via HKDF under the label\n * `@smonn/ids/opaque/aes` (ADR-0027). Accepts 16, 24, or 32 bytes; the input\n * size sets the entropy floor only — a 16-byte handle still yields AES-256 with\n * a 128-bit entropy floor. To store or transport key material, use\n * {@link encodeOpaqueKey} / {@link decodeOpaqueKey} (`\"hex\"` or `\"base64url\"` —\n * not Crockford base32).\n *\n * @param bytes - 16, 24, or 32 bytes of raw key material.\n * @throws {IdsError} `invalid_key_length` if `bytes.length` is not 16, 24, or 32.\n */\nexport async function importOpaqueKey(bytes: Uint8Array): Promise<OpaqueKey> {\n  assertValidKeyMaterialByteLength(bytes.length, \"AES\");\n  const cryptoKey = await deriveKey(bytes, aesInfo, { name: \"AES-CBC\", length: 256 }, [\n    \"encrypt\",\n    \"decrypt\",\n  ]);\n  return opaqueKeyStore.make(cryptoKey);\n}\n\n// Deliberate: name getOpaqueKeyCryptoKey diverges from sibling accessors (…HmacKey/…Material) — internal only; accepted as not-a-defect. See CONTEXT.md postures.\nexport function getOpaqueKeyCryptoKey(key: OpaqueKey): webcrypto.CryptoKey {\n  return opaqueKeyStore.get(key);\n}\n\n/**\n * Encodes raw Opaque key material bytes for storage in env vars or secret managers.\n *\n * @param bytes - 16, 24, or 32 raw Opaque key material bytes.\n * @param format - `hex` (lowercase) or `base64url`.\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 encodeOpaqueKey(bytes: Uint8Array, format: OpaqueKeyFormat): string {\n  return encodeKeyMaterial(bytes, format, \"opaque\", \"AES\");\n}\n\n/**\n * Decodes key material emitted by `encodeOpaqueKey` (or `ids keygen`) back to raw bytes.\n *\n * @param encoded - Hex or base64url string.\n * @param format - Must match how the string was encoded.\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 decodeOpaqueKey(encoded: string, format: OpaqueKeyFormat): Uint8Array {\n  return decodeKeyMaterial(encoded, format, \"opaque\", \"AES\");\n}\n","import { validateBrand } from \"../_kernel/brand.js\";\nimport { createOpaqueLayoutOps } from \"./layout.js\";\nimport { getOpaqueKeyCryptoKey, type OpaqueKey } from \"./key.js\";\nimport { registerBrand } from \"../_kernel/registry.js\";\nimport { defaultRng } from \"../_kernel/rng.js\";\nimport type {\n  Id,\n  JsonSchema,\n  ParseResult,\n  Prefix,\n  StandardSchemaProps,\n  ValidBrand,\n} from \"../../types.js\";\nimport { wireMethods } from \"../../wire/codec-shell.js\";\n\nexport {\n  decodeOpaqueKey,\n  encodeOpaqueKey,\n  importOpaqueKey,\n  type OpaqueKey,\n  type OpaqueKeyFormat,\n} from \"./key.js\";\n\n/**\n * Configuration options for an Opaque Timestamp codec instance.\n */\nexport type OpaqueTimestampOptions = {\n  /**\n   * {@link OpaqueKey} handle for AES-CBC encryption and decryption.\n   * Obtain via {@link importOpaqueKey}.\n   *\n   * A single key, not a ring: rotation is forward-only and caller-tracked —\n   * hold one codec per key epoch and select it from your own records. The\n   * library cannot trial keys (the payload is unauthenticated). See ADR-0013.\n   */\n  key: OpaqueKey;\n  /** Returns the current timestamp in milliseconds. Defaults to `Date.now`. */\n  now?: () => number;\n  /** Writes random bytes into `target` for ID generation. Defaults to `crypto.getRandomValues`. */\n  rng?: (target: Uint8Array) => void;\n  /** If true, silences the duplicate-brand warning in non-production environments. */\n  allowDuplicateBrand?: boolean;\n};\n\ntype ResolvedOpaqueTimestampOptions = Required<Pick<OpaqueTimestampOptions, \"now\" | \"rng\">> &\n  Pick<OpaqueTimestampOptions, \"allowDuplicateBrand\">;\n\n/**\n * A brand-scoped codec for generating and validating Opaque Timestamp IDs.\n *\n * Same wire shape as the Timestamp codec (`{brand}_` + 26 base32 chars) but the\n * payload is AES-CBC encrypted. `generate`, `generateAt`, and `extractTimestamp`\n * are async; parsing methods are sync. No `minIdForTime` / `maxIdForTime` —\n * encrypted payloads do not sort by creation time.\n *\n * @remarks\n * **Security properties (unauthenticated, deterministic, and malleable by design):**\n *\n * - The payload is AES-CBC encrypted but **unauthenticated** — there is no\n *   integrity tag. A tampered or wrong-key payload decrypts to garbage bytes\n *   without throwing.\n * - Opaque IDs must be treated as **opaque handles**, not as trusted or\n *   authenticated tokens.\n * - `extractTimestamp` is best-effort on untrusted input: a wrong or tampered\n *   key returns a plausible-looking `Date` without error, not a verification\n *   failure. Do not treat the returned timestamp as proof of origin.\n */\nexport type OpaqueTimestampCodec<Brand extends string> = {\n  /** Produces a new canonical encrypted ID using the codec's `now` and `rng`. */\n  generate(): Promise<Id<Brand>>;\n  /** Produces a new canonical encrypted ID with timestamp bytes from `date`. Throws on invalid dates. */\n  generateAt(date: Date): Promise<Id<Brand>>;\n  /**\n   * Strict type guard: `true` only for already-canonical strings for this brand.\n   * For untrusted input, use `safeParse()` or `parse()` instead. See ADR-0003.\n   */\n  is(value: unknown): value is Id<Brand>;\n  /**\n   * Lenient parse: normalises case and Crockford aliases, returns canonical `Id<Brand>`, or throws.\n   */\n  parse(value: unknown): Id<Brand>;\n  /**\n   * Lenient parse without throwing: normalises to canonical form, or returns `{ ok: false, error }`.\n   */\n  safeParse(value: unknown): ParseResult<Brand>;\n  /**\n   * Decrypts and decodes the creation `Date` from an `Id<Brand>`. Trusts the type — use `safeParse()` at boundaries first. See ADR-0002.\n   *\n   * Requires the same key used at generation; a wrong key returns a plausible\n   * but wrong `Date`, never an error. With rotation, select the codec for the\n   * ID's key epoch from your own records — the library cannot. See ADR-0013.\n   */\n  extractTimestamp(id: Id<Brand>): Promise<Date>;\n  /**\n   * JSON Schema for the canonical wire form. The `pattern` matches the canonical stored\n   * form only and is deliberately stricter than `parse()`/`safeParse()`, which accept\n   * uppercase letters and Crockford aliases (`o`/`i`/`l`) before normalising. See ADR-0003.\n   * The `example` is a structural placeholder (generated at construction time).\n   */\n  toJsonSchema(): JsonSchema;\n  /** Standard Schema validate entry point. */\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. The payload is the\n   * encrypted ciphertext — `toUUID` does not decrypt it. 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\nconst defaultOpaqueTimestampOptions: ResolvedOpaqueTimestampOptions = {\n  now: Date.now,\n  rng: defaultRng,\n};\n\n/**\n * Creates an Opaque Timestamp codec for `brand` (three lowercase a–z characters).\n *\n * @param brand - Entity type brand validated once at construction.\n * @param opts - Required `key` (an {@link OpaqueKey} from {@link importOpaqueKey}) plus\n *   optional `now`, `rng`, and `allowDuplicateBrand` overrides.\n */\nexport function createOpaqueTimestampId<Brand extends string>(\n  brand: Brand & ValidBrand<Brand>,\n  opts: OpaqueTimestampOptions,\n): OpaqueTimestampCodec<Brand> {\n  validateBrand(brand);\n  registerBrand(brand, opts.allowDuplicateBrand);\n\n  const cryptoKey = getOpaqueKeyCryptoKey(opts.key);\n  const options = {\n    now: opts.now ?? defaultOpaqueTimestampOptions.now,\n    rng: opts.rng ?? defaultOpaqueTimestampOptions.rng,\n  } satisfies ResolvedOpaqueTimestampOptions;\n  const prefix: Prefix<Brand> = `${brand}_`;\n  const wire = wireMethods(prefix);\n  const layout = createOpaqueLayoutOps(prefix, cryptoKey, options.rng);\n\n  return {\n    generate: () => layout.generateAt(options.now()),\n    generateAt: (date: Date) => layout.generateAt(date.getTime()),\n    is: wire.is,\n    parse: wire.parse,\n    safeParse: wire.safeParse,\n    extractTimestamp: layout.extractTimestamp,\n    toJsonSchema: wire.toJsonSchema,\n    \"~standard\": wire[\"~standard\"],\n    toUUID: wire.toUUID,\n    fromUUID: wire.fromUUID,\n    safeFromUUID: wire.safeFromUUID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