@kya-os/checkpoint-nextjs 1.9.0 → 1.10.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 +77 -0
- package/dist/adapt.d.mts +6 -34
- package/dist/adapt.d.mts.map +1 -0
- package/dist/adapt.d.ts +6 -34
- package/dist/adapt.d.ts.map +1 -0
- package/dist/adapt.js +78 -51
- package/dist/adapt.mjs +77 -48
- package/dist/adapt.mjs.map +1 -0
- package/dist/api-client.d.mts +150 -159
- package/dist/api-client.d.mts.map +1 -0
- package/dist/api-client.d.ts +150 -159
- package/dist/api-client.d.ts.map +1 -0
- package/dist/api-client.js +218 -204
- package/dist/api-client.mjs +217 -201
- package/dist/api-client.mjs.map +1 -0
- package/dist/api-middleware-CDSh3TSE.js +379 -0
- package/dist/api-middleware-CMDRoQik.mjs +357 -0
- package/dist/api-middleware-CMDRoQik.mjs.map +1 -0
- package/dist/api-middleware.d.mts +117 -131
- package/dist/api-middleware.d.mts.map +1 -0
- package/dist/api-middleware.d.ts +117 -131
- package/dist/api-middleware.d.ts.map +1 -0
- package/dist/api-middleware.js +8 -527
- package/dist/api-middleware.mjs +3 -521
- package/dist/composed-policy-BCaNiVHv.d.mts +98 -0
- package/dist/composed-policy-BCaNiVHv.d.mts.map +1 -0
- package/dist/composed-policy-zzJYNFTb.d.ts +98 -0
- package/dist/composed-policy-zzJYNFTb.d.ts.map +1 -0
- package/dist/composed-policy.d.mts +2 -115
- package/dist/composed-policy.d.ts +2 -115
- package/dist/composed-policy.js +122 -89
- package/dist/composed-policy.mjs +121 -86
- package/dist/composed-policy.mjs.map +1 -0
- package/dist/config-CbAg2mze.d.ts +255 -0
- package/dist/config-CbAg2mze.d.ts.map +1 -0
- package/dist/config-Doe0Tn53.d.mts +255 -0
- package/dist/config-Doe0Tn53.d.mts.map +1 -0
- package/dist/create-middleware.d.mts +7 -18
- package/dist/create-middleware.d.mts.map +1 -0
- package/dist/create-middleware.d.ts +7 -18
- package/dist/create-middleware.d.ts.map +1 -0
- package/dist/create-middleware.js +36 -31
- package/dist/create-middleware.mjs +35 -28
- package/dist/create-middleware.mjs.map +1 -0
- package/dist/edge/index.d.mts +64 -88
- package/dist/edge/index.d.mts.map +1 -0
- package/dist/edge/index.d.ts +64 -88
- package/dist/edge/index.d.ts.map +1 -0
- package/dist/edge/index.js +349 -264
- package/dist/edge/index.mjs +348 -261
- package/dist/edge/index.mjs.map +1 -0
- package/dist/edge-runtime-loader.d.mts +37 -65
- package/dist/edge-runtime-loader.d.mts.map +1 -0
- package/dist/edge-runtime-loader.d.ts +37 -65
- package/dist/edge-runtime-loader.d.ts.map +1 -0
- package/dist/edge-runtime-loader.js +268 -213
- package/dist/edge-runtime-loader.mjs +267 -210
- package/dist/edge-runtime-loader.mjs.map +1 -0
- package/dist/edge-wasm-middleware.d.mts +27 -46
- package/dist/edge-wasm-middleware.d.mts.map +1 -0
- package/dist/edge-wasm-middleware.d.ts +27 -46
- package/dist/edge-wasm-middleware.d.ts.map +1 -0
- package/dist/edge-wasm-middleware.js +26 -15
- package/dist/edge-wasm-middleware.mjs +25 -12
- package/dist/edge-wasm-middleware.mjs.map +1 -0
- package/dist/index.d.mts +10 -17
- package/dist/index.d.ts +10 -17
- package/dist/index.js +55 -1265
- package/dist/index.mjs +16 -1234
- package/dist/index.mjs.map +1 -0
- package/dist/middleware-bundler.d.mts +6 -12
- package/dist/middleware-bundler.d.mts.map +1 -0
- package/dist/middleware-bundler.d.ts +6 -12
- package/dist/middleware-bundler.d.ts.map +1 -0
- package/dist/middleware-bundler.js +12 -350
- package/dist/middleware-bundler.mjs +11 -347
- package/dist/middleware-bundler.mjs.map +1 -0
- package/dist/middleware-core-BYQP9FND.mjs +165 -0
- package/dist/middleware-core-BYQP9FND.mjs.map +1 -0
- package/dist/middleware-core-D6TijE6P.js +175 -0
- package/dist/middleware-edge.d.mts +8 -14
- package/dist/middleware-edge.d.mts.map +1 -0
- package/dist/middleware-edge.d.ts +8 -14
- package/dist/middleware-edge.d.ts.map +1 -0
- package/dist/middleware-edge.js +41 -355
- package/dist/middleware-edge.mjs +39 -347
- package/dist/middleware-edge.mjs.map +1 -0
- package/dist/middleware-node-CE4GevYs.d.ts +20 -0
- package/dist/middleware-node-CE4GevYs.d.ts.map +1 -0
- package/dist/middleware-node-DtyOuPta.d.mts +20 -0
- package/dist/middleware-node-DtyOuPta.d.mts.map +1 -0
- package/dist/middleware-node-context-BqPbf-fI.mjs +34 -0
- package/dist/middleware-node-context-BqPbf-fI.mjs.map +1 -0
- package/dist/middleware-node-context-rgnc7UNR.js +38 -0
- package/dist/middleware-node.d.mts +3 -27
- package/dist/middleware-node.d.ts +3 -27
- package/dist/middleware-node.js +13 -351
- package/dist/middleware-node.mjs +11 -347
- package/dist/middleware-node.mjs.map +1 -0
- package/dist/middleware.d.mts +8 -28
- package/dist/middleware.d.mts.map +1 -0
- package/dist/middleware.d.ts +8 -28
- package/dist/middleware.d.ts.map +1 -0
- package/dist/middleware.js +43 -9
- package/dist/middleware.mjs +42 -6
- package/dist/middleware.mjs.map +1 -0
- package/dist/nodejs-wasm-loader.d.mts +8 -7
- package/dist/nodejs-wasm-loader.d.mts.map +1 -0
- package/dist/nodejs-wasm-loader.d.ts +8 -7
- package/dist/nodejs-wasm-loader.d.ts.map +1 -0
- package/dist/nodejs-wasm-loader.js +53 -19
- package/dist/nodejs-wasm-loader.mjs +52 -16
- package/dist/nodejs-wasm-loader.mjs.map +1 -0
- package/dist/policy.d.mts +86 -110
- package/dist/policy.d.mts.map +1 -0
- package/dist/policy.d.ts +86 -110
- package/dist/policy.d.ts.map +1 -0
- package/dist/policy.js +203 -165
- package/dist/policy.mjs +183 -152
- package/dist/policy.mjs.map +1 -0
- package/dist/session-tracker.d.mts +42 -47
- package/dist/session-tracker.d.mts.map +1 -0
- package/dist/session-tracker.d.ts +42 -47
- package/dist/session-tracker.d.ts.map +1 -0
- package/dist/session-tracker.js +141 -165
- package/dist/session-tracker.mjs +140 -162
- package/dist/session-tracker.mjs.map +1 -0
- package/dist/translate.d.mts +17 -32
- package/dist/translate.d.mts.map +1 -0
- package/dist/translate.d.ts +17 -32
- package/dist/translate.d.ts.map +1 -0
- package/dist/translate.js +69 -34
- package/dist/translate.mjs +68 -31
- package/dist/translate.mjs.map +1 -0
- package/dist/types-C0SkqLMM.d.mts +102 -0
- package/dist/types-C0SkqLMM.d.mts.map +1 -0
- package/dist/types-C7DNSCTO.d.ts +102 -0
- package/dist/types-C7DNSCTO.d.ts.map +1 -0
- package/dist/utils-Cj4XNhIY.mjs +35 -0
- package/dist/utils-Cj4XNhIY.mjs.map +1 -0
- package/dist/utils-DAisnYnI.js +45 -0
- package/dist/wasm-setup.d.mts +6 -5
- package/dist/wasm-setup.d.mts.map +1 -0
- package/dist/wasm-setup.d.ts +6 -5
- package/dist/wasm-setup.d.ts.map +1 -0
- package/dist/wasm-setup.js +82 -113
- package/dist/wasm-setup.mjs +85 -108
- package/dist/wasm-setup.mjs.map +1 -0
- package/package.json +8 -8
- package/dist/config-CleTeeoW.d.mts +0 -233
- package/dist/config-XMOIkxFN.d.ts +0 -233
- package/dist/types-Chgi5TFC.d.mts +0 -105
- package/dist/types-Chgi5TFC.d.ts +0 -105
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import { getCheckpointApiClient } from "./api-client.mjs";
|
|
2
|
+
import { n as safeHostname, t as getClientIp } from "./utils-Cj4XNhIY.mjs";
|
|
3
|
+
import { matchPath, selectBodyReadable200 } from "@kya-os/checkpoint-shared";
|
|
4
|
+
import { NextResponse } from "next/server";
|
|
5
|
+
import { waitUntil } from "@vercel/functions";
|
|
6
|
+
|
|
7
|
+
//#region src/responses/agent-instruction.ts
|
|
8
|
+
/**
|
|
9
|
+
* Agent Instruction Response Builder (Next.js)
|
|
10
|
+
*
|
|
11
|
+
* Tells an AI agent where to send its user to complete consent / connect,
|
|
12
|
+
* via a machine-parseable Link header + JSON body.
|
|
13
|
+
*
|
|
14
|
+
* **Dual envelope.** By default this is a 401 instruction response. AI-agent fetchers (Claude-User
|
|
15
|
+
* WebFetch, ChatGPT) collapse 4xx responses and never surface the body to
|
|
16
|
+
* the LLM, so the instruction is invisible. When the caller is a
|
|
17
|
+
* cooperative, self-identifying agent (selected upstream via
|
|
18
|
+
* `serveBodyReadable200`), pass `{ bodyReadable200: true }` to serve the
|
|
19
|
+
* SAME body at HTTP 200 with NO `WWW-Authenticate` (a 200 + WWW-Authenticate
|
|
20
|
+
* is reinterpreted as 401 by some fetchers); the consent URL stays in the
|
|
21
|
+
* body + the `KYA-Auth-Url`/`Link` hint headers. This also realigns
|
|
22
|
+
* TS-instruct (was 401-only) with .NET-instruct (200).
|
|
23
|
+
*
|
|
24
|
+
* Envelope selection is a cooperative-UX bridge, NOT an access control —
|
|
25
|
+
* the authoritative consent target is the body `user_action_required.url`;
|
|
26
|
+
* the `KYA-Auth-Url`/`Link` headers are unsigned hints.
|
|
27
|
+
*
|
|
28
|
+
* This is the in-app counterpart to the Cloudflare Gateway's builder at
|
|
29
|
+
* `apps/web/workers/gateway/src/responses/agent-instruction.ts`. The body
|
|
30
|
+
* is kept in sync so LLM and MCP clients see identical behavior whether a
|
|
31
|
+
* site is protected by the gateway or by the Next.js middleware.
|
|
32
|
+
*
|
|
33
|
+
* Implements RFC 8288 Link discovery. It deliberately emits no
|
|
34
|
+
* `WWW-Authenticate`; only a registered policy Challenge may emit the canonical
|
|
35
|
+
* Delegation authentication fields.
|
|
36
|
+
*
|
|
37
|
+
* @see ../../apps/web/workers/gateway/src/responses/agent-instruction.ts
|
|
38
|
+
*/
|
|
39
|
+
const MCP_I_DOCS_URL = "https://kya.vouched.id/docs/enforce/kya-os-enforcement";
|
|
40
|
+
const DEFAULT_CONNECT_PATH = "/connect";
|
|
41
|
+
/**
|
|
42
|
+
* Build an "agent must connect" response for the Next.js middleware.
|
|
43
|
+
*
|
|
44
|
+
* The caller is responsible for deciding *when* to call this (typically when
|
|
45
|
+
* `decision.action === 'redirect'` or `'instruct'`) and *which envelope* via
|
|
46
|
+
* `options.bodyReadable200`. This helper only owns the response shape.
|
|
47
|
+
*/
|
|
48
|
+
function buildAgentInstructionResponse(request, decision, redirectUrl, options) {
|
|
49
|
+
const resolved = resolveUrl(redirectUrl ?? DEFAULT_CONNECT_PATH, request.url);
|
|
50
|
+
const agentName = decision.agentName || decision.agentType || "unknown";
|
|
51
|
+
if (!resolved.searchParams.has("agent")) resolved.searchParams.set("agent", agentName.toLowerCase());
|
|
52
|
+
const authUrl = resolved.toString();
|
|
53
|
+
const hostname = safeHostname(request.url);
|
|
54
|
+
const body = {
|
|
55
|
+
message: `I can't access ${hostname} yet — this site checks AI assistants at the front door.\n\n**To give me access, open this link:**\n[Connect securely to ${hostname}](${authUrl})\n\nIt only takes a moment and you won't need to do it again. Once you're done, ask me to try again and I'll connect through the verified channel automatically.`,
|
|
56
|
+
user_action_required: {
|
|
57
|
+
action: `Connect securely to ${hostname}`,
|
|
58
|
+
url: authUrl,
|
|
59
|
+
reason: `${hostname} checks AI assistants before they connect. Open the link to give your assistant a verified key.`
|
|
60
|
+
},
|
|
61
|
+
mcp_i: {
|
|
62
|
+
version: "1.0",
|
|
63
|
+
action: "authenticate",
|
|
64
|
+
authorization_url: authUrl,
|
|
65
|
+
flow: {
|
|
66
|
+
type: "oauth2_delegation",
|
|
67
|
+
steps: [
|
|
68
|
+
"1. Direct your user to the authorization_url",
|
|
69
|
+
"2. User reviews requested scopes and grants consent",
|
|
70
|
+
"3. Receive delegation credential (JWT)",
|
|
71
|
+
"4. Include credential in KYA-Delegation header",
|
|
72
|
+
"5. Retry this request with the proof"
|
|
73
|
+
]
|
|
74
|
+
},
|
|
75
|
+
retry_instructions: {
|
|
76
|
+
header: "KYA-Delegation",
|
|
77
|
+
format: "JWT delegation credential from authorization flow"
|
|
78
|
+
},
|
|
79
|
+
documentation: MCP_I_DOCS_URL
|
|
80
|
+
},
|
|
81
|
+
error: "mcp_authentication_required",
|
|
82
|
+
code: "AGENT_REQUIRES_DELEGATION",
|
|
83
|
+
detection: {
|
|
84
|
+
agent_type: decision.agentType || "ai_agent",
|
|
85
|
+
agent_name: decision.agentName || "Unknown Agent",
|
|
86
|
+
confidence: decision.confidence
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
const bodyReadable200 = options?.bodyReadable200 ?? false;
|
|
90
|
+
const response = NextResponse.json(body, { status: bodyReadable200 ? 200 : 401 });
|
|
91
|
+
response.headers.set("Link", `<${authUrl}>; rel="kya-authorize", <${MCP_I_DOCS_URL}>; rel="help"`);
|
|
92
|
+
response.headers.set("KYA-Auth-Required", "true");
|
|
93
|
+
response.headers.set("KYA-Auth-Url", authUrl);
|
|
94
|
+
response.headers.set("KYA-Action", "instruct");
|
|
95
|
+
response.headers.set("KYA-Detected-Agent", agentName);
|
|
96
|
+
response.headers.set("KYA-Confidence", decision.confidence.toString());
|
|
97
|
+
response.headers.set("Cache-Control", "no-store");
|
|
98
|
+
return response;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Resolve a URL that may be absolute or a same-origin path.
|
|
102
|
+
* Falls back to `/connect` on the request origin if parsing fails.
|
|
103
|
+
*/
|
|
104
|
+
function resolveUrl(target, baseUrl) {
|
|
105
|
+
try {
|
|
106
|
+
return new URL(target, baseUrl);
|
|
107
|
+
} catch {
|
|
108
|
+
return new URL(DEFAULT_CONNECT_PATH, baseUrl);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
//#endregion
|
|
113
|
+
//#region src/api-middleware.ts
|
|
114
|
+
/**
|
|
115
|
+
* API-based AgentShield Middleware for Next.js
|
|
116
|
+
*
|
|
117
|
+
* This middleware uses the AgentShield API for detection and enforcement,
|
|
118
|
+
* instead of running detection locally. This approach:
|
|
119
|
+
*
|
|
120
|
+
* 1. Works reliably in Edge Runtime (no WASM loading issues)
|
|
121
|
+
* 2. Ensures consistent detection across all platforms
|
|
122
|
+
* 3. Applies centralized policies from the dashboard
|
|
123
|
+
* 4. Supports deny lists, thresholds, and path rules
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```typescript
|
|
127
|
+
* // middleware.ts
|
|
128
|
+
* import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';
|
|
129
|
+
*
|
|
130
|
+
* export default withCheckpointApi({
|
|
131
|
+
* apiKey: process.env.CHECKPOINT_API_KEY!,
|
|
132
|
+
* // Optional overrides:
|
|
133
|
+
* onBlock: 'redirect', // 'block' | 'redirect' | 'challenge'
|
|
134
|
+
* redirectUrl: '/blocked',
|
|
135
|
+
* skipPaths: ['/api/health', '/_next/*'],
|
|
136
|
+
* });
|
|
137
|
+
*
|
|
138
|
+
* export const config = {
|
|
139
|
+
* matcher: ['/((?!_next/static|favicon.ico).*)'],
|
|
140
|
+
* };
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
/**
|
|
144
|
+
* Check if path should be skipped
|
|
145
|
+
*/
|
|
146
|
+
function shouldSkipPath(path, skipPaths) {
|
|
147
|
+
return skipPaths.some((pattern) => matchPath(path, pattern));
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Check if path should be included (if includePaths is set)
|
|
151
|
+
*/
|
|
152
|
+
function shouldIncludePath(path, includePaths) {
|
|
153
|
+
if (!includePaths || includePaths.length === 0) return true;
|
|
154
|
+
return includePaths.some((pattern) => matchPath(path, pattern));
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Build blocked response.
|
|
158
|
+
*
|
|
159
|
+
* When the policy attaches a `redirectUrl` (e.g. the dashboard's hosted
|
|
160
|
+
* /connect page), we still respect the `block` action but surface the URL to
|
|
161
|
+
* LLM clients so the user can recover: `Link` header + `user_action_required`
|
|
162
|
+
* in the JSON body. Status stays 403 — this is not an auth challenge, it's a
|
|
163
|
+
* blocked request with a recovery hint.
|
|
164
|
+
*/
|
|
165
|
+
function buildBlockedResponse(request, decision, config) {
|
|
166
|
+
const status = config.blockedResponse?.status ?? 403;
|
|
167
|
+
const message = config.blockedResponse?.message ?? decision.message ?? "Access denied";
|
|
168
|
+
const recoveryUrl = resolveRecoveryUrl(request, config.redirectUrl || decision.redirectUrl);
|
|
169
|
+
const body = {
|
|
170
|
+
error: message,
|
|
171
|
+
code: "AGENT_BLOCKED",
|
|
172
|
+
reason: decision.reason,
|
|
173
|
+
agentType: decision.agentType
|
|
174
|
+
};
|
|
175
|
+
if (recoveryUrl) {
|
|
176
|
+
const hostname = safeHostname(request.url);
|
|
177
|
+
body.user_action_required = {
|
|
178
|
+
action: `Connect securely to ${hostname}`,
|
|
179
|
+
url: recoveryUrl,
|
|
180
|
+
reason: `${hostname} blocks unverified AI assistants. Open the link to give your assistant a verified key and try again.`
|
|
181
|
+
};
|
|
182
|
+
body.message = `I can't access ${hostname} — this site blocks unverified AI assistants.\n\n**To give me access, open this link:**\n[Connect securely to ${hostname}](${recoveryUrl})\n\nOnce you're done, ask me to try again.`;
|
|
183
|
+
}
|
|
184
|
+
const response = NextResponse.json(body, { status });
|
|
185
|
+
if (config.blockedResponse?.headers) for (const [key, value] of Object.entries(config.blockedResponse.headers)) response.headers.set(key, value);
|
|
186
|
+
if (recoveryUrl) {
|
|
187
|
+
response.headers.set("Link", `<${recoveryUrl}>; rel="kya-authorize"`);
|
|
188
|
+
response.headers.set("KYA-Auth-Url", recoveryUrl);
|
|
189
|
+
}
|
|
190
|
+
response.headers.set("KYA-Action", decision.action);
|
|
191
|
+
response.headers.set("KYA-Reason", decision.reason);
|
|
192
|
+
return response;
|
|
193
|
+
}
|
|
194
|
+
function resolveRecoveryUrl(request, target) {
|
|
195
|
+
if (!target) return void 0;
|
|
196
|
+
try {
|
|
197
|
+
return new URL(target, request.url).toString();
|
|
198
|
+
} catch {
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Build redirect response
|
|
204
|
+
*/
|
|
205
|
+
function buildRedirectResponse(request, decision, config) {
|
|
206
|
+
const redirectUrl = config.redirectUrl || decision.redirectUrl || "/blocked";
|
|
207
|
+
const url = new URL(redirectUrl, request.url);
|
|
208
|
+
url.searchParams.set("reason", decision.reason);
|
|
209
|
+
if (decision.agentType) url.searchParams.set("agent", decision.agentType);
|
|
210
|
+
return NextResponse.redirect(url);
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Create AgentShield middleware with API-based detection
|
|
214
|
+
*
|
|
215
|
+
* @example
|
|
216
|
+
* ```typescript
|
|
217
|
+
* // middleware.ts
|
|
218
|
+
* import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';
|
|
219
|
+
*
|
|
220
|
+
* export default withCheckpointApi({
|
|
221
|
+
* onBlock: 'block',
|
|
222
|
+
* skipPaths: ['/api/health'],
|
|
223
|
+
* });
|
|
224
|
+
* ```
|
|
225
|
+
*/
|
|
226
|
+
function withCheckpointApi(config = {}) {
|
|
227
|
+
let client = null;
|
|
228
|
+
const getClient = () => {
|
|
229
|
+
if (!client) client = getCheckpointApiClient({
|
|
230
|
+
apiKey: config.apiKey,
|
|
231
|
+
baseUrl: config.apiUrl,
|
|
232
|
+
useEdge: config.useEdge,
|
|
233
|
+
timeout: config.timeout,
|
|
234
|
+
debug: config.debug
|
|
235
|
+
});
|
|
236
|
+
return client;
|
|
237
|
+
};
|
|
238
|
+
const skipPaths = [...[
|
|
239
|
+
"/_next/static/**",
|
|
240
|
+
"/_next/image/**",
|
|
241
|
+
"/favicon.ico",
|
|
242
|
+
"/robots.txt",
|
|
243
|
+
"/sitemap.xml"
|
|
244
|
+
], ...config.skipPaths || []];
|
|
245
|
+
const failOpen = config.failOpen ?? true;
|
|
246
|
+
return async function middleware(request) {
|
|
247
|
+
const path = request.nextUrl.pathname;
|
|
248
|
+
const startTime = Date.now();
|
|
249
|
+
if (shouldSkipPath(path, skipPaths)) return NextResponse.next();
|
|
250
|
+
if (!shouldIncludePath(path, config.includePaths)) return NextResponse.next();
|
|
251
|
+
try {
|
|
252
|
+
const client = getClient();
|
|
253
|
+
const userAgent = request.headers.get("user-agent") || void 0;
|
|
254
|
+
const ipAddress = getClientIp(request, config.clientIpPolicy);
|
|
255
|
+
const result = await client.enforce({
|
|
256
|
+
headers: Object.fromEntries(request.headers.entries()),
|
|
257
|
+
userAgent,
|
|
258
|
+
ipAddress,
|
|
259
|
+
path,
|
|
260
|
+
url: request.url,
|
|
261
|
+
method: request.method,
|
|
262
|
+
requestId: request.headers.get("x-request-id") || void 0,
|
|
263
|
+
options: { includeDetectionResult: true }
|
|
264
|
+
});
|
|
265
|
+
if (!result.success || !result.data) {
|
|
266
|
+
if (config.debug) console.warn("[Checkpoint] API error:", result.error);
|
|
267
|
+
if (failOpen) return NextResponse.next();
|
|
268
|
+
return NextResponse.json({
|
|
269
|
+
error: "Security check failed",
|
|
270
|
+
code: "API_ERROR"
|
|
271
|
+
}, { status: 503 });
|
|
272
|
+
}
|
|
273
|
+
const decision = result.data.decision;
|
|
274
|
+
if (config.debug) console.log("[Checkpoint] Decision:", {
|
|
275
|
+
path,
|
|
276
|
+
action: decision.action,
|
|
277
|
+
isAgent: decision.isAgent,
|
|
278
|
+
confidence: decision.confidence,
|
|
279
|
+
agentName: decision.agentName,
|
|
280
|
+
detectionMethod: result.data.detection?.detectionMethod || "not-included",
|
|
281
|
+
processingTimeMs: Date.now() - startTime
|
|
282
|
+
});
|
|
283
|
+
if (client.isUsingEdge() && result.data.detection) waitUntil(client.logDetection({
|
|
284
|
+
detection: result.data.detection,
|
|
285
|
+
context: {
|
|
286
|
+
userAgent,
|
|
287
|
+
ipAddress,
|
|
288
|
+
path,
|
|
289
|
+
url: request.url,
|
|
290
|
+
method: request.method
|
|
291
|
+
},
|
|
292
|
+
source: "middleware"
|
|
293
|
+
}).catch((err) => {
|
|
294
|
+
if (config.debug) console.error("[Checkpoint] Log detection failed:", err);
|
|
295
|
+
}));
|
|
296
|
+
if (decision.isAgent && config.onAgentDetected) try {
|
|
297
|
+
await config.onAgentDetected(request, decision);
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (config.debug) console.error("[Checkpoint] onAgentDetected callback failed:", error);
|
|
300
|
+
}
|
|
301
|
+
const redirectMode = config.redirectMode ?? "instruct";
|
|
302
|
+
switch (decision.action) {
|
|
303
|
+
case "block":
|
|
304
|
+
if (config.customBlockedResponse) return await config.customBlockedResponse(request, decision);
|
|
305
|
+
if (config.onBlock === "redirect") return buildRedirectResponse(request, decision, config);
|
|
306
|
+
return buildBlockedResponse(request, decision, config);
|
|
307
|
+
case "redirect":
|
|
308
|
+
case "instruct": {
|
|
309
|
+
if (redirectMode === "http" && decision.action === "redirect") return buildRedirectResponse(request, decision, config);
|
|
310
|
+
const targetUrl = config.redirectUrl || decision.redirectUrl;
|
|
311
|
+
const bodyReadable200 = selectBodyReadable200(config.delegationChallengeMode ?? "negotiated", request.headers, result.data.detection?.detectionClass, result.data.detection?.isAgent ?? false);
|
|
312
|
+
return buildAgentInstructionResponse(request, decision, targetUrl, { bodyReadable200 });
|
|
313
|
+
}
|
|
314
|
+
case "challenge": return buildRedirectResponse(request, decision, config);
|
|
315
|
+
default: {
|
|
316
|
+
const response = NextResponse.next();
|
|
317
|
+
if (decision.isAgent) {
|
|
318
|
+
response.headers.set("KYA-Detected", "true");
|
|
319
|
+
response.headers.set("KYA-Confidence", decision.confidence.toString());
|
|
320
|
+
if (decision.agentName) response.headers.set("KYA-Agent", decision.agentName);
|
|
321
|
+
}
|
|
322
|
+
return response;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
} catch (error) {
|
|
326
|
+
if (config.debug) console.error("[Checkpoint] Middleware error:", error);
|
|
327
|
+
if (failOpen) return NextResponse.next();
|
|
328
|
+
return NextResponse.json({
|
|
329
|
+
error: "Security check failed",
|
|
330
|
+
code: "MIDDLEWARE_ERROR"
|
|
331
|
+
}, { status: 503 });
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
/** @deprecated Renamed to {@link withCheckpointApi}. The behaviour is identical. */
|
|
336
|
+
const withAgentShield = withCheckpointApi;
|
|
337
|
+
const LEGACY_MIGRATION_ERROR = "This export was removed in Phase D. Migrate to `withCheckpoint` (local-engine deployment) or `withCheckpointApi` (SaaS-gateway deployment) from `@kya-os/checkpoint-nextjs`. See packages/checkpoint-nextjs/README.md (Two deployment shapes) for which one fits your runtime.";
|
|
338
|
+
/**
|
|
339
|
+
* @deprecated Module-load-time invocation of the legacy `withAgentShield()`.
|
|
340
|
+
* Construct the middleware explicitly via `withCheckpointApi({ apiKey })`
|
|
341
|
+
* instead of relying on a default-constructed singleton at import time.
|
|
342
|
+
*/
|
|
343
|
+
function agentShieldMiddleware(_request) {
|
|
344
|
+
throw new Error(LEGACY_MIGRATION_ERROR);
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* @deprecated The "enhanced middleware" combined detection + storage +
|
|
348
|
+
* enforcement into a single legacy path that no longer exists. Migrate
|
|
349
|
+
* to `withCheckpoint` (local-engine) or `withCheckpointApi` (SaaS-gateway).
|
|
350
|
+
*/
|
|
351
|
+
function createEnhancedAgentShieldMiddleware(_config = {}) {
|
|
352
|
+
throw new Error(LEGACY_MIGRATION_ERROR);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
//#endregion
|
|
356
|
+
export { withCheckpointApi as i, createEnhancedAgentShieldMiddleware as n, withAgentShield as r, agentShieldMiddleware as t };
|
|
357
|
+
//# sourceMappingURL=api-middleware-CMDRoQik.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-middleware-CMDRoQik.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';\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 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 {\n matchPath,\n type ClientIpTrustPolicy,\n selectBodyReadable200,\n type ChallengeEnvelopeMode,\n} 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// 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 — the\n// pattern this file used briefly, mirroring `storage/index.ts`'s\n// `@upstash/redis` — 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. Recommended for production.\n *\n * @default true\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// 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, 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 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('[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 })\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 hit the outer fail-open catch before block/redirect\n // actions ran, 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 `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 // 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 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"],"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;I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