@kya-os/checkpoint-nextjs 1.11.0 → 1.12.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.
- package/CHANGELOG.md +16 -0
- package/README.md +16 -8
- package/dist/{adapt-BdQ9R7Iw.mjs → adapt-BvqYgrAk.mjs} +2 -2
- package/dist/{adapt-BdQ9R7Iw.mjs.map → adapt-BvqYgrAk.mjs.map} +1 -1
- package/dist/{adapt-CCSKGjVH.js → adapt-DUEIfZnx.js} +1 -1
- package/dist/{api-middleware-BWjokNis.d.mts → api-middleware-BtsYJU5u.d.mts} +2 -2
- package/dist/{api-middleware-BWjokNis.d.mts.map → api-middleware-BtsYJU5u.d.mts.map} +1 -1
- package/dist/{api-middleware-C-ngFX_8.mjs → api-middleware-DvmkJ_Li.mjs} +4 -4
- package/dist/{api-middleware-C-ngFX_8.mjs.map → api-middleware-DvmkJ_Li.mjs.map} +1 -1
- package/dist/{api-middleware-Bf3xmM9W.js → api-middleware-beNlXd5P.js} +3 -3
- package/dist/api-middleware.d.mts +1 -1
- package/dist/api-middleware.js +1 -1
- package/dist/api-middleware.mjs +1 -1
- package/dist/cedar-wasm.d.mts +1 -1
- package/dist/cedar-wasm.d.ts +1 -1
- package/dist/cedar-wasm.js +1 -1
- package/dist/cedar-wasm.mjs +1 -1
- package/dist/cedar-wasm.mjs.map +1 -1
- package/dist/config-D7h2w_it.d.mts +89 -0
- package/dist/config-D7h2w_it.d.mts.map +1 -0
- package/dist/config-DkXvl4nH.d.ts +89 -0
- package/dist/config-DkXvl4nH.d.ts.map +1 -0
- package/dist/engine-wasm.d.mts +1 -1
- package/dist/engine-wasm.d.ts +1 -1
- package/dist/engine-wasm.js +1 -1
- package/dist/engine-wasm.mjs +1 -1
- package/dist/engine-wasm.mjs.map +1 -1
- package/dist/index-edge.d.mts +4 -4
- package/dist/index-edge.d.ts +3 -3
- package/dist/index-edge.js +2 -2
- package/dist/index-edge.mjs +2 -2
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/middleware-bundler.d.mts +1 -1
- package/dist/middleware-bundler.d.ts +1 -1
- package/dist/middleware-bundler.js +3 -3
- package/dist/middleware-bundler.mjs +3 -3
- package/dist/middleware-bundler.mjs.map +1 -1
- package/dist/middleware-core-B1GuspOY.js +169 -0
- package/dist/{middleware-core-Bol44X9C.d.ts → middleware-core-BmW2kH8J.d.ts} +4 -7
- package/dist/middleware-core-BmW2kH8J.d.ts.map +1 -0
- package/dist/{middleware-core-DycsbHUd.d.mts → middleware-core-CnPUoD2v.d.mts} +4 -7
- package/dist/middleware-core-CnPUoD2v.d.mts.map +1 -0
- package/dist/middleware-core-WZeMSRqx.mjs +159 -0
- package/dist/middleware-core-WZeMSRqx.mjs.map +1 -0
- package/dist/middleware-edge.d.mts +1 -1
- package/dist/middleware-edge.d.mts.map +1 -1
- package/dist/middleware-edge.d.ts +1 -1
- package/dist/middleware-edge.d.ts.map +1 -1
- package/dist/middleware-edge.js +21 -35
- package/dist/middleware-edge.mjs +21 -35
- package/dist/middleware-edge.mjs.map +1 -1
- package/dist/middleware-node-context-BvqrL2Ra.mjs +16 -0
- package/dist/middleware-node-context-BvqrL2Ra.mjs.map +1 -0
- package/dist/middleware-node-context-TRMTgp3y.js +20 -0
- package/dist/middleware-node.d.mts +2 -2
- package/dist/middleware-node.d.ts +2 -2
- package/dist/middleware-node.js +3 -3
- package/dist/middleware-node.mjs +3 -3
- package/dist/middleware-node.mjs.map +1 -1
- package/dist/{public-api-CYsHrTQI.d.ts → public-api-Cw7Zj290.d.ts} +2 -2
- package/dist/public-api-DgCw1uo6.d.mts +5 -0
- package/package.json +3 -3
- package/dist/config-CPP1RV0f.d.mts +0 -291
- package/dist/config-CPP1RV0f.d.mts.map +0 -1
- package/dist/config-DVgOFxJs.d.ts +0 -291
- package/dist/config-DVgOFxJs.d.ts.map +0 -1
- package/dist/middleware-core-B0jf5_Hm.mjs +0 -264
- package/dist/middleware-core-B0jf5_Hm.mjs.map +0 -1
- package/dist/middleware-core-Bol44X9C.d.ts.map +0 -1
- package/dist/middleware-core-CMc-2QkU.js +0 -274
- package/dist/middleware-core-DycsbHUd.d.mts.map +0 -1
- package/dist/middleware-node-context-591KsiYg.js +0 -39
- package/dist/middleware-node-context-D_ZyUEcA.mjs +0 -35
- package/dist/middleware-node-context-D_ZyUEcA.mjs.map +0 -1
- package/dist/public-api-DkG7pRE0.d.mts +0 -5
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
# @kya-os/checkpoint-nextjs
|
|
4
4
|
|
|
5
|
+
## 1.12.0 - 2026-10-22
|
|
6
|
+
|
|
7
|
+
### Breaking changes
|
|
8
|
+
|
|
9
|
+
- Removed: `adapters.didResolver` and `adapters.statusListCache`. Use `adapters.fetch` to replace the transport DID documents and status lists are fetched with; it must connect only to a vetted public address, refuse redirects, cap the body and enforce a deadline. (#6600)
|
|
10
|
+
- Removed: `adapters.policyEvaluator` and `reputationBaseline` from `CheckpointConfig`. A config that still sets them has them ignored: no TS code produces a Block, and a tenant's rules are Cedar. (#6678)
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- A status list that cannot be fetched or verified is answered `503 kyaos/status-pending` with `Retry-After: 1`. (#6600)
|
|
15
|
+
- `withCheckpoint` runs wasm-runtime's shared request pipeline (`./pipeline`), so it needs a wasm-runtime release that has it. `CheckpointConfig` extends wasm-runtime's `CheckpointHostConfig`; its fields are unchanged. With `debug` on, an engine that fails to load is logged once instead of twice. (#6650)
|
|
16
|
+
|
|
17
|
+
### Deprecated
|
|
18
|
+
|
|
19
|
+
- `tenantHost` is optional; it is no longer used and will be removed. (#6678)
|
|
20
|
+
|
|
5
21
|
## 1.11.0 - 2026-10-21
|
|
6
22
|
|
|
7
23
|
### Added
|
package/README.md
CHANGED
|
@@ -28,7 +28,6 @@ import { withCheckpoint } from '@kya-os/checkpoint-nextjs';
|
|
|
28
28
|
export default withCheckpoint({
|
|
29
29
|
// Honor platform headers only inside Vercel's managed runtime.
|
|
30
30
|
clientIpPolicy: { platform: 'vercel' },
|
|
31
|
-
tenantHost: 'demo.example',
|
|
32
31
|
engineWasmModule,
|
|
33
32
|
});
|
|
34
33
|
```
|
|
@@ -70,7 +69,6 @@ import { withCheckpoint } from '@kya-os/checkpoint-nextjs';
|
|
|
70
69
|
|
|
71
70
|
export default withCheckpoint({
|
|
72
71
|
clientIpPolicy: { platform: 'vercel' },
|
|
73
|
-
tenantHost: 'demo.example',
|
|
74
72
|
engineWasmModule,
|
|
75
73
|
});
|
|
76
74
|
|
|
@@ -92,7 +90,6 @@ import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';
|
|
|
92
90
|
import { withCheckpoint } from '@kya-os/checkpoint-nextjs';
|
|
93
91
|
|
|
94
92
|
export default withCheckpoint({
|
|
95
|
-
tenantHost: 'demo.example',
|
|
96
93
|
projectId: process.env.CHECKPOINT_PROJECT_ID,
|
|
97
94
|
engineWasmModule,
|
|
98
95
|
});
|
|
@@ -156,7 +153,7 @@ A request can start work that outlives its response: a refresh of the engine's v
|
|
|
156
153
|
If you wrap `withCheckpoint` in your own middleware, pass the event through:
|
|
157
154
|
|
|
158
155
|
```ts
|
|
159
|
-
const checkpoint = withCheckpoint({
|
|
156
|
+
const checkpoint = withCheckpoint({});
|
|
160
157
|
|
|
161
158
|
export default function middleware(request: NextRequest, event: NextFetchEvent) {
|
|
162
159
|
return checkpoint(request, event);
|
|
@@ -272,10 +269,11 @@ export default withCheckpointApi({
|
|
|
272
269
|
});
|
|
273
270
|
```
|
|
274
271
|
|
|
275
|
-
The local-engine shape (`withCheckpoint`) takes a `CheckpointConfig` instead
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
272
|
+
The local-engine shape (`withCheckpoint`) takes a `CheckpointConfig` instead,
|
|
273
|
+
every field optional: `enforcementMode` (`'enforce'` | `'observe'`), `apiKey`
|
|
274
|
+
(enables dashboard reporting), `projectId` (enforces your deployed dashboard
|
|
275
|
+
policy in-process), and more. `tenantHost` is deprecated: it is no longer used
|
|
276
|
+
and will be removed. See the
|
|
279
277
|
[middleware docs](https://kya.vouched.id/docs/enforce/middleware) for the
|
|
280
278
|
full option tables for both shapes.
|
|
281
279
|
|
|
@@ -291,6 +289,16 @@ process memory and, when a `PolicyCacheAdapter` is configured, in that adapter
|
|
|
291
289
|
or a body that is not a policy-API response is treated like an outage:
|
|
292
290
|
last-good is served for up to 24h.
|
|
293
291
|
|
|
292
|
+
### DID documents and status lists
|
|
293
|
+
|
|
294
|
+
The engine names every DID document and status list a request needs, after its own trust checks, and `withCheckpoint` fetches only what it names, before the request is decided.
|
|
295
|
+
A status list that cannot be fetched or verified is answered `503` with `Retry-After: 1` (`kyaos/status-pending`); a request signer's DID document that cannot be fetched is refused (`401 kyaos/did-unresolvable`).
|
|
296
|
+
|
|
297
|
+
On the Node.js runtime each fetch connects only to a public address its own DNS lookup checked, refuses redirects, caps the body and has a deadline.
|
|
298
|
+
The Edge runtime has no connect hook, so there the same rules apply except the address check, and the platform's egress rules are what keep a fetch off private addresses.
|
|
299
|
+
`adapters.fetch` replaces the transport, and the connect-time address check becomes your job: a custom `fetch` must connect only to a vetted public address (check every address DNS returns, and never re-resolve), refuse redirects, cap the body and enforce a deadline.
|
|
300
|
+
`safeGet`, `makeSafeLookup` and `isBlockedIpAddress` from `@kya-os/checkpoint-wasm-runtime/adapters` are the pieces the default uses.
|
|
301
|
+
|
|
294
302
|
`withCheckpoint` itself never throws, because a Next.js middleware module that fails to load can let requests through unchecked.
|
|
295
303
|
An invalid configuration (for example a missing `engineWasmModule` on the Edge runtime) and an engine that fails to load (for example an unreadable `.wasm`) are logged with a `[checkpoint]` prefix and every request is answered `503`.
|
|
296
304
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { BLOCKED_PATH, VERDICT_COOKIE_NAME, acceptsHtml, classifyResponseShape, encodeVerdictCookie } from "@kya-os/checkpoint-shared/host-adapter";
|
|
2
1
|
import { NextResponse } from "next/server.js";
|
|
2
|
+
import { BLOCKED_PATH, VERDICT_COOKIE_NAME, acceptsHtml, classifyResponseShape, encodeVerdictCookie } from "@kya-os/checkpoint-shared/host-adapter";
|
|
3
3
|
import { FAIL_CLOSED_BODY, FAIL_CLOSED_HEADERS, FAIL_CLOSED_STATUS } from "@kya-os/checkpoint-shared/policy/enforcement";
|
|
4
4
|
|
|
5
5
|
//#region src/adapt.ts
|
|
@@ -94,4 +94,4 @@ function applyHeaders(res, rendered) {
|
|
|
94
94
|
|
|
95
95
|
//#endregion
|
|
96
96
|
export { failClosedResponse as n, adaptToNextResponse as t };
|
|
97
|
-
//# sourceMappingURL=adapt-
|
|
97
|
+
//# sourceMappingURL=adapt-BvqYgrAk.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapt-
|
|
1
|
+
{"version":3,"file":"adapt-BvqYgrAk.mjs","names":[],"sources":["../src/adapt.ts"],"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.js';\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/host-adapter';\nimport {\n FAIL_CLOSED_BODY,\n FAIL_CLOSED_HEADERS,\n FAIL_CLOSED_STATUS,\n} from '@kya-os/checkpoint-shared/policy/enforcement';\n\n/**\n * 503 (Retry-After, no-store) for an engine/pipeline fault. Never a 500 and\n * never a pass-through: an unverifiable request is not allowed.\n */\nexport function failClosedResponse(): NextResponse {\n return NextResponse.json(FAIL_CLOSED_BODY, {\n status: FAIL_CLOSED_STATUS,\n headers: FAIL_CLOSED_HEADERS,\n });\n}\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);\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);\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);\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);\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, rendered: RenderedResponse): 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(rendered.headers)) {\n res.headers.set(key, value);\n }\n for (const [key, value] of rendered.headerEntries ?? []) {\n res.headers.append(key, value);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,qBAAmC;CACjD,OAAO,aAAa,KAAK,kBAAkB;EACzC,QAAQ;EACR,SAAS;CACX,CAAC;AACH;;;;;;AAOA,SAAgB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
|
|
1
|
-
let _kya_os_checkpoint_shared_host_adapter = require("@kya-os/checkpoint-shared/host-adapter");
|
|
2
1
|
let next_server_js = require("next/server.js");
|
|
2
|
+
let _kya_os_checkpoint_shared_host_adapter = require("@kya-os/checkpoint-shared/host-adapter");
|
|
3
3
|
let _kya_os_checkpoint_shared_policy_enforcement = require("@kya-os/checkpoint-shared/policy/enforcement");
|
|
4
4
|
|
|
5
5
|
//#region src/adapt.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { s as EnforcementDecision } from "./api-client-JHOrRUA_.mjs";
|
|
2
|
-
import { ChallengeEnvelopeMode } from "@kya-os/checkpoint-shared/host-adapter";
|
|
3
2
|
import { NextRequest, NextResponse } from "next/server.js";
|
|
3
|
+
import { ChallengeEnvelopeMode } from "@kya-os/checkpoint-shared/host-adapter";
|
|
4
4
|
import { ClientIpTrustPolicy } from "@kya-os/checkpoint-shared/client-ip";
|
|
5
5
|
//#region src/api-middleware.d.ts
|
|
6
6
|
/**
|
|
@@ -128,4 +128,4 @@ interface CheckpointApiMiddlewareConfig {
|
|
|
128
128
|
declare function withCheckpointApi(config?: CheckpointApiMiddlewareConfig): (request: NextRequest) => Promise<NextResponse>;
|
|
129
129
|
//#endregion
|
|
130
130
|
export { withCheckpointApi as n, CheckpointApiMiddlewareConfig as t };
|
|
131
|
-
//# sourceMappingURL=api-middleware-
|
|
131
|
+
//# sourceMappingURL=api-middleware-BtsYJU5u.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-middleware-
|
|
1
|
+
{"version":3,"file":"api-middleware-BtsYJU5u.d.mts","names":[],"sources":["../src/api-middleware.ts"],"mappings":";;;;;;;;UA4EiB;;EAEf,iBAAiB;;EAEjB;;;;;;;EAOA;;;;;;;;EAQA;;;;;;EAMA;;;;;;;;EASA;;;;;EAMA;;;;;;;;;;;;;EAcA;;;;;;;;;;EAWA,0BAA0B;;;;;;EAO1B;IACE;IACA;IACA,UAAU;;;;;;EAOZ;;;;EAKA;;;;EAKA,mBAAmB,SAAS,aAAa,UAAU,+BAA+B;;;;EAKlF,yBACE,SAAS,aACT,UAAU,wBACP,eAAe,QAAQ;;;;;;;;;EAU5B;;;;;;EAOA;;;;;;;;;;;;;;;;iBA2Mc,kBAAkB,SAAQ,iCA6CP,SAAS,gBAAc,QAAQ"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { n as failClosedResponse } from "./adapt-
|
|
1
|
+
import { n as failClosedResponse } from "./adapt-BvqYgrAk.mjs";
|
|
2
2
|
import { r as safeHostname, t as getClientIp } from "./utils-Cnwg0VrY.mjs";
|
|
3
3
|
import { getCheckpointApiClient } from "./api-client.mjs";
|
|
4
|
-
import { selectBodyReadable200 } from "@kya-os/checkpoint-shared/host-adapter";
|
|
5
4
|
import { waitUntil } from "@vercel/functions";
|
|
6
5
|
import { NextResponse } from "next/server.js";
|
|
6
|
+
import { selectBodyReadable200 } from "@kya-os/checkpoint-shared/host-adapter";
|
|
7
7
|
import { matchPath } from "@kya-os/checkpoint-shared/policy/enforcement";
|
|
8
8
|
import { requestPresentedCredential } from "@kya-os/checkpoint-shared/kya-http";
|
|
9
9
|
|
|
@@ -177,7 +177,7 @@ function sdkSelfIdentification() {
|
|
|
177
177
|
const runtime = typeof process !== "undefined" && process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
|
|
178
178
|
return {
|
|
179
179
|
name: SDK_NAME,
|
|
180
|
-
version: "1.
|
|
180
|
+
version: "1.12.0",
|
|
181
181
|
runtime
|
|
182
182
|
};
|
|
183
183
|
}
|
|
@@ -384,4 +384,4 @@ function failOpenResponse() {
|
|
|
384
384
|
|
|
385
385
|
//#endregion
|
|
386
386
|
export { withCheckpointApi as t };
|
|
387
|
-
//# sourceMappingURL=api-middleware-
|
|
387
|
+
//# sourceMappingURL=api-middleware-DvmkJ_Li.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-middleware-C-ngFX_8.mjs","names":[],"sources":["../src/responses/agent-instruction.ts","../src/api-middleware.ts"],"sourcesContent":["/**\n * Agent Instruction Response Builder (Next.js)\n *\n * Tells an AI agent where to send its user to complete consent / connect,\n * via a machine-parseable Link header + JSON body.\n *\n * **Dual envelope.** By default this is a 401 instruction response. AI-agent fetchers (Claude-User\n * WebFetch, ChatGPT) collapse 4xx responses and never surface the body to\n * the LLM, so the instruction is invisible. When the caller is a\n * cooperative, self-identifying agent (selected upstream via\n * `serveBodyReadable200`), pass `{ bodyReadable200: true }` to serve the\n * SAME body at HTTP 200 with NO `WWW-Authenticate` (a 200 + WWW-Authenticate\n * is reinterpreted as 401 by some fetchers); the consent URL stays in the\n * body + the `KYA-Auth-Url`/`Link` hint headers. This also realigns\n * TS-instruct (was 401-only) with .NET-instruct (200).\n *\n * Envelope selection is a cooperative-UX bridge, NOT an access control —\n * the authoritative consent target is the body `user_action_required.url`;\n * the `KYA-Auth-Url`/`Link` headers are unsigned hints.\n *\n * This is the in-app counterpart to the Cloudflare Gateway's builder at\n * `apps/web/workers/gateway/src/responses/agent-instruction.ts`. The body\n * is kept in sync so LLM and MCP clients see identical behavior whether a\n * site is protected by the gateway or by the Next.js middleware.\n *\n * Implements RFC 8288 Link discovery. It deliberately emits no\n * `WWW-Authenticate`; only a registered policy Challenge may emit the canonical\n * Delegation authentication fields.\n *\n * @see ../../apps/web/workers/gateway/src/responses/agent-instruction.ts\n */\n\nimport { NextResponse, type NextRequest } from 'next/server.js';\nimport type { EnforcementDecision } from '../api-client';\nimport { safeHostname } from '../utils';\n\nconst MCP_I_DOCS_URL = 'https://kya.vouched.id/docs/enforce/kya-os-enforcement';\nconst DEFAULT_CONNECT_PATH = '/connect';\n\n/** Options controlling which envelope `buildAgentInstructionResponse` emits. */\nexport interface AgentInstructionResponseOptions {\n /**\n * When true, serve the body-readable HTTP 200 fetcher envelope (same\n * body, no `WWW-Authenticate`) instead of the 401. The caller\n * decides this via the shared `serveBodyReadable200` predicate when its\n * challenge-emission mode is `negotiated`. Defaults to false.\n */\n bodyReadable200?: boolean;\n}\n\n/**\n * Build an \"agent must connect\" response for the Next.js middleware.\n *\n * The caller is responsible for deciding *when* to call this (typically when\n * `decision.action === 'redirect'` or `'instruct'`) and *which envelope* via\n * `options.bodyReadable200`. This helper only owns the response shape.\n */\nexport function buildAgentInstructionResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n redirectUrl: string | undefined,\n options?: AgentInstructionResponseOptions\n): NextResponse {\n // Resolve the target to an absolute URL against the incoming request so the\n // Link header is dereferenceable by strict clients (some LLM fetchers refuse\n // relative URIs in Link).\n const resolved = resolveUrl(redirectUrl ?? DEFAULT_CONNECT_PATH, request.url);\n\n // Match gateway's \"connect page\" branch: attach ?agent= for client-specific\n // install cards on the landing page.\n const agentName = decision.agentName || decision.agentType || 'unknown';\n if (!resolved.searchParams.has('agent')) {\n resolved.searchParams.set('agent', agentName.toLowerCase());\n }\n\n const authUrl = resolved.toString();\n const hostname = safeHostname(request.url);\n\n const body = {\n // Markdown-formatted so clients that render markdown (Claude Desktop,\n // ChatGPT web) surface the URL as a clickable link. Tone mirrors the\n // gateway response so messaging stays consistent across platforms.\n message:\n `I can't access ${hostname} yet — this site checks AI assistants at the front door.\\n\\n` +\n `**To give me access, open this link:**\\n` +\n `[Connect securely to ${hostname}](${authUrl})\\n\\n` +\n `It only takes a moment and you won't need to do it again. ` +\n `Once you're done, ask me to try again and I'll connect through the verified channel automatically.`,\n\n user_action_required: {\n action: `Connect securely to ${hostname}`,\n url: authUrl,\n reason: `${hostname} checks AI assistants before they connect. Open the link to give your assistant a verified key.`,\n },\n\n mcp_i: {\n version: '1.0' as const,\n action: 'authenticate' as const,\n authorization_url: authUrl,\n flow: {\n type: 'oauth2_delegation' as const,\n steps: [\n '1. Direct your user to the authorization_url',\n '2. User reviews requested scopes and grants consent',\n '3. Receive delegation credential (JWT)',\n '4. Include credential in KYA-Delegation header',\n '5. Retry this request with the proof',\n ],\n },\n retry_instructions: {\n header: 'KYA-Delegation' as const,\n format: 'JWT delegation credential from authorization flow',\n },\n documentation: MCP_I_DOCS_URL,\n },\n\n error: 'mcp_authentication_required',\n code: 'AGENT_REQUIRES_DELEGATION',\n\n detection: {\n agent_type: decision.agentType || 'ai_agent',\n agent_name: decision.agentName || 'Unknown Agent',\n confidence: decision.confidence,\n },\n };\n\n // Dual envelope: 200 body-readable for cooperative fetchers, else 401.\n // The body is identical across both. INSTRUCT is not a registered policy\n // Delegation challenge, so it must not advertise a fabricated auth scheme.\n const bodyReadable200 = options?.bodyReadable200 ?? false;\n const response = NextResponse.json(body, { status: bodyReadable200 ? 200 : 401 });\n\n // RFC 8288 discovery pointer + KYA-* hints. Present on BOTH envelopes —\n // these are unsigned hints; the authoritative target is the body\n // `user_action_required.url`. `rel=\"kya-authorize\"` matches the CF gateway.\n response.headers.set(\n 'Link',\n `<${authUrl}>; rel=\"kya-authorize\", <${MCP_I_DOCS_URL}>; rel=\"help\"`\n );\n response.headers.set('KYA-Auth-Required', 'true');\n response.headers.set('KYA-Auth-Url', authUrl);\n response.headers.set('KYA-Action', 'instruct');\n response.headers.set('KYA-Detected-Agent', agentName);\n response.headers.set('KYA-Confidence', decision.confidence.toString());\n response.headers.set('Cache-Control', 'no-store');\n\n return response;\n}\n\n/**\n * Resolve a URL that may be absolute or a same-origin path.\n * Falls back to `/connect` on the request origin if parsing fails.\n */\nfunction resolveUrl(target: string, baseUrl: string): URL {\n try {\n return new URL(target, baseUrl);\n } catch {\n return new URL(DEFAULT_CONNECT_PATH, baseUrl);\n }\n}\n","/**\n * API-based Checkpoint Middleware for Next.js\n *\n * This middleware uses the Checkpoint API for detection and enforcement,\n * instead of running detection locally. This approach:\n *\n * 1. Works reliably in Edge Runtime (no WASM loading issues)\n * 2. Ensures consistent detection across all platforms\n * 3. Applies centralized policies from the dashboard\n * 4. Supports deny lists, thresholds, and path rules\n *\n * @example\n * ```typescript\n * // middleware.ts\n * import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';\n *\n * export default withCheckpointApi({\n * apiKey: process.env.CHECKPOINT_API_KEY!,\n * // Optional overrides:\n * onBlock: 'redirect', // 'block' | 'redirect' | 'challenge'\n * redirectUrl: '/blocked',\n * skipPaths: ['/api/health', '/_next/*'],\n * });\n *\n * export const config = {\n * matcher: ['/((?!_next/static|favicon.ico).*)'],\n * };\n * ```\n */\n\nimport { NextRequest, NextResponse } from 'next/server.js';\nimport { matchPath } from '@kya-os/checkpoint-shared/policy/enforcement';\nimport { requestPresentedCredential } from '@kya-os/checkpoint-shared/kya-http';\nimport {\n selectBodyReadable200,\n type ChallengeEnvelopeMode,\n} from '@kya-os/checkpoint-shared/host-adapter';\nimport type { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared/client-ip';\nimport type { EngineInfo } from '@kya-os/checkpoint-shared';\nimport {\n CheckpointApiClient,\n getCheckpointApiClient,\n type EnforcementDecision,\n type LogDetectionInput,\n} from './api-client';\nimport { buildAgentInstructionResponse } from './responses/agent-instruction';\nimport { failClosedResponse } from './adapt';\nimport { getClientIp, safeHostname } from './utils';\n// A genuine hard dependency, not an optional one, despite forcing every\n// consumer (even non-Vercel ones) to install it (bestbrian review,\n// checkpoint#4460). Two reasons a dynamic/optional-peer import, which this\n// file used briefly, does NOT work here (Bugbot review, checkpoint#4657):\n// 1. This middleware explicitly targets Edge Runtime (see the module doc\n// comment). A `webpackIgnore`d variable-name `import()` is invisible\n// to the bundler on purpose — but Edge Runtime has no filesystem/module\n// resolution at request time, only what the bundler actually included.\n// An intentionally-unbundled import can never resolve there; `waitUntil`\n// would silently never register, reintroducing the exact lost-detection\n// bug this wrapper exists to prevent.\n// 2. It's unnecessary: `waitUntil()`'s own implementation\n// (`getContext().waitUntil?.(promise)`, where `getContext()` returns\n// `{}` off Vercel) already no-ops safely everywhere it isn't backed by\n// a real Vercel request context — Node, Edge, tests, wherever. There is\n// no failure mode to guard against with a fallback; the only real cost\n// of the hard dependency is a few extra KB installed on non-Vercel\n// consumers, which is the correct trade against actually breaking\n// detection logging on Vercel.\nimport { waitUntil } from '@vercel/functions';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Middleware configuration\n */\nexport interface CheckpointApiMiddlewareConfig {\n /** Explicit deployment/proxy trust profile for client-IP resolution. */\n clientIpPolicy?: ClientIpTrustPolicy;\n /** API key (or use CHECKPOINT_API_KEY env var) */\n apiKey?: string;\n /**\n * Gateway base URL. Override for staging or self-hosted deployments.\n * With `useEdge: false` the default becomes `https://kya.vouched.id`.\n *\n * @default 'https://detect.checkpoint-gateway.ai'\n */\n apiUrl?: string;\n /**\n * Use edge detection for lower latency (~30-50ms vs ~150ms) and better coverage.\n * Edge detection can identify non-JS clients (curl, Python, Claude Code WebFetch)\n * that the pixel cannot detect since they don't execute JavaScript.\n * Set to false to use the Vercel API instead.\n * @default true\n */\n useEdge?: boolean;\n /**\n * Request timeout in milliseconds for the gateway call.\n *\n * @default 5000\n */\n timeout?: number;\n\n /**\n * Action to take when an agent should be blocked\n * - 'block': Return 403 response\n * - 'redirect': Redirect to redirectUrl\n * - 'challenge': Show a challenge page (future)\n * Default: uses policy from dashboard\n */\n onBlock?: 'block' | 'redirect' | 'challenge';\n\n /**\n * URL to redirect to when blocking (if onBlock is 'redirect')\n * Default: uses redirectUrl from dashboard policy\n */\n redirectUrl?: string;\n\n /**\n * How the middleware handles a `redirect` / `instruct` action.\n *\n * - `'instruct'` (default): return HTTP 401 with a KYA-OS Link header + JSON\n * body pointing the agent at the redirect URL. LLMs surface the URL as a\n * clickable link for the user. Matches the Cloudflare Gateway contract.\n * - `'http'`: legacy behavior — return HTTP 302 with `Location`. Most LLM\n * fetchers won't follow the redirect, so this is only useful when your\n * traffic is real browsers.\n *\n * @default 'instruct'\n */\n redirectMode?: 'instruct' | 'http';\n\n /**\n * Challenge-emission envelope mode (draft-kya-http-02 §8.1 fetcher-200).\n * `negotiated` serves a body-readable HTTP 200 instruct response to\n * cooperative agents (so fetchers that drop 4xx bodies can read it),\n * keeping the spec 401 for everyone else. Defaults to `negotiated` (#3530).\n * A cooperative-UX bridge, NOT an access control.\n *\n * @default 'negotiated'\n */\n delegationChallengeMode?: ChallengeEnvelopeMode;\n\n /**\n * Customize the blocked response's status, message, and extra headers.\n *\n * @default { status: 403, message: 'Access denied' }\n */\n blockedResponse?: {\n status?: number;\n message?: string;\n headers?: Record<string, string>;\n };\n\n /**\n * Paths to skip (in addition to dashboard policy)\n * Supports glob patterns: '/api/*', '/_next/*'\n */\n skipPaths?: string[];\n\n /**\n * Only enforce on these paths (overrides dashboard policy)\n */\n includePaths?: string[];\n\n /**\n * Callback when an agent is detected\n */\n onAgentDetected?: (request: NextRequest, decision: EnforcementDecision) => void | Promise<void>;\n\n /**\n * Callback to customize the blocked response\n */\n customBlockedResponse?: (\n request: NextRequest,\n decision: EnforcementDecision\n ) => NextResponse | Promise<NextResponse>;\n\n /**\n * Whether to fail open (allow) on API errors. Must be explicitly `true`;\n * the default is fail-closed (503 with `Retry-After`). A request that\n * presented a credential (bearer or KYA delegation headers) is answered 503\n * on an API error even when this is `true`.\n *\n * @default false\n */\n failOpen?: boolean;\n\n /**\n * Log detection decisions and errors to the console.\n *\n * @default false\n */\n debug?: boolean;\n}\n\n// ============================================================================\n// Path Matching\n// ============================================================================\n\n/**\n * Check if path should be skipped\n */\nfunction shouldSkipPath(path: string, skipPaths: string[]): boolean {\n return skipPaths.some((pattern) => matchPath(path, pattern));\n}\n\n/**\n * Check if path should be included (if includePaths is set)\n */\nfunction shouldIncludePath(path: string, includePaths?: string[]): boolean {\n if (!includePaths || includePaths.length === 0) return true;\n return includePaths.some((pattern) => matchPath(path, pattern));\n}\n\n// ============================================================================\n// Detection Report\n// ============================================================================\n\n/**\n * Package version, injected at build time by tsdown's `define` from\n * package.json (which the publish workflow stamps before it builds). Unbundled\n * source, as in the unit tests, has no such global, so every read is\n * `typeof`-guarded and the report then omits `sdk` rather than guess a version.\n */\ndeclare const __CHECKPOINT_PKG_VERSION__: string | undefined;\n\n/** The npm package this middleware ships in (package.json `name`, pinned by a unit test). */\nconst SDK_NAME = '@kya-os/checkpoint-nextjs';\n\n/**\n * The gateway ran the engine, so its engine info is reported under the\n * remote-engine name `checkpoint-remote`. Forwarding the gateway's own\n * `checkpoint-worker-wasm` would make this install read as a DNS Gateway.\n */\nfunction remoteEngineInfo(engine: EngineInfo): EngineInfo {\n return {\n name: 'checkpoint-remote',\n version: engine.version,\n rulesetHash: engine.rulesetHash,\n rulesetVersion: engine.rulesetVersion,\n ...(engine.buildSha ? { buildSha: engine.buildSha } : {}),\n };\n}\n\n/** The SDK's self-identification, or undefined when the build injected no version. */\nfunction sdkSelfIdentification(): LogDetectionInput['sdk'] {\n if (typeof __CHECKPOINT_PKG_VERSION__ === 'undefined') return undefined;\n const runtime =\n typeof process !== 'undefined' && process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node';\n return { name: SDK_NAME, version: __CHECKPOINT_PKG_VERSION__, runtime };\n}\n\n// ============================================================================\n// Response Builders\n// ============================================================================\n\n/**\n * Build blocked response.\n *\n * When the policy attaches a `redirectUrl` (e.g. the dashboard's hosted\n * /connect page), we still respect the `block` action but surface the URL to\n * LLM clients so the user can recover: `Link` header + `user_action_required`\n * in the JSON body. Status stays 403 — this is not an auth challenge, it's a\n * blocked request with a recovery hint.\n */\nfunction buildBlockedResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n config: CheckpointApiMiddlewareConfig\n): NextResponse {\n const status = config.blockedResponse?.status ?? 403;\n const message = config.blockedResponse?.message ?? decision.message ?? 'Access denied';\n\n const recoveryUrl = resolveRecoveryUrl(request, config.redirectUrl || decision.redirectUrl);\n\n const body: Record<string, unknown> = {\n error: message,\n code: 'AGENT_BLOCKED',\n reason: decision.reason,\n agentType: decision.agentType,\n };\n\n if (recoveryUrl) {\n const hostname = safeHostname(request.url);\n body.user_action_required = {\n action: `Connect securely to ${hostname}`,\n url: recoveryUrl,\n reason: `${hostname} blocks unverified AI assistants. Open the link to give your assistant a verified key and try again.`,\n };\n body.message =\n `I can't access ${hostname} — this site blocks unverified AI assistants.\\n\\n` +\n `**To give me access, open this link:**\\n` +\n `[Connect securely to ${hostname}](${recoveryUrl})\\n\\n` +\n `Once you're done, ask me to try again.`;\n }\n\n const response = NextResponse.json(body, { status });\n\n // Add custom headers\n if (config.blockedResponse?.headers) {\n for (const [key, value] of Object.entries(config.blockedResponse.headers)) {\n response.headers.set(key, value);\n }\n }\n\n if (recoveryUrl) {\n // RFC 8288 discovery pointer — same rel value the 401 instruct path uses\n // so LLM clients can parse it uniformly.\n response.headers.set('Link', `<${recoveryUrl}>; rel=\"kya-authorize\"`);\n response.headers.set('KYA-Auth-Url', recoveryUrl);\n }\n\n // Add Checkpoint headers\n response.headers.set('KYA-Action', decision.action);\n response.headers.set('KYA-Reason', decision.reason);\n\n return response;\n}\n\n/**\n * A policy `requestsPerMinute` throttle arrives as `block` with reason\n * `rate_limited`. It is a 429 with a retry hint, not an access denial: no\n * \"unverified assistant\" recovery copy and no redirect.\n */\nfunction buildRateLimitedResponse(\n decision: EnforcementDecision,\n config: CheckpointApiMiddlewareConfig\n): NextResponse {\n const retryAfter = decision.metadata?.rateLimit?.retryAfterSeconds;\n const response = NextResponse.json(\n {\n error: decision.message ?? 'Rate limit exceeded',\n code: 'RATE_LIMITED',\n reason: decision.reason,\n agentType: decision.agentType,\n ...(retryAfter !== undefined ? { retryAfterSeconds: retryAfter } : {}),\n },\n { status: 429 }\n );\n for (const [key, value] of Object.entries(config.blockedResponse?.headers ?? {})) {\n response.headers.set(key, value);\n }\n if (retryAfter !== undefined) response.headers.set('Retry-After', String(retryAfter));\n response.headers.set('KYA-Action', decision.action);\n response.headers.set('KYA-Reason', decision.reason);\n return response;\n}\n\nfunction resolveRecoveryUrl(request: NextRequest, target: string | undefined): string | undefined {\n if (!target) return undefined;\n try {\n return new URL(target, request.url).toString();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Build redirect response\n */\nfunction buildRedirectResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n config: CheckpointApiMiddlewareConfig\n): NextResponse {\n const redirectUrl = config.redirectUrl || decision.redirectUrl || '/blocked';\n const url = new URL(redirectUrl, request.url);\n\n // Add query params with detection info\n url.searchParams.set('reason', decision.reason);\n if (decision.agentType) {\n url.searchParams.set('agent', decision.agentType);\n }\n\n return NextResponse.redirect(url);\n}\n\n// ============================================================================\n// Middleware Factory\n// ============================================================================\n\n/**\n * Create Checkpoint middleware with API-based detection\n *\n * @example\n * ```typescript\n * // middleware.ts\n * import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';\n *\n * export default withCheckpointApi({\n * onBlock: 'block',\n * skipPaths: ['/api/health'],\n * });\n * ```\n */\nexport function withCheckpointApi(config: CheckpointApiMiddlewareConfig = {}) {\n // Initialize client (will use CHECKPOINT_API_KEY env var if not provided)\n let client: CheckpointApiClient | null = null;\n\n const getClient = () => {\n if (!client) {\n client = getCheckpointApiClient({\n apiKey: config.apiKey,\n baseUrl: config.apiUrl,\n useEdge: config.useEdge,\n timeout: config.timeout,\n debug: config.debug,\n });\n }\n return client;\n };\n\n // Default skip paths (static assets, etc.).\n //\n // `**` (globstar) is intentional for the `_next/*` patterns: Next.js\n // ships static assets at deeply nested paths like\n // `/_next/static/chunks/main.js` and `/_next/image/?url=…` query-\n // suffixed. The shared `matchPath` treats single `*` as `[^/]*`\n // (segment-local) — pre-rename this code relied on the local\n // matchPath's buggy `*` → `.*` (cross-boundary) coincidence; without\n // `**` here every static-asset request would now hit the enforcement\n // API. Picked up by cursor-bot on PR #2568 after the matchPath swap.\n const defaultSkipPaths = [\n '/_next/static/**',\n '/_next/image/**',\n '/favicon.ico',\n '/robots.txt',\n '/sitemap.xml',\n ];\n\n const skipPaths = [...defaultSkipPaths, ...(config.skipPaths || [])];\n\n // Fails open only on the explicit opt-in AND when the request presented no\n // credential; a presented credential that could not be verified is never\n // waved through.\n const faultResponse = (request: NextRequest): NextResponse =>\n config.failOpen === true && !requestPresentedCredential(request.headers)\n ? failOpenResponse()\n : failClosedResponse();\n\n return async function middleware(request: NextRequest): Promise<NextResponse> {\n const path = request.nextUrl.pathname;\n const startTime = Date.now();\n\n // Check skip paths\n if (shouldSkipPath(path, skipPaths)) {\n return NextResponse.next();\n }\n\n // Check include paths\n if (!shouldIncludePath(path, config.includePaths)) {\n return NextResponse.next();\n }\n\n try {\n const client = getClient();\n\n // Extract request context for potential logging\n const userAgent = request.headers.get('user-agent') || undefined;\n const ipAddress = getClientIp(request, config.clientIpPolicy);\n\n // Call enforce API\n const result = await client.enforce({\n headers: Object.fromEntries(request.headers.entries()),\n userAgent,\n ipAddress,\n path,\n url: request.url,\n method: request.method,\n requestId: request.headers.get('x-request-id') || undefined,\n options: {\n // Always include detection results for logging (needed when using edge)\n includeDetectionResult: true,\n },\n });\n\n // Handle API error\n if (!result.success || !result.data) {\n if (config.debug) {\n console.warn('[Checkpoint] API error:', result.error);\n }\n\n return faultResponse(request);\n }\n\n const decision = result.data.decision;\n\n // Log if debug enabled\n if (config.debug) {\n console.log('[Checkpoint] Decision:', {\n path,\n action: decision.action,\n isAgent: decision.isAgent,\n confidence: decision.confidence,\n agentName: decision.agentName,\n detectionMethod: result.data.detection?.detectionMethod || 'not-included',\n processingTimeMs: Date.now() - startTime,\n });\n }\n\n // Fire-and-forget logging - ONLY when using Gateway Worker (edge detection)\n // When useEdge: false, the /api/v1/enforce endpoint already logs to the database\n // This prevents double-logging while ensuring Gateway detections are persisted\n //\n // Wrapped in waitUntil(): on Vercel's Edge/Fluid Compute runtimes, the\n // platform is free to abort any work still pending once this function\n // returns its Response — an un-awaited fetch() with no lifecycle\n // extension gets killed mid-flight (observed live as `[Checkpoint] Log\n // detection failed: DOMException [AbortError]: This operation was\n // aborted`, 100% reproduction rate on a real deployment: every\n // detection classified correctly but never persisted). waitUntil()\n // tells the platform to keep the function alive until this promise\n // settles, without making the response wait for it. Off Vercel (or\n // wherever no request context backs it) waitUntil() itself no-ops\n // safely — see the import's doc comment — so this needs no fallback.\n if (client.isUsingEdge() && result.data.detection) {\n waitUntil(\n client\n .logDetection({\n detection: result.data.detection,\n context: { userAgent, ipAddress, path, url: request.url, method: request.method },\n // This is the Next.js middleware regardless of whether it used\n // edge detection or the Vercel API. `logDetection`'s own\n // default ('gateway') describes the transport, not the\n // installation, so this must say 'middleware' explicitly.\n source: 'middleware',\n // The decision this middleware acts on below, and the engine\n // that made it, so the dashboard shows a verdict and a method\n // instead of an unknown runtime with no decision.\n enforcement: { action: decision.action },\n engine: result.data.engine ? remoteEngineInfo(result.data.engine) : undefined,\n sdk: sdkSelfIdentification(),\n })\n .catch((err) => {\n if (config.debug) {\n console.error('[Checkpoint] Log detection failed:', err);\n }\n })\n );\n }\n\n // Observability callbacks must not influence enforcement. A throwing\n // callback used to reach the outer catch before block/redirect actions\n // ran, which fails open only when the explicit opt-in is set and no\n // credential was presented, allowing requests the API had already denied.\n if (decision.isAgent && config.onAgentDetected) {\n try {\n await config.onAgentDetected(request, decision);\n } catch (error) {\n if (config.debug) {\n console.error('[Checkpoint] onAgentDetected callback failed:', error);\n }\n }\n }\n\n // Handle enforcement action\n const redirectMode = config.redirectMode ?? 'instruct';\n switch (decision.action) {\n case 'block': {\n // Use custom response if provided. `return await` (not bare\n // `return`) keeps a rejected promise inside this try block so\n // the catch path below can absorb it — without the\n // await, the rejection escapes synchronously and the caller\n // sees an unhandled 500 instead of the intended fault response\n // (fail-open only with the explicit opt-in and no credential\n // presented, else 503). Same shape as the\n // `await config.onAgentDetected(...)` call earlier in this handler.\n if (config.customBlockedResponse) {\n return await config.customBlockedResponse(request, decision);\n }\n\n if (decision.reason === 'rate_limited') {\n return buildRateLimitedResponse(decision, config);\n }\n\n // Check if config overrides to redirect\n if (config.onBlock === 'redirect') {\n return buildRedirectResponse(request, decision, config);\n }\n\n return buildBlockedResponse(request, decision, config);\n }\n\n case 'redirect':\n case 'instruct': {\n // Default behavior: 401 + Link header + JSON body so LLM clients can\n // surface the /connect URL as a link for the user to open. This\n // matches `buildAgentInstructionResponse` in the CF gateway, so\n // hostname-routed and self-hosted deployments behave the same.\n //\n // Legacy 302 behavior is available under `redirectMode: 'http'` for\n // customers who want a plain browser redirect.\n if (redirectMode === 'http' && decision.action === 'redirect') {\n return buildRedirectResponse(request, decision, config);\n }\n\n const targetUrl = config.redirectUrl || decision.redirectUrl;\n // Dual envelope: serve the body-readable 200 to cooperative agents\n // under negotiated mode; else the spec 401. Feed the shared selector\n // the API's detection class + isAgent from the SAME detection payload\n // the engine PEPs (express / nextjs middleware) use — so negotiated\n // mode can't disagree across PEPs, and the class/isAgent pair the\n // predicate gates on stays internally consistent (never the\n // `decision.isAgent` proxy, which could diverge from this payload).\n const bodyReadable200 = selectBodyReadable200(\n config.delegationChallengeMode ?? 'negotiated',\n request.headers,\n result.data.detection?.detectionClass,\n result.data.detection?.isAgent ?? false\n );\n return buildAgentInstructionResponse(request, decision, targetUrl, {\n bodyReadable200,\n });\n }\n\n case 'challenge': {\n return buildRedirectResponse(request, decision, config);\n }\n\n case 'log':\n case 'allow':\n default: {\n // Allow the request to proceed\n const response = NextResponse.next();\n\n // Add detection headers for downstream use\n if (decision.isAgent) {\n response.headers.set('KYA-Detected', 'true');\n response.headers.set('KYA-Confidence', decision.confidence.toString());\n if (decision.agentName) {\n response.headers.set('KYA-Agent', decision.agentName);\n }\n }\n\n return response;\n }\n }\n } catch (error) {\n // Unexpected error\n if (config.debug) {\n console.error('[Checkpoint] Middleware error:', error);\n }\n\n return faultResponse(request);\n }\n };\n}\n\nfunction failOpenResponse(): NextResponse {\n const response = NextResponse.next();\n response.headers.set('KYA-Failopen', 'true');\n return response;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,iBAAiB;AACvB,MAAM,uBAAuB;;;;;;;;AAoB7B,SAAgB,8BACd,SACA,UACA,aACA,SACc;CAId,MAAM,WAAW,WAAW,eAAe,sBAAsB,QAAQ,GAAG;CAI5E,MAAM,YAAY,SAAS,aAAa,SAAS,aAA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tB,OAAO,2BAA2B,cAClC,QAAQ,SACR,OAAO,KAAK,WAAW,gBACvB,OAAO,KAAK,WAAW,WAAW,KACpC;KACA,OAAO,8BAA8B,SAAS,UAAU,WAAW,EACjE,gBACF,CAAC;IACH;IAEA,KAAK,aACH,OAAO,sBAAsB,SAAS,UAAU,MAAM;IAKxD,SAAS;KAEP,MAAM,WAAW,aAAa,KAAK;KAGnC,IAAI,SAAS,SAAS;MACpB,SAAS,QAAQ,IAAI,gBAAgB,MAAM;MAC3C,SAAS,QAAQ,IAAI,kBAAkB,SAAS,WAAW,SAAS,CAAC;MACrE,IAAI,SAAS,WACX,SAAS,QAAQ,IAAI,aAAa,SAAS,SAAS;KAExD;KAEA,OAAO;IACT;GACF;EACF,SAAS,OAAO;GAEd,IAAI,OAAO,OACT,QAAQ,MAAM,kCAAkC,KAAK;GAGvD,OAAO,cAAc,OAAO;EAC9B;CACF;AACF;AAEA,SAAS,mBAAiC;CACxC,MAAM,WAAW,aAAa,KAAK;CACnC,SAAS,QAAQ,IAAI,gBAAgB,MAAM;CAC3C,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"api-middleware-DvmkJ_Li.mjs","names":[],"sources":["../src/responses/agent-instruction.ts","../src/api-middleware.ts"],"sourcesContent":["/**\n * Agent Instruction Response Builder (Next.js)\n *\n * Tells an AI agent where to send its user to complete consent / connect,\n * via a machine-parseable Link header + JSON body.\n *\n * **Dual envelope.** By default this is a 401 instruction response. AI-agent fetchers (Claude-User\n * WebFetch, ChatGPT) collapse 4xx responses and never surface the body to\n * the LLM, so the instruction is invisible. When the caller is a\n * cooperative, self-identifying agent (selected upstream via\n * `serveBodyReadable200`), pass `{ bodyReadable200: true }` to serve the\n * SAME body at HTTP 200 with NO `WWW-Authenticate` (a 200 + WWW-Authenticate\n * is reinterpreted as 401 by some fetchers); the consent URL stays in the\n * body + the `KYA-Auth-Url`/`Link` hint headers. This also realigns\n * TS-instruct (was 401-only) with .NET-instruct (200).\n *\n * Envelope selection is a cooperative-UX bridge, NOT an access control —\n * the authoritative consent target is the body `user_action_required.url`;\n * the `KYA-Auth-Url`/`Link` headers are unsigned hints.\n *\n * This is the in-app counterpart to the Cloudflare Gateway's builder at\n * `apps/web/workers/gateway/src/responses/agent-instruction.ts`. The body\n * is kept in sync so LLM and MCP clients see identical behavior whether a\n * site is protected by the gateway or by the Next.js middleware.\n *\n * Implements RFC 8288 Link discovery. It deliberately emits no\n * `WWW-Authenticate`; only a registered policy Challenge may emit the canonical\n * Delegation authentication fields.\n *\n * @see ../../apps/web/workers/gateway/src/responses/agent-instruction.ts\n */\n\nimport { NextResponse, type NextRequest } from 'next/server.js';\nimport type { EnforcementDecision } from '../api-client';\nimport { safeHostname } from '../utils';\n\nconst MCP_I_DOCS_URL = 'https://kya.vouched.id/docs/enforce/kya-os-enforcement';\nconst DEFAULT_CONNECT_PATH = '/connect';\n\n/** Options controlling which envelope `buildAgentInstructionResponse` emits. */\nexport interface AgentInstructionResponseOptions {\n /**\n * When true, serve the body-readable HTTP 200 fetcher envelope (same\n * body, no `WWW-Authenticate`) instead of the 401. The caller\n * decides this via the shared `serveBodyReadable200` predicate when its\n * challenge-emission mode is `negotiated`. Defaults to false.\n */\n bodyReadable200?: boolean;\n}\n\n/**\n * Build an \"agent must connect\" response for the Next.js middleware.\n *\n * The caller is responsible for deciding *when* to call this (typically when\n * `decision.action === 'redirect'` or `'instruct'`) and *which envelope* via\n * `options.bodyReadable200`. This helper only owns the response shape.\n */\nexport function buildAgentInstructionResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n redirectUrl: string | undefined,\n options?: AgentInstructionResponseOptions\n): NextResponse {\n // Resolve the target to an absolute URL against the incoming request so the\n // Link header is dereferenceable by strict clients (some LLM fetchers refuse\n // relative URIs in Link).\n const resolved = resolveUrl(redirectUrl ?? DEFAULT_CONNECT_PATH, request.url);\n\n // Match gateway's \"connect page\" branch: attach ?agent= for client-specific\n // install cards on the landing page.\n const agentName = decision.agentName || decision.agentType || 'unknown';\n if (!resolved.searchParams.has('agent')) {\n resolved.searchParams.set('agent', agentName.toLowerCase());\n }\n\n const authUrl = resolved.toString();\n const hostname = safeHostname(request.url);\n\n const body = {\n // Markdown-formatted so clients that render markdown (Claude Desktop,\n // ChatGPT web) surface the URL as a clickable link. Tone mirrors the\n // gateway response so messaging stays consistent across platforms.\n message:\n `I can't access ${hostname} yet — this site checks AI assistants at the front door.\\n\\n` +\n `**To give me access, open this link:**\\n` +\n `[Connect securely to ${hostname}](${authUrl})\\n\\n` +\n `It only takes a moment and you won't need to do it again. ` +\n `Once you're done, ask me to try again and I'll connect through the verified channel automatically.`,\n\n user_action_required: {\n action: `Connect securely to ${hostname}`,\n url: authUrl,\n reason: `${hostname} checks AI assistants before they connect. Open the link to give your assistant a verified key.`,\n },\n\n mcp_i: {\n version: '1.0' as const,\n action: 'authenticate' as const,\n authorization_url: authUrl,\n flow: {\n type: 'oauth2_delegation' as const,\n steps: [\n '1. Direct your user to the authorization_url',\n '2. User reviews requested scopes and grants consent',\n '3. Receive delegation credential (JWT)',\n '4. Include credential in KYA-Delegation header',\n '5. Retry this request with the proof',\n ],\n },\n retry_instructions: {\n header: 'KYA-Delegation' as const,\n format: 'JWT delegation credential from authorization flow',\n },\n documentation: MCP_I_DOCS_URL,\n },\n\n error: 'mcp_authentication_required',\n code: 'AGENT_REQUIRES_DELEGATION',\n\n detection: {\n agent_type: decision.agentType || 'ai_agent',\n agent_name: decision.agentName || 'Unknown Agent',\n confidence: decision.confidence,\n },\n };\n\n // Dual envelope: 200 body-readable for cooperative fetchers, else 401.\n // The body is identical across both. INSTRUCT is not a registered policy\n // Delegation challenge, so it must not advertise a fabricated auth scheme.\n const bodyReadable200 = options?.bodyReadable200 ?? false;\n const response = NextResponse.json(body, { status: bodyReadable200 ? 200 : 401 });\n\n // RFC 8288 discovery pointer + KYA-* hints. Present on BOTH envelopes —\n // these are unsigned hints; the authoritative target is the body\n // `user_action_required.url`. `rel=\"kya-authorize\"` matches the CF gateway.\n response.headers.set(\n 'Link',\n `<${authUrl}>; rel=\"kya-authorize\", <${MCP_I_DOCS_URL}>; rel=\"help\"`\n );\n response.headers.set('KYA-Auth-Required', 'true');\n response.headers.set('KYA-Auth-Url', authUrl);\n response.headers.set('KYA-Action', 'instruct');\n response.headers.set('KYA-Detected-Agent', agentName);\n response.headers.set('KYA-Confidence', decision.confidence.toString());\n response.headers.set('Cache-Control', 'no-store');\n\n return response;\n}\n\n/**\n * Resolve a URL that may be absolute or a same-origin path.\n * Falls back to `/connect` on the request origin if parsing fails.\n */\nfunction resolveUrl(target: string, baseUrl: string): URL {\n try {\n return new URL(target, baseUrl);\n } catch {\n return new URL(DEFAULT_CONNECT_PATH, baseUrl);\n }\n}\n","/**\n * API-based Checkpoint Middleware for Next.js\n *\n * This middleware uses the Checkpoint API for detection and enforcement,\n * instead of running detection locally. This approach:\n *\n * 1. Works reliably in Edge Runtime (no WASM loading issues)\n * 2. Ensures consistent detection across all platforms\n * 3. Applies centralized policies from the dashboard\n * 4. Supports deny lists, thresholds, and path rules\n *\n * @example\n * ```typescript\n * // middleware.ts\n * import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';\n *\n * export default withCheckpointApi({\n * apiKey: process.env.CHECKPOINT_API_KEY!,\n * // Optional overrides:\n * onBlock: 'redirect', // 'block' | 'redirect' | 'challenge'\n * redirectUrl: '/blocked',\n * skipPaths: ['/api/health', '/_next/*'],\n * });\n *\n * export const config = {\n * matcher: ['/((?!_next/static|favicon.ico).*)'],\n * };\n * ```\n */\n\nimport { NextRequest, NextResponse } from 'next/server.js';\nimport { matchPath } from '@kya-os/checkpoint-shared/policy/enforcement';\nimport { requestPresentedCredential } from '@kya-os/checkpoint-shared/kya-http';\nimport {\n selectBodyReadable200,\n type ChallengeEnvelopeMode,\n} from '@kya-os/checkpoint-shared/host-adapter';\nimport type { ClientIpTrustPolicy } from '@kya-os/checkpoint-shared/client-ip';\nimport type { EngineInfo } from '@kya-os/checkpoint-shared';\nimport {\n CheckpointApiClient,\n getCheckpointApiClient,\n type EnforcementDecision,\n type LogDetectionInput,\n} from './api-client';\nimport { buildAgentInstructionResponse } from './responses/agent-instruction';\nimport { failClosedResponse } from './adapt';\nimport { getClientIp, safeHostname } from './utils';\n// A genuine hard dependency, not an optional one, despite forcing every\n// consumer (even non-Vercel ones) to install it (bestbrian review,\n// checkpoint#4460). Two reasons a dynamic/optional-peer import, which this\n// file used briefly, does NOT work here (Bugbot review, checkpoint#4657):\n// 1. This middleware explicitly targets Edge Runtime (see the module doc\n// comment). A `webpackIgnore`d variable-name `import()` is invisible\n// to the bundler on purpose — but Edge Runtime has no filesystem/module\n// resolution at request time, only what the bundler actually included.\n// An intentionally-unbundled import can never resolve there; `waitUntil`\n// would silently never register, reintroducing the exact lost-detection\n// bug this wrapper exists to prevent.\n// 2. It's unnecessary: `waitUntil()`'s own implementation\n// (`getContext().waitUntil?.(promise)`, where `getContext()` returns\n// `{}` off Vercel) already no-ops safely everywhere it isn't backed by\n// a real Vercel request context — Node, Edge, tests, wherever. There is\n// no failure mode to guard against with a fallback; the only real cost\n// of the hard dependency is a few extra KB installed on non-Vercel\n// consumers, which is the correct trade against actually breaking\n// detection logging on Vercel.\nimport { waitUntil } from '@vercel/functions';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Middleware configuration\n */\nexport interface CheckpointApiMiddlewareConfig {\n /** Explicit deployment/proxy trust profile for client-IP resolution. */\n clientIpPolicy?: ClientIpTrustPolicy;\n /** API key (or use CHECKPOINT_API_KEY env var) */\n apiKey?: string;\n /**\n * Gateway base URL. Override for staging or self-hosted deployments.\n * With `useEdge: false` the default becomes `https://kya.vouched.id`.\n *\n * @default 'https://detect.checkpoint-gateway.ai'\n */\n apiUrl?: string;\n /**\n * Use edge detection for lower latency (~30-50ms vs ~150ms) and better coverage.\n * Edge detection can identify non-JS clients (curl, Python, Claude Code WebFetch)\n * that the pixel cannot detect since they don't execute JavaScript.\n * Set to false to use the Vercel API instead.\n * @default true\n */\n useEdge?: boolean;\n /**\n * Request timeout in milliseconds for the gateway call.\n *\n * @default 5000\n */\n timeout?: number;\n\n /**\n * Action to take when an agent should be blocked\n * - 'block': Return 403 response\n * - 'redirect': Redirect to redirectUrl\n * - 'challenge': Show a challenge page (future)\n * Default: uses policy from dashboard\n */\n onBlock?: 'block' | 'redirect' | 'challenge';\n\n /**\n * URL to redirect to when blocking (if onBlock is 'redirect')\n * Default: uses redirectUrl from dashboard policy\n */\n redirectUrl?: string;\n\n /**\n * How the middleware handles a `redirect` / `instruct` action.\n *\n * - `'instruct'` (default): return HTTP 401 with a KYA-OS Link header + JSON\n * body pointing the agent at the redirect URL. LLMs surface the URL as a\n * clickable link for the user. Matches the Cloudflare Gateway contract.\n * - `'http'`: legacy behavior — return HTTP 302 with `Location`. Most LLM\n * fetchers won't follow the redirect, so this is only useful when your\n * traffic is real browsers.\n *\n * @default 'instruct'\n */\n redirectMode?: 'instruct' | 'http';\n\n /**\n * Challenge-emission envelope mode (draft-kya-http-02 §8.1 fetcher-200).\n * `negotiated` serves a body-readable HTTP 200 instruct response to\n * cooperative agents (so fetchers that drop 4xx bodies can read it),\n * keeping the spec 401 for everyone else. Defaults to `negotiated` (#3530).\n * A cooperative-UX bridge, NOT an access control.\n *\n * @default 'negotiated'\n */\n delegationChallengeMode?: ChallengeEnvelopeMode;\n\n /**\n * Customize the blocked response's status, message, and extra headers.\n *\n * @default { status: 403, message: 'Access denied' }\n */\n blockedResponse?: {\n status?: number;\n message?: string;\n headers?: Record<string, string>;\n };\n\n /**\n * Paths to skip (in addition to dashboard policy)\n * Supports glob patterns: '/api/*', '/_next/*'\n */\n skipPaths?: string[];\n\n /**\n * Only enforce on these paths (overrides dashboard policy)\n */\n includePaths?: string[];\n\n /**\n * Callback when an agent is detected\n */\n onAgentDetected?: (request: NextRequest, decision: EnforcementDecision) => void | Promise<void>;\n\n /**\n * Callback to customize the blocked response\n */\n customBlockedResponse?: (\n request: NextRequest,\n decision: EnforcementDecision\n ) => NextResponse | Promise<NextResponse>;\n\n /**\n * Whether to fail open (allow) on API errors. Must be explicitly `true`;\n * the default is fail-closed (503 with `Retry-After`). A request that\n * presented a credential (bearer or KYA delegation headers) is answered 503\n * on an API error even when this is `true`.\n *\n * @default false\n */\n failOpen?: boolean;\n\n /**\n * Log detection decisions and errors to the console.\n *\n * @default false\n */\n debug?: boolean;\n}\n\n// ============================================================================\n// Path Matching\n// ============================================================================\n\n/**\n * Check if path should be skipped\n */\nfunction shouldSkipPath(path: string, skipPaths: string[]): boolean {\n return skipPaths.some((pattern) => matchPath(path, pattern));\n}\n\n/**\n * Check if path should be included (if includePaths is set)\n */\nfunction shouldIncludePath(path: string, includePaths?: string[]): boolean {\n if (!includePaths || includePaths.length === 0) return true;\n return includePaths.some((pattern) => matchPath(path, pattern));\n}\n\n// ============================================================================\n// Detection Report\n// ============================================================================\n\n/**\n * Package version, injected at build time by tsdown's `define` from\n * package.json (which the publish workflow stamps before it builds). Unbundled\n * source, as in the unit tests, has no such global, so every read is\n * `typeof`-guarded and the report then omits `sdk` rather than guess a version.\n */\ndeclare const __CHECKPOINT_PKG_VERSION__: string | undefined;\n\n/** The npm package this middleware ships in (package.json `name`, pinned by a unit test). */\nconst SDK_NAME = '@kya-os/checkpoint-nextjs';\n\n/**\n * The gateway ran the engine, so its engine info is reported under the\n * remote-engine name `checkpoint-remote`. Forwarding the gateway's own\n * `checkpoint-worker-wasm` would make this install read as a DNS Gateway.\n */\nfunction remoteEngineInfo(engine: EngineInfo): EngineInfo {\n return {\n name: 'checkpoint-remote',\n version: engine.version,\n rulesetHash: engine.rulesetHash,\n rulesetVersion: engine.rulesetVersion,\n ...(engine.buildSha ? { buildSha: engine.buildSha } : {}),\n };\n}\n\n/** The SDK's self-identification, or undefined when the build injected no version. */\nfunction sdkSelfIdentification(): LogDetectionInput['sdk'] {\n if (typeof __CHECKPOINT_PKG_VERSION__ === 'undefined') return undefined;\n const runtime =\n typeof process !== 'undefined' && process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node';\n return { name: SDK_NAME, version: __CHECKPOINT_PKG_VERSION__, runtime };\n}\n\n// ============================================================================\n// Response Builders\n// ============================================================================\n\n/**\n * Build blocked response.\n *\n * When the policy attaches a `redirectUrl` (e.g. the dashboard's hosted\n * /connect page), we still respect the `block` action but surface the URL to\n * LLM clients so the user can recover: `Link` header + `user_action_required`\n * in the JSON body. Status stays 403 — this is not an auth challenge, it's a\n * blocked request with a recovery hint.\n */\nfunction buildBlockedResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n config: CheckpointApiMiddlewareConfig\n): NextResponse {\n const status = config.blockedResponse?.status ?? 403;\n const message = config.blockedResponse?.message ?? decision.message ?? 'Access denied';\n\n const recoveryUrl = resolveRecoveryUrl(request, config.redirectUrl || decision.redirectUrl);\n\n const body: Record<string, unknown> = {\n error: message,\n code: 'AGENT_BLOCKED',\n reason: decision.reason,\n agentType: decision.agentType,\n };\n\n if (recoveryUrl) {\n const hostname = safeHostname(request.url);\n body.user_action_required = {\n action: `Connect securely to ${hostname}`,\n url: recoveryUrl,\n reason: `${hostname} blocks unverified AI assistants. Open the link to give your assistant a verified key and try again.`,\n };\n body.message =\n `I can't access ${hostname} — this site blocks unverified AI assistants.\\n\\n` +\n `**To give me access, open this link:**\\n` +\n `[Connect securely to ${hostname}](${recoveryUrl})\\n\\n` +\n `Once you're done, ask me to try again.`;\n }\n\n const response = NextResponse.json(body, { status });\n\n // Add custom headers\n if (config.blockedResponse?.headers) {\n for (const [key, value] of Object.entries(config.blockedResponse.headers)) {\n response.headers.set(key, value);\n }\n }\n\n if (recoveryUrl) {\n // RFC 8288 discovery pointer — same rel value the 401 instruct path uses\n // so LLM clients can parse it uniformly.\n response.headers.set('Link', `<${recoveryUrl}>; rel=\"kya-authorize\"`);\n response.headers.set('KYA-Auth-Url', recoveryUrl);\n }\n\n // Add Checkpoint headers\n response.headers.set('KYA-Action', decision.action);\n response.headers.set('KYA-Reason', decision.reason);\n\n return response;\n}\n\n/**\n * A policy `requestsPerMinute` throttle arrives as `block` with reason\n * `rate_limited`. It is a 429 with a retry hint, not an access denial: no\n * \"unverified assistant\" recovery copy and no redirect.\n */\nfunction buildRateLimitedResponse(\n decision: EnforcementDecision,\n config: CheckpointApiMiddlewareConfig\n): NextResponse {\n const retryAfter = decision.metadata?.rateLimit?.retryAfterSeconds;\n const response = NextResponse.json(\n {\n error: decision.message ?? 'Rate limit exceeded',\n code: 'RATE_LIMITED',\n reason: decision.reason,\n agentType: decision.agentType,\n ...(retryAfter !== undefined ? { retryAfterSeconds: retryAfter } : {}),\n },\n { status: 429 }\n );\n for (const [key, value] of Object.entries(config.blockedResponse?.headers ?? {})) {\n response.headers.set(key, value);\n }\n if (retryAfter !== undefined) response.headers.set('Retry-After', String(retryAfter));\n response.headers.set('KYA-Action', decision.action);\n response.headers.set('KYA-Reason', decision.reason);\n return response;\n}\n\nfunction resolveRecoveryUrl(request: NextRequest, target: string | undefined): string | undefined {\n if (!target) return undefined;\n try {\n return new URL(target, request.url).toString();\n } catch {\n return undefined;\n }\n}\n\n/**\n * Build redirect response\n */\nfunction buildRedirectResponse(\n request: NextRequest,\n decision: EnforcementDecision,\n config: CheckpointApiMiddlewareConfig\n): NextResponse {\n const redirectUrl = config.redirectUrl || decision.redirectUrl || '/blocked';\n const url = new URL(redirectUrl, request.url);\n\n // Add query params with detection info\n url.searchParams.set('reason', decision.reason);\n if (decision.agentType) {\n url.searchParams.set('agent', decision.agentType);\n }\n\n return NextResponse.redirect(url);\n}\n\n// ============================================================================\n// Middleware Factory\n// ============================================================================\n\n/**\n * Create Checkpoint middleware with API-based detection\n *\n * @example\n * ```typescript\n * // middleware.ts\n * import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';\n *\n * export default withCheckpointApi({\n * onBlock: 'block',\n * skipPaths: ['/api/health'],\n * });\n * ```\n */\nexport function withCheckpointApi(config: CheckpointApiMiddlewareConfig = {}) {\n // Initialize client (will use CHECKPOINT_API_KEY env var if not provided)\n let client: CheckpointApiClient | null = null;\n\n const getClient = () => {\n if (!client) {\n client = getCheckpointApiClient({\n apiKey: config.apiKey,\n baseUrl: config.apiUrl,\n useEdge: config.useEdge,\n timeout: config.timeout,\n debug: config.debug,\n });\n }\n return client;\n };\n\n // Default skip paths (static assets, etc.).\n //\n // `**` (globstar) is intentional for the `_next/*` patterns: Next.js\n // ships static assets at deeply nested paths like\n // `/_next/static/chunks/main.js` and `/_next/image/?url=…` query-\n // suffixed. The shared `matchPath` treats single `*` as `[^/]*`\n // (segment-local) — pre-rename this code relied on the local\n // matchPath's buggy `*` → `.*` (cross-boundary) coincidence; without\n // `**` here every static-asset request would now hit the enforcement\n // API. Picked up by cursor-bot on PR #2568 after the matchPath swap.\n const defaultSkipPaths = [\n '/_next/static/**',\n '/_next/image/**',\n '/favicon.ico',\n '/robots.txt',\n '/sitemap.xml',\n ];\n\n const skipPaths = [...defaultSkipPaths, ...(config.skipPaths || [])];\n\n // Fails open only on the explicit opt-in AND when the request presented no\n // credential; a presented credential that could not be verified is never\n // waved through.\n const faultResponse = (request: NextRequest): NextResponse =>\n config.failOpen === true && !requestPresentedCredential(request.headers)\n ? failOpenResponse()\n : failClosedResponse();\n\n return async function middleware(request: NextRequest): Promise<NextResponse> {\n const path = request.nextUrl.pathname;\n const startTime = Date.now();\n\n // Check skip paths\n if (shouldSkipPath(path, skipPaths)) {\n return NextResponse.next();\n }\n\n // Check include paths\n if (!shouldIncludePath(path, config.includePaths)) {\n return NextResponse.next();\n }\n\n try {\n const client = getClient();\n\n // Extract request context for potential logging\n const userAgent = request.headers.get('user-agent') || undefined;\n const ipAddress = getClientIp(request, config.clientIpPolicy);\n\n // Call enforce API\n const result = await client.enforce({\n headers: Object.fromEntries(request.headers.entries()),\n userAgent,\n ipAddress,\n path,\n url: request.url,\n method: request.method,\n requestId: request.headers.get('x-request-id') || undefined,\n options: {\n // Always include detection results for logging (needed when using edge)\n includeDetectionResult: true,\n },\n });\n\n // Handle API error\n if (!result.success || !result.data) {\n if (config.debug) {\n console.warn('[Checkpoint] API error:', result.error);\n }\n\n return faultResponse(request);\n }\n\n const decision = result.data.decision;\n\n // Log if debug enabled\n if (config.debug) {\n console.log('[Checkpoint] Decision:', {\n path,\n action: decision.action,\n isAgent: decision.isAgent,\n confidence: decision.confidence,\n agentName: decision.agentName,\n detectionMethod: result.data.detection?.detectionMethod || 'not-included',\n processingTimeMs: Date.now() - startTime,\n });\n }\n\n // Fire-and-forget logging - ONLY when using Gateway Worker (edge detection)\n // When useEdge: false, the /api/v1/enforce endpoint already logs to the database\n // This prevents double-logging while ensuring Gateway detections are persisted\n //\n // Wrapped in waitUntil(): on Vercel's Edge/Fluid Compute runtimes, the\n // platform is free to abort any work still pending once this function\n // returns its Response — an un-awaited fetch() with no lifecycle\n // extension gets killed mid-flight (observed live as `[Checkpoint] Log\n // detection failed: DOMException [AbortError]: This operation was\n // aborted`, 100% reproduction rate on a real deployment: every\n // detection classified correctly but never persisted). waitUntil()\n // tells the platform to keep the function alive until this promise\n // settles, without making the response wait for it. Off Vercel (or\n // wherever no request context backs it) waitUntil() itself no-ops\n // safely — see the import's doc comment — so this needs no fallback.\n if (client.isUsingEdge() && result.data.detection) {\n waitUntil(\n client\n .logDetection({\n detection: result.data.detection,\n context: { userAgent, ipAddress, path, url: request.url, method: request.method },\n // This is the Next.js middleware regardless of whether it used\n // edge detection or the Vercel API. `logDetection`'s own\n // default ('gateway') describes the transport, not the\n // installation, so this must say 'middleware' explicitly.\n source: 'middleware',\n // The decision this middleware acts on below, and the engine\n // that made it, so the dashboard shows a verdict and a method\n // instead of an unknown runtime with no decision.\n enforcement: { action: decision.action },\n engine: result.data.engine ? remoteEngineInfo(result.data.engine) : undefined,\n sdk: sdkSelfIdentification(),\n })\n .catch((err) => {\n if (config.debug) {\n console.error('[Checkpoint] Log detection failed:', err);\n }\n })\n );\n }\n\n // Observability callbacks must not influence enforcement. A throwing\n // callback used to reach the outer catch before block/redirect actions\n // ran, which fails open only when the explicit opt-in is set and no\n // credential was presented, allowing requests the API had already denied.\n if (decision.isAgent && config.onAgentDetected) {\n try {\n await config.onAgentDetected(request, decision);\n } catch (error) {\n if (config.debug) {\n console.error('[Checkpoint] onAgentDetected callback failed:', error);\n }\n }\n }\n\n // Handle enforcement action\n const redirectMode = config.redirectMode ?? 'instruct';\n switch (decision.action) {\n case 'block': {\n // Use custom response if provided. `return await` (not bare\n // `return`) keeps a rejected promise inside this try block so\n // the catch path below can absorb it — without the\n // await, the rejection escapes synchronously and the caller\n // sees an unhandled 500 instead of the intended fault response\n // (fail-open only with the explicit opt-in and no credential\n // presented, else 503). Same shape as the\n // `await config.onAgentDetected(...)` call earlier in this handler.\n if (config.customBlockedResponse) {\n return await config.customBlockedResponse(request, decision);\n }\n\n if (decision.reason === 'rate_limited') {\n return buildRateLimitedResponse(decision, config);\n }\n\n // Check if config overrides to redirect\n if (config.onBlock === 'redirect') {\n return buildRedirectResponse(request, decision, config);\n }\n\n return buildBlockedResponse(request, decision, config);\n }\n\n case 'redirect':\n case 'instruct': {\n // Default behavior: 401 + Link header + JSON body so LLM clients can\n // surface the /connect URL as a link for the user to open. This\n // matches `buildAgentInstructionResponse` in the CF gateway, so\n // hostname-routed and self-hosted deployments behave the same.\n //\n // Legacy 302 behavior is available under `redirectMode: 'http'` for\n // customers who want a plain browser redirect.\n if (redirectMode === 'http' && decision.action === 'redirect') {\n return buildRedirectResponse(request, decision, config);\n }\n\n const targetUrl = config.redirectUrl || decision.redirectUrl;\n // Dual envelope: serve the body-readable 200 to cooperative agents\n // under negotiated mode; else the spec 401. Feed the shared selector\n // the API's detection class + isAgent from the SAME detection payload\n // the engine PEPs (express / nextjs middleware) use — so negotiated\n // mode can't disagree across PEPs, and the class/isAgent pair the\n // predicate gates on stays internally consistent (never the\n // `decision.isAgent` proxy, which could diverge from this payload).\n const bodyReadable200 = selectBodyReadable200(\n config.delegationChallengeMode ?? 'negotiated',\n request.headers,\n result.data.detection?.detectionClass,\n result.data.detection?.isAgent ?? false\n );\n return buildAgentInstructionResponse(request, decision, targetUrl, {\n bodyReadable200,\n });\n }\n\n case 'challenge': {\n return buildRedirectResponse(request, decision, config);\n }\n\n case 'log':\n case 'allow':\n default: {\n // Allow the request to proceed\n const response = NextResponse.next();\n\n // Add detection headers for downstream use\n if (decision.isAgent) {\n response.headers.set('KYA-Detected', 'true');\n response.headers.set('KYA-Confidence', decision.confidence.toString());\n if (decision.agentName) {\n response.headers.set('KYA-Agent', decision.agentName);\n }\n }\n\n return response;\n }\n }\n } catch (error) {\n // Unexpected error\n if (config.debug) {\n console.error('[Checkpoint] Middleware error:', error);\n }\n\n return faultResponse(request);\n }\n };\n}\n\nfunction failOpenResponse(): NextResponse {\n const response = NextResponse.next();\n response.headers.set('KYA-Failopen', 'true');\n return response;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,iBAAiB;AACvB,MAAM,uBAAuB;;;;;;;;AAoB7B,SAAgB,8BACd,SACA,UACA,aACA,SACc;CAId,MAAM,WAAW,WAAW,eAAe,sBAAsB,QAAQ,GAAG;CAI5E,MAAM,YAAY,SAAS,aAAa,SAAS,aAAa;CAC9D,IAAI,CAAC,SAAS,aAAa,IAAI,OAAO,GACpC,SAAS,aAAa,IAAI,SAAS,UAAU,YAAY,CAAC;CAG5D,MAAM,UAAU,SAAS,SAAS;CAClC,MAAM,WAAW,aAAa,QAAQ,GAAG;CAEzC,MAAM,OAAO;EAIX,SACE,kBAAkB,SAAS,2HAEH,SAAS,IAAI,QAAQ;EAI/C,sBAAsB;GACpB,QAAQ,uBAAuB;GAC/B,KAAK;GACL,QAAQ,GAAG,SAAS;EACtB;EAEA,OAAO;GACL,SAAS;GACT,QAAQ;GACR,mBAAmB;GACnB,MAAM;IACJ,MAAM;IACN,OAAO;KACL;KACA;KACA;KACA;KACA;IACF;GACF;GACA,oBAAoB;IAClB,QAAQ;IACR,QAAQ;GACV;GACA,eAAe;EACjB;EAEA,OAAO;E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AAM,kCAAkC,KAAK;GAGvD,OAAO,cAAc,OAAO;EAC9B;CACF;AACF;AAEA,SAAS,mBAAiC;CACxC,MAAM,WAAW,aAAa,KAAK;CACnC,SAAS,QAAQ,IAAI,gBAAgB,MAAM;CAC3C,OAAO;AACT"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
const require_adapt = require('./adapt-
|
|
1
|
+
const require_adapt = require('./adapt-DUEIfZnx.js');
|
|
2
2
|
const require_utils = require('./utils-dyFxqlFI.js');
|
|
3
3
|
const require_api_client = require('./api-client.js');
|
|
4
|
-
let _kya_os_checkpoint_shared_host_adapter = require("@kya-os/checkpoint-shared/host-adapter");
|
|
5
4
|
let _vercel_functions = require("@vercel/functions");
|
|
6
5
|
let next_server_js = require("next/server.js");
|
|
6
|
+
let _kya_os_checkpoint_shared_host_adapter = require("@kya-os/checkpoint-shared/host-adapter");
|
|
7
7
|
let _kya_os_checkpoint_shared_policy_enforcement = require("@kya-os/checkpoint-shared/policy/enforcement");
|
|
8
8
|
let _kya_os_checkpoint_shared_kya_http = require("@kya-os/checkpoint-shared/kya-http");
|
|
9
9
|
|
|
@@ -177,7 +177,7 @@ function sdkSelfIdentification() {
|
|
|
177
177
|
const runtime = typeof process !== "undefined" && process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
|
|
178
178
|
return {
|
|
179
179
|
name: SDK_NAME,
|
|
180
|
-
version: "1.
|
|
180
|
+
version: "1.12.0",
|
|
181
181
|
runtime
|
|
182
182
|
};
|
|
183
183
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as withCheckpointApi, t as CheckpointApiMiddlewareConfig } from "./api-middleware-
|
|
1
|
+
import { n as withCheckpointApi, t as CheckpointApiMiddlewareConfig } from "./api-middleware-BtsYJU5u.mjs";
|
|
2
2
|
export { CheckpointApiMiddlewareConfig, withCheckpointApi };
|
package/dist/api-middleware.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_api_middleware = require('./api-middleware-
|
|
2
|
+
const require_api_middleware = require('./api-middleware-beNlXd5P.js');
|
|
3
3
|
|
|
4
4
|
exports.withCheckpointApi = require_api_middleware.withCheckpointApi;
|
package/dist/api-middleware.mjs
CHANGED
package/dist/cedar-wasm.d.mts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*
|
|
8
8
|
* ```ts
|
|
9
9
|
* import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';
|
|
10
|
-
* export default withCheckpoint({
|
|
10
|
+
* export default withCheckpoint({ projectId, engineWasmModule });
|
|
11
11
|
* ```
|
|
12
12
|
*
|
|
13
13
|
* Opt-in because it is larger than the engine-only build; a project whose
|
package/dist/cedar-wasm.d.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*
|
|
8
8
|
* ```ts
|
|
9
9
|
* import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';
|
|
10
|
-
* export default withCheckpoint({
|
|
10
|
+
* export default withCheckpoint({ projectId, engineWasmModule });
|
|
11
11
|
* ```
|
|
12
12
|
*
|
|
13
13
|
* Opt-in because it is larger than the engine-only build; a project whose
|
package/dist/cedar-wasm.js
CHANGED
|
@@ -11,7 +11,7 @@ _kya_os_checkpoint_wasm_runtime_wasm_kya_os_engine_cedar_web_kya_os_engine_bg_wa
|
|
|
11
11
|
*
|
|
12
12
|
* ```ts
|
|
13
13
|
* import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';
|
|
14
|
-
* export default withCheckpoint({
|
|
14
|
+
* export default withCheckpoint({ projectId, engineWasmModule });
|
|
15
15
|
* ```
|
|
16
16
|
*
|
|
17
17
|
* Opt-in because it is larger than the engine-only build; a project whose
|
package/dist/cedar-wasm.mjs
CHANGED
|
@@ -9,7 +9,7 @@ import compiled from "@kya-os/checkpoint-wasm-runtime/wasm/kya-os-engine-cedar-w
|
|
|
9
9
|
*
|
|
10
10
|
* ```ts
|
|
11
11
|
* import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';
|
|
12
|
-
* export default withCheckpoint({
|
|
12
|
+
* export default withCheckpoint({ projectId, engineWasmModule });
|
|
13
13
|
* ```
|
|
14
14
|
*
|
|
15
15
|
* Opt-in because it is larger than the engine-only build; a project whose
|
package/dist/cedar-wasm.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cedar-wasm.mjs","names":[],"sources":["../src/cedar-wasm.ts"],"sourcesContent":["/**\n * The Cedar build's compiled `WebAssembly.Module`: the engine plus the Cedar\n * policy evaluator. Pass it as `withCheckpoint`'s `engineWasmModule` on the\n * Edge runtime, in place of `./engine-wasm`, and one module runs detection and\n * the project's Cedar policy:\n *\n * ```ts\n * import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';\n * export default withCheckpoint({
|
|
1
|
+
{"version":3,"file":"cedar-wasm.mjs","names":[],"sources":["../src/cedar-wasm.ts"],"sourcesContent":["/**\n * The Cedar build's compiled `WebAssembly.Module`: the engine plus the Cedar\n * policy evaluator. Pass it as `withCheckpoint`'s `engineWasmModule` on the\n * Edge runtime, in place of `./engine-wasm`, and one module runs detection and\n * the project's Cedar policy:\n *\n * ```ts\n * import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';\n * export default withCheckpoint({ projectId, engineWasmModule });\n * ```\n *\n * Opt-in because it is larger than the engine-only build; a project whose\n * Cedar policy is enforcing needs it on the Edge runtime. Imported through\n * this package, the binary always matches the glue this package loads.\n */\n\nimport compiled from '@kya-os/checkpoint-wasm-runtime/wasm/kya-os-engine-cedar-web/kya_os_engine_bg.wasm?module';\n\n// Typed here so the published declaration names no `?module` specifier.\nconst cedarWasmModule: WebAssembly.Module = compiled;\nexport default cedarWasmModule;\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAM,kBAAsC"}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { CheckpointHostConfig } from "@kya-os/checkpoint-wasm-runtime/pipeline";
|
|
2
|
+
import { NextRequest } from "next/server.js";
|
|
3
|
+
import { ClientIpTrustPolicy } from "@kya-os/checkpoint-shared";
|
|
4
|
+
//#region src/config.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Configuration for `withCheckpoint`. Every field is optional; on the Edge
|
|
7
|
+
* runtime `withCheckpoint` also needs a compiled engine module
|
|
8
|
+
* (`CheckpointEdgeConfig`).
|
|
9
|
+
*/
|
|
10
|
+
interface CheckpointConfig extends CheckpointHostConfig<NextRequest> {
|
|
11
|
+
/**
|
|
12
|
+
* Selects the infrastructure allowed to vouch for observed client addresses.
|
|
13
|
+
* Vercel headers are honored only inside its managed runtime (`VERCEL=1`).
|
|
14
|
+
* NextRequest exposes no socket peer, so generic proxy and Cloudflare origin
|
|
15
|
+
* profiles cannot authenticate that boundary and return no address. Use a
|
|
16
|
+
* transport-aware ingress, such as the Express adapter, for those profiles.
|
|
17
|
+
*/
|
|
18
|
+
clientIpPolicy?: ClientIpTrustPolicy;
|
|
19
|
+
/**
|
|
20
|
+
* Read the request body when `content-type` is `application/json` so
|
|
21
|
+
* the orchestrator can extract a KYA-OS envelope from
|
|
22
|
+
* `_meta.proof.jws`. Default `true`.
|
|
23
|
+
*
|
|
24
|
+
* **When to disable** — streaming middlewares that can't tolerate
|
|
25
|
+
* the `req.clone()` memory overhead (one full-body copy is buffered
|
|
26
|
+
* during the read). For those, set `false` and route KYA-OS
|
|
27
|
+
* envelopes through the `KYA-Delegation` header transport instead
|
|
28
|
+
* (requires `legacyEnvelopeFallback: true`).
|
|
29
|
+
*
|
|
30
|
+
* The clone preserves `req.body` for downstream handlers — disabling
|
|
31
|
+
* is a performance optimization, not a correctness fix.
|
|
32
|
+
*
|
|
33
|
+
* SDK-Envelope-Plumbing-1 (#2594). Added in `@kya-os/checkpoint-nextjs@1.1.0`.
|
|
34
|
+
*
|
|
35
|
+
* @default true
|
|
36
|
+
*/
|
|
37
|
+
drainJsonBody?: boolean;
|
|
38
|
+
/**
|
|
39
|
+
* EDGE runtime only. The Cedar build's `WebAssembly.Module`. Prefer passing
|
|
40
|
+
* it as `engineWasmModule` (see there); this field is kept so existing
|
|
41
|
+
* configs work. Passed alone it serves both roles, detection and policy, on
|
|
42
|
+
* one instance. Passed next to the engine-only build it runs as a second
|
|
43
|
+
* instance, and the Edge bundle carries the engine twice (`debug` logs a
|
|
44
|
+
* hint).
|
|
45
|
+
*
|
|
46
|
+
* Without a Cedar module the project's policy is still fetched and never
|
|
47
|
+
* skipped: with no Cedar policy nothing changes, a policy in shadow mode
|
|
48
|
+
* keeps the structured decision, and an enforcing policy answers every
|
|
49
|
+
* request 503 and logs which module is missing. The Node runtime ignores
|
|
50
|
+
* this field (it loads Cedar through `createPolicyEvaluator`).
|
|
51
|
+
*
|
|
52
|
+
* Added in `@kya-os/checkpoint-nextjs@1.5.0` (@Policy middleware-Cedar, #3076).
|
|
53
|
+
*/
|
|
54
|
+
cedarWasmModule?: WebAssembly.Module;
|
|
55
|
+
/**
|
|
56
|
+
* EDGE runtime only, and required there unless `cedarWasmModule` is set.
|
|
57
|
+
* The module the engine runs on, statically imported by the host:
|
|
58
|
+
*
|
|
59
|
+
* ```ts
|
|
60
|
+
* // Detection only:
|
|
61
|
+
* import engineWasmModule from '@kya-os/checkpoint-nextjs/engine-wasm';
|
|
62
|
+
* // Detection and the project's Cedar policy, on one module:
|
|
63
|
+
* import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';
|
|
64
|
+
*
|
|
65
|
+
* export default withCheckpoint({ projectId, engineWasmModule });
|
|
66
|
+
* ```
|
|
67
|
+
*
|
|
68
|
+
* The Cedar build is the engine plus Cedar, so it replaces the engine-only
|
|
69
|
+
* build rather than adding to it; it is larger, which is why it is opt-in.
|
|
70
|
+
* A project whose Cedar policy is enforcing needs it on the Edge runtime.
|
|
71
|
+
*
|
|
72
|
+
* The Edge runtime does not let code compile WebAssembly from bytes, so the
|
|
73
|
+
* engine cannot fetch and compile its own binary there; the bundler has to
|
|
74
|
+
* hand it over as a compiled module. The Node runtime ignores this field.
|
|
75
|
+
*/
|
|
76
|
+
engineWasmModule?: WebAssembly.Module;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* `withCheckpoint` configuration for the Edge runtime (`./edge`): the engine
|
|
80
|
+
* needs a module, `engineWasmModule` or, on its own, `cedarWasmModule`.
|
|
81
|
+
*/
|
|
82
|
+
type CheckpointEdgeConfig = CheckpointConfig & ({
|
|
83
|
+
engineWasmModule: WebAssembly.Module;
|
|
84
|
+
} | {
|
|
85
|
+
cedarWasmModule: WebAssembly.Module;
|
|
86
|
+
});
|
|
87
|
+
//#endregion
|
|
88
|
+
export { CheckpointEdgeConfig as n, CheckpointConfig as t };
|
|
89
|
+
//# sourceMappingURL=config-D7h2w_it.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-D7h2w_it.d.mts","names":[],"sources":["../src/config.ts"],"mappings":";;;;;;;;;UAkBiB,yBAAyB,qBAAqB;;;;;;;;EAQ7D,iBAAiB;;;;;;;;;;;;;;;;;;;EAoBjB;;;;;;;;;;;;;;;;;EAkBA,kBAAkB,YAAY;;;;;;;;;;;;;;;;;;;;;;EAuB9B,mBAAmB,YAAY;;;;;;KAOrB,uBAAuB;EAC9B,kBAAkB,YAAY;;EAAa,iBAAiB,YAAY"}
|