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.
@@ -36,6 +36,7 @@ __export(index_exports, {
36
36
  module.exports = __toCommonJS(index_exports);
37
37
  var import_node_crypto = require("node:crypto");
38
38
  var import_node_stream = require("node:stream");
39
+ var import_node_zlib = require("node:zlib");
39
40
  var import_promises = require("node:stream/promises");
40
41
 
41
42
  // ../shared/src/exchange.ts
@@ -298,6 +299,13 @@ function browserIncoherence(h) {
298
299
  }
299
300
  return reasons;
300
301
  }
302
+ function presentsAsBrowser(h) {
303
+ const ua = h.userAgent ?? "";
304
+ if (!/^Mozilla\/5\.0 \(/.test(ua) || !h.secFetchDest) return false;
305
+ const tool = toolOf(ua);
306
+ if (tool && tool.family !== "headless_browser") return false;
307
+ return browserIncoherence(h).length === 0;
308
+ }
301
309
  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;
302
310
  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;
303
311
  var BROWSER_AUTOMATIC = /^\/(?:favicon\.ico|apple-touch-icon[\w.-]*\.png|browserconfig\.xml|site\.webmanifest|manifest\.json|\.well-known\/appspecific\/)/i;
@@ -381,18 +389,21 @@ function resolveCollect(input, warn = () => {
381
389
  }
382
390
  return out;
383
391
  }
384
- function skipMatcher(patterns) {
392
+ function skipMatcher(patterns, ignoreCase = false) {
385
393
  if (!patterns.length) return () => false;
386
394
  const res = patterns.map((p) => {
387
395
  const tail = p.endsWith("/*");
388
396
  const body = (tail ? p.slice(0, -2) : p).split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
389
- return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`);
397
+ return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`, ignoreCase ? "i" : "");
390
398
  });
391
399
  return (path) => {
392
400
  const p = path.split(/[?#]/)[0] ?? path;
393
401
  return res.some((re) => re.test(p));
394
402
  };
395
403
  }
404
+ function protectionMatcher(patterns) {
405
+ return skipMatcher(patterns, true);
406
+ }
396
407
  function collectAttributes(c) {
397
408
  const a = {};
398
409
  if (c.pages !== DEFAULT_COLLECT.pages) a["data-pages"] = c.pages;
@@ -475,6 +486,98 @@ var CLOUDFLARE_RANGES = [
475
486
  "2a06:98c0::/29",
476
487
  "2c0f:f248::/32"
477
488
  ];
489
+ var CLOUDFRONT_RANGES = [
490
+ "13.124.199.0/24",
491
+ "130.176.0.0/18",
492
+ "130.176.128.0/21",
493
+ "130.176.136.0/23",
494
+ "130.176.140.0/22",
495
+ "130.176.144.0/20",
496
+ "130.176.160.0/19",
497
+ "130.176.192.0/19",
498
+ "130.176.64.0/21",
499
+ "130.176.72.0/22",
500
+ "130.176.76.0/24",
501
+ "130.176.78.0/23",
502
+ "130.176.80.0/22",
503
+ "130.176.86.0/23",
504
+ "130.176.88.0/21",
505
+ "130.176.96.0/19",
506
+ "15.158.0.0/16",
507
+ "18.68.0.0/16",
508
+ "204.246.166.0/24",
509
+ "205.251.218.0/24",
510
+ "24.110.128.0/17",
511
+ "3.172.0.0/18",
512
+ "3.172.64.0/18",
513
+ "3.29.57.0/26",
514
+ "51.72.40.128/28",
515
+ "51.72.40.144/28",
516
+ "51.72.96.0/23",
517
+ "51.74.20.0/24",
518
+ "51.74.21.0/24",
519
+ "51.74.22.0/24",
520
+ "52.46.0.0/18",
521
+ "52.82.128.0/23",
522
+ "52.82.134.0/23",
523
+ "54.182.128.0/20",
524
+ "54.182.144.0/21",
525
+ "54.182.154.0/23",
526
+ "54.182.156.0/22",
527
+ "54.182.160.0/21",
528
+ "54.182.172.0/22",
529
+ "54.182.176.0/21",
530
+ "54.182.184.0/22",
531
+ "54.182.188.0/23",
532
+ "54.182.224.0/21",
533
+ "54.182.240.0/21",
534
+ "54.182.248.0/22",
535
+ "54.239.134.0/23",
536
+ "54.239.170.0/23",
537
+ "54.239.204.0/22",
538
+ "54.239.208.0/21",
539
+ "64.252.128.0/18",
540
+ "64.252.64.0/18",
541
+ "70.132.0.0/18",
542
+ "2001:3fc6:4::/48",
543
+ "2001:3fc6:5::/48",
544
+ "2406:da10:847f:a100::/56",
545
+ "2406:da11:438:2300::/56",
546
+ "2406:da12:4b:c200::/56",
547
+ "2406:da12:8b2e:9c00::/56",
548
+ "2406:da14:17bd:2f00::/56",
549
+ "2406:da14:80bb:ea00::/56",
550
+ "2406:da16:c01:c200::/56",
551
+ "2406:da18:9fa:1b00::/56",
552
+ "2406:da19:e19:4a00::/56",
553
+ "2406:da1a:6df:6c00::/56",
554
+ "2406:da1b:e7c:ad00::/56",
555
+ "2406:da1c:787:2b00::/56",
556
+ "2406:da1c:8d8c:4600::/56",
557
+ "2406:da1e:705:1600::/56",
558
+ "2406:da1f:396:9100::/56",
559
+ "2600:1f11:e79:a800::/56",
560
+ "2600:1f13:417:4d00::/56",
561
+ "2600:1f16:1923:3000::/56",
562
+ "2600:1f17:4356:f100::/56",
563
+ "2600:1f18:7530:7200::/56",
564
+ "2600:1f1a:4568:b500::/56",
565
+ "2600:1f1c:da:600::/56",
566
+ "2600:1f1e:a7:2300::/56",
567
+ "2600:9000:1000::/36",
568
+ "2600:9000:5200::/40",
569
+ "2600:9000:6000::/36",
570
+ "2a05:d011:531:1800::/56",
571
+ "2a05:d012:581:b400::/56",
572
+ "2a05:d014:1362:b000::/56",
573
+ "2a05:d016:9ed:de00::/56",
574
+ "2a05:d018:1a3a:2d00::/56",
575
+ "2a05:d019:80b:e300::/56",
576
+ "2a05:d01a:8a9:be00::/56",
577
+ "2a05:d01c:343:c300::/56",
578
+ "2a05:d025:e59:fb00::/56"
579
+ ];
580
+ var PORT_SUFFIXED_HEADERS = ["cloudfront-viewer-address"];
478
581
  var NON_PUBLIC_RANGES = [
479
582
  "0.0.0.0/8",
480
583
  "10.0.0.0/8",
@@ -604,63 +707,73 @@ function inCidr(c, b) {
604
707
  return true;
605
708
  }
606
709
  var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
607
- var NON_PUBLIC = compile(NON_PUBLIC_RANGES);
608
- var CLOUDFLARE = compile(CLOUDFLARE_RANGES);
609
- function ipInRanges(address, ranges) {
610
- const b = parseIp(address);
611
- if (!b) return false;
612
- const cidrs = typeof ranges[0] === "string" ? compile(ranges) : ranges;
613
- return cidrs.some((c) => inCidr(c, b));
710
+ var compiled;
711
+ var tables = () => compiled ??= { nonPublic: compile(NON_PUBLIC_RANGES), cloudflare: compile(CLOUDFLARE_RANGES), cloudfront: compile(CLOUDFRONT_RANGES) };
712
+ function addressKey(address) {
713
+ const ip = normalizeIp(address);
714
+ if (!ip) return "";
715
+ if (!ip.includes(":")) return ip;
716
+ const b = parseIp(ip);
717
+ const prefix = new Uint8Array(16);
718
+ prefix.set(b.subarray(0, 8));
719
+ return `${formatIp(prefix)}/64`;
614
720
  }
615
721
  function isPublicIp(address) {
616
722
  const b = parseIp(address);
617
- return !!b && !NON_PUBLIC.some((c) => inCidr(c, b));
723
+ return !!b && !tables().nonPublic.some((c) => inCidr(c, b));
618
724
  }
619
- function chainOf(req) {
620
- const xff = req.header("x-forwarded-for") ?? "";
621
- const entries = xff.split(",").map((s) => s.trim()).filter(Boolean).slice(-MAX_FORWARDED);
622
- return [...entries, req.peer];
725
+ function forwardedOf(req) {
726
+ return (req.header("x-forwarded-for") ?? "").split(",").map((t) => t.trim()).filter(Boolean).slice(-MAX_FORWARDED).map((t) => normalizeIp(t)).filter((x) => !!x);
623
727
  }
624
728
  var result = (address, via) => ({ address, internal: !isPublicIp(address), via });
625
- function walk(req, trusted, via) {
626
- const chain = chainOf(req);
627
- let last = "";
729
+ function walk(req, trusted, via, cdns) {
730
+ const peer = normalizeIp(req.peer);
731
+ const chain = [...forwardedOf(req), ...peer ? [peer] : []];
732
+ let edge = "";
628
733
  for (let i = chain.length - 1; i >= 0; i--) {
629
- const ip = normalizeIp(chain[i]);
630
- if (!ip) continue;
631
- last ||= ip;
734
+ const ip = chain[i];
632
735
  const b = parseIp(ip);
633
- if (NON_PUBLIC.some((c) => inCidr(c, b)) || trusted.some((c) => inCidr(c, b))) continue;
634
- return { address: ip, internal: false, via: i === chain.length - 1 ? "socket" : via };
736
+ const { nonPublic, cloudflare, cloudfront } = tables();
737
+ if (nonPublic.some((c) => inCidr(c, b)) || trusted.some((c) => inCidr(c, b))) continue;
738
+ if (cdns && cloudfront.some((c) => inCidr(c, b))) {
739
+ edge = ip;
740
+ continue;
741
+ }
742
+ if (cdns && cloudflare.some((c) => inCidr(c, b))) {
743
+ const client = normalizeIp(req.header("cf-connecting-ip"));
744
+ return client ? result(client, "cloudflare") : { address: ip, internal: false, via };
745
+ }
746
+ return { address: ip, internal: false, via: peer && i === chain.length - 1 ? "socket" : via };
635
747
  }
636
- return { address: last, internal: true, via: "socket" };
748
+ if (edge) return { address: edge, internal: false, via };
749
+ return { address: chain[chain.length - 1] ?? "", internal: true, via: "socket" };
750
+ }
751
+ function headerAddress(req, name) {
752
+ const first = req.header(name)?.split(",")[0]?.trim();
753
+ if (!first) return null;
754
+ if (PORT_SUFFIXED_HEADERS.includes(name) && !first.startsWith("[")) return normalizeIp(first.replace(/:\d{1,5}$/, ""));
755
+ return normalizeIp(first);
637
756
  }
638
757
  function resolveClientAddress(req, mode = "auto", platform = null) {
639
758
  const peer = normalizeIp(req.peer) ?? "";
640
759
  if (mode === "socket") return result(peer, "socket");
641
760
  if (typeof mode === "object" && "header" in mode) {
642
- const first = req.header(mode.header.toLowerCase())?.split(",")[0];
643
- const ip = normalizeIp(first);
761
+ const ip = headerAddress(req, mode.header.toLowerCase());
644
762
  return ip ? result(ip, "header") : result(peer, "socket");
645
763
  }
646
764
  if (typeof mode === "object" && "hops" in mode) {
647
- const chain = chainOf(req).map((t) => normalizeIp(t)).filter((x) => !!x);
648
- if (!chain.length) return result("", "socket");
649
- const at = Math.max(0, chain.length - 1 - mode.hops);
650
- return result(chain[at], at === chain.length - 1 ? "socket" : "hops");
765
+ const xff = forwardedOf(req);
766
+ if (xff.length < mode.hops) return walk(req, [], "hops", false);
767
+ return result(xff[xff.length - mode.hops], "hops");
651
768
  }
652
- if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies");
769
+ if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies", false);
653
770
  const framework = normalizeIp(req.framework);
654
771
  if (framework) return result(framework, "framework");
655
772
  if (platform) {
656
- const ip = normalizeIp(req.header(PLATFORM_HEADERS[platform])?.split(",")[0]);
773
+ const ip = headerAddress(req, PLATFORM_HEADERS[platform]);
657
774
  if (ip) return result(ip, `platform:${platform}`);
658
775
  }
659
- if (peer && ipInRanges(peer, CLOUDFLARE)) {
660
- const ip = normalizeIp(req.header("cf-connecting-ip"));
661
- if (ip) return result(ip, "cloudflare");
662
- }
663
- return walk(req, [], "forwarded");
776
+ return walk(req, [], "forwarded", true);
664
777
  }
665
778
  function clientIpModeProblem(value) {
666
779
  if (value === "auto" || value === "socket") return null;
@@ -710,7 +823,7 @@ function canonicalPath(target) {
710
823
  const cut = t.search(/[?#]/);
711
824
  let raw = cut === -1 ? t : t.slice(0, cut);
712
825
  if (!raw.startsWith("/")) raw = `/${raw}`;
713
- return { raw, decoded: normalizeSegments(decodeOnce(raw)) };
826
+ return { raw, decoded: normalizeSegments(decodeOnce(raw).replace(/\\/g, "/")) };
714
827
  }
715
828
  function matchesEither(matcher, p) {
716
829
  return matcher(p.raw) || matcher(p.decoded);
@@ -901,7 +1014,7 @@ var ReguardConfigError = class extends TypeError {
901
1014
  }
902
1015
  };
903
1016
  var BLOCK_REASONS = ["flagged", "flagged_server", "require", "pace"];
904
- var LABELS = ["rea", "automated_exploration", "unauthorized_extraction"];
1017
+ var LABELS = ["reverse_engineering", "automated_exploration", "unauthorized_extraction"];
905
1018
  var STAGES = ["candidate", "alert", "enforce"];
906
1019
  var fail = (option, code, detail) => {
907
1020
  throw new ReguardConfigError(option, code, detail);
@@ -909,14 +1022,16 @@ var fail = (option, code, detail) => {
909
1022
  var show = (v) => typeof v === "function" ? "a function" : JSON.stringify(v) ?? String(v);
910
1023
  var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
911
1024
  var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
912
- function checkKeys(obj, allowed, prefix, moved = {}) {
1025
+ function checkKeys(obj, allowed, prefix, moved = {}, nested) {
1026
+ const like = (k) => (a) => a === camel(k).replace(/Seconds$|Secs$/, "Ms") || a === camel(k) || a.toLowerCase() === k.toLowerCase();
913
1027
  for (const k of Object.keys(obj)) {
914
1028
  if (obj[k] === void 0 || allowed.includes(k)) continue;
915
1029
  const path = prefix ? `${prefix}.${k}` : k;
916
1030
  if (moved[k]) fail(path, "removed_option", `was removed: ${moved[k]}`);
917
- const c = camel(k).replace(/Seconds$|Secs$/, "Ms");
918
- const hint = allowed.find((a) => a === c || a === camel(k) || a.toLowerCase() === k.toLowerCase());
919
- fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${prefix ? `${prefix}.` : ""}${hint}?)` : ""}`);
1031
+ const here = allowed.find(like(k));
1032
+ const below = here ? void 0 : nested?.keys.find(like(k));
1033
+ const hint = here ? `${prefix ? `${prefix}.` : ""}${here}` : below ? `${nested.under}.${below}` : void 0;
1034
+ fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${hint}?)` : ""}`);
920
1035
  }
921
1036
  }
922
1037
  function checkBoolean(v, option) {
@@ -1111,7 +1226,7 @@ function checkOptions(options) {
1111
1226
  if (options === void 0 || options === null) options = {};
1112
1227
  if (!isObject(options)) fail("options", "invalid_type", `must be an object (got ${show(options)})`);
1113
1228
  const o = options;
1114
- checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS);
1229
+ checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS, { under: "block", keys: BLOCK_KEYS });
1115
1230
  if (typeof o.ignore === "function") fail("ignore", "invalid_type", "is now a list of paths; use ignoreIf for a function");
1116
1231
  return {
1117
1232
  key: checkString(o.key, "key"),
@@ -1301,7 +1416,31 @@ var STRIP_FROM_RESPONSE = /* @__PURE__ */ new Set(["content-encoding", "content-
1301
1416
  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)/;
1302
1417
  var SCAN_LIMIT = 64 * 1024;
1303
1418
  function visitorHash(secret, address) {
1304
- return (0, import_node_crypto.createHmac)("sha256", secret).update(`visitor:${address}`).digest("base64url").slice(0, 22);
1419
+ return (0, import_node_crypto.createHmac)("sha256", secret).update(`visitor:${addressKey(address) || address}`).digest("base64url").slice(0, 22);
1420
+ }
1421
+ function browserHeaders(h) {
1422
+ const get = (n) => header(h, n);
1423
+ 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") };
1424
+ }
1425
+ var compressedScripts = /* @__PURE__ */ new Map();
1426
+ function compressedScript(etag, body) {
1427
+ let c = compressedScripts.get(etag);
1428
+ if (!c) {
1429
+ 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 }) };
1430
+ if (compressedScripts.size >= 8) compressedScripts.clear();
1431
+ compressedScripts.set(etag, c);
1432
+ }
1433
+ return c;
1434
+ }
1435
+ async function readBody(req, limit = 1048576) {
1436
+ const chunks = [];
1437
+ let size = 0;
1438
+ for await (const c of req) {
1439
+ size += c.length;
1440
+ if (size > limit) throw new Error("request body over 1 MiB");
1441
+ chunks.push(c);
1442
+ }
1443
+ return Buffer.concat(chunks);
1305
1444
  }
1306
1445
  function keyFingerprint(secret) {
1307
1446
  return (0, import_node_crypto.createHash)("sha256").update(`reguard-key:${secret}`).digest("base64url").slice(0, 8);
@@ -1392,14 +1531,15 @@ function reguard(options = {}) {
1392
1531
  !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.`
1393
1532
  );
1394
1533
  const passthrough = ((req, _res, next) => {
1395
- req.reguard = null;
1396
- req.reguardDecision = null;
1397
- req.reDetect = null;
1534
+ req.reguard ??= null;
1535
+ req.reguardDecision ??= null;
1536
+ req.reDetect ??= null;
1398
1537
  next();
1399
1538
  });
1400
1539
  Object.defineProperty(passthrough, "site", { value: void 0 });
1401
1540
  passthrough.scriptTag = () => "";
1402
- passthrough.status = () => ({ enabled: false, collector: "off", since: Date.now(), failOpen: false, queued: 0, blocking: "off" });
1541
+ const since = Date.now();
1542
+ passthrough.status = () => ({ enabled: false, collector: "off", since, failOpen: false, queued: 0, blocking: "off" });
1403
1543
  passthrough.flush = async () => {
1404
1544
  };
1405
1545
  passthrough.close = async () => {
@@ -1430,9 +1570,9 @@ function reguard(options = {}) {
1430
1570
  const platform = detectPlatform(typeof process !== "undefined" ? process.env : void 0);
1431
1571
  const blockCfg = o.block;
1432
1572
  const allDry = !blockCfg || BLOCK_REASONS.every((r) => blockCfg.dryRun.has(r));
1433
- const skipped = skipMatcher(o.collect.skip);
1434
- const ignored = o.ignore.length ? skipMatcher(o.ignore) : void 0;
1435
- const required = blockCfg?.require ? skipMatcher(blockCfg.require) : void 0;
1573
+ const skipped = protectionMatcher(o.collect.skip);
1574
+ const ignored = o.ignore.length ? protectionMatcher(o.ignore) : void 0;
1575
+ const required = blockCfg?.require ? protectionMatcher(blockCfg.require) : void 0;
1436
1576
  const allowList = blockCfg?.allow.length ? skipMatcher(blockCfg.allow) : void 0;
1437
1577
  const denyMaps = (o.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
1438
1578
  const tagSettings = { site, collect: o.collect, fresh: freshSeconds(blockCfg), cookieDomain: o.cookieDomain };
@@ -1452,7 +1592,9 @@ function reguard(options = {}) {
1452
1592
  const ip = normalizeIp(custom ?? void 0);
1453
1593
  a = ip ? { address: ip, internal: !isPublicIp(ip), via: "custom" } : resolveClientAddress({ peer, header: get }, "socket");
1454
1594
  } else {
1455
- const framework = req.app?.get?.("trust proxy") ? req.ip : void 0;
1595
+ const trust = req.app?.get?.("trust proxy");
1596
+ 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)).`);
1597
+ const framework = trust && trust !== true ? req.ip : void 0;
1456
1598
  a = resolveClientAddress({ peer, header: get, framework }, o.clientIp, platform);
1457
1599
  }
1458
1600
  ADDRESS.set(req, a);
@@ -1531,15 +1673,15 @@ function reguard(options = {}) {
1531
1673
  const paceApi = pace ? rate(pace.api) : void 0;
1532
1674
  const paceMisses = pace ? rate(pace.notFound) : void 0;
1533
1675
  const cooling = /* @__PURE__ */ new Map();
1534
- const addressKey = (req) => `v:${visitorHash(parsed.secret, resolve(req).address)}`;
1676
+ const addressKey2 = (req) => `v:${visitorHash(parsed.secret, resolve(req).address)}`;
1535
1677
  const paceOf = (req, res, p) => {
1536
1678
  if (!pace || resolve(req).internal) return void 0;
1537
1679
  const get = (n) => header(req.headers, n);
1538
1680
  const now = Date.now();
1539
- const browser = get("sec-fetch-dest") !== void 0;
1681
+ const browser = presentsAsBrowser(browserHeaders(req.headers));
1540
1682
  const tool = browser ? void 0 : toolOf(get("user-agent"));
1541
1683
  if (!browser && !(tool && BENIGN_TOOL_FAMILIES.has(tool.family))) {
1542
- const key2 = addressKey(req);
1684
+ const key2 = addressKey2(req);
1543
1685
  res.once("finish", () => {
1544
1686
  const st = res.statusCode;
1545
1687
  if ((st === 404 || st === 405 || st === 410) && !paceMisses.take(key2)) {
@@ -1559,7 +1701,7 @@ function reguard(options = {}) {
1559
1701
  }
1560
1702
  if (required && matchesEither(required, p)) {
1561
1703
  const sid = cookieValue(get("cookie"), SESSION_COOKIE);
1562
- if (!paceApi.take(sid ? `s:${sid}` : addressKey(req), now)) return "api";
1704
+ if (!paceApi.take(sid ? `s:${sid}` : addressKey2(req), now)) return "api";
1563
1705
  }
1564
1706
  return void 0;
1565
1707
  };
@@ -1569,8 +1711,9 @@ function reguard(options = {}) {
1569
1711
  const dryCounts = /* @__PURE__ */ new Map();
1570
1712
  const dryTimer = setInterval(() => {
1571
1713
  if (!dryCounts.size) return;
1572
- const parts = [...dryCounts].map(([r, n]) => `${r} ${n}`).join(", ");
1573
- log.info(`dry run: would have answered ${[...dryCounts.values()].reduce((a, b) => a + b, 0)} requests in the last minute (${parts})`);
1714
+ const parts = [...dryCounts].map(([r, n2]) => `${r} ${n2}`).join(", ");
1715
+ const n = [...dryCounts.values()].reduce((a, b) => a + b, 0);
1716
+ log.info(`dry run: would have answered ${n} request${n === 1 ? "" : "s"} in the last minute (${parts})`);
1574
1717
  dryCounts.clear();
1575
1718
  }, 6e4);
1576
1719
  dryTimer.unref?.();
@@ -1605,9 +1748,11 @@ function reguard(options = {}) {
1605
1748
  const answer = async (req, res, d) => {
1606
1749
  const respond = blockCfg.respond;
1607
1750
  if (respond) {
1751
+ let threw = false;
1608
1752
  try {
1609
1753
  await respond(req, res, d);
1610
1754
  } catch (e) {
1755
+ threw = true;
1611
1756
  log.once("respond-threw", "error", `block.respond threw (${errorText(e)}): sent the default answer instead`);
1612
1757
  }
1613
1758
  if (res.writableEnded) return;
@@ -1615,7 +1760,7 @@ function reguard(options = {}) {
1615
1760
  res.end();
1616
1761
  return;
1617
1762
  }
1618
- log.once("respond-silent", "warn", "block.respond didn't answer the request: sent the default answer");
1763
+ if (!threw) log.once("respond-silent", "warn", "block.respond didn't answer the request: sent the default answer");
1619
1764
  }
1620
1765
  defaultBlockResponse(req, res, d);
1621
1766
  };
@@ -1628,10 +1773,8 @@ function reguard(options = {}) {
1628
1773
  const init = { method: req.method, headers, redirect: "manual", signal: AbortSignal.timeout(o.timeoutMs) };
1629
1774
  if (req.method !== "GET" && req.method !== "HEAD") {
1630
1775
  const consumed = req.readableEnded || req._body === true;
1631
- if (!consumed) {
1632
- init.body = import_node_stream.Readable.toWeb(req);
1633
- init.duplex = "half";
1634
- } else if (req.body !== void 0) {
1776
+ if (!consumed) init.body = new Uint8Array(await readBody(req));
1777
+ else if (req.body !== void 0) {
1635
1778
  const b = req.body;
1636
1779
  init.body = Buffer.isBuffer(b) ? new Uint8Array(b) : typeof b === "string" ? b : JSON.stringify(b);
1637
1780
  }
@@ -1647,6 +1790,16 @@ function reguard(options = {}) {
1647
1790
  });
1648
1791
  const cookies = r.headers.getSetCookie?.() ?? [];
1649
1792
  if (cookies.length) res.setHeader("set-cookie", cookies);
1793
+ const etag = r.headers.get("etag");
1794
+ const accepts = header(req.headers, "accept-encoding") ?? "";
1795
+ if (etag && r.ok && req.method === "GET" && /javascript/.test(r.headers.get("content-type") ?? "") && /\b(br|gzip)\b/.test(accepts)) {
1796
+ const c = compressedScript(etag, Buffer.from(await r.arrayBuffer()));
1797
+ const encoding = /\bbr\b/.test(accepts) ? "br" : "gzip";
1798
+ res.setHeader("content-encoding", encoding);
1799
+ res.setHeader("vary", "Accept-Encoding");
1800
+ res.end(c[encoding]);
1801
+ return;
1802
+ }
1650
1803
  if (r.body && req.method !== "HEAD") await (0, import_promises.pipeline)(import_node_stream.Readable.fromWeb(r.body), res);
1651
1804
  else res.end();
1652
1805
  } catch (e) {
@@ -1933,7 +2086,7 @@ function createReDetect(opts, wiring = {}) {
1933
2086
  const timeoutMs = wiring.timeoutMs ?? 1e4;
1934
2087
  const addressFor = (req) => wiring.address?.(req) ?? addressOf(req);
1935
2088
  const collect = resolveCollect(opts.collect, (m) => log.once(`collect:${m}`, "warn", m));
1936
- const skipped = skipMatcher(collect.skip);
2089
+ const skipped = protectionMatcher(collect.skip);
1937
2090
  const forward = collect.requests;
1938
2091
  const siteTag = siteTagOf(opts.site, secret);
1939
2092
  const maxQueue = opts.maxQueue ?? 5e3;
@@ -1958,7 +2111,7 @@ function createReDetect(opts, wiring = {}) {
1958
2111
  if (!pushed.size) return null;
1959
2112
  const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
1960
2113
  const a = addressFor(req);
1961
- const address = collect.addresses !== "off" && !verified && !a.internal ? a.address : "";
2114
+ const address = collect.addresses !== "off" && !verified && !a.internal && !presentsAsBrowser(browserHeaders(req.headers)) ? a.address : "";
1962
2115
  const now = Date.now();
1963
2116
  const claims = [];
1964
2117
  let vid;
@@ -2018,6 +2171,7 @@ function createReDetect(opts, wiring = {}) {
2018
2171
  const flushSoon = () => {
2019
2172
  if (queue.length && !inflight) inflight = flush().finally(() => inflight = void 0);
2020
2173
  };
2174
+ let lastUrgent = 0;
2021
2175
  const timer = setInterval(flushSoon, opts.flushIntervalMs ?? 2e3);
2022
2176
  timer.unref?.();
2023
2177
  const readVerdict = (cookieHeader) => readVerdictFrom(secret, opts.site, cookieHeader);
@@ -2029,19 +2183,19 @@ function createReDetect(opts, wiring = {}) {
2029
2183
  const secure = secureRequest(req);
2030
2184
  const decision = wiring.decided?.(req);
2031
2185
  const pace = PACED.get(req);
2186
+ const tool = watchworthy({
2187
+ userAgent: header(h, "user-agent") ?? "",
2188
+ acceptLanguage: header(h, "accept-language"),
2189
+ accept: header(h, "accept"),
2190
+ secFetchMode: header(h, "sec-fetch-mode"),
2191
+ secChUa: header(h, "sec-ch-ua"),
2192
+ secure,
2193
+ path: url.split("?")[0] ?? url,
2194
+ status: res.statusCode
2195
+ });
2032
2196
  if (!sid && !opts.includeSessionless && !decision) {
2033
2197
  if (opts.watchSessionless === false || collect.addresses === "off") return;
2034
- const watch = watchworthy({
2035
- userAgent: header(h, "user-agent") ?? "",
2036
- acceptLanguage: header(h, "accept-language"),
2037
- accept: header(h, "accept"),
2038
- secFetchMode: header(h, "sec-fetch-mode"),
2039
- secChUa: header(h, "sec-ch-ua"),
2040
- secure,
2041
- path: url.split("?")[0] ?? url,
2042
- status: res.statusCode
2043
- });
2044
- if (!watch) return;
2198
+ if (!tool) return;
2045
2199
  }
2046
2200
  const a = addressFor(req);
2047
2201
  const visitor = !sid && a.address && collect.addresses !== "off" ? visitorHash(secret, a.address) : void 0;
@@ -2102,7 +2256,10 @@ function createReDetect(opts, wiring = {}) {
2102
2256
  ...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
2103
2257
  ...a.internal ? { internal: true } : {}
2104
2258
  });
2105
- if (decision) flushSoon();
2259
+ if (decision || tool && Date.now() - lastUrgent >= 500) {
2260
+ lastUrgent = Date.now();
2261
+ flushSoon();
2262
+ }
2106
2263
  } catch (e) {
2107
2264
  onError(e);
2108
2265
  }