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.
Files changed (44) hide show
  1. package/README.md +25 -3
  2. package/dist/chunks/{chunk-PA46KSOR.js → chunk-2N762ZXU.js} +235 -44
  3. package/dist/chunks/{chunk-3AYS7WSY.js → chunk-4RD66ACT.js} +81 -8
  4. package/dist/chunks/{chunk-U54IP6G4.js → chunk-GOT54CF4.js} +61 -40
  5. package/dist/chunks/{chunk-KNKCUJL3.js → chunk-RTCPK4MF.js} +102 -41
  6. package/dist/cjs/fastify.cjs +305 -93
  7. package/dist/cjs/fetch.cjs +347 -87
  8. package/dist/cjs/index.cjs +386 -86
  9. package/dist/cjs/next.cjs +366 -103
  10. package/dist/cjs/testing.cjs +28 -100
  11. package/dist/fastify.js +4 -12
  12. package/dist/fetch.js +14 -5
  13. package/dist/index.js +13 -5
  14. package/dist/next.js +33 -23
  15. package/dist/testing.js +9 -3
  16. package/dist/types/node/src/api.d.ts +139 -0
  17. package/dist/types/node/src/core.d.ts +8 -1
  18. package/dist/types/node/src/fastify.d.ts +15 -7
  19. package/dist/types/node/src/fetch.d.ts +12 -2
  20. package/dist/types/node/src/index.d.ts +6 -0
  21. package/dist/types/node/src/next.d.ts +39 -17
  22. package/dist/types/node/src/testing.d.ts +11 -0
  23. package/dist/types/shared/src/address.d.ts +25 -6
  24. package/dist/types/shared/src/collect.d.ts +7 -1
  25. package/dist/types/shared/src/index.d.ts +14 -0
  26. package/dist/types/shared/src/paths.d.ts +6 -2
  27. package/dist/types/shared/src/tools.d.ts +10 -0
  28. package/dist/types/shared/src/verdict.d.ts +6 -0
  29. package/dist/types/shared/src/webhooks.d.ts +32 -0
  30. package/dist/types-cjs/node/src/api.d.cts +139 -0
  31. package/dist/types-cjs/node/src/core.d.cts +8 -1
  32. package/dist/types-cjs/node/src/fastify.d.cts +15 -7
  33. package/dist/types-cjs/node/src/fetch.d.cts +12 -2
  34. package/dist/types-cjs/node/src/index.d.cts +6 -0
  35. package/dist/types-cjs/node/src/next.d.cts +39 -17
  36. package/dist/types-cjs/node/src/testing.d.cts +11 -0
  37. package/dist/types-cjs/shared/src/address.d.cts +25 -6
  38. package/dist/types-cjs/shared/src/collect.d.cts +7 -1
  39. package/dist/types-cjs/shared/src/index.d.cts +14 -0
  40. package/dist/types-cjs/shared/src/paths.d.cts +6 -2
  41. package/dist/types-cjs/shared/src/tools.d.cts +10 -0
  42. package/dist/types-cjs/shared/src/verdict.d.cts +6 -0
  43. package/dist/types-cjs/shared/src/webhooks.d.cts +32 -0
  44. package/package.json +3 -2
@@ -2,20 +2,20 @@
2
2
  * reguard/next: Reguard for Next.js. Runtime-neutral (no node: imports), so it also runs in
3
3
  * middleware and on the edge runtime. Built on reguard/fetch.
4
4
  *
5
- * // next.config.js
6
- * import { withReguard } from "reguard/next";
7
- * export default withReguard({ ...yourConfig });
5
+ * // middleware.ts (proxy.ts on Next 16): serves /_s/* (the script and its reports) from Reguard,
6
+ * // first-party, and answers flagged visitors with { block: true }
7
+ * export const middleware = reguardMiddleware();
8
8
  *
9
9
  * // app/layout.tsx (App Router), or pages/_document.tsx (Pages Router)
10
10
  * import Script from "next/script";
11
11
  * import { reguardScriptProps } from "reguard/next";
12
12
  * <Script {...reguardScriptProps()} />
13
13
  *
14
+ * // next.config.js: the site id for pages rendered where REGUARD_KEY isn't (build, browser)
15
+ * export default withReguard({ ...yourConfig });
16
+ *
14
17
  * // anywhere on the server: route handler, server action, middleware
15
18
  * const verdict = await reguardVerdict(request);
16
- *
17
- * // middleware.ts (proxy.ts on Next 16): answer flagged visitors, like reguard({ block: true })
18
- * export const middleware = reguardMiddleware({ block: true });
19
19
  */
20
20
  import { type CollectOptions } from "../../shared/src/index.js";
21
21
  import { type ClientIpOption, type LoggerLike } from "./config.js";
@@ -24,16 +24,21 @@ import { type FetchBlockOptions } from "./fetch.js";
24
24
  export type { Decision, Verdict, VerdictSource } from "./core.js";
25
25
  export type { FetchBlockOptions as BlockOptions } from "./fetch.js";
26
26
  export { type BlockReason, ReguardConfigError } from "./config.js";
27
+ export { type EventsPage, type ReguardApiOptions, type ReguardEvent, type ReguardEventType, type VisitorStatus, ReguardApiError, ReguardWebhookError, reguardApi, verifyWebhook, } from "./api.js";
27
28
  export type { AddressesMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.js";
28
29
  /**
29
- * Adds the rewrite that serves /_s/* from Reguard, first-party, ahead of your own routes, and makes
30
- * the site id (public: it is in the script tag anyway) available to browser code as
31
- * NEXT_PUBLIC_REGUARD_SITE, so `reguardScriptProps()` works in components that also render in the
32
- * browser. Keeps your rewrites in whichever shape they come and takes a config object or function.
30
+ * Makes the site id (public: it is in the script tag anyway) available as NEXT_PUBLIC_REGUARD_SITE,
31
+ * so `reguardScriptProps()` works in pages rendered where REGUARD_KEY isn't: prerendered at build
32
+ * time, or in components that also render in the browser. The id comes from `site`, else from
33
+ * REGUARD_KEY when the build has it. Takes a config object or function.
34
+ *
35
+ * Earlier releases also routed /_s/* here with a rewrite; reguardMiddleware() serves it now, so the
36
+ * visitor's sign-in cookies and headers stay on your server and the collector address is read at
37
+ * run time.
33
38
  */
34
39
  export declare function withReguard<T extends object>(config: T, options?: {
35
- collector?: string;
36
40
  key?: string;
41
+ site?: string;
37
42
  }): T;
38
43
  /** The visitor's verified verdict from a Request or NextRequest (null when there is none). */
39
44
  export declare function reguardVerdict(request: {
@@ -69,17 +74,34 @@ export interface ReguardMiddlewareOptions {
69
74
  block?: boolean | FetchBlockOptions;
70
75
  key?: string;
71
76
  previousKey?: string;
77
+ /** Where /_s/* goes (default https://api.reguard.site, or REGUARD_COLLECTOR), read at run time. */
78
+ collector?: string;
79
+ /** What Reguard receives from your server: `requests: false` sends nothing but the script's traffic. */
80
+ collect?: CollectOptions;
81
+ /** Paths Reguard leaves alone entirely (health checks, webhooks). */
82
+ ignore?: string[];
72
83
  sourceMaps?: "deny" | "allow";
73
84
  clientIp?: ClientIpOption<Request>;
85
+ timeoutMs?: number;
74
86
  debug?: boolean;
75
87
  logger?: LoggerLike | false;
76
88
  }
77
89
  /**
78
- * Next.js middleware (edge or Node runtime) that answers blocked visitors itself, like
79
- * `reguard({ block: true })` in Express: Reguard's default answer (or `block.respond`'s), with
80
- * `block.dryRun`, `block.allow` and `block.onBlock` as there. With `block` it also paces pages for
81
- * clients that don't present as a browser (each instance counts on its own) and denies source maps
82
- * (keep `*.map` in your matcher for that). Everyone else gets `undefined`, so Next carries on.
90
+ * Next.js middleware (edge or Node runtime). It serves /_s/* (the script and its reports) from
91
+ * Reguard, first-party: the visitor's cookies other than Reguard's own, Authorization, the full
92
+ * referrer and address or location headers stay on your server, and the visitor's address goes as a
93
+ * keyed hash. Keep /_s/:path* in your matcher.
94
+ *
95
+ * With `block` it answers blocked visitors itself, like `reguard({ block: true })` in Express:
96
+ * Reguard's default answer (or `block.respond`'s), with `block.dryRun`, `block.allow` and
97
+ * `block.onBlock` as there. It also paces pages for clients that don't present as a browser (each
98
+ * instance counts on its own) and denies source maps (keep `*.map` in your matcher for that).
83
99
  * `block.require` needs reguard() in a Node server and is refused here.
100
+ *
101
+ * Middleware never sees your response, so it reports what it can without one: what Reguard decided
102
+ * (blocks, and what a dry run would have blocked, which the dashboard counts) and requests from
103
+ * clients that don't present as a browser. Everyone else gets `undefined`, so Next carries on.
84
104
  */
85
- export declare function reguardMiddleware(options?: ReguardMiddlewareOptions): (request: Request) => Promise<Response | undefined>;
105
+ export declare function reguardMiddleware(options?: ReguardMiddlewareOptions): (request: Request, event?: {
106
+ waitUntil?(p: Promise<unknown>): void;
107
+ }) => Promise<Response | undefined>;
@@ -22,4 +22,15 @@ export declare function verdictCookie(key: string, options?: {
22
22
  claims?: VerdictClaim[];
23
23
  sid?: string;
24
24
  issuedAt?: number;
25
+ visitor?: string;
26
+ }): Promise<string>;
27
+ /**
28
+ * A Reguard-Signature header for `payload` (the exact body you'll send to your webhook handler),
29
+ * signed with `secret` at `timestamp` (epoch seconds, default now): test your handler without Reguard.
30
+ *
31
+ * const body = JSON.stringify({ id: "evt_1", type: "visitor.caught", created: 0, site: "shop", data: {} });
32
+ * await request(app).post("/hooks/reguard").set("reguard-signature", await signWebhook("rgwh_test", body)).send(body);
33
+ */
34
+ export declare function signWebhook(secret: string, payload: string | Uint8Array, options?: {
35
+ timestamp?: number;
25
36
  }): Promise<string>;
@@ -10,12 +10,15 @@
10
10
  * `trust proxy`, Fastify with `trustProxy`);
11
11
  * 2. the host's own client header when the host is known from the environment (Fly, Vercel,
12
12
  * Railway, Netlify, App Engine, Cloudflare Workers);
13
- * 3. `cf-connecting-ip` when the connection comes from Cloudflare's published ranges;
14
- * 4. the X-Forwarded-For chain read right to left from the connecting peer, skipping private,
15
- * loopback and shared-network addresses (load balancers and proxies inside your network): the
16
- * first public address is the visitor.
17
- * When no public address appears at all, the request came from your own network (server-side
18
- * rendering, health checks, internal services): it is marked internal and never paced.
13
+ * 3. the chain [...X-Forwarded-For, connecting peer] read right to left. Each hop is skipped when it
14
+ * is one of yours (private, loopback, shared-network: load balancers, proxies, the cluster) or
15
+ * CloudFront's (its origin-facing ranges; CloudFront appends the address it saw, so the next entry
16
+ * left is that). A Cloudflare address ends the walk at `cf-connecting-ip`, which Cloudflare sets
17
+ * itself. The first other address is the visitor.
18
+ * Without a connecting peer (Next.js middleware, fetch runtimes) the walk starts at the right end of
19
+ * X-Forwarded-For, which the nearest proxy wrote. When no public address appears at all, the request
20
+ * came from your own network (server-side rendering, health checks, internal services): it is marked
21
+ * internal and never paced.
19
22
  */
20
23
  export type ClientIpMode = "auto" | "socket" | {
21
24
  header: string;
@@ -47,6 +50,16 @@ export interface ResolvedAddress {
47
50
  }
48
51
  /** Cloudflare's published ranges (cloudflare.com/ips-v4, /ips-v6; checked 2026-12-03). */
49
52
  export declare const CLOUDFLARE_RANGES: readonly string[];
53
+ /**
54
+ * CloudFront's origin-facing ranges (AWS's published ip-ranges.json, service CLOUDFRONT_ORIGIN_FACING;
55
+ * checked 2026-12-04): the addresses CloudFront connects to origins from. Only CloudFront uses them.
56
+ */
57
+ export declare const CLOUDFRONT_RANGES: readonly string[];
58
+ /**
59
+ * Headers whose value is always "address:port", so the last ":port" is cut even from an IPv6 address
60
+ * written without brackets (CloudFront-Viewer-Address: "2001:db8::1:443" is 2001:db8::1, port 443).
61
+ */
62
+ export declare const PORT_SUFFIXED_HEADERS: readonly string[];
50
63
  /** Addresses that are never a visitor's: unspecified, private, shared (carrier-grade NAT), loopback, link-local. */
51
64
  export declare const NON_PUBLIC_RANGES: readonly string[];
52
65
  /** At most this many X-Forwarded-For entries are read (from the right). */
@@ -67,6 +80,12 @@ interface Cidr {
67
80
  }
68
81
  /** "a.b.c.d/n", "v6/n" or a bare address; null when malformed. */
69
82
  export declare function parseCidr(text: string): Cidr | null;
83
+ /**
84
+ * What pace, claims and visitor hashes key an address by: an IPv6 address by its /64 (one host or
85
+ * home network's whole block, which its owner can rotate through freely), an IPv4 one as it is.
86
+ * "" for anything that isn't an address.
87
+ */
88
+ export declare function addressKey(address: string | undefined): string;
70
89
  /** Whether an address (any text form) belongs to one of the ranges. */
71
90
  export declare function ipInRanges(address: string, ranges: readonly string[] | readonly Cidr[]): boolean;
72
91
  /** A visitor's address could be this one: not private, shared, loopback, link-local or unspecified. */
@@ -43,8 +43,14 @@ export declare function resolveCollect(input: unknown, warn?: (message: string)
43
43
  /**
44
44
  * A matcher for skip patterns: `*` matches any characters (slashes included), and a pattern ending in
45
45
  * "/*" also matches the path without it ("/account/*" covers "/account"). Query and fragment are ignored.
46
+ * Exemptions (block.allow) match exactly; protections use protectionMatcher.
46
47
  */
47
- export declare function skipMatcher(patterns: readonly string[]): (path: string) => boolean;
48
+ export declare function skipMatcher(patterns: readonly string[], ignoreCase?: boolean): (path: string) => boolean;
49
+ /**
50
+ * A matcher for protections (require, collect.skip, ignore): as skipMatcher, ignoring case, since
51
+ * routers that match paths case-insensitively (Express's default) serve /API/x as /api/x.
52
+ */
53
+ export declare function protectionMatcher(patterns: readonly string[]): (path: string) => boolean;
48
54
  /** The script tag's data-* attributes for the settings that differ from the defaults. */
49
55
  export declare function collectAttributes(c: CollectSettings): Record<string, string>;
50
56
  export declare function collectReport(c: CollectSettings): CollectReport;
@@ -18,6 +18,11 @@ export interface InitRequest {
18
18
  site: string;
19
19
  /** This browser's previous session id (the `_s` cookie), for linking reloads when the cookie can't travel (cross-origin script). */
20
20
  prev?: string;
21
+ /**
22
+ * The session this tab's previous page load started (sessionStorage `_s_tab`, script 0.9.3+): page
23
+ * loads in one tab stay one investigation when the `_s` cookie is cleared or blocked between them.
24
+ */
25
+ tab?: string;
21
26
  /** SDK version (packages/sdk/package.json). */
22
27
  sdk?: string;
23
28
  /** Verification-run id from the `lab_run` query parameter; the hosted collector ignores it. */
@@ -28,6 +33,14 @@ export interface InitRequest {
28
33
  */
29
34
  path?: string;
30
35
  deviceId: string;
36
+ /** Whether `deviceId` persists across visits (the site turned on `persistentId`; SDK 0.9+). */
37
+ persistent?: boolean;
38
+ /**
39
+ * A hash of this device's traits (screen, time zone, languages, cores, memory; SDK 0.9+), never the
40
+ * traits themselves. The collector keeps it only for visitors it catches, to recognize their next
41
+ * session without cookies.
42
+ */
43
+ dk?: string;
31
44
  /** The site's data choices (SDK 0.6+), so the collector honours them and reviewers see them. */
32
45
  collect?: CollectReport;
33
46
  /** Seconds between verdict refreshes the site asks for (data-fresh, block.require): never sampled out (SDK 0.8+). */
@@ -101,5 +114,6 @@ export * from "./collect.js";
101
114
  export * from "./allowance.js";
102
115
  export * from "./address.js";
103
116
  export * from "./paths.js";
117
+ export * from "./webhooks.js";
104
118
  import type { VerdictClaim } from "./verdict.js";
105
119
  import type { CollectReport } from "./collect.js";
@@ -7,7 +7,8 @@
7
7
  * one. A rule checked against only one form can be walked around with the other (`/%61pi/items`
8
8
  * reaches `/api/items`; `/app.js%2Emap` is served as `/app.js.map`). So every rule sees both:
9
9
  * - `raw`: the path as sent, without query or fragment (absolute-form targets cut to their path);
10
- * - `decoded`: percent-decoded once, `//` collapsed and `.`/`..` segments resolved.
10
+ * - `decoded`: percent-decoded once, `\` read as `/` (as URL parsers read it), `//` collapsed and
11
+ * `.`/`..` segments resolved.
11
12
  * Protections apply when either form matches; exemptions only when both do. Summaries keep the raw
12
13
  * path.
13
14
  */
@@ -24,7 +25,10 @@ export declare function decodeOnce(s: string): string;
24
25
  export declare function normalizeSegments(path: string): string;
25
26
  /** Both forms of a request target (`req.url`, a RequestURI, a WSGI path): see the module comment. */
26
27
  export declare function canonicalPath(target: string | undefined): CanonicalPath;
27
- /** A protection (require, source maps, skip, ignore) applies when either form matches. */
28
+ /**
29
+ * A protection (require, source maps, skip, ignore) applies when either form matches; build its
30
+ * matcher with protectionMatcher, which ignores case (routers like Express's match /API as /api).
31
+ */
28
32
  export declare function matchesEither(matcher: (path: string) => boolean, p: CanonicalPath): boolean;
29
33
  /** An exemption (block.allow) applies only when both forms match. */
30
34
  export declare function matchesBoth(matcher: (path: string) => boolean, p: CanonicalPath): boolean;
@@ -52,6 +52,16 @@ export interface BrowserHeaders {
52
52
  * devices stay coherent: only fetch metadata depends on the version, and only for current ones.
53
53
  */
54
54
  export declare function browserIncoherence(h: BrowserHeaders): string[];
55
+ /**
56
+ * Whether a request presents as a person's browser: a browser's user agent (not a tool's), the
57
+ * fetch metadata every current browser sends to a secure origin (Sec-Fetch-Dest), and nothing
58
+ * incoherent (Accept-Language present, client hints matching the user agent). A script that adds
59
+ * one browser header doesn't pass. Such requests get to run the page and earn their own verdict:
60
+ * pace and claims keyed by an address never apply to them.
61
+ */
62
+ export declare function presentsAsBrowser(h: BrowserHeaders & {
63
+ secFetchDest?: string;
64
+ }): boolean;
55
65
  /**
56
66
  * Paths scanners and agents probe and normal browsing never requests. Matched on the path only;
57
67
  * the forced-browsing evidence needs several distinct families in one investigation.
@@ -20,6 +20,12 @@ export interface VerdictPayload {
20
20
  claims: VerdictClaim[];
21
21
  /** Expiry, epoch ms. */
22
22
  exp: number;
23
+ /**
24
+ * The visitor (collector 0.9+): Reguard's id for everything one browser does, stable across its page
25
+ * loads. Signed with the rest, so it can't be forged; use it to look the visitor up (GET
26
+ * /v1/visitors/:id) or to match webhook events.
27
+ */
28
+ vid?: string;
23
29
  }
24
30
  export declare const VERDICT_COOKIE = "_sv";
25
31
  export declare const SESSION_COOKIE = "_s";
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Webhook signatures (collector 0.9). Every delivery carries
3
+ *
4
+ * Reguard-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>
5
+ *
6
+ * with one v1 per signing secret in use (two for a day after the secret is rotated). WebCrypto only,
7
+ * so the same code signs in the collector and verifies in Node, Workers, Deno and Bun.
8
+ */
9
+ export declare const WEBHOOK_SIGNATURE_HEADER = "reguard-signature";
10
+ /** How far a delivery's timestamp may be from now, in seconds (replayed deliveries are refused). */
11
+ export declare const WEBHOOK_TOLERANCE_SECONDS = 300;
12
+ export type WebhookErrorCode = "missing_secret" | "missing_signature" | "malformed_signature" | "expired" | "bad_signature" | "bad_payload";
13
+ export declare class WebhookSignatureError extends Error {
14
+ readonly code: WebhookErrorCode;
15
+ constructor(code: WebhookErrorCode, message: string);
16
+ }
17
+ /** The header value for `payload` (the exact bytes sent), signed with each secret given. */
18
+ export declare function signWebhookPayload(secrets: string | readonly string[], payload: string | Uint8Array, timestamp: number): Promise<string>;
19
+ /** `t` and every v1 signature of a header; null when it isn't one. */
20
+ export declare function parseWebhookSignature(header: string): {
21
+ t: number;
22
+ v1: string[];
23
+ } | null;
24
+ /**
25
+ * Throws a WebhookSignatureError unless `header` signs `payload` with `secret` within `tolerance`
26
+ * seconds of `now` (epoch seconds). Pass the raw body exactly as received: parsed and re-serialized
27
+ * JSON no longer matches.
28
+ */
29
+ export declare function verifyWebhookSignature(payload: string | Uint8Array, header: string | null | undefined, secret: string | null | undefined, options?: {
30
+ tolerance?: number;
31
+ now?: number;
32
+ }): Promise<void>;
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The visitors API and webhooks (reguard 0.9). Runtime-neutral (fetch and WebCrypto): Node 20+,
3
+ * Workers, Deno and Bun.
4
+ *
5
+ * import { reguardApi, verifyWebhook } from "reguard";
6
+ *
7
+ * const api = reguardApi(); // REGUARD_KEY from the environment
8
+ * const v = await api.visitor(req.reguard.visitor); // the id from the visitor's signed verdict
9
+ * if (v.caught) …
10
+ *
11
+ * for (let after = null; ; ) { // poll instead of receiving webhooks
12
+ * const page = await api.events({ after });
13
+ * for (const e of page.events) handle(e);
14
+ * after = page.next;
15
+ * if (!page.hasMore) break;
16
+ * }
17
+ *
18
+ * const event = await verifyWebhook(rawBody, req.headers["reguard-signature"]); // REGUARD_WEBHOOK_SECRET
19
+ */
20
+ import { type Label, type Stage } from "../../shared/src/index.cjs";
21
+ export { WebhookSignatureError as ReguardWebhookError } from "../../shared/src/index.cjs";
22
+ export type { WebhookErrorCode as ReguardWebhookErrorCode } from "../../shared/src/index.cjs";
23
+ /** What matched when a caught visitor came back without its cookies. */
24
+ export type ReturnReason = "network_device" | "device_id";
25
+ export interface VisitorCatch {
26
+ rule: string;
27
+ label: Label;
28
+ stage: Stage;
29
+ at: string;
30
+ page: string | null;
31
+ evidence: Array<{
32
+ rule: string;
33
+ observed: unknown;
34
+ }>;
35
+ }
36
+ /** A caught visitor's later session without its cookies. */
37
+ export interface VisitorReturn {
38
+ visitor: string;
39
+ reason: ReturnReason;
40
+ at: string;
41
+ /** Seconds since the caught visitor's last page load. */
42
+ gapSeconds: number | null;
43
+ /** It came back while its session cookie should still have been there: cleared or blocked. */
44
+ cookieCleared: boolean;
45
+ userAgent: string | null;
46
+ page: string | null;
47
+ }
48
+ /** The caught visitor a visitor was recognized as. */
49
+ export interface VisitorLink {
50
+ visitor: string;
51
+ reason: ReturnReason;
52
+ at: string;
53
+ gapSeconds: number | null;
54
+ cookieCleared: boolean;
55
+ }
56
+ /** What Reguard knows about a visitor. `caught: false` for clean visitors and unknown ids alike. */
57
+ export interface VisitorStatus {
58
+ id: string;
59
+ caught: boolean;
60
+ kind: "browser" | "cookieless" | null;
61
+ labels: Label[];
62
+ stage: Stage | null;
63
+ firstSeen: string | null;
64
+ lastSeen: string | null;
65
+ caughtAt: string | null;
66
+ userAgent: string | null;
67
+ firstPage: string | null;
68
+ counts: {
69
+ catches: number;
70
+ blocked: number;
71
+ wouldBlock: number;
72
+ returns: number;
73
+ };
74
+ catches: VisitorCatch[];
75
+ returns: VisitorReturn[];
76
+ linkedTo: VisitorLink[];
77
+ /** The visitor on the dashboard. */
78
+ url: string;
79
+ }
80
+ export type ReguardEventType = "visitor.caught" | "visitor.escalated" | "visitor.returned" | "ping";
81
+ export interface ReguardEvent {
82
+ /** `evt_…`: unique; a delivery retried after a failure carries the same id. */
83
+ id: string;
84
+ type: ReguardEventType;
85
+ /** Epoch seconds. */
86
+ created: number;
87
+ site: string;
88
+ data: {
89
+ visitor?: VisitorStatus;
90
+ /** visitor.escalated: the stage before. */
91
+ previousStage?: Stage | null;
92
+ /** visitor.returned: the session that came back. */
93
+ returned?: VisitorReturn;
94
+ /** ping: the dashboard's test message. */
95
+ message?: string;
96
+ };
97
+ }
98
+ export interface EventsPage {
99
+ /** Oldest first. */
100
+ events: ReguardEvent[];
101
+ /** Pass as `after` next time (null until there is an event). */
102
+ next: string | null;
103
+ /** More events are waiting: ask again now. */
104
+ hasMore: boolean;
105
+ }
106
+ export declare class ReguardApiError extends Error {
107
+ readonly status: number;
108
+ constructor(status: number, message: string);
109
+ }
110
+ export interface ReguardApiOptions {
111
+ /** Site key; default REGUARD_KEY. */
112
+ key?: string;
113
+ /** Default REGUARD_COLLECTOR, then https://api.reguard.site. */
114
+ collector?: string;
115
+ fetch?: typeof fetch;
116
+ /** Per call (default 10000). */
117
+ timeoutMs?: number;
118
+ }
119
+ export interface ReguardApi {
120
+ /** A visitor by the id in its signed verdict (`req.reguard.visitor`). */
121
+ visitor(id: string): Promise<VisitorStatus>;
122
+ /** The event feed, oldest first, after `after` (an `evt_…` id). */
123
+ events(options?: {
124
+ after?: string | null;
125
+ limit?: number;
126
+ types?: readonly Exclude<ReguardEventType, "ping">[];
127
+ }): Promise<EventsPage>;
128
+ }
129
+ export declare function reguardApi(options?: ReguardApiOptions): ReguardApi;
130
+ /**
131
+ * The event in a webhook delivery, once its signature checks out; throws a ReguardWebhookError
132
+ * (`code`: missing_secret, missing_signature, malformed_signature, expired, bad_signature,
133
+ * bad_payload) otherwise. Pass the raw request body exactly as received, the Reguard-Signature
134
+ * header, and the endpoint's signing secret (default REGUARD_WEBHOOK_SECRET).
135
+ */
136
+ export declare function verifyWebhook(payload: string | Uint8Array | ArrayBuffer, signature: string | string[] | null | undefined, secret?: string, options?: {
137
+ tolerance?: number;
138
+ now?: number;
139
+ }): Promise<ReguardEvent>;
@@ -5,6 +5,11 @@ export type VerdictSource = "browser" | "server" | "both";
5
5
  export interface Verdict extends VerdictPayload {
6
6
  /** Where the claims came from. */
7
7
  source: VerdictSource;
8
+ /**
9
+ * The visitor's id (collector 0.9+; null from older ones): stable across its page loads, signed
10
+ * by Reguard. Look it up with `reguardApi().visitor(id)`, or match it to webhook events.
11
+ */
12
+ visitor: string | null;
8
13
  /**
9
14
  * Whether there is a claim for one of `labels` (default: any) at `minStage` or above (default
10
15
  * "candidate", i.e. including rules still on trial).
@@ -15,6 +20,8 @@ export interface Verdict extends VerdictPayload {
15
20
  }): boolean;
16
21
  }
17
22
  export declare const STAGE_RANK: Record<Stage, number>;
23
+ /** A visitor id as the collector issues them (`vis_` and 22 characters); anything else is ignored. */
24
+ export declare const visitorIdOf: (v: unknown) => string | undefined;
18
25
  export declare function withFlagged(p: VerdictPayload, source?: VerdictSource): Verdict;
19
26
  /** A browser verdict with claims the collector pushed to your server added (deduplicated by rule). */
20
27
  export declare function mergeVerdicts(browser: Verdict | null, pushed: Verdict | null): Verdict | null;
@@ -52,7 +59,7 @@ export declare function verdictAgeMs(v: {
52
59
  exp: number;
53
60
  }, now?: number): number;
54
61
  /** Claims the collector sent back to a site's server (no token: they arrived over its authenticated channel). */
55
- export declare function pushedVerdict(sid: string, site: string, claims: VerdictClaim[], now?: number): Verdict;
62
+ export declare function pushedVerdict(sid: string, site: string, claims: VerdictClaim[], now?: number, vid?: string): Verdict;
56
63
  /** Which limit a paced request went over. */
57
64
  export type PaceKind = "document" | "api" | "notfound";
58
65
  /** Why Reguard answered for the app (or, in a dry run, would have). */
@@ -5,12 +5,15 @@
5
5
  * import Fastify from "fastify";
6
6
  * import reguard from "reguard/fastify";
7
7
  *
8
- * const app = Fastify({ trustProxy: true }); // then Reguard uses Fastify's request.ip
9
- * await app.register(reguard, { block: { dryRun: true } });
8
+ * const app = Fastify();
9
+ * await app.register(reguard, { block: { dryRun: true } }); // at the root: it covers the whole app
10
10
  * app.get("/api/items", async (request) => (request.reguard?.flagged() ? [] : items));
11
11
  *
12
- * No dependency on fastify itself: the plugin is marked like fastify-plugin does, so its request
13
- * decorations apply app-wide.
12
+ * No dependency on fastify itself: the plugin is marked like fastify-plugin does, so registered at
13
+ * the root its hooks and request decorations apply app-wide (inside a prefixed scope, only there).
14
+ * Visitor addresses are read as reguard() reads them (your proxies, CloudFront, Cloudflare, the
15
+ * host's header); set `clientIp` for anything else. Fastify's `trustProxy: true` would hand over the
16
+ * client's own X-Forwarded-For entry, so it isn't used.
14
17
  */
15
18
  import type { IncomingMessage, ServerResponse } from "node:http";
16
19
  import type { Decision, Verdict } from "./core.cjs";
@@ -32,10 +35,15 @@ interface FastifyLike {
32
35
  addHook(name: "onClose", hook: (instance: unknown, done: () => void) => void): unknown;
33
36
  decorateRequest?(name: string, value: unknown): unknown;
34
37
  hasRequestDecorator?(name: string): boolean;
35
- initialConfig?: {
36
- trustProxy?: unknown;
37
- };
38
38
  }
39
39
  declare function plugin(fastify: FastifyLike, options: ReguardOptions, done: (err?: Error) => void): void;
40
40
  export declare const reguardFastify: typeof plugin;
41
41
  export default plugin;
42
+ declare module "fastify" {
43
+ interface FastifyRequest {
44
+ /** The visitor's verified verdict (null: none). Set by reguard/fastify. */
45
+ reguard: Verdict | null;
46
+ /** In a dry run, what Reguard would have done for this request (null: nothing). */
47
+ reguardDecision: Decision | null;
48
+ }
49
+ }
@@ -18,6 +18,8 @@ import { type BlockBase, type ClientIpOption, type LoggerLike } from "./config.c
18
18
  import { type Decision, type Verdict } from "./core.cjs";
19
19
  export type { Decision, Verdict, VerdictSource } from "./core.cjs";
20
20
  export { type BlockReason, ReguardConfigError } from "./config.cjs";
21
+ export { type EventsPage, type ReguardApi, type ReguardApiOptions, type ReguardEvent, type ReguardEventType, type ReguardWebhookErrorCode, type ReturnReason, type VisitorCatch, type VisitorLink, type VisitorReturn, type VisitorStatus, ReguardApiError, ReguardWebhookError, reguardApi, verifyWebhook, } from "./api.cjs";
22
+ import { type EventsPage, type ReguardApi, type VisitorStatus } from "./api.cjs";
21
23
  export interface FetchBlockOptions extends Omit<BlockBase, "require" | "requireMaxAgeMs" | "requireGraceMs" | "requireGraceRequests" | "requireGracePages" | "requireRefreshRequests" | "requireRefreshMs"> {
22
24
  allowIf?: (request: Request) => boolean;
23
25
  /** Your own answer for a blocked request; Reguard's default (`defaultBlockAnswer`) when it throws. */
@@ -55,8 +57,12 @@ export interface ReguardFetch {
55
57
  handle(request: Request, ctx?: {
56
58
  waitUntil?: WaitUntil;
57
59
  }): Promise<Response | undefined>;
58
- /** After your handler: queue the summary of its response. */
59
- record(request: Request, response: Response, ctx?: {
60
+ /**
61
+ * After your handler: queue the summary of its response. Middleware that never sees the response
62
+ * (Next.js) passes null: Reguard then reports only what it knows without one, its own decisions
63
+ * and requests from clients that don't present as a browser.
64
+ */
65
+ record(request: Request, response: Response | null, ctx?: {
60
66
  waitUntil?: WaitUntil;
61
67
  }): void;
62
68
  /** handle + your handler + record. The platform's waitUntil is found among the handler's arguments. */
@@ -69,6 +75,10 @@ export interface ReguardFetch {
69
75
  nonce?: string;
70
76
  }): string;
71
77
  flush(): Promise<void>;
78
+ /** A visitor by the id in its verdict: see reguardApi(). */
79
+ visitor(id: string): Promise<VisitorStatus>;
80
+ /** The event feed, for polling instead of webhooks: see reguardApi(). */
81
+ events(options?: Parameters<ReguardApi["events"]>[0]): Promise<EventsPage>;
72
82
  }
73
83
  /** Reguard's default answer for a decision (HTML page for page loads, JSON with a `code` otherwise). */
74
84
  export declare function defaultBlockAnswer(request: Request, decision: Decision): Response;
@@ -6,7 +6,9 @@ import { Health, type HealthState, type Log } from "./health.cjs";
6
6
  export type { AddressesMode, ClientIpMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.cjs";
7
7
  export type { Decision, PaceConfig, PaceKind, PaceRate, Verdict, VerdictSource } from "./core.cjs";
8
8
  export { type BlockReason, type ConfigErrorCode, type LoggerLike, ReguardConfigError } from "./config.cjs";
9
+ import { type EventsPage, type ReguardApi, type VisitorStatus } from "./api.cjs";
9
10
  export type { HealthState } from "./health.cjs";
11
+ export { type EventsPage, type ReguardApi, type ReguardApiOptions, type ReguardEvent, type ReguardEventType, type ReguardWebhookErrorCode, type ReturnReason, type VisitorCatch, type VisitorLink, type VisitorReturn, type VisitorStatus, ReguardApiError, ReguardWebhookError, reguardApi, verifyWebhook, } from "./api.cjs";
10
12
  export { formatSiteKey, parseSiteKey, type ParsedSiteKey } from "../../shared/src/index.cjs";
11
13
  declare global {
12
14
  namespace Express {
@@ -136,6 +138,10 @@ export interface ReguardMiddleware {
136
138
  flush(): Promise<void>;
137
139
  /** Stop the summary timer and send what's queued (e.g. on shutdown). */
138
140
  close(): Promise<void>;
141
+ /** A visitor by the id in its verdict (`req.reguard.visitor`): see reguardApi(). */
142
+ visitor(id: string): Promise<VisitorStatus>;
143
+ /** The event feed, for polling instead of webhooks: see reguardApi(). */
144
+ events(options?: Parameters<ReguardApi["events"]>[0]): Promise<EventsPage>;
139
145
  }
140
146
  /** A short public fingerprint of a key's secret: safe to log and to compare with the dashboard. */
141
147
  export declare function keyFingerprint(secret: string): string;