@kya-os/checkpoint-nextjs 1.9.0 → 1.10.0

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