@webdecoy/node 0.12.0 → 0.14.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.
package/dist/index.d.ts CHANGED
@@ -1,1014 +1,638 @@
1
+ import { R as Rule, a as RuleContext, b as RuleResult, c as RuleEngineResult, d as RateLimitConfig, F as FilterConfig, T as TripwireConfig, B as BotRuleConfig, e as BotAgent, f as BotCategory, A as AgentCategory, g as RateLimitStore, h as RateLimitConsume, i as RateLimitOutcome, W as WebDecoy, P as ProtectResult, D as Decision, j as WebDecoyConfig, k as ProtectOptions, l as AgentVerifierOptions, m as AgentRequestInput, n as AgentVerdict, S as SignedAgentDirectory } from './sdk-qUjMf8ZX.js';
2
+ export { o as AgentStatus, p as BOT_CATEGORIES, q as BOT_REGISTRY, r as BotVerdict, C as Characteristic, s as Conclusion, t as DEFAULT_CHARACTERISTICS, u as DecisionCache, v as DecisionCacheOptions, w as DecisionInit, E as EDGE_CLASS_HEADER, x as EDGE_CLEARANCE_HEADER, y as EdgeClass, z as EdgeVerdict, I as IPEnrichmentData, L as LocalAnalysis, G as LogFields, H as Logger, M as MemoryRateLimitStore, J as RequestMetadata, K as RuleOutcome, N as RuleState, O as SDKDetectionRequest, Q as SDKDetectionResponse, U as Span, V as SyncRateLimitStore, X as TLSInfo, Y as Tracer, Z as ViolationEvent, _ as classifyUserAgent, $ as consoleLogger, a0 as deriveKey, a1 as fromPino, a2 as matchUserAgent, a3 as newDecisionId, a4 as readEdgeVerdict, a5 as silentLogger } from './sdk-qUjMf8ZX.js';
3
+
1
4
  /**
2
- * Web Bot Auth verification — public types.
5
+ * The reserved test trigger.
3
6
  *
4
- * A local verifier for the WebDecoy Web Bot Auth profile (RFC 9421 HTTP
5
- * Message Signatures, tag "web-bot-auth"). It answers one question about an
6
- * inbound request: is it a *cryptographically verified* AI agent, an
7
- * *impersonator* forging a known agent's identity, an unverifiable *claim*,
8
- * or plain traffic carrying no agent signature at all?
7
+ * A request whose User-Agent starts with `WebDecoy-Test/` is the documented
8
+ * install-verification probe:
9
9
  *
10
- * The verdict taxonomy mirrors the server-side verifier in the ingest service
11
- * so the SDK, the edge validator, and the backend all speak
12
- * the same language.
13
- */
14
- /** The four possible outcomes of Web Bot Auth verification. */
15
- type AgentStatus =
16
- /** No Web Bot Auth signature on the request. Ordinary traffic. */
17
- 'none'
18
- /** Signature verified against a curated agent's published key. Trustworthy. */
19
- | 'verified'
20
- /**
21
- * A signature claiming a **known** agent's key that did **not** verify (bad
22
- * signature, or outside its created/expires window). A forgery attempt —
23
- * deny-able, tripwire-grade.
24
- */
25
- | 'impersonation'
26
- /**
27
- * A signature is present but cannot be verified against any curated agent
28
- * (unknown keyid, or an unsupported / malformed signature). An unverifiable
29
- * claim — not proof of an agent, not proof of a forgery.
30
- */
31
- | 'claimed';
32
- /**
33
- * Category an agent falls into, used for allow/deny policy. Matches the
34
- * category taxonomy used by the edge validator and backend curation.
35
- */
36
- type AgentCategory = 'ai_crawlers' | 'search_engines' | 'monitoring' | string;
37
- /** The result of verifying one request. */
38
- interface AgentVerdict {
39
- /** Verification outcome. */
40
- status: AgentStatus;
41
- /** Human display name of the matched agent (e.g. "OpenAI"). Only on `verified`. */
42
- agentName?: string;
43
- /** Category of the matched agent. Only on `verified`. */
44
- category?: AgentCategory;
45
- /** The JWK thumbprint keyid the signature claimed. Present on verified/impersonation/claimed. */
46
- keyId?: string;
47
- /** Signature algorithm used (e.g. "ed25519", "rsa-pss-sha512"). Only on `verified`. */
48
- algorithm?: string;
49
- /**
50
- * How the verdict was reached — always `'signature'` for now (Web Bot Auth
51
- * cryptographic verification). Kept for parity with the ingest verifier,
52
- * which also reports `ip_rdns` / `claimed` methods it derives from other
53
- * signals unavailable in-process.
54
- */
55
- method?: 'signature';
56
- /** Short, non-sensitive reason string for non-verified outcomes (diagnostics). */
57
- reason?: string;
58
- }
59
- /** A curated, trusted signing agent whose directory the SDK will fetch. */
60
- interface SignedAgentDirectory {
61
- /** Display name, e.g. "OpenAI". */
62
- name: string;
63
- /** Category for allow/deny policy. */
64
- category: AgentCategory;
65
- /**
66
- * Origin (scheme + host) whose well-known HTTP Message Signatures directory
67
- * publishes the agent's keys, e.g. `https://operator.openai.com`. The
68
- * `/.well-known/http-message-signatures-directory` path is appended
69
- * automatically. A full URL ending in a path is also accepted verbatim.
70
- */
71
- directory: string;
72
- }
73
- /** Options for {@link createAgentVerifier}. */
74
- interface AgentVerifierOptions {
75
- /**
76
- * Trusted agent directories to verify against. Defaults to
77
- * {@link DEFAULT_SIGNED_AGENT_DIRECTORIES}. Only origins in this list are
78
- * ever fetched — the request's own `Signature-Agent` header is never used to
79
- * choose a fetch target, so there is no SSRF surface.
80
- */
81
- directories?: SignedAgentDirectory[];
82
- /**
83
- * How long a fetched directory stays fresh, in milliseconds. After this the
84
- * cached keys are still served (stale-while-revalidate) while a background
85
- * refresh runs, so the warm path never blocks on the network.
86
- * @default 21600000 (6 hours)
87
- */
88
- cacheTtlMs?: number;
89
- /**
90
- * Per-directory fetch timeout in milliseconds.
91
- * @default 5000
92
- */
93
- fetchTimeoutMs?: number;
94
- /**
95
- * Clock-skew tolerance in seconds applied to a signature's created/expires
96
- * window.
97
- * @default 300 (5 minutes)
98
- */
99
- toleranceSec?: number;
100
- /** Emit debug logging to the console. @default false */
101
- debug?: boolean;
102
- /**
103
- * Injectable fetch, primarily for tests. Defaults to the global `fetch`.
104
- */
105
- fetchImpl?: typeof fetch;
106
- }
107
- /**
108
- * A request to verify. Either a WHATWG {@link Request} (the natural shape on
109
- * Vercel Edge / Next.js middleware and Cloudflare Workers) or a plain object
110
- * carrying the method, absolute URL, and headers.
10
+ * curl -A "WebDecoy-Test/1.0" http://localhost:3000/
11
+ *
12
+ * The SDK always reports it to ingest — before rules, before local-analysis
13
+ * thresholds, before sampling of any kind — so the developer who just
14
+ * installed the middleware gets a guaranteed, labeled detection in the
15
+ * dashboard within seconds, including from localhost. Ingest recognizes the
16
+ * same prefix server-side, marks the row `is_test`, and keeps it out of
17
+ * stats, billing, actor scoring, and enforcement.
18
+ *
19
+ * Prefix-anchored on purpose: a UA that merely mentions the string mid-way
20
+ * is NOT the trigger, so real traffic can't hide behind the test label.
111
21
  */
112
- type AgentRequestInput = Request | {
113
- method: string;
114
- /** Absolute request URL, e.g. `https://example.com/path?q=1`. */
115
- url: string;
116
- /** Headers as a WHATWG `Headers` or a plain (lowercased-key) record. */
117
- headers: Headers | Record<string, string>;
118
- };
22
+ /** Any User-Agent starting with this (case-insensitive) is a test trigger. */
23
+ declare const TEST_TRIGGER_UA_PREFIX = "WebDecoy-Test/";
24
+ /** The exact value the quickstart docs tell developers to send. */
25
+ declare const TEST_TRIGGER_USER_AGENT = "WebDecoy-Test/1.0";
26
+ /** Whether this User-Agent is the reserved test trigger. */
27
+ declare function isTestTriggerUserAgent(userAgent: string | undefined): boolean;
119
28
 
120
29
  /**
121
- * The edge validator's verdict, as the origin sees it.
30
+ * Resolving the client IP address behind a proxy.
122
31
  *
123
32
  * WHY THIS MODULE EXISTS
124
33
  *
125
- * The Cloudflare clearance worker has set `x-wd-clearance` on every forwarded
126
- * request since the validator shipped, and nothing has ever read it. Grepping the
127
- * header across the monorepo, this SDK and the WordPress plugin returned only the
128
- * worker that writes it, its own tests, and one documentation page. We shipped a
129
- * tag no customer could act on, then documented it as "watch the header in your
130
- * logs."
34
+ * Every adapter used to read the leftmost value of `X-Forwarded-For` and call it
35
+ * the client. That header is written by the client for the first hop, so the
36
+ * leftmost value is whatever the caller decided to put there. One
37
+ * `-H 'X-Forwarded-For: 1.2.3.4'` gave an attacker a fresh rate-limit bucket per
38
+ * forged address, put an address of their choosing on every violation we
39
+ * reported, and made `filter({ expression: 'ip.tor' })` an opt-in check.
131
40
  *
132
- * That gap matters more than it sounds. On a scoped route the gate's only options
133
- * were pass or challenge, and a challenge on public content is a 403 to every
134
- * client that cannot run JavaScript — search crawlers included. Reading the tag
135
- * gives the application a third option it owns: log it, meter it, skip an
136
- * expensive query, serve something cheaper. That is the first "yes" a cautious
137
- * operator can give.
41
+ * A forwarding header is only evidence if you know who wrote it. So the default
42
+ * here is to not read one at all: use the address the connection actually came
43
+ * from, and make the operator say how many proxies sit in front before we
44
+ * believe anything else. The WordPress plugin already works this way; this
45
+ * brings the Node adapters in line.
138
46
  *
139
- * WHAT IT IS NOT
47
+ * THE MODEL
140
48
  *
141
- * These values are advisory context, not authentication. They are only meaningful
142
- * for requests that actually passed through the edge validator, and the validator
143
- * strips inbound copies precisely so that the origin can attribute them to us.
144
- * A request that reaches the origin WITHOUT passing through the proxy — straight
145
- * to the origin IP, or a route that does not match — can carry anything. Treat
146
- * `present: false` as "no information", never as "not a bot", and keep the origin
147
- * unreachable except through the proxy if you intend to branch on this.
148
- */
149
- /** Header the edge validator uses for its clearance verdict. */
150
- declare const EDGE_CLEARANCE_HEADER = "x-wd-clearance";
151
- /** Header the edge validator uses for the sensor's client classification. */
152
- declare const EDGE_CLASS_HEADER = "x-wd-class";
153
- /**
154
- * What the edge sensor concluded the client is.
155
- *
156
- * - `verified` — an identity something other than the client has attested
157
- * (Cloudflare's verified-bot signal). **Never degrade these.** This is
158
- * Googlebot and friends, and quietly serving them less is how a customer loses
159
- * search presence and blames you six weeks later.
160
- * - `crawler` — self-declares as a crawler, unproven. Real-but-unverified
161
- * crawlers and forged ones both land here.
162
- * - `script` — an HTTP client library, a Chromium user agent sending no client
163
- * hints, or no user agent at all. Not a browser.
164
- * - `browser` — nothing that distinguishes a non-human fired. A statement about
165
- * our signals, not a certificate.
166
- */
167
- type EdgeClass = 'verified' | 'crawler' | 'script' | 'browser';
168
- /**
169
- * The edge's annotations on one request, typed.
49
+ * Each proxy appends the address it received the connection from, so the
50
+ * observed chain outermost-first is `[...X-Forwarded-For, peer]` and the entries
51
+ * to the RIGHT are the ones added by infrastructure you control. Trust is
52
+ * therefore counted from the right: with one proxy in front of you, the client
53
+ * is the last `X-Forwarded-For` entry; with two, the second from last. Anything
54
+ * further left was supplied by someone you have no reason to believe.
170
55
  *
171
- * Every field is optional except `present`, because the edge validator may not be
172
- * in front of this request at all — and the difference between "the edge said
173
- * browser" and "there is no edge here" is the difference between a safe
174
- * optimisation and a security hole.
56
+ * No `node:net` — this runs in Edge and Workers runtimes too, so the address
57
+ * parsing is hand-rolled and covered by tests.
175
58
  */
176
- interface EdgeVerdict {
177
- /**
178
- * True when the edge validator annotated this request. False means no
179
- * information — not "human", not "safe".
180
- */
181
- present: boolean;
182
- /**
183
- * The clearance verdict, e.g. `valid`, `missing`, `verified-bot`,
184
- * `signed-agent`, `machine`, `insufficient-trust`. Free-form on purpose: the
185
- * validator gains labels faster than an SDK release can enumerate them, and an
186
- * unknown label must not become `undefined`.
187
- */
188
- clearance?: string;
189
- /** The sensor's classification, when it classified this request. */
190
- class?: EdgeClass;
191
- /** `class === 'verified'`. Convenience so callers need no string literals. */
192
- isVerified: boolean;
193
- /** `class === 'crawler'`. */
194
- isCrawler: boolean;
195
- /** `class === 'script'`. */
196
- isScript: boolean;
197
- /** `class === 'browser'`. */
198
- isBrowser: boolean;
199
- /**
200
- * True for a class that is not a browser and is not attested — `script` or
201
- * `crawler`.
202
- *
203
- * This is the predicate most applications actually want, and it deliberately
204
- * excludes `verified`: the common intent is "cheapen this response", and the one
205
- * population you must never cheapen for is the one whose identity was proven.
206
- */
207
- isUnattestedNonBrowser: boolean;
208
- }
209
59
  /**
210
- * Read the edge validator's annotations out of a request's headers.
211
- *
212
- * Accepts the header bag the SDK already carries on `RequestMetadata` — lowercase
213
- * keys — and tolerates mixed case, since adapters differ on normalisation.
60
+ * How much of the forwarding chain to believe.
214
61
  *
215
- * An unrecognised class value is dropped rather than passed through. The set is
216
- * closed and small; a value outside it means either a version skew or something
217
- * that is not our worker, and in both cases silence beats a value a caller might
218
- * branch on.
62
+ * - `false` (default) — read no forwarding headers; the peer address is the
63
+ * client. Correct for an app exposed directly, and safe for one that isn't:
64
+ * it attributes traffic to your proxy rather than to a forged address.
65
+ * - `number` — the number of trusted proxies between the client and this
66
+ * process. The client is the Nth entry from the right of `X-Forwarded-For`.
67
+ * - `'cloudflare'` — use `CF-Connecting-IP`. Only meaningful if the origin is
68
+ * unreachable except through Cloudflare, since the header is otherwise just
69
+ * another thing a client can send.
70
+ * - `string[]` — CIDRs (or bare addresses) of the proxies you run. The chain is
71
+ * walked right to left and the first address that isn't one of yours is the
72
+ * client. Use this when the depth varies.
219
73
  */
220
- declare function readEdgeVerdict(headers: Record<string, string> | undefined): EdgeVerdict;
221
-
74
+ type TrustedProxies = false | number | 'cloudflare' | string[];
75
+ /** Headers as either a Node-style bag or a WHATWG `Headers`. */
76
+ type HeaderSource = Record<string, string | string[] | undefined> | {
77
+ get(name: string): string | null;
78
+ };
79
+ interface ResolveClientIpOptions {
80
+ /** Request headers. */
81
+ headers: HeaderSource;
82
+ /** The address the connection came from, when the runtime exposes one. */
83
+ peer?: string;
84
+ /** How much of the forwarding chain to believe. Defaults to `false`. */
85
+ trustProxy?: TrustedProxies;
86
+ }
222
87
  /**
223
- * GENERATED FILE — DO NOT EDIT.
224
- *
225
- * Source of truth: the Go agent registry in the main application repo.
226
- * Regenerate with `packages/webdecoy/scripts/gen-bot-registry.mjs`; see that
227
- * script for the command.
228
- *
229
- * ORDER IS SIGNIFICANT. Entries are in `agents.MatchUserAgent` order — AI data
230
- * scrapers first, then AI search crawlers, AI agents, search engines, then the
231
- * remaining categories. `matchUserAgent()` returns the first hit, and several
232
- * agents share User-Agent substrings, so sorting this array changes how real
233
- * traffic is classified.
88
+ * Strip the decoration real-world sources add to an address — brackets, a port,
89
+ * an IPv6 zone id — and return it in a canonical form, or null if what's left
90
+ * isn't an address at all.
234
91
  *
235
- * 169 agents across 15 categories.
92
+ * IPv4-mapped IPv6 (`::ffff:203.0.113.9`) collapses to the IPv4 form, so a
93
+ * dual-stack listener and an `X-Forwarded-For` entry for the same client
94
+ * produce the same key.
236
95
  */
96
+ declare function normalizeIp(raw: string | undefined | null): string | null;
237
97
  /**
238
- * Classification categories, mirroring `agents.Category` in Go.
239
- *
240
- * Declared here rather than hand-written next door so a category added in Go
241
- * cannot go missing in TypeScript.
98
+ * Whether an address falls inside a CIDR range. A bare address is treated as a
99
+ * single-host range. Families never match across each other.
242
100
  */
243
- type BotCategory = "training_crawler" | "ai_search_crawler" | "ai_agent" | "ai_assistant" | "search_crawler" | "seo_crawler" | "security_scanner" | "generic_scraper" | "archiver" | "fetcher" | "monitoring" | "headless_browser" | "feed_reader" | "commercial_scraper" | "none";
244
- /** One entry in the registry. */
245
- interface BotAgent {
246
- /** Stable lowercase slug, e.g. `gptbot`. */
247
- id: string;
248
- /** Display name, e.g. `GPTBot`. */
249
- name: string;
250
- category: BotCategory;
251
- /** Operator, e.g. `OpenAI`. */
252
- organization: string;
253
- /** The registry's default threat score for this agent (0-100). */
254
- baseScore: number;
255
- /** Whether the operator documents honouring robots.txt. */
256
- respectsRobots: boolean;
257
- /** Lowercase User-Agent substrings that identify it. */
258
- uaPatterns: readonly string[];
259
- }
260
- /** Every declared category, including any with no agents yet. */
261
- declare const BOT_CATEGORIES: readonly BotCategory[];
262
- /** The agent table, in match order. */
263
- declare const BOT_REGISTRY: readonly BotAgent[];
264
-
101
+ declare function ipInCidr(ip: string, cidr: string): boolean;
265
102
  /**
266
- * Local bot classification.
267
- *
268
- * WHY THIS IS IN THE SDK AT ALL
269
- *
270
- * The scoring pipeline already identifies named agents server-side, but it does
271
- * so *after* the request is reported — which is too late to decide anything. A
272
- * customer who wants "block AI training crawlers, allow search crawlers" needs
273
- * the answer synchronously, in the request path, with no network call. So the Go
274
- * registry is generated into {@link BOT_REGISTRY} and matched here.
275
- *
276
- * WHAT THIS IS NOT
277
- *
278
- * This is a User-Agent lookup. It identifies agents that say who they are, and
279
- * nothing else. An agent that spoofs Chrome is invisible to it, and always will
280
- * be — that is the point of the 1% User-Agent weight in the unified score, and
281
- * nothing here changes that arithmetic.
103
+ * Resolve the client IP for a request.
282
104
  *
283
- * That is a feature for the use case it serves. GPTBot, ClaudeBot and Googlebot
284
- * all self-identify honestly, and the decision a customer wants to make about
285
- * them ("don't train on my content") is a POLICY choice about a cooperative
286
- * agent, not a threat judgement about a hostile one. Acting on a claim is
287
- * correct when the claim is the thing you care about.
105
+ * Returns `undefined` only when there is nothing to go on: no peer address and
106
+ * no header the configuration says to believe. Callers supply their own last
107
+ * resort, because what that should be is a per-framework question.
288
108
  *
289
- * For agents that lie, the answer is the rest of the product: tripwires,
290
- * honeytokens and the edge classifier see behaviour, which cannot be spoofed by
291
- * editing a header.
109
+ * Whenever the configured source is missing or malformed this falls back to the
110
+ * peer address rather than reaching further left in the chain. The peer is the
111
+ * one address on a request that cannot be forged, so a wrong-but-real proxy
112
+ * address beats a plausible-looking value the caller chose.
292
113
  */
114
+ declare function resolveClientIp(options: ResolveClientIpOptions): string | undefined;
293
115
 
294
116
  /**
295
- * What a rule sees about the agent behind a request.
117
+ * Detection engine types.
296
118
  *
297
- * Always populated, never undefined: a rule that has to check whether
298
- * classification ran is a rule people get wrong. When nothing matched,
299
- * `known` is false and `category` is `'none'`.
300
- */
301
- interface BotVerdict {
302
- /** Whether the User-Agent matched a known agent. */
303
- known: boolean;
304
- /** Registry slug, e.g. `gptbot`. Undefined when unknown. */
305
- id?: string;
306
- /** Display name, e.g. `GPTBot`. Undefined when unknown. */
307
- name?: string;
308
- /** Customer-facing category — the same vocabulary as the dashboard. */
309
- category: BotCategory;
310
- /** Operator, e.g. `OpenAI`. Undefined when unknown. */
311
- organization?: string;
312
- /** The registry's threat score for this agent, 0-100. 0 when unknown. */
313
- score: number;
314
- /**
315
- * Whether the operator documents honouring robots.txt. Undefined when unknown.
316
- *
317
- * Documented behaviour, not observed behaviour — it is what the operator
318
- * publishes, so treat it as a claim like any other.
319
- */
320
- respectsRobots?: boolean;
321
- /** True for training crawlers, AI search crawlers, AI agents and assistants. */
322
- isAI: boolean;
323
- }
324
- /**
325
- * Find the agent behind a User-Agent string, or undefined.
119
+ * The detection engine scores a set of client-collected `Signals` against ~40
120
+ * behavioral, environmental, and fingerprint heuristics and produces a verdict.
121
+ * Ported from the FCaptcha scoring engine so behavior matches the self-hosted
122
+ * server (server.js `runVerification`).
326
123
  *
327
- * Returns the FIRST match in registry order, which is why {@link BOT_REGISTRY}
328
- * must not be sorted: the table arrives ordered by category priority, mirroring
329
- * `agents.MatchUserAgent` in Go so both sides classify identically.
330
- */
331
- declare function matchUserAgent(userAgent: string | undefined | null): BotAgent | undefined;
332
- /** Classify a User-Agent into the verdict rules evaluate against. */
333
- declare function classifyUserAgent(userAgent: string | undefined | null): BotVerdict;
334
-
335
- /**
336
- * Rules Engine Types
337
- * Core interfaces for the WebDecoy rules engine
338
- */
339
-
340
- /**
341
- * Context available to rules during evaluation
342
- */
343
- interface RuleContext {
344
- /** Client IP address */
345
- ip: string;
346
- /** Request path */
347
- path: string;
348
- /** HTTP method */
349
- method: string;
350
- /** User-Agent string */
351
- userAgent?: string;
352
- /** Request headers (lowercase keys) */
353
- headers: Record<string, string>;
354
- /** Request timestamp */
355
- timestamp: number;
356
- /** IP enrichment data (populated async when available) */
357
- enrichment?: IPEnrichmentData;
358
- /**
359
- * Web Bot Auth verdict (populated async before evaluation when a
360
- * `webBotAuth` rule is
361
- * present). Lets a synchronous rule act on cryptographic agent verification.
362
- */
363
- agent?: AgentVerdict;
364
- /**
365
- * The edge validator's annotations on this request, parsed from
366
- * `x-wd-clearance` and `x-wd-class`. Always populated — `present: false` when
367
- * the edge did not front this request. Filter expressions read it as
368
- * `edge.class`, `edge.clearance` and `edge.present`.
369
- */
370
- edge?: EdgeVerdict;
371
- /**
372
- * Who the User-Agent says it is, matched against the generated agent
373
- * registry. Always populated — `known: false` when nothing matched. Filter
374
- * expressions read it as `bot.category`, `bot.name`, `bot.ai` and friends.
375
- *
376
- * A self-declared identity, so it is evidence about cooperative agents only.
377
- * See {@link BotVerdict}.
378
- */
379
- bot?: BotVerdict;
380
- }
381
- /**
382
- * Result of evaluating a single rule
124
+ * Signals originate from an untrusted client, so every field is optional and the
125
+ * detectors fall back to neutral defaults (mirroring the `?? default` pattern in
126
+ * the reference implementation).
383
127
  */
384
- interface RuleResult {
385
- /** Action to take */
386
- action: 'ALLOW' | 'DENY' | 'THROTTLE';
387
- /** Name of the rule that produced this result */
388
- rule: string;
389
- /** Human-readable reason */
390
- reason?: string;
391
- /** Additional metadata */
392
- metadata?: Record<string, any>;
128
+ /** A single triggered heuristic. */
129
+ interface Detection {
130
+ /** Scoring bucket this detection contributes to (see {@link Weights}). */
131
+ category: string;
132
+ /** Likelihood this signal indicates a bot/attack, 0..1. */
133
+ score: number;
134
+ /** Certainty of the score, 0..1, used to weight the per-category aggregate. */
135
+ confidence: number;
136
+ /** Human-readable explanation. */
137
+ reason: string;
138
+ /** Optional structured detail (e.g. keystroke-cadence metrics). */
139
+ details?: Record<string, unknown>;
393
140
  }
394
- /**
395
- * A rule that can evaluate request context and produce a decision
396
- */
397
- interface Rule {
398
- /** Unique name for this rule */
399
- name: string;
400
- /** Evaluate the rule against request context */
401
- evaluate(context: RuleContext): RuleResult;
402
- /** Clean up resources (timers, etc.) */
403
- destroy?(): void;
141
+ /** Per-category aggregated scores (0..1), keyed by category name. */
142
+ type CategoryScores = Record<string, number>;
143
+ /** Final action recommendation derived from the weighted score. */
144
+ type Recommendation = 'allow' | 'challenge' | 'block';
145
+ /** Behavioral signals: mouse, touch, keyboard, and interaction timing. */
146
+ interface BehavioralSignals {
147
+ totalPoints?: number;
148
+ trajectoryLength?: number;
149
+ approachPoints?: number;
150
+ touchEvents?: number;
151
+ keyEvents?: number;
152
+ microTremorScore?: number;
153
+ approachDirectness?: number;
154
+ clickPrecision?: number;
155
+ explorationRatio?: number;
156
+ velocityVariance?: number;
157
+ overshootCorrections?: number;
158
+ interactionDuration?: number;
159
+ mouseEventRate?: number;
160
+ straightLineRatio?: number;
161
+ directionChanges?: number;
162
+ eventDeltaVariance?: number;
163
+ touchTotalPoints?: number;
164
+ touchForceMin?: number;
165
+ touchForceMax?: number;
166
+ touchForceVariance?: number;
167
+ touchForceAllOne?: boolean;
168
+ touchForceAllZero?: boolean;
169
+ touchRadiusMin?: number;
170
+ touchRadiusMax?: number;
171
+ touchRadiusVariance?: number;
172
+ touchUniqueIdentifiers?: number;
173
+ touchMultiTouchSeen?: boolean;
174
+ touchStraightLineRatio?: number;
175
+ touchMicroTremorScore?: number;
176
+ touchDirectionChanges?: number;
177
+ [key: string]: unknown;
404
178
  }
405
- /**
406
- * Configuration for rate limiting
407
- */
408
- interface RateLimitConfig {
409
- /** Maximum requests allowed in the window */
410
- max: number;
411
- /** Window size in seconds */
412
- window: number;
413
- /** Algorithm: 'fixed' (default) or 'sliding' */
414
- algorithm?: 'fixed' | 'sliding';
415
- /** Custom key derivation function. Default: by IP */
416
- keyBy?: (context: RuleContext) => string;
417
- /** Action when limit is exceeded: 'DENY' or 'THROTTLE' (default: 'THROTTLE') */
418
- action?: 'DENY' | 'THROTTLE';
419
- /** Dry run mode: log violations but don't block */
420
- dryRun?: boolean;
179
+ interface PoWTiming {
180
+ duration?: number;
181
+ iterations?: number;
182
+ [key: string]: unknown;
421
183
  }
422
- /**
423
- * Configuration for filter rules
424
- */
425
- interface FilterConfig {
426
- /** Filter expression (e.g., 'ip.vpn or ip.tor') */
427
- expression: string;
428
- /** Action when filter matches: 'DENY' (default) or 'THROTTLE' */
429
- action?: 'DENY' | 'THROTTLE';
430
- /** Dry run mode: log violations but don't block */
431
- dryRun?: boolean;
184
+ interface TemporalSignals {
185
+ pow?: PoWTiming;
186
+ pageLoadToFirstInteraction?: number | null;
187
+ [key: string]: unknown;
432
188
  }
433
- /**
434
- * Configuration for bot-category rules
435
- */
436
- interface BotRuleConfig {
437
- /**
438
- * Categories to act on, e.g. `['training_crawler']`. Uses the same vocabulary
439
- * as the dashboard's `ai_scraper_category` column.
440
- */
441
- categories?: BotCategory[];
442
- /** Specific agents by registry slug or display name, e.g. `['gptbot']`. */
443
- agents?: string[];
444
- /**
445
- * Act on every AI client — training crawlers, AI search crawlers, AI agents
446
- * and AI assistants.
447
- */
448
- ai?: boolean;
449
- /**
450
- * Never act on these, whatever else matches. Applied last, so
451
- * `{ ai: true, allow: ['perplexitybot'] }` reads the way it looks.
452
- */
453
- allow?: string[];
454
- /** Action when an agent matches: 'DENY' (default) or 'THROTTLE'. */
455
- action?: 'DENY' | 'THROTTLE';
456
- /** Log the violation but don't block. */
457
- dryRun?: boolean;
458
- }
459
- /**
460
- * Configuration for tripwire (honeypot-path) rules
461
- */
462
- interface TripwireConfig {
463
- /** Exact hidden honeypot paths (e.g. a honeytoken path or `/admin-backup.zip`). */
464
- paths?: string[];
465
- /** Path prefixes treated as tripwires (e.g. `/.git/`). */
466
- prefixes?: string[];
467
- /** Regex patterns for tripwire paths. */
468
- patterns?: RegExp[];
469
- /** Include the built-in scanner/scraper bait paths. Default `true`. */
470
- includeDefaults?: boolean;
471
- /** Action when a tripwire is hit: 'DENY' (default) or 'THROTTLE'. */
472
- action?: 'DENY' | 'THROTTLE';
473
- /** Dry run mode: log the violation but don't block. */
474
- dryRun?: boolean;
475
- }
476
- /**
477
- * A violation event recorded when a rule triggers
478
- */
479
- interface ViolationEvent {
480
- /** Rule that triggered */
481
- rule: string;
482
- /** Action taken */
483
- action: 'DENY' | 'THROTTLE' | 'ALLOW';
484
- /** Client IP */
485
- ip: string;
486
- /** Request path */
487
- path?: string;
488
- /** HTTP method */
489
- method?: string;
490
- /** User-Agent */
491
- userAgent?: string;
492
- /** Reason for the violation */
493
- reason?: string;
494
- /**
495
- * The request's wd_clearance token, when present. Lets the backend bind a
496
- * tripwire hit to the actor's device fingerprint and deny it — the same
497
- * durable lockout a decoy hit produces. Only carried
498
- * for deception rules (tripwires); undefined otherwise.
499
- */
500
- clearance?: string;
501
- /** Additional metadata */
502
- metadata?: Record<string, any>;
503
- /** Whether this was a dry run */
504
- dryRun: boolean;
505
- /** When the violation occurred (ISO 8601) */
506
- timestamp: string;
507
- }
508
- /**
509
- * IP enrichment data from the WebDecoy API
510
- */
511
- interface IPEnrichmentData {
512
- ip: string;
513
- security: {
514
- vpn: boolean;
515
- proxy: boolean;
516
- tor: boolean;
517
- relay: boolean;
518
- hosting: boolean;
189
+ interface EnvironmentalSignals {
190
+ webdriver?: boolean;
191
+ headlessIndicators?: {
192
+ hasOuterDimensions?: boolean;
193
+ innerEqualsOuter?: boolean;
194
+ notificationPermission?: string;
195
+ [key: string]: unknown;
196
+ };
197
+ automationFlags?: {
198
+ plugins?: number;
199
+ languages?: boolean;
200
+ chrome?: boolean;
201
+ platform?: string;
202
+ maxTouchPoints?: number;
203
+ hardwareConcurrency?: number;
204
+ [key: string]: unknown;
205
+ };
206
+ navigator?: {
207
+ platform?: string;
208
+ maxTouchPoints?: number;
209
+ [key: string]: unknown;
210
+ };
211
+ webglInfo?: {
212
+ renderer?: string;
213
+ [key: string]: unknown;
214
+ };
215
+ playwright?: {
216
+ detected?: boolean;
217
+ signals?: string[];
519
218
  };
520
- location: {
521
- country: string;
522
- country_name: string;
523
- city: string;
524
- timezone: string;
219
+ cdp?: {
220
+ detected?: boolean;
221
+ signals?: string[];
222
+ };
223
+ jsExecutionTime?: {
224
+ mathOps?: number;
225
+ [key: string]: unknown;
226
+ };
227
+ rafConsistency?: {
228
+ frameTimeVariance?: number;
229
+ [key: string]: unknown;
525
230
  };
526
- network: {
527
- asn: number;
528
- asn_org: string;
231
+ canvasHash?: {
232
+ hash?: string;
233
+ error?: unknown;
234
+ supported?: boolean;
235
+ [key: string]: unknown;
529
236
  };
530
- reputation: {
531
- abuse_score: number;
532
- total_reports: number;
533
- is_high_risk: boolean;
237
+ sensor?: {
238
+ motionEventCount?: number;
239
+ motionAccelVariance?: number;
240
+ orientationEventCount?: number;
241
+ orientationVariance?: number;
242
+ [key: string]: unknown;
534
243
  };
535
- categories: string[];
244
+ webrtcInfo?: WebRTCInfo;
245
+ speechInfo?: SpeechInfo;
246
+ workerConsistency?: WorkerConsistencyInfo;
247
+ cssMediaQueries?: CSSMediaQueriesInfo;
248
+ fontsInfo?: FontsInfo;
249
+ permissionsInfo?: PermissionsInfo;
250
+ domRectFingerprint?: DOMRectInfo;
251
+ audioInfo?: AudioContextInfo;
252
+ lieDetection?: LieDetectionInfo;
253
+ [key: string]: unknown;
536
254
  }
537
- /**
538
- * Combined result from evaluating all rules
539
- */
540
- interface RuleEngineResult {
541
- /** Final action (first DENY/THROTTLE wins, or ALLOW) */
542
- action: 'ALLOW' | 'DENY' | 'THROTTLE';
543
- /** The rule that caused the action (null if all allowed) */
544
- rule?: string;
545
- /** Reason from the deciding rule */
546
- reason?: string;
547
- /** Metadata from the deciding rule */
548
- metadata?: Record<string, any>;
549
- /** All violations generated during evaluation */
550
- violations: ViolationEvent[];
255
+ interface WebRTCInfo {
256
+ supported?: boolean;
257
+ mediaDevices?: {
258
+ supported?: boolean;
259
+ audioInputs?: number;
260
+ audioOutputs?: number;
261
+ videoInputs?: number;
262
+ totalDevices?: number;
263
+ };
264
+ hasLocalIP?: boolean;
265
+ localIPError?: unknown;
266
+ [key: string]: unknown;
551
267
  }
552
-
553
- /**
554
- * Configuration options for the Web Decoy SDK
555
- */
556
- interface WebDecoyConfig {
557
- /**
558
- * API key for authentication (sk_live_xxxxx format)
559
- * Get this from your Web Decoy dashboard
560
- * Optional — when omitted, SDK runs in local-only mode (rules still evaluate)
561
- */
562
- apiKey?: string;
563
- /**
564
- * API URL for the Web Decoy ingest service
565
- * @default 'https://ingest.webdecoy.com'
566
- */
567
- apiUrl?: string;
568
- /**
569
- * Enable TLS fingerprinting for advanced bot detection
570
- * @default true
571
- */
572
- enableTLSFingerprinting?: boolean;
573
- /**
574
- * Threat score threshold for blocking (0-100)
575
- * Requests with scores above this will be blocked
576
- * @default 80
577
- */
578
- threatScoreThreshold?: number;
579
- /**
580
- * Timeout for API requests in milliseconds
581
- * @default 5000
582
- */
583
- timeout?: number;
584
- /**
585
- * Enable debug logging
586
- * @default false
587
- */
588
- debug?: boolean;
589
- /**
590
- * Whether to reject unauthorized TLS certificates
591
- * Set to false for development/testing with self-signed certificates
592
- * @default true
593
- */
594
- tlsRejectUnauthorized?: boolean;
595
- /**
596
- * Rules to evaluate before calling the detection API
597
- * Rules are evaluated in order; first DENY/THROTTLE wins
598
- */
599
- rules?: Rule[];
600
- /**
601
- * Options for local Web Bot Auth agent verification (used by `detectBot()`
602
- * and the `webBotAuth()` rule) — trusted directories, cache TTL, etc.
603
- * Defaults are sensible; override only to curate your own agent allowlist.
604
- */
605
- webBotAuth?: AgentVerifierOptions;
268
+ interface SpeechInfo {
269
+ supported?: boolean;
270
+ totalVoices?: number;
271
+ localVoices?: number;
272
+ [key: string]: unknown;
606
273
  }
607
- /**
608
- * TLS connection information from the request
609
- */
610
- interface TLSInfo {
611
- /** TLS version (e.g., 771 for TLS 1.2, 772 for TLS 1.3) */
612
- version?: number;
613
- /** List of cipher suites supported by the client */
614
- cipher_suites?: number[];
615
- /** List of TLS extensions */
616
- extensions?: number[];
617
- /** Elliptic curves supported */
618
- supported_groups?: number[];
619
- /** EC point formats */
620
- ec_point_formats?: number[];
621
- /** Signature algorithms */
622
- signature_algorithms?: number[];
623
- /** Server name indication */
624
- server_name?: string;
625
- /** ALPN protocols */
626
- alpn_protocols?: string[];
274
+ interface WorkerConsistencyInfo {
275
+ supported?: boolean;
276
+ consistent?: boolean;
277
+ mismatches?: string[];
278
+ mismatchCount?: number;
279
+ [key: string]: unknown;
627
280
  }
628
- /**
629
- * Request metadata sent to the detection service
630
- */
631
- interface RequestMetadata {
632
- /** HTTP method (GET, POST, etc.) */
633
- method: string;
634
- /** Request path */
635
- path: string;
636
- /** Client IP address (REQUIRED) */
637
- ip: string;
638
- /** User-Agent header */
639
- user_agent?: string;
640
- /** All request headers */
641
- headers: Record<string, string>;
642
- /** TLS connection information */
643
- tls_info?: TLSInfo;
644
- /** Request timestamp (Unix milliseconds) */
645
- timestamp: number;
281
+ interface CSSMediaQueriesInfo {
282
+ supported?: boolean;
283
+ pointer?: string;
284
+ hover?: boolean;
285
+ [key: string]: unknown;
646
286
  }
647
- /**
648
- * Local analysis performed by the SDK
649
- */
650
- interface LocalAnalysis {
651
- /** True if suspicious headers detected */
652
- suspicious_headers: boolean;
653
- /** True if Sec-CH-UA header is missing */
654
- missing_sec_ch_ua: boolean;
655
- /** True if IP is from a known datacenter */
656
- datacenter_ip: boolean;
657
- /** Local threat score (0-100) */
658
- local_score: number;
659
- /** True if server-side verification is needed */
660
- needs_verification: boolean;
661
- /** Detection flags */
662
- flags: string[];
287
+ interface FontsInfo {
288
+ supported?: boolean;
289
+ count?: number;
290
+ hasSegoeUI?: boolean;
291
+ hasSFPro?: boolean;
292
+ hasDejaVuSans?: boolean;
293
+ [key: string]: unknown;
663
294
  }
664
- /**
665
- * Detection request sent to the ingest service
666
- */
667
- interface SDKDetectionRequest {
668
- request_metadata: RequestMetadata;
669
- local_analysis: LocalAnalysis;
295
+ interface PermissionsInfo {
296
+ supported?: boolean;
297
+ [key: string]: unknown;
670
298
  }
671
- /**
672
- * Detection response from the ingest service
673
- */
674
- interface SDKDetectionResponse {
675
- /** Decision: "allow", "block", or "challenge" */
676
- decision: 'allow' | 'block' | 'challenge';
677
- /** Confidence score (0-100) */
678
- confidence: number;
679
- /** Threat level classification */
680
- threat_level: 'MINIMAL' | 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
681
- /** True if a bot was detected */
682
- bot_detected: boolean;
683
- /** Type of bot detected (if any) */
684
- bot_type?: string;
685
- /** Unique detection ID */
686
- detection_id: string;
687
- /** True if a response rule was enforced */
688
- rule_enforced: boolean;
299
+ interface DOMRectInfo {
300
+ supported?: boolean;
301
+ rectAWidth?: number;
302
+ rectBWidth?: number;
303
+ rangeWidth?: number;
304
+ [key: string]: unknown;
689
305
  }
690
- /**
691
- * Result of the protect() method
692
- */
693
- interface ProtectResult {
694
- /** Whether to allow the request */
695
- allowed: boolean;
696
- /** Detection response from the service */
697
- detection: SDKDetectionResponse;
698
- /** Error message if the request failed */
699
- error?: string;
700
- /** Rule engine result (if rules were evaluated) */
701
- ruleResult?: RuleEngineResult;
702
- /**
703
- * Web Bot Auth verdict, present when a `webBotAuth()` rule triggered the
704
- * local agent verification for this request. Lets middleware treat a
705
- * `verified` agent specially (e.g. allow) without re-verifying.
706
- */
707
- agent?: AgentVerdict;
708
- /**
709
- * What the edge validator said about this request, parsed from
710
- * `x-wd-clearance` and `x-wd-class`.
711
- *
712
- * Always present. Check `edge.present` before branching: false means the edge
713
- * did not front this request, which is no information rather than a clean bill
714
- * of health.
715
- */
716
- edge?: EdgeVerdict;
306
+ /** AudioContext fingerprint. A real audio stack exposes `baseLatency` and a
307
+ * conventional sample rate; headless/mocked stacks omit or fake these. */
308
+ interface AudioContextInfo {
309
+ supported?: boolean;
310
+ sampleRate?: number;
311
+ state?: string;
312
+ baseLatency?: number | null;
313
+ [key: string]: unknown;
717
314
  }
718
- /**
719
- * Options for the protect() method
720
- */
721
- interface ProtectOptions {
722
- /** Custom threat score threshold for this request */
723
- threshold?: number;
724
- /** Skip local analysis and only use server-side detection */
725
- skipLocalAnalysis?: boolean;
726
- /** Additional metadata to include in the detection */
727
- metadata?: Record<string, any>;
315
+ /** Native-function integrity check. `patched` lists native functions whose
316
+ * `toString()` no longer reports `[native code]` (or whose prototype was
317
+ * tampered with) — the signature of stealth automation hiding itself. A real
318
+ * browser never patches its own natives. */
319
+ interface LieDetectionInfo {
320
+ supported?: boolean;
321
+ patched?: string[];
322
+ patchedCount?: number;
323
+ [key: string]: unknown;
324
+ }
325
+ /** Per-field keystroke statistics for one textarea. */
326
+ interface TextareaKeyboardStats {
327
+ keyCount?: number;
328
+ pasteCount?: number;
329
+ avgKeyInterval?: number;
330
+ keyIntervalVariance?: number;
331
+ keydownUpRatio?: number;
332
+ noKeyboardEvents?: boolean;
333
+ contentLength?: number;
334
+ intervals?: number[];
335
+ dwellTimes?: number[];
336
+ rollovers?: number;
337
+ [key: string]: unknown;
338
+ }
339
+ interface FormSubmitInfo {
340
+ method?: string;
341
+ timeSincePageLoad?: number | null;
342
+ eventsBeforeSubmit?: number;
343
+ hadTriggerEvent?: boolean;
344
+ [key: string]: unknown;
345
+ }
346
+ interface FormAnalysisSignals {
347
+ pageLoadToFirstInteraction?: number | null;
348
+ submit?: FormSubmitInfo;
349
+ textareaKeyboard?: Record<string, TextareaKeyboardStats>;
350
+ [key: string]: unknown;
351
+ }
352
+ /** The full set of signals the client widget reports. */
353
+ interface Signals {
354
+ behavioral?: BehavioralSignals;
355
+ temporal?: TemporalSignals;
356
+ environmental?: EnvironmentalSignals;
357
+ formAnalysis?: FormAnalysisSignals;
358
+ meta?: {
359
+ challengeNonce?: string;
360
+ [key: string]: unknown;
361
+ };
362
+ [key: string]: unknown;
728
363
  }
729
-
730
364
  /**
731
- * Web Decoy API Client
732
- * Handles communication with the ingest service.
733
- *
734
- * Uses the Web-standard `fetch` API (no axios, no `node:` imports) so the SDK
735
- * runs in Node >= 18 and edge runtimes (Vercel Edge Middleware, Cloudflare
736
- * Workers) alike.
365
+ * Outcome of proof-of-work verification, supplied by the caller (the PoW
366
+ * subsystem lands in Phase 2). When omitted and `requirePoW` is enabled the
367
+ * engine emits a hard-fail "No PoW solution provided" detection, matching the
368
+ * reference server.
737
369
  */
738
-
739
- interface ClientConfig {
740
- apiKey: string;
741
- apiUrl: string;
742
- timeout: number;
743
- debug: boolean;
744
- /**
745
- * Kept for API compatibility; the fetch transport does not support disabling
746
- * TLS verification. For local self-signed certs in Node, trust the CA
747
- * instead: `NODE_EXTRA_CA_CERTS=/path/to/ca.pem`.
748
- */
749
- tlsRejectUnauthorized: boolean;
370
+ interface PoWOutcome {
371
+ /** Whether a PoW solution was submitted at all. */
372
+ provided: boolean;
373
+ /** Whether the submitted solution verified. */
374
+ valid?: boolean;
375
+ /** Failure reason when `valid` is false. */
376
+ reason?: string;
377
+ /** Server-measured solve time in ms (un-spoofable). */
378
+ serverElapsed?: number;
379
+ /** Nonce bound to the verified challenge. */
380
+ nonce?: string;
750
381
  }
751
- declare class WebDecoyClient {
752
- private config;
753
- private baseUrl;
754
- private headers;
755
- constructor(config: ClientConfig);
756
- private request;
757
- /**
758
- * Send a detection request to the ingest service
759
- */
760
- detect(request: SDKDetectionRequest): Promise<SDKDetectionResponse>;
761
- /**
762
- * Send violation events to the ingest service
763
- */
764
- sendViolations(events: ViolationEvent[]): Promise<void>;
765
- /**
766
- * Get IP enrichment data from the ingest service
767
- */
768
- getIPEnrichment(ip: string): Promise<IPEnrichmentData | null>;
382
+ /** Per-request context for scoring. */
383
+ interface DetectionContext {
384
+ ip: string;
385
+ siteKey: string;
386
+ userAgent: string;
387
+ /** Lower-cased request headers. */
388
+ headers?: Record<string, string>;
389
+ /** Client-supplied JA3 hash (spoofable). */
390
+ ja3Hash?: string | null;
391
+ /** Trusted reverse-proxy header names carrying a JA4 fingerprint. */
392
+ trustedJA4Headers?: string[];
393
+ /** Proof-of-work verification outcome (supplied by the PoW subsystem). */
394
+ pow?: PoWOutcome;
769
395
  /**
770
- * Validate the API key by making a test request
396
+ * Additional detections to fold into scoring, produced by an outer
397
+ * orchestrator (e.g. the signals-tampering check in the Captcha service).
771
398
  */
772
- validateAPIKey(): Promise<boolean>;
399
+ extraDetections?: Detection[];
400
+ }
401
+ /** Final verdict returned by {@link DetectionEngine.score}. */
402
+ interface Verdict {
403
+ /** True when the weighted score is below the success threshold (< 0.5). */
404
+ success: boolean;
405
+ /** Weighted final score, 0..1. */
406
+ score: number;
407
+ /** Recommended action. */
408
+ recommendation: Recommendation;
409
+ /** Per-category aggregated scores. */
410
+ categoryScores: CategoryScores;
411
+ /** Every triggered detection. */
412
+ detections: Detection[];
413
+ /** Unix seconds at evaluation time. */
414
+ timestamp: number;
773
415
  }
774
416
 
775
- declare class WebDecoy {
776
- private client;
777
- private config;
778
- private ruleEngine;
779
- private violationReporter;
780
- private ipEnrichmentClient;
781
- private _hasFilterRules;
782
- private _hasAgentRules;
783
- private agentVerifier;
784
- private readonly webBotAuthOptions?;
785
- constructor(config: WebDecoyConfig);
786
- /**
787
- * Evaluate rules against request metadata (synchronous).
788
- * Returns null if no rules are configured.
789
- */
790
- evaluateRules(metadata: RequestMetadata): RuleEngineResult | null;
791
- /**
792
- * Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
793
- * verification). Use this instead of evaluateRules() when filter rules or
794
- * webBotAuth() rules are present.
795
- */
796
- evaluateRulesAsync(metadata: RequestMetadata): Promise<RuleEngineResult | null>;
797
- /**
798
- * Register a rule after construction.
799
- *
800
- * For signals whose definition is not available synchronously — the site
801
- * honeytoken's path is derived by async HMAC, so the adapter arms it once the
802
- * derivation settles. Creates the engine if there was none, so an SDK built
803
- * with `rules: []` can still gain one.
804
- */
805
- addRule(rule: Rule): void;
806
- /** Build the base (synchronous) rule context from request metadata. */
807
- private buildContext;
808
- /**
809
- * Build a rule context with async signals resolved: IP enrichment (for
810
- * filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
811
- */
812
- private buildAsyncContext;
813
- /** Evaluate rules against a prepared context and report any violations. */
814
- private runRules;
815
- /** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
816
- private getAgentVerifier;
817
- /**
818
- * Verify a request's Web Bot Auth signature locally, deriving the request
819
- * URL/authority from its metadata. Returns undefined when the request lacks
820
- * the host information needed to verify (verdict is then simply absent).
821
- */
822
- private computeAgentVerdict;
823
- /**
824
- * Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
825
- * "web-bot-auth"). Returns whether it is a cryptographically `verified`
826
- * agent, an `impersonation` of a known one, an unverifiable `claimed`
827
- * signature, or `none`. No network on the warm path.
828
- *
829
- * Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
830
- * object (Node).
831
- *
832
- * @example
833
- * ```ts
834
- * const verdict = await webdecoy.detectBot(request);
835
- * if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
836
- * if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
837
- * ```
838
- */
839
- detectBot(request: AgentRequestInput): Promise<AgentVerdict>;
840
- /**
841
- * Whether this SDK instance has filter rules that need async enrichment
842
- */
843
- get hasFilterRules(): boolean;
844
- /**
845
- * Whether this SDK instance has Web Bot Auth rules that need async
846
- * verification before evaluation.
847
- */
848
- get hasAgentRules(): boolean;
849
- /**
850
- * Protect a request by checking it against Web Decoy's bot detection
851
- *
852
- * @param metadata - Request metadata to analyze
853
- * @param options - Optional configuration for this specific request
854
- * @returns Protection result with decision and detection details
855
- */
856
- protect(metadata: RequestMetadata, options?: ProtectOptions): Promise<ProtectResult>;
857
- private decide;
858
- /**
859
- * Report a test-trigger request and return a blocking verdict.
860
- *
861
- * The verdict is `allowed: false` so an enforce-mode adapter answers the
862
- * curl with a 403 — a visibly different response that tells the developer
863
- * their middleware acted, Arcjet-quickstart style. (The default monitor
864
- * mode still serves the request; the dashboard row is the real receipt.)
865
- *
866
- * Without an API key nothing can reach the dashboard, so the verdict says
867
- * so via `error` instead of pretending the test ran.
868
- */
869
- private reportTestTrigger;
870
- /**
871
- * Validate the API key configuration
872
- * Useful for testing integration during setup
873
- */
874
- validateConfig(): Promise<{
875
- valid: boolean;
876
- error?: string;
877
- }>;
878
- /**
879
- * Attach a violation reporter for sending violations to the backend.
880
- * Called internally when apiKey is present and rules are configured.
881
- */
882
- setViolationReporter(reporter: {
883
- report(violations: ViolationEvent[]): void;
884
- flush(): Promise<void>;
885
- destroy(): Promise<void>;
886
- }): void;
887
- /**
888
- * Get the API client (for use by violation reporter, enrichment, etc.)
889
- */
890
- getClient(): WebDecoyClient | null;
891
- /**
892
- * Get the current configuration
893
- */
894
- getConfig(): Readonly<typeof this.config>;
417
+ /**
418
+ * In-memory stores backing the stateful detectors (fingerprint correlation and
419
+ * rate abuse). Ported from FCaptcha index.js.
420
+ *
421
+ * These are defined behind interfaces so Phase 2 can swap in a shared/Redis
422
+ * backend for serverless and multi-instance deployments.
423
+ */
424
+ /** Tracks fingerprint ↔ IP relationships to spot distributed attacks. */
425
+ interface FingerprintStore {
426
+ record(fp: string, ip: string, siteKey: string): void;
427
+ /** Number of distinct fingerprints seen from `ip`. */
428
+ getIpFpCount(ip: string): number;
429
+ /** Number of distinct IPs that produced fingerprint `fp` for `siteKey`. */
430
+ getFpIpCount(fp: string, siteKey: string): number;
431
+ }
432
+ /** Sliding-window request counter. */
433
+ interface RateLimiter {
434
+ /** Returns `[exceeded, count]` for the window, recording this hit. */
435
+ check(key: string, windowSeconds?: number, maxRequests?: number): [boolean, number];
436
+ }
437
+ declare class InMemoryFingerprintStore implements FingerprintStore {
438
+ private fingerprints;
439
+ private ipFingerprints;
440
+ record(fp: string, ip: string, siteKey: string): void;
441
+ getIpFpCount(ip: string): number;
442
+ getFpIpCount(fp: string, siteKey: string): number;
443
+ }
444
+ declare class InMemoryRateLimiter implements RateLimiter {
445
+ private requests;
446
+ check(key: string, windowSeconds?: number, maxRequests?: number): [boolean, number];
447
+ }
448
+
449
+ /**
450
+ * Detection engine.
451
+ *
452
+ * Runs the full FCaptcha detector suite in-process and produces a {@link Verdict}.
453
+ * Mirrors the reference server's `runVerification` orchestration. The actual
454
+ * proof-of-work crypto and token issuance land in Phase 2 — for now the caller
455
+ * supplies a {@link PoWOutcome} and the engine emits the matching detections.
456
+ */
457
+
458
+ interface DetectionEngineOptions {
459
+ /** Override the per-category weights (defaults to {@link DEFAULT_WEIGHTS}). */
460
+ weights?: Record<string, number>;
895
461
  /**
896
- * Clean up resources (timers, flush pending violations)
462
+ * When true (default), a request with no PoW outcome emits a hard-fail "No PoW
463
+ * solution provided" detection — matching the reference server. Set false to
464
+ * score raw signals without requiring proof-of-work.
897
465
  */
898
- destroy(): Promise<void>;
466
+ requirePoW?: boolean;
467
+ /** Fingerprint-correlation store (defaults to an in-memory store). */
468
+ fingerprintStore?: FingerprintStore;
469
+ /** Rate limiter for rate-abuse detection (defaults to in-memory). */
470
+ rateLimiter?: RateLimiter;
471
+ }
472
+ declare class DetectionEngine {
473
+ private readonly weights;
474
+ private readonly requirePoW;
475
+ private readonly fingerprintStore;
476
+ private readonly rateLimiter;
477
+ constructor(options?: DetectionEngineOptions);
478
+ /** Score `signals` for the given request context and return a verdict. */
479
+ score(signals: Signals, context: DetectionContext): Verdict;
899
480
  }
900
481
 
482
+ /** Score aggregation: per-category confidence-weighted means → weighted total. */
483
+
901
484
  /**
902
- * The reserved test trigger.
903
- *
904
- * A request whose User-Agent starts with `WebDecoy-Test/` is the documented
905
- * install-verification probe:
906
- *
907
- * curl -A "WebDecoy-Test/1.0" http://localhost:3000/
485
+ * Aggregate detections into per-category scores. Each category's score is the
486
+ * confidence-weighted mean of its detections' scores, capped at 1.0. Categories
487
+ * present in `weights` but with no detections are filled with 0.
488
+ */
489
+ declare function calculateCategoryScores(detections: Detection[], weights: Record<string, number>): CategoryScores;
490
+ /** Combine category scores into the final weighted score (capped at 1.0). */
491
+ declare function calculateFinalScore(categoryScores: CategoryScores, weights: Record<string, number>): number;
492
+ /** Map a final score to an action recommendation. */
493
+ declare function recommend(finalScore: number): Recommendation;
494
+
495
+ /**
496
+ * Category weights and automation UA patterns.
908
497
  *
909
- * The SDK always reports it to ingest — before rules, before local-analysis
910
- * thresholds, before sampling of any kind — so the developer who just
911
- * installed the middleware gets a guaranteed, labeled detection in the
912
- * dashboard within seconds, including from localhost. Ingest recognizes the
913
- * same prefix server-side, marks the row `is_test`, and keeps it out of
914
- * stats, billing, actor scoring, and enforcement.
498
+ * Values match the FCaptcha standalone server (server.js), which is the most
499
+ * complete variant of the engine and the one the reference test suite exercises.
500
+ */
501
+ /**
502
+ * Default per-category weights used to compute the final score.
915
503
  *
916
- * Prefix-anchored on purpose: a UA that merely mentions the string mid-way
917
- * is NOT the trigger, so real traffic can't hide behind the test label.
504
+ * `stealth` carries deliberate anti-detection tampering (native functions
505
+ * patched to hide automation). This is the least-ambiguous evidence of a bot —
506
+ * a genuine browser never patches its own natives — so it is weighted highest.
507
+ * Because weights are a simple weighted sum (not required to total 1.0), and
508
+ * `stealth` is 0 for any clean browser, this raises stealth-bot scores without
509
+ * affecting legitimate traffic.
918
510
  */
919
- /** Any User-Agent starting with this (case-insensitive) is a test trigger. */
920
- declare const TEST_TRIGGER_UA_PREFIX = "WebDecoy-Test/";
921
- /** The exact value the quickstart docs tell developers to send. */
922
- declare const TEST_TRIGGER_USER_AGENT = "WebDecoy-Test/1.0";
923
- /** Whether this User-Agent is the reserved test trigger. */
924
- declare function isTestTriggerUserAgent(userAgent: string | undefined): boolean;
511
+ declare const DEFAULT_WEIGHTS: Record<string, number>;
512
+
513
+ /** True when `ip` falls inside a known datacenter CIDR block (IPv4 only). */
514
+ declare function isDatacenterIP(ip: string): boolean;
925
515
 
926
516
  /**
927
- * Resolving the client IP address behind a proxy.
517
+ * User-Agent parsing and bot-pattern matching. Ported from FCaptcha detection.js.
518
+ */
519
+ interface UserAgentInfo {
520
+ browser: string | null;
521
+ os: string | null;
522
+ isMobile: boolean;
523
+ isBot: boolean;
524
+ botName: string | null;
525
+ }
526
+ /** True when the UA looks like a mobile device. */
527
+ declare function isMobileUA(userAgent: string): boolean;
528
+ /** Extract browser/OS/bot info from a User-Agent string. */
529
+ declare function parseUserAgent(ua: string): UserAgentInfo;
530
+
531
+ /**
532
+ * What the browser told us, made available to the request that follows.
928
533
  *
929
- * WHY THIS MODULE EXISTS
534
+ * WHY THIS EXISTS
930
535
  *
931
- * Every adapter used to read the leftmost value of `X-Forwarded-For` and call it
932
- * the client. That header is written by the client for the first hop, so the
933
- * leftmost value is whatever the caller decided to put there. One
934
- * `-H 'X-Forwarded-For: 1.2.3.4'` gave an attacker a fresh rate-limit bucket per
935
- * forged address, put an address of their choosing on every violation we
936
- * reported, and made `filter({ expression: 'ip.tor' })` an opt-in check.
536
+ * `@webdecoy/client` collects behavioural, environmental and form signals and
537
+ * can run proof-of-work; `DetectionEngine` scores them; `/score` already
538
+ * accepted a submission and returned a verdict. The parts were all there and
539
+ * they were not connected: the verdict went back to the browser, and the next
540
+ * request to the origin knew nothing about it. Joining the two was left as an
541
+ * exercise for the developer, so in practice nobody did.
937
542
  *
938
- * A forwarding header is only evidence if you know who wrote it. So the default
939
- * here is to not read one at all: use the address the connection actually came
940
- * from, and make the operator say how many proxies sit in front before we
941
- * believe anything else. The WordPress plugin already works this way; this
942
- * brings the Node adapters in line.
543
+ * That matters because this is the SDK's answer to the one thing a tripwire
544
+ * cannot catch — a real browser, driven by Playwright, that follows no hidden
545
+ * links and requests no honeypot paths. It has a genuine fingerprint and it
546
+ * still cannot fake human interaction. Competitors launched exactly this shape
547
+ * as a headline feature; we have had the parts for longer and no way to use
548
+ * them.
943
549
  *
944
- * THE MODEL
550
+ * WHAT IT IS NOT
945
551
  *
946
- * Each proxy appends the address it received the connection from, so the
947
- * observed chain outermost-first is `[...X-Forwarded-For, peer]` and the entries
948
- * to the RIGHT are the ones added by infrastructure you control. Trust is
949
- * therefore counted from the right: with one proxy in front of you, the client
950
- * is the last `X-Forwarded-For` entry; with two, the second from last. Anything
951
- * further left was supplied by someone you have no reason to believe.
552
+ * A client signal is a claim by code running on the client, so it is evidence
553
+ * about a cooperative browser and nothing else. No JavaScript means no signals,
554
+ * which is why {@link ClientSignalRule} treats "absent" as `NOT_RUN` rather than
555
+ * as suspicion: a curl request and a search crawler both send nothing, and
556
+ * scoring silence would deny the crawlers we most need to keep.
952
557
  *
953
- * No `node:net` — this runs in Edge and Workers runtimes too, so the address
954
- * parsing is hand-rolled and covered by tests.
558
+ * This augments the keyless deterministic rules. It does not replace them.
955
559
  */
560
+
561
+ /** The engine's verdict on one browser session. */
562
+ interface ClientVerdict {
563
+ /** Session id supplied by the browser widget. */
564
+ sessionId: string;
565
+ /** 0–1, higher is more bot-like. */
566
+ score: number;
567
+ /** What the engine recommends doing about it. */
568
+ recommendation: Recommendation;
569
+ /** When the verdict was recorded, Unix ms. */
570
+ at: number;
571
+ }
572
+ /**
573
+ * Where verdicts live between the `/score` submission and the requests that
574
+ * follow it.
575
+ *
576
+ * Same sync/async split as the rate-limit store, and for the same reason: an
577
+ * in-memory default must not make every rule evaluation a promise.
578
+ */
579
+ interface ClientSignalStore {
580
+ readonly sync: boolean;
581
+ get(sessionId: string): ClientVerdict | undefined | Promise<ClientVerdict | undefined>;
582
+ set(verdict: ClientVerdict): void | Promise<void>;
583
+ }
584
+ interface MemoryClientSignalStoreOptions {
585
+ /** How long a verdict stays usable. @default 900_000 (15 minutes) */
586
+ ttl?: number;
587
+ /** Maximum sessions held. @default 10_000 */
588
+ max?: number;
589
+ }
590
+ declare class MemoryClientSignalStore implements ClientSignalStore {
591
+ readonly sync: true;
592
+ private readonly ttl;
593
+ private readonly max;
594
+ private entries;
595
+ constructor(options?: MemoryClientSignalStoreOptions);
596
+ get(sessionId: string): ClientVerdict | undefined;
597
+ set(verdict: ClientVerdict): void;
598
+ get size(): number;
599
+ }
600
+ /** The cookie the widget sets, and the header it will also accept. */
601
+ declare const CLIENT_SESSION_COOKIE = "wd_cs";
602
+ declare const CLIENT_SESSION_HEADER = "x-wd-session";
603
+ /** Read the browser session id off a request, cookie first then header. */
604
+ declare function readClientSession(headers: Record<string, string>): string | undefined;
605
+ interface ClientSignalConfig {
606
+ /** Where verdicts are read from. Must be the store `/score` writes to. */
607
+ store: ClientSignalStore;
608
+ /**
609
+ * Deny at or above this score, 0–1. The engine's own `recommendation` is used
610
+ * when this is omitted.
611
+ */
612
+ minScore?: number;
613
+ /** Action on a match. @default 'DENY' */
614
+ action?: 'DENY' | 'THROTTLE';
615
+ /** Log the violation but do not block. */
616
+ dryRun?: boolean;
617
+ }
956
618
  /**
957
- * How much of the forwarding chain to believe.
619
+ * Act on what the browser widget reported for this session.
958
620
  *
959
- * - `false` (default) — read no forwarding headers; the peer address is the
960
- * client. Correct for an app exposed directly, and safe for one that isn't:
961
- * it attributes traffic to your proxy rather than to a forged address.
962
- * - `number` — the number of trusted proxies between the client and this
963
- * process. The client is the Nth entry from the right of `X-Forwarded-For`.
964
- * - `'cloudflare'` — use `CF-Connecting-IP`. Only meaningful if the origin is
965
- * unreachable except through Cloudflare, since the header is otherwise just
966
- * another thing a client can send.
967
- * - `string[]` — CIDRs (or bare addresses) of the proxies you run. The chain is
968
- * walked right to left and the first address that isn't one of yours is the
969
- * client. Use this when the depth varies.
621
+ * A request with no session — no JavaScript, no widget, a crawler, curl — is
622
+ * `NOT_RUN`, never a denial. See the module note.
970
623
  */
971
- type TrustedProxies = false | number | 'cloudflare' | string[];
972
- /** Headers as either a Node-style bag or a WHATWG `Headers`. */
973
- type HeaderSource = Record<string, string | string[] | undefined> | {
974
- get(name: string): string | null;
975
- };
976
- interface ResolveClientIpOptions {
977
- /** Request headers. */
978
- headers: HeaderSource;
979
- /** The address the connection came from, when the runtime exposes one. */
980
- peer?: string;
981
- /** How much of the forwarding chain to believe. Defaults to `false`. */
982
- trustProxy?: TrustedProxies;
983
- }
984
- /**
985
- * Strip the decoration real-world sources add to an address — brackets, a port,
986
- * an IPv6 zone id — and return it in a canonical form, or null if what's left
987
- * isn't an address at all.
988
- *
989
- * IPv4-mapped IPv6 (`::ffff:203.0.113.9`) collapses to the IPv4 form, so a
990
- * dual-stack listener and an `X-Forwarded-For` entry for the same client
991
- * produce the same key.
992
- */
993
- declare function normalizeIp(raw: string | undefined | null): string | null;
994
- /**
995
- * Whether an address falls inside a CIDR range. A bare address is treated as a
996
- * single-host range. Families never match across each other.
997
- */
998
- declare function ipInCidr(ip: string, cidr: string): boolean;
999
- /**
1000
- * Resolve the client IP for a request.
1001
- *
1002
- * Returns `undefined` only when there is nothing to go on: no peer address and
1003
- * no header the configuration says to believe. Callers supply their own last
1004
- * resort, because what that should be is a per-framework question.
1005
- *
1006
- * Whenever the configured source is missing or malformed this falls back to the
1007
- * peer address rather than reaching further left in the chain. The peer is the
1008
- * one address on a request that cannot be forged, so a wrong-but-real proxy
1009
- * address beats a plausible-looking value the caller chose.
1010
- */
1011
- declare function resolveClientIp(options: ResolveClientIpOptions): string | undefined;
624
+ declare class ClientSignalRule implements Rule {
625
+ readonly name = "client-signals";
626
+ private readonly store;
627
+ private readonly minScore?;
628
+ private readonly action;
629
+ private readonly dryRun;
630
+ constructor(config: ClientSignalConfig);
631
+ prepare(context: RuleContext): Promise<void>;
632
+ evaluate(context: RuleContext): RuleResult;
633
+ }
634
+ /** Act on the browser widget's verdict for this session. See {@link ClientSignalConfig}. */
635
+ declare function clientSignals(config: ClientSignalConfig): Rule;
1012
636
 
1013
637
  /**
1014
638
  * Rule Engine
@@ -1044,9 +668,20 @@ declare class RuleEngine {
1044
668
 
1045
669
  declare class RateLimitRule implements Rule {
1046
670
  readonly name: string;
1047
- private limiter;
671
+ private store;
1048
672
  private config;
1049
673
  constructor(config: RateLimitConfig);
674
+ /**
675
+ * Which bucket this request counts against.
676
+ *
677
+ * Precedence: this rule's own keyBy, then the SDK-wide characteristics, then
678
+ * the IP. `context.key` is always populated, so the last fallback only matters
679
+ * for a context built by hand.
680
+ */
681
+ private keyFor;
682
+ private consumption;
683
+ /** Consume from a networked store before evaluation. No-op for a sync store. */
684
+ prepare(context: RuleContext): Promise<void>;
1050
685
  evaluate(context: RuleContext): RuleResult;
1051
686
  destroy(): void;
1052
687
  }
@@ -1133,6 +768,174 @@ declare class BotRule implements Rule {
1133
768
  evaluate(context: RuleContext): RuleResult;
1134
769
  }
1135
770
 
771
+ /**
772
+ * One bot policy, published and enforced.
773
+ *
774
+ * WHY THIS EXISTS
775
+ *
776
+ * `BOT_REGISTRY` is generated from the Go registry and already carries the
777
+ * customer-facing categories. `bots()` enforces against that table. Nothing
778
+ * published from it — so every site that wanted to control AI crawlers
779
+ * hand-wrote a `robots.txt` that drifted from whatever the code actually did.
780
+ *
781
+ * Drift here is not cosmetic. A `robots.txt` that disallows GPTBot while the
782
+ * middleware lets it through is a policy the operator believes is in force and
783
+ * is not. The reverse — enforcing against a crawler the published file invites —
784
+ * is how a site quietly disappears from a search index.
785
+ *
786
+ * So the two come from one object:
787
+ *
788
+ * ```ts
789
+ * const policy = botPolicy({ deny: ['training_crawler'], allow: ['perplexitybot'] });
790
+ *
791
+ * app.get('/robots.txt', (_req, res) => res.type('text/plain').send(policy.robotsTxt()));
792
+ * const wd = new WebDecoy({ rules: [policy.rule()] });
793
+ * ```
794
+ *
795
+ * WHAT ROBOTS.TXT IS AND IS NOT
796
+ *
797
+ * It is a request, honoured at the crawler's discretion. The registry records
798
+ * whether each operator *documents* honouring it, which is a claim rather than
799
+ * an observation, and {@link BotPolicy.unenforceable} lists the agents in your
800
+ * deny set that do not even claim it. Those are the ones the rule is actually
801
+ * doing the work for, and `robotsTxt()` names them in a comment so the file
802
+ * itself says which half of the policy is voluntary.
803
+ */
804
+
805
+ interface BotPolicyOptions {
806
+ /**
807
+ * What the policy is against: category names (`'training_crawler'`), agent
808
+ * slugs or display names (`'gptbot'`, `'GPTBot'`), or the literal `'ai'` for
809
+ * every AI client.
810
+ */
811
+ deny?: (BotCategory | 'ai' | string)[];
812
+ /** Never act on these, whatever else matches. Applied last. */
813
+ allow?: string[];
814
+ /** Action the rule takes on a match. @default 'DENY' */
815
+ action?: 'DENY' | 'THROTTLE';
816
+ /** Rule logs but does not block. Does not change what `robotsTxt()` emits. */
817
+ dryRun?: boolean;
818
+ }
819
+ interface RobotsTxtOptions {
820
+ /** Absolute sitemap URL, emitted as a `Sitemap:` line. */
821
+ sitemap?: string;
822
+ /** `Crawl-delay` in seconds, applied to the wildcard group. */
823
+ crawlDelay?: number;
824
+ /**
825
+ * Emit a trailing `User-agent: *` group allowing everything else.
826
+ * @default true
827
+ */
828
+ allowOthers?: boolean;
829
+ /** Paths to disallow for every agent, e.g. `['/admin']`. */
830
+ disallow?: string[];
831
+ /**
832
+ * Include the header comment naming agents that do not document honouring
833
+ * robots.txt. @default true
834
+ */
835
+ annotate?: boolean;
836
+ }
837
+ declare class BotPolicy {
838
+ private readonly config;
839
+ /** The agents this policy is against, resolved from the registry. */
840
+ readonly matched: readonly BotAgent[];
841
+ constructor(options?: BotPolicyOptions);
842
+ /**
843
+ * Agents in the deny set whose operator does not document honouring
844
+ * robots.txt. Publishing still declares the policy; only the rule enforces it
845
+ * against these.
846
+ */
847
+ get unenforceable(): readonly BotAgent[];
848
+ /** The enforcing rule. Denies exactly the agents in {@link matched}. */
849
+ rule(): Rule;
850
+ /** The published policy, as a `robots.txt` body. */
851
+ robotsTxt(options?: RobotsTxtOptions): string;
852
+ }
853
+ /**
854
+ * A bot policy you can both publish and enforce. See {@link BotPolicy}.
855
+ */
856
+ declare function botPolicy(options?: BotPolicyOptions): BotPolicy;
857
+
858
+ /**
859
+ * Attack payloads in the request.
860
+ *
861
+ * WHAT THIS IS, AND WHAT IT REFUSES TO BE
862
+ *
863
+ * Tripwires catch scanners by the **path** they ask for. Nothing here looked at
864
+ * what those same scanners *send* — the injection strings in a query, the
865
+ * traversal in a parameter, the `${jndi:` in a header. Their absence read as
866
+ * "this only does honeypots".
867
+ *
868
+ * This is not a WAF and should not grow into one. A WAF's value is breadth, and
869
+ * breadth is bought with false positives on ordinary traffic — which is the
870
+ * complaint every incumbent's customers have. What this is: a small, curated set
871
+ * of signatures that are unambiguous, cheap, and useful precisely because they
872
+ * compose with the deterministic signals. A request that carries an injection
873
+ * payload *and* walks into a tripwire is a far stronger detection than either
874
+ * alone, and both are facts rather than probabilities.
875
+ *
876
+ * FALSE POSITIVES ARE THE DESIGN CONSTRAINT
877
+ *
878
+ * By default only the path and query string are inspected. Bodies and headers
879
+ * are opt-in, because a CMS saving an article, a template in a JSON payload and
880
+ * a URL passed as a query parameter all legitimately contain things that look
881
+ * like attacks. Inspecting them is the right call for an API that never carries
882
+ * markup, and the wrong one for a publishing tool — so it is the operator's
883
+ * call, and `dryRun` is the way to find out.
884
+ *
885
+ * PERFORMANCE IS ALSO A CONSTRAINT
886
+ *
887
+ * Every pattern is anchored or literal, with no nested quantifiers — a regex
888
+ * that backtracks catastrophically on a crafted input turns a detection rule
889
+ * into the denial of service it was meant to catch. Input is truncated before
890
+ * matching, and decoded a bounded number of times.
891
+ */
892
+
893
+ interface AttackSignatureConfig {
894
+ /**
895
+ * Which parts of the request to inspect.
896
+ *
897
+ * Defaults to `['path', 'query']`, which is where a signature has no innocent
898
+ * reading. `'body'` and `'headers'` are opt-in: a CMS saving an article, a
899
+ * template inside a JSON payload and a URL passed as a parameter all
900
+ * legitimately contain things that look like attacks. Start those in `dryRun`.
901
+ *
902
+ * @default ['path', 'query']
903
+ */
904
+ inspect?: ('path' | 'query' | 'body' | 'headers')[];
905
+ /**
906
+ * Bytes of each inspected part to scan. Beyond this the input is truncated,
907
+ * so a large body cannot turn matching into the denial of service the rule
908
+ * exists to catch.
909
+ * @default 8192
910
+ */
911
+ maxBytes?: number;
912
+ /** Signature ids to skip, e.g. `['traversal']`. */
913
+ exclude?: string[];
914
+ /** Action on a match. @default 'DENY' */
915
+ action?: 'DENY' | 'THROTTLE';
916
+ /** Log the violation but do not block. */
917
+ dryRun?: boolean;
918
+ }
919
+ declare class AttackSignatureRule implements Rule {
920
+ readonly name = "attack-signatures";
921
+ private readonly inspect;
922
+ private readonly maxBytes;
923
+ private readonly signatures;
924
+ private readonly action;
925
+ private readonly dryRun;
926
+ constructor(config?: AttackSignatureConfig);
927
+ evaluate(context: RuleContext): RuleResult;
928
+ private parts;
929
+ }
930
+ /**
931
+ * Deny requests carrying unambiguous attack payloads. See
932
+ * {@link AttackSignatureConfig} — and note that this is a small curated set, not
933
+ * a WAF.
934
+ */
935
+ declare function attackSignatures(config?: AttackSignatureConfig): Rule;
936
+ /** The signature ids, for `exclude` and for tests. */
937
+ declare const ATTACK_SIGNATURE_IDS: readonly string[];
938
+
1136
939
  /**
1137
940
  * Web Bot Auth rule (the main application repo).
1138
941
  *
@@ -1231,6 +1034,86 @@ interface Honeytoken {
1231
1034
  */
1232
1035
  declare function honeytoken(options?: HoneytokenOptions): Honeytoken;
1233
1036
 
1037
+ /**
1038
+ * Rate-limit counters in Upstash Redis.
1039
+ *
1040
+ * WHY UPSTASH, AND WHY NO DEPENDENCY
1041
+ *
1042
+ * Upstash speaks Redis over HTTP, which is the only shape that works everywhere
1043
+ * this SDK runs: Vercel Edge, Cloudflare Workers and Deno have no `node:net`, so
1044
+ * an ordinary Redis client cannot open a socket there. The core package already
1045
+ * passes an edge-compatibility gate, and a store that only worked on Node would
1046
+ * be unavailable in exactly the serverless deployments that need shared counters
1047
+ * most.
1048
+ *
1049
+ * It talks to the REST API with `fetch` rather than pulling in `@upstash/redis`.
1050
+ * Two commands in a pipeline is not worth a dependency, a version to track, or a
1051
+ * transitive `node:` import finding its way into an edge bundle.
1052
+ *
1053
+ * ```ts
1054
+ * rateLimit({
1055
+ * max: 100,
1056
+ * window: 60,
1057
+ * store: upstashRateLimitStore({
1058
+ * url: process.env.UPSTASH_REDIS_REST_URL!,
1059
+ * token: process.env.UPSTASH_REDIS_REST_TOKEN!,
1060
+ * }),
1061
+ * })
1062
+ * ```
1063
+ */
1064
+
1065
+ interface UpstashStoreOptions {
1066
+ /** REST endpoint, e.g. `https://eu1-xxx.upstash.io`. */
1067
+ url: string;
1068
+ /** REST token. */
1069
+ token: string;
1070
+ /** Prefix for every key written. @default 'wd:rl:' */
1071
+ prefix?: string;
1072
+ /** Request timeout in milliseconds. @default 1000 */
1073
+ timeout?: number;
1074
+ /**
1075
+ * What to do when Redis is unreachable.
1076
+ *
1077
+ * `'open'` (default) allows the request: a rate limiter that takes the site
1078
+ * down when its datastore has a bad minute has done more damage than the
1079
+ * traffic it was shaping. `'closed'` denies, for a limit that is protecting
1080
+ * something more expensive than availability.
1081
+ *
1082
+ * Either way the outcome is reported, so the decision says which happened
1083
+ * rather than looking like a normal evaluation.
1084
+ */
1085
+ onError?: 'open' | 'closed';
1086
+ }
1087
+ declare class UpstashRateLimitStore implements RateLimitStore {
1088
+ readonly sync: false;
1089
+ private readonly url;
1090
+ private readonly token;
1091
+ private readonly prefix;
1092
+ private readonly timeout;
1093
+ private readonly failOpen;
1094
+ constructor(options: UpstashStoreOptions);
1095
+ consume(input: RateLimitConsume): Promise<RateLimitOutcome>;
1096
+ /**
1097
+ * Fixed window: one counter per key per window.
1098
+ *
1099
+ * The window id is in the key rather than tracked separately, so expiry is the
1100
+ * only cleanup needed and two processes incrementing concurrently cannot
1101
+ * disagree about which window they are in.
1102
+ */
1103
+ private fixed;
1104
+ /**
1105
+ * Sliding window: a sorted set of request timestamps, trimmed on every read.
1106
+ *
1107
+ * The member is timestamp plus random bytes because two requests in the same
1108
+ * millisecond would otherwise be one ZADD that overwrites rather than two that
1109
+ * count — undercounting exactly when the limit matters.
1110
+ */
1111
+ private sliding;
1112
+ private pipeline;
1113
+ }
1114
+ /** Rate-limit counters shared through Upstash Redis. See {@link UpstashStoreOptions}. */
1115
+ declare function upstashRateLimitStore(options: UpstashStoreOptions): RateLimitStore;
1116
+
1234
1117
  /**
1235
1118
  * Site honeytoken — a stable, derivable trap the adapters can inject for you
1236
1119
  *.
@@ -1391,567 +1274,311 @@ declare function filter(config: FilterConfig): Rule;
1391
1274
  * const hp = honeytoken();
1392
1275
  * const sdk = new WebDecoy({
1393
1276
  * rules: [
1394
- * tripwire({ paths: [hp.path] }), // + built-in scanner-bait paths
1395
- * ],
1396
- * });
1397
- * // inject hp.linkHtml into your pages
1398
- * ```
1399
- */
1400
- declare function tripwire(config?: TripwireConfig): Rule;
1401
- /**
1402
- * Factory function to create a bot-category rule.
1403
- *
1404
- * Acts on agents that identify themselves in the User-Agent, matched against the
1405
- * registry generated from the same table the scoring pipeline uses — so
1406
- * `'training_crawler'` here means what `ai_scraper_category` means in your
1407
- * dashboard.
1408
- *
1409
- * @example
1410
- * ```typescript
1411
- * import { WebDecoy, bots } from '@webdecoy/node';
1412
- *
1413
- * const sdk = new WebDecoy({
1414
- * rules: [
1415
- * // Keep AI models out of your content, keep your search ranking.
1416
- * bots({ categories: ['training_crawler'] }),
1417
- *
1418
- * // Or everything AI, minus the one you want referral traffic from.
1419
- * bots({ ai: true, allow: ['perplexitybot'] }),
1420
- *
1421
- * // Or a specific operator.
1422
- * bots({ agents: ['gptbot', 'ClaudeBot'], action: 'THROTTLE' }),
1423
- * ],
1424
- * });
1425
- * ```
1426
- *
1427
- * Only catches agents that declare themselves — anything spoofing a browser
1428
- * passes through, by design. Pair with {@link tripwire} for agents that lie.
1429
- */
1430
- declare function bots(config?: BotRuleConfig): Rule;
1431
-
1432
- /**
1433
- * AgentVerifier — the public entry point for local Web Bot Auth verification.
1434
- *
1435
- * Wraps the cached directory client and the signature core into a single
1436
- * `verify(request)` call returning an {@link AgentVerdict}. Designed for the
1437
- * hot path of edge/Node middleware: warm verification is a header parse, one
1438
- * map lookup, and one WebCrypto verify — no network, well under the 5ms p95
1439
- * budget in the acceptance criteria.
1440
- */
1441
-
1442
- declare class AgentVerifier {
1443
- private readonly cache;
1444
- private readonly toleranceSec;
1445
- constructor(options?: AgentVerifierOptions);
1446
- /** Pre-fetch trusted directories so the first request verifies warm. */
1447
- warmup(): void;
1448
- /** Verify a request's Web Bot Auth signature (if any) locally. */
1449
- verify(request: AgentRequestInput): Promise<AgentVerdict>;
1450
- /** Cached-key count (diagnostics/tests). */
1451
- get cachedKeyCount(): number;
1452
- }
1453
- /** Convenience factory mirroring the SDK's other `create*` helpers. */
1454
- declare function createAgentVerifier(options?: AgentVerifierOptions): AgentVerifier;
1455
-
1456
- /**
1457
- * RFC 9421 HTTP Message Signatures — the Web Bot Auth verification core.
1458
- *
1459
- * Verifies signatures tagged `web-bot-auth`: parse `Signature-Input` /
1460
- * `Signature`, rebuild the signature base for each covered-component set, and
1461
- * check the raw signature with WebCrypto against a key resolved by its JWK
1462
- * thumbprint keyid. Adapted from the WebDecoy edge validator
1463
- * (`edge/clearance-worker/src/web-bot-auth.ts`), generalized to resolve keys
1464
- * from a directory cache instead of a pushed key list.
1465
- *
1466
- * Zero dependencies, Edge-runtime safe: only `crypto.subtle`, `TextEncoder`,
1467
- * `atob`, and `URL` are used.
1468
- */
1469
- /** A verification key resolved from a trusted directory, ready for WebCrypto. */
1470
- interface VerificationKey {
1471
- cryptoKey: CryptoKey;
1472
- /** WebCrypto verify params (e.g. `{ name: 'Ed25519' }`). */
1473
- verifyParams: AlgorithmIdentifier | RsaPssParams;
1474
- /** Human-readable algorithm label, e.g. "ed25519". */
1475
- algorithm: string;
1476
- /** Display name of the owning agent. */
1477
- name: string;
1478
- /** Category of the owning agent. */
1479
- category: string;
1480
- /** Key validity bounds in Unix seconds, if the directory published them. */
1481
- nbf?: number;
1482
- exp?: number;
1483
- }
1484
- /** Resolves a JWK-thumbprint keyid to a verification key, or undefined if unknown. */
1485
- type KeyResolver = (keyId: string) => Promise<VerificationKey | undefined>;
1486
-
1487
- /**
1488
- * Cached Web Bot Auth directory client.
1489
- *
1490
- * Fetches the JWK sets of a **curated** set of trusted agent directories,
1491
- * imports their keys into WebCrypto, and indexes them by JWK-thumbprint keyid
1492
- * so signatures resolve in O(1) with zero network on the warm path.
1493
- *
1494
- * Security posture — the reason this is curated-only:
1495
- * a request's own `Signature-Agent` header is **never** used to choose a fetch
1496
- * target, so an attacker cannot make the middleware fetch an arbitrary URL
1497
- * (no SSRF). Only the origins in {@link AgentVerifierOptions.directories} are
1498
- * ever contacted. This mirrors the backend curation
1499
- * (`backend/internal/services/signed_agents.go`).
1500
- *
1501
- * Freshness — stale-while-revalidate: once populated, an expired cache keeps
1502
- * serving its keys while a background refresh runs, so verification latency is
1503
- * never coupled to a directory fetch. A cold cache (never populated) blocks
1504
- * once to fetch, then backs off briefly if every directory is unreachable so a
1505
- * degraded network can't be hammered per request.
1506
- */
1507
-
1508
- /**
1509
- * The default curated allowlist. These are the agents that sign production
1510
- * traffic today; kept in lock-step with the backend's curated list.
1511
- */
1512
- declare const DEFAULT_SIGNED_AGENT_DIRECTORIES: SignedAgentDirectory[];
1513
- interface DirectoryCacheOptions {
1514
- directories: SignedAgentDirectory[];
1515
- cacheTtlMs: number;
1516
- fetchTimeoutMs: number;
1517
- debug: boolean;
1518
- fetchImpl: typeof fetch;
1519
- }
1520
- declare class DirectoryCache {
1521
- private readonly opts;
1522
- private keys;
1523
- private refreshedAt;
1524
- private nextColdRetryAt;
1525
- private inflight;
1526
- constructor(opts: DirectoryCacheOptions);
1527
- /** Resolve a keyid to a verification key, fetching/refreshing as needed. */
1528
- resolveKey: KeyResolver;
1529
- /** Kick off a fetch without blocking — call at startup to warm the cache. */
1530
- prime(): void;
1531
- /** Number of keys currently cached (diagnostics/tests). */
1532
- get size(): number;
1533
- private ensureFresh;
1534
- /** Re-fetch every directory. De-duplicated: concurrent callers share one run. */
1535
- refresh(): Promise<void>;
1536
- private doRefresh;
1537
- private fetchDirectory;
1538
- private debug;
1539
- }
1540
-
1541
- /**
1542
- * Detection engine types.
1543
- *
1544
- * The detection engine scores a set of client-collected `Signals` against ~40
1545
- * behavioral, environmental, and fingerprint heuristics and produces a verdict.
1546
- * Ported from the FCaptcha scoring engine so behavior matches the self-hosted
1547
- * server (server.js `runVerification`).
1548
- *
1549
- * Signals originate from an untrusted client, so every field is optional and the
1550
- * detectors fall back to neutral defaults (mirroring the `?? default` pattern in
1551
- * the reference implementation).
1552
- */
1553
- /** A single triggered heuristic. */
1554
- interface Detection {
1555
- /** Scoring bucket this detection contributes to (see {@link Weights}). */
1556
- category: string;
1557
- /** Likelihood this signal indicates a bot/attack, 0..1. */
1558
- score: number;
1559
- /** Certainty of the score, 0..1, used to weight the per-category aggregate. */
1560
- confidence: number;
1561
- /** Human-readable explanation. */
1562
- reason: string;
1563
- /** Optional structured detail (e.g. keystroke-cadence metrics). */
1564
- details?: Record<string, unknown>;
1565
- }
1566
- /** Per-category aggregated scores (0..1), keyed by category name. */
1567
- type CategoryScores = Record<string, number>;
1568
- /** Final action recommendation derived from the weighted score. */
1569
- type Recommendation = 'allow' | 'challenge' | 'block';
1570
- /** Behavioral signals: mouse, touch, keyboard, and interaction timing. */
1571
- interface BehavioralSignals {
1572
- totalPoints?: number;
1573
- trajectoryLength?: number;
1574
- approachPoints?: number;
1575
- touchEvents?: number;
1576
- keyEvents?: number;
1577
- microTremorScore?: number;
1578
- approachDirectness?: number;
1579
- clickPrecision?: number;
1580
- explorationRatio?: number;
1581
- velocityVariance?: number;
1582
- overshootCorrections?: number;
1583
- interactionDuration?: number;
1584
- mouseEventRate?: number;
1585
- straightLineRatio?: number;
1586
- directionChanges?: number;
1587
- eventDeltaVariance?: number;
1588
- touchTotalPoints?: number;
1589
- touchForceMin?: number;
1590
- touchForceMax?: number;
1591
- touchForceVariance?: number;
1592
- touchForceAllOne?: boolean;
1593
- touchForceAllZero?: boolean;
1594
- touchRadiusMin?: number;
1595
- touchRadiusMax?: number;
1596
- touchRadiusVariance?: number;
1597
- touchUniqueIdentifiers?: number;
1598
- touchMultiTouchSeen?: boolean;
1599
- touchStraightLineRatio?: number;
1600
- touchMicroTremorScore?: number;
1601
- touchDirectionChanges?: number;
1602
- [key: string]: unknown;
1603
- }
1604
- interface PoWTiming {
1605
- duration?: number;
1606
- iterations?: number;
1607
- [key: string]: unknown;
1608
- }
1609
- interface TemporalSignals {
1610
- pow?: PoWTiming;
1611
- pageLoadToFirstInteraction?: number | null;
1612
- [key: string]: unknown;
1613
- }
1614
- interface EnvironmentalSignals {
1615
- webdriver?: boolean;
1616
- headlessIndicators?: {
1617
- hasOuterDimensions?: boolean;
1618
- innerEqualsOuter?: boolean;
1619
- notificationPermission?: string;
1620
- [key: string]: unknown;
1621
- };
1622
- automationFlags?: {
1623
- plugins?: number;
1624
- languages?: boolean;
1625
- chrome?: boolean;
1626
- platform?: string;
1627
- maxTouchPoints?: number;
1628
- hardwareConcurrency?: number;
1629
- [key: string]: unknown;
1630
- };
1631
- navigator?: {
1632
- platform?: string;
1633
- maxTouchPoints?: number;
1634
- [key: string]: unknown;
1635
- };
1636
- webglInfo?: {
1637
- renderer?: string;
1638
- [key: string]: unknown;
1639
- };
1640
- playwright?: {
1641
- detected?: boolean;
1642
- signals?: string[];
1643
- };
1644
- cdp?: {
1645
- detected?: boolean;
1646
- signals?: string[];
1647
- };
1648
- jsExecutionTime?: {
1649
- mathOps?: number;
1650
- [key: string]: unknown;
1651
- };
1652
- rafConsistency?: {
1653
- frameTimeVariance?: number;
1654
- [key: string]: unknown;
1655
- };
1656
- canvasHash?: {
1657
- hash?: string;
1658
- error?: unknown;
1659
- supported?: boolean;
1660
- [key: string]: unknown;
1661
- };
1662
- sensor?: {
1663
- motionEventCount?: number;
1664
- motionAccelVariance?: number;
1665
- orientationEventCount?: number;
1666
- orientationVariance?: number;
1667
- [key: string]: unknown;
1668
- };
1669
- webrtcInfo?: WebRTCInfo;
1670
- speechInfo?: SpeechInfo;
1671
- workerConsistency?: WorkerConsistencyInfo;
1672
- cssMediaQueries?: CSSMediaQueriesInfo;
1673
- fontsInfo?: FontsInfo;
1674
- permissionsInfo?: PermissionsInfo;
1675
- domRectFingerprint?: DOMRectInfo;
1676
- audioInfo?: AudioContextInfo;
1677
- lieDetection?: LieDetectionInfo;
1678
- [key: string]: unknown;
1679
- }
1680
- interface WebRTCInfo {
1681
- supported?: boolean;
1682
- mediaDevices?: {
1683
- supported?: boolean;
1684
- audioInputs?: number;
1685
- audioOutputs?: number;
1686
- videoInputs?: number;
1687
- totalDevices?: number;
1688
- };
1689
- hasLocalIP?: boolean;
1690
- localIPError?: unknown;
1691
- [key: string]: unknown;
1692
- }
1693
- interface SpeechInfo {
1694
- supported?: boolean;
1695
- totalVoices?: number;
1696
- localVoices?: number;
1697
- [key: string]: unknown;
1698
- }
1699
- interface WorkerConsistencyInfo {
1700
- supported?: boolean;
1701
- consistent?: boolean;
1702
- mismatches?: string[];
1703
- mismatchCount?: number;
1704
- [key: string]: unknown;
1705
- }
1706
- interface CSSMediaQueriesInfo {
1707
- supported?: boolean;
1708
- pointer?: string;
1709
- hover?: boolean;
1710
- [key: string]: unknown;
1711
- }
1712
- interface FontsInfo {
1713
- supported?: boolean;
1714
- count?: number;
1715
- hasSegoeUI?: boolean;
1716
- hasSFPro?: boolean;
1717
- hasDejaVuSans?: boolean;
1718
- [key: string]: unknown;
1719
- }
1720
- interface PermissionsInfo {
1721
- supported?: boolean;
1722
- [key: string]: unknown;
1723
- }
1724
- interface DOMRectInfo {
1725
- supported?: boolean;
1726
- rectAWidth?: number;
1727
- rectBWidth?: number;
1728
- rangeWidth?: number;
1729
- [key: string]: unknown;
1730
- }
1731
- /** AudioContext fingerprint. A real audio stack exposes `baseLatency` and a
1732
- * conventional sample rate; headless/mocked stacks omit or fake these. */
1733
- interface AudioContextInfo {
1734
- supported?: boolean;
1735
- sampleRate?: number;
1736
- state?: string;
1737
- baseLatency?: number | null;
1738
- [key: string]: unknown;
1739
- }
1740
- /** Native-function integrity check. `patched` lists native functions whose
1741
- * `toString()` no longer reports `[native code]` (or whose prototype was
1742
- * tampered with) — the signature of stealth automation hiding itself. A real
1743
- * browser never patches its own natives. */
1744
- interface LieDetectionInfo {
1745
- supported?: boolean;
1746
- patched?: string[];
1747
- patchedCount?: number;
1748
- [key: string]: unknown;
1749
- }
1750
- /** Per-field keystroke statistics for one textarea. */
1751
- interface TextareaKeyboardStats {
1752
- keyCount?: number;
1753
- pasteCount?: number;
1754
- avgKeyInterval?: number;
1755
- keyIntervalVariance?: number;
1756
- keydownUpRatio?: number;
1757
- noKeyboardEvents?: boolean;
1758
- contentLength?: number;
1759
- intervals?: number[];
1760
- dwellTimes?: number[];
1761
- rollovers?: number;
1762
- [key: string]: unknown;
1763
- }
1764
- interface FormSubmitInfo {
1765
- method?: string;
1766
- timeSincePageLoad?: number | null;
1767
- eventsBeforeSubmit?: number;
1768
- hadTriggerEvent?: boolean;
1769
- [key: string]: unknown;
1770
- }
1771
- interface FormAnalysisSignals {
1772
- pageLoadToFirstInteraction?: number | null;
1773
- submit?: FormSubmitInfo;
1774
- textareaKeyboard?: Record<string, TextareaKeyboardStats>;
1775
- [key: string]: unknown;
1776
- }
1777
- /** The full set of signals the client widget reports. */
1778
- interface Signals {
1779
- behavioral?: BehavioralSignals;
1780
- temporal?: TemporalSignals;
1781
- environmental?: EnvironmentalSignals;
1782
- formAnalysis?: FormAnalysisSignals;
1783
- meta?: {
1784
- challengeNonce?: string;
1785
- [key: string]: unknown;
1786
- };
1787
- [key: string]: unknown;
1788
- }
1789
- /**
1790
- * Outcome of proof-of-work verification, supplied by the caller (the PoW
1791
- * subsystem lands in Phase 2). When omitted and `requirePoW` is enabled the
1792
- * engine emits a hard-fail "No PoW solution provided" detection, matching the
1793
- * reference server.
1794
- */
1795
- interface PoWOutcome {
1796
- /** Whether a PoW solution was submitted at all. */
1797
- provided: boolean;
1798
- /** Whether the submitted solution verified. */
1799
- valid?: boolean;
1800
- /** Failure reason when `valid` is false. */
1801
- reason?: string;
1802
- /** Server-measured solve time in ms (un-spoofable). */
1803
- serverElapsed?: number;
1804
- /** Nonce bound to the verified challenge. */
1805
- nonce?: string;
1806
- }
1807
- /** Per-request context for scoring. */
1808
- interface DetectionContext {
1809
- ip: string;
1810
- siteKey: string;
1811
- userAgent: string;
1812
- /** Lower-cased request headers. */
1813
- headers?: Record<string, string>;
1814
- /** Client-supplied JA3 hash (spoofable). */
1815
- ja3Hash?: string | null;
1816
- /** Trusted reverse-proxy header names carrying a JA4 fingerprint. */
1817
- trustedJA4Headers?: string[];
1818
- /** Proof-of-work verification outcome (supplied by the PoW subsystem). */
1819
- pow?: PoWOutcome;
1820
- /**
1821
- * Additional detections to fold into scoring, produced by an outer
1822
- * orchestrator (e.g. the signals-tampering check in the Captcha service).
1823
- */
1824
- extraDetections?: Detection[];
1825
- }
1826
- /** Final verdict returned by {@link DetectionEngine.score}. */
1827
- interface Verdict {
1828
- /** True when the weighted score is below the success threshold (< 0.5). */
1829
- success: boolean;
1830
- /** Weighted final score, 0..1. */
1831
- score: number;
1832
- /** Recommended action. */
1833
- recommendation: Recommendation;
1834
- /** Per-category aggregated scores. */
1835
- categoryScores: CategoryScores;
1836
- /** Every triggered detection. */
1837
- detections: Detection[];
1838
- /** Unix seconds at evaluation time. */
1839
- timestamp: number;
1840
- }
1277
+ * tripwire({ paths: [hp.path] }), // + built-in scanner-bait paths
1278
+ * ],
1279
+ * });
1280
+ * // inject hp.linkHtml into your pages
1281
+ * ```
1282
+ */
1283
+ declare function tripwire(config?: TripwireConfig): Rule;
1284
+ /**
1285
+ * Factory function to create a bot-category rule.
1286
+ *
1287
+ * Acts on agents that identify themselves in the User-Agent, matched against the
1288
+ * registry generated from the same table the scoring pipeline uses — so
1289
+ * `'training_crawler'` here means what `ai_scraper_category` means in your
1290
+ * dashboard.
1291
+ *
1292
+ * @example
1293
+ * ```typescript
1294
+ * import { WebDecoy, bots } from '@webdecoy/node';
1295
+ *
1296
+ * const sdk = new WebDecoy({
1297
+ * rules: [
1298
+ * // Keep AI models out of your content, keep your search ranking.
1299
+ * bots({ categories: ['training_crawler'] }),
1300
+ *
1301
+ * // Or everything AI, minus the one you want referral traffic from.
1302
+ * bots({ ai: true, allow: ['perplexitybot'] }),
1303
+ *
1304
+ * // Or a specific operator.
1305
+ * bots({ agents: ['gptbot', 'ClaudeBot'], action: 'THROTTLE' }),
1306
+ * ],
1307
+ * });
1308
+ * ```
1309
+ *
1310
+ * Only catches agents that declare themselves — anything spoofing a browser
1311
+ * passes through, by design. Pair with {@link tripwire} for agents that lie.
1312
+ */
1313
+ declare function bots(config?: BotRuleConfig): Rule;
1841
1314
 
1842
1315
  /**
1843
- * In-memory stores backing the stateful detectors (fingerprint correlation and
1844
- * rate abuse). Ported from FCaptcha index.js.
1316
+ * The parts of a middleware that are the same in every framework.
1845
1317
  *
1846
- * These are defined behind interfaces so Phase 2 can swap in a shared/Redis
1847
- * backend for serverless and multi-instance deployments.
1318
+ * WHY THIS EXISTS
1319
+ *
1320
+ * Express, Fastify, Next.js and the fetch guard each grew their own copy of the
1321
+ * same decision tree: skip-path matching, monitor-versus-enforce, honeytoken
1322
+ * arming, the 429 payload, the 403 payload. Four copies of one set of rules.
1323
+ *
1324
+ * That is not a tidiness complaint. The leftmost-`X-Forwarded-For` bug survived
1325
+ * in two adapters after the same class of bug had already been fixed elsewhere,
1326
+ * precisely because there was no one place to fix. Every copy is a place the
1327
+ * next correction can fail to land, and each one reads perfectly sensibly on its
1328
+ * own — which is why review does not catch it.
1329
+ *
1330
+ * WHAT STAYS IN THE ADAPTERS
1331
+ *
1332
+ * Everything that touches the framework: reading metadata off its request
1333
+ * object, writing its response, and injecting the honeytoken link into whatever
1334
+ * that framework calls a body. Response mechanics differ genuinely — Express
1335
+ * intercepts `res.write`/`res.end`, Fastify uses an `onSend` hook, a fetch
1336
+ * handler rebuilds a `Response` — and the detail in each is hard-won. This
1337
+ * module holds the decisions, not the I/O.
1848
1338
  */
1849
- /** Tracks fingerprint ↔ IP relationships to spot distributed attacks. */
1850
- interface FingerprintStore {
1851
- record(fp: string, ip: string, siteKey: string): void;
1852
- /** Number of distinct fingerprints seen from `ip`. */
1853
- getIpFpCount(ip: string): number;
1854
- /** Number of distinct IPs that produced fingerprint `fp` for `siteKey`. */
1855
- getFpIpCount(fp: string, siteKey: string): number;
1856
- }
1857
- /** Sliding-window request counter. */
1858
- interface RateLimiter {
1859
- /** Returns `[exceeded, count]` for the window, recording this hit. */
1860
- check(key: string, windowSeconds?: number, maxRequests?: number): [boolean, number];
1861
- }
1862
- declare class InMemoryFingerprintStore implements FingerprintStore {
1863
- private fingerprints;
1864
- private ipFingerprints;
1865
- record(fp: string, ip: string, siteKey: string): void;
1866
- getIpFpCount(ip: string): number;
1867
- getFpIpCount(fp: string, siteKey: string): number;
1339
+
1340
+ /** Whether a request path is exempt from protection. */
1341
+ declare function shouldSkipPath(path: string, patterns: readonly (string | RegExp)[] | undefined): boolean;
1342
+ /** A framework-agnostic description of the response a blocked request gets. */
1343
+ interface BlockResponse {
1344
+ status: number;
1345
+ headers: Record<string, string>;
1346
+ body: Record<string, unknown>;
1868
1347
  }
1869
- declare class InMemoryRateLimiter implements RateLimiter {
1870
- private requests;
1871
- check(key: string, windowSeconds?: number, maxRequests?: number): [boolean, number];
1348
+ /**
1349
+ * What to answer a request the rules refused.
1350
+ *
1351
+ * Returns null when the decision was not a rule refusal — a server-score block
1352
+ * has no rule to name, and each adapter's `onBlocked` handles that case with its
1353
+ * own default.
1354
+ */
1355
+ declare function ruleBlockResponse(decision: ProtectResult): BlockResponse | null;
1356
+ interface HoneytokenArmingOptions {
1357
+ /** The site honeytoken is derived from this. No key, no token. */
1358
+ apiKey?: string;
1359
+ /** Defaults to on when an apiKey is present. */
1360
+ enabled?: boolean;
1361
+ /** Reported when derivation fails, so a silent absence is at least loggable. */
1362
+ onError?: (error: unknown) => void;
1872
1363
  }
1364
+ /**
1365
+ * Derive the site honeytoken and arm the tripwire it points at.
1366
+ *
1367
+ * Returns a getter rather than a promise: derivation is async (WebCrypto HMAC,
1368
+ * so this still runs on edge runtimes) and requests served before it settles
1369
+ * simply carry no link. That is a few milliseconds at boot against the
1370
+ * alternative of blocking startup on crypto.
1371
+ *
1372
+ * The token is derived from the API key so every replica computes the same path
1373
+ * without coordinating. A random per-process token would advertise a link whose
1374
+ * tripwire only one replica had armed — bait with no trap behind it.
1375
+ */
1376
+ declare function armSiteHoneytoken(sdk: WebDecoy, options: HoneytokenArmingOptions): () => SiteHoneytoken | null;
1377
+ /**
1378
+ * Derive and arm, awaited.
1379
+ *
1380
+ * For a framework whose registration is already an async boot phase — Fastify's
1381
+ * plugin hook — where waiting costs nothing and removes the window in which
1382
+ * early requests are served without the link. Same logic as
1383
+ * {@link armSiteHoneytoken}; only the timing differs, which is why it is a
1384
+ * second entry point rather than a second implementation.
1385
+ */
1386
+ declare function deriveAndArm(sdk: WebDecoy, options: HoneytokenArmingOptions): Promise<SiteHoneytoken | null>;
1873
1387
 
1874
1388
  /**
1875
- * Detection engine.
1389
+ * One adapter, for every runtime that speaks `Request` and `Response`.
1876
1390
  *
1877
- * Runs the full FCaptcha detector suite in-process and produces a {@link Verdict}.
1878
- * Mirrors the reference server's `runVerification` orchestration. The actual
1879
- * proof-of-work crypto and token issuance land in Phase 2 — for now the caller
1880
- * supplies a {@link PoWOutcome} and the engine emits the matching detections.
1391
+ * WHY THIS EXISTS
1392
+ *
1393
+ * Express, Fastify and Next.js each grew their own copy of the same middleware:
1394
+ * skip-path matching, monitor-versus-enforce, honeytoken arming, the 429 with a
1395
+ * `Retry-After`, fail-open error handling. Three copies of a decision tree is
1396
+ * three places for the branch that matters to be subtly different — and it
1397
+ * already had been, which is how the leftmost-`X-Forwarded-For` bug survived in
1398
+ * two adapters after the WordPress plugin fixed it.
1399
+ *
1400
+ * It is also the answer to "which framework do you support?". Hono, Bun, Deno,
1401
+ * Astro, Nitro, SvelteKit and Remix all hand you a WHATWG `Request` and want a
1402
+ * `Response` back. Written once here, each of those is a translation layer thin
1403
+ * enough not to need a package — see the README recipe — and `@webdecoy/hono` is
1404
+ * the one that does, because Hono has a middleware contract worth fitting.
1405
+ *
1406
+ * No `node:` imports: this is the code path that has to run on Workers.
1881
1407
  */
1882
1408
 
1883
- interface DetectionEngineOptions {
1884
- /** Override the per-category weights (defaults to {@link DEFAULT_WEIGHTS}). */
1885
- weights?: Record<string, number>;
1409
+ interface FetchGuardOptions extends WebDecoyConfig, ProtectOptions {
1886
1410
  /**
1887
- * When true (default), a request with no PoW outcome emits a hard-fail "No PoW
1888
- * solution provided" detection — matching the reference server. Set false to
1889
- * score raw signals without requiring proof-of-work.
1411
+ * Whether a blocking verdict actually blocks. Defaults to `'monitor'`.
1412
+ *
1413
+ * Nobody adopts a defence by having it break their site on the first install.
1414
+ * Watch what it would have done, then switch.
1890
1415
  */
1891
- requirePoW?: boolean;
1892
- /** Fingerprint-correlation store (defaults to an in-memory store). */
1893
- fingerprintStore?: FingerprintStore;
1894
- /** Rate limiter for rate-abuse detection (defaults to in-memory). */
1895
- rateLimiter?: RateLimiter;
1416
+ mode?: 'monitor' | 'enforce';
1417
+ /** Paths to skip entirely — health checks, static assets. */
1418
+ skipPaths?: (string | RegExp)[];
1419
+ /**
1420
+ * How much of the `X-Forwarded-For` chain to believe. Defaults to `1` trusted
1421
+ * hop: a fetch handler has no socket to fall back on, so there is no
1422
+ * believe-nothing default available. See `resolveClientIp`.
1423
+ */
1424
+ trustProxy?: TrustedProxies;
1425
+ /** Override IP resolution entirely. */
1426
+ getIP?: (request: Request) => string;
1427
+ /**
1428
+ * Inject a hidden honeytoken link into HTML responses, and arm the tripwire it
1429
+ * points at. Defaults to on when an `apiKey` is present.
1430
+ */
1431
+ honeytoken?: boolean;
1432
+ /** Build the blocking response. Defaults to 403, or 429 for a throttle. */
1433
+ onBlocked?: (request: Request, decision: Decision) => Response | Promise<Response>;
1896
1434
  }
1897
- declare class DetectionEngine {
1898
- private readonly weights;
1899
- private readonly requirePoW;
1900
- private readonly fingerprintStore;
1901
- private readonly rateLimiter;
1902
- constructor(options?: DetectionEngineOptions);
1903
- /** Score `signals` for the given request context and return a verdict. */
1904
- score(signals: Signals, context: DetectionContext): Verdict;
1435
+ interface GuardOutcome {
1436
+ /** What the SDK concluded. Always present, in both modes. */
1437
+ decision: Decision;
1438
+ /**
1439
+ * The response to return instead of calling the handler, or undefined to
1440
+ * carry on. Undefined in monitor mode even when the decision is a denial.
1441
+ */
1442
+ response?: Response;
1443
+ }
1444
+ interface FetchGuard {
1445
+ /** Evaluate one request. */
1446
+ check(request: Request, peer?: string): Promise<GuardOutcome>;
1447
+ /**
1448
+ * Rewrite an HTML response to carry the honeytoken link. Returns the response
1449
+ * unchanged when there is no token yet, or the body is not injectable HTML.
1450
+ */
1451
+ decorate(response: Response): Promise<Response>;
1452
+ /** Whether this path is skipped. */
1453
+ skips(pathname: string): boolean;
1454
+ /** The underlying SDK, for `detectBot()` and friends. */
1455
+ sdk: WebDecoy;
1905
1456
  }
1906
-
1907
- /** Score aggregation: per-category confidence-weighted means → weighted total. */
1908
-
1909
1457
  /**
1910
- * Aggregate detections into per-category scores. Each category's score is the
1911
- * confidence-weighted mean of its detections' scores, capped at 1.0. Categories
1912
- * present in `weights` but with no detections are filled with 0.
1458
+ * A guard over WHATWG `Request`/`Response`.
1459
+ *
1460
+ * ```ts
1461
+ * const guard = createFetchGuard({ rules: [tripwire()] });
1462
+ *
1463
+ * export default {
1464
+ * async fetch(request) {
1465
+ * const { response } = await guard.check(request);
1466
+ * if (response) return response;
1467
+ * return guard.decorate(await handle(request));
1468
+ * },
1469
+ * };
1470
+ * ```
1913
1471
  */
1914
- declare function calculateCategoryScores(detections: Detection[], weights: Record<string, number>): CategoryScores;
1915
- /** Combine category scores into the final weighted score (capped at 1.0). */
1916
- declare function calculateFinalScore(categoryScores: CategoryScores, weights: Record<string, number>): number;
1917
- /** Map a final score to an action recommendation. */
1918
- declare function recommend(finalScore: number): Recommendation;
1472
+ declare function createFetchGuard(options?: FetchGuardOptions): FetchGuard;
1919
1473
 
1920
1474
  /**
1921
- * Category weights and automation UA patterns.
1475
+ * AgentVerifier — the public entry point for local Web Bot Auth verification.
1922
1476
  *
1923
- * Values match the FCaptcha standalone server (server.js), which is the most
1924
- * complete variant of the engine and the one the reference test suite exercises.
1477
+ * Wraps the cached directory client and the signature core into a single
1478
+ * `verify(request)` call returning an {@link AgentVerdict}. Designed for the
1479
+ * hot path of edge/Node middleware: warm verification is a header parse, one
1480
+ * map lookup, and one WebCrypto verify — no network, well under the 5ms p95
1481
+ * budget in the acceptance criteria.
1925
1482
  */
1483
+
1484
+ declare class AgentVerifier {
1485
+ private readonly cache;
1486
+ private readonly toleranceSec;
1487
+ constructor(options?: AgentVerifierOptions);
1488
+ /** Pre-fetch trusted directories so the first request verifies warm. */
1489
+ warmup(): void;
1490
+ /** Verify a request's Web Bot Auth signature (if any) locally. */
1491
+ verify(request: AgentRequestInput): Promise<AgentVerdict>;
1492
+ /** Cached-key count (diagnostics/tests). */
1493
+ get cachedKeyCount(): number;
1494
+ }
1495
+ /** Convenience factory mirroring the SDK's other `create*` helpers. */
1496
+ declare function createAgentVerifier(options?: AgentVerifierOptions): AgentVerifier;
1497
+
1926
1498
  /**
1927
- * Default per-category weights used to compute the final score.
1499
+ * RFC 9421 HTTP Message Signatures — the Web Bot Auth verification core.
1928
1500
  *
1929
- * `stealth` carries deliberate anti-detection tampering (native functions
1930
- * patched to hide automation). This is the least-ambiguous evidence of a bot —
1931
- * a genuine browser never patches its own natives — so it is weighted highest.
1932
- * Because weights are a simple weighted sum (not required to total 1.0), and
1933
- * `stealth` is 0 for any clean browser, this raises stealth-bot scores without
1934
- * affecting legitimate traffic.
1501
+ * Verifies signatures tagged `web-bot-auth`: parse `Signature-Input` /
1502
+ * `Signature`, rebuild the signature base for each covered-component set, and
1503
+ * check the raw signature with WebCrypto against a key resolved by its JWK
1504
+ * thumbprint keyid. Adapted from the WebDecoy edge validator
1505
+ * (`edge/clearance-worker/src/web-bot-auth.ts`), generalized to resolve keys
1506
+ * from a directory cache instead of a pushed key list.
1507
+ *
1508
+ * Zero dependencies, Edge-runtime safe: only `crypto.subtle`, `TextEncoder`,
1509
+ * `atob`, and `URL` are used.
1935
1510
  */
1936
- declare const DEFAULT_WEIGHTS: Record<string, number>;
1511
+ /** A verification key resolved from a trusted directory, ready for WebCrypto. */
1512
+ interface VerificationKey {
1513
+ cryptoKey: CryptoKey;
1514
+ /** WebCrypto verify params (e.g. `{ name: 'Ed25519' }`). */
1515
+ verifyParams: AlgorithmIdentifier | RsaPssParams;
1516
+ /** Human-readable algorithm label, e.g. "ed25519". */
1517
+ algorithm: string;
1518
+ /** Display name of the owning agent. */
1519
+ name: string;
1520
+ /** Category of the owning agent. */
1521
+ category: string;
1522
+ /** Key validity bounds in Unix seconds, if the directory published them. */
1523
+ nbf?: number;
1524
+ exp?: number;
1525
+ }
1526
+ /** Resolves a JWK-thumbprint keyid to a verification key, or undefined if unknown. */
1527
+ type KeyResolver = (keyId: string) => Promise<VerificationKey | undefined>;
1937
1528
 
1938
- /** True when `ip` falls inside a known datacenter CIDR block (IPv4 only). */
1939
- declare function isDatacenterIP(ip: string): boolean;
1529
+ /**
1530
+ * Cached Web Bot Auth directory client.
1531
+ *
1532
+ * Fetches the JWK sets of a **curated** set of trusted agent directories,
1533
+ * imports their keys into WebCrypto, and indexes them by JWK-thumbprint keyid
1534
+ * so signatures resolve in O(1) with zero network on the warm path.
1535
+ *
1536
+ * Security posture — the reason this is curated-only:
1537
+ * a request's own `Signature-Agent` header is **never** used to choose a fetch
1538
+ * target, so an attacker cannot make the middleware fetch an arbitrary URL
1539
+ * (no SSRF). Only the origins in {@link AgentVerifierOptions.directories} are
1540
+ * ever contacted. This mirrors the backend curation
1541
+ * (`backend/internal/services/signed_agents.go`).
1542
+ *
1543
+ * Freshness — stale-while-revalidate: once populated, an expired cache keeps
1544
+ * serving its keys while a background refresh runs, so verification latency is
1545
+ * never coupled to a directory fetch. A cold cache (never populated) blocks
1546
+ * once to fetch, then backs off briefly if every directory is unreachable so a
1547
+ * degraded network can't be hammered per request.
1548
+ */
1940
1549
 
1941
1550
  /**
1942
- * User-Agent parsing and bot-pattern matching. Ported from FCaptcha detection.js.
1551
+ * The default curated allowlist. These are the agents that sign production
1552
+ * traffic today; kept in lock-step with the backend's curated list.
1943
1553
  */
1944
- interface UserAgentInfo {
1945
- browser: string | null;
1946
- os: string | null;
1947
- isMobile: boolean;
1948
- isBot: boolean;
1949
- botName: string | null;
1554
+ declare const DEFAULT_SIGNED_AGENT_DIRECTORIES: SignedAgentDirectory[];
1555
+ interface DirectoryCacheOptions {
1556
+ directories: SignedAgentDirectory[];
1557
+ cacheTtlMs: number;
1558
+ fetchTimeoutMs: number;
1559
+ debug: boolean;
1560
+ fetchImpl: typeof fetch;
1561
+ }
1562
+ declare class DirectoryCache {
1563
+ private readonly opts;
1564
+ private keys;
1565
+ private refreshedAt;
1566
+ private nextColdRetryAt;
1567
+ private inflight;
1568
+ constructor(opts: DirectoryCacheOptions);
1569
+ /** Resolve a keyid to a verification key, fetching/refreshing as needed. */
1570
+ resolveKey: KeyResolver;
1571
+ /** Kick off a fetch without blocking — call at startup to warm the cache. */
1572
+ prime(): void;
1573
+ /** Number of keys currently cached (diagnostics/tests). */
1574
+ get size(): number;
1575
+ private ensureFresh;
1576
+ /** Re-fetch every directory. De-duplicated: concurrent callers share one run. */
1577
+ refresh(): Promise<void>;
1578
+ private doRefresh;
1579
+ private fetchDirectory;
1580
+ private debug;
1950
1581
  }
1951
- /** True when the UA looks like a mobile device. */
1952
- declare function isMobileUA(userAgent: string): boolean;
1953
- /** Extract browser/OS/bot info from a User-Agent string. */
1954
- declare function parseUserAgent(ua: string): UserAgentInfo;
1955
1582
 
1956
1583
  /** Types for the self-hosted captcha service (PoW + scoring + tokens). */
1957
1584
 
@@ -2204,6 +1831,12 @@ interface CaptchaHttpResponse {
2204
1831
  body: unknown;
2205
1832
  }
2206
1833
  interface CaptchaEndpointsOptions extends CaptchaOptions {
1834
+ /**
1835
+ * Where `/score` records its verdict, for `clientSignals()` to read on
1836
+ * subsequent requests. Omit and the score is returned to the browser and
1837
+ * forgotten, which is what happened before this existed.
1838
+ */
1839
+ signalStore?: ClientSignalStore;
2207
1840
  /** Base path the routes are mounted under (default `/__webdecoy`). */
2208
1841
  basePath?: string;
2209
1842
  }
@@ -2219,4 +1852,4 @@ declare function createCaptchaEndpoints(options?: CaptchaEndpointsOptions): {
2219
1852
  };
2220
1853
  type CaptchaEndpoints = ReturnType<typeof createCaptchaEndpoints>;
2221
1854
 
2222
- export { type AgentCategory, type AgentRequestInput, type AgentStatus, type AgentVerdict, AgentVerifier, type AgentVerifierOptions, BOT_CATEGORIES, BOT_REGISTRY, type BehavioralSignals, type BotAgent, type BotCategory, BotRule, type BotRuleConfig, type BotVerdict, Captcha, type CaptchaEndpoints, type CaptchaEndpointsOptions, type CaptchaHttpResponse, type CaptchaOptions, type CaptchaRequest, type CategoryScores, type ChallengeData, type ChallengeStore, DEFAULT_SIGNED_AGENT_DIRECTORIES, DEFAULT_TRIPWIRE_PATHS, DEFAULT_WEIGHTS, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, DirectoryCache, EDGE_CLASS_HEADER, EDGE_CLEARANCE_HEADER, type EdgeClass, type EdgeVerdict, type EnvironmentalSignals, type FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, HONEYTOKEN_BASE_PATH, type HeaderSource, type Honeytoken, type HoneytokenLinkProps, type HoneytokenOptions, type IPEnrichmentData, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, type LocalAnalysis, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, type ProtectOptions, type ProtectResult, type RateLimitConfig, RateLimitRule, type RateLimiter, type Recommendation, type RequestMetadata, type ResolveClientIpOptions, type Rule, type RuleContext, RuleEngine, type RuleEngineResult, type RuleResult, type SDKDetectionRequest, type SDKDetectionResponse, type ScoreResult, type Signals, type SignedAgentDirectory, type SiteHoneytoken, type SiteHoneytokenOptions, type StoredChallenge, TEST_TRIGGER_UA_PREFIX, TEST_TRIGGER_USER_AGENT, type TLSInfo, type TemporalSignals, type TextareaKeyboardStats, TokenManager, type TokenManagerOptions, type TokenStore, type TokenVerification, type TripwireConfig, TripwireRule, type TrustedProxies, type Verdict, type VerifyInput, type VerifyResult, type ViolationEvent, type WebBotAuthConfig, WebBotAuthRule, WebDecoy, type WebDecoyConfig, bots, calculateCategoryScores, calculateFinalScore, classifyUserAgent, createAgentVerifier, createCaptchaEndpoints, filter, honeytoken, injectHoneytokenLink, ipInCidr, isDatacenterIP, isInjectableHtml, isMobileUA, isTestTriggerUserAgent, matchUserAgent, normalizeIp, parseUserAgent, rateLimit, readEdgeVerdict, recommend, resolveClientIp, resolveSecret, siteHoneytoken, tripwire, webBotAuth };
1855
+ export { ATTACK_SIGNATURE_IDS, AgentCategory, AgentRequestInput, AgentVerdict, AgentVerifier, AgentVerifierOptions, type AttackSignatureConfig, AttackSignatureRule, type BehavioralSignals, type BlockResponse, BotAgent, BotCategory, BotPolicy, type BotPolicyOptions, BotRule, BotRuleConfig, CLIENT_SESSION_COOKIE, CLIENT_SESSION_HEADER, Captcha, type CaptchaEndpoints, type CaptchaEndpointsOptions, type CaptchaHttpResponse, type CaptchaOptions, type CaptchaRequest, type CategoryScores, type ChallengeData, type ChallengeStore, type ClientSignalConfig, ClientSignalRule, type ClientSignalStore, type ClientVerdict, DEFAULT_SIGNED_AGENT_DIRECTORIES, DEFAULT_TRIPWIRE_PATHS, DEFAULT_WEIGHTS, Decision, type Detection, type DetectionContext, DetectionEngine, type DetectionEngineOptions, DirectoryCache, type EnvironmentalSignals, type FetchGuard, type FetchGuardOptions, FilterConfig, FilterRule, type FingerprintStore, type FormAnalysisSignals, type GuardOutcome, HONEYTOKEN_BASE_PATH, type HeaderSource, type Honeytoken, type HoneytokenArmingOptions, type HoneytokenLinkProps, type HoneytokenOptions, InMemoryChallengeStore, InMemoryFingerprintStore, InMemoryRateLimiter, InMemoryTokenStore, MemoryClientSignalStore, type MemoryClientSignalStoreOptions, PoWManager, type PoWManagerOptions, type PoWOutcome, type PoWSolution, type PoWVerification, ProtectOptions, ProtectResult, RateLimitConfig, RateLimitConsume, RateLimitOutcome, RateLimitRule, RateLimitStore, type RateLimiter, type Recommendation, type ResolveClientIpOptions, type RobotsTxtOptions, Rule, RuleContext, RuleEngine, RuleEngineResult, RuleResult, type ScoreResult, type Signals, SignedAgentDirectory, type SiteHoneytoken, type SiteHoneytokenOptions, type StoredChallenge, TEST_TRIGGER_UA_PREFIX, TEST_TRIGGER_USER_AGENT, type TemporalSignals, type TextareaKeyboardStats, TokenManager, type TokenManagerOptions, type TokenStore, type TokenVerification, TripwireConfig, TripwireRule, type TrustedProxies, UpstashRateLimitStore, type UpstashStoreOptions, type Verdict, type VerifyInput, type VerifyResult, type WebBotAuthConfig, WebBotAuthRule, WebDecoy, WebDecoyConfig, armSiteHoneytoken, attackSignatures, botPolicy, bots, calculateCategoryScores, calculateFinalScore, clientSignals, createAgentVerifier, createCaptchaEndpoints, createFetchGuard, deriveAndArm, filter, honeytoken, injectHoneytokenLink, ipInCidr, isDatacenterIP, isInjectableHtml, isMobileUA, isTestTriggerUserAgent, normalizeIp, parseUserAgent, rateLimit, readClientSession, recommend, resolveClientIp, resolveSecret, ruleBlockResponse, shouldSkipPath, siteHoneytoken, tripwire, upstashRateLimitStore, webBotAuth };