reguard 0.7.1 → 0.8.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 +51 -31
  2. package/dist/chunks/chunk-3AYS7WSY.js +350 -0
  3. package/dist/chunks/chunk-KNKCUJL3.js +969 -0
  4. package/dist/chunks/{chunk-W56LN2M5.js → chunk-PA46KSOR.js} +385 -33
  5. package/dist/chunks/chunk-U54IP6G4.js +448 -0
  6. package/dist/cjs/fastify.cjs +2109 -0
  7. package/dist/cjs/fetch.cjs +1463 -0
  8. package/dist/cjs/index.cjs +2074 -0
  9. package/dist/cjs/next.cjs +1535 -0
  10. package/dist/cjs/testing.cjs +214 -0
  11. package/dist/fastify.js +59 -0
  12. package/dist/fetch.js +13 -0
  13. package/dist/index.js +15 -716
  14. package/dist/next.js +48 -52
  15. package/dist/testing.js +39 -0
  16. package/dist/types/node/src/config.d.ts +107 -0
  17. package/dist/types/node/src/core.d.ts +66 -72
  18. package/dist/types/node/src/fastify.d.ts +41 -0
  19. package/dist/types/node/src/fetch.d.ts +76 -0
  20. package/dist/types/node/src/health.d.ts +41 -0
  21. package/dist/types/node/src/index.d.ts +114 -34
  22. package/dist/types/node/src/next.d.ts +40 -27
  23. package/dist/types/node/src/testing.d.ts +25 -0
  24. package/dist/types/shared/src/address.d.ts +81 -0
  25. package/dist/types/shared/src/index.d.ts +6 -0
  26. package/dist/types/shared/src/paths.d.ts +32 -0
  27. package/dist/types-cjs/node/src/config.d.cts +107 -0
  28. package/dist/types-cjs/node/src/core.d.cts +107 -0
  29. package/dist/types-cjs/node/src/fastify.d.cts +41 -0
  30. package/dist/types-cjs/node/src/fetch.d.cts +76 -0
  31. package/dist/types-cjs/node/src/health.d.cts +41 -0
  32. package/dist/types-cjs/node/src/index.d.cts +203 -0
  33. package/dist/types-cjs/node/src/next.d.cts +85 -0
  34. package/dist/types-cjs/node/src/testing.d.cts +25 -0
  35. package/dist/types-cjs/shared/src/address.d.cts +81 -0
  36. package/dist/types-cjs/shared/src/allowance.d.cts +17 -0
  37. package/dist/types-cjs/shared/src/collect.d.cts +52 -0
  38. package/dist/types-cjs/shared/src/exchange.d.cts +69 -0
  39. package/dist/types-cjs/shared/src/index.d.cts +105 -0
  40. package/dist/types-cjs/shared/src/keys.d.cts +13 -0
  41. package/dist/types-cjs/shared/src/paths.d.cts +32 -0
  42. package/dist/types-cjs/shared/src/tools.d.cts +101 -0
  43. package/dist/types-cjs/shared/src/verdict.d.cts +37 -0
  44. package/package.json +73 -10
@@ -124,6 +124,11 @@ var VERDICT_COOKIE = "_sv";
124
124
  var SESSION_COOKIE = "_s";
125
125
  var enc = new TextEncoder();
126
126
  var keys = /* @__PURE__ */ new Map();
127
+ function b64url(bytes) {
128
+ let s = "";
129
+ for (const b of bytes) s += String.fromCharCode(b);
130
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
131
+ }
127
132
  function unb64url(s) {
128
133
  const pad = s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4);
129
134
  const bin = atob(pad);
@@ -139,6 +144,11 @@ function hmacKey(siteKey) {
139
144
  }
140
145
  return k;
141
146
  }
147
+ async function signVerdict(siteKey, payload) {
148
+ const body = b64url(enc.encode(JSON.stringify(payload)));
149
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await hmacKey(siteKey), enc.encode(`v1.${body}`)));
150
+ return `v1.${body}.${b64url(sig)}`;
151
+ }
142
152
  async function verifyVerdict(siteKey, token, expect = {}) {
143
153
  try {
144
154
  if (!token) return null;
@@ -393,22 +403,334 @@ var Allowance = class {
393
403
  }
394
404
  };
395
405
 
406
+ // ../shared/src/address.ts
407
+ var PLATFORM_HEADERS = {
408
+ fly: "fly-client-ip",
409
+ vercel: "x-vercel-forwarded-for",
410
+ railway: "x-real-ip",
411
+ netlify: "x-nf-client-connection-ip",
412
+ appengine: "x-appengine-user-ip",
413
+ workers: "cf-connecting-ip"
414
+ };
415
+ function detectPlatform(env) {
416
+ if (!env) return null;
417
+ if (env.FLY_APP_NAME) return "fly";
418
+ if (env.VERCEL) return "vercel";
419
+ if (env.RAILWAY_ENVIRONMENT_ID || env.RAILWAY_PROJECT_ID || env.RAILWAY_ENVIRONMENT) return "railway";
420
+ if (env.NETLIFY) return "netlify";
421
+ if (env.GAE_APPLICATION) return "appengine";
422
+ return null;
423
+ }
424
+ var CLOUDFLARE_RANGES = [
425
+ "173.245.48.0/20",
426
+ "103.21.244.0/22",
427
+ "103.22.200.0/22",
428
+ "103.31.4.0/22",
429
+ "141.101.64.0/18",
430
+ "108.162.192.0/18",
431
+ "190.93.240.0/20",
432
+ "188.114.96.0/20",
433
+ "197.234.240.0/22",
434
+ "198.41.128.0/17",
435
+ "162.158.0.0/15",
436
+ "104.16.0.0/13",
437
+ "104.24.0.0/14",
438
+ "172.64.0.0/13",
439
+ "131.0.72.0/22",
440
+ "2400:cb00::/32",
441
+ "2606:4700::/32",
442
+ "2803:f800::/32",
443
+ "2405:b500::/32",
444
+ "2405:8100::/32",
445
+ "2a06:98c0::/29",
446
+ "2c0f:f248::/32"
447
+ ];
448
+ var NON_PUBLIC_RANGES = [
449
+ "0.0.0.0/8",
450
+ "10.0.0.0/8",
451
+ "100.64.0.0/10",
452
+ "127.0.0.0/8",
453
+ "169.254.0.0/16",
454
+ "172.16.0.0/12",
455
+ "192.168.0.0/16",
456
+ "::/128",
457
+ "::1/128",
458
+ "fc00::/7",
459
+ "fe80::/10"
460
+ ];
461
+ var MAX_FORWARDED = 32;
462
+ function parseIpv4(s) {
463
+ const parts = s.split(".");
464
+ if (parts.length !== 4) return null;
465
+ const out = [];
466
+ for (const p of parts) {
467
+ if (!/^\d{1,3}$/.test(p) || p.length > 1 && p.startsWith("0")) return null;
468
+ const n = Number(p);
469
+ if (n > 255) return null;
470
+ out.push(n);
471
+ }
472
+ return out;
473
+ }
474
+ function parseIp(text) {
475
+ const s = text.trim();
476
+ if (!s) return null;
477
+ const v4 = parseIpv4(s);
478
+ if (v4) return Uint8Array.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, ...v4]);
479
+ if (!s.includes(":") || !/^[0-9a-fA-F:.]+$/.test(s)) return null;
480
+ const halves = s.split("::");
481
+ if (halves.length > 2) return null;
482
+ const groups = (part) => {
483
+ if (part === "") return [];
484
+ const out = [];
485
+ const items = part.split(":");
486
+ for (let i = 0; i < items.length; i++) {
487
+ const it = items[i];
488
+ if (i === items.length - 1 && it.includes(".")) {
489
+ const tail2 = parseIpv4(it);
490
+ if (!tail2) return null;
491
+ out.push(tail2[0] << 8 | tail2[1], tail2[2] << 8 | tail2[3]);
492
+ } else {
493
+ if (!/^[0-9a-fA-F]{1,4}$/.test(it)) return null;
494
+ out.push(parseInt(it, 16));
495
+ }
496
+ }
497
+ return out;
498
+ };
499
+ const head = groups(halves[0]);
500
+ const tail = halves.length === 2 ? groups(halves[1]) : [];
501
+ if (!head || !tail) return null;
502
+ const total = head.length + tail.length;
503
+ if (halves.length === 2 ? total > 7 : total !== 8) return null;
504
+ const all = [...head, ...Array(8 - total).fill(0), ...tail];
505
+ const bytes = new Uint8Array(16);
506
+ all.forEach((g, i) => {
507
+ bytes[i * 2] = g >> 8;
508
+ bytes[i * 2 + 1] = g & 255;
509
+ });
510
+ return bytes;
511
+ }
512
+ var isMapped = (b) => b.slice(0, 10).every((x) => x === 0) && b[10] === 255 && b[11] === 255;
513
+ function formatIp(b) {
514
+ if (isMapped(b)) return `${b[12]}.${b[13]}.${b[14]}.${b[15]}`;
515
+ const g = [];
516
+ for (let i = 0; i < 8; i++) g.push(b[i * 2] << 8 | b[i * 2 + 1]);
517
+ let best = -1;
518
+ let bestLen = 0;
519
+ for (let i = 0; i < 8; ) {
520
+ if (g[i] !== 0) {
521
+ i++;
522
+ continue;
523
+ }
524
+ let j = i;
525
+ while (j < 8 && g[j] === 0) j++;
526
+ if (j - i > bestLen && j - i >= 2) {
527
+ best = i;
528
+ bestLen = j - i;
529
+ }
530
+ i = j;
531
+ }
532
+ const hex = (xs) => xs.map((x) => x.toString(16)).join(":");
533
+ if (best === -1) return hex(g);
534
+ return `${hex(g.slice(0, best))}::${hex(g.slice(best + bestLen))}`;
535
+ }
536
+ function normalizeIp(token) {
537
+ if (!token) return null;
538
+ let s = token.trim().replace(/^"(.*)"$/, "$1");
539
+ if (s.startsWith("[")) {
540
+ const end = s.indexOf("]");
541
+ if (end < 0) return null;
542
+ s = s.slice(1, end);
543
+ } else {
544
+ const v4port = /^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(s);
545
+ if (v4port) s = v4port[1];
546
+ }
547
+ const zone = s.indexOf("%");
548
+ if (zone > 0) s = s.slice(0, zone);
549
+ let b = parseIp(s);
550
+ if (!b && s.includes(":")) {
551
+ const cut = /^(.*):\d{1,5}$/.exec(s);
552
+ if (cut) b = parseIp(cut[1]);
553
+ }
554
+ return b ? formatIp(b) : null;
555
+ }
556
+ function parseCidr(text) {
557
+ const [addr, len, extra] = text.trim().split("/");
558
+ if (extra !== void 0 || !addr) return null;
559
+ const bytes = parseIp(addr);
560
+ if (!bytes) return null;
561
+ const v4 = parseIpv4(addr.trim()) !== null;
562
+ const max = v4 ? 32 : 128;
563
+ if (len !== void 0 && !/^\d{1,3}$/.test(len)) return null;
564
+ const n = len === void 0 ? max : Number(len);
565
+ if (n > max) return null;
566
+ return { bytes, bits: v4 ? n + 96 : n };
567
+ }
568
+ function inCidr(c, b) {
569
+ let bits = c.bits;
570
+ for (let i = 0; i < 16 && bits > 0; i++, bits -= 8) {
571
+ const mask = bits >= 8 ? 255 : 255 << 8 - bits & 255;
572
+ if ((c.bytes[i] & mask) !== (b[i] & mask)) return false;
573
+ }
574
+ return true;
575
+ }
576
+ 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));
584
+ }
585
+ function isPublicIp(address) {
586
+ const b = parseIp(address);
587
+ return !!b && !NON_PUBLIC.some((c) => inCidr(c, b));
588
+ }
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];
593
+ }
594
+ var result = (address, via) => ({ address, internal: !isPublicIp(address), via });
595
+ function walk(req, trusted, via) {
596
+ const chain = chainOf(req);
597
+ let last = "";
598
+ for (let i = chain.length - 1; i >= 0; i--) {
599
+ const ip = normalizeIp(chain[i]);
600
+ if (!ip) continue;
601
+ last ||= ip;
602
+ 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 };
605
+ }
606
+ return { address: last, internal: true, via: "socket" };
607
+ }
608
+ function resolveClientAddress(req, mode = "auto", platform = null) {
609
+ const peer = normalizeIp(req.peer) ?? "";
610
+ if (mode === "socket") return result(peer, "socket");
611
+ if (typeof mode === "object" && "header" in mode) {
612
+ const first = req.header(mode.header.toLowerCase())?.split(",")[0];
613
+ const ip = normalizeIp(first);
614
+ return ip ? result(ip, "header") : result(peer, "socket");
615
+ }
616
+ 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");
621
+ }
622
+ if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies");
623
+ const framework = normalizeIp(req.framework);
624
+ if (framework) return result(framework, "framework");
625
+ if (platform) {
626
+ const ip = normalizeIp(req.header(PLATFORM_HEADERS[platform])?.split(",")[0]);
627
+ if (ip) return result(ip, `platform:${platform}`);
628
+ }
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");
634
+ }
635
+ function clientIpModeProblem(value) {
636
+ if (value === "auto" || value === "socket") return null;
637
+ if (!value || typeof value !== "object" || Array.isArray(value)) return 'must be "auto", "socket", { header }, { proxies } or { hops }';
638
+ const keys2 = Object.keys(value);
639
+ if (keys2.length !== 1) return "must set exactly one of header, proxies or hops";
640
+ const v = value;
641
+ if ("header" in v) return typeof v.header === "string" && /^[A-Za-z0-9-]+$/.test(v.header) ? null : "header must be a header name";
642
+ if ("hops" in v) return Number.isInteger(v.hops) && v.hops >= 1 && v.hops <= MAX_FORWARDED ? null : `hops must be a whole number from 1 to ${MAX_FORWARDED}`;
643
+ if ("proxies" in v) {
644
+ if (!Array.isArray(v.proxies) || !v.proxies.length) return "proxies must be a non-empty list of addresses or ranges";
645
+ const bad = v.proxies.find((p) => typeof p !== "string" || !parseCidr(p));
646
+ return bad === void 0 ? null : `proxies has an entry that is not an address or range: ${JSON.stringify(bad)}`;
647
+ }
648
+ return "must set exactly one of header, proxies or hops";
649
+ }
650
+
651
+ // ../shared/src/paths.ts
652
+ function decodeOnce(s) {
653
+ if (!s.includes("%")) return s;
654
+ try {
655
+ return decodeURIComponent(s);
656
+ } catch {
657
+ return s.replace(/%([0-7][0-9a-fA-F])/g, (_, h) => String.fromCharCode(parseInt(h, 16)));
658
+ }
659
+ }
660
+ function normalizeSegments(path) {
661
+ const collapsed = path.replace(/\/{2,}/g, "/");
662
+ const segs = collapsed.split("/");
663
+ const out = [];
664
+ for (let i = 1; i < segs.length; i++) {
665
+ const s = segs[i];
666
+ const last = i === segs.length - 1;
667
+ if (s === ".") {
668
+ if (last) out.push("");
669
+ } else if (s === "..") {
670
+ out.pop();
671
+ if (last) out.push("");
672
+ } else out.push(s);
673
+ }
674
+ return `/${out.join("/")}`;
675
+ }
676
+ function canonicalPath(target) {
677
+ let t = target || "/";
678
+ const abs = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]*/.exec(t);
679
+ if (abs) t = t.slice(abs[0].length) || "/";
680
+ const cut = t.search(/[?#]/);
681
+ let raw = cut === -1 ? t : t.slice(0, cut);
682
+ if (!raw.startsWith("/")) raw = `/${raw}`;
683
+ return { raw, decoded: normalizeSegments(decodeOnce(raw)) };
684
+ }
685
+ function matchesEither(matcher, p) {
686
+ return matcher(p.raw) || matcher(p.decoded);
687
+ }
688
+ function matchesBoth(matcher, p) {
689
+ return matcher(p.raw) && matcher(p.decoded);
690
+ }
691
+ function isSourceMapPath(p) {
692
+ return /\.map$/i.test(p.raw) || /\.map$/i.test(p.decoded);
693
+ }
694
+
396
695
  // src/core.ts
397
696
  var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
398
- function withFlagged(p) {
697
+ function withFlagged(p, source = "browser") {
399
698
  return {
400
699
  ...p,
700
+ source,
401
701
  flagged({ labels, minStage = "candidate" } = {}) {
402
- return p.claims.some((c) => STAGE_RANK[c.stage] >= STAGE_RANK[minStage] && (!labels || labels.includes(c.label)));
702
+ const want = typeof labels === "string" ? [labels] : labels?.length ? labels : void 0;
703
+ const rank = STAGE_RANK[minStage] ?? 0;
704
+ return p.claims.some((c) => (STAGE_RANK[c.stage] ?? -1) >= rank && (!want || want.includes(c.label)));
403
705
  }
404
706
  };
405
707
  }
708
+ function mergeVerdicts(browser, pushed) {
709
+ if (!pushed) return browser;
710
+ if (!browser) return withFlagged(pushed, "server");
711
+ const rules = new Set(browser.claims.map((c) => `${c.rule}|${c.label}|${c.stage}`));
712
+ const claims = [...browser.claims, ...pushed.claims.filter((c) => !rules.has(`${c.rule}|${c.label}|${c.stage}`))];
713
+ const { source: _s, flagged: _f, ...payload } = browser;
714
+ return withFlagged({ ...payload, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
715
+ }
406
716
  async function readVerdictFrom(secret, site, cookieHeader) {
407
717
  const token = cookieValue(cookieHeader, VERDICT_COOKIE);
408
718
  if (!token) return null;
409
719
  const p = await verifyVerdict(secret, token, { site, sid: cookieValue(cookieHeader, SESSION_COOKIE) });
410
720
  return p ? withFlagged(p) : null;
411
721
  }
722
+ function looksCurrent(site, cookieHeader, now = Date.now()) {
723
+ const token = cookieValue(cookieHeader, VERDICT_COOKIE);
724
+ const parts = token?.split(".");
725
+ if (parts?.length !== 3 || parts[0] !== "v1") return false;
726
+ try {
727
+ const json = atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"));
728
+ const p = JSON.parse(json);
729
+ return p.site === site && typeof p.exp === "number" && p.exp > now && p.sid === cookieValue(cookieHeader, SESSION_COOKIE);
730
+ } catch {
731
+ return false;
732
+ }
733
+ }
412
734
  var DEFAULT_COLLECTOR = "https://api.reguard.site";
413
735
  function collectorBase(collector) {
414
736
  return (collector ?? DEFAULT_COLLECTOR).replace(/\/+$/, "").replace(/\/_s$/, "");
@@ -422,43 +744,60 @@ var DEFAULT_PACE = {
422
744
  api: { burst: 60, perSecond: 5 },
423
745
  notFound: { burst: 20, perSecond: 0.5 }
424
746
  };
425
- function blockConfig(block) {
426
- if (!block) return null;
427
- const cfg = block === true ? {} : block;
428
- return {
429
- labels: cfg.labels,
430
- status: cfg.status ?? 429,
431
- minStage: cfg.minStage ?? "candidate",
432
- require: cfg.require?.length ? cfg.require : void 0,
433
- maxAgeMs: cfg.requireMaxAgeMs ?? 6e4,
434
- graceMs: cfg.requireGraceMs ?? 15e3,
435
- graceRequests: cfg.requireGraceRequests ?? 30,
436
- gracePages: cfg.requireGracePages ?? 3,
437
- refreshRequests: cfg.requireRefreshRequests ?? 30,
438
- refreshMs: cfg.requireRefreshMs ?? 1e4,
439
- pace: cfg.pace === false ? null : { ...DEFAULT_PACE, ...cfg.pace ?? {} }
440
- };
441
- }
442
747
  function freshSeconds(cfg) {
443
748
  return cfg?.require ? Math.max(5, Math.floor(cfg.maxAgeMs / 2e3)) : void 0;
444
749
  }
445
- var PACE_RETRY_AFTER = "2";
446
- var PACE_JSON = JSON.stringify({ error: "Too many requests. Slow down and try again in a moment." });
447
750
  function verdictAgeMs(v, now = Date.now()) {
448
751
  return now - (v.exp - VERDICT_TTL_MS);
449
752
  }
450
- function pushedVerdict(sid, site, claims) {
451
- return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: Date.now() + 6e4 });
753
+ function pushedVerdict(sid, site, claims, now = Date.now()) {
754
+ return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4 }, "server");
755
+ }
756
+ var ANSWER_CODES = { flagged: "reguard.blocked", flagged_server: "reguard.blocked", require: "reguard.require", pace: "reguard.pace" };
757
+ var RETRY_AFTER = { flagged: 120, flagged_server: 120, require: 5, pace: 2 };
758
+ var page = (title, text) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title}</title></head><body><h1>${title}</h1><p>${text}</p></body></html>`;
759
+ var BLOCK_HTML = page("Please slow down", "This browser looks like it is being driven by an automated tool. Try again in a few minutes.");
760
+ var REQUIRE_HTML = page("Reload the page to continue", "This page needs its security check to run. Reload the page; if this keeps happening, allow scripts from this site.");
761
+ var PACE_TEXT = "Too many requests. Slow down and try again in a moment.";
762
+ var MESSAGES = {
763
+ flagged: "Too many automated requests from this browser. Try again in a few minutes.",
764
+ flagged_server: "Too many automated requests from this browser. Try again in a few minutes.",
765
+ require: "This request needs the page's security check. Reload the page and try again.",
766
+ pace: PACE_TEXT
767
+ };
768
+ function defaultAnswer(reason, wantsHtml) {
769
+ if (wantsHtml) {
770
+ if (reason === "pace") return { contentType: "text/plain; charset=utf-8", body: PACE_TEXT };
771
+ return { contentType: "text/html; charset=utf-8", body: reason === "require" ? REQUIRE_HTML : BLOCK_HTML };
772
+ }
773
+ return { contentType: "application/json", body: JSON.stringify({ error: MESSAGES[reason], code: ANSWER_CODES[reason] }) };
452
774
  }
453
- var BLOCK_RETRY_AFTER = "120";
454
- var BLOCK_HTML = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Please slow down</title></head><body><h1>Please slow down</h1><p>This browser looks like it is being driven by an automated tool. Try again in a few minutes.</p></body></html>';
455
- var BLOCK_JSON = JSON.stringify({ error: "Too many automated requests from this browser. Try again in a few minutes." });
456
775
  function wantsPage(get) {
457
776
  return get("sec-fetch-dest") === "document" || /text\/html/i.test(get("accept") ?? "");
458
777
  }
459
778
  function isReguardPath(path) {
460
779
  return path === "/_s" || path.startsWith("/_s/");
461
780
  }
781
+ function isPreflight(method, get) {
782
+ return method === "OPTIONS" && !!get("access-control-request-method");
783
+ }
784
+ var escapeAttr = (v) => v.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
785
+ function renderScriptTag(t, nonce) {
786
+ const attrs = { ...collectAttributes(t.collect) };
787
+ if (t.fresh) attrs["data-fresh"] = String(t.fresh);
788
+ if (t.cookieDomain) attrs["data-cookie-domain"] = t.cookieDomain;
789
+ if (nonce && /^[A-Za-z0-9+/=_-]{1,200}$/.test(nonce)) attrs.nonce = nonce;
790
+ const rest = Object.entries(attrs).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("");
791
+ return `<script async src="${t.prefix ?? "/_s"}/sdk.js" data-site="${t.site.replace(/[^\w.-]/g, "")}"${rest}></script>`;
792
+ }
793
+ function cspNonce(csp) {
794
+ if (!csp) return void 0;
795
+ const directives = csp.split(";").map((d) => d.trim().split(/\s+/));
796
+ const pick = (name) => directives.find((d) => d[0]?.toLowerCase() === name);
797
+ const src = pick("script-src-elem") ?? pick("script-src") ?? pick("default-src");
798
+ const m = src?.slice(1).map((t) => /^'nonce-([A-Za-z0-9+/=_-]+)'$/.exec(t)).find(Boolean);
799
+ return m?.[1];
800
+ }
462
801
 
463
802
  export {
464
803
  privateUrl,
@@ -466,6 +805,7 @@ export {
466
805
  isApiLike,
467
806
  isSpeculativeHeaders,
468
807
  SESSION_COOKIE,
808
+ signVerdict,
469
809
  cookieValue,
470
810
  formatSiteKey,
471
811
  parseSiteKey,
@@ -479,18 +819,30 @@ export {
479
819
  collectAttributes,
480
820
  collectReport,
481
821
  Allowance,
822
+ detectPlatform,
823
+ normalizeIp,
824
+ isPublicIp,
825
+ resolveClientAddress,
826
+ clientIpModeProblem,
827
+ canonicalPath,
828
+ matchesEither,
829
+ matchesBoth,
830
+ isSourceMapPath,
831
+ mergeVerdicts,
482
832
  readVerdictFrom,
833
+ looksCurrent,
483
834
  collectorBase,
484
835
  envValue,
485
- blockConfig,
836
+ VERDICT_TTL_MS,
837
+ DEFAULT_PACE,
486
838
  freshSeconds,
487
- PACE_RETRY_AFTER,
488
- PACE_JSON,
489
839
  verdictAgeMs,
490
840
  pushedVerdict,
491
- BLOCK_RETRY_AFTER,
492
- BLOCK_HTML,
493
- BLOCK_JSON,
841
+ RETRY_AFTER,
842
+ defaultAnswer,
494
843
  wantsPage,
495
- isReguardPath
844
+ isReguardPath,
845
+ isPreflight,
846
+ renderScriptTag,
847
+ cspNonce
496
848
  };