{"version":3,"file":"adapters.mjs","names":["WARNED","warnOnce"],"sources":["../src/engine/adapters/agent-card-resolver.ts","../src/engine/adapters/legacy-resolvers.ts","../src/engine/adapters/policy-evaluator.ts","../src/engine/adapters/rdns-verifier.ts"],"sourcesContent":["/**\n * AgentCardResolver adapter — A2A support.\n *\n * Fetches an A2A Agent Card (`/.well-known/agent.json`) over HTTPS and\n * reduces it to the engine's `AgentCard` shape — see\n * `docs/architecture/a2a-verification.md`. Same shape as the sibling\n * `did-resolver.ts`: the async half does all the I/O; the adapter's output\n * is plain data the host wrapper bundles into `ContextSpec.agentCards`\n * before calling `engineVerify`. The engine itself never fetches anything.\n *\n * **Card → scheme mapping is a best-effort reduction, not a full A2A/OpenAPI\n * `SecurityScheme` parser.** The A2A spec's `securitySchemes` is a named\n * object map (scheme name → scheme object, per OpenAPI 3), not an array —\n * `securitySchemeEntries` reduces it to values regardless of shape. It\n * reuses OpenAPI 3's scheme vocabulary (`apiKey` / `http` / `oauth2` /\n * `openIdConnect` / `mutualTLS`), which has no first-class \"RFC 9421\" or\n * \"JWKS-backed JWT bearer\" scheme name. Until a concrete field example says\n * otherwise, this resolver recognizes two shapes (a card MAY put the extra\n * fields under a vendor `x-*` extension instead; both spellings are checked):\n *   - `{ type: 'http', scheme: 'signature', keyid: '<did-url>' }` → RFC 9421\n *     HTTP Message Signatures.\n *   - `{ type: 'http', scheme: 'bearer', bearerFormat: 'JWT', jwksUri: '...' }`\n *     → a JWT bearer with a resolvable JWKS.\n * Every other scheme (or a card with none of the above) reduces to\n * `{ kind: 'unverifiable' }` — the engine still attributes the agent by\n * name, but never treats it as a verified claim.\n */\nimport type { AgentCard, AgentCardSecurityScheme, VerificationMethod } from '../types';\nimport { assertSafeHttpsUrl, UnsafeOutboundUrl } from './outbound-url-policy';\nimport { base64UrlDecode } from './util';\n\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\nconst AGENT_CARD_PATH = '/.well-known/agent.json';\n\n// -----------------------------------------------------------------------------\n// Errors — the adapter throws these; the host wrapper translates to \"card\n// unreachable\" (omit the origin from ContextSpec.agentCards).\n// -----------------------------------------------------------------------------\n\nexport class AgentCardNotFound extends Error {\n  readonly kind = 'AgentCardNotFound';\n}\n\nexport class AgentCardResolverTimeout extends Error {\n  readonly kind = 'AgentCardResolverTimeout';\n}\n\nexport class AgentCardResolverError extends Error {\n  readonly kind = 'AgentCardResolverError';\n}\n\n// -----------------------------------------------------------------------------\n// Public surface.\n// -----------------------------------------------------------------------------\n\nexport interface AgentCardResolverAdapter {\n  resolve(origin: string): Promise<AgentCard>;\n}\n\n// bestbrian, PR #4987 P2: a hard card-fetch failure (network error,\n// timeout, 404, invalid JSON, SSRF-rejected URL) previously wasn't cached\n// at all, so an origin named repeatedly (an attacker's chosen\n// `Signature-Agent`, or just a genuinely-down agent) re-paid the full\n// fetch timeout on every single `resolve()` call. `failure` entries use\n// this much shorter TTL than the 10-minute positive one, so a transient\n// outage still recovers quickly.\nconst NEGATIVE_CACHE_TTL_MS = 30_000;\n// bestbrian, PR #4987 P2: the cache was an unbounded `Map` keyed on the\n// un-normalized origin — an attacker driving a high-cardinality stream of\n// origins (or casing variants of the same one) grows it without bound.\n// `Map` preserves insertion order, so the oldest entry is evicted once\n// this cap is hit.\nconst MAX_CACHE_ENTRIES = 1_000;\n\ntype CacheEntry =\n  | { kind: 'card'; card: AgentCard; fetchedAt: number }\n  | { kind: 'failure'; error: Error; fetchedAt: number };\n\nexport interface AgentCardResolverOpts {\n  /** AbortController timeout shared by the card AND (if the scheme needs it) the JWKS fetch. Default 3000ms — docs/architecture/a2a-verification.md. */\n  fetchTimeoutMs?: number;\n  /** TTL for a resolved card. Default 10 minutes — docs/architecture/a2a-verification.md. */\n  ttlMs?: number;\n  /** Injectable fetch — defaults to global `fetch` (Node 18+). */\n  fetch?: typeof fetch;\n  /** Injectable cache — defaults to a fresh `Map` per adapter instance. */\n  cache?: Map<string, CacheEntry>;\n  /** Injectable wall-clock — defaults to `Date.now()`. Tests use a stub. */\n  now?: () => number;\n}\n\nconst DEFAULT_FETCH_TIMEOUT_MS = 3_000;\nconst DEFAULT_TTL_MS = 10 * 60_000;\n\nexport function makeAgentCardResolver(opts: AgentCardResolverOpts = {}): AgentCardResolverAdapter {\n  const timeoutMs = opts.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;\n  const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;\n  const fetchImpl = opts.fetch ?? fetch;\n  const cache = opts.cache ?? new Map<string, CacheEntry>();\n  const now = opts.now ?? (() => Date.now());\n\n  return {\n    async resolve(origin: string): Promise<AgentCard> {\n      // bestbrian, PR #4987 P2: key the cache on the normalized origin —\n      // mirrors the engine's own `canonical_a2a_origin` (rust/crates/\n      // kya-os-engine/src/api.rs) — so casing variants of the same origin\n      // (which the engine now treats as one identity) hit the SAME entry\n      // instead of each growing the cache separately. Falls back to the\n      // raw origin when it isn't a valid https origin; `assertSafeHttpsUrl`\n      // rejects it before any fetch happens either way.\n      const cacheKey = normalizeOrigin(origin) ?? origin;\n      const cached = cache.get(cacheKey);\n      if (cached) {\n        const cacheTtlMs = cached.kind === 'failure' ? NEGATIVE_CACHE_TTL_MS : ttlMs;\n        if (now() - cached.fetchedAt < cacheTtlMs) {\n          if (cached.kind === 'failure') throw cached.error;\n          return cached.card;\n        }\n      }\n\n      // bestbrian, PR #4987 P2: the card and JWKS fetches used to each get\n      // their OWN full `timeoutMs` budget (a fresh `AbortController` per\n      // call), so a JWT-bearer card's worst case was 2x the documented\n      // budget. Share one deadline across both — `reduceCard` computes\n      // each fetch's remaining slice of it.\n      const deadlineAt = now() + timeoutMs;\n      try {\n        // Cursor Bugbot (bug id 58da7e7e-034d-4f28-8479-ac71d4fb0c45): fetch\n        // from the SAME canonical origin the cache is keyed on, not the raw\n        // input — a trailing slash or stray path on `Signature-Agent` (e.g.\n        // \"https://agent.example/\") otherwise hit the wrong URL\n        // (\"https://agent.example//.well-known/agent.json\") while any\n        // resulting failure was still stored under the canonical key,\n        // poisoning the negative cache for a clean request to the same\n        // origin.\n        const raw = await fetchJson(\n          cacheKey + AGENT_CARD_PATH,\n          fetchImpl,\n          deadlineAt - now(),\n          'agent card'\n        );\n        const { card, jwksFetchFailed } = await reduceCard(raw, fetchImpl, deadlineAt, now);\n        // A transient JWKS outage degrades this resolve() to `unverifiable`\n        // (see `selectSecurityScheme`) but must not be cached for the full\n        // TTL — that would strand a real jwtBearer agent on the pattern rung\n        // for up to 10 minutes after JWKS recovers. Skip the write so the\n        // next call retries key resolution instead of serving the stale miss.\n        if (!jwksFetchFailed) {\n          setCacheEntry(cache, cacheKey, { kind: 'card', card, fetchedAt: now() });\n        }\n        return card;\n      } catch (error) {\n        if (error instanceof Error) {\n          setCacheEntry(cache, cacheKey, { kind: 'failure', error, fetchedAt: now() });\n        }\n        throw error;\n      }\n    },\n  };\n}\n\n/**\n * Normalize an origin to the same canonical form the engine's\n * `canonical_a2a_origin` produces (rust/crates/kya-os-engine/src/api.rs):\n * lowercased, `https://` required, one trailing `/` stripped, the value\n * narrowed to its authority alone (a path/query/fragment dropped), userinfo\n * (`user@host`) rejected outright, and a trailing default `:443` port\n * stripped. `null` for anything else.\n *\n * Cursor Bugbot (bug id 390adcd0-0282-4ab8-b14e-70bca0b5f072), PR #4987\n * review 2: this function used to stop at lowercase + one trailing slash,\n * before `canonical_a2a_origin` gained the userinfo/port/path-isolation\n * gaps it closes today. A `Signature-Agent` spelled with the explicit\n * default port, or one riding a path/query/fragment, canonicalized\n * DIFFERENTLY on the two sides — this cache's key stayed on the old, wider\n * form, so a card the engine considers reachable (canonical key without the\n * port) missed here (still keyed with the port), and every such request\n * fell back to `Unreachable`. Both sides must derive the SAME key from the\n * SAME input; this mirrors `canonical_a2a_origin`'s logic step-for-step.\n */\nfunction normalizeOrigin(origin: string): string | null {\n  const PREFIX = 'https://';\n  const lower = origin.toLowerCase();\n  if (!lower.startsWith(PREFIX)) return null;\n  const hostAndPath = lower.slice(PREFIX.length);\n  const trimmed = hostAndPath.endsWith('/') ? hostAndPath.slice(0, -1) : hostAndPath;\n  if (trimmed.length === 0) return null;\n  // Isolate the authority the same way `canonical_a2a_origin` does — a\n  // path/query/fragment that sneaks past the caller must not smuggle an\n  // `@` in ahead of the real host.\n  const authority = trimmed.split(/[/?#]/, 1)[0];\n  if (authority.includes('@')) return null;\n  const bareAuthority = authority.endsWith(':443') ? authority.slice(0, -4) : authority;\n  return bareAuthority.length > 0 ? PREFIX + bareAuthority : null;\n}\n\nfunction setCacheEntry(cache: Map<string, CacheEntry>, key: string, entry: CacheEntry): void {\n  if (!cache.has(key) && cache.size >= MAX_CACHE_ENTRIES) {\n    const oldestKey = cache.keys().next().value;\n    if (oldestKey !== undefined) cache.delete(oldestKey);\n  }\n  cache.set(key, entry);\n}\n\n// -----------------------------------------------------------------------------\n// Fetch + reduction.\n// -----------------------------------------------------------------------------\n\nasync function fetchJson(\n  url: string,\n  fetchImpl: typeof fetch,\n  remainingMs: number,\n  what: string\n): Promise<unknown> {\n  let safeUrl: string;\n  try {\n    safeUrl = assertSafeHttpsUrl(url, `${what} URL`);\n  } catch (cause) {\n    if (cause instanceof UnsafeOutboundUrl) {\n      throw new AgentCardResolverError(cause.message);\n    }\n    throw cause;\n  }\n\n  // bestbrian, PR #4987 P2: the card and JWKS fetches used to each get\n  // their own full budget, so a JWT-bearer card's worst case was 2x the\n  // documented ~3s fetch allowance. Callers pass what's LEFT of one shared\n  // deadline (`resolve()`'s `deadlineAt`); if a slow card fetch already\n  // spent it all, don't even attempt the JWKS fetch.\n  if (remainingMs <= 0) {\n    throw new AgentCardResolverTimeout(\n      `${what} fetch timed out: no time left in the shared fetch budget: ${safeUrl}`\n    );\n  }\n\n  const controller = new AbortController();\n  const timer = setTimeout(() => controller.abort(), remainingMs);\n  // bestbrian, PR #4987 P2 (round 2): the shared deadline used to only\n  // guard the `fetchImpl` call — `clearTimeout` ran in a `finally` right\n  // after headers arrived, before the body was ever read. A response\n  // could publish valid headers instantly and then drip its body one byte\n  // at a time forever; the byte cap bounds memory but nothing bounded\n  // TIME, so a single such origin pins a resolve() call (and, once a host\n  // wires A2A, a request) open indefinitely. The timer — and the abort it\n  // drives — now stay live across the ENTIRE fetch-plus-read, not just the\n  // header wait; `readCappedText` reacts to the same `controller.signal`.\n  try {\n    let response: Response;\n    try {\n      // `redirect: 'manual'` — `assertSafeHttpsUrl` only validated `safeUrl`\n      // itself; a 3xx here would otherwise have the runtime's default\n      // follow-redirects behavior fetch an unvalidated Location header,\n      // letting a `Signature-Agent` origin (or a card's `jwksUri`) bounce\n      // this SSRF-guarded fetch at a private address. Fail closed instead of\n      // chasing the redirect.\n      response = await fetchImpl(safeUrl, { signal: controller.signal, redirect: 'manual' });\n    } catch (cause) {\n      if (cause instanceof Error && cause.name === 'AbortError') {\n        throw new AgentCardResolverTimeout(\n          `${what} fetch timed out after ${remainingMs}ms: ${safeUrl}`\n        );\n      }\n      throw new AgentCardResolverError(`${what} fetch failed: ${safeUrl}: ${String(cause)}`);\n    }\n\n    if (response.status === 404) {\n      throw new AgentCardNotFound(`no ${what} at ${safeUrl}`);\n    }\n    if (!response.ok) {\n      throw new AgentCardResolverError(`${what} HTTP ${response.status} at ${safeUrl}`);\n    }\n    // bestbrian, PR #4987 P2: an attacker-controlled origin (or a\n    // misconfigured/compromised agent site) could serve something other than\n    // a card/JWKS at this well-known path — check the content-type before\n    // spending any effort reading the body.\n    const contentType = response.headers.get('content-type') ?? '';\n    if (!JSON_CONTENT_TYPE.test(contentType)) {\n      throw new AgentCardResolverError(\n        `${what} response has unexpected content-type \"${contentType}\" at ${safeUrl}`\n      );\n    }\n    let text: string;\n    try {\n      text = await readCappedText(response, what, safeUrl, controller.signal);\n    } catch (cause) {\n      if (cause instanceof Error && cause.name === 'AbortError') {\n        throw new AgentCardResolverTimeout(\n          `${what} response body timed out after ${remainingMs}ms: ${safeUrl}`\n        );\n      }\n      if (cause instanceof AgentCardResolverError) throw cause;\n      throw new AgentCardResolverError(\n        `${what} response body could not be read at ${safeUrl}: ${String(cause)}`\n      );\n    }\n    try {\n      return JSON.parse(text);\n    } catch (cause) {\n      throw new AgentCardResolverError(\n        `${what} response not valid JSON at ${safeUrl}: ${String(cause)}`\n      );\n    }\n  } finally {\n    clearTimeout(timer);\n  }\n}\n\n// `application/json`, or a `+json` structured-syntax suffix (e.g. a vendor\n// media type), optionally followed by `; charset=...` — case-insensitive.\nconst JSON_CONTENT_TYPE = /^application\\/(?:[\\w.-]+\\+)?json\\s*(?:;.*)?$/i;\n\n// bestbrian, PR #4987 P2: `response.json()` (and `.text()`) buffer the\n// ENTIRE body into memory before parsing, with no size limit — an\n// attacker-controlled origin could serve a multi-gigabyte response at the\n// card/JWKS path and exhaust host memory. 1 MiB is generous for either\n// document; a `Content-Length` header alone isn't trusted (it can be\n// absent, or simply wrong) — the stream itself is capped as it's read.\nconst MAX_RESPONSE_BYTES = 1_048_576;\n\nasync function readCappedText(\n  response: Response,\n  what: string,\n  safeUrl: string,\n  signal: AbortSignal\n): Promise<string> {\n  if (!response.body) {\n    // A runtime (or test double) that doesn't expose a streaming body —\n    // fall back to the whole-body read; every such caller in this\n    // codebase only ever hands small, already-in-memory fixtures.\n    return response.text();\n  }\n  const reader = response.body.getReader();\n  const abortError = (): Error => {\n    const err = new Error(`${what} response body read aborted: ${safeUrl}`);\n    err.name = 'AbortError';\n    return err;\n  };\n  if (signal.aborted) {\n    await reader.cancel().catch(() => {});\n    throw abortError();\n  }\n  // bestbrian, PR #4987 P2 (round 2): `reader.read()` takes no signal of\n  // its own — without this listener, an abort fired while a read is\n  // in-flight (a slow-drip body) would leave the loop waiting forever.\n  // Cancelling the reader settles the pending read (per the Streams\n  // spec), and the `aborted` check below turns that settlement into the\n  // SAME timeout error `fetchJson` already raises for a slow header wait.\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 decoder = new TextDecoder();\n    let text = '';\n    let totalBytes = 0;\n    for (;;) {\n      const { done, value } = await reader.read();\n      if (aborted) throw abortError();\n      if (done) break;\n      totalBytes += value.byteLength;\n      if (totalBytes > MAX_RESPONSE_BYTES) {\n        await reader.cancel().catch(() => {});\n        throw new AgentCardResolverError(\n          `${what} response exceeds the ${MAX_RESPONSE_BYTES}-byte cap at ${safeUrl}`\n        );\n      }\n      text += decoder.decode(value, { stream: true });\n    }\n    text += decoder.decode();\n    return text;\n  } finally {\n    signal.removeEventListener('abort', onAbort);\n  }\n}\n\ninterface ReducedCard {\n  card: AgentCard;\n  /** True when a jwtBearer scheme's JWKS fetch threw (network/timeout/HTTP/JSON) — see `resolve()`'s cache write. */\n  jwksFetchFailed: boolean;\n}\n\n// bestbrian, PR #4987 P3: an attributed-but-unverified card's `name` /\n// `provider.organization` ride into analytics at confidence 95 verbatim\n// (`a2a_attributed_result`, rust/crates/kya-os-engine/src/api.rs) — the\n// card is entirely self-asserted by the calling agent, never verified, so\n// an unbounded string here is unbounded storage/log growth per malicious\n// request. Cap well before either string reaches the engine.\nconst MAX_CARD_STRING_LENGTH = 128;\n\nfunction capCardString(value: string): string {\n  return value.length > MAX_CARD_STRING_LENGTH ? value.slice(0, MAX_CARD_STRING_LENGTH) : value;\n}\n\nasync function reduceCard(\n  raw: unknown,\n  fetchImpl: typeof fetch,\n  deadlineAt: number,\n  now: () => number\n): Promise<ReducedCard> {\n  if (raw === null || typeof raw !== 'object') {\n    throw new AgentCardResolverError('agent card response must be a JSON object');\n  }\n  const doc = raw as Record<string, unknown>;\n  const name = typeof doc.name === 'string' ? capCardString(doc.name) : 'unknown';\n  const provider =\n    doc.provider !== null && typeof doc.provider === 'object'\n      ? (doc.provider as Record<string, unknown>)\n      : undefined;\n  const providerOrganization =\n    provider && typeof provider.organization === 'string'\n      ? capCardString(provider.organization)\n      : undefined;\n\n  const { scheme: securityScheme, jwksFetchFailed } = await selectSecurityScheme(\n    securitySchemeEntries(doc.securitySchemes),\n    fetchImpl,\n    deadlineAt,\n    now\n  );\n\n  return {\n    card: {\n      name,\n      ...(providerOrganization ? { providerOrganization } : {}),\n      securityScheme,\n    },\n    jwksFetchFailed,\n  };\n}\n\n/**\n * A2A/OpenAPI 3 define `securitySchemes` as a named object map (scheme name\n * → scheme object), not an array — `{ \"http-sig\": { type: 'http', ... } }`.\n * Reduce it to the values regardless of shape: a real card is the object\n * map; an array is accepted too, defensively, in case a card ever supplies\n * one. Anything else (missing, or a scalar) yields no schemes.\n */\nfunction securitySchemeEntries(raw: unknown): unknown[] {\n  if (Array.isArray(raw)) return raw;\n  if (raw !== null && typeof raw === 'object') return Object.values(raw);\n  return [];\n}\n\ninterface SelectedScheme {\n  scheme: AgentCardSecurityScheme;\n  jwksFetchFailed: boolean;\n}\n\nasync function selectSecurityScheme(\n  schemes: unknown[],\n  fetchImpl: typeof fetch,\n  deadlineAt: number,\n  now: () => number\n): Promise<SelectedScheme> {\n  // Sticky across the loop, not returned early on: a JWKS outage on one\n  // entry must not stop the search for a later usable scheme, but if\n  // nothing else matches either, `resolve()` still needs to know this\n  // `unverifiable` is a transient miss, not a genuine one — see the\n  // `jwksFetchFailed` comment below and `resolve()`'s cache write.\n  let jwksFetchFailed = false;\n\n  for (const entry of schemes) {\n    if (entry === null || typeof entry !== 'object') continue;\n    const scheme = entry as Record<string, unknown>;\n    if (scheme.type !== 'http') continue;\n\n    if (scheme.scheme === 'signature') {\n      const keyid = firstString(scheme.keyid, scheme['x-keyid']);\n      if (keyid) {\n        return { scheme: { kind: 'httpMessageSignatures', keyid }, jwksFetchFailed: false };\n      }\n    }\n\n    if (scheme.scheme === 'bearer' && scheme.bearerFormat === 'JWT') {\n      const jwksUri = firstString(scheme.jwksUri, scheme['x-jwks-uri']);\n      if (jwksUri) {\n        // A JWKS fetch failure means the CARD is fine but the KEYS are not\n        // reachable right now — degrade to the next scheme (or\n        // `unverifiable` below), same as an unrecognized scheme. Do not let\n        // it propagate: `resolveJwks`'s own `fetchJson` throws on a\n        // network/timeout/non-2xx/non-JSON JWKS response, and letting that\n        // escape `reduceCard` makes the whole card look unreachable to the\n        // caller, which then loses the agent's name/vendor attribution\n        // entirely (Block/Unauthenticated) instead of falling to the\n        // pattern rung the engine already has for an unverifiable scheme.\n        // `jwksFetchFailed` tells `resolve()` this outcome is transient —\n        // not a genuine \"no usable keys\" — so the caller must not cache it.\n        let keys: VerificationMethod[] = [];\n        try {\n          keys = await resolveJwks(jwksUri, fetchImpl, deadlineAt - now());\n        } catch {\n          jwksFetchFailed = true;\n          keys = [];\n        }\n        if (keys.length > 0) return { scheme: { kind: 'jwtBearer', keys }, jwksFetchFailed: false };\n      }\n    }\n  }\n  return { scheme: { kind: 'unverifiable' }, jwksFetchFailed };\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n  for (const v of values) {\n    if (typeof v === 'string' && v.length > 0) return v;\n  }\n  return undefined;\n}\n\n/**\n * Fetch a JWKS and reduce it to the engine's `VerificationMethod[]` shape.\n * Ed25519 (`kty: 'OKP', crv: 'Ed25519'`) only — the engine's `KeyType` has a\n * single variant, same Phase-1 scope as `did-resolver.ts`'s did:web mapping.\n * A key missing `kid`, or that doesn't decode to exactly 32 bytes, is\n * silently dropped rather than smuggled into the WASM engine.\n */\nasync function resolveJwks(\n  jwksUri: string,\n  fetchImpl: typeof fetch,\n  remainingMs: number\n): Promise<VerificationMethod[]> {\n  const raw = await fetchJson(jwksUri, fetchImpl, remainingMs, 'JWKS');\n  if (raw === null || typeof raw !== 'object') return [];\n  const doc = raw as Record<string, unknown>;\n  const rawKeys = Array.isArray(doc.keys) ? doc.keys : [];\n\n  const keys: VerificationMethod[] = [];\n  for (const entry of rawKeys) {\n    if (entry === null || typeof entry !== 'object') continue;\n    const jwk = entry as Record<string, unknown>;\n    if (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519') continue;\n    if (typeof jwk.kid !== 'string' || typeof jwk.x !== 'string') continue;\n    let decoded: Uint8Array;\n    try {\n      decoded = base64UrlDecode(jwk.x);\n    } catch {\n      continue;\n    }\n    if (decoded.length !== ED25519_PUBLIC_KEY_LENGTH) continue;\n    keys.push({ id: jwk.kid, keyType: 'Ed25519', publicKeyBytes: Array.from(decoded) });\n  }\n  return keys;\n}\n","/**\n * Deprecated stand-ins for the DID resolver and status-list cache that\n * `verifyRequest` used to take as `didResolver` and `statusListCache`.\n *\n * The orchestrators answer the engine's needs with a resolution host\n * (`makeResolutionHost`) and ignore both options. Published SDK versions\n * (`@kya-os/checkpoint-express` up to 1.10.0, `@kya-os/checkpoint-nextjs` up\n * to 1.9.0, `@kya-os/checkpoint` 1.4.0) still import these factories and\n * pass what they build, and their dependency ranges accept this release, so\n * the names stay exported for them to load. What they build does nothing:\n * `resolve` and `fetch` reject. They are removed once those versions are\n * deprecated on npm.\n */\n\nimport type { DidDocument } from '../types';\nimport type { StatusListVerifier } from './status-list-cache';\n\n/**\n * @deprecated `verifyRequest` ignores `didResolver`; it answers the engine's\n * needs with a resolution host (`makeResolutionHost`).\n */\nexport interface DidResolverAdapter {\n  resolve(did: string): Promise<DidDocument>;\n}\n\n/**\n * @deprecated `verifyRequest` ignores `statusListCache`; it answers the\n * engine's needs with a resolution host (`makeResolutionHost`).\n */\nexport interface StatusListCacheAdapter {\n  fetch(url: string, issuer: string, verify: StatusListVerifier): Promise<number[]>;\n}\n\n/** One warning per process, shared by every copy of this package. */\nconst WARNED = Symbol.for('kya.checkpoint.legacyResolversWarned');\n\nfunction warnOnce(): void {\n  const registry = globalThis as { [WARNED]?: boolean };\n  if (registry[WARNED]) return;\n  registry[WARNED] = true;\n  console.warn(\n    '[checkpoint] makeDidResolver and makeStatusListCache are deprecated and do nothing: ' +\n      'verifyRequest ignores the didResolver and statusListCache options and answers the ' +\n      \"engine's needs with a resolution host (makeResolutionHost). Upgrade the Checkpoint SDK.\"\n  );\n}\n\nfunction removed(name: string): Error {\n  return new Error(`${name} no longer resolves anything; use makeResolutionHost`);\n}\n\n/**\n * @deprecated Returns an adapter whose `resolve` rejects. `verifyRequest`\n * ignores `didResolver`; use `makeResolutionHost`.\n */\nexport function makeDidResolver(_options?: unknown): DidResolverAdapter {\n  warnOnce();\n  return { resolve: () => Promise.reject(removed('makeDidResolver')) };\n}\n\n/**\n * @deprecated Returns an adapter whose `fetch` rejects. `verifyRequest`\n * ignores `statusListCache`; use `makeResolutionHost`.\n */\nexport function makeStatusListCache(_options?: unknown): StatusListCacheAdapter {\n  warnOnce();\n  return { fetch: () => Promise.reject(removed('makeStatusListCache')) };\n}\n","/**\n * Deprecated stand-in for the tenant policy evaluator that `verifyRequest`\n * used to take as `policyEvaluator`.\n *\n * The engine decides: the orchestrators hand it a Permit tenant decision and\n * ignore `policyEvaluator`, so no TS code produces a Block. A tenant's rules\n * are Cedar (composed policy, or the structured policy the engine compiles),\n * which the engine evaluates. Published SDK versions\n * (`@kya-os/checkpoint-express` 1.6.0 to 1.10.0) still import\n * `makePolicyEvaluator` and pass what it builds, and their dependency ranges\n * accept this release, so the names stay exported for them to load. What it\n * builds decides nothing and reads no remote policy. They are removed once\n * those versions are deprecated on npm.\n */\n\nimport type { Decision } from '../types';\n\n/**\n * @deprecated `verifyRequest` ignores `policyEvaluator`; the engine decides,\n * and a tenant's rules are Cedar.\n */\nexport interface PolicyEvalInput {\n  tenantHost: string;\n  reputation: number;\n}\n\n/**\n * @deprecated `verifyRequest` ignores `policyEvaluator`; the engine decides,\n * and a tenant's rules are Cedar.\n */\nexport interface PolicyEvaluatorAdapter {\n  evaluate(input: PolicyEvalInput): Promise<Decision>;\n}\n\n/** One warning per process, shared by every copy of this package. */\nconst WARNED = Symbol.for('kya.checkpoint.policyEvaluatorWarned');\n\nfunction warnOnce(): void {\n  const registry = globalThis as { [WARNED]?: boolean };\n  if (registry[WARNED]) return;\n  registry[WARNED] = true;\n  console.warn(\n    '[checkpoint] makePolicyEvaluator is deprecated and decides nothing: verifyRequest ' +\n      'ignores the policyEvaluator option and the engine makes the tenant decision. Write ' +\n      \"a tenant's rules as Cedar (composed policy). Upgrade the Checkpoint SDK.\"\n  );\n}\n\nconst PERMIT: Decision = { kind: 'Permit' };\n\n/**\n * @deprecated Returns an adapter that permits every request and reads no\n * remote policy. `verifyRequest` ignores `policyEvaluator`; a tenant's rules\n * are Cedar.\n */\nexport function makePolicyEvaluator(_options?: unknown): PolicyEvaluatorAdapter {\n  warnOnce();\n  return { evaluate: async () => PERMIT };\n}\n","/**\n * ReverseDnsVerifier adapter — P36.\n *\n * Forward-confirmed reverse DNS: the mechanism vendors document for\n * proving a request genuinely came from their infrastructure (Google via\n * `crawler.googlebot.com` reverse DNS + a published range file, Bing via\n * `search.msn.com`). Three steps, in order:\n *\n *   1. Reverse-resolve the client address to a hostname (PTR).\n *   2. Forward-resolve that hostname back to addresses (A/AAAA).\n *   3. Confirm the original address is among them, AND that the hostname\n *      falls within the vendor's expected domain.\n *\n * Step 2 is not optional and not a belt-and-braces extra. A PTR record is\n * controlled by whoever holds the address block, so anyone can point their\n * own address at `crawler.googlebot.com` — reverse-only \"verification\" is\n * trivially forgeable, and worse than no verification at all, because it\n * produces a *confident* wrong answer. Only the forward step, which\n * resolves through the domain owner's own authoritative DNS, actually\n * proves anything.\n *\n * **Degrade-to-unverified.** DNS is unreliable. A resolver timeout or\n * error must never become a thrown error (which would fail the caller)\n * or a `verified: true` (which would forge trust from a resolver hiccup).\n * Every failure mode returns `{ verified: false, reason }`; this adapter\n * never throws.\n *\n * SCOPE: this is the verification mechanism only. Wiring a verdict into\n * an attribution / confidence tier (consuming `agent-types.yaml`'s vendor\n * list, exposing it to the classification engine) is a separate ticket\n * (P37) — this module intentionally takes the expected hostname suffixes\n * as a plain argument rather than owning a vendor registry.\n *\n * **No default resolver, deliberately.** This file lives in the\n * `adapters` barrel (`./index.ts`), which tsup builds as a single\n * runtime-agnostic entry consumed by both Node hosts and the Cloudflare\n * Worker gateway (`apps/web/workers/gateway`, `nodejs_compat`). A static\n * top-level `import ... from 'node:dns/promises'` would tie the whole\n * bundled entry — every other adapter in it, not just this one — to\n * whatever DNS support that Worker runtime happens to have, for a\n * capability (raw resolver I/O) that Workers are not guaranteed to\n * implement. The entry also reaches the Edge runtime, which has no Node\n * built-ins at all. `resolver` is therefore a\n * required argument: a Node caller passes `node:dns/promises`'s\n * `reverse`/`resolve4`/`resolve6` in directly (three lines), the same\n * way `apps/web/workers/gateway/src/detection/resolution-host.ts` gives\n * the Worker its own KV-backed resolution host instead of this package's\n * Node `resolution-warmer.ts`: the split lives at the call site, not\n * inside this module.\n */\n\n// -----------------------------------------------------------------------------\n// Public surface.\n// -----------------------------------------------------------------------------\n\nexport type RdnsVerdictReason =\n  | 'confirmed'\n  | 'no-ptr'\n  | 'forward-mismatch'\n  | 'suffix-mismatch'\n  | 'timeout'\n  | 'lookup-error';\n\nexport interface RdnsVerdict {\n  /** True only when PTR → forward resolution → suffix all agree. */\n  verified: boolean;\n  /** The PTR hostname that was checked, present whenever one was found. */\n  hostname?: string;\n  reason: RdnsVerdictReason;\n}\n\n/**\n * The subset of `node:dns/promises` this adapter depends on. Exposed as\n * an injectable parameter (mirroring `DnsLookupFn` in\n * `apps/web/lib/security/ssrf-dns.ts`) so tests supply a deterministic\n * resolver instead of monkey-patching the `dns` module.\n */\nexport interface RdnsResolverFns {\n  reverse: (address: string) => Promise<string[]>;\n  resolve4: (hostname: string) => Promise<string[]>;\n  resolve6: (hostname: string) => Promise<string[]>;\n}\n\nexport interface RdnsVerifierOptions {\n  /** DNS budget per individual lookup call. Default 2000ms. */\n  timeoutMs?: number;\n  /**\n   * TTL for a confirmed hostname. Default 6h — PTR/A/AAAA records for\n   * stable crawler infrastructure change rarely, and a long success TTL\n   * is what keeps a verified vendor address from re-paying two DNS round\n   * trips on every request.\n   */\n  successTtlMs?: number;\n  /**\n   * TTL for a negative result (no PTR, forged/mismatched PTR, or a\n   * lookup failure). Deliberately shorter than `successTtlMs`: without a\n   * negative cache at all, every request from an ordinary non-crawler\n   * address would cost two uncached DNS lookups, which is both a latency\n   * cost and query volume aimed at resolvers — a cheap amplification for\n   * an attacker to trigger. Short enough that a newly-published PTR\n   * record or a transient resolver blip recovers quickly. Default 5min.\n   */\n  failureTtlMs?: number;\n  /** Injectable wall-clock, so TTL behaviour is testable without real time. */\n  now?: () => number;\n  /** Injectable cache, keyed by the client address. */\n  cache?: Map<string, ConfirmCacheEntry>;\n  /**\n   * DNS resolver functions. Required — see the module docblock for why\n   * this adapter does not default to `node:dns/promises` itself. On\n   * Node, pass `{ reverse, resolve4, resolve6 }` imported directly from\n   * `node:dns/promises`.\n   */\n  resolver: RdnsResolverFns;\n  /** Diagnostics hook. Never allowed to throw back into the adapter. */\n  logger?: (msg: string) => void;\n}\n\nexport interface RdnsVerifier {\n  /**\n   * Verify that `address` genuinely belongs to a host within\n   * `expectedSuffixes` (e.g. `['googlebot.com', 'google.com']`), via\n   * forward-confirmed reverse DNS. Never throws.\n   *\n   * The PTR → forward-confirm result is cached per address regardless of\n   * which suffixes are asked for — the underlying DNS fact (\"does this\n   * address forward-confirm to hostname X\") doesn't depend on the\n   * caller's allowlist, so checking the same address against several\n   * vendors' suffix lists costs one DNS round trip, not one per vendor.\n   */\n  verify(address: string, expectedSuffixes: string[]): Promise<RdnsVerdict>;\n}\n\n// -----------------------------------------------------------------------------\n// Internals.\n// -----------------------------------------------------------------------------\n\nconst DEFAULT_TIMEOUT_MS = 2_000;\nconst DEFAULT_SUCCESS_TTL_MS = 6 * 60 * 60 * 1000; // 6h\nconst DEFAULT_FAILURE_TTL_MS = 5 * 60 * 1000; // 5min\n\nconst RDNS_TIMEOUT_MARKER = 'rdns-lookup-timeout';\n\n/**\n * A legitimate PTR answer is one hostname. This bounds how many a\n * malicious reverse-zone owner can make this adapter forward-resolve for\n * a single verification call — see the cap's call site for why.\n */\nconst MAX_PTR_CANDIDATES = 5;\n\ntype HostnameConfirmation =\n  | { ok: true; hostname: string }\n  | { ok: false; reason: 'no-ptr' | 'forward-mismatch' | 'timeout' | 'lookup-error' };\n\ninterface ConfirmCacheEntry {\n  confirmation: HostnameConfirmation;\n  expiresAt: number;\n}\n\n/**\n * Matches a hostname against an expected domain suffix on a label\n * boundary: `hostname === suffix`, or `hostname` ends with `.` + suffix.\n * A bare substring/`.endsWith` check would let `crawler.googlebot.com`\n * pass a suffix check for `.com` (too loose) or let `evilgooglebot.com`\n * pass a check for `googlebot.com` (contains, not a real subdomain) —\n * this only accepts a genuine label-aligned match.\n */\nfunction matchesSuffix(hostname: string, suffix: string): boolean {\n  const h = hostname.toLowerCase().replace(/\\.$/, '');\n  const s = suffix.toLowerCase().replace(/\\.$/, '');\n  return h === s || h.endsWith(`.${s}`);\n}\n\n/**\n * Canonicalizes an address for equality comparison. IPv6 has several\n * valid textual encodings of the same address — compression (`::`),\n * leading zeros, and case — so the address a caller observed and the\n * address `resolve6` returns can be textually different while naming the\n * same host; a raw string comparison would wrongly fail a real match.\n * The WHATWG URL parser is this codebase's own established way to get\n * the canonical (lowercase, compressed) form — the same trick\n * `outbound-url-policy.ts` relies on for IPv6 range checks — so this\n * reuses it rather than hand-rolling another IPv6 parser. IPv4 goes\n * through the same path for a single normalization function; the URL\n * parser canonicalizes it too (e.g. drops leading zeros), which is\n * harmless since a plain dotted-quad has no other ambiguity to begin\n * with. Falls back to a lowercase compare for anything that fails to\n * parse rather than crashing a verification call.\n */\nfunction normalizeAddress(address: string): string {\n  const bare = address.startsWith('[') && address.endsWith(']') ? address.slice(1, -1) : address;\n  try {\n    const host = new URL(`http://${bare.includes(':') ? `[${bare}]` : bare}`).hostname;\n    return host.replace(/^\\[|\\]$/g, '');\n  } catch {\n    return address.toLowerCase();\n  }\n}\n\nfunction isTimeoutError(err: unknown): boolean {\n  return err instanceof Error && err.message === RDNS_TIMEOUT_MARKER;\n}\n\n/** Races `promise` against a timeout that rejects with a recognizable marker. */\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n  return new Promise((resolvePromise, reject) => {\n    const timer = setTimeout(() => reject(new Error(RDNS_TIMEOUT_MARKER)), ms);\n    promise.then(\n      (value) => {\n        clearTimeout(timer);\n        resolvePromise(value);\n      },\n      (err) => {\n        clearTimeout(timer);\n        reject(err);\n      }\n    );\n  });\n}\n\n/**\n * Forward-resolves one PTR candidate hostname to its A + AAAA addresses.\n * A missing record family (e.g. AAAA-only or A-only hostnames) is normal\n * and not an error — only a genuine timeout is tracked separately, so a\n * resolver hiccup on the forward step can be told apart from a clean\n * \"this hostname does not resolve to the client address\" mismatch.\n */\nasync function forwardResolve(\n  hostname: string,\n  resolver: RdnsResolverFns,\n  timeoutMs: number\n): Promise<{ addresses: string[]; timedOut: boolean }> {\n  const resolveFamily = async (fn: (hostname: string) => Promise<string[]>) => {\n    try {\n      return { addresses: await withTimeout(fn(hostname), timeoutMs), timedOut: false };\n    } catch (err) {\n      return { addresses: [] as string[], timedOut: isTimeoutError(err) };\n    }\n  };\n\n  const [v4, v6] = await Promise.all([\n    resolveFamily(resolver.resolve4),\n    resolveFamily(resolver.resolve6),\n  ]);\n\n  return {\n    addresses: [...v4.addresses, ...v6.addresses],\n    timedOut: v4.timedOut || v6.timedOut,\n  };\n}\n\nasync function resolveAndConfirm(\n  address: string,\n  resolver: RdnsResolverFns,\n  timeoutMs: number,\n  log: (msg: string) => void\n): Promise<HostnameConfirmation> {\n  let hostnames: string[];\n  try {\n    hostnames = await withTimeout(resolver.reverse(address), timeoutMs);\n  } catch (err) {\n    if (isTimeoutError(err)) {\n      log(`[rdns-verifier] PTR lookup timed out for ${address}`);\n      return { ok: false, reason: 'timeout' };\n    }\n    log(`[rdns-verifier] PTR lookup failed for ${address}: ${String(err)}`);\n    return { ok: false, reason: 'lookup-error' };\n  }\n\n  if (hostnames.length === 0) {\n    return { ok: false, reason: 'no-ptr' };\n  }\n\n  // A PTR response is otherwise-untrusted, attacker-shaped data — the same\n  // threat model this whole adapter exists for grants an attacker control\n  // over their own reverse zone. An unbounded number of returned hostnames\n  // would mean an unbounded number of forward-resolution round trips for a\n  // single verification call; a legitimate PTR answer is one hostname, so\n  // capping at a small constant costs nothing real and closes the fan-out.\n  const candidates = hostnames.slice(0, MAX_PTR_CANDIDATES);\n\n  const normalizedAddress = normalizeAddress(address);\n  let sawTimeout = false;\n  for (const hostname of candidates) {\n    const forward = await forwardResolve(hostname, resolver, timeoutMs);\n    // Check for a match BEFORE looking at timedOut. resolve4 and resolve6\n    // run independently (see forwardResolve); if one family times out\n    // while the other already returned the matching address, that\n    // already-successful match must not be discarded — otherwise a real\n    // crawler whose AAAA query merely hung would fail confirmation on a\n    // A record that matched fine, and get cached negative for\n    // `failureTtlMs` over a resolver hiccup in the OTHER family.\n    if (forward.addresses.some((a) => normalizeAddress(a) === normalizedAddress)) {\n      return { ok: true, hostname };\n    }\n    if (forward.timedOut) {\n      sawTimeout = true;\n    }\n  }\n\n  if (sawTimeout) {\n    log(`[rdns-verifier] forward confirmation timed out for ${address}`);\n    return { ok: false, reason: 'timeout' };\n  }\n\n  const truncated =\n    hostnames.length > candidates.length\n      ? `, ${hostnames.length - candidates.length} more truncated`\n      : '';\n  log(\n    `[rdns-verifier] forward confirmation failed for ${address} (PTR claimed: ${candidates.join(', ')}${truncated})`\n  );\n  return { ok: false, reason: 'forward-mismatch' };\n}\n\nexport function makeRdnsVerifier(opts: RdnsVerifierOptions): RdnsVerifier {\n  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n  const successTtlMs = opts.successTtlMs ?? DEFAULT_SUCCESS_TTL_MS;\n  const failureTtlMs = opts.failureTtlMs ?? DEFAULT_FAILURE_TTL_MS;\n  const now = opts.now ?? (() => Date.now());\n  const cache = opts.cache ?? new Map<string, ConfirmCacheEntry>();\n  const resolver = opts.resolver;\n  const log = opts.logger ?? (() => {});\n  const inFlight = new Map<string, Promise<HostnameConfirmation>>();\n\n  async function confirmHostname(address: string): Promise<HostnameConfirmation> {\n    // Same class of bug the forward-match comparison had: two textually\n    // different encodings of the same IPv6 address must not become two\n    // different cache entries (or two different in-flight lookups) for\n    // what is really one address.\n    const key = normalizeAddress(address);\n\n    const cached = cache.get(key);\n    if (cached && now() < cached.expiresAt) {\n      return cached.confirmation;\n    }\n\n    const pending = inFlight.get(key);\n    if (pending) return pending;\n\n    // Resolve using the CANONICAL form, not the raw caller-supplied one. A\n    // form `normalizeAddress` treats as equivalent (bracketed IPv6, a\n    // leading-zero IPv4 octet) can be a form `resolver.reverse` itself\n    // rejects or mishandles — passing the raw address through would fail\n    // the real lookup and cache that failure under the clean key,\n    // poisoning every future request for the canonical form too.\n    const resolved = resolveAndConfirm(key, resolver, timeoutMs, log)\n      .then((confirmation) => {\n        cache.set(key, {\n          confirmation,\n          expiresAt: now() + (confirmation.ok ? successTtlMs : failureTtlMs),\n        });\n        return confirmation;\n      })\n      .finally(() => {\n        inFlight.delete(key);\n      });\n\n    inFlight.set(key, resolved);\n    return resolved;\n  }\n\n  return {\n    async verify(address, expectedSuffixes) {\n      const confirmation = await confirmHostname(address);\n      if (!confirmation.ok) {\n        return { verified: false, reason: confirmation.reason };\n      }\n      if (!expectedSuffixes.some((suffix) => matchesSuffix(confirmation.hostname, suffix))) {\n        return { verified: false, hostname: confirmation.hostname, reason: 'suffix-mismatch' };\n      }\n      return { verified: true, hostname: confirmation.hostname, reason: 'confirmed' };\n    },\n  };\n}\n"],"mappings":";;;;AA+BA,MAAM,4BAA4B;AAClC,MAAM,kBAAkB;AAOxB,IAAa,oBAAb,cAAuC,MAAM;CAC3C,OAAgB;AAClB;AAEA,IAAa,2BAAb,cAA8C,MAAM;CAClD,OAAgB;AAClB;AAEA,IAAa,yBAAb,cAA4C,MAAM;CAChD,OAAgB;AAClB;AAiBA,MAAM,wBAAwB;AAM9B,MAAM,oBAAoB;AAmB1B,MAAM,2BAA2B;AACjC,MAAM,iBAAiB;AAEvB,SAAgB,sBAAsB,OAA8B,CAAC,GAA6B;CAChG,MAAM,YAAY,KAAK,kBAAkB;CACzC,MAAM,QAAQ,KAAK,SAAS;CAC5B,MAAM,YAAY,KAAK,SAAS;CAChC,MAAM,QAAQ,KAAK,yBAAS,IAAI,IAAwB;CACxD,MAAM,MAAM,KAAK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