reguard 0.9.0 → 0.11.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/README.md +2 -2
- package/dist/chunks/{chunk-CGXTVKRB.js → chunk-2N762ZXU.js} +152 -37
- package/dist/chunks/{chunk-CUIFGML3.js → chunk-EV6D7UZF.js} +82 -36
- package/dist/chunks/{chunk-W4FDH5AD.js → chunk-VZKXPEWQ.js} +9 -7
- package/dist/chunks/{chunk-PRPLLMXA.js → chunk-XCSVBLHF.js} +39 -34
- package/dist/cjs/fastify.cjs +235 -86
- package/dist/cjs/fetch.cjs +190 -74
- package/dist/cjs/index.cjs +234 -77
- package/dist/cjs/next.cjs +211 -92
- 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 +17 -5
- 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 +17 -5
- 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
package/README.md
CHANGED
|
@@ -76,8 +76,8 @@ Dry-run decisions are on `req.reguardDecision` and in the dashboard as "would ha
|
|
|
76
76
|
|
|
77
77
|
- **Fastify:** `import reguard from "reguard/fastify"` then `await app.register(reguard, { block: true })`;
|
|
78
78
|
reads `request.ip` when `trustProxy` is set, and sets `request.reguard`.
|
|
79
|
-
- **Next.js:** `
|
|
80
|
-
|
|
79
|
+
- **Next.js:** `reguardMiddleware({ block: true })` in `middleware.ts` (or `proxy.ts`), which also
|
|
80
|
+
serves `/_s/*`, and `<Script {...reguardScriptProps()} />`, from `reguard/next`.
|
|
81
81
|
- **Hono, Remix, SvelteKit, Astro, Bun, Deno, Workers:** `reguardFetch()` from `reguard/fetch`, then
|
|
82
82
|
`export default { fetch: rg.wrap(app.fetch) }`.
|
|
83
83
|
|
|
@@ -268,6 +268,13 @@ function browserIncoherence(h) {
|
|
|
268
268
|
}
|
|
269
269
|
return reasons;
|
|
270
270
|
}
|
|
271
|
+
function presentsAsBrowser(h) {
|
|
272
|
+
const ua = h.userAgent ?? "";
|
|
273
|
+
if (!/^Mozilla\/5\.0 \(/.test(ua) || !h.secFetchDest) return false;
|
|
274
|
+
const tool = toolOf(ua);
|
|
275
|
+
if (tool && tool.family !== "headless_browser") return false;
|
|
276
|
+
return browserIncoherence(h).length === 0;
|
|
277
|
+
}
|
|
271
278
|
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;
|
|
272
279
|
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;
|
|
273
280
|
var BROWSER_AUTOMATIC = /^\/(?:favicon\.ico|apple-touch-icon[\w.-]*\.png|browserconfig\.xml|site\.webmanifest|manifest\.json|\.well-known\/appspecific\/)/i;
|
|
@@ -351,18 +358,21 @@ function resolveCollect(input, warn = () => {
|
|
|
351
358
|
}
|
|
352
359
|
return out;
|
|
353
360
|
}
|
|
354
|
-
function skipMatcher(patterns) {
|
|
361
|
+
function skipMatcher(patterns, ignoreCase = false) {
|
|
355
362
|
if (!patterns.length) return () => false;
|
|
356
363
|
const res = patterns.map((p) => {
|
|
357
364
|
const tail = p.endsWith("/*");
|
|
358
365
|
const body = (tail ? p.slice(0, -2) : p).split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
359
|
-
return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}
|
|
366
|
+
return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`, ignoreCase ? "i" : "");
|
|
360
367
|
});
|
|
361
368
|
return (path) => {
|
|
362
369
|
const p = path.split(/[?#]/)[0] ?? path;
|
|
363
370
|
return res.some((re) => re.test(p));
|
|
364
371
|
};
|
|
365
372
|
}
|
|
373
|
+
function protectionMatcher(patterns) {
|
|
374
|
+
return skipMatcher(patterns, true);
|
|
375
|
+
}
|
|
366
376
|
function collectAttributes(c) {
|
|
367
377
|
const a = {};
|
|
368
378
|
if (c.pages !== DEFAULT_COLLECT.pages) a["data-pages"] = c.pages;
|
|
@@ -445,6 +455,98 @@ var CLOUDFLARE_RANGES = [
|
|
|
445
455
|
"2a06:98c0::/29",
|
|
446
456
|
"2c0f:f248::/32"
|
|
447
457
|
];
|
|
458
|
+
var CLOUDFRONT_RANGES = [
|
|
459
|
+
"13.124.199.0/24",
|
|
460
|
+
"130.176.0.0/18",
|
|
461
|
+
"130.176.128.0/21",
|
|
462
|
+
"130.176.136.0/23",
|
|
463
|
+
"130.176.140.0/22",
|
|
464
|
+
"130.176.144.0/20",
|
|
465
|
+
"130.176.160.0/19",
|
|
466
|
+
"130.176.192.0/19",
|
|
467
|
+
"130.176.64.0/21",
|
|
468
|
+
"130.176.72.0/22",
|
|
469
|
+
"130.176.76.0/24",
|
|
470
|
+
"130.176.78.0/23",
|
|
471
|
+
"130.176.80.0/22",
|
|
472
|
+
"130.176.86.0/23",
|
|
473
|
+
"130.176.88.0/21",
|
|
474
|
+
"130.176.96.0/19",
|
|
475
|
+
"15.158.0.0/16",
|
|
476
|
+
"18.68.0.0/16",
|
|
477
|
+
"204.246.166.0/24",
|
|
478
|
+
"205.251.218.0/24",
|
|
479
|
+
"24.110.128.0/17",
|
|
480
|
+
"3.172.0.0/18",
|
|
481
|
+
"3.172.64.0/18",
|
|
482
|
+
"3.29.57.0/26",
|
|
483
|
+
"51.72.40.128/28",
|
|
484
|
+
"51.72.40.144/28",
|
|
485
|
+
"51.72.96.0/23",
|
|
486
|
+
"51.74.20.0/24",
|
|
487
|
+
"51.74.21.0/24",
|
|
488
|
+
"51.74.22.0/24",
|
|
489
|
+
"52.46.0.0/18",
|
|
490
|
+
"52.82.128.0/23",
|
|
491
|
+
"52.82.134.0/23",
|
|
492
|
+
"54.182.128.0/20",
|
|
493
|
+
"54.182.144.0/21",
|
|
494
|
+
"54.182.154.0/23",
|
|
495
|
+
"54.182.156.0/22",
|
|
496
|
+
"54.182.160.0/21",
|
|
497
|
+
"54.182.172.0/22",
|
|
498
|
+
"54.182.176.0/21",
|
|
499
|
+
"54.182.184.0/22",
|
|
500
|
+
"54.182.188.0/23",
|
|
501
|
+
"54.182.224.0/21",
|
|
502
|
+
"54.182.240.0/21",
|
|
503
|
+
"54.182.248.0/22",
|
|
504
|
+
"54.239.134.0/23",
|
|
505
|
+
"54.239.170.0/23",
|
|
506
|
+
"54.239.204.0/22",
|
|
507
|
+
"54.239.208.0/21",
|
|
508
|
+
"64.252.128.0/18",
|
|
509
|
+
"64.252.64.0/18",
|
|
510
|
+
"70.132.0.0/18",
|
|
511
|
+
"2001:3fc6:4::/48",
|
|
512
|
+
"2001:3fc6:5::/48",
|
|
513
|
+
"2406:da10:847f:a100::/56",
|
|
514
|
+
"2406:da11:438:2300::/56",
|
|
515
|
+
"2406:da12:4b:c200::/56",
|
|
516
|
+
"2406:da12:8b2e:9c00::/56",
|
|
517
|
+
"2406:da14:17bd:2f00::/56",
|
|
518
|
+
"2406:da14:80bb:ea00::/56",
|
|
519
|
+
"2406:da16:c01:c200::/56",
|
|
520
|
+
"2406:da18:9fa:1b00::/56",
|
|
521
|
+
"2406:da19:e19:4a00::/56",
|
|
522
|
+
"2406:da1a:6df:6c00::/56",
|
|
523
|
+
"2406:da1b:e7c:ad00::/56",
|
|
524
|
+
"2406:da1c:787:2b00::/56",
|
|
525
|
+
"2406:da1c:8d8c:4600::/56",
|
|
526
|
+
"2406:da1e:705:1600::/56",
|
|
527
|
+
"2406:da1f:396:9100::/56",
|
|
528
|
+
"2600:1f11:e79:a800::/56",
|
|
529
|
+
"2600:1f13:417:4d00::/56",
|
|
530
|
+
"2600:1f16:1923:3000::/56",
|
|
531
|
+
"2600:1f17:4356:f100::/56",
|
|
532
|
+
"2600:1f18:7530:7200::/56",
|
|
533
|
+
"2600:1f1a:4568:b500::/56",
|
|
534
|
+
"2600:1f1c:da:600::/56",
|
|
535
|
+
"2600:1f1e:a7:2300::/56",
|
|
536
|
+
"2600:9000:1000::/36",
|
|
537
|
+
"2600:9000:5200::/40",
|
|
538
|
+
"2600:9000:6000::/36",
|
|
539
|
+
"2a05:d011:531:1800::/56",
|
|
540
|
+
"2a05:d012:581:b400::/56",
|
|
541
|
+
"2a05:d014:1362:b000::/56",
|
|
542
|
+
"2a05:d016:9ed:de00::/56",
|
|
543
|
+
"2a05:d018:1a3a:2d00::/56",
|
|
544
|
+
"2a05:d019:80b:e300::/56",
|
|
545
|
+
"2a05:d01a:8a9:be00::/56",
|
|
546
|
+
"2a05:d01c:343:c300::/56",
|
|
547
|
+
"2a05:d025:e59:fb00::/56"
|
|
548
|
+
];
|
|
549
|
+
var PORT_SUFFIXED_HEADERS = ["cloudfront-viewer-address"];
|
|
448
550
|
var NON_PUBLIC_RANGES = [
|
|
449
551
|
"0.0.0.0/8",
|
|
450
552
|
"10.0.0.0/8",
|
|
@@ -574,63 +676,73 @@ function inCidr(c, b) {
|
|
|
574
676
|
return true;
|
|
575
677
|
}
|
|
576
678
|
var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
|
|
577
|
-
var
|
|
578
|
-
var
|
|
579
|
-
function
|
|
580
|
-
const
|
|
581
|
-
if (!
|
|
582
|
-
|
|
583
|
-
|
|
679
|
+
var compiled;
|
|
680
|
+
var tables = () => compiled ??= { nonPublic: compile(NON_PUBLIC_RANGES), cloudflare: compile(CLOUDFLARE_RANGES), cloudfront: compile(CLOUDFRONT_RANGES) };
|
|
681
|
+
function addressKey(address) {
|
|
682
|
+
const ip = normalizeIp(address);
|
|
683
|
+
if (!ip) return "";
|
|
684
|
+
if (!ip.includes(":")) return ip;
|
|
685
|
+
const b = parseIp(ip);
|
|
686
|
+
const prefix = new Uint8Array(16);
|
|
687
|
+
prefix.set(b.subarray(0, 8));
|
|
688
|
+
return `${formatIp(prefix)}/64`;
|
|
584
689
|
}
|
|
585
690
|
function isPublicIp(address) {
|
|
586
691
|
const b = parseIp(address);
|
|
587
|
-
return !!b && !
|
|
692
|
+
return !!b && !tables().nonPublic.some((c) => inCidr(c, b));
|
|
588
693
|
}
|
|
589
|
-
function
|
|
590
|
-
|
|
591
|
-
const entries = xff.split(",").map((s) => s.trim()).filter(Boolean).slice(-MAX_FORWARDED);
|
|
592
|
-
return [...entries, req.peer];
|
|
694
|
+
function forwardedOf(req) {
|
|
695
|
+
return (req.header("x-forwarded-for") ?? "").split(",").map((t) => t.trim()).filter(Boolean).slice(-MAX_FORWARDED).map((t) => normalizeIp(t)).filter((x) => !!x);
|
|
593
696
|
}
|
|
594
697
|
var result = (address, via) => ({ address, internal: !isPublicIp(address), via });
|
|
595
|
-
function walk(req, trusted, via) {
|
|
596
|
-
const
|
|
597
|
-
|
|
698
|
+
function walk(req, trusted, via, cdns) {
|
|
699
|
+
const peer = normalizeIp(req.peer);
|
|
700
|
+
const chain = [...forwardedOf(req), ...peer ? [peer] : []];
|
|
701
|
+
let edge = "";
|
|
598
702
|
for (let i = chain.length - 1; i >= 0; i--) {
|
|
599
|
-
const ip =
|
|
600
|
-
if (!ip) continue;
|
|
601
|
-
last ||= ip;
|
|
703
|
+
const ip = chain[i];
|
|
602
704
|
const b = parseIp(ip);
|
|
603
|
-
|
|
604
|
-
|
|
705
|
+
const { nonPublic, cloudflare, cloudfront } = tables();
|
|
706
|
+
if (nonPublic.some((c) => inCidr(c, b)) || trusted.some((c) => inCidr(c, b))) continue;
|
|
707
|
+
if (cdns && cloudfront.some((c) => inCidr(c, b))) {
|
|
708
|
+
edge = ip;
|
|
709
|
+
continue;
|
|
710
|
+
}
|
|
711
|
+
if (cdns && cloudflare.some((c) => inCidr(c, b))) {
|
|
712
|
+
const client = normalizeIp(req.header("cf-connecting-ip"));
|
|
713
|
+
return client ? result(client, "cloudflare") : { address: ip, internal: false, via };
|
|
714
|
+
}
|
|
715
|
+
return { address: ip, internal: false, via: peer && i === chain.length - 1 ? "socket" : via };
|
|
605
716
|
}
|
|
606
|
-
return { address:
|
|
717
|
+
if (edge) return { address: edge, internal: false, via };
|
|
718
|
+
return { address: chain[chain.length - 1] ?? "", internal: true, via: "socket" };
|
|
719
|
+
}
|
|
720
|
+
function headerAddress(req, name) {
|
|
721
|
+
const first = req.header(name)?.split(",")[0]?.trim();
|
|
722
|
+
if (!first) return null;
|
|
723
|
+
if (PORT_SUFFIXED_HEADERS.includes(name) && !first.startsWith("[")) return normalizeIp(first.replace(/:\d{1,5}$/, ""));
|
|
724
|
+
return normalizeIp(first);
|
|
607
725
|
}
|
|
608
726
|
function resolveClientAddress(req, mode = "auto", platform = null) {
|
|
609
727
|
const peer = normalizeIp(req.peer) ?? "";
|
|
610
728
|
if (mode === "socket") return result(peer, "socket");
|
|
611
729
|
if (typeof mode === "object" && "header" in mode) {
|
|
612
|
-
const
|
|
613
|
-
const ip = normalizeIp(first);
|
|
730
|
+
const ip = headerAddress(req, mode.header.toLowerCase());
|
|
614
731
|
return ip ? result(ip, "header") : result(peer, "socket");
|
|
615
732
|
}
|
|
616
733
|
if (typeof mode === "object" && "hops" in mode) {
|
|
617
|
-
const
|
|
618
|
-
if (
|
|
619
|
-
|
|
620
|
-
return result(chain[at], at === chain.length - 1 ? "socket" : "hops");
|
|
734
|
+
const xff = forwardedOf(req);
|
|
735
|
+
if (xff.length < mode.hops) return walk(req, [], "hops", false);
|
|
736
|
+
return result(xff[xff.length - mode.hops], "hops");
|
|
621
737
|
}
|
|
622
|
-
if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies");
|
|
738
|
+
if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies", false);
|
|
623
739
|
const framework = normalizeIp(req.framework);
|
|
624
740
|
if (framework) return result(framework, "framework");
|
|
625
741
|
if (platform) {
|
|
626
|
-
const ip =
|
|
742
|
+
const ip = headerAddress(req, PLATFORM_HEADERS[platform]);
|
|
627
743
|
if (ip) return result(ip, `platform:${platform}`);
|
|
628
744
|
}
|
|
629
|
-
|
|
630
|
-
const ip = normalizeIp(req.header("cf-connecting-ip"));
|
|
631
|
-
if (ip) return result(ip, "cloudflare");
|
|
632
|
-
}
|
|
633
|
-
return walk(req, [], "forwarded");
|
|
745
|
+
return walk(req, [], "forwarded", true);
|
|
634
746
|
}
|
|
635
747
|
function clientIpModeProblem(value) {
|
|
636
748
|
if (value === "auto" || value === "socket") return null;
|
|
@@ -680,7 +792,7 @@ function canonicalPath(target) {
|
|
|
680
792
|
const cut = t.search(/[?#]/);
|
|
681
793
|
let raw = cut === -1 ? t : t.slice(0, cut);
|
|
682
794
|
if (!raw.startsWith("/")) raw = `/${raw}`;
|
|
683
|
-
return { raw, decoded: normalizeSegments(decodeOnce(raw)) };
|
|
795
|
+
return { raw, decoded: normalizeSegments(decodeOnce(raw).replace(/\\/g, "/")) };
|
|
684
796
|
}
|
|
685
797
|
function matchesEither(matcher, p) {
|
|
686
798
|
return matcher(p.raw) || matcher(p.decoded);
|
|
@@ -883,16 +995,19 @@ export {
|
|
|
883
995
|
parseSiteKey,
|
|
884
996
|
BENIGN_TOOL_FAMILIES,
|
|
885
997
|
toolOf,
|
|
998
|
+
presentsAsBrowser,
|
|
886
999
|
watchworthy,
|
|
887
1000
|
requestKind,
|
|
888
1001
|
pathTraits,
|
|
889
1002
|
resolveCollect,
|
|
890
1003
|
skipMatcher,
|
|
1004
|
+
protectionMatcher,
|
|
891
1005
|
collectAttributes,
|
|
892
1006
|
collectReport,
|
|
893
1007
|
Allowance,
|
|
894
1008
|
detectPlatform,
|
|
895
1009
|
normalizeIp,
|
|
1010
|
+
addressKey,
|
|
896
1011
|
isPublicIp,
|
|
897
1012
|
resolveClientAddress,
|
|
898
1013
|
clientIpModeProblem,
|
|
@@ -6,12 +6,13 @@ import {
|
|
|
6
6
|
checkOptions,
|
|
7
7
|
makeLog,
|
|
8
8
|
reguardApi
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-VZKXPEWQ.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
|
}
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
resolveCollect,
|
|
9
9
|
verifyWebhookSignature,
|
|
10
10
|
visitorIdOf
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-2N762ZXU.js";
|
|
12
12
|
|
|
13
13
|
// src/config.ts
|
|
14
14
|
var ReguardConfigError = class extends TypeError {
|
|
@@ -22,7 +22,7 @@ var ReguardConfigError = class extends TypeError {
|
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
24
|
var BLOCK_REASONS = ["flagged", "flagged_server", "require", "pace"];
|
|
25
|
-
var LABELS = ["
|
|
25
|
+
var LABELS = ["reverse_engineering", "automated_exploration", "unauthorized_extraction"];
|
|
26
26
|
var STAGES = ["candidate", "alert", "enforce"];
|
|
27
27
|
var fail = (option, code, detail) => {
|
|
28
28
|
throw new ReguardConfigError(option, code, detail);
|
|
@@ -30,14 +30,16 @@ var fail = (option, code, detail) => {
|
|
|
30
30
|
var show = (v) => typeof v === "function" ? "a function" : JSON.stringify(v) ?? String(v);
|
|
31
31
|
var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
32
32
|
var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
|
33
|
-
function checkKeys(obj, allowed, prefix, moved = {}) {
|
|
33
|
+
function checkKeys(obj, allowed, prefix, moved = {}, nested) {
|
|
34
|
+
const like = (k) => (a) => a === camel(k).replace(/Seconds$|Secs$/, "Ms") || a === camel(k) || a.toLowerCase() === k.toLowerCase();
|
|
34
35
|
for (const k of Object.keys(obj)) {
|
|
35
36
|
if (obj[k] === void 0 || allowed.includes(k)) continue;
|
|
36
37
|
const path = prefix ? `${prefix}.${k}` : k;
|
|
37
38
|
if (moved[k]) fail(path, "removed_option", `was removed: ${moved[k]}`);
|
|
38
|
-
const
|
|
39
|
-
const
|
|
40
|
-
|
|
39
|
+
const here = allowed.find(like(k));
|
|
40
|
+
const below = here ? void 0 : nested?.keys.find(like(k));
|
|
41
|
+
const hint = here ? `${prefix ? `${prefix}.` : ""}${here}` : below ? `${nested.under}.${below}` : void 0;
|
|
42
|
+
fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${hint}?)` : ""}`);
|
|
41
43
|
}
|
|
42
44
|
}
|
|
43
45
|
function checkBoolean(v, option) {
|
|
@@ -232,7 +234,7 @@ function checkOptions(options) {
|
|
|
232
234
|
if (options === void 0 || options === null) options = {};
|
|
233
235
|
if (!isObject(options)) fail("options", "invalid_type", `must be an object (got ${show(options)})`);
|
|
234
236
|
const o = options;
|
|
235
|
-
checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS);
|
|
237
|
+
checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS, { under: "block", keys: BLOCK_KEYS });
|
|
236
238
|
if (typeof o.ignore === "function") fail("ignore", "invalid_type", "is now a list of paths; use ignoreIf for a function");
|
|
237
239
|
return {
|
|
238
240
|
key: checkString(o.key, "key"),
|