{"version":3,"file":"digest-yInMrzcL.mjs","names":[],"sources":["../src/codecs/digest/layout.ts","../src/codecs/digest/key.ts","../src/codecs/digest/index.ts"],"sourcesContent":["import type { webcrypto } from \"node:crypto\";\nimport type { Id, Prefix } from \"../../types.js\";\nimport { hmacSignTruncated } from \"../_kernel/crypto.js\";\nimport { len32ByteLength, writeLen32 } from \"../_kernel/bytes.js\";\nimport { toWireId } from \"../../wire/envelope.js\";\nimport { payloadByteLength } from \"../../wire/invariants.js\";\n\nconst encoder = new TextEncoder();\n\n/**\n * Precomputed HMAC-message template for a fixed (brand, ns) pair.\n *\n * The message is `len32(brand) ‖ brand ‖ len32(ns) ‖ ns ‖ material`. Everything\n * except the trailing variable-length material is constant for the life of the\n * codec, so we build the prefix once at construction. `brand`/`ns` are never\n * re-encoded and no `writeLen32` call occurs on the `digest()` hot path.\n */\ntype DigestMessageTemplate = {\n  /** Constant prefix buffer: `len32(brand) ‖ brand ‖ len32(ns) ‖ ns`. */\n  readonly prefix: Uint8Array;\n};\n\nfunction createDigestMessageTemplate(brand: string, ns: string): DigestMessageTemplate {\n  const brandBytes = encoder.encode(brand);\n  const nsBytes = encoder.encode(ns);\n  const prefixLen = len32ByteLength + brandBytes.length + len32ByteLength + nsBytes.length;\n  const prefix = new Uint8Array(prefixLen);\n  let offset = 0;\n  writeLen32(brandBytes.length, prefix, offset);\n  offset += len32ByteLength;\n  prefix.set(brandBytes, offset);\n  offset += brandBytes.length;\n  writeLen32(nsBytes.length, prefix, offset);\n  offset += len32ByteLength;\n  prefix.set(nsBytes, offset);\n  return { prefix };\n}\n\n/** Materialise the HMAC message for `material`. Fresh buffer per call → safe under concurrent async signs. */\nfunction digestMessage(template: DigestMessageTemplate, material: Uint8Array): Uint8Array {\n  const message = new Uint8Array(template.prefix.length + material.length);\n  message.set(template.prefix, 0);\n  message.set(material, template.prefix.length);\n  return message;\n}\n\nexport function createDigestLayoutOps<Brand extends string>(\n  prefix: Prefix<Brand>,\n  brand: Brand,\n  ns: string,\n  hmacKey: webcrypto.CryptoKey,\n): {\n  digest(material: string | Uint8Array): Promise<Id<Brand>>;\n} {\n  const template = createDigestMessageTemplate(brand, ns);\n\n  return {\n    digest: async (material: string | Uint8Array): Promise<Id<Brand>> => {\n      const materialBytes = typeof material === \"string\" ? encoder.encode(material) : material;\n      const message = digestMessage(template, materialBytes);\n      const payload = await hmacSignTruncated(hmacKey, message, payloadByteLength);\n      return toWireId(prefix, payload);\n    },\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 digest operator key material (not Crockford base32). */\nexport type DigestKeyFormat = \"hex\" | \"base64url\";\n\nconst hmacInfo = new TextEncoder().encode(\"@smonn/ids/digest/hmac\");\n\ndeclare const digestKeyBrand: unique symbol;\n\n/**\n * Opaque imported handle for one operator Digest key.\n *\n * Holds a single HMAC-SHA-256 key derived via HKDF under the domain-separation\n * label `@smonn/ids/digest/hmac`. The underlying `webcrypto.CryptoKey` is held internally and\n * never exposed to callers. Obtain handles via {@link importDigestKey} and pass\n * them to `createDigestId` as the `key` option.\n *\n * Unlike the other keyed codecs, the Digest codec holds exactly one key — there\n * is no keyring. Re-keying is a deliberate, breaking operator action (every ID\n * changes), never an in-band rotation.\n *\n * Distinct from the **Opaque key**, **Wrapping key**, and **Signing key** — the\n * same raw bytes imported as a `DigestKey` are cryptographically independent of\n * any other codec's key.\n */\nexport type DigestKey = {\n  readonly [digestKeyBrand]: \"DigestKey\";\n};\n\ntype DigestKeyInternals = {\n  hmacKey: webcrypto.CryptoKey;\n};\n\nconst digestKeyStore = createKeyHandleStore<DigestKey, DigestKeyInternals>(\"digest\");\n\n/**\n * Import raw operator key material into a {@link DigestKey} handle.\n *\n * Derives a single HMAC-SHA-256 key via HKDF under the domain-separation label\n * `@smonn/ids/digest/hmac`. Accepts 16, 24, or 32 bytes. To store or transport key\n * material, use {@link encodeDigestKey} / {@link decodeDigestKey}\n * (`\"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 importDigestKey(bytes: Uint8Array): Promise<DigestKey> {\n  assertValidKeyMaterialByteLength(bytes.length, \"digest\");\n  const hmacKey = await deriveKey(bytes, hmacInfo, { name: \"HMAC\", hash: \"SHA-256\", length: 256 }, [\n    \"sign\",\n  ]);\n  return digestKeyStore.make({ hmacKey });\n}\n\n/**\n * Encode raw digest operator key material for storage in env vars or secret managers.\n *\n * Supports `\"hex\"` (lowercase) and `\"base64url\"`. Output round-trips through\n * {@link decodeDigestKey} 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 encodeDigestKey(bytes: Uint8Array, format: DigestKeyFormat): string {\n  return encodeKeyMaterial(bytes, format, \"digest\", \"digest\");\n}\n\n/**\n * Decode key material emitted by {@link encodeDigestKey} back to raw bytes.\n *\n * The result can be passed directly to {@link importDigestKey}.\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 decodeDigestKey(encoded: string, format: DigestKeyFormat): Uint8Array {\n  return decodeKeyMaterial(encoded, format, \"digest\", \"digest\");\n}\n\n/**\n * Returns the derived HMAC webcrypto.CryptoKey held inside the handle.\n *\n * Intentional module-internal escape hatch for codec implementations.\n * Not re-exported from `@smonn/ids/digest`; external callers cannot reach this.\n */\nexport function getDigestKeyHmacKey(key: DigestKey): webcrypto.CryptoKey {\n  return digestKeyStore.get(key).hmacKey;\n}\n","import { validateBrand } from \"../_kernel/brand.js\";\nimport { IdsError } from \"../../error.js\";\nimport { createDigestLayoutOps } from \"./layout.js\";\nimport { registerBrand } from \"../_kernel/registry.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\";\nimport {\n  decodeDigestKey,\n  encodeDigestKey,\n  getDigestKeyHmacKey,\n  importDigestKey,\n  type DigestKey,\n  type DigestKeyFormat,\n} from \"./key.js\";\n\nexport { decodeDigestKey, encodeDigestKey, importDigestKey, type DigestKey, type DigestKeyFormat };\n\n/**\n * Configuration options for a Digest codec instance.\n */\nexport type DigestOptions = {\n  /**\n   * Non-secret, required namespace. The same material under a different\n   * `ns` yields a different ID, so one key can serve multiple unlinkable namespaces.\n   * Must be non-empty and not whitespace-only.\n   */\n  ns: string;\n  /**\n   * Single operator digest key. The Digest codec holds exactly one key — there\n   * is no keyring. Re-keying is a deliberate, breaking operator action.\n   */\n  key: DigestKey;\n  /** If true, silences the duplicate-brand warning in non-production environments. */\n  allowDuplicateBrand?: boolean;\n};\n\n/**\n * Codec returned by {@link createDigestId}.\n *\n * Maps caller **material** to a stable public ID under one **Digest key**:\n * the same material always yields the same ID, and the material cannot be\n * recovered from the ID (**equality leakage** is the intended property).\n *\n * - `digest` is async (WebCrypto HMAC).\n * - `is`, `parse`, `safeParse`, `toJsonSchema`, and `~standard` are synchronous\n *   and require no key material — they validate prefix and base32 shape only.\n * - There is no reverse method (`unwrap`, `verify`, `extractTimestamp`) — the\n *   codec is one-way by definition.\n */\nexport type DigestCodec<Brand extends string> = {\n  /**\n   * Digest `material` into a stable canonical {@link Id}.\n   *\n   * The same `(brand, ns, key, material)` tuple always returns the same ID.\n   * Strings are UTF-8 encoded; byte arrays are used as-is.\n   */\n  digest(material: string | Uint8Array): Promise<Id<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  /** JSON Schema for the canonical wire form (`pattern` is canonical-only). */\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. 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 * Construct a {@link DigestCodec} for `brand`.\n *\n * `opts.ns` is the required namespace — the same material under a\n * different `ns` yields a different ID. `opts.key` is the single operator\n * Digest key; there is no keyring.\n *\n * @example\n * ```ts\n * const key = await importDigestKey(new Uint8Array(32));\n * const idk = createDigestId(\"idk\", { ns: \"checkout\", key });\n *\n * const id = await idk.digest(\"order-123\"); // Id<\"idk\">\n * idk.is(id);                               // true\n * ```\n */\nexport function createDigestId<Brand extends string>(\n  brand: Brand & ValidBrand<Brand>,\n  opts: DigestOptions,\n): DigestCodec<Brand> {\n  validateBrand(brand);\n  registerBrand(brand, opts.allowDuplicateBrand);\n\n  if (typeof opts.ns !== \"string\" || opts.ns.trim() === \"\") {\n    throw new IdsError(\n      \"invalid_namespace\",\n      \"invalid namespace: ns must be a non-empty, non-whitespace string\",\n    );\n  }\n\n  const hmacKey = getDigestKeyHmacKey(opts.key);\n  const prefix: Prefix<Brand> = `${brand}_`;\n  const wire = wireMethods(prefix);\n  const layout = createDigestLayoutOps(prefix, brand, opts.ns, hmacKey);\n\n  return {\n    digest: layout.digest,\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":";;;;AAOA,MAAM,UAAU,IAAI,YAAY;AAehC,SAAS,4BAA4B,OAAe,IAAmC;CACrF,MAAM,aAAa,QAAQ,OAAO,KAAK;CACvC,MAAM,UAAU,QAAQ,OAAO,EAAE;CACjC,MAAM,YAAA,IAA8B,WAAW,SAAA,IAA2B,QAAQ;CAClF,MAAM,SAAS,IAAI,WAAW,SAAS;CACvC,IAAI,SAAS;CACb,WAAW,WAAW,QAAQ,QAAQ,MAAM;CAC5C,UAAA;CACA,OAAO,IAAI,YAAY,MAAM;CAC7B,UAAU,WAAW;CACrB,WAAW,QAAQ,QAAQ,QAAQ,MAAM;CACzC,UAAA;CACA,OAAO,IAAI,SAAS,MAAM;CAC1B,OAAO,EAAE,OAAO;AAClB;;AAGA,SAAS,cAAc,UAAiC,UAAkC;CACxF,MAAM,UAAU,IAAI,WAAW,SAAS,OAAO,SAAS,SAAS,MAAM;CACvE,QAAQ,IAAI,SAAS,QAAQ,CAAC;CAC9B,QAAQ,IAAI,UAAU,SAAS,OAAO,MAAM;CAC5C,OAAO;AACT;AAEA,SAAgB,sBACd,QACA,OACA,IACA,SAGA;CACA,MAAM,WAAW,4BAA4B,OAAO,EAAE;CAEtD,OAAO,EACL,QAAQ,OAAO,aAAsD;EAInE,OAAO,SAAS,QAAQ,MADF,kBAAkB,SADxB,cAAc,UADR,OAAO,aAAa,WAAW,QAAQ,OAAO,QAAQ,IAAI,QAEzB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