@kya-os/checkpoint-nextjs 1.10.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 (210) hide show
  1. package/CHANGELOG.md +245 -0
  2. package/README.md +205 -31
  3. package/dist/{adapt.mjs → adapt-BdQ9R7Iw.mjs} +15 -4
  4. package/dist/adapt-BdQ9R7Iw.mjs.map +1 -0
  5. package/dist/{adapt.js → adapt-CCSKGjVH.js} +34 -13
  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 -204
  11. package/dist/api-client.d.ts +2 -204
  12. package/dist/api-client.js +19 -18
  13. package/dist/api-client.mjs +20 -16
  14. package/dist/api-client.mjs.map +1 -1
  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-CDSh3TSE.js → api-middleware-Bf3xmM9W.js} +75 -63
  18. package/dist/{api-middleware-CMDRoQik.mjs → api-middleware-C-ngFX_8.mjs} +68 -38
  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 -152
  23. package/dist/api-middleware.d.ts +2 -152
  24. package/dist/api-middleware.js +1 -5
  25. package/dist/api-middleware.mjs +2 -3
  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-Doe0Tn53.d.mts → config-CPP1RV0f.d.mts} +65 -29
  34. package/dist/config-CPP1RV0f.d.mts.map +1 -0
  35. package/dist/{config-CbAg2mze.d.ts → config-DVgOFxJs.d.ts} +66 -30
  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 -10
  49. package/dist/index.d.ts +8 -10
  50. package/dist/index.js +20 -49
  51. package/dist/index.mjs +21 -8
  52. package/dist/index.mjs.map +1 -1
  53. package/dist/middleware-bundler.d.mts +1 -1
  54. package/dist/middleware-bundler.d.mts.map +1 -1
  55. package/dist/middleware-bundler.d.ts +1 -1
  56. package/dist/middleware-bundler.d.ts.map +1 -1
  57. package/dist/middleware-bundler.js +4 -4
  58. package/dist/middleware-bundler.mjs +4 -4
  59. package/dist/middleware-bundler.mjs.map +1 -1
  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 +11 -3
  68. package/dist/middleware-edge.d.mts.map +1 -1
  69. package/dist/middleware-edge.d.ts +11 -3
  70. package/dist/middleware-edge.d.ts.map +1 -1
  71. package/dist/middleware-edge.js +77 -24
  72. package/dist/middleware-edge.mjs +74 -23
  73. package/dist/middleware-edge.mjs.map +1 -1
  74. package/dist/{middleware-node-context-rgnc7UNR.js → middleware-node-context-591KsiYg.js} +8 -7
  75. package/dist/{middleware-node-context-BqPbf-fI.mjs → middleware-node-context-D_ZyUEcA.mjs} +6 -5
  76. package/dist/middleware-node-context-D_ZyUEcA.mjs.map +1 -0
  77. package/dist/middleware-node.d.mts +12 -3
  78. package/dist/middleware-node.d.mts.map +1 -0
  79. package/dist/middleware-node.d.ts +12 -3
  80. package/dist/middleware-node.d.ts.map +1 -0
  81. package/dist/middleware-node.js +13 -5
  82. package/dist/middleware-node.mjs +13 -5
  83. package/dist/middleware-node.mjs.map +1 -1
  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 +27 -62
  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 -11
  101. package/dist/adapt.d.mts.map +0 -1
  102. package/dist/adapt.d.ts +0 -11
  103. package/dist/adapt.d.ts.map +0 -1
  104. package/dist/adapt.mjs.map +0 -1
  105. package/dist/api-client.d.mts.map +0 -1
  106. package/dist/api-client.d.ts.map +0 -1
  107. package/dist/api-middleware-CMDRoQik.mjs.map +0 -1
  108. package/dist/api-middleware.d.mts.map +0 -1
  109. package/dist/api-middleware.d.ts.map +0 -1
  110. package/dist/composed-policy-BCaNiVHv.d.mts +0 -98
  111. package/dist/composed-policy-BCaNiVHv.d.mts.map +0 -1
  112. package/dist/composed-policy-zzJYNFTb.d.ts +0 -98
  113. package/dist/composed-policy-zzJYNFTb.d.ts.map +0 -1
  114. package/dist/composed-policy.d.mts +0 -2
  115. package/dist/composed-policy.d.ts +0 -2
  116. package/dist/composed-policy.js +0 -136
  117. package/dist/composed-policy.mjs +0 -132
  118. package/dist/composed-policy.mjs.map +0 -1
  119. package/dist/config-CbAg2mze.d.ts.map +0 -1
  120. package/dist/config-Doe0Tn53.d.mts.map +0 -1
  121. package/dist/create-middleware.d.mts +0 -11
  122. package/dist/create-middleware.d.mts.map +0 -1
  123. package/dist/create-middleware.d.ts +0 -11
  124. package/dist/create-middleware.d.ts.map +0 -1
  125. package/dist/create-middleware.js +0 -39
  126. package/dist/create-middleware.mjs +0 -38
  127. package/dist/create-middleware.mjs.map +0 -1
  128. package/dist/edge/index.d.mts +0 -88
  129. package/dist/edge/index.d.mts.map +0 -1
  130. package/dist/edge/index.d.ts +0 -88
  131. package/dist/edge/index.d.ts.map +0 -1
  132. package/dist/edge/index.js +0 -362
  133. package/dist/edge/index.mjs +0 -362
  134. package/dist/edge/index.mjs.map +0 -1
  135. package/dist/edge-runtime-loader.d.mts +0 -49
  136. package/dist/edge-runtime-loader.d.mts.map +0 -1
  137. package/dist/edge-runtime-loader.d.ts +0 -49
  138. package/dist/edge-runtime-loader.d.ts.map +0 -1
  139. package/dist/edge-runtime-loader.js +0 -297
  140. package/dist/edge-runtime-loader.mjs +0 -292
  141. package/dist/edge-runtime-loader.mjs.map +0 -1
  142. package/dist/edge-wasm-middleware.d.mts +0 -43
  143. package/dist/edge-wasm-middleware.d.mts.map +0 -1
  144. package/dist/edge-wasm-middleware.d.ts +0 -43
  145. package/dist/edge-wasm-middleware.d.ts.map +0 -1
  146. package/dist/edge-wasm-middleware.js +0 -37
  147. package/dist/edge-wasm-middleware.mjs +0 -35
  148. package/dist/edge-wasm-middleware.mjs.map +0 -1
  149. package/dist/middleware-core-BYQP9FND.mjs +0 -165
  150. package/dist/middleware-core-BYQP9FND.mjs.map +0 -1
  151. package/dist/middleware-core-D6TijE6P.js +0 -175
  152. package/dist/middleware-node-CE4GevYs.d.ts +0 -20
  153. package/dist/middleware-node-CE4GevYs.d.ts.map +0 -1
  154. package/dist/middleware-node-DtyOuPta.d.mts +0 -20
  155. package/dist/middleware-node-DtyOuPta.d.mts.map +0 -1
  156. package/dist/middleware-node-context-BqPbf-fI.mjs.map +0 -1
  157. package/dist/middleware.d.mts +0 -25
  158. package/dist/middleware.d.mts.map +0 -1
  159. package/dist/middleware.d.ts +0 -25
  160. package/dist/middleware.d.ts.map +0 -1
  161. package/dist/middleware.js +0 -53
  162. package/dist/middleware.mjs +0 -51
  163. package/dist/middleware.mjs.map +0 -1
  164. package/dist/nodejs-wasm-loader.d.mts +0 -42
  165. package/dist/nodejs-wasm-loader.d.mts.map +0 -1
  166. package/dist/nodejs-wasm-loader.d.ts +0 -42
  167. package/dist/nodejs-wasm-loader.d.ts.map +0 -1
  168. package/dist/nodejs-wasm-loader.js +0 -70
  169. package/dist/nodejs-wasm-loader.mjs +0 -66
  170. package/dist/nodejs-wasm-loader.mjs.map +0 -1
  171. package/dist/policy.d.mts +0 -138
  172. package/dist/policy.d.mts.map +0 -1
  173. package/dist/policy.d.ts +0 -138
  174. package/dist/policy.d.ts.map +0 -1
  175. package/dist/policy.js +0 -236
  176. package/dist/policy.mjs +0 -205
  177. package/dist/policy.mjs.map +0 -1
  178. package/dist/session-tracker.d.mts +0 -50
  179. package/dist/session-tracker.d.mts.map +0 -1
  180. package/dist/session-tracker.d.ts +0 -50
  181. package/dist/session-tracker.d.ts.map +0 -1
  182. package/dist/session-tracker.js +0 -148
  183. package/dist/session-tracker.mjs +0 -147
  184. package/dist/session-tracker.mjs.map +0 -1
  185. package/dist/translate.d.mts +0 -48
  186. package/dist/translate.d.mts.map +0 -1
  187. package/dist/translate.d.ts +0 -48
  188. package/dist/translate.d.ts.map +0 -1
  189. package/dist/translate.js +0 -79
  190. package/dist/translate.mjs +0 -79
  191. package/dist/translate.mjs.map +0 -1
  192. package/dist/types-C0SkqLMM.d.mts +0 -102
  193. package/dist/types-C0SkqLMM.d.mts.map +0 -1
  194. package/dist/types-C7DNSCTO.d.ts +0 -102
  195. package/dist/types-C7DNSCTO.d.ts.map +0 -1
  196. package/dist/utils-Cj4XNhIY.mjs +0 -35
  197. package/dist/utils-Cj4XNhIY.mjs.map +0 -1
  198. package/dist/utils-DAisnYnI.js +0 -45
  199. package/dist/wasm-setup.d.mts +0 -47
  200. package/dist/wasm-setup.d.mts.map +0 -1
  201. package/dist/wasm-setup.d.ts +0 -47
  202. package/dist/wasm-setup.d.ts.map +0 -1
  203. package/dist/wasm-setup.js +0 -91
  204. package/dist/wasm-setup.mjs +0 -95
  205. package/dist/wasm-setup.mjs.map +0 -1
  206. package/wasm/agentshield_wasm.d.ts +0 -479
  207. package/wasm/agentshield_wasm.js +0 -1536
  208. package/wasm/agentshield_wasm_bg.wasm +0 -0
  209. package/wasm/package.json +0 -30
  210. package/wasm.d.ts +0 -21
@@ -1 +1 @@
1
- {"version":3,"file":"api-client.mjs","names":[],"sources":["../src/api-client.ts"],"sourcesContent":["/**\n * AgentShield API Client\n *\n * Lightweight client for calling the AgentShield enforce API from middleware.\n * Designed for Edge Runtime compatibility (no Node.js-specific APIs).\n */\n\nimport type { DetectionDetail, EnforcementAction } from '@kya-os/checkpoint-shared';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * API client configuration\n */\nexport interface CheckpointApiClientConfig {\n /** API key for authentication */\n apiKey: string;\n /** API base URL (defaults to production) */\n baseUrl?: string;\n /**\n * Use edge detection for lower latency (~30-50ms vs ~150ms) and better coverage.\n * Edge detection can identify non-JS clients (curl, Python, Claude Code WebFetch)\n * that the pixel cannot detect since they don't execute JavaScript.\n * @default true\n */\n useEdge?: boolean;\n /** Request timeout in milliseconds (default: 5000) */\n timeout?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * Enforcement action — re-exported from `@kya-os/checkpoint-shared`\n * so consumers of this package can keep importing it from the same\n * place. The canonical 6-value union is defined in\n * `packages/checkpoint-shared/src/policy/constants.ts`. `'instruct'`\n * tells the middleware to emit a 401 with a KYA-OS Link header\n * pointing the agent at a connect/consent URL.\n */\nexport type { EnforcementAction };\n\n/**\n * Enforcement decision from the API\n */\nexport interface EnforcementDecision {\n action: EnforcementAction;\n reason: string;\n isAgent: boolean;\n confidence: number;\n agentName?: string;\n agentType?: string;\n redirectUrl?: string;\n message?: string;\n metadata?: {\n policyVersion?: string;\n signatureVerified?: boolean;\n denyListMatch?: {\n clientDid?: string;\n agentDid?: string;\n clientName?: string;\n reason?: string;\n };\n };\n}\n\n/**\n * Detection detail (optional in response)\n */\nexport type ApiDetectionDetail = Omit<\n DetectionDetail,\n 'detectionClass' | 'verificationMethod' | 'reasons' | 'signals' | 'timestamp'\n> & {\n agentName?: string;\n /** Detection class: 'human', 'ai_agent', 'bot', 'incomplete_data' */\n detectionClass?: string;\n verificationMethod?: string;\n reasons?: string[];\n signals?: DetectionDetail['signals'];\n timestamp?: DetectionDetail['timestamp'];\n /** Detection engine used: 'wasm' or 'javascript-fallback' */\n detectionMethod?: string;\n /**\n * Ordered `detection/*` reason codes (KYA-1107 signal exposure; carried\n * on every enforce detection payload alongside the populated `signals`\n * list). Deliberately `string[]` rather than\n * the registry union so an older SDK build tolerates codes added\n * server-side later; the registry lives in\n * `@kya-os/checkpoint-shared` (`DETECTION_REASON_CODES`).\n */\n reasonCodes?: string[];\n};\n\n/**\n * @deprecated Use ApiDetectionDetail.\n */\nexport type { ApiDetectionDetail as DetectionResult };\n\n/**\n * Enforce API response\n */\nexport interface EnforceResponse {\n success: boolean;\n data?: {\n decision: EnforcementDecision;\n processingTimeMs: number;\n requestId: string;\n detection?: ApiDetectionDetail;\n };\n error?: {\n code: string;\n message: string;\n };\n}\n\n/**\n * Request input for enforce API\n */\nexport interface EnforceInput {\n /** HTTP headers from the incoming request */\n headers?: Record<string, string>;\n /** User-Agent header */\n userAgent?: string;\n /** Client IP address */\n ipAddress?: string;\n /** Request path */\n path?: string;\n /** Request URL */\n url?: string;\n /** HTTP method */\n method?: string;\n /** Request ID for tracing */\n requestId?: string;\n /** Options */\n options?: {\n /** Include full detection result */\n includeDetectionResult?: boolean;\n /** Cache TTL override */\n cacheTTL?: number;\n };\n}\n\n/**\n * Input for logging a detection result\n */\nexport interface LogDetectionInput {\n /** Detection result from Gateway */\n detection: ApiDetectionDetail;\n /** Request context */\n context: {\n userAgent?: string;\n ipAddress?: string;\n path?: string;\n url?: string;\n method?: string;\n };\n /** Source of the detection */\n source?: 'gateway' | 'middleware';\n}\n\n// ============================================================================\n// Client Implementation\n// ============================================================================\n\nconst DEFAULT_BASE_URL = 'https://kya.vouched.id';\nconst EDGE_DETECT_URL = 'https://detect.checkpoint-gateway.ai';\nconst DEFAULT_TIMEOUT = 5000;\n\n/**\n * AgentShield API Client\n *\n * @example\n * ```typescript\n * const client = new CheckpointApiClient({\n * apiKey: process.env.CHECKPOINT_API_KEY!,\n * });\n *\n * const result = await client.enforce({\n * headers: Object.fromEntries(request.headers),\n * path: request.nextUrl.pathname,\n * method: request.method,\n * });\n *\n * if (result.decision.action === 'block') {\n * return new Response('Access denied', { status: 403 });\n * }\n * ```\n */\nexport class CheckpointApiClient {\n private apiKey: string;\n private baseUrl: string;\n private useEdge: boolean;\n private timeout: number;\n private debug: boolean;\n\n constructor(config: CheckpointApiClientConfig) {\n if (!config.apiKey) {\n throw new Error('Checkpoint API key is required');\n }\n\n this.apiKey = config.apiKey;\n // Default to edge detection for better coverage (detects non-JS clients)\n this.useEdge = config.useEdge !== false; // true by default\n this.baseUrl = config.baseUrl || (this.useEdge ? EDGE_DETECT_URL : DEFAULT_BASE_URL);\n this.timeout = config.timeout || DEFAULT_TIMEOUT;\n this.debug = config.debug || false;\n }\n\n /**\n * Call the enforce API to check if a request should be allowed\n */\n async enforce(input: EnforceInput): Promise<EnforceResponse> {\n const startTime = Date.now();\n\n try {\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n // Use edge endpoint or Vercel API based on configuration\n const endpoint = this.useEdge\n ? `${this.baseUrl}/__detect/enforce`\n : `${this.baseUrl}/api/v1/enforce`;\n\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-Request-ID': input.requestId || crypto.randomUUID(),\n },\n body: JSON.stringify(input),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Parse response\n const data = (await response.json()) as EnforceResponse;\n\n if (this.debug) {\n console.log('[Checkpoint] Enforce response:', {\n status: response.status,\n action: data.data?.decision.action,\n processingTimeMs: Date.now() - startTime,\n });\n }\n\n // Handle non-2xx responses\n if (!response.ok) {\n return {\n success: false,\n error: {\n code: `HTTP_${response.status}`,\n message: data.error?.message || `HTTP error: ${response.status}`,\n },\n };\n }\n\n return data;\n } catch (error) {\n clearTimeout(timeoutId);\n throw error;\n }\n } catch (error) {\n // Handle timeout\n if (error instanceof Error && error.name === 'AbortError') {\n if (this.debug) {\n console.warn('[Checkpoint] Request timed out');\n }\n return {\n success: false,\n error: {\n code: 'TIMEOUT',\n message: `Request timed out after ${this.timeout}ms`,\n },\n };\n }\n\n // Handle network errors\n if (this.debug) {\n console.error('[Checkpoint] Request failed:', error);\n }\n\n return {\n success: false,\n error: {\n code: 'NETWORK_ERROR',\n message: error instanceof Error ? error.message : 'Network request failed',\n },\n };\n }\n }\n\n /**\n * Quick check - returns just the action without full response parsing\n * Useful for very fast middleware that just needs allow/block\n */\n async quickCheck(input: EnforceInput): Promise<{\n action: EnforcementAction;\n error?: string;\n }> {\n const result = await this.enforce(input);\n\n if (!result.success || !result.data) {\n // On error, default to allow (fail-open)\n return {\n action: 'allow',\n error: result.error?.message,\n };\n }\n\n return {\n action: result.data.decision.action,\n };\n }\n\n /**\n * Check if this client is using edge detection (Gateway Worker)\n */\n isUsingEdge(): boolean {\n return this.useEdge;\n }\n\n /**\n * Log a detection result to AgentShield database.\n * Use after Gateway Worker detection to persist results.\n * Fire-and-forget - returns immediately without waiting for DB write.\n *\n * @example\n * ```typescript\n * // After receiving Gateway response\n * if (client.isUsingEdge() && response.data?.detection) {\n * client.logDetection({\n * detection: response.data.detection,\n * context: { userAgent, ipAddress, path, url, method }\n * }).catch(err => console.error('Log failed:', err));\n * }\n * ```\n */\n async logDetection(input: LogDetectionInput): Promise<void> {\n // Don't await - fire and forget\n // Use the base URL (not edge) for logging since this goes to the main API\n const logEndpoint = this.useEdge\n ? `${DEFAULT_BASE_URL}/api/v1/log-detection`\n : `${this.baseUrl}/api/v1/log-detection`;\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(logEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({\n detection: {\n isAgent: input.detection.isAgent,\n confidence: input.detection.confidence,\n agentName: input.detection.agentName,\n agentType: input.detection.agentType,\n detectionClass: input.detection.detectionClass,\n verificationMethod: input.detection.verificationMethod,\n reasons: input.detection.reasons,\n },\n context: input.context,\n source: input.source || 'gateway',\n }),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok && this.debug) {\n console.warn('[Checkpoint] Log detection returned non-2xx:', response.status);\n }\n } catch (error) {\n clearTimeout(timeoutId);\n throw error;\n }\n } catch (error) {\n // Silently fail for fire-and-forget, but log in debug mode\n if (this.debug) {\n console.error('[Checkpoint] Log detection failed:', error);\n }\n // Re-throw so caller can catch if needed\n throw error;\n }\n }\n}\n\n/**\n * Create a cached client instance for a resolved configuration.\n *\n * @example\n * ```typescript\n * // In middleware.ts\n * import { getCheckpointApiClient } from '@kya-os/checkpoint-nextjs';\n *\n * const client = getCheckpointApiClient();\n * ```\n */\nconst clientInstances = new Map<string, CheckpointApiClient>();\n\nfunction resolveClientConfig(\n config?: Partial<CheckpointApiClientConfig>\n): CheckpointApiClientConfig {\n const apiKey = config?.apiKey || process.env.CHECKPOINT_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n 'Checkpoint API key is required. Set CHECKPOINT_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n return {\n apiKey,\n baseUrl: config?.baseUrl || process.env.CHECKPOINT_API_URL,\n // Default to edge detection unless explicitly disabled\n useEdge: config?.useEdge ?? process.env.CHECKPOINT_USE_EDGE !== 'false',\n timeout: config?.timeout,\n debug: config?.debug || process.env.CHECKPOINT_DEBUG === 'true',\n };\n}\n\nfunction clientCacheKey(config: CheckpointApiClientConfig): string {\n return JSON.stringify([\n config.apiKey,\n config.baseUrl ?? '',\n config.useEdge ?? true,\n config.timeout ?? DEFAULT_TIMEOUT,\n config.debug ?? false,\n ]);\n}\n\nexport function getCheckpointApiClient(\n config?: Partial<CheckpointApiClientConfig>\n): CheckpointApiClient {\n const resolvedConfig = resolveClientConfig(config);\n const key = clientCacheKey(resolvedConfig);\n let clientInstance = clientInstances.get(key);\n\n if (!clientInstance) {\n clientInstance = new CheckpointApiClient(resolvedConfig);\n clientInstances.set(key, clientInstance);\n }\n\n return clientInstance;\n}\n\n/**\n * Reset the singleton client (useful for testing)\n */\nexport function resetCheckpointApiClient(): void {\n clientInstances.clear();\n}\n\n// ---------------------------------------------------------------------------\n// Back-compat aliases (Phase D rename — `AgentShield*` → `CheckpointApi*`).\n//\n// The SaaS-API deployment shape is preserved post-Phase-D — it talks to\n// the Cloudflare DNS gateway and remains a supported deployment option\n// alongside the local-engine `withCheckpoint` path. The names changed\n// to align with the rest of the `checkpoint-*` packages; the old names\n// stay live as @deprecated aliases for one release.\n// ---------------------------------------------------------------------------\n\n/** @deprecated Renamed to {@link CheckpointApiClient}. The runtime is identical. */\nexport const AgentShieldClient = CheckpointApiClient;\n\n/** @deprecated Renamed to {@link CheckpointApiClientConfig}. */\nexport type AgentShieldClientConfig = CheckpointApiClientConfig;\n\n/** @deprecated Renamed to {@link getCheckpointApiClient}. */\nexport const getAgentShieldClient = getCheckpointApiClient;\n\n/** @deprecated Renamed to {@link resetCheckpointApiClient}. */\nexport const resetAgentShieldClient = resetCheckpointApiClient;\n"],"mappings":";AAsKA,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;AAsBxB,IAAa,sBAAb,MAAiC;CAC/B,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAY,QAAmC;EAC7C,IAAI,CAAC,OAAO,QACV,MAAM,IAAI,MAAM,gCAAgC;EAGlD,KAAK,SAAS,OAAO;EAErB,KAAK,UAAU,OAAO,YAAY;EAClC,KAAK,UAAU,OAAO,YAAY,KAAK,UAAU,kBAAkB;EACnE,KAAK,UAAU,OAAO,WAAW;EACjC,KAAK,QAAQ,OAAO,SAAS;CAC/B;;;;CAKA,MAAM,QAAQ,OAA+C;EAC3D,MAAM,YAAY,KAAK,IAAI;EAE3B,IAAI;GAEF,MAAM,aAAa,IAAI,gBAAgB;GACvC,MAAM,YAAY,iBAAiB,WAAW,MAAM,GAAG,KAAK,OAAO;GAEnE,IAAI;IAEF,MAAM,WAAW,KAAK,UAClB,GAAG,KAAK,QAAQ,qBAChB,GAAG,KAAK,QAAQ;IAEpB,MAAM,WAAW,MAAM,MAAM,UAAU;KACrC,QAAQ;KACR,SAAS;MACP,gBAAgB;MAChB,eAAe,UAAU,KAAK;MAC9B,gBAAgB,MAAM,aAAa,OAAO,WAAW;KACvD;KACA,MAAM,KAAK,UAAU,KA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iB,oBAAoB,MAAM;CACjD,MAAM,MAAM,eAAe,cAAc;CACzC,IAAI,iBAAiB,gBAAgB,IAAI,GAAG;CAE5C,IAAI,CAAC,gBAAgB;EACnB,iBAAiB,IAAI,oBAAoB,cAAc;EACvD,gBAAgB,IAAI,KAAK,cAAc;CACzC;CAEA,OAAO;AACT;;;;AAKA,SAAgB,2BAAiC;CAC/C,gBAAgB,MAAM;AACxB;;AAaA,MAAa,oBAAoB;;AAMjC,MAAa,uBAAuB;;AAGpC,MAAa,yBAAyB"}
1
+ {"version":3,"file":"api-client.mjs","names":[],"sources":["../src/api-client.ts"],"sourcesContent":["/**\n * Checkpoint API Client\n *\n * Lightweight client for calling the Checkpoint enforce API from middleware.\n * Designed for Edge Runtime compatibility (no Node.js-specific APIs).\n */\n\nimport type { DetectionDetail, EnforcementAction, EngineInfo } from '@kya-os/checkpoint-shared';\nimport { relayHeaders } from './utils';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * API client configuration\n */\nexport interface CheckpointApiClientConfig {\n /** API key for authentication */\n apiKey: string;\n /** API base URL (defaults to production) */\n baseUrl?: string;\n /**\n * Use edge detection for lower latency (~30-50ms vs ~150ms) and better coverage.\n * Edge detection can identify non-JS clients (curl, Python, Claude Code WebFetch)\n * that the pixel cannot detect since they don't execute JavaScript.\n * @default true\n */\n useEdge?: boolean;\n /** Request timeout in milliseconds (default: 5000) */\n timeout?: number;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n/**\n * Enforcement action — re-exported from `@kya-os/checkpoint-shared`\n * so consumers of this package can keep importing it from the same\n * place. The canonical 6-value union is defined in\n * `packages/checkpoint-shared/src/policy/constants.ts`. `'instruct'`\n * tells the middleware to emit a 401 with a KYA-OS Link header\n * pointing the agent at a connect/consent URL.\n */\nexport type { EnforcementAction };\n\n/**\n * Enforcement decision from the API\n */\nexport interface EnforcementDecision {\n action: EnforcementAction;\n reason: string;\n isAgent: boolean;\n confidence: number;\n agentName?: string;\n agentType?: string;\n redirectUrl?: string;\n message?: string;\n metadata?: {\n policyVersion?: string;\n signatureVerified?: boolean;\n denyListMatch?: {\n clientDid?: string;\n agentDid?: string;\n clientName?: string;\n reason?: string;\n };\n rateLimit?: {\n limit?: number;\n retryAfterSeconds?: number;\n wouldBlock?: boolean;\n skipped?: 'no_client_ip';\n };\n };\n}\n\n/**\n * Detection detail (optional in response)\n */\nexport type ApiDetectionDetail = Omit<\n DetectionDetail,\n 'detectionClass' | 'verificationMethod' | 'reasons' | 'signals' | 'timestamp'\n> & {\n agentName?: string;\n /** Detection class: 'human', 'ai_agent', 'bot', 'incomplete_data' */\n detectionClass?: string;\n verificationMethod?: string;\n reasons?: string[];\n signals?: DetectionDetail['signals'];\n timestamp?: DetectionDetail['timestamp'];\n /** Detection engine used: 'wasm' or 'javascript-fallback' */\n detectionMethod?: string;\n detectionBasis?: string;\n /**\n * Ordered `detection/*` reason codes (KYA-1107 signal exposure; carried\n * on every enforce detection payload alongside the populated `signals`\n * list). Deliberately `string[]` rather than\n * the registry union so an older SDK build tolerates codes added\n * server-side later; the registry lives in\n * `@kya-os/checkpoint-shared` (`DETECTION_REASON_CODES`).\n */\n reasonCodes?: string[];\n};\n\n/**\n * Enforce API response\n */\nexport interface EnforceResponse {\n success: boolean;\n data?: {\n decision: EnforcementDecision;\n processingTimeMs: number;\n requestId: string;\n detection?: ApiDetectionDetail;\n /**\n * Self-identification of the engine that ran the detection (the gateway\n * worker's `checkpoint-worker-wasm`). Absent when the gateway could not\n * compute it.\n */\n engine?: EngineInfo;\n };\n error?: {\n code: string;\n message: string;\n };\n}\n\n/**\n * Request input for enforce API\n */\nexport interface EnforceInput {\n /** HTTP headers from the incoming request */\n headers?: Record<string, string>;\n /** User-Agent header */\n userAgent?: string;\n /** Client IP address */\n ipAddress?: string;\n /** Request path */\n path?: string;\n /** Request URL */\n url?: string;\n /** HTTP method */\n method?: string;\n /** Request ID for tracing */\n requestId?: string;\n /** Options */\n options?: {\n /** Include full detection result */\n includeDetectionResult?: boolean;\n /** Cache TTL override */\n cacheTTL?: number;\n };\n}\n\n/**\n * Input for logging a detection result\n */\nexport interface LogDetectionInput {\n /** Detection result from Gateway */\n detection: ApiDetectionDetail;\n /** Request context */\n context: {\n userAgent?: string;\n ipAddress?: string;\n path?: string;\n url?: string;\n method?: string;\n };\n /** Source of the detection */\n source?: 'gateway' | 'middleware';\n /** The enforcement decision the caller received and acted on. */\n enforcement?: { action: EnforcementAction };\n /** Self-identification of the engine that produced the detection. */\n engine?: EngineInfo;\n /** Self-identification of the reporting SDK: package, version and Next.js runtime. */\n sdk?: { name: string; version: string; runtime: 'node' | 'edge' };\n}\n\n// ============================================================================\n// Client Implementation\n// ============================================================================\n\nconst DEFAULT_BASE_URL = 'https://kya.vouched.id';\nconst EDGE_DETECT_URL = 'https://detect.checkpoint-gateway.ai';\nconst DEFAULT_TIMEOUT = 5000;\n\n/**\n * Checkpoint API Client\n *\n * @example\n * ```typescript\n * const client = new CheckpointApiClient({\n * apiKey: process.env.CHECKPOINT_API_KEY!,\n * });\n *\n * const result = await client.enforce({\n * headers: Object.fromEntries(request.headers),\n * path: request.nextUrl.pathname,\n * method: request.method,\n * });\n *\n * if (result.decision.action === 'block') {\n * return new Response('Access denied', { status: 403 });\n * }\n * ```\n */\nexport class CheckpointApiClient {\n private apiKey: string;\n private baseUrl: string;\n private useEdge: boolean;\n private timeout: number;\n private debug: boolean;\n\n constructor(config: CheckpointApiClientConfig) {\n if (!config.apiKey) {\n throw new Error('Checkpoint API key is required');\n }\n\n this.apiKey = config.apiKey;\n // Default to edge detection for better coverage (detects non-JS clients)\n this.useEdge = config.useEdge !== false; // true by default\n this.baseUrl = config.baseUrl || (this.useEdge ? EDGE_DETECT_URL : DEFAULT_BASE_URL);\n this.timeout = config.timeout || DEFAULT_TIMEOUT;\n this.debug = config.debug || false;\n }\n\n /**\n * Call the enforce API to check if a request should be allowed\n */\n async enforce(input: EnforceInput): Promise<EnforceResponse> {\n const startTime = Date.now();\n\n try {\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n // Use edge endpoint or Vercel API based on configuration\n const endpoint = this.useEdge\n ? `${this.baseUrl}/__detect/enforce`\n : `${this.baseUrl}/api/v1/enforce`;\n\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n 'X-Request-ID': input.requestId || crypto.randomUUID(),\n },\n body: JSON.stringify({\n ...input,\n headers: input.headers && relayHeaders(input.headers),\n }),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Parse response\n const data = (await response.json()) as EnforceResponse;\n\n if (this.debug) {\n console.log('[Checkpoint] Enforce response:', {\n status: response.status,\n action: data.data?.decision.action,\n processingTimeMs: Date.now() - startTime,\n });\n }\n\n // Handle non-2xx responses\n if (!response.ok) {\n return {\n success: false,\n error: {\n code: `HTTP_${response.status}`,\n message: data.error?.message || `HTTP error: ${response.status}`,\n },\n };\n }\n\n return data;\n } catch (error) {\n clearTimeout(timeoutId);\n throw error;\n }\n } catch (error) {\n // Handle timeout\n if (error instanceof Error && error.name === 'AbortError') {\n if (this.debug) {\n console.warn('[Checkpoint] Request timed out');\n }\n return {\n success: false,\n error: {\n code: 'TIMEOUT',\n message: `Request timed out after ${this.timeout}ms`,\n },\n };\n }\n\n // Handle network errors\n if (this.debug) {\n console.error('[Checkpoint] Request failed:', error);\n }\n\n return {\n success: false,\n error: {\n code: 'NETWORK_ERROR',\n message: error instanceof Error ? error.message : 'Network request failed',\n },\n };\n }\n }\n\n /**\n * Quick check - returns just the action without full response parsing\n * Useful for very fast middleware that just needs allow/block. On an API\n * error the action is `block` (fail-closed) with `error` set.\n */\n async quickCheck(input: EnforceInput): Promise<{\n action: EnforcementAction;\n error?: string;\n }> {\n const result = await this.enforce(input);\n\n if (!result.success || !result.data) {\n return {\n action: 'block',\n error: result.error?.message,\n };\n }\n\n return {\n action: result.data.decision.action,\n };\n }\n\n /**\n * Check if this client is using edge detection (Gateway Worker)\n */\n isUsingEdge(): boolean {\n return this.useEdge;\n }\n\n /**\n * Log a detection result to the Checkpoint database.\n * Use after Gateway Worker detection to persist results.\n * Fire-and-forget - returns immediately without waiting for DB write.\n *\n * @example\n * ```typescript\n * // After receiving Gateway response\n * if (client.isUsingEdge() && response.data?.detection) {\n * client.logDetection({\n * detection: response.data.detection,\n * context: { userAgent, ipAddress, path, url, method }\n * }).catch(err => console.error('Log failed:', err));\n * }\n * ```\n */\n async logDetection(input: LogDetectionInput): Promise<void> {\n // Don't await - fire and forget\n // Use the base URL (not edge) for logging since this goes to the main API\n const logEndpoint = this.useEdge\n ? `${DEFAULT_BASE_URL}/api/v1/log-detection`\n : `${this.baseUrl}/api/v1/log-detection`;\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(logEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({\n detection: {\n isAgent: input.detection.isAgent,\n confidence: input.detection.confidence,\n agentName: input.detection.agentName,\n agentType: input.detection.agentType,\n detectionClass: input.detection.detectionClass,\n verificationMethod: input.detection.verificationMethod,\n reasons: input.detection.reasons,\n detectionBasis:\n typeof input.detection.detectionBasis === 'string'\n ? input.detection.detectionBasis\n : undefined,\n },\n context: input.context,\n source: input.source || 'gateway',\n // Optional blocks; JSON.stringify drops the ones left undefined, so\n // a caller that sends none posts the same body as before.\n enforcement: input.enforcement,\n engine: input.engine,\n sdk: input.sdk,\n }),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok && this.debug) {\n console.warn('[Checkpoint] Log detection returned non-2xx:', response.status);\n }\n } catch (error) {\n clearTimeout(timeoutId);\n throw error;\n }\n } catch (error) {\n // Silently fail for fire-and-forget, but log in debug mode\n if (this.debug) {\n console.error('[Checkpoint] Log detection failed:', error);\n }\n // Re-throw so caller can catch if needed\n throw error;\n }\n }\n}\n\n/**\n * Create a cached client instance for a resolved configuration.\n *\n * @example\n * ```typescript\n * // In middleware.ts\n * import { getCheckpointApiClient } from '@kya-os/checkpoint-nextjs';\n *\n * const client = getCheckpointApiClient();\n * ```\n */\nconst clientInstances = new Map<string, CheckpointApiClient>();\n\nfunction resolveClientConfig(\n config?: Partial<CheckpointApiClientConfig>\n): CheckpointApiClientConfig {\n const apiKey = config?.apiKey || process.env.CHECKPOINT_API_KEY;\n\n if (!apiKey) {\n throw new Error(\n 'Checkpoint API key is required. Set CHECKPOINT_API_KEY environment variable or pass apiKey in config.'\n );\n }\n\n return {\n apiKey,\n baseUrl: config?.baseUrl || process.env.CHECKPOINT_API_URL,\n // Default to edge detection unless explicitly disabled\n useEdge: config?.useEdge ?? process.env.CHECKPOINT_USE_EDGE !== 'false',\n timeout: config?.timeout,\n debug: config?.debug || process.env.CHECKPOINT_DEBUG === 'true',\n };\n}\n\nfunction clientCacheKey(config: CheckpointApiClientConfig): string {\n return JSON.stringify([\n config.apiKey,\n config.baseUrl ?? '',\n config.useEdge,\n config.timeout ?? DEFAULT_TIMEOUT,\n config.debug,\n ]);\n}\n\nexport function getCheckpointApiClient(\n config?: Partial<CheckpointApiClientConfig>\n): CheckpointApiClient {\n const resolvedConfig = resolveClientConfig(config);\n const key = clientCacheKey(resolvedConfig);\n let clientInstance = clientInstances.get(key);\n\n if (!clientInstance) {\n clientInstance = new CheckpointApiClient(resolvedConfig);\n clientInstances.set(key, clientInstance);\n }\n\n return clientInstance;\n}\n\n/**\n * Reset the singleton client (useful for testing)\n */\nexport function resetCheckpointApiClient(): void {\n clientInstances.clear();\n}\n"],"mappings":";;;AAqLA,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;AAsBxB,IAAa,sBAAb,MAAiC;CAC/B,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAA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ACd,KAAK,MAAM;KACb,CAAC;KACD,QAAQ,WAAW;IACrB,CAAC;IAED,aAAa,SAAS;IAEtB,IAAI,CAAC,SAAS,MAAM,KAAK,OACvB,QAAQ,KAAK,gDAAgD,SAAS,MAAM;GAEhF,SAAS,OAAO;IACd,aAAa,SAAS;IACtB,MAAM;GACR;EACF,SAAS,OAAO;GAEd,IAAI,KAAK,OACP,QAAQ,MAAM,sCAAsC,KAAK;GAG3D,MAAM;EACR;CACF;AACF;;;;;;;;;;;;AAaA,MAAM,kCAAkB,IAAI,IAAiC;AAE7D,SAAS,oBACP,QAC2B;CAC3B,MAAM,SAAS,QAAQ,UAAU,QAAQ,IAAI;CAE7C,IAAI,CAAC,QACH,MAAM,IAAI,MACR,uGACF;CAGF,OAAO;EACL;EACA,SAAS,QAAQ,WAAW,QAAQ,IAAI;EAExC,SAAS,QAAQ,WAAW,QAAQ,IAAI,wBAAwB;EAChE,SAAS,QAAQ;EACjB,OAAO,QAAQ,SAAS,QAAQ,IAAI,qBAAqB;CAC3D;AACF;AAEA,SAAS,eAAe,QAA2C;CACjE,OAAO,KAAK,UAAU;EACpB,OAAO;EACP,OAAO,WAAW;EAClB,OAAO;EACP,OAAO,WAAW;EAClB,OAAO;CACT,CAAC;AACH;AAEA,SAAgB,uBACd,QACqB;CACrB,MAAM,iBAAiB,oBAAoB,MAAM;CACjD,MAAM,MAAM,eAAe,cAAc;CACzC,IAAI,iBAAiB,gBAAgB,IAAI,GAAG;CAE5C,IAAI,CAAC,gBAAgB;EACnB,iBAAiB,IAAI,oBAAoB,cAAc;EACvD,gBAAgB,IAAI,KAAK,cAAc;CACzC;CAEA,OAAO;AACT;;;;AAKA,SAAgB,2BAAiC;CAC/C,gBAAgB,MAAM;AACxB"}
@@ -0,0 +1,131 @@
1
+ import { s as EnforcementDecision } from "./api-client-JHOrRUA_.mjs";
2
+ import { ChallengeEnvelopeMode } from "@kya-os/checkpoint-shared/host-adapter";
3
+ import { NextRequest, NextResponse } from "next/server.js";
4
+ import { ClientIpTrustPolicy } from "@kya-os/checkpoint-shared/client-ip";
5
+ //#region src/api-middleware.d.ts
6
+ /**
7
+ * Middleware configuration
8
+ */
9
+ interface CheckpointApiMiddlewareConfig {
10
+ /** Explicit deployment/proxy trust profile for client-IP resolution. */
11
+ clientIpPolicy?: ClientIpTrustPolicy;
12
+ /** API key (or use CHECKPOINT_API_KEY env var) */
13
+ apiKey?: string;
14
+ /**
15
+ * Gateway base URL. Override for staging or self-hosted deployments.
16
+ * With `useEdge: false` the default becomes `https://kya.vouched.id`.
17
+ *
18
+ * @default 'https://detect.checkpoint-gateway.ai'
19
+ */
20
+ apiUrl?: string;
21
+ /**
22
+ * Use edge detection for lower latency (~30-50ms vs ~150ms) and better coverage.
23
+ * Edge detection can identify non-JS clients (curl, Python, Claude Code WebFetch)
24
+ * that the pixel cannot detect since they don't execute JavaScript.
25
+ * Set to false to use the Vercel API instead.
26
+ * @default true
27
+ */
28
+ useEdge?: boolean;
29
+ /**
30
+ * Request timeout in milliseconds for the gateway call.
31
+ *
32
+ * @default 5000
33
+ */
34
+ timeout?: number;
35
+ /**
36
+ * Action to take when an agent should be blocked
37
+ * - 'block': Return 403 response
38
+ * - 'redirect': Redirect to redirectUrl
39
+ * - 'challenge': Show a challenge page (future)
40
+ * Default: uses policy from dashboard
41
+ */
42
+ onBlock?: 'block' | 'redirect' | 'challenge';
43
+ /**
44
+ * URL to redirect to when blocking (if onBlock is 'redirect')
45
+ * Default: uses redirectUrl from dashboard policy
46
+ */
47
+ redirectUrl?: string;
48
+ /**
49
+ * How the middleware handles a `redirect` / `instruct` action.
50
+ *
51
+ * - `'instruct'` (default): return HTTP 401 with a KYA-OS Link header + JSON
52
+ * body pointing the agent at the redirect URL. LLMs surface the URL as a
53
+ * clickable link for the user. Matches the Cloudflare Gateway contract.
54
+ * - `'http'`: legacy behavior — return HTTP 302 with `Location`. Most LLM
55
+ * fetchers won't follow the redirect, so this is only useful when your
56
+ * traffic is real browsers.
57
+ *
58
+ * @default 'instruct'
59
+ */
60
+ redirectMode?: 'instruct' | 'http';
61
+ /**
62
+ * Challenge-emission envelope mode (draft-kya-http-02 §8.1 fetcher-200).
63
+ * `negotiated` serves a body-readable HTTP 200 instruct response to
64
+ * cooperative agents (so fetchers that drop 4xx bodies can read it),
65
+ * keeping the spec 401 for everyone else. Defaults to `negotiated` (#3530).
66
+ * A cooperative-UX bridge, NOT an access control.
67
+ *
68
+ * @default 'negotiated'
69
+ */
70
+ delegationChallengeMode?: ChallengeEnvelopeMode;
71
+ /**
72
+ * Customize the blocked response's status, message, and extra headers.
73
+ *
74
+ * @default { status: 403, message: 'Access denied' }
75
+ */
76
+ blockedResponse?: {
77
+ status?: number;
78
+ message?: string;
79
+ headers?: Record<string, string>;
80
+ };
81
+ /**
82
+ * Paths to skip (in addition to dashboard policy)
83
+ * Supports glob patterns: '/api/*', '/_next/*'
84
+ */
85
+ skipPaths?: string[];
86
+ /**
87
+ * Only enforce on these paths (overrides dashboard policy)
88
+ */
89
+ includePaths?: string[];
90
+ /**
91
+ * Callback when an agent is detected
92
+ */
93
+ onAgentDetected?: (request: NextRequest, decision: EnforcementDecision) => void | Promise<void>;
94
+ /**
95
+ * Callback to customize the blocked response
96
+ */
97
+ customBlockedResponse?: (request: NextRequest, decision: EnforcementDecision) => NextResponse | Promise<NextResponse>;
98
+ /**
99
+ * Whether to fail open (allow) on API errors. Must be explicitly `true`;
100
+ * the default is fail-closed (503 with `Retry-After`). A request that
101
+ * presented a credential (bearer or KYA delegation headers) is answered 503
102
+ * on an API error even when this is `true`.
103
+ *
104
+ * @default false
105
+ */
106
+ failOpen?: boolean;
107
+ /**
108
+ * Log detection decisions and errors to the console.
109
+ *
110
+ * @default false
111
+ */
112
+ debug?: boolean;
113
+ }
114
+ /**
115
+ * Create Checkpoint middleware with API-based detection
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * // middleware.ts
120
+ * import { withCheckpointApi } from '@kya-os/checkpoint-nextjs/api-middleware';
121
+ *
122
+ * export default withCheckpointApi({
123
+ * onBlock: 'block',
124
+ * skipPaths: ['/api/health'],
125
+ * });
126
+ * ```
127
+ */
128
+ declare function withCheckpointApi(config?: CheckpointApiMiddlewareConfig): (request: NextRequest) => Promise<NextResponse>;
129
+ //#endregion
130
+ export { withCheckpointApi as n, CheckpointApiMiddlewareConfig as t };
131
+ //# sourceMappingURL=api-middleware-BWjokNis.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-middleware-BWjokNis.d.mts","names":[],"sources":["../src/api-middleware.ts"],"mappings":";;;;;;;;UA4EiB;;EAEf,iBAAiB;;EAEjB;;;;;;;EAOA;;;;;;;;EAQA;;;;;;EAMA;;;;;;;;EASA;;;;;EAMA;;;;;;;;;;;;;EAcA;;;;;;;;;;EAWA,0BAA0B;;;;;;EAO1B;IACE;IACA;IACA,UAAU;;;;;;EAOZ;;;;EAKA;;;;EAKA,mBAAmB,SAAS,aAAa,UAAU,+BAA+B;;;;EAKlF,yBACE,SAAS,aACT,UAAU,wBACP,eAAe,QAAQ;;;;;;;;;EAU5B;;;;;;EAOA;;;;;;;;;;;;;;;;iBA2Mc,kBAAkB,SAAQ,iCA6CP,SAAS,gBAAc,QAAQ"}
@@ -1,8 +1,11 @@
1
+ const require_adapt = require('./adapt-CCSKGjVH.js');
2
+ const require_utils = require('./utils-dyFxqlFI.js');
1
3
  const require_api_client = require('./api-client.js');
2
- const require_utils = require('./utils-DAisnYnI.js');
3
- let _kya_os_checkpoint_shared = require("@kya-os/checkpoint-shared");
4
- let next_server = require("next/server");
4
+ let _kya_os_checkpoint_shared_host_adapter = require("@kya-os/checkpoint-shared/host-adapter");
5
5
  let _vercel_functions = require("@vercel/functions");
6
+ let next_server_js = require("next/server.js");
7
+ let _kya_os_checkpoint_shared_policy_enforcement = require("@kya-os/checkpoint-shared/policy/enforcement");
8
+ let _kya_os_checkpoint_shared_kya_http = require("@kya-os/checkpoint-shared/kya-http");
6
9
 
7
10
  //#region src/responses/agent-instruction.ts
8
11
  /**
@@ -87,7 +90,7 @@ function buildAgentInstructionResponse(request, decision, redirectUrl, options)
87
90
  }
88
91
  };
89
92
  const bodyReadable200 = options?.bodyReadable200 ?? false;
90
- const response = next_server.NextResponse.json(body, { status: bodyReadable200 ? 200 : 401 });
93
+ const response = next_server_js.NextResponse.json(body, { status: bodyReadable200 ? 200 : 401 });
91
94
  response.headers.set("Link", `<${authUrl}>; rel="kya-authorize", <${MCP_I_DOCS_URL}>; rel="help"`);
92
95
  response.headers.set("KYA-Auth-Required", "true");
93
96
  response.headers.set("KYA-Auth-Url", authUrl);
@@ -112,9 +115,9 @@ function resolveUrl(target, baseUrl) {
112
115
  //#endregion
113
116
  //#region src/api-middleware.ts
114
117
  /**
115
- * API-based AgentShield Middleware for Next.js
118
+ * API-based Checkpoint Middleware for Next.js
116
119
  *
117
- * This middleware uses the AgentShield API for detection and enforcement,
120
+ * This middleware uses the Checkpoint API for detection and enforcement,
118
121
  * instead of running detection locally. This approach:
119
122
  *
120
123
  * 1. Works reliably in Edge Runtime (no WASM loading issues)
@@ -144,14 +147,39 @@ function resolveUrl(target, baseUrl) {
144
147
  * Check if path should be skipped
145
148
  */
146
149
  function shouldSkipPath(path, skipPaths) {
147
- return skipPaths.some((pattern) => (0, _kya_os_checkpoint_shared.matchPath)(path, pattern));
150
+ return skipPaths.some((pattern) => (0, _kya_os_checkpoint_shared_policy_enforcement.matchPath)(path, pattern));
148
151
  }
149
152
  /**
150
153
  * Check if path should be included (if includePaths is set)
151
154
  */
152
155
  function shouldIncludePath(path, includePaths) {
153
156
  if (!includePaths || includePaths.length === 0) return true;
154
- return includePaths.some((pattern) => (0, _kya_os_checkpoint_shared.matchPath)(path, pattern));
157
+ return includePaths.some((pattern) => (0, _kya_os_checkpoint_shared_policy_enforcement.matchPath)(path, pattern));
158
+ }
159
+ /** The npm package this middleware ships in (package.json `name`, pinned by a unit test). */
160
+ const SDK_NAME = "@kya-os/checkpoint-nextjs";
161
+ /**
162
+ * The gateway ran the engine, so its engine info is reported under the
163
+ * remote-engine name `checkpoint-remote`. Forwarding the gateway's own
164
+ * `checkpoint-worker-wasm` would make this install read as a DNS Gateway.
165
+ */
166
+ function remoteEngineInfo(engine) {
167
+ return {
168
+ name: "checkpoint-remote",
169
+ version: engine.version,
170
+ rulesetHash: engine.rulesetHash,
171
+ rulesetVersion: engine.rulesetVersion,
172
+ ...engine.buildSha ? { buildSha: engine.buildSha } : {}
173
+ };
174
+ }
175
+ /** The SDK's self-identification, or undefined when the build injected no version. */
176
+ function sdkSelfIdentification() {
177
+ const runtime = typeof process !== "undefined" && process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
178
+ return {
179
+ name: SDK_NAME,
180
+ version: "1.11.0",
181
+ runtime
182
+ };
155
183
  }
156
184
  /**
157
185
  * Build blocked response.
@@ -181,7 +209,7 @@ function buildBlockedResponse(request, decision, config) {
181
209
  };
182
210
  body.message = `I can't access ${hostname} — this site blocks unverified AI assistants.\n\n**To give me access, open this link:**\n[Connect securely to ${hostname}](${recoveryUrl})\n\nOnce you're done, ask me to try again.`;
183
211
  }
184
- const response = next_server.NextResponse.json(body, { status });
212
+ const response = next_server_js.NextResponse.json(body, { status });
185
213
  if (config.blockedResponse?.headers) for (const [key, value] of Object.entries(config.blockedResponse.headers)) response.headers.set(key, value);
186
214
  if (recoveryUrl) {
187
215
  response.headers.set("Link", `<${recoveryUrl}>; rel="kya-authorize"`);
@@ -191,6 +219,26 @@ function buildBlockedResponse(request, decision, config) {
191
219
  response.headers.set("KYA-Reason", decision.reason);
192
220
  return response;
193
221
  }
222
+ /**
223
+ * A policy `requestsPerMinute` throttle arrives as `block` with reason
224
+ * `rate_limited`. It is a 429 with a retry hint, not an access denial: no
225
+ * "unverified assistant" recovery copy and no redirect.
226
+ */
227
+ function buildRateLimitedResponse(decision, config) {
228
+ const retryAfter = decision.metadata?.rateLimit?.retryAfterSeconds;
229
+ const response = next_server_js.NextResponse.json({
230
+ error: decision.message ?? "Rate limit exceeded",
231
+ code: "RATE_LIMITED",
232
+ reason: decision.reason,
233
+ agentType: decision.agentType,
234
+ ...retryAfter !== void 0 ? { retryAfterSeconds: retryAfter } : {}
235
+ }, { status: 429 });
236
+ for (const [key, value] of Object.entries(config.blockedResponse?.headers ?? {})) response.headers.set(key, value);
237
+ if (retryAfter !== void 0) response.headers.set("Retry-After", String(retryAfter));
238
+ response.headers.set("KYA-Action", decision.action);
239
+ response.headers.set("KYA-Reason", decision.reason);
240
+ return response;
241
+ }
194
242
  function resolveRecoveryUrl(request, target) {
195
243
  if (!target) return void 0;
196
244
  try {
@@ -207,10 +255,10 @@ function buildRedirectResponse(request, decision, config) {
207
255
  const url = new URL(redirectUrl, request.url);
208
256
  url.searchParams.set("reason", decision.reason);
209
257
  if (decision.agentType) url.searchParams.set("agent", decision.agentType);
210
- return next_server.NextResponse.redirect(url);
258
+ return next_server_js.NextResponse.redirect(url);
211
259
  }
212
260
  /**
213
- * Create AgentShield middleware with API-based detection
261
+ * Create Checkpoint middleware with API-based detection
214
262
  *
215
263
  * @example
216
264
  * ```typescript
@@ -242,12 +290,12 @@ function withCheckpointApi(config = {}) {
242
290
  "/robots.txt",
243
291
  "/sitemap.xml"
244
292
  ], ...config.skipPaths || []];
245
- const failOpen = config.failOpen ?? true;
293
+ const faultResponse = (request) => config.failOpen === true && !(0, _kya_os_checkpoint_shared_kya_http.requestPresentedCredential)(request.headers) ? failOpenResponse() : require_adapt.failClosedResponse();
246
294
  return async function middleware(request) {
247
295
  const path = request.nextUrl.pathname;
248
296
  const startTime = Date.now();
249
- if (shouldSkipPath(path, skipPaths)) return next_server.NextResponse.next();
250
- if (!shouldIncludePath(path, config.includePaths)) return next_server.NextResponse.next();
297
+ if (shouldSkipPath(path, skipPaths)) return next_server_js.NextResponse.next();
298
+ if (!shouldIncludePath(path, config.includePaths)) return next_server_js.NextResponse.next();
251
299
  try {
252
300
  const client = getClient();
253
301
  const userAgent = request.headers.get("user-agent") || void 0;
@@ -264,11 +312,7 @@ function withCheckpointApi(config = {}) {
264
312
  });
265
313
  if (!result.success || !result.data) {
266
314
  if (config.debug) console.warn("[Checkpoint] API error:", result.error);
267
- if (failOpen) return next_server.NextResponse.next();
268
- return next_server.NextResponse.json({
269
- error: "Security check failed",
270
- code: "API_ERROR"
271
- }, { status: 503 });
315
+ return faultResponse(request);
272
316
  }
273
317
  const decision = result.data.decision;
274
318
  if (config.debug) console.log("[Checkpoint] Decision:", {
@@ -289,7 +333,10 @@ function withCheckpointApi(config = {}) {
289
333
  url: request.url,
290
334
  method: request.method
291
335
  },
292
- source: "middleware"
336
+ source: "middleware",
337
+ enforcement: { action: decision.action },
338
+ engine: result.data.engine ? remoteEngineInfo(result.data.engine) : void 0,
339
+ sdk: sdkSelfIdentification()
293
340
  }).catch((err) => {
294
341
  if (config.debug) console.error("[Checkpoint] Log detection failed:", err);
295
342
  }));
@@ -302,18 +349,19 @@ function withCheckpointApi(config = {}) {
302
349
  switch (decision.action) {
303
350
  case "block":
304
351
  if (config.customBlockedResponse) return await config.customBlockedResponse(request, decision);
352
+ if (decision.reason === "rate_limited") return buildRateLimitedResponse(decision, config);
305
353
  if (config.onBlock === "redirect") return buildRedirectResponse(request, decision, config);
306
354
  return buildBlockedResponse(request, decision, config);
307
355
  case "redirect":
308
356
  case "instruct": {
309
357
  if (redirectMode === "http" && decision.action === "redirect") return buildRedirectResponse(request, decision, config);
310
358
  const targetUrl = config.redirectUrl || decision.redirectUrl;
311
- const bodyReadable200 = (0, _kya_os_checkpoint_shared.selectBodyReadable200)(config.delegationChallengeMode ?? "negotiated", request.headers, result.data.detection?.detectionClass, result.data.detection?.isAgent ?? false);
359
+ const bodyReadable200 = (0, _kya_os_checkpoint_shared_host_adapter.selectBodyReadable200)(config.delegationChallengeMode ?? "negotiated", request.headers, result.data.detection?.detectionClass, result.data.detection?.isAgent ?? false);
312
360
  return buildAgentInstructionResponse(request, decision, targetUrl, { bodyReadable200 });
313
361
  }
314
362
  case "challenge": return buildRedirectResponse(request, decision, config);
315
363
  default: {
316
- const response = next_server.NextResponse.next();
364
+ const response = next_server_js.NextResponse.next();
317
365
  if (decision.isAgent) {
318
366
  response.headers.set("KYA-Detected", "true");
319
367
  response.headers.set("KYA-Confidence", decision.confidence.toString());
@@ -324,53 +372,17 @@ function withCheckpointApi(config = {}) {
324
372
  }
325
373
  } catch (error) {
326
374
  if (config.debug) console.error("[Checkpoint] Middleware error:", error);
327
- if (failOpen) return next_server.NextResponse.next();
328
- return next_server.NextResponse.json({
329
- error: "Security check failed",
330
- code: "MIDDLEWARE_ERROR"
331
- }, { status: 503 });
375
+ return faultResponse(request);
332
376
  }
333
377
  };
334
378
  }
335
- /** @deprecated Renamed to {@link withCheckpointApi}. The behaviour is identical. */
336
- const withAgentShield = withCheckpointApi;
337
- const LEGACY_MIGRATION_ERROR = "This export was removed in Phase D. Migrate to `withCheckpoint` (local-engine deployment) or `withCheckpointApi` (SaaS-gateway deployment) from `@kya-os/checkpoint-nextjs`. See packages/checkpoint-nextjs/README.md (Two deployment shapes) for which one fits your runtime.";
338
- /**
339
- * @deprecated Module-load-time invocation of the legacy `withAgentShield()`.
340
- * Construct the middleware explicitly via `withCheckpointApi({ apiKey })`
341
- * instead of relying on a default-constructed singleton at import time.
342
- */
343
- function agentShieldMiddleware(_request) {
344
- throw new Error(LEGACY_MIGRATION_ERROR);
345
- }
346
- /**
347
- * @deprecated The "enhanced middleware" combined detection + storage +
348
- * enforcement into a single legacy path that no longer exists. Migrate
349
- * to `withCheckpoint` (local-engine) or `withCheckpointApi` (SaaS-gateway).
350
- */
351
- function createEnhancedAgentShieldMiddleware(_config = {}) {
352
- throw new Error(LEGACY_MIGRATION_ERROR);
379
+ function failOpenResponse() {
380
+ const response = next_server_js.NextResponse.next();
381
+ response.headers.set("KYA-Failopen", "true");
382
+ return response;
353
383
  }
354
384
 
355
385
  //#endregion
356
- Object.defineProperty(exports, 'agentShieldMiddleware', {
357
- enumerable: true,
358
- get: function () {
359
- return agentShieldMiddleware;
360
- }
361
- });
362
- Object.defineProperty(exports, 'createEnhancedAgentShieldMiddleware', {
363
- enumerable: true,
364
- get: function () {
365
- return createEnhancedAgentShieldMiddleware;
366
- }
367
- });
368
- Object.defineProperty(exports, 'withAgentShield', {
369
- enumerable: true,
370
- get: function () {
371
- return withAgentShield;
372
- }
373
- });
374
386
  Object.defineProperty(exports, 'withCheckpointApi', {
375
387
  enumerable: true,
376
388
  get: function () {
@@ -1,8 +1,11 @@
1
+ import { n as failClosedResponse } from "./adapt-BdQ9R7Iw.mjs";
2
+ import { r as safeHostname, t as getClientIp } from "./utils-Cnwg0VrY.mjs";
1
3
  import { getCheckpointApiClient } from "./api-client.mjs";
2
- import { n as safeHostname, t as getClientIp } from "./utils-Cj4XNhIY.mjs";
3
- import { matchPath, selectBodyReadable200 } from "@kya-os/checkpoint-shared";
4
- import { NextResponse } from "next/server";
4
+ import { selectBodyReadable200 } from "@kya-os/checkpoint-shared/host-adapter";
5
5
  import { waitUntil } from "@vercel/functions";
6
+ import { NextResponse } from "next/server.js";
7
+ import { matchPath } from "@kya-os/checkpoint-shared/policy/enforcement";
8
+ import { requestPresentedCredential } from "@kya-os/checkpoint-shared/kya-http";
6
9
 
7
10
  //#region src/responses/agent-instruction.ts
8
11
  /**
@@ -112,9 +115,9 @@ function resolveUrl(target, baseUrl) {
112
115
  //#endregion
113
116
  //#region src/api-middleware.ts
114
117
  /**
115
- * API-based AgentShield Middleware for Next.js
118
+ * API-based Checkpoint Middleware for Next.js
116
119
  *
117
- * This middleware uses the AgentShield API for detection and enforcement,
120
+ * This middleware uses the Checkpoint API for detection and enforcement,
118
121
  * instead of running detection locally. This approach:
119
122
  *
120
123
  * 1. Works reliably in Edge Runtime (no WASM loading issues)
@@ -153,6 +156,31 @@ function shouldIncludePath(path, includePaths) {
153
156
  if (!includePaths || includePaths.length === 0) return true;
154
157
  return includePaths.some((pattern) => matchPath(path, pattern));
155
158
  }
159
+ /** The npm package this middleware ships in (package.json `name`, pinned by a unit test). */
160
+ const SDK_NAME = "@kya-os/checkpoint-nextjs";
161
+ /**
162
+ * The gateway ran the engine, so its engine info is reported under the
163
+ * remote-engine name `checkpoint-remote`. Forwarding the gateway's own
164
+ * `checkpoint-worker-wasm` would make this install read as a DNS Gateway.
165
+ */
166
+ function remoteEngineInfo(engine) {
167
+ return {
168
+ name: "checkpoint-remote",
169
+ version: engine.version,
170
+ rulesetHash: engine.rulesetHash,
171
+ rulesetVersion: engine.rulesetVersion,
172
+ ...engine.buildSha ? { buildSha: engine.buildSha } : {}
173
+ };
174
+ }
175
+ /** The SDK's self-identification, or undefined when the build injected no version. */
176
+ function sdkSelfIdentification() {
177
+ const runtime = typeof process !== "undefined" && process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
178
+ return {
179
+ name: SDK_NAME,
180
+ version: "1.11.0",
181
+ runtime
182
+ };
183
+ }
156
184
  /**
157
185
  * Build blocked response.
158
186
  *
@@ -191,6 +219,26 @@ function buildBlockedResponse(request, decision, config) {
191
219
  response.headers.set("KYA-Reason", decision.reason);
192
220
  return response;
193
221
  }
222
+ /**
223
+ * A policy `requestsPerMinute` throttle arrives as `block` with reason
224
+ * `rate_limited`. It is a 429 with a retry hint, not an access denial: no
225
+ * "unverified assistant" recovery copy and no redirect.
226
+ */
227
+ function buildRateLimitedResponse(decision, config) {
228
+ const retryAfter = decision.metadata?.rateLimit?.retryAfterSeconds;
229
+ const response = NextResponse.json({
230
+ error: decision.message ?? "Rate limit exceeded",
231
+ code: "RATE_LIMITED",
232
+ reason: decision.reason,
233
+ agentType: decision.agentType,
234
+ ...retryAfter !== void 0 ? { retryAfterSeconds: retryAfter } : {}
235
+ }, { status: 429 });
236
+ for (const [key, value] of Object.entries(config.blockedResponse?.headers ?? {})) response.headers.set(key, value);
237
+ if (retryAfter !== void 0) response.headers.set("Retry-After", String(retryAfter));
238
+ response.headers.set("KYA-Action", decision.action);
239
+ response.headers.set("KYA-Reason", decision.reason);
240
+ return response;
241
+ }
194
242
  function resolveRecoveryUrl(request, target) {
195
243
  if (!target) return void 0;
196
244
  try {
@@ -210,7 +258,7 @@ function buildRedirectResponse(request, decision, config) {
210
258
  return NextResponse.redirect(url);
211
259
  }
212
260
  /**
213
- * Create AgentShield middleware with API-based detection
261
+ * Create Checkpoint middleware with API-based detection
214
262
  *
215
263
  * @example
216
264
  * ```typescript
@@ -242,7 +290,7 @@ function withCheckpointApi(config = {}) {
242
290
  "/robots.txt",
243
291
  "/sitemap.xml"
244
292
  ], ...config.skipPaths || []];
245
- const failOpen = config.failOpen ?? true;
293
+ const faultResponse = (request) => config.failOpen === true && !requestPresentedCredential(request.headers) ? failOpenResponse() : failClosedResponse();
246
294
  return async function middleware(request) {
247
295
  const path = request.nextUrl.pathname;
248
296
  const startTime = Date.now();
@@ -264,11 +312,7 @@ function withCheckpointApi(config = {}) {
264
312
  });
265
313
  if (!result.success || !result.data) {
266
314
  if (config.debug) console.warn("[Checkpoint] API error:", result.error);
267
- if (failOpen) return NextResponse.next();
268
- return NextResponse.json({
269
- error: "Security check failed",
270
- code: "API_ERROR"
271
- }, { status: 503 });
315
+ return faultResponse(request);
272
316
  }
273
317
  const decision = result.data.decision;
274
318
  if (config.debug) console.log("[Checkpoint] Decision:", {
@@ -289,7 +333,10 @@ function withCheckpointApi(config = {}) {
289
333
  url: request.url,
290
334
  method: request.method
291
335
  },
292
- source: "middleware"
336
+ source: "middleware",
337
+ enforcement: { action: decision.action },
338
+ engine: result.data.engine ? remoteEngineInfo(result.data.engine) : void 0,
339
+ sdk: sdkSelfIdentification()
293
340
  }).catch((err) => {
294
341
  if (config.debug) console.error("[Checkpoint] Log detection failed:", err);
295
342
  }));
@@ -302,6 +349,7 @@ function withCheckpointApi(config = {}) {
302
349
  switch (decision.action) {
303
350
  case "block":
304
351
  if (config.customBlockedResponse) return await config.customBlockedResponse(request, decision);
352
+ if (decision.reason === "rate_limited") return buildRateLimitedResponse(decision, config);
305
353
  if (config.onBlock === "redirect") return buildRedirectResponse(request, decision, config);
306
354
  return buildBlockedResponse(request, decision, config);
307
355
  case "redirect":
@@ -324,34 +372,16 @@ function withCheckpointApi(config = {}) {
324
372
  }
325
373
  } catch (error) {
326
374
  if (config.debug) console.error("[Checkpoint] Middleware error:", error);
327
- if (failOpen) return NextResponse.next();
328
- return NextResponse.json({
329
- error: "Security check failed",
330
- code: "MIDDLEWARE_ERROR"
331
- }, { status: 503 });
375
+ return faultResponse(request);
332
376
  }
333
377
  };
334
378
  }
335
- /** @deprecated Renamed to {@link withCheckpointApi}. The behaviour is identical. */
336
- const withAgentShield = withCheckpointApi;
337
- const LEGACY_MIGRATION_ERROR = "This export was removed in Phase D. Migrate to `withCheckpoint` (local-engine deployment) or `withCheckpointApi` (SaaS-gateway deployment) from `@kya-os/checkpoint-nextjs`. See packages/checkpoint-nextjs/README.md (Two deployment shapes) for which one fits your runtime.";
338
- /**
339
- * @deprecated Module-load-time invocation of the legacy `withAgentShield()`.
340
- * Construct the middleware explicitly via `withCheckpointApi({ apiKey })`
341
- * instead of relying on a default-constructed singleton at import time.
342
- */
343
- function agentShieldMiddleware(_request) {
344
- throw new Error(LEGACY_MIGRATION_ERROR);
345
- }
346
- /**
347
- * @deprecated The "enhanced middleware" combined detection + storage +
348
- * enforcement into a single legacy path that no longer exists. Migrate
349
- * to `withCheckpoint` (local-engine) or `withCheckpointApi` (SaaS-gateway).
350
- */
351
- function createEnhancedAgentShieldMiddleware(_config = {}) {
352
- throw new Error(LEGACY_MIGRATION_ERROR);
379
+ function failOpenResponse() {
380
+ const response = NextResponse.next();
381
+ response.headers.set("KYA-Failopen", "true");
382
+ return response;
353
383
  }
354
384
 
355
385
  //#endregion
356
- export { withCheckpointApi as i, createEnhancedAgentShieldMiddleware as n, withAgentShield as r, agentShieldMiddleware as t };
357
- //# sourceMappingURL=api-middleware-CMDRoQik.mjs.map
386
+ export { withCheckpointApi as t };
387
+ //# sourceMappingURL=api-middleware-C-ngFX_8.mjs.map