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