reguard 0.7.1 → 0.8.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 +51 -31
  2. package/dist/chunks/chunk-3AYS7WSY.js +350 -0
  3. package/dist/chunks/chunk-KNKCUJL3.js +969 -0
  4. package/dist/chunks/{chunk-W56LN2M5.js → chunk-PA46KSOR.js} +385 -33
  5. package/dist/chunks/chunk-U54IP6G4.js +448 -0
  6. package/dist/cjs/fastify.cjs +2109 -0
  7. package/dist/cjs/fetch.cjs +1463 -0
  8. package/dist/cjs/index.cjs +2074 -0
  9. package/dist/cjs/next.cjs +1535 -0
  10. package/dist/cjs/testing.cjs +214 -0
  11. package/dist/fastify.js +59 -0
  12. package/dist/fetch.js +13 -0
  13. package/dist/index.js +15 -716
  14. package/dist/next.js +48 -52
  15. package/dist/testing.js +39 -0
  16. package/dist/types/node/src/config.d.ts +107 -0
  17. package/dist/types/node/src/core.d.ts +66 -72
  18. package/dist/types/node/src/fastify.d.ts +41 -0
  19. package/dist/types/node/src/fetch.d.ts +76 -0
  20. package/dist/types/node/src/health.d.ts +41 -0
  21. package/dist/types/node/src/index.d.ts +114 -34
  22. package/dist/types/node/src/next.d.ts +40 -27
  23. package/dist/types/node/src/testing.d.ts +25 -0
  24. package/dist/types/shared/src/address.d.ts +81 -0
  25. package/dist/types/shared/src/index.d.ts +6 -0
  26. package/dist/types/shared/src/paths.d.ts +32 -0
  27. package/dist/types-cjs/node/src/config.d.cts +107 -0
  28. package/dist/types-cjs/node/src/core.d.cts +107 -0
  29. package/dist/types-cjs/node/src/fastify.d.cts +41 -0
  30. package/dist/types-cjs/node/src/fetch.d.cts +76 -0
  31. package/dist/types-cjs/node/src/health.d.cts +41 -0
  32. package/dist/types-cjs/node/src/index.d.cts +203 -0
  33. package/dist/types-cjs/node/src/next.d.cts +85 -0
  34. package/dist/types-cjs/node/src/testing.d.cts +25 -0
  35. package/dist/types-cjs/shared/src/address.d.cts +81 -0
  36. package/dist/types-cjs/shared/src/allowance.d.cts +17 -0
  37. package/dist/types-cjs/shared/src/collect.d.cts +52 -0
  38. package/dist/types-cjs/shared/src/exchange.d.cts +69 -0
  39. package/dist/types-cjs/shared/src/index.d.cts +105 -0
  40. package/dist/types-cjs/shared/src/keys.d.cts +13 -0
  41. package/dist/types-cjs/shared/src/paths.d.cts +32 -0
  42. package/dist/types-cjs/shared/src/tools.d.cts +101 -0
  43. package/dist/types-cjs/shared/src/verdict.d.cts +37 -0
  44. package/package.json +73 -10
@@ -0,0 +1,2109 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/fastify.ts
21
+ var fastify_exports = {};
22
+ __export(fastify_exports, {
23
+ ReguardConfigError: () => ReguardConfigError,
24
+ default: () => fastify_default,
25
+ reguardFastify: () => reguardFastify
26
+ });
27
+ module.exports = __toCommonJS(fastify_exports);
28
+
29
+ // src/index.ts
30
+ var import_node_crypto = require("node:crypto");
31
+ var import_node_stream = require("node:stream");
32
+ var import_promises = require("node:stream/promises");
33
+
34
+ // ../shared/src/exchange.ts
35
+ var IGNORED_PARAMS = /* @__PURE__ */ new Set(["_rsc", "_", "cb", "ts", "t", "_t", "v", "nocache", "__nextDataReq", "__nextLocale"]);
36
+ var PAGE_KEYS = /* @__PURE__ */ new Set(["page", "p", "offset", "skip", "start", "cursor", "after", "from"]);
37
+ var STRONG = [
38
+ /['"`]\s*(?:or|and|union|select|order\s+by|--|#|;|\))/i,
39
+ // breaking out of a quoted string
40
+ /\bunion\s+(?:all\s+)?select\b|\bsleep\s*\(|\bbenchmark\s*\(|\bwaitfor\s+delay\b|\bxp_cmdshell\b/i,
41
+ /\.\.[/\\]/,
42
+ // traversal
43
+ /\$\{[^}]*\}|\{\{[^}]*\}\}|<%[\s\S]*%>/,
44
+ // template injection
45
+ /<\s*\/?\s*(?:script|iframe|svg|img)\b|javascript:|\bon(?:error|load)\s*=/i,
46
+ // markup injection
47
+ /%[0-9a-f]{2}/i,
48
+ // still percent-encoded after decoding: double encoding
49
+ /\u0000/
50
+ // null byte
51
+ ];
52
+ function normalizeEndpoint(path) {
53
+ return path.split("/").map(
54
+ (seg) => /^\d+$/.test(seg) ? ":n" : /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(seg) ? ":uuid" : /^[0-9a-f]{16,}$/i.test(seg) ? ":hex" : /@|%40/i.test(seg) ? ":email" : /^(?=(?:.*\d){2})(?=(?:.*[a-z]){2})[a-z0-9_-]{16,}$/i.test(seg) ? ":id" : seg
55
+ ).join("/");
56
+ }
57
+ function privateUrl(url) {
58
+ const [path = "/", query] = url.split("?");
59
+ const names = query ? [...new Set(new URLSearchParams(query).keys())] : [];
60
+ return normalizeEndpoint(path) + (names.length ? `?${names.map((n) => `${n}=`).join("&")}` : "");
61
+ }
62
+ function shapeOf(v) {
63
+ if (v === "") return "empty";
64
+ if (/^-?\d+$/.test(v)) return "int";
65
+ if (/^-?\d*\.\d+$/.test(v)) return "decimal";
66
+ if (/^(?:true|false)$/i.test(v)) return "bool";
67
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v)) return "uuid";
68
+ if (/^[0-9a-f]{16,}$/i.test(v)) return "hex";
69
+ if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return "email";
70
+ if (/^[a-z0-9]+(?:[-_.][a-z0-9]+)+$/i.test(v)) return "slug";
71
+ if (/^[\p{L}\p{N}]+$/u.test(v)) return "word";
72
+ return "text";
73
+ }
74
+ function strongMarker(v) {
75
+ return STRONG.some((re) => re.test(v));
76
+ }
77
+ function boundaryOf(v) {
78
+ if (!/^-?\d+$/.test(v)) return void 0;
79
+ if (/^-?0+$/.test(v)) return "zero";
80
+ if (v.startsWith("-")) return "neg";
81
+ if (v.length >= 10) return "overflow";
82
+ return void 0;
83
+ }
84
+ function describeExchange(hash, x) {
85
+ const [path = "/", query = ""] = x.url.split("?");
86
+ const params = {};
87
+ let pageValue = null;
88
+ const add = (name, value, shape = shapeOf(value), scanned = true) => {
89
+ const p = { h: hash(`${name}=${value}`), shape };
90
+ if (scanned) {
91
+ if (strongMarker(value)) p.strong = true;
92
+ const b = boundaryOf(value);
93
+ if (b) p.boundary = b;
94
+ }
95
+ params[name] = p;
96
+ const bare = name.replace(/^body\./, "").toLowerCase();
97
+ if (PAGE_KEYS.has(bare) && /^\d+$/.test(value)) pageValue = Number(value);
98
+ };
99
+ for (const [k, v] of new URLSearchParams(query)) if (!IGNORED_PARAMS.has(k)) add(k, v);
100
+ const body = x.requestBody ?? "";
101
+ const ct = (x.requestContentType ?? "").toLowerCase();
102
+ if (body) {
103
+ try {
104
+ if (ct.includes("json")) {
105
+ const parsed = JSON.parse(body);
106
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
107
+ for (const [k, v] of Object.entries(parsed)) {
108
+ const name = `body.${k}`;
109
+ if (typeof v === "string") add(name, v);
110
+ else if (typeof v === "number") add(name, String(v));
111
+ else if (typeof v === "boolean") add(name, String(v), "bool", false);
112
+ else if (v === null) add(name, "null", "empty", false);
113
+ else add(name, JSON.stringify(v).slice(0, 256), "json", false);
114
+ }
115
+ }
116
+ } else if (ct.includes("x-www-form-urlencoded")) {
117
+ for (const [k, v] of new URLSearchParams(body)) add(`body.${k}`, v);
118
+ }
119
+ } catch {
120
+ }
121
+ }
122
+ let listLength = null;
123
+ const head = x.responseHead ?? "";
124
+ if ((x.responseContentType ?? "").includes("json") && head) {
125
+ try {
126
+ const parsed = JSON.parse(head);
127
+ if (Array.isArray(parsed)) listLength = parsed.length;
128
+ else if (parsed && typeof parsed === "object") {
129
+ const firstArray = Object.values(parsed).find(Array.isArray);
130
+ if (firstArray) listLength = firstArray.length;
131
+ }
132
+ } catch {
133
+ }
134
+ }
135
+ return {
136
+ method: x.method,
137
+ endpoint: normalizeEndpoint(path),
138
+ item: hash(`path:${path}`),
139
+ params,
140
+ requestBytes: x.requestBytes,
141
+ status: x.status,
142
+ responseBytes: x.responseBytes,
143
+ listLength,
144
+ pageValue
145
+ };
146
+ }
147
+ function isApiLike(url, responseContentType, requestBytes) {
148
+ const ct = responseContentType.toLowerCase();
149
+ return url.startsWith("/api/") || url.includes("_rsc=") || ct.includes("json") || ct.includes("x-component") || requestBytes > 0;
150
+ }
151
+ function isSpeculativeHeaders(get) {
152
+ return get("next-router-prefetch") !== void 0 || /prefetch|prerender/i.test(get("sec-purpose") ?? get("purpose") ?? "");
153
+ }
154
+
155
+ // ../shared/src/verdict.ts
156
+ var VERDICT_COOKIE = "_sv";
157
+ var SESSION_COOKIE = "_s";
158
+ var enc = new TextEncoder();
159
+ var keys = /* @__PURE__ */ new Map();
160
+ function unb64url(s) {
161
+ const pad = s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4);
162
+ const bin = atob(pad);
163
+ const out = new Uint8Array(new ArrayBuffer(bin.length));
164
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
165
+ return out;
166
+ }
167
+ function hmacKey(siteKey) {
168
+ let k = keys.get(siteKey);
169
+ if (!k) {
170
+ k = crypto.subtle.importKey("raw", enc.encode(siteKey), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
171
+ keys.set(siteKey, k);
172
+ }
173
+ return k;
174
+ }
175
+ async function verifyVerdict(siteKey, token, expect = {}) {
176
+ try {
177
+ if (!token) return null;
178
+ const [v, body, sig] = token.split(".");
179
+ if (v !== "v1" || !body || !sig) return null;
180
+ const ok = await crypto.subtle.verify("HMAC", await hmacKey(siteKey), unb64url(sig), enc.encode(`v1.${body}`));
181
+ if (!ok) return null;
182
+ const p = JSON.parse(new TextDecoder().decode(unb64url(body)));
183
+ if (p.v !== 1 || p.exp < (expect.now ?? Date.now())) return null;
184
+ if (expect.site !== void 0 && p.site !== expect.site) return null;
185
+ if (expect.sid !== void 0 && p.sid !== expect.sid) return null;
186
+ return p;
187
+ } catch {
188
+ return null;
189
+ }
190
+ }
191
+ function cookieValue(header2, name) {
192
+ if (!header2) return void 0;
193
+ for (const part of header2.split(";")) {
194
+ const i = part.indexOf("=");
195
+ if (i > 0 && part.slice(0, i).trim() === name) return part.slice(i + 1).trim();
196
+ }
197
+ return void 0;
198
+ }
199
+
200
+ // ../shared/src/keys.ts
201
+ var SITE_KEY_PREFIX = "rgk";
202
+ function parseSiteKey(key) {
203
+ const k = (key ?? "").trim();
204
+ if (!k) return null;
205
+ if (!k.startsWith(`${SITE_KEY_PREFIX}.`)) return /^[\w-]+$/.test(k) ? { secret: k } : null;
206
+ const parts = k.split(".");
207
+ if (parts.length < 4) return null;
208
+ const secret = parts[parts.length - 1];
209
+ const version = /^v(\d+)$/.exec(parts[parts.length - 2]);
210
+ const site = parts.slice(1, -2).join(".");
211
+ if (!version || !site || !/^[\w-]+$/.test(secret)) return null;
212
+ return { site, version: Number(version[1]), secret };
213
+ }
214
+
215
+ // ../shared/src/tools.ts
216
+ var BENIGN_TOOL_FAMILIES = /* @__PURE__ */ new Set(["search_bot", "monitor"]);
217
+ var TOOLS = [
218
+ // Scanners and fuzzers (captured: ffuf sends "Fuzz Faster U Fool v2.x").
219
+ [/fuzz faster u fool/i, "scanner", "ffuf"],
220
+ [/^feroxbuster\//i, "scanner", "feroxbuster"],
221
+ [/^gobuster\//i, "scanner", "gobuster"],
222
+ [/\bnikto\b/i, "scanner", "nikto"],
223
+ [/^sqlmap\//i, "scanner", "sqlmap"],
224
+ [/wpscan/i, "scanner", "wpscan"],
225
+ [/nuclei/i, "scanner", "nuclei"],
226
+ [/dirbuster|\bdirb\b|wfuzz|\bdirsearch\b/i, "scanner", "dirbuster"],
227
+ [/xnlinkfinder/i, "scanner", "xnlinkfinder"],
228
+ [/zgrab|masscan|nmap scripting engine|nessus|qualys|acunetix|netsparker|burp ?suite|owasp ?zap|zaproxy|arachni|w3af|whatweb|wappalyzer/i, "scanner", "scanner"],
229
+ // Site copiers.
230
+ [/httrack/i, "cloner", "httrack"],
231
+ [/^wget\//i, "cloner", "wget"],
232
+ [/website ?(?:copier|downloader|ripper)|sitesucker|webcopy|teleport ?pro|offline ?explorer|webzip|pagenest/i, "cloner", "site-copier"],
233
+ // Crawlers and spiders.
234
+ [/katana/i, "crawler", "katana"],
235
+ [/gospider/i, "crawler", "gospider"],
236
+ [/hakrawler/i, "crawler", "hakrawler"],
237
+ [/colly/i, "crawler", "colly"],
238
+ [/^scrapy\//i, "crawler", "scrapy"],
239
+ [/crawl4ai/i, "crawler", "crawl4ai"],
240
+ // Declared AI crawlers and agents.
241
+ [/firecrawl/i, "ai_crawler", "firecrawl"],
242
+ [
243
+ /gptbot|chatgpt-user|oai-searchbot|claudebot|claude-user|claude-searchbot|anthropic-ai|perplexitybot|perplexity-user|\bccbot\b|bytespider|amazonbot|meta-external(?:agent|fetcher)|applebot-extended|cohere-ai|diffbot|youbot|imagesiftbot|timpibot|omgili|ai2bot|duckassistbot|mistralai-user|novaact/i,
244
+ "ai_crawler",
245
+ "ai-crawler"
246
+ ],
247
+ // Search engines, link previews, monitors.
248
+ [
249
+ /googlebot|google-inspectiontool|bingbot|duckduckbot|baiduspider|yandex(?:bot)?\/|applebot\/|slurp|slackbot|twitterbot|facebookexternalhit|linkedinbot|discordbot|telegrambot|whatsapp|pinterestbot|embedly|redditbot|skypeuripreview|iframely|ahrefsbot|mj12bot|dotbot|petalbot|seznambot|qwantify|mojeek|coccocbot|yeti\/|naverbot/i,
250
+ "search_bot",
251
+ "search-or-preview-bot"
252
+ ],
253
+ [/uptimerobot|pingdom|statuscake|datadog|newrelic|site24x7|better ?uptime|betterstack|checkly|freshping|hetrixtools|uptime-kuma/i, "monitor", "uptime-monitor"],
254
+ // Site audits a site's owner runs on their own site (SEO crawlers, link checkers, archives).
255
+ [/screaming frog|sitebulb|deepcrawl|lumar|ahrefs(?:site)?audit|semrush|w3c_validator|w3c-checklink|ia_archiver|archive\.org_bot/i, "monitor", "site-audit"],
256
+ // Error trackers fetch a site's scripts and source maps to symbolicate stack traces.
257
+ [/\bsentry\/|rollbar|bugsnag|raygun|trackjs|honeybadger/i, "monitor", "error-tracker"],
258
+ [/headlesschrome/i, "headless_browser", "headless-chrome"],
259
+ // Generic HTTP libraries and CLIs (captured: sourcemapper sends "Go-http-client/1.1").
260
+ [
261
+ /^(?:python-requests|python-urllib|python-httpx|aiohttp|httpx|curl\/|go-http-client|okhttp|java\/|apache-httpclient|libwww-perl|lwp::|ruby|faraday|node-fetch|undici|axios|got \(|node$|deno\/|bun\/|guzzlehttp|restsharp|postmanruntime|insomnia|k6\/|hey\/|apachebench|wrk|httpie)/i,
262
+ "http_library",
263
+ "http-library"
264
+ ]
265
+ ];
266
+ function toolOf(userAgent) {
267
+ const ua = (userAgent ?? "").trim();
268
+ if (!ua) return { family: "http_library", tool: "no-user-agent" };
269
+ for (const [re, family, tool] of TOOLS) if (re.test(ua)) return { family, tool };
270
+ return void 0;
271
+ }
272
+ function browserIncoherence(h) {
273
+ const ua = h.userAgent ?? "";
274
+ if (!/^Mozilla\/5\.0 \(/.test(ua) || toolOf(ua)) return [];
275
+ const reasons = [];
276
+ if (!h.acceptLanguage) reasons.push("no_accept_language");
277
+ if (/ {2,}/.test(ua) || / {2,}/.test(h.accept ?? "")) reasons.push("header_whitespace");
278
+ const chrome = /(?:Chrome|CriOS)\/(\d+)/.exec(ua);
279
+ const firefox = /(?:Firefox|FxiOS)\/(\d+)/.exec(ua);
280
+ const safari = /Version\/(\d+)[.\d]* (?:Mobile\/\w+ )?Safari\//.exec(ua);
281
+ const version = Number(chrome?.[1] ?? firefox?.[1] ?? safari?.[1] ?? 0);
282
+ const modern = chrome && version >= 90 || firefox && version >= 90 || safari && version >= 17;
283
+ if (h.secure !== false && modern && !h.secFetchMode) reasons.push("no_fetch_metadata");
284
+ if (h.secure !== false && h.secChUa && chrome && !/CriOS/.test(ua)) {
285
+ const hinted = /"Chromium";\s*v="(\d+)"/.exec(h.secChUa)?.[1];
286
+ if (hinted && Number(hinted) !== Number(chrome[1])) reasons.push("client_hints_version_mismatch");
287
+ if (/"HeadlessChrome"/.test(h.secChUa) && !/HeadlessChrome/.test(ua)) reasons.push("client_hints_headless_mismatch");
288
+ }
289
+ return reasons;
290
+ }
291
+ var SENSITIVE_PATH = /^\/(\.env|\.git|\.svn|\.hg|\.DS_Store|\.aws|\.ssh|\.htaccess|\.htpasswd|web\.config|wp-admin|wp-login\.php|xmlrpc\.php|phpinfo|phpmyadmin|server-status|server-info|actuator|backup|dump\.sql|config\.(?:json|ya?ml|php|js)|swagger|openapi|api-docs|admin|debug|console)(?=$|[/.?#_-])/i;
292
+ var DISCOVERY_FILE = /^\/(?:robots\.txt|sitemap[\w-]*\.xml(?:\.gz)?|\.well-known\/security\.txt|security\.txt|humans\.txt|crossdomain\.xml|asset-manifest\.json|_next\/static\/[^/]+\/_buildManifest\.js)$/i;
293
+ var BROWSER_AUTOMATIC = /^\/(?:favicon\.ico|apple-touch-icon[\w.-]*\.png|browserconfig\.xml|site\.webmanifest|manifest\.json|\.well-known\/appspecific\/)/i;
294
+ function watchworthy(w) {
295
+ const tool = toolOf(w.userAgent);
296
+ if (tool && tool.family !== "headless_browser") return !BENIGN_TOOL_FAMILIES.has(tool.family);
297
+ if (browserIncoherence(w).length) return true;
298
+ const t = w.traits ?? pathTraits(w.path);
299
+ if (t.family || t.discovery || t.map) return true;
300
+ if (t.auto) return false;
301
+ return w.status === 404 || w.status === 405 || w.status === 410;
302
+ }
303
+ function requestKind(url, rsc = false) {
304
+ const path = url.split("?")[0] ?? url;
305
+ if (rsc || url.includes("_rsc=")) return "rsc";
306
+ if (path.startsWith("/api/")) return "api";
307
+ if (/\.(?:html?|php|aspx?|jsp)$/i.test(path)) return "document";
308
+ if (/\.[a-z0-9]{1,6}$/i.test(path) || path.startsWith("/_next/")) return "static";
309
+ return "document";
310
+ }
311
+ function pathTraits(url, rsc = false) {
312
+ const path = url.split("?")[0] ?? url;
313
+ const t = { kind: requestKind(url, rsc) };
314
+ const fam = SENSITIVE_PATH.exec(path)?.[1]?.toLowerCase();
315
+ if (fam) t.family = fam.startsWith(".") ? fam : fam.replace(/\..*$/, "");
316
+ if (DISCOVERY_FILE.test(path)) t.discovery = path.toLowerCase();
317
+ if (BROWSER_AUTOMATIC.test(path)) t.auto = true;
318
+ if (/\.map$/i.test(path)) t.map = true;
319
+ if (/\.(?:m?js|cjs)$/i.test(path)) t.script = true;
320
+ if (/[0-9a-f]{32,}/i.test(path)) t.random = true;
321
+ return t;
322
+ }
323
+
324
+ // ../shared/src/collect.ts
325
+ var DEFAULT_COLLECT = Object.freeze({ pages: "masked", addresses: "hashed", behavior: true, requests: true, skip: [] });
326
+ var PAGES = ["masked", "hashed", "off"];
327
+ var ADDRESSES = ["hashed", "off"];
328
+ var SKIP_PATTERN = /^\/[\w\-.~%!$&'()*+;=:@/]{0,199}$/;
329
+ var MAX_SKIP = 50;
330
+ function flag(v) {
331
+ if (typeof v === "boolean") return v;
332
+ if (typeof v !== "string") return void 0;
333
+ const s = v.trim().toLowerCase();
334
+ return s === "on" || s === "true" || s === "1" || s === "yes" ? true : s === "off" || s === "false" || s === "0" || s === "no" ? false : void 0;
335
+ }
336
+ function resolveCollect(input, warn = () => {
337
+ }) {
338
+ const out = { ...DEFAULT_COLLECT, skip: [] };
339
+ if (input === void 0 || input === null) return out;
340
+ if (typeof input !== "object" || Array.isArray(input)) {
341
+ warn("collect should be an object; using the defaults");
342
+ return out;
343
+ }
344
+ const c = input;
345
+ const bad = (name, value, allowed) => warn(`collect.${name} = ${JSON.stringify(value)} isn't ${allowed}; using the default`);
346
+ if (c.pages !== void 0) {
347
+ if (PAGES.includes(c.pages)) out.pages = c.pages;
348
+ else bad("pages", c.pages, '"masked", "hashed" or "off"');
349
+ }
350
+ if (c.addresses !== void 0) {
351
+ if (ADDRESSES.includes(c.addresses)) out.addresses = c.addresses;
352
+ else bad("addresses", c.addresses, '"hashed" or "off"');
353
+ }
354
+ for (const name of ["behavior", "requests"]) {
355
+ if (c[name] === void 0) continue;
356
+ const v = flag(c[name]);
357
+ if (v === void 0) bad(name, c[name], "true or false");
358
+ else out[name] = v;
359
+ }
360
+ if (c.skip !== void 0) {
361
+ const list = typeof c.skip === "string" ? c.skip.split(",") : Array.isArray(c.skip) ? c.skip : void 0;
362
+ if (!list) bad("skip", c.skip, "a list of paths");
363
+ else {
364
+ for (const raw of list) {
365
+ const p = typeof raw === "string" ? raw.trim() : raw;
366
+ if (p === "") continue;
367
+ if (typeof p === "string" && SKIP_PATTERN.test(p) && out.skip.length < MAX_SKIP) out.skip.push(p);
368
+ else bad("skip", p, `a path that starts with "/" (at most ${MAX_SKIP} of them)`);
369
+ }
370
+ }
371
+ }
372
+ return out;
373
+ }
374
+ function skipMatcher(patterns) {
375
+ if (!patterns.length) return () => false;
376
+ const res = patterns.map((p) => {
377
+ const tail = p.endsWith("/*");
378
+ const body = (tail ? p.slice(0, -2) : p).split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
379
+ return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`);
380
+ });
381
+ return (path) => {
382
+ const p = path.split(/[?#]/)[0] ?? path;
383
+ return res.some((re) => re.test(p));
384
+ };
385
+ }
386
+ function collectAttributes(c) {
387
+ const a = {};
388
+ if (c.pages !== DEFAULT_COLLECT.pages) a["data-pages"] = c.pages;
389
+ if (c.addresses !== DEFAULT_COLLECT.addresses) a["data-addresses"] = c.addresses;
390
+ if (!c.behavior) a["data-behavior"] = "off";
391
+ if (c.skip.length) a["data-skip"] = c.skip.join(",");
392
+ return a;
393
+ }
394
+ function collectReport(c) {
395
+ return { pages: c.pages, addresses: c.addresses, behavior: c.behavior };
396
+ }
397
+
398
+ // ../shared/src/allowance.ts
399
+ var Allowance = class {
400
+ constructor(capacity, refillPerMs, maxKeys = 1e5) {
401
+ this.capacity = capacity;
402
+ this.refillPerMs = refillPerMs;
403
+ this.maxKeys = maxKeys;
404
+ }
405
+ buckets = /* @__PURE__ */ new Map();
406
+ take(key, now = Date.now()) {
407
+ const b = this.refill(key, now);
408
+ if (b.tokens < 1) return false;
409
+ b.tokens -= 1;
410
+ return true;
411
+ }
412
+ /** Whether `take` would succeed now, without using anything. */
413
+ has(key, now = Date.now()) {
414
+ return this.refill(key, now).tokens >= 1;
415
+ }
416
+ refill(key, now) {
417
+ const prev = this.buckets.get(key);
418
+ const b = prev ? { tokens: Math.min(this.capacity, prev.tokens + (now - prev.at) * this.refillPerMs), at: now } : { tokens: this.capacity, at: now };
419
+ this.buckets.delete(key);
420
+ this.buckets.set(key, b);
421
+ if (this.buckets.size > this.maxKeys) this.buckets.delete(this.buckets.keys().next().value);
422
+ return b;
423
+ }
424
+ };
425
+
426
+ // ../shared/src/address.ts
427
+ var PLATFORM_HEADERS = {
428
+ fly: "fly-client-ip",
429
+ vercel: "x-vercel-forwarded-for",
430
+ railway: "x-real-ip",
431
+ netlify: "x-nf-client-connection-ip",
432
+ appengine: "x-appengine-user-ip",
433
+ workers: "cf-connecting-ip"
434
+ };
435
+ function detectPlatform(env) {
436
+ if (!env) return null;
437
+ if (env.FLY_APP_NAME) return "fly";
438
+ if (env.VERCEL) return "vercel";
439
+ if (env.RAILWAY_ENVIRONMENT_ID || env.RAILWAY_PROJECT_ID || env.RAILWAY_ENVIRONMENT) return "railway";
440
+ if (env.NETLIFY) return "netlify";
441
+ if (env.GAE_APPLICATION) return "appengine";
442
+ return null;
443
+ }
444
+ var CLOUDFLARE_RANGES = [
445
+ "173.245.48.0/20",
446
+ "103.21.244.0/22",
447
+ "103.22.200.0/22",
448
+ "103.31.4.0/22",
449
+ "141.101.64.0/18",
450
+ "108.162.192.0/18",
451
+ "190.93.240.0/20",
452
+ "188.114.96.0/20",
453
+ "197.234.240.0/22",
454
+ "198.41.128.0/17",
455
+ "162.158.0.0/15",
456
+ "104.16.0.0/13",
457
+ "104.24.0.0/14",
458
+ "172.64.0.0/13",
459
+ "131.0.72.0/22",
460
+ "2400:cb00::/32",
461
+ "2606:4700::/32",
462
+ "2803:f800::/32",
463
+ "2405:b500::/32",
464
+ "2405:8100::/32",
465
+ "2a06:98c0::/29",
466
+ "2c0f:f248::/32"
467
+ ];
468
+ var NON_PUBLIC_RANGES = [
469
+ "0.0.0.0/8",
470
+ "10.0.0.0/8",
471
+ "100.64.0.0/10",
472
+ "127.0.0.0/8",
473
+ "169.254.0.0/16",
474
+ "172.16.0.0/12",
475
+ "192.168.0.0/16",
476
+ "::/128",
477
+ "::1/128",
478
+ "fc00::/7",
479
+ "fe80::/10"
480
+ ];
481
+ var MAX_FORWARDED = 32;
482
+ function parseIpv4(s) {
483
+ const parts = s.split(".");
484
+ if (parts.length !== 4) return null;
485
+ const out = [];
486
+ for (const p of parts) {
487
+ if (!/^\d{1,3}$/.test(p) || p.length > 1 && p.startsWith("0")) return null;
488
+ const n = Number(p);
489
+ if (n > 255) return null;
490
+ out.push(n);
491
+ }
492
+ return out;
493
+ }
494
+ function parseIp(text) {
495
+ const s = text.trim();
496
+ if (!s) return null;
497
+ const v4 = parseIpv4(s);
498
+ if (v4) return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, ...v4]);
499
+ if (!s.includes(":") || !/^[0-9a-fA-F:.]+$/.test(s)) return null;
500
+ const halves = s.split("::");
501
+ if (halves.length > 2) return null;
502
+ const groups = (part) => {
503
+ if (part === "") return [];
504
+ const out = [];
505
+ const items = part.split(":");
506
+ for (let i = 0; i < items.length; i++) {
507
+ const it = items[i];
508
+ if (i === items.length - 1 && it.includes(".")) {
509
+ const tail2 = parseIpv4(it);
510
+ if (!tail2) return null;
511
+ out.push(tail2[0] << 8 | tail2[1], tail2[2] << 8 | tail2[3]);
512
+ } else {
513
+ if (!/^[0-9a-fA-F]{1,4}$/.test(it)) return null;
514
+ out.push(parseInt(it, 16));
515
+ }
516
+ }
517
+ return out;
518
+ };
519
+ const head = groups(halves[0]);
520
+ const tail = halves.length === 2 ? groups(halves[1]) : [];
521
+ if (!head || !tail) return null;
522
+ const total = head.length + tail.length;
523
+ if (halves.length === 2 ? total > 7 : total !== 8) return null;
524
+ const all = [...head, ...Array(8 - total).fill(0), ...tail];
525
+ const bytes = new Uint8Array(16);
526
+ all.forEach((g, i) => {
527
+ bytes[i * 2] = g >> 8;
528
+ bytes[i * 2 + 1] = g & 255;
529
+ });
530
+ return bytes;
531
+ }
532
+ var isMapped = (b) => b.slice(0, 10).every((x) => x === 0) && b[10] === 255 && b[11] === 255;
533
+ function formatIp(b) {
534
+ if (isMapped(b)) return `${b[12]}.${b[13]}.${b[14]}.${b[15]}`;
535
+ const g = [];
536
+ for (let i = 0; i < 8; i++) g.push(b[i * 2] << 8 | b[i * 2 + 1]);
537
+ let best = -1;
538
+ let bestLen = 0;
539
+ for (let i = 0; i < 8; ) {
540
+ if (g[i] !== 0) {
541
+ i++;
542
+ continue;
543
+ }
544
+ let j = i;
545
+ while (j < 8 && g[j] === 0) j++;
546
+ if (j - i > bestLen && j - i >= 2) {
547
+ best = i;
548
+ bestLen = j - i;
549
+ }
550
+ i = j;
551
+ }
552
+ const hex = (xs) => xs.map((x) => x.toString(16)).join(":");
553
+ if (best === -1) return hex(g);
554
+ return `${hex(g.slice(0, best))}::${hex(g.slice(best + bestLen))}`;
555
+ }
556
+ function normalizeIp(token) {
557
+ if (!token) return null;
558
+ let s = token.trim().replace(/^"(.*)"$/, "$1");
559
+ if (s.startsWith("[")) {
560
+ const end = s.indexOf("]");
561
+ if (end < 0) return null;
562
+ s = s.slice(1, end);
563
+ } else {
564
+ const v4port = /^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(s);
565
+ if (v4port) s = v4port[1];
566
+ }
567
+ const zone = s.indexOf("%");
568
+ if (zone > 0) s = s.slice(0, zone);
569
+ let b = parseIp(s);
570
+ if (!b && s.includes(":")) {
571
+ const cut = /^(.*):\d{1,5}$/.exec(s);
572
+ if (cut) b = parseIp(cut[1]);
573
+ }
574
+ return b ? formatIp(b) : null;
575
+ }
576
+ function parseCidr(text) {
577
+ const [addr, len, extra] = text.trim().split("/");
578
+ if (extra !== void 0 || !addr) return null;
579
+ const bytes = parseIp(addr);
580
+ if (!bytes) return null;
581
+ const v4 = parseIpv4(addr.trim()) !== null;
582
+ const max = v4 ? 32 : 128;
583
+ if (len !== void 0 && !/^\d{1,3}$/.test(len)) return null;
584
+ const n = len === void 0 ? max : Number(len);
585
+ if (n > max) return null;
586
+ return { bytes, bits: v4 ? n + 96 : n };
587
+ }
588
+ function inCidr(c, b) {
589
+ let bits = c.bits;
590
+ for (let i = 0; i < 16 && bits > 0; i++, bits -= 8) {
591
+ const mask = bits >= 8 ? 255 : 255 << 8 - bits & 255;
592
+ if ((c.bytes[i] & mask) !== (b[i] & mask)) return false;
593
+ }
594
+ return true;
595
+ }
596
+ var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
597
+ var NON_PUBLIC = compile(NON_PUBLIC_RANGES);
598
+ var CLOUDFLARE = compile(CLOUDFLARE_RANGES);
599
+ function ipInRanges(address, ranges) {
600
+ const b = parseIp(address);
601
+ if (!b) return false;
602
+ const cidrs = typeof ranges[0] === "string" ? compile(ranges) : ranges;
603
+ return cidrs.some((c) => inCidr(c, b));
604
+ }
605
+ function isPublicIp(address) {
606
+ const b = parseIp(address);
607
+ return !!b && !NON_PUBLIC.some((c) => inCidr(c, b));
608
+ }
609
+ function chainOf(req) {
610
+ const xff = req.header("x-forwarded-for") ?? "";
611
+ const entries = xff.split(",").map((s) => s.trim()).filter(Boolean).slice(-MAX_FORWARDED);
612
+ return [...entries, req.peer];
613
+ }
614
+ var result = (address, via) => ({ address, internal: !isPublicIp(address), via });
615
+ function walk(req, trusted, via) {
616
+ const chain = chainOf(req);
617
+ let last = "";
618
+ for (let i = chain.length - 1; i >= 0; i--) {
619
+ const ip = normalizeIp(chain[i]);
620
+ if (!ip) continue;
621
+ last ||= ip;
622
+ const b = parseIp(ip);
623
+ if (NON_PUBLIC.some((c) => inCidr(c, b)) || trusted.some((c) => inCidr(c, b))) continue;
624
+ return { address: ip, internal: false, via: i === chain.length - 1 ? "socket" : via };
625
+ }
626
+ return { address: last, internal: true, via: "socket" };
627
+ }
628
+ function resolveClientAddress(req, mode = "auto", platform = null) {
629
+ const peer = normalizeIp(req.peer) ?? "";
630
+ if (mode === "socket") return result(peer, "socket");
631
+ if (typeof mode === "object" && "header" in mode) {
632
+ const first = req.header(mode.header.toLowerCase())?.split(",")[0];
633
+ const ip = normalizeIp(first);
634
+ return ip ? result(ip, "header") : result(peer, "socket");
635
+ }
636
+ if (typeof mode === "object" && "hops" in mode) {
637
+ const chain = chainOf(req).map((t) => normalizeIp(t)).filter((x) => !!x);
638
+ if (!chain.length) return result("", "socket");
639
+ const at = Math.max(0, chain.length - 1 - mode.hops);
640
+ return result(chain[at], at === chain.length - 1 ? "socket" : "hops");
641
+ }
642
+ if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies");
643
+ const framework = normalizeIp(req.framework);
644
+ if (framework) return result(framework, "framework");
645
+ if (platform) {
646
+ const ip = normalizeIp(req.header(PLATFORM_HEADERS[platform])?.split(",")[0]);
647
+ if (ip) return result(ip, `platform:${platform}`);
648
+ }
649
+ if (peer && ipInRanges(peer, CLOUDFLARE)) {
650
+ const ip = normalizeIp(req.header("cf-connecting-ip"));
651
+ if (ip) return result(ip, "cloudflare");
652
+ }
653
+ return walk(req, [], "forwarded");
654
+ }
655
+ function clientIpModeProblem(value) {
656
+ if (value === "auto" || value === "socket") return null;
657
+ if (!value || typeof value !== "object" || Array.isArray(value)) return 'must be "auto", "socket", { header }, { proxies } or { hops }';
658
+ const keys2 = Object.keys(value);
659
+ if (keys2.length !== 1) return "must set exactly one of header, proxies or hops";
660
+ const v = value;
661
+ if ("header" in v) return typeof v.header === "string" && /^[A-Za-z0-9-]+$/.test(v.header) ? null : "header must be a header name";
662
+ if ("hops" in v) return Number.isInteger(v.hops) && v.hops >= 1 && v.hops <= MAX_FORWARDED ? null : `hops must be a whole number from 1 to ${MAX_FORWARDED}`;
663
+ if ("proxies" in v) {
664
+ if (!Array.isArray(v.proxies) || !v.proxies.length) return "proxies must be a non-empty list of addresses or ranges";
665
+ const bad = v.proxies.find((p) => typeof p !== "string" || !parseCidr(p));
666
+ return bad === void 0 ? null : `proxies has an entry that is not an address or range: ${JSON.stringify(bad)}`;
667
+ }
668
+ return "must set exactly one of header, proxies or hops";
669
+ }
670
+
671
+ // ../shared/src/paths.ts
672
+ function decodeOnce(s) {
673
+ if (!s.includes("%")) return s;
674
+ try {
675
+ return decodeURIComponent(s);
676
+ } catch {
677
+ return s.replace(/%([0-7][0-9a-fA-F])/g, (_, h) => String.fromCharCode(parseInt(h, 16)));
678
+ }
679
+ }
680
+ function normalizeSegments(path) {
681
+ const collapsed = path.replace(/\/{2,}/g, "/");
682
+ const segs = collapsed.split("/");
683
+ const out = [];
684
+ for (let i = 1; i < segs.length; i++) {
685
+ const s = segs[i];
686
+ const last = i === segs.length - 1;
687
+ if (s === ".") {
688
+ if (last) out.push("");
689
+ } else if (s === "..") {
690
+ out.pop();
691
+ if (last) out.push("");
692
+ } else out.push(s);
693
+ }
694
+ return `/${out.join("/")}`;
695
+ }
696
+ function canonicalPath(target) {
697
+ let t = target || "/";
698
+ const abs = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]*/.exec(t);
699
+ if (abs) t = t.slice(abs[0].length) || "/";
700
+ const cut = t.search(/[?#]/);
701
+ let raw = cut === -1 ? t : t.slice(0, cut);
702
+ if (!raw.startsWith("/")) raw = `/${raw}`;
703
+ return { raw, decoded: normalizeSegments(decodeOnce(raw)) };
704
+ }
705
+ function matchesEither(matcher, p) {
706
+ return matcher(p.raw) || matcher(p.decoded);
707
+ }
708
+ function matchesBoth(matcher, p) {
709
+ return matcher(p.raw) && matcher(p.decoded);
710
+ }
711
+ function isSourceMapPath(p) {
712
+ return /\.map$/i.test(p.raw) || /\.map$/i.test(p.decoded);
713
+ }
714
+
715
+ // src/core.ts
716
+ var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
717
+ function withFlagged(p, source = "browser") {
718
+ return {
719
+ ...p,
720
+ source,
721
+ flagged({ labels, minStage = "candidate" } = {}) {
722
+ const want = typeof labels === "string" ? [labels] : labels?.length ? labels : void 0;
723
+ const rank = STAGE_RANK[minStage] ?? 0;
724
+ return p.claims.some((c) => (STAGE_RANK[c.stage] ?? -1) >= rank && (!want || want.includes(c.label)));
725
+ }
726
+ };
727
+ }
728
+ function mergeVerdicts(browser, pushed) {
729
+ if (!pushed) return browser;
730
+ if (!browser) return withFlagged(pushed, "server");
731
+ const rules = new Set(browser.claims.map((c) => `${c.rule}|${c.label}|${c.stage}`));
732
+ 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");
735
+ }
736
+ async function readVerdictFrom(secret, site, cookieHeader) {
737
+ const token = cookieValue(cookieHeader, VERDICT_COOKIE);
738
+ if (!token) return null;
739
+ const p = await verifyVerdict(secret, token, { site, sid: cookieValue(cookieHeader, SESSION_COOKIE) });
740
+ return p ? withFlagged(p) : null;
741
+ }
742
+ function looksCurrent(site, cookieHeader, now = Date.now()) {
743
+ const token = cookieValue(cookieHeader, VERDICT_COOKIE);
744
+ const parts = token?.split(".");
745
+ if (parts?.length !== 3 || parts[0] !== "v1") return false;
746
+ try {
747
+ const json = atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"));
748
+ const p = JSON.parse(json);
749
+ return p.site === site && typeof p.exp === "number" && p.exp > now && p.sid === cookieValue(cookieHeader, SESSION_COOKIE);
750
+ } catch {
751
+ return false;
752
+ }
753
+ }
754
+ var DEFAULT_COLLECTOR = "https://api.reguard.site";
755
+ function collectorBase(collector) {
756
+ return (collector ?? DEFAULT_COLLECTOR).replace(/\/+$/, "").replace(/\/_s$/, "");
757
+ }
758
+ function envValue(name) {
759
+ return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
760
+ }
761
+ var VERDICT_TTL_MS = 10 * 6e4;
762
+ var DEFAULT_PACE = {
763
+ documents: { burst: 30, perSecond: 1 },
764
+ api: { burst: 60, perSecond: 5 },
765
+ notFound: { burst: 20, perSecond: 0.5 }
766
+ };
767
+ function freshSeconds(cfg) {
768
+ return cfg?.require ? Math.max(5, Math.floor(cfg.maxAgeMs / 2e3)) : void 0;
769
+ }
770
+ function verdictAgeMs(v, now = Date.now()) {
771
+ return now - (v.exp - VERDICT_TTL_MS);
772
+ }
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");
775
+ }
776
+ var ANSWER_CODES = { flagged: "reguard.blocked", flagged_server: "reguard.blocked", require: "reguard.require", pace: "reguard.pace" };
777
+ var RETRY_AFTER = { flagged: 120, flagged_server: 120, require: 5, pace: 2 };
778
+ var page = (title, text) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title}</title></head><body><h1>${title}</h1><p>${text}</p></body></html>`;
779
+ var BLOCK_HTML = page("Please slow down", "This browser looks like it is being driven by an automated tool. Try again in a few minutes.");
780
+ var REQUIRE_HTML = page("Reload the page to continue", "This page needs its security check to run. Reload the page; if this keeps happening, allow scripts from this site.");
781
+ var PACE_TEXT = "Too many requests. Slow down and try again in a moment.";
782
+ var MESSAGES = {
783
+ flagged: "Too many automated requests from this browser. Try again in a few minutes.",
784
+ flagged_server: "Too many automated requests from this browser. Try again in a few minutes.",
785
+ require: "This request needs the page's security check. Reload the page and try again.",
786
+ pace: PACE_TEXT
787
+ };
788
+ function defaultAnswer(reason, wantsHtml) {
789
+ if (wantsHtml) {
790
+ if (reason === "pace") return { contentType: "text/plain; charset=utf-8", body: PACE_TEXT };
791
+ return { contentType: "text/html; charset=utf-8", body: reason === "require" ? REQUIRE_HTML : BLOCK_HTML };
792
+ }
793
+ return { contentType: "application/json", body: JSON.stringify({ error: MESSAGES[reason], code: ANSWER_CODES[reason] }) };
794
+ }
795
+ function wantsPage(get) {
796
+ return get("sec-fetch-dest") === "document" || /text\/html/i.test(get("accept") ?? "");
797
+ }
798
+ function isReguardPath(path) {
799
+ return path === "/_s" || path.startsWith("/_s/");
800
+ }
801
+ function isPreflight(method, get) {
802
+ return method === "OPTIONS" && !!get("access-control-request-method");
803
+ }
804
+ var escapeAttr = (v) => v.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
805
+ function renderScriptTag(t, nonce) {
806
+ const attrs = { ...collectAttributes(t.collect) };
807
+ if (t.fresh) attrs["data-fresh"] = String(t.fresh);
808
+ if (t.cookieDomain) attrs["data-cookie-domain"] = t.cookieDomain;
809
+ if (nonce && /^[A-Za-z0-9+/=_-]{1,200}$/.test(nonce)) attrs.nonce = nonce;
810
+ const rest = Object.entries(attrs).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("");
811
+ return `<script async src="${t.prefix ?? "/_s"}/sdk.js" data-site="${t.site.replace(/[^\w.-]/g, "")}"${rest}></script>`;
812
+ }
813
+ function cspNonce(csp) {
814
+ if (!csp) return void 0;
815
+ const directives = csp.split(";").map((d) => d.trim().split(/\s+/));
816
+ const pick = (name) => directives.find((d) => d[0]?.toLowerCase() === name);
817
+ const src = pick("script-src-elem") ?? pick("script-src") ?? pick("default-src");
818
+ const m = src?.slice(1).map((t) => /^'nonce-([A-Za-z0-9+/=_-]+)'$/.exec(t)).find(Boolean);
819
+ return m?.[1];
820
+ }
821
+
822
+ // src/config.ts
823
+ var ReguardConfigError = class extends TypeError {
824
+ option;
825
+ code;
826
+ constructor(option, code, detail) {
827
+ super(`[reguard] ${option} ${detail}`);
828
+ this.name = "ReguardConfigError";
829
+ this.option = option;
830
+ this.code = code;
831
+ }
832
+ };
833
+ var BLOCK_REASONS = ["flagged", "flagged_server", "require", "pace"];
834
+ var LABELS = ["rea", "automated_exploration", "unauthorized_extraction"];
835
+ var STAGES = ["candidate", "alert", "enforce"];
836
+ var fail = (option, code, detail) => {
837
+ throw new ReguardConfigError(option, code, detail);
838
+ };
839
+ var show = (v) => typeof v === "function" ? "a function" : JSON.stringify(v) ?? String(v);
840
+ var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
841
+ var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
842
+ function checkKeys(obj, allowed, prefix, moved = {}) {
843
+ for (const k of Object.keys(obj)) {
844
+ if (obj[k] === void 0 || allowed.includes(k)) continue;
845
+ const path = prefix ? `${prefix}.${k}` : k;
846
+ if (moved[k]) fail(path, "removed_option", `was removed: ${moved[k]}`);
847
+ const c = camel(k).replace(/Seconds$|Secs$/, "Ms");
848
+ const hint = allowed.find((a) => a === c || a === camel(k) || a.toLowerCase() === k.toLowerCase());
849
+ fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${prefix ? `${prefix}.` : ""}${hint}?)` : ""}`);
850
+ }
851
+ }
852
+ function checkBoolean(v, option) {
853
+ if (v === void 0) return void 0;
854
+ if (typeof v !== "boolean") fail(option, "invalid_type", `must be true or false (got ${show(v)})`);
855
+ return v;
856
+ }
857
+ function checkFunction(v, option) {
858
+ if (v === void 0) return void 0;
859
+ if (typeof v !== "function") fail(option, "invalid_type", `must be a function (got ${show(v)})`);
860
+ return v;
861
+ }
862
+ function checkString(v, option) {
863
+ if (v === void 0) return void 0;
864
+ if (typeof v !== "string") fail(option, "invalid_type", `must be a string (got ${show(v)})`);
865
+ return v;
866
+ }
867
+ function checkNumber(v, option, min, max, integer = true) {
868
+ if (v === void 0) return void 0;
869
+ if (typeof v !== "number" || !Number.isFinite(v)) fail(option, "invalid_type", `must be a number (got ${show(v)})`);
870
+ const n = v;
871
+ if (integer && !Number.isInteger(n)) fail(option, "invalid_value", `must be a whole number (got ${n})`);
872
+ if (n < min || n > max) fail(option, "out_of_range", `must be from ${min} to ${max} (got ${n})`);
873
+ return n;
874
+ }
875
+ function checkOneOf(v, option, allowed) {
876
+ if (v === void 0) return void 0;
877
+ if (typeof v !== "string") fail(option, "invalid_type", `must be one of ${allowed.map((a) => `"${a}"`).join(", ")} (got ${show(v)})`);
878
+ if (!allowed.includes(v)) fail(option, "invalid_value", `must be one of ${allowed.map((a) => `"${a}"`).join(", ")} (got ${show(v)})`);
879
+ return v;
880
+ }
881
+ var PATH_PATTERN = /^\/[\w\-.~%!$&'()*+;=:@/]{0,199}$/;
882
+ var MAX_PATHS = 50;
883
+ function checkPaths(v, option, commas = false) {
884
+ if (v === void 0) return void 0;
885
+ const list = commas && typeof v === "string" ? v.split(",").map((s) => s.trim()).filter(Boolean) : v;
886
+ if (!Array.isArray(list)) fail(option, "invalid_type", `must be a list of paths like "/api/*" (got ${show(v)})`);
887
+ const out = [];
888
+ for (const p of list) {
889
+ if (typeof p !== "string" || !PATH_PATTERN.test(p)) fail(option, "invalid_value", `has an entry that isn't a path starting with "/": ${show(p)}`);
890
+ out.push(p);
891
+ }
892
+ if (out.length > MAX_PATHS) fail(option, "out_of_range", `can hold at most ${MAX_PATHS} paths (got ${out.length})`);
893
+ return out;
894
+ }
895
+ function checkCollect(v, option = "collect") {
896
+ if (v === void 0 || v === null) return resolveCollect(void 0);
897
+ if (!isObject(v)) fail(option, "invalid_type", `must be an object (got ${show(v)})`);
898
+ const c = v;
899
+ checkKeys(c, ["pages", "addresses", "behavior", "requests", "skip"], option);
900
+ checkOneOf(c.pages, `${option}.pages`, ["masked", "hashed", "off"]);
901
+ checkOneOf(c.addresses, `${option}.addresses`, ["hashed", "off"]);
902
+ checkBoolean(c.behavior, `${option}.behavior`);
903
+ checkBoolean(c.requests, `${option}.requests`);
904
+ const skip = checkPaths(c.skip, `${option}.skip`, true);
905
+ return resolveCollect({ ...c, ...skip ? { skip } : {} });
906
+ }
907
+ function checkClientIp(v, option = "clientIp") {
908
+ if (v === void 0) return "auto";
909
+ if (typeof v === "function") return v;
910
+ const problem = clientIpModeProblem(v);
911
+ if (problem) fail(option, typeof v === "object" && v !== null ? "invalid_value" : "invalid_type", problem);
912
+ return v;
913
+ }
914
+ var DOMAIN = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
915
+ function checkCookieDomain(v, option = "cookieDomain") {
916
+ const s = checkString(v, option);
917
+ if (s === void 0) return void 0;
918
+ const d = s.trim().toLowerCase().replace(/^\./, "");
919
+ if (!DOMAIN.test(d)) fail(option, "invalid_value", `must be a domain like "example.com" (got ${show(s)})`);
920
+ return d;
921
+ }
922
+ function checkCollector(v, option = "collector") {
923
+ const s = checkString(v, option);
924
+ if (s === void 0) return void 0;
925
+ if (!/^https?:\/\/[^/?#\s]+(?:\/[^?#\s]*)?$/i.test(s)) fail(option, "invalid_value", `must be an http(s) URL (got ${show(s)})`);
926
+ return s;
927
+ }
928
+ function checkLogger(v, option = "logger") {
929
+ if (v === void 0 || v === false) return v;
930
+ if (!isObject(v) && typeof v !== "function") fail(option, "invalid_type", `must be an object with warn and error methods, or false (got ${show(v)})`);
931
+ const l = v;
932
+ if (typeof l.warn !== "function" || typeof l.error !== "function") fail(option, "invalid_value", "must have warn and error methods");
933
+ return v;
934
+ }
935
+ var BLOCK_KEYS = [
936
+ "labels",
937
+ "status",
938
+ "minStage",
939
+ "dryRun",
940
+ "allow",
941
+ "allowIf",
942
+ "respond",
943
+ "onBlock",
944
+ "require",
945
+ "requireMaxAgeMs",
946
+ "requireGraceMs",
947
+ "requireGraceRequests",
948
+ "requireGracePages",
949
+ "requireRefreshRequests",
950
+ "requireRefreshMs",
951
+ "pace"
952
+ ];
953
+ function checkRate(v, option, base) {
954
+ if (v === void 0) return base;
955
+ if (!isObject(v)) fail(option, "invalid_type", `must be { burst, perSecond } (got ${show(v)})`);
956
+ const r = v;
957
+ checkKeys(r, ["burst", "perSecond"], option);
958
+ const burst = checkNumber(r.burst, `${option}.burst`, 1, 1e5) ?? base.burst;
959
+ const perSecond = checkNumber(r.perSecond, `${option}.perSecond`, 1e-3, 1e4, false) ?? base.perSecond;
960
+ return { burst, perSecond };
961
+ }
962
+ function checkBlock(v, option = "block", runtime = "node") {
963
+ if (v === void 0 || v === false || v === null) return null;
964
+ if (v !== true && !isObject(v)) fail(option, "invalid_type", `must be true, false or an object (got ${show(v)})`);
965
+ const b = v === true ? {} : v;
966
+ checkKeys(b, BLOCK_KEYS, option);
967
+ if (runtime === "fetch") {
968
+ for (const k of ["require", "requireMaxAgeMs", "requireGraceMs", "requireGraceRequests", "requireGracePages", "requireRefreshRequests", "requireRefreshMs"])
969
+ if (b[k] !== void 0) fail(`${option}.${k}`, "invalid_value", "needs reguard() in a Node server (it keeps page grace in memory across requests); the edge helpers can't enforce it");
970
+ }
971
+ let labels;
972
+ if (b.labels !== void 0) {
973
+ if (!Array.isArray(b.labels)) fail(`${option}.labels`, "invalid_type", `must be a list of labels (got ${show(b.labels)})`);
974
+ const list = b.labels;
975
+ if (!list.length) fail(`${option}.labels`, "empty_list", "is empty; leave it out to block on any label");
976
+ for (const l of list) checkOneOf(l, `${option}.labels`, LABELS);
977
+ labels = list;
978
+ }
979
+ let dryRun = /* @__PURE__ */ new Set();
980
+ if (b.dryRun === true) dryRun = new Set(BLOCK_REASONS);
981
+ else if (Array.isArray(b.dryRun)) {
982
+ if (!b.dryRun.length) fail(`${option}.dryRun`, "empty_list", "is empty; use false, true, or a list of reasons");
983
+ for (const r of b.dryRun) dryRun.add(checkOneOf(r, `${option}.dryRun`, BLOCK_REASONS));
984
+ } else if (b.dryRun !== void 0 && b.dryRun !== false) fail(`${option}.dryRun`, "invalid_type", `must be true, false or a list of reasons (got ${show(b.dryRun)})`);
985
+ const require2 = checkPaths(b.require, `${option}.require`);
986
+ let pace = { ...DEFAULT_PACE };
987
+ if (b.pace === false) pace = null;
988
+ else if (b.pace !== void 0 && b.pace !== true) {
989
+ if (!isObject(b.pace)) fail(`${option}.pace`, "invalid_type", `must be true, false or an object (got ${show(b.pace)})`);
990
+ const p = b.pace;
991
+ checkKeys(p, ["documents", "api", "notFound"], `${option}.pace`);
992
+ pace = {
993
+ documents: checkRate(p.documents, `${option}.pace.documents`, DEFAULT_PACE.documents),
994
+ api: checkRate(p.api, `${option}.pace.api`, DEFAULT_PACE.api),
995
+ notFound: checkRate(p.notFound, `${option}.pace.notFound`, DEFAULT_PACE.notFound)
996
+ };
997
+ }
998
+ return {
999
+ labels,
1000
+ status: checkNumber(b.status, `${option}.status`, 400, 599) ?? 429,
1001
+ minStage: checkOneOf(b.minStage, `${option}.minStage`, STAGES) ?? "candidate",
1002
+ dryRun,
1003
+ allow: checkPaths(b.allow, `${option}.allow`) ?? [],
1004
+ require: require2?.length ? require2 : void 0,
1005
+ maxAgeMs: checkNumber(b.requireMaxAgeMs, `${option}.requireMaxAgeMs`, 1e3, 6e5) ?? 6e4,
1006
+ graceMs: checkNumber(b.requireGraceMs, `${option}.requireGraceMs`, 0, 6e5) ?? 15e3,
1007
+ graceRequests: checkNumber(b.requireGraceRequests, `${option}.requireGraceRequests`, 0, 1e5) ?? 30,
1008
+ gracePages: checkNumber(b.requireGracePages, `${option}.requireGracePages`, 0, 1e3) ?? 3,
1009
+ refreshRequests: checkNumber(b.requireRefreshRequests, `${option}.requireRefreshRequests`, 0, 1e5) ?? 30,
1010
+ refreshMs: checkNumber(b.requireRefreshMs, `${option}.requireRefreshMs`, 0, 6e5) ?? 1e4,
1011
+ pace,
1012
+ allowIf: checkFunction(b.allowIf, `${option}.allowIf`),
1013
+ respond: checkFunction(b.respond, `${option}.respond`),
1014
+ onBlock: checkFunction(b.onBlock, `${option}.onBlock`)
1015
+ };
1016
+ }
1017
+ var NODE_OPTION_KEYS = [
1018
+ "key",
1019
+ "previousKey",
1020
+ "collector",
1021
+ "inject",
1022
+ "block",
1023
+ "sourceMaps",
1024
+ "ignore",
1025
+ "ignoreIf",
1026
+ "collect",
1027
+ "watchSessionless",
1028
+ "clientIp",
1029
+ "cookieDomain",
1030
+ "debug",
1031
+ "logger",
1032
+ "timeoutMs",
1033
+ "fetch",
1034
+ "onError",
1035
+ "flushIntervalMs"
1036
+ ];
1037
+ var MOVED_OPTIONS = {
1038
+ forward: "use collect: { requests: false } to stop request summaries"
1039
+ };
1040
+ function checkOptions(options) {
1041
+ if (options === void 0 || options === null) options = {};
1042
+ if (!isObject(options)) fail("options", "invalid_type", `must be an object (got ${show(options)})`);
1043
+ const o = options;
1044
+ checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS);
1045
+ if (typeof o.ignore === "function") fail("ignore", "invalid_type", "is now a list of paths; use ignoreIf for a function");
1046
+ return {
1047
+ key: checkString(o.key, "key"),
1048
+ previousKey: checkString(o.previousKey, "previousKey"),
1049
+ collector: checkCollector(o.collector),
1050
+ inject: checkBoolean(o.inject, "inject") ?? true,
1051
+ block: checkBlock(o.block),
1052
+ sourceMaps: checkOneOf(o.sourceMaps, "sourceMaps", ["deny", "allow"]),
1053
+ ignore: checkPaths(o.ignore, "ignore") ?? [],
1054
+ ignoreIf: checkFunction(o.ignoreIf, "ignoreIf"),
1055
+ collect: checkCollect(o.collect),
1056
+ watchSessionless: checkBoolean(o.watchSessionless, "watchSessionless") ?? true,
1057
+ clientIp: checkClientIp(o.clientIp),
1058
+ cookieDomain: checkCookieDomain(o.cookieDomain),
1059
+ debug: checkBoolean(o.debug, "debug"),
1060
+ logger: checkLogger(o.logger),
1061
+ timeoutMs: checkNumber(o.timeoutMs, "timeoutMs", 100, 12e4) ?? 1e4,
1062
+ fetch: checkFunction(o.fetch, "fetch"),
1063
+ onError: checkFunction(o.onError, "onError"),
1064
+ flushIntervalMs: checkNumber(o.flushIntervalMs, "flushIntervalMs", 10, 36e5) ?? 2e3
1065
+ };
1066
+ }
1067
+
1068
+ // src/health.ts
1069
+ var seenBy = /* @__PURE__ */ new WeakMap();
1070
+ function makeLog(logger, debugging) {
1071
+ const out = logger === false ? null : logger ?? console;
1072
+ let seen = out ? seenBy.get(out) : void 0;
1073
+ if (out && !seen) {
1074
+ seen = /* @__PURE__ */ new Set();
1075
+ seenBy.set(out, seen);
1076
+ }
1077
+ const say = (level, message) => {
1078
+ if (!out) return;
1079
+ const fn = level === "debug" ? out.debug ?? out.info ?? out.warn : level === "info" ? out.info ?? out.warn : out[level];
1080
+ try {
1081
+ fn.call(out, `[reguard] ${message}`);
1082
+ } catch {
1083
+ }
1084
+ };
1085
+ return {
1086
+ warn: (m) => say("warn", m),
1087
+ error: (m) => say("error", m),
1088
+ info: (m) => say("info", m),
1089
+ debug: (m) => {
1090
+ if (debugging) say("debug", m);
1091
+ },
1092
+ once: (kind, level, m) => {
1093
+ if (!seen || seen.has(kind)) return;
1094
+ seen.add(kind);
1095
+ say(level, m);
1096
+ },
1097
+ debugging
1098
+ };
1099
+ }
1100
+ var PAUSE_MS = 60 * 6e4;
1101
+ var REJECTED_RETRY_MS = 5 * 6e4;
1102
+ var Health = class {
1103
+ constructor(log, now = Date.now) {
1104
+ this.log = log;
1105
+ this.now = now;
1106
+ this.since = now();
1107
+ }
1108
+ state = "ok";
1109
+ since;
1110
+ lastError;
1111
+ pausedUntil = 0;
1112
+ retryAt = 0;
1113
+ move(state, error) {
1114
+ if (state !== this.state) this.since = this.now();
1115
+ this.state = state;
1116
+ this.lastError = error;
1117
+ }
1118
+ ok() {
1119
+ if (this.state !== "ok") this.log.info("reaching Reguard again: summaries and require routes are back to normal");
1120
+ this.move("ok");
1121
+ }
1122
+ failing(error) {
1123
+ if (this.state === "ok") this.log.warn(`can't reach Reguard (${error}): summaries are dropped and require routes stay open until it answers`);
1124
+ this.move("failing", error);
1125
+ }
1126
+ rejected(status) {
1127
+ if (this.state !== "rejected")
1128
+ this.log.error(
1129
+ `Reguard rejected REGUARD_KEY (HTTP ${status}): it is wrong or was rotated. Copy the current key from the dashboard (Settings, Site key). Verdicts won't verify and require routes stay open until it is fixed.`
1130
+ );
1131
+ this.retryAt = this.now() + REJECTED_RETRY_MS;
1132
+ this.move("rejected", `HTTP ${status}`);
1133
+ }
1134
+ paused() {
1135
+ if (this.state !== "paused") this.log.warn("your plan's monthly requests are used up: summaries are paused for an hour and require routes stay open (browsers stop starting too). Upgrade under Billing.");
1136
+ this.pausedUntil = this.now() + PAUSE_MS;
1137
+ this.move("paused", "HTTP 429");
1138
+ }
1139
+ /** Whether a batch may be sent now (not while paused or waiting after a rejection). */
1140
+ canSend() {
1141
+ const now = this.now();
1142
+ return now >= this.pausedUntil && now >= this.retryAt;
1143
+ }
1144
+ /** `require` routes are not enforced while this is true. */
1145
+ get failOpen() {
1146
+ return this.state !== "ok";
1147
+ }
1148
+ };
1149
+
1150
+ // src/index.ts
1151
+ var PREFIX = "/_s";
1152
+ var NOT_FORWARDED = /* @__PURE__ */ new Set([
1153
+ "connection",
1154
+ "keep-alive",
1155
+ "proxy-authenticate",
1156
+ "proxy-authorization",
1157
+ "te",
1158
+ "trailer",
1159
+ "transfer-encoding",
1160
+ "upgrade",
1161
+ "host",
1162
+ "content-length",
1163
+ "expect",
1164
+ "accept-encoding",
1165
+ "cookie",
1166
+ "authorization"
1167
+ ]);
1168
+ var STRIP_FROM_RESPONSE = /* @__PURE__ */ new Set(["content-encoding", "content-length", "transfer-encoding", "connection", "keep-alive", "set-cookie"]);
1169
+ var ADDRESS_HEADER = /^(?:x-forwarded-for|forwarded|x-real-ip|x-original-forwarded-for|x-envoy-external-address|x-nf-client-connection-ip|x-vercel-forwarded-for|x-vercel-proxied-for|fly-client-ip)$|client-?ip|connecting-ip|^cf-ip|^cf-(?:region|metro|postal|timezone)|^x-vercel-ip-|^cloudfront-viewer-|^x-appengine-(?:user-ip|city|country|region)/;
1170
+ var SCAN_LIMIT = 64 * 1024;
1171
+ function visitorHash(secret, address) {
1172
+ return (0, import_node_crypto.createHmac)("sha256", secret).update(`visitor:${address}`).digest("base64url").slice(0, 22);
1173
+ }
1174
+ function keyFingerprint(secret) {
1175
+ return (0, import_node_crypto.createHash)("sha256").update(`reguard-key:${secret}`).digest("base64url").slice(0, 8);
1176
+ }
1177
+ function visitorHeader(secret, address, addresses) {
1178
+ const value = addresses === "off" || !address ? "-" : visitorHash(secret, address);
1179
+ return `${value}.${(0, import_node_crypto.createHmac)("sha256", secret).update(`visitor-header:${value}`).digest("base64url").slice(0, 16)}`;
1180
+ }
1181
+ var ADDRESS = /* @__PURE__ */ new WeakMap();
1182
+ function addressOf(req) {
1183
+ return ADDRESS.get(req) ?? resolveClientAddress({ peer: req.socket?.remoteAddress ?? "", header: (n) => header(req.headers, n) }, "socket");
1184
+ }
1185
+ function refererOrigin(v) {
1186
+ try {
1187
+ const u = new URL(v);
1188
+ return u.origin === "null" ? void 0 : `${u.origin}/`;
1189
+ } catch {
1190
+ return void 0;
1191
+ }
1192
+ }
1193
+ function headersForReguard(req, secret, siteTag, collect) {
1194
+ const headers = new Headers();
1195
+ for (const [k, v] of Object.entries(req.headers)) {
1196
+ if (v === void 0 || NOT_FORWARDED.has(k) || k.startsWith(":") || k.startsWith("x-reguard-") || k === "referer" || ADDRESS_HEADER.test(k)) continue;
1197
+ try {
1198
+ headers.set(k, Array.isArray(v) ? v.join(", ") : v);
1199
+ } catch {
1200
+ }
1201
+ }
1202
+ const referer = header(req.headers, "referer");
1203
+ const origin = referer ? refererOrigin(referer) : void 0;
1204
+ if (origin) headers.set("referer", origin);
1205
+ const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
1206
+ if (sid && /^[\w-]{1,64}$/.test(sid)) headers.set("cookie", `${SESSION_COOKIE}=${sid}`);
1207
+ headers.set("x-reguard-site", siteTag);
1208
+ headers.set("x-reguard-visitor", visitorHeader(secret, addressOf(req).address, collect.addresses));
1209
+ return headers;
1210
+ }
1211
+ function siteTagOf(site, secret) {
1212
+ return `${site}.${(0, import_node_crypto.createHmac)("sha256", secret).update(`prefix:${site}`).digest("base64url").slice(0, 16)}`;
1213
+ }
1214
+ var PACED = /* @__PURE__ */ new WeakMap();
1215
+ var DECIDED = /* @__PURE__ */ new WeakMap();
1216
+ function stripSourceMapHeaders(res) {
1217
+ const isMapHeader = (name) => typeof name === "string" && /^(?:x-)?sourcemap$/i.test(name);
1218
+ const setHeader = res.setHeader.bind(res);
1219
+ res.setHeader = ((name, value) => isMapHeader(name) ? res : setHeader(name, value));
1220
+ const writeHead = res.writeHead.bind(res);
1221
+ res.writeHead = (...a) => {
1222
+ const h = a.find((x, i) => i > 0 && x && typeof x === "object" && !Array.isArray(x));
1223
+ if (h) {
1224
+ for (const k of Object.keys(h)) if (isMapHeader(k)) delete h[k];
1225
+ }
1226
+ for (const k of res.getHeaderNames()) if (isMapHeader(k)) res.removeHeader(k);
1227
+ return writeHead(...a);
1228
+ };
1229
+ }
1230
+ function withoutEndpoint(d, pages, hash) {
1231
+ if (pages === "masked") return d;
1232
+ if (pages === "hashed") return { ...d, endpoint: `~${hash(`endpoint:${d.endpoint}`)}` };
1233
+ const { item: _item, ...rest } = d;
1234
+ return { ...rest, endpoint: "" };
1235
+ }
1236
+ function defaultBlockResponse(req, res, decision) {
1237
+ const a = defaultAnswer(decision.reason, wantsPage((n) => header(req.headers, n)));
1238
+ res.statusCode = decision.status;
1239
+ res.setHeader("retry-after", String(decision.retryAfter));
1240
+ res.setHeader("cache-control", "no-store");
1241
+ res.setHeader("content-type", a.contentType);
1242
+ res.end(a.body);
1243
+ }
1244
+ var errorText = (e) => e instanceof Error ? e.message : String(e);
1245
+ function keyShape(key) {
1246
+ const quoted = /^["'].*["']$/.test(key) ? " (it has quotes around it: remove them)" : "";
1247
+ return `"${key.slice(0, 4)}\u2026", ${key.length} characters${quoted}`;
1248
+ }
1249
+ function reguard(options = {}) {
1250
+ const o = checkOptions(options);
1251
+ const debugging = o.debug ?? /^(?:1|true|yes)$/i.test(envValue("REGUARD_DEBUG") ?? "");
1252
+ const log = makeLog(o.logger, debugging);
1253
+ const key = (o.key ?? envValue("REGUARD_KEY"))?.trim();
1254
+ const parsed = parseSiteKey(key);
1255
+ if (!parsed?.site) {
1256
+ const level = envValue("NODE_ENV") === "production" ? "error" : "warn";
1257
+ log.once(
1258
+ "no-key",
1259
+ level,
1260
+ !key ? "REGUARD_KEY is not set: passing every request through (no script, no verdicts, no blocking)." : parsed ? "this key has no site id (a key from before v0.4): use the rgk.\u2026 key from your dashboard. Passing every request through." : `REGUARD_KEY isn't a Reguard key (expected rgk.<site>.v<n>.<secret>; got ${keyShape(key)}). Passing every request through.`
1261
+ );
1262
+ const passthrough = ((req, _res, next) => {
1263
+ req.reguard = null;
1264
+ req.reguardDecision = null;
1265
+ req.reDetect = null;
1266
+ next();
1267
+ });
1268
+ Object.defineProperty(passthrough, "site", { value: void 0 });
1269
+ passthrough.scriptTag = () => "";
1270
+ passthrough.status = () => ({ enabled: false, collector: "off", since: Date.now(), failOpen: false, queued: 0, blocking: "off" });
1271
+ passthrough.flush = async () => {
1272
+ };
1273
+ passthrough.close = async () => {
1274
+ };
1275
+ return passthrough;
1276
+ }
1277
+ const site = parsed.site;
1278
+ const secrets = [parsed.secret];
1279
+ const previous = o.previousKey ?? envValue("REGUARD_KEY_PREVIOUS");
1280
+ if (previous?.trim()) {
1281
+ const prev = parseSiteKey(previous.trim());
1282
+ if (!prev?.site || prev.site !== site) {
1283
+ if (o.previousKey !== void 0) throw new ReguardConfigError("previousKey", "invalid_value", `must be an earlier rgk.${site}.\u2026 key for the same site`);
1284
+ log.once("bad-previous", "warn", `REGUARD_KEY_PREVIOUS isn't an earlier key for site ${site}: ignored.`);
1285
+ } else if (prev.secret !== parsed.secret) secrets.push(prev.secret);
1286
+ }
1287
+ const siteTag = siteTagOf(site, parsed.secret);
1288
+ const collector = collectorBase(o.collector ?? envValue("REGUARD_COLLECTOR"));
1289
+ const doFetch = o.fetch ?? fetch;
1290
+ const onError = o.onError ?? (() => {
1291
+ });
1292
+ const health = new Health(log);
1293
+ const platform = detectPlatform(typeof process !== "undefined" ? process.env : void 0);
1294
+ const blockCfg = o.block;
1295
+ const allDry = !blockCfg || BLOCK_REASONS.every((r) => blockCfg.dryRun.has(r));
1296
+ const skipped = skipMatcher(o.collect.skip);
1297
+ const ignored = o.ignore.length ? skipMatcher(o.ignore) : void 0;
1298
+ const required = blockCfg?.require ? skipMatcher(blockCfg.require) : void 0;
1299
+ const allowList = blockCfg?.allow.length ? skipMatcher(blockCfg.allow) : void 0;
1300
+ const denyMaps = (o.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
1301
+ const tagSettings = { site, collect: o.collect, fresh: freshSeconds(blockCfg), cookieDomain: o.cookieDomain };
1302
+ const resolve = (req) => {
1303
+ const known = ADDRESS.get(req);
1304
+ if (known) return known;
1305
+ const peer = req.socket?.remoteAddress ?? "";
1306
+ const get = (n) => header(req.headers, n);
1307
+ let a;
1308
+ if (typeof o.clientIp === "function") {
1309
+ let custom;
1310
+ try {
1311
+ custom = o.clientIp(req);
1312
+ } catch (e) {
1313
+ log.once("clientIp-threw", "warn", `clientIp threw (${errorText(e)}): using the connecting address`);
1314
+ }
1315
+ const ip = normalizeIp(custom ?? void 0);
1316
+ a = ip ? { address: ip, internal: !isPublicIp(ip), via: "custom" } : resolveClientAddress({ peer, header: get }, "socket");
1317
+ } else {
1318
+ const framework = req.app?.get?.("trust proxy") ? req.ip : void 0;
1319
+ a = resolveClientAddress({ peer, header: get, framework }, o.clientIp, platform);
1320
+ }
1321
+ ADDRESS.set(req, a);
1322
+ return a;
1323
+ };
1324
+ const crowd = /* @__PURE__ */ new Map();
1325
+ let crowdWarned = false;
1326
+ const watchCrowd = (req, a) => {
1327
+ if (crowdWarned || a.internal || !a.address) return;
1328
+ const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
1329
+ if (!sid) return;
1330
+ const now = Date.now();
1331
+ let c = crowd.get(a.address);
1332
+ if (!c || now - c.since > 10 * 6e4) {
1333
+ if (crowd.size > 1e4) crowd.clear();
1334
+ c = { sids: /* @__PURE__ */ new Set(), since: now };
1335
+ crowd.set(a.address, c);
1336
+ }
1337
+ c.sids.add(sid);
1338
+ if (c.sids.size >= 200) {
1339
+ crowdWarned = true;
1340
+ log.warn(
1341
+ `200 different browser sessions came from one address (${a.address}, read from ${a.via}) within 10 minutes. Reguard is probably reading a proxy's address instead of your visitors': set clientIp (reguard.site/docs/production/#visitor-addresses).`
1342
+ );
1343
+ }
1344
+ };
1345
+ const core = createReDetect(
1346
+ {
1347
+ site,
1348
+ siteKey: key,
1349
+ // the whole rgk key: summaries authenticate with it, verdicts verify with its secret
1350
+ collector: `${collector}${PREFIX}`,
1351
+ watchSessionless: o.watchSessionless,
1352
+ collect: o.collect,
1353
+ fetch: doFetch,
1354
+ onError,
1355
+ flushIntervalMs: o.flushIntervalMs
1356
+ },
1357
+ {
1358
+ health,
1359
+ log,
1360
+ timeoutMs: o.timeoutMs,
1361
+ address: resolve,
1362
+ ignored: (req, p) => (ignored ? matchesEither(ignored, p) : false) || safeIf(o.ignoreIf, req, "ignoreIf", log),
1363
+ decided: (req) => DECIDED.get(req)
1364
+ }
1365
+ );
1366
+ let reads = 0;
1367
+ let badSignatures = 0;
1368
+ let readsSince = Date.now();
1369
+ const readVerdict = async (cookie) => {
1370
+ for (const s of secrets) {
1371
+ const v = await readVerdictFrom(s, site, cookie).catch(() => null);
1372
+ if (v) return v;
1373
+ }
1374
+ if (cookie?.includes("_sv=")) {
1375
+ const now = Date.now();
1376
+ if (now - readsSince > 10 * 6e4) {
1377
+ reads = 0;
1378
+ badSignatures = 0;
1379
+ readsSince = now;
1380
+ }
1381
+ reads++;
1382
+ if (looksCurrent(site, cookie, now) && ++badSignatures >= 20 && badSignatures * 2 > reads)
1383
+ log.once(
1384
+ "bad-signatures",
1385
+ "error",
1386
+ "most visitors' verdicts carry a signature this key doesn't match: REGUARD_KEY is wrong for this site or was rotated. Set the current key; during a rotation, set the old one as previousKey (REGUARD_KEY_PREVIOUS)."
1387
+ );
1388
+ }
1389
+ return null;
1390
+ };
1391
+ const pace = blockCfg?.pace ?? null;
1392
+ const rate = (r) => new Allowance(r.burst, r.perSecond / 1e3, 5e4);
1393
+ const paceDocs = pace ? rate(pace.documents) : void 0;
1394
+ const paceApi = pace ? rate(pace.api) : void 0;
1395
+ const paceMisses = pace ? rate(pace.notFound) : void 0;
1396
+ const cooling = /* @__PURE__ */ new Map();
1397
+ const addressKey = (req) => `v:${visitorHash(parsed.secret, resolve(req).address)}`;
1398
+ const paceOf = (req, res, p) => {
1399
+ if (!pace || resolve(req).internal) return void 0;
1400
+ const get = (n) => header(req.headers, n);
1401
+ const now = Date.now();
1402
+ const browser = get("sec-fetch-dest") !== void 0;
1403
+ const tool = browser ? void 0 : toolOf(get("user-agent"));
1404
+ if (!browser && !(tool && BENIGN_TOOL_FAMILIES.has(tool.family))) {
1405
+ const key2 = addressKey(req);
1406
+ res.once("finish", () => {
1407
+ const st = res.statusCode;
1408
+ if ((st === 404 || st === 405 || st === 410) && !paceMisses.take(key2)) {
1409
+ cooling.set(key2, Date.now() + 1e3 / pace.notFound.perSecond);
1410
+ if (cooling.size > 5e4) {
1411
+ for (const [k, until] of cooling) if (until < Date.now()) cooling.delete(k);
1412
+ }
1413
+ }
1414
+ });
1415
+ if ((cooling.get(key2) ?? 0) > now) return "notfound";
1416
+ if ((req.method === "GET" || req.method === "HEAD") && requestKind(p.decoded) === "document" && !isSpeculativeHeaders(get)) {
1417
+ if (!paceDocs.has(key2, now)) return "document";
1418
+ onHeaders(res, (status, contentType) => {
1419
+ if (/^\s*text\/html/i.test(contentType) && !(status >= 300 && status < 400) && status !== 204) paceDocs.take(key2);
1420
+ });
1421
+ }
1422
+ }
1423
+ if (required && matchesEither(required, p)) {
1424
+ const sid = cookieValue(get("cookie"), SESSION_COOKIE);
1425
+ if (!paceApi.take(sid ? `s:${sid}` : addressKey(req), now)) return "api";
1426
+ }
1427
+ return void 0;
1428
+ };
1429
+ const grace = /* @__PURE__ */ new Map();
1430
+ const visitorOf = (req) => o.collect.addresses !== "off" ? visitorHash(parsed.secret, resolve(req).address) : void 0;
1431
+ const refresh = /* @__PURE__ */ new Map();
1432
+ const dryCounts = /* @__PURE__ */ new Map();
1433
+ const dryTimer = setInterval(() => {
1434
+ if (!dryCounts.size) return;
1435
+ const parts = [...dryCounts].map(([r, n]) => `${r} ${n}`).join(", ");
1436
+ log.info(`dry run: would have answered ${[...dryCounts.values()].reduce((a, b) => a + b, 0)} requests in the last minute (${parts})`);
1437
+ dryCounts.clear();
1438
+ }, 6e4);
1439
+ dryTimer.unref?.();
1440
+ const decide = (req, reason, p, verdict, paceKind) => ({
1441
+ reason,
1442
+ dryRun: blockCfg.dryRun.has(reason),
1443
+ status: reason === "flagged" || reason === "flagged_server" ? blockCfg.status : 429,
1444
+ retryAfter: RETRY_AFTER[reason],
1445
+ ...paceKind ? { pace: paceKind } : {},
1446
+ claims: reason === "flagged" || reason === "flagged_server" ? verdict?.claims ?? [] : [],
1447
+ verdict,
1448
+ path: p.decoded,
1449
+ clientIp: resolve(req).address
1450
+ });
1451
+ const act = (req, res, d) => {
1452
+ DECIDED.set(req, d);
1453
+ if (d.reason === "pace" && d.pace) PACED.set(req, d.pace);
1454
+ try {
1455
+ blockCfg.onBlock?.(d, req);
1456
+ } catch (e) {
1457
+ log.once("onBlock-threw", "warn", `block.onBlock threw: ${errorText(e)}`);
1458
+ }
1459
+ log.debug(`${d.dryRun ? "would block" : "blocked"} ${req.method} ${d.path}: ${d.reason}${d.pace ? ` (${d.pace})` : ""} from ${d.clientIp}`);
1460
+ if (d.dryRun) {
1461
+ req.reguardDecision = d;
1462
+ dryCounts.set(d.reason, (dryCounts.get(d.reason) ?? 0) + 1);
1463
+ return false;
1464
+ }
1465
+ void answer(req, res, d);
1466
+ return true;
1467
+ };
1468
+ const answer = async (req, res, d) => {
1469
+ const respond = blockCfg.respond;
1470
+ if (respond) {
1471
+ try {
1472
+ await respond(req, res, d);
1473
+ } catch (e) {
1474
+ log.once("respond-threw", "error", `block.respond threw (${errorText(e)}): sent the default answer instead`);
1475
+ }
1476
+ if (res.writableEnded) return;
1477
+ if (res.headersSent) {
1478
+ res.end();
1479
+ return;
1480
+ }
1481
+ log.once("respond-silent", "warn", "block.respond didn't answer the request: sent the default answer");
1482
+ }
1483
+ defaultBlockResponse(req, res, d);
1484
+ };
1485
+ let proxyFailing = false;
1486
+ async function proxy(req, res, p, target) {
1487
+ try {
1488
+ const q = target.indexOf("?");
1489
+ const url = `${p.decoded}${q === -1 ? "" : target.slice(q)}`;
1490
+ const headers = headersForReguard(req, parsed.secret, siteTag, o.collect);
1491
+ const init = { method: req.method, headers, redirect: "manual", signal: AbortSignal.timeout(o.timeoutMs) };
1492
+ if (req.method !== "GET" && req.method !== "HEAD") {
1493
+ const consumed = req.readableEnded || req._body === true;
1494
+ if (!consumed) {
1495
+ init.body = import_node_stream.Readable.toWeb(req);
1496
+ init.duplex = "half";
1497
+ } else if (req.body !== void 0) {
1498
+ const b = req.body;
1499
+ init.body = Buffer.isBuffer(b) ? new Uint8Array(b) : typeof b === "string" ? b : JSON.stringify(b);
1500
+ }
1501
+ }
1502
+ const r = await doFetch(`${collector}${url}`, init);
1503
+ if (proxyFailing) {
1504
+ proxyFailing = false;
1505
+ log.info("passing /_s/* to Reguard again");
1506
+ }
1507
+ res.statusCode = r.status;
1508
+ r.headers.forEach((v, k) => {
1509
+ if (!STRIP_FROM_RESPONSE.has(k)) res.setHeader(k, v);
1510
+ });
1511
+ const cookies = r.headers.getSetCookie?.() ?? [];
1512
+ if (cookies.length) res.setHeader("set-cookie", cookies);
1513
+ if (r.body && req.method !== "HEAD") await (0, import_promises.pipeline)(import_node_stream.Readable.fromWeb(r.body), res);
1514
+ else res.end();
1515
+ } catch (e) {
1516
+ if (e?.code !== "ERR_STREAM_PREMATURE_CLOSE") {
1517
+ onError(e);
1518
+ if (!proxyFailing) {
1519
+ proxyFailing = true;
1520
+ log.warn(`couldn't pass /_s/* to Reguard (${errorText(e)}): pages load without Reguard's script until it answers`);
1521
+ }
1522
+ }
1523
+ if (!res.headersSent) {
1524
+ res.statusCode = 502;
1525
+ res.end();
1526
+ } else res.destroy();
1527
+ }
1528
+ }
1529
+ const exempt = (req, p) => (allowList ? matchesBoth(allowList, p) : false) || safeIf(blockCfg?.allowIf, req, "block.allowIf", log);
1530
+ const middleware = ((req, res, next) => {
1531
+ const target = req.originalUrl ?? req.url ?? "/";
1532
+ const p = canonicalPath(target);
1533
+ req.reguard = null;
1534
+ req.reguardDecision = null;
1535
+ req.reDetect = null;
1536
+ const address = resolve(req);
1537
+ if (isReguardPath(p.decoded)) {
1538
+ void proxy(req, res, p, target);
1539
+ return;
1540
+ }
1541
+ watchCrowd(req, address);
1542
+ core.track(req, res);
1543
+ if (denyMaps) {
1544
+ if (isSourceMapPath(p)) {
1545
+ res.statusCode = 404;
1546
+ res.setHeader("cache-control", "no-store");
1547
+ res.end();
1548
+ return;
1549
+ }
1550
+ stripSourceMapHeaders(res);
1551
+ }
1552
+ const allowed = blockCfg ? exempt(req, p) : true;
1553
+ if (blockCfg && !allowed) {
1554
+ const paced = paceOf(req, res, p);
1555
+ if (paced && act(req, res, decide(req, "pace", p, null, paced))) return;
1556
+ }
1557
+ const injection = o.inject && !matchesEither(skipped, p) ? injectTag(req, res, tagSettings) : void 0;
1558
+ const cookie = header(req.headers, "cookie");
1559
+ readVerdict(cookie).then(
1560
+ (browser) => {
1561
+ const pushed = core.pushedFor(req, !!browser);
1562
+ const v = mergeVerdicts(browser, pushed);
1563
+ req.reguard = v;
1564
+ req.reDetect = v;
1565
+ if (blockCfg && !allowed) {
1566
+ const opt = { labels: blockCfg.labels, minStage: blockCfg.minStage };
1567
+ let reason = browser?.flagged(opt) ? "flagged" : pushed?.flagged(opt) ? "flagged_server" : void 0;
1568
+ const fresh = !!browser && verdictAgeMs(browser) <= blockCfg.maxAgeMs;
1569
+ if (required && fresh) {
1570
+ const g = grace.get(visitorOf(req) ?? "");
1571
+ if (g) g.pages = 0;
1572
+ }
1573
+ const get = (n) => header(req.headers, n);
1574
+ if (!reason && required && matchesEither(required, p) && !fresh && !isPreflight(req.method, get)) {
1575
+ if (health.failOpen) log.debug(`require not enforced for ${p.decoded}: Reguard is ${health.state}`);
1576
+ else {
1577
+ const now = Date.now();
1578
+ let r = browser ? refresh.get(`${browser.sid}:${browser.exp}`) : void 0;
1579
+ if (browser && !r) {
1580
+ r = { until: now + blockCfg.refreshMs, left: blockCfg.refreshRequests };
1581
+ refresh.set(`${browser.sid}:${browser.exp}`, r);
1582
+ if (refresh.size > 5e4) {
1583
+ for (const [k, x] of refresh) if (x.until < now) refresh.delete(k);
1584
+ }
1585
+ }
1586
+ if (r && now <= r.until && r.left > 0) r.left--;
1587
+ else {
1588
+ const k = visitorOf(req);
1589
+ const g = k ? grace.get(k) : void 0;
1590
+ if (g && now - g.at <= blockCfg.graceMs && g.left > 0) g.left--;
1591
+ else reason = "require";
1592
+ }
1593
+ }
1594
+ }
1595
+ if (reason) {
1596
+ const d = decide(req, reason, p, v);
1597
+ if (!d.dryRun || !req.reguardDecision) {
1598
+ if (!d.dryRun) injection?.cancel();
1599
+ if (act(req, res, d)) return;
1600
+ }
1601
+ }
1602
+ if (required && !matchesEither(required, p) && req.method !== "HEAD" && wantsPage(get)) {
1603
+ const k = visitorOf(req);
1604
+ if (k)
1605
+ onHeaders(res, (status, contentType) => {
1606
+ if (!/^\s*text\/html/i.test(contentType) || status >= 300 && status < 400 || status === 204) return;
1607
+ const g = grace.get(k) ?? { at: 0, left: 0, pages: 0 };
1608
+ g.pages = fresh ? 0 : g.pages + 1;
1609
+ g.at = Date.now();
1610
+ g.left = g.pages <= blockCfg.gracePages ? blockCfg.graceRequests : 0;
1611
+ grace.set(k, g);
1612
+ if (grace.size > 5e4) {
1613
+ for (const [key2, x] of grace) if (Date.now() - x.at > 10 * 6e4) grace.delete(key2);
1614
+ }
1615
+ });
1616
+ }
1617
+ }
1618
+ next();
1619
+ },
1620
+ () => {
1621
+ next();
1622
+ }
1623
+ );
1624
+ });
1625
+ const blocking = !blockCfg ? "off" : allDry ? "dry run" : blockCfg.dryRun.size ? "partial dry run" : "on";
1626
+ Object.defineProperty(middleware, "site", { value: site });
1627
+ middleware.scriptTag = (opts) => renderScriptTag(tagSettings, opts?.nonce);
1628
+ middleware.status = () => ({
1629
+ enabled: true,
1630
+ site,
1631
+ keyFingerprint: keyFingerprint(parsed.secret),
1632
+ collector: o.collect.requests ? health.state : "off",
1633
+ since: health.since,
1634
+ ...health.lastError ? { lastError: health.lastError } : {},
1635
+ failOpen: health.failOpen,
1636
+ queued: core.queued(),
1637
+ blocking
1638
+ });
1639
+ middleware.flush = core.flush;
1640
+ middleware.close = async () => {
1641
+ clearInterval(dryTimer);
1642
+ await core.close();
1643
+ };
1644
+ log.debug(
1645
+ `on for site ${site} (key v${parsed.version ?? "?"}, fingerprint ${keyFingerprint(parsed.secret)}${secrets.length > 1 ? ", plus the previous key" : ""}); collector ${collector}; blocking ${blocking}${blockCfg?.dryRun.size && !allDry ? ` (dry run: ${[...blockCfg.dryRun].join(", ")})` : ""}; client address ${typeof o.clientIp === "function" ? "custom" : JSON.stringify(o.clientIp)}${platform ? ` (host: ${platform})` : ""}; source maps ${denyMaps ? "denied" : "allowed"}`
1646
+ );
1647
+ return middleware;
1648
+ }
1649
+ function safeIf(fn, req, name, log) {
1650
+ if (!fn) return false;
1651
+ try {
1652
+ return fn(req) === true;
1653
+ } catch (e) {
1654
+ log.once(`${name}-threw`, "warn", `${name} threw (${errorText(e)}): treated as false`);
1655
+ return false;
1656
+ }
1657
+ }
1658
+ function onHeaders(res, cb) {
1659
+ const writeHead = res.writeHead;
1660
+ let done = false;
1661
+ res.writeHead = function(...a) {
1662
+ const out = writeHead.apply(this, a);
1663
+ if (!done) {
1664
+ done = true;
1665
+ let contentType = String(res.getHeader("content-type") ?? "");
1666
+ if (!contentType) {
1667
+ const h = a.find((x, i) => i > 0 && x !== null && typeof x === "object");
1668
+ if (Array.isArray(h)) {
1669
+ for (let i = 0; i + 1 < h.length; i += 2) if (String(h[i]).toLowerCase() === "content-type") contentType = String(h[i + 1]);
1670
+ } else if (h) {
1671
+ for (const [k, v] of Object.entries(h)) if (k.toLowerCase() === "content-type") contentType = String(v);
1672
+ }
1673
+ }
1674
+ try {
1675
+ cb(res.statusCode, contentType);
1676
+ } catch {
1677
+ }
1678
+ }
1679
+ return out;
1680
+ };
1681
+ }
1682
+ function injectTag(req, res, settings) {
1683
+ let mode = "undecided";
1684
+ let held = [];
1685
+ let tag = Buffer.alloc(0);
1686
+ const origWrite = res.write.bind(res);
1687
+ const origEnd = res.end.bind(res);
1688
+ const origWriteHead = res.writeHead.bind(res);
1689
+ const decide = () => {
1690
+ if (mode !== "undecided") return;
1691
+ const ct = String(res.getHeader("content-type") ?? "");
1692
+ const html = /^\s*text\/html/i.test(ct) && !/charset\s*=\s*"?utf-16/i.test(ct) && !res.getHeader("content-encoding") && !res.getHeader("content-range") && req.method !== "HEAD" && ![204, 206, 304].includes(res.statusCode);
1693
+ mode = html ? "scan" : "pass";
1694
+ if (html) {
1695
+ res.removeHeader("content-length");
1696
+ const csp = res.getHeader("content-security-policy");
1697
+ tag = Buffer.from(renderScriptTag(settings, cspNonce(Array.isArray(csp) ? csp.join(", ") : csp === void 0 ? void 0 : String(csp))));
1698
+ }
1699
+ };
1700
+ const toBuffer = (chunk, encoding) => typeof chunk === "string" ? Buffer.from(chunk, typeof encoding === "string" ? encoding : "utf8") : chunk instanceof Uint8Array ? Buffer.from(chunk) : null;
1701
+ const release = (final) => {
1702
+ const buf = held.length === 1 ? held[0] : Buffer.concat(held);
1703
+ const text = buf.toString("latin1");
1704
+ const lower = text.toLowerCase();
1705
+ const headClose = lower.search(/<\/head[\t\n\f\r >]/);
1706
+ if (headClose === -1 && !final && buf.length < SCAN_LIMIT) return null;
1707
+ mode = "pass";
1708
+ held = [];
1709
+ const head = headClose === -1 ? lower : lower.slice(0, headClose);
1710
+ if (head.includes("/_s/sdk") || head.includes("re-detect.js")) return buf;
1711
+ const open = /<head(?:\s[^>]*)?>/i.exec(text);
1712
+ const at = open && (headClose === -1 || open.index < headClose) ? open.index + open[0].length : headClose;
1713
+ return at === -1 ? buf : Buffer.concat([buf.subarray(0, at), tag, buf.subarray(at)]);
1714
+ };
1715
+ const r = res;
1716
+ r.writeHead = (statusCode, ...rest) => {
1717
+ const reason = typeof rest[0] === "string" ? rest[0] : void 0;
1718
+ const hdrs = reason !== void 0 ? rest[1] : rest[0];
1719
+ if (Array.isArray(hdrs)) {
1720
+ const grouped = /* @__PURE__ */ new Map();
1721
+ for (let i = 0; i + 1 < hdrs.length; i += 2) {
1722
+ const name = String(hdrs[i]);
1723
+ const g = grouped.get(name.toLowerCase()) ?? { name, values: [] };
1724
+ g.values.push(String(hdrs[i + 1]));
1725
+ grouped.set(name.toLowerCase(), g);
1726
+ }
1727
+ for (const g of grouped.values()) res.setHeader(g.name, g.values.length === 1 ? g.values[0] : g.values);
1728
+ } else if (hdrs && typeof hdrs === "object") {
1729
+ for (const [k, v] of Object.entries(hdrs)) if (v !== void 0) res.setHeader(k, v);
1730
+ }
1731
+ if (typeof statusCode === "number") res.statusCode = statusCode;
1732
+ decide();
1733
+ return reason !== void 0 ? origWriteHead(res.statusCode, reason) : origWriteHead(res.statusCode);
1734
+ };
1735
+ r.write = (chunk, encoding, cb) => {
1736
+ decide();
1737
+ if (mode !== "scan") return origWrite(chunk, encoding, cb);
1738
+ const callback = typeof encoding === "function" ? encoding : cb;
1739
+ const b = toBuffer(chunk, encoding);
1740
+ if (b) held.push(b);
1741
+ const out = release(false);
1742
+ if (out === null) {
1743
+ if (typeof callback === "function") process.nextTick(callback);
1744
+ return true;
1745
+ }
1746
+ return typeof callback === "function" ? origWrite(out, callback) : origWrite(out);
1747
+ };
1748
+ r.end = (chunk, encoding, cb) => {
1749
+ decide();
1750
+ if (mode !== "scan") return origEnd(chunk, encoding, cb);
1751
+ const callback = [chunk, encoding, cb].find((x) => typeof x === "function");
1752
+ if (typeof chunk !== "function" && chunk != null) {
1753
+ const b = toBuffer(chunk, encoding);
1754
+ if (b) held.push(b);
1755
+ }
1756
+ const out = release(true) ?? Buffer.alloc(0);
1757
+ return callback ? origEnd(out, callback) : origEnd(out);
1758
+ };
1759
+ return {
1760
+ cancel() {
1761
+ if (mode === "undecided") mode = "pass";
1762
+ }
1763
+ };
1764
+ }
1765
+ function secureRequest(req) {
1766
+ const proto = header(req.headers, "x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
1767
+ if (proto === "https" || req.socket?.encrypted) return true;
1768
+ const host = (header(req.headers, "host") ?? "").toLowerCase().replace(/:\d+$/, "");
1769
+ if (host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host.endsWith(".localhost")) return true;
1770
+ if (proto === "http") return false;
1771
+ return void 0;
1772
+ }
1773
+ function header(h, name) {
1774
+ const v = h[name];
1775
+ return Array.isArray(v) ? v.join(", ") : v;
1776
+ }
1777
+ var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "host", "content-length"]);
1778
+ function toArrayBuffer(b) {
1779
+ const ab = new ArrayBuffer(b.byteLength);
1780
+ new Uint8Array(ab).set(b);
1781
+ return ab;
1782
+ }
1783
+ function createReDetect(opts, wiring = {}) {
1784
+ const prefix = (opts.prefix ?? "/_s").replace(/\/$/, "");
1785
+ const collector = opts.collector.replace(/\/$/, "");
1786
+ const secret = parseSiteKey(opts.siteKey)?.secret ?? opts.siteKey;
1787
+ const doFetch = opts.fetch ?? fetch;
1788
+ const onError = opts.onError ?? (() => {
1789
+ });
1790
+ const log = wiring.log ?? makeLog(void 0, false);
1791
+ const health = wiring.health ?? new Health(log);
1792
+ const timeoutMs = wiring.timeoutMs ?? 1e4;
1793
+ const addressFor = (req) => wiring.address?.(req) ?? addressOf(req);
1794
+ const collect = resolveCollect(opts.collect, (m) => log.once(`collect:${m}`, "warn", m));
1795
+ const skipped = skipMatcher(collect.skip);
1796
+ const forward = collect.requests;
1797
+ const siteTag = siteTagOf(opts.site, secret);
1798
+ const maxQueue = opts.maxQueue ?? 5e3;
1799
+ const hash = (s) => (0, import_node_crypto.createHmac)("sha256", secret).update(s).digest("base64url").slice(0, 16);
1800
+ const queue = [];
1801
+ let inflight;
1802
+ const pushed = /* @__PURE__ */ new Map();
1803
+ const PUSHED_TTL_MS = 10 * 6e4;
1804
+ const isClaims = (c) => Array.isArray(c) && c.every((x) => !!x && typeof x.rule === "string" && typeof x.label === "string" && typeof x.stage === "string");
1805
+ const absorb = (body) => {
1806
+ const f = body?.flagged;
1807
+ if (!f) return;
1808
+ 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 });
1811
+ if (pushed.size > 5e4) {
1812
+ for (const [k, e] of pushed) if (e.until < now) pushed.delete(k);
1813
+ }
1814
+ };
1815
+ const pushedFor = (req, verified = false) => {
1816
+ if (!pushed.size) return null;
1817
+ const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
1818
+ const a = addressFor(req);
1819
+ const address = collect.addresses !== "off" && !verified && !a.internal ? a.address : "";
1820
+ const now = Date.now();
1821
+ const claims = [];
1822
+ for (const k of [sid ? `s:${sid}` : "", address ? `v:${visitorHash(secret, address)}` : ""]) {
1823
+ const e = k ? pushed.get(k) : void 0;
1824
+ if (e && e.until > now) claims.push(...e.claims);
1825
+ }
1826
+ return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now) : null;
1827
+ };
1828
+ const flush = async () => {
1829
+ while (queue.length) {
1830
+ if (!health.canSend()) {
1831
+ queue.length = 0;
1832
+ return;
1833
+ }
1834
+ const events = queue.splice(0, 500);
1835
+ try {
1836
+ const res = await doFetch(`${collector}/v1/server`, {
1837
+ method: "POST",
1838
+ headers: { "content-type": "application/json", authorization: `Bearer ${opts.siteKey}` },
1839
+ body: JSON.stringify({ site: opts.site, collect: collectReport(collect), events }),
1840
+ signal: AbortSignal.timeout(timeoutMs)
1841
+ });
1842
+ if (res.status === 429) {
1843
+ health.paused();
1844
+ onError(new Error("collector answered 429 to /v1/server (monthly usage limit): summaries paused for an hour"));
1845
+ queue.length = 0;
1846
+ return;
1847
+ }
1848
+ if (res.status === 401 || res.status === 403) {
1849
+ health.rejected(res.status);
1850
+ onError(new Error(`collector answered ${res.status} to /v1/server: the site key was rejected`));
1851
+ queue.length = 0;
1852
+ return;
1853
+ }
1854
+ if (res.status >= 500) {
1855
+ health.failing(`HTTP ${res.status}`);
1856
+ onError(new Error(`collector answered ${res.status} to /v1/server`));
1857
+ continue;
1858
+ }
1859
+ if (!res.ok) {
1860
+ log.once(`server-${res.status}`, "error", `Reguard refused a batch of summaries (HTTP ${res.status}): please report this with your reguard version`);
1861
+ onError(new Error(`collector answered ${res.status} to /v1/server`));
1862
+ continue;
1863
+ }
1864
+ health.ok();
1865
+ absorb(await res.json().catch(() => null));
1866
+ } catch (e) {
1867
+ health.failing(e?.name === "TimeoutError" ? `no answer within ${timeoutMs} ms` : errorText(e));
1868
+ onError(e);
1869
+ }
1870
+ }
1871
+ };
1872
+ const flushSoon = () => {
1873
+ if (queue.length && !inflight) inflight = flush().finally(() => inflight = void 0);
1874
+ };
1875
+ const timer = setInterval(flushSoon, opts.flushIntervalMs ?? 2e3);
1876
+ timer.unref?.();
1877
+ const readVerdict = (cookieHeader) => readVerdictFrom(secret, opts.site, cookieHeader);
1878
+ function record(req, res, started, bytes) {
1879
+ try {
1880
+ const h = req.headers;
1881
+ const sid = cookieValue(header(h, "cookie"), SESSION_COOKIE);
1882
+ const url = req.originalUrl ?? req.url ?? "/";
1883
+ const secure = secureRequest(req);
1884
+ const decision = wiring.decided?.(req);
1885
+ const pace = PACED.get(req);
1886
+ if (!sid && !opts.includeSessionless && !decision) {
1887
+ if (opts.watchSessionless === false || collect.addresses === "off") return;
1888
+ const watch = watchworthy({
1889
+ userAgent: header(h, "user-agent") ?? "",
1890
+ acceptLanguage: header(h, "accept-language"),
1891
+ accept: header(h, "accept"),
1892
+ secFetchMode: header(h, "sec-fetch-mode"),
1893
+ secChUa: header(h, "sec-ch-ua"),
1894
+ secure,
1895
+ path: url.split("?")[0] ?? url,
1896
+ status: res.statusCode
1897
+ });
1898
+ if (!watch) return;
1899
+ }
1900
+ const a = addressFor(req);
1901
+ const visitor = !sid && a.address && collect.addresses !== "off" ? visitorHash(secret, a.address) : void 0;
1902
+ const contentType = String(res.getHeader("content-type") ?? "");
1903
+ const requestBytes = Number(header(h, "content-length") ?? 0) || 0;
1904
+ const speculative = isSpeculativeHeaders((n) => header(h, n));
1905
+ let exchange;
1906
+ if (!speculative && isApiLike(url, contentType, requestBytes)) {
1907
+ const body = req.body;
1908
+ const bodyText = typeof body === "string" ? body : body && typeof body === "object" ? JSON.stringify(body) : "";
1909
+ const requestContentType = typeof body === "object" && body ? "application/json" : header(h, "content-type") ?? "";
1910
+ exchange = describeExchange(hash, {
1911
+ method: req.method ?? "GET",
1912
+ url,
1913
+ requestContentType,
1914
+ requestBody: bodyText.slice(0, 65536),
1915
+ requestBytes,
1916
+ status: res.statusCode,
1917
+ responseContentType: contentType,
1918
+ responseBytes: bytes()
1919
+ });
1920
+ }
1921
+ const order = [];
1922
+ for (let i = 0; i < req.rawHeaders.length; i += 2) order.push(String(req.rawHeaders[i]).toLowerCase());
1923
+ const picked = {};
1924
+ for (const n of ["rsc", "next-router-prefetch", "sec-purpose", "purpose"]) {
1925
+ const v = header(h, n);
1926
+ if (v !== void 0) picked[n] = v;
1927
+ }
1928
+ if (queue.length >= maxQueue) return;
1929
+ const pages = collect.pages;
1930
+ queue.push({
1931
+ sid,
1932
+ at: started,
1933
+ method: req.method ?? "GET",
1934
+ url: pages === "masked" ? privateUrl(url) : "",
1935
+ ...pages !== "off" ? { item: hash(`path:${url.split("?")[0] ?? url}`) } : {},
1936
+ ...pages !== "masked" ? { traits: pathTraits(url, header(h, "rsc") === "1") } : {},
1937
+ status: res.statusCode,
1938
+ headers: picked,
1939
+ client: {
1940
+ ua: header(h, "user-agent") ?? "",
1941
+ accept: header(h, "accept") ?? "",
1942
+ acceptLanguage: header(h, "accept-language") ?? "",
1943
+ secFetchMode: header(h, "sec-fetch-mode"),
1944
+ secFetchSite: header(h, "sec-fetch-site"),
1945
+ secFetchDest: header(h, "sec-fetch-dest"),
1946
+ secChUa: header(h, "sec-ch-ua"),
1947
+ hasCookie: Boolean(header(h, "cookie")),
1948
+ hasReferer: Boolean(header(h, "referer")),
1949
+ httpVersion: req.httpVersion,
1950
+ order,
1951
+ ...secure !== void 0 ? { secure } : {}
1952
+ },
1953
+ ...visitor ? { visitor } : {},
1954
+ ...exchange ? { exchange: withoutEndpoint(exchange, pages, hash) } : {},
1955
+ ...pace ? { pace } : {},
1956
+ ...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
1957
+ ...a.internal ? { internal: true } : {}
1958
+ });
1959
+ if (decision) flushSoon();
1960
+ } catch (e) {
1961
+ onError(e);
1962
+ }
1963
+ }
1964
+ function track(req, res) {
1965
+ const started = Date.now();
1966
+ const p = canonicalPath(req.originalUrl ?? req.url ?? "/");
1967
+ if (!forward || isReguardPath(p.decoded) || p.raw.startsWith(`${prefix}/`) || matchesEither(skipped, p) || matchesEither((x) => !!opts.ignore?.(x), p) || wiring.ignored?.(req, p)) return;
1968
+ let n = 0;
1969
+ const write = res.write.bind(res);
1970
+ const end = res.end.bind(res);
1971
+ const count = (chunk) => {
1972
+ if (typeof chunk === "string") n += Buffer.byteLength(chunk);
1973
+ else if (chunk instanceof Uint8Array) n += chunk.byteLength;
1974
+ };
1975
+ res.write = (...a) => {
1976
+ count(a[0]);
1977
+ return write(...a);
1978
+ };
1979
+ res.end = (...a) => {
1980
+ if (typeof a[0] !== "function") count(a[0]);
1981
+ return end(...a);
1982
+ };
1983
+ res.once("finish", () => record(req, res, started, () => n));
1984
+ }
1985
+ function middleware() {
1986
+ return (req, res, next) => {
1987
+ track(req, res);
1988
+ readVerdict(header(req.headers, "cookie")).then(
1989
+ (v) => {
1990
+ req.reDetect = v;
1991
+ req.reguard = v;
1992
+ next();
1993
+ },
1994
+ () => {
1995
+ req.reDetect = null;
1996
+ req.reguard = null;
1997
+ next();
1998
+ }
1999
+ );
2000
+ };
2001
+ }
2002
+ function route() {
2003
+ return async (req, res) => {
2004
+ try {
2005
+ const full = req.originalUrl ?? req.url ?? "/";
2006
+ const rest = full.startsWith(prefix) ? full.slice(prefix.length) : req.url ?? "/";
2007
+ const headers = headersForReguard(req, secret, siteTag, collect);
2008
+ for (const k of HOP_BY_HOP) headers.delete(k);
2009
+ let body;
2010
+ if (req.method !== "GET" && req.method !== "HEAD") {
2011
+ const chunks = [];
2012
+ let size = 0;
2013
+ for await (const c of req) {
2014
+ size += c.length;
2015
+ if (size > 1048576) throw new Error("request body over 1 MiB");
2016
+ chunks.push(c);
2017
+ }
2018
+ body = Buffer.concat(chunks);
2019
+ }
2020
+ const r = await doFetch(`${collector}${rest}`, { method: req.method, headers, body: body ? toArrayBuffer(body) : void 0, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
2021
+ res.statusCode = r.status;
2022
+ r.headers.forEach((v, k) => {
2023
+ if (!["content-encoding", "content-length", "transfer-encoding", "connection", "set-cookie"].includes(k)) res.setHeader(k, v);
2024
+ });
2025
+ const cookies = r.headers.getSetCookie?.() ?? [];
2026
+ if (cookies.length) res.setHeader("set-cookie", cookies);
2027
+ res.end(Buffer.from(await r.arrayBuffer()));
2028
+ } catch (e) {
2029
+ onError(e);
2030
+ if (!res.headersSent) res.statusCode = 502;
2031
+ res.end();
2032
+ }
2033
+ };
2034
+ }
2035
+ return {
2036
+ middleware,
2037
+ route,
2038
+ track,
2039
+ readVerdict,
2040
+ /** Claims the collector pushed back for this request's session or visitor (null: none). */
2041
+ pushedFor,
2042
+ /** For fetch-style handlers (Next.js route handlers, edge functions): pass `request.headers`. */
2043
+ readVerdictFromHeaders: (headers) => readVerdict(headers.get("cookie")),
2044
+ /** Summaries waiting to be sent. */
2045
+ queued: () => queue.length,
2046
+ /** Send queued summaries now (e.g. before shutdown). */
2047
+ flush: async () => {
2048
+ await inflight;
2049
+ await flush();
2050
+ },
2051
+ close: async () => {
2052
+ clearInterval(timer);
2053
+ await inflight;
2054
+ await flush();
2055
+ }
2056
+ };
2057
+ }
2058
+
2059
+ // src/fastify.ts
2060
+ var FASTIFY_IP = /* @__PURE__ */ new WeakMap();
2061
+ function plugin(fastify, options, done) {
2062
+ let mw;
2063
+ try {
2064
+ const trusted = !!fastify.initialConfig?.trustProxy;
2065
+ mw = reguard(
2066
+ trusted && options.clientIp === void 0 ? {
2067
+ ...options,
2068
+ clientIp: (req) => FASTIFY_IP.get(req) ?? null
2069
+ } : options
2070
+ );
2071
+ } catch (e) {
2072
+ done(e);
2073
+ return;
2074
+ }
2075
+ for (const name of ["reguard", "reguardDecision"]) if (!fastify.hasRequestDecorator?.(name)) fastify.decorateRequest?.(name, null);
2076
+ fastify.addHook("onRequest", (request, reply, next) => {
2077
+ const raw = request.raw;
2078
+ if (request.ip) FASTIFY_IP.set(raw, request.ip);
2079
+ let passed = false;
2080
+ const res = reply.raw;
2081
+ const writeHead = res.writeHead;
2082
+ res.writeHead = function(...args) {
2083
+ if (!passed) {
2084
+ passed = true;
2085
+ reply.hijack();
2086
+ }
2087
+ return writeHead.apply(this, args);
2088
+ };
2089
+ mw(raw, res, () => {
2090
+ passed = true;
2091
+ request.reguard = raw.reguard ?? null;
2092
+ request.reguardDecision = raw.reguardDecision ?? null;
2093
+ next();
2094
+ });
2095
+ });
2096
+ fastify.addHook("onClose", (_instance, closed) => {
2097
+ void mw.close().finally(closed);
2098
+ });
2099
+ done();
2100
+ }
2101
+ plugin[Symbol.for("skip-override")] = true;
2102
+ plugin[Symbol.for("fastify.display-name")] = "reguard";
2103
+ var reguardFastify = plugin;
2104
+ var fastify_default = plugin;
2105
+ // Annotate the CommonJS export names for ESM import in node:
2106
+ 0 && (module.exports = {
2107
+ ReguardConfigError,
2108
+ reguardFastify
2109
+ });