reguard 0.8.1 → 0.10.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.
Files changed (44) hide show
  1. package/README.md +25 -3
  2. package/dist/chunks/{chunk-PA46KSOR.js → chunk-2N762ZXU.js} +235 -44
  3. package/dist/chunks/{chunk-3AYS7WSY.js → chunk-4RD66ACT.js} +81 -8
  4. package/dist/chunks/{chunk-U54IP6G4.js → chunk-GOT54CF4.js} +61 -40
  5. package/dist/chunks/{chunk-KNKCUJL3.js → chunk-RTCPK4MF.js} +102 -41
  6. package/dist/cjs/fastify.cjs +305 -93
  7. package/dist/cjs/fetch.cjs +347 -87
  8. package/dist/cjs/index.cjs +386 -86
  9. package/dist/cjs/next.cjs +366 -103
  10. package/dist/cjs/testing.cjs +28 -100
  11. package/dist/fastify.js +4 -12
  12. package/dist/fetch.js +14 -5
  13. package/dist/index.js +13 -5
  14. package/dist/next.js +33 -23
  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/fastify.d.ts +15 -7
  19. package/dist/types/node/src/fetch.d.ts +12 -2
  20. package/dist/types/node/src/index.d.ts +6 -0
  21. package/dist/types/node/src/next.d.ts +39 -17
  22. package/dist/types/node/src/testing.d.ts +11 -0
  23. package/dist/types/shared/src/address.d.ts +25 -6
  24. package/dist/types/shared/src/collect.d.ts +7 -1
  25. package/dist/types/shared/src/index.d.ts +14 -0
  26. package/dist/types/shared/src/paths.d.ts +6 -2
  27. package/dist/types/shared/src/tools.d.ts +10 -0
  28. package/dist/types/shared/src/verdict.d.ts +6 -0
  29. package/dist/types/shared/src/webhooks.d.ts +32 -0
  30. package/dist/types-cjs/node/src/api.d.cts +139 -0
  31. package/dist/types-cjs/node/src/core.d.cts +8 -1
  32. package/dist/types-cjs/node/src/fastify.d.cts +15 -7
  33. package/dist/types-cjs/node/src/fetch.d.cts +12 -2
  34. package/dist/types-cjs/node/src/index.d.cts +6 -0
  35. package/dist/types-cjs/node/src/next.d.cts +39 -17
  36. package/dist/types-cjs/node/src/testing.d.cts +11 -0
  37. package/dist/types-cjs/shared/src/address.d.cts +25 -6
  38. package/dist/types-cjs/shared/src/collect.d.cts +7 -1
  39. package/dist/types-cjs/shared/src/index.d.cts +14 -0
  40. package/dist/types-cjs/shared/src/paths.d.cts +6 -2
  41. package/dist/types-cjs/shared/src/tools.d.cts +10 -0
  42. package/dist/types-cjs/shared/src/verdict.d.cts +6 -0
  43. package/dist/types-cjs/shared/src/webhooks.d.cts +32 -0
  44. package/package.json +3 -2
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var testing_exports = {};
22
22
  __export(testing_exports, {
23
23
  claim: () => claim,
24
+ signWebhook: () => signWebhook,
24
25
  testKey: () => testKey,
25
26
  verdictCookie: () => verdictCookie
26
27
  });
@@ -69,109 +70,31 @@ function parseSiteKey(key) {
69
70
  // ../shared/src/collect.ts
70
71
  var DEFAULT_COLLECT = Object.freeze({ pages: "masked", addresses: "hashed", behavior: true, requests: true, skip: [] });
71
72
 
72
- // ../shared/src/address.ts
73
- var CLOUDFLARE_RANGES = [
74
- "173.245.48.0/20",
75
- "103.21.244.0/22",
76
- "103.22.200.0/22",
77
- "103.31.4.0/22",
78
- "141.101.64.0/18",
79
- "108.162.192.0/18",
80
- "190.93.240.0/20",
81
- "188.114.96.0/20",
82
- "197.234.240.0/22",
83
- "198.41.128.0/17",
84
- "162.158.0.0/15",
85
- "104.16.0.0/13",
86
- "104.24.0.0/14",
87
- "172.64.0.0/13",
88
- "131.0.72.0/22",
89
- "2400:cb00::/32",
90
- "2606:4700::/32",
91
- "2803:f800::/32",
92
- "2405:b500::/32",
93
- "2405:8100::/32",
94
- "2a06:98c0::/29",
95
- "2c0f:f248::/32"
96
- ];
97
- var NON_PUBLIC_RANGES = [
98
- "0.0.0.0/8",
99
- "10.0.0.0/8",
100
- "100.64.0.0/10",
101
- "127.0.0.0/8",
102
- "169.254.0.0/16",
103
- "172.16.0.0/12",
104
- "192.168.0.0/16",
105
- "::/128",
106
- "::1/128",
107
- "fc00::/7",
108
- "fe80::/10"
109
- ];
110
- function parseIpv4(s) {
111
- const parts = s.split(".");
112
- if (parts.length !== 4) return null;
113
- const out = [];
114
- for (const p of parts) {
115
- if (!/^\d{1,3}$/.test(p) || p.length > 1 && p.startsWith("0")) return null;
116
- const n = Number(p);
117
- if (n > 255) return null;
118
- out.push(n);
119
- }
73
+ // ../shared/src/webhooks.ts
74
+ var enc2 = new TextEncoder();
75
+ function hmacKey2(secret) {
76
+ return crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
77
+ }
78
+ function signedBytes(timestamp, payload) {
79
+ const head = enc2.encode(`${timestamp}.`);
80
+ const body = typeof payload === "string" ? enc2.encode(payload) : payload;
81
+ const out = new Uint8Array(new ArrayBuffer(head.length + body.length));
82
+ out.set(head, 0);
83
+ out.set(body, head.length);
120
84
  return out;
121
85
  }
122
- function parseIp(text) {
123
- const s = text.trim();
124
- if (!s) return null;
125
- const v4 = parseIpv4(s);
126
- if (v4) return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, ...v4]);
127
- if (!s.includes(":") || !/^[0-9a-fA-F:.]+$/.test(s)) return null;
128
- const halves = s.split("::");
129
- if (halves.length > 2) return null;
130
- const groups = (part) => {
131
- if (part === "") return [];
132
- const out = [];
133
- const items = part.split(":");
134
- for (let i = 0; i < items.length; i++) {
135
- const it = items[i];
136
- if (i === items.length - 1 && it.includes(".")) {
137
- const tail2 = parseIpv4(it);
138
- if (!tail2) return null;
139
- out.push(tail2[0] << 8 | tail2[1], tail2[2] << 8 | tail2[3]);
140
- } else {
141
- if (!/^[0-9a-fA-F]{1,4}$/.test(it)) return null;
142
- out.push(parseInt(it, 16));
143
- }
144
- }
145
- return out;
146
- };
147
- const head = groups(halves[0]);
148
- const tail = halves.length === 2 ? groups(halves[1]) : [];
149
- if (!head || !tail) return null;
150
- const total = head.length + tail.length;
151
- if (halves.length === 2 ? total > 7 : total !== 8) return null;
152
- const all = [...head, ...Array(8 - total).fill(0), ...tail];
153
- const bytes = new Uint8Array(16);
154
- all.forEach((g, i) => {
155
- bytes[i * 2] = g >> 8;
156
- bytes[i * 2 + 1] = g & 255;
157
- });
158
- return bytes;
86
+ function hex(bytes) {
87
+ return [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
159
88
  }
160
- function parseCidr(text) {
161
- const [addr, len, extra] = text.trim().split("/");
162
- if (extra !== void 0 || !addr) return null;
163
- const bytes = parseIp(addr);
164
- if (!bytes) return null;
165
- const v4 = parseIpv4(addr.trim()) !== null;
166
- const max = v4 ? 32 : 128;
167
- if (len !== void 0 && !/^\d{1,3}$/.test(len)) return null;
168
- const n = len === void 0 ? max : Number(len);
169
- if (n > max) return null;
170
- return { bytes, bits: v4 ? n + 96 : n };
89
+ async function signWebhookPayload(secrets, payload, timestamp) {
90
+ const t = Math.floor(timestamp);
91
+ const data = signedBytes(t, payload);
92
+ const sigs = [];
93
+ for (const secret of typeof secrets === "string" ? [secrets] : secrets) {
94
+ sigs.push(`v1=${hex(await crypto.subtle.sign("HMAC", await hmacKey2(secret), data))}`);
95
+ }
96
+ return [`t=${t}`, ...sigs].join(",");
171
97
  }
172
- var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
173
- var NON_PUBLIC = compile(NON_PUBLIC_RANGES);
174
- var CLOUDFLARE = compile(CLOUDFLARE_RANGES);
175
98
 
176
99
  // src/core.ts
177
100
  var VERDICT_TTL_MS = 10 * 6e4;
@@ -202,13 +125,18 @@ async function verdictCookie(key, options = {}) {
202
125
  site: parsed.site,
203
126
  outcome: claims.length ? "review" : "insufficient_evidence",
204
127
  claims,
205
- exp: (options.issuedAt ?? Date.now()) + VERDICT_TTL_MS
128
+ exp: (options.issuedAt ?? Date.now()) + VERDICT_TTL_MS,
129
+ ...options.visitor ? { vid: options.visitor } : {}
206
130
  });
207
131
  return `_s=${sid}; _sv=${token}`;
208
132
  }
133
+ function signWebhook(secret, payload, options = {}) {
134
+ return signWebhookPayload(secret, payload, options.timestamp ?? Math.floor(Date.now() / 1e3));
135
+ }
209
136
  // Annotate the CommonJS export names for ESM import in node:
210
137
  0 && (module.exports = {
211
138
  claim,
139
+ signWebhook,
212
140
  testKey,
213
141
  verdictCookie
214
142
  });
package/dist/fastify.js CHANGED
@@ -1,23 +1,16 @@
1
1
  import {
2
2
  reguard
3
- } from "./chunks/chunk-KNKCUJL3.js";
3
+ } from "./chunks/chunk-RTCPK4MF.js";
4
4
  import {
5
5
  ReguardConfigError
6
- } from "./chunks/chunk-3AYS7WSY.js";
7
- import "./chunks/chunk-PA46KSOR.js";
6
+ } from "./chunks/chunk-4RD66ACT.js";
7
+ import "./chunks/chunk-2N762ZXU.js";
8
8
 
9
9
  // src/fastify.ts
10
- var FASTIFY_IP = /* @__PURE__ */ new WeakMap();
11
10
  function plugin(fastify, options, done) {
12
11
  let mw;
13
12
  try {
14
- const trusted = !!fastify.initialConfig?.trustProxy;
15
- mw = reguard(
16
- trusted && options.clientIp === void 0 ? {
17
- ...options,
18
- clientIp: (req) => FASTIFY_IP.get(req) ?? null
19
- } : options
20
- );
13
+ mw = reguard(options);
21
14
  } catch (e) {
22
15
  done(e);
23
16
  return;
@@ -25,7 +18,6 @@ function plugin(fastify, options, done) {
25
18
  for (const name of ["reguard", "reguardDecision"]) if (!fastify.hasRequestDecorator?.(name)) fastify.decorateRequest?.(name, null);
26
19
  fastify.addHook("onRequest", (request, reply, next) => {
27
20
  const raw = request.raw;
28
- if (request.ip) FASTIFY_IP.set(raw, request.ip);
29
21
  let passed = false;
30
22
  const res = reply.raw;
31
23
  const writeHead = res.writeHead;
package/dist/fetch.js CHANGED
@@ -1,13 +1,22 @@
1
1
  import {
2
2
  defaultBlockAnswer,
3
3
  reguardFetch
4
- } from "./chunks/chunk-U54IP6G4.js";
4
+ } from "./chunks/chunk-GOT54CF4.js";
5
5
  import {
6
- ReguardConfigError
7
- } from "./chunks/chunk-3AYS7WSY.js";
8
- import "./chunks/chunk-PA46KSOR.js";
6
+ ReguardApiError,
7
+ ReguardConfigError,
8
+ reguardApi,
9
+ verifyWebhook
10
+ } from "./chunks/chunk-4RD66ACT.js";
11
+ import {
12
+ WebhookSignatureError
13
+ } from "./chunks/chunk-2N762ZXU.js";
9
14
  export {
15
+ ReguardApiError,
10
16
  ReguardConfigError,
17
+ WebhookSignatureError as ReguardWebhookError,
11
18
  defaultBlockAnswer,
12
- reguardFetch
19
+ reguardApi,
20
+ reguardFetch,
21
+ verifyWebhook
13
22
  };
package/dist/index.js CHANGED
@@ -4,21 +4,29 @@ import {
4
4
  index_default,
5
5
  keyFingerprint,
6
6
  reguard
7
- } from "./chunks/chunk-KNKCUJL3.js";
7
+ } from "./chunks/chunk-RTCPK4MF.js";
8
8
  import {
9
- ReguardConfigError
10
- } from "./chunks/chunk-3AYS7WSY.js";
9
+ ReguardApiError,
10
+ ReguardConfigError,
11
+ reguardApi,
12
+ verifyWebhook
13
+ } from "./chunks/chunk-4RD66ACT.js";
11
14
  import {
15
+ WebhookSignatureError,
12
16
  formatSiteKey,
13
17
  parseSiteKey
14
- } from "./chunks/chunk-PA46KSOR.js";
18
+ } from "./chunks/chunk-2N762ZXU.js";
15
19
  export {
20
+ ReguardApiError,
16
21
  ReguardConfigError,
22
+ WebhookSignatureError as ReguardWebhookError,
17
23
  createReDetect,
18
24
  index_default as default,
19
25
  defaultBlockResponse,
20
26
  formatSiteKey,
21
27
  keyFingerprint,
22
28
  parseSiteKey,
23
- reguard
29
+ reguard,
30
+ reguardApi,
31
+ verifyWebhook
24
32
  };
package/dist/next.js CHANGED
@@ -1,36 +1,34 @@
1
1
  import {
2
2
  reguardFetch
3
- } from "./chunks/chunk-U54IP6G4.js";
3
+ } from "./chunks/chunk-GOT54CF4.js";
4
4
  import {
5
+ ReguardApiError,
5
6
  ReguardConfigError,
6
7
  checkBlock,
7
8
  checkCollect,
8
- checkCookieDomain
9
- } from "./chunks/chunk-3AYS7WSY.js";
9
+ checkCookieDomain,
10
+ reguardApi,
11
+ verifyWebhook
12
+ } from "./chunks/chunk-4RD66ACT.js";
10
13
  import {
14
+ WebhookSignatureError,
11
15
  collectAttributes,
12
- collectorBase,
13
16
  envValue,
14
17
  isReguardPath,
15
18
  parseSiteKey,
16
19
  readVerdictFrom,
17
20
  resolveCollect
18
- } from "./chunks/chunk-PA46KSOR.js";
21
+ } from "./chunks/chunk-2N762ZXU.js";
19
22
 
20
23
  // src/next.ts
24
+ var SITE_ID = /^[\w.-]{1,64}$/;
21
25
  function withReguard(config, options = {}) {
22
- const rule = { source: "/_s/:path*", destination: `${collectorBase(options.collector ?? envValue("REGUARD_COLLECTOR"))}/_s/:path*`, basePath: false };
23
- const site = parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site;
24
- const apply = (cfg) => ({
25
- ...cfg,
26
- ...site ? { env: { ...cfg.env ?? {}, NEXT_PUBLIC_REGUARD_SITE: site } } : {},
27
- async rewrites() {
28
- const mine = cfg.rewrites ? await cfg.rewrites() : void 0;
29
- if (!mine) return { beforeFiles: [rule], afterFiles: [], fallback: [] };
30
- if (Array.isArray(mine)) return { beforeFiles: [rule], afterFiles: mine, fallback: [] };
31
- return { ...mine, beforeFiles: [rule, ...mine.beforeFiles ?? []] };
32
- }
33
- });
26
+ if (options.collector !== void 0)
27
+ throw new ReguardConfigError("collector", "removed_option", "was removed from withReguard: reguardMiddleware() serves /_s/* and reads REGUARD_COLLECTOR at run time");
28
+ if (options.site !== void 0 && (typeof options.site !== "string" || !SITE_ID.test(options.site)))
29
+ throw new ReguardConfigError("site", "invalid_value", 'must be your site id (on your dashboard), e.g. "shop-example-com"');
30
+ const site = options.site ?? parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site;
31
+ const apply = (cfg) => site ? { ...cfg, env: { ...cfg.env ?? {}, NEXT_PUBLIC_REGUARD_SITE: site } } : cfg;
34
32
  if (typeof config === "function") {
35
33
  const fn = config;
36
34
  return (async (...args) => apply(await fn(...args)));
@@ -58,9 +56,13 @@ function reguardScriptProps(options = {}) {
58
56
  const site = parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site ?? publicSite();
59
57
  if (!site && !warned) {
60
58
  warned = true;
61
- console.warn("[reguard] REGUARD_KEY is not set (and withReguard didn't provide NEXT_PUBLIC_REGUARD_SITE): the script will load but not start.");
59
+ console.warn(
60
+ "[reguard] No site id for the script tag: REGUARD_KEY isn't set here and NEXT_PUBLIC_REGUARD_SITE isn't either, so the script won't start on this page. For pages rendered at build time, set NEXT_PUBLIC_REGUARD_SITE to your site id (it's public; your dashboard shows it), or pass it to withReguard({ ... }, { site })."
61
+ );
62
62
  }
63
63
  const production = envValue("NODE_ENV") === "production";
64
+ if (!production && options.collect && options.collect.requests !== void 0)
65
+ throw new ReguardConfigError("collect.requests", "unknown_option", "isn't an option of reguardScriptProps (the script sends no request summaries): pass it to reguardMiddleware");
64
66
  const collect = production ? resolveCollect(options.collect, (m) => console.warn(`[reguard] ${m}`)) : checkCollect(options.collect);
65
67
  const cookieDomain = production ? typeof options.cookieDomain === "string" ? options.cookieDomain.replace(/^\./, "").toLowerCase() : void 0 : checkCookieDomain(options.cookieDomain);
66
68
  return {
@@ -73,21 +75,29 @@ function reguardScriptProps(options = {}) {
73
75
  ...cookieDomain ? { "data-cookie-domain": cookieDomain } : {}
74
76
  };
75
77
  }
78
+ var MIDDLEWARE_OPTIONS = ["block", "key", "previousKey", "collector", "collect", "ignore", "sourceMaps", "clientIp", "timeoutMs", "debug", "logger"];
76
79
  function reguardMiddleware(options = {}) {
77
80
  for (const k of Object.keys(options))
78
- if (!["block", "key", "previousKey", "sourceMaps", "clientIp", "debug", "logger"].includes(k) && options[k] !== void 0)
81
+ if (!MIDDLEWARE_OPTIONS.includes(k) && options[k] !== void 0)
79
82
  throw new ReguardConfigError(k, "unknown_option", "isn't an option of reguardMiddleware");
80
83
  checkBlock(options.block, "block", "fetch");
81
- const rg = reguardFetch({ ...options, collect: { requests: false } });
82
- return async (request) => {
83
- if (isReguardPath(new URL(request.url).pathname)) return void 0;
84
- return rg.handle(request);
84
+ const rg = reguardFetch(options);
85
+ return async (request, event) => {
86
+ const ctx = typeof event?.waitUntil === "function" ? { waitUntil: event.waitUntil.bind(event) } : void 0;
87
+ const answered = await rg.handle(request, ctx);
88
+ if (isReguardPath(new URL(request.url).pathname)) return answered;
89
+ rg.record(request, answered ?? null, ctx);
90
+ return answered;
85
91
  };
86
92
  }
87
93
  export {
94
+ ReguardApiError,
88
95
  ReguardConfigError,
96
+ WebhookSignatureError as ReguardWebhookError,
97
+ reguardApi,
89
98
  reguardMiddleware,
90
99
  reguardScriptProps,
91
100
  reguardVerdict,
101
+ verifyWebhook,
92
102
  withReguard
93
103
  };
package/dist/testing.js CHANGED
@@ -2,8 +2,9 @@ import {
2
2
  VERDICT_TTL_MS,
3
3
  formatSiteKey,
4
4
  parseSiteKey,
5
- signVerdict
6
- } from "./chunks/chunk-PA46KSOR.js";
5
+ signVerdict,
6
+ signWebhookPayload
7
+ } from "./chunks/chunk-2N762ZXU.js";
7
8
 
8
9
  // src/testing.ts
9
10
  function testKey(site = "test-site") {
@@ -28,12 +29,17 @@ async function verdictCookie(key, options = {}) {
28
29
  site: parsed.site,
29
30
  outcome: claims.length ? "review" : "insufficient_evidence",
30
31
  claims,
31
- exp: (options.issuedAt ?? Date.now()) + VERDICT_TTL_MS
32
+ exp: (options.issuedAt ?? Date.now()) + VERDICT_TTL_MS,
33
+ ...options.visitor ? { vid: options.visitor } : {}
32
34
  });
33
35
  return `_s=${sid}; _sv=${token}`;
34
36
  }
37
+ function signWebhook(secret, payload, options = {}) {
38
+ return signWebhookPayload(secret, payload, options.timestamp ?? Math.floor(Date.now() / 1e3));
39
+ }
35
40
  export {
36
41
  claim,
42
+ signWebhook,
37
43
  testKey,
38
44
  verdictCookie
39
45
  };
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The visitors API and webhooks (reguard 0.9). Runtime-neutral (fetch and WebCrypto): Node 20+,
3
+ * Workers, Deno and Bun.
4
+ *
5
+ * import { reguardApi, verifyWebhook } from "reguard";
6
+ *
7
+ * const api = reguardApi(); // REGUARD_KEY from the environment
8
+ * const v = await api.visitor(req.reguard.visitor); // the id from the visitor's signed verdict
9
+ * if (v.caught) …
10
+ *
11
+ * for (let after = null; ; ) { // poll instead of receiving webhooks
12
+ * const page = await api.events({ after });
13
+ * for (const e of page.events) handle(e);
14
+ * after = page.next;
15
+ * if (!page.hasMore) break;
16
+ * }
17
+ *
18
+ * const event = await verifyWebhook(rawBody, req.headers["reguard-signature"]); // REGUARD_WEBHOOK_SECRET
19
+ */
20
+ import { type Label, type Stage } from "../../shared/src/index.js";
21
+ export { WebhookSignatureError as ReguardWebhookError } from "../../shared/src/index.js";
22
+ export type { WebhookErrorCode as ReguardWebhookErrorCode } from "../../shared/src/index.js";
23
+ /** What matched when a caught visitor came back without its cookies. */
24
+ export type ReturnReason = "network_device" | "device_id";
25
+ export interface VisitorCatch {
26
+ rule: string;
27
+ label: Label;
28
+ stage: Stage;
29
+ at: string;
30
+ page: string | null;
31
+ evidence: Array<{
32
+ rule: string;
33
+ observed: unknown;
34
+ }>;
35
+ }
36
+ /** A caught visitor's later session without its cookies. */
37
+ export interface VisitorReturn {
38
+ visitor: string;
39
+ reason: ReturnReason;
40
+ at: string;
41
+ /** Seconds since the caught visitor's last page load. */
42
+ gapSeconds: number | null;
43
+ /** It came back while its session cookie should still have been there: cleared or blocked. */
44
+ cookieCleared: boolean;
45
+ userAgent: string | null;
46
+ page: string | null;
47
+ }
48
+ /** The caught visitor a visitor was recognized as. */
49
+ export interface VisitorLink {
50
+ visitor: string;
51
+ reason: ReturnReason;
52
+ at: string;
53
+ gapSeconds: number | null;
54
+ cookieCleared: boolean;
55
+ }
56
+ /** What Reguard knows about a visitor. `caught: false` for clean visitors and unknown ids alike. */
57
+ export interface VisitorStatus {
58
+ id: string;
59
+ caught: boolean;
60
+ kind: "browser" | "cookieless" | null;
61
+ labels: Label[];
62
+ stage: Stage | null;
63
+ firstSeen: string | null;
64
+ lastSeen: string | null;
65
+ caughtAt: string | null;
66
+ userAgent: string | null;
67
+ firstPage: string | null;
68
+ counts: {
69
+ catches: number;
70
+ blocked: number;
71
+ wouldBlock: number;
72
+ returns: number;
73
+ };
74
+ catches: VisitorCatch[];
75
+ returns: VisitorReturn[];
76
+ linkedTo: VisitorLink[];
77
+ /** The visitor on the dashboard. */
78
+ url: string;
79
+ }
80
+ export type ReguardEventType = "visitor.caught" | "visitor.escalated" | "visitor.returned" | "ping";
81
+ export interface ReguardEvent {
82
+ /** `evt_…`: unique; a delivery retried after a failure carries the same id. */
83
+ id: string;
84
+ type: ReguardEventType;
85
+ /** Epoch seconds. */
86
+ created: number;
87
+ site: string;
88
+ data: {
89
+ visitor?: VisitorStatus;
90
+ /** visitor.escalated: the stage before. */
91
+ previousStage?: Stage | null;
92
+ /** visitor.returned: the session that came back. */
93
+ returned?: VisitorReturn;
94
+ /** ping: the dashboard's test message. */
95
+ message?: string;
96
+ };
97
+ }
98
+ export interface EventsPage {
99
+ /** Oldest first. */
100
+ events: ReguardEvent[];
101
+ /** Pass as `after` next time (null until there is an event). */
102
+ next: string | null;
103
+ /** More events are waiting: ask again now. */
104
+ hasMore: boolean;
105
+ }
106
+ export declare class ReguardApiError extends Error {
107
+ readonly status: number;
108
+ constructor(status: number, message: string);
109
+ }
110
+ export interface ReguardApiOptions {
111
+ /** Site key; default REGUARD_KEY. */
112
+ key?: string;
113
+ /** Default REGUARD_COLLECTOR, then https://api.reguard.site. */
114
+ collector?: string;
115
+ fetch?: typeof fetch;
116
+ /** Per call (default 10000). */
117
+ timeoutMs?: number;
118
+ }
119
+ export interface ReguardApi {
120
+ /** A visitor by the id in its signed verdict (`req.reguard.visitor`). */
121
+ visitor(id: string): Promise<VisitorStatus>;
122
+ /** The event feed, oldest first, after `after` (an `evt_…` id). */
123
+ events(options?: {
124
+ after?: string | null;
125
+ limit?: number;
126
+ types?: readonly Exclude<ReguardEventType, "ping">[];
127
+ }): Promise<EventsPage>;
128
+ }
129
+ export declare function reguardApi(options?: ReguardApiOptions): ReguardApi;
130
+ /**
131
+ * The event in a webhook delivery, once its signature checks out; throws a ReguardWebhookError
132
+ * (`code`: missing_secret, missing_signature, malformed_signature, expired, bad_signature,
133
+ * bad_payload) otherwise. Pass the raw request body exactly as received, the Reguard-Signature
134
+ * header, and the endpoint's signing secret (default REGUARD_WEBHOOK_SECRET).
135
+ */
136
+ export declare function verifyWebhook(payload: string | Uint8Array | ArrayBuffer, signature: string | string[] | null | undefined, secret?: string, options?: {
137
+ tolerance?: number;
138
+ now?: number;
139
+ }): Promise<ReguardEvent>;
@@ -5,6 +5,11 @@ export type VerdictSource = "browser" | "server" | "both";
5
5
  export interface Verdict extends VerdictPayload {
6
6
  /** Where the claims came from. */
7
7
  source: VerdictSource;
8
+ /**
9
+ * The visitor's id (collector 0.9+; null from older ones): stable across its page loads, signed
10
+ * by Reguard. Look it up with `reguardApi().visitor(id)`, or match it to webhook events.
11
+ */
12
+ visitor: string | null;
8
13
  /**
9
14
  * Whether there is a claim for one of `labels` (default: any) at `minStage` or above (default
10
15
  * "candidate", i.e. including rules still on trial).
@@ -15,6 +20,8 @@ export interface Verdict extends VerdictPayload {
15
20
  }): boolean;
16
21
  }
17
22
  export declare const STAGE_RANK: Record<Stage, number>;
23
+ /** A visitor id as the collector issues them (`vis_` and 22 characters); anything else is ignored. */
24
+ export declare const visitorIdOf: (v: unknown) => string | undefined;
18
25
  export declare function withFlagged(p: VerdictPayload, source?: VerdictSource): Verdict;
19
26
  /** A browser verdict with claims the collector pushed to your server added (deduplicated by rule). */
20
27
  export declare function mergeVerdicts(browser: Verdict | null, pushed: Verdict | null): Verdict | null;
@@ -52,7 +59,7 @@ export declare function verdictAgeMs(v: {
52
59
  exp: number;
53
60
  }, now?: number): number;
54
61
  /** Claims the collector sent back to a site's server (no token: they arrived over its authenticated channel). */
55
- export declare function pushedVerdict(sid: string, site: string, claims: VerdictClaim[], now?: number): Verdict;
62
+ export declare function pushedVerdict(sid: string, site: string, claims: VerdictClaim[], now?: number, vid?: string): Verdict;
56
63
  /** Which limit a paced request went over. */
57
64
  export type PaceKind = "document" | "api" | "notfound";
58
65
  /** Why Reguard answered for the app (or, in a dry run, would have). */
@@ -5,12 +5,15 @@
5
5
  * import Fastify from "fastify";
6
6
  * import reguard from "reguard/fastify";
7
7
  *
8
- * const app = Fastify({ trustProxy: true }); // then Reguard uses Fastify's request.ip
9
- * await app.register(reguard, { block: { dryRun: true } });
8
+ * const app = Fastify();
9
+ * await app.register(reguard, { block: { dryRun: true } }); // at the root: it covers the whole app
10
10
  * app.get("/api/items", async (request) => (request.reguard?.flagged() ? [] : items));
11
11
  *
12
- * No dependency on fastify itself: the plugin is marked like fastify-plugin does, so its request
13
- * decorations apply app-wide.
12
+ * No dependency on fastify itself: the plugin is marked like fastify-plugin does, so registered at
13
+ * the root its hooks and request decorations apply app-wide (inside a prefixed scope, only there).
14
+ * Visitor addresses are read as reguard() reads them (your proxies, CloudFront, Cloudflare, the
15
+ * host's header); set `clientIp` for anything else. Fastify's `trustProxy: true` would hand over the
16
+ * client's own X-Forwarded-For entry, so it isn't used.
14
17
  */
15
18
  import type { IncomingMessage, ServerResponse } from "node:http";
16
19
  import type { Decision, Verdict } from "./core.js";
@@ -32,10 +35,15 @@ interface FastifyLike {
32
35
  addHook(name: "onClose", hook: (instance: unknown, done: () => void) => void): unknown;
33
36
  decorateRequest?(name: string, value: unknown): unknown;
34
37
  hasRequestDecorator?(name: string): boolean;
35
- initialConfig?: {
36
- trustProxy?: unknown;
37
- };
38
38
  }
39
39
  declare function plugin(fastify: FastifyLike, options: ReguardOptions, done: (err?: Error) => void): void;
40
40
  export declare const reguardFastify: typeof plugin;
41
41
  export default plugin;
42
+ declare module "fastify" {
43
+ interface FastifyRequest {
44
+ /** The visitor's verified verdict (null: none). Set by reguard/fastify. */
45
+ reguard: Verdict | null;
46
+ /** In a dry run, what Reguard would have done for this request (null: nothing). */
47
+ reguardDecision: Decision | null;
48
+ }
49
+ }
@@ -18,6 +18,8 @@ import { type BlockBase, type ClientIpOption, type LoggerLike } from "./config.j
18
18
  import { type Decision, type Verdict } from "./core.js";
19
19
  export type { Decision, Verdict, VerdictSource } from "./core.js";
20
20
  export { type BlockReason, ReguardConfigError } from "./config.js";
21
+ export { type EventsPage, type ReguardApi, type ReguardApiOptions, type ReguardEvent, type ReguardEventType, type ReguardWebhookErrorCode, type ReturnReason, type VisitorCatch, type VisitorLink, type VisitorReturn, type VisitorStatus, ReguardApiError, ReguardWebhookError, reguardApi, verifyWebhook, } from "./api.js";
22
+ import { type EventsPage, type ReguardApi, type VisitorStatus } from "./api.js";
21
23
  export interface FetchBlockOptions extends Omit<BlockBase, "require" | "requireMaxAgeMs" | "requireGraceMs" | "requireGraceRequests" | "requireGracePages" | "requireRefreshRequests" | "requireRefreshMs"> {
22
24
  allowIf?: (request: Request) => boolean;
23
25
  /** Your own answer for a blocked request; Reguard's default (`defaultBlockAnswer`) when it throws. */
@@ -55,8 +57,12 @@ export interface ReguardFetch {
55
57
  handle(request: Request, ctx?: {
56
58
  waitUntil?: WaitUntil;
57
59
  }): Promise<Response | undefined>;
58
- /** After your handler: queue the summary of its response. */
59
- record(request: Request, response: Response, ctx?: {
60
+ /**
61
+ * After your handler: queue the summary of its response. Middleware that never sees the response
62
+ * (Next.js) passes null: Reguard then reports only what it knows without one, its own decisions
63
+ * and requests from clients that don't present as a browser.
64
+ */
65
+ record(request: Request, response: Response | null, ctx?: {
60
66
  waitUntil?: WaitUntil;
61
67
  }): void;
62
68
  /** handle + your handler + record. The platform's waitUntil is found among the handler's arguments. */
@@ -69,6 +75,10 @@ export interface ReguardFetch {
69
75
  nonce?: string;
70
76
  }): string;
71
77
  flush(): Promise<void>;
78
+ /** A visitor by the id in its verdict: see reguardApi(). */
79
+ visitor(id: string): Promise<VisitorStatus>;
80
+ /** The event feed, for polling instead of webhooks: see reguardApi(). */
81
+ events(options?: Parameters<ReguardApi["events"]>[0]): Promise<EventsPage>;
72
82
  }
73
83
  /** Reguard's default answer for a decision (HTML page for page loads, JSON with a `code` otherwise). */
74
84
  export declare function defaultBlockAnswer(request: Request, decision: Decision): Response;
@@ -6,7 +6,9 @@ import { Health, type HealthState, type Log } from "./health.js";
6
6
  export type { AddressesMode, ClientIpMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.js";
7
7
  export type { Decision, PaceConfig, PaceKind, PaceRate, Verdict, VerdictSource } from "./core.js";
8
8
  export { type BlockReason, type ConfigErrorCode, type LoggerLike, ReguardConfigError } from "./config.js";
9
+ import { type EventsPage, type ReguardApi, type VisitorStatus } from "./api.js";
9
10
  export type { HealthState } from "./health.js";
11
+ export { type EventsPage, type ReguardApi, type ReguardApiOptions, type ReguardEvent, type ReguardEventType, type ReguardWebhookErrorCode, type ReturnReason, type VisitorCatch, type VisitorLink, type VisitorReturn, type VisitorStatus, ReguardApiError, ReguardWebhookError, reguardApi, verifyWebhook, } from "./api.js";
10
12
  export { formatSiteKey, parseSiteKey, type ParsedSiteKey } from "../../shared/src/index.js";
11
13
  declare global {
12
14
  namespace Express {
@@ -136,6 +138,10 @@ export interface ReguardMiddleware {
136
138
  flush(): Promise<void>;
137
139
  /** Stop the summary timer and send what's queued (e.g. on shutdown). */
138
140
  close(): Promise<void>;
141
+ /** A visitor by the id in its verdict (`req.reguard.visitor`): see reguardApi(). */
142
+ visitor(id: string): Promise<VisitorStatus>;
143
+ /** The event feed, for polling instead of webhooks: see reguardApi(). */
144
+ events(options?: Parameters<ReguardApi["events"]>[0]): Promise<EventsPage>;
139
145
  }
140
146
  /** A short public fingerprint of a key's secret: safe to log and to compare with the dashboard. */
141
147
  export declare function keyFingerprint(secret: string): string;