reguard 0.0.0-stage → 0.7.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/next.js ADDED
@@ -0,0 +1,97 @@
1
+ import {
2
+ Allowance,
3
+ BENIGN_TOOL_FAMILIES,
4
+ BLOCK_HTML,
5
+ BLOCK_JSON,
6
+ BLOCK_RETRY_AFTER,
7
+ PACE_JSON,
8
+ PACE_RETRY_AFTER,
9
+ blockConfig,
10
+ collectAttributes,
11
+ collectorBase,
12
+ envValue,
13
+ isReguardPath,
14
+ isSpeculativeHeaders,
15
+ parseSiteKey,
16
+ readVerdictFrom,
17
+ requestKind,
18
+ resolveCollect,
19
+ toolOf,
20
+ wantsPage
21
+ } from "./chunks/chunk-W56LN2M5.js";
22
+
23
+ // src/next.ts
24
+ function withReguard(config, options = {}) {
25
+ const rule = { source: "/_s/:path*", destination: `${collectorBase(options.collector ?? envValue("REGUARD_COLLECTOR"))}/_s/:path*`, basePath: false };
26
+ const apply = (cfg) => ({
27
+ ...cfg,
28
+ async rewrites() {
29
+ const mine = cfg.rewrites ? await cfg.rewrites() : void 0;
30
+ if (!mine) return { beforeFiles: [rule], afterFiles: [], fallback: [] };
31
+ if (Array.isArray(mine)) return { beforeFiles: [rule], afterFiles: mine, fallback: [] };
32
+ return { ...mine, beforeFiles: [rule, ...mine.beforeFiles ?? []] };
33
+ }
34
+ });
35
+ if (typeof config === "function") {
36
+ const fn = config;
37
+ return (async (...args) => apply(await fn(...args)));
38
+ }
39
+ return apply(config);
40
+ }
41
+ async function reguardVerdict(request, options = {}) {
42
+ const parsed = parseSiteKey(options.key ?? envValue("REGUARD_KEY"));
43
+ if (!parsed?.site) return null;
44
+ return readVerdictFrom(parsed.secret, parsed.site, request.headers.get("cookie"));
45
+ }
46
+ var warned = false;
47
+ var warnedCollect = /* @__PURE__ */ new Set();
48
+ function reguardScriptProps(options = {}) {
49
+ const site = parseSiteKey(options.key ?? envValue("REGUARD_KEY"))?.site;
50
+ if (!site && !warned) {
51
+ warned = true;
52
+ console.warn("[reguard] REGUARD_KEY is not set (or has no site id); the script will load but not start.");
53
+ }
54
+ const collect = resolveCollect(options.collect, (m) => {
55
+ if (warnedCollect.has(m)) return;
56
+ warnedCollect.add(m);
57
+ console.warn(`[reguard] ${m}`);
58
+ });
59
+ return { src: "/_s/sdk.js", async: true, referrerPolicy: "origin", ...site ? { "data-site": site } : {}, ...collectAttributes(collect) };
60
+ }
61
+ function reguardMiddleware(options = {}) {
62
+ const block = blockConfig(options.block);
63
+ const denyMaps = (options.sourceMaps ?? (block ? "deny" : "allow")) === "deny";
64
+ const pace = block?.pace;
65
+ const pages = pace ? new Allowance(pace.documents.burst, pace.documents.perSecond / 1e3, 5e4) : void 0;
66
+ return async (request) => {
67
+ const path = new URL(request.url).pathname;
68
+ if (isReguardPath(path)) return void 0;
69
+ if (denyMaps && /\.map$/i.test(path)) return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
70
+ if (!block) return void 0;
71
+ const get = (n) => request.headers.get(n) ?? void 0;
72
+ if (pages && get("sec-fetch-dest") === void 0 && (request.method === "GET" || request.method === "HEAD")) {
73
+ const tool = toolOf(get("user-agent"));
74
+ const address = get("x-forwarded-for")?.split(",")[0]?.trim() || get("x-real-ip") || "";
75
+ if (!(tool && BENIGN_TOOL_FAMILIES.has(tool.family)) && address && requestKind(path) === "document" && !isSpeculativeHeaders(get) && !pages.take(address)) {
76
+ return new Response(PACE_JSON, { status: 429, headers: { "content-type": "application/json", "retry-after": PACE_RETRY_AFTER, "cache-control": "no-store" } });
77
+ }
78
+ }
79
+ const verdict = await reguardVerdict(request, { key: options.key });
80
+ if (!verdict?.flagged({ labels: block.labels, minStage: block.minStage })) return void 0;
81
+ const page = wantsPage((n) => request.headers.get(n));
82
+ return new Response(page ? BLOCK_HTML : BLOCK_JSON, {
83
+ status: block.status,
84
+ headers: {
85
+ "content-type": page ? "text/html; charset=utf-8" : "application/json",
86
+ "retry-after": BLOCK_RETRY_AFTER,
87
+ "cache-control": "no-store"
88
+ }
89
+ });
90
+ };
91
+ }
92
+ export {
93
+ reguardMiddleware,
94
+ reguardScriptProps,
95
+ reguardVerdict,
96
+ withReguard
97
+ };
@@ -0,0 +1,113 @@
1
+ import { type Label, type Stage, type VerdictClaim, type VerdictPayload } from "../../shared/src/index.js";
2
+ export interface Verdict extends VerdictPayload {
3
+ /**
4
+ * Whether the investigation meets a claim for one of `labels` (default: any) at `minStage` or
5
+ * above (default "candidate", i.e. including shadow claims not yet validated to a precision floor).
6
+ */
7
+ flagged(options?: {
8
+ labels?: Label[];
9
+ minStage?: Stage;
10
+ }): boolean;
11
+ }
12
+ export declare const STAGE_RANK: Record<Stage, number>;
13
+ export declare function withFlagged(p: VerdictPayload): Verdict;
14
+ /** Verify the visitor's verdict from a Cookie header. Null when absent, forged, expired or another session's. */
15
+ export declare function readVerdictFrom(secret: string, site: string, cookieHeader: string | null | undefined): Promise<Verdict | null>;
16
+ export declare const DEFAULT_COLLECTOR = "https://api.reguard.site";
17
+ /** The collector's base URL without a trailing slash or `/_s`. */
18
+ export declare function collectorBase(collector: string | undefined): string;
19
+ export declare function envValue(name: string): string | undefined;
20
+ /** The collector signs verdicts for this long (packages/server, beacon reply). */
21
+ export declare const VERDICT_TTL_MS: number;
22
+ /** `block` for reguard() and reguardMiddleware(): true (any claim) or which labels, and the status (default 429). */
23
+ export type BlockOption = boolean | {
24
+ labels?: Label[];
25
+ status?: number;
26
+ /** Least stage that blocks (default "candidate", shadow claims included). */
27
+ minStage?: Stage;
28
+ /**
29
+ * reguard() only. Routes that need a live Reguard script, e.g. ["/api/*"]: a request there
30
+ * without a fresh verdict (script blocked, cookies dropped, a lifted or stale verdict, a client
31
+ * that never ran the page) is answered like a flagged one. A page's own first calls can come
32
+ * before its script reports, so each tagged page a visitor is served opens a short grace.
33
+ * Leave out routes your integrations call with API keys.
34
+ */
35
+ require?: string[];
36
+ /** How old a verdict may be on `require` routes (default 60 s; open pages refresh it every few seconds). */
37
+ requireMaxAgeMs?: number;
38
+ /** Grace after each tagged page (default 15 s) and calls allowed in it (default 30). */
39
+ requireGraceMs?: number;
40
+ requireGraceRequests?: number;
41
+ /**
42
+ * Pages in a row a visitor may load without its script ever reporting before pages stop
43
+ * opening a grace (default 3): a browser that blocks the script can't ride page loads forever.
44
+ */
45
+ requireGracePages?: number;
46
+ /**
47
+ * Calls a `require` route still answers for a verified verdict that has aged past
48
+ * `requireMaxAgeMs` (an open page coming back from idle fires its calls at once while its
49
+ * script refreshes): once per verdict, this many calls (default 30, a page's first burst)
50
+ * within this long (default 10 s). A lifted cookie gets these once.
51
+ */
52
+ requireRefreshRequests?: number;
53
+ requireRefreshMs?: number;
54
+ /**
55
+ * Slow down whoever goes faster than a person (default on; `false` turns it off), each limit a
56
+ * burst then a steady rate:
57
+ * - pages and not-found answers, per address, for clients that don't present as a browser
58
+ * (browsers send Sec-Fetch headers; site copiers, crawlers, fuzzers and scripts don't), so
59
+ * people sharing an office or carrier address are never slowed;
60
+ * - API calls on `require` routes, per page session.
61
+ * Over a limit, the request gets 429 with a short Retry-After (not the block page), and Reguard
62
+ * hears about it at once. Raise `api` for apps that poll a lot. Search engine crawlers and uptime
63
+ * monitors are not paced. On the edge (Next.js middleware) each instance keeps its own count.
64
+ */
65
+ pace?: false | Partial<PaceConfig>;
66
+ };
67
+ /** A burst, then a steady rate per second. */
68
+ export interface PaceRate {
69
+ burst: number;
70
+ perSecond: number;
71
+ }
72
+ export interface PaceConfig {
73
+ /** Pages from clients that don't present as a browser, per address (default 30, then 1 a second). */
74
+ documents: PaceRate;
75
+ /** API calls on `require` routes, per page session (default 60, then 5 a second). */
76
+ api: PaceRate;
77
+ /** Not-found answers to clients that don't present as a browser, per address (default 20, then 1 every 2 s). */
78
+ notFound: PaceRate;
79
+ }
80
+ export declare const DEFAULT_PACE: PaceConfig;
81
+ export interface BlockConfig {
82
+ labels?: Label[];
83
+ status: number;
84
+ minStage: Stage;
85
+ require?: string[];
86
+ maxAgeMs: number;
87
+ graceMs: number;
88
+ graceRequests: number;
89
+ gracePages: number;
90
+ refreshRequests: number;
91
+ refreshMs: number;
92
+ pace: PaceConfig | null;
93
+ }
94
+ export declare function blockConfig(block: BlockOption | undefined): BlockConfig | null;
95
+ /** Seconds the script tag asks the browser to keep its verdict fresh on `require` sites (half the allowed age). */
96
+ export declare function freshSeconds(cfg: BlockConfig | null): number | undefined;
97
+ /** Retry-After for a request slowed down by pace, in seconds. */
98
+ export declare const PACE_RETRY_AFTER = "2";
99
+ export declare const PACE_JSON: string;
100
+ /** How long ago the collector issued a verified verdict. */
101
+ export declare function verdictAgeMs(v: {
102
+ exp: number;
103
+ }, now?: number): number;
104
+ /** Claims the collector sent back to a site's server (no token: they arrived over its authenticated channel). */
105
+ export declare function pushedVerdict(sid: string, site: string, claims: VerdictClaim[]): Verdict;
106
+ /** Retry-After for blocked visitors, in seconds. */
107
+ export declare const BLOCK_RETRY_AFTER = "120";
108
+ export declare const BLOCK_HTML: string;
109
+ export declare const BLOCK_JSON: string;
110
+ /** A page load gets the short HTML page; anything else (API calls, assets) gets JSON. */
111
+ export declare function wantsPage(get: (name: string) => string | null | undefined): boolean;
112
+ /** Reguard's own paths (the script and its reports) are never blocked. */
113
+ export declare function isReguardPath(path: string): boolean;
@@ -0,0 +1,123 @@
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";
6
+ export { formatSiteKey, parseSiteKey, type ParsedSiteKey } from "../../shared/src/index.js";
7
+ declare global {
8
+ namespace Express {
9
+ interface Request {
10
+ reguard?: Verdict | null;
11
+ reDetect?: Verdict | null;
12
+ }
13
+ }
14
+ }
15
+ export interface ReguardOptions {
16
+ /** Your site key (`rgk.…`, from the dashboard). Default: process.env.REGUARD_KEY. */
17
+ key?: string;
18
+ /** Where Reguard answers. Default: process.env.REGUARD_COLLECTOR or https://api.reguard.site. */
19
+ collector?: string;
20
+ /** Add the script tag to HTML pages. Default true. */
21
+ inject?: boolean;
22
+ /**
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.
26
+ */
27
+ block?: BlockOption;
28
+ /** Send request summaries to Reguard. Default true. (`collect.requests: false` does the same.) */
29
+ forward?: boolean;
30
+ /**
31
+ * 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.
34
+ */
35
+ sourceMaps?: "deny" | "allow";
36
+ /** Paths never summarized (e.g. health checks). */
37
+ ignore?: (path: string) => boolean;
38
+ /**
39
+ * 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/*"].
48
+ */
49
+ collect?: CollectOptions;
50
+ /**
51
+ * Summarize cookieless requests worth watching (scanners, crawlers, site copiers, scripts, scanner
52
+ * paths, source maps, not-found answers). Default true. Addresses are sent only as a keyed hash.
53
+ */
54
+ watchSessionless?: boolean;
55
+ /** Advanced: custom fetch, error hook, summary flush interval. */
56
+ fetch?: typeof fetch;
57
+ onError?: (error: unknown) => void;
58
+ flushIntervalMs?: number;
59
+ }
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
+ type Next = (err?: unknown) => void;
68
+ export interface ReguardMiddleware {
69
+ (req: IncomingMessage, res: ServerResponse, next: Next): void;
70
+ /** The site id read from the key (undefined when no key is configured). */
71
+ readonly site: string | undefined;
72
+ /** Send queued summaries now. */
73
+ flush(): Promise<void>;
74
+ /** Stop the summary timer and send what's queued (e.g. on shutdown). */
75
+ close(): Promise<void>;
76
+ }
77
+ /** Express/Connect middleware: `app.use(reguard())`. */
78
+ export declare function reguard(options?: ReguardOptions): ReguardMiddleware;
79
+ export default reguard;
80
+ export interface ReDetectServerOptions {
81
+ /** The site's public id. */
82
+ site: string;
83
+ /** The site's key: the `rgk.…` key or, for sites set up before v0.4, the bare secret. Server-side only. */
84
+ siteKey: string;
85
+ /** The collector's base URL including its prefix, e.g. "https://api.reguard.site/_s". */
86
+ collector: string;
87
+ /** First-party path the browser SDK uses on this origin (default "/_s"). */
88
+ prefix?: string;
89
+ /** Send request summaries to the collector (default true). */
90
+ forward?: boolean;
91
+ /** Also describe every request that carries no SDK session (default false). */
92
+ includeSessionless?: boolean;
93
+ /**
94
+ * Describe cookieless requests worth watching (default true): scanners, crawlers, site copiers,
95
+ * HTTP libraries and clients that only pretend to be browsers, scanner paths, source maps and
96
+ * not-found answers. Tools that never run the page never get a session; Reguard groups these per
97
+ * visitor through a keyed hash of the address (the address itself never leaves this process).
98
+ */
99
+ watchSessionless?: boolean;
100
+ /** Paths never described, e.g. health checks. */
101
+ ignore?: (path: string) => boolean;
102
+ /** What Reguard receives (see ReguardOptions.collect). */
103
+ collect?: CollectOptions;
104
+ flushIntervalMs?: number;
105
+ maxQueue?: number;
106
+ fetch?: typeof fetch;
107
+ onError?: (error: unknown) => void;
108
+ }
109
+ export declare function createReDetect(opts: ReDetectServerOptions): {
110
+ middleware: () => (req: ReguardRequest, res: ServerResponse, next: Next) => void;
111
+ route: () => (req: ReguardRequest, res: ServerResponse) => Promise<void>;
112
+ track: (req: ReguardRequest, res: ServerResponse) => void;
113
+ readVerdict: (cookieHeader: string | null | undefined) => Promise<Verdict | null>;
114
+ /** Claims the collector pushed back for this request's session or visitor (null: none). */
115
+ pushedFor: (req: IncomingMessage, verified?: boolean) => Verdict | null;
116
+ /** For fetch-style handlers (Next.js route handlers, edge functions): pass `request.headers`. */
117
+ readVerdictFromHeaders: (headers: {
118
+ get(name: string): string | null;
119
+ }) => Promise<Verdict | null>;
120
+ /** Send queued summaries now (e.g. before shutdown). */
121
+ flush: () => Promise<void>;
122
+ close: () => Promise<void>;
123
+ };
@@ -0,0 +1,72 @@
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.
4
+ *
5
+ * // next.config.js
6
+ * import { withReguard } from "reguard/next";
7
+ * export default withReguard({ ...yourConfig });
8
+ *
9
+ * // app/layout.tsx
10
+ * import Script from "next/script";
11
+ * import { reguardScriptProps } from "reguard/next";
12
+ * <Script {...reguardScriptProps()} />
13
+ * // what Reguard receives: reguardScriptProps({ collect: { pages: "hashed", skip: ["/account/*"] } })
14
+ *
15
+ * // anywhere on the server: route handler, server action, middleware
16
+ * const verdict = await reguardVerdict(request);
17
+ *
18
+ * // middleware.ts: answer flagged visitors with 429, like reguard({ block: true }) in Express
19
+ * export const middleware = reguardMiddleware({ block: true });
20
+ */
21
+ 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";
24
+ export type { AddressesMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.js";
25
+ /**
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
+ */
30
+ export declare function withReguard<T extends object>(config: T, options?: {
31
+ collector?: string;
32
+ }): T;
33
+ /** The visitor's verified verdict from a Request or NextRequest (null when there is none). */
34
+ export declare function reguardVerdict(request: {
35
+ headers: {
36
+ get(name: string): string | null;
37
+ };
38
+ }, options?: {
39
+ key?: string;
40
+ }): Promise<Verdict | null>;
41
+ export type ReguardScriptProps = {
42
+ src: string;
43
+ async: true;
44
+ referrerPolicy: "origin";
45
+ } & {
46
+ [attr: `data-${string}`]: string;
47
+ };
48
+ /**
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.
53
+ */
54
+ export declare function reguardScriptProps(options?: {
55
+ key?: string;
56
+ collect?: Omit<CollectOptions, "requests">;
57
+ }): 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;
70
+ key?: string;
71
+ sourceMaps?: "deny" | "allow";
72
+ }): (request: Request) => Promise<Response | undefined>;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Token buckets, one per key: `take` answers whether this use still fits. Runtime-neutral (a Map and
3
+ * numbers), so the collector's usage metering and the middleware's pace limits share it, on Node and
4
+ * on the edge. Memory stays bounded: past `maxKeys`, the least recently used key is forgotten (it
5
+ * starts full again if it returns).
6
+ */
7
+ export declare class Allowance {
8
+ private readonly capacity;
9
+ private readonly refillPerMs;
10
+ private readonly maxKeys;
11
+ private readonly buckets;
12
+ constructor(capacity: number, refillPerMs: number, maxKeys?: number);
13
+ take(key: string, now?: number): boolean;
14
+ /** Whether `take` would succeed now, without using anything. */
15
+ has(key: string, now?: number): boolean;
16
+ private refill;
17
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * What a site lets Reguard receive: `collect` in reguard, in the SDK's `init()` and in the
3
+ * script tag's data-* attributes. Every setting has a default; a value that isn't understood falls
4
+ * back to its default with one warning, and nothing here ever throws into the host app.
5
+ */
6
+ export type PagesMode = "masked" | "hashed" | "off";
7
+ export type AddressesMode = "hashed" | "off";
8
+ export interface CollectOptions {
9
+ /**
10
+ * Page and API addresses. "masked" (default): ids, emails and long tokens are replaced before
11
+ * anything leaves. "hashed": only a keyed hash of each address and the kind of request. "off":
12
+ * only the kind of request.
13
+ */
14
+ pages?: PagesMode;
15
+ /** Visitor addresses. "hashed" (default): only as a keyed hash. "off": Reguard keeps none. */
16
+ addresses?: AddressesMode;
17
+ /** Click, key, scroll and pointer timings from the browser. Default true. */
18
+ behavior?: boolean;
19
+ /** Request summaries from your server (reguard only). Default true. */
20
+ requests?: boolean;
21
+ /** Pages Reguard never runs on or reports. `*` matches anything; "/account/*" also covers "/account". */
22
+ skip?: string[];
23
+ }
24
+ export interface CollectSettings {
25
+ pages: PagesMode;
26
+ addresses: AddressesMode;
27
+ behavior: boolean;
28
+ requests: boolean;
29
+ skip: string[];
30
+ }
31
+ /** The site's choices as the browser and the site's server report them, so reviewers know what was withheld. */
32
+ export interface CollectReport {
33
+ pages: PagesMode;
34
+ addresses: AddressesMode;
35
+ behavior: boolean;
36
+ }
37
+ export declare const DEFAULT_COLLECT: Readonly<CollectSettings>;
38
+ /**
39
+ * The settings `input` asks for. Anything unrecognized is reported through `warn` and replaced by its
40
+ * default; unknown fields are ignored. `skip` takes an array or a comma-separated string.
41
+ */
42
+ export declare function resolveCollect(input: unknown, warn?: (message: string) => void): CollectSettings;
43
+ /**
44
+ * A matcher for skip patterns: `*` matches any characters (slashes included), and a pattern ending in
45
+ * "/*" also matches the path without it ("/account/*" covers "/account"). Query and fragment are ignored.
46
+ */
47
+ export declare function skipMatcher(patterns: readonly string[]): (path: string) => boolean;
48
+ /** The script tag's data-* attributes for the settings that differ from the defaults. */
49
+ export declare function collectAttributes(c: CollectSettings): Record<string, string>;
50
+ export declare function collectReport(c: CollectSettings): CollectReport;
51
+ /** A report from the wire, kept only if every field is one of the known values. */
52
+ export declare function parseCollectReport(v: unknown): CollectReport | undefined;
@@ -0,0 +1,69 @@
1
+ /**
2
+ * What the server side may learn about one request/response without keeping its values. Shared by
3
+ * the collector (when it proxies a site) and by reguard (inside a site's own server), so
4
+ * raw parameter and body values never leave the process that saw them: each value is reduced to a
5
+ * keyed hash (to count distinct values), a coarse shape, and a few probe flags.
6
+ *
7
+ * Whether a flagged value counts as probing is decided later, against what that parameter normally
8
+ * receives on that site (by Reguard's collector): an injection string in a parameter that always
9
+ * carries ids is a probe; the same string in a chat message on a site about coding is not.
10
+ */
11
+ export type Shape = "empty" | "int" | "decimal" | "bool" | "uuid" | "hex" | "slug" | "word" | "email" | "text" | "json";
12
+ export type Boundary = "neg" | "zero" | "overflow";
13
+ export interface ParamDescription {
14
+ /** Keyed hash of name=value (per site): equal values hash equally, nothing else is recoverable. */
15
+ h: string;
16
+ shape: Shape;
17
+ /** The value carries an injection, traversal, template or markup marker. */
18
+ strong?: true;
19
+ /** Integer-shaped boundary value: negative, zero, or overflow-sized. */
20
+ boundary?: Boundary;
21
+ }
22
+ export interface ExchangeDescription {
23
+ method: string;
24
+ /** Path with ids normalized (`/api/rounds/123/turn` → `/api/rounds/:n/turn`). */
25
+ endpoint: string;
26
+ /** Keyed hash of the raw path: distinct items fetched, even when endpoints normalize to one. */
27
+ item?: string;
28
+ /** Query parameters and top-level body fields. */
29
+ params: Record<string, ParamDescription>;
30
+ requestBytes: number;
31
+ status: number;
32
+ responseBytes: number;
33
+ /** Length of the top-level JSON array in the response (or of its first array field). */
34
+ listLength: number | null;
35
+ /** Pagination parameter (page/offset/cursor/after/skip) present and numeric. */
36
+ pageValue: number | null;
37
+ }
38
+ /**
39
+ * Framework cache-busters and routing parameters: unique on every request by design (Next.js
40
+ * `_rsc`, jQuery `_`, generic `cb`/`ts`/`v`), so their values say nothing about the visitor.
41
+ */
42
+ export declare const IGNORED_PARAMS: Set<string>;
43
+ /** Path with id-like segments masked: numbers, UUIDs, hex, emails, long opaque tokens. */
44
+ export declare function normalizeEndpoint(path: string): string;
45
+ /** A URL as it may leave a site's server: masked path, parameter names, no values. */
46
+ export declare function privateUrl(url: string): string;
47
+ export declare function shapeOf(v: string): Shape;
48
+ export declare function strongMarker(v: string): boolean;
49
+ export declare function boundaryOf(v: string): Boundary | undefined;
50
+ export interface ExchangeInput {
51
+ method: string;
52
+ /** Path and query, as requested. */
53
+ url: string;
54
+ requestContentType?: string;
55
+ /** Request body as text (first 64 KB is plenty); empty when there is none. */
56
+ requestBody?: string;
57
+ requestBytes: number;
58
+ status: number;
59
+ responseContentType?: string;
60
+ /** First bytes of the response as text, for its list length only; never stored. */
61
+ responseHead?: string;
62
+ responseBytes: number;
63
+ }
64
+ /** `hash(name=value)` must be a keyed hash (HMAC with a per-site key). */
65
+ export declare function describeExchange(hash: (s: string) => string, x: ExchangeInput): ExchangeDescription;
66
+ /** Requests worth describing: APIs, RSC payloads, JSON, form posts. Pages and assets are counted elsewhere. */
67
+ export declare function isApiLike(url: string, responseContentType: string, requestBytes: number): boolean;
68
+ /** Requests the browser or framework issued on speculation (router prefetch, prerender), not the visitor. */
69
+ export declare function isSpeculativeHeaders(get: (name: string) => string | undefined): boolean;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Wire contract between the SDK (packages/sdk), the server package (packages/node) and Reguard's
3
+ * collector and detection model. Probe ids are stable strings; renaming one is a breaking change
4
+ * for stored datasets, so add new ids instead.
5
+ */
6
+ export declare const WIRE_VERSION = 1;
7
+ /** Timestamped observation recorded by a probe (ms since page time origin). */
8
+ export interface ProbeEvent {
9
+ /** Probe id, e.g. "a3.gap" or "b.mark_target". */
10
+ id: string;
11
+ t: number;
12
+ data?: Record<string, unknown>;
13
+ }
14
+ /** Cumulative, last-write-wins measurements (the SDK resends the full map each beacon). */
15
+ export type Signals = Record<string, unknown>;
16
+ export interface InitRequest {
17
+ v: number;
18
+ site: string;
19
+ /** This browser's previous session id (the `_s` cookie), for linking reloads when the cookie can't travel (cross-origin script). */
20
+ prev?: string;
21
+ /** SDK version (packages/sdk/package.json). */
22
+ sdk?: string;
23
+ /** Verification-run id from the `lab_run` query parameter; the hosted collector ignores it. */
24
+ labRun?: string;
25
+ /**
26
+ * The page's path, masked before it leaves the browser (ids, emails and long tokens replaced);
27
+ * absent when the site keeps its page addresses to itself (`collect.pages` "hashed" or "off").
28
+ */
29
+ path?: string;
30
+ deviceId: string;
31
+ /** The site's data choices (SDK 0.6+), so the collector honours them and reviewers see them. */
32
+ collect?: CollectReport;
33
+ }
34
+ export interface InitResponse {
35
+ sid: string;
36
+ token: string;
37
+ /** Canary token used for the first-party source-map tripwire (F1). */
38
+ canary: string;
39
+ /** First-party prefix the collector is reachable at on this origin, e.g. "/_s". */
40
+ prefix: string;
41
+ config: SdkConfig;
42
+ }
43
+ export interface SdkConfig {
44
+ debuggerTrap: "main" | "worker" | "off";
45
+ /** Period of the debugger trap; shorter catches briefer debugger attachments. */
46
+ trapIntervalMs: number;
47
+ /** Hidden display:none nodes that make DOM snapshots expensive (E tarpit). 0 disables. */
48
+ tarpitNodes: number;
49
+ beaconIntervalMs: number;
50
+ /** Opt-in experimental probes (research), e.g. "ax_mutation", "jit_ratio". */
51
+ experiments: string[];
52
+ /**
53
+ * Quiet mode (SDK 0.7+): the browser signal and event ids some rule reads. With the debugger trap
54
+ * off, the SDK reports only when one of these turns up (plus refreshes a site's server asks for)
55
+ * instead of every `beaconIntervalMs`. Absent: the SDK keeps the periodic heartbeat.
56
+ */
57
+ news?: string[];
58
+ }
59
+ export interface BeaconRequest {
60
+ v: number;
61
+ sid: string;
62
+ token: string;
63
+ seq: number;
64
+ /** ms since page time origin when the beacon was built. */
65
+ t: number;
66
+ signals: Signals;
67
+ events: ProbeEvent[];
68
+ final?: boolean;
69
+ }
70
+ /**
71
+ * Positive labels are kept separate: detecting automation does not establish REA usage, and
72
+ * neither establishes extraction. Everything else (DevTools, QA automation, assistive technology,
73
+ * curious customers) is negative unless it meets one of these definitions.
74
+ */
75
+ export type Label = "rea" | "automated_exploration" | "unauthorized_extraction";
76
+ /**
77
+ * Decision outcomes. Uncertainty never becomes an accusation: without a validated alert the
78
+ * outcome is insufficient_evidence and the session keeps being observed.
79
+ */
80
+ export type Outcome = "insufficient_evidence" | "review" | "restrict";
81
+ /**
82
+ * What the page learns after each beacon. Rule internals and evidence stay server-side, where
83
+ * reviewers see them; `token` is the signed form the site's own server verifies (packages/node).
84
+ */
85
+ export interface Verdict {
86
+ sid: string;
87
+ outcome: Outcome;
88
+ /** Claims the investigation currently meets, shadow (`candidate`) ones included. */
89
+ claims?: VerdictClaim[];
90
+ token?: string;
91
+ }
92
+ export * from "./exchange.js";
93
+ export * from "./verdict.js";
94
+ export * from "./keys.js";
95
+ export * from "./tools.js";
96
+ export * from "./collect.js";
97
+ export * from "./allowance.js";
98
+ import type { VerdictClaim } from "./verdict.js";
99
+ import type { CollectReport } from "./collect.js";
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Customer site keys: `rgk.<siteId>.v<version>.<secret>`. One value to configure (REGUARD_KEY):
3
+ * the site id and key version are readable from it, the secret part is what verifies verdicts and
4
+ * authenticates request summaries. Bare secrets (the format before v0.4) still parse, without a site.
5
+ */
6
+ export interface ParsedSiteKey {
7
+ site?: string;
8
+ version?: number;
9
+ secret: string;
10
+ }
11
+ export declare const SITE_KEY_PREFIX = "rgk";
12
+ export declare function formatSiteKey(site: string, version: number, secret: string): string;
13
+ export declare function parseSiteKey(key: string | null | undefined): ParsedSiteKey | null;