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.
Files changed (44) hide show
  1. package/README.md +51 -31
  2. package/dist/chunks/chunk-3AYS7WSY.js +350 -0
  3. package/dist/chunks/chunk-KNKCUJL3.js +969 -0
  4. package/dist/chunks/{chunk-W56LN2M5.js → chunk-PA46KSOR.js} +385 -33
  5. package/dist/chunks/chunk-YDDBWUPV.js +438 -0
  6. package/dist/cjs/fastify.cjs +2109 -0
  7. package/dist/cjs/fetch.cjs +1453 -0
  8. package/dist/cjs/index.cjs +2074 -0
  9. package/dist/cjs/next.cjs +1518 -0
  10. package/dist/cjs/testing.cjs +214 -0
  11. package/dist/fastify.js +59 -0
  12. package/dist/fetch.js +13 -0
  13. package/dist/index.js +15 -716
  14. package/dist/next.js +41 -52
  15. package/dist/testing.js +39 -0
  16. package/dist/types/node/src/config.d.ts +107 -0
  17. package/dist/types/node/src/core.d.ts +66 -72
  18. package/dist/types/node/src/fastify.d.ts +41 -0
  19. package/dist/types/node/src/fetch.d.ts +76 -0
  20. package/dist/types/node/src/health.d.ts +41 -0
  21. package/dist/types/node/src/index.d.ts +114 -34
  22. package/dist/types/node/src/next.d.ts +40 -27
  23. package/dist/types/node/src/testing.d.ts +25 -0
  24. package/dist/types/shared/src/address.d.ts +81 -0
  25. package/dist/types/shared/src/index.d.ts +6 -0
  26. package/dist/types/shared/src/paths.d.ts +32 -0
  27. package/dist/types-cjs/node/src/config.d.cts +107 -0
  28. package/dist/types-cjs/node/src/core.d.cts +107 -0
  29. package/dist/types-cjs/node/src/fastify.d.cts +41 -0
  30. package/dist/types-cjs/node/src/fetch.d.cts +76 -0
  31. package/dist/types-cjs/node/src/health.d.cts +41 -0
  32. package/dist/types-cjs/node/src/index.d.cts +203 -0
  33. package/dist/types-cjs/node/src/next.d.cts +85 -0
  34. package/dist/types-cjs/node/src/testing.d.cts +25 -0
  35. package/dist/types-cjs/shared/src/address.d.cts +81 -0
  36. package/dist/types-cjs/shared/src/allowance.d.cts +17 -0
  37. package/dist/types-cjs/shared/src/collect.d.cts +52 -0
  38. package/dist/types-cjs/shared/src/exchange.d.cts +69 -0
  39. package/dist/types-cjs/shared/src/index.d.cts +105 -0
  40. package/dist/types-cjs/shared/src/keys.d.cts +13 -0
  41. package/dist/types-cjs/shared/src/paths.d.cts +32 -0
  42. package/dist/types-cjs/shared/src/tools.d.cts +101 -0
  43. package/dist/types-cjs/shared/src/verdict.d.cts +37 -0
  44. package/package.json +73 -10
package/dist/index.js CHANGED
@@ -1,725 +1,24 @@
1
1
  import {
2
- Allowance,
3
- BENIGN_TOOL_FAMILIES,
4
- BLOCK_HTML,
5
- BLOCK_JSON,
6
- BLOCK_RETRY_AFTER,
7
- PACE_JSON,
8
- PACE_RETRY_AFTER,
9
- SESSION_COOKIE,
10
- blockConfig,
11
- collectAttributes,
12
- collectReport,
13
- collectorBase,
14
- cookieValue,
15
- describeExchange,
16
- envValue,
2
+ createReDetect,
3
+ defaultBlockResponse,
4
+ index_default,
5
+ keyFingerprint,
6
+ reguard
7
+ } from "./chunks/chunk-KNKCUJL3.js";
8
+ import {
9
+ ReguardConfigError
10
+ } from "./chunks/chunk-3AYS7WSY.js";
11
+ import {
17
12
  formatSiteKey,
18
- freshSeconds,
19
- isApiLike,
20
- isReguardPath,
21
- isSpeculativeHeaders,
22
- parseSiteKey,
23
- pathTraits,
24
- privateUrl,
25
- pushedVerdict,
26
- readVerdictFrom,
27
- requestKind,
28
- resolveCollect,
29
- skipMatcher,
30
- toolOf,
31
- verdictAgeMs,
32
- wantsPage,
33
- watchworthy
34
- } from "./chunks/chunk-W56LN2M5.js";
35
-
36
- // src/index.ts
37
- import { createHmac } from "node:crypto";
38
- import { Readable } from "node:stream";
39
- import { pipeline } from "node:stream/promises";
40
- var PREFIX = "/_s";
41
- var NOT_FORWARDED = /* @__PURE__ */ new Set([
42
- "connection",
43
- "keep-alive",
44
- "proxy-authenticate",
45
- "proxy-authorization",
46
- "te",
47
- "trailer",
48
- "transfer-encoding",
49
- "upgrade",
50
- "host",
51
- "content-length",
52
- "expect",
53
- "accept-encoding",
54
- "cookie",
55
- "authorization"
56
- ]);
57
- var STRIP_FROM_RESPONSE = /* @__PURE__ */ new Set(["content-encoding", "content-length", "transfer-encoding", "connection", "keep-alive", "set-cookie"]);
58
- 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)$|client-?ip|connecting-ip|^cf-ip|^cf-(?:region|metro|postal|timezone)|^x-vercel-ip-|^cloudfront-viewer-|^x-appengine-(?:user-ip|city|country|region)/;
59
- var SCAN_LIMIT = 64 * 1024;
60
- var warned = false;
61
- var warnedCollect = /* @__PURE__ */ new Set();
62
- function warnCollect(message) {
63
- if (warnedCollect.has(message)) return;
64
- warnedCollect.add(message);
65
- console.warn(`[reguard] ${message}`);
66
- }
67
- function visitorHash(secret, address) {
68
- return createHmac("sha256", secret).update(`visitor:${address}`).digest("base64url").slice(0, 22);
69
- }
70
- function visitorHeader(secret, address, addresses) {
71
- const value = addresses === "off" || !address ? "-" : visitorHash(secret, address);
72
- return `${value}.${createHmac("sha256", secret).update(`visitor-header:${value}`).digest("base64url").slice(0, 16)}`;
73
- }
74
- function addressOf(req) {
75
- return header(req.headers, "x-forwarded-for")?.split(",")[0]?.trim() || req.socket?.remoteAddress || "";
76
- }
77
- function refererOrigin(v) {
78
- try {
79
- const u = new URL(v);
80
- return u.origin === "null" ? void 0 : `${u.origin}/`;
81
- } catch {
82
- return void 0;
83
- }
84
- }
85
- function headersForReguard(req, secret, siteTag, collect) {
86
- const headers = new Headers();
87
- for (const [k, v] of Object.entries(req.headers)) {
88
- if (v === void 0 || NOT_FORWARDED.has(k) || k.startsWith(":") || k.startsWith("x-reguard-") || k === "referer" || ADDRESS_HEADER.test(k)) continue;
89
- try {
90
- headers.set(k, Array.isArray(v) ? v.join(", ") : v);
91
- } catch {
92
- }
93
- }
94
- const referer = header(req.headers, "referer");
95
- const origin = referer ? refererOrigin(referer) : void 0;
96
- if (origin) headers.set("referer", origin);
97
- const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
98
- if (sid && /^[\w-]{1,64}$/.test(sid)) headers.set("cookie", `${SESSION_COOKIE}=${sid}`);
99
- headers.set("x-reguard-site", siteTag);
100
- headers.set("x-reguard-visitor", visitorHeader(secret, addressOf(req), collect.addresses));
101
- return headers;
102
- }
103
- function siteTagOf(site, secret) {
104
- return `${site}.${createHmac("sha256", secret).update(`prefix:${site}`).digest("base64url").slice(0, 16)}`;
105
- }
106
- var escapeAttr = (v) => v.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
107
- function scriptTag(site, collect, fresh) {
108
- const attrs = Object.entries({ ...collectAttributes(collect), ...fresh ? { "data-fresh": String(fresh) } : {} }).map(([k, v]) => ` ${k}="${escapeAttr(v)}"`).join("");
109
- return `<script async src="${PREFIX}/sdk.js" data-site="${site.replace(/[^\w.-]/g, "")}"${attrs}></script>`;
110
- }
111
- var PACED = /* @__PURE__ */ new WeakMap();
112
- function paceResponse(req, res) {
113
- res.statusCode = 429;
114
- res.setHeader("retry-after", PACE_RETRY_AFTER);
115
- res.setHeader("cache-control", "no-store");
116
- if (wantsPage((n) => header(req.headers, n))) {
117
- res.setHeader("content-type", "text/plain; charset=utf-8");
118
- res.end("Too many requests. Slow down and try again in a moment.");
119
- } else {
120
- res.setHeader("content-type", "application/json");
121
- res.end(PACE_JSON);
122
- }
123
- }
124
- function stripSourceMapHeaders(res) {
125
- const isMapHeader = (name) => typeof name === "string" && /^(?:x-)?sourcemap$/i.test(name);
126
- const setHeader = res.setHeader.bind(res);
127
- res.setHeader = ((name, value) => isMapHeader(name) ? res : setHeader(name, value));
128
- const writeHead = res.writeHead.bind(res);
129
- res.writeHead = (...a) => {
130
- const h = a.find((x, i) => i > 0 && x && typeof x === "object" && !Array.isArray(x));
131
- if (h) {
132
- for (const k of Object.keys(h)) if (isMapHeader(k)) delete h[k];
133
- }
134
- for (const k of res.getHeaderNames()) if (isMapHeader(k)) res.removeHeader(k);
135
- return writeHead(...a);
136
- };
137
- }
138
- function withoutEndpoint(d, pages, hash) {
139
- if (pages === "masked") return d;
140
- if (pages === "hashed") return { ...d, endpoint: `~${hash(`endpoint:${d.endpoint}`)}` };
141
- const { item: _item, ...rest } = d;
142
- return { ...rest, endpoint: "" };
143
- }
144
- function reguard(options = {}) {
145
- const key = (options.key ?? envValue("REGUARD_KEY"))?.trim();
146
- const parsed = parseSiteKey(key);
147
- if (!parsed?.site) {
148
- if (!warned) {
149
- warned = true;
150
- console.warn(
151
- parsed ? "[reguard] this key has no site id (keys from before v0.4). Use the rgk.\u2026 key from your dashboard. Passing requests through." : "[reguard] REGUARD_KEY is not set. Passing requests through."
152
- );
153
- }
154
- const passthrough = ((_req, _res, next) => next());
155
- Object.defineProperty(passthrough, "site", { value: void 0 });
156
- passthrough.flush = async () => {
157
- };
158
- passthrough.close = async () => {
159
- };
160
- return passthrough;
161
- }
162
- const site = parsed.site;
163
- const siteTag = siteTagOf(site, parsed.secret);
164
- const collector = collectorBase(options.collector ?? envValue("REGUARD_COLLECTOR"));
165
- const doFetch = options.fetch ?? fetch;
166
- const onError = options.onError ?? (() => {
167
- });
168
- const collect = resolveCollect(options.collect, warnCollect);
169
- const skipped = skipMatcher(collect.skip);
170
- const core = createReDetect({
171
- site,
172
- siteKey: key,
173
- // the whole rgk key: summaries authenticate with it, verdicts verify with its secret
174
- collector: `${collector}${PREFIX}`,
175
- forward: options.forward ?? true,
176
- ignore: options.ignore,
177
- watchSessionless: options.watchSessionless,
178
- collect,
179
- fetch: doFetch,
180
- onError,
181
- flushIntervalMs: options.flushIntervalMs
182
- });
183
- const blockCfg = blockConfig(options.block);
184
- const tag = Buffer.from(scriptTag(site, collect, freshSeconds(blockCfg)));
185
- const required = blockCfg?.require ? skipMatcher(blockCfg.require) : void 0;
186
- const denyMaps = (options.sourceMaps ?? (blockCfg ? "deny" : "allow")) === "deny";
187
- const refresh = /* @__PURE__ */ new Map();
188
- const pace = blockCfg?.pace ?? null;
189
- const rate = (r) => new Allowance(r.burst, r.perSecond / 1e3, 5e4);
190
- const paceDocs = pace ? rate(pace.documents) : void 0;
191
- const paceApi = pace ? rate(pace.api) : void 0;
192
- const paceMisses = pace ? rate(pace.notFound) : void 0;
193
- const cooling = /* @__PURE__ */ new Map();
194
- const addressKey = (req) => `v:${visitorHash(parsed.secret, addressOf(req))}`;
195
- const paceOf = (req, res, path) => {
196
- if (!pace) return void 0;
197
- const get = (n) => header(req.headers, n);
198
- const now = Date.now();
199
- const browser = get("sec-fetch-dest") !== void 0;
200
- const tool = browser ? void 0 : toolOf(get("user-agent"));
201
- if (!browser && !(tool && BENIGN_TOOL_FAMILIES.has(tool.family))) {
202
- const key2 = addressKey(req);
203
- res.once("finish", () => {
204
- const st = res.statusCode;
205
- if ((st === 404 || st === 405 || st === 410) && !paceMisses.take(key2)) {
206
- cooling.set(key2, Date.now() + 1e3 / pace.notFound.perSecond);
207
- if (cooling.size > 5e4) {
208
- for (const [k, until] of cooling) if (until < Date.now()) cooling.delete(k);
209
- }
210
- }
211
- });
212
- if ((cooling.get(key2) ?? 0) > now) return "notfound";
213
- if ((req.method === "GET" || req.method === "HEAD") && requestKind(path) === "document" && !isSpeculativeHeaders(get) && !paceDocs.take(key2, now)) return "document";
214
- }
215
- if (required?.(path)) {
216
- const sid = cookieValue(get("cookie"), SESSION_COOKIE);
217
- if (!paceApi.take(sid ? `s:${sid}` : addressKey(req), now)) return "api";
218
- }
219
- return void 0;
220
- };
221
- const grace = /* @__PURE__ */ new Map();
222
- const visitorOf = (req) => collect.addresses !== "off" ? visitorHash(parsed.secret, addressOf(req)) : void 0;
223
- async function proxy(req, res) {
224
- try {
225
- const url = req.originalUrl ?? req.url ?? "/";
226
- const headers = headersForReguard(req, parsed.secret, siteTag, collect);
227
- const init = { method: req.method, headers, redirect: "manual" };
228
- if (req.method !== "GET" && req.method !== "HEAD") {
229
- const consumed = req.readableEnded || req._body === true;
230
- if (!consumed) {
231
- init.body = Readable.toWeb(req);
232
- init.duplex = "half";
233
- } else if (req.body !== void 0) {
234
- const b = req.body;
235
- init.body = Buffer.isBuffer(b) ? new Uint8Array(b) : typeof b === "string" ? b : JSON.stringify(b);
236
- }
237
- }
238
- const r = await doFetch(`${collector}${url}`, init);
239
- res.statusCode = r.status;
240
- r.headers.forEach((v, k) => {
241
- if (!STRIP_FROM_RESPONSE.has(k)) res.setHeader(k, v);
242
- });
243
- const cookies = r.headers.getSetCookie?.() ?? [];
244
- if (cookies.length) res.setHeader("set-cookie", cookies);
245
- if (r.body && req.method !== "HEAD") await pipeline(Readable.fromWeb(r.body), res);
246
- else res.end();
247
- } catch (e) {
248
- if (e?.code !== "ERR_STREAM_PREMATURE_CLOSE") onError(e);
249
- if (!res.headersSent) {
250
- res.statusCode = 502;
251
- res.end();
252
- } else res.destroy();
253
- }
254
- }
255
- const middleware = ((req, res, next) => {
256
- const path = (req.originalUrl ?? req.url ?? "/").split("?")[0] ?? "/";
257
- if (isReguardPath(path)) {
258
- void proxy(req, res);
259
- return;
260
- }
261
- core.track(req, res);
262
- if (denyMaps) {
263
- if (/\.map$/i.test(path)) {
264
- res.statusCode = 404;
265
- res.setHeader("cache-control", "no-store");
266
- res.end();
267
- return;
268
- }
269
- stripSourceMapHeaders(res);
270
- }
271
- const paced = paceOf(req, res, path);
272
- if (paced) {
273
- PACED.set(req, paced);
274
- paceResponse(req, res);
275
- return;
276
- }
277
- const injection = options.inject !== false && !skipped(path) ? injectTag(req, res, tag) : void 0;
278
- core.readVerdict(header(req.headers, "cookie")).then(
279
- (v) => {
280
- req.reguard = v;
281
- req.reDetect = v;
282
- if (blockCfg) {
283
- const opt = { labels: blockCfg.labels, minStage: blockCfg.minStage };
284
- let deny = !!v?.flagged(opt) || !!core.pushedFor(req, !!v)?.flagged(opt);
285
- const fresh = !!v && verdictAgeMs(v) <= blockCfg.maxAgeMs;
286
- if (required && fresh) {
287
- const g = grace.get(visitorOf(req) ?? "");
288
- if (g) g.pages = 0;
289
- }
290
- if (!deny && required?.(path) && !fresh) {
291
- const now = Date.now();
292
- let r = v ? refresh.get(`${v.sid}:${v.exp}`) : void 0;
293
- if (v && !r) {
294
- r = { until: now + blockCfg.refreshMs, left: blockCfg.refreshRequests };
295
- refresh.set(`${v.sid}:${v.exp}`, r);
296
- if (refresh.size > 5e4) {
297
- for (const [k, x] of refresh) if (x.until < now) refresh.delete(k);
298
- }
299
- }
300
- if (r && now <= r.until && r.left > 0) r.left--;
301
- else {
302
- const key2 = visitorOf(req);
303
- const g = key2 ? grace.get(key2) : void 0;
304
- if (g && now - g.at <= blockCfg.graceMs && g.left > 0) g.left--;
305
- else deny = true;
306
- }
307
- }
308
- if (deny) {
309
- injection?.cancel();
310
- blockResponse(req, res, blockCfg.status);
311
- return;
312
- }
313
- if (required && !required(path) && req.method !== "HEAD" && wantsPage((n) => header(req.headers, n))) {
314
- const key2 = visitorOf(req);
315
- if (key2)
316
- onHeaders(res, (status, contentType) => {
317
- if (!/^\s*text\/html/i.test(contentType) || status >= 300 && status < 400 || status === 204) return;
318
- const g = grace.get(key2) ?? { at: 0, left: 0, pages: 0 };
319
- g.pages = fresh ? 0 : g.pages + 1;
320
- g.at = Date.now();
321
- g.left = g.pages <= blockCfg.gracePages ? blockCfg.graceRequests : 0;
322
- grace.set(key2, g);
323
- if (grace.size > 5e4) {
324
- for (const [k, x] of grace) if (Date.now() - x.at > 10 * 6e4) grace.delete(k);
325
- }
326
- });
327
- }
328
- }
329
- next();
330
- },
331
- () => {
332
- req.reguard = null;
333
- req.reDetect = null;
334
- next();
335
- }
336
- );
337
- });
338
- Object.defineProperty(middleware, "site", { value: site });
339
- middleware.flush = core.flush;
340
- middleware.close = core.close;
341
- return middleware;
342
- }
343
- var index_default = reguard;
344
- function onHeaders(res, cb) {
345
- const writeHead = res.writeHead;
346
- let done = false;
347
- res.writeHead = function(...a) {
348
- const out = writeHead.apply(this, a);
349
- if (!done) {
350
- done = true;
351
- let contentType = String(res.getHeader("content-type") ?? "");
352
- if (!contentType) {
353
- const h = a.find((x, i) => i > 0 && x !== null && typeof x === "object");
354
- if (Array.isArray(h)) {
355
- for (let i = 0; i + 1 < h.length; i += 2) if (String(h[i]).toLowerCase() === "content-type") contentType = String(h[i + 1]);
356
- } else if (h) {
357
- for (const [k, v] of Object.entries(h)) if (k.toLowerCase() === "content-type") contentType = String(v);
358
- }
359
- }
360
- try {
361
- cb(res.statusCode, contentType);
362
- } catch {
363
- }
364
- }
365
- return out;
366
- };
367
- }
368
- function blockResponse(req, res, status) {
369
- const page = wantsPage((n) => header(req.headers, n));
370
- res.statusCode = status;
371
- res.setHeader("retry-after", BLOCK_RETRY_AFTER);
372
- res.setHeader("cache-control", "no-store");
373
- res.setHeader("content-type", page ? "text/html; charset=utf-8" : "application/json");
374
- res.end(page ? BLOCK_HTML : BLOCK_JSON);
375
- }
376
- function injectTag(req, res, tag) {
377
- let mode = "undecided";
378
- let held = [];
379
- const origWrite = res.write.bind(res);
380
- const origEnd = res.end.bind(res);
381
- const origWriteHead = res.writeHead.bind(res);
382
- const decide = () => {
383
- if (mode !== "undecided") return;
384
- const ct = String(res.getHeader("content-type") ?? "");
385
- 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);
386
- mode = html ? "scan" : "pass";
387
- if (html) res.removeHeader("content-length");
388
- };
389
- const toBuffer = (chunk, encoding) => typeof chunk === "string" ? Buffer.from(chunk, typeof encoding === "string" ? encoding : "utf8") : chunk instanceof Uint8Array ? Buffer.from(chunk) : null;
390
- const release = (final) => {
391
- const buf = held.length === 1 ? held[0] : Buffer.concat(held);
392
- const text = buf.toString("latin1");
393
- const lower = text.toLowerCase();
394
- const headClose = lower.search(/<\/head[\t\n\f\r >]/);
395
- if (headClose === -1 && !final && buf.length < SCAN_LIMIT) return null;
396
- mode = "pass";
397
- held = [];
398
- const head = headClose === -1 ? lower : lower.slice(0, headClose);
399
- if (head.includes("/_s/sdk") || head.includes("re-detect.js")) return buf;
400
- const open = /<head(?:\s[^>]*)?>/i.exec(text);
401
- const at = open && (headClose === -1 || open.index < headClose) ? open.index + open[0].length : headClose;
402
- return at === -1 ? buf : Buffer.concat([buf.subarray(0, at), tag, buf.subarray(at)]);
403
- };
404
- const r = res;
405
- r.writeHead = (statusCode, ...rest) => {
406
- const reason = typeof rest[0] === "string" ? rest[0] : void 0;
407
- const hdrs = reason !== void 0 ? rest[1] : rest[0];
408
- if (Array.isArray(hdrs)) {
409
- const grouped = /* @__PURE__ */ new Map();
410
- for (let i = 0; i + 1 < hdrs.length; i += 2) {
411
- const name = String(hdrs[i]);
412
- const g = grouped.get(name.toLowerCase()) ?? { name, values: [] };
413
- g.values.push(String(hdrs[i + 1]));
414
- grouped.set(name.toLowerCase(), g);
415
- }
416
- for (const g of grouped.values()) res.setHeader(g.name, g.values.length === 1 ? g.values[0] : g.values);
417
- } else if (hdrs && typeof hdrs === "object") {
418
- for (const [k, v] of Object.entries(hdrs)) if (v !== void 0) res.setHeader(k, v);
419
- }
420
- if (typeof statusCode === "number") res.statusCode = statusCode;
421
- decide();
422
- return reason !== void 0 ? origWriteHead(res.statusCode, reason) : origWriteHead(res.statusCode);
423
- };
424
- r.write = (chunk, encoding, cb) => {
425
- decide();
426
- if (mode !== "scan") return origWrite(chunk, encoding, cb);
427
- const callback = typeof encoding === "function" ? encoding : cb;
428
- const b = toBuffer(chunk, encoding);
429
- if (b) held.push(b);
430
- const out = release(false);
431
- if (out === null) {
432
- if (typeof callback === "function") process.nextTick(callback);
433
- return true;
434
- }
435
- return typeof callback === "function" ? origWrite(out, callback) : origWrite(out);
436
- };
437
- r.end = (chunk, encoding, cb) => {
438
- decide();
439
- if (mode !== "scan") return origEnd(chunk, encoding, cb);
440
- const callback = [chunk, encoding, cb].find((x) => typeof x === "function");
441
- if (typeof chunk !== "function" && chunk != null) {
442
- const b = toBuffer(chunk, encoding);
443
- if (b) held.push(b);
444
- }
445
- const out = release(true) ?? Buffer.alloc(0);
446
- return callback ? origEnd(out, callback) : origEnd(out);
447
- };
448
- return {
449
- cancel() {
450
- if (mode === "undecided") mode = "pass";
451
- }
452
- };
453
- }
454
- function secureRequest(req) {
455
- const proto = header(req.headers, "x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase();
456
- if (proto === "https" || req.socket?.encrypted) return true;
457
- const host = (header(req.headers, "host") ?? "").toLowerCase().replace(/:\d+$/, "");
458
- if (host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host.endsWith(".localhost")) return true;
459
- if (proto === "http") return false;
460
- return void 0;
461
- }
462
- function header(h, name) {
463
- const v = h[name];
464
- return Array.isArray(v) ? v.join(", ") : v;
465
- }
466
- var HOP_BY_HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "host", "content-length"]);
467
- function toArrayBuffer(b) {
468
- const ab = new ArrayBuffer(b.byteLength);
469
- new Uint8Array(ab).set(b);
470
- return ab;
471
- }
472
- function createReDetect(opts) {
473
- const prefix = (opts.prefix ?? "/_s").replace(/\/$/, "");
474
- const collector = opts.collector.replace(/\/$/, "");
475
- const secret = parseSiteKey(opts.siteKey)?.secret ?? opts.siteKey;
476
- const doFetch = opts.fetch ?? fetch;
477
- const onError = opts.onError ?? (() => {
478
- });
479
- const collect = resolveCollect(opts.collect, warnCollect);
480
- const skipped = skipMatcher(collect.skip);
481
- const forward = (opts.forward ?? true) && collect.requests;
482
- const siteTag = siteTagOf(opts.site, secret);
483
- const maxQueue = opts.maxQueue ?? 5e3;
484
- const hash = (s) => createHmac("sha256", secret).update(s).digest("base64url").slice(0, 16);
485
- const queue = [];
486
- let inflight;
487
- const pushed = /* @__PURE__ */ new Map();
488
- const PUSHED_TTL_MS = 10 * 6e4;
489
- const isClaims = (c) => Array.isArray(c) && c.every((x) => !!x && typeof x.rule === "string" && typeof x.label === "string" && typeof x.stage === "string");
490
- const absorb = (body) => {
491
- const f = body?.flagged;
492
- if (!f) return;
493
- const now = Date.now();
494
- 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 });
495
- 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 });
496
- if (pushed.size > 5e4) {
497
- for (const [k, e] of pushed) if (e.until < now) pushed.delete(k);
498
- }
499
- };
500
- const pushedFor = (req, verified = false) => {
501
- if (!pushed.size) return null;
502
- const sid = cookieValue(header(req.headers, "cookie"), SESSION_COOKIE);
503
- const address = collect.addresses !== "off" && !verified ? addressOf(req) : "";
504
- const now = Date.now();
505
- const claims = [];
506
- for (const k of [sid ? `s:${sid}` : "", address ? `v:${visitorHash(secret, address)}` : ""]) {
507
- const e = k ? pushed.get(k) : void 0;
508
- if (e && e.until > now) claims.push(...e.claims);
509
- }
510
- return claims.length ? pushedVerdict(sid ?? "", opts.site, claims) : null;
511
- };
512
- let refusedUntil = 0;
513
- const REFUSED_BACKOFF_MS = 5 * 6e4;
514
- const flush = async () => {
515
- while (queue.length) {
516
- if (Date.now() < refusedUntil) {
517
- queue.length = 0;
518
- return;
519
- }
520
- const events = queue.splice(0, 500);
521
- try {
522
- const res = await doFetch(`${collector}/v1/server`, {
523
- method: "POST",
524
- headers: { "content-type": "application/json", authorization: `Bearer ${opts.siteKey}` },
525
- body: JSON.stringify({ site: opts.site, collect: collectReport(collect), events })
526
- });
527
- if (res.status === 429) {
528
- refusedUntil = Date.now() + REFUSED_BACKOFF_MS;
529
- onError(new Error("collector answered 429 to /v1/server (monthly usage limit): summaries paused for 5 minutes"));
530
- queue.length = 0;
531
- return;
532
- }
533
- if (!res.ok) onError(new Error(`collector answered ${res.status} to /v1/server`));
534
- else absorb(await res.json().catch(() => null));
535
- } catch (e) {
536
- onError(e);
537
- }
538
- }
539
- };
540
- const flushSoon = () => {
541
- if (queue.length && !inflight) inflight = flush().finally(() => inflight = void 0);
542
- };
543
- const timer = setInterval(flushSoon, opts.flushIntervalMs ?? 2e3);
544
- timer.unref();
545
- const readVerdict = (cookieHeader) => readVerdictFrom(secret, opts.site, cookieHeader);
546
- function record(req, res, started, bytes) {
547
- try {
548
- const h = req.headers;
549
- const sid = cookieValue(header(h, "cookie"), SESSION_COOKIE);
550
- const url = req.originalUrl ?? req.url ?? "/";
551
- const secure = secureRequest(req);
552
- const pace = PACED.get(req);
553
- if (!sid && !opts.includeSessionless && !pace) {
554
- if (opts.watchSessionless === false || collect.addresses === "off") return;
555
- const watch = watchworthy({
556
- userAgent: header(h, "user-agent") ?? "",
557
- acceptLanguage: header(h, "accept-language"),
558
- accept: header(h, "accept"),
559
- secFetchMode: header(h, "sec-fetch-mode"),
560
- secChUa: header(h, "sec-ch-ua"),
561
- secure,
562
- path: url.split("?")[0] ?? url,
563
- status: res.statusCode
564
- });
565
- if (!watch) return;
566
- }
567
- const address = addressOf(req);
568
- const visitor = !sid && address && collect.addresses !== "off" ? visitorHash(secret, address) : void 0;
569
- const contentType = String(res.getHeader("content-type") ?? "");
570
- const requestBytes = Number(header(h, "content-length") ?? 0) || 0;
571
- const speculative = isSpeculativeHeaders((n) => header(h, n));
572
- let exchange;
573
- if (!speculative && isApiLike(url, contentType, requestBytes)) {
574
- const body = req.body;
575
- const bodyText = typeof body === "string" ? body : body && typeof body === "object" ? JSON.stringify(body) : "";
576
- const requestContentType = typeof body === "object" && body ? "application/json" : header(h, "content-type") ?? "";
577
- exchange = describeExchange(hash, {
578
- method: req.method ?? "GET",
579
- url,
580
- requestContentType,
581
- requestBody: bodyText.slice(0, 65536),
582
- requestBytes,
583
- status: res.statusCode,
584
- responseContentType: contentType,
585
- responseBytes: bytes()
586
- });
587
- }
588
- const order = [];
589
- for (let i = 0; i < req.rawHeaders.length; i += 2) order.push(String(req.rawHeaders[i]).toLowerCase());
590
- const picked = {};
591
- for (const n of ["rsc", "next-router-prefetch", "sec-purpose", "purpose"]) {
592
- const v = header(h, n);
593
- if (v !== void 0) picked[n] = v;
594
- }
595
- if (queue.length >= maxQueue) return;
596
- const pages = collect.pages;
597
- queue.push({
598
- sid,
599
- at: started,
600
- method: req.method ?? "GET",
601
- url: pages === "masked" ? privateUrl(url) : "",
602
- ...pages !== "off" ? { item: hash(`path:${url.split("?")[0] ?? url}`) } : {},
603
- ...pages !== "masked" ? { traits: pathTraits(url, header(h, "rsc") === "1") } : {},
604
- status: res.statusCode,
605
- headers: picked,
606
- client: {
607
- ua: header(h, "user-agent") ?? "",
608
- accept: header(h, "accept") ?? "",
609
- acceptLanguage: header(h, "accept-language") ?? "",
610
- secFetchMode: header(h, "sec-fetch-mode"),
611
- secFetchSite: header(h, "sec-fetch-site"),
612
- secFetchDest: header(h, "sec-fetch-dest"),
613
- secChUa: header(h, "sec-ch-ua"),
614
- hasCookie: Boolean(header(h, "cookie")),
615
- hasReferer: Boolean(header(h, "referer")),
616
- httpVersion: req.httpVersion,
617
- order,
618
- ...secure !== void 0 ? { secure } : {}
619
- },
620
- ...visitor ? { visitor } : {},
621
- ...exchange ? { exchange: withoutEndpoint(exchange, pages, hash) } : {},
622
- ...pace ? { pace } : {}
623
- });
624
- if (pace) flushSoon();
625
- } catch (e) {
626
- onError(e);
627
- }
628
- }
629
- function track(req, res) {
630
- const started = Date.now();
631
- const path = (req.originalUrl ?? req.url ?? "/").split("?")[0] ?? "/";
632
- if (!forward || path.startsWith(`${prefix}/`) || skipped(path) || opts.ignore?.(path)) return;
633
- let n = 0;
634
- const write = res.write.bind(res);
635
- const end = res.end.bind(res);
636
- const count = (chunk) => {
637
- if (typeof chunk === "string") n += Buffer.byteLength(chunk);
638
- else if (chunk instanceof Uint8Array) n += chunk.byteLength;
639
- };
640
- res.write = (...a) => {
641
- count(a[0]);
642
- return write(...a);
643
- };
644
- res.end = (...a) => {
645
- if (typeof a[0] !== "function") count(a[0]);
646
- return end(...a);
647
- };
648
- res.once("finish", () => record(req, res, started, () => n));
649
- }
650
- function middleware() {
651
- return (req, res, next) => {
652
- track(req, res);
653
- readVerdict(header(req.headers, "cookie")).then(
654
- (v) => {
655
- req.reDetect = v;
656
- req.reguard = v;
657
- next();
658
- },
659
- () => {
660
- req.reDetect = null;
661
- req.reguard = null;
662
- next();
663
- }
664
- );
665
- };
666
- }
667
- function route() {
668
- return async (req, res) => {
669
- try {
670
- const full = req.originalUrl ?? req.url ?? "/";
671
- const rest = full.startsWith(prefix) ? full.slice(prefix.length) : req.url ?? "/";
672
- const headers = headersForReguard(req, secret, siteTag, collect);
673
- for (const k of HOP_BY_HOP) headers.delete(k);
674
- let body;
675
- if (req.method !== "GET" && req.method !== "HEAD") {
676
- const chunks = [];
677
- let size = 0;
678
- for await (const c of req) {
679
- size += c.length;
680
- if (size > 1048576) throw new Error("request body over 1 MiB");
681
- chunks.push(c);
682
- }
683
- body = Buffer.concat(chunks);
684
- }
685
- const r = await doFetch(`${collector}${rest}`, { method: req.method, headers, body: body ? toArrayBuffer(body) : void 0, redirect: "manual" });
686
- res.statusCode = r.status;
687
- r.headers.forEach((v, k) => {
688
- if (!["content-encoding", "content-length", "transfer-encoding", "connection"].includes(k)) res.setHeader(k, v);
689
- });
690
- res.end(Buffer.from(await r.arrayBuffer()));
691
- } catch (e) {
692
- onError(e);
693
- if (!res.headersSent) res.statusCode = 502;
694
- res.end();
695
- }
696
- };
697
- }
698
- return {
699
- middleware,
700
- route,
701
- track,
702
- readVerdict,
703
- /** Claims the collector pushed back for this request's session or visitor (null: none). */
704
- pushedFor,
705
- /** For fetch-style handlers (Next.js route handlers, edge functions): pass `request.headers`. */
706
- readVerdictFromHeaders: (headers) => readVerdict(headers.get("cookie")),
707
- /** Send queued summaries now (e.g. before shutdown). */
708
- flush: async () => {
709
- await inflight;
710
- await flush();
711
- },
712
- close: async () => {
713
- clearInterval(timer);
714
- await inflight;
715
- await flush();
716
- }
717
- };
718
- }
13
+ parseSiteKey
14
+ } from "./chunks/chunk-PA46KSOR.js";
719
15
  export {
16
+ ReguardConfigError,
720
17
  createReDetect,
721
18
  index_default as default,
19
+ defaultBlockResponse,
722
20
  formatSiteKey,
21
+ keyFingerprint,
723
22
  parseSiteKey,
724
23
  reguard
725
24
  };