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
@@ -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;
@@ -6,7 +6,9 @@ import { Health, type HealthState, type Log } from "./health.js";
6
6
  export type { AddressesMode, ClientIpMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.js";
7
7
  export type { Decision, PaceConfig, PaceKind, PaceRate, Verdict, VerdictSource } from "./core.js";
8
8
  export { type BlockReason, type ConfigErrorCode, type LoggerLike, ReguardConfigError } from "./config.js";
9
+ import { type EventsPage, type ReguardApi, type VisitorStatus } from "./api.js";
9
10
  export type { HealthState } from "./health.js";
11
+ 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";
10
12
  export { formatSiteKey, parseSiteKey, type ParsedSiteKey } from "../../shared/src/index.js";
11
13
  declare global {
12
14
  namespace Express {
@@ -136,6 +138,10 @@ export interface ReguardMiddleware {
136
138
  flush(): Promise<void>;
137
139
  /** Stop the summary timer and send what's queued (e.g. on shutdown). */
138
140
  close(): Promise<void>;
141
+ /** A visitor by the id in its verdict (`req.reguard.visitor`): see reguardApi(). */
142
+ visitor(id: string): Promise<VisitorStatus>;
143
+ /** The event feed, for polling instead of webhooks: see reguardApi(). */
144
+ events(options?: Parameters<ReguardApi["events"]>[0]): Promise<EventsPage>;
139
145
  }
140
146
  /** A short public fingerprint of a key's secret: safe to log and to compare with the dashboard. */
141
147
  export declare function keyFingerprint(secret: string): string;
@@ -24,6 +24,7 @@ import { type FetchBlockOptions } from "./fetch.js";
24
24
  export type { Decision, Verdict, VerdictSource } from "./core.js";
25
25
  export type { FetchBlockOptions as BlockOptions } from "./fetch.js";
26
26
  export { type BlockReason, ReguardConfigError } from "./config.js";
27
+ export { type EventsPage, type ReguardApiOptions, type ReguardEvent, type ReguardEventType, type VisitorStatus, ReguardApiError, ReguardWebhookError, reguardApi, verifyWebhook, } from "./api.js";
27
28
  export type { AddressesMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.js";
28
29
  /**
29
30
  * Adds the rewrite that serves /_s/* from Reguard, first-party, ahead of your own routes, and makes
@@ -22,4 +22,15 @@ export declare function verdictCookie(key: string, options?: {
22
22
  claims?: VerdictClaim[];
23
23
  sid?: string;
24
24
  issuedAt?: number;
25
+ visitor?: string;
26
+ }): Promise<string>;
27
+ /**
28
+ * A Reguard-Signature header for `payload` (the exact body you'll send to your webhook handler),
29
+ * signed with `secret` at `timestamp` (epoch seconds, default now): test your handler without Reguard.
30
+ *
31
+ * const body = JSON.stringify({ id: "evt_1", type: "visitor.caught", created: 0, site: "shop", data: {} });
32
+ * await request(app).post("/hooks/reguard").set("reguard-signature", await signWebhook("rgwh_test", body)).send(body);
33
+ */
34
+ export declare function signWebhook(secret: string, payload: string | Uint8Array, options?: {
35
+ timestamp?: number;
25
36
  }): Promise<string>;
@@ -28,6 +28,14 @@ export interface InitRequest {
28
28
  */
29
29
  path?: string;
30
30
  deviceId: string;
31
+ /** Whether `deviceId` persists across visits (the site turned on `persistentId`; SDK 0.9+). */
32
+ persistent?: boolean;
33
+ /**
34
+ * A hash of this device's traits (screen, time zone, languages, cores, memory; SDK 0.9+), never the
35
+ * traits themselves. The collector keeps it only for visitors it catches, to recognize their next
36
+ * session without cookies.
37
+ */
38
+ dk?: string;
31
39
  /** The site's data choices (SDK 0.6+), so the collector honours them and reviewers see them. */
32
40
  collect?: CollectReport;
33
41
  /** Seconds between verdict refreshes the site asks for (data-fresh, block.require): never sampled out (SDK 0.8+). */
@@ -101,5 +109,6 @@ export * from "./collect.js";
101
109
  export * from "./allowance.js";
102
110
  export * from "./address.js";
103
111
  export * from "./paths.js";
112
+ export * from "./webhooks.js";
104
113
  import type { VerdictClaim } from "./verdict.js";
105
114
  import type { CollectReport } from "./collect.js";
@@ -20,6 +20,12 @@ export interface VerdictPayload {
20
20
  claims: VerdictClaim[];
21
21
  /** Expiry, epoch ms. */
22
22
  exp: number;
23
+ /**
24
+ * The visitor (collector 0.9+): Reguard's id for everything one browser does, stable across its page
25
+ * loads. Signed with the rest, so it can't be forged; use it to look the visitor up (GET
26
+ * /v1/visitors/:id) or to match webhook events.
27
+ */
28
+ vid?: string;
23
29
  }
24
30
  export declare const VERDICT_COOKIE = "_sv";
25
31
  export declare const SESSION_COOKIE = "_s";
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Webhook signatures (collector 0.9). Every delivery carries
3
+ *
4
+ * Reguard-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>
5
+ *
6
+ * with one v1 per signing secret in use (two for a day after the secret is rotated). WebCrypto only,
7
+ * so the same code signs in the collector and verifies in Node, Workers, Deno and Bun.
8
+ */
9
+ export declare const WEBHOOK_SIGNATURE_HEADER = "reguard-signature";
10
+ /** How far a delivery's timestamp may be from now, in seconds (replayed deliveries are refused). */
11
+ export declare const WEBHOOK_TOLERANCE_SECONDS = 300;
12
+ export type WebhookErrorCode = "missing_secret" | "missing_signature" | "malformed_signature" | "expired" | "bad_signature" | "bad_payload";
13
+ export declare class WebhookSignatureError extends Error {
14
+ readonly code: WebhookErrorCode;
15
+ constructor(code: WebhookErrorCode, message: string);
16
+ }
17
+ /** The header value for `payload` (the exact bytes sent), signed with each secret given. */
18
+ export declare function signWebhookPayload(secrets: string | readonly string[], payload: string | Uint8Array, timestamp: number): Promise<string>;
19
+ /** `t` and every v1 signature of a header; null when it isn't one. */
20
+ export declare function parseWebhookSignature(header: string): {
21
+ t: number;
22
+ v1: string[];
23
+ } | null;
24
+ /**
25
+ * Throws a WebhookSignatureError unless `header` signs `payload` with `secret` within `tolerance`
26
+ * seconds of `now` (epoch seconds). Pass the raw body exactly as received: parsed and re-serialized
27
+ * JSON no longer matches.
28
+ */
29
+ export declare function verifyWebhookSignature(payload: string | Uint8Array, header: string | null | undefined, secret: string | null | undefined, options?: {
30
+ tolerance?: number;
31
+ now?: number;
32
+ }): Promise<void>;
@@ -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.cjs";
21
+ export { WebhookSignatureError as ReguardWebhookError } from "../../shared/src/index.cjs";
22
+ export type { WebhookErrorCode as ReguardWebhookErrorCode } from "../../shared/src/index.cjs";
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.c
18
18
  import { type Decision, type Verdict } from "./core.cjs";
19
19
  export type { Decision, Verdict, VerdictSource } from "./core.cjs";
20
20
  export { type BlockReason, ReguardConfigError } from "./config.cjs";
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.cjs";
22
+ import { type EventsPage, type ReguardApi, type VisitorStatus } from "./api.cjs";
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;
@@ -6,7 +6,9 @@ import { Health, type HealthState, type Log } from "./health.cjs";
6
6
  export type { AddressesMode, ClientIpMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.cjs";
7
7
  export type { Decision, PaceConfig, PaceKind, PaceRate, Verdict, VerdictSource } from "./core.cjs";
8
8
  export { type BlockReason, type ConfigErrorCode, type LoggerLike, ReguardConfigError } from "./config.cjs";
9
+ import { type EventsPage, type ReguardApi, type VisitorStatus } from "./api.cjs";
9
10
  export type { HealthState } from "./health.cjs";
11
+ 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.cjs";
10
12
  export { formatSiteKey, parseSiteKey, type ParsedSiteKey } from "../../shared/src/index.cjs";
11
13
  declare global {
12
14
  namespace Express {
@@ -136,6 +138,10 @@ export interface ReguardMiddleware {
136
138
  flush(): Promise<void>;
137
139
  /** Stop the summary timer and send what's queued (e.g. on shutdown). */
138
140
  close(): Promise<void>;
141
+ /** A visitor by the id in its verdict (`req.reguard.visitor`): see reguardApi(). */
142
+ visitor(id: string): Promise<VisitorStatus>;
143
+ /** The event feed, for polling instead of webhooks: see reguardApi(). */
144
+ events(options?: Parameters<ReguardApi["events"]>[0]): Promise<EventsPage>;
139
145
  }
140
146
  /** A short public fingerprint of a key's secret: safe to log and to compare with the dashboard. */
141
147
  export declare function keyFingerprint(secret: string): string;
@@ -24,6 +24,7 @@ import { type FetchBlockOptions } from "./fetch.cjs";
24
24
  export type { Decision, Verdict, VerdictSource } from "./core.cjs";
25
25
  export type { FetchBlockOptions as BlockOptions } from "./fetch.cjs";
26
26
  export { type BlockReason, ReguardConfigError } from "./config.cjs";
27
+ export { type EventsPage, type ReguardApiOptions, type ReguardEvent, type ReguardEventType, type VisitorStatus, ReguardApiError, ReguardWebhookError, reguardApi, verifyWebhook, } from "./api.cjs";
27
28
  export type { AddressesMode, CollectOptions, Label, PagesMode, Stage, VerdictClaim } from "../../shared/src/index.cjs";
28
29
  /**
29
30
  * Adds the rewrite that serves /_s/* from Reguard, first-party, ahead of your own routes, and makes
@@ -22,4 +22,15 @@ export declare function verdictCookie(key: string, options?: {
22
22
  claims?: VerdictClaim[];
23
23
  sid?: string;
24
24
  issuedAt?: number;
25
+ visitor?: string;
26
+ }): Promise<string>;
27
+ /**
28
+ * A Reguard-Signature header for `payload` (the exact body you'll send to your webhook handler),
29
+ * signed with `secret` at `timestamp` (epoch seconds, default now): test your handler without Reguard.
30
+ *
31
+ * const body = JSON.stringify({ id: "evt_1", type: "visitor.caught", created: 0, site: "shop", data: {} });
32
+ * await request(app).post("/hooks/reguard").set("reguard-signature", await signWebhook("rgwh_test", body)).send(body);
33
+ */
34
+ export declare function signWebhook(secret: string, payload: string | Uint8Array, options?: {
35
+ timestamp?: number;
25
36
  }): Promise<string>;
@@ -28,6 +28,14 @@ export interface InitRequest {
28
28
  */
29
29
  path?: string;
30
30
  deviceId: string;
31
+ /** Whether `deviceId` persists across visits (the site turned on `persistentId`; SDK 0.9+). */
32
+ persistent?: boolean;
33
+ /**
34
+ * A hash of this device's traits (screen, time zone, languages, cores, memory; SDK 0.9+), never the
35
+ * traits themselves. The collector keeps it only for visitors it catches, to recognize their next
36
+ * session without cookies.
37
+ */
38
+ dk?: string;
31
39
  /** The site's data choices (SDK 0.6+), so the collector honours them and reviewers see them. */
32
40
  collect?: CollectReport;
33
41
  /** Seconds between verdict refreshes the site asks for (data-fresh, block.require): never sampled out (SDK 0.8+). */
@@ -101,5 +109,6 @@ export * from "./collect.cjs";
101
109
  export * from "./allowance.cjs";
102
110
  export * from "./address.cjs";
103
111
  export * from "./paths.cjs";
112
+ export * from "./webhooks.cjs";
104
113
  import type { VerdictClaim } from "./verdict.cjs";
105
114
  import type { CollectReport } from "./collect.cjs";
@@ -20,6 +20,12 @@ export interface VerdictPayload {
20
20
  claims: VerdictClaim[];
21
21
  /** Expiry, epoch ms. */
22
22
  exp: number;
23
+ /**
24
+ * The visitor (collector 0.9+): Reguard's id for everything one browser does, stable across its page
25
+ * loads. Signed with the rest, so it can't be forged; use it to look the visitor up (GET
26
+ * /v1/visitors/:id) or to match webhook events.
27
+ */
28
+ vid?: string;
23
29
  }
24
30
  export declare const VERDICT_COOKIE = "_sv";
25
31
  export declare const SESSION_COOKIE = "_s";
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Webhook signatures (collector 0.9). Every delivery carries
3
+ *
4
+ * Reguard-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>
5
+ *
6
+ * with one v1 per signing secret in use (two for a day after the secret is rotated). WebCrypto only,
7
+ * so the same code signs in the collector and verifies in Node, Workers, Deno and Bun.
8
+ */
9
+ export declare const WEBHOOK_SIGNATURE_HEADER = "reguard-signature";
10
+ /** How far a delivery's timestamp may be from now, in seconds (replayed deliveries are refused). */
11
+ export declare const WEBHOOK_TOLERANCE_SECONDS = 300;
12
+ export type WebhookErrorCode = "missing_secret" | "missing_signature" | "malformed_signature" | "expired" | "bad_signature" | "bad_payload";
13
+ export declare class WebhookSignatureError extends Error {
14
+ readonly code: WebhookErrorCode;
15
+ constructor(code: WebhookErrorCode, message: string);
16
+ }
17
+ /** The header value for `payload` (the exact bytes sent), signed with each secret given. */
18
+ export declare function signWebhookPayload(secrets: string | readonly string[], payload: string | Uint8Array, timestamp: number): Promise<string>;
19
+ /** `t` and every v1 signature of a header; null when it isn't one. */
20
+ export declare function parseWebhookSignature(header: string): {
21
+ t: number;
22
+ v1: string[];
23
+ } | null;
24
+ /**
25
+ * Throws a WebhookSignatureError unless `header` signs `payload` with `secret` within `tolerance`
26
+ * seconds of `now` (epoch seconds). Pass the raw body exactly as received: parsed and re-serialized
27
+ * JSON no longer matches.
28
+ */
29
+ export declare function verifyWebhookSignature(payload: string | Uint8Array, header: string | null | undefined, secret: string | null | undefined, options?: {
30
+ tolerance?: number;
31
+ now?: number;
32
+ }): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reguard",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Reguard for your server: catch AI agents and tools reverse engineering your web app. app.use(reguard()) serves /_s/*, adds the script tag, verifies verdicts, blocks (or dry-runs) flagged visitors and sends request summaries (hashes and shapes only). Next.js helpers in reguard/next, fetch runtimes in reguard/fetch, Fastify in reguard/fastify, test helpers in reguard/testing.",
5
5
  "keywords": [
6
6
  "reguard",