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
package/dist/cjs/fastify.cjs
CHANGED
|
@@ -29,6 +29,7 @@ module.exports = __toCommonJS(fastify_exports);
|
|
|
29
29
|
// src/index.ts
|
|
30
30
|
var import_node_crypto = require("node:crypto");
|
|
31
31
|
var import_node_stream = require("node:stream");
|
|
32
|
+
var import_node_zlib = require("node:zlib");
|
|
32
33
|
var import_promises = require("node:stream/promises");
|
|
33
34
|
|
|
34
35
|
// ../shared/src/exchange.ts
|
|
@@ -288,6 +289,13 @@ function browserIncoherence(h) {
|
|
|
288
289
|
}
|
|
289
290
|
return reasons;
|
|
290
291
|
}
|
|
292
|
+
function presentsAsBrowser(h) {
|
|
293
|
+
const ua = h.userAgent ?? "";
|
|
294
|
+
if (!/^Mozilla\/5\.0 \(/.test(ua) || !h.secFetchDest) return false;
|
|
295
|
+
const tool = toolOf(ua);
|
|
296
|
+
if (tool && tool.family !== "headless_browser") return false;
|
|
297
|
+
return browserIncoherence(h).length === 0;
|
|
298
|
+
}
|
|
291
299
|
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;
|
|
292
300
|
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;
|
|
293
301
|
var BROWSER_AUTOMATIC = /^\/(?:favicon\.ico|apple-touch-icon[\w.-]*\.png|browserconfig\.xml|site\.webmanifest|manifest\.json|\.well-known\/appspecific\/)/i;
|
|
@@ -371,18 +379,21 @@ function resolveCollect(input, warn = () => {
|
|
|
371
379
|
}
|
|
372
380
|
return out;
|
|
373
381
|
}
|
|
374
|
-
function skipMatcher(patterns) {
|
|
382
|
+
function skipMatcher(patterns, ignoreCase = false) {
|
|
375
383
|
if (!patterns.length) return () => false;
|
|
376
384
|
const res = patterns.map((p) => {
|
|
377
385
|
const tail = p.endsWith("/*");
|
|
378
386
|
const body = (tail ? p.slice(0, -2) : p).split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
379
|
-
return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}
|
|
387
|
+
return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`, ignoreCase ? "i" : "");
|
|
380
388
|
});
|
|
381
389
|
return (path) => {
|
|
382
390
|
const p = path.split(/[?#]/)[0] ?? path;
|
|
383
391
|
return res.some((re) => re.test(p));
|
|
384
392
|
};
|
|
385
393
|
}
|
|
394
|
+
function protectionMatcher(patterns) {
|
|
395
|
+
return skipMatcher(patterns, true);
|
|
396
|
+
}
|
|
386
397
|
function collectAttributes(c) {
|
|
387
398
|
const a = {};
|
|
388
399
|
if (c.pages !== DEFAULT_COLLECT.pages) a["data-pages"] = c.pages;
|
|
@@ -465,6 +476,98 @@ var CLOUDFLARE_RANGES = [
|
|
|
465
476
|
"2a06:98c0::/29",
|
|
466
477
|
"2c0f:f248::/32"
|
|
467
478
|
];
|
|
479
|
+
var CLOUDFRONT_RANGES = [
|
|
480
|
+
"13.124.199.0/24",
|
|
481
|
+
"130.176.0.0/18",
|
|
482
|
+
"130.176.128.0/21",
|
|
483
|
+
"130.176.136.0/23",
|
|
484
|
+
"130.176.140.0/22",
|
|
485
|
+
"130.176.144.0/20",
|
|
486
|
+
"130.176.160.0/19",
|
|
487
|
+
"130.176.192.0/19",
|
|
488
|
+
"130.176.64.0/21",
|
|
489
|
+
"130.176.72.0/22",
|
|
490
|
+
"130.176.76.0/24",
|
|
491
|
+
"130.176.78.0/23",
|
|
492
|
+
"130.176.80.0/22",
|
|
493
|
+
"130.176.86.0/23",
|
|
494
|
+
"130.176.88.0/21",
|
|
495
|
+
"130.176.96.0/19",
|
|
496
|
+
"15.158.0.0/16",
|
|
497
|
+
"18.68.0.0/16",
|
|
498
|
+
"204.246.166.0/24",
|
|
499
|
+
"205.251.218.0/24",
|
|
500
|
+
"24.110.128.0/17",
|
|
501
|
+
"3.172.0.0/18",
|
|
502
|
+
"3.172.64.0/18",
|
|
503
|
+
"3.29.57.0/26",
|
|
504
|
+
"51.72.40.128/28",
|
|
505
|
+
"51.72.40.144/28",
|
|
506
|
+
"51.72.96.0/23",
|
|
507
|
+
"51.74.20.0/24",
|
|
508
|
+
"51.74.21.0/24",
|
|
509
|
+
"51.74.22.0/24",
|
|
510
|
+
"52.46.0.0/18",
|
|
511
|
+
"52.82.128.0/23",
|
|
512
|
+
"52.82.134.0/23",
|
|
513
|
+
"54.182.128.0/20",
|
|
514
|
+
"54.182.144.0/21",
|
|
515
|
+
"54.182.154.0/23",
|
|
516
|
+
"54.182.156.0/22",
|
|
517
|
+
"54.182.160.0/21",
|
|
518
|
+
"54.182.172.0/22",
|
|
519
|
+
"54.182.176.0/21",
|
|
520
|
+
"54.182.184.0/22",
|
|
521
|
+
"54.182.188.0/23",
|
|
522
|
+
"54.182.224.0/21",
|
|
523
|
+
"54.182.240.0/21",
|
|
524
|
+
"54.182.248.0/22",
|
|
525
|
+
"54.239.134.0/23",
|
|
526
|
+
"54.239.170.0/23",
|
|
527
|
+
"54.239.204.0/22",
|
|
528
|
+
"54.239.208.0/21",
|
|
529
|
+
"64.252.128.0/18",
|
|
530
|
+
"64.252.64.0/18",
|
|
531
|
+
"70.132.0.0/18",
|
|
532
|
+
"2001:3fc6:4::/48",
|
|
533
|
+
"2001:3fc6:5::/48",
|
|
534
|
+
"2406:da10:847f:a100::/56",
|
|
535
|
+
"2406:da11:438:2300::/56",
|
|
536
|
+
"2406:da12:4b:c200::/56",
|
|
537
|
+
"2406:da12:8b2e:9c00::/56",
|
|
538
|
+
"2406:da14:17bd:2f00::/56",
|
|
539
|
+
"2406:da14:80bb:ea00::/56",
|
|
540
|
+
"2406:da16:c01:c200::/56",
|
|
541
|
+
"2406:da18:9fa:1b00::/56",
|
|
542
|
+
"2406:da19:e19:4a00::/56",
|
|
543
|
+
"2406:da1a:6df:6c00::/56",
|
|
544
|
+
"2406:da1b:e7c:ad00::/56",
|
|
545
|
+
"2406:da1c:787:2b00::/56",
|
|
546
|
+
"2406:da1c:8d8c:4600::/56",
|
|
547
|
+
"2406:da1e:705:1600::/56",
|
|
548
|
+
"2406:da1f:396:9100::/56",
|
|
549
|
+
"2600:1f11:e79:a800::/56",
|
|
550
|
+
"2600:1f13:417:4d00::/56",
|
|
551
|
+
"2600:1f16:1923:3000::/56",
|
|
552
|
+
"2600:1f17:4356:f100::/56",
|
|
553
|
+
"2600:1f18:7530:7200::/56",
|
|
554
|
+
"2600:1f1a:4568:b500::/56",
|
|
555
|
+
"2600:1f1c:da:600::/56",
|
|
556
|
+
"2600:1f1e:a7:2300::/56",
|
|
557
|
+
"2600:9000:1000::/36",
|
|
558
|
+
"2600:9000:5200::/40",
|
|
559
|
+
"2600:9000:6000::/36",
|
|
560
|
+
"2a05:d011:531:1800::/56",
|
|
561
|
+
"2a05:d012:581:b400::/56",
|
|
562
|
+
"2a05:d014:1362:b000::/56",
|
|
563
|
+
"2a05:d016:9ed:de00::/56",
|
|
564
|
+
"2a05:d018:1a3a:2d00::/56",
|
|
565
|
+
"2a05:d019:80b:e300::/56",
|
|
566
|
+
"2a05:d01a:8a9:be00::/56",
|
|
567
|
+
"2a05:d01c:343:c300::/56",
|
|
568
|
+
"2a05:d025:e59:fb00::/56"
|
|
569
|
+
];
|
|
570
|
+
var PORT_SUFFIXED_HEADERS = ["cloudfront-viewer-address"];
|
|
468
571
|
var NON_PUBLIC_RANGES = [
|
|
469
572
|
"0.0.0.0/8",
|
|
470
573
|
"10.0.0.0/8",
|
|
@@ -594,63 +697,73 @@ function inCidr(c, b) {
|
|
|
594
697
|
return true;
|
|
595
698
|
}
|
|
596
699
|
var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
|
|
597
|
-
var
|
|
598
|
-
var
|
|
599
|
-
function
|
|
600
|
-
const
|
|
601
|
-
if (!
|
|
602
|
-
|
|
603
|
-
|
|
700
|
+
var compiled;
|
|
701
|
+
var tables = () => compiled ??= { nonPublic: compile(NON_PUBLIC_RANGES), cloudflare: compile(CLOUDFLARE_RANGES), cloudfront: compile(CLOUDFRONT_RANGES) };
|
|
702
|
+
function addressKey(address) {
|
|
703
|
+
const ip = normalizeIp(address);
|
|
704
|
+
if (!ip) return "";
|
|
705
|
+
if (!ip.includes(":")) return ip;
|
|
706
|
+
const b = parseIp(ip);
|
|
707
|
+
const prefix = new Uint8Array(16);
|
|
708
|
+
prefix.set(b.subarray(0, 8));
|
|
709
|
+
return `${formatIp(prefix)}/64`;
|
|
604
710
|
}
|
|
605
711
|
function isPublicIp(address) {
|
|
606
712
|
const b = parseIp(address);
|
|
607
|
-
return !!b && !
|
|
713
|
+
return !!b && !tables().nonPublic.some((c) => inCidr(c, b));
|
|
608
714
|
}
|
|
609
|
-
function
|
|
610
|
-
|
|
611
|
-
const entries = xff.split(",").map((s) => s.trim()).filter(Boolean).slice(-MAX_FORWARDED);
|
|
612
|
-
return [...entries, req.peer];
|
|
715
|
+
function forwardedOf(req) {
|
|
716
|
+
return (req.header("x-forwarded-for") ?? "").split(",").map((t) => t.trim()).filter(Boolean).slice(-MAX_FORWARDED).map((t) => normalizeIp(t)).filter((x) => !!x);
|
|
613
717
|
}
|
|
614
718
|
var result = (address, via) => ({ address, internal: !isPublicIp(address), via });
|
|
615
|
-
function walk(req, trusted, via) {
|
|
616
|
-
const
|
|
617
|
-
|
|
719
|
+
function walk(req, trusted, via, cdns) {
|
|
720
|
+
const peer = normalizeIp(req.peer);
|
|
721
|
+
const chain = [...forwardedOf(req), ...peer ? [peer] : []];
|
|
722
|
+
let edge = "";
|
|
618
723
|
for (let i = chain.length - 1; i >= 0; i--) {
|
|
619
|
-
const ip =
|
|
620
|
-
if (!ip) continue;
|
|
621
|
-
last ||= ip;
|
|
724
|
+
const ip = chain[i];
|
|
622
725
|
const b = parseIp(ip);
|
|
623
|
-
|
|
624
|
-
|
|
726
|
+
const { nonPublic, cloudflare, cloudfront } = tables();
|
|
727
|
+
if (nonPublic.some((c) => inCidr(c, b)) || trusted.some((c) => inCidr(c, b))) continue;
|
|
728
|
+
if (cdns && cloudfront.some((c) => inCidr(c, b))) {
|
|
729
|
+
edge = ip;
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
732
|
+
if (cdns && cloudflare.some((c) => inCidr(c, b))) {
|
|
733
|
+
const client = normalizeIp(req.header("cf-connecting-ip"));
|
|
734
|
+
return client ? result(client, "cloudflare") : { address: ip, internal: false, via };
|
|
735
|
+
}
|
|
736
|
+
return { address: ip, internal: false, via: peer && i === chain.length - 1 ? "socket" : via };
|
|
625
737
|
}
|
|
626
|
-
return { address:
|
|
738
|
+
if (edge) return { address: edge, internal: false, via };
|
|
739
|
+
return { address: chain[chain.length - 1] ?? "", internal: true, via: "socket" };
|
|
740
|
+
}
|
|
741
|
+
function headerAddress(req, name) {
|
|
742
|
+
const first = req.header(name)?.split(",")[0]?.trim();
|
|
743
|
+
if (!first) return null;
|
|
744
|
+
if (PORT_SUFFIXED_HEADERS.includes(name) && !first.startsWith("[")) return normalizeIp(first.replace(/:\d{1,5}$/, ""));
|
|
745
|
+
return normalizeIp(first);
|
|
627
746
|
}
|
|
628
747
|
function resolveClientAddress(req, mode = "auto", platform = null) {
|
|
629
748
|
const peer = normalizeIp(req.peer) ?? "";
|
|
630
749
|
if (mode === "socket") return result(peer, "socket");
|
|
631
750
|
if (typeof mode === "object" && "header" in mode) {
|
|
632
|
-
const
|
|
633
|
-
const ip = normalizeIp(first);
|
|
751
|
+
const ip = headerAddress(req, mode.header.toLowerCase());
|
|
634
752
|
return ip ? result(ip, "header") : result(peer, "socket");
|
|
635
753
|
}
|
|
636
754
|
if (typeof mode === "object" && "hops" in mode) {
|
|
637
|
-
const
|
|
638
|
-
if (
|
|
639
|
-
|
|
640
|
-
return result(chain[at], at === chain.length - 1 ? "socket" : "hops");
|
|
755
|
+
const xff = forwardedOf(req);
|
|
756
|
+
if (xff.length < mode.hops) return walk(req, [], "hops", false);
|
|
757
|
+
return result(xff[xff.length - mode.hops], "hops");
|
|
641
758
|
}
|
|
642
|
-
if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies");
|
|
759
|
+
if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies", false);
|
|
643
760
|
const framework = normalizeIp(req.framework);
|
|
644
761
|
if (framework) return result(framework, "framework");
|
|
645
762
|
if (platform) {
|
|
646
|
-
const ip =
|
|
763
|
+
const ip = headerAddress(req, PLATFORM_HEADERS[platform]);
|
|
647
764
|
if (ip) return result(ip, `platform:${platform}`);
|
|
648
765
|
}
|
|
649
|
-
|
|
650
|
-
const ip = normalizeIp(req.header("cf-connecting-ip"));
|
|
651
|
-
if (ip) return result(ip, "cloudflare");
|
|
652
|
-
}
|
|
653
|
-
return walk(req, [], "forwarded");
|
|
766
|
+
return walk(req, [], "forwarded", true);
|
|
654
767
|
}
|
|
655
768
|
function clientIpModeProblem(value) {
|
|
656
769
|
if (value === "auto" || value === "socket") return null;
|
|
@@ -700,7 +813,7 @@ function canonicalPath(target) {
|
|
|
700
813
|
const cut = t.search(/[?#]/);
|
|
701
814
|
let raw = cut === -1 ? t : t.slice(0, cut);
|
|
702
815
|
if (!raw.startsWith("/")) raw = `/${raw}`;
|
|
703
|
-
return { raw, decoded: normalizeSegments(decodeOnce(raw)) };
|
|
816
|
+
return { raw, decoded: normalizeSegments(decodeOnce(raw).replace(/\\/g, "/")) };
|
|
704
817
|
}
|
|
705
818
|
function matchesEither(matcher, p) {
|
|
706
819
|
return matcher(p.raw) || matcher(p.decoded);
|
|
@@ -845,14 +958,16 @@ var fail = (option, code, detail) => {
|
|
|
845
958
|
var show = (v) => typeof v === "function" ? "a function" : JSON.stringify(v) ?? String(v);
|
|
846
959
|
var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
847
960
|
var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
|
848
|
-
function checkKeys(obj, allowed, prefix, moved = {}) {
|
|
961
|
+
function checkKeys(obj, allowed, prefix, moved = {}, nested) {
|
|
962
|
+
const like = (k) => (a) => a === camel(k).replace(/Seconds$|Secs$/, "Ms") || a === camel(k) || a.toLowerCase() === k.toLowerCase();
|
|
849
963
|
for (const k of Object.keys(obj)) {
|
|
850
964
|
if (obj[k] === void 0 || allowed.includes(k)) continue;
|
|
851
965
|
const path = prefix ? `${prefix}.${k}` : k;
|
|
852
966
|
if (moved[k]) fail(path, "removed_option", `was removed: ${moved[k]}`);
|
|
853
|
-
const
|
|
854
|
-
const
|
|
855
|
-
|
|
967
|
+
const here = allowed.find(like(k));
|
|
968
|
+
const below = here ? void 0 : nested?.keys.find(like(k));
|
|
969
|
+
const hint = here ? `${prefix ? `${prefix}.` : ""}${here}` : below ? `${nested.under}.${below}` : void 0;
|
|
970
|
+
fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${hint}?)` : ""}`);
|
|
856
971
|
}
|
|
857
972
|
}
|
|
858
973
|
function checkBoolean(v, option) {
|
|
@@ -1047,7 +1162,7 @@ function checkOptions(options) {
|
|
|
1047
1162
|
if (options === void 0 || options === null) options = {};
|
|
1048
1163
|
if (!isObject(options)) fail("options", "invalid_type", `must be an object (got ${show(options)})`);
|
|
1049
1164
|
const o = options;
|
|
1050
|
-
checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS);
|
|
1165
|
+
checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS, { under: "block", keys: BLOCK_KEYS });
|
|
1051
1166
|
if (typeof o.ignore === "function") fail("ignore", "invalid_type", "is now a list of paths; use ignoreIf for a function");
|
|
1052
1167
|
return {
|
|
1053
1168
|
key: checkString(o.key, "key"),
|
|
@@ -1219,7 +1334,31 @@ var STRIP_FROM_RESPONSE = /* @__PURE__ */ new Set(["content-encoding", "content-
|
|
|
1219
1334
|
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)/;
|
|
1220
1335
|
var SCAN_LIMIT = 64 * 1024;
|
|
1221
1336
|
function visitorHash(secret, address) {
|
|
1222
|
-
return (0, import_node_crypto.createHmac)("sha256", secret).update(`visitor:${address}`).digest("base64url").slice(0, 22);
|
|
1337
|
+
return (0, import_node_crypto.createHmac)("sha256", secret).update(`visitor:${addressKey(address) || address}`).digest("base64url").slice(0, 22);
|
|
1338
|
+
}
|
|
1339
|
+
function browserHeaders(h) {
|
|
1340
|
+
const get = (n) => header(h, n);
|
|
1341
|
+
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") };
|
|
1342
|
+
}
|
|
1343
|
+
var compressedScripts = /* @__PURE__ */ new Map();
|
|
1344
|
+
function compressedScript(etag, body) {
|
|
1345
|
+
let c = compressedScripts.get(etag);
|
|
1346
|
+
if (!c) {
|
|
1347
|
+
c = { br: (0, import_node_zlib.brotliCompressSync)(body, { params: { [import_node_zlib.constants.BROTLI_PARAM_QUALITY]: 10, [import_node_zlib.constants.BROTLI_PARAM_MODE]: import_node_zlib.constants.BROTLI_MODE_TEXT } }), gzip: (0, import_node_zlib.gzipSync)(body, { level: 9 }) };
|
|
1348
|
+
if (compressedScripts.size >= 8) compressedScripts.clear();
|
|
1349
|
+
compressedScripts.set(etag, c);
|
|
1350
|
+
}
|
|
1351
|
+
return c;
|
|
1352
|
+
}
|
|
1353
|
+
async function readBody(req, limit = 1048576) {
|
|
1354
|
+
const chunks = [];
|
|
1355
|
+
let size = 0;
|
|
1356
|
+
for await (const c of req) {
|
|
1357
|
+
size += c.length;
|
|
1358
|
+
if (size > limit) throw new Error("request body over 1 MiB");
|
|
1359
|
+
chunks.push(c);
|
|
1360
|
+
}
|
|
1361
|
+
return Buffer.concat(chunks);
|
|
1223
1362
|
}
|
|
1224
1363
|
function keyFingerprint(secret) {
|
|
1225
1364
|
return (0, import_node_crypto.createHash)("sha256").update(`reguard-key:${secret}`).digest("base64url").slice(0, 8);
|
|
@@ -1310,14 +1449,15 @@ function reguard(options = {}) {
|
|
|
1310
1449
|
!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.`
|
|
1311
1450
|
);
|
|
1312
1451
|
const passthrough = ((req, _res, next) => {
|
|
1313
|
-
req.reguard
|
|
1314
|
-
req.reguardDecision
|
|
1315
|
-
req.reDetect
|
|
1452
|
+
req.reguard ??= null;
|
|
1453
|
+
req.reguardDecision ??= null;
|
|
1454
|
+
req.reDetect ??= null;
|
|
1316
1455
|
next();
|
|
1317
1456
|
});
|
|
1318
1457
|
Object.defineProperty(passthrough, "site", { value: void 0 });
|
|
1319
1458
|
passthrough.scriptTag = () => "";
|
|
1320
|
-
|
|
1459
|
+
const since = Date.now();
|
|
1460
|
+
passthrough.status = () => ({ enabled: false, collector: "off", since, failOpen: false, queued: 0, blocking: "off" });
|
|
1321
1461
|
passthrough.flush = async () => {
|
|
1322
1462
|
};
|
|
1323
1463
|
passthrough.close = async () => {
|
|
@@ -1348,9 +1488,9 @@ function reguard(options = {}) {
|
|
|
1348
1488
|
const platform = detectPlatform(typeof process !== "undefined" ? process.env : void 0);
|
|
1349
1489
|
const blockCfg = o.block;
|
|
1350
1490
|
const allDry = !blockCfg || BLOCK_REASONS.every((r) => blockCfg.dryRun.has(r));
|
|
1351
|
-
const skipped =
|
|
1352
|
-
const ignored = o.ignore.length ?
|
|
1353
|
-
const required = blockCfg?.require ?
|
|
1491
|
+
const skipped = protectionMatcher(o.collect.skip);
|
|
1492
|
+
const ignored = o.ignore.length ? protectionMatcher(o.ignore) : void 0;
|
|
1493
|
+
const required = blockCfg?.require ? protectionMatcher(blockCfg.require) : void 0;
|
|
1354
1494
|
const allowList = blockCfg?.allow.length ? skipMatcher(blockCfg.allow) : void 0;
|
|
1355
1495
|
const denyMaps = (o.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
|
|
1356
1496
|
const tagSettings = { site, collect: o.collect, fresh: freshSeconds(blockCfg), cookieDomain: o.cookieDomain };
|
|
@@ -1370,7 +1510,9 @@ function reguard(options = {}) {
|
|
|
1370
1510
|
const ip = normalizeIp(custom ?? void 0);
|
|
1371
1511
|
a = ip ? { address: ip, internal: !isPublicIp(ip), via: "custom" } : resolveClientAddress({ peer, header: get }, "socket");
|
|
1372
1512
|
} else {
|
|
1373
|
-
const
|
|
1513
|
+
const trust = req.app?.get?.("trust proxy");
|
|
1514
|
+
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)).`);
|
|
1515
|
+
const framework = trust && trust !== true ? req.ip : void 0;
|
|
1374
1516
|
a = resolveClientAddress({ peer, header: get, framework }, o.clientIp, platform);
|
|
1375
1517
|
}
|
|
1376
1518
|
ADDRESS.set(req, a);
|
|
@@ -1449,15 +1591,15 @@ function reguard(options = {}) {
|
|
|
1449
1591
|
const paceApi = pace ? rate(pace.api) : void 0;
|
|
1450
1592
|
const paceMisses = pace ? rate(pace.notFound) : void 0;
|
|
1451
1593
|
const cooling = /* @__PURE__ */ new Map();
|
|
1452
|
-
const
|
|
1594
|
+
const addressKey2 = (req) => `v:${visitorHash(parsed.secret, resolve(req).address)}`;
|
|
1453
1595
|
const paceOf = (req, res, p) => {
|
|
1454
1596
|
if (!pace || resolve(req).internal) return void 0;
|
|
1455
1597
|
const get = (n) => header(req.headers, n);
|
|
1456
1598
|
const now = Date.now();
|
|
1457
|
-
const browser =
|
|
1599
|
+
const browser = presentsAsBrowser(browserHeaders(req.headers));
|
|
1458
1600
|
const tool = browser ? void 0 : toolOf(get("user-agent"));
|
|
1459
1601
|
if (!browser && !(tool && BENIGN_TOOL_FAMILIES.has(tool.family))) {
|
|
1460
|
-
const key2 =
|
|
1602
|
+
const key2 = addressKey2(req);
|
|
1461
1603
|
res.once("finish", () => {
|
|
1462
1604
|
const st = res.statusCode;
|
|
1463
1605
|
if ((st === 404 || st === 405 || st === 410) && !paceMisses.take(key2)) {
|
|
@@ -1477,7 +1619,7 @@ function reguard(options = {}) {
|
|
|
1477
1619
|
}
|
|
1478
1620
|
if (required && matchesEither(required, p)) {
|
|
1479
1621
|
const sid = cookieValue(get("cookie"), SESSION_COOKIE);
|
|
1480
|
-
if (!paceApi.take(sid ? `s:${sid}` :
|
|
1622
|
+
if (!paceApi.take(sid ? `s:${sid}` : addressKey2(req), now)) return "api";
|
|
1481
1623
|
}
|
|
1482
1624
|
return void 0;
|
|
1483
1625
|
};
|
|
@@ -1487,8 +1629,9 @@ function reguard(options = {}) {
|
|
|
1487
1629
|
const dryCounts = /* @__PURE__ */ new Map();
|
|
1488
1630
|
const dryTimer = setInterval(() => {
|
|
1489
1631
|
if (!dryCounts.size) return;
|
|
1490
|
-
const parts = [...dryCounts].map(([r,
|
|
1491
|
-
|
|
1632
|
+
const parts = [...dryCounts].map(([r, n2]) => `${r} ${n2}`).join(", ");
|
|
1633
|
+
const n = [...dryCounts.values()].reduce((a, b) => a + b, 0);
|
|
1634
|
+
log.info(`dry run: would have answered ${n} request${n === 1 ? "" : "s"} in the last minute (${parts})`);
|
|
1492
1635
|
dryCounts.clear();
|
|
1493
1636
|
}, 6e4);
|
|
1494
1637
|
dryTimer.unref?.();
|
|
@@ -1523,9 +1666,11 @@ function reguard(options = {}) {
|
|
|
1523
1666
|
const answer = async (req, res, d) => {
|
|
1524
1667
|
const respond = blockCfg.respond;
|
|
1525
1668
|
if (respond) {
|
|
1669
|
+
let threw = false;
|
|
1526
1670
|
try {
|
|
1527
1671
|
await respond(req, res, d);
|
|
1528
1672
|
} catch (e) {
|
|
1673
|
+
threw = true;
|
|
1529
1674
|
log.once("respond-threw", "error", `block.respond threw (${errorText(e)}): sent the default answer instead`);
|
|
1530
1675
|
}
|
|
1531
1676
|
if (res.writableEnded) return;
|
|
@@ -1533,7 +1678,7 @@ function reguard(options = {}) {
|
|
|
1533
1678
|
res.end();
|
|
1534
1679
|
return;
|
|
1535
1680
|
}
|
|
1536
|
-
log.once("respond-silent", "warn", "block.respond didn't answer the request: sent the default answer");
|
|
1681
|
+
if (!threw) log.once("respond-silent", "warn", "block.respond didn't answer the request: sent the default answer");
|
|
1537
1682
|
}
|
|
1538
1683
|
defaultBlockResponse(req, res, d);
|
|
1539
1684
|
};
|
|
@@ -1546,10 +1691,8 @@ function reguard(options = {}) {
|
|
|
1546
1691
|
const init = { method: req.method, headers, redirect: "manual", signal: AbortSignal.timeout(o.timeoutMs) };
|
|
1547
1692
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
1548
1693
|
const consumed = req.readableEnded || req._body === true;
|
|
1549
|
-
if (!consumed)
|
|
1550
|
-
|
|
1551
|
-
init.duplex = "half";
|
|
1552
|
-
} else if (req.body !== void 0) {
|
|
1694
|
+
if (!consumed) init.body = new Uint8Array(await readBody(req));
|
|
1695
|
+
else if (req.body !== void 0) {
|
|
1553
1696
|
const b = req.body;
|
|
1554
1697
|
init.body = Buffer.isBuffer(b) ? new Uint8Array(b) : typeof b === "string" ? b : JSON.stringify(b);
|
|
1555
1698
|
}
|
|
@@ -1565,6 +1708,16 @@ function reguard(options = {}) {
|
|
|
1565
1708
|
});
|
|
1566
1709
|
const cookies = r.headers.getSetCookie?.() ?? [];
|
|
1567
1710
|
if (cookies.length) res.setHeader("set-cookie", cookies);
|
|
1711
|
+
const etag = r.headers.get("etag");
|
|
1712
|
+
const accepts = header(req.headers, "accept-encoding") ?? "";
|
|
1713
|
+
if (etag && r.ok && req.method === "GET" && /javascript/.test(r.headers.get("content-type") ?? "") && /\b(br|gzip)\b/.test(accepts)) {
|
|
1714
|
+
const c = compressedScript(etag, Buffer.from(await r.arrayBuffer()));
|
|
1715
|
+
const encoding = /\bbr\b/.test(accepts) ? "br" : "gzip";
|
|
1716
|
+
res.setHeader("content-encoding", encoding);
|
|
1717
|
+
res.setHeader("vary", "Accept-Encoding");
|
|
1718
|
+
res.end(c[encoding]);
|
|
1719
|
+
return;
|
|
1720
|
+
}
|
|
1568
1721
|
if (r.body && req.method !== "HEAD") await (0, import_promises.pipeline)(import_node_stream.Readable.fromWeb(r.body), res);
|
|
1569
1722
|
else res.end();
|
|
1570
1723
|
} catch (e) {
|
|
@@ -1850,7 +2003,7 @@ function createReDetect(opts, wiring = {}) {
|
|
|
1850
2003
|
const timeoutMs = wiring.timeoutMs ?? 1e4;
|
|
1851
2004
|
const addressFor = (req) => wiring.address?.(req) ?? addressOf(req);
|
|
1852
2005
|
const collect = resolveCollect(opts.collect, (m) => log.once(`collect:${m}`, "warn", m));
|
|
1853
|
-
const skipped =
|
|
2006
|
+
const skipped = protectionMatcher(collect.skip);
|
|
1854
2007
|
const forward = collect.requests;
|
|
1855
2008
|
const siteTag = siteTagOf(opts.site, secret);
|
|
1856
2009
|
const maxQueue = opts.maxQueue ?? 5e3;
|
|
@@ -1875,7 +2028,7 @@ function createReDetect(opts, wiring = {}) {
|
|
|
1875
2028
|
if (!pushed.size) return null;
|
|
1876
2029
|
const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
|
|
1877
2030
|
const a = addressFor(req);
|
|
1878
|
-
const address = collect.addresses !== "off" && !verified && !a.internal ? a.address : "";
|
|
2031
|
+
const address = collect.addresses !== "off" && !verified && !a.internal && !presentsAsBrowser(browserHeaders(req.headers)) ? a.address : "";
|
|
1879
2032
|
const now = Date.now();
|
|
1880
2033
|
const claims = [];
|
|
1881
2034
|
let vid;
|
|
@@ -1935,6 +2088,7 @@ function createReDetect(opts, wiring = {}) {
|
|
|
1935
2088
|
const flushSoon = () => {
|
|
1936
2089
|
if (queue.length && !inflight) inflight = flush().finally(() => inflight = void 0);
|
|
1937
2090
|
};
|
|
2091
|
+
let lastUrgent = 0;
|
|
1938
2092
|
const timer = setInterval(flushSoon, opts.flushIntervalMs ?? 2e3);
|
|
1939
2093
|
timer.unref?.();
|
|
1940
2094
|
const readVerdict = (cookieHeader) => readVerdictFrom(secret, opts.site, cookieHeader);
|
|
@@ -1946,19 +2100,19 @@ function createReDetect(opts, wiring = {}) {
|
|
|
1946
2100
|
const secure = secureRequest(req);
|
|
1947
2101
|
const decision = wiring.decided?.(req);
|
|
1948
2102
|
const pace = PACED.get(req);
|
|
2103
|
+
const tool = watchworthy({
|
|
2104
|
+
userAgent: header(h, "user-agent") ?? "",
|
|
2105
|
+
acceptLanguage: header(h, "accept-language"),
|
|
2106
|
+
accept: header(h, "accept"),
|
|
2107
|
+
secFetchMode: header(h, "sec-fetch-mode"),
|
|
2108
|
+
secChUa: header(h, "sec-ch-ua"),
|
|
2109
|
+
secure,
|
|
2110
|
+
path: url.split("?")[0] ?? url,
|
|
2111
|
+
status: res.statusCode
|
|
2112
|
+
});
|
|
1949
2113
|
if (!sid && !opts.includeSessionless && !decision) {
|
|
1950
2114
|
if (opts.watchSessionless === false || collect.addresses === "off") return;
|
|
1951
|
-
|
|
1952
|
-
userAgent: header(h, "user-agent") ?? "",
|
|
1953
|
-
acceptLanguage: header(h, "accept-language"),
|
|
1954
|
-
accept: header(h, "accept"),
|
|
1955
|
-
secFetchMode: header(h, "sec-fetch-mode"),
|
|
1956
|
-
secChUa: header(h, "sec-ch-ua"),
|
|
1957
|
-
secure,
|
|
1958
|
-
path: url.split("?")[0] ?? url,
|
|
1959
|
-
status: res.statusCode
|
|
1960
|
-
});
|
|
1961
|
-
if (!watch) return;
|
|
2115
|
+
if (!tool) return;
|
|
1962
2116
|
}
|
|
1963
2117
|
const a = addressFor(req);
|
|
1964
2118
|
const visitor = !sid && a.address && collect.addresses !== "off" ? visitorHash(secret, a.address) : void 0;
|
|
@@ -2019,7 +2173,10 @@ function createReDetect(opts, wiring = {}) {
|
|
|
2019
2173
|
...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
|
|
2020
2174
|
...a.internal ? { internal: true } : {}
|
|
2021
2175
|
});
|
|
2022
|
-
if (decision
|
|
2176
|
+
if (decision || tool && Date.now() - lastUrgent >= 500) {
|
|
2177
|
+
lastUrgent = Date.now();
|
|
2178
|
+
flushSoon();
|
|
2179
|
+
}
|
|
2023
2180
|
} catch (e) {
|
|
2024
2181
|
onError(e);
|
|
2025
2182
|
}
|
|
@@ -2120,17 +2277,10 @@ function createReDetect(opts, wiring = {}) {
|
|
|
2120
2277
|
}
|
|
2121
2278
|
|
|
2122
2279
|
// src/fastify.ts
|
|
2123
|
-
var FASTIFY_IP = /* @__PURE__ */ new WeakMap();
|
|
2124
2280
|
function plugin(fastify, options, done) {
|
|
2125
2281
|
let mw;
|
|
2126
2282
|
try {
|
|
2127
|
-
|
|
2128
|
-
mw = reguard(
|
|
2129
|
-
trusted && options.clientIp === void 0 ? {
|
|
2130
|
-
...options,
|
|
2131
|
-
clientIp: (req) => FASTIFY_IP.get(req) ?? null
|
|
2132
|
-
} : options
|
|
2133
|
-
);
|
|
2283
|
+
mw = reguard(options);
|
|
2134
2284
|
} catch (e) {
|
|
2135
2285
|
done(e);
|
|
2136
2286
|
return;
|
|
@@ -2138,7 +2288,6 @@ function plugin(fastify, options, done) {
|
|
|
2138
2288
|
for (const name of ["reguard", "reguardDecision"]) if (!fastify.hasRequestDecorator?.(name)) fastify.decorateRequest?.(name, null);
|
|
2139
2289
|
fastify.addHook("onRequest", (request, reply, next) => {
|
|
2140
2290
|
const raw = request.raw;
|
|
2141
|
-
if (request.ip) FASTIFY_IP.set(raw, request.ip);
|
|
2142
2291
|
let passed = false;
|
|
2143
2292
|
const res = reply.raw;
|
|
2144
2293
|
const writeHead = res.writeHead;
|