@kya-os/checkpoint-nextjs 1.13.0 → 1.15.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.
- package/CHANGELOG.md +43 -0
- package/README.md +19 -10
- package/dist/{api-client-JHOrRUA_.d.ts → api-client-yjr43Itz.d.mts} +6 -17
- package/dist/api-client-yjr43Itz.d.mts.map +1 -0
- package/dist/{api-client-JHOrRUA_.d.mts → api-client-yjr43Itz.d.ts} +6 -17
- package/dist/api-client-yjr43Itz.d.ts.map +1 -0
- package/dist/api-client.d.mts +1 -1
- package/dist/api-client.d.ts +1 -1
- package/dist/api-client.js +45 -59
- package/dist/api-client.mjs +45 -59
- package/dist/api-client.mjs.map +1 -1
- package/dist/{api-middleware-LhLqOapx.js → api-middleware-Bcu8f06W.js} +7 -5
- package/dist/{api-middleware-BtsYJU5u.d.mts → api-middleware-CIXuGurw.d.mts} +4 -2
- package/dist/{api-middleware-BtsYJU5u.d.mts.map → api-middleware-CIXuGurw.d.mts.map} +1 -1
- package/dist/{api-middleware-DyLDqOYF.d.ts → api-middleware-CpAbnkfa.d.ts} +4 -2
- package/dist/{api-middleware-DyLDqOYF.d.ts.map → api-middleware-CpAbnkfa.d.ts.map} +1 -1
- package/dist/{api-middleware-DcUgTDv5.mjs → api-middleware-xhlisoi2.mjs} +8 -6
- package/dist/api-middleware-xhlisoi2.mjs.map +1 -0
- package/dist/api-middleware.d.mts +1 -1
- package/dist/api-middleware.d.ts +1 -1
- package/dist/api-middleware.js +1 -1
- package/dist/api-middleware.mjs +1 -1
- package/dist/cedar-wasm.d.mts +1 -1
- package/dist/cedar-wasm.d.ts +1 -1
- package/dist/cedar-wasm.js +1 -1
- package/dist/cedar-wasm.mjs +1 -1
- package/dist/cedar-wasm.mjs.map +1 -1
- package/dist/{config-DQ-VuHlJ.d.mts → config-CVqpjhwT.d.mts} +2 -2
- package/dist/{config-DQ-VuHlJ.d.mts.map → config-CVqpjhwT.d.mts.map} +1 -1
- package/dist/{config-CXS_-rRv.d.ts → config-Dn2ptSA2.d.ts} +2 -2
- package/dist/{config-CXS_-rRv.d.ts.map → config-Dn2ptSA2.d.ts.map} +1 -1
- package/dist/index-edge.d.mts +5 -5
- package/dist/index-edge.d.ts +5 -5
- package/dist/index-edge.js +3 -3
- package/dist/index-edge.mjs +3 -3
- package/dist/index.d.mts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/index.mjs +3 -3
- package/dist/middleware-bundler.d.mts +1 -1
- package/dist/middleware-bundler.d.ts +1 -1
- package/dist/middleware-bundler.js +1 -1
- package/dist/middleware-bundler.mjs +1 -1
- package/dist/{middleware-core-Cxb9Jh0a.d.mts → middleware-core-B70g9yLE.d.mts} +3 -3
- package/dist/middleware-core-B70g9yLE.d.mts.map +1 -0
- package/dist/{middleware-core-DaNMjsib.d.ts → middleware-core-DH6kGKc8.d.ts} +3 -3
- package/dist/middleware-core-DH6kGKc8.d.ts.map +1 -0
- package/dist/{middleware-core-DN_FLlaV.mjs → middleware-core-qXSvMDYw.mjs} +3 -3
- package/dist/{middleware-core-DN_FLlaV.mjs.map → middleware-core-qXSvMDYw.mjs.map} +1 -1
- package/dist/{middleware-core-0s8y7UNN.js → middleware-core-yE25rSJE.js} +2 -2
- package/dist/middleware-edge.d.mts +1 -1
- package/dist/middleware-edge.d.ts +1 -1
- package/dist/middleware-edge.js +2 -2
- package/dist/middleware-edge.mjs +2 -2
- package/dist/middleware-node.d.mts +2 -2
- package/dist/middleware-node.d.ts +2 -2
- package/dist/middleware-node.js +1 -1
- package/dist/middleware-node.mjs +1 -1
- package/dist/{posture-outcome-DddsJtL8.js → posture-outcome-3mJLVX85.js} +5 -0
- package/dist/{posture-outcome-DQ4fdMfq.mjs → posture-outcome-CN1WranD.mjs} +7 -2
- package/dist/posture-outcome-CN1WranD.mjs.map +1 -0
- package/dist/posture-outcome-Ccujx_9V.d.mts.map +1 -1
- package/dist/posture-outcome-Ccujx_9V.d.ts.map +1 -1
- package/dist/public-api-CAJ9XPJC.d.mts +5 -0
- package/dist/public-api-D5so-53z.d.ts +5 -0
- package/dist/{utils-dyFxqlFI.js → utils-CdoAQaFy.js} +16 -0
- package/dist/{utils-Cnwg0VrY.mjs → utils-DK9HXCUV.mjs} +12 -2
- package/dist/utils-DK9HXCUV.mjs.map +1 -0
- package/package.json +3 -3
- package/dist/api-client-JHOrRUA_.d.mts.map +0 -1
- package/dist/api-client-JHOrRUA_.d.ts.map +0 -1
- package/dist/api-middleware-DcUgTDv5.mjs.map +0 -1
- package/dist/middleware-core-Cxb9Jh0a.d.mts.map +0 -1
- package/dist/middleware-core-DaNMjsib.d.ts.map +0 -1
- package/dist/posture-outcome-DQ4fdMfq.mjs.map +0 -1
- package/dist/public-api-BZ5Ahk6X.d.mts +0 -5
- package/dist/public-api-DnTh8YEz.d.ts +0 -5
- package/dist/utils-Cnwg0VrY.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,49 @@
|
|
|
2
2
|
|
|
3
3
|
# @kya-os/checkpoint-nextjs
|
|
4
4
|
|
|
5
|
+
## 1.15.0 - 2026-11-19
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- `getCheckpointPostureOutcome` logs one warning (`console.warn`) when its `browserPosture` turns on `allowLoopbackOrigins`, which is for development only. (#8113)
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- a decision from the enforce API without a numeric confidence is applied without the `KYA-Confidence` header, instead of ending in the fault response (a 503 by default, or a pass-through with `failOpen`). (#8056)
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- `withCheckpointApi` sends the `KYA-Confidence` header as a whole number from 0 to 100 (for example `100`, not `99.99999999993561`), matching the .NET SDK and the docs. (#8056)
|
|
18
|
+
|
|
19
|
+
## 1.14.0 - 2026-11-16
|
|
20
|
+
|
|
21
|
+
### Breaking changes
|
|
22
|
+
|
|
23
|
+
- 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)
|
|
24
|
+
- Removed: the legacy entry points and aliases, also removed in 1.11.0 by #6271, whose imports now fail at build:
|
|
25
|
+
- the throw stubs `./middleware`, `./edge-wasm-middleware`, `createMiddleware`, `createAgentShieldMiddleware`, `createAgentShieldMiddlewareBase` and `createEnhancedAgentShieldMiddleware`;
|
|
26
|
+
- the TypeScript detector entries `./edge-runtime-loader` and `./wasm-setup`;
|
|
27
|
+
- the `AgentShield*` aliases of the current API: `withAgentShield`, `agentShieldMiddleware`, `AgentShieldClient`, `getAgentShieldClient` and `resetAgentShieldClient`, with `AgentShieldMiddlewareConfig` and `AgentShieldClientConfig`.
|
|
28
|
+
Use `withCheckpoint`, `withCheckpointApi`, `CheckpointApiClient`, `getCheckpointApiClient` and `resetCheckpointApiClient`. (#6809)
|
|
29
|
+
- 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.
|
|
30
|
+
Like every configuration error, it does not throw from the middleware module. (#6973)
|
|
31
|
+
|
|
32
|
+
### Changed
|
|
33
|
+
|
|
34
|
+
- 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.
|
|
35
|
+
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.
|
|
36
|
+
A policy outage is logged at most about every 5 seconds, and the next request reads the policy again. (#6973)
|
|
37
|
+
- CheckpointApiClient.logDetection retries once, after waiting it out, when the receiver sheds with a 503 whose Retry-After is 1 to 3 seconds. (#7250)
|
|
38
|
+
- `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)
|
|
39
|
+
|
|
40
|
+
### Fixed
|
|
41
|
+
|
|
42
|
+
- 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.
|
|
43
|
+
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)
|
|
44
|
+
- 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.
|
|
45
|
+
Enforce mode still answers 503 with `Retry-After: 3`. (#6973)
|
|
46
|
+
- 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)
|
|
47
|
+
|
|
5
48
|
## 1.13.0 - 2026-10-22
|
|
6
49
|
|
|
7
50
|
### 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
|
});
|
|
@@ -144,11 +145,17 @@ Next.js always bundles `proxy.ts` and `middleware.ts`, and Turbopack follows tha
|
|
|
144
145
|
In a minimal Next.js 16 app, `proxy.ts` with `withCheckpoint` traces 117 files (5.6 MiB), against 111 files for a `proxy.ts` without it.
|
|
145
146
|
If the engine cannot load (a missing or unreadable `.wasm`), every request is answered 503, the cause is logged, and the next request tries again.
|
|
146
147
|
|
|
148
|
+
In a Server Component or a Server Function, Next.js bundles the engine and rewrites that URL, so the engine cannot load and the logged `EngineLoadError` says so.
|
|
149
|
+
There, load the engine from `node_modules`: install `@kya-os/checkpoint-wasm-runtime` as a direct dependency, at the version this package uses (`npm ls @kya-os/checkpoint-wasm-runtime` shows it), and add `serverExternalPackages: ['@kya-os/checkpoint-wasm-runtime']` to `next.config`.
|
|
150
|
+
Next.js keeps the package out of the bundle only when the app itself resolves it, which pnpm does not do for a dependency of a dependency, so under webpack the setting alone does nothing there.
|
|
151
|
+
`serverExternalPackages` needs Next.js 15 or later; on Next.js 13 and 14 it is `experimental.serverComponentsExternalPackages`.
|
|
152
|
+
|
|
147
153
|
On webpack, the Node.js runtime is not supported yet: the build succeeds, but webpack rewrites the `.wasm` URL into a value Node's file read rejects, so the engine fails to load and every request is answered 503.
|
|
148
154
|
|
|
149
155
|
### Background work
|
|
150
156
|
|
|
151
157
|
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.
|
|
158
|
+
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
159
|
`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
160
|
If you wrap `withCheckpoint` in your own middleware, pass the event through:
|
|
154
161
|
|
|
@@ -271,8 +278,10 @@ export default withCheckpointApi({
|
|
|
271
278
|
|
|
272
279
|
The local-engine shape (`withCheckpoint`) takes a `CheckpointConfig` instead,
|
|
273
280
|
every field optional: `enforcementMode` (`'enforce'` | `'observe'`), `apiKey`
|
|
274
|
-
(enables dashboard reporting), `projectId` (
|
|
275
|
-
policy in-process
|
|
281
|
+
(enables dashboard reporting), `projectId` (applies your deployed dashboard
|
|
282
|
+
policy in-process, and needs `apiKey`: without it, enforce mode is a
|
|
283
|
+
configuration error answered 503, and observe mode serves without the policy and
|
|
284
|
+
warns once), and more. `tenantHost` is deprecated: it is no longer used
|
|
276
285
|
and will be removed. See the
|
|
277
286
|
[middleware docs](https://kya.vouched.id/docs/enforce/middleware) for the
|
|
278
287
|
full option tables for both shapes.
|
|
@@ -281,13 +290,13 @@ full option tables for both shapes.
|
|
|
281
290
|
|
|
282
291
|
`withCheckpoint` answers `503` (`Retry-After: 3`, `Cache-Control: no-store`)
|
|
283
292
|
when the verification pipeline errors; it never passes the request through or
|
|
284
|
-
returns a 500. If the policy API is unreachable,
|
|
285
|
-
policy
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
293
|
+
returns a 500. If the policy API is unreachable,
|
|
294
|
+
a policy still inside its cache window (`policyCacheTtlSeconds`, 300 by default)
|
|
295
|
+
keeps being used. Once that window ends, or on a cold start, the request is
|
|
296
|
+
answered `503`: no older copy is kept, and the default policy is never
|
|
297
|
+
substituted. A timeout, a 5xx, a policy-origin 401/403/404 or a body that is
|
|
298
|
+
not a policy-API response all end the same way. In observe mode the request is
|
|
299
|
+
served on the engine's decision instead.
|
|
291
300
|
|
|
292
301
|
### DID documents and status lists
|
|
293
302
|
|
|
@@ -499,4 +508,4 @@ component), pass those instead of a request. Verification is a single ES256 chec
|
|
|
499
508
|
calling it in a handler as well as in the middleware costs little. A verified token that carries
|
|
500
509
|
the beacon's agent or bot verdict (`posture.detection`), or discloses automation, also
|
|
501
510
|
reclassifies a request the engine called human or incomplete data.
|
|
502
|
-
The accessor validates `browserPosture` and `projectId` with the same check `withCheckpoint` runs at startup: `projectId` must be the lowercase project UUID, not the friendly id, and any invalid config throws. Pass the same config object the middleware takes. Treat `absent` and `rejected` alike (neither is usable posture evidence), and log `reason` on the server rather than returning it to the client.
|
|
511
|
+
The accessor validates `browserPosture` and `projectId` with the same check `withCheckpoint` runs at startup: `projectId` must be the lowercase project UUID, not the friendly id, and any invalid config throws. To find the UUID, copy **Project UUID** from the top of the **Installations** page or from **All settings → Projects** in the user menu (a project with no friendly ID shows its UUID as the **Project ID**). Pass the same config object the middleware takes. Treat `absent` and `rejected` alike (neither is usable posture evidence), and log `reason` on the server rather than returning it to the client.
|
|
@@ -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-
|
|
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-
|
|
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"}
|
package/dist/api-client.d.mts
CHANGED
|
@@ -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-
|
|
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 };
|
package/dist/api-client.d.ts
CHANGED
|
@@ -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-
|
|
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 };
|
package/dist/api-client.js
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_utils = require('./utils-
|
|
2
|
+
const require_utils = require('./utils-CdoAQaFy.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
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
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) {
|
package/dist/api-client.mjs
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
|
-
import { n as relayHeaders } from "./utils-
|
|
1
|
+
import { n as relayHeaders } from "./utils-DK9HXCUV.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
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
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) {
|
package/dist/api-client.mjs.map
CHANGED
|
@@ -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,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;MACnB,GAAG;MACH,SAAS,MAAM,WAAW,aAAa,MAAM,OAAO;KACtD,CAAC;KACD,QAAQ,WAAW;IACrB,CAAC;IAED,aAAa,SAAS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C;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,IAAa,sBAAb,MAAiC;CAC/B,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,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;EAC7B,KAAK,qBA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