reguard 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +51 -31
  2. package/dist/chunks/chunk-3AYS7WSY.js +350 -0
  3. package/dist/chunks/chunk-KNKCUJL3.js +969 -0
  4. package/dist/chunks/{chunk-W56LN2M5.js → chunk-PA46KSOR.js} +385 -33
  5. package/dist/chunks/chunk-YDDBWUPV.js +438 -0
  6. package/dist/cjs/fastify.cjs +2109 -0
  7. package/dist/cjs/fetch.cjs +1453 -0
  8. package/dist/cjs/index.cjs +2074 -0
  9. package/dist/cjs/next.cjs +1518 -0
  10. package/dist/cjs/testing.cjs +214 -0
  11. package/dist/fastify.js +59 -0
  12. package/dist/fetch.js +13 -0
  13. package/dist/index.js +15 -716
  14. package/dist/next.js +41 -52
  15. package/dist/testing.js +39 -0
  16. package/dist/types/node/src/config.d.ts +107 -0
  17. package/dist/types/node/src/core.d.ts +66 -72
  18. package/dist/types/node/src/fastify.d.ts +41 -0
  19. package/dist/types/node/src/fetch.d.ts +76 -0
  20. package/dist/types/node/src/health.d.ts +41 -0
  21. package/dist/types/node/src/index.d.ts +114 -34
  22. package/dist/types/node/src/next.d.ts +40 -27
  23. package/dist/types/node/src/testing.d.ts +25 -0
  24. package/dist/types/shared/src/address.d.ts +81 -0
  25. package/dist/types/shared/src/index.d.ts +6 -0
  26. package/dist/types/shared/src/paths.d.ts +32 -0
  27. package/dist/types-cjs/node/src/config.d.cts +107 -0
  28. package/dist/types-cjs/node/src/core.d.cts +107 -0
  29. package/dist/types-cjs/node/src/fastify.d.cts +41 -0
  30. package/dist/types-cjs/node/src/fetch.d.cts +76 -0
  31. package/dist/types-cjs/node/src/health.d.cts +41 -0
  32. package/dist/types-cjs/node/src/index.d.cts +203 -0
  33. package/dist/types-cjs/node/src/next.d.cts +85 -0
  34. package/dist/types-cjs/node/src/testing.d.cts +25 -0
  35. package/dist/types-cjs/shared/src/address.d.cts +81 -0
  36. package/dist/types-cjs/shared/src/allowance.d.cts +17 -0
  37. package/dist/types-cjs/shared/src/collect.d.cts +52 -0
  38. package/dist/types-cjs/shared/src/exchange.d.cts +69 -0
  39. package/dist/types-cjs/shared/src/index.d.cts +105 -0
  40. package/dist/types-cjs/shared/src/keys.d.cts +13 -0
  41. package/dist/types-cjs/shared/src/paths.d.cts +32 -0
  42. package/dist/types-cjs/shared/src/tools.d.cts +101 -0
  43. package/dist/types-cjs/shared/src/verdict.d.cts +37 -0
  44. package/package.json +73 -10
@@ -1,50 +1,81 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
- import { type CollectOptions } from "../../shared/src/index.js";
3
- import { type BlockOption, type Verdict } from "./core.js";
4
- export type { AddressesMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.js";
5
- export type { BlockOption, PaceConfig, PaceRate, Verdict } from "./core.js";
2
+ import { type CanonicalPath, type CollectOptions, type CollectSettings, type ResolvedAddress } from "../../shared/src/index.js";
3
+ import { type BlockBase, type ClientIpOption, type LoggerLike } from "./config.js";
4
+ import { type Decision, type Verdict } from "./core.js";
5
+ import { Health, type HealthState, type Log } from "./health.js";
6
+ export type { AddressesMode, ClientIpMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.js";
7
+ export type { Decision, PaceConfig, PaceKind, PaceRate, Verdict, VerdictSource } from "./core.js";
8
+ export { type BlockReason, type ConfigErrorCode, type LoggerLike, ReguardConfigError } from "./config.js";
9
+ export type { HealthState } from "./health.js";
6
10
  export { formatSiteKey, parseSiteKey, type ParsedSiteKey } from "../../shared/src/index.js";
7
11
  declare global {
8
12
  namespace Express {
9
13
  interface Request {
10
14
  reguard?: Verdict | null;
15
+ reguardDecision?: Decision | null;
11
16
  reDetect?: Verdict | null;
12
17
  }
13
18
  }
14
19
  }
20
+ export type ReguardRequest = IncomingMessage & {
21
+ originalUrl?: string;
22
+ body?: unknown;
23
+ /** The visitor's verified verdict (null: none). Set on every request. */
24
+ reguard?: Verdict | null;
25
+ /** In a dry run, what Reguard would have done (null: nothing). */
26
+ reguardDecision?: Decision | null;
27
+ /** Alias of `reguard`, for code written against 0.3. */
28
+ reDetect?: Verdict | null;
29
+ /** Express: the address it resolved with `trust proxy`. */
30
+ ip?: string;
31
+ app?: {
32
+ get?(name: string): unknown;
33
+ };
34
+ };
35
+ export interface BlockOptions extends BlockBase {
36
+ /** Never block, pace or require these requests (after `allow`), e.g. `(req) => req.headers["x-internal"] === token`. */
37
+ allowIf?: (req: ReguardRequest) => boolean;
38
+ /**
39
+ * Answer a blocked request yourself (a page in your design, JSON your API clients expect). If it
40
+ * throws or doesn't answer, Reguard sends its default answer (`defaultBlockResponse`).
41
+ */
42
+ respond?: (req: ReguardRequest, res: ServerResponse, decision: Decision) => void | Promise<void>;
43
+ /** Called for every block, and in a dry run for every block that would have happened. */
44
+ onBlock?: (decision: Decision, req: ReguardRequest) => void;
45
+ }
46
+ export type BlockOption = boolean | BlockOptions;
15
47
  export interface ReguardOptions {
16
48
  /** Your site key (`rgk.…`, from the dashboard). Default: process.env.REGUARD_KEY. */
17
49
  key?: string;
50
+ /**
51
+ * The key you rotated away from, while visitors still hold verdicts signed with it (up to 10
52
+ * minutes). Default: process.env.REGUARD_KEY_PREVIOUS.
53
+ */
54
+ previousKey?: string;
18
55
  /** Where Reguard answers. Default: process.env.REGUARD_COLLECTOR or https://api.reguard.site. */
19
56
  collector?: string;
20
- /** Add the script tag to HTML pages. Default true. */
57
+ /** Add the script tag to HTML pages. Default true (add it yourself with `scriptTag()` when false). */
21
58
  inject?: boolean;
22
59
  /**
23
- * Answer flagged visitors for you. Default false: you decide, with `req.reguard`. `true` blocks
24
- * a visitor with any claim; `{ labels, status }` narrows it to some labels and picks the status
25
- * (default 429). Reguard's own /_s/* paths are never blocked.
60
+ * Answer flagged visitors for you. Default false: you decide, with `req.reguard`. `true` blocks a
61
+ * visitor with any claim, and paces clients faster than a person. See BlockOptions for labels,
62
+ * minStage, dryRun, allow, require, pace, respond and onBlock.
26
63
  */
27
64
  block?: BlockOption;
28
- /** Send request summaries to Reguard. Default true. (`collect.requests: false` does the same.) */
29
- forward?: boolean;
30
65
  /**
31
66
  * Source maps (`*.map`): "deny" answers 404 and drops SourceMap headers, so your original source
32
- * never leaves your server; requests for them are still reported. Default "deny" when `block` is
33
- * set, else "allow". Keep maps for your error tracker by uploading them to it privately.
67
+ * never leaves your server; requests for them are still reported. Default "deny" while `block`
68
+ * enforces anything, else "allow". Keep maps for your error tracker by uploading them to it privately.
34
69
  */
35
70
  sourceMaps?: "deny" | "allow";
36
- /** Paths never summarized (e.g. health checks). */
37
- ignore?: (path: string) => boolean;
71
+ /** Paths never summarized (e.g. ["/healthz"]). */
72
+ ignore?: readonly string[];
73
+ /** Requests never summarized, decided per request. */
74
+ ignoreIf?: (req: ReguardRequest) => boolean;
38
75
  /**
39
76
  * What Reguard receives, from your server and from the browser (the tag carries the same choices):
40
- * - `pages`: "masked" (default) sends page and API addresses with ids, emails and long tokens
41
- * replaced; "hashed" sends only a keyed hash of each address and the kind of request; "off" only
42
- * the kind of request.
43
- * - `addresses`: "hashed" (default) sends the visitor's address only as a keyed hash; "off" sends
44
- * nothing about it.
45
- * - `behavior`: false stops click, key, scroll and pointer timings from the browser.
46
- * - `requests`: false stops request summaries (the same as `forward: false`).
47
- * - `skip`: pages Reguard never runs on or reports, e.g. ["/account/*"].
77
+ * `pages` ("masked", "hashed", "off"), `addresses` ("hashed", "off"), `behavior`, `requests`
78
+ * (false stops request summaries) and `skip` (pages Reguard never runs on, e.g. ["/account/*"]).
48
79
  */
49
80
  collect?: CollectOptions;
50
81
  /**
@@ -52,29 +83,69 @@ export interface ReguardOptions {
52
83
  * paths, source maps, not-found answers). Default true. Addresses are sent only as a keyed hash.
53
84
  */
54
85
  watchSessionless?: boolean;
86
+ /**
87
+ * How to find the visitor's address behind your proxies. Default "auto": Express's `req.ip` when
88
+ * `trust proxy` is set, your host's header on Fly, Vercel, Railway, Netlify and App Engine,
89
+ * cf-connecting-ip behind Cloudflare, else X-Forwarded-For read from the right. Or "socket",
90
+ * `{ header: "x-real-ip" }`, `{ hops: 2 }`, `{ proxies: ["35.191.0.0/16"] }` or a function.
91
+ */
92
+ clientIp?: ClientIpOption<ReguardRequest>;
93
+ /**
94
+ * A parent domain (e.g. "example.com") for Reguard's cookies, so verdicts earned on www.example.com
95
+ * reach api.example.com (send credentials with those API calls).
96
+ */
97
+ cookieDomain?: string;
98
+ /** Log the resolved setup at startup and each decision. Default: process.env.REGUARD_DEBUG = "1". */
99
+ debug?: boolean;
100
+ /** Where Reguard logs (default console; false for silence). */
101
+ logger?: LoggerLike | false;
102
+ /** Limit for each call to Reguard (summaries, /_s/*). Default 10 000 ms. */
103
+ timeoutMs?: number;
55
104
  /** Advanced: custom fetch, error hook, summary flush interval. */
56
105
  fetch?: typeof fetch;
57
106
  onError?: (error: unknown) => void;
58
107
  flushIntervalMs?: number;
59
108
  }
60
- export type ReguardRequest = IncomingMessage & {
61
- originalUrl?: string;
62
- body?: unknown;
63
- reguard?: Verdict | null;
64
- /** Alias of `reguard`, for code written against 0.3. */
65
- reDetect?: Verdict | null;
66
- };
67
109
  type Next = (err?: unknown) => void;
110
+ export interface ReguardStatus {
111
+ /** False when no key is configured (everything passes through). */
112
+ enabled: boolean;
113
+ site?: string;
114
+ /** A short fingerprint of the key (the dashboard shows the same one), never the key. */
115
+ keyFingerprint?: string;
116
+ /** What the last summaries to Reguard saw. */
117
+ collector: HealthState | "off";
118
+ since: number;
119
+ lastError?: string;
120
+ /** require routes aren't enforced right now (Reguard unreachable, key rejected, plan paused). */
121
+ failOpen: boolean;
122
+ queued: number;
123
+ blocking: "off" | "on" | "dry run" | "partial dry run";
124
+ }
68
125
  export interface ReguardMiddleware {
69
126
  (req: IncomingMessage, res: ServerResponse, next: Next): void;
70
127
  /** The site id read from the key (undefined when no key is configured). */
71
128
  readonly site: string | undefined;
129
+ /** The script tag for this site, for pages that don't get it added (`inject: false`, a CSP nonce). */
130
+ scriptTag(options?: {
131
+ nonce?: string;
132
+ }): string;
133
+ /** For health endpoints: whether Reguard is on and reachable. */
134
+ status(): ReguardStatus;
72
135
  /** Send queued summaries now. */
73
136
  flush(): Promise<void>;
74
137
  /** Stop the summary timer and send what's queued (e.g. on shutdown). */
75
138
  close(): Promise<void>;
76
139
  }
77
- /** Express/Connect middleware: `app.use(reguard())`. */
140
+ /** A short public fingerprint of a key's secret: safe to log and to compare with the dashboard. */
141
+ export declare function keyFingerprint(secret: string): string;
142
+ /**
143
+ * Reguard's default answer for a decision: the status, a Retry-After, and a short HTML page for page
144
+ * loads or JSON with a stable `code` ("reguard.blocked", "reguard.require", "reguard.pace").
145
+ * Exported so a `block.respond` can fall back to it.
146
+ */
147
+ export declare function defaultBlockResponse(req: IncomingMessage, res: ServerResponse, decision: Decision): void;
148
+ /** Express/Connect middleware: `app.use(reguard())`. Throws ReguardConfigError for an option it can't use. */
78
149
  export declare function reguard(options?: ReguardOptions): ReguardMiddleware;
79
150
  export default reguard;
80
151
  export interface ReDetectServerOptions {
@@ -86,8 +157,6 @@ export interface ReDetectServerOptions {
86
157
  collector: string;
87
158
  /** First-party path the browser SDK uses on this origin (default "/_s"). */
88
159
  prefix?: string;
89
- /** Send request summaries to the collector (default true). */
90
- forward?: boolean;
91
160
  /** Also describe every request that carries no SDK session (default false). */
92
161
  includeSessionless?: boolean;
93
162
  /**
@@ -100,13 +169,22 @@ export interface ReDetectServerOptions {
100
169
  /** Paths never described, e.g. health checks. */
101
170
  ignore?: (path: string) => boolean;
102
171
  /** What Reguard receives (see ReguardOptions.collect). */
103
- collect?: CollectOptions;
172
+ collect?: CollectOptions | CollectSettings;
104
173
  flushIntervalMs?: number;
105
174
  maxQueue?: number;
106
175
  fetch?: typeof fetch;
107
176
  onError?: (error: unknown) => void;
108
177
  }
109
- export declare function createReDetect(opts: ReDetectServerOptions): {
178
+ /** reguard()'s wiring into createReDetect (not a public API). */
179
+ interface Wiring {
180
+ health?: Health;
181
+ log?: Log;
182
+ timeoutMs?: number;
183
+ address?: (req: ReguardRequest) => ResolvedAddress;
184
+ ignored?: (req: ReguardRequest, p: CanonicalPath) => boolean;
185
+ decided?: (req: ReguardRequest) => Decision | undefined;
186
+ }
187
+ export declare function createReDetect(opts: ReDetectServerOptions, wiring?: Wiring): {
110
188
  middleware: () => (req: ReguardRequest, res: ServerResponse, next: Next) => void;
111
189
  route: () => (req: ReguardRequest, res: ServerResponse) => Promise<void>;
112
190
  track: (req: ReguardRequest, res: ServerResponse) => void;
@@ -117,6 +195,8 @@ export declare function createReDetect(opts: ReDetectServerOptions): {
117
195
  readVerdictFromHeaders: (headers: {
118
196
  get(name: string): string | null;
119
197
  }) => Promise<Verdict | null>;
198
+ /** Summaries waiting to be sent. */
199
+ queued: () => number;
120
200
  /** Send queued summaries now (e.g. before shutdown). */
121
201
  flush: () => Promise<void>;
122
202
  close: () => Promise<void>;
@@ -1,34 +1,39 @@
1
1
  /**
2
- * reguard/next: Reguard for Next.js. Runtime-neutral (no node: imports), so it also runs
3
- * in middleware and on the edge runtime.
2
+ * reguard/next: Reguard for Next.js. Runtime-neutral (no node: imports), so it also runs in
3
+ * middleware and on the edge runtime. Built on reguard/fetch.
4
4
  *
5
5
  * // next.config.js
6
6
  * import { withReguard } from "reguard/next";
7
7
  * export default withReguard({ ...yourConfig });
8
8
  *
9
- * // app/layout.tsx
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
- * // what Reguard receives: reguardScriptProps({ collect: { pages: "hashed", skip: ["/account/*"] } })
14
13
  *
15
14
  * // anywhere on the server: route handler, server action, middleware
16
15
  * const verdict = await reguardVerdict(request);
17
16
  *
18
- * // middleware.ts: answer flagged visitors with 429, like reguard({ block: true }) in Express
17
+ * // middleware.ts (proxy.ts on Next 16): answer flagged visitors, like reguard({ block: true })
19
18
  * export const middleware = reguardMiddleware({ block: true });
20
19
  */
21
20
  import { type CollectOptions } from "../../shared/src/index.js";
22
- import { type BlockOption, type Verdict } from "./core.js";
23
- export type { BlockOption, Verdict } from "./core.js";
21
+ import { type ClientIpOption, type LoggerLike } from "./config.js";
22
+ import { type Verdict } from "./core.js";
23
+ import { type FetchBlockOptions } from "./fetch.js";
24
+ export type { Decision, Verdict, VerdictSource } from "./core.js";
25
+ export type { FetchBlockOptions as BlockOptions } from "./fetch.js";
26
+ export { type BlockReason, ReguardConfigError } from "./config.js";
24
27
  export type { AddressesMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.js";
25
28
  /**
26
- * Adds the rewrite that serves /_s/* from Reguard, first-party, ahead of your own routes. Keeps your
27
- * rewrites in whichever shape they come (none, an array, or beforeFiles/afterFiles/fallback), and
28
- * takes a config object or a config function. Typed loosely on purpose: it returns what it is given.
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.
29
33
  */
30
34
  export declare function withReguard<T extends object>(config: T, options?: {
31
35
  collector?: string;
36
+ key?: string;
32
37
  }): T;
33
38
  /** The visitor's verified verdict from a Request or NextRequest (null when there is none). */
34
39
  export declare function reguardVerdict(request: {
@@ -37,36 +42,44 @@ export declare function reguardVerdict(request: {
37
42
  };
38
43
  }, options?: {
39
44
  key?: string;
45
+ previousKey?: string;
40
46
  }): Promise<Verdict | null>;
41
47
  export type ReguardScriptProps = {
42
48
  src: string;
43
49
  async: true;
44
50
  referrerPolicy: "origin";
51
+ nonce?: string;
45
52
  } & {
46
53
  [attr: `data-${string}`]: string;
47
54
  };
48
55
  /**
49
- * Props for `<Script>`: the site id comes from REGUARD_KEY on the server; the secret never leaves it.
50
- * `collect` chooses what Reguard receives from the browser (pages, addresses, behavior, skip; see
51
- * the integration guide). The script asks for the origin-only Referer, so the page's own address
52
- * never rides along on its requests through the /_s rewrite.
56
+ * Props for `<Script>`. The site id comes from REGUARD_KEY on the server (the secret never leaves
57
+ * it), or from NEXT_PUBLIC_REGUARD_SITE (set by withReguard) where the key isn't available.
58
+ * `collect` chooses what Reguard receives from the browser; `nonce` for a nonce-based CSP;
59
+ * `cookieDomain` to share verdicts with sibling hosts (api.example.com). The script asks for the
60
+ * origin-only Referer, so the page's own address never rides along on its requests.
53
61
  */
54
62
  export declare function reguardScriptProps(options?: {
55
63
  key?: string;
56
64
  collect?: Omit<CollectOptions, "requests">;
65
+ nonce?: string;
66
+ cookieDomain?: string;
57
67
  }): ReguardScriptProps;
58
- /**
59
- * Next.js middleware (edge or Node runtime) that answers flagged visitors itself, like
60
- * `reguard({ block: true })` in Express: status 429 (or `status`) with Retry-After, a short page for
61
- * page loads and JSON otherwise. `block: true` acts on any claim; `{ labels }` narrows it. Reguard's
62
- * own /_s/* is never blocked. Everyone else gets `undefined`, so Next carries on.
63
- *
64
- * With `block` it also paces pages for clients that don't present as a browser (`block.pace`; each
65
- * edge instance counts on its own) and denies source maps (`sourceMaps`, default "deny" with
66
- * `block`): keep `*.map` in your middleware matcher for that.
67
- */
68
- export declare function reguardMiddleware(options?: {
69
- block?: BlockOption;
68
+ export interface ReguardMiddlewareOptions {
69
+ block?: boolean | FetchBlockOptions;
70
70
  key?: string;
71
+ previousKey?: string;
71
72
  sourceMaps?: "deny" | "allow";
72
- }): (request: Request) => Promise<Response | undefined>;
73
+ clientIp?: ClientIpOption<Request>;
74
+ debug?: boolean;
75
+ logger?: LoggerLike | false;
76
+ }
77
+ /**
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.
83
+ * `block.require` needs reguard() in a Node server and is refused here.
84
+ */
85
+ export declare function reguardMiddleware(options?: ReguardMiddlewareOptions): (request: Request) => Promise<Response | undefined>;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * reguard/testing: helpers for your own tests. Make a visitor Reguard has flagged (or a clean one)
3
+ * without running a browser, and check how your app responds.
4
+ *
5
+ * import { testKey, verdictCookie, claim } from "reguard/testing";
6
+ * const key = testKey("shop"); // pass it as reguard({ key }) or REGUARD_KEY
7
+ * const cookie = await verdictCookie(key, { claims: [claim("unauthorized_extraction", "alert")] });
8
+ * await request(app).get("/api/items").set("cookie", cookie).expect(429);
9
+ *
10
+ * Never use a test key in production: it only signs verdicts your tests make up.
11
+ */
12
+ import { type Label, type Stage, type VerdictClaim } from "../../shared/src/index.js";
13
+ /** A fresh, valid key for a made-up site (random secret each call). */
14
+ export declare function testKey(site?: string): string;
15
+ /** One claim, as Reguard would make it (default stage "alert", rule "test.claim.<label>"). */
16
+ export declare function claim(label: Label, stage?: Stage, rule?: string): VerdictClaim;
17
+ /**
18
+ * A Cookie header value (`_s=…; _sv=…`) carrying a verdict signed with `key`: no claims for a clean
19
+ * visitor, claims for a flagged one. Valid for 10 minutes from `issuedAt` (default now).
20
+ */
21
+ export declare function verdictCookie(key: string, options?: {
22
+ claims?: VerdictClaim[];
23
+ sid?: string;
24
+ issuedAt?: number;
25
+ }): Promise<string>;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The visitor's address, as a site's server can trust it. Runtime-neutral (no node: imports), shared
3
+ * by the Node middleware and the fetch/edge helpers; the Python and Go SDKs implement the same rules
4
+ * (checked against sdks/conformance/vectors.json).
5
+ *
6
+ * X-Forwarded-For is a list every proxy appends to, so only its right end can be trusted: anything to
7
+ * the left of the last proxy you run was written by the client. "auto" therefore never takes the first
8
+ * entry. In order, it uses:
9
+ * 1. an address the web framework already resolved from its own proxy settings (Express with
10
+ * `trust proxy`, Fastify with `trustProxy`);
11
+ * 2. the host's own client header when the host is known from the environment (Fly, Vercel,
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.
19
+ */
20
+ export type ClientIpMode = "auto" | "socket" | {
21
+ header: string;
22
+ } | {
23
+ proxies: readonly string[];
24
+ } | {
25
+ hops: number;
26
+ };
27
+ /** Hosts whose own client header "auto" trusts once they are detected from the environment. */
28
+ export type Platform = "fly" | "vercel" | "railway" | "netlify" | "appengine" | "workers";
29
+ export declare const PLATFORM_HEADERS: Readonly<Record<Platform, string>>;
30
+ /** The host, from environment variables it sets for every app (null when not one of the known hosts). */
31
+ export declare function detectPlatform(env: Record<string, string | undefined> | undefined): Platform | null;
32
+ export interface AddressRequest {
33
+ /** The connecting peer (the socket's remote address); "" when unknown. */
34
+ peer: string;
35
+ /** A request header by lower-case name; several values joined with ", ". */
36
+ header(name: string): string | undefined;
37
+ /** An address the web framework already resolved from its own proxy settings. */
38
+ framework?: string;
39
+ }
40
+ export interface ResolvedAddress {
41
+ /** The visitor's address, normalized (IPv4 dotted, IPv6 compressed); "" when none could be read. */
42
+ address: string;
43
+ /** No public address anywhere in the chain: one of your own servers. Never paced. */
44
+ internal: boolean;
45
+ /** Where it came from: "framework", "platform:<host>", "cloudflare", "forwarded", "socket", "header", "hops", "proxies". */
46
+ via: string;
47
+ }
48
+ /** Cloudflare's published ranges (cloudflare.com/ips-v4, /ips-v6; checked 2026-12-03). */
49
+ export declare const CLOUDFLARE_RANGES: readonly string[];
50
+ /** Addresses that are never a visitor's: unspecified, private, shared (carrier-grade NAT), loopback, link-local. */
51
+ export declare const NON_PUBLIC_RANGES: readonly string[];
52
+ /** At most this many X-Forwarded-For entries are read (from the right). */
53
+ export declare const MAX_FORWARDED = 32;
54
+ /** An address as 16 bytes, or null. Accepts IPv4, IPv6 (with an IPv4 tail) and IPv4-mapped IPv6. */
55
+ export declare function parseIp(text: string): Uint8Array | null;
56
+ /** The canonical text of a parsed address: dotted IPv4 (mapped forms unmapped), RFC 5952 IPv6. */
57
+ export declare function formatIp(b: Uint8Array): string;
58
+ /**
59
+ * One address out of a header token: quotes, brackets, ports ("1.2.3.4:80", "[::1]:443",
60
+ * "2001:db8::1:46532" as CloudFront sends it) and zone ids removed, then normalized. Null when the
61
+ * token is not an address ("unknown", obfuscated identifiers, garbage).
62
+ */
63
+ export declare function normalizeIp(token: string | undefined): string | null;
64
+ interface Cidr {
65
+ bytes: Uint8Array;
66
+ bits: number;
67
+ }
68
+ /** "a.b.c.d/n", "v6/n" or a bare address; null when malformed. */
69
+ export declare function parseCidr(text: string): Cidr | null;
70
+ /** Whether an address (any text form) belongs to one of the ranges. */
71
+ export declare function ipInRanges(address: string, ranges: readonly string[] | readonly Cidr[]): boolean;
72
+ /** A visitor's address could be this one: not private, shared, loopback, link-local or unspecified. */
73
+ export declare function isPublicIp(address: string): boolean;
74
+ /**
75
+ * The visitor's address under `mode` (default "auto"). `platform` is the host detected from the
76
+ * environment (detectPlatform), passed in so the result never depends on hidden state.
77
+ */
78
+ export declare function resolveClientAddress(req: AddressRequest, mode?: ClientIpMode, platform?: Platform | null): ResolvedAddress;
79
+ /** Whether `value` is a valid clientIp mode (for config validation). Functions are checked by the caller. */
80
+ export declare function clientIpModeProblem(value: unknown): string | null;
81
+ export {};
@@ -30,10 +30,14 @@ export interface InitRequest {
30
30
  deviceId: string;
31
31
  /** The site's data choices (SDK 0.6+), so the collector honours them and reviewers see them. */
32
32
  collect?: CollectReport;
33
+ /** Seconds between verdict refreshes the site asks for (data-fresh, block.require): never sampled out (SDK 0.8+). */
34
+ fresh?: number;
33
35
  }
34
36
  export interface InitResponse {
35
37
  sid: string;
36
38
  token: string;
39
+ /** A signed verdict with no claims for this session (collector 0.8+): the SDK sets it as `_sv` at once. */
40
+ verdict?: string;
37
41
  /** Canary token used for the first-party source-map tripwire (F1). */
38
42
  canary: string;
39
43
  /** First-party prefix the collector is reachable at on this origin, e.g. "/_s". */
@@ -95,5 +99,7 @@ export * from "./keys.js";
95
99
  export * from "./tools.js";
96
100
  export * from "./collect.js";
97
101
  export * from "./allowance.js";
102
+ export * from "./address.js";
103
+ export * from "./paths.js";
98
104
  import type { VerdictClaim } from "./verdict.js";
99
105
  import type { CollectReport } from "./collect.js";
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Request paths for matching rules (`require`, `allow`, `collect.skip`, `ignore`, source-map denial).
3
+ * Runtime-neutral; the Python and Go SDKs implement the same rules (sdks/conformance/vectors.json).
4
+ *
5
+ * Frameworks route on different forms of the same path: Express on the raw path, Flask, Django,
6
+ * Starlette and Go's ServeMux on the decoded one, static file servers on a decoded and normalized
7
+ * one. A rule checked against only one form can be walked around with the other (`/%61pi/items`
8
+ * reaches `/api/items`; `/app.js%2Emap` is served as `/app.js.map`). So every rule sees both:
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.
11
+ * Protections apply when either form matches; exemptions only when both do. Summaries keep the raw
12
+ * path.
13
+ */
14
+ export interface CanonicalPath {
15
+ raw: string;
16
+ decoded: string;
17
+ }
18
+ /**
19
+ * Percent-decoding, once. When the path holds a malformed escape or the bytes aren't UTF-8, only
20
+ * escapes of ASCII characters (%00-%7F) are decoded and the rest stay as they are.
21
+ */
22
+ export declare function decodeOnce(s: string): string;
23
+ /** `//` collapsed, then `.` and `..` resolved (RFC 3986 section 5.2.4); never climbs above `/`. */
24
+ export declare function normalizeSegments(path: string): string;
25
+ /** Both forms of a request target (`req.url`, a RequestURI, a WSGI path): see the module comment. */
26
+ export declare function canonicalPath(target: string | undefined): CanonicalPath;
27
+ /** A protection (require, source maps, skip, ignore) applies when either form matches. */
28
+ export declare function matchesEither(matcher: (path: string) => boolean, p: CanonicalPath): boolean;
29
+ /** An exemption (block.allow) applies only when both forms match. */
30
+ export declare function matchesBoth(matcher: (path: string) => boolean, p: CanonicalPath): boolean;
31
+ /** A source map request (`*.map`), in either form. */
32
+ export declare function isSourceMapPath(p: CanonicalPath): boolean;
@@ -0,0 +1,107 @@
1
+ import { type ClientIpMode, type CollectSettings, type Label, type Stage } from "../../shared/src/index.cjs";
2
+ import { type PaceConfig, type PaceRate } from "./core.cjs";
3
+ export type ConfigErrorCode = "unknown_option" | "removed_option" | "invalid_type" | "invalid_value" | "empty_list" | "out_of_range";
4
+ /** Thrown at startup for an option Reguard can't use. `option` is its path, e.g. "block.minStage". */
5
+ export declare class ReguardConfigError extends TypeError {
6
+ readonly option: string;
7
+ readonly code: ConfigErrorCode;
8
+ constructor(option: string, code: ConfigErrorCode, detail: string);
9
+ }
10
+ /** Why Reguard answered (or, in a dry run, would have answered) for the app. */
11
+ export type BlockReason = "flagged" | "flagged_server" | "require" | "pace";
12
+ export declare const BLOCK_REASONS: readonly BlockReason[];
13
+ export declare const LABELS: readonly Label[];
14
+ export declare const STAGES: readonly Stage[];
15
+ export declare function checkBoolean(v: unknown, option: string): boolean | undefined;
16
+ export declare function checkFunction<T>(v: unknown, option: string): T | undefined;
17
+ export declare function checkNumber(v: unknown, option: string, min: number, max: number, integer?: boolean): number | undefined;
18
+ /** A list of path patterns ("/api/*"); a comma-separated string is accepted where `commas` is set. */
19
+ export declare function checkPaths(v: unknown, option: string, commas?: boolean): string[] | undefined;
20
+ /** collect, checked strictly (the browser's resolveCollect stays lenient: it must never throw into a page). */
21
+ export declare function checkCollect(v: unknown, option?: string): CollectSettings;
22
+ export type ClientIpOption<Req> = ClientIpMode | ((req: Req) => string | undefined | null);
23
+ export declare function checkClientIp<Req>(v: unknown, option?: string): ClientIpOption<Req>;
24
+ /** A parent domain for Reguard's cookies ("example.com" or ".example.com"), normalized without the dot. */
25
+ export declare function checkCookieDomain(v: unknown, option?: string): string | undefined;
26
+ export declare function checkCollector(v: unknown, option?: string): string | undefined;
27
+ export interface LoggerLike {
28
+ warn(message: string): void;
29
+ error(message: string): void;
30
+ info?(message: string): void;
31
+ debug?(message: string): void;
32
+ }
33
+ export declare function checkLogger(v: unknown, option?: string): LoggerLike | false | undefined;
34
+ export interface BlockBase {
35
+ /** Only claims with these labels block (default: any label). */
36
+ labels?: readonly Label[];
37
+ /** Status for flagged visitors (default 429). Pace and require answers are always 429. */
38
+ status?: number;
39
+ /** Least stage that blocks (default "candidate": rules still on trial count too). */
40
+ minStage?: Stage;
41
+ /**
42
+ * Decide, report and call onBlock, but never answer for the app: `true` for every reason, or a
43
+ * list of reasons (["require", "pace"]) to roll out one at a time. The decision is on the request
44
+ * (req.reguardDecision) and in the dashboard as "would have blocked".
45
+ */
46
+ dryRun?: boolean | readonly BlockReason[];
47
+ /** Paths never blocked, paced or required, e.g. webhooks and health checks (["/webhooks/*"]). */
48
+ allow?: readonly string[];
49
+ /** Routes that need a live Reguard page (see the docs, "Require a live page"). reguard() only. */
50
+ require?: readonly string[];
51
+ requireMaxAgeMs?: number;
52
+ requireGraceMs?: number;
53
+ requireGraceRequests?: number;
54
+ requireGracePages?: number;
55
+ requireRefreshRequests?: number;
56
+ requireRefreshMs?: number;
57
+ /** Slow down clients faster than a person (default on with block; false turns it off). */
58
+ pace?: boolean | {
59
+ documents?: Partial<PaceRate>;
60
+ api?: Partial<PaceRate>;
61
+ notFound?: Partial<PaceRate>;
62
+ };
63
+ }
64
+ export interface BlockConfig {
65
+ labels?: readonly Label[];
66
+ status: number;
67
+ minStage: Stage;
68
+ dryRun: ReadonlySet<BlockReason>;
69
+ allow: readonly string[];
70
+ require?: readonly string[];
71
+ maxAgeMs: number;
72
+ graceMs: number;
73
+ graceRequests: number;
74
+ gracePages: number;
75
+ refreshRequests: number;
76
+ refreshMs: number;
77
+ pace: PaceConfig | null;
78
+ allowIf?: (...a: never[]) => unknown;
79
+ respond?: (...a: never[]) => unknown;
80
+ onBlock?: (...a: never[]) => unknown;
81
+ }
82
+ /** `block` (true, false or options) as the middleware uses it; null when blocking is off. */
83
+ export declare function checkBlock(v: unknown, option?: string, runtime?: "node" | "fetch"): BlockConfig | null;
84
+ export declare const NODE_OPTION_KEYS: readonly ["key", "previousKey", "collector", "inject", "block", "sourceMaps", "ignore", "ignoreIf", "collect", "watchSessionless", "clientIp", "cookieDomain", "debug", "logger", "timeoutMs", "fetch", "onError", "flushIntervalMs"];
85
+ export declare const MOVED_OPTIONS: Record<string, string>;
86
+ export interface CheckedOptions<Req> {
87
+ key?: string;
88
+ previousKey?: string;
89
+ collector?: string;
90
+ inject: boolean;
91
+ block: BlockConfig | null;
92
+ sourceMaps?: "deny" | "allow";
93
+ ignore: string[];
94
+ ignoreIf?: (req: Req) => boolean;
95
+ collect: CollectSettings;
96
+ watchSessionless: boolean;
97
+ clientIp: ClientIpOption<Req>;
98
+ cookieDomain?: string;
99
+ debug?: boolean;
100
+ logger?: LoggerLike | false;
101
+ timeoutMs: number;
102
+ fetch?: typeof fetch;
103
+ onError?: (error: unknown) => void;
104
+ flushIntervalMs: number;
105
+ }
106
+ /** Every reguard() option checked; throws ReguardConfigError on the first problem. */
107
+ export declare function checkOptions<Req>(options: unknown): CheckedOptions<Req>;