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/next.cjs
CHANGED
|
@@ -289,6 +289,13 @@ function browserIncoherence(h) {
|
|
|
289
289
|
}
|
|
290
290
|
return reasons;
|
|
291
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
|
+
}
|
|
292
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;
|
|
293
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;
|
|
294
301
|
var BROWSER_AUTOMATIC = /^\/(?:favicon\.ico|apple-touch-icon[\w.-]*\.png|browserconfig\.xml|site\.webmanifest|manifest\.json|\.well-known\/appspecific\/)/i;
|
|
@@ -372,18 +379,21 @@ function resolveCollect(input, warn = () => {
|
|
|
372
379
|
}
|
|
373
380
|
return out;
|
|
374
381
|
}
|
|
375
|
-
function skipMatcher(patterns) {
|
|
382
|
+
function skipMatcher(patterns, ignoreCase = false) {
|
|
376
383
|
if (!patterns.length) return () => false;
|
|
377
384
|
const res = patterns.map((p) => {
|
|
378
385
|
const tail = p.endsWith("/*");
|
|
379
386
|
const body = (tail ? p.slice(0, -2) : p).split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
380
|
-
return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}
|
|
387
|
+
return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`, ignoreCase ? "i" : "");
|
|
381
388
|
});
|
|
382
389
|
return (path) => {
|
|
383
390
|
const p = path.split(/[?#]/)[0] ?? path;
|
|
384
391
|
return res.some((re) => re.test(p));
|
|
385
392
|
};
|
|
386
393
|
}
|
|
394
|
+
function protectionMatcher(patterns) {
|
|
395
|
+
return skipMatcher(patterns, true);
|
|
396
|
+
}
|
|
387
397
|
function collectAttributes(c) {
|
|
388
398
|
const a = {};
|
|
389
399
|
if (c.pages !== DEFAULT_COLLECT.pages) a["data-pages"] = c.pages;
|
|
@@ -466,6 +476,98 @@ var CLOUDFLARE_RANGES = [
|
|
|
466
476
|
"2a06:98c0::/29",
|
|
467
477
|
"2c0f:f248::/32"
|
|
468
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"];
|
|
469
571
|
var NON_PUBLIC_RANGES = [
|
|
470
572
|
"0.0.0.0/8",
|
|
471
573
|
"10.0.0.0/8",
|
|
@@ -595,63 +697,73 @@ function inCidr(c, b) {
|
|
|
595
697
|
return true;
|
|
596
698
|
}
|
|
597
699
|
var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
|
|
598
|
-
var
|
|
599
|
-
var
|
|
600
|
-
function
|
|
601
|
-
const
|
|
602
|
-
if (!
|
|
603
|
-
|
|
604
|
-
|
|
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`;
|
|
605
710
|
}
|
|
606
711
|
function isPublicIp(address) {
|
|
607
712
|
const b = parseIp(address);
|
|
608
|
-
return !!b && !
|
|
713
|
+
return !!b && !tables().nonPublic.some((c) => inCidr(c, b));
|
|
609
714
|
}
|
|
610
|
-
function
|
|
611
|
-
|
|
612
|
-
const entries = xff.split(",").map((s) => s.trim()).filter(Boolean).slice(-MAX_FORWARDED);
|
|
613
|
-
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);
|
|
614
717
|
}
|
|
615
718
|
var result = (address, via) => ({ address, internal: !isPublicIp(address), via });
|
|
616
|
-
function walk(req, trusted, via) {
|
|
617
|
-
const
|
|
618
|
-
|
|
719
|
+
function walk(req, trusted, via, cdns) {
|
|
720
|
+
const peer = normalizeIp(req.peer);
|
|
721
|
+
const chain = [...forwardedOf(req), ...peer ? [peer] : []];
|
|
722
|
+
let edge = "";
|
|
619
723
|
for (let i = chain.length - 1; i >= 0; i--) {
|
|
620
|
-
const ip =
|
|
621
|
-
if (!ip) continue;
|
|
622
|
-
last ||= ip;
|
|
724
|
+
const ip = chain[i];
|
|
623
725
|
const b = parseIp(ip);
|
|
624
|
-
|
|
625
|
-
|
|
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 };
|
|
626
737
|
}
|
|
627
|
-
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);
|
|
628
746
|
}
|
|
629
747
|
function resolveClientAddress(req, mode = "auto", platform = null) {
|
|
630
748
|
const peer = normalizeIp(req.peer) ?? "";
|
|
631
749
|
if (mode === "socket") return result(peer, "socket");
|
|
632
750
|
if (typeof mode === "object" && "header" in mode) {
|
|
633
|
-
const
|
|
634
|
-
const ip = normalizeIp(first);
|
|
751
|
+
const ip = headerAddress(req, mode.header.toLowerCase());
|
|
635
752
|
return ip ? result(ip, "header") : result(peer, "socket");
|
|
636
753
|
}
|
|
637
754
|
if (typeof mode === "object" && "hops" in mode) {
|
|
638
|
-
const
|
|
639
|
-
if (
|
|
640
|
-
|
|
641
|
-
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");
|
|
642
758
|
}
|
|
643
|
-
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);
|
|
644
760
|
const framework = normalizeIp(req.framework);
|
|
645
761
|
if (framework) return result(framework, "framework");
|
|
646
762
|
if (platform) {
|
|
647
|
-
const ip =
|
|
763
|
+
const ip = headerAddress(req, PLATFORM_HEADERS[platform]);
|
|
648
764
|
if (ip) return result(ip, `platform:${platform}`);
|
|
649
765
|
}
|
|
650
|
-
|
|
651
|
-
const ip = normalizeIp(req.header("cf-connecting-ip"));
|
|
652
|
-
if (ip) return result(ip, "cloudflare");
|
|
653
|
-
}
|
|
654
|
-
return walk(req, [], "forwarded");
|
|
766
|
+
return walk(req, [], "forwarded", true);
|
|
655
767
|
}
|
|
656
768
|
function clientIpModeProblem(value) {
|
|
657
769
|
if (value === "auto" || value === "socket") return null;
|
|
@@ -701,7 +813,7 @@ function canonicalPath(target) {
|
|
|
701
813
|
const cut = t.search(/[?#]/);
|
|
702
814
|
let raw = cut === -1 ? t : t.slice(0, cut);
|
|
703
815
|
if (!raw.startsWith("/")) raw = `/${raw}`;
|
|
704
|
-
return { raw, decoded: normalizeSegments(decodeOnce(raw)) };
|
|
816
|
+
return { raw, decoded: normalizeSegments(decodeOnce(raw).replace(/\\/g, "/")) };
|
|
705
817
|
}
|
|
706
818
|
function matchesEither(matcher, p) {
|
|
707
819
|
return matcher(p.raw) || matcher(p.decoded);
|
|
@@ -871,14 +983,16 @@ var fail = (option, code, detail) => {
|
|
|
871
983
|
var show = (v) => typeof v === "function" ? "a function" : JSON.stringify(v) ?? String(v);
|
|
872
984
|
var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
873
985
|
var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
|
874
|
-
function checkKeys(obj, allowed, prefix, moved = {}) {
|
|
986
|
+
function checkKeys(obj, allowed, prefix, moved = {}, nested) {
|
|
987
|
+
const like = (k) => (a) => a === camel(k).replace(/Seconds$|Secs$/, "Ms") || a === camel(k) || a.toLowerCase() === k.toLowerCase();
|
|
875
988
|
for (const k of Object.keys(obj)) {
|
|
876
989
|
if (obj[k] === void 0 || allowed.includes(k)) continue;
|
|
877
990
|
const path = prefix ? `${prefix}.${k}` : k;
|
|
878
991
|
if (moved[k]) fail(path, "removed_option", `was removed: ${moved[k]}`);
|
|
879
|
-
const
|
|
880
|
-
const
|
|
881
|
-
|
|
992
|
+
const here = allowed.find(like(k));
|
|
993
|
+
const below = here ? void 0 : nested?.keys.find(like(k));
|
|
994
|
+
const hint = here ? `${prefix ? `${prefix}.` : ""}${here}` : below ? `${nested.under}.${below}` : void 0;
|
|
995
|
+
fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${hint}?)` : ""}`);
|
|
882
996
|
}
|
|
883
997
|
}
|
|
884
998
|
function checkBoolean(v, option) {
|
|
@@ -1253,7 +1367,7 @@ function reguardFetch(options = {}) {
|
|
|
1253
1367
|
checkFunction(options.fetch, "fetch");
|
|
1254
1368
|
checkFunction(options.onError, "onError");
|
|
1255
1369
|
const log = makeLog(checkLogger(options.logger), checkBoolean(options.debug, "debug") ?? /^(?:1|true|yes)$/i.test(envValue("REGUARD_DEBUG") ?? ""));
|
|
1256
|
-
const ignore = options.ignore?.length ?
|
|
1370
|
+
const ignore = options.ignore?.length ? protectionMatcher(options.ignore) : void 0;
|
|
1257
1371
|
const key = (options.key ?? envValue("REGUARD_KEY"))?.trim();
|
|
1258
1372
|
const parsed = parseSiteKey(key);
|
|
1259
1373
|
const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
|
|
@@ -1293,7 +1407,7 @@ function reguardFetch(options = {}) {
|
|
|
1293
1407
|
const allDry = !block || BLOCK_REASONS.every((r) => block.dryRun.has(r));
|
|
1294
1408
|
const denyMaps = (options.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
|
|
1295
1409
|
const allowList = block?.allow.length ? skipMatcher(block.allow) : void 0;
|
|
1296
|
-
const skipped =
|
|
1410
|
+
const skipped = protectionMatcher(collect.skip);
|
|
1297
1411
|
const tagSettings = { site, collect, cookieDomain };
|
|
1298
1412
|
const pace = block?.pace;
|
|
1299
1413
|
const pages = pace ? new Allowance(pace.documents.burst, pace.documents.perSecond / 1e3, 5e4) : void 0;
|
|
@@ -1352,11 +1466,10 @@ function reguardFetch(options = {}) {
|
|
|
1352
1466
|
}
|
|
1353
1467
|
if (!health.canSend()) queue.length = 0;
|
|
1354
1468
|
};
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
if (!
|
|
1358
|
-
|
|
1359
|
-
waitUntil?.(inflight);
|
|
1469
|
+
let lastUrgent = 0;
|
|
1470
|
+
const flushSoon = (now = false) => {
|
|
1471
|
+
if (queue.length && !inflight && (now || Date.now() - lastFlush >= flushIntervalMs || queue.length >= 100)) inflight = flush().finally(() => inflight = void 0);
|
|
1472
|
+
return inflight;
|
|
1360
1473
|
};
|
|
1361
1474
|
const pushedFor = async (request, verified) => {
|
|
1362
1475
|
if (!pushed.size) return null;
|
|
@@ -1365,7 +1478,9 @@ function reguardFetch(options = {}) {
|
|
|
1365
1478
|
const now = Date.now();
|
|
1366
1479
|
const claims = [];
|
|
1367
1480
|
const k = [sid ? `s:${sid}` : ""];
|
|
1368
|
-
|
|
1481
|
+
const get = (n) => request.headers.get(n) ?? void 0;
|
|
1482
|
+
const browser = presentsAsBrowser({ 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") });
|
|
1483
|
+
if (collect.addresses !== "off" && !verified && !a.internal && !browser && a.address) k.push(`v:${await hmac(parsed.secret, `visitor:${addressKey(a.address) || a.address}`, 22)}`);
|
|
1369
1484
|
let vid;
|
|
1370
1485
|
for (const x of k) {
|
|
1371
1486
|
const e = x ? pushed.get(x) : void 0;
|
|
@@ -1394,14 +1509,11 @@ function reguardFetch(options = {}) {
|
|
|
1394
1509
|
if (sid && /^[\w-]{1,64}$/.test(sid)) headers.set("cookie", `${SESSION_COOKIE}=${sid}`);
|
|
1395
1510
|
headers.set("x-reguard-site", `${site}.${await hmac(parsed.secret, `prefix:${site}`, 16)}`);
|
|
1396
1511
|
const a = addressFor(request);
|
|
1397
|
-
const value = collect.addresses === "off" || !a.address ? "-" : await hmac(parsed.secret, `visitor:${a.address}`, 22);
|
|
1512
|
+
const value = collect.addresses === "off" || !a.address ? "-" : await hmac(parsed.secret, `visitor:${addressKey(a.address) || a.address}`, 22);
|
|
1398
1513
|
headers.set("x-reguard-visitor", `${value}.${await hmac(parsed.secret, `visitor-header:${value}`, 16)}`);
|
|
1399
1514
|
try {
|
|
1400
1515
|
const init = { method: request.method, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) };
|
|
1401
|
-
if (request.method !== "GET" && request.method !== "HEAD" && request.body)
|
|
1402
|
-
init.body = request.body;
|
|
1403
|
-
init.duplex = "half";
|
|
1404
|
-
}
|
|
1516
|
+
if (request.method !== "GET" && request.method !== "HEAD" && request.body) init.body = await request.arrayBuffer();
|
|
1405
1517
|
const r = await doFetch(`${collector}${p.decoded}${url.search}`, init);
|
|
1406
1518
|
const out = new Headers();
|
|
1407
1519
|
r.headers.forEach((v, k) => {
|
|
@@ -1433,7 +1545,7 @@ function reguardFetch(options = {}) {
|
|
|
1433
1545
|
} catch (e) {
|
|
1434
1546
|
log.once("onBlock-threw", "warn", `block.onBlock threw: ${e?.message ?? e}`);
|
|
1435
1547
|
}
|
|
1436
|
-
log.debug(`${d.dryRun ? "would block" : "blocked"} ${request.method} ${d.path}: ${d.reason}`);
|
|
1548
|
+
log.debug(`${d.dryRun ? "would block" : "blocked"} ${request.method} ${d.path}: ${d.reason}${d.pace ? ` (${d.pace})` : ""} from ${d.clientIp}`);
|
|
1437
1549
|
if (d.dryRun) return void 0;
|
|
1438
1550
|
const respond = block.respond;
|
|
1439
1551
|
if (respond) {
|
|
@@ -1453,9 +1565,9 @@ function reguardFetch(options = {}) {
|
|
|
1453
1565
|
if (denyMaps && isSourceMapPath(p)) return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
|
|
1454
1566
|
const cookie = request.headers.get("cookie");
|
|
1455
1567
|
const pending = (async () => {
|
|
1456
|
-
const
|
|
1457
|
-
const pushedV = await pushedFor(request, !!
|
|
1458
|
-
return { browser, pushed: pushedV, merged: mergeVerdicts(
|
|
1568
|
+
const browser2 = await readVerdict(cookie);
|
|
1569
|
+
const pushedV = await pushedFor(request, !!browser2);
|
|
1570
|
+
return { browser: browser2, pushed: pushedV, merged: mergeVerdicts(browser2, pushedV) };
|
|
1459
1571
|
})();
|
|
1460
1572
|
verdicts.set(request, pending);
|
|
1461
1573
|
if (!block) return void 0;
|
|
@@ -1468,10 +1580,11 @@ function reguardFetch(options = {}) {
|
|
|
1468
1580
|
})();
|
|
1469
1581
|
if (allowed) return void 0;
|
|
1470
1582
|
const get = (n) => request.headers.get(n) ?? void 0;
|
|
1471
|
-
|
|
1583
|
+
const browser = presentsAsBrowser({ 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") });
|
|
1584
|
+
if (pages && !browser && (request.method === "GET" || request.method === "HEAD") && requestKind(p.decoded) === "document" && !isSpeculativeHeaders(get)) {
|
|
1472
1585
|
const tool = toolOf(get("user-agent"));
|
|
1473
1586
|
const a = addressFor(request);
|
|
1474
|
-
if (!(tool && BENIGN_TOOL_FAMILIES.has(tool.family)) && a.address && !a.internal && !pages.take(a.address)) {
|
|
1587
|
+
if (!(tool && BENIGN_TOOL_FAMILIES.has(tool.family)) && a.address && !a.internal && !pages.take(addressKey(a.address) || a.address)) {
|
|
1475
1588
|
const answered = await act(request, decide(request, "pace", p, null, "document"));
|
|
1476
1589
|
if (answered) return answered;
|
|
1477
1590
|
}
|
|
@@ -1487,7 +1600,7 @@ function reguardFetch(options = {}) {
|
|
|
1487
1600
|
};
|
|
1488
1601
|
const record = (request, response, ctx) => {
|
|
1489
1602
|
if (!collect.requests) return;
|
|
1490
|
-
|
|
1603
|
+
const task = (async () => {
|
|
1491
1604
|
try {
|
|
1492
1605
|
const url = new URL(request.url);
|
|
1493
1606
|
const p = canonicalPath(url.pathname);
|
|
@@ -1496,18 +1609,19 @@ function reguardFetch(options = {}) {
|
|
|
1496
1609
|
const sid = cookieValue(get("cookie"), SESSION_COOKIE);
|
|
1497
1610
|
const decision = decisions.get(request);
|
|
1498
1611
|
const target = `${url.pathname}${url.search}`;
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
if (!
|
|
1612
|
+
const toolLike = () => watchworthy({ userAgent: get("user-agent") ?? "", acceptLanguage: get("accept-language"), accept: get("accept"), secFetchMode: get("sec-fetch-mode"), secChUa: get("sec-ch-ua"), secure: url.protocol === "https:" ? true : void 0, path: url.pathname, status: response?.status });
|
|
1613
|
+
const tool = toolLike();
|
|
1614
|
+
if (!decision) {
|
|
1615
|
+
if (!sid && (options.watchSessionless === false || collect.addresses === "off" || !tool)) return;
|
|
1616
|
+
if (sid && !response && !tool) return;
|
|
1503
1617
|
}
|
|
1504
1618
|
const a = addressFor(request);
|
|
1505
1619
|
const hash = (s) => hmac(parsed.secret, s, 16);
|
|
1506
|
-
const contentType = response
|
|
1507
|
-
const responseBytes = Number(response
|
|
1620
|
+
const contentType = response?.headers.get("content-type") ?? "";
|
|
1621
|
+
const responseBytes = Number(response?.headers.get("content-length") ?? 0) || 0;
|
|
1508
1622
|
const requestBytes = Number(get("content-length") ?? 0) || 0;
|
|
1509
1623
|
let exchange;
|
|
1510
|
-
if (!isSpeculativeHeaders(get) && isApiLike(target, contentType, requestBytes)) {
|
|
1624
|
+
if (response && !isSpeculativeHeaders(get) && isApiLike(target, contentType, requestBytes)) {
|
|
1511
1625
|
const input = { method: request.method, url: target, requestContentType: get("content-type") ?? "", requestBody: "", requestBytes, status: response.status, responseContentType: contentType, responseBytes };
|
|
1512
1626
|
const wanted = /* @__PURE__ */ new Set();
|
|
1513
1627
|
describeExchange((s) => (wanted.add(s), ""), input);
|
|
@@ -1527,7 +1641,7 @@ function reguardFetch(options = {}) {
|
|
|
1527
1641
|
url: collect.pages === "masked" ? privateUrl(target) : "",
|
|
1528
1642
|
...collect.pages !== "off" ? { item: await hash(`path:${url.pathname}`) } : {},
|
|
1529
1643
|
...collect.pages !== "masked" ? { traits: pathTraits(target, get("rsc") === "1") } : {},
|
|
1530
|
-
status: response.status,
|
|
1644
|
+
...response ? { status: response.status } : {},
|
|
1531
1645
|
headers: Object.fromEntries(["rsc", "next-router-prefetch", "sec-purpose", "purpose"].flatMap((n) => get(n) !== void 0 ? [[n, get(n)]] : [])),
|
|
1532
1646
|
client: {
|
|
1533
1647
|
ua: get("user-agent") ?? "",
|
|
@@ -1541,26 +1655,28 @@ function reguardFetch(options = {}) {
|
|
|
1541
1655
|
hasReferer: !!get("referer"),
|
|
1542
1656
|
...url.protocol === "https:" ? { secure: true } : {}
|
|
1543
1657
|
},
|
|
1544
|
-
...!sid && a.address && collect.addresses !== "off" ? { visitor: await hmac(parsed.secret, `visitor:${a.address}`, 22) } : {},
|
|
1658
|
+
...!sid && a.address && collect.addresses !== "off" ? { visitor: await hmac(parsed.secret, `visitor:${addressKey(a.address) || a.address}`, 22) } : {},
|
|
1545
1659
|
...exchange ? { exchange } : {},
|
|
1546
1660
|
...decision?.pace ? { pace: decision.pace } : {},
|
|
1547
1661
|
...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
|
|
1548
1662
|
...a.internal ? { internal: true } : {}
|
|
1549
1663
|
});
|
|
1550
1664
|
if (queue.length > 5e3) queue.splice(0, queue.length - 5e3);
|
|
1551
|
-
const waitUntil = ctx?.waitUntil ? (p2) => ctx.waitUntil.call(ctx, p2) : void 0;
|
|
1552
1665
|
ensureTimer();
|
|
1553
|
-
|
|
1666
|
+
const urgent = !!decision || tool && Date.now() - lastUrgent >= 500;
|
|
1667
|
+
if (urgent) lastUrgent = Date.now();
|
|
1668
|
+
await flushSoon(urgent);
|
|
1554
1669
|
} catch (e) {
|
|
1555
1670
|
onError(e);
|
|
1556
1671
|
}
|
|
1557
1672
|
})();
|
|
1673
|
+
ctx?.waitUntil?.call(ctx, task);
|
|
1558
1674
|
};
|
|
1559
1675
|
let timer;
|
|
1560
1676
|
const ensureTimer = () => {
|
|
1561
1677
|
if (timer !== void 0 || platform === "workers" || typeof setInterval !== "function") return;
|
|
1562
1678
|
try {
|
|
1563
|
-
timer = setInterval(() => flushSoon(
|
|
1679
|
+
timer = setInterval(() => void flushSoon(true), flushIntervalMs);
|
|
1564
1680
|
timer.unref?.();
|
|
1565
1681
|
} catch {
|
|
1566
1682
|
timer = null;
|
|
@@ -1599,19 +1715,14 @@ function reguardFetch(options = {}) {
|
|
|
1599
1715
|
}
|
|
1600
1716
|
|
|
1601
1717
|
// src/next.ts
|
|
1718
|
+
var SITE_ID = /^[\w.-]{1,64}$/;
|
|
1602
1719
|
function withReguard(config, options = {}) {
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
const mine = cfg.rewrites ? await cfg.rewrites() : void 0;
|
|
1610
|
-
if (!mine) return { beforeFiles: [rule], afterFiles: [], fallback: [] };
|
|
1611
|
-
if (Array.isArray(mine)) return { beforeFiles: [rule], afterFiles: mine, fallback: [] };
|
|
1612
|
-
return { ...mine, beforeFiles: [rule, ...mine.beforeFiles ?? []] };
|
|
1613
|
-
}
|
|
1614
|
-
});
|
|
1720
|
+
if (options.collector !== void 0)
|
|
1721
|
+
throw new ReguardConfigError("collector", "removed_option", "was removed from withReguard: reguardMiddleware() serves /_s/* and reads REGUARD_COLLECTOR at run time");
|
|
1722
|
+
if (options.site !== void 0 && (typeof options.site !== "string" || !SITE_ID.test(options.site)))
|
|
1723
|
+
throw new ReguardConfigError("site", "invalid_value", 'must be your site id (on your dashboard), e.g. "shop-example-com"');
|
|
1724
|
+
const site = options.site ?? parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site;
|
|
1725
|
+
const apply = (cfg) => site ? { ...cfg, env: { ...cfg.env ?? {}, NEXT_PUBLIC_REGUARD_SITE: site } } : cfg;
|
|
1615
1726
|
if (typeof config === "function") {
|
|
1616
1727
|
const fn = config;
|
|
1617
1728
|
return (async (...args) => apply(await fn(...args)));
|
|
@@ -1639,9 +1750,13 @@ function reguardScriptProps(options = {}) {
|
|
|
1639
1750
|
const site = parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site ?? publicSite();
|
|
1640
1751
|
if (!site && !warned) {
|
|
1641
1752
|
warned = true;
|
|
1642
|
-
console.warn(
|
|
1753
|
+
console.warn(
|
|
1754
|
+
"[reguard] No site id for the script tag: REGUARD_KEY isn't set here and NEXT_PUBLIC_REGUARD_SITE isn't either, so the script won't start on this page. For pages rendered at build time, set NEXT_PUBLIC_REGUARD_SITE to your site id (it's public; your dashboard shows it), or pass it to withReguard({ ... }, { site })."
|
|
1755
|
+
);
|
|
1643
1756
|
}
|
|
1644
1757
|
const production = envValue("NODE_ENV") === "production";
|
|
1758
|
+
if (!production && options.collect && options.collect.requests !== void 0)
|
|
1759
|
+
throw new ReguardConfigError("collect.requests", "unknown_option", "isn't an option of reguardScriptProps (the script sends no request summaries): pass it to reguardMiddleware");
|
|
1645
1760
|
const collect = production ? resolveCollect(options.collect, (m) => console.warn(`[reguard] ${m}`)) : checkCollect(options.collect);
|
|
1646
1761
|
const cookieDomain = production ? typeof options.cookieDomain === "string" ? options.cookieDomain.replace(/^\./, "").toLowerCase() : void 0 : checkCookieDomain(options.cookieDomain);
|
|
1647
1762
|
return {
|
|
@@ -1654,15 +1769,19 @@ function reguardScriptProps(options = {}) {
|
|
|
1654
1769
|
...cookieDomain ? { "data-cookie-domain": cookieDomain } : {}
|
|
1655
1770
|
};
|
|
1656
1771
|
}
|
|
1772
|
+
var MIDDLEWARE_OPTIONS = ["block", "key", "previousKey", "collector", "collect", "ignore", "sourceMaps", "clientIp", "timeoutMs", "debug", "logger"];
|
|
1657
1773
|
function reguardMiddleware(options = {}) {
|
|
1658
1774
|
for (const k of Object.keys(options))
|
|
1659
|
-
if (!
|
|
1775
|
+
if (!MIDDLEWARE_OPTIONS.includes(k) && options[k] !== void 0)
|
|
1660
1776
|
throw new ReguardConfigError(k, "unknown_option", "isn't an option of reguardMiddleware");
|
|
1661
1777
|
checkBlock(options.block, "block", "fetch");
|
|
1662
|
-
const rg = reguardFetch(
|
|
1663
|
-
return async (request) => {
|
|
1664
|
-
|
|
1665
|
-
|
|
1778
|
+
const rg = reguardFetch(options);
|
|
1779
|
+
return async (request, event) => {
|
|
1780
|
+
const ctx = typeof event?.waitUntil === "function" ? { waitUntil: event.waitUntil.bind(event) } : void 0;
|
|
1781
|
+
const answered = await rg.handle(request, ctx);
|
|
1782
|
+
if (isReguardPath(new URL(request.url).pathname)) return answered;
|
|
1783
|
+
rg.record(request, answered ?? null, ctx);
|
|
1784
|
+
return answered;
|
|
1666
1785
|
};
|
|
1667
1786
|
}
|
|
1668
1787
|
// Annotate the CommonJS export names for ESM import in node:
|
package/dist/cjs/testing.cjs
CHANGED
|
@@ -70,110 +70,6 @@ function parseSiteKey(key) {
|
|
|
70
70
|
// ../shared/src/collect.ts
|
|
71
71
|
var DEFAULT_COLLECT = Object.freeze({ pages: "masked", addresses: "hashed", behavior: true, requests: true, skip: [] });
|
|
72
72
|
|
|
73
|
-
// ../shared/src/address.ts
|
|
74
|
-
var CLOUDFLARE_RANGES = [
|
|
75
|
-
"173.245.48.0/20",
|
|
76
|
-
"103.21.244.0/22",
|
|
77
|
-
"103.22.200.0/22",
|
|
78
|
-
"103.31.4.0/22",
|
|
79
|
-
"141.101.64.0/18",
|
|
80
|
-
"108.162.192.0/18",
|
|
81
|
-
"190.93.240.0/20",
|
|
82
|
-
"188.114.96.0/20",
|
|
83
|
-
"197.234.240.0/22",
|
|
84
|
-
"198.41.128.0/17",
|
|
85
|
-
"162.158.0.0/15",
|
|
86
|
-
"104.16.0.0/13",
|
|
87
|
-
"104.24.0.0/14",
|
|
88
|
-
"172.64.0.0/13",
|
|
89
|
-
"131.0.72.0/22",
|
|
90
|
-
"2400:cb00::/32",
|
|
91
|
-
"2606:4700::/32",
|
|
92
|
-
"2803:f800::/32",
|
|
93
|
-
"2405:b500::/32",
|
|
94
|
-
"2405:8100::/32",
|
|
95
|
-
"2a06:98c0::/29",
|
|
96
|
-
"2c0f:f248::/32"
|
|
97
|
-
];
|
|
98
|
-
var NON_PUBLIC_RANGES = [
|
|
99
|
-
"0.0.0.0/8",
|
|
100
|
-
"10.0.0.0/8",
|
|
101
|
-
"100.64.0.0/10",
|
|
102
|
-
"127.0.0.0/8",
|
|
103
|
-
"169.254.0.0/16",
|
|
104
|
-
"172.16.0.0/12",
|
|
105
|
-
"192.168.0.0/16",
|
|
106
|
-
"::/128",
|
|
107
|
-
"::1/128",
|
|
108
|
-
"fc00::/7",
|
|
109
|
-
"fe80::/10"
|
|
110
|
-
];
|
|
111
|
-
function parseIpv4(s) {
|
|
112
|
-
const parts = s.split(".");
|
|
113
|
-
if (parts.length !== 4) return null;
|
|
114
|
-
const out = [];
|
|
115
|
-
for (const p of parts) {
|
|
116
|
-
if (!/^\d{1,3}$/.test(p) || p.length > 1 && p.startsWith("0")) return null;
|
|
117
|
-
const n = Number(p);
|
|
118
|
-
if (n > 255) return null;
|
|
119
|
-
out.push(n);
|
|
120
|
-
}
|
|
121
|
-
return out;
|
|
122
|
-
}
|
|
123
|
-
function parseIp(text) {
|
|
124
|
-
const s = text.trim();
|
|
125
|
-
if (!s) return null;
|
|
126
|
-
const v4 = parseIpv4(s);
|
|
127
|
-
if (v4) return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, ...v4]);
|
|
128
|
-
if (!s.includes(":") || !/^[0-9a-fA-F:.]+$/.test(s)) return null;
|
|
129
|
-
const halves = s.split("::");
|
|
130
|
-
if (halves.length > 2) return null;
|
|
131
|
-
const groups = (part) => {
|
|
132
|
-
if (part === "") return [];
|
|
133
|
-
const out = [];
|
|
134
|
-
const items = part.split(":");
|
|
135
|
-
for (let i = 0; i < items.length; i++) {
|
|
136
|
-
const it = items[i];
|
|
137
|
-
if (i === items.length - 1 && it.includes(".")) {
|
|
138
|
-
const tail2 = parseIpv4(it);
|
|
139
|
-
if (!tail2) return null;
|
|
140
|
-
out.push(tail2[0] << 8 | tail2[1], tail2[2] << 8 | tail2[3]);
|
|
141
|
-
} else {
|
|
142
|
-
if (!/^[0-9a-fA-F]{1,4}$/.test(it)) return null;
|
|
143
|
-
out.push(parseInt(it, 16));
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
return out;
|
|
147
|
-
};
|
|
148
|
-
const head = groups(halves[0]);
|
|
149
|
-
const tail = halves.length === 2 ? groups(halves[1]) : [];
|
|
150
|
-
if (!head || !tail) return null;
|
|
151
|
-
const total = head.length + tail.length;
|
|
152
|
-
if (halves.length === 2 ? total > 7 : total !== 8) return null;
|
|
153
|
-
const all = [...head, ...Array(8 - total).fill(0), ...tail];
|
|
154
|
-
const bytes = new Uint8Array(16);
|
|
155
|
-
all.forEach((g, i) => {
|
|
156
|
-
bytes[i * 2] = g >> 8;
|
|
157
|
-
bytes[i * 2 + 1] = g & 255;
|
|
158
|
-
});
|
|
159
|
-
return bytes;
|
|
160
|
-
}
|
|
161
|
-
function parseCidr(text) {
|
|
162
|
-
const [addr, len, extra] = text.trim().split("/");
|
|
163
|
-
if (extra !== void 0 || !addr) return null;
|
|
164
|
-
const bytes = parseIp(addr);
|
|
165
|
-
if (!bytes) return null;
|
|
166
|
-
const v4 = parseIpv4(addr.trim()) !== null;
|
|
167
|
-
const max = v4 ? 32 : 128;
|
|
168
|
-
if (len !== void 0 && !/^\d{1,3}$/.test(len)) return null;
|
|
169
|
-
const n = len === void 0 ? max : Number(len);
|
|
170
|
-
if (n > max) return null;
|
|
171
|
-
return { bytes, bits: v4 ? n + 96 : n };
|
|
172
|
-
}
|
|
173
|
-
var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
|
|
174
|
-
var NON_PUBLIC = compile(NON_PUBLIC_RANGES);
|
|
175
|
-
var CLOUDFLARE = compile(CLOUDFLARE_RANGES);
|
|
176
|
-
|
|
177
73
|
// ../shared/src/webhooks.ts
|
|
178
74
|
var enc2 = new TextEncoder();
|
|
179
75
|
function hmacKey2(secret) {
|