@kya-os/checkpoint-nextjs 1.9.0 → 1.11.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 +322 -0
- package/README.md +205 -31
- package/dist/adapt-BdQ9R7Iw.mjs +97 -0
- package/dist/adapt-BdQ9R7Iw.mjs.map +1 -0
- package/dist/adapt-CCSKGjVH.js +107 -0
- package/dist/api-client-JHOrRUA_.d.mts +222 -0
- package/dist/api-client-JHOrRUA_.d.mts.map +1 -0
- package/dist/api-client-JHOrRUA_.d.ts +222 -0
- package/dist/api-client-JHOrRUA_.d.ts.map +1 -0
- package/dist/api-client.d.mts +2 -213
- package/dist/api-client.d.ts +2 -213
- package/dist/api-client.js +221 -206
- package/dist/api-client.mjs +222 -202
- package/dist/api-client.mjs.map +1 -0
- package/dist/api-middleware-BWjokNis.d.mts +131 -0
- package/dist/api-middleware-BWjokNis.d.mts.map +1 -0
- package/dist/api-middleware-Bf3xmM9W.js +391 -0
- package/dist/api-middleware-C-ngFX_8.mjs +387 -0
- package/dist/api-middleware-C-ngFX_8.mjs.map +1 -0
- package/dist/api-middleware-DyLDqOYF.d.ts +131 -0
- package/dist/api-middleware-DyLDqOYF.d.ts.map +1 -0
- package/dist/api-middleware.d.mts +2 -166
- package/dist/api-middleware.d.ts +2 -166
- package/dist/api-middleware.js +3 -526
- package/dist/api-middleware.mjs +2 -521
- package/dist/cedar-wasm.d.mts +20 -0
- package/dist/cedar-wasm.d.mts.map +1 -0
- package/dist/cedar-wasm.d.ts +19 -0
- package/dist/cedar-wasm.d.ts.map +1 -0
- package/dist/cedar-wasm.js +24 -0
- package/dist/cedar-wasm.mjs +23 -0
- package/dist/cedar-wasm.mjs.map +1 -0
- package/dist/config-CPP1RV0f.d.mts +291 -0
- package/dist/config-CPP1RV0f.d.mts.map +1 -0
- package/dist/config-DVgOFxJs.d.ts +291 -0
- package/dist/config-DVgOFxJs.d.ts.map +1 -0
- package/dist/engine-wasm.d.mts +20 -0
- package/dist/engine-wasm.d.mts.map +1 -0
- package/dist/engine-wasm.d.ts +19 -0
- package/dist/engine-wasm.d.ts.map +1 -0
- package/dist/engine-wasm.js +24 -0
- package/dist/engine-wasm.mjs +23 -0
- package/dist/engine-wasm.mjs.map +1 -0
- package/dist/index-edge.d.mts +8 -0
- package/dist/index-edge.d.ts +8 -0
- package/dist/index-edge.js +14 -0
- package/dist/index-edge.mjs +7 -0
- package/dist/index.d.mts +8 -17
- package/dist/index.d.ts +8 -17
- package/dist/index.js +36 -1275
- package/dist/index.mjs +29 -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-B0jf5_Hm.mjs +264 -0
- package/dist/middleware-core-B0jf5_Hm.mjs.map +1 -0
- package/dist/middleware-core-Bol44X9C.d.ts +17 -0
- package/dist/middleware-core-Bol44X9C.d.ts.map +1 -0
- package/dist/middleware-core-CMc-2QkU.js +274 -0
- package/dist/middleware-core-DycsbHUd.d.mts +17 -0
- package/dist/middleware-core-DycsbHUd.d.mts.map +1 -0
- package/dist/middleware-edge.d.mts +16 -14
- package/dist/middleware-edge.d.mts.map +1 -0
- package/dist/middleware-edge.d.ts +16 -14
- package/dist/middleware-edge.d.ts.map +1 -0
- package/dist/middleware-edge.js +94 -355
- package/dist/middleware-edge.mjs +90 -347
- package/dist/middleware-edge.mjs.map +1 -0
- package/dist/middleware-node-context-591KsiYg.js +39 -0
- package/dist/middleware-node-context-D_ZyUEcA.mjs +35 -0
- package/dist/middleware-node-context-D_ZyUEcA.mjs.map +1 -0
- package/dist/middleware-node.d.mts +10 -25
- package/dist/middleware-node.d.mts.map +1 -0
- package/dist/middleware-node.d.ts +10 -25
- package/dist/middleware-node.d.ts.map +1 -0
- package/dist/middleware-node.js +21 -351
- package/dist/middleware-node.mjs +19 -347
- package/dist/middleware-node.mjs.map +1 -0
- package/dist/posture-outcome-Ccujx_9V.d.mts +14 -0
- package/dist/posture-outcome-Ccujx_9V.d.mts.map +1 -0
- package/dist/posture-outcome-Ccujx_9V.d.ts +14 -0
- package/dist/posture-outcome-Ccujx_9V.d.ts.map +1 -0
- package/dist/posture-outcome-DQ4fdMfq.mjs +21 -0
- package/dist/posture-outcome-DQ4fdMfq.mjs.map +1 -0
- package/dist/posture-outcome-DddsJtL8.js +25 -0
- package/dist/public-api-CYsHrTQI.d.ts +5 -0
- package/dist/public-api-DkG7pRE0.d.mts +5 -0
- package/dist/rolldown-runtime-C24Yb2bl.js +33 -0
- package/dist/utils-Cnwg0VrY.mjs +88 -0
- package/dist/utils-Cnwg0VrY.mjs.map +1 -0
- package/dist/utils-dyFxqlFI.js +104 -0
- package/package.json +31 -66
- package/EDGE_RUNTIME_WASM_SETUP.md +0 -342
- package/bin/setup-edge-wasm.js +0 -513
- package/dist/adapt.d.mts +0 -39
- package/dist/adapt.d.ts +0 -39
- package/dist/adapt.js +0 -59
- package/dist/adapt.mjs +0 -57
- package/dist/composed-policy.d.mts +0 -115
- package/dist/composed-policy.d.ts +0 -115
- package/dist/composed-policy.js +0 -103
- package/dist/composed-policy.mjs +0 -97
- package/dist/config-CleTeeoW.d.mts +0 -233
- package/dist/config-XMOIkxFN.d.ts +0 -233
- package/dist/create-middleware.d.mts +0 -22
- package/dist/create-middleware.d.ts +0 -22
- package/dist/create-middleware.js +0 -34
- package/dist/create-middleware.mjs +0 -31
- package/dist/edge/index.d.mts +0 -112
- package/dist/edge/index.d.ts +0 -112
- package/dist/edge/index.js +0 -277
- package/dist/edge/index.mjs +0 -275
- package/dist/edge-runtime-loader.d.mts +0 -77
- package/dist/edge-runtime-loader.d.ts +0 -77
- package/dist/edge-runtime-loader.js +0 -242
- package/dist/edge-runtime-loader.mjs +0 -235
- package/dist/edge-wasm-middleware.d.mts +0 -62
- package/dist/edge-wasm-middleware.d.ts +0 -62
- package/dist/edge-wasm-middleware.js +0 -26
- package/dist/edge-wasm-middleware.mjs +0 -22
- package/dist/middleware.d.mts +0 -45
- package/dist/middleware.d.ts +0 -45
- package/dist/middleware.js +0 -19
- package/dist/middleware.mjs +0 -15
- package/dist/nodejs-wasm-loader.d.mts +0 -41
- package/dist/nodejs-wasm-loader.d.ts +0 -41
- package/dist/nodejs-wasm-loader.js +0 -36
- package/dist/nodejs-wasm-loader.mjs +0 -30
- package/dist/policy.d.mts +0 -162
- package/dist/policy.d.ts +0 -162
- package/dist/policy.js +0 -198
- package/dist/policy.mjs +0 -174
- package/dist/session-tracker.d.mts +0 -55
- package/dist/session-tracker.d.ts +0 -55
- package/dist/session-tracker.js +0 -172
- package/dist/session-tracker.mjs +0 -169
- package/dist/translate.d.mts +0 -63
- package/dist/translate.d.ts +0 -63
- package/dist/translate.js +0 -44
- package/dist/translate.mjs +0 -42
- package/dist/types-Chgi5TFC.d.mts +0 -105
- package/dist/types-Chgi5TFC.d.ts +0 -105
- package/dist/wasm-setup.d.mts +0 -46
- package/dist/wasm-setup.d.ts +0 -46
- package/dist/wasm-setup.js +0 -122
- package/dist/wasm-setup.mjs +0 -118
- package/wasm/agentshield_wasm.d.ts +0 -479
- package/wasm/agentshield_wasm.js +0 -1536
- package/wasm/agentshield_wasm_bg.wasm +0 -0
- package/wasm/package.json +0 -30
- package/wasm.d.ts +0 -21
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
const require_adapt = require('./adapt-CCSKGjVH.js');
|
|
2
|
+
const require_utils = require('./utils-dyFxqlFI.js');
|
|
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
|
+
let _vercel_functions = require("@vercel/functions");
|
|
6
|
+
let next_server_js = require("next/server.js");
|
|
7
|
+
let _kya_os_checkpoint_shared_policy_enforcement = require("@kya-os/checkpoint-shared/policy/enforcement");
|
|
8
|
+
let _kya_os_checkpoint_shared_kya_http = require("@kya-os/checkpoint-shared/kya-http");
|
|
9
|
+
|
|
10
|
+
//#region src/responses/agent-instruction.ts
|
|
11
|
+
/**
|
|
12
|
+
* Agent Instruction Response Builder (Next.js)
|
|
13
|
+
*
|
|
14
|
+
* Tells an AI agent where to send its user to complete consent / connect,
|
|
15
|
+
* via a machine-parseable Link header + JSON body.
|
|
16
|
+
*
|
|
17
|
+
* **Dual envelope.** By default this is a 401 instruction response. AI-agent fetchers (Claude-User
|
|
18
|
+
* WebFetch, ChatGPT) collapse 4xx responses and never surface the body to
|
|
19
|
+
* the LLM, so the instruction is invisible. When the caller is a
|
|
20
|
+
* cooperative, self-identifying agent (selected upstream via
|
|
21
|
+
* `serveBodyReadable200`), pass `{ bodyReadable200: true }` to serve the
|
|
22
|
+
* SAME body at HTTP 200 with NO `WWW-Authenticate` (a 200 + WWW-Authenticate
|
|
23
|
+
* is reinterpreted as 401 by some fetchers); the consent URL stays in the
|
|
24
|
+
* body + the `KYA-Auth-Url`/`Link` hint headers. This also realigns
|
|
25
|
+
* TS-instruct (was 401-only) with .NET-instruct (200).
|
|
26
|
+
*
|
|
27
|
+
* Envelope selection is a cooperative-UX bridge, NOT an access control —
|
|
28
|
+
* the authoritative consent target is the body `user_action_required.url`;
|
|
29
|
+
* the `KYA-Auth-Url`/`Link` headers are unsigned hints.
|
|
30
|
+
*
|
|
31
|
+
* This is the in-app counterpart to the Cloudflare Gateway's builder at
|
|
32
|
+
* `apps/web/workers/gateway/src/responses/agent-instruction.ts`. The body
|
|
33
|
+
* is kept in sync so LLM and MCP clients see identical behavior whether a
|
|
34
|
+
* site is protected by the gateway or by the Next.js middleware.
|
|
35
|
+
*
|
|
36
|
+
* Implements RFC 8288 Link discovery. It deliberately emits no
|
|
37
|
+
* `WWW-Authenticate`; only a registered policy Challenge may emit the canonical
|
|
38
|
+
* Delegation authentication fields.
|
|
39
|
+
*
|
|
40
|
+
* @see ../../apps/web/workers/gateway/src/responses/agent-instruction.ts
|
|
41
|
+
*/
|
|
42
|
+
const MCP_I_DOCS_URL = "https://kya.vouched.id/docs/enforce/kya-os-enforcement";
|
|
43
|
+
const DEFAULT_CONNECT_PATH = "/connect";
|
|
44
|
+
/**
|
|
45
|
+
* Build an "agent must connect" response for the Next.js middleware.
|
|
46
|
+
*
|
|
47
|
+
* The caller is responsible for deciding *when* to call this (typically when
|
|
48
|
+
* `decision.action === 'redirect'` or `'instruct'`) and *which envelope* via
|
|
49
|
+
* `options.bodyReadable200`. This helper only owns the response shape.
|
|
50
|
+
*/
|
|
51
|
+
function buildAgentInstructionResponse(request, decision, redirectUrl, options) {
|
|
52
|
+
const resolved = resolveUrl(redirectUrl ?? DEFAULT_CONNECT_PATH, request.url);
|
|
53
|
+
const agentName = decision.agentName || decision.agentType || "unknown";
|
|
54
|
+
if (!resolved.searchParams.has("agent")) resolved.searchParams.set("agent", agentName.toLowerCase());
|
|
55
|
+
const authUrl = resolved.toString();
|
|
56
|
+
const hostname = require_utils.safeHostname(request.url);
|
|
57
|
+
const body = {
|
|
58
|
+
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.`,
|
|
59
|
+
user_action_required: {
|
|
60
|
+
action: `Connect securely to ${hostname}`,
|
|
61
|
+
url: authUrl,
|
|
62
|
+
reason: `${hostname} checks AI assistants before they connect. Open the link to give your assistant a verified key.`
|
|
63
|
+
},
|
|
64
|
+
mcp_i: {
|
|
65
|
+
version: "1.0",
|
|
66
|
+
action: "authenticate",
|
|
67
|
+
authorization_url: authUrl,
|
|
68
|
+
flow: {
|
|
69
|
+
type: "oauth2_delegation",
|
|
70
|
+
steps: [
|
|
71
|
+
"1. Direct your user to the authorization_url",
|
|
72
|
+
"2. User reviews requested scopes and grants consent",
|
|
73
|
+
"3. Receive delegation credential (JWT)",
|
|
74
|
+
"4. Include credential in KYA-Delegation header",
|
|
75
|
+
"5. Retry this request with the proof"
|
|
76
|
+
]
|
|
77
|
+
},
|
|
78
|
+
retry_instructions: {
|
|
79
|
+
header: "KYA-Delegation",
|
|
80
|
+
format: "JWT delegation credential from authorization flow"
|
|
81
|
+
},
|
|
82
|
+
documentation: MCP_I_DOCS_URL
|
|
83
|
+
},
|
|
84
|
+
error: "mcp_authentication_required",
|
|
85
|
+
code: "AGENT_REQUIRES_DELEGATION",
|
|
86
|
+
detection: {
|
|
87
|
+
agent_type: decision.agentType || "ai_agent",
|
|
88
|
+
agent_name: decision.agentName || "Unknown Agent",
|
|
89
|
+
confidence: decision.confidence
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
const bodyReadable200 = options?.bodyReadable200 ?? false;
|
|
93
|
+
const response = next_server_js.NextResponse.json(body, { status: bodyReadable200 ? 200 : 401 });
|
|
94
|
+
response.headers.set("Link", `<${authUrl}>; rel="kya-authorize", <${MCP_I_DOCS_URL}>; rel="help"`);
|
|
95
|
+
response.headers.set("KYA-Auth-Required", "true");
|
|
96
|
+
response.headers.set("KYA-Auth-Url", authUrl);
|
|
97
|
+
response.headers.set("KYA-Action", "instruct");
|
|
98
|
+
response.headers.set("KYA-Detected-Agent", agentName);
|
|
99
|
+
response.headers.set("KYA-Confidence", decision.confidence.toString());
|
|
100
|
+
response.headers.set("Cache-Control", "no-store");
|
|
101
|
+
return response;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Resolve a URL that may be absolute or a same-origin path.
|
|
105
|
+
* Falls back to `/connect` on the request origin if parsing fails.
|
|
106
|
+
*/
|
|
107
|
+
function resolveUrl(target, baseUrl) {
|
|
108
|
+
try {
|
|
109
|
+
return new URL(target, baseUrl);
|
|
110
|
+
} catch {
|
|
111
|
+
return new URL(DEFAULT_CONNECT_PATH, baseUrl);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region src/api-middleware.ts
|
|
117
|
+
/**
|
|
118
|
+
* API-based Checkpoint Middleware for Next.js
|
|
119
|
+
*
|
|
120
|
+
* This middleware uses the Checkpoint API for detection and enforcement,
|
|
121
|
+
* instead of running detection locally. This approach:
|
|
122
|
+
*
|
|
123
|
+
* 1. Works reliably in Edge Runtime (no WASM loading issues)
|
|
124
|
+
* 2. Ensures consistent detection across all platforms
|
|
125
|
+
* 3. Applies centralized policies from the dashboard
|
|
126
|
+
* 4. Supports deny lists, thresholds, and path rules
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* ```typescript
|
|
130
|
+
* // middleware.ts
|
|
131
|
+
* import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';
|
|
132
|
+
*
|
|
133
|
+
* export default withCheckpointApi({
|
|
134
|
+
* apiKey: process.env.CHECKPOINT_API_KEY!,
|
|
135
|
+
* // Optional overrides:
|
|
136
|
+
* onBlock: 'redirect', // 'block' | 'redirect' | 'challenge'
|
|
137
|
+
* redirectUrl: '/blocked',
|
|
138
|
+
* skipPaths: ['/api/health', '/_next/*'],
|
|
139
|
+
* });
|
|
140
|
+
*
|
|
141
|
+
* export const config = {
|
|
142
|
+
* matcher: ['/((?!_next/static|favicon.ico).*)'],
|
|
143
|
+
* };
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
/**
|
|
147
|
+
* Check if path should be skipped
|
|
148
|
+
*/
|
|
149
|
+
function shouldSkipPath(path, skipPaths) {
|
|
150
|
+
return skipPaths.some((pattern) => (0, _kya_os_checkpoint_shared_policy_enforcement.matchPath)(path, pattern));
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Check if path should be included (if includePaths is set)
|
|
154
|
+
*/
|
|
155
|
+
function shouldIncludePath(path, includePaths) {
|
|
156
|
+
if (!includePaths || includePaths.length === 0) return true;
|
|
157
|
+
return includePaths.some((pattern) => (0, _kya_os_checkpoint_shared_policy_enforcement.matchPath)(path, pattern));
|
|
158
|
+
}
|
|
159
|
+
/** The npm package this middleware ships in (package.json `name`, pinned by a unit test). */
|
|
160
|
+
const SDK_NAME = "@kya-os/checkpoint-nextjs";
|
|
161
|
+
/**
|
|
162
|
+
* The gateway ran the engine, so its engine info is reported under the
|
|
163
|
+
* remote-engine name `checkpoint-remote`. Forwarding the gateway's own
|
|
164
|
+
* `checkpoint-worker-wasm` would make this install read as a DNS Gateway.
|
|
165
|
+
*/
|
|
166
|
+
function remoteEngineInfo(engine) {
|
|
167
|
+
return {
|
|
168
|
+
name: "checkpoint-remote",
|
|
169
|
+
version: engine.version,
|
|
170
|
+
rulesetHash: engine.rulesetHash,
|
|
171
|
+
rulesetVersion: engine.rulesetVersion,
|
|
172
|
+
...engine.buildSha ? { buildSha: engine.buildSha } : {}
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
/** The SDK's self-identification, or undefined when the build injected no version. */
|
|
176
|
+
function sdkSelfIdentification() {
|
|
177
|
+
const runtime = typeof process !== "undefined" && process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
|
|
178
|
+
return {
|
|
179
|
+
name: SDK_NAME,
|
|
180
|
+
version: "1.11.0",
|
|
181
|
+
runtime
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Build blocked response.
|
|
186
|
+
*
|
|
187
|
+
* When the policy attaches a `redirectUrl` (e.g. the dashboard's hosted
|
|
188
|
+
* /connect page), we still respect the `block` action but surface the URL to
|
|
189
|
+
* LLM clients so the user can recover: `Link` header + `user_action_required`
|
|
190
|
+
* in the JSON body. Status stays 403 — this is not an auth challenge, it's a
|
|
191
|
+
* blocked request with a recovery hint.
|
|
192
|
+
*/
|
|
193
|
+
function buildBlockedResponse(request, decision, config) {
|
|
194
|
+
const status = config.blockedResponse?.status ?? 403;
|
|
195
|
+
const message = config.blockedResponse?.message ?? decision.message ?? "Access denied";
|
|
196
|
+
const recoveryUrl = resolveRecoveryUrl(request, config.redirectUrl || decision.redirectUrl);
|
|
197
|
+
const body = {
|
|
198
|
+
error: message,
|
|
199
|
+
code: "AGENT_BLOCKED",
|
|
200
|
+
reason: decision.reason,
|
|
201
|
+
agentType: decision.agentType
|
|
202
|
+
};
|
|
203
|
+
if (recoveryUrl) {
|
|
204
|
+
const hostname = require_utils.safeHostname(request.url);
|
|
205
|
+
body.user_action_required = {
|
|
206
|
+
action: `Connect securely to ${hostname}`,
|
|
207
|
+
url: recoveryUrl,
|
|
208
|
+
reason: `${hostname} blocks unverified AI assistants. Open the link to give your assistant a verified key and try again.`
|
|
209
|
+
};
|
|
210
|
+
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.`;
|
|
211
|
+
}
|
|
212
|
+
const response = next_server_js.NextResponse.json(body, { status });
|
|
213
|
+
if (config.blockedResponse?.headers) for (const [key, value] of Object.entries(config.blockedResponse.headers)) response.headers.set(key, value);
|
|
214
|
+
if (recoveryUrl) {
|
|
215
|
+
response.headers.set("Link", `<${recoveryUrl}>; rel="kya-authorize"`);
|
|
216
|
+
response.headers.set("KYA-Auth-Url", recoveryUrl);
|
|
217
|
+
}
|
|
218
|
+
response.headers.set("KYA-Action", decision.action);
|
|
219
|
+
response.headers.set("KYA-Reason", decision.reason);
|
|
220
|
+
return response;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* A policy `requestsPerMinute` throttle arrives as `block` with reason
|
|
224
|
+
* `rate_limited`. It is a 429 with a retry hint, not an access denial: no
|
|
225
|
+
* "unverified assistant" recovery copy and no redirect.
|
|
226
|
+
*/
|
|
227
|
+
function buildRateLimitedResponse(decision, config) {
|
|
228
|
+
const retryAfter = decision.metadata?.rateLimit?.retryAfterSeconds;
|
|
229
|
+
const response = next_server_js.NextResponse.json({
|
|
230
|
+
error: decision.message ?? "Rate limit exceeded",
|
|
231
|
+
code: "RATE_LIMITED",
|
|
232
|
+
reason: decision.reason,
|
|
233
|
+
agentType: decision.agentType,
|
|
234
|
+
...retryAfter !== void 0 ? { retryAfterSeconds: retryAfter } : {}
|
|
235
|
+
}, { status: 429 });
|
|
236
|
+
for (const [key, value] of Object.entries(config.blockedResponse?.headers ?? {})) response.headers.set(key, value);
|
|
237
|
+
if (retryAfter !== void 0) response.headers.set("Retry-After", String(retryAfter));
|
|
238
|
+
response.headers.set("KYA-Action", decision.action);
|
|
239
|
+
response.headers.set("KYA-Reason", decision.reason);
|
|
240
|
+
return response;
|
|
241
|
+
}
|
|
242
|
+
function resolveRecoveryUrl(request, target) {
|
|
243
|
+
if (!target) return void 0;
|
|
244
|
+
try {
|
|
245
|
+
return new URL(target, request.url).toString();
|
|
246
|
+
} catch {
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Build redirect response
|
|
252
|
+
*/
|
|
253
|
+
function buildRedirectResponse(request, decision, config) {
|
|
254
|
+
const redirectUrl = config.redirectUrl || decision.redirectUrl || "/blocked";
|
|
255
|
+
const url = new URL(redirectUrl, request.url);
|
|
256
|
+
url.searchParams.set("reason", decision.reason);
|
|
257
|
+
if (decision.agentType) url.searchParams.set("agent", decision.agentType);
|
|
258
|
+
return next_server_js.NextResponse.redirect(url);
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Create Checkpoint middleware with API-based detection
|
|
262
|
+
*
|
|
263
|
+
* @example
|
|
264
|
+
* ```typescript
|
|
265
|
+
* // middleware.ts
|
|
266
|
+
* import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';
|
|
267
|
+
*
|
|
268
|
+
* export default withCheckpointApi({
|
|
269
|
+
* onBlock: 'block',
|
|
270
|
+
* skipPaths: ['/api/health'],
|
|
271
|
+
* });
|
|
272
|
+
* ```
|
|
273
|
+
*/
|
|
274
|
+
function withCheckpointApi(config = {}) {
|
|
275
|
+
let client = null;
|
|
276
|
+
const getClient = () => {
|
|
277
|
+
if (!client) client = require_api_client.getCheckpointApiClient({
|
|
278
|
+
apiKey: config.apiKey,
|
|
279
|
+
baseUrl: config.apiUrl,
|
|
280
|
+
useEdge: config.useEdge,
|
|
281
|
+
timeout: config.timeout,
|
|
282
|
+
debug: config.debug
|
|
283
|
+
});
|
|
284
|
+
return client;
|
|
285
|
+
};
|
|
286
|
+
const skipPaths = [...[
|
|
287
|
+
"/_next/static/**",
|
|
288
|
+
"/_next/image/**",
|
|
289
|
+
"/favicon.ico",
|
|
290
|
+
"/robots.txt",
|
|
291
|
+
"/sitemap.xml"
|
|
292
|
+
], ...config.skipPaths || []];
|
|
293
|
+
const faultResponse = (request) => config.failOpen === true && !(0, _kya_os_checkpoint_shared_kya_http.requestPresentedCredential)(request.headers) ? failOpenResponse() : require_adapt.failClosedResponse();
|
|
294
|
+
return async function middleware(request) {
|
|
295
|
+
const path = request.nextUrl.pathname;
|
|
296
|
+
const startTime = Date.now();
|
|
297
|
+
if (shouldSkipPath(path, skipPaths)) return next_server_js.NextResponse.next();
|
|
298
|
+
if (!shouldIncludePath(path, config.includePaths)) return next_server_js.NextResponse.next();
|
|
299
|
+
try {
|
|
300
|
+
const client = getClient();
|
|
301
|
+
const userAgent = request.headers.get("user-agent") || void 0;
|
|
302
|
+
const ipAddress = require_utils.getClientIp(request, config.clientIpPolicy);
|
|
303
|
+
const result = await client.enforce({
|
|
304
|
+
headers: Object.fromEntries(request.headers.entries()),
|
|
305
|
+
userAgent,
|
|
306
|
+
ipAddress,
|
|
307
|
+
path,
|
|
308
|
+
url: request.url,
|
|
309
|
+
method: request.method,
|
|
310
|
+
requestId: request.headers.get("x-request-id") || void 0,
|
|
311
|
+
options: { includeDetectionResult: true }
|
|
312
|
+
});
|
|
313
|
+
if (!result.success || !result.data) {
|
|
314
|
+
if (config.debug) console.warn("[Checkpoint] API error:", result.error);
|
|
315
|
+
return faultResponse(request);
|
|
316
|
+
}
|
|
317
|
+
const decision = result.data.decision;
|
|
318
|
+
if (config.debug) console.log("[Checkpoint] Decision:", {
|
|
319
|
+
path,
|
|
320
|
+
action: decision.action,
|
|
321
|
+
isAgent: decision.isAgent,
|
|
322
|
+
confidence: decision.confidence,
|
|
323
|
+
agentName: decision.agentName,
|
|
324
|
+
detectionMethod: result.data.detection?.detectionMethod || "not-included",
|
|
325
|
+
processingTimeMs: Date.now() - startTime
|
|
326
|
+
});
|
|
327
|
+
if (client.isUsingEdge() && result.data.detection) (0, _vercel_functions.waitUntil)(client.logDetection({
|
|
328
|
+
detection: result.data.detection,
|
|
329
|
+
context: {
|
|
330
|
+
userAgent,
|
|
331
|
+
ipAddress,
|
|
332
|
+
path,
|
|
333
|
+
url: request.url,
|
|
334
|
+
method: request.method
|
|
335
|
+
},
|
|
336
|
+
source: "middleware",
|
|
337
|
+
enforcement: { action: decision.action },
|
|
338
|
+
engine: result.data.engine ? remoteEngineInfo(result.data.engine) : void 0,
|
|
339
|
+
sdk: sdkSelfIdentification()
|
|
340
|
+
}).catch((err) => {
|
|
341
|
+
if (config.debug) console.error("[Checkpoint] Log detection failed:", err);
|
|
342
|
+
}));
|
|
343
|
+
if (decision.isAgent && config.onAgentDetected) try {
|
|
344
|
+
await config.onAgentDetected(request, decision);
|
|
345
|
+
} catch (error) {
|
|
346
|
+
if (config.debug) console.error("[Checkpoint] onAgentDetected callback failed:", error);
|
|
347
|
+
}
|
|
348
|
+
const redirectMode = config.redirectMode ?? "instruct";
|
|
349
|
+
switch (decision.action) {
|
|
350
|
+
case "block":
|
|
351
|
+
if (config.customBlockedResponse) return await config.customBlockedResponse(request, decision);
|
|
352
|
+
if (decision.reason === "rate_limited") return buildRateLimitedResponse(decision, config);
|
|
353
|
+
if (config.onBlock === "redirect") return buildRedirectResponse(request, decision, config);
|
|
354
|
+
return buildBlockedResponse(request, decision, config);
|
|
355
|
+
case "redirect":
|
|
356
|
+
case "instruct": {
|
|
357
|
+
if (redirectMode === "http" && decision.action === "redirect") return buildRedirectResponse(request, decision, config);
|
|
358
|
+
const targetUrl = config.redirectUrl || decision.redirectUrl;
|
|
359
|
+
const bodyReadable200 = (0, _kya_os_checkpoint_shared_host_adapter.selectBodyReadable200)(config.delegationChallengeMode ?? "negotiated", request.headers, result.data.detection?.detectionClass, result.data.detection?.isAgent ?? false);
|
|
360
|
+
return buildAgentInstructionResponse(request, decision, targetUrl, { bodyReadable200 });
|
|
361
|
+
}
|
|
362
|
+
case "challenge": return buildRedirectResponse(request, decision, config);
|
|
363
|
+
default: {
|
|
364
|
+
const response = next_server_js.NextResponse.next();
|
|
365
|
+
if (decision.isAgent) {
|
|
366
|
+
response.headers.set("KYA-Detected", "true");
|
|
367
|
+
response.headers.set("KYA-Confidence", decision.confidence.toString());
|
|
368
|
+
if (decision.agentName) response.headers.set("KYA-Agent", decision.agentName);
|
|
369
|
+
}
|
|
370
|
+
return response;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
} catch (error) {
|
|
374
|
+
if (config.debug) console.error("[Checkpoint] Middleware error:", error);
|
|
375
|
+
return faultResponse(request);
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
function failOpenResponse() {
|
|
380
|
+
const response = next_server_js.NextResponse.next();
|
|
381
|
+
response.headers.set("KYA-Failopen", "true");
|
|
382
|
+
return response;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
//#endregion
|
|
386
|
+
Object.defineProperty(exports, 'withCheckpointApi', {
|
|
387
|
+
enumerable: true,
|
|
388
|
+
get: function () {
|
|
389
|
+
return withCheckpointApi;
|
|
390
|
+
}
|
|
391
|
+
});
|