{"version":3,"file":"composed-policy-context-DzeTfKfl.mjs","names":[],"sources":["../src/request-claim.ts","../src/composed-policy.ts","../src/composed-policy-context.ts"],"sourcesContent":["/**\n * Request claims: the one use of an accepted signed request.\n *\n * The engine names the claim a host must make on every accepted signed request\n * that needs one, in `detectionDetail.metadata`: `kya_request_keyid`,\n * `kya_request_nonce`, `kya_request_expires` and `kya_request_claim_scope`\n * (a resource DID, or `authority:` and the signed authority). The host claims\n * it atomically, before any handler effect; a second request carrying the\n * same claim is refused. Whether a request needs a claim is the engine's\n * decision: the host claims exactly when the keys are present.\n *\n * Two stores share one shape. The platform store claims through the\n * dashboard (`POST /api/v1/enforce/replay`), so every instance of a resource\n * shares one ledger. The local store keeps claims in this process, which is\n * enough for a single instance; a host that runs several needs the platform\n * store or a shared store of its own.\n *\n * A claim that cannot be made fails closed: a request whose claim keys are\n * incomplete, or whose store errors or cannot answer, is blocked.\n */\n\nimport type { VerifyResult } from './engine/types';\n\nexport interface RequestClaim {\n  /** The engine's `kya_request_claim_scope`. */\n  scope: string;\n  keyId: string;\n  nonce: string;\n  /** Unix seconds: the end of the request's signature window. */\n  expiresUnix: number;\n  /** The client address, when the host resolved one. */\n  sourceIp?: string;\n}\n\n/** `claimed` lets the request through; the others refuse it. */\nexport type RequestClaimOutcome = 'claimed' | 'replay' | 'capacity' | 'unavailable';\n\nexport interface RequestClaimStore {\n  claim(claim: RequestClaim): Promise<RequestClaimOutcome>;\n}\n\n/** Live claims the local store holds, the platform's per-project limit. */\nexport const LOCAL_REQUEST_CLAIM_CAPACITY = 10_000;\n\n/**\n * Seconds a claim is kept past its signature's expiry, the platform ledger's\n * retention, so a verifier's allowed clock skew cannot reopen a used claim.\n */\nexport const REQUEST_CLAIM_RETENTION_SECONDS = 31;\n\n/** The `kya_error_code` a refused claim answers with (engine registry). */\nexport const REQUEST_CLAIM_ERROR_CODE: Record<Exclude<RequestClaimOutcome, 'claimed'>, string> = {\n  replay: 'kyaos/replay',\n  capacity: 'kyaos/replay-capacity',\n  unavailable: 'kyaos/replay-state-unavailable',\n};\n\nexport interface LocalRequestClaimStoreOptions {\n  /** Live claims held at most. Default {@link LOCAL_REQUEST_CLAIM_CAPACITY}. */\n  capacity?: number;\n  /** Epoch milliseconds. Default `Date.now`. */\n  now?: () => number;\n}\n\n/**\n * Claims kept in this process. A claim lives until its signature expires plus\n * {@link REQUEST_CLAIM_RETENTION_SECONDS}; expired claims are swept in expiry\n * order. When it holds `capacity` live claims it answers `capacity` and never\n * evicts one, since evicting a live claim would let its request through again.\n */\nexport function createLocalRequestClaimStore(\n  options: LocalRequestClaimStoreOptions = {}\n): RequestClaimStore {\n  const capacity = options.capacity ?? LOCAL_REQUEST_CLAIM_CAPACITY;\n  const now = options.now ?? Date.now;\n  /** Claim key → the instant (Unix seconds) it may be forgotten. */\n  const live = new Map<string, number>();\n  /** Min-heap of [deadline, key], so the sweep reads claims in expiry order. */\n  const byDeadline: Array<[number, string]> = [];\n\n  const push = (entry: [number, string]) => {\n    byDeadline.push(entry);\n    let i = byDeadline.length - 1;\n    while (i > 0) {\n      const parent = (i - 1) >> 1;\n      if (byDeadline[parent][0] <= byDeadline[i][0]) break;\n      [byDeadline[parent], byDeadline[i]] = [byDeadline[i], byDeadline[parent]];\n      i = parent;\n    }\n  };\n  const pop = () => {\n    const top = byDeadline[0];\n    const last = byDeadline.pop() as [number, string];\n    if (byDeadline.length > 0) {\n      byDeadline[0] = last;\n      let i = 0;\n      for (;;) {\n        const left = 2 * i + 1;\n        const right = left + 1;\n        let smallest = i;\n        if (left < byDeadline.length && byDeadline[left][0] < byDeadline[smallest][0]) {\n          smallest = left;\n        }\n        if (right < byDeadline.length && byDeadline[right][0] < byDeadline[smallest][0]) {\n          smallest = right;\n        }\n        if (smallest === i) break;\n        [byDeadline[smallest], byDeadline[i]] = [byDeadline[i], byDeadline[smallest]];\n        i = smallest;\n      }\n    }\n    return top;\n  };\n\n  return {\n    async claim(claim) {\n      const nowUnix = Math.floor(now() / 1000);\n      while (byDeadline.length > 0 && byDeadline[0][0] <= nowUnix) {\n        const [deadline, key] = pop();\n        if (live.get(key) === deadline) live.delete(key);\n      }\n      const key = `${claim.scope}\\0${claim.keyId}\\0${claim.nonce}`;\n      if (live.has(key)) return 'replay';\n      if (live.size >= capacity) return 'capacity';\n      const deadline = claim.expiresUnix + REQUEST_CLAIM_RETENTION_SECONDS;\n      live.set(key, deadline);\n      push([deadline, key]);\n      return 'claimed';\n    },\n  };\n}\n\nexport interface PlatformRequestClaimStoreOptions {\n  /** Dashboard origin, e.g. `https://kya.vouched.id`. */\n  baseUrl: string;\n  /** The project API key; the dashboard takes the project from it. */\n  apiKey: string;\n  fetch?: typeof fetch;\n  /** Default 2000 ms. A claim that cannot be answered in time is `unavailable`. */\n  timeoutMs?: number;\n}\n\nconst PLATFORM_OUTCOME: Record<number, RequestClaimOutcome> = {\n  200: 'claimed',\n  409: 'replay',\n  429: 'capacity',\n};\n\n/**\n * Claims made in the dashboard's shared ledger, so every instance of a\n * resource refuses a request any of them already accepted. Any answer other\n * than claimed, replay or capacity, and any transport failure, is\n * `unavailable`.\n */\nexport function createPlatformRequestClaimStore(\n  options: PlatformRequestClaimStoreOptions\n): RequestClaimStore {\n  const fetchImpl = options.fetch ?? fetch;\n  const url = `${options.baseUrl.replace(/\\/$/, '')}/api/v1/enforce/replay`;\n  const timeoutMs = options.timeoutMs ?? 2_000;\n  return {\n    async claim(claim) {\n      try {\n        const response = await fetchImpl(url, {\n          method: 'POST',\n          headers: {\n            'Content-Type': 'application/json',\n            Authorization: `Bearer ${options.apiKey}`,\n          },\n          body: JSON.stringify({\n            scope: claim.scope,\n            keyId: claim.keyId,\n            nonce: claim.nonce,\n            expiresUnix: claim.expiresUnix,\n            ...(claim.sourceIp ? { sourceIp: claim.sourceIp } : {}),\n          }),\n          signal: AbortSignal.timeout(timeoutMs),\n        });\n        return PLATFORM_OUTCOME[response.status] ?? 'unavailable';\n      } catch {\n        return 'unavailable';\n      }\n    },\n  };\n}\n\n/**\n * The claim the engine named on `result`: the four keys, none of them (no\n * claim needed), or `incomplete` when a nonce arrived without the rest.\n */\nexport function requestClaimOf(\n  result: VerifyResult\n): Omit<RequestClaim, 'sourceIp'> | 'incomplete' | null {\n  const metadata = result.detectionDetail.metadata ?? {};\n  const scope = metadata.kya_request_claim_scope;\n  const keyId = metadata.kya_request_keyid;\n  const nonce = metadata.kya_request_nonce;\n  const expiresUnix = metadata.kya_request_expires;\n  if (scope === undefined && keyId === undefined && nonce === undefined) return null;\n  if (\n    typeof scope !== 'string' ||\n    scope === '' ||\n    typeof keyId !== 'string' ||\n    keyId === '' ||\n    typeof nonce !== 'string' ||\n    nonce === '' ||\n    typeof expiresUnix !== 'number' ||\n    !Number.isSafeInteger(expiresUnix)\n  ) {\n    return 'incomplete';\n  }\n  return { scope, keyId, nonce, expiresUnix };\n}\n\n/**\n * Make the claim on a final Permit, before the request reaches its handler.\n * Like the other post-verify steps it changes `result` in place, and returns\n * it. A result that is not a Permit lets nothing through and is left as is; a\n * Permit that needs no claim is left as is. A refused claim turns the Permit\n * into a Block carrying the registry code, which renders as 401\n * `kyaos/replay`, 429 `kyaos/replay-capacity` or 503\n * `kyaos/replay-state-unavailable`; its granted scopes are cleared.\n */\nexport async function applyRequestClaim(\n  result: VerifyResult,\n  store: RequestClaimStore,\n  options: { sourceIp?: string } = {}\n): Promise<VerifyResult> {\n  if (result.decision.kind !== 'Permit') return result;\n  const claim = requestClaimOf(result);\n  if (claim === null) return result;\n  let outcome: RequestClaimOutcome = 'unavailable';\n  if (claim !== 'incomplete') {\n    try {\n      outcome = await store.claim(\n        options.sourceIp ? { ...claim, sourceIp: options.sourceIp } : claim\n      );\n    } catch {\n      outcome = 'unavailable';\n    }\n  }\n  if (outcome === 'claimed') return result;\n  result.decision = { kind: 'Block', reason: { kind: 'Unauthenticated' } };\n  result.detectionDetail = {\n    ...result.detectionDetail,\n    grantedScopes: [],\n    metadata: {\n      ...result.detectionDetail.metadata,\n      kya_error_code: REQUEST_CLAIM_ERROR_CODE[outcome],\n    },\n  };\n  return result;\n}\n","import { verifiedBrowserPosture } from './browser-posture';\nexport {\n  applyBrowserPosture,\n  applyBrowserIntegrityStepUp,\n  verifiedBrowserPosture,\n  browserIntegrityChallengeScopes,\n  postureHandlerView,\n  postureOutcomeView,\n  validateBrowserIntegrityChallenge,\n} from './browser-posture';\nexport type { PostureHandlerView } from './browser-posture';\nexport { isConsentRemediableBlock } from './engine/orchestrator/consent-remediable';\nexport {\n  applyRequestClaim,\n  createLocalRequestClaimStore,\n  createPlatformRequestClaimStore,\n  requestClaimOf,\n  LOCAL_REQUEST_CLAIM_CAPACITY,\n  REQUEST_CLAIM_RETENTION_SECONDS,\n  type RequestClaim,\n  type RequestClaimOutcome,\n  type RequestClaimStore,\n} from './request-claim';\n/**\n * Composed-policy (kya-os-engine) evaluation core — runtime-neutral.\n *\n * The single source of truth for \"evaluate a project's composed `/policy-\n * compose` Cedar bundle for one request\", shared by every SDK runtime that\n * enforces in-process: the DNS Gateway worker (edge), `@kya-os/checkpoint-\n * express` (node), and `@kya-os/checkpoint-nextjs` (node + edge). Before this\n * module each runtime hand-rolled the same orchestration against its own\n * intermediate detection shape, risking edge-vs-in-process divergence — the\n * exact thing the engine-as-SSOT mandate forbids.\n *\n * Pure TS over the canonical engine types + `globalThis.crypto.subtle` + an\n * INJECTED compile fn. No WASM import, no `node:*` import, so it loads\n * identically on Node and edge. Each runtime injects its own compiler\n * (`createPolicyEvaluator` on Node via `./policy`; `evaluatePolicy` on edge\n * via `./policy-edge`) and maps the returned engine `Decision` to its own\n * response shape.\n *\n * Three pieces:\n *   1. {@link verifyResultToAuthorizeInput} — project a canonical\n *      {@link VerifyResult} into the engine {@link AuthorizeInput} (category\n *      map, verified-delegation allowlist). The parity SSOT for fact →\n *      policy-input.\n *   2. {@link makeComposedPolicyCache} — compile-once / evaluate-many LRU with\n *      single-flight + `crypto.subtle` keying.\n *   3. {@link evaluateComposedPolicy} — empty-Cedar guard + compile + authorize\n *      + act-gate + divergence, returning a tagged outcome each runtime maps.\n */\n\nimport { isEngineEnforcing } from '@kya-os/checkpoint-shared/policy/enforcement';\n\nimport {\n  NO_EVIDENCE_CATEGORY,\n  withNoEvidenceExclusion,\n} from '@kya-os/checkpoint-shared/policy/enforcement';\nimport { REJECTED_POLICY_PREFIX } from './cedar-nesting';\nimport type { DetectionDetail, VerifyResult } from './engine/types';\nimport type { AuthorizeInput, BlockReason, Decision } from './policy-evaluator';\n\n/**\n * Structural shape of a compiled policy bundle — `{ authorize, free }`. The\n * cache + compile contract reference THIS, not the nominal\n * `PolicyEvaluatorRuntime` class, so a compiler returning either the Node\n * (`./policy`) or edge (`./policy-edge`) `PolicyEvaluatorRuntime` — whose\n * `private` member makes the two class declarations nominally distinct ACROSS\n * subpaths — type-checks uniformly. Both runtimes' evaluators (and a test\n * fake) satisfy this public surface.\n */\nexport interface CompiledPolicy {\n  authorize(input: AuthorizeInput): Decision;\n  free(): void;\n}\n\n// -----------------------------------------------------------------------------\n// 1. AuthorizeInput projection — the cross-runtime parity SSOT.\n// -----------------------------------------------------------------------------\n\n/**\n * RAW engine `verificationMethod` values that represent a\n * CRYPTOGRAPHICALLY-verified identity and therefore map to the\n * `principal.delegation == \"verified\"` posture a composed policy can trust.\n * Deliberately an ALLOWLIST, NOT `!== 'none'` — heuristic (`pattern` /\n * `behavioral` / `network`), failed (`error`), and absent (`none`) methods are\n * all unverified. `kya-http` / `kya-http-delegated` are the draft-kya-http-02\n * §4.3 verified request-signature and delegation methods (both\n * crypto-established). `signature` and `tier1_rfc9421` are both\n * RFC 9421 outcomes but distinct verdicts — see their own comments below.\n */\nconst VERIFIED_VERIFICATION_METHODS = new Set<DetectionDetail['verificationMethod']>([\n  // RFC 9421 signature that passed crypto with a bare (non-DID) keyid, the\n  // KYA-profile downgrade outcome and what legacy hosts report.\n  'signature',\n  // RFC 9421 signature verified against the embedded vendor-key registry\n  // (Web Bot Auth, Tier 1). The engine's own O2 policy arm passes\n  // `delegation: \"verified\"` for this verdict (api.rs verify_http_signed);\n  // omitting it here made every WASM host disagree with the native engine\n  // (#4804).\n  'tier1_rfc9421',\n  'kya-http',\n  'kya-http-delegated',\n  // A2A Agent Card security scheme cryptographically verified — see\n  // docs/architecture/a2a-verification.md. Detail is built AFTER crypto,\n  // same as tier1_rfc9421 above.\n  'a2a',\n]);\n\nconst CREDENTIAL_VERIFICATION_BLOCK_REASONS = new Set<BlockReason['kind']>([\n  'InvalidSignature',\n  'Revoked',\n  'Unauthenticated',\n  'Expired',\n  'OutOfScope',\n  'ParseError',\n]);\n\n/**\n * Credential/protocol verification failures are a fail-closed floor. Tenant\n * Cedar may further restrict verified traffic, but it must never turn a failed\n * signature, revoked credential, missing auth, expired credential, scope miss,\n * or parse failure back into Permit.\n */\nexport function isCredentialVerificationBlock(\n  decision: Decision\n): decision is Extract<Decision, { kind: 'Block' }> {\n  return (\n    decision.kind === 'Block' && CREDENTIAL_VERIFICATION_BLOCK_REASONS.has(decision.reason.kind)\n  );\n}\n\n/**\n * Map the canonical engine `detectionClass` (PascalCase discriminated union) to\n * the `principal.category` string composed policies match on. The AI-crawler\n * carve-out (`isAiCrawler ? 'scraper'`) mirrors the gateway worker.\n */\nfunction mapCategory(detail: DetectionDetail): string {\n  if (detail.isAiCrawler) return 'scraper';\n  switch (detail.detectionClass.type) {\n    case 'Human':\n      return 'human';\n    case 'AiAgent':\n      return 'ai_agent';\n    case 'Bot':\n      return 'bot';\n    case 'IncompleteData':\n      return detail.metadata?.detection_basis === 'no_evidence' ? 'no_evidence' : 'incomplete_data';\n    // 'Automation' is a real member of the shared `DetectionClassSchema`\n    // union (historical detection rows may still carry it), but the\n    // four-variant Rust `DetectionClassDetail` enum can never emit it —\n    // see `rust/CLAUDE.md`'s detection-classes note. Kept here ONLY for\n    // TypeScript exhaustiveness over the wider shared type, not as a\n    // reachable branch; do not add a dedicated `principal.category` value\n    // for it.\n    default:\n      return 'unknown';\n  }\n}\n\nexport interface AuthorizeInputContext {\n  /**\n   * Trusted host configuration for the native HTTP agent lane. Never set from\n   * request headers. The host must complete status/revision/replay admission\n   * before projecting a Permit result. Existing TS hosts do not enable this\n   * until they implement that native boundary; .NET owns the qualified path.\n   */\n  nativeHttp?: boolean;\n  /** Tenant identifier — the project id whose composed policy is evaluated. */\n  tenantId: string;\n  /** Request path → `resource` + `resource.path`. Defaults to `'/'`. */\n  path?: string;\n  /**\n   * Cryptographically-verified agent DID, when the host resolved one. Used\n   * SOLELY to mark `delegation: 'verified'` — it is deliberately NOT written to\n   * `AuthorizeInput.agentDid` (the Cedar principal id). Only some hosts resolve a\n   * DID (the edge worker / Fly MCP PEP do; the SDK middlewares may not), so\n   * binding the principal id to it would make the SAME composed bundle decide\n   * differently per host — and generated `/policy-compose` Cedar matches on\n   * principal ATTRIBUTES (name/category/delegation), never the principal id, so\n   * the id is decision-inert. Leaving it unset keeps the projection\n   * host-independent. Omit when none.\n   */\n  agentDid?: string;\n}\n\n/**\n * Project a verified request's detection facts into the engine's\n * `AuthorizeInput`. Facts a request cannot supply are left unset → the engine\n * defaults them (`''`) so an attribute clause evaluates `false` rather than\n * erroring.\n */\nexport function verifyResultToAuthorizeInput(\n  result: VerifyResult,\n  ctx: AuthorizeInputContext\n): AuthorizeInput {\n  const detail = result.detectionDetail;\n  const requestPath = ctx.path ?? '/';\n\n  const verifiedMethod = detail.verificationMethod\n    ? VERIFIED_VERIFICATION_METHODS.has(detail.verificationMethod)\n    : false;\n  const verified = verifiedMethod || Boolean(ctx.agentDid);\n\n  const nativeAgent =\n    ctx.nativeHttp === true &&\n    result.decision.kind === 'Permit' &&\n    detail.verificationMethod === 'kya-http-delegated' &&\n    detail.assurance === 'delegated' &&\n    detail.metadata?.kya_delegation_lane === 'agent' &&\n    typeof detail.metadata.agent_did === 'string' &&\n    detail.metadata.agent_did.trim() !== '' &&\n    typeof detail.metadata.kya_request_keyid === 'string' &&\n    detail.metadata.kya_request_keyid.trim() !== '' &&\n    typeof detail.metadata.kya_request_nonce === 'string' &&\n    detail.metadata.kya_request_nonce.trim() !== '' &&\n    typeof detail.metadata.kya_request_expires === 'number' &&\n    Number.isSafeInteger(detail.metadata.kya_request_expires);\n  const authorizingUserDid = nativeAgent ? detail.metadata?.kya_authorizing_user_did : undefined;\n\n  // `ctx.agentDid` is captured ONLY in `verified` above; it is intentionally NOT\n  // emitted as `AuthorizeInput.agentDid` (the Cedar principal id) — see\n  // AuthorizeInputContext.agentDid (legacy host-independence). Native identity\n  // below comes exclusively from the accepted agent-lane engine output.\n  return {\n    action: 'request',\n    resource: requestPath,\n    path: requestPath,\n    tenantId: ctx.tenantId,\n    ...(verifiedBrowserPosture(result)\n      ? { integrity: verifiedBrowserPosture(result)!.verdict }\n      : {}),\n    ...(nativeAgent ? { agentDid: detail.metadata!.agent_did as string } : {}),\n    ...(typeof authorizingUserDid === 'string' && authorizingUserDid.trim() !== ''\n      ? { authorizingUserDid }\n      : {}),\n    name: detail.detectedAgent?.name,\n    category: mapCategory(detail),\n    delegation: verified ? 'verified' : '',\n    // Forward the engine-verified delegation scopes into `context.granted_scopes`\n    // so a scope-gated carve-out (`unless { granted_scopes.contains(\"S\") }`) is\n    // satisfiable — the engine already verified them; the host does NOT re-decode.\n    ...(detail.grantedScopes?.length ? { grantedScopes: detail.grantedScopes } : {}),\n    // Forward the engine-stamped assurance tier (draft-kya-http-02 §1) into\n    // `context.assurance` so an assurance-gated rule can match. The `\"anonymous\"`\n    // default is OMITTED — the engine's build_context re-supplies it — so the JSON\n    // byte shape stays IDENTICAL to the .NET AuthorizeInputProjection (which omits\n    // it too); forwarding it here would diverge Express from .NET on the same\n    // verdict. Also omitted when the engine stamped none.\n    // REASON: `detail.assurance` is a loose `string` on the detail schema (kept\n    // decoupled from `../policy` AssuranceTierSchema to avoid a core→policy module\n    // dep, mirroring `riskLevel`); the engine only ever stamps a valid tier, so\n    // narrow to the AuthorizeInput field type at this boundary.\n    ...(detail.assurance && detail.assurance !== 'anonymous'\n      ? { assurance: detail.assurance as AuthorizeInput['assurance'] }\n      : {}),\n    // Detection confidence → `principal.confidence` (a Cedar Long). Always\n    // available on `DetectionDetail` (never optional), unlike the other\n    // conditionally-forwarded facts above — rounded to the engine's integer\n    // Long attribute. No existing composed bundle can already reference\n    // `principal.confidence` (it did not exist before this attribute), so\n    // forwarding it unconditionally changes no existing verdict.\n    confidence: Math.round(detail.confidence),\n    // Forward the engine-echoed network context (when the request carried\n    // one) into `context.ip_routing_type` / `context.is_proxy` /\n    // `context.proxy_type` / `context.network_confidence`. Absent on every\n    // protocol besides PlainHttp and on any PlainHttp request that supplied\n    // none — the same absent-stays-absent posture as `assurance`. The two\n    // finer-grained proxy facts are further conditional on a proxy verdict\n    // having been computed at all, same as `isProxy`.\n    ...(result.network\n      ? {\n          ipRoutingType: result.network.routingType,\n          ...(result.network.proxy\n            ? {\n                isProxy: result.network.proxy.isProxy,\n                proxyType: result.network.proxy.proxyType,\n                networkConfidence: result.network.proxy.confidence,\n              }\n            : {}),\n        }\n      : {}),\n  };\n}\n\n// -----------------------------------------------------------------------------\n// 2. Compile-once / evaluate-many cache.\n// -----------------------------------------------------------------------------\n\n/**\n * Compile a `(language, source)` bundle into a reusable evaluator. Injected so\n * each runtime supplies its target's compiler — Node `createPolicyEvaluator`\n * (sync) wrapped, or edge `evaluatePolicy` (async). Throws on invalid source /\n * unsupported language (surfaced by {@link evaluateComposedPolicy} as an\n * `error` outcome).\n */\nexport type ComposedPolicyCompile = (\n  language: string,\n  source: string\n) => CompiledPolicy | Promise<CompiledPolicy>;\n\nexport interface ComposedPolicyCacheLogger {\n  warn(message: string, fields: Record<string, unknown>): void;\n}\n\nexport interface ComposedPolicyCacheOptions {\n  compile: ComposedPolicyCompile;\n  /** Max distinct compiled bundles held (LRU). Default 50. */\n  cacheMax?: number;\n  logger?: ComposedPolicyCacheLogger;\n}\n\nexport interface ComposedPolicyCache {\n  getOrCompile(projectId: string, language: string, source: string): Promise<CompiledPolicy>;\n}\n\nconst DEFAULT_COMPILE_CACHE_MAX = 50;\n\nfunction isRejectedPolicy(error: unknown): boolean {\n  const message = error instanceof Error ? error.message : error;\n  return typeof message === 'string' && message.startsWith(REJECTED_POLICY_PREFIX);\n}\n\nfunction readingNoEvidenceAsHuman(policy: CompiledPolicy): CompiledPolicy {\n  return {\n    authorize: (input) =>\n      policy.authorize(\n        input.category === NO_EVIDENCE_CATEGORY ? { ...input, category: 'human' } : input\n      ),\n    free: () => policy.free(),\n  };\n}\n\nexport async function compileWithNoEvidenceExclusion(\n  source: string,\n  compile: (source: string) => CompiledPolicy | Promise<CompiledPolicy>,\n  onFallback?: (error: unknown) => void\n): Promise<CompiledPolicy> {\n  const served = withNoEvidenceExclusion(source);\n  try {\n    return await compile(served);\n  } catch (error) {\n    if (served === source || !isRejectedPolicy(error)) throw error;\n    const authored = readingNoEvidenceAsHuman(await compile(source));\n    onFallback?.(error);\n    return authored;\n  }\n}\n\n/**\n * Build a bounded, single-flight compile cache keyed by `projectId:hash(source)`\n * — a policy edit yields a new key (the stale evaluator ages out). Stores the\n * in-flight PROMISE (not the resolved evaluator) so concurrent callers for the\n * same key join ONE compile rather than each compiling a ~2 MB WASM evaluator\n * and orphaning all but the last (a WASM-memory leak). A rejected compile is\n * evicted so a later request retries. Eviction DROPS THE REFERENCE; it does NOT\n * call `free()` — the evaluator can be shared with an in-flight `authorize()`,\n * so freeing on eviction risks a use-after-free against freed WASM; the\n * wasm-bindgen FinalizationRegistry reclaims it once unreferenced.\n */\nexport function makeComposedPolicyCache(opts: ComposedPolicyCacheOptions): ComposedPolicyCache {\n  const { compile, logger } = opts;\n  const cacheMax = opts.cacheMax ?? DEFAULT_COMPILE_CACHE_MAX;\n  const cache = new Map<string, Promise<CompiledPolicy>>();\n\n  return {\n    async getOrCompile(projectId, language, source) {\n      const key = `${projectId}:${await hashSource(source)}`;\n      const existing = cache.get(key);\n      if (existing) {\n        // LRU touch — move to most-recent.\n        cache.delete(key);\n        cache.set(key, existing);\n        return existing;\n      }\n\n      // Single-flight: cache the PROMISE synchronously (no await between the get\n      // above and the set here) so concurrent callers join THIS compile.\n      const pending = compileWithNoEvidenceExclusion(\n        source,\n        (text) => compile(language, text),\n        (error) =>\n          logger?.warn('[ComposedPolicy] rewritten policy rejected; compiling the authored text', {\n            projectId,\n            error: error instanceof Error ? error.message : String(error),\n          })\n      );\n      cache.set(key, pending);\n      pending.catch((error) => {\n        if (cache.get(key) === pending && !isRejectedPolicy(error)) cache.delete(key);\n      });\n\n      while (cache.size > cacheMax) {\n        const oldest = cache.keys().next().value as string | undefined;\n        if (oldest === undefined || oldest === key) break;\n        cache.delete(oldest);\n      }\n\n      return pending;\n    },\n  };\n}\n\n/** SHA-256 of the policy source, truncated — the cache-key fingerprint. */\nasync function hashSource(text: string): Promise<string> {\n  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));\n  return Array.from(new Uint8Array(digest))\n    .map((b) => b.toString(16).padStart(2, '0'))\n    .join('')\n    .slice(0, 32);\n}\n\n// -----------------------------------------------------------------------------\n// 3. Evaluation orchestration.\n// -----------------------------------------------------------------------------\n\n/**\n * Composed-policy languages every runtime's injected compiler supports today.\n * MUST track {@link ComposedPolicyCompile}'s languages — adding Rego means\n * shipping the rego evaluator across runtimes AND adding it here. Read\n * EXPLICITLY (no `?? 'cedar'` default): a null/unsupported language means \"no\n * composed policy\", which must fall through to the baseline, never be silently\n * treated as Cedar.\n */\nconst SUPPORTED_COMPOSED_LANGUAGES = new Set<string>(['cedar']);\n\n/** The composed-policy fields the host reads off the project's `PolicyConfig`. */\nexport interface ComposedPolicyFlags {\n  policyLanguage: string | null | undefined;\n  policySourceText: string | null | undefined;\n  engineEnforcementEnabled: boolean | null | undefined;\n  /** Master enable toggle — enforcement off (`false`) ⇒ OBSERVE, never act. */\n  enabled: boolean | null | undefined;\n}\n\nexport type ComposedPolicyOutcome =\n  /** No composed policy (null/unsupported language or blank source). */\n  | { status: 'no-policy' }\n  /** Compile/authorize fault — shadow keeps the baseline; an enforcing host fails closed. */\n  | { status: 'error'; error: unknown }\n  /** Computed but NOT acting (flag off / master off). Use for telemetry. */\n  | { status: 'shadow'; engineDecision: Decision; diverged: boolean }\n  /** Acting — replace the baseline with `engineDecision`. */\n  | { status: 'acting'; engineDecision: Decision; diverged: boolean };\n\nexport interface EvaluateComposedPolicyArgs {\n  cache: ComposedPolicyCache;\n  projectId: string;\n  flags: ComposedPolicyFlags;\n  authorizeInput: AuthorizeInput;\n  /** Baseline (structured/bespoke) decision kind — for divergence telemetry. */\n  baselineDecisionKind: Decision['kind'];\n}\n\n/**\n * Evaluate a project's composed policy for one request. Pure orchestration: the\n * caller owns fetching the policy, building the `authorizeInput` (typically via\n * {@link verifyResultToAuthorizeInput}), computing the baseline decision, and\n * mapping/logging the outcome. Never throws — a compile/authorize fault returns\n * `{ status: 'error' }`; an enforcing host (`isEngineEnforcing`) must fail closed.\n */\nexport async function evaluateComposedPolicy(\n  args: EvaluateComposedPolicyArgs\n): Promise<ComposedPolicyOutcome> {\n  const { cache, projectId, flags, authorizeInput, baselineDecisionKind } = args;\n  const language = flags.policyLanguage;\n  const source = flags.policySourceText;\n\n  // Empty-Cedar guard: blank source must NEVER reach the evaluator (empty Cedar\n  // compiles to deny-all). `.trim()`, not bare truthiness — whitespace is truthy.\n  if (!language || !SUPPORTED_COMPOSED_LANGUAGES.has(language) || !source || source.trim() === '') {\n    return { status: 'no-policy' };\n  }\n\n  let engineDecision: Decision;\n  try {\n    const evaluator = await cache.getOrCompile(projectId, language, source);\n    engineDecision = evaluator.authorize(authorizeInput);\n  } catch (error) {\n    return { status: 'error', error };\n  }\n\n  const diverged = engineDecision.kind !== baselineDecisionKind;\n  // ACT only when the project is flagged AND master enforcement is on (policy\n  // present + enforcement off = OBSERVE).\n  return isEngineEnforcing(flags)\n    ? { status: 'acting', engineDecision, diverged }\n    : { status: 'shadow', engineDecision, diverged };\n}\n\nexport {\n  createBrowserIntegrityChallengeResolver,\n  type BrowserIntegrityChallengeOptions,\n} from './browser-integrity-challenge';\n","/**\n * The per-project composed-policy context the SDK middleware builds once and\n * drives once per request: it fetches the project's `PolicyConfig`, runs the\n * core in `./composed-policy` (empty-Cedar guard, compile-once cache, act-gate,\n * divergence, the `verifyResultToAuthorizeInput` projection), maps the outcome\n * to a decision swap, and logs.\n *\n * Express and Next.js both build theirs here, so they decide the same way for\n * the same policy. The Cedar compiler is injected, so this module loads no\n * evaluator build of its own:\n *   - Node: `(language, source) => createPolicyEvaluator(source)` (`./policy`)\n *   - Edge: `(language, source) => evaluatePolicy(language, source)` (`./policy-edge`)\n */\n\nimport { requestPresentedCredential } from '@kya-os/checkpoint-shared/kya-http';\nimport { isEngineEnforcing } from '@kya-os/checkpoint-shared/policy/enforcement';\nimport type { PolicyFetcher } from '@kya-os/checkpoint-shared/policy/fetcher';\n\nimport {\n  evaluateComposedPolicy,\n  isCredentialVerificationBlock,\n  makeComposedPolicyCache,\n  verifyResultToAuthorizeInput,\n  type ComposedPolicyCompile,\n} from './composed-policy';\nimport type { VerifyResult } from './engine/types';\nimport type { Decision } from './policy-evaluator';\n\n/** Dashboard the policy fetch defaults to when no base URL is set. */\nexport const DEFAULT_DASHBOARD_URL = 'https://kya.vouched.id';\n\n/**\n * Telemetry sink. The shadow-divergence signal is the go/no-go instrument for\n * flipping a project to ENFORCE.\n */\nexport interface ComposedPolicyLogger {\n  shadowDivergence(info: ShadowDivergenceInfo): void;\n  evaluationError(projectId: string, error: unknown): void;\n  compileFallback?(projectId: string, error: string): void;\n}\n\nexport interface ShadowDivergenceInfo {\n  projectId: string;\n  path?: string;\n  /** The engine's composed-policy decision kind. */\n  engineDecision: Decision['kind'];\n  /** The structured decision kind it diverged from. */\n  structuredDecision: Decision['kind'];\n  detectionClass: string;\n  verificationMethod?: string;\n  confidence: number;\n  agentName?: string;\n}\n\nconst NOOP_LOGGER: ComposedPolicyLogger = {\n  shadowDivergence: () => {},\n  evaluationError: () => {},\n};\n\n/** One composed-policy evaluation: the decision to enforce, and whether it replaced the structured one. */\nexport interface ComposedPolicyApplyResult {\n  decision: Decision;\n  acted: boolean;\n  composedBlobHash?: string;\n}\n\nexport interface ComposedPolicyContext {\n  /**\n   * Evaluate the project's composed policy for one request. Reads\n   * `result.decision` as the structured baseline for the divergence comparison;\n   * the caller applies `acted ? decision` afterwards (see\n   * {@link applyComposedPolicy}). Throws when an ENFORCING project's bundle\n   * cannot be evaluated, or when the policy cannot be read (origin\n   * unavailable, or the API key refused); the middleware answers 503 in\n   * enforce mode.\n   */\n  apply(result: VerifyResult, path: string | undefined): Promise<ComposedPolicyApplyResult>;\n  /**\n   * Resolve the org's trusted Layer-2 delegation root DIDs from the project's\n   * policy payload. The middleware forwards these into the engine's\n   * `ContextSpec.trustedDelegationRoots` on requests presenting a credential.\n   * Optional so an injected context (advanced use and tests) need not implement\n   * it: absence means no roots, and the engine rejects delegation. A policy\n   * origin outage propagates `PolicyUnavailableError`, and a refused API key\n   * `PolicyAuthError`; the middleware answers 503 in enforce mode.\n   */\n  trustedDelegationRoots?(): Promise<string[]>;\n}\n\nexport interface MakeComposedPolicyContextOptions {\n  projectId: string;\n  /** Fetches the project's `PolicyConfig` (carries the composed-policy fields). */\n  fetcher: PolicyFetcher;\n  /** The runtime's Cedar compiler (see the module comment). */\n  compile: ComposedPolicyCompile;\n  logger?: ComposedPolicyLogger;\n  /** Max distinct compiled bundles cached (LRU); the core's default when unset. */\n  cacheMax?: number;\n}\n\nexport function makeComposedPolicyContext(\n  opts: MakeComposedPolicyContextOptions\n): ComposedPolicyContext {\n  const { projectId, fetcher } = opts;\n  const logger = opts.logger ?? NOOP_LOGGER;\n  const cache = makeComposedPolicyCache({\n    compile: opts.compile,\n    cacheMax: opts.cacheMax,\n    logger: {\n      warn: (_message, fields) =>\n        (logger.compileFallback ?? warnCompileFallback)(\n          String(fields.projectId),\n          String(fields.error)\n        ),\n    },\n  });\n\n  return {\n    async apply(result, path): Promise<ComposedPolicyApplyResult> {\n      const structured: ComposedPolicyApplyResult = { decision: result.decision, acted: false };\n      if (isCredentialVerificationBlock(result.decision)) return structured;\n\n      // PolicyFetcher.getPolicy throws PolicyUnavailableError on a strict\n      // origin outage and PolicyAuthError on a refused key, which propagate\n      // so the middleware answers 503 in enforce mode.\n      const policy = await fetcher.getPolicy(projectId);\n\n      const outcome = await evaluateComposedPolicy({\n        cache,\n        projectId,\n        flags: {\n          policyLanguage: policy.policyLanguage,\n          policySourceText: policy.policySourceText,\n          engineEnforcementEnabled: policy.engineEnforcementEnabled,\n          enabled: policy.enabled,\n        },\n        authorizeInput: verifyResultToAuthorizeInput(result, { tenantId: projectId, path }),\n        baselineDecisionKind: result.decision.kind,\n      });\n\n      // Divergence telemetry (acting OR shadow): the engine decided differently\n      // than the structured baseline. `result.decision` is still the baseline\n      // here; the caller swaps it only after this returns.\n      if ((outcome.status === 'acting' || outcome.status === 'shadow') && outcome.diverged) {\n        logger.shadowDivergence({\n          projectId,\n          path,\n          engineDecision: outcome.engineDecision.kind,\n          structuredDecision: result.decision.kind,\n          detectionClass: result.detectionDetail.detectionClass.type,\n          verificationMethod: result.detectionDetail.verificationMethod,\n          confidence: result.detectionDetail.confidence,\n          agentName: result.detectionDetail.detectedAgent?.name,\n        });\n      }\n\n      if (outcome.status === 'error') {\n        logger.evaluationError(projectId, outcome.error);\n        if (isEngineEnforcing(policy)) throw outcome.error;\n        return structured;\n      }\n      if (outcome.status === 'acting') {\n        return {\n          decision: outcome.engineDecision,\n          acted: true,\n          // Echo the policy revision pin with the decision it produced.\n          // Conditional spread: absent upstream stays absent here.\n          ...(policy.policySourceHash ? { composedBlobHash: policy.policySourceHash } : {}),\n        };\n      }\n      // 'shadow' | 'no-policy': the structured decision stands.\n      return structured;\n    },\n\n    async trustedDelegationRoots(): Promise<string[]> {\n      // The same cached PolicyFetcher `apply` uses, so the early root\n      // resolution and the later composed-policy fetch coalesce into one\n      // network call. A strict origin outage or a refused key propagates, so\n      // the middleware answers a retryable 503 in enforce mode.\n      const policy = await fetcher.getPolicy(projectId);\n      return policy.trustedDelegationRoots ?? [];\n    },\n  };\n}\n\n/**\n * Evaluate the composed policy and swap `result.decision` in place when the\n * engine acts. The middleware calls it before the detection reporter and\n * before render, so the reporter records, and the response renders, the\n * enforced decision. A fault on an enforcing project propagates so the\n * middleware answers 503 instead of allowing.\n */\nexport async function applyComposedPolicy(\n  context: ComposedPolicyContext | null,\n  result: VerifyResult,\n  path: string | undefined\n): Promise<void> {\n  if (!context) return;\n  const outcome = await context.apply(result, path);\n  if (outcome.acted) {\n    result.decision = outcome.decision;\n    if (outcome.composedBlobHash) {\n      result.composedBlobHash = outcome.composedBlobHash;\n    }\n  }\n}\n\n/**\n * Resolves the org's trusted delegation roots (empty when none), from whatever\n * source the middleware has: the composed context's accessor, or a\n * `projectId`-only policy fetch when no context exists.\n */\nexport type TrustedDelegationRootsResolver = () => Promise<string[]>;\n\n/**\n * The org trusted-delegation roots to pass to the engine for this request.\n * `undefined` (leaving the verify options unchanged) unless a resolver is\n * configured and the request presents a KYA credential (a kya-http signature,\n * a delegation-proof header, or a VC-JWT bearer), so the human and\n * no-credential path never pays the policy fetch.\n */\nexport async function resolveTrustedDelegationRootsForRequest(\n  resolver: TrustedDelegationRootsResolver | null,\n  headers: Headers | Record<string, unknown>\n): Promise<string[] | undefined> {\n  if (!resolver) return undefined;\n  if (!requestPresentedCredential(headers)) return undefined;\n  const roots = await resolver();\n  return roots.length > 0 ? roots : undefined;\n}\n\nfunction warnCompileFallback(projectId: string, error: string): void {\n  console.warn(\n    '[checkpoint/composed-policy] rewritten policy rejected; compiled the authored text',\n    { projectId, error }\n  );\n}\n\n/**\n * Debug logger mirroring the gateway worker's evaluation telemetry. The\n * middleware wires it only when `config.debug` is set, so the default stays\n * silent.\n */\nexport const consoleComposedPolicyLogger: ComposedPolicyLogger = {\n  shadowDivergence(info) {\n    // eslint-disable-next-line no-console -- debug-gated telemetry (see withCheckpoint)\n    console.warn('[checkpoint/composed-policy] shadow-divergence', info);\n  },\n  evaluationError(projectId, error) {\n    // eslint-disable-next-line no-console -- debug-gated telemetry (see withCheckpoint)\n    console.error(`[checkpoint/composed-policy] evaluation failed for ${projectId}:`, error);\n  },\n  compileFallback: warnCompileFallback,\n};\n"],"mappings":";;;;;;AA0CA,MAAa,+BAA+B;;;;;AAM5C,MAAa,kCAAkC;;AAG/C,MAAa,2BAAoF;CAC/F,QAAQ;CACR,UAAU;CACV,aAAa;AACf;;;;;;;AAeA,SAAgB,6BACd,UAAyC,CAAC,GACvB;CACnB,MAAM,WAAW,QAAQ,YAAA;CACzB,MAAM,MAAM,QAAQ,OAAO,KAAK;;CAEhC,MAAM,uBAAO,IAAI,IAAoB;;CAErC,MAAM,aAAsC,CAAC;CAE7C,MAAM,QAAQ,UAA4B;EACxC,WAAW,KAAK,KAAK;EACrB,IAAI,IAAI,WAAW,SAAS;EAC5B,OAAO,IAAI,GAAG;GACZ,MAAM,SAAU,IAAI,KAAM;GAC1B,IAAI,WAAW,OAAO,CAAC,MAAM,WAAW,EAAE,CAAC,IAAI;GAC/C,CAAC,WAAW,SAAS,WAAW,MAAM,CAAC,WAAW,IAAI,WAAW,OAAO;GACxE,IAAI;EACN;CACF;CACA,MAAM,YAAY;EAChB,MAAM,MAAM,WAAW;EACvB,MAAM,OAAO,WAAW,IAAI;EAC5B,IAAI,WAAW,SAAS,GAAG;GACzB,WAAW,KAAK;GAChB,IAAI,IAAI;GACR,SAAS;IACP,MAAM,OAAO,IAAI,IAAI;IACrB,MAAM,QAAQ,OAAO;IACrB,IAAI,WAAW;IACf,IAAI,OAAO,WAAW,UAAU,WAAW,KAAK,CAAC,KAAK,WAAW,SAAS,CAAC,IACzE,WAAW;IAEb,IAAI,QAAQ,WAAW,UAAU,WAAW,MAAM,CAAC,KAAK,WAAW,SAAS,CAAC,IAC3E,WAAW;IAEb,IAAI,aAAa,GAAG;IACpB,CAAC,WAAW,WAAW,WAAW,MAAM,CAAC,WAAW,IAAI,WAAW,SAAS;IAC5E,IAAI;GACN;EACF;EACA,OAAO;CACT;CAEA,OAAO,EACL,MA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