reguard 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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-YDDBWUPV.js +438 -0
  6. package/dist/cjs/fastify.cjs +2109 -0
  7. package/dist/cjs/fetch.cjs +1453 -0
  8. package/dist/cjs/index.cjs +2074 -0
  9. package/dist/cjs/next.cjs +1518 -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 +41 -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,1453 @@
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/fetch.ts
21
+ var fetch_exports = {};
22
+ __export(fetch_exports, {
23
+ ReguardConfigError: () => ReguardConfigError,
24
+ defaultBlockAnswer: () => defaultBlockAnswer,
25
+ reguardFetch: () => reguardFetch
26
+ });
27
+ module.exports = __toCommonJS(fetch_exports);
28
+
29
+ // ../shared/src/exchange.ts
30
+ var IGNORED_PARAMS = /* @__PURE__ */ new Set(["_rsc", "_", "cb", "ts", "t", "_t", "v", "nocache", "__nextDataReq", "__nextLocale"]);
31
+ var PAGE_KEYS = /* @__PURE__ */ new Set(["page", "p", "offset", "skip", "start", "cursor", "after", "from"]);
32
+ var STRONG = [
33
+ /['"`]\s*(?:or|and|union|select|order\s+by|--|#|;|\))/i,
34
+ // breaking out of a quoted string
35
+ /\bunion\s+(?:all\s+)?select\b|\bsleep\s*\(|\bbenchmark\s*\(|\bwaitfor\s+delay\b|\bxp_cmdshell\b/i,
36
+ /\.\.[/\\]/,
37
+ // traversal
38
+ /\$\{[^}]*\}|\{\{[^}]*\}\}|<%[\s\S]*%>/,
39
+ // template injection
40
+ /<\s*\/?\s*(?:script|iframe|svg|img)\b|javascript:|\bon(?:error|load)\s*=/i,
41
+ // markup injection
42
+ /%[0-9a-f]{2}/i,
43
+ // still percent-encoded after decoding: double encoding
44
+ /\u0000/
45
+ // null byte
46
+ ];
47
+ function normalizeEndpoint(path) {
48
+ return path.split("/").map(
49
+ (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
50
+ ).join("/");
51
+ }
52
+ function privateUrl(url) {
53
+ const [path = "/", query] = url.split("?");
54
+ const names = query ? [...new Set(new URLSearchParams(query).keys())] : [];
55
+ return normalizeEndpoint(path) + (names.length ? `?${names.map((n) => `${n}=`).join("&")}` : "");
56
+ }
57
+ function shapeOf(v) {
58
+ if (v === "") return "empty";
59
+ if (/^-?\d+$/.test(v)) return "int";
60
+ if (/^-?\d*\.\d+$/.test(v)) return "decimal";
61
+ if (/^(?:true|false)$/i.test(v)) return "bool";
62
+ 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";
63
+ if (/^[0-9a-f]{16,}$/i.test(v)) return "hex";
64
+ if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return "email";
65
+ if (/^[a-z0-9]+(?:[-_.][a-z0-9]+)+$/i.test(v)) return "slug";
66
+ if (/^[\p{L}\p{N}]+$/u.test(v)) return "word";
67
+ return "text";
68
+ }
69
+ function strongMarker(v) {
70
+ return STRONG.some((re) => re.test(v));
71
+ }
72
+ function boundaryOf(v) {
73
+ if (!/^-?\d+$/.test(v)) return void 0;
74
+ if (/^-?0+$/.test(v)) return "zero";
75
+ if (v.startsWith("-")) return "neg";
76
+ if (v.length >= 10) return "overflow";
77
+ return void 0;
78
+ }
79
+ function describeExchange(hash, x) {
80
+ const [path = "/", query = ""] = x.url.split("?");
81
+ const params = {};
82
+ let pageValue = null;
83
+ const add = (name, value, shape = shapeOf(value), scanned = true) => {
84
+ const p = { h: hash(`${name}=${value}`), shape };
85
+ if (scanned) {
86
+ if (strongMarker(value)) p.strong = true;
87
+ const b = boundaryOf(value);
88
+ if (b) p.boundary = b;
89
+ }
90
+ params[name] = p;
91
+ const bare = name.replace(/^body\./, "").toLowerCase();
92
+ if (PAGE_KEYS.has(bare) && /^\d+$/.test(value)) pageValue = Number(value);
93
+ };
94
+ for (const [k, v] of new URLSearchParams(query)) if (!IGNORED_PARAMS.has(k)) add(k, v);
95
+ const body = x.requestBody ?? "";
96
+ const ct = (x.requestContentType ?? "").toLowerCase();
97
+ if (body) {
98
+ try {
99
+ if (ct.includes("json")) {
100
+ const parsed = JSON.parse(body);
101
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
102
+ for (const [k, v] of Object.entries(parsed)) {
103
+ const name = `body.${k}`;
104
+ if (typeof v === "string") add(name, v);
105
+ else if (typeof v === "number") add(name, String(v));
106
+ else if (typeof v === "boolean") add(name, String(v), "bool", false);
107
+ else if (v === null) add(name, "null", "empty", false);
108
+ else add(name, JSON.stringify(v).slice(0, 256), "json", false);
109
+ }
110
+ }
111
+ } else if (ct.includes("x-www-form-urlencoded")) {
112
+ for (const [k, v] of new URLSearchParams(body)) add(`body.${k}`, v);
113
+ }
114
+ } catch {
115
+ }
116
+ }
117
+ let listLength = null;
118
+ const head = x.responseHead ?? "";
119
+ if ((x.responseContentType ?? "").includes("json") && head) {
120
+ try {
121
+ const parsed = JSON.parse(head);
122
+ if (Array.isArray(parsed)) listLength = parsed.length;
123
+ else if (parsed && typeof parsed === "object") {
124
+ const firstArray = Object.values(parsed).find(Array.isArray);
125
+ if (firstArray) listLength = firstArray.length;
126
+ }
127
+ } catch {
128
+ }
129
+ }
130
+ return {
131
+ method: x.method,
132
+ endpoint: normalizeEndpoint(path),
133
+ item: hash(`path:${path}`),
134
+ params,
135
+ requestBytes: x.requestBytes,
136
+ status: x.status,
137
+ responseBytes: x.responseBytes,
138
+ listLength,
139
+ pageValue
140
+ };
141
+ }
142
+ function isApiLike(url, responseContentType, requestBytes) {
143
+ const ct = responseContentType.toLowerCase();
144
+ return url.startsWith("/api/") || url.includes("_rsc=") || ct.includes("json") || ct.includes("x-component") || requestBytes > 0;
145
+ }
146
+ function isSpeculativeHeaders(get) {
147
+ return get("next-router-prefetch") !== void 0 || /prefetch|prerender/i.test(get("sec-purpose") ?? get("purpose") ?? "");
148
+ }
149
+
150
+ // ../shared/src/verdict.ts
151
+ var VERDICT_COOKIE = "_sv";
152
+ var SESSION_COOKIE = "_s";
153
+ var enc = new TextEncoder();
154
+ var keys = /* @__PURE__ */ new Map();
155
+ function unb64url(s) {
156
+ const pad = s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4);
157
+ const bin = atob(pad);
158
+ const out = new Uint8Array(new ArrayBuffer(bin.length));
159
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
160
+ return out;
161
+ }
162
+ function hmacKey(siteKey) {
163
+ let k = keys.get(siteKey);
164
+ if (!k) {
165
+ k = crypto.subtle.importKey("raw", enc.encode(siteKey), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
166
+ keys.set(siteKey, k);
167
+ }
168
+ return k;
169
+ }
170
+ async function verifyVerdict(siteKey, token, expect = {}) {
171
+ try {
172
+ if (!token) return null;
173
+ const [v, body, sig] = token.split(".");
174
+ if (v !== "v1" || !body || !sig) return null;
175
+ const ok = await crypto.subtle.verify("HMAC", await hmacKey(siteKey), unb64url(sig), enc.encode(`v1.${body}`));
176
+ if (!ok) return null;
177
+ const p = JSON.parse(new TextDecoder().decode(unb64url(body)));
178
+ if (p.v !== 1 || p.exp < (expect.now ?? Date.now())) return null;
179
+ if (expect.site !== void 0 && p.site !== expect.site) return null;
180
+ if (expect.sid !== void 0 && p.sid !== expect.sid) return null;
181
+ return p;
182
+ } catch {
183
+ return null;
184
+ }
185
+ }
186
+ function cookieValue(header, name) {
187
+ if (!header) return void 0;
188
+ for (const part of header.split(";")) {
189
+ const i = part.indexOf("=");
190
+ if (i > 0 && part.slice(0, i).trim() === name) return part.slice(i + 1).trim();
191
+ }
192
+ return void 0;
193
+ }
194
+
195
+ // ../shared/src/keys.ts
196
+ var SITE_KEY_PREFIX = "rgk";
197
+ function parseSiteKey(key) {
198
+ const k = (key ?? "").trim();
199
+ if (!k) return null;
200
+ if (!k.startsWith(`${SITE_KEY_PREFIX}.`)) return /^[\w-]+$/.test(k) ? { secret: k } : null;
201
+ const parts = k.split(".");
202
+ if (parts.length < 4) return null;
203
+ const secret = parts[parts.length - 1];
204
+ const version = /^v(\d+)$/.exec(parts[parts.length - 2]);
205
+ const site = parts.slice(1, -2).join(".");
206
+ if (!version || !site || !/^[\w-]+$/.test(secret)) return null;
207
+ return { site, version: Number(version[1]), secret };
208
+ }
209
+
210
+ // ../shared/src/tools.ts
211
+ var BENIGN_TOOL_FAMILIES = /* @__PURE__ */ new Set(["search_bot", "monitor"]);
212
+ var TOOLS = [
213
+ // Scanners and fuzzers (captured: ffuf sends "Fuzz Faster U Fool v2.x").
214
+ [/fuzz faster u fool/i, "scanner", "ffuf"],
215
+ [/^feroxbuster\//i, "scanner", "feroxbuster"],
216
+ [/^gobuster\//i, "scanner", "gobuster"],
217
+ [/\bnikto\b/i, "scanner", "nikto"],
218
+ [/^sqlmap\//i, "scanner", "sqlmap"],
219
+ [/wpscan/i, "scanner", "wpscan"],
220
+ [/nuclei/i, "scanner", "nuclei"],
221
+ [/dirbuster|\bdirb\b|wfuzz|\bdirsearch\b/i, "scanner", "dirbuster"],
222
+ [/xnlinkfinder/i, "scanner", "xnlinkfinder"],
223
+ [/zgrab|masscan|nmap scripting engine|nessus|qualys|acunetix|netsparker|burp ?suite|owasp ?zap|zaproxy|arachni|w3af|whatweb|wappalyzer/i, "scanner", "scanner"],
224
+ // Site copiers.
225
+ [/httrack/i, "cloner", "httrack"],
226
+ [/^wget\//i, "cloner", "wget"],
227
+ [/website ?(?:copier|downloader|ripper)|sitesucker|webcopy|teleport ?pro|offline ?explorer|webzip|pagenest/i, "cloner", "site-copier"],
228
+ // Crawlers and spiders.
229
+ [/katana/i, "crawler", "katana"],
230
+ [/gospider/i, "crawler", "gospider"],
231
+ [/hakrawler/i, "crawler", "hakrawler"],
232
+ [/colly/i, "crawler", "colly"],
233
+ [/^scrapy\//i, "crawler", "scrapy"],
234
+ [/crawl4ai/i, "crawler", "crawl4ai"],
235
+ // Declared AI crawlers and agents.
236
+ [/firecrawl/i, "ai_crawler", "firecrawl"],
237
+ [
238
+ /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,
239
+ "ai_crawler",
240
+ "ai-crawler"
241
+ ],
242
+ // Search engines, link previews, monitors.
243
+ [
244
+ /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,
245
+ "search_bot",
246
+ "search-or-preview-bot"
247
+ ],
248
+ [/uptimerobot|pingdom|statuscake|datadog|newrelic|site24x7|better ?uptime|betterstack|checkly|freshping|hetrixtools|uptime-kuma/i, "monitor", "uptime-monitor"],
249
+ // Site audits a site's owner runs on their own site (SEO crawlers, link checkers, archives).
250
+ [/screaming frog|sitebulb|deepcrawl|lumar|ahrefs(?:site)?audit|semrush|w3c_validator|w3c-checklink|ia_archiver|archive\.org_bot/i, "monitor", "site-audit"],
251
+ // Error trackers fetch a site's scripts and source maps to symbolicate stack traces.
252
+ [/\bsentry\/|rollbar|bugsnag|raygun|trackjs|honeybadger/i, "monitor", "error-tracker"],
253
+ [/headlesschrome/i, "headless_browser", "headless-chrome"],
254
+ // Generic HTTP libraries and CLIs (captured: sourcemapper sends "Go-http-client/1.1").
255
+ [
256
+ /^(?: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,
257
+ "http_library",
258
+ "http-library"
259
+ ]
260
+ ];
261
+ function toolOf(userAgent) {
262
+ const ua = (userAgent ?? "").trim();
263
+ if (!ua) return { family: "http_library", tool: "no-user-agent" };
264
+ for (const [re, family, tool] of TOOLS) if (re.test(ua)) return { family, tool };
265
+ return void 0;
266
+ }
267
+ function browserIncoherence(h) {
268
+ const ua = h.userAgent ?? "";
269
+ if (!/^Mozilla\/5\.0 \(/.test(ua) || toolOf(ua)) return [];
270
+ const reasons = [];
271
+ if (!h.acceptLanguage) reasons.push("no_accept_language");
272
+ if (/ {2,}/.test(ua) || / {2,}/.test(h.accept ?? "")) reasons.push("header_whitespace");
273
+ const chrome = /(?:Chrome|CriOS)\/(\d+)/.exec(ua);
274
+ const firefox = /(?:Firefox|FxiOS)\/(\d+)/.exec(ua);
275
+ const safari = /Version\/(\d+)[.\d]* (?:Mobile\/\w+ )?Safari\//.exec(ua);
276
+ const version = Number(chrome?.[1] ?? firefox?.[1] ?? safari?.[1] ?? 0);
277
+ const modern = chrome && version >= 90 || firefox && version >= 90 || safari && version >= 17;
278
+ if (h.secure !== false && modern && !h.secFetchMode) reasons.push("no_fetch_metadata");
279
+ if (h.secure !== false && h.secChUa && chrome && !/CriOS/.test(ua)) {
280
+ const hinted = /"Chromium";\s*v="(\d+)"/.exec(h.secChUa)?.[1];
281
+ if (hinted && Number(hinted) !== Number(chrome[1])) reasons.push("client_hints_version_mismatch");
282
+ if (/"HeadlessChrome"/.test(h.secChUa) && !/HeadlessChrome/.test(ua)) reasons.push("client_hints_headless_mismatch");
283
+ }
284
+ return reasons;
285
+ }
286
+ 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;
287
+ 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;
288
+ var BROWSER_AUTOMATIC = /^\/(?:favicon\.ico|apple-touch-icon[\w.-]*\.png|browserconfig\.xml|site\.webmanifest|manifest\.json|\.well-known\/appspecific\/)/i;
289
+ function watchworthy(w) {
290
+ const tool = toolOf(w.userAgent);
291
+ if (tool && tool.family !== "headless_browser") return !BENIGN_TOOL_FAMILIES.has(tool.family);
292
+ if (browserIncoherence(w).length) return true;
293
+ const t = w.traits ?? pathTraits(w.path);
294
+ if (t.family || t.discovery || t.map) return true;
295
+ if (t.auto) return false;
296
+ return w.status === 404 || w.status === 405 || w.status === 410;
297
+ }
298
+ function requestKind(url, rsc = false) {
299
+ const path = url.split("?")[0] ?? url;
300
+ if (rsc || url.includes("_rsc=")) return "rsc";
301
+ if (path.startsWith("/api/")) return "api";
302
+ if (/\.(?:html?|php|aspx?|jsp)$/i.test(path)) return "document";
303
+ if (/\.[a-z0-9]{1,6}$/i.test(path) || path.startsWith("/_next/")) return "static";
304
+ return "document";
305
+ }
306
+ function pathTraits(url, rsc = false) {
307
+ const path = url.split("?")[0] ?? url;
308
+ const t = { kind: requestKind(url, rsc) };
309
+ const fam = SENSITIVE_PATH.exec(path)?.[1]?.toLowerCase();
310
+ if (fam) t.family = fam.startsWith(".") ? fam : fam.replace(/\..*$/, "");
311
+ if (DISCOVERY_FILE.test(path)) t.discovery = path.toLowerCase();
312
+ if (BROWSER_AUTOMATIC.test(path)) t.auto = true;
313
+ if (/\.map$/i.test(path)) t.map = true;
314
+ if (/\.(?:m?js|cjs)$/i.test(path)) t.script = true;
315
+ if (/[0-9a-f]{32,}/i.test(path)) t.random = true;
316
+ return t;
317
+ }
318
+
319
+ // ../shared/src/collect.ts
320
+ var DEFAULT_COLLECT = Object.freeze({ pages: "masked", addresses: "hashed", behavior: true, requests: true, skip: [] });
321
+ var PAGES = ["masked", "hashed", "off"];
322
+ var ADDRESSES = ["hashed", "off"];
323
+ var SKIP_PATTERN = /^\/[\w\-.~%!$&'()*+;=:@/]{0,199}$/;
324
+ var MAX_SKIP = 50;
325
+ function flag(v) {
326
+ if (typeof v === "boolean") return v;
327
+ if (typeof v !== "string") return void 0;
328
+ const s = v.trim().toLowerCase();
329
+ return s === "on" || s === "true" || s === "1" || s === "yes" ? true : s === "off" || s === "false" || s === "0" || s === "no" ? false : void 0;
330
+ }
331
+ function resolveCollect(input, warn = () => {
332
+ }) {
333
+ const out = { ...DEFAULT_COLLECT, skip: [] };
334
+ if (input === void 0 || input === null) return out;
335
+ if (typeof input !== "object" || Array.isArray(input)) {
336
+ warn("collect should be an object; using the defaults");
337
+ return out;
338
+ }
339
+ const c = input;
340
+ const bad = (name, value, allowed) => warn(`collect.${name} = ${JSON.stringify(value)} isn't ${allowed}; using the default`);
341
+ if (c.pages !== void 0) {
342
+ if (PAGES.includes(c.pages)) out.pages = c.pages;
343
+ else bad("pages", c.pages, '"masked", "hashed" or "off"');
344
+ }
345
+ if (c.addresses !== void 0) {
346
+ if (ADDRESSES.includes(c.addresses)) out.addresses = c.addresses;
347
+ else bad("addresses", c.addresses, '"hashed" or "off"');
348
+ }
349
+ for (const name of ["behavior", "requests"]) {
350
+ if (c[name] === void 0) continue;
351
+ const v = flag(c[name]);
352
+ if (v === void 0) bad(name, c[name], "true or false");
353
+ else out[name] = v;
354
+ }
355
+ if (c.skip !== void 0) {
356
+ const list = typeof c.skip === "string" ? c.skip.split(",") : Array.isArray(c.skip) ? c.skip : void 0;
357
+ if (!list) bad("skip", c.skip, "a list of paths");
358
+ else {
359
+ for (const raw of list) {
360
+ const p = typeof raw === "string" ? raw.trim() : raw;
361
+ if (p === "") continue;
362
+ if (typeof p === "string" && SKIP_PATTERN.test(p) && out.skip.length < MAX_SKIP) out.skip.push(p);
363
+ else bad("skip", p, `a path that starts with "/" (at most ${MAX_SKIP} of them)`);
364
+ }
365
+ }
366
+ }
367
+ return out;
368
+ }
369
+ function skipMatcher(patterns) {
370
+ if (!patterns.length) return () => false;
371
+ const res = patterns.map((p) => {
372
+ const tail = p.endsWith("/*");
373
+ const body = (tail ? p.slice(0, -2) : p).split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
374
+ return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`);
375
+ });
376
+ return (path) => {
377
+ const p = path.split(/[?#]/)[0] ?? path;
378
+ return res.some((re) => re.test(p));
379
+ };
380
+ }
381
+ function collectAttributes(c) {
382
+ const a = {};
383
+ if (c.pages !== DEFAULT_COLLECT.pages) a["data-pages"] = c.pages;
384
+ if (c.addresses !== DEFAULT_COLLECT.addresses) a["data-addresses"] = c.addresses;
385
+ if (!c.behavior) a["data-behavior"] = "off";
386
+ if (c.skip.length) a["data-skip"] = c.skip.join(",");
387
+ return a;
388
+ }
389
+ function collectReport(c) {
390
+ return { pages: c.pages, addresses: c.addresses, behavior: c.behavior };
391
+ }
392
+
393
+ // ../shared/src/allowance.ts
394
+ var Allowance = class {
395
+ constructor(capacity, refillPerMs, maxKeys = 1e5) {
396
+ this.capacity = capacity;
397
+ this.refillPerMs = refillPerMs;
398
+ this.maxKeys = maxKeys;
399
+ }
400
+ buckets = /* @__PURE__ */ new Map();
401
+ take(key, now = Date.now()) {
402
+ const b = this.refill(key, now);
403
+ if (b.tokens < 1) return false;
404
+ b.tokens -= 1;
405
+ return true;
406
+ }
407
+ /** Whether `take` would succeed now, without using anything. */
408
+ has(key, now = Date.now()) {
409
+ return this.refill(key, now).tokens >= 1;
410
+ }
411
+ refill(key, now) {
412
+ const prev = this.buckets.get(key);
413
+ const b = prev ? { tokens: Math.min(this.capacity, prev.tokens + (now - prev.at) * this.refillPerMs), at: now } : { tokens: this.capacity, at: now };
414
+ this.buckets.delete(key);
415
+ this.buckets.set(key, b);
416
+ if (this.buckets.size > this.maxKeys) this.buckets.delete(this.buckets.keys().next().value);
417
+ return b;
418
+ }
419
+ };
420
+
421
+ // ../shared/src/address.ts
422
+ var PLATFORM_HEADERS = {
423
+ fly: "fly-client-ip",
424
+ vercel: "x-vercel-forwarded-for",
425
+ railway: "x-real-ip",
426
+ netlify: "x-nf-client-connection-ip",
427
+ appengine: "x-appengine-user-ip",
428
+ workers: "cf-connecting-ip"
429
+ };
430
+ function detectPlatform(env) {
431
+ if (!env) return null;
432
+ if (env.FLY_APP_NAME) return "fly";
433
+ if (env.VERCEL) return "vercel";
434
+ if (env.RAILWAY_ENVIRONMENT_ID || env.RAILWAY_PROJECT_ID || env.RAILWAY_ENVIRONMENT) return "railway";
435
+ if (env.NETLIFY) return "netlify";
436
+ if (env.GAE_APPLICATION) return "appengine";
437
+ return null;
438
+ }
439
+ var CLOUDFLARE_RANGES = [
440
+ "173.245.48.0/20",
441
+ "103.21.244.0/22",
442
+ "103.22.200.0/22",
443
+ "103.31.4.0/22",
444
+ "141.101.64.0/18",
445
+ "108.162.192.0/18",
446
+ "190.93.240.0/20",
447
+ "188.114.96.0/20",
448
+ "197.234.240.0/22",
449
+ "198.41.128.0/17",
450
+ "162.158.0.0/15",
451
+ "104.16.0.0/13",
452
+ "104.24.0.0/14",
453
+ "172.64.0.0/13",
454
+ "131.0.72.0/22",
455
+ "2400:cb00::/32",
456
+ "2606:4700::/32",
457
+ "2803:f800::/32",
458
+ "2405:b500::/32",
459
+ "2405:8100::/32",
460
+ "2a06:98c0::/29",
461
+ "2c0f:f248::/32"
462
+ ];
463
+ var NON_PUBLIC_RANGES = [
464
+ "0.0.0.0/8",
465
+ "10.0.0.0/8",
466
+ "100.64.0.0/10",
467
+ "127.0.0.0/8",
468
+ "169.254.0.0/16",
469
+ "172.16.0.0/12",
470
+ "192.168.0.0/16",
471
+ "::/128",
472
+ "::1/128",
473
+ "fc00::/7",
474
+ "fe80::/10"
475
+ ];
476
+ var MAX_FORWARDED = 32;
477
+ function parseIpv4(s) {
478
+ const parts = s.split(".");
479
+ if (parts.length !== 4) return null;
480
+ const out = [];
481
+ for (const p of parts) {
482
+ if (!/^\d{1,3}$/.test(p) || p.length > 1 && p.startsWith("0")) return null;
483
+ const n = Number(p);
484
+ if (n > 255) return null;
485
+ out.push(n);
486
+ }
487
+ return out;
488
+ }
489
+ function parseIp(text) {
490
+ const s = text.trim();
491
+ if (!s) return null;
492
+ const v4 = parseIpv4(s);
493
+ if (v4) return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, ...v4]);
494
+ if (!s.includes(":") || !/^[0-9a-fA-F:.]+$/.test(s)) return null;
495
+ const halves = s.split("::");
496
+ if (halves.length > 2) return null;
497
+ const groups = (part) => {
498
+ if (part === "") return [];
499
+ const out = [];
500
+ const items = part.split(":");
501
+ for (let i = 0; i < items.length; i++) {
502
+ const it = items[i];
503
+ if (i === items.length - 1 && it.includes(".")) {
504
+ const tail2 = parseIpv4(it);
505
+ if (!tail2) return null;
506
+ out.push(tail2[0] << 8 | tail2[1], tail2[2] << 8 | tail2[3]);
507
+ } else {
508
+ if (!/^[0-9a-fA-F]{1,4}$/.test(it)) return null;
509
+ out.push(parseInt(it, 16));
510
+ }
511
+ }
512
+ return out;
513
+ };
514
+ const head = groups(halves[0]);
515
+ const tail = halves.length === 2 ? groups(halves[1]) : [];
516
+ if (!head || !tail) return null;
517
+ const total = head.length + tail.length;
518
+ if (halves.length === 2 ? total > 7 : total !== 8) return null;
519
+ const all = [...head, ...Array(8 - total).fill(0), ...tail];
520
+ const bytes = new Uint8Array(16);
521
+ all.forEach((g, i) => {
522
+ bytes[i * 2] = g >> 8;
523
+ bytes[i * 2 + 1] = g & 255;
524
+ });
525
+ return bytes;
526
+ }
527
+ var isMapped = (b) => b.slice(0, 10).every((x) => x === 0) && b[10] === 255 && b[11] === 255;
528
+ function formatIp(b) {
529
+ if (isMapped(b)) return `${b[12]}.${b[13]}.${b[14]}.${b[15]}`;
530
+ const g = [];
531
+ for (let i = 0; i < 8; i++) g.push(b[i * 2] << 8 | b[i * 2 + 1]);
532
+ let best = -1;
533
+ let bestLen = 0;
534
+ for (let i = 0; i < 8; ) {
535
+ if (g[i] !== 0) {
536
+ i++;
537
+ continue;
538
+ }
539
+ let j = i;
540
+ while (j < 8 && g[j] === 0) j++;
541
+ if (j - i > bestLen && j - i >= 2) {
542
+ best = i;
543
+ bestLen = j - i;
544
+ }
545
+ i = j;
546
+ }
547
+ const hex = (xs) => xs.map((x) => x.toString(16)).join(":");
548
+ if (best === -1) return hex(g);
549
+ return `${hex(g.slice(0, best))}::${hex(g.slice(best + bestLen))}`;
550
+ }
551
+ function normalizeIp(token) {
552
+ if (!token) return null;
553
+ let s = token.trim().replace(/^"(.*)"$/, "$1");
554
+ if (s.startsWith("[")) {
555
+ const end = s.indexOf("]");
556
+ if (end < 0) return null;
557
+ s = s.slice(1, end);
558
+ } else {
559
+ const v4port = /^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(s);
560
+ if (v4port) s = v4port[1];
561
+ }
562
+ const zone = s.indexOf("%");
563
+ if (zone > 0) s = s.slice(0, zone);
564
+ let b = parseIp(s);
565
+ if (!b && s.includes(":")) {
566
+ const cut = /^(.*):\d{1,5}$/.exec(s);
567
+ if (cut) b = parseIp(cut[1]);
568
+ }
569
+ return b ? formatIp(b) : null;
570
+ }
571
+ function parseCidr(text) {
572
+ const [addr, len, extra] = text.trim().split("/");
573
+ if (extra !== void 0 || !addr) return null;
574
+ const bytes = parseIp(addr);
575
+ if (!bytes) return null;
576
+ const v4 = parseIpv4(addr.trim()) !== null;
577
+ const max = v4 ? 32 : 128;
578
+ if (len !== void 0 && !/^\d{1,3}$/.test(len)) return null;
579
+ const n = len === void 0 ? max : Number(len);
580
+ if (n > max) return null;
581
+ return { bytes, bits: v4 ? n + 96 : n };
582
+ }
583
+ function inCidr(c, b) {
584
+ let bits = c.bits;
585
+ for (let i = 0; i < 16 && bits > 0; i++, bits -= 8) {
586
+ const mask = bits >= 8 ? 255 : 255 << 8 - bits & 255;
587
+ if ((c.bytes[i] & mask) !== (b[i] & mask)) return false;
588
+ }
589
+ return true;
590
+ }
591
+ var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
592
+ var NON_PUBLIC = compile(NON_PUBLIC_RANGES);
593
+ var CLOUDFLARE = compile(CLOUDFLARE_RANGES);
594
+ function ipInRanges(address, ranges) {
595
+ const b = parseIp(address);
596
+ if (!b) return false;
597
+ const cidrs = typeof ranges[0] === "string" ? compile(ranges) : ranges;
598
+ return cidrs.some((c) => inCidr(c, b));
599
+ }
600
+ function isPublicIp(address) {
601
+ const b = parseIp(address);
602
+ return !!b && !NON_PUBLIC.some((c) => inCidr(c, b));
603
+ }
604
+ function chainOf(req) {
605
+ const xff = req.header("x-forwarded-for") ?? "";
606
+ const entries = xff.split(",").map((s) => s.trim()).filter(Boolean).slice(-MAX_FORWARDED);
607
+ return [...entries, req.peer];
608
+ }
609
+ var result = (address, via) => ({ address, internal: !isPublicIp(address), via });
610
+ function walk(req, trusted, via) {
611
+ const chain = chainOf(req);
612
+ let last = "";
613
+ for (let i = chain.length - 1; i >= 0; i--) {
614
+ const ip = normalizeIp(chain[i]);
615
+ if (!ip) continue;
616
+ last ||= ip;
617
+ const b = parseIp(ip);
618
+ if (NON_PUBLIC.some((c) => inCidr(c, b)) || trusted.some((c) => inCidr(c, b))) continue;
619
+ return { address: ip, internal: false, via: i === chain.length - 1 ? "socket" : via };
620
+ }
621
+ return { address: last, internal: true, via: "socket" };
622
+ }
623
+ function resolveClientAddress(req, mode = "auto", platform = null) {
624
+ const peer = normalizeIp(req.peer) ?? "";
625
+ if (mode === "socket") return result(peer, "socket");
626
+ if (typeof mode === "object" && "header" in mode) {
627
+ const first = req.header(mode.header.toLowerCase())?.split(",")[0];
628
+ const ip = normalizeIp(first);
629
+ return ip ? result(ip, "header") : result(peer, "socket");
630
+ }
631
+ if (typeof mode === "object" && "hops" in mode) {
632
+ const chain = chainOf(req).map((t) => normalizeIp(t)).filter((x) => !!x);
633
+ if (!chain.length) return result("", "socket");
634
+ const at = Math.max(0, chain.length - 1 - mode.hops);
635
+ return result(chain[at], at === chain.length - 1 ? "socket" : "hops");
636
+ }
637
+ if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies");
638
+ const framework = normalizeIp(req.framework);
639
+ if (framework) return result(framework, "framework");
640
+ if (platform) {
641
+ const ip = normalizeIp(req.header(PLATFORM_HEADERS[platform])?.split(",")[0]);
642
+ if (ip) return result(ip, `platform:${platform}`);
643
+ }
644
+ if (peer && ipInRanges(peer, CLOUDFLARE)) {
645
+ const ip = normalizeIp(req.header("cf-connecting-ip"));
646
+ if (ip) return result(ip, "cloudflare");
647
+ }
648
+ return walk(req, [], "forwarded");
649
+ }
650
+ function clientIpModeProblem(value) {
651
+ if (value === "auto" || value === "socket") return null;
652
+ if (!value || typeof value !== "object" || Array.isArray(value)) return 'must be "auto", "socket", { header }, { proxies } or { hops }';
653
+ const keys3 = Object.keys(value);
654
+ if (keys3.length !== 1) return "must set exactly one of header, proxies or hops";
655
+ const v = value;
656
+ if ("header" in v) return typeof v.header === "string" && /^[A-Za-z0-9-]+$/.test(v.header) ? null : "header must be a header name";
657
+ 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}`;
658
+ if ("proxies" in v) {
659
+ if (!Array.isArray(v.proxies) || !v.proxies.length) return "proxies must be a non-empty list of addresses or ranges";
660
+ const bad = v.proxies.find((p) => typeof p !== "string" || !parseCidr(p));
661
+ return bad === void 0 ? null : `proxies has an entry that is not an address or range: ${JSON.stringify(bad)}`;
662
+ }
663
+ return "must set exactly one of header, proxies or hops";
664
+ }
665
+
666
+ // ../shared/src/paths.ts
667
+ function decodeOnce(s) {
668
+ if (!s.includes("%")) return s;
669
+ try {
670
+ return decodeURIComponent(s);
671
+ } catch {
672
+ return s.replace(/%([0-7][0-9a-fA-F])/g, (_, h) => String.fromCharCode(parseInt(h, 16)));
673
+ }
674
+ }
675
+ function normalizeSegments(path) {
676
+ const collapsed = path.replace(/\/{2,}/g, "/");
677
+ const segs = collapsed.split("/");
678
+ const out = [];
679
+ for (let i = 1; i < segs.length; i++) {
680
+ const s = segs[i];
681
+ const last = i === segs.length - 1;
682
+ if (s === ".") {
683
+ if (last) out.push("");
684
+ } else if (s === "..") {
685
+ out.pop();
686
+ if (last) out.push("");
687
+ } else out.push(s);
688
+ }
689
+ return `/${out.join("/")}`;
690
+ }
691
+ function canonicalPath(target) {
692
+ let t = target || "/";
693
+ const abs = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]*/.exec(t);
694
+ if (abs) t = t.slice(abs[0].length) || "/";
695
+ const cut = t.search(/[?#]/);
696
+ let raw = cut === -1 ? t : t.slice(0, cut);
697
+ if (!raw.startsWith("/")) raw = `/${raw}`;
698
+ return { raw, decoded: normalizeSegments(decodeOnce(raw)) };
699
+ }
700
+ function matchesEither(matcher, p) {
701
+ return matcher(p.raw) || matcher(p.decoded);
702
+ }
703
+ function matchesBoth(matcher, p) {
704
+ return matcher(p.raw) && matcher(p.decoded);
705
+ }
706
+ function isSourceMapPath(p) {
707
+ return /\.map$/i.test(p.raw) || /\.map$/i.test(p.decoded);
708
+ }
709
+
710
+ // src/core.ts
711
+ var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
712
+ function withFlagged(p, source = "browser") {
713
+ return {
714
+ ...p,
715
+ source,
716
+ flagged({ labels, minStage = "candidate" } = {}) {
717
+ const want = typeof labels === "string" ? [labels] : labels?.length ? labels : void 0;
718
+ const rank = STAGE_RANK[minStage] ?? 0;
719
+ return p.claims.some((c) => (STAGE_RANK[c.stage] ?? -1) >= rank && (!want || want.includes(c.label)));
720
+ }
721
+ };
722
+ }
723
+ function mergeVerdicts(browser, pushed) {
724
+ if (!pushed) return browser;
725
+ if (!browser) return withFlagged(pushed, "server");
726
+ const rules = new Set(browser.claims.map((c) => `${c.rule}|${c.label}|${c.stage}`));
727
+ const claims = [...browser.claims, ...pushed.claims.filter((c) => !rules.has(`${c.rule}|${c.label}|${c.stage}`))];
728
+ const { source: _s, flagged: _f, ...payload } = browser;
729
+ return withFlagged({ ...payload, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
730
+ }
731
+ async function readVerdictFrom(secret, site, cookieHeader) {
732
+ const token = cookieValue(cookieHeader, VERDICT_COOKIE);
733
+ if (!token) return null;
734
+ const p = await verifyVerdict(secret, token, { site, sid: cookieValue(cookieHeader, SESSION_COOKIE) });
735
+ return p ? withFlagged(p) : null;
736
+ }
737
+ var DEFAULT_COLLECTOR = "https://api.reguard.site";
738
+ function collectorBase(collector) {
739
+ return (collector ?? DEFAULT_COLLECTOR).replace(/\/+$/, "").replace(/\/_s$/, "");
740
+ }
741
+ function envValue(name) {
742
+ return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
743
+ }
744
+ var VERDICT_TTL_MS = 10 * 6e4;
745
+ var DEFAULT_PACE = {
746
+ documents: { burst: 30, perSecond: 1 },
747
+ api: { burst: 60, perSecond: 5 },
748
+ notFound: { burst: 20, perSecond: 0.5 }
749
+ };
750
+ function pushedVerdict(sid, site, claims, now = Date.now()) {
751
+ return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4 }, "server");
752
+ }
753
+ var ANSWER_CODES = { flagged: "reguard.blocked", flagged_server: "reguard.blocked", require: "reguard.require", pace: "reguard.pace" };
754
+ var RETRY_AFTER = { flagged: 120, flagged_server: 120, require: 5, pace: 2 };
755
+ 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>`;
756
+ 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.");
757
+ 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.");
758
+ var PACE_TEXT = "Too many requests. Slow down and try again in a moment.";
759
+ var MESSAGES = {
760
+ flagged: "Too many automated requests from this browser. Try again in a few minutes.",
761
+ flagged_server: "Too many automated requests from this browser. Try again in a few minutes.",
762
+ require: "This request needs the page's security check. Reload the page and try again.",
763
+ pace: PACE_TEXT
764
+ };
765
+ function defaultAnswer(reason, wantsHtml) {
766
+ if (wantsHtml) {
767
+ if (reason === "pace") return { contentType: "text/plain; charset=utf-8", body: PACE_TEXT };
768
+ return { contentType: "text/html; charset=utf-8", body: reason === "require" ? REQUIRE_HTML : BLOCK_HTML };
769
+ }
770
+ return { contentType: "application/json", body: JSON.stringify({ error: MESSAGES[reason], code: ANSWER_CODES[reason] }) };
771
+ }
772
+ function wantsPage(get) {
773
+ return get("sec-fetch-dest") === "document" || /text\/html/i.test(get("accept") ?? "");
774
+ }
775
+ function isReguardPath(path) {
776
+ return path === "/_s" || path.startsWith("/_s/");
777
+ }
778
+ var escapeAttr = (v) => v.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
779
+ function renderScriptTag(t, nonce) {
780
+ const attrs = { ...collectAttributes(t.collect) };
781
+ if (t.fresh) attrs["data-fresh"] = String(t.fresh);
782
+ if (t.cookieDomain) attrs["data-cookie-domain"] = t.cookieDomain;
783
+ if (nonce && /^[A-Za-z0-9+/=_-]{1,200}$/.test(nonce)) attrs.nonce = nonce;
784
+ const rest = Object.entries(attrs).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("");
785
+ return `<script async src="${t.prefix ?? "/_s"}/sdk.js" data-site="${t.site.replace(/[^\w.-]/g, "")}"${rest}></script>`;
786
+ }
787
+
788
+ // src/config.ts
789
+ var ReguardConfigError = class extends TypeError {
790
+ option;
791
+ code;
792
+ constructor(option, code, detail) {
793
+ super(`[reguard] ${option} ${detail}`);
794
+ this.name = "ReguardConfigError";
795
+ this.option = option;
796
+ this.code = code;
797
+ }
798
+ };
799
+ var BLOCK_REASONS = ["flagged", "flagged_server", "require", "pace"];
800
+ var LABELS = ["rea", "automated_exploration", "unauthorized_extraction"];
801
+ var STAGES = ["candidate", "alert", "enforce"];
802
+ var fail = (option, code, detail) => {
803
+ throw new ReguardConfigError(option, code, detail);
804
+ };
805
+ var show = (v) => typeof v === "function" ? "a function" : JSON.stringify(v) ?? String(v);
806
+ var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
807
+ var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
808
+ function checkKeys(obj, allowed, prefix, moved = {}) {
809
+ for (const k of Object.keys(obj)) {
810
+ if (obj[k] === void 0 || allowed.includes(k)) continue;
811
+ const path = prefix ? `${prefix}.${k}` : k;
812
+ if (moved[k]) fail(path, "removed_option", `was removed: ${moved[k]}`);
813
+ const c = camel(k).replace(/Seconds$|Secs$/, "Ms");
814
+ const hint = allowed.find((a) => a === c || a === camel(k) || a.toLowerCase() === k.toLowerCase());
815
+ fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${prefix ? `${prefix}.` : ""}${hint}?)` : ""}`);
816
+ }
817
+ }
818
+ function checkBoolean(v, option) {
819
+ if (v === void 0) return void 0;
820
+ if (typeof v !== "boolean") fail(option, "invalid_type", `must be true or false (got ${show(v)})`);
821
+ return v;
822
+ }
823
+ function checkFunction(v, option) {
824
+ if (v === void 0) return void 0;
825
+ if (typeof v !== "function") fail(option, "invalid_type", `must be a function (got ${show(v)})`);
826
+ return v;
827
+ }
828
+ function checkString(v, option) {
829
+ if (v === void 0) return void 0;
830
+ if (typeof v !== "string") fail(option, "invalid_type", `must be a string (got ${show(v)})`);
831
+ return v;
832
+ }
833
+ function checkNumber(v, option, min, max, integer = true) {
834
+ if (v === void 0) return void 0;
835
+ if (typeof v !== "number" || !Number.isFinite(v)) fail(option, "invalid_type", `must be a number (got ${show(v)})`);
836
+ const n = v;
837
+ if (integer && !Number.isInteger(n)) fail(option, "invalid_value", `must be a whole number (got ${n})`);
838
+ if (n < min || n > max) fail(option, "out_of_range", `must be from ${min} to ${max} (got ${n})`);
839
+ return n;
840
+ }
841
+ function checkOneOf(v, option, allowed) {
842
+ if (v === void 0) return void 0;
843
+ if (typeof v !== "string") fail(option, "invalid_type", `must be one of ${allowed.map((a) => `"${a}"`).join(", ")} (got ${show(v)})`);
844
+ if (!allowed.includes(v)) fail(option, "invalid_value", `must be one of ${allowed.map((a) => `"${a}"`).join(", ")} (got ${show(v)})`);
845
+ return v;
846
+ }
847
+ var PATH_PATTERN = /^\/[\w\-.~%!$&'()*+;=:@/]{0,199}$/;
848
+ var MAX_PATHS = 50;
849
+ function checkPaths(v, option, commas = false) {
850
+ if (v === void 0) return void 0;
851
+ const list = commas && typeof v === "string" ? v.split(",").map((s) => s.trim()).filter(Boolean) : v;
852
+ if (!Array.isArray(list)) fail(option, "invalid_type", `must be a list of paths like "/api/*" (got ${show(v)})`);
853
+ const out = [];
854
+ for (const p of list) {
855
+ if (typeof p !== "string" || !PATH_PATTERN.test(p)) fail(option, "invalid_value", `has an entry that isn't a path starting with "/": ${show(p)}`);
856
+ out.push(p);
857
+ }
858
+ if (out.length > MAX_PATHS) fail(option, "out_of_range", `can hold at most ${MAX_PATHS} paths (got ${out.length})`);
859
+ return out;
860
+ }
861
+ function checkCollect(v, option = "collect") {
862
+ if (v === void 0 || v === null) return resolveCollect(void 0);
863
+ if (!isObject(v)) fail(option, "invalid_type", `must be an object (got ${show(v)})`);
864
+ const c = v;
865
+ checkKeys(c, ["pages", "addresses", "behavior", "requests", "skip"], option);
866
+ checkOneOf(c.pages, `${option}.pages`, ["masked", "hashed", "off"]);
867
+ checkOneOf(c.addresses, `${option}.addresses`, ["hashed", "off"]);
868
+ checkBoolean(c.behavior, `${option}.behavior`);
869
+ checkBoolean(c.requests, `${option}.requests`);
870
+ const skip = checkPaths(c.skip, `${option}.skip`, true);
871
+ return resolveCollect({ ...c, ...skip ? { skip } : {} });
872
+ }
873
+ function checkClientIp(v, option = "clientIp") {
874
+ if (v === void 0) return "auto";
875
+ if (typeof v === "function") return v;
876
+ const problem = clientIpModeProblem(v);
877
+ if (problem) fail(option, typeof v === "object" && v !== null ? "invalid_value" : "invalid_type", problem);
878
+ return v;
879
+ }
880
+ var DOMAIN = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
881
+ function checkCookieDomain(v, option = "cookieDomain") {
882
+ const s = checkString(v, option);
883
+ if (s === void 0) return void 0;
884
+ const d = s.trim().toLowerCase().replace(/^\./, "");
885
+ if (!DOMAIN.test(d)) fail(option, "invalid_value", `must be a domain like "example.com" (got ${show(s)})`);
886
+ return d;
887
+ }
888
+ function checkCollector(v, option = "collector") {
889
+ const s = checkString(v, option);
890
+ if (s === void 0) return void 0;
891
+ if (!/^https?:\/\/[^/?#\s]+(?:\/[^?#\s]*)?$/i.test(s)) fail(option, "invalid_value", `must be an http(s) URL (got ${show(s)})`);
892
+ return s;
893
+ }
894
+ function checkLogger(v, option = "logger") {
895
+ if (v === void 0 || v === false) return v;
896
+ if (!isObject(v) && typeof v !== "function") fail(option, "invalid_type", `must be an object with warn and error methods, or false (got ${show(v)})`);
897
+ const l = v;
898
+ if (typeof l.warn !== "function" || typeof l.error !== "function") fail(option, "invalid_value", "must have warn and error methods");
899
+ return v;
900
+ }
901
+ var BLOCK_KEYS = [
902
+ "labels",
903
+ "status",
904
+ "minStage",
905
+ "dryRun",
906
+ "allow",
907
+ "allowIf",
908
+ "respond",
909
+ "onBlock",
910
+ "require",
911
+ "requireMaxAgeMs",
912
+ "requireGraceMs",
913
+ "requireGraceRequests",
914
+ "requireGracePages",
915
+ "requireRefreshRequests",
916
+ "requireRefreshMs",
917
+ "pace"
918
+ ];
919
+ function checkRate(v, option, base) {
920
+ if (v === void 0) return base;
921
+ if (!isObject(v)) fail(option, "invalid_type", `must be { burst, perSecond } (got ${show(v)})`);
922
+ const r = v;
923
+ checkKeys(r, ["burst", "perSecond"], option);
924
+ const burst = checkNumber(r.burst, `${option}.burst`, 1, 1e5) ?? base.burst;
925
+ const perSecond = checkNumber(r.perSecond, `${option}.perSecond`, 1e-3, 1e4, false) ?? base.perSecond;
926
+ return { burst, perSecond };
927
+ }
928
+ function checkBlock(v, option = "block", runtime = "node") {
929
+ if (v === void 0 || v === false || v === null) return null;
930
+ if (v !== true && !isObject(v)) fail(option, "invalid_type", `must be true, false or an object (got ${show(v)})`);
931
+ const b = v === true ? {} : v;
932
+ checkKeys(b, BLOCK_KEYS, option);
933
+ if (runtime === "fetch") {
934
+ for (const k of ["require", "requireMaxAgeMs", "requireGraceMs", "requireGraceRequests", "requireGracePages", "requireRefreshRequests", "requireRefreshMs"])
935
+ 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");
936
+ }
937
+ let labels;
938
+ if (b.labels !== void 0) {
939
+ if (!Array.isArray(b.labels)) fail(`${option}.labels`, "invalid_type", `must be a list of labels (got ${show(b.labels)})`);
940
+ const list = b.labels;
941
+ if (!list.length) fail(`${option}.labels`, "empty_list", "is empty; leave it out to block on any label");
942
+ for (const l of list) checkOneOf(l, `${option}.labels`, LABELS);
943
+ labels = list;
944
+ }
945
+ let dryRun = /* @__PURE__ */ new Set();
946
+ if (b.dryRun === true) dryRun = new Set(BLOCK_REASONS);
947
+ else if (Array.isArray(b.dryRun)) {
948
+ if (!b.dryRun.length) fail(`${option}.dryRun`, "empty_list", "is empty; use false, true, or a list of reasons");
949
+ for (const r of b.dryRun) dryRun.add(checkOneOf(r, `${option}.dryRun`, BLOCK_REASONS));
950
+ } 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)})`);
951
+ const require2 = checkPaths(b.require, `${option}.require`);
952
+ let pace = { ...DEFAULT_PACE };
953
+ if (b.pace === false) pace = null;
954
+ else if (b.pace !== void 0 && b.pace !== true) {
955
+ if (!isObject(b.pace)) fail(`${option}.pace`, "invalid_type", `must be true, false or an object (got ${show(b.pace)})`);
956
+ const p = b.pace;
957
+ checkKeys(p, ["documents", "api", "notFound"], `${option}.pace`);
958
+ pace = {
959
+ documents: checkRate(p.documents, `${option}.pace.documents`, DEFAULT_PACE.documents),
960
+ api: checkRate(p.api, `${option}.pace.api`, DEFAULT_PACE.api),
961
+ notFound: checkRate(p.notFound, `${option}.pace.notFound`, DEFAULT_PACE.notFound)
962
+ };
963
+ }
964
+ return {
965
+ labels,
966
+ status: checkNumber(b.status, `${option}.status`, 400, 599) ?? 429,
967
+ minStage: checkOneOf(b.minStage, `${option}.minStage`, STAGES) ?? "candidate",
968
+ dryRun,
969
+ allow: checkPaths(b.allow, `${option}.allow`) ?? [],
970
+ require: require2?.length ? require2 : void 0,
971
+ maxAgeMs: checkNumber(b.requireMaxAgeMs, `${option}.requireMaxAgeMs`, 1e3, 6e5) ?? 6e4,
972
+ graceMs: checkNumber(b.requireGraceMs, `${option}.requireGraceMs`, 0, 6e5) ?? 15e3,
973
+ graceRequests: checkNumber(b.requireGraceRequests, `${option}.requireGraceRequests`, 0, 1e5) ?? 30,
974
+ gracePages: checkNumber(b.requireGracePages, `${option}.requireGracePages`, 0, 1e3) ?? 3,
975
+ refreshRequests: checkNumber(b.requireRefreshRequests, `${option}.requireRefreshRequests`, 0, 1e5) ?? 30,
976
+ refreshMs: checkNumber(b.requireRefreshMs, `${option}.requireRefreshMs`, 0, 6e5) ?? 1e4,
977
+ pace,
978
+ allowIf: checkFunction(b.allowIf, `${option}.allowIf`),
979
+ respond: checkFunction(b.respond, `${option}.respond`),
980
+ onBlock: checkFunction(b.onBlock, `${option}.onBlock`)
981
+ };
982
+ }
983
+
984
+ // src/health.ts
985
+ var seenBy = /* @__PURE__ */ new WeakMap();
986
+ function makeLog(logger, debugging) {
987
+ const out = logger === false ? null : logger ?? console;
988
+ let seen = out ? seenBy.get(out) : void 0;
989
+ if (out && !seen) {
990
+ seen = /* @__PURE__ */ new Set();
991
+ seenBy.set(out, seen);
992
+ }
993
+ const say = (level, message) => {
994
+ if (!out) return;
995
+ const fn = level === "debug" ? out.debug ?? out.info ?? out.warn : level === "info" ? out.info ?? out.warn : out[level];
996
+ try {
997
+ fn.call(out, `[reguard] ${message}`);
998
+ } catch {
999
+ }
1000
+ };
1001
+ return {
1002
+ warn: (m) => say("warn", m),
1003
+ error: (m) => say("error", m),
1004
+ info: (m) => say("info", m),
1005
+ debug: (m) => {
1006
+ if (debugging) say("debug", m);
1007
+ },
1008
+ once: (kind, level, m) => {
1009
+ if (!seen || seen.has(kind)) return;
1010
+ seen.add(kind);
1011
+ say(level, m);
1012
+ },
1013
+ debugging
1014
+ };
1015
+ }
1016
+ var PAUSE_MS = 60 * 6e4;
1017
+ var REJECTED_RETRY_MS = 5 * 6e4;
1018
+ var Health = class {
1019
+ constructor(log, now = Date.now) {
1020
+ this.log = log;
1021
+ this.now = now;
1022
+ this.since = now();
1023
+ }
1024
+ state = "ok";
1025
+ since;
1026
+ lastError;
1027
+ pausedUntil = 0;
1028
+ retryAt = 0;
1029
+ move(state, error) {
1030
+ if (state !== this.state) this.since = this.now();
1031
+ this.state = state;
1032
+ this.lastError = error;
1033
+ }
1034
+ ok() {
1035
+ if (this.state !== "ok") this.log.info("reaching Reguard again: summaries and require routes are back to normal");
1036
+ this.move("ok");
1037
+ }
1038
+ failing(error) {
1039
+ if (this.state === "ok") this.log.warn(`can't reach Reguard (${error}): summaries are dropped and require routes stay open until it answers`);
1040
+ this.move("failing", error);
1041
+ }
1042
+ rejected(status) {
1043
+ if (this.state !== "rejected")
1044
+ this.log.error(
1045
+ `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.`
1046
+ );
1047
+ this.retryAt = this.now() + REJECTED_RETRY_MS;
1048
+ this.move("rejected", `HTTP ${status}`);
1049
+ }
1050
+ paused() {
1051
+ 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.");
1052
+ this.pausedUntil = this.now() + PAUSE_MS;
1053
+ this.move("paused", "HTTP 429");
1054
+ }
1055
+ /** Whether a batch may be sent now (not while paused or waiting after a rejection). */
1056
+ canSend() {
1057
+ const now = this.now();
1058
+ return now >= this.pausedUntil && now >= this.retryAt;
1059
+ }
1060
+ /** `require` routes are not enforced while this is true. */
1061
+ get failOpen() {
1062
+ return this.state !== "ok";
1063
+ }
1064
+ };
1065
+
1066
+ // src/fetch.ts
1067
+ var OPTION_KEYS = [
1068
+ "key",
1069
+ "previousKey",
1070
+ "collector",
1071
+ "block",
1072
+ "sourceMaps",
1073
+ "ignore",
1074
+ "collect",
1075
+ "watchSessionless",
1076
+ "clientIp",
1077
+ "cookieDomain",
1078
+ "debug",
1079
+ "logger",
1080
+ "timeoutMs",
1081
+ "flushIntervalMs",
1082
+ "platform",
1083
+ "fetch",
1084
+ "onError"
1085
+ ];
1086
+ var enc2 = new TextEncoder();
1087
+ var keys2 = /* @__PURE__ */ new Map();
1088
+ async function hmac(secret, text, length) {
1089
+ let k = keys2.get(secret);
1090
+ if (!k) {
1091
+ k = crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
1092
+ keys2.set(secret, k);
1093
+ }
1094
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await k, enc2.encode(text)));
1095
+ let s = "";
1096
+ for (const b of sig) s += String.fromCharCode(b);
1097
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "").slice(0, length);
1098
+ }
1099
+ var NOT_FORWARDED = /^(?:connection|keep-alive|proxy-authenticate|proxy-authorization|te|trailer|transfer-encoding|upgrade|host|content-length|expect|accept-encoding|cookie|authorization|referer)$|^x-reguard-/;
1100
+ 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)/;
1101
+ var STRIP_FROM_RESPONSE = /* @__PURE__ */ new Set(["content-encoding", "content-length", "transfer-encoding", "connection", "keep-alive"]);
1102
+ function defaultBlockAnswer(request, decision) {
1103
+ const a = defaultAnswer(decision.reason, wantsPage((n) => request.headers.get(n)));
1104
+ return new Response(a.body, { status: decision.status, headers: { "content-type": a.contentType, "retry-after": String(decision.retryAfter), "cache-control": "no-store" } });
1105
+ }
1106
+ function findWaitUntil(args) {
1107
+ for (const a of args) {
1108
+ const w = a?.waitUntil;
1109
+ if (typeof w === "function") return w.bind(a);
1110
+ }
1111
+ return void 0;
1112
+ }
1113
+ function reguardFetch(options = {}) {
1114
+ if (options === null || typeof options !== "object") throw new ReguardConfigError("options", "invalid_type", "must be an object");
1115
+ for (const k of Object.keys(options))
1116
+ if (options[k] !== void 0 && !OPTION_KEYS.includes(k))
1117
+ throw new ReguardConfigError(k, k === "forward" ? "removed_option" : "unknown_option", k === "forward" ? "was removed: use collect: { requests: false }" : "isn't an option");
1118
+ const block = checkBlock(options.block, "block", "fetch");
1119
+ const collect = checkCollect(options.collect);
1120
+ const clientIp = checkClientIp(options.clientIp);
1121
+ const cookieDomain = checkCookieDomain(options.cookieDomain);
1122
+ const timeoutMs = checkNumber(options.timeoutMs, "timeoutMs", 100, 12e4) ?? 1e4;
1123
+ const flushIntervalMs = checkNumber(options.flushIntervalMs, "flushIntervalMs", 10, 36e5) ?? 2e3;
1124
+ checkCollector(options.collector);
1125
+ checkFunction(options.fetch, "fetch");
1126
+ checkFunction(options.onError, "onError");
1127
+ const log = makeLog(checkLogger(options.logger), checkBoolean(options.debug, "debug") ?? /^(?:1|true|yes)$/i.test(envValue("REGUARD_DEBUG") ?? ""));
1128
+ const ignore = options.ignore?.length ? skipMatcher(options.ignore) : void 0;
1129
+ const key = (options.key ?? envValue("REGUARD_KEY"))?.trim();
1130
+ const parsed = parseSiteKey(key);
1131
+ const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
1132
+ const onError = options.onError ?? (() => {
1133
+ });
1134
+ const verdicts = /* @__PURE__ */ new WeakMap();
1135
+ const decisions = /* @__PURE__ */ new WeakMap();
1136
+ if (!parsed?.site) {
1137
+ log.once("no-key", "warn", "REGUARD_KEY is not set (or isn't an rgk.\u2026 key): passing every request through.");
1138
+ return {
1139
+ site: void 0,
1140
+ handle: async () => void 0,
1141
+ record: () => {
1142
+ },
1143
+ wrap: (h) => h,
1144
+ verdict: async () => null,
1145
+ decision: () => null,
1146
+ scriptTag: () => "",
1147
+ flush: async () => {
1148
+ }
1149
+ };
1150
+ }
1151
+ const site = parsed.site;
1152
+ const secrets = [parsed.secret];
1153
+ const prev = parseSiteKey((options.previousKey ?? envValue("REGUARD_KEY_PREVIOUS"))?.trim());
1154
+ if (prev?.site === site && prev.secret !== parsed.secret) secrets.push(prev.secret);
1155
+ const collector = collectorBase(options.collector ?? envValue("REGUARD_COLLECTOR"));
1156
+ const platform = options.platform ?? detectPlatform(typeof process !== "undefined" ? process.env : void 0) ?? (typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" ? "workers" : null);
1157
+ const health = new Health(log);
1158
+ const allDry = !block || BLOCK_REASONS.every((r) => block.dryRun.has(r));
1159
+ const denyMaps = (options.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
1160
+ const allowList = block?.allow.length ? skipMatcher(block.allow) : void 0;
1161
+ const skipped = skipMatcher(collect.skip);
1162
+ const tagSettings = { site, collect, cookieDomain };
1163
+ const pace = block?.pace;
1164
+ const pages = pace ? new Allowance(pace.documents.burst, pace.documents.perSecond / 1e3, 5e4) : void 0;
1165
+ const addressFor = (request) => {
1166
+ const get = (n) => request.headers.get(n) ?? void 0;
1167
+ if (typeof clientIp === "function") {
1168
+ let ip = null;
1169
+ try {
1170
+ ip = normalizeIp(clientIp(request) ?? void 0);
1171
+ } catch (e) {
1172
+ log.once("clientIp-threw", "warn", `clientIp threw: ${e?.message ?? e}`);
1173
+ }
1174
+ return ip ? { address: ip, internal: !isPublicIp(ip), via: "custom" } : { address: "", internal: false, via: "none" };
1175
+ }
1176
+ return resolveClientAddress({ peer: "", header: get }, clientIp, platform);
1177
+ };
1178
+ const readVerdict = async (cookie) => {
1179
+ for (const s of secrets) {
1180
+ const v = await readVerdictFrom(s, site, cookie).catch(() => null);
1181
+ if (v) return v;
1182
+ }
1183
+ return null;
1184
+ };
1185
+ const pushed = /* @__PURE__ */ new Map();
1186
+ const queue = [];
1187
+ let inflight;
1188
+ let lastFlush = 0;
1189
+ const flush = async () => {
1190
+ while (queue.length && health.canSend()) {
1191
+ const events = queue.splice(0, 500);
1192
+ lastFlush = Date.now();
1193
+ try {
1194
+ const res = await doFetch(`${collector}/_s/v1/server`, {
1195
+ method: "POST",
1196
+ headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
1197
+ body: JSON.stringify({ site, collect: collectReport(collect), events }),
1198
+ signal: AbortSignal.timeout(timeoutMs)
1199
+ });
1200
+ if (res.status === 429) health.paused();
1201
+ else if (res.status === 401 || res.status === 403) health.rejected(res.status);
1202
+ else if (res.status >= 500) health.failing(`HTTP ${res.status}`);
1203
+ else if (res.ok) {
1204
+ health.ok();
1205
+ const f = (await res.json().catch(() => null))?.flagged;
1206
+ const now = Date.now();
1207
+ for (const x of f?.sessions ?? []) if (typeof x.sid === "string" && Array.isArray(x.claims)) pushed.set(`s:${x.sid}`, { claims: x.claims, until: now + 6e5 });
1208
+ for (const x of f?.visitors ?? []) if (typeof x.visitor === "string" && Array.isArray(x.claims)) pushed.set(`v:${x.visitor}`, { claims: x.claims, until: now + 6e5 });
1209
+ if (pushed.size > 5e4) pushed.clear();
1210
+ }
1211
+ if (!res.ok) onError(new Error(`collector answered ${res.status} to /v1/server`));
1212
+ } catch (e) {
1213
+ health.failing(e?.name === "TimeoutError" ? `no answer within ${timeoutMs} ms` : String(e?.message ?? e));
1214
+ onError(e);
1215
+ }
1216
+ }
1217
+ if (!health.canSend()) queue.length = 0;
1218
+ };
1219
+ const flushSoon = (waitUntil, now = false) => {
1220
+ if (!queue.length || inflight) return;
1221
+ if (!now && Date.now() - lastFlush < flushIntervalMs && queue.length < 100) return;
1222
+ inflight = flush().finally(() => inflight = void 0);
1223
+ waitUntil?.(inflight);
1224
+ };
1225
+ const pushedFor = async (request, verified) => {
1226
+ if (!pushed.size) return null;
1227
+ const sid = cookieValue(request.headers.get("cookie"), SESSION_COOKIE);
1228
+ const a = addressFor(request);
1229
+ const now = Date.now();
1230
+ const claims = [];
1231
+ const k = [sid ? `s:${sid}` : ""];
1232
+ if (collect.addresses !== "off" && !verified && !a.internal && a.address) k.push(`v:${await hmac(parsed.secret, `visitor:${a.address}`, 22)}`);
1233
+ for (const x of k) {
1234
+ const e = x ? pushed.get(x) : void 0;
1235
+ if (e && e.until > now) claims.push(...e.claims);
1236
+ }
1237
+ return claims.length ? pushedVerdict(sid ?? "", site, claims, now) : null;
1238
+ };
1239
+ const proxy = async (request, p) => {
1240
+ const url = new URL(request.url);
1241
+ const headers = new Headers();
1242
+ request.headers.forEach((v, k) => {
1243
+ if (!NOT_FORWARDED.test(k) && !ADDRESS_HEADER.test(k)) headers.set(k, v);
1244
+ });
1245
+ const ref = request.headers.get("referer");
1246
+ if (ref) {
1247
+ try {
1248
+ const o = new URL(ref).origin;
1249
+ if (o !== "null") headers.set("referer", `${o}/`);
1250
+ } catch {
1251
+ }
1252
+ }
1253
+ const sid = cookieValue(request.headers.get("cookie"), SESSION_COOKIE);
1254
+ if (sid && /^[\w-]{1,64}$/.test(sid)) headers.set("cookie", `${SESSION_COOKIE}=${sid}`);
1255
+ headers.set("x-reguard-site", `${site}.${await hmac(parsed.secret, `prefix:${site}`, 16)}`);
1256
+ const a = addressFor(request);
1257
+ const value = collect.addresses === "off" || !a.address ? "-" : await hmac(parsed.secret, `visitor:${a.address}`, 22);
1258
+ headers.set("x-reguard-visitor", `${value}.${await hmac(parsed.secret, `visitor-header:${value}`, 16)}`);
1259
+ try {
1260
+ const init = { method: request.method, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) };
1261
+ if (request.method !== "GET" && request.method !== "HEAD" && request.body) {
1262
+ init.body = request.body;
1263
+ init.duplex = "half";
1264
+ }
1265
+ const r = await doFetch(`${collector}${p.decoded}${url.search}`, init);
1266
+ const out = new Headers();
1267
+ r.headers.forEach((v, k) => {
1268
+ if (!STRIP_FROM_RESPONSE.has(k) && k !== "set-cookie") out.set(k, v);
1269
+ });
1270
+ for (const c of r.headers.getSetCookie?.() ?? []) out.append("set-cookie", c);
1271
+ return new Response(request.method === "HEAD" ? null : r.body, { status: r.status, headers: out });
1272
+ } catch (e) {
1273
+ onError(e);
1274
+ log.once("proxy-failed", "warn", `couldn't pass /_s/* to Reguard (${e?.message ?? e}): pages load without Reguard's script until it answers`);
1275
+ return new Response(null, { status: 502 });
1276
+ }
1277
+ };
1278
+ const decide = (request, reason, p, verdict, paceKind) => ({
1279
+ reason,
1280
+ dryRun: block.dryRun.has(reason),
1281
+ status: reason === "pace" ? 429 : block.status,
1282
+ retryAfter: RETRY_AFTER[reason],
1283
+ ...paceKind ? { pace: paceKind } : {},
1284
+ claims: reason === "pace" ? [] : verdict?.claims ?? [],
1285
+ verdict,
1286
+ path: p.decoded,
1287
+ clientIp: addressFor(request).address
1288
+ });
1289
+ const act = async (request, d) => {
1290
+ decisions.set(request, d);
1291
+ try {
1292
+ block.onBlock?.(d, request);
1293
+ } catch (e) {
1294
+ log.once("onBlock-threw", "warn", `block.onBlock threw: ${e?.message ?? e}`);
1295
+ }
1296
+ log.debug(`${d.dryRun ? "would block" : "blocked"} ${request.method} ${d.path}: ${d.reason}`);
1297
+ if (d.dryRun) return void 0;
1298
+ const respond = block.respond;
1299
+ if (respond) {
1300
+ try {
1301
+ const r = await respond(request, d);
1302
+ if (r instanceof Response) return r;
1303
+ log.once("respond-silent", "warn", "block.respond didn't return a Response: sent the default answer");
1304
+ } catch (e) {
1305
+ log.once("respond-threw", "error", `block.respond threw (${e?.message ?? e}): sent the default answer instead`);
1306
+ }
1307
+ }
1308
+ return defaultBlockAnswer(request, d);
1309
+ };
1310
+ const handle = async (request) => {
1311
+ const p = canonicalPath(new URL(request.url).pathname);
1312
+ if (isReguardPath(p.decoded)) return proxy(request, p);
1313
+ if (denyMaps && isSourceMapPath(p)) return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
1314
+ const cookie = request.headers.get("cookie");
1315
+ const pending = (async () => {
1316
+ const browser = await readVerdict(cookie);
1317
+ const pushedV = await pushedFor(request, !!browser);
1318
+ return { browser, pushed: pushedV, merged: mergeVerdicts(browser, pushedV) };
1319
+ })();
1320
+ verdicts.set(request, pending);
1321
+ if (!block) return void 0;
1322
+ const allowed = (allowList ? matchesBoth(allowList, p) : false) || (() => {
1323
+ try {
1324
+ return block.allowIf?.(request) === true;
1325
+ } catch {
1326
+ return false;
1327
+ }
1328
+ })();
1329
+ if (allowed) return void 0;
1330
+ const get = (n) => request.headers.get(n) ?? void 0;
1331
+ if (pages && get("sec-fetch-dest") === void 0 && (request.method === "GET" || request.method === "HEAD") && requestKind(p.decoded) === "document" && !isSpeculativeHeaders(get)) {
1332
+ const tool = toolOf(get("user-agent"));
1333
+ const a = addressFor(request);
1334
+ if (!(tool && BENIGN_TOOL_FAMILIES.has(tool.family)) && a.address && !a.internal && !pages.take(a.address)) {
1335
+ const answered = await act(request, decide(request, "pace", p, null, "document"));
1336
+ if (answered) return answered;
1337
+ }
1338
+ }
1339
+ const v = await pending;
1340
+ const opt = { labels: block.labels, minStage: block.minStage };
1341
+ const reason = v.browser?.flagged(opt) ? "flagged" : v.pushed?.flagged(opt) ? "flagged_server" : void 0;
1342
+ if (reason) {
1343
+ const d = decide(request, reason, p, v.merged);
1344
+ if (!d.dryRun || !decisions.has(request)) return act(request, d);
1345
+ }
1346
+ return void 0;
1347
+ };
1348
+ const record = (request, response, ctx) => {
1349
+ if (!collect.requests) return;
1350
+ void (async () => {
1351
+ try {
1352
+ const url = new URL(request.url);
1353
+ const p = canonicalPath(url.pathname);
1354
+ if (isReguardPath(p.decoded) || matchesEither(skipped, p) || ignore && matchesEither(ignore, p)) return;
1355
+ const get = (n) => request.headers.get(n) ?? void 0;
1356
+ const sid = cookieValue(get("cookie"), SESSION_COOKIE);
1357
+ const decision = decisions.get(request);
1358
+ const target = `${url.pathname}${url.search}`;
1359
+ if (!sid && !decision) {
1360
+ if (options.watchSessionless === false || collect.addresses === "off") return;
1361
+ const secure = url.protocol === "https:" ? true : void 0;
1362
+ if (!watchworthy({ userAgent: get("user-agent") ?? "", acceptLanguage: get("accept-language"), accept: get("accept"), secFetchMode: get("sec-fetch-mode"), secChUa: get("sec-ch-ua"), secure, path: url.pathname, status: response.status })) return;
1363
+ }
1364
+ const a = addressFor(request);
1365
+ const hash = (s) => hmac(parsed.secret, s, 16);
1366
+ const contentType = response.headers.get("content-type") ?? "";
1367
+ const responseBytes = Number(response.headers.get("content-length") ?? 0) || 0;
1368
+ const requestBytes = Number(get("content-length") ?? 0) || 0;
1369
+ let exchange;
1370
+ if (!isSpeculativeHeaders(get) && isApiLike(target, contentType, requestBytes)) {
1371
+ const input = { method: request.method, url: target, requestContentType: get("content-type") ?? "", requestBody: "", requestBytes, status: response.status, responseContentType: contentType, responseBytes };
1372
+ const wanted = /* @__PURE__ */ new Set();
1373
+ describeExchange((s) => (wanted.add(s), ""), input);
1374
+ const memo = new Map(await Promise.all([...wanted].map(async (s) => [s, await hash(s)])));
1375
+ const d = describeExchange((s) => memo.get(s) ?? "", input);
1376
+ if (collect.pages === "masked") exchange = d;
1377
+ else if (collect.pages === "hashed") exchange = { ...d, endpoint: `~${await hash(`endpoint:${d.endpoint}`)}` };
1378
+ else {
1379
+ const { item: _item, ...rest } = d;
1380
+ exchange = { ...rest, endpoint: "" };
1381
+ }
1382
+ }
1383
+ queue.push({
1384
+ ...sid ? { sid } : {},
1385
+ at: Date.now(),
1386
+ method: request.method,
1387
+ url: collect.pages === "masked" ? privateUrl(target) : "",
1388
+ ...collect.pages !== "off" ? { item: await hash(`path:${url.pathname}`) } : {},
1389
+ ...collect.pages !== "masked" ? { traits: pathTraits(target, get("rsc") === "1") } : {},
1390
+ status: response.status,
1391
+ headers: Object.fromEntries(["rsc", "next-router-prefetch", "sec-purpose", "purpose"].flatMap((n) => get(n) !== void 0 ? [[n, get(n)]] : [])),
1392
+ client: {
1393
+ ua: get("user-agent") ?? "",
1394
+ accept: get("accept") ?? "",
1395
+ acceptLanguage: get("accept-language") ?? "",
1396
+ secFetchMode: get("sec-fetch-mode"),
1397
+ secFetchSite: get("sec-fetch-site"),
1398
+ secFetchDest: get("sec-fetch-dest"),
1399
+ secChUa: get("sec-ch-ua"),
1400
+ hasCookie: !!get("cookie"),
1401
+ hasReferer: !!get("referer"),
1402
+ ...url.protocol === "https:" ? { secure: true } : {}
1403
+ },
1404
+ ...!sid && a.address && collect.addresses !== "off" ? { visitor: await hmac(parsed.secret, `visitor:${a.address}`, 22) } : {},
1405
+ ...exchange ? { exchange } : {},
1406
+ ...decision?.pace ? { pace: decision.pace } : {},
1407
+ ...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
1408
+ ...a.internal ? { internal: true } : {}
1409
+ });
1410
+ if (queue.length > 5e3) queue.splice(0, queue.length - 5e3);
1411
+ flushSoon(ctx?.waitUntil, !!decision);
1412
+ } catch (e) {
1413
+ onError(e);
1414
+ }
1415
+ })();
1416
+ };
1417
+ const timer = typeof setInterval === "function" ? setInterval(() => flushSoon(void 0, true), flushIntervalMs) : void 0;
1418
+ timer?.unref?.();
1419
+ return {
1420
+ site,
1421
+ handle: (request) => handle(request),
1422
+ record,
1423
+ wrap(handler) {
1424
+ return async (request, ...rest) => {
1425
+ const waitUntil = findWaitUntil(rest);
1426
+ const early = await handle(request);
1427
+ if (early) {
1428
+ record(request, early, { waitUntil });
1429
+ return early;
1430
+ }
1431
+ const res = await handler(request, ...rest);
1432
+ record(request, res, { waitUntil });
1433
+ return res;
1434
+ };
1435
+ },
1436
+ verdict: async (request) => (await verdicts.get(request))?.merged ?? mergeVerdicts(await readVerdict(request.headers.get("cookie")), null),
1437
+ decision: (request) => {
1438
+ const d = decisions.get(request);
1439
+ return d?.dryRun ? d : null;
1440
+ },
1441
+ scriptTag: (opts) => renderScriptTag(tagSettings, opts?.nonce),
1442
+ flush: async () => {
1443
+ await inflight;
1444
+ await flush();
1445
+ }
1446
+ };
1447
+ }
1448
+ // Annotate the CommonJS export names for ESM import in node:
1449
+ 0 && (module.exports = {
1450
+ ReguardConfigError,
1451
+ defaultBlockAnswer,
1452
+ reguardFetch
1453
+ });