{"version":3,"file":"resolution-host-BF2oLpxG.mjs","names":[],"sources":["../src/engine/adapters/outbound-url-policy.ts","../src/engine/adapters/safe-get.ts","../src/engine/adapters/resolution-host.ts"],"sourcesContent":["/**\n * Shared egress guard for verifier-owned outbound fetches.\n *\n * KYA-OS payloads are attacker controlled until the signature verifies. Any\n * host-side fetch derived from that payload must reject obvious local/private\n * targets before invoking `fetch`.\n */\n\nconst BLOCKED_HOSTNAMES = new Set(['localhost', 'metadata', 'metadata.google.internal']);\n\nexport class UnsafeOutboundUrl extends Error {\n  readonly kind = 'UnsafeOutboundUrl';\n}\n\nexport function assertSafeHttpsUrl(rawUrl: string, label = 'outbound URL'): string {\n  let parsed: URL;\n  try {\n    parsed = new URL(rawUrl);\n  } catch {\n    throw new UnsafeOutboundUrl(`${label} must be a valid URL: ${rawUrl}`);\n  }\n\n  if (parsed.protocol !== 'https:') {\n    throw new UnsafeOutboundUrl(`${label} must use https: ${rawUrl}`);\n  }\n  if (parsed.username || parsed.password) {\n    throw new UnsafeOutboundUrl(`${label} must not contain credentials: ${rawUrl}`);\n  }\n  // #3331: https on 443 only. `URL` drops an explicit `:443` for https, so\n  // any port left here is a non-default one, which would let a caller-chosen\n  // URL probe arbitrary services on a host.\n  if (parsed.port !== '') {\n    throw new UnsafeOutboundUrl(`${label} must use the default https port 443: ${rawUrl}`);\n  }\n\n  const hostname = normalizeHostname(parsed.hostname);\n  if (!hostname || isBlockedHostname(hostname)) {\n    throw new UnsafeOutboundUrl(`${label} targets a local or private host: ${rawUrl}`);\n  }\n\n  return rawUrl;\n}\n\n/**\n * True when a resolved socket address must not be dialed. The Node transport\n * in `safe-get.ts` calls this at connect time on every address a hostname\n * resolves to. Anything that is not a parseable IP address fails closed.\n */\nexport function isBlockedIpAddress(address: string): boolean {\n  const ipv4 = parseIpv4(address);\n  if (ipv4) return isBlockedIpv4(ipv4);\n  if (!address.includes(':')) return true;\n  try {\n    // Same canonical form `URL` gives an IPv6 literal hostname, which is what\n    // `isBlockedIpv6` expects (a zone id such as `%en0` throws: fail closed).\n    return isBlockedIpv6(normalizeHostname(new URL(`https://[${address}]/`).hostname));\n  } catch {\n    return true;\n  }\n}\n\nfunction normalizeHostname(hostname: string): string {\n  let normalized = hostname.trim().toLowerCase();\n  if (normalized.startsWith('[') && normalized.endsWith(']')) {\n    normalized = normalized.slice(1, -1);\n  }\n  while (normalized.endsWith('.')) {\n    normalized = normalized.slice(0, -1);\n  }\n  return normalized;\n}\n\nfunction isBlockedHostname(hostname: string): boolean {\n  if (BLOCKED_HOSTNAMES.has(hostname) || hostname.endsWith('.localhost')) {\n    return true;\n  }\n\n  const ipv4 = parseIpv4(hostname);\n  if (ipv4) {\n    return isBlockedIpv4(ipv4);\n  }\n\n  return isBlockedIpv6(hostname);\n}\n\nfunction parseIpv4(hostname: string): [number, number, number, number] | null {\n  const parts = hostname.split('.');\n  if (parts.length !== 4) return null;\n\n  const octets = parts.map((part) => {\n    if (!/^\\d{1,3}$/.test(part)) return Number.NaN;\n    const value = Number(part);\n    return value >= 0 && value <= 255 ? value : Number.NaN;\n  });\n\n  if (octets.some(Number.isNaN)) return null;\n  return octets as [number, number, number, number];\n}\n\nfunction isBlockedIpv4([a, b, c]: [number, number, number, number]): boolean {\n  return (\n    a === 0 ||\n    a === 10 ||\n    a === 127 ||\n    (a === 100 && b >= 64 && b <= 127) ||\n    (a === 169 && b === 254) ||\n    (a === 172 && b >= 16 && b <= 31) ||\n    (a === 192 && b === 168) ||\n    (a === 192 && b === 0 && c === 0) || // IETF protocol block; Oracle Cloud metadata 192.0.0.192\n    (a === 198 && (b === 18 || b === 19)) ||\n    a >= 224\n  );\n}\n\nfunction isBlockedIpv6(hostname: string): boolean {\n  if (!hostname.includes(':')) return false;\n\n  // Expand to the 8 16-bit groups so every textual encoding of the same\n  // address (dotted-quad tail, compressed hex pairs, fully expanded) is\n  // judged identically. `URL` itself canonicalizes IPv6 literals to the\n  // compressed hex-pair form (`::ffff:127.0.0.1` becomes `::ffff:7f00:1`)\n  // before this function ever runs, so checking only the dotted textual\n  // form here would never actually fire.\n  const groups = expandIpv6Groups(hostname);\n\n  // IPv4-mapped (::ffff:a.b.c.d) and the deprecated IPv4-compatible\n  // (::a.b.c.d) forms both embed an IPv4 address in the low 32 bits.\n  const top5Zero = groups.slice(0, 5).every((g) => g === 0);\n  if (top5Zero && groups[5] === 0xffff) {\n    return isBlockedIpv4(groupPairToIpv4(groups[6], groups[7]));\n  }\n  if (top5Zero && groups[5] === 0) {\n    // This also rejects :: and ::1 through the existing IPv4 zero-network rule.\n    return isBlockedIpv4(groupPairToIpv4(groups[6], groups[7]));\n  }\n\n  // NAT64 (RFC 6052, 64:ff9b::/96): top 96 bits fixed at\n  // 0064:ff9b:0000:0000:0000:0000, last 32 bits are the embedded IPv4 (e.g.\n  // 64:ff9b::a9fe:a9fe embeds the AWS/GCP/Azure IMDS address\n  // 169.254.169.254). Standard on IPv6-only / DNS64+NAT64 cloud subnets, so\n  // this is a live cloud-metadata SSRF vector, not a theoretical one. Groups\n  // are already fully expanded above, so every compression an attacker's\n  // textual encoding could use collapses to the same check here.\n  if (\n    groups[0] === 0x64 &&\n    groups[1] === 0xff9b &&\n    groups[2] === 0 &&\n    groups[3] === 0 &&\n    groups[4] === 0 &&\n    groups[5] === 0\n  ) {\n    return isBlockedIpv4(groupPairToIpv4(groups[6], groups[7]));\n  }\n\n  // Local-use NAT64 (RFC 8215, 64:ff9b:1::/48): a site's own translator, so\n  // never a public destination. Where the IPv4 sits depends on the prefix\n  // length the site picked (RFC 6052 layouts), so block the whole /48.\n  if (groups[0] === 0x64 && groups[1] === 0xff9b && groups[2] === 1) {\n    return true;\n  }\n\n  // 6to4 (RFC 3056, 2002::/16): groups 1-2 embed the IPv4 A.B.C.D\n  // (group1 = A<<8|B, group2 = C<<8|D). Unlike NAT64/mapped above, groups\n  // 3-7 (SLA ID + interface ID) are attacker- or router-arbitrary, not fixed\n  // at zero, so this checks group[0] alone rather than assuming any\n  // particular trailing shape.\n  if (groups[0] === 0x2002) {\n    return isBlockedIpv4(groupPairToIpv4(groups[1], groups[2]));\n  }\n\n  const firstSegment = groups[0];\n  return (\n    (firstSegment & 0xfe00) === 0xfc00 || // unique local fc00::/7\n    (firstSegment & 0xffc0) === 0xfe80 || // link-local fe80::/10\n    (firstSegment & 0xff00) === 0xff00 // multicast ff00::/8\n  );\n}\n\n/** Splits a pair of 16-bit IPv6 groups into the 4 octets of their embedded IPv4 address. */\nfunction groupPairToIpv4(hi: number, lo: number): [number, number, number, number] {\n  return [(hi >> 8) & 0xff, hi & 0xff, (lo >> 8) & 0xff, lo & 0xff];\n}\n\n/**\n * Expands the canonical IPv6 hostname produced by `URL` into its 8 16-bit\n * groups. The URL parser rejects malformed literals and converts mixed\n * dotted-quad tails to hexadecimal groups before this function runs.\n */\nfunction expandIpv6Groups(hostname: string): number[] {\n  const halves = hostname.split('::');\n  const parseGroups = (segment: string): number[] =>\n    segment === '' ? [] : segment.split(':').map((part) => Number.parseInt(part, 16));\n\n  if (halves.length === 1) return parseGroups(halves[0]);\n\n  const left = parseGroups(halves[0]);\n  const right = parseGroups(halves[1]);\n  const zeroGroups = new Array(8 - left.length - right.length).fill(0);\n  return [...left, ...zeroGroups, ...right];\n}\n","/**\n * Hardened GET for verifier-owned fetches whose URL comes from an\n * attacker-presented request: the did:web document and the status list\n * (#3331). The caller has already passed the URL through `assertSafeHttpsUrl`.\n *\n * - No redirects. Any 3xx is refused: its `Location` was never checked.\n * - The body is capped at `maxBytes`. The read stops as soon as it goes over.\n *   On Node the body is decoded per Content-Encoding first (gzip, deflate,\n *   br), as `fetch` does, and the cap counts decoded bytes.\n * - On Node, the socket only ever connects to an address `isBlockedIpAddress`\n *   accepted: `https.get` runs every A/AAAA answer through a custom `lookup`\n *   and connects to the address that lookup returned. A public-looking\n *   hostname that resolves (or re-resolves, DNS rebinding) to a private,\n *   loopback, link-local, CGNAT or metadata address is refused.\n * - Edge runtimes, Workers, Bun and Deno expose no connect hook, so there the\n *   DNS step is skipped and global `fetch` runs with the other rules. They\n *   are recognized by markers a Node host does not carry. Anything else with\n *   `process.versions.node` is Node, where the check is mandatory: Node\n *   without `process.getBuiltinModule` (before 20.16 / 22.3) is refused\n *   rather than silently fetched without it.\n *\n * Node modules are reached through `process.getBuiltinModule`, never a\n * static import, so the runtime-agnostic `adapters` entry stays loadable on\n * Edge and in Workers (see `rdns-verifier.ts` for the same constraint).\n */\n\nimport type { LookupAddress, LookupOptions } from 'node:dns';\nimport type * as NodeDns from 'node:dns';\nimport type * as NodeHttps from 'node:https';\nimport type * as NodeZlib from 'node:zlib';\n\nimport { isBlockedIpAddress } from './outbound-url-policy';\n\n/** Why `safeGet` refused a fetch. */\nexport type SafeGetRefusal =\n  | 'redirect'\n  | 'too-large'\n  | 'blocked-address'\n  | 'no-address'\n  | 'content-encoding'\n  | 'no-address-check';\n\n/** A redirect, an oversized body, or a blocked address. */\nexport class SafeGetRefused extends Error {\n  readonly kind = 'SafeGetRefused';\n\n  constructor(\n    message: string,\n    readonly reason: SafeGetRefusal\n  ) {\n    super(message);\n  }\n}\n\nexport interface SafeGetResponse {\n  status: number;\n  /** The body for a 2xx; empty for any other status (never read). */\n  body: Uint8Array;\n}\n\nexport interface SafeGetOpts {\n  /** Bounds the whole exchange: connect, headers and body. */\n  signal: AbortSignal;\n  maxBytes: number;\n  /**\n   * A caller-supplied `fetch` is used as-is (with `redirect: 'manual'`, the\n   * size cap and `SAFE_GET_HEADERS`); connect-time address checks are then\n   * the caller's job.\n   */\n  fetch?: typeof fetch;\n}\n\n// Sent on every transport, so a did:web or status-list host sees the same\n// request from Node, Edge and Workers. `https.get` sends no User-Agent or\n// Accept of its own (undici's `fetch` sent `node` and `*/*`), and a WAF or bot\n// filter that refuses a header-less request would otherwise 403 on Node only.\n// Accept still ends in `*/*`, so no host that served the old fetch answers 406.\n// No version and nothing about the operator: one fixed, public identity.\nexport const SAFE_GET_HEADERS: Readonly<Record<'user-agent' | 'accept', string>> = Object.freeze({\n  'user-agent': 'kya-checkpoint-resolver (+https://github.com/Know-That-Ai/checkpoint)',\n  accept: 'application/json, */*;q=0.8',\n});\n\nconst EMPTY = new Uint8Array(0);\n\nexport async function safeGet(url: string, opts: SafeGetOpts): Promise<SafeGetResponse> {\n  try {\n    if (opts.fetch) return await fetchGet(url, opts.fetch, opts);\n    const transport = pickTransport();\n    if (transport === 'fetch') return await fetchGet(url, fetch, opts);\n    if (transport === 'unchecked-node') {\n      warnUncheckedNodeOnce();\n      throw new SafeGetRefused(\n        `refused ${url}: this Node has no process.getBuiltinModule, ` +\n          'so the connect-time address check cannot run; upgrade to Node 20.19+ or 22.12+ or pass your own fetch',\n        'no-address-check'\n      );\n    }\n    return await nodeGet(url, transport, opts);\n  } catch (cause) {\n    // One error shape for \"ran out of time\", whichever layer noticed first.\n    if (opts.signal.aborted && !(cause instanceof SafeGetRefused)) throw abortError(url);\n    throw cause;\n  }\n}\n\nfunction abortError(url: string): Error {\n  const err = new Error(`request aborted: ${url}`);\n  err.name = 'AbortError';\n  return err;\n}\n\nfunction tooLarge(url: string, maxBytes: number): SafeGetRefused {\n  return new SafeGetRefused(`response body exceeds ${maxBytes} bytes: ${url}`, 'too-large');\n}\n\n// -----------------------------------------------------------------------------\n// fetch transport (Edge, Workers, injected fetch).\n// -----------------------------------------------------------------------------\n\nasync function fetchGet(\n  url: string,\n  fetchImpl: typeof fetch,\n  { signal, maxBytes }: SafeGetOpts\n): Promise<SafeGetResponse> {\n  // 'manual', not 'error': Cloudflare Workers reject `redirect: 'error'`.\n  const response = await fetchImpl(url, {\n    signal,\n    redirect: 'manual',\n    headers: { ...SAFE_GET_HEADERS },\n  });\n  // An opaque redirect (browsers, some edge runtimes) reports status 0.\n  if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) {\n    await response.body?.cancel().catch(() => {});\n    throw new SafeGetRefused(`redirect refused (HTTP ${response.status}): ${url}`, 'redirect');\n  }\n  if (!response.ok) {\n    await response.body?.cancel().catch(() => {});\n    return { status: response.status, body: EMPTY };\n  }\n  if (Number(response.headers.get('content-length')) > maxBytes) {\n    await response.body?.cancel().catch(() => {});\n    throw tooLarge(url, maxBytes);\n  }\n  return { status: response.status, body: await readCapped(response, url, signal, maxBytes) };\n}\n\n/**\n * Reads the body through a stream reader so the read can stop at `maxBytes`\n * and so an abort settles a pending `read()` (a body that drips forever).\n */\nasync function readCapped(\n  response: Response,\n  url: string,\n  signal: AbortSignal,\n  maxBytes: number\n): Promise<Uint8Array> {\n  if (!response.body) {\n    // A runtime (or test double) without a streaming body.\n    const whole = new Uint8Array(await response.arrayBuffer());\n    if (whole.byteLength > maxBytes) throw tooLarge(url, maxBytes);\n    return whole;\n  }\n  const reader = response.body.getReader();\n  if (signal.aborted) {\n    await reader.cancel().catch(() => {});\n    throw abortError(url);\n  }\n  let aborted = false;\n  const onAbort = (): void => {\n    aborted = true;\n    reader.cancel().catch(() => {});\n  };\n  signal.addEventListener('abort', onAbort);\n  try {\n    const chunks: Uint8Array[] = [];\n    let total = 0;\n    for (;;) {\n      const { done, value } = await reader.read();\n      if (aborted) throw abortError(url);\n      if (done) break;\n      total += value.byteLength;\n      if (total > maxBytes) {\n        await reader.cancel().catch(() => {});\n        throw tooLarge(url, maxBytes);\n      }\n      chunks.push(value);\n    }\n    return concat(chunks, total);\n  } finally {\n    signal.removeEventListener('abort', onAbort);\n  }\n}\n\nfunction concat(chunks: Uint8Array[], total: number): Uint8Array {\n  const out = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    out.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return out;\n}\n\n// -----------------------------------------------------------------------------\n// Node transport: `https.get` with a lookup that refuses blocked addresses.\n// -----------------------------------------------------------------------------\n\ninterface NodeNetModules {\n  https: typeof NodeHttps;\n  dns: typeof NodeDns;\n  zlib: typeof NodeZlib;\n}\n\ntype LookupCallback = (\n  err: NodeJS.ErrnoException | null,\n  address: string | LookupAddress[],\n  family?: number\n) => void;\n\ninterface RuntimeGlobals {\n  process?: {\n    versions?: { node?: unknown; bun?: unknown };\n    getBuiltinModule?: (id: string) => unknown;\n  };\n  navigator?: { userAgent?: unknown };\n  EdgeRuntime?: unknown;\n  Deno?: unknown;\n}\n\n/**\n * Which transport this runtime gets. Non-Node runtimes are matched on\n * markers a Node host does not carry (not on a missing or odd\n * `navigator.userAgent`, which jsdom or a polyfill can set on Node), so a\n * Node host never falls through to an unchecked fetch.\n */\nfunction pickTransport(): NodeNetModules | 'fetch' | 'unchecked-node' {\n  const runtime = globalThis as RuntimeGlobals;\n  const proc = runtime.process;\n  // Workers (nodejs_compat), Bun and Deno expose `process.versions.node` and\n  // `getBuiltinModule` too, but their `node:https` has no connect-time lookup.\n  if (\n    runtime.navigator?.userAgent === 'Cloudflare-Workers' ||\n    typeof runtime.EdgeRuntime === 'string' ||\n    runtime.Deno !== undefined ||\n    proc?.versions?.bun !== undefined ||\n    typeof proc?.versions?.node !== 'string'\n  ) {\n    return 'fetch';\n  }\n  if (typeof proc.getBuiltinModule !== 'function') return 'unchecked-node';\n  const https = proc.getBuiltinModule('node:https') as typeof NodeHttps | undefined;\n  const dns = proc.getBuiltinModule('node:dns') as typeof NodeDns | undefined;\n  const zlib = proc.getBuiltinModule('node:zlib') as typeof NodeZlib | undefined;\n  return https && dns && zlib ? { https, dns, zlib } : 'unchecked-node';\n}\n\n// On `globalThis` under a registered symbol so the CJS and ESM builds (or a\n// duplicate copy of the package) share it: one warning per process.\nconst UNCHECKED_NODE_WARNED = Symbol.for('kya.safeGet.uncheckedNodeWarned');\n\n/**\n * Every did:web and status-list fetch on this host is about to be refused\n * (and each request carrying one answered 503 or blocked). Say why once, so\n * an operator on old Node sees the cause instead of a wall of 503s.\n */\nfunction warnUncheckedNodeOnce(): void {\n  const registry = globalThis as { [UNCHECKED_NODE_WARNED]?: boolean };\n  if (registry[UNCHECKED_NODE_WARNED]) return;\n  registry[UNCHECKED_NODE_WARNED] = true;\n  const version = (globalThis as { process?: { version?: unknown } }).process?.version;\n  console.warn(\n    `[checkpoint] Node ${String(version)} has no process.getBuiltinModule, so the ` +\n      'connect-time address check cannot run: did:web and status-list fetches are refused. ' +\n      'Upgrade to Node 20.19+ or 22.12+, or pass your own fetch to makeResolutionHost.'\n  );\n}\n\n/**\n * Wraps `dns.lookup` so the socket can only connect to checked addresses.\n * One blocked answer refuses the whole host (as the .NET SDK's\n * `SsrfSafeDidFetcher` does), so a mixed public/private record set cannot\n * win a Happy Eyeballs race to the private one.\n */\nexport function makeSafeLookup(lookup: typeof NodeDns.lookup) {\n  return (hostname: string, options: LookupOptions, callback: LookupCallback): void => {\n    lookup(hostname, { ...options, all: true }, (err, addresses) => {\n      if (err) {\n        callback(err, '');\n        return;\n      }\n      const blocked = addresses.find((entry) => isBlockedIpAddress(entry.address));\n      if (blocked || addresses.length === 0) {\n        callback(\n          new SafeGetRefused(\n            `${hostname} resolves to ${blocked ? `blocked address ${blocked.address}` : 'no address'}`,\n            blocked ? 'blocked-address' : 'no-address'\n          ),\n          ''\n        );\n        return;\n      }\n      if (options.all) callback(null, addresses);\n      else callback(null, addresses[0].address, addresses[0].family);\n    });\n  };\n}\n\n/**\n * `https.get` hands back the bytes as sent, while global `fetch` decodes\n * Content-Encoding. A did.json or status list stored gzipped (S3 object\n * metadata, a precompressed CDN object) is sent that way whatever the request\n * asked for, so the Node path decodes the codings fetch decodes. Anything\n * else (an unknown coding, or a stack of them) is refused rather than handed\n * to JSON.parse as bytes.\n */\nfunction makeDecoder(\n  contentEncoding: string | undefined,\n  zlib: typeof NodeZlib,\n  url: string\n): NodeZlib.Gunzip | NodeZlib.Inflate | NodeZlib.BrotliDecompress | null {\n  const coding = (contentEncoding ?? '').trim().toLowerCase();\n  if (coding === '' || coding === 'identity') return null;\n  if (coding === 'gzip' || coding === 'x-gzip') return zlib.createGunzip();\n  if (coding === 'deflate') return zlib.createInflate();\n  if (coding === 'br') return zlib.createBrotliDecompress();\n  throw new SafeGetRefused(`unsupported content-encoding \"${coding}\": ${url}`, 'content-encoding');\n}\n\nfunction nodeGet(\n  url: string,\n  { https, dns, zlib }: NodeNetModules,\n  { signal, maxBytes }: SafeGetOpts\n): Promise<SafeGetResponse> {\n  return new Promise((resolve, reject) => {\n    // `agent: false`: a fresh socket every time, so a pooled socket some\n    // other caller opened without this lookup is never reused.\n    const request = https.get(\n      url,\n      {\n        agent: false,\n        signal,\n        lookup: makeSafeLookup(dns.lookup),\n        headers: { ...SAFE_GET_HEADERS },\n      },\n      (response) => {\n        const status = response.statusCode ?? 0;\n        let decoder: ReturnType<typeof makeDecoder> = null;\n        const refuse = (err: Error): void => {\n          response.destroy();\n          decoder?.destroy();\n          reject(err);\n        };\n        if (status >= 300 && status < 400) {\n          refuse(new SafeGetRefused(`redirect refused (HTTP ${status}): ${url}`, 'redirect'));\n          return;\n        }\n        if (status < 200 || status >= 300) {\n          response.destroy();\n          resolve({ status, body: EMPTY });\n          return;\n        }\n        if (Number(response.headers['content-length']) > maxBytes) {\n          refuse(tooLarge(url, maxBytes));\n          return;\n        }\n        try {\n          decoder = makeDecoder(response.headers['content-encoding'], zlib, url);\n        } catch (err) {\n          refuse(err as Error);\n          return;\n        }\n        // The cap counts decoded bytes, as on the fetch path, so a\n        // compression bomb stops at `maxBytes`.\n        const body = decoder ? response.pipe(decoder) : response;\n        const chunks: Uint8Array[] = [];\n        let total = 0;\n        body.on('data', (chunk: Uint8Array) => {\n          total += chunk.byteLength;\n          if (total > maxBytes) {\n            refuse(tooLarge(url, maxBytes));\n            return;\n          }\n          chunks.push(chunk);\n        });\n        body.on('end', () => resolve({ status, body: concat(chunks, total) }));\n        response.on('error', refuse);\n        decoder?.on('error', refuse);\n      }\n    );\n    request.on('error', reject);\n  });\n}\n","/**\n * The host side of engine-directed resolution: answers the DID documents and\n * status lists the engine names (`Need`), from a cache keyed by need key.\n *\n * The engine owns every trust and freshness rule. This module only fetches\n * what was named, keeps the answers, and reports one outcome per need:\n *\n * - a fetched DID document (`body`, `fetchedAtUnix`, `lastRefreshFailed`);\n * - a status list, verified once per fetch with the engine's\n *   `verifyStatusList` against its issuer's cached DID document;\n * - `pending` until the first fetch attempt for a key has finished;\n * - after that, `failed` with the attempt's reason until a fetch succeeds.\n *\n * Two modes:\n *\n * - `inline`: a miss, or an entry past its maximum age, is fetched before\n *   the answer, within the fetch budget.\n * - `cache-only`: the request path never waits on a fetch. A miss is answered\n *   `pending` and starts a background fetch, so the client's retry after\n *   `kyaos/identity-pending` (503, `Retry-After: 1`) usually finds it; the\n *   owner's `refresh` tick keeps every entry fresh.\n *\n * A host with no memory shared between requests (a Worker isolate) passes a\n * `store`: a fetched DID document or status list is put there as its raw\n * bytes and its fetch time, and an entry this host has never tried is read\n * from it before anything is fetched, so a cold host answers what another\n * already fetched. In cache-only mode an entry past its refresh point, or a\n * failure past the retry wait, is refreshed in the background (the store\n * first, then a fetch), so a host with no `refresh` tick of its own still\n * keeps the entries it is asked for fresh. Background work goes to the\n * caller's `waitUntil` when it passes one.\n *\n * Entries are kept by role, because a request chooses which presenter DIDs it\n * names. Configured roots are pinned. Issuer status lists and presenter DID\n * documents each live in their own bounded table, least recently named\n * evicted first, with a fetch budget per window, so request-chosen DIDs can\n * displace only other presenters and add only a bounded number of fetches.\n *\n * Fetches go through `safeGet`: no redirects, the need's byte cap, a\n * deadline, and on Node a socket that connects only to an address its lookup\n * checked. A caller-supplied `fetch` replaces that transport, and with it the\n * connect-time address check: it must connect only to a vetted public\n * address, refuse redirects, cap the body and enforce a deadline. Edge\n * runtimes and Workers have no connect hook, so there the platform's egress\n * rules are what keep a fetch off private addresses.\n */\n\nimport type {\n  Need,\n  NeedRole,\n  ResourceFailureDetail,\n  ResourceOutcome,\n  StatusListRecord,\n} from '../types';\nimport { assertSafeHttpsUrl, UnsafeOutboundUrl } from './outbound-url-policy';\nimport { safeGet, SafeGetRefused } from './safe-get';\nimport type { StatusListVerifier } from './status-list-cache';\n\n/** One fetch's deadline: connect, headers and body. */\nexport const RESOLUTION_FETCH_TIMEOUT_MS = 3_000;\n/** The window the per-role fetch budget counts in. */\nexport const RESOLUTION_BUDGET_WINDOW_MS = 10_000;\n/** Fetches per window for each request-chosen role. Roots are not budgeted. */\nexport const RESOLUTION_FETCH_BUDGET: Readonly<Record<'issuer' | 'presenter', number>> =\n  Object.freeze({ issuer: 32, presenter: 16 });\n/** Largest number of entries kept for each request-chosen role. */\nexport const RESOLUTION_MAX_ENTRIES: Readonly<Record<'issuer' | 'presenter', number>> =\n  Object.freeze({ issuer: 1024, presenter: 1024 });\n/** A non-root entry is refreshed in the background while it was named this recently. */\nexport const RESOLUTION_ACTIVE_MS = 900_000;\n/** After a failed fetch, an entry is tried again after this long. */\nexport const RESOLUTION_RETRY_MS = 30_000;\n/** The background refresh fetches an entry this far ahead of its maximum age. */\nexport const RESOLUTION_REFRESH_LEAD_MS = 35_000;\n/** A non-root entry no request named for this long is dropped. */\nexport const RESOLUTION_INACTIVE_EVICT_MS = 86_400_000;\n/** Background fetches in flight at once. */\nexport const RESOLUTION_MAX_CONCURRENT_FETCHES = 4;\n\ntype Freshness = 'stale' | 'refresh';\n\n/**\n * Milliseconds after its fetch at which the background refresh fetches an\n * entry again: half its maximum age, or `RESOLUTION_REFRESH_LEAD_MS` before\n * it, whichever is sooner, and never under a second.\n */\nexport function refreshAfterMs(maxAgeSeconds: number): number {\n  const leadSeconds = RESOLUTION_REFRESH_LEAD_MS / 1000;\n  return Math.max(1, Math.min(maxAgeSeconds / 2, maxAgeSeconds - leadSeconds)) * 1000;\n}\n\n/** The engine call a host needs to answer a status-list need. */\nexport interface ResolutionEngine {\n  verifyStatusList: StatusListVerifier;\n}\n\nexport type ResolutionMode = 'inline' | 'cache-only';\n\n/** A fetched resource as a store keeps it: the raw body and when it was fetched. */\nexport interface StoredResource {\n  /** The response body: a DID document's JSON, or a status list's envelope. */\n  body: string;\n  /** Epoch seconds of the fetch that produced `body`. */\n  fetchedAtUnix: number;\n}\n\n/**\n * Persistent storage for fetched resources, keyed by need key, for a host\n * that keeps no memory between requests. A `get` that throws counts as a\n * miss and a `put` that throws is logged; neither fails a request.\n */\nexport interface ResolutionStore {\n  get(key: string): Promise<StoredResource | null>;\n  put(key: string, value: StoredResource): Promise<void>;\n}\n\nexport interface ResolutionHostOptions {\n  mode: ResolutionMode;\n  /**\n   * Replaces `safeGet`'s transport. It must connect only to a vetted public\n   * address, refuse redirects, cap the body and enforce a deadline; the\n   * connect-time address check is then the caller's job.\n   */\n  fetch?: typeof fetch;\n  /** Epoch milliseconds. Defaults to `Date.now`. */\n  now?: () => number;\n  fetchTimeoutMs?: number;\n  logger?: (msg: string) => void;\n  /** Where fetched resources are kept between requests. See {@link ResolutionStore}. */\n  store?: ResolutionStore;\n}\n\n/**\n * The verification a host answers for. The engine judges every answer with the\n * verify call's clock (`opts.clock`), which need not be the host's: a replay or\n * a conformance run pins it to an instant of its own. So what the host hands\n * the engine is in that clock: a resource's fetch time is the call's `nowUnix`\n * less the resource's real age, and a status list fetched for the call is\n * verified, and its expiry judged, at the call's `nowUnix`. The host's own\n * timing (retry delays, budgets, refresh points) stays on its clock.\n */\nexport interface ResolutionCall {\n  /** The `nowUnix` the engine is called with for this request. */\n  nowUnix: number;\n  /**\n   * Keeps the call's background work alive after the response (Cloudflare\n   * Workers' `ctx.waitUntil`). Without it, background fetches run detached.\n   */\n  waitUntil?: (promise: Promise<unknown>) => void;\n}\n\nexport interface ResolutionHost {\n  readonly mode: ResolutionMode;\n  /**\n   * The answers already held for configured roots that an engine would\n   * accept, to send with a request's first call so a request that needs only\n   * roots is decided in one call. Without `call`, in the host's clock.\n   */\n  rootAnswers(call?: ResolutionCall): Record<string, ResourceOutcome>;\n  /**\n   * One outcome per need, from the cache, a fetch, or `pending`. Never throws.\n   * Without `call`, in the host's clock.\n   */\n  answer(\n    needs: readonly Need[],\n    engine: ResolutionEngine,\n    call?: ResolutionCall\n  ): Promise<Record<string, ResourceOutcome>>;\n  /** Track needs without answering them (the configured roots at startup). */\n  register(needs: readonly Need[]): void;\n  /** Keep only these root needs pinned; a root no longer configured is dropped. */\n  setRoots(needs: readonly Need[]): void;\n  /**\n   * Fetch every tracked need that is due, DID documents before status lists,\n   * within the budgets, reading the store first when there is one. Never\n   * throws.\n   */\n  refresh(engine: ResolutionEngine): Promise<void>;\n}\n\ninterface Entry {\n  key: string;\n  need: Need;\n  role: NeedRole;\n  body?: string;\n  record?: StatusListRecord;\n  /** Epoch ms of the latest successful fetch. */\n  fetchedAt?: number;\n  lastRefreshFailed: boolean;\n  /** The latest attempt's failure, cleared by a success. */\n  failure?: ResourceFailureDetail;\n  /** Epoch ms the latest attempt finished. */\n  attemptedAt?: number;\n  inFlight?: Promise<void>;\n  /** The store read in progress for this entry, shared by concurrent callers. */\n  storeRead?: Promise<boolean>;\n  /**\n   * Epoch ms the latest store read finished. The store is read again for this\n   * entry only `RESOLUTION_RETRY_MS` later, so a key the store does not hold\n   * (and the fetch budget skipped) costs one read per wait, not one per request.\n   */\n  storeReadAt?: number;\n  /** Epoch ms a request last named this entry. */\n  namedAt: number;\n}\n\nexport function makeResolutionHost(options: ResolutionHostOptions): ResolutionHost {\n  const now = options.now ?? (() => Date.now());\n  const timeoutMs = options.fetchTimeoutMs ?? RESOLUTION_FETCH_TIMEOUT_MS;\n  const log = options.logger ?? (() => {});\n  const tables: Record<NeedRole, Map<string, Entry>> = {\n    root: new Map(),\n    issuer: new Map(),\n    presenter: new Map(),\n  };\n  let windowStart = Number.NEGATIVE_INFINITY;\n  const spent: Record<'issuer' | 'presenter', number> = { issuer: 0, presenter: 0 };\n\n  function find(key: string): Entry | undefined {\n    return tables.root.get(key) ?? tables.issuer.get(key) ?? tables.presenter.get(key);\n  }\n\n  /** The entry for `need`, created or moved to its role's table and marked named. */\n  function track(need: Need, named: boolean): Entry {\n    const at = now();\n    let entry = find(need.key);\n    if (entry && entry.role !== need.role && (need.role === 'root' || entry.role !== 'root')) {\n      tables[entry.role].delete(entry.key);\n      entry.role = need.role;\n    }\n    if (!entry) {\n      entry = { key: need.key, need, role: need.role, lastRefreshFailed: false, namedAt: at };\n    }\n    entry.need = need;\n    if (named) entry.namedAt = at;\n    const table = tables[entry.role];\n    // Re-inserting moves the key to the end: Map order is least recently named first.\n    table.delete(entry.key);\n    table.set(entry.key, entry);\n    if (entry.role !== 'root') evictOver(entry.role);\n    return entry;\n  }\n\n  function evictOver(role: 'issuer' | 'presenter'): void {\n    const table = tables[role];\n    for (const victim of table.values()) {\n      if (table.size <= RESOLUTION_MAX_ENTRIES[role]) return;\n      if (!victim.inFlight) table.delete(victim.key);\n    }\n  }\n\n  function spend(role: NeedRole): boolean {\n    if (role === 'root') return true;\n    const at = now();\n    if (at < windowStart || at - windowStart >= RESOLUTION_BUDGET_WINDOW_MS) {\n      windowStart = at;\n      spent.issuer = 0;\n      spent.presenter = 0;\n    }\n    if (spent[role] >= RESOLUTION_FETCH_BUDGET[role]) return false;\n    spent[role] += 1;\n    return true;\n  }\n\n  function ageMs(entry: Entry): number {\n    return entry.fetchedAt === undefined ? Number.POSITIVE_INFINITY : now() - entry.fetchedAt;\n  }\n\n  /** The `nowUnix` the engine judges with: the call's, else the host's. */\n  function engineNowUnix(call: ResolutionCall | undefined): number {\n    return call?.nowUnix ?? Math.floor(now() / 1000);\n  }\n\n  /**\n   * Whether `entry` holds a resource younger than `when` allows: `stale`, the\n   * need's maximum age (what the engine accepts), or `refresh`, the instant the\n   * background refresh fetches it again.\n   */\n  function isFresh(entry: Entry, when: Freshness = 'stale', call?: ResolutionCall): boolean {\n    if (entry.body === undefined && entry.record === undefined) return false;\n    const limitMs =\n      when === 'stale' ? entry.need.maxAgeSeconds * 1000 : refreshAfterMs(entry.need.maxAgeSeconds);\n    if (ageMs(entry) >= limitMs) return false;\n    // A list's own expiry is an instant the engine checks in its clock.\n    return entry.record === undefined || entry.record.expiresAt > engineNowUnix(call);\n  }\n\n  /** Whether a fetch of `entry` should start now. */\n  function isDue(entry: Entry, when: Freshness, call?: ResolutionCall): boolean {\n    if (entry.inFlight) return false;\n    if (entry.attemptedAt === undefined) return true;\n    if (isFresh(entry, when, call)) return false;\n    // Past its age or never fetched: a failed attempt waits before the next.\n    return entry.failure === undefined || now() - entry.attemptedAt >= RESOLUTION_RETRY_MS;\n  }\n\n  function outcomeOf(entry: Entry, call?: ResolutionCall): ResourceOutcome {\n    // The fetch time in the engine's clock: its real age, back from `nowUnix`.\n    const fetchedAtUnix =\n      entry.fetchedAt === undefined\n        ? 0\n        : call\n          ? call.nowUnix - Math.floor(ageMs(entry) / 1000)\n          : Math.floor(entry.fetchedAt / 1000);\n    if (entry.body !== undefined) {\n      return {\n        ok: true,\n        body: entry.body,\n        fetchedAtUnix,\n        lastRefreshFailed: entry.lastRefreshFailed,\n      };\n    }\n    // A status list is never used past its maximum age, so a failed refresh\n    // of a stale list answers the failure.\n    if (\n      entry.record !== undefined &&\n      (entry.failure === undefined || isFresh(entry, 'stale', call))\n    ) {\n      return { ok: true, record: entry.record, fetchedAtUnix };\n    }\n    if (entry.failure !== undefined) return { ok: false, reason: 'failed', detail: entry.failure };\n    return { ok: false, reason: 'pending' };\n  }\n\n  /** The entries tracking `did`'s DID document, in whichever role holds it. */\n  function documentEntries(did: string | undefined): Entry[] {\n    if (!did) return [];\n    const found: Entry[] = [];\n    for (const table of Object.values(tables)) {\n      for (const entry of table.values()) {\n        if (entry.need.kind === 'did-document' && entry.need.did === did) found.push(entry);\n      }\n    }\n    return found;\n  }\n\n  /** The cached body of `did`'s DID document, from whichever role holds it. */\n  function documentBody(did: string | undefined): string | null {\n    return documentEntries(did).find((entry) => entry.body !== undefined)?.body ?? null;\n  }\n\n  function start(entry: Entry, engine: ResolutionEngine, call?: ResolutionCall): Promise<void> {\n    if (entry.inFlight) return entry.inFlight;\n    const run = (async () => {\n      try {\n        if (entry.need.kind === 'did-document') {\n          const body = await fetchText(entry.need, options.fetch, timeoutMs);\n          entry.body = body;\n          entry.fetchedAt = now();\n          entry.lastRefreshFailed = false;\n          entry.failure = undefined;\n          await persist(entry, body);\n        } else {\n          const envelope = await fetchText(entry.need, options.fetch, timeoutMs);\n          entry.record = await verifyStatusListEnvelope(\n            entry.need,\n            envelope,\n            documentBody(entry.need.issuer),\n            engine,\n            engineNowUnix(call)\n          );\n          entry.fetchedAt = now();\n          entry.failure = undefined;\n          await persist(entry, envelope);\n        }\n      } catch (cause) {\n        const detail = failureDetail(cause);\n        entry.failure = detail;\n        entry.lastRefreshFailed = entry.body !== undefined;\n        log(\n          `[checkpoint] resolution fetch failed (${detail}): ${entry.need.url}: ${String(cause)}`\n        );\n      } finally {\n        entry.attemptedAt = now();\n        entry.inFlight = undefined;\n      }\n    })();\n    entry.inFlight = run;\n    return run;\n  }\n\n  /** Put a fetched resource in the store, with the fetch's own time. */\n  async function persist(entry: Entry, body: string): Promise<void> {\n    if (!options.store || entry.fetchedAt === undefined) return;\n    try {\n      await options.store.put(entry.key, {\n        body,\n        fetchedAtUnix: Math.floor(entry.fetchedAt / 1000),\n      });\n    } catch (cause) {\n      log(`[checkpoint] resolution store put failed: ${entry.need.url}: ${String(cause)}`);\n    }\n  }\n\n  /**\n   * Take a stored resource for `entry` when it was fetched after what the\n   * entry holds. A stored status list is verified again first, at the call's\n   * `nowUnix`, against its issuer's document, and not used when the engine\n   * rejects it or the issuer has no document yet. The stored fetch time is\n   * the host's clock, like the entry's.\n   */\n  async function adopt(\n    entry: Entry,\n    stored: StoredResource,\n    engine: ResolutionEngine,\n    call: ResolutionCall | undefined\n  ): Promise<boolean> {\n    const fetchedAt = stored.fetchedAtUnix * 1000;\n    if (entry.fetchedAt !== undefined && fetchedAt <= entry.fetchedAt) return false;\n    if (entry.need.kind === 'did-document') {\n      entry.body = stored.body;\n      entry.lastRefreshFailed = false;\n    } else {\n      const issuerDocument = documentBody(entry.need.issuer);\n      if (issuerDocument === null) return false;\n      try {\n        entry.record = await verifyStatusListEnvelope(\n          entry.need,\n          stored.body,\n          issuerDocument,\n          engine,\n          engineNowUnix(call)\n        );\n      } catch (cause) {\n        log(`[checkpoint] stored status list not used: ${entry.need.url}: ${String(cause)}`);\n        return false;\n      }\n    }\n    entry.fetchedAt = fetchedAt;\n    entry.failure = undefined;\n    entry.attemptedAt = now();\n    return true;\n  }\n\n  /**\n   * Read `entry` from the store, one read at a time per entry and at most one\n   * per `RESOLUTION_RETRY_MS`. A status list whose issuer has no document yet\n   * is not read: like a fetch, it waits for a later call. Never throws.\n   */\n  function readStore(\n    entry: Entry,\n    engine: ResolutionEngine,\n    call: ResolutionCall | undefined\n  ): Promise<boolean> {\n    const store = options.store;\n    if (!store) return Promise.resolve(false);\n    if (entry.need.kind === 'status-list' && documentBody(entry.need.issuer) === null) {\n      return Promise.resolve(false);\n    }\n    if (entry.storeRead) return entry.storeRead;\n    if (entry.storeReadAt !== undefined && now() - entry.storeReadAt < RESOLUTION_RETRY_MS) {\n      return Promise.resolve(false);\n    }\n    const read = (async () => {\n      try {\n        const stored = await store.get(entry.key);\n        if (\n          !stored ||\n          typeof stored.body !== 'string' ||\n          typeof stored.fetchedAtUnix !== 'number' ||\n          !Number.isFinite(stored.fetchedAtUnix)\n        ) {\n          return false;\n        }\n        return await adopt(entry, stored, engine, call);\n      } catch (cause) {\n        log(`[checkpoint] resolution store read failed: ${entry.need.url}: ${String(cause)}`);\n        return false;\n      } finally {\n        entry.storeReadAt = now();\n      }\n    })();\n    entry.storeRead = read;\n    void read.finally(() => {\n      if (entry.storeRead === read) entry.storeRead = undefined;\n    });\n    return read;\n  }\n\n  /**\n   * Read the store for the entries this host has never tried, DID documents\n   * before status lists so a stored list is verified against its issuer's\n   * stored document.\n   */\n  async function hydrate(\n    entries: readonly Entry[],\n    engine: ResolutionEngine,\n    call: ResolutionCall | undefined\n  ): Promise<void> {\n    if (!options.store) return;\n    const cold = (kind: Need['kind']) =>\n      entries.filter(\n        (entry) =>\n          entry.need.kind === kind &&\n          entry.body === undefined &&\n          entry.record === undefined &&\n          entry.attemptedAt === undefined &&\n          !entry.inFlight\n      );\n    await Promise.all(cold('did-document').map((entry) => readStore(entry, engine, call)));\n    await Promise.all(cold('status-list').map((entry) => readStore(entry, engine, call)));\n  }\n\n  /**\n   * Bring the due entries up to date: a newer copy in the store when there is\n   * one, otherwise a fetch within the budgets.\n   */\n  async function refreshEntries(\n    entries: readonly Entry[],\n    engine: ResolutionEngine,\n    when: Freshness,\n    call?: ResolutionCall\n  ): Promise<void> {\n    if (options.store) {\n      const due = (kind: Need['kind']) =>\n        entries.filter((entry) => entry.need.kind === kind && isDue(entry, when, call));\n      await Promise.all(due('did-document').map((entry) => readStore(entry, engine, call)));\n      await Promise.all(due('status-list').map((entry) => readStore(entry, engine, call)));\n    }\n    await fetchDue(entries, engine, when, call);\n  }\n\n  /** Run background work under the call's `waitUntil`, or detached. */\n  function inBackground(work: Promise<void>, call: ResolutionCall | undefined): void {\n    const guarded = work.catch(() => {});\n    if (call?.waitUntil) {\n      try {\n        call.waitUntil(guarded);\n      } catch {\n        // A waitUntil that throws leaves the work running detached.\n      }\n    }\n  }\n\n  /** Start every due entry the budget allows, DID documents first, at most `RESOLUTION_MAX_CONCURRENT_FETCHES` at once. */\n  async function fetchDue(\n    entries: readonly Entry[],\n    engine: ResolutionEngine,\n    when: Freshness,\n    call?: ResolutionCall\n  ) {\n    // A list is verified against its issuer's document, so lists are picked\n    // after the documents: those this call fetched, and any fetch of an\n    // issuer's document another call already started. A list whose issuer\n    // still has no document is left for a later call, unattempted and\n    // unbudgeted, so it is never rejected for want of one.\n    const due = (kind: Need['kind']) =>\n      entries.filter(\n        (entry) =>\n          entry.need.kind === kind &&\n          isDue(entry, when, call) &&\n          (kind === 'did-document' || documentBody(entry.need.issuer) !== null) &&\n          spend(entry.role)\n      );\n    await runBounded(due('did-document'), (entry) => start(entry, engine, call));\n    const issuerFetches = entries\n      .filter((entry) => entry.need.kind === 'status-list')\n      .flatMap((entry) => documentEntries(entry.need.issuer))\n      .map((document) => document.inFlight)\n      .filter((running) => running !== undefined);\n    await Promise.all(issuerFetches);\n    await runBounded(due('status-list'), (entry) => start(entry, engine, call));\n  }\n\n  async function runBounded(entries: readonly Entry[], fn: (entry: Entry) => Promise<void>) {\n    let cursor = 0;\n    const worker = async (): Promise<void> => {\n      while (cursor < entries.length) await fn(entries[cursor++]!);\n    };\n    await Promise.all(\n      Array.from({ length: Math.min(RESOLUTION_MAX_CONCURRENT_FETCHES, entries.length) }, worker)\n    );\n  }\n\n  return {\n    mode: options.mode,\n\n    rootAnswers(call) {\n      const out: Record<string, ResourceOutcome> = {};\n      for (const entry of tables.root.values()) {\n        const usable =\n          isFresh(entry, 'stale', call) ||\n          (entry.body !== undefined &&\n            entry.lastRefreshFailed &&\n            ageMs(entry) < entry.need.maxStaleSeconds * 1000);\n        if (usable) out[entry.key] = outcomeOf(entry, call);\n      }\n      return out;\n    },\n\n    async answer(needs, engine, call) {\n      const entries = needs.map((need) => track(need, true));\n      await hydrate(entries, engine, call);\n      if (options.mode === 'inline') {\n        await fetchDue(entries, engine, 'stale', call);\n      } else {\n        // A miss the store did not answer, and an entry past its refresh point\n        // (a quiet period can outlast the background refresh's active window),\n        // is brought up to date in the background now, from a newer stored\n        // copy or a fetch, so the client's retry finds it, as a miss's does.\n        const due = entries.filter((entry) => isDue(entry, 'refresh', call));\n        if (due.length > 0) {\n          inBackground(refreshEntries(due, engine, 'refresh', call), call);\n        }\n      }\n      // Wait for a fetch another request already started for the same key.\n      if (options.mode === 'inline') {\n        await Promise.all(entries.map((entry) => entry.inFlight).filter(Boolean));\n      }\n      const out: Record<string, ResourceOutcome> = {};\n      for (const entry of entries) out[entry.key] = outcomeOf(entry, call);\n      return out;\n    },\n\n    register(needs) {\n      for (const need of needs) track(need, false);\n    },\n\n    setRoots(needs) {\n      const keep = new Set(needs.map((need) => need.key));\n      for (const key of [...tables.root.keys()]) {\n        if (!keep.has(key)) tables.root.delete(key);\n      }\n      for (const need of needs) track(need, false);\n    },\n\n    async refresh(engine) {\n      const at = now();\n      for (const role of ['issuer', 'presenter'] as const) {\n        for (const entry of [...tables[role].values()]) {\n          if (at - entry.namedAt > RESOLUTION_INACTIVE_EVICT_MS && !entry.inFlight)\n            tables[role].delete(entry.key);\n        }\n      }\n      const active = [\n        ...tables.root.values(),\n        ...[...tables.issuer.values(), ...tables.presenter.values()].filter(\n          (entry) => at - entry.namedAt <= RESOLUTION_ACTIVE_MS\n        ),\n      ];\n      try {\n        await refreshEntries(active, engine, 'refresh');\n      } catch (cause) {\n        log(`[checkpoint] resolution refresh failed: ${String(cause)}`);\n      }\n    },\n  };\n}\n\n// -----------------------------------------------------------------------------\n// Transport.\n// -----------------------------------------------------------------------------\n\n/** A fetch that produced no usable resource, with the reason the engine is told. */\nexport class ResourceFetchError extends Error {\n  readonly kind = 'ResourceFetchError';\n\n  constructor(\n    readonly detail: ResourceFailureDetail,\n    message: string\n  ) {\n    super(message);\n  }\n}\n\nfunction failureDetail(cause: unknown): ResourceFailureDetail {\n  if (cause instanceof ResourceFetchError) return cause.detail;\n  if (cause instanceof UnsafeOutboundUrl) return 'unsafe-address';\n  if (cause instanceof SafeGetRefused) {\n    switch (cause.reason) {\n      case 'redirect':\n        return 'http-status';\n      case 'too-large':\n        return 'too-large';\n      case 'blocked-address':\n      case 'no-address-check':\n        return 'unsafe-address';\n      case 'content-encoding':\n        return 'rejected';\n      case 'no-address':\n        return 'network';\n    }\n  }\n  if (cause instanceof Error && cause.name === 'AbortError') return 'timeout';\n  return 'network';\n}\n\n/** The response body at `need.url` as text, within the need's byte cap. */\nasync function fetchText(\n  need: Pick<Need, 'url' | 'maxBytes'>,\n  fetchImpl: typeof fetch | undefined,\n  timeoutMs: number\n): Promise<string> {\n  const url = assertSafeHttpsUrl(need.url, 'resolution URL');\n  const controller = new AbortController();\n  const timer = setTimeout(() => controller.abort(), timeoutMs);\n  try {\n    const response = await safeGet(url, {\n      signal: controller.signal,\n      maxBytes: need.maxBytes,\n      fetch: fetchImpl,\n    });\n    if (response.status < 200 || response.status >= 300) {\n      throw new ResourceFetchError('http-status', `HTTP ${response.status} at ${url}`);\n    }\n    return new TextDecoder().decode(response.body);\n  } finally {\n    clearTimeout(timer);\n  }\n}\n\n/**\n * Verify a status-list need's envelope with the engine against its issuer's\n * DID document, at `nowUnix` in the engine's clock. A list the engine rejects\n * is `rejected`.\n */\nasync function verifyStatusListEnvelope(\n  need: Need,\n  envelope: string,\n  issuerDocument: string | null,\n  engine: ResolutionEngine,\n  nowUnix: number\n): Promise<StatusListRecord> {\n  const result = await engine.verifyStatusList(\n    JSON.stringify({\n      envelope,\n      url: need.url,\n      issuer: need.issuer ?? '',\n      didDocument: issuerDocument,\n      nowUnix,\n    })\n  );\n  if (!result.ok) {\n    throw new ResourceFetchError('rejected', `status list rejected (${result.code}): ${need.url}`);\n  }\n  return {\n    url: result.url,\n    issuer: result.issuer,\n    issuedAt: result.issuedAt,\n    expiresAt: result.expiresAt,\n    setIndices: result.setIndices,\n  };\n}\n"],"mappings":";;;;;;;;AAQA,MAAM,oCAAoB,IAAI,IAAI;CAAC;CAAa;CAAY;AAA0B,CAAC;AAEvF,IAAa,oBAAb,cAAuC,MAAM;CAC3C,OAAgB;AAClB;AAEA,SAAgB,mBAAmB,QAAgB,QAAQ,gBAAwB;CACjF,IAAI;CACJ,IAAI;EACF,SAAS,IAAI,IAAI,MAAM;CACzB,QAAQ;EACN,MAAM,IAAI,kBAAkB,GAAG,MAAM,wBAAwB,QAAQ;CACvE;CAEA,IAAI,OAAO,aAAa,UACtB,MAAM,IAAI,kBAAkB,GAAG,MAAM,mBAAmB,QAAQ;CAElE,IAAI,OAAO,YAAY,OAAO,UAC5B,MAAM,IAAI,kBAAkB,GAAG,MAAM,iCAAiC,QAAQ;CAKhF,IAAI,OAAO,SAAS,IAClB,MAAM,IAAI,kBAAkB,GAAG,MAAM,wCAAwC,QAAQ;CAGvF,MAAM,WAAW,kBAAkB,OAAO,QAAQ;CAClD,IAAI,CAAC,YAAY,kBAAkB,QAAQ,GACzC,MAAM,IAAI,kBAAkB,GAAG,MAAM,oCAAoC,QAAQ;CAGnF,OAAO;AACT;;;;;;AAOA,SAAgB,mBAA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