reguard 0.0.0-stage → 0.7.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Reguard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,65 @@
1
- # Temporary Holding Version
1
+ # reguard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Reguard for your server. Reguard spots tools that take your web app apart or copy it (REA, AI
4
+ browser agents, crawlers, scanners, site copiers, source-map downloaders) and tells your server,
5
+ so you can slow them down. Normal visitors see nothing.
6
+
7
+ ```bash
8
+ npm install reguard
9
+ ```
10
+
11
+ Put your site key in the server's environment as `REGUARD_KEY` (it looks like
12
+ `rgk.your-site.v1.…`; copy it from https://reguard.site/app/). Then:
13
+
14
+ ```js
15
+ import reguard from "reguard";
16
+
17
+ app.use(reguard()); // Express, Connect, or anything that takes Connect-style middleware
18
+ ```
19
+
20
+ `reguard()` serves `/_s/*` from your own domain, adds the Reguard script tag to your HTML pages,
21
+ puts each visitor's verdict on `req.reguard`, and sends Reguard short request summaries: hashes and
22
+ shapes, never values. Addresses are sent only as a keyed hash. With no `REGUARD_KEY` it does nothing,
23
+ so local development keeps working.
24
+
25
+ Choose what Reguard receives (the tag carries the same choices to the browser):
26
+
27
+ ```js
28
+ app.use(reguard({
29
+ collect: {
30
+ pages: "masked", // or "hashed" (keyed hashes only) or "off" (only the kind of request)
31
+ addresses: "hashed", // or "off": nothing about visitors' addresses
32
+ behavior: true, // false: no click, key or scroll timings from the browser
33
+ requests: true, // false: no request summaries
34
+ skip: ["/account/*"], // pages Reguard never runs on or reports
35
+ },
36
+ }));
37
+ ```
38
+
39
+ Each setting and what it costs in detection: https://reguard.site/docs/data-controls/
40
+
41
+ Turn blocking on when you trust what you see:
42
+
43
+ ```js
44
+ app.use(reguard({ block: true })); // confirmed copycats get a 429 "slow down" answer
45
+ ```
46
+
47
+ ## Next.js
48
+
49
+ ```js
50
+ // next.config.mjs
51
+ import { withReguard } from "reguard/next";
52
+ export default withReguard({ /* your config */ });
53
+ ```
54
+
55
+ ```jsx
56
+ // app/layout.jsx
57
+ import Script from "next/script";
58
+ import { reguardScriptProps } from "reguard/next";
59
+
60
+ <Script {...reguardScriptProps()} />; // or reguardScriptProps({ collect: { pages: "hashed" } })
61
+ ```
62
+
63
+ Full guide, verdicts, blocking and privacy: https://reguard.site/docs/
64
+
65
+ Node.js 20 or newer. ESM only.
@@ -0,0 +1,496 @@
1
+ // ../shared/src/exchange.ts
2
+ var IGNORED_PARAMS = /* @__PURE__ */ new Set(["_rsc", "_", "cb", "ts", "t", "_t", "v", "nocache", "__nextDataReq", "__nextLocale"]);
3
+ var PAGE_KEYS = /* @__PURE__ */ new Set(["page", "p", "offset", "skip", "start", "cursor", "after", "from"]);
4
+ var STRONG = [
5
+ /['"`]\s*(?:or|and|union|select|order\s+by|--|#|;|\))/i,
6
+ // breaking out of a quoted string
7
+ /\bunion\s+(?:all\s+)?select\b|\bsleep\s*\(|\bbenchmark\s*\(|\bwaitfor\s+delay\b|\bxp_cmdshell\b/i,
8
+ /\.\.[/\\]/,
9
+ // traversal
10
+ /\$\{[^}]*\}|\{\{[^}]*\}\}|<%[\s\S]*%>/,
11
+ // template injection
12
+ /<\s*\/?\s*(?:script|iframe|svg|img)\b|javascript:|\bon(?:error|load)\s*=/i,
13
+ // markup injection
14
+ /%[0-9a-f]{2}/i,
15
+ // still percent-encoded after decoding: double encoding
16
+ /\u0000/
17
+ // null byte
18
+ ];
19
+ function normalizeEndpoint(path) {
20
+ return path.split("/").map(
21
+ (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
22
+ ).join("/");
23
+ }
24
+ function privateUrl(url) {
25
+ const [path = "/", query] = url.split("?");
26
+ const names = query ? [...new Set(new URLSearchParams(query).keys())] : [];
27
+ return normalizeEndpoint(path) + (names.length ? `?${names.map((n) => `${n}=`).join("&")}` : "");
28
+ }
29
+ function shapeOf(v) {
30
+ if (v === "") return "empty";
31
+ if (/^-?\d+$/.test(v)) return "int";
32
+ if (/^-?\d*\.\d+$/.test(v)) return "decimal";
33
+ if (/^(?:true|false)$/i.test(v)) return "bool";
34
+ 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";
35
+ if (/^[0-9a-f]{16,}$/i.test(v)) return "hex";
36
+ if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return "email";
37
+ if (/^[a-z0-9]+(?:[-_.][a-z0-9]+)+$/i.test(v)) return "slug";
38
+ if (/^[\p{L}\p{N}]+$/u.test(v)) return "word";
39
+ return "text";
40
+ }
41
+ function strongMarker(v) {
42
+ return STRONG.some((re) => re.test(v));
43
+ }
44
+ function boundaryOf(v) {
45
+ if (!/^-?\d+$/.test(v)) return void 0;
46
+ if (/^-?0+$/.test(v)) return "zero";
47
+ if (v.startsWith("-")) return "neg";
48
+ if (v.length >= 10) return "overflow";
49
+ return void 0;
50
+ }
51
+ function describeExchange(hash, x) {
52
+ const [path = "/", query = ""] = x.url.split("?");
53
+ const params = {};
54
+ let pageValue = null;
55
+ const add = (name, value, shape = shapeOf(value), scanned = true) => {
56
+ const p = { h: hash(`${name}=${value}`), shape };
57
+ if (scanned) {
58
+ if (strongMarker(value)) p.strong = true;
59
+ const b = boundaryOf(value);
60
+ if (b) p.boundary = b;
61
+ }
62
+ params[name] = p;
63
+ const bare = name.replace(/^body\./, "").toLowerCase();
64
+ if (PAGE_KEYS.has(bare) && /^\d+$/.test(value)) pageValue = Number(value);
65
+ };
66
+ for (const [k, v] of new URLSearchParams(query)) if (!IGNORED_PARAMS.has(k)) add(k, v);
67
+ const body = x.requestBody ?? "";
68
+ const ct = (x.requestContentType ?? "").toLowerCase();
69
+ if (body) {
70
+ try {
71
+ if (ct.includes("json")) {
72
+ const parsed = JSON.parse(body);
73
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
74
+ for (const [k, v] of Object.entries(parsed)) {
75
+ const name = `body.${k}`;
76
+ if (typeof v === "string") add(name, v);
77
+ else if (typeof v === "number") add(name, String(v));
78
+ else if (typeof v === "boolean") add(name, String(v), "bool", false);
79
+ else if (v === null) add(name, "null", "empty", false);
80
+ else add(name, JSON.stringify(v).slice(0, 256), "json", false);
81
+ }
82
+ }
83
+ } else if (ct.includes("x-www-form-urlencoded")) {
84
+ for (const [k, v] of new URLSearchParams(body)) add(`body.${k}`, v);
85
+ }
86
+ } catch {
87
+ }
88
+ }
89
+ let listLength = null;
90
+ const head = x.responseHead ?? "";
91
+ if ((x.responseContentType ?? "").includes("json") && head) {
92
+ try {
93
+ const parsed = JSON.parse(head);
94
+ if (Array.isArray(parsed)) listLength = parsed.length;
95
+ else if (parsed && typeof parsed === "object") {
96
+ const firstArray = Object.values(parsed).find(Array.isArray);
97
+ if (firstArray) listLength = firstArray.length;
98
+ }
99
+ } catch {
100
+ }
101
+ }
102
+ return {
103
+ method: x.method,
104
+ endpoint: normalizeEndpoint(path),
105
+ item: hash(`path:${path}`),
106
+ params,
107
+ requestBytes: x.requestBytes,
108
+ status: x.status,
109
+ responseBytes: x.responseBytes,
110
+ listLength,
111
+ pageValue
112
+ };
113
+ }
114
+ function isApiLike(url, responseContentType, requestBytes) {
115
+ const ct = responseContentType.toLowerCase();
116
+ return url.startsWith("/api/") || url.includes("_rsc=") || ct.includes("json") || ct.includes("x-component") || requestBytes > 0;
117
+ }
118
+ function isSpeculativeHeaders(get) {
119
+ return get("next-router-prefetch") !== void 0 || /prefetch|prerender/i.test(get("sec-purpose") ?? get("purpose") ?? "");
120
+ }
121
+
122
+ // ../shared/src/verdict.ts
123
+ var VERDICT_COOKIE = "_sv";
124
+ var SESSION_COOKIE = "_s";
125
+ var enc = new TextEncoder();
126
+ var keys = /* @__PURE__ */ new Map();
127
+ function unb64url(s) {
128
+ const pad = s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4);
129
+ const bin = atob(pad);
130
+ const out = new Uint8Array(new ArrayBuffer(bin.length));
131
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
132
+ return out;
133
+ }
134
+ function hmacKey(siteKey) {
135
+ let k = keys.get(siteKey);
136
+ if (!k) {
137
+ k = crypto.subtle.importKey("raw", enc.encode(siteKey), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
138
+ keys.set(siteKey, k);
139
+ }
140
+ return k;
141
+ }
142
+ async function verifyVerdict(siteKey, token, expect = {}) {
143
+ try {
144
+ if (!token) return null;
145
+ const [v, body, sig] = token.split(".");
146
+ if (v !== "v1" || !body || !sig) return null;
147
+ const ok = await crypto.subtle.verify("HMAC", await hmacKey(siteKey), unb64url(sig), enc.encode(`v1.${body}`));
148
+ if (!ok) return null;
149
+ const p = JSON.parse(new TextDecoder().decode(unb64url(body)));
150
+ if (p.v !== 1 || p.exp < (expect.now ?? Date.now())) return null;
151
+ if (expect.site !== void 0 && p.site !== expect.site) return null;
152
+ if (expect.sid !== void 0 && p.sid !== expect.sid) return null;
153
+ return p;
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+ function cookieValue(header, name) {
159
+ if (!header) return void 0;
160
+ for (const part of header.split(";")) {
161
+ const i = part.indexOf("=");
162
+ if (i > 0 && part.slice(0, i).trim() === name) return part.slice(i + 1).trim();
163
+ }
164
+ return void 0;
165
+ }
166
+
167
+ // ../shared/src/keys.ts
168
+ var SITE_KEY_PREFIX = "rgk";
169
+ function formatSiteKey(site, version, secret) {
170
+ return `${SITE_KEY_PREFIX}.${site}.v${version}.${secret}`;
171
+ }
172
+ function parseSiteKey(key) {
173
+ const k = (key ?? "").trim();
174
+ if (!k) return null;
175
+ if (!k.startsWith(`${SITE_KEY_PREFIX}.`)) return /^[\w-]+$/.test(k) ? { secret: k } : null;
176
+ const parts = k.split(".");
177
+ if (parts.length < 4) return null;
178
+ const secret = parts[parts.length - 1];
179
+ const version = /^v(\d+)$/.exec(parts[parts.length - 2]);
180
+ const site = parts.slice(1, -2).join(".");
181
+ if (!version || !site || !/^[\w-]+$/.test(secret)) return null;
182
+ return { site, version: Number(version[1]), secret };
183
+ }
184
+
185
+ // ../shared/src/tools.ts
186
+ var BENIGN_TOOL_FAMILIES = /* @__PURE__ */ new Set(["search_bot", "monitor"]);
187
+ var TOOLS = [
188
+ // Scanners and fuzzers (captured: ffuf sends "Fuzz Faster U Fool v2.x").
189
+ [/fuzz faster u fool/i, "scanner", "ffuf"],
190
+ [/^feroxbuster\//i, "scanner", "feroxbuster"],
191
+ [/^gobuster\//i, "scanner", "gobuster"],
192
+ [/\bnikto\b/i, "scanner", "nikto"],
193
+ [/^sqlmap\//i, "scanner", "sqlmap"],
194
+ [/wpscan/i, "scanner", "wpscan"],
195
+ [/nuclei/i, "scanner", "nuclei"],
196
+ [/dirbuster|\bdirb\b|wfuzz|\bdirsearch\b/i, "scanner", "dirbuster"],
197
+ [/xnlinkfinder/i, "scanner", "xnlinkfinder"],
198
+ [/zgrab|masscan|nmap scripting engine|nessus|qualys|acunetix|netsparker|burp ?suite|owasp ?zap|zaproxy|arachni|w3af|whatweb|wappalyzer/i, "scanner", "scanner"],
199
+ // Site copiers.
200
+ [/httrack/i, "cloner", "httrack"],
201
+ [/^wget\//i, "cloner", "wget"],
202
+ [/website ?(?:copier|downloader|ripper)|sitesucker|webcopy|teleport ?pro|offline ?explorer|webzip|pagenest/i, "cloner", "site-copier"],
203
+ // Crawlers and spiders.
204
+ [/katana/i, "crawler", "katana"],
205
+ [/gospider/i, "crawler", "gospider"],
206
+ [/hakrawler/i, "crawler", "hakrawler"],
207
+ [/colly/i, "crawler", "colly"],
208
+ [/^scrapy\//i, "crawler", "scrapy"],
209
+ [/crawl4ai/i, "crawler", "crawl4ai"],
210
+ // Declared AI crawlers and agents.
211
+ [/firecrawl/i, "ai_crawler", "firecrawl"],
212
+ [
213
+ /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,
214
+ "ai_crawler",
215
+ "ai-crawler"
216
+ ],
217
+ // Search engines, link previews, monitors.
218
+ [
219
+ /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,
220
+ "search_bot",
221
+ "search-or-preview-bot"
222
+ ],
223
+ [/uptimerobot|pingdom|statuscake|datadog|newrelic|site24x7|better ?uptime|betterstack|checkly|freshping|hetrixtools|uptime-kuma/i, "monitor", "uptime-monitor"],
224
+ // Site audits a site's owner runs on their own site (SEO crawlers, link checkers, archives).
225
+ [/screaming frog|sitebulb|deepcrawl|lumar|ahrefs(?:site)?audit|semrush|w3c_validator|w3c-checklink|ia_archiver|archive\.org_bot/i, "monitor", "site-audit"],
226
+ // Error trackers fetch a site's scripts and source maps to symbolicate stack traces.
227
+ [/\bsentry\/|rollbar|bugsnag|raygun|trackjs|honeybadger/i, "monitor", "error-tracker"],
228
+ [/headlesschrome/i, "headless_browser", "headless-chrome"],
229
+ // Generic HTTP libraries and CLIs (captured: sourcemapper sends "Go-http-client/1.1").
230
+ [
231
+ /^(?: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,
232
+ "http_library",
233
+ "http-library"
234
+ ]
235
+ ];
236
+ function toolOf(userAgent) {
237
+ const ua = (userAgent ?? "").trim();
238
+ if (!ua) return { family: "http_library", tool: "no-user-agent" };
239
+ for (const [re, family, tool] of TOOLS) if (re.test(ua)) return { family, tool };
240
+ return void 0;
241
+ }
242
+ function browserIncoherence(h) {
243
+ const ua = h.userAgent ?? "";
244
+ if (!/^Mozilla\/5\.0 \(/.test(ua) || toolOf(ua)) return [];
245
+ const reasons = [];
246
+ if (!h.acceptLanguage) reasons.push("no_accept_language");
247
+ if (/ {2,}/.test(ua) || / {2,}/.test(h.accept ?? "")) reasons.push("header_whitespace");
248
+ const chrome = /(?:Chrome|CriOS)\/(\d+)/.exec(ua);
249
+ const firefox = /(?:Firefox|FxiOS)\/(\d+)/.exec(ua);
250
+ const safari = /Version\/(\d+)[.\d]* (?:Mobile\/\w+ )?Safari\//.exec(ua);
251
+ const version = Number(chrome?.[1] ?? firefox?.[1] ?? safari?.[1] ?? 0);
252
+ const modern = chrome && version >= 90 || firefox && version >= 90 || safari && version >= 17;
253
+ if (h.secure !== false && modern && !h.secFetchMode) reasons.push("no_fetch_metadata");
254
+ if (h.secure !== false && h.secChUa && chrome && !/CriOS/.test(ua)) {
255
+ const hinted = /"Chromium";\s*v="(\d+)"/.exec(h.secChUa)?.[1];
256
+ if (hinted && Number(hinted) !== Number(chrome[1])) reasons.push("client_hints_version_mismatch");
257
+ if (/"HeadlessChrome"/.test(h.secChUa) && !/HeadlessChrome/.test(ua)) reasons.push("client_hints_headless_mismatch");
258
+ }
259
+ return reasons;
260
+ }
261
+ 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;
262
+ 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;
263
+ var BROWSER_AUTOMATIC = /^\/(?:favicon\.ico|apple-touch-icon[\w.-]*\.png|browserconfig\.xml|site\.webmanifest|manifest\.json|\.well-known\/appspecific\/)/i;
264
+ function watchworthy(w) {
265
+ const tool = toolOf(w.userAgent);
266
+ if (tool && tool.family !== "headless_browser") return !BENIGN_TOOL_FAMILIES.has(tool.family);
267
+ if (browserIncoherence(w).length) return true;
268
+ const t = w.traits ?? pathTraits(w.path);
269
+ if (t.family || t.discovery || t.map) return true;
270
+ if (t.auto) return false;
271
+ return w.status === 404 || w.status === 405 || w.status === 410;
272
+ }
273
+ function requestKind(url, rsc = false) {
274
+ const path = url.split("?")[0] ?? url;
275
+ if (rsc || url.includes("_rsc=")) return "rsc";
276
+ if (path.startsWith("/api/")) return "api";
277
+ if (/\.(?:html?|php|aspx?|jsp)$/i.test(path)) return "document";
278
+ if (/\.[a-z0-9]{1,6}$/i.test(path) || path.startsWith("/_next/")) return "static";
279
+ return "document";
280
+ }
281
+ function pathTraits(url, rsc = false) {
282
+ const path = url.split("?")[0] ?? url;
283
+ const t = { kind: requestKind(url, rsc) };
284
+ const fam = SENSITIVE_PATH.exec(path)?.[1]?.toLowerCase();
285
+ if (fam) t.family = fam.startsWith(".") ? fam : fam.replace(/\..*$/, "");
286
+ if (DISCOVERY_FILE.test(path)) t.discovery = path.toLowerCase();
287
+ if (BROWSER_AUTOMATIC.test(path)) t.auto = true;
288
+ if (/\.map$/i.test(path)) t.map = true;
289
+ if (/\.(?:m?js|cjs)$/i.test(path)) t.script = true;
290
+ if (/[0-9a-f]{32,}/i.test(path)) t.random = true;
291
+ return t;
292
+ }
293
+
294
+ // ../shared/src/collect.ts
295
+ var DEFAULT_COLLECT = Object.freeze({ pages: "masked", addresses: "hashed", behavior: true, requests: true, skip: [] });
296
+ var PAGES = ["masked", "hashed", "off"];
297
+ var ADDRESSES = ["hashed", "off"];
298
+ var SKIP_PATTERN = /^\/[\w\-.~%!$&'()*+;=:@/]{0,199}$/;
299
+ var MAX_SKIP = 50;
300
+ function flag(v) {
301
+ if (typeof v === "boolean") return v;
302
+ if (typeof v !== "string") return void 0;
303
+ const s = v.trim().toLowerCase();
304
+ return s === "on" || s === "true" || s === "1" || s === "yes" ? true : s === "off" || s === "false" || s === "0" || s === "no" ? false : void 0;
305
+ }
306
+ function resolveCollect(input, warn = () => {
307
+ }) {
308
+ const out = { ...DEFAULT_COLLECT, skip: [] };
309
+ if (input === void 0 || input === null) return out;
310
+ if (typeof input !== "object" || Array.isArray(input)) {
311
+ warn("collect should be an object; using the defaults");
312
+ return out;
313
+ }
314
+ const c = input;
315
+ const bad = (name, value, allowed) => warn(`collect.${name} = ${JSON.stringify(value)} isn't ${allowed}; using the default`);
316
+ if (c.pages !== void 0) {
317
+ if (PAGES.includes(c.pages)) out.pages = c.pages;
318
+ else bad("pages", c.pages, '"masked", "hashed" or "off"');
319
+ }
320
+ if (c.addresses !== void 0) {
321
+ if (ADDRESSES.includes(c.addresses)) out.addresses = c.addresses;
322
+ else bad("addresses", c.addresses, '"hashed" or "off"');
323
+ }
324
+ for (const name of ["behavior", "requests"]) {
325
+ if (c[name] === void 0) continue;
326
+ const v = flag(c[name]);
327
+ if (v === void 0) bad(name, c[name], "true or false");
328
+ else out[name] = v;
329
+ }
330
+ if (c.skip !== void 0) {
331
+ const list = typeof c.skip === "string" ? c.skip.split(",") : Array.isArray(c.skip) ? c.skip : void 0;
332
+ if (!list) bad("skip", c.skip, "a list of paths");
333
+ else {
334
+ for (const raw of list) {
335
+ const p = typeof raw === "string" ? raw.trim() : raw;
336
+ if (p === "") continue;
337
+ if (typeof p === "string" && SKIP_PATTERN.test(p) && out.skip.length < MAX_SKIP) out.skip.push(p);
338
+ else bad("skip", p, `a path that starts with "/" (at most ${MAX_SKIP} of them)`);
339
+ }
340
+ }
341
+ }
342
+ return out;
343
+ }
344
+ function skipMatcher(patterns) {
345
+ if (!patterns.length) return () => false;
346
+ const res = patterns.map((p) => {
347
+ const tail = p.endsWith("/*");
348
+ const body = (tail ? p.slice(0, -2) : p).split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
349
+ return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`);
350
+ });
351
+ return (path) => {
352
+ const p = path.split(/[?#]/)[0] ?? path;
353
+ return res.some((re) => re.test(p));
354
+ };
355
+ }
356
+ function collectAttributes(c) {
357
+ const a = {};
358
+ if (c.pages !== DEFAULT_COLLECT.pages) a["data-pages"] = c.pages;
359
+ if (c.addresses !== DEFAULT_COLLECT.addresses) a["data-addresses"] = c.addresses;
360
+ if (!c.behavior) a["data-behavior"] = "off";
361
+ if (c.skip.length) a["data-skip"] = c.skip.join(",");
362
+ return a;
363
+ }
364
+ function collectReport(c) {
365
+ return { pages: c.pages, addresses: c.addresses, behavior: c.behavior };
366
+ }
367
+
368
+ // ../shared/src/allowance.ts
369
+ var Allowance = class {
370
+ constructor(capacity, refillPerMs, maxKeys = 1e5) {
371
+ this.capacity = capacity;
372
+ this.refillPerMs = refillPerMs;
373
+ this.maxKeys = maxKeys;
374
+ }
375
+ buckets = /* @__PURE__ */ new Map();
376
+ take(key, now = Date.now()) {
377
+ const b = this.refill(key, now);
378
+ if (b.tokens < 1) return false;
379
+ b.tokens -= 1;
380
+ return true;
381
+ }
382
+ /** Whether `take` would succeed now, without using anything. */
383
+ has(key, now = Date.now()) {
384
+ return this.refill(key, now).tokens >= 1;
385
+ }
386
+ refill(key, now) {
387
+ const prev = this.buckets.get(key);
388
+ const b = prev ? { tokens: Math.min(this.capacity, prev.tokens + (now - prev.at) * this.refillPerMs), at: now } : { tokens: this.capacity, at: now };
389
+ this.buckets.delete(key);
390
+ this.buckets.set(key, b);
391
+ if (this.buckets.size > this.maxKeys) this.buckets.delete(this.buckets.keys().next().value);
392
+ return b;
393
+ }
394
+ };
395
+
396
+ // src/core.ts
397
+ var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
398
+ function withFlagged(p) {
399
+ return {
400
+ ...p,
401
+ flagged({ labels, minStage = "candidate" } = {}) {
402
+ return p.claims.some((c) => STAGE_RANK[c.stage] >= STAGE_RANK[minStage] && (!labels || labels.includes(c.label)));
403
+ }
404
+ };
405
+ }
406
+ async function readVerdictFrom(secret, site, cookieHeader) {
407
+ const token = cookieValue(cookieHeader, VERDICT_COOKIE);
408
+ if (!token) return null;
409
+ const p = await verifyVerdict(secret, token, { site, sid: cookieValue(cookieHeader, SESSION_COOKIE) });
410
+ return p ? withFlagged(p) : null;
411
+ }
412
+ var DEFAULT_COLLECTOR = "https://api.reguard.site";
413
+ function collectorBase(collector) {
414
+ return (collector ?? DEFAULT_COLLECTOR).replace(/\/+$/, "").replace(/\/_s$/, "");
415
+ }
416
+ function envValue(name) {
417
+ return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
418
+ }
419
+ var VERDICT_TTL_MS = 10 * 6e4;
420
+ var DEFAULT_PACE = {
421
+ documents: { burst: 30, perSecond: 1 },
422
+ api: { burst: 60, perSecond: 5 },
423
+ notFound: { burst: 20, perSecond: 0.5 }
424
+ };
425
+ function blockConfig(block) {
426
+ if (!block) return null;
427
+ const cfg = block === true ? {} : block;
428
+ return {
429
+ labels: cfg.labels,
430
+ status: cfg.status ?? 429,
431
+ minStage: cfg.minStage ?? "candidate",
432
+ require: cfg.require?.length ? cfg.require : void 0,
433
+ maxAgeMs: cfg.requireMaxAgeMs ?? 6e4,
434
+ graceMs: cfg.requireGraceMs ?? 15e3,
435
+ graceRequests: cfg.requireGraceRequests ?? 30,
436
+ gracePages: cfg.requireGracePages ?? 3,
437
+ refreshRequests: cfg.requireRefreshRequests ?? 30,
438
+ refreshMs: cfg.requireRefreshMs ?? 1e4,
439
+ pace: cfg.pace === false ? null : { ...DEFAULT_PACE, ...cfg.pace ?? {} }
440
+ };
441
+ }
442
+ function freshSeconds(cfg) {
443
+ return cfg?.require ? Math.max(5, Math.floor(cfg.maxAgeMs / 2e3)) : void 0;
444
+ }
445
+ var PACE_RETRY_AFTER = "2";
446
+ var PACE_JSON = JSON.stringify({ error: "Too many requests. Slow down and try again in a moment." });
447
+ function verdictAgeMs(v, now = Date.now()) {
448
+ return now - (v.exp - VERDICT_TTL_MS);
449
+ }
450
+ function pushedVerdict(sid, site, claims) {
451
+ return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: Date.now() + 6e4 });
452
+ }
453
+ var BLOCK_RETRY_AFTER = "120";
454
+ var BLOCK_HTML = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Please slow down</title></head><body><h1>Please slow down</h1><p>This browser looks like it is being driven by an automated tool. Try again in a few minutes.</p></body></html>';
455
+ var BLOCK_JSON = JSON.stringify({ error: "Too many automated requests from this browser. Try again in a few minutes." });
456
+ function wantsPage(get) {
457
+ return get("sec-fetch-dest") === "document" || /text\/html/i.test(get("accept") ?? "");
458
+ }
459
+ function isReguardPath(path) {
460
+ return path === "/_s" || path.startsWith("/_s/");
461
+ }
462
+
463
+ export {
464
+ privateUrl,
465
+ describeExchange,
466
+ isApiLike,
467
+ isSpeculativeHeaders,
468
+ SESSION_COOKIE,
469
+ cookieValue,
470
+ formatSiteKey,
471
+ parseSiteKey,
472
+ BENIGN_TOOL_FAMILIES,
473
+ toolOf,
474
+ watchworthy,
475
+ requestKind,
476
+ pathTraits,
477
+ resolveCollect,
478
+ skipMatcher,
479
+ collectAttributes,
480
+ collectReport,
481
+ Allowance,
482
+ readVerdictFrom,
483
+ collectorBase,
484
+ envValue,
485
+ blockConfig,
486
+ freshSeconds,
487
+ PACE_RETRY_AFTER,
488
+ PACE_JSON,
489
+ verdictAgeMs,
490
+ pushedVerdict,
491
+ BLOCK_RETRY_AFTER,
492
+ BLOCK_HTML,
493
+ BLOCK_JSON,
494
+ wantsPage,
495
+ isReguardPath
496
+ };