@kya-os/checkpoint-nextjs 1.14.0 → 1.16.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 +24 -1
- package/README.md +29 -1
- package/dist/{api-client-yjr43Itz.d.ts → api-client-CmNX_FHm.d.mts} +24 -1
- package/dist/api-client-CmNX_FHm.d.mts.map +1 -0
- package/dist/{api-client-yjr43Itz.d.mts → api-client-W9WPq82L.d.ts} +24 -1
- package/dist/api-client-W9WPq82L.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 +16 -4
- package/dist/api-client.mjs +16 -4
- package/dist/api-client.mjs.map +1 -1
- package/dist/{api-middleware-BVXf7qCM.js → api-middleware-CAN0gnw-.js} +10 -5
- package/dist/{api-middleware-CIXuGurw.d.mts → api-middleware-D-djCzbx.d.mts} +8 -2
- package/dist/{api-middleware-CIXuGurw.d.mts.map → api-middleware-D-djCzbx.d.mts.map} +1 -1
- package/dist/{api-middleware-CAarHFKk.mjs → api-middleware-GEmIPBLq.mjs} +11 -6
- package/dist/api-middleware-GEmIPBLq.mjs.map +1 -0
- package/dist/{api-middleware-CpAbnkfa.d.ts → api-middleware-n1aAWNoQ.d.ts} +8 -2
- package/dist/{api-middleware-CpAbnkfa.d.ts.map → api-middleware-n1aAWNoQ.d.ts.map} +1 -1
- 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/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.js +1 -1
- package/dist/middleware-bundler.mjs +1 -1
- package/dist/{middleware-core-tGGPv727.js → middleware-core-BPLmDNjf.js} +2 -2
- package/dist/{middleware-core-D88q8dIt.d.mts → middleware-core-Cd4fdQog.d.mts} +2 -2
- package/dist/middleware-core-Cd4fdQog.d.mts.map +1 -0
- package/dist/{middleware-core-C4xi1I9I.mjs → middleware-core-CkKHnNgF.mjs} +3 -3
- package/dist/{middleware-core-C4xi1I9I.mjs.map → middleware-core-CkKHnNgF.mjs.map} +1 -1
- package/dist/{middleware-core-BLCAErYE.d.ts → middleware-core-D6EpfMLW.d.ts} +2 -2
- package/dist/middleware-core-D6EpfMLW.d.ts.map +1 -0
- 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 +1 -1
- package/dist/middleware-node.d.ts +1 -1
- package/dist/middleware-node.js +1 -1
- package/dist/middleware-node.mjs +1 -1
- package/dist/{posture-outcome-DQ4fdMfq.mjs → posture-outcome-BecgUc_x.mjs} +15 -3
- package/dist/posture-outcome-BecgUc_x.mjs.map +1 -0
- package/dist/{posture-outcome-DddsJtL8.js → posture-outcome-BtVin59Q.js} +13 -1
- package/dist/{posture-outcome-Ccujx_9V.d.ts → posture-outcome-DFkDKHVS.d.mts} +6 -3
- package/dist/posture-outcome-DFkDKHVS.d.mts.map +1 -0
- package/dist/{posture-outcome-Ccujx_9V.d.mts → posture-outcome-DFkDKHVS.d.ts} +6 -3
- package/dist/posture-outcome-DFkDKHVS.d.ts.map +1 -0
- package/dist/public-api-CcTZtETe.d.ts +5 -0
- package/dist/public-api-JV2lXjAr.d.mts +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-yjr43Itz.d.mts.map +0 -1
- package/dist/api-client-yjr43Itz.d.ts.map +0 -1
- package/dist/api-middleware-CAarHFKk.mjs.map +0 -1
- package/dist/middleware-core-BLCAErYE.d.ts.map +0 -1
- package/dist/middleware-core-D88q8dIt.d.mts.map +0 -1
- package/dist/posture-outcome-Ccujx_9V.d.mts.map +0 -1
- package/dist/posture-outcome-Ccujx_9V.d.ts.map +0 -1
- package/dist/posture-outcome-DQ4fdMfq.mjs.map +0 -1
- package/dist/public-api-CBQzjriI.d.mts +0 -5
- package/dist/public-api-Ea4jgcwD.d.ts +0 -5
- package/dist/utils-Cnwg0VrY.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,29 @@
|
|
|
2
2
|
|
|
3
3
|
# @kya-os/checkpoint-nextjs
|
|
4
4
|
|
|
5
|
+
## 1.16.0 - 2026-12-01
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- detection reports carry `context.browserSessionId` and `context.sessionSource`, so a server request lands in the same session as the beacon's rows for that visit. `withCheckpointApi` also sends the beacon session on its enforce call, and takes a `sessionCookieName` option for a renamed beacon cookie. (#8338)
|
|
10
|
+
- `getCheckpointPostureOutcome` verifies kp2 and 480 s key-bound tokens, checking the DPoP proof against the request method and URL. (#8339)
|
|
11
|
+
- `getCheckpointPostureOutcome` accepts `browserPosture.publicBaseUrl`, so a Next.js app behind a proxy checks the proof against its public URL. (#8339)
|
|
12
|
+
- `getCheckpointPostureOutcome` also takes `{ headers, method, url }`, so a proof sent with headers outside a `Request` is checked. (#8339)
|
|
13
|
+
|
|
14
|
+
## 1.15.0 - 2026-11-19
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
|
|
18
|
+
- `getCheckpointPostureOutcome` logs one warning (`console.warn`) when its `browserPosture` turns on `allowLoopbackOrigins`, which is for development only. (#8113)
|
|
19
|
+
|
|
20
|
+
### Changed
|
|
21
|
+
|
|
22
|
+
- 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)
|
|
23
|
+
|
|
24
|
+
### Fixed
|
|
25
|
+
|
|
26
|
+
- `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)
|
|
27
|
+
|
|
5
28
|
## 1.14.0 - 2026-11-16
|
|
6
29
|
|
|
7
30
|
### Breaking changes
|
|
@@ -524,7 +547,7 @@ Node and Edge runtimes ship byte-equivalent payloads to
|
|
|
524
547
|
opened in 1.1.2 via PR #2610 / AgentDetector-Deletion-1. Per project
|
|
525
548
|
semver policy this is shipped as a minor bump (not a major) because:
|
|
526
549
|
(a) the deprecation landed yesterday and was effectively one calendar
|
|
527
|
-
day, (b) the package is pre-
|
|
550
|
+
day, (b) the package is pre-customer-trial with no external pins to
|
|
528
551
|
`^1.x.0`, and (c) the workspace-wide deletion-gate test pins the absence
|
|
529
552
|
structurally so re-introduction is mechanically blocked.
|
|
530
553
|
|
package/README.md
CHANGED
|
@@ -145,6 +145,11 @@ Next.js always bundles `proxy.ts` and `middleware.ts`, and Turbopack follows tha
|
|
|
145
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.
|
|
146
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.
|
|
147
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
|
+
|
|
148
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.
|
|
149
154
|
|
|
150
155
|
### Background work
|
|
@@ -164,6 +169,29 @@ export default function middleware(request: NextRequest, event: NextFetchEvent)
|
|
|
164
169
|
|
|
165
170
|
Without an event, it falls back to `waitUntil` from `@vercel/functions`, which only has an effect on Vercel.
|
|
166
171
|
|
|
172
|
+
### Sessions in detection reports
|
|
173
|
+
|
|
174
|
+
Each report names the visit's session in `context.browserSessionId`, so a server request lands in the same session as the beacon's rows for that visit.
|
|
175
|
+
The SDK picks it in this order:
|
|
176
|
+
|
|
177
|
+
1. The `KYA-Posture-Session` header, then the `_as_beacon_session` cookie (or `browserPosture.sessionCookieName`).
|
|
178
|
+
A value that is not a UUID is dropped.
|
|
179
|
+
2. A guest token: a bearer JWT whose payload has `atp` equal to `guest`.
|
|
180
|
+
`context.browserSessionId` is a key derived from the token, and `context.sessionSource` is `guest-token`.
|
|
181
|
+
Every call made with one token lands in one session, and a different token is a different session.
|
|
182
|
+
3. Otherwise both fields are left out, and the dashboard gives the request a session of its own.
|
|
183
|
+
|
|
184
|
+
Any other bearer token adds nothing: a signed-in caller's access token changes on every refresh, so a key derived from it would look like a new visitor each time.
|
|
185
|
+
The key is an HMAC-SHA256 of the exact token string, shaped as a version 4 UUID, under a key derived from your project API key, so the same token gives a different id in another project, and rotating the API key starts new sessions.
|
|
186
|
+
The token is never logged, stored or sent, and the key cannot be turned back into the token.
|
|
187
|
+
|
|
188
|
+
| Field | Contents |
|
|
189
|
+
| -------------------------- | ---------------------------------------------------------------------------------- |
|
|
190
|
+
| `context.browserSessionId` | the session id the request carries, or a keyed hash of its guest bearer token |
|
|
191
|
+
| `context.sessionSource` | `guest-token` when `browserSessionId` came from a guest bearer token; else omitted |
|
|
192
|
+
|
|
193
|
+
`withCheckpointApi` takes the cookie name as its own `sessionCookieName` option. Its call to the enforce API carries the beacon session alone; a guest token's key goes only on the report it sends with `useEdge` (the default), so with `useEdge: false` a guest caller's row gets a session of its own.
|
|
194
|
+
|
|
167
195
|
## Installation
|
|
168
196
|
|
|
169
197
|
```bash
|
|
@@ -503,4 +531,4 @@ component), pass those instead of a request. Verification is a single ES256 chec
|
|
|
503
531
|
calling it in a handler as well as in the middleware costs little. A verified token that carries
|
|
504
532
|
the beacon's agent or bot verdict (`posture.detection`), or discloses automation, also
|
|
505
533
|
reclassifies a request the engine called human or incomplete data.
|
|
506
|
-
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.
|
|
534
|
+
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.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { BrowserSessionRequest } from "@kya-os/checkpoint-shared/browser-session";
|
|
1
2
|
import { DetectionDetail, EnforcementAction, EngineInfo } from "@kya-os/checkpoint-shared";
|
|
2
3
|
//#region src/api-client.d.ts
|
|
3
4
|
/**
|
|
@@ -21,6 +22,12 @@ interface CheckpointApiClientConfig {
|
|
|
21
22
|
debug?: boolean;
|
|
22
23
|
telemetryBatchSize?: number;
|
|
23
24
|
telemetryFlushIntervalMs?: number;
|
|
25
|
+
/**
|
|
26
|
+
* The beacon's session cookie name, when the project set another than
|
|
27
|
+
* `_as_beacon_session` (the beacon's `sessionCookieName`). Reports read the
|
|
28
|
+
* visit's session from it.
|
|
29
|
+
*/
|
|
30
|
+
sessionCookieName?: string;
|
|
24
31
|
}
|
|
25
32
|
/**
|
|
26
33
|
* Enforcement decision from the API
|
|
@@ -115,6 +122,13 @@ interface EnforceInput {
|
|
|
115
122
|
method?: string;
|
|
116
123
|
/** Request ID for tracing */
|
|
117
124
|
requestId?: string;
|
|
125
|
+
/**
|
|
126
|
+
* The visit's beacon session (`beaconSessionId` from
|
|
127
|
+
* `@kya-os/checkpoint-shared/browser-session`): the enforce endpoint stores
|
|
128
|
+
* it as the detection's session, so the row joins the beacon rows of the
|
|
129
|
+
* same visit. Without it the row gets a session of its own.
|
|
130
|
+
*/
|
|
131
|
+
browserSessionId?: string;
|
|
118
132
|
/** Options */
|
|
119
133
|
options?: {
|
|
120
134
|
/** Include full detection result */
|
|
@@ -137,6 +151,14 @@ interface LogDetectionInput {
|
|
|
137
151
|
url?: string;
|
|
138
152
|
method?: string;
|
|
139
153
|
};
|
|
154
|
+
/**
|
|
155
|
+
* The request's `KYA-Posture-Session` header, cookie and `Authorization`
|
|
156
|
+
* values (`browserSessionRequestFromHeaders`). The report's `context` then
|
|
157
|
+
* names the session they pick as `browserSessionId` (and `sessionSource`
|
|
158
|
+
* for a guest token's key), in the order every SDK uses: the header, then
|
|
159
|
+
* the session cookie, then a guest bearer token.
|
|
160
|
+
*/
|
|
161
|
+
session?: BrowserSessionRequest;
|
|
140
162
|
/** Source of the detection */
|
|
141
163
|
source?: 'gateway' | 'middleware';
|
|
142
164
|
/** The enforcement decision the caller received and acted on. */
|
|
@@ -181,6 +203,7 @@ declare class CheckpointApiClient {
|
|
|
181
203
|
private telemetryBatchSize;
|
|
182
204
|
private telemetryFlushIntervalMs;
|
|
183
205
|
private reportSender;
|
|
206
|
+
private readonly sessionPicker;
|
|
184
207
|
constructor(config: CheckpointApiClientConfig);
|
|
185
208
|
/**
|
|
186
209
|
* Call the enforce API to check if a request should be allowed
|
|
@@ -208,4 +231,4 @@ declare function getCheckpointApiClient(config?: Partial<CheckpointApiClientConf
|
|
|
208
231
|
declare function resetCheckpointApiClient(): void;
|
|
209
232
|
//#endregion
|
|
210
233
|
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 };
|
|
211
|
-
//# sourceMappingURL=api-client-
|
|
234
|
+
//# sourceMappingURL=api-client-CmNX_FHm.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-client-CmNX_FHm.d.mts","names":[],"sources":["../src/api-client.ts"],"mappings":";;;;;;UAuBiB;;EAEf;;EAEA;;;;;;;EAOA;;EAEA;;EAEA;EACA;EACA;;;;;;EAMA;;;;;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;;;;;;;EAOA;;EAEA;;IAEE;;IAEA;;;;;;UAOa;;EAEf,WAAW;;EAEX;IACE;IACA;IACA;IACA;IACA;;;;;;;;;EASF,UAAU;;EAEV;;EAEA;IAAgB,QAAQ;;;EAExB,SAAS;;EAET;IAAQ;IAAc;IAAiB;;;;;;;;;;;;;;;;;;;;;;;cA8B5B;UACH;UACA;UACA;UACA;UACA;UACA;UACA;UACA;mBACS;EAEL,YAAA,QAAQ;;;;EAsBd,QAAQ,OAAO,eAAe,QAAQ;;;;;;EA4FtC,WAAW,OAAO,eAAe;IACrC,QAAQ;IACR;;;;;EAmBF;EAIM,aAAa,OAAO,oBAAoB;;iBAoFhC,uBACd,SAAS,QAAQ,6BAChB;;;;iBAgBa"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { DetectionDetail, EnforcementAction, EngineInfo } from "@kya-os/checkpoint-shared";
|
|
2
|
+
import { BrowserSessionRequest } from "@kya-os/checkpoint-shared/browser-session";
|
|
2
3
|
//#region src/api-client.d.ts
|
|
3
4
|
/**
|
|
4
5
|
* API client configuration
|
|
@@ -21,6 +22,12 @@ interface CheckpointApiClientConfig {
|
|
|
21
22
|
debug?: boolean;
|
|
22
23
|
telemetryBatchSize?: number;
|
|
23
24
|
telemetryFlushIntervalMs?: number;
|
|
25
|
+
/**
|
|
26
|
+
* The beacon's session cookie name, when the project set another than
|
|
27
|
+
* `_as_beacon_session` (the beacon's `sessionCookieName`). Reports read the
|
|
28
|
+
* visit's session from it.
|
|
29
|
+
*/
|
|
30
|
+
sessionCookieName?: string;
|
|
24
31
|
}
|
|
25
32
|
/**
|
|
26
33
|
* Enforcement decision from the API
|
|
@@ -115,6 +122,13 @@ interface EnforceInput {
|
|
|
115
122
|
method?: string;
|
|
116
123
|
/** Request ID for tracing */
|
|
117
124
|
requestId?: string;
|
|
125
|
+
/**
|
|
126
|
+
* The visit's beacon session (`beaconSessionId` from
|
|
127
|
+
* `@kya-os/checkpoint-shared/browser-session`): the enforce endpoint stores
|
|
128
|
+
* it as the detection's session, so the row joins the beacon rows of the
|
|
129
|
+
* same visit. Without it the row gets a session of its own.
|
|
130
|
+
*/
|
|
131
|
+
browserSessionId?: string;
|
|
118
132
|
/** Options */
|
|
119
133
|
options?: {
|
|
120
134
|
/** Include full detection result */
|
|
@@ -137,6 +151,14 @@ interface LogDetectionInput {
|
|
|
137
151
|
url?: string;
|
|
138
152
|
method?: string;
|
|
139
153
|
};
|
|
154
|
+
/**
|
|
155
|
+
* The request's `KYA-Posture-Session` header, cookie and `Authorization`
|
|
156
|
+
* values (`browserSessionRequestFromHeaders`). The report's `context` then
|
|
157
|
+
* names the session they pick as `browserSessionId` (and `sessionSource`
|
|
158
|
+
* for a guest token's key), in the order every SDK uses: the header, then
|
|
159
|
+
* the session cookie, then a guest bearer token.
|
|
160
|
+
*/
|
|
161
|
+
session?: BrowserSessionRequest;
|
|
140
162
|
/** Source of the detection */
|
|
141
163
|
source?: 'gateway' | 'middleware';
|
|
142
164
|
/** The enforcement decision the caller received and acted on. */
|
|
@@ -181,6 +203,7 @@ declare class CheckpointApiClient {
|
|
|
181
203
|
private telemetryBatchSize;
|
|
182
204
|
private telemetryFlushIntervalMs;
|
|
183
205
|
private reportSender;
|
|
206
|
+
private readonly sessionPicker;
|
|
184
207
|
constructor(config: CheckpointApiClientConfig);
|
|
185
208
|
/**
|
|
186
209
|
* Call the enforce API to check if a request should be allowed
|
|
@@ -208,4 +231,4 @@ declare function getCheckpointApiClient(config?: Partial<CheckpointApiClientConf
|
|
|
208
231
|
declare function resetCheckpointApiClient(): void;
|
|
209
232
|
//#endregion
|
|
210
233
|
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 };
|
|
211
|
-
//# sourceMappingURL=api-client-
|
|
234
|
+
//# sourceMappingURL=api-client-W9WPq82L.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-client-W9WPq82L.d.ts","names":[],"sources":["../src/api-client.ts"],"mappings":";;;;;;UAuBiB;;EAEf;;EAEA;;;;;;;EAOA;;EAEA;;EAEA;EACA;EACA;;;;;;EAMA;;;;;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;;;;;;;EAOA;;EAEA;;IAEE;;IAEA;;;;;;UAOa;;EAEf,WAAW;;EAEX;IACE;IACA;IACA;IACA;IACA;;;;;;;;;EASF,UAAU;;EAEV;;EAEA;IAAgB,QAAQ;;;EAExB,SAAS;;EAET;IAAQ;IAAc;IAAiB;;;;;;;;;;;;;;;;;;;;;;;cA8B5B;UACH;UACA;UACA;UACA;UACA;UACA;UACA;UACA;mBACS;EAEL,YAAA,QAAQ;;;;EAsBd,QAAQ,OAAO,eAAe,QAAQ;;;;;;EA4FtC,WAAW,OAAO,eAAe;IACrC,QAAQ;IACR;;;;;EAmBF;EAIM,aAAa,OAAO,oBAAoB;;iBAoFhC,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-CmNX_FHm.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-W9WPq82L.js";
|
|
2
2
|
export { ApiDetectionDetail, CheckpointApiClient, CheckpointApiClientConfig, EnforceInput, EnforceResponse, type EnforcementAction, EnforcementDecision, LogDetectionInput, getCheckpointApiClient, resetCheckpointApiClient };
|
package/dist/api-client.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
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_shared_browser_session = require("@kya-os/checkpoint-shared/browser-session");
|
|
3
4
|
let _kya_os_checkpoint_wasm_runtime_reporter = require("@kya-os/checkpoint-wasm-runtime/reporter");
|
|
4
5
|
|
|
5
6
|
//#region src/api-client.ts
|
|
@@ -41,6 +42,7 @@ var CheckpointApiClient = class {
|
|
|
41
42
|
telemetryBatchSize;
|
|
42
43
|
telemetryFlushIntervalMs;
|
|
43
44
|
reportSender;
|
|
45
|
+
sessionPicker;
|
|
44
46
|
constructor(config) {
|
|
45
47
|
if (!config.apiKey) throw new Error("Checkpoint API key is required");
|
|
46
48
|
this.apiKey = config.apiKey;
|
|
@@ -50,6 +52,10 @@ var CheckpointApiClient = class {
|
|
|
50
52
|
this.debug = config.debug || false;
|
|
51
53
|
this.telemetryBatchSize = config.telemetryBatchSize;
|
|
52
54
|
this.telemetryFlushIntervalMs = config.telemetryFlushIntervalMs;
|
|
55
|
+
this.sessionPicker = (0, _kya_os_checkpoint_shared_browser_session.makeBrowserSessionPicker)({
|
|
56
|
+
apiKey: config.apiKey,
|
|
57
|
+
sessionCookieName: config.sessionCookieName
|
|
58
|
+
});
|
|
53
59
|
}
|
|
54
60
|
/**
|
|
55
61
|
* Call the enforce API to check if a request should be allowed
|
|
@@ -143,6 +149,7 @@ var CheckpointApiClient = class {
|
|
|
143
149
|
telemetryFlushIntervalMs: this.telemetryFlushIntervalMs,
|
|
144
150
|
runtime: input.sdk?.runtime
|
|
145
151
|
});
|
|
152
|
+
const session = input.session ? await this.sessionPicker(input.session) : {};
|
|
146
153
|
await this.reportSender.send({
|
|
147
154
|
detection: {
|
|
148
155
|
isAgent: input.detection.isAgent,
|
|
@@ -154,7 +161,10 @@ var CheckpointApiClient = class {
|
|
|
154
161
|
reasons: input.detection.reasons,
|
|
155
162
|
detectionBasis: typeof input.detection.detectionBasis === "string" ? input.detection.detectionBasis : void 0
|
|
156
163
|
},
|
|
157
|
-
context:
|
|
164
|
+
context: {
|
|
165
|
+
...input.context,
|
|
166
|
+
...session
|
|
167
|
+
},
|
|
158
168
|
source: input.source || "gateway",
|
|
159
169
|
enforcement: input.enforcement,
|
|
160
170
|
engine: input.engine,
|
|
@@ -184,7 +194,8 @@ function resolveClientConfig(config) {
|
|
|
184
194
|
timeout: config?.timeout,
|
|
185
195
|
debug: config?.debug || process.env.CHECKPOINT_DEBUG === "true",
|
|
186
196
|
telemetryBatchSize: config?.telemetryBatchSize,
|
|
187
|
-
telemetryFlushIntervalMs: config?.telemetryFlushIntervalMs
|
|
197
|
+
telemetryFlushIntervalMs: config?.telemetryFlushIntervalMs,
|
|
198
|
+
sessionCookieName: config?.sessionCookieName
|
|
188
199
|
};
|
|
189
200
|
}
|
|
190
201
|
function clientCacheKey(config) {
|
|
@@ -195,7 +206,8 @@ function clientCacheKey(config) {
|
|
|
195
206
|
config.timeout ?? DEFAULT_TIMEOUT,
|
|
196
207
|
config.debug,
|
|
197
208
|
config.telemetryBatchSize ?? null,
|
|
198
|
-
config.telemetryFlushIntervalMs ?? null
|
|
209
|
+
config.telemetryFlushIntervalMs ?? null,
|
|
210
|
+
config.sessionCookieName ?? null
|
|
199
211
|
]);
|
|
200
212
|
}
|
|
201
213
|
function getCheckpointApiClient(config) {
|
package/dist/api-client.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { n as relayHeaders } from "./utils-
|
|
1
|
+
import { n as relayHeaders } from "./utils-DK9HXCUV.mjs";
|
|
2
|
+
import { makeBrowserSessionPicker } from "@kya-os/checkpoint-shared/browser-session";
|
|
2
3
|
import { makeReportSender } from "@kya-os/checkpoint-wasm-runtime/reporter";
|
|
3
4
|
|
|
4
5
|
//#region src/api-client.ts
|
|
@@ -40,6 +41,7 @@ var CheckpointApiClient = class {
|
|
|
40
41
|
telemetryBatchSize;
|
|
41
42
|
telemetryFlushIntervalMs;
|
|
42
43
|
reportSender;
|
|
44
|
+
sessionPicker;
|
|
43
45
|
constructor(config) {
|
|
44
46
|
if (!config.apiKey) throw new Error("Checkpoint API key is required");
|
|
45
47
|
this.apiKey = config.apiKey;
|
|
@@ -49,6 +51,10 @@ var CheckpointApiClient = class {
|
|
|
49
51
|
this.debug = config.debug || false;
|
|
50
52
|
this.telemetryBatchSize = config.telemetryBatchSize;
|
|
51
53
|
this.telemetryFlushIntervalMs = config.telemetryFlushIntervalMs;
|
|
54
|
+
this.sessionPicker = makeBrowserSessionPicker({
|
|
55
|
+
apiKey: config.apiKey,
|
|
56
|
+
sessionCookieName: config.sessionCookieName
|
|
57
|
+
});
|
|
52
58
|
}
|
|
53
59
|
/**
|
|
54
60
|
* Call the enforce API to check if a request should be allowed
|
|
@@ -142,6 +148,7 @@ var CheckpointApiClient = class {
|
|
|
142
148
|
telemetryFlushIntervalMs: this.telemetryFlushIntervalMs,
|
|
143
149
|
runtime: input.sdk?.runtime
|
|
144
150
|
});
|
|
151
|
+
const session = input.session ? await this.sessionPicker(input.session) : {};
|
|
145
152
|
await this.reportSender.send({
|
|
146
153
|
detection: {
|
|
147
154
|
isAgent: input.detection.isAgent,
|
|
@@ -153,7 +160,10 @@ var CheckpointApiClient = class {
|
|
|
153
160
|
reasons: input.detection.reasons,
|
|
154
161
|
detectionBasis: typeof input.detection.detectionBasis === "string" ? input.detection.detectionBasis : void 0
|
|
155
162
|
},
|
|
156
|
-
context:
|
|
163
|
+
context: {
|
|
164
|
+
...input.context,
|
|
165
|
+
...session
|
|
166
|
+
},
|
|
157
167
|
source: input.source || "gateway",
|
|
158
168
|
enforcement: input.enforcement,
|
|
159
169
|
engine: input.engine,
|
|
@@ -183,7 +193,8 @@ function resolveClientConfig(config) {
|
|
|
183
193
|
timeout: config?.timeout,
|
|
184
194
|
debug: config?.debug || process.env.CHECKPOINT_DEBUG === "true",
|
|
185
195
|
telemetryBatchSize: config?.telemetryBatchSize,
|
|
186
|
-
telemetryFlushIntervalMs: config?.telemetryFlushIntervalMs
|
|
196
|
+
telemetryFlushIntervalMs: config?.telemetryFlushIntervalMs,
|
|
197
|
+
sessionCookieName: config?.sessionCookieName
|
|
187
198
|
};
|
|
188
199
|
}
|
|
189
200
|
function clientCacheKey(config) {
|
|
@@ -194,7 +205,8 @@ function clientCacheKey(config) {
|
|
|
194
205
|
config.timeout ?? DEFAULT_TIMEOUT,
|
|
195
206
|
config.debug,
|
|
196
207
|
config.telemetryBatchSize ?? null,
|
|
197
|
-
config.telemetryFlushIntervalMs ?? null
|
|
208
|
+
config.telemetryFlushIntervalMs ?? null,
|
|
209
|
+
config.sessionCookieName ?? null
|
|
198
210
|
]);
|
|
199
211
|
}
|
|
200
212
|
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 { 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,qBAAqB,OAAO;EACjC,KAAK,2BAA2B,OAAO;CACzC;;;;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,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,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 {\n makeBrowserSessionPicker,\n type BrowserSessionPicker,\n type BrowserSessionRequest,\n} from '@kya-os/checkpoint-shared/browser-session';\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 * The beacon's session cookie name, when the project set another than\n * `_as_beacon_session` (the beacon's `sessionCookieName`). Reports read the\n * visit's session from it.\n */\n sessionCookieName?: string;\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 /**\n * The visit's beacon session (`beaconSessionId` from\n * `@kya-os/checkpoint-shared/browser-session`): the enforce endpoint stores\n * it as the detection's session, so the row joins the beacon rows of the\n * same visit. Without it the row gets a session of its own.\n */\n browserSessionId?: 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 /**\n * The request's `KYA-Posture-Session` header, cookie and `Authorization`\n * values (`browserSessionRequestFromHeaders`). The report's `context` then\n * names the session they pick as `browserSessionId` (and `sessionSource`\n * for a guest token's key), in the order every SDK uses: the header, then\n * the session cookie, then a guest bearer token.\n */\n session?: BrowserSessionRequest;\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 private readonly sessionPicker: BrowserSessionPicker;\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 this.sessionPicker = makeBrowserSessionPicker({\n apiKey: config.apiKey,\n sessionCookieName: config.sessionCookieName,\n });\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 const session = input.session ? await this.sessionPicker(input.session) : {};\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, ...session },\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 sessionCookieName: config?.sessionCookieName,\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 config.sessionCookieName ?? 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 resetCheckpointApiCl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iBAAiB,IAAI,oBAAoB,cAAc;EACvD,gBAAgB,IAAI,KAAK,cAAc;CACzC;CAEA,OAAO;AACT;;;;AAKA,SAAgB,2BAAiC;CAC/C,gBAAgB,MAAM;AACxB"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
const require_adapt = require('./adapt-D2-OBY9M.js');
|
|
2
|
-
const require_utils = require('./utils-
|
|
2
|
+
const require_utils = require('./utils-CdoAQaFy.js');
|
|
3
3
|
const require_api_client = require('./api-client.js');
|
|
4
4
|
let _vercel_functions = require("@vercel/functions");
|
|
5
5
|
let next_server_js = require("next/server.js");
|
|
6
6
|
let _kya_os_checkpoint_shared_host_adapter = require("@kya-os/checkpoint-shared/host-adapter");
|
|
7
7
|
let _kya_os_checkpoint_shared_policy_enforcement = require("@kya-os/checkpoint-shared/policy/enforcement");
|
|
8
8
|
let _kya_os_checkpoint_shared_kya_http = require("@kya-os/checkpoint-shared/kya-http");
|
|
9
|
+
let _kya_os_checkpoint_shared_browser_session = require("@kya-os/checkpoint-shared/browser-session");
|
|
9
10
|
|
|
10
11
|
//#region src/responses/agent-instruction.ts
|
|
11
12
|
/**
|
|
@@ -96,7 +97,7 @@ function buildAgentInstructionResponse(request, decision, redirectUrl, options)
|
|
|
96
97
|
response.headers.set("KYA-Auth-Url", authUrl);
|
|
97
98
|
response.headers.set("KYA-Action", "instruct");
|
|
98
99
|
response.headers.set("KYA-Detected-Agent", agentName);
|
|
99
|
-
response.headers
|
|
100
|
+
require_utils.setConfidenceHeader(response.headers, decision.confidence);
|
|
100
101
|
response.headers.set("Cache-Control", "no-store");
|
|
101
102
|
return response;
|
|
102
103
|
}
|
|
@@ -177,7 +178,7 @@ function sdkSelfIdentification() {
|
|
|
177
178
|
const runtime = typeof process !== "undefined" && process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
|
|
178
179
|
return {
|
|
179
180
|
name: SDK_NAME,
|
|
180
|
-
version: "1.
|
|
181
|
+
version: "1.16.0",
|
|
181
182
|
runtime
|
|
182
183
|
};
|
|
183
184
|
}
|
|
@@ -281,7 +282,8 @@ function withCheckpointApi(config = {}) {
|
|
|
281
282
|
timeout: config.timeout,
|
|
282
283
|
debug: config.debug,
|
|
283
284
|
telemetryBatchSize: config.telemetryBatchSize,
|
|
284
|
-
telemetryFlushIntervalMs: config.telemetryFlushIntervalMs
|
|
285
|
+
telemetryFlushIntervalMs: config.telemetryFlushIntervalMs,
|
|
286
|
+
sessionCookieName: config.sessionCookieName
|
|
285
287
|
});
|
|
286
288
|
return client;
|
|
287
289
|
};
|
|
@@ -302,6 +304,7 @@ function withCheckpointApi(config = {}) {
|
|
|
302
304
|
const client = getClient();
|
|
303
305
|
const userAgent = request.headers.get("user-agent") || void 0;
|
|
304
306
|
const ipAddress = require_utils.getClientIp(request, config.clientIpPolicy);
|
|
307
|
+
const session = (0, _kya_os_checkpoint_shared_browser_session.browserSessionRequestFromHeaders)((name) => request.headers.get(name));
|
|
305
308
|
const result = await client.enforce({
|
|
306
309
|
headers: Object.fromEntries(request.headers.entries()),
|
|
307
310
|
userAgent,
|
|
@@ -310,6 +313,7 @@ function withCheckpointApi(config = {}) {
|
|
|
310
313
|
url: request.url,
|
|
311
314
|
method: request.method,
|
|
312
315
|
requestId: request.headers.get("x-request-id") || void 0,
|
|
316
|
+
browserSessionId: (0, _kya_os_checkpoint_shared_browser_session.beaconSessionId)(session, config.sessionCookieName),
|
|
313
317
|
options: { includeDetectionResult: true }
|
|
314
318
|
});
|
|
315
319
|
if (!result.success || !result.data) {
|
|
@@ -335,6 +339,7 @@ function withCheckpointApi(config = {}) {
|
|
|
335
339
|
url: request.url,
|
|
336
340
|
method: request.method
|
|
337
341
|
},
|
|
342
|
+
session,
|
|
338
343
|
source: "middleware",
|
|
339
344
|
enforcement: { action: decision.action },
|
|
340
345
|
engine: result.data.engine ? remoteEngineInfo(result.data.engine) : void 0,
|
|
@@ -366,7 +371,7 @@ function withCheckpointApi(config = {}) {
|
|
|
366
371
|
const response = next_server_js.NextResponse.next();
|
|
367
372
|
if (decision.isAgent) {
|
|
368
373
|
response.headers.set("KYA-Detected", "true");
|
|
369
|
-
response.headers
|
|
374
|
+
require_utils.setConfidenceHeader(response.headers, decision.confidence);
|
|
370
375
|
if (decision.agentName) response.headers.set("KYA-Agent", decision.agentName);
|
|
371
376
|
}
|
|
372
377
|
return response;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { s as EnforcementDecision } from "./api-client-
|
|
1
|
+
import { s as EnforcementDecision } from "./api-client-CmNX_FHm.mjs";
|
|
2
2
|
import { NextRequest, NextResponse } from "next/server.js";
|
|
3
3
|
import { ChallengeEnvelopeMode } from "@kya-os/checkpoint-shared/host-adapter";
|
|
4
4
|
import { ClientIpTrustPolicy } from "@kya-os/checkpoint-shared/client-ip";
|
|
@@ -112,6 +112,12 @@ interface CheckpointApiMiddlewareConfig {
|
|
|
112
112
|
debug?: boolean;
|
|
113
113
|
telemetryBatchSize?: number;
|
|
114
114
|
telemetryFlushIntervalMs?: number;
|
|
115
|
+
/**
|
|
116
|
+
* The beacon's session cookie name, when the project set another than
|
|
117
|
+
* `_as_beacon_session` (the beacon's `sessionCookieName`). Reports read the
|
|
118
|
+
* visit's session from it.
|
|
119
|
+
*/
|
|
120
|
+
sessionCookieName?: string;
|
|
115
121
|
}
|
|
116
122
|
/**
|
|
117
123
|
* Create Checkpoint middleware with API-based detection
|
|
@@ -130,4 +136,4 @@ interface CheckpointApiMiddlewareConfig {
|
|
|
130
136
|
declare function withCheckpointApi(config?: CheckpointApiMiddlewareConfig): (request: NextRequest) => Promise<NextResponse>;
|
|
131
137
|
//#endregion
|
|
132
138
|
export { withCheckpointApi as n, CheckpointApiMiddlewareConfig as t };
|
|
133
|
-
//# sourceMappingURL=api-middleware-
|
|
139
|
+
//# sourceMappingURL=api-middleware-D-djCzbx.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-middleware-
|
|
1
|
+
{"version":3,"file":"api-middleware-D-djCzbx.d.mts","names":[],"sources":["../src/api-middleware.ts"],"mappings":";;;;;;;;UAgFiB;;EAEf,iBAAiB;;EAEjB;;;;;;;EAOA;;;;;;;;EAQA;;;;;;EAMA;;;;;;;;EASA;;;;;EAMA;;;;;;;;;;;;;EAcA;;;;;;;;;;EAWA,0BAA0B;;;;;;EAO1B;IACE;IACA;IACA,UAAU;;;;;;EAOZ;;;;EAKA;;;;EAKA,mBAAmB,SAAS,aAAa,UAAU,+BAA+B;;;;EAKlF,yBACE,SAAS,aACT,UAAU,wBACP,eAAe,QAAQ;;;;;;;;;EAU5B;;;;;;EAOA;EACA;EACA;;;;;;EAMA;;;;;;;;;;;;;;;;iBA2Mc,kBAAkB,SAAQ,iCAgDP,SAAS,gBAAc,QAAQ"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { n as failClosedResponse } from "./adapt-BGEyLf44.mjs";
|
|
2
|
-
import { r as safeHostname, t as getClientIp } from "./utils-
|
|
2
|
+
import { i as setConfidenceHeader, r as safeHostname, t as getClientIp } from "./utils-DK9HXCUV.mjs";
|
|
3
3
|
import { getCheckpointApiClient } from "./api-client.mjs";
|
|
4
4
|
import { waitUntil } from "@vercel/functions";
|
|
5
5
|
import { NextResponse } from "next/server.js";
|
|
6
6
|
import { selectBodyReadable200 } from "@kya-os/checkpoint-shared/host-adapter";
|
|
7
7
|
import { matchPath } from "@kya-os/checkpoint-shared/policy/enforcement";
|
|
8
8
|
import { requestPresentedCredential } from "@kya-os/checkpoint-shared/kya-http";
|
|
9
|
+
import { beaconSessionId, browserSessionRequestFromHeaders } from "@kya-os/checkpoint-shared/browser-session";
|
|
9
10
|
|
|
10
11
|
//#region src/responses/agent-instruction.ts
|
|
11
12
|
/**
|
|
@@ -96,7 +97,7 @@ function buildAgentInstructionResponse(request, decision, redirectUrl, options)
|
|
|
96
97
|
response.headers.set("KYA-Auth-Url", authUrl);
|
|
97
98
|
response.headers.set("KYA-Action", "instruct");
|
|
98
99
|
response.headers.set("KYA-Detected-Agent", agentName);
|
|
99
|
-
response.headers
|
|
100
|
+
setConfidenceHeader(response.headers, decision.confidence);
|
|
100
101
|
response.headers.set("Cache-Control", "no-store");
|
|
101
102
|
return response;
|
|
102
103
|
}
|
|
@@ -177,7 +178,7 @@ function sdkSelfIdentification() {
|
|
|
177
178
|
const runtime = typeof process !== "undefined" && process.env.NEXT_RUNTIME === "edge" ? "edge" : "node";
|
|
178
179
|
return {
|
|
179
180
|
name: SDK_NAME,
|
|
180
|
-
version: "1.
|
|
181
|
+
version: "1.16.0",
|
|
181
182
|
runtime
|
|
182
183
|
};
|
|
183
184
|
}
|
|
@@ -281,7 +282,8 @@ function withCheckpointApi(config = {}) {
|
|
|
281
282
|
timeout: config.timeout,
|
|
282
283
|
debug: config.debug,
|
|
283
284
|
telemetryBatchSize: config.telemetryBatchSize,
|
|
284
|
-
telemetryFlushIntervalMs: config.telemetryFlushIntervalMs
|
|
285
|
+
telemetryFlushIntervalMs: config.telemetryFlushIntervalMs,
|
|
286
|
+
sessionCookieName: config.sessionCookieName
|
|
285
287
|
});
|
|
286
288
|
return client;
|
|
287
289
|
};
|
|
@@ -302,6 +304,7 @@ function withCheckpointApi(config = {}) {
|
|
|
302
304
|
const client = getClient();
|
|
303
305
|
const userAgent = request.headers.get("user-agent") || void 0;
|
|
304
306
|
const ipAddress = getClientIp(request, config.clientIpPolicy);
|
|
307
|
+
const session = browserSessionRequestFromHeaders((name) => request.headers.get(name));
|
|
305
308
|
const result = await client.enforce({
|
|
306
309
|
headers: Object.fromEntries(request.headers.entries()),
|
|
307
310
|
userAgent,
|
|
@@ -310,6 +313,7 @@ function withCheckpointApi(config = {}) {
|
|
|
310
313
|
url: request.url,
|
|
311
314
|
method: request.method,
|
|
312
315
|
requestId: request.headers.get("x-request-id") || void 0,
|
|
316
|
+
browserSessionId: beaconSessionId(session, config.sessionCookieName),
|
|
313
317
|
options: { includeDetectionResult: true }
|
|
314
318
|
});
|
|
315
319
|
if (!result.success || !result.data) {
|
|
@@ -335,6 +339,7 @@ function withCheckpointApi(config = {}) {
|
|
|
335
339
|
url: request.url,
|
|
336
340
|
method: request.method
|
|
337
341
|
},
|
|
342
|
+
session,
|
|
338
343
|
source: "middleware",
|
|
339
344
|
enforcement: { action: decision.action },
|
|
340
345
|
engine: result.data.engine ? remoteEngineInfo(result.data.engine) : void 0,
|
|
@@ -366,7 +371,7 @@ function withCheckpointApi(config = {}) {
|
|
|
366
371
|
const response = NextResponse.next();
|
|
367
372
|
if (decision.isAgent) {
|
|
368
373
|
response.headers.set("KYA-Detected", "true");
|
|
369
|
-
response.headers
|
|
374
|
+
setConfidenceHeader(response.headers, decision.confidence);
|
|
370
375
|
if (decision.agentName) response.headers.set("KYA-Agent", decision.agentName);
|
|
371
376
|
}
|
|
372
377
|
return response;
|
|
@@ -386,4 +391,4 @@ function failOpenResponse() {
|
|
|
386
391
|
|
|
387
392
|
//#endregion
|
|
388
393
|
export { withCheckpointApi as t };
|
|
389
|
-
//# sourceMappingURL=api-middleware-
|
|
394
|
+
//# sourceMappingURL=api-middleware-GEmIPBLq.mjs.map
|