reguard 0.9.0 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/chunks/{chunk-CGXTVKRB.js → chunk-2N762ZXU.js} +152 -37
- package/dist/chunks/{chunk-W4FDH5AD.js → chunk-4RD66ACT.js} +8 -6
- package/dist/chunks/{chunk-PRPLLMXA.js → chunk-GOT54CF4.js} +39 -34
- package/dist/chunks/{chunk-CUIFGML3.js → chunk-RTCPK4MF.js} +82 -36
- package/dist/cjs/fastify.cjs +234 -85
- package/dist/cjs/fetch.cjs +189 -73
- package/dist/cjs/index.cjs +233 -76
- package/dist/cjs/next.cjs +210 -91
- package/dist/cjs/testing.cjs +0 -104
- package/dist/fastify.js +4 -12
- package/dist/fetch.js +3 -3
- package/dist/index.js +3 -3
- package/dist/next.js +24 -22
- package/dist/testing.js +1 -1
- package/dist/types/node/src/fastify.d.ts +15 -7
- package/dist/types/node/src/fetch.d.ts +6 -2
- package/dist/types/node/src/next.d.ts +38 -17
- package/dist/types/shared/src/address.d.ts +25 -6
- package/dist/types/shared/src/collect.d.ts +7 -1
- package/dist/types/shared/src/index.d.ts +5 -0
- package/dist/types/shared/src/paths.d.ts +6 -2
- package/dist/types/shared/src/tools.d.ts +10 -0
- package/dist/types-cjs/node/src/fastify.d.cts +15 -7
- package/dist/types-cjs/node/src/fetch.d.cts +6 -2
- package/dist/types-cjs/node/src/next.d.cts +38 -17
- package/dist/types-cjs/shared/src/address.d.cts +25 -6
- package/dist/types-cjs/shared/src/collect.d.cts +7 -1
- package/dist/types-cjs/shared/src/index.d.cts +5 -0
- package/dist/types-cjs/shared/src/paths.d.cts +6 -2
- package/dist/types-cjs/shared/src/tools.d.cts +10 -0
- package/package.json +3 -2
|
@@ -6,12 +6,13 @@ import {
|
|
|
6
6
|
checkOptions,
|
|
7
7
|
makeLog,
|
|
8
8
|
reguardApi
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-4RD66ACT.js";
|
|
10
10
|
import {
|
|
11
11
|
Allowance,
|
|
12
12
|
BENIGN_TOOL_FAMILIES,
|
|
13
13
|
RETRY_AFTER,
|
|
14
14
|
SESSION_COOKIE,
|
|
15
|
+
addressKey,
|
|
15
16
|
canonicalPath,
|
|
16
17
|
collectReport,
|
|
17
18
|
collectorBase,
|
|
@@ -35,7 +36,9 @@ import {
|
|
|
35
36
|
normalizeIp,
|
|
36
37
|
parseSiteKey,
|
|
37
38
|
pathTraits,
|
|
39
|
+
presentsAsBrowser,
|
|
38
40
|
privateUrl,
|
|
41
|
+
protectionMatcher,
|
|
39
42
|
pushedVerdict,
|
|
40
43
|
readVerdictFrom,
|
|
41
44
|
renderScriptTag,
|
|
@@ -47,11 +50,12 @@ import {
|
|
|
47
50
|
verdictAgeMs,
|
|
48
51
|
wantsPage,
|
|
49
52
|
watchworthy
|
|
50
|
-
} from "./chunk-
|
|
53
|
+
} from "./chunk-2N762ZXU.js";
|
|
51
54
|
|
|
52
55
|
// src/index.ts
|
|
53
56
|
import { createHash, createHmac } from "node:crypto";
|
|
54
57
|
import { Readable } from "node:stream";
|
|
58
|
+
import { brotliCompressSync, constants as zlibConstants, gzipSync } from "node:zlib";
|
|
55
59
|
import { pipeline } from "node:stream/promises";
|
|
56
60
|
var PREFIX = "/_s";
|
|
57
61
|
var NOT_FORWARDED = /* @__PURE__ */ new Set([
|
|
@@ -74,7 +78,31 @@ var STRIP_FROM_RESPONSE = /* @__PURE__ */ new Set(["content-encoding", "content-
|
|
|
74
78
|
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)/;
|
|
75
79
|
var SCAN_LIMIT = 64 * 1024;
|
|
76
80
|
function visitorHash(secret, address) {
|
|
77
|
-
return createHmac("sha256", secret).update(`visitor:${address}`).digest("base64url").slice(0, 22);
|
|
81
|
+
return createHmac("sha256", secret).update(`visitor:${addressKey(address) || address}`).digest("base64url").slice(0, 22);
|
|
82
|
+
}
|
|
83
|
+
function browserHeaders(h) {
|
|
84
|
+
const get = (n) => header(h, n);
|
|
85
|
+
return { userAgent: get("user-agent") ?? "", acceptLanguage: get("accept-language"), accept: get("accept"), secFetchMode: get("sec-fetch-mode"), secFetchDest: get("sec-fetch-dest"), secChUa: get("sec-ch-ua") };
|
|
86
|
+
}
|
|
87
|
+
var compressedScripts = /* @__PURE__ */ new Map();
|
|
88
|
+
function compressedScript(etag, body) {
|
|
89
|
+
let c = compressedScripts.get(etag);
|
|
90
|
+
if (!c) {
|
|
91
|
+
c = { br: brotliCompressSync(body, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 10, [zlibConstants.BROTLI_PARAM_MODE]: zlibConstants.BROTLI_MODE_TEXT } }), gzip: gzipSync(body, { level: 9 }) };
|
|
92
|
+
if (compressedScripts.size >= 8) compressedScripts.clear();
|
|
93
|
+
compressedScripts.set(etag, c);
|
|
94
|
+
}
|
|
95
|
+
return c;
|
|
96
|
+
}
|
|
97
|
+
async function readBody(req, limit = 1048576) {
|
|
98
|
+
const chunks = [];
|
|
99
|
+
let size = 0;
|
|
100
|
+
for await (const c of req) {
|
|
101
|
+
size += c.length;
|
|
102
|
+
if (size > limit) throw new Error("request body over 1 MiB");
|
|
103
|
+
chunks.push(c);
|
|
104
|
+
}
|
|
105
|
+
return Buffer.concat(chunks);
|
|
78
106
|
}
|
|
79
107
|
function keyFingerprint(secret) {
|
|
80
108
|
return createHash("sha256").update(`reguard-key:${secret}`).digest("base64url").slice(0, 8);
|
|
@@ -165,14 +193,15 @@ function reguard(options = {}) {
|
|
|
165
193
|
!key ? "REGUARD_KEY is not set: passing every request through (no script, no verdicts, no blocking)." : parsed ? "this key has no site id (a key from before v0.4): use the rgk.\u2026 key from your dashboard. Passing every request through." : `REGUARD_KEY isn't a Reguard key (expected rgk.<site>.v<n>.<secret>; got ${keyShape(key)}). Passing every request through.`
|
|
166
194
|
);
|
|
167
195
|
const passthrough = ((req, _res, next) => {
|
|
168
|
-
req.reguard
|
|
169
|
-
req.reguardDecision
|
|
170
|
-
req.reDetect
|
|
196
|
+
req.reguard ??= null;
|
|
197
|
+
req.reguardDecision ??= null;
|
|
198
|
+
req.reDetect ??= null;
|
|
171
199
|
next();
|
|
172
200
|
});
|
|
173
201
|
Object.defineProperty(passthrough, "site", { value: void 0 });
|
|
174
202
|
passthrough.scriptTag = () => "";
|
|
175
|
-
|
|
203
|
+
const since = Date.now();
|
|
204
|
+
passthrough.status = () => ({ enabled: false, collector: "off", since, failOpen: false, queued: 0, blocking: "off" });
|
|
176
205
|
passthrough.flush = async () => {
|
|
177
206
|
};
|
|
178
207
|
passthrough.close = async () => {
|
|
@@ -203,9 +232,9 @@ function reguard(options = {}) {
|
|
|
203
232
|
const platform = detectPlatform(typeof process !== "undefined" ? process.env : void 0);
|
|
204
233
|
const blockCfg = o.block;
|
|
205
234
|
const allDry = !blockCfg || BLOCK_REASONS.every((r) => blockCfg.dryRun.has(r));
|
|
206
|
-
const skipped =
|
|
207
|
-
const ignored = o.ignore.length ?
|
|
208
|
-
const required = blockCfg?.require ?
|
|
235
|
+
const skipped = protectionMatcher(o.collect.skip);
|
|
236
|
+
const ignored = o.ignore.length ? protectionMatcher(o.ignore) : void 0;
|
|
237
|
+
const required = blockCfg?.require ? protectionMatcher(blockCfg.require) : void 0;
|
|
209
238
|
const allowList = blockCfg?.allow.length ? skipMatcher(blockCfg.allow) : void 0;
|
|
210
239
|
const denyMaps = (o.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
|
|
211
240
|
const tagSettings = { site, collect: o.collect, fresh: freshSeconds(blockCfg), cookieDomain: o.cookieDomain };
|
|
@@ -225,7 +254,9 @@ function reguard(options = {}) {
|
|
|
225
254
|
const ip = normalizeIp(custom ?? void 0);
|
|
226
255
|
a = ip ? { address: ip, internal: !isPublicIp(ip), via: "custom" } : resolveClientAddress({ peer, header: get }, "socket");
|
|
227
256
|
} else {
|
|
228
|
-
const
|
|
257
|
+
const trust = req.app?.get?.("trust proxy");
|
|
258
|
+
if (trust === true) log.once("trust-proxy-true", "warn", `Express's trust proxy is true, so req.ip is whatever the client sends: Reguard reads the visitor's address itself. Set trust proxy to the number of proxies in front of you (e.g. app.set("trust proxy", 1)).`);
|
|
259
|
+
const framework = trust && trust !== true ? req.ip : void 0;
|
|
229
260
|
a = resolveClientAddress({ peer, header: get, framework }, o.clientIp, platform);
|
|
230
261
|
}
|
|
231
262
|
ADDRESS.set(req, a);
|
|
@@ -304,15 +335,15 @@ function reguard(options = {}) {
|
|
|
304
335
|
const paceApi = pace ? rate(pace.api) : void 0;
|
|
305
336
|
const paceMisses = pace ? rate(pace.notFound) : void 0;
|
|
306
337
|
const cooling = /* @__PURE__ */ new Map();
|
|
307
|
-
const
|
|
338
|
+
const addressKey2 = (req) => `v:${visitorHash(parsed.secret, resolve(req).address)}`;
|
|
308
339
|
const paceOf = (req, res, p) => {
|
|
309
340
|
if (!pace || resolve(req).internal) return void 0;
|
|
310
341
|
const get = (n) => header(req.headers, n);
|
|
311
342
|
const now = Date.now();
|
|
312
|
-
const browser =
|
|
343
|
+
const browser = presentsAsBrowser(browserHeaders(req.headers));
|
|
313
344
|
const tool = browser ? void 0 : toolOf(get("user-agent"));
|
|
314
345
|
if (!browser && !(tool && BENIGN_TOOL_FAMILIES.has(tool.family))) {
|
|
315
|
-
const key2 =
|
|
346
|
+
const key2 = addressKey2(req);
|
|
316
347
|
res.once("finish", () => {
|
|
317
348
|
const st = res.statusCode;
|
|
318
349
|
if ((st === 404 || st === 405 || st === 410) && !paceMisses.take(key2)) {
|
|
@@ -332,7 +363,7 @@ function reguard(options = {}) {
|
|
|
332
363
|
}
|
|
333
364
|
if (required && matchesEither(required, p)) {
|
|
334
365
|
const sid = cookieValue(get("cookie"), SESSION_COOKIE);
|
|
335
|
-
if (!paceApi.take(sid ? `s:${sid}` :
|
|
366
|
+
if (!paceApi.take(sid ? `s:${sid}` : addressKey2(req), now)) return "api";
|
|
336
367
|
}
|
|
337
368
|
return void 0;
|
|
338
369
|
};
|
|
@@ -342,8 +373,9 @@ function reguard(options = {}) {
|
|
|
342
373
|
const dryCounts = /* @__PURE__ */ new Map();
|
|
343
374
|
const dryTimer = setInterval(() => {
|
|
344
375
|
if (!dryCounts.size) return;
|
|
345
|
-
const parts = [...dryCounts].map(([r,
|
|
346
|
-
|
|
376
|
+
const parts = [...dryCounts].map(([r, n2]) => `${r} ${n2}`).join(", ");
|
|
377
|
+
const n = [...dryCounts.values()].reduce((a, b) => a + b, 0);
|
|
378
|
+
log.info(`dry run: would have answered ${n} request${n === 1 ? "" : "s"} in the last minute (${parts})`);
|
|
347
379
|
dryCounts.clear();
|
|
348
380
|
}, 6e4);
|
|
349
381
|
dryTimer.unref?.();
|
|
@@ -378,9 +410,11 @@ function reguard(options = {}) {
|
|
|
378
410
|
const answer = async (req, res, d) => {
|
|
379
411
|
const respond = blockCfg.respond;
|
|
380
412
|
if (respond) {
|
|
413
|
+
let threw = false;
|
|
381
414
|
try {
|
|
382
415
|
await respond(req, res, d);
|
|
383
416
|
} catch (e) {
|
|
417
|
+
threw = true;
|
|
384
418
|
log.once("respond-threw", "error", `block.respond threw (${errorText(e)}): sent the default answer instead`);
|
|
385
419
|
}
|
|
386
420
|
if (res.writableEnded) return;
|
|
@@ -388,7 +422,7 @@ function reguard(options = {}) {
|
|
|
388
422
|
res.end();
|
|
389
423
|
return;
|
|
390
424
|
}
|
|
391
|
-
log.once("respond-silent", "warn", "block.respond didn't answer the request: sent the default answer");
|
|
425
|
+
if (!threw) log.once("respond-silent", "warn", "block.respond didn't answer the request: sent the default answer");
|
|
392
426
|
}
|
|
393
427
|
defaultBlockResponse(req, res, d);
|
|
394
428
|
};
|
|
@@ -401,10 +435,8 @@ function reguard(options = {}) {
|
|
|
401
435
|
const init = { method: req.method, headers, redirect: "manual", signal: AbortSignal.timeout(o.timeoutMs) };
|
|
402
436
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
403
437
|
const consumed = req.readableEnded || req._body === true;
|
|
404
|
-
if (!consumed)
|
|
405
|
-
|
|
406
|
-
init.duplex = "half";
|
|
407
|
-
} else if (req.body !== void 0) {
|
|
438
|
+
if (!consumed) init.body = new Uint8Array(await readBody(req));
|
|
439
|
+
else if (req.body !== void 0) {
|
|
408
440
|
const b = req.body;
|
|
409
441
|
init.body = Buffer.isBuffer(b) ? new Uint8Array(b) : typeof b === "string" ? b : JSON.stringify(b);
|
|
410
442
|
}
|
|
@@ -420,6 +452,16 @@ function reguard(options = {}) {
|
|
|
420
452
|
});
|
|
421
453
|
const cookies = r.headers.getSetCookie?.() ?? [];
|
|
422
454
|
if (cookies.length) res.setHeader("set-cookie", cookies);
|
|
455
|
+
const etag = r.headers.get("etag");
|
|
456
|
+
const accepts = header(req.headers, "accept-encoding") ?? "";
|
|
457
|
+
if (etag && r.ok && req.method === "GET" && /javascript/.test(r.headers.get("content-type") ?? "") && /\b(br|gzip)\b/.test(accepts)) {
|
|
458
|
+
const c = compressedScript(etag, Buffer.from(await r.arrayBuffer()));
|
|
459
|
+
const encoding = /\bbr\b/.test(accepts) ? "br" : "gzip";
|
|
460
|
+
res.setHeader("content-encoding", encoding);
|
|
461
|
+
res.setHeader("vary", "Accept-Encoding");
|
|
462
|
+
res.end(c[encoding]);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
423
465
|
if (r.body && req.method !== "HEAD") await pipeline(Readable.fromWeb(r.body), res);
|
|
424
466
|
else res.end();
|
|
425
467
|
} catch (e) {
|
|
@@ -706,7 +748,7 @@ function createReDetect(opts, wiring = {}) {
|
|
|
706
748
|
const timeoutMs = wiring.timeoutMs ?? 1e4;
|
|
707
749
|
const addressFor = (req) => wiring.address?.(req) ?? addressOf(req);
|
|
708
750
|
const collect = resolveCollect(opts.collect, (m) => log.once(`collect:${m}`, "warn", m));
|
|
709
|
-
const skipped =
|
|
751
|
+
const skipped = protectionMatcher(collect.skip);
|
|
710
752
|
const forward = collect.requests;
|
|
711
753
|
const siteTag = siteTagOf(opts.site, secret);
|
|
712
754
|
const maxQueue = opts.maxQueue ?? 5e3;
|
|
@@ -731,7 +773,7 @@ function createReDetect(opts, wiring = {}) {
|
|
|
731
773
|
if (!pushed.size) return null;
|
|
732
774
|
const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
|
|
733
775
|
const a = addressFor(req);
|
|
734
|
-
const address = collect.addresses !== "off" && !verified && !a.internal ? a.address : "";
|
|
776
|
+
const address = collect.addresses !== "off" && !verified && !a.internal && !presentsAsBrowser(browserHeaders(req.headers)) ? a.address : "";
|
|
735
777
|
const now = Date.now();
|
|
736
778
|
const claims = [];
|
|
737
779
|
let vid;
|
|
@@ -791,6 +833,7 @@ function createReDetect(opts, wiring = {}) {
|
|
|
791
833
|
const flushSoon = () => {
|
|
792
834
|
if (queue.length && !inflight) inflight = flush().finally(() => inflight = void 0);
|
|
793
835
|
};
|
|
836
|
+
let lastUrgent = 0;
|
|
794
837
|
const timer = setInterval(flushSoon, opts.flushIntervalMs ?? 2e3);
|
|
795
838
|
timer.unref?.();
|
|
796
839
|
const readVerdict = (cookieHeader) => readVerdictFrom(secret, opts.site, cookieHeader);
|
|
@@ -802,19 +845,19 @@ function createReDetect(opts, wiring = {}) {
|
|
|
802
845
|
const secure = secureRequest(req);
|
|
803
846
|
const decision = wiring.decided?.(req);
|
|
804
847
|
const pace = PACED.get(req);
|
|
848
|
+
const tool = watchworthy({
|
|
849
|
+
userAgent: header(h, "user-agent") ?? "",
|
|
850
|
+
acceptLanguage: header(h, "accept-language"),
|
|
851
|
+
accept: header(h, "accept"),
|
|
852
|
+
secFetchMode: header(h, "sec-fetch-mode"),
|
|
853
|
+
secChUa: header(h, "sec-ch-ua"),
|
|
854
|
+
secure,
|
|
855
|
+
path: url.split("?")[0] ?? url,
|
|
856
|
+
status: res.statusCode
|
|
857
|
+
});
|
|
805
858
|
if (!sid && !opts.includeSessionless && !decision) {
|
|
806
859
|
if (opts.watchSessionless === false || collect.addresses === "off") return;
|
|
807
|
-
|
|
808
|
-
userAgent: header(h, "user-agent") ?? "",
|
|
809
|
-
acceptLanguage: header(h, "accept-language"),
|
|
810
|
-
accept: header(h, "accept"),
|
|
811
|
-
secFetchMode: header(h, "sec-fetch-mode"),
|
|
812
|
-
secChUa: header(h, "sec-ch-ua"),
|
|
813
|
-
secure,
|
|
814
|
-
path: url.split("?")[0] ?? url,
|
|
815
|
-
status: res.statusCode
|
|
816
|
-
});
|
|
817
|
-
if (!watch) return;
|
|
860
|
+
if (!tool) return;
|
|
818
861
|
}
|
|
819
862
|
const a = addressFor(req);
|
|
820
863
|
const visitor = !sid && a.address && collect.addresses !== "off" ? visitorHash(secret, a.address) : void 0;
|
|
@@ -875,7 +918,10 @@ function createReDetect(opts, wiring = {}) {
|
|
|
875
918
|
...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
|
|
876
919
|
...a.internal ? { internal: true } : {}
|
|
877
920
|
});
|
|
878
|
-
if (decision
|
|
921
|
+
if (decision || tool && Date.now() - lastUrgent >= 500) {
|
|
922
|
+
lastUrgent = Date.now();
|
|
923
|
+
flushSoon();
|
|
924
|
+
}
|
|
879
925
|
} catch (e) {
|
|
880
926
|
onError(e);
|
|
881
927
|
}
|