reguard 0.8.0 → 0.9.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 (34) hide show
  1. package/README.md +23 -1
  2. package/dist/chunks/{chunk-PA46KSOR.js → chunk-CGXTVKRB.js} +83 -7
  3. package/dist/chunks/{chunk-KNKCUJL3.js → chunk-CUIFGML3.js} +22 -7
  4. package/dist/chunks/{chunk-YDDBWUPV.js → chunk-PRPLLMXA.js} +37 -11
  5. package/dist/chunks/{chunk-3AYS7WSY.js → chunk-W4FDH5AD.js} +74 -3
  6. package/dist/cjs/fastify.cjs +71 -8
  7. package/dist/cjs/fetch.cjs +171 -17
  8. package/dist/cjs/index.cjs +153 -10
  9. package/dist/cjs/next.cjs +177 -16
  10. package/dist/cjs/testing.cjs +33 -1
  11. package/dist/fastify.js +3 -3
  12. package/dist/fetch.js +14 -5
  13. package/dist/index.js +13 -5
  14. package/dist/next.js +20 -5
  15. package/dist/testing.js +9 -3
  16. package/dist/types/node/src/api.d.ts +139 -0
  17. package/dist/types/node/src/core.d.ts +8 -1
  18. package/dist/types/node/src/fetch.d.ts +6 -0
  19. package/dist/types/node/src/index.d.ts +6 -0
  20. package/dist/types/node/src/next.d.ts +1 -0
  21. package/dist/types/node/src/testing.d.ts +11 -0
  22. package/dist/types/shared/src/index.d.ts +9 -0
  23. package/dist/types/shared/src/verdict.d.ts +6 -0
  24. package/dist/types/shared/src/webhooks.d.ts +32 -0
  25. package/dist/types-cjs/node/src/api.d.cts +139 -0
  26. package/dist/types-cjs/node/src/core.d.cts +8 -1
  27. package/dist/types-cjs/node/src/fetch.d.cts +6 -0
  28. package/dist/types-cjs/node/src/index.d.cts +6 -0
  29. package/dist/types-cjs/node/src/next.d.cts +1 -0
  30. package/dist/types-cjs/node/src/testing.d.cts +11 -0
  31. package/dist/types-cjs/shared/src/index.d.cts +9 -0
  32. package/dist/types-cjs/shared/src/verdict.d.cts +6 -0
  33. package/dist/types-cjs/shared/src/webhooks.d.cts +32 -0
  34. package/package.json +1 -1
package/dist/cjs/next.cjs CHANGED
@@ -20,10 +20,14 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/next.ts
21
21
  var next_exports = {};
22
22
  __export(next_exports, {
23
+ ReguardApiError: () => ReguardApiError,
23
24
  ReguardConfigError: () => ReguardConfigError,
25
+ ReguardWebhookError: () => WebhookSignatureError,
26
+ reguardApi: () => reguardApi,
24
27
  reguardMiddleware: () => reguardMiddleware,
25
28
  reguardScriptProps: () => reguardScriptProps,
26
29
  reguardVerdict: () => reguardVerdict,
30
+ verifyWebhook: () => verifyWebhook,
27
31
  withReguard: () => withReguard
28
32
  });
29
33
  module.exports = __toCommonJS(next_exports);
@@ -709,12 +713,71 @@ function isSourceMapPath(p) {
709
713
  return /\.map$/i.test(p.raw) || /\.map$/i.test(p.decoded);
710
714
  }
711
715
 
716
+ // ../shared/src/webhooks.ts
717
+ var WEBHOOK_TOLERANCE_SECONDS = 300;
718
+ var WebhookSignatureError = class extends Error {
719
+ constructor(code, message) {
720
+ super(message);
721
+ this.code = code;
722
+ this.name = "ReguardWebhookError";
723
+ }
724
+ };
725
+ var enc2 = new TextEncoder();
726
+ function hmacKey2(secret) {
727
+ return crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
728
+ }
729
+ function signedBytes(timestamp, payload) {
730
+ const head = enc2.encode(`${timestamp}.`);
731
+ const body = typeof payload === "string" ? enc2.encode(payload) : payload;
732
+ const out = new Uint8Array(new ArrayBuffer(head.length + body.length));
733
+ out.set(head, 0);
734
+ out.set(body, head.length);
735
+ return out;
736
+ }
737
+ function unhex(s) {
738
+ const out = new Uint8Array(new ArrayBuffer(s.length / 2));
739
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
740
+ return out;
741
+ }
742
+ function parseWebhookSignature(header) {
743
+ let t;
744
+ const v1 = [];
745
+ for (const part of header.split(",")) {
746
+ const i = part.indexOf("=");
747
+ if (i < 1) continue;
748
+ const k = part.slice(0, i).trim();
749
+ const v = part.slice(i + 1).trim();
750
+ if (k === "t" && /^\d{1,12}$/.test(v)) t = Number(v);
751
+ else if (k === "v1" && /^[0-9a-f]{64}$/.test(v)) v1.push(v);
752
+ }
753
+ return t === void 0 || !v1.length ? null : { t, v1 };
754
+ }
755
+ async function verifyWebhookSignature(payload, header, secret, options = {}) {
756
+ if (!secret) throw new WebhookSignatureError("missing_secret", "No webhook signing secret: pass it, or set REGUARD_WEBHOOK_SECRET.");
757
+ if (!header) throw new WebhookSignatureError("missing_signature", "No Reguard-Signature header on this request.");
758
+ const parsed = parseWebhookSignature(header);
759
+ if (!parsed) throw new WebhookSignatureError("malformed_signature", "The Reguard-Signature header isn't in the form t=\u2026,v1=\u2026.");
760
+ const tolerance = options.tolerance ?? WEBHOOK_TOLERANCE_SECONDS;
761
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
762
+ if (tolerance > 0 && Math.abs(now - parsed.t) > tolerance) {
763
+ throw new WebhookSignatureError("expired", `The delivery is signed ${Math.abs(now - parsed.t)} s from now, more than the ${tolerance} s allowed (a replay, or a clock that's off).`);
764
+ }
765
+ const key = await hmacKey2(secret);
766
+ const data = signedBytes(parsed.t, payload);
767
+ for (const sig of parsed.v1) {
768
+ if (await crypto.subtle.verify("HMAC", key, unhex(sig), data)) return;
769
+ }
770
+ throw new WebhookSignatureError("bad_signature", "The signature doesn't match: check the signing secret, and pass the raw request body.");
771
+ }
772
+
712
773
  // src/core.ts
713
774
  var STAGE_RANK = { candidate: 0, alert: 1, enforce: 2 };
775
+ var visitorIdOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
714
776
  function withFlagged(p, source = "browser") {
715
777
  return {
716
778
  ...p,
717
779
  source,
780
+ visitor: visitorIdOf(p.vid) ?? null,
718
781
  flagged({ labels, minStage = "candidate" } = {}) {
719
782
  const want = typeof labels === "string" ? [labels] : labels?.length ? labels : void 0;
720
783
  const rank = STAGE_RANK[minStage] ?? 0;
@@ -727,8 +790,9 @@ function mergeVerdicts(browser, pushed) {
727
790
  if (!browser) return withFlagged(pushed, "server");
728
791
  const rules = new Set(browser.claims.map((c) => `${c.rule}|${c.label}|${c.stage}`));
729
792
  const claims = [...browser.claims, ...pushed.claims.filter((c) => !rules.has(`${c.rule}|${c.label}|${c.stage}`))];
730
- const { source: _s, flagged: _f, ...payload } = browser;
731
- return withFlagged({ ...payload, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
793
+ const { source: _s, flagged: _f, visitor: _v, ...payload } = browser;
794
+ const vid = visitorIdOf(payload.vid) ?? visitorIdOf(pushed.vid);
795
+ return withFlagged({ ...payload, ...vid ? { vid } : {}, claims, outcome: claims.length && payload.outcome === "insufficient_evidence" ? "review" : payload.outcome }, "both");
732
796
  }
733
797
  async function readVerdictFrom(secret, site, cookieHeader) {
734
798
  const token = cookieValue(cookieHeader, VERDICT_COOKIE);
@@ -749,8 +813,8 @@ var DEFAULT_PACE = {
749
813
  api: { burst: 60, perSecond: 5 },
750
814
  notFound: { burst: 20, perSecond: 0.5 }
751
815
  };
752
- function pushedVerdict(sid, site, claims, now = Date.now()) {
753
- return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4 }, "server");
816
+ function pushedVerdict(sid, site, claims, now = Date.now(), vid) {
817
+ return withFlagged({ v: 1, sid, site, outcome: claims.length ? "review" : "insufficient_evidence", claims, exp: now + 6e4, ...vid ? { vid } : {} }, "server");
754
818
  }
755
819
  var ANSWER_CODES = { flagged: "reguard.blocked", flagged_server: "reguard.blocked", require: "reguard.require", pace: "reguard.pace" };
756
820
  var RETRY_AFTER = { flagged: 120, flagged_server: 120, require: 5, pace: 2 };
@@ -1065,6 +1129,68 @@ var Health = class {
1065
1129
  }
1066
1130
  };
1067
1131
 
1132
+ // src/api.ts
1133
+ var ReguardApiError = class extends Error {
1134
+ constructor(status, message) {
1135
+ super(message);
1136
+ this.status = status;
1137
+ this.name = "ReguardApiError";
1138
+ }
1139
+ };
1140
+ function reguardApi(options = {}) {
1141
+ const key = (options.key?.trim() || envValue("REGUARD_KEY"))?.trim();
1142
+ if (options.key?.trim() && !parseSiteKey(options.key.trim())?.site) throw new TypeError("[reguard] reguardApi: key must be a site key (rgk.<site>.v<n>.\u2026)");
1143
+ const base = collectorBase(options.collector || envValue("REGUARD_COLLECTOR"));
1144
+ const doFetch = options.fetch ?? fetch;
1145
+ const timeoutMs = options.timeoutMs ?? 1e4;
1146
+ async function get(path) {
1147
+ if (!key) throw new ReguardApiError(0, "No site key: pass { key } or set REGUARD_KEY.");
1148
+ if (!parseSiteKey(key)?.site) throw new ReguardApiError(0, "REGUARD_KEY isn't a site key (rgk.<site>.v<n>.\u2026).");
1149
+ let res;
1150
+ try {
1151
+ res = await doFetch(`${base}${path}`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
1152
+ } catch (e) {
1153
+ throw new ReguardApiError(0, `Reguard's API can't be reached: ${e.message}`);
1154
+ }
1155
+ const parsed = await res.json().catch(() => null);
1156
+ const body = parsed && typeof parsed === "object" ? parsed : {};
1157
+ if (!res.ok) throw new ReguardApiError(res.status, typeof body.error === "string" && body.error ? body.error : `Reguard's API answered ${res.status}`);
1158
+ return body;
1159
+ }
1160
+ return {
1161
+ async visitor(id) {
1162
+ if (!visitorIdOf(id)) throw new ReguardApiError(400, "Not a visitor id: they look like vis_ followed by 22 characters.");
1163
+ return (await get(`/v1/visitors/${id}`)).visitor;
1164
+ },
1165
+ events({ after, limit, types } = {}) {
1166
+ const q = new URLSearchParams();
1167
+ if (after) q.set("after", after);
1168
+ if (typeof limit === "number" && Number.isInteger(limit) && limit > 0) q.set("limit", String(limit));
1169
+ if (types?.length) q.set("type", types.join(","));
1170
+ const qs = q.toString();
1171
+ return get(`/v1/events${qs ? `?${qs}` : ""}`);
1172
+ }
1173
+ };
1174
+ }
1175
+ async function verifyWebhook(payload, signature, secret, options = {}) {
1176
+ if (typeof payload !== "string" && !(payload instanceof Uint8Array) && !(payload instanceof ArrayBuffer)) {
1177
+ throw new TypeError(
1178
+ '[reguard] verifyWebhook needs the raw request body (a string or bytes), not parsed JSON: in Express, use express.raw({ type: "application/json" }) on this route.'
1179
+ );
1180
+ }
1181
+ const raw = payload instanceof ArrayBuffer ? new Uint8Array(payload) : payload;
1182
+ const header = Array.isArray(signature) ? signature[0] : signature;
1183
+ await verifyWebhookSignature(raw, header, secret || envValue("REGUARD_WEBHOOK_SECRET"), options);
1184
+ let event;
1185
+ try {
1186
+ event = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw));
1187
+ } catch {
1188
+ throw new WebhookSignatureError("bad_payload", "The body isn't JSON (a Slack or Discord URL gets messages, not events).");
1189
+ }
1190
+ if (!event || typeof event.id !== "string" || typeof event.type !== "string") throw new WebhookSignatureError("bad_payload", "The body isn't a Reguard event.");
1191
+ return event;
1192
+ }
1193
+
1068
1194
  // src/fetch.ts
1069
1195
  var OPTION_KEYS = [
1070
1196
  "key",
@@ -1085,15 +1211,15 @@ var OPTION_KEYS = [
1085
1211
  "fetch",
1086
1212
  "onError"
1087
1213
  ];
1088
- var enc2 = new TextEncoder();
1214
+ var enc3 = new TextEncoder();
1089
1215
  var keys2 = /* @__PURE__ */ new Map();
1090
1216
  async function hmac(secret, text, length) {
1091
1217
  let k = keys2.get(secret);
1092
1218
  if (!k) {
1093
- k = crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
1219
+ k = crypto.subtle.importKey("raw", enc3.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
1094
1220
  keys2.set(secret, k);
1095
1221
  }
1096
- const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await k, enc2.encode(text)));
1222
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await k, enc3.encode(text)));
1097
1223
  let s = "";
1098
1224
  for (const b of sig) s += String.fromCharCode(b);
1099
1225
  return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "").slice(0, length);
@@ -1147,6 +1273,12 @@ function reguardFetch(options = {}) {
1147
1273
  decision: () => null,
1148
1274
  scriptTag: () => "",
1149
1275
  flush: async () => {
1276
+ },
1277
+ visitor: async () => {
1278
+ throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
1279
+ },
1280
+ events: async () => {
1281
+ throw new ReguardApiError(0, "Reguard is off here: no valid REGUARD_KEY.");
1150
1282
  }
1151
1283
  };
1152
1284
  }
@@ -1155,6 +1287,7 @@ function reguardFetch(options = {}) {
1155
1287
  const prev = parseSiteKey((options.previousKey ?? envValue("REGUARD_KEY_PREVIOUS"))?.trim());
1156
1288
  if (prev?.site === site && prev.secret !== parsed.secret) secrets.push(prev.secret);
1157
1289
  const collector = collectorBase(options.collector ?? envValue("REGUARD_COLLECTOR"));
1290
+ const api = reguardApi({ key, collector, fetch: doFetch, timeoutMs });
1158
1291
  const platform = options.platform ?? detectPlatform(typeof process !== "undefined" ? process.env : void 0) ?? (typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" ? "workers" : null);
1159
1292
  const health = new Health(log);
1160
1293
  const allDry = !block || BLOCK_REASONS.every((r) => block.dryRun.has(r));
@@ -1206,8 +1339,9 @@ function reguardFetch(options = {}) {
1206
1339
  health.ok();
1207
1340
  const f = (await res.json().catch(() => null))?.flagged;
1208
1341
  const now = Date.now();
1209
- 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 });
1210
- 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 });
1342
+ const vidOf = (v) => typeof v === "string" && /^vis_[\w-]{22}$/.test(v) ? v : void 0;
1343
+ 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) });
1344
+ 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) });
1211
1345
  if (pushed.size > 5e4) pushed.clear();
1212
1346
  }
1213
1347
  if (!res.ok) onError(new Error(`collector answered ${res.status} to /v1/server`));
@@ -1232,11 +1366,15 @@ function reguardFetch(options = {}) {
1232
1366
  const claims = [];
1233
1367
  const k = [sid ? `s:${sid}` : ""];
1234
1368
  if (collect.addresses !== "off" && !verified && !a.internal && a.address) k.push(`v:${await hmac(parsed.secret, `visitor:${a.address}`, 22)}`);
1369
+ let vid;
1235
1370
  for (const x of k) {
1236
1371
  const e = x ? pushed.get(x) : void 0;
1237
- if (e && e.until > now) claims.push(...e.claims);
1372
+ if (e && e.until > now) {
1373
+ claims.push(...e.claims);
1374
+ vid ??= e.vid;
1375
+ }
1238
1376
  }
1239
- return claims.length ? pushedVerdict(sid ?? "", site, claims, now) : null;
1377
+ return claims.length ? pushedVerdict(sid ?? "", site, claims, now, vid) : null;
1240
1378
  };
1241
1379
  const proxy = async (request, p) => {
1242
1380
  const url = new URL(request.url);
@@ -1410,14 +1548,24 @@ function reguardFetch(options = {}) {
1410
1548
  ...a.internal ? { internal: true } : {}
1411
1549
  });
1412
1550
  if (queue.length > 5e3) queue.splice(0, queue.length - 5e3);
1413
- flushSoon(ctx?.waitUntil, !!decision);
1551
+ const waitUntil = ctx?.waitUntil ? (p2) => ctx.waitUntil.call(ctx, p2) : void 0;
1552
+ ensureTimer();
1553
+ flushSoon(waitUntil, !!decision);
1414
1554
  } catch (e) {
1415
1555
  onError(e);
1416
1556
  }
1417
1557
  })();
1418
1558
  };
1419
- const timer = typeof setInterval === "function" ? setInterval(() => flushSoon(void 0, true), flushIntervalMs) : void 0;
1420
- timer?.unref?.();
1559
+ let timer;
1560
+ const ensureTimer = () => {
1561
+ if (timer !== void 0 || platform === "workers" || typeof setInterval !== "function") return;
1562
+ try {
1563
+ timer = setInterval(() => flushSoon(void 0, true), flushIntervalMs);
1564
+ timer.unref?.();
1565
+ } catch {
1566
+ timer = null;
1567
+ }
1568
+ };
1421
1569
  return {
1422
1570
  site,
1423
1571
  handle: (request) => handle(request),
@@ -1444,7 +1592,9 @@ function reguardFetch(options = {}) {
1444
1592
  flush: async () => {
1445
1593
  await inflight;
1446
1594
  await flush();
1447
- }
1595
+ },
1596
+ visitor: (id) => api.visitor(id),
1597
+ events: (q) => api.events(q)
1448
1598
  };
1449
1599
  }
1450
1600
 
@@ -1477,9 +1627,16 @@ async function reguardVerdict(request, options = {}) {
1477
1627
  const prev = parseSiteKey((options.previousKey ?? envValue("REGUARD_KEY_PREVIOUS"))?.trim());
1478
1628
  return prev?.site === parsed.site ? readVerdictFrom(prev.secret, prev.site, cookie) : null;
1479
1629
  }
1630
+ function publicSite() {
1631
+ try {
1632
+ return process.env.NEXT_PUBLIC_REGUARD_SITE || void 0;
1633
+ } catch {
1634
+ return void 0;
1635
+ }
1636
+ }
1480
1637
  var warned = false;
1481
1638
  function reguardScriptProps(options = {}) {
1482
- const site = parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site ?? envValue("NEXT_PUBLIC_REGUARD_SITE");
1639
+ const site = parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site ?? publicSite();
1483
1640
  if (!site && !warned) {
1484
1641
  warned = true;
1485
1642
  console.warn("[reguard] REGUARD_KEY is not set (and withReguard didn't provide NEXT_PUBLIC_REGUARD_SITE): the script will load but not start.");
@@ -1510,9 +1667,13 @@ function reguardMiddleware(options = {}) {
1510
1667
  }
1511
1668
  // Annotate the CommonJS export names for ESM import in node:
1512
1669
  0 && (module.exports = {
1670
+ ReguardApiError,
1513
1671
  ReguardConfigError,
1672
+ ReguardWebhookError,
1673
+ reguardApi,
1514
1674
  reguardMiddleware,
1515
1675
  reguardScriptProps,
1516
1676
  reguardVerdict,
1677
+ verifyWebhook,
1517
1678
  withReguard
1518
1679
  });
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var testing_exports = {};
22
22
  __export(testing_exports, {
23
23
  claim: () => claim,
24
+ signWebhook: () => signWebhook,
24
25
  testKey: () => testKey,
25
26
  verdictCookie: () => verdictCookie
26
27
  });
@@ -173,6 +174,32 @@ var compile = (list) => list.map(parseCidr).filter((c) => c !== null);
173
174
  var NON_PUBLIC = compile(NON_PUBLIC_RANGES);
174
175
  var CLOUDFLARE = compile(CLOUDFLARE_RANGES);
175
176
 
177
+ // ../shared/src/webhooks.ts
178
+ var enc2 = new TextEncoder();
179
+ function hmacKey2(secret) {
180
+ return crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
181
+ }
182
+ function signedBytes(timestamp, payload) {
183
+ const head = enc2.encode(`${timestamp}.`);
184
+ const body = typeof payload === "string" ? enc2.encode(payload) : payload;
185
+ const out = new Uint8Array(new ArrayBuffer(head.length + body.length));
186
+ out.set(head, 0);
187
+ out.set(body, head.length);
188
+ return out;
189
+ }
190
+ function hex(bytes) {
191
+ return [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
192
+ }
193
+ async function signWebhookPayload(secrets, payload, timestamp) {
194
+ const t = Math.floor(timestamp);
195
+ const data = signedBytes(t, payload);
196
+ const sigs = [];
197
+ for (const secret of typeof secrets === "string" ? [secrets] : secrets) {
198
+ sigs.push(`v1=${hex(await crypto.subtle.sign("HMAC", await hmacKey2(secret), data))}`);
199
+ }
200
+ return [`t=${t}`, ...sigs].join(",");
201
+ }
202
+
176
203
  // src/core.ts
177
204
  var VERDICT_TTL_MS = 10 * 6e4;
178
205
  var page = (title, text) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title}</title></head><body><h1>${title}</h1><p>${text}</p></body></html>`;
@@ -202,13 +229,18 @@ async function verdictCookie(key, options = {}) {
202
229
  site: parsed.site,
203
230
  outcome: claims.length ? "review" : "insufficient_evidence",
204
231
  claims,
205
- exp: (options.issuedAt ?? Date.now()) + VERDICT_TTL_MS
232
+ exp: (options.issuedAt ?? Date.now()) + VERDICT_TTL_MS,
233
+ ...options.visitor ? { vid: options.visitor } : {}
206
234
  });
207
235
  return `_s=${sid}; _sv=${token}`;
208
236
  }
237
+ function signWebhook(secret, payload, options = {}) {
238
+ return signWebhookPayload(secret, payload, options.timestamp ?? Math.floor(Date.now() / 1e3));
239
+ }
209
240
  // Annotate the CommonJS export names for ESM import in node:
210
241
  0 && (module.exports = {
211
242
  claim,
243
+ signWebhook,
212
244
  testKey,
213
245
  verdictCookie
214
246
  });
package/dist/fastify.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  reguard
3
- } from "./chunks/chunk-KNKCUJL3.js";
3
+ } from "./chunks/chunk-CUIFGML3.js";
4
4
  import {
5
5
  ReguardConfigError
6
- } from "./chunks/chunk-3AYS7WSY.js";
7
- import "./chunks/chunk-PA46KSOR.js";
6
+ } from "./chunks/chunk-W4FDH5AD.js";
7
+ import "./chunks/chunk-CGXTVKRB.js";
8
8
 
9
9
  // src/fastify.ts
10
10
  var FASTIFY_IP = /* @__PURE__ */ new WeakMap();
package/dist/fetch.js CHANGED
@@ -1,13 +1,22 @@
1
1
  import {
2
2
  defaultBlockAnswer,
3
3
  reguardFetch
4
- } from "./chunks/chunk-YDDBWUPV.js";
4
+ } from "./chunks/chunk-PRPLLMXA.js";
5
5
  import {
6
- ReguardConfigError
7
- } from "./chunks/chunk-3AYS7WSY.js";
8
- import "./chunks/chunk-PA46KSOR.js";
6
+ ReguardApiError,
7
+ ReguardConfigError,
8
+ reguardApi,
9
+ verifyWebhook
10
+ } from "./chunks/chunk-W4FDH5AD.js";
11
+ import {
12
+ WebhookSignatureError
13
+ } from "./chunks/chunk-CGXTVKRB.js";
9
14
  export {
15
+ ReguardApiError,
10
16
  ReguardConfigError,
17
+ WebhookSignatureError as ReguardWebhookError,
11
18
  defaultBlockAnswer,
12
- reguardFetch
19
+ reguardApi,
20
+ reguardFetch,
21
+ verifyWebhook
13
22
  };
package/dist/index.js CHANGED
@@ -4,21 +4,29 @@ import {
4
4
  index_default,
5
5
  keyFingerprint,
6
6
  reguard
7
- } from "./chunks/chunk-KNKCUJL3.js";
7
+ } from "./chunks/chunk-CUIFGML3.js";
8
8
  import {
9
- ReguardConfigError
10
- } from "./chunks/chunk-3AYS7WSY.js";
9
+ ReguardApiError,
10
+ ReguardConfigError,
11
+ reguardApi,
12
+ verifyWebhook
13
+ } from "./chunks/chunk-W4FDH5AD.js";
11
14
  import {
15
+ WebhookSignatureError,
12
16
  formatSiteKey,
13
17
  parseSiteKey
14
- } from "./chunks/chunk-PA46KSOR.js";
18
+ } from "./chunks/chunk-CGXTVKRB.js";
15
19
  export {
20
+ ReguardApiError,
16
21
  ReguardConfigError,
22
+ WebhookSignatureError as ReguardWebhookError,
17
23
  createReDetect,
18
24
  index_default as default,
19
25
  defaultBlockResponse,
20
26
  formatSiteKey,
21
27
  keyFingerprint,
22
28
  parseSiteKey,
23
- reguard
29
+ reguard,
30
+ reguardApi,
31
+ verifyWebhook
24
32
  };
package/dist/next.js CHANGED
@@ -1,13 +1,17 @@
1
1
  import {
2
2
  reguardFetch
3
- } from "./chunks/chunk-YDDBWUPV.js";
3
+ } from "./chunks/chunk-PRPLLMXA.js";
4
4
  import {
5
+ ReguardApiError,
5
6
  ReguardConfigError,
6
7
  checkBlock,
7
8
  checkCollect,
8
- checkCookieDomain
9
- } from "./chunks/chunk-3AYS7WSY.js";
9
+ checkCookieDomain,
10
+ reguardApi,
11
+ verifyWebhook
12
+ } from "./chunks/chunk-W4FDH5AD.js";
10
13
  import {
14
+ WebhookSignatureError,
11
15
  collectAttributes,
12
16
  collectorBase,
13
17
  envValue,
@@ -15,7 +19,7 @@ import {
15
19
  parseSiteKey,
16
20
  readVerdictFrom,
17
21
  resolveCollect
18
- } from "./chunks/chunk-PA46KSOR.js";
22
+ } from "./chunks/chunk-CGXTVKRB.js";
19
23
 
20
24
  // src/next.ts
21
25
  function withReguard(config, options = {}) {
@@ -46,9 +50,16 @@ async function reguardVerdict(request, options = {}) {
46
50
  const prev = parseSiteKey((options.previousKey ?? envValue("REGUARD_KEY_PREVIOUS"))?.trim());
47
51
  return prev?.site === parsed.site ? readVerdictFrom(prev.secret, prev.site, cookie) : null;
48
52
  }
53
+ function publicSite() {
54
+ try {
55
+ return process.env.NEXT_PUBLIC_REGUARD_SITE || void 0;
56
+ } catch {
57
+ return void 0;
58
+ }
59
+ }
49
60
  var warned = false;
50
61
  function reguardScriptProps(options = {}) {
51
- const site = parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site ?? envValue("NEXT_PUBLIC_REGUARD_SITE");
62
+ const site = parseSiteKey((options.key ?? envValue("REGUARD_KEY"))?.trim())?.site ?? publicSite();
52
63
  if (!site && !warned) {
53
64
  warned = true;
54
65
  console.warn("[reguard] REGUARD_KEY is not set (and withReguard didn't provide NEXT_PUBLIC_REGUARD_SITE): the script will load but not start.");
@@ -78,9 +89,13 @@ function reguardMiddleware(options = {}) {
78
89
  };
79
90
  }
80
91
  export {
92
+ ReguardApiError,
81
93
  ReguardConfigError,
94
+ WebhookSignatureError as ReguardWebhookError,
95
+ reguardApi,
82
96
  reguardMiddleware,
83
97
  reguardScriptProps,
84
98
  reguardVerdict,
99
+ verifyWebhook,
85
100
  withReguard
86
101
  };
package/dist/testing.js CHANGED
@@ -2,8 +2,9 @@ import {
2
2
  VERDICT_TTL_MS,
3
3
  formatSiteKey,
4
4
  parseSiteKey,
5
- signVerdict
6
- } from "./chunks/chunk-PA46KSOR.js";
5
+ signVerdict,
6
+ signWebhookPayload
7
+ } from "./chunks/chunk-CGXTVKRB.js";
7
8
 
8
9
  // src/testing.ts
9
10
  function testKey(site = "test-site") {
@@ -28,12 +29,17 @@ async function verdictCookie(key, options = {}) {
28
29
  site: parsed.site,
29
30
  outcome: claims.length ? "review" : "insufficient_evidence",
30
31
  claims,
31
- exp: (options.issuedAt ?? Date.now()) + VERDICT_TTL_MS
32
+ exp: (options.issuedAt ?? Date.now()) + VERDICT_TTL_MS,
33
+ ...options.visitor ? { vid: options.visitor } : {}
32
34
  });
33
35
  return `_s=${sid}; _sv=${token}`;
34
36
  }
37
+ function signWebhook(secret, payload, options = {}) {
38
+ return signWebhookPayload(secret, payload, options.timestamp ?? Math.floor(Date.now() / 1e3));
39
+ }
35
40
  export {
36
41
  claim,
42
+ signWebhook,
37
43
  testKey,
38
44
  verdictCookie
39
45
  };