@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/README.md +1 -1
- package/dist/chunk-4QKKW7GN.mjs +3425 -0
- package/dist/index.d.mts +1102 -1469
- package/dist/index.d.ts +1102 -1469
- package/dist/index.js +1584 -615
- package/dist/index.mjs +358 -2726
- package/dist/sdk-qUjMf8ZX.d.mts +1404 -0
- package/dist/sdk-qUjMf8ZX.d.ts +1404 -0
- package/dist/testing.d.mts +85 -0
- package/dist/testing.d.ts +85 -0
- package/dist/testing.js +2324 -0
- package/dist/testing.mjs +113 -0
- package/package.json +8 -3
|
@@ -0,0 +1,1404 @@
|
|
|
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
|
+
* 175 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
|
+
* OpenTelemetry spans, without depending on OpenTelemetry.
|
|
556
|
+
*
|
|
557
|
+
* WHY INJECTED RATHER THAN IMPORTED
|
|
558
|
+
*
|
|
559
|
+
* An optional peer dependency was the obvious route and the wrong one. This
|
|
560
|
+
* package is dependency-free and passes an edge-compatibility gate, and most of
|
|
561
|
+
* the runtimes it targets — Workers, Vercel Edge — are exactly where a stray
|
|
562
|
+
* transitive import hurts. A conditional `import('@opentelemetry/api')` also
|
|
563
|
+
* bundles badly: the bundler either resolves it, adding weight for the majority
|
|
564
|
+
* who do not use it, or fails on a module that is legitimately absent.
|
|
565
|
+
*
|
|
566
|
+
* So the tracer is passed in. The interface below is a structural subset of
|
|
567
|
+
* OpenTelemetry's, which means `trace.getTracer('webdecoy')` satisfies it
|
|
568
|
+
* directly with no adapter:
|
|
569
|
+
*
|
|
570
|
+
* ```ts
|
|
571
|
+
* import { trace } from '@opentelemetry/api';
|
|
572
|
+
* new WebDecoy({ tracer: trace.getTracer('webdecoy') });
|
|
573
|
+
* ```
|
|
574
|
+
*
|
|
575
|
+
* An app that passes nothing gets no spans, no dependency, and no behaviour
|
|
576
|
+
* change — which is the majority, and they should not pay for this.
|
|
577
|
+
*/
|
|
578
|
+
/** A span, structurally compatible with OpenTelemetry's. */
|
|
579
|
+
interface Span {
|
|
580
|
+
setAttribute(key: string, value: string | number | boolean): unknown;
|
|
581
|
+
recordException?(error: unknown): unknown;
|
|
582
|
+
setStatus?(status: {
|
|
583
|
+
code: number;
|
|
584
|
+
message?: string;
|
|
585
|
+
}): unknown;
|
|
586
|
+
end(): unknown;
|
|
587
|
+
}
|
|
588
|
+
/** A tracer, structurally compatible with OpenTelemetry's. */
|
|
589
|
+
interface Tracer {
|
|
590
|
+
startSpan(name: string): Span;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* Web Decoy SDK Types
|
|
595
|
+
* Based on the ingest service API contract
|
|
596
|
+
*/
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Configuration options for the Web Decoy SDK
|
|
600
|
+
*/
|
|
601
|
+
interface WebDecoyConfig {
|
|
602
|
+
/**
|
|
603
|
+
* API key for authentication (sk_live_xxxxx format)
|
|
604
|
+
* Get this from your Web Decoy dashboard
|
|
605
|
+
* Optional — when omitted, SDK runs in local-only mode (rules still evaluate)
|
|
606
|
+
*/
|
|
607
|
+
apiKey?: string;
|
|
608
|
+
/**
|
|
609
|
+
* API URL for the Web Decoy ingest service. Server-to-server traffic
|
|
610
|
+
* fronts through Cloudflare at in.webdecoy.com; only the browser tag
|
|
611
|
+
* stays on the direct hostname.
|
|
612
|
+
* @default 'https://in.webdecoy.com'
|
|
613
|
+
*/
|
|
614
|
+
apiUrl?: string;
|
|
615
|
+
/**
|
|
616
|
+
* Enable TLS fingerprinting for advanced bot detection
|
|
617
|
+
* @default true
|
|
618
|
+
*/
|
|
619
|
+
enableTLSFingerprinting?: boolean;
|
|
620
|
+
/**
|
|
621
|
+
* Threat score threshold for blocking (0-100)
|
|
622
|
+
* Requests with scores above this will be blocked
|
|
623
|
+
* @default 80
|
|
624
|
+
*/
|
|
625
|
+
threatScoreThreshold?: number;
|
|
626
|
+
/**
|
|
627
|
+
* Timeout for API requests in milliseconds
|
|
628
|
+
* @default 5000
|
|
629
|
+
*/
|
|
630
|
+
timeout?: number;
|
|
631
|
+
/**
|
|
632
|
+
* Enable debug logging
|
|
633
|
+
* @default false
|
|
634
|
+
*/
|
|
635
|
+
debug?: boolean;
|
|
636
|
+
/**
|
|
637
|
+
* Whether to reject unauthorized TLS certificates
|
|
638
|
+
* Set to false for development/testing with self-signed certificates
|
|
639
|
+
* @default true
|
|
640
|
+
*/
|
|
641
|
+
tlsRejectUnauthorized?: boolean;
|
|
642
|
+
/**
|
|
643
|
+
* Rules to evaluate before calling the detection API
|
|
644
|
+
* Rules are evaluated in order; first DENY/THROTTLE wins
|
|
645
|
+
*/
|
|
646
|
+
rules?: Rule[];
|
|
647
|
+
/**
|
|
648
|
+
* Options for local Web Bot Auth agent verification (used by `detectBot()`
|
|
649
|
+
* and the `webBotAuth()` rule) — trusted directories, cache TTL, etc.
|
|
650
|
+
* Defaults are sensible; override only to curate your own agent allowlist.
|
|
651
|
+
*/
|
|
652
|
+
webBotAuth?: AgentVerifierOptions;
|
|
653
|
+
/**
|
|
654
|
+
* What counts as "the same caller" — the components of the key that keyed
|
|
655
|
+
* rules and the decision cache use.
|
|
656
|
+
*
|
|
657
|
+
* Defaults to `['ip']`. On an authenticated API the meaningful subject is
|
|
658
|
+
* usually not an address:
|
|
659
|
+
*
|
|
660
|
+
* ```ts
|
|
661
|
+
* characteristics: [(ctx) => ctx.headers['x-api-key']]
|
|
662
|
+
* ```
|
|
663
|
+
*
|
|
664
|
+
* A rule's own `keyBy` still wins over this. If a characteristic is absent on
|
|
665
|
+
* a request the key falls back to the IP rather than bucketing every such
|
|
666
|
+
* request together.
|
|
667
|
+
*/
|
|
668
|
+
characteristics?: Characteristic[];
|
|
669
|
+
/**
|
|
670
|
+
* Reuse of decisions that cost a network round trip. `false` disables it.
|
|
671
|
+
*
|
|
672
|
+
* Only server-derived DENY and CHALLENGE verdicts are cached — never ALLOW,
|
|
673
|
+
* and never a rule outcome, because a rate limiter has to see every request.
|
|
674
|
+
* @default { ttl: 60_000, max: 10_000 }
|
|
675
|
+
*/
|
|
676
|
+
decisionCache?: DecisionCacheOptions | false;
|
|
677
|
+
/**
|
|
678
|
+
* Where the SDK's diagnostics go. Defaults to `console`, gated on `debug` for
|
|
679
|
+
* everything below `warn`.
|
|
680
|
+
*
|
|
681
|
+
* Any object with `debug`/`info`/`warn`/`error` taking `(message, fields?)`
|
|
682
|
+
* works. For a pino-style logger, whose argument order is the other way
|
|
683
|
+
* round, wrap it with `fromPino()` — passing one directly type-checks and then
|
|
684
|
+
* silently drops every structured field.
|
|
685
|
+
*/
|
|
686
|
+
logger?: Logger;
|
|
687
|
+
/**
|
|
688
|
+
* An OpenTelemetry tracer, if you run one.
|
|
689
|
+
*
|
|
690
|
+
* Injected rather than imported so this package stays dependency-free and
|
|
691
|
+
* edge-safe. The interface is a structural subset of OpenTelemetry's, so
|
|
692
|
+
* `trace.getTracer('webdecoy')` works directly:
|
|
693
|
+
*
|
|
694
|
+
* ```ts
|
|
695
|
+
* new WebDecoy({ tracer: trace.getTracer('webdecoy') });
|
|
696
|
+
* ```
|
|
697
|
+
*
|
|
698
|
+
* Omit it and there are no spans, no dependency and no behaviour change.
|
|
699
|
+
*/
|
|
700
|
+
tracer?: Tracer;
|
|
701
|
+
}
|
|
702
|
+
/**
|
|
703
|
+
* TLS connection information from the request
|
|
704
|
+
*/
|
|
705
|
+
interface TLSInfo {
|
|
706
|
+
/** TLS version (e.g., 771 for TLS 1.2, 772 for TLS 1.3) */
|
|
707
|
+
version?: number;
|
|
708
|
+
/** List of cipher suites supported by the client */
|
|
709
|
+
cipher_suites?: number[];
|
|
710
|
+
/** List of TLS extensions */
|
|
711
|
+
extensions?: number[];
|
|
712
|
+
/** Elliptic curves supported */
|
|
713
|
+
supported_groups?: number[];
|
|
714
|
+
/** EC point formats */
|
|
715
|
+
ec_point_formats?: number[];
|
|
716
|
+
/** Signature algorithms */
|
|
717
|
+
signature_algorithms?: number[];
|
|
718
|
+
/** Server name indication */
|
|
719
|
+
server_name?: string;
|
|
720
|
+
/** ALPN protocols */
|
|
721
|
+
alpn_protocols?: string[];
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* Request metadata sent to the detection service
|
|
725
|
+
*/
|
|
726
|
+
interface RequestMetadata {
|
|
727
|
+
/** HTTP method (GET, POST, etc.) */
|
|
728
|
+
method: string;
|
|
729
|
+
/** Request path */
|
|
730
|
+
path: string;
|
|
731
|
+
/** Client IP address (REQUIRED) */
|
|
732
|
+
ip: string;
|
|
733
|
+
/** User-Agent header */
|
|
734
|
+
user_agent?: string;
|
|
735
|
+
/** All request headers */
|
|
736
|
+
headers: Record<string, string>;
|
|
737
|
+
/**
|
|
738
|
+
* Raw query string, without the leading `?`. Populated by the adapters.
|
|
739
|
+
* Read by `attackSignatures()`, which cannot see it via `path` — Express's
|
|
740
|
+
* `req.path` excludes the query, and that is where injection payloads live.
|
|
741
|
+
*/
|
|
742
|
+
query?: string;
|
|
743
|
+
/**
|
|
744
|
+
* Request body as text, when the application chooses to supply it. Never
|
|
745
|
+
* populated automatically: buffering a body the application has not already
|
|
746
|
+
* parsed would change its streaming behaviour.
|
|
747
|
+
*/
|
|
748
|
+
body?: string;
|
|
749
|
+
/** TLS connection information */
|
|
750
|
+
tls_info?: TLSInfo;
|
|
751
|
+
/** Request timestamp (Unix milliseconds) */
|
|
752
|
+
timestamp: number;
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Local analysis performed by the SDK
|
|
756
|
+
*/
|
|
757
|
+
interface LocalAnalysis {
|
|
758
|
+
/** True if suspicious headers detected */
|
|
759
|
+
suspicious_headers: boolean;
|
|
760
|
+
/** True if Sec-CH-UA header is missing */
|
|
761
|
+
missing_sec_ch_ua: boolean;
|
|
762
|
+
/** True if IP is from a known datacenter */
|
|
763
|
+
datacenter_ip: boolean;
|
|
764
|
+
/** Local threat score (0-100) */
|
|
765
|
+
local_score: number;
|
|
766
|
+
/** True if server-side verification is needed */
|
|
767
|
+
needs_verification: boolean;
|
|
768
|
+
/** Detection flags */
|
|
769
|
+
flags: string[];
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* Detection request sent to the ingest service
|
|
773
|
+
*/
|
|
774
|
+
interface SDKDetectionRequest {
|
|
775
|
+
request_metadata: RequestMetadata;
|
|
776
|
+
local_analysis: LocalAnalysis;
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* Detection response from the ingest service
|
|
780
|
+
*/
|
|
781
|
+
interface SDKDetectionResponse {
|
|
782
|
+
/** Decision: "allow", "block", or "challenge" */
|
|
783
|
+
decision: 'allow' | 'block' | 'challenge';
|
|
784
|
+
/** Confidence score (0-100) */
|
|
785
|
+
confidence: number;
|
|
786
|
+
/** Threat level classification */
|
|
787
|
+
threat_level: 'MINIMAL' | 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
|
|
788
|
+
/** True if a bot was detected */
|
|
789
|
+
bot_detected: boolean;
|
|
790
|
+
/** Type of bot detected (if any) */
|
|
791
|
+
bot_type?: string;
|
|
792
|
+
/** Unique detection ID */
|
|
793
|
+
detection_id: string;
|
|
794
|
+
/** True if a response rule was enforced */
|
|
795
|
+
rule_enforced: boolean;
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* Options for the protect() method
|
|
799
|
+
*/
|
|
800
|
+
interface ProtectOptions {
|
|
801
|
+
/** Custom threat score threshold for this request */
|
|
802
|
+
threshold?: number;
|
|
803
|
+
/** Skip local analysis and only use server-side detection */
|
|
804
|
+
skipLocalAnalysis?: boolean;
|
|
805
|
+
/** Additional metadata to include in the detection */
|
|
806
|
+
metadata?: Record<string, any>;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* What the SDK concluded about one request, and why.
|
|
811
|
+
*
|
|
812
|
+
* WHY THIS MODULE EXISTS
|
|
813
|
+
*
|
|
814
|
+
* `protect()` used to return `{ allowed, detection }` and the adapters typed the
|
|
815
|
+
* value they handed to `onBlocked` as `any`. A developer integrating us had to
|
|
816
|
+
* destructure a blob and string-match to find out which rule fired, and there
|
|
817
|
+
* was nowhere to put three things the SDK already knew:
|
|
818
|
+
*
|
|
819
|
+
* - **Which rules ran.** The engine collapsed to a single deciding rule plus a
|
|
820
|
+
* violations array, so a filter rule that never ran for want of enrichment was
|
|
821
|
+
* indistinguishable from one that ran and passed.
|
|
822
|
+
* - **"Challenge this one."** The captcha in `@webdecoy/client` had no verdict
|
|
823
|
+
* that could route to it, so it was reachable only by wiring it up by hand.
|
|
824
|
+
* - **A stable id.** `'rule_' + Date.now()` is not unique under concurrency and
|
|
825
|
+
* correlates with nothing in the dashboard.
|
|
826
|
+
*
|
|
827
|
+
* `allowed` still means exactly what it meant before, including failing open on
|
|
828
|
+
* ERROR, so existing middleware keeps working unchanged.
|
|
829
|
+
*/
|
|
830
|
+
|
|
831
|
+
/**
|
|
832
|
+
* The outcome of a decision.
|
|
833
|
+
*
|
|
834
|
+
* `ERROR` is not a synonym for `DENY`. It means the SDK could not reach a
|
|
835
|
+
* verdict — the detection call failed, the request was malformed — and the
|
|
836
|
+
* request is allowed through, because a security control that takes the site
|
|
837
|
+
* down when it has a bad day is worse than the traffic it was filtering.
|
|
838
|
+
*/
|
|
839
|
+
type Conclusion = 'ALLOW' | 'DENY' | 'CHALLENGE' | 'ERROR';
|
|
840
|
+
/**
|
|
841
|
+
* Whether a rule actually contributed to the decision.
|
|
842
|
+
*
|
|
843
|
+
* - `RUN` — evaluated, and its conclusion counts.
|
|
844
|
+
* - `DRY_RUN` — evaluated, and its conclusion is recorded but not enforced.
|
|
845
|
+
* - `NOT_RUN` — could not evaluate, because a signal it needs was absent. A
|
|
846
|
+
* filter rule with no IP enrichment, a Web Bot Auth rule on a request with no
|
|
847
|
+
* host. This is the state that used to be invisible: such a rule reported
|
|
848
|
+
* ALLOW, which reads as "checked and fine" rather than "never checked".
|
|
849
|
+
* - `CACHED` — not evaluated; a prior decision for this key was reused.
|
|
850
|
+
*/
|
|
851
|
+
type RuleState = 'RUN' | 'DRY_RUN' | 'NOT_RUN' | 'CACHED';
|
|
852
|
+
/** One rule's contribution to a decision. */
|
|
853
|
+
interface RuleOutcome {
|
|
854
|
+
/** The rule's name, e.g. `tripwire` or `rate-limit:100/60s`. */
|
|
855
|
+
rule: string;
|
|
856
|
+
state: RuleState;
|
|
857
|
+
conclusion: Conclusion;
|
|
858
|
+
/** The raw rule action, for rules that distinguish throttling from denial. */
|
|
859
|
+
action?: 'ALLOW' | 'DENY' | 'THROTTLE';
|
|
860
|
+
reason?: string;
|
|
861
|
+
metadata?: Record<string, unknown>;
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* The result of `protect()`.
|
|
865
|
+
*
|
|
866
|
+
* Kept as an interface separate from the class so that the shape is what
|
|
867
|
+
* consumers depend on. The class exists to carry the narrowing helpers.
|
|
868
|
+
*/
|
|
869
|
+
interface ProtectResult {
|
|
870
|
+
/** Unique id for this decision. Correlates with the dashboard. */
|
|
871
|
+
readonly id: string;
|
|
872
|
+
readonly conclusion: Conclusion;
|
|
873
|
+
/**
|
|
874
|
+
* Whether to serve the request.
|
|
875
|
+
*
|
|
876
|
+
* True for `ALLOW` and for `ERROR` (fail open); false for `DENY` and
|
|
877
|
+
* `CHALLENGE`. Unchanged from before the typed decision existed.
|
|
878
|
+
*/
|
|
879
|
+
readonly allowed: boolean;
|
|
880
|
+
/** Every rule that was configured, and what it concluded. */
|
|
881
|
+
readonly results: readonly RuleOutcome[];
|
|
882
|
+
/** The deciding reason, when there is one. */
|
|
883
|
+
readonly reason?: string;
|
|
884
|
+
/** Detection response from the service, or the locally-synthesised one. */
|
|
885
|
+
readonly detection: SDKDetectionResponse;
|
|
886
|
+
/** Error message when `conclusion` is `ERROR`. */
|
|
887
|
+
readonly error?: string;
|
|
888
|
+
/** The rule engine's raw result, for callers that were already using it. */
|
|
889
|
+
readonly ruleResult?: RuleEngineResult;
|
|
890
|
+
/**
|
|
891
|
+
* Web Bot Auth verdict, present when a `webBotAuth()` rule triggered local
|
|
892
|
+
* agent verification. Lets middleware treat a `verified` agent specially
|
|
893
|
+
* without re-verifying.
|
|
894
|
+
*/
|
|
895
|
+
readonly agent?: AgentVerdict;
|
|
896
|
+
/**
|
|
897
|
+
* What the edge validator said about this request, parsed from
|
|
898
|
+
* `x-wd-clearance` and `x-wd-class`.
|
|
899
|
+
*
|
|
900
|
+
* Always present. Check `edge.present` before branching: false means the edge
|
|
901
|
+
* did not front this request, which is no information rather than a clean
|
|
902
|
+
* bill of health.
|
|
903
|
+
*/
|
|
904
|
+
readonly edge?: EdgeVerdict;
|
|
905
|
+
/** The characteristic key this decision was made for. */
|
|
906
|
+
readonly key?: string;
|
|
907
|
+
/** How long this decision may be reused, in milliseconds. 0 means never. */
|
|
908
|
+
readonly ttl: number;
|
|
909
|
+
isAllowed(): boolean;
|
|
910
|
+
isDenied(): boolean;
|
|
911
|
+
isChallenged(): boolean;
|
|
912
|
+
isErrored(): boolean;
|
|
913
|
+
/** Whether a named rule denied the request. */
|
|
914
|
+
deniedBy(rule: string): boolean;
|
|
915
|
+
}
|
|
916
|
+
interface DecisionInit {
|
|
917
|
+
conclusion: Conclusion;
|
|
918
|
+
detection: SDKDetectionResponse;
|
|
919
|
+
results?: RuleOutcome[];
|
|
920
|
+
reason?: string;
|
|
921
|
+
error?: string;
|
|
922
|
+
ruleResult?: RuleEngineResult;
|
|
923
|
+
agent?: AgentVerdict;
|
|
924
|
+
edge?: EdgeVerdict;
|
|
925
|
+
key?: string;
|
|
926
|
+
ttl?: number;
|
|
927
|
+
id?: string;
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* A decision id.
|
|
931
|
+
*
|
|
932
|
+
* Random rather than sequential: ids leave the process (they go on the
|
|
933
|
+
* detection row and into customers' logs), and a counter would leak request
|
|
934
|
+
* volume to anyone who saw two of them.
|
|
935
|
+
*/
|
|
936
|
+
declare function newDecisionId(): string;
|
|
937
|
+
declare class Decision implements ProtectResult {
|
|
938
|
+
readonly id: string;
|
|
939
|
+
readonly conclusion: Conclusion;
|
|
940
|
+
readonly results: readonly RuleOutcome[];
|
|
941
|
+
readonly reason?: string;
|
|
942
|
+
readonly detection: SDKDetectionResponse;
|
|
943
|
+
readonly error?: string;
|
|
944
|
+
readonly ruleResult?: RuleEngineResult;
|
|
945
|
+
readonly agent?: AgentVerdict;
|
|
946
|
+
readonly edge?: EdgeVerdict;
|
|
947
|
+
readonly key?: string;
|
|
948
|
+
readonly ttl: number;
|
|
949
|
+
constructor(init: DecisionInit);
|
|
950
|
+
get allowed(): boolean;
|
|
951
|
+
isAllowed(): boolean;
|
|
952
|
+
isDenied(): boolean;
|
|
953
|
+
isChallenged(): boolean;
|
|
954
|
+
isErrored(): boolean;
|
|
955
|
+
deniedBy(rule: string): boolean;
|
|
956
|
+
/** A copy of this decision with the edge verdict attached. */
|
|
957
|
+
withEdge(edge: EdgeVerdict | undefined): Decision;
|
|
958
|
+
/** A copy marked as served from cache, with every rule re-stated as CACHED. */
|
|
959
|
+
asCached(): Decision;
|
|
960
|
+
private init;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/**
|
|
964
|
+
* Context available to rules during evaluation
|
|
965
|
+
*/
|
|
966
|
+
interface RuleContext {
|
|
967
|
+
/** Client IP address */
|
|
968
|
+
ip: string;
|
|
969
|
+
/** Request path */
|
|
970
|
+
path: string;
|
|
971
|
+
/** HTTP method */
|
|
972
|
+
method: string;
|
|
973
|
+
/** User-Agent string */
|
|
974
|
+
userAgent?: string;
|
|
975
|
+
/** Request headers (lowercase keys) */
|
|
976
|
+
headers: Record<string, string>;
|
|
977
|
+
/** Raw query string, without the leading `?`. */
|
|
978
|
+
query?: string;
|
|
979
|
+
/** Request body as text, when the application supplied one. */
|
|
980
|
+
body?: string;
|
|
981
|
+
/** Request timestamp */
|
|
982
|
+
timestamp: number;
|
|
983
|
+
/** IP enrichment data (populated async when available) */
|
|
984
|
+
enrichment?: IPEnrichmentData;
|
|
985
|
+
/**
|
|
986
|
+
* Web Bot Auth verdict (populated async before evaluation when a
|
|
987
|
+
* `webBotAuth` rule is
|
|
988
|
+
* present). Lets a synchronous rule act on cryptographic agent verification.
|
|
989
|
+
*/
|
|
990
|
+
agent?: AgentVerdict;
|
|
991
|
+
/**
|
|
992
|
+
* The edge validator's annotations on this request, parsed from
|
|
993
|
+
* `x-wd-clearance` and `x-wd-class`. Always populated — `present: false` when
|
|
994
|
+
* the edge did not front this request. Filter expressions read it as
|
|
995
|
+
* `edge.class`, `edge.clearance` and `edge.present`.
|
|
996
|
+
*/
|
|
997
|
+
edge?: EdgeVerdict;
|
|
998
|
+
/**
|
|
999
|
+
* Who the User-Agent says it is, matched against the generated agent
|
|
1000
|
+
* registry. Always populated — `known: false` when nothing matched. Filter
|
|
1001
|
+
* expressions read it as `bot.category`, `bot.name`, `bot.ai` and friends.
|
|
1002
|
+
*
|
|
1003
|
+
* A self-declared identity, so it is evidence about cooperative agents only.
|
|
1004
|
+
* See {@link BotVerdict}.
|
|
1005
|
+
*/
|
|
1006
|
+
bot?: BotVerdict;
|
|
1007
|
+
/**
|
|
1008
|
+
* The key identifying this caller, derived from the SDK's `characteristics`.
|
|
1009
|
+
* Keyed rules use it unless they were given their own `keyBy`. Defaults to
|
|
1010
|
+
* the IP, so a rule can read it unconditionally.
|
|
1011
|
+
*/
|
|
1012
|
+
key?: string;
|
|
1013
|
+
/**
|
|
1014
|
+
* Outcomes a rule resolved during the async pre-fetch, keyed by rule name.
|
|
1015
|
+
* Populated by {@link Rule.prepare}; read synchronously by `evaluate`.
|
|
1016
|
+
*/
|
|
1017
|
+
prepared?: Record<string, unknown>;
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* Result of evaluating a single rule
|
|
1021
|
+
*/
|
|
1022
|
+
interface RuleResult {
|
|
1023
|
+
/** Action to take */
|
|
1024
|
+
action: 'ALLOW' | 'DENY' | 'THROTTLE';
|
|
1025
|
+
/** Name of the rule that produced this result */
|
|
1026
|
+
rule: string;
|
|
1027
|
+
/** Human-readable reason */
|
|
1028
|
+
reason?: string;
|
|
1029
|
+
/** Additional metadata */
|
|
1030
|
+
metadata?: Record<string, any>;
|
|
1031
|
+
/**
|
|
1032
|
+
* Set by a rule that could not evaluate because a signal it needs was absent
|
|
1033
|
+
* — a filter rule with no IP enrichment, a Web Bot Auth rule on a request
|
|
1034
|
+
* with no host. Such a rule returns ALLOW, and without this the result is
|
|
1035
|
+
* indistinguishable from "checked and fine".
|
|
1036
|
+
*
|
|
1037
|
+
* Rules that ran leave this unset; the engine fills in `RUN` or `DRY_RUN`.
|
|
1038
|
+
*/
|
|
1039
|
+
state?: RuleState;
|
|
1040
|
+
}
|
|
1041
|
+
/**
|
|
1042
|
+
* A rule that can evaluate request context and produce a decision
|
|
1043
|
+
*/
|
|
1044
|
+
interface Rule {
|
|
1045
|
+
/** Unique name for this rule */
|
|
1046
|
+
name: string;
|
|
1047
|
+
/** Evaluate the rule against request context */
|
|
1048
|
+
evaluate(context: RuleContext): RuleResult;
|
|
1049
|
+
/**
|
|
1050
|
+
* Resolve anything this rule needs from the network before `evaluate` runs,
|
|
1051
|
+
* stashing it on `context.prepared`.
|
|
1052
|
+
*
|
|
1053
|
+
* `evaluate` is synchronous, and making it async would turn every rule
|
|
1054
|
+
* evaluation into a promise for the sake of the one rule that needs it. This
|
|
1055
|
+
* is the same pre-fetch the SDK already does for IP enrichment and Web Bot
|
|
1056
|
+
* Auth verdicts.
|
|
1057
|
+
*/
|
|
1058
|
+
prepare?(context: RuleContext): Promise<void>;
|
|
1059
|
+
/** Clean up resources (timers, etc.) */
|
|
1060
|
+
destroy?(): void;
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Configuration for rate limiting
|
|
1064
|
+
*/
|
|
1065
|
+
interface RateLimitConfig {
|
|
1066
|
+
/** Maximum requests allowed in the window */
|
|
1067
|
+
max: number;
|
|
1068
|
+
/** Window size in seconds */
|
|
1069
|
+
window: number;
|
|
1070
|
+
/** Algorithm: 'fixed' (default) or 'sliding' */
|
|
1071
|
+
algorithm?: 'fixed' | 'sliding';
|
|
1072
|
+
/** Custom key derivation function. Default: the SDK's characteristics, then IP */
|
|
1073
|
+
keyBy?: (context: RuleContext) => string;
|
|
1074
|
+
/**
|
|
1075
|
+
* Where the counters live. Defaults to this process's memory, which is
|
|
1076
|
+
* correct for a single process and wrong the moment you run two — the limit
|
|
1077
|
+
* becomes `max × instances` and resets on every cold start.
|
|
1078
|
+
*
|
|
1079
|
+
* Pass {@link upstashRateLimitStore} (or your own {@link RateLimitStore}) to
|
|
1080
|
+
* share counters across replicas.
|
|
1081
|
+
*/
|
|
1082
|
+
store?: RateLimitStore;
|
|
1083
|
+
/** Action when limit is exceeded: 'DENY' or 'THROTTLE' (default: 'THROTTLE') */
|
|
1084
|
+
action?: 'DENY' | 'THROTTLE';
|
|
1085
|
+
/** Dry run mode: log violations but don't block */
|
|
1086
|
+
dryRun?: boolean;
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Configuration for filter rules
|
|
1090
|
+
*/
|
|
1091
|
+
interface FilterConfig {
|
|
1092
|
+
/** Filter expression (e.g., 'ip.vpn or ip.tor') */
|
|
1093
|
+
expression: string;
|
|
1094
|
+
/** Action when filter matches: 'DENY' (default) or 'THROTTLE' */
|
|
1095
|
+
action?: 'DENY' | 'THROTTLE';
|
|
1096
|
+
/** Dry run mode: log violations but don't block */
|
|
1097
|
+
dryRun?: boolean;
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* Configuration for bot-category rules
|
|
1101
|
+
*/
|
|
1102
|
+
interface BotRuleConfig {
|
|
1103
|
+
/**
|
|
1104
|
+
* Categories to act on, e.g. `['training_crawler']`. Uses the same vocabulary
|
|
1105
|
+
* as the dashboard's `ai_scraper_category` column.
|
|
1106
|
+
*/
|
|
1107
|
+
categories?: BotCategory[];
|
|
1108
|
+
/** Specific agents by registry slug or display name, e.g. `['gptbot']`. */
|
|
1109
|
+
agents?: string[];
|
|
1110
|
+
/**
|
|
1111
|
+
* Act on every AI client — training crawlers, AI search crawlers, AI agents
|
|
1112
|
+
* and AI assistants.
|
|
1113
|
+
*/
|
|
1114
|
+
ai?: boolean;
|
|
1115
|
+
/**
|
|
1116
|
+
* Never act on these, whatever else matches. Applied last, so
|
|
1117
|
+
* `{ ai: true, allow: ['perplexitybot'] }` reads the way it looks.
|
|
1118
|
+
*/
|
|
1119
|
+
allow?: string[];
|
|
1120
|
+
/** Action when an agent matches: 'DENY' (default) or 'THROTTLE'. */
|
|
1121
|
+
action?: 'DENY' | 'THROTTLE';
|
|
1122
|
+
/** Log the violation but don't block. */
|
|
1123
|
+
dryRun?: boolean;
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* Configuration for tripwire (honeypot-path) rules
|
|
1127
|
+
*/
|
|
1128
|
+
interface TripwireConfig {
|
|
1129
|
+
/** Exact hidden honeypot paths (e.g. a honeytoken path or `/admin-backup.zip`). */
|
|
1130
|
+
paths?: string[];
|
|
1131
|
+
/** Path prefixes treated as tripwires (e.g. `/.git/`). */
|
|
1132
|
+
prefixes?: string[];
|
|
1133
|
+
/** Regex patterns for tripwire paths. */
|
|
1134
|
+
patterns?: RegExp[];
|
|
1135
|
+
/** Include the built-in scanner/scraper bait paths. Default `true`. */
|
|
1136
|
+
includeDefaults?: boolean;
|
|
1137
|
+
/** Action when a tripwire is hit: 'DENY' (default) or 'THROTTLE'. */
|
|
1138
|
+
action?: 'DENY' | 'THROTTLE';
|
|
1139
|
+
/** Dry run mode: log the violation but don't block. */
|
|
1140
|
+
dryRun?: boolean;
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* A violation event recorded when a rule triggers
|
|
1144
|
+
*/
|
|
1145
|
+
interface ViolationEvent {
|
|
1146
|
+
/** Rule that triggered */
|
|
1147
|
+
rule: string;
|
|
1148
|
+
/** Action taken */
|
|
1149
|
+
action: 'DENY' | 'THROTTLE' | 'ALLOW';
|
|
1150
|
+
/** Client IP */
|
|
1151
|
+
ip: string;
|
|
1152
|
+
/** Request path */
|
|
1153
|
+
path?: string;
|
|
1154
|
+
/** HTTP method */
|
|
1155
|
+
method?: string;
|
|
1156
|
+
/** User-Agent */
|
|
1157
|
+
userAgent?: string;
|
|
1158
|
+
/** Reason for the violation */
|
|
1159
|
+
reason?: string;
|
|
1160
|
+
/**
|
|
1161
|
+
* The request's wd_clearance token, when present. Lets the backend bind a
|
|
1162
|
+
* tripwire hit to the actor's device fingerprint and deny it — the same
|
|
1163
|
+
* durable lockout a decoy hit produces. Only carried
|
|
1164
|
+
* for deception rules (tripwires); undefined otherwise.
|
|
1165
|
+
*/
|
|
1166
|
+
clearance?: string;
|
|
1167
|
+
/** Additional metadata */
|
|
1168
|
+
metadata?: Record<string, any>;
|
|
1169
|
+
/** Whether this was a dry run */
|
|
1170
|
+
dryRun: boolean;
|
|
1171
|
+
/** When the violation occurred (ISO 8601) */
|
|
1172
|
+
timestamp: string;
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* IP enrichment data from the WebDecoy API
|
|
1176
|
+
*/
|
|
1177
|
+
interface IPEnrichmentData {
|
|
1178
|
+
ip: string;
|
|
1179
|
+
security: {
|
|
1180
|
+
vpn: boolean;
|
|
1181
|
+
proxy: boolean;
|
|
1182
|
+
tor: boolean;
|
|
1183
|
+
relay: boolean;
|
|
1184
|
+
hosting: boolean;
|
|
1185
|
+
};
|
|
1186
|
+
location: {
|
|
1187
|
+
country: string;
|
|
1188
|
+
country_name: string;
|
|
1189
|
+
city: string;
|
|
1190
|
+
timezone: string;
|
|
1191
|
+
};
|
|
1192
|
+
network: {
|
|
1193
|
+
asn: number;
|
|
1194
|
+
asn_org: string;
|
|
1195
|
+
};
|
|
1196
|
+
reputation: {
|
|
1197
|
+
abuse_score: number;
|
|
1198
|
+
total_reports: number;
|
|
1199
|
+
is_high_risk: boolean;
|
|
1200
|
+
};
|
|
1201
|
+
categories: string[];
|
|
1202
|
+
}
|
|
1203
|
+
/**
|
|
1204
|
+
* Combined result from evaluating all rules
|
|
1205
|
+
*/
|
|
1206
|
+
interface RuleEngineResult {
|
|
1207
|
+
/** Final action (first DENY/THROTTLE wins, or ALLOW) */
|
|
1208
|
+
action: 'ALLOW' | 'DENY' | 'THROTTLE';
|
|
1209
|
+
/** The rule that caused the action (null if all allowed) */
|
|
1210
|
+
rule?: string;
|
|
1211
|
+
/** Reason from the deciding rule */
|
|
1212
|
+
reason?: string;
|
|
1213
|
+
/** Metadata from the deciding rule */
|
|
1214
|
+
metadata?: Record<string, any>;
|
|
1215
|
+
/** All violations generated during evaluation */
|
|
1216
|
+
violations: ViolationEvent[];
|
|
1217
|
+
/**
|
|
1218
|
+
* Every configured rule and what it concluded, in evaluation order —
|
|
1219
|
+
* including the ones that allowed, dry-ran, or could not run. `violations`
|
|
1220
|
+
* only ever held the non-ALLOW subset.
|
|
1221
|
+
*/
|
|
1222
|
+
results: RuleOutcome[];
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
/**
|
|
1226
|
+
* Web Decoy API Client
|
|
1227
|
+
* Handles communication with the ingest service.
|
|
1228
|
+
*
|
|
1229
|
+
* Uses the Web-standard `fetch` API (no axios, no `node:` imports) so the SDK
|
|
1230
|
+
* runs in Node >= 18 and edge runtimes (Vercel Edge Middleware, Cloudflare
|
|
1231
|
+
* Workers) alike.
|
|
1232
|
+
*/
|
|
1233
|
+
|
|
1234
|
+
interface ClientConfig {
|
|
1235
|
+
apiKey: string;
|
|
1236
|
+
apiUrl: string;
|
|
1237
|
+
timeout: number;
|
|
1238
|
+
debug: boolean;
|
|
1239
|
+
/**
|
|
1240
|
+
* Kept for API compatibility; the fetch transport does not support disabling
|
|
1241
|
+
* TLS verification. For local self-signed certs in Node, trust the CA
|
|
1242
|
+
* instead: `NODE_EXTRA_CA_CERTS=/path/to/ca.pem`.
|
|
1243
|
+
*/
|
|
1244
|
+
tlsRejectUnauthorized: boolean;
|
|
1245
|
+
}
|
|
1246
|
+
declare class WebDecoyClient {
|
|
1247
|
+
private config;
|
|
1248
|
+
private baseUrl;
|
|
1249
|
+
private headers;
|
|
1250
|
+
constructor(config: ClientConfig);
|
|
1251
|
+
private request;
|
|
1252
|
+
/**
|
|
1253
|
+
* Send a detection request to the ingest service
|
|
1254
|
+
*/
|
|
1255
|
+
detect(request: SDKDetectionRequest): Promise<SDKDetectionResponse>;
|
|
1256
|
+
/**
|
|
1257
|
+
* Send violation events to the ingest service
|
|
1258
|
+
*/
|
|
1259
|
+
sendViolations(events: ViolationEvent[]): Promise<void>;
|
|
1260
|
+
/**
|
|
1261
|
+
* Get IP enrichment data from the ingest service
|
|
1262
|
+
*/
|
|
1263
|
+
getIPEnrichment(ip: string): Promise<IPEnrichmentData | null>;
|
|
1264
|
+
/**
|
|
1265
|
+
* Validate the API key by making a test request
|
|
1266
|
+
*/
|
|
1267
|
+
validateAPIKey(): Promise<boolean>;
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
declare class WebDecoy {
|
|
1271
|
+
private client;
|
|
1272
|
+
private config;
|
|
1273
|
+
private ruleEngine;
|
|
1274
|
+
private violationReporter;
|
|
1275
|
+
private ipEnrichmentClient;
|
|
1276
|
+
private _hasFilterRules;
|
|
1277
|
+
private _hasAgentRules;
|
|
1278
|
+
private _preparingRules;
|
|
1279
|
+
private agentVerifier;
|
|
1280
|
+
private readonly webBotAuthOptions?;
|
|
1281
|
+
private readonly characteristics;
|
|
1282
|
+
/** Where diagnostics go. Never console directly — see logger.ts. */
|
|
1283
|
+
readonly log: Logger;
|
|
1284
|
+
/** Optional OpenTelemetry tracer. Absent means no spans and no cost. */
|
|
1285
|
+
private readonly tracer?;
|
|
1286
|
+
private readonly decisionCache;
|
|
1287
|
+
constructor(config: WebDecoyConfig);
|
|
1288
|
+
/**
|
|
1289
|
+
* Evaluate rules against request metadata (synchronous).
|
|
1290
|
+
* Returns null if no rules are configured.
|
|
1291
|
+
*/
|
|
1292
|
+
evaluateRules(metadata: RequestMetadata): RuleEngineResult | null;
|
|
1293
|
+
/**
|
|
1294
|
+
* Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
|
|
1295
|
+
* verification). Use this instead of evaluateRules() when filter rules or
|
|
1296
|
+
* webBotAuth() rules are present.
|
|
1297
|
+
*/
|
|
1298
|
+
evaluateRulesAsync(metadata: RequestMetadata): Promise<RuleEngineResult | null>;
|
|
1299
|
+
/**
|
|
1300
|
+
* Register a rule after construction.
|
|
1301
|
+
*
|
|
1302
|
+
* For signals whose definition is not available synchronously — the site
|
|
1303
|
+
* honeytoken's path is derived by async HMAC, so the adapter arms it once the
|
|
1304
|
+
* derivation settles. Creates the engine if there was none, so an SDK built
|
|
1305
|
+
* with `rules: []` can still gain one.
|
|
1306
|
+
*/
|
|
1307
|
+
addRule(rule: Rule): void;
|
|
1308
|
+
/** Build the base (synchronous) rule context from request metadata. */
|
|
1309
|
+
private buildContext;
|
|
1310
|
+
/**
|
|
1311
|
+
* Build a rule context with async signals resolved: IP enrichment (for
|
|
1312
|
+
* filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
|
|
1313
|
+
*/
|
|
1314
|
+
private buildAsyncContext;
|
|
1315
|
+
/** Evaluate rules against a prepared context and report any violations. */
|
|
1316
|
+
private runRules;
|
|
1317
|
+
/** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
|
|
1318
|
+
private getAgentVerifier;
|
|
1319
|
+
/**
|
|
1320
|
+
* Verify a request's Web Bot Auth signature locally, deriving the request
|
|
1321
|
+
* URL/authority from its metadata. Returns undefined when the request lacks
|
|
1322
|
+
* the host information needed to verify (verdict is then simply absent).
|
|
1323
|
+
*/
|
|
1324
|
+
private computeAgentVerdict;
|
|
1325
|
+
/**
|
|
1326
|
+
* Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
|
|
1327
|
+
* "web-bot-auth"). Returns whether it is a cryptographically `verified`
|
|
1328
|
+
* agent, an `impersonation` of a known one, an unverifiable `claimed`
|
|
1329
|
+
* signature, or `none`. No network on the warm path.
|
|
1330
|
+
*
|
|
1331
|
+
* Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
|
|
1332
|
+
* object (Node).
|
|
1333
|
+
*
|
|
1334
|
+
* @example
|
|
1335
|
+
* ```ts
|
|
1336
|
+
* const verdict = await webdecoy.detectBot(request);
|
|
1337
|
+
* if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
|
|
1338
|
+
* if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
|
|
1339
|
+
* ```
|
|
1340
|
+
*/
|
|
1341
|
+
detectBot(request: AgentRequestInput): Promise<AgentVerdict>;
|
|
1342
|
+
/**
|
|
1343
|
+
* Whether this SDK instance has filter rules that need async enrichment
|
|
1344
|
+
*/
|
|
1345
|
+
get hasFilterRules(): boolean;
|
|
1346
|
+
/**
|
|
1347
|
+
* Whether this SDK instance has Web Bot Auth rules that need async
|
|
1348
|
+
* verification before evaluation.
|
|
1349
|
+
*/
|
|
1350
|
+
get hasAgentRules(): boolean;
|
|
1351
|
+
/**
|
|
1352
|
+
* Protect a request by checking it against Web Decoy's bot detection
|
|
1353
|
+
*
|
|
1354
|
+
* @param metadata - Request metadata to analyze
|
|
1355
|
+
* @param options - Optional configuration for this specific request
|
|
1356
|
+
* @returns The decision — `conclusion`, every rule's outcome, and the
|
|
1357
|
+
* narrowing helpers. Satisfies `ProtectResult`.
|
|
1358
|
+
*/
|
|
1359
|
+
protect(metadata: RequestMetadata, options?: ProtectOptions): Promise<Decision>;
|
|
1360
|
+
private decide;
|
|
1361
|
+
/**
|
|
1362
|
+
* Report a test-trigger request and return a blocking verdict.
|
|
1363
|
+
*
|
|
1364
|
+
* The verdict is `allowed: false` so an enforce-mode adapter answers the
|
|
1365
|
+
* curl with a 403 — a visibly different response that tells the developer
|
|
1366
|
+
* their middleware acted, Arcjet-quickstart style. (The default monitor
|
|
1367
|
+
* mode still serves the request; the dashboard row is the real receipt.)
|
|
1368
|
+
*
|
|
1369
|
+
* Without an API key nothing can reach the dashboard, so the verdict says
|
|
1370
|
+
* so via `error` instead of pretending the test ran.
|
|
1371
|
+
*/
|
|
1372
|
+
private reportTestTrigger;
|
|
1373
|
+
/**
|
|
1374
|
+
* Validate the API key configuration
|
|
1375
|
+
* Useful for testing integration during setup
|
|
1376
|
+
*/
|
|
1377
|
+
validateConfig(): Promise<{
|
|
1378
|
+
valid: boolean;
|
|
1379
|
+
error?: string;
|
|
1380
|
+
}>;
|
|
1381
|
+
/**
|
|
1382
|
+
* Attach a violation reporter for sending violations to the backend.
|
|
1383
|
+
* Called internally when apiKey is present and rules are configured.
|
|
1384
|
+
*/
|
|
1385
|
+
setViolationReporter(reporter: {
|
|
1386
|
+
report(violations: ViolationEvent[]): void;
|
|
1387
|
+
flush(): Promise<void>;
|
|
1388
|
+
destroy(): Promise<void>;
|
|
1389
|
+
}): void;
|
|
1390
|
+
/**
|
|
1391
|
+
* Get the API client (for use by violation reporter, enrichment, etc.)
|
|
1392
|
+
*/
|
|
1393
|
+
getClient(): WebDecoyClient | null;
|
|
1394
|
+
/**
|
|
1395
|
+
* Get the current configuration
|
|
1396
|
+
*/
|
|
1397
|
+
getConfig(): Readonly<typeof this.config>;
|
|
1398
|
+
/**
|
|
1399
|
+
* Clean up resources (timers, flush pending violations)
|
|
1400
|
+
*/
|
|
1401
|
+
destroy(): Promise<void>;
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
export { consoleLogger 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 LogFields as G, type Logger 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 ProtectResult as P, type SDKDetectionResponse as Q, type Rule as R, type SignedAgentDirectory as S, type TripwireConfig as T, type Span as U, type SyncRateLimitStore as V, WebDecoy as W, type TLSInfo as X, type Tracer as Y, type ViolationEvent as Z, classifyUserAgent as _, type RuleContext as a, deriveKey as a0, fromPino as a1, matchUserAgent as a2, newDecisionId as a3, readEdgeVerdict as a4, silentLogger as a5, type RuleResult as b, type RuleEngineResult as c, type RateLimitConfig as d, type BotAgent as e, type BotCategory as f, type RateLimitStore as g, type RateLimitConsume as h, type RateLimitOutcome as i, type WebDecoyConfig as j, type ProtectOptions as k, type AgentVerifierOptions as l, type AgentRequestInput as m, type AgentVerdict as n, type AgentStatus as o, BOT_CATEGORIES as p, BOT_REGISTRY as q, type BotVerdict as r, type Conclusion as s, DEFAULT_CHARACTERISTICS as t, DecisionCache as u, type DecisionCacheOptions as v, type DecisionInit as w, EDGE_CLEARANCE_HEADER as x, type EdgeClass as y, type EdgeVerdict as z };
|