reguard 0.8.0 → 0.9.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 (34) hide show
  1. package/README.md +23 -1
  2. package/dist/chunks/{chunk-PA46KSOR.js → chunk-CGXTVKRB.js} +83 -7
  3. package/dist/chunks/{chunk-KNKCUJL3.js → chunk-CUIFGML3.js} +22 -7
  4. package/dist/chunks/{chunk-YDDBWUPV.js → chunk-PRPLLMXA.js} +37 -11
  5. package/dist/chunks/{chunk-3AYS7WSY.js → chunk-W4FDH5AD.js} +74 -3
  6. package/dist/cjs/fastify.cjs +71 -8
  7. package/dist/cjs/fetch.cjs +171 -17
  8. package/dist/cjs/index.cjs +153 -10
  9. package/dist/cjs/next.cjs +177 -16
  10. package/dist/cjs/testing.cjs +33 -1
  11. package/dist/fastify.js +3 -3
  12. package/dist/fetch.js +14 -5
  13. package/dist/index.js +13 -5
  14. package/dist/next.js +20 -5
  15. package/dist/testing.js +9 -3
  16. package/dist/types/node/src/api.d.ts +139 -0
  17. package/dist/types/node/src/core.d.ts +8 -1
  18. package/dist/types/node/src/fetch.d.ts +6 -0
  19. package/dist/types/node/src/index.d.ts +6 -0
  20. package/dist/types/node/src/next.d.ts +1 -0
  21. package/dist/types/node/src/testing.d.ts +11 -0
  22. package/dist/types/shared/src/index.d.ts +9 -0
  23. package/dist/types/shared/src/verdict.d.ts +6 -0
  24. package/dist/types/shared/src/webhooks.d.ts +32 -0
  25. package/dist/types-cjs/node/src/api.d.cts +139 -0
  26. package/dist/types-cjs/node/src/core.d.cts +8 -1
  27. package/dist/types-cjs/node/src/fetch.d.cts +6 -0
  28. package/dist/types-cjs/node/src/index.d.cts +6 -0
  29. package/dist/types-cjs/node/src/next.d.cts +1 -0
  30. package/dist/types-cjs/node/src/testing.d.cts +11 -0
  31. package/dist/types-cjs/shared/src/index.d.cts +9 -0
  32. package/dist/types-cjs/shared/src/verdict.d.cts +6 -0
  33. package/dist/types-cjs/shared/src/webhooks.d.cts +32 -0
  34. package/package.json +1 -1
@@ -20,9 +20,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/fetch.ts
21
21
  var fetch_exports = {};
22
22
  __export(fetch_exports, {
23
+ ReguardApiError: () => ReguardApiError,
23
24
  ReguardConfigError: () => ReguardConfigError,
25
+ ReguardWebhookError: () => WebhookSignatureError,
24
26
  defaultBlockAnswer: () => defaultBlockAnswer,
25
- reguardFetch: () => reguardFetch
27
+ reguardApi: () => reguardApi,
28
+ reguardFetch: () => reguardFetch,
29
+ verifyWebhook: () => verifyWebhook
26
30
  });
27
31
  module.exports = __toCommonJS(fetch_exports);
28
32
 
@@ -707,12 +711,71 @@ function isSourceMapPath(p) {
707
711
  return /\.map$/i.test(p.raw) || /\.map$/i.test(p.decoded);
708
712
  }
709
713
 
714
+ // ../shared/src/webhooks.ts
715
+ var WEBHOOK_TOLERANCE_SECONDS = 300;
716
+ var WebhookSignatureError = class extends Error {
717
+ constructor(code, message) {
718
+ super(message);
719
+ this.code = code;
720
+ this.name = "ReguardWebhookError";
721
+ }
722
+ };
723
+ var enc2 = new TextEncoder();
724
+ function hmacKey2(secret) {
725
+ return crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
726
+ }
727
+ function signedBytes(timestamp, payload) {
728
+ const head = enc2.encode(`${timestamp}.`);
729
+ const body = typeof payload === "string" ? enc2.encode(payload) : payload;
730
+ const out = new Uint8Array(new ArrayBuffer(head.length + body.length));
731
+ out.set(head, 0);
732
+ out.set(body, head.length);
733
+ return out;
734
+ }
735
+ function unhex(s) {
736
+ const out = new Uint8Array(new ArrayBuffer(s.length / 2));
737
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
738
+ return out;
739
+ }
740
+ function parseWebhookSignature(header) {
741
+ let t;
742
+ const v1 = [];
743
+ for (const part of header.split(",")) {
744
+ const i = part.indexOf("=");
745
+ if (i < 1) continue;
746
+ const k = part.slice(0, i).trim();
747
+ const v = part.slice(i + 1).trim();
748
+ if (k === "t" && /^\d{1,12}$/.test(v)) t = Number(v);
749
+ else if (k === "v1" && /^[0-9a-f]{64}$/.test(v)) v1.push(v);
750
+ }
751
+ return t === void 0 || !v1.length ? null : { t, v1 };
752
+ }
753
+ async function verifyWebhookSignature(payload, header, secret, options = {}) {
754
+ if (!secret) throw new WebhookSignatureError("missing_secret", "No webhook signing secret: pass it, or set REGUARD_WEBHOOK_SECRET.");
755
+ if (!header) throw new WebhookSignatureError("missing_signature", "No Reguard-Signature header on this request.");
756
+ const parsed = parseWebhookSignature(header);
757
+ if (!parsed) throw new WebhookSignatureError("malformed_signature", "The Reguard-Signature header isn't in the form t=\u2026,v1=\u2026.");
758
+ const tolerance = options.tolerance ?? WEBHOOK_TOLERANCE_SECONDS;
759
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
760
+ if (tolerance > 0 && Math.abs(now - parsed.t) > tolerance) {
761
+ throw new WebhookSignatureError("expired", `The delivery is signed ${Math.abs(now - parsed.t)} s from now, more than the ${tolerance} s allowed (a replay, or a clock that's off).`);
762
+ }
763
+ const key = await hmacKey2(secret);
764
+ const data = signedBytes(parsed.t, payload);
765
+ for (const sig of parsed.v1) {
766
+ if (await crypto.subtle.verify("HMAC", key, unhex(sig), data)) return;
767
+ }
768
+ throw new WebhookSignatureError("bad_signature", "The signature doesn't match: check the signing secret, and pass the raw request body.");
769
+ }
770
+
710
771
  // src/core.ts
711
772
  var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
773
+ var visitorIdOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
712
774
  function withFlagged(p, source = "browser") {
713
775
  return {
714
776
  ...p,
715
777
  source,
778
+ visitor: visitorIdOf(p.vid) ?? null,
716
779
  flagged({ labels, minStage = "candidate" } = {}) {
717
780
  const want = typeof labels === "string" ? [labels] : labels?.length ? labels : void 0;
718
781
  const rank = STAGE_RANK[minStage] ?? 0;
@@ -725,8 +788,9 @@ function mergeVerdicts(browser, pushed) {
725
788
  if (!browser) return withFlagged(pushed, "server");
726
789
  const rules = new Set(browser.claims.map((c) => `${c.rule}|${c.label}|${c.stage}`));
727
790
  const claims = [...browser.claims, ...pushed.claims.filter((c) => !rules.has(`${c.rule}|${c.label}|${c.stage}`))];
728
- const { source: _s, flagged: _f, ...payload } = browser;
729
- return withFlagged({ ...payload, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
791
+ const { source: _s, flagged: _f, visitor: _v, ...payload } = browser;
792
+ const vid = visitorIdOf(payload.vid) ?? visitorIdOf(pushed.vid);
793
+ return withFlagged({ ...payload, ...vid ? { vid } : {}, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
730
794
  }
731
795
  async function readVerdictFrom(secret, site, cookieHeader) {
732
796
  const token = cookieValue(cookieHeader, VERDICT_COOKIE);
@@ -747,8 +811,8 @@ var DEFAULT_PACE = {
747
811
  api: { burst: 60, perSecond: 5 },
748
812
  notFound: { burst: 20, perSecond: 0.5 }
749
813
  };
750
- function pushedVerdict(sid, site, claims, now = Date.now()) {
751
- return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4 }, "server");
814
+ function pushedVerdict(sid, site, claims, now = Date.now(), vid) {
815
+ return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4, ...vid ? { vid } : {} }, "server");
752
816
  }
753
817
  var ANSWER_CODES = { flagged: "reguard.blocked", flagged_server: "reguard.blocked", require: "reguard.require", pace: "reguard.pace" };
754
818
  var RETRY_AFTER = { flagged: 120, flagged_server: 120, require: 5, pace: 2 };
@@ -1063,6 +1127,68 @@ var Health = class {
1063
1127
  }
1064
1128
  };
1065
1129
 
1130
+ // src/api.ts
1131
+ var ReguardApiError = class extends Error {
1132
+ constructor(status, message) {
1133
+ super(message);
1134
+ this.status = status;
1135
+ this.name = "ReguardApiError";
1136
+ }
1137
+ };
1138
+ function reguardApi(options = {}) {
1139
+ const key = (options.key?.trim() || envValue("REGUARD_KEY"))?.trim();
1140
+ if (options.key?.trim() && !parseSiteKey(options.key.trim())?.site) throw new TypeError("[reguard] reguardApi: key must be a site key (rgk.<site>.v<n>.\u2026)");
1141
+ const base = collectorBase(options.collector || envValue("REGUARD_COLLECTOR"));
1142
+ const doFetch = options.fetch ?? fetch;
1143
+ const timeoutMs = options.timeoutMs ?? 1e4;
1144
+ async function get(path) {
1145
+ if (!key) throw new ReguardApiError(0, "No site key: pass { key } or set REGUARD_KEY.");
1146
+ if (!parseSiteKey(key)?.site) throw new ReguardApiError(0, "REGUARD_KEY isn't a site key (rgk.<site>.v<n>.\u2026).");
1147
+ let res;
1148
+ try {
1149
+ res = await doFetch(`${base}${path}`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
1150
+ } catch (e) {
1151
+ throw new ReguardApiError(0, `Reguard's API can't be reached: ${e.message}`);
1152
+ }
1153
+ const parsed = await res.json().catch(() => null);
1154
+ const body = parsed && typeof parsed === "object" ? parsed : {};
1155
+ if (!res.ok) throw new ReguardApiError(res.status, typeof body.error === "string" && body.error ? body.error : `Reguard's API answered ${res.status}`);
1156
+ return body;
1157
+ }
1158
+ return {
1159
+ async visitor(id) {
1160
+ if (!visitorIdOf(id)) throw new ReguardApiError(400, "Not a visitor id: they look like vis_ followed by 22 characters.");
1161
+ return (await get(`/v1/visitors/${id}`)).visitor;
1162
+ },
1163
+ events({ after, limit, types } = {}) {
1164
+ const q = new URLSearchParams();
1165
+ if (after) q.set("after", after);
1166
+ if (typeof limit === "number" && Number.isInteger(limit) && limit > 0) q.set("limit", String(limit));
1167
+ if (types?.length) q.set("type", types.join(","));
1168
+ const qs = q.toString();
1169
+ return get(`/v1/events${qs ? `?${qs}` : ""}`);
1170
+ }
1171
+ };
1172
+ }
1173
+ async function verifyWebhook(payload, signature, secret, options = {}) {
1174
+ if (typeof payload !== "string" && !(payload instanceof Uint8Array) && !(payload instanceof ArrayBuffer)) {
1175
+ throw new TypeError(
1176
+ '[reguard] verifyWebhook needs the raw request body (a string or bytes), not parsed JSON: in Express, use express.raw({ type: "application/json" }) on this route.'
1177
+ );
1178
+ }
1179
+ const raw = payload instanceof ArrayBuffer ? new Uint8Array(payload) : payload;
1180
+ const header = Array.isArray(signature) ? signature[0] : signature;
1181
+ await verifyWebhookSignature(raw, header, secret || envValue("REGUARD_WEBHOOK_SECRET"), options);
1182
+ let event;
1183
+ try {
1184
+ event = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw));
1185
+ } catch {
1186
+ throw new WebhookSignatureError("bad_payload", "The body isn't JSON (a Slack or Discord URL gets messages, not events).");
1187
+ }
1188
+ if (!event || typeof event.id !== "string" || typeof event.type !== "string") throw new WebhookSignatureError("bad_payload", "The body isn't a Reguard event.");
1189
+ return event;
1190
+ }
1191
+
1066
1192
  // src/fetch.ts
1067
1193
  var OPTION_KEYS = [
1068
1194
  "key",
@@ -1083,15 +1209,15 @@ var OPTION_KEYS = [
1083
1209
  "fetch",
1084
1210
  "onError"
1085
1211
  ];
1086
- var enc2 = new TextEncoder();
1212
+ var enc3 = new TextEncoder();
1087
1213
  var keys2 = /* @__PURE__ */ new Map();
1088
1214
  async function hmac(secret, text, length) {
1089
1215
  let k = keys2.get(secret);
1090
1216
  if (!k) {
1091
- k = crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
1217
+ k = crypto.subtle.importKey("raw", enc3.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
1092
1218
  keys2.set(secret, k);
1093
1219
  }
1094
- const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await k, enc2.encode(text)));
1220
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await k, enc3.encode(text)));
1095
1221
  let s = "";
1096
1222
  for (const b of sig) s += String.fromCharCode(b);
1097
1223
  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "").slice(0, length);
@@ -1145,6 +1271,12 @@ function reguardFetch(options = {}) {
1145
1271
  decision: () => null,
1146
1272
  scriptTag: () => "",
1147
1273
  flush: async () => {
1274
+ },
1275
+ visitor: async () => {
1276
+ throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
1277
+ },
1278
+ events: async () => {
1279
+ throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
1148
1280
  }
1149
1281
  };
1150
1282
  }
@@ -1153,6 +1285,7 @@ function reguardFetch(options = {}) {
1153
1285
  const prev = parseSiteKey((options.previousKey ?? envValue("REGUARD_KEY_PREVIOUS"))?.trim());
1154
1286
  if (prev?.site === site && prev.secret !== parsed.secret) secrets.push(prev.secret);
1155
1287
  const collector = collectorBase(options.collector ?? envValue("REGUARD_COLLECTOR"));
1288
+ const api = reguardApi({ key, collector, fetch: doFetch, timeoutMs });
1156
1289
  const platform = options.platform ?? detectPlatform(typeof process !== "undefined" ? process.env : void 0) ?? (typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" ? "workers" : null);
1157
1290
  const health = new Health(log);
1158
1291
  const allDry = !block || BLOCK_REASONS.every((r) => block.dryRun.has(r));
@@ -1204,8 +1337,9 @@ function reguardFetch(options = {}) {
1204
1337
  health.ok();
1205
1338
  const f = (await res.json().catch(() => null))?.flagged;
1206
1339
  const now = Date.now();
1207
- for (const x of f?.sessions ?? []) if (typeof x.sid === "string" && Array.isArray(x.claims)) pushed.set(`s:${x.sid}`, { claims: x.claims, until: now + 6e5 });
1208
- for (const x of f?.visitors ?? []) if (typeof x.visitor === "string" && Array.isArray(x.claims)) pushed.set(`v:${x.visitor}`, { claims: x.claims, until: now + 6e5 });
1340
+ const vidOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
1341
+ for (const x of f?.sessions ?? []) if (typeof x.sid === "string" && Array.isArray(x.claims)) pushed.set(`s:${x.sid}`, { claims: x.claims, until: now + 6e5, vid: vidOf(x.vid) });
1342
+ for (const x of f?.visitors ?? []) if (typeof x.visitor === "string" && Array.isArray(x.claims)) pushed.set(`v:${x.visitor}`, { claims: x.claims, until: now + 6e5, vid: vidOf(x.vid) });
1209
1343
  if (pushed.size > 5e4) pushed.clear();
1210
1344
  }
1211
1345
  if (!res.ok) onError(new Error(`collector answered ${res.status} to /v1/server`));
@@ -1230,11 +1364,15 @@ function reguardFetch(options = {}) {
1230
1364
  const claims = [];
1231
1365
  const k = [sid ? `s:${sid}` : ""];
1232
1366
  if (collect.addresses !== "off" && !verified && !a.internal && a.address) k.push(`v:${await hmac(parsed.secret, `visitor:${a.address}`, 22)}`);
1367
+ let vid;
1233
1368
  for (const x of k) {
1234
1369
  const e = x ? pushed.get(x) : void 0;
1235
- if (e && e.until > now) claims.push(...e.claims);
1370
+ if (e && e.until > now) {
1371
+ claims.push(...e.claims);
1372
+ vid ??= e.vid;
1373
+ }
1236
1374
  }
1237
- return claims.length ? pushedVerdict(sid ?? "", site, claims, now) : null;
1375
+ return claims.length ? pushedVerdict(sid ?? "", site, claims, now, vid) : null;
1238
1376
  };
1239
1377
  const proxy = async (request, p) => {
1240
1378
  const url = new URL(request.url);
@@ -1408,14 +1546,24 @@ function reguardFetch(options = {}) {
1408
1546
  ...a.internal ? { internal: true } : {}
1409
1547
  });
1410
1548
  if (queue.length > 5e3) queue.splice(0, queue.length - 5e3);
1411
- flushSoon(ctx?.waitUntil, !!decision);
1549
+ const waitUntil = ctx?.waitUntil ? (p2) => ctx.waitUntil.call(ctx, p2) : void 0;
1550
+ ensureTimer();
1551
+ flushSoon(waitUntil, !!decision);
1412
1552
  } catch (e) {
1413
1553
  onError(e);
1414
1554
  }
1415
1555
  })();
1416
1556
  };
1417
- const timer = typeof setInterval === "function" ? setInterval(() => flushSoon(void 0, true), flushIntervalMs) : void 0;
1418
- timer?.unref?.();
1557
+ let timer;
1558
+ const ensureTimer = () => {
1559
+ if (timer !== void 0 || platform === "workers" || typeof setInterval !== "function") return;
1560
+ try {
1561
+ timer = setInterval(() => flushSoon(void 0, true), flushIntervalMs);
1562
+ timer.unref?.();
1563
+ } catch {
1564
+ timer = null;
1565
+ }
1566
+ };
1419
1567
  return {
1420
1568
  site,
1421
1569
  handle: (request) => handle(request),
@@ -1442,12 +1590,18 @@ function reguardFetch(options = {}) {
1442
1590
  flush: async () => {
1443
1591
  await inflight;
1444
1592
  await flush();
1445
- }
1593
+ },
1594
+ visitor: (id) => api.visitor(id),
1595
+ events: (q) => api.events(q)
1446
1596
  };
1447
1597
  }
1448
1598
  // Annotate the CommonJS export names for ESM import in node:
1449
1599
  0 && (module.exports = {
1600
+ ReguardApiError,
1450
1601
  ReguardConfigError,
1602
+ ReguardWebhookError,
1451
1603
  defaultBlockAnswer,
1452
- reguardFetch
1604
+ reguardApi,
1605
+ reguardFetch,
1606
+ verifyWebhook
1453
1607
  });
@@ -20,14 +20,18 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ ReguardApiError: () => ReguardApiError,
23
24
  ReguardConfigError: () => ReguardConfigError,
25
+ ReguardWebhookError: () => WebhookSignatureError,
24
26
  createReDetect: () => createReDetect,
25
27
  default: () => index_default,
26
28
  defaultBlockResponse: () => defaultBlockResponse,
27
29
  formatSiteKey: () => formatSiteKey,
28
30
  keyFingerprint: () => keyFingerprint,
29
31
  parseSiteKey: () => parseSiteKey,
30
- reguard: () => reguard
32
+ reguard: () => reguard,
33
+ reguardApi: () => reguardApi,
34
+ verifyWebhook: () => verifyWebhook
31
35
  });
32
36
  module.exports = __toCommonJS(index_exports);
33
37
  var import_node_crypto = require("node:crypto");
@@ -718,12 +722,71 @@ function isSourceMapPath(p) {
718
722
  return /\.map$/i.test(p.raw) || /\.map$/i.test(p.decoded);
719
723
  }
720
724
 
725
+ // ../shared/src/webhooks.ts
726
+ var WEBHOOK_TOLERANCE_SECONDS = 300;
727
+ var WebhookSignatureError = class extends Error {
728
+ constructor(code, message) {
729
+ super(message);
730
+ this.code = code;
731
+ this.name = "ReguardWebhookError";
732
+ }
733
+ };
734
+ var enc2 = new TextEncoder();
735
+ function hmacKey2(secret) {
736
+ return crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
737
+ }
738
+ function signedBytes(timestamp, payload) {
739
+ const head = enc2.encode(`${timestamp}.`);
740
+ const body = typeof payload === "string" ? enc2.encode(payload) : payload;
741
+ const out = new Uint8Array(new ArrayBuffer(head.length + body.length));
742
+ out.set(head, 0);
743
+ out.set(body, head.length);
744
+ return out;
745
+ }
746
+ function unhex(s) {
747
+ const out = new Uint8Array(new ArrayBuffer(s.length / 2));
748
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
749
+ return out;
750
+ }
751
+ function parseWebhookSignature(header2) {
752
+ let t;
753
+ const v1 = [];
754
+ for (const part of header2.split(",")) {
755
+ const i = part.indexOf("=");
756
+ if (i < 1) continue;
757
+ const k = part.slice(0, i).trim();
758
+ const v = part.slice(i + 1).trim();
759
+ if (k === "t" && /^\d{1,12}$/.test(v)) t = Number(v);
760
+ else if (k === "v1" && /^[0-9a-f]{64}$/.test(v)) v1.push(v);
761
+ }
762
+ return t === void 0 || !v1.length ? null : { t, v1 };
763
+ }
764
+ async function verifyWebhookSignature(payload, header2, secret, options = {}) {
765
+ if (!secret) throw new WebhookSignatureError("missing_secret", "No webhook signing secret: pass it, or set REGUARD_WEBHOOK_SECRET.");
766
+ if (!header2) throw new WebhookSignatureError("missing_signature", "No Reguard-Signature header on this request.");
767
+ const parsed = parseWebhookSignature(header2);
768
+ if (!parsed) throw new WebhookSignatureError("malformed_signature", "The Reguard-Signature header isn't in the form t=\u2026,v1=\u2026.");
769
+ const tolerance = options.tolerance ?? WEBHOOK_TOLERANCE_SECONDS;
770
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
771
+ if (tolerance > 0 && Math.abs(now - parsed.t) > tolerance) {
772
+ throw new WebhookSignatureError("expired", `The delivery is signed ${Math.abs(now - parsed.t)} s from now, more than the ${tolerance} s allowed (a replay, or a clock that's off).`);
773
+ }
774
+ const key = await hmacKey2(secret);
775
+ const data = signedBytes(parsed.t, payload);
776
+ for (const sig of parsed.v1) {
777
+ if (await crypto.subtle.verify("HMAC", key, unhex(sig), data)) return;
778
+ }
779
+ throw new WebhookSignatureError("bad_signature", "The signature doesn't match: check the signing secret, and pass the raw request body.");
780
+ }
781
+
721
782
  // src/core.ts
722
783
  var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
784
+ var visitorIdOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
723
785
  function withFlagged(p, source = "browser") {
724
786
  return {
725
787
  ...p,
726
788
  source,
789
+ visitor: visitorIdOf(p.vid) ?? null,
727
790
  flagged({ labels, minStage = "candidate" } = {}) {
728
791
  const want = typeof labels === "string" ? [labels] : labels?.length ? labels : void 0;
729
792
  const rank = STAGE_RANK[minStage] ?? 0;
@@ -736,8 +799,9 @@ function mergeVerdicts(browser, pushed) {
736
799
  if (!browser) return withFlagged(pushed, "server");
737
800
  const rules = new Set(browser.claims.map((c) => `${c.rule}|${c.label}|${c.stage}`));
738
801
  const claims = [...browser.claims, ...pushed.claims.filter((c) => !rules.has(`${c.rule}|${c.label}|${c.stage}`))];
739
- const { source: _s, flagged: _f, ...payload } = browser;
740
- return withFlagged({ ...payload, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
802
+ const { source: _s, flagged: _f, visitor: _v, ...payload } = browser;
803
+ const vid = visitorIdOf(payload.vid) ?? visitorIdOf(pushed.vid);
804
+ return withFlagged({ ...payload, ...vid ? { vid } : {}, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
741
805
  }
742
806
  async function readVerdictFrom(secret, site, cookieHeader) {
743
807
  const token = cookieValue(cookieHeader, VERDICT_COOKIE);
@@ -776,8 +840,8 @@ function freshSeconds(cfg) {
776
840
  function verdictAgeMs(v, now = Date.now()) {
777
841
  return now - (v.exp - VERDICT_TTL_MS);
778
842
  }
779
- function pushedVerdict(sid, site, claims, now = Date.now()) {
780
- return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4 }, "server");
843
+ function pushedVerdict(sid, site, claims, now = Date.now(), vid) {
844
+ return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4, ...vid ? { vid } : {} }, "server");
781
845
  }
782
846
  var ANSWER_CODES = { flagged: "reguard.blocked", flagged_server: "reguard.blocked", require: "reguard.require", pace: "reguard.pace" };
783
847
  var RETRY_AFTER = { flagged: 120, flagged_server: 120, require: 5, pace: 2 };
@@ -1153,6 +1217,68 @@ var Health = class {
1153
1217
  }
1154
1218
  };
1155
1219
 
1220
+ // src/api.ts
1221
+ var ReguardApiError = class extends Error {
1222
+ constructor(status, message) {
1223
+ super(message);
1224
+ this.status = status;
1225
+ this.name = "ReguardApiError";
1226
+ }
1227
+ };
1228
+ function reguardApi(options = {}) {
1229
+ const key = (options.key?.trim() || envValue("REGUARD_KEY"))?.trim();
1230
+ if (options.key?.trim() && !parseSiteKey(options.key.trim())?.site) throw new TypeError("[reguard] reguardApi: key must be a site key (rgk.<site>.v<n>.\u2026)");
1231
+ const base = collectorBase(options.collector || envValue("REGUARD_COLLECTOR"));
1232
+ const doFetch = options.fetch ?? fetch;
1233
+ const timeoutMs = options.timeoutMs ?? 1e4;
1234
+ async function get(path) {
1235
+ if (!key) throw new ReguardApiError(0, "No site key: pass { key } or set REGUARD_KEY.");
1236
+ if (!parseSiteKey(key)?.site) throw new ReguardApiError(0, "REGUARD_KEY isn't a site key (rgk.<site>.v<n>.\u2026).");
1237
+ let res;
1238
+ try {
1239
+ res = await doFetch(`${base}${path}`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
1240
+ } catch (e) {
1241
+ throw new ReguardApiError(0, `Reguard's API can't be reached: ${e.message}`);
1242
+ }
1243
+ const parsed = await res.json().catch(() => null);
1244
+ const body = parsed && typeof parsed === "object" ? parsed : {};
1245
+ if (!res.ok) throw new ReguardApiError(res.status, typeof body.error === "string" && body.error ? body.error : `Reguard's API answered ${res.status}`);
1246
+ return body;
1247
+ }
1248
+ return {
1249
+ async visitor(id) {
1250
+ if (!visitorIdOf(id)) throw new ReguardApiError(400, "Not a visitor id: they look like vis_ followed by 22 characters.");
1251
+ return (await get(`/v1/visitors/${id}`)).visitor;
1252
+ },
1253
+ events({ after, limit, types } = {}) {
1254
+ const q = new URLSearchParams();
1255
+ if (after) q.set("after", after);
1256
+ if (typeof limit === "number" && Number.isInteger(limit) && limit > 0) q.set("limit", String(limit));
1257
+ if (types?.length) q.set("type", types.join(","));
1258
+ const qs = q.toString();
1259
+ return get(`/v1/events${qs ? `?${qs}` : ""}`);
1260
+ }
1261
+ };
1262
+ }
1263
+ async function verifyWebhook(payload, signature, secret, options = {}) {
1264
+ if (typeof payload !== "string" && !(payload instanceof Uint8Array) && !(payload instanceof ArrayBuffer)) {
1265
+ throw new TypeError(
1266
+ '[reguard] verifyWebhook needs the raw request body (a string or bytes), not parsed JSON: in Express, use express.raw({ type: "application/json" }) on this route.'
1267
+ );
1268
+ }
1269
+ const raw = payload instanceof ArrayBuffer ? new Uint8Array(payload) : payload;
1270
+ const header2 = Array.isArray(signature) ? signature[0] : signature;
1271
+ await verifyWebhookSignature(raw, header2, secret || envValue("REGUARD_WEBHOOK_SECRET"), options);
1272
+ let event;
1273
+ try {
1274
+ event = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw));
1275
+ } catch {
1276
+ throw new WebhookSignatureError("bad_payload", "The body isn't JSON (a Slack or Discord URL gets messages, not events).");
1277
+ }
1278
+ if (!event || typeof event.id !== "string" || typeof event.type !== "string") throw new WebhookSignatureError("bad_payload", "The body isn't a Reguard event.");
1279
+ return event;
1280
+ }
1281
+
1156
1282
  // src/index.ts
1157
1283
  var PREFIX = "/_s";
1158
1284
  var NOT_FORWARDED = /* @__PURE__ */ new Set([
@@ -1278,6 +1404,11 @@ function reguard(options = {}) {
1278
1404
  };
1279
1405
  passthrough.close = async () => {
1280
1406
  };
1407
+ const off = async () => {
1408
+ throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
1409
+ };
1410
+ passthrough.visitor = off;
1411
+ passthrough.events = off;
1281
1412
  return passthrough;
1282
1413
  }
1283
1414
  const site = parsed.site;
@@ -1630,6 +1761,9 @@ function reguard(options = {}) {
1630
1761
  });
1631
1762
  const blocking = !blockCfg ? "off" : allDry ? "dry run" : blockCfg.dryRun.size ? "partial dry run" : "on";
1632
1763
  Object.defineProperty(middleware, "site", { value: site });
1764
+ const api = reguardApi({ key, collector, fetch: doFetch, timeoutMs: o.timeoutMs });
1765
+ middleware.visitor = (id) => api.visitor(id);
1766
+ middleware.events = (q) => api.events(q);
1633
1767
  middleware.scriptTag = (opts) => renderScriptTag(tagSettings, opts?.nonce);
1634
1768
  middleware.status = () => ({
1635
1769
  enabled: true,
@@ -1808,13 +1942,14 @@ function createReDetect(opts, wiring = {}) {
1808
1942
  let inflight;
1809
1943
  const pushed = /* @__PURE__ */ new Map();
1810
1944
  const PUSHED_TTL_MS = 10 * 6e4;
1945
+ const vidOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
1811
1946
  const isClaims = (c) => Array.isArray(c) && c.every((x) => !!x && typeof x.rule === "string" && typeof x.label === "string" && typeof x.stage === "string");
1812
1947
  const absorb = (body) => {
1813
1948
  const f = body?.flagged;
1814
1949
  if (!f) return;
1815
1950
  const now = Date.now();
1816
- for (const x of f.sessions ?? []) if (typeof x.sid === "string" && isClaims(x.claims)) pushed.set(`s:${x.sid}`, { claims: x.claims, until: now + PUSHED_TTL_MS });
1817
- for (const x of f.visitors ?? []) if (typeof x.visitor === "string" && isClaims(x.claims)) pushed.set(`v:${x.visitor}`, { claims: x.claims, until: now + PUSHED_TTL_MS });
1951
+ for (const x of f.sessions ?? []) if (typeof x.sid === "string" && isClaims(x.claims)) pushed.set(`s:${x.sid}`, { claims: x.claims, until: now + PUSHED_TTL_MS, vid: vidOf(x.vid) });
1952
+ for (const x of f.visitors ?? []) if (typeof x.visitor === "string" && isClaims(x.claims)) pushed.set(`v:${x.visitor}`, { claims: x.claims, until: now + PUSHED_TTL_MS, vid: vidOf(x.vid) });
1818
1953
  if (pushed.size > 5e4) {
1819
1954
  for (const [k, e] of pushed) if (e.until < now) pushed.delete(k);
1820
1955
  }
@@ -1826,11 +1961,15 @@ function createReDetect(opts, wiring = {}) {
1826
1961
  const address = collect.addresses !== "off" && !verified && !a.internal ? a.address : "";
1827
1962
  const now = Date.now();
1828
1963
  const claims = [];
1964
+ let vid;
1829
1965
  for (const k of [sid ? `s:${sid}` : "", address ? `v:${visitorHash(secret, address)}` : ""]) {
1830
1966
  const e = k ? pushed.get(k) : void 0;
1831
- if (e && e.until > now) claims.push(...e.claims);
1967
+ if (e && e.until > now) {
1968
+ claims.push(...e.claims);
1969
+ vid ??= e.vid;
1970
+ }
1832
1971
  }
1833
- return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now) : null;
1972
+ return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now, vid) : null;
1834
1973
  };
1835
1974
  const flush = async () => {
1836
1975
  while (queue.length) {
@@ -2064,11 +2203,15 @@ function createReDetect(opts, wiring = {}) {
2064
2203
  }
2065
2204
  // Annotate the CommonJS export names for ESM import in node:
2066
2205
  0 && (module.exports = {
2206
+ ReguardApiError,
2067
2207
  ReguardConfigError,
2208
+ ReguardWebhookError,
2068
2209
  createReDetect,
2069
2210
  defaultBlockResponse,
2070
2211
  formatSiteKey,
2071
2212
  keyFingerprint,
2072
2213
  parseSiteKey,
2073
- reguard
2214
+ reguard,
2215
+ reguardApi,
2216
+ verifyWebhook
2074
2217
  });