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.
- package/README.md +25 -3
- package/dist/chunks/{chunk-PA46KSOR.js → chunk-2N762ZXU.js} +235 -44
- package/dist/chunks/{chunk-3AYS7WSY.js → chunk-4RD66ACT.js} +81 -8
- package/dist/chunks/{chunk-U54IP6G4.js → chunk-GOT54CF4.js} +61 -40
- package/dist/chunks/{chunk-KNKCUJL3.js → chunk-RTCPK4MF.js} +102 -41
- package/dist/cjs/fastify.cjs +305 -93
- package/dist/cjs/fetch.cjs +347 -87
- package/dist/cjs/index.cjs +386 -86
- package/dist/cjs/next.cjs +366 -103
- package/dist/cjs/testing.cjs +28 -100
- package/dist/fastify.js +4 -12
- package/dist/fetch.js +14 -5
- package/dist/index.js +13 -5
- package/dist/next.js +33 -23
- package/dist/testing.js +9 -3
- package/dist/types/node/src/api.d.ts +139 -0
- package/dist/types/node/src/core.d.ts +8 -1
- package/dist/types/node/src/fastify.d.ts +15 -7
- package/dist/types/node/src/fetch.d.ts +12 -2
- package/dist/types/node/src/index.d.ts +6 -0
- package/dist/types/node/src/next.d.ts +39 -17
- package/dist/types/node/src/testing.d.ts +11 -0
- package/dist/types/shared/src/address.d.ts +25 -6
- package/dist/types/shared/src/collect.d.ts +7 -1
- package/dist/types/shared/src/index.d.ts +14 -0
- package/dist/types/shared/src/paths.d.ts +6 -2
- package/dist/types/shared/src/tools.d.ts +10 -0
- package/dist/types/shared/src/verdict.d.ts +6 -0
- package/dist/types/shared/src/webhooks.d.ts +32 -0
- package/dist/types-cjs/node/src/api.d.cts +139 -0
- package/dist/types-cjs/node/src/core.d.cts +8 -1
- package/dist/types-cjs/node/src/fastify.d.cts +15 -7
- package/dist/types-cjs/node/src/fetch.d.cts +12 -2
- package/dist/types-cjs/node/src/index.d.cts +6 -0
- package/dist/types-cjs/node/src/next.d.cts +39 -17
- package/dist/types-cjs/node/src/testing.d.cts +11 -0
- package/dist/types-cjs/shared/src/address.d.cts +25 -6
- package/dist/types-cjs/shared/src/collect.d.cts +7 -1
- package/dist/types-cjs/shared/src/index.d.cts +14 -0
- package/dist/types-cjs/shared/src/paths.d.cts +6 -2
- package/dist/types-cjs/shared/src/tools.d.cts +10 -0
- package/dist/types-cjs/shared/src/verdict.d.cts +6 -0
- package/dist/types-cjs/shared/src/webhooks.d.cts +32 -0
- package/package.json +3 -2
package/dist/cjs/fetch.cjs
CHANGED
|
@@ -20,9 +20,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/fetch.ts
|
|
21
21
|
var fetch_exports = {};
|
|
22
22
|
__export(fetch_exports, {
|
|
23
|
+
ReguardApiError: () => ReguardApiError,
|
|
23
24
|
ReguardConfigError: () => ReguardConfigError,
|
|
25
|
+
ReguardWebhookError: () => WebhookSignatureError,
|
|
24
26
|
defaultBlockAnswer: () => defaultBlockAnswer,
|
|
25
|
-
|
|
27
|
+
reguardApi: () => reguardApi,
|
|
28
|
+
reguardFetch: () => reguardFetch,
|
|
29
|
+
verifyWebhook: () => verifyWebhook
|
|
26
30
|
});
|
|
27
31
|
module.exports = __toCommonJS(fetch_exports);
|
|
28
32
|
|
|
@@ -283,6 +287,13 @@ function browserIncoherence(h) {
|
|
|
283
287
|
}
|
|
284
288
|
return reasons;
|
|
285
289
|
}
|
|
290
|
+
function presentsAsBrowser(h) {
|
|
291
|
+
const ua = h.userAgent ?? "";
|
|
292
|
+
if (!/^Mozilla\/5\.0 \(/.test(ua) || !h.secFetchDest) return false;
|
|
293
|
+
const tool = toolOf(ua);
|
|
294
|
+
if (tool && tool.family !== "headless_browser") return false;
|
|
295
|
+
return browserIncoherence(h).length === 0;
|
|
296
|
+
}
|
|
286
297
|
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;
|
|
287
298
|
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;
|
|
288
299
|
var BROWSER_AUTOMATIC = /^\/(?:favicon\.ico|apple-touch-icon[\w.-]*\.png|browserconfig\.xml|site\.webmanifest|manifest\.json|\.well-known\/appspecific\/)/i;
|
|
@@ -366,18 +377,21 @@ function resolveCollect(input, warn = () => {
|
|
|
366
377
|
}
|
|
367
378
|
return out;
|
|
368
379
|
}
|
|
369
|
-
function skipMatcher(patterns) {
|
|
380
|
+
function skipMatcher(patterns, ignoreCase = false) {
|
|
370
381
|
if (!patterns.length) return () => false;
|
|
371
382
|
const res = patterns.map((p) => {
|
|
372
383
|
const tail = p.endsWith("/*");
|
|
373
384
|
const body = (tail ? p.slice(0, -2) : p).split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
374
|
-
return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}
|
|
385
|
+
return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`, ignoreCase ? "i" : "");
|
|
375
386
|
});
|
|
376
387
|
return (path) => {
|
|
377
388
|
const p = path.split(/[?#]/)[0] ?? path;
|
|
378
389
|
return res.some((re) => re.test(p));
|
|
379
390
|
};
|
|
380
391
|
}
|
|
392
|
+
function protectionMatcher(patterns) {
|
|
393
|
+
return skipMatcher(patterns, true);
|
|
394
|
+
}
|
|
381
395
|
function collectAttributes(c) {
|
|
382
396
|
const a = {};
|
|
383
397
|
if (c.pages !== DEFAULT_COLLECT.pages) a["data-pages"] = c.pages;
|
|
@@ -460,6 +474,98 @@ var CLOUDFLARE_RANGES = [
|
|
|
460
474
|
"2a06:98c0::/29",
|
|
461
475
|
"2c0f:f248::/32"
|
|
462
476
|
];
|
|
477
|
+
var CLOUDFRONT_RANGES = [
|
|
478
|
+
"13.124.199.0/24",
|
|
479
|
+
"130.176.0.0/18",
|
|
480
|
+
"130.176.128.0/21",
|
|
481
|
+
"130.176.136.0/23",
|
|
482
|
+
"130.176.140.0/22",
|
|
483
|
+
"130.176.144.0/20",
|
|
484
|
+
"130.176.160.0/19",
|
|
485
|
+
"130.176.192.0/19",
|
|
486
|
+
"130.176.64.0/21",
|
|
487
|
+
"130.176.72.0/22",
|
|
488
|
+
"130.176.76.0/24",
|
|
489
|
+
"130.176.78.0/23",
|
|
490
|
+
"130.176.80.0/22",
|
|
491
|
+
"130.176.86.0/23",
|
|
492
|
+
"130.176.88.0/21",
|
|
493
|
+
"130.176.96.0/19",
|
|
494
|
+
"15.158.0.0/16",
|
|
495
|
+
"18.68.0.0/16",
|
|
496
|
+
"204.246.166.0/24",
|
|
497
|
+
"205.251.218.0/24",
|
|
498
|
+
"24.110.128.0/17",
|
|
499
|
+
"3.172.0.0/18",
|
|
500
|
+
"3.172.64.0/18",
|
|
501
|
+
"3.29.57.0/26",
|
|
502
|
+
"51.72.40.128/28",
|
|
503
|
+
"51.72.40.144/28",
|
|
504
|
+
"51.72.96.0/23",
|
|
505
|
+
"51.74.20.0/24",
|
|
506
|
+
"51.74.21.0/24",
|
|
507
|
+
"51.74.22.0/24",
|
|
508
|
+
"52.46.0.0/18",
|
|
509
|
+
"52.82.128.0/23",
|
|
510
|
+
"52.82.134.0/23",
|
|
511
|
+
"54.182.128.0/20",
|
|
512
|
+
"54.182.144.0/21",
|
|
513
|
+
"54.182.154.0/23",
|
|
514
|
+
"54.182.156.0/22",
|
|
515
|
+
"54.182.160.0/21",
|
|
516
|
+
"54.182.172.0/22",
|
|
517
|
+
"54.182.176.0/21",
|
|
518
|
+
"54.182.184.0/22",
|
|
519
|
+
"54.182.188.0/23",
|
|
520
|
+
"54.182.224.0/21",
|
|
521
|
+
"54.182.240.0/21",
|
|
522
|
+
"54.182.248.0/22",
|
|
523
|
+
"54.239.134.0/23",
|
|
524
|
+
"54.239.170.0/23",
|
|
525
|
+
"54.239.204.0/22",
|
|
526
|
+
"54.239.208.0/21",
|
|
527
|
+
"64.252.128.0/18",
|
|
528
|
+
"64.252.64.0/18",
|
|
529
|
+
"70.132.0.0/18",
|
|
530
|
+
"2001:3fc6:4::/48",
|
|
531
|
+
"2001:3fc6:5::/48",
|
|
532
|
+
"2406:da10:847f:a100::/56",
|
|
533
|
+
"2406:da11:438:2300::/56",
|
|
534
|
+
"2406:da12:4b:c200::/56",
|
|
535
|
+
"2406:da12:8b2e:9c00::/56",
|
|
536
|
+
"2406:da14:17bd:2f00::/56",
|
|
537
|
+
"2406:da14:80bb:ea00::/56",
|
|
538
|
+
"2406:da16:c01:c200::/56",
|
|
539
|
+
"2406:da18:9fa:1b00::/56",
|
|
540
|
+
"2406:da19:e19:4a00::/56",
|
|
541
|
+
"2406:da1a:6df:6c00::/56",
|
|
542
|
+
"2406:da1b:e7c:ad00::/56",
|
|
543
|
+
"2406:da1c:787:2b00::/56",
|
|
544
|
+
"2406:da1c:8d8c:4600::/56",
|
|
545
|
+
"2406:da1e:705:1600::/56",
|
|
546
|
+
"2406:da1f:396:9100::/56",
|
|
547
|
+
"2600:1f11:e79:a800::/56",
|
|
548
|
+
"2600:1f13:417:4d00::/56",
|
|
549
|
+
"2600:1f16:1923:3000::/56",
|
|
550
|
+
"2600:1f17:4356:f100::/56",
|
|
551
|
+
"2600:1f18:7530:7200::/56",
|
|
552
|
+
"2600:1f1a:4568:b500::/56",
|
|
553
|
+
"2600:1f1c:da:600::/56",
|
|
554
|
+
"2600:1f1e:a7:2300::/56",
|
|
555
|
+
"2600:9000:1000::/36",
|
|
556
|
+
"2600:9000:5200::/40",
|
|
557
|
+
"2600:9000:6000::/36",
|
|
558
|
+
"2a05:d011:531:1800::/56",
|
|
559
|
+
"2a05:d012:581:b400::/56",
|
|
560
|
+
"2a05:d014:1362:b000::/56",
|
|
561
|
+
"2a05:d016:9ed:de00::/56",
|
|
562
|
+
"2a05:d018:1a3a:2d00::/56",
|
|
563
|
+
"2a05:d019:80b:e300::/56",
|
|
564
|
+
"2a05:d01a:8a9:be00::/56",
|
|
565
|
+
"2a05:d01c:343:c300::/56",
|
|
566
|
+
"2a05:d025:e59:fb00::/56"
|
|
567
|
+
];
|
|
568
|
+
var PORT_SUFFIXED_HEADERS = ["cloudfront-viewer-address"];
|
|
463
569
|
var NON_PUBLIC_RANGES = [
|
|
464
570
|
"0.0.0.0/8",
|
|
465
571
|
"10.0.0.0/8",
|
|
@@ -589,63 +695,73 @@ function inCidr(c, b) {
|
|
|
589
695
|
return true;
|
|
590
696
|
}
|
|
591
697
|
var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
|
|
592
|
-
var
|
|
593
|
-
var
|
|
594
|
-
function
|
|
595
|
-
const
|
|
596
|
-
if (!
|
|
597
|
-
|
|
598
|
-
|
|
698
|
+
var compiled;
|
|
699
|
+
var tables = () => compiled ??= { nonPublic: compile(NON_PUBLIC_RANGES), cloudflare: compile(CLOUDFLARE_RANGES), cloudfront: compile(CLOUDFRONT_RANGES) };
|
|
700
|
+
function addressKey(address) {
|
|
701
|
+
const ip = normalizeIp(address);
|
|
702
|
+
if (!ip) return "";
|
|
703
|
+
if (!ip.includes(":")) return ip;
|
|
704
|
+
const b = parseIp(ip);
|
|
705
|
+
const prefix = new Uint8Array(16);
|
|
706
|
+
prefix.set(b.subarray(0, 8));
|
|
707
|
+
return `${formatIp(prefix)}/64`;
|
|
599
708
|
}
|
|
600
709
|
function isPublicIp(address) {
|
|
601
710
|
const b = parseIp(address);
|
|
602
|
-
return !!b && !
|
|
711
|
+
return !!b && !tables().nonPublic.some((c) => inCidr(c, b));
|
|
603
712
|
}
|
|
604
|
-
function
|
|
605
|
-
|
|
606
|
-
const entries = xff.split(",").map((s) => s.trim()).filter(Boolean).slice(-MAX_FORWARDED);
|
|
607
|
-
return [...entries, req.peer];
|
|
713
|
+
function forwardedOf(req) {
|
|
714
|
+
return (req.header("x-forwarded-for") ?? "").split(",").map((t) => t.trim()).filter(Boolean).slice(-MAX_FORWARDED).map((t) => normalizeIp(t)).filter((x) => !!x);
|
|
608
715
|
}
|
|
609
716
|
var result = (address, via) => ({ address, internal: !isPublicIp(address), via });
|
|
610
|
-
function walk(req, trusted, via) {
|
|
611
|
-
const
|
|
612
|
-
|
|
717
|
+
function walk(req, trusted, via, cdns) {
|
|
718
|
+
const peer = normalizeIp(req.peer);
|
|
719
|
+
const chain = [...forwardedOf(req), ...peer ? [peer] : []];
|
|
720
|
+
let edge = "";
|
|
613
721
|
for (let i = chain.length - 1; i >= 0; i--) {
|
|
614
|
-
const ip =
|
|
615
|
-
if (!ip) continue;
|
|
616
|
-
last ||= ip;
|
|
722
|
+
const ip = chain[i];
|
|
617
723
|
const b = parseIp(ip);
|
|
618
|
-
|
|
619
|
-
|
|
724
|
+
const { nonPublic, cloudflare, cloudfront } = tables();
|
|
725
|
+
if (nonPublic.some((c) => inCidr(c, b)) || trusted.some((c) => inCidr(c, b))) continue;
|
|
726
|
+
if (cdns && cloudfront.some((c) => inCidr(c, b))) {
|
|
727
|
+
edge = ip;
|
|
728
|
+
continue;
|
|
729
|
+
}
|
|
730
|
+
if (cdns && cloudflare.some((c) => inCidr(c, b))) {
|
|
731
|
+
const client = normalizeIp(req.header("cf-connecting-ip"));
|
|
732
|
+
return client ? result(client, "cloudflare") : { address: ip, internal: false, via };
|
|
733
|
+
}
|
|
734
|
+
return { address: ip, internal: false, via: peer && i === chain.length - 1 ? "socket" : via };
|
|
620
735
|
}
|
|
621
|
-
return { address:
|
|
736
|
+
if (edge) return { address: edge, internal: false, via };
|
|
737
|
+
return { address: chain[chain.length - 1] ?? "", internal: true, via: "socket" };
|
|
738
|
+
}
|
|
739
|
+
function headerAddress(req, name) {
|
|
740
|
+
const first = req.header(name)?.split(",")[0]?.trim();
|
|
741
|
+
if (!first) return null;
|
|
742
|
+
if (PORT_SUFFIXED_HEADERS.includes(name) && !first.startsWith("[")) return normalizeIp(first.replace(/:\d{1,5}$/, ""));
|
|
743
|
+
return normalizeIp(first);
|
|
622
744
|
}
|
|
623
745
|
function resolveClientAddress(req, mode = "auto", platform = null) {
|
|
624
746
|
const peer = normalizeIp(req.peer) ?? "";
|
|
625
747
|
if (mode === "socket") return result(peer, "socket");
|
|
626
748
|
if (typeof mode === "object" && "header" in mode) {
|
|
627
|
-
const
|
|
628
|
-
const ip = normalizeIp(first);
|
|
749
|
+
const ip = headerAddress(req, mode.header.toLowerCase());
|
|
629
750
|
return ip ? result(ip, "header") : result(peer, "socket");
|
|
630
751
|
}
|
|
631
752
|
if (typeof mode === "object" && "hops" in mode) {
|
|
632
|
-
const
|
|
633
|
-
if (
|
|
634
|
-
|
|
635
|
-
return result(chain[at], at === chain.length - 1 ? "socket" : "hops");
|
|
753
|
+
const xff = forwardedOf(req);
|
|
754
|
+
if (xff.length < mode.hops) return walk(req, [], "hops", false);
|
|
755
|
+
return result(xff[xff.length - mode.hops], "hops");
|
|
636
756
|
}
|
|
637
|
-
if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies");
|
|
757
|
+
if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies", false);
|
|
638
758
|
const framework = normalizeIp(req.framework);
|
|
639
759
|
if (framework) return result(framework, "framework");
|
|
640
760
|
if (platform) {
|
|
641
|
-
const ip =
|
|
761
|
+
const ip = headerAddress(req, PLATFORM_HEADERS[platform]);
|
|
642
762
|
if (ip) return result(ip, `platform:${platform}`);
|
|
643
763
|
}
|
|
644
|
-
|
|
645
|
-
const ip = normalizeIp(req.header("cf-connecting-ip"));
|
|
646
|
-
if (ip) return result(ip, "cloudflare");
|
|
647
|
-
}
|
|
648
|
-
return walk(req, [], "forwarded");
|
|
764
|
+
return walk(req, [], "forwarded", true);
|
|
649
765
|
}
|
|
650
766
|
function clientIpModeProblem(value) {
|
|
651
767
|
if (value === "auto" || value === "socket") return null;
|
|
@@ -695,7 +811,7 @@ function canonicalPath(target) {
|
|
|
695
811
|
const cut = t.search(/[?#]/);
|
|
696
812
|
let raw = cut === -1 ? t : t.slice(0, cut);
|
|
697
813
|
if (!raw.startsWith("/")) raw = `/${raw}`;
|
|
698
|
-
return { raw, decoded: normalizeSegments(decodeOnce(raw)) };
|
|
814
|
+
return { raw, decoded: normalizeSegments(decodeOnce(raw).replace(/\\/g, "/")) };
|
|
699
815
|
}
|
|
700
816
|
function matchesEither(matcher, p) {
|
|
701
817
|
return matcher(p.raw) || matcher(p.decoded);
|
|
@@ -707,12 +823,71 @@ function isSourceMapPath(p) {
|
|
|
707
823
|
return /\.map$/i.test(p.raw) || /\.map$/i.test(p.decoded);
|
|
708
824
|
}
|
|
709
825
|
|
|
826
|
+
// ../shared/src/webhooks.ts
|
|
827
|
+
var WEBHOOK_TOLERANCE_SECONDS = 300;
|
|
828
|
+
var WebhookSignatureError = class extends Error {
|
|
829
|
+
constructor(code, message) {
|
|
830
|
+
super(message);
|
|
831
|
+
this.code = code;
|
|
832
|
+
this.name = "ReguardWebhookError";
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
var enc2 = new TextEncoder();
|
|
836
|
+
function hmacKey2(secret) {
|
|
837
|
+
return crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
|
|
838
|
+
}
|
|
839
|
+
function signedBytes(timestamp, payload) {
|
|
840
|
+
const head = enc2.encode(`${timestamp}.`);
|
|
841
|
+
const body = typeof payload === "string" ? enc2.encode(payload) : payload;
|
|
842
|
+
const out = new Uint8Array(new ArrayBuffer(head.length + body.length));
|
|
843
|
+
out.set(head, 0);
|
|
844
|
+
out.set(body, head.length);
|
|
845
|
+
return out;
|
|
846
|
+
}
|
|
847
|
+
function unhex(s) {
|
|
848
|
+
const out = new Uint8Array(new ArrayBuffer(s.length / 2));
|
|
849
|
+
for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
|
|
850
|
+
return out;
|
|
851
|
+
}
|
|
852
|
+
function parseWebhookSignature(header) {
|
|
853
|
+
let t;
|
|
854
|
+
const v1 = [];
|
|
855
|
+
for (const part of header.split(",")) {
|
|
856
|
+
const i = part.indexOf("=");
|
|
857
|
+
if (i < 1) continue;
|
|
858
|
+
const k = part.slice(0, i).trim();
|
|
859
|
+
const v = part.slice(i + 1).trim();
|
|
860
|
+
if (k === "t" && /^\d{1,12}$/.test(v)) t = Number(v);
|
|
861
|
+
else if (k === "v1" && /^[0-9a-f]{64}$/.test(v)) v1.push(v);
|
|
862
|
+
}
|
|
863
|
+
return t === void 0 || !v1.length ? null : { t, v1 };
|
|
864
|
+
}
|
|
865
|
+
async function verifyWebhookSignature(payload, header, secret, options = {}) {
|
|
866
|
+
if (!secret) throw new WebhookSignatureError("missing_secret", "No webhook signing secret: pass it, or set REGUARD_WEBHOOK_SECRET.");
|
|
867
|
+
if (!header) throw new WebhookSignatureError("missing_signature", "No Reguard-Signature header on this request.");
|
|
868
|
+
const parsed = parseWebhookSignature(header);
|
|
869
|
+
if (!parsed) throw new WebhookSignatureError("malformed_signature", "The Reguard-Signature header isn't in the form t=\u2026,v1=\u2026.");
|
|
870
|
+
const tolerance = options.tolerance ?? WEBHOOK_TOLERANCE_SECONDS;
|
|
871
|
+
const now = options.now ?? Math.floor(Date.now() / 1e3);
|
|
872
|
+
if (tolerance > 0 && Math.abs(now - parsed.t) > tolerance) {
|
|
873
|
+
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).`);
|
|
874
|
+
}
|
|
875
|
+
const key = await hmacKey2(secret);
|
|
876
|
+
const data = signedBytes(parsed.t, payload);
|
|
877
|
+
for (const sig of parsed.v1) {
|
|
878
|
+
if (await crypto.subtle.verify("HMAC", key, unhex(sig), data)) return;
|
|
879
|
+
}
|
|
880
|
+
throw new WebhookSignatureError("bad_signature", "The signature doesn't match: check the signing secret, and pass the raw request body.");
|
|
881
|
+
}
|
|
882
|
+
|
|
710
883
|
// src/core.ts
|
|
711
884
|
var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
|
|
885
|
+
var visitorIdOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
|
|
712
886
|
function withFlagged(p, source = "browser") {
|
|
713
887
|
return {
|
|
714
888
|
...p,
|
|
715
889
|
source,
|
|
890
|
+
visitor: visitorIdOf(p.vid) ?? null,
|
|
716
891
|
flagged({ labels, minStage = "candidate" } = {}) {
|
|
717
892
|
const want = typeof labels === "string" ? [labels] : labels?.length ? labels : void 0;
|
|
718
893
|
const rank = STAGE_RANK[minStage] ?? 0;
|
|
@@ -725,8 +900,9 @@ function mergeVerdicts(browser, pushed) {
|
|
|
725
900
|
if (!browser) return withFlagged(pushed, "server");
|
|
726
901
|
const rules = new Set(browser.claims.map((c) => `${c.rule}|${c.label}|${c.stage}`));
|
|
727
902
|
const claims = [...browser.claims, ...pushed.claims.filter((c) => !rules.has(`${c.rule}|${c.label}|${c.stage}`))];
|
|
728
|
-
const { source: _s, flagged: _f, ...payload } = browser;
|
|
729
|
-
|
|
903
|
+
const { source: _s, flagged: _f, visitor: _v, ...payload } = browser;
|
|
904
|
+
const vid = visitorIdOf(payload.vid) ?? visitorIdOf(pushed.vid);
|
|
905
|
+
return withFlagged({ ...payload, ...vid ? { vid } : {}, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
|
|
730
906
|
}
|
|
731
907
|
async function readVerdictFrom(secret, site, cookieHeader) {
|
|
732
908
|
const token = cookieValue(cookieHeader, VERDICT_COOKIE);
|
|
@@ -747,8 +923,8 @@ var DEFAULT_PACE = {
|
|
|
747
923
|
api: { burst: 60, perSecond: 5 },
|
|
748
924
|
notFound: { burst: 20, perSecond: 0.5 }
|
|
749
925
|
};
|
|
750
|
-
function pushedVerdict(sid, site, claims, now = Date.now()) {
|
|
751
|
-
return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4 }, "server");
|
|
926
|
+
function pushedVerdict(sid, site, claims, now = Date.now(), vid) {
|
|
927
|
+
return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4, ...vid ? { vid } : {} }, "server");
|
|
752
928
|
}
|
|
753
929
|
var ANSWER_CODES = { flagged: "reguard.blocked", flagged_server: "reguard.blocked", require: "reguard.require", pace: "reguard.pace" };
|
|
754
930
|
var RETRY_AFTER = { flagged: 120, flagged_server: 120, require: 5, pace: 2 };
|
|
@@ -805,14 +981,16 @@ var fail = (option, code, detail) => {
|
|
|
805
981
|
var show = (v) => typeof v === "function" ? "a function" : JSON.stringify(v) ?? String(v);
|
|
806
982
|
var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
807
983
|
var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
|
808
|
-
function checkKeys(obj, allowed, prefix, moved = {}) {
|
|
984
|
+
function checkKeys(obj, allowed, prefix, moved = {}, nested) {
|
|
985
|
+
const like = (k) => (a) => a === camel(k).replace(/Seconds$|Secs$/, "Ms") || a === camel(k) || a.toLowerCase() === k.toLowerCase();
|
|
809
986
|
for (const k of Object.keys(obj)) {
|
|
810
987
|
if (obj[k] === void 0 || allowed.includes(k)) continue;
|
|
811
988
|
const path = prefix ? `${prefix}.${k}` : k;
|
|
812
989
|
if (moved[k]) fail(path, "removed_option", `was removed: ${moved[k]}`);
|
|
813
|
-
const
|
|
814
|
-
const
|
|
815
|
-
|
|
990
|
+
const here = allowed.find(like(k));
|
|
991
|
+
const below = here ? void 0 : nested?.keys.find(like(k));
|
|
992
|
+
const hint = here ? `${prefix ? `${prefix}.` : ""}${here}` : below ? `${nested.under}.${below}` : void 0;
|
|
993
|
+
fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${hint}?)` : ""}`);
|
|
816
994
|
}
|
|
817
995
|
}
|
|
818
996
|
function checkBoolean(v, option) {
|
|
@@ -1063,6 +1241,68 @@ var Health = class {
|
|
|
1063
1241
|
}
|
|
1064
1242
|
};
|
|
1065
1243
|
|
|
1244
|
+
// src/api.ts
|
|
1245
|
+
var ReguardApiError = class extends Error {
|
|
1246
|
+
constructor(status, message) {
|
|
1247
|
+
super(message);
|
|
1248
|
+
this.status = status;
|
|
1249
|
+
this.name = "ReguardApiError";
|
|
1250
|
+
}
|
|
1251
|
+
};
|
|
1252
|
+
function reguardApi(options = {}) {
|
|
1253
|
+
const key = (options.key?.trim() || envValue("REGUARD_KEY"))?.trim();
|
|
1254
|
+
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)");
|
|
1255
|
+
const base = collectorBase(options.collector || envValue("REGUARD_COLLECTOR"));
|
|
1256
|
+
const doFetch = options.fetch ?? fetch;
|
|
1257
|
+
const timeoutMs = options.timeoutMs ?? 1e4;
|
|
1258
|
+
async function get(path) {
|
|
1259
|
+
if (!key) throw new ReguardApiError(0, "No site key: pass { key } or set REGUARD_KEY.");
|
|
1260
|
+
if (!parseSiteKey(key)?.site) throw new ReguardApiError(0, "REGUARD_KEY isn't a site key (rgk.<site>.v<n>.\u2026).");
|
|
1261
|
+
let res;
|
|
1262
|
+
try {
|
|
1263
|
+
res = await doFetch(`${base}${path}`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
|
|
1264
|
+
} catch (e) {
|
|
1265
|
+
throw new ReguardApiError(0, `Reguard's API can't be reached: ${e.message}`);
|
|
1266
|
+
}
|
|
1267
|
+
const parsed = await res.json().catch(() => null);
|
|
1268
|
+
const body = parsed && typeof parsed === "object" ? parsed : {};
|
|
1269
|
+
if (!res.ok) throw new ReguardApiError(res.status, typeof body.error === "string" && body.error ? body.error : `Reguard's API answered ${res.status}`);
|
|
1270
|
+
return body;
|
|
1271
|
+
}
|
|
1272
|
+
return {
|
|
1273
|
+
async visitor(id) {
|
|
1274
|
+
if (!visitorIdOf(id)) throw new ReguardApiError(400, "Not a visitor id: they look like vis_ followed by 22 characters.");
|
|
1275
|
+
return (await get(`/v1/visitors/${id}`)).visitor;
|
|
1276
|
+
},
|
|
1277
|
+
events({ after, limit, types } = {}) {
|
|
1278
|
+
const q = new URLSearchParams();
|
|
1279
|
+
if (after) q.set("after", after);
|
|
1280
|
+
if (typeof limit === "number" && Number.isInteger(limit) && limit > 0) q.set("limit", String(limit));
|
|
1281
|
+
if (types?.length) q.set("type", types.join(","));
|
|
1282
|
+
const qs = q.toString();
|
|
1283
|
+
return get(`/v1/events${qs ? `?${qs}` : ""}`);
|
|
1284
|
+
}
|
|
1285
|
+
};
|
|
1286
|
+
}
|
|
1287
|
+
async function verifyWebhook(payload, signature, secret, options = {}) {
|
|
1288
|
+
if (typeof payload !== "string" && !(payload instanceof Uint8Array) && !(payload instanceof ArrayBuffer)) {
|
|
1289
|
+
throw new TypeError(
|
|
1290
|
+
'[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.'
|
|
1291
|
+
);
|
|
1292
|
+
}
|
|
1293
|
+
const raw = payload instanceof ArrayBuffer ? new Uint8Array(payload) : payload;
|
|
1294
|
+
const header = Array.isArray(signature) ? signature[0] : signature;
|
|
1295
|
+
await verifyWebhookSignature(raw, header, secret || envValue("REGUARD_WEBHOOK_SECRET"), options);
|
|
1296
|
+
let event;
|
|
1297
|
+
try {
|
|
1298
|
+
event = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw));
|
|
1299
|
+
} catch {
|
|
1300
|
+
throw new WebhookSignatureError("bad_payload", "The body isn't JSON (a Slack or Discord URL gets messages, not events).");
|
|
1301
|
+
}
|
|
1302
|
+
if (!event || typeof event.id !== "string" || typeof event.type !== "string") throw new WebhookSignatureError("bad_payload", "The body isn't a Reguard event.");
|
|
1303
|
+
return event;
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1066
1306
|
// src/fetch.ts
|
|
1067
1307
|
var OPTION_KEYS = [
|
|
1068
1308
|
"key",
|
|
@@ -1083,15 +1323,15 @@ var OPTION_KEYS = [
|
|
|
1083
1323
|
"fetch",
|
|
1084
1324
|
"onError"
|
|
1085
1325
|
];
|
|
1086
|
-
var
|
|
1326
|
+
var enc3 = new TextEncoder();
|
|
1087
1327
|
var keys2 = /* @__PURE__ */ new Map();
|
|
1088
1328
|
async function hmac(secret, text, length) {
|
|
1089
1329
|
let k = keys2.get(secret);
|
|
1090
1330
|
if (!k) {
|
|
1091
|
-
k = crypto.subtle.importKey("raw",
|
|
1331
|
+
k = crypto.subtle.importKey("raw", enc3.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
1092
1332
|
keys2.set(secret, k);
|
|
1093
1333
|
}
|
|
1094
|
-
const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await k,
|
|
1334
|
+
const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await k, enc3.encode(text)));
|
|
1095
1335
|
let s = "";
|
|
1096
1336
|
for (const b of sig) s += String.fromCharCode(b);
|
|
1097
1337
|
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "").slice(0, length);
|
|
@@ -1125,7 +1365,7 @@ function reguardFetch(options = {}) {
|
|
|
1125
1365
|
checkFunction(options.fetch, "fetch");
|
|
1126
1366
|
checkFunction(options.onError, "onError");
|
|
1127
1367
|
const log = makeLog(checkLogger(options.logger), checkBoolean(options.debug, "debug") ?? /^(?:1|true|yes)$/i.test(envValue("REGUARD_DEBUG") ?? ""));
|
|
1128
|
-
const ignore = options.ignore?.length ?
|
|
1368
|
+
const ignore = options.ignore?.length ? protectionMatcher(options.ignore) : void 0;
|
|
1129
1369
|
const key = (options.key ?? envValue("REGUARD_KEY"))?.trim();
|
|
1130
1370
|
const parsed = parseSiteKey(key);
|
|
1131
1371
|
const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
|
|
@@ -1145,6 +1385,12 @@ function reguardFetch(options = {}) {
|
|
|
1145
1385
|
decision: () => null,
|
|
1146
1386
|
scriptTag: () => "",
|
|
1147
1387
|
flush: async () => {
|
|
1388
|
+
},
|
|
1389
|
+
visitor: async () => {
|
|
1390
|
+
throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
|
|
1391
|
+
},
|
|
1392
|
+
events: async () => {
|
|
1393
|
+
throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
|
|
1148
1394
|
}
|
|
1149
1395
|
};
|
|
1150
1396
|
}
|
|
@@ -1153,12 +1399,13 @@ function reguardFetch(options = {}) {
|
|
|
1153
1399
|
const prev = parseSiteKey((options.previousKey ?? envValue("REGUARD_KEY_PREVIOUS"))?.trim());
|
|
1154
1400
|
if (prev?.site === site && prev.secret !== parsed.secret) secrets.push(prev.secret);
|
|
1155
1401
|
const collector = collectorBase(options.collector ?? envValue("REGUARD_COLLECTOR"));
|
|
1402
|
+
const api = reguardApi({ key, collector, fetch: doFetch, timeoutMs });
|
|
1156
1403
|
const platform = options.platform ?? detectPlatform(typeof process !== "undefined" ? process.env : void 0) ?? (typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" ? "workers" : null);
|
|
1157
1404
|
const health = new Health(log);
|
|
1158
1405
|
const allDry = !block || BLOCK_REASONS.every((r) => block.dryRun.has(r));
|
|
1159
1406
|
const denyMaps = (options.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
|
|
1160
1407
|
const allowList = block?.allow.length ? skipMatcher(block.allow) : void 0;
|
|
1161
|
-
const skipped =
|
|
1408
|
+
const skipped = protectionMatcher(collect.skip);
|
|
1162
1409
|
const tagSettings = { site, collect, cookieDomain };
|
|
1163
1410
|
const pace = block?.pace;
|
|
1164
1411
|
const pages = pace ? new Allowance(pace.documents.burst, pace.documents.perSecond / 1e3, 5e4) : void 0;
|
|
@@ -1204,8 +1451,9 @@ function reguardFetch(options = {}) {
|
|
|
1204
1451
|
health.ok();
|
|
1205
1452
|
const f = (await res.json().catch(() => null))?.flagged;
|
|
1206
1453
|
const now = Date.now();
|
|
1207
|
-
|
|
1208
|
-
for (const x of f?.
|
|
1454
|
+
const vidOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
|
|
1455
|
+
for (const x of f?.sessions ?? []) if (typeof x.sid === "string" && Array.isArray(x.claims)) pushed.set(`s:${x.sid}`, { claims: x.claims, until: now + 6e5, vid: vidOf(x.vid) });
|
|
1456
|
+
for (const x of f?.visitors ?? []) if (typeof x.visitor === "string" && Array.isArray(x.claims)) pushed.set(`v:${x.visitor}`, { claims: x.claims, until: now + 6e5, vid: vidOf(x.vid) });
|
|
1209
1457
|
if (pushed.size > 5e4) pushed.clear();
|
|
1210
1458
|
}
|
|
1211
1459
|
if (!res.ok) onError(new Error(`collector answered ${res.status} to /v1/server`));
|
|
@@ -1216,11 +1464,10 @@ function reguardFetch(options = {}) {
|
|
|
1216
1464
|
}
|
|
1217
1465
|
if (!health.canSend()) queue.length = 0;
|
|
1218
1466
|
};
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
if (!
|
|
1222
|
-
|
|
1223
|
-
waitUntil?.(inflight);
|
|
1467
|
+
let lastUrgent = 0;
|
|
1468
|
+
const flushSoon = (now = false) => {
|
|
1469
|
+
if (queue.length && !inflight && (now || Date.now() - lastFlush >= flushIntervalMs || queue.length >= 100)) inflight = flush().finally(() => inflight = void 0);
|
|
1470
|
+
return inflight;
|
|
1224
1471
|
};
|
|
1225
1472
|
const pushedFor = async (request, verified) => {
|
|
1226
1473
|
if (!pushed.size) return null;
|
|
@@ -1229,12 +1476,18 @@ function reguardFetch(options = {}) {
|
|
|
1229
1476
|
const now = Date.now();
|
|
1230
1477
|
const claims = [];
|
|
1231
1478
|
const k = [sid ? `s:${sid}` : ""];
|
|
1232
|
-
|
|
1479
|
+
const get = (n) => request.headers.get(n) ?? void 0;
|
|
1480
|
+
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") });
|
|
1481
|
+
if (collect.addresses !== "off" && !verified && !a.internal && !browser && a.address) k.push(`v:${await hmac(parsed.secret, `visitor:${addressKey(a.address) || a.address}`, 22)}`);
|
|
1482
|
+
let vid;
|
|
1233
1483
|
for (const x of k) {
|
|
1234
1484
|
const e = x ? pushed.get(x) : void 0;
|
|
1235
|
-
if (e && e.until > now)
|
|
1485
|
+
if (e && e.until > now) {
|
|
1486
|
+
claims.push(...e.claims);
|
|
1487
|
+
vid ??= e.vid;
|
|
1488
|
+
}
|
|
1236
1489
|
}
|
|
1237
|
-
return claims.length ? pushedVerdict(sid ?? "", site, claims, now) : null;
|
|
1490
|
+
return claims.length ? pushedVerdict(sid ?? "", site, claims, now, vid) : null;
|
|
1238
1491
|
};
|
|
1239
1492
|
const proxy = async (request, p) => {
|
|
1240
1493
|
const url = new URL(request.url);
|
|
@@ -1254,14 +1507,11 @@ function reguardFetch(options = {}) {
|
|
|
1254
1507
|
if (sid && /^[\w-]{1,64}$/.test(sid)) headers.set("cookie", `${SESSION_COOKIE}=${sid}`);
|
|
1255
1508
|
headers.set("x-reguard-site", `${site}.${await hmac(parsed.secret, `prefix:${site}`, 16)}`);
|
|
1256
1509
|
const a = addressFor(request);
|
|
1257
|
-
const value = collect.addresses === "off" || !a.address ? "-" : await hmac(parsed.secret, `visitor:${a.address}`, 22);
|
|
1510
|
+
const value = collect.addresses === "off" || !a.address ? "-" : await hmac(parsed.secret, `visitor:${addressKey(a.address) || a.address}`, 22);
|
|
1258
1511
|
headers.set("x-reguard-visitor", `${value}.${await hmac(parsed.secret, `visitor-header:${value}`, 16)}`);
|
|
1259
1512
|
try {
|
|
1260
1513
|
const init = { method: request.method, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) };
|
|
1261
|
-
if (request.method !== "GET" && request.method !== "HEAD" && request.body)
|
|
1262
|
-
init.body = request.body;
|
|
1263
|
-
init.duplex = "half";
|
|
1264
|
-
}
|
|
1514
|
+
if (request.method !== "GET" && request.method !== "HEAD" && request.body) init.body = await request.arrayBuffer();
|
|
1265
1515
|
const r = await doFetch(`${collector}${p.decoded}${url.search}`, init);
|
|
1266
1516
|
const out = new Headers();
|
|
1267
1517
|
r.headers.forEach((v, k) => {
|
|
@@ -1293,7 +1543,7 @@ function reguardFetch(options = {}) {
|
|
|
1293
1543
|
} catch (e) {
|
|
1294
1544
|
log.once("onBlock-threw", "warn", `block.onBlock threw: ${e?.message ?? e}`);
|
|
1295
1545
|
}
|
|
1296
|
-
log.debug(`${d.dryRun ? "would block" : "blocked"} ${request.method} ${d.path}: ${d.reason}`);
|
|
1546
|
+
log.debug(`${d.dryRun ? "would block" : "blocked"} ${request.method} ${d.path}: ${d.reason}${d.pace ? ` (${d.pace})` : ""} from ${d.clientIp}`);
|
|
1297
1547
|
if (d.dryRun) return void 0;
|
|
1298
1548
|
const respond = block.respond;
|
|
1299
1549
|
if (respond) {
|
|
@@ -1313,9 +1563,9 @@ function reguardFetch(options = {}) {
|
|
|
1313
1563
|
if (denyMaps && isSourceMapPath(p)) return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
|
|
1314
1564
|
const cookie = request.headers.get("cookie");
|
|
1315
1565
|
const pending = (async () => {
|
|
1316
|
-
const
|
|
1317
|
-
const pushedV = await pushedFor(request, !!
|
|
1318
|
-
return { browser, pushed: pushedV, merged: mergeVerdicts(
|
|
1566
|
+
const browser2 = await readVerdict(cookie);
|
|
1567
|
+
const pushedV = await pushedFor(request, !!browser2);
|
|
1568
|
+
return { browser: browser2, pushed: pushedV, merged: mergeVerdicts(browser2, pushedV) };
|
|
1319
1569
|
})();
|
|
1320
1570
|
verdicts.set(request, pending);
|
|
1321
1571
|
if (!block) return void 0;
|
|
@@ -1328,10 +1578,11 @@ function reguardFetch(options = {}) {
|
|
|
1328
1578
|
})();
|
|
1329
1579
|
if (allowed) return void 0;
|
|
1330
1580
|
const get = (n) => request.headers.get(n) ?? void 0;
|
|
1331
|
-
|
|
1581
|
+
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") });
|
|
1582
|
+
if (pages && !browser && (request.method === "GET" || request.method === "HEAD") && requestKind(p.decoded) === "document" && !isSpeculativeHeaders(get)) {
|
|
1332
1583
|
const tool = toolOf(get("user-agent"));
|
|
1333
1584
|
const a = addressFor(request);
|
|
1334
|
-
if (!(tool && BENIGN_TOOL_FAMILIES.has(tool.family)) && a.address && !a.internal && !pages.take(a.address)) {
|
|
1585
|
+
if (!(tool && BENIGN_TOOL_FAMILIES.has(tool.family)) && a.address && !a.internal && !pages.take(addressKey(a.address) || a.address)) {
|
|
1335
1586
|
const answered = await act(request, decide(request, "pace", p, null, "document"));
|
|
1336
1587
|
if (answered) return answered;
|
|
1337
1588
|
}
|
|
@@ -1347,7 +1598,7 @@ function reguardFetch(options = {}) {
|
|
|
1347
1598
|
};
|
|
1348
1599
|
const record = (request, response, ctx) => {
|
|
1349
1600
|
if (!collect.requests) return;
|
|
1350
|
-
|
|
1601
|
+
const task = (async () => {
|
|
1351
1602
|
try {
|
|
1352
1603
|
const url = new URL(request.url);
|
|
1353
1604
|
const p = canonicalPath(url.pathname);
|
|
@@ -1356,18 +1607,19 @@ function reguardFetch(options = {}) {
|
|
|
1356
1607
|
const sid = cookieValue(get("cookie"), SESSION_COOKIE);
|
|
1357
1608
|
const decision = decisions.get(request);
|
|
1358
1609
|
const target = `${url.pathname}${url.search}`;
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
if (!
|
|
1610
|
+
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 });
|
|
1611
|
+
const tool = toolLike();
|
|
1612
|
+
if (!decision) {
|
|
1613
|
+
if (!sid && (options.watchSessionless === false || collect.addresses === "off" || !tool)) return;
|
|
1614
|
+
if (sid && !response && !tool) return;
|
|
1363
1615
|
}
|
|
1364
1616
|
const a = addressFor(request);
|
|
1365
1617
|
const hash = (s) => hmac(parsed.secret, s, 16);
|
|
1366
|
-
const contentType = response
|
|
1367
|
-
const responseBytes = Number(response
|
|
1618
|
+
const contentType = response?.headers.get("content-type") ?? "";
|
|
1619
|
+
const responseBytes = Number(response?.headers.get("content-length") ?? 0) || 0;
|
|
1368
1620
|
const requestBytes = Number(get("content-length") ?? 0) || 0;
|
|
1369
1621
|
let exchange;
|
|
1370
|
-
if (!isSpeculativeHeaders(get) && isApiLike(target, contentType, requestBytes)) {
|
|
1622
|
+
if (response && !isSpeculativeHeaders(get) && isApiLike(target, contentType, requestBytes)) {
|
|
1371
1623
|
const input = { method: request.method, url: target, requestContentType: get("content-type") ?? "", requestBody: "", requestBytes, status: response.status, responseContentType: contentType, responseBytes };
|
|
1372
1624
|
const wanted = /* @__PURE__ */ new Set();
|
|
1373
1625
|
describeExchange((s) => (wanted.add(s), ""), input);
|
|
@@ -1387,7 +1639,7 @@ function reguardFetch(options = {}) {
|
|
|
1387
1639
|
url: collect.pages === "masked" ? privateUrl(target) : "",
|
|
1388
1640
|
...collect.pages !== "off" ? { item: await hash(`path:${url.pathname}`) } : {},
|
|
1389
1641
|
...collect.pages !== "masked" ? { traits: pathTraits(target, get("rsc") === "1") } : {},
|
|
1390
|
-
status: response.status,
|
|
1642
|
+
...response ? { status: response.status } : {},
|
|
1391
1643
|
headers: Object.fromEntries(["rsc", "next-router-prefetch", "sec-purpose", "purpose"].flatMap((n) => get(n) !== void 0 ? [[n, get(n)]] : [])),
|
|
1392
1644
|
client: {
|
|
1393
1645
|
ua: get("user-agent") ?? "",
|
|
@@ -1401,26 +1653,28 @@ function reguardFetch(options = {}) {
|
|
|
1401
1653
|
hasReferer: !!get("referer"),
|
|
1402
1654
|
...url.protocol === "https:" ? { secure: true } : {}
|
|
1403
1655
|
},
|
|
1404
|
-
...!sid && a.address && collect.addresses !== "off" ? { visitor: await hmac(parsed.secret, `visitor:${a.address}`, 22) } : {},
|
|
1656
|
+
...!sid && a.address && collect.addresses !== "off" ? { visitor: await hmac(parsed.secret, `visitor:${addressKey(a.address) || a.address}`, 22) } : {},
|
|
1405
1657
|
...exchange ? { exchange } : {},
|
|
1406
1658
|
...decision?.pace ? { pace: decision.pace } : {},
|
|
1407
1659
|
...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
|
|
1408
1660
|
...a.internal ? { internal: true } : {}
|
|
1409
1661
|
});
|
|
1410
1662
|
if (queue.length > 5e3) queue.splice(0, queue.length - 5e3);
|
|
1411
|
-
const waitUntil = ctx?.waitUntil ? (p2) => ctx.waitUntil.call(ctx, p2) : void 0;
|
|
1412
1663
|
ensureTimer();
|
|
1413
|
-
|
|
1664
|
+
const urgent = !!decision || tool && Date.now() - lastUrgent >= 500;
|
|
1665
|
+
if (urgent) lastUrgent = Date.now();
|
|
1666
|
+
await flushSoon(urgent);
|
|
1414
1667
|
} catch (e) {
|
|
1415
1668
|
onError(e);
|
|
1416
1669
|
}
|
|
1417
1670
|
})();
|
|
1671
|
+
ctx?.waitUntil?.call(ctx, task);
|
|
1418
1672
|
};
|
|
1419
1673
|
let timer;
|
|
1420
1674
|
const ensureTimer = () => {
|
|
1421
1675
|
if (timer !== void 0 || platform === "workers" || typeof setInterval !== "function") return;
|
|
1422
1676
|
try {
|
|
1423
|
-
timer = setInterval(() => flushSoon(
|
|
1677
|
+
timer = setInterval(() => void flushSoon(true), flushIntervalMs);
|
|
1424
1678
|
timer.unref?.();
|
|
1425
1679
|
} catch {
|
|
1426
1680
|
timer = null;
|
|
@@ -1452,12 +1706,18 @@ function reguardFetch(options = {}) {
|
|
|
1452
1706
|
flush: async () => {
|
|
1453
1707
|
await inflight;
|
|
1454
1708
|
await flush();
|
|
1455
|
-
}
|
|
1709
|
+
},
|
|
1710
|
+
visitor: (id) => api.visitor(id),
|
|
1711
|
+
events: (q) => api.events(q)
|
|
1456
1712
|
};
|
|
1457
1713
|
}
|
|
1458
1714
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1459
1715
|
0 && (module.exports = {
|
|
1716
|
+
ReguardApiError,
|
|
1460
1717
|
ReguardConfigError,
|
|
1718
|
+
ReguardWebhookError,
|
|
1461
1719
|
defaultBlockAnswer,
|
|
1462
|
-
|
|
1720
|
+
reguardApi,
|
|
1721
|
+
reguardFetch,
|
|
1722
|
+
verifyWebhook
|
|
1463
1723
|
});
|