{"version":3,"sources":["../src/types/bundle.ts","../src/errors/index.ts","../src/crypto/jcs.ts","../src/crypto/hash.ts","../src/crypto/manifest.ts","../src/crypto/merkle.ts","../src/client/sse.ts","../src/client/index.ts","../src/verify/unzip.ts","../src/verify/index.ts","../src/index.ts"],"names":["sha256","createHash","h"],"mappings":";;;AA2HO,SAAS,gBAAgB,CAAA,EAAoC;AAClE,EAAA,OAAQ,EAAoB,IAAA,KAAS,MAAA;AACvC;AAiBO,IAAM,YAAA,GAAe;AAAA,EAC1B,QAAA,EAAU,cAAA;AAAA,EACV,QAAA,EAAU,eAAA;AAAA,EACV,aAAA,EAAe,eAAA;AAAA,EACf,UAAA,EAAY,YAAA;AAAA,EACZ,MAAA,EAAQ,aAAA;AAAA,EACR,UAAA,EAAY,YAAA;AAAA,EACZ,MAAA,EAAQ,aAAA;AAAA,EACR,OAAA,EAAS,cAAA;AAAA,EACT,SAAA,EAAW,eAAA;AAAA,EACX,GAAA,EAAK,UAAA;AAAA,EACL,aAAA,EAAe,WAAA;AAAA,EACf,kBAAA,EAAoB,aAAA;AAAA,EACpB,WAAA,EAAa,yBAAA;AAAA,EACb,cAAA,EAAgB,4BAAA;AAAA,EAChB,UAAA,EAAY,wBAAA;AAAA,EACZ,aAAA,EAAe;AACjB;AAEO,IAAM,aAAA,GAAgB;;;ACnItB,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACzB,IAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EACS,KAAA;AAAA,EAEzB,WAAA,CAAY,OAAA,EAAiB,GAAA,GAA8B,EAAC,EAAG;AAC7D,IAAA,KAAA,CAAM,OAAA,EAAS,IAAI,KAAA,KAAU,MAAA,GAAY,SAAY,EAAE,KAAA,EAAO,GAAA,CAAI,KAAA,EAAO,CAAA;AACzE,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAI,GAAA,CAAI,IAAA,KAAS,MAAA,EAAW,IAAA,CAAK,OAAO,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E,CAAA;AAAA,EACzD;AACA,EAAA,OAAO,CAAA;AACT;AAEA,SAAS,cAAc,CAAA,EAAuB;AAC5C,EAAA,OAAO,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,CAAE,SAAS,OAAO,CAAA;AACxC;AAEA,SAAS,SAAA,CAAa,GAAe,KAAA,EAAkB;AACrD,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,KAAA,CAAM,aAAA,CAAc,CAAC,CAAC,CAAA;AAAA,EACpC,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAI,MAAM,CAAA,EAAG,KAAK,mBAAmB,QAAA,CAAS,GAAG,CAAC,CAAA,CAAE,CAAA;AAAA,EAC5D;AACF;AAEA,SAAS,SAAS,GAAA,EAAsB;AACtC,EAAA,OAAO,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AACxD;AAEA,SAAS,IAAA,CACP,MAAA,EACA,OAAA,EACA,QAAA,EACA,MAAA,EACc;AACd,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,KAAA;AAAA,IACJ,MAAA;AAAA,IACA,OAAA;AAAA,IACA,MAAA,EAAQ,CAAA,EAAG,QAAQ,CAAA,EAAA,EAAK,MAAM,CAAA;AAAA,GAChC;AACF;;;AC9WO,IAAM,WAAA,GAAc","file":"index.mjs","sourcesContent":["/**\n * `.dpiv-bundle` JSON shapes.\n *\n * Mirrors `shared-deps/chain/bundle/bundle-types.ts`. Any drift\n * between this file and ARCHITECTURE.md §8 is a bug — the\n * architecture doc wins.\n *\n * The files documented here are the JSON payloads inside a bundle:\n *   - `merkle.json`   — `MerkleProofJson`\n *   - `sth.json`      — `STH` (re-exported from `./sth`)\n *   - `onchain.json`  — `OnchainProofJson`   (optional)\n *   - `labels.json`   — `LabelsJson`\n *   - `MANIFEST.txt`  — `ManifestEntry[]` (see `../crypto/manifest`)\n */\n\n/**\n * `merkle.json` — the inclusion proof for one leaf in one segment.\n *\n * Verifiers walk `audit_path` bottom-up using RFC 6962 domain\n * separation (`0x00 || leaf` for leaf hashes, `0x01 || left || right`\n * for nodes). The walk MUST close to the `root` field of the\n * bundle's `sth.json` for the segment — verifiers cross-check the\n * two files, not just `merkle.json` in isolation.\n *\n * `leaf_hash` is the RFC 6962 leaf hash:\n * `SHA-256(0x00 || envelope_canonical_bytes)`. It is NOT\n * `envelope_hash` (which omits the `0x00` prefix). A naive verifier\n * that checks `leaf_hash === envelope_hash` is wrong — they differ\n * by the prefix-and-rehash step.\n *\n * Hex fields are lowercase, no `0x` prefix. `audit_path` is ordered\n * leaf-to-root and its length equals `ceil(log2(tree_size))` for the\n * segment's tree at the STH used.\n */\nexport interface MerkleProofJson {\n  v: 1;\n  segment: number;\n  leaf_index: number;\n  leaf_hash: string;\n  audit_path: string[];\n}\n\n/**\n * `onchain.json` — optional. Present only when the segment has a\n * confirmed `anchor_checkpoint` row whose `tree_size` covers\n * `merkle.json.leaf_index` and whose `root` matches the bundle's\n * `sth.json.root`.\n *\n * The bundle service refuses to assemble a bundle if an attestation\n * has been logged as `onchain` or `dual` mode but no confirmed\n * receipt exists — i.e. this file is present iff the on-chain claim\n * is substantiated server-side at build time. Per\n * ARCHITECTURE.md §8 D.7, `verify.sh` step 6 is informational only;\n * absence of this file does NOT weaken the proof's off-chain checks.\n *\n * `chain` uses canonical short names matching the on-chain anchor\n * service. `contract` is the registry address as a 0x-prefixed\n * checksummed hex string. `tx` is the tx hash. `block` is the block\n * number containing the tx. `tree_size` and `root` MUST match the\n * corresponding fields of `sth.json`.\n */\nexport interface OnchainProofJson {\n  v: 1;\n  chain: \"base-mainnet\" | \"base-sepolia\";\n  contract: `0x${string}`;\n  tx: `0x${string}`;\n  block: number;\n  segment: number;\n  tree_size: number;\n  root: string;\n}\n\n/**\n * One label entry in `labels.json`.\n *\n * The discriminator is the presence of the `salt` field — `salt`\n * appears ONLY when the bundle was built with the matching label\n * name in the reveal-set query parameter. A verifier seeing a `salt`\n * field MUST compute\n *\n *   SHA-256(name + \":\" + String(value) + \":\" + salt)\n *\n * and check it equals `commit`. Mismatch = the bundle was tampered\n * with or the salt is for a different label.\n *\n * Unrevealed labels have NO `salt` and NO `value` field. Bundle\n * builders MUST default to unrevealed; salts only ship when\n * explicitly requested. SDK consumers MUST NOT render salt values\n * outside an explicit \"reveal\" UI; logging `salt` at any level is a\n * privacy bug.\n */\nexport interface RevealedLabel {\n  name: string;\n  value: boolean | string | number;\n  salt: string;\n  commit: string;\n  public_value?: boolean | string | number;\n}\n\nexport interface UnrevealedLabel {\n  name: string;\n  commit: string;\n  public_value?: boolean | string | number;\n}\n\nexport type BundleLabel = RevealedLabel | UnrevealedLabel;\n\n/**\n * `labels.json`. Always present, even when the envelope has zero\n * labels (in that case `labels` is the empty list). The empty-list\n * sentinel is non-negotiable so verifiers can unconditionally\n * attempt to read this file without first checking its existence.\n */\nexport interface LabelsJson {\n  v: 1;\n  labels: BundleLabel[];\n}\n\n/**\n * Type guard — narrow a `BundleLabel` to the revealed variant.\n * Use to gate any UI that needs to display the salt-recompute step\n * (and only that UI — never log the salt).\n */\nexport function isRevealedLabel(l: BundleLabel): l is RevealedLabel {\n  return (l as RevealedLabel).salt !== undefined;\n}\n\n/**\n * One row in `MANIFEST.txt`. `path` is the bundle-relative path\n * (POSIX forward-slashes); `sha256` is the lowercase hex digest of\n * the file's contents. The on-disk format is sha256sum-compatible.\n */\nexport interface ManifestEntry {\n  path: string;\n  sha256: string;\n}\n\n/**\n * Canonical bundle filenames. Renaming any of these is a breaking\n * change to every historical bundle's `verify.sh` script. Treat as\n * append-only.\n */\nexport const BUNDLE_FILES = {\n  MANIFEST: \"MANIFEST.txt\",\n  ENVELOPE: \"envelope.json\",\n  ENVELOPE_HASH: \"envelope.hash\",\n  ISSUER_PEM: \"issuer.pem\",\n  LABELS: \"labels.json\",\n  MASTER_PEM: \"master.pem\",\n  MERKLE: \"merkle.json\",\n  ONCHAIN: \"onchain.json\",\n  SIGNATURE: \"signature.bin\",\n  STH: \"sth.json\",\n  VERIFY_SCRIPT: \"verify.sh\",\n  MERKLE_WALK_HELPER: \"merkle-walk\",\n  TS_DIGICERT: \"timestamps/digicert.tsr\",\n  TS_DIGICERT_CA: \"timestamps/digicert-ca.pem\",\n  TS_SECTIGO: \"timestamps/sectigo.tsr\",\n  TS_SECTIGO_CA: \"timestamps/sectigo-ca.pem\",\n} as const;\n\nexport const BUNDLE_SUFFIX = \".dpiv-bundle\";\n","/**\n * Typed error hierarchy for `@deepidv/chain`.\n *\n * `DeepidvApiError` is the parent class — every error thrown from\n * the client extends it, and consumers can `catch (err instanceof\n * DeepidvApiError)` once for the whole surface. Specific subclasses\n * exist so common failure modes (auth, not-found, rate-limit) can\n * be branched on without inspecting `status`.\n *\n * Design notes:\n *   - Stack traces include the full prototype chain so `instanceof`\n *     works across the dual ESM/CJS build boundaries.\n *   - `cause` is propagated via the standard ES2022 `cause` option\n *     so wrappers can retain the underlying network error.\n *   - Error messages NEVER include claim bodies, salts, or\n *     authentication headers. Privacy is enforced at construction\n *     time, not at logging time.\n */\n\nexport interface DeepidvApiErrorContext {\n  /** Bundle-relative URL path, e.g. `/v1/registry`. Never query string. */\n  path?: string;\n  /** HTTP status when applicable. */\n  status?: number;\n  /** Request id from the `X-Request-Id` response header, if present. */\n  requestId?: string;\n  /** Underlying network or parse error. */\n  cause?: unknown;\n}\n\nexport class DeepidvApiError extends Error {\n  public readonly path?: string;\n  public readonly status?: number;\n  public readonly requestId?: string;\n  public override readonly cause?: unknown;\n\n  constructor(message: string, ctx: DeepidvApiErrorContext = {}) {\n    super(message, ctx.cause === undefined ? undefined : { cause: ctx.cause });\n    this.name = \"DeepidvApiError\";\n    if (ctx.path !== undefined) this.path = ctx.path;\n    if (ctx.status !== undefined) this.status = ctx.status;\n    if (ctx.requestId !== undefined) this.requestId = ctx.requestId;\n    if (ctx.cause !== undefined) this.cause = ctx.cause;\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n\nexport class DeepidvAuthError extends DeepidvApiError {\n  constructor(message = \"unauthorized\", ctx: DeepidvApiErrorContext = {}) {\n    super(message, { ...ctx, status: ctx.status ?? 401 });\n    this.name = \"DeepidvAuthError\";\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n\nexport class DeepidvNotFoundError extends DeepidvApiError {\n  constructor(message = \"not found\", ctx: DeepidvApiErrorContext = {}) {\n    super(message, { ...ctx, status: ctx.status ?? 404 });\n    this.name = \"DeepidvNotFoundError\";\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n\nexport class DeepidvRateLimitError extends DeepidvApiError {\n  /** Seconds, parsed from the `Retry-After` header when available. */\n  public readonly retryAfterSeconds?: number;\n  constructor(\n    message = \"rate limited\",\n    ctx: DeepidvApiErrorContext & { retryAfterSeconds?: number } = {},\n  ) {\n    super(message, { ...ctx, status: ctx.status ?? 429 });\n    this.name = \"DeepidvRateLimitError\";\n    if (ctx.retryAfterSeconds !== undefined) {\n      this.retryAfterSeconds = ctx.retryAfterSeconds;\n    }\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n\nexport class DeepidvServerError extends DeepidvApiError {\n  constructor(message = \"server error\", ctx: DeepidvApiErrorContext = {}) {\n    super(message, { ...ctx, status: ctx.status ?? 500 });\n    this.name = \"DeepidvServerError\";\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n\nexport class DeepidvNetworkError extends DeepidvApiError {\n  constructor(message: string, ctx: DeepidvApiErrorContext = {}) {\n    super(message, ctx);\n    this.name = \"DeepidvNetworkError\";\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n\n/**\n * Map an HTTP status to the most specific error class.\n *\n * Used by `client.ts::request` to construct the right subclass\n * before throwing. Public so consumers can plug in their own retry\n * policy: `if (mapStatusToError(res.status) === DeepidvRateLimitError) ...`\n */\nexport function statusToErrorClass(status: number): typeof DeepidvApiError {\n  if (status === 401 || status === 403) return DeepidvAuthError;\n  if (status === 404) return DeepidvNotFoundError;\n  if (status === 429) return DeepidvRateLimitError;\n  if (status >= 500) return DeepidvServerError;\n  return DeepidvApiError;\n}\n","/**\n * JCS (RFC 8785) canonicalization.\n *\n * Deterministic JSON serialization. Without this, two servers might\n * produce different byte strings for the same object, breaking hash\n * equality and verification. JCS sorts object keys lexically and\n * uses stable number / string formatting.\n *\n * This implementation matches Python's\n *\n *   json.dumps(o, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=False)\n *\n * for all JSON-safe values used in EnvelopeV1, STH, and bundle JSON\n * files. Cross-language parity is a hard invariant — any change here\n * requires a coordinated update to the Python SDK's equivalent\n * function and a re-run of the parity fixtures (see\n * `test/envelope-parity.spec.ts` and `test/sth-parity.spec.ts`).\n *\n * Functionally equivalent to `shared-deps/chain/lib/crypto.ts::jcs`.\n * Reimplemented here rather than imported because:\n *   - the SDK has zero runtime dependencies (shared-deps pulls in\n *     `@aws-sdk/client-kms` for backend signing);\n *   - duplicating ~25 lines is cheaper than a peer-dep treadmill;\n *   - the parity tests cross-validate byte-for-byte against\n *     shared-deps' fixture, so drift is caught at CI time.\n */\n\nexport function jcs(value: unknown): string {\n  if (value === null) return \"null\";\n  if (typeof value === \"number\") {\n    if (!Number.isFinite(value)) {\n      throw new Error(\"JCS: non-finite number\");\n    }\n    return value.toString();\n  }\n  if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n  if (typeof value === \"string\") return JSON.stringify(value);\n  if (Array.isArray(value)) {\n    return \"[\" + value.map(jcs).join(\",\") + \"]\";\n  }\n  if (typeof value === \"object\") {\n    const obj = value as Record<string, unknown>;\n    const keys = Object.keys(obj).sort();\n    return (\n      \"{\" +\n      keys.map((k) => JSON.stringify(k) + \":\" + jcs(obj[k])).join(\",\") +\n      \"}\"\n    );\n  }\n  throw new Error(\"JCS: unsupported type \" + typeof value);\n}\n","/**\n * Hash primitives — SHA-256 over Buffers and strings, plus the\n * canonical envelope-hash and STH-hash entry points.\n *\n * Uses `node:crypto` only. Browser / non-Node runtimes are not\n * supported in v1; if a Phase 2 use case needs them we can swap in\n * `globalThis.crypto.subtle` behind a thin abstraction.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { jcs } from \"./jcs.js\";\n\nexport function sha256(buf: Buffer | Uint8Array | string): Buffer {\n  const input =\n    typeof buf === \"string\"\n      ? buf\n      : Buffer.isBuffer(buf)\n        ? buf\n        : Buffer.from(buf);\n  return createHash(\"sha256\").update(input).digest();\n}\n\nexport function sha256Hex(buf: Buffer | Uint8Array | string): string {\n  return sha256(buf).toString(\"hex\");\n}\n\n/**\n * Canonical envelope hash.\n *\n * Per ARCHITECTURE.md §5, the envelope does not contain a signature.\n * Defensively strip any `sig` field before hashing — protects\n * against dynamic callers (e.g. negative-case tests, or a deserialized\n * pre-spec envelope) that might include one.\n *\n * The result is the value the issuer signs, the value emitted as\n * `envelope_hash` everywhere, and the value verifiers compare to the\n * `envelope.hash` file inside a bundle.\n */\nexport function envelopeHash(envelope: Record<string, unknown>): string {\n  const withoutSig: Record<string, unknown> = { ...envelope };\n  delete withoutSig.sig;\n  return sha256Hex(jcs(withoutSig));\n}\n\n/**\n * Canonical STH hash.\n *\n * Per ARCHITECTURE.md §6.3, the chain-master signature is stored in\n * the `master_sig` field on the wire form. Strip both `master_sig`\n * and the legacy `sig` (defensively, for any pre-M03 STHs that\n * might still be in flight) before hashing.\n *\n * After stripping, JCS sorts the remaining keys lexically — the\n * preimage byte order is `alg, checkpoint, key_id, root, segment,\n * timestamp, tree_size, v`.\n */\nexport function sthHash(sth: Record<string, unknown>): string {\n  const withoutSigs: Record<string, unknown> = { ...sth };\n  delete withoutSigs.master_sig;\n  delete withoutSigs.sig;\n  return sha256Hex(jcs(withoutSigs));\n}\n","/**\n * `MANIFEST.txt` serializer + parser.\n *\n * Format (per ARCHITECTURE.md §8 D.9):\n *\n *     <64 hex chars><two spaces><path><LF>\n *\n * Drop-in compatible with `sha256sum -c MANIFEST.txt` on Linux and\n * `shasum -a 256 -c MANIFEST.txt` on macOS. Lines are sorted\n * lexically by `path` so two builds of the same bundle produce\n * byte-identical MANIFEST contents.\n *\n * Hex digests are 64 lowercase characters (256 bits). No `0x`\n * prefix. Two literal ASCII spaces separate digest from path —\n * matching GNU coreutils output exactly. Trailing newline after\n * every entry.\n *\n * Paths are bundle-relative POSIX-style with forward slashes\n * (`timestamps/digicert.tsr`, NOT `timestamps\\\\digicert.tsr`). The\n * bundle's zip already enforces forward slashes; manifest paths\n * inherit.\n *\n * Functionally equivalent to\n * `shared-deps/chain/bundle/manifest.ts`. Reimplemented here for\n * dependency-zero parity reasons (see `./jcs.ts` rationale).\n */\n\nimport type { ManifestEntry } from \"../types/index.js\";\n\nconst SHA256_HEX_LEN = 64;\nconst SEPARATOR = \"  \"; // exactly two spaces — sha256sum convention\n\n/**\n * Serialize a list of manifest entries to `MANIFEST.txt` text.\n *\n * Sorts by `path` (lexical) before emitting so output is\n * deterministic — re-running on the same input always produces the\n * same bytes. Sorting is non-mutating; the input array is not\n * modified.\n *\n * Throws if any `sha256` field is not 64 lowercase hex characters,\n * or if any `path` contains a literal newline. Callers should\n * validate inputs upstream; this is defense-in-depth.\n */\nexport function serializeManifest(entries: readonly ManifestEntry[]): string {\n  const sorted = [...entries].sort((a, b) =>\n    a.path < b.path ? -1 : a.path > b.path ? 1 : 0,\n  );\n  const lines: string[] = [];\n  for (const e of sorted) {\n    if (!isValidSha256Hex(e.sha256)) {\n      throw new Error(\n        `manifest: invalid sha256 for \"${e.path}\": expected 64 lowercase hex chars`,\n      );\n    }\n    if (e.path.includes(\"\\n\") || e.path.includes(\"\\r\")) {\n      throw new Error(\n        `manifest: path contains newline: ${JSON.stringify(e.path)}`,\n      );\n    }\n    lines.push(e.sha256 + SEPARATOR + e.path + \"\\n\");\n  }\n  return lines.join(\"\");\n}\n\n/**\n * Parse `MANIFEST.txt` text back into entries.\n *\n * Strict — rejects:\n *   - lines that don't match the `<64 hex>  <path>` shape\n *   - duplicate paths (the bundle builder never produces duplicates;\n *     a duplicate at parse time means the manifest was tampered\n *     with or hand-edited)\n *   - paths beginning with whitespace (defends against an attacker\n *     padding the separator with extra spaces)\n *\n * Tolerates a trailing empty line (CRLF or LF). Does NOT tolerate\n * arbitrary whitespace around fields — the format is rigid by\n * design so malicious manifests can't sneak in lookalike paths via\n * normalization.\n *\n * Returns entries in their on-disk order. Callers that need a\n * canonical order should sort by `path`; `serializeManifest`\n * round-trips a sort.\n */\nexport function parseManifest(text: string): ManifestEntry[] {\n  const out: ManifestEntry[] = [];\n  const seen = new Set<string>();\n  const lines = text\n    .split(\"\\n\")\n    .map((l) => (l.endsWith(\"\\r\") ? l.slice(0, -1) : l));\n  while (lines.length > 0 && lines[lines.length - 1] === \"\") {\n    lines.pop();\n  }\n  for (let i = 0; i < lines.length; i++) {\n    const line = lines[i] as string;\n    if (line.length === 0) {\n      throw new Error(`manifest: empty line at line ${i + 1}`);\n    }\n    if (line.length < SHA256_HEX_LEN + SEPARATOR.length + 1) {\n      throw new Error(`manifest: short line at line ${i + 1}`);\n    }\n    const sha256 = line.slice(0, SHA256_HEX_LEN);\n    const sep = line.slice(SHA256_HEX_LEN, SHA256_HEX_LEN + SEPARATOR.length);\n    const path = line.slice(SHA256_HEX_LEN + SEPARATOR.length);\n    if (!isValidSha256Hex(sha256)) {\n      throw new Error(`manifest: invalid sha256 at line ${i + 1}`);\n    }\n    if (sep !== SEPARATOR) {\n      throw new Error(`manifest: missing two-space separator at line ${i + 1}`);\n    }\n    if (path.length === 0) {\n      throw new Error(`manifest: empty path at line ${i + 1}`);\n    }\n    if (path[0] === \" \" || path[0] === \"\\t\") {\n      throw new Error(`manifest: path begins with whitespace at line ${i + 1}`);\n    }\n    if (seen.has(path)) {\n      throw new Error(`manifest: duplicate path at line ${i + 1}: ${path}`);\n    }\n    seen.add(path);\n    out.push({ path, sha256 });\n  }\n  return out;\n}\n\n/**\n * True iff `s` is exactly 64 lowercase hex characters. The format\n * is deliberately strict — uppercase or short digests are rejected\n * so verifiers can rely on byte-equality of MANIFEST contents\n * across platforms.\n */\nexport function isValidSha256Hex(s: string): boolean {\n  if (s.length !== SHA256_HEX_LEN) return false;\n  for (let i = 0; i < SHA256_HEX_LEN; i++) {\n    const c = s.charCodeAt(i);\n    const isDigit = c >= 0x30 && c <= 0x39;\n    const isLowerHex = c >= 0x61 && c <= 0x66;\n    if (!isDigit && !isLowerHex) return false;\n  }\n  return true;\n}\n","/**\n * RFC 6962 Certificate-Transparency-style Merkle tree primitives.\n *\n * - Domain-separated leaf and node prefixes (0x00, 0x01) to prevent\n *   second-preimage / length-extension attacks.\n * - SHA-256 only in v1 (matches shared-deps default; SHA-512 lives\n *   on the backend tree but is irrelevant to v1 verification).\n * - Verification only: this SDK never builds trees, only walks\n *   audit paths. Tree construction lives in the backend\n *   (`anchor-service` Lambda) and is unnecessary here.\n *\n * Mirrors `shared-deps/chain/lib/merkle.ts::leafHash`,\n * `nodeHash`, `verifyInclusion`. Reimplemented for the same\n * dependency-zero reasons as `./jcs.ts`.\n */\n\nimport { createHash } from \"node:crypto\";\n\nconst LEAF_PREFIX = Buffer.from([0x00]);\nconst NODE_PREFIX = Buffer.from([0x01]);\n\nfunction h(...parts: Buffer[]): Buffer {\n  const d = createHash(\"sha256\");\n  for (const p of parts) d.update(p);\n  return d.digest();\n}\n\n/**\n * Hash a leaf payload (canonical envelope bytes).\n *\n * The result is the bundle's `merkle.json::leaf_hash` — NOT the\n * envelope hash. The two differ by the `0x00` prefix; a verifier\n * that compares them directly is wrong.\n */\nexport function leafHash(payload: Buffer | Uint8Array): Buffer {\n  const buf = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);\n  return h(LEAF_PREFIX, buf);\n}\n\n/** Hash an internal node from two children. */\nexport function nodeHash(left: Buffer, right: Buffer): Buffer {\n  return h(NODE_PREFIX, left, right);\n}\n\n/**\n * Verify an inclusion proof.\n *\n * Recomputes the root from `(leaf, m, n, path)` and compares against\n * `expectedRoot`. Consumes the path bottom-up (closest-to-leaf first),\n * matching the RFC 6962 §2.1.1 audit-path format and the order that\n * the backend's `inclusionProof` produces.\n *\n * Handles non-power-of-two sizes correctly: at levels where a subtree\n * is \"promoted\" without a sibling (`fn === sn`), the walk keeps\n * climbing until it encounters the next real sibling.\n */\nexport function verifyInclusion(\n  leaf: Buffer,\n  m: number,\n  n: number,\n  path: Buffer[],\n  expectedRoot: Buffer,\n): boolean {\n  if (m >= n || n === 0) return false;\n\n  let fn = m;\n  let sn = n - 1;\n  let r = leaf;\n\n  for (const sibling of path) {\n    if (sn === 0) return false; // over-long path\n    if ((fn & 1) === 1 || fn === sn) {\n      r = nodeHash(sibling, r);\n      while ((fn & 1) === 0 && fn !== 0) {\n        fn >>= 1;\n        sn >>= 1;\n      }\n    } else {\n      r = nodeHash(r, sibling);\n    }\n    fn >>= 1;\n    sn >>= 1;\n  }\n\n  return sn === 0 && r.equals(expectedRoot);\n}\n\n/**\n * Verify a consistency proof: old root (size m) → new root (size n).\n * RFC 6962 §2.1.4.\n *\n * Used by witness implementations and the consistency-check feature\n * in the Governance Console (M10). Verification only — no proof\n * construction in v1.\n */\nexport function verifyConsistency(\n  oldRoot: Buffer,\n  newRoot: Buffer,\n  m: number,\n  n: number,\n  proof: Buffer[],\n): boolean {\n  if (m < 0 || m > n) return false;\n  if (m === n) return proof.length === 0 && oldRoot.equals(newRoot);\n  if (m === 0) return proof.length === 0;\n\n  let fn = m - 1;\n  let sn = n - 1;\n  while ((fn & 1) === 1) {\n    fn >>= 1;\n    sn >>= 1;\n  }\n\n  let i = 0;\n  let oldHash: Buffer;\n  let newHash: Buffer;\n\n  if (fn === 0) {\n    oldHash = oldRoot;\n    newHash = oldRoot;\n  } else {\n    if (proof.length === 0) return false;\n    oldHash = proof[i] as Buffer;\n    newHash = proof[i] as Buffer;\n    i++;\n  }\n\n  while (sn !== 0) {\n    if (i >= proof.length) return false;\n    if ((fn & 1) === 1 || fn === sn) {\n      const sib = proof[i] as Buffer;\n      oldHash = nodeHash(sib, oldHash);\n      newHash = nodeHash(sib, newHash);\n      while ((fn & 1) === 0 && fn !== 0) {\n        fn >>= 1;\n        sn >>= 1;\n      }\n    } else {\n      const sib = proof[i] as Buffer;\n      newHash = nodeHash(newHash, sib);\n    }\n    i++;\n    fn >>= 1;\n    sn >>= 1;\n  }\n\n  return (\n    i === proof.length && oldHash.equals(oldRoot) && newHash.equals(newRoot)\n  );\n}\n\nexport const hex = (b: Buffer): string => b.toString(\"hex\");\nexport const unhex = (s: string): Buffer => Buffer.from(s, \"hex\");\n","/**\n * Server-Sent Events stream consumer.\n *\n * The chain registry exposes `/v1/stream` as a long-lived\n * `text/event-stream` connection emitting one JSON-encoded\n * `StreamEvent` per `data:` frame. This module turns that into an\n * `AsyncIterable<StreamEvent>` with built-in reconnection backoff.\n *\n * Why a hand-rolled SSE consumer rather than EventSource?\n *   - Node 20's `EventSource` is still flagged behind `--experimental`\n *     in some patch versions and skips the `Last-Event-ID` semantics\n *     we want for resumption.\n *   - Keeping the SDK runtime-dep-free rules out `eventsource` /\n *     `@microsoft/fetch-event-source`.\n *   - We only need a parser for the `data:` field — no comments, no\n *     custom event types — so the spec subset is small enough to own.\n *\n * Reconnect policy:\n *   - Connection lost → exponential backoff starting at `initialDelayMs`,\n *     doubling up to `maxDelayMs`, with ±20 % jitter.\n *   - The iterator surfaces every event delivered between reconnects\n *     transparently. Consumers see a continuous stream.\n *   - Stop iterating (`break`, `return`, `throw`) cleanly aborts the\n *     underlying fetch.\n */\n\nimport type { StreamEvent } from \"../types/api.js\";\nimport { DeepidvNetworkError } from \"../errors/index.js\";\n\nexport interface SseStreamOptions {\n  url: string;\n  fetch: typeof fetch;\n  /** Caller-provided abort signal. Iteration stops when it fires. */\n  signal?: AbortSignal | undefined;\n  initialDelayMs?: number;\n  maxDelayMs?: number;\n  /** Optional `Last-Event-ID` for resumption after a reconnect. */\n  lastEventId?: string;\n  /** Custom request headers (e.g. `Accept-Language`). Authorization\n   *  is NOT supported on the public stream — the registry is\n   *  unauthenticated. */\n  headers?: Record<string, string>;\n}\n\nconst DEFAULT_INITIAL_DELAY_MS = 500;\nconst DEFAULT_MAX_DELAY_MS = 30_000;\n\n/**\n * Yields `StreamEvent` values from the registry's `/v1/stream`\n * endpoint. Reconnects automatically; surfaces a final\n * `DeepidvNetworkError` only if the caller's `signal` aborts AND\n * a reconnect was already in flight (clean shutdown is silent).\n *\n * Usage:\n *\n *     for await (const ev of streamAttestations({...})) {\n *       if (ev.type === \"attestation.minted\") console.log(ev.payload.id);\n *     }\n */\nexport async function* sseIterator(\n  opts: SseStreamOptions,\n): AsyncIterableIterator<StreamEvent> {\n  const initial = opts.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n  const max = opts.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n  let delay = initial;\n  let lastEventId = opts.lastEventId;\n\n  while (!opts.signal?.aborted) {\n    let response: Response;\n    try {\n      const headers: Record<string, string> = {\n        Accept: \"text/event-stream\",\n        \"Cache-Control\": \"no-cache\",\n        ...opts.headers,\n      };\n      if (lastEventId) headers[\"Last-Event-ID\"] = lastEventId;\n\n      const init: RequestInit = { method: \"GET\", headers };\n      if (opts.signal) init.signal = opts.signal;\n      response = await opts.fetch(opts.url, init);\n    } catch {\n      if (opts.signal?.aborted) return;\n      await sleep(jitter(delay), opts.signal);\n      delay = Math.min(delay * 2, max);\n      continue;\n    }\n\n    if (!response.ok || !response.body) {\n      // 4xx/5xx — back off, retry. We do NOT throw here; the registry\n      // can transiently 503 during deploys and consumers expect the\n      // iterator to ride through it.\n      try {\n        await response.body?.cancel();\n      } catch {\n        // ignore\n      }\n      await sleep(jitter(delay), opts.signal);\n      delay = Math.min(delay * 2, max);\n      continue;\n    }\n\n    // Connected — reset backoff.\n    delay = initial;\n\n    try {\n      for await (const ev of parseEventStream(response.body, opts.signal)) {\n        if (ev.id) lastEventId = ev.id;\n        if (ev.data === undefined || ev.data === \"\") continue;\n        try {\n          const parsed = JSON.parse(ev.data) as StreamEvent;\n          yield parsed;\n        } catch {\n          // Drop malformed frames silently — the registry guarantees\n          // valid JSON per frame; a malformed frame indicates a wire-\n          // level corruption that the next frame will recover from.\n          continue;\n        }\n      }\n    } catch {\n      if (opts.signal?.aborted) return;\n      // Underlying body iteration threw — fall through to reconnect.\n      await sleep(jitter(delay), opts.signal);\n      delay = Math.min(delay * 2, max);\n      continue;\n    }\n\n    // Stream ended cleanly without abort — reconnect after a small\n    // pause. This handles registry edge proxies that recycle long-\n    // lived connections every few minutes.\n    if (!opts.signal?.aborted) {\n      await sleep(jitter(initial), opts.signal);\n    }\n  }\n}\n\ninterface ParsedFrame {\n  id?: string;\n  event?: string;\n  data?: string;\n}\n\nasync function* parseEventStream(\n  body: ReadableStream<Uint8Array>,\n  signal: AbortSignal | undefined,\n): AsyncIterableIterator<ParsedFrame> {\n  const decoder = new TextDecoder(\"utf-8\");\n  const reader = body.getReader();\n  let buffer = \"\";\n\n  try {\n    while (true) {\n      if (signal?.aborted) return;\n      const { value, done } = await reader.read();\n      if (done) break;\n      buffer += decoder.decode(value, { stream: true });\n\n      let sepIdx: number;\n      while ((sepIdx = buffer.search(/\\r?\\n\\r?\\n/)) >= 0) {\n        const frameText = buffer.slice(0, sepIdx);\n        const matched = buffer.slice(sepIdx).match(/^\\r?\\n\\r?\\n/);\n        buffer = buffer.slice(sepIdx + (matched ? matched[0].length : 2));\n        const frame = parseFrame(frameText);\n        if (frame !== null) yield frame;\n      }\n    }\n\n    // Trailing buffer at clean EOF — only emit if it's a full frame.\n    if (buffer.length > 0) {\n      const frame = parseFrame(buffer);\n      if (frame !== null) yield frame;\n    }\n  } finally {\n    try {\n      reader.releaseLock();\n    } catch {\n      // ignore\n    }\n  }\n}\n\nfunction parseFrame(text: string): ParsedFrame | null {\n  const out: ParsedFrame = {};\n  const dataLines: string[] = [];\n  for (const rawLine of text.split(/\\r?\\n/)) {\n    if (rawLine === \"\" || rawLine.startsWith(\":\")) continue;\n    const colonIdx = rawLine.indexOf(\":\");\n    const field = colonIdx === -1 ? rawLine : rawLine.slice(0, colonIdx);\n    let value = colonIdx === -1 ? \"\" : rawLine.slice(colonIdx + 1);\n    if (value.startsWith(\" \")) value = value.slice(1);\n    if (field === \"data\") dataLines.push(value);\n    else if (field === \"id\") out.id = value;\n    else if (field === \"event\") out.event = value;\n    // retry/everything else: ignored — the SDK manages backoff.\n  }\n  if (dataLines.length > 0) out.data = dataLines.join(\"\\n\");\n  if (\n    out.data === undefined &&\n    out.id === undefined &&\n    out.event === undefined\n  ) {\n    return null;\n  }\n  return out;\n}\n\nfunction jitter(ms: number): number {\n  const j = ms * (0.8 + Math.random() * 0.4);\n  return Math.max(50, Math.min(ms * 2, j));\n}\n\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n  return new Promise<void>((resolve) => {\n    if (signal?.aborted) {\n      resolve();\n      return;\n    }\n    const timer = setTimeout(() => {\n      cleanup();\n      resolve();\n    }, ms);\n    const onAbort = (): void => {\n      clearTimeout(timer);\n      cleanup();\n      resolve();\n    };\n    const cleanup = (): void => {\n      signal?.removeEventListener(\"abort\", onAbort);\n    };\n    signal?.addEventListener(\"abort\", onAbort);\n  });\n}\n\n// Suppress unused export-only type; keeps the public surface tidy.\nexport type { DeepidvNetworkError };\n","/**\n * `@deepidv/chain/client` — typed wrapper around the public registry\n * API at `api.proof.deepidv.com/v1`.\n *\n * The client is a thin GET-only fetcher: every operation is a read.\n * Mint and revoke are tenant-authenticated operations that don't\n * belong on this SDK in v1 — they live behind tenant-API-key auth on\n * a different surface (see runbook §0.E for credential hygiene).\n *\n * Pluggable `fetch` lets consumers wire in:\n *   - `node-fetch` polyfills (Node <20 — discouraged but supported)\n *   - request signing wrappers\n *   - Cloudflare Workers / Bun / Deno's native fetch\n *\n * SSE streaming is exposed as `streamAttestations()`, which returns\n * an `AsyncIterable<StreamEvent>` with built-in reconnect.\n *\n * Bundle download returns an `ArrayBuffer` ready to be unzipped by\n * the verify module.\n */\n\nimport {\n  DeepidvApiError,\n  DeepidvNetworkError,\n  DeepidvRateLimitError,\n  statusToErrorClass,\n} from \"../errors/index.js\";\nimport type {\n  AttestationDetail,\n  ConsistencyProofResponse,\n  IssuerDetail,\n  RegistryListFilters,\n  RegistryPage,\n  SegmentDetail,\n  StreamEvent,\n  SthListResponse,\n} from \"../types/api.js\";\nimport { sseIterator } from \"./sse.js\";\n\nexport type FetchLike = typeof fetch;\n\nexport interface ClientOptions {\n  /**\n   * Base URL of the registry API. Default:\n   * `https://staging-api.proof.deepidv.com`.\n   *\n   * Production hosts the same surface at\n   * `https://api.proof.deepidv.com`. Override at construction time.\n   * No trailing slash; the client adds `/v1/...` paths.\n   */\n  apiUrl?: string;\n  /**\n   * Custom fetch implementation. Defaults to `globalThis.fetch`.\n   * Pass a wrapped fetch to inject headers, telemetry, or retries.\n   */\n  fetch?: FetchLike;\n  /**\n   * Optional default `User-Agent`. The registry doesn't require one\n   * but identifying SDK versions makes operator triage easier.\n   */\n  userAgent?: string;\n  /**\n   * Default per-request timeout in milliseconds. Default `15_000`.\n   * `0` disables. Plumbed via `AbortSignal.timeout(...)`.\n   */\n  timeoutMs?: number;\n}\n\nconst DEFAULT_API_URL = \"https://staging-api.proof.deepidv.com\";\nconst DEFAULT_TIMEOUT_MS = 15_000;\nconst SDK_USER_AGENT = \"deepidv-chain-node/1.1.0\";\n\nexport interface RequestOptions {\n  signal?: AbortSignal;\n  /** Per-request override of the client's default timeout. */\n  timeoutMs?: number;\n}\n\nexport class DeepidvChainClient {\n  public readonly apiUrl: string;\n  private readonly fetchImpl: FetchLike;\n  private readonly userAgent: string;\n  private readonly defaultTimeoutMs: number;\n\n  constructor(opts: ClientOptions = {}) {\n    this.apiUrl = (opts.apiUrl ?? DEFAULT_API_URL).replace(/\\/+$/, \"\");\n    this.fetchImpl =\n      opts.fetch ??\n      (typeof globalThis.fetch === \"function\"\n        ? globalThis.fetch.bind(globalThis)\n        : (() => {\n            throw new DeepidvNetworkError(\n              \"no fetch available — pass a `fetch` option (Node 20+ has it built in)\",\n            );\n          })());\n    this.userAgent = opts.userAgent ?? SDK_USER_AGENT;\n    this.defaultTimeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n  }\n\n  /* ------------------------------------------------------------ *\n   *  Public read methods\n   * ------------------------------------------------------------ */\n\n  async getAttestation(\n    id: string,\n    opts: RequestOptions = {},\n  ): Promise<AttestationDetail> {\n    return this.requestJson<AttestationDetail>(\n      `/v1/attestation/${encodeURIComponent(id)}`,\n      opts,\n    );\n  }\n\n  async listRegistry(\n    filters: RegistryListFilters & { page?: number; cursor?: string } = {},\n    opts: RequestOptions = {},\n  ): Promise<RegistryPage> {\n    const search = new URLSearchParams();\n    if (typeof filters.page === \"number\") {\n      search.set(\"page\", String(filters.page));\n    }\n    if (filters.cursor) search.set(\"cursor\", filters.cursor);\n    if (filters.type) search.set(\"type\", filters.type);\n    if (filters.issuer) search.set(\"issuer\", filters.issuer);\n    if (filters.q) search.set(\"q\", filters.q);\n    const qs = search.toString();\n    return this.requestJson<RegistryPage>(\n      `/v1/registry${qs ? `?${qs}` : \"\"}`,\n      opts,\n    );\n  }\n\n  async getIssuer(\n    id: string,\n    opts: RequestOptions = {},\n  ): Promise<IssuerDetail> {\n    return this.requestJson<IssuerDetail>(\n      `/v1/issuer/${encodeURIComponent(id)}`,\n      opts,\n    );\n  }\n\n  async getSegment(\n    n: number,\n    opts: RequestOptions = {},\n  ): Promise<SegmentDetail> {\n    return this.requestJson<SegmentDetail>(`/v1/segment/${n}`, opts);\n  }\n\n  async listSths(\n    segment: number,\n    opts: RequestOptions = {},\n  ): Promise<SthListResponse> {\n    return this.requestJson<SthListResponse>(\n      `/v1/sth?segment=${segment}`,\n      opts,\n    );\n  }\n\n  async getConsistencyProof(\n    fromTreeSize: number,\n    toTreeSize: number,\n    segment: number,\n    opts: RequestOptions = {},\n  ): Promise<ConsistencyProofResponse> {\n    const search = new URLSearchParams({\n      from: String(fromTreeSize),\n      to: String(toTreeSize),\n      segment: String(segment),\n    });\n    return this.requestJson<ConsistencyProofResponse>(\n      `/v1/consistency?${search.toString()}`,\n      opts,\n    );\n  }\n\n  /**\n   * The transparency log viewer endpoint — returns the latest\n   * checkpoint for every open segment plus the current head's STH.\n   * Shape is the same as `getSegment` for each entry.\n   */\n  async getLog(\n    opts: RequestOptions = {},\n  ): Promise<{ segments: SegmentDetail[] }> {\n    return this.requestJson<{ segments: SegmentDetail[] }>(`/v1/log`, opts);\n  }\n\n  /**\n   * Download a `.dpiv-bundle` zip as raw bytes. The caller unzips\n   * and feeds the result to `verifyBundle()` from\n   * `@deepidv/chain/verify`.\n   */\n  async downloadBundle(\n    id: string,\n    opts: RequestOptions = {},\n  ): Promise<ArrayBuffer> {\n    const path = `/v1/bundle/${encodeURIComponent(id)}`;\n    const res = await this.rawRequest(path, {\n      ...opts,\n      headers: { Accept: \"application/octet-stream\" },\n    });\n    return await res.arrayBuffer();\n  }\n\n  /**\n   * Subscribe to live attestation events.\n   *\n   * Returns an `AsyncIterable<StreamEvent>`. The iterator manages\n   * reconnection internally (exponential backoff, jittered, capped\n   * at 30s). Pass `signal` to stop iterating cleanly.\n   *\n   *     const ctrl = new AbortController();\n   *     for await (const ev of client.streamAttestations({ signal: ctrl.signal })) {\n   *       if (ev.type === \"attestation.minted\") {\n   *         console.log(ev.payload.id);\n   *       }\n   *     }\n   */\n  streamAttestations(\n    opts: { signal?: AbortSignal | undefined } = {},\n  ): AsyncIterable<StreamEvent> {\n    const url = `${this.apiUrl}/v1/stream`;\n    return sseIterator({\n      url,\n      fetch: this.fetchImpl,\n      signal: opts.signal,\n      headers: { \"User-Agent\": this.userAgent },\n    });\n  }\n\n  /* ------------------------------------------------------------ *\n   *  Internal request plumbing\n   * ------------------------------------------------------------ */\n\n  private async requestJson<T>(path: string, opts: RequestOptions): Promise<T> {\n    const res = await this.rawRequest(path, {\n      ...opts,\n      headers: { Accept: \"application/json\" },\n    });\n    try {\n      return (await res.json()) as T;\n    } catch (err) {\n      throw new DeepidvApiError(\"invalid JSON in response\", {\n        path,\n        status: res.status,\n        cause: err,\n      });\n    }\n  }\n\n  private async rawRequest(\n    path: string,\n    opts: RequestOptions & { headers?: Record<string, string> },\n  ): Promise<Response> {\n    const url = `${this.apiUrl}${path}`;\n    const timeoutMs = opts.timeoutMs ?? this.defaultTimeoutMs;\n\n    const headers: Record<string, string> = {\n      \"User-Agent\": this.userAgent,\n      ...(opts.headers ?? {}),\n    };\n\n    const signal = combineSignals(opts.signal, timeoutMs);\n\n    let res: Response;\n    try {\n      const init: RequestInit = { method: \"GET\", headers };\n      if (signal) init.signal = signal;\n      res = await this.fetchImpl(url, init);\n    } catch (err) {\n      throw new DeepidvNetworkError(\n        `network error fetching ${path}: ${describeError(err)}`,\n        { path, cause: err },\n      );\n    }\n\n    if (!res.ok) {\n      const requestId =\n        res.headers.get(\"x-request-id\") ??\n        res.headers.get(\"x-amzn-requestid\") ??\n        undefined;\n      const body = await res.text().catch(() => \"\");\n      const ErrorClass = statusToErrorClass(res.status);\n      const ctx: { path: string; status: number; requestId?: string } = {\n        path,\n        status: res.status,\n      };\n      if (requestId !== undefined) ctx.requestId = requestId;\n      if (ErrorClass === DeepidvRateLimitError) {\n        const retryAfter = res.headers.get(\"retry-after\");\n        const retryAfterSeconds = retryAfter\n          ? Number.parseInt(retryAfter, 10)\n          : undefined;\n        const rlCtx: typeof ctx & { retryAfterSeconds?: number } = ctx;\n        if (\n          retryAfterSeconds !== undefined &&\n          Number.isFinite(retryAfterSeconds)\n        ) {\n          rlCtx.retryAfterSeconds = retryAfterSeconds;\n        }\n        throw new DeepidvRateLimitError(\n          truncateBody(body) || \"rate limited\",\n          rlCtx,\n        );\n      }\n      throw new ErrorClass(truncateBody(body) || `HTTP ${res.status}`, ctx);\n    }\n    return res;\n  }\n}\n\n/**\n * Convenience constructor — many consumers prefer\n * `createClient({...})` over `new DeepidvChainClient({...})`.\n */\nexport function createClient(opts: ClientOptions = {}): DeepidvChainClient {\n  return new DeepidvChainClient(opts);\n}\n\nfunction combineSignals(\n  caller: AbortSignal | undefined,\n  timeoutMs: number,\n): AbortSignal | undefined {\n  if (timeoutMs <= 0) return caller;\n  const timeoutSignal = AbortSignal.timeout(timeoutMs);\n  if (!caller) return timeoutSignal;\n  if (typeof AbortSignal.any === \"function\") {\n    return AbortSignal.any([caller, timeoutSignal]);\n  }\n  // Fallback for runtimes without AbortSignal.any.\n  const ctrl = new AbortController();\n  const onAbort = (sig: AbortSignal): void => {\n    ctrl.abort(sig.reason);\n  };\n  caller.addEventListener(\"abort\", () => onAbort(caller), { once: true });\n  timeoutSignal.addEventListener(\"abort\", () => onAbort(timeoutSignal), {\n    once: true,\n  });\n  return ctrl.signal;\n}\n\nfunction describeError(err: unknown): string {\n  if (err instanceof Error) return err.message;\n  return String(err);\n}\n\nfunction truncateBody(body: string): string {\n  const trimmed = body.trim();\n  if (trimmed.length === 0) return \"\";\n  if (trimmed.length <= 200) return trimmed;\n  return trimmed.slice(0, 200) + \"…\";\n}\n","/**\n * Minimal stored-method ZIP reader.\n *\n * `.dpiv-bundle` files are produced by the M05 bundle Lambda using\n * the stored (uncompressed) method per ARCHITECTURE.md §8 D.4 — the\n * payloads are already entropy-dense (sigs, hex digests, signed\n * timestamps) and storing uncompressed lets verifiers operate\n * without a deflate implementation. That choice keeps this SDK at\n * zero runtime deps.\n *\n * This reader supports STORED (method=0) only. If the registry ever\n * starts emitting DEFLATE bundles, this function throws a clear\n * \"unsupported compression method\" error rather than silently\n * misverifying. The intent is documented in the bundle builder, the\n * verify.sh script, and ARCHITECTURE.md — coordinated change only.\n *\n * No symlink, no zip-slip, no UTF-8 surprises. Path entries are\n * checked against backslashes and `..` segments before being added\n * to the output map.\n */\n\nconst ZIP_LFH_SIG = 0x04034b50;\nconst ZIP_CDFH_SIG = 0x02014b50;\nconst ZIP_EOCD_SIG = 0x06054b50;\n\nconst METHOD_STORED = 0;\n\nexport interface UnzipResult {\n  /** Bundle-relative path → file bytes. POSIX forward slashes only. */\n  files: Record<string, Uint8Array>;\n}\n\n/**\n * Parse a stored-method ZIP buffer into a flat path → bytes map.\n *\n * Reads the End Of Central Directory record at the tail, walks the\n * central directory forward, and extracts each entry from its local\n * file header position. Refuses entries with backslashes, leading\n * slashes, or `..` segments.\n */\nexport function unzipBundle(input: ArrayBuffer | Uint8Array): UnzipResult {\n  const buf = input instanceof ArrayBuffer ? new Uint8Array(input) : input;\n  const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n\n  // Locate EOCD (search backward up to ~64 KB to skip a minimal\n  // ZIP64 / no-comment archive — the bundle's comment is empty).\n  const maxBack = Math.min(buf.byteLength, 65557);\n  let eocdOffset = -1;\n  for (let i = buf.byteLength - 22; i >= buf.byteLength - maxBack; i--) {\n    if (i < 0) break;\n    if (dv.getUint32(i, true) === ZIP_EOCD_SIG) {\n      eocdOffset = i;\n      break;\n    }\n  }\n  if (eocdOffset === -1) {\n    throw new Error(\"unzip: not a ZIP archive (no EOCD signature)\");\n  }\n\n  const totalEntries = dv.getUint16(eocdOffset + 10, true);\n  const cdSize = dv.getUint32(eocdOffset + 12, true);\n  const cdOffset = dv.getUint32(eocdOffset + 16, true);\n  if (cdSize === 0xffffffff || cdOffset === 0xffffffff) {\n    throw new Error(\"unzip: ZIP64 archives are not supported\");\n  }\n\n  const files: Record<string, Uint8Array> = {};\n  let cur = cdOffset;\n  const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\n  for (let i = 0; i < totalEntries; i++) {\n    if (dv.getUint32(cur, true) !== ZIP_CDFH_SIG) {\n      throw new Error(\"unzip: bad central directory file header\");\n    }\n    const method = dv.getUint16(cur + 10, true);\n    const compressedSize = dv.getUint32(cur + 20, true);\n    const uncompressedSize = dv.getUint32(cur + 24, true);\n    const nameLen = dv.getUint16(cur + 28, true);\n    const extraLen = dv.getUint16(cur + 30, true);\n    const commentLen = dv.getUint16(cur + 32, true);\n    const lfhOffset = dv.getUint32(cur + 42, true);\n\n    if (compressedSize === 0xffffffff || uncompressedSize === 0xffffffff) {\n      throw new Error(\"unzip: ZIP64 entries are not supported\");\n    }\n    if (lfhOffset === 0xffffffff) {\n      throw new Error(\"unzip: ZIP64 entries are not supported\");\n    }\n\n    const nameBytes = buf.subarray(cur + 46, cur + 46 + nameLen);\n    let name: string;\n    try {\n      name = decoder.decode(nameBytes);\n    } catch {\n      throw new Error(\"unzip: filename is not valid UTF-8\");\n    }\n\n    if (name.length === 0) {\n      throw new Error(\"unzip: empty filename in central directory\");\n    }\n    if (name.includes(\"\\\\\")) {\n      throw new Error(`unzip: backslash in filename: ${JSON.stringify(name)}`);\n    }\n    if (name.startsWith(\"/\")) {\n      throw new Error(`unzip: absolute path filename: ${JSON.stringify(name)}`);\n    }\n    for (const segment of name.split(\"/\")) {\n      if (segment === \"..\") {\n        throw new Error(\n          `unzip: parent-directory traversal in filename: ${JSON.stringify(name)}`,\n        );\n      }\n    }\n\n    cur += 46 + nameLen + extraLen + commentLen;\n\n    // Skip directory entries (trailing /).\n    if (name.endsWith(\"/\")) continue;\n\n    if (method !== METHOD_STORED) {\n      throw new Error(\n        `unzip: unsupported compression method ${method} for ${JSON.stringify(name)} ` +\n          `(only STORED is supported; .dpiv-bundle uses STORED per ARCHITECTURE.md §8 D.4)`,\n      );\n    }\n\n    if (dv.getUint32(lfhOffset, true) !== ZIP_LFH_SIG) {\n      throw new Error(\"unzip: bad local file header\");\n    }\n    const lfhNameLen = dv.getUint16(lfhOffset + 26, true);\n    const lfhExtraLen = dv.getUint16(lfhOffset + 28, true);\n    const dataStart = lfhOffset + 30 + lfhNameLen + lfhExtraLen;\n    const dataEnd = dataStart + compressedSize;\n    if (dataEnd > buf.byteLength) {\n      throw new Error(`unzip: entry \"${name}\" extends past end of archive`);\n    }\n\n    files[name] = buf.subarray(dataStart, dataEnd);\n  }\n\n  return { files };\n}\n","/**\n * Partial in-process bundle verifier — 5 of 6 checks per\n * ARCHITECTURE.md §8 D.5.\n *\n *                  ⚠ DELIBERATE PARTIAL VERIFIER ⚠\n *\n * This SDK performs FIVE of the six checks defined in\n * ARCHITECTURE.md §8 D.5. Step 3 — RFC 3161 timestamp token\n * verification against the DigiCert and Sectigo TSA CA chains — is\n * **deliberately skipped**. Pulling a full ASN.1 + RFC 3161 verifier\n * into a zero-dependency SDK would add ~200 KB of transitive deps;\n * any caller that needs the canonical TSA check should run the\n * bundle's own `verify.sh` script (which uses `openssl ts -verify`\n * and is the canonical TSA verifier by design).\n *\n * Step 3 status is reported as the literal string `\"skipped\"`\n * rather than a boolean — callers MUST handle that case explicitly.\n * We do not silently treat unverified TSA tokens as valid.\n *\n * # Checks performed\n *\n *   1. envelope_hash:          SHA-256(JCS(envelope.json)) ==\n *                              envelope.hash content\n *   2. issuer_signature:       ECDSA P-256 / SHA-256 verify of\n *                              signature.bin against the canonical\n *                              envelope bytes using issuer.pem\n *   3. tsa_tokens:             SKIPPED — see above\n *   4. merkle_inclusion:       audit_path walk closes to\n *                              sth.json.root via RFC 6962 leaf/node\n *                              prefixes\n *   5. master_sth_signature:   ECDSA P-256 / SHA-256 verify of\n *                              base64-decoded master_sig against the\n *                              JCS-canonical STH preimage using\n *                              master.pem\n *   6. onchain_anchor:         presence + structural validity of\n *                              onchain.json (or \"absent\" when the\n *                              file isn't in the bundle).\n *                              INFORMATIONAL ONLY — we do NOT call\n *                              an RPC. Live tx existence is a\n *                              verify.sh / SDK-RPC concern.\n *\n * # Cross-check requirements (defense in depth)\n *\n *   - merkle.json.segment must equal sth.json.segment\n *   - merkle.json.leaf_index must be < sth.json.tree_size\n *   - audit_path verification uses sth.json.root as the expected\n *     root\n *   - When onchain.json is present, its (segment, tree_size, root)\n *     must equal sth.json's\n *\n * # Privacy\n *\n * verifyBundle MUST NOT log salt values. Any salt in\n * `labels.json::RevealedLabel` is recomputed against `commit` and\n * cross-checked, then discarded. Callers building UIs that surface\n * the salt do so explicitly via `parseLabels` — never via the\n * verifier.\n */\n\nimport { createPublicKey, createVerify } from \"node:crypto\";\n\nimport { jcs } from \"../crypto/jcs.js\";\nimport { sha256Hex } from \"../crypto/hash.js\";\nimport { leafHash, verifyInclusion, unhex } from \"../crypto/merkle.js\";\nimport { BUNDLE_FILES } from \"../types/bundle.js\";\nimport type { MerkleProofJson, OnchainProofJson } from \"../types/bundle.js\";\nimport type { STH } from \"../types/sth.js\";\nimport { unzipBundle } from \"./unzip.js\";\n\nexport { unzipBundle } from \"./unzip.js\";\n\n/**\n * Per-check result.\n *\n * - Boolean for the four cryptographic checks plus the structural\n *   on-chain check.\n * - Literal `\"skipped\"` for the deliberately-unimplemented TSA step.\n * - Literal `\"absent\"` for the optional `onchain.json` when missing.\n */\nexport interface VerifyChecks {\n  envelope_hash: boolean;\n  issuer_signature: boolean;\n  tsa_tokens: \"skipped\";\n  merkle_inclusion: boolean;\n  master_sth_signature: boolean;\n  onchain_anchor: boolean | \"absent\";\n}\n\nexport interface VerifyResult {\n  /**\n   * `true` iff every PERFORMED check passed. The deliberately-\n   * skipped TSA step is not counted toward `ok`. Callers requiring\n   * full six-of-six verification must run `verify.sh` separately.\n   */\n  ok: boolean;\n  checks: VerifyChecks;\n  /**\n   * The list of explicitly skipped checks. Always contains\n   * `\"tsa_tokens\"` so consumers can present a \"5 of 6 verified\"\n   * disclaimer without re-deriving it.\n   */\n  skipped: ReadonlyArray<keyof VerifyChecks>;\n  /**\n   * Short human-readable explanation when `ok === false`. Names the\n   * first failing check (in declaration order). Absent on success.\n   */\n  reason?: string;\n  /**\n   * On-chain reference, when `onchain.json` was present in the\n   * bundle and structurally valid. Informational only — no RPC was\n   * called. Surfaces so consumers can render the explorer link\n   * without re-parsing the bundle.\n   */\n  onchainReference?: {\n    chain: OnchainProofJson[\"chain\"];\n    contract: string;\n    tx: string;\n    block: number;\n    segment: number;\n    treeSize: number;\n    root: string;\n  };\n}\n\n/** Map of bundle-relative path → file bytes. */\nexport type BundleFiles = Record<string, Uint8Array>;\n\n/**\n * Verify a `.dpiv-bundle` (sans TSA).\n *\n * Accepts either:\n *   - the raw `.dpiv-bundle` zip as `ArrayBuffer | Uint8Array`\n *     (most common — what `client.downloadBundle()` returns),\n *   - or a pre-unzipped `BundleFiles` map (useful for tests and for\n *     callers that already have the bundle in memory).\n *\n * Promise-returning for symmetry with the Python SDK, but the\n * implementation is fully synchronous; awaiting it adds a single\n * microtask.\n */\nexport async function verifyBundle(\n  bundle: ArrayBuffer | Uint8Array | BundleFiles,\n): Promise<VerifyResult> {\n  const files: BundleFiles =\n    bundle instanceof ArrayBuffer\n      ? unzipBundle(bundle).files\n      : bundle instanceof Uint8Array\n        ? unzipBundle(bundle).files\n        : bundle;\n\n  const checks: VerifyChecks = {\n    envelope_hash: false,\n    issuer_signature: false,\n    tsa_tokens: \"skipped\",\n    merkle_inclusion: false,\n    master_sth_signature: false,\n    onchain_anchor: \"absent\",\n  };\n  const skipped: ReadonlyArray<keyof VerifyChecks> = [\"tsa_tokens\"];\n\n  const envelopeBytes = required(files, BUNDLE_FILES.ENVELOPE);\n  const envelopeHashBytes = required(files, BUNDLE_FILES.ENVELOPE_HASH);\n  const signatureBytes = required(files, BUNDLE_FILES.SIGNATURE);\n  const issuerPemBytes = required(files, BUNDLE_FILES.ISSUER_PEM);\n  const merkleBytes = required(files, BUNDLE_FILES.MERKLE);\n  const sthBytes = required(files, BUNDLE_FILES.STH);\n  const masterPemBytes = required(files, BUNDLE_FILES.MASTER_PEM);\n\n  // Check 1 — envelope_hash.\n  const envelope = parseJson<Record<string, unknown>>(\n    envelopeBytes,\n    BUNDLE_FILES.ENVELOPE,\n  );\n  const computedHashHex = sha256Hex(jcs(envelope));\n  const claimedHashHex = bytesToString(envelopeHashBytes).trim().toLowerCase();\n  if (computedHashHex !== claimedHashHex) {\n    return fail(checks, skipped, \"envelope_hash\", \"envelope hash mismatch\");\n  }\n  checks.envelope_hash = true;\n\n  // Check 2 — issuer_signature.\n  // KMS signs the 32-byte digest in DIGEST mode. node:crypto's\n  // createVerify takes the message bytes and does the SHA-256\n  // itself, so we feed the JCS-canonical envelope bytes.\n  let issuerKey: ReturnType<typeof createPublicKey>;\n  try {\n    issuerKey = createPublicKey({\n      key: Buffer.from(issuerPemBytes),\n      format: \"pem\",\n      type: \"spki\",\n    });\n  } catch (err) {\n    return fail(\n      checks,\n      skipped,\n      \"issuer_signature\",\n      `issuer.pem could not be parsed: ${describe(err)}`,\n    );\n  }\n  const v1 = createVerify(\"SHA256\");\n  v1.update(jcs(envelope));\n  v1.end();\n  const issuerOk = v1.verify(issuerKey, Buffer.from(signatureBytes));\n  if (!issuerOk) {\n    return fail(\n      checks,\n      skipped,\n      \"issuer_signature\",\n      \"issuer signature invalid\",\n    );\n  }\n  checks.issuer_signature = true;\n\n  // Check 3 — TSA: deliberately skipped.\n\n  // Check 4 — merkle_inclusion.\n  const merkle = parseJson<MerkleProofJson>(merkleBytes, BUNDLE_FILES.MERKLE);\n  const sth = parseJson<STH & Record<string, unknown>>(\n    sthBytes,\n    BUNDLE_FILES.STH,\n  );\n  if (merkle.segment !== sth.segment) {\n    return fail(\n      checks,\n      skipped,\n      \"merkle_inclusion\",\n      `segment mismatch: merkle=${merkle.segment} sth=${sth.segment}`,\n    );\n  }\n  if (merkle.leaf_index >= sth.tree_size) {\n    return fail(\n      checks,\n      skipped,\n      \"merkle_inclusion\",\n      `leaf_index ${merkle.leaf_index} >= tree_size ${sth.tree_size}`,\n    );\n  }\n  const computedLeafHash = leafHash(Buffer.from(jcs(envelope)));\n  if (computedLeafHash.toString(\"hex\") !== merkle.leaf_hash.toLowerCase()) {\n    return fail(\n      checks,\n      skipped,\n      \"merkle_inclusion\",\n      \"merkle.leaf_hash does not match SHA-256(0x00 || envelope_canonical_bytes)\",\n    );\n  }\n  const auditPath = merkle.audit_path.map((h) => unhex(h));\n  const expectedRoot = unhex(sth.root);\n  const inclusionOk = verifyInclusion(\n    computedLeafHash,\n    merkle.leaf_index,\n    sth.tree_size,\n    auditPath,\n    expectedRoot,\n  );\n  if (!inclusionOk) {\n    return fail(\n      checks,\n      skipped,\n      \"merkle_inclusion\",\n      \"audit_path does not close to sth.root\",\n    );\n  }\n  checks.merkle_inclusion = true;\n\n  // Check 5 — master_sth_signature.\n  const sthForHash: Record<string, unknown> = { ...sth };\n  delete sthForHash.master_sig;\n  delete (sthForHash as Record<string, unknown>).sig;\n  const sthPreimageBytes = Buffer.from(jcs(sthForHash));\n  const masterSigB64 = (sth as { master_sig?: string }).master_sig;\n  if (!masterSigB64) {\n    return fail(\n      checks,\n      skipped,\n      \"master_sth_signature\",\n      \"sth.json missing master_sig\",\n    );\n  }\n  let masterKey: ReturnType<typeof createPublicKey>;\n  try {\n    masterKey = createPublicKey({\n      key: Buffer.from(masterPemBytes),\n      format: \"pem\",\n      type: \"spki\",\n    });\n  } catch (err) {\n    return fail(\n      checks,\n      skipped,\n      \"master_sth_signature\",\n      `master.pem could not be parsed: ${describe(err)}`,\n    );\n  }\n  const v5 = createVerify(\"SHA256\");\n  v5.update(sthPreimageBytes);\n  v5.end();\n  const masterOk = v5.verify(masterKey, Buffer.from(masterSigB64, \"base64\"));\n  if (!masterOk) {\n    return fail(\n      checks,\n      skipped,\n      \"master_sth_signature\",\n      \"chain-master signature on sth.json invalid\",\n    );\n  }\n  checks.master_sth_signature = true;\n\n  // Check 6 — onchain_anchor (informational).\n  const onchainBytes = files[BUNDLE_FILES.ONCHAIN];\n  let onchainReference: VerifyResult[\"onchainReference\"];\n  if (onchainBytes) {\n    const onchain = parseJson<OnchainProofJson>(\n      onchainBytes,\n      BUNDLE_FILES.ONCHAIN,\n    );\n    if (\n      onchain.segment !== sth.segment ||\n      onchain.tree_size !== sth.tree_size ||\n      onchain.root.toLowerCase() !== sth.root.toLowerCase()\n    ) {\n      return fail(\n        checks,\n        skipped,\n        \"onchain_anchor\",\n        \"onchain.json (segment, tree_size, root) does not match sth.json\",\n      );\n    }\n    checks.onchain_anchor = true;\n    onchainReference = {\n      chain: onchain.chain,\n      contract: onchain.contract,\n      tx: onchain.tx,\n      block: onchain.block,\n      segment: onchain.segment,\n      treeSize: onchain.tree_size,\n      root: onchain.root,\n    };\n  } else {\n    checks.onchain_anchor = \"absent\";\n  }\n\n  const result: VerifyResult = { ok: true, checks, skipped };\n  if (onchainReference) result.onchainReference = onchainReference;\n  return result;\n}\n\n/* -------------------------------------------------------------- *\n *  helpers\n * -------------------------------------------------------------- */\n\nfunction required(files: BundleFiles, path: string): Uint8Array {\n  const v = files[path];\n  if (!v) {\n    throw new Error(`bundle missing required file: ${path}`);\n  }\n  return v;\n}\n\nfunction bytesToString(b: Uint8Array): string {\n  return Buffer.from(b).toString(\"utf-8\");\n}\n\nfunction parseJson<T>(b: Uint8Array, label: string): T {\n  try {\n    return JSON.parse(bytesToString(b)) as T;\n  } catch (err) {\n    throw new Error(`${label}: invalid JSON: ${describe(err)}`);\n  }\n}\n\nfunction describe(err: unknown): string {\n  return err instanceof Error ? err.message : String(err);\n}\n\nfunction fail(\n  checks: VerifyChecks,\n  skipped: ReadonlyArray<keyof VerifyChecks>,\n  failedAt: keyof VerifyChecks,\n  reason: string,\n): VerifyResult {\n  return {\n    ok: false,\n    checks,\n    skipped,\n    reason: `${failedAt}: ${reason}`,\n  };\n}\n","/**\n * @deepidv/chain — Node SDK entry point.\n *\n * Public surface for the chain layer at api.proof.deepidv.com:\n *   - typed clients for the public registry API\n *   - typed envelope, STH, and bundle shapes\n *   - canonicalization (JCS) and hashing primitives that are\n *     byte-identical with the Python SDK and the backend\n *   - partial offline bundle verification (5 of 6 checks per\n *     ARCHITECTURE.md §8 D.5; TSA tokens are deliberately skipped)\n *\n * Subpath imports are supported and recommended for tree-shakability:\n *\n *   import { createClient } from \"@deepidv/chain/client\";\n *   import { verifyBundle } from \"@deepidv/chain/verify\";\n *   import { jcs, envelopeHash } from \"@deepidv/chain/crypto\";\n *   import type { AttestationDetail } from \"@deepidv/chain/types\";\n *\n * Or pull everything from the root export.\n */\n\nexport const SDK_VERSION = \"1.1.0\";\n\n// Wire-format types.\nexport type {\n  EnvelopeVersion,\n  SigningAlg,\n  RecordType,\n  LabelCommit,\n  EnvelopeV1,\n  Envelope,\n  STH,\n  MerkleProofJson,\n  OnchainProofJson,\n  RevealedLabel,\n  UnrevealedLabel,\n  BundleLabel,\n  LabelsJson,\n  ManifestEntry,\n  AnchorNetwork,\n  ChainAnchor,\n  RegistryLabelView,\n  RegistryRow,\n  RegistryPage,\n  InclusionView,\n  SthView,\n  AttestationDetail,\n  SthListResponse,\n  SegmentDetail,\n  IssuerDetail,\n  ConsistencyProofResponse,\n  StreamEvent,\n  RegistryListFilters,\n} from \"./types/index.js\";\nexport { isRevealedLabel, BUNDLE_FILES, BUNDLE_SUFFIX } from \"./types/index.js\";\n\n// Errors.\nexport {\n  DeepidvApiError,\n  DeepidvAuthError,\n  DeepidvNotFoundError,\n  DeepidvRateLimitError,\n  DeepidvServerError,\n  DeepidvNetworkError,\n  statusToErrorClass,\n  type DeepidvApiErrorContext,\n} from \"./errors/index.js\";\n\n// Crypto primitives.\nexport {\n  jcs,\n  sha256,\n  sha256Hex,\n  envelopeHash,\n  sthHash,\n  serializeManifest,\n  parseManifest,\n  isValidSha256Hex,\n  leafHash,\n  nodeHash,\n  verifyInclusion,\n  verifyConsistency,\n  hex,\n  unhex,\n} from \"./crypto/index.js\";\n\n// API client.\nexport {\n  createClient,\n  DeepidvChainClient,\n  type ClientOptions,\n  type FetchLike,\n  type RequestOptions,\n} from \"./client/index.js\";\n\n// Bundle verification.\nexport {\n  verifyBundle,\n  unzipBundle,\n  type VerifyResult,\n  type VerifyChecks,\n  type BundleFiles,\n} from \"./verify/index.js\";\n"]}