reguard 0.9.0 → 0.11.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.
package/dist/fastify.js CHANGED
@@ -1,23 +1,16 @@
1
1
  import {
2
2
  reguard
3
- } from "./chunks/chunk-CUIFGML3.js";
3
+ } from "./chunks/chunk-EV6D7UZF.js";
4
4
  import {
5
5
  ReguardConfigError
6
- } from "./chunks/chunk-W4FDH5AD.js";
7
- import "./chunks/chunk-CGXTVKRB.js";
6
+ } from "./chunks/chunk-VZKXPEWQ.js";
7
+ import "./chunks/chunk-2N762ZXU.js";
8
8
 
9
9
  // src/fastify.ts
10
- var FASTIFY_IP = /* @__PURE__ */ new WeakMap();
11
10
  function plugin(fastify, options, done) {
12
11
  let mw;
13
12
  try {
14
- const trusted = !!fastify.initialConfig?.trustProxy;
15
- mw = reguard(
16
- trusted && options.clientIp === void 0 ? {
17
- ...options,
18
- clientIp: (req) => FASTIFY_IP.get(req) ?? null
19
- } : options
20
- );
13
+ mw = reguard(options);
21
14
  } catch (e) {
22
15
  done(e);
23
16
  return;
@@ -25,7 +18,6 @@ function plugin(fastify, options, done) {
25
18
  for (const name of ["reguard", "reguardDecision"]) if (!fastify.hasRequestDecorator?.(name)) fastify.decorateRequest?.(name, null);
26
19
  fastify.addHook("onRequest", (request, reply, next) => {
27
20
  const raw = request.raw;
28
- if (request.ip) FASTIFY_IP.set(raw, request.ip);
29
21
  let passed = false;
30
22
  const res = reply.raw;
31
23
  const writeHead = res.writeHead;
package/dist/fetch.js CHANGED
@@ -1,16 +1,16 @@
1
1
  import {
2
2
  defaultBlockAnswer,
3
3
  reguardFetch
4
- } from "./chunks/chunk-PRPLLMXA.js";
4
+ } from "./chunks/chunk-XCSVBLHF.js";
5
5
  import {
6
6
  ReguardApiError,
7
7
  ReguardConfigError,
8
8
  reguardApi,
9
9
  verifyWebhook
10
- } from "./chunks/chunk-W4FDH5AD.js";
10
+ } from "./chunks/chunk-VZKXPEWQ.js";
11
11
  import {
12
12
  WebhookSignatureError
13
- } from "./chunks/chunk-CGXTVKRB.js";
13
+ } from "./chunks/chunk-2N762ZXU.js";
14
14
  export {
15
15
  ReguardApiError,
16
16
  ReguardConfigError,
package/dist/index.js CHANGED
@@ -4,18 +4,18 @@ import {
4
4
  index_default,
5
5
  keyFingerprint,
6
6
  reguard
7
- } from "./chunks/chunk-CUIFGML3.js";
7
+ } from "./chunks/chunk-EV6D7UZF.js";
8
8
  import {
9
9
  ReguardApiError,
10
10
  ReguardConfigError,
11
11
  reguardApi,
12
12
  verifyWebhook
13
- } from "./chunks/chunk-W4FDH5AD.js";
13
+ } from "./chunks/chunk-VZKXPEWQ.js";
14
14
  import {
15
15
  WebhookSignatureError,
16
16
  formatSiteKey,
17
17
  parseSiteKey
18
- } from "./chunks/chunk-CGXTVKRB.js";
18
+ } from "./chunks/chunk-2N762ZXU.js";
19
19
  export {
20
20
  ReguardApiError,
21
21
  ReguardConfigError,
package/dist/next.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  reguardFetch
3
- } from "./chunks/chunk-PRPLLMXA.js";
3
+ } from "./chunks/chunk-XCSVBLHF.js";
4
4
  import {
5
5
  ReguardApiError,
6
6
  ReguardConfigError,
@@ -9,32 +9,26 @@ import {
9
9
  checkCookieDomain,
10
10
  reguardApi,
11
11
  verifyWebhook
12
- } from "./chunks/chunk-W4FDH5AD.js";
12
+ } from "./chunks/chunk-VZKXPEWQ.js";
13
13
  import {
14
14
  WebhookSignatureError,
15
15
  collectAttributes,
16
- collectorBase,
17
16
  envValue,
18
17
  isReguardPath,
19
18
  parseSiteKey,
20
19
  readVerdictFrom,
21
20
  resolveCollect
22
- } from "./chunks/chunk-CGXTVKRB.js";
21
+ } from "./chunks/chunk-2N762ZXU.js";
23
22
 
24
23
  // src/next.ts
24
+ var SITE_ID = /^[\w.-]{1,64}$/;
25
25
  function withReguard(config, options = {}) {
26
- const rule = { source: "/_s/:path*", destination: `${collectorBase(options.collector ?? envValue("REGUARD_COLLECTOR"))}/_s/:path*`, basePath: false };
27
- const site = parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site;
28
- const apply = (cfg) => ({
29
- ...cfg,
30
- ...site ? { env: { ...cfg.env ?? {}, NEXT_PUBLIC_REGUARD_SITE: site } } : {},
31
- async rewrites() {
32
- const mine = cfg.rewrites ? await cfg.rewrites() : void 0;
33
- if (!mine) return { beforeFiles: [rule], afterFiles: [], fallback: [] };
34
- if (Array.isArray(mine)) return { beforeFiles: [rule], afterFiles: mine, fallback: [] };
35
- return { ...mine, beforeFiles: [rule, ...mine.beforeFiles ?? []] };
36
- }
37
- });
26
+ if (options.collector !== void 0)
27
+ throw new ReguardConfigError("collector", "removed_option", "was removed from withReguard: reguardMiddleware() serves /_s/* and reads REGUARD_COLLECTOR at run time");
28
+ if (options.site !== void 0 && (typeof options.site !== "string" || !SITE_ID.test(options.site)))
29
+ throw new ReguardConfigError("site", "invalid_value", 'must be your site id (on your dashboard), e.g. "shop-example-com"');
30
+ const site = options.site ?? parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site;
31
+ const apply = (cfg) => site ? { ...cfg, env: { ...cfg.env ?? {}, NEXT_PUBLIC_REGUARD_SITE: site } } : cfg;
38
32
  if (typeof config === "function") {
39
33
  const fn = config;
40
34
  return (async (...args) => apply(await fn(...args)));
@@ -62,9 +56,13 @@ function reguardScriptProps(options = {}) {
62
56
  const site = parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site ?? publicSite();
63
57
  if (!site && !warned) {
64
58
  warned = true;
65
- console.warn("[reguard] REGUARD_KEY is not set (and withReguard didn't provide NEXT_PUBLIC_REGUARD_SITE): the script will load but not start.");
59
+ console.warn(
60
+ "[reguard] No site id for the script tag: REGUARD_KEY isn't set here and NEXT_PUBLIC_REGUARD_SITE isn't either, so the script won't start on this page. For pages rendered at build time, set NEXT_PUBLIC_REGUARD_SITE to your site id (it's public; your dashboard shows it), or pass it to withReguard({ ... }, { site })."
61
+ );
66
62
  }
67
63
  const production = envValue("NODE_ENV") === "production";
64
+ if (!production && options.collect && options.collect.requests !== void 0)
65
+ throw new ReguardConfigError("collect.requests", "unknown_option", "isn't an option of reguardScriptProps (the script sends no request summaries): pass it to reguardMiddleware");
68
66
  const collect = production ? resolveCollect(options.collect, (m) => console.warn(`[reguard] ${m}`)) : checkCollect(options.collect);
69
67
  const cookieDomain = production ? typeof options.cookieDomain === "string" ? options.cookieDomain.replace(/^\./, "").toLowerCase() : void 0 : checkCookieDomain(options.cookieDomain);
70
68
  return {
@@ -77,15 +75,19 @@ function reguardScriptProps(options = {}) {
77
75
  ...cookieDomain ? { "data-cookie-domain": cookieDomain } : {}
78
76
  };
79
77
  }
78
+ var MIDDLEWARE_OPTIONS = ["block", "key", "previousKey", "collector", "collect", "ignore", "sourceMaps", "clientIp", "timeoutMs", "debug", "logger"];
80
79
  function reguardMiddleware(options = {}) {
81
80
  for (const k of Object.keys(options))
82
- if (!["block", "key", "previousKey", "sourceMaps", "clientIp", "debug", "logger"].includes(k) && options[k] !== void 0)
81
+ if (!MIDDLEWARE_OPTIONS.includes(k) && options[k] !== void 0)
83
82
  throw new ReguardConfigError(k, "unknown_option", "isn't an option of reguardMiddleware");
84
83
  checkBlock(options.block, "block", "fetch");
85
- const rg = reguardFetch({ ...options, collect: { requests: false } });
86
- return async (request) => {
87
- if (isReguardPath(new URL(request.url).pathname)) return void 0;
88
- return rg.handle(request);
84
+ const rg = reguardFetch(options);
85
+ return async (request, event) => {
86
+ const ctx = typeof event?.waitUntil === "function" ? { waitUntil: event.waitUntil.bind(event) } : void 0;
87
+ const answered = await rg.handle(request, ctx);
88
+ if (isReguardPath(new URL(request.url).pathname)) return answered;
89
+ rg.record(request, answered ?? null, ctx);
90
+ return answered;
89
91
  };
90
92
  }
91
93
  export {
package/dist/testing.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  parseSiteKey,
5
5
  signVerdict,
6
6
  signWebhookPayload
7
- } from "./chunks/chunk-CGXTVKRB.js";
7
+ } from "./chunks/chunk-2N762ZXU.js";
8
8
 
9
9
  // src/testing.ts
10
10
  function testKey(site = "test-site") {
@@ -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.js";
@@ -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
+ }
@@ -57,8 +57,12 @@ export interface ReguardFetch {
57
57
  handle(request: Request, ctx?: {
58
58
  waitUntil?: WaitUntil;
59
59
  }): Promise<Response | undefined>;
60
- /** After your handler: queue the summary of its response. */
61
- 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?: {
62
66
  waitUntil?: WaitUntil;
63
67
  }): void;
64
68
  /** handle + your handler + record. The platform's waitUntil is found among the handler's arguments. */
@@ -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";
@@ -27,14 +27,18 @@ export { type BlockReason, ReguardConfigError } from "./config.js";
27
27
  export { type EventsPage, type ReguardApiOptions, type ReguardEvent, type ReguardEventType, type VisitorStatus, ReguardApiError, ReguardWebhookError, reguardApi, verifyWebhook, } from "./api.js";
28
28
  export type { AddressesMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.js";
29
29
  /**
30
- * Adds the rewrite that serves /_s/* from Reguard, first-party, ahead of your own routes, and makes
31
- * the site id (public: it is in the script tag anyway) available to browser code as
32
- * NEXT_PUBLIC_REGUARD_SITE, so `reguardScriptProps()` works in components that also render in the
33
- * 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.
34
38
  */
35
39
  export declare function withReguard<T extends object>(config: T, options?: {
36
- collector?: string;
37
40
  key?: string;
41
+ site?: string;
38
42
  }): T;
39
43
  /** The visitor's verified verdict from a Request or NextRequest (null when there is none). */
40
44
  export declare function reguardVerdict(request: {
@@ -70,17 +74,34 @@ export interface ReguardMiddlewareOptions {
70
74
  block?: boolean | FetchBlockOptions;
71
75
  key?: string;
72
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[];
73
83
  sourceMaps?: "deny" | "allow";
74
84
  clientIp?: ClientIpOption<Request>;
85
+ timeoutMs?: number;
75
86
  debug?: boolean;
76
87
  logger?: LoggerLike | false;
77
88
  }
78
89
  /**
79
- * Next.js middleware (edge or Node runtime) that answers blocked visitors itself, like
80
- * `reguard({ block: true })` in Express: Reguard's default answer (or `block.respond`'s), with
81
- * `block.dryRun`, `block.allow` and `block.onBlock` as there. With `block` it also paces pages for
82
- * clients that don't present as a browser (each instance counts on its own) and denies source maps
83
- * (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).
84
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.
85
104
  */
86
- 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>;
@@ -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. */
@@ -53,18 +58,25 @@ export interface InitResponse {
53
58
  config: SdkConfig;
54
59
  }
55
60
  export interface SdkConfig {
56
- debuggerTrap: "main" | "worker" | "off";
61
+ /**
62
+ * The debugger trap (SDK 0.9.5+: served under /node_modules/, which Chrome DevTools ignore-lists, so
63
+ * DevTools doesn't stop there while tools that turn the Debugger on without ignore lists do).
64
+ * "worker" is read as "main". "probe" (lab) runs only the attach probe (SDK 0.9.6), to measure it alone.
65
+ */
66
+ debuggerTrap: "main" | "worker" | "off" | "probe";
57
67
  /** Period of the debugger trap; shorter catches briefer debugger attachments. */
58
68
  trapIntervalMs: number;
69
+ /** Where the trap runs: "public" (default) skips localhost, private addresses and .local/.test hosts; "all" (lab) runs anywhere. */
70
+ trapScope?: "public" | "all";
59
71
  /** Hidden display:none nodes that make DOM snapshots expensive (E tarpit). 0 disables. */
60
72
  tarpitNodes: number;
61
73
  beaconIntervalMs: number;
62
74
  /** Opt-in experimental probes (research), e.g. "ax_mutation", "jit_ratio". */
63
75
  experiments: string[];
64
76
  /**
65
- * Quiet mode (SDK 0.7+): the browser signal and event ids some rule reads. With the debugger trap
66
- * off, the SDK reports only when one of these turns up (plus refreshes a site's server asks for)
67
- * instead of every `beaconIntervalMs`. Absent: the SDK keeps the periodic heartbeat.
77
+ * Quiet mode (SDK 0.7+): the browser signal and event ids some rule reads. The SDK reports only when
78
+ * one of these turns up (plus refreshes a site's server asks for) instead of every
79
+ * `beaconIntervalMs`; from SDK 0.9.5 also with the debugger trap on. Absent: the periodic heartbeat.
68
80
  */
69
81
  news?: string[];
70
82
  }
@@ -84,7 +96,7 @@ export interface BeaconRequest {
84
96
  * neither establishes extraction. Everything else (DevTools, QA automation, assistive technology,
85
97
  * curious customers) is negative unless it meets one of these definitions.
86
98
  */
87
- export type Label = "rea" | "automated_exploration" | "unauthorized_extraction";
99
+ export type Label = "reverse_engineering" | "automated_exploration" | "unauthorized_extraction";
88
100
  /**
89
101
  * Decision outcomes. Uncertainty never becomes an accusation: without a validated alert the
90
102
  * outcome is insufficient_evidence and the session keeps being observed.
@@ -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.
@@ -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
+ }
@@ -57,8 +57,12 @@ export interface ReguardFetch {
57
57
  handle(request: Request, ctx?: {
58
58
  waitUntil?: WaitUntil;
59
59
  }): Promise<Response | undefined>;
60
- /** After your handler: queue the summary of its response. */
61
- 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?: {
62
66
  waitUntil?: WaitUntil;
63
67
  }): void;
64
68
  /** handle + your handler + record. The platform's waitUntil is found among the handler's arguments. */