reguard 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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-YDDBWUPV.js +438 -0
- package/dist/cjs/fastify.cjs +2109 -0
- package/dist/cjs/fetch.cjs +1453 -0
- package/dist/cjs/index.cjs +2074 -0
- package/dist/cjs/next.cjs +1518 -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 +41 -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
package/dist/next.js
CHANGED
|
@@ -1,30 +1,29 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
2
|
+
reguardFetch
|
|
3
|
+
} from "./chunks/chunk-YDDBWUPV.js";
|
|
4
|
+
import {
|
|
5
|
+
ReguardConfigError,
|
|
6
|
+
checkBlock,
|
|
7
|
+
checkCollect,
|
|
8
|
+
checkCookieDomain
|
|
9
|
+
} from "./chunks/chunk-3AYS7WSY.js";
|
|
10
|
+
import {
|
|
10
11
|
collectAttributes,
|
|
11
12
|
collectorBase,
|
|
12
13
|
envValue,
|
|
13
14
|
isReguardPath,
|
|
14
|
-
isSpeculativeHeaders,
|
|
15
15
|
parseSiteKey,
|
|
16
16
|
readVerdictFrom,
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
toolOf,
|
|
20
|
-
wantsPage
|
|
21
|
-
} from "./chunks/chunk-W56LN2M5.js";
|
|
17
|
+
resolveCollect
|
|
18
|
+
} from "./chunks/chunk-PA46KSOR.js";
|
|
22
19
|
|
|
23
20
|
// src/next.ts
|
|
24
21
|
function withReguard(config, options = {}) {
|
|
25
22
|
const rule = { source: "/_s/:path*", destination: `${collectorBase(options.collector ?? envValue("REGUARD_COLLECTOR"))}/_s/:path*`, basePath: false };
|
|
23
|
+
const site = parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site;
|
|
26
24
|
const apply = (cfg) => ({
|
|
27
25
|
...cfg,
|
|
26
|
+
...site ? { env: { ...cfg.env ?? {}, NEXT_PUBLIC_REGUARD_SITE: site } } : {},
|
|
28
27
|
async rewrites() {
|
|
29
28
|
const mine = cfg.rewrites ? await cfg.rewrites() : void 0;
|
|
30
29
|
if (!mine) return { beforeFiles: [rule], afterFiles: [], fallback: [] };
|
|
@@ -39,57 +38,47 @@ function withReguard(config, options = {}) {
|
|
|
39
38
|
return apply(config);
|
|
40
39
|
}
|
|
41
40
|
async function reguardVerdict(request, options = {}) {
|
|
42
|
-
const
|
|
41
|
+
const cookie = request.headers.get("cookie");
|
|
42
|
+
const parsed = parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim());
|
|
43
43
|
if (!parsed?.site) return null;
|
|
44
|
-
|
|
44
|
+
const v = await readVerdictFrom(parsed.secret, parsed.site, cookie);
|
|
45
|
+
if (v) return v;
|
|
46
|
+
const prev = parseSiteKey((options.previousKey ?? envValue("REGUARD_KEY_PREVIOUS"))?.trim());
|
|
47
|
+
return prev?.site === parsed.site ? readVerdictFrom(prev.secret, prev.site, cookie) : null;
|
|
45
48
|
}
|
|
46
49
|
var warned = false;
|
|
47
|
-
var warnedCollect = /* @__PURE__ */ new Set();
|
|
48
50
|
function reguardScriptProps(options = {}) {
|
|
49
|
-
const site = parseSiteKey(options.key ?? envValue("REGUARD_KEY"))?.site;
|
|
51
|
+
const site = parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site ?? envValue("NEXT_PUBLIC_REGUARD_SITE");
|
|
50
52
|
if (!site && !warned) {
|
|
51
53
|
warned = true;
|
|
52
|
-
console.warn("[reguard] REGUARD_KEY is not set (
|
|
54
|
+
console.warn("[reguard] REGUARD_KEY is not set (and withReguard didn't provide NEXT_PUBLIC_REGUARD_SITE): the script will load but not start.");
|
|
53
55
|
}
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
56
|
+
const production = envValue("NODE_ENV") === "production";
|
|
57
|
+
const collect = production ? resolveCollect(options.collect, (m) => console.warn(`[reguard] ${m}`)) : checkCollect(options.collect);
|
|
58
|
+
const cookieDomain = production ? typeof options.cookieDomain === "string" ? options.cookieDomain.replace(/^\./, "").toLowerCase() : void 0 : checkCookieDomain(options.cookieDomain);
|
|
59
|
+
return {
|
|
60
|
+
src: "/_s/sdk.js",
|
|
61
|
+
async: true,
|
|
62
|
+
referrerPolicy: "origin",
|
|
63
|
+
...options.nonce ? { nonce: options.nonce } : {},
|
|
64
|
+
...site ? { "data-site": site } : {},
|
|
65
|
+
...collectAttributes(collect),
|
|
66
|
+
...cookieDomain ? { "data-cookie-domain": cookieDomain } : {}
|
|
67
|
+
};
|
|
60
68
|
}
|
|
61
69
|
function reguardMiddleware(options = {}) {
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
70
|
+
for (const k of Object.keys(options))
|
|
71
|
+
if (!["block", "key", "previousKey", "sourceMaps", "clientIp", "debug", "logger"].includes(k) && options[k] !== void 0)
|
|
72
|
+
throw new ReguardConfigError(k, "unknown_option", "isn't an option of reguardMiddleware");
|
|
73
|
+
checkBlock(options.block, "block", "fetch");
|
|
74
|
+
const rg = reguardFetch({ ...options, collect: { requests: false } });
|
|
66
75
|
return async (request) => {
|
|
67
|
-
|
|
68
|
-
|
|
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
|
-
});
|
|
76
|
+
if (isReguardPath(new URL(request.url).pathname)) return void 0;
|
|
77
|
+
return rg.handle(request);
|
|
90
78
|
};
|
|
91
79
|
}
|
|
92
80
|
export {
|
|
81
|
+
ReguardConfigError,
|
|
93
82
|
reguardMiddleware,
|
|
94
83
|
reguardScriptProps,
|
|
95
84
|
reguardVerdict,
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import {
|
|
2
|
+
VERDICT_TTL_MS,
|
|
3
|
+
formatSiteKey,
|
|
4
|
+
parseSiteKey,
|
|
5
|
+
signVerdict
|
|
6
|
+
} from "./chunks/chunk-PA46KSOR.js";
|
|
7
|
+
|
|
8
|
+
// src/testing.ts
|
|
9
|
+
function testKey(site = "test-site") {
|
|
10
|
+
const bytes = new Uint8Array(24);
|
|
11
|
+
crypto.getRandomValues(bytes);
|
|
12
|
+
let s = "";
|
|
13
|
+
for (const b of bytes) s += String.fromCharCode(b);
|
|
14
|
+
const secret = btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
15
|
+
return formatSiteKey(site, 1, secret);
|
|
16
|
+
}
|
|
17
|
+
function claim(label, stage = "alert", rule = `test.claim.${label}`) {
|
|
18
|
+
return { rule, label, stage };
|
|
19
|
+
}
|
|
20
|
+
async function verdictCookie(key, options = {}) {
|
|
21
|
+
const parsed = parseSiteKey(key);
|
|
22
|
+
if (!parsed?.site) throw new TypeError("[reguard] verdictCookie needs an rgk.\u2026 key (testKey() makes one)");
|
|
23
|
+
const claims = options.claims ?? [];
|
|
24
|
+
const sid = options.sid ?? "test_session_0123456789";
|
|
25
|
+
const token = await signVerdict(parsed.secret, {
|
|
26
|
+
v: 1,
|
|
27
|
+
sid,
|
|
28
|
+
site: parsed.site,
|
|
29
|
+
outcome: claims.length ? "review" : "insufficient_evidence",
|
|
30
|
+
claims,
|
|
31
|
+
exp: (options.issuedAt ?? Date.now()) + VERDICT_TTL_MS
|
|
32
|
+
});
|
|
33
|
+
return `_s=${sid}; _sv=${token}`;
|
|
34
|
+
}
|
|
35
|
+
export {
|
|
36
|
+
claim,
|
|
37
|
+
testKey,
|
|
38
|
+
verdictCookie
|
|
39
|
+
};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { type ClientIpMode, type CollectSettings, type Label, type Stage } from "../../shared/src/index.js";
|
|
2
|
+
import { type PaceConfig, type PaceRate } from "./core.js";
|
|
3
|
+
export type ConfigErrorCode = "unknown_option" | "removed_option" | "invalid_type" | "invalid_value" | "empty_list" | "out_of_range";
|
|
4
|
+
/** Thrown at startup for an option Reguard can't use. `option` is its path, e.g. "block.minStage". */
|
|
5
|
+
export declare class ReguardConfigError extends TypeError {
|
|
6
|
+
readonly option: string;
|
|
7
|
+
readonly code: ConfigErrorCode;
|
|
8
|
+
constructor(option: string, code: ConfigErrorCode, detail: string);
|
|
9
|
+
}
|
|
10
|
+
/** Why Reguard answered (or, in a dry run, would have answered) for the app. */
|
|
11
|
+
export type BlockReason = "flagged" | "flagged_server" | "require" | "pace";
|
|
12
|
+
export declare const BLOCK_REASONS: readonly BlockReason[];
|
|
13
|
+
export declare const LABELS: readonly Label[];
|
|
14
|
+
export declare const STAGES: readonly Stage[];
|
|
15
|
+
export declare function checkBoolean(v: unknown, option: string): boolean | undefined;
|
|
16
|
+
export declare function checkFunction<T>(v: unknown, option: string): T | undefined;
|
|
17
|
+
export declare function checkNumber(v: unknown, option: string, min: number, max: number, integer?: boolean): number | undefined;
|
|
18
|
+
/** A list of path patterns ("/api/*"); a comma-separated string is accepted where `commas` is set. */
|
|
19
|
+
export declare function checkPaths(v: unknown, option: string, commas?: boolean): string[] | undefined;
|
|
20
|
+
/** collect, checked strictly (the browser's resolveCollect stays lenient: it must never throw into a page). */
|
|
21
|
+
export declare function checkCollect(v: unknown, option?: string): CollectSettings;
|
|
22
|
+
export type ClientIpOption<Req> = ClientIpMode | ((req: Req) => string | undefined | null);
|
|
23
|
+
export declare function checkClientIp<Req>(v: unknown, option?: string): ClientIpOption<Req>;
|
|
24
|
+
/** A parent domain for Reguard's cookies ("example.com" or ".example.com"), normalized without the dot. */
|
|
25
|
+
export declare function checkCookieDomain(v: unknown, option?: string): string | undefined;
|
|
26
|
+
export declare function checkCollector(v: unknown, option?: string): string | undefined;
|
|
27
|
+
export interface LoggerLike {
|
|
28
|
+
warn(message: string): void;
|
|
29
|
+
error(message: string): void;
|
|
30
|
+
info?(message: string): void;
|
|
31
|
+
debug?(message: string): void;
|
|
32
|
+
}
|
|
33
|
+
export declare function checkLogger(v: unknown, option?: string): LoggerLike | false | undefined;
|
|
34
|
+
export interface BlockBase {
|
|
35
|
+
/** Only claims with these labels block (default: any label). */
|
|
36
|
+
labels?: readonly Label[];
|
|
37
|
+
/** Status for flagged visitors (default 429). Pace and require answers are always 429. */
|
|
38
|
+
status?: number;
|
|
39
|
+
/** Least stage that blocks (default "candidate": rules still on trial count too). */
|
|
40
|
+
minStage?: Stage;
|
|
41
|
+
/**
|
|
42
|
+
* Decide, report and call onBlock, but never answer for the app: `true` for every reason, or a
|
|
43
|
+
* list of reasons (["require", "pace"]) to roll out one at a time. The decision is on the request
|
|
44
|
+
* (req.reguardDecision) and in the dashboard as "would have blocked".
|
|
45
|
+
*/
|
|
46
|
+
dryRun?: boolean | readonly BlockReason[];
|
|
47
|
+
/** Paths never blocked, paced or required, e.g. webhooks and health checks (["/webhooks/*"]). */
|
|
48
|
+
allow?: readonly string[];
|
|
49
|
+
/** Routes that need a live Reguard page (see the docs, "Require a live page"). reguard() only. */
|
|
50
|
+
require?: readonly string[];
|
|
51
|
+
requireMaxAgeMs?: number;
|
|
52
|
+
requireGraceMs?: number;
|
|
53
|
+
requireGraceRequests?: number;
|
|
54
|
+
requireGracePages?: number;
|
|
55
|
+
requireRefreshRequests?: number;
|
|
56
|
+
requireRefreshMs?: number;
|
|
57
|
+
/** Slow down clients faster than a person (default on with block; false turns it off). */
|
|
58
|
+
pace?: boolean | {
|
|
59
|
+
documents?: Partial<PaceRate>;
|
|
60
|
+
api?: Partial<PaceRate>;
|
|
61
|
+
notFound?: Partial<PaceRate>;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export interface BlockConfig {
|
|
65
|
+
labels?: readonly Label[];
|
|
66
|
+
status: number;
|
|
67
|
+
minStage: Stage;
|
|
68
|
+
dryRun: ReadonlySet<BlockReason>;
|
|
69
|
+
allow: readonly string[];
|
|
70
|
+
require?: readonly string[];
|
|
71
|
+
maxAgeMs: number;
|
|
72
|
+
graceMs: number;
|
|
73
|
+
graceRequests: number;
|
|
74
|
+
gracePages: number;
|
|
75
|
+
refreshRequests: number;
|
|
76
|
+
refreshMs: number;
|
|
77
|
+
pace: PaceConfig | null;
|
|
78
|
+
allowIf?: (...a: never[]) => unknown;
|
|
79
|
+
respond?: (...a: never[]) => unknown;
|
|
80
|
+
onBlock?: (...a: never[]) => unknown;
|
|
81
|
+
}
|
|
82
|
+
/** `block` (true, false or options) as the middleware uses it; null when blocking is off. */
|
|
83
|
+
export declare function checkBlock(v: unknown, option?: string, runtime?: "node" | "fetch"): BlockConfig | null;
|
|
84
|
+
export declare const NODE_OPTION_KEYS: readonly ["key", "previousKey", "collector", "inject", "block", "sourceMaps", "ignore", "ignoreIf", "collect", "watchSessionless", "clientIp", "cookieDomain", "debug", "logger", "timeoutMs", "fetch", "onError", "flushIntervalMs"];
|
|
85
|
+
export declare const MOVED_OPTIONS: Record<string, string>;
|
|
86
|
+
export interface CheckedOptions<Req> {
|
|
87
|
+
key?: string;
|
|
88
|
+
previousKey?: string;
|
|
89
|
+
collector?: string;
|
|
90
|
+
inject: boolean;
|
|
91
|
+
block: BlockConfig | null;
|
|
92
|
+
sourceMaps?: "deny" | "allow";
|
|
93
|
+
ignore: string[];
|
|
94
|
+
ignoreIf?: (req: Req) => boolean;
|
|
95
|
+
collect: CollectSettings;
|
|
96
|
+
watchSessionless: boolean;
|
|
97
|
+
clientIp: ClientIpOption<Req>;
|
|
98
|
+
cookieDomain?: string;
|
|
99
|
+
debug?: boolean;
|
|
100
|
+
logger?: LoggerLike | false;
|
|
101
|
+
timeoutMs: number;
|
|
102
|
+
fetch?: typeof fetch;
|
|
103
|
+
onError?: (error: unknown) => void;
|
|
104
|
+
flushIntervalMs: number;
|
|
105
|
+
}
|
|
106
|
+
/** Every reguard() option checked; throws ReguardConfigError on the first problem. */
|
|
107
|
+
export declare function checkOptions<Req>(options: unknown): CheckedOptions<Req>;
|
|
@@ -1,69 +1,36 @@
|
|
|
1
|
-
import { type Label, type Stage, type VerdictClaim, type VerdictPayload } from "../../shared/src/index.js";
|
|
1
|
+
import { type CollectSettings, type Label, type Stage, type VerdictClaim, type VerdictPayload } from "../../shared/src/index.js";
|
|
2
|
+
import type { BlockConfig, BlockReason } from "./config.js";
|
|
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";
|
|
2
5
|
export interface Verdict extends VerdictPayload {
|
|
6
|
+
/** Where the claims came from. */
|
|
7
|
+
source: VerdictSource;
|
|
3
8
|
/**
|
|
4
|
-
* Whether
|
|
5
|
-
*
|
|
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).
|
|
6
11
|
*/
|
|
7
12
|
flagged(options?: {
|
|
8
|
-
labels?: Label[];
|
|
13
|
+
labels?: readonly Label[] | Label;
|
|
9
14
|
minStage?: Stage;
|
|
10
15
|
}): boolean;
|
|
11
16
|
}
|
|
12
17
|
export declare const STAGE_RANK: Record<Stage, number>;
|
|
13
|
-
export declare function withFlagged(p: VerdictPayload): Verdict;
|
|
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;
|
|
14
21
|
/** Verify the visitor's verdict from a Cookie header. Null when absent, forged, expired or another session's. */
|
|
15
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;
|
|
16
28
|
export declare const DEFAULT_COLLECTOR = "https://api.reguard.site";
|
|
17
29
|
/** The collector's base URL without a trailing slash or `/_s`. */
|
|
18
30
|
export declare function collectorBase(collector: string | undefined): string;
|
|
19
31
|
export declare function envValue(name: string): string | undefined;
|
|
20
|
-
/** The collector signs verdicts for this long
|
|
32
|
+
/** The collector signs verdicts for this long. */
|
|
21
33
|
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
34
|
/** A burst, then a steady rate per second. */
|
|
68
35
|
export interface PaceRate {
|
|
69
36
|
burst: number;
|
|
@@ -78,36 +45,63 @@ export interface PaceConfig {
|
|
|
78
45
|
notFound: PaceRate;
|
|
79
46
|
}
|
|
80
47
|
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
48
|
/** Seconds the script tag asks the browser to keep its verdict fresh on `require` sites (half the allowed age). */
|
|
96
49
|
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
50
|
/** How long ago the collector issued a verified verdict. */
|
|
101
51
|
export declare function verdictAgeMs(v: {
|
|
102
52
|
exp: number;
|
|
103
53
|
}, now?: number): number;
|
|
104
54
|
/** 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
|
-
/**
|
|
107
|
-
export
|
|
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>;
|
|
108
79
|
export declare const BLOCK_HTML: string;
|
|
109
|
-
export declare const
|
|
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
|
+
};
|
|
110
87
|
/** A page load gets the short HTML page; anything else (API calls, assets) gets JSON. */
|
|
111
88
|
export declare function wantsPage(get: (name: string) => string | null | undefined): boolean;
|
|
112
89
|
/** Reguard's own paths (the script and its reports) are never blocked. */
|
|
113
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.js";
|
|
17
|
+
import { type ReguardOptions } from "./index.js";
|
|
18
|
+
export type { Decision, Verdict } from "./core.js";
|
|
19
|
+
export { ReguardConfigError } from "./config.js";
|
|
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.js";
|
|
17
|
+
import { type BlockBase, type ClientIpOption, type LoggerLike } from "./config.js";
|
|
18
|
+
import { type Decision, type Verdict } from "./core.js";
|
|
19
|
+
export type { Decision, Verdict, VerdictSource } from "./core.js";
|
|
20
|
+
export { type BlockReason, ReguardConfigError } from "./config.js";
|
|
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.js";
|
|
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
|
+
}
|