reguard 0.7.1 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -31
- package/dist/chunks/chunk-3AYS7WSY.js +350 -0
- package/dist/chunks/chunk-KNKCUJL3.js +969 -0
- package/dist/chunks/{chunk-W56LN2M5.js → chunk-PA46KSOR.js} +385 -33
- package/dist/chunks/chunk-U54IP6G4.js +448 -0
- package/dist/cjs/fastify.cjs +2109 -0
- package/dist/cjs/fetch.cjs +1463 -0
- package/dist/cjs/index.cjs +2074 -0
- package/dist/cjs/next.cjs +1535 -0
- package/dist/cjs/testing.cjs +214 -0
- package/dist/fastify.js +59 -0
- package/dist/fetch.js +13 -0
- package/dist/index.js +15 -716
- package/dist/next.js +48 -52
- package/dist/testing.js +39 -0
- package/dist/types/node/src/config.d.ts +107 -0
- package/dist/types/node/src/core.d.ts +66 -72
- package/dist/types/node/src/fastify.d.ts +41 -0
- package/dist/types/node/src/fetch.d.ts +76 -0
- package/dist/types/node/src/health.d.ts +41 -0
- package/dist/types/node/src/index.d.ts +114 -34
- package/dist/types/node/src/next.d.ts +40 -27
- package/dist/types/node/src/testing.d.ts +25 -0
- package/dist/types/shared/src/address.d.ts +81 -0
- package/dist/types/shared/src/index.d.ts +6 -0
- package/dist/types/shared/src/paths.d.ts +32 -0
- package/dist/types-cjs/node/src/config.d.cts +107 -0
- package/dist/types-cjs/node/src/core.d.cts +107 -0
- package/dist/types-cjs/node/src/fastify.d.cts +41 -0
- package/dist/types-cjs/node/src/fetch.d.cts +76 -0
- package/dist/types-cjs/node/src/health.d.cts +41 -0
- package/dist/types-cjs/node/src/index.d.cts +203 -0
- package/dist/types-cjs/node/src/next.d.cts +85 -0
- package/dist/types-cjs/node/src/testing.d.cts +25 -0
- package/dist/types-cjs/shared/src/address.d.cts +81 -0
- package/dist/types-cjs/shared/src/allowance.d.cts +17 -0
- package/dist/types-cjs/shared/src/collect.d.cts +52 -0
- package/dist/types-cjs/shared/src/exchange.d.cts +69 -0
- package/dist/types-cjs/shared/src/index.d.cts +105 -0
- package/dist/types-cjs/shared/src/keys.d.cts +13 -0
- package/dist/types-cjs/shared/src/paths.d.cts +32 -0
- package/dist/types-cjs/shared/src/tools.d.cts +101 -0
- package/dist/types-cjs/shared/src/verdict.d.cts +37 -0
- package/package.json +73 -10
package/README.md
CHANGED
|
@@ -12,54 +12,74 @@ Put your site key in the server's environment as `REGUARD_KEY` (it looks like
|
|
|
12
12
|
`rgk.your-site.v1.…`; copy it from https://reguard.site/app/). Then:
|
|
13
13
|
|
|
14
14
|
```js
|
|
15
|
-
import reguard from "reguard";
|
|
15
|
+
import reguard from "reguard"; // or: const { reguard } = require("reguard");
|
|
16
16
|
|
|
17
|
-
app.use(reguard());
|
|
17
|
+
app.use(reguard()); // Express, Connect, NestJS on Express
|
|
18
18
|
```
|
|
19
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
|
|
22
|
-
|
|
23
|
-
so local development keeps working.
|
|
20
|
+
`reguard()` serves `/_s/*` from your own domain, adds the Reguard script tag to your HTML pages
|
|
21
|
+
(after `compression()`, so it sees the page first), puts each visitor's verdict on `req.reguard`, and
|
|
22
|
+
sends Reguard short request summaries: hashes and shapes, never values. With no `REGUARD_KEY` it
|
|
23
|
+
passes everything through, so local development keeps working. A mistake in the options throws a
|
|
24
|
+
`ReguardConfigError` at startup, naming the option.
|
|
24
25
|
|
|
25
|
-
|
|
26
|
+
## Read the verdict
|
|
26
27
|
|
|
27
28
|
```js
|
|
29
|
+
app.get("/api/export", (req, res) => {
|
|
30
|
+
if (req.reguard?.flagged({ minStage: "alert" })) return res.status(429).end();
|
|
31
|
+
// …
|
|
32
|
+
});
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`req.reguard` is the visitor's verified verdict (or `null`): its `claims`, where they came from
|
|
36
|
+
(`source`: the browser, your server's summaries, or both) and `flagged({ labels, minStage })`.
|
|
37
|
+
|
|
38
|
+
## Block: dry run first
|
|
39
|
+
|
|
40
|
+
```js
|
|
41
|
+
app.use(reguard({ block: { dryRun: true } })); // decide and report, never answer for your app
|
|
42
|
+
app.use(reguard({ block: true })); // then answer flagged visitors with 429
|
|
28
43
|
app.use(reguard({
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
skip: ["/account/*"], // pages Reguard never runs on or reports
|
|
44
|
+
block: {
|
|
45
|
+
minStage: "alert", // only rules past their trial
|
|
46
|
+
allow: ["/webhooks/*", "/healthz"], // never blocked, paced or required
|
|
47
|
+
respond: (req, res, decision) => res.status(403).json({ blocked: decision.reason }),
|
|
48
|
+
onBlock: (decision) => metrics.increment(`reguard.${decision.reason}`),
|
|
35
49
|
},
|
|
36
50
|
}));
|
|
37
51
|
```
|
|
38
52
|
|
|
39
|
-
|
|
53
|
+
Dry-run decisions are on `req.reguardDecision` and in the dashboard as "would have blocked".
|
|
40
54
|
|
|
41
|
-
|
|
55
|
+
## Other servers
|
|
42
56
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
57
|
+
- **Fastify:** `import reguard from "reguard/fastify"` then `await app.register(reguard, { block: true })`;
|
|
58
|
+
reads `request.ip` when `trustProxy` is set, and sets `request.reguard`.
|
|
59
|
+
- **Next.js:** `withReguard()` in `next.config`, `<Script {...reguardScriptProps()} />`, and
|
|
60
|
+
`reguardMiddleware({ block: true })` in `middleware.ts` (or `proxy.ts`), from `reguard/next`.
|
|
61
|
+
- **Hono, Remix, SvelteKit, Astro, Bun, Deno, Workers:** `reguardFetch()` from `reguard/fetch`, then
|
|
62
|
+
`export default { fetch: rg.wrap(app.fetch) }`.
|
|
46
63
|
|
|
47
|
-
##
|
|
64
|
+
## Test your app
|
|
48
65
|
|
|
49
66
|
```js
|
|
50
|
-
|
|
51
|
-
import { withReguard } from "reguard/next";
|
|
52
|
-
export default withReguard({ /* your config */ });
|
|
53
|
-
```
|
|
67
|
+
import { testKey, verdictCookie, claim } from "reguard/testing";
|
|
54
68
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
import { reguardScriptProps } from "reguard/next";
|
|
59
|
-
|
|
60
|
-
<Script {...reguardScriptProps()} />; // or reguardScriptProps({ collect: { pages: "hashed" } })
|
|
69
|
+
const key = testKey("shop"); // reguard({ key }) in your test app
|
|
70
|
+
const cookie = await verdictCookie(key, { claims: [claim("unauthorized_extraction")] });
|
|
71
|
+
await request(app).get("/api/items").set("cookie", cookie).expect(429);
|
|
61
72
|
```
|
|
62
73
|
|
|
63
|
-
|
|
74
|
+
## More
|
|
75
|
+
|
|
76
|
+
- Choose what Reguard receives with `collect` (pages, addresses, behavior, requests, skip).
|
|
77
|
+
- Get the visitor's address right behind your proxies with `clientIp` (auto-detected on common
|
|
78
|
+
hosts).
|
|
79
|
+
- Share verdicts with sibling hosts using `cookieDomain`.
|
|
80
|
+
- Rotate keys without downtime using `previousKey`.
|
|
81
|
+
- Check health with `status()`.
|
|
82
|
+
- Render the tag yourself with `scriptTag({ nonce })`.
|
|
64
83
|
|
|
65
|
-
Node.js 20 or newer
|
|
84
|
+
Full guide: https://reguard.site/docs/. Node.js 20 or newer, ESM and CommonJS. Source:
|
|
85
|
+
https://github.com/cadenticai/reguard-js (MIT).
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_PACE,
|
|
3
|
+
clientIpModeProblem,
|
|
4
|
+
resolveCollect
|
|
5
|
+
} from "./chunk-PA46KSOR.js";
|
|
6
|
+
|
|
7
|
+
// src/config.ts
|
|
8
|
+
var ReguardConfigError = class extends TypeError {
|
|
9
|
+
option;
|
|
10
|
+
code;
|
|
11
|
+
constructor(option, code, detail) {
|
|
12
|
+
super(`[reguard] ${option} ${detail}`);
|
|
13
|
+
this.name = "ReguardConfigError";
|
|
14
|
+
this.option = option;
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
var BLOCK_REASONS = ["flagged", "flagged_server", "require", "pace"];
|
|
19
|
+
var LABELS = ["rea", "automated_exploration", "unauthorized_extraction"];
|
|
20
|
+
var STAGES = ["candidate", "alert", "enforce"];
|
|
21
|
+
var fail = (option, code, detail) => {
|
|
22
|
+
throw new ReguardConfigError(option, code, detail);
|
|
23
|
+
};
|
|
24
|
+
var show = (v) => typeof v === "function" ? "a function" : JSON.stringify(v) ?? String(v);
|
|
25
|
+
var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
26
|
+
var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
|
27
|
+
function checkKeys(obj, allowed, prefix, moved = {}) {
|
|
28
|
+
for (const k of Object.keys(obj)) {
|
|
29
|
+
if (obj[k] === void 0 || allowed.includes(k)) continue;
|
|
30
|
+
const path = prefix ? `${prefix}.${k}` : k;
|
|
31
|
+
if (moved[k]) fail(path, "removed_option", `was removed: ${moved[k]}`);
|
|
32
|
+
const c = camel(k).replace(/Seconds$|Secs$/, "Ms");
|
|
33
|
+
const hint = allowed.find((a) => a === c || a === camel(k) || a.toLowerCase() === k.toLowerCase());
|
|
34
|
+
fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${prefix ? `${prefix}.` : ""}${hint}?)` : ""}`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function checkBoolean(v, option) {
|
|
38
|
+
if (v === void 0) return void 0;
|
|
39
|
+
if (typeof v !== "boolean") fail(option, "invalid_type", `must be true or false (got ${show(v)})`);
|
|
40
|
+
return v;
|
|
41
|
+
}
|
|
42
|
+
function checkFunction(v, option) {
|
|
43
|
+
if (v === void 0) return void 0;
|
|
44
|
+
if (typeof v !== "function") fail(option, "invalid_type", `must be a function (got ${show(v)})`);
|
|
45
|
+
return v;
|
|
46
|
+
}
|
|
47
|
+
function checkString(v, option) {
|
|
48
|
+
if (v === void 0) return void 0;
|
|
49
|
+
if (typeof v !== "string") fail(option, "invalid_type", `must be a string (got ${show(v)})`);
|
|
50
|
+
return v;
|
|
51
|
+
}
|
|
52
|
+
function checkNumber(v, option, min, max, integer = true) {
|
|
53
|
+
if (v === void 0) return void 0;
|
|
54
|
+
if (typeof v !== "number" || !Number.isFinite(v)) fail(option, "invalid_type", `must be a number (got ${show(v)})`);
|
|
55
|
+
const n = v;
|
|
56
|
+
if (integer && !Number.isInteger(n)) fail(option, "invalid_value", `must be a whole number (got ${n})`);
|
|
57
|
+
if (n < min || n > max) fail(option, "out_of_range", `must be from ${min} to ${max} (got ${n})`);
|
|
58
|
+
return n;
|
|
59
|
+
}
|
|
60
|
+
function checkOneOf(v, option, allowed) {
|
|
61
|
+
if (v === void 0) return void 0;
|
|
62
|
+
if (typeof v !== "string") fail(option, "invalid_type", `must be one of ${allowed.map((a) => `"${a}"`).join(", ")} (got ${show(v)})`);
|
|
63
|
+
if (!allowed.includes(v)) fail(option, "invalid_value", `must be one of ${allowed.map((a) => `"${a}"`).join(", ")} (got ${show(v)})`);
|
|
64
|
+
return v;
|
|
65
|
+
}
|
|
66
|
+
var PATH_PATTERN = /^\/[\w\-.~%!$&'()*+;=:@/]{0,199}$/;
|
|
67
|
+
var MAX_PATHS = 50;
|
|
68
|
+
function checkPaths(v, option, commas = false) {
|
|
69
|
+
if (v === void 0) return void 0;
|
|
70
|
+
const list = commas && typeof v === "string" ? v.split(",").map((s) => s.trim()).filter(Boolean) : v;
|
|
71
|
+
if (!Array.isArray(list)) fail(option, "invalid_type", `must be a list of paths like "/api/*" (got ${show(v)})`);
|
|
72
|
+
const out = [];
|
|
73
|
+
for (const p of list) {
|
|
74
|
+
if (typeof p !== "string" || !PATH_PATTERN.test(p)) fail(option, "invalid_value", `has an entry that isn't a path starting with "/": ${show(p)}`);
|
|
75
|
+
out.push(p);
|
|
76
|
+
}
|
|
77
|
+
if (out.length > MAX_PATHS) fail(option, "out_of_range", `can hold at most ${MAX_PATHS} paths (got ${out.length})`);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
function checkCollect(v, option = "collect") {
|
|
81
|
+
if (v === void 0 || v === null) return resolveCollect(void 0);
|
|
82
|
+
if (!isObject(v)) fail(option, "invalid_type", `must be an object (got ${show(v)})`);
|
|
83
|
+
const c = v;
|
|
84
|
+
checkKeys(c, ["pages", "addresses", "behavior", "requests", "skip"], option);
|
|
85
|
+
checkOneOf(c.pages, `${option}.pages`, ["masked", "hashed", "off"]);
|
|
86
|
+
checkOneOf(c.addresses, `${option}.addresses`, ["hashed", "off"]);
|
|
87
|
+
checkBoolean(c.behavior, `${option}.behavior`);
|
|
88
|
+
checkBoolean(c.requests, `${option}.requests`);
|
|
89
|
+
const skip = checkPaths(c.skip, `${option}.skip`, true);
|
|
90
|
+
return resolveCollect({ ...c, ...skip ? { skip } : {} });
|
|
91
|
+
}
|
|
92
|
+
function checkClientIp(v, option = "clientIp") {
|
|
93
|
+
if (v === void 0) return "auto";
|
|
94
|
+
if (typeof v === "function") return v;
|
|
95
|
+
const problem = clientIpModeProblem(v);
|
|
96
|
+
if (problem) fail(option, typeof v === "object" && v !== null ? "invalid_value" : "invalid_type", problem);
|
|
97
|
+
return v;
|
|
98
|
+
}
|
|
99
|
+
var DOMAIN = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
100
|
+
function checkCookieDomain(v, option = "cookieDomain") {
|
|
101
|
+
const s = checkString(v, option);
|
|
102
|
+
if (s === void 0) return void 0;
|
|
103
|
+
const d = s.trim().toLowerCase().replace(/^\./, "");
|
|
104
|
+
if (!DOMAIN.test(d)) fail(option, "invalid_value", `must be a domain like "example.com" (got ${show(s)})`);
|
|
105
|
+
return d;
|
|
106
|
+
}
|
|
107
|
+
function checkCollector(v, option = "collector") {
|
|
108
|
+
const s = checkString(v, option);
|
|
109
|
+
if (s === void 0) return void 0;
|
|
110
|
+
if (!/^https?:\/\/[^/?#\s]+(?:\/[^?#\s]*)?$/i.test(s)) fail(option, "invalid_value", `must be an http(s) URL (got ${show(s)})`);
|
|
111
|
+
return s;
|
|
112
|
+
}
|
|
113
|
+
function checkLogger(v, option = "logger") {
|
|
114
|
+
if (v === void 0 || v === false) return v;
|
|
115
|
+
if (!isObject(v) && typeof v !== "function") fail(option, "invalid_type", `must be an object with warn and error methods, or false (got ${show(v)})`);
|
|
116
|
+
const l = v;
|
|
117
|
+
if (typeof l.warn !== "function" || typeof l.error !== "function") fail(option, "invalid_value", "must have warn and error methods");
|
|
118
|
+
return v;
|
|
119
|
+
}
|
|
120
|
+
var BLOCK_KEYS = [
|
|
121
|
+
"labels",
|
|
122
|
+
"status",
|
|
123
|
+
"minStage",
|
|
124
|
+
"dryRun",
|
|
125
|
+
"allow",
|
|
126
|
+
"allowIf",
|
|
127
|
+
"respond",
|
|
128
|
+
"onBlock",
|
|
129
|
+
"require",
|
|
130
|
+
"requireMaxAgeMs",
|
|
131
|
+
"requireGraceMs",
|
|
132
|
+
"requireGraceRequests",
|
|
133
|
+
"requireGracePages",
|
|
134
|
+
"requireRefreshRequests",
|
|
135
|
+
"requireRefreshMs",
|
|
136
|
+
"pace"
|
|
137
|
+
];
|
|
138
|
+
function checkRate(v, option, base) {
|
|
139
|
+
if (v === void 0) return base;
|
|
140
|
+
if (!isObject(v)) fail(option, "invalid_type", `must be { burst, perSecond } (got ${show(v)})`);
|
|
141
|
+
const r = v;
|
|
142
|
+
checkKeys(r, ["burst", "perSecond"], option);
|
|
143
|
+
const burst = checkNumber(r.burst, `${option}.burst`, 1, 1e5) ?? base.burst;
|
|
144
|
+
const perSecond = checkNumber(r.perSecond, `${option}.perSecond`, 1e-3, 1e4, false) ?? base.perSecond;
|
|
145
|
+
return { burst, perSecond };
|
|
146
|
+
}
|
|
147
|
+
function checkBlock(v, option = "block", runtime = "node") {
|
|
148
|
+
if (v === void 0 || v === false || v === null) return null;
|
|
149
|
+
if (v !== true && !isObject(v)) fail(option, "invalid_type", `must be true, false or an object (got ${show(v)})`);
|
|
150
|
+
const b = v === true ? {} : v;
|
|
151
|
+
checkKeys(b, BLOCK_KEYS, option);
|
|
152
|
+
if (runtime === "fetch") {
|
|
153
|
+
for (const k of ["require", "requireMaxAgeMs", "requireGraceMs", "requireGraceRequests", "requireGracePages", "requireRefreshRequests", "requireRefreshMs"])
|
|
154
|
+
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");
|
|
155
|
+
}
|
|
156
|
+
let labels;
|
|
157
|
+
if (b.labels !== void 0) {
|
|
158
|
+
if (!Array.isArray(b.labels)) fail(`${option}.labels`, "invalid_type", `must be a list of labels (got ${show(b.labels)})`);
|
|
159
|
+
const list = b.labels;
|
|
160
|
+
if (!list.length) fail(`${option}.labels`, "empty_list", "is empty; leave it out to block on any label");
|
|
161
|
+
for (const l of list) checkOneOf(l, `${option}.labels`, LABELS);
|
|
162
|
+
labels = list;
|
|
163
|
+
}
|
|
164
|
+
let dryRun = /* @__PURE__ */ new Set();
|
|
165
|
+
if (b.dryRun === true) dryRun = new Set(BLOCK_REASONS);
|
|
166
|
+
else if (Array.isArray(b.dryRun)) {
|
|
167
|
+
if (!b.dryRun.length) fail(`${option}.dryRun`, "empty_list", "is empty; use false, true, or a list of reasons");
|
|
168
|
+
for (const r of b.dryRun) dryRun.add(checkOneOf(r, `${option}.dryRun`, BLOCK_REASONS));
|
|
169
|
+
} 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)})`);
|
|
170
|
+
const require2 = checkPaths(b.require, `${option}.require`);
|
|
171
|
+
let pace = { ...DEFAULT_PACE };
|
|
172
|
+
if (b.pace === false) pace = null;
|
|
173
|
+
else if (b.pace !== void 0 && b.pace !== true) {
|
|
174
|
+
if (!isObject(b.pace)) fail(`${option}.pace`, "invalid_type", `must be true, false or an object (got ${show(b.pace)})`);
|
|
175
|
+
const p = b.pace;
|
|
176
|
+
checkKeys(p, ["documents", "api", "notFound"], `${option}.pace`);
|
|
177
|
+
pace = {
|
|
178
|
+
documents: checkRate(p.documents, `${option}.pace.documents`, DEFAULT_PACE.documents),
|
|
179
|
+
api: checkRate(p.api, `${option}.pace.api`, DEFAULT_PACE.api),
|
|
180
|
+
notFound: checkRate(p.notFound, `${option}.pace.notFound`, DEFAULT_PACE.notFound)
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
return {
|
|
184
|
+
labels,
|
|
185
|
+
status: checkNumber(b.status, `${option}.status`, 400, 599) ?? 429,
|
|
186
|
+
minStage: checkOneOf(b.minStage, `${option}.minStage`, STAGES) ?? "candidate",
|
|
187
|
+
dryRun,
|
|
188
|
+
allow: checkPaths(b.allow, `${option}.allow`) ?? [],
|
|
189
|
+
require: require2?.length ? require2 : void 0,
|
|
190
|
+
maxAgeMs: checkNumber(b.requireMaxAgeMs, `${option}.requireMaxAgeMs`, 1e3, 6e5) ?? 6e4,
|
|
191
|
+
graceMs: checkNumber(b.requireGraceMs, `${option}.requireGraceMs`, 0, 6e5) ?? 15e3,
|
|
192
|
+
graceRequests: checkNumber(b.requireGraceRequests, `${option}.requireGraceRequests`, 0, 1e5) ?? 30,
|
|
193
|
+
gracePages: checkNumber(b.requireGracePages, `${option}.requireGracePages`, 0, 1e3) ?? 3,
|
|
194
|
+
refreshRequests: checkNumber(b.requireRefreshRequests, `${option}.requireRefreshRequests`, 0, 1e5) ?? 30,
|
|
195
|
+
refreshMs: checkNumber(b.requireRefreshMs, `${option}.requireRefreshMs`, 0, 6e5) ?? 1e4,
|
|
196
|
+
pace,
|
|
197
|
+
allowIf: checkFunction(b.allowIf, `${option}.allowIf`),
|
|
198
|
+
respond: checkFunction(b.respond, `${option}.respond`),
|
|
199
|
+
onBlock: checkFunction(b.onBlock, `${option}.onBlock`)
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
var NODE_OPTION_KEYS = [
|
|
203
|
+
"key",
|
|
204
|
+
"previousKey",
|
|
205
|
+
"collector",
|
|
206
|
+
"inject",
|
|
207
|
+
"block",
|
|
208
|
+
"sourceMaps",
|
|
209
|
+
"ignore",
|
|
210
|
+
"ignoreIf",
|
|
211
|
+
"collect",
|
|
212
|
+
"watchSessionless",
|
|
213
|
+
"clientIp",
|
|
214
|
+
"cookieDomain",
|
|
215
|
+
"debug",
|
|
216
|
+
"logger",
|
|
217
|
+
"timeoutMs",
|
|
218
|
+
"fetch",
|
|
219
|
+
"onError",
|
|
220
|
+
"flushIntervalMs"
|
|
221
|
+
];
|
|
222
|
+
var MOVED_OPTIONS = {
|
|
223
|
+
forward: "use collect: { requests: false } to stop request summaries"
|
|
224
|
+
};
|
|
225
|
+
function checkOptions(options) {
|
|
226
|
+
if (options === void 0 || options === null) options = {};
|
|
227
|
+
if (!isObject(options)) fail("options", "invalid_type", `must be an object (got ${show(options)})`);
|
|
228
|
+
const o = options;
|
|
229
|
+
checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS);
|
|
230
|
+
if (typeof o.ignore === "function") fail("ignore", "invalid_type", "is now a list of paths; use ignoreIf for a function");
|
|
231
|
+
return {
|
|
232
|
+
key: checkString(o.key, "key"),
|
|
233
|
+
previousKey: checkString(o.previousKey, "previousKey"),
|
|
234
|
+
collector: checkCollector(o.collector),
|
|
235
|
+
inject: checkBoolean(o.inject, "inject") ?? true,
|
|
236
|
+
block: checkBlock(o.block),
|
|
237
|
+
sourceMaps: checkOneOf(o.sourceMaps, "sourceMaps", ["deny", "allow"]),
|
|
238
|
+
ignore: checkPaths(o.ignore, "ignore") ?? [],
|
|
239
|
+
ignoreIf: checkFunction(o.ignoreIf, "ignoreIf"),
|
|
240
|
+
collect: checkCollect(o.collect),
|
|
241
|
+
watchSessionless: checkBoolean(o.watchSessionless, "watchSessionless") ?? true,
|
|
242
|
+
clientIp: checkClientIp(o.clientIp),
|
|
243
|
+
cookieDomain: checkCookieDomain(o.cookieDomain),
|
|
244
|
+
debug: checkBoolean(o.debug, "debug"),
|
|
245
|
+
logger: checkLogger(o.logger),
|
|
246
|
+
timeoutMs: checkNumber(o.timeoutMs, "timeoutMs", 100, 12e4) ?? 1e4,
|
|
247
|
+
fetch: checkFunction(o.fetch, "fetch"),
|
|
248
|
+
onError: checkFunction(o.onError, "onError"),
|
|
249
|
+
flushIntervalMs: checkNumber(o.flushIntervalMs, "flushIntervalMs", 10, 36e5) ?? 2e3
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// src/health.ts
|
|
254
|
+
var seenBy = /* @__PURE__ */ new WeakMap();
|
|
255
|
+
function makeLog(logger, debugging) {
|
|
256
|
+
const out = logger === false ? null : logger ?? console;
|
|
257
|
+
let seen = out ? seenBy.get(out) : void 0;
|
|
258
|
+
if (out && !seen) {
|
|
259
|
+
seen = /* @__PURE__ */ new Set();
|
|
260
|
+
seenBy.set(out, seen);
|
|
261
|
+
}
|
|
262
|
+
const say = (level, message) => {
|
|
263
|
+
if (!out) return;
|
|
264
|
+
const fn = level === "debug" ? out.debug ?? out.info ?? out.warn : level === "info" ? out.info ?? out.warn : out[level];
|
|
265
|
+
try {
|
|
266
|
+
fn.call(out, `[reguard] ${message}`);
|
|
267
|
+
} catch {
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
return {
|
|
271
|
+
warn: (m) => say("warn", m),
|
|
272
|
+
error: (m) => say("error", m),
|
|
273
|
+
info: (m) => say("info", m),
|
|
274
|
+
debug: (m) => {
|
|
275
|
+
if (debugging) say("debug", m);
|
|
276
|
+
},
|
|
277
|
+
once: (kind, level, m) => {
|
|
278
|
+
if (!seen || seen.has(kind)) return;
|
|
279
|
+
seen.add(kind);
|
|
280
|
+
say(level, m);
|
|
281
|
+
},
|
|
282
|
+
debugging
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
var PAUSE_MS = 60 * 6e4;
|
|
286
|
+
var REJECTED_RETRY_MS = 5 * 6e4;
|
|
287
|
+
var Health = class {
|
|
288
|
+
constructor(log, now = Date.now) {
|
|
289
|
+
this.log = log;
|
|
290
|
+
this.now = now;
|
|
291
|
+
this.since = now();
|
|
292
|
+
}
|
|
293
|
+
state = "ok";
|
|
294
|
+
since;
|
|
295
|
+
lastError;
|
|
296
|
+
pausedUntil = 0;
|
|
297
|
+
retryAt = 0;
|
|
298
|
+
move(state, error) {
|
|
299
|
+
if (state !== this.state) this.since = this.now();
|
|
300
|
+
this.state = state;
|
|
301
|
+
this.lastError = error;
|
|
302
|
+
}
|
|
303
|
+
ok() {
|
|
304
|
+
if (this.state !== "ok") this.log.info("reaching Reguard again: summaries and require routes are back to normal");
|
|
305
|
+
this.move("ok");
|
|
306
|
+
}
|
|
307
|
+
failing(error) {
|
|
308
|
+
if (this.state === "ok") this.log.warn(`can't reach Reguard (${error}): summaries are dropped and require routes stay open until it answers`);
|
|
309
|
+
this.move("failing", error);
|
|
310
|
+
}
|
|
311
|
+
rejected(status) {
|
|
312
|
+
if (this.state !== "rejected")
|
|
313
|
+
this.log.error(
|
|
314
|
+
`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.`
|
|
315
|
+
);
|
|
316
|
+
this.retryAt = this.now() + REJECTED_RETRY_MS;
|
|
317
|
+
this.move("rejected", `HTTP ${status}`);
|
|
318
|
+
}
|
|
319
|
+
paused() {
|
|
320
|
+
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.");
|
|
321
|
+
this.pausedUntil = this.now() + PAUSE_MS;
|
|
322
|
+
this.move("paused", "HTTP 429");
|
|
323
|
+
}
|
|
324
|
+
/** Whether a batch may be sent now (not while paused or waiting after a rejection). */
|
|
325
|
+
canSend() {
|
|
326
|
+
const now = this.now();
|
|
327
|
+
return now >= this.pausedUntil && now >= this.retryAt;
|
|
328
|
+
}
|
|
329
|
+
/** `require` routes are not enforced while this is true. */
|
|
330
|
+
get failOpen() {
|
|
331
|
+
return this.state !== "ok";
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
export {
|
|
336
|
+
ReguardConfigError,
|
|
337
|
+
BLOCK_REASONS,
|
|
338
|
+
checkBoolean,
|
|
339
|
+
checkFunction,
|
|
340
|
+
checkNumber,
|
|
341
|
+
checkCollect,
|
|
342
|
+
checkClientIp,
|
|
343
|
+
checkCookieDomain,
|
|
344
|
+
checkCollector,
|
|
345
|
+
checkLogger,
|
|
346
|
+
checkBlock,
|
|
347
|
+
checkOptions,
|
|
348
|
+
makeLog,
|
|
349
|
+
Health
|
|
350
|
+
};
|