reguard 0.8.1 → 0.10.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 +25 -3
- package/dist/chunks/{chunk-PA46KSOR.js → chunk-2N762ZXU.js} +235 -44
- package/dist/chunks/{chunk-3AYS7WSY.js → chunk-4RD66ACT.js} +81 -8
- package/dist/chunks/{chunk-U54IP6G4.js → chunk-GOT54CF4.js} +61 -40
- package/dist/chunks/{chunk-KNKCUJL3.js → chunk-RTCPK4MF.js} +102 -41
- package/dist/cjs/fastify.cjs +305 -93
- package/dist/cjs/fetch.cjs +347 -87
- package/dist/cjs/index.cjs +386 -86
- package/dist/cjs/next.cjs +366 -103
- package/dist/cjs/testing.cjs +28 -100
- package/dist/fastify.js +4 -12
- package/dist/fetch.js +14 -5
- package/dist/index.js +13 -5
- package/dist/next.js +33 -23
- package/dist/testing.js +9 -3
- package/dist/types/node/src/api.d.ts +139 -0
- package/dist/types/node/src/core.d.ts +8 -1
- package/dist/types/node/src/fastify.d.ts +15 -7
- package/dist/types/node/src/fetch.d.ts +12 -2
- package/dist/types/node/src/index.d.ts +6 -0
- package/dist/types/node/src/next.d.ts +39 -17
- package/dist/types/node/src/testing.d.ts +11 -0
- package/dist/types/shared/src/address.d.ts +25 -6
- package/dist/types/shared/src/collect.d.ts +7 -1
- package/dist/types/shared/src/index.d.ts +14 -0
- package/dist/types/shared/src/paths.d.ts +6 -2
- package/dist/types/shared/src/tools.d.ts +10 -0
- package/dist/types/shared/src/verdict.d.ts +6 -0
- package/dist/types/shared/src/webhooks.d.ts +32 -0
- package/dist/types-cjs/node/src/api.d.cts +139 -0
- package/dist/types-cjs/node/src/core.d.cts +8 -1
- package/dist/types-cjs/node/src/fastify.d.cts +15 -7
- package/dist/types-cjs/node/src/fetch.d.cts +12 -2
- package/dist/types-cjs/node/src/index.d.cts +6 -0
- package/dist/types-cjs/node/src/next.d.cts +39 -17
- package/dist/types-cjs/node/src/testing.d.cts +11 -0
- package/dist/types-cjs/shared/src/address.d.cts +25 -6
- package/dist/types-cjs/shared/src/collect.d.cts +7 -1
- package/dist/types-cjs/shared/src/index.d.cts +14 -0
- package/dist/types-cjs/shared/src/paths.d.cts +6 -2
- package/dist/types-cjs/shared/src/tools.d.cts +10 -0
- package/dist/types-cjs/shared/src/verdict.d.cts +6 -0
- package/dist/types-cjs/shared/src/webhooks.d.cts +32 -0
- package/package.json +3 -2
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
BLOCK_REASONS,
|
|
3
3
|
Health,
|
|
4
|
+
ReguardApiError,
|
|
4
5
|
ReguardConfigError,
|
|
5
6
|
checkBlock,
|
|
6
7
|
checkBoolean,
|
|
@@ -11,13 +12,15 @@ import {
|
|
|
11
12
|
checkFunction,
|
|
12
13
|
checkLogger,
|
|
13
14
|
checkNumber,
|
|
14
|
-
makeLog
|
|
15
|
-
|
|
15
|
+
makeLog,
|
|
16
|
+
reguardApi
|
|
17
|
+
} from "./chunk-4RD66ACT.js";
|
|
16
18
|
import {
|
|
17
19
|
Allowance,
|
|
18
20
|
BENIGN_TOOL_FAMILIES,
|
|
19
21
|
RETRY_AFTER,
|
|
20
22
|
SESSION_COOKIE,
|
|
23
|
+
addressKey,
|
|
21
24
|
canonicalPath,
|
|
22
25
|
collectReport,
|
|
23
26
|
collectorBase,
|
|
@@ -37,7 +40,9 @@ import {
|
|
|
37
40
|
normalizeIp,
|
|
38
41
|
parseSiteKey,
|
|
39
42
|
pathTraits,
|
|
43
|
+
presentsAsBrowser,
|
|
40
44
|
privateUrl,
|
|
45
|
+
protectionMatcher,
|
|
41
46
|
pushedVerdict,
|
|
42
47
|
readVerdictFrom,
|
|
43
48
|
renderScriptTag,
|
|
@@ -47,7 +52,7 @@ import {
|
|
|
47
52
|
toolOf,
|
|
48
53
|
wantsPage,
|
|
49
54
|
watchworthy
|
|
50
|
-
} from "./chunk-
|
|
55
|
+
} from "./chunk-2N762ZXU.js";
|
|
51
56
|
|
|
52
57
|
// src/fetch.ts
|
|
53
58
|
var OPTION_KEYS = [
|
|
@@ -111,7 +116,7 @@ function reguardFetch(options = {}) {
|
|
|
111
116
|
checkFunction(options.fetch, "fetch");
|
|
112
117
|
checkFunction(options.onError, "onError");
|
|
113
118
|
const log = makeLog(checkLogger(options.logger), checkBoolean(options.debug, "debug") ?? /^(?:1|true|yes)$/i.test(envValue("REGUARD_DEBUG") ?? ""));
|
|
114
|
-
const ignore = options.ignore?.length ?
|
|
119
|
+
const ignore = options.ignore?.length ? protectionMatcher(options.ignore) : void 0;
|
|
115
120
|
const key = (options.key ?? envValue("REGUARD_KEY"))?.trim();
|
|
116
121
|
const parsed = parseSiteKey(key);
|
|
117
122
|
const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
|
|
@@ -131,6 +136,12 @@ function reguardFetch(options = {}) {
|
|
|
131
136
|
decision: () => null,
|
|
132
137
|
scriptTag: () => "",
|
|
133
138
|
flush: async () => {
|
|
139
|
+
},
|
|
140
|
+
visitor: async () => {
|
|
141
|
+
throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
|
|
142
|
+
},
|
|
143
|
+
events: async () => {
|
|
144
|
+
throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
|
|
134
145
|
}
|
|
135
146
|
};
|
|
136
147
|
}
|
|
@@ -139,12 +150,13 @@ function reguardFetch(options = {}) {
|
|
|
139
150
|
const prev = parseSiteKey((options.previousKey ?? envValue("REGUARD_KEY_PREVIOUS"))?.trim());
|
|
140
151
|
if (prev?.site === site && prev.secret !== parsed.secret) secrets.push(prev.secret);
|
|
141
152
|
const collector = collectorBase(options.collector ?? envValue("REGUARD_COLLECTOR"));
|
|
153
|
+
const api = reguardApi({ key, collector, fetch: doFetch, timeoutMs });
|
|
142
154
|
const platform = options.platform ?? detectPlatform(typeof process !== "undefined" ? process.env : void 0) ?? (typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" ? "workers" : null);
|
|
143
155
|
const health = new Health(log);
|
|
144
156
|
const allDry = !block || BLOCK_REASONS.every((r) => block.dryRun.has(r));
|
|
145
157
|
const denyMaps = (options.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
|
|
146
158
|
const allowList = block?.allow.length ? skipMatcher(block.allow) : void 0;
|
|
147
|
-
const skipped =
|
|
159
|
+
const skipped = protectionMatcher(collect.skip);
|
|
148
160
|
const tagSettings = { site, collect, cookieDomain };
|
|
149
161
|
const pace = block?.pace;
|
|
150
162
|
const pages = pace ? new Allowance(pace.documents.burst, pace.documents.perSecond / 1e3, 5e4) : void 0;
|
|
@@ -190,8 +202,9 @@ function reguardFetch(options = {}) {
|
|
|
190
202
|
health.ok();
|
|
191
203
|
const f = (await res.json().catch(() => null))?.flagged;
|
|
192
204
|
const now = Date.now();
|
|
193
|
-
|
|
194
|
-
for (const x of f?.
|
|
205
|
+
const vidOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
|
|
206
|
+
for (const x of f?.sessions ?? []) if (typeof x.sid === "string" && Array.isArray(x.claims)) pushed.set(`s:${x.sid}`, { claims: x.claims, until: now + 6e5, vid: vidOf(x.vid) });
|
|
207
|
+
for (const x of f?.visitors ?? []) if (typeof x.visitor === "string" && Array.isArray(x.claims)) pushed.set(`v:${x.visitor}`, { claims: x.claims, until: now + 6e5, vid: vidOf(x.vid) });
|
|
195
208
|
if (pushed.size > 5e4) pushed.clear();
|
|
196
209
|
}
|
|
197
210
|
if (!res.ok) onError(new Error(`collector answered ${res.status} to /v1/server`));
|
|
@@ -202,11 +215,10 @@ function reguardFetch(options = {}) {
|
|
|
202
215
|
}
|
|
203
216
|
if (!health.canSend()) queue.length = 0;
|
|
204
217
|
};
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
if (!
|
|
208
|
-
|
|
209
|
-
waitUntil?.(inflight);
|
|
218
|
+
let lastUrgent = 0;
|
|
219
|
+
const flushSoon = (now = false) => {
|
|
220
|
+
if (queue.length && !inflight && (now || Date.now() - lastFlush >= flushIntervalMs || queue.length >= 100)) inflight = flush().finally(() => inflight = void 0);
|
|
221
|
+
return inflight;
|
|
210
222
|
};
|
|
211
223
|
const pushedFor = async (request, verified) => {
|
|
212
224
|
if (!pushed.size) return null;
|
|
@@ -215,12 +227,18 @@ function reguardFetch(options = {}) {
|
|
|
215
227
|
const now = Date.now();
|
|
216
228
|
const claims = [];
|
|
217
229
|
const k = [sid ? `s:${sid}` : ""];
|
|
218
|
-
|
|
230
|
+
const get = (n) => request.headers.get(n) ?? void 0;
|
|
231
|
+
const browser = presentsAsBrowser({ userAgent: get("user-agent") ?? "", acceptLanguage: get("accept-language"), accept: get("accept"), secFetchMode: get("sec-fetch-mode"), secFetchDest: get("sec-fetch-dest"), secChUa: get("sec-ch-ua") });
|
|
232
|
+
if (collect.addresses !== "off" && !verified && !a.internal && !browser && a.address) k.push(`v:${await hmac(parsed.secret, `visitor:${addressKey(a.address) || a.address}`, 22)}`);
|
|
233
|
+
let vid;
|
|
219
234
|
for (const x of k) {
|
|
220
235
|
const e = x ? pushed.get(x) : void 0;
|
|
221
|
-
if (e && e.until > now)
|
|
236
|
+
if (e && e.until > now) {
|
|
237
|
+
claims.push(...e.claims);
|
|
238
|
+
vid ??= e.vid;
|
|
239
|
+
}
|
|
222
240
|
}
|
|
223
|
-
return claims.length ? pushedVerdict(sid ?? "", site, claims, now) : null;
|
|
241
|
+
return claims.length ? pushedVerdict(sid ?? "", site, claims, now, vid) : null;
|
|
224
242
|
};
|
|
225
243
|
const proxy = async (request, p) => {
|
|
226
244
|
const url = new URL(request.url);
|
|
@@ -240,14 +258,11 @@ function reguardFetch(options = {}) {
|
|
|
240
258
|
if (sid && /^[\w-]{1,64}$/.test(sid)) headers.set("cookie", `${SESSION_COOKIE}=${sid}`);
|
|
241
259
|
headers.set("x-reguard-site", `${site}.${await hmac(parsed.secret, `prefix:${site}`, 16)}`);
|
|
242
260
|
const a = addressFor(request);
|
|
243
|
-
const value = collect.addresses === "off" || !a.address ? "-" : await hmac(parsed.secret, `visitor:${a.address}`, 22);
|
|
261
|
+
const value = collect.addresses === "off" || !a.address ? "-" : await hmac(parsed.secret, `visitor:${addressKey(a.address) || a.address}`, 22);
|
|
244
262
|
headers.set("x-reguard-visitor", `${value}.${await hmac(parsed.secret, `visitor-header:${value}`, 16)}`);
|
|
245
263
|
try {
|
|
246
264
|
const init = { method: request.method, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) };
|
|
247
|
-
if (request.method !== "GET" && request.method !== "HEAD" && request.body)
|
|
248
|
-
init.body = request.body;
|
|
249
|
-
init.duplex = "half";
|
|
250
|
-
}
|
|
265
|
+
if (request.method !== "GET" && request.method !== "HEAD" && request.body) init.body = await request.arrayBuffer();
|
|
251
266
|
const r = await doFetch(`${collector}${p.decoded}${url.search}`, init);
|
|
252
267
|
const out = new Headers();
|
|
253
268
|
r.headers.forEach((v, k) => {
|
|
@@ -279,7 +294,7 @@ function reguardFetch(options = {}) {
|
|
|
279
294
|
} catch (e) {
|
|
280
295
|
log.once("onBlock-threw", "warn", `block.onBlock threw: ${e?.message ?? e}`);
|
|
281
296
|
}
|
|
282
|
-
log.debug(`${d.dryRun ? "would block" : "blocked"} ${request.method} ${d.path}: ${d.reason}`);
|
|
297
|
+
log.debug(`${d.dryRun ? "would block" : "blocked"} ${request.method} ${d.path}: ${d.reason}${d.pace ? ` (${d.pace})` : ""} from ${d.clientIp}`);
|
|
283
298
|
if (d.dryRun) return void 0;
|
|
284
299
|
const respond = block.respond;
|
|
285
300
|
if (respond) {
|
|
@@ -299,9 +314,9 @@ function reguardFetch(options = {}) {
|
|
|
299
314
|
if (denyMaps && isSourceMapPath(p)) return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
|
|
300
315
|
const cookie = request.headers.get("cookie");
|
|
301
316
|
const pending = (async () => {
|
|
302
|
-
const
|
|
303
|
-
const pushedV = await pushedFor(request, !!
|
|
304
|
-
return { browser, pushed: pushedV, merged: mergeVerdicts(
|
|
317
|
+
const browser2 = await readVerdict(cookie);
|
|
318
|
+
const pushedV = await pushedFor(request, !!browser2);
|
|
319
|
+
return { browser: browser2, pushed: pushedV, merged: mergeVerdicts(browser2, pushedV) };
|
|
305
320
|
})();
|
|
306
321
|
verdicts.set(request, pending);
|
|
307
322
|
if (!block) return void 0;
|
|
@@ -314,10 +329,11 @@ function reguardFetch(options = {}) {
|
|
|
314
329
|
})();
|
|
315
330
|
if (allowed) return void 0;
|
|
316
331
|
const get = (n) => request.headers.get(n) ?? void 0;
|
|
317
|
-
|
|
332
|
+
const browser = presentsAsBrowser({ userAgent: get("user-agent") ?? "", acceptLanguage: get("accept-language"), accept: get("accept"), secFetchMode: get("sec-fetch-mode"), secFetchDest: get("sec-fetch-dest"), secChUa: get("sec-ch-ua") });
|
|
333
|
+
if (pages && !browser && (request.method === "GET" || request.method === "HEAD") && requestKind(p.decoded) === "document" && !isSpeculativeHeaders(get)) {
|
|
318
334
|
const tool = toolOf(get("user-agent"));
|
|
319
335
|
const a = addressFor(request);
|
|
320
|
-
if (!(tool && BENIGN_TOOL_FAMILIES.has(tool.family)) && a.address && !a.internal && !pages.take(a.address)) {
|
|
336
|
+
if (!(tool && BENIGN_TOOL_FAMILIES.has(tool.family)) && a.address && !a.internal && !pages.take(addressKey(a.address) || a.address)) {
|
|
321
337
|
const answered = await act(request, decide(request, "pace", p, null, "document"));
|
|
322
338
|
if (answered) return answered;
|
|
323
339
|
}
|
|
@@ -333,7 +349,7 @@ function reguardFetch(options = {}) {
|
|
|
333
349
|
};
|
|
334
350
|
const record = (request, response, ctx) => {
|
|
335
351
|
if (!collect.requests) return;
|
|
336
|
-
|
|
352
|
+
const task = (async () => {
|
|
337
353
|
try {
|
|
338
354
|
const url = new URL(request.url);
|
|
339
355
|
const p = canonicalPath(url.pathname);
|
|
@@ -342,18 +358,19 @@ function reguardFetch(options = {}) {
|
|
|
342
358
|
const sid = cookieValue(get("cookie"), SESSION_COOKIE);
|
|
343
359
|
const decision = decisions.get(request);
|
|
344
360
|
const target = `${url.pathname}${url.search}`;
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
if (!
|
|
361
|
+
const toolLike = () => watchworthy({ userAgent: get("user-agent") ?? "", acceptLanguage: get("accept-language"), accept: get("accept"), secFetchMode: get("sec-fetch-mode"), secChUa: get("sec-ch-ua"), secure: url.protocol === "https:" ? true : void 0, path: url.pathname, status: response?.status });
|
|
362
|
+
const tool = toolLike();
|
|
363
|
+
if (!decision) {
|
|
364
|
+
if (!sid && (options.watchSessionless === false || collect.addresses === "off" || !tool)) return;
|
|
365
|
+
if (sid && !response && !tool) return;
|
|
349
366
|
}
|
|
350
367
|
const a = addressFor(request);
|
|
351
368
|
const hash = (s) => hmac(parsed.secret, s, 16);
|
|
352
|
-
const contentType = response
|
|
353
|
-
const responseBytes = Number(response
|
|
369
|
+
const contentType = response?.headers.get("content-type") ?? "";
|
|
370
|
+
const responseBytes = Number(response?.headers.get("content-length") ?? 0) || 0;
|
|
354
371
|
const requestBytes = Number(get("content-length") ?? 0) || 0;
|
|
355
372
|
let exchange;
|
|
356
|
-
if (!isSpeculativeHeaders(get) && isApiLike(target, contentType, requestBytes)) {
|
|
373
|
+
if (response && !isSpeculativeHeaders(get) && isApiLike(target, contentType, requestBytes)) {
|
|
357
374
|
const input = { method: request.method, url: target, requestContentType: get("content-type") ?? "", requestBody: "", requestBytes, status: response.status, responseContentType: contentType, responseBytes };
|
|
358
375
|
const wanted = /* @__PURE__ */ new Set();
|
|
359
376
|
describeExchange((s) => (wanted.add(s), ""), input);
|
|
@@ -373,7 +390,7 @@ function reguardFetch(options = {}) {
|
|
|
373
390
|
url: collect.pages === "masked" ? privateUrl(target) : "",
|
|
374
391
|
...collect.pages !== "off" ? { item: await hash(`path:${url.pathname}`) } : {},
|
|
375
392
|
...collect.pages !== "masked" ? { traits: pathTraits(target, get("rsc") === "1") } : {},
|
|
376
|
-
status: response.status,
|
|
393
|
+
...response ? { status: response.status } : {},
|
|
377
394
|
headers: Object.fromEntries(["rsc", "next-router-prefetch", "sec-purpose", "purpose"].flatMap((n) => get(n) !== void 0 ? [[n, get(n)]] : [])),
|
|
378
395
|
client: {
|
|
379
396
|
ua: get("user-agent") ?? "",
|
|
@@ -387,26 +404,28 @@ function reguardFetch(options = {}) {
|
|
|
387
404
|
hasReferer: !!get("referer"),
|
|
388
405
|
...url.protocol === "https:" ? { secure: true } : {}
|
|
389
406
|
},
|
|
390
|
-
...!sid && a.address && collect.addresses !== "off" ? { visitor: await hmac(parsed.secret, `visitor:${a.address}`, 22) } : {},
|
|
407
|
+
...!sid && a.address && collect.addresses !== "off" ? { visitor: await hmac(parsed.secret, `visitor:${addressKey(a.address) || a.address}`, 22) } : {},
|
|
391
408
|
...exchange ? { exchange } : {},
|
|
392
409
|
...decision?.pace ? { pace: decision.pace } : {},
|
|
393
410
|
...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
|
|
394
411
|
...a.internal ? { internal: true } : {}
|
|
395
412
|
});
|
|
396
413
|
if (queue.length > 5e3) queue.splice(0, queue.length - 5e3);
|
|
397
|
-
const waitUntil = ctx?.waitUntil ? (p2) => ctx.waitUntil.call(ctx, p2) : void 0;
|
|
398
414
|
ensureTimer();
|
|
399
|
-
|
|
415
|
+
const urgent = !!decision || tool && Date.now() - lastUrgent >= 500;
|
|
416
|
+
if (urgent) lastUrgent = Date.now();
|
|
417
|
+
await flushSoon(urgent);
|
|
400
418
|
} catch (e) {
|
|
401
419
|
onError(e);
|
|
402
420
|
}
|
|
403
421
|
})();
|
|
422
|
+
ctx?.waitUntil?.call(ctx, task);
|
|
404
423
|
};
|
|
405
424
|
let timer;
|
|
406
425
|
const ensureTimer = () => {
|
|
407
426
|
if (timer !== void 0 || platform === "workers" || typeof setInterval !== "function") return;
|
|
408
427
|
try {
|
|
409
|
-
timer = setInterval(() => flushSoon(
|
|
428
|
+
timer = setInterval(() => void flushSoon(true), flushIntervalMs);
|
|
410
429
|
timer.unref?.();
|
|
411
430
|
} catch {
|
|
412
431
|
timer = null;
|
|
@@ -438,7 +457,9 @@ function reguardFetch(options = {}) {
|
|
|
438
457
|
flush: async () => {
|
|
439
458
|
await inflight;
|
|
440
459
|
await flush();
|
|
441
|
-
}
|
|
460
|
+
},
|
|
461
|
+
visitor: (id) => api.visitor(id),
|
|
462
|
+
events: (q) => api.events(q)
|
|
442
463
|
};
|
|
443
464
|
}
|
|
444
465
|
|
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
2
|
BLOCK_REASONS,
|
|
3
3
|
Health,
|
|
4
|
+
ReguardApiError,
|
|
4
5
|
ReguardConfigError,
|
|
5
6
|
checkOptions,
|
|
6
|
-
makeLog
|
|
7
|
-
|
|
7
|
+
makeLog,
|
|
8
|
+
reguardApi
|
|
9
|
+
} from "./chunk-4RD66ACT.js";
|
|
8
10
|
import {
|
|
9
11
|
Allowance,
|
|
10
12
|
BENIGN_TOOL_FAMILIES,
|
|
11
13
|
RETRY_AFTER,
|
|
12
14
|
SESSION_COOKIE,
|
|
15
|
+
addressKey,
|
|
13
16
|
canonicalPath,
|
|
14
17
|
collectReport,
|
|
15
18
|
collectorBase,
|
|
@@ -33,7 +36,9 @@ import {
|
|
|
33
36
|
normalizeIp,
|
|
34
37
|
parseSiteKey,
|
|
35
38
|
pathTraits,
|
|
39
|
+
presentsAsBrowser,
|
|
36
40
|
privateUrl,
|
|
41
|
+
protectionMatcher,
|
|
37
42
|
pushedVerdict,
|
|
38
43
|
readVerdictFrom,
|
|
39
44
|
renderScriptTag,
|
|
@@ -45,11 +50,12 @@ import {
|
|
|
45
50
|
verdictAgeMs,
|
|
46
51
|
wantsPage,
|
|
47
52
|
watchworthy
|
|
48
|
-
} from "./chunk-
|
|
53
|
+
} from "./chunk-2N762ZXU.js";
|
|
49
54
|
|
|
50
55
|
// src/index.ts
|
|
51
56
|
import { createHash, createHmac } from "node:crypto";
|
|
52
57
|
import { Readable } from "node:stream";
|
|
58
|
+
import { brotliCompressSync, constants as zlibConstants, gzipSync } from "node:zlib";
|
|
53
59
|
import { pipeline } from "node:stream/promises";
|
|
54
60
|
var PREFIX = "/_s";
|
|
55
61
|
var NOT_FORWARDED = /* @__PURE__ */ new Set([
|
|
@@ -72,7 +78,31 @@ var STRIP_FROM_RESPONSE = /* @__PURE__ */ new Set(["content-encoding", "content-
|
|
|
72
78
|
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
79
|
var SCAN_LIMIT = 64 * 1024;
|
|
74
80
|
function visitorHash(secret, address) {
|
|
75
|
-
return createHmac("sha256", secret).update(`visitor:${address}`).digest("base64url").slice(0, 22);
|
|
81
|
+
return createHmac("sha256", secret).update(`visitor:${addressKey(address) || address}`).digest("base64url").slice(0, 22);
|
|
82
|
+
}
|
|
83
|
+
function browserHeaders(h) {
|
|
84
|
+
const get = (n) => header(h, n);
|
|
85
|
+
return { userAgent: get("user-agent") ?? "", acceptLanguage: get("accept-language"), accept: get("accept"), secFetchMode: get("sec-fetch-mode"), secFetchDest: get("sec-fetch-dest"), secChUa: get("sec-ch-ua") };
|
|
86
|
+
}
|
|
87
|
+
var compressedScripts = /* @__PURE__ */ new Map();
|
|
88
|
+
function compressedScript(etag, body) {
|
|
89
|
+
let c = compressedScripts.get(etag);
|
|
90
|
+
if (!c) {
|
|
91
|
+
c = { br: brotliCompressSync(body, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 10, [zlibConstants.BROTLI_PARAM_MODE]: zlibConstants.BROTLI_MODE_TEXT } }), gzip: gzipSync(body, { level: 9 }) };
|
|
92
|
+
if (compressedScripts.size >= 8) compressedScripts.clear();
|
|
93
|
+
compressedScripts.set(etag, c);
|
|
94
|
+
}
|
|
95
|
+
return c;
|
|
96
|
+
}
|
|
97
|
+
async function readBody(req, limit = 1048576) {
|
|
98
|
+
const chunks = [];
|
|
99
|
+
let size = 0;
|
|
100
|
+
for await (const c of req) {
|
|
101
|
+
size += c.length;
|
|
102
|
+
if (size > limit) throw new Error("request body over 1 MiB");
|
|
103
|
+
chunks.push(c);
|
|
104
|
+
}
|
|
105
|
+
return Buffer.concat(chunks);
|
|
76
106
|
}
|
|
77
107
|
function keyFingerprint(secret) {
|
|
78
108
|
return createHash("sha256").update(`reguard-key:${secret}`).digest("base64url").slice(0, 8);
|
|
@@ -163,18 +193,24 @@ function reguard(options = {}) {
|
|
|
163
193
|
!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
194
|
);
|
|
165
195
|
const passthrough = ((req, _res, next) => {
|
|
166
|
-
req.reguard
|
|
167
|
-
req.reguardDecision
|
|
168
|
-
req.reDetect
|
|
196
|
+
req.reguard ??= null;
|
|
197
|
+
req.reguardDecision ??= null;
|
|
198
|
+
req.reDetect ??= null;
|
|
169
199
|
next();
|
|
170
200
|
});
|
|
171
201
|
Object.defineProperty(passthrough, "site", { value: void 0 });
|
|
172
202
|
passthrough.scriptTag = () => "";
|
|
173
|
-
|
|
203
|
+
const since = Date.now();
|
|
204
|
+
passthrough.status = () => ({ enabled: false, collector: "off", since, failOpen: false, queued: 0, blocking: "off" });
|
|
174
205
|
passthrough.flush = async () => {
|
|
175
206
|
};
|
|
176
207
|
passthrough.close = async () => {
|
|
177
208
|
};
|
|
209
|
+
const off = async () => {
|
|
210
|
+
throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
|
|
211
|
+
};
|
|
212
|
+
passthrough.visitor = off;
|
|
213
|
+
passthrough.events = off;
|
|
178
214
|
return passthrough;
|
|
179
215
|
}
|
|
180
216
|
const site = parsed.site;
|
|
@@ -196,9 +232,9 @@ function reguard(options = {}) {
|
|
|
196
232
|
const platform = detectPlatform(typeof process !== "undefined" ? process.env : void 0);
|
|
197
233
|
const blockCfg = o.block;
|
|
198
234
|
const allDry = !blockCfg || BLOCK_REASONS.every((r) => blockCfg.dryRun.has(r));
|
|
199
|
-
const skipped =
|
|
200
|
-
const ignored = o.ignore.length ?
|
|
201
|
-
const required = blockCfg?.require ?
|
|
235
|
+
const skipped = protectionMatcher(o.collect.skip);
|
|
236
|
+
const ignored = o.ignore.length ? protectionMatcher(o.ignore) : void 0;
|
|
237
|
+
const required = blockCfg?.require ? protectionMatcher(blockCfg.require) : void 0;
|
|
202
238
|
const allowList = blockCfg?.allow.length ? skipMatcher(blockCfg.allow) : void 0;
|
|
203
239
|
const denyMaps = (o.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
|
|
204
240
|
const tagSettings = { site, collect: o.collect, fresh: freshSeconds(blockCfg), cookieDomain: o.cookieDomain };
|
|
@@ -218,7 +254,9 @@ function reguard(options = {}) {
|
|
|
218
254
|
const ip = normalizeIp(custom ?? void 0);
|
|
219
255
|
a = ip ? { address: ip, internal: !isPublicIp(ip), via: "custom" } : resolveClientAddress({ peer, header: get }, "socket");
|
|
220
256
|
} else {
|
|
221
|
-
const
|
|
257
|
+
const trust = req.app?.get?.("trust proxy");
|
|
258
|
+
if (trust === true) log.once("trust-proxy-true", "warn", `Express's trust proxy is true, so req.ip is whatever the client sends: Reguard reads the visitor's address itself. Set trust proxy to the number of proxies in front of you (e.g. app.set("trust proxy", 1)).`);
|
|
259
|
+
const framework = trust && trust !== true ? req.ip : void 0;
|
|
222
260
|
a = resolveClientAddress({ peer, header: get, framework }, o.clientIp, platform);
|
|
223
261
|
}
|
|
224
262
|
ADDRESS.set(req, a);
|
|
@@ -297,15 +335,15 @@ function reguard(options = {}) {
|
|
|
297
335
|
const paceApi = pace ? rate(pace.api) : void 0;
|
|
298
336
|
const paceMisses = pace ? rate(pace.notFound) : void 0;
|
|
299
337
|
const cooling = /* @__PURE__ */ new Map();
|
|
300
|
-
const
|
|
338
|
+
const addressKey2 = (req) => `v:${visitorHash(parsed.secret, resolve(req).address)}`;
|
|
301
339
|
const paceOf = (req, res, p) => {
|
|
302
340
|
if (!pace || resolve(req).internal) return void 0;
|
|
303
341
|
const get = (n) => header(req.headers, n);
|
|
304
342
|
const now = Date.now();
|
|
305
|
-
const browser =
|
|
343
|
+
const browser = presentsAsBrowser(browserHeaders(req.headers));
|
|
306
344
|
const tool = browser ? void 0 : toolOf(get("user-agent"));
|
|
307
345
|
if (!browser && !(tool && BENIGN_TOOL_FAMILIES.has(tool.family))) {
|
|
308
|
-
const key2 =
|
|
346
|
+
const key2 = addressKey2(req);
|
|
309
347
|
res.once("finish", () => {
|
|
310
348
|
const st = res.statusCode;
|
|
311
349
|
if ((st === 404 || st === 405 || st === 410) && !paceMisses.take(key2)) {
|
|
@@ -325,7 +363,7 @@ function reguard(options = {}) {
|
|
|
325
363
|
}
|
|
326
364
|
if (required && matchesEither(required, p)) {
|
|
327
365
|
const sid = cookieValue(get("cookie"), SESSION_COOKIE);
|
|
328
|
-
if (!paceApi.take(sid ? `s:${sid}` :
|
|
366
|
+
if (!paceApi.take(sid ? `s:${sid}` : addressKey2(req), now)) return "api";
|
|
329
367
|
}
|
|
330
368
|
return void 0;
|
|
331
369
|
};
|
|
@@ -335,8 +373,9 @@ function reguard(options = {}) {
|
|
|
335
373
|
const dryCounts = /* @__PURE__ */ new Map();
|
|
336
374
|
const dryTimer = setInterval(() => {
|
|
337
375
|
if (!dryCounts.size) return;
|
|
338
|
-
const parts = [...dryCounts].map(([r,
|
|
339
|
-
|
|
376
|
+
const parts = [...dryCounts].map(([r, n2]) => `${r} ${n2}`).join(", ");
|
|
377
|
+
const n = [...dryCounts.values()].reduce((a, b) => a + b, 0);
|
|
378
|
+
log.info(`dry run: would have answered ${n} request${n === 1 ? "" : "s"} in the last minute (${parts})`);
|
|
340
379
|
dryCounts.clear();
|
|
341
380
|
}, 6e4);
|
|
342
381
|
dryTimer.unref?.();
|
|
@@ -371,9 +410,11 @@ function reguard(options = {}) {
|
|
|
371
410
|
const answer = async (req, res, d) => {
|
|
372
411
|
const respond = blockCfg.respond;
|
|
373
412
|
if (respond) {
|
|
413
|
+
let threw = false;
|
|
374
414
|
try {
|
|
375
415
|
await respond(req, res, d);
|
|
376
416
|
} catch (e) {
|
|
417
|
+
threw = true;
|
|
377
418
|
log.once("respond-threw", "error", `block.respond threw (${errorText(e)}): sent the default answer instead`);
|
|
378
419
|
}
|
|
379
420
|
if (res.writableEnded) return;
|
|
@@ -381,7 +422,7 @@ function reguard(options = {}) {
|
|
|
381
422
|
res.end();
|
|
382
423
|
return;
|
|
383
424
|
}
|
|
384
|
-
log.once("respond-silent", "warn", "block.respond didn't answer the request: sent the default answer");
|
|
425
|
+
if (!threw) log.once("respond-silent", "warn", "block.respond didn't answer the request: sent the default answer");
|
|
385
426
|
}
|
|
386
427
|
defaultBlockResponse(req, res, d);
|
|
387
428
|
};
|
|
@@ -394,10 +435,8 @@ function reguard(options = {}) {
|
|
|
394
435
|
const init = { method: req.method, headers, redirect: "manual", signal: AbortSignal.timeout(o.timeoutMs) };
|
|
395
436
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
396
437
|
const consumed = req.readableEnded || req._body === true;
|
|
397
|
-
if (!consumed)
|
|
398
|
-
|
|
399
|
-
init.duplex = "half";
|
|
400
|
-
} else if (req.body !== void 0) {
|
|
438
|
+
if (!consumed) init.body = new Uint8Array(await readBody(req));
|
|
439
|
+
else if (req.body !== void 0) {
|
|
401
440
|
const b = req.body;
|
|
402
441
|
init.body = Buffer.isBuffer(b) ? new Uint8Array(b) : typeof b === "string" ? b : JSON.stringify(b);
|
|
403
442
|
}
|
|
@@ -413,6 +452,16 @@ function reguard(options = {}) {
|
|
|
413
452
|
});
|
|
414
453
|
const cookies = r.headers.getSetCookie?.() ?? [];
|
|
415
454
|
if (cookies.length) res.setHeader("set-cookie", cookies);
|
|
455
|
+
const etag = r.headers.get("etag");
|
|
456
|
+
const accepts = header(req.headers, "accept-encoding") ?? "";
|
|
457
|
+
if (etag && r.ok && req.method === "GET" && /javascript/.test(r.headers.get("content-type") ?? "") && /\b(br|gzip)\b/.test(accepts)) {
|
|
458
|
+
const c = compressedScript(etag, Buffer.from(await r.arrayBuffer()));
|
|
459
|
+
const encoding = /\bbr\b/.test(accepts) ? "br" : "gzip";
|
|
460
|
+
res.setHeader("content-encoding", encoding);
|
|
461
|
+
res.setHeader("vary", "Accept-Encoding");
|
|
462
|
+
res.end(c[encoding]);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
416
465
|
if (r.body && req.method !== "HEAD") await pipeline(Readable.fromWeb(r.body), res);
|
|
417
466
|
else res.end();
|
|
418
467
|
} catch (e) {
|
|
@@ -527,6 +576,9 @@ function reguard(options = {}) {
|
|
|
527
576
|
});
|
|
528
577
|
const blocking = !blockCfg ? "off" : allDry ? "dry run" : blockCfg.dryRun.size ? "partial dry run" : "on";
|
|
529
578
|
Object.defineProperty(middleware, "site", { value: site });
|
|
579
|
+
const api = reguardApi({ key, collector, fetch: doFetch, timeoutMs: o.timeoutMs });
|
|
580
|
+
middleware.visitor = (id) => api.visitor(id);
|
|
581
|
+
middleware.events = (q) => api.events(q);
|
|
530
582
|
middleware.scriptTag = (opts) => renderScriptTag(tagSettings, opts?.nonce);
|
|
531
583
|
middleware.status = () => ({
|
|
532
584
|
enabled: true,
|
|
@@ -696,7 +748,7 @@ function createReDetect(opts, wiring = {}) {
|
|
|
696
748
|
const timeoutMs = wiring.timeoutMs ?? 1e4;
|
|
697
749
|
const addressFor = (req) => wiring.address?.(req) ?? addressOf(req);
|
|
698
750
|
const collect = resolveCollect(opts.collect, (m) => log.once(`collect:${m}`, "warn", m));
|
|
699
|
-
const skipped =
|
|
751
|
+
const skipped = protectionMatcher(collect.skip);
|
|
700
752
|
const forward = collect.requests;
|
|
701
753
|
const siteTag = siteTagOf(opts.site, secret);
|
|
702
754
|
const maxQueue = opts.maxQueue ?? 5e3;
|
|
@@ -705,13 +757,14 @@ function createReDetect(opts, wiring = {}) {
|
|
|
705
757
|
let inflight;
|
|
706
758
|
const pushed = /* @__PURE__ */ new Map();
|
|
707
759
|
const PUSHED_TTL_MS = 10 * 6e4;
|
|
760
|
+
const vidOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
|
|
708
761
|
const isClaims = (c) => Array.isArray(c) && c.every((x) => !!x && typeof x.rule === "string" && typeof x.label === "string" && typeof x.stage === "string");
|
|
709
762
|
const absorb = (body) => {
|
|
710
763
|
const f = body?.flagged;
|
|
711
764
|
if (!f) return;
|
|
712
765
|
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 });
|
|
766
|
+
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, vid: vidOf(x.vid) });
|
|
767
|
+
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, vid: vidOf(x.vid) });
|
|
715
768
|
if (pushed.size > 5e4) {
|
|
716
769
|
for (const [k, e] of pushed) if (e.until < now) pushed.delete(k);
|
|
717
770
|
}
|
|
@@ -720,14 +773,18 @@ function createReDetect(opts, wiring = {}) {
|
|
|
720
773
|
if (!pushed.size) return null;
|
|
721
774
|
const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
|
|
722
775
|
const a = addressFor(req);
|
|
723
|
-
const address = collect.addresses !== "off" && !verified && !a.internal ? a.address : "";
|
|
776
|
+
const address = collect.addresses !== "off" && !verified && !a.internal && !presentsAsBrowser(browserHeaders(req.headers)) ? a.address : "";
|
|
724
777
|
const now = Date.now();
|
|
725
778
|
const claims = [];
|
|
779
|
+
let vid;
|
|
726
780
|
for (const k of [sid ? `s:${sid}` : "", address ? `v:${visitorHash(secret, address)}` : ""]) {
|
|
727
781
|
const e = k ? pushed.get(k) : void 0;
|
|
728
|
-
if (e && e.until > now)
|
|
782
|
+
if (e && e.until > now) {
|
|
783
|
+
claims.push(...e.claims);
|
|
784
|
+
vid ??= e.vid;
|
|
785
|
+
}
|
|
729
786
|
}
|
|
730
|
-
return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now) : null;
|
|
787
|
+
return claims.length ? pushedVerdict(sid ?? "", opts.site, claims, now, vid) : null;
|
|
731
788
|
};
|
|
732
789
|
const flush = async () => {
|
|
733
790
|
while (queue.length) {
|
|
@@ -776,6 +833,7 @@ function createReDetect(opts, wiring = {}) {
|
|
|
776
833
|
const flushSoon = () => {
|
|
777
834
|
if (queue.length && !inflight) inflight = flush().finally(() => inflight = void 0);
|
|
778
835
|
};
|
|
836
|
+
let lastUrgent = 0;
|
|
779
837
|
const timer = setInterval(flushSoon, opts.flushIntervalMs ?? 2e3);
|
|
780
838
|
timer.unref?.();
|
|
781
839
|
const readVerdict = (cookieHeader) => readVerdictFrom(secret, opts.site, cookieHeader);
|
|
@@ -787,19 +845,19 @@ function createReDetect(opts, wiring = {}) {
|
|
|
787
845
|
const secure = secureRequest(req);
|
|
788
846
|
const decision = wiring.decided?.(req);
|
|
789
847
|
const pace = PACED.get(req);
|
|
848
|
+
const tool = watchworthy({
|
|
849
|
+
userAgent: header(h, "user-agent") ?? "",
|
|
850
|
+
acceptLanguage: header(h, "accept-language"),
|
|
851
|
+
accept: header(h, "accept"),
|
|
852
|
+
secFetchMode: header(h, "sec-fetch-mode"),
|
|
853
|
+
secChUa: header(h, "sec-ch-ua"),
|
|
854
|
+
secure,
|
|
855
|
+
path: url.split("?")[0] ?? url,
|
|
856
|
+
status: res.statusCode
|
|
857
|
+
});
|
|
790
858
|
if (!sid && !opts.includeSessionless && !decision) {
|
|
791
859
|
if (opts.watchSessionless === false || collect.addresses === "off") return;
|
|
792
|
-
|
|
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;
|
|
860
|
+
if (!tool) return;
|
|
803
861
|
}
|
|
804
862
|
const a = addressFor(req);
|
|
805
863
|
const visitor = !sid && a.address && collect.addresses !== "off" ? visitorHash(secret, a.address) : void 0;
|
|
@@ -860,7 +918,10 @@ function createReDetect(opts, wiring = {}) {
|
|
|
860
918
|
...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
|
|
861
919
|
...a.internal ? { internal: true } : {}
|
|
862
920
|
});
|
|
863
|
-
if (decision
|
|
921
|
+
if (decision || tool && Date.now() - lastUrgent >= 500) {
|
|
922
|
+
lastUrgent = Date.now();
|
|
923
|
+
flushSoon();
|
|
924
|
+
}
|
|
864
925
|
} catch (e) {
|
|
865
926
|
onError(e);
|
|
866
927
|
}
|