@webdecoy/node 0.12.0 → 0.13.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.
@@ -0,0 +1,1347 @@
1
+ /**
2
+ * Where rate-limit counters live.
3
+ *
4
+ * WHY THIS EXISTS
5
+ *
6
+ * `RateLimitRule` hard-constructed an `InMemoryRateLimiter` — a `Map`, with no
7
+ * seam to replace it. On any deployment with more than one process the limit was
8
+ * effectively `max × instances`, and on Vercel or Lambda it also reset on every
9
+ * cold start. A `rateLimit({ max: 100, window: 60 })` across eight replicas is a
10
+ * 800/min limit that an autoscaler can raise for you.
11
+ *
12
+ * That was inconsistent with the rest of the SDK: the detection stores and the
13
+ * captcha's challenge and token stores were already behind swappable interfaces
14
+ * with in-memory defaults. The one piece of state that actually has to be shared
15
+ * was the only one that could not be.
16
+ *
17
+ * SYNC AND ASYNC
18
+ *
19
+ * `Rule.evaluate()` is synchronous, and making it async would turn every rule
20
+ * evaluation into a promise for the sake of the one rule that might need it. So
21
+ * a store declares which it is:
22
+ *
23
+ * - A **sync** store is consumed inline during `evaluate()`. This is the default
24
+ * in-memory path, unchanged and allocation-free.
25
+ * - An **async** store is consumed in `prepare()`, which `protect()` awaits
26
+ * before evaluation — the same pre-fetch the SDK already does for IP
27
+ * enrichment and Web Bot Auth verdicts.
28
+ *
29
+ * A rule whose async store was never prepared reports `NOT_RUN` rather than
30
+ * silently allowing. A rate limiter that quietly stops limiting is worse than
31
+ * one that says it is not running.
32
+ */
33
+ /** What one consumption of the limit produced. */
34
+ interface RateLimitOutcome {
35
+ /** Whether this request is within the limit. */
36
+ allowed: boolean;
37
+ /** Requests counted in the current window, including this one. */
38
+ current: number;
39
+ /** When the window resets, as a Unix ms timestamp. */
40
+ resetAt: number;
41
+ }
42
+ interface RateLimitConsume {
43
+ key: string;
44
+ max: number;
45
+ windowMs: number;
46
+ algorithm: 'fixed' | 'sliding';
47
+ }
48
+ /**
49
+ * A counter store.
50
+ *
51
+ * `sync: true` means `consume()` returns an outcome directly and may be called
52
+ * during rule evaluation. `sync: false` means it returns a promise and will be
53
+ * consumed during the async pre-fetch instead.
54
+ */
55
+ interface RateLimitStore {
56
+ readonly sync: boolean;
57
+ consume(input: RateLimitConsume): RateLimitOutcome | Promise<RateLimitOutcome>;
58
+ destroy?(): void | Promise<void>;
59
+ }
60
+ /** A store whose `consume` is callable inline. */
61
+ interface SyncRateLimitStore extends RateLimitStore {
62
+ readonly sync: true;
63
+ consume(input: RateLimitConsume): RateLimitOutcome;
64
+ }
65
+ /**
66
+ * The default: counters in this process's memory.
67
+ *
68
+ * Correct for a single process, and the reason the SDK works with no
69
+ * infrastructure at all. Wrong the moment you run two — see
70
+ * {@link upstashRateLimitStore} for the shared alternative.
71
+ */
72
+ declare class MemoryRateLimitStore implements SyncRateLimitStore {
73
+ readonly sync: true;
74
+ private limiter;
75
+ consume({ key, max, windowMs, algorithm }: RateLimitConsume): RateLimitOutcome;
76
+ destroy(): void;
77
+ }
78
+
79
+ /**
80
+ * Web Bot Auth verification — public types.
81
+ *
82
+ * A local verifier for the WebDecoy Web Bot Auth profile (RFC 9421 HTTP
83
+ * Message Signatures, tag "web-bot-auth"). It answers one question about an
84
+ * inbound request: is it a *cryptographically verified* AI agent, an
85
+ * *impersonator* forging a known agent's identity, an unverifiable *claim*,
86
+ * or plain traffic carrying no agent signature at all?
87
+ *
88
+ * The verdict taxonomy mirrors the server-side verifier in the ingest service
89
+ * so the SDK, the edge validator, and the backend all speak
90
+ * the same language.
91
+ */
92
+ /** The four possible outcomes of Web Bot Auth verification. */
93
+ type AgentStatus =
94
+ /** No Web Bot Auth signature on the request. Ordinary traffic. */
95
+ 'none'
96
+ /** Signature verified against a curated agent's published key. Trustworthy. */
97
+ | 'verified'
98
+ /**
99
+ * A signature claiming a **known** agent's key that did **not** verify (bad
100
+ * signature, or outside its created/expires window). A forgery attempt —
101
+ * deny-able, tripwire-grade.
102
+ */
103
+ | 'impersonation'
104
+ /**
105
+ * A signature is present but cannot be verified against any curated agent
106
+ * (unknown keyid, or an unsupported / malformed signature). An unverifiable
107
+ * claim — not proof of an agent, not proof of a forgery.
108
+ */
109
+ | 'claimed';
110
+ /**
111
+ * Category an agent falls into, used for allow/deny policy. Matches the
112
+ * category taxonomy used by the edge validator and backend curation.
113
+ */
114
+ type AgentCategory = 'ai_crawlers' | 'search_engines' | 'monitoring' | string;
115
+ /** The result of verifying one request. */
116
+ interface AgentVerdict {
117
+ /** Verification outcome. */
118
+ status: AgentStatus;
119
+ /** Human display name of the matched agent (e.g. "OpenAI"). Only on `verified`. */
120
+ agentName?: string;
121
+ /** Category of the matched agent. Only on `verified`. */
122
+ category?: AgentCategory;
123
+ /** The JWK thumbprint keyid the signature claimed. Present on verified/impersonation/claimed. */
124
+ keyId?: string;
125
+ /** Signature algorithm used (e.g. "ed25519", "rsa-pss-sha512"). Only on `verified`. */
126
+ algorithm?: string;
127
+ /**
128
+ * How the verdict was reached — always `'signature'` for now (Web Bot Auth
129
+ * cryptographic verification). Kept for parity with the ingest verifier,
130
+ * which also reports `ip_rdns` / `claimed` methods it derives from other
131
+ * signals unavailable in-process.
132
+ */
133
+ method?: 'signature';
134
+ /** Short, non-sensitive reason string for non-verified outcomes (diagnostics). */
135
+ reason?: string;
136
+ }
137
+ /** A curated, trusted signing agent whose directory the SDK will fetch. */
138
+ interface SignedAgentDirectory {
139
+ /** Display name, e.g. "OpenAI". */
140
+ name: string;
141
+ /** Category for allow/deny policy. */
142
+ category: AgentCategory;
143
+ /**
144
+ * Origin (scheme + host) whose well-known HTTP Message Signatures directory
145
+ * publishes the agent's keys, e.g. `https://operator.openai.com`. The
146
+ * `/.well-known/http-message-signatures-directory` path is appended
147
+ * automatically. A full URL ending in a path is also accepted verbatim.
148
+ */
149
+ directory: string;
150
+ }
151
+ /** Options for {@link createAgentVerifier}. */
152
+ interface AgentVerifierOptions {
153
+ /**
154
+ * Trusted agent directories to verify against. Defaults to
155
+ * {@link DEFAULT_SIGNED_AGENT_DIRECTORIES}. Only origins in this list are
156
+ * ever fetched — the request's own `Signature-Agent` header is never used to
157
+ * choose a fetch target, so there is no SSRF surface.
158
+ */
159
+ directories?: SignedAgentDirectory[];
160
+ /**
161
+ * How long a fetched directory stays fresh, in milliseconds. After this the
162
+ * cached keys are still served (stale-while-revalidate) while a background
163
+ * refresh runs, so the warm path never blocks on the network.
164
+ * @default 21600000 (6 hours)
165
+ */
166
+ cacheTtlMs?: number;
167
+ /**
168
+ * Per-directory fetch timeout in milliseconds.
169
+ * @default 5000
170
+ */
171
+ fetchTimeoutMs?: number;
172
+ /**
173
+ * Clock-skew tolerance in seconds applied to a signature's created/expires
174
+ * window.
175
+ * @default 300 (5 minutes)
176
+ */
177
+ toleranceSec?: number;
178
+ /** Emit debug logging to the console. @default false */
179
+ debug?: boolean;
180
+ /**
181
+ * Injectable fetch, primarily for tests. Defaults to the global `fetch`.
182
+ */
183
+ fetchImpl?: typeof fetch;
184
+ }
185
+ /**
186
+ * A request to verify. Either a WHATWG {@link Request} (the natural shape on
187
+ * Vercel Edge / Next.js middleware and Cloudflare Workers) or a plain object
188
+ * carrying the method, absolute URL, and headers.
189
+ */
190
+ type AgentRequestInput = Request | {
191
+ method: string;
192
+ /** Absolute request URL, e.g. `https://example.com/path?q=1`. */
193
+ url: string;
194
+ /** Headers as a WHATWG `Headers` or a plain (lowercased-key) record. */
195
+ headers: Headers | Record<string, string>;
196
+ };
197
+
198
+ /**
199
+ * The edge validator's verdict, as the origin sees it.
200
+ *
201
+ * WHY THIS MODULE EXISTS
202
+ *
203
+ * The Cloudflare clearance worker has set `x-wd-clearance` on every forwarded
204
+ * request since the validator shipped, and nothing has ever read it. Grepping the
205
+ * header across the monorepo, this SDK and the WordPress plugin returned only the
206
+ * worker that writes it, its own tests, and one documentation page. We shipped a
207
+ * tag no customer could act on, then documented it as "watch the header in your
208
+ * logs."
209
+ *
210
+ * That gap matters more than it sounds. On a scoped route the gate's only options
211
+ * were pass or challenge, and a challenge on public content is a 403 to every
212
+ * client that cannot run JavaScript — search crawlers included. Reading the tag
213
+ * gives the application a third option it owns: log it, meter it, skip an
214
+ * expensive query, serve something cheaper. That is the first "yes" a cautious
215
+ * operator can give.
216
+ *
217
+ * WHAT IT IS NOT
218
+ *
219
+ * These values are advisory context, not authentication. They are only meaningful
220
+ * for requests that actually passed through the edge validator, and the validator
221
+ * strips inbound copies precisely so that the origin can attribute them to us.
222
+ * A request that reaches the origin WITHOUT passing through the proxy — straight
223
+ * to the origin IP, or a route that does not match — can carry anything. Treat
224
+ * `present: false` as "no information", never as "not a bot", and keep the origin
225
+ * unreachable except through the proxy if you intend to branch on this.
226
+ */
227
+ /** Header the edge validator uses for its clearance verdict. */
228
+ declare const EDGE_CLEARANCE_HEADER = "x-wd-clearance";
229
+ /** Header the edge validator uses for the sensor's client classification. */
230
+ declare const EDGE_CLASS_HEADER = "x-wd-class";
231
+ /**
232
+ * What the edge sensor concluded the client is.
233
+ *
234
+ * - `verified` — an identity something other than the client has attested
235
+ * (Cloudflare's verified-bot signal). **Never degrade these.** This is
236
+ * Googlebot and friends, and quietly serving them less is how a customer loses
237
+ * search presence and blames you six weeks later.
238
+ * - `crawler` — self-declares as a crawler, unproven. Real-but-unverified
239
+ * crawlers and forged ones both land here.
240
+ * - `script` — an HTTP client library, a Chromium user agent sending no client
241
+ * hints, or no user agent at all. Not a browser.
242
+ * - `browser` — nothing that distinguishes a non-human fired. A statement about
243
+ * our signals, not a certificate.
244
+ */
245
+ type EdgeClass = 'verified' | 'crawler' | 'script' | 'browser';
246
+ /**
247
+ * The edge's annotations on one request, typed.
248
+ *
249
+ * Every field is optional except `present`, because the edge validator may not be
250
+ * in front of this request at all — and the difference between "the edge said
251
+ * browser" and "there is no edge here" is the difference between a safe
252
+ * optimisation and a security hole.
253
+ */
254
+ interface EdgeVerdict {
255
+ /**
256
+ * True when the edge validator annotated this request. False means no
257
+ * information — not "human", not "safe".
258
+ */
259
+ present: boolean;
260
+ /**
261
+ * The clearance verdict, e.g. `valid`, `missing`, `verified-bot`,
262
+ * `signed-agent`, `machine`, `insufficient-trust`. Free-form on purpose: the
263
+ * validator gains labels faster than an SDK release can enumerate them, and an
264
+ * unknown label must not become `undefined`.
265
+ */
266
+ clearance?: string;
267
+ /** The sensor's classification, when it classified this request. */
268
+ class?: EdgeClass;
269
+ /** `class === 'verified'`. Convenience so callers need no string literals. */
270
+ isVerified: boolean;
271
+ /** `class === 'crawler'`. */
272
+ isCrawler: boolean;
273
+ /** `class === 'script'`. */
274
+ isScript: boolean;
275
+ /** `class === 'browser'`. */
276
+ isBrowser: boolean;
277
+ /**
278
+ * True for a class that is not a browser and is not attested — `script` or
279
+ * `crawler`.
280
+ *
281
+ * This is the predicate most applications actually want, and it deliberately
282
+ * excludes `verified`: the common intent is "cheapen this response", and the one
283
+ * population you must never cheapen for is the one whose identity was proven.
284
+ */
285
+ isUnattestedNonBrowser: boolean;
286
+ }
287
+ /**
288
+ * Read the edge validator's annotations out of a request's headers.
289
+ *
290
+ * Accepts the header bag the SDK already carries on `RequestMetadata` — lowercase
291
+ * keys — and tolerates mixed case, since adapters differ on normalisation.
292
+ *
293
+ * An unrecognised class value is dropped rather than passed through. The set is
294
+ * closed and small; a value outside it means either a version skew or something
295
+ * that is not our worker, and in both cases silence beats a value a caller might
296
+ * branch on.
297
+ */
298
+ declare function readEdgeVerdict(headers: Record<string, string> | undefined): EdgeVerdict;
299
+
300
+ /**
301
+ * GENERATED FILE — DO NOT EDIT.
302
+ *
303
+ * Source of truth: the Go agent registry in the main application repo.
304
+ * Regenerate with `packages/webdecoy/scripts/gen-bot-registry.mjs`; see that
305
+ * script for the command.
306
+ *
307
+ * ORDER IS SIGNIFICANT. Entries are in `agents.MatchUserAgent` order — AI data
308
+ * scrapers first, then AI search crawlers, AI agents, search engines, then the
309
+ * remaining categories. `matchUserAgent()` returns the first hit, and several
310
+ * agents share User-Agent substrings, so sorting this array changes how real
311
+ * traffic is classified.
312
+ *
313
+ * 169 agents across 15 categories.
314
+ */
315
+ /**
316
+ * Classification categories, mirroring `agents.Category` in Go.
317
+ *
318
+ * Declared here rather than hand-written next door so a category added in Go
319
+ * cannot go missing in TypeScript.
320
+ */
321
+ 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";
322
+ /** One entry in the registry. */
323
+ interface BotAgent {
324
+ /** Stable lowercase slug, e.g. `gptbot`. */
325
+ id: string;
326
+ /** Display name, e.g. `GPTBot`. */
327
+ name: string;
328
+ category: BotCategory;
329
+ /** Operator, e.g. `OpenAI`. */
330
+ organization: string;
331
+ /** The registry's default threat score for this agent (0-100). */
332
+ baseScore: number;
333
+ /** Whether the operator documents honouring robots.txt. */
334
+ respectsRobots: boolean;
335
+ /** Lowercase User-Agent substrings that identify it. */
336
+ uaPatterns: readonly string[];
337
+ }
338
+ /** Every declared category, including any with no agents yet. */
339
+ declare const BOT_CATEGORIES: readonly BotCategory[];
340
+ /** The agent table, in match order. */
341
+ declare const BOT_REGISTRY: readonly BotAgent[];
342
+
343
+ /**
344
+ * Local bot classification.
345
+ *
346
+ * WHY THIS IS IN THE SDK AT ALL
347
+ *
348
+ * The scoring pipeline already identifies named agents server-side, but it does
349
+ * so *after* the request is reported — which is too late to decide anything. A
350
+ * customer who wants "block AI training crawlers, allow search crawlers" needs
351
+ * the answer synchronously, in the request path, with no network call. So the Go
352
+ * registry is generated into {@link BOT_REGISTRY} and matched here.
353
+ *
354
+ * WHAT THIS IS NOT
355
+ *
356
+ * This is a User-Agent lookup. It identifies agents that say who they are, and
357
+ * nothing else. An agent that spoofs Chrome is invisible to it, and always will
358
+ * be — that is the point of the 1% User-Agent weight in the unified score, and
359
+ * nothing here changes that arithmetic.
360
+ *
361
+ * That is a feature for the use case it serves. GPTBot, ClaudeBot and Googlebot
362
+ * all self-identify honestly, and the decision a customer wants to make about
363
+ * them ("don't train on my content") is a POLICY choice about a cooperative
364
+ * agent, not a threat judgement about a hostile one. Acting on a claim is
365
+ * correct when the claim is the thing you care about.
366
+ *
367
+ * For agents that lie, the answer is the rest of the product: tripwires,
368
+ * honeytokens and the edge classifier see behaviour, which cannot be spoofed by
369
+ * editing a header.
370
+ */
371
+
372
+ /**
373
+ * What a rule sees about the agent behind a request.
374
+ *
375
+ * Always populated, never undefined: a rule that has to check whether
376
+ * classification ran is a rule people get wrong. When nothing matched,
377
+ * `known` is false and `category` is `'none'`.
378
+ */
379
+ interface BotVerdict {
380
+ /** Whether the User-Agent matched a known agent. */
381
+ known: boolean;
382
+ /** Registry slug, e.g. `gptbot`. Undefined when unknown. */
383
+ id?: string;
384
+ /** Display name, e.g. `GPTBot`. Undefined when unknown. */
385
+ name?: string;
386
+ /** Customer-facing category — the same vocabulary as the dashboard. */
387
+ category: BotCategory;
388
+ /** Operator, e.g. `OpenAI`. Undefined when unknown. */
389
+ organization?: string;
390
+ /** The registry's threat score for this agent, 0-100. 0 when unknown. */
391
+ score: number;
392
+ /**
393
+ * Whether the operator documents honouring robots.txt. Undefined when unknown.
394
+ *
395
+ * Documented behaviour, not observed behaviour — it is what the operator
396
+ * publishes, so treat it as a claim like any other.
397
+ */
398
+ respectsRobots?: boolean;
399
+ /** True for training crawlers, AI search crawlers, AI agents and assistants. */
400
+ isAI: boolean;
401
+ }
402
+ /**
403
+ * Find the agent behind a User-Agent string, or undefined.
404
+ *
405
+ * Returns the FIRST match in registry order, which is why {@link BOT_REGISTRY}
406
+ * must not be sorted: the table arrives ordered by category priority, mirroring
407
+ * `agents.MatchUserAgent` in Go so both sides classify identically.
408
+ */
409
+ declare function matchUserAgent(userAgent: string | undefined | null): BotAgent | undefined;
410
+ /** Classify a User-Agent into the verdict rules evaluate against. */
411
+ declare function classifyUserAgent(userAgent: string | undefined | null): BotVerdict;
412
+
413
+ /**
414
+ * What the SDK considers "the same caller".
415
+ *
416
+ * WHY THIS MODULE EXISTS
417
+ *
418
+ * `rateLimit({ keyBy })` was the only place a caller could change what a rule
419
+ * keyed on, and it was per-rule. Everything else — the decision cache, and any
420
+ * future keyed rule — was IP-only.
421
+ *
422
+ * That is the wrong subject for exactly the traffic worth limiting. On an
423
+ * authenticated API the meaningful caller is a user id or an API key, not an
424
+ * address shared by a whole office or rotated through a proxy pool. It is also
425
+ * the wrong subject for us specifically: the actor model exists because IP is
426
+ * not identity.
427
+ */
428
+
429
+ /**
430
+ * One component of the key that identifies a caller.
431
+ *
432
+ * A string names a field of the request; a function derives whatever you like
433
+ * from the context (a decoded JWT subject, a tenant id, an API key header).
434
+ */
435
+ type Characteristic = 'ip' | 'path' | 'method' | 'userAgent' | ((context: RuleContext) => string | undefined);
436
+ /** The default: one bucket per client address. */
437
+ declare const DEFAULT_CHARACTERISTICS: readonly Characteristic[];
438
+ /**
439
+ * Derive the key identifying this caller.
440
+ *
441
+ * If any characteristic is absent the whole key falls back to the IP. The
442
+ * alternative — a key with an empty component — silently merges every request
443
+ * missing that field into one bucket, so an unauthenticated request would share
444
+ * a rate limit with every other unauthenticated request. That is the failure
445
+ * mode where a limit meant for one tenant takes out anonymous traffic site-wide,
446
+ * and it is invisible until it happens.
447
+ */
448
+ declare function deriveKey(context: RuleContext, characteristics?: readonly Characteristic[]): string;
449
+
450
+ /**
451
+ * Reusing a decision we already paid for.
452
+ *
453
+ * WHY THIS IS NARROW
454
+ *
455
+ * Only decisions that cost a network round trip are cached, and only when they
456
+ * came back DENY or CHALLENGE. Two deliberate exclusions:
457
+ *
458
+ * - **Rule decisions are never cached.** A rate limiter has to see every
459
+ * request to advance its window, and a cached tripwire DENY would stop the
460
+ * violation being reported. Rules are evaluated in-process and cost
461
+ * microseconds, so there is nothing to save.
462
+ * - **ALLOW is never cached.** Caching an allow is how a client that has since
463
+ * started misbehaving keeps sailing through, and the request it saves is the
464
+ * cheap one — a low-risk request already returns without calling out.
465
+ *
466
+ * So this exists for one case: a client we have decided against, hammering the
467
+ * origin, where each request would otherwise re-ask the service the question it
468
+ * just answered.
469
+ */
470
+
471
+ interface DecisionCacheOptions {
472
+ /**
473
+ * How long a denial may be reused, in milliseconds.
474
+ * @default 60_000
475
+ */
476
+ ttl?: number;
477
+ /**
478
+ * Maximum entries held. When full, the oldest insertions are dropped.
479
+ * A bound rather than a target: this must not become a way for a caller
480
+ * cycling keys to grow the process's memory without limit.
481
+ * @default 10_000
482
+ */
483
+ max?: number;
484
+ }
485
+ declare class DecisionCache {
486
+ private readonly ttl;
487
+ private readonly max;
488
+ private entries;
489
+ constructor(options?: DecisionCacheOptions);
490
+ /** A cached decision for this key, or undefined. Expired entries are dropped. */
491
+ get(key: string): Decision | undefined;
492
+ /**
493
+ * Remember a decision, if it is one of the kinds worth remembering.
494
+ * Returns whether it was stored, so a caller can assert on the policy rather
495
+ * than infer it.
496
+ */
497
+ set(key: string, decision: Decision): boolean;
498
+ clear(): void;
499
+ get size(): number;
500
+ /** How long entries live, in milliseconds. Reported on the decision. */
501
+ get lifetime(): number;
502
+ }
503
+
504
+ /**
505
+ * Where the SDK's diagnostics go.
506
+ *
507
+ * WHY THIS EXISTS
508
+ *
509
+ * Observability was `debug: boolean` writing to `console.log`. In any real
510
+ * deployment that is either off or noise: it cannot be routed into the logger
511
+ * the app already runs, it cannot be sampled, and the lines it emits are
512
+ * unstructured strings that a log aggregator can only match on.
513
+ *
514
+ * The interface is deliberately the smallest thing every logger already
515
+ * implements — pino, winston, bunyan, `console` — so wiring one up is passing
516
+ * it, not writing an adapter.
517
+ */
518
+ /** A structured payload attached to a log line. */
519
+ type LogFields = Record<string, unknown>;
520
+ interface Logger {
521
+ debug(message: string, fields?: LogFields): void;
522
+ info(message: string, fields?: LogFields): void;
523
+ warn(message: string, fields?: LogFields): void;
524
+ error(message: string, fields?: LogFields): void;
525
+ }
526
+ /**
527
+ * The historical behaviour: `console`, and silent below `warn` unless `debug` is
528
+ * on. Kept exactly as it was so an existing install sees no change in output.
529
+ */
530
+ declare function consoleLogger(debug: boolean): Logger;
531
+ /** Discards everything. Useful in tests and in the testing utilities. */
532
+ declare const silentLogger: Logger;
533
+ /**
534
+ * Wrap a pino-style logger, which takes `(fields, message)` — the opposite
535
+ * order to this interface and to `console`.
536
+ *
537
+ * Passing a pino instance directly would type-check and then quietly mangle
538
+ * every line: pino reads the first argument as the message and treats the second
539
+ * as printf interpolation, so the structured fields vanish. Nobody notices until
540
+ * they need the log. One explicit wrapper is better than argument-order
541
+ * guesswork that is wrong for somebody.
542
+ *
543
+ * ```ts
544
+ * new WebDecoy({ logger: fromPino(pino()) });
545
+ * ```
546
+ */
547
+ declare function fromPino(pino: {
548
+ debug(fields: LogFields, message: string): void;
549
+ info(fields: LogFields, message: string): void;
550
+ warn(fields: LogFields, message: string): void;
551
+ error(fields: LogFields, message: string): void;
552
+ }): Logger;
553
+
554
+ /**
555
+ * Web Decoy SDK Types
556
+ * Based on the ingest service API contract
557
+ */
558
+
559
+ /**
560
+ * Configuration options for the Web Decoy SDK
561
+ */
562
+ interface WebDecoyConfig {
563
+ /**
564
+ * API key for authentication (sk_live_xxxxx format)
565
+ * Get this from your Web Decoy dashboard
566
+ * Optional — when omitted, SDK runs in local-only mode (rules still evaluate)
567
+ */
568
+ apiKey?: string;
569
+ /**
570
+ * API URL for the Web Decoy ingest service
571
+ * @default 'https://ingest.webdecoy.com'
572
+ */
573
+ apiUrl?: string;
574
+ /**
575
+ * Enable TLS fingerprinting for advanced bot detection
576
+ * @default true
577
+ */
578
+ enableTLSFingerprinting?: boolean;
579
+ /**
580
+ * Threat score threshold for blocking (0-100)
581
+ * Requests with scores above this will be blocked
582
+ * @default 80
583
+ */
584
+ threatScoreThreshold?: number;
585
+ /**
586
+ * Timeout for API requests in milliseconds
587
+ * @default 5000
588
+ */
589
+ timeout?: number;
590
+ /**
591
+ * Enable debug logging
592
+ * @default false
593
+ */
594
+ debug?: boolean;
595
+ /**
596
+ * Whether to reject unauthorized TLS certificates
597
+ * Set to false for development/testing with self-signed certificates
598
+ * @default true
599
+ */
600
+ tlsRejectUnauthorized?: boolean;
601
+ /**
602
+ * Rules to evaluate before calling the detection API
603
+ * Rules are evaluated in order; first DENY/THROTTLE wins
604
+ */
605
+ rules?: Rule[];
606
+ /**
607
+ * Options for local Web Bot Auth agent verification (used by `detectBot()`
608
+ * and the `webBotAuth()` rule) — trusted directories, cache TTL, etc.
609
+ * Defaults are sensible; override only to curate your own agent allowlist.
610
+ */
611
+ webBotAuth?: AgentVerifierOptions;
612
+ /**
613
+ * What counts as "the same caller" — the components of the key that keyed
614
+ * rules and the decision cache use.
615
+ *
616
+ * Defaults to `['ip']`. On an authenticated API the meaningful subject is
617
+ * usually not an address:
618
+ *
619
+ * ```ts
620
+ * characteristics: [(ctx) => ctx.headers['x-api-key']]
621
+ * ```
622
+ *
623
+ * A rule's own `keyBy` still wins over this. If a characteristic is absent on
624
+ * a request the key falls back to the IP rather than bucketing every such
625
+ * request together.
626
+ */
627
+ characteristics?: Characteristic[];
628
+ /**
629
+ * Reuse of decisions that cost a network round trip. `false` disables it.
630
+ *
631
+ * Only server-derived DENY and CHALLENGE verdicts are cached — never ALLOW,
632
+ * and never a rule outcome, because a rate limiter has to see every request.
633
+ * @default { ttl: 60_000, max: 10_000 }
634
+ */
635
+ decisionCache?: DecisionCacheOptions | false;
636
+ /**
637
+ * Where the SDK's diagnostics go. Defaults to `console`, gated on `debug` for
638
+ * everything below `warn`.
639
+ *
640
+ * Any object with `debug`/`info`/`warn`/`error` taking `(message, fields?)`
641
+ * works. For a pino-style logger, whose argument order is the other way
642
+ * round, wrap it with `fromPino()` — passing one directly type-checks and then
643
+ * silently drops every structured field.
644
+ */
645
+ logger?: Logger;
646
+ }
647
+ /**
648
+ * TLS connection information from the request
649
+ */
650
+ interface TLSInfo {
651
+ /** TLS version (e.g., 771 for TLS 1.2, 772 for TLS 1.3) */
652
+ version?: number;
653
+ /** List of cipher suites supported by the client */
654
+ cipher_suites?: number[];
655
+ /** List of TLS extensions */
656
+ extensions?: number[];
657
+ /** Elliptic curves supported */
658
+ supported_groups?: number[];
659
+ /** EC point formats */
660
+ ec_point_formats?: number[];
661
+ /** Signature algorithms */
662
+ signature_algorithms?: number[];
663
+ /** Server name indication */
664
+ server_name?: string;
665
+ /** ALPN protocols */
666
+ alpn_protocols?: string[];
667
+ }
668
+ /**
669
+ * Request metadata sent to the detection service
670
+ */
671
+ interface RequestMetadata {
672
+ /** HTTP method (GET, POST, etc.) */
673
+ method: string;
674
+ /** Request path */
675
+ path: string;
676
+ /** Client IP address (REQUIRED) */
677
+ ip: string;
678
+ /** User-Agent header */
679
+ user_agent?: string;
680
+ /** All request headers */
681
+ headers: Record<string, string>;
682
+ /**
683
+ * Raw query string, without the leading `?`. Populated by the adapters.
684
+ * Read by `attackSignatures()`, which cannot see it via `path` — Express's
685
+ * `req.path` excludes the query, and that is where injection payloads live.
686
+ */
687
+ query?: string;
688
+ /**
689
+ * Request body as text, when the application chooses to supply it. Never
690
+ * populated automatically: buffering a body the application has not already
691
+ * parsed would change its streaming behaviour.
692
+ */
693
+ body?: string;
694
+ /** TLS connection information */
695
+ tls_info?: TLSInfo;
696
+ /** Request timestamp (Unix milliseconds) */
697
+ timestamp: number;
698
+ }
699
+ /**
700
+ * Local analysis performed by the SDK
701
+ */
702
+ interface LocalAnalysis {
703
+ /** True if suspicious headers detected */
704
+ suspicious_headers: boolean;
705
+ /** True if Sec-CH-UA header is missing */
706
+ missing_sec_ch_ua: boolean;
707
+ /** True if IP is from a known datacenter */
708
+ datacenter_ip: boolean;
709
+ /** Local threat score (0-100) */
710
+ local_score: number;
711
+ /** True if server-side verification is needed */
712
+ needs_verification: boolean;
713
+ /** Detection flags */
714
+ flags: string[];
715
+ }
716
+ /**
717
+ * Detection request sent to the ingest service
718
+ */
719
+ interface SDKDetectionRequest {
720
+ request_metadata: RequestMetadata;
721
+ local_analysis: LocalAnalysis;
722
+ }
723
+ /**
724
+ * Detection response from the ingest service
725
+ */
726
+ interface SDKDetectionResponse {
727
+ /** Decision: "allow", "block", or "challenge" */
728
+ decision: 'allow' | 'block' | 'challenge';
729
+ /** Confidence score (0-100) */
730
+ confidence: number;
731
+ /** Threat level classification */
732
+ threat_level: 'MINIMAL' | 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
733
+ /** True if a bot was detected */
734
+ bot_detected: boolean;
735
+ /** Type of bot detected (if any) */
736
+ bot_type?: string;
737
+ /** Unique detection ID */
738
+ detection_id: string;
739
+ /** True if a response rule was enforced */
740
+ rule_enforced: boolean;
741
+ }
742
+ /**
743
+ * Options for the protect() method
744
+ */
745
+ interface ProtectOptions {
746
+ /** Custom threat score threshold for this request */
747
+ threshold?: number;
748
+ /** Skip local analysis and only use server-side detection */
749
+ skipLocalAnalysis?: boolean;
750
+ /** Additional metadata to include in the detection */
751
+ metadata?: Record<string, any>;
752
+ }
753
+
754
+ /**
755
+ * What the SDK concluded about one request, and why.
756
+ *
757
+ * WHY THIS MODULE EXISTS
758
+ *
759
+ * `protect()` used to return `{ allowed, detection }` and the adapters typed the
760
+ * value they handed to `onBlocked` as `any`. A developer integrating us had to
761
+ * destructure a blob and string-match to find out which rule fired, and there
762
+ * was nowhere to put three things the SDK already knew:
763
+ *
764
+ * - **Which rules ran.** The engine collapsed to a single deciding rule plus a
765
+ * violations array, so a filter rule that never ran for want of enrichment was
766
+ * indistinguishable from one that ran and passed.
767
+ * - **"Challenge this one."** The captcha in `@webdecoy/client` had no verdict
768
+ * that could route to it, so it was reachable only by wiring it up by hand.
769
+ * - **A stable id.** `'rule_' + Date.now()` is not unique under concurrency and
770
+ * correlates with nothing in the dashboard.
771
+ *
772
+ * `allowed` still means exactly what it meant before, including failing open on
773
+ * ERROR, so existing middleware keeps working unchanged.
774
+ */
775
+
776
+ /**
777
+ * The outcome of a decision.
778
+ *
779
+ * `ERROR` is not a synonym for `DENY`. It means the SDK could not reach a
780
+ * verdict — the detection call failed, the request was malformed — and the
781
+ * request is allowed through, because a security control that takes the site
782
+ * down when it has a bad day is worse than the traffic it was filtering.
783
+ */
784
+ type Conclusion = 'ALLOW' | 'DENY' | 'CHALLENGE' | 'ERROR';
785
+ /**
786
+ * Whether a rule actually contributed to the decision.
787
+ *
788
+ * - `RUN` — evaluated, and its conclusion counts.
789
+ * - `DRY_RUN` — evaluated, and its conclusion is recorded but not enforced.
790
+ * - `NOT_RUN` — could not evaluate, because a signal it needs was absent. A
791
+ * filter rule with no IP enrichment, a Web Bot Auth rule on a request with no
792
+ * host. This is the state that used to be invisible: such a rule reported
793
+ * ALLOW, which reads as "checked and fine" rather than "never checked".
794
+ * - `CACHED` — not evaluated; a prior decision for this key was reused.
795
+ */
796
+ type RuleState = 'RUN' | 'DRY_RUN' | 'NOT_RUN' | 'CACHED';
797
+ /** One rule's contribution to a decision. */
798
+ interface RuleOutcome {
799
+ /** The rule's name, e.g. `tripwire` or `rate-limit:100/60s`. */
800
+ rule: string;
801
+ state: RuleState;
802
+ conclusion: Conclusion;
803
+ /** The raw rule action, for rules that distinguish throttling from denial. */
804
+ action?: 'ALLOW' | 'DENY' | 'THROTTLE';
805
+ reason?: string;
806
+ metadata?: Record<string, unknown>;
807
+ }
808
+ /**
809
+ * The result of `protect()`.
810
+ *
811
+ * Kept as an interface separate from the class so that the shape is what
812
+ * consumers depend on. The class exists to carry the narrowing helpers.
813
+ */
814
+ interface ProtectResult {
815
+ /** Unique id for this decision. Correlates with the dashboard. */
816
+ readonly id: string;
817
+ readonly conclusion: Conclusion;
818
+ /**
819
+ * Whether to serve the request.
820
+ *
821
+ * True for `ALLOW` and for `ERROR` (fail open); false for `DENY` and
822
+ * `CHALLENGE`. Unchanged from before the typed decision existed.
823
+ */
824
+ readonly allowed: boolean;
825
+ /** Every rule that was configured, and what it concluded. */
826
+ readonly results: readonly RuleOutcome[];
827
+ /** The deciding reason, when there is one. */
828
+ readonly reason?: string;
829
+ /** Detection response from the service, or the locally-synthesised one. */
830
+ readonly detection: SDKDetectionResponse;
831
+ /** Error message when `conclusion` is `ERROR`. */
832
+ readonly error?: string;
833
+ /** The rule engine's raw result, for callers that were already using it. */
834
+ readonly ruleResult?: RuleEngineResult;
835
+ /**
836
+ * Web Bot Auth verdict, present when a `webBotAuth()` rule triggered local
837
+ * agent verification. Lets middleware treat a `verified` agent specially
838
+ * without re-verifying.
839
+ */
840
+ readonly agent?: AgentVerdict;
841
+ /**
842
+ * What the edge validator said about this request, parsed from
843
+ * `x-wd-clearance` and `x-wd-class`.
844
+ *
845
+ * Always present. Check `edge.present` before branching: false means the edge
846
+ * did not front this request, which is no information rather than a clean
847
+ * bill of health.
848
+ */
849
+ readonly edge?: EdgeVerdict;
850
+ /** The characteristic key this decision was made for. */
851
+ readonly key?: string;
852
+ /** How long this decision may be reused, in milliseconds. 0 means never. */
853
+ readonly ttl: number;
854
+ isAllowed(): boolean;
855
+ isDenied(): boolean;
856
+ isChallenged(): boolean;
857
+ isErrored(): boolean;
858
+ /** Whether a named rule denied the request. */
859
+ deniedBy(rule: string): boolean;
860
+ }
861
+ interface DecisionInit {
862
+ conclusion: Conclusion;
863
+ detection: SDKDetectionResponse;
864
+ results?: RuleOutcome[];
865
+ reason?: string;
866
+ error?: string;
867
+ ruleResult?: RuleEngineResult;
868
+ agent?: AgentVerdict;
869
+ edge?: EdgeVerdict;
870
+ key?: string;
871
+ ttl?: number;
872
+ id?: string;
873
+ }
874
+ /**
875
+ * A decision id.
876
+ *
877
+ * Random rather than sequential: ids leave the process (they go on the
878
+ * detection row and into customers' logs), and a counter would leak request
879
+ * volume to anyone who saw two of them.
880
+ */
881
+ declare function newDecisionId(): string;
882
+ declare class Decision implements ProtectResult {
883
+ readonly id: string;
884
+ readonly conclusion: Conclusion;
885
+ readonly results: readonly RuleOutcome[];
886
+ readonly reason?: string;
887
+ readonly detection: SDKDetectionResponse;
888
+ readonly error?: string;
889
+ readonly ruleResult?: RuleEngineResult;
890
+ readonly agent?: AgentVerdict;
891
+ readonly edge?: EdgeVerdict;
892
+ readonly key?: string;
893
+ readonly ttl: number;
894
+ constructor(init: DecisionInit);
895
+ get allowed(): boolean;
896
+ isAllowed(): boolean;
897
+ isDenied(): boolean;
898
+ isChallenged(): boolean;
899
+ isErrored(): boolean;
900
+ deniedBy(rule: string): boolean;
901
+ /** A copy of this decision with the edge verdict attached. */
902
+ withEdge(edge: EdgeVerdict | undefined): Decision;
903
+ /** A copy marked as served from cache, with every rule re-stated as CACHED. */
904
+ asCached(): Decision;
905
+ private init;
906
+ }
907
+
908
+ /**
909
+ * Context available to rules during evaluation
910
+ */
911
+ interface RuleContext {
912
+ /** Client IP address */
913
+ ip: string;
914
+ /** Request path */
915
+ path: string;
916
+ /** HTTP method */
917
+ method: string;
918
+ /** User-Agent string */
919
+ userAgent?: string;
920
+ /** Request headers (lowercase keys) */
921
+ headers: Record<string, string>;
922
+ /** Raw query string, without the leading `?`. */
923
+ query?: string;
924
+ /** Request body as text, when the application supplied one. */
925
+ body?: string;
926
+ /** Request timestamp */
927
+ timestamp: number;
928
+ /** IP enrichment data (populated async when available) */
929
+ enrichment?: IPEnrichmentData;
930
+ /**
931
+ * Web Bot Auth verdict (populated async before evaluation when a
932
+ * `webBotAuth` rule is
933
+ * present). Lets a synchronous rule act on cryptographic agent verification.
934
+ */
935
+ agent?: AgentVerdict;
936
+ /**
937
+ * The edge validator's annotations on this request, parsed from
938
+ * `x-wd-clearance` and `x-wd-class`. Always populated — `present: false` when
939
+ * the edge did not front this request. Filter expressions read it as
940
+ * `edge.class`, `edge.clearance` and `edge.present`.
941
+ */
942
+ edge?: EdgeVerdict;
943
+ /**
944
+ * Who the User-Agent says it is, matched against the generated agent
945
+ * registry. Always populated — `known: false` when nothing matched. Filter
946
+ * expressions read it as `bot.category`, `bot.name`, `bot.ai` and friends.
947
+ *
948
+ * A self-declared identity, so it is evidence about cooperative agents only.
949
+ * See {@link BotVerdict}.
950
+ */
951
+ bot?: BotVerdict;
952
+ /**
953
+ * The key identifying this caller, derived from the SDK's `characteristics`.
954
+ * Keyed rules use it unless they were given their own `keyBy`. Defaults to
955
+ * the IP, so a rule can read it unconditionally.
956
+ */
957
+ key?: string;
958
+ /**
959
+ * Outcomes a rule resolved during the async pre-fetch, keyed by rule name.
960
+ * Populated by {@link Rule.prepare}; read synchronously by `evaluate`.
961
+ */
962
+ prepared?: Record<string, unknown>;
963
+ }
964
+ /**
965
+ * Result of evaluating a single rule
966
+ */
967
+ interface RuleResult {
968
+ /** Action to take */
969
+ action: 'ALLOW' | 'DENY' | 'THROTTLE';
970
+ /** Name of the rule that produced this result */
971
+ rule: string;
972
+ /** Human-readable reason */
973
+ reason?: string;
974
+ /** Additional metadata */
975
+ metadata?: Record<string, any>;
976
+ /**
977
+ * Set by a rule that could not evaluate because a signal it needs was absent
978
+ * — a filter rule with no IP enrichment, a Web Bot Auth rule on a request
979
+ * with no host. Such a rule returns ALLOW, and without this the result is
980
+ * indistinguishable from "checked and fine".
981
+ *
982
+ * Rules that ran leave this unset; the engine fills in `RUN` or `DRY_RUN`.
983
+ */
984
+ state?: RuleState;
985
+ }
986
+ /**
987
+ * A rule that can evaluate request context and produce a decision
988
+ */
989
+ interface Rule {
990
+ /** Unique name for this rule */
991
+ name: string;
992
+ /** Evaluate the rule against request context */
993
+ evaluate(context: RuleContext): RuleResult;
994
+ /**
995
+ * Resolve anything this rule needs from the network before `evaluate` runs,
996
+ * stashing it on `context.prepared`.
997
+ *
998
+ * `evaluate` is synchronous, and making it async would turn every rule
999
+ * evaluation into a promise for the sake of the one rule that needs it. This
1000
+ * is the same pre-fetch the SDK already does for IP enrichment and Web Bot
1001
+ * Auth verdicts.
1002
+ */
1003
+ prepare?(context: RuleContext): Promise<void>;
1004
+ /** Clean up resources (timers, etc.) */
1005
+ destroy?(): void;
1006
+ }
1007
+ /**
1008
+ * Configuration for rate limiting
1009
+ */
1010
+ interface RateLimitConfig {
1011
+ /** Maximum requests allowed in the window */
1012
+ max: number;
1013
+ /** Window size in seconds */
1014
+ window: number;
1015
+ /** Algorithm: 'fixed' (default) or 'sliding' */
1016
+ algorithm?: 'fixed' | 'sliding';
1017
+ /** Custom key derivation function. Default: the SDK's characteristics, then IP */
1018
+ keyBy?: (context: RuleContext) => string;
1019
+ /**
1020
+ * Where the counters live. Defaults to this process's memory, which is
1021
+ * correct for a single process and wrong the moment you run two — the limit
1022
+ * becomes `max × instances` and resets on every cold start.
1023
+ *
1024
+ * Pass {@link upstashRateLimitStore} (or your own {@link RateLimitStore}) to
1025
+ * share counters across replicas.
1026
+ */
1027
+ store?: RateLimitStore;
1028
+ /** Action when limit is exceeded: 'DENY' or 'THROTTLE' (default: 'THROTTLE') */
1029
+ action?: 'DENY' | 'THROTTLE';
1030
+ /** Dry run mode: log violations but don't block */
1031
+ dryRun?: boolean;
1032
+ }
1033
+ /**
1034
+ * Configuration for filter rules
1035
+ */
1036
+ interface FilterConfig {
1037
+ /** Filter expression (e.g., 'ip.vpn or ip.tor') */
1038
+ expression: string;
1039
+ /** Action when filter matches: 'DENY' (default) or 'THROTTLE' */
1040
+ action?: 'DENY' | 'THROTTLE';
1041
+ /** Dry run mode: log violations but don't block */
1042
+ dryRun?: boolean;
1043
+ }
1044
+ /**
1045
+ * Configuration for bot-category rules
1046
+ */
1047
+ interface BotRuleConfig {
1048
+ /**
1049
+ * Categories to act on, e.g. `['training_crawler']`. Uses the same vocabulary
1050
+ * as the dashboard's `ai_scraper_category` column.
1051
+ */
1052
+ categories?: BotCategory[];
1053
+ /** Specific agents by registry slug or display name, e.g. `['gptbot']`. */
1054
+ agents?: string[];
1055
+ /**
1056
+ * Act on every AI client — training crawlers, AI search crawlers, AI agents
1057
+ * and AI assistants.
1058
+ */
1059
+ ai?: boolean;
1060
+ /**
1061
+ * Never act on these, whatever else matches. Applied last, so
1062
+ * `{ ai: true, allow: ['perplexitybot'] }` reads the way it looks.
1063
+ */
1064
+ allow?: string[];
1065
+ /** Action when an agent matches: 'DENY' (default) or 'THROTTLE'. */
1066
+ action?: 'DENY' | 'THROTTLE';
1067
+ /** Log the violation but don't block. */
1068
+ dryRun?: boolean;
1069
+ }
1070
+ /**
1071
+ * Configuration for tripwire (honeypot-path) rules
1072
+ */
1073
+ interface TripwireConfig {
1074
+ /** Exact hidden honeypot paths (e.g. a honeytoken path or `/admin-backup.zip`). */
1075
+ paths?: string[];
1076
+ /** Path prefixes treated as tripwires (e.g. `/.git/`). */
1077
+ prefixes?: string[];
1078
+ /** Regex patterns for tripwire paths. */
1079
+ patterns?: RegExp[];
1080
+ /** Include the built-in scanner/scraper bait paths. Default `true`. */
1081
+ includeDefaults?: boolean;
1082
+ /** Action when a tripwire is hit: 'DENY' (default) or 'THROTTLE'. */
1083
+ action?: 'DENY' | 'THROTTLE';
1084
+ /** Dry run mode: log the violation but don't block. */
1085
+ dryRun?: boolean;
1086
+ }
1087
+ /**
1088
+ * A violation event recorded when a rule triggers
1089
+ */
1090
+ interface ViolationEvent {
1091
+ /** Rule that triggered */
1092
+ rule: string;
1093
+ /** Action taken */
1094
+ action: 'DENY' | 'THROTTLE' | 'ALLOW';
1095
+ /** Client IP */
1096
+ ip: string;
1097
+ /** Request path */
1098
+ path?: string;
1099
+ /** HTTP method */
1100
+ method?: string;
1101
+ /** User-Agent */
1102
+ userAgent?: string;
1103
+ /** Reason for the violation */
1104
+ reason?: string;
1105
+ /**
1106
+ * The request's wd_clearance token, when present. Lets the backend bind a
1107
+ * tripwire hit to the actor's device fingerprint and deny it — the same
1108
+ * durable lockout a decoy hit produces. Only carried
1109
+ * for deception rules (tripwires); undefined otherwise.
1110
+ */
1111
+ clearance?: string;
1112
+ /** Additional metadata */
1113
+ metadata?: Record<string, any>;
1114
+ /** Whether this was a dry run */
1115
+ dryRun: boolean;
1116
+ /** When the violation occurred (ISO 8601) */
1117
+ timestamp: string;
1118
+ }
1119
+ /**
1120
+ * IP enrichment data from the WebDecoy API
1121
+ */
1122
+ interface IPEnrichmentData {
1123
+ ip: string;
1124
+ security: {
1125
+ vpn: boolean;
1126
+ proxy: boolean;
1127
+ tor: boolean;
1128
+ relay: boolean;
1129
+ hosting: boolean;
1130
+ };
1131
+ location: {
1132
+ country: string;
1133
+ country_name: string;
1134
+ city: string;
1135
+ timezone: string;
1136
+ };
1137
+ network: {
1138
+ asn: number;
1139
+ asn_org: string;
1140
+ };
1141
+ reputation: {
1142
+ abuse_score: number;
1143
+ total_reports: number;
1144
+ is_high_risk: boolean;
1145
+ };
1146
+ categories: string[];
1147
+ }
1148
+ /**
1149
+ * Combined result from evaluating all rules
1150
+ */
1151
+ interface RuleEngineResult {
1152
+ /** Final action (first DENY/THROTTLE wins, or ALLOW) */
1153
+ action: 'ALLOW' | 'DENY' | 'THROTTLE';
1154
+ /** The rule that caused the action (null if all allowed) */
1155
+ rule?: string;
1156
+ /** Reason from the deciding rule */
1157
+ reason?: string;
1158
+ /** Metadata from the deciding rule */
1159
+ metadata?: Record<string, any>;
1160
+ /** All violations generated during evaluation */
1161
+ violations: ViolationEvent[];
1162
+ /**
1163
+ * Every configured rule and what it concluded, in evaluation order —
1164
+ * including the ones that allowed, dry-ran, or could not run. `violations`
1165
+ * only ever held the non-ALLOW subset.
1166
+ */
1167
+ results: RuleOutcome[];
1168
+ }
1169
+
1170
+ /**
1171
+ * Web Decoy API Client
1172
+ * Handles communication with the ingest service.
1173
+ *
1174
+ * Uses the Web-standard `fetch` API (no axios, no `node:` imports) so the SDK
1175
+ * runs in Node >= 18 and edge runtimes (Vercel Edge Middleware, Cloudflare
1176
+ * Workers) alike.
1177
+ */
1178
+
1179
+ interface ClientConfig {
1180
+ apiKey: string;
1181
+ apiUrl: string;
1182
+ timeout: number;
1183
+ debug: boolean;
1184
+ /**
1185
+ * Kept for API compatibility; the fetch transport does not support disabling
1186
+ * TLS verification. For local self-signed certs in Node, trust the CA
1187
+ * instead: `NODE_EXTRA_CA_CERTS=/path/to/ca.pem`.
1188
+ */
1189
+ tlsRejectUnauthorized: boolean;
1190
+ }
1191
+ declare class WebDecoyClient {
1192
+ private config;
1193
+ private baseUrl;
1194
+ private headers;
1195
+ constructor(config: ClientConfig);
1196
+ private request;
1197
+ /**
1198
+ * Send a detection request to the ingest service
1199
+ */
1200
+ detect(request: SDKDetectionRequest): Promise<SDKDetectionResponse>;
1201
+ /**
1202
+ * Send violation events to the ingest service
1203
+ */
1204
+ sendViolations(events: ViolationEvent[]): Promise<void>;
1205
+ /**
1206
+ * Get IP enrichment data from the ingest service
1207
+ */
1208
+ getIPEnrichment(ip: string): Promise<IPEnrichmentData | null>;
1209
+ /**
1210
+ * Validate the API key by making a test request
1211
+ */
1212
+ validateAPIKey(): Promise<boolean>;
1213
+ }
1214
+
1215
+ declare class WebDecoy {
1216
+ private client;
1217
+ private config;
1218
+ private ruleEngine;
1219
+ private violationReporter;
1220
+ private ipEnrichmentClient;
1221
+ private _hasFilterRules;
1222
+ private _hasAgentRules;
1223
+ private _preparingRules;
1224
+ private agentVerifier;
1225
+ private readonly webBotAuthOptions?;
1226
+ private readonly characteristics;
1227
+ /** Where diagnostics go. Never console directly — see logger.ts. */
1228
+ readonly log: Logger;
1229
+ private readonly decisionCache;
1230
+ constructor(config: WebDecoyConfig);
1231
+ /**
1232
+ * Evaluate rules against request metadata (synchronous).
1233
+ * Returns null if no rules are configured.
1234
+ */
1235
+ evaluateRules(metadata: RequestMetadata): RuleEngineResult | null;
1236
+ /**
1237
+ * Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
1238
+ * verification). Use this instead of evaluateRules() when filter rules or
1239
+ * webBotAuth() rules are present.
1240
+ */
1241
+ evaluateRulesAsync(metadata: RequestMetadata): Promise<RuleEngineResult | null>;
1242
+ /**
1243
+ * Register a rule after construction.
1244
+ *
1245
+ * For signals whose definition is not available synchronously — the site
1246
+ * honeytoken's path is derived by async HMAC, so the adapter arms it once the
1247
+ * derivation settles. Creates the engine if there was none, so an SDK built
1248
+ * with `rules: []` can still gain one.
1249
+ */
1250
+ addRule(rule: Rule): void;
1251
+ /** Build the base (synchronous) rule context from request metadata. */
1252
+ private buildContext;
1253
+ /**
1254
+ * Build a rule context with async signals resolved: IP enrichment (for
1255
+ * filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
1256
+ */
1257
+ private buildAsyncContext;
1258
+ /** Evaluate rules against a prepared context and report any violations. */
1259
+ private runRules;
1260
+ /** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
1261
+ private getAgentVerifier;
1262
+ /**
1263
+ * Verify a request's Web Bot Auth signature locally, deriving the request
1264
+ * URL/authority from its metadata. Returns undefined when the request lacks
1265
+ * the host information needed to verify (verdict is then simply absent).
1266
+ */
1267
+ private computeAgentVerdict;
1268
+ /**
1269
+ * Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
1270
+ * "web-bot-auth"). Returns whether it is a cryptographically `verified`
1271
+ * agent, an `impersonation` of a known one, an unverifiable `claimed`
1272
+ * signature, or `none`. No network on the warm path.
1273
+ *
1274
+ * Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
1275
+ * object (Node).
1276
+ *
1277
+ * @example
1278
+ * ```ts
1279
+ * const verdict = await webdecoy.detectBot(request);
1280
+ * if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
1281
+ * if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
1282
+ * ```
1283
+ */
1284
+ detectBot(request: AgentRequestInput): Promise<AgentVerdict>;
1285
+ /**
1286
+ * Whether this SDK instance has filter rules that need async enrichment
1287
+ */
1288
+ get hasFilterRules(): boolean;
1289
+ /**
1290
+ * Whether this SDK instance has Web Bot Auth rules that need async
1291
+ * verification before evaluation.
1292
+ */
1293
+ get hasAgentRules(): boolean;
1294
+ /**
1295
+ * Protect a request by checking it against Web Decoy's bot detection
1296
+ *
1297
+ * @param metadata - Request metadata to analyze
1298
+ * @param options - Optional configuration for this specific request
1299
+ * @returns The decision — `conclusion`, every rule's outcome, and the
1300
+ * narrowing helpers. Satisfies `ProtectResult`.
1301
+ */
1302
+ protect(metadata: RequestMetadata, options?: ProtectOptions): Promise<Decision>;
1303
+ private decide;
1304
+ /**
1305
+ * Report a test-trigger request and return a blocking verdict.
1306
+ *
1307
+ * The verdict is `allowed: false` so an enforce-mode adapter answers the
1308
+ * curl with a 403 — a visibly different response that tells the developer
1309
+ * their middleware acted, Arcjet-quickstart style. (The default monitor
1310
+ * mode still serves the request; the dashboard row is the real receipt.)
1311
+ *
1312
+ * Without an API key nothing can reach the dashboard, so the verdict says
1313
+ * so via `error` instead of pretending the test ran.
1314
+ */
1315
+ private reportTestTrigger;
1316
+ /**
1317
+ * Validate the API key configuration
1318
+ * Useful for testing integration during setup
1319
+ */
1320
+ validateConfig(): Promise<{
1321
+ valid: boolean;
1322
+ error?: string;
1323
+ }>;
1324
+ /**
1325
+ * Attach a violation reporter for sending violations to the backend.
1326
+ * Called internally when apiKey is present and rules are configured.
1327
+ */
1328
+ setViolationReporter(reporter: {
1329
+ report(violations: ViolationEvent[]): void;
1330
+ flush(): Promise<void>;
1331
+ destroy(): Promise<void>;
1332
+ }): void;
1333
+ /**
1334
+ * Get the API client (for use by violation reporter, enrichment, etc.)
1335
+ */
1336
+ getClient(): WebDecoyClient | null;
1337
+ /**
1338
+ * Get the current configuration
1339
+ */
1340
+ getConfig(): Readonly<typeof this.config>;
1341
+ /**
1342
+ * Clean up resources (timers, flush pending violations)
1343
+ */
1344
+ destroy(): Promise<void>;
1345
+ }
1346
+
1347
+ export { fromPino as $, type AgentCategory as A, type BotRuleConfig as B, type Characteristic as C, Decision as D, EDGE_CLASS_HEADER as E, type FilterConfig as F, type Logger as G, type ProtectResult as H, type IPEnrichmentData as I, type RequestMetadata as J, type RuleOutcome as K, type LocalAnalysis as L, MemoryRateLimitStore as M, type RuleState as N, type SDKDetectionRequest as O, type ProtectOptions as P, type SDKDetectionResponse as Q, type Rule as R, type SignedAgentDirectory as S, type TripwireConfig as T, type SyncRateLimitStore as U, type TLSInfo as V, WebDecoy as W, type ViolationEvent as X, classifyUserAgent as Y, consoleLogger as Z, deriveKey as _, type RuleContext as a, matchUserAgent as a0, newDecisionId as a1, readEdgeVerdict as a2, silentLogger as a3, type RuleResult as b, type WebDecoyConfig as c, type RuleEngineResult as d, type RateLimitConfig as e, type BotAgent as f, type BotCategory as g, type RateLimitStore as h, type RateLimitConsume as i, type RateLimitOutcome as j, type AgentVerifierOptions as k, type AgentRequestInput as l, type AgentVerdict as m, type AgentStatus as n, BOT_CATEGORIES as o, BOT_REGISTRY as p, type BotVerdict as q, type Conclusion as r, DEFAULT_CHARACTERISTICS as s, DecisionCache as t, type DecisionCacheOptions as u, type DecisionInit as v, EDGE_CLEARANCE_HEADER as w, type EdgeClass as x, type EdgeVerdict as y, type LogFields as z };