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/README.md
CHANGED
|
@@ -33,7 +33,27 @@ app.get("/api/export", (req, res) => {
|
|
|
33
33
|
```
|
|
34
34
|
|
|
35
35
|
`req.reguard` is the visitor's verified verdict (or `null`): its `claims`, where they came from
|
|
36
|
-
(`source`: the browser, your server's summaries, or both)
|
|
36
|
+
(`source`: the browser, your server's summaries, or both), `flagged({ labels, minStage })`, and
|
|
37
|
+
`visitor`, Reguard's id for the visitor across its page loads. It's signed, so trust it over any
|
|
38
|
+
cookie: store it with your user's session, look it up, or match it to webhook events.
|
|
39
|
+
|
|
40
|
+
## Visitors and webhooks
|
|
41
|
+
|
|
42
|
+
```js
|
|
43
|
+
import { reguardApi, verifyWebhook } from "reguard";
|
|
44
|
+
|
|
45
|
+
const v = await reguardApi().visitor(req.reguard.visitor); // REGUARD_KEY from the environment
|
|
46
|
+
if (v.caught) { /* v.labels, v.stage, v.catches, v.returns */ }
|
|
47
|
+
|
|
48
|
+
app.post("/hooks/reguard", express.raw({ type: "application/json" }), async (req, res) => {
|
|
49
|
+
const event = await verifyWebhook(req.body, req.headers["reguard-signature"]); // REGUARD_WEBHOOK_SECRET
|
|
50
|
+
// event.type: "visitor.caught", "visitor.escalated", "visitor.returned" or "ping"
|
|
51
|
+
res.sendStatus(204);
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Add webhook URLs under Settings, Notifications. Prefer polling? `reguardApi().events({ after })`
|
|
56
|
+
returns the same events, oldest first, with a cursor.
|
|
37
57
|
|
|
38
58
|
## Block: dry run first
|
|
39
59
|
|
|
@@ -56,8 +76,8 @@ Dry-run decisions are on `req.reguardDecision` and in the dashboard as "would ha
|
|
|
56
76
|
|
|
57
77
|
- **Fastify:** `import reguard from "reguard/fastify"` then `await app.register(reguard, { block: true })`;
|
|
58
78
|
reads `request.ip` when `trustProxy` is set, and sets `request.reguard`.
|
|
59
|
-
- **Next.js:** `
|
|
60
|
-
|
|
79
|
+
- **Next.js:** `reguardMiddleware({ block: true })` in `middleware.ts` (or `proxy.ts`), which also
|
|
80
|
+
serves `/_s/*`, and `<Script {...reguardScriptProps()} />`, from `reguard/next`.
|
|
61
81
|
- **Hono, Remix, SvelteKit, Astro, Bun, Deno, Workers:** `reguardFetch()` from `reguard/fetch`, then
|
|
62
82
|
`export default { fetch: rg.wrap(app.fetch) }`.
|
|
63
83
|
|
|
@@ -71,6 +91,8 @@ const cookie = await verdictCookie(key, { claims: [claim("unauthorized_extractio
|
|
|
71
91
|
await request(app).get("/api/items").set("cookie", cookie).expect(429);
|
|
72
92
|
```
|
|
73
93
|
|
|
94
|
+
`signWebhook(secret, body)` signs a made-up delivery for testing your webhook handler.
|
|
95
|
+
|
|
74
96
|
## More
|
|
75
97
|
|
|
76
98
|
- Choose what Reguard receives with `collect` (pages, addresses, behavior, requests, skip).
|
|
@@ -268,6 +268,13 @@ function browserIncoherence(h) {
|
|
|
268
268
|
}
|
|
269
269
|
return reasons;
|
|
270
270
|
}
|
|
271
|
+
function presentsAsBrowser(h) {
|
|
272
|
+
const ua = h.userAgent ?? "";
|
|
273
|
+
if (!/^Mozilla\/5\.0 \(/.test(ua) || !h.secFetchDest) return false;
|
|
274
|
+
const tool = toolOf(ua);
|
|
275
|
+
if (tool && tool.family !== "headless_browser") return false;
|
|
276
|
+
return browserIncoherence(h).length === 0;
|
|
277
|
+
}
|
|
271
278
|
var SENSITIVE_PATH = /^\/(\.env|\.git|\.svn|\.hg|\.DS_Store|\.aws|\.ssh|\.htaccess|\.htpasswd|web\.config|wp-admin|wp-login\.php|xmlrpc\.php|phpinfo|phpmyadmin|server-status|server-info|actuator|backup|dump\.sql|config\.(?:json|ya?ml|php|js)|swagger|openapi|api-docs|admin|debug|console)(?=$|[/.?#_-])/i;
|
|
272
279
|
var DISCOVERY_FILE = /^\/(?:robots\.txt|sitemap[\w-]*\.xml(?:\.gz)?|\.well-known\/security\.txt|security\.txt|humans\.txt|crossdomain\.xml|asset-manifest\.json|_next\/static\/[^/]+\/_buildManifest\.js)$/i;
|
|
273
280
|
var BROWSER_AUTOMATIC = /^\/(?:favicon\.ico|apple-touch-icon[\w.-]*\.png|browserconfig\.xml|site\.webmanifest|manifest\.json|\.well-known\/appspecific\/)/i;
|
|
@@ -351,18 +358,21 @@ function resolveCollect(input, warn = () => {
|
|
|
351
358
|
}
|
|
352
359
|
return out;
|
|
353
360
|
}
|
|
354
|
-
function skipMatcher(patterns) {
|
|
361
|
+
function skipMatcher(patterns, ignoreCase = false) {
|
|
355
362
|
if (!patterns.length) return () => false;
|
|
356
363
|
const res = patterns.map((p) => {
|
|
357
364
|
const tail = p.endsWith("/*");
|
|
358
365
|
const body = (tail ? p.slice(0, -2) : p).split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
359
|
-
return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}
|
|
366
|
+
return new RegExp(`^${body}${tail ? "(?:/.*)?" : ""}$`, ignoreCase ? "i" : "");
|
|
360
367
|
});
|
|
361
368
|
return (path) => {
|
|
362
369
|
const p = path.split(/[?#]/)[0] ?? path;
|
|
363
370
|
return res.some((re) => re.test(p));
|
|
364
371
|
};
|
|
365
372
|
}
|
|
373
|
+
function protectionMatcher(patterns) {
|
|
374
|
+
return skipMatcher(patterns, true);
|
|
375
|
+
}
|
|
366
376
|
function collectAttributes(c) {
|
|
367
377
|
const a = {};
|
|
368
378
|
if (c.pages !== DEFAULT_COLLECT.pages) a["data-pages"] = c.pages;
|
|
@@ -445,6 +455,98 @@ var CLOUDFLARE_RANGES = [
|
|
|
445
455
|
"2a06:98c0::/29",
|
|
446
456
|
"2c0f:f248::/32"
|
|
447
457
|
];
|
|
458
|
+
var CLOUDFRONT_RANGES = [
|
|
459
|
+
"13.124.199.0/24",
|
|
460
|
+
"130.176.0.0/18",
|
|
461
|
+
"130.176.128.0/21",
|
|
462
|
+
"130.176.136.0/23",
|
|
463
|
+
"130.176.140.0/22",
|
|
464
|
+
"130.176.144.0/20",
|
|
465
|
+
"130.176.160.0/19",
|
|
466
|
+
"130.176.192.0/19",
|
|
467
|
+
"130.176.64.0/21",
|
|
468
|
+
"130.176.72.0/22",
|
|
469
|
+
"130.176.76.0/24",
|
|
470
|
+
"130.176.78.0/23",
|
|
471
|
+
"130.176.80.0/22",
|
|
472
|
+
"130.176.86.0/23",
|
|
473
|
+
"130.176.88.0/21",
|
|
474
|
+
"130.176.96.0/19",
|
|
475
|
+
"15.158.0.0/16",
|
|
476
|
+
"18.68.0.0/16",
|
|
477
|
+
"204.246.166.0/24",
|
|
478
|
+
"205.251.218.0/24",
|
|
479
|
+
"24.110.128.0/17",
|
|
480
|
+
"3.172.0.0/18",
|
|
481
|
+
"3.172.64.0/18",
|
|
482
|
+
"3.29.57.0/26",
|
|
483
|
+
"51.72.40.128/28",
|
|
484
|
+
"51.72.40.144/28",
|
|
485
|
+
"51.72.96.0/23",
|
|
486
|
+
"51.74.20.0/24",
|
|
487
|
+
"51.74.21.0/24",
|
|
488
|
+
"51.74.22.0/24",
|
|
489
|
+
"52.46.0.0/18",
|
|
490
|
+
"52.82.128.0/23",
|
|
491
|
+
"52.82.134.0/23",
|
|
492
|
+
"54.182.128.0/20",
|
|
493
|
+
"54.182.144.0/21",
|
|
494
|
+
"54.182.154.0/23",
|
|
495
|
+
"54.182.156.0/22",
|
|
496
|
+
"54.182.160.0/21",
|
|
497
|
+
"54.182.172.0/22",
|
|
498
|
+
"54.182.176.0/21",
|
|
499
|
+
"54.182.184.0/22",
|
|
500
|
+
"54.182.188.0/23",
|
|
501
|
+
"54.182.224.0/21",
|
|
502
|
+
"54.182.240.0/21",
|
|
503
|
+
"54.182.248.0/22",
|
|
504
|
+
"54.239.134.0/23",
|
|
505
|
+
"54.239.170.0/23",
|
|
506
|
+
"54.239.204.0/22",
|
|
507
|
+
"54.239.208.0/21",
|
|
508
|
+
"64.252.128.0/18",
|
|
509
|
+
"64.252.64.0/18",
|
|
510
|
+
"70.132.0.0/18",
|
|
511
|
+
"2001:3fc6:4::/48",
|
|
512
|
+
"2001:3fc6:5::/48",
|
|
513
|
+
"2406:da10:847f:a100::/56",
|
|
514
|
+
"2406:da11:438:2300::/56",
|
|
515
|
+
"2406:da12:4b:c200::/56",
|
|
516
|
+
"2406:da12:8b2e:9c00::/56",
|
|
517
|
+
"2406:da14:17bd:2f00::/56",
|
|
518
|
+
"2406:da14:80bb:ea00::/56",
|
|
519
|
+
"2406:da16:c01:c200::/56",
|
|
520
|
+
"2406:da18:9fa:1b00::/56",
|
|
521
|
+
"2406:da19:e19:4a00::/56",
|
|
522
|
+
"2406:da1a:6df:6c00::/56",
|
|
523
|
+
"2406:da1b:e7c:ad00::/56",
|
|
524
|
+
"2406:da1c:787:2b00::/56",
|
|
525
|
+
"2406:da1c:8d8c:4600::/56",
|
|
526
|
+
"2406:da1e:705:1600::/56",
|
|
527
|
+
"2406:da1f:396:9100::/56",
|
|
528
|
+
"2600:1f11:e79:a800::/56",
|
|
529
|
+
"2600:1f13:417:4d00::/56",
|
|
530
|
+
"2600:1f16:1923:3000::/56",
|
|
531
|
+
"2600:1f17:4356:f100::/56",
|
|
532
|
+
"2600:1f18:7530:7200::/56",
|
|
533
|
+
"2600:1f1a:4568:b500::/56",
|
|
534
|
+
"2600:1f1c:da:600::/56",
|
|
535
|
+
"2600:1f1e:a7:2300::/56",
|
|
536
|
+
"2600:9000:1000::/36",
|
|
537
|
+
"2600:9000:5200::/40",
|
|
538
|
+
"2600:9000:6000::/36",
|
|
539
|
+
"2a05:d011:531:1800::/56",
|
|
540
|
+
"2a05:d012:581:b400::/56",
|
|
541
|
+
"2a05:d014:1362:b000::/56",
|
|
542
|
+
"2a05:d016:9ed:de00::/56",
|
|
543
|
+
"2a05:d018:1a3a:2d00::/56",
|
|
544
|
+
"2a05:d019:80b:e300::/56",
|
|
545
|
+
"2a05:d01a:8a9:be00::/56",
|
|
546
|
+
"2a05:d01c:343:c300::/56",
|
|
547
|
+
"2a05:d025:e59:fb00::/56"
|
|
548
|
+
];
|
|
549
|
+
var PORT_SUFFIXED_HEADERS = ["cloudfront-viewer-address"];
|
|
448
550
|
var NON_PUBLIC_RANGES = [
|
|
449
551
|
"0.0.0.0/8",
|
|
450
552
|
"10.0.0.0/8",
|
|
@@ -529,9 +631,9 @@ function formatIp(b) {
|
|
|
529
631
|
}
|
|
530
632
|
i = j;
|
|
531
633
|
}
|
|
532
|
-
const
|
|
533
|
-
if (best === -1) return
|
|
534
|
-
return `${
|
|
634
|
+
const hex2 = (xs) => xs.map((x) => x.toString(16)).join(":");
|
|
635
|
+
if (best === -1) return hex2(g);
|
|
636
|
+
return `${hex2(g.slice(0, best))}::${hex2(g.slice(best + bestLen))}`;
|
|
535
637
|
}
|
|
536
638
|
function normalizeIp(token) {
|
|
537
639
|
if (!token) return null;
|
|
@@ -574,63 +676,73 @@ function inCidr(c, b) {
|
|
|
574
676
|
return true;
|
|
575
677
|
}
|
|
576
678
|
var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
|
|
577
|
-
var
|
|
578
|
-
var
|
|
579
|
-
function
|
|
580
|
-
const
|
|
581
|
-
if (!
|
|
582
|
-
|
|
583
|
-
|
|
679
|
+
var compiled;
|
|
680
|
+
var tables = () => compiled ??= { nonPublic: compile(NON_PUBLIC_RANGES), cloudflare: compile(CLOUDFLARE_RANGES), cloudfront: compile(CLOUDFRONT_RANGES) };
|
|
681
|
+
function addressKey(address) {
|
|
682
|
+
const ip = normalizeIp(address);
|
|
683
|
+
if (!ip) return "";
|
|
684
|
+
if (!ip.includes(":")) return ip;
|
|
685
|
+
const b = parseIp(ip);
|
|
686
|
+
const prefix = new Uint8Array(16);
|
|
687
|
+
prefix.set(b.subarray(0, 8));
|
|
688
|
+
return `${formatIp(prefix)}/64`;
|
|
584
689
|
}
|
|
585
690
|
function isPublicIp(address) {
|
|
586
691
|
const b = parseIp(address);
|
|
587
|
-
return !!b && !
|
|
692
|
+
return !!b && !tables().nonPublic.some((c) => inCidr(c, b));
|
|
588
693
|
}
|
|
589
|
-
function
|
|
590
|
-
|
|
591
|
-
const entries = xff.split(",").map((s) => s.trim()).filter(Boolean).slice(-MAX_FORWARDED);
|
|
592
|
-
return [...entries, req.peer];
|
|
694
|
+
function forwardedOf(req) {
|
|
695
|
+
return (req.header("x-forwarded-for") ?? "").split(",").map((t) => t.trim()).filter(Boolean).slice(-MAX_FORWARDED).map((t) => normalizeIp(t)).filter((x) => !!x);
|
|
593
696
|
}
|
|
594
697
|
var result = (address, via) => ({ address, internal: !isPublicIp(address), via });
|
|
595
|
-
function walk(req, trusted, via) {
|
|
596
|
-
const
|
|
597
|
-
|
|
698
|
+
function walk(req, trusted, via, cdns) {
|
|
699
|
+
const peer = normalizeIp(req.peer);
|
|
700
|
+
const chain = [...forwardedOf(req), ...peer ? [peer] : []];
|
|
701
|
+
let edge = "";
|
|
598
702
|
for (let i = chain.length - 1; i >= 0; i--) {
|
|
599
|
-
const ip =
|
|
600
|
-
if (!ip) continue;
|
|
601
|
-
last ||= ip;
|
|
703
|
+
const ip = chain[i];
|
|
602
704
|
const b = parseIp(ip);
|
|
603
|
-
|
|
604
|
-
|
|
705
|
+
const { nonPublic, cloudflare, cloudfront } = tables();
|
|
706
|
+
if (nonPublic.some((c) => inCidr(c, b)) || trusted.some((c) => inCidr(c, b))) continue;
|
|
707
|
+
if (cdns && cloudfront.some((c) => inCidr(c, b))) {
|
|
708
|
+
edge = ip;
|
|
709
|
+
continue;
|
|
710
|
+
}
|
|
711
|
+
if (cdns && cloudflare.some((c) => inCidr(c, b))) {
|
|
712
|
+
const client = normalizeIp(req.header("cf-connecting-ip"));
|
|
713
|
+
return client ? result(client, "cloudflare") : { address: ip, internal: false, via };
|
|
714
|
+
}
|
|
715
|
+
return { address: ip, internal: false, via: peer && i === chain.length - 1 ? "socket" : via };
|
|
605
716
|
}
|
|
606
|
-
return { address:
|
|
717
|
+
if (edge) return { address: edge, internal: false, via };
|
|
718
|
+
return { address: chain[chain.length - 1] ?? "", internal: true, via: "socket" };
|
|
719
|
+
}
|
|
720
|
+
function headerAddress(req, name) {
|
|
721
|
+
const first = req.header(name)?.split(",")[0]?.trim();
|
|
722
|
+
if (!first) return null;
|
|
723
|
+
if (PORT_SUFFIXED_HEADERS.includes(name) && !first.startsWith("[")) return normalizeIp(first.replace(/:\d{1,5}$/, ""));
|
|
724
|
+
return normalizeIp(first);
|
|
607
725
|
}
|
|
608
726
|
function resolveClientAddress(req, mode = "auto", platform = null) {
|
|
609
727
|
const peer = normalizeIp(req.peer) ?? "";
|
|
610
728
|
if (mode === "socket") return result(peer, "socket");
|
|
611
729
|
if (typeof mode === "object" && "header" in mode) {
|
|
612
|
-
const
|
|
613
|
-
const ip = normalizeIp(first);
|
|
730
|
+
const ip = headerAddress(req, mode.header.toLowerCase());
|
|
614
731
|
return ip ? result(ip, "header") : result(peer, "socket");
|
|
615
732
|
}
|
|
616
733
|
if (typeof mode === "object" && "hops" in mode) {
|
|
617
|
-
const
|
|
618
|
-
if (
|
|
619
|
-
|
|
620
|
-
return result(chain[at], at === chain.length - 1 ? "socket" : "hops");
|
|
734
|
+
const xff = forwardedOf(req);
|
|
735
|
+
if (xff.length < mode.hops) return walk(req, [], "hops", false);
|
|
736
|
+
return result(xff[xff.length - mode.hops], "hops");
|
|
621
737
|
}
|
|
622
|
-
if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies");
|
|
738
|
+
if (typeof mode === "object" && "proxies" in mode) return walk(req, compile(mode.proxies), "proxies", false);
|
|
623
739
|
const framework = normalizeIp(req.framework);
|
|
624
740
|
if (framework) return result(framework, "framework");
|
|
625
741
|
if (platform) {
|
|
626
|
-
const ip =
|
|
742
|
+
const ip = headerAddress(req, PLATFORM_HEADERS[platform]);
|
|
627
743
|
if (ip) return result(ip, `platform:${platform}`);
|
|
628
744
|
}
|
|
629
|
-
|
|
630
|
-
const ip = normalizeIp(req.header("cf-connecting-ip"));
|
|
631
|
-
if (ip) return result(ip, "cloudflare");
|
|
632
|
-
}
|
|
633
|
-
return walk(req, [], "forwarded");
|
|
745
|
+
return walk(req, [], "forwarded", true);
|
|
634
746
|
}
|
|
635
747
|
function clientIpModeProblem(value) {
|
|
636
748
|
if (value === "auto" || value === "socket") return null;
|
|
@@ -680,7 +792,7 @@ function canonicalPath(target) {
|
|
|
680
792
|
const cut = t.search(/[?#]/);
|
|
681
793
|
let raw = cut === -1 ? t : t.slice(0, cut);
|
|
682
794
|
if (!raw.startsWith("/")) raw = `/${raw}`;
|
|
683
|
-
return { raw, decoded: normalizeSegments(decodeOnce(raw)) };
|
|
795
|
+
return { raw, decoded: normalizeSegments(decodeOnce(raw).replace(/\\/g, "/")) };
|
|
684
796
|
}
|
|
685
797
|
function matchesEither(matcher, p) {
|
|
686
798
|
return matcher(p.raw) || matcher(p.decoded);
|
|
@@ -692,12 +804,83 @@ function isSourceMapPath(p) {
|
|
|
692
804
|
return /\.map$/i.test(p.raw) || /\.map$/i.test(p.decoded);
|
|
693
805
|
}
|
|
694
806
|
|
|
807
|
+
// ../shared/src/webhooks.ts
|
|
808
|
+
var WEBHOOK_TOLERANCE_SECONDS = 300;
|
|
809
|
+
var WebhookSignatureError = class extends Error {
|
|
810
|
+
constructor(code, message) {
|
|
811
|
+
super(message);
|
|
812
|
+
this.code = code;
|
|
813
|
+
this.name = "ReguardWebhookError";
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
var enc2 = new TextEncoder();
|
|
817
|
+
function hmacKey2(secret) {
|
|
818
|
+
return crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
|
|
819
|
+
}
|
|
820
|
+
function signedBytes(timestamp, payload) {
|
|
821
|
+
const head = enc2.encode(`${timestamp}.`);
|
|
822
|
+
const body = typeof payload === "string" ? enc2.encode(payload) : payload;
|
|
823
|
+
const out = new Uint8Array(new ArrayBuffer(head.length + body.length));
|
|
824
|
+
out.set(head, 0);
|
|
825
|
+
out.set(body, head.length);
|
|
826
|
+
return out;
|
|
827
|
+
}
|
|
828
|
+
function hex(bytes) {
|
|
829
|
+
return [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
830
|
+
}
|
|
831
|
+
function unhex(s) {
|
|
832
|
+
const out = new Uint8Array(new ArrayBuffer(s.length / 2));
|
|
833
|
+
for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
|
|
834
|
+
return out;
|
|
835
|
+
}
|
|
836
|
+
async function signWebhookPayload(secrets, payload, timestamp) {
|
|
837
|
+
const t = Math.floor(timestamp);
|
|
838
|
+
const data = signedBytes(t, payload);
|
|
839
|
+
const sigs = [];
|
|
840
|
+
for (const secret of typeof secrets === "string" ? [secrets] : secrets) {
|
|
841
|
+
sigs.push(`v1=${hex(await crypto.subtle.sign("HMAC", await hmacKey2(secret), data))}`);
|
|
842
|
+
}
|
|
843
|
+
return [`t=${t}`, ...sigs].join(",");
|
|
844
|
+
}
|
|
845
|
+
function parseWebhookSignature(header) {
|
|
846
|
+
let t;
|
|
847
|
+
const v1 = [];
|
|
848
|
+
for (const part of header.split(",")) {
|
|
849
|
+
const i = part.indexOf("=");
|
|
850
|
+
if (i < 1) continue;
|
|
851
|
+
const k = part.slice(0, i).trim();
|
|
852
|
+
const v = part.slice(i + 1).trim();
|
|
853
|
+
if (k === "t" && /^\d{1,12}$/.test(v)) t = Number(v);
|
|
854
|
+
else if (k === "v1" && /^[0-9a-f]{64}$/.test(v)) v1.push(v);
|
|
855
|
+
}
|
|
856
|
+
return t === void 0 || !v1.length ? null : { t, v1 };
|
|
857
|
+
}
|
|
858
|
+
async function verifyWebhookSignature(payload, header, secret, options = {}) {
|
|
859
|
+
if (!secret) throw new WebhookSignatureError("missing_secret", "No webhook signing secret: pass it, or set REGUARD_WEBHOOK_SECRET.");
|
|
860
|
+
if (!header) throw new WebhookSignatureError("missing_signature", "No Reguard-Signature header on this request.");
|
|
861
|
+
const parsed = parseWebhookSignature(header);
|
|
862
|
+
if (!parsed) throw new WebhookSignatureError("malformed_signature", "The Reguard-Signature header isn't in the form t=\u2026,v1=\u2026.");
|
|
863
|
+
const tolerance = options.tolerance ?? WEBHOOK_TOLERANCE_SECONDS;
|
|
864
|
+
const now = options.now ?? Math.floor(Date.now() / 1e3);
|
|
865
|
+
if (tolerance > 0 && Math.abs(now - parsed.t) > tolerance) {
|
|
866
|
+
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).`);
|
|
867
|
+
}
|
|
868
|
+
const key = await hmacKey2(secret);
|
|
869
|
+
const data = signedBytes(parsed.t, payload);
|
|
870
|
+
for (const sig of parsed.v1) {
|
|
871
|
+
if (await crypto.subtle.verify("HMAC", key, unhex(sig), data)) return;
|
|
872
|
+
}
|
|
873
|
+
throw new WebhookSignatureError("bad_signature", "The signature doesn't match: check the signing secret, and pass the raw request body.");
|
|
874
|
+
}
|
|
875
|
+
|
|
695
876
|
// src/core.ts
|
|
696
877
|
var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
|
|
878
|
+
var visitorIdOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
|
|
697
879
|
function withFlagged(p, source = "browser") {
|
|
698
880
|
return {
|
|
699
881
|
...p,
|
|
700
882
|
source,
|
|
883
|
+
visitor: visitorIdOf(p.vid) ?? null,
|
|
701
884
|
flagged({ labels, minStage = "candidate" } = {}) {
|
|
702
885
|
const want = typeof labels === "string" ? [labels] : labels?.length ? labels : void 0;
|
|
703
886
|
const rank = STAGE_RANK[minStage] ?? 0;
|
|
@@ -710,8 +893,9 @@ function mergeVerdicts(browser, pushed) {
|
|
|
710
893
|
if (!browser) return withFlagged(pushed, "server");
|
|
711
894
|
const rules = new Set(browser.claims.map((c) => `${c.rule}|${c.label}|${c.stage}`));
|
|
712
895
|
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
|
-
|
|
896
|
+
const { source: _s, flagged: _f, visitor: _v, ...payload } = browser;
|
|
897
|
+
const vid = visitorIdOf(payload.vid) ?? visitorIdOf(pushed.vid);
|
|
898
|
+
return withFlagged({ ...payload, ...vid ? { vid } : {}, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
|
|
715
899
|
}
|
|
716
900
|
async function readVerdictFrom(secret, site, cookieHeader) {
|
|
717
901
|
const token = cookieValue(cookieHeader, VERDICT_COOKIE);
|
|
@@ -750,8 +934,8 @@ function freshSeconds(cfg) {
|
|
|
750
934
|
function verdictAgeMs(v, now = Date.now()) {
|
|
751
935
|
return now - (v.exp - VERDICT_TTL_MS);
|
|
752
936
|
}
|
|
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");
|
|
937
|
+
function pushedVerdict(sid, site, claims, now = Date.now(), vid) {
|
|
938
|
+
return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4, ...vid ? { vid } : {} }, "server");
|
|
755
939
|
}
|
|
756
940
|
var ANSWER_CODES = { flagged: "reguard.blocked", flagged_server: "reguard.blocked", require: "reguard.require", pace: "reguard.pace" };
|
|
757
941
|
var RETRY_AFTER = { flagged: 120, flagged_server: 120, require: 5, pace: 2 };
|
|
@@ -811,16 +995,19 @@ export {
|
|
|
811
995
|
parseSiteKey,
|
|
812
996
|
BENIGN_TOOL_FAMILIES,
|
|
813
997
|
toolOf,
|
|
998
|
+
presentsAsBrowser,
|
|
814
999
|
watchworthy,
|
|
815
1000
|
requestKind,
|
|
816
1001
|
pathTraits,
|
|
817
1002
|
resolveCollect,
|
|
818
1003
|
skipMatcher,
|
|
1004
|
+
protectionMatcher,
|
|
819
1005
|
collectAttributes,
|
|
820
1006
|
collectReport,
|
|
821
1007
|
Allowance,
|
|
822
1008
|
detectPlatform,
|
|
823
1009
|
normalizeIp,
|
|
1010
|
+
addressKey,
|
|
824
1011
|
isPublicIp,
|
|
825
1012
|
resolveClientAddress,
|
|
826
1013
|
clientIpModeProblem,
|
|
@@ -828,6 +1015,10 @@ export {
|
|
|
828
1015
|
matchesEither,
|
|
829
1016
|
matchesBoth,
|
|
830
1017
|
isSourceMapPath,
|
|
1018
|
+
WebhookSignatureError,
|
|
1019
|
+
signWebhookPayload,
|
|
1020
|
+
verifyWebhookSignature,
|
|
1021
|
+
visitorIdOf,
|
|
831
1022
|
mergeVerdicts,
|
|
832
1023
|
readVerdictFrom,
|
|
833
1024
|
looksCurrent,
|
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
2
|
DEFAULT_PACE,
|
|
3
|
+
WebhookSignatureError,
|
|
3
4
|
clientIpModeProblem,
|
|
4
|
-
|
|
5
|
-
|
|
5
|
+
collectorBase,
|
|
6
|
+
envValue,
|
|
7
|
+
parseSiteKey,
|
|
8
|
+
resolveCollect,
|
|
9
|
+
verifyWebhookSignature,
|
|
10
|
+
visitorIdOf
|
|
11
|
+
} from "./chunk-2N762ZXU.js";
|
|
6
12
|
|
|
7
13
|
// src/config.ts
|
|
8
14
|
var ReguardConfigError = class extends TypeError {
|
|
@@ -24,14 +30,16 @@ var fail = (option, code, detail) => {
|
|
|
24
30
|
var show = (v) => typeof v === "function" ? "a function" : JSON.stringify(v) ?? String(v);
|
|
25
31
|
var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
26
32
|
var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
|
27
|
-
function checkKeys(obj, allowed, prefix, moved = {}) {
|
|
33
|
+
function checkKeys(obj, allowed, prefix, moved = {}, nested) {
|
|
34
|
+
const like = (k) => (a) => a === camel(k).replace(/Seconds$|Secs$/, "Ms") || a === camel(k) || a.toLowerCase() === k.toLowerCase();
|
|
28
35
|
for (const k of Object.keys(obj)) {
|
|
29
36
|
if (obj[k] === void 0 || allowed.includes(k)) continue;
|
|
30
37
|
const path = prefix ? `${prefix}.${k}` : k;
|
|
31
38
|
if (moved[k]) fail(path, "removed_option", `was removed: ${moved[k]}`);
|
|
32
|
-
const
|
|
33
|
-
const
|
|
34
|
-
|
|
39
|
+
const here = allowed.find(like(k));
|
|
40
|
+
const below = here ? void 0 : nested?.keys.find(like(k));
|
|
41
|
+
const hint = here ? `${prefix ? `${prefix}.` : ""}${here}` : below ? `${nested.under}.${below}` : void 0;
|
|
42
|
+
fail(path, "unknown_option", `isn't an option${hint ? ` (did you mean ${hint}?)` : ""}`);
|
|
35
43
|
}
|
|
36
44
|
}
|
|
37
45
|
function checkBoolean(v, option) {
|
|
@@ -226,7 +234,7 @@ function checkOptions(options) {
|
|
|
226
234
|
if (options === void 0 || options === null) options = {};
|
|
227
235
|
if (!isObject(options)) fail("options", "invalid_type", `must be an object (got ${show(options)})`);
|
|
228
236
|
const o = options;
|
|
229
|
-
checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS);
|
|
237
|
+
checkKeys(o, NODE_OPTION_KEYS, "", MOVED_OPTIONS, { under: "block", keys: BLOCK_KEYS });
|
|
230
238
|
if (typeof o.ignore === "function") fail("ignore", "invalid_type", "is now a list of paths; use ignoreIf for a function");
|
|
231
239
|
return {
|
|
232
240
|
key: checkString(o.key, "key"),
|
|
@@ -332,6 +340,68 @@ var Health = class {
|
|
|
332
340
|
}
|
|
333
341
|
};
|
|
334
342
|
|
|
343
|
+
// src/api.ts
|
|
344
|
+
var ReguardApiError = class extends Error {
|
|
345
|
+
constructor(status, message) {
|
|
346
|
+
super(message);
|
|
347
|
+
this.status = status;
|
|
348
|
+
this.name = "ReguardApiError";
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
function reguardApi(options = {}) {
|
|
352
|
+
const key = (options.key?.trim() || envValue("REGUARD_KEY"))?.trim();
|
|
353
|
+
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)");
|
|
354
|
+
const base = collectorBase(options.collector || envValue("REGUARD_COLLECTOR"));
|
|
355
|
+
const doFetch = options.fetch ?? fetch;
|
|
356
|
+
const timeoutMs = options.timeoutMs ?? 1e4;
|
|
357
|
+
async function get(path) {
|
|
358
|
+
if (!key) throw new ReguardApiError(0, "No site key: pass { key } or set REGUARD_KEY.");
|
|
359
|
+
if (!parseSiteKey(key)?.site) throw new ReguardApiError(0, "REGUARD_KEY isn't a site key (rgk.<site>.v<n>.\u2026).");
|
|
360
|
+
let res;
|
|
361
|
+
try {
|
|
362
|
+
res = await doFetch(`${base}${path}`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
|
|
363
|
+
} catch (e) {
|
|
364
|
+
throw new ReguardApiError(0, `Reguard's API can't be reached: ${e.message}`);
|
|
365
|
+
}
|
|
366
|
+
const parsed = await res.json().catch(() => null);
|
|
367
|
+
const body = parsed && typeof parsed === "object" ? parsed : {};
|
|
368
|
+
if (!res.ok) throw new ReguardApiError(res.status, typeof body.error === "string" && body.error ? body.error : `Reguard's API answered ${res.status}`);
|
|
369
|
+
return body;
|
|
370
|
+
}
|
|
371
|
+
return {
|
|
372
|
+
async visitor(id) {
|
|
373
|
+
if (!visitorIdOf(id)) throw new ReguardApiError(400, "Not a visitor id: they look like vis_ followed by 22 characters.");
|
|
374
|
+
return (await get(`/v1/visitors/${id}`)).visitor;
|
|
375
|
+
},
|
|
376
|
+
events({ after, limit, types } = {}) {
|
|
377
|
+
const q = new URLSearchParams();
|
|
378
|
+
if (after) q.set("after", after);
|
|
379
|
+
if (typeof limit === "number" && Number.isInteger(limit) && limit > 0) q.set("limit", String(limit));
|
|
380
|
+
if (types?.length) q.set("type", types.join(","));
|
|
381
|
+
const qs = q.toString();
|
|
382
|
+
return get(`/v1/events${qs ? `?${qs}` : ""}`);
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
async function verifyWebhook(payload, signature, secret, options = {}) {
|
|
387
|
+
if (typeof payload !== "string" && !(payload instanceof Uint8Array) && !(payload instanceof ArrayBuffer)) {
|
|
388
|
+
throw new TypeError(
|
|
389
|
+
'[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.'
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
const raw = payload instanceof ArrayBuffer ? new Uint8Array(payload) : payload;
|
|
393
|
+
const header = Array.isArray(signature) ? signature[0] : signature;
|
|
394
|
+
await verifyWebhookSignature(raw, header, secret || envValue("REGUARD_WEBHOOK_SECRET"), options);
|
|
395
|
+
let event;
|
|
396
|
+
try {
|
|
397
|
+
event = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw));
|
|
398
|
+
} catch {
|
|
399
|
+
throw new WebhookSignatureError("bad_payload", "The body isn't JSON (a Slack or Discord URL gets messages, not events).");
|
|
400
|
+
}
|
|
401
|
+
if (!event || typeof event.id !== "string" || typeof event.type !== "string") throw new WebhookSignatureError("bad_payload", "The body isn't a Reguard event.");
|
|
402
|
+
return event;
|
|
403
|
+
}
|
|
404
|
+
|
|
335
405
|
export {
|
|
336
406
|
ReguardConfigError,
|
|
337
407
|
BLOCK_REASONS,
|
|
@@ -346,5 +416,8 @@ export {
|
|
|
346
416
|
checkBlock,
|
|
347
417
|
checkOptions,
|
|
348
418
|
makeLog,
|
|
349
|
-
Health
|
|
419
|
+
Health,
|
|
420
|
+
ReguardApiError,
|
|
421
|
+
reguardApi,
|
|
422
|
+
verifyWebhook
|
|
350
423
|
};
|