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
package/README.md CHANGED
@@ -33,7 +33,27 @@ app.get("/api/export", (req, res) => {
33
33
  ```
34
34
 
35
35
  `req.reguard` is the visitor's verified verdict (or `null`): its `claims`, where they came from
36
- (`source`: the browser, your server's summaries, or both) and `flagged({ labels, minStage })`.
36
+ (`source`: the browser, your server's summaries, or both), `flagged({ labels, minStage })`, and
37
+ `visitor`, Reguard's id for the visitor across its page loads. It's signed, so trust it over any
38
+ cookie: store it with your user's session, look it up, or match it to webhook events.
39
+
40
+ ## Visitors and webhooks
41
+
42
+ ```js
43
+ import { reguardApi, verifyWebhook } from "reguard";
44
+
45
+ const v = await reguardApi().visitor(req.reguard.visitor); // REGUARD_KEY from the environment
46
+ if (v.caught) { /* v.labels, v.stage, v.catches, v.returns */ }
47
+
48
+ app.post("/hooks/reguard", express.raw({ type: "application/json" }), async (req, res) => {
49
+ const event = await verifyWebhook(req.body, req.headers["reguard-signature"]); // REGUARD_WEBHOOK_SECRET
50
+ // event.type: "visitor.caught", "visitor.escalated", "visitor.returned" or "ping"
51
+ res.sendStatus(204);
52
+ });
53
+ ```
54
+
55
+ Add webhook URLs under Settings, Notifications. Prefer polling? `reguardApi().events({ after })`
56
+ returns the same events, oldest first, with a cursor.
37
57
 
38
58
  ## Block: dry run first
39
59
 
@@ -71,6 +91,8 @@ const cookie = await verdictCookie(key, { claims: [claim("unauthorized_extractio
71
91
  await request(app).get("/api/items").set("cookie", cookie).expect(429);
72
92
  ```
73
93
 
94
+ `signWebhook(secret, body)` signs a made-up delivery for testing your webhook handler.
95
+
74
96
  ## More
75
97
 
76
98
  - Choose what Reguard receives with `collect` (pages, addresses, behavior, requests, skip).
@@ -529,9 +529,9 @@ function formatIp(b) {
529
529
  }
530
530
  i = j;
531
531
  }
532
- const hex = (xs) => xs.map((x) => x.toString(16)).join(":");
533
- if (best === -1) return hex(g);
534
- return `${hex(g.slice(0, best))}::${hex(g.slice(best + bestLen))}`;
532
+ const hex2 = (xs) => xs.map((x) => x.toString(16)).join(":");
533
+ if (best === -1) return hex2(g);
534
+ return `${hex2(g.slice(0, best))}::${hex2(g.slice(best + bestLen))}`;
535
535
  }
536
536
  function normalizeIp(token) {
537
537
  if (!token) return null;
@@ -692,12 +692,83 @@ function isSourceMapPath(p) {
692
692
  return /\.map$/i.test(p.raw) || /\.map$/i.test(p.decoded);
693
693
  }
694
694
 
695
+ // ../shared/src/webhooks.ts
696
+ var WEBHOOK_TOLERANCE_SECONDS = 300;
697
+ var WebhookSignatureError = class extends Error {
698
+ constructor(code, message) {
699
+ super(message);
700
+ this.code = code;
701
+ this.name = "ReguardWebhookError";
702
+ }
703
+ };
704
+ var enc2 = new TextEncoder();
705
+ function hmacKey2(secret) {
706
+ return crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
707
+ }
708
+ function signedBytes(timestamp, payload) {
709
+ const head = enc2.encode(`${timestamp}.`);
710
+ const body = typeof payload === "string" ? enc2.encode(payload) : payload;
711
+ const out = new Uint8Array(new ArrayBuffer(head.length + body.length));
712
+ out.set(head, 0);
713
+ out.set(body, head.length);
714
+ return out;
715
+ }
716
+ function hex(bytes) {
717
+ return [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
718
+ }
719
+ function unhex(s) {
720
+ const out = new Uint8Array(new ArrayBuffer(s.length / 2));
721
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
722
+ return out;
723
+ }
724
+ async function signWebhookPayload(secrets, payload, timestamp) {
725
+ const t = Math.floor(timestamp);
726
+ const data = signedBytes(t, payload);
727
+ const sigs = [];
728
+ for (const secret of typeof secrets === "string" ? [secrets] : secrets) {
729
+ sigs.push(`v1=${hex(await crypto.subtle.sign("HMAC", await hmacKey2(secret), data))}`);
730
+ }
731
+ return [`t=${t}`, ...sigs].join(",");
732
+ }
733
+ function parseWebhookSignature(header) {
734
+ let t;
735
+ const v1 = [];
736
+ for (const part of header.split(",")) {
737
+ const i = part.indexOf("=");
738
+ if (i < 1) continue;
739
+ const k = part.slice(0, i).trim();
740
+ const v = part.slice(i + 1).trim();
741
+ if (k === "t" && /^\d{1,12}$/.test(v)) t = Number(v);
742
+ else if (k === "v1" && /^[0-9a-f]{64}$/.test(v)) v1.push(v);
743
+ }
744
+ return t === void 0 || !v1.length ? null : { t, v1 };
745
+ }
746
+ async function verifyWebhookSignature(payload, header, secret, options = {}) {
747
+ if (!secret) throw new WebhookSignatureError("missing_secret", "No webhook signing secret: pass it, or set REGUARD_WEBHOOK_SECRET.");
748
+ if (!header) throw new WebhookSignatureError("missing_signature", "No Reguard-Signature header on this request.");
749
+ const parsed = parseWebhookSignature(header);
750
+ if (!parsed) throw new WebhookSignatureError("malformed_signature", "The Reguard-Signature header isn't in the form t=\u2026,v1=\u2026.");
751
+ const tolerance = options.tolerance ?? WEBHOOK_TOLERANCE_SECONDS;
752
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
753
+ if (tolerance > 0 && Math.abs(now - parsed.t) > tolerance) {
754
+ 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).`);
755
+ }
756
+ const key = await hmacKey2(secret);
757
+ const data = signedBytes(parsed.t, payload);
758
+ for (const sig of parsed.v1) {
759
+ if (await crypto.subtle.verify("HMAC", key, unhex(sig), data)) return;
760
+ }
761
+ throw new WebhookSignatureError("bad_signature", "The signature doesn't match: check the signing secret, and pass the raw request body.");
762
+ }
763
+
695
764
  // src/core.ts
696
765
  var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
766
+ var visitorIdOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
697
767
  function withFlagged(p, source = "browser") {
698
768
  return {
699
769
  ...p,
700
770
  source,
771
+ visitor: visitorIdOf(p.vid) ?? null,
701
772
  flagged({ labels, minStage = "candidate" } = {}) {
702
773
  const want = typeof labels === "string" ? [labels] : labels?.length ? labels : void 0;
703
774
  const rank = STAGE_RANK[minStage] ?? 0;
@@ -710,8 +781,9 @@ function mergeVerdicts(browser, pushed) {
710
781
  if (!browser) return withFlagged(pushed, "server");
711
782
  const rules = new Set(browser.claims.map((c) => `${c.rule}|${c.label}|${c.stage}`));
712
783
  const claims = [...browser.claims, ...pushed.claims.filter((c) => !rules.has(`${c.rule}|${c.label}|${c.stage}`))];
713
- const { source: _s, flagged: _f, ...payload } = browser;
714
- return withFlagged({ ...payload, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
784
+ const { source: _s, flagged: _f, visitor: _v, ...payload } = browser;
785
+ const vid = visitorIdOf(payload.vid) ?? visitorIdOf(pushed.vid);
786
+ return withFlagged({ ...payload, ...vid ? { vid } : {}, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
715
787
  }
716
788
  async function readVerdictFrom(secret, site, cookieHeader) {
717
789
  const token = cookieValue(cookieHeader, VERDICT_COOKIE);
@@ -750,8 +822,8 @@ function freshSeconds(cfg) {
750
822
  function verdictAgeMs(v, now = Date.now()) {
751
823
  return now - (v.exp - VERDICT_TTL_MS);
752
824
  }
753
- function pushedVerdict(sid, site, claims, now = Date.now()) {
754
- return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4 }, "server");
825
+ function pushedVerdict(sid, site, claims, now = Date.now(), vid) {
826
+ return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4, ...vid ? { vid } : {} }, "server");
755
827
  }
756
828
  var ANSWER_CODES = { flagged: "reguard.blocked", flagged_server: "reguard.blocked", require: "reguard.require", pace: "reguard.pace" };
757
829
  var RETRY_AFTER = { flagged: 120, flagged_server: 120, require: 5, pace: 2 };
@@ -828,6 +900,10 @@ export {
828
900
  matchesEither,
829
901
  matchesBoth,
830
902
  isSourceMapPath,
903
+ WebhookSignatureError,
904
+ signWebhookPayload,
905
+ verifyWebhookSignature,
906
+ visitorIdOf,
831
907
  mergeVerdicts,
832
908
  readVerdictFrom,
833
909
  looksCurrent,
@@ -1,10 +1,12 @@
1
1
  import {
2
2
  BLOCK_REASONS,
3
3
  Health,
4
+ ReguardApiError,
4
5
  ReguardConfigError,
5
6
  checkOptions,
6
- makeLog
7
- } from "./chunk-3AYS7WSY.js";
7
+ makeLog,
8
+ reguardApi
9
+ } from "./chunk-W4FDH5AD.js";
8
10
  import {
9
11
  Allowance,
10
12
  BENIGN_TOOL_FAMILIES,
@@ -45,7 +47,7 @@ import {
45
47
  verdictAgeMs,
46
48
  wantsPage,
47
49
  watchworthy
48
- } from "./chunk-PA46KSOR.js";
50
+ } from "./chunk-CGXTVKRB.js";
49
51
 
50
52
  // src/index.ts
51
53
  import { createHash, createHmac } from "node:crypto";
@@ -175,6 +177,11 @@ function reguard(options = {}) {
175
177
  };
176
178
  passthrough.close = async () => {
177
179
  };
180
+ const off = async () => {
181
+ throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
182
+ };
183
+ passthrough.visitor = off;
184
+ passthrough.events = off;
178
185
  return passthrough;
179
186
  }
180
187
  const site = parsed.site;
@@ -527,6 +534,9 @@ function reguard(options = {}) {
527
534
  });
528
535
  const blocking = !blockCfg ? "off" : allDry ? "dry run" : blockCfg.dryRun.size ? "partial dry run" : "on";
529
536
  Object.defineProperty(middleware, "site", { value: site });
537
+ const api = reguardApi({ key, collector, fetch: doFetch, timeoutMs: o.timeoutMs });
538
+ middleware.visitor = (id) => api.visitor(id);
539
+ middleware.events = (q) => api.events(q);
530
540
  middleware.scriptTag = (opts) => renderScriptTag(tagSettings, opts?.nonce);
531
541
  middleware.status = () => ({
532
542
  enabled: true,
@@ -705,13 +715,14 @@ function createReDetect(opts, wiring = {}) {
705
715
  let inflight;
706
716
  const pushed = /* @__PURE__ */ new Map();
707
717
  const PUSHED_TTL_MS = 10 * 6e4;
718
+ const vidOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
708
719
  const isClaims = (c) => Array.isArray(c) && c.every((x) => !!x && typeof x.rule === "string" && typeof x.label === "string" && typeof x.stage === "string");
709
720
  const absorb = (body) => {
710
721
  const f = body?.flagged;
711
722
  if (!f) return;
712
723
  const now = Date.now();
713
- 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 });
714
- 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 });
724
+ 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) });
725
+ 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) });
715
726
  if (pushed.size > 5e4) {
716
727
  for (const [k, e] of pushed) if (e.until < now) pushed.delete(k);
717
728
  }
@@ -723,11 +734,15 @@ function createReDetect(opts, wiring = {}) {
723
734
  const address = collect.addresses !== "off" && !verified && !a.internal ? a.address : "";
724
735
  const now = Date.now();
725
736
  const claims = [];
737
+ let vid;
726
738
  for (const k of [sid ? `s:${sid}` : "", address ? `v:${visitorHash(secret, address)}` : ""]) {
727
739
  const e = k ? pushed.get(k) : void 0;
728
- if (e && e.until > now) claims.push(...e.claims);
740
+ if (e && e.until > now) {
741
+ claims.push(...e.claims);
742
+ vid ??= e.vid;
743
+ }
729
744
  }
730
- return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now) : null;
745
+ return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now, vid) : null;
731
746
  };
732
747
  const flush = async () => {
733
748
  while (queue.length) {
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  BLOCK_REASONS,
3
3
  Health,
4
+ ReguardApiError,
4
5
  ReguardConfigError,
5
6
  checkBlock,
6
7
  checkBoolean,
@@ -11,8 +12,9 @@ import {
11
12
  checkFunction,
12
13
  checkLogger,
13
14
  checkNumber,
14
- makeLog
15
- } from "./chunk-3AYS7WSY.js";
15
+ makeLog,
16
+ reguardApi
17
+ } from "./chunk-W4FDH5AD.js";
16
18
  import {
17
19
  Allowance,
18
20
  BENIGN_TOOL_FAMILIES,
@@ -47,7 +49,7 @@ import {
47
49
  toolOf,
48
50
  wantsPage,
49
51
  watchworthy
50
- } from "./chunk-PA46KSOR.js";
52
+ } from "./chunk-CGXTVKRB.js";
51
53
 
52
54
  // src/fetch.ts
53
55
  var OPTION_KEYS = [
@@ -131,6 +133,12 @@ function reguardFetch(options = {}) {
131
133
  decision: () => null,
132
134
  scriptTag: () => "",
133
135
  flush: async () => {
136
+ },
137
+ visitor: async () => {
138
+ throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
139
+ },
140
+ events: async () => {
141
+ throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
134
142
  }
135
143
  };
136
144
  }
@@ -139,6 +147,7 @@ function reguardFetch(options = {}) {
139
147
  const prev = parseSiteKey((options.previousKey ?? envValue("REGUARD_KEY_PREVIOUS"))?.trim());
140
148
  if (prev?.site === site && prev.secret !== parsed.secret) secrets.push(prev.secret);
141
149
  const collector = collectorBase(options.collector ?? envValue("REGUARD_COLLECTOR"));
150
+ const api = reguardApi({ key, collector, fetch: doFetch, timeoutMs });
142
151
  const platform = options.platform ?? detectPlatform(typeof process !== "undefined" ? process.env : void 0) ?? (typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" ? "workers" : null);
143
152
  const health = new Health(log);
144
153
  const allDry = !block || BLOCK_REASONS.every((r) => block.dryRun.has(r));
@@ -190,8 +199,9 @@ function reguardFetch(options = {}) {
190
199
  health.ok();
191
200
  const f = (await res.json().catch(() => null))?.flagged;
192
201
  const now = Date.now();
193
- 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 });
194
- 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 });
202
+ const vidOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
203
+ 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) });
204
+ 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) });
195
205
  if (pushed.size > 5e4) pushed.clear();
196
206
  }
197
207
  if (!res.ok) onError(new Error(`collector answered ${res.status} to /v1/server`));
@@ -216,11 +226,15 @@ function reguardFetch(options = {}) {
216
226
  const claims = [];
217
227
  const k = [sid ? `s:${sid}` : ""];
218
228
  if (collect.addresses !== "off" && !verified && !a.internal && a.address) k.push(`v:${await hmac(parsed.secret, `visitor:${a.address}`, 22)}`);
229
+ let vid;
219
230
  for (const x of k) {
220
231
  const e = x ? pushed.get(x) : void 0;
221
- if (e && e.until > now) claims.push(...e.claims);
232
+ if (e && e.until > now) {
233
+ claims.push(...e.claims);
234
+ vid ??= e.vid;
235
+ }
222
236
  }
223
- return claims.length ? pushedVerdict(sid ?? "", site, claims, now) : null;
237
+ return claims.length ? pushedVerdict(sid ?? "", site, claims, now, vid) : null;
224
238
  };
225
239
  const proxy = async (request, p) => {
226
240
  const url = new URL(request.url);
@@ -394,14 +408,24 @@ function reguardFetch(options = {}) {
394
408
  ...a.internal ? { internal: true } : {}
395
409
  });
396
410
  if (queue.length > 5e3) queue.splice(0, queue.length - 5e3);
397
- flushSoon(ctx?.waitUntil, !!decision);
411
+ const waitUntil = ctx?.waitUntil ? (p2) => ctx.waitUntil.call(ctx, p2) : void 0;
412
+ ensureTimer();
413
+ flushSoon(waitUntil, !!decision);
398
414
  } catch (e) {
399
415
  onError(e);
400
416
  }
401
417
  })();
402
418
  };
403
- const timer = typeof setInterval === "function" ? setInterval(() => flushSoon(void 0, true), flushIntervalMs) : void 0;
404
- timer?.unref?.();
419
+ let timer;
420
+ const ensureTimer = () => {
421
+ if (timer !== void 0 || platform === "workers" || typeof setInterval !== "function") return;
422
+ try {
423
+ timer = setInterval(() => flushSoon(void 0, true), flushIntervalMs);
424
+ timer.unref?.();
425
+ } catch {
426
+ timer = null;
427
+ }
428
+ };
405
429
  return {
406
430
  site,
407
431
  handle: (request) => handle(request),
@@ -428,7 +452,9 @@ function reguardFetch(options = {}) {
428
452
  flush: async () => {
429
453
  await inflight;
430
454
  await flush();
431
- }
455
+ },
456
+ visitor: (id) => api.visitor(id),
457
+ events: (q) => api.events(q)
432
458
  };
433
459
  }
434
460
 
@@ -1,8 +1,14 @@
1
1
  import {
2
2
  DEFAULT_PACE,
3
+ WebhookSignatureError,
3
4
  clientIpModeProblem,
4
- resolveCollect
5
- } from "./chunk-PA46KSOR.js";
5
+ collectorBase,
6
+ envValue,
7
+ parseSiteKey,
8
+ resolveCollect,
9
+ verifyWebhookSignature,
10
+ visitorIdOf
11
+ } from "./chunk-CGXTVKRB.js";
6
12
 
7
13
  // src/config.ts
8
14
  var ReguardConfigError = class extends TypeError {
@@ -332,6 +338,68 @@ var Health = class {
332
338
  }
333
339
  };
334
340
 
341
+ // src/api.ts
342
+ var ReguardApiError = class extends Error {
343
+ constructor(status, message) {
344
+ super(message);
345
+ this.status = status;
346
+ this.name = "ReguardApiError";
347
+ }
348
+ };
349
+ function reguardApi(options = {}) {
350
+ const key = (options.key?.trim() || envValue("REGUARD_KEY"))?.trim();
351
+ 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)");
352
+ const base = collectorBase(options.collector || envValue("REGUARD_COLLECTOR"));
353
+ const doFetch = options.fetch ?? fetch;
354
+ const timeoutMs = options.timeoutMs ?? 1e4;
355
+ async function get(path) {
356
+ if (!key) throw new ReguardApiError(0, "No site key: pass { key } or set REGUARD_KEY.");
357
+ if (!parseSiteKey(key)?.site) throw new ReguardApiError(0, "REGUARD_KEY isn't a site key (rgk.<site>.v<n>.\u2026).");
358
+ let res;
359
+ try {
360
+ res = await doFetch(`${base}${path}`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
361
+ } catch (e) {
362
+ throw new ReguardApiError(0, `Reguard's API can't be reached: ${e.message}`);
363
+ }
364
+ const parsed = await res.json().catch(() => null);
365
+ const body = parsed && typeof parsed === "object" ? parsed : {};
366
+ if (!res.ok) throw new ReguardApiError(res.status, typeof body.error === "string" && body.error ? body.error : `Reguard's API answered ${res.status}`);
367
+ return body;
368
+ }
369
+ return {
370
+ async visitor(id) {
371
+ if (!visitorIdOf(id)) throw new ReguardApiError(400, "Not a visitor id: they look like vis_ followed by 22 characters.");
372
+ return (await get(`/v1/visitors/${id}`)).visitor;
373
+ },
374
+ events({ after, limit, types } = {}) {
375
+ const q = new URLSearchParams();
376
+ if (after) q.set("after", after);
377
+ if (typeof limit === "number" && Number.isInteger(limit) && limit > 0) q.set("limit", String(limit));
378
+ if (types?.length) q.set("type", types.join(","));
379
+ const qs = q.toString();
380
+ return get(`/v1/events${qs ? `?${qs}` : ""}`);
381
+ }
382
+ };
383
+ }
384
+ async function verifyWebhook(payload, signature, secret, options = {}) {
385
+ if (typeof payload !== "string" && !(payload instanceof Uint8Array) && !(payload instanceof ArrayBuffer)) {
386
+ throw new TypeError(
387
+ '[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.'
388
+ );
389
+ }
390
+ const raw = payload instanceof ArrayBuffer ? new Uint8Array(payload) : payload;
391
+ const header = Array.isArray(signature) ? signature[0] : signature;
392
+ await verifyWebhookSignature(raw, header, secret || envValue("REGUARD_WEBHOOK_SECRET"), options);
393
+ let event;
394
+ try {
395
+ event = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw));
396
+ } catch {
397
+ throw new WebhookSignatureError("bad_payload", "The body isn't JSON (a Slack or Discord URL gets messages, not events).");
398
+ }
399
+ if (!event || typeof event.id !== "string" || typeof event.type !== "string") throw new WebhookSignatureError("bad_payload", "The body isn't a Reguard event.");
400
+ return event;
401
+ }
402
+
335
403
  export {
336
404
  ReguardConfigError,
337
405
  BLOCK_REASONS,
@@ -346,5 +414,8 @@ export {
346
414
  checkBlock,
347
415
  checkOptions,
348
416
  makeLog,
349
- Health
417
+ Health,
418
+ ReguardApiError,
419
+ reguardApi,
420
+ verifyWebhook
350
421
  };
@@ -712,12 +712,17 @@ function isSourceMapPath(p) {
712
712
  return /\.map$/i.test(p.raw) || /\.map$/i.test(p.decoded);
713
713
  }
714
714
 
715
+ // ../shared/src/webhooks.ts
716
+ var enc2 = new TextEncoder();
717
+
715
718
  // src/core.ts
716
719
  var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
720
+ var visitorIdOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
717
721
  function withFlagged(p, source = "browser") {
718
722
  return {
719
723
  ...p,
720
724
  source,
725
+ visitor: visitorIdOf(p.vid) ?? null,
721
726
  flagged({ labels, minStage = "candidate" } = {}) {
722
727
  const want = typeof labels === "string" ? [labels] : labels?.length ? labels : void 0;
723
728
  const rank = STAGE_RANK[minStage] ?? 0;
@@ -730,8 +735,9 @@ function mergeVerdicts(browser, pushed) {
730
735
  if (!browser) return withFlagged(pushed, "server");
731
736
  const rules = new Set(browser.claims.map((c) => `${c.rule}|${c.label}|${c.stage}`));
732
737
  const claims = [...browser.claims, ...pushed.claims.filter((c) => !rules.has(`${c.rule}|${c.label}|${c.stage}`))];
733
- const { source: _s, flagged: _f, ...payload } = browser;
734
- return withFlagged({ ...payload, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
738
+ const { source: _s, flagged: _f, visitor: _v, ...payload } = browser;
739
+ const vid = visitorIdOf(payload.vid) ?? visitorIdOf(pushed.vid);
740
+ return withFlagged({ ...payload, ...vid ? { vid } : {}, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
735
741
  }
736
742
  async function readVerdictFrom(secret, site, cookieHeader) {
737
743
  const token = cookieValue(cookieHeader, VERDICT_COOKIE);
@@ -770,8 +776,8 @@ function freshSeconds(cfg) {
770
776
  function verdictAgeMs(v, now = Date.now()) {
771
777
  return now - (v.exp - VERDICT_TTL_MS);
772
778
  }
773
- function pushedVerdict(sid, site, claims, now = Date.now()) {
774
- return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4 }, "server");
779
+ function pushedVerdict(sid, site, claims, now = Date.now(), vid) {
780
+ return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4, ...vid ? { vid } : {} }, "server");
775
781
  }
776
782
  var ANSWER_CODES = { flagged: "reguard.blocked", flagged_server: "reguard.blocked", require: "reguard.require", pace: "reguard.pace" };
777
783
  var RETRY_AFTER = { flagged: 120, flagged_server: 120, require: 5, pace: 2 };
@@ -1147,6 +1153,50 @@ var Health = class {
1147
1153
  }
1148
1154
  };
1149
1155
 
1156
+ // src/api.ts
1157
+ var ReguardApiError = class extends Error {
1158
+ constructor(status, message) {
1159
+ super(message);
1160
+ this.status = status;
1161
+ this.name = "ReguardApiError";
1162
+ }
1163
+ };
1164
+ function reguardApi(options = {}) {
1165
+ const key = (options.key?.trim() || envValue("REGUARD_KEY"))?.trim();
1166
+ 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)");
1167
+ const base = collectorBase(options.collector || envValue("REGUARD_COLLECTOR"));
1168
+ const doFetch = options.fetch ?? fetch;
1169
+ const timeoutMs = options.timeoutMs ?? 1e4;
1170
+ async function get(path) {
1171
+ if (!key) throw new ReguardApiError(0, "No site key: pass { key } or set REGUARD_KEY.");
1172
+ if (!parseSiteKey(key)?.site) throw new ReguardApiError(0, "REGUARD_KEY isn't a site key (rgk.<site>.v<n>.\u2026).");
1173
+ let res;
1174
+ try {
1175
+ res = await doFetch(`${base}${path}`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
1176
+ } catch (e) {
1177
+ throw new ReguardApiError(0, `Reguard's API can't be reached: ${e.message}`);
1178
+ }
1179
+ const parsed = await res.json().catch(() => null);
1180
+ const body = parsed && typeof parsed === "object" ? parsed : {};
1181
+ if (!res.ok) throw new ReguardApiError(res.status, typeof body.error === "string" && body.error ? body.error : `Reguard's API answered ${res.status}`);
1182
+ return body;
1183
+ }
1184
+ return {
1185
+ async visitor(id) {
1186
+ if (!visitorIdOf(id)) throw new ReguardApiError(400, "Not a visitor id: they look like vis_ followed by 22 characters.");
1187
+ return (await get(`/v1/visitors/${id}`)).visitor;
1188
+ },
1189
+ events({ after, limit, types } = {}) {
1190
+ const q = new URLSearchParams();
1191
+ if (after) q.set("after", after);
1192
+ if (typeof limit === "number" && Number.isInteger(limit) && limit > 0) q.set("limit", String(limit));
1193
+ if (types?.length) q.set("type", types.join(","));
1194
+ const qs = q.toString();
1195
+ return get(`/v1/events${qs ? `?${qs}` : ""}`);
1196
+ }
1197
+ };
1198
+ }
1199
+
1150
1200
  // src/index.ts
1151
1201
  var PREFIX = "/_s";
1152
1202
  var NOT_FORWARDED = /* @__PURE__ */ new Set([
@@ -1272,6 +1322,11 @@ function reguard(options = {}) {
1272
1322
  };
1273
1323
  passthrough.close = async () => {
1274
1324
  };
1325
+ const off = async () => {
1326
+ throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
1327
+ };
1328
+ passthrough.visitor = off;
1329
+ passthrough.events = off;
1275
1330
  return passthrough;
1276
1331
  }
1277
1332
  const site = parsed.site;
@@ -1624,6 +1679,9 @@ function reguard(options = {}) {
1624
1679
  });
1625
1680
  const blocking = !blockCfg ? "off" : allDry ? "dry run" : blockCfg.dryRun.size ? "partial dry run" : "on";
1626
1681
  Object.defineProperty(middleware, "site", { value: site });
1682
+ const api = reguardApi({ key, collector, fetch: doFetch, timeoutMs: o.timeoutMs });
1683
+ middleware.visitor = (id) => api.visitor(id);
1684
+ middleware.events = (q) => api.events(q);
1627
1685
  middleware.scriptTag = (opts) => renderScriptTag(tagSettings, opts?.nonce);
1628
1686
  middleware.status = () => ({
1629
1687
  enabled: true,
@@ -1801,13 +1859,14 @@ function createReDetect(opts, wiring = {}) {
1801
1859
  let inflight;
1802
1860
  const pushed = /* @__PURE__ */ new Map();
1803
1861
  const PUSHED_TTL_MS = 10 * 6e4;
1862
+ const vidOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
1804
1863
  const isClaims = (c) => Array.isArray(c) && c.every((x) => !!x && typeof x.rule === "string" && typeof x.label === "string" && typeof x.stage === "string");
1805
1864
  const absorb = (body) => {
1806
1865
  const f = body?.flagged;
1807
1866
  if (!f) return;
1808
1867
  const now = Date.now();
1809
- 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 });
1810
- 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 });
1868
+ 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) });
1869
+ 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) });
1811
1870
  if (pushed.size > 5e4) {
1812
1871
  for (const [k, e] of pushed) if (e.until < now) pushed.delete(k);
1813
1872
  }
@@ -1819,11 +1878,15 @@ function createReDetect(opts, wiring = {}) {
1819
1878
  const address = collect.addresses !== "off" && !verified && !a.internal ? a.address : "";
1820
1879
  const now = Date.now();
1821
1880
  const claims = [];
1881
+ let vid;
1822
1882
  for (const k of [sid ? `s:${sid}` : "", address ? `v:${visitorHash(secret, address)}` : ""]) {
1823
1883
  const e = k ? pushed.get(k) : void 0;
1824
- if (e && e.until > now) claims.push(...e.claims);
1884
+ if (e && e.until > now) {
1885
+ claims.push(...e.claims);
1886
+ vid ??= e.vid;
1887
+ }
1825
1888
  }
1826
- return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now) : null;
1889
+ return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now, vid) : null;
1827
1890
  };
1828
1891
  const flush = async () => {
1829
1892
  while (queue.length) {