@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.
Files changed (156) hide show
  1. package/CHANGELOG.md +322 -0
  2. package/README.md +205 -31
  3. package/dist/adapt-BdQ9R7Iw.mjs +97 -0
  4. package/dist/adapt-BdQ9R7Iw.mjs.map +1 -0
  5. package/dist/adapt-CCSKGjVH.js +107 -0
  6. package/dist/api-client-JHOrRUA_.d.mts +222 -0
  7. package/dist/api-client-JHOrRUA_.d.mts.map +1 -0
  8. package/dist/api-client-JHOrRUA_.d.ts +222 -0
  9. package/dist/api-client-JHOrRUA_.d.ts.map +1 -0
  10. package/dist/api-client.d.mts +2 -213
  11. package/dist/api-client.d.ts +2 -213
  12. package/dist/api-client.js +221 -206
  13. package/dist/api-client.mjs +222 -202
  14. package/dist/api-client.mjs.map +1 -0
  15. package/dist/api-middleware-BWjokNis.d.mts +131 -0
  16. package/dist/api-middleware-BWjokNis.d.mts.map +1 -0
  17. package/dist/api-middleware-Bf3xmM9W.js +391 -0
  18. package/dist/api-middleware-C-ngFX_8.mjs +387 -0
  19. package/dist/api-middleware-C-ngFX_8.mjs.map +1 -0
  20. package/dist/api-middleware-DyLDqOYF.d.ts +131 -0
  21. package/dist/api-middleware-DyLDqOYF.d.ts.map +1 -0
  22. package/dist/api-middleware.d.mts +2 -166
  23. package/dist/api-middleware.d.ts +2 -166
  24. package/dist/api-middleware.js +3 -526
  25. package/dist/api-middleware.mjs +2 -521
  26. package/dist/cedar-wasm.d.mts +20 -0
  27. package/dist/cedar-wasm.d.mts.map +1 -0
  28. package/dist/cedar-wasm.d.ts +19 -0
  29. package/dist/cedar-wasm.d.ts.map +1 -0
  30. package/dist/cedar-wasm.js +24 -0
  31. package/dist/cedar-wasm.mjs +23 -0
  32. package/dist/cedar-wasm.mjs.map +1 -0
  33. package/dist/config-CPP1RV0f.d.mts +291 -0
  34. package/dist/config-CPP1RV0f.d.mts.map +1 -0
  35. package/dist/config-DVgOFxJs.d.ts +291 -0
  36. package/dist/config-DVgOFxJs.d.ts.map +1 -0
  37. package/dist/engine-wasm.d.mts +20 -0
  38. package/dist/engine-wasm.d.mts.map +1 -0
  39. package/dist/engine-wasm.d.ts +19 -0
  40. package/dist/engine-wasm.d.ts.map +1 -0
  41. package/dist/engine-wasm.js +24 -0
  42. package/dist/engine-wasm.mjs +23 -0
  43. package/dist/engine-wasm.mjs.map +1 -0
  44. package/dist/index-edge.d.mts +8 -0
  45. package/dist/index-edge.d.ts +8 -0
  46. package/dist/index-edge.js +14 -0
  47. package/dist/index-edge.mjs +7 -0
  48. package/dist/index.d.mts +8 -17
  49. package/dist/index.d.ts +8 -17
  50. package/dist/index.js +36 -1275
  51. package/dist/index.mjs +29 -1234
  52. package/dist/index.mjs.map +1 -0
  53. package/dist/middleware-bundler.d.mts +6 -12
  54. package/dist/middleware-bundler.d.mts.map +1 -0
  55. package/dist/middleware-bundler.d.ts +6 -12
  56. package/dist/middleware-bundler.d.ts.map +1 -0
  57. package/dist/middleware-bundler.js +12 -350
  58. package/dist/middleware-bundler.mjs +11 -347
  59. package/dist/middleware-bundler.mjs.map +1 -0
  60. package/dist/middleware-core-B0jf5_Hm.mjs +264 -0
  61. package/dist/middleware-core-B0jf5_Hm.mjs.map +1 -0
  62. package/dist/middleware-core-Bol44X9C.d.ts +17 -0
  63. package/dist/middleware-core-Bol44X9C.d.ts.map +1 -0
  64. package/dist/middleware-core-CMc-2QkU.js +274 -0
  65. package/dist/middleware-core-DycsbHUd.d.mts +17 -0
  66. package/dist/middleware-core-DycsbHUd.d.mts.map +1 -0
  67. package/dist/middleware-edge.d.mts +16 -14
  68. package/dist/middleware-edge.d.mts.map +1 -0
  69. package/dist/middleware-edge.d.ts +16 -14
  70. package/dist/middleware-edge.d.ts.map +1 -0
  71. package/dist/middleware-edge.js +94 -355
  72. package/dist/middleware-edge.mjs +90 -347
  73. package/dist/middleware-edge.mjs.map +1 -0
  74. package/dist/middleware-node-context-591KsiYg.js +39 -0
  75. package/dist/middleware-node-context-D_ZyUEcA.mjs +35 -0
  76. package/dist/middleware-node-context-D_ZyUEcA.mjs.map +1 -0
  77. package/dist/middleware-node.d.mts +10 -25
  78. package/dist/middleware-node.d.mts.map +1 -0
  79. package/dist/middleware-node.d.ts +10 -25
  80. package/dist/middleware-node.d.ts.map +1 -0
  81. package/dist/middleware-node.js +21 -351
  82. package/dist/middleware-node.mjs +19 -347
  83. package/dist/middleware-node.mjs.map +1 -0
  84. package/dist/posture-outcome-Ccujx_9V.d.mts +14 -0
  85. package/dist/posture-outcome-Ccujx_9V.d.mts.map +1 -0
  86. package/dist/posture-outcome-Ccujx_9V.d.ts +14 -0
  87. package/dist/posture-outcome-Ccujx_9V.d.ts.map +1 -0
  88. package/dist/posture-outcome-DQ4fdMfq.mjs +21 -0
  89. package/dist/posture-outcome-DQ4fdMfq.mjs.map +1 -0
  90. package/dist/posture-outcome-DddsJtL8.js +25 -0
  91. package/dist/public-api-CYsHrTQI.d.ts +5 -0
  92. package/dist/public-api-DkG7pRE0.d.mts +5 -0
  93. package/dist/rolldown-runtime-C24Yb2bl.js +33 -0
  94. package/dist/utils-Cnwg0VrY.mjs +88 -0
  95. package/dist/utils-Cnwg0VrY.mjs.map +1 -0
  96. package/dist/utils-dyFxqlFI.js +104 -0
  97. package/package.json +31 -66
  98. package/EDGE_RUNTIME_WASM_SETUP.md +0 -342
  99. package/bin/setup-edge-wasm.js +0 -513
  100. package/dist/adapt.d.mts +0 -39
  101. package/dist/adapt.d.ts +0 -39
  102. package/dist/adapt.js +0 -59
  103. package/dist/adapt.mjs +0 -57
  104. package/dist/composed-policy.d.mts +0 -115
  105. package/dist/composed-policy.d.ts +0 -115
  106. package/dist/composed-policy.js +0 -103
  107. package/dist/composed-policy.mjs +0 -97
  108. package/dist/config-CleTeeoW.d.mts +0 -233
  109. package/dist/config-XMOIkxFN.d.ts +0 -233
  110. package/dist/create-middleware.d.mts +0 -22
  111. package/dist/create-middleware.d.ts +0 -22
  112. package/dist/create-middleware.js +0 -34
  113. package/dist/create-middleware.mjs +0 -31
  114. package/dist/edge/index.d.mts +0 -112
  115. package/dist/edge/index.d.ts +0 -112
  116. package/dist/edge/index.js +0 -277
  117. package/dist/edge/index.mjs +0 -275
  118. package/dist/edge-runtime-loader.d.mts +0 -77
  119. package/dist/edge-runtime-loader.d.ts +0 -77
  120. package/dist/edge-runtime-loader.js +0 -242
  121. package/dist/edge-runtime-loader.mjs +0 -235
  122. package/dist/edge-wasm-middleware.d.mts +0 -62
  123. package/dist/edge-wasm-middleware.d.ts +0 -62
  124. package/dist/edge-wasm-middleware.js +0 -26
  125. package/dist/edge-wasm-middleware.mjs +0 -22
  126. package/dist/middleware.d.mts +0 -45
  127. package/dist/middleware.d.ts +0 -45
  128. package/dist/middleware.js +0 -19
  129. package/dist/middleware.mjs +0 -15
  130. package/dist/nodejs-wasm-loader.d.mts +0 -41
  131. package/dist/nodejs-wasm-loader.d.ts +0 -41
  132. package/dist/nodejs-wasm-loader.js +0 -36
  133. package/dist/nodejs-wasm-loader.mjs +0 -30
  134. package/dist/policy.d.mts +0 -162
  135. package/dist/policy.d.ts +0 -162
  136. package/dist/policy.js +0 -198
  137. package/dist/policy.mjs +0 -174
  138. package/dist/session-tracker.d.mts +0 -55
  139. package/dist/session-tracker.d.ts +0 -55
  140. package/dist/session-tracker.js +0 -172
  141. package/dist/session-tracker.mjs +0 -169
  142. package/dist/translate.d.mts +0 -63
  143. package/dist/translate.d.ts +0 -63
  144. package/dist/translate.js +0 -44
  145. package/dist/translate.mjs +0 -42
  146. package/dist/types-Chgi5TFC.d.mts +0 -105
  147. package/dist/types-Chgi5TFC.d.ts +0 -105
  148. package/dist/wasm-setup.d.mts +0 -46
  149. package/dist/wasm-setup.d.ts +0 -46
  150. package/dist/wasm-setup.js +0 -122
  151. package/dist/wasm-setup.mjs +0 -118
  152. package/wasm/agentshield_wasm.d.ts +0 -479
  153. package/wasm/agentshield_wasm.js +0 -1536
  154. package/wasm/agentshield_wasm_bg.wasm +0 -0
  155. package/wasm/package.json +0 -30
  156. package/wasm.d.ts +0 -21
@@ -1,522 +1,3 @@
1
- import { NextResponse } from 'next/server';
2
- import { selectBodyReadable200, matchPath, resolveClientIp } from '@kya-os/checkpoint-shared';
3
- import { waitUntil } from '@vercel/functions';
1
+ import { t as withCheckpointApi } from "./api-middleware-C-ngFX_8.mjs";
4
2
 
5
- // src/api-middleware.ts
6
-
7
- // src/api-client.ts
8
- var DEFAULT_BASE_URL = "https://kya.vouched.id";
9
- var EDGE_DETECT_URL = "https://detect.checkpoint-gateway.ai";
10
- var DEFAULT_TIMEOUT = 5e3;
11
- var CheckpointApiClient = class {
12
- apiKey;
13
- baseUrl;
14
- useEdge;
15
- timeout;
16
- debug;
17
- constructor(config) {
18
- if (!config.apiKey) {
19
- throw new Error("Checkpoint API key is required");
20
- }
21
- this.apiKey = config.apiKey;
22
- this.useEdge = config.useEdge !== false;
23
- this.baseUrl = config.baseUrl || (this.useEdge ? EDGE_DETECT_URL : DEFAULT_BASE_URL);
24
- this.timeout = config.timeout || DEFAULT_TIMEOUT;
25
- this.debug = config.debug || false;
26
- }
27
- /**
28
- * Call the enforce API to check if a request should be allowed
29
- */
30
- async enforce(input) {
31
- const startTime = Date.now();
32
- try {
33
- const controller = new AbortController();
34
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
35
- try {
36
- const endpoint = this.useEdge ? `${this.baseUrl}/__detect/enforce` : `${this.baseUrl}/api/v1/enforce`;
37
- const response = await fetch(endpoint, {
38
- method: "POST",
39
- headers: {
40
- "Content-Type": "application/json",
41
- Authorization: `Bearer ${this.apiKey}`,
42
- "X-Request-ID": input.requestId || crypto.randomUUID()
43
- },
44
- body: JSON.stringify(input),
45
- signal: controller.signal
46
- });
47
- clearTimeout(timeoutId);
48
- const data = await response.json();
49
- if (this.debug) {
50
- console.log("[Checkpoint] Enforce response:", {
51
- status: response.status,
52
- action: data.data?.decision.action,
53
- processingTimeMs: Date.now() - startTime
54
- });
55
- }
56
- if (!response.ok) {
57
- return {
58
- success: false,
59
- error: {
60
- code: `HTTP_${response.status}`,
61
- message: data.error?.message || `HTTP error: ${response.status}`
62
- }
63
- };
64
- }
65
- return data;
66
- } catch (error) {
67
- clearTimeout(timeoutId);
68
- throw error;
69
- }
70
- } catch (error) {
71
- if (error instanceof Error && error.name === "AbortError") {
72
- if (this.debug) {
73
- console.warn("[Checkpoint] Request timed out");
74
- }
75
- return {
76
- success: false,
77
- error: {
78
- code: "TIMEOUT",
79
- message: `Request timed out after ${this.timeout}ms`
80
- }
81
- };
82
- }
83
- if (this.debug) {
84
- console.error("[Checkpoint] Request failed:", error);
85
- }
86
- return {
87
- success: false,
88
- error: {
89
- code: "NETWORK_ERROR",
90
- message: error instanceof Error ? error.message : "Network request failed"
91
- }
92
- };
93
- }
94
- }
95
- /**
96
- * Quick check - returns just the action without full response parsing
97
- * Useful for very fast middleware that just needs allow/block
98
- */
99
- async quickCheck(input) {
100
- const result = await this.enforce(input);
101
- if (!result.success || !result.data) {
102
- return {
103
- action: "allow",
104
- error: result.error?.message
105
- };
106
- }
107
- return {
108
- action: result.data.decision.action
109
- };
110
- }
111
- /**
112
- * Check if this client is using edge detection (Gateway Worker)
113
- */
114
- isUsingEdge() {
115
- return this.useEdge;
116
- }
117
- /**
118
- * Log a detection result to AgentShield database.
119
- * Use after Gateway Worker detection to persist results.
120
- * Fire-and-forget - returns immediately without waiting for DB write.
121
- *
122
- * @example
123
- * ```typescript
124
- * // After receiving Gateway response
125
- * if (client.isUsingEdge() && response.data?.detection) {
126
- * client.logDetection({
127
- * detection: response.data.detection,
128
- * context: { userAgent, ipAddress, path, url, method }
129
- * }).catch(err => console.error('Log failed:', err));
130
- * }
131
- * ```
132
- */
133
- async logDetection(input) {
134
- const logEndpoint = this.useEdge ? `${DEFAULT_BASE_URL}/api/v1/log-detection` : `${this.baseUrl}/api/v1/log-detection`;
135
- try {
136
- const controller = new AbortController();
137
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
138
- try {
139
- const response = await fetch(logEndpoint, {
140
- method: "POST",
141
- headers: {
142
- "Content-Type": "application/json",
143
- Authorization: `Bearer ${this.apiKey}`
144
- },
145
- body: JSON.stringify({
146
- detection: {
147
- isAgent: input.detection.isAgent,
148
- confidence: input.detection.confidence,
149
- agentName: input.detection.agentName,
150
- agentType: input.detection.agentType,
151
- detectionClass: input.detection.detectionClass,
152
- verificationMethod: input.detection.verificationMethod,
153
- reasons: input.detection.reasons
154
- },
155
- context: input.context,
156
- source: input.source || "gateway"
157
- }),
158
- signal: controller.signal
159
- });
160
- clearTimeout(timeoutId);
161
- if (!response.ok && this.debug) {
162
- console.warn("[Checkpoint] Log detection returned non-2xx:", response.status);
163
- }
164
- } catch (error) {
165
- clearTimeout(timeoutId);
166
- throw error;
167
- }
168
- } catch (error) {
169
- if (this.debug) {
170
- console.error("[Checkpoint] Log detection failed:", error);
171
- }
172
- throw error;
173
- }
174
- }
175
- };
176
- var clientInstances = /* @__PURE__ */ new Map();
177
- function resolveClientConfig(config) {
178
- const apiKey = config?.apiKey || process.env.CHECKPOINT_API_KEY;
179
- if (!apiKey) {
180
- throw new Error(
181
- "Checkpoint API key is required. Set CHECKPOINT_API_KEY environment variable or pass apiKey in config."
182
- );
183
- }
184
- return {
185
- apiKey,
186
- baseUrl: config?.baseUrl || process.env.CHECKPOINT_API_URL,
187
- // Default to edge detection unless explicitly disabled
188
- useEdge: config?.useEdge ?? process.env.CHECKPOINT_USE_EDGE !== "false",
189
- timeout: config?.timeout,
190
- debug: config?.debug || process.env.CHECKPOINT_DEBUG === "true"
191
- };
192
- }
193
- function clientCacheKey(config) {
194
- return JSON.stringify([
195
- config.apiKey,
196
- config.baseUrl ?? "",
197
- config.useEdge ?? true,
198
- config.timeout ?? DEFAULT_TIMEOUT,
199
- config.debug ?? false
200
- ]);
201
- }
202
- function getCheckpointApiClient(config) {
203
- const resolvedConfig = resolveClientConfig(config);
204
- const key = clientCacheKey(resolvedConfig);
205
- let clientInstance = clientInstances.get(key);
206
- if (!clientInstance) {
207
- clientInstance = new CheckpointApiClient(resolvedConfig);
208
- clientInstances.set(key, clientInstance);
209
- }
210
- return clientInstance;
211
- }
212
- function getClientIp(request, policy = { platform: "direct" }) {
213
- const frameworkAddress = request.ip;
214
- return resolveClientIp({ headers: request.headers, frameworkAddress, policy }).ip ?? void 0;
215
- }
216
- function safeHostname(url) {
217
- try {
218
- return new URL(url).hostname;
219
- } catch {
220
- return "this site";
221
- }
222
- }
223
-
224
- // src/responses/agent-instruction.ts
225
- var MCP_I_DOCS_URL = "https://kya.vouched.id/docs/enforce/kya-os-enforcement";
226
- var DEFAULT_CONNECT_PATH = "/connect";
227
- function buildAgentInstructionResponse(request, decision, redirectUrl, options) {
228
- const resolved = resolveUrl(redirectUrl ?? DEFAULT_CONNECT_PATH, request.url);
229
- const agentName = decision.agentName || decision.agentType || "unknown";
230
- if (!resolved.searchParams.has("agent")) {
231
- resolved.searchParams.set("agent", agentName.toLowerCase());
232
- }
233
- const authUrl = resolved.toString();
234
- const hostname = safeHostname(request.url);
235
- const body = {
236
- // Markdown-formatted so clients that render markdown (Claude Desktop,
237
- // ChatGPT web) surface the URL as a clickable link. Tone mirrors the
238
- // gateway response so messaging stays consistent across platforms.
239
- message: `I can't access ${hostname} yet \u2014 this site checks AI assistants at the front door.
240
-
241
- **To give me access, open this link:**
242
- [Connect securely to ${hostname}](${authUrl})
243
-
244
- It 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.`,
245
- user_action_required: {
246
- action: `Connect securely to ${hostname}`,
247
- url: authUrl,
248
- reason: `${hostname} checks AI assistants before they connect. Open the link to give your assistant a verified key.`
249
- },
250
- mcp_i: {
251
- version: "1.0",
252
- action: "authenticate",
253
- authorization_url: authUrl,
254
- flow: {
255
- type: "oauth2_delegation",
256
- steps: [
257
- "1. Direct your user to the authorization_url",
258
- "2. User reviews requested scopes and grants consent",
259
- "3. Receive delegation credential (JWT)",
260
- "4. Include credential in KYA-Delegation header",
261
- "5. Retry this request with the proof"
262
- ]
263
- },
264
- retry_instructions: {
265
- header: "KYA-Delegation",
266
- format: "JWT delegation credential from authorization flow"
267
- },
268
- documentation: MCP_I_DOCS_URL
269
- },
270
- error: "mcp_authentication_required",
271
- code: "AGENT_REQUIRES_DELEGATION",
272
- detection: {
273
- agent_type: decision.agentType || "ai_agent",
274
- agent_name: decision.agentName || "Unknown Agent",
275
- confidence: decision.confidence
276
- }
277
- };
278
- const bodyReadable200 = options?.bodyReadable200 ?? false;
279
- const response = NextResponse.json(body, { status: bodyReadable200 ? 200 : 401 });
280
- response.headers.set(
281
- "Link",
282
- `<${authUrl}>; rel="kya-authorize", <${MCP_I_DOCS_URL}>; rel="help"`
283
- );
284
- response.headers.set("KYA-Auth-Required", "true");
285
- response.headers.set("KYA-Auth-Url", authUrl);
286
- response.headers.set("KYA-Action", "instruct");
287
- response.headers.set("KYA-Detected-Agent", agentName);
288
- response.headers.set("KYA-Confidence", decision.confidence.toString());
289
- response.headers.set("Cache-Control", "no-store");
290
- return response;
291
- }
292
- function resolveUrl(target, baseUrl) {
293
- try {
294
- return new URL(target, baseUrl);
295
- } catch {
296
- return new URL(DEFAULT_CONNECT_PATH, baseUrl);
297
- }
298
- }
299
- function shouldSkipPath(path, skipPaths) {
300
- return skipPaths.some((pattern) => matchPath(path, pattern));
301
- }
302
- function shouldIncludePath(path, includePaths) {
303
- if (!includePaths || includePaths.length === 0) return true;
304
- return includePaths.some((pattern) => matchPath(path, pattern));
305
- }
306
- function buildBlockedResponse(request, decision, config) {
307
- const status = config.blockedResponse?.status ?? 403;
308
- const message = config.blockedResponse?.message ?? decision.message ?? "Access denied";
309
- const recoveryUrl = resolveRecoveryUrl(request, config.redirectUrl || decision.redirectUrl);
310
- const body = {
311
- error: message,
312
- code: "AGENT_BLOCKED",
313
- reason: decision.reason,
314
- agentType: decision.agentType
315
- };
316
- if (recoveryUrl) {
317
- const hostname = safeHostname(request.url);
318
- body.user_action_required = {
319
- action: `Connect securely to ${hostname}`,
320
- url: recoveryUrl,
321
- reason: `${hostname} blocks unverified AI assistants. Open the link to give your assistant a verified key and try again.`
322
- };
323
- body.message = `I can't access ${hostname} \u2014 this site blocks unverified AI assistants.
324
-
325
- **To give me access, open this link:**
326
- [Connect securely to ${hostname}](${recoveryUrl})
327
-
328
- Once you're done, ask me to try again.`;
329
- }
330
- const response = NextResponse.json(body, { status });
331
- if (config.blockedResponse?.headers) {
332
- for (const [key, value] of Object.entries(config.blockedResponse.headers)) {
333
- response.headers.set(key, value);
334
- }
335
- }
336
- if (recoveryUrl) {
337
- response.headers.set("Link", `<${recoveryUrl}>; rel="kya-authorize"`);
338
- response.headers.set("KYA-Auth-Url", recoveryUrl);
339
- }
340
- response.headers.set("KYA-Action", decision.action);
341
- response.headers.set("KYA-Reason", decision.reason);
342
- return response;
343
- }
344
- function resolveRecoveryUrl(request, target) {
345
- if (!target) return void 0;
346
- try {
347
- return new URL(target, request.url).toString();
348
- } catch {
349
- return void 0;
350
- }
351
- }
352
- function buildRedirectResponse(request, decision, config) {
353
- const redirectUrl = config.redirectUrl || decision.redirectUrl || "/blocked";
354
- const url = new URL(redirectUrl, request.url);
355
- url.searchParams.set("reason", decision.reason);
356
- if (decision.agentType) {
357
- url.searchParams.set("agent", decision.agentType);
358
- }
359
- return NextResponse.redirect(url);
360
- }
361
- function withCheckpointApi(config = {}) {
362
- let client = null;
363
- const getClient = () => {
364
- if (!client) {
365
- client = getCheckpointApiClient({
366
- apiKey: config.apiKey,
367
- baseUrl: config.apiUrl,
368
- useEdge: config.useEdge,
369
- timeout: config.timeout,
370
- debug: config.debug
371
- });
372
- }
373
- return client;
374
- };
375
- const defaultSkipPaths = [
376
- "/_next/static/**",
377
- "/_next/image/**",
378
- "/favicon.ico",
379
- "/robots.txt",
380
- "/sitemap.xml"
381
- ];
382
- const skipPaths = [...defaultSkipPaths, ...config.skipPaths || []];
383
- const failOpen = config.failOpen ?? true;
384
- return async function middleware(request) {
385
- const path = request.nextUrl.pathname;
386
- const startTime = Date.now();
387
- if (shouldSkipPath(path, skipPaths)) {
388
- return NextResponse.next();
389
- }
390
- if (!shouldIncludePath(path, config.includePaths)) {
391
- return NextResponse.next();
392
- }
393
- try {
394
- const client2 = getClient();
395
- const userAgent = request.headers.get("user-agent") || void 0;
396
- const ipAddress = getClientIp(request, config.clientIpPolicy);
397
- const result = await client2.enforce({
398
- headers: Object.fromEntries(request.headers.entries()),
399
- userAgent,
400
- ipAddress,
401
- path,
402
- url: request.url,
403
- method: request.method,
404
- requestId: request.headers.get("x-request-id") || void 0,
405
- options: {
406
- // Always include detection results for logging (needed when using edge)
407
- includeDetectionResult: true
408
- }
409
- });
410
- if (!result.success || !result.data) {
411
- if (config.debug) {
412
- console.warn("[Checkpoint] API error:", result.error);
413
- }
414
- if (failOpen) {
415
- return NextResponse.next();
416
- }
417
- return NextResponse.json(
418
- { error: "Security check failed", code: "API_ERROR" },
419
- { status: 503 }
420
- );
421
- }
422
- const decision = result.data.decision;
423
- if (config.debug) {
424
- console.log("[Checkpoint] Decision:", {
425
- path,
426
- action: decision.action,
427
- isAgent: decision.isAgent,
428
- confidence: decision.confidence,
429
- agentName: decision.agentName,
430
- detectionMethod: result.data.detection?.detectionMethod || "not-included",
431
- processingTimeMs: Date.now() - startTime
432
- });
433
- }
434
- if (client2.isUsingEdge() && result.data.detection) {
435
- waitUntil(
436
- client2.logDetection({
437
- detection: result.data.detection,
438
- context: { userAgent, ipAddress, path, url: request.url, method: request.method }
439
- }).catch((err) => {
440
- if (config.debug) {
441
- console.error("[Checkpoint] Log detection failed:", err);
442
- }
443
- })
444
- );
445
- }
446
- if (decision.isAgent && config.onAgentDetected) {
447
- try {
448
- await config.onAgentDetected(request, decision);
449
- } catch (error) {
450
- if (config.debug) {
451
- console.error("[Checkpoint] onAgentDetected callback failed:", error);
452
- }
453
- }
454
- }
455
- const redirectMode = config.redirectMode ?? "instruct";
456
- switch (decision.action) {
457
- case "block": {
458
- if (config.customBlockedResponse) {
459
- return await config.customBlockedResponse(request, decision);
460
- }
461
- if (config.onBlock === "redirect") {
462
- return buildRedirectResponse(request, decision, config);
463
- }
464
- return buildBlockedResponse(request, decision, config);
465
- }
466
- case "redirect":
467
- case "instruct": {
468
- if (redirectMode === "http" && decision.action === "redirect") {
469
- return buildRedirectResponse(request, decision, config);
470
- }
471
- const targetUrl = config.redirectUrl || decision.redirectUrl;
472
- const bodyReadable200 = selectBodyReadable200(
473
- config.delegationChallengeMode ?? "negotiated",
474
- request.headers,
475
- result.data.detection?.detectionClass,
476
- result.data.detection?.isAgent ?? false
477
- );
478
- return buildAgentInstructionResponse(request, decision, targetUrl, {
479
- bodyReadable200
480
- });
481
- }
482
- case "challenge": {
483
- return buildRedirectResponse(request, decision, config);
484
- }
485
- case "log":
486
- case "allow":
487
- default: {
488
- const response = NextResponse.next();
489
- if (decision.isAgent) {
490
- response.headers.set("KYA-Detected", "true");
491
- response.headers.set("KYA-Confidence", decision.confidence.toString());
492
- if (decision.agentName) {
493
- response.headers.set("KYA-Agent", decision.agentName);
494
- }
495
- }
496
- return response;
497
- }
498
- }
499
- } catch (error) {
500
- if (config.debug) {
501
- console.error("[Checkpoint] Middleware error:", error);
502
- }
503
- if (failOpen) {
504
- return NextResponse.next();
505
- }
506
- return NextResponse.json(
507
- { error: "Security check failed", code: "MIDDLEWARE_ERROR" },
508
- { status: 503 }
509
- );
510
- }
511
- };
512
- }
513
- var withAgentShield = withCheckpointApi;
514
- var 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.";
515
- function agentShieldMiddleware(_request) {
516
- throw new Error(LEGACY_MIGRATION_ERROR);
517
- }
518
- function createEnhancedAgentShieldMiddleware(_config = {}) {
519
- throw new Error(LEGACY_MIGRATION_ERROR);
520
- }
521
-
522
- export { agentShieldMiddleware, createEnhancedAgentShieldMiddleware, withAgentShield, withCheckpointApi };
3
+ export { withCheckpointApi };
@@ -0,0 +1,20 @@
1
+ //#region src/cedar-wasm.d.ts
2
+ /**
3
+ * The Cedar build's compiled `WebAssembly.Module`: the engine plus the Cedar
4
+ * policy evaluator. Pass it as `withCheckpoint`'s `engineWasmModule` on the
5
+ * Edge runtime, in place of `./engine-wasm`, and one module runs detection and
6
+ * the project's Cedar policy:
7
+ *
8
+ * ```ts
9
+ * import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';
10
+ * export default withCheckpoint({ tenantHost, projectId, engineWasmModule });
11
+ * ```
12
+ *
13
+ * Opt-in because it is larger than the engine-only build; a project whose
14
+ * Cedar policy is enforcing needs it on the Edge runtime. Imported through
15
+ * this package, the binary always matches the glue this package loads.
16
+ */
17
+ declare const cedarWasmModule: WebAssembly.Module;
18
+ //#endregion
19
+ export { cedarWasmModule as default };
20
+ //# sourceMappingURL=cedar-wasm.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cedar-wasm.d.mts","names":[],"sources":["../src/cedar-wasm.ts"],"mappings":";;;;;;;;;;;;;;;;cAmBM,iBAAiB,YAAY"}
@@ -0,0 +1,19 @@
1
+ //#region src/cedar-wasm.d.ts
2
+ /**
3
+ * The Cedar build's compiled `WebAssembly.Module`: the engine plus the Cedar
4
+ * policy evaluator. Pass it as `withCheckpoint`'s `engineWasmModule` on the
5
+ * Edge runtime, in place of `./engine-wasm`, and one module runs detection and
6
+ * the project's Cedar policy:
7
+ *
8
+ * ```ts
9
+ * import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';
10
+ * export default withCheckpoint({ tenantHost, projectId, engineWasmModule });
11
+ * ```
12
+ *
13
+ * Opt-in because it is larger than the engine-only build; a project whose
14
+ * Cedar policy is enforcing needs it on the Edge runtime. Imported through
15
+ * this package, the binary always matches the glue this package loads.
16
+ */
17
+ declare const cedarWasmModule: WebAssembly.Module;
18
+ export = cedarWasmModule;
19
+ //# sourceMappingURL=cedar-wasm.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cedar-wasm.d.ts","names":[],"sources":["../src/cedar-wasm.ts"],"mappings":";;;;;;;;;;;;;;;;cAmBM,iBAAiB,YAAY"}
@@ -0,0 +1,24 @@
1
+ const require_rolldown_runtime = require('./rolldown-runtime-C24Yb2bl.js');
2
+ let _kya_os_checkpoint_wasm_runtime_wasm_kya_os_engine_cedar_web_kya_os_engine_bg_wasm_module = require("@kya-os/checkpoint-wasm-runtime/wasm/kya-os-engine-cedar-web/kya_os_engine_bg.wasm?module");
3
+ _kya_os_checkpoint_wasm_runtime_wasm_kya_os_engine_cedar_web_kya_os_engine_bg_wasm_module = require_rolldown_runtime.__toESM(_kya_os_checkpoint_wasm_runtime_wasm_kya_os_engine_cedar_web_kya_os_engine_bg_wasm_module);
4
+
5
+ //#region src/cedar-wasm.ts
6
+ /**
7
+ * The Cedar build's compiled `WebAssembly.Module`: the engine plus the Cedar
8
+ * policy evaluator. Pass it as `withCheckpoint`'s `engineWasmModule` on the
9
+ * Edge runtime, in place of `./engine-wasm`, and one module runs detection and
10
+ * the project's Cedar policy:
11
+ *
12
+ * ```ts
13
+ * import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';
14
+ * export default withCheckpoint({ tenantHost, projectId, engineWasmModule });
15
+ * ```
16
+ *
17
+ * Opt-in because it is larger than the engine-only build; a project whose
18
+ * Cedar policy is enforcing needs it on the Edge runtime. Imported through
19
+ * this package, the binary always matches the glue this package loads.
20
+ */
21
+ const cedarWasmModule = _kya_os_checkpoint_wasm_runtime_wasm_kya_os_engine_cedar_web_kya_os_engine_bg_wasm_module.default;
22
+
23
+ //#endregion
24
+ module.exports = cedarWasmModule;
@@ -0,0 +1,23 @@
1
+ import compiled from "@kya-os/checkpoint-wasm-runtime/wasm/kya-os-engine-cedar-web/kya_os_engine_bg.wasm?module";
2
+
3
+ //#region src/cedar-wasm.ts
4
+ /**
5
+ * The Cedar build's compiled `WebAssembly.Module`: the engine plus the Cedar
6
+ * policy evaluator. Pass it as `withCheckpoint`'s `engineWasmModule` on the
7
+ * Edge runtime, in place of `./engine-wasm`, and one module runs detection and
8
+ * the project's Cedar policy:
9
+ *
10
+ * ```ts
11
+ * import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';
12
+ * export default withCheckpoint({ tenantHost, projectId, engineWasmModule });
13
+ * ```
14
+ *
15
+ * Opt-in because it is larger than the engine-only build; a project whose
16
+ * Cedar policy is enforcing needs it on the Edge runtime. Imported through
17
+ * this package, the binary always matches the glue this package loads.
18
+ */
19
+ const cedarWasmModule = compiled;
20
+
21
+ //#endregion
22
+ export { cedarWasmModule as default };
23
+ //# sourceMappingURL=cedar-wasm.mjs.map
@@ -0,0 +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({ tenantHost, 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"}