@kya-os/checkpoint-nextjs 1.13.0 → 1.14.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 (68) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +13 -9
  3. package/dist/{api-client-JHOrRUA_.d.ts → api-client-yjr43Itz.d.mts} +6 -17
  4. package/dist/api-client-yjr43Itz.d.mts.map +1 -0
  5. package/dist/{api-client-JHOrRUA_.d.mts → api-client-yjr43Itz.d.ts} +6 -17
  6. package/dist/api-client-yjr43Itz.d.ts.map +1 -0
  7. package/dist/api-client.d.mts +1 -1
  8. package/dist/api-client.d.ts +1 -1
  9. package/dist/api-client.js +44 -58
  10. package/dist/api-client.mjs +44 -58
  11. package/dist/api-client.mjs.map +1 -1
  12. package/dist/{api-middleware-LhLqOapx.js → api-middleware-BVXf7qCM.js} +4 -2
  13. package/dist/{api-middleware-DcUgTDv5.mjs → api-middleware-CAarHFKk.mjs} +5 -3
  14. package/dist/api-middleware-CAarHFKk.mjs.map +1 -0
  15. package/dist/{api-middleware-BtsYJU5u.d.mts → api-middleware-CIXuGurw.d.mts} +4 -2
  16. package/dist/{api-middleware-BtsYJU5u.d.mts.map → api-middleware-CIXuGurw.d.mts.map} +1 -1
  17. package/dist/{api-middleware-DyLDqOYF.d.ts → api-middleware-CpAbnkfa.d.ts} +4 -2
  18. package/dist/{api-middleware-DyLDqOYF.d.ts.map → api-middleware-CpAbnkfa.d.ts.map} +1 -1
  19. package/dist/api-middleware.d.mts +1 -1
  20. package/dist/api-middleware.d.ts +1 -1
  21. package/dist/api-middleware.js +1 -1
  22. package/dist/api-middleware.mjs +1 -1
  23. package/dist/cedar-wasm.d.mts +1 -1
  24. package/dist/cedar-wasm.d.ts +1 -1
  25. package/dist/cedar-wasm.js +1 -1
  26. package/dist/cedar-wasm.mjs +1 -1
  27. package/dist/cedar-wasm.mjs.map +1 -1
  28. package/dist/{config-DQ-VuHlJ.d.mts → config-CVqpjhwT.d.mts} +2 -2
  29. package/dist/{config-DQ-VuHlJ.d.mts.map → config-CVqpjhwT.d.mts.map} +1 -1
  30. package/dist/{config-CXS_-rRv.d.ts → config-Dn2ptSA2.d.ts} +2 -2
  31. package/dist/{config-CXS_-rRv.d.ts.map → config-Dn2ptSA2.d.ts.map} +1 -1
  32. package/dist/index-edge.d.mts +5 -5
  33. package/dist/index-edge.d.ts +5 -5
  34. package/dist/index-edge.js +2 -2
  35. package/dist/index-edge.mjs +2 -2
  36. package/dist/index.d.mts +5 -5
  37. package/dist/index.d.ts +5 -5
  38. package/dist/index.js +2 -2
  39. package/dist/index.mjs +2 -2
  40. package/dist/middleware-bundler.d.mts +1 -1
  41. package/dist/middleware-bundler.d.ts +1 -1
  42. package/dist/middleware-bundler.js +1 -1
  43. package/dist/middleware-bundler.mjs +1 -1
  44. package/dist/{middleware-core-DaNMjsib.d.ts → middleware-core-BLCAErYE.d.ts} +3 -3
  45. package/dist/middleware-core-BLCAErYE.d.ts.map +1 -0
  46. package/dist/{middleware-core-DN_FLlaV.mjs → middleware-core-C4xi1I9I.mjs} +2 -2
  47. package/dist/{middleware-core-DN_FLlaV.mjs.map → middleware-core-C4xi1I9I.mjs.map} +1 -1
  48. package/dist/{middleware-core-Cxb9Jh0a.d.mts → middleware-core-D88q8dIt.d.mts} +3 -3
  49. package/dist/middleware-core-D88q8dIt.d.mts.map +1 -0
  50. package/dist/{middleware-core-0s8y7UNN.js → middleware-core-tGGPv727.js} +1 -1
  51. package/dist/middleware-edge.d.mts +1 -1
  52. package/dist/middleware-edge.d.ts +1 -1
  53. package/dist/middleware-edge.js +1 -1
  54. package/dist/middleware-edge.mjs +1 -1
  55. package/dist/middleware-node.d.mts +2 -2
  56. package/dist/middleware-node.d.ts +2 -2
  57. package/dist/middleware-node.js +1 -1
  58. package/dist/middleware-node.mjs +1 -1
  59. package/dist/public-api-CBQzjriI.d.mts +5 -0
  60. package/dist/public-api-Ea4jgcwD.d.ts +5 -0
  61. package/package.json +3 -3
  62. package/dist/api-client-JHOrRUA_.d.mts.map +0 -1
  63. package/dist/api-client-JHOrRUA_.d.ts.map +0 -1
  64. package/dist/api-middleware-DcUgTDv5.mjs.map +0 -1
  65. package/dist/middleware-core-Cxb9Jh0a.d.mts.map +0 -1
  66. package/dist/middleware-core-DaNMjsib.d.ts.map +0 -1
  67. package/dist/public-api-BZ5Ahk6X.d.mts +0 -5
  68. package/dist/public-api-DnTh8YEz.d.ts +0 -5
package/CHANGELOG.md CHANGED
@@ -2,6 +2,35 @@
2
2
 
3
3
  # @kya-os/checkpoint-nextjs
4
4
 
5
+ ## 1.14.0 - 2026-11-16
6
+
7
+ ### Breaking changes
8
+
9
+ - Removed: the policy helpers, removed in 1.11.0 by #6271 from both the `./policy` entry point and the package root, and listed then only under "Other merged changes". That covers `evaluatePolicyForDetection`, `handlePolicyDecision`, `applyPolicy`, `getPolicy` and `createContextFromDetection`; `buildBlockedResponse` and `buildRedirectResponse`, which the root exported as `buildPolicyBlockedResponse` and `buildPolicyRedirectResponse`; `buildChallengeResponse` (`./policy` only); the re-exported `evaluatePolicy`, `createEvaluationContext`, `ENFORCEMENT_ACTIONS` and `DEFAULT_POLICY`; and the types `PolicyMiddlewareConfig`, `NextJSPolicyMiddlewareConfig`, `PolicyConfig`, `PolicyEvaluationContext` and `PolicyEvaluationResult`. The project's deployed composed policy replaces them: `withCheckpoint({ projectId })` fetches it and evaluates every request in the engine, and `withCheckpointApi` gets the same decision from the hosted gateway. (#6809)
10
+ - Removed: the legacy entry points and aliases, also removed in 1.11.0 by #6271, whose imports now fail at build:
11
+ - the throw stubs `./middleware`, `./edge-wasm-middleware`, `createMiddleware`, `createAgentShieldMiddleware`, `createAgentShieldMiddlewareBase` and `createEnhancedAgentShieldMiddleware`;
12
+ - the TypeScript detector entries `./edge-runtime-loader` and `./wasm-setup`;
13
+ - the `AgentShield*` aliases of the current API: `withAgentShield`, `agentShieldMiddleware`, `AgentShieldClient`, `getAgentShieldClient` and `resetAgentShieldClient`, with `AgentShieldMiddlewareConfig` and `AgentShieldClientConfig`.
14
+ Use `withCheckpoint`, `withCheckpointApi`, `CheckpointApiClient`, `getCheckpointApiClient` and `resetCheckpointApiClient`. (#6809)
15
+ - Changed: In enforce mode, `projectId` (including one set for `browserPosture`) without `apiKey` is a configuration error: it is logged, and every request is answered 503.
16
+ Like every configuration error, it does not throw from the middleware module. (#6973)
17
+
18
+ ### Changed
19
+
20
+ - On the Node.js runtime, the project's policy is read once when the middleware starts, so a refused key is logged before the first request.
21
+ A refused key (HTTP 401 or 403) is logged as a configuration error naming `CHECKPOINT_API_KEY`, at most about once a minute, and so are the detection reports the dashboard refuses for it.
22
+ A policy outage is logged at most about every 5 seconds, and the next request reads the policy again. (#6973)
23
+ - CheckpointApiClient.logDetection retries once, after waiting it out, when the receiver sheds with a 503 whose Retry-After is 1 to 3 seconds. (#7250)
24
+ - `withCheckpointApi` sends its detection reports in gzip batches instead of one request each, with `telemetryBatchSize` and `telemetryFlushIntervalMs` to tune or turn off batching (`telemetryBatchSize: 1`). `CheckpointApiClient.logDetection` no longer rejects when the dashboard is unreachable: it warns and resolves. (#7338)
25
+
26
+ ### Fixed
27
+
28
+ - Since 1.11.0, `withCheckpoint` with `projectId` and no `apiKey` answered every request 503 in observe mode and logged a policy fetch failure for each.
29
+ In observe mode it now serves every request on the engine's decision without fetching the policy, and logs one warning at startup that `projectId` needs `apiKey` to apply the project's policy. (#6973)
30
+ - In observe mode, requests are served when the project's policy cannot be read, as when the policy API is down or refuses the key.
31
+ Enforce mode still answers 503 with `Retry-After: 3`. (#6973)
32
+ - a log-detection report answered with 503 is retried once even when Retry-After is missing, not a whole number or outside 1 to 3 seconds (the wait is clamped to 1-3 s); it was dropped before. (#7250)
33
+
5
34
  ## 1.13.0 - 2026-10-22
6
35
 
7
36
  ### Changed
package/README.md CHANGED
@@ -90,6 +90,7 @@ import engineWasmModule from '@kya-os/checkpoint-nextjs/cedar-wasm';
90
90
  import { withCheckpoint } from '@kya-os/checkpoint-nextjs';
91
91
 
92
92
  export default withCheckpoint({
93
+ apiKey: process.env.CHECKPOINT_API_KEY,
93
94
  projectId: process.env.CHECKPOINT_PROJECT_ID,
94
95
  engineWasmModule,
95
96
  });
@@ -149,6 +150,7 @@ On webpack, the Node.js runtime is not supported yet: the build succeeds, but we
149
150
  ### Background work
150
151
 
151
152
  A request can start work that outlives its response: a refresh of the engine's vendor keys, and the detection report when `apiKey` is set.
153
+ Detection reports go to the dashboard in gzip batches: `telemetryBatchSize` (default 200, at most 500; `1` sends each report alone) sets the batch and `telemetryFlushIntervalMs` (default 2000) the longest a report waits. Every request is reported, humans included, and the first report after a quiet period is sent at once.
152
154
  `withCheckpoint` registers that work with the `waitUntil` of the event Next.js passes to middleware, so Vercel does not cancel it once the response is sent.
153
155
  If you wrap `withCheckpoint` in your own middleware, pass the event through:
154
156
 
@@ -271,8 +273,10 @@ export default withCheckpointApi({
271
273
 
272
274
  The local-engine shape (`withCheckpoint`) takes a `CheckpointConfig` instead,
273
275
  every field optional: `enforcementMode` (`'enforce'` | `'observe'`), `apiKey`
274
- (enables dashboard reporting), `projectId` (enforces your deployed dashboard
275
- policy in-process), and more. `tenantHost` is deprecated: it is no longer used
276
+ (enables dashboard reporting), `projectId` (applies your deployed dashboard
277
+ policy in-process, and needs `apiKey`: without it, enforce mode is a
278
+ configuration error answered 503, and observe mode serves without the policy and
279
+ warns once), and more. `tenantHost` is deprecated: it is no longer used
276
280
  and will be removed. See the
277
281
  [middleware docs](https://kya.vouched.id/docs/enforce/middleware) for the
278
282
  full option tables for both shapes.
@@ -281,13 +285,13 @@ full option tables for both shapes.
281
285
 
282
286
  `withCheckpoint` answers `503` (`Retry-After: 3`, `Cache-Control: no-store`)
283
287
  when the verification pipeline errors; it never passes the request through or
284
- returns a 500. If the policy API is unreachable, the last successfully fetched
285
- policy (at most 24h old) is served; with none, the request is answered `503`
286
- and the default policy is never substituted. The last-good copy lives in
287
- process memory and, when a `PolicyCacheAdapter` is configured, in that adapter
288
- (so a cold process or isolate can still serve it). A policy-origin 401/403/404
289
- or a body that is not a policy-API response is treated like an outage:
290
- last-good is served for up to 24h.
288
+ returns a 500. If the policy API is unreachable,
289
+ a policy still inside its cache window (`policyCacheTtlSeconds`, 300 by default)
290
+ keeps being used. Once that window ends, or on a cold start, the request is
291
+ answered `503`: no older copy is kept, and the default policy is never
292
+ substituted. A timeout, a 5xx, a policy-origin 401/403/404 or a body that is
293
+ not a policy-API response all end the same way. In observe mode the request is
294
+ served on the engine's decision instead.
291
295
 
292
296
  ### DID documents and status lists
293
297
 
@@ -19,6 +19,8 @@ interface CheckpointApiClientConfig {
19
19
  timeout?: number;
20
20
  /** Enable debug logging */
21
21
  debug?: boolean;
22
+ telemetryBatchSize?: number;
23
+ telemetryFlushIntervalMs?: number;
22
24
  }
23
25
  /**
24
26
  * Enforcement decision from the API
@@ -176,6 +178,9 @@ declare class CheckpointApiClient {
176
178
  private useEdge;
177
179
  private timeout;
178
180
  private debug;
181
+ private telemetryBatchSize;
182
+ private telemetryFlushIntervalMs;
183
+ private reportSender;
179
184
  constructor(config: CheckpointApiClientConfig);
180
185
  /**
181
186
  * Call the enforce API to check if a request should be allowed
@@ -194,22 +199,6 @@ declare class CheckpointApiClient {
194
199
  * Check if this client is using edge detection (Gateway Worker)
195
200
  */
196
201
  isUsingEdge(): boolean;
197
- /**
198
- * Log a detection result to the Checkpoint database.
199
- * Use after Gateway Worker detection to persist results.
200
- * Fire-and-forget - returns immediately without waiting for DB write.
201
- *
202
- * @example
203
- * ```typescript
204
- * // After receiving Gateway response
205
- * if (client.isUsingEdge() && response.data?.detection) {
206
- * client.logDetection({
207
- * detection: response.data.detection,
208
- * context: { userAgent, ipAddress, path, url, method }
209
- * }).catch(err => console.error('Log failed:', err));
210
- * }
211
- * ```
212
- */
213
202
  logDetection(input: LogDetectionInput): Promise<void>;
214
203
  }
215
204
  declare function getCheckpointApiClient(config?: Partial<CheckpointApiClientConfig>): CheckpointApiClient;
@@ -219,4 +208,4 @@ declare function getCheckpointApiClient(config?: Partial<CheckpointApiClientConf
219
208
  declare function resetCheckpointApiClient(): void;
220
209
  //#endregion
221
210
  export { EnforceResponse as a, LogDetectionInput as c, EnforceInput as i, getCheckpointApiClient as l, CheckpointApiClient as n, EnforcementAction as o, CheckpointApiClientConfig as r, EnforcementDecision as s, ApiDetectionDetail as t, resetCheckpointApiClient as u };
222
- //# sourceMappingURL=api-client-JHOrRUA_.d.ts.map
211
+ //# sourceMappingURL=api-client-yjr43Itz.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-client-yjr43Itz.d.mts","names":[],"sources":["../src/api-client.ts"],"mappings":";;;;;UAkBiB;;EAEf;;EAEA;;;;;;;EAOA;;EAEA;;EAEA;EACA;EACA;;;;;UAgBe;EACf,QAAQ;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IACE;IACA;IACA;MACE;MACA;MACA;MACA;;IAEF;MACE;MACA;MACA;MACA;;;;;;;KAQM,qBAAqB,KAC/B;EAGA;;EAEA;EACA;EACA;EACA,UAAU;EACV,YAAY;;EAEZ;EACA;;;;;;;;;EASA;;;;;UAMe;EACf;EACA;IACE,UAAU;IACV;IACA;IACA,YAAY;;;;;;IAMZ,SAAS;;EAEX;IACE;IACA;;;;;;UAOa;;EAEf,UAAU;;EAEV;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;IAEE;;IAEA;;;;;;UAOa;;EAEf,WAAW;;EAEX;IACE;IACA;IACA;IACA;IACA;;;EAGF;;EAEA;IAAgB,QAAQ;;;EAExB,SAAS;;EAET;IAAQ;IAAc;IAAiB;;;;;;;;;;;;;;;;;;;;;;;cA8B5B;UACH;UACA;UACA;UACA;UACA;UACA;UACA;UACA;EAEI,YAAA,QAAQ;;;;EAkBd,QAAQ,OAAO,eAAe,QAAQ;;;;;;EA4FtC,WAAW,OAAO,eAAe;IACrC,QAAQ;IACR;;;;;EAmBF;EAIM,aAAa,OAAO,oBAAoB;;iBAiFhC,uBACd,SAAS,QAAQ,6BAChB;;;;iBAgBa"}
@@ -19,6 +19,8 @@ interface CheckpointApiClientConfig {
19
19
  timeout?: number;
20
20
  /** Enable debug logging */
21
21
  debug?: boolean;
22
+ telemetryBatchSize?: number;
23
+ telemetryFlushIntervalMs?: number;
22
24
  }
23
25
  /**
24
26
  * Enforcement decision from the API
@@ -176,6 +178,9 @@ declare class CheckpointApiClient {
176
178
  private useEdge;
177
179
  private timeout;
178
180
  private debug;
181
+ private telemetryBatchSize;
182
+ private telemetryFlushIntervalMs;
183
+ private reportSender;
179
184
  constructor(config: CheckpointApiClientConfig);
180
185
  /**
181
186
  * Call the enforce API to check if a request should be allowed
@@ -194,22 +199,6 @@ declare class CheckpointApiClient {
194
199
  * Check if this client is using edge detection (Gateway Worker)
195
200
  */
196
201
  isUsingEdge(): boolean;
197
- /**
198
- * Log a detection result to the Checkpoint database.
199
- * Use after Gateway Worker detection to persist results.
200
- * Fire-and-forget - returns immediately without waiting for DB write.
201
- *
202
- * @example
203
- * ```typescript
204
- * // After receiving Gateway response
205
- * if (client.isUsingEdge() && response.data?.detection) {
206
- * client.logDetection({
207
- * detection: response.data.detection,
208
- * context: { userAgent, ipAddress, path, url, method }
209
- * }).catch(err => console.error('Log failed:', err));
210
- * }
211
- * ```
212
- */
213
202
  logDetection(input: LogDetectionInput): Promise<void>;
214
203
  }
215
204
  declare function getCheckpointApiClient(config?: Partial<CheckpointApiClientConfig>): CheckpointApiClient;
@@ -219,4 +208,4 @@ declare function getCheckpointApiClient(config?: Partial<CheckpointApiClientConf
219
208
  declare function resetCheckpointApiClient(): void;
220
209
  //#endregion
221
210
  export { EnforceResponse as a, LogDetectionInput as c, EnforceInput as i, getCheckpointApiClient as l, CheckpointApiClient as n, EnforcementAction as o, CheckpointApiClientConfig as r, EnforcementDecision as s, ApiDetectionDetail as t, resetCheckpointApiClient as u };
222
- //# sourceMappingURL=api-client-JHOrRUA_.d.mts.map
211
+ //# sourceMappingURL=api-client-yjr43Itz.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-client-yjr43Itz.d.ts","names":[],"sources":["../src/api-client.ts"],"mappings":";;;;;UAkBiB;;EAEf;;EAEA;;;;;;;EAOA;;EAEA;;EAEA;EACA;EACA;;;;;UAgBe;EACf,QAAQ;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IACE;IACA;IACA;MACE;MACA;MACA;MACA;;IAEF;MACE;MACA;MACA;MACA;;;;;;;KAQM,qBAAqB,KAC/B;EAGA;;EAEA;EACA;EACA;EACA,UAAU;EACV,YAAY;;EAEZ;EACA;;;;;;;;;EASA;;;;;UAMe;EACf;EACA;IACE,UAAU;IACV;IACA;IACA,YAAY;;;;;;IAMZ,SAAS;;EAEX;IACE;IACA;;;;;;UAOa;;EAEf,UAAU;;EAEV;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;IAEE;;IAEA;;;;;;UAOa;;EAEf,WAAW;;EAEX;IACE;IACA;IACA;IACA;IACA;;;EAGF;;EAEA;IAAgB,QAAQ;;;EAExB,SAAS;;EAET;IAAQ;IAAc;IAAiB;;;;;;;;;;;;;;;;;;;;;;;cA8B5B;UACH;UACA;UACA;UACA;UACA;UACA;UACA;UACA;EAEI,YAAA,QAAQ;;;;EAkBd,QAAQ,OAAO,eAAe,QAAQ;;;;;;EA4FtC,WAAW,OAAO,eAAe;IACrC,QAAQ;IACR;;;;;EAmBF;EAIM,aAAa,OAAO,oBAAoB;;iBAiFhC,uBACd,SAAS,QAAQ,6BAChB;;;;iBAgBa"}
@@ -1,2 +1,2 @@
1
- import { a as EnforceResponse, c as LogDetectionInput, i as EnforceInput, l as getCheckpointApiClient, n as CheckpointApiClient, o as EnforcementAction, r as CheckpointApiClientConfig, s as EnforcementDecision, t as ApiDetectionDetail, u as resetCheckpointApiClient } from "./api-client-JHOrRUA_.mjs";
1
+ import { a as EnforceResponse, c as LogDetectionInput, i as EnforceInput, l as getCheckpointApiClient, n as CheckpointApiClient, o as EnforcementAction, r as CheckpointApiClientConfig, s as EnforcementDecision, t as ApiDetectionDetail, u as resetCheckpointApiClient } from "./api-client-yjr43Itz.mjs";
2
2
  export { ApiDetectionDetail, CheckpointApiClient, CheckpointApiClientConfig, EnforceInput, EnforceResponse, type EnforcementAction, EnforcementDecision, LogDetectionInput, getCheckpointApiClient, resetCheckpointApiClient };
@@ -1,2 +1,2 @@
1
- import { a as EnforceResponse, c as LogDetectionInput, i as EnforceInput, l as getCheckpointApiClient, n as CheckpointApiClient, o as EnforcementAction, r as CheckpointApiClientConfig, s as EnforcementDecision, t as ApiDetectionDetail, u as resetCheckpointApiClient } from "./api-client-JHOrRUA_.js";
1
+ import { a as EnforceResponse, c as LogDetectionInput, i as EnforceInput, l as getCheckpointApiClient, n as CheckpointApiClient, o as EnforcementAction, r as CheckpointApiClientConfig, s as EnforcementDecision, t as ApiDetectionDetail, u as resetCheckpointApiClient } from "./api-client-yjr43Itz.js";
2
2
  export { ApiDetectionDetail, CheckpointApiClient, CheckpointApiClientConfig, EnforceInput, EnforceResponse, type EnforcementAction, EnforcementDecision, LogDetectionInput, getCheckpointApiClient, resetCheckpointApiClient };
@@ -1,7 +1,14 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_utils = require('./utils-dyFxqlFI.js');
3
+ let _kya_os_checkpoint_wasm_runtime_reporter = require("@kya-os/checkpoint-wasm-runtime/reporter");
3
4
 
4
5
  //#region src/api-client.ts
6
+ /**
7
+ * Checkpoint API Client
8
+ *
9
+ * Lightweight client for calling the Checkpoint enforce API from middleware.
10
+ * Designed for Edge Runtime compatibility (no Node.js-specific APIs).
11
+ */
5
12
  const DEFAULT_BASE_URL = "https://kya.vouched.id";
6
13
  const EDGE_DETECT_URL = "https://detect.checkpoint-gateway.ai";
7
14
  const DEFAULT_TIMEOUT = 5e3;
@@ -31,6 +38,9 @@ var CheckpointApiClient = class {
31
38
  useEdge;
32
39
  timeout;
33
40
  debug;
41
+ telemetryBatchSize;
42
+ telemetryFlushIntervalMs;
43
+ reportSender;
34
44
  constructor(config) {
35
45
  if (!config.apiKey) throw new Error("Checkpoint API key is required");
36
46
  this.apiKey = config.apiKey;
@@ -38,6 +48,8 @@ var CheckpointApiClient = class {
38
48
  this.baseUrl = config.baseUrl || (this.useEdge ? EDGE_DETECT_URL : DEFAULT_BASE_URL);
39
49
  this.timeout = config.timeout || DEFAULT_TIMEOUT;
40
50
  this.debug = config.debug || false;
51
+ this.telemetryBatchSize = config.telemetryBatchSize;
52
+ this.telemetryFlushIntervalMs = config.telemetryFlushIntervalMs;
41
53
  }
42
54
  /**
43
55
  * Call the enforce API to check if a request should be allowed
@@ -121,63 +133,33 @@ var CheckpointApiClient = class {
121
133
  isUsingEdge() {
122
134
  return this.useEdge;
123
135
  }
124
- /**
125
- * Log a detection result to the Checkpoint database.
126
- * Use after Gateway Worker detection to persist results.
127
- * Fire-and-forget - returns immediately without waiting for DB write.
128
- *
129
- * @example
130
- * ```typescript
131
- * // After receiving Gateway response
132
- * if (client.isUsingEdge() && response.data?.detection) {
133
- * client.logDetection({
134
- * detection: response.data.detection,
135
- * context: { userAgent, ipAddress, path, url, method }
136
- * }).catch(err => console.error('Log failed:', err));
137
- * }
138
- * ```
139
- */
140
136
  async logDetection(input) {
141
- const logEndpoint = this.useEdge ? `${DEFAULT_BASE_URL}/api/v1/log-detection` : `${this.baseUrl}/api/v1/log-detection`;
142
- try {
143
- const controller = new AbortController();
144
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
145
- try {
146
- const response = await fetch(logEndpoint, {
147
- method: "POST",
148
- headers: {
149
- "Content-Type": "application/json",
150
- Authorization: `Bearer ${this.apiKey}`
151
- },
152
- body: JSON.stringify({
153
- detection: {
154
- isAgent: input.detection.isAgent,
155
- confidence: input.detection.confidence,
156
- agentName: input.detection.agentName,
157
- agentType: input.detection.agentType,
158
- detectionClass: input.detection.detectionClass,
159
- verificationMethod: input.detection.verificationMethod,
160
- reasons: input.detection.reasons,
161
- detectionBasis: typeof input.detection.detectionBasis === "string" ? input.detection.detectionBasis : void 0
162
- },
163
- context: input.context,
164
- source: input.source || "gateway",
165
- enforcement: input.enforcement,
166
- engine: input.engine,
167
- sdk: input.sdk
168
- }),
169
- signal: controller.signal
170
- });
171
- clearTimeout(timeoutId);
172
- if (!response.ok && this.debug) console.warn("[Checkpoint] Log detection returned non-2xx:", response.status);
173
- } catch (error) {
174
- clearTimeout(timeoutId);
175
- throw error;
176
- }
177
- } catch (error) {
178
- if (this.debug) console.error("[Checkpoint] Log detection failed:", error);
179
- throw error;
180
- }
137
+ this.reportSender ??= (0, _kya_os_checkpoint_wasm_runtime_reporter.makeReportSender)({
138
+ apiKey: this.apiKey,
139
+ baseUrl: this.useEdge ? DEFAULT_BASE_URL : this.baseUrl,
140
+ timeoutMs: this.timeout,
141
+ debug: this.debug,
142
+ telemetryBatchSize: this.telemetryBatchSize,
143
+ telemetryFlushIntervalMs: this.telemetryFlushIntervalMs,
144
+ runtime: input.sdk?.runtime
145
+ });
146
+ await this.reportSender.send({
147
+ detection: {
148
+ isAgent: input.detection.isAgent,
149
+ confidence: input.detection.confidence,
150
+ agentName: input.detection.agentName,
151
+ agentType: input.detection.agentType,
152
+ detectionClass: input.detection.detectionClass,
153
+ verificationMethod: input.detection.verificationMethod,
154
+ reasons: input.detection.reasons,
155
+ detectionBasis: typeof input.detection.detectionBasis === "string" ? input.detection.detectionBasis : void 0
156
+ },
157
+ context: input.context,
158
+ source: input.source || "gateway",
159
+ enforcement: input.enforcement,
160
+ engine: input.engine,
161
+ sdk: input.sdk
162
+ });
181
163
  }
182
164
  };
183
165
  /**
@@ -200,7 +182,9 @@ function resolveClientConfig(config) {
200
182
  baseUrl: config?.baseUrl || process.env.CHECKPOINT_API_URL,
201
183
  useEdge: config?.useEdge ?? process.env.CHECKPOINT_USE_EDGE !== "false",
202
184
  timeout: config?.timeout,
203
- debug: config?.debug || process.env.CHECKPOINT_DEBUG === "true"
185
+ debug: config?.debug || process.env.CHECKPOINT_DEBUG === "true",
186
+ telemetryBatchSize: config?.telemetryBatchSize,
187
+ telemetryFlushIntervalMs: config?.telemetryFlushIntervalMs
204
188
  };
205
189
  }
206
190
  function clientCacheKey(config) {
@@ -209,7 +193,9 @@ function clientCacheKey(config) {
209
193
  config.baseUrl ?? "",
210
194
  config.useEdge,
211
195
  config.timeout ?? DEFAULT_TIMEOUT,
212
- config.debug
196
+ config.debug,
197
+ config.telemetryBatchSize ?? null,
198
+ config.telemetryFlushIntervalMs ?? null
213
199
  ]);
214
200
  }
215
201
  function getCheckpointApiClient(config) {
@@ -1,6 +1,13 @@
1
1
  import { n as relayHeaders } from "./utils-Cnwg0VrY.mjs";
2
+ import { makeReportSender } from "@kya-os/checkpoint-wasm-runtime/reporter";
2
3
 
3
4
  //#region src/api-client.ts
5
+ /**
6
+ * Checkpoint API Client
7
+ *
8
+ * Lightweight client for calling the Checkpoint enforce API from middleware.
9
+ * Designed for Edge Runtime compatibility (no Node.js-specific APIs).
10
+ */
4
11
  const DEFAULT_BASE_URL = "https://kya.vouched.id";
5
12
  const EDGE_DETECT_URL = "https://detect.checkpoint-gateway.ai";
6
13
  const DEFAULT_TIMEOUT = 5e3;
@@ -30,6 +37,9 @@ var CheckpointApiClient = class {
30
37
  useEdge;
31
38
  timeout;
32
39
  debug;
40
+ telemetryBatchSize;
41
+ telemetryFlushIntervalMs;
42
+ reportSender;
33
43
  constructor(config) {
34
44
  if (!config.apiKey) throw new Error("Checkpoint API key is required");
35
45
  this.apiKey = config.apiKey;
@@ -37,6 +47,8 @@ var CheckpointApiClient = class {
37
47
  this.baseUrl = config.baseUrl || (this.useEdge ? EDGE_DETECT_URL : DEFAULT_BASE_URL);
38
48
  this.timeout = config.timeout || DEFAULT_TIMEOUT;
39
49
  this.debug = config.debug || false;
50
+ this.telemetryBatchSize = config.telemetryBatchSize;
51
+ this.telemetryFlushIntervalMs = config.telemetryFlushIntervalMs;
40
52
  }
41
53
  /**
42
54
  * Call the enforce API to check if a request should be allowed
@@ -120,63 +132,33 @@ var CheckpointApiClient = class {
120
132
  isUsingEdge() {
121
133
  return this.useEdge;
122
134
  }
123
- /**
124
- * Log a detection result to the Checkpoint database.
125
- * Use after Gateway Worker detection to persist results.
126
- * Fire-and-forget - returns immediately without waiting for DB write.
127
- *
128
- * @example
129
- * ```typescript
130
- * // After receiving Gateway response
131
- * if (client.isUsingEdge() && response.data?.detection) {
132
- * client.logDetection({
133
- * detection: response.data.detection,
134
- * context: { userAgent, ipAddress, path, url, method }
135
- * }).catch(err => console.error('Log failed:', err));
136
- * }
137
- * ```
138
- */
139
135
  async logDetection(input) {
140
- const logEndpoint = this.useEdge ? `${DEFAULT_BASE_URL}/api/v1/log-detection` : `${this.baseUrl}/api/v1/log-detection`;
141
- try {
142
- const controller = new AbortController();
143
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
144
- try {
145
- const response = await fetch(logEndpoint, {
146
- method: "POST",
147
- headers: {
148
- "Content-Type": "application/json",
149
- Authorization: `Bearer ${this.apiKey}`
150
- },
151
- body: JSON.stringify({
152
- detection: {
153
- isAgent: input.detection.isAgent,
154
- confidence: input.detection.confidence,
155
- agentName: input.detection.agentName,
156
- agentType: input.detection.agentType,
157
- detectionClass: input.detection.detectionClass,
158
- verificationMethod: input.detection.verificationMethod,
159
- reasons: input.detection.reasons,
160
- detectionBasis: typeof input.detection.detectionBasis === "string" ? input.detection.detectionBasis : void 0
161
- },
162
- context: input.context,
163
- source: input.source || "gateway",
164
- enforcement: input.enforcement,
165
- engine: input.engine,
166
- sdk: input.sdk
167
- }),
168
- signal: controller.signal
169
- });
170
- clearTimeout(timeoutId);
171
- if (!response.ok && this.debug) console.warn("[Checkpoint] Log detection returned non-2xx:", response.status);
172
- } catch (error) {
173
- clearTimeout(timeoutId);
174
- throw error;
175
- }
176
- } catch (error) {
177
- if (this.debug) console.error("[Checkpoint] Log detection failed:", error);
178
- throw error;
179
- }
136
+ this.reportSender ??= makeReportSender({
137
+ apiKey: this.apiKey,
138
+ baseUrl: this.useEdge ? DEFAULT_BASE_URL : this.baseUrl,
139
+ timeoutMs: this.timeout,
140
+ debug: this.debug,
141
+ telemetryBatchSize: this.telemetryBatchSize,
142
+ telemetryFlushIntervalMs: this.telemetryFlushIntervalMs,
143
+ runtime: input.sdk?.runtime
144
+ });
145
+ await this.reportSender.send({
146
+ detection: {
147
+ isAgent: input.detection.isAgent,
148
+ confidence: input.detection.confidence,
149
+ agentName: input.detection.agentName,
150
+ agentType: input.detection.agentType,
151
+ detectionClass: input.detection.detectionClass,
152
+ verificationMethod: input.detection.verificationMethod,
153
+ reasons: input.detection.reasons,
154
+ detectionBasis: typeof input.detection.detectionBasis === "string" ? input.detection.detectionBasis : void 0
155
+ },
156
+ context: input.context,
157
+ source: input.source || "gateway",
158
+ enforcement: input.enforcement,
159
+ engine: input.engine,
160
+ sdk: input.sdk
161
+ });
180
162
  }
181
163
  };
182
164
  /**
@@ -199,7 +181,9 @@ function resolveClientConfig(config) {
199
181
  baseUrl: config?.baseUrl || process.env.CHECKPOINT_API_URL,
200
182
  useEdge: config?.useEdge ?? process.env.CHECKPOINT_USE_EDGE !== "false",
201
183
  timeout: config?.timeout,
202
- debug: config?.debug || process.env.CHECKPOINT_DEBUG === "true"
184
+ debug: config?.debug || process.env.CHECKPOINT_DEBUG === "true",
185
+ telemetryBatchSize: config?.telemetryBatchSize,
186
+ telemetryFlushIntervalMs: config?.telemetryFlushIntervalMs
203
187
  };
204
188
  }
205
189
  function clientCacheKey(config) {
@@ -208,7 +192,9 @@ function clientCacheKey(config) {
208
192
  config.baseUrl ?? "",
209
193
  config.useEdge,
210
194
  config.timeout ?? DEFAULT_TIMEOUT,
211
- config.debug
195
+ config.debug,
196
+ config.telemetryBatchSize ?? null,
197
+ config.telemetryFlushIntervalMs ?? null
212
198
  ]);
213
199
  }
214
200
  function getCheckpointApiClient(config) {
@@ -1 +1 @@
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,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,G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AS,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"}
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 { makeReportSender, type ReportSender } from '@kya-os/checkpoint-wasm-runtime/reporter';\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 telemetryBatchSize?: number;\n telemetryFlushIntervalMs?: number;\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 * 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 private telemetryBatchSize: number | undefined;\n private telemetryFlushIntervalMs: number | undefined;\n private reportSender: ReportSender | undefined;\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 this.telemetryBatchSize = config.telemetryBatchSize;\n this.telemetryFlushIntervalMs = config.telemetryFlushIntervalMs;\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 async logDetection(input: LogDetectionInput): Promise<void> {\n this.reportSender ??= makeReportSender({\n apiKey: this.apiKey,\n baseUrl: this.useEdge ? DEFAULT_BASE_URL : this.baseUrl,\n timeoutMs: this.timeout,\n debug: this.debug,\n telemetryBatchSize: this.telemetryBatchSize,\n telemetryFlushIntervalMs: this.telemetryFlushIntervalMs,\n runtime: input.sdk?.runtime,\n });\n await this.reportSender.send({\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 enforcement: input.enforcement,\n engine: input.engine,\n sdk: input.sdk,\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 telemetryBatchSize: config?.telemetryBatchSize,\n telemetryFlushIntervalMs: config?.telemetryFlushIntervalMs,\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 config.telemetryBatchSize ?? null,\n config.telemetryFlushIntervalMs ?? null,\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":";;;;;;;;;;AAwLA,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;AAqBxB,I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A,SAAS,MAAM;GACf,QAAQ,MAAM,UAAU;GACxB,aAAa,MAAM;GACnB,QAAQ,MAAM;GACd,KAAK,MAAM;EACb,CAAC;CACH;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;EACzD,oBAAoB,QAAQ;EAC5B,0BAA0B,QAAQ;CACpC;AACF;AAEA,SAAS,eAAe,QAA2C;CACjE,OAAO,KAAK,UAAU;EACpB,OAAO;EACP,OAAO,WAAW;EAClB,OAAO;EACP,OAAO,WAAW;EAClB,OAAO;EACP,OAAO,sBAAsB;EAC7B,OAAO,4BAA4B;CACrC,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"}
@@ -177,7 +177,7 @@ function sdkSelfIdentification() {
177
177
  const runtime = typeof process !== "undefined" && process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
178
178
  return {
179
179
  name: SDK_NAME,
180
- version: "1.13.0",
180
+ version: "1.14.0",
181
181
  runtime
182
182
  };
183
183
  }
@@ -279,7 +279,9 @@ function withCheckpointApi(config = {}) {
279
279
  baseUrl: config.apiUrl,
280
280
  useEdge: config.useEdge,
281
281
  timeout: config.timeout,
282
- debug: config.debug
282
+ debug: config.debug,
283
+ telemetryBatchSize: config.telemetryBatchSize,
284
+ telemetryFlushIntervalMs: config.telemetryFlushIntervalMs
283
285
  });
284
286
  return client;
285
287
  };
@@ -177,7 +177,7 @@ function sdkSelfIdentification() {
177
177
  const runtime = typeof process !== "undefined" && process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
178
178
  return {
179
179
  name: SDK_NAME,
180
- version: "1.13.0",
180
+ version: "1.14.0",
181
181
  runtime
182
182
  };
183
183
  }
@@ -279,7 +279,9 @@ function withCheckpointApi(config = {}) {
279
279
  baseUrl: config.apiUrl,
280
280
  useEdge: config.useEdge,
281
281
  timeout: config.timeout,
282
- debug: config.debug
282
+ debug: config.debug,
283
+ telemetryBatchSize: config.telemetryBatchSize,
284
+ telemetryFlushIntervalMs: config.telemetryFlushIntervalMs
283
285
  });
284
286
  return client;
285
287
  };
@@ -384,4 +386,4 @@ function failOpenResponse() {
384
386
 
385
387
  //#endregion
386
388
  export { withCheckpointApi as t };
387
- //# sourceMappingURL=api-middleware-DcUgTDv5.mjs.map
389
+ //# sourceMappingURL=api-middleware-CAarHFKk.mjs.map