{"version":3,"file":"pipeline.mjs","names":[],"sources":["../src/pipeline/pipeline.ts"],"sourcesContent":["/**\n * The request pipeline every `withCheckpoint` adapter runs: everything between\n * translating the framework's request and adapting the rendered response.\n *\n * The adapter supplies the engine (its runtime's `./orchestrator` build), the\n * Cedar compiler its runtime can load, and per request the translated request\n * plus a few accessors. The pipeline verifies, applies browser posture, the\n * project's composed Cedar policy and the browser-integrity step-up, claims an\n * accepted signed request, reports, calls `onResult`, resolves challenge\n * context and renders. The adapter turns the rendered response into its\n * framework's response, and answers 503 when the pipeline throws.\n *\n * Nothing here imports an engine build, so the module loads on every runtime\n * (Node, Next.js Edge, Workers).\n */\n\nimport {\n  LOOPBACK_ORIGINS_WARNING,\n  postureRequestFromHeaders,\n  validateBrowserPostureConfig,\n} from '@kya-os/checkpoint-shared/browser-posture';\nimport {\n  resolveChallengeContext,\n  selectBodyReadable200,\n} from '@kya-os/checkpoint-shared/host-adapter';\nimport { PolicyFetcher } from '@kya-os/checkpoint-shared/policy/fetcher';\n\nimport {\n  applyBrowserIntegrityStepUp,\n  applyBrowserPosture,\n  postureHandlerView,\n  validateBrowserIntegrityChallenge,\n  type PostureHandlerView,\n} from '../browser-posture';\nimport {\n  applyComposedPolicy,\n  consoleComposedPolicyLogger,\n  DEFAULT_DASHBOARD_URL,\n  makeComposedPolicyContext,\n  resolveTrustedDelegationRootsForRequest,\n  type ComposedPolicyContext,\n  type MakeComposedPolicyContextOptions,\n  type TrustedDelegationRootsResolver,\n} from '../composed-policy-context';\nimport { makeEngineDefaults } from '../engine/adapters/engine-defaults';\nimport {\n  makeResolutionWarmer,\n  type ResolutionWarmerEngine,\n} from '../engine/adapters/resolution-warmer';\nimport { isConsentRemediableBlock } from '../engine/orchestrator/consent-remediable';\nimport type {\n  IncomingHttpLike,\n  renderDecisionAsResponse as RenderDecision,\n  VerifyRequestOpts,\n} from '../engine/orchestrator';\nimport type { VerifyResult } from '../engine/types';\nimport { makeDetectionReporter, type DetectionReporter, type ReporterContext } from '../reporter';\nimport {\n  applyRequestClaim,\n  createLocalRequestClaimStore,\n  createPlatformRequestClaimStore,\n  type RequestClaimStore,\n} from '../request-claim';\nimport type { VendorKeyEdgeOptions } from '../vendor-keys/feed';\nimport type { CheckpointHostConfig } from './config';\n\n/** The engine an adapter runs: one `./orchestrator` build of this package. */\nexport interface PipelineEngine {\n  // Typed with the edge options, which add `waitUntil`; the Node and bundler\n  // builds take the same call and ignore it.\n  verifyRequest: (\n    req: IncomingHttpLike,\n    opts: VerifyRequestOpts & VendorKeyEdgeOptions\n  ) => Promise<VerifyResult>;\n  renderDecisionAsResponse: typeof RenderDecision;\n}\n\n/** The Cedar compiler a composed-policy context uses. */\nexport type PolicyCompile = MakeComposedPolicyContextOptions['compile'];\n\n/** What an adapter supplies once, when it builds its middleware. */\nexport interface PipelineHost<Config> {\n  /** The SDK the detection reporter names, so the dashboard can version-gate it. */\n  sdk: { name: string; version: string; runtime: 'node' | 'edge' };\n  /**\n   * Loads the engine. A rejection is answered by the request that asked (the\n   * adapter's 503), and the next request tries again.\n   */\n  loadEngine: () => Promise<PipelineEngine>;\n  /**\n   * The Cedar compiler for the project's composed policy. Called once, only\n   * when the pipeline builds the composed-policy context itself (`projectId`\n   * set, no `composedPolicyEnforcer` injected).\n   */\n  policyCompiler: (config: Config) => PolicyCompile;\n  /** Host-specific setup, run once after the configuration is checked; it may throw. */\n  start?: (config: Config) => void;\n  /**\n   * A persistent host's resolution engine (the orchestrator entry's\n   * `resolutionEngine`). With it and a trusted-roots source, the engine's\n   * DID document and status-list needs are answered from a background\n   * warmer and the request path never fetches; without it they are fetched\n   * inline.\n   */\n  warmerEngine?: ResolutionWarmerEngine;\n}\n\n/** A request's headers, as the framework holds them. */\nexport type CheckpointRequestHeaders = Headers | Record<string, string | string[] | undefined>;\n\n/** What an adapter supplies per request. */\nexport interface PipelineRequest<Req> {\n  /** The framework's request, handed to `onResult` and `resolveDelegationChallenge`. */\n  request: Req;\n  /** The request in the engine's shape. Called once, after the engine has loaded. */\n  translate: () => IncomingHttpLike | Promise<IncomingHttpLike>;\n  headers: CheckpointRequestHeaders;\n  /** The full request path without its query: what verification saw. */\n  path: string;\n  /** The client address the adapter's `clientIpPolicy` vouches for, if any. */\n  clientIp: () => string | null | undefined;\n  /** The dashboard report's request context. Called only when reporting. */\n  reportContext: () => ReporterContext;\n  /** Registers work that outlives the response (Edge, Workers). */\n  waitUntil?: (promise: Promise<unknown>) => void;\n  /** Called with the browser-posture outcome as soon as it is known, before `onResult`. */\n  onPostureOutcome?: (outcome: PostureHandlerView) => void;\n}\n\n/** What the pipeline hands back for the adapter to send. */\nexport interface PipelineOutcome {\n  rendered: ReturnType<typeof RenderDecision>;\n  result: VerifyResult;\n}\n\n/** One request through the pipeline. Throws on any fault; the adapter answers 503. */\nexport type CheckpointPipeline<Req> = (input: PipelineRequest<Req>) => Promise<PipelineOutcome>;\n\n/**\n * Build the pipeline for one `withCheckpoint` call. Throws on an invalid\n * configuration.\n */\nexport function makeCheckpointPipeline<Req, Config extends CheckpointHostConfig<Req>>(\n  config: Config,\n  host: PipelineHost<Config>\n): CheckpointPipeline<Req> {\n  validateHostConfig(config);\n  host.start?.(config);\n  const engine = memoizeEngine(host.loadEngine);\n  // Start loading now; a failure is answered by the first request that needs it.\n  engine().catch(() => undefined);\n  const opts = makeEngineDefaults(config);\n  const reporter = buildReporter(config, host.sdk);\n  const policySource = projectPolicySource(config);\n  const composed = buildComposedContext<Req, Config>(config, host, policySource);\n  const requestClaimStore = buildRequestClaimStore(config);\n  const trustedRootsResolver = buildTrustedRootsResolver(config, composed, policySource);\n\n  // A persistent host answers the engine's needs from a warmer, so the request\n  // path never fetches: the roots are fetched at startup and refreshed every\n  // 30 s off the request thread, and any other DID document or status list a\n  // request names is answered pending (503 identity-pending or status-pending)\n  // while a background fetch starts. Without a roots source there is no warmer,\n  // and needs are fetched inline.\n  const warmer =\n    host.warmerEngine && trustedRootsResolver\n      ? makeResolutionWarmer({\n          rootsSource: trustedRootsResolver,\n          engine: host.warmerEngine,\n          fetch: config.adapters?.fetch,\n          logger: config.debug ? (msg: string) => console.warn(msg) : undefined,\n        })\n      : undefined;\n  warmer?.start();\n  const verifyOpts = warmer ? { ...opts, resolutionHost: warmer.host } : opts;\n  // A warmer reads the project's policy as it starts. A Node host without one\n  // reads it once here, so a refused key or an unreachable origin is logged\n  // when the host starts rather than by its first visitor, and the first\n  // requests wait for this read instead of fetching again. Not on the edge,\n  // where a module may not do I/O outside a request.\n  const startupRead =\n    policySource && !warmer && host.sdk.runtime === 'node'\n      ? policySource.fetcher.getPolicy(policySource.projectId).then(\n          () => undefined,\n          () => undefined\n        )\n      : undefined;\n\n  return async function runCheckpointPipeline(input) {\n    const { verifyRequest, renderDecisionAsResponse } = await engine();\n    // On a credential-bearing request, pin the engine's delegation chains to\n    // the org's trusted roots (resolved from the same cached policy payload).\n    // Omitted otherwise, so the options are unchanged.\n    const [translated, rootsResult] = await Promise.allSettled([\n      input.translate(),\n      servedWhenObserving(\n        config,\n        async () => {\n          if (startupRead) await startupRead;\n          return resolveTrustedDelegationRootsForRequest(trustedRootsResolver, input.headers);\n        },\n        undefined\n      ),\n    ]);\n    if (translated.status === 'rejected') throw translated.reason;\n    if (rootsResult.status === 'rejected') throw rootsResult.reason;\n    const httpLike = translated.value;\n    const trustedDelegationRoots = rootsResult.value;\n    const result = await verifyRequest(httpLike, {\n      ...verifyOpts,\n      ...(trustedDelegationRoots ? { trustedDelegationRoots } : {}),\n      ...(input.waitUntil ? { waitUntil: input.waitUntil } : {}),\n    });\n    await applyBrowserPosture(\n      result,\n      postureRequestFromHeaders(headerReader(input.headers)),\n      config.browserPosture,\n      config.projectId\n    );\n    if (input.onPostureOutcome) {\n      const postureOutcome = postureHandlerView(result);\n      if (postureOutcome) input.onPostureOutcome(postureOutcome);\n    }\n    // When the project's deployed Cedar policy acts, it swaps the decision in\n    // place; before the report, so the dashboard records the enforced decision.\n    // A fault on an enforcing project throws and is answered 503, except in\n    // observe mode, where the request is served on the engine's decision.\n    await servedWhenObserving(\n      config,\n      () => applyComposedPolicy(composed, result, input.path),\n      undefined\n    );\n    applyBrowserIntegrityStepUp(result, config.browserPosture, input.path);\n    // The final decision is known: claim an accepted signed request before\n    // anything acts on it, so it is used once.\n    await applyRequestClaim(result, requestClaimStore, {\n      sourceIp: input.clientIp() ?? undefined,\n    });\n    if (reporter) {\n      const report = reporter(result, input.reportContext());\n      if (input.waitUntil) input.waitUntil(report);\n      else void report;\n    }\n    await dispatchOnResult(config, result, input.request);\n    // Dual envelope: the body-readable 200 step-up for cooperative agents under\n    // negotiated mode, else the spec 401/422.\n    const bodyReadable200 = selectBodyReadable200(\n      config.delegationChallengeMode ?? 'negotiated',\n      input.headers,\n      result.detectionDetail.detectionClass,\n      result.detectionDetail.isAgent\n    );\n    const challengeContextRequested =\n      result.enforcementMode === 'enforce' &&\n      (result.decision.kind === 'Challenge' || isConsentRemediableBlock(result)) &&\n      config.resolveDelegationChallenge !== undefined;\n    const delegationChallenge = challengeContextRequested\n      ? await resolveChallengeContext(\n          config.resolveDelegationChallenge,\n          { result, request: input.request },\n          {\n            timeoutMs: config.delegationChallengeTimeoutMs,\n            onFailure: config.onDelegationChallengeFailure,\n          }\n        )\n      : undefined;\n    const rendered = renderDecisionAsResponse(result, {\n      bodyReadable200,\n      delegationChallenge: validateBrowserIntegrityChallenge(result, delegationChallenge),\n      challengeContextRequested,\n    });\n    return { rendered, result };\n  };\n}\n\n/**\n * Log a pipeline fault the adapter is about to answer 503. An engine that\n * cannot load is an outage the operator has to see, so it is logged whatever\n * `debug` says; anything else only with `debug`.\n */\nexport function logPipelineFailure(error: unknown, debug: boolean | undefined): void {\n  if (isEngineLoadFailure(error)) {\n    console.error('[checkpoint] kya-os-engine failed to load; responding 503:', error);\n  } else if (debug) {\n    console.error('[checkpoint] verification pipeline failed; responding 503:', error);\n  }\n}\n\n/** Errors `loadEngine` rejected with, so a later log names them as engine failures. */\nconst engineLoadFailures = new WeakSet<object>();\n\n/**\n * An engine failure: a `loadEngine` rejection, or wasm-runtime's\n * `EngineLoadError` (told apart by its code, whichever build threw it), which\n * the Node build raises from its first verify or render.\n */\nfunction isEngineLoadFailure(error: unknown): boolean {\n  if (typeof error !== 'object' || error === null) return false;\n  return (\n    engineLoadFailures.has(error) || (error as { code?: unknown }).code === 'engine_load_failed'\n  );\n}\n\nlet warnedObservedPolicyFault = false;\n\n/**\n * Run a step that reads the project's policy. In observe mode a fault in it\n * (the policy origin down or refusing the key, or a Cedar bundle that cannot be\n * evaluated) never refuses a request: the step's `fallback` stands and the\n * request is served, and the first such fault in the process is warned (every\n * one with `debug`), so a bundle that cannot be evaluated is not silent. In\n * enforce mode the fault propagates and the adapter answers 503.\n */\nasync function servedWhenObserving<Req, T>(\n  config: CheckpointHostConfig<Req>,\n  step: () => Promise<T>,\n  fallback: T\n): Promise<T> {\n  if (config.enforcementMode !== 'observe') return step();\n  try {\n    return await step();\n  } catch (error) {\n    if (config.debug || !warnedObservedPolicyFault) {\n      warnedObservedPolicyFault = true;\n      console.warn(\n        \"[checkpoint] the project's policy could not be applied in observe mode, so requests are served on the engine's decision:\",\n        error\n      );\n    }\n    return fallback;\n  }\n}\n\n/** Load the engine once; a failed load is retried by the next request. */\nfunction memoizeEngine(load: () => Promise<PipelineEngine>): () => Promise<PipelineEngine> {\n  let loading: Promise<PipelineEngine> | undefined;\n  return () =>\n    (loading ??= load().catch((error: unknown) => {\n      loading = undefined;\n      if (typeof error === 'object' && error !== null) engineLoadFailures.add(error);\n      throw error;\n    }));\n}\n\nlet warnedLoopbackOrigins = false;\n\nfunction validateHostConfig<Req>(config: CheckpointHostConfig<Req>): void {\n  // Enforce mode never runs without the project's policy it was configured\n  // for; observe mode serves without it and warns (projectPolicySource).\n  if (readsProjectPolicy(config) && !config.apiKey && config.enforcementMode !== 'observe') {\n    throw new Error(\n      \"projectId needs apiKey (CHECKPOINT_API_KEY) to apply the project's policy: pass apiKey, or leave out projectId to run without the project's policy\"\n    );\n  }\n  if (config.browserPosture) validateBrowserPostureConfig(config.browserPosture, config.projectId);\n  if (config.browserPosture?.allowLoopbackOrigins === true && !warnedLoopbackOrigins) {\n    warnedLoopbackOrigins = true;\n    console.warn(LOOPBACK_ORIGINS_WARNING);\n  }\n  if (config.browserPosture?.protectedRoutes?.length && !config.resolveDelegationChallenge) {\n    throw new Error(\n      'browserPosture.protectedRoutes requires resolveDelegationChallenge (see createBrowserIntegrityChallengeResolver)'\n    );\n  }\n}\n\n/** Reads one lowercase header from either header shape. */\nfunction headerReader(\n  headers: CheckpointRequestHeaders\n): (name: string) => string | string[] | null | undefined {\n  if (typeof (headers as Headers).get === 'function') {\n    return (name) => (headers as Headers).get(name);\n  }\n  return (name) => (headers as Record<string, string | string[] | undefined>)[name];\n}\n\n/**\n * The fire-and-forget detection reporter, or `null` without `apiKey`: the\n * documented opt-out (the engine still runs; the dashboard sees no detections).\n */\nfunction buildReporter<Req>(\n  config: CheckpointHostConfig<Req>,\n  sdk: PipelineHost<unknown>['sdk']\n): DetectionReporter | null {\n  if (!config.apiKey) return null;\n  return makeDetectionReporter({\n    apiKey: config.apiKey,\n    baseUrl: config.baseUrl,\n    debug: config.debug,\n    telemetryBatchSize: config.telemetryBatchSize,\n    telemetryFlushIntervalMs: config.telemetryFlushIntervalMs,\n    sdk,\n  });\n}\n\n/**\n * Whether the pipeline reads the project's policy itself: for the composed\n * context unless one is injected, and for the trusted delegation roots unless\n * the configuration or an injected context supplies them.\n */\nfunction readsProjectPolicy<Req>(config: CheckpointHostConfig<Req>): boolean {\n  if (!config.projectId) return false;\n  const injected = config.composedPolicyEnforcer;\n  if (!injected) return true;\n  return !config.trustedDelegationRoots && !injected.trustedDelegationRoots;\n}\n\n/** Where the pipeline reads the project's policy, with one fetcher for every use. */\ninterface ProjectPolicySource {\n  projectId: string;\n  fetcher: PolicyFetcher;\n}\n\nlet warnedProjectIdWithoutApiKey = false;\n\n/**\n * The project's policy source, or `null` when the pipeline does not read it.\n * The policy API answers only a request carrying the project's API key, so\n * `projectId` without `apiKey` fetches nothing: enforce mode refuses that\n * configuration (validateHostConfig), and observe mode warns once that the\n * project's policy is not applied.\n */\nfunction projectPolicySource<Req>(config: CheckpointHostConfig<Req>): ProjectPolicySource | null {\n  if (!readsProjectPolicy(config)) return null;\n  if (!config.apiKey) {\n    if (!warnedProjectIdWithoutApiKey) {\n      warnedProjectIdWithoutApiKey = true;\n      console.warn(\n        \"[checkpoint] projectId is set without apiKey, so the project's policy is not applied; pass apiKey (CHECKPOINT_API_KEY) with projectId to apply it\"\n      );\n    }\n    return null;\n  }\n  return { projectId: config.projectId!, fetcher: policyFetcher(config, config.apiKey) };\n}\n\n/**\n * The project-policy fetcher. Policy is fetched from `dashboardUrl` (the\n * documented policy-fetch base) first, then `baseUrl` (the general dashboard\n * base), then the hosted dashboard, so a host that points only `dashboardUrl`\n * at staging or a self-hosted dashboard never fetches production policy. An\n * origin outage rejects with `PolicyUnavailableError` and a refused key with\n * `PolicyAuthError`; in enforce mode either is answered as a retryable 503.\n */\nfunction policyFetcher<Req>(config: CheckpointHostConfig<Req>, apiKey: string): PolicyFetcher {\n  return new PolicyFetcher({\n    apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,\n    apiKey,\n    cacheTtlSeconds: config.policyCacheTtlSeconds,\n    throwOnUnavailable: true,\n  });\n}\n\n/**\n * The composed-policy context: an injected one (advanced and testing), else\n * one built from `projectId` and `apiKey` with the host's Cedar compiler, else\n * `null`, which runs detection and the structured policy only.\n */\nfunction buildComposedContext<Req, Config extends CheckpointHostConfig<Req>>(\n  config: Config,\n  host: PipelineHost<Config>,\n  policySource: ProjectPolicySource | null\n): ComposedPolicyContext | null {\n  if (config.composedPolicyEnforcer) return config.composedPolicyEnforcer;\n  if (!policySource) return null;\n  return makeComposedPolicyContext({\n    projectId: policySource.projectId,\n    fetcher: policySource.fetcher,\n    compile: host.policyCompiler(config),\n    logger: config.debug ? consoleComposedPolicyLogger : undefined,\n  });\n}\n\n/**\n * The trusted-delegation-roots resolver. Root pinning does not depend on\n * composed Cedar enforcement, so it resolves wherever the project's policy can\n * be read, preferring the composed context's accessor (its cached fetcher, or\n * an injected context's own), else a policy fetch of its own. `null` when no\n * source is configured (no roots: the engine refuses delegation).\n */\nfunction buildTrustedRootsResolver<Req>(\n  config: CheckpointHostConfig<Req>,\n  composed: ComposedPolicyContext | null,\n  policySource: ProjectPolicySource | null\n): TrustedDelegationRootsResolver | null {\n  if (config.trustedDelegationRoots) return () => Promise.resolve(config.trustedDelegationRoots!);\n  if (composed?.trustedDelegationRoots) return () => composed.trustedDelegationRoots!();\n  if (!policySource) return null;\n  const { fetcher, projectId } = policySource;\n  return async () => (await fetcher.getPolicy(projectId)).trustedDelegationRoots ?? [];\n}\n\nlet warnedLocalClaimStore = false;\n\n/**\n * Where accepted signed requests are claimed: the caller's store, else the\n * dashboard's shared ledger when the project is configured, else this process\n * (or isolate), with a one-time warning that several instances need a shared\n * store.\n */\nfunction buildRequestClaimStore<Req>(config: CheckpointHostConfig<Req>): RequestClaimStore {\n  if (config.requestClaimStore) return config.requestClaimStore;\n  if (config.apiKey && config.projectId) {\n    return createPlatformRequestClaimStore({\n      baseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,\n      apiKey: config.apiKey,\n    });\n  }\n  if (!warnedLocalClaimStore) {\n    warnedLocalClaimStore = true;\n    console.warn(\n      '[checkpoint] signed requests are claimed in this process only; a deployment with several instances needs apiKey and projectId, or a shared requestClaimStore'\n    );\n  }\n  return createLocalRequestClaimStore();\n}\n\nasync function dispatchOnResult<Req>(\n  config: CheckpointHostConfig<Req>,\n  result: VerifyResult,\n  request: Req\n): Promise<void> {\n  if (!config.onResult) return;\n  try {\n    await config.onResult(result, request);\n  } catch {\n    // Swallowed: onResult is observability, and the verdict is already known.\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8IA,SAAgB,uBACd,QACA,MACyB;CACzB,mBAAmB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