@kya-os/checkpoint-nextjs 1.15.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.
Files changed (67) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/README.md +23 -0
  3. package/dist/{api-client-yjr43Itz.d.ts → api-client-CmNX_FHm.d.mts} +24 -1
  4. package/dist/api-client-CmNX_FHm.d.mts.map +1 -0
  5. package/dist/{api-client-yjr43Itz.d.mts → api-client-W9WPq82L.d.ts} +24 -1
  6. package/dist/api-client-W9WPq82L.d.ts.map +1 -0
  7. package/dist/api-client.d.mts +1 -1
  8. package/dist/api-client.d.ts +1 -1
  9. package/dist/api-client.js +15 -3
  10. package/dist/api-client.mjs +15 -3
  11. package/dist/api-client.mjs.map +1 -1
  12. package/dist/{api-middleware-Bcu8f06W.js → api-middleware-CAN0gnw-.js} +7 -2
  13. package/dist/{api-middleware-CIXuGurw.d.mts → api-middleware-D-djCzbx.d.mts} +8 -2
  14. package/dist/{api-middleware-CIXuGurw.d.mts.map → api-middleware-D-djCzbx.d.mts.map} +1 -1
  15. package/dist/{api-middleware-xhlisoi2.mjs → api-middleware-GEmIPBLq.mjs} +8 -3
  16. package/dist/api-middleware-GEmIPBLq.mjs.map +1 -0
  17. package/dist/{api-middleware-CpAbnkfa.d.ts → api-middleware-n1aAWNoQ.d.ts} +8 -2
  18. package/dist/{api-middleware-CpAbnkfa.d.ts.map → api-middleware-n1aAWNoQ.d.ts.map} +1 -1
  19. package/dist/api-middleware.d.mts +1 -1
  20. package/dist/api-middleware.d.ts +1 -1
  21. package/dist/api-middleware.js +1 -1
  22. package/dist/api-middleware.mjs +1 -1
  23. package/dist/index-edge.d.mts +5 -5
  24. package/dist/index-edge.d.ts +5 -5
  25. package/dist/index-edge.js +3 -3
  26. package/dist/index-edge.mjs +3 -3
  27. package/dist/index.d.mts +5 -5
  28. package/dist/index.d.ts +5 -5
  29. package/dist/index.js +3 -3
  30. package/dist/index.mjs +3 -3
  31. package/dist/middleware-bundler.js +1 -1
  32. package/dist/middleware-bundler.mjs +1 -1
  33. package/dist/{middleware-core-yE25rSJE.js → middleware-core-BPLmDNjf.js} +1 -1
  34. package/dist/{middleware-core-B70g9yLE.d.mts → middleware-core-Cd4fdQog.d.mts} +2 -2
  35. package/dist/middleware-core-Cd4fdQog.d.mts.map +1 -0
  36. package/dist/{middleware-core-qXSvMDYw.mjs → middleware-core-CkKHnNgF.mjs} +2 -2
  37. package/dist/{middleware-core-qXSvMDYw.mjs.map → middleware-core-CkKHnNgF.mjs.map} +1 -1
  38. package/dist/{middleware-core-DH6kGKc8.d.ts → middleware-core-D6EpfMLW.d.ts} +2 -2
  39. package/dist/middleware-core-D6EpfMLW.d.ts.map +1 -0
  40. package/dist/middleware-edge.d.mts +1 -1
  41. package/dist/middleware-edge.d.ts +1 -1
  42. package/dist/middleware-edge.js +2 -2
  43. package/dist/middleware-edge.mjs +2 -2
  44. package/dist/middleware-node.d.mts +1 -1
  45. package/dist/middleware-node.d.ts +1 -1
  46. package/dist/middleware-node.js +1 -1
  47. package/dist/middleware-node.mjs +1 -1
  48. package/dist/{posture-outcome-CN1WranD.mjs → posture-outcome-BecgUc_x.mjs} +9 -2
  49. package/dist/posture-outcome-BecgUc_x.mjs.map +1 -0
  50. package/dist/{posture-outcome-3mJLVX85.js → posture-outcome-BtVin59Q.js} +8 -1
  51. package/dist/{posture-outcome-Ccujx_9V.d.mts → posture-outcome-DFkDKHVS.d.mts} +6 -3
  52. package/dist/posture-outcome-DFkDKHVS.d.mts.map +1 -0
  53. package/dist/{posture-outcome-Ccujx_9V.d.ts → posture-outcome-DFkDKHVS.d.ts} +6 -3
  54. package/dist/posture-outcome-DFkDKHVS.d.ts.map +1 -0
  55. package/dist/public-api-CcTZtETe.d.ts +5 -0
  56. package/dist/public-api-JV2lXjAr.d.mts +5 -0
  57. package/package.json +3 -3
  58. package/dist/api-client-yjr43Itz.d.mts.map +0 -1
  59. package/dist/api-client-yjr43Itz.d.ts.map +0 -1
  60. package/dist/api-middleware-xhlisoi2.mjs.map +0 -1
  61. package/dist/middleware-core-B70g9yLE.d.mts.map +0 -1
  62. package/dist/middleware-core-DH6kGKc8.d.ts.map +0 -1
  63. package/dist/posture-outcome-CN1WranD.mjs.map +0 -1
  64. package/dist/posture-outcome-Ccujx_9V.d.mts.map +0 -1
  65. package/dist/posture-outcome-Ccujx_9V.d.ts.map +0 -1
  66. package/dist/public-api-CAJ9XPJC.d.mts +0 -5
  67. package/dist/public-api-D5so-53z.d.ts +0 -5
package/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
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
+
5
14
  ## 1.15.0 - 2026-11-19
6
15
 
7
16
  ### Added
@@ -538,7 +547,7 @@ Node and Edge runtimes ship byte-equivalent payloads to
538
547
  opened in 1.1.2 via PR #2610 / AgentDetector-Deletion-1. Per project
539
548
  semver policy this is shipped as a minor bump (not a major) because:
540
549
  (a) the deprecation landed yesterday and was effectively one calendar
541
- day, (b) the package is pre-Adobe-trial with no external pins to
550
+ day, (b) the package is pre-customer-trial with no external pins to
542
551
  `^1.x.0`, and (c) the workspace-wide deletion-gate test pins the absence
543
552
  structurally so re-introduction is mechanically blocked.
544
553
 
package/README.md CHANGED
@@ -169,6 +169,29 @@ export default function middleware(request: NextRequest, event: NextFetchEvent)
169
169
 
170
170
  Without an event, it falls back to `waitUntil` from `@vercel/functions`, which only has an effect on Vercel.
171
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
+
172
195
  ## Installation
173
196
 
174
197
  ```bash
@@ -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-yjr43Itz.d.ts.map
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-yjr43Itz.d.mts.map
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"}
@@ -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-yjr43Itz.mjs";
1
+ import { a as EnforceResponse, c as LogDetectionInput, i as EnforceInput, l as getCheckpointApiClient, n as CheckpointApiClient, o as EnforcementAction, r as CheckpointApiClientConfig, s as EnforcementDecision, t as ApiDetectionDetail, u as resetCheckpointApiClient } from "./api-client-CmNX_FHm.mjs";
2
2
  export { ApiDetectionDetail, CheckpointApiClient, CheckpointApiClientConfig, EnforceInput, EnforceResponse, type EnforcementAction, EnforcementDecision, LogDetectionInput, getCheckpointApiClient, resetCheckpointApiClient };
@@ -1,2 +1,2 @@
1
- import { a as EnforceResponse, c as LogDetectionInput, i as EnforceInput, l as getCheckpointApiClient, n as CheckpointApiClient, o as EnforcementAction, r as CheckpointApiClientConfig, s as EnforcementDecision, t as ApiDetectionDetail, u as resetCheckpointApiClient } from "./api-client-yjr43Itz.js";
1
+ import { a as EnforceResponse, c as LogDetectionInput, i as EnforceInput, l as getCheckpointApiClient, n as CheckpointApiClient, o as EnforcementAction, r as CheckpointApiClientConfig, s as EnforcementDecision, t as ApiDetectionDetail, u as resetCheckpointApiClient } from "./api-client-W9WPq82L.js";
2
2
  export { ApiDetectionDetail, CheckpointApiClient, CheckpointApiClientConfig, EnforceInput, EnforceResponse, type EnforcementAction, EnforcementDecision, LogDetectionInput, getCheckpointApiClient, resetCheckpointApiClient };
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
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: input.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) {
@@ -1,4 +1,5 @@
1
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: input.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) {
@@ -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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,UAAU;GACxB,aAAa,MAAM;GACnB,QAAQ,MAAM;GACd,KAAK,MAAM;EACb,CAAC;CACH;AACF;;;;;;;;;;;;AAaA,MAAM,kCAAkB,IAAI,IAAiC;AAE7D,SAAS,oBACP,QAC2B;CAC3B,MAAM,SAAS,QAAQ,UAAU,QAAQ,IAAI;CAE7C,IAAI,CAAC,QACH,MAAM,IAAI,MACR,uGACF;CAGF,OAAO;EACL;EACA,SAAS,QAAQ,WAAW,QAAQ,IAAI;EAExC,SAAS,QAAQ,WAAW,QAAQ,IAAI,wBAAwB;EAChE,SAAS,QAAQ;EACjB,OAAO,QAAQ,SAAS,QAAQ,IAAI,qBAAqB;EACzD,oBAAoB,QAAQ;EAC5B,0BAA0B,QAAQ;CACpC;AACF;AAEA,SAAS,eAAe,QAA2C;CACjE,OAAO,KAAK,UAAU;EACpB,OAAO;EACP,OAAO,WAAW;EAClB,OAAO;EACP,OAAO,WAAW;EAClB,OAAO;EACP,OAAO,sBAAsB;EAC7B,OAAO,4BAA4B;CACrC,CAAC;AACH;AAEA,SAAgB,uBACd,QACqB;CACrB,MAAM,iBAAiB,oBAAoB,MAAM;CACjD,MAAM,MAAM,eAAe,cAAc;CACzC,IAAI,iBAAiB,gBAAgB,IAAI,GAAG;CAE5C,IAAI,CAAC,gBAAgB;EACnB,iBAAiB,IAAI,oBAAoB,cAAc;EACvD,gBAAgB,IAAI,KAAK,cAAc;CACzC;CAEA,OAAO;AACT;;;;AAKA,SAAgB,2BAAiC;CAC/C,gBAAgB,MAAM;AACxB"}
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 resetCheckpointApiClient(): void {\n clientInstances.clear();\n}\n"],"mappings":";;;;;;;;;;;AAkNA,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;CACR,AAAiB;CAEjB,YAAY,QAAmC;EAC7C,IAAI,CAAC,OAAO,QACV,MAAM,IAAI,MAAM,gCAAgC;EAGlD,KAAK,SAAS,OAAO;EAErB,KAAK,UAAU,OAAO,YAAY;EAClC,KA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MAAM;GACd,KAAK,MAAM;EACb,CAAC;CACH;AACF;;;;;;;;;;;;AAaA,MAAM,kCAAkB,IAAI,IAAiC;AAE7D,SAAS,oBACP,QAC2B;CAC3B,MAAM,SAAS,QAAQ,UAAU,QAAQ,IAAI;CAE7C,IAAI,CAAC,QACH,MAAM,IAAI,MACR,uGACF;CAGF,OAAO;EACL;EACA,SAAS,QAAQ,WAAW,QAAQ,IAAI;EAExC,SAAS,QAAQ,WAAW,QAAQ,IAAI,wBAAwB;EAChE,SAAS,QAAQ;EACjB,OAAO,QAAQ,SAAS,QAAQ,IAAI,qBAAqB;EACzD,oBAAoB,QAAQ;EAC5B,0BAA0B,QAAQ;EAClC,mBAAmB,QAAQ;CAC7B;AACF;AAEA,SAAS,eAAe,QAA2C;CACjE,OAAO,KAAK,UAAU;EACpB,OAAO;EACP,OAAO,WAAW;EAClB,OAAO;EACP,OAAO,WAAW;EAClB,OAAO;EACP,OAAO,sBAAsB;EAC7B,OAAO,4BAA4B;EACnC,OAAO,qBAAqB;CAC9B,CAAC;AACH;AAEA,SAAgB,uBACd,QACqB;CACrB,MAAM,iBAAiB,oBAAoB,MAAM;CACjD,MAAM,MAAM,eAAe,cAAc;CACzC,IAAI,iBAAiB,gBAAgB,IAAI,GAAG;CAE5C,IAAI,CAAC,gBAAgB;EACnB,iBAAiB,IAAI,oBAAoB,cAAc;EACvD,gBAAgB,IAAI,KAAK,cAAc;CACzC;CAEA,OAAO;AACT;;;;AAKA,SAAgB,2BAAiC;CAC/C,gBAAgB,MAAM;AACxB"}
@@ -6,6 +6,7 @@ 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
  /**
@@ -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.15.0",
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,
@@ -1,4 +1,4 @@
1
- import { s as EnforcementDecision } from "./api-client-yjr43Itz.mjs";
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-CIXuGurw.d.mts.map
139
+ //# sourceMappingURL=api-middleware-D-djCzbx.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"api-middleware-CIXuGurw.d.mts","names":[],"sources":["../src/api-middleware.ts"],"mappings":";;;;;;;;UA4EiB;;EAEf,iBAAiB;;EAEjB;;;;;;;EAOA;;;;;;;;EAQA;;;;;;EAMA;;;;;;;;EASA;;;;;EAMA;;;;;;;;;;;;;EAcA;;;;;;;;;;EAWA,0BAA0B;;;;;;EAO1B;IACE;IACA;IACA,UAAU;;;;;;EAOZ;;;;EAKA;;;;EAKA,mBAAmB,SAAS,aAAa,UAAU,+BAA+B;;;;EAKlF,yBACE,SAAS,aACT,UAAU,wBACP,eAAe,QAAQ;;;;;;;;;EAU5B;;;;;;EAOA;EACA;EACA;;;;;;;;;;;;;;;;iBA2Mc,kBAAkB,SAAQ,iCA+CP,SAAS,gBAAc,QAAQ"}
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"}
@@ -6,6 +6,7 @@ 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
  /**
@@ -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.15.0",
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,
@@ -386,4 +391,4 @@ function failOpenResponse() {
386
391
 
387
392
  //#endregion
388
393
  export { withCheckpointApi as t };
389
- //# sourceMappingURL=api-middleware-xhlisoi2.mjs.map
394
+ //# sourceMappingURL=api-middleware-GEmIPBLq.mjs.map