@kya-os/checkpoint-nextjs 1.14.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +6 -1
  3. package/dist/api-client.js +1 -1
  4. package/dist/api-client.mjs +1 -1
  5. package/dist/{api-middleware-BVXf7qCM.js → api-middleware-Bcu8f06W.js} +4 -4
  6. package/dist/{api-middleware-CAarHFKk.mjs → api-middleware-xhlisoi2.mjs} +5 -5
  7. package/dist/api-middleware-xhlisoi2.mjs.map +1 -0
  8. package/dist/api-middleware.js +1 -1
  9. package/dist/api-middleware.mjs +1 -1
  10. package/dist/index-edge.d.mts +2 -2
  11. package/dist/index-edge.d.ts +2 -2
  12. package/dist/index-edge.js +3 -3
  13. package/dist/index-edge.mjs +3 -3
  14. package/dist/index.d.mts +2 -2
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.js +3 -3
  17. package/dist/index.mjs +3 -3
  18. package/dist/middleware-bundler.js +1 -1
  19. package/dist/middleware-bundler.mjs +1 -1
  20. package/dist/{middleware-core-D88q8dIt.d.mts → middleware-core-B70g9yLE.d.mts} +2 -2
  21. package/dist/middleware-core-B70g9yLE.d.mts.map +1 -0
  22. package/dist/{middleware-core-BLCAErYE.d.ts → middleware-core-DH6kGKc8.d.ts} +2 -2
  23. package/dist/middleware-core-DH6kGKc8.d.ts.map +1 -0
  24. package/dist/{middleware-core-C4xi1I9I.mjs → middleware-core-qXSvMDYw.mjs} +3 -3
  25. package/dist/{middleware-core-C4xi1I9I.mjs.map → middleware-core-qXSvMDYw.mjs.map} +1 -1
  26. package/dist/{middleware-core-tGGPv727.js → middleware-core-yE25rSJE.js} +2 -2
  27. package/dist/middleware-edge.js +2 -2
  28. package/dist/middleware-edge.mjs +2 -2
  29. package/dist/middleware-node.d.mts +1 -1
  30. package/dist/middleware-node.d.ts +1 -1
  31. package/dist/middleware-node.js +1 -1
  32. package/dist/middleware-node.mjs +1 -1
  33. package/dist/{posture-outcome-DddsJtL8.js → posture-outcome-3mJLVX85.js} +5 -0
  34. package/dist/{posture-outcome-DQ4fdMfq.mjs → posture-outcome-CN1WranD.mjs} +7 -2
  35. package/dist/posture-outcome-CN1WranD.mjs.map +1 -0
  36. package/dist/posture-outcome-Ccujx_9V.d.mts.map +1 -1
  37. package/dist/posture-outcome-Ccujx_9V.d.ts.map +1 -1
  38. package/dist/{public-api-CBQzjriI.d.mts → public-api-CAJ9XPJC.d.mts} +1 -1
  39. package/dist/{public-api-Ea4jgcwD.d.ts → public-api-D5so-53z.d.ts} +1 -1
  40. package/dist/{utils-dyFxqlFI.js → utils-CdoAQaFy.js} +16 -0
  41. package/dist/{utils-Cnwg0VrY.mjs → utils-DK9HXCUV.mjs} +12 -2
  42. package/dist/utils-DK9HXCUV.mjs.map +1 -0
  43. package/package.json +3 -3
  44. package/dist/api-middleware-CAarHFKk.mjs.map +0 -1
  45. package/dist/middleware-core-BLCAErYE.d.ts.map +0 -1
  46. package/dist/middleware-core-D88q8dIt.d.mts.map +0 -1
  47. package/dist/posture-outcome-DQ4fdMfq.mjs.map +0 -1
  48. package/dist/utils-Cnwg0VrY.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  # @kya-os/checkpoint-nextjs
4
4
 
5
+ ## 1.15.0 - 2026-11-19
6
+
7
+ ### Added
8
+
9
+ - `getCheckpointPostureOutcome` logs one warning (`console.warn`) when its `browserPosture` turns on `allowLoopbackOrigins`, which is for development only. (#8113)
10
+
11
+ ### Changed
12
+
13
+ - a decision from the enforce API without a numeric confidence is applied without the `KYA-Confidence` header, instead of ending in the fault response (a 503 by default, or a pass-through with `failOpen`). (#8056)
14
+
15
+ ### Fixed
16
+
17
+ - `withCheckpointApi` sends the `KYA-Confidence` header as a whole number from 0 to 100 (for example `100`, not `99.99999999993561`), matching the .NET SDK and the docs. (#8056)
18
+
5
19
  ## 1.14.0 - 2026-11-16
6
20
 
7
21
  ### Breaking changes
package/README.md CHANGED
@@ -145,6 +145,11 @@ Next.js always bundles `proxy.ts` and `middleware.ts`, and Turbopack follows tha
145
145
  In a minimal Next.js 16 app, `proxy.ts` with `withCheckpoint` traces 117 files (5.6 MiB), against 111 files for a `proxy.ts` without it.
146
146
  If the engine cannot load (a missing or unreadable `.wasm`), every request is answered 503, the cause is logged, and the next request tries again.
147
147
 
148
+ In a Server Component or a Server Function, Next.js bundles the engine and rewrites that URL, so the engine cannot load and the logged `EngineLoadError` says so.
149
+ There, load the engine from `node_modules`: install `@kya-os/checkpoint-wasm-runtime` as a direct dependency, at the version this package uses (`npm ls @kya-os/checkpoint-wasm-runtime` shows it), and add `serverExternalPackages: ['@kya-os/checkpoint-wasm-runtime']` to `next.config`.
150
+ Next.js keeps the package out of the bundle only when the app itself resolves it, which pnpm does not do for a dependency of a dependency, so under webpack the setting alone does nothing there.
151
+ `serverExternalPackages` needs Next.js 15 or later; on Next.js 13 and 14 it is `experimental.serverComponentsExternalPackages`.
152
+
148
153
  On webpack, the Node.js runtime is not supported yet: the build succeeds, but webpack rewrites the `.wasm` URL into a value Node's file read rejects, so the engine fails to load and every request is answered 503.
149
154
 
150
155
  ### Background work
@@ -503,4 +508,4 @@ component), pass those instead of a request. Verification is a single ES256 chec
503
508
  calling it in a handler as well as in the middleware costs little. A verified token that carries
504
509
  the beacon's agent or bot verdict (`posture.detection`), or discloses automation, also
505
510
  reclassifies a request the engine called human or incomplete data.
506
- The accessor validates `browserPosture` and `projectId` with the same check `withCheckpoint` runs at startup: `projectId` must be the lowercase project UUID, not the friendly id, and any invalid config throws. Pass the same config object the middleware takes. Treat `absent` and `rejected` alike (neither is usable posture evidence), and log `reason` on the server rather than returning it to the client.
511
+ The accessor validates `browserPosture` and `projectId` with the same check `withCheckpoint` runs at startup: `projectId` must be the lowercase project UUID, not the friendly id, and any invalid config throws. To find the UUID, copy **Project UUID** from the top of the **Installations** page or from **All settings → Projects** in the user menu (a project with no friendly ID shows its UUID as the **Project ID**). Pass the same config object the middleware takes. Treat `absent` and `rejected` alike (neither is usable posture evidence), and log `reason` on the server rather than returning it to the client.
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_utils = require('./utils-dyFxqlFI.js');
2
+ const require_utils = require('./utils-CdoAQaFy.js');
3
3
  let _kya_os_checkpoint_wasm_runtime_reporter = require("@kya-os/checkpoint-wasm-runtime/reporter");
4
4
 
5
5
  //#region src/api-client.ts
@@ -1,4 +1,4 @@
1
- import { n as relayHeaders } from "./utils-Cnwg0VrY.mjs";
1
+ import { n as relayHeaders } from "./utils-DK9HXCUV.mjs";
2
2
  import { makeReportSender } from "@kya-os/checkpoint-wasm-runtime/reporter";
3
3
 
4
4
  //#region src/api-client.ts
@@ -1,5 +1,5 @@
1
1
  const require_adapt = require('./adapt-D2-OBY9M.js');
2
- const require_utils = require('./utils-dyFxqlFI.js');
2
+ const require_utils = require('./utils-CdoAQaFy.js');
3
3
  const require_api_client = require('./api-client.js');
4
4
  let _vercel_functions = require("@vercel/functions");
5
5
  let next_server_js = require("next/server.js");
@@ -96,7 +96,7 @@ function buildAgentInstructionResponse(request, decision, redirectUrl, options)
96
96
  response.headers.set("KYA-Auth-Url", authUrl);
97
97
  response.headers.set("KYA-Action", "instruct");
98
98
  response.headers.set("KYA-Detected-Agent", agentName);
99
- response.headers.set("KYA-Confidence", decision.confidence.toString());
99
+ require_utils.setConfidenceHeader(response.headers, decision.confidence);
100
100
  response.headers.set("Cache-Control", "no-store");
101
101
  return response;
102
102
  }
@@ -177,7 +177,7 @@ function sdkSelfIdentification() {
177
177
  const runtime = typeof process !== "undefined" && process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
178
178
  return {
179
179
  name: SDK_NAME,
180
- version: "1.14.0",
180
+ version: "1.15.0",
181
181
  runtime
182
182
  };
183
183
  }
@@ -366,7 +366,7 @@ function withCheckpointApi(config = {}) {
366
366
  const response = next_server_js.NextResponse.next();
367
367
  if (decision.isAgent) {
368
368
  response.headers.set("KYA-Detected", "true");
369
- response.headers.set("KYA-Confidence", decision.confidence.toString());
369
+ require_utils.setConfidenceHeader(response.headers, decision.confidence);
370
370
  if (decision.agentName) response.headers.set("KYA-Agent", decision.agentName);
371
371
  }
372
372
  return response;
@@ -1,5 +1,5 @@
1
1
  import { n as failClosedResponse } from "./adapt-BGEyLf44.mjs";
2
- import { r as safeHostname, t as getClientIp } from "./utils-Cnwg0VrY.mjs";
2
+ import { i as setConfidenceHeader, r as safeHostname, t as getClientIp } from "./utils-DK9HXCUV.mjs";
3
3
  import { getCheckpointApiClient } from "./api-client.mjs";
4
4
  import { waitUntil } from "@vercel/functions";
5
5
  import { NextResponse } from "next/server.js";
@@ -96,7 +96,7 @@ function buildAgentInstructionResponse(request, decision, redirectUrl, options)
96
96
  response.headers.set("KYA-Auth-Url", authUrl);
97
97
  response.headers.set("KYA-Action", "instruct");
98
98
  response.headers.set("KYA-Detected-Agent", agentName);
99
- response.headers.set("KYA-Confidence", decision.confidence.toString());
99
+ setConfidenceHeader(response.headers, decision.confidence);
100
100
  response.headers.set("Cache-Control", "no-store");
101
101
  return response;
102
102
  }
@@ -177,7 +177,7 @@ function sdkSelfIdentification() {
177
177
  const runtime = typeof process !== "undefined" && process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
178
178
  return {
179
179
  name: SDK_NAME,
180
- version: "1.14.0",
180
+ version: "1.15.0",
181
181
  runtime
182
182
  };
183
183
  }
@@ -366,7 +366,7 @@ function withCheckpointApi(config = {}) {
366
366
  const response = NextResponse.next();
367
367
  if (decision.isAgent) {
368
368
  response.headers.set("KYA-Detected", "true");
369
- response.headers.set("KYA-Confidence", decision.confidence.toString());
369
+ setConfidenceHeader(response.headers, decision.confidence);
370
370
  if (decision.agentName) response.headers.set("KYA-Agent", decision.agentName);
371
371
  }
372
372
  return response;
@@ -386,4 +386,4 @@ function failOpenResponse() {
386
386
 
387
387
  //#endregion
388
388
  export { withCheckpointApi as t };
389
- //# sourceMappingURL=api-middleware-CAarHFKk.mjs.map
389
+ //# sourceMappingURL=api-middleware-xhlisoi2.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-middleware-xhlisoi2.mjs","names":[],"sources":["../src/responses/agent-instruction.ts","../src/api-middleware.ts"],"sourcesContent":["/**\n * Agent Instruction Response Builder (Next.js)\n *\n * Tells an AI agent where to send its user to complete consent / connect,\n * via a machine-parseable Link header + JSON body.\n *\n * **Dual envelope.** By default this is a 401 instruction response. AI-agent fetchers (Claude-User\n * WebFetch, ChatGPT) collapse 4xx responses and never surface the body to\n * the LLM, so the instruction is invisible. When the caller is a\n * cooperative, self-identifying agent (selected upstream via\n * `serveBodyReadable200`), pass `{ bodyReadable200: true }` to serve the\n * SAME body at HTTP 200 with NO `WWW-Authenticate` (a 200 + WWW-Authenticate\n * is reinterpreted as 401 by some fetchers); the consent URL stays in the\n * body + the `KYA-Auth-Url`/`Link` hint headers. This also realigns\n * TS-instruct (was 401-only) with .NET-instruct (200).\n *\n * Envelope selection is a cooperative-UX bridge, NOT an access control —\n * the authoritative consent target is the body `user_action_required.url`;\n * the `KYA-Auth-Url`/`Link` headers are unsigned hints.\n *\n * This is the in-app counterpart to the Cloudflare Gateway's builder at\n * `apps/web/workers/gateway/src/responses/agent-instruction.ts`. The body\n * is kept in sync so LLM and MCP clients see identical behavior whether a\n * site is protected by the gateway or by the Next.js middleware.\n *\n * Implements RFC 8288 Link discovery. It deliberately emits no\n * `WWW-Authenticate`; only a registered policy Challenge may emit the canonical\n * Delegation authentication fields.\n *\n * @see ../../apps/web/workers/gateway/src/responses/agent-instruction.ts\n */\n\nimport { NextResponse, type NextRequest } from 'next/server.js';\nimport type { EnforcementDecision } from '../api-client';\nimport { safeHostname, setConfidenceHeader } from '../utils';\n\nconst MCP_I_DOCS_URL = 'https://kya.vouched.id/docs/enforce/kya-os-enforcement';\nconst DEFAULT_CONNECT_PATH = '/connect';\n\n/** Options controlling which envelope `buildAgentInstructionResponse` emits. */\nexport interface AgentInstructionResponseOptions {\n /**\n * When true, serve the body-readable HTTP 200 fetcher envelope (same\n * body, no `WWW-Authenticate`) instead of the 401. The caller\n * decides this via the shared `serveBodyReadable200` predicate when its\n * challenge-emission mode is `negotiated`. Defaults to false.\n */\n bodyReadable200?: boolean;\n}\n\n/**\n * Build an \"agent must connect\" response for the Next.js middleware.\n *\n * The caller is responsible for deciding *when* to call this (typically when\n * `decision.action === 'redirect'` or `'instruct'`) and *which envelope* via\n * `options.bodyReadable200`. This helper only owns the response shape.\n */\nexport function buildAgentInstructionResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n redirectUrl: string | undefined,\n options?: AgentInstructionResponseOptions\n): NextResponse {\n // Resolve the target to an absolute URL against the incoming request so the\n // Link header is dereferenceable by strict clients (some LLM fetchers refuse\n // relative URIs in Link).\n const resolved = resolveUrl(redirectUrl ?? DEFAULT_CONNECT_PATH, request.url);\n\n // Match gateway's \"connect page\" branch: attach ?agent= for client-specific\n // install cards on the landing page.\n const agentName = decision.agentName || decision.agentType || 'unknown';\n if (!resolved.searchParams.has('agent')) {\n resolved.searchParams.set('agent', agentName.toLowerCase());\n }\n\n const authUrl = resolved.toString();\n const hostname = safeHostname(request.url);\n\n const body = {\n // Markdown-formatted so clients that render markdown (Claude Desktop,\n // ChatGPT web) surface the URL as a clickable link. Tone mirrors the\n // gateway response so messaging stays consistent across platforms.\n message:\n `I can't access ${hostname} yet — this site checks AI assistants at the front door.\\n\\n` +\n `**To give me access, open this link:**\\n` +\n `[Connect securely to ${hostname}](${authUrl})\\n\\n` +\n `It only takes a moment and you won't need to do it again. ` +\n `Once you're done, ask me to try again and I'll connect through the verified channel automatically.`,\n\n user_action_required: {\n action: `Connect securely to ${hostname}`,\n url: authUrl,\n reason: `${hostname} checks AI assistants before they connect. Open the link to give your assistant a verified key.`,\n },\n\n mcp_i: {\n version: '1.0' as const,\n action: 'authenticate' as const,\n authorization_url: authUrl,\n flow: {\n type: 'oauth2_delegation' as const,\n steps: [\n '1. Direct your user to the authorization_url',\n '2. User reviews requested scopes and grants consent',\n '3. Receive delegation credential (JWT)',\n '4. Include credential in KYA-Delegation header',\n '5. Retry this request with the proof',\n ],\n },\n retry_instructions: {\n header: 'KYA-Delegation' as const,\n format: 'JWT delegation credential from authorization flow',\n },\n documentation: MCP_I_DOCS_URL,\n },\n\n error: 'mcp_authentication_required',\n code: 'AGENT_REQUIRES_DELEGATION',\n\n detection: {\n agent_type: decision.agentType || 'ai_agent',\n agent_name: decision.agentName || 'Unknown Agent',\n confidence: decision.confidence,\n },\n };\n\n // Dual envelope: 200 body-readable for cooperative fetchers, else 401.\n // The body is identical across both. INSTRUCT is not a registered policy\n // Delegation challenge, so it must not advertise a fabricated auth scheme.\n const bodyReadable200 = options?.bodyReadable200 ?? false;\n const response = NextResponse.json(body, { status: bodyReadable200 ? 200 : 401 });\n\n // RFC 8288 discovery pointer + KYA-* hints. Present on BOTH envelopes —\n // these are unsigned hints; the authoritative target is the body\n // `user_action_required.url`. `rel=\"kya-authorize\"` matches the CF gateway.\n response.headers.set(\n 'Link',\n `<${authUrl}>; rel=\"kya-authorize\", <${MCP_I_DOCS_URL}>; rel=\"help\"`\n );\n response.headers.set('KYA-Auth-Required', 'true');\n response.headers.set('KYA-Auth-Url', authUrl);\n response.headers.set('KYA-Action', 'instruct');\n response.headers.set('KYA-Detected-Agent', agentName);\n setConfidenceHeader(response.headers, decision.confidence);\n response.headers.set('Cache-Control', 'no-store');\n\n return response;\n}\n\n/**\n * Resolve a URL that may be absolute or a same-origin path.\n * Falls back to `/connect` on the request origin if parsing fails.\n */\nfunction resolveUrl(target: string, baseUrl: string): URL {\n try {\n return new URL(target, baseUrl);\n } catch {\n return new URL(DEFAULT_CONNECT_PATH, baseUrl);\n }\n}\n","/**\n * API-based Checkpoint Middleware for Next.js\n *\n * This middleware uses the Checkpoint API for detection and enforcement,\n * instead of running detection locally. This approach:\n *\n * 1. Works reliably in Edge Runtime (no WASM loading issues)\n * 2. Ensures consistent detection across all platforms\n * 3. Applies centralized policies from the dashboard\n * 4. Supports deny lists, thresholds, and path rules\n *\n * @example\n * ```typescript\n * // middleware.ts\n * import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';\n *\n * export default withCheckpointApi({\n * apiKey: process.env.CHECKPOINT_API_KEY!,\n * // Optional overrides:\n * onBlock: 'redirect', // 'block' | 'redirect' | 'challenge'\n * redirectUrl: '/blocked',\n * skipPaths: ['/api/health', '/_next/*'],\n * });\n *\n * export const config = {\n * matcher: ['/((?!_next/static|favicon.ico).*)'],\n * };\n * ```\n */\n\nimport { NextRequest, NextResponse } from 'next/server.js';\nimport { matchPath } from '@kya-os/checkpoint-shared/policy/enforcement';\nimport { requestPresentedCredential } from '@kya-os/checkpoint-shared/kya-http';\nimport {\n selectBodyReadable200,\n type ChallengeEnvelopeMode,\n} from '@kya-os/checkpoint-shared/host-adapter';\nimport type { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared/client-ip';\nimport type { EngineInfo } from '@kya-os/checkpoint-shared';\nimport {\n CheckpointApiClient,\n getCheckpointApiClient,\n type EnforcementDecision,\n type LogDetectionInput,\n} from './api-client';\nimport { buildAgentInstructionResponse } from './responses/agent-instruction';\nimport { failClosedResponse } from './adapt';\nimport { getClientIp, safeHostname, setConfidenceHeader } from './utils';\n// A genuine hard dependency, not an optional one, despite forcing every\n// consumer (even non-Vercel ones) to install it (bestbrian review,\n// checkpoint#4460). Two reasons a dynamic/optional-peer import, which this\n// file used briefly, does NOT work here (Bugbot review, checkpoint#4657):\n// 1. This middleware explicitly targets Edge Runtime (see the module doc\n// comment). A `webpackIgnore`d variable-name `import()` is invisible\n// to the bundler on purpose — but Edge Runtime has no filesystem/module\n// resolution at request time, only what the bundler actually included.\n// An intentionally-unbundled import can never resolve there; `waitUntil`\n// would silently never register, reintroducing the exact lost-detection\n// bug this wrapper exists to prevent.\n// 2. It's unnecessary: `waitUntil()`'s own implementation\n// (`getContext().waitUntil?.(promise)`, where `getContext()` returns\n// `{}` off Vercel) already no-ops safely everywhere it isn't backed by\n// a real Vercel request context — Node, Edge, tests, wherever. There is\n// no failure mode to guard against with a fallback; the only real cost\n// of the hard dependency is a few extra KB installed on non-Vercel\n// consumers, which is the correct trade against actually breaking\n// detection logging on Vercel.\nimport { waitUntil } from '@vercel/functions';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Middleware configuration\n */\nexport interface CheckpointApiMiddlewareConfig {\n /** Explicit deployment/proxy trust profile for client-IP resolution. */\n clientIpPolicy?: ClientIpTrustPolicy;\n /** API key (or use CHECKPOINT_API_KEY env var) */\n apiKey?: string;\n /**\n * Gateway base URL. Override for staging or self-hosted deployments.\n * With `useEdge: false` the default becomes `https://kya.vouched.id`.\n *\n * @default 'https://detect.checkpoint-gateway.ai'\n */\n apiUrl?: string;\n /**\n * Use edge detection for lower latency (~30-50ms vs ~150ms) and better coverage.\n * Edge detection can identify non-JS clients (curl, Python, Claude Code WebFetch)\n * that the pixel cannot detect since they don't execute JavaScript.\n * Set to false to use the Vercel API instead.\n * @default true\n */\n useEdge?: boolean;\n /**\n * Request timeout in milliseconds for the gateway call.\n *\n * @default 5000\n */\n timeout?: number;\n\n /**\n * Action to take when an agent should be blocked\n * - 'block': Return 403 response\n * - 'redirect': Redirect to redirectUrl\n * - 'challenge': Show a challenge page (future)\n * Default: uses policy from dashboard\n */\n onBlock?: 'block' | 'redirect' | 'challenge';\n\n /**\n * URL to redirect to when blocking (if onBlock is 'redirect')\n * Default: uses redirectUrl from dashboard policy\n */\n redirectUrl?: string;\n\n /**\n * How the middleware handles a `redirect` / `instruct` action.\n *\n * - `'instruct'` (default): return HTTP 401 with a KYA-OS Link header + JSON\n * body pointing the agent at the redirect URL. LLMs surface the URL as a\n * clickable link for the user. Matches the Cloudflare Gateway contract.\n * - `'http'`: legacy behavior — return HTTP 302 with `Location`. Most LLM\n * fetchers won't follow the redirect, so this is only useful when your\n * traffic is real browsers.\n *\n * @default 'instruct'\n */\n redirectMode?: 'instruct' | 'http';\n\n /**\n * Challenge-emission envelope mode (draft-kya-http-02 §8.1 fetcher-200).\n * `negotiated` serves a body-readable HTTP 200 instruct response to\n * cooperative agents (so fetchers that drop 4xx bodies can read it),\n * keeping the spec 401 for everyone else. Defaults to `negotiated` (#3530).\n * A cooperative-UX bridge, NOT an access control.\n *\n * @default 'negotiated'\n */\n delegationChallengeMode?: ChallengeEnvelopeMode;\n\n /**\n * Customize the blocked response's status, message, and extra headers.\n *\n * @default { status: 403, message: 'Access denied' }\n */\n blockedResponse?: {\n status?: number;\n message?: string;\n headers?: Record<string, string>;\n };\n\n /**\n * Paths to skip (in addition to dashboard policy)\n * Supports glob patterns: '/api/*', '/_next/*'\n */\n skipPaths?: string[];\n\n /**\n * Only enforce on these paths (overrides dashboard policy)\n */\n includePaths?: string[];\n\n /**\n * Callback when an agent is detected\n */\n onAgentDetected?: (request: NextRequest, decision: EnforcementDecision) => void | Promise<void>;\n\n /**\n * Callback to customize the blocked response\n */\n customBlockedResponse?: (\n request: NextRequest,\n decision: EnforcementDecision\n ) => NextResponse | Promise<NextResponse>;\n\n /**\n * Whether to fail open (allow) on API errors. Must be explicitly `true`;\n * the default is fail-closed (503 with `Retry-After`). A request that\n * presented a credential (bearer or KYA delegation headers) is answered 503\n * on an API error even when this is `true`.\n *\n * @default false\n */\n failOpen?: boolean;\n\n /**\n * Log detection decisions and errors to the console.\n *\n * @default false\n */\n debug?: boolean;\n telemetryBatchSize?: number;\n telemetryFlushIntervalMs?: number;\n}\n\n// ============================================================================\n// Path Matching\n// ============================================================================\n\n/**\n * Check if path should be skipped\n */\nfunction shouldSkipPath(path: string, skipPaths: string[]): boolean {\n return skipPaths.some((pattern) => matchPath(path, pattern));\n}\n\n/**\n * Check if path should be included (if includePaths is set)\n */\nfunction shouldIncludePath(path: string, includePaths?: string[]): boolean {\n if (!includePaths || includePaths.length === 0) return true;\n return includePaths.some((pattern) => matchPath(path, pattern));\n}\n\n// ============================================================================\n// Detection Report\n// ============================================================================\n\n/**\n * Package version, injected at build time by tsdown's `define` from\n * package.json (which the publish workflow stamps before it builds). Unbundled\n * source, as in the unit tests, has no such global, so every read is\n * `typeof`-guarded and the report then omits `sdk` rather than guess a version.\n */\ndeclare const __CHECKPOINT_PKG_VERSION__: string | undefined;\n\n/** The npm package this middleware ships in (package.json `name`, pinned by a unit test). */\nconst SDK_NAME = '@kya-os/checkpoint-nextjs';\n\n/**\n * The gateway ran the engine, so its engine info is reported under the\n * remote-engine name `checkpoint-remote`. Forwarding the gateway's own\n * `checkpoint-worker-wasm` would make this install read as a DNS Gateway.\n */\nfunction remoteEngineInfo(engine: EngineInfo): EngineInfo {\n return {\n name: 'checkpoint-remote',\n version: engine.version,\n rulesetHash: engine.rulesetHash,\n rulesetVersion: engine.rulesetVersion,\n ...(engine.buildSha ? { buildSha: engine.buildSha } : {}),\n };\n}\n\n/** The SDK's self-identification, or undefined when the build injected no version. */\nfunction sdkSelfIdentification(): LogDetectionInput['sdk'] {\n if (typeof __CHECKPOINT_PKG_VERSION__ === 'undefined') return undefined;\n const runtime =\n typeof process !== 'undefined' && process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node';\n return { name: SDK_NAME, version: __CHECKPOINT_PKG_VERSION__, runtime };\n}\n\n// ============================================================================\n// Response Builders\n// ============================================================================\n\n/**\n * Build blocked response.\n *\n * When the policy attaches a `redirectUrl` (e.g. the dashboard's hosted\n * /connect page), we still respect the `block` action but surface the URL to\n * LLM clients so the user can recover: `Link` header + `user_action_required`\n * in the JSON body. Status stays 403 — this is not an auth challenge, it's a\n * blocked request with a recovery hint.\n */\nfunction buildBlockedResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n config: CheckpointApiMiddlewareConfig\n): NextResponse {\n const status = config.blockedResponse?.status ?? 403;\n const message = config.blockedResponse?.message ?? decision.message ?? 'Access denied';\n\n const recoveryUrl = resolveRecoveryUrl(request, config.redirectUrl || decision.redirectUrl);\n\n const body: Record<string, unknown> = {\n error: message,\n code: 'AGENT_BLOCKED',\n reason: decision.reason,\n agentType: decision.agentType,\n };\n\n if (recoveryUrl) {\n const hostname = safeHostname(request.url);\n body.user_action_required = {\n action: `Connect securely to ${hostname}`,\n url: recoveryUrl,\n reason: `${hostname} blocks unverified AI assistants. Open the link to give your assistant a verified key and try again.`,\n };\n body.message =\n `I can't access ${hostname} — this site blocks unverified AI assistants.\\n\\n` +\n `**To give me access, open this link:**\\n` +\n `[Connect securely to ${hostname}](${recoveryUrl})\\n\\n` +\n `Once you're done, ask me to try again.`;\n }\n\n const response = NextResponse.json(body, { status });\n\n // Add custom headers\n if (config.blockedResponse?.headers) {\n for (const [key, value] of Object.entries(config.blockedResponse.headers)) {\n response.headers.set(key, value);\n }\n }\n\n if (recoveryUrl) {\n // RFC 8288 discovery pointer — same rel value the 401 instruct path uses\n // so LLM clients can parse it uniformly.\n response.headers.set('Link', `<${recoveryUrl}>; rel=\"kya-authorize\"`);\n response.headers.set('KYA-Auth-Url', recoveryUrl);\n }\n\n // Add Checkpoint headers\n response.headers.set('KYA-Action', decision.action);\n response.headers.set('KYA-Reason', decision.reason);\n\n return response;\n}\n\n/**\n * A policy `requestsPerMinute` throttle arrives as `block` with reason\n * `rate_limited`. It is a 429 with a retry hint, not an access denial: no\n * \"unverified assistant\" recovery copy and no redirect.\n */\nfunction buildRateLimitedResponse(\n decision: EnforcementDecision,\n config: CheckpointApiMiddlewareConfig\n): NextResponse {\n const retryAfter = decision.metadata?.rateLimit?.retryAfterSeconds;\n const response = NextResponse.json(\n {\n error: decision.message ?? 'Rate limit exceeded',\n code: 'RATE_LIMITED',\n reason: decision.reason,\n agentType: decision.agentType,\n ...(retryAfter !== undefined ? { retryAfterSeconds: retryAfter } : {}),\n },\n { status: 429 }\n );\n for (const [key, value] of Object.entries(config.blockedResponse?.headers ?? {})) {\n response.headers.set(key, value);\n }\n if (retryAfter !== undefined) response.headers.set('Retry-After', String(retryAfter));\n response.headers.set('KYA-Action', decision.action);\n response.headers.set('KYA-Reason', decision.reason);\n return response;\n}\n\nfunction resolveRecoveryUrl(request: NextRequest, target: string | undefined): string | undefined {\n if (!target) return undefined;\n try {\n return new URL(target, request.url).toString();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Build redirect response\n */\nfunction buildRedirectResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n config: CheckpointApiMiddlewareConfig\n): NextResponse {\n const redirectUrl = config.redirectUrl || decision.redirectUrl || '/blocked';\n const url = new URL(redirectUrl, request.url);\n\n // Add query params with detection info\n url.searchParams.set('reason', decision.reason);\n if (decision.agentType) {\n url.searchParams.set('agent', decision.agentType);\n }\n\n return NextResponse.redirect(url);\n}\n\n// ============================================================================\n// Middleware Factory\n// ============================================================================\n\n/**\n * Create Checkpoint middleware with API-based detection\n *\n * @example\n * ```typescript\n * // middleware.ts\n * import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';\n *\n * export default withCheckpointApi({\n * onBlock: 'block',\n * skipPaths: ['/api/health'],\n * });\n * ```\n */\nexport function withCheckpointApi(config: CheckpointApiMiddlewareConfig = {}) {\n // Initialize client (will use CHECKPOINT_API_KEY env var if not provided)\n let client: CheckpointApiClient | null = null;\n\n const getClient = () => {\n if (!client) {\n client = getCheckpointApiClient({\n apiKey: config.apiKey,\n baseUrl: config.apiUrl,\n useEdge: config.useEdge,\n timeout: config.timeout,\n debug: config.debug,\n telemetryBatchSize: config.telemetryBatchSize,\n telemetryFlushIntervalMs: config.telemetryFlushIntervalMs,\n });\n }\n return client;\n };\n\n // Default skip paths (static assets, etc.).\n //\n // `**` (globstar) is intentional for the `_next/*` patterns: Next.js\n // ships static assets at deeply nested paths like\n // `/_next/static/chunks/main.js` and `/_next/image/?url=…` query-\n // suffixed. The shared `matchPath` treats single `*` as `[^/]*`\n // (segment-local) — pre-rename this code relied on the local\n // matchPath's buggy `*` → `.*` (cross-boundary) coincidence; without\n // `**` here every static-asset request would now hit the enforcement\n // API. Picked up by cursor-bot on PR #2568 after the matchPath swap.\n const defaultSkipPaths = [\n '/_next/static/**',\n '/_next/image/**',\n '/favicon.ico',\n '/robots.txt',\n '/sitemap.xml',\n ];\n\n const skipPaths = [...defaultSkipPaths, ...(config.skipPaths || [])];\n\n // Fails open only on the explicit opt-in AND when the request presented no\n // credential; a presented credential that could not be verified is never\n // waved through.\n const faultResponse = (request: NextRequest): NextResponse =>\n config.failOpen === true && !requestPresentedCredential(request.headers)\n ? failOpenResponse()\n : failClosedResponse();\n\n return async function middleware(request: NextRequest): Promise<NextResponse> {\n const path = request.nextUrl.pathname;\n const startTime = Date.now();\n\n // Check skip paths\n if (shouldSkipPath(path, skipPaths)) {\n return NextResponse.next();\n }\n\n // Check include paths\n if (!shouldIncludePath(path, config.includePaths)) {\n return NextResponse.next();\n }\n\n try {\n const client = getClient();\n\n // Extract request context for potential logging\n const userAgent = request.headers.get('user-agent') || undefined;\n const ipAddress = getClientIp(request, config.clientIpPolicy);\n\n // Call enforce API\n const result = await client.enforce({\n headers: Object.fromEntries(request.headers.entries()),\n userAgent,\n ipAddress,\n path,\n url: request.url,\n method: request.method,\n requestId: request.headers.get('x-request-id') || undefined,\n options: {\n // Always include detection results for logging (needed when using edge)\n includeDetectionResult: true,\n },\n });\n\n // Handle API error\n if (!result.success || !result.data) {\n if (config.debug) {\n console.warn('[Checkpoint] API error:', result.error);\n }\n\n return faultResponse(request);\n }\n\n const decision = result.data.decision;\n\n // Log if debug enabled\n if (config.debug) {\n console.log('[Checkpoint] Decision:', {\n path,\n action: decision.action,\n isAgent: decision.isAgent,\n confidence: decision.confidence,\n agentName: decision.agentName,\n detectionMethod: result.data.detection?.detectionMethod || 'not-included',\n processingTimeMs: Date.now() - startTime,\n });\n }\n\n // Fire-and-forget logging - ONLY when using Gateway Worker (edge detection)\n // When useEdge: false, the /api/v1/enforce endpoint already logs to the database\n // This prevents double-logging while ensuring Gateway detections are persisted\n //\n // Wrapped in waitUntil(): on Vercel's Edge/Fluid Compute runtimes, the\n // platform is free to abort any work still pending once this function\n // returns its Response — an un-awaited fetch() with no lifecycle\n // extension gets killed mid-flight (observed live as `[Checkpoint] Log\n // detection failed: DOMException [AbortError]: This operation was\n // aborted`, 100% reproduction rate on a real deployment: every\n // detection classified correctly but never persisted). waitUntil()\n // tells the platform to keep the function alive until this promise\n // settles, without making the response wait for it. Off Vercel (or\n // wherever no request context backs it) waitUntil() itself no-ops\n // safely — see the import's doc comment — so this needs no fallback.\n if (client.isUsingEdge() && result.data.detection) {\n waitUntil(\n client\n .logDetection({\n detection: result.data.detection,\n context: { userAgent, ipAddress, path, url: request.url, method: request.method },\n // This is the Next.js middleware regardless of whether it used\n // edge detection or the Vercel API. `logDetection`'s own\n // default ('gateway') describes the transport, not the\n // installation, so this must say 'middleware' explicitly.\n source: 'middleware',\n // The decision this middleware acts on below, and the engine\n // that made it, so the dashboard shows a verdict and a method\n // instead of an unknown runtime with no decision.\n enforcement: { action: decision.action },\n engine: result.data.engine ? remoteEngineInfo(result.data.engine) : undefined,\n sdk: sdkSelfIdentification(),\n })\n .catch((err) => {\n if (config.debug) {\n console.error('[Checkpoint] Log detection failed:', err);\n }\n })\n );\n }\n\n // Observability callbacks must not influence enforcement. A throwing\n // callback used to reach the outer catch before block/redirect actions\n // ran, which fails open only when the explicit opt-in is set and no\n // credential was presented, allowing requests the API had already denied.\n if (decision.isAgent && config.onAgentDetected) {\n try {\n await config.onAgentDetected(request, decision);\n } catch (error) {\n if (config.debug) {\n console.error('[Checkpoint] onAgentDetected callback failed:', error);\n }\n }\n }\n\n // Handle enforcement action\n const redirectMode = config.redirectMode ?? 'instruct';\n switch (decision.action) {\n case 'block': {\n // Use custom response if provided. `return await` (not bare\n // `return`) keeps a rejected promise inside this try block so\n // the catch path below can absorb it — without the\n // await, the rejection escapes synchronously and the caller\n // sees an unhandled 500 instead of the intended fault response\n // (fail-open only with the explicit opt-in and no credential\n // presented, else 503). Same shape as the\n // `await config.onAgentDetected(...)` call earlier in this handler.\n if (config.customBlockedResponse) {\n return await config.customBlockedResponse(request, decision);\n }\n\n if (decision.reason === 'rate_limited') {\n return buildRateLimitedResponse(decision, config);\n }\n\n // Check if config overrides to redirect\n if (config.onBlock === 'redirect') {\n return buildRedirectResponse(request, decision, config);\n }\n\n return buildBlockedResponse(request, decision, config);\n }\n\n case 'redirect':\n case 'instruct': {\n // Default behavior: 401 + Link header + JSON body so LLM clients can\n // surface the /connect URL as a link for the user to open. This\n // matches `buildAgentInstructionResponse` in the CF gateway, so\n // hostname-routed and self-hosted deployments behave the same.\n //\n // Legacy 302 behavior is available under `redirectMode: 'http'` for\n // customers who want a plain browser redirect.\n if (redirectMode === 'http' && decision.action === 'redirect') {\n return buildRedirectResponse(request, decision, config);\n }\n\n const targetUrl = config.redirectUrl || decision.redirectUrl;\n // Dual envelope: serve the body-readable 200 to cooperative agents\n // under negotiated mode; else the spec 401. Feed the shared selector\n // the API's detection class + isAgent from the SAME detection payload\n // the engine PEPs (express / nextjs middleware) use — so negotiated\n // mode can't disagree across PEPs, and the class/isAgent pair the\n // predicate gates on stays internally consistent (never the\n // `decision.isAgent` proxy, which could diverge from this payload).\n const bodyReadable200 = selectBodyReadable200(\n config.delegationChallengeMode ?? 'negotiated',\n request.headers,\n result.data.detection?.detectionClass,\n result.data.detection?.isAgent ?? false\n );\n return buildAgentInstructionResponse(request, decision, targetUrl, {\n bodyReadable200,\n });\n }\n\n case 'challenge': {\n return buildRedirectResponse(request, decision, config);\n }\n\n case 'log':\n case 'allow':\n default: {\n // Allow the request to proceed\n const response = NextResponse.next();\n\n // Add detection headers for downstream use\n if (decision.isAgent) {\n response.headers.set('KYA-Detected', 'true');\n setConfidenceHeader(response.headers, decision.confidence);\n if (decision.agentName) {\n response.headers.set('KYA-Agent', decision.agentName);\n }\n }\n\n return response;\n }\n }\n } catch (error) {\n // Unexpected error\n if (config.debug) {\n console.error('[Checkpoint] Middleware error:', error);\n }\n\n return faultResponse(request);\n }\n };\n}\n\nfunction failOpenResponse(): NextResponse {\n const response = N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W,gBACtB,OAAO,yBAAyB,UAAU,MAAM;KAIlD,IAAI,OAAO,YAAY,YACrB,OAAO,sBAAsB,SAAS,UAAU,MAAM;KAGxD,OAAO,qBAAqB,SAAS,UAAU,MAAM;IAGvD,KAAK;IACL,KAAK,YAAY;KAQf,IAAI,iBAAiB,UAAU,SAAS,WAAW,YACjD,OAAO,sBAAsB,SAAS,UAAU,MAAM;KAGxD,MAAM,YAAY,OAAO,eAAe,SAAS;KAQjD,MAAM,kBAAkB,sBACtB,OAAO,2BAA2B,cAClC,QAAQ,SACR,OAAO,KAAK,WAAW,gBACvB,OAAO,KAAK,WAAW,WAAW,KACpC;KACA,OAAO,8BAA8B,SAAS,UAAU,WAAW,EACjE,gBACF,CAAC;IACH;IAEA,KAAK,aACH,OAAO,sBAAsB,SAAS,UAAU,MAAM;IAKxD,SAAS;KAEP,MAAM,WAAW,aAAa,KAAK;KAGnC,IAAI,SAAS,SAAS;MACpB,SAAS,QAAQ,IAAI,gBAAgB,MAAM;MAC3C,oBAAoB,SAAS,SAAS,SAAS,UAAU;MACzD,IAAI,SAAS,WACX,SAAS,QAAQ,IAAI,aAAa,SAAS,SAAS;KAExD;KAEA,OAAO;IACT;GACF;EACF,SAAS,OAAO;GAEd,IAAI,OAAO,OACT,QAAQ,MAAM,kCAAkC,KAAK;GAGvD,OAAO,cAAc,OAAO;EAC9B;CACF;AACF;AAEA,SAAS,mBAAiC;CACxC,MAAM,WAAW,aAAa,KAAK;CACnC,SAAS,QAAQ,IAAI,gBAAgB,MAAM;CAC3C,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_api_middleware = require('./api-middleware-BVXf7qCM.js');
2
+ const require_api_middleware = require('./api-middleware-Bcu8f06W.js');
3
3
 
4
4
  exports.withCheckpointApi = require_api_middleware.withCheckpointApi;
@@ -1,3 +1,3 @@
1
- import { t as withCheckpointApi } from "./api-middleware-CAarHFKk.mjs";
1
+ import { t as withCheckpointApi } from "./api-middleware-xhlisoi2.mjs";
2
2
 
3
3
  export { withCheckpointApi };
@@ -3,6 +3,6 @@ import { n as withCheckpointApi, t as CheckpointApiMiddlewareConfig } from "./ap
3
3
  import { t as CheckpointConfig } from "./config-CVqpjhwT.mjs";
4
4
  import { n as CheckpointPostureOutcome, r as getCheckpointPostureOutcome, t as CheckpointPostureOptions } from "./posture-outcome-Ccujx_9V.mjs";
5
5
  import { withCheckpoint } from "./middleware-edge.mjs";
6
- import { t as VERSION } from "./middleware-core-D88q8dIt.mjs";
7
- import "./public-api-CBQzjriI.mjs";
6
+ import { t as VERSION } from "./middleware-core-B70g9yLE.mjs";
7
+ import "./public-api-CAJ9XPJC.mjs";
8
8
  export { CheckpointApiClient, type CheckpointApiClientConfig, type CheckpointApiMiddlewareConfig, type CheckpointConfig, type CheckpointPostureOptions, type CheckpointPostureOutcome, type EnforceInput, type EnforceResponse, type EnforcementAction, type EnforcementDecision, type LogDetectionInput, VERSION, getCheckpointApiClient, getCheckpointPostureOutcome, resetCheckpointApiClient, withCheckpoint, withCheckpointApi };
@@ -3,6 +3,6 @@ import { n as withCheckpointApi, t as CheckpointApiMiddlewareConfig } from "./ap
3
3
  import { t as CheckpointConfig } from "./config-Dn2ptSA2.js";
4
4
  import { n as CheckpointPostureOutcome, r as getCheckpointPostureOutcome, t as CheckpointPostureOptions } from "./posture-outcome-Ccujx_9V.js";
5
5
  import { withCheckpoint } from "./middleware-edge.js";
6
- import { t as VERSION } from "./middleware-core-BLCAErYE.js";
7
- import "./public-api-Ea4jgcwD.js";
6
+ import { t as VERSION } from "./middleware-core-DH6kGKc8.js";
7
+ import "./public-api-D5so-53z.js";
8
8
  export { CheckpointApiClient, type CheckpointApiClientConfig, type CheckpointApiMiddlewareConfig, type CheckpointConfig, type CheckpointPostureOptions, type CheckpointPostureOutcome, type EnforceInput, type EnforceResponse, type EnforcementAction, type EnforcementDecision, type LogDetectionInput, VERSION, getCheckpointApiClient, getCheckpointPostureOutcome, resetCheckpointApiClient, withCheckpoint, withCheckpointApi };
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_middleware_core = require('./middleware-core-tGGPv727.js');
3
- const require_posture_outcome = require('./posture-outcome-DddsJtL8.js');
2
+ const require_middleware_core = require('./middleware-core-yE25rSJE.js');
3
+ const require_posture_outcome = require('./posture-outcome-3mJLVX85.js');
4
4
  const require_api_client = require('./api-client.js');
5
- const require_api_middleware = require('./api-middleware-BVXf7qCM.js');
5
+ const require_api_middleware = require('./api-middleware-Bcu8f06W.js');
6
6
  const require_middleware_edge = require('./middleware-edge.js');
7
7
 
8
8
  exports.CheckpointApiClient = require_api_client.CheckpointApiClient;
@@ -1,7 +1,7 @@
1
- import { t as VERSION } from "./middleware-core-C4xi1I9I.mjs";
2
- import { t as getCheckpointPostureOutcome } from "./posture-outcome-DQ4fdMfq.mjs";
1
+ import { t as VERSION } from "./middleware-core-qXSvMDYw.mjs";
2
+ import { t as getCheckpointPostureOutcome } from "./posture-outcome-CN1WranD.mjs";
3
3
  import { CheckpointApiClient, getCheckpointApiClient, resetCheckpointApiClient } from "./api-client.mjs";
4
- import { t as withCheckpointApi } from "./api-middleware-CAarHFKk.mjs";
4
+ import { t as withCheckpointApi } from "./api-middleware-xhlisoi2.mjs";
5
5
  import { withCheckpoint } from "./middleware-edge.mjs";
6
6
 
7
7
  export { CheckpointApiClient, VERSION, getCheckpointApiClient, getCheckpointPostureOutcome, resetCheckpointApiClient, withCheckpoint, withCheckpointApi };
package/dist/index.d.mts CHANGED
@@ -2,7 +2,7 @@ import { a as EnforceResponse, c as LogDetectionInput, i as EnforceInput, l as g
2
2
  import { n as withCheckpointApi, t as CheckpointApiMiddlewareConfig } from "./api-middleware-CIXuGurw.mjs";
3
3
  import { t as CheckpointConfig } from "./config-CVqpjhwT.mjs";
4
4
  import { n as CheckpointPostureOutcome, r as getCheckpointPostureOutcome, t as CheckpointPostureOptions } from "./posture-outcome-Ccujx_9V.mjs";
5
- import { t as VERSION } from "./middleware-core-D88q8dIt.mjs";
6
- import "./public-api-CBQzjriI.mjs";
5
+ import { t as VERSION } from "./middleware-core-B70g9yLE.mjs";
6
+ import "./public-api-CAJ9XPJC.mjs";
7
7
  import { withCheckpoint } from "./middleware-node.mjs";
8
8
  export { CheckpointApiClient, type CheckpointApiClientConfig, type CheckpointApiMiddlewareConfig, type CheckpointConfig, type CheckpointPostureOptions, type CheckpointPostureOutcome, type EnforceInput, type EnforceResponse, type EnforcementAction, type EnforcementDecision, type LogDetectionInput, VERSION, getCheckpointApiClient, getCheckpointPostureOutcome, resetCheckpointApiClient, withCheckpoint, withCheckpointApi };
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { a as EnforceResponse, c as LogDetectionInput, i as EnforceInput, l as g
2
2
  import { n as withCheckpointApi, t as CheckpointApiMiddlewareConfig } from "./api-middleware-CpAbnkfa.js";
3
3
  import { t as CheckpointConfig } from "./config-Dn2ptSA2.js";
4
4
  import { n as CheckpointPostureOutcome, r as getCheckpointPostureOutcome, t as CheckpointPostureOptions } from "./posture-outcome-Ccujx_9V.js";
5
- import { t as VERSION } from "./middleware-core-BLCAErYE.js";
6
- import "./public-api-Ea4jgcwD.js";
5
+ import { t as VERSION } from "./middleware-core-DH6kGKc8.js";
6
+ import "./public-api-D5so-53z.js";
7
7
  import { withCheckpoint } from "./middleware-node.js";
8
8
  export { CheckpointApiClient, type CheckpointApiClientConfig, type CheckpointApiMiddlewareConfig, type CheckpointConfig, type CheckpointPostureOptions, type CheckpointPostureOutcome, type EnforceInput, type EnforceResponse, type EnforcementAction, type EnforcementDecision, type LogDetectionInput, VERSION, getCheckpointApiClient, getCheckpointPostureOutcome, resetCheckpointApiClient, withCheckpoint, withCheckpointApi };
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_middleware_core = require('./middleware-core-tGGPv727.js');
2
+ const require_middleware_core = require('./middleware-core-yE25rSJE.js');
3
3
  const require_middleware_node = require('./middleware-node.js');
4
- const require_posture_outcome = require('./posture-outcome-DddsJtL8.js');
4
+ const require_posture_outcome = require('./posture-outcome-3mJLVX85.js');
5
5
  const require_api_client = require('./api-client.js');
6
- const require_api_middleware = require('./api-middleware-BVXf7qCM.js');
6
+ const require_api_middleware = require('./api-middleware-Bcu8f06W.js');
7
7
 
8
8
  //#region src/index.ts
9
9
  /**
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { t as VERSION } from "./middleware-core-C4xi1I9I.mjs";
1
+ import { t as VERSION } from "./middleware-core-qXSvMDYw.mjs";
2
2
  import { withCheckpoint } from "./middleware-node.mjs";
3
- import { t as getCheckpointPostureOutcome } from "./posture-outcome-DQ4fdMfq.mjs";
3
+ import { t as getCheckpointPostureOutcome } from "./posture-outcome-CN1WranD.mjs";
4
4
  import { CheckpointApiClient, getCheckpointApiClient, resetCheckpointApiClient } from "./api-client.mjs";
5
- import { t as withCheckpointApi } from "./api-middleware-CAarHFKk.mjs";
5
+ import { t as withCheckpointApi } from "./api-middleware-xhlisoi2.mjs";
6
6
 
7
7
  //#region src/index.ts
8
8
  /**
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_middleware_core = require('./middleware-core-tGGPv727.js');
2
+ const require_middleware_core = require('./middleware-core-yE25rSJE.js');
3
3
  const require_middleware_node_context = require('./middleware-node-context-TRMTgp3y.js');
4
4
 
5
5
  //#region src/middleware-bundler.ts
@@ -1,4 +1,4 @@
1
- import { n as makeNextMiddleware } from "./middleware-core-C4xi1I9I.mjs";
1
+ import { n as makeNextMiddleware } from "./middleware-core-qXSvMDYw.mjs";
2
2
  import { t as nodePolicyCompiler } from "./middleware-node-context-BvqrL2Ra.mjs";
3
3
 
4
4
  //#region src/middleware-bundler.ts
@@ -8,7 +8,7 @@ import { NextRequest, NextResponse } from "next/server.js";
8
8
  * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
9
9
  * drifted). Re-exported as `VERSION` from the package index.
10
10
  */
11
- declare const VERSION = "1.14.0";
11
+ declare const VERSION = "1.15.0";
12
12
  //#endregion
13
13
  export { VERSION as t };
14
- //# sourceMappingURL=middleware-core-D88q8dIt.d.mts.map
14
+ //# sourceMappingURL=middleware-core-B70g9yLE.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware-core-B70g9yLE.d.mts","names":[],"sources":["../src/middleware-core.ts"],"mappings":";;;;;;;;;;cA4Da"}
@@ -8,7 +8,7 @@ import "@kya-os/checkpoint-wasm-runtime/pipeline";
8
8
  * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
9
9
  * drifted). Re-exported as `VERSION` from the package index.
10
10
  */
11
- declare const VERSION = "1.14.0";
11
+ declare const VERSION = "1.15.0";
12
12
  //#endregion
13
13
  export { VERSION as t };
14
- //# sourceMappingURL=middleware-core-BLCAErYE.d.ts.map
14
+ //# sourceMappingURL=middleware-core-DH6kGKc8.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware-core-DH6kGKc8.d.ts","names":[],"sources":["../src/middleware-core.ts"],"mappings":";;;;;;;;;;cA4Da"}
@@ -1,5 +1,5 @@
1
1
  import { n as failClosedResponse, r as signedBodyTooLargeResponse, t as adaptToNextResponse } from "./adapt-BGEyLf44.mjs";
2
- import { t as getClientIp } from "./utils-Cnwg0VrY.mjs";
2
+ import { t as getClientIp } from "./utils-DK9HXCUV.mjs";
3
3
  import { logPipelineFailure, makeCheckpointPipeline } from "@kya-os/checkpoint-wasm-runtime/pipeline";
4
4
  import { waitUntil } from "@vercel/functions";
5
5
  import { KYA_SIGNED_BODY_MAX_BYTES, readBodyBounded, requestPresentsKyaSignature } from "@kya-os/checkpoint-shared/kya-http";
@@ -112,7 +112,7 @@ const SDK_NAME = "@kya-os/checkpoint-nextjs";
112
112
  * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
113
113
  * drifted). Re-exported as `VERSION` from the package index.
114
114
  */
115
- const VERSION = "1.14.0";
115
+ const VERSION = "1.15.0";
116
116
  /**
117
117
  * Build the Checkpoint middleware. Returns a function `(req) => NextResponse`
118
118
  * suitable for `export default withCheckpoint({...})` in `middleware.ts`.
@@ -190,4 +190,4 @@ function extractReporterContext(req, policy) {
190
190
 
191
191
  //#endregion
192
192
  export { makeNextMiddleware as n, VERSION as t };
193
- //# sourceMappingURL=middleware-core-C4xi1I9I.mjs.map
193
+ //# sourceMappingURL=middleware-core-qXSvMDYw.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"middleware-core-C4xi1I9I.mjs","names":["waitUntil","vercelWaitUntil"],"sources":["../src/translate.ts","../src/middleware-core.ts"],"sourcesContent":["/**\n * D.2 — `NextRequest` → `IncomingHttpLike` translator.\n *\n * The host wrapper's *only* job on the inbound path: take Next.js's\n * native request shape and produce the transport-agnostic\n * `IncomingHttpLike` Phase C's orchestrator consumes. Zero verification\n * logic, zero adapter calls, zero engine I/O.\n *\n * Shared between the Node-runtime and Edge-runtime entries. Next.js\n * `NextRequest` is the same shape in both runtimes — `req.headers` is\n * a `Headers` instance, `req.body` is a `ReadableStream`, `req.ip` is\n * a getter (only present in some deployment surfaces; forwarding headers\n * are considered only when the caller selects a matching trust policy).\n */\n\nimport type { NextRequest } from 'next/server.js';\n\nimport type { IncomingHttpLike } from '@kya-os/checkpoint-wasm-runtime/orchestrator';\nimport type { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';\nimport {\n KYA_SIGNED_BODY_MAX_BYTES,\n readBodyBounded,\n requestPresentsKyaSignature,\n} from '@kya-os/checkpoint-shared/kya-http';\n\nimport { getClientIp } from './utils';\n\n/**\n * Options controlling translator side effects.\n *\n * `drainJsonBody` (default `true`) controls whether the translator\n * reads the request body: JSON bodies so the orchestrator can extract a\n * KYA-OS envelope from `_meta.proof.jws` (the canonical spec-form\n * transport), and the exact bytes of a kya-http/2 signed request so the\n * KYA HTTP Binding can check its `Content-Digest`.\n *\n * Trade-off — body draining consumes the request stream. We read a\n * `req.clone()` so the original `req.body` stream is preserved for\n * downstream Next.js handlers. Cloning has memory overhead\n * proportional to the body size; for large request bodies (>1 MB) or\n * streaming-sensitive routes, set `drainJsonBody: false` and verify\n * envelopes via the `KYA-Delegation` header transport instead (the\n * legacy form, requires `legacyEnvelopeFallback: true` on\n * `withCheckpoint`). With draining off, a kya-http/2 request whose\n * `Content-Length` or `Transfer-Encoding` declares a body is refused,\n * because the body cannot be bound to its signature.\n */\nexport interface NextRequestToHttpLikeOpts {\n /**\n * Read the request body when `content-type` is `application/json` or the\n * request carries a kya-http/2 signature. Default `true`. Set `false`\n * for streaming middlewares that can't tolerate the clone/read overhead.\n */\n drainJsonBody?: boolean;\n /** Deployment trust profile. Defaults to direct/peer-only fail-closed behavior. */\n clientIpPolicy?: ClientIpTrustPolicy;\n}\n\n/** {@link translateNextRequest}'s result. */\nexport interface TranslatedNextRequest {\n httpLike: IncomingHttpLike;\n /** A kya-http/2 signed body over 1 MiB: the middleware answers 413 (enforce mode). */\n signedBodyTooLarge: boolean;\n}\n\n/**\n * Translate a Next.js `NextRequest` into the orchestrator's\n * `IncomingHttpLike` shape.\n *\n * When `opts.drainJsonBody !== false` the translator reads a clone of\n * the request body: JSON as a string so `buildAgentRequest` can extract\n * a `_meta.proof.jws` envelope, and the body of a kya-http/2 signed\n * request as its exact bytes (`rawBody`) for the `Content-Digest` check.\n * The original `req.body` stream is preserved for downstream handlers.\n *\n * When the body can't be read (drain disabled, non-JSON unsigned, or a\n * stream error) we pass `body: null` and the orchestrator routes to\n * PlainHttp — same behavior as the pre-1.1.0 default. A kya-http/2\n * request whose `Content-Length` or `Transfer-Encoding` declares a body\n * the engine never received is refused by the orchestrator.\n */\nexport async function translateNextRequest(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts = {}\n): Promise<TranslatedNextRequest> {\n const url = new URL(req.url);\n const { body, rawBody, signedBodyTooLarge } = await tryDrainBody(req, opts);\n return {\n httpLike: {\n method: req.method,\n // Path + query only — orchestrator's URL parsing expects no scheme/host.\n url: url.pathname + url.search,\n headers: headersToRecord(req.headers),\n body,\n ...(rawBody ? { rawBody } : {}),\n remoteAddress: getClientIp(req, opts.clientIpPolicy),\n },\n signedBodyTooLarge,\n };\n}\n\n/** {@link translateNextRequest} without the over-cap signal. */\nexport async function nextRequestToHttpLike(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts = {}\n): Promise<IncomingHttpLike> {\n return (await translateNextRequest(req, opts)).httpLike;\n}\n\ninterface DrainedBody {\n body: string | null;\n rawBody?: Uint8Array;\n signedBodyTooLarge: boolean;\n}\n\n/**\n * Read the request body when the caller has opted in (default). Returns\n * `body: null` on any failure — the orchestrator handles `null` as \"no\n * body present\" (→ PlainHttp).\n *\n * Clone-first means the original `req.body` ReadableStream stays\n * unconsumed and downstream handlers can re-read it. Without the\n * clone, calling `req.text()` in middleware would block any route\n * handler that needs the body.\n */\nasync function tryDrainBody(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts\n): Promise<DrainedBody> {\n if (opts.drainJsonBody === false) return { body: null, signedBodyTooLarge: false };\n const contentType = req.headers.get('content-type') ?? '';\n const isJson = contentType.toLowerCase().includes('application/json');\n // Any content type: a kya-http/2 signature binds the body bytes, not a\n // parsed form of them. Gated on a `kya` signature member so ordinary\n // uploads and vendor signatures are never buffered here. A signed body\n // the bounded read could not take is withheld entirely, JSON included:\n // falling through to the unbounded text read below would hand the engine\n // the body anyway.\n if (requestPresentsKyaSignature(req.headers)) {\n const read = await readBodyBounded(req, KYA_SIGNED_BODY_MAX_BYTES);\n if ('failure' in read) {\n return { body: null, signedBodyTooLarge: read.failure === 'too-large' };\n }\n return {\n body: isJson ? new TextDecoder().decode(read.bytes) : null,\n rawBody: read.bytes,\n signedBodyTooLarge: false,\n };\n }\n if (!isJson) return { body: null, signedBodyTooLarge: false };\n try {\n return { body: await req.clone().text(), signedBodyTooLarge: false };\n } catch {\n // Body unreadable (stream errored, content-length mismatch, etc.).\n // Falling through to null routes the request as PlainHttp —\n // identical behavior to the pre-1.1.0 default.\n return { body: null, signedBodyTooLarge: false };\n }\n}\n\n/**\n * Convert a `Headers` instance into a lowercase-keyed plain object.\n * HTTP header names are case-insensitive (RFC 9110 § 5.1); the\n * orchestrator does case-sensitive lookups, so we normalise to\n * lowercase here. Multi-value headers (Set-Cookie, Accept) are\n * surfaced as their `Headers.get()` view — a single string with\n * comma-joined values, matching what other host adapters produce.\n */\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n headers.forEach((value, key) => {\n out[key.toLowerCase()] = value;\n });\n return out;\n}\n","/**\n * The Next.js side of the shared request pipeline\n * (`@kya-os/checkpoint-wasm-runtime/pipeline`). Node, bundler and Edge hosts\n * inject their engine and Cedar compiler; runtime-specific WASM initialization\n * stays in each host entry. Public withCheckpoint exports live there too.\n */\n\nimport {\n logPipelineFailure,\n makeCheckpointPipeline,\n type PipelineEngine,\n type PolicyCompile,\n} from '@kya-os/checkpoint-wasm-runtime/pipeline';\nimport type { ReporterContext } from '@kya-os/checkpoint-wasm-runtime/reporter';\nimport type { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';\n\nimport { type NextFetchEvent, type NextRequest, type NextResponse } from 'next/server.js';\n\nimport { waitUntil as vercelWaitUntil } from '@vercel/functions';\n\nimport { adaptToNextResponse, failClosedResponse, signedBodyTooLargeResponse } from './adapt';\nimport type { CheckpointConfig } from './config';\nimport { translateNextRequest } from './translate';\nimport { getClientIp } from './utils';\n\n// `CheckpointConfig` lives in `./config`; the public import paths (`.`,\n// `/node`, `/edge`) stay stable via this re-export.\nexport type { CheckpointConfig } from './config';\n\n/** The engine a host runs: one `./orchestrator` build of wasm-runtime. */\nexport type EngineEntry = PipelineEngine;\n\nexport interface NextMiddlewareHost {\n runtime: 'node' | 'edge';\n /**\n * Loads the engine. Hosts import it lazily, so a failure to load the engine\n * (a missing or unreadable `.wasm`) rejects here, inside the request\n * pipeline, and is answered 503 instead of failing the middleware module.\n */\n loadEngine: () => Promise<EngineEntry>;\n /** The Cedar compiler this runtime can load, for the project's composed policy. */\n policyCompiler: (config: CheckpointConfig) => PolicyCompile;\n /** Host-specific setup, run once with the rest; it may throw. */\n start?: (config: CheckpointConfig) => void;\n}\n\ntype CheckpointMiddleware = (\n req: NextRequest,\n event?: Pick<NextFetchEvent, 'waitUntil'>\n) => Promise<NextResponse>;\n\n/** npm package name this SDK self-reports to the detection reporter. */\nconst SDK_NAME = '@kya-os/checkpoint-nextjs';\n\n/**\n * Installed SDK version, self-reported to the detection reporter so the\n * dashboard can version-gate \"composed policy enforces here\". MUST equal\n * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had\n * drifted). Re-exported as `VERSION` from the package index.\n */\nexport const VERSION = '1.14.0';\n\n/**\n * Build the Checkpoint middleware. Returns a function `(req) => NextResponse`\n * suitable for `export default withCheckpoint({...})` in `middleware.ts`.\n *\n * Every verification decision flows through the Rust `kya-os-engine`\n * via WASM. The TS layer translates request shape, runs the shared\n * pipeline, and translates the verdict to `NextResponse`. No\n * verification logic lives in this file.\n *\n * It never throws. An error in the configuration or in loading the engine\n * would otherwise fail the middleware module, and a Next.js middleware that\n * fails to load can let requests through unchecked. Every such error is\n * answered 503 instead (fail closed) and logged.\n */\nexport function makeNextMiddleware(\n config: CheckpointConfig,\n host: NextMiddlewareHost\n): CheckpointMiddleware {\n try {\n return makeMiddleware(config, host);\n } catch (error) {\n return async function misconfiguredCheckpointMiddleware() {\n console.error('[checkpoint] withCheckpoint is misconfigured; responding 503:', error);\n return failClosedResponse();\n };\n }\n}\n\nfunction makeMiddleware(config: CheckpointConfig, host: NextMiddlewareHost): CheckpointMiddleware {\n const pipeline = makeCheckpointPipeline<NextRequest, CheckpointConfig>(config, {\n // Self-identify (incl. node-vs-edge) so the dashboard can version-gate\n // enforcement. Next.js EDGE composed enforcement is opt-in (needs a Cedar\n // module), so the dashboard shows it as opt-in, never \"Enforcing\".\n sdk: { name: SDK_NAME, version: VERSION, runtime: host.runtime },\n loadEngine: host.loadEngine,\n policyCompiler: host.policyCompiler,\n start: host.start,\n });\n const translateOpts = {\n drainJsonBody: config.drainJsonBody,\n clientIpPolicy: config.clientIpPolicy,\n };\n return async function checkpointMiddleware(\n req: NextRequest,\n event?: Pick<NextFetchEvent, 'waitUntil'>\n ): Promise<NextResponse> {\n // Work that outlives the response (the engine's vendor key feed round, the\n // detection report) must be registered, or Vercel and Workers cancel it\n // once the response is sent. Next.js passes the event to middleware; a\n // wrapper that drops it falls back to Vercel's request context.\n const waitUntil = event\n ? (promise: Promise<unknown>) => event.waitUntil(promise)\n : vercelWaitUntil;\n try {\n // A kya-http/2 signed body is read here, before the shared pipeline: over\n // the cap it is answered 413 and never verified in part, as the .NET\n // adapters do. Observe mode passes everything through: the request goes\n // on to verification without its bytes, the orchestrator refuses it\n // there, and observe reports that as the would-have-been Block.\n const { httpLike, signedBodyTooLarge } = await translateNextRequest(req, translateOpts);\n if (signedBodyTooLarge && config.enforcementMode !== 'observe') {\n return signedBodyTooLargeResponse();\n }\n const { rendered } = await pipeline({\n request: req,\n translate: () => httpLike,\n headers: req.headers,\n // The query-free path verification saw.\n path: req.nextUrl.pathname,\n clientIp: () => getClientIp(req, config.clientIpPolicy),\n reportContext: () => extractReporterContext(req, config.clientIpPolicy),\n waitUntil,\n });\n return adaptToNextResponse(rendered, req);\n } catch (err) {\n logPipelineFailure(err, config.debug);\n return failClosedResponse();\n }\n };\n}\n\n/**\n * Pull the request context the dashboard's `/api/v1/log-detection`\n * endpoint expects out of a `NextRequest`. Works under both Node and\n * Edge runtimes — no runtime-specific APIs.\n */\nfunction extractReporterContext(\n req: NextRequest,\n policy: ClientIpTrustPolicy | undefined\n): ReporterContext {\n return {\n userAgent: req.headers.get('user-agent') ?? undefined,\n ipAddress: getClientIp(req, policy),\n path: req.nextUrl.pathname,\n url: req.nextUrl.href,\n method: req.method,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;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I,QAAQ;EACjB,QAAQ,IAAI;CACd;AACF"}
1
+ {"version":3,"file":"middleware-core-qXSvMDYw.mjs","names":["waitUntil","vercelWaitUntil"],"sources":["../src/translate.ts","../src/middleware-core.ts"],"sourcesContent":["/**\n * D.2 — `NextRequest` → `IncomingHttpLike` translator.\n *\n * The host wrapper's *only* job on the inbound path: take Next.js's\n * native request shape and produce the transport-agnostic\n * `IncomingHttpLike` Phase C's orchestrator consumes. Zero verification\n * logic, zero adapter calls, zero engine I/O.\n *\n * Shared between the Node-runtime and Edge-runtime entries. Next.js\n * `NextRequest` is the same shape in both runtimes — `req.headers` is\n * a `Headers` instance, `req.body` is a `ReadableStream`, `req.ip` is\n * a getter (only present in some deployment surfaces; forwarding headers\n * are considered only when the caller selects a matching trust policy).\n */\n\nimport type { NextRequest } from 'next/server.js';\n\nimport type { IncomingHttpLike } from '@kya-os/checkpoint-wasm-runtime/orchestrator';\nimport type { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';\nimport {\n KYA_SIGNED_BODY_MAX_BYTES,\n readBodyBounded,\n requestPresentsKyaSignature,\n} from '@kya-os/checkpoint-shared/kya-http';\n\nimport { getClientIp } from './utils';\n\n/**\n * Options controlling translator side effects.\n *\n * `drainJsonBody` (default `true`) controls whether the translator\n * reads the request body: JSON bodies so the orchestrator can extract a\n * KYA-OS envelope from `_meta.proof.jws` (the canonical spec-form\n * transport), and the exact bytes of a kya-http/2 signed request so the\n * KYA HTTP Binding can check its `Content-Digest`.\n *\n * Trade-off — body draining consumes the request stream. We read a\n * `req.clone()` so the original `req.body` stream is preserved for\n * downstream Next.js handlers. Cloning has memory overhead\n * proportional to the body size; for large request bodies (>1 MB) or\n * streaming-sensitive routes, set `drainJsonBody: false` and verify\n * envelopes via the `KYA-Delegation` header transport instead (the\n * legacy form, requires `legacyEnvelopeFallback: true` on\n * `withCheckpoint`). With draining off, a kya-http/2 request whose\n * `Content-Length` or `Transfer-Encoding` declares a body is refused,\n * because the body cannot be bound to its signature.\n */\nexport interface NextRequestToHttpLikeOpts {\n /**\n * Read the request body when `content-type` is `application/json` or the\n * request carries a kya-http/2 signature. Default `true`. Set `false`\n * for streaming middlewares that can't tolerate the clone/read overhead.\n */\n drainJsonBody?: boolean;\n /** Deployment trust profile. Defaults to direct/peer-only fail-closed behavior. */\n clientIpPolicy?: ClientIpTrustPolicy;\n}\n\n/** {@link translateNextRequest}'s result. */\nexport interface TranslatedNextRequest {\n httpLike: IncomingHttpLike;\n /** A kya-http/2 signed body over 1 MiB: the middleware answers 413 (enforce mode). */\n signedBodyTooLarge: boolean;\n}\n\n/**\n * Translate a Next.js `NextRequest` into the orchestrator's\n * `IncomingHttpLike` shape.\n *\n * When `opts.drainJsonBody !== false` the translator reads a clone of\n * the request body: JSON as a string so `buildAgentRequest` can extract\n * a `_meta.proof.jws` envelope, and the body of a kya-http/2 signed\n * request as its exact bytes (`rawBody`) for the `Content-Digest` check.\n * The original `req.body` stream is preserved for downstream handlers.\n *\n * When the body can't be read (drain disabled, non-JSON unsigned, or a\n * stream error) we pass `body: null` and the orchestrator routes to\n * PlainHttp — same behavior as the pre-1.1.0 default. A kya-http/2\n * request whose `Content-Length` or `Transfer-Encoding` declares a body\n * the engine never received is refused by the orchestrator.\n */\nexport async function translateNextRequest(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts = {}\n): Promise<TranslatedNextRequest> {\n const url = new URL(req.url);\n const { body, rawBody, signedBodyTooLarge } = await tryDrainBody(req, opts);\n return {\n httpLike: {\n method: req.method,\n // Path + query only — orchestrator's URL parsing expects no scheme/host.\n url: url.pathname + url.search,\n headers: headersToRecord(req.headers),\n body,\n ...(rawBody ? { rawBody } : {}),\n remoteAddress: getClientIp(req, opts.clientIpPolicy),\n },\n signedBodyTooLarge,\n };\n}\n\n/** {@link translateNextRequest} without the over-cap signal. */\nexport async function nextRequestToHttpLike(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts = {}\n): Promise<IncomingHttpLike> {\n return (await translateNextRequest(req, opts)).httpLike;\n}\n\ninterface DrainedBody {\n body: string | null;\n rawBody?: Uint8Array;\n signedBodyTooLarge: boolean;\n}\n\n/**\n * Read the request body when the caller has opted in (default). Returns\n * `body: null` on any failure — the orchestrator handles `null` as \"no\n * body present\" (→ PlainHttp).\n *\n * Clone-first means the original `req.body` ReadableStream stays\n * unconsumed and downstream handlers can re-read it. Without the\n * clone, calling `req.text()` in middleware would block any route\n * handler that needs the body.\n */\nasync function tryDrainBody(\n req: NextRequest,\n opts: NextRequestToHttpLikeOpts\n): Promise<DrainedBody> {\n if (opts.drainJsonBody === false) return { body: null, signedBodyTooLarge: false };\n const contentType = req.headers.get('content-type') ?? '';\n const isJson = contentType.toLowerCase().includes('application/json');\n // Any content type: a kya-http/2 signature binds the body bytes, not a\n // parsed form of them. Gated on a `kya` signature member so ordinary\n // uploads and vendor signatures are never buffered here. A signed body\n // the bounded read could not take is withheld entirely, JSON included:\n // falling through to the unbounded text read below would hand the engine\n // the body anyway.\n if (requestPresentsKyaSignature(req.headers)) {\n const read = await readBodyBounded(req, KYA_SIGNED_BODY_MAX_BYTES);\n if ('failure' in read) {\n return { body: null, signedBodyTooLarge: read.failure === 'too-large' };\n }\n return {\n body: isJson ? new TextDecoder().decode(read.bytes) : null,\n rawBody: read.bytes,\n signedBodyTooLarge: false,\n };\n }\n if (!isJson) return { body: null, signedBodyTooLarge: false };\n try {\n return { body: await req.clone().text(), signedBodyTooLarge: false };\n } catch {\n // Body unreadable (stream errored, content-length mismatch, etc.).\n // Falling through to null routes the request as PlainHttp —\n // identical behavior to the pre-1.1.0 default.\n return { body: null, signedBodyTooLarge: false };\n }\n}\n\n/**\n * Convert a `Headers` instance into a lowercase-keyed plain object.\n * HTTP header names are case-insensitive (RFC 9110 § 5.1); the\n * orchestrator does case-sensitive lookups, so we normalise to\n * lowercase here. Multi-value headers (Set-Cookie, Accept) are\n * surfaced as their `Headers.get()` view — a single string with\n * comma-joined values, matching what other host adapters produce.\n */\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n headers.forEach((value, key) => {\n out[key.toLowerCase()] = value;\n });\n return out;\n}\n","/**\n * The Next.js side of the shared request pipeline\n * (`@kya-os/checkpoint-wasm-runtime/pipeline`). Node, bundler and Edge hosts\n * inject their engine and Cedar compiler; runtime-specific WASM initialization\n * stays in each host entry. Public withCheckpoint exports live there too.\n */\n\nimport {\n logPipelineFailure,\n makeCheckpointPipeline,\n type PipelineEngine,\n type PolicyCompile,\n} from '@kya-os/checkpoint-wasm-runtime/pipeline';\nimport type { ReporterContext } from '@kya-os/checkpoint-wasm-runtime/reporter';\nimport type { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared';\n\nimport { type NextFetchEvent, type NextRequest, type NextResponse } from 'next/server.js';\n\nimport { waitUntil as vercelWaitUntil } from '@vercel/functions';\n\nimport { adaptToNextResponse, failClosedResponse, signedBodyTooLargeResponse } from './adapt';\nimport type { CheckpointConfig } from './config';\nimport { translateNextRequest } from './translate';\nimport { getClientIp } from './utils';\n\n// `CheckpointConfig` lives in `./config`; the public import paths (`.`,\n// `/node`, `/edge`) stay stable via this re-export.\nexport type { CheckpointConfig } from './config';\n\n/** The engine a host runs: one `./orchestrator` build of wasm-runtime. */\nexport type EngineEntry = PipelineEngine;\n\nexport interface NextMiddlewareHost {\n runtime: 'node' | 'edge';\n /**\n * Loads the engine. Hosts import it lazily, so a failure to load the engine\n * (a missing or unreadable `.wasm`) rejects here, inside the request\n * pipeline, and is answered 503 instead of failing the middleware module.\n */\n loadEngine: () => Promise<EngineEntry>;\n /** The Cedar compiler this runtime can load, for the project's composed policy. */\n policyCompiler: (config: CheckpointConfig) => PolicyCompile;\n /** Host-specific setup, run once with the rest; it may throw. */\n start?: (config: CheckpointConfig) => void;\n}\n\ntype CheckpointMiddleware = (\n req: NextRequest,\n event?: Pick<NextFetchEvent, 'waitUntil'>\n) => Promise<NextResponse>;\n\n/** npm package name this SDK self-reports to the detection reporter. */\nconst SDK_NAME = '@kya-os/checkpoint-nextjs';\n\n/**\n * Installed SDK version, self-reported to the detection reporter so the\n * dashboard can version-gate \"composed policy enforces here\". MUST equal\n * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had\n * drifted). Re-exported as `VERSION` from the package index.\n */\nexport const VERSION = '1.15.0';\n\n/**\n * Build the Checkpoint middleware. Returns a function `(req) => NextResponse`\n * suitable for `export default withCheckpoint({...})` in `middleware.ts`.\n *\n * Every verification decision flows through the Rust `kya-os-engine`\n * via WASM. The TS layer translates request shape, runs the shared\n * pipeline, and translates the verdict to `NextResponse`. No\n * verification logic lives in this file.\n *\n * It never throws. An error in the configuration or in loading the engine\n * would otherwise fail the middleware module, and a Next.js middleware that\n * fails to load can let requests through unchecked. Every such error is\n * answered 503 instead (fail closed) and logged.\n */\nexport function makeNextMiddleware(\n config: CheckpointConfig,\n host: NextMiddlewareHost\n): CheckpointMiddleware {\n try {\n return makeMiddleware(config, host);\n } catch (error) {\n return async function misconfiguredCheckpointMiddleware() {\n console.error('[checkpoint] withCheckpoint is misconfigured; responding 503:', error);\n return failClosedResponse();\n };\n }\n}\n\nfunction makeMiddleware(config: CheckpointConfig, host: NextMiddlewareHost): CheckpointMiddleware {\n const pipeline = makeCheckpointPipeline<NextRequest, CheckpointConfig>(config, {\n // Self-identify (incl. node-vs-edge) so the dashboard can version-gate\n // enforcement. Next.js EDGE composed enforcement is opt-in (needs a Cedar\n // module), so the dashboard shows it as opt-in, never \"Enforcing\".\n sdk: { name: SDK_NAME, version: VERSION, runtime: host.runtime },\n loadEngine: host.loadEngine,\n policyCompiler: host.policyCompiler,\n start: host.start,\n });\n const translateOpts = {\n drainJsonBody: config.drainJsonBody,\n clientIpPolicy: config.clientIpPolicy,\n };\n return async function checkpointMiddleware(\n req: NextRequest,\n event?: Pick<NextFetchEvent, 'waitUntil'>\n ): Promise<NextResponse> {\n // Work that outlives the response (the engine's vendor key feed round, the\n // detection report) must be registered, or Vercel and Workers cancel it\n // once the response is sent. Next.js passes the event to middleware; a\n // wrapper that drops it falls back to Vercel's request context.\n const waitUntil = event\n ? (promise: Promise<unknown>) => event.waitUntil(promise)\n : vercelWaitUntil;\n try {\n // A kya-http/2 signed body is read here, before the shared pipeline: over\n // the cap it is answered 413 and never verified in part, as the .NET\n // adapters do. Observe mode passes everything through: the request goes\n // on to verification without its bytes, the orchestrator refuses it\n // there, and observe reports that as the would-have-been Block.\n const { httpLike, signedBodyTooLarge } = await translateNextRequest(req, translateOpts);\n if (signedBodyTooLarge && config.enforcementMode !== 'observe') {\n return signedBodyTooLargeResponse();\n }\n const { rendered } = await pipeline({\n request: req,\n translate: () => httpLike,\n headers: req.headers,\n // The query-free path verification saw.\n path: req.nextUrl.pathname,\n clientIp: () => getClientIp(req, config.clientIpPolicy),\n reportContext: () => extractReporterContext(req, config.clientIpPolicy),\n waitUntil,\n });\n return adaptToNextResponse(rendered, req);\n } catch (err) {\n logPipelineFailure(err, config.debug);\n return failClosedResponse();\n }\n };\n}\n\n/**\n * Pull the request context the dashboard's `/api/v1/log-detection`\n * endpoint expects out of a `NextRequest`. Works under both Node and\n * Edge runtimes — no runtime-specific APIs.\n */\nfunction extractReporterContext(\n req: NextRequest,\n policy: ClientIpTrustPolicy | undefined\n): ReporterContext {\n return {\n userAgent: req.headers.get('user-agent') ?? undefined,\n ipAddress: getClientIp(req, policy),\n path: req.nextUrl.pathname,\n url: req.nextUrl.href,\n method: req.method,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiFA,eAAsB,qBACpB,KACA,OAAkC,CAAC,GACH;CAChC,MAAM,MAAM,IAAI,IAAI,IAAI,GAAG;CAC3B,MAAM,EAAE,MAAM,SAAS,uBAAuB,MAAM,aAAa,KAAK,IAAI;CAC1E,OAAO;EACL,UAAU;GACR,QAAQ,IAAI;GAEZ,KAAK,IAAI,WAAW,IAAI;GACxB,SAAS,gBAAgB,IAAI,OAAO;GACpC;GACA,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;GAC7B,eAAe,Y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QAAQ;EAI7E,KAAK;GAAE,MAAM;GAAU,SAAS;GAAS,SAAS,KAAK;EAAQ;EAC/D,YAAY,KAAK;EACjB,gBAAgB,KAAK;EACrB,OAAO,KAAK;CACd,CAAC;CACD,MAAM,gBAAgB;EACpB,eAAe,OAAO;EACtB,gBAAgB,OAAO;CACzB;CACA,OAAO,eAAe,qBACpB,KACA,OACuB;EAKvB,MAAMA,cAAY,SACb,YAA8B,MAAM,UAAU,OAAO,IACtDC;EACJ,IAAI;GAMF,MAAM,EAAE,UAAU,uBAAuB,MAAM,qBAAqB,KAAK,aAAa;GACtF,IAAI,sBAAsB,OAAO,oBAAoB,WACnD,OAAO,2BAA2B;GAEpC,MAAM,EAAE,aAAa,MAAM,SAAS;IAClC,SAAS;IACT,iBAAiB;IACjB,SAAS,IAAI;IAEb,MAAM,IAAI,QAAQ;IAClB,gBAAgB,YAAY,KAAK,OAAO,cAAc;IACtD,qBAAqB,uBAAuB,KAAK,OAAO,cAAc;IACtE;GACF,CAAC;GACD,OAAO,oBAAoB,UAAU,GAAG;EAC1C,SAAS,KAAK;GACZ,mBAAmB,KAAK,OAAO,KAAK;GACpC,OAAO,mBAAmB;EAC5B;CACF;AACF;;;;;;AAOA,SAAS,uBACP,KACA,QACiB;CACjB,OAAO;EACL,WAAW,IAAI,QAAQ,IAAI,YAAY,KAAK;EAC5C,WAAW,YAAY,KAAK,MAAM;EAClC,MAAM,IAAI,QAAQ;EAClB,KAAK,IAAI,QAAQ;EACjB,QAAQ,IAAI;CACd;AACF"}
@@ -1,5 +1,5 @@
1
1
  const require_adapt = require('./adapt-D2-OBY9M.js');
2
- const require_utils = require('./utils-dyFxqlFI.js');
2
+ const require_utils = require('./utils-CdoAQaFy.js');
3
3
  let _kya_os_checkpoint_wasm_runtime_pipeline = require("@kya-os/checkpoint-wasm-runtime/pipeline");
4
4
  let _vercel_functions = require("@vercel/functions");
5
5
  let _kya_os_checkpoint_shared_kya_http = require("@kya-os/checkpoint-shared/kya-http");
@@ -112,7 +112,7 @@ const SDK_NAME = "@kya-os/checkpoint-nextjs";
112
112
  * `package.json` version — pinned by a unit test (the old hardcoded `0.1.0` had
113
113
  * drifted). Re-exported as `VERSION` from the package index.
114
114
  */
115
- const VERSION = "1.14.0";
115
+ const VERSION = "1.15.0";
116
116
  /**
117
117
  * Build the Checkpoint middleware. Returns a function `(req) => NextResponse`
118
118
  * suitable for `export default withCheckpoint({...})` in `middleware.ts`.
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_middleware_core = require('./middleware-core-tGGPv727.js');
3
- const require_posture_outcome = require('./posture-outcome-DddsJtL8.js');
2
+ const require_middleware_core = require('./middleware-core-yE25rSJE.js');
3
+ const require_posture_outcome = require('./posture-outcome-3mJLVX85.js');
4
4
  let _kya_os_checkpoint_wasm_runtime_orchestrator_edge = require("@kya-os/checkpoint-wasm-runtime/orchestrator/edge");
5
5
  let _kya_os_checkpoint_wasm_runtime_policy_edge = require("@kya-os/checkpoint-wasm-runtime/policy-edge");
6
6
 
@@ -1,5 +1,5 @@
1
- import { n as makeNextMiddleware } from "./middleware-core-C4xi1I9I.mjs";
2
- import { t as getCheckpointPostureOutcome } from "./posture-outcome-DQ4fdMfq.mjs";
1
+ import { n as makeNextMiddleware } from "./middleware-core-qXSvMDYw.mjs";
2
+ import { t as getCheckpointPostureOutcome } from "./posture-outcome-CN1WranD.mjs";
3
3
  import { initEngineEdge, renderDecisionAsResponse, verifyRequestEdge } from "@kya-os/checkpoint-wasm-runtime/orchestrator/edge";
4
4
  import { evaluatePolicy, initPolicyEvaluatorEdge, isCedarModule } from "@kya-os/checkpoint-wasm-runtime/policy-edge";
5
5
 
@@ -1,5 +1,5 @@
1
1
  import { t as CheckpointConfig } from "./config-CVqpjhwT.mjs";
2
- import { t as VERSION } from "./middleware-core-D88q8dIt.mjs";
2
+ import { t as VERSION } from "./middleware-core-B70g9yLE.mjs";
3
3
  //#region src/middleware-node.d.ts
4
4
  /**
5
5
  * `withCheckpoint` on the Node.js runtime, bundled (`proxy.ts`, `middleware.ts`)
@@ -1,5 +1,5 @@
1
1
  import { t as CheckpointConfig } from "./config-Dn2ptSA2.js";
2
- import { t as VERSION } from "./middleware-core-BLCAErYE.js";
2
+ import { t as VERSION } from "./middleware-core-DH6kGKc8.js";
3
3
  //#region src/middleware-node.d.ts
4
4
  /**
5
5
  * `withCheckpoint` on the Node.js runtime, bundled (`proxy.ts`, `middleware.ts`)
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_middleware_core = require('./middleware-core-tGGPv727.js');
2
+ const require_middleware_core = require('./middleware-core-yE25rSJE.js');
3
3
  const require_middleware_node_context = require('./middleware-node-context-TRMTgp3y.js');
4
4
 
5
5
  //#region src/middleware-node.ts
@@ -1,4 +1,4 @@
1
- import { n as makeNextMiddleware, t as VERSION } from "./middleware-core-C4xi1I9I.mjs";
1
+ import { n as makeNextMiddleware, t as VERSION } from "./middleware-core-qXSvMDYw.mjs";
2
2
  import { t as nodePolicyCompiler } from "./middleware-node-context-BvqrL2Ra.mjs";
3
3
 
4
4
  //#region src/middleware-node.ts
@@ -6,11 +6,16 @@ function hasGet(input) {
6
6
  return typeof input.get === "function";
7
7
  }
8
8
  const validatedProjects = /* @__PURE__ */ new WeakMap();
9
+ let warnedLoopbackOrigins = false;
9
10
  async function getCheckpointPostureOutcome(input, options) {
10
11
  if (!options.browserPosture) throw new Error("getCheckpointPostureOutcome requires the browserPosture config");
11
12
  if (validatedProjects.get(options.browserPosture) !== options.projectId) {
12
13
  (0, _kya_os_checkpoint_shared_browser_posture.validateBrowserPostureConfig)(options.browserPosture, options.projectId);
13
14
  validatedProjects.set(options.browserPosture, options.projectId);
15
+ if (options.browserPosture.allowLoopbackOrigins === true && !warnedLoopbackOrigins) {
16
+ warnedLoopbackOrigins = true;
17
+ console.warn(_kya_os_checkpoint_shared_browser_posture.LOOPBACK_ORIGINS_WARNING);
18
+ }
14
19
  }
15
20
  const headers = hasGet(input) ? input : input.headers;
16
21
  return (0, _kya_os_checkpoint_wasm_runtime_composed_policy.postureOutcomeView)(await (0, _kya_os_checkpoint_shared_browser_posture.postureOutcomeFromRequest)((0, _kya_os_checkpoint_shared_browser_posture.postureRequestFromHeaders)((name) => headers.get(name)), options.browserPosture, options.projectId));
@@ -1,4 +1,4 @@
1
- import { postureOutcomeFromRequest, postureRequestFromHeaders, validateBrowserPostureConfig } from "@kya-os/checkpoint-shared/browser-posture";
1
+ import { LOOPBACK_ORIGINS_WARNING, postureOutcomeFromRequest, postureRequestFromHeaders, validateBrowserPostureConfig } from "@kya-os/checkpoint-shared/browser-posture";
2
2
  import { postureOutcomeView } from "@kya-os/checkpoint-wasm-runtime/composed-policy";
3
3
 
4
4
  //#region src/posture-outcome.ts
@@ -6,11 +6,16 @@ function hasGet(input) {
6
6
  return typeof input.get === "function";
7
7
  }
8
8
  const validatedProjects = /* @__PURE__ */ new WeakMap();
9
+ let warnedLoopbackOrigins = false;
9
10
  async function getCheckpointPostureOutcome(input, options) {
10
11
  if (!options.browserPosture) throw new Error("getCheckpointPostureOutcome requires the browserPosture config");
11
12
  if (validatedProjects.get(options.browserPosture) !== options.projectId) {
12
13
  validateBrowserPostureConfig(options.browserPosture, options.projectId);
13
14
  validatedProjects.set(options.browserPosture, options.projectId);
15
+ if (options.browserPosture.allowLoopbackOrigins === true && !warnedLoopbackOrigins) {
16
+ warnedLoopbackOrigins = true;
17
+ console.warn(LOOPBACK_ORIGINS_WARNING);
18
+ }
14
19
  }
15
20
  const headers = hasGet(input) ? input : input.headers;
16
21
  return postureOutcomeView(await postureOutcomeFromRequest(postureRequestFromHeaders((name) => headers.get(name)), options.browserPosture, options.projectId));
@@ -18,4 +23,4 @@ async function getCheckpointPostureOutcome(input, options) {
18
23
 
19
24
  //#endregion
20
25
  export { getCheckpointPostureOutcome as t };
21
- //# sourceMappingURL=posture-outcome-DQ4fdMfq.mjs.map
26
+ //# sourceMappingURL=posture-outcome-CN1WranD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"posture-outcome-CN1WranD.mjs","names":[],"sources":["../src/posture-outcome.ts"],"sourcesContent":["import {\n LOOPBACK_ORIGINS_WARNING,\n postureOutcomeFromRequest,\n postureRequestFromHeaders,\n validateBrowserPostureConfig,\n type BrowserPostureConfig,\n} from '@kya-os/checkpoint-shared/browser-posture';\nimport {\n postureOutcomeView,\n type PostureHandlerView,\n} from '@kya-os/checkpoint-wasm-runtime/composed-policy';\n\nexport type CheckpointPostureOutcome = PostureHandlerView;\n\nexport interface CheckpointPostureOptions {\n browserPosture: BrowserPostureConfig;\n projectId: string;\n}\n\nfunction hasGet(input: Request | Headers | { headers: Headers }): input is Headers {\n return typeof (input as Headers).get === 'function';\n}\n\nconst validatedProjects = new WeakMap<BrowserPostureConfig, string>();\nlet warnedLoopbackOrigins = false;\n\nexport async function getCheckpointPostureOutcome(\n input: Request | Headers | { headers: Headers },\n options: CheckpointPostureOptions\n): Promise<CheckpointPostureOutcome> {\n if (!options.browserPosture) {\n throw new Error('getCheckpointPostureOutcome requires the browserPosture config');\n }\n if (validatedProjects.get(options.browserPosture) !== options.projectId) {\n validateBrowserPostureConfig(options.browserPosture, options.projectId);\n validatedProjects.set(options.browserPosture, options.projectId);\n if (options.browserPosture.allowLoopbackOrigins === true && !warnedLoopbackOrigins) {\n warnedLoopbackOrigins = true;\n console.warn(LOOPBACK_ORIGINS_WARNING);\n }\n }\n const headers = hasGet(input) ? input : input.headers;\n return postureOutcomeView(\n await postureOutcomeFromRequest(\n postureRequestFromHeaders((name) => headers.get(name)),\n options.browserPosture,\n options.projectId\n )\n );\n}\n"],"mappings":";;;;AAmBA,SAAS,OAAO,OAAmE;CACjF,OAAO,OAAQ,MAAkB,QAAQ;AAC3C;AAEA,MAAM,oCAAoB,IAAI,QAAsC;AACpE,IAAI,wBAAwB;AAE5B,eAAsB,4BACpB,OACA,SACmC;CACnC,IAAI,CAAC,QAAQ,gBACX,MAAM,IAAI,MAAM,gEAAgE;CAElF,IAAI,kBAAkB,IAAI,QAAQ,cAAc,MAAM,QAAQ,WAAW;EACvE,6BAA6B,QAAQ,gBAAgB,QAAQ,SAAS;EACtE,kBAAkB,IAAI,QAAQ,gBAAgB,QAAQ,SAAS;EAC/D,IAAI,QAAQ,eAAe,yBAAyB,QAAQ,CAAC,uBAAuB;GAClF,wBAAwB;GACxB,QAAQ,KAAK,wBAAwB;EACvC;CACF;CACA,MAAM,UAAU,OAAO,KAAK,IAAI,QAAQ,MAAM;CAC9C,OAAO,mBACL,MAAM,0BACJ,2BAA2B,SAAS,QAAQ,IAAI,IAAI,CAAC,GACrD,QAAQ,gBACR,QAAQ,SACV,CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"posture-outcome-Ccujx_9V.d.mts","names":[],"sources":["../src/posture-outcome.ts"],"mappings":";;;KAWY,2BAA2B;UAEtB;EACf,gBAAgB;EAChB;;iBASoB,4BACpB,OAAO,UAAU;EAAY,SAAS;GACtC,SAAS,2BACR,QAAQ"}
1
+ {"version":3,"file":"posture-outcome-Ccujx_9V.d.mts","names":[],"sources":["../src/posture-outcome.ts"],"mappings":";;;KAYY,2BAA2B;UAEtB;EACf,gBAAgB;EAChB;;iBAUoB,4BACpB,OAAO,UAAU;EAAY,SAAS;GACtC,SAAS,2BACR,QAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"posture-outcome-Ccujx_9V.d.ts","names":[],"sources":["../src/posture-outcome.ts"],"mappings":";;;KAWY,2BAA2B;UAEtB;EACf,gBAAgB;EAChB;;iBASoB,4BACpB,OAAO,UAAU;EAAY,SAAS;GACtC,SAAS,2BACR,QAAQ"}
1
+ {"version":3,"file":"posture-outcome-Ccujx_9V.d.ts","names":[],"sources":["../src/posture-outcome.ts"],"mappings":";;;KAYY,2BAA2B;UAEtB;EACf,gBAAgB;EAChB;;iBAUoB,4BACpB,OAAO,UAAU;EAAY,SAAS;GACtC,SAAS,2BACR,QAAQ"}
@@ -2,4 +2,4 @@ import "./api-client-yjr43Itz.mjs";
2
2
  import "./api-middleware-CIXuGurw.mjs";
3
3
  import "./config-CVqpjhwT.mjs";
4
4
  import "./posture-outcome-Ccujx_9V.mjs";
5
- import "./middleware-core-D88q8dIt.mjs";
5
+ import "./middleware-core-B70g9yLE.mjs";
@@ -2,4 +2,4 @@ import "./api-client-yjr43Itz.js";
2
2
  import "./api-middleware-CpAbnkfa.js";
3
3
  import "./config-Dn2ptSA2.js";
4
4
  import "./posture-outcome-Ccujx_9V.js";
5
- import "./middleware-core-BLCAErYE.js";
5
+ import "./middleware-core-DH6kGKc8.js";
@@ -34,6 +34,16 @@ function safeHostname(url) {
34
34
  return "this site";
35
35
  }
36
36
  }
37
+ /**
38
+ * Set `KYA-Confidence` to the decision's confidence as a whole number from
39
+ * 0 to 100, as the gateway and the .NET SDK (`F0`) send it. The confidence
40
+ * is a float, so 99.99999999993561 goes out as "100". A decision without a
41
+ * finite confidence leaves the header off rather than sending "NaN".
42
+ */
43
+ function setConfidenceHeader(headers, confidence) {
44
+ if (!Number.isFinite(confidence)) return;
45
+ headers.set("KYA-Confidence", Math.round(confidence).toString());
46
+ }
37
47
  const DROPPED_HEADERS = [
38
48
  "cookie",
39
49
  "authorization",
@@ -101,4 +111,10 @@ Object.defineProperty(exports, 'safeHostname', {
101
111
  get: function () {
102
112
  return safeHostname;
103
113
  }
114
+ });
115
+ Object.defineProperty(exports, 'setConfidenceHeader', {
116
+ enumerable: true,
117
+ get: function () {
118
+ return setConfidenceHeader;
119
+ }
104
120
  });
@@ -34,6 +34,16 @@ function safeHostname(url) {
34
34
  return "this site";
35
35
  }
36
36
  }
37
+ /**
38
+ * Set `KYA-Confidence` to the decision's confidence as a whole number from
39
+ * 0 to 100, as the gateway and the .NET SDK (`F0`) send it. The confidence
40
+ * is a float, so 99.99999999993561 goes out as "100". A decision without a
41
+ * finite confidence leaves the header off rather than sending "NaN".
42
+ */
43
+ function setConfidenceHeader(headers, confidence) {
44
+ if (!Number.isFinite(confidence)) return;
45
+ headers.set("KYA-Confidence", Math.round(confidence).toString());
46
+ }
37
47
  const DROPPED_HEADERS = [
38
48
  "cookie",
39
49
  "authorization",
@@ -84,5 +94,5 @@ function relayHeaders(input) {
84
94
  }
85
95
 
86
96
  //#endregion
87
- export { relayHeaders as n, safeHostname as r, getClientIp as t };
88
- //# sourceMappingURL=utils-Cnwg0VrY.mjs.map
97
+ export { setConfidenceHeader as i, relayHeaders as n, safeHostname as r, getClientIp as t };
98
+ //# sourceMappingURL=utils-DK9HXCUV.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils-DK9HXCUV.mjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["/**\n * Utility functions for @kya-os/checkpoint-nextjs\n */\n\nimport type { NextRequest } from 'next/server.js';\nimport {\n resolveObservedClientAddress,\n type ClientIpTrustPolicy,\n} from '@kya-os/checkpoint-shared/client-ip';\n\n/**\n * Extract client IP address from a NextRequest.\n * In Next.js 15+, the `ip` property was removed from NextRequest.\n * Forwarded values require an authenticated deployment boundary. NextRequest\n * exposes no socket peer, so arbitrary proxy profiles remain unavailable.\n *\n * @param request - The NextRequest object\n * @returns The client IP address or undefined if not available\n */\nexport function getClientIp(\n request: NextRequest,\n policy: ClientIpTrustPolicy = { platform: 'direct' }\n): string | undefined {\n const frameworkAddress = (request as unknown as { ip?: string }).ip;\n const onVercel = typeof process !== 'undefined' && process.env?.VERCEL === '1';\n const effectivePolicy: ClientIpTrustPolicy =\n policy.platform === 'vercel' && !onVercel ? { platform: 'direct' } : policy;\n const resolution = resolveObservedClientAddress({\n headers: request.headers,\n frameworkAddress,\n vercelRuntime: onVercel,\n policy: effectivePolicy,\n });\n return resolution.trusted ? resolution.ip : undefined;\n}\n\n/**\n * Safely extract the hostname from a URL string.\n * Returns a friendly fallback when parsing fails so UX copy doesn't leak\n * \"undefined\" or similar to end users.\n */\nexport function safeHostname(url: string): string {\n try {\n return new URL(url).hostname;\n } catch {\n return 'this site';\n }\n}\n\n/**\n * Set `KYA-Confidence` to the decision's confidence as a whole number from\n * 0 to 100, as the gateway and the .NET SDK (`F0`) send it. The confidence\n * is a float, so 99.99999999993561 goes out as \"100\". A decision without a\n * finite confidence leaves the header off rather than sending \"NaN\".\n */\nexport function setConfidenceHeader(headers: Headers, confidence: number): void {\n if (!Number.isFinite(confidence)) return;\n headers.set('KYA-Confidence', Math.round(confidence).toString());\n}\n\nconst DROPPED_HEADERS = [\n 'cookie',\n 'authorization',\n 'proxy-authorization',\n 'x-api-key',\n 'x-vercel-protection-bypass',\n 'cf-access-jwt-assertion',\n 'cf-access-client-secret',\n];\nconst CREDENTIAL_HEADER =\n /^(?!kya-|x-bot-token$)(?:.*-)?(?:authorization|auth|token|secret|password|api-?key|apikey|subscription-key|credential)s?(?:-.*)?$/;\nconst BEACON_COOKIE = '_as_beacon_session=';\nconst DELEGATION_BEARER = /^bearer\\s+[\\w-]+\\.([\\w-]+)\\.[\\w-]+$/i;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction hasDelegationType(type: unknown): boolean {\n return Array.isArray(type) && type.includes('DelegationCredential');\n}\n\nfunction isDelegationBearer(authorization: string | null): authorization is string {\n for (const candidate of (authorization ?? '').split(',')) {\n const match = DELEGATION_BEARER.exec(candidate.trim());\n if (!match) continue;\n\n // Match the engine's conservative routing: oversized compact bearers must\n // reach it so it can fail closed without decoding an untrusted payload.\n if (match[1].length > 16 * 1024) return true;\n\n let claims: unknown;\n try {\n claims = JSON.parse(atob(match[1].replace(/-/g, '+').replace(/_/g, '/')));\n } catch {\n continue;\n }\n if (!isRecord(claims)) continue;\n if (hasDelegationType(claims.type)) return true;\n const vc = claims.vc;\n if (!isRecord(vc)) continue;\n if (hasDelegationType(vc.type)) return true;\n const subject = vc.credentialSubject;\n if (isRecord(subject) && isRecord(subject.delegation)) return true;\n }\n return false;\n}\n\nexport function relayHeaders(input: Record<string, string>): Record<string, string> {\n const headers = new Headers(input);\n const relayed = Object.fromEntries(\n [...headers].filter(\n ([name]) => !DROPPED_HEADERS.includes(name) && !CREDENTIAL_HEADER.test(name)\n )\n );\n const beacon = (headers.get('cookie') ?? '')\n .split(';')\n .map((part) => part.trim())\n .filter((part) => part.startsWith(BEACON_COOKIE));\n if (beacon.length) relayed.cookie = beacon.join('; ');\n const authorization = headers.get('authorization');\n if (isDelegationBearer(authorization)) relayed.authorization = authorization;\n return relayed;\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,SAAgB,YACd,SACA,SAA8B,EAAE,UAAU,SAAS,GAC/B;CACpB,MAAM,mBAAoB,QAAuC;CACjE,MAAM,WAAW,OAAO,YAAY,eAAe,QAAQ,KAAK,WAAW;CAC3E,MAAM,kBACJ,OAAO,aAAa,YAAY,CAAC,WAAW,EAAE,UAAU,SAAS,IAAI;CACvE,MAAM,aAAa,6BAA6B;EAC9C,SAAS,QAAQ;EACjB;EACA,eAAe;EACf,QAAQ;CACV,CAAC;CACD,OAAO,WAAW,UAAU,WAAW,KAAK;AAC9C;;;;;;AAOA,SAAgB,aAAa,KAAqB;CAChD,IAAI;EACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CACtB,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;AAQA,SAAgB,oBAAoB,SAAkB,YAA0B;CAC9E,IAAI,CAAC,OAAO,SAAS,UAAU,GAAG;CAClC,QAAQ,IAAI,kBAAkB,KAAK,MAAM,UAAU,CAAC,CAAC,SAAS,CAAC;AACjE;AAEA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,oBACJ;AACF,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAE1B,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,kBAAkB,MAAwB;CACjD,OAAO,MAAM,QAAQ,IAAI,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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kya-os/checkpoint-nextjs",
3
- "version": "1.14.0",
3
+ "version": "1.15.0",
4
4
  "description": "Checkpoint Next.js middleware: AI agent detection and verification through kya-os-engine",
5
5
  "keywords": [
6
6
  "nextjs",
@@ -103,8 +103,8 @@
103
103
  "sideEffects": false,
104
104
  "dependencies": {
105
105
  "@vercel/functions": "^3.9.3",
106
- "@kya-os/checkpoint-shared": "^1.11.0",
107
- "@kya-os/checkpoint-wasm-runtime": "^1.16.0"
106
+ "@kya-os/checkpoint-shared": "^1.12.0",
107
+ "@kya-os/checkpoint-wasm-runtime": "^1.17.0"
108
108
  },
109
109
  "scripts": {
110
110
  "build": "tsdown",
@@ -1 +0,0 @@
1
- {"version":3,"file":"api-middleware-CAarHFKk.mjs","names":[],"sources":["../src/responses/agent-instruction.ts","../src/api-middleware.ts"],"sourcesContent":["/**\n * Agent Instruction Response Builder (Next.js)\n *\n * Tells an AI agent where to send its user to complete consent / connect,\n * via a machine-parseable Link header + JSON body.\n *\n * **Dual envelope.** By default this is a 401 instruction response. AI-agent fetchers (Claude-User\n * WebFetch, ChatGPT) collapse 4xx responses and never surface the body to\n * the LLM, so the instruction is invisible. When the caller is a\n * cooperative, self-identifying agent (selected upstream via\n * `serveBodyReadable200`), pass `{ bodyReadable200: true }` to serve the\n * SAME body at HTTP 200 with NO `WWW-Authenticate` (a 200 + WWW-Authenticate\n * is reinterpreted as 401 by some fetchers); the consent URL stays in the\n * body + the `KYA-Auth-Url`/`Link` hint headers. This also realigns\n * TS-instruct (was 401-only) with .NET-instruct (200).\n *\n * Envelope selection is a cooperative-UX bridge, NOT an access control —\n * the authoritative consent target is the body `user_action_required.url`;\n * the `KYA-Auth-Url`/`Link` headers are unsigned hints.\n *\n * This is the in-app counterpart to the Cloudflare Gateway's builder at\n * `apps/web/workers/gateway/src/responses/agent-instruction.ts`. The body\n * is kept in sync so LLM and MCP clients see identical behavior whether a\n * site is protected by the gateway or by the Next.js middleware.\n *\n * Implements RFC 8288 Link discovery. It deliberately emits no\n * `WWW-Authenticate`; only a registered policy Challenge may emit the canonical\n * Delegation authentication fields.\n *\n * @see ../../apps/web/workers/gateway/src/responses/agent-instruction.ts\n */\n\nimport { NextResponse, type NextRequest } from 'next/server.js';\nimport type { EnforcementDecision } from '../api-client';\nimport { safeHostname } from '../utils';\n\nconst MCP_I_DOCS_URL = 'https://kya.vouched.id/docs/enforce/kya-os-enforcement';\nconst DEFAULT_CONNECT_PATH = '/connect';\n\n/** Options controlling which envelope `buildAgentInstructionResponse` emits. */\nexport interface AgentInstructionResponseOptions {\n /**\n * When true, serve the body-readable HTTP 200 fetcher envelope (same\n * body, no `WWW-Authenticate`) instead of the 401. The caller\n * decides this via the shared `serveBodyReadable200` predicate when its\n * challenge-emission mode is `negotiated`. Defaults to false.\n */\n bodyReadable200?: boolean;\n}\n\n/**\n * Build an \"agent must connect\" response for the Next.js middleware.\n *\n * The caller is responsible for deciding *when* to call this (typically when\n * `decision.action === 'redirect'` or `'instruct'`) and *which envelope* via\n * `options.bodyReadable200`. This helper only owns the response shape.\n */\nexport function buildAgentInstructionResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n redirectUrl: string | undefined,\n options?: AgentInstructionResponseOptions\n): NextResponse {\n // Resolve the target to an absolute URL against the incoming request so the\n // Link header is dereferenceable by strict clients (some LLM fetchers refuse\n // relative URIs in Link).\n const resolved = resolveUrl(redirectUrl ?? DEFAULT_CONNECT_PATH, request.url);\n\n // Match gateway's \"connect page\" branch: attach ?agent= for client-specific\n // install cards on the landing page.\n const agentName = decision.agentName || decision.agentType || 'unknown';\n if (!resolved.searchParams.has('agent')) {\n resolved.searchParams.set('agent', agentName.toLowerCase());\n }\n\n const authUrl = resolved.toString();\n const hostname = safeHostname(request.url);\n\n const body = {\n // Markdown-formatted so clients that render markdown (Claude Desktop,\n // ChatGPT web) surface the URL as a clickable link. Tone mirrors the\n // gateway response so messaging stays consistent across platforms.\n message:\n `I can't access ${hostname} yet — this site checks AI assistants at the front door.\\n\\n` +\n `**To give me access, open this link:**\\n` +\n `[Connect securely to ${hostname}](${authUrl})\\n\\n` +\n `It only takes a moment and you won't need to do it again. ` +\n `Once you're done, ask me to try again and I'll connect through the verified channel automatically.`,\n\n user_action_required: {\n action: `Connect securely to ${hostname}`,\n url: authUrl,\n reason: `${hostname} checks AI assistants before they connect. Open the link to give your assistant a verified key.`,\n },\n\n mcp_i: {\n version: '1.0' as const,\n action: 'authenticate' as const,\n authorization_url: authUrl,\n flow: {\n type: 'oauth2_delegation' as const,\n steps: [\n '1. Direct your user to the authorization_url',\n '2. User reviews requested scopes and grants consent',\n '3. Receive delegation credential (JWT)',\n '4. Include credential in KYA-Delegation header',\n '5. Retry this request with the proof',\n ],\n },\n retry_instructions: {\n header: 'KYA-Delegation' as const,\n format: 'JWT delegation credential from authorization flow',\n },\n documentation: MCP_I_DOCS_URL,\n },\n\n error: 'mcp_authentication_required',\n code: 'AGENT_REQUIRES_DELEGATION',\n\n detection: {\n agent_type: decision.agentType || 'ai_agent',\n agent_name: decision.agentName || 'Unknown Agent',\n confidence: decision.confidence,\n },\n };\n\n // Dual envelope: 200 body-readable for cooperative fetchers, else 401.\n // The body is identical across both. INSTRUCT is not a registered policy\n // Delegation challenge, so it must not advertise a fabricated auth scheme.\n const bodyReadable200 = options?.bodyReadable200 ?? false;\n const response = NextResponse.json(body, { status: bodyReadable200 ? 200 : 401 });\n\n // RFC 8288 discovery pointer + KYA-* hints. Present on BOTH envelopes —\n // these are unsigned hints; the authoritative target is the body\n // `user_action_required.url`. `rel=\"kya-authorize\"` matches the CF gateway.\n response.headers.set(\n 'Link',\n `<${authUrl}>; rel=\"kya-authorize\", <${MCP_I_DOCS_URL}>; rel=\"help\"`\n );\n response.headers.set('KYA-Auth-Required', 'true');\n response.headers.set('KYA-Auth-Url', authUrl);\n response.headers.set('KYA-Action', 'instruct');\n response.headers.set('KYA-Detected-Agent', agentName);\n response.headers.set('KYA-Confidence', decision.confidence.toString());\n response.headers.set('Cache-Control', 'no-store');\n\n return response;\n}\n\n/**\n * Resolve a URL that may be absolute or a same-origin path.\n * Falls back to `/connect` on the request origin if parsing fails.\n */\nfunction resolveUrl(target: string, baseUrl: string): URL {\n try {\n return new URL(target, baseUrl);\n } catch {\n return new URL(DEFAULT_CONNECT_PATH, baseUrl);\n }\n}\n","/**\n * API-based Checkpoint Middleware for Next.js\n *\n * This middleware uses the Checkpoint API for detection and enforcement,\n * instead of running detection locally. This approach:\n *\n * 1. Works reliably in Edge Runtime (no WASM loading issues)\n * 2. Ensures consistent detection across all platforms\n * 3. Applies centralized policies from the dashboard\n * 4. Supports deny lists, thresholds, and path rules\n *\n * @example\n * ```typescript\n * // middleware.ts\n * import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';\n *\n * export default withCheckpointApi({\n * apiKey: process.env.CHECKPOINT_API_KEY!,\n * // Optional overrides:\n * onBlock: 'redirect', // 'block' | 'redirect' | 'challenge'\n * redirectUrl: '/blocked',\n * skipPaths: ['/api/health', '/_next/*'],\n * });\n *\n * export const config = {\n * matcher: ['/((?!_next/static|favicon.ico).*)'],\n * };\n * ```\n */\n\nimport { NextRequest, NextResponse } from 'next/server.js';\nimport { matchPath } from '@kya-os/checkpoint-shared/policy/enforcement';\nimport { requestPresentedCredential } from '@kya-os/checkpoint-shared/kya-http';\nimport {\n selectBodyReadable200,\n type ChallengeEnvelopeMode,\n} from '@kya-os/checkpoint-shared/host-adapter';\nimport type { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared/client-ip';\nimport type { EngineInfo } from '@kya-os/checkpoint-shared';\nimport {\n CheckpointApiClient,\n getCheckpointApiClient,\n type EnforcementDecision,\n type LogDetectionInput,\n} from './api-client';\nimport { buildAgentInstructionResponse } from './responses/agent-instruction';\nimport { failClosedResponse } from './adapt';\nimport { getClientIp, safeHostname } from './utils';\n// A genuine hard dependency, not an optional one, despite forcing every\n// consumer (even non-Vercel ones) to install it (bestbrian review,\n// checkpoint#4460). Two reasons a dynamic/optional-peer import, which this\n// file used briefly, does NOT work here (Bugbot review, checkpoint#4657):\n// 1. This middleware explicitly targets Edge Runtime (see the module doc\n// comment). A `webpackIgnore`d variable-name `import()` is invisible\n// to the bundler on purpose — but Edge Runtime has no filesystem/module\n// resolution at request time, only what the bundler actually included.\n// An intentionally-unbundled import can never resolve there; `waitUntil`\n// would silently never register, reintroducing the exact lost-detection\n// bug this wrapper exists to prevent.\n// 2. It's unnecessary: `waitUntil()`'s own implementation\n// (`getContext().waitUntil?.(promise)`, where `getContext()` returns\n// `{}` off Vercel) already no-ops safely everywhere it isn't backed by\n// a real Vercel request context — Node, Edge, tests, wherever. There is\n// no failure mode to guard against with a fallback; the only real cost\n// of the hard dependency is a few extra KB installed on non-Vercel\n// consumers, which is the correct trade against actually breaking\n// detection logging on Vercel.\nimport { waitUntil } from '@vercel/functions';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Middleware configuration\n */\nexport interface CheckpointApiMiddlewareConfig {\n /** Explicit deployment/proxy trust profile for client-IP resolution. */\n clientIpPolicy?: ClientIpTrustPolicy;\n /** API key (or use CHECKPOINT_API_KEY env var) */\n apiKey?: string;\n /**\n * Gateway base URL. Override for staging or self-hosted deployments.\n * With `useEdge: false` the default becomes `https://kya.vouched.id`.\n *\n * @default 'https://detect.checkpoint-gateway.ai'\n */\n apiUrl?: string;\n /**\n * Use edge detection for lower latency (~30-50ms vs ~150ms) and better coverage.\n * Edge detection can identify non-JS clients (curl, Python, Claude Code WebFetch)\n * that the pixel cannot detect since they don't execute JavaScript.\n * Set to false to use the Vercel API instead.\n * @default true\n */\n useEdge?: boolean;\n /**\n * Request timeout in milliseconds for the gateway call.\n *\n * @default 5000\n */\n timeout?: number;\n\n /**\n * Action to take when an agent should be blocked\n * - 'block': Return 403 response\n * - 'redirect': Redirect to redirectUrl\n * - 'challenge': Show a challenge page (future)\n * Default: uses policy from dashboard\n */\n onBlock?: 'block' | 'redirect' | 'challenge';\n\n /**\n * URL to redirect to when blocking (if onBlock is 'redirect')\n * Default: uses redirectUrl from dashboard policy\n */\n redirectUrl?: string;\n\n /**\n * How the middleware handles a `redirect` / `instruct` action.\n *\n * - `'instruct'` (default): return HTTP 401 with a KYA-OS Link header + JSON\n * body pointing the agent at the redirect URL. LLMs surface the URL as a\n * clickable link for the user. Matches the Cloudflare Gateway contract.\n * - `'http'`: legacy behavior — return HTTP 302 with `Location`. Most LLM\n * fetchers won't follow the redirect, so this is only useful when your\n * traffic is real browsers.\n *\n * @default 'instruct'\n */\n redirectMode?: 'instruct' | 'http';\n\n /**\n * Challenge-emission envelope mode (draft-kya-http-02 §8.1 fetcher-200).\n * `negotiated` serves a body-readable HTTP 200 instruct response to\n * cooperative agents (so fetchers that drop 4xx bodies can read it),\n * keeping the spec 401 for everyone else. Defaults to `negotiated` (#3530).\n * A cooperative-UX bridge, NOT an access control.\n *\n * @default 'negotiated'\n */\n delegationChallengeMode?: ChallengeEnvelopeMode;\n\n /**\n * Customize the blocked response's status, message, and extra headers.\n *\n * @default { status: 403, message: 'Access denied' }\n */\n blockedResponse?: {\n status?: number;\n message?: string;\n headers?: Record<string, string>;\n };\n\n /**\n * Paths to skip (in addition to dashboard policy)\n * Supports glob patterns: '/api/*', '/_next/*'\n */\n skipPaths?: string[];\n\n /**\n * Only enforce on these paths (overrides dashboard policy)\n */\n includePaths?: string[];\n\n /**\n * Callback when an agent is detected\n */\n onAgentDetected?: (request: NextRequest, decision: EnforcementDecision) => void | Promise<void>;\n\n /**\n * Callback to customize the blocked response\n */\n customBlockedResponse?: (\n request: NextRequest,\n decision: EnforcementDecision\n ) => NextResponse | Promise<NextResponse>;\n\n /**\n * Whether to fail open (allow) on API errors. Must be explicitly `true`;\n * the default is fail-closed (503 with `Retry-After`). A request that\n * presented a credential (bearer or KYA delegation headers) is answered 503\n * on an API error even when this is `true`.\n *\n * @default false\n */\n failOpen?: boolean;\n\n /**\n * Log detection decisions and errors to the console.\n *\n * @default false\n */\n debug?: boolean;\n telemetryBatchSize?: number;\n telemetryFlushIntervalMs?: number;\n}\n\n// ============================================================================\n// Path Matching\n// ============================================================================\n\n/**\n * Check if path should be skipped\n */\nfunction shouldSkipPath(path: string, skipPaths: string[]): boolean {\n return skipPaths.some((pattern) => matchPath(path, pattern));\n}\n\n/**\n * Check if path should be included (if includePaths is set)\n */\nfunction shouldIncludePath(path: string, includePaths?: string[]): boolean {\n if (!includePaths || includePaths.length === 0) return true;\n return includePaths.some((pattern) => matchPath(path, pattern));\n}\n\n// ============================================================================\n// Detection Report\n// ============================================================================\n\n/**\n * Package version, injected at build time by tsdown's `define` from\n * package.json (which the publish workflow stamps before it builds). Unbundled\n * source, as in the unit tests, has no such global, so every read is\n * `typeof`-guarded and the report then omits `sdk` rather than guess a version.\n */\ndeclare const __CHECKPOINT_PKG_VERSION__: string | undefined;\n\n/** The npm package this middleware ships in (package.json `name`, pinned by a unit test). */\nconst SDK_NAME = '@kya-os/checkpoint-nextjs';\n\n/**\n * The gateway ran the engine, so its engine info is reported under the\n * remote-engine name `checkpoint-remote`. Forwarding the gateway's own\n * `checkpoint-worker-wasm` would make this install read as a DNS Gateway.\n */\nfunction remoteEngineInfo(engine: EngineInfo): EngineInfo {\n return {\n name: 'checkpoint-remote',\n version: engine.version,\n rulesetHash: engine.rulesetHash,\n rulesetVersion: engine.rulesetVersion,\n ...(engine.buildSha ? { buildSha: engine.buildSha } : {}),\n };\n}\n\n/** The SDK's self-identification, or undefined when the build injected no version. */\nfunction sdkSelfIdentification(): LogDetectionInput['sdk'] {\n if (typeof __CHECKPOINT_PKG_VERSION__ === 'undefined') return undefined;\n const runtime =\n typeof process !== 'undefined' && process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node';\n return { name: SDK_NAME, version: __CHECKPOINT_PKG_VERSION__, runtime };\n}\n\n// ============================================================================\n// Response Builders\n// ============================================================================\n\n/**\n * Build blocked response.\n *\n * When the policy attaches a `redirectUrl` (e.g. the dashboard's hosted\n * /connect page), we still respect the `block` action but surface the URL to\n * LLM clients so the user can recover: `Link` header + `user_action_required`\n * in the JSON body. Status stays 403 — this is not an auth challenge, it's a\n * blocked request with a recovery hint.\n */\nfunction buildBlockedResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n config: CheckpointApiMiddlewareConfig\n): NextResponse {\n const status = config.blockedResponse?.status ?? 403;\n const message = config.blockedResponse?.message ?? decision.message ?? 'Access denied';\n\n const recoveryUrl = resolveRecoveryUrl(request, config.redirectUrl || decision.redirectUrl);\n\n const body: Record<string, unknown> = {\n error: message,\n code: 'AGENT_BLOCKED',\n reason: decision.reason,\n agentType: decision.agentType,\n };\n\n if (recoveryUrl) {\n const hostname = safeHostname(request.url);\n body.user_action_required = {\n action: `Connect securely to ${hostname}`,\n url: recoveryUrl,\n reason: `${hostname} blocks unverified AI assistants. Open the link to give your assistant a verified key and try again.`,\n };\n body.message =\n `I can't access ${hostname} — this site blocks unverified AI assistants.\\n\\n` +\n `**To give me access, open this link:**\\n` +\n `[Connect securely to ${hostname}](${recoveryUrl})\\n\\n` +\n `Once you're done, ask me to try again.`;\n }\n\n const response = NextResponse.json(body, { status });\n\n // Add custom headers\n if (config.blockedResponse?.headers) {\n for (const [key, value] of Object.entries(config.blockedResponse.headers)) {\n response.headers.set(key, value);\n }\n }\n\n if (recoveryUrl) {\n // RFC 8288 discovery pointer — same rel value the 401 instruct path uses\n // so LLM clients can parse it uniformly.\n response.headers.set('Link', `<${recoveryUrl}>; rel=\"kya-authorize\"`);\n response.headers.set('KYA-Auth-Url', recoveryUrl);\n }\n\n // Add Checkpoint headers\n response.headers.set('KYA-Action', decision.action);\n response.headers.set('KYA-Reason', decision.reason);\n\n return response;\n}\n\n/**\n * A policy `requestsPerMinute` throttle arrives as `block` with reason\n * `rate_limited`. It is a 429 with a retry hint, not an access denial: no\n * \"unverified assistant\" recovery copy and no redirect.\n */\nfunction buildRateLimitedResponse(\n decision: EnforcementDecision,\n config: CheckpointApiMiddlewareConfig\n): NextResponse {\n const retryAfter = decision.metadata?.rateLimit?.retryAfterSeconds;\n const response = NextResponse.json(\n {\n error: decision.message ?? 'Rate limit exceeded',\n code: 'RATE_LIMITED',\n reason: decision.reason,\n agentType: decision.agentType,\n ...(retryAfter !== undefined ? { retryAfterSeconds: retryAfter } : {}),\n },\n { status: 429 }\n );\n for (const [key, value] of Object.entries(config.blockedResponse?.headers ?? {})) {\n response.headers.set(key, value);\n }\n if (retryAfter !== undefined) response.headers.set('Retry-After', String(retryAfter));\n response.headers.set('KYA-Action', decision.action);\n response.headers.set('KYA-Reason', decision.reason);\n return response;\n}\n\nfunction resolveRecoveryUrl(request: NextRequest, target: string | undefined): string | undefined {\n if (!target) return undefined;\n try {\n return new URL(target, request.url).toString();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Build redirect response\n */\nfunction buildRedirectResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n config: CheckpointApiMiddlewareConfig\n): NextResponse {\n const redirectUrl = config.redirectUrl || decision.redirectUrl || '/blocked';\n const url = new URL(redirectUrl, request.url);\n\n // Add query params with detection info\n url.searchParams.set('reason', decision.reason);\n if (decision.agentType) {\n url.searchParams.set('agent', decision.agentType);\n }\n\n return NextResponse.redirect(url);\n}\n\n// ============================================================================\n// Middleware Factory\n// ============================================================================\n\n/**\n * Create Checkpoint middleware with API-based detection\n *\n * @example\n * ```typescript\n * // middleware.ts\n * import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';\n *\n * export default withCheckpointApi({\n * onBlock: 'block',\n * skipPaths: ['/api/health'],\n * });\n * ```\n */\nexport function withCheckpointApi(config: CheckpointApiMiddlewareConfig = {}) {\n // Initialize client (will use CHECKPOINT_API_KEY env var if not provided)\n let client: CheckpointApiClient | null = null;\n\n const getClient = () => {\n if (!client) {\n client = getCheckpointApiClient({\n apiKey: config.apiKey,\n baseUrl: config.apiUrl,\n useEdge: config.useEdge,\n timeout: config.timeout,\n debug: config.debug,\n telemetryBatchSize: config.telemetryBatchSize,\n telemetryFlushIntervalMs: config.telemetryFlushIntervalMs,\n });\n }\n return client;\n };\n\n // Default skip paths (static assets, etc.).\n //\n // `**` (globstar) is intentional for the `_next/*` patterns: Next.js\n // ships static assets at deeply nested paths like\n // `/_next/static/chunks/main.js` and `/_next/image/?url=…` query-\n // suffixed. The shared `matchPath` treats single `*` as `[^/]*`\n // (segment-local) — pre-rename this code relied on the local\n // matchPath's buggy `*` → `.*` (cross-boundary) coincidence; without\n // `**` here every static-asset request would now hit the enforcement\n // API. Picked up by cursor-bot on PR #2568 after the matchPath swap.\n const defaultSkipPaths = [\n '/_next/static/**',\n '/_next/image/**',\n '/favicon.ico',\n '/robots.txt',\n '/sitemap.xml',\n ];\n\n const skipPaths = [...defaultSkipPaths, ...(config.skipPaths || [])];\n\n // Fails open only on the explicit opt-in AND when the request presented no\n // credential; a presented credential that could not be verified is never\n // waved through.\n const faultResponse = (request: NextRequest): NextResponse =>\n config.failOpen === true && !requestPresentedCredential(request.headers)\n ? failOpenResponse()\n : failClosedResponse();\n\n return async function middleware(request: NextRequest): Promise<NextResponse> {\n const path = request.nextUrl.pathname;\n const startTime = Date.now();\n\n // Check skip paths\n if (shouldSkipPath(path, skipPaths)) {\n return NextResponse.next();\n }\n\n // Check include paths\n if (!shouldIncludePath(path, config.includePaths)) {\n return NextResponse.next();\n }\n\n try {\n const client = getClient();\n\n // Extract request context for potential logging\n const userAgent = request.headers.get('user-agent') || undefined;\n const ipAddress = getClientIp(request, config.clientIpPolicy);\n\n // Call enforce API\n const result = await client.enforce({\n headers: Object.fromEntries(request.headers.entries()),\n userAgent,\n ipAddress,\n path,\n url: request.url,\n method: request.method,\n requestId: request.headers.get('x-request-id') || undefined,\n options: {\n // Always include detection results for logging (needed when using edge)\n includeDetectionResult: true,\n },\n });\n\n // Handle API error\n if (!result.success || !result.data) {\n if (config.debug) {\n console.warn('[Checkpoint] API error:', result.error);\n }\n\n return faultResponse(request);\n }\n\n const decision = result.data.decision;\n\n // Log if debug enabled\n if (config.debug) {\n console.log('[Checkpoint] Decision:', {\n path,\n action: decision.action,\n isAgent: decision.isAgent,\n confidence: decision.confidence,\n agentName: decision.agentName,\n detectionMethod: result.data.detection?.detectionMethod || 'not-included',\n processingTimeMs: Date.now() - startTime,\n });\n }\n\n // Fire-and-forget logging - ONLY when using Gateway Worker (edge detection)\n // When useEdge: false, the /api/v1/enforce endpoint already logs to the database\n // This prevents double-logging while ensuring Gateway detections are persisted\n //\n // Wrapped in waitUntil(): on Vercel's Edge/Fluid Compute runtimes, the\n // platform is free to abort any work still pending once this function\n // returns its Response — an un-awaited fetch() with no lifecycle\n // extension gets killed mid-flight (observed live as `[Checkpoint] Log\n // detection failed: DOMException [AbortError]: This operation was\n // aborted`, 100% reproduction rate on a real deployment: every\n // detection classified correctly but never persisted). waitUntil()\n // tells the platform to keep the function alive until this promise\n // settles, without making the response wait for it. Off Vercel (or\n // wherever no request context backs it) waitUntil() itself no-ops\n // safely — see the import's doc comment — so this needs no fallback.\n if (client.isUsingEdge() && result.data.detection) {\n waitUntil(\n client\n .logDetection({\n detection: result.data.detection,\n context: { userAgent, ipAddress, path, url: request.url, method: request.method },\n // This is the Next.js middleware regardless of whether it used\n // edge detection or the Vercel API. `logDetection`'s own\n // default ('gateway') describes the transport, not the\n // installation, so this must say 'middleware' explicitly.\n source: 'middleware',\n // The decision this middleware acts on below, and the engine\n // that made it, so the dashboard shows a verdict and a method\n // instead of an unknown runtime with no decision.\n enforcement: { action: decision.action },\n engine: result.data.engine ? remoteEngineInfo(result.data.engine) : undefined,\n sdk: sdkSelfIdentification(),\n })\n .catch((err) => {\n if (config.debug) {\n console.error('[Checkpoint] Log detection failed:', err);\n }\n })\n );\n }\n\n // Observability callbacks must not influence enforcement. A throwing\n // callback used to reach the outer catch before block/redirect actions\n // ran, which fails open only when the explicit opt-in is set and no\n // credential was presented, allowing requests the API had already denied.\n if (decision.isAgent && config.onAgentDetected) {\n try {\n await config.onAgentDetected(request, decision);\n } catch (error) {\n if (config.debug) {\n console.error('[Checkpoint] onAgentDetected callback failed:', error);\n }\n }\n }\n\n // Handle enforcement action\n const redirectMode = config.redirectMode ?? 'instruct';\n switch (decision.action) {\n case 'block': {\n // Use custom response if provided. `return await` (not bare\n // `return`) keeps a rejected promise inside this try block so\n // the catch path below can absorb it — without the\n // await, the rejection escapes synchronously and the caller\n // sees an unhandled 500 instead of the intended fault response\n // (fail-open only with the explicit opt-in and no credential\n // presented, else 503). Same shape as the\n // `await config.onAgentDetected(...)` call earlier in this handler.\n if (config.customBlockedResponse) {\n return await config.customBlockedResponse(request, decision);\n }\n\n if (decision.reason === 'rate_limited') {\n return buildRateLimitedResponse(decision, config);\n }\n\n // Check if config overrides to redirect\n if (config.onBlock === 'redirect') {\n return buildRedirectResponse(request, decision, config);\n }\n\n return buildBlockedResponse(request, decision, config);\n }\n\n case 'redirect':\n case 'instruct': {\n // Default behavior: 401 + Link header + JSON body so LLM clients can\n // surface the /connect URL as a link for the user to open. This\n // matches `buildAgentInstructionResponse` in the CF gateway, so\n // hostname-routed and self-hosted deployments behave the same.\n //\n // Legacy 302 behavior is available under `redirectMode: 'http'` for\n // customers who want a plain browser redirect.\n if (redirectMode === 'http' && decision.action === 'redirect') {\n return buildRedirectResponse(request, decision, config);\n }\n\n const targetUrl = config.redirectUrl || decision.redirectUrl;\n // Dual envelope: serve the body-readable 200 to cooperative agents\n // under negotiated mode; else the spec 401. Feed the shared selector\n // the API's detection class + isAgent from the SAME detection payload\n // the engine PEPs (express / nextjs middleware) use — so negotiated\n // mode can't disagree across PEPs, and the class/isAgent pair the\n // predicate gates on stays internally consistent (never the\n // `decision.isAgent` proxy, which could diverge from this payload).\n const bodyReadable200 = selectBodyReadable200(\n config.delegationChallengeMode ?? 'negotiated',\n request.headers,\n result.data.detection?.detectionClass,\n result.data.detection?.isAgent ?? false\n );\n return buildAgentInstructionResponse(request, decision, targetUrl, {\n bodyReadable200,\n });\n }\n\n case 'challenge': {\n return buildRedirectResponse(request, decision, config);\n }\n\n case 'log':\n case 'allow':\n default: {\n // Allow the request to proceed\n const response = NextResponse.next();\n\n // Add detection headers for downstream use\n if (decision.isAgent) {\n response.headers.set('KYA-Detected', 'true');\n response.headers.set('KYA-Confidence', decision.confidence.toString());\n if (decision.agentName) {\n response.headers.set('KYA-Agent', decision.agentName);\n }\n }\n\n return response;\n }\n }\n } catch (error) {\n // Unexpected error\n if (config.debug) {\n console.error('[Checkpoint] Middleware error:', error);\n }\n\n return faultResponse(request);\n }\n };\n}\n\nfunction failOpenResponse(): NextResponse {\n const response = NextResponse.next();\n response.headers.set('KYA-Failopen', 'true');\n return response;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,iBAAiB;AACvB,MAAM,uBAAuB;;;;;;;;AAoB7B,SAAgB,8BACd,SACA,UACA,aACA,SACc;CAId,MAAM,WAAW,WAAW,eAAe,sBAAsB,QAAQ,GAAG;CAI5E,MAAM,YAAY,SAAS,aAAa,SAAS,aAAa;CAC9D,IAAI,CAAC,SAAS,aAAa,IAAI,OAAO,GACpC,SAAS,aAAa,IAAI,SAAS,UAAU,YAAY,CAAC;CAG5D,MAAM,UAAU,SAAS,SAAS;CAClC,MAAM,WAAW,aAAa,QAAQ,GAAG;CAEzC,MAAM,OAAO;EAIX,SACE,kBAAkB,SAAS,2HAEH,SAAS,IAAI,QAAQ;EAI/C,sBAAsB;GACpB,QAAQ,uBAAuB;GAC/B,KAAK;GACL,QAAQ,GAAG,SAAS;EACtB;EAEA,OAAO;GACL,SAAS;GACT,QAAQ;GACR,mBAAmB;GACnB,MAAM;IACJ,MAAM;IACN,OAAO;KACL;KACA;KACA;KACA;KACA;IACF;GACF;GACA,oBAAoB;IAClB,QAAQ;IACR,QAAQ;GACV;GACA,eAAe;EACjB;EAEA,OAAO;EACP,MAAM;EAEN,WAAW;GACT,YAAY,SAAS,aAAa;GAClC,YAAY,SAAS,aAAa;GAClC,YAAY,SAAS;EACvB;CACF;CAKA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AAEA,SAAS,mBAAiC;CACxC,MAAM,WAAW,aAAa,KAAK;CACnC,SAAS,QAAQ,IAAI,gBAAgB,MAAM;CAC3C,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"middleware-core-BLCAErYE.d.ts","names":[],"sources":["../src/middleware-core.ts"],"mappings":";;;;;;;;;;cA4Da"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"middleware-core-D88q8dIt.d.mts","names":[],"sources":["../src/middleware-core.ts"],"mappings":";;;;;;;;;;cA4Da"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"posture-outcome-DQ4fdMfq.mjs","names":[],"sources":["../src/posture-outcome.ts"],"sourcesContent":["import {\n postureOutcomeFromRequest,\n postureRequestFromHeaders,\n validateBrowserPostureConfig,\n type BrowserPostureConfig,\n} from '@kya-os/checkpoint-shared/browser-posture';\nimport {\n postureOutcomeView,\n type PostureHandlerView,\n} from '@kya-os/checkpoint-wasm-runtime/composed-policy';\n\nexport type CheckpointPostureOutcome = PostureHandlerView;\n\nexport interface CheckpointPostureOptions {\n browserPosture: BrowserPostureConfig;\n projectId: string;\n}\n\nfunction hasGet(input: Request | Headers | { headers: Headers }): input is Headers {\n return typeof (input as Headers).get === 'function';\n}\n\nconst validatedProjects = new WeakMap<BrowserPostureConfig, string>();\n\nexport async function getCheckpointPostureOutcome(\n input: Request | Headers | { headers: Headers },\n options: CheckpointPostureOptions\n): Promise<CheckpointPostureOutcome> {\n if (!options.browserPosture) {\n throw new Error('getCheckpointPostureOutcome requires the browserPosture config');\n }\n if (validatedProjects.get(options.browserPosture) !== options.projectId) {\n validateBrowserPostureConfig(options.browserPosture, options.projectId);\n validatedProjects.set(options.browserPosture, options.projectId);\n }\n const headers = hasGet(input) ? input : input.headers;\n return postureOutcomeView(\n await postureOutcomeFromRequest(\n postureRequestFromHeaders((name) => headers.get(name)),\n options.browserPosture,\n options.projectId\n )\n );\n}\n"],"mappings":";;;;AAkBA,SAAS,OAAO,OAAmE;CACjF,OAAO,OAAQ,MAAkB,QAAQ;AAC3C;AAEA,MAAM,oCAAoB,IAAI,QAAsC;AAEpE,eAAsB,4BACpB,OACA,SACmC;CACnC,IAAI,CAAC,QAAQ,gBACX,MAAM,IAAI,MAAM,gEAAgE;CAElF,IAAI,kBAAkB,IAAI,QAAQ,cAAc,MAAM,QAAQ,WAAW;EACvE,6BAA6B,QAAQ,gBAAgB,QAAQ,SAAS;EACtE,kBAAkB,IAAI,QAAQ,gBAAgB,QAAQ,SAAS;CACjE;CACA,MAAM,UAAU,OAAO,KAAK,IAAI,QAAQ,MAAM;CAC9C,OAAO,mBACL,MAAM,0BACJ,2BAA2B,SAAS,QAAQ,IAAI,IAAI,CAAC,GACrD,QAAQ,gBACR,QAAQ,SACV,CACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils-Cnwg0VrY.mjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["/**\n * Utility functions for @kya-os/checkpoint-nextjs\n */\n\nimport type { NextRequest } from 'next/server.js';\nimport {\n resolveObservedClientAddress,\n type ClientIpTrustPolicy,\n} from '@kya-os/checkpoint-shared/client-ip';\n\n/**\n * Extract client IP address from a NextRequest.\n * In Next.js 15+, the `ip` property was removed from NextRequest.\n * Forwarded values require an authenticated deployment boundary. NextRequest\n * exposes no socket peer, so arbitrary proxy profiles remain unavailable.\n *\n * @param request - The NextRequest object\n * @returns The client IP address or undefined if not available\n */\nexport function getClientIp(\n request: NextRequest,\n policy: ClientIpTrustPolicy = { platform: 'direct' }\n): string | undefined {\n const frameworkAddress = (request as unknown as { ip?: string }).ip;\n const onVercel = typeof process !== 'undefined' && process.env?.VERCEL === '1';\n const effectivePolicy: ClientIpTrustPolicy =\n policy.platform === 'vercel' && !onVercel ? { platform: 'direct' } : policy;\n const resolution = resolveObservedClientAddress({\n headers: request.headers,\n frameworkAddress,\n vercelRuntime: onVercel,\n policy: effectivePolicy,\n });\n return resolution.trusted ? resolution.ip : undefined;\n}\n\n/**\n * Safely extract the hostname from a URL string.\n * Returns a friendly fallback when parsing fails so UX copy doesn't leak\n * \"undefined\" or similar to end users.\n */\nexport function safeHostname(url: string): string {\n try {\n return new URL(url).hostname;\n } catch {\n return 'this site';\n }\n}\n\nconst DROPPED_HEADERS = [\n 'cookie',\n 'authorization',\n 'proxy-authorization',\n 'x-api-key',\n 'x-vercel-protection-bypass',\n 'cf-access-jwt-assertion',\n 'cf-access-client-secret',\n];\nconst CREDENTIAL_HEADER =\n /^(?!kya-|x-bot-token$)(?:.*-)?(?:authorization|auth|token|secret|password|api-?key|apikey|subscription-key|credential)s?(?:-.*)?$/;\nconst BEACON_COOKIE = '_as_beacon_session=';\nconst DELEGATION_BEARER = /^bearer\\s+[\\w-]+\\.([\\w-]+)\\.[\\w-]+$/i;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction hasDelegationType(type: unknown): boolean {\n return Array.isArray(type) && type.includes('DelegationCredential');\n}\n\nfunction isDelegationBearer(authorization: string | null): authorization is string {\n for (const candidate of (authorization ?? '').split(',')) {\n const match = DELEGATION_BEARER.exec(candidate.trim());\n if (!match) continue;\n\n // Match the engine's conservative routing: oversized compact bearers must\n // reach it so it can fail closed without decoding an untrusted payload.\n if (match[1].length > 16 * 1024) return true;\n\n let claims: unknown;\n try {\n claims = JSON.parse(atob(match[1].replace(/-/g, '+').replace(/_/g, '/')));\n } catch {\n continue;\n }\n if (!isRecord(claims)) continue;\n if (hasDelegationType(claims.type)) return true;\n const vc = claims.vc;\n if (!isRecord(vc)) continue;\n if (hasDelegationType(vc.type)) return true;\n const subject = vc.credentialSubject;\n if (isRecord(subject) && isRecord(subject.delegation)) return true;\n }\n return false;\n}\n\nexport function relayHeaders(input: Record<string, string>): Record<string, string> {\n const headers = new Headers(input);\n const relayed = Object.fromEntries(\n [...headers].filter(\n ([name]) => !DROPPED_HEADERS.includes(name) && !CREDENTIAL_HEADER.test(name)\n )\n );\n const beacon = (headers.get('cookie') ?? '')\n .split(';')\n .map((part) => part.trim())\n .filter((part) => part.startsWith(BEACON_COOKIE));\n if (beacon.length) relayed.cookie = beacon.join('; ');\n const authorization = headers.get('authorization');\n if (isDelegationBearer(authorization)) relayed.authorization = authorization;\n return relayed;\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,SAAgB,YACd,SACA,SAA8B,EAAE,UAAU,SAAS,GAC/B;CACpB,MAAM,mBAAoB,QAAuC;CACjE,MAAM,WAAW,OAAO,YAAY,eAAe,QAAQ,KAAK,WAAW;CAC3E,MAAM,kBACJ,OAAO,aAAa,YAAY,CAAC,WAAW,EAAE,UAAU,SAAS,IAAI;CACvE,MAAM,aAAa,6BAA6B;EAC9C,SAAS,QAAQ;EACjB;EACA,eAAe;EACf,QAAQ;CACV,CAAC;CACD,OAAO,WAAW,UAAU,WAAW,KAAK;AAC9C;;;;;;AAOA,SAAgB,aAAa,KAAqB;CAChD,IAAI;EACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CACtB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,oBACJ;AACF,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAE1B,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,kBAAkB,MAAwB;CACjD,OAAO,MAAM,QAAQ,IAAI,KAAK,KAAK,SAAS,sBAAsB;AACpE;AAEA,SAAS,mBAAmB,eAAuD;CACjF,KAAK,MAAM,cAAc,iBAAiB,GAAE,CAAE,MAAM,GAAG,GAAG;EACxD,MAAM,QAAQ,kBAAkB,KAAK,UAAU,KAAK,CAAC;EACrD,IAAI,CAAC,OAAO;EAIZ,IAAI,MAAM,EAAE,CAAC,SAAS,OAAW,OAAO;EAExC,IAAI;EACJ,IAAI;GACF,SAAS,KAAK,MAAM,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