reguard 0.8.1 → 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-U54IP6G4.js → chunk-PRPLLMXA.js} +24 -8
  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 +158 -14
  8. package/dist/cjs/index.cjs +153 -10
  9. package/dist/cjs/next.cjs +156 -12
  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 +12 -4
  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);
@@ -1454,7 +1592,9 @@ function reguardFetch(options = {}) {
1454
1592
  flush: async () => {
1455
1593
  await inflight;
1456
1594
  await flush();
1457
- }
1595
+ },
1596
+ visitor: (id) => api.visitor(id),
1597
+ events: (q) => api.events(q)
1458
1598
  };
1459
1599
  }
1460
1600
 
@@ -1527,9 +1667,13 @@ function reguardMiddleware(options = {}) {
1527
1667
  }
1528
1668
  // Annotate the CommonJS export names for ESM import in node:
1529
1669
  0 && (module.exports = {
1670
+ ReguardApiError,
1530
1671
  ReguardConfigError,
1672
+ ReguardWebhookError,
1673
+ reguardApi,
1531
1674
  reguardMiddleware,
1532
1675
  reguardScriptProps,
1533
1676
  reguardVerdict,
1677
+ verifyWebhook,
1534
1678
  withReguard
1535
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-U54IP6G4.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-U54IP6G4.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 = {}) {
@@ -85,9 +89,13 @@ function reguardMiddleware(options = {}) {
85
89
  };
86
90
  }
87
91
  export {
92
+ ReguardApiError,
88
93
  ReguardConfigError,
94
+ WebhookSignatureError as ReguardWebhookError,
95
+ reguardApi,
89
96
  reguardMiddleware,
90
97
  reguardScriptProps,
91
98
  reguardVerdict,
99
+ verifyWebhook,
92
100
  withReguard
93
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
  };
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The visitors API and webhooks (reguard 0.9). Runtime-neutral (fetch and WebCrypto): Node 20+,
3
+ * Workers, Deno and Bun.
4
+ *
5
+ * import { reguardApi, verifyWebhook } from "reguard";
6
+ *
7
+ * const api = reguardApi(); // REGUARD_KEY from the environment
8
+ * const v = await api.visitor(req.reguard.visitor); // the id from the visitor's signed verdict
9
+ * if (v.caught) …
10
+ *
11
+ * for (let after = null; ; ) { // poll instead of receiving webhooks
12
+ * const page = await api.events({ after });
13
+ * for (const e of page.events) handle(e);
14
+ * after = page.next;
15
+ * if (!page.hasMore) break;
16
+ * }
17
+ *
18
+ * const event = await verifyWebhook(rawBody, req.headers["reguard-signature"]); // REGUARD_WEBHOOK_SECRET
19
+ */
20
+ import { type Label, type Stage } from "../../shared/src/index.js";
21
+ export { WebhookSignatureError as ReguardWebhookError } from "../../shared/src/index.js";
22
+ export type { WebhookErrorCode as ReguardWebhookErrorCode } from "../../shared/src/index.js";
23
+ /** What matched when a caught visitor came back without its cookies. */
24
+ export type ReturnReason = "network_device" | "device_id";
25
+ export interface VisitorCatch {
26
+ rule: string;
27
+ label: Label;
28
+ stage: Stage;
29
+ at: string;
30
+ page: string | null;
31
+ evidence: Array<{
32
+ rule: string;
33
+ observed: unknown;
34
+ }>;
35
+ }
36
+ /** A caught visitor's later session without its cookies. */
37
+ export interface VisitorReturn {
38
+ visitor: string;
39
+ reason: ReturnReason;
40
+ at: string;
41
+ /** Seconds since the caught visitor's last page load. */
42
+ gapSeconds: number | null;
43
+ /** It came back while its session cookie should still have been there: cleared or blocked. */
44
+ cookieCleared: boolean;
45
+ userAgent: string | null;
46
+ page: string | null;
47
+ }
48
+ /** The caught visitor a visitor was recognized as. */
49
+ export interface VisitorLink {
50
+ visitor: string;
51
+ reason: ReturnReason;
52
+ at: string;
53
+ gapSeconds: number | null;
54
+ cookieCleared: boolean;
55
+ }
56
+ /** What Reguard knows about a visitor. `caught: false` for clean visitors and unknown ids alike. */
57
+ export interface VisitorStatus {
58
+ id: string;
59
+ caught: boolean;
60
+ kind: "browser" | "cookieless" | null;
61
+ labels: Label[];
62
+ stage: Stage | null;
63
+ firstSeen: string | null;
64
+ lastSeen: string | null;
65
+ caughtAt: string | null;
66
+ userAgent: string | null;
67
+ firstPage: string | null;
68
+ counts: {
69
+ catches: number;
70
+ blocked: number;
71
+ wouldBlock: number;
72
+ returns: number;
73
+ };
74
+ catches: VisitorCatch[];
75
+ returns: VisitorReturn[];
76
+ linkedTo: VisitorLink[];
77
+ /** The visitor on the dashboard. */
78
+ url: string;
79
+ }
80
+ export type ReguardEventType = "visitor.caught" | "visitor.escalated" | "visitor.returned" | "ping";
81
+ export interface ReguardEvent {
82
+ /** `evt_…`: unique; a delivery retried after a failure carries the same id. */
83
+ id: string;
84
+ type: ReguardEventType;
85
+ /** Epoch seconds. */
86
+ created: number;
87
+ site: string;
88
+ data: {
89
+ visitor?: VisitorStatus;
90
+ /** visitor.escalated: the stage before. */
91
+ previousStage?: Stage | null;
92
+ /** visitor.returned: the session that came back. */
93
+ returned?: VisitorReturn;
94
+ /** ping: the dashboard's test message. */
95
+ message?: string;
96
+ };
97
+ }
98
+ export interface EventsPage {
99
+ /** Oldest first. */
100
+ events: ReguardEvent[];
101
+ /** Pass as `after` next time (null until there is an event). */
102
+ next: string | null;
103
+ /** More events are waiting: ask again now. */
104
+ hasMore: boolean;
105
+ }
106
+ export declare class ReguardApiError extends Error {
107
+ readonly status: number;
108
+ constructor(status: number, message: string);
109
+ }
110
+ export interface ReguardApiOptions {
111
+ /** Site key; default REGUARD_KEY. */
112
+ key?: string;
113
+ /** Default REGUARD_COLLECTOR, then https://api.reguard.site. */
114
+ collector?: string;
115
+ fetch?: typeof fetch;
116
+ /** Per call (default 10000). */
117
+ timeoutMs?: number;
118
+ }
119
+ export interface ReguardApi {
120
+ /** A visitor by the id in its signed verdict (`req.reguard.visitor`). */
121
+ visitor(id: string): Promise<VisitorStatus>;
122
+ /** The event feed, oldest first, after `after` (an `evt_…` id). */
123
+ events(options?: {
124
+ after?: string | null;
125
+ limit?: number;
126
+ types?: readonly Exclude<ReguardEventType, "ping">[];
127
+ }): Promise<EventsPage>;
128
+ }
129
+ export declare function reguardApi(options?: ReguardApiOptions): ReguardApi;
130
+ /**
131
+ * The event in a webhook delivery, once its signature checks out; throws a ReguardWebhookError
132
+ * (`code`: missing_secret, missing_signature, malformed_signature, expired, bad_signature,
133
+ * bad_payload) otherwise. Pass the raw request body exactly as received, the Reguard-Signature
134
+ * header, and the endpoint's signing secret (default REGUARD_WEBHOOK_SECRET).
135
+ */
136
+ export declare function verifyWebhook(payload: string | Uint8Array | ArrayBuffer, signature: string | string[] | null | undefined, secret?: string, options?: {
137
+ tolerance?: number;
138
+ now?: number;
139
+ }): Promise<ReguardEvent>;
@@ -5,6 +5,11 @@ export type VerdictSource = "browser" | "server" | "both";
5
5
  export interface Verdict extends VerdictPayload {
6
6
  /** Where the claims came from. */
7
7
  source: VerdictSource;
8
+ /**
9
+ * The visitor's id (collector 0.9+; null from older ones): stable across its page loads, signed
10
+ * by Reguard. Look it up with `reguardApi().visitor(id)`, or match it to webhook events.
11
+ */
12
+ visitor: string | null;
8
13
  /**
9
14
  * Whether there is a claim for one of `labels` (default: any) at `minStage` or above (default
10
15
  * "candidate", i.e. including rules still on trial).
@@ -15,6 +20,8 @@ export interface Verdict extends VerdictPayload {
15
20
  }): boolean;
16
21
  }
17
22
  export declare const STAGE_RANK: Record<Stage, number>;
23
+ /** A visitor id as the collector issues them (`vis_` and 22 characters); anything else is ignored. */
24
+ export declare const visitorIdOf: (v: unknown) => string | undefined;
18
25
  export declare function withFlagged(p: VerdictPayload, source?: VerdictSource): Verdict;
19
26
  /** A browser verdict with claims the collector pushed to your server added (deduplicated by rule). */
20
27
  export declare function mergeVerdicts(browser: Verdict | null, pushed: Verdict | null): Verdict | null;
@@ -52,7 +59,7 @@ export declare function verdictAgeMs(v: {
52
59
  exp: number;
53
60
  }, now?: number): number;
54
61
  /** Claims the collector sent back to a site's server (no token: they arrived over its authenticated channel). */
55
- export declare function pushedVerdict(sid: string, site: string, claims: VerdictClaim[], now?: number): Verdict;
62
+ export declare function pushedVerdict(sid: string, site: string, claims: VerdictClaim[], now?: number, vid?: string): Verdict;
56
63
  /** Which limit a paced request went over. */
57
64
  export type PaceKind = "document" | "api" | "notfound";
58
65
  /** Why Reguard answered for the app (or, in a dry run, would have). */
@@ -18,6 +18,8 @@ import { type BlockBase, type ClientIpOption, type LoggerLike } from "./config.j
18
18
  import { type Decision, type Verdict } from "./core.js";
19
19
  export type { Decision, Verdict, VerdictSource } from "./core.js";
20
20
  export { type BlockReason, ReguardConfigError } from "./config.js";
21
+ export { type EventsPage, type ReguardApi, type ReguardApiOptions, type ReguardEvent, type ReguardEventType, type ReguardWebhookErrorCode, type ReturnReason, type VisitorCatch, type VisitorLink, type VisitorReturn, type VisitorStatus, ReguardApiError, ReguardWebhookError, reguardApi, verifyWebhook, } from "./api.js";
22
+ import { type EventsPage, type ReguardApi, type VisitorStatus } from "./api.js";
21
23
  export interface FetchBlockOptions extends Omit<BlockBase, "require" | "requireMaxAgeMs" | "requireGraceMs" | "requireGraceRequests" | "requireGracePages" | "requireRefreshRequests" | "requireRefreshMs"> {
22
24
  allowIf?: (request: Request) => boolean;
23
25
  /** Your own answer for a blocked request; Reguard's default (`defaultBlockAnswer`) when it throws. */
@@ -69,6 +71,10 @@ export interface ReguardFetch {
69
71
  nonce?: string;
70
72
  }): string;
71
73
  flush(): Promise<void>;
74
+ /** A visitor by the id in its verdict: see reguardApi(). */
75
+ visitor(id: string): Promise<VisitorStatus>;
76
+ /** The event feed, for polling instead of webhooks: see reguardApi(). */
77
+ events(options?: Parameters<ReguardApi["events"]>[0]): Promise<EventsPage>;
72
78
  }
73
79
  /** Reguard's default answer for a decision (HTML page for page loads, JSON with a `code` otherwise). */
74
80
  export declare function defaultBlockAnswer(request: Request, decision: Decision): Response;