reguard 0.7.1 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -31
- package/dist/chunks/chunk-3AYS7WSY.js +350 -0
- package/dist/chunks/chunk-KNKCUJL3.js +969 -0
- package/dist/chunks/{chunk-W56LN2M5.js → chunk-PA46KSOR.js} +385 -33
- package/dist/chunks/chunk-U54IP6G4.js +448 -0
- package/dist/cjs/fastify.cjs +2109 -0
- package/dist/cjs/fetch.cjs +1463 -0
- package/dist/cjs/index.cjs +2074 -0
- package/dist/cjs/next.cjs +1535 -0
- package/dist/cjs/testing.cjs +214 -0
- package/dist/fastify.js +59 -0
- package/dist/fetch.js +13 -0
- package/dist/index.js +15 -716
- package/dist/next.js +48 -52
- package/dist/testing.js +39 -0
- package/dist/types/node/src/config.d.ts +107 -0
- package/dist/types/node/src/core.d.ts +66 -72
- package/dist/types/node/src/fastify.d.ts +41 -0
- package/dist/types/node/src/fetch.d.ts +76 -0
- package/dist/types/node/src/health.d.ts +41 -0
- package/dist/types/node/src/index.d.ts +114 -34
- package/dist/types/node/src/next.d.ts +40 -27
- package/dist/types/node/src/testing.d.ts +25 -0
- package/dist/types/shared/src/address.d.ts +81 -0
- package/dist/types/shared/src/index.d.ts +6 -0
- package/dist/types/shared/src/paths.d.ts +32 -0
- package/dist/types-cjs/node/src/config.d.cts +107 -0
- package/dist/types-cjs/node/src/core.d.cts +107 -0
- package/dist/types-cjs/node/src/fastify.d.cts +41 -0
- package/dist/types-cjs/node/src/fetch.d.cts +76 -0
- package/dist/types-cjs/node/src/health.d.cts +41 -0
- package/dist/types-cjs/node/src/index.d.cts +203 -0
- package/dist/types-cjs/node/src/next.d.cts +85 -0
- package/dist/types-cjs/node/src/testing.d.cts +25 -0
- package/dist/types-cjs/shared/src/address.d.cts +81 -0
- package/dist/types-cjs/shared/src/allowance.d.cts +17 -0
- package/dist/types-cjs/shared/src/collect.d.cts +52 -0
- package/dist/types-cjs/shared/src/exchange.d.cts +69 -0
- package/dist/types-cjs/shared/src/index.d.cts +105 -0
- package/dist/types-cjs/shared/src/keys.d.cts +13 -0
- package/dist/types-cjs/shared/src/paths.d.cts +32 -0
- package/dist/types-cjs/shared/src/tools.d.cts +101 -0
- package/dist/types-cjs/shared/src/verdict.d.cts +37 -0
- package/package.json +73 -10
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { type CollectSettings, type Label, type Stage, type VerdictClaim, type VerdictPayload } from "../../shared/src/index.cjs";
|
|
2
|
+
import type { BlockConfig, BlockReason } from "./config.cjs";
|
|
3
|
+
/** Where a verdict's claims came from: the visitor's browser (a signed cookie), your server's summaries, or both. */
|
|
4
|
+
export type VerdictSource = "browser" | "server" | "both";
|
|
5
|
+
export interface Verdict extends VerdictPayload {
|
|
6
|
+
/** Where the claims came from. */
|
|
7
|
+
source: VerdictSource;
|
|
8
|
+
/**
|
|
9
|
+
* Whether there is a claim for one of `labels` (default: any) at `minStage` or above (default
|
|
10
|
+
* "candidate", i.e. including rules still on trial).
|
|
11
|
+
*/
|
|
12
|
+
flagged(options?: {
|
|
13
|
+
labels?: readonly Label[] | Label;
|
|
14
|
+
minStage?: Stage;
|
|
15
|
+
}): boolean;
|
|
16
|
+
}
|
|
17
|
+
export declare const STAGE_RANK: Record<Stage, number>;
|
|
18
|
+
export declare function withFlagged(p: VerdictPayload, source?: VerdictSource): Verdict;
|
|
19
|
+
/** A browser verdict with claims the collector pushed to your server added (deduplicated by rule). */
|
|
20
|
+
export declare function mergeVerdicts(browser: Verdict | null, pushed: Verdict | null): Verdict | null;
|
|
21
|
+
/** Verify the visitor's verdict from a Cookie header. Null when absent, forged, expired or another session's. */
|
|
22
|
+
export declare function readVerdictFrom(secret: string, site: string, cookieHeader: string | null | undefined): Promise<Verdict | null>;
|
|
23
|
+
/**
|
|
24
|
+
* Whether a verdict cookie that didn't verify looks current (right site, this session, not expired):
|
|
25
|
+
* then its signature is what failed, which means a wrong or rotated key, not a stale cookie.
|
|
26
|
+
*/
|
|
27
|
+
export declare function looksCurrent(site: string, cookieHeader: string | null | undefined, now?: number): boolean;
|
|
28
|
+
export declare const DEFAULT_COLLECTOR = "https://api.reguard.site";
|
|
29
|
+
/** The collector's base URL without a trailing slash or `/_s`. */
|
|
30
|
+
export declare function collectorBase(collector: string | undefined): string;
|
|
31
|
+
export declare function envValue(name: string): string | undefined;
|
|
32
|
+
/** The collector signs verdicts for this long. */
|
|
33
|
+
export declare const VERDICT_TTL_MS: number;
|
|
34
|
+
/** A burst, then a steady rate per second. */
|
|
35
|
+
export interface PaceRate {
|
|
36
|
+
burst: number;
|
|
37
|
+
perSecond: number;
|
|
38
|
+
}
|
|
39
|
+
export interface PaceConfig {
|
|
40
|
+
/** Pages from clients that don't present as a browser, per address (default 30, then 1 a second). */
|
|
41
|
+
documents: PaceRate;
|
|
42
|
+
/** API calls on `require` routes, per page session (default 60, then 5 a second). */
|
|
43
|
+
api: PaceRate;
|
|
44
|
+
/** Not-found answers to clients that don't present as a browser, per address (default 20, then 1 every 2 s). */
|
|
45
|
+
notFound: PaceRate;
|
|
46
|
+
}
|
|
47
|
+
export declare const DEFAULT_PACE: PaceConfig;
|
|
48
|
+
/** Seconds the script tag asks the browser to keep its verdict fresh on `require` sites (half the allowed age). */
|
|
49
|
+
export declare function freshSeconds(cfg: BlockConfig | null): number | undefined;
|
|
50
|
+
/** How long ago the collector issued a verified verdict. */
|
|
51
|
+
export declare function verdictAgeMs(v: {
|
|
52
|
+
exp: number;
|
|
53
|
+
}, now?: number): number;
|
|
54
|
+
/** Claims the collector sent back to a site's server (no token: they arrived over its authenticated channel). */
|
|
55
|
+
export declare function pushedVerdict(sid: string, site: string, claims: VerdictClaim[], now?: number): Verdict;
|
|
56
|
+
/** Which limit a paced request went over. */
|
|
57
|
+
export type PaceKind = "document" | "api" | "notfound";
|
|
58
|
+
/** Why Reguard answered for the app (or, in a dry run, would have). */
|
|
59
|
+
export interface Decision {
|
|
60
|
+
reason: BlockReason;
|
|
61
|
+
/** True when this was only reported (block.dryRun): the app answered. */
|
|
62
|
+
dryRun: boolean;
|
|
63
|
+
/** The status Reguard answers (or would answer) with. */
|
|
64
|
+
status: number;
|
|
65
|
+
/** Retry-After, in seconds. */
|
|
66
|
+
retryAfter: number;
|
|
67
|
+
/** For reason "pace": which limit. */
|
|
68
|
+
pace?: PaceKind;
|
|
69
|
+
/** The claims behind it (empty for require and pace). */
|
|
70
|
+
claims: VerdictClaim[];
|
|
71
|
+
verdict: Verdict | null;
|
|
72
|
+
/** The request path (decoded). */
|
|
73
|
+
path: string;
|
|
74
|
+
/** The visitor's address as resolved (see clientIp). */
|
|
75
|
+
clientIp: string;
|
|
76
|
+
}
|
|
77
|
+
export declare const ANSWER_CODES: Record<BlockReason, string>;
|
|
78
|
+
export declare const RETRY_AFTER: Record<BlockReason, number>;
|
|
79
|
+
export declare const BLOCK_HTML: string;
|
|
80
|
+
export declare const REQUIRE_HTML: string;
|
|
81
|
+
export declare const PACE_TEXT = "Too many requests. Slow down and try again in a moment.";
|
|
82
|
+
/** The default answer for a decision: an HTML page for page loads, JSON with a stable `code` otherwise. */
|
|
83
|
+
export declare function defaultAnswer(reason: BlockReason, wantsHtml: boolean): {
|
|
84
|
+
contentType: string;
|
|
85
|
+
body: string;
|
|
86
|
+
};
|
|
87
|
+
/** A page load gets the short HTML page; anything else (API calls, assets) gets JSON. */
|
|
88
|
+
export declare function wantsPage(get: (name: string) => string | null | undefined): boolean;
|
|
89
|
+
/** Reguard's own paths (the script and its reports) are never blocked. */
|
|
90
|
+
export declare function isReguardPath(path: string): boolean;
|
|
91
|
+
/** A CORS preflight: never carries cookies, so `require` can't judge it (and never needs to). */
|
|
92
|
+
export declare function isPreflight(method: string | undefined, get: (name: string) => string | null | undefined): boolean;
|
|
93
|
+
export interface TagSettings {
|
|
94
|
+
site: string;
|
|
95
|
+
collect: CollectSettings;
|
|
96
|
+
/** block.require: seconds between refreshes while the page calls the site's API. */
|
|
97
|
+
fresh?: number;
|
|
98
|
+
cookieDomain?: string;
|
|
99
|
+
prefix?: string;
|
|
100
|
+
}
|
|
101
|
+
/** The tag for a page: the site, data choices that differ from the defaults, freshness, cookie domain and a CSP nonce. */
|
|
102
|
+
export declare function renderScriptTag(t: TagSettings, nonce?: string): string;
|
|
103
|
+
/**
|
|
104
|
+
* The nonce a page's Content-Security-Policy allows scripts with ('nonce-…' in script-src, or in
|
|
105
|
+
* default-src when there is no script-src); undefined when it doesn't use one.
|
|
106
|
+
*/
|
|
107
|
+
export declare function cspNonce(csp: string | undefined | null): string | undefined;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* reguard/fastify: Reguard as a Fastify plugin (Fastify 4 and 5). Everything reguard() does: /_s/*
|
|
3
|
+
* served first-party, the tag added to HTML pages, `request.reguard`, blocking and summaries.
|
|
4
|
+
*
|
|
5
|
+
* import Fastify from "fastify";
|
|
6
|
+
* import reguard from "reguard/fastify";
|
|
7
|
+
*
|
|
8
|
+
* const app = Fastify({ trustProxy: true }); // then Reguard uses Fastify's request.ip
|
|
9
|
+
* await app.register(reguard, { block: { dryRun: true } });
|
|
10
|
+
* app.get("/api/items", async (request) => (request.reguard?.flagged() ? [] : items));
|
|
11
|
+
*
|
|
12
|
+
* No dependency on fastify itself: the plugin is marked like fastify-plugin does, so its request
|
|
13
|
+
* decorations apply app-wide.
|
|
14
|
+
*/
|
|
15
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
16
|
+
import type { Decision, Verdict } from "./core.cjs";
|
|
17
|
+
import { type ReguardOptions } from "./index.cjs";
|
|
18
|
+
export type { Decision, Verdict } from "./core.cjs";
|
|
19
|
+
export { ReguardConfigError } from "./config.cjs";
|
|
20
|
+
interface FastifyRequestLike {
|
|
21
|
+
raw: IncomingMessage;
|
|
22
|
+
ip?: string;
|
|
23
|
+
reguard?: Verdict | null;
|
|
24
|
+
reguardDecision?: Decision | null;
|
|
25
|
+
}
|
|
26
|
+
interface FastifyReplyLike {
|
|
27
|
+
raw: ServerResponse;
|
|
28
|
+
hijack(): unknown;
|
|
29
|
+
}
|
|
30
|
+
interface FastifyLike {
|
|
31
|
+
addHook(name: "onRequest", hook: (request: FastifyRequestLike, reply: FastifyReplyLike, done: (err?: Error) => void) => void): unknown;
|
|
32
|
+
addHook(name: "onClose", hook: (instance: unknown, done: () => void) => void): unknown;
|
|
33
|
+
decorateRequest?(name: string, value: unknown): unknown;
|
|
34
|
+
hasRequestDecorator?(name: string): boolean;
|
|
35
|
+
initialConfig?: {
|
|
36
|
+
trustProxy?: unknown;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
declare function plugin(fastify: FastifyLike, options: ReguardOptions, done: (err?: Error) => void): void;
|
|
40
|
+
export declare const reguardFastify: typeof plugin;
|
|
41
|
+
export default plugin;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* reguard/fetch: Reguard for fetch-style servers (Request in, Response out): Hono, Remix, SvelteKit,
|
|
3
|
+
* Astro, Bun, Deno, Cloudflare Workers, Vercel and Netlify functions. Runtime-neutral (Web Crypto,
|
|
4
|
+
* no node: imports).
|
|
5
|
+
*
|
|
6
|
+
* import { reguardFetch } from "reguard/fetch";
|
|
7
|
+
* const rg = reguardFetch({ block: true }); // reads REGUARD_KEY
|
|
8
|
+
* export default { fetch: rg.wrap(app.fetch) }; // Workers, Bun, Deno, Hono
|
|
9
|
+
*
|
|
10
|
+
* `wrap(handler)` serves /_s/* (the script and its reports) from Reguard, answers blocked visitors,
|
|
11
|
+
* runs your handler for everyone else and queues a summary of each response (sent through the
|
|
12
|
+
* platform's `waitUntil` when it has one). Inside your handler, `rg.verdict(request)` is the
|
|
13
|
+
* visitor's verdict. Add the script tag to your pages with `rg.scriptTag()`; it isn't added for you
|
|
14
|
+
* here. Not available on these runtimes: `block.require` (it needs one long-lived process).
|
|
15
|
+
*/
|
|
16
|
+
import { type CollectOptions, type Platform } from "../../shared/src/index.cjs";
|
|
17
|
+
import { type BlockBase, type ClientIpOption, type LoggerLike } from "./config.cjs";
|
|
18
|
+
import { type Decision, type Verdict } from "./core.cjs";
|
|
19
|
+
export type { Decision, Verdict, VerdictSource } from "./core.cjs";
|
|
20
|
+
export { type BlockReason, ReguardConfigError } from "./config.cjs";
|
|
21
|
+
export interface FetchBlockOptions extends Omit<BlockBase, "require" | "requireMaxAgeMs" | "requireGraceMs" | "requireGraceRequests" | "requireGracePages" | "requireRefreshRequests" | "requireRefreshMs"> {
|
|
22
|
+
allowIf?: (request: Request) => boolean;
|
|
23
|
+
/** Your own answer for a blocked request; Reguard's default (`defaultBlockAnswer`) when it throws. */
|
|
24
|
+
respond?: (request: Request, decision: Decision) => Response | Promise<Response>;
|
|
25
|
+
onBlock?: (decision: Decision, request: Request) => void;
|
|
26
|
+
}
|
|
27
|
+
export interface ReguardFetchOptions {
|
|
28
|
+
key?: string;
|
|
29
|
+
previousKey?: string;
|
|
30
|
+
collector?: string;
|
|
31
|
+
block?: boolean | FetchBlockOptions;
|
|
32
|
+
sourceMaps?: "deny" | "allow";
|
|
33
|
+
ignore?: readonly string[];
|
|
34
|
+
collect?: CollectOptions;
|
|
35
|
+
watchSessionless?: boolean;
|
|
36
|
+
clientIp?: ClientIpOption<Request>;
|
|
37
|
+
cookieDomain?: string;
|
|
38
|
+
debug?: boolean;
|
|
39
|
+
logger?: LoggerLike | false;
|
|
40
|
+
timeoutMs?: number;
|
|
41
|
+
flushIntervalMs?: number;
|
|
42
|
+
/** The host, when the environment can't tell (Workers have no process.env): "workers", "vercel", "netlify". */
|
|
43
|
+
platform?: Platform;
|
|
44
|
+
fetch?: typeof fetch;
|
|
45
|
+
onError?: (error: unknown) => void;
|
|
46
|
+
}
|
|
47
|
+
type WaitUntil = (p: Promise<unknown>) => void;
|
|
48
|
+
type Handler<A extends unknown[]> = (request: Request, ...rest: A) => Response | Promise<Response>;
|
|
49
|
+
export interface ReguardFetch {
|
|
50
|
+
readonly site: string | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* Before your handler: a Response for /_s/*, source maps and blocked visitors; undefined for
|
|
53
|
+
* everyone else (the verdict is then ready for `verdict(request)`).
|
|
54
|
+
*/
|
|
55
|
+
handle(request: Request, ctx?: {
|
|
56
|
+
waitUntil?: WaitUntil;
|
|
57
|
+
}): Promise<Response | undefined>;
|
|
58
|
+
/** After your handler: queue the summary of its response. */
|
|
59
|
+
record(request: Request, response: Response, ctx?: {
|
|
60
|
+
waitUntil?: WaitUntil;
|
|
61
|
+
}): void;
|
|
62
|
+
/** handle + your handler + record. The platform's waitUntil is found among the handler's arguments. */
|
|
63
|
+
wrap<A extends unknown[]>(handler: Handler<A>): Handler<A>;
|
|
64
|
+
/** The visitor's verdict for a request that went through handle (null: none). */
|
|
65
|
+
verdict(request: Request): Promise<Verdict | null>;
|
|
66
|
+
/** In a dry run, what Reguard would have done for this request (null: nothing). */
|
|
67
|
+
decision(request: Request): Decision | null;
|
|
68
|
+
scriptTag(options?: {
|
|
69
|
+
nonce?: string;
|
|
70
|
+
}): string;
|
|
71
|
+
flush(): Promise<void>;
|
|
72
|
+
}
|
|
73
|
+
/** Reguard's default answer for a decision (HTML page for page loads, JSON with a `code` otherwise). */
|
|
74
|
+
export declare function defaultBlockAnswer(request: Request, decision: Decision): Response;
|
|
75
|
+
/** Reguard for fetch-style servers. Throws ReguardConfigError for an option it can't use. */
|
|
76
|
+
export declare function reguardFetch(options?: ReguardFetchOptions): ReguardFetch;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { LoggerLike } from "./config.cjs";
|
|
2
|
+
export interface Log {
|
|
3
|
+
warn(message: string): void;
|
|
4
|
+
error(message: string): void;
|
|
5
|
+
info(message: string): void;
|
|
6
|
+
debug(message: string): void;
|
|
7
|
+
/** Logs `message` the first time `kind` comes up in this process. */
|
|
8
|
+
once(kind: string, level: "warn" | "error" | "info", message: string): void;
|
|
9
|
+
readonly debugging: boolean;
|
|
10
|
+
}
|
|
11
|
+
export declare function makeLog(logger: LoggerLike | false | undefined, debugging: boolean): Log;
|
|
12
|
+
export type HealthState = "ok" | "failing" | "rejected" | "paused";
|
|
13
|
+
/** How long summaries stay paused after Reguard answers 429 (the plan's monthly limit). Browsers wait as long. */
|
|
14
|
+
export declare const PAUSE_MS: number;
|
|
15
|
+
/** How long before summaries are tried again after Reguard rejects the key. */
|
|
16
|
+
export declare const REJECTED_RETRY_MS: number;
|
|
17
|
+
/**
|
|
18
|
+
* What the server's own authenticated calls to Reguard (request summaries) last saw. Only these
|
|
19
|
+
* drive `failOpen`: nothing a visitor sends can make them fail. While Reguard is unreachable,
|
|
20
|
+
* rejects the key or is paused for the plan's limit, `require` routes stay open (a visitor can't
|
|
21
|
+
* get a fresh verdict then, and denying everyone would turn Reguard's outage into yours).
|
|
22
|
+
*/
|
|
23
|
+
export declare class Health {
|
|
24
|
+
private readonly log;
|
|
25
|
+
private readonly now;
|
|
26
|
+
state: HealthState;
|
|
27
|
+
since: number;
|
|
28
|
+
lastError: string | undefined;
|
|
29
|
+
private pausedUntil;
|
|
30
|
+
private retryAt;
|
|
31
|
+
constructor(log: Log, now?: () => number);
|
|
32
|
+
private move;
|
|
33
|
+
ok(): void;
|
|
34
|
+
failing(error: string): void;
|
|
35
|
+
rejected(status: number): void;
|
|
36
|
+
paused(): void;
|
|
37
|
+
/** Whether a batch may be sent now (not while paused or waiting after a rejection). */
|
|
38
|
+
canSend(): boolean;
|
|
39
|
+
/** `require` routes are not enforced while this is true. */
|
|
40
|
+
get failOpen(): boolean;
|
|
41
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { type CanonicalPath, type CollectOptions, type CollectSettings, type ResolvedAddress } from "../../shared/src/index.cjs";
|
|
3
|
+
import { type BlockBase, type ClientIpOption, type LoggerLike } from "./config.cjs";
|
|
4
|
+
import { type Decision, type Verdict } from "./core.cjs";
|
|
5
|
+
import { Health, type HealthState, type Log } from "./health.cjs";
|
|
6
|
+
export type { AddressesMode, ClientIpMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.cjs";
|
|
7
|
+
export type { Decision, PaceConfig, PaceKind, PaceRate, Verdict, VerdictSource } from "./core.cjs";
|
|
8
|
+
export { type BlockReason, type ConfigErrorCode, type LoggerLike, ReguardConfigError } from "./config.cjs";
|
|
9
|
+
export type { HealthState } from "./health.cjs";
|
|
10
|
+
export { formatSiteKey, parseSiteKey, type ParsedSiteKey } from "../../shared/src/index.cjs";
|
|
11
|
+
declare global {
|
|
12
|
+
namespace Express {
|
|
13
|
+
interface Request {
|
|
14
|
+
reguard?: Verdict | null;
|
|
15
|
+
reguardDecision?: Decision | null;
|
|
16
|
+
reDetect?: Verdict | null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
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;
|
|
47
|
+
export interface ReguardOptions {
|
|
48
|
+
/** Your site key (`rgk.…`, from the dashboard). Default: process.env.REGUARD_KEY. */
|
|
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;
|
|
55
|
+
/** Where Reguard answers. Default: process.env.REGUARD_COLLECTOR or https://api.reguard.site. */
|
|
56
|
+
collector?: string;
|
|
57
|
+
/** Add the script tag to HTML pages. Default true (add it yourself with `scriptTag()` when false). */
|
|
58
|
+
inject?: boolean;
|
|
59
|
+
/**
|
|
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.
|
|
63
|
+
*/
|
|
64
|
+
block?: BlockOption;
|
|
65
|
+
/**
|
|
66
|
+
* Source maps (`*.map`): "deny" answers 404 and drops SourceMap headers, so your original source
|
|
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.
|
|
69
|
+
*/
|
|
70
|
+
sourceMaps?: "deny" | "allow";
|
|
71
|
+
/** Paths never summarized (e.g. ["/healthz"]). */
|
|
72
|
+
ignore?: readonly string[];
|
|
73
|
+
/** Requests never summarized, decided per request. */
|
|
74
|
+
ignoreIf?: (req: ReguardRequest) => boolean;
|
|
75
|
+
/**
|
|
76
|
+
* What Reguard receives, from your server and from the browser (the tag carries the same choices):
|
|
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/*"]).
|
|
79
|
+
*/
|
|
80
|
+
collect?: CollectOptions;
|
|
81
|
+
/**
|
|
82
|
+
* Summarize cookieless requests worth watching (scanners, crawlers, site copiers, scripts, scanner
|
|
83
|
+
* paths, source maps, not-found answers). Default true. Addresses are sent only as a keyed hash.
|
|
84
|
+
*/
|
|
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;
|
|
104
|
+
/** Advanced: custom fetch, error hook, summary flush interval. */
|
|
105
|
+
fetch?: typeof fetch;
|
|
106
|
+
onError?: (error: unknown) => void;
|
|
107
|
+
flushIntervalMs?: number;
|
|
108
|
+
}
|
|
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
|
+
}
|
|
125
|
+
export interface ReguardMiddleware {
|
|
126
|
+
(req: IncomingMessage, res: ServerResponse, next: Next): void;
|
|
127
|
+
/** The site id read from the key (undefined when no key is configured). */
|
|
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;
|
|
135
|
+
/** Send queued summaries now. */
|
|
136
|
+
flush(): Promise<void>;
|
|
137
|
+
/** Stop the summary timer and send what's queued (e.g. on shutdown). */
|
|
138
|
+
close(): Promise<void>;
|
|
139
|
+
}
|
|
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. */
|
|
149
|
+
export declare function reguard(options?: ReguardOptions): ReguardMiddleware;
|
|
150
|
+
export default reguard;
|
|
151
|
+
export interface ReDetectServerOptions {
|
|
152
|
+
/** The site's public id. */
|
|
153
|
+
site: string;
|
|
154
|
+
/** The site's key: the `rgk.…` key or, for sites set up before v0.4, the bare secret. Server-side only. */
|
|
155
|
+
siteKey: string;
|
|
156
|
+
/** The collector's base URL including its prefix, e.g. "https://api.reguard.site/_s". */
|
|
157
|
+
collector: string;
|
|
158
|
+
/** First-party path the browser SDK uses on this origin (default "/_s"). */
|
|
159
|
+
prefix?: string;
|
|
160
|
+
/** Also describe every request that carries no SDK session (default false). */
|
|
161
|
+
includeSessionless?: boolean;
|
|
162
|
+
/**
|
|
163
|
+
* Describe cookieless requests worth watching (default true): scanners, crawlers, site copiers,
|
|
164
|
+
* HTTP libraries and clients that only pretend to be browsers, scanner paths, source maps and
|
|
165
|
+
* not-found answers. Tools that never run the page never get a session; Reguard groups these per
|
|
166
|
+
* visitor through a keyed hash of the address (the address itself never leaves this process).
|
|
167
|
+
*/
|
|
168
|
+
watchSessionless?: boolean;
|
|
169
|
+
/** Paths never described, e.g. health checks. */
|
|
170
|
+
ignore?: (path: string) => boolean;
|
|
171
|
+
/** What Reguard receives (see ReguardOptions.collect). */
|
|
172
|
+
collect?: CollectOptions | CollectSettings;
|
|
173
|
+
flushIntervalMs?: number;
|
|
174
|
+
maxQueue?: number;
|
|
175
|
+
fetch?: typeof fetch;
|
|
176
|
+
onError?: (error: unknown) => void;
|
|
177
|
+
}
|
|
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): {
|
|
188
|
+
middleware: () => (req: ReguardRequest, res: ServerResponse, next: Next) => void;
|
|
189
|
+
route: () => (req: ReguardRequest, res: ServerResponse) => Promise<void>;
|
|
190
|
+
track: (req: ReguardRequest, res: ServerResponse) => void;
|
|
191
|
+
readVerdict: (cookieHeader: string | null | undefined) => Promise<Verdict | null>;
|
|
192
|
+
/** Claims the collector pushed back for this request's session or visitor (null: none). */
|
|
193
|
+
pushedFor: (req: IncomingMessage, verified?: boolean) => Verdict | null;
|
|
194
|
+
/** For fetch-style handlers (Next.js route handlers, edge functions): pass `request.headers`. */
|
|
195
|
+
readVerdictFromHeaders: (headers: {
|
|
196
|
+
get(name: string): string | null;
|
|
197
|
+
}) => Promise<Verdict | null>;
|
|
198
|
+
/** Summaries waiting to be sent. */
|
|
199
|
+
queued: () => number;
|
|
200
|
+
/** Send queued summaries now (e.g. before shutdown). */
|
|
201
|
+
flush: () => Promise<void>;
|
|
202
|
+
close: () => Promise<void>;
|
|
203
|
+
};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
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
|
+
*
|
|
5
|
+
* // next.config.js
|
|
6
|
+
* import { withReguard } from "reguard/next";
|
|
7
|
+
* export default withReguard({ ...yourConfig });
|
|
8
|
+
*
|
|
9
|
+
* // app/layout.tsx (App Router), or pages/_document.tsx (Pages Router)
|
|
10
|
+
* import Script from "next/script";
|
|
11
|
+
* import { reguardScriptProps } from "reguard/next";
|
|
12
|
+
* <Script {...reguardScriptProps()} />
|
|
13
|
+
*
|
|
14
|
+
* // anywhere on the server: route handler, server action, middleware
|
|
15
|
+
* 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
|
+
*/
|
|
20
|
+
import { type CollectOptions } from "../../shared/src/index.cjs";
|
|
21
|
+
import { type ClientIpOption, type LoggerLike } from "./config.cjs";
|
|
22
|
+
import { type Verdict } from "./core.cjs";
|
|
23
|
+
import { type FetchBlockOptions } from "./fetch.cjs";
|
|
24
|
+
export type { Decision, Verdict, VerdictSource } from "./core.cjs";
|
|
25
|
+
export type { FetchBlockOptions as BlockOptions } from "./fetch.cjs";
|
|
26
|
+
export { type BlockReason, ReguardConfigError } from "./config.cjs";
|
|
27
|
+
export type { AddressesMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.cjs";
|
|
28
|
+
/**
|
|
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.
|
|
33
|
+
*/
|
|
34
|
+
export declare function withReguard<T extends object>(config: T, options?: {
|
|
35
|
+
collector?: string;
|
|
36
|
+
key?: string;
|
|
37
|
+
}): T;
|
|
38
|
+
/** The visitor's verified verdict from a Request or NextRequest (null when there is none). */
|
|
39
|
+
export declare function reguardVerdict(request: {
|
|
40
|
+
headers: {
|
|
41
|
+
get(name: string): string | null;
|
|
42
|
+
};
|
|
43
|
+
}, options?: {
|
|
44
|
+
key?: string;
|
|
45
|
+
previousKey?: string;
|
|
46
|
+
}): Promise<Verdict | null>;
|
|
47
|
+
export type ReguardScriptProps = {
|
|
48
|
+
src: string;
|
|
49
|
+
async: true;
|
|
50
|
+
referrerPolicy: "origin";
|
|
51
|
+
nonce?: string;
|
|
52
|
+
} & {
|
|
53
|
+
[attr: `data-${string}`]: string;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
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.
|
|
61
|
+
*/
|
|
62
|
+
export declare function reguardScriptProps(options?: {
|
|
63
|
+
key?: string;
|
|
64
|
+
collect?: Omit<CollectOptions, "requests">;
|
|
65
|
+
nonce?: string;
|
|
66
|
+
cookieDomain?: string;
|
|
67
|
+
}): ReguardScriptProps;
|
|
68
|
+
export interface ReguardMiddlewareOptions {
|
|
69
|
+
block?: boolean | FetchBlockOptions;
|
|
70
|
+
key?: string;
|
|
71
|
+
previousKey?: string;
|
|
72
|
+
sourceMaps?: "deny" | "allow";
|
|
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.cjs";
|
|
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>;
|