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