@kya-os/checkpoint-nextjs 1.0.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 (122) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/EDGE_RUNTIME_WASM_SETUP.md +348 -0
  3. package/README.md +414 -0
  4. package/bin/setup-edge-wasm.js +497 -0
  5. package/dist/.tsbuildinfo +1 -0
  6. package/dist/adapt.d.mts +39 -0
  7. package/dist/adapt.d.ts +39 -0
  8. package/dist/adapt.js +58 -0
  9. package/dist/adapt.js.map +1 -0
  10. package/dist/adapt.mjs +56 -0
  11. package/dist/adapt.mjs.map +1 -0
  12. package/dist/api-client.d.mts +204 -0
  13. package/dist/api-client.d.ts +204 -0
  14. package/dist/api-client.js +206 -0
  15. package/dist/api-client.js.map +1 -0
  16. package/dist/api-client.mjs +199 -0
  17. package/dist/api-client.mjs.map +1 -0
  18. package/dist/api-middleware.d.mts +156 -0
  19. package/dist/api-middleware.d.ts +156 -0
  20. package/dist/api-middleware.js +510 -0
  21. package/dist/api-middleware.js.map +1 -0
  22. package/dist/api-middleware.mjs +505 -0
  23. package/dist/api-middleware.mjs.map +1 -0
  24. package/dist/create-middleware.d.mts +17 -0
  25. package/dist/create-middleware.d.ts +17 -0
  26. package/dist/create-middleware.js +38 -0
  27. package/dist/create-middleware.js.map +1 -0
  28. package/dist/create-middleware.mjs +35 -0
  29. package/dist/create-middleware.mjs.map +1 -0
  30. package/dist/edge/index.d.mts +110 -0
  31. package/dist/edge/index.d.ts +110 -0
  32. package/dist/edge/index.js +277 -0
  33. package/dist/edge/index.js.map +1 -0
  34. package/dist/edge/index.mjs +275 -0
  35. package/dist/edge/index.mjs.map +1 -0
  36. package/dist/edge-runtime-loader.d.mts +50 -0
  37. package/dist/edge-runtime-loader.d.ts +50 -0
  38. package/dist/edge-runtime-loader.js +204 -0
  39. package/dist/edge-runtime-loader.js.map +1 -0
  40. package/dist/edge-runtime-loader.mjs +201 -0
  41. package/dist/edge-runtime-loader.mjs.map +1 -0
  42. package/dist/edge-wasm-middleware.d.mts +68 -0
  43. package/dist/edge-wasm-middleware.d.ts +68 -0
  44. package/dist/edge-wasm-middleware.js +318 -0
  45. package/dist/edge-wasm-middleware.js.map +1 -0
  46. package/dist/edge-wasm-middleware.mjs +315 -0
  47. package/dist/edge-wasm-middleware.mjs.map +1 -0
  48. package/dist/index.d.mts +25 -0
  49. package/dist/index.d.ts +25 -0
  50. package/dist/index.js +1019 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/index.mjs +979 -0
  53. package/dist/index.mjs.map +1 -0
  54. package/dist/middleware-edge.d.mts +46 -0
  55. package/dist/middleware-edge.d.ts +46 -0
  56. package/dist/middleware-edge.js +134 -0
  57. package/dist/middleware-edge.js.map +1 -0
  58. package/dist/middleware-edge.mjs +129 -0
  59. package/dist/middleware-edge.mjs.map +1 -0
  60. package/dist/middleware-node.d.mts +89 -0
  61. package/dist/middleware-node.d.ts +89 -0
  62. package/dist/middleware-node.js +127 -0
  63. package/dist/middleware-node.js.map +1 -0
  64. package/dist/middleware-node.mjs +124 -0
  65. package/dist/middleware-node.mjs.map +1 -0
  66. package/dist/middleware.d.mts +36 -0
  67. package/dist/middleware.d.ts +36 -0
  68. package/dist/middleware.js +15 -0
  69. package/dist/middleware.js.map +1 -0
  70. package/dist/middleware.mjs +12 -0
  71. package/dist/middleware.mjs.map +1 -0
  72. package/dist/nodejs-wasm-loader.d.mts +25 -0
  73. package/dist/nodejs-wasm-loader.d.ts +25 -0
  74. package/dist/nodejs-wasm-loader.js +95 -0
  75. package/dist/nodejs-wasm-loader.js.map +1 -0
  76. package/dist/nodejs-wasm-loader.mjs +85 -0
  77. package/dist/nodejs-wasm-loader.mjs.map +1 -0
  78. package/dist/policy.d.mts +162 -0
  79. package/dist/policy.d.ts +162 -0
  80. package/dist/policy.js +189 -0
  81. package/dist/policy.js.map +1 -0
  82. package/dist/policy.mjs +165 -0
  83. package/dist/policy.mjs.map +1 -0
  84. package/dist/session-tracker.d.mts +55 -0
  85. package/dist/session-tracker.d.ts +55 -0
  86. package/dist/session-tracker.js +170 -0
  87. package/dist/session-tracker.js.map +1 -0
  88. package/dist/session-tracker.mjs +167 -0
  89. package/dist/session-tracker.mjs.map +1 -0
  90. package/dist/signature-verifier.d.mts +33 -0
  91. package/dist/signature-verifier.d.ts +33 -0
  92. package/dist/signature-verifier.js +386 -0
  93. package/dist/signature-verifier.js.map +1 -0
  94. package/dist/signature-verifier.mjs +362 -0
  95. package/dist/signature-verifier.mjs.map +1 -0
  96. package/dist/translate.d.mts +33 -0
  97. package/dist/translate.d.ts +33 -0
  98. package/dist/translate.js +38 -0
  99. package/dist/translate.js.map +1 -0
  100. package/dist/translate.mjs +36 -0
  101. package/dist/translate.mjs.map +1 -0
  102. package/dist/types-C-xCUNTr.d.mts +105 -0
  103. package/dist/types-C-xCUNTr.d.ts +105 -0
  104. package/dist/wasm-middleware.d.mts +63 -0
  105. package/dist/wasm-middleware.d.ts +63 -0
  106. package/dist/wasm-middleware.js +98 -0
  107. package/dist/wasm-middleware.js.map +1 -0
  108. package/dist/wasm-middleware.mjs +95 -0
  109. package/dist/wasm-middleware.mjs.map +1 -0
  110. package/dist/wasm-setup.d.mts +46 -0
  111. package/dist/wasm-setup.d.ts +46 -0
  112. package/dist/wasm-setup.js +176 -0
  113. package/dist/wasm-setup.js.map +1 -0
  114. package/dist/wasm-setup.mjs +167 -0
  115. package/dist/wasm-setup.mjs.map +1 -0
  116. package/package.json +156 -0
  117. package/templates/middleware-wasm-100.ts +153 -0
  118. package/wasm/agentshield_wasm.d.ts +479 -0
  119. package/wasm/agentshield_wasm.js +1536 -0
  120. package/wasm/agentshield_wasm_bg.wasm +0 -0
  121. package/wasm/package.json +30 -0
  122. package/wasm.d.ts +21 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapt.ts","../src/translate.ts","../src/middleware-node.ts","../src/middleware.ts","../src/create-middleware.ts","../src/api-client.ts","../src/utils.ts","../src/responses/agent-instruction.ts","../src/api-middleware.ts","../src/session-tracker.ts","../src/policy.ts","../src/index.ts"],"names":["createAgentShieldMiddleware","agentShieldMiddleware","NextResponse","client","buildBlockedResponse","buildRedirectResponse","matchPath"],"mappings":";;;;;;;AA4CO,SAAS,mBAAA,CAAoB,UAA4B,GAAA,EAAgC;AAC9F,EAAA,MAAM,iBAAA,GAAoB,WAAA,CAAY,GAAA,CAAI,OAAO,CAAA;AACjD,EAAA,MAAM,aAAA,GAAgB,oBAAoB,QAAQ,CAAA;AAClD,EAAA,MAAM,KAAA,GAAQ,qBAAA,CAAsB,QAAA,EAAU,iBAAiB,CAAA;AAE/D,EAAA,QAAQ,KAAA;AAAO,IACb,KAAK,cAAA,EAAgB;AAEnB,MAAA,MAAM,GAAA,GAAM,aAAa,IAAA,EAAK;AAC9B,MAAA,YAAA,CAAa,GAAA,EAAK,SAAS,OAAO,CAAA;AAClC,MAAA,gBAAA,CAAiB,KAAK,aAAa,CAAA;AACnC,MAAA,OAAO,GAAA;AAAA,IACT;AAAA,IAEA,KAAK,UAAA,EAAY;AAEf,MAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,QAAA,CAAS,QAAQ,QAAS,CAAA;AACjD,MAAA,MAAM,GAAA,GAAM,YAAA,CAAa,QAAA,CAAS,MAAM,CAAA;AACxC,MAAA,YAAA,CAAa,GAAA,EAAK,SAAS,OAAO,CAAA;AAClC,MAAA,gBAAA,CAAiB,KAAK,aAAa,CAAA;AACnC,MAAA,OAAO,GAAA;AAAA,IACT;AAAA,IAEA,KAAK,YAAA,EAAc;AAIjB,MAAA,MAAM,UAAA,GAAa,IAAI,GAAA,CAAI,YAAA,EAAc,IAAI,GAAG,CAAA;AAChD,MAAA,MAAM,MAAM,YAAA,CAAa,OAAA,CAAQ,YAAY,EAAE,MAAA,EAAQ,KAAK,CAAA;AAC5D,MAAA,YAAA,CAAa,GAAA,EAAK,SAAS,OAAO,CAAA;AAClC,MAAA,gBAAA,CAA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deredResponse` → `NextResponse` adapter.\n *\n * The host wrapper's *only* job on the outbound path: take the\n * transport-agnostic `RenderedResponse` Phase C's\n * `renderDecisionAsResponse` produces and translate it to a\n * `NextResponse`. Zero verdict decisions, zero engine I/O.\n *\n * Shared between the Node-runtime and Edge-runtime entries. The\n * branching here is identical in both — Next.js `NextResponse` has the\n * same API surface across runtimes; only the underlying response\n * primitive differs (Node http.ServerResponse vs Edge `Response`).\n *\n * Architectural pins per architect § 4.3 / § 4.4:\n *\n * 1. **Verdict-cookie format is contract.** Sites-1's Sonner toast\n * depends on `__checkpoint_verdict=%7B%22verdict%22%3A%22<v>%22...\n * %7D` (single URL-encoded JSON). Byte-format pinned by adapt.test.\n *\n * 2. **HTML-accepting clients → `/blocked` rewrite at status 200**\n * (so the page renders with the verdict cookie set; Sonner picks\n * up the cookie and shows the toast). Non-HTML clients → JSON 4xx.\n *\n * 3. **`X-Checkpoint-Engine` carries `result.engineInfo.name`** —\n * `checkpoint-engine-wasm` after Phase D ships. Brian's Sites-2\n * deviation note confirmed the `X-Checkpoint-*` prefix is canon.\n */\n\nimport { type NextRequest, NextResponse } from 'next/server';\n\nimport type { RenderedResponse } from '@kya-os/checkpoint-wasm-runtime/orchestrator';\nimport {\n VERDICT_COOKIE_NAME,\n BLOCKED_PATH,\n encodeVerdictCookie,\n acceptsHtml,\n classifyResponseShape,\n} from '@kya-os/checkpoint-shared';\n\n/**\n * Convert the engine's transport-agnostic `RenderedResponse` into a\n * `NextResponse`. Sites-1's Playwright suite is the regression gate;\n * any drift here is caught downstream.\n */\nexport function adaptToNextResponse(rendered: RenderedResponse, req: NextRequest): NextResponse {\n const clientAcceptsHtml = acceptsHtml(req.headers);\n const verdictCookie = encodeVerdictCookie(rendered);\n const shape = classifyResponseShape(rendered, clientAcceptsHtml);\n\n switch (shape) {\n case 'pass-through': {\n // Permit OR Observe-mode any-verdict.\n const res = NextResponse.next();\n applyHeaders(res, rendered.headers);\n setVerdictCookie(res, verdictCookie);\n return res;\n }\n\n case 'redirect': {\n // Decision::Redirect → 302 + Location.\n const target = new URL(rendered.headers.Location!);\n const res = NextResponse.redirect(target);\n applyHeaders(res, rendered.headers);\n setVerdictCookie(res, verdictCookie);\n return res;\n }\n\n case 'html-block': {\n // Sites-1 contract: HTML clients (browsers) need a renderable page\n // to show the rejection UI. The verdict cookie carries the reason;\n // the /blocked route reads it and renders the toast.\n const blockedUrl = new URL(BLOCKED_PATH, req.url);\n const res = NextResponse.rewrite(blockedUrl, { status: 200 });\n applyHeaders(res, rendered.headers);\n setVerdictCookie(res, verdictCookie);\n return res;\n }\n\n case 'json-block': {\n // The orchestrator's RenderedResponse already supplies the correct\n // status (401/403/422/...); we just need to materialise the body.\n // application/problem+json (Instruct) uses the Content-Type from\n // rendered.headers; defaults to application/json for everything else.\n const body = rendered.body ?? {};\n const res = NextResponse.json(body, { status: rendered.status as number });\n applyHeaders(res, rendered.headers);\n setVerdictCookie(res, verdictCookie);\n return res;\n }\n }\n}\n\n// -----------------------------------------------------------------------------\n// Helpers — Next.js-specific glue. The framework-agnostic primitives\n// (encodeVerdictCookie, acceptsHtml, classifyResponseShape,\n// VERDICT_COOKIE_NAME, BLOCKED_PATH) live in `@kya-os/checkpoint-shared`\n// so checkpoint-express + future host wrappers produce byte-identical\n// cookies and route HTML/JSON branching the same way.\n// -----------------------------------------------------------------------------\n\nfunction setVerdictCookie(res: NextResponse, value: string): void {\n // Path / SameSite / HttpOnly chosen for the Sonner-bridge use case:\n // path=/ so any route can read it, SameSite=Lax so first-party\n // navigations carry it, HttpOnly=false so the client-side toast JS\n // can read it (it's verdict UX, not a session token).\n res.cookies.set({\n name: VERDICT_COOKIE_NAME,\n value,\n path: '/',\n sameSite: 'lax',\n httpOnly: false,\n });\n}\n\nfunction applyHeaders(res: NextResponse, headers: Record<string, string>): void {\n // NextResponse.next() / rewrite() / json() return responses with\n // some default headers; orchestrator headers (X-Checkpoint-*, Location)\n // override. We don't strip pre-existing headers — only set new ones.\n for (const [key, value] of Object.entries(headers)) {\n res.headers.set(key, value);\n }\n}\n","/**\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; fall back to\n * `x-forwarded-for` first IP).\n */\n\nimport type { NextRequest } from 'next/server';\n\nimport type { IncomingHttpLike } from '@kya-os/checkpoint-wasm-runtime/orchestrator';\n\n/**\n * Translate a Next.js `NextRequest` into the orchestrator's\n * `IncomingHttpLike` shape.\n *\n * The body is passed through as-is — the orchestrator's\n * `buildAgentRequest` decides whether to parse JSON (looking for an\n * MCP-I `_meta.proof.jws` envelope) or treat the request as PlainHttp.\n * On Next.js middleware the body is typically not pre-parsed; consumers\n * who want to inspect the body for routing decisions should `await\n * req.json()` themselves and pass the parsed result via a second\n * `verifyRequest` call (not common).\n */\nexport function nextRequestToHttpLike(req: NextRequest): IncomingHttpLike {\n const url = new URL(req.url);\n return {\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 // NextRequest.body is a ReadableStream; we don't drain it here.\n // The orchestrator routes to PlainHttp when body is falsy, which\n // is the right call for streaming middlewares that don't want to\n // buffer the request body just to detect agents.\n body: null,\n remoteAddress: extractRemoteAddress(req),\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/**\n * Pull the originating client IP, preferring `x-forwarded-for`'s first\n * entry over `NextRequest.ip` (the latter is only populated on Vercel-\n * hosted deployments and is missing on self-hosted Next.js + nginx /\n * Fly.io / docker-compose surfaces). The `x-forwarded-for` first IP is\n * the closest the request has come to a load balancer's \"trust this is\n * the real client\" attestation — same convention as nginx, Caddy,\n * Cloudflare.\n */\nfunction extractRemoteAddress(req: NextRequest): string | undefined {\n const xff = req.headers.get('x-forwarded-for');\n if (xff) {\n const first = xff.split(',')[0]?.trim();\n if (first) return first;\n }\n // `req.ip` is typed but may be undefined off-Vercel.\n // Use `unknown` cast to avoid the type-narrowing optimism.\n const maybeIp = (req as unknown as { ip?: string }).ip;\n return maybeIp;\n}\n","/**\n * D.1 + D.3 — Node-runtime Next.js middleware entry.\n *\n * The host wrapper that composes Phase B adapters + Phase C\n * `verifyRequest` (sync engine) + Phase D translate/adapt into the\n * `withCheckpoint(config)` factory. Mounted under Vercel Node-runtime\n * serverless functions and long-lived Node servers.\n *\n * For Vercel Edge runtime (the Next.js middleware default), customers\n * import from `./edge` or `@kya-os/checkpoint-nextjs/edge` — that\n * variant uses `verifyRequestEdge` (async-init) and is otherwise\n * structurally identical. Both share `translate.ts` + `adapt.ts`.\n *\n * **Public API contract (architect § 4.1 — preserved):**\n *\n * - `withCheckpoint(config)` — factory returning the middleware.\n * - `CheckpointConfig` — the config shape; new fields are additive.\n *\n * Internal implementation gutted, external contract held. Sites-1's\n * Playwright suite is the regression gate.\n */\n\nimport { type NextRequest, type NextResponse } from 'next/server';\n\nimport {\n renderDecisionAsResponse,\n verifyRequest,\n} from '@kya-os/checkpoint-wasm-runtime/orchestrator';\nimport {\n makeDidResolver,\n makePolicyEvaluator,\n makeReputationOracle,\n makeStatusListCache,\n makeSystemClock,\n type DidResolverAdapter,\n type PolicyEvaluatorAdapter,\n type ReputationOracleAdapter,\n type StatusListCacheAdapter,\n} from '@kya-os/checkpoint-wasm-runtime/adapters';\nimport type { EnforcementMode, VerifyResult } from '@kya-os/checkpoint-wasm-runtime/engine';\n\nimport { adaptToNextResponse } from './adapt';\nimport { nextRequestToHttpLike } from './translate';\n\n/**\n * Configuration for `withCheckpoint`.\n *\n * The new minimal shape Phase D's middleware needs. Legacy\n * `AgentShieldMiddlewareConfig` (from `./api-middleware`) remains\n * exported during the deprecation window — see D.4 cutover.\n */\nexport interface CheckpointConfig {\n /**\n * Tenant identifier — typically the customer's dashboard hostname\n * (e.g. `acme.checkpoint.example`). The PolicyEvaluator uses this\n * to look up tenant policy from the dashboard.\n */\n tenantHost: string;\n\n /**\n * `'enforce'` (default) blocks; `'observe'` passes everything\n * through with `X-Checkpoint-Would-Have-Been` headers. Per Phase 0.2.\n */\n enforcementMode?: EnforcementMode;\n\n /**\n * Argus reputation oracle base URL. Omit to use the trust-by-default\n * baseline (reputation defaults to 1.0; orchestrator logs a one-shot\n * warning at first request).\n */\n argusUrl?: string;\n\n /**\n * Dashboard base URL for the PolicyEvaluator to fetch tenant policy\n * from. Omit to use the open-by-default tenant policy.\n */\n dashboardUrl?: string;\n\n /**\n * Returned to the PolicyEvaluator for anonymous requests (no agent\n * DID). Default 1.0 (trust-by-default).\n */\n reputationBaseline?: number;\n\n /**\n * Pre-built adapter instances. Production deployments use the\n * factory-built defaults from `@kya-os/checkpoint-wasm-runtime/adapters`;\n * tests use stubs. The factory composes any provided overrides over\n * defaults — partial overrides are supported.\n */\n adapters?: Partial<{\n didResolver: DidResolverAdapter;\n statusListCache: StatusListCacheAdapter;\n reputationOracle: ReputationOracleAdapter;\n policyEvaluator: PolicyEvaluatorAdapter;\n }>;\n\n /**\n * Optional callback for the post-verdict path — fires after every\n * verification, regardless of permit/block, with the full\n * `VerifyResult`. Use for logging, dashboards, telemetry. Errors\n * thrown here are swallowed so user code can't break the middleware\n * response.\n */\n onResult?: (result: VerifyResult, req: NextRequest) => void | Promise<void>;\n}\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, calls\n * `verifyRequest`, and translates the verdict to `NextResponse`. No\n * verification logic lives in this file.\n */\nexport function withCheckpoint(\n config: CheckpointConfig\n): (req: NextRequest) => Promise<NextResponse> {\n const opts = buildVerifyOpts(config);\n return async function checkpointMiddleware(req: NextRequest): Promise<NextResponse> {\n const httpLike = nextRequestToHttpLike(req);\n const result = await verifyRequest(httpLike, opts);\n await dispatchOnResult(config, result, req);\n const rendered = renderDecisionAsResponse(result);\n return adaptToNextResponse(rendered, req);\n };\n}\n\n/**\n * Compose adapter defaults with caller-supplied overrides. Factored\n * out so the Edge entry (which uses the same composition) can reuse\n * the shape.\n */\nfunction buildVerifyOpts(config: CheckpointConfig) {\n const overrides = config.adapters ?? {};\n return {\n didResolver: overrides.didResolver ?? makeDidResolver(),\n statusListCache: overrides.statusListCache ?? makeStatusListCache(),\n reputationOracle:\n overrides.reputationOracle ?? makeReputationOracle({ argusUrl: config.argusUrl }),\n policyEvaluator:\n overrides.policyEvaluator ?? makePolicyEvaluator({ dashboardUrl: config.dashboardUrl }),\n clock: makeSystemClock(),\n tenantHost: config.tenantHost,\n enforcementMode: config.enforcementMode ?? 'enforce',\n reputationBaseline: config.reputationBaseline,\n argusUrl: config.argusUrl,\n };\n}\n\nasync function dispatchOnResult(\n config: CheckpointConfig,\n result: VerifyResult,\n req: NextRequest\n): Promise<void> {\n if (!config.onResult) return;\n try {\n await config.onResult(result, req);\n } catch {\n // Swallow — onResult is observability, not verdict-critical.\n // Verdict already computed; let the response proceed.\n }\n}\n\n// Re-export the shared opts builder for the Edge entry. Internal seam;\n// not part of the public surface.\nexport { buildVerifyOpts as _buildVerifyOpts };\n","/**\n * @deprecated Phase D — legacy TS-pattern-matching middleware path is\n * gone. This file now exists only to preserve the historical export\n * surface (`createAgentShieldMiddleware`, `agentShield`) at compile\n * time. Calling either function throws a clear migration error.\n *\n * Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs`\n * (Node runtime) or `@kya-os/checkpoint-nextjs/edge` (Edge runtime).\n * The new factory accepts a `CheckpointConfig` and routes every\n * verification through the Rust `kya-os-engine` via WASM. See the\n * package CHANGELOG for the recipe.\n *\n * Architect Q10 deletion ratification — the 600-line TS pattern\n * matcher (`edge-detector-wrapper.ts`) was removed in Phase D's\n * cutover. The new path is structurally simpler and decisive: one\n * engine, one verdict, every runtime.\n */\n\nimport type { NextRequest, NextResponse } from 'next/server';\n\nimport type { NextJSMiddlewareConfig } from './types';\n\nconst MIGRATION_ERROR =\n \"@kya-os/checkpoint-nextjs's `createAgentShieldMiddleware` / `agentShield` \" +\n 'were deleted in Phase D (engine consolidation). The 600-line TS pattern ' +\n 'matcher that backed them is gone. Migrate to `withCheckpoint` from ' +\n '`@kya-os/checkpoint-nextjs` (Node runtime) or ' +\n '`@kya-os/checkpoint-nextjs/edge` (Edge runtime). ' +\n 'See packages/checkpoint-nextjs/CHANGELOG.md (1.0.0) for the recipe.';\n\n/**\n * @deprecated Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs`.\n * Throws on invocation; surface exists only so static analysis sees\n * the historical export.\n */\nexport function createAgentShieldMiddleware(\n _config: Partial<NextJSMiddlewareConfig> = {}\n): (request: NextRequest) => Promise<NextResponse> {\n throw new Error(MIGRATION_ERROR);\n}\n\n/**\n * @deprecated Alias of the deprecated `createAgentShieldMiddleware`.\n * Migrate to `withCheckpoint`.\n */\nexport function agentShield(\n config: Partial<NextJSMiddlewareConfig> = {}\n): (request: NextRequest) => Promise<NextResponse> {\n return createAgentShieldMiddleware(config);\n}\n","/**\n * Enhanced middleware creator for Edge Runtime\n * Uses EdgeAgentDetector which doesn't require WASM\n */\n\nimport { NextResponse } from 'next/server';\nimport type { NextRequest } from 'next/server';\nimport { createAgentShieldMiddleware as createBaseMiddleware } from './middleware';\nimport type { NextJSMiddlewareConfig } from './types';\n\ntype MiddlewareFunction = (request: NextRequest) => Promise<NextResponse>;\n\nlet middlewareInstance: MiddlewareFunction | null = null;\nlet isInitializing = false;\nlet initPromise: Promise<MiddlewareFunction> | null = null;\n\n/**\n * Create an AgentShield middleware with automatic WASM initialization\n * This version handles initialization internally to avoid top-level await\n */\nexport function createAgentShieldMiddleware(config: NextJSMiddlewareConfig) {\n return async function agentShieldMiddleware(request: NextRequest): Promise<NextResponse> {\n // Initialize middleware on first request (no WASM needed in Edge Runtime)\n if (!middlewareInstance) {\n if (!isInitializing) {\n isInitializing = true;\n initPromise = (async () => {\n // No WASM initialization needed - EdgeAgentDetector works without it\n\n // Create the actual middleware instance\n middlewareInstance = createBaseMiddleware(config);\n return middlewareInstance;\n })();\n }\n\n // Wait for initialization to complete\n if (initPromise) {\n middlewareInstance = await initPromise;\n }\n }\n\n // Run the middleware\n return middlewareInstance ? middlewareInstance(request) : NextResponse.next();\n };\n}\n\n/**\n * Export the original function as well for backward compatibility\n */\nexport { createAgentShieldMiddleware as createMiddleware };\n","/**\n * AgentShield API Client\n *\n * Lightweight client for calling the AgentShield enforce API from middleware.\n * Designed for Edge Runtime compatibility (no Node.js-specific APIs).\n */\n\nimport type { EnforcementAction } from '@kya-os/checkpoint-shared';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * API client configuration\n */\nexport interface CheckpointApiClientConfig {\n /** API key for authentication */\n apiKey: string;\n /** API base URL (defaults to production) */\n baseUrl?: 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 * @default true\n */\n useEdge?: boolean;\n /** Request timeout in milliseconds (default: 5000) */\n timeout?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * Enforcement action — re-exported from `@kya-os/checkpoint-shared`\n * so consumers of this package can keep importing it from the same\n * place. The canonical 6-value union is defined in\n * `packages/checkpoint-shared/src/policy/constants.ts`. `'instruct'`\n * tells the middleware to emit a 401 with an MCP-I Link header\n * pointing the agent at a connect/consent URL.\n */\nexport type { EnforcementAction };\n\n/**\n * Enforcement decision from the API\n */\nexport interface EnforcementDecision {\n action: EnforcementAction;\n reason: string;\n isAgent: boolean;\n confidence: number;\n agentName?: string;\n agentType?: string;\n redirectUrl?: string;\n message?: string;\n metadata?: {\n policyVersion?: string;\n signatureVerified?: boolean;\n denyListMatch?: {\n clientDid?: string;\n agentDid?: string;\n clientName?: string;\n reason?: string;\n };\n };\n}\n\n/**\n * Detection result (optional in response)\n */\nexport interface DetectionResult {\n isAgent: boolean;\n confidence: number;\n agentName?: string;\n agentType?: string;\n /** Detection class: 'human', 'ai_agent', 'bot', 'incomplete_data' */\n detectionClass?: string;\n verificationMethod?: string;\n reasons?: string[];\n /** Detection engine used: 'wasm' or 'javascript-fallback' */\n detectionMethod?: string;\n}\n\n/**\n * Enforce API response\n */\nexport interface EnforceResponse {\n success: boolean;\n data?: {\n decision: EnforcementDecision;\n processingTimeMs: number;\n requestId: string;\n detection?: DetectionResult;\n };\n error?: {\n code: string;\n message: string;\n };\n}\n\n/**\n * Request input for enforce API\n */\nexport interface EnforceInput {\n /** HTTP headers from the incoming request */\n headers?: Record<string, string>;\n /** User-Agent header */\n userAgent?: string;\n /** Client IP address */\n ipAddress?: string;\n /** Request path */\n path?: string;\n /** Request URL */\n url?: string;\n /** HTTP method */\n method?: string;\n /** Request ID for tracing */\n requestId?: string;\n /** Options */\n options?: {\n /** Include full detection result */\n includeDetectionResult?: boolean;\n /** Cache TTL override */\n cacheTTL?: number;\n };\n}\n\n/**\n * Input for logging a detection result\n */\nexport interface LogDetectionInput {\n /** Detection result from Gateway */\n detection: DetectionResult;\n /** Request context */\n context: {\n userAgent?: string;\n ipAddress?: string;\n path?: string;\n url?: string;\n method?: string;\n };\n /** Source of the detection */\n source?: 'gateway' | 'middleware';\n}\n\n// ============================================================================\n// Client Implementation\n// ============================================================================\n\nconst DEFAULT_BASE_URL = 'https://kya.vouched.id';\nconst EDGE_DETECT_URL = 'https://detect.checkpoint-gateway.ai';\nconst DEFAULT_TIMEOUT = 5000;\n\n/**\n * AgentShield API Client\n *\n * @example\n * ```typescript\n * const client = new CheckpointApiClient({\n * apiKey: process.env.CHECKPOINT_API_KEY!,\n * });\n *\n * const result = await client.enforce({\n * headers: Object.fromEntries(request.headers),\n * path: request.nextUrl.pathname,\n * method: request.method,\n * });\n *\n * if (result.decision.action === 'block') {\n * return new Response('Access denied', { status: 403 });\n * }\n * ```\n */\nexport class CheckpointApiClient {\n private apiKey: string;\n private baseUrl: string;\n private useEdge: boolean;\n private timeout: number;\n private debug: boolean;\n\n constructor(config: CheckpointApiClientConfig) {\n if (!config.apiKey) {\n throw new Error('AgentShield API key is required');\n }\n\n this.apiKey = config.apiKey;\n // Default to edge detection for better coverage (detects non-JS clients)\n this.useEdge = config.useEdge !== false; // true by default\n this.baseUrl = config.baseUrl || (this.useEdge ? EDGE_DETECT_URL : DEFAULT_BASE_URL);\n this.timeout = config.timeout || DEFAULT_TIMEOUT;\n this.debug = config.debug || false;\n }\n\n /**\n * Call the enforce API to check if a request should be allowed\n */\n async enforce(input: EnforceInput): Promise<EnforceResponse> {\n const startTime = Date.now();\n\n try {\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n // Use edge endpoint or Vercel API based on configuration\n const endpoint = this.useEdge\n ? `${this.baseUrl}/__detect/enforce`\n : `${this.baseUrl}/api/v1/enforce`;\n\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-Request-ID': input.requestId || crypto.randomUUID(),\n },\n body: JSON.stringify(input),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Parse response\n const data = (await response.json()) as EnforceResponse;\n\n if (this.debug) {\n console.log('[AgentShield] Enforce response:', {\n status: response.status,\n action: data.data?.decision.action,\n processingTimeMs: Date.now() - startTime,\n });\n }\n\n // Handle non-2xx responses\n if (!response.ok) {\n return {\n success: false,\n error: {\n code: `HTTP_${response.status}`,\n message: data.error?.message || `HTTP error: ${response.status}`,\n },\n };\n }\n\n return data;\n } catch (error) {\n clearTimeout(timeoutId);\n throw error;\n }\n } catch (error) {\n // Handle timeout\n if (error instanceof Error && error.name === 'AbortError') {\n if (this.debug) {\n console.warn('[AgentShield] Request timed out');\n }\n return {\n success: false,\n error: {\n code: 'TIMEOUT',\n message: `Request timed out after ${this.timeout}ms`,\n },\n };\n }\n\n // Handle network errors\n if (this.debug) {\n console.error('[AgentShield] Request failed:', error);\n }\n\n return {\n success: false,\n error: {\n code: 'NETWORK_ERROR',\n message: error instanceof Error ? error.message : 'Network request failed',\n },\n };\n }\n }\n\n /**\n * Quick check - returns just the action without full response parsing\n * Useful for very fast middleware that just needs allow/block\n */\n async quickCheck(input: EnforceInput): Promise<{\n action: EnforcementAction;\n error?: string;\n }> {\n const result = await this.enforce(input);\n\n if (!result.success || !result.data) {\n // On error, default to allow (fail-open)\n return {\n action: 'allow',\n error: result.error?.message,\n };\n }\n\n return {\n action: result.data.decision.action,\n };\n }\n\n /**\n * Check if this client is using edge detection (Gateway Worker)\n */\n isUsingEdge(): boolean {\n return this.useEdge;\n }\n\n /**\n * Log a detection result to AgentShield database.\n * Use after Gateway Worker detection to persist results.\n * Fire-and-forget - returns immediately without waiting for DB write.\n *\n * @example\n * ```typescript\n * // After receiving Gateway response\n * if (client.isUsingEdge() && response.data?.detection) {\n * client.logDetection({\n * detection: response.data.detection,\n * context: { userAgent, ipAddress, path, url, method }\n * }).catch(err => console.error('Log failed:', err));\n * }\n * ```\n */\n async logDetection(input: LogDetectionInput): Promise<void> {\n // Don't await - fire and forget\n // Use the base URL (not edge) for logging since this goes to the main API\n const logEndpoint = this.useEdge\n ? `${DEFAULT_BASE_URL}/api/v1/log-detection`\n : `${this.baseUrl}/api/v1/log-detection`;\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(logEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({\n detection: {\n isAgent: input.detection.isAgent,\n confidence: input.detection.confidence,\n agentName: input.detection.agentName,\n agentType: input.detection.agentType,\n detectionClass: input.detection.detectionClass,\n verificationMethod: input.detection.verificationMethod,\n reasons: input.detection.reasons,\n },\n context: input.context,\n source: input.source || 'gateway',\n }),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok && this.debug) {\n console.warn('[AgentShield] Log detection returned non-2xx:', response.status);\n }\n } catch (error) {\n clearTimeout(timeoutId);\n throw error;\n }\n } catch (error) {\n // Silently fail for fire-and-forget, but log in debug mode\n if (this.debug) {\n console.error('[AgentShield] Log detection failed:', error);\n }\n // Re-throw so caller can catch if needed\n throw error;\n }\n }\n}\n\n/**\n * Create a singleton client instance\n *\n * @example\n * ```typescript\n * // In middleware.ts\n * import { getCheckpointApiClient } from '@kya-os/checkpoint-nextjs';\n *\n * const client = getCheckpointApiClient();\n * ```\n */\nlet clientInstance: CheckpointApiClient | null = null;\n\nexport function getCheckpointApiClient(\n config?: Partial<CheckpointApiClientConfig>\n): CheckpointApiClient {\n if (!clientInstance) {\n const apiKey = config?.apiKey || process.env.CHECKPOINT_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n 'AgentShield API key is required. Set CHECKPOINT_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n clientInstance = new CheckpointApiClient({\n apiKey,\n baseUrl: config?.baseUrl || process.env.AGENTSHIELD_API_URL,\n // Default to edge detection unless explicitly disabled\n useEdge: config?.useEdge ?? process.env.AGENTSHIELD_USE_EDGE !== 'false',\n timeout: config?.timeout,\n debug: config?.debug || process.env.AGENTSHIELD_DEBUG === 'true',\n });\n }\n\n return clientInstance;\n}\n\n/**\n * Reset the singleton client (useful for testing)\n */\nexport function resetCheckpointApiClient(): void {\n clientInstance = null;\n}\n\n// ---------------------------------------------------------------------------\n// Back-compat aliases (Phase D rename — `AgentShield*` → `CheckpointApi*`).\n//\n// The SaaS-API deployment shape is preserved post-Phase-D — it talks to\n// the Cloudflare DNS gateway and remains a supported deployment option\n// alongside the local-engine `withCheckpoint` path. The names changed\n// to align with the rest of the `checkpoint-*` packages; the old names\n// stay live as @deprecated aliases for one release.\n// ---------------------------------------------------------------------------\n\n/** @deprecated Renamed to {@link CheckpointApiClient}. The runtime is identical. */\nexport const AgentShieldClient = CheckpointApiClient;\n\n/** @deprecated Renamed to {@link CheckpointApiClientConfig}. */\nexport type AgentShieldClientConfig = CheckpointApiClientConfig;\n\n/** @deprecated Renamed to {@link getCheckpointApiClient}. */\nexport const getAgentShieldClient = getCheckpointApiClient;\n\n/** @deprecated Renamed to {@link resetCheckpointApiClient}. */\nexport const resetAgentShieldClient = resetCheckpointApiClient;\n","/**\n * Utility functions for agentshield-nextjs\n */\n\nimport type { NextRequest } from 'next/server';\n\n/**\n * Extract client IP address from a NextRequest.\n * In Next.js 15+, the `ip` property was removed from NextRequest.\n * This function uses headers to determine the client IP.\n *\n * @param request - The NextRequest object\n * @returns The client IP address or undefined if not available\n */\nexport function getClientIp(request: NextRequest): string | undefined {\n // Check x-forwarded-for header (standard for proxies/load balancers)\n const forwardedFor = request.headers.get('x-forwarded-for');\n if (forwardedFor) {\n // Take the first IP in the chain (original client)\n const ip = forwardedFor.split(',')[0]?.trim();\n if (ip) return ip;\n }\n\n // Check x-real-ip header (commonly used by nginx)\n const realIp = request.headers.get('x-real-ip');\n if (realIp) return realIp;\n\n // Check cf-connecting-ip header (Cloudflare)\n const cfIp = request.headers.get('cf-connecting-ip');\n if (cfIp) return cfIp;\n\n // Check x-client-ip header (some proxies use this)\n const clientIp = request.headers.get('x-client-ip');\n if (clientIp) return clientIp;\n\n return 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 * Agent Instruction Response Builder (Next.js)\n *\n * Returns a 401 response with a machine-parseable Link header + JSON body\n * telling an AI agent where to send its user to complete consent / connect.\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 response\n * shape is kept in sync so LLM and MCP clients see identical behavior whether\n * a site is protected by the gateway or by the Next.js middleware.\n *\n * Implements:\n * - RFC 7235 (WWW-Authenticate header)\n * - RFC 8288 (Link header for discovery)\n *\n * @see ../../apps/web/workers/gateway/src/responses/agent-instruction.ts\n */\n\nimport { NextResponse, type NextRequest } from 'next/server';\nimport type { EnforcementDecision } from '../api-client';\nimport { safeHostname } from '../utils';\n\nconst MCP_I_DOCS_URL = 'https://docs.knowthat.ai/mcp-i/getting-started';\nconst DEFAULT_CONNECT_PATH = '/connect';\n\n/**\n * Build a 401 \"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'`). This helper only owns the\n * response shape.\n */\nexport function buildAgentInstructionResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n redirectUrl: string | undefined\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 const response = NextResponse.json(body, { status: 401 });\n\n // RFC 7235: tells strict clients this is an auth challenge.\n response.headers.set('WWW-Authenticate', `KYA realm=\"api\", authorization_uri=\"${authUrl}\"`);\n\n // RFC 8288: discovery pointer. `rel=\"kya-authorize\"` is the same value\n // the CF gateway emits — keep in sync.\n response.headers.set(\n 'Link',\n `<${authUrl}>; rel=\"kya-authorize\", <${MCP_I_DOCS_URL}>; rel=\"help\"`\n );\n\n // Headers read by MCP-I clients + our own tooling.\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 AgentShield Middleware for Next.js\n *\n * This middleware uses the AgentShield 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';\nimport { matchPath } from '@kya-os/checkpoint-shared';\nimport {\n CheckpointApiClient,\n getCheckpointApiClient,\n type EnforcementDecision,\n} from './api-client';\nimport { buildAgentInstructionResponse } from './responses/agent-instruction';\nimport { getClientIp, safeHostname } from './utils';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Middleware configuration\n */\nexport interface CheckpointApiMiddlewareConfig {\n /** API key (or use CHECKPOINT_API_KEY env var) */\n apiKey?: string;\n /** API base URL (defaults to production) */\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 /** Request timeout in ms (default: 5000) */\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 an MCP-I 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 * Custom blocked response\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\n * Default: true (recommended for production)\n */\n failOpen?: boolean;\n\n /**\n * Enable debug logging\n */\n debug?: boolean;\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// 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 AgentShield headers\n response.headers.set('KYA-Action', decision.action);\n response.headers.set('KYA-Reason', decision.reason);\n\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 AgentShield 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 });\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 const failOpen = config.failOpen ?? true;\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);\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('[AgentShield] API error:', result.error);\n }\n\n if (failOpen) {\n return NextResponse.next();\n }\n\n // Fail closed - block on error\n return NextResponse.json(\n { error: 'Security check failed', code: 'API_ERROR' },\n { status: 503 }\n );\n }\n\n const decision = result.data.decision;\n\n // Log if debug enabled\n if (config.debug) {\n console.log('[AgentShield] 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 if (client.isUsingEdge() && result.data.detection) {\n client\n .logDetection({\n detection: result.data.detection,\n context: { userAgent, ipAddress, path, url: request.url, method: request.method },\n })\n .catch((err) => {\n if (config.debug) {\n console.error('[AgentShield] Log detection failed:', err);\n }\n });\n }\n\n // Handle agent detection callback\n if (decision.isAgent && config.onAgentDetected) {\n await config.onAgentDetected(request, decision);\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 `failOpen` 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 `NextResponse.next()`\n // fail-open. Same shape as the `await config.onAgentDetected(...)`\n // call earlier in this handler.\n if (config.customBlockedResponse) {\n return await config.customBlockedResponse(request, decision);\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 return buildAgentInstructionResponse(request, decision, targetUrl);\n }\n\n case 'challenge': {\n // Future: implement challenge page\n // For now, treat as redirect\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('[AgentShield] Middleware error:', error);\n }\n\n if (failOpen) {\n return NextResponse.next();\n }\n\n return NextResponse.json(\n { error: 'Security check failed', code: 'MIDDLEWARE_ERROR' },\n { status: 503 }\n );\n }\n };\n}\n\n// ---------------------------------------------------------------------------\n// Back-compat aliases (Phase D rename — `withAgentShield` → `withCheckpointApi`).\n//\n// The SaaS-API deployment shape is alive and maintained — it dispatches\n// to the Cloudflare DNS gateway (`https://detect.checkpoint-gateway.ai`)\n// rather than running the engine locally. Customers running on\n// platforms where the local-engine path (`withCheckpoint`) doesn't fit\n// (no WASM toolchain, edge runtime quirks, centralized policy needs)\n// stay on this path. The rename aligns the function name with the rest\n// of the `checkpoint-*` surface; the old `withAgentShield` name keeps\n// shipping as a deprecated alias.\n// ---------------------------------------------------------------------------\n\n/** @deprecated Renamed to {@link withCheckpointApi}. The behaviour is identical. */\nexport const withAgentShield = withCheckpointApi;\n\n/** @deprecated Renamed to {@link CheckpointApiMiddlewareConfig}. */\nexport type AgentShieldMiddlewareConfig = CheckpointApiMiddlewareConfig;\n\n// ---------------------------------------------------------------------------\n// Legacy throw-stubs — these forms predate Phase D and were ratified as\n// dead in the architect's review. The `withCheckpoint` (local engine)\n// and `withCheckpointApi` (SaaS gateway) paths replace them.\n// ---------------------------------------------------------------------------\n\nconst LEGACY_MIGRATION_ERROR =\n 'This export was removed in Phase D. Migrate to `withCheckpoint` ' +\n '(local-engine deployment) or `withCheckpointApi` (SaaS-gateway ' +\n 'deployment) from `@kya-os/checkpoint-nextjs`. See ' +\n 'packages/checkpoint-nextjs/README.md (Two deployment shapes) for ' +\n 'which one fits your runtime.';\n\n/**\n * @deprecated Module-load-time invocation of the legacy `withAgentShield()`.\n * Construct the middleware explicitly via `withCheckpointApi({ apiKey })`\n * instead of relying on a default-constructed singleton at import time.\n */\nexport function agentShieldMiddleware(_request: NextRequest): Promise<NextResponse> {\n throw new Error(LEGACY_MIGRATION_ERROR);\n}\n\n/**\n * @deprecated The \"enhanced middleware\" combined detection + storage +\n * enforcement into a single legacy path that no longer exists. Migrate\n * to `withCheckpoint` (local-engine) or `withCheckpointApi` (SaaS-gateway).\n */\nexport function createEnhancedAgentShieldMiddleware(\n _config: EnhancedMiddlewareConfig = {}\n): (request: NextRequest) => Promise<NextResponse> {\n throw new Error(LEGACY_MIGRATION_ERROR);\n}\n\n// Deprecated type aliases retained for compile-time surface stability —\n// every field was tied to the now-dead enhanced-middleware path.\n\n/** @deprecated The enhanced-middleware path is gone. Use `CheckpointConfig` (local-engine) or `CheckpointApiMiddlewareConfig` (SaaS). */\nexport type EnhancedMiddlewareConfig = Record<string, unknown>;\n\n/** @deprecated Storage was tied to the legacy enhanced-middleware path. */\nexport type StorageAdapter = Record<string, unknown>;\n\n/** @deprecated Storage was tied to the legacy enhanced-middleware path. */\nexport type StorageConfig = Record<string, unknown>;\n\n/** @deprecated Detection events now flow through the engine; the legacy event shape no longer applies. */\nexport type AgentDetectionEvent = Record<string, unknown>;\n\n/** @deprecated Use `EdgeSessionTracker` / `StatelessSessionChecker` from `./session-tracker`. */\nexport type AgentSession = Record<string, unknown>;\n","/**\n * Edge-compatible session tracking for AI agents\n * Uses cookie-based storage to work in Edge Runtime\n */\n\nimport type { NextRequest, NextResponse } from 'next/server';\nimport type { DetectionResult } from '@kya-os/checkpoint-shared';\nimport { shouldEnforce } from '@kya-os/checkpoint-shared';\n\nexport interface SessionData {\n id: string;\n agent: string;\n confidence: number;\n detectedAt: number;\n expires: number;\n}\n\nexport interface SessionTrackingConfig {\n enabled: boolean;\n cookieName?: string;\n cookieMaxAge?: number; // in seconds\n encryptionKey?: string;\n}\n\nexport class EdgeSessionTracker {\n private readonly config: Required<SessionTrackingConfig>;\n\n constructor(config: SessionTrackingConfig) {\n this.config = {\n enabled: config.enabled,\n cookieName: config.cookieName || '__agentshield_session',\n cookieMaxAge: config.cookieMaxAge || 3600, // 1 hour default\n encryptionKey:\n config.encryptionKey || process.env.AGENTSHIELD_SECRET || 'agentshield-default-key',\n };\n }\n\n /**\n * Track a new AI agent session\n */\n async track(\n _request: NextRequest,\n response: NextResponse,\n result: DetectionResult\n ): Promise<NextResponse> {\n try {\n if (!this.config.enabled || !shouldEnforce(result)) {\n return response;\n }\n\n const sessionData: SessionData = {\n id: crypto.randomUUID(),\n agent: result.detectedAgent?.name || 'unknown',\n confidence: result.confidence,\n detectedAt: Date.now(),\n expires: Date.now() + this.config.cookieMaxAge * 1000,\n };\n\n // Encrypt session data for security\n const encrypted = await this.encrypt(JSON.stringify(sessionData));\n\n // Set secure httpOnly cookie\n response.cookies.set(this.config.cookieName, encrypted, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n maxAge: this.config.cookieMaxAge,\n path: '/',\n });\n\n return response;\n } catch (error) {\n // Fail gracefully - log error but don't break request\n if (process.env.DEBUG_AGENTSHIELD) {\n console.warn('AgentShield: Failed to track session:', error);\n }\n return response;\n }\n }\n\n /**\n * Check for existing AI agent session\n */\n async check(request: NextRequest): Promise<SessionData | null> {\n try {\n if (!this.config.enabled) {\n return null;\n }\n\n const cookie = request.cookies.get(this.config.cookieName);\n if (!cookie?.value) {\n return null;\n }\n\n // Decrypt and parse session data\n const decrypted = await this.decrypt(cookie.value);\n const session: SessionData = JSON.parse(decrypted);\n\n // Check if session is expired\n if (session.expires < Date.now()) {\n return null;\n }\n\n return session;\n } catch (error) {\n // Fail gracefully - invalid or corrupted session\n if (process.env.DEBUG_AGENTSHIELD) {\n console.warn('AgentShield: Failed to check session:', error);\n }\n return null;\n }\n }\n\n /**\n * Clear an existing session\n */\n clear(response: NextResponse): NextResponse {\n try {\n response.cookies.delete(this.config.cookieName);\n } catch (error) {\n // Fail gracefully\n if (process.env.DEBUG_AGENTSHIELD) {\n console.warn('AgentShield: Failed to clear session:', error);\n }\n }\n return response;\n }\n\n /**\n * Simple encryption using Web Crypto API (Edge-compatible)\n */\n private async encrypt(data: string): Promise<string> {\n try {\n // For Edge Runtime, use simple base64 encoding with obfuscation\n // In production, consider using Web Crypto API subtle.encrypt()\n const key = this.config.encryptionKey;\n const encoded = new TextEncoder().encode(data);\n\n // Simple XOR obfuscation\n const obfuscated = new Uint8Array(encoded.length);\n for (let i = 0; i < encoded.length; i++) {\n obfuscated[i] = (encoded[i] || 0) ^ key.charCodeAt(i % key.length);\n }\n\n // Convert to base64\n return btoa(Array.from(obfuscated, (byte) => String.fromCharCode(byte)).join(''));\n } catch (error) {\n // Fallback to simple base64 if encryption fails\n return btoa(data);\n }\n }\n\n /**\n * Simple decryption (Edge-compatible)\n */\n private async decrypt(data: string): Promise<string> {\n try {\n const key = this.config.encryptionKey;\n const decoded = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));\n\n // Reverse XOR obfuscation\n const deobfuscated = new Uint8Array(decoded.length);\n for (let i = 0; i < decoded.length; i++) {\n deobfuscated[i] = (decoded[i] || 0) ^ key.charCodeAt(i % key.length);\n }\n\n return new TextDecoder().decode(deobfuscated);\n } catch (error) {\n // Fallback to simple base64 if decryption fails\n return atob(data);\n }\n }\n}\n\n/**\n * Stateless session checker for non-Next.js environments (Express, etc.)\n * Uses a combination of headers to identify continued sessions\n */\nexport class StatelessSessionChecker {\n static check(headers: Record<string, string>): SessionData | null {\n try {\n // Check for session headers (set by previous response)\n const agent = headers['kya-session-agent'];\n const confidence = headers['kya-session-confidence'];\n const sessionId = headers['kya-session-id'];\n\n if (agent && confidence && sessionId) {\n return {\n id: sessionId,\n agent,\n confidence: parseFloat(confidence),\n detectedAt: Date.now(),\n expires: Date.now() + 3600000, // 1 hour\n };\n }\n\n // Check for cookie-based session (if cookies are parsed)\n const cookieHeader = headers['cookie'];\n if (cookieHeader && cookieHeader.includes('__agentshield_session=')) {\n // Simple cookie parsing\n const match = cookieHeader.match(/__agentshield_session=([^;]+)/);\n if (match && match[1]) {\n try {\n const decoded = atob(match[1]);\n return JSON.parse(decoded);\n } catch {\n // Invalid session data\n }\n }\n }\n\n return null;\n } catch {\n return null;\n }\n }\n\n static setHeaders(response: any, session: SessionData): void {\n try {\n // Set session headers for stateless tracking\n if (response.setHeader) {\n response.setHeader('KYA-Session-Agent', session.agent);\n response.setHeader('KYA-Session-Confidence', session.confidence.toString());\n response.setHeader('KYA-Session-Id', session.id);\n } else if (response.headers && response.headers.set) {\n response.headers.set('kya-session-agent', session.agent);\n response.headers.set('kya-session-confidence', session.confidence.toString());\n response.headers.set('kya-session-id', session.id);\n }\n } catch {\n // Fail gracefully\n }\n }\n}\n","/**\n * Policy Integration for agentshield-nextjs\n *\n * This module provides policy evaluation support for the Next.js middleware.\n * It can use:\n * - Local policy configuration (static)\n * - Fetched policy from AgentShield API (dynamic with caching)\n * - Fallback/default policies\n *\n * @example\n * ```typescript\n * import { createPolicyMiddleware } from '@kya-os/checkpoint-nextjs/policy';\n *\n * export default createPolicyMiddleware({\n * policy: {\n * enabled: true,\n * defaultAction: 'allow',\n * thresholds: { confidenceThreshold: 80, confidenceAction: 'block' },\n * allowList: [{ clientName: 'ChatGPT' }],\n * },\n * });\n * ```\n */\n\nimport { NextRequest, NextResponse } from 'next/server';\nimport {\n evaluatePolicy,\n createEvaluationContext,\n createPolicyFetcher,\n matchPath,\n PolicyFetcher,\n PolicyConfigSchema,\n ENFORCEMENT_ACTIONS,\n DEFAULT_POLICY,\n type PolicyConfig,\n type PolicyEvaluationContext,\n type PolicyEvaluationResult,\n type PolicyFetcherConfig,\n type DetectionResult,\n} from '@kya-os/checkpoint-shared';\n\n// Re-export shared policy types for convenience\nexport {\n evaluatePolicy,\n createEvaluationContext,\n type PolicyConfig,\n type PolicyEvaluationContext,\n type PolicyEvaluationResult,\n ENFORCEMENT_ACTIONS,\n DEFAULT_POLICY,\n} from '@kya-os/checkpoint-shared';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Policy middleware configuration\n */\nexport interface PolicyMiddlewareConfig {\n /**\n * Local policy configuration (static)\n * If provided, this policy is used instead of fetching from API\n */\n policy?: Partial<PolicyConfig>;\n\n /**\n * Fetch policy from AgentShield API\n * Requires projectId and optionally an apiKey\n */\n fetchPolicy?: {\n /** Project ID to fetch policy for */\n projectId: string;\n /** API base URL (defaults to production) */\n apiUrl?: string;\n /** API key for authentication */\n apiKey?: string;\n /** Cache TTL in seconds (default: 300) */\n cacheTtlSeconds?: number;\n };\n\n /**\n * Fallback policy to use when fetch fails\n * Defaults to DEFAULT_POLICY (allow all)\n */\n fallbackPolicy?: Partial<PolicyConfig>;\n\n /**\n * Custom blocked response\n */\n blockedResponse?: {\n status?: number;\n message?: string;\n headers?: Record<string, string>;\n };\n\n /**\n * Default redirect URL for redirect actions\n */\n redirectUrl?: string;\n\n /**\n * Callback when policy decision is made\n */\n onPolicyDecision?: (\n request: NextRequest,\n decision: PolicyEvaluationResult,\n context: PolicyEvaluationContext\n ) => void | Promise<void>;\n\n /**\n * Custom response builder for blocked requests\n */\n customBlockedResponse?: (\n request: NextRequest,\n decision: PolicyEvaluationResult\n ) => NextResponse | Promise<NextResponse>;\n\n /**\n * Whether to fail open (allow) on policy evaluation errors\n * Default: true (recommended for production)\n */\n failOpen?: boolean;\n\n /**\n * Enable debug logging\n */\n debug?: boolean;\n}\n\n/**\n * Combined middleware configuration with policy support\n */\nexport interface NextJSPolicyMiddlewareConfig extends PolicyMiddlewareConfig {\n /**\n * Paths to skip (in addition to policy excludedPaths)\n */\n skipPaths?: string[];\n\n /**\n * Only enforce on these paths (overrides policy includedPaths)\n */\n includePaths?: string[];\n}\n\n// ============================================================================\n// Policy Evaluation Helper\n// ============================================================================\n\n/**\n * Create policy evaluation context from detection result and request\n */\nexport function createContextFromDetection(\n detection: DetectionResult,\n request: NextRequest\n): PolicyEvaluationContext {\n return createEvaluationContext({\n agentType: detection.detectedAgent?.type,\n agentName: detection.detectedAgent?.name,\n agentVendor: detection.detectedAgent?.vendor,\n confidence: detection.confidence,\n riskLevel: detection.riskLevel,\n path: request.nextUrl.pathname,\n method: request.method,\n signatureVerified: detection.verificationMethod === 'signature',\n isAuthenticated: false, // TODO: integrate with auth\n userAgent: request.headers.get('user-agent') || undefined,\n });\n}\n\n/**\n * Evaluate policy for a detection result\n */\nexport function evaluatePolicyForDetection(\n detection: DetectionResult,\n request: NextRequest,\n policy: PolicyConfig\n): PolicyEvaluationResult {\n const context = createContextFromDetection(detection, request);\n return evaluatePolicy(policy, context);\n}\n\n// ============================================================================\n// Response Builders\n// ============================================================================\n\n/**\n * Build blocked response based on policy decision\n */\nexport function buildBlockedResponse(\n decision: PolicyEvaluationResult,\n config: PolicyMiddlewareConfig\n): NextResponse {\n const status = config.blockedResponse?.status ?? 403;\n const message = config.blockedResponse?.message ?? decision.message ?? 'Access denied';\n\n const response = NextResponse.json(\n {\n error: message,\n code: 'POLICY_BLOCKED',\n reason: decision.reason,\n ruleId: decision.ruleId,\n matchType: decision.matchType,\n },\n { status }\n );\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 // Add AgentShield headers\n response.headers.set('KYA-Action', decision.action);\n response.headers.set('KYA-Reason', decision.reason);\n response.headers.set('KYA-Match-Type', decision.matchType);\n\n return response;\n}\n\n/**\n * Build redirect response based on policy decision\n */\nexport function buildRedirectResponse(\n request: NextRequest,\n decision: PolicyEvaluationResult,\n config: PolicyMiddlewareConfig,\n detection?: { detectedAgent?: { name?: string } }\n): NextResponse {\n const redirectUrl = decision.redirectUrl || config.redirectUrl || '/blocked';\n const url = new URL(redirectUrl, request.url);\n\n // Add query params with policy info\n url.searchParams.set('reason', decision.reason);\n if (decision.ruleId) {\n url.searchParams.set('ruleId', decision.ruleId);\n }\n const agentName = detection?.detectedAgent?.name;\n if (agentName && !url.searchParams.has('agent')) {\n url.searchParams.set('agent', agentName.toLowerCase());\n }\n\n return NextResponse.redirect(url);\n}\n\n/**\n * Build challenge response (placeholder - future implementation)\n */\nexport function buildChallengeResponse(\n request: NextRequest,\n decision: PolicyEvaluationResult,\n config: PolicyMiddlewareConfig,\n detection?: { detectedAgent?: { name?: string } }\n): NextResponse {\n // For now, treat challenge as redirect\n // Future: implement CAPTCHA, proof-of-work, etc.\n return buildRedirectResponse(request, decision, config, detection);\n}\n\n// ============================================================================\n// Policy Handler\n// ============================================================================\n\n/**\n * Handle policy decision and return appropriate response\n */\nexport async function handlePolicyDecision(\n request: NextRequest,\n decision: PolicyEvaluationResult,\n config: PolicyMiddlewareConfig,\n detection?: { detectedAgent?: { name?: string } }\n): Promise<NextResponse | null> {\n switch (decision.action) {\n case ENFORCEMENT_ACTIONS.BLOCK:\n if (config.customBlockedResponse) {\n return await config.customBlockedResponse(request, decision);\n }\n return buildBlockedResponse(decision, config);\n\n case ENFORCEMENT_ACTIONS.REDIRECT:\n return buildRedirectResponse(request, decision, config, detection);\n\n case ENFORCEMENT_ACTIONS.CHALLENGE:\n return buildChallengeResponse(request, decision, config, detection);\n\n case ENFORCEMENT_ACTIONS.LOG:\n // LOG action always logs - that's its purpose\n // (debug flag controls verbose debugging output, not LOG action behavior)\n console.log('[AgentShield] Policy decision (log):', {\n path: request.nextUrl.pathname,\n action: decision.action,\n reason: decision.reason,\n matchType: decision.matchType,\n ruleId: decision.ruleId,\n });\n return null; // Continue to allow\n\n case ENFORCEMENT_ACTIONS.ALLOW:\n default:\n return null; // Continue\n }\n}\n\n// ============================================================================\n// Policy Fetcher Integration\n// ============================================================================\n\n// Cache fetchers by config to avoid recreating them, but also support\n// different configurations (different apiUrl, apiKey, etc.)\nconst fetcherCache = new Map<string, PolicyFetcher>();\n\n/**\n * Generate a cache key for fetcher config.\n * Uses ?? to distinguish between explicit 0 and undefined values.\n */\nfunction getFetcherCacheKey(config: NonNullable<PolicyMiddlewareConfig['fetchPolicy']>): string {\n return `${config.apiUrl ?? 'default'}:${config.apiKey ?? ''}:${config.cacheTtlSeconds ?? 'default'}`;\n}\n\n/**\n * Get or create policy fetcher for the given config\n */\nfunction getPolicyFetcher(config: PolicyMiddlewareConfig['fetchPolicy']): PolicyFetcher {\n if (!config) {\n throw new Error('fetchPolicy config required');\n }\n\n const cacheKey = getFetcherCacheKey(config);\n let fetcher = fetcherCache.get(cacheKey);\n\n if (!fetcher) {\n const fetcherConfig: PolicyFetcherConfig = {\n apiBaseUrl: config.apiUrl || 'https://kya.vouched.id',\n apiKey: config.apiKey,\n cacheTtlSeconds: config.cacheTtlSeconds,\n };\n fetcher = createPolicyFetcher(fetcherConfig);\n fetcherCache.set(cacheKey, fetcher);\n }\n\n return fetcher;\n}\n\n/**\n * Get policy (local, fetched, or fallback)\n */\nexport async function getPolicy(config: PolicyMiddlewareConfig): Promise<PolicyConfig> {\n // Use local policy if provided\n if (config.policy) {\n return PolicyConfigSchema.parse({ ...DEFAULT_POLICY, ...config.policy });\n }\n\n // Fetch from API if configured\n if (config.fetchPolicy) {\n try {\n const fetcher = getPolicyFetcher(config.fetchPolicy);\n return await fetcher.getPolicy(config.fetchPolicy.projectId);\n } catch (error) {\n if (config.debug) {\n console.warn('[AgentShield] Policy fetch failed, using fallback:', error);\n }\n // Return fallback policy\n return PolicyConfigSchema.parse({\n ...DEFAULT_POLICY,\n ...(config.fallbackPolicy || {}),\n });\n }\n }\n\n // No policy configured - return default (allow all)\n return PolicyConfigSchema.parse(DEFAULT_POLICY);\n}\n\n// ============================================================================\n// Standalone Policy Middleware\n// ============================================================================\n\n/**\n * Apply policy to a detection result\n *\n * This function can be used standalone to evaluate policy after detection.\n * Supports extended config with skipPaths and includePaths for path-based filtering.\n *\n * @example\n * ```typescript\n * const result = await detector.analyze(context);\n * const response = await applyPolicy(request, result, {\n * policy: { thresholds: { confidenceThreshold: 80 } },\n * skipPaths: ['/health', '/api/public/*'],\n * includePaths: ['/api/*'],\n * });\n *\n * if (response) {\n * return response; // Policy blocked the request\n * }\n * ```\n */\nexport async function applyPolicy(\n request: NextRequest,\n detection: DetectionResult,\n config: NextJSPolicyMiddlewareConfig\n): Promise<NextResponse | null> {\n try {\n const path = request.nextUrl.pathname;\n\n // Check skipPaths - if path matches any skip pattern, allow through\n if (config.skipPaths?.some((pattern) => matchPath(path, pattern))) {\n return null; // Skip policy enforcement for this path\n }\n\n // Check includePaths - if defined, path must match at least one pattern\n if (config.includePaths && config.includePaths.length > 0) {\n if (!config.includePaths.some((pattern) => matchPath(path, pattern))) {\n return null; // Path not in included paths, skip policy enforcement\n }\n }\n\n // Get policy\n const policy = await getPolicy(config);\n\n // Create context and evaluate\n const context = createContextFromDetection(detection, request);\n const decision = evaluatePolicy(policy, context);\n\n // Call decision callback if provided\n if (config.onPolicyDecision) {\n await config.onPolicyDecision(request, decision, context);\n }\n\n // Handle decision — pass detection through so redirect can append ?agent=\n return await handlePolicyDecision(request, decision, config, detection);\n } catch (error) {\n if (config.debug) {\n console.error('[AgentShield] Policy evaluation error:', error);\n }\n\n if (config.failOpen !== false) {\n return null; // Allow on error\n }\n\n // Fail closed\n return NextResponse.json(\n { error: 'Security check failed', code: 'POLICY_ERROR' },\n { status: 503 }\n );\n }\n}\n","/**\n * @fileoverview Checkpoint Next.js Integration\n * @license MIT OR Apache-2.0\n */\n\n// =============================================================================\n// Two deployment shapes — pick the one that fits your runtime.\n//\n// 1. `withCheckpoint` (local-engine):\n// Runs the Rust `kya-os-engine` in-process via WASM. Lowest latency,\n// no network round-trip per request, deterministic verdicts. Requires\n// the WASM artifact to load — works under Node and Vercel Edge by\n// default; bare-Edge / browser embedders need a polyfill story.\n//\n// 2. `withCheckpointApi` (SaaS-gateway):\n// Dispatches detection + enforcement to the Cloudflare DNS gateway\n// (`https://detect.checkpoint-gateway.ai`). Trades ~30-50ms of edge\n// latency for centralized policy management + dashboard rules + works\n// in any environment that can fetch HTTPS. No WASM needed.\n//\n// Both ship from the same package; mix and match per route if you want.\n// See `README.md` § \"Two deployment shapes\" for the decision matrix.\n// =============================================================================\n\n// Shape 1 — local-engine. `.` export auto-routes via package.json\n// conditions (`edge-runtime`, `browser`, default); explicit `./edge`\n// and `./node` subpaths also exported.\nexport { withCheckpoint } from './middleware-node';\nexport type { CheckpointConfig } from './middleware-node';\n\n// Export the enhanced middleware that handles initialization internally\nexport { createAgentShieldMiddleware, createMiddleware } from './create-middleware';\n\n// Legacy throw-stubs — the enhanced-middleware path was retired in\n// Phase D and the type aliases ship as `Record<string, unknown>` to\n// keep the compile-time surface stable. The shapes were moved off\n// `./enhanced-middleware` so the public API has zero static refs to\n// the three D.4-deferred files\n// (`enhanced-middleware.ts`, `edge-detector-with-wasm.ts`,\n// `edge-safe-detector.ts`); see\n// `__tests__/phase-d-orphan-deferred-files.test.ts` for the gate.\nexport {\n createEnhancedAgentShieldMiddleware,\n type EnhancedMiddlewareConfig,\n type StorageAdapter,\n type StorageConfig,\n type AgentDetectionEvent,\n type AgentSession,\n} from './api-middleware';\n\n// Legacy `createAgentShieldMiddleware` from middleware.ts is now a\n// deprecation stub — see middleware.ts header. Re-export preserved\n// for surface-stability; calls throw a migration error pointing at\n// `withCheckpoint`.\nexport { createAgentShieldMiddleware as createAgentShieldMiddlewareBase } from './middleware';\n\n// Export session tracking utilities\nexport { EdgeSessionTracker, StatelessSessionChecker } from './session-tracker';\nexport type { SessionData, SessionTrackingConfig } from './session-tracker';\n\n// Shape 2 — SaaS-gateway. Talks to the Cloudflare DNS gateway over\n// HTTPS; no local WASM. The function name was `withAgentShield` pre-\n// Phase D; the old name is kept as a `@deprecated` alias for one\n// release. The behaviour is identical.\nexport { withCheckpointApi } from './api-middleware';\nexport type { CheckpointApiMiddlewareConfig } from './api-middleware';\nexport {\n CheckpointApiClient,\n getCheckpointApiClient,\n resetCheckpointApiClient,\n} from './api-client';\nexport type {\n CheckpointApiClientConfig,\n EnforcementAction,\n EnforcementDecision,\n EnforceResponse,\n EnforceInput,\n LogDetectionInput,\n} from './api-client';\n\n// Deprecated aliases for the pre-Phase-D names. New code should import\n// the `Checkpoint*` names directly.\nexport {\n withAgentShield,\n agentShieldMiddleware,\n type AgentShieldMiddlewareConfig,\n} from './api-middleware';\nexport {\n AgentShieldClient,\n getAgentShieldClient,\n resetAgentShieldClient,\n type AgentShieldClientConfig,\n} from './api-client';\n\nexport * from './types';\n// Hooks are not exported from main entry - they're client-only\n// If someone needs hooks, they should import from '@kya-os/checkpoint-nextjs/hooks'\n\n// Export policy utilities for local policy evaluation\nexport {\n applyPolicy,\n evaluatePolicyForDetection,\n createContextFromDetection,\n handlePolicyDecision,\n getPolicy,\n buildBlockedResponse as buildPolicyBlockedResponse,\n buildRedirectResponse as buildPolicyRedirectResponse,\n // Re-exports from shared\n evaluatePolicy,\n createEvaluationContext,\n ENFORCEMENT_ACTIONS,\n DEFAULT_POLICY,\n} from './policy';\nexport type {\n PolicyMiddlewareConfig,\n NextJSPolicyMiddlewareConfig,\n PolicyConfig,\n PolicyEvaluationContext,\n PolicyEvaluationResult,\n} from './policy';\n\n/**\n * Library version\n */\nexport const VERSION = '0.1.0';\n"]}
@@ -0,0 +1,46 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ export { initEngineEdge } from '@kya-os/checkpoint-wasm-runtime/orchestrator/edge';
3
+ import { CheckpointConfig } from './middleware-node.mjs';
4
+ import '@kya-os/checkpoint-wasm-runtime/adapters';
5
+ import '@kya-os/checkpoint-wasm-runtime/engine';
6
+
7
+ /**
8
+ * D.3 — Edge-runtime Next.js middleware entry.
9
+ *
10
+ * The async-init equivalent of `./middleware-node.ts`. Mounted under
11
+ * Vercel Edge runtime (the Next.js middleware default) and Cloudflare
12
+ * Workers when Next.js targets the Edge.
13
+ *
14
+ * Differs from the Node entry in exactly two places:
15
+ *
16
+ * 1. Imports `verifyRequestEdge` + `initEngineEdge` from the
17
+ * orchestrator's `./edge` subpath (Edge-WASM-2 from D.1.5)
18
+ * instead of `verifyRequest` from the Node orchestrator entry.
19
+ * 2. Calls `initEngineEdge()` once at module load (eagerly, before
20
+ * any request hits the middleware) so the first request's cold-
21
+ * boot latency is amortised onto deploy time. Subsequent calls
22
+ * to `initEngineEdge` are idempotent.
23
+ *
24
+ * Adapter composition (`buildVerifyOpts`), translate.ts, adapt.ts,
25
+ * verdict-cookie format, X-Checkpoint-* headers — all shared with
26
+ * the Node entry. Cross-runtime parity verified by Phase F's CI gate
27
+ * (D.5 ships the Next.js-specific half).
28
+ *
29
+ * **Public API contract — preserved:** `withCheckpoint(config)`,
30
+ * `CheckpointConfig`. Same exports as Node, same signatures.
31
+ */
32
+
33
+ /**
34
+ * Build the Checkpoint middleware for Edge runtime. Returns a function
35
+ * `(req) => Promise<NextResponse>` suitable for
36
+ * `export default withCheckpoint({...})` in `middleware.ts` under
37
+ * `export const config = { runtime: 'edge' }`.
38
+ *
39
+ * Idempotent eager init: the first call to `withCheckpoint` kicks off
40
+ * `initEngineEdge()` so the wasm artifact loads while the rest of the
41
+ * factory closure is being built. The first request awaits the same
42
+ * promise; subsequent requests resolve sync.
43
+ */
44
+ declare function withCheckpoint(config: CheckpointConfig): (req: NextRequest) => Promise<NextResponse>;
45
+
46
+ export { CheckpointConfig, withCheckpoint };
@@ -0,0 +1,46 @@
1
+ import { NextRequest, NextResponse } from 'next/server';
2
+ export { initEngineEdge } from '@kya-os/checkpoint-wasm-runtime/orchestrator/edge';
3
+ import { CheckpointConfig } from './middleware-node.js';
4
+ import '@kya-os/checkpoint-wasm-runtime/adapters';
5
+ import '@kya-os/checkpoint-wasm-runtime/engine';
6
+
7
+ /**
8
+ * D.3 — Edge-runtime Next.js middleware entry.
9
+ *
10
+ * The async-init equivalent of `./middleware-node.ts`. Mounted under
11
+ * Vercel Edge runtime (the Next.js middleware default) and Cloudflare
12
+ * Workers when Next.js targets the Edge.
13
+ *
14
+ * Differs from the Node entry in exactly two places:
15
+ *
16
+ * 1. Imports `verifyRequestEdge` + `initEngineEdge` from the
17
+ * orchestrator's `./edge` subpath (Edge-WASM-2 from D.1.5)
18
+ * instead of `verifyRequest` from the Node orchestrator entry.
19
+ * 2. Calls `initEngineEdge()` once at module load (eagerly, before
20
+ * any request hits the middleware) so the first request's cold-
21
+ * boot latency is amortised onto deploy time. Subsequent calls
22
+ * to `initEngineEdge` are idempotent.
23
+ *
24
+ * Adapter composition (`buildVerifyOpts`), translate.ts, adapt.ts,
25
+ * verdict-cookie format, X-Checkpoint-* headers — all shared with
26
+ * the Node entry. Cross-runtime parity verified by Phase F's CI gate
27
+ * (D.5 ships the Next.js-specific half).
28
+ *
29
+ * **Public API contract — preserved:** `withCheckpoint(config)`,
30
+ * `CheckpointConfig`. Same exports as Node, same signatures.
31
+ */
32
+
33
+ /**
34
+ * Build the Checkpoint middleware for Edge runtime. Returns a function
35
+ * `(req) => Promise<NextResponse>` suitable for
36
+ * `export default withCheckpoint({...})` in `middleware.ts` under
37
+ * `export const config = { runtime: 'edge' }`.
38
+ *
39
+ * Idempotent eager init: the first call to `withCheckpoint` kicks off
40
+ * `initEngineEdge()` so the wasm artifact loads while the rest of the
41
+ * factory closure is being built. The first request awaits the same
42
+ * promise; subsequent requests resolve sync.
43
+ */
44
+ declare function withCheckpoint(config: CheckpointConfig): (req: NextRequest) => Promise<NextResponse>;
45
+
46
+ export { CheckpointConfig, withCheckpoint };
@@ -0,0 +1,134 @@
1
+ 'use strict';
2
+
3
+ var edge = require('@kya-os/checkpoint-wasm-runtime/orchestrator/edge');
4
+ var server = require('next/server');
5
+ var checkpointShared = require('@kya-os/checkpoint-shared');
6
+ require('@kya-os/checkpoint-wasm-runtime/orchestrator');
7
+ var adapters = require('@kya-os/checkpoint-wasm-runtime/adapters');
8
+
9
+ // src/middleware-edge.ts
10
+ function adaptToNextResponse(rendered, req) {
11
+ const clientAcceptsHtml = checkpointShared.acceptsHtml(req.headers);
12
+ const verdictCookie = checkpointShared.encodeVerdictCookie(rendered);
13
+ const shape = checkpointShared.classifyResponseShape(rendered, clientAcceptsHtml);
14
+ switch (shape) {
15
+ case "pass-through": {
16
+ const res = server.NextResponse.next();
17
+ applyHeaders(res, rendered.headers);
18
+ setVerdictCookie(res, verdictCookie);
19
+ return res;
20
+ }
21
+ case "redirect": {
22
+ const target = new URL(rendered.headers.Location);
23
+ const res = server.NextResponse.redirect(target);
24
+ applyHeaders(res, rendered.headers);
25
+ setVerdictCookie(res, verdictCookie);
26
+ return res;
27
+ }
28
+ case "html-block": {
29
+ const blockedUrl = new URL(checkpointShared.BLOCKED_PATH, req.url);
30
+ const res = server.NextResponse.rewrite(blockedUrl, { status: 200 });
31
+ applyHeaders(res, rendered.headers);
32
+ setVerdictCookie(res, verdictCookie);
33
+ return res;
34
+ }
35
+ case "json-block": {
36
+ const body = rendered.body ?? {};
37
+ const res = server.NextResponse.json(body, { status: rendered.status });
38
+ applyHeaders(res, rendered.headers);
39
+ setVerdictCookie(res, verdictCookie);
40
+ return res;
41
+ }
42
+ }
43
+ }
44
+ function setVerdictCookie(res, value) {
45
+ res.cookies.set({
46
+ name: checkpointShared.VERDICT_COOKIE_NAME,
47
+ value,
48
+ path: "/",
49
+ sameSite: "lax",
50
+ httpOnly: false
51
+ });
52
+ }
53
+ function applyHeaders(res, headers) {
54
+ for (const [key, value] of Object.entries(headers)) {
55
+ res.headers.set(key, value);
56
+ }
57
+ }
58
+
59
+ // src/translate.ts
60
+ function nextRequestToHttpLike(req) {
61
+ const url = new URL(req.url);
62
+ return {
63
+ method: req.method,
64
+ // Path + query only — orchestrator's URL parsing expects no scheme/host.
65
+ url: url.pathname + url.search,
66
+ headers: headersToRecord(req.headers),
67
+ // NextRequest.body is a ReadableStream; we don't drain it here.
68
+ // The orchestrator routes to PlainHttp when body is falsy, which
69
+ // is the right call for streaming middlewares that don't want to
70
+ // buffer the request body just to detect agents.
71
+ body: null,
72
+ remoteAddress: extractRemoteAddress(req)
73
+ };
74
+ }
75
+ function headersToRecord(headers) {
76
+ const out = {};
77
+ headers.forEach((value, key) => {
78
+ out[key.toLowerCase()] = value;
79
+ });
80
+ return out;
81
+ }
82
+ function extractRemoteAddress(req) {
83
+ const xff = req.headers.get("x-forwarded-for");
84
+ if (xff) {
85
+ const first = xff.split(",")[0]?.trim();
86
+ if (first) return first;
87
+ }
88
+ const maybeIp = req.ip;
89
+ return maybeIp;
90
+ }
91
+
92
+ // src/middleware-node.ts
93
+ function buildVerifyOpts(config) {
94
+ const overrides = config.adapters ?? {};
95
+ return {
96
+ didResolver: overrides.didResolver ?? adapters.makeDidResolver(),
97
+ statusListCache: overrides.statusListCache ?? adapters.makeStatusListCache(),
98
+ reputationOracle: overrides.reputationOracle ?? adapters.makeReputationOracle({ argusUrl: config.argusUrl }),
99
+ policyEvaluator: overrides.policyEvaluator ?? adapters.makePolicyEvaluator({ dashboardUrl: config.dashboardUrl }),
100
+ clock: adapters.makeSystemClock(),
101
+ tenantHost: config.tenantHost,
102
+ enforcementMode: config.enforcementMode ?? "enforce",
103
+ reputationBaseline: config.reputationBaseline,
104
+ argusUrl: config.argusUrl
105
+ };
106
+ }
107
+
108
+ // src/middleware-edge.ts
109
+ function withCheckpoint(config) {
110
+ void edge.initEngineEdge();
111
+ const opts = buildVerifyOpts(config);
112
+ return async function checkpointMiddlewareEdge(req) {
113
+ const httpLike = nextRequestToHttpLike(req);
114
+ const result = await edge.verifyRequestEdge(httpLike, opts);
115
+ await dispatchOnResult(config, result, req);
116
+ const rendered = edge.renderDecisionAsResponse(result);
117
+ return adaptToNextResponse(rendered, req);
118
+ };
119
+ }
120
+ async function dispatchOnResult(config, result, req) {
121
+ if (!config.onResult) return;
122
+ try {
123
+ await config.onResult(result, req);
124
+ } catch {
125
+ }
126
+ }
127
+
128
+ Object.defineProperty(exports, "initEngineEdge", {
129
+ enumerable: true,
130
+ get: function () { return edge.initEngineEdge; }
131
+ });
132
+ exports.withCheckpoint = withCheckpoint;
133
+ //# sourceMappingURL=middleware-edge.js.map
134
+ //# sourceMappingURL=middleware-edge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapt.ts","../src/translate.ts","../src/middleware-node.ts","../src/middleware-edge.ts"],"names":["acceptsHtml","encodeVerdictCookie","classifyResponseShape","NextResponse","BLOCKED_PATH","VERDICT_COOKIE_NAME","makeDidResolver","makeStatusListCache","makeReputationOracle","makePolicyEvaluator","makeSystemClock","initEngineEdge","verifyRequestEdge","renderDecisionAsResponse"],"mappings":";;;;;;;;;AA4CO,SAAS,mBAAA,CAAoB,UAA4B,GAAA,EAAgC;AAC9F,EAAA,MAAM,iBAAA,GAAoBA,4BAAA,CAAY,GAAA,CAAI,OAAO,CAAA;AACjD,EAAA,MAAM,aAAA,GAAgBC,qCAAoB,QAAQ,CAAA;AAClD,E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GAAS,MAAMC,sBAAA,CAAkB,QAAA,EAAU,IAAI,CAAA;AACrD,IAAA,MAAM,gBAAA,CAAiB,MAAA,EAAQ,MAAA,EAAQ,GAAG,CAAA;AAC1C,IAAA,MAAM,QAAA,GAAWC,8BAAyB,MAAM,CAAA;AAChD,IAAA,OAAO,mBAAA,CAAoB,UAAU,GAAG,CAAA;AAAA,EAC1C,CAAA;AACF;AAEA,eAAe,gBAAA,CACb,MAAA,EACA,MAAA,EACA,GAAA,EACe;AACf,EAAA,IAAI,CAAC,OAAO,QAAA,EAAU;AACtB,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,CAAO,QAAA,CAAS,MAAA,EAAQ,GAAG,CAAA;AAAA,EACnC,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"middleware-edge.js","sourcesContent":["/**\n * D.3 — `RenderedResponse` → `NextResponse` adapter.\n *\n * The host wrapper's *only* job on the outbound path: take the\n * transport-agnostic `RenderedResponse` Phase C's\n * `renderDecisionAsResponse` produces and translate it to a\n * `NextResponse`. Zero verdict decisions, zero engine I/O.\n *\n * Shared between the Node-runtime and Edge-runtime entries. The\n * branching here is identical in both — Next.js `NextResponse` has the\n * same API surface across runtimes; only the underlying response\n * primitive differs (Node http.ServerResponse vs Edge `Response`).\n *\n * Architectural pins per architect § 4.3 / § 4.4:\n *\n * 1. **Verdict-cookie format is contract.** Sites-1's Sonner toast\n * depends on `__checkpoint_verdict=%7B%22verdict%22%3A%22<v>%22...\n * %7D` (single URL-encoded JSON). Byte-format pinned by adapt.test.\n *\n * 2. **HTML-accepting clients → `/blocked` rewrite at status 200**\n * (so the page renders with the verdict cookie set; Sonner picks\n * up the cookie and shows the toast). Non-HTML clients → JSON 4xx.\n *\n * 3. **`X-Checkpoint-Engine` carries `result.engineInfo.name`** —\n * `checkpoint-engine-wasm` after Phase D ships. Brian's Sites-2\n * deviation note confirmed the `X-Checkpoint-*` prefix is canon.\n */\n\nimport { type NextRequest, NextResponse } from 'next/server';\n\nimport type { RenderedResponse } from '@kya-os/checkpoint-wasm-runtime/orchestrator';\nimport {\n VERDICT_COOKIE_NAME,\n BLOCKED_PATH,\n encodeVerdictCookie,\n acceptsHtml,\n classifyResponseShape,\n} from '@kya-os/checkpoint-shared';\n\n/**\n * Convert the engine's transport-agnostic `RenderedResponse` into a\n * `NextResponse`. Sites-1's Playwright suite is the regression gate;\n * any drift here is caught downstream.\n */\nexport function adaptToNextResponse(rendered: RenderedResponse, req: NextRequest): NextResponse {\n const clientAcceptsHtml = acceptsHtml(req.headers);\n const verdictCookie = encodeVerdictCookie(rendered);\n const shape = classifyResponseShape(rendered, clientAcceptsHtml);\n\n switch (shape) {\n case 'pass-through': {\n // Permit OR Observe-mode any-verdict.\n const res = NextResponse.next();\n applyHeaders(res, rendered.headers);\n setVerdictCookie(res, verdictCookie);\n return res;\n }\n\n case 'redirect': {\n // Decision::Redirect → 302 + Location.\n const target = new URL(rendered.headers.Location!);\n const res = NextResponse.redirect(target);\n applyHeaders(res, rendered.headers);\n setVerdictCookie(res, verdictCookie);\n return res;\n }\n\n case 'html-block': {\n // Sites-1 contract: HTML clients (browsers) need a renderable page\n // to show the rejection UI. The verdict cookie carries the reason;\n // the /blocked route reads it and renders the toast.\n const blockedUrl = new URL(BLOCKED_PATH, req.url);\n const res = NextResponse.rewrite(blockedUrl, { status: 200 });\n applyHeaders(res, rendered.headers);\n setVerdictCookie(res, verdictCookie);\n return res;\n }\n\n case 'json-block': {\n // The orchestrator's RenderedResponse already supplies the correct\n // status (401/403/422/...); we just need to materialise the body.\n // application/problem+json (Instruct) uses the Content-Type from\n // rendered.headers; defaults to application/json for everything else.\n const body = rendered.body ?? {};\n const res = NextResponse.json(body, { status: rendered.status as number });\n applyHeaders(res, rendered.headers);\n setVerdictCookie(res, verdictCookie);\n return res;\n }\n }\n}\n\n// -----------------------------------------------------------------------------\n// Helpers — Next.js-specific glue. The framework-agnostic primitives\n// (encodeVerdictCookie, acceptsHtml, classifyResponseShape,\n// VERDICT_COOKIE_NAME, BLOCKED_PATH) live in `@kya-os/checkpoint-shared`\n// so checkpoint-express + future host wrappers produce byte-identical\n// cookies and route HTML/JSON branching the same way.\n// -----------------------------------------------------------------------------\n\nfunction setVerdictCookie(res: NextResponse, value: string): void {\n // Path / SameSite / HttpOnly chosen for the Sonner-bridge use case:\n // path=/ so any route can read it, SameSite=Lax so first-party\n // navigations carry it, HttpOnly=false so the client-side toast JS\n // can read it (it's verdict UX, not a session token).\n res.cookies.set({\n name: VERDICT_COOKIE_NAME,\n value,\n path: '/',\n sameSite: 'lax',\n httpOnly: false,\n });\n}\n\nfunction applyHeaders(res: NextResponse, headers: Record<string, string>): void {\n // NextResponse.next() / rewrite() / json() return responses with\n // some default headers; orchestrator headers (X-Checkpoint-*, Location)\n // override. We don't strip pre-existing headers — only set new ones.\n for (const [key, value] of Object.entries(headers)) {\n res.headers.set(key, value);\n }\n}\n","/**\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; fall back to\n * `x-forwarded-for` first IP).\n */\n\nimport type { NextRequest } from 'next/server';\n\nimport type { IncomingHttpLike } from '@kya-os/checkpoint-wasm-runtime/orchestrator';\n\n/**\n * Translate a Next.js `NextRequest` into the orchestrator's\n * `IncomingHttpLike` shape.\n *\n * The body is passed through as-is — the orchestrator's\n * `buildAgentRequest` decides whether to parse JSON (looking for an\n * MCP-I `_meta.proof.jws` envelope) or treat the request as PlainHttp.\n * On Next.js middleware the body is typically not pre-parsed; consumers\n * who want to inspect the body for routing decisions should `await\n * req.json()` themselves and pass the parsed result via a second\n * `verifyRequest` call (not common).\n */\nexport function nextRequestToHttpLike(req: NextRequest): IncomingHttpLike {\n const url = new URL(req.url);\n return {\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 // NextRequest.body is a ReadableStream; we don't drain it here.\n // The orchestrator routes to PlainHttp when body is falsy, which\n // is the right call for streaming middlewares that don't want to\n // buffer the request body just to detect agents.\n body: null,\n remoteAddress: extractRemoteAddress(req),\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/**\n * Pull the originating client IP, preferring `x-forwarded-for`'s first\n * entry over `NextRequest.ip` (the latter is only populated on Vercel-\n * hosted deployments and is missing on self-hosted Next.js + nginx /\n * Fly.io / docker-compose surfaces). The `x-forwarded-for` first IP is\n * the closest the request has come to a load balancer's \"trust this is\n * the real client\" attestation — same convention as nginx, Caddy,\n * Cloudflare.\n */\nfunction extractRemoteAddress(req: NextRequest): string | undefined {\n const xff = req.headers.get('x-forwarded-for');\n if (xff) {\n const first = xff.split(',')[0]?.trim();\n if (first) return first;\n }\n // `req.ip` is typed but may be undefined off-Vercel.\n // Use `unknown` cast to avoid the type-narrowing optimism.\n const maybeIp = (req as unknown as { ip?: string }).ip;\n return maybeIp;\n}\n","/**\n * D.1 + D.3 — Node-runtime Next.js middleware entry.\n *\n * The host wrapper that composes Phase B adapters + Phase C\n * `verifyRequest` (sync engine) + Phase D translate/adapt into the\n * `withCheckpoint(config)` factory. Mounted under Vercel Node-runtime\n * serverless functions and long-lived Node servers.\n *\n * For Vercel Edge runtime (the Next.js middleware default), customers\n * import from `./edge` or `@kya-os/checkpoint-nextjs/edge` — that\n * variant uses `verifyRequestEdge` (async-init) and is otherwise\n * structurally identical. Both share `translate.ts` + `adapt.ts`.\n *\n * **Public API contract (architect § 4.1 — preserved):**\n *\n * - `withCheckpoint(config)` — factory returning the middleware.\n * - `CheckpointConfig` — the config shape; new fields are additive.\n *\n * Internal implementation gutted, external contract held. Sites-1's\n * Playwright suite is the regression gate.\n */\n\nimport { type NextRequest, type NextResponse } from 'next/server';\n\nimport {\n renderDecisionAsResponse,\n verifyRequest,\n} from '@kya-os/checkpoint-wasm-runtime/orchestrator';\nimport {\n makeDidResolver,\n makePolicyEvaluator,\n makeReputationOracle,\n makeStatusListCache,\n makeSystemClock,\n type DidResolverAdapter,\n type PolicyEvaluatorAdapter,\n type ReputationOracleAdapter,\n type StatusListCacheAdapter,\n} from '@kya-os/checkpoint-wasm-runtime/adapters';\nimport type { EnforcementMode, VerifyResult } from '@kya-os/checkpoint-wasm-runtime/engine';\n\nimport { adaptToNextResponse } from './adapt';\nimport { nextRequestToHttpLike } from './translate';\n\n/**\n * Configuration for `withCheckpoint`.\n *\n * The new minimal shape Phase D's middleware needs. Legacy\n * `AgentShieldMiddlewareConfig` (from `./api-middleware`) remains\n * exported during the deprecation window — see D.4 cutover.\n */\nexport interface CheckpointConfig {\n /**\n * Tenant identifier — typically the customer's dashboard hostname\n * (e.g. `acme.checkpoint.example`). The PolicyEvaluator uses this\n * to look up tenant policy from the dashboard.\n */\n tenantHost: string;\n\n /**\n * `'enforce'` (default) blocks; `'observe'` passes everything\n * through with `X-Checkpoint-Would-Have-Been` headers. Per Phase 0.2.\n */\n enforcementMode?: EnforcementMode;\n\n /**\n * Argus reputation oracle base URL. Omit to use the trust-by-default\n * baseline (reputation defaults to 1.0; orchestrator logs a one-shot\n * warning at first request).\n */\n argusUrl?: string;\n\n /**\n * Dashboard base URL for the PolicyEvaluator to fetch tenant policy\n * from. Omit to use the open-by-default tenant policy.\n */\n dashboardUrl?: string;\n\n /**\n * Returned to the PolicyEvaluator for anonymous requests (no agent\n * DID). Default 1.0 (trust-by-default).\n */\n reputationBaseline?: number;\n\n /**\n * Pre-built adapter instances. Production deployments use the\n * factory-built defaults from `@kya-os/checkpoint-wasm-runtime/adapters`;\n * tests use stubs. The factory composes any provided overrides over\n * defaults — partial overrides are supported.\n */\n adapters?: Partial<{\n didResolver: DidResolverAdapter;\n statusListCache: StatusListCacheAdapter;\n reputationOracle: ReputationOracleAdapter;\n policyEvaluator: PolicyEvaluatorAdapter;\n }>;\n\n /**\n * Optional callback for the post-verdict path — fires after every\n * verification, regardless of permit/block, with the full\n * `VerifyResult`. Use for logging, dashboards, telemetry. Errors\n * thrown here are swallowed so user code can't break the middleware\n * response.\n */\n onResult?: (result: VerifyResult, req: NextRequest) => void | Promise<void>;\n}\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, calls\n * `verifyRequest`, and translates the verdict to `NextResponse`. No\n * verification logic lives in this file.\n */\nexport function withCheckpoint(\n config: CheckpointConfig\n): (req: NextRequest) => Promise<NextResponse> {\n const opts = buildVerifyOpts(config);\n return async function checkpointMiddleware(req: NextRequest): Promise<NextResponse> {\n const httpLike = nextRequestToHttpLike(req);\n const result = await verifyRequest(httpLike, opts);\n await dispatchOnResult(config, result, req);\n const rendered = renderDecisionAsResponse(result);\n return adaptToNextResponse(rendered, req);\n };\n}\n\n/**\n * Compose adapter defaults with caller-supplied overrides. Factored\n * out so the Edge entry (which uses the same composition) can reuse\n * the shape.\n */\nfunction buildVerifyOpts(config: CheckpointConfig) {\n const overrides = config.adapters ?? {};\n return {\n didResolver: overrides.didResolver ?? makeDidResolver(),\n statusListCache: overrides.statusListCache ?? makeStatusListCache(),\n reputationOracle:\n overrides.reputationOracle ?? makeReputationOracle({ argusUrl: config.argusUrl }),\n policyEvaluator:\n overrides.policyEvaluator ?? makePolicyEvaluator({ dashboardUrl: config.dashboardUrl }),\n clock: makeSystemClock(),\n tenantHost: config.tenantHost,\n enforcementMode: config.enforcementMode ?? 'enforce',\n reputationBaseline: config.reputationBaseline,\n argusUrl: config.argusUrl,\n };\n}\n\nasync function dispatchOnResult(\n config: CheckpointConfig,\n result: VerifyResult,\n req: NextRequest\n): Promise<void> {\n if (!config.onResult) return;\n try {\n await config.onResult(result, req);\n } catch {\n // Swallow — onResult is observability, not verdict-critical.\n // Verdict already computed; let the response proceed.\n }\n}\n\n// Re-export the shared opts builder for the Edge entry. Internal seam;\n// not part of the public surface.\nexport { buildVerifyOpts as _buildVerifyOpts };\n","/**\n * D.3 — Edge-runtime Next.js middleware entry.\n *\n * The async-init equivalent of `./middleware-node.ts`. Mounted under\n * Vercel Edge runtime (the Next.js middleware default) and Cloudflare\n * Workers when Next.js targets the Edge.\n *\n * Differs from the Node entry in exactly two places:\n *\n * 1. Imports `verifyRequestEdge` + `initEngineEdge` from the\n * orchestrator's `./edge` subpath (Edge-WASM-2 from D.1.5)\n * instead of `verifyRequest` from the Node orchestrator entry.\n * 2. Calls `initEngineEdge()` once at module load (eagerly, before\n * any request hits the middleware) so the first request's cold-\n * boot latency is amortised onto deploy time. Subsequent calls\n * to `initEngineEdge` are idempotent.\n *\n * Adapter composition (`buildVerifyOpts`), translate.ts, adapt.ts,\n * verdict-cookie format, X-Checkpoint-* headers — all shared with\n * the Node entry. Cross-runtime parity verified by Phase F's CI gate\n * (D.5 ships the Next.js-specific half).\n *\n * **Public API contract — preserved:** `withCheckpoint(config)`,\n * `CheckpointConfig`. Same exports as Node, same signatures.\n */\n\nimport { type NextRequest, type NextResponse } from 'next/server';\n\nimport {\n initEngineEdge,\n renderDecisionAsResponse,\n verifyRequestEdge,\n} from '@kya-os/checkpoint-wasm-runtime/orchestrator/edge';\nimport type { VerifyResult } from '@kya-os/checkpoint-wasm-runtime/engine';\n\nimport { adaptToNextResponse } from './adapt';\nimport { _buildVerifyOpts, type CheckpointConfig } from './middleware-node';\nimport { nextRequestToHttpLike } from './translate';\n\n// Re-export the config type so consumers can `import type` from the\n// edge entry without a second import line.\nexport type { CheckpointConfig } from './middleware-node';\n\n/**\n * Build the Checkpoint middleware for Edge runtime. Returns a function\n * `(req) => Promise<NextResponse>` suitable for\n * `export default withCheckpoint({...})` in `middleware.ts` under\n * `export const config = { runtime: 'edge' }`.\n *\n * Idempotent eager init: the first call to `withCheckpoint` kicks off\n * `initEngineEdge()` so the wasm artifact loads while the rest of the\n * factory closure is being built. The first request awaits the same\n * promise; subsequent requests resolve sync.\n */\nexport function withCheckpoint(\n config: CheckpointConfig\n): (req: NextRequest) => Promise<NextResponse> {\n // Eager init — fire-and-forget. The first request will await the\n // same promise via the orchestrator's lazy init path. Eager-init\n // hosts that want to await the init explicitly can call\n // `initEngineEdge()` themselves at startup.\n void initEngineEdge();\n\n const opts = _buildVerifyOpts(config);\n return async function checkpointMiddlewareEdge(req: NextRequest): Promise<NextResponse> {\n const httpLike = nextRequestToHttpLike(req);\n const result = await verifyRequestEdge(httpLike, opts);\n await dispatchOnResult(config, result, req);\n const rendered = renderDecisionAsResponse(result);\n return adaptToNextResponse(rendered, req);\n };\n}\n\nasync function dispatchOnResult(\n config: CheckpointConfig,\n result: VerifyResult,\n req: NextRequest\n): Promise<void> {\n if (!config.onResult) return;\n try {\n await config.onResult(result, req);\n } catch {\n // Swallow — onResult is observability, not verdict-critical.\n }\n}\n\n// Re-export `initEngineEdge` so eager-init hosts that want to warm the\n// wasm load at process startup can do so without a second import line.\nexport { initEngineEdge };\n"]}