@webdecoy/node 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2250 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/testing.ts
21
+ var testing_exports = {};
22
+ __export(testing_exports, {
23
+ botRequest: () => botRequest,
24
+ createTestHarness: () => createTestHarness,
25
+ expectAllowed: () => expectAllowed,
26
+ expectDenied: () => expectDenied,
27
+ expectRuleState: () => expectRuleState,
28
+ get: () => get,
29
+ post: () => post,
30
+ protectMany: () => protectMany,
31
+ request: () => request
32
+ });
33
+ module.exports = __toCommonJS(testing_exports);
34
+
35
+ // src/client.ts
36
+ var WebDecoyClient = class {
37
+ constructor(config) {
38
+ this.config = config;
39
+ this.baseUrl = config.apiUrl.replace(/\/+$/, "");
40
+ this.headers = {
41
+ "Content-Type": "application/json",
42
+ Authorization: `Bearer ${config.apiKey}`,
43
+ "User-Agent": "webdecoy-node-sdk/0.1.0"
44
+ };
45
+ if (config.tlsRejectUnauthorized === false && config.debug) {
46
+ console.warn(
47
+ "[WebDecoy] tlsRejectUnauthorized=false is not supported by the fetch transport and is ignored; for local self-signed certs, trust your CA via NODE_EXTRA_CA_CERTS=/path/to/ca.pem."
48
+ );
49
+ }
50
+ }
51
+ async request(method, path, body) {
52
+ const controller = new AbortController();
53
+ const timer = setTimeout(() => controller.abort(), this.config.timeout);
54
+ if (typeof timer.unref === "function") {
55
+ timer.unref();
56
+ }
57
+ if (this.config.debug) {
58
+ console.log("[WebDecoy] Request:", { method, url: this.baseUrl + path, data: body });
59
+ }
60
+ try {
61
+ const response = await fetch(this.baseUrl + path, {
62
+ method,
63
+ headers: this.headers,
64
+ body: body === void 0 ? void 0 : JSON.stringify(body),
65
+ signal: controller.signal
66
+ });
67
+ let data;
68
+ const text = await response.text();
69
+ if (text) {
70
+ try {
71
+ data = JSON.parse(text);
72
+ } catch {
73
+ data = void 0;
74
+ }
75
+ }
76
+ if (this.config.debug) {
77
+ console.log("[WebDecoy] Response:", { status: response.status, data });
78
+ }
79
+ return { status: response.status, data };
80
+ } catch (error) {
81
+ if (this.config.debug) {
82
+ console.error("[WebDecoy] Error:", {
83
+ message: error instanceof Error ? error.message : String(error)
84
+ });
85
+ }
86
+ throw error;
87
+ } finally {
88
+ clearTimeout(timer);
89
+ }
90
+ }
91
+ /**
92
+ * Send a detection request to the ingest service
93
+ */
94
+ async detect(request2) {
95
+ let response;
96
+ try {
97
+ response = await this.request(
98
+ "POST",
99
+ "/api/v1/sdk/detect",
100
+ request2
101
+ );
102
+ } catch (error) {
103
+ if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) {
104
+ throw new Error("Request timeout. The Web Decoy service did not respond in time.");
105
+ }
106
+ if (error instanceof TypeError) {
107
+ throw new Error("Unable to connect to Web Decoy service. Please check your network.");
108
+ }
109
+ throw error;
110
+ }
111
+ if (response.status === 401) {
112
+ throw new Error("Invalid API key. Please check your Web Decoy configuration.");
113
+ }
114
+ if (response.status === 429) {
115
+ throw new Error("Rate limit exceeded. Please try again later.");
116
+ }
117
+ if (response.status >= 400) {
118
+ if (response.data?.error || response.data?.message) {
119
+ throw new Error(response.data.error || response.data.message || "API error");
120
+ }
121
+ throw new Error(`API request failed: HTTP ${response.status}`);
122
+ }
123
+ return response.data;
124
+ }
125
+ /**
126
+ * Send violation events to the ingest service
127
+ */
128
+ async sendViolations(events) {
129
+ try {
130
+ await this.request("POST", "/api/v1/sdk/violations/batch", { events });
131
+ } catch (error) {
132
+ if (this.config.debug) {
133
+ console.error("[WebDecoy] Failed to send violations:", error);
134
+ }
135
+ }
136
+ }
137
+ /**
138
+ * Get IP enrichment data from the ingest service
139
+ */
140
+ async getIPEnrichment(ip) {
141
+ try {
142
+ const response = await this.request(
143
+ "GET",
144
+ `/api/v1/sdk/ip/${encodeURIComponent(ip)}/enrichment`
145
+ );
146
+ if (response.status >= 400) return null;
147
+ return response.data ?? null;
148
+ } catch (error) {
149
+ if (this.config.debug) {
150
+ console.error("[WebDecoy] Failed to get IP enrichment:", error);
151
+ }
152
+ return null;
153
+ }
154
+ }
155
+ /**
156
+ * Validate the API key by making a test request
157
+ */
158
+ async validateAPIKey() {
159
+ try {
160
+ const testRequest = {
161
+ request_metadata: {
162
+ method: "GET",
163
+ path: "/__webdecoy_test__",
164
+ ip: "127.0.0.1",
165
+ headers: {},
166
+ timestamp: Date.now()
167
+ },
168
+ local_analysis: {
169
+ suspicious_headers: false,
170
+ missing_sec_ch_ua: false,
171
+ datacenter_ip: false,
172
+ local_score: 0,
173
+ needs_verification: false,
174
+ flags: ["api_key_validation"]
175
+ }
176
+ };
177
+ await this.detect(testRequest);
178
+ return true;
179
+ } catch (error) {
180
+ if (error instanceof Error && error.message.includes("Invalid API key")) {
181
+ return false;
182
+ }
183
+ return true;
184
+ }
185
+ }
186
+ };
187
+
188
+ // src/local-analysis.ts
189
+ var DATACENTER_RANGES = [
190
+ // AWS
191
+ "3.0.0.0/8",
192
+ "13.0.0.0/8",
193
+ "18.0.0.0/8",
194
+ "52.0.0.0/8",
195
+ "54.0.0.0/8",
196
+ // Google Cloud
197
+ "34.0.0.0/8",
198
+ "35.0.0.0/8",
199
+ // Azure
200
+ "13.64.0.0/11",
201
+ "20.0.0.0/8",
202
+ "40.0.0.0/8",
203
+ "104.0.0.0/8",
204
+ // DigitalOcean
205
+ "159.65.0.0/16",
206
+ "178.62.0.0/16",
207
+ // Hetzner
208
+ "88.99.0.0/16",
209
+ "116.203.0.0/16"
210
+ ];
211
+ var SUSPICIOUS_PATTERNS = {
212
+ userAgents: [
213
+ /bot/i,
214
+ /crawler/i,
215
+ /spider/i,
216
+ /scraper/i,
217
+ /curl/i,
218
+ /wget/i,
219
+ /python/i,
220
+ /java/i,
221
+ /go-http-client/i,
222
+ /axios/i,
223
+ /okhttp/i
224
+ ],
225
+ missingHeaders: [
226
+ "accept",
227
+ "accept-language",
228
+ "accept-encoding"
229
+ ]
230
+ };
231
+ function isIPInRange(ip, cidr) {
232
+ const ipParts = ip.split(".").map(Number);
233
+ const [range, bits] = cidr.split("/");
234
+ const rangeParts = range.split(".").map(Number);
235
+ const mask = ~(2 ** (32 - parseInt(bits)) - 1);
236
+ const ipNum = (ipParts[0] << 24) + (ipParts[1] << 16) + (ipParts[2] << 8) + ipParts[3];
237
+ const rangeNum = (rangeParts[0] << 24) + (rangeParts[1] << 16) + (rangeParts[2] << 8) + rangeParts[3];
238
+ return (ipNum & mask) === (rangeNum & mask);
239
+ }
240
+ function isDatacenterIP(ip) {
241
+ if (ip.includes(":")) {
242
+ return false;
243
+ }
244
+ return DATACENTER_RANGES.some((range) => isIPInRange(ip, range));
245
+ }
246
+ function hasSuspiciousHeaders(metadata) {
247
+ const userAgent = metadata.user_agent || "";
248
+ const headers = metadata.headers || {};
249
+ const hasBotUA = SUSPICIOUS_PATTERNS.userAgents.some((pattern) => pattern.test(userAgent));
250
+ const missingCommonHeaders = SUSPICIOUS_PATTERNS.missingHeaders.filter(
251
+ (header) => !headers[header] && !headers[header.toLowerCase()]
252
+ );
253
+ return hasBotUA || missingCommonHeaders.length > 0;
254
+ }
255
+ function isMissingSecCHUA(metadata) {
256
+ const headers = metadata.headers || {};
257
+ return !headers["sec-ch-ua"] && !headers["Sec-CH-UA"];
258
+ }
259
+ function calculateLocalScore(suspiciousHeaders, missingSecCHUA, datacenterIP) {
260
+ let score = 0;
261
+ if (suspiciousHeaders) score += 30;
262
+ if (missingSecCHUA) score += 20;
263
+ if (datacenterIP) score += 40;
264
+ return Math.min(score, 100);
265
+ }
266
+ function needsVerification(localScore, hasTLSInfo) {
267
+ if (hasTLSInfo) {
268
+ return true;
269
+ }
270
+ return localScore >= 30;
271
+ }
272
+ function buildFlags(suspiciousHeaders, missingSecCHUA, datacenterIP, metadata) {
273
+ const flags = [];
274
+ if (suspiciousHeaders) {
275
+ flags.push("suspicious_headers");
276
+ }
277
+ if (missingSecCHUA) {
278
+ flags.push("missing_sec_ch_ua");
279
+ }
280
+ if (datacenterIP) {
281
+ flags.push("datacenter_ip");
282
+ }
283
+ const headerCount = Object.keys(metadata.headers || {}).length;
284
+ if (headerCount < 5) {
285
+ flags.push("minimal_headers");
286
+ }
287
+ if (!metadata.headers?.referer && !metadata.headers?.Referer) {
288
+ flags.push("missing_referer");
289
+ }
290
+ return flags;
291
+ }
292
+ function analyzeRequest(metadata) {
293
+ const suspiciousHeaders = hasSuspiciousHeaders(metadata);
294
+ const missingSecCHUA = isMissingSecCHUA(metadata);
295
+ const datacenterIP = isDatacenterIP(metadata.ip);
296
+ const localScore = calculateLocalScore(suspiciousHeaders, missingSecCHUA, datacenterIP);
297
+ const hasTLSInfo = Boolean(metadata.tls_info);
298
+ const needsVerify = needsVerification(localScore, hasTLSInfo);
299
+ const flags = buildFlags(suspiciousHeaders, missingSecCHUA, datacenterIP, metadata);
300
+ return {
301
+ suspicious_headers: suspiciousHeaders,
302
+ missing_sec_ch_ua: missingSecCHUA,
303
+ datacenter_ip: datacenterIP,
304
+ local_score: localScore,
305
+ needs_verification: needsVerify,
306
+ flags
307
+ };
308
+ }
309
+
310
+ // src/rules/rule-engine.ts
311
+ function extractClearance(headers) {
312
+ const cookie = headers["cookie"];
313
+ if (!cookie) return void 0;
314
+ for (const part of cookie.split(";")) {
315
+ const eq = part.indexOf("=");
316
+ if (eq < 0) continue;
317
+ if (part.slice(0, eq).trim() === "wd_clearance") {
318
+ return part.slice(eq + 1).trim() || void 0;
319
+ }
320
+ }
321
+ return void 0;
322
+ }
323
+ var RuleEngine = class {
324
+ constructor(rules) {
325
+ this.rules = rules;
326
+ }
327
+ /**
328
+ * Append a rule after construction.
329
+ *
330
+ * Exists for signals that cannot be known synchronously at construction —
331
+ * currently the site honeytoken, whose path is derived by async HMAC.
332
+ * Evaluation order is append order, matching the constructor.
333
+ */
334
+ add(rule) {
335
+ this.rules.push(rule);
336
+ }
337
+ /**
338
+ * Evaluate all rules against the request context.
339
+ * First DENY or THROTTLE result wins. Violations are recorded for all non-ALLOW results.
340
+ */
341
+ evaluate(context) {
342
+ const violations = [];
343
+ const results = [];
344
+ let decidingResult = null;
345
+ for (const rule of this.rules) {
346
+ const result = rule.evaluate(context);
347
+ const dryRun = result.metadata?.dryRun === true;
348
+ results.push({
349
+ rule: result.rule,
350
+ state: result.state ?? (dryRun ? "DRY_RUN" : "RUN"),
351
+ conclusion: dryRun || result.action !== "ALLOW" ? "DENY" : "ALLOW",
352
+ action: result.action,
353
+ reason: result.reason,
354
+ metadata: result.metadata
355
+ });
356
+ if (result.action !== "ALLOW") {
357
+ violations.push({
358
+ rule: result.rule,
359
+ action: result.action,
360
+ ip: context.ip,
361
+ path: context.path,
362
+ method: context.method,
363
+ userAgent: context.userAgent,
364
+ reason: result.reason,
365
+ clearance: result.rule === "tripwire" ? extractClearance(context.headers) : void 0,
366
+ metadata: result.metadata,
367
+ dryRun,
368
+ timestamp: new Date(context.timestamp).toISOString()
369
+ });
370
+ if (!decidingResult && !dryRun) {
371
+ decidingResult = result;
372
+ }
373
+ }
374
+ }
375
+ if (decidingResult) {
376
+ return {
377
+ action: decidingResult.action,
378
+ rule: decidingResult.rule,
379
+ reason: decidingResult.reason,
380
+ metadata: decidingResult.metadata,
381
+ violations,
382
+ results
383
+ };
384
+ }
385
+ return {
386
+ action: "ALLOW",
387
+ violations,
388
+ results
389
+ };
390
+ }
391
+ /**
392
+ * Clean up all rule resources
393
+ */
394
+ destroy() {
395
+ for (const rule of this.rules) {
396
+ rule.destroy?.();
397
+ }
398
+ }
399
+ };
400
+
401
+ // src/rules/tripwire-rule.ts
402
+ var DEFAULT_TRIPWIRE_PATHS = [
403
+ "/.git/config",
404
+ "/.git/HEAD",
405
+ "/.env",
406
+ "/.env.local",
407
+ "/.env.production",
408
+ "/wp-config.php",
409
+ "/config.php",
410
+ "/.aws/credentials",
411
+ "/.ssh/id_rsa",
412
+ "/backup.zip",
413
+ "/backup.sql",
414
+ "/database.sql",
415
+ "/dump.sql",
416
+ "/.DS_Store",
417
+ "/phpinfo.php",
418
+ "/server-status",
419
+ "/actuator/env",
420
+ "/.vscode/sftp.json"
421
+ ];
422
+ function normalizePath(path) {
423
+ return path.split("?")[0].split("#")[0];
424
+ }
425
+ var TripwireRule = class {
426
+ constructor(config = {}) {
427
+ this.name = "tripwire";
428
+ const paths = [...config.paths ?? []];
429
+ if (config.includeDefaults ?? true) paths.push(...DEFAULT_TRIPWIRE_PATHS);
430
+ this.exact = new Set(paths);
431
+ this.prefixes = config.prefixes ?? [];
432
+ this.patterns = config.patterns ?? [];
433
+ this.action = config.action ?? "DENY";
434
+ this.dryRun = config.dryRun ?? false;
435
+ }
436
+ evaluate(context) {
437
+ const path = normalizePath(context.path);
438
+ const hit = this.exact.has(path) || this.prefixes.some((prefix) => path.startsWith(prefix)) || this.patterns.some((re) => re.test(path));
439
+ if (hit) {
440
+ return {
441
+ action: this.dryRun ? "ALLOW" : this.action,
442
+ rule: this.name,
443
+ reason: `Tripwire hit: ${path} \u2014 hidden honeypot path, deterministic automated-intent signal`,
444
+ metadata: { path, dryRun: this.dryRun, confidence: 100 }
445
+ };
446
+ }
447
+ return { action: "ALLOW", rule: this.name };
448
+ }
449
+ };
450
+
451
+ // src/bots/registry.generated.ts
452
+ var BOT_REGISTRY = [
453
+ { id: "gptbot", name: "GPTBot", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["gptbot"] },
454
+ { id: "chatgpt-user", name: "ChatGPT-User", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["chatgpt-user", "chatgpt"] },
455
+ { id: "oai-searchbot", name: "OAI-SearchBot", category: "training_crawler", organization: "OpenAI", baseScore: 80, respectsRobots: true, uaPatterns: ["oai-searchbot"] },
456
+ { id: "claudebot", name: "ClaudeBot", category: "training_crawler", organization: "Anthropic", baseScore: 85, respectsRobots: true, uaPatterns: ["claudebot"] },
457
+ { id: "anthropic", name: "Anthropic", category: "training_crawler", organization: "Anthropic", baseScore: 85, respectsRobots: true, uaPatterns: ["anthropic"] },
458
+ { id: "ccbot", name: "CCBot", category: "training_crawler", organization: "Common Crawl", baseScore: 80, respectsRobots: true, uaPatterns: ["ccbot"] },
459
+ { id: "google-extended", name: "Google-Extended", category: "training_crawler", organization: "Google", baseScore: 80, respectsRobots: true, uaPatterns: ["google-extended"] },
460
+ { id: "bytespider", name: "ByteSpider", category: "training_crawler", organization: "ByteDance", baseScore: 75, respectsRobots: false, uaPatterns: ["bytespider"] },
461
+ { id: "amazonbot", name: "Amazonbot", category: "training_crawler", organization: "Amazon", baseScore: 70, respectsRobots: true, uaPatterns: ["amazonbot"] },
462
+ { id: "facebookbot", name: "FacebookBot", category: "training_crawler", organization: "Meta", baseScore: 70, respectsRobots: true, uaPatterns: ["facebookbot"] },
463
+ { id: "meta-externalagent", name: "Meta-ExternalAgent", category: "training_crawler", organization: "Meta", baseScore: 75, respectsRobots: true, uaPatterns: ["meta-externalagent"] },
464
+ { id: "cohere-ai", name: "Cohere", category: "training_crawler", organization: "Cohere", baseScore: 80, respectsRobots: true, uaPatterns: ["cohere-ai", "cohere"] },
465
+ { id: "perplexitybot", name: "PerplexityBot", category: "training_crawler", organization: "Perplexity AI", baseScore: 80, respectsRobots: true, uaPatterns: ["perplexitybot"] },
466
+ { id: "applebot-extended", name: "Applebot-Extended", category: "training_crawler", organization: "Apple", baseScore: 75, respectsRobots: true, uaPatterns: ["applebot-extended"] },
467
+ { id: "youbot", name: "YouBot", category: "training_crawler", organization: "You.com", baseScore: 75, respectsRobots: true, uaPatterns: ["youbot"] },
468
+ { id: "mistral", name: "MistralBot", category: "training_crawler", organization: "Mistral AI", baseScore: 80, respectsRobots: true, uaPatterns: ["mistral"] },
469
+ { id: "gemini", name: "Gemini", category: "training_crawler", organization: "Google", baseScore: 80, respectsRobots: true, uaPatterns: ["gemini"] },
470
+ { id: "ai2bot", name: "AI2Bot", category: "training_crawler", organization: "Allen Institute for AI", baseScore: 75, respectsRobots: true, uaPatterns: ["ai2bot"] },
471
+ { id: "deepseek", name: "DeepSeek", category: "training_crawler", organization: "DeepSeek", baseScore: 80, respectsRobots: true, uaPatterns: ["deepseek"] },
472
+ { id: "qwen", name: "Qwen", category: "training_crawler", organization: "Alibaba", baseScore: 75, respectsRobots: true, uaPatterns: ["qwen"] },
473
+ { id: "webzio", name: "Webz.io", category: "training_crawler", organization: "Webz.io", baseScore: 70, respectsRobots: false, uaPatterns: ["webzio"] },
474
+ { id: "sentibot", name: "Sentibot", category: "training_crawler", organization: "Sentibot", baseScore: 70, respectsRobots: false, uaPatterns: ["sentibot"] },
475
+ { id: "omgili", name: "Omgili", category: "training_crawler", organization: "Webz.io", baseScore: 70, respectsRobots: false, uaPatterns: ["omgili"] },
476
+ { id: "img2dataset", name: "img2dataset", category: "training_crawler", organization: "LAION", baseScore: 75, respectsRobots: false, uaPatterns: ["img2dataset"] },
477
+ { id: "timpibot", name: "Timpibot", category: "training_crawler", organization: "Timpi", baseScore: 70, respectsRobots: true, uaPatterns: ["timpibot"] },
478
+ { id: "velenpublicwebcrawler", name: "VelenPublicWebCrawler", category: "training_crawler", organization: "Velen", baseScore: 70, respectsRobots: false, uaPatterns: ["velenpublicwebcrawler"] },
479
+ { id: "isscyberriskcrawler", name: "ISSCyberRiskCrawler", category: "training_crawler", organization: "ISS", baseScore: 65, respectsRobots: false, uaPatterns: ["isscyberriskcrawler"] },
480
+ { id: "friendlycrawler", name: "FriendlyCrawler", category: "training_crawler", organization: "Unknown", baseScore: 65, respectsRobots: true, uaPatterns: ["friendlycrawler"] },
481
+ { id: "searchgpt", name: "SearchGPT", category: "ai_search_crawler", organization: "OpenAI", baseScore: 75, respectsRobots: true, uaPatterns: ["searchgpt"] },
482
+ { id: "phind", name: "Phind", category: "ai_search_crawler", organization: "Phind", baseScore: 70, respectsRobots: true, uaPatterns: ["phind"] },
483
+ { id: "kagi", name: "Kagi", category: "ai_search_crawler", organization: "Kagi", baseScore: 65, respectsRobots: true, uaPatterns: ["kagi"] },
484
+ { id: "exa", name: "Exa", category: "ai_search_crawler", organization: "Exa AI", baseScore: 70, respectsRobots: true, uaPatterns: ["exa.ai", "exabot"] },
485
+ { id: "metaphor", name: "Metaphor", category: "ai_search_crawler", organization: "Metaphor", baseScore: 70, respectsRobots: true, uaPatterns: ["metaphor"] },
486
+ { id: "tavily", name: "Tavily", category: "ai_search_crawler", organization: "Tavily", baseScore: 70, respectsRobots: true, uaPatterns: ["tavily"] },
487
+ { id: "brave-search", name: "BraveSearch", category: "ai_search_crawler", organization: "Brave", baseScore: 65, respectsRobots: true, uaPatterns: ["bravesearch"] },
488
+ { id: "neeva", name: "NeevaBot", category: "ai_search_crawler", organization: "Neeva", baseScore: 65, respectsRobots: true, uaPatterns: ["neevabot"] },
489
+ { id: "operator", name: "Operator", category: "ai_agent", organization: "OpenAI", baseScore: 75, respectsRobots: true, uaPatterns: ["operator"] },
490
+ { id: "claude-user", name: "Claude-User", category: "ai_agent", organization: "Anthropic", baseScore: 75, respectsRobots: true, uaPatterns: ["claude-user"] },
491
+ { id: "gemini-user", name: "Gemini-User", category: "ai_agent", organization: "Google", baseScore: 75, respectsRobots: true, uaPatterns: ["gemini-user"] },
492
+ { id: "googleagent-mariner", name: "GoogleAgent-Mariner", category: "ai_agent", organization: "Google", baseScore: 75, respectsRobots: true, uaPatterns: ["googleagent-mariner", "mariner"] },
493
+ { id: "amazon-buyforme", name: "AmazonBuyForMe", category: "ai_agent", organization: "Amazon", baseScore: 70, respectsRobots: true, uaPatterns: ["amazonbuyforme", "buyforme"] },
494
+ { id: "browser-use", name: "Browser-Use", category: "ai_agent", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["browser-use"] },
495
+ { id: "stagehand", name: "Stagehand", category: "ai_agent", organization: "Browserbase", baseScore: 70, respectsRobots: false, uaPatterns: ["stagehand"] },
496
+ { id: "multion", name: "MultiOn", category: "ai_agent", organization: "MultiOn", baseScore: 70, respectsRobots: false, uaPatterns: ["multion"] },
497
+ { id: "googlebot", name: "Googlebot", category: "search_crawler", organization: "Google", baseScore: 30, respectsRobots: true, uaPatterns: ["googlebot"] },
498
+ { id: "bingbot", name: "Bingbot", category: "search_crawler", organization: "Microsoft", baseScore: 30, respectsRobots: true, uaPatterns: ["bingbot"] },
499
+ { id: "yandexbot", name: "YandexBot", category: "search_crawler", organization: "Yandex", baseScore: 35, respectsRobots: true, uaPatterns: ["yandexbot"] },
500
+ { id: "baiduspider", name: "Baiduspider", category: "search_crawler", organization: "Baidu", baseScore: 40, respectsRobots: true, uaPatterns: ["baiduspider"] },
501
+ { id: "duckduckbot", name: "DuckDuckBot", category: "search_crawler", organization: "DuckDuckGo", baseScore: 30, respectsRobots: true, uaPatterns: ["duckduckbot"] },
502
+ { id: "applebot", name: "Applebot", category: "search_crawler", organization: "Apple", baseScore: 30, respectsRobots: true, uaPatterns: ["applebot"] },
503
+ { id: "sogou", name: "Sogou Spider", category: "search_crawler", organization: "Sogou", baseScore: 40, respectsRobots: true, uaPatterns: ["sogou"] },
504
+ { id: "qwantify", name: "Qwantify", category: "search_crawler", organization: "Qwant", baseScore: 35, respectsRobots: true, uaPatterns: ["qwantify"] },
505
+ { id: "naver", name: "Naver", category: "search_crawler", organization: "Naver", baseScore: 35, respectsRobots: true, uaPatterns: ["naver", "yeti"] },
506
+ { id: "seznam", name: "SeznamBot", category: "search_crawler", organization: "Seznam", baseScore: 35, respectsRobots: true, uaPatterns: ["seznambot"] },
507
+ { id: "ecosia", name: "Ecosia", category: "search_crawler", organization: "Ecosia", baseScore: 30, respectsRobots: true, uaPatterns: ["ecosia"] },
508
+ { id: "mojeek", name: "MojeekBot", category: "search_crawler", organization: "Mojeek", baseScore: 35, respectsRobots: true, uaPatterns: ["mojeekbot"] },
509
+ { id: "yahoo-slurp", name: "Yahoo! Slurp", category: "search_crawler", organization: "Yahoo", baseScore: 30, respectsRobots: true, uaPatterns: ["slurp"] },
510
+ { id: "ahrefsbot", name: "AhrefsBot", category: "seo_crawler", organization: "Ahrefs", baseScore: 50, respectsRobots: true, uaPatterns: ["ahrefsbot", "ahrefs"] },
511
+ { id: "semrushbot", name: "SemrushBot", category: "seo_crawler", organization: "Semrush", baseScore: 50, respectsRobots: true, uaPatterns: ["semrushbot", "semrush"] },
512
+ { id: "mj12bot", name: "MJ12bot", category: "seo_crawler", organization: "Majestic", baseScore: 50, respectsRobots: true, uaPatterns: ["mj12bot"] },
513
+ { id: "dotbot", name: "DotBot", category: "seo_crawler", organization: "Moz", baseScore: 50, respectsRobots: true, uaPatterns: ["dotbot"] },
514
+ { id: "rogerbot", name: "Rogerbot", category: "seo_crawler", organization: "Moz", baseScore: 50, respectsRobots: true, uaPatterns: ["rogerbot"] },
515
+ { id: "screaming-frog", name: "Screaming Frog", category: "seo_crawler", organization: "Screaming Frog", baseScore: 55, respectsRobots: true, uaPatterns: ["screaming frog"] },
516
+ { id: "sitebulb", name: "Sitebulb", category: "seo_crawler", organization: "Sitebulb", baseScore: 55, respectsRobots: true, uaPatterns: ["sitebulb"] },
517
+ { id: "deepcrawl", name: "DeepCrawl", category: "seo_crawler", organization: "Lumar", baseScore: 50, respectsRobots: true, uaPatterns: ["deepcrawl"] },
518
+ { id: "oncrawl", name: "OnCrawl", category: "seo_crawler", organization: "OnCrawl", baseScore: 50, respectsRobots: true, uaPatterns: ["oncrawl"] },
519
+ { id: "botify", name: "Botify", category: "seo_crawler", organization: "Botify", baseScore: 50, respectsRobots: true, uaPatterns: ["botify"] },
520
+ { id: "contentking", name: "ContentKing", category: "seo_crawler", organization: "ContentKing", baseScore: 50, respectsRobots: true, uaPatterns: ["contentking"] },
521
+ { id: "sistrix", name: "SISTRIX", category: "seo_crawler", organization: "SISTRIX", baseScore: 50, respectsRobots: true, uaPatterns: ["sistrix"] },
522
+ { id: "serpstat", name: "Serpstat", category: "seo_crawler", organization: "Serpstat", baseScore: 50, respectsRobots: true, uaPatterns: ["serpstat"] },
523
+ { id: "spyfu", name: "SpyFu", category: "seo_crawler", organization: "SpyFu", baseScore: 50, respectsRobots: true, uaPatterns: ["spyfu"] },
524
+ { id: "nessus", name: "Nessus", category: "security_scanner", organization: "Tenable", baseScore: 70, respectsRobots: false, uaPatterns: ["nessus"] },
525
+ { id: "qualys", name: "Qualys", category: "security_scanner", organization: "Qualys", baseScore: 70, respectsRobots: false, uaPatterns: ["qualys"] },
526
+ { id: "shodan", name: "Shodan", category: "security_scanner", organization: "Shodan", baseScore: 75, respectsRobots: false, uaPatterns: ["shodan"] },
527
+ { id: "censys", name: "Censys", category: "security_scanner", organization: "Censys", baseScore: 75, respectsRobots: false, uaPatterns: ["censys"] },
528
+ { id: "nmap", name: "Nmap", category: "security_scanner", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["nmap"] },
529
+ { id: "zap", name: "OWASP ZAP", category: "security_scanner", organization: "OWASP", baseScore: 70, respectsRobots: false, uaPatterns: ["zap/"] },
530
+ { id: "burp", name: "Burp Suite", category: "security_scanner", organization: "PortSwigger", baseScore: 70, respectsRobots: false, uaPatterns: ["burp"] },
531
+ { id: "nikto", name: "Nikto", category: "security_scanner", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["nikto"] },
532
+ { id: "nuclei", name: "Nuclei", category: "security_scanner", organization: "ProjectDiscovery", baseScore: 70, respectsRobots: false, uaPatterns: ["nuclei"] },
533
+ { id: "acunetix", name: "Acunetix", category: "security_scanner", organization: "Invicti", baseScore: 70, respectsRobots: false, uaPatterns: ["acunetix"] },
534
+ { id: "netsparker", name: "Netsparker", category: "security_scanner", organization: "Invicti", baseScore: 70, respectsRobots: false, uaPatterns: ["netsparker"] },
535
+ { id: "detectify", name: "Detectify", category: "security_scanner", organization: "Detectify", baseScore: 65, respectsRobots: false, uaPatterns: ["detectify"] },
536
+ { id: "intruder", name: "Intruder", category: "security_scanner", organization: "Intruder", baseScore: 65, respectsRobots: false, uaPatterns: ["intruder"] },
537
+ { id: "python-requests", name: "Python-Requests", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["python-requests"] },
538
+ { id: "python-urllib", name: "Python-urllib", category: "generic_scraper", organization: "Python", baseScore: 55, respectsRobots: false, uaPatterns: ["python-urllib"] },
539
+ { id: "python", name: "Python", category: "generic_scraper", organization: "Python", baseScore: 50, respectsRobots: false, uaPatterns: ["python/"] },
540
+ { id: "scrapy", name: "Scrapy", category: "generic_scraper", organization: "Scrapy", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapy"] },
541
+ { id: "httpx", name: "HTTPX", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["httpx"] },
542
+ { id: "aiohttp", name: "aiohttp", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["aiohttp"] },
543
+ { id: "beautifulsoup", name: "BeautifulSoup", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["beautifulsoup"] },
544
+ { id: "node-fetch", name: "node-fetch", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["node-fetch"] },
545
+ { id: "axios", name: "Axios", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["axios/"] },
546
+ { id: "got", name: "Got", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["got/"] },
547
+ { id: "undici", name: "Undici", category: "generic_scraper", organization: "Node.js", baseScore: 55, respectsRobots: false, uaPatterns: ["undici"] },
548
+ { id: "go-http-client", name: "Go-HTTP-Client", category: "generic_scraper", organization: "Go", baseScore: 55, respectsRobots: false, uaPatterns: ["go-http-client"] },
549
+ { id: "colly", name: "Colly", category: "generic_scraper", organization: "Open Source", baseScore: 65, respectsRobots: true, uaPatterns: ["colly"] },
550
+ { id: "java", name: "Java", category: "generic_scraper", organization: "Oracle", baseScore: 50, respectsRobots: false, uaPatterns: ["java/"] },
551
+ { id: "okhttp", name: "OkHttp", category: "generic_scraper", organization: "Square", baseScore: 55, respectsRobots: false, uaPatterns: ["okhttp"] },
552
+ { id: "apache-httpclient", name: "Apache-HttpClient", category: "generic_scraper", organization: "Apache", baseScore: 55, respectsRobots: false, uaPatterns: ["apache-httpclient"] },
553
+ { id: "jsoup", name: "Jsoup", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["jsoup"] },
554
+ { id: "guzzlehttp", name: "GuzzleHttp", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["guzzlehttp"] },
555
+ { id: "php", name: "PHP", category: "generic_scraper", organization: "PHP", baseScore: 50, respectsRobots: false, uaPatterns: ["php/"] },
556
+ { id: "ruby", name: "Ruby", category: "generic_scraper", organization: "Ruby", baseScore: 50, respectsRobots: false, uaPatterns: ["ruby"] },
557
+ { id: "faraday", name: "Faraday", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["faraday"] },
558
+ { id: "mechanize", name: "Mechanize", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["mechanize"] },
559
+ { id: "headlesschrome", name: "HeadlessChrome", category: "headless_browser", organization: "Google", baseScore: 70, respectsRobots: false, uaPatterns: ["headlesschrome"] },
560
+ { id: "puppeteer", name: "Puppeteer", category: "headless_browser", organization: "Google", baseScore: 70, respectsRobots: false, uaPatterns: ["puppeteer"] },
561
+ { id: "playwright", name: "Playwright", category: "headless_browser", organization: "Microsoft", baseScore: 70, respectsRobots: false, uaPatterns: ["playwright"] },
562
+ { id: "selenium", name: "Selenium", category: "headless_browser", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["selenium"] },
563
+ { id: "phantomjs", name: "PhantomJS", category: "headless_browser", organization: "Open Source", baseScore: 75, respectsRobots: false, uaPatterns: ["phantomjs"] },
564
+ { id: "splash", name: "Splash", category: "headless_browser", organization: "Scrapinghub", baseScore: 70, respectsRobots: false, uaPatterns: ["splash"] },
565
+ { id: "browserless", name: "Browserless", category: "headless_browser", organization: "Browserless", baseScore: 65, respectsRobots: false, uaPatterns: ["browserless"] },
566
+ { id: "browserbase", name: "Browserbase", category: "headless_browser", organization: "Browserbase", baseScore: 65, respectsRobots: false, uaPatterns: ["browserbase"] },
567
+ { id: "ia-archiver", name: "Internet Archive", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["ia_archiver"] },
568
+ { id: "archive-org-bot", name: "Archive.org", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["archive.org_bot"] },
569
+ { id: "wayback", name: "Wayback Machine", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["wayback"] },
570
+ { id: "heritrix", name: "Heritrix", category: "archiver", organization: "Internet Archive", baseScore: 30, respectsRobots: true, uaPatterns: ["heritrix"] },
571
+ { id: "brozzler", name: "Brozzler", category: "archiver", organization: "Internet Archive", baseScore: 30, respectsRobots: true, uaPatterns: ["brozzler"] },
572
+ { id: "facebookexternalhit", name: "Facebook", category: "fetcher", organization: "Meta", baseScore: 25, respectsRobots: true, uaPatterns: ["facebookexternalhit"] },
573
+ { id: "twitterbot", name: "Twitterbot", category: "fetcher", organization: "X Corp", baseScore: 25, respectsRobots: true, uaPatterns: ["twitterbot"] },
574
+ { id: "linkedinbot", name: "LinkedInBot", category: "fetcher", organization: "LinkedIn", baseScore: 25, respectsRobots: true, uaPatterns: ["linkedinbot"] },
575
+ { id: "slackbot", name: "Slackbot", category: "fetcher", organization: "Slack", baseScore: 25, respectsRobots: true, uaPatterns: ["slackbot"] },
576
+ { id: "telegrambot", name: "TelegramBot", category: "fetcher", organization: "Telegram", baseScore: 25, respectsRobots: true, uaPatterns: ["telegrambot"] },
577
+ { id: "whatsapp", name: "WhatsApp", category: "fetcher", organization: "Meta", baseScore: 25, respectsRobots: true, uaPatterns: ["whatsapp"] },
578
+ { id: "discordbot", name: "Discordbot", category: "fetcher", organization: "Discord", baseScore: 25, respectsRobots: true, uaPatterns: ["discordbot"] },
579
+ { id: "pinterestbot", name: "Pinterest", category: "fetcher", organization: "Pinterest", baseScore: 30, respectsRobots: true, uaPatterns: ["pinterest"] },
580
+ { id: "tumblr", name: "Tumblr", category: "fetcher", organization: "Automattic", baseScore: 30, respectsRobots: true, uaPatterns: ["tumblr"] },
581
+ { id: "reddit", name: "Reddit", category: "fetcher", organization: "Reddit", baseScore: 30, respectsRobots: true, uaPatterns: ["reddit"] },
582
+ { id: "embedly", name: "Embedly", category: "fetcher", organization: "Medium", baseScore: 30, respectsRobots: true, uaPatterns: ["embedly"] },
583
+ { id: "iframely", name: "Iframely", category: "fetcher", organization: "Iframely", baseScore: 30, respectsRobots: true, uaPatterns: ["iframely"] },
584
+ { id: "curl", name: "cURL", category: "fetcher", organization: "Open Source", baseScore: 45, respectsRobots: false, uaPatterns: ["curl/"] },
585
+ { id: "wget", name: "Wget", category: "fetcher", organization: "GNU", baseScore: 45, respectsRobots: false, uaPatterns: ["wget/"] },
586
+ { id: "libwww-perl", name: "libwww-perl", category: "fetcher", organization: "Perl", baseScore: 50, respectsRobots: false, uaPatterns: ["libwww-perl"] },
587
+ { id: "lwp", name: "LWP", category: "fetcher", organization: "Perl", baseScore: 50, respectsRobots: false, uaPatterns: ["lwp-"] },
588
+ { id: "httrack", name: "HTTrack", category: "fetcher", organization: "Open Source", baseScore: 60, respectsRobots: true, uaPatterns: ["httrack"] },
589
+ { id: "webdecoybot", name: "WebDecoyBot", category: "monitoring", organization: "WebDecoy", baseScore: 5, respectsRobots: true, uaPatterns: ["webdecoybot"] },
590
+ { id: "uptimerobot", name: "UptimeRobot", category: "monitoring", organization: "UptimeRobot", baseScore: 20, respectsRobots: true, uaPatterns: ["uptimerobot"] },
591
+ { id: "pingdom", name: "Pingdom", category: "monitoring", organization: "SolarWinds", baseScore: 20, respectsRobots: true, uaPatterns: ["pingdom"] },
592
+ { id: "statuscake", name: "StatusCake", category: "monitoring", organization: "StatusCake", baseScore: 20, respectsRobots: true, uaPatterns: ["statuscake"] },
593
+ { id: "better-uptime", name: "Better Uptime", category: "monitoring", organization: "Better Stack", baseScore: 20, respectsRobots: true, uaPatterns: ["betteruptime"] },
594
+ { id: "datadog-synthetics", name: "Datadog Synthetics", category: "monitoring", organization: "Datadog", baseScore: 25, respectsRobots: true, uaPatterns: ["datadog"] },
595
+ { id: "newrelic", name: "New Relic", category: "monitoring", organization: "New Relic", baseScore: 25, respectsRobots: true, uaPatterns: ["newrelic"] },
596
+ { id: "site24x7", name: "Site24x7", category: "monitoring", organization: "Zoho", baseScore: 20, respectsRobots: true, uaPatterns: ["site24x7"] },
597
+ { id: "freshping", name: "Freshping", category: "monitoring", organization: "Freshworks", baseScore: 20, respectsRobots: true, uaPatterns: ["freshping"] },
598
+ { id: "hetrixtools", name: "HetrixTools", category: "monitoring", organization: "HetrixTools", baseScore: 20, respectsRobots: true, uaPatterns: ["hetrixtools"] },
599
+ { id: "nodeping", name: "NodePing", category: "monitoring", organization: "NodePing", baseScore: 20, respectsRobots: true, uaPatterns: ["nodeping"] },
600
+ { id: "feedly", name: "Feedly", category: "feed_reader", organization: "Feedly", baseScore: 25, respectsRobots: true, uaPatterns: ["feedly"] },
601
+ { id: "newsblur", name: "NewsBlur", category: "feed_reader", organization: "NewsBlur", baseScore: 25, respectsRobots: true, uaPatterns: ["newsblur"] },
602
+ { id: "inoreader", name: "Inoreader", category: "feed_reader", organization: "Inoreader", baseScore: 25, respectsRobots: true, uaPatterns: ["inoreader"] },
603
+ { id: "theoldreader", name: "The Old Reader", category: "feed_reader", organization: "The Old Reader", baseScore: 25, respectsRobots: true, uaPatterns: ["theoldreader"] },
604
+ { id: "feedbin", name: "Feedbin", category: "feed_reader", organization: "Feedbin", baseScore: 25, respectsRobots: true, uaPatterns: ["feedbin"] },
605
+ { id: "miniflux", name: "Miniflux", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["miniflux"] },
606
+ { id: "freshrss", name: "FreshRSS", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["freshrss"] },
607
+ { id: "commafeed", name: "CommaFeed", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["commafeed"] },
608
+ { id: "diffbot", name: "Diffbot", category: "commercial_scraper", organization: "Diffbot", baseScore: 70, respectsRobots: true, uaPatterns: ["diffbot"] },
609
+ { id: "import-io", name: "Import.io", category: "commercial_scraper", organization: "Import.io", baseScore: 65, respectsRobots: true, uaPatterns: ["import.io"] },
610
+ { id: "bright-data", name: "Bright Data", category: "commercial_scraper", organization: "Bright Data", baseScore: 70, respectsRobots: false, uaPatterns: ["brightdata", "luminati"] },
611
+ { id: "oxylabs", name: "Oxylabs", category: "commercial_scraper", organization: "Oxylabs", baseScore: 70, respectsRobots: false, uaPatterns: ["oxylabs"] },
612
+ { id: "scrapingbee", name: "ScrapingBee", category: "commercial_scraper", organization: "ScrapingBee", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapingbee"] },
613
+ { id: "scrapingant", name: "ScrapingAnt", category: "commercial_scraper", organization: "ScrapingAnt", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapingant"] },
614
+ { id: "zyte", name: "Zyte", category: "commercial_scraper", organization: "Zyte", baseScore: 65, respectsRobots: true, uaPatterns: ["zyte", "scrapinghub"] },
615
+ { id: "apify", name: "Apify", category: "commercial_scraper", organization: "Apify", baseScore: 65, respectsRobots: true, uaPatterns: ["apify"] },
616
+ { id: "crawlbase", name: "Crawlbase", category: "commercial_scraper", organization: "Crawlbase", baseScore: 65, respectsRobots: true, uaPatterns: ["crawlbase"] },
617
+ { id: "webscrapingapi", name: "WebScrapingAPI", category: "commercial_scraper", organization: "WebScrapingAPI", baseScore: 65, respectsRobots: true, uaPatterns: ["webscrapingapi"] },
618
+ { id: "gemini-deep-research", name: "Gemini-Deep-Research", category: "ai_assistant", organization: "Google", baseScore: 65, respectsRobots: true, uaPatterns: ["gemini-deep-research"] },
619
+ { id: "copilot", name: "Microsoft Copilot", category: "ai_assistant", organization: "Microsoft", baseScore: 65, respectsRobots: true, uaPatterns: ["copilot"] },
620
+ { id: "cortana", name: "Cortana", category: "ai_assistant", organization: "Microsoft", baseScore: 60, respectsRobots: true, uaPatterns: ["cortana"] },
621
+ { id: "siri", name: "Siri", category: "ai_assistant", organization: "Apple", baseScore: 60, respectsRobots: true, uaPatterns: ["siri"] }
622
+ ];
623
+
624
+ // src/bots/index.ts
625
+ var AI_CATEGORIES = /* @__PURE__ */ new Set([
626
+ "training_crawler",
627
+ "ai_search_crawler",
628
+ "ai_agent",
629
+ "ai_assistant"
630
+ ]);
631
+ var UNKNOWN = Object.freeze({
632
+ known: false,
633
+ category: "none",
634
+ score: 0,
635
+ isAI: false
636
+ });
637
+ var MAX_CACHE = 1e3;
638
+ var cache = /* @__PURE__ */ new Map();
639
+ function matchUserAgent(userAgent) {
640
+ if (!userAgent) return void 0;
641
+ const cached = cache.get(userAgent);
642
+ if (cached !== void 0) return cached ?? void 0;
643
+ const ua = userAgent.toLowerCase();
644
+ let found = null;
645
+ for (const agent of BOT_REGISTRY) {
646
+ for (const pattern of agent.uaPatterns) {
647
+ if (ua.includes(pattern)) {
648
+ found = agent;
649
+ break;
650
+ }
651
+ }
652
+ if (found) break;
653
+ }
654
+ if (cache.size >= MAX_CACHE) cache.clear();
655
+ cache.set(userAgent, found);
656
+ return found ?? void 0;
657
+ }
658
+ function classifyUserAgent(userAgent) {
659
+ const agent = matchUserAgent(userAgent);
660
+ if (!agent) return UNKNOWN;
661
+ return {
662
+ known: true,
663
+ id: agent.id,
664
+ name: agent.name,
665
+ category: agent.category,
666
+ organization: agent.organization,
667
+ score: agent.baseScore,
668
+ respectsRobots: agent.respectsRobots,
669
+ isAI: AI_CATEGORIES.has(agent.category)
670
+ };
671
+ }
672
+
673
+ // src/rules/attack-signatures.ts
674
+ var SIGNATURES = [
675
+ // --- SQL injection -------------------------------------------------------
676
+ { id: "sqli_union", label: "SQL UNION SELECT", test: /\bunion\b[\s/*]+\bselect\b/i },
677
+ {
678
+ id: "sqli_tautology",
679
+ label: "SQL tautology",
680
+ // ' OR 1=1 / " or 'a'='a — the quote is required, which is what keeps this
681
+ // off ordinary query strings containing "or".
682
+ test: /['"`]\s*(?:or|and)\s+(?:\d+\s*=\s*\d+|['"`][^'"`]{0,32}['"`]\s*=\s*['"`])/i
683
+ },
684
+ {
685
+ id: "sqli_stacked",
686
+ label: "Stacked SQL statement",
687
+ test: /;\s*(?:drop|truncate|alter|create|insert|update|delete)\s+(?:table|database|from|into)\b/i
688
+ },
689
+ {
690
+ id: "sqli_timing",
691
+ label: "SQL timing function",
692
+ test: /\b(?:sleep|pg_sleep|benchmark|waitfor\s+delay)\s*\(/i
693
+ },
694
+ { id: "sqli_probe", label: "SQL metadata probe", test: /\binformation_schema\.[a-z_]+/i },
695
+ // --- Cross-site scripting -----------------------------------------------
696
+ { id: "xss_script_tag", label: "Inline <script>", test: /<\s*script[\s>/]/i },
697
+ { id: "xss_javascript_uri", label: "javascript: URI", test: /javascript\s*:[^\s]{0,64}\(/i },
698
+ {
699
+ id: "xss_event_handler",
700
+ label: "Inline event handler",
701
+ // Requires a tag context, so `onerror` as a bare parameter name is not a hit.
702
+ test: /<[a-z][a-z0-9]{0,15}[^>]{0,256}\son(?:error|load|click|mouseover|focus)\s*=/i
703
+ },
704
+ { id: "xss_svg_onload", label: "SVG onload", test: /<\s*svg[^>]{0,128}\bonload\b/i },
705
+ // --- Path traversal ------------------------------------------------------
706
+ {
707
+ id: "traversal",
708
+ label: "Path traversal",
709
+ // Two or more segments: a single `../` shows up in legitimately relative
710
+ // redirect targets often enough to be worth the extra evidence.
711
+ test: /(?:\.\.[/\\]){2,}/
712
+ },
713
+ { id: "traversal_etc", label: "Sensitive file path", test: /\/etc\/(?:passwd|shadow)\b/i },
714
+ // --- Command injection ---------------------------------------------------
715
+ {
716
+ id: "cmdi_shell",
717
+ label: "Shell command injection",
718
+ test: /[;|&`]\s*(?:cat|curl|wget|nc|bash|sh|python|perl|chmod)\s+[-/\w]/i
719
+ },
720
+ { id: "cmdi_subshell", label: "Shell substitution", test: /\$\([a-z][^)]{0,64}\)/i },
721
+ // --- Template / expression injection -------------------------------------
722
+ { id: "ssti_jndi", label: "JNDI lookup (Log4Shell)", test: /\$\{\s*jndi\s*:/i },
723
+ { id: "ssti_expression", label: "Template expression", test: /\{\{\s*[\w.]+\s*[(*]/ }
724
+ ];
725
+ var ATTACK_SIGNATURE_IDS = SIGNATURES.map((s) => s.id);
726
+
727
+ // src/webcrypto.ts
728
+ var encoder = new TextEncoder();
729
+ function toHex(bytes) {
730
+ let hex = "";
731
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
732
+ return hex;
733
+ }
734
+ function randomHex(bytes) {
735
+ const buf = new Uint8Array(bytes);
736
+ crypto.getRandomValues(buf);
737
+ return toHex(buf);
738
+ }
739
+
740
+ // src/rules/index.ts
741
+ function tripwire(config = {}) {
742
+ return new TripwireRule(config);
743
+ }
744
+
745
+ // src/violation-reporter.ts
746
+ var ViolationReporter = class {
747
+ constructor(client, config = {}) {
748
+ this.buffer = [];
749
+ this.flushing = false;
750
+ this.client = client;
751
+ this.maxBufferSize = config.maxBufferSize ?? 50;
752
+ this.debug = config.debug ?? false;
753
+ const flushInterval = config.flushInterval ?? 5e3;
754
+ this.flushTimer = setInterval(() => void this.flush(), flushInterval);
755
+ if (this.flushTimer.unref) {
756
+ this.flushTimer.unref();
757
+ }
758
+ }
759
+ /**
760
+ * Add violations to the buffer. Auto-flushes when buffer reaches maxBufferSize.
761
+ */
762
+ report(violations) {
763
+ this.buffer.push(...violations);
764
+ if (this.buffer.length >= this.maxBufferSize) {
765
+ this.flush().catch(() => {
766
+ });
767
+ }
768
+ }
769
+ /**
770
+ * Flush buffered violations to the backend
771
+ */
772
+ async flush() {
773
+ if (this.flushing || this.buffer.length === 0) return;
774
+ this.flushing = true;
775
+ const events = this.buffer.splice(0, this.buffer.length);
776
+ try {
777
+ for (let i = 0; i < events.length; i += 100) {
778
+ const batch = events.slice(i, i + 100);
779
+ await this.client.sendViolations(batch);
780
+ if (this.debug) {
781
+ console.log(`[WebDecoy] Flushed ${batch.length} violation events`);
782
+ }
783
+ }
784
+ } catch (error) {
785
+ if (this.debug) {
786
+ console.error("[WebDecoy] Failed to flush violations:", error);
787
+ }
788
+ } finally {
789
+ this.flushing = false;
790
+ }
791
+ }
792
+ /**
793
+ * Flush remaining events and stop the timer
794
+ */
795
+ async destroy() {
796
+ clearInterval(this.flushTimer);
797
+ await this.flush();
798
+ }
799
+ };
800
+
801
+ // src/ip-enrichment.ts
802
+ var IPEnrichmentClient = class {
803
+ constructor(client, ttlMs = 36e5) {
804
+ this.cache = /* @__PURE__ */ new Map();
805
+ this.pending = /* @__PURE__ */ new Map();
806
+ this.client = client;
807
+ this.ttlMs = ttlMs;
808
+ }
809
+ /**
810
+ * Get enrichment data for an IP address.
811
+ * Returns cached data if available (1h TTL), otherwise fetches from API.
812
+ * Returns null if enrichment fails (fail-open).
813
+ */
814
+ async enrich(ip) {
815
+ const cached = this.cache.get(ip);
816
+ if (cached && cached.expiresAt > Date.now()) {
817
+ return cached.data;
818
+ }
819
+ const inflight = this.pending.get(ip);
820
+ if (inflight) {
821
+ return inflight;
822
+ }
823
+ const promise = this.fetchAndCache(ip);
824
+ this.pending.set(ip, promise);
825
+ try {
826
+ return await promise;
827
+ } finally {
828
+ this.pending.delete(ip);
829
+ }
830
+ }
831
+ async fetchAndCache(ip) {
832
+ const data = await this.client.getIPEnrichment(ip);
833
+ if (data) {
834
+ this.cache.set(ip, {
835
+ data,
836
+ expiresAt: Date.now() + this.ttlMs
837
+ });
838
+ }
839
+ return data;
840
+ }
841
+ /**
842
+ * Clear the cache
843
+ */
844
+ clearCache() {
845
+ this.cache.clear();
846
+ }
847
+ };
848
+
849
+ // src/agent/thumbprint.ts
850
+ var encoder2 = new TextEncoder();
851
+ async function rsaThumbprint(n, e) {
852
+ return digest(`{"e":${JSON.stringify(e)},"kty":"RSA","n":${JSON.stringify(n)}}`);
853
+ }
854
+ async function okpThumbprint(crv, x) {
855
+ return digest(`{"crv":${JSON.stringify(crv)},"kty":"OKP","x":${JSON.stringify(x)}}`);
856
+ }
857
+ async function jwkThumbprint(k) {
858
+ switch (k.kty) {
859
+ case "OKP":
860
+ if (!k.crv || !k.x) throw new Error("thumbprint: OKP JWK missing crv or x");
861
+ return okpThumbprint(k.crv, k.x);
862
+ case "RSA":
863
+ if (!k.n || !k.e) throw new Error("thumbprint: RSA JWK missing n or e");
864
+ return rsaThumbprint(k.n, k.e);
865
+ default:
866
+ throw new Error(`thumbprint: unsupported kty ${JSON.stringify(k.kty)}`);
867
+ }
868
+ }
869
+ async function digest(canonical) {
870
+ const buf = await crypto.subtle.digest("SHA-256", encoder2.encode(canonical));
871
+ return base64urlBytes(new Uint8Array(buf));
872
+ }
873
+ function base64urlBytes(bytes) {
874
+ let binary = "";
875
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
876
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
877
+ }
878
+
879
+ // src/agent/directory.ts
880
+ var WELL_KNOWN = "/.well-known/http-message-signatures-directory";
881
+ var COLD_RETRY_BACKOFF_MS = 3e4;
882
+ var DEFAULT_SIGNED_AGENT_DIRECTORIES = [
883
+ { name: "OpenAI", category: "ai_crawlers", directory: "https://operator.openai.com" },
884
+ { name: "OpenAI ChatGPT", category: "ai_crawlers", directory: "https://chatgpt.com" }
885
+ ];
886
+ var DirectoryCache = class {
887
+ constructor(opts) {
888
+ this.keys = /* @__PURE__ */ new Map();
889
+ this.refreshedAt = 0;
890
+ this.nextColdRetryAt = 0;
891
+ this.inflight = null;
892
+ /** Resolve a keyid to a verification key, fetching/refreshing as needed. */
893
+ this.resolveKey = async (keyId) => {
894
+ await this.ensureFresh();
895
+ return this.keys.get(keyId);
896
+ };
897
+ this.opts = opts;
898
+ }
899
+ /** Kick off a fetch without blocking — call at startup to warm the cache. */
900
+ prime() {
901
+ if (this.keys.size === 0 && Date.now() >= this.nextColdRetryAt) void this.refresh();
902
+ }
903
+ /** Number of keys currently cached (diagnostics/tests). */
904
+ get size() {
905
+ return this.keys.size;
906
+ }
907
+ async ensureFresh() {
908
+ const now = Date.now();
909
+ const stale = now - this.refreshedAt > this.opts.cacheTtlMs;
910
+ if (this.keys.size > 0) {
911
+ if (stale) void this.refresh();
912
+ return;
913
+ }
914
+ if (now < this.nextColdRetryAt) return;
915
+ await this.refresh();
916
+ }
917
+ /** Re-fetch every directory. De-duplicated: concurrent callers share one run. */
918
+ refresh() {
919
+ if (this.inflight) return this.inflight;
920
+ this.inflight = this.doRefresh().finally(() => {
921
+ this.inflight = null;
922
+ });
923
+ return this.inflight;
924
+ }
925
+ async doRefresh() {
926
+ const results = await Promise.all(
927
+ this.opts.directories.map((src) => this.fetchDirectory(src))
928
+ );
929
+ const next = new Map(this.keys);
930
+ let fetchedAny = false;
931
+ for (const keys of results) {
932
+ if (keys === null) continue;
933
+ fetchedAny = true;
934
+ for (const k of keys) next.set(k.thumbprint, k.key);
935
+ }
936
+ if (fetchedAny) {
937
+ this.keys = next;
938
+ this.refreshedAt = Date.now();
939
+ this.nextColdRetryAt = 0;
940
+ this.debug(`refreshed: ${this.keys.size} key(s) across ${this.opts.directories.length} directories`);
941
+ } else if (this.keys.size === 0) {
942
+ this.nextColdRetryAt = Date.now() + COLD_RETRY_BACKOFF_MS;
943
+ this.debug("all directories unreachable; backing off cold retry");
944
+ }
945
+ }
946
+ async fetchDirectory(src) {
947
+ const url = directoryUrl(src.directory);
948
+ const controller = new AbortController();
949
+ const timer = setTimeout(() => controller.abort(), this.opts.fetchTimeoutMs);
950
+ try {
951
+ const res = await this.opts.fetchImpl(url, {
952
+ signal: controller.signal,
953
+ headers: {
954
+ Accept: "application/http-message-signatures-directory+json, application/jwk-set+json, application/json"
955
+ },
956
+ redirect: "follow"
957
+ });
958
+ if (!res.ok) {
959
+ this.debug(`${src.name}: HTTP ${res.status}`);
960
+ return null;
961
+ }
962
+ const body = await res.json();
963
+ if (!body || !Array.isArray(body.keys)) {
964
+ this.debug(`${src.name}: no keys in directory`);
965
+ return null;
966
+ }
967
+ const out = [];
968
+ for (const jwk of body.keys) {
969
+ const resolved = await importKey(jwk, src);
970
+ if (resolved) out.push(resolved);
971
+ }
972
+ this.debug(`${src.name}: ${out.length} key(s)`);
973
+ return out;
974
+ } catch (err) {
975
+ this.debug(`${src.name}: fetch failed \u2014 ${err.message}`);
976
+ return null;
977
+ } finally {
978
+ clearTimeout(timer);
979
+ }
980
+ }
981
+ debug(msg) {
982
+ if (this.opts.debug) console.log(`[WebDecoy][web-bot-auth] ${msg}`);
983
+ }
984
+ };
985
+ function directoryUrl(directory) {
986
+ const u = new URL(directory);
987
+ if (u.pathname && u.pathname !== "/") return u.toString();
988
+ u.pathname = WELL_KNOWN;
989
+ return u.toString();
990
+ }
991
+ async function importKey(jwk, src) {
992
+ try {
993
+ let cryptoKey;
994
+ let verifyParams;
995
+ let algorithm;
996
+ if (jwk.kty === "OKP") {
997
+ if (jwk.crv !== "Ed25519" || !jwk.x) return null;
998
+ cryptoKey = await crypto.subtle.importKey(
999
+ "jwk",
1000
+ { kty: "OKP", crv: "Ed25519", x: jwk.x },
1001
+ { name: "Ed25519" },
1002
+ false,
1003
+ ["verify"]
1004
+ );
1005
+ verifyParams = { name: "Ed25519" };
1006
+ algorithm = "ed25519";
1007
+ } else if (jwk.kty === "RSA") {
1008
+ if (!jwk.n || !jwk.e) return null;
1009
+ cryptoKey = await crypto.subtle.importKey(
1010
+ "jwk",
1011
+ { kty: "RSA", n: jwk.n, e: jwk.e },
1012
+ { name: "RSA-PSS", hash: "SHA-512" },
1013
+ false,
1014
+ ["verify"]
1015
+ );
1016
+ verifyParams = { name: "RSA-PSS", saltLength: 64 };
1017
+ algorithm = "rsa-pss-sha512";
1018
+ } else {
1019
+ return null;
1020
+ }
1021
+ const thumbprint = await jwkThumbprint(jwk);
1022
+ return {
1023
+ thumbprint,
1024
+ key: {
1025
+ cryptoKey,
1026
+ verifyParams,
1027
+ algorithm,
1028
+ name: src.name,
1029
+ category: src.category,
1030
+ nbf: normalizeEpoch(jwk.nbf),
1031
+ exp: normalizeEpoch(jwk.exp)
1032
+ }
1033
+ };
1034
+ } catch {
1035
+ return null;
1036
+ }
1037
+ }
1038
+ function normalizeEpoch(v) {
1039
+ if (v === void 0 || v === 0) return void 0;
1040
+ return v > 1e12 ? Math.floor(v / 1e3) : v;
1041
+ }
1042
+
1043
+ // src/agent/sfv.ts
1044
+ var Cursor = class {
1045
+ constructor(s, i = 0) {
1046
+ this.s = s;
1047
+ this.i = i;
1048
+ }
1049
+ eof() {
1050
+ return this.i >= this.s.length;
1051
+ }
1052
+ peek() {
1053
+ return this.s[this.i];
1054
+ }
1055
+ skipSP() {
1056
+ while (!this.eof() && (this.peek() === " " || this.peek() === " ")) this.i++;
1057
+ }
1058
+ };
1059
+ function parseDictionary(input) {
1060
+ const p = new Cursor(input);
1061
+ const out = [];
1062
+ p.skipSP();
1063
+ while (!p.eof()) {
1064
+ const key = parseKey(p);
1065
+ const entry = { key, raw: "", isList: false, items: [], params: /* @__PURE__ */ new Map() };
1066
+ if (!p.eof() && p.peek() === "=") {
1067
+ p.i++;
1068
+ const start = p.i;
1069
+ if (!p.eof() && p.peek() === "(") {
1070
+ entry.isList = true;
1071
+ parseInnerList(p, entry);
1072
+ } else {
1073
+ entry.items.push(parseItem(p));
1074
+ entry.params = entry.items[0].params;
1075
+ }
1076
+ entry.raw = input.slice(start, p.i);
1077
+ } else {
1078
+ entry.params = parseParams(p);
1079
+ entry.items.push({ value: true, params: /* @__PURE__ */ new Map() });
1080
+ entry.raw = "?1";
1081
+ }
1082
+ out.push(entry);
1083
+ p.skipSP();
1084
+ if (p.eof()) break;
1085
+ if (p.peek() !== ",") throw new Error(`sfv: expected ',' at ${p.i}`);
1086
+ p.i++;
1087
+ p.skipSP();
1088
+ if (p.eof()) throw new Error("sfv: trailing comma");
1089
+ }
1090
+ return out;
1091
+ }
1092
+ function parseInnerList(p, entry) {
1093
+ p.i++;
1094
+ for (; ; ) {
1095
+ p.skipSP();
1096
+ if (p.eof()) throw new Error("sfv: unterminated inner list");
1097
+ if (p.peek() === ")") {
1098
+ p.i++;
1099
+ break;
1100
+ }
1101
+ entry.items.push(parseItem(p));
1102
+ if (p.eof()) throw new Error("sfv: unterminated inner list");
1103
+ const c = p.peek();
1104
+ if (c !== " " && c !== ")") throw new Error(`sfv: bad inner list at ${p.i}`);
1105
+ }
1106
+ entry.params = parseParams(p);
1107
+ }
1108
+ function parseItem(p) {
1109
+ const { value, bytes } = parseBareItem(p);
1110
+ const params = parseParams(p);
1111
+ return bytes ? { value, params, bytes } : { value, params };
1112
+ }
1113
+ function parseParams(p) {
1114
+ const params = /* @__PURE__ */ new Map();
1115
+ while (!p.eof() && p.peek() === ";") {
1116
+ p.i++;
1117
+ p.skipSP();
1118
+ const key = parseKey(p);
1119
+ let val = true;
1120
+ if (!p.eof() && p.peek() === "=") {
1121
+ p.i++;
1122
+ val = parseBareItem(p).value;
1123
+ }
1124
+ params.set(key, val);
1125
+ }
1126
+ return params;
1127
+ }
1128
+ function parseKey(p) {
1129
+ const c = p.peek();
1130
+ if (!c || !/[a-z*]/.test(c)) throw new Error(`sfv: invalid key at ${p.i}`);
1131
+ const start = p.i;
1132
+ while (!p.eof() && /[a-z0-9_\-.*]/.test(p.peek())) p.i++;
1133
+ return p.s.slice(start, p.i);
1134
+ }
1135
+ function parseBareItem(p) {
1136
+ const c = p.peek();
1137
+ if (c === '"') return { value: parseString(p) };
1138
+ if (c === ":") return { value: "", bytes: parseByteSequence(p) };
1139
+ if (c === "?") {
1140
+ p.i++;
1141
+ const b = p.s[p.i++];
1142
+ if (b === "1") return { value: true };
1143
+ if (b === "0") return { value: false };
1144
+ throw new Error("sfv: bad boolean");
1145
+ }
1146
+ if (c === "-" || /[0-9]/.test(c)) return { value: parseNumber(p) };
1147
+ if (/[a-zA-Z*]/.test(c)) return { value: parseToken(p) };
1148
+ throw new Error(`sfv: invalid bare item at ${p.i}`);
1149
+ }
1150
+ function parseString(p) {
1151
+ p.i++;
1152
+ let out = "";
1153
+ while (!p.eof()) {
1154
+ const c = p.s[p.i++];
1155
+ if (c === '"') return out;
1156
+ if (c === "\\") {
1157
+ const e = p.s[p.i++];
1158
+ if (e !== '"' && e !== "\\") throw new Error("sfv: bad escape");
1159
+ out += e;
1160
+ } else {
1161
+ const code = c.charCodeAt(0);
1162
+ if (code < 32 || code > 126) throw new Error("sfv: bad char in string");
1163
+ out += c;
1164
+ }
1165
+ }
1166
+ throw new Error("sfv: unterminated string");
1167
+ }
1168
+ function parseByteSequence(p) {
1169
+ p.i++;
1170
+ const start = p.i;
1171
+ while (!p.eof() && p.peek() !== ":") p.i++;
1172
+ if (p.eof()) throw new Error("sfv: unterminated byte sequence");
1173
+ const b64 = p.s.slice(start, p.i);
1174
+ p.i++;
1175
+ return base64StdToBytes(b64);
1176
+ }
1177
+ function parseNumber(p) {
1178
+ const start = p.i;
1179
+ if (p.peek() === "-") p.i++;
1180
+ while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
1181
+ if (!p.eof() && p.peek() === ".") {
1182
+ p.i++;
1183
+ while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
1184
+ }
1185
+ return Number(p.s.slice(start, p.i));
1186
+ }
1187
+ function parseToken(p) {
1188
+ const start = p.i;
1189
+ p.i++;
1190
+ while (!p.eof() && /[a-zA-Z0-9!#$%&'*+\-.^_`|~:/]/.test(p.peek())) p.i++;
1191
+ return p.s.slice(start, p.i);
1192
+ }
1193
+ function base64StdToBytes(s) {
1194
+ const bin = atob(s);
1195
+ const out = new Uint8Array(bin.length);
1196
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
1197
+ return out;
1198
+ }
1199
+
1200
+ // src/agent/signature.ts
1201
+ var TAG = "web-bot-auth";
1202
+ var encoder3 = new TextEncoder();
1203
+ async function verifyWebBotAuth(req, resolveKey, toleranceSec) {
1204
+ const sigInput = req.headers.get("signature-input");
1205
+ const sigHeader = req.headers.get("signature");
1206
+ if (!sigInput && !sigHeader) return { outcome: "none" };
1207
+ if (!sigInput || !sigHeader) return { outcome: "claimed", reason: "incomplete-signature" };
1208
+ let members;
1209
+ let sigs;
1210
+ try {
1211
+ members = parseSignatureInput(sigInput);
1212
+ sigs = parseSignatureBytes(sigHeader);
1213
+ } catch {
1214
+ return { outcome: "claimed", reason: "malformed-signature" };
1215
+ }
1216
+ const now = Date.now() / 1e3;
1217
+ let best = { outcome: "none" };
1218
+ for (const m of members) {
1219
+ if (m.params.get("tag") !== TAG) continue;
1220
+ if (best.outcome === "none") best = { outcome: "claimed", reason: "unverifiable" };
1221
+ const sig = sigs.get(m.label);
1222
+ if (!sig) continue;
1223
+ const keyid = m.params.get("keyid");
1224
+ if (typeof keyid !== "string") continue;
1225
+ if (!m.components.some((c) => c.name === "@authority" || c.name === "@target-uri")) continue;
1226
+ const key = await resolveKey(keyid);
1227
+ if (!key) {
1228
+ best = higher(best, { outcome: "claimed", keyId: keyid, reason: "unknown-key" });
1229
+ continue;
1230
+ }
1231
+ const created = numeric(m.params.get("created"));
1232
+ const expires = numeric(m.params.get("expires"));
1233
+ if (expires !== void 0 && now > expires + toleranceSec) {
1234
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "expired" });
1235
+ continue;
1236
+ }
1237
+ if (created !== void 0 && now + toleranceSec < created) {
1238
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "not-yet-valid" });
1239
+ continue;
1240
+ }
1241
+ if (key.exp !== void 0 && now > key.exp + toleranceSec) {
1242
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-expired" });
1243
+ continue;
1244
+ }
1245
+ if (key.nbf !== void 0 && now + toleranceSec < key.nbf) {
1246
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-not-yet-valid" });
1247
+ continue;
1248
+ }
1249
+ let base;
1250
+ try {
1251
+ base = buildSignatureBase(req, m);
1252
+ } catch {
1253
+ best = higher(best, { outcome: "claimed", keyId: keyid, reason: "uncoverable-component" });
1254
+ continue;
1255
+ }
1256
+ let ok = false;
1257
+ try {
1258
+ ok = await crypto.subtle.verify(
1259
+ key.verifyParams,
1260
+ key.cryptoKey,
1261
+ sig,
1262
+ encoder3.encode(base)
1263
+ );
1264
+ } catch {
1265
+ ok = false;
1266
+ }
1267
+ if (ok) {
1268
+ return { outcome: "verified", keyId: keyid, key };
1269
+ }
1270
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "bad-signature" });
1271
+ }
1272
+ return best;
1273
+ }
1274
+ var PRECEDENCE = { none: 0, claimed: 1, impersonation: 2, verified: 3 };
1275
+ function higher(a, b) {
1276
+ return PRECEDENCE[b.outcome] >= PRECEDENCE[a.outcome] ? b : a;
1277
+ }
1278
+ function numeric(v) {
1279
+ return typeof v === "number" ? v : void 0;
1280
+ }
1281
+ function buildSignatureBase(req, m) {
1282
+ const lines = [];
1283
+ for (const c of m.components) {
1284
+ lines.push(`${serializeComponentId(c)}: ${componentValue(req, c)}`);
1285
+ }
1286
+ lines.push(`"@signature-params": ${m.raw.trim()}`);
1287
+ return lines.join("\n");
1288
+ }
1289
+ function serializeComponentId(c) {
1290
+ const base = `"${c.name.toLowerCase()}"`;
1291
+ return c.keyParam !== void 0 ? `${base};key="${c.keyParam}"` : base;
1292
+ }
1293
+ function componentValue(req, c) {
1294
+ const name = c.name.toLowerCase();
1295
+ switch (name) {
1296
+ case "@method":
1297
+ return req.method.toUpperCase();
1298
+ case "@authority":
1299
+ return canonicalAuthority(req.url);
1300
+ case "@scheme":
1301
+ return req.url.protocol.replace(/:$/, "").toLowerCase();
1302
+ case "@target-uri":
1303
+ return `${req.url.protocol}//${canonicalAuthority(req.url)}${req.url.pathname}${req.url.search}`;
1304
+ case "@path":
1305
+ return req.url.pathname;
1306
+ case "@query":
1307
+ return req.url.search === "" ? "?" : req.url.search;
1308
+ case "signature-agent": {
1309
+ const header = req.headers.get("signature-agent");
1310
+ if (header === null) throw new Error("signature-agent covered but absent");
1311
+ if (c.keyParam !== void 0) return dictMemberValue(header, c.keyParam);
1312
+ return header.trim().replace(/\s+/g, " ");
1313
+ }
1314
+ default: {
1315
+ if (name.startsWith("@")) throw new Error(`unsupported derived component ${name}`);
1316
+ const header = req.headers.get(name);
1317
+ if (header === null) throw new Error(`covered header ${name} absent`);
1318
+ return header.trim().replace(/\s+/g, " ");
1319
+ }
1320
+ }
1321
+ }
1322
+ function canonicalAuthority(url) {
1323
+ const host = url.hostname.toLowerCase();
1324
+ const port = url.port;
1325
+ if (!port) return host;
1326
+ if (url.protocol === "https:" && port === "443" || url.protocol === "http:" && port === "80") {
1327
+ return host;
1328
+ }
1329
+ return `${host}:${port}`;
1330
+ }
1331
+ function dictMemberValue(header, key) {
1332
+ const dict = parseDictionary(header);
1333
+ const found = dict.find((d) => d.key === key);
1334
+ if (!found) throw new Error(`signature-agent has no member ${key}`);
1335
+ return found.raw;
1336
+ }
1337
+ function parseSignatureInput(value) {
1338
+ return parseDictionary(value).map((d) => {
1339
+ if (!d.isList) throw new Error(`Signature-Input member ${d.key} is not an inner list`);
1340
+ const components = d.items.map((it) => {
1341
+ if (typeof it.value !== "string") throw new Error("component identifier is not a string");
1342
+ const keyParam = it.params.get("key");
1343
+ return { name: it.value, keyParam: typeof keyParam === "string" ? keyParam : void 0 };
1344
+ });
1345
+ return { label: d.key, components, params: d.params, raw: d.raw };
1346
+ });
1347
+ }
1348
+ function parseSignatureBytes(value) {
1349
+ const out = /* @__PURE__ */ new Map();
1350
+ for (const d of parseDictionary(value)) {
1351
+ if (d.isList || d.items.length !== 1 || !d.items[0].bytes) {
1352
+ throw new Error(`Signature member ${d.key} is not a byte sequence`);
1353
+ }
1354
+ out.set(d.key, d.items[0].bytes);
1355
+ }
1356
+ return out;
1357
+ }
1358
+
1359
+ // src/agent/verifier.ts
1360
+ var DEFAULT_TTL_MS = 6 * 60 * 60 * 1e3;
1361
+ var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
1362
+ var DEFAULT_TOLERANCE_SEC = 300;
1363
+ var AgentVerifier = class {
1364
+ constructor(options = {}) {
1365
+ this.toleranceSec = options.toleranceSec ?? DEFAULT_TOLERANCE_SEC;
1366
+ this.cache = new DirectoryCache({
1367
+ directories: options.directories ?? DEFAULT_SIGNED_AGENT_DIRECTORIES,
1368
+ cacheTtlMs: options.cacheTtlMs ?? DEFAULT_TTL_MS,
1369
+ fetchTimeoutMs: options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,
1370
+ debug: options.debug ?? false,
1371
+ fetchImpl: options.fetchImpl ?? fetch
1372
+ });
1373
+ }
1374
+ /** Pre-fetch trusted directories so the first request verifies warm. */
1375
+ warmup() {
1376
+ this.cache.prime();
1377
+ }
1378
+ /** Verify a request's Web Bot Auth signature (if any) locally. */
1379
+ async verify(request2) {
1380
+ let req;
1381
+ try {
1382
+ req = normalize(request2);
1383
+ } catch {
1384
+ return { status: "none" };
1385
+ }
1386
+ const result = await verifyWebBotAuth(req, this.cache.resolveKey, this.toleranceSec);
1387
+ switch (result.outcome) {
1388
+ case "verified":
1389
+ return {
1390
+ status: "verified",
1391
+ method: "signature",
1392
+ keyId: result.keyId,
1393
+ agentName: result.key?.name,
1394
+ category: result.key?.category,
1395
+ algorithm: result.key?.algorithm
1396
+ };
1397
+ case "impersonation":
1398
+ return {
1399
+ status: "impersonation",
1400
+ method: "signature",
1401
+ keyId: result.keyId,
1402
+ agentName: result.key?.name,
1403
+ category: result.key?.category,
1404
+ reason: result.reason
1405
+ };
1406
+ case "claimed":
1407
+ return { status: "claimed", keyId: result.keyId, reason: result.reason };
1408
+ default:
1409
+ return { status: "none" };
1410
+ }
1411
+ }
1412
+ /** Cached-key count (diagnostics/tests). */
1413
+ get cachedKeyCount() {
1414
+ return this.cache.size;
1415
+ }
1416
+ };
1417
+ function normalize(input) {
1418
+ if (isRequest(input)) {
1419
+ return { method: input.method, url: new URL(input.url), headers: input.headers };
1420
+ }
1421
+ const headers = input.headers instanceof Headers ? input.headers : toHeaders(input.headers);
1422
+ return { method: input.method, url: new URL(input.url), headers };
1423
+ }
1424
+ function isRequest(input) {
1425
+ return typeof Request !== "undefined" && input instanceof Request && typeof input.url === "string";
1426
+ }
1427
+ function toHeaders(record) {
1428
+ const h = new Headers();
1429
+ for (const [k, v] of Object.entries(record)) {
1430
+ if (v !== void 0 && v !== null) h.set(k, String(v));
1431
+ }
1432
+ return h;
1433
+ }
1434
+
1435
+ // src/edge.ts
1436
+ var EDGE_CLEARANCE_HEADER = "x-wd-clearance";
1437
+ var EDGE_CLASS_HEADER = "x-wd-class";
1438
+ var EDGE_CLASSES = ["verified", "crawler", "script", "browser"];
1439
+ function absent() {
1440
+ return {
1441
+ present: false,
1442
+ isVerified: false,
1443
+ isCrawler: false,
1444
+ isScript: false,
1445
+ isBrowser: false,
1446
+ isUnattestedNonBrowser: false
1447
+ };
1448
+ }
1449
+ function normaliseClass(raw) {
1450
+ if (!raw) return void 0;
1451
+ const v = raw.trim().toLowerCase();
1452
+ return EDGE_CLASSES.includes(v) ? v : void 0;
1453
+ }
1454
+ function readEdgeVerdict(headers) {
1455
+ if (!headers) return absent();
1456
+ let clearanceRaw;
1457
+ let classRaw;
1458
+ for (const key of Object.keys(headers)) {
1459
+ const k = key.toLowerCase();
1460
+ if (k === EDGE_CLEARANCE_HEADER) clearanceRaw = headers[key];
1461
+ else if (k === EDGE_CLASS_HEADER) classRaw = headers[key];
1462
+ }
1463
+ const clearance = clearanceRaw?.trim() || void 0;
1464
+ const cls = normaliseClass(classRaw);
1465
+ if (!clearance && !cls) return absent();
1466
+ return {
1467
+ present: true,
1468
+ clearance,
1469
+ class: cls,
1470
+ isVerified: cls === "verified",
1471
+ isCrawler: cls === "crawler",
1472
+ isScript: cls === "script",
1473
+ isBrowser: cls === "browser",
1474
+ isUnattestedNonBrowser: cls === "script" || cls === "crawler"
1475
+ };
1476
+ }
1477
+
1478
+ // src/logger.ts
1479
+ var PREFIX = "[WebDecoy]";
1480
+ function consoleLogger(debug) {
1481
+ const emit = (fn, gated) => (message, fields) => {
1482
+ if (gated && !debug) return;
1483
+ if (fields) fn(`${PREFIX} ${message}`, fields);
1484
+ else fn(`${PREFIX} ${message}`);
1485
+ };
1486
+ return {
1487
+ debug: emit(console.log, true),
1488
+ info: emit(console.log, true),
1489
+ // Warnings and errors are not debug output. A violation that failed to
1490
+ // report, or a key that was rejected, is something the operator needs to
1491
+ // see whether or not they opted into diagnostics.
1492
+ warn: emit(console.warn, false),
1493
+ error: emit(console.error, false)
1494
+ };
1495
+ }
1496
+ var silentLogger = {
1497
+ debug() {
1498
+ },
1499
+ info() {
1500
+ },
1501
+ warn() {
1502
+ },
1503
+ error() {
1504
+ }
1505
+ };
1506
+ function resolveLogger(provided, debug) {
1507
+ return provided ?? consoleLogger(debug);
1508
+ }
1509
+
1510
+ // src/decision.ts
1511
+ function newDecisionId() {
1512
+ return `dec_${randomHex(12)}`;
1513
+ }
1514
+ var Decision = class _Decision {
1515
+ constructor(init) {
1516
+ this.id = init.id ?? newDecisionId();
1517
+ this.conclusion = init.conclusion;
1518
+ this.results = Object.freeze([...init.results ?? []]);
1519
+ this.reason = init.reason;
1520
+ this.detection = init.detection;
1521
+ this.error = init.error;
1522
+ this.ruleResult = init.ruleResult;
1523
+ this.agent = init.agent;
1524
+ this.edge = init.edge;
1525
+ this.key = init.key;
1526
+ this.ttl = init.ttl ?? 0;
1527
+ }
1528
+ get allowed() {
1529
+ return this.conclusion === "ALLOW" || this.conclusion === "ERROR";
1530
+ }
1531
+ isAllowed() {
1532
+ return this.conclusion === "ALLOW";
1533
+ }
1534
+ isDenied() {
1535
+ return this.conclusion === "DENY";
1536
+ }
1537
+ isChallenged() {
1538
+ return this.conclusion === "CHALLENGE";
1539
+ }
1540
+ isErrored() {
1541
+ return this.conclusion === "ERROR";
1542
+ }
1543
+ deniedBy(rule) {
1544
+ return this.results.some(
1545
+ (r) => r.rule === rule && r.state === "RUN" && r.conclusion === "DENY"
1546
+ );
1547
+ }
1548
+ /** A copy of this decision with the edge verdict attached. */
1549
+ withEdge(edge) {
1550
+ return new _Decision({ ...this.init(), edge });
1551
+ }
1552
+ /** A copy marked as served from cache, with every rule re-stated as CACHED. */
1553
+ asCached() {
1554
+ return new _Decision({
1555
+ ...this.init(),
1556
+ results: this.results.map((r) => ({ ...r, state: "CACHED" }))
1557
+ });
1558
+ }
1559
+ init() {
1560
+ return {
1561
+ id: this.id,
1562
+ conclusion: this.conclusion,
1563
+ results: [...this.results],
1564
+ reason: this.reason,
1565
+ detection: this.detection,
1566
+ error: this.error,
1567
+ ruleResult: this.ruleResult,
1568
+ agent: this.agent,
1569
+ edge: this.edge,
1570
+ key: this.key,
1571
+ ttl: this.ttl
1572
+ };
1573
+ }
1574
+ };
1575
+
1576
+ // src/characteristics.ts
1577
+ var DEFAULT_CHARACTERISTICS = ["ip"];
1578
+ function resolveOne(context, c) {
1579
+ if (typeof c === "function") {
1580
+ try {
1581
+ return c(context) || void 0;
1582
+ } catch {
1583
+ return void 0;
1584
+ }
1585
+ }
1586
+ switch (c) {
1587
+ case "ip":
1588
+ return context.ip || void 0;
1589
+ case "path":
1590
+ return context.path || void 0;
1591
+ case "method":
1592
+ return context.method || void 0;
1593
+ case "userAgent":
1594
+ return context.userAgent || void 0;
1595
+ }
1596
+ }
1597
+ function deriveKey(context, characteristics = DEFAULT_CHARACTERISTICS) {
1598
+ if (characteristics.length === 0) return context.ip;
1599
+ const parts = [];
1600
+ for (const c of characteristics) {
1601
+ const value = resolveOne(context, c);
1602
+ if (value === void 0) return context.ip;
1603
+ parts.push(value);
1604
+ }
1605
+ return parts.join("|");
1606
+ }
1607
+
1608
+ // src/decision-cache.ts
1609
+ var DecisionCache = class {
1610
+ constructor(options = {}) {
1611
+ // Insertion-ordered, which is what makes the eviction below oldest-first.
1612
+ this.entries = /* @__PURE__ */ new Map();
1613
+ this.ttl = options.ttl ?? 6e4;
1614
+ this.max = options.max ?? 1e4;
1615
+ }
1616
+ /** A cached decision for this key, or undefined. Expired entries are dropped. */
1617
+ get(key) {
1618
+ const entry = this.entries.get(key);
1619
+ if (!entry) return void 0;
1620
+ if (entry.expiresAt <= Date.now()) {
1621
+ this.entries.delete(key);
1622
+ return void 0;
1623
+ }
1624
+ return entry.decision;
1625
+ }
1626
+ /**
1627
+ * Remember a decision, if it is one of the kinds worth remembering.
1628
+ * Returns whether it was stored, so a caller can assert on the policy rather
1629
+ * than infer it.
1630
+ */
1631
+ set(key, decision) {
1632
+ if (decision.conclusion !== "DENY" && decision.conclusion !== "CHALLENGE") return false;
1633
+ if (this.ttl <= 0) return false;
1634
+ this.entries.delete(key);
1635
+ this.entries.set(key, { decision, expiresAt: Date.now() + this.ttl });
1636
+ while (this.entries.size > this.max) {
1637
+ const oldest = this.entries.keys().next();
1638
+ if (oldest.done) break;
1639
+ this.entries.delete(oldest.value);
1640
+ }
1641
+ return true;
1642
+ }
1643
+ clear() {
1644
+ this.entries.clear();
1645
+ }
1646
+ get size() {
1647
+ return this.entries.size;
1648
+ }
1649
+ /** How long entries live, in milliseconds. Reported on the decision. */
1650
+ get lifetime() {
1651
+ return this.ttl;
1652
+ }
1653
+ };
1654
+
1655
+ // src/test-trigger.ts
1656
+ var TEST_TRIGGER_UA_PREFIX = "WebDecoy-Test/";
1657
+ function isTestTriggerUserAgent(userAgent) {
1658
+ if (!userAgent) return false;
1659
+ return userAgent.trimStart().toLowerCase().startsWith(TEST_TRIGGER_UA_PREFIX.toLowerCase());
1660
+ }
1661
+
1662
+ // src/sdk.ts
1663
+ var WebDecoy = class {
1664
+ constructor(config) {
1665
+ this.violationReporter = null;
1666
+ this.ipEnrichmentClient = null;
1667
+ this._hasFilterRules = false;
1668
+ this._hasAgentRules = false;
1669
+ this._preparingRules = [];
1670
+ this.agentVerifier = null;
1671
+ const hasApiKey = !!config.apiKey;
1672
+ if (hasApiKey) {
1673
+ if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
1674
+ throw new Error(
1675
+ 'Invalid API key format. API key should start with "sk_live_" or "sk_test_".'
1676
+ );
1677
+ }
1678
+ }
1679
+ this.config = {
1680
+ apiKey: config.apiKey,
1681
+ apiUrl: config.apiUrl || "https://ingest.webdecoy.com",
1682
+ enableTLSFingerprinting: config.enableTLSFingerprinting ?? true,
1683
+ threatScoreThreshold: config.threatScoreThreshold ?? 80,
1684
+ timeout: config.timeout ?? 5e3,
1685
+ debug: config.debug ?? false,
1686
+ tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
1687
+ };
1688
+ this.log = resolveLogger(config.logger, this.config.debug);
1689
+ if (hasApiKey) {
1690
+ this.client = new WebDecoyClient({
1691
+ apiKey: config.apiKey,
1692
+ apiUrl: this.config.apiUrl,
1693
+ timeout: this.config.timeout,
1694
+ debug: this.config.debug,
1695
+ tlsRejectUnauthorized: this.config.tlsRejectUnauthorized
1696
+ });
1697
+ } else {
1698
+ this.client = null;
1699
+ this.log.info("Running in local-only mode (no API key). Rules will still evaluate.");
1700
+ }
1701
+ this.webBotAuthOptions = config.webBotAuth;
1702
+ this.characteristics = config.characteristics ?? DEFAULT_CHARACTERISTICS;
1703
+ this.decisionCache = config.decisionCache === false ? null : new DecisionCache(config.decisionCache ?? {});
1704
+ const rules = config.rules ?? [tripwire()];
1705
+ if (rules.length > 0) {
1706
+ this.ruleEngine = new RuleEngine(rules);
1707
+ this._hasFilterRules = rules.some((r) => r.name.startsWith("filter:"));
1708
+ this._hasAgentRules = rules.some((r) => r.name === "web-bot-auth");
1709
+ this._preparingRules = rules.filter((r) => typeof r.prepare === "function");
1710
+ if (this._hasAgentRules) {
1711
+ this.getAgentVerifier().warmup();
1712
+ }
1713
+ } else {
1714
+ this.ruleEngine = null;
1715
+ }
1716
+ if (this.client && this._hasFilterRules) {
1717
+ this.ipEnrichmentClient = new IPEnrichmentClient(this.client);
1718
+ }
1719
+ if (this.client && this.ruleEngine) {
1720
+ const reporter = new ViolationReporter(this.client, {
1721
+ debug: this.config.debug
1722
+ });
1723
+ this.setViolationReporter(reporter);
1724
+ }
1725
+ this.log.debug("Initialized", {
1726
+ apiUrl: this.config.apiUrl,
1727
+ enableTLSFingerprinting: this.config.enableTLSFingerprinting,
1728
+ threatScoreThreshold: this.config.threatScoreThreshold,
1729
+ hasApiKey,
1730
+ rulesCount: rules.length
1731
+ });
1732
+ }
1733
+ /**
1734
+ * Evaluate rules against request metadata (synchronous).
1735
+ * Returns null if no rules are configured.
1736
+ */
1737
+ evaluateRules(metadata) {
1738
+ if (!this.ruleEngine) return null;
1739
+ return this.runRules(this.buildContext(metadata));
1740
+ }
1741
+ /**
1742
+ * Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
1743
+ * verification). Use this instead of evaluateRules() when filter rules or
1744
+ * webBotAuth() rules are present.
1745
+ */
1746
+ async evaluateRulesAsync(metadata) {
1747
+ if (!this.ruleEngine) return null;
1748
+ const context = await this.buildAsyncContext(metadata);
1749
+ return this.runRules(context);
1750
+ }
1751
+ /**
1752
+ * Register a rule after construction.
1753
+ *
1754
+ * For signals whose definition is not available synchronously — the site
1755
+ * honeytoken's path is derived by async HMAC, so the adapter arms it once the
1756
+ * derivation settles. Creates the engine if there was none, so an SDK built
1757
+ * with `rules: []` can still gain one.
1758
+ */
1759
+ addRule(rule) {
1760
+ if (!this.ruleEngine) {
1761
+ this.ruleEngine = new RuleEngine([rule]);
1762
+ } else {
1763
+ this.ruleEngine.add(rule);
1764
+ }
1765
+ if (rule.name.startsWith("filter:")) this._hasFilterRules = true;
1766
+ if (rule.name === "web-bot-auth") this._hasAgentRules = true;
1767
+ if (typeof rule.prepare === "function") this._preparingRules.push(rule);
1768
+ }
1769
+ /** Build the base (synchronous) rule context from request metadata. */
1770
+ buildContext(metadata) {
1771
+ const context = {
1772
+ ip: metadata.ip,
1773
+ path: metadata.path,
1774
+ method: metadata.method,
1775
+ userAgent: metadata.user_agent,
1776
+ headers: metadata.headers,
1777
+ query: metadata.query,
1778
+ body: metadata.body,
1779
+ timestamp: metadata.timestamp || Date.now(),
1780
+ // Parsed synchronously and unconditionally: it is two header reads,
1781
+ // it needs no network, and a rule that has to check whether the edge
1782
+ // verdict was populated is a rule people will get wrong.
1783
+ edge: readEdgeVerdict(metadata.headers),
1784
+ // Same reasoning as `edge`, and the same cost profile: a memoised
1785
+ // substring scan over a static table, no network, no async. Populating it
1786
+ // unconditionally means a rule never has to ask whether classification
1787
+ // ran.
1788
+ bot: classifyUserAgent(metadata.user_agent)
1789
+ };
1790
+ context.key = deriveKey(context, this.characteristics);
1791
+ return context;
1792
+ }
1793
+ /**
1794
+ * Build a rule context with async signals resolved: IP enrichment (for
1795
+ * filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
1796
+ */
1797
+ async buildAsyncContext(metadata) {
1798
+ const context = this.buildContext(metadata);
1799
+ if (this._hasFilterRules && this.ipEnrichmentClient) {
1800
+ const enrichment = await this.ipEnrichmentClient.enrich(metadata.ip);
1801
+ if (enrichment) {
1802
+ context.enrichment = enrichment;
1803
+ }
1804
+ }
1805
+ if (this._hasAgentRules) {
1806
+ context.agent = await this.computeAgentVerdict(metadata);
1807
+ }
1808
+ if (this._preparingRules.length > 0) {
1809
+ await Promise.all(this._preparingRules.map((rule) => rule.prepare(context)));
1810
+ }
1811
+ return context;
1812
+ }
1813
+ /** Evaluate rules against a prepared context and report any violations. */
1814
+ runRules(context) {
1815
+ if (!this.ruleEngine) return null;
1816
+ const result = this.ruleEngine.evaluate(context);
1817
+ if (result.violations.length > 0 && this.violationReporter) {
1818
+ this.violationReporter.report(result.violations);
1819
+ }
1820
+ return result;
1821
+ }
1822
+ /** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
1823
+ getAgentVerifier() {
1824
+ if (!this.agentVerifier) {
1825
+ this.agentVerifier = new AgentVerifier({
1826
+ debug: this.config.debug,
1827
+ ...this.webBotAuthOptions
1828
+ });
1829
+ }
1830
+ return this.agentVerifier;
1831
+ }
1832
+ /**
1833
+ * Verify a request's Web Bot Auth signature locally, deriving the request
1834
+ * URL/authority from its metadata. Returns undefined when the request lacks
1835
+ * the host information needed to verify (verdict is then simply absent).
1836
+ */
1837
+ async computeAgentVerdict(metadata) {
1838
+ const input = agentInputFromMetadata(metadata);
1839
+ if (!input) return void 0;
1840
+ return this.getAgentVerifier().verify(input);
1841
+ }
1842
+ /**
1843
+ * Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
1844
+ * "web-bot-auth"). Returns whether it is a cryptographically `verified`
1845
+ * agent, an `impersonation` of a known one, an unverifiable `claimed`
1846
+ * signature, or `none`. No network on the warm path.
1847
+ *
1848
+ * Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
1849
+ * object (Node).
1850
+ *
1851
+ * @example
1852
+ * ```ts
1853
+ * const verdict = await webdecoy.detectBot(request);
1854
+ * if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
1855
+ * if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
1856
+ * ```
1857
+ */
1858
+ async detectBot(request2) {
1859
+ return this.getAgentVerifier().verify(request2);
1860
+ }
1861
+ /**
1862
+ * Whether this SDK instance has filter rules that need async enrichment
1863
+ */
1864
+ get hasFilterRules() {
1865
+ return this._hasFilterRules;
1866
+ }
1867
+ /**
1868
+ * Whether this SDK instance has Web Bot Auth rules that need async
1869
+ * verification before evaluation.
1870
+ */
1871
+ get hasAgentRules() {
1872
+ return this._hasAgentRules;
1873
+ }
1874
+ /**
1875
+ * Protect a request by checking it against Web Decoy's bot detection
1876
+ *
1877
+ * @param metadata - Request metadata to analyze
1878
+ * @param options - Optional configuration for this specific request
1879
+ * @returns The decision — `conclusion`, every rule's outcome, and the
1880
+ * narrowing helpers. Satisfies `ProtectResult`.
1881
+ */
1882
+ async protect(metadata, options = {}) {
1883
+ const edge = readEdgeVerdict(metadata.headers);
1884
+ return (await this.decide(metadata, options)).withEdge(edge);
1885
+ }
1886
+ async decide(metadata, options = {}) {
1887
+ const id = newDecisionId();
1888
+ let key = metadata.ip || "unknown";
1889
+ try {
1890
+ if (!metadata.ip) {
1891
+ throw new Error("IP address is required in request metadata");
1892
+ }
1893
+ if (!metadata.timestamp) {
1894
+ metadata.timestamp = Date.now();
1895
+ }
1896
+ if (isTestTriggerUserAgent(metadata.user_agent)) {
1897
+ return this.reportTestTrigger(metadata, id);
1898
+ }
1899
+ const needsAsync = this._hasFilterRules || this._hasAgentRules || this._preparingRules.length > 0;
1900
+ const context = needsAsync ? await this.buildAsyncContext(metadata) : this.buildContext(metadata);
1901
+ key = context.key ?? key;
1902
+ const agentVerdict = context.agent;
1903
+ const ruleResult = this.ruleEngine ? this.runRules(context) : null;
1904
+ if (ruleResult && ruleResult.action !== "ALLOW") {
1905
+ const throttled = ruleResult.action === "THROTTLE";
1906
+ return new Decision({
1907
+ conclusion: "DENY",
1908
+ reason: ruleResult.reason,
1909
+ detection: {
1910
+ decision: "block",
1911
+ confidence: 100,
1912
+ threat_level: throttled ? "MEDIUM" : "HIGH",
1913
+ bot_detected: false,
1914
+ detection_id: id,
1915
+ rule_enforced: true
1916
+ },
1917
+ id,
1918
+ results: ruleResult.results,
1919
+ ruleResult,
1920
+ agent: agentVerdict,
1921
+ key
1922
+ });
1923
+ }
1924
+ if (!this.client) {
1925
+ return new Decision({
1926
+ conclusion: "ALLOW",
1927
+ detection: {
1928
+ decision: "allow",
1929
+ confidence: 0,
1930
+ threat_level: "MINIMAL",
1931
+ bot_detected: false,
1932
+ detection_id: id,
1933
+ rule_enforced: false
1934
+ },
1935
+ id,
1936
+ results: ruleResult?.results ?? [],
1937
+ ruleResult: ruleResult ?? void 0,
1938
+ agent: agentVerdict,
1939
+ key
1940
+ });
1941
+ }
1942
+ const cached = this.decisionCache?.get(key);
1943
+ if (cached) return cached.asCached();
1944
+ const localAnalysis = options.skipLocalAnalysis ? {
1945
+ suspicious_headers: false,
1946
+ missing_sec_ch_ua: false,
1947
+ datacenter_ip: false,
1948
+ local_score: 0,
1949
+ needs_verification: true,
1950
+ flags: ["local_analysis_skipped"]
1951
+ } : analyzeRequest(metadata);
1952
+ this.log.debug("Local analysis", { ...localAnalysis });
1953
+ const detectionRequest = {
1954
+ request_metadata: metadata,
1955
+ local_analysis: localAnalysis
1956
+ };
1957
+ const shouldCallServer = localAnalysis.needs_verification || this.config.enableTLSFingerprinting && metadata.tls_info;
1958
+ if (!shouldCallServer && localAnalysis.local_score < 50) {
1959
+ return new Decision({
1960
+ conclusion: "ALLOW",
1961
+ detection: {
1962
+ decision: "allow",
1963
+ confidence: 100 - localAnalysis.local_score,
1964
+ threat_level: "MINIMAL",
1965
+ bot_detected: false,
1966
+ detection_id: id,
1967
+ rule_enforced: false
1968
+ },
1969
+ id,
1970
+ results: ruleResult?.results ?? [],
1971
+ ruleResult: ruleResult ?? void 0,
1972
+ agent: agentVerdict,
1973
+ key
1974
+ });
1975
+ }
1976
+ const detection = await this.client.detect(detectionRequest);
1977
+ const threshold = options.threshold ?? this.config.threatScoreThreshold;
1978
+ const allowed = detection.decision === "allow" || detection.confidence < threshold;
1979
+ this.log.debug("Server detection", {
1980
+ decision: detection.decision,
1981
+ confidence: detection.confidence,
1982
+ allowed
1983
+ });
1984
+ const conclusion = allowed ? "ALLOW" : detection.decision === "challenge" ? "CHALLENGE" : "DENY";
1985
+ const decision = new Decision({
1986
+ conclusion,
1987
+ reason: allowed ? void 0 : `Threat score ${detection.confidence} (threshold ${threshold})`,
1988
+ detection,
1989
+ id,
1990
+ results: ruleResult?.results ?? [],
1991
+ ruleResult: ruleResult ?? void 0,
1992
+ agent: agentVerdict,
1993
+ key,
1994
+ ttl: this.decisionCache && !allowed ? this.decisionCache.lifetime : 0
1995
+ });
1996
+ if (this.decisionCache) this.decisionCache.set(key, decision);
1997
+ return decision;
1998
+ } catch (error) {
1999
+ this.log.error("Protection error", {
2000
+ error: error instanceof Error ? error.message : String(error)
2001
+ });
2002
+ return new Decision({
2003
+ conclusion: "ERROR",
2004
+ detection: {
2005
+ decision: "allow",
2006
+ confidence: 0,
2007
+ threat_level: "MINIMAL",
2008
+ bot_detected: false,
2009
+ detection_id: id,
2010
+ rule_enforced: false
2011
+ },
2012
+ id,
2013
+ key,
2014
+ error: error instanceof Error ? error.message : "Unknown error"
2015
+ });
2016
+ }
2017
+ }
2018
+ /**
2019
+ * Report a test-trigger request and return a blocking verdict.
2020
+ *
2021
+ * The verdict is `allowed: false` so an enforce-mode adapter answers the
2022
+ * curl with a 403 — a visibly different response that tells the developer
2023
+ * their middleware acted, Arcjet-quickstart style. (The default monitor
2024
+ * mode still serves the request; the dashboard row is the real receipt.)
2025
+ *
2026
+ * Without an API key nothing can reach the dashboard, so the verdict says
2027
+ * so via `error` instead of pretending the test ran.
2028
+ */
2029
+ async reportTestTrigger(metadata, id) {
2030
+ const blocked = {
2031
+ decision: "block",
2032
+ confidence: 100,
2033
+ threat_level: "HIGH",
2034
+ bot_detected: true,
2035
+ bot_type: "test_trigger",
2036
+ detection_id: id,
2037
+ rule_enforced: false
2038
+ };
2039
+ if (!this.client) {
2040
+ return new Decision({
2041
+ id,
2042
+ conclusion: "DENY",
2043
+ reason: "Reserved test trigger",
2044
+ detection: blocked,
2045
+ error: "Test trigger recognized, but no apiKey is configured \u2014 nothing was reported to the dashboard."
2046
+ });
2047
+ }
2048
+ try {
2049
+ const detection = await this.client.detect({
2050
+ request_metadata: metadata,
2051
+ local_analysis: {
2052
+ suspicious_headers: false,
2053
+ missing_sec_ch_ua: false,
2054
+ datacenter_ip: false,
2055
+ local_score: 100,
2056
+ needs_verification: true,
2057
+ flags: ["test_trigger"]
2058
+ }
2059
+ });
2060
+ return new Decision({
2061
+ id,
2062
+ conclusion: "DENY",
2063
+ reason: "Reserved test trigger",
2064
+ detection
2065
+ });
2066
+ } catch (error) {
2067
+ return new Decision({
2068
+ id,
2069
+ conclusion: "DENY",
2070
+ reason: "Reserved test trigger",
2071
+ detection: blocked,
2072
+ error: error instanceof Error ? error.message : "Failed to report test detection"
2073
+ });
2074
+ }
2075
+ }
2076
+ /**
2077
+ * Validate the API key configuration
2078
+ * Useful for testing integration during setup
2079
+ */
2080
+ async validateConfig() {
2081
+ if (!this.client) {
2082
+ return { valid: false, error: "No API key configured" };
2083
+ }
2084
+ try {
2085
+ const isValid = await this.client.validateAPIKey();
2086
+ return { valid: isValid };
2087
+ } catch (error) {
2088
+ return {
2089
+ valid: false,
2090
+ error: error instanceof Error ? error.message : "Unknown error"
2091
+ };
2092
+ }
2093
+ }
2094
+ /**
2095
+ * Attach a violation reporter for sending violations to the backend.
2096
+ * Called internally when apiKey is present and rules are configured.
2097
+ */
2098
+ setViolationReporter(reporter) {
2099
+ this.violationReporter = reporter;
2100
+ }
2101
+ /**
2102
+ * Get the API client (for use by violation reporter, enrichment, etc.)
2103
+ */
2104
+ getClient() {
2105
+ return this.client;
2106
+ }
2107
+ /**
2108
+ * Get the current configuration
2109
+ */
2110
+ getConfig() {
2111
+ return { ...this.config };
2112
+ }
2113
+ /**
2114
+ * Clean up resources (timers, flush pending violations)
2115
+ */
2116
+ async destroy() {
2117
+ this.ruleEngine?.destroy();
2118
+ if (this.violationReporter) {
2119
+ await this.violationReporter.destroy();
2120
+ }
2121
+ }
2122
+ };
2123
+ function agentInputFromMetadata(metadata) {
2124
+ const headers = metadata.headers || {};
2125
+ const host = headers["host"] || headers[":authority"] || headers["x-forwarded-host"] || headers["Host"];
2126
+ if (!host) return null;
2127
+ const proto = headers["x-forwarded-proto"] || headers["X-Forwarded-Proto"];
2128
+ const scheme = (proto ? proto.split(",")[0].trim() : "https") || "https";
2129
+ const rawPath = metadata.path || "/";
2130
+ const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
2131
+ try {
2132
+ return {
2133
+ method: metadata.method,
2134
+ url: `${scheme}://${host}${path}`,
2135
+ headers
2136
+ };
2137
+ } catch {
2138
+ return null;
2139
+ }
2140
+ }
2141
+
2142
+ // src/testing.ts
2143
+ function request(over = {}) {
2144
+ return {
2145
+ method: "GET",
2146
+ path: "/",
2147
+ ip: "203.0.113.1",
2148
+ user_agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36",
2149
+ headers: {},
2150
+ timestamp: Date.now(),
2151
+ ...over
2152
+ };
2153
+ }
2154
+ function get(path, over = {}) {
2155
+ const q = path.indexOf("?");
2156
+ return request({
2157
+ method: "GET",
2158
+ path: q === -1 ? path : path.slice(0, q),
2159
+ query: q === -1 ? void 0 : path.slice(q + 1),
2160
+ ...over
2161
+ });
2162
+ }
2163
+ function post(path, body, over = {}) {
2164
+ return { ...get(path, over), method: "POST", body };
2165
+ }
2166
+ function botRequest(userAgent, over = {}) {
2167
+ return request({ user_agent: userAgent, ...over });
2168
+ }
2169
+ function createTestHarness(options = {}) {
2170
+ const { allowNetwork = false, ...config } = options;
2171
+ return new WebDecoy({
2172
+ ...config,
2173
+ apiKey: allowNetwork ? config.apiKey : void 0,
2174
+ logger: config.logger ?? silentLogger
2175
+ });
2176
+ }
2177
+ function describeDecision(decision) {
2178
+ const rules = decision.results.map((r) => `${r.rule}=${r.conclusion}${r.state === "RUN" ? "" : `(${r.state})`}`).join(", ");
2179
+ return [
2180
+ `conclusion=${decision.conclusion}`,
2181
+ decision.reason ? `reason="${decision.reason}"` : null,
2182
+ rules ? `rules[${rules}]` : "rules[none]"
2183
+ ].filter(Boolean).join(" ");
2184
+ }
2185
+ var AssertionError = class extends Error {
2186
+ constructor(message) {
2187
+ super(message);
2188
+ this.name = "WebDecoyAssertionError";
2189
+ }
2190
+ };
2191
+ function expectDenied(decision, expected = {}) {
2192
+ if (decision.conclusion !== "DENY") {
2193
+ throw new AssertionError(
2194
+ `Expected the request to be denied, but ${describeDecision(decision)}`
2195
+ );
2196
+ }
2197
+ if (expected.rule && !decision.deniedBy(expected.rule)) {
2198
+ throw new AssertionError(
2199
+ `Expected ${expected.rule} to deny, but ${describeDecision(decision)}`
2200
+ );
2201
+ }
2202
+ if (expected.reason !== void 0) {
2203
+ const reason = decision.reason ?? "";
2204
+ const ok = typeof expected.reason === "string" ? reason.includes(expected.reason) : expected.reason.test(reason);
2205
+ if (!ok) {
2206
+ throw new AssertionError(
2207
+ `Expected the reason to match ${String(expected.reason)}, got "${reason}"`
2208
+ );
2209
+ }
2210
+ }
2211
+ }
2212
+ function expectAllowed(decision) {
2213
+ if (decision.conclusion !== "ALLOW") {
2214
+ throw new AssertionError(
2215
+ `Expected the request to be allowed, but ${describeDecision(decision)}`
2216
+ );
2217
+ }
2218
+ }
2219
+ function expectRuleState(decision, rule, state) {
2220
+ const outcome = decision.results.find((r) => r.rule === rule);
2221
+ if (!outcome) {
2222
+ throw new AssertionError(
2223
+ `No rule named ${rule} ran. ${describeDecision(decision)}`
2224
+ );
2225
+ }
2226
+ if (outcome.state !== state) {
2227
+ throw new AssertionError(
2228
+ `Expected ${rule} to be ${state}, got ${outcome.state}. ${describeDecision(decision)}`
2229
+ );
2230
+ }
2231
+ }
2232
+ async function protectMany(sdk, metadata, count) {
2233
+ const out = [];
2234
+ for (let i = 0; i < count; i++) {
2235
+ out.push(await sdk.protect(typeof metadata === "function" ? metadata() : { ...metadata }));
2236
+ }
2237
+ return out;
2238
+ }
2239
+ // Annotate the CommonJS export names for ESM import in node:
2240
+ 0 && (module.exports = {
2241
+ botRequest,
2242
+ createTestHarness,
2243
+ expectAllowed,
2244
+ expectDenied,
2245
+ expectRuleState,
2246
+ get,
2247
+ post,
2248
+ protectMany,
2249
+ request
2250
+ });