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
|
@@ -0,0 +1,969 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BLOCK_REASONS,
|
|
3
|
+
Health,
|
|
4
|
+
ReguardConfigError,
|
|
5
|
+
checkOptions,
|
|
6
|
+
makeLog
|
|
7
|
+
} from "./chunk-3AYS7WSY.js";
|
|
8
|
+
import {
|
|
9
|
+
Allowance,
|
|
10
|
+
BENIGN_TOOL_FAMILIES,
|
|
11
|
+
RETRY_AFTER,
|
|
12
|
+
SESSION_COOKIE,
|
|
13
|
+
canonicalPath,
|
|
14
|
+
collectReport,
|
|
15
|
+
collectorBase,
|
|
16
|
+
cookieValue,
|
|
17
|
+
cspNonce,
|
|
18
|
+
defaultAnswer,
|
|
19
|
+
describeExchange,
|
|
20
|
+
detectPlatform,
|
|
21
|
+
envValue,
|
|
22
|
+
freshSeconds,
|
|
23
|
+
isApiLike,
|
|
24
|
+
isPreflight,
|
|
25
|
+
isPublicIp,
|
|
26
|
+
isReguardPath,
|
|
27
|
+
isSourceMapPath,
|
|
28
|
+
isSpeculativeHeaders,
|
|
29
|
+
looksCurrent,
|
|
30
|
+
matchesBoth,
|
|
31
|
+
matchesEither,
|
|
32
|
+
mergeVerdicts,
|
|
33
|
+
normalizeIp,
|
|
34
|
+
parseSiteKey,
|
|
35
|
+
pathTraits,
|
|
36
|
+
privateUrl,
|
|
37
|
+
pushedVerdict,
|
|
38
|
+
readVerdictFrom,
|
|
39
|
+
renderScriptTag,
|
|
40
|
+
requestKind,
|
|
41
|
+
resolveClientAddress,
|
|
42
|
+
resolveCollect,
|
|
43
|
+
skipMatcher,
|
|
44
|
+
toolOf,
|
|
45
|
+
verdictAgeMs,
|
|
46
|
+
wantsPage,
|
|
47
|
+
watchworthy
|
|
48
|
+
} from "./chunk-PA46KSOR.js";
|
|
49
|
+
|
|
50
|
+
// src/index.ts
|
|
51
|
+
import { createHash, createHmac } from "node:crypto";
|
|
52
|
+
import { Readable } from "node:stream";
|
|
53
|
+
import { pipeline } from "node:stream/promises";
|
|
54
|
+
var PREFIX = "/_s";
|
|
55
|
+
var NOT_FORWARDED = /* @__PURE__ */ new Set([
|
|
56
|
+
"connection",
|
|
57
|
+
"keep-alive",
|
|
58
|
+
"proxy-authenticate",
|
|
59
|
+
"proxy-authorization",
|
|
60
|
+
"te",
|
|
61
|
+
"trailer",
|
|
62
|
+
"transfer-encoding",
|
|
63
|
+
"upgrade",
|
|
64
|
+
"host",
|
|
65
|
+
"content-length",
|
|
66
|
+
"expect",
|
|
67
|
+
"accept-encoding",
|
|
68
|
+
"cookie",
|
|
69
|
+
"authorization"
|
|
70
|
+
]);
|
|
71
|
+
var STRIP_FROM_RESPONSE = /* @__PURE__ */ new Set(["content-encoding", "content-length", "transfer-encoding", "connection", "keep-alive", "set-cookie"]);
|
|
72
|
+
var ADDRESS_HEADER = /^(?:x-forwarded-for|forwarded|x-real-ip|x-original-forwarded-for|x-envoy-external-address|x-nf-client-connection-ip|x-vercel-forwarded-for|x-vercel-proxied-for|fly-client-ip)$|client-?ip|connecting-ip|^cf-ip|^cf-(?:region|metro|postal|timezone)|^x-vercel-ip-|^cloudfront-viewer-|^x-appengine-(?:user-ip|city|country|region)/;
|
|
73
|
+
var SCAN_LIMIT = 64 * 1024;
|
|
74
|
+
function visitorHash(secret, address) {
|
|
75
|
+
return createHmac("sha256", secret).update(`visitor:${address}`).digest("base64url").slice(0, 22);
|
|
76
|
+
}
|
|
77
|
+
function keyFingerprint(secret) {
|
|
78
|
+
return createHash("sha256").update(`reguard-key:${secret}`).digest("base64url").slice(0, 8);
|
|
79
|
+
}
|
|
80
|
+
function visitorHeader(secret, address, addresses) {
|
|
81
|
+
const value = addresses === "off" || !address ? "-" : visitorHash(secret, address);
|
|
82
|
+
return `${value}.${createHmac("sha256", secret).update(`visitor-header:${value}`).digest("base64url").slice(0, 16)}`;
|
|
83
|
+
}
|
|
84
|
+
var ADDRESS = /* @__PURE__ */ new WeakMap();
|
|
85
|
+
function addressOf(req) {
|
|
86
|
+
return ADDRESS.get(req) ?? resolveClientAddress({ peer: req.socket?.remoteAddress ?? "", header: (n) => header(req.headers, n) }, "socket");
|
|
87
|
+
}
|
|
88
|
+
function refererOrigin(v) {
|
|
89
|
+
try {
|
|
90
|
+
const u = new URL(v);
|
|
91
|
+
return u.origin === "null" ? void 0 : `${u.origin}/`;
|
|
92
|
+
} catch {
|
|
93
|
+
return void 0;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function headersForReguard(req, secret, siteTag, collect) {
|
|
97
|
+
const headers = new Headers();
|
|
98
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
99
|
+
if (v === void 0 || NOT_FORWARDED.has(k) || k.startsWith(":") || k.startsWith("x-reguard-") || k === "referer" || ADDRESS_HEADER.test(k)) continue;
|
|
100
|
+
try {
|
|
101
|
+
headers.set(k, Array.isArray(v) ? v.join(", ") : v);
|
|
102
|
+
} catch {
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const referer = header(req.headers, "referer");
|
|
106
|
+
const origin = referer ? refererOrigin(referer) : void 0;
|
|
107
|
+
if (origin) headers.set("referer", origin);
|
|
108
|
+
const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
|
|
109
|
+
if (sid && /^[\w-]{1,64}$/.test(sid)) headers.set("cookie", `${SESSION_COOKIE}=${sid}`);
|
|
110
|
+
headers.set("x-reguard-site", siteTag);
|
|
111
|
+
headers.set("x-reguard-visitor", visitorHeader(secret, addressOf(req).address, collect.addresses));
|
|
112
|
+
return headers;
|
|
113
|
+
}
|
|
114
|
+
function siteTagOf(site, secret) {
|
|
115
|
+
return `${site}.${createHmac("sha256", secret).update(`prefix:${site}`).digest("base64url").slice(0, 16)}`;
|
|
116
|
+
}
|
|
117
|
+
var PACED = /* @__PURE__ */ new WeakMap();
|
|
118
|
+
var DECIDED = /* @__PURE__ */ new WeakMap();
|
|
119
|
+
function stripSourceMapHeaders(res) {
|
|
120
|
+
const isMapHeader = (name) => typeof name === "string" && /^(?:x-)?sourcemap$/i.test(name);
|
|
121
|
+
const setHeader = res.setHeader.bind(res);
|
|
122
|
+
res.setHeader = ((name, value) => isMapHeader(name) ? res : setHeader(name, value));
|
|
123
|
+
const writeHead = res.writeHead.bind(res);
|
|
124
|
+
res.writeHead = (...a) => {
|
|
125
|
+
const h = a.find((x, i) => i > 0 && x && typeof x === "object" && !Array.isArray(x));
|
|
126
|
+
if (h) {
|
|
127
|
+
for (const k of Object.keys(h)) if (isMapHeader(k)) delete h[k];
|
|
128
|
+
}
|
|
129
|
+
for (const k of res.getHeaderNames()) if (isMapHeader(k)) res.removeHeader(k);
|
|
130
|
+
return writeHead(...a);
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function withoutEndpoint(d, pages, hash) {
|
|
134
|
+
if (pages === "masked") return d;
|
|
135
|
+
if (pages === "hashed") return { ...d, endpoint: `~${hash(`endpoint:${d.endpoint}`)}` };
|
|
136
|
+
const { item: _item, ...rest } = d;
|
|
137
|
+
return { ...rest, endpoint: "" };
|
|
138
|
+
}
|
|
139
|
+
function defaultBlockResponse(req, res, decision) {
|
|
140
|
+
const a = defaultAnswer(decision.reason, wantsPage((n) => header(req.headers, n)));
|
|
141
|
+
res.statusCode = decision.status;
|
|
142
|
+
res.setHeader("retry-after", String(decision.retryAfter));
|
|
143
|
+
res.setHeader("cache-control", "no-store");
|
|
144
|
+
res.setHeader("content-type", a.contentType);
|
|
145
|
+
res.end(a.body);
|
|
146
|
+
}
|
|
147
|
+
var errorText = (e) => e instanceof Error ? e.message : String(e);
|
|
148
|
+
function keyShape(key) {
|
|
149
|
+
const quoted = /^["'].*["']$/.test(key) ? " (it has quotes around it: remove them)" : "";
|
|
150
|
+
return `"${key.slice(0, 4)}\u2026", ${key.length} characters${quoted}`;
|
|
151
|
+
}
|
|
152
|
+
function reguard(options = {}) {
|
|
153
|
+
const o = checkOptions(options);
|
|
154
|
+
const debugging = o.debug ?? /^(?:1|true|yes)$/i.test(envValue("REGUARD_DEBUG") ?? "");
|
|
155
|
+
const log = makeLog(o.logger, debugging);
|
|
156
|
+
const key = (o.key ?? envValue("REGUARD_KEY"))?.trim();
|
|
157
|
+
const parsed = parseSiteKey(key);
|
|
158
|
+
if (!parsed?.site) {
|
|
159
|
+
const level = envValue("NODE_ENV") === "production" ? "error" : "warn";
|
|
160
|
+
log.once(
|
|
161
|
+
"no-key",
|
|
162
|
+
level,
|
|
163
|
+
!key ? "REGUARD_KEY is not set: passing every request through (no script, no verdicts, no blocking)." : parsed ? "this key has no site id (a key from before v0.4): use the rgk.\u2026 key from your dashboard. Passing every request through." : `REGUARD_KEY isn't a Reguard key (expected rgk.<site>.v<n>.<secret>; got ${keyShape(key)}). Passing every request through.`
|
|
164
|
+
);
|
|
165
|
+
const passthrough = ((req, _res, next) => {
|
|
166
|
+
req.reguard = null;
|
|
167
|
+
req.reguardDecision = null;
|
|
168
|
+
req.reDetect = null;
|
|
169
|
+
next();
|
|
170
|
+
});
|
|
171
|
+
Object.defineProperty(passthrough, "site", { value: void 0 });
|
|
172
|
+
passthrough.scriptTag = () => "";
|
|
173
|
+
passthrough.status = () => ({ enabled: false, collector: "off", since: Date.now(), failOpen: false, queued: 0, blocking: "off" });
|
|
174
|
+
passthrough.flush = async () => {
|
|
175
|
+
};
|
|
176
|
+
passthrough.close = async () => {
|
|
177
|
+
};
|
|
178
|
+
return passthrough;
|
|
179
|
+
}
|
|
180
|
+
const site = parsed.site;
|
|
181
|
+
const secrets = [parsed.secret];
|
|
182
|
+
const previous = o.previousKey ?? envValue("REGUARD_KEY_PREVIOUS");
|
|
183
|
+
if (previous?.trim()) {
|
|
184
|
+
const prev = parseSiteKey(previous.trim());
|
|
185
|
+
if (!prev?.site || prev.site !== site) {
|
|
186
|
+
if (o.previousKey !== void 0) throw new ReguardConfigError("previousKey", "invalid_value", `must be an earlier rgk.${site}.\u2026 key for the same site`);
|
|
187
|
+
log.once("bad-previous", "warn", `REGUARD_KEY_PREVIOUS isn't an earlier key for site ${site}: ignored.`);
|
|
188
|
+
} else if (prev.secret !== parsed.secret) secrets.push(prev.secret);
|
|
189
|
+
}
|
|
190
|
+
const siteTag = siteTagOf(site, parsed.secret);
|
|
191
|
+
const collector = collectorBase(o.collector ?? envValue("REGUARD_COLLECTOR"));
|
|
192
|
+
const doFetch = o.fetch ?? fetch;
|
|
193
|
+
const onError = o.onError ?? (() => {
|
|
194
|
+
});
|
|
195
|
+
const health = new Health(log);
|
|
196
|
+
const platform = detectPlatform(typeof process !== "undefined" ? process.env : void 0);
|
|
197
|
+
const blockCfg = o.block;
|
|
198
|
+
const allDry = !blockCfg || BLOCK_REASONS.every((r) => blockCfg.dryRun.has(r));
|
|
199
|
+
const skipped = skipMatcher(o.collect.skip);
|
|
200
|
+
const ignored = o.ignore.length ? skipMatcher(o.ignore) : void 0;
|
|
201
|
+
const required = blockCfg?.require ? skipMatcher(blockCfg.require) : void 0;
|
|
202
|
+
const allowList = blockCfg?.allow.length ? skipMatcher(blockCfg.allow) : void 0;
|
|
203
|
+
const denyMaps = (o.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
|
|
204
|
+
const tagSettings = { site, collect: o.collect, fresh: freshSeconds(blockCfg), cookieDomain: o.cookieDomain };
|
|
205
|
+
const resolve = (req) => {
|
|
206
|
+
const known = ADDRESS.get(req);
|
|
207
|
+
if (known) return known;
|
|
208
|
+
const peer = req.socket?.remoteAddress ?? "";
|
|
209
|
+
const get = (n) => header(req.headers, n);
|
|
210
|
+
let a;
|
|
211
|
+
if (typeof o.clientIp === "function") {
|
|
212
|
+
let custom;
|
|
213
|
+
try {
|
|
214
|
+
custom = o.clientIp(req);
|
|
215
|
+
} catch (e) {
|
|
216
|
+
log.once("clientIp-threw", "warn", `clientIp threw (${errorText(e)}): using the connecting address`);
|
|
217
|
+
}
|
|
218
|
+
const ip = normalizeIp(custom ?? void 0);
|
|
219
|
+
a = ip ? { address: ip, internal: !isPublicIp(ip), via: "custom" } : resolveClientAddress({ peer, header: get }, "socket");
|
|
220
|
+
} else {
|
|
221
|
+
const framework = req.app?.get?.("trust proxy") ? req.ip : void 0;
|
|
222
|
+
a = resolveClientAddress({ peer, header: get, framework }, o.clientIp, platform);
|
|
223
|
+
}
|
|
224
|
+
ADDRESS.set(req, a);
|
|
225
|
+
return a;
|
|
226
|
+
};
|
|
227
|
+
const crowd = /* @__PURE__ */ new Map();
|
|
228
|
+
let crowdWarned = false;
|
|
229
|
+
const watchCrowd = (req, a) => {
|
|
230
|
+
if (crowdWarned || a.internal || !a.address) return;
|
|
231
|
+
const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
|
|
232
|
+
if (!sid) return;
|
|
233
|
+
const now = Date.now();
|
|
234
|
+
let c = crowd.get(a.address);
|
|
235
|
+
if (!c || now - c.since > 10 * 6e4) {
|
|
236
|
+
if (crowd.size > 1e4) crowd.clear();
|
|
237
|
+
c = { sids: /* @__PURE__ */ new Set(), since: now };
|
|
238
|
+
crowd.set(a.address, c);
|
|
239
|
+
}
|
|
240
|
+
c.sids.add(sid);
|
|
241
|
+
if (c.sids.size >= 200) {
|
|
242
|
+
crowdWarned = true;
|
|
243
|
+
log.warn(
|
|
244
|
+
`200 different browser sessions came from one address (${a.address}, read from ${a.via}) within 10 minutes. Reguard is probably reading a proxy's address instead of your visitors': set clientIp (reguard.site/docs/production/#visitor-addresses).`
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
const core = createReDetect(
|
|
249
|
+
{
|
|
250
|
+
site,
|
|
251
|
+
siteKey: key,
|
|
252
|
+
// the whole rgk key: summaries authenticate with it, verdicts verify with its secret
|
|
253
|
+
collector: `${collector}${PREFIX}`,
|
|
254
|
+
watchSessionless: o.watchSessionless,
|
|
255
|
+
collect: o.collect,
|
|
256
|
+
fetch: doFetch,
|
|
257
|
+
onError,
|
|
258
|
+
flushIntervalMs: o.flushIntervalMs
|
|
259
|
+
},
|
|
260
|
+
{
|
|
261
|
+
health,
|
|
262
|
+
log,
|
|
263
|
+
timeoutMs: o.timeoutMs,
|
|
264
|
+
address: resolve,
|
|
265
|
+
ignored: (req, p) => (ignored ? matchesEither(ignored, p) : false) || safeIf(o.ignoreIf, req, "ignoreIf", log),
|
|
266
|
+
decided: (req) => DECIDED.get(req)
|
|
267
|
+
}
|
|
268
|
+
);
|
|
269
|
+
let reads = 0;
|
|
270
|
+
let badSignatures = 0;
|
|
271
|
+
let readsSince = Date.now();
|
|
272
|
+
const readVerdict = async (cookie) => {
|
|
273
|
+
for (const s of secrets) {
|
|
274
|
+
const v = await readVerdictFrom(s, site, cookie).catch(() => null);
|
|
275
|
+
if (v) return v;
|
|
276
|
+
}
|
|
277
|
+
if (cookie?.includes("_sv=")) {
|
|
278
|
+
const now = Date.now();
|
|
279
|
+
if (now - readsSince > 10 * 6e4) {
|
|
280
|
+
reads = 0;
|
|
281
|
+
badSignatures = 0;
|
|
282
|
+
readsSince = now;
|
|
283
|
+
}
|
|
284
|
+
reads++;
|
|
285
|
+
if (looksCurrent(site, cookie, now) && ++badSignatures >= 20 && badSignatures * 2 > reads)
|
|
286
|
+
log.once(
|
|
287
|
+
"bad-signatures",
|
|
288
|
+
"error",
|
|
289
|
+
"most visitors' verdicts carry a signature this key doesn't match: REGUARD_KEY is wrong for this site or was rotated. Set the current key; during a rotation, set the old one as previousKey (REGUARD_KEY_PREVIOUS)."
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
return null;
|
|
293
|
+
};
|
|
294
|
+
const pace = blockCfg?.pace ?? null;
|
|
295
|
+
const rate = (r) => new Allowance(r.burst, r.perSecond / 1e3, 5e4);
|
|
296
|
+
const paceDocs = pace ? rate(pace.documents) : void 0;
|
|
297
|
+
const paceApi = pace ? rate(pace.api) : void 0;
|
|
298
|
+
const paceMisses = pace ? rate(pace.notFound) : void 0;
|
|
299
|
+
const cooling = /* @__PURE__ */ new Map();
|
|
300
|
+
const addressKey = (req) => `v:${visitorHash(parsed.secret, resolve(req).address)}`;
|
|
301
|
+
const paceOf = (req, res, p) => {
|
|
302
|
+
if (!pace || resolve(req).internal) return void 0;
|
|
303
|
+
const get = (n) => header(req.headers, n);
|
|
304
|
+
const now = Date.now();
|
|
305
|
+
const browser = get("sec-fetch-dest") !== void 0;
|
|
306
|
+
const tool = browser ? void 0 : toolOf(get("user-agent"));
|
|
307
|
+
if (!browser && !(tool && BENIGN_TOOL_FAMILIES.has(tool.family))) {
|
|
308
|
+
const key2 = addressKey(req);
|
|
309
|
+
res.once("finish", () => {
|
|
310
|
+
const st = res.statusCode;
|
|
311
|
+
if ((st === 404 || st === 405 || st === 410) && !paceMisses.take(key2)) {
|
|
312
|
+
cooling.set(key2, Date.now() + 1e3 / pace.notFound.perSecond);
|
|
313
|
+
if (cooling.size > 5e4) {
|
|
314
|
+
for (const [k, until] of cooling) if (until < Date.now()) cooling.delete(k);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
if ((cooling.get(key2) ?? 0) > now) return "notfound";
|
|
319
|
+
if ((req.method === "GET" || req.method === "HEAD") && requestKind(p.decoded) === "document" && !isSpeculativeHeaders(get)) {
|
|
320
|
+
if (!paceDocs.has(key2, now)) return "document";
|
|
321
|
+
onHeaders(res, (status, contentType) => {
|
|
322
|
+
if (/^\s*text\/html/i.test(contentType) && !(status >= 300 && status < 400) && status !== 204) paceDocs.take(key2);
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (required && matchesEither(required, p)) {
|
|
327
|
+
const sid = cookieValue(get("cookie"), SESSION_COOKIE);
|
|
328
|
+
if (!paceApi.take(sid ? `s:${sid}` : addressKey(req), now)) return "api";
|
|
329
|
+
}
|
|
330
|
+
return void 0;
|
|
331
|
+
};
|
|
332
|
+
const grace = /* @__PURE__ */ new Map();
|
|
333
|
+
const visitorOf = (req) => o.collect.addresses !== "off" ? visitorHash(parsed.secret, resolve(req).address) : void 0;
|
|
334
|
+
const refresh = /* @__PURE__ */ new Map();
|
|
335
|
+
const dryCounts = /* @__PURE__ */ new Map();
|
|
336
|
+
const dryTimer = setInterval(() => {
|
|
337
|
+
if (!dryCounts.size) return;
|
|
338
|
+
const parts = [...dryCounts].map(([r, n]) => `${r} ${n}`).join(", ");
|
|
339
|
+
log.info(`dry run: would have answered ${[...dryCounts.values()].reduce((a, b) => a + b, 0)} requests in the last minute (${parts})`);
|
|
340
|
+
dryCounts.clear();
|
|
341
|
+
}, 6e4);
|
|
342
|
+
dryTimer.unref?.();
|
|
343
|
+
const decide = (req, reason, p, verdict, paceKind) => ({
|
|
344
|
+
reason,
|
|
345
|
+
dryRun: blockCfg.dryRun.has(reason),
|
|
346
|
+
status: reason === "flagged" || reason === "flagged_server" ? blockCfg.status : 429,
|
|
347
|
+
retryAfter: RETRY_AFTER[reason],
|
|
348
|
+
...paceKind ? { pace: paceKind } : {},
|
|
349
|
+
claims: reason === "flagged" || reason === "flagged_server" ? verdict?.claims ?? [] : [],
|
|
350
|
+
verdict,
|
|
351
|
+
path: p.decoded,
|
|
352
|
+
clientIp: resolve(req).address
|
|
353
|
+
});
|
|
354
|
+
const act = (req, res, d) => {
|
|
355
|
+
DECIDED.set(req, d);
|
|
356
|
+
if (d.reason === "pace" && d.pace) PACED.set(req, d.pace);
|
|
357
|
+
try {
|
|
358
|
+
blockCfg.onBlock?.(d, req);
|
|
359
|
+
} catch (e) {
|
|
360
|
+
log.once("onBlock-threw", "warn", `block.onBlock threw: ${errorText(e)}`);
|
|
361
|
+
}
|
|
362
|
+
log.debug(`${d.dryRun ? "would block" : "blocked"} ${req.method} ${d.path}: ${d.reason}${d.pace ? ` (${d.pace})` : ""} from ${d.clientIp}`);
|
|
363
|
+
if (d.dryRun) {
|
|
364
|
+
req.reguardDecision = d;
|
|
365
|
+
dryCounts.set(d.reason, (dryCounts.get(d.reason) ?? 0) + 1);
|
|
366
|
+
return false;
|
|
367
|
+
}
|
|
368
|
+
void answer(req, res, d);
|
|
369
|
+
return true;
|
|
370
|
+
};
|
|
371
|
+
const answer = async (req, res, d) => {
|
|
372
|
+
const respond = blockCfg.respond;
|
|
373
|
+
if (respond) {
|
|
374
|
+
try {
|
|
375
|
+
await respond(req, res, d);
|
|
376
|
+
} catch (e) {
|
|
377
|
+
log.once("respond-threw", "error", `block.respond threw (${errorText(e)}): sent the default answer instead`);
|
|
378
|
+
}
|
|
379
|
+
if (res.writableEnded) return;
|
|
380
|
+
if (res.headersSent) {
|
|
381
|
+
res.end();
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
log.once("respond-silent", "warn", "block.respond didn't answer the request: sent the default answer");
|
|
385
|
+
}
|
|
386
|
+
defaultBlockResponse(req, res, d);
|
|
387
|
+
};
|
|
388
|
+
let proxyFailing = false;
|
|
389
|
+
async function proxy(req, res, p, target) {
|
|
390
|
+
try {
|
|
391
|
+
const q = target.indexOf("?");
|
|
392
|
+
const url = `${p.decoded}${q === -1 ? "" : target.slice(q)}`;
|
|
393
|
+
const headers = headersForReguard(req, parsed.secret, siteTag, o.collect);
|
|
394
|
+
const init = { method: req.method, headers, redirect: "manual", signal: AbortSignal.timeout(o.timeoutMs) };
|
|
395
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
396
|
+
const consumed = req.readableEnded || req._body === true;
|
|
397
|
+
if (!consumed) {
|
|
398
|
+
init.body = Readable.toWeb(req);
|
|
399
|
+
init.duplex = "half";
|
|
400
|
+
} else if (req.body !== void 0) {
|
|
401
|
+
const b = req.body;
|
|
402
|
+
init.body = Buffer.isBuffer(b) ? new Uint8Array(b) : typeof b === "string" ? b : JSON.stringify(b);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
const r = await doFetch(`${collector}${url}`, init);
|
|
406
|
+
if (proxyFailing) {
|
|
407
|
+
proxyFailing = false;
|
|
408
|
+
log.info("passing /_s/* to Reguard again");
|
|
409
|
+
}
|
|
410
|
+
res.statusCode = r.status;
|
|
411
|
+
r.headers.forEach((v, k) => {
|
|
412
|
+
if (!STRIP_FROM_RESPONSE.has(k)) res.setHeader(k, v);
|
|
413
|
+
});
|
|
414
|
+
const cookies = r.headers.getSetCookie?.() ?? [];
|
|
415
|
+
if (cookies.length) res.setHeader("set-cookie", cookies);
|
|
416
|
+
if (r.body && req.method !== "HEAD") await pipeline(Readable.fromWeb(r.body), res);
|
|
417
|
+
else res.end();
|
|
418
|
+
} catch (e) {
|
|
419
|
+
if (e?.code !== "ERR_STREAM_PREMATURE_CLOSE") {
|
|
420
|
+
onError(e);
|
|
421
|
+
if (!proxyFailing) {
|
|
422
|
+
proxyFailing = true;
|
|
423
|
+
log.warn(`couldn't pass /_s/* to Reguard (${errorText(e)}): pages load without Reguard's script until it answers`);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
if (!res.headersSent) {
|
|
427
|
+
res.statusCode = 502;
|
|
428
|
+
res.end();
|
|
429
|
+
} else res.destroy();
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
const exempt = (req, p) => (allowList ? matchesBoth(allowList, p) : false) || safeIf(blockCfg?.allowIf, req, "block.allowIf", log);
|
|
433
|
+
const middleware = ((req, res, next) => {
|
|
434
|
+
const target = req.originalUrl ?? req.url ?? "/";
|
|
435
|
+
const p = canonicalPath(target);
|
|
436
|
+
req.reguard = null;
|
|
437
|
+
req.reguardDecision = null;
|
|
438
|
+
req.reDetect = null;
|
|
439
|
+
const address = resolve(req);
|
|
440
|
+
if (isReguardPath(p.decoded)) {
|
|
441
|
+
void proxy(req, res, p, target);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
watchCrowd(req, address);
|
|
445
|
+
core.track(req, res);
|
|
446
|
+
if (denyMaps) {
|
|
447
|
+
if (isSourceMapPath(p)) {
|
|
448
|
+
res.statusCode = 404;
|
|
449
|
+
res.setHeader("cache-control", "no-store");
|
|
450
|
+
res.end();
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
stripSourceMapHeaders(res);
|
|
454
|
+
}
|
|
455
|
+
const allowed = blockCfg ? exempt(req, p) : true;
|
|
456
|
+
if (blockCfg && !allowed) {
|
|
457
|
+
const paced = paceOf(req, res, p);
|
|
458
|
+
if (paced && act(req, res, decide(req, "pace", p, null, paced))) return;
|
|
459
|
+
}
|
|
460
|
+
const injection = o.inject && !matchesEither(skipped, p) ? injectTag(req, res, tagSettings) : void 0;
|
|
461
|
+
const cookie = header(req.headers, "cookie");
|
|
462
|
+
readVerdict(cookie).then(
|
|
463
|
+
(browser) => {
|
|
464
|
+
const pushed = core.pushedFor(req, !!browser);
|
|
465
|
+
const v = mergeVerdicts(browser, pushed);
|
|
466
|
+
req.reguard = v;
|
|
467
|
+
req.reDetect = v;
|
|
468
|
+
if (blockCfg && !allowed) {
|
|
469
|
+
const opt = { labels: blockCfg.labels, minStage: blockCfg.minStage };
|
|
470
|
+
let reason = browser?.flagged(opt) ? "flagged" : pushed?.flagged(opt) ? "flagged_server" : void 0;
|
|
471
|
+
const fresh = !!browser && verdictAgeMs(browser) <= blockCfg.maxAgeMs;
|
|
472
|
+
if (required && fresh) {
|
|
473
|
+
const g = grace.get(visitorOf(req) ?? "");
|
|
474
|
+
if (g) g.pages = 0;
|
|
475
|
+
}
|
|
476
|
+
const get = (n) => header(req.headers, n);
|
|
477
|
+
if (!reason && required && matchesEither(required, p) && !fresh && !isPreflight(req.method, get)) {
|
|
478
|
+
if (health.failOpen) log.debug(`require not enforced for ${p.decoded}: Reguard is ${health.state}`);
|
|
479
|
+
else {
|
|
480
|
+
const now = Date.now();
|
|
481
|
+
let r = browser ? refresh.get(`${browser.sid}:${browser.exp}`) : void 0;
|
|
482
|
+
if (browser && !r) {
|
|
483
|
+
r = { until: now + blockCfg.refreshMs, left: blockCfg.refreshRequests };
|
|
484
|
+
refresh.set(`${browser.sid}:${browser.exp}`, r);
|
|
485
|
+
if (refresh.size > 5e4) {
|
|
486
|
+
for (const [k, x] of refresh) if (x.until < now) refresh.delete(k);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
if (r && now <= r.until && r.left > 0) r.left--;
|
|
490
|
+
else {
|
|
491
|
+
const k = visitorOf(req);
|
|
492
|
+
const g = k ? grace.get(k) : void 0;
|
|
493
|
+
if (g && now - g.at <= blockCfg.graceMs && g.left > 0) g.left--;
|
|
494
|
+
else reason = "require";
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
if (reason) {
|
|
499
|
+
const d = decide(req, reason, p, v);
|
|
500
|
+
if (!d.dryRun || !req.reguardDecision) {
|
|
501
|
+
if (!d.dryRun) injection?.cancel();
|
|
502
|
+
if (act(req, res, d)) return;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
if (required && !matchesEither(required, p) && req.method !== "HEAD" && wantsPage(get)) {
|
|
506
|
+
const k = visitorOf(req);
|
|
507
|
+
if (k)
|
|
508
|
+
onHeaders(res, (status, contentType) => {
|
|
509
|
+
if (!/^\s*text\/html/i.test(contentType) || status >= 300 && status < 400 || status === 204) return;
|
|
510
|
+
const g = grace.get(k) ?? { at: 0, left: 0, pages: 0 };
|
|
511
|
+
g.pages = fresh ? 0 : g.pages + 1;
|
|
512
|
+
g.at = Date.now();
|
|
513
|
+
g.left = g.pages <= blockCfg.gracePages ? blockCfg.graceRequests : 0;
|
|
514
|
+
grace.set(k, g);
|
|
515
|
+
if (grace.size > 5e4) {
|
|
516
|
+
for (const [key2, x] of grace) if (Date.now() - x.at > 10 * 6e4) grace.delete(key2);
|
|
517
|
+
}
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
next();
|
|
522
|
+
},
|
|
523
|
+
() => {
|
|
524
|
+
next();
|
|
525
|
+
}
|
|
526
|
+
);
|
|
527
|
+
});
|
|
528
|
+
const blocking = !blockCfg ? "off" : allDry ? "dry run" : blockCfg.dryRun.size ? "partial dry run" : "on";
|
|
529
|
+
Object.defineProperty(middleware, "site", { value: site });
|
|
530
|
+
middleware.scriptTag = (opts) => renderScriptTag(tagSettings, opts?.nonce);
|
|
531
|
+
middleware.status = () => ({
|
|
532
|
+
enabled: true,
|
|
533
|
+
site,
|
|
534
|
+
keyFingerprint: keyFingerprint(parsed.secret),
|
|
535
|
+
collector: o.collect.requests ? health.state : "off",
|
|
536
|
+
since: health.since,
|
|
537
|
+
...health.lastError ? { lastError: health.lastError } : {},
|
|
538
|
+
failOpen: health.failOpen,
|
|
539
|
+
queued: core.queued(),
|
|
540
|
+
blocking
|
|
541
|
+
});
|
|
542
|
+
middleware.flush = core.flush;
|
|
543
|
+
middleware.close = async () => {
|
|
544
|
+
clearInterval(dryTimer);
|
|
545
|
+
await core.close();
|
|
546
|
+
};
|
|
547
|
+
log.debug(
|
|
548
|
+
`on for site ${site} (key v${parsed.version ?? "?"}, fingerprint ${keyFingerprint(parsed.secret)}${secrets.length > 1 ? ", plus the previous key" : ""}); collector ${collector}; blocking ${blocking}${blockCfg?.dryRun.size && !allDry ? ` (dry run: ${[...blockCfg.dryRun].join(", ")})` : ""}; client address ${typeof o.clientIp === "function" ? "custom" : JSON.stringify(o.clientIp)}${platform ? ` (host: ${platform})` : ""}; source maps ${denyMaps ? "denied" : "allowed"}`
|
|
549
|
+
);
|
|
550
|
+
return middleware;
|
|
551
|
+
}
|
|
552
|
+
var index_default = reguard;
|
|
553
|
+
function safeIf(fn, req, name, log) {
|
|
554
|
+
if (!fn) return false;
|
|
555
|
+
try {
|
|
556
|
+
return fn(req) === true;
|
|
557
|
+
} catch (e) {
|
|
558
|
+
log.once(`${name}-threw`, "warn", `${name} threw (${errorText(e)}): treated as false`);
|
|
559
|
+
return false;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
function onHeaders(res, cb) {
|
|
563
|
+
const writeHead = res.writeHead;
|
|
564
|
+
let done = false;
|
|
565
|
+
res.writeHead = function(...a) {
|
|
566
|
+
const out = writeHead.apply(this, a);
|
|
567
|
+
if (!done) {
|
|
568
|
+
done = true;
|
|
569
|
+
let contentType = String(res.getHeader("content-type") ?? "");
|
|
570
|
+
if (!contentType) {
|
|
571
|
+
const h = a.find((x, i) => i > 0 && x !== null && typeof x === "object");
|
|
572
|
+
if (Array.isArray(h)) {
|
|
573
|
+
for (let i = 0; i + 1 < h.length; i += 2) if (String(h[i]).toLowerCase() === "content-type") contentType = String(h[i + 1]);
|
|
574
|
+
} else if (h) {
|
|
575
|
+
for (const [k, v] of Object.entries(h)) if (k.toLowerCase() === "content-type") contentType = String(v);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
try {
|
|
579
|
+
cb(res.statusCode, contentType);
|
|
580
|
+
} catch {
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return out;
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
function injectTag(req, res, settings) {
|
|
587
|
+
let mode = "undecided";
|
|
588
|
+
let held = [];
|
|
589
|
+
let tag = Buffer.alloc(0);
|
|
590
|
+
const origWrite = res.write.bind(res);
|
|
591
|
+
const origEnd = res.end.bind(res);
|
|
592
|
+
const origWriteHead = res.writeHead.bind(res);
|
|
593
|
+
const decide = () => {
|
|
594
|
+
if (mode !== "undecided") return;
|
|
595
|
+
const ct = String(res.getHeader("content-type") ?? "");
|
|
596
|
+
const html = /^\s*text\/html/i.test(ct) && !/charset\s*=\s*"?utf-16/i.test(ct) && !res.getHeader("content-encoding") && !res.getHeader("content-range") && req.method !== "HEAD" && ![204, 206, 304].includes(res.statusCode);
|
|
597
|
+
mode = html ? "scan" : "pass";
|
|
598
|
+
if (html) {
|
|
599
|
+
res.removeHeader("content-length");
|
|
600
|
+
const csp = res.getHeader("content-security-policy");
|
|
601
|
+
tag = Buffer.from(renderScriptTag(settings, cspNonce(Array.isArray(csp) ? csp.join(", ") : csp === void 0 ? void 0 : String(csp))));
|
|
602
|
+
}
|
|
603
|
+
};
|
|
604
|
+
const toBuffer = (chunk, encoding) => typeof chunk === "string" ? Buffer.from(chunk, typeof encoding === "string" ? encoding : "utf8") : chunk instanceof Uint8Array ? Buffer.from(chunk) : null;
|
|
605
|
+
const release = (final) => {
|
|
606
|
+
const buf = held.length === 1 ? held[0] : Buffer.concat(held);
|
|
607
|
+
const text = buf.toString("latin1");
|
|
608
|
+
const lower = text.toLowerCase();
|
|
609
|
+
const headClose = lower.search(/<\/head[\t\n\f\r >]/);
|
|
610
|
+
if (headClose === -1 && !final && buf.length < SCAN_LIMIT) return null;
|
|
611
|
+
mode = "pass";
|
|
612
|
+
held = [];
|
|
613
|
+
const head = headClose === -1 ? lower : lower.slice(0, headClose);
|
|
614
|
+
if (head.includes("/_s/sdk") || head.includes("re-detect.js")) return buf;
|
|
615
|
+
const open = /<head(?:\s[^>]*)?>/i.exec(text);
|
|
616
|
+
const at = open && (headClose === -1 || open.index < headClose) ? open.index + open[0].length : headClose;
|
|
617
|
+
return at === -1 ? buf : Buffer.concat([buf.subarray(0, at), tag, buf.subarray(at)]);
|
|
618
|
+
};
|
|
619
|
+
const r = res;
|
|
620
|
+
r.writeHead = (statusCode, ...rest) => {
|
|
621
|
+
const reason = typeof rest[0] === "string" ? rest[0] : void 0;
|
|
622
|
+
const hdrs = reason !== void 0 ? rest[1] : rest[0];
|
|
623
|
+
if (Array.isArray(hdrs)) {
|
|
624
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
625
|
+
for (let i = 0; i + 1 < hdrs.length; i += 2) {
|
|
626
|
+
const name = String(hdrs[i]);
|
|
627
|
+
const g = grouped.get(name.toLowerCase()) ?? { name, values: [] };
|
|
628
|
+
g.values.push(String(hdrs[i + 1]));
|
|
629
|
+
grouped.set(name.toLowerCase(), g);
|
|
630
|
+
}
|
|
631
|
+
for (const g of grouped.values()) res.setHeader(g.name, g.values.length === 1 ? g.values[0] : g.values);
|
|
632
|
+
} else if (hdrs && typeof hdrs === "object") {
|
|
633
|
+
for (const [k, v] of Object.entries(hdrs)) if (v !== void 0) res.setHeader(k, v);
|
|
634
|
+
}
|
|
635
|
+
if (typeof statusCode === "number") res.statusCode = statusCode;
|
|
636
|
+
decide();
|
|
637
|
+
return reason !== void 0 ? origWriteHead(res.statusCode, reason) : origWriteHead(res.statusCode);
|
|
638
|
+
};
|
|
639
|
+
r.write = (chunk, encoding, cb) => {
|
|
640
|
+
decide();
|
|
641
|
+
if (mode !== "scan") return origWrite(chunk, encoding, cb);
|
|
642
|
+
const callback = typeof encoding === "function" ? encoding : cb;
|
|
643
|
+
const b = toBuffer(chunk, encoding);
|
|
644
|
+
if (b) held.push(b);
|
|
645
|
+
const out = release(false);
|
|
646
|
+
if (out === null) {
|
|
647
|
+
if (typeof callback === "function") process.nextTick(callback);
|
|
648
|
+
return true;
|
|
649
|
+
}
|
|
650
|
+
return typeof callback === "function" ? origWrite(out, callback) : origWrite(out);
|
|
651
|
+
};
|
|
652
|
+
r.end = (chunk, encoding, cb) => {
|
|
653
|
+
decide();
|
|
654
|
+
if (mode !== "scan") return origEnd(chunk, encoding, cb);
|
|
655
|
+
const callback = [chunk, encoding, cb].find((x) => typeof x === "function");
|
|
656
|
+
if (typeof chunk !== "function" && chunk != null) {
|
|
657
|
+
const b = toBuffer(chunk, encoding);
|
|
658
|
+
if (b) held.push(b);
|
|
659
|
+
}
|
|
660
|
+
const out = release(true) ?? Buffer.alloc(0);
|
|
661
|
+
return callback ? origEnd(out, callback) : origEnd(out);
|
|
662
|
+
};
|
|
663
|
+
return {
|
|
664
|
+
cancel() {
|
|
665
|
+
if (mode === "undecided") mode = "pass";
|
|
666
|
+
}
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
function secureRequest(req) {
|
|
670
|
+
const proto = header(req.headers, "x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
|
|
671
|
+
if (proto === "https" || req.socket?.encrypted) return true;
|
|
672
|
+
const host = (header(req.headers, "host") ?? "").toLowerCase().replace(/:\d+$/, "");
|
|
673
|
+
if (host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host.endsWith(".localhost")) return true;
|
|
674
|
+
if (proto === "http") return false;
|
|
675
|
+
return void 0;
|
|
676
|
+
}
|
|
677
|
+
function header(h, name) {
|
|
678
|
+
const v = h[name];
|
|
679
|
+
return Array.isArray(v) ? v.join(", ") : v;
|
|
680
|
+
}
|
|
681
|
+
var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "host", "content-length"]);
|
|
682
|
+
function toArrayBuffer(b) {
|
|
683
|
+
const ab = new ArrayBuffer(b.byteLength);
|
|
684
|
+
new Uint8Array(ab).set(b);
|
|
685
|
+
return ab;
|
|
686
|
+
}
|
|
687
|
+
function createReDetect(opts, wiring = {}) {
|
|
688
|
+
const prefix = (opts.prefix ?? "/_s").replace(/\/$/, "");
|
|
689
|
+
const collector = opts.collector.replace(/\/$/, "");
|
|
690
|
+
const secret = parseSiteKey(opts.siteKey)?.secret ?? opts.siteKey;
|
|
691
|
+
const doFetch = opts.fetch ?? fetch;
|
|
692
|
+
const onError = opts.onError ?? (() => {
|
|
693
|
+
});
|
|
694
|
+
const log = wiring.log ?? makeLog(void 0, false);
|
|
695
|
+
const health = wiring.health ?? new Health(log);
|
|
696
|
+
const timeoutMs = wiring.timeoutMs ?? 1e4;
|
|
697
|
+
const addressFor = (req) => wiring.address?.(req) ?? addressOf(req);
|
|
698
|
+
const collect = resolveCollect(opts.collect, (m) => log.once(`collect:${m}`, "warn", m));
|
|
699
|
+
const skipped = skipMatcher(collect.skip);
|
|
700
|
+
const forward = collect.requests;
|
|
701
|
+
const siteTag = siteTagOf(opts.site, secret);
|
|
702
|
+
const maxQueue = opts.maxQueue ?? 5e3;
|
|
703
|
+
const hash = (s) => createHmac("sha256", secret).update(s).digest("base64url").slice(0, 16);
|
|
704
|
+
const queue = [];
|
|
705
|
+
let inflight;
|
|
706
|
+
const pushed = /* @__PURE__ */ new Map();
|
|
707
|
+
const PUSHED_TTL_MS = 10 * 6e4;
|
|
708
|
+
const isClaims = (c) => Array.isArray(c) && c.every((x) => !!x && typeof x.rule === "string" && typeof x.label === "string" && typeof x.stage === "string");
|
|
709
|
+
const absorb = (body) => {
|
|
710
|
+
const f = body?.flagged;
|
|
711
|
+
if (!f) return;
|
|
712
|
+
const now = Date.now();
|
|
713
|
+
for (const x of f.sessions ?? []) if (typeof x.sid === "string" && isClaims(x.claims)) pushed.set(`s:${x.sid}`, { claims: x.claims, until: now + PUSHED_TTL_MS });
|
|
714
|
+
for (const x of f.visitors ?? []) if (typeof x.visitor === "string" && isClaims(x.claims)) pushed.set(`v:${x.visitor}`, { claims: x.claims, until: now + PUSHED_TTL_MS });
|
|
715
|
+
if (pushed.size > 5e4) {
|
|
716
|
+
for (const [k, e] of pushed) if (e.until < now) pushed.delete(k);
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
const pushedFor = (req, verified = false) => {
|
|
720
|
+
if (!pushed.size) return null;
|
|
721
|
+
const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
|
|
722
|
+
const a = addressFor(req);
|
|
723
|
+
const address = collect.addresses !== "off" && !verified && !a.internal ? a.address : "";
|
|
724
|
+
const now = Date.now();
|
|
725
|
+
const claims = [];
|
|
726
|
+
for (const k of [sid ? `s:${sid}` : "", address ? `v:${visitorHash(secret, address)}` : ""]) {
|
|
727
|
+
const e = k ? pushed.get(k) : void 0;
|
|
728
|
+
if (e && e.until > now) claims.push(...e.claims);
|
|
729
|
+
}
|
|
730
|
+
return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now) : null;
|
|
731
|
+
};
|
|
732
|
+
const flush = async () => {
|
|
733
|
+
while (queue.length) {
|
|
734
|
+
if (!health.canSend()) {
|
|
735
|
+
queue.length = 0;
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
const events = queue.splice(0, 500);
|
|
739
|
+
try {
|
|
740
|
+
const res = await doFetch(`${collector}/v1/server`, {
|
|
741
|
+
method: "POST",
|
|
742
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${opts.siteKey}` },
|
|
743
|
+
body: JSON.stringify({ site: opts.site, collect: collectReport(collect), events }),
|
|
744
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
745
|
+
});
|
|
746
|
+
if (res.status === 429) {
|
|
747
|
+
health.paused();
|
|
748
|
+
onError(new Error("collector answered 429 to /v1/server (monthly usage limit): summaries paused for an hour"));
|
|
749
|
+
queue.length = 0;
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
if (res.status === 401 || res.status === 403) {
|
|
753
|
+
health.rejected(res.status);
|
|
754
|
+
onError(new Error(`collector answered ${res.status} to /v1/server: the site key was rejected`));
|
|
755
|
+
queue.length = 0;
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
if (res.status >= 500) {
|
|
759
|
+
health.failing(`HTTP ${res.status}`);
|
|
760
|
+
onError(new Error(`collector answered ${res.status} to /v1/server`));
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
if (!res.ok) {
|
|
764
|
+
log.once(`server-${res.status}`, "error", `Reguard refused a batch of summaries (HTTP ${res.status}): please report this with your reguard version`);
|
|
765
|
+
onError(new Error(`collector answered ${res.status} to /v1/server`));
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
health.ok();
|
|
769
|
+
absorb(await res.json().catch(() => null));
|
|
770
|
+
} catch (e) {
|
|
771
|
+
health.failing(e?.name === "TimeoutError" ? `no answer within ${timeoutMs} ms` : errorText(e));
|
|
772
|
+
onError(e);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
};
|
|
776
|
+
const flushSoon = () => {
|
|
777
|
+
if (queue.length && !inflight) inflight = flush().finally(() => inflight = void 0);
|
|
778
|
+
};
|
|
779
|
+
const timer = setInterval(flushSoon, opts.flushIntervalMs ?? 2e3);
|
|
780
|
+
timer.unref?.();
|
|
781
|
+
const readVerdict = (cookieHeader) => readVerdictFrom(secret, opts.site, cookieHeader);
|
|
782
|
+
function record(req, res, started, bytes) {
|
|
783
|
+
try {
|
|
784
|
+
const h = req.headers;
|
|
785
|
+
const sid = cookieValue(header(h, "cookie"), SESSION_COOKIE);
|
|
786
|
+
const url = req.originalUrl ?? req.url ?? "/";
|
|
787
|
+
const secure = secureRequest(req);
|
|
788
|
+
const decision = wiring.decided?.(req);
|
|
789
|
+
const pace = PACED.get(req);
|
|
790
|
+
if (!sid && !opts.includeSessionless && !decision) {
|
|
791
|
+
if (opts.watchSessionless === false || collect.addresses === "off") return;
|
|
792
|
+
const watch = watchworthy({
|
|
793
|
+
userAgent: header(h, "user-agent") ?? "",
|
|
794
|
+
acceptLanguage: header(h, "accept-language"),
|
|
795
|
+
accept: header(h, "accept"),
|
|
796
|
+
secFetchMode: header(h, "sec-fetch-mode"),
|
|
797
|
+
secChUa: header(h, "sec-ch-ua"),
|
|
798
|
+
secure,
|
|
799
|
+
path: url.split("?")[0] ?? url,
|
|
800
|
+
status: res.statusCode
|
|
801
|
+
});
|
|
802
|
+
if (!watch) return;
|
|
803
|
+
}
|
|
804
|
+
const a = addressFor(req);
|
|
805
|
+
const visitor = !sid && a.address && collect.addresses !== "off" ? visitorHash(secret, a.address) : void 0;
|
|
806
|
+
const contentType = String(res.getHeader("content-type") ?? "");
|
|
807
|
+
const requestBytes = Number(header(h, "content-length") ?? 0) || 0;
|
|
808
|
+
const speculative = isSpeculativeHeaders((n) => header(h, n));
|
|
809
|
+
let exchange;
|
|
810
|
+
if (!speculative && isApiLike(url, contentType, requestBytes)) {
|
|
811
|
+
const body = req.body;
|
|
812
|
+
const bodyText = typeof body === "string" ? body : body && typeof body === "object" ? JSON.stringify(body) : "";
|
|
813
|
+
const requestContentType = typeof body === "object" && body ? "application/json" : header(h, "content-type") ?? "";
|
|
814
|
+
exchange = describeExchange(hash, {
|
|
815
|
+
method: req.method ?? "GET",
|
|
816
|
+
url,
|
|
817
|
+
requestContentType,
|
|
818
|
+
requestBody: bodyText.slice(0, 65536),
|
|
819
|
+
requestBytes,
|
|
820
|
+
status: res.statusCode,
|
|
821
|
+
responseContentType: contentType,
|
|
822
|
+
responseBytes: bytes()
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
const order = [];
|
|
826
|
+
for (let i = 0; i < req.rawHeaders.length; i += 2) order.push(String(req.rawHeaders[i]).toLowerCase());
|
|
827
|
+
const picked = {};
|
|
828
|
+
for (const n of ["rsc", "next-router-prefetch", "sec-purpose", "purpose"]) {
|
|
829
|
+
const v = header(h, n);
|
|
830
|
+
if (v !== void 0) picked[n] = v;
|
|
831
|
+
}
|
|
832
|
+
if (queue.length >= maxQueue) return;
|
|
833
|
+
const pages = collect.pages;
|
|
834
|
+
queue.push({
|
|
835
|
+
sid,
|
|
836
|
+
at: started,
|
|
837
|
+
method: req.method ?? "GET",
|
|
838
|
+
url: pages === "masked" ? privateUrl(url) : "",
|
|
839
|
+
...pages !== "off" ? { item: hash(`path:${url.split("?")[0] ?? url}`) } : {},
|
|
840
|
+
...pages !== "masked" ? { traits: pathTraits(url, header(h, "rsc") === "1") } : {},
|
|
841
|
+
status: res.statusCode,
|
|
842
|
+
headers: picked,
|
|
843
|
+
client: {
|
|
844
|
+
ua: header(h, "user-agent") ?? "",
|
|
845
|
+
accept: header(h, "accept") ?? "",
|
|
846
|
+
acceptLanguage: header(h, "accept-language") ?? "",
|
|
847
|
+
secFetchMode: header(h, "sec-fetch-mode"),
|
|
848
|
+
secFetchSite: header(h, "sec-fetch-site"),
|
|
849
|
+
secFetchDest: header(h, "sec-fetch-dest"),
|
|
850
|
+
secChUa: header(h, "sec-ch-ua"),
|
|
851
|
+
hasCookie: Boolean(header(h, "cookie")),
|
|
852
|
+
hasReferer: Boolean(header(h, "referer")),
|
|
853
|
+
httpVersion: req.httpVersion,
|
|
854
|
+
order,
|
|
855
|
+
...secure !== void 0 ? { secure } : {}
|
|
856
|
+
},
|
|
857
|
+
...visitor ? { visitor } : {},
|
|
858
|
+
...exchange ? { exchange: withoutEndpoint(exchange, pages, hash) } : {},
|
|
859
|
+
...pace ? { pace } : {},
|
|
860
|
+
...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
|
|
861
|
+
...a.internal ? { internal: true } : {}
|
|
862
|
+
});
|
|
863
|
+
if (decision) flushSoon();
|
|
864
|
+
} catch (e) {
|
|
865
|
+
onError(e);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
function track(req, res) {
|
|
869
|
+
const started = Date.now();
|
|
870
|
+
const p = canonicalPath(req.originalUrl ?? req.url ?? "/");
|
|
871
|
+
if (!forward || isReguardPath(p.decoded) || p.raw.startsWith(`${prefix}/`) || matchesEither(skipped, p) || matchesEither((x) => !!opts.ignore?.(x), p) || wiring.ignored?.(req, p)) return;
|
|
872
|
+
let n = 0;
|
|
873
|
+
const write = res.write.bind(res);
|
|
874
|
+
const end = res.end.bind(res);
|
|
875
|
+
const count = (chunk) => {
|
|
876
|
+
if (typeof chunk === "string") n += Buffer.byteLength(chunk);
|
|
877
|
+
else if (chunk instanceof Uint8Array) n += chunk.byteLength;
|
|
878
|
+
};
|
|
879
|
+
res.write = (...a) => {
|
|
880
|
+
count(a[0]);
|
|
881
|
+
return write(...a);
|
|
882
|
+
};
|
|
883
|
+
res.end = (...a) => {
|
|
884
|
+
if (typeof a[0] !== "function") count(a[0]);
|
|
885
|
+
return end(...a);
|
|
886
|
+
};
|
|
887
|
+
res.once("finish", () => record(req, res, started, () => n));
|
|
888
|
+
}
|
|
889
|
+
function middleware() {
|
|
890
|
+
return (req, res, next) => {
|
|
891
|
+
track(req, res);
|
|
892
|
+
readVerdict(header(req.headers, "cookie")).then(
|
|
893
|
+
(v) => {
|
|
894
|
+
req.reDetect = v;
|
|
895
|
+
req.reguard = v;
|
|
896
|
+
next();
|
|
897
|
+
},
|
|
898
|
+
() => {
|
|
899
|
+
req.reDetect = null;
|
|
900
|
+
req.reguard = null;
|
|
901
|
+
next();
|
|
902
|
+
}
|
|
903
|
+
);
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
function route() {
|
|
907
|
+
return async (req, res) => {
|
|
908
|
+
try {
|
|
909
|
+
const full = req.originalUrl ?? req.url ?? "/";
|
|
910
|
+
const rest = full.startsWith(prefix) ? full.slice(prefix.length) : req.url ?? "/";
|
|
911
|
+
const headers = headersForReguard(req, secret, siteTag, collect);
|
|
912
|
+
for (const k of HOP_BY_HOP) headers.delete(k);
|
|
913
|
+
let body;
|
|
914
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
915
|
+
const chunks = [];
|
|
916
|
+
let size = 0;
|
|
917
|
+
for await (const c of req) {
|
|
918
|
+
size += c.length;
|
|
919
|
+
if (size > 1048576) throw new Error("request body over 1 MiB");
|
|
920
|
+
chunks.push(c);
|
|
921
|
+
}
|
|
922
|
+
body = Buffer.concat(chunks);
|
|
923
|
+
}
|
|
924
|
+
const r = await doFetch(`${collector}${rest}`, { method: req.method, headers, body: body ? toArrayBuffer(body) : void 0, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
|
|
925
|
+
res.statusCode = r.status;
|
|
926
|
+
r.headers.forEach((v, k) => {
|
|
927
|
+
if (!["content-encoding", "content-length", "transfer-encoding", "connection", "set-cookie"].includes(k)) res.setHeader(k, v);
|
|
928
|
+
});
|
|
929
|
+
const cookies = r.headers.getSetCookie?.() ?? [];
|
|
930
|
+
if (cookies.length) res.setHeader("set-cookie", cookies);
|
|
931
|
+
res.end(Buffer.from(await r.arrayBuffer()));
|
|
932
|
+
} catch (e) {
|
|
933
|
+
onError(e);
|
|
934
|
+
if (!res.headersSent) res.statusCode = 502;
|
|
935
|
+
res.end();
|
|
936
|
+
}
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
return {
|
|
940
|
+
middleware,
|
|
941
|
+
route,
|
|
942
|
+
track,
|
|
943
|
+
readVerdict,
|
|
944
|
+
/** Claims the collector pushed back for this request's session or visitor (null: none). */
|
|
945
|
+
pushedFor,
|
|
946
|
+
/** For fetch-style handlers (Next.js route handlers, edge functions): pass `request.headers`. */
|
|
947
|
+
readVerdictFromHeaders: (headers) => readVerdict(headers.get("cookie")),
|
|
948
|
+
/** Summaries waiting to be sent. */
|
|
949
|
+
queued: () => queue.length,
|
|
950
|
+
/** Send queued summaries now (e.g. before shutdown). */
|
|
951
|
+
flush: async () => {
|
|
952
|
+
await inflight;
|
|
953
|
+
await flush();
|
|
954
|
+
},
|
|
955
|
+
close: async () => {
|
|
956
|
+
clearInterval(timer);
|
|
957
|
+
await inflight;
|
|
958
|
+
await flush();
|
|
959
|
+
}
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
export {
|
|
964
|
+
keyFingerprint,
|
|
965
|
+
defaultBlockResponse,
|
|
966
|
+
reguard,
|
|
967
|
+
index_default,
|
|
968
|
+
createReDetect
|
|
969
|
+
};
|