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
@@ -20,18 +20,23 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ ReguardApiError: () => ReguardApiError,
23
24
  ReguardConfigError: () => ReguardConfigError,
25
+ ReguardWebhookError: () => WebhookSignatureError,
24
26
  createReDetect: () => createReDetect,
25
27
  default: () => index_default,
26
28
  defaultBlockResponse: () => defaultBlockResponse,
27
29
  formatSiteKey: () => formatSiteKey,
28
30
  keyFingerprint: () => keyFingerprint,
29
31
  parseSiteKey: () => parseSiteKey,
30
- reguard: () => reguard
32
+ reguard: () => reguard,
33
+ reguardApi: () => reguardApi,
34
+ verifyWebhook: () => verifyWebhook
31
35
  });
32
36
  module.exports = __toCommonJS(index_exports);
33
37
  var import_node_crypto = require("node:crypto");
34
38
  var import_node_stream = require("node:stream");
39
+ var import_node_zlib = require("node:zlib");
35
40
  var import_promises = require("node:stream/promises");
36
41
 
37
42
  // ../shared/src/exchange.ts
@@ -294,6 +299,13 @@ function browserIncoherence(h) {
294
299
  }
295
300
  return reasons;
296
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
+ }
297
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;
298
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;
299
311
  var BROWSER_AUTOMATIC = /^\/(?:favicon\.ico|apple-touch-icon[\w.-]*\.png|browserconfig\.xml|site\.webmanifest|manifest\.json|\.well-known\/appspecific\/)/i;
@@ -377,18 +389,21 @@ function resolveCollect(input, warn = () => {
377
389
  }
378
390
  return out;
379
391
  }
380
- function skipMatcher(patterns) {
392
+ function skipMatcher(patterns, ignoreCase = false) {
381
393
  if (!patterns.length) return () => false;
382
394
  const res = patterns.map((p) => {
383
395
  const tail = p.endsWith("/*");
384
396
  const body = (tail ? p.slice(0, -2) : p).split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
385
- return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`);
397
+ return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`, ignoreCase ? "i" : "");
386
398
  });
387
399
  return (path) => {
388
400
  const p = path.split(/[?#]/)[0] ?? path;
389
401
  return res.some((re) => re.test(p));
390
402
  };
391
403
  }
404
+ function protectionMatcher(patterns) {
405
+ return skipMatcher(patterns, true);
406
+ }
392
407
  function collectAttributes(c) {
393
408
  const a = {};
394
409
  if (c.pages !== DEFAULT_COLLECT.pages) a["data-pages"] = c.pages;
@@ -471,6 +486,98 @@ var CLOUDFLARE_RANGES = [
471
486
  "2a06:98c0::/29",
472
487
  "2c0f:f248::/32"
473
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"];
474
581
  var NON_PUBLIC_RANGES = [
475
582
  "0.0.0.0/8",
476
583
  "10.0.0.0/8",
@@ -600,63 +707,73 @@ function inCidr(c, b) {
600
707
  return true;
601
708
  }
602
709
  var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
603
- var NON_PUBLIC = compile(NON_PUBLIC_RANGES);
604
- var CLOUDFLARE = compile(CLOUDFLARE_RANGES);
605
- function ipInRanges(address, ranges) {
606
- const b = parseIp(address);
607
- if (!b) return false;
608
- const cidrs = typeof ranges[0] === "string" ? compile(ranges) : ranges;
609
- 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`;
610
720
  }
611
721
  function isPublicIp(address) {
612
722
  const b = parseIp(address);
613
- return !!b && !NON_PUBLIC.some((c) => inCidr(c, b));
723
+ return !!b && !tables().nonPublic.some((c) => inCidr(c, b));
614
724
  }
615
- function chainOf(req) {
616
- const xff = req.header("x-forwarded-for") ?? "";
617
- const entries = xff.split(",").map((s) => s.trim()).filter(Boolean).slice(-MAX_FORWARDED);
618
- 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);
619
727
  }
620
728
  var result = (address, via) => ({ address, internal: !isPublicIp(address), via });
621
- function walk(req, trusted, via) {
622
- const chain = chainOf(req);
623
- 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 = "";
624
733
  for (let i = chain.length - 1; i >= 0; i--) {
625
- const ip = normalizeIp(chain[i]);
626
- if (!ip) continue;
627
- last ||= ip;
734
+ const ip = chain[i];
628
735
  const b = parseIp(ip);
629
- if (NON_PUBLIC.some((c) => inCidr(c, b)) || trusted.some((c) => inCidr(c, b))) continue;
630
- 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 };
631
747
  }
632
- 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);
633
756
  }
634
757
  function resolveClientAddress(req, mode = "auto", platform = null) {
635
758
  const peer = normalizeIp(req.peer) ?? "";
636
759
  if (mode === "socket") return result(peer, "socket");
637
760
  if (typeof mode === "object" && "header" in mode) {
638
- const first = req.header(mode.header.toLowerCase())?.split(",")[0];
639
- const ip = normalizeIp(first);
761
+ const ip = headerAddress(req, mode.header.toLowerCase());
640
762
  return ip ? result(ip, "header") : result(peer, "socket");
641
763
  }
642
764
  if (typeof mode === "object" && "hops" in mode) {
643
- const chain = chainOf(req).map((t) => normalizeIp(t)).filter((x) => !!x);
644
- if (!chain.length) return result("", "socket");
645
- const at = Math.max(0, chain.length - 1 - mode.hops);
646
- 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");
647
768
  }
648
- 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);
649
770
  const framework = normalizeIp(req.framework);
650
771
  if (framework) return result(framework, "framework");
651
772
  if (platform) {
652
- const ip = normalizeIp(req.header(PLATFORM_HEADERS[platform])?.split(",")[0]);
773
+ const ip = headerAddress(req, PLATFORM_HEADERS[platform]);
653
774
  if (ip) return result(ip, `platform:${platform}`);
654
775
  }
655
- if (peer && ipInRanges(peer, CLOUDFLARE)) {
656
- const ip = normalizeIp(req.header("cf-connecting-ip"));
657
- if (ip) return result(ip, "cloudflare");
658
- }
659
- return walk(req, [], "forwarded");
776
+ return walk(req, [], "forwarded", true);
660
777
  }
661
778
  function clientIpModeProblem(value) {
662
779
  if (value === "auto" || value === "socket") return null;
@@ -706,7 +823,7 @@ function canonicalPath(target) {
706
823
  const cut = t.search(/[?#]/);
707
824
  let raw = cut === -1 ? t : t.slice(0, cut);
708
825
  if (!raw.startsWith("/")) raw = `/${raw}`;
709
- return { raw, decoded: normalizeSegments(decodeOnce(raw)) };
826
+ return { raw, decoded: normalizeSegments(decodeOnce(raw).replace(/\\/g, "/")) };
710
827
  }
711
828
  function matchesEither(matcher, p) {
712
829
  return matcher(p.raw) || matcher(p.decoded);
@@ -718,12 +835,71 @@ function isSourceMapPath(p) {
718
835
  return /\.map$/i.test(p.raw) || /\.map$/i.test(p.decoded);
719
836
  }
720
837
 
838
+ // ../shared/src/webhooks.ts
839
+ var WEBHOOK_TOLERANCE_SECONDS = 300;
840
+ var WebhookSignatureError = class extends Error {
841
+ constructor(code, message) {
842
+ super(message);
843
+ this.code = code;
844
+ this.name = "ReguardWebhookError";
845
+ }
846
+ };
847
+ var enc2 = new TextEncoder();
848
+ function hmacKey2(secret) {
849
+ return crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
850
+ }
851
+ function signedBytes(timestamp, payload) {
852
+ const head = enc2.encode(`${timestamp}.`);
853
+ const body = typeof payload === "string" ? enc2.encode(payload) : payload;
854
+ const out = new Uint8Array(new ArrayBuffer(head.length + body.length));
855
+ out.set(head, 0);
856
+ out.set(body, head.length);
857
+ return out;
858
+ }
859
+ function unhex(s) {
860
+ const out = new Uint8Array(new ArrayBuffer(s.length / 2));
861
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
862
+ return out;
863
+ }
864
+ function parseWebhookSignature(header2) {
865
+ let t;
866
+ const v1 = [];
867
+ for (const part of header2.split(",")) {
868
+ const i = part.indexOf("=");
869
+ if (i < 1) continue;
870
+ const k = part.slice(0, i).trim();
871
+ const v = part.slice(i + 1).trim();
872
+ if (k === "t" && /^\d{1,12}$/.test(v)) t = Number(v);
873
+ else if (k === "v1" && /^[0-9a-f]{64}$/.test(v)) v1.push(v);
874
+ }
875
+ return t === void 0 || !v1.length ? null : { t, v1 };
876
+ }
877
+ async function verifyWebhookSignature(payload, header2, secret, options = {}) {
878
+ if (!secret) throw new WebhookSignatureError("missing_secret", "No webhook signing secret: pass it, or set REGUARD_WEBHOOK_SECRET.");
879
+ if (!header2) throw new WebhookSignatureError("missing_signature", "No Reguard-Signature header on this request.");
880
+ const parsed = parseWebhookSignature(header2);
881
+ if (!parsed) throw new WebhookSignatureError("malformed_signature", "The Reguard-Signature header isn't in the form t=\u2026,v1=\u2026.");
882
+ const tolerance = options.tolerance ?? WEBHOOK_TOLERANCE_SECONDS;
883
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
884
+ if (tolerance > 0 && Math.abs(now - parsed.t) > tolerance) {
885
+ throw new WebhookSignatureError("expired", `The delivery is signed ${Math.abs(now - parsed.t)} s from now, more than the ${tolerance} s allowed (a replay, or a clock that's off).`);
886
+ }
887
+ const key = await hmacKey2(secret);
888
+ const data = signedBytes(parsed.t, payload);
889
+ for (const sig of parsed.v1) {
890
+ if (await crypto.subtle.verify("HMAC", key, unhex(sig), data)) return;
891
+ }
892
+ throw new WebhookSignatureError("bad_signature", "The signature doesn't match: check the signing secret, and pass the raw request body.");
893
+ }
894
+
721
895
  // src/core.ts
722
896
  var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
897
+ var visitorIdOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
723
898
  function withFlagged(p, source = "browser") {
724
899
  return {
725
900
  ...p,
726
901
  source,
902
+ visitor: visitorIdOf(p.vid) ?? null,
727
903
  flagged({ labels, minStage = "candidate" } = {}) {
728
904
  const want = typeof labels === "string" ? [labels] : labels?.length ? labels : void 0;
729
905
  const rank = STAGE_RANK[minStage] ?? 0;
@@ -736,8 +912,9 @@ function mergeVerdicts(browser, pushed) {
736
912
  if (!browser) return withFlagged(pushed, "server");
737
913
  const rules = new Set(browser.claims.map((c) => `${c.rule}|${c.label}|${c.stage}`));
738
914
  const claims = [...browser.claims, ...pushed.claims.filter((c) => !rules.has(`${c.rule}|${c.label}|${c.stage}`))];
739
- const { source: _s, flagged: _f, ...payload } = browser;
740
- return withFlagged({ ...payload, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
915
+ const { source: _s, flagged: _f, visitor: _v, ...payload } = browser;
916
+ const vid = visitorIdOf(payload.vid) ?? visitorIdOf(pushed.vid);
917
+ return withFlagged({ ...payload, ...vid ? { vid } : {}, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
741
918
  }
742
919
  async function readVerdictFrom(secret, site, cookieHeader) {
743
920
  const token = cookieValue(cookieHeader, VERDICT_COOKIE);
@@ -776,8 +953,8 @@ function freshSeconds(cfg) {
776
953
  function verdictAgeMs(v, now = Date.now()) {
777
954
  return now - (v.exp - VERDICT_TTL_MS);
778
955
  }
779
- function pushedVerdict(sid, site, claims, now = Date.now()) {
780
- return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4 }, "server");
956
+ function pushedVerdict(sid, site, claims, now = Date.now(), vid) {
957
+ return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4, ...vid ? { vid } : {} }, "server");
781
958
  }
782
959
  var ANSWER_CODES = { flagged: "reguard.blocked", flagged_server: "reguard.blocked", require: "reguard.require", pace: "reguard.pace" };
783
960
  var RETRY_AFTER = { flagged: 120, flagged_server: 120, require: 5, pace: 2 };
@@ -845,14 +1022,16 @@ var fail = (option, code, detail) => {
845
1022
  var show = (v) => typeof v === "function" ? "a function" : JSON.stringify(v) ?? String(v);
846
1023
  var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
847
1024
  var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
848
- 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();
849
1027
  for (const k of Object.keys(obj)) {
850
1028
  if (obj[k] === void 0 || allowed.includes(k)) continue;
851
1029
  const path = prefix ? `${prefix}.${k}` : k;
852
1030
  if (moved[k]) fail(path, "removed_option", `was removed: ${moved[k]}`);
853
- const c = camel(k).replace(/Seconds$|Secs$/, "Ms");
854
- const hint = allowed.find((a) => a === c || a === camel(k) || a.toLowerCase() === k.toLowerCase());
855
- 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}?)` : ""}`);
856
1035
  }
857
1036
  }
858
1037
  function checkBoolean(v, option) {
@@ -1047,7 +1226,7 @@ function checkOptions(options) {
1047
1226
  if (options === void 0 || options === null) options = {};
1048
1227
  if (!isObject(options)) fail("options", "invalid_type", `must be an object (got ${show(options)})`);
1049
1228
  const o = options;
1050
- checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS);
1229
+ checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS, { under: "block", keys: BLOCK_KEYS });
1051
1230
  if (typeof o.ignore === "function") fail("ignore", "invalid_type", "is now a list of paths; use ignoreIf for a function");
1052
1231
  return {
1053
1232
  key: checkString(o.key, "key"),
@@ -1153,6 +1332,68 @@ var Health = class {
1153
1332
  }
1154
1333
  };
1155
1334
 
1335
+ // src/api.ts
1336
+ var ReguardApiError = class extends Error {
1337
+ constructor(status, message) {
1338
+ super(message);
1339
+ this.status = status;
1340
+ this.name = "ReguardApiError";
1341
+ }
1342
+ };
1343
+ function reguardApi(options = {}) {
1344
+ const key = (options.key?.trim() || envValue("REGUARD_KEY"))?.trim();
1345
+ 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)");
1346
+ const base = collectorBase(options.collector || envValue("REGUARD_COLLECTOR"));
1347
+ const doFetch = options.fetch ?? fetch;
1348
+ const timeoutMs = options.timeoutMs ?? 1e4;
1349
+ async function get(path) {
1350
+ if (!key) throw new ReguardApiError(0, "No site key: pass { key } or set REGUARD_KEY.");
1351
+ if (!parseSiteKey(key)?.site) throw new ReguardApiError(0, "REGUARD_KEY isn't a site key (rgk.<site>.v<n>.\u2026).");
1352
+ let res;
1353
+ try {
1354
+ res = await doFetch(`${base}${path}`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
1355
+ } catch (e) {
1356
+ throw new ReguardApiError(0, `Reguard's API can't be reached: ${e.message}`);
1357
+ }
1358
+ const parsed = await res.json().catch(() => null);
1359
+ const body = parsed && typeof parsed === "object" ? parsed : {};
1360
+ if (!res.ok) throw new ReguardApiError(res.status, typeof body.error === "string" && body.error ? body.error : `Reguard's API answered ${res.status}`);
1361
+ return body;
1362
+ }
1363
+ return {
1364
+ async visitor(id) {
1365
+ if (!visitorIdOf(id)) throw new ReguardApiError(400, "Not a visitor id: they look like vis_ followed by 22 characters.");
1366
+ return (await get(`/v1/visitors/${id}`)).visitor;
1367
+ },
1368
+ events({ after, limit, types } = {}) {
1369
+ const q = new URLSearchParams();
1370
+ if (after) q.set("after", after);
1371
+ if (typeof limit === "number" && Number.isInteger(limit) && limit > 0) q.set("limit", String(limit));
1372
+ if (types?.length) q.set("type", types.join(","));
1373
+ const qs = q.toString();
1374
+ return get(`/v1/events${qs ? `?${qs}` : ""}`);
1375
+ }
1376
+ };
1377
+ }
1378
+ async function verifyWebhook(payload, signature, secret, options = {}) {
1379
+ if (typeof payload !== "string" && !(payload instanceof Uint8Array) && !(payload instanceof ArrayBuffer)) {
1380
+ throw new TypeError(
1381
+ '[reguard] verifyWebhook needs the raw request body (a string or bytes), not parsed JSON: in Express, use express.raw({ type: "application/json" }) on this route.'
1382
+ );
1383
+ }
1384
+ const raw = payload instanceof ArrayBuffer ? new Uint8Array(payload) : payload;
1385
+ const header2 = Array.isArray(signature) ? signature[0] : signature;
1386
+ await verifyWebhookSignature(raw, header2, secret || envValue("REGUARD_WEBHOOK_SECRET"), options);
1387
+ let event;
1388
+ try {
1389
+ event = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw));
1390
+ } catch {
1391
+ throw new WebhookSignatureError("bad_payload", "The body isn't JSON (a Slack or Discord URL gets messages, not events).");
1392
+ }
1393
+ if (!event || typeof event.id !== "string" || typeof event.type !== "string") throw new WebhookSignatureError("bad_payload", "The body isn't a Reguard event.");
1394
+ return event;
1395
+ }
1396
+
1156
1397
  // src/index.ts
1157
1398
  var PREFIX = "/_s";
1158
1399
  var NOT_FORWARDED = /* @__PURE__ */ new Set([
@@ -1175,7 +1416,31 @@ var STRIP_FROM_RESPONSE = /* @__PURE__ */ new Set(["content-encoding", "content-
1175
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)/;
1176
1417
  var SCAN_LIMIT = 64 * 1024;
1177
1418
  function visitorHash(secret, address) {
1178
- 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);
1179
1444
  }
1180
1445
  function keyFingerprint(secret) {
1181
1446
  return (0, import_node_crypto.createHash)("sha256").update(`reguard-key:${secret}`).digest("base64url").slice(0, 8);
@@ -1266,18 +1531,24 @@ function reguard(options = {}) {
1266
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.`
1267
1532
  );
1268
1533
  const passthrough = ((req, _res, next) => {
1269
- req.reguard = null;
1270
- req.reguardDecision = null;
1271
- req.reDetect = null;
1534
+ req.reguard ??= null;
1535
+ req.reguardDecision ??= null;
1536
+ req.reDetect ??= null;
1272
1537
  next();
1273
1538
  });
1274
1539
  Object.defineProperty(passthrough, "site", { value: void 0 });
1275
1540
  passthrough.scriptTag = () => "";
1276
- 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" });
1277
1543
  passthrough.flush = async () => {
1278
1544
  };
1279
1545
  passthrough.close = async () => {
1280
1546
  };
1547
+ const off = async () => {
1548
+ throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
1549
+ };
1550
+ passthrough.visitor = off;
1551
+ passthrough.events = off;
1281
1552
  return passthrough;
1282
1553
  }
1283
1554
  const site = parsed.site;
@@ -1299,9 +1570,9 @@ function reguard(options = {}) {
1299
1570
  const platform = detectPlatform(typeof process !== "undefined" ? process.env : void 0);
1300
1571
  const blockCfg = o.block;
1301
1572
  const allDry = !blockCfg || BLOCK_REASONS.every((r) => blockCfg.dryRun.has(r));
1302
- const skipped = skipMatcher(o.collect.skip);
1303
- const ignored = o.ignore.length ? skipMatcher(o.ignore) : void 0;
1304
- 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;
1305
1576
  const allowList = blockCfg?.allow.length ? skipMatcher(blockCfg.allow) : void 0;
1306
1577
  const denyMaps = (o.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
1307
1578
  const tagSettings = { site, collect: o.collect, fresh: freshSeconds(blockCfg), cookieDomain: o.cookieDomain };
@@ -1321,7 +1592,9 @@ function reguard(options = {}) {
1321
1592
  const ip = normalizeIp(custom ?? void 0);
1322
1593
  a = ip ? { address: ip, internal: !isPublicIp(ip), via: "custom" } : resolveClientAddress({ peer, header: get }, "socket");
1323
1594
  } else {
1324
- 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;
1325
1598
  a = resolveClientAddress({ peer, header: get, framework }, o.clientIp, platform);
1326
1599
  }
1327
1600
  ADDRESS.set(req, a);
@@ -1400,15 +1673,15 @@ function reguard(options = {}) {
1400
1673
  const paceApi = pace ? rate(pace.api) : void 0;
1401
1674
  const paceMisses = pace ? rate(pace.notFound) : void 0;
1402
1675
  const cooling = /* @__PURE__ */ new Map();
1403
- const addressKey = (req) => `v:${visitorHash(parsed.secret, resolve(req).address)}`;
1676
+ const addressKey2 = (req) => `v:${visitorHash(parsed.secret, resolve(req).address)}`;
1404
1677
  const paceOf = (req, res, p) => {
1405
1678
  if (!pace || resolve(req).internal) return void 0;
1406
1679
  const get = (n) => header(req.headers, n);
1407
1680
  const now = Date.now();
1408
- const browser = get("sec-fetch-dest") !== void 0;
1681
+ const browser = presentsAsBrowser(browserHeaders(req.headers));
1409
1682
  const tool = browser ? void 0 : toolOf(get("user-agent"));
1410
1683
  if (!browser && !(tool && BENIGN_TOOL_FAMILIES.has(tool.family))) {
1411
- const key2 = addressKey(req);
1684
+ const key2 = addressKey2(req);
1412
1685
  res.once("finish", () => {
1413
1686
  const st = res.statusCode;
1414
1687
  if ((st === 404 || st === 405 || st === 410) && !paceMisses.take(key2)) {
@@ -1428,7 +1701,7 @@ function reguard(options = {}) {
1428
1701
  }
1429
1702
  if (required && matchesEither(required, p)) {
1430
1703
  const sid = cookieValue(get("cookie"), SESSION_COOKIE);
1431
- if (!paceApi.take(sid ? `s:${sid}` : addressKey(req), now)) return "api";
1704
+ if (!paceApi.take(sid ? `s:${sid}` : addressKey2(req), now)) return "api";
1432
1705
  }
1433
1706
  return void 0;
1434
1707
  };
@@ -1438,8 +1711,9 @@ function reguard(options = {}) {
1438
1711
  const dryCounts = /* @__PURE__ */ new Map();
1439
1712
  const dryTimer = setInterval(() => {
1440
1713
  if (!dryCounts.size) return;
1441
- const parts = [...dryCounts].map(([r, n]) => `${r} ${n}`).join(", ");
1442
- 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})`);
1443
1717
  dryCounts.clear();
1444
1718
  }, 6e4);
1445
1719
  dryTimer.unref?.();
@@ -1474,9 +1748,11 @@ function reguard(options = {}) {
1474
1748
  const answer = async (req, res, d) => {
1475
1749
  const respond = blockCfg.respond;
1476
1750
  if (respond) {
1751
+ let threw = false;
1477
1752
  try {
1478
1753
  await respond(req, res, d);
1479
1754
  } catch (e) {
1755
+ threw = true;
1480
1756
  log.once("respond-threw", "error", `block.respond threw (${errorText(e)}): sent the default answer instead`);
1481
1757
  }
1482
1758
  if (res.writableEnded) return;
@@ -1484,7 +1760,7 @@ function reguard(options = {}) {
1484
1760
  res.end();
1485
1761
  return;
1486
1762
  }
1487
- 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");
1488
1764
  }
1489
1765
  defaultBlockResponse(req, res, d);
1490
1766
  };
@@ -1497,10 +1773,8 @@ function reguard(options = {}) {
1497
1773
  const init = { method: req.method, headers, redirect: "manual", signal: AbortSignal.timeout(o.timeoutMs) };
1498
1774
  if (req.method !== "GET" && req.method !== "HEAD") {
1499
1775
  const consumed = req.readableEnded || req._body === true;
1500
- if (!consumed) {
1501
- init.body = import_node_stream.Readable.toWeb(req);
1502
- init.duplex = "half";
1503
- } else if (req.body !== void 0) {
1776
+ if (!consumed) init.body = new Uint8Array(await readBody(req));
1777
+ else if (req.body !== void 0) {
1504
1778
  const b = req.body;
1505
1779
  init.body = Buffer.isBuffer(b) ? new Uint8Array(b) : typeof b === "string" ? b : JSON.stringify(b);
1506
1780
  }
@@ -1516,6 +1790,16 @@ function reguard(options = {}) {
1516
1790
  });
1517
1791
  const cookies = r.headers.getSetCookie?.() ?? [];
1518
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
+ }
1519
1803
  if (r.body && req.method !== "HEAD") await (0, import_promises.pipeline)(import_node_stream.Readable.fromWeb(r.body), res);
1520
1804
  else res.end();
1521
1805
  } catch (e) {
@@ -1630,6 +1914,9 @@ function reguard(options = {}) {
1630
1914
  });
1631
1915
  const blocking = !blockCfg ? "off" : allDry ? "dry run" : blockCfg.dryRun.size ? "partial dry run" : "on";
1632
1916
  Object.defineProperty(middleware, "site", { value: site });
1917
+ const api = reguardApi({ key, collector, fetch: doFetch, timeoutMs: o.timeoutMs });
1918
+ middleware.visitor = (id) => api.visitor(id);
1919
+ middleware.events = (q) => api.events(q);
1633
1920
  middleware.scriptTag = (opts) => renderScriptTag(tagSettings, opts?.nonce);
1634
1921
  middleware.status = () => ({
1635
1922
  enabled: true,
@@ -1799,7 +2086,7 @@ function createReDetect(opts, wiring = {}) {
1799
2086
  const timeoutMs = wiring.timeoutMs ?? 1e4;
1800
2087
  const addressFor = (req) => wiring.address?.(req) ?? addressOf(req);
1801
2088
  const collect = resolveCollect(opts.collect, (m) => log.once(`collect:${m}`, "warn", m));
1802
- const skipped = skipMatcher(collect.skip);
2089
+ const skipped = protectionMatcher(collect.skip);
1803
2090
  const forward = collect.requests;
1804
2091
  const siteTag = siteTagOf(opts.site, secret);
1805
2092
  const maxQueue = opts.maxQueue ?? 5e3;
@@ -1808,13 +2095,14 @@ function createReDetect(opts, wiring = {}) {
1808
2095
  let inflight;
1809
2096
  const pushed = /* @__PURE__ */ new Map();
1810
2097
  const PUSHED_TTL_MS = 10 * 6e4;
2098
+ const vidOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
1811
2099
  const isClaims = (c) => Array.isArray(c) && c.every((x) => !!x && typeof x.rule === "string" && typeof x.label === "string" && typeof x.stage === "string");
1812
2100
  const absorb = (body) => {
1813
2101
  const f = body?.flagged;
1814
2102
  if (!f) return;
1815
2103
  const now = Date.now();
1816
- 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 });
1817
- 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 });
2104
+ 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) });
2105
+ 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) });
1818
2106
  if (pushed.size > 5e4) {
1819
2107
  for (const [k, e] of pushed) if (e.until < now) pushed.delete(k);
1820
2108
  }
@@ -1823,14 +2111,18 @@ function createReDetect(opts, wiring = {}) {
1823
2111
  if (!pushed.size) return null;
1824
2112
  const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
1825
2113
  const a = addressFor(req);
1826
- 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 : "";
1827
2115
  const now = Date.now();
1828
2116
  const claims = [];
2117
+ let vid;
1829
2118
  for (const k of [sid ? `s:${sid}` : "", address ? `v:${visitorHash(secret, address)}` : ""]) {
1830
2119
  const e = k ? pushed.get(k) : void 0;
1831
- if (e && e.until > now) claims.push(...e.claims);
2120
+ if (e && e.until > now) {
2121
+ claims.push(...e.claims);
2122
+ vid ??= e.vid;
2123
+ }
1832
2124
  }
1833
- return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now) : null;
2125
+ return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now, vid) : null;
1834
2126
  };
1835
2127
  const flush = async () => {
1836
2128
  while (queue.length) {
@@ -1879,6 +2171,7 @@ function createReDetect(opts, wiring = {}) {
1879
2171
  const flushSoon = () => {
1880
2172
  if (queue.length && !inflight) inflight = flush().finally(() => inflight = void 0);
1881
2173
  };
2174
+ let lastUrgent = 0;
1882
2175
  const timer = setInterval(flushSoon, opts.flushIntervalMs ?? 2e3);
1883
2176
  timer.unref?.();
1884
2177
  const readVerdict = (cookieHeader) => readVerdictFrom(secret, opts.site, cookieHeader);
@@ -1890,19 +2183,19 @@ function createReDetect(opts, wiring = {}) {
1890
2183
  const secure = secureRequest(req);
1891
2184
  const decision = wiring.decided?.(req);
1892
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
+ });
1893
2196
  if (!sid && !opts.includeSessionless && !decision) {
1894
2197
  if (opts.watchSessionless === false || collect.addresses === "off") return;
1895
- const watch = watchworthy({
1896
- userAgent: header(h, "user-agent") ?? "",
1897
- acceptLanguage: header(h, "accept-language"),
1898
- accept: header(h, "accept"),
1899
- secFetchMode: header(h, "sec-fetch-mode"),
1900
- secChUa: header(h, "sec-ch-ua"),
1901
- secure,
1902
- path: url.split("?")[0] ?? url,
1903
- status: res.statusCode
1904
- });
1905
- if (!watch) return;
2198
+ if (!tool) return;
1906
2199
  }
1907
2200
  const a = addressFor(req);
1908
2201
  const visitor = !sid && a.address && collect.addresses !== "off" ? visitorHash(secret, a.address) : void 0;
@@ -1963,7 +2256,10 @@ function createReDetect(opts, wiring = {}) {
1963
2256
  ...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
1964
2257
  ...a.internal ? { internal: true } : {}
1965
2258
  });
1966
- if (decision) flushSoon();
2259
+ if (decision || tool && Date.now() - lastUrgent >= 500) {
2260
+ lastUrgent = Date.now();
2261
+ flushSoon();
2262
+ }
1967
2263
  } catch (e) {
1968
2264
  onError(e);
1969
2265
  }
@@ -2064,11 +2360,15 @@ function createReDetect(opts, wiring = {}) {
2064
2360
  }
2065
2361
  // Annotate the CommonJS export names for ESM import in node:
2066
2362
  0 && (module.exports = {
2363
+ ReguardApiError,
2067
2364
  ReguardConfigError,
2365
+ ReguardWebhookError,
2068
2366
  createReDetect,
2069
2367
  defaultBlockResponse,
2070
2368
  formatSiteKey,
2071
2369
  keyFingerprint,
2072
2370
  parseSiteKey,
2073
- reguard
2371
+ reguard,
2372
+ reguardApi,
2373
+ verifyWebhook
2074
2374
  });