@reopt-ai/data-contract 0.6.2 → 0.6.3
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/dist/{chunk-FMOKJTQD.js → chunk-7W33YGRO.js} +2 -2
- package/dist/chunk-7W33YGRO.js.map +1 -0
- package/dist/{chunk-AOS53KAV.cjs → chunk-F2RNXJGO.cjs} +2 -2
- package/dist/{chunk-AOS53KAV.cjs.map → chunk-F2RNXJGO.cjs.map} +1 -1
- package/dist/{chunk-33BCA2LH.js → chunk-JCEWUSUM.js} +1 -1
- package/dist/{chunk-33BCA2LH.js.map → chunk-JCEWUSUM.js.map} +1 -1
- package/dist/{chunk-FQSCQSMP.cjs → chunk-L3JPDRVG.cjs} +3 -3
- package/dist/chunk-L3JPDRVG.cjs.map +1 -0
- package/dist/{chunk-IY4MXH35.js → chunk-L4KBQAOO.js} +3 -3
- package/dist/{chunk-L3WJGIKD.js → chunk-NJ4JKNBX.js} +2 -2
- package/dist/{chunk-YSAEOYPD.cjs → chunk-ORNTN6AK.cjs} +1 -1
- package/dist/{chunk-YSAEOYPD.cjs.map → chunk-ORNTN6AK.cjs.map} +1 -1
- package/dist/{chunk-ZCKVMUIQ.js → chunk-PSUINLW7.js} +2 -2
- package/dist/{chunk-ZCKVMUIQ.js.map → chunk-PSUINLW7.js.map} +1 -1
- package/dist/{chunk-DUJSYMYY.js → chunk-RU26QFM2.js} +2 -2
- package/dist/{chunk-FUGY5ANJ.cjs → chunk-XDH5QQYF.cjs} +13 -13
- package/dist/{chunk-FUGY5ANJ.cjs.map → chunk-XDH5QQYF.cjs.map} +1 -1
- package/dist/{chunk-LA5F5KR6.cjs → chunk-YCTGHWTP.cjs} +6 -6
- package/dist/{chunk-LA5F5KR6.cjs.map → chunk-YCTGHWTP.cjs.map} +1 -1
- package/dist/{chunk-BA52YA7N.cjs → chunk-ZI6A3WQP.cjs} +4 -4
- package/dist/{chunk-BA52YA7N.cjs.map → chunk-ZI6A3WQP.cjs.map} +1 -1
- package/dist/client.cjs +51 -51
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +10 -10
- package/dist/client.d.ts +10 -10
- package/dist/client.js +6 -6
- package/dist/client.js.map +1 -1
- package/dist/control.cjs +5 -5
- package/dist/control.d.cts +6 -6
- package/dist/control.d.ts +6 -6
- package/dist/control.js +4 -4
- package/dist/identity.cjs +3 -3
- package/dist/identity.d.cts +3 -3
- package/dist/identity.d.ts +3 -3
- package/dist/identity.js +2 -2
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +2 -2
- package/dist/ingest.cjs +4 -4
- package/dist/ingest.d.cts +6 -6
- package/dist/ingest.d.ts +6 -6
- package/dist/ingest.js +3 -3
- package/dist/query.cjs +4 -4
- package/dist/query.d.cts +5 -5
- package/dist/query.d.ts +5 -5
- package/dist/query.js +3 -3
- package/dist/{version-BANKB6Og.d.ts → version-DJ2Grb_N.d.cts} +1 -1
- package/dist/{version-BANKB6Og.d.cts → version-DJ2Grb_N.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-FMOKJTQD.js.map +0 -1
- package/dist/chunk-FQSCQSMP.cjs.map +0 -1
- /package/dist/{chunk-IY4MXH35.js.map → chunk-L4KBQAOO.js.map} +0 -0
- /package/dist/{chunk-L3WJGIKD.js.map → chunk-NJ4JKNBX.js.map} +0 -0
- /package/dist/{chunk-DUJSYMYY.js.map → chunk-RU26QFM2.js.map} +0 -0
package/dist/ingest.d.cts
CHANGED
|
@@ -264,33 +264,33 @@ declare function reconcileIngestResponse(response: IngestResponse, sentCount: nu
|
|
|
264
264
|
*/
|
|
265
265
|
declare const INGEST_ERROR_CODES: readonly ["unauthorized", "invalid_json", "payload_too_large", "empty_batch", "alias_unsupported", "project_without_organization", "validation_failed", "rate_limited", "quota_exceeded", "project_purging", "internal_error"];
|
|
266
266
|
declare const zIngestErrorCode: z.ZodEnum<{
|
|
267
|
-
unauthorized: "unauthorized";
|
|
268
267
|
validation_failed: "validation_failed";
|
|
269
|
-
|
|
270
|
-
internal_error: "internal_error";
|
|
268
|
+
unauthorized: "unauthorized";
|
|
271
269
|
invalid_json: "invalid_json";
|
|
272
270
|
payload_too_large: "payload_too_large";
|
|
273
271
|
empty_batch: "empty_batch";
|
|
274
272
|
alias_unsupported: "alias_unsupported";
|
|
275
273
|
project_without_organization: "project_without_organization";
|
|
274
|
+
rate_limited: "rate_limited";
|
|
276
275
|
quota_exceeded: "quota_exceeded";
|
|
277
276
|
project_purging: "project_purging";
|
|
277
|
+
internal_error: "internal_error";
|
|
278
278
|
}>;
|
|
279
279
|
type IngestErrorCode = z.infer<typeof zIngestErrorCode>;
|
|
280
280
|
declare const zIngestError: z.ZodObject<{
|
|
281
281
|
status: z.ZodNumber;
|
|
282
282
|
code: z.ZodEnum<{
|
|
283
|
-
unauthorized: "unauthorized";
|
|
284
283
|
validation_failed: "validation_failed";
|
|
285
|
-
|
|
286
|
-
internal_error: "internal_error";
|
|
284
|
+
unauthorized: "unauthorized";
|
|
287
285
|
invalid_json: "invalid_json";
|
|
288
286
|
payload_too_large: "payload_too_large";
|
|
289
287
|
empty_batch: "empty_batch";
|
|
290
288
|
alias_unsupported: "alias_unsupported";
|
|
291
289
|
project_without_organization: "project_without_organization";
|
|
290
|
+
rate_limited: "rate_limited";
|
|
292
291
|
quota_exceeded: "quota_exceeded";
|
|
293
292
|
project_purging: "project_purging";
|
|
293
|
+
internal_error: "internal_error";
|
|
294
294
|
}>;
|
|
295
295
|
error: z.ZodString;
|
|
296
296
|
message: z.ZodOptional<z.ZodString>;
|
package/dist/ingest.d.ts
CHANGED
|
@@ -264,33 +264,33 @@ declare function reconcileIngestResponse(response: IngestResponse, sentCount: nu
|
|
|
264
264
|
*/
|
|
265
265
|
declare const INGEST_ERROR_CODES: readonly ["unauthorized", "invalid_json", "payload_too_large", "empty_batch", "alias_unsupported", "project_without_organization", "validation_failed", "rate_limited", "quota_exceeded", "project_purging", "internal_error"];
|
|
266
266
|
declare const zIngestErrorCode: z.ZodEnum<{
|
|
267
|
-
unauthorized: "unauthorized";
|
|
268
267
|
validation_failed: "validation_failed";
|
|
269
|
-
|
|
270
|
-
internal_error: "internal_error";
|
|
268
|
+
unauthorized: "unauthorized";
|
|
271
269
|
invalid_json: "invalid_json";
|
|
272
270
|
payload_too_large: "payload_too_large";
|
|
273
271
|
empty_batch: "empty_batch";
|
|
274
272
|
alias_unsupported: "alias_unsupported";
|
|
275
273
|
project_without_organization: "project_without_organization";
|
|
274
|
+
rate_limited: "rate_limited";
|
|
276
275
|
quota_exceeded: "quota_exceeded";
|
|
277
276
|
project_purging: "project_purging";
|
|
277
|
+
internal_error: "internal_error";
|
|
278
278
|
}>;
|
|
279
279
|
type IngestErrorCode = z.infer<typeof zIngestErrorCode>;
|
|
280
280
|
declare const zIngestError: z.ZodObject<{
|
|
281
281
|
status: z.ZodNumber;
|
|
282
282
|
code: z.ZodEnum<{
|
|
283
|
-
unauthorized: "unauthorized";
|
|
284
283
|
validation_failed: "validation_failed";
|
|
285
|
-
|
|
286
|
-
internal_error: "internal_error";
|
|
284
|
+
unauthorized: "unauthorized";
|
|
287
285
|
invalid_json: "invalid_json";
|
|
288
286
|
payload_too_large: "payload_too_large";
|
|
289
287
|
empty_batch: "empty_batch";
|
|
290
288
|
alias_unsupported: "alias_unsupported";
|
|
291
289
|
project_without_organization: "project_without_organization";
|
|
290
|
+
rate_limited: "rate_limited";
|
|
292
291
|
quota_exceeded: "quota_exceeded";
|
|
293
292
|
project_purging: "project_purging";
|
|
293
|
+
internal_error: "internal_error";
|
|
294
294
|
}>;
|
|
295
295
|
error: z.ZodString;
|
|
296
296
|
message: z.ZodOptional<z.ZodString>;
|
package/dist/ingest.js
CHANGED
|
@@ -18,9 +18,9 @@ import {
|
|
|
18
18
|
zSessionCredential,
|
|
19
19
|
zTrackHandlerPayload,
|
|
20
20
|
zTrackPayload
|
|
21
|
-
} from "./chunk-
|
|
22
|
-
import "./chunk-
|
|
23
|
-
import "./chunk-
|
|
21
|
+
} from "./chunk-RU26QFM2.js";
|
|
22
|
+
import "./chunk-7W33YGRO.js";
|
|
23
|
+
import "./chunk-PSUINLW7.js";
|
|
24
24
|
import {
|
|
25
25
|
AUTO_EVENT_NAMES,
|
|
26
26
|
AUTO_EVENT_PROPERTIES,
|
package/dist/query.cjs
CHANGED
|
@@ -36,12 +36,12 @@
|
|
|
36
36
|
|
|
37
37
|
|
|
38
38
|
|
|
39
|
-
var
|
|
39
|
+
var _chunkXDH5QQYFcjs = require('./chunk-XDH5QQYF.cjs');
|
|
40
40
|
|
|
41
41
|
|
|
42
42
|
|
|
43
|
-
var
|
|
44
|
-
require('./chunk-
|
|
43
|
+
var _chunkORNTN6AKcjs = require('./chunk-ORNTN6AK.cjs');
|
|
44
|
+
require('./chunk-F2RNXJGO.cjs');
|
|
45
45
|
|
|
46
46
|
|
|
47
47
|
|
|
@@ -82,5 +82,5 @@ require('./chunk-AOS53KAV.cjs');
|
|
|
82
82
|
|
|
83
83
|
|
|
84
84
|
|
|
85
|
-
exports.QUERY_API_PATHS =
|
|
85
|
+
exports.QUERY_API_PATHS = _chunkXDH5QQYFcjs.QUERY_API_PATHS; exports.QUERY_ERROR_CODES = _chunkXDH5QQYFcjs.QUERY_ERROR_CODES; exports.isValidTimeZone = _chunkXDH5QQYFcjs.isValidTimeZone; exports.zBucketStart = _chunkXDH5QQYFcjs.zBucketStart; exports.zChannelFilter = _chunkXDH5QQYFcjs.zChannelFilter; exports.zDate = _chunkORNTN6AKcjs.zDate; exports.zEventPropertyFilter = _chunkXDH5QQYFcjs.zEventPropertyFilter; exports.zEventsTimeseriesData = _chunkXDH5QQYFcjs.zEventsTimeseriesData; exports.zEventsTimeseriesInput = _chunkXDH5QQYFcjs.zEventsTimeseriesInput; exports.zEventsTimeseriesResponse = _chunkXDH5QQYFcjs.zEventsTimeseriesResponse; exports.zFunnelData = _chunkXDH5QQYFcjs.zFunnelData; exports.zFunnelInput = _chunkXDH5QQYFcjs.zFunnelInput; exports.zFunnelResponse = _chunkXDH5QQYFcjs.zFunnelResponse; exports.zFunnelStep = _chunkXDH5QQYFcjs.zFunnelStep; exports.zGranularity = _chunkXDH5QQYFcjs.zGranularity; exports.zInstant = _chunkORNTN6AKcjs.zInstant; exports.zQueryEnvelope = _chunkXDH5QQYFcjs.zQueryEnvelope; exports.zQueryError = _chunkXDH5QQYFcjs.zQueryError; exports.zQueryErrorCode = _chunkXDH5QQYFcjs.zQueryErrorCode; exports.zQueryMeta = _chunkXDH5QQYFcjs.zQueryMeta; exports.zQuerySource = _chunkXDH5QQYFcjs.zQuerySource; exports.zRetentionCell = _chunkXDH5QQYFcjs.zRetentionCell; exports.zRetentionData = _chunkXDH5QQYFcjs.zRetentionData; exports.zRetentionInput = _chunkXDH5QQYFcjs.zRetentionInput; exports.zRetentionInterval = _chunkXDH5QQYFcjs.zRetentionInterval; exports.zRetentionResponse = _chunkXDH5QQYFcjs.zRetentionResponse; exports.zTimeseriesBreakdown = _chunkXDH5QQYFcjs.zTimeseriesBreakdown; exports.zTimeseriesPoint = _chunkXDH5QQYFcjs.zTimeseriesPoint; exports.zTimezone = _chunkXDH5QQYFcjs.zTimezone; exports.zTrafficDimension = _chunkXDH5QQYFcjs.zTrafficDimension; exports.zTrafficOverviewData = _chunkXDH5QQYFcjs.zTrafficOverviewData; exports.zTrafficOverviewInput = _chunkXDH5QQYFcjs.zTrafficOverviewInput; exports.zTrafficOverviewResponse = _chunkXDH5QQYFcjs.zTrafficOverviewResponse; exports.zTrafficSeriesPoint = _chunkXDH5QQYFcjs.zTrafficSeriesPoint; exports.zTrafficSourceRow = _chunkXDH5QQYFcjs.zTrafficSourceRow; exports.zTrafficSourcesData = _chunkXDH5QQYFcjs.zTrafficSourcesData; exports.zTrafficSourcesInput = _chunkXDH5QQYFcjs.zTrafficSourcesInput; exports.zTrafficSourcesResponse = _chunkXDH5QQYFcjs.zTrafficSourcesResponse; exports.zTrafficTotals = _chunkXDH5QQYFcjs.zTrafficTotals;
|
|
86
86
|
//# sourceMappingURL=query.cjs.map
|
package/dist/query.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
export { zDate, zInstant } from './index.cjs';
|
|
3
|
-
import './version-
|
|
3
|
+
import './version-DJ2Grb_N.cjs';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* `POST /api/v1/query/*` — the read contract.
|
|
@@ -629,11 +629,11 @@ declare const zTrafficSourcesResponse: z.ZodObject<{
|
|
|
629
629
|
type TrafficSourcesResponse = z.infer<typeof zTrafficSourcesResponse>;
|
|
630
630
|
declare const QUERY_ERROR_CODES: readonly ["unauthorized", "project_scope_mismatch", "query_scope_missing", "validation_failed", "unsupported_combination", "project_purging", "rate_limited", "query_timeout", "internal_error"];
|
|
631
631
|
declare const zQueryErrorCode: z.ZodEnum<{
|
|
632
|
-
unauthorized: "unauthorized";
|
|
633
632
|
validation_failed: "validation_failed";
|
|
633
|
+
unauthorized: "unauthorized";
|
|
634
634
|
rate_limited: "rate_limited";
|
|
635
|
-
internal_error: "internal_error";
|
|
636
635
|
project_purging: "project_purging";
|
|
636
|
+
internal_error: "internal_error";
|
|
637
637
|
project_scope_mismatch: "project_scope_mismatch";
|
|
638
638
|
query_scope_missing: "query_scope_missing";
|
|
639
639
|
unsupported_combination: "unsupported_combination";
|
|
@@ -643,11 +643,11 @@ type QueryErrorCode = z.infer<typeof zQueryErrorCode>;
|
|
|
643
643
|
declare const zQueryError: z.ZodObject<{
|
|
644
644
|
status: z.ZodNumber;
|
|
645
645
|
code: z.ZodEnum<{
|
|
646
|
-
unauthorized: "unauthorized";
|
|
647
646
|
validation_failed: "validation_failed";
|
|
647
|
+
unauthorized: "unauthorized";
|
|
648
648
|
rate_limited: "rate_limited";
|
|
649
|
-
internal_error: "internal_error";
|
|
650
649
|
project_purging: "project_purging";
|
|
650
|
+
internal_error: "internal_error";
|
|
651
651
|
project_scope_mismatch: "project_scope_mismatch";
|
|
652
652
|
query_scope_missing: "query_scope_missing";
|
|
653
653
|
unsupported_combination: "unsupported_combination";
|
package/dist/query.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
export { zDate, zInstant } from './index.js';
|
|
3
|
-
import './version-
|
|
3
|
+
import './version-DJ2Grb_N.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* `POST /api/v1/query/*` — the read contract.
|
|
@@ -629,11 +629,11 @@ declare const zTrafficSourcesResponse: z.ZodObject<{
|
|
|
629
629
|
type TrafficSourcesResponse = z.infer<typeof zTrafficSourcesResponse>;
|
|
630
630
|
declare const QUERY_ERROR_CODES: readonly ["unauthorized", "project_scope_mismatch", "query_scope_missing", "validation_failed", "unsupported_combination", "project_purging", "rate_limited", "query_timeout", "internal_error"];
|
|
631
631
|
declare const zQueryErrorCode: z.ZodEnum<{
|
|
632
|
-
unauthorized: "unauthorized";
|
|
633
632
|
validation_failed: "validation_failed";
|
|
633
|
+
unauthorized: "unauthorized";
|
|
634
634
|
rate_limited: "rate_limited";
|
|
635
|
-
internal_error: "internal_error";
|
|
636
635
|
project_purging: "project_purging";
|
|
636
|
+
internal_error: "internal_error";
|
|
637
637
|
project_scope_mismatch: "project_scope_mismatch";
|
|
638
638
|
query_scope_missing: "query_scope_missing";
|
|
639
639
|
unsupported_combination: "unsupported_combination";
|
|
@@ -643,11 +643,11 @@ type QueryErrorCode = z.infer<typeof zQueryErrorCode>;
|
|
|
643
643
|
declare const zQueryError: z.ZodObject<{
|
|
644
644
|
status: z.ZodNumber;
|
|
645
645
|
code: z.ZodEnum<{
|
|
646
|
-
unauthorized: "unauthorized";
|
|
647
646
|
validation_failed: "validation_failed";
|
|
647
|
+
unauthorized: "unauthorized";
|
|
648
648
|
rate_limited: "rate_limited";
|
|
649
|
-
internal_error: "internal_error";
|
|
650
649
|
project_purging: "project_purging";
|
|
650
|
+
internal_error: "internal_error";
|
|
651
651
|
project_scope_mismatch: "project_scope_mismatch";
|
|
652
652
|
query_scope_missing: "query_scope_missing";
|
|
653
653
|
unsupported_combination: "unsupported_combination";
|
package/dist/query.js
CHANGED
|
@@ -36,12 +36,12 @@ import {
|
|
|
36
36
|
zTrafficSourcesInput,
|
|
37
37
|
zTrafficSourcesResponse,
|
|
38
38
|
zTrafficTotals
|
|
39
|
-
} from "./chunk-
|
|
39
|
+
} from "./chunk-NJ4JKNBX.js";
|
|
40
40
|
import {
|
|
41
41
|
zDate,
|
|
42
42
|
zInstant
|
|
43
|
-
} from "./chunk-
|
|
44
|
-
import "./chunk-
|
|
43
|
+
} from "./chunk-JCEWUSUM.js";
|
|
44
|
+
import "./chunk-PSUINLW7.js";
|
|
45
45
|
export {
|
|
46
46
|
QUERY_API_PATHS,
|
|
47
47
|
QUERY_ERROR_CODES,
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* every publish is a wire bump: consumers that check for exact equality —
|
|
14
14
|
* every SDK — must upgrade in lockstep with the server.
|
|
15
15
|
*/
|
|
16
|
-
declare const CONTRACT_VERSION = "0.6.
|
|
16
|
+
declare const CONTRACT_VERSION = "0.6.3";
|
|
17
17
|
/** Response header carrying the server's contract version. */
|
|
18
18
|
declare const CONTRACT_VERSION_HEADER = "x-reopt-contract-version";
|
|
19
19
|
/** Request header names shared by the ingest and query planes. */
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* every publish is a wire bump: consumers that check for exact equality —
|
|
14
14
|
* every SDK — must upgrade in lockstep with the server.
|
|
15
15
|
*/
|
|
16
|
-
declare const CONTRACT_VERSION = "0.6.
|
|
16
|
+
declare const CONTRACT_VERSION = "0.6.3";
|
|
17
17
|
/** Response header carrying the server's contract version. */
|
|
18
18
|
declare const CONTRACT_VERSION_HEADER = "x-reopt-contract-version";
|
|
19
19
|
/** Request header names shared by the ingest and query planes. */
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/identity.ts"],"sourcesContent":["/**\n * `@reopt-ai/data-contract/identity` — the names and encodings that carry a\n * visitor's identity between the browser SDK, the server SDK, the Next.js\n * proxy and the ingest pipeline.\n *\n * Every one of those parties reads or writes the same cookies and headers.\n * None of them depends on another (ingest does not import the SDKs), so this\n * module is the only place a name may be spelled out. A party that hardcodes\n * `reopt_<key>_device` instead of calling `deviceCookieName()` fails silently:\n * the browser sets one cookie, the server looks for another, and every\n * visitor is counted as new. `packages/db/src/__tests__/redis-namespace.test.ts`\n * guards Redis key prefixes for exactly the same reason.\n *\n * Nothing here touches `document`, `fetch` or Node built-ins — it runs in\n * browsers, edge runtimes and Node alike.\n */\nimport { DEVICE_ID_HEADER } from \"./version.js\";\n\nexport {\n CLIENT_ID_HEADER,\n CLIENT_SECRET_HEADER,\n CONTRACT_VERSION,\n CONTRACT_VERSION_HEADER,\n DEVICE_ID_HEADER,\n REQUEST_ID_HEADER,\n WRITE_KEY_HEADER,\n} from \"./version.js\";\n\n/**\n * Request header carrying the browser's current session id. The browser SDK\n * adds it to same-origin requests so a server-side `track()` can land in the\n * session the user is actually in; the server SDK forwards it to ingest.\n *\n * Ingest treats it as a *hint*, never as authority — a browser can put any\n * value here.\n */\nexport const SESSION_ID_HEADER = \"reopt-session-id\";\n\n/** Every request header the identity protocol may carry, for CORS allow-lists. */\nexport const IDENTITY_REQUEST_HEADERS = [DEVICE_ID_HEADER, SESSION_ID_HEADER] as const;\n\n/**\n * 400 days — the longest lifetime Chrome will honour. Anything longer is\n * silently clamped to this, so asking for more only hides the real expiry.\n */\nexport const COOKIE_MAX_AGE_SECONDS = 400 * 24 * 60 * 60;\n\n/** Consent category whose refusal means \"send nothing at all\". */\nexport const OPT_OUT_CONSENT_CATEGORY = \"analytics\";\n\nconst COOKIE_PREFIX = \"reopt_\";\n\n/**\n * Cookie names may not contain separators (`=`, `;`, `,`, whitespace) or\n * control characters. A write key is opaque to us, so anything outside the\n * safe set is folded to `_` — deterministically, so both ends agree.\n */\nfunction cookieSafe(writeKey: string): string {\n if (!writeKey) {\n throw new Error(\"[reopt] writeKey is required to derive cookie names\");\n }\n return writeKey.replace(/[^A-Za-z0-9_-]/g, \"_\");\n}\n\n/**\n * `reopt_<writeKey>_device` — device id plus session/profile hints.\n *\n * The write key is **sanitized**: any character outside `[A-Za-z0-9_-]`\n * becomes `_` (see `cookieSafe`), so do not derive prefix/suffix pieces by\n * probing this with a marker character — the marker is folded too. Always\n * call this with the real write key and compare whole names.\n */\nexport function deviceCookieName(writeKey: string): string {\n return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_device`;\n}\n\n/** `reopt_<writeKey>_consent` — per-category consent decisions. Same sanitizing as `deviceCookieName`. */\nexport function consentCookieName(writeKey: string): string {\n return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_consent`;\n}\n\n/** Everything the device cookie may carry. Only `deviceId` is required. */\nexport interface DeviceCookieState {\n deviceId: string;\n /** Current session, if the browser has one. */\n sessionId?: string;\n /** Last identified profile. A hint for the server SDK, never trusted by ingest. */\n profileId?: string;\n}\n\n/** Per-category consent. `false` withdraws, `true` grants, absent = undecided. */\nexport type ConsentCookieState = Record<string, boolean>;\n\n/**\n * What the server hands the browser SDK so the first render already agrees\n * with the server about who the visitor is. Plain JSON — it crosses the\n * RSC → client component boundary as a prop.\n */\nexport interface ReoptBootstrap {\n /** From the device cookie (seeded by the proxy on first visit). */\n deviceId: string;\n /** Session hint, or `null` when the browser has not started one. */\n sessionId: string | null;\n /** Result of the server's `getProfileId` resolver, or `null`. */\n profileId: string | null;\n consent: ConsentCookieState;\n /** Server clock at render time, so a skewed device clock can be corrected. */\n serverTimeMs: number;\n}\n\n/**\n * Ids are opaque, but a cookie is attacker-controlled input (a sibling\n * subdomain can set one). The value ends up in an HTTP header, and\n * `Headers.set` throws on anything outside ISO-8859-1 — so a single odd\n * cookie would break every `fetch` the tracing patch touches. Only the URL\n * \"unreserved\" set is accepted; every id this SDK mints is a UUID.\n */\nexport const IDENTITY_ID_PATTERN = /^[A-Za-z0-9._~-]{1,200}$/;\n\nexport function isValidIdentityId(value: unknown): value is string {\n return typeof value === \"string\" && IDENTITY_ID_PATTERN.test(value);\n}\n\n/**\n * Decodes the envelope. Tolerates one extra layer (`%257B…`) — a cookie\n * setter that encodes an already-encoded value is a mistake we have shipped\n * once, and a visitor's identity should survive it rather than be reminted.\n */\nfunction decode(raw: string): string {\n let text = raw;\n for (let round = 0; round < 3 && /%[0-9A-Fa-f]{2}/.test(text); round++) {\n try {\n const next = decodeURIComponent(text);\n if (next === text) break;\n text = next;\n } catch {\n break;\n }\n if (text.startsWith(\"{\")) break;\n }\n return text;\n}\n\n/**\n * Reads a device cookie value. Accepts the JSON envelope written by\n * `serializeDeviceCookie` and, for cookies seeded before the envelope existed,\n * a bare device id. Returns `null` for anything else — a malformed cookie is\n * treated as absent, never as an error, so a corrupted value cannot take the\n * page down.\n */\nexport function parseDeviceCookie(raw: string | null | undefined): DeviceCookieState | null {\n if (!raw) return null;\n const text = decode(raw.trim());\n if (!text) return null;\n\n if (!text.startsWith(\"{\")) {\n return isValidIdentityId(text) ? { deviceId: text } : null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null) return null;\n\n const candidate = parsed as Record<string, unknown>;\n if (!isValidIdentityId(candidate.deviceId)) return null;\n\n const state: DeviceCookieState = { deviceId: candidate.deviceId };\n if (isValidIdentityId(candidate.sessionId)) state.sessionId = candidate.sessionId;\n if (isValidIdentityId(candidate.profileId)) state.profileId = candidate.profileId;\n return state;\n}\n\n/**\n * Cookie values may not contain `;`, `,` or whitespace, and JSON contains\n * quotes and commas. The envelope is therefore URI-encoded; `parseDeviceCookie`\n * reverses it. Optional fields are omitted rather than written as `null` so\n * the cookie stays as small as the state it carries.\n */\nexport function serializeDeviceCookie(state: DeviceCookieState): string {\n if (!isValidIdentityId(state.deviceId)) {\n throw new Error(\"[reopt] deviceId must be a non-empty string without control characters\");\n }\n const envelope: DeviceCookieState = { deviceId: state.deviceId };\n if (isValidIdentityId(state.sessionId)) envelope.sessionId = state.sessionId;\n if (isValidIdentityId(state.profileId)) envelope.profileId = state.profileId;\n return encodeURIComponent(JSON.stringify(envelope));\n}\n\n/**\n * Reads a consent cookie. Only boolean entries survive; anything else in the\n * object is dropped rather than failing the whole cookie, because one odd key\n * must not erase a user's recorded opt-out.\n */\nexport function parseConsentCookie(raw: string | null | undefined): ConsentCookieState | null {\n if (!raw) return null;\n const text = decode(raw.trim());\n if (!text.startsWith(\"{\")) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return null;\n\n const state: ConsentCookieState = {};\n for (const [category, decision] of Object.entries(parsed as Record<string, unknown>)) {\n if (typeof decision === \"boolean\" && isValidIdentityId(category)) {\n state[category] = decision;\n }\n }\n return state;\n}\n\nexport function serializeConsentCookie(state: ConsentCookieState): string {\n const clean: ConsentCookieState = {};\n for (const [category, decision] of Object.entries(state)) {\n if (typeof decision === \"boolean\" && isValidIdentityId(category)) {\n clean[category] = decision;\n }\n }\n return encodeURIComponent(JSON.stringify(clean));\n}\n\n/**\n * \"Opted out\" means the visitor refused the `analytics` category. An absent\n * cookie or an undecided category is *not* an opt-out — it is the default\n * state of every first visit, and treating it as refusal would make consent\n * banners mandatory for every integration.\n */\nexport function isOptedOut(consent: ConsentCookieState | null | undefined): boolean {\n return consent?.[OPT_OUT_CONSENT_CATEGORY] === false;\n}\n\n// ─── Session tokens ───────────────────────────────────────────────────────────\n\n/**\n * Sessions are assigned by ingest, not by the browser. To let a later request\n * — from the same browser, or from a server acting for it — join that session\n * with authority, ingest hands the browser its session id together with an\n * HMAC over it, and the browser sends both back as `reopt-session-id`. An\n * unsigned or wrongly signed value is a hint at most: ingest falls back to\n * deciding the session from the device, exactly as if the header were absent.\n *\n * The token is `base64url(HMAC-SHA256(secret, sessionId))`. The secret is\n * per project and never leaves the server. WebCrypto only, so this runs in\n * browsers, edge runtimes and Node alike.\n */\nexport const SESSION_HEADER_SEPARATOR = \".\";\n\nexport interface SessionCredential {\n id: string;\n token: string;\n}\n\n/** `<id>.<token>` — what travels in `reopt-session-id`. */\nexport function formatSessionHeader(credential: SessionCredential): string {\n return `${credential.id}${SESSION_HEADER_SEPARATOR}${credential.token}`;\n}\n\n/** Splits a `reopt-session-id` value. `null` unless both parts are well-formed. */\nexport function parseSessionHeader(value: string | null | undefined): SessionCredential | null {\n if (!value) return null;\n const at = value.lastIndexOf(SESSION_HEADER_SEPARATOR);\n if (at <= 0 || at === value.length - 1) return null;\n const id = value.slice(0, at);\n const token = value.slice(at + 1);\n return isValidIdentityId(id) && /^[A-Za-z0-9_-]{43}$/.test(token) ? { id, token } : null;\n}\n\nconst encoder = new TextEncoder();\n\nfunction base64url(bytes: ArrayBuffer): string {\n let binary = \"\";\n for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);\n const b64 = typeof btoa === \"function\" ? btoa(binary) : Buffer.from(binary, \"binary\").toString(\"base64\");\n return b64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function hmacKey(secret: string): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n}\n\n/** Issues the token for `sessionId`. Server-side only — needs the project secret. */\nexport async function signSessionToken(secret: string, sessionId: string): Promise<string> {\n if (!secret) throw new Error(\"[reopt] a session signing secret is required\");\n const signature = await crypto.subtle.sign(\"HMAC\", await hmacKey(secret), encoder.encode(sessionId));\n return base64url(signature);\n}\n\n/**\n * Constant-time check of a presented token. Recomputes and compares the\n * digests byte by byte rather than using `subtle.verify` with a decoded\n * token, so a malformed token can never throw its way past the check.\n */\nexport async function verifySessionToken(secret: string, credential: SessionCredential): Promise<boolean> {\n if (!secret || !credential) return false;\n const expected = await signSessionToken(secret, credential.id);\n if (expected.length !== credential.token.length) return false;\n let diff = 0;\n for (let index = 0; index < expected.length; index++) {\n diff |= expected.charCodeAt(index) ^ credential.token.charCodeAt(index);\n }\n return diff === 0;\n}\n"],"mappings":";;;;;AAoCO,IAAM,oBAAoB;AAG1B,IAAM,2BAA2B,CAAC,kBAAkB,iBAAiB;AAMrE,IAAM,yBAAyB,MAAM,KAAK,KAAK;AAG/C,IAAM,2BAA2B;AAExC,IAAM,gBAAgB;AAOtB,SAAS,WAAW,UAA0B;AAC5C,MAAI,CAAC,UAAU;AACb,UAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE;AACA,SAAO,SAAS,QAAQ,mBAAmB,GAAG;AAChD;AAUO,SAAS,iBAAiB,UAA0B;AACzD,SAAO,GAAG,aAAa,GAAG,WAAW,QAAQ,CAAC;AAChD;AAGO,SAAS,kBAAkB,UAA0B;AAC1D,SAAO,GAAG,aAAa,GAAG,WAAW,QAAQ,CAAC;AAChD;AAsCO,IAAM,sBAAsB;AAE5B,SAAS,kBAAkB,OAAiC;AACjE,SAAO,OAAO,UAAU,YAAY,oBAAoB,KAAK,KAAK;AACpE;AAOA,SAAS,OAAO,KAAqB;AACnC,MAAI,OAAO;AACX,WAAS,QAAQ,GAAG,QAAQ,KAAK,kBAAkB,KAAK,IAAI,GAAG,SAAS;AACtE,QAAI;AACF,YAAM,OAAO,mBAAmB,IAAI;AACpC,UAAI,SAAS,KAAM;AACnB,aAAO;AAAA,IACT,QAAQ;AACN;AAAA,IACF;AACA,QAAI,KAAK,WAAW,GAAG,EAAG;AAAA,EAC5B;AACA,SAAO;AACT;AASO,SAAS,kBAAkB,KAA0D;AAC1F,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,OAAO,OAAO,IAAI,KAAK,CAAC;AAC9B,MAAI,CAAC,KAAM,QAAO;AAElB,MAAI,CAAC,KAAK,WAAW,GAAG,GAAG;AACzB,WAAO,kBAAkB,IAAI,IAAI,EAAE,UAAU,KAAK,IAAI;AAAA,EACxD;AAEA,MAA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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/eric/reopt-ai/reopt-data/packages/data-contract/dist/chunk-FQSCQSMP.cjs","sourcesContent":[null,"/**\n * `@reopt-ai/data-contract/identity` — the names and encodings that carry a\n * visitor's identity between the browser SDK, the server SDK, the Next.js\n * proxy and the ingest pipeline.\n *\n * Every one of those parties reads or writes the same cookies and headers.\n * None of them depends on another (ingest does not import the SDKs), so this\n * module is the only place a name may be spelled out. A party that hardcodes\n * `reopt_<key>_device` instead of calling `deviceCookieName()` fails silently:\n * the browser sets one cookie, the server looks for another, and every\n * visitor is counted as new. `packages/db/src/__tests__/redis-namespace.test.ts`\n * guards Redis key prefixes for exactly the same reason.\n *\n * Nothing here touches `document`, `fetch` or Node built-ins — it runs in\n * browsers, edge runtimes and Node alike.\n */\nimport { DEVICE_ID_HEADER } from \"./version.js\";\n\nexport {\n CLIENT_ID_HEADER,\n CLIENT_SECRET_HEADER,\n CONTRACT_VERSION,\n CONTRACT_VERSION_HEADER,\n DEVICE_ID_HEADER,\n REQUEST_ID_HEADER,\n WRITE_KEY_HEADER,\n} from \"./version.js\";\n\n/**\n * Request header carrying the browser's current session id. The browser SDK\n * adds it to same-origin requests so a server-side `track()` can land in the\n * session the user is actually in; the server SDK forwards it to ingest.\n *\n * Ingest treats it as a *hint*, never as authority — a browser can put any\n * value here.\n */\nexport const SESSION_ID_HEADER = \"reopt-session-id\";\n\n/** Every request header the identity protocol may carry, for CORS allow-lists. */\nexport const IDENTITY_REQUEST_HEADERS = [DEVICE_ID_HEADER, SESSION_ID_HEADER] as const;\n\n/**\n * 400 days — the longest lifetime Chrome will honour. Anything longer is\n * silently clamped to this, so asking for more only hides the real expiry.\n */\nexport const COOKIE_MAX_AGE_SECONDS = 400 * 24 * 60 * 60;\n\n/** Consent category whose refusal means \"send nothing at all\". */\nexport const OPT_OUT_CONSENT_CATEGORY = \"analytics\";\n\nconst COOKIE_PREFIX = \"reopt_\";\n\n/**\n * Cookie names may not contain separators (`=`, `;`, `,`, whitespace) or\n * control characters. A write key is opaque to us, so anything outside the\n * safe set is folded to `_` — deterministically, so both ends agree.\n */\nfunction cookieSafe(writeKey: string): string {\n if (!writeKey) {\n throw new Error(\"[reopt] writeKey is required to derive cookie names\");\n }\n return writeKey.replace(/[^A-Za-z0-9_-]/g, \"_\");\n}\n\n/**\n * `reopt_<writeKey>_device` — device id plus session/profile hints.\n *\n * The write key is **sanitized**: any character outside `[A-Za-z0-9_-]`\n * becomes `_` (see `cookieSafe`), so do not derive prefix/suffix pieces by\n * probing this with a marker character — the marker is folded too. Always\n * call this with the real write key and compare whole names.\n */\nexport function deviceCookieName(writeKey: string): string {\n return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_device`;\n}\n\n/** `reopt_<writeKey>_consent` — per-category consent decisions. Same sanitizing as `deviceCookieName`. */\nexport function consentCookieName(writeKey: string): string {\n return `${COOKIE_PREFIX}${cookieSafe(writeKey)}_consent`;\n}\n\n/** Everything the device cookie may carry. Only `deviceId` is required. */\nexport interface DeviceCookieState {\n deviceId: string;\n /** Current session, if the browser has one. */\n sessionId?: string;\n /** Last identified profile. A hint for the server SDK, never trusted by ingest. */\n profileId?: string;\n}\n\n/** Per-category consent. `false` withdraws, `true` grants, absent = undecided. */\nexport type ConsentCookieState = Record<string, boolean>;\n\n/**\n * What the server hands the browser SDK so the first render already agrees\n * with the server about who the visitor is. Plain JSON — it crosses the\n * RSC → client component boundary as a prop.\n */\nexport interface ReoptBootstrap {\n /** From the device cookie (seeded by the proxy on first visit). */\n deviceId: string;\n /** Session hint, or `null` when the browser has not started one. */\n sessionId: string | null;\n /** Result of the server's `getProfileId` resolver, or `null`. */\n profileId: string | null;\n consent: ConsentCookieState;\n /** Server clock at render time, so a skewed device clock can be corrected. */\n serverTimeMs: number;\n}\n\n/**\n * Ids are opaque, but a cookie is attacker-controlled input (a sibling\n * subdomain can set one). The value ends up in an HTTP header, and\n * `Headers.set` throws on anything outside ISO-8859-1 — so a single odd\n * cookie would break every `fetch` the tracing patch touches. Only the URL\n * \"unreserved\" set is accepted; every id this SDK mints is a UUID.\n */\nexport const IDENTITY_ID_PATTERN = /^[A-Za-z0-9._~-]{1,200}$/;\n\nexport function isValidIdentityId(value: unknown): value is string {\n return typeof value === \"string\" && IDENTITY_ID_PATTERN.test(value);\n}\n\n/**\n * Decodes the envelope. Tolerates one extra layer (`%257B…`) — a cookie\n * setter that encodes an already-encoded value is a mistake we have shipped\n * once, and a visitor's identity should survive it rather than be reminted.\n */\nfunction decode(raw: string): string {\n let text = raw;\n for (let round = 0; round < 3 && /%[0-9A-Fa-f]{2}/.test(text); round++) {\n try {\n const next = decodeURIComponent(text);\n if (next === text) break;\n text = next;\n } catch {\n break;\n }\n if (text.startsWith(\"{\")) break;\n }\n return text;\n}\n\n/**\n * Reads a device cookie value. Accepts the JSON envelope written by\n * `serializeDeviceCookie` and, for cookies seeded before the envelope existed,\n * a bare device id. Returns `null` for anything else — a malformed cookie is\n * treated as absent, never as an error, so a corrupted value cannot take the\n * page down.\n */\nexport function parseDeviceCookie(raw: string | null | undefined): DeviceCookieState | null {\n if (!raw) return null;\n const text = decode(raw.trim());\n if (!text) return null;\n\n if (!text.startsWith(\"{\")) {\n return isValidIdentityId(text) ? { deviceId: text } : null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null) return null;\n\n const candidate = parsed as Record<string, unknown>;\n if (!isValidIdentityId(candidate.deviceId)) return null;\n\n const state: DeviceCookieState = { deviceId: candidate.deviceId };\n if (isValidIdentityId(candidate.sessionId)) state.sessionId = candidate.sessionId;\n if (isValidIdentityId(candidate.profileId)) state.profileId = candidate.profileId;\n return state;\n}\n\n/**\n * Cookie values may not contain `;`, `,` or whitespace, and JSON contains\n * quotes and commas. The envelope is therefore URI-encoded; `parseDeviceCookie`\n * reverses it. Optional fields are omitted rather than written as `null` so\n * the cookie stays as small as the state it carries.\n */\nexport function serializeDeviceCookie(state: DeviceCookieState): string {\n if (!isValidIdentityId(state.deviceId)) {\n throw new Error(\"[reopt] deviceId must be a non-empty string without control characters\");\n }\n const envelope: DeviceCookieState = { deviceId: state.deviceId };\n if (isValidIdentityId(state.sessionId)) envelope.sessionId = state.sessionId;\n if (isValidIdentityId(state.profileId)) envelope.profileId = state.profileId;\n return encodeURIComponent(JSON.stringify(envelope));\n}\n\n/**\n * Reads a consent cookie. Only boolean entries survive; anything else in the\n * object is dropped rather than failing the whole cookie, because one odd key\n * must not erase a user's recorded opt-out.\n */\nexport function parseConsentCookie(raw: string | null | undefined): ConsentCookieState | null {\n if (!raw) return null;\n const text = decode(raw.trim());\n if (!text.startsWith(\"{\")) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return null;\n\n const state: ConsentCookieState = {};\n for (const [category, decision] of Object.entries(parsed as Record<string, unknown>)) {\n if (typeof decision === \"boolean\" && isValidIdentityId(category)) {\n state[category] = decision;\n }\n }\n return state;\n}\n\nexport function serializeConsentCookie(state: ConsentCookieState): string {\n const clean: ConsentCookieState = {};\n for (const [category, decision] of Object.entries(state)) {\n if (typeof decision === \"boolean\" && isValidIdentityId(category)) {\n clean[category] = decision;\n }\n }\n return encodeURIComponent(JSON.stringify(clean));\n}\n\n/**\n * \"Opted out\" means the visitor refused the `analytics` category. An absent\n * cookie or an undecided category is *not* an opt-out — it is the default\n * state of every first visit, and treating it as refusal would make consent\n * banners mandatory for every integration.\n */\nexport function isOptedOut(consent: ConsentCookieState | null | undefined): boolean {\n return consent?.[OPT_OUT_CONSENT_CATEGORY] === false;\n}\n\n// ─── Session tokens ───────────────────────────────────────────────────────────\n\n/**\n * Sessions are assigned by ingest, not by the browser. To let a later request\n * — from the same browser, or from a server acting for it — join that session\n * with authority, ingest hands the browser its session id together with an\n * HMAC over it, and the browser sends both back as `reopt-session-id`. An\n * unsigned or wrongly signed value is a hint at most: ingest falls back to\n * deciding the session from the device, exactly as if the header were absent.\n *\n * The token is `base64url(HMAC-SHA256(secret, sessionId))`. The secret is\n * per project and never leaves the server. WebCrypto only, so this runs in\n * browsers, edge runtimes and Node alike.\n */\nexport const SESSION_HEADER_SEPARATOR = \".\";\n\nexport interface SessionCredential {\n id: string;\n token: string;\n}\n\n/** `<id>.<token>` — what travels in `reopt-session-id`. */\nexport function formatSessionHeader(credential: SessionCredential): string {\n return `${credential.id}${SESSION_HEADER_SEPARATOR}${credential.token}`;\n}\n\n/** Splits a `reopt-session-id` value. `null` unless both parts are well-formed. */\nexport function parseSessionHeader(value: string | null | undefined): SessionCredential | null {\n if (!value) return null;\n const at = value.lastIndexOf(SESSION_HEADER_SEPARATOR);\n if (at <= 0 || at === value.length - 1) return null;\n const id = value.slice(0, at);\n const token = value.slice(at + 1);\n return isValidIdentityId(id) && /^[A-Za-z0-9_-]{43}$/.test(token) ? { id, token } : null;\n}\n\nconst encoder = new TextEncoder();\n\nfunction base64url(bytes: ArrayBuffer): string {\n let binary = \"\";\n for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);\n const b64 = typeof btoa === \"function\" ? btoa(binary) : Buffer.from(binary, \"binary\").toString(\"base64\");\n return b64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function hmacKey(secret: string): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n}\n\n/** Issues the token for `sessionId`. Server-side only — needs the project secret. */\nexport async function signSessionToken(secret: string, sessionId: string): Promise<string> {\n if (!secret) throw new Error(\"[reopt] a session signing secret is required\");\n const signature = await crypto.subtle.sign(\"HMAC\", await hmacKey(secret), encoder.encode(sessionId));\n return base64url(signature);\n}\n\n/**\n * Constant-time check of a presented token. Recomputes and compares the\n * digests byte by byte rather than using `subtle.verify` with a decoded\n * token, so a malformed token can never throw its way past the check.\n */\nexport async function verifySessionToken(secret: string, credential: SessionCredential): Promise<boolean> {\n if (!secret || !credential) return false;\n const expected = await signSessionToken(secret, credential.id);\n if (expected.length !== credential.token.length) return false;\n let diff = 0;\n for (let index = 0; index < expected.length; index++) {\n diff |= expected.charCodeAt(index) ^ credential.token.charCodeAt(index);\n }\n return diff === 0;\n}\n"]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|