@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
package/dist/index.js CHANGED
@@ -1,1276 +1,37 @@
1
- 'use strict';
2
-
3
- var orchestrator = require('@kya-os/checkpoint-wasm-runtime/orchestrator');
4
- var browserPosture = require('@kya-os/checkpoint-shared/browser-posture');
5
- var composedPolicy = require('@kya-os/checkpoint-wasm-runtime/composed-policy');
6
- var adapters = require('@kya-os/checkpoint-wasm-runtime/adapters');
7
- var reporter = require('@kya-os/checkpoint-wasm-runtime/reporter');
8
- var checkpointShared = require('@kya-os/checkpoint-shared');
9
- var server = require('next/server');
10
- var functions = require('@vercel/functions');
11
-
12
- // src/middleware-node.ts
13
- function adaptToNextResponse(rendered, req) {
14
- const clientAcceptsHtml = checkpointShared.acceptsHtml(req.headers);
15
- const verdictCookie = checkpointShared.encodeVerdictCookie(rendered);
16
- const shape = checkpointShared.classifyResponseShape(rendered, clientAcceptsHtml);
17
- switch (shape) {
18
- case "pass-through": {
19
- const res = server.NextResponse.next();
20
- applyHeaders(res, rendered);
21
- setVerdictCookie(res, verdictCookie);
22
- return res;
23
- }
24
- case "redirect": {
25
- const target = new URL(rendered.headers.Location);
26
- const res = server.NextResponse.redirect(target);
27
- applyHeaders(res, rendered);
28
- setVerdictCookie(res, verdictCookie);
29
- return res;
30
- }
31
- case "html-block": {
32
- const blockedUrl = new URL(checkpointShared.BLOCKED_PATH, req.url);
33
- const res = server.NextResponse.rewrite(blockedUrl, { status: 200 });
34
- applyHeaders(res, rendered);
35
- setVerdictCookie(res, verdictCookie);
36
- return res;
37
- }
38
- case "json-block": {
39
- const body = rendered.body ?? {};
40
- const res = server.NextResponse.json(body, { status: rendered.status });
41
- applyHeaders(res, rendered);
42
- setVerdictCookie(res, verdictCookie);
43
- return res;
44
- }
45
- }
46
- }
47
- function setVerdictCookie(res, value) {
48
- res.cookies.set({
49
- name: checkpointShared.VERDICT_COOKIE_NAME,
50
- value,
51
- path: "/",
52
- sameSite: "lax",
53
- httpOnly: false
54
- });
55
- }
56
- function applyHeaders(res, rendered) {
57
- for (const [key, value] of Object.entries(rendered.headers)) {
58
- res.headers.set(key, value);
59
- }
60
- for (const [key, value] of rendered.headerEntries ?? []) {
61
- res.headers.append(key, value);
62
- }
63
- }
64
- var DEFAULT_DASHBOARD_URL = "https://kya.vouched.id";
65
- var NOOP_LOGGER = {
66
- shadowDivergence: () => {
67
- },
68
- evaluationError: () => {
69
- }
70
- };
71
- function makeComposedPolicyContext(opts) {
72
- const { projectId, fetcher } = opts;
73
- const cache = composedPolicy.makeComposedPolicyCache({ compile: opts.compile, cacheMax: opts.cacheMax });
74
- const logger = opts.logger ?? NOOP_LOGGER;
75
- return {
76
- async apply(result, path) {
77
- const structured = { decision: result.decision, acted: false };
78
- if (composedPolicy.isCredentialVerificationBlock(result.decision)) return structured;
79
- const policy = await fetcher.getPolicy(projectId);
80
- const outcome = await composedPolicy.evaluateComposedPolicy({
81
- cache,
82
- projectId,
83
- flags: {
84
- policyLanguage: policy.policyLanguage,
85
- policySourceText: policy.policySourceText,
86
- engineEnforcementEnabled: policy.engineEnforcementEnabled,
87
- enabled: policy.enabled
88
- },
89
- authorizeInput: composedPolicy.verifyResultToAuthorizeInput(result, { tenantId: projectId, path }),
90
- baselineDecisionKind: result.decision.kind
91
- });
92
- if ((outcome.status === "acting" || outcome.status === "shadow") && outcome.diverged) {
93
- logger.shadowDivergence({
94
- projectId,
95
- path,
96
- engineDecision: outcome.engineDecision.kind,
97
- structuredDecision: result.decision.kind,
98
- detectionClass: result.detectionDetail.detectionClass.type,
99
- verificationMethod: result.detectionDetail.verificationMethod,
100
- confidence: result.detectionDetail.confidence,
101
- agentName: result.detectionDetail.detectedAgent?.name
102
- });
103
- }
104
- if (outcome.status === "error") {
105
- logger.evaluationError(projectId, outcome.error);
106
- return structured;
107
- }
108
- if (outcome.status === "acting") {
109
- return {
110
- decision: outcome.engineDecision,
111
- acted: true,
112
- // Echo the SSOT revision pin with the decision it produced (#3246
113
- // PR5). Conditional spread: absent upstream stays absent here.
114
- ...policy.policySourceHash ? { composedBlobHash: policy.policySourceHash } : {}
115
- };
116
- }
117
- return structured;
118
- },
119
- async trustedDelegationRoots() {
120
- const policy = await fetcher.getPolicy(projectId);
121
- return policy.trustedDelegationRoots ?? [];
122
- }
123
- };
124
- }
125
- async function resolveTrustedDelegationRootsForRequest(resolver, headers) {
126
- if (!resolver) return void 0;
127
- if (!checkpointShared.requestCarriesDelegationProof(headers)) return void 0;
128
- const roots = await resolver();
129
- return roots.length > 0 ? roots : void 0;
130
- }
131
- async function applyComposedPolicy(context, result, path) {
132
- if (!context) return;
133
- try {
134
- const outcome = await context.apply(result, path);
135
- if (outcome.acted) {
136
- result.decision = outcome.decision;
137
- if (outcome.composedBlobHash) {
138
- result.composedBlobHash = outcome.composedBlobHash;
139
- }
140
- }
141
- } catch {
142
- }
143
- }
144
- var consoleComposedPolicyLogger = {
145
- shadowDivergence(info) {
146
- console.warn("[checkpoint/composed-policy] shadow-divergence", info);
147
- },
148
- evaluationError(projectId, error) {
149
- console.error(
150
- `[checkpoint/composed-policy] evaluation failed for ${projectId}; using structured decision:`,
151
- error
152
- );
153
- }
154
- };
155
- async function nextRequestToHttpLike(req, opts = {}) {
156
- const url = new URL(req.url);
157
- const body = await tryDrainJsonBody(req, opts);
158
- return {
159
- method: req.method,
160
- // Path + query only — orchestrator's URL parsing expects no scheme/host.
161
- url: url.pathname + url.search,
162
- headers: headersToRecord(req.headers),
163
- body,
164
- remoteAddress: extractRemoteAddress(req, opts.clientIpPolicy ?? { platform: "direct" })
165
- };
166
- }
167
- async function tryDrainJsonBody(req, opts) {
168
- if (opts.drainJsonBody === false) return null;
169
- const contentType = req.headers.get("content-type") ?? "";
170
- if (!contentType.toLowerCase().includes("application/json")) return null;
171
- try {
172
- return await req.clone().text();
173
- } catch {
174
- return null;
175
- }
176
- }
177
- function headersToRecord(headers) {
178
- const out = {};
179
- headers.forEach((value, key) => {
180
- out[key.toLowerCase()] = value;
181
- });
182
- return out;
183
- }
184
- function extractRemoteAddress(req, policy) {
185
- const maybeIp = req.ip;
186
- return checkpointShared.resolveClientIp({
187
- headers: req.headers,
188
- frameworkAddress: maybeIp,
189
- policy
190
- }).ip ?? void 0;
191
- }
192
-
193
- // src/middleware-core.ts
194
- function makeNextMiddleware(verifyRequest2, renderDecisionAsResponse2, config, host) {
195
- if (config.browserPosture) browserPosture.validateBrowserPostureConfig(config.browserPosture, config.projectId);
196
- if (config.browserPosture?.protectedRoutes?.length && !config.resolveDelegationChallenge) {
197
- throw new Error(
198
- "browserPosture.protectedRoutes requires resolveDelegationChallenge (see createBrowserIntegrityChallengeResolver)"
199
- );
200
- }
201
- const opts = buildVerifyOpts(config);
202
- const reporter = buildReporter(config, host.runtime);
203
- const composed = host.buildComposedContext(config);
204
- const trustedRootsResolver = buildTrustedRootsResolver(config, composed);
205
- const translateOpts = {
206
- drainJsonBody: config.drainJsonBody,
207
- clientIpPolicy: config.clientIpPolicy
208
- };
209
- return async function checkpointMiddleware(req, event) {
210
- const httpLike = await nextRequestToHttpLike(req, translateOpts);
211
- const trustedDelegationRoots = await resolveTrustedDelegationRootsForRequest(
212
- trustedRootsResolver,
213
- req.headers
214
- );
215
- const result = await verifyRequest2(
216
- httpLike,
217
- trustedDelegationRoots ? { ...opts, trustedDelegationRoots } : opts
218
- );
219
- await composedPolicy.applyBrowserPosture(
220
- result,
221
- req.headers.get("cookie"),
222
- config.browserPosture,
223
- config.projectId
224
- );
225
- await applyComposedPolicy(composed, result, req.nextUrl.pathname);
226
- composedPolicy.applyBrowserIntegrityStepUp(result, config.browserPosture, req.nextUrl.pathname);
227
- if (reporter) {
228
- const reportPromise = reporter(
229
- result,
230
- extractReporterContext(req, config.clientIpPolicy ?? { platform: "direct" })
231
- );
232
- if (event) {
233
- event.waitUntil(reportPromise);
234
- }
235
- }
236
- await dispatchOnResult(config, result, req);
237
- const bodyReadable200 = checkpointShared.selectBodyReadable200(
238
- config.delegationChallengeMode ?? "negotiated",
239
- req.headers,
240
- result.detectionDetail.detectionClass,
241
- result.detectionDetail.isAgent
242
- );
243
- const challengeContextRequested = result.enforcementMode === "enforce" && result.decision.kind === "Challenge" && config.resolveDelegationChallenge !== void 0;
244
- const delegationChallenge = challengeContextRequested ? await checkpointShared.resolveChallengeContext(
245
- config.resolveDelegationChallenge,
246
- { result, request: req },
247
- {
248
- timeoutMs: config.delegationChallengeTimeoutMs,
249
- onFailure: config.onDelegationChallengeFailure
250
- }
251
- ) : void 0;
252
- const rendered = renderDecisionAsResponse2(result, {
253
- bodyReadable200,
254
- delegationChallenge: composedPolicy.validateBrowserIntegrityChallenge(result, delegationChallenge),
255
- challengeContextRequested
256
- });
257
- return adaptToNextResponse(rendered, req);
258
- };
259
- }
260
- var SDK_NAME = "@kya-os/checkpoint-nextjs";
261
- var VERSION = "1.9.0";
262
- function buildReporter(config, runtime = "node") {
263
- if (!config.apiKey) return null;
264
- return reporter.makeDetectionReporter({
265
- apiKey: config.apiKey,
266
- baseUrl: config.baseUrl,
267
- debug: config.debug,
268
- // Self-identify (incl. node-vs-edge) so the dashboard can version-gate
269
- // enforcement. Next.js EDGE composed enforcement is opt-in (needs
270
- // `cedarWasmModule`), so the dashboard shows it as opt-in, never "Enforcing".
271
- sdk: { name: SDK_NAME, version: VERSION, runtime }
272
- });
273
- }
274
- function buildTrustedRootsResolver(config, composed) {
275
- if (config.trustedDelegationRoots) return () => Promise.resolve(config.trustedDelegationRoots);
276
- if (composed?.trustedDelegationRoots) {
277
- return () => composed.trustedDelegationRoots();
278
- }
279
- if (!config.projectId) return null;
280
- const fetcher = new checkpointShared.PolicyFetcher({
281
- apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,
282
- apiKey: config.apiKey,
283
- cacheTtlSeconds: config.policyCacheTtlSeconds
284
- });
285
- const projectId = config.projectId;
286
- return async () => (await fetcher.getPolicy(projectId)).trustedDelegationRoots ?? [];
287
- }
288
- function extractReporterContext(req, policy) {
289
- const resolution = checkpointShared.resolveClientIp({
290
- headers: req.headers,
291
- frameworkAddress: req.ip,
292
- policy
293
- });
294
- return {
295
- userAgent: req.headers.get("user-agent") ?? void 0,
296
- ipAddress: resolution.ip ?? void 0,
297
- path: req.nextUrl.pathname,
298
- url: req.nextUrl.href,
299
- method: req.method
300
- };
301
- }
302
- function buildVerifyOpts(config) {
303
- const overrides = config.adapters ?? {};
304
- return {
305
- didResolver: overrides.didResolver ?? adapters.makeDidResolver(),
306
- statusListCache: overrides.statusListCache ?? adapters.makeStatusListCache(),
307
- reputationOracle: overrides.reputationOracle ?? adapters.makeReputationOracle({ argusUrl: config.argusUrl }),
308
- policyEvaluator: overrides.policyEvaluator ?? adapters.makePolicyEvaluator({ dashboardUrl: config.dashboardUrl }),
309
- clock: adapters.makeSystemClock(),
310
- tenantHost: config.tenantHost,
311
- resourceOrgDid: config.resourceOrgDid,
312
- trustedDelegationRoots: config.trustedDelegationRoots,
313
- enforcementMode: config.enforcementMode ?? "enforce",
314
- reputationBaseline: config.reputationBaseline,
315
- argusUrl: config.argusUrl,
316
- legacyEnvelopeFallback: config.legacyEnvelopeFallback ?? false,
317
- engineConfig: config.engineConfig
318
- };
319
- }
320
- async function dispatchOnResult(config, result, req) {
321
- if (!config.onResult) return;
322
- try {
323
- await config.onResult(result, req);
324
- } catch {
325
- }
326
- }
327
- function buildComposedContext(config) {
328
- if (config.composedPolicyEnforcer) return config.composedPolicyEnforcer;
329
- if (!config.projectId) return null;
330
- return makeComposedPolicyContext({
331
- projectId: config.projectId,
332
- fetcher: new checkpointShared.PolicyFetcher({
333
- apiBaseUrl: config.dashboardUrl ?? config.baseUrl ?? DEFAULT_DASHBOARD_URL,
334
- apiKey: config.apiKey,
335
- cacheTtlSeconds: config.policyCacheTtlSeconds
336
- }),
337
- // Load the Node policy compiler only on first use. This module is imported
338
- // exclusively by the Node and bundler hosts, never by the Edge pipeline.
339
- compile: async (_language, source) => {
340
- const { createPolicyEvaluator } = await import('@kya-os/checkpoint-wasm-runtime/policy');
341
- return createPolicyEvaluator(source);
342
- },
343
- logger: config.debug ? consoleComposedPolicyLogger : void 0
344
- });
345
- }
346
-
347
- // src/middleware-node.ts
348
- function withCheckpoint(config) {
349
- return makeNextMiddleware(orchestrator.verifyRequest, orchestrator.renderDecisionAsResponse, config, {
350
- runtime: "node",
351
- buildComposedContext
352
- });
353
- }
354
- var MIGRATION_ERROR = "@kya-os/checkpoint-nextjs's `createAgentShieldMiddleware` / `agentShield` were deleted in Phase D (engine consolidation). The 600-line TS pattern matcher that backed them is gone. Migrate to `withCheckpoint` from `@kya-os/checkpoint-nextjs` (Node runtime) or `@kya-os/checkpoint-nextjs/edge` (Edge runtime). See packages/checkpoint-nextjs/CHANGELOG.md (1.0.0) for the recipe.";
355
- function createAgentShieldMiddleware(_config = {}) {
356
- throw new Error(MIGRATION_ERROR);
357
- }
358
-
359
- // src/create-middleware.ts
360
- var middlewareInstance = null;
361
- var isInitializing = false;
362
- var initPromise = null;
363
- function createAgentShieldMiddleware2(config) {
364
- return async function agentShieldMiddleware2(request) {
365
- if (!middlewareInstance) {
366
- if (!isInitializing) {
367
- isInitializing = true;
368
- initPromise = (async () => {
369
- middlewareInstance = createAgentShieldMiddleware(config);
370
- return middlewareInstance;
371
- })();
372
- }
373
- if (initPromise) {
374
- middlewareInstance = await initPromise;
375
- }
376
- }
377
- return middlewareInstance ? middlewareInstance(request) : server.NextResponse.next();
378
- };
379
- }
380
-
381
- // src/api-client.ts
382
- var DEFAULT_BASE_URL = "https://kya.vouched.id";
383
- var EDGE_DETECT_URL = "https://detect.checkpoint-gateway.ai";
384
- var DEFAULT_TIMEOUT = 5e3;
385
- var CheckpointApiClient = class {
386
- apiKey;
387
- baseUrl;
388
- useEdge;
389
- timeout;
390
- debug;
391
- constructor(config) {
392
- if (!config.apiKey) {
393
- throw new Error("Checkpoint API key is required");
394
- }
395
- this.apiKey = config.apiKey;
396
- this.useEdge = config.useEdge !== false;
397
- this.baseUrl = config.baseUrl || (this.useEdge ? EDGE_DETECT_URL : DEFAULT_BASE_URL);
398
- this.timeout = config.timeout || DEFAULT_TIMEOUT;
399
- this.debug = config.debug || false;
400
- }
401
- /**
402
- * Call the enforce API to check if a request should be allowed
403
- */
404
- async enforce(input) {
405
- const startTime = Date.now();
406
- try {
407
- const controller = new AbortController();
408
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
409
- try {
410
- const endpoint = this.useEdge ? `${this.baseUrl}/__detect/enforce` : `${this.baseUrl}/api/v1/enforce`;
411
- const response = await fetch(endpoint, {
412
- method: "POST",
413
- headers: {
414
- "Content-Type": "application/json",
415
- Authorization: `Bearer ${this.apiKey}`,
416
- "X-Request-ID": input.requestId || crypto.randomUUID()
417
- },
418
- body: JSON.stringify(input),
419
- signal: controller.signal
420
- });
421
- clearTimeout(timeoutId);
422
- const data = await response.json();
423
- if (this.debug) {
424
- console.log("[Checkpoint] Enforce response:", {
425
- status: response.status,
426
- action: data.data?.decision.action,
427
- processingTimeMs: Date.now() - startTime
428
- });
429
- }
430
- if (!response.ok) {
431
- return {
432
- success: false,
433
- error: {
434
- code: `HTTP_${response.status}`,
435
- message: data.error?.message || `HTTP error: ${response.status}`
436
- }
437
- };
438
- }
439
- return data;
440
- } catch (error) {
441
- clearTimeout(timeoutId);
442
- throw error;
443
- }
444
- } catch (error) {
445
- if (error instanceof Error && error.name === "AbortError") {
446
- if (this.debug) {
447
- console.warn("[Checkpoint] Request timed out");
448
- }
449
- return {
450
- success: false,
451
- error: {
452
- code: "TIMEOUT",
453
- message: `Request timed out after ${this.timeout}ms`
454
- }
455
- };
456
- }
457
- if (this.debug) {
458
- console.error("[Checkpoint] Request failed:", error);
459
- }
460
- return {
461
- success: false,
462
- error: {
463
- code: "NETWORK_ERROR",
464
- message: error instanceof Error ? error.message : "Network request failed"
465
- }
466
- };
467
- }
468
- }
469
- /**
470
- * Quick check - returns just the action without full response parsing
471
- * Useful for very fast middleware that just needs allow/block
472
- */
473
- async quickCheck(input) {
474
- const result = await this.enforce(input);
475
- if (!result.success || !result.data) {
476
- return {
477
- action: "allow",
478
- error: result.error?.message
479
- };
480
- }
481
- return {
482
- action: result.data.decision.action
483
- };
484
- }
485
- /**
486
- * Check if this client is using edge detection (Gateway Worker)
487
- */
488
- isUsingEdge() {
489
- return this.useEdge;
490
- }
491
- /**
492
- * Log a detection result to AgentShield database.
493
- * Use after Gateway Worker detection to persist results.
494
- * Fire-and-forget - returns immediately without waiting for DB write.
495
- *
496
- * @example
497
- * ```typescript
498
- * // After receiving Gateway response
499
- * if (client.isUsingEdge() && response.data?.detection) {
500
- * client.logDetection({
501
- * detection: response.data.detection,
502
- * context: { userAgent, ipAddress, path, url, method }
503
- * }).catch(err => console.error('Log failed:', err));
504
- * }
505
- * ```
506
- */
507
- async logDetection(input) {
508
- const logEndpoint = this.useEdge ? `${DEFAULT_BASE_URL}/api/v1/log-detection` : `${this.baseUrl}/api/v1/log-detection`;
509
- try {
510
- const controller = new AbortController();
511
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
512
- try {
513
- const response = await fetch(logEndpoint, {
514
- method: "POST",
515
- headers: {
516
- "Content-Type": "application/json",
517
- Authorization: `Bearer ${this.apiKey}`
518
- },
519
- body: JSON.stringify({
520
- detection: {
521
- isAgent: input.detection.isAgent,
522
- confidence: input.detection.confidence,
523
- agentName: input.detection.agentName,
524
- agentType: input.detection.agentType,
525
- detectionClass: input.detection.detectionClass,
526
- verificationMethod: input.detection.verificationMethod,
527
- reasons: input.detection.reasons
528
- },
529
- context: input.context,
530
- source: input.source || "gateway"
531
- }),
532
- signal: controller.signal
533
- });
534
- clearTimeout(timeoutId);
535
- if (!response.ok && this.debug) {
536
- console.warn("[Checkpoint] Log detection returned non-2xx:", response.status);
537
- }
538
- } catch (error) {
539
- clearTimeout(timeoutId);
540
- throw error;
541
- }
542
- } catch (error) {
543
- if (this.debug) {
544
- console.error("[Checkpoint] Log detection failed:", error);
545
- }
546
- throw error;
547
- }
548
- }
549
- };
550
- var clientInstances = /* @__PURE__ */ new Map();
551
- function resolveClientConfig(config) {
552
- const apiKey = config?.apiKey || process.env.CHECKPOINT_API_KEY;
553
- if (!apiKey) {
554
- throw new Error(
555
- "Checkpoint API key is required. Set CHECKPOINT_API_KEY environment variable or pass apiKey in config."
556
- );
557
- }
558
- return {
559
- apiKey,
560
- baseUrl: config?.baseUrl || process.env.CHECKPOINT_API_URL,
561
- // Default to edge detection unless explicitly disabled
562
- useEdge: config?.useEdge ?? process.env.CHECKPOINT_USE_EDGE !== "false",
563
- timeout: config?.timeout,
564
- debug: config?.debug || process.env.CHECKPOINT_DEBUG === "true"
565
- };
566
- }
567
- function clientCacheKey(config) {
568
- return JSON.stringify([
569
- config.apiKey,
570
- config.baseUrl ?? "",
571
- config.useEdge ?? true,
572
- config.timeout ?? DEFAULT_TIMEOUT,
573
- config.debug ?? false
574
- ]);
575
- }
576
- function getCheckpointApiClient(config) {
577
- const resolvedConfig = resolveClientConfig(config);
578
- const key = clientCacheKey(resolvedConfig);
579
- let clientInstance = clientInstances.get(key);
580
- if (!clientInstance) {
581
- clientInstance = new CheckpointApiClient(resolvedConfig);
582
- clientInstances.set(key, clientInstance);
583
- }
584
- return clientInstance;
585
- }
586
- function resetCheckpointApiClient() {
587
- clientInstances.clear();
588
- }
589
- var AgentShieldClient = CheckpointApiClient;
590
- var getAgentShieldClient = getCheckpointApiClient;
591
- var resetAgentShieldClient = resetCheckpointApiClient;
592
- function getClientIp(request, policy = { platform: "direct" }) {
593
- const frameworkAddress = request.ip;
594
- return checkpointShared.resolveClientIp({ headers: request.headers, frameworkAddress, policy }).ip ?? void 0;
595
- }
596
- function safeHostname(url) {
597
- try {
598
- return new URL(url).hostname;
599
- } catch {
600
- return "this site";
601
- }
602
- }
603
-
604
- // src/responses/agent-instruction.ts
605
- var MCP_I_DOCS_URL = "https://kya.vouched.id/docs/enforce/kya-os-enforcement";
606
- var DEFAULT_CONNECT_PATH = "/connect";
607
- function buildAgentInstructionResponse(request, decision, redirectUrl, options) {
608
- const resolved = resolveUrl(redirectUrl ?? DEFAULT_CONNECT_PATH, request.url);
609
- const agentName = decision.agentName || decision.agentType || "unknown";
610
- if (!resolved.searchParams.has("agent")) {
611
- resolved.searchParams.set("agent", agentName.toLowerCase());
612
- }
613
- const authUrl = resolved.toString();
614
- const hostname = safeHostname(request.url);
615
- const body = {
616
- // Markdown-formatted so clients that render markdown (Claude Desktop,
617
- // ChatGPT web) surface the URL as a clickable link. Tone mirrors the
618
- // gateway response so messaging stays consistent across platforms.
619
- message: `I can't access ${hostname} yet \u2014 this site checks AI assistants at the front door.
620
-
621
- **To give me access, open this link:**
622
- [Connect securely to ${hostname}](${authUrl})
623
-
624
- 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.`,
625
- user_action_required: {
626
- action: `Connect securely to ${hostname}`,
627
- url: authUrl,
628
- reason: `${hostname} checks AI assistants before they connect. Open the link to give your assistant a verified key.`
629
- },
630
- mcp_i: {
631
- version: "1.0",
632
- action: "authenticate",
633
- authorization_url: authUrl,
634
- flow: {
635
- type: "oauth2_delegation",
636
- steps: [
637
- "1. Direct your user to the authorization_url",
638
- "2. User reviews requested scopes and grants consent",
639
- "3. Receive delegation credential (JWT)",
640
- "4. Include credential in KYA-Delegation header",
641
- "5. Retry this request with the proof"
642
- ]
643
- },
644
- retry_instructions: {
645
- header: "KYA-Delegation",
646
- format: "JWT delegation credential from authorization flow"
647
- },
648
- documentation: MCP_I_DOCS_URL
649
- },
650
- error: "mcp_authentication_required",
651
- code: "AGENT_REQUIRES_DELEGATION",
652
- detection: {
653
- agent_type: decision.agentType || "ai_agent",
654
- agent_name: decision.agentName || "Unknown Agent",
655
- confidence: decision.confidence
656
- }
657
- };
658
- const bodyReadable200 = options?.bodyReadable200 ?? false;
659
- const response = server.NextResponse.json(body, { status: bodyReadable200 ? 200 : 401 });
660
- response.headers.set(
661
- "Link",
662
- `<${authUrl}>; rel="kya-authorize", <${MCP_I_DOCS_URL}>; rel="help"`
663
- );
664
- response.headers.set("KYA-Auth-Required", "true");
665
- response.headers.set("KYA-Auth-Url", authUrl);
666
- response.headers.set("KYA-Action", "instruct");
667
- response.headers.set("KYA-Detected-Agent", agentName);
668
- response.headers.set("KYA-Confidence", decision.confidence.toString());
669
- response.headers.set("Cache-Control", "no-store");
670
- return response;
671
- }
672
- function resolveUrl(target, baseUrl) {
673
- try {
674
- return new URL(target, baseUrl);
675
- } catch {
676
- return new URL(DEFAULT_CONNECT_PATH, baseUrl);
677
- }
678
- }
679
- function shouldSkipPath(path, skipPaths) {
680
- return skipPaths.some((pattern) => checkpointShared.matchPath(path, pattern));
681
- }
682
- function shouldIncludePath(path, includePaths) {
683
- if (!includePaths || includePaths.length === 0) return true;
684
- return includePaths.some((pattern) => checkpointShared.matchPath(path, pattern));
685
- }
686
- function buildBlockedResponse(request, decision, config) {
687
- const status = config.blockedResponse?.status ?? 403;
688
- const message = config.blockedResponse?.message ?? decision.message ?? "Access denied";
689
- const recoveryUrl = resolveRecoveryUrl(request, config.redirectUrl || decision.redirectUrl);
690
- const body = {
691
- error: message,
692
- code: "AGENT_BLOCKED",
693
- reason: decision.reason,
694
- agentType: decision.agentType
695
- };
696
- if (recoveryUrl) {
697
- const hostname = safeHostname(request.url);
698
- body.user_action_required = {
699
- action: `Connect securely to ${hostname}`,
700
- url: recoveryUrl,
701
- reason: `${hostname} blocks unverified AI assistants. Open the link to give your assistant a verified key and try again.`
702
- };
703
- body.message = `I can't access ${hostname} \u2014 this site blocks unverified AI assistants.
704
-
705
- **To give me access, open this link:**
706
- [Connect securely to ${hostname}](${recoveryUrl})
707
-
708
- Once you're done, ask me to try again.`;
709
- }
710
- const response = server.NextResponse.json(body, { status });
711
- if (config.blockedResponse?.headers) {
712
- for (const [key, value] of Object.entries(config.blockedResponse.headers)) {
713
- response.headers.set(key, value);
714
- }
715
- }
716
- if (recoveryUrl) {
717
- response.headers.set("Link", `<${recoveryUrl}>; rel="kya-authorize"`);
718
- response.headers.set("KYA-Auth-Url", recoveryUrl);
719
- }
720
- response.headers.set("KYA-Action", decision.action);
721
- response.headers.set("KYA-Reason", decision.reason);
722
- return response;
723
- }
724
- function resolveRecoveryUrl(request, target) {
725
- if (!target) return void 0;
726
- try {
727
- return new URL(target, request.url).toString();
728
- } catch {
729
- return void 0;
730
- }
731
- }
732
- function buildRedirectResponse(request, decision, config) {
733
- const redirectUrl = config.redirectUrl || decision.redirectUrl || "/blocked";
734
- const url = new URL(redirectUrl, request.url);
735
- url.searchParams.set("reason", decision.reason);
736
- if (decision.agentType) {
737
- url.searchParams.set("agent", decision.agentType);
738
- }
739
- return server.NextResponse.redirect(url);
740
- }
741
- function withCheckpointApi(config = {}) {
742
- let client = null;
743
- const getClient = () => {
744
- if (!client) {
745
- client = getCheckpointApiClient({
746
- apiKey: config.apiKey,
747
- baseUrl: config.apiUrl,
748
- useEdge: config.useEdge,
749
- timeout: config.timeout,
750
- debug: config.debug
751
- });
752
- }
753
- return client;
754
- };
755
- const defaultSkipPaths = [
756
- "/_next/static/**",
757
- "/_next/image/**",
758
- "/favicon.ico",
759
- "/robots.txt",
760
- "/sitemap.xml"
761
- ];
762
- const skipPaths = [...defaultSkipPaths, ...config.skipPaths || []];
763
- const failOpen = config.failOpen ?? true;
764
- return async function middleware(request) {
765
- const path = request.nextUrl.pathname;
766
- const startTime = Date.now();
767
- if (shouldSkipPath(path, skipPaths)) {
768
- return server.NextResponse.next();
769
- }
770
- if (!shouldIncludePath(path, config.includePaths)) {
771
- return server.NextResponse.next();
772
- }
773
- try {
774
- const client2 = getClient();
775
- const userAgent = request.headers.get("user-agent") || void 0;
776
- const ipAddress = getClientIp(request, config.clientIpPolicy);
777
- const result = await client2.enforce({
778
- headers: Object.fromEntries(request.headers.entries()),
779
- userAgent,
780
- ipAddress,
781
- path,
782
- url: request.url,
783
- method: request.method,
784
- requestId: request.headers.get("x-request-id") || void 0,
785
- options: {
786
- // Always include detection results for logging (needed when using edge)
787
- includeDetectionResult: true
788
- }
789
- });
790
- if (!result.success || !result.data) {
791
- if (config.debug) {
792
- console.warn("[Checkpoint] API error:", result.error);
793
- }
794
- if (failOpen) {
795
- return server.NextResponse.next();
796
- }
797
- return server.NextResponse.json(
798
- { error: "Security check failed", code: "API_ERROR" },
799
- { status: 503 }
800
- );
801
- }
802
- const decision = result.data.decision;
803
- if (config.debug) {
804
- console.log("[Checkpoint] Decision:", {
805
- path,
806
- action: decision.action,
807
- isAgent: decision.isAgent,
808
- confidence: decision.confidence,
809
- agentName: decision.agentName,
810
- detectionMethod: result.data.detection?.detectionMethod || "not-included",
811
- processingTimeMs: Date.now() - startTime
812
- });
813
- }
814
- if (client2.isUsingEdge() && result.data.detection) {
815
- functions.waitUntil(
816
- client2.logDetection({
817
- detection: result.data.detection,
818
- context: { userAgent, ipAddress, path, url: request.url, method: request.method }
819
- }).catch((err) => {
820
- if (config.debug) {
821
- console.error("[Checkpoint] Log detection failed:", err);
822
- }
823
- })
824
- );
825
- }
826
- if (decision.isAgent && config.onAgentDetected) {
827
- try {
828
- await config.onAgentDetected(request, decision);
829
- } catch (error) {
830
- if (config.debug) {
831
- console.error("[Checkpoint] onAgentDetected callback failed:", error);
832
- }
833
- }
834
- }
835
- const redirectMode = config.redirectMode ?? "instruct";
836
- switch (decision.action) {
837
- case "block": {
838
- if (config.customBlockedResponse) {
839
- return await config.customBlockedResponse(request, decision);
840
- }
841
- if (config.onBlock === "redirect") {
842
- return buildRedirectResponse(request, decision, config);
843
- }
844
- return buildBlockedResponse(request, decision, config);
845
- }
846
- case "redirect":
847
- case "instruct": {
848
- if (redirectMode === "http" && decision.action === "redirect") {
849
- return buildRedirectResponse(request, decision, config);
850
- }
851
- const targetUrl = config.redirectUrl || decision.redirectUrl;
852
- const bodyReadable200 = checkpointShared.selectBodyReadable200(
853
- config.delegationChallengeMode ?? "negotiated",
854
- request.headers,
855
- result.data.detection?.detectionClass,
856
- result.data.detection?.isAgent ?? false
857
- );
858
- return buildAgentInstructionResponse(request, decision, targetUrl, {
859
- bodyReadable200
860
- });
861
- }
862
- case "challenge": {
863
- return buildRedirectResponse(request, decision, config);
864
- }
865
- case "log":
866
- case "allow":
867
- default: {
868
- const response = server.NextResponse.next();
869
- if (decision.isAgent) {
870
- response.headers.set("KYA-Detected", "true");
871
- response.headers.set("KYA-Confidence", decision.confidence.toString());
872
- if (decision.agentName) {
873
- response.headers.set("KYA-Agent", decision.agentName);
874
- }
875
- }
876
- return response;
877
- }
878
- }
879
- } catch (error) {
880
- if (config.debug) {
881
- console.error("[Checkpoint] Middleware error:", error);
882
- }
883
- if (failOpen) {
884
- return server.NextResponse.next();
885
- }
886
- return server.NextResponse.json(
887
- { error: "Security check failed", code: "MIDDLEWARE_ERROR" },
888
- { status: 503 }
889
- );
890
- }
891
- };
892
- }
893
- var withAgentShield = withCheckpointApi;
894
- 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.";
895
- function agentShieldMiddleware(_request) {
896
- throw new Error(LEGACY_MIGRATION_ERROR);
897
- }
898
- function createEnhancedAgentShieldMiddleware(_config = {}) {
899
- throw new Error(LEGACY_MIGRATION_ERROR);
900
- }
901
- var EdgeSessionTracker = class {
902
- config;
903
- constructor(config) {
904
- this.config = {
905
- enabled: config.enabled,
906
- cookieName: config.cookieName || "__agentshield_session",
907
- cookieMaxAge: config.cookieMaxAge || 3600,
908
- // 1 hour default
909
- encryptionKey: config.encryptionKey || process.env.CHECKPOINT_SECRET || "agentshield-default-key"
910
- };
911
- }
912
- /**
913
- * Track a new AI agent session
914
- */
915
- async track(_request, response, result) {
916
- try {
917
- const detectedName = result.detectedAgent?.name;
918
- const isEnforceable = result.isAgent || result.isAiCrawler || checkpointShared.isKnownAiCrawler(detectedName);
919
- if (!this.config.enabled || !isEnforceable) {
920
- return response;
921
- }
922
- const sessionData = {
923
- id: crypto.randomUUID(),
924
- agent: result.detectedAgent?.name || "unknown",
925
- confidence: result.confidence,
926
- detectedAt: Date.now(),
927
- expires: Date.now() + this.config.cookieMaxAge * 1e3
928
- };
929
- const encrypted = await this.encrypt(JSON.stringify(sessionData));
930
- response.cookies.set(this.config.cookieName, encrypted, {
931
- httpOnly: true,
932
- secure: process.env.NODE_ENV === "production",
933
- sameSite: "lax",
934
- maxAge: this.config.cookieMaxAge,
935
- path: "/"
936
- });
937
- return response;
938
- } catch (error) {
939
- if (process.env.DEBUG_AGENTSHIELD) {
940
- console.warn("AgentShield: Failed to track session:", error);
941
- }
942
- return response;
943
- }
944
- }
945
- /**
946
- * Check for existing AI agent session
947
- */
948
- async check(request) {
949
- try {
950
- if (!this.config.enabled) {
951
- return null;
952
- }
953
- const cookie = request.cookies.get(this.config.cookieName);
954
- if (!cookie?.value) {
955
- return null;
956
- }
957
- const decrypted = await this.decrypt(cookie.value);
958
- const session = JSON.parse(decrypted);
959
- if (session.expires < Date.now()) {
960
- return null;
961
- }
962
- return session;
963
- } catch (error) {
964
- if (process.env.DEBUG_AGENTSHIELD) {
965
- console.warn("AgentShield: Failed to check session:", error);
966
- }
967
- return null;
968
- }
969
- }
970
- /**
971
- * Clear an existing session
972
- */
973
- clear(response) {
974
- try {
975
- response.cookies.delete(this.config.cookieName);
976
- } catch (error) {
977
- if (process.env.DEBUG_AGENTSHIELD) {
978
- console.warn("AgentShield: Failed to clear session:", error);
979
- }
980
- }
981
- return response;
982
- }
983
- /**
984
- * Simple encryption using Web Crypto API (Edge-compatible)
985
- */
986
- async encrypt(data) {
987
- try {
988
- const key = this.config.encryptionKey;
989
- const encoded = new TextEncoder().encode(data);
990
- const obfuscated = new Uint8Array(encoded.length);
991
- for (let i = 0; i < encoded.length; i++) {
992
- obfuscated[i] = (encoded[i] || 0) ^ key.charCodeAt(i % key.length);
993
- }
994
- return btoa(Array.from(obfuscated, (byte) => String.fromCharCode(byte)).join(""));
995
- } catch (error) {
996
- return btoa(data);
997
- }
998
- }
999
- /**
1000
- * Simple decryption (Edge-compatible)
1001
- */
1002
- async decrypt(data) {
1003
- try {
1004
- const key = this.config.encryptionKey;
1005
- const decoded = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
1006
- const deobfuscated = new Uint8Array(decoded.length);
1007
- for (let i = 0; i < decoded.length; i++) {
1008
- deobfuscated[i] = (decoded[i] || 0) ^ key.charCodeAt(i % key.length);
1009
- }
1010
- return new TextDecoder().decode(deobfuscated);
1011
- } catch (error) {
1012
- return atob(data);
1013
- }
1014
- }
1015
- };
1016
- var StatelessSessionChecker = class {
1017
- static check(headers) {
1018
- try {
1019
- const agent = headers["kya-session-agent"];
1020
- const confidence = headers["kya-session-confidence"];
1021
- const sessionId = headers["kya-session-id"];
1022
- if (agent && confidence && sessionId) {
1023
- return {
1024
- id: sessionId,
1025
- agent,
1026
- confidence: parseFloat(confidence),
1027
- detectedAt: Date.now(),
1028
- expires: Date.now() + 36e5
1029
- // 1 hour
1030
- };
1031
- }
1032
- const cookieHeader = headers["cookie"];
1033
- if (cookieHeader && cookieHeader.includes("__agentshield_session=")) {
1034
- const match = cookieHeader.match(/__agentshield_session=([^;]+)/);
1035
- if (match && match[1]) {
1036
- try {
1037
- const decoded = atob(match[1]);
1038
- return JSON.parse(decoded);
1039
- } catch {
1040
- }
1041
- }
1042
- }
1043
- return null;
1044
- } catch {
1045
- return null;
1046
- }
1047
- }
1048
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- published
1049
- // signature; narrowing it is a breaking change, deferred to a major.
1050
- static setHeaders(response, session) {
1051
- try {
1052
- if (response.setHeader) {
1053
- response.setHeader("KYA-Session-Agent", session.agent);
1054
- response.setHeader("KYA-Session-Confidence", session.confidence.toString());
1055
- response.setHeader("KYA-Session-Id", session.id);
1056
- } else if (response.headers && response.headers.set) {
1057
- response.headers.set("kya-session-agent", session.agent);
1058
- response.headers.set("kya-session-confidence", session.confidence.toString());
1059
- response.headers.set("kya-session-id", session.id);
1060
- }
1061
- } catch {
1062
- }
1063
- }
1064
- };
1065
- function createContextFromDetection(detection, request) {
1066
- return checkpointShared.createEvaluationContext({
1067
- agentType: detection.detectedAgent?.type,
1068
- agentName: detection.detectedAgent?.name,
1069
- agentVendor: detection.detectedAgent?.vendor,
1070
- confidence: detection.confidence,
1071
- riskLevel: detection.riskLevel,
1072
- path: request.nextUrl.pathname,
1073
- method: request.method,
1074
- // Cryptographic-signature methods only, mirroring the composed-policy
1075
- // VERIFIED_VERIFICATION_METHODS allowlist (checkpoint-wasm-runtime):
1076
- // 'signature' (bare RFC 9421 keyid) and 'tier1_rfc9421' (RFC 9421 vendor-key
1077
- // / Web Bot Auth, #4804) are the same crypto class; kya-http/kya-http-delegated
1078
- // are the draft-kya-http-02 §4.3 request-signature methods.
1079
- signatureVerified: detection.verificationMethod === "signature" || detection.verificationMethod === "tier1_rfc9421" || detection.verificationMethod === "kya-http" || detection.verificationMethod === "kya-http-delegated",
1080
- isAuthenticated: false,
1081
- // TODO: integrate with auth
1082
- userAgent: request.headers.get("user-agent") || void 0
1083
- });
1084
- }
1085
- function evaluatePolicyForDetection(detection, request, policy) {
1086
- const context = createContextFromDetection(detection, request);
1087
- return checkpointShared.evaluatePolicy(policy, context);
1088
- }
1089
- function buildBlockedResponse2(decision, config) {
1090
- const status = config.blockedResponse?.status ?? 403;
1091
- const message = config.blockedResponse?.message ?? decision.message ?? "Access denied";
1092
- const response = server.NextResponse.json(
1093
- {
1094
- error: message,
1095
- code: "POLICY_BLOCKED",
1096
- reason: decision.reason,
1097
- ruleId: decision.ruleId,
1098
- matchType: decision.matchType
1099
- },
1100
- { status }
1101
- );
1102
- if (config.blockedResponse?.headers) {
1103
- for (const [key, value] of Object.entries(config.blockedResponse.headers)) {
1104
- response.headers.set(key, value);
1105
- }
1106
- }
1107
- response.headers.set("KYA-Action", decision.action);
1108
- response.headers.set("KYA-Reason", decision.reason);
1109
- response.headers.set("KYA-Match-Type", decision.matchType);
1110
- return response;
1111
- }
1112
- function buildRedirectResponse2(request, decision, config, detection) {
1113
- const redirectUrl = decision.redirectUrl || config.redirectUrl || "/blocked";
1114
- const url = new URL(redirectUrl, request.url);
1115
- url.searchParams.set("reason", decision.reason);
1116
- if (decision.ruleId) {
1117
- url.searchParams.set("ruleId", decision.ruleId);
1118
- }
1119
- const agentName = detection?.detectedAgent?.name;
1120
- if (agentName && !url.searchParams.has("agent")) {
1121
- url.searchParams.set("agent", agentName.toLowerCase());
1122
- }
1123
- return server.NextResponse.redirect(url);
1124
- }
1125
- function buildChallengeResponse(request, decision, config, detection) {
1126
- return buildRedirectResponse2(request, decision, config, detection);
1127
- }
1128
- async function handlePolicyDecision(request, decision, config, detection) {
1129
- switch (decision.action) {
1130
- case checkpointShared.ENFORCEMENT_ACTIONS.BLOCK:
1131
- if (config.customBlockedResponse) {
1132
- return await config.customBlockedResponse(request, decision);
1133
- }
1134
- return buildBlockedResponse2(decision, config);
1135
- case checkpointShared.ENFORCEMENT_ACTIONS.REDIRECT:
1136
- return buildRedirectResponse2(request, decision, config, detection);
1137
- case checkpointShared.ENFORCEMENT_ACTIONS.CHALLENGE:
1138
- return buildChallengeResponse(request, decision, config, detection);
1139
- case checkpointShared.ENFORCEMENT_ACTIONS.LOG:
1140
- console.log("[Checkpoint] Policy decision (log):", {
1141
- path: request.nextUrl.pathname,
1142
- action: decision.action,
1143
- reason: decision.reason,
1144
- matchType: decision.matchType,
1145
- ruleId: decision.ruleId
1146
- });
1147
- return null;
1148
- // Continue to allow
1149
- case checkpointShared.ENFORCEMENT_ACTIONS.ALLOW:
1150
- default:
1151
- return null;
1152
- }
1153
- }
1154
- var fetcherCache = /* @__PURE__ */ new Map();
1155
- function getFetcherCacheKey(config) {
1156
- return `${config.apiUrl ?? "default"}:${config.apiKey ?? ""}:${config.cacheTtlSeconds ?? "default"}`;
1157
- }
1158
- function getPolicyFetcher(config) {
1159
- if (!config) {
1160
- throw new Error("fetchPolicy config required");
1161
- }
1162
- const cacheKey = getFetcherCacheKey(config);
1163
- let fetcher = fetcherCache.get(cacheKey);
1164
- if (!fetcher) {
1165
- const fetcherConfig = {
1166
- apiBaseUrl: config.apiUrl || "https://kya.vouched.id",
1167
- apiKey: config.apiKey,
1168
- cacheTtlSeconds: config.cacheTtlSeconds
1169
- };
1170
- fetcher = checkpointShared.createPolicyFetcher(fetcherConfig);
1171
- fetcherCache.set(cacheKey, fetcher);
1172
- }
1173
- return fetcher;
1174
- }
1175
- async function getPolicy(config) {
1176
- if (config.policy) {
1177
- return checkpointShared.PolicyConfigSchema.parse({ ...checkpointShared.DEFAULT_POLICY, ...config.policy });
1178
- }
1179
- if (config.fetchPolicy) {
1180
- try {
1181
- const fetcher = getPolicyFetcher(config.fetchPolicy);
1182
- return await fetcher.getPolicy(config.fetchPolicy.projectId);
1183
- } catch (error) {
1184
- if (config.debug) {
1185
- console.warn("[Checkpoint] Policy fetch failed, using fallback:", error);
1186
- }
1187
- return checkpointShared.PolicyConfigSchema.parse({
1188
- ...checkpointShared.DEFAULT_POLICY,
1189
- ...config.fallbackPolicy || {}
1190
- });
1191
- }
1192
- }
1193
- return checkpointShared.PolicyConfigSchema.parse(checkpointShared.DEFAULT_POLICY);
1194
- }
1195
- async function applyPolicy(request, detection, config) {
1196
- try {
1197
- const path = request.nextUrl.pathname;
1198
- if (config.skipPaths?.some((pattern) => checkpointShared.matchPath(path, pattern))) {
1199
- return null;
1200
- }
1201
- if (config.includePaths && config.includePaths.length > 0) {
1202
- if (!config.includePaths.some((pattern) => checkpointShared.matchPath(path, pattern))) {
1203
- return null;
1204
- }
1205
- }
1206
- const policy = await getPolicy(config);
1207
- const context = createContextFromDetection(detection, request);
1208
- const decision = checkpointShared.evaluatePolicy(policy, context);
1209
- if (config.onPolicyDecision) {
1210
- try {
1211
- await config.onPolicyDecision(request, decision, context);
1212
- } catch (error) {
1213
- if (config.debug) {
1214
- console.error("[Checkpoint] onPolicyDecision callback failed:", error);
1215
- }
1216
- }
1217
- }
1218
- return await handlePolicyDecision(request, decision, config, detection);
1219
- } catch (error) {
1220
- if (config.debug) {
1221
- console.error("[Checkpoint] Policy evaluation error:", error);
1222
- }
1223
- if (config.failOpen !== false) {
1224
- return null;
1225
- }
1226
- return server.NextResponse.json(
1227
- { error: "Security check failed", code: "POLICY_ERROR" },
1228
- { status: 503 }
1229
- );
1230
- }
1231
- }
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_middleware_core = require('./middleware-core-CMc-2QkU.js');
3
+ const require_middleware_node = require('./middleware-node.js');
4
+ const require_posture_outcome = require('./posture-outcome-DddsJtL8.js');
5
+ const require_api_client = require('./api-client.js');
6
+ const require_api_middleware = require('./api-middleware-Bf3xmM9W.js');
7
+
8
+ //#region src/index.ts
1232
9
  /**
1233
- * @fileoverview Checkpoint Next.js Integration
1234
- * @license MIT OR Apache-2.0
1235
- */
1236
-
1237
- Object.defineProperty(exports, "DEFAULT_POLICY", {
1238
- enumerable: true,
1239
- get: function () { return checkpointShared.DEFAULT_POLICY; }
1240
- });
1241
- Object.defineProperty(exports, "ENFORCEMENT_ACTIONS", {
1242
- enumerable: true,
1243
- get: function () { return checkpointShared.ENFORCEMENT_ACTIONS; }
1244
- });
1245
- Object.defineProperty(exports, "createEvaluationContext", {
1246
- enumerable: true,
1247
- get: function () { return checkpointShared.createEvaluationContext; }
1248
- });
1249
- Object.defineProperty(exports, "evaluatePolicy", {
1250
- enumerable: true,
1251
- get: function () { return checkpointShared.evaluatePolicy; }
1252
- });
1253
- exports.AgentShieldClient = AgentShieldClient;
1254
- exports.CheckpointApiClient = CheckpointApiClient;
1255
- exports.EdgeSessionTracker = EdgeSessionTracker;
1256
- exports.StatelessSessionChecker = StatelessSessionChecker;
1257
- exports.VERSION = VERSION;
1258
- exports.agentShieldMiddleware = agentShieldMiddleware;
1259
- exports.applyPolicy = applyPolicy;
1260
- exports.buildPolicyBlockedResponse = buildBlockedResponse2;
1261
- exports.buildPolicyRedirectResponse = buildRedirectResponse2;
1262
- exports.createAgentShieldMiddleware = createAgentShieldMiddleware2;
1263
- exports.createAgentShieldMiddlewareBase = createAgentShieldMiddleware;
1264
- exports.createContextFromDetection = createContextFromDetection;
1265
- exports.createEnhancedAgentShieldMiddleware = createEnhancedAgentShieldMiddleware;
1266
- exports.createMiddleware = createAgentShieldMiddleware2;
1267
- exports.evaluatePolicyForDetection = evaluatePolicyForDetection;
1268
- exports.getAgentShieldClient = getAgentShieldClient;
1269
- exports.getCheckpointApiClient = getCheckpointApiClient;
1270
- exports.getPolicy = getPolicy;
1271
- exports.handlePolicyDecision = handlePolicyDecision;
1272
- exports.resetAgentShieldClient = resetAgentShieldClient;
1273
- exports.resetCheckpointApiClient = resetCheckpointApiClient;
1274
- exports.withAgentShield = withAgentShield;
1275
- exports.withCheckpoint = withCheckpoint;
1276
- exports.withCheckpointApi = withCheckpointApi;
10
+ * @fileoverview Checkpoint Next.js Integration
11
+ * @license MIT OR Apache-2.0
12
+ *
13
+ * Two deployment shapes ship from this package:
14
+ *
15
+ * 1. `withCheckpoint` runs `kya-os-engine` in-process through WebAssembly:
16
+ * no network round trip per request, and every verdict comes from the
17
+ * engine.
18
+ * 2. `withCheckpointApi` sends each request to the hosted gateway instead. It
19
+ * is opt-in, for runtimes that cannot run WebAssembly.
20
+ *
21
+ * This is the `.` entry outside the Edge runtime, the same as `./node`: the
22
+ * engine's Node build, which loads its `.wasm` through `new URL(...,
23
+ * import.meta.url)`, so it works unbundled and when Next.js bundles `proxy.ts`
24
+ * or `middleware.ts` (the bundler copies the file it names). `index-edge.ts` is
25
+ * the `.` entry on the Edge runtime.
26
+ *
27
+ * See `README.md` ("Two deployment shapes").
28
+ */
29
+
30
+ //#endregion
31
+ exports.CheckpointApiClient = require_api_client.CheckpointApiClient;
32
+ exports.VERSION = require_middleware_core.VERSION;
33
+ exports.getCheckpointApiClient = require_api_client.getCheckpointApiClient;
34
+ exports.getCheckpointPostureOutcome = require_posture_outcome.getCheckpointPostureOutcome;
35
+ exports.resetCheckpointApiClient = require_api_client.resetCheckpointApiClient;
36
+ exports.withCheckpoint = require_middleware_node.withCheckpoint;
37
+ exports.withCheckpointApi = require_api_middleware.withCheckpointApi;