@steadphast/connector-nextjs 0.6.0 → 0.7.1

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/index.js CHANGED
@@ -66,6 +66,57 @@ function missingApiKeyDiagnostic(customEnvVar) {
66
66
  return `Steadphast connector skipped event: no usable API key resolved from ${STEADPHAST_API_KEY_ENV_VAR} or deprecated fallback ${LEGACY_DISCOVER_API_KEY_ENV_VAR}. ${STEADPHAST_API_KEY_ENV_VAR} takes precedence when defined, even when blank.`;
67
67
  }
68
68
 
69
+ // ../connector-core/src/query.ts
70
+ var ENCODED_QUESTION_MARK = /%3f/i;
71
+ var ENCODED_PAIR_SEPARATOR = /&|%26/i;
72
+ var ENCODED_KEY_END = /=|%3d/i;
73
+ function redactQuery(search) {
74
+ const withoutFragment = search.split("#", 1)[0] ?? "";
75
+ const query = withoutFragment.startsWith("?") ? withoutFragment.slice(1) : withoutFragment;
76
+ const keys = query.split("&").map((pair) => pair.split("=", 1)[0] ?? "").filter((key) => key.length > 0);
77
+ return keys.length > 0 ? `?${keys.map((key) => `${key}=`).join("&")}` : "";
78
+ }
79
+ function redactPath(pathAndQuery) {
80
+ const withoutFragment = pathAndQuery.split("#", 1)[0] ?? "";
81
+ const queryStart = withoutFragment.indexOf("?");
82
+ const pathPart = queryStart === -1 ? withoutFragment : withoutFragment.slice(0, queryStart);
83
+ const query = queryStart === -1 ? "" : withoutFragment.slice(queryStart);
84
+ return `${redactPathPart(pathPart)}${redactQuery(query)}`;
85
+ }
86
+ function redactUrlLike(value) {
87
+ let prefix;
88
+ if (value.startsWith("//")) {
89
+ prefix = "//";
90
+ } else if (value.startsWith("/")) {
91
+ return redactPath(value);
92
+ } else if (/^https:\/\//i.test(value)) {
93
+ prefix = value.slice(0, "https://".length);
94
+ } else if (/^http:\/\//i.test(value)) {
95
+ prefix = value.slice(0, "http://".length);
96
+ } else {
97
+ return void 0;
98
+ }
99
+ const rest = value.slice(prefix.length);
100
+ const authorityEnd = rest.search(/[/?#]/);
101
+ const authority = authorityEnd === -1 ? rest : rest.slice(0, authorityEnd);
102
+ const tail = authorityEnd === -1 ? "" : rest.slice(authorityEnd);
103
+ const host = authority.slice(authority.lastIndexOf("@") + 1);
104
+ return `${prefix}${host}${redactPath(tail)}`;
105
+ }
106
+ function redactPathPart(pathPart) {
107
+ const encoded = ENCODED_QUESTION_MARK.exec(pathPart);
108
+ const prefix = encoded === null ? pathPart : pathPart.slice(0, encoded.index);
109
+ const redactedPrefix = prefix.replaceAll(
110
+ /;([^/;=]*)=[^/;]*/g,
111
+ (_match, name) => `;${name}=`
112
+ );
113
+ if (encoded === null) {
114
+ return redactedPrefix;
115
+ }
116
+ const keys = pathPart.slice(encoded.index + encoded[0].length).split(ENCODED_PAIR_SEPARATOR).map((pair) => pair.split(ENCODED_KEY_END, 1)[0] ?? "").filter((key) => key.length > 0);
117
+ return keys.length > 0 ? `${redactedPrefix}${encoded[0]}${keys.map((key) => `${key}=`).join("&")}` : redactedPrefix;
118
+ }
119
+
69
120
  // ../connector-core/src/headers.ts
70
121
  var EXCLUDED_HEADER_IDENTITIES = /* @__PURE__ */ new Set([
71
122
  "authorization",
@@ -109,29 +160,148 @@ var EXCLUDED_HEADER_IDENTITIES = /* @__PURE__ */ new Set([
109
160
  var EXCLUDED_HEADER_SUBSTRINGS = ["cryptogram", "networktoken"];
110
161
  var PAYMENT_CREDENTIAL_MARKER_HEADER = "x-steadphast-payment-credential";
111
162
  var PAYMENT_AUTHORIZATION_MARKER_VALUE = "payment-authorization";
163
+ var COOKIE_NAMES_MARKER_HEADER = "x-steadphast-cookie-names";
164
+ var COOKIE_NAME_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
165
+ var MAX_COOKIE_NAME_BYTES = 64;
166
+ var MAX_COOKIE_NAMES = 32;
167
+ var MAX_COOKIE_NAMES_VALUE_BYTES = 1024;
168
+ var PRESENCE_ONLY_IDENTITIES = /* @__PURE__ */ new Set(["nextrouterstatetree", "nexturl"]);
169
+ var PRESENCE_ONLY_VALUE = "present";
170
+ var PROXY_URL_IDENTITIES = /* @__PURE__ */ new Set([
171
+ "xforwardeduri",
172
+ "xoriginalurl",
173
+ "xoriginaluri",
174
+ "xenvoyoriginalpath",
175
+ "xrewriteurl"
176
+ ]);
177
+ var DEDICATED_PEER_HEADERS = /* @__PURE__ */ new Set([
178
+ "user-agent",
179
+ "signature",
180
+ "signature-input",
181
+ "x-forwarded-for",
182
+ "x-vercel-forwarded-for",
183
+ "x-vercel-id",
184
+ "x-vercel-ja4-digest",
185
+ "x-vercel-ja3-digest"
186
+ ]);
112
187
  function captureRequestHeaders(headers, options) {
113
188
  const captured = /* @__PURE__ */ Object.create(null);
114
189
  const additionalExclusions = new Set(
115
190
  options?.excludedHeaders?.map((name) => name.trim().toLowerCase()) ?? []
116
191
  );
192
+ const excludedIdentities = new Set(
193
+ [...additionalExclusions].map((name) => collapseHeaderName(name))
194
+ );
195
+ const excludesCookie = excludedIdentities.has("cookie");
196
+ const excludesSetCookie = excludedIdentities.has("setcookie");
197
+ const excludesCookieNamesMarker = excludedIdentities.has(
198
+ "xsteadphastcookienames"
199
+ );
200
+ const cookieNames = [];
117
201
  let paymentCredential = false;
118
202
  headers.forEach((value, name) => {
119
203
  const lowerName = name.toLowerCase();
120
- if (lowerName === PAYMENT_CREDENTIAL_MARKER_HEADER) {
204
+ const identity = collapseHeaderName(lowerName);
205
+ if (lowerName === PAYMENT_CREDENTIAL_MARKER_HEADER || identity === "xsteadphastcookienames") {
206
+ return;
207
+ }
208
+ if (identity === "cookie") {
209
+ if (!excludesCookie) cookieNames.push(...cookieHeaderNames(value));
210
+ return;
211
+ }
212
+ if (identity === "setcookie") {
213
+ if (!excludesSetCookie && lowerName !== "set-cookie") {
214
+ cookieNames.push(...setCookieNames([value]));
215
+ }
121
216
  return;
122
217
  }
123
- if (collapseHeaderName(lowerName) === "paymentauthorization") {
218
+ if (identity === "paymentauthorization") {
124
219
  paymentCredential = true;
125
220
  }
126
- if (!isExcludedHeader(lowerName) && !additionalExclusions.has(lowerName)) {
127
- captured[lowerName] = value;
221
+ if (isExcludedHeader(lowerName) || additionalExclusions.has(lowerName)) {
222
+ return;
223
+ }
224
+ if (identity === "referer" || identity === "referrer") {
225
+ const reduced = reduceReferer(value);
226
+ if (reduced !== void 0) captured[lowerName] = reduced;
227
+ return;
228
+ }
229
+ if (PRESENCE_ONLY_IDENTITIES.has(identity)) {
230
+ captured[lowerName] = PRESENCE_ONLY_VALUE;
231
+ return;
232
+ }
233
+ if (PROXY_URL_IDENTITIES.has(identity)) {
234
+ captured[lowerName] = redactUrlLike(value) ?? redactPath(value);
235
+ return;
128
236
  }
237
+ captured[lowerName] = value.includes("?") && !DEDICATED_PEER_HEADERS.has(lowerName) ? redactUrlLike(value) ?? value : value;
129
238
  });
239
+ if (!excludesSetCookie) {
240
+ cookieNames.push(...setCookieNames(setCookieValues(headers)));
241
+ }
130
242
  if (paymentCredential && !additionalExclusions.has(PAYMENT_CREDENTIAL_MARKER_HEADER)) {
131
243
  captured[PAYMENT_CREDENTIAL_MARKER_HEADER] = PAYMENT_AUTHORIZATION_MARKER_VALUE;
132
244
  }
245
+ const cookieNamesValue = normalizeCookieNames(cookieNames);
246
+ if (cookieNamesValue !== void 0 && !excludesCookieNamesMarker) {
247
+ captured[COOKIE_NAMES_MARKER_HEADER] = cookieNamesValue;
248
+ }
133
249
  return captured;
134
250
  }
251
+ function reduceReferer(value) {
252
+ for (let index = 0; index < value.length; index += 1) {
253
+ const code = value.charCodeAt(index);
254
+ if (code <= 32 || code === 127 || code === 92) {
255
+ return void 0;
256
+ }
257
+ }
258
+ const schemeEnd = value.indexOf("://");
259
+ if (schemeEnd === -1) {
260
+ return void 0;
261
+ }
262
+ const authority = value.slice(schemeEnd + 3).split(/[/?#]/, 1)[0] ?? "";
263
+ if (authority.length === 0 || /[^\u0021-\u007e]|[@%]/.test(authority)) {
264
+ return void 0;
265
+ }
266
+ let url;
267
+ try {
268
+ url = new URL(value);
269
+ } catch {
270
+ return void 0;
271
+ }
272
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
273
+ return void 0;
274
+ }
275
+ return url.origin;
276
+ }
277
+ function cookieHeaderNames(value) {
278
+ return value.split(";").flatMap((segment) => cookieName(segment.trim()));
279
+ }
280
+ function setCookieNames(values) {
281
+ return values.flatMap((value) => cookieName(value.split(";", 1)[0] ?? ""));
282
+ }
283
+ function cookieName(pair) {
284
+ const separator = pair.indexOf("=");
285
+ if (separator === -1) {
286
+ return [];
287
+ }
288
+ const name = pair.slice(0, separator).trim();
289
+ return name.length <= MAX_COOKIE_NAME_BYTES && COOKIE_NAME_PATTERN.test(name) ? [name] : [];
290
+ }
291
+ function setCookieValues(headers) {
292
+ if (typeof headers.getSetCookie === "function") {
293
+ return headers.getSetCookie();
294
+ }
295
+ const joined = headers.get("set-cookie");
296
+ return joined === null ? [] : [joined];
297
+ }
298
+ function normalizeCookieNames(names) {
299
+ const kept = [...new Set(names)].sort().slice(0, MAX_COOKIE_NAMES);
300
+ while (kept.length > 0 && kept.join(", ").length > MAX_COOKIE_NAMES_VALUE_BYTES) {
301
+ kept.pop();
302
+ }
303
+ return kept.length > 0 ? kept.join(", ") : void 0;
304
+ }
135
305
  function parseForwardedChain(headerValue) {
136
306
  if (headerValue === null) {
137
307
  return void 0;
@@ -147,6 +317,61 @@ function collapseHeaderName(name) {
147
317
  return name.replaceAll(/[^0-9A-Za-z]/g, "").toLowerCase();
148
318
  }
149
319
 
320
+ // ../connector-core/src/signed-components.ts
321
+ var QUERY_BEARING_COMPONENTS = /* @__PURE__ */ new Set([
322
+ "@query",
323
+ "@query-param",
324
+ "@target-uri",
325
+ "@request-target"
326
+ ]);
327
+ function signatureInputCoversQuery(signatureInput) {
328
+ return signatureInputCovers(signatureInput, QUERY_BEARING_COMPONENTS);
329
+ }
330
+ function signatureInputCoversPath(signatureInput) {
331
+ return signatureInputCovers(signatureInput, PATH_COMPONENTS) || signatureInputCoversQuery(signatureInput);
332
+ }
333
+ var PATH_COMPONENTS = /* @__PURE__ */ new Set(["@path"]);
334
+ function signatureInputCovers(signatureInput, components) {
335
+ if (signatureInput === null) {
336
+ return false;
337
+ }
338
+ let depth = 0;
339
+ let index = 0;
340
+ let covered = false;
341
+ while (index < signatureInput.length) {
342
+ const char = signatureInput[index];
343
+ if (char === '"') {
344
+ let end = index + 1;
345
+ let value = "";
346
+ while (end < signatureInput.length && signatureInput[end] !== '"') {
347
+ if (signatureInput[end] === "\\") {
348
+ end += 1;
349
+ }
350
+ value += signatureInput[end] ?? "";
351
+ end += 1;
352
+ }
353
+ if (end >= signatureInput.length) {
354
+ return false;
355
+ }
356
+ if (depth > 0 && signatureInput[index - 1] !== "=" && components.has(value.toLowerCase())) {
357
+ covered = true;
358
+ }
359
+ index = end + 1;
360
+ continue;
361
+ }
362
+ if (char === "(") {
363
+ depth += 1;
364
+ } else if (char === ")") {
365
+ if (depth === 0) {
366
+ return false;
367
+ }
368
+ depth -= 1;
369
+ }
370
+ index += 1;
371
+ }
372
+ return covered && depth === 0;
373
+ }
374
+
150
375
  // ../connector-core/src/shipper.ts
151
376
  var DEFAULT_SHIP_TIMEOUT_MS = 5e3;
152
377
  var droppedEventCount = 0;
@@ -163,6 +388,7 @@ var SELF_HOSTED_CONNECTOR_ASSERTION = "nextjs-self-hosted";
163
388
  var ENVELOPE_INGEST_PATHNAME = "/v1/connectors/nextjs/events";
164
389
  var COLLECTOR_HEADER_PREFIX = "x-steadphast-collector-";
165
390
  var COLLECTOR_CONTEXT_HEADER = `${COLLECTOR_HEADER_PREFIX}context`;
391
+ var BEHAVIORAL_CONTEXT_HEADER = `${COLLECTOR_HEADER_PREFIX}behavioral`;
166
392
  var LEGACY_CANONICAL_INGEST_PATHNAME = "/v1/events";
167
393
  var DiscoverConfigError = class extends TypeError {
168
394
  name = "DiscoverConfigError";
@@ -306,19 +532,24 @@ function stripCollectorHeaders(headers) {
306
532
  for (const name of names) headers.delete(name);
307
533
  return true;
308
534
  }
309
- function forwardedRequestHeaders(request, context) {
535
+ function forwardedRequestHeaders(request, context, behavioralContext) {
310
536
  const headers = new Headers(request.headers);
311
537
  stripCollectorHeaders(headers);
312
538
  if (context !== void 0) headers.set(COLLECTOR_CONTEXT_HEADER, context);
539
+ if (behavioralContext !== void 0)
540
+ headers.set(BEHAVIORAL_CONTEXT_HEADER, behavioralContext);
313
541
  return headers;
314
542
  }
315
543
  function applyForwardedHeaders(result, forwarded) {
316
- if (result === void 0 || result === null) {
317
- return NextResponse.next({ request: { headers: forwarded } });
544
+ const response = result ?? NextResponse.next({ request: { headers: forwarded } });
545
+ const headers = response.headers;
546
+ if (forwarded.has(BEHAVIORAL_CONTEXT_HEADER)) {
547
+ headers.set("cache-control", "private, no-store, max-age=0");
548
+ headers.set("cdn-cache-control", "no-store");
549
+ headers.set("vercel-cdn-cache-control", "no-store");
318
550
  }
319
- const headers = result.headers;
320
551
  if (!headers.has(NEXT_HEADER) && !headers.has(REWRITE_HEADER)) {
321
- return result;
552
+ return response;
322
553
  }
323
554
  const override = headers.get(OVERRIDE_HEADERS);
324
555
  if (override === null) {
@@ -328,7 +559,7 @@ function applyForwardedHeaders(result, forwarded) {
328
559
  names2.push(name);
329
560
  }
330
561
  headers.set(OVERRIDE_HEADERS, names2.join(","));
331
- return result;
562
+ return response;
332
563
  }
333
564
  const names = override.split(",").map((name) => name.trim()).filter((name) => {
334
565
  if (!name.toLowerCase().startsWith(COLLECTOR_HEADER_PREFIX)) return true;
@@ -340,8 +571,13 @@ function applyForwardedHeaders(result, forwarded) {
340
571
  headers.set(`${OVERRIDE_PREFIX}${COLLECTOR_CONTEXT_HEADER}`, context);
341
572
  names.push(COLLECTOR_CONTEXT_HEADER);
342
573
  }
574
+ const behavioral = forwarded.get(BEHAVIORAL_CONTEXT_HEADER);
575
+ if (behavioral !== null) {
576
+ headers.set(`${OVERRIDE_PREFIX}${BEHAVIORAL_CONTEXT_HEADER}`, behavioral);
577
+ names.push(BEHAVIORAL_CONTEXT_HEADER);
578
+ }
343
579
  headers.set(OVERRIDE_HEADERS, names.join(","));
344
- return result;
580
+ return response;
345
581
  }
346
582
 
347
583
  // src/delivery.ts
@@ -449,7 +685,12 @@ function prepareEvidenceEnvelope(request, options, capturedAt = /* @__PURE__ */
449
685
  if (method.length > MAX_METHOD_BYTES || !HTTP_METHOD_PATTERN.test(method)) {
450
686
  return void 0;
451
687
  }
452
- const externalUrl = resolveExternalUrl(request.url, deployment);
688
+ const signed = request.headers.get(SIGNATURE_HEADER) !== null;
689
+ const signatureInputValue = request.headers.get(SIGNATURE_INPUT_HEADER);
690
+ const externalUrl = resolveExternalUrl(request.url, deployment, {
691
+ rawPath: signed && signatureInputCoversPath(signatureInputValue),
692
+ rawQuery: signed && signatureInputCoversQuery(signatureInputValue)
693
+ });
453
694
  if (externalUrl === void 0) {
454
695
  return void 0;
455
696
  }
@@ -505,7 +746,7 @@ function prepareEvidenceEnvelope(request, options, capturedAt = /* @__PURE__ */
505
746
  recordId: platform.request_id === void 0 ? void 0 : `${recordIdPrefix}:${platform.request_id}`
506
747
  };
507
748
  }
508
- function resolveExternalUrl(runtimeUrl, deployment) {
749
+ function resolveExternalUrl(runtimeUrl, deployment, keep) {
509
750
  let url;
510
751
  try {
511
752
  url = new URL(runtimeUrl);
@@ -522,7 +763,7 @@ function resolveExternalUrl(runtimeUrl, deployment) {
522
763
  if (url.protocol !== "https:" || url.username.length > 0 || url.password.length > 0 || url.hash.length > 0 || utf8Length(url.host) > MAX_AUTHORITY_BYTES) {
523
764
  return void 0;
524
765
  }
525
- const serialized = url.toString();
766
+ const serialized = keep.rawQuery ? url.toString() : `${url.origin}${keep.rawPath ? url.pathname : redactPath(url.pathname)}${redactQuery(url.search)}`;
526
767
  return utf8Length(serialized) > MAX_EXTERNAL_URL_BYTES ? void 0 : serialized;
527
768
  }
528
769
  function captureHeaders(headers, deployment, excludedHeaders) {
@@ -692,6 +933,9 @@ var API_KEY_VERIFIER_DOMAIN = "steadphast-discover:api-key:v1";
692
933
  var NONCE_KEY_SALT = "steadphast-discover/client-nonce/v1/salt";
693
934
  var NONCE_KEY_INFO = "steadphast-discover/client-nonce/v1";
694
935
  var RENDER_CONTEXT_DOMAIN = "steadphast-discover/collector-render/v1";
936
+ var T1_KEY_SALT = "steadphast-discover/client-t1/v1/salt";
937
+ var T1_KEY_INFO = "steadphast-discover/client-t1/v1";
938
+ var T1_RENDER_DOMAIN = "steadphast-discover/behavioral-render/v1";
695
939
  var MAX_RID_BYTES = 512;
696
940
  var MAX_KEY_ID_BYTES = 64;
697
941
  var TAG_BYTES = 32;
@@ -715,7 +959,72 @@ function createNonceMinter(apiKey) {
715
959
  }
716
960
  const keyIdBytes = utf8(parsed.keyId);
717
961
  let nonceKey;
962
+ let t1Key;
718
963
  return {
964
+ async mintBehavioralContext(context) {
965
+ t1Key ??= deriveNonceKey(parsed, keyIdBytes, T1_KEY_SALT, T1_KEY_INFO);
966
+ const header = utf8(JSON.stringify(context));
967
+ const tag = new Uint8Array(
968
+ await crypto.subtle.sign(
969
+ "HMAC",
970
+ await t1Key,
971
+ concat(utf8(T1_RENDER_DOMAIN), header)
972
+ )
973
+ );
974
+ const wire = bytes(header.byteLength + TAG_BYTES);
975
+ wire.set(header);
976
+ wire.set(tag, header.byteLength);
977
+ return base64UrlNoPad(wire);
978
+ },
979
+ async behavioralFromContext(context, policy) {
980
+ if (context.length > 2048 || policy.mode !== "own") return void 0;
981
+ try {
982
+ const binary = atob(context.replace(/-/g, "+").replace(/_/g, "/"));
983
+ const wire = bytes(binary.length);
984
+ for (let i = 0; i < binary.length; i++) wire[i] = binary.charCodeAt(i);
985
+ if (wire.length <= TAG_BYTES) return void 0;
986
+ const header = wire.subarray(0, -TAG_BYTES);
987
+ t1Key ??= deriveNonceKey(parsed, keyIdBytes, T1_KEY_SALT, T1_KEY_INFO);
988
+ if (!await crypto.subtle.verify(
989
+ "HMAC",
990
+ await t1Key,
991
+ wire.subarray(-TAG_BYTES),
992
+ concat(utf8(T1_RENDER_DOMAIN), header)
993
+ ))
994
+ return void 0;
995
+ const input = JSON.parse(
996
+ new TextDecoder().decode(header)
997
+ );
998
+ if (Date.now() - input.issued_at_ms > 6e5 || input.issued_at_ms > Date.now() + 3e4)
999
+ return void 0;
1000
+ const binding = utf8(
1001
+ JSON.stringify({
1002
+ version: 1,
1003
+ key_id: parsed.keyId,
1004
+ source: input.source,
1005
+ rid: input.rid,
1006
+ site: input.site,
1007
+ issued_at_ms: input.issued_at_ms,
1008
+ expires_at_ms: input.issued_at_ms + 6e5,
1009
+ revision: policy.revision,
1010
+ timing_enabled: policy.timing_enabled
1011
+ })
1012
+ );
1013
+ const tag = new Uint8Array(
1014
+ await crypto.subtle.sign("HMAC", await t1Key, binding)
1015
+ );
1016
+ const token = bytes(binding.byteLength + TAG_BYTES);
1017
+ token.set(binding);
1018
+ token.set(tag, binding.byteLength);
1019
+ return {
1020
+ nonce: base64UrlNoPad(token),
1021
+ path: input.path,
1022
+ issuedAt: input.issued_at_ms
1023
+ };
1024
+ } catch {
1025
+ return void 0;
1026
+ }
1027
+ },
719
1028
  async mintRenderContext(rid, servedAtMs) {
720
1029
  const header = encodeHeader(rid, servedAtMs, keyIdBytes);
721
1030
  if (header === void 0) return void 0;
@@ -732,7 +1041,7 @@ function createNonceMinter(apiKey) {
732
1041
  context.set(tag, header.byteLength);
733
1042
  return base64UrlNoPad(context);
734
1043
  },
735
- async nonceFromRenderContext(context) {
1044
+ async nonceFromRenderContext(context, rendering) {
736
1045
  if (context.length > 850 || !/^[A-Za-z0-9_-]+$/.test(context)) {
737
1046
  return void 0;
738
1047
  }
@@ -755,10 +1064,29 @@ function createNonceMinter(apiKey) {
755
1064
  concat(utf8(RENDER_CONTEXT_DOMAIN), header)
756
1065
  ))
757
1066
  return void 0;
758
- const tag = new Uint8Array(
759
- await crypto.subtle.sign("HMAC", await nonceKey, header)
1067
+ let signed = header;
1068
+ if (rendering !== void 0) {
1069
+ const { revision, catalog } = rendering;
1070
+ if (![revision, catalog].every(
1071
+ (n) => Number.isInteger(n) && n >= 0 && n <= 4294967295
1072
+ ) || revision === 0)
1073
+ return void 0;
1074
+ const extended = bytes(header.byteLength + 9 + TAG_BYTES);
1075
+ extended.set(header);
1076
+ extended[0] = 2;
1077
+ extended[header.byteLength] = 4;
1078
+ const view = new DataView(extended.buffer);
1079
+ view.setUint32(header.byteLength + 1, revision);
1080
+ view.setUint32(header.byteLength + 5, catalog);
1081
+ decoded = extended;
1082
+ signed = extended.subarray(0, -TAG_BYTES);
1083
+ }
1084
+ decoded.set(
1085
+ new Uint8Array(
1086
+ await crypto.subtle.sign("HMAC", await nonceKey, signed)
1087
+ ),
1088
+ signed.byteLength
760
1089
  );
761
- decoded.set(tag, header.byteLength);
762
1090
  return base64UrlNoPad(decoded);
763
1091
  }
764
1092
  };
@@ -786,7 +1114,7 @@ function encodeHeader(rid, servedAtMs, keyIdBytes) {
786
1114
  header.set(keyIdBytes, offset);
787
1115
  return header;
788
1116
  }
789
- async function deriveNonceKey(parsed, keyIdBytes) {
1117
+ async function deriveNonceKey(parsed, keyIdBytes, salt = NONCE_KEY_SALT, info = NONCE_KEY_INFO) {
790
1118
  const secretKey = await crypto.subtle.importKey(
791
1119
  "raw",
792
1120
  utf8(parsed.secret),
@@ -806,8 +1134,8 @@ async function deriveNonceKey(parsed, keyIdBytes) {
806
1134
  {
807
1135
  name: "HKDF",
808
1136
  hash: "SHA-256",
809
- salt: utf8(NONCE_KEY_SALT),
810
- info: concat(utf8(NONCE_KEY_INFO), keyIdBytes)
1137
+ salt: utf8(salt),
1138
+ info: concat(utf8(info), keyIdBytes)
811
1139
  },
812
1140
  hkdfKey,
813
1141
  TAG_BYTES * 8
@@ -874,7 +1202,7 @@ function buildMiddleware(config, ingestUrl, handler) {
874
1202
  console.warn(missingApiKeyDiagnostic(settings.apiKeyEnvVar));
875
1203
  didWarnMissingApiKey = true;
876
1204
  }
877
- } else if (settings.collector) {
1205
+ } else if (settings.collector || settings.behavioralRoutes.length > 0) {
878
1206
  return captureWithCollector(
879
1207
  settings,
880
1208
  minters.for(apiKey),
@@ -902,6 +1230,7 @@ function snapshotSettings(config, ingestUrl) {
902
1230
  apiKeyEnvVar: config.apiKeyEnvVar,
903
1231
  captureAllPaths: config.captureAllPaths === true,
904
1232
  collector: config.collector === true,
1233
+ behavioralRoutes: config.collector === false || (config.behavioral?.mode ?? "own") !== "own" ? [] : [...config.behavioral?.routes ?? []],
905
1234
  connectorAssertion: connectorAssertionFor(deployment),
906
1235
  endpoint: ingestUrl,
907
1236
  envelopeOptions: {
@@ -938,9 +1267,22 @@ function ship2(settings, apiKey, prepared, servedAtMs, event) {
938
1267
  }
939
1268
  async function captureWithCollector(settings, minter, apiKey, request, event, handler, scrubbed) {
940
1269
  const prepared = prepareEvidenceEnvelope(request, settings.envelopeOptions);
941
- const armed = prepared?.recordId !== void 0 && minter !== void 0 && isDocumentNavigation(request);
1270
+ const path = new URL(request.url).pathname;
1271
+ const behavioral = settings.behavioralRoutes.includes(path) && !path.split("/").some(
1272
+ (part) => /^(auth|login|signin|signup|password|checkout|payment|billing|health|medical)$/i.test(
1273
+ part
1274
+ )
1275
+ );
1276
+ const armed = prepared?.recordId !== void 0 && minter !== void 0 && isDocumentNavigation(request) && (settings.collector || behavioral);
942
1277
  const servedAt = armed ? Date.now() : void 0;
943
1278
  const context = armed && prepared?.recordId !== void 0 && servedAt !== void 0 ? await minter.mintRenderContext(prepared.recordId, servedAt) : void 0;
1279
+ const behavioralContext = armed && behavioral && minter && prepared?.recordId && servedAt !== void 0 ? await minter.mintBehavioralContext({
1280
+ rid: prepared.recordId,
1281
+ site: new URL(prepared.envelope.request.external_url).host,
1282
+ path,
1283
+ source: settings.connectorAssertion,
1284
+ issued_at_ms: servedAt
1285
+ }) : void 0;
944
1286
  if (context === void 0) {
945
1287
  ship2(settings, apiKey, prepared, void 0, event);
946
1288
  return scrubbed ? delegateWithHeaders(
@@ -950,12 +1292,18 @@ async function captureWithCollector(settings, minter, apiKey, request, event, ha
950
1292
  forwardedRequestHeaders(request, void 0)
951
1293
  ) : delegate(handler, request, event);
952
1294
  }
953
- ship2(settings, apiKey, prepared, servedAt, event);
1295
+ ship2(
1296
+ settings,
1297
+ apiKey,
1298
+ prepared,
1299
+ settings.collector ? servedAt : void 0,
1300
+ event
1301
+ );
954
1302
  return delegateWithHeaders(
955
1303
  handler,
956
1304
  request,
957
1305
  event,
958
- forwardedRequestHeaders(request, context)
1306
+ forwardedRequestHeaders(request, context, behavioralContext)
959
1307
  );
960
1308
  }
961
1309
  function delegate(handler, request, event) {
@@ -966,7 +1314,7 @@ function delegate(handler, request, event) {
966
1314
  }
967
1315
  async function delegateWithHeaders(handler, request, event, forwarded) {
968
1316
  if (handler === void 0) {
969
- return NextResponse2.next({ request: { headers: forwarded } });
1317
+ return applyForwardedHeaders(void 0, forwarded);
970
1318
  }
971
1319
  const forwardedRequest = new request.constructor(
972
1320
  request,
@@ -0,0 +1,27 @@
1
+ type ProbeRoute = "page" | "customer-host" | "steadphast-host" | "steadphast-host-dns-fallback";
2
+ type ProbeModule = "environment" | "behavior" | "device" | "network";
3
+ type Outcome = {
4
+ state: "not-observed";
5
+ value: null;
6
+ } | {
7
+ state: "observed" | "differs";
8
+ value: number;
9
+ };
10
+ type Reading = {
11
+ module: ProbeModule;
12
+ name: string;
13
+ route: ProbeRoute;
14
+ } & Outcome;
15
+ export interface ProbeJob {
16
+ reading: Reading;
17
+ cancel(): void;
18
+ }
19
+ export interface ProbeRunner {
20
+ run(module: ProbeModule, name: string, route: ProbeRoute, permitted: boolean, start: (finish: (value?: number, state?: "observed" | "differs") => void, signal: AbortSignal) => void): ProbeJob;
21
+ }
22
+ /** Stringified into the server-rendered script. The budget covers active work, not time waiting for consent. */
23
+ export declare function createProbeRunner(): ProbeRunner;
24
+ /** One installation per Document, including duplicate tags and bfcache restores. Only a boolean
25
+ * lives on the document; neither credentials, readings nor callable probes are exposed there. */
26
+ export declare function pageScript(invocations: string): string;
27
+ export {};
package/dist/server.d.ts CHANGED
@@ -8,6 +8,8 @@ import { type DiscoverNextConfig } from "./config.js";
8
8
  export interface DiscoverCollectorProps {
9
9
  /** Server-owned tenant settings shared with withDiscover. Missing settings fail closed. */
10
10
  config?: DiscoverNextConfig;
11
+ /** Server decision for this visitor, approved origin and route; omission denies. */
12
+ environmentPermitted?: boolean;
11
13
  /** Optional server-owned Content Security Policy nonce. Never copied from visitor headers. */
12
14
  nonce?: string;
13
15
  }