reguard 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -76,8 +76,8 @@ Dry-run decisions are on `req.reguardDecision` and in the dashboard as "would ha
76
76
 
77
77
  - **Fastify:** `import reguard from "reguard/fastify"` then `await app.register(reguard, { block: true })`;
78
78
  reads `request.ip` when `trustProxy` is set, and sets `request.reguard`.
79
- - **Next.js:** `withReguard()` in `next.config`, `<Script {...reguardScriptProps()} />`, and
80
- `reguardMiddleware({ block: true })` in `middleware.ts` (or `proxy.ts`), from `reguard/next`.
79
+ - **Next.js:** `reguardMiddleware({ block: true })` in `middleware.ts` (or `proxy.ts`), which also
80
+ serves `/_s/*`, and `<Script {...reguardScriptProps()} />`, from `reguard/next`.
81
81
  - **Hono, Remix, SvelteKit, Astro, Bun, Deno, Workers:** `reguardFetch()` from `reguard/fetch`, then
82
82
  `export default { fetch: rg.wrap(app.fetch) }`.
83
83
 
@@ -268,6 +268,13 @@ function browserIncoherence(h) {
268
268
  }
269
269
  return reasons;
270
270
  }
271
+ function presentsAsBrowser(h) {
272
+ const ua = h.userAgent ?? "";
273
+ if (!/^Mozilla\/5\.0 \(/.test(ua) || !h.secFetchDest) return false;
274
+ const tool = toolOf(ua);
275
+ if (tool && tool.family !== "headless_browser") return false;
276
+ return browserIncoherence(h).length === 0;
277
+ }
271
278
  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;
272
279
  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;
273
280
  var BROWSER_AUTOMATIC = /^\/(?:favicon\.ico|apple-touch-icon[\w.-]*\.png|browserconfig\.xml|site\.webmanifest|manifest\.json|\.well-known\/appspecific\/)/i;
@@ -351,18 +358,21 @@ function resolveCollect(input, warn = () => {
351
358
  }
352
359
  return out;
353
360
  }
354
- function skipMatcher(patterns) {
361
+ function skipMatcher(patterns, ignoreCase = false) {
355
362
  if (!patterns.length) return () => false;
356
363
  const res = patterns.map((p) => {
357
364
  const tail = p.endsWith("/*");
358
365
  const body = (tail ? p.slice(0, -2) : p).split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
359
- return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`);
366
+ return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`, ignoreCase ? "i" : "");
360
367
  });
361
368
  return (path) => {
362
369
  const p = path.split(/[?#]/)[0] ?? path;
363
370
  return res.some((re) => re.test(p));
364
371
  };
365
372
  }
373
+ function protectionMatcher(patterns) {
374
+ return skipMatcher(patterns, true);
375
+ }
366
376
  function collectAttributes(c) {
367
377
  const a = {};
368
378
  if (c.pages !== DEFAULT_COLLECT.pages) a["data-pages"] = c.pages;
@@ -445,6 +455,98 @@ var CLOUDFLARE_RANGES = [
445
455
  "2a06:98c0::/29",
446
456
  "2c0f:f248::/32"
447
457
  ];
458
+ var CLOUDFRONT_RANGES = [
459
+ "13.124.199.0/24",
460
+ "130.176.0.0/18",
461
+ "130.176.128.0/21",
462
+ "130.176.136.0/23",
463
+ "130.176.140.0/22",
464
+ "130.176.144.0/20",
465
+ "130.176.160.0/19",
466
+ "130.176.192.0/19",
467
+ "130.176.64.0/21",
468
+ "130.176.72.0/22",
469
+ "130.176.76.0/24",
470
+ "130.176.78.0/23",
471
+ "130.176.80.0/22",
472
+ "130.176.86.0/23",
473
+ "130.176.88.0/21",
474
+ "130.176.96.0/19",
475
+ "15.158.0.0/16",
476
+ "18.68.0.0/16",
477
+ "204.246.166.0/24",
478
+ "205.251.218.0/24",
479
+ "24.110.128.0/17",
480
+ "3.172.0.0/18",
481
+ "3.172.64.0/18",
482
+ "3.29.57.0/26",
483
+ "51.72.40.128/28",
484
+ "51.72.40.144/28",
485
+ "51.72.96.0/23",
486
+ "51.74.20.0/24",
487
+ "51.74.21.0/24",
488
+ "51.74.22.0/24",
489
+ "52.46.0.0/18",
490
+ "52.82.128.0/23",
491
+ "52.82.134.0/23",
492
+ "54.182.128.0/20",
493
+ "54.182.144.0/21",
494
+ "54.182.154.0/23",
495
+ "54.182.156.0/22",
496
+ "54.182.160.0/21",
497
+ "54.182.172.0/22",
498
+ "54.182.176.0/21",
499
+ "54.182.184.0/22",
500
+ "54.182.188.0/23",
501
+ "54.182.224.0/21",
502
+ "54.182.240.0/21",
503
+ "54.182.248.0/22",
504
+ "54.239.134.0/23",
505
+ "54.239.170.0/23",
506
+ "54.239.204.0/22",
507
+ "54.239.208.0/21",
508
+ "64.252.128.0/18",
509
+ "64.252.64.0/18",
510
+ "70.132.0.0/18",
511
+ "2001:3fc6:4::/48",
512
+ "2001:3fc6:5::/48",
513
+ "2406:da10:847f:a100::/56",
514
+ "2406:da11:438:2300::/56",
515
+ "2406:da12:4b:c200::/56",
516
+ "2406:da12:8b2e:9c00::/56",
517
+ "2406:da14:17bd:2f00::/56",
518
+ "2406:da14:80bb:ea00::/56",
519
+ "2406:da16:c01:c200::/56",
520
+ "2406:da18:9fa:1b00::/56",
521
+ "2406:da19:e19:4a00::/56",
522
+ "2406:da1a:6df:6c00::/56",
523
+ "2406:da1b:e7c:ad00::/56",
524
+ "2406:da1c:787:2b00::/56",
525
+ "2406:da1c:8d8c:4600::/56",
526
+ "2406:da1e:705:1600::/56",
527
+ "2406:da1f:396:9100::/56",
528
+ "2600:1f11:e79:a800::/56",
529
+ "2600:1f13:417:4d00::/56",
530
+ "2600:1f16:1923:3000::/56",
531
+ "2600:1f17:4356:f100::/56",
532
+ "2600:1f18:7530:7200::/56",
533
+ "2600:1f1a:4568:b500::/56",
534
+ "2600:1f1c:da:600::/56",
535
+ "2600:1f1e:a7:2300::/56",
536
+ "2600:9000:1000::/36",
537
+ "2600:9000:5200::/40",
538
+ "2600:9000:6000::/36",
539
+ "2a05:d011:531:1800::/56",
540
+ "2a05:d012:581:b400::/56",
541
+ "2a05:d014:1362:b000::/56",
542
+ "2a05:d016:9ed:de00::/56",
543
+ "2a05:d018:1a3a:2d00::/56",
544
+ "2a05:d019:80b:e300::/56",
545
+ "2a05:d01a:8a9:be00::/56",
546
+ "2a05:d01c:343:c300::/56",
547
+ "2a05:d025:e59:fb00::/56"
548
+ ];
549
+ var PORT_SUFFIXED_HEADERS = ["cloudfront-viewer-address"];
448
550
  var NON_PUBLIC_RANGES = [
449
551
  "0.0.0.0/8",
450
552
  "10.0.0.0/8",
@@ -574,63 +676,73 @@ function inCidr(c, b) {
574
676
  return true;
575
677
  }
576
678
  var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
577
- var NON_PUBLIC = compile(NON_PUBLIC_RANGES);
578
- var CLOUDFLARE = compile(CLOUDFLARE_RANGES);
579
- function ipInRanges(address, ranges) {
580
- const b = parseIp(address);
581
- if (!b) return false;
582
- const cidrs = typeof ranges[0] === "string" ? compile(ranges) : ranges;
583
- return cidrs.some((c) => inCidr(c, b));
679
+ var compiled;
680
+ var tables = () => compiled ??= { nonPublic: compile(NON_PUBLIC_RANGES), cloudflare: compile(CLOUDFLARE_RANGES), cloudfront: compile(CLOUDFRONT_RANGES) };
681
+ function addressKey(address) {
682
+ const ip = normalizeIp(address);
683
+ if (!ip) return "";
684
+ if (!ip.includes(":")) return ip;
685
+ const b = parseIp(ip);
686
+ const prefix = new Uint8Array(16);
687
+ prefix.set(b.subarray(0, 8));
688
+ return `${formatIp(prefix)}/64`;
584
689
  }
585
690
  function isPublicIp(address) {
586
691
  const b = parseIp(address);
587
- return !!b && !NON_PUBLIC.some((c) => inCidr(c, b));
692
+ return !!b && !tables().nonPublic.some((c) => inCidr(c, b));
588
693
  }
589
- function chainOf(req) {
590
- const xff = req.header("x-forwarded-for") ?? "";
591
- const entries = xff.split(",").map((s) => s.trim()).filter(Boolean).slice(-MAX_FORWARDED);
592
- return [...entries, req.peer];
694
+ function forwardedOf(req) {
695
+ return (req.header("x-forwarded-for") ?? "").split(",").map((t) => t.trim()).filter(Boolean).slice(-MAX_FORWARDED).map((t) => normalizeIp(t)).filter((x) => !!x);
593
696
  }
594
697
  var result = (address, via) => ({ address, internal: !isPublicIp(address), via });
595
- function walk(req, trusted, via) {
596
- const chain = chainOf(req);
597
- let last = "";
698
+ function walk(req, trusted, via, cdns) {
699
+ const peer = normalizeIp(req.peer);
700
+ const chain = [...forwardedOf(req), ...peer ? [peer] : []];
701
+ let edge = "";
598
702
  for (let i = chain.length - 1; i >= 0; i--) {
599
- const ip = normalizeIp(chain[i]);
600
- if (!ip) continue;
601
- last ||= ip;
703
+ const ip = chain[i];
602
704
  const b = parseIp(ip);
603
- if (NON_PUBLIC.some((c) => inCidr(c, b)) || trusted.some((c) => inCidr(c, b))) continue;
604
- return { address: ip, internal: false, via: i === chain.length - 1 ? "socket" : via };
705
+ const { nonPublic, cloudflare, cloudfront } = tables();
706
+ if (nonPublic.some((c) => inCidr(c, b)) || trusted.some((c) => inCidr(c, b))) continue;
707
+ if (cdns && cloudfront.some((c) => inCidr(c, b))) {
708
+ edge = ip;
709
+ continue;
710
+ }
711
+ if (cdns && cloudflare.some((c) => inCidr(c, b))) {
712
+ const client = normalizeIp(req.header("cf-connecting-ip"));
713
+ return client ? result(client, "cloudflare") : { address: ip, internal: false, via };
714
+ }
715
+ return { address: ip, internal: false, via: peer && i === chain.length - 1 ? "socket" : via };
605
716
  }
606
- return { address: last, internal: true, via: "socket" };
717
+ if (edge) return { address: edge, internal: false, via };
718
+ return { address: chain[chain.length - 1] ?? "", internal: true, via: "socket" };
719
+ }
720
+ function headerAddress(req, name) {
721
+ const first = req.header(name)?.split(",")[0]?.trim();
722
+ if (!first) return null;
723
+ if (PORT_SUFFIXED_HEADERS.includes(name) && !first.startsWith("[")) return normalizeIp(first.replace(/:\d{1,5}$/, ""));
724
+ return normalizeIp(first);
607
725
  }
608
726
  function resolveClientAddress(req, mode = "auto", platform = null) {
609
727
  const peer = normalizeIp(req.peer) ?? "";
610
728
  if (mode === "socket") return result(peer, "socket");
611
729
  if (typeof mode === "object" && "header" in mode) {
612
- const first = req.header(mode.header.toLowerCase())?.split(",")[0];
613
- const ip = normalizeIp(first);
730
+ const ip = headerAddress(req, mode.header.toLowerCase());
614
731
  return ip ? result(ip, "header") : result(peer, "socket");
615
732
  }
616
733
  if (typeof mode === "object" && "hops" in mode) {
617
- const chain = chainOf(req).map((t) => normalizeIp(t)).filter((x) => !!x);
618
- if (!chain.length) return result("", "socket");
619
- const at = Math.max(0, chain.length - 1 - mode.hops);
620
- return result(chain[at], at === chain.length - 1 ? "socket" : "hops");
734
+ const xff = forwardedOf(req);
735
+ if (xff.length < mode.hops) return walk(req, [], "hops", false);
736
+ return result(xff[xff.length - mode.hops], "hops");
621
737
  }
622
- if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies");
738
+ if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies", false);
623
739
  const framework = normalizeIp(req.framework);
624
740
  if (framework) return result(framework, "framework");
625
741
  if (platform) {
626
- const ip = normalizeIp(req.header(PLATFORM_HEADERS[platform])?.split(",")[0]);
742
+ const ip = headerAddress(req, PLATFORM_HEADERS[platform]);
627
743
  if (ip) return result(ip, `platform:${platform}`);
628
744
  }
629
- if (peer && ipInRanges(peer, CLOUDFLARE)) {
630
- const ip = normalizeIp(req.header("cf-connecting-ip"));
631
- if (ip) return result(ip, "cloudflare");
632
- }
633
- return walk(req, [], "forwarded");
745
+ return walk(req, [], "forwarded", true);
634
746
  }
635
747
  function clientIpModeProblem(value) {
636
748
  if (value === "auto" || value === "socket") return null;
@@ -680,7 +792,7 @@ function canonicalPath(target) {
680
792
  const cut = t.search(/[?#]/);
681
793
  let raw = cut === -1 ? t : t.slice(0, cut);
682
794
  if (!raw.startsWith("/")) raw = `/${raw}`;
683
- return { raw, decoded: normalizeSegments(decodeOnce(raw)) };
795
+ return { raw, decoded: normalizeSegments(decodeOnce(raw).replace(/\\/g, "/")) };
684
796
  }
685
797
  function matchesEither(matcher, p) {
686
798
  return matcher(p.raw) || matcher(p.decoded);
@@ -883,16 +995,19 @@ export {
883
995
  parseSiteKey,
884
996
  BENIGN_TOOL_FAMILIES,
885
997
  toolOf,
998
+ presentsAsBrowser,
886
999
  watchworthy,
887
1000
  requestKind,
888
1001
  pathTraits,
889
1002
  resolveCollect,
890
1003
  skipMatcher,
1004
+ protectionMatcher,
891
1005
  collectAttributes,
892
1006
  collectReport,
893
1007
  Allowance,
894
1008
  detectPlatform,
895
1009
  normalizeIp,
1010
+ addressKey,
896
1011
  isPublicIp,
897
1012
  resolveClientAddress,
898
1013
  clientIpModeProblem,
@@ -8,7 +8,7 @@ import {
8
8
  resolveCollect,
9
9
  verifyWebhookSignature,
10
10
  visitorIdOf
11
- } from "./chunk-CGXTVKRB.js";
11
+ } from "./chunk-2N762ZXU.js";
12
12
 
13
13
  // src/config.ts
14
14
  var ReguardConfigError = class extends TypeError {
@@ -30,14 +30,16 @@ var fail = (option, code, detail) => {
30
30
  var show = (v) => typeof v === "function" ? "a function" : JSON.stringify(v) ?? String(v);
31
31
  var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
32
32
  var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
33
- function checkKeys(obj, allowed, prefix, moved = {}) {
33
+ function checkKeys(obj, allowed, prefix, moved = {}, nested) {
34
+ const like = (k) => (a) => a === camel(k).replace(/Seconds$|Secs$/, "Ms") || a === camel(k) || a.toLowerCase() === k.toLowerCase();
34
35
  for (const k of Object.keys(obj)) {
35
36
  if (obj[k] === void 0 || allowed.includes(k)) continue;
36
37
  const path = prefix ? `${prefix}.${k}` : k;
37
38
  if (moved[k]) fail(path, "removed_option", `was removed: ${moved[k]}`);
38
- const c = camel(k).replace(/Seconds$|Secs$/, "Ms");
39
- const hint = allowed.find((a) => a === c || a === camel(k) || a.toLowerCase() === k.toLowerCase());
40
- fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${prefix ? `${prefix}.` : ""}${hint}?)` : ""}`);
39
+ const here = allowed.find(like(k));
40
+ const below = here ? void 0 : nested?.keys.find(like(k));
41
+ const hint = here ? `${prefix ? `${prefix}.` : ""}${here}` : below ? `${nested.under}.${below}` : void 0;
42
+ fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${hint}?)` : ""}`);
41
43
  }
42
44
  }
43
45
  function checkBoolean(v, option) {
@@ -232,7 +234,7 @@ function checkOptions(options) {
232
234
  if (options === void 0 || options === null) options = {};
233
235
  if (!isObject(options)) fail("options", "invalid_type", `must be an object (got ${show(options)})`);
234
236
  const o = options;
235
- checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS);
237
+ checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS, { under: "block", keys: BLOCK_KEYS });
236
238
  if (typeof o.ignore === "function") fail("ignore", "invalid_type", "is now a list of paths; use ignoreIf for a function");
237
239
  return {
238
240
  key: checkString(o.key, "key"),
@@ -14,12 +14,13 @@ import {
14
14
  checkNumber,
15
15
  makeLog,
16
16
  reguardApi
17
- } from "./chunk-W4FDH5AD.js";
17
+ } from "./chunk-4RD66ACT.js";
18
18
  import {
19
19
  Allowance,
20
20
  BENIGN_TOOL_FAMILIES,
21
21
  RETRY_AFTER,
22
22
  SESSION_COOKIE,
23
+ addressKey,
23
24
  canonicalPath,
24
25
  collectReport,
25
26
  collectorBase,
@@ -39,7 +40,9 @@ import {
39
40
  normalizeIp,
40
41
  parseSiteKey,
41
42
  pathTraits,
43
+ presentsAsBrowser,
42
44
  privateUrl,
45
+ protectionMatcher,
43
46
  pushedVerdict,
44
47
  readVerdictFrom,
45
48
  renderScriptTag,
@@ -49,7 +52,7 @@ import {
49
52
  toolOf,
50
53
  wantsPage,
51
54
  watchworthy
52
- } from "./chunk-CGXTVKRB.js";
55
+ } from "./chunk-2N762ZXU.js";
53
56
 
54
57
  // src/fetch.ts
55
58
  var OPTION_KEYS = [
@@ -113,7 +116,7 @@ function reguardFetch(options = {}) {
113
116
  checkFunction(options.fetch, "fetch");
114
117
  checkFunction(options.onError, "onError");
115
118
  const log = makeLog(checkLogger(options.logger), checkBoolean(options.debug, "debug") ?? /^(?:1|true|yes)$/i.test(envValue("REGUARD_DEBUG") ?? ""));
116
- const ignore = options.ignore?.length ? skipMatcher(options.ignore) : void 0;
119
+ const ignore = options.ignore?.length ? protectionMatcher(options.ignore) : void 0;
117
120
  const key = (options.key ?? envValue("REGUARD_KEY"))?.trim();
118
121
  const parsed = parseSiteKey(key);
119
122
  const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
@@ -153,7 +156,7 @@ function reguardFetch(options = {}) {
153
156
  const allDry = !block || BLOCK_REASONS.every((r) => block.dryRun.has(r));
154
157
  const denyMaps = (options.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
155
158
  const allowList = block?.allow.length ? skipMatcher(block.allow) : void 0;
156
- const skipped = skipMatcher(collect.skip);
159
+ const skipped = protectionMatcher(collect.skip);
157
160
  const tagSettings = { site, collect, cookieDomain };
158
161
  const pace = block?.pace;
159
162
  const pages = pace ? new Allowance(pace.documents.burst, pace.documents.perSecond / 1e3, 5e4) : void 0;
@@ -212,11 +215,10 @@ function reguardFetch(options = {}) {
212
215
  }
213
216
  if (!health.canSend()) queue.length = 0;
214
217
  };
215
- const flushSoon = (waitUntil, now = false) => {
216
- if (!queue.length || inflight) return;
217
- if (!now && Date.now() - lastFlush < flushIntervalMs && queue.length < 100) return;
218
- inflight = flush().finally(() => inflight = void 0);
219
- waitUntil?.(inflight);
218
+ let lastUrgent = 0;
219
+ const flushSoon = (now = false) => {
220
+ if (queue.length && !inflight && (now || Date.now() - lastFlush >= flushIntervalMs || queue.length >= 100)) inflight = flush().finally(() => inflight = void 0);
221
+ return inflight;
220
222
  };
221
223
  const pushedFor = async (request, verified) => {
222
224
  if (!pushed.size) return null;
@@ -225,7 +227,9 @@ function reguardFetch(options = {}) {
225
227
  const now = Date.now();
226
228
  const claims = [];
227
229
  const k = [sid ? `s:${sid}` : ""];
228
- if (collect.addresses !== "off" && !verified && !a.internal && a.address) k.push(`v:${await hmac(parsed.secret, `visitor:${a.address}`, 22)}`);
230
+ const get = (n) => request.headers.get(n) ?? void 0;
231
+ const browser = presentsAsBrowser({ userAgent: get("user-agent") ?? "", acceptLanguage: get("accept-language"), accept: get("accept"), secFetchMode: get("sec-fetch-mode"), secFetchDest: get("sec-fetch-dest"), secChUa: get("sec-ch-ua") });
232
+ if (collect.addresses !== "off" && !verified && !a.internal && !browser && a.address) k.push(`v:${await hmac(parsed.secret, `visitor:${addressKey(a.address) || a.address}`, 22)}`);
229
233
  let vid;
230
234
  for (const x of k) {
231
235
  const e = x ? pushed.get(x) : void 0;
@@ -254,14 +258,11 @@ function reguardFetch(options = {}) {
254
258
  if (sid && /^[\w-]{1,64}$/.test(sid)) headers.set("cookie", `${SESSION_COOKIE}=${sid}`);
255
259
  headers.set("x-reguard-site", `${site}.${await hmac(parsed.secret, `prefix:${site}`, 16)}`);
256
260
  const a = addressFor(request);
257
- const value = collect.addresses === "off" || !a.address ? "-" : await hmac(parsed.secret, `visitor:${a.address}`, 22);
261
+ const value = collect.addresses === "off" || !a.address ? "-" : await hmac(parsed.secret, `visitor:${addressKey(a.address) || a.address}`, 22);
258
262
  headers.set("x-reguard-visitor", `${value}.${await hmac(parsed.secret, `visitor-header:${value}`, 16)}`);
259
263
  try {
260
264
  const init = { method: request.method, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) };
261
- if (request.method !== "GET" && request.method !== "HEAD" && request.body) {
262
- init.body = request.body;
263
- init.duplex = "half";
264
- }
265
+ if (request.method !== "GET" && request.method !== "HEAD" && request.body) init.body = await request.arrayBuffer();
265
266
  const r = await doFetch(`${collector}${p.decoded}${url.search}`, init);
266
267
  const out = new Headers();
267
268
  r.headers.forEach((v, k) => {
@@ -293,7 +294,7 @@ function reguardFetch(options = {}) {
293
294
  } catch (e) {
294
295
  log.once("onBlock-threw", "warn", `block.onBlock threw: ${e?.message ?? e}`);
295
296
  }
296
- log.debug(`${d.dryRun ? "would block" : "blocked"} ${request.method} ${d.path}: ${d.reason}`);
297
+ log.debug(`${d.dryRun ? "would block" : "blocked"} ${request.method} ${d.path}: ${d.reason}${d.pace ? ` (${d.pace})` : ""} from ${d.clientIp}`);
297
298
  if (d.dryRun) return void 0;
298
299
  const respond = block.respond;
299
300
  if (respond) {
@@ -313,9 +314,9 @@ function reguardFetch(options = {}) {
313
314
  if (denyMaps && isSourceMapPath(p)) return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
314
315
  const cookie = request.headers.get("cookie");
315
316
  const pending = (async () => {
316
- const browser = await readVerdict(cookie);
317
- const pushedV = await pushedFor(request, !!browser);
318
- return { browser, pushed: pushedV, merged: mergeVerdicts(browser, pushedV) };
317
+ const browser2 = await readVerdict(cookie);
318
+ const pushedV = await pushedFor(request, !!browser2);
319
+ return { browser: browser2, pushed: pushedV, merged: mergeVerdicts(browser2, pushedV) };
319
320
  })();
320
321
  verdicts.set(request, pending);
321
322
  if (!block) return void 0;
@@ -328,10 +329,11 @@ function reguardFetch(options = {}) {
328
329
  })();
329
330
  if (allowed) return void 0;
330
331
  const get = (n) => request.headers.get(n) ?? void 0;
331
- if (pages && get("sec-fetch-dest") === void 0 && (request.method === "GET" || request.method === "HEAD") && requestKind(p.decoded) === "document" && !isSpeculativeHeaders(get)) {
332
+ const browser = presentsAsBrowser({ userAgent: get("user-agent") ?? "", acceptLanguage: get("accept-language"), accept: get("accept"), secFetchMode: get("sec-fetch-mode"), secFetchDest: get("sec-fetch-dest"), secChUa: get("sec-ch-ua") });
333
+ if (pages && !browser && (request.method === "GET" || request.method === "HEAD") && requestKind(p.decoded) === "document" && !isSpeculativeHeaders(get)) {
332
334
  const tool = toolOf(get("user-agent"));
333
335
  const a = addressFor(request);
334
- if (!(tool && BENIGN_TOOL_FAMILIES.has(tool.family)) && a.address && !a.internal && !pages.take(a.address)) {
336
+ if (!(tool && BENIGN_TOOL_FAMILIES.has(tool.family)) && a.address && !a.internal && !pages.take(addressKey(a.address) || a.address)) {
335
337
  const answered = await act(request, decide(request, "pace", p, null, "document"));
336
338
  if (answered) return answered;
337
339
  }
@@ -347,7 +349,7 @@ function reguardFetch(options = {}) {
347
349
  };
348
350
  const record = (request, response, ctx) => {
349
351
  if (!collect.requests) return;
350
- void (async () => {
352
+ const task = (async () => {
351
353
  try {
352
354
  const url = new URL(request.url);
353
355
  const p = canonicalPath(url.pathname);
@@ -356,18 +358,19 @@ function reguardFetch(options = {}) {
356
358
  const sid = cookieValue(get("cookie"), SESSION_COOKIE);
357
359
  const decision = decisions.get(request);
358
360
  const target = `${url.pathname}${url.search}`;
359
- if (!sid && !decision) {
360
- if (options.watchSessionless === false || collect.addresses === "off") return;
361
- const secure = url.protocol === "https:" ? true : void 0;
362
- if (!watchworthy({ userAgent: get("user-agent") ?? "", acceptLanguage: get("accept-language"), accept: get("accept"), secFetchMode: get("sec-fetch-mode"), secChUa: get("sec-ch-ua"), secure, path: url.pathname, status: response.status })) return;
361
+ const toolLike = () => watchworthy({ userAgent: get("user-agent") ?? "", acceptLanguage: get("accept-language"), accept: get("accept"), secFetchMode: get("sec-fetch-mode"), secChUa: get("sec-ch-ua"), secure: url.protocol === "https:" ? true : void 0, path: url.pathname, status: response?.status });
362
+ const tool = toolLike();
363
+ if (!decision) {
364
+ if (!sid && (options.watchSessionless === false || collect.addresses === "off" || !tool)) return;
365
+ if (sid && !response && !tool) return;
363
366
  }
364
367
  const a = addressFor(request);
365
368
  const hash = (s) => hmac(parsed.secret, s, 16);
366
- const contentType = response.headers.get("content-type") ?? "";
367
- const responseBytes = Number(response.headers.get("content-length") ?? 0) || 0;
369
+ const contentType = response?.headers.get("content-type") ?? "";
370
+ const responseBytes = Number(response?.headers.get("content-length") ?? 0) || 0;
368
371
  const requestBytes = Number(get("content-length") ?? 0) || 0;
369
372
  let exchange;
370
- if (!isSpeculativeHeaders(get) && isApiLike(target, contentType, requestBytes)) {
373
+ if (response && !isSpeculativeHeaders(get) && isApiLike(target, contentType, requestBytes)) {
371
374
  const input = { method: request.method, url: target, requestContentType: get("content-type") ?? "", requestBody: "", requestBytes, status: response.status, responseContentType: contentType, responseBytes };
372
375
  const wanted = /* @__PURE__ */ new Set();
373
376
  describeExchange((s) => (wanted.add(s), ""), input);
@@ -387,7 +390,7 @@ function reguardFetch(options = {}) {
387
390
  url: collect.pages === "masked" ? privateUrl(target) : "",
388
391
  ...collect.pages !== "off" ? { item: await hash(`path:${url.pathname}`) } : {},
389
392
  ...collect.pages !== "masked" ? { traits: pathTraits(target, get("rsc") === "1") } : {},
390
- status: response.status,
393
+ ...response ? { status: response.status } : {},
391
394
  headers: Object.fromEntries(["rsc", "next-router-prefetch", "sec-purpose", "purpose"].flatMap((n) => get(n) !== void 0 ? [[n, get(n)]] : [])),
392
395
  client: {
393
396
  ua: get("user-agent") ?? "",
@@ -401,26 +404,28 @@ function reguardFetch(options = {}) {
401
404
  hasReferer: !!get("referer"),
402
405
  ...url.protocol === "https:" ? { secure: true } : {}
403
406
  },
404
- ...!sid && a.address && collect.addresses !== "off" ? { visitor: await hmac(parsed.secret, `visitor:${a.address}`, 22) } : {},
407
+ ...!sid && a.address && collect.addresses !== "off" ? { visitor: await hmac(parsed.secret, `visitor:${addressKey(a.address) || a.address}`, 22) } : {},
405
408
  ...exchange ? { exchange } : {},
406
409
  ...decision?.pace ? { pace: decision.pace } : {},
407
410
  ...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
408
411
  ...a.internal ? { internal: true } : {}
409
412
  });
410
413
  if (queue.length > 5e3) queue.splice(0, queue.length - 5e3);
411
- const waitUntil = ctx?.waitUntil ? (p2) => ctx.waitUntil.call(ctx, p2) : void 0;
412
414
  ensureTimer();
413
- flushSoon(waitUntil, !!decision);
415
+ const urgent = !!decision || tool && Date.now() - lastUrgent >= 500;
416
+ if (urgent) lastUrgent = Date.now();
417
+ await flushSoon(urgent);
414
418
  } catch (e) {
415
419
  onError(e);
416
420
  }
417
421
  })();
422
+ ctx?.waitUntil?.call(ctx, task);
418
423
  };
419
424
  let timer;
420
425
  const ensureTimer = () => {
421
426
  if (timer !== void 0 || platform === "workers" || typeof setInterval !== "function") return;
422
427
  try {
423
- timer = setInterval(() => flushSoon(void 0, true), flushIntervalMs);
428
+ timer = setInterval(() => void flushSoon(true), flushIntervalMs);
424
429
  timer.unref?.();
425
430
  } catch {
426
431
  timer = null;