reguard 0.8.1 → 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.
Files changed (44) hide show
  1. package/README.md +25 -3
  2. package/dist/chunks/{chunk-PA46KSOR.js → chunk-2N762ZXU.js} +235 -44
  3. package/dist/chunks/{chunk-3AYS7WSY.js → chunk-4RD66ACT.js} +81 -8
  4. package/dist/chunks/{chunk-U54IP6G4.js → chunk-GOT54CF4.js} +61 -40
  5. package/dist/chunks/{chunk-KNKCUJL3.js → chunk-RTCPK4MF.js} +102 -41
  6. package/dist/cjs/fastify.cjs +305 -93
  7. package/dist/cjs/fetch.cjs +347 -87
  8. package/dist/cjs/index.cjs +386 -86
  9. package/dist/cjs/next.cjs +366 -103
  10. package/dist/cjs/testing.cjs +28 -100
  11. package/dist/fastify.js +4 -12
  12. package/dist/fetch.js +14 -5
  13. package/dist/index.js +13 -5
  14. package/dist/next.js +33 -23
  15. package/dist/testing.js +9 -3
  16. package/dist/types/node/src/api.d.ts +139 -0
  17. package/dist/types/node/src/core.d.ts +8 -1
  18. package/dist/types/node/src/fastify.d.ts +15 -7
  19. package/dist/types/node/src/fetch.d.ts +12 -2
  20. package/dist/types/node/src/index.d.ts +6 -0
  21. package/dist/types/node/src/next.d.ts +39 -17
  22. package/dist/types/node/src/testing.d.ts +11 -0
  23. package/dist/types/shared/src/address.d.ts +25 -6
  24. package/dist/types/shared/src/collect.d.ts +7 -1
  25. package/dist/types/shared/src/index.d.ts +14 -0
  26. package/dist/types/shared/src/paths.d.ts +6 -2
  27. package/dist/types/shared/src/tools.d.ts +10 -0
  28. package/dist/types/shared/src/verdict.d.ts +6 -0
  29. package/dist/types/shared/src/webhooks.d.ts +32 -0
  30. package/dist/types-cjs/node/src/api.d.cts +139 -0
  31. package/dist/types-cjs/node/src/core.d.cts +8 -1
  32. package/dist/types-cjs/node/src/fastify.d.cts +15 -7
  33. package/dist/types-cjs/node/src/fetch.d.cts +12 -2
  34. package/dist/types-cjs/node/src/index.d.cts +6 -0
  35. package/dist/types-cjs/node/src/next.d.cts +39 -17
  36. package/dist/types-cjs/node/src/testing.d.cts +11 -0
  37. package/dist/types-cjs/shared/src/address.d.cts +25 -6
  38. package/dist/types-cjs/shared/src/collect.d.cts +7 -1
  39. package/dist/types-cjs/shared/src/index.d.cts +14 -0
  40. package/dist/types-cjs/shared/src/paths.d.cts +6 -2
  41. package/dist/types-cjs/shared/src/tools.d.cts +10 -0
  42. package/dist/types-cjs/shared/src/verdict.d.cts +6 -0
  43. package/dist/types-cjs/shared/src/webhooks.d.cts +32 -0
  44. package/package.json +3 -2
@@ -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 NON_PUBLIC = compile(NON_PUBLIC_RANGES);
598
- var CLOUDFLARE = compile(CLOUDFLARE_RANGES);
599
- function ipInRanges(address, ranges) {
600
- const b = parseIp(address);
601
- if (!b) return false;
602
- const cidrs = typeof ranges[0] === "string" ? compile(ranges) : ranges;
603
- return cidrs.some((c) => inCidr(c, b));
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 && !NON_PUBLIC.some((c) => inCidr(c, b));
713
+ return !!b && !tables().nonPublic.some((c) => inCidr(c, b));
608
714
  }
609
- function chainOf(req) {
610
- const xff = req.header("x-forwarded-for") ?? "";
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 chain = chainOf(req);
617
- let last = "";
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 = normalizeIp(chain[i]);
620
- if (!ip) continue;
621
- last ||= ip;
724
+ const ip = chain[i];
622
725
  const b = parseIp(ip);
623
- if (NON_PUBLIC.some((c) => inCidr(c, b)) || trusted.some((c) => inCidr(c, b))) continue;
624
- return { address: ip, internal: false, via: i === chain.length - 1 ? "socket" : via };
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: last, internal: true, via: "socket" };
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 first = req.header(mode.header.toLowerCase())?.split(",")[0];
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 chain = chainOf(req).map((t) => normalizeIp(t)).filter((x) => !!x);
638
- if (!chain.length) return result("", "socket");
639
- const at = Math.max(0, chain.length - 1 - mode.hops);
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 = normalizeIp(req.header(PLATFORM_HEADERS[platform])?.split(",")[0]);
763
+ const ip = headerAddress(req, PLATFORM_HEADERS[platform]);
647
764
  if (ip) return result(ip, `platform:${platform}`);
648
765
  }
649
- if (peer && ipInRanges(peer, CLOUDFLARE)) {
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);
@@ -712,12 +825,17 @@ function isSourceMapPath(p) {
712
825
  return /\.map$/i.test(p.raw) || /\.map$/i.test(p.decoded);
713
826
  }
714
827
 
828
+ // ../shared/src/webhooks.ts
829
+ var enc2 = new TextEncoder();
830
+
715
831
  // src/core.ts
716
832
  var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
833
+ var visitorIdOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
717
834
  function withFlagged(p, source = "browser") {
718
835
  return {
719
836
  ...p,
720
837
  source,
838
+ visitor: visitorIdOf(p.vid) ?? null,
721
839
  flagged({ labels, minStage = "candidate" } = {}) {
722
840
  const want = typeof labels === "string" ? [labels] : labels?.length ? labels : void 0;
723
841
  const rank = STAGE_RANK[minStage] ?? 0;
@@ -730,8 +848,9 @@ function mergeVerdicts(browser, pushed) {
730
848
  if (!browser) return withFlagged(pushed, "server");
731
849
  const rules = new Set(browser.claims.map((c) => `${c.rule}|${c.label}|${c.stage}`));
732
850
  const claims = [...browser.claims, ...pushed.claims.filter((c) => !rules.has(`${c.rule}|${c.label}|${c.stage}`))];
733
- const { source: _s, flagged: _f, ...payload } = browser;
734
- return withFlagged({ ...payload, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
851
+ const { source: _s, flagged: _f, visitor: _v, ...payload } = browser;
852
+ const vid = visitorIdOf(payload.vid) ?? visitorIdOf(pushed.vid);
853
+ return withFlagged({ ...payload, ...vid ? { vid } : {}, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
735
854
  }
736
855
  async function readVerdictFrom(secret, site, cookieHeader) {
737
856
  const token = cookieValue(cookieHeader, VERDICT_COOKIE);
@@ -770,8 +889,8 @@ function freshSeconds(cfg) {
770
889
  function verdictAgeMs(v, now = Date.now()) {
771
890
  return now - (v.exp - VERDICT_TTL_MS);
772
891
  }
773
- function pushedVerdict(sid, site, claims, now = Date.now()) {
774
- return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4 }, "server");
892
+ function pushedVerdict(sid, site, claims, now = Date.now(), vid) {
893
+ return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4, ...vid ? { vid } : {} }, "server");
775
894
  }
776
895
  var ANSWER_CODES = { flagged: "reguard.blocked", flagged_server: "reguard.blocked", require: "reguard.require", pace: "reguard.pace" };
777
896
  var RETRY_AFTER = { flagged: 120, flagged_server: 120, require: 5, pace: 2 };
@@ -839,14 +958,16 @@ var fail = (option, code, detail) => {
839
958
  var show = (v) => typeof v === "function" ? "a function" : JSON.stringify(v) ?? String(v);
840
959
  var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
841
960
  var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
842
- 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();
843
963
  for (const k of Object.keys(obj)) {
844
964
  if (obj[k] === void 0 || allowed.includes(k)) continue;
845
965
  const path = prefix ? `${prefix}.${k}` : k;
846
966
  if (moved[k]) fail(path, "removed_option", `was removed: ${moved[k]}`);
847
- const c = camel(k).replace(/Seconds$|Secs$/, "Ms");
848
- const hint = allowed.find((a) => a === c || a === camel(k) || a.toLowerCase() === k.toLowerCase());
849
- fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${prefix ? `${prefix}.` : ""}${hint}?)` : ""}`);
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}?)` : ""}`);
850
971
  }
851
972
  }
852
973
  function checkBoolean(v, option) {
@@ -1041,7 +1162,7 @@ function checkOptions(options) {
1041
1162
  if (options === void 0 || options === null) options = {};
1042
1163
  if (!isObject(options)) fail("options", "invalid_type", `must be an object (got ${show(options)})`);
1043
1164
  const o = options;
1044
- checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS);
1165
+ checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS, { under: "block", keys: BLOCK_KEYS });
1045
1166
  if (typeof o.ignore === "function") fail("ignore", "invalid_type", "is now a list of paths; use ignoreIf for a function");
1046
1167
  return {
1047
1168
  key: checkString(o.key, "key"),
@@ -1147,6 +1268,50 @@ var Health = class {
1147
1268
  }
1148
1269
  };
1149
1270
 
1271
+ // src/api.ts
1272
+ var ReguardApiError = class extends Error {
1273
+ constructor(status, message) {
1274
+ super(message);
1275
+ this.status = status;
1276
+ this.name = "ReguardApiError";
1277
+ }
1278
+ };
1279
+ function reguardApi(options = {}) {
1280
+ const key = (options.key?.trim() || envValue("REGUARD_KEY"))?.trim();
1281
+ if (options.key?.trim() && !parseSiteKey(options.key.trim())?.site) throw new TypeError("[reguard] reguardApi: key must be a site key (rgk.<site>.v<n>.\u2026)");
1282
+ const base = collectorBase(options.collector || envValue("REGUARD_COLLECTOR"));
1283
+ const doFetch = options.fetch ?? fetch;
1284
+ const timeoutMs = options.timeoutMs ?? 1e4;
1285
+ async function get(path) {
1286
+ if (!key) throw new ReguardApiError(0, "No site key: pass { key } or set REGUARD_KEY.");
1287
+ if (!parseSiteKey(key)?.site) throw new ReguardApiError(0, "REGUARD_KEY isn't a site key (rgk.<site>.v<n>.\u2026).");
1288
+ let res;
1289
+ try {
1290
+ res = await doFetch(`${base}${path}`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
1291
+ } catch (e) {
1292
+ throw new ReguardApiError(0, `Reguard's API can't be reached: ${e.message}`);
1293
+ }
1294
+ const parsed = await res.json().catch(() => null);
1295
+ const body = parsed && typeof parsed === "object" ? parsed : {};
1296
+ if (!res.ok) throw new ReguardApiError(res.status, typeof body.error === "string" && body.error ? body.error : `Reguard's API answered ${res.status}`);
1297
+ return body;
1298
+ }
1299
+ return {
1300
+ async visitor(id) {
1301
+ if (!visitorIdOf(id)) throw new ReguardApiError(400, "Not a visitor id: they look like vis_ followed by 22 characters.");
1302
+ return (await get(`/v1/visitors/${id}`)).visitor;
1303
+ },
1304
+ events({ after, limit, types } = {}) {
1305
+ const q = new URLSearchParams();
1306
+ if (after) q.set("after", after);
1307
+ if (typeof limit === "number" && Number.isInteger(limit) && limit > 0) q.set("limit", String(limit));
1308
+ if (types?.length) q.set("type", types.join(","));
1309
+ const qs = q.toString();
1310
+ return get(`/v1/events${qs ? `?${qs}` : ""}`);
1311
+ }
1312
+ };
1313
+ }
1314
+
1150
1315
  // src/index.ts
1151
1316
  var PREFIX = "/_s";
1152
1317
  var NOT_FORWARDED = /* @__PURE__ */ new Set([
@@ -1169,7 +1334,31 @@ var STRIP_FROM_RESPONSE = /* @__PURE__ */ new Set(["content-encoding", "content-
1169
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)/;
1170
1335
  var SCAN_LIMIT = 64 * 1024;
1171
1336
  function visitorHash(secret, address) {
1172
- 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);
1173
1362
  }
1174
1363
  function keyFingerprint(secret) {
1175
1364
  return (0, import_node_crypto.createHash)("sha256").update(`reguard-key:${secret}`).digest("base64url").slice(0, 8);
@@ -1260,18 +1449,24 @@ function reguard(options = {}) {
1260
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.`
1261
1450
  );
1262
1451
  const passthrough = ((req, _res, next) => {
1263
- req.reguard = null;
1264
- req.reguardDecision = null;
1265
- req.reDetect = null;
1452
+ req.reguard ??= null;
1453
+ req.reguardDecision ??= null;
1454
+ req.reDetect ??= null;
1266
1455
  next();
1267
1456
  });
1268
1457
  Object.defineProperty(passthrough, "site", { value: void 0 });
1269
1458
  passthrough.scriptTag = () => "";
1270
- passthrough.status = () => ({ enabled: false, collector: "off", since: Date.now(), failOpen: false, queued: 0, blocking: "off" });
1459
+ const since = Date.now();
1460
+ passthrough.status = () => ({ enabled: false, collector: "off", since, failOpen: false, queued: 0, blocking: "off" });
1271
1461
  passthrough.flush = async () => {
1272
1462
  };
1273
1463
  passthrough.close = async () => {
1274
1464
  };
1465
+ const off = async () => {
1466
+ throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
1467
+ };
1468
+ passthrough.visitor = off;
1469
+ passthrough.events = off;
1275
1470
  return passthrough;
1276
1471
  }
1277
1472
  const site = parsed.site;
@@ -1293,9 +1488,9 @@ function reguard(options = {}) {
1293
1488
  const platform = detectPlatform(typeof process !== "undefined" ? process.env : void 0);
1294
1489
  const blockCfg = o.block;
1295
1490
  const allDry = !blockCfg || BLOCK_REASONS.every((r) => blockCfg.dryRun.has(r));
1296
- const skipped = skipMatcher(o.collect.skip);
1297
- const ignored = o.ignore.length ? skipMatcher(o.ignore) : void 0;
1298
- const required = blockCfg?.require ? skipMatcher(blockCfg.require) : void 0;
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;
1299
1494
  const allowList = blockCfg?.allow.length ? skipMatcher(blockCfg.allow) : void 0;
1300
1495
  const denyMaps = (o.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
1301
1496
  const tagSettings = { site, collect: o.collect, fresh: freshSeconds(blockCfg), cookieDomain: o.cookieDomain };
@@ -1315,7 +1510,9 @@ function reguard(options = {}) {
1315
1510
  const ip = normalizeIp(custom ?? void 0);
1316
1511
  a = ip ? { address: ip, internal: !isPublicIp(ip), via: "custom" } : resolveClientAddress({ peer, header: get }, "socket");
1317
1512
  } else {
1318
- const framework = req.app?.get?.("trust proxy") ? req.ip : void 0;
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;
1319
1516
  a = resolveClientAddress({ peer, header: get, framework }, o.clientIp, platform);
1320
1517
  }
1321
1518
  ADDRESS.set(req, a);
@@ -1394,15 +1591,15 @@ function reguard(options = {}) {
1394
1591
  const paceApi = pace ? rate(pace.api) : void 0;
1395
1592
  const paceMisses = pace ? rate(pace.notFound) : void 0;
1396
1593
  const cooling = /* @__PURE__ */ new Map();
1397
- const addressKey = (req) => `v:${visitorHash(parsed.secret, resolve(req).address)}`;
1594
+ const addressKey2 = (req) => `v:${visitorHash(parsed.secret, resolve(req).address)}`;
1398
1595
  const paceOf = (req, res, p) => {
1399
1596
  if (!pace || resolve(req).internal) return void 0;
1400
1597
  const get = (n) => header(req.headers, n);
1401
1598
  const now = Date.now();
1402
- const browser = get("sec-fetch-dest") !== void 0;
1599
+ const browser = presentsAsBrowser(browserHeaders(req.headers));
1403
1600
  const tool = browser ? void 0 : toolOf(get("user-agent"));
1404
1601
  if (!browser && !(tool && BENIGN_TOOL_FAMILIES.has(tool.family))) {
1405
- const key2 = addressKey(req);
1602
+ const key2 = addressKey2(req);
1406
1603
  res.once("finish", () => {
1407
1604
  const st = res.statusCode;
1408
1605
  if ((st === 404 || st === 405 || st === 410) && !paceMisses.take(key2)) {
@@ -1422,7 +1619,7 @@ function reguard(options = {}) {
1422
1619
  }
1423
1620
  if (required && matchesEither(required, p)) {
1424
1621
  const sid = cookieValue(get("cookie"), SESSION_COOKIE);
1425
- if (!paceApi.take(sid ? `s:${sid}` : addressKey(req), now)) return "api";
1622
+ if (!paceApi.take(sid ? `s:${sid}` : addressKey2(req), now)) return "api";
1426
1623
  }
1427
1624
  return void 0;
1428
1625
  };
@@ -1432,8 +1629,9 @@ function reguard(options = {}) {
1432
1629
  const dryCounts = /* @__PURE__ */ new Map();
1433
1630
  const dryTimer = setInterval(() => {
1434
1631
  if (!dryCounts.size) return;
1435
- const parts = [...dryCounts].map(([r, n]) => `${r} ${n}`).join(", ");
1436
- log.info(`dry run: would have answered ${[...dryCounts.values()].reduce((a, b) => a + b, 0)} requests in the last minute (${parts})`);
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})`);
1437
1635
  dryCounts.clear();
1438
1636
  }, 6e4);
1439
1637
  dryTimer.unref?.();
@@ -1468,9 +1666,11 @@ function reguard(options = {}) {
1468
1666
  const answer = async (req, res, d) => {
1469
1667
  const respond = blockCfg.respond;
1470
1668
  if (respond) {
1669
+ let threw = false;
1471
1670
  try {
1472
1671
  await respond(req, res, d);
1473
1672
  } catch (e) {
1673
+ threw = true;
1474
1674
  log.once("respond-threw", "error", `block.respond threw (${errorText(e)}): sent the default answer instead`);
1475
1675
  }
1476
1676
  if (res.writableEnded) return;
@@ -1478,7 +1678,7 @@ function reguard(options = {}) {
1478
1678
  res.end();
1479
1679
  return;
1480
1680
  }
1481
- 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");
1482
1682
  }
1483
1683
  defaultBlockResponse(req, res, d);
1484
1684
  };
@@ -1491,10 +1691,8 @@ function reguard(options = {}) {
1491
1691
  const init = { method: req.method, headers, redirect: "manual", signal: AbortSignal.timeout(o.timeoutMs) };
1492
1692
  if (req.method !== "GET" && req.method !== "HEAD") {
1493
1693
  const consumed = req.readableEnded || req._body === true;
1494
- if (!consumed) {
1495
- init.body = import_node_stream.Readable.toWeb(req);
1496
- init.duplex = "half";
1497
- } else if (req.body !== void 0) {
1694
+ if (!consumed) init.body = new Uint8Array(await readBody(req));
1695
+ else if (req.body !== void 0) {
1498
1696
  const b = req.body;
1499
1697
  init.body = Buffer.isBuffer(b) ? new Uint8Array(b) : typeof b === "string" ? b : JSON.stringify(b);
1500
1698
  }
@@ -1510,6 +1708,16 @@ function reguard(options = {}) {
1510
1708
  });
1511
1709
  const cookies = r.headers.getSetCookie?.() ?? [];
1512
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
+ }
1513
1721
  if (r.body && req.method !== "HEAD") await (0, import_promises.pipeline)(import_node_stream.Readable.fromWeb(r.body), res);
1514
1722
  else res.end();
1515
1723
  } catch (e) {
@@ -1624,6 +1832,9 @@ function reguard(options = {}) {
1624
1832
  });
1625
1833
  const blocking = !blockCfg ? "off" : allDry ? "dry run" : blockCfg.dryRun.size ? "partial dry run" : "on";
1626
1834
  Object.defineProperty(middleware, "site", { value: site });
1835
+ const api = reguardApi({ key, collector, fetch: doFetch, timeoutMs: o.timeoutMs });
1836
+ middleware.visitor = (id) => api.visitor(id);
1837
+ middleware.events = (q) => api.events(q);
1627
1838
  middleware.scriptTag = (opts) => renderScriptTag(tagSettings, opts?.nonce);
1628
1839
  middleware.status = () => ({
1629
1840
  enabled: true,
@@ -1792,7 +2003,7 @@ function createReDetect(opts, wiring = {}) {
1792
2003
  const timeoutMs = wiring.timeoutMs ?? 1e4;
1793
2004
  const addressFor = (req) => wiring.address?.(req) ?? addressOf(req);
1794
2005
  const collect = resolveCollect(opts.collect, (m) => log.once(`collect:${m}`, "warn", m));
1795
- const skipped = skipMatcher(collect.skip);
2006
+ const skipped = protectionMatcher(collect.skip);
1796
2007
  const forward = collect.requests;
1797
2008
  const siteTag = siteTagOf(opts.site, secret);
1798
2009
  const maxQueue = opts.maxQueue ?? 5e3;
@@ -1801,13 +2012,14 @@ function createReDetect(opts, wiring = {}) {
1801
2012
  let inflight;
1802
2013
  const pushed = /* @__PURE__ */ new Map();
1803
2014
  const PUSHED_TTL_MS = 10 * 6e4;
2015
+ const vidOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
1804
2016
  const isClaims = (c) => Array.isArray(c) && c.every((x) => !!x && typeof x.rule === "string" && typeof x.label === "string" && typeof x.stage === "string");
1805
2017
  const absorb = (body) => {
1806
2018
  const f = body?.flagged;
1807
2019
  if (!f) return;
1808
2020
  const now = Date.now();
1809
- for (const x of f.sessions ?? []) if (typeof x.sid === "string" && isClaims(x.claims)) pushed.set(`s:${x.sid}`, { claims: x.claims, until: now + PUSHED_TTL_MS });
1810
- for (const x of f.visitors ?? []) if (typeof x.visitor === "string" && isClaims(x.claims)) pushed.set(`v:${x.visitor}`, { claims: x.claims, until: now + PUSHED_TTL_MS });
2021
+ for (const x of f.sessions ?? []) if (typeof x.sid === "string" && isClaims(x.claims)) pushed.set(`s:${x.sid}`, { claims: x.claims, until: now + PUSHED_TTL_MS, vid: vidOf(x.vid) });
2022
+ for (const x of f.visitors ?? []) if (typeof x.visitor === "string" && isClaims(x.claims)) pushed.set(`v:${x.visitor}`, { claims: x.claims, until: now + PUSHED_TTL_MS, vid: vidOf(x.vid) });
1811
2023
  if (pushed.size > 5e4) {
1812
2024
  for (const [k, e] of pushed) if (e.until < now) pushed.delete(k);
1813
2025
  }
@@ -1816,14 +2028,18 @@ function createReDetect(opts, wiring = {}) {
1816
2028
  if (!pushed.size) return null;
1817
2029
  const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
1818
2030
  const a = addressFor(req);
1819
- 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 : "";
1820
2032
  const now = Date.now();
1821
2033
  const claims = [];
2034
+ let vid;
1822
2035
  for (const k of [sid ? `s:${sid}` : "", address ? `v:${visitorHash(secret, address)}` : ""]) {
1823
2036
  const e = k ? pushed.get(k) : void 0;
1824
- if (e && e.until > now) claims.push(...e.claims);
2037
+ if (e && e.until > now) {
2038
+ claims.push(...e.claims);
2039
+ vid ??= e.vid;
2040
+ }
1825
2041
  }
1826
- return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now) : null;
2042
+ return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now, vid) : null;
1827
2043
  };
1828
2044
  const flush = async () => {
1829
2045
  while (queue.length) {
@@ -1872,6 +2088,7 @@ function createReDetect(opts, wiring = {}) {
1872
2088
  const flushSoon = () => {
1873
2089
  if (queue.length && !inflight) inflight = flush().finally(() => inflight = void 0);
1874
2090
  };
2091
+ let lastUrgent = 0;
1875
2092
  const timer = setInterval(flushSoon, opts.flushIntervalMs ?? 2e3);
1876
2093
  timer.unref?.();
1877
2094
  const readVerdict = (cookieHeader) => readVerdictFrom(secret, opts.site, cookieHeader);
@@ -1883,19 +2100,19 @@ function createReDetect(opts, wiring = {}) {
1883
2100
  const secure = secureRequest(req);
1884
2101
  const decision = wiring.decided?.(req);
1885
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
+ });
1886
2113
  if (!sid && !opts.includeSessionless && !decision) {
1887
2114
  if (opts.watchSessionless === false || collect.addresses === "off") return;
1888
- const watch = watchworthy({
1889
- userAgent: header(h, "user-agent") ?? "",
1890
- acceptLanguage: header(h, "accept-language"),
1891
- accept: header(h, "accept"),
1892
- secFetchMode: header(h, "sec-fetch-mode"),
1893
- secChUa: header(h, "sec-ch-ua"),
1894
- secure,
1895
- path: url.split("?")[0] ?? url,
1896
- status: res.statusCode
1897
- });
1898
- if (!watch) return;
2115
+ if (!tool) return;
1899
2116
  }
1900
2117
  const a = addressFor(req);
1901
2118
  const visitor = !sid && a.address && collect.addresses !== "off" ? visitorHash(secret, a.address) : void 0;
@@ -1956,7 +2173,10 @@ function createReDetect(opts, wiring = {}) {
1956
2173
  ...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
1957
2174
  ...a.internal ? { internal: true } : {}
1958
2175
  });
1959
- if (decision) flushSoon();
2176
+ if (decision || tool && Date.now() - lastUrgent >= 500) {
2177
+ lastUrgent = Date.now();
2178
+ flushSoon();
2179
+ }
1960
2180
  } catch (e) {
1961
2181
  onError(e);
1962
2182
  }
@@ -2057,17 +2277,10 @@ function createReDetect(opts, wiring = {}) {
2057
2277
  }
2058
2278
 
2059
2279
  // src/fastify.ts
2060
- var FASTIFY_IP = /* @__PURE__ */ new WeakMap();
2061
2280
  function plugin(fastify, options, done) {
2062
2281
  let mw;
2063
2282
  try {
2064
- const trusted = !!fastify.initialConfig?.trustProxy;
2065
- mw = reguard(
2066
- trusted && options.clientIp === void 0 ? {
2067
- ...options,
2068
- clientIp: (req) => FASTIFY_IP.get(req) ?? null
2069
- } : options
2070
- );
2283
+ mw = reguard(options);
2071
2284
  } catch (e) {
2072
2285
  done(e);
2073
2286
  return;
@@ -2075,7 +2288,6 @@ function plugin(fastify, options, done) {
2075
2288
  for (const name of ["reguard", "reguardDecision"]) if (!fastify.hasRequestDecorator?.(name)) fastify.decorateRequest?.(name, null);
2076
2289
  fastify.addHook("onRequest", (request, reply, next) => {
2077
2290
  const raw = request.raw;
2078
- if (request.ip) FASTIFY_IP.set(raw, request.ip);
2079
2291
  let passed = false;
2080
2292
  const res = reply.raw;
2081
2293
  const writeHead = res.writeHead;