@webdecoy/node 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,2715 +1,60 @@
1
- // src/client.ts
2
- var WebDecoyClient = class {
3
- constructor(config) {
4
- this.config = config;
5
- this.baseUrl = config.apiUrl.replace(/\/+$/, "");
6
- this.headers = {
7
- "Content-Type": "application/json",
8
- Authorization: `Bearer ${config.apiKey}`,
9
- "User-Agent": "webdecoy-node-sdk/0.1.0"
10
- };
11
- if (config.tlsRejectUnauthorized === false && config.debug) {
12
- console.warn(
13
- "[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."
14
- );
15
- }
16
- }
17
- async request(method, path, body) {
18
- const controller = new AbortController();
19
- const timer = setTimeout(() => controller.abort(), this.config.timeout);
20
- if (typeof timer.unref === "function") {
21
- timer.unref();
22
- }
23
- if (this.config.debug) {
24
- console.log("[WebDecoy] Request:", { method, url: this.baseUrl + path, data: body });
25
- }
26
- try {
27
- const response = await fetch(this.baseUrl + path, {
28
- method,
29
- headers: this.headers,
30
- body: body === void 0 ? void 0 : JSON.stringify(body),
31
- signal: controller.signal
32
- });
33
- let data;
34
- const text = await response.text();
35
- if (text) {
36
- try {
37
- data = JSON.parse(text);
38
- } catch {
39
- data = void 0;
40
- }
41
- }
42
- if (this.config.debug) {
43
- console.log("[WebDecoy] Response:", { status: response.status, data });
44
- }
45
- return { status: response.status, data };
46
- } catch (error) {
47
- if (this.config.debug) {
48
- console.error("[WebDecoy] Error:", {
49
- message: error instanceof Error ? error.message : String(error)
50
- });
51
- }
52
- throw error;
53
- } finally {
54
- clearTimeout(timer);
55
- }
56
- }
57
- /**
58
- * Send a detection request to the ingest service
59
- */
60
- async detect(request) {
61
- let response;
62
- try {
63
- response = await this.request(
64
- "POST",
65
- "/api/v1/sdk/detect",
66
- request
67
- );
68
- } catch (error) {
69
- if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) {
70
- throw new Error("Request timeout. The Web Decoy service did not respond in time.");
71
- }
72
- if (error instanceof TypeError) {
73
- throw new Error("Unable to connect to Web Decoy service. Please check your network.");
74
- }
75
- throw error;
76
- }
77
- if (response.status === 401) {
78
- throw new Error("Invalid API key. Please check your Web Decoy configuration.");
79
- }
80
- if (response.status === 429) {
81
- throw new Error("Rate limit exceeded. Please try again later.");
82
- }
83
- if (response.status >= 400) {
84
- if (response.data?.error || response.data?.message) {
85
- throw new Error(response.data.error || response.data.message || "API error");
86
- }
87
- throw new Error(`API request failed: HTTP ${response.status}`);
88
- }
89
- return response.data;
90
- }
91
- /**
92
- * Send violation events to the ingest service
93
- */
94
- async sendViolations(events) {
95
- try {
96
- await this.request("POST", "/api/v1/sdk/violations/batch", { events });
97
- } catch (error) {
98
- if (this.config.debug) {
99
- console.error("[WebDecoy] Failed to send violations:", error);
100
- }
101
- }
102
- }
103
- /**
104
- * Get IP enrichment data from the ingest service
105
- */
106
- async getIPEnrichment(ip) {
107
- try {
108
- const response = await this.request(
109
- "GET",
110
- `/api/v1/sdk/ip/${encodeURIComponent(ip)}/enrichment`
111
- );
112
- if (response.status >= 400) return null;
113
- return response.data ?? null;
114
- } catch (error) {
115
- if (this.config.debug) {
116
- console.error("[WebDecoy] Failed to get IP enrichment:", error);
117
- }
118
- return null;
119
- }
120
- }
121
- /**
122
- * Validate the API key by making a test request
123
- */
124
- async validateAPIKey() {
125
- try {
126
- const testRequest = {
127
- request_metadata: {
128
- method: "GET",
129
- path: "/__webdecoy_test__",
130
- ip: "127.0.0.1",
131
- headers: {},
132
- timestamp: Date.now()
133
- },
134
- local_analysis: {
135
- suspicious_headers: false,
136
- missing_sec_ch_ua: false,
137
- datacenter_ip: false,
138
- local_score: 0,
139
- needs_verification: false,
140
- flags: ["api_key_validation"]
141
- }
142
- };
143
- await this.detect(testRequest);
144
- return true;
145
- } catch (error) {
146
- if (error instanceof Error && error.message.includes("Invalid API key")) {
147
- return false;
148
- }
149
- return true;
150
- }
151
- }
152
- };
153
-
154
- // src/local-analysis.ts
155
- var DATACENTER_RANGES = [
156
- // AWS
157
- "3.0.0.0/8",
158
- "13.0.0.0/8",
159
- "18.0.0.0/8",
160
- "52.0.0.0/8",
161
- "54.0.0.0/8",
162
- // Google Cloud
163
- "34.0.0.0/8",
164
- "35.0.0.0/8",
165
- // Azure
166
- "13.64.0.0/11",
167
- "20.0.0.0/8",
168
- "40.0.0.0/8",
169
- "104.0.0.0/8",
170
- // DigitalOcean
171
- "159.65.0.0/16",
172
- "178.62.0.0/16",
173
- // Hetzner
174
- "88.99.0.0/16",
175
- "116.203.0.0/16"
176
- ];
177
- var SUSPICIOUS_PATTERNS = {
178
- userAgents: [
179
- /bot/i,
180
- /crawler/i,
181
- /spider/i,
182
- /scraper/i,
183
- /curl/i,
184
- /wget/i,
185
- /python/i,
186
- /java/i,
187
- /go-http-client/i,
188
- /axios/i,
189
- /okhttp/i
190
- ],
191
- missingHeaders: [
192
- "accept",
193
- "accept-language",
194
- "accept-encoding"
195
- ]
196
- };
197
- function isIPInRange(ip, cidr) {
198
- const ipParts = ip.split(".").map(Number);
199
- const [range, bits] = cidr.split("/");
200
- const rangeParts = range.split(".").map(Number);
201
- const mask = ~(2 ** (32 - parseInt(bits)) - 1);
202
- const ipNum = (ipParts[0] << 24) + (ipParts[1] << 16) + (ipParts[2] << 8) + ipParts[3];
203
- const rangeNum = (rangeParts[0] << 24) + (rangeParts[1] << 16) + (rangeParts[2] << 8) + rangeParts[3];
204
- return (ipNum & mask) === (rangeNum & mask);
205
- }
206
- function isDatacenterIP(ip) {
207
- if (ip.includes(":")) {
208
- return false;
209
- }
210
- return DATACENTER_RANGES.some((range) => isIPInRange(ip, range));
211
- }
212
- function hasSuspiciousHeaders(metadata) {
213
- const userAgent = metadata.user_agent || "";
214
- const headers = metadata.headers || {};
215
- const hasBotUA = SUSPICIOUS_PATTERNS.userAgents.some((pattern) => pattern.test(userAgent));
216
- const missingCommonHeaders = SUSPICIOUS_PATTERNS.missingHeaders.filter(
217
- (header) => !headers[header] && !headers[header.toLowerCase()]
218
- );
219
- return hasBotUA || missingCommonHeaders.length > 0;
220
- }
221
- function isMissingSecCHUA(metadata) {
222
- const headers = metadata.headers || {};
223
- return !headers["sec-ch-ua"] && !headers["Sec-CH-UA"];
224
- }
225
- function calculateLocalScore(suspiciousHeaders, missingSecCHUA, datacenterIP) {
226
- let score = 0;
227
- if (suspiciousHeaders) score += 30;
228
- if (missingSecCHUA) score += 20;
229
- if (datacenterIP) score += 40;
230
- return Math.min(score, 100);
231
- }
232
- function needsVerification(localScore, hasTLSInfo) {
233
- if (hasTLSInfo) {
234
- return true;
235
- }
236
- return localScore >= 30;
237
- }
238
- function buildFlags(suspiciousHeaders, missingSecCHUA, datacenterIP, metadata) {
239
- const flags = [];
240
- if (suspiciousHeaders) {
241
- flags.push("suspicious_headers");
242
- }
243
- if (missingSecCHUA) {
244
- flags.push("missing_sec_ch_ua");
245
- }
246
- if (datacenterIP) {
247
- flags.push("datacenter_ip");
248
- }
249
- const headerCount = Object.keys(metadata.headers || {}).length;
250
- if (headerCount < 5) {
251
- flags.push("minimal_headers");
252
- }
253
- if (!metadata.headers?.referer && !metadata.headers?.Referer) {
254
- flags.push("missing_referer");
255
- }
256
- return flags;
257
- }
258
- function analyzeRequest(metadata) {
259
- const suspiciousHeaders = hasSuspiciousHeaders(metadata);
260
- const missingSecCHUA = isMissingSecCHUA(metadata);
261
- const datacenterIP = isDatacenterIP(metadata.ip);
262
- const localScore = calculateLocalScore(suspiciousHeaders, missingSecCHUA, datacenterIP);
263
- const hasTLSInfo = Boolean(metadata.tls_info);
264
- const needsVerify = needsVerification(localScore, hasTLSInfo);
265
- const flags = buildFlags(suspiciousHeaders, missingSecCHUA, datacenterIP, metadata);
266
- return {
267
- suspicious_headers: suspiciousHeaders,
268
- missing_sec_ch_ua: missingSecCHUA,
269
- datacenter_ip: datacenterIP,
270
- local_score: localScore,
271
- needs_verification: needsVerify,
272
- flags
273
- };
274
- }
275
-
276
- // src/rules/rule-engine.ts
277
- function extractClearance(headers) {
278
- const cookie = headers["cookie"];
279
- if (!cookie) return void 0;
280
- for (const part of cookie.split(";")) {
281
- const eq = part.indexOf("=");
282
- if (eq < 0) continue;
283
- if (part.slice(0, eq).trim() === "wd_clearance") {
284
- return part.slice(eq + 1).trim() || void 0;
285
- }
286
- }
287
- return void 0;
288
- }
289
- var RuleEngine = class {
290
- constructor(rules) {
291
- this.rules = rules;
292
- }
293
- /**
294
- * Append a rule after construction.
295
- *
296
- * Exists for signals that cannot be known synchronously at construction —
297
- * currently the site honeytoken, whose path is derived by async HMAC.
298
- * Evaluation order is append order, matching the constructor.
299
- */
300
- add(rule) {
301
- this.rules.push(rule);
302
- }
303
- /**
304
- * Evaluate all rules against the request context.
305
- * First DENY or THROTTLE result wins. Violations are recorded for all non-ALLOW results.
306
- */
307
- evaluate(context) {
308
- const violations = [];
309
- let decidingResult = null;
310
- for (const rule of this.rules) {
311
- const result = rule.evaluate(context);
312
- if (result.action !== "ALLOW") {
313
- violations.push({
314
- rule: result.rule,
315
- action: result.action,
316
- ip: context.ip,
317
- path: context.path,
318
- method: context.method,
319
- userAgent: context.userAgent,
320
- reason: result.reason,
321
- clearance: result.rule === "tripwire" ? extractClearance(context.headers) : void 0,
322
- metadata: result.metadata,
323
- dryRun: result.metadata?.dryRun === true,
324
- timestamp: new Date(context.timestamp).toISOString()
325
- });
326
- if (!decidingResult && !result.metadata?.dryRun) {
327
- decidingResult = result;
328
- }
329
- }
330
- }
331
- if (decidingResult) {
332
- return {
333
- action: decidingResult.action,
334
- rule: decidingResult.rule,
335
- reason: decidingResult.reason,
336
- metadata: decidingResult.metadata,
337
- violations
338
- };
339
- }
340
- return {
341
- action: "ALLOW",
342
- violations
343
- };
344
- }
345
- /**
346
- * Clean up all rule resources
347
- */
348
- destroy() {
349
- for (const rule of this.rules) {
350
- rule.destroy?.();
351
- }
352
- }
353
- };
354
-
355
- // src/rules/rate-limiter.ts
356
- var InMemoryRateLimiter = class {
357
- constructor() {
358
- this.fixedWindows = /* @__PURE__ */ new Map();
359
- this.slidingWindows = /* @__PURE__ */ new Map();
360
- this.cleanupTimer = setInterval(() => this.cleanup(), 6e4);
361
- if (this.cleanupTimer.unref) {
362
- this.cleanupTimer.unref();
363
- }
364
- }
365
- /**
366
- * Check and increment for fixed window algorithm
367
- * Returns the current count after increment, and the window reset time
368
- */
369
- checkFixedWindow(key, max, windowMs) {
370
- const now = Date.now();
371
- const entry = this.fixedWindows.get(key);
372
- if (!entry || now - entry.windowStart >= windowMs) {
373
- this.fixedWindows.set(key, { count: 1, windowStart: now });
374
- return { allowed: true, current: 1, resetAt: now + windowMs };
375
- }
376
- entry.count++;
377
- const resetAt = entry.windowStart + windowMs;
378
- if (entry.count > max) {
379
- return { allowed: false, current: entry.count, resetAt };
380
- }
381
- return { allowed: true, current: entry.count, resetAt };
382
- }
383
- /**
384
- * Check and increment for sliding window algorithm
385
- * Returns the current count after adding the new timestamp
386
- */
387
- checkSlidingWindow(key, max, windowMs) {
388
- const now = Date.now();
389
- const cutoff = now - windowMs;
390
- let timestamps = this.slidingWindows.get(key);
391
- if (!timestamps) {
392
- timestamps = [];
393
- this.slidingWindows.set(key, timestamps);
394
- }
395
- while (timestamps.length > 0 && timestamps[0] <= cutoff) {
396
- timestamps.shift();
397
- }
398
- timestamps.push(now);
399
- const resetAt = timestamps.length > 0 ? timestamps[0] + windowMs : now + windowMs;
400
- if (timestamps.length > max) {
401
- return { allowed: false, current: timestamps.length, resetAt };
402
- }
403
- return { allowed: true, current: timestamps.length, resetAt };
404
- }
405
- /**
406
- * Clean up expired entries from both maps
407
- */
408
- cleanup() {
409
- const now = Date.now();
410
- for (const [key, entry] of this.fixedWindows) {
411
- if (now - entry.windowStart > 3e5) {
412
- this.fixedWindows.delete(key);
413
- }
414
- }
415
- for (const [key, timestamps] of this.slidingWindows) {
416
- if (timestamps.length === 0) {
417
- this.slidingWindows.delete(key);
418
- continue;
419
- }
420
- const latest = timestamps[timestamps.length - 1];
421
- if (now - latest > 3e5) {
422
- this.slidingWindows.delete(key);
423
- }
424
- }
425
- }
426
- /**
427
- * Release resources
428
- */
429
- destroy() {
430
- clearInterval(this.cleanupTimer);
431
- this.fixedWindows.clear();
432
- this.slidingWindows.clear();
433
- }
434
- };
435
-
436
- // src/rules/rate-limit-rule.ts
437
- var RateLimitRule = class {
438
- constructor(config) {
439
- this.name = `rate-limit:${config.max}/${config.window}s`;
440
- this.limiter = new InMemoryRateLimiter();
441
- this.config = {
442
- max: config.max,
443
- window: config.window,
444
- algorithm: config.algorithm ?? "fixed",
445
- keyBy: config.keyBy,
446
- action: config.action ?? "THROTTLE",
447
- dryRun: config.dryRun ?? false
448
- };
449
- }
450
- evaluate(context) {
451
- const key = this.config.keyBy ? this.config.keyBy(context) : context.ip;
452
- const windowMs = this.config.window * 1e3;
453
- const result = this.config.algorithm === "sliding" ? this.limiter.checkSlidingWindow(key, this.config.max, windowMs) : this.limiter.checkFixedWindow(key, this.config.max, windowMs);
454
- if (!result.allowed) {
455
- const retryAfter = Math.ceil((result.resetAt - Date.now()) / 1e3);
456
- return {
457
- action: this.config.dryRun ? "ALLOW" : this.config.action,
458
- rule: this.name,
459
- reason: `Rate limit exceeded: ${result.current}/${this.config.max} requests in ${this.config.window}s window`,
460
- metadata: {
461
- current: result.current,
462
- max: this.config.max,
463
- window: this.config.window,
464
- retryAfter: Math.max(retryAfter, 1),
465
- dryRun: this.config.dryRun
466
- }
467
- };
468
- }
469
- return {
470
- action: "ALLOW",
471
- rule: this.name,
472
- metadata: {
473
- current: result.current,
474
- max: this.config.max,
475
- remaining: this.config.max - result.current
476
- }
477
- };
478
- }
479
- destroy() {
480
- this.limiter.destroy();
481
- }
482
- };
483
-
484
- // src/rules/filter/tokenizer.ts
485
- var KEYWORDS = {
486
- and: "AND" /* AND */,
487
- or: "OR" /* OR */,
488
- not: "NOT" /* NOT */,
489
- in: "IN" /* IN */,
490
- matches: "MATCHES" /* MATCHES */,
491
- true: "BOOL" /* BOOL */,
492
- false: "BOOL" /* BOOL */
493
- };
494
- var Tokenizer = class {
495
- constructor(source) {
496
- this.pos = 0;
497
- this.tokens = [];
498
- this.source = source;
499
- }
500
- tokenize() {
501
- while (this.pos < this.source.length) {
502
- this.skipWhitespace();
503
- if (this.pos >= this.source.length) break;
504
- const ch = this.source[this.pos];
505
- if (ch === ".") {
506
- this.tokens.push({ type: "DOT" /* DOT */, value: ".", position: this.pos });
507
- this.pos++;
508
- continue;
509
- }
510
- if (ch === "(") {
511
- this.tokens.push({ type: "LPAREN" /* LPAREN */, value: "(", position: this.pos });
512
- this.pos++;
513
- continue;
514
- }
515
- if (ch === ")") {
516
- this.tokens.push({ type: "RPAREN" /* RPAREN */, value: ")", position: this.pos });
517
- this.pos++;
518
- continue;
519
- }
520
- if (ch === "[") {
521
- this.tokens.push({ type: "LBRACKET" /* LBRACKET */, value: "[", position: this.pos });
522
- this.pos++;
523
- continue;
524
- }
525
- if (ch === "]") {
526
- this.tokens.push({ type: "RBRACKET" /* RBRACKET */, value: "]", position: this.pos });
527
- this.pos++;
528
- continue;
529
- }
530
- if (ch === ",") {
531
- this.tokens.push({ type: "COMMA" /* COMMA */, value: ",", position: this.pos });
532
- this.pos++;
533
- continue;
534
- }
535
- if (ch === "=" && this.peek(1) === "=") {
536
- this.tokens.push({ type: "EQ" /* EQ */, value: "==", position: this.pos });
537
- this.pos += 2;
538
- continue;
539
- }
540
- if (ch === "!" && this.peek(1) === "=") {
541
- this.tokens.push({ type: "NEQ" /* NEQ */, value: "!=", position: this.pos });
542
- this.pos += 2;
543
- continue;
544
- }
545
- if (ch === ">" && this.peek(1) === "=") {
546
- this.tokens.push({ type: "GTE" /* GTE */, value: ">=", position: this.pos });
547
- this.pos += 2;
548
- continue;
549
- }
550
- if (ch === "<" && this.peek(1) === "=") {
551
- this.tokens.push({ type: "LTE" /* LTE */, value: "<=", position: this.pos });
552
- this.pos += 2;
553
- continue;
554
- }
555
- if (ch === ">") {
556
- this.tokens.push({ type: "GT" /* GT */, value: ">", position: this.pos });
557
- this.pos++;
558
- continue;
559
- }
560
- if (ch === "<") {
561
- this.tokens.push({ type: "LT" /* LT */, value: "<", position: this.pos });
562
- this.pos++;
563
- continue;
564
- }
565
- if (ch === '"' || ch === "'") {
566
- this.readString(ch);
567
- continue;
568
- }
569
- if (this.isDigit(ch) || ch === "-" && this.isDigit(this.peek(1))) {
570
- this.readNumber();
571
- continue;
572
- }
573
- if (this.isIdentStart(ch)) {
574
- this.readIdent();
575
- continue;
576
- }
577
- throw new Error(`Unexpected character '${ch}' at position ${this.pos}`);
578
- }
579
- this.tokens.push({ type: "EOF" /* EOF */, value: "", position: this.pos });
580
- return this.tokens;
581
- }
582
- peek(offset) {
583
- const idx = this.pos + offset;
584
- return idx < this.source.length ? this.source[idx] : "";
585
- }
586
- skipWhitespace() {
587
- while (this.pos < this.source.length && /\s/.test(this.source[this.pos])) {
588
- this.pos++;
589
- }
590
- }
591
- readString(quote) {
592
- const start = this.pos;
593
- this.pos++;
594
- let value = "";
595
- while (this.pos < this.source.length && this.source[this.pos] !== quote) {
596
- if (this.source[this.pos] === "\\") {
597
- this.pos++;
598
- }
599
- value += this.source[this.pos];
600
- this.pos++;
601
- }
602
- if (this.pos >= this.source.length) {
603
- throw new Error(`Unterminated string at position ${start}`);
604
- }
605
- this.pos++;
606
- this.tokens.push({ type: "STRING" /* STRING */, value, position: start });
607
- }
608
- readNumber() {
609
- const start = this.pos;
610
- if (this.source[this.pos] === "-") this.pos++;
611
- while (this.pos < this.source.length && this.isDigit(this.source[this.pos])) {
612
- this.pos++;
613
- }
614
- if (this.pos < this.source.length && this.source[this.pos] === ".") {
615
- this.pos++;
616
- while (this.pos < this.source.length && this.isDigit(this.source[this.pos])) {
617
- this.pos++;
618
- }
619
- }
620
- this.tokens.push({ type: "NUMBER" /* NUMBER */, value: this.source.slice(start, this.pos), position: start });
621
- }
622
- readIdent() {
623
- const start = this.pos;
624
- while (this.pos < this.source.length && this.isIdentPart(this.source[this.pos])) {
625
- this.pos++;
626
- }
627
- const value = this.source.slice(start, this.pos);
628
- const keyword = KEYWORDS[value.toLowerCase()];
629
- if (keyword) {
630
- this.tokens.push({ type: keyword, value: value.toLowerCase(), position: start });
631
- } else {
632
- this.tokens.push({ type: "IDENT" /* IDENT */, value, position: start });
633
- }
634
- }
635
- isDigit(ch) {
636
- return ch >= "0" && ch <= "9";
637
- }
638
- isIdentStart(ch) {
639
- return /[a-zA-Z_]/.test(ch);
640
- }
641
- isIdentPart(ch) {
642
- return /[a-zA-Z0-9_]/.test(ch);
643
- }
644
- };
645
-
646
- // src/rules/filter/parser.ts
647
- var Parser = class {
648
- constructor(source) {
649
- this.pos = 0;
650
- this.tokens = new Tokenizer(source).tokenize();
651
- }
652
- parse() {
653
- const ast = this.orExpr();
654
- this.expect("EOF" /* EOF */, "Expected end of expression");
655
- return ast;
656
- }
657
- orExpr() {
658
- let left = this.andExpr();
659
- while (this.match("OR" /* OR */)) {
660
- const right = this.andExpr();
661
- left = { kind: "binary", op: "or", left, right };
662
- }
663
- return left;
664
- }
665
- andExpr() {
666
- let left = this.unary();
667
- while (this.match("AND" /* AND */)) {
668
- const right = this.unary();
669
- left = { kind: "binary", op: "and", left, right };
670
- }
671
- return left;
672
- }
673
- unary() {
674
- if (this.match("NOT" /* NOT */)) {
675
- if (this.check("IN" /* IN */)) {
676
- this.pos--;
677
- return this.comparison();
678
- }
679
- const operand = this.unary();
680
- return { kind: "unary", op: "not", operand };
681
- }
682
- return this.comparison();
683
- }
684
- comparison() {
685
- const left = this.primary();
686
- if (this.match("EQ" /* EQ */)) return { kind: "binary", op: "==", left, right: this.primary() };
687
- if (this.match("NEQ" /* NEQ */)) return { kind: "binary", op: "!=", left, right: this.primary() };
688
- if (this.match("GT" /* GT */)) return { kind: "binary", op: ">", left, right: this.primary() };
689
- if (this.match("GTE" /* GTE */)) return { kind: "binary", op: ">=", left, right: this.primary() };
690
- if (this.match("LT" /* LT */)) return { kind: "binary", op: "<", left, right: this.primary() };
691
- if (this.match("LTE" /* LTE */)) return { kind: "binary", op: "<=", left, right: this.primary() };
692
- if (this.match("IN" /* IN */)) return { kind: "binary", op: "in", left, right: this.primary() };
693
- if (this.match("MATCHES" /* MATCHES */)) return { kind: "binary", op: "matches", left, right: this.primary() };
694
- if (this.check("NOT" /* NOT */) && this.checkAhead("IN" /* IN */)) {
695
- this.advance();
696
- this.advance();
697
- return { kind: "binary", op: "not in", left, right: this.primary() };
698
- }
699
- return left;
700
- }
701
- primary() {
702
- if (this.check("BOOL" /* BOOL */)) {
703
- const token = this.advance();
704
- return { kind: "bool", value: token.value === "true" };
705
- }
706
- if (this.check("NUMBER" /* NUMBER */)) {
707
- const token = this.advance();
708
- return { kind: "number", value: parseFloat(token.value) };
709
- }
710
- if (this.check("STRING" /* STRING */)) {
711
- const token = this.advance();
712
- return { kind: "string", value: token.value };
713
- }
714
- if (this.match("LBRACKET" /* LBRACKET */)) {
715
- const elements = [];
716
- if (!this.check("RBRACKET" /* RBRACKET */)) {
717
- elements.push(this.primary());
718
- while (this.match("COMMA" /* COMMA */)) {
719
- elements.push(this.primary());
720
- }
721
- }
722
- this.expect("RBRACKET" /* RBRACKET */, 'Expected "]"');
723
- return { kind: "array", elements };
724
- }
725
- if (this.match("LPAREN" /* LPAREN */)) {
726
- const expr = this.orExpr();
727
- this.expect("RPAREN" /* RPAREN */, 'Expected ")"');
728
- return expr;
729
- }
730
- if (this.check("IDENT" /* IDENT */)) {
731
- const path = [this.advance().value];
732
- while (this.match("DOT" /* DOT */)) {
733
- if (!this.check("IDENT" /* IDENT */)) {
734
- throw new Error(`Expected identifier after "." at position ${this.current().position}`);
735
- }
736
- path.push(this.advance().value);
737
- }
738
- if (this.match("LPAREN" /* LPAREN */)) {
739
- const method = path.pop();
740
- const args = [];
741
- if (!this.check("RPAREN" /* RPAREN */)) {
742
- args.push(this.primary());
743
- while (this.match("COMMA" /* COMMA */)) {
744
- args.push(this.primary());
745
- }
746
- }
747
- this.expect("RPAREN" /* RPAREN */, 'Expected ")"');
748
- return { kind: "call", object: path, method, args };
749
- }
750
- return { kind: "property", path };
751
- }
752
- throw new Error(`Unexpected token "${this.current().value}" at position ${this.current().position}`);
753
- }
754
- // Helper methods
755
- current() {
756
- return this.tokens[this.pos];
757
- }
758
- advance() {
759
- return this.tokens[this.pos++];
760
- }
761
- check(type) {
762
- return this.current().type === type;
763
- }
764
- checkAhead(type) {
765
- return this.pos + 1 < this.tokens.length && this.tokens[this.pos + 1].type === type;
766
- }
767
- match(type) {
768
- if (this.check(type)) {
769
- this.advance();
770
- return true;
771
- }
772
- return false;
773
- }
774
- expect(type, message) {
775
- if (this.check(type)) return this.advance();
776
- throw new Error(`${message}, got "${this.current().value}" at position ${this.current().position}`);
777
- }
778
- };
779
-
780
- // src/rules/filter/evaluator.ts
781
- var MAX_REGEX_LENGTH = 500;
782
- function evaluate(node, context) {
783
- switch (node.kind) {
784
- case "bool":
785
- return node.value;
786
- case "number":
787
- return node.value;
788
- case "string":
789
- return node.value;
790
- case "array":
791
- return node.elements.map((el) => evaluate(el, context));
792
- case "property":
793
- return resolveProperty(node.path, context);
794
- case "call":
795
- return resolveCall(node.object, node.method, node.args, context);
796
- case "unary":
797
- return evaluateUnary(node.op, node.operand, context);
798
- case "binary":
799
- return evaluateBinary(node.op, node.left, node.right, context);
800
- }
801
- }
802
- function resolveProperty(path, context) {
803
- const namespace = path[0];
804
- const prop = path.slice(1).join(".");
805
- if (namespace === "ip") {
806
- const e = context.enrichment;
807
- if (!e) return void 0;
808
- if (prop === "vpn") return e.security.vpn;
809
- if (prop === "proxy") return e.security.proxy;
810
- if (prop === "tor") return e.security.tor;
811
- if (prop === "relay") return e.security.relay;
812
- if (prop === "hosting") return e.security.hosting;
813
- if (prop === "country") return e.location.country;
814
- if (prop === "country_name") return e.location.country_name;
815
- if (prop === "city") return e.location.city;
816
- if (prop === "timezone") return e.location.timezone;
817
- if (prop === "asn") return e.network.asn;
818
- if (prop === "asn_org") return e.network.asn_org;
819
- if (prop === "abuse_score") return e.reputation.abuse_score;
820
- if (prop === "total_reports") return e.reputation.total_reports;
821
- if (prop === "is_high_risk") return e.reputation.is_high_risk;
822
- return void 0;
823
- }
824
- if (namespace === "req") {
825
- if (prop === "path") return context.path;
826
- if (prop === "method") return context.method;
827
- if (prop === "ip") return context.ip;
828
- if (prop === "user_agent") return context.userAgent;
829
- return void 0;
830
- }
831
- if (namespace === "edge") {
832
- const e = context.edge;
833
- if (!e) return void 0;
834
- if (prop === "present") return e.present;
835
- if (prop === "clearance") return e.clearance;
836
- if (prop === "class") return e.class;
837
- if (prop === "verified") return e.isVerified;
838
- if (prop === "crawler") return e.isCrawler;
839
- if (prop === "script") return e.isScript;
840
- if (prop === "browser") return e.isBrowser;
841
- return void 0;
842
- }
843
- if (namespace === "bot") {
844
- const b = context.bot;
845
- if (!b) return void 0;
846
- if (prop === "known") return b.known;
847
- if (prop === "ai") return b.isAI;
848
- if (!b.known) return void 0;
849
- if (prop === "id") return b.id;
850
- if (prop === "name") return b.name;
851
- if (prop === "category") return b.category;
852
- if (prop === "organization") return b.organization;
853
- if (prop === "score") return b.score;
854
- if (prop === "respects_robots") return b.respectsRobots;
855
- return void 0;
856
- }
857
- if (path.length === 1) return void 0;
858
- return void 0;
859
- }
860
- function resolveCall(object, method, args, context) {
861
- const namespace = object[0];
862
- if (namespace === "req" && method === "header") {
863
- if (args.length !== 1) return void 0;
864
- const headerName = evaluate(args[0], context);
865
- if (typeof headerName !== "string") return void 0;
866
- return context.headers[headerName.toLowerCase()];
867
- }
868
- return void 0;
869
- }
870
- function evaluateUnary(op, operand, context) {
871
- const val = evaluate(operand, context);
872
- if (op === "not") {
873
- if (val === void 0) return false;
874
- return !val;
875
- }
876
- return void 0;
877
- }
878
- function evaluateBinary(op, left, right, context) {
879
- if (op === "and") {
880
- const l2 = evaluate(left, context);
881
- if (l2 === void 0 || l2 === false) return false;
882
- const r2 = evaluate(right, context);
883
- if (r2 === void 0) return false;
884
- return !!r2;
885
- }
886
- if (op === "or") {
887
- const l2 = evaluate(left, context);
888
- if (l2 === void 0 ? false : !!l2) return true;
889
- const r2 = evaluate(right, context);
890
- if (r2 === void 0) return false;
891
- return !!r2;
892
- }
893
- const l = evaluate(left, context);
894
- const r = evaluate(right, context);
895
- if (l === void 0 || r === void 0) return false;
896
- switch (op) {
897
- case "==":
898
- return l === r;
899
- case "!=":
900
- return l !== r;
901
- case ">":
902
- return typeof l === "number" && typeof r === "number" && l > r;
903
- case ">=":
904
- return typeof l === "number" && typeof r === "number" && l >= r;
905
- case "<":
906
- return typeof l === "number" && typeof r === "number" && l < r;
907
- case "<=":
908
- return typeof l === "number" && typeof r === "number" && l <= r;
909
- case "in": {
910
- if (!Array.isArray(r)) return false;
911
- return r.includes(l);
912
- }
913
- case "not in": {
914
- if (!Array.isArray(r)) return false;
915
- return !r.includes(l);
916
- }
917
- case "matches": {
918
- if (typeof l !== "string" || typeof r !== "string") return false;
919
- if (r.length > MAX_REGEX_LENGTH) return false;
920
- try {
921
- return new RegExp(r).test(l);
922
- } catch {
923
- return false;
924
- }
925
- }
926
- default:
927
- return false;
928
- }
929
- }
930
-
931
- // src/rules/filter-rule.ts
932
- var FilterRule = class {
933
- constructor(config) {
934
- this.expression = config.expression;
935
- this.action = config.action ?? "DENY";
936
- this.dryRun = config.dryRun ?? false;
937
- this.name = `filter:${this.expression.slice(0, 50)}`;
938
- const parser = new Parser(config.expression);
939
- this.ast = parser.parse();
940
- }
941
- evaluate(context) {
942
- const result = evaluate(this.ast, context);
943
- if (result) {
944
- return {
945
- action: this.dryRun ? "ALLOW" : this.action,
946
- rule: this.name,
947
- reason: `Filter matched: ${this.expression}`,
948
- metadata: {
949
- expression: this.expression,
950
- dryRun: this.dryRun
951
- }
952
- };
953
- }
954
- return {
955
- action: "ALLOW",
956
- rule: this.name
957
- };
958
- }
959
- };
960
-
961
- // src/rules/tripwire-rule.ts
962
- var DEFAULT_TRIPWIRE_PATHS = [
963
- "/.git/config",
964
- "/.git/HEAD",
965
- "/.env",
966
- "/.env.local",
967
- "/.env.production",
968
- "/wp-config.php",
969
- "/config.php",
970
- "/.aws/credentials",
971
- "/.ssh/id_rsa",
972
- "/backup.zip",
973
- "/backup.sql",
974
- "/database.sql",
975
- "/dump.sql",
976
- "/.DS_Store",
977
- "/phpinfo.php",
978
- "/server-status",
979
- "/actuator/env",
980
- "/.vscode/sftp.json"
981
- ];
982
- function normalizePath(path) {
983
- return path.split("?")[0].split("#")[0];
984
- }
985
- var TripwireRule = class {
986
- constructor(config = {}) {
987
- this.name = "tripwire";
988
- const paths = [...config.paths ?? []];
989
- if (config.includeDefaults ?? true) paths.push(...DEFAULT_TRIPWIRE_PATHS);
990
- this.exact = new Set(paths);
991
- this.prefixes = config.prefixes ?? [];
992
- this.patterns = config.patterns ?? [];
993
- this.action = config.action ?? "DENY";
994
- this.dryRun = config.dryRun ?? false;
995
- }
996
- evaluate(context) {
997
- const path = normalizePath(context.path);
998
- const hit = this.exact.has(path) || this.prefixes.some((prefix) => path.startsWith(prefix)) || this.patterns.some((re) => re.test(path));
999
- if (hit) {
1000
- return {
1001
- action: this.dryRun ? "ALLOW" : this.action,
1002
- rule: this.name,
1003
- reason: `Tripwire hit: ${path} \u2014 hidden honeypot path, deterministic automated-intent signal`,
1004
- metadata: { path, dryRun: this.dryRun, confidence: 100 }
1005
- };
1006
- }
1007
- return { action: "ALLOW", rule: this.name };
1008
- }
1009
- };
1010
-
1011
- // src/rules/bot-rule.ts
1012
- var BotRule = class {
1013
- constructor(config = {}) {
1014
- this.name = "bots";
1015
- this.categories = new Set(config.categories ?? []);
1016
- this.agents = new Set((config.agents ?? []).map((a) => a.toLowerCase()));
1017
- this.ai = config.ai ?? false;
1018
- this.allow = new Set((config.allow ?? []).map((a) => a.toLowerCase()));
1019
- this.action = config.action ?? "DENY";
1020
- this.dryRun = config.dryRun ?? false;
1021
- }
1022
- evaluate(context) {
1023
- const bot = context.bot;
1024
- if (!bot?.known) return { action: "ALLOW", rule: this.name };
1025
- const id = bot.id?.toLowerCase();
1026
- const name = bot.name?.toLowerCase();
1027
- if (id && this.allow.has(id) || name && this.allow.has(name)) {
1028
- return { action: "ALLOW", rule: this.name };
1029
- }
1030
- const matched = this.ai && bot.isAI || this.categories.has(bot.category) || id !== void 0 && this.agents.has(id) || name !== void 0 && this.agents.has(name);
1031
- if (!matched) return { action: "ALLOW", rule: this.name };
1032
- return {
1033
- action: this.dryRun ? "ALLOW" : this.action,
1034
- rule: this.name,
1035
- reason: `${bot.name ?? "Bot"} (${bot.category}) matched a bot policy rule`,
1036
- metadata: {
1037
- bot: bot.id,
1038
- botName: bot.name,
1039
- category: bot.category,
1040
- organization: bot.organization,
1041
- dryRun: this.dryRun,
1042
- // Deliberately not 100. The match is a self-declared User-Agent, and a
1043
- // downstream consumer that treats this like a tripwire hit would be
1044
- // wrong: a tripwire proves behaviour, this repeats a claim.
1045
- confidence: 70
1046
- }
1047
- };
1048
- }
1049
- };
1050
-
1051
- // src/rules/web-bot-auth-rule.ts
1052
- var WebBotAuthRule = class {
1053
- constructor(config = {}) {
1054
- this.name = "web-bot-auth";
1055
- this.onImpersonation = config.onImpersonation ?? "DENY";
1056
- this.onClaimed = config.onClaimed ?? "ALLOW";
1057
- this.allowCategories = config.allowCategories ? new Set(config.allowCategories) : void 0;
1058
- this.dryRun = config.dryRun ?? false;
1059
- }
1060
- evaluate(context) {
1061
- const verdict = context.agent;
1062
- if (!verdict || verdict.status === "none") return this.allow();
1063
- if (verdict.status === "impersonation") {
1064
- return this.act(this.onImpersonation, "agent_impersonation", {
1065
- agentName: verdict.agentName,
1066
- category: verdict.category,
1067
- keyId: verdict.keyId,
1068
- detail: verdict.reason
1069
- });
1070
- }
1071
- if (verdict.status === "claimed") {
1072
- return this.act(this.onClaimed, "agent_unverifiable", {
1073
- keyId: verdict.keyId,
1074
- detail: verdict.reason
1075
- });
1076
- }
1077
- if (this.allowCategories && verdict.category && !this.allowCategories.has(verdict.category)) {
1078
- return this.act(this.onClaimed, "agent_category_not_allowed", {
1079
- agentName: verdict.agentName,
1080
- category: verdict.category,
1081
- keyId: verdict.keyId
1082
- });
1083
- }
1084
- return this.allow();
1085
- }
1086
- act(action, verdict, detail) {
1087
- if (action === "ALLOW") return this.allow();
1088
- return {
1089
- action: this.dryRun ? "ALLOW" : action,
1090
- rule: this.name,
1091
- reason: reasonFor(verdict),
1092
- metadata: { verdict, dryRun: this.dryRun, ...detail }
1093
- };
1094
- }
1095
- allow() {
1096
- return { action: "ALLOW", rule: this.name };
1097
- }
1098
- };
1099
- function reasonFor(verdict) {
1100
- switch (verdict) {
1101
- case "agent_impersonation":
1102
- return "Web Bot Auth signature failed verification (agent impersonation)";
1103
- case "agent_unverifiable":
1104
- return "Web Bot Auth signature could not be verified";
1105
- case "agent_category_not_allowed":
1106
- return "Verified agent category is not allowed";
1107
- default:
1108
- return "Web Bot Auth rule triggered";
1109
- }
1110
- }
1111
- function webBotAuth(config = {}) {
1112
- return new WebBotAuthRule(config);
1113
- }
1114
-
1115
- // src/webcrypto.ts
1116
- var encoder = new TextEncoder();
1117
- function toHex(bytes) {
1118
- let hex = "";
1119
- for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
1120
- return hex;
1121
- }
1122
- async function sha256Hex(data) {
1123
- const digest2 = await crypto.subtle.digest("SHA-256", encoder.encode(data));
1124
- return toHex(new Uint8Array(digest2));
1125
- }
1126
- async function hmacSha256Hex(secret, data) {
1127
- const key = await crypto.subtle.importKey(
1128
- "raw",
1129
- encoder.encode(secret),
1130
- { name: "HMAC", hash: "SHA-256" },
1131
- false,
1132
- ["sign"]
1133
- );
1134
- const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(data));
1135
- return toHex(new Uint8Array(sig));
1136
- }
1137
- function randomHex(bytes) {
1138
- const buf = new Uint8Array(bytes);
1139
- crypto.getRandomValues(buf);
1140
- return toHex(buf);
1141
- }
1142
- function timingSafeEqualStr(a, b) {
1143
- if (a.length !== b.length) return false;
1144
- let diff = 0;
1145
- for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
1146
- return diff === 0;
1147
- }
1148
- function base64urlEncode(data) {
1149
- const bytes = encoder.encode(data);
1150
- let binary = "";
1151
- for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1152
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1153
- }
1154
- function base64urlDecode(data) {
1155
- const b64 = data.replace(/-/g, "+").replace(/_/g, "/");
1156
- const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
1157
- const binary = atob(padded);
1158
- const bytes = new Uint8Array(binary.length);
1159
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1160
- return new TextDecoder().decode(bytes);
1161
- }
1162
- function fnv1a64Hex(data) {
1163
- const PRIME = 0x100000001b3n;
1164
- const MASK = 0xffffffffffffffffn;
1165
- let hash = 0xcbf29ce484222325n;
1166
- const bytes = encoder.encode(data);
1167
- for (let i = 0; i < bytes.length; i++) {
1168
- hash ^= BigInt(bytes[i]);
1169
- hash = hash * PRIME & MASK;
1170
- }
1171
- return hash.toString(16).padStart(16, "0");
1172
- }
1173
-
1174
- // src/rules/honeytoken.ts
1175
- function honeytoken(options = {}) {
1176
- const base = (options.basePath ?? "/__wd").replace(/\/+$/, "");
1177
- const token = options.token ?? randomHex(6);
1178
- const path = `${base}/${token}`;
1179
- const text = options.text ?? ".";
1180
- const linkHtml = `<a href="${path}" aria-hidden="true" tabindex="-1" rel="nofollow noindex" style="position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden">${text}</a>`;
1181
- return { path, linkHtml };
1182
- }
1183
-
1184
- // src/rules/honeytoken-site.ts
1185
- var HONEYTOKEN_BASE_PATH = "/__wd";
1186
- var TOKEN_LEN = 12;
1187
- function utcDay(offsetDays = 0) {
1188
- const d = new Date(Date.now() + offsetDays * 864e5);
1189
- return d.toISOString().slice(0, 10);
1190
- }
1191
- function escapeHtml(v) {
1192
- return v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1193
- }
1194
- function linkFor(path, text) {
1195
- text = escapeHtml(text);
1196
- return `<a href="${path}" aria-hidden="true" tabindex="-1" rel="nofollow noindex" style="position:absolute;left:-9999px;top:auto;width:1px;height:1px;overflow:hidden">${text}</a>`;
1197
- }
1198
- var HIDDEN_STYLE = {
1199
- position: "absolute",
1200
- left: "-9999px",
1201
- top: "auto",
1202
- width: "1px",
1203
- height: "1px",
1204
- overflow: "hidden"
1205
- };
1206
- function propsFor(path, text) {
1207
- return {
1208
- href: path,
1209
- rel: "nofollow noindex",
1210
- tabIndex: -1,
1211
- "aria-hidden": "true",
1212
- style: HIDDEN_STYLE,
1213
- text
1214
- };
1215
- }
1216
- async function siteHoneytoken(options) {
1217
- const base = (options.basePath ?? HONEYTOKEN_BASE_PATH).replace(/\/+$/, "");
1218
- const text = options.text ?? ".";
1219
- const derive = async (label) => `${base}/${(await hmacSha256Hex(options.secret, label)).slice(0, TOKEN_LEN)}`;
1220
- if (!options.rotate) {
1221
- const path = await derive("stable");
1222
- return {
1223
- primaryPath: path,
1224
- activePaths: [path],
1225
- linkHtml: linkFor(path, text),
1226
- linkProps: propsFor(path, text)
1227
- };
1228
- }
1229
- const today = await derive(`day:${utcDay(0)}`);
1230
- const yesterday = await derive(`day:${utcDay(-1)}`);
1231
- return {
1232
- primaryPath: today,
1233
- // Yesterday stays armed so a crawler that read the page before midnight and
1234
- // follows the link after it still trips.
1235
- activePaths: Array.from(/* @__PURE__ */ new Set([today, yesterday])),
1236
- linkHtml: linkFor(today, text),
1237
- linkProps: propsFor(today, text)
1238
- };
1239
- }
1240
- function injectHoneytokenLink(html, linkHtml) {
1241
- if (!html || html.includes(linkHtml)) return html;
1242
- const lower = html.toLowerCase();
1243
- for (const close of ["</body>", "</html>"]) {
1244
- const at = lower.lastIndexOf(close);
1245
- if (at !== -1) {
1246
- return html.slice(0, at) + linkHtml + html.slice(at);
1247
- }
1248
- }
1249
- return html;
1250
- }
1251
- function isInjectableHtml(contentType) {
1252
- if (!contentType) return false;
1253
- return contentType.toLowerCase().split(";")[0].trim() === "text/html";
1254
- }
1255
-
1256
- // src/rules/index.ts
1257
- function rateLimit(config) {
1258
- return new RateLimitRule(config);
1259
- }
1260
- function filter(config) {
1261
- return new FilterRule(config);
1262
- }
1263
- function tripwire(config = {}) {
1264
- return new TripwireRule(config);
1265
- }
1266
- function bots(config = {}) {
1267
- return new BotRule(config);
1268
- }
1269
-
1270
- // src/violation-reporter.ts
1271
- var ViolationReporter = class {
1272
- constructor(client, config = {}) {
1273
- this.buffer = [];
1274
- this.flushing = false;
1275
- this.client = client;
1276
- this.maxBufferSize = config.maxBufferSize ?? 50;
1277
- this.debug = config.debug ?? false;
1278
- const flushInterval = config.flushInterval ?? 5e3;
1279
- this.flushTimer = setInterval(() => this.flush(), flushInterval);
1280
- if (this.flushTimer.unref) {
1281
- this.flushTimer.unref();
1282
- }
1283
- }
1284
- /**
1285
- * Add violations to the buffer. Auto-flushes when buffer reaches maxBufferSize.
1286
- */
1287
- report(violations) {
1288
- this.buffer.push(...violations);
1289
- if (this.buffer.length >= this.maxBufferSize) {
1290
- this.flush().catch(() => {
1291
- });
1292
- }
1293
- }
1294
- /**
1295
- * Flush buffered violations to the backend
1296
- */
1297
- async flush() {
1298
- if (this.flushing || this.buffer.length === 0) return;
1299
- this.flushing = true;
1300
- const events = this.buffer.splice(0, this.buffer.length);
1301
- try {
1302
- for (let i = 0; i < events.length; i += 100) {
1303
- const batch = events.slice(i, i + 100);
1304
- await this.client.sendViolations(batch);
1305
- if (this.debug) {
1306
- console.log(`[WebDecoy] Flushed ${batch.length} violation events`);
1307
- }
1308
- }
1309
- } catch (error) {
1310
- if (this.debug) {
1311
- console.error("[WebDecoy] Failed to flush violations:", error);
1312
- }
1313
- } finally {
1314
- this.flushing = false;
1315
- }
1316
- }
1317
- /**
1318
- * Flush remaining events and stop the timer
1319
- */
1320
- async destroy() {
1321
- clearInterval(this.flushTimer);
1322
- await this.flush();
1323
- }
1324
- };
1325
-
1326
- // src/ip-enrichment.ts
1327
- var IPEnrichmentClient = class {
1328
- constructor(client, ttlMs = 36e5) {
1329
- this.cache = /* @__PURE__ */ new Map();
1330
- this.pending = /* @__PURE__ */ new Map();
1331
- this.client = client;
1332
- this.ttlMs = ttlMs;
1333
- }
1334
- /**
1335
- * Get enrichment data for an IP address.
1336
- * Returns cached data if available (1h TTL), otherwise fetches from API.
1337
- * Returns null if enrichment fails (fail-open).
1338
- */
1339
- async enrich(ip) {
1340
- const cached = this.cache.get(ip);
1341
- if (cached && cached.expiresAt > Date.now()) {
1342
- return cached.data;
1343
- }
1344
- const inflight = this.pending.get(ip);
1345
- if (inflight) {
1346
- return inflight;
1347
- }
1348
- const promise = this.fetchAndCache(ip);
1349
- this.pending.set(ip, promise);
1350
- try {
1351
- return await promise;
1352
- } finally {
1353
- this.pending.delete(ip);
1354
- }
1355
- }
1356
- async fetchAndCache(ip) {
1357
- const data = await this.client.getIPEnrichment(ip);
1358
- if (data) {
1359
- this.cache.set(ip, {
1360
- data,
1361
- expiresAt: Date.now() + this.ttlMs
1362
- });
1363
- }
1364
- return data;
1365
- }
1366
- /**
1367
- * Clear the cache
1368
- */
1369
- clearCache() {
1370
- this.cache.clear();
1371
- }
1372
- };
1373
-
1374
- // src/agent/thumbprint.ts
1375
- var encoder2 = new TextEncoder();
1376
- async function rsaThumbprint(n, e) {
1377
- return digest(`{"e":${JSON.stringify(e)},"kty":"RSA","n":${JSON.stringify(n)}}`);
1378
- }
1379
- async function okpThumbprint(crv, x) {
1380
- return digest(`{"crv":${JSON.stringify(crv)},"kty":"OKP","x":${JSON.stringify(x)}}`);
1381
- }
1382
- async function jwkThumbprint(k) {
1383
- switch (k.kty) {
1384
- case "OKP":
1385
- if (!k.crv || !k.x) throw new Error("thumbprint: OKP JWK missing crv or x");
1386
- return okpThumbprint(k.crv, k.x);
1387
- case "RSA":
1388
- if (!k.n || !k.e) throw new Error("thumbprint: RSA JWK missing n or e");
1389
- return rsaThumbprint(k.n, k.e);
1390
- default:
1391
- throw new Error(`thumbprint: unsupported kty ${JSON.stringify(k.kty)}`);
1392
- }
1393
- }
1394
- async function digest(canonical) {
1395
- const buf = await crypto.subtle.digest("SHA-256", encoder2.encode(canonical));
1396
- return base64urlBytes(new Uint8Array(buf));
1397
- }
1398
- function base64urlBytes(bytes) {
1399
- let binary = "";
1400
- for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1401
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1402
- }
1403
-
1404
- // src/agent/directory.ts
1405
- var WELL_KNOWN = "/.well-known/http-message-signatures-directory";
1406
- var COLD_RETRY_BACKOFF_MS = 3e4;
1407
- var DEFAULT_SIGNED_AGENT_DIRECTORIES = [
1408
- { name: "OpenAI", category: "ai_crawlers", directory: "https://operator.openai.com" },
1409
- { name: "OpenAI ChatGPT", category: "ai_crawlers", directory: "https://chatgpt.com" }
1410
- ];
1411
- var DirectoryCache = class {
1412
- constructor(opts) {
1413
- this.keys = /* @__PURE__ */ new Map();
1414
- this.refreshedAt = 0;
1415
- this.nextColdRetryAt = 0;
1416
- this.inflight = null;
1417
- /** Resolve a keyid to a verification key, fetching/refreshing as needed. */
1418
- this.resolveKey = async (keyId) => {
1419
- await this.ensureFresh();
1420
- return this.keys.get(keyId);
1421
- };
1422
- this.opts = opts;
1423
- }
1424
- /** Kick off a fetch without blocking — call at startup to warm the cache. */
1425
- prime() {
1426
- if (this.keys.size === 0 && Date.now() >= this.nextColdRetryAt) void this.refresh();
1427
- }
1428
- /** Number of keys currently cached (diagnostics/tests). */
1429
- get size() {
1430
- return this.keys.size;
1431
- }
1432
- async ensureFresh() {
1433
- const now = Date.now();
1434
- const stale = now - this.refreshedAt > this.opts.cacheTtlMs;
1435
- if (this.keys.size > 0) {
1436
- if (stale) void this.refresh();
1437
- return;
1438
- }
1439
- if (now < this.nextColdRetryAt) return;
1440
- await this.refresh();
1441
- }
1442
- /** Re-fetch every directory. De-duplicated: concurrent callers share one run. */
1443
- refresh() {
1444
- if (this.inflight) return this.inflight;
1445
- this.inflight = this.doRefresh().finally(() => {
1446
- this.inflight = null;
1447
- });
1448
- return this.inflight;
1449
- }
1450
- async doRefresh() {
1451
- const results = await Promise.all(
1452
- this.opts.directories.map((src) => this.fetchDirectory(src))
1453
- );
1454
- const next = new Map(this.keys);
1455
- let fetchedAny = false;
1456
- for (const keys of results) {
1457
- if (keys === null) continue;
1458
- fetchedAny = true;
1459
- for (const k of keys) next.set(k.thumbprint, k.key);
1460
- }
1461
- if (fetchedAny) {
1462
- this.keys = next;
1463
- this.refreshedAt = Date.now();
1464
- this.nextColdRetryAt = 0;
1465
- this.debug(`refreshed: ${this.keys.size} key(s) across ${this.opts.directories.length} directories`);
1466
- } else if (this.keys.size === 0) {
1467
- this.nextColdRetryAt = Date.now() + COLD_RETRY_BACKOFF_MS;
1468
- this.debug("all directories unreachable; backing off cold retry");
1469
- }
1470
- }
1471
- async fetchDirectory(src) {
1472
- const url = directoryUrl(src.directory);
1473
- const controller = new AbortController();
1474
- const timer = setTimeout(() => controller.abort(), this.opts.fetchTimeoutMs);
1475
- try {
1476
- const res = await this.opts.fetchImpl(url, {
1477
- signal: controller.signal,
1478
- headers: {
1479
- Accept: "application/http-message-signatures-directory+json, application/jwk-set+json, application/json"
1480
- },
1481
- redirect: "follow"
1482
- });
1483
- if (!res.ok) {
1484
- this.debug(`${src.name}: HTTP ${res.status}`);
1485
- return null;
1486
- }
1487
- const body = await res.json();
1488
- if (!body || !Array.isArray(body.keys)) {
1489
- this.debug(`${src.name}: no keys in directory`);
1490
- return null;
1491
- }
1492
- const out = [];
1493
- for (const jwk of body.keys) {
1494
- const resolved = await importKey(jwk, src);
1495
- if (resolved) out.push(resolved);
1496
- }
1497
- this.debug(`${src.name}: ${out.length} key(s)`);
1498
- return out;
1499
- } catch (err) {
1500
- this.debug(`${src.name}: fetch failed \u2014 ${err.message}`);
1501
- return null;
1502
- } finally {
1503
- clearTimeout(timer);
1504
- }
1505
- }
1506
- debug(msg) {
1507
- if (this.opts.debug) console.log(`[WebDecoy][web-bot-auth] ${msg}`);
1508
- }
1509
- };
1510
- function directoryUrl(directory) {
1511
- const u = new URL(directory);
1512
- if (u.pathname && u.pathname !== "/") return u.toString();
1513
- u.pathname = WELL_KNOWN;
1514
- return u.toString();
1515
- }
1516
- async function importKey(jwk, src) {
1517
- try {
1518
- let cryptoKey;
1519
- let verifyParams;
1520
- let algorithm;
1521
- if (jwk.kty === "OKP") {
1522
- if (jwk.crv !== "Ed25519" || !jwk.x) return null;
1523
- cryptoKey = await crypto.subtle.importKey(
1524
- "jwk",
1525
- { kty: "OKP", crv: "Ed25519", x: jwk.x },
1526
- { name: "Ed25519" },
1527
- false,
1528
- ["verify"]
1529
- );
1530
- verifyParams = { name: "Ed25519" };
1531
- algorithm = "ed25519";
1532
- } else if (jwk.kty === "RSA") {
1533
- if (!jwk.n || !jwk.e) return null;
1534
- cryptoKey = await crypto.subtle.importKey(
1535
- "jwk",
1536
- { kty: "RSA", n: jwk.n, e: jwk.e },
1537
- { name: "RSA-PSS", hash: "SHA-512" },
1538
- false,
1539
- ["verify"]
1540
- );
1541
- verifyParams = { name: "RSA-PSS", saltLength: 64 };
1542
- algorithm = "rsa-pss-sha512";
1543
- } else {
1544
- return null;
1545
- }
1546
- const thumbprint = await jwkThumbprint(jwk);
1547
- return {
1548
- thumbprint,
1549
- key: {
1550
- cryptoKey,
1551
- verifyParams,
1552
- algorithm,
1553
- name: src.name,
1554
- category: src.category,
1555
- nbf: normalizeEpoch(jwk.nbf),
1556
- exp: normalizeEpoch(jwk.exp)
1557
- }
1558
- };
1559
- } catch {
1560
- return null;
1561
- }
1562
- }
1563
- function normalizeEpoch(v) {
1564
- if (v === void 0 || v === 0) return void 0;
1565
- return v > 1e12 ? Math.floor(v / 1e3) : v;
1566
- }
1567
-
1568
- // src/agent/sfv.ts
1569
- var Cursor = class {
1570
- constructor(s, i = 0) {
1571
- this.s = s;
1572
- this.i = i;
1573
- }
1574
- eof() {
1575
- return this.i >= this.s.length;
1576
- }
1577
- peek() {
1578
- return this.s[this.i];
1579
- }
1580
- skipSP() {
1581
- while (!this.eof() && (this.peek() === " " || this.peek() === " ")) this.i++;
1582
- }
1583
- };
1584
- function parseDictionary(input) {
1585
- const p = new Cursor(input);
1586
- const out = [];
1587
- p.skipSP();
1588
- while (!p.eof()) {
1589
- const key = parseKey(p);
1590
- const entry = { key, raw: "", isList: false, items: [], params: /* @__PURE__ */ new Map() };
1591
- if (!p.eof() && p.peek() === "=") {
1592
- p.i++;
1593
- const start = p.i;
1594
- if (!p.eof() && p.peek() === "(") {
1595
- entry.isList = true;
1596
- parseInnerList(p, entry);
1597
- } else {
1598
- entry.items.push(parseItem(p));
1599
- entry.params = entry.items[0].params;
1600
- }
1601
- entry.raw = input.slice(start, p.i);
1602
- } else {
1603
- entry.params = parseParams(p);
1604
- entry.items.push({ value: true, params: /* @__PURE__ */ new Map() });
1605
- entry.raw = "?1";
1606
- }
1607
- out.push(entry);
1608
- p.skipSP();
1609
- if (p.eof()) break;
1610
- if (p.peek() !== ",") throw new Error(`sfv: expected ',' at ${p.i}`);
1611
- p.i++;
1612
- p.skipSP();
1613
- if (p.eof()) throw new Error("sfv: trailing comma");
1614
- }
1615
- return out;
1616
- }
1617
- function parseInnerList(p, entry) {
1618
- p.i++;
1619
- for (; ; ) {
1620
- p.skipSP();
1621
- if (p.eof()) throw new Error("sfv: unterminated inner list");
1622
- if (p.peek() === ")") {
1623
- p.i++;
1624
- break;
1625
- }
1626
- entry.items.push(parseItem(p));
1627
- if (p.eof()) throw new Error("sfv: unterminated inner list");
1628
- const c = p.peek();
1629
- if (c !== " " && c !== ")") throw new Error(`sfv: bad inner list at ${p.i}`);
1630
- }
1631
- entry.params = parseParams(p);
1632
- }
1633
- function parseItem(p) {
1634
- const { value, bytes } = parseBareItem(p);
1635
- const params = parseParams(p);
1636
- return bytes ? { value, params, bytes } : { value, params };
1637
- }
1638
- function parseParams(p) {
1639
- const params = /* @__PURE__ */ new Map();
1640
- while (!p.eof() && p.peek() === ";") {
1641
- p.i++;
1642
- p.skipSP();
1643
- const key = parseKey(p);
1644
- let val = true;
1645
- if (!p.eof() && p.peek() === "=") {
1646
- p.i++;
1647
- val = parseBareItem(p).value;
1648
- }
1649
- params.set(key, val);
1650
- }
1651
- return params;
1652
- }
1653
- function parseKey(p) {
1654
- const c = p.peek();
1655
- if (!c || !/[a-z*]/.test(c)) throw new Error(`sfv: invalid key at ${p.i}`);
1656
- const start = p.i;
1657
- while (!p.eof() && /[a-z0-9_\-.*]/.test(p.peek())) p.i++;
1658
- return p.s.slice(start, p.i);
1659
- }
1660
- function parseBareItem(p) {
1661
- const c = p.peek();
1662
- if (c === '"') return { value: parseString(p) };
1663
- if (c === ":") return { value: "", bytes: parseByteSequence(p) };
1664
- if (c === "?") {
1665
- p.i++;
1666
- const b = p.s[p.i++];
1667
- if (b === "1") return { value: true };
1668
- if (b === "0") return { value: false };
1669
- throw new Error("sfv: bad boolean");
1670
- }
1671
- if (c === "-" || /[0-9]/.test(c)) return { value: parseNumber(p) };
1672
- if (/[a-zA-Z*]/.test(c)) return { value: parseToken(p) };
1673
- throw new Error(`sfv: invalid bare item at ${p.i}`);
1674
- }
1675
- function parseString(p) {
1676
- p.i++;
1677
- let out = "";
1678
- while (!p.eof()) {
1679
- const c = p.s[p.i++];
1680
- if (c === '"') return out;
1681
- if (c === "\\") {
1682
- const e = p.s[p.i++];
1683
- if (e !== '"' && e !== "\\") throw new Error("sfv: bad escape");
1684
- out += e;
1685
- } else {
1686
- const code = c.charCodeAt(0);
1687
- if (code < 32 || code > 126) throw new Error("sfv: bad char in string");
1688
- out += c;
1689
- }
1690
- }
1691
- throw new Error("sfv: unterminated string");
1692
- }
1693
- function parseByteSequence(p) {
1694
- p.i++;
1695
- const start = p.i;
1696
- while (!p.eof() && p.peek() !== ":") p.i++;
1697
- if (p.eof()) throw new Error("sfv: unterminated byte sequence");
1698
- const b64 = p.s.slice(start, p.i);
1699
- p.i++;
1700
- return base64StdToBytes(b64);
1701
- }
1702
- function parseNumber(p) {
1703
- const start = p.i;
1704
- if (p.peek() === "-") p.i++;
1705
- while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
1706
- if (!p.eof() && p.peek() === ".") {
1707
- p.i++;
1708
- while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
1709
- }
1710
- return Number(p.s.slice(start, p.i));
1711
- }
1712
- function parseToken(p) {
1713
- const start = p.i;
1714
- p.i++;
1715
- while (!p.eof() && /[a-zA-Z0-9!#$%&'*+\-.^_`|~:/]/.test(p.peek())) p.i++;
1716
- return p.s.slice(start, p.i);
1717
- }
1718
- function base64StdToBytes(s) {
1719
- const bin = atob(s);
1720
- const out = new Uint8Array(bin.length);
1721
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
1722
- return out;
1723
- }
1724
-
1725
- // src/agent/signature.ts
1726
- var TAG = "web-bot-auth";
1727
- var encoder3 = new TextEncoder();
1728
- async function verifyWebBotAuth(req, resolveKey, toleranceSec) {
1729
- const sigInput = req.headers.get("signature-input");
1730
- const sigHeader = req.headers.get("signature");
1731
- if (!sigInput && !sigHeader) return { outcome: "none" };
1732
- if (!sigInput || !sigHeader) return { outcome: "claimed", reason: "incomplete-signature" };
1733
- let members;
1734
- let sigs;
1735
- try {
1736
- members = parseSignatureInput(sigInput);
1737
- sigs = parseSignatureBytes(sigHeader);
1738
- } catch {
1739
- return { outcome: "claimed", reason: "malformed-signature" };
1740
- }
1741
- const now = Date.now() / 1e3;
1742
- let best = { outcome: "none" };
1743
- for (const m of members) {
1744
- if (m.params.get("tag") !== TAG) continue;
1745
- if (best.outcome === "none") best = { outcome: "claimed", reason: "unverifiable" };
1746
- const sig = sigs.get(m.label);
1747
- if (!sig) continue;
1748
- const keyid = m.params.get("keyid");
1749
- if (typeof keyid !== "string") continue;
1750
- if (!m.components.some((c) => c.name === "@authority" || c.name === "@target-uri")) continue;
1751
- const key = await resolveKey(keyid);
1752
- if (!key) {
1753
- best = higher(best, { outcome: "claimed", keyId: keyid, reason: "unknown-key" });
1754
- continue;
1755
- }
1756
- const created = numeric(m.params.get("created"));
1757
- const expires = numeric(m.params.get("expires"));
1758
- if (expires !== void 0 && now > expires + toleranceSec) {
1759
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "expired" });
1760
- continue;
1761
- }
1762
- if (created !== void 0 && now + toleranceSec < created) {
1763
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "not-yet-valid" });
1764
- continue;
1765
- }
1766
- if (key.exp !== void 0 && now > key.exp + toleranceSec) {
1767
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-expired" });
1768
- continue;
1769
- }
1770
- if (key.nbf !== void 0 && now + toleranceSec < key.nbf) {
1771
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-not-yet-valid" });
1772
- continue;
1773
- }
1774
- let base;
1775
- try {
1776
- base = buildSignatureBase(req, m);
1777
- } catch {
1778
- best = higher(best, { outcome: "claimed", keyId: keyid, reason: "uncoverable-component" });
1779
- continue;
1780
- }
1781
- let ok = false;
1782
- try {
1783
- ok = await crypto.subtle.verify(
1784
- key.verifyParams,
1785
- key.cryptoKey,
1786
- sig,
1787
- encoder3.encode(base)
1788
- );
1789
- } catch {
1790
- ok = false;
1791
- }
1792
- if (ok) {
1793
- return { outcome: "verified", keyId: keyid, key };
1794
- }
1795
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "bad-signature" });
1796
- }
1797
- return best;
1798
- }
1799
- var PRECEDENCE = { none: 0, claimed: 1, impersonation: 2, verified: 3 };
1800
- function higher(a, b) {
1801
- return PRECEDENCE[b.outcome] >= PRECEDENCE[a.outcome] ? b : a;
1802
- }
1803
- function numeric(v) {
1804
- return typeof v === "number" ? v : void 0;
1805
- }
1806
- function buildSignatureBase(req, m) {
1807
- const lines = [];
1808
- for (const c of m.components) {
1809
- lines.push(`${serializeComponentId(c)}: ${componentValue(req, c)}`);
1810
- }
1811
- lines.push(`"@signature-params": ${m.raw.trim()}`);
1812
- return lines.join("\n");
1813
- }
1814
- function serializeComponentId(c) {
1815
- const base = `"${c.name.toLowerCase()}"`;
1816
- return c.keyParam !== void 0 ? `${base};key="${c.keyParam}"` : base;
1817
- }
1818
- function componentValue(req, c) {
1819
- const name = c.name.toLowerCase();
1820
- switch (name) {
1821
- case "@method":
1822
- return req.method.toUpperCase();
1823
- case "@authority":
1824
- return canonicalAuthority(req.url);
1825
- case "@scheme":
1826
- return req.url.protocol.replace(/:$/, "").toLowerCase();
1827
- case "@target-uri":
1828
- return `${req.url.protocol}//${canonicalAuthority(req.url)}${req.url.pathname}${req.url.search}`;
1829
- case "@path":
1830
- return req.url.pathname;
1831
- case "@query":
1832
- return req.url.search === "" ? "?" : req.url.search;
1833
- case "signature-agent": {
1834
- const header = req.headers.get("signature-agent");
1835
- if (header === null) throw new Error("signature-agent covered but absent");
1836
- if (c.keyParam !== void 0) return dictMemberValue(header, c.keyParam);
1837
- return header.trim().replace(/\s+/g, " ");
1838
- }
1839
- default: {
1840
- if (name.startsWith("@")) throw new Error(`unsupported derived component ${name}`);
1841
- const header = req.headers.get(name);
1842
- if (header === null) throw new Error(`covered header ${name} absent`);
1843
- return header.trim().replace(/\s+/g, " ");
1844
- }
1845
- }
1846
- }
1847
- function canonicalAuthority(url) {
1848
- const host = url.hostname.toLowerCase();
1849
- const port = url.port;
1850
- if (!port) return host;
1851
- if (url.protocol === "https:" && port === "443" || url.protocol === "http:" && port === "80") {
1852
- return host;
1853
- }
1854
- return `${host}:${port}`;
1855
- }
1856
- function dictMemberValue(header, key) {
1857
- const dict = parseDictionary(header);
1858
- const found = dict.find((d) => d.key === key);
1859
- if (!found) throw new Error(`signature-agent has no member ${key}`);
1860
- return found.raw;
1861
- }
1862
- function parseSignatureInput(value) {
1863
- return parseDictionary(value).map((d) => {
1864
- if (!d.isList) throw new Error(`Signature-Input member ${d.key} is not an inner list`);
1865
- const components = d.items.map((it) => {
1866
- if (typeof it.value !== "string") throw new Error("component identifier is not a string");
1867
- const keyParam = it.params.get("key");
1868
- return { name: it.value, keyParam: typeof keyParam === "string" ? keyParam : void 0 };
1869
- });
1870
- return { label: d.key, components, params: d.params, raw: d.raw };
1871
- });
1872
- }
1873
- function parseSignatureBytes(value) {
1874
- const out = /* @__PURE__ */ new Map();
1875
- for (const d of parseDictionary(value)) {
1876
- if (d.isList || d.items.length !== 1 || !d.items[0].bytes) {
1877
- throw new Error(`Signature member ${d.key} is not a byte sequence`);
1878
- }
1879
- out.set(d.key, d.items[0].bytes);
1880
- }
1881
- return out;
1882
- }
1883
-
1884
- // src/agent/verifier.ts
1885
- var DEFAULT_TTL_MS = 6 * 60 * 60 * 1e3;
1886
- var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
1887
- var DEFAULT_TOLERANCE_SEC = 300;
1888
- var AgentVerifier = class {
1889
- constructor(options = {}) {
1890
- this.toleranceSec = options.toleranceSec ?? DEFAULT_TOLERANCE_SEC;
1891
- this.cache = new DirectoryCache({
1892
- directories: options.directories ?? DEFAULT_SIGNED_AGENT_DIRECTORIES,
1893
- cacheTtlMs: options.cacheTtlMs ?? DEFAULT_TTL_MS,
1894
- fetchTimeoutMs: options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,
1895
- debug: options.debug ?? false,
1896
- fetchImpl: options.fetchImpl ?? fetch
1897
- });
1898
- }
1899
- /** Pre-fetch trusted directories so the first request verifies warm. */
1900
- warmup() {
1901
- this.cache.prime();
1902
- }
1903
- /** Verify a request's Web Bot Auth signature (if any) locally. */
1904
- async verify(request) {
1905
- let req;
1906
- try {
1907
- req = normalize(request);
1908
- } catch {
1909
- return { status: "none" };
1910
- }
1911
- const result = await verifyWebBotAuth(req, this.cache.resolveKey, this.toleranceSec);
1912
- switch (result.outcome) {
1913
- case "verified":
1914
- return {
1915
- status: "verified",
1916
- method: "signature",
1917
- keyId: result.keyId,
1918
- agentName: result.key?.name,
1919
- category: result.key?.category,
1920
- algorithm: result.key?.algorithm
1921
- };
1922
- case "impersonation":
1923
- return {
1924
- status: "impersonation",
1925
- method: "signature",
1926
- keyId: result.keyId,
1927
- agentName: result.key?.name,
1928
- category: result.key?.category,
1929
- reason: result.reason
1930
- };
1931
- case "claimed":
1932
- return { status: "claimed", keyId: result.keyId, reason: result.reason };
1933
- default:
1934
- return { status: "none" };
1935
- }
1936
- }
1937
- /** Cached-key count (diagnostics/tests). */
1938
- get cachedKeyCount() {
1939
- return this.cache.size;
1940
- }
1941
- };
1942
- function createAgentVerifier(options = {}) {
1943
- return new AgentVerifier(options);
1944
- }
1945
- function normalize(input) {
1946
- if (isRequest(input)) {
1947
- return { method: input.method, url: new URL(input.url), headers: input.headers };
1948
- }
1949
- const headers = input.headers instanceof Headers ? input.headers : toHeaders(input.headers);
1950
- return { method: input.method, url: new URL(input.url), headers };
1951
- }
1952
- function isRequest(input) {
1953
- return typeof Request !== "undefined" && input instanceof Request && typeof input.url === "string";
1954
- }
1955
- function toHeaders(record) {
1956
- const h = new Headers();
1957
- for (const [k, v] of Object.entries(record)) {
1958
- if (v !== void 0 && v !== null) h.set(k, String(v));
1959
- }
1960
- return h;
1961
- }
1962
-
1963
- // src/edge.ts
1964
- var EDGE_CLEARANCE_HEADER = "x-wd-clearance";
1965
- var EDGE_CLASS_HEADER = "x-wd-class";
1966
- var EDGE_CLASSES = ["verified", "crawler", "script", "browser"];
1967
- function absent() {
1968
- return {
1969
- present: false,
1970
- isVerified: false,
1971
- isCrawler: false,
1972
- isScript: false,
1973
- isBrowser: false,
1974
- isUnattestedNonBrowser: false
1975
- };
1976
- }
1977
- function normaliseClass(raw) {
1978
- if (!raw) return void 0;
1979
- const v = raw.trim().toLowerCase();
1980
- return EDGE_CLASSES.includes(v) ? v : void 0;
1981
- }
1982
- function readEdgeVerdict(headers) {
1983
- if (!headers) return absent();
1984
- let clearanceRaw;
1985
- let classRaw;
1986
- for (const key of Object.keys(headers)) {
1987
- const k = key.toLowerCase();
1988
- if (k === EDGE_CLEARANCE_HEADER) clearanceRaw = headers[key];
1989
- else if (k === EDGE_CLASS_HEADER) classRaw = headers[key];
1990
- }
1991
- const clearance = clearanceRaw?.trim() || void 0;
1992
- const cls = normaliseClass(classRaw);
1993
- if (!clearance && !cls) return absent();
1994
- return {
1995
- present: true,
1996
- clearance,
1997
- class: cls,
1998
- isVerified: cls === "verified",
1999
- isCrawler: cls === "crawler",
2000
- isScript: cls === "script",
2001
- isBrowser: cls === "browser",
2002
- isUnattestedNonBrowser: cls === "script" || cls === "crawler"
2003
- };
2004
- }
2005
-
2006
- // src/bots/registry.generated.ts
2007
- var BOT_CATEGORIES = [
2008
- "training_crawler",
2009
- "ai_search_crawler",
2010
- "ai_agent",
2011
- "ai_assistant",
2012
- "search_crawler",
2013
- "seo_crawler",
2014
- "security_scanner",
2015
- "generic_scraper",
2016
- "archiver",
2017
- "fetcher",
2018
- "monitoring",
2019
- "headless_browser",
2020
- "feed_reader",
2021
- "commercial_scraper",
2022
- "none"
2023
- ];
2024
- var BOT_REGISTRY = [
2025
- { id: "gptbot", name: "GPTBot", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["gptbot"] },
2026
- { id: "chatgpt-user", name: "ChatGPT-User", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["chatgpt-user", "chatgpt"] },
2027
- { id: "oai-searchbot", name: "OAI-SearchBot", category: "training_crawler", organization: "OpenAI", baseScore: 80, respectsRobots: true, uaPatterns: ["oai-searchbot"] },
2028
- { id: "claudebot", name: "ClaudeBot", category: "training_crawler", organization: "Anthropic", baseScore: 85, respectsRobots: true, uaPatterns: ["claudebot"] },
2029
- { id: "anthropic", name: "Anthropic", category: "training_crawler", organization: "Anthropic", baseScore: 85, respectsRobots: true, uaPatterns: ["anthropic"] },
2030
- { id: "ccbot", name: "CCBot", category: "training_crawler", organization: "Common Crawl", baseScore: 80, respectsRobots: true, uaPatterns: ["ccbot"] },
2031
- { id: "google-extended", name: "Google-Extended", category: "training_crawler", organization: "Google", baseScore: 80, respectsRobots: true, uaPatterns: ["google-extended"] },
2032
- { id: "bytespider", name: "ByteSpider", category: "training_crawler", organization: "ByteDance", baseScore: 75, respectsRobots: false, uaPatterns: ["bytespider"] },
2033
- { id: "amazonbot", name: "Amazonbot", category: "training_crawler", organization: "Amazon", baseScore: 70, respectsRobots: true, uaPatterns: ["amazonbot"] },
2034
- { id: "facebookbot", name: "FacebookBot", category: "training_crawler", organization: "Meta", baseScore: 70, respectsRobots: true, uaPatterns: ["facebookbot"] },
2035
- { id: "meta-externalagent", name: "Meta-ExternalAgent", category: "training_crawler", organization: "Meta", baseScore: 75, respectsRobots: true, uaPatterns: ["meta-externalagent"] },
2036
- { id: "cohere-ai", name: "Cohere", category: "training_crawler", organization: "Cohere", baseScore: 80, respectsRobots: true, uaPatterns: ["cohere-ai", "cohere"] },
2037
- { id: "perplexitybot", name: "PerplexityBot", category: "training_crawler", organization: "Perplexity AI", baseScore: 80, respectsRobots: true, uaPatterns: ["perplexitybot"] },
2038
- { id: "applebot-extended", name: "Applebot-Extended", category: "training_crawler", organization: "Apple", baseScore: 75, respectsRobots: true, uaPatterns: ["applebot-extended"] },
2039
- { id: "youbot", name: "YouBot", category: "training_crawler", organization: "You.com", baseScore: 75, respectsRobots: true, uaPatterns: ["youbot"] },
2040
- { id: "mistral", name: "MistralBot", category: "training_crawler", organization: "Mistral AI", baseScore: 80, respectsRobots: true, uaPatterns: ["mistral"] },
2041
- { id: "gemini", name: "Gemini", category: "training_crawler", organization: "Google", baseScore: 80, respectsRobots: true, uaPatterns: ["gemini"] },
2042
- { id: "ai2bot", name: "AI2Bot", category: "training_crawler", organization: "Allen Institute for AI", baseScore: 75, respectsRobots: true, uaPatterns: ["ai2bot"] },
2043
- { id: "deepseek", name: "DeepSeek", category: "training_crawler", organization: "DeepSeek", baseScore: 80, respectsRobots: true, uaPatterns: ["deepseek"] },
2044
- { id: "qwen", name: "Qwen", category: "training_crawler", organization: "Alibaba", baseScore: 75, respectsRobots: true, uaPatterns: ["qwen"] },
2045
- { id: "webzio", name: "Webz.io", category: "training_crawler", organization: "Webz.io", baseScore: 70, respectsRobots: false, uaPatterns: ["webzio"] },
2046
- { id: "sentibot", name: "Sentibot", category: "training_crawler", organization: "Sentibot", baseScore: 70, respectsRobots: false, uaPatterns: ["sentibot"] },
2047
- { id: "omgili", name: "Omgili", category: "training_crawler", organization: "Webz.io", baseScore: 70, respectsRobots: false, uaPatterns: ["omgili"] },
2048
- { id: "img2dataset", name: "img2dataset", category: "training_crawler", organization: "LAION", baseScore: 75, respectsRobots: false, uaPatterns: ["img2dataset"] },
2049
- { id: "timpibot", name: "Timpibot", category: "training_crawler", organization: "Timpi", baseScore: 70, respectsRobots: true, uaPatterns: ["timpibot"] },
2050
- { id: "velenpublicwebcrawler", name: "VelenPublicWebCrawler", category: "training_crawler", organization: "Velen", baseScore: 70, respectsRobots: false, uaPatterns: ["velenpublicwebcrawler"] },
2051
- { id: "isscyberriskcrawler", name: "ISSCyberRiskCrawler", category: "training_crawler", organization: "ISS", baseScore: 65, respectsRobots: false, uaPatterns: ["isscyberriskcrawler"] },
2052
- { id: "friendlycrawler", name: "FriendlyCrawler", category: "training_crawler", organization: "Unknown", baseScore: 65, respectsRobots: true, uaPatterns: ["friendlycrawler"] },
2053
- { id: "searchgpt", name: "SearchGPT", category: "ai_search_crawler", organization: "OpenAI", baseScore: 75, respectsRobots: true, uaPatterns: ["searchgpt"] },
2054
- { id: "phind", name: "Phind", category: "ai_search_crawler", organization: "Phind", baseScore: 70, respectsRobots: true, uaPatterns: ["phind"] },
2055
- { id: "kagi", name: "Kagi", category: "ai_search_crawler", organization: "Kagi", baseScore: 65, respectsRobots: true, uaPatterns: ["kagi"] },
2056
- { id: "exa", name: "Exa", category: "ai_search_crawler", organization: "Exa AI", baseScore: 70, respectsRobots: true, uaPatterns: ["exa.ai", "exabot"] },
2057
- { id: "metaphor", name: "Metaphor", category: "ai_search_crawler", organization: "Metaphor", baseScore: 70, respectsRobots: true, uaPatterns: ["metaphor"] },
2058
- { id: "tavily", name: "Tavily", category: "ai_search_crawler", organization: "Tavily", baseScore: 70, respectsRobots: true, uaPatterns: ["tavily"] },
2059
- { id: "brave-search", name: "BraveSearch", category: "ai_search_crawler", organization: "Brave", baseScore: 65, respectsRobots: true, uaPatterns: ["bravesearch"] },
2060
- { id: "neeva", name: "NeevaBot", category: "ai_search_crawler", organization: "Neeva", baseScore: 65, respectsRobots: true, uaPatterns: ["neevabot"] },
2061
- { id: "operator", name: "Operator", category: "ai_agent", organization: "OpenAI", baseScore: 75, respectsRobots: true, uaPatterns: ["operator"] },
2062
- { id: "claude-user", name: "Claude-User", category: "ai_agent", organization: "Anthropic", baseScore: 75, respectsRobots: true, uaPatterns: ["claude-user"] },
2063
- { id: "gemini-user", name: "Gemini-User", category: "ai_agent", organization: "Google", baseScore: 75, respectsRobots: true, uaPatterns: ["gemini-user"] },
2064
- { id: "googleagent-mariner", name: "GoogleAgent-Mariner", category: "ai_agent", organization: "Google", baseScore: 75, respectsRobots: true, uaPatterns: ["googleagent-mariner", "mariner"] },
2065
- { id: "amazon-buyforme", name: "AmazonBuyForMe", category: "ai_agent", organization: "Amazon", baseScore: 70, respectsRobots: true, uaPatterns: ["amazonbuyforme", "buyforme"] },
2066
- { id: "browser-use", name: "Browser-Use", category: "ai_agent", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["browser-use"] },
2067
- { id: "stagehand", name: "Stagehand", category: "ai_agent", organization: "Browserbase", baseScore: 70, respectsRobots: false, uaPatterns: ["stagehand"] },
2068
- { id: "multion", name: "MultiOn", category: "ai_agent", organization: "MultiOn", baseScore: 70, respectsRobots: false, uaPatterns: ["multion"] },
2069
- { id: "googlebot", name: "Googlebot", category: "search_crawler", organization: "Google", baseScore: 30, respectsRobots: true, uaPatterns: ["googlebot"] },
2070
- { id: "bingbot", name: "Bingbot", category: "search_crawler", organization: "Microsoft", baseScore: 30, respectsRobots: true, uaPatterns: ["bingbot"] },
2071
- { id: "yandexbot", name: "YandexBot", category: "search_crawler", organization: "Yandex", baseScore: 35, respectsRobots: true, uaPatterns: ["yandexbot"] },
2072
- { id: "baiduspider", name: "Baiduspider", category: "search_crawler", organization: "Baidu", baseScore: 40, respectsRobots: true, uaPatterns: ["baiduspider"] },
2073
- { id: "duckduckbot", name: "DuckDuckBot", category: "search_crawler", organization: "DuckDuckGo", baseScore: 30, respectsRobots: true, uaPatterns: ["duckduckbot"] },
2074
- { id: "applebot", name: "Applebot", category: "search_crawler", organization: "Apple", baseScore: 30, respectsRobots: true, uaPatterns: ["applebot"] },
2075
- { id: "sogou", name: "Sogou Spider", category: "search_crawler", organization: "Sogou", baseScore: 40, respectsRobots: true, uaPatterns: ["sogou"] },
2076
- { id: "qwantify", name: "Qwantify", category: "search_crawler", organization: "Qwant", baseScore: 35, respectsRobots: true, uaPatterns: ["qwantify"] },
2077
- { id: "naver", name: "Naver", category: "search_crawler", organization: "Naver", baseScore: 35, respectsRobots: true, uaPatterns: ["naver", "yeti"] },
2078
- { id: "seznam", name: "SeznamBot", category: "search_crawler", organization: "Seznam", baseScore: 35, respectsRobots: true, uaPatterns: ["seznambot"] },
2079
- { id: "ecosia", name: "Ecosia", category: "search_crawler", organization: "Ecosia", baseScore: 30, respectsRobots: true, uaPatterns: ["ecosia"] },
2080
- { id: "mojeek", name: "MojeekBot", category: "search_crawler", organization: "Mojeek", baseScore: 35, respectsRobots: true, uaPatterns: ["mojeekbot"] },
2081
- { id: "yahoo-slurp", name: "Yahoo! Slurp", category: "search_crawler", organization: "Yahoo", baseScore: 30, respectsRobots: true, uaPatterns: ["slurp"] },
2082
- { id: "ahrefsbot", name: "AhrefsBot", category: "seo_crawler", organization: "Ahrefs", baseScore: 50, respectsRobots: true, uaPatterns: ["ahrefsbot", "ahrefs"] },
2083
- { id: "semrushbot", name: "SemrushBot", category: "seo_crawler", organization: "Semrush", baseScore: 50, respectsRobots: true, uaPatterns: ["semrushbot", "semrush"] },
2084
- { id: "mj12bot", name: "MJ12bot", category: "seo_crawler", organization: "Majestic", baseScore: 50, respectsRobots: true, uaPatterns: ["mj12bot"] },
2085
- { id: "dotbot", name: "DotBot", category: "seo_crawler", organization: "Moz", baseScore: 50, respectsRobots: true, uaPatterns: ["dotbot"] },
2086
- { id: "rogerbot", name: "Rogerbot", category: "seo_crawler", organization: "Moz", baseScore: 50, respectsRobots: true, uaPatterns: ["rogerbot"] },
2087
- { id: "screaming-frog", name: "Screaming Frog", category: "seo_crawler", organization: "Screaming Frog", baseScore: 55, respectsRobots: true, uaPatterns: ["screaming frog"] },
2088
- { id: "sitebulb", name: "Sitebulb", category: "seo_crawler", organization: "Sitebulb", baseScore: 55, respectsRobots: true, uaPatterns: ["sitebulb"] },
2089
- { id: "deepcrawl", name: "DeepCrawl", category: "seo_crawler", organization: "Lumar", baseScore: 50, respectsRobots: true, uaPatterns: ["deepcrawl"] },
2090
- { id: "oncrawl", name: "OnCrawl", category: "seo_crawler", organization: "OnCrawl", baseScore: 50, respectsRobots: true, uaPatterns: ["oncrawl"] },
2091
- { id: "botify", name: "Botify", category: "seo_crawler", organization: "Botify", baseScore: 50, respectsRobots: true, uaPatterns: ["botify"] },
2092
- { id: "contentking", name: "ContentKing", category: "seo_crawler", organization: "ContentKing", baseScore: 50, respectsRobots: true, uaPatterns: ["contentking"] },
2093
- { id: "sistrix", name: "SISTRIX", category: "seo_crawler", organization: "SISTRIX", baseScore: 50, respectsRobots: true, uaPatterns: ["sistrix"] },
2094
- { id: "serpstat", name: "Serpstat", category: "seo_crawler", organization: "Serpstat", baseScore: 50, respectsRobots: true, uaPatterns: ["serpstat"] },
2095
- { id: "spyfu", name: "SpyFu", category: "seo_crawler", organization: "SpyFu", baseScore: 50, respectsRobots: true, uaPatterns: ["spyfu"] },
2096
- { id: "nessus", name: "Nessus", category: "security_scanner", organization: "Tenable", baseScore: 70, respectsRobots: false, uaPatterns: ["nessus"] },
2097
- { id: "qualys", name: "Qualys", category: "security_scanner", organization: "Qualys", baseScore: 70, respectsRobots: false, uaPatterns: ["qualys"] },
2098
- { id: "shodan", name: "Shodan", category: "security_scanner", organization: "Shodan", baseScore: 75, respectsRobots: false, uaPatterns: ["shodan"] },
2099
- { id: "censys", name: "Censys", category: "security_scanner", organization: "Censys", baseScore: 75, respectsRobots: false, uaPatterns: ["censys"] },
2100
- { id: "nmap", name: "Nmap", category: "security_scanner", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["nmap"] },
2101
- { id: "zap", name: "OWASP ZAP", category: "security_scanner", organization: "OWASP", baseScore: 70, respectsRobots: false, uaPatterns: ["zap/"] },
2102
- { id: "burp", name: "Burp Suite", category: "security_scanner", organization: "PortSwigger", baseScore: 70, respectsRobots: false, uaPatterns: ["burp"] },
2103
- { id: "nikto", name: "Nikto", category: "security_scanner", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["nikto"] },
2104
- { id: "nuclei", name: "Nuclei", category: "security_scanner", organization: "ProjectDiscovery", baseScore: 70, respectsRobots: false, uaPatterns: ["nuclei"] },
2105
- { id: "acunetix", name: "Acunetix", category: "security_scanner", organization: "Invicti", baseScore: 70, respectsRobots: false, uaPatterns: ["acunetix"] },
2106
- { id: "netsparker", name: "Netsparker", category: "security_scanner", organization: "Invicti", baseScore: 70, respectsRobots: false, uaPatterns: ["netsparker"] },
2107
- { id: "detectify", name: "Detectify", category: "security_scanner", organization: "Detectify", baseScore: 65, respectsRobots: false, uaPatterns: ["detectify"] },
2108
- { id: "intruder", name: "Intruder", category: "security_scanner", organization: "Intruder", baseScore: 65, respectsRobots: false, uaPatterns: ["intruder"] },
2109
- { id: "python-requests", name: "Python-Requests", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["python-requests"] },
2110
- { id: "python-urllib", name: "Python-urllib", category: "generic_scraper", organization: "Python", baseScore: 55, respectsRobots: false, uaPatterns: ["python-urllib"] },
2111
- { id: "python", name: "Python", category: "generic_scraper", organization: "Python", baseScore: 50, respectsRobots: false, uaPatterns: ["python/"] },
2112
- { id: "scrapy", name: "Scrapy", category: "generic_scraper", organization: "Scrapy", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapy"] },
2113
- { id: "httpx", name: "HTTPX", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["httpx"] },
2114
- { id: "aiohttp", name: "aiohttp", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["aiohttp"] },
2115
- { id: "beautifulsoup", name: "BeautifulSoup", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["beautifulsoup"] },
2116
- { id: "node-fetch", name: "node-fetch", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["node-fetch"] },
2117
- { id: "axios", name: "Axios", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["axios/"] },
2118
- { id: "got", name: "Got", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["got/"] },
2119
- { id: "undici", name: "Undici", category: "generic_scraper", organization: "Node.js", baseScore: 55, respectsRobots: false, uaPatterns: ["undici"] },
2120
- { id: "go-http-client", name: "Go-HTTP-Client", category: "generic_scraper", organization: "Go", baseScore: 55, respectsRobots: false, uaPatterns: ["go-http-client"] },
2121
- { id: "colly", name: "Colly", category: "generic_scraper", organization: "Open Source", baseScore: 65, respectsRobots: true, uaPatterns: ["colly"] },
2122
- { id: "java", name: "Java", category: "generic_scraper", organization: "Oracle", baseScore: 50, respectsRobots: false, uaPatterns: ["java/"] },
2123
- { id: "okhttp", name: "OkHttp", category: "generic_scraper", organization: "Square", baseScore: 55, respectsRobots: false, uaPatterns: ["okhttp"] },
2124
- { id: "apache-httpclient", name: "Apache-HttpClient", category: "generic_scraper", organization: "Apache", baseScore: 55, respectsRobots: false, uaPatterns: ["apache-httpclient"] },
2125
- { id: "jsoup", name: "Jsoup", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["jsoup"] },
2126
- { id: "guzzlehttp", name: "GuzzleHttp", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["guzzlehttp"] },
2127
- { id: "php", name: "PHP", category: "generic_scraper", organization: "PHP", baseScore: 50, respectsRobots: false, uaPatterns: ["php/"] },
2128
- { id: "ruby", name: "Ruby", category: "generic_scraper", organization: "Ruby", baseScore: 50, respectsRobots: false, uaPatterns: ["ruby"] },
2129
- { id: "faraday", name: "Faraday", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["faraday"] },
2130
- { id: "mechanize", name: "Mechanize", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["mechanize"] },
2131
- { id: "headlesschrome", name: "HeadlessChrome", category: "headless_browser", organization: "Google", baseScore: 70, respectsRobots: false, uaPatterns: ["headlesschrome"] },
2132
- { id: "puppeteer", name: "Puppeteer", category: "headless_browser", organization: "Google", baseScore: 70, respectsRobots: false, uaPatterns: ["puppeteer"] },
2133
- { id: "playwright", name: "Playwright", category: "headless_browser", organization: "Microsoft", baseScore: 70, respectsRobots: false, uaPatterns: ["playwright"] },
2134
- { id: "selenium", name: "Selenium", category: "headless_browser", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["selenium"] },
2135
- { id: "phantomjs", name: "PhantomJS", category: "headless_browser", organization: "Open Source", baseScore: 75, respectsRobots: false, uaPatterns: ["phantomjs"] },
2136
- { id: "splash", name: "Splash", category: "headless_browser", organization: "Scrapinghub", baseScore: 70, respectsRobots: false, uaPatterns: ["splash"] },
2137
- { id: "browserless", name: "Browserless", category: "headless_browser", organization: "Browserless", baseScore: 65, respectsRobots: false, uaPatterns: ["browserless"] },
2138
- { id: "browserbase", name: "Browserbase", category: "headless_browser", organization: "Browserbase", baseScore: 65, respectsRobots: false, uaPatterns: ["browserbase"] },
2139
- { id: "ia-archiver", name: "Internet Archive", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["ia_archiver"] },
2140
- { id: "archive-org-bot", name: "Archive.org", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["archive.org_bot"] },
2141
- { id: "wayback", name: "Wayback Machine", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["wayback"] },
2142
- { id: "heritrix", name: "Heritrix", category: "archiver", organization: "Internet Archive", baseScore: 30, respectsRobots: true, uaPatterns: ["heritrix"] },
2143
- { id: "brozzler", name: "Brozzler", category: "archiver", organization: "Internet Archive", baseScore: 30, respectsRobots: true, uaPatterns: ["brozzler"] },
2144
- { id: "facebookexternalhit", name: "Facebook", category: "fetcher", organization: "Meta", baseScore: 25, respectsRobots: true, uaPatterns: ["facebookexternalhit"] },
2145
- { id: "twitterbot", name: "Twitterbot", category: "fetcher", organization: "X Corp", baseScore: 25, respectsRobots: true, uaPatterns: ["twitterbot"] },
2146
- { id: "linkedinbot", name: "LinkedInBot", category: "fetcher", organization: "LinkedIn", baseScore: 25, respectsRobots: true, uaPatterns: ["linkedinbot"] },
2147
- { id: "slackbot", name: "Slackbot", category: "fetcher", organization: "Slack", baseScore: 25, respectsRobots: true, uaPatterns: ["slackbot"] },
2148
- { id: "telegrambot", name: "TelegramBot", category: "fetcher", organization: "Telegram", baseScore: 25, respectsRobots: true, uaPatterns: ["telegrambot"] },
2149
- { id: "whatsapp", name: "WhatsApp", category: "fetcher", organization: "Meta", baseScore: 25, respectsRobots: true, uaPatterns: ["whatsapp"] },
2150
- { id: "discordbot", name: "Discordbot", category: "fetcher", organization: "Discord", baseScore: 25, respectsRobots: true, uaPatterns: ["discordbot"] },
2151
- { id: "pinterestbot", name: "Pinterest", category: "fetcher", organization: "Pinterest", baseScore: 30, respectsRobots: true, uaPatterns: ["pinterest"] },
2152
- { id: "tumblr", name: "Tumblr", category: "fetcher", organization: "Automattic", baseScore: 30, respectsRobots: true, uaPatterns: ["tumblr"] },
2153
- { id: "reddit", name: "Reddit", category: "fetcher", organization: "Reddit", baseScore: 30, respectsRobots: true, uaPatterns: ["reddit"] },
2154
- { id: "embedly", name: "Embedly", category: "fetcher", organization: "Medium", baseScore: 30, respectsRobots: true, uaPatterns: ["embedly"] },
2155
- { id: "iframely", name: "Iframely", category: "fetcher", organization: "Iframely", baseScore: 30, respectsRobots: true, uaPatterns: ["iframely"] },
2156
- { id: "curl", name: "cURL", category: "fetcher", organization: "Open Source", baseScore: 45, respectsRobots: false, uaPatterns: ["curl/"] },
2157
- { id: "wget", name: "Wget", category: "fetcher", organization: "GNU", baseScore: 45, respectsRobots: false, uaPatterns: ["wget/"] },
2158
- { id: "libwww-perl", name: "libwww-perl", category: "fetcher", organization: "Perl", baseScore: 50, respectsRobots: false, uaPatterns: ["libwww-perl"] },
2159
- { id: "lwp", name: "LWP", category: "fetcher", organization: "Perl", baseScore: 50, respectsRobots: false, uaPatterns: ["lwp-"] },
2160
- { id: "httrack", name: "HTTrack", category: "fetcher", organization: "Open Source", baseScore: 60, respectsRobots: true, uaPatterns: ["httrack"] },
2161
- { id: "webdecoybot", name: "WebDecoyBot", category: "monitoring", organization: "WebDecoy", baseScore: 5, respectsRobots: true, uaPatterns: ["webdecoybot"] },
2162
- { id: "uptimerobot", name: "UptimeRobot", category: "monitoring", organization: "UptimeRobot", baseScore: 20, respectsRobots: true, uaPatterns: ["uptimerobot"] },
2163
- { id: "pingdom", name: "Pingdom", category: "monitoring", organization: "SolarWinds", baseScore: 20, respectsRobots: true, uaPatterns: ["pingdom"] },
2164
- { id: "statuscake", name: "StatusCake", category: "monitoring", organization: "StatusCake", baseScore: 20, respectsRobots: true, uaPatterns: ["statuscake"] },
2165
- { id: "better-uptime", name: "Better Uptime", category: "monitoring", organization: "Better Stack", baseScore: 20, respectsRobots: true, uaPatterns: ["betteruptime"] },
2166
- { id: "datadog-synthetics", name: "Datadog Synthetics", category: "monitoring", organization: "Datadog", baseScore: 25, respectsRobots: true, uaPatterns: ["datadog"] },
2167
- { id: "newrelic", name: "New Relic", category: "monitoring", organization: "New Relic", baseScore: 25, respectsRobots: true, uaPatterns: ["newrelic"] },
2168
- { id: "site24x7", name: "Site24x7", category: "monitoring", organization: "Zoho", baseScore: 20, respectsRobots: true, uaPatterns: ["site24x7"] },
2169
- { id: "freshping", name: "Freshping", category: "monitoring", organization: "Freshworks", baseScore: 20, respectsRobots: true, uaPatterns: ["freshping"] },
2170
- { id: "hetrixtools", name: "HetrixTools", category: "monitoring", organization: "HetrixTools", baseScore: 20, respectsRobots: true, uaPatterns: ["hetrixtools"] },
2171
- { id: "nodeping", name: "NodePing", category: "monitoring", organization: "NodePing", baseScore: 20, respectsRobots: true, uaPatterns: ["nodeping"] },
2172
- { id: "feedly", name: "Feedly", category: "feed_reader", organization: "Feedly", baseScore: 25, respectsRobots: true, uaPatterns: ["feedly"] },
2173
- { id: "newsblur", name: "NewsBlur", category: "feed_reader", organization: "NewsBlur", baseScore: 25, respectsRobots: true, uaPatterns: ["newsblur"] },
2174
- { id: "inoreader", name: "Inoreader", category: "feed_reader", organization: "Inoreader", baseScore: 25, respectsRobots: true, uaPatterns: ["inoreader"] },
2175
- { id: "theoldreader", name: "The Old Reader", category: "feed_reader", organization: "The Old Reader", baseScore: 25, respectsRobots: true, uaPatterns: ["theoldreader"] },
2176
- { id: "feedbin", name: "Feedbin", category: "feed_reader", organization: "Feedbin", baseScore: 25, respectsRobots: true, uaPatterns: ["feedbin"] },
2177
- { id: "miniflux", name: "Miniflux", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["miniflux"] },
2178
- { id: "freshrss", name: "FreshRSS", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["freshrss"] },
2179
- { id: "commafeed", name: "CommaFeed", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["commafeed"] },
2180
- { id: "diffbot", name: "Diffbot", category: "commercial_scraper", organization: "Diffbot", baseScore: 70, respectsRobots: true, uaPatterns: ["diffbot"] },
2181
- { id: "import-io", name: "Import.io", category: "commercial_scraper", organization: "Import.io", baseScore: 65, respectsRobots: true, uaPatterns: ["import.io"] },
2182
- { id: "bright-data", name: "Bright Data", category: "commercial_scraper", organization: "Bright Data", baseScore: 70, respectsRobots: false, uaPatterns: ["brightdata", "luminati"] },
2183
- { id: "oxylabs", name: "Oxylabs", category: "commercial_scraper", organization: "Oxylabs", baseScore: 70, respectsRobots: false, uaPatterns: ["oxylabs"] },
2184
- { id: "scrapingbee", name: "ScrapingBee", category: "commercial_scraper", organization: "ScrapingBee", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapingbee"] },
2185
- { id: "scrapingant", name: "ScrapingAnt", category: "commercial_scraper", organization: "ScrapingAnt", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapingant"] },
2186
- { id: "zyte", name: "Zyte", category: "commercial_scraper", organization: "Zyte", baseScore: 65, respectsRobots: true, uaPatterns: ["zyte", "scrapinghub"] },
2187
- { id: "apify", name: "Apify", category: "commercial_scraper", organization: "Apify", baseScore: 65, respectsRobots: true, uaPatterns: ["apify"] },
2188
- { id: "crawlbase", name: "Crawlbase", category: "commercial_scraper", organization: "Crawlbase", baseScore: 65, respectsRobots: true, uaPatterns: ["crawlbase"] },
2189
- { id: "webscrapingapi", name: "WebScrapingAPI", category: "commercial_scraper", organization: "WebScrapingAPI", baseScore: 65, respectsRobots: true, uaPatterns: ["webscrapingapi"] },
2190
- { id: "gemini-deep-research", name: "Gemini-Deep-Research", category: "ai_assistant", organization: "Google", baseScore: 65, respectsRobots: true, uaPatterns: ["gemini-deep-research"] },
2191
- { id: "copilot", name: "Microsoft Copilot", category: "ai_assistant", organization: "Microsoft", baseScore: 65, respectsRobots: true, uaPatterns: ["copilot"] },
2192
- { id: "cortana", name: "Cortana", category: "ai_assistant", organization: "Microsoft", baseScore: 60, respectsRobots: true, uaPatterns: ["cortana"] },
2193
- { id: "siri", name: "Siri", category: "ai_assistant", organization: "Apple", baseScore: 60, respectsRobots: true, uaPatterns: ["siri"] }
2194
- ];
2195
-
2196
- // src/bots/index.ts
2197
- var AI_CATEGORIES = /* @__PURE__ */ new Set([
2198
- "training_crawler",
2199
- "ai_search_crawler",
2200
- "ai_agent",
2201
- "ai_assistant"
2202
- ]);
2203
- var UNKNOWN = Object.freeze({
2204
- known: false,
2205
- category: "none",
2206
- score: 0,
2207
- isAI: false
2208
- });
2209
- var MAX_CACHE = 1e3;
2210
- var cache = /* @__PURE__ */ new Map();
2211
- function matchUserAgent(userAgent) {
2212
- if (!userAgent) return void 0;
2213
- const cached = cache.get(userAgent);
2214
- if (cached !== void 0) return cached ?? void 0;
2215
- const ua = userAgent.toLowerCase();
2216
- let found = null;
2217
- for (const agent of BOT_REGISTRY) {
2218
- for (const pattern of agent.uaPatterns) {
2219
- if (ua.includes(pattern)) {
2220
- found = agent;
2221
- break;
2222
- }
2223
- }
2224
- if (found) break;
2225
- }
2226
- if (cache.size >= MAX_CACHE) cache.clear();
2227
- cache.set(userAgent, found);
2228
- return found ?? void 0;
2229
- }
2230
- function classifyUserAgent(userAgent) {
2231
- const agent = matchUserAgent(userAgent);
2232
- if (!agent) return UNKNOWN;
2233
- return {
2234
- known: true,
2235
- id: agent.id,
2236
- name: agent.name,
2237
- category: agent.category,
2238
- organization: agent.organization,
2239
- score: agent.baseScore,
2240
- respectsRobots: agent.respectsRobots,
2241
- isAI: AI_CATEGORIES.has(agent.category)
2242
- };
2243
- }
2244
-
2245
- // src/test-trigger.ts
2246
- var TEST_TRIGGER_UA_PREFIX = "WebDecoy-Test/";
2247
- var TEST_TRIGGER_USER_AGENT = "WebDecoy-Test/1.0";
2248
- function isTestTriggerUserAgent(userAgent) {
2249
- if (!userAgent) return false;
2250
- return userAgent.trimStart().toLowerCase().startsWith(TEST_TRIGGER_UA_PREFIX.toLowerCase());
2251
- }
2252
-
2253
- // src/sdk.ts
2254
- var WebDecoy = class {
2255
- constructor(config) {
2256
- this.violationReporter = null;
2257
- this.ipEnrichmentClient = null;
2258
- this._hasFilterRules = false;
2259
- this._hasAgentRules = false;
2260
- this.agentVerifier = null;
2261
- const hasApiKey = !!config.apiKey;
2262
- if (hasApiKey) {
2263
- if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
2264
- throw new Error(
2265
- 'Invalid API key format. API key should start with "sk_live_" or "sk_test_".'
2266
- );
2267
- }
2268
- }
2269
- this.config = {
2270
- apiKey: config.apiKey,
2271
- apiUrl: config.apiUrl || "https://ingest.webdecoy.com",
2272
- enableTLSFingerprinting: config.enableTLSFingerprinting ?? true,
2273
- threatScoreThreshold: config.threatScoreThreshold ?? 80,
2274
- timeout: config.timeout ?? 5e3,
2275
- debug: config.debug ?? false,
2276
- tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
2277
- };
2278
- if (hasApiKey) {
2279
- this.client = new WebDecoyClient({
2280
- apiKey: config.apiKey,
2281
- apiUrl: this.config.apiUrl,
2282
- timeout: this.config.timeout,
2283
- debug: this.config.debug,
2284
- tlsRejectUnauthorized: this.config.tlsRejectUnauthorized
2285
- });
2286
- } else {
2287
- this.client = null;
2288
- if (this.config.debug) {
2289
- console.log("[WebDecoy] Running in local-only mode (no API key). Rules will still evaluate.");
2290
- }
2291
- }
2292
- this.webBotAuthOptions = config.webBotAuth;
2293
- const rules = config.rules ?? [tripwire()];
2294
- if (rules.length > 0) {
2295
- this.ruleEngine = new RuleEngine(rules);
2296
- this._hasFilterRules = rules.some((r) => r.name.startsWith("filter:"));
2297
- this._hasAgentRules = rules.some((r) => r.name === "web-bot-auth");
2298
- if (this._hasAgentRules) {
2299
- this.getAgentVerifier().warmup();
2300
- }
2301
- } else {
2302
- this.ruleEngine = null;
2303
- }
2304
- if (this.client && this._hasFilterRules) {
2305
- this.ipEnrichmentClient = new IPEnrichmentClient(this.client);
2306
- }
2307
- if (this.client && this.ruleEngine) {
2308
- const reporter = new ViolationReporter(this.client, {
2309
- debug: this.config.debug
2310
- });
2311
- this.setViolationReporter(reporter);
2312
- }
2313
- if (this.config.debug) {
2314
- console.log("[WebDecoy] Initialized with config:", {
2315
- apiUrl: this.config.apiUrl,
2316
- enableTLSFingerprinting: this.config.enableTLSFingerprinting,
2317
- threatScoreThreshold: this.config.threatScoreThreshold,
2318
- hasApiKey,
2319
- rulesCount: rules.length
2320
- });
2321
- }
2322
- }
2323
- /**
2324
- * Evaluate rules against request metadata (synchronous).
2325
- * Returns null if no rules are configured.
2326
- */
2327
- evaluateRules(metadata) {
2328
- if (!this.ruleEngine) return null;
2329
- return this.runRules(this.buildContext(metadata));
2330
- }
2331
- /**
2332
- * Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
2333
- * verification). Use this instead of evaluateRules() when filter rules or
2334
- * webBotAuth() rules are present.
2335
- */
2336
- async evaluateRulesAsync(metadata) {
2337
- if (!this.ruleEngine) return null;
2338
- const context = await this.buildAsyncContext(metadata);
2339
- return this.runRules(context);
2340
- }
2341
- /**
2342
- * Register a rule after construction.
2343
- *
2344
- * For signals whose definition is not available synchronously — the site
2345
- * honeytoken's path is derived by async HMAC, so the adapter arms it once the
2346
- * derivation settles. Creates the engine if there was none, so an SDK built
2347
- * with `rules: []` can still gain one.
2348
- */
2349
- addRule(rule) {
2350
- if (!this.ruleEngine) {
2351
- this.ruleEngine = new RuleEngine([rule]);
2352
- } else {
2353
- this.ruleEngine.add(rule);
2354
- }
2355
- if (rule.name.startsWith("filter:")) this._hasFilterRules = true;
2356
- if (rule.name === "web-bot-auth") this._hasAgentRules = true;
2357
- }
2358
- /** Build the base (synchronous) rule context from request metadata. */
2359
- buildContext(metadata) {
2360
- return {
2361
- ip: metadata.ip,
2362
- path: metadata.path,
2363
- method: metadata.method,
2364
- userAgent: metadata.user_agent,
2365
- headers: metadata.headers,
2366
- timestamp: metadata.timestamp || Date.now(),
2367
- // Parsed synchronously and unconditionally: it is two header reads,
2368
- // it needs no network, and a rule that has to check whether the edge
2369
- // verdict was populated is a rule people will get wrong.
2370
- edge: readEdgeVerdict(metadata.headers),
2371
- // Same reasoning as `edge`, and the same cost profile: a memoised
2372
- // substring scan over a static table, no network, no async. Populating it
2373
- // unconditionally means a rule never has to ask whether classification
2374
- // ran.
2375
- bot: classifyUserAgent(metadata.user_agent)
2376
- };
2377
- }
2378
- /**
2379
- * Build a rule context with async signals resolved: IP enrichment (for
2380
- * filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
2381
- */
2382
- async buildAsyncContext(metadata) {
2383
- const context = this.buildContext(metadata);
2384
- if (this._hasFilterRules && this.ipEnrichmentClient) {
2385
- const enrichment = await this.ipEnrichmentClient.enrich(metadata.ip);
2386
- if (enrichment) {
2387
- context.enrichment = enrichment;
2388
- }
2389
- }
2390
- if (this._hasAgentRules) {
2391
- context.agent = await this.computeAgentVerdict(metadata);
2392
- }
2393
- return context;
2394
- }
2395
- /** Evaluate rules against a prepared context and report any violations. */
2396
- runRules(context) {
2397
- if (!this.ruleEngine) return null;
2398
- const result = this.ruleEngine.evaluate(context);
2399
- if (result.violations.length > 0 && this.violationReporter) {
2400
- this.violationReporter.report(result.violations);
2401
- }
2402
- return result;
2403
- }
2404
- /** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
2405
- getAgentVerifier() {
2406
- if (!this.agentVerifier) {
2407
- this.agentVerifier = new AgentVerifier({
2408
- debug: this.config.debug,
2409
- ...this.webBotAuthOptions
2410
- });
2411
- }
2412
- return this.agentVerifier;
2413
- }
2414
- /**
2415
- * Verify a request's Web Bot Auth signature locally, deriving the request
2416
- * URL/authority from its metadata. Returns undefined when the request lacks
2417
- * the host information needed to verify (verdict is then simply absent).
2418
- */
2419
- async computeAgentVerdict(metadata) {
2420
- const input = agentInputFromMetadata(metadata);
2421
- if (!input) return void 0;
2422
- return this.getAgentVerifier().verify(input);
2423
- }
2424
- /**
2425
- * Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
2426
- * "web-bot-auth"). Returns whether it is a cryptographically `verified`
2427
- * agent, an `impersonation` of a known one, an unverifiable `claimed`
2428
- * signature, or `none`. No network on the warm path.
2429
- *
2430
- * Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
2431
- * object (Node).
2432
- *
2433
- * @example
2434
- * ```ts
2435
- * const verdict = await webdecoy.detectBot(request);
2436
- * if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
2437
- * if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
2438
- * ```
2439
- */
2440
- async detectBot(request) {
2441
- return this.getAgentVerifier().verify(request);
2442
- }
2443
- /**
2444
- * Whether this SDK instance has filter rules that need async enrichment
2445
- */
2446
- get hasFilterRules() {
2447
- return this._hasFilterRules;
2448
- }
2449
- /**
2450
- * Whether this SDK instance has Web Bot Auth rules that need async
2451
- * verification before evaluation.
2452
- */
2453
- get hasAgentRules() {
2454
- return this._hasAgentRules;
2455
- }
2456
- /**
2457
- * Protect a request by checking it against Web Decoy's bot detection
2458
- *
2459
- * @param metadata - Request metadata to analyze
2460
- * @param options - Optional configuration for this specific request
2461
- * @returns Protection result with decision and detection details
2462
- */
2463
- async protect(metadata, options = {}) {
2464
- const edge = readEdgeVerdict(metadata.headers);
2465
- const result = await this.decide(metadata, options);
2466
- return { ...result, edge };
2467
- }
2468
- async decide(metadata, options = {}) {
2469
- try {
2470
- if (!metadata.ip) {
2471
- throw new Error("IP address is required in request metadata");
2472
- }
2473
- if (!metadata.timestamp) {
2474
- metadata.timestamp = Date.now();
2475
- }
2476
- if (isTestTriggerUserAgent(metadata.user_agent)) {
2477
- return this.reportTestTrigger(metadata);
2478
- }
2479
- let ruleResult;
2480
- let agentVerdict;
2481
- if (this.ruleEngine && (this._hasFilterRules || this._hasAgentRules)) {
2482
- const context = await this.buildAsyncContext(metadata);
2483
- agentVerdict = context.agent;
2484
- ruleResult = this.runRules(context);
2485
- } else {
2486
- ruleResult = this.evaluateRules(metadata);
2487
- }
2488
- if (ruleResult && ruleResult.action === "DENY") {
2489
- return {
2490
- allowed: false,
2491
- detection: {
2492
- decision: "block",
2493
- confidence: 100,
2494
- threat_level: "HIGH",
2495
- bot_detected: false,
2496
- detection_id: "rule_" + Date.now(),
2497
- rule_enforced: true
2498
- },
2499
- ruleResult,
2500
- agent: agentVerdict
2501
- };
2502
- }
2503
- if (ruleResult && ruleResult.action === "THROTTLE") {
2504
- return {
2505
- allowed: false,
2506
- detection: {
2507
- decision: "block",
2508
- confidence: 100,
2509
- threat_level: "MEDIUM",
2510
- bot_detected: false,
2511
- detection_id: "rule_" + Date.now(),
2512
- rule_enforced: true
2513
- },
2514
- ruleResult,
2515
- agent: agentVerdict
2516
- };
2517
- }
2518
- if (!this.client) {
2519
- return {
2520
- allowed: true,
2521
- detection: {
2522
- decision: "allow",
2523
- confidence: 0,
2524
- threat_level: "MINIMAL",
2525
- bot_detected: false,
2526
- detection_id: "local_" + Date.now(),
2527
- rule_enforced: false
2528
- },
2529
- ruleResult: ruleResult ?? void 0,
2530
- agent: agentVerdict
2531
- };
2532
- }
2533
- const localAnalysis = options.skipLocalAnalysis ? {
2534
- suspicious_headers: false,
2535
- missing_sec_ch_ua: false,
2536
- datacenter_ip: false,
2537
- local_score: 0,
2538
- needs_verification: true,
2539
- flags: ["local_analysis_skipped"]
2540
- } : analyzeRequest(metadata);
2541
- if (this.config.debug) {
2542
- console.log("[WebDecoy] Local analysis result:", localAnalysis);
2543
- }
2544
- const detectionRequest = {
2545
- request_metadata: metadata,
2546
- local_analysis: localAnalysis
2547
- };
2548
- const shouldCallServer = localAnalysis.needs_verification || this.config.enableTLSFingerprinting && metadata.tls_info;
2549
- if (!shouldCallServer && localAnalysis.local_score < 50) {
2550
- return {
2551
- allowed: true,
2552
- detection: {
2553
- decision: "allow",
2554
- confidence: 100 - localAnalysis.local_score,
2555
- threat_level: "MINIMAL",
2556
- bot_detected: false,
2557
- detection_id: "local_" + Date.now(),
2558
- rule_enforced: false
2559
- },
2560
- ruleResult: ruleResult ?? void 0,
2561
- agent: agentVerdict
2562
- };
2563
- }
2564
- const detection = await this.client.detect(detectionRequest);
2565
- const threshold = options.threshold ?? this.config.threatScoreThreshold;
2566
- const allowed = detection.decision === "allow" || detection.confidence < threshold;
2567
- if (this.config.debug) {
2568
- console.log("[WebDecoy] Server detection result:", {
2569
- decision: detection.decision,
2570
- confidence: detection.confidence,
2571
- allowed
2572
- });
2573
- }
2574
- return {
2575
- allowed,
2576
- detection,
2577
- ruleResult: ruleResult ?? void 0,
2578
- agent: agentVerdict
2579
- };
2580
- } catch (error) {
2581
- if (this.config.debug) {
2582
- console.error("[WebDecoy] Protection error:", error);
2583
- }
2584
- return {
2585
- allowed: true,
2586
- // Fail open to avoid blocking legitimate users
2587
- detection: {
2588
- decision: "allow",
2589
- confidence: 0,
2590
- threat_level: "MINIMAL",
2591
- bot_detected: false,
2592
- detection_id: "error_" + Date.now(),
2593
- rule_enforced: false
2594
- },
2595
- error: error instanceof Error ? error.message : "Unknown error"
2596
- };
2597
- }
2598
- }
2599
- /**
2600
- * Report a test-trigger request and return a blocking verdict.
2601
- *
2602
- * The verdict is `allowed: false` so an enforce-mode adapter answers the
2603
- * curl with a 403 — a visibly different response that tells the developer
2604
- * their middleware acted, Arcjet-quickstart style. (The default monitor
2605
- * mode still serves the request; the dashboard row is the real receipt.)
2606
- *
2607
- * Without an API key nothing can reach the dashboard, so the verdict says
2608
- * so via `error` instead of pretending the test ran.
2609
- */
2610
- async reportTestTrigger(metadata) {
2611
- const blocked = {
2612
- decision: "block",
2613
- confidence: 100,
2614
- threat_level: "HIGH",
2615
- bot_detected: true,
2616
- bot_type: "test_trigger",
2617
- detection_id: "test_" + Date.now(),
2618
- rule_enforced: false
2619
- };
2620
- if (!this.client) {
2621
- return {
2622
- allowed: false,
2623
- detection: blocked,
2624
- error: "Test trigger recognized, but no apiKey is configured \u2014 nothing was reported to the dashboard."
2625
- };
2626
- }
2627
- try {
2628
- const detection = await this.client.detect({
2629
- request_metadata: metadata,
2630
- local_analysis: {
2631
- suspicious_headers: false,
2632
- missing_sec_ch_ua: false,
2633
- datacenter_ip: false,
2634
- local_score: 100,
2635
- needs_verification: true,
2636
- flags: ["test_trigger"]
2637
- }
2638
- });
2639
- return { allowed: false, detection };
2640
- } catch (error) {
2641
- return {
2642
- allowed: false,
2643
- detection: blocked,
2644
- error: error instanceof Error ? error.message : "Failed to report test detection"
2645
- };
2646
- }
2647
- }
2648
- /**
2649
- * Validate the API key configuration
2650
- * Useful for testing integration during setup
2651
- */
2652
- async validateConfig() {
2653
- if (!this.client) {
2654
- return { valid: false, error: "No API key configured" };
2655
- }
2656
- try {
2657
- const isValid = await this.client.validateAPIKey();
2658
- return { valid: isValid };
2659
- } catch (error) {
2660
- return {
2661
- valid: false,
2662
- error: error instanceof Error ? error.message : "Unknown error"
2663
- };
2664
- }
2665
- }
2666
- /**
2667
- * Attach a violation reporter for sending violations to the backend.
2668
- * Called internally when apiKey is present and rules are configured.
2669
- */
2670
- setViolationReporter(reporter) {
2671
- this.violationReporter = reporter;
2672
- }
2673
- /**
2674
- * Get the API client (for use by violation reporter, enrichment, etc.)
2675
- */
2676
- getClient() {
2677
- return this.client;
2678
- }
2679
- /**
2680
- * Get the current configuration
2681
- */
2682
- getConfig() {
2683
- return { ...this.config };
2684
- }
2685
- /**
2686
- * Clean up resources (timers, flush pending violations)
2687
- */
2688
- async destroy() {
2689
- this.ruleEngine?.destroy();
2690
- if (this.violationReporter) {
2691
- await this.violationReporter.destroy();
2692
- }
2693
- }
2694
- };
2695
- function agentInputFromMetadata(metadata) {
2696
- const headers = metadata.headers || {};
2697
- const host = headers["host"] || headers[":authority"] || headers["x-forwarded-host"] || headers["Host"];
2698
- if (!host) return null;
2699
- const proto = headers["x-forwarded-proto"] || headers["X-Forwarded-Proto"];
2700
- const scheme = (proto ? proto.split(",")[0].trim() : "https") || "https";
2701
- const rawPath = metadata.path || "/";
2702
- const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
2703
- try {
2704
- return {
2705
- method: metadata.method,
2706
- url: `${scheme}://${host}${path}`,
2707
- headers
2708
- };
2709
- } catch {
2710
- return null;
2711
- }
2712
- }
1
+ import {
2
+ ATTACK_SIGNATURE_IDS,
3
+ AgentVerifier,
4
+ AttackSignatureRule,
5
+ BOT_CATEGORIES,
6
+ BOT_REGISTRY,
7
+ BotPolicy,
8
+ BotRule,
9
+ DEFAULT_CHARACTERISTICS,
10
+ DEFAULT_SIGNED_AGENT_DIRECTORIES,
11
+ DEFAULT_TRIPWIRE_PATHS,
12
+ Decision,
13
+ DecisionCache,
14
+ DirectoryCache,
15
+ EDGE_CLASS_HEADER,
16
+ EDGE_CLEARANCE_HEADER,
17
+ FilterRule,
18
+ HONEYTOKEN_BASE_PATH,
19
+ MemoryRateLimitStore,
20
+ RateLimitRule,
21
+ RuleEngine,
22
+ TEST_TRIGGER_UA_PREFIX,
23
+ TEST_TRIGGER_USER_AGENT,
24
+ TripwireRule,
25
+ UpstashRateLimitStore,
26
+ WebBotAuthRule,
27
+ WebDecoy,
28
+ attackSignatures,
29
+ base64urlDecode,
30
+ base64urlEncode,
31
+ botPolicy,
32
+ bots,
33
+ classifyUserAgent,
34
+ consoleLogger,
35
+ createAgentVerifier,
36
+ deriveKey,
37
+ filter,
38
+ fnv1a64Hex,
39
+ fromPino,
40
+ hmacSha256Hex,
41
+ honeytoken,
42
+ injectHoneytokenLink,
43
+ isInjectableHtml,
44
+ isTestTriggerUserAgent,
45
+ matchUserAgent,
46
+ newDecisionId,
47
+ randomHex,
48
+ rateLimit,
49
+ readEdgeVerdict,
50
+ sha256Hex,
51
+ silentLogger,
52
+ siteHoneytoken,
53
+ timingSafeEqualStr,
54
+ tripwire,
55
+ upstashRateLimitStore,
56
+ webBotAuth
57
+ } from "./chunk-CIRFOOMU.mjs";
2713
58
 
2714
59
  // src/client-ip.ts
2715
60
  var IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
@@ -2854,6 +199,225 @@ function resolveClientIp(options) {
2854
199
  return full[0] ?? void 0 ?? peer;
2855
200
  }
2856
201
 
202
+ // src/client-signals.ts
203
+ var MemoryClientSignalStore = class {
204
+ constructor(options = {}) {
205
+ this.sync = true;
206
+ this.entries = /* @__PURE__ */ new Map();
207
+ this.ttl = options.ttl ?? 9e5;
208
+ this.max = options.max ?? 1e4;
209
+ }
210
+ get(sessionId) {
211
+ const entry = this.entries.get(sessionId);
212
+ if (!entry) return void 0;
213
+ if (Date.now() - entry.at > this.ttl) {
214
+ this.entries.delete(sessionId);
215
+ return void 0;
216
+ }
217
+ return entry;
218
+ }
219
+ set(verdict) {
220
+ this.entries.delete(verdict.sessionId);
221
+ this.entries.set(verdict.sessionId, verdict);
222
+ while (this.entries.size > this.max) {
223
+ const oldest = this.entries.keys().next();
224
+ if (oldest.done) break;
225
+ this.entries.delete(oldest.value);
226
+ }
227
+ }
228
+ get size() {
229
+ return this.entries.size;
230
+ }
231
+ };
232
+ var CLIENT_SESSION_COOKIE = "wd_cs";
233
+ var CLIENT_SESSION_HEADER = "x-wd-session";
234
+ function readClientSession(headers) {
235
+ const cookie = headers["cookie"];
236
+ if (cookie) {
237
+ for (const part of cookie.split(";")) {
238
+ const eq = part.indexOf("=");
239
+ if (eq < 0) continue;
240
+ if (part.slice(0, eq).trim() === CLIENT_SESSION_COOKIE) {
241
+ const value = part.slice(eq + 1).trim();
242
+ if (value) return value;
243
+ }
244
+ }
245
+ }
246
+ const header = headers[CLIENT_SESSION_HEADER];
247
+ return header || void 0;
248
+ }
249
+ var ClientSignalRule = class {
250
+ constructor(config) {
251
+ this.name = "client-signals";
252
+ this.store = config.store;
253
+ this.minScore = config.minScore;
254
+ this.action = config.action ?? "DENY";
255
+ this.dryRun = config.dryRun ?? false;
256
+ }
257
+ async prepare(context) {
258
+ if (this.store.sync) return;
259
+ const sessionId = readClientSession(context.headers);
260
+ if (!sessionId) return;
261
+ const verdict = await this.store.get(sessionId);
262
+ if (verdict) {
263
+ context.prepared ?? (context.prepared = {});
264
+ context.prepared[this.name] = verdict;
265
+ }
266
+ }
267
+ evaluate(context) {
268
+ const sessionId = readClientSession(context.headers);
269
+ if (!sessionId) {
270
+ return {
271
+ action: "ALLOW",
272
+ rule: this.name,
273
+ state: "NOT_RUN",
274
+ reason: "No browser session \u2014 the client widget did not run for this request"
275
+ };
276
+ }
277
+ const verdict = this.store.sync ? this.store.get(sessionId) : context.prepared?.[this.name];
278
+ if (!verdict) {
279
+ return {
280
+ action: "ALLOW",
281
+ rule: this.name,
282
+ state: "NOT_RUN",
283
+ reason: "No signals recorded for this session yet"
284
+ };
285
+ }
286
+ const bad = this.minScore !== void 0 ? verdict.score >= this.minScore : verdict.recommendation === "block";
287
+ if (!bad) {
288
+ return {
289
+ action: "ALLOW",
290
+ rule: this.name,
291
+ metadata: { score: verdict.score, recommendation: verdict.recommendation }
292
+ };
293
+ }
294
+ return {
295
+ action: this.dryRun ? "ALLOW" : this.action,
296
+ rule: this.name,
297
+ reason: `Client signals scored ${verdict.score.toFixed(2)} (${verdict.recommendation})`,
298
+ metadata: {
299
+ score: verdict.score,
300
+ recommendation: verdict.recommendation,
301
+ sessionId,
302
+ dryRun: this.dryRun
303
+ }
304
+ };
305
+ }
306
+ };
307
+ function clientSignals(config) {
308
+ return new ClientSignalRule(config);
309
+ }
310
+
311
+ // src/fetch-guard.ts
312
+ function defaultBlocked(_request, decision) {
313
+ const throttled = decision.ruleResult?.action === "THROTTLE";
314
+ const retryAfter = Number(decision.ruleResult?.metadata?.retryAfter ?? 60);
315
+ if (throttled) {
316
+ return new Response(
317
+ JSON.stringify({
318
+ error: "Too Many Requests",
319
+ message: decision.reason ?? "Rate limit exceeded",
320
+ retry_after: retryAfter,
321
+ detection_id: decision.id
322
+ }),
323
+ {
324
+ status: 429,
325
+ headers: {
326
+ "content-type": "application/json",
327
+ "retry-after": String(retryAfter)
328
+ }
329
+ }
330
+ );
331
+ }
332
+ return new Response(
333
+ JSON.stringify({
334
+ error: "Forbidden",
335
+ message: "Access denied by Web Decoy protection",
336
+ detection_id: decision.id
337
+ }),
338
+ { status: 403, headers: { "content-type": "application/json" } }
339
+ );
340
+ }
341
+ function matches(pathname, patterns) {
342
+ if (!patterns || patterns.length === 0) return false;
343
+ return patterns.some(
344
+ (p) => typeof p === "string" ? pathname === p || pathname.startsWith(p) : p.test(pathname)
345
+ );
346
+ }
347
+ function headerRecord(headers) {
348
+ const out = {};
349
+ headers.forEach((value, key) => {
350
+ out[key.toLowerCase()] = value;
351
+ });
352
+ return out;
353
+ }
354
+ function createFetchGuard(options = {}) {
355
+ const sdk = new WebDecoy(options);
356
+ const mode = options.mode ?? "monitor";
357
+ const onBlocked = options.onBlocked ?? defaultBlocked;
358
+ let token = null;
359
+ if ((options.honeytoken ?? true) && options.apiKey) {
360
+ void siteHoneytoken({ secret: options.apiKey }).then((t) => {
361
+ token = t;
362
+ sdk.addRule(tripwire({ paths: t.activePaths, includeDefaults: false }));
363
+ }).catch(() => {
364
+ });
365
+ }
366
+ function resolveIP(request, peer) {
367
+ if (options.getIP) return options.getIP(request);
368
+ return resolveClientIp({
369
+ headers: request.headers,
370
+ peer,
371
+ trustProxy: options.trustProxy ?? 1
372
+ }) ?? normalizeIp(peer) ?? "127.0.0.1";
373
+ }
374
+ return {
375
+ sdk,
376
+ skips(pathname) {
377
+ return matches(pathname, options.skipPaths);
378
+ },
379
+ async check(request, peer) {
380
+ const url = new URL(request.url);
381
+ const metadata = {
382
+ method: request.method,
383
+ path: url.pathname,
384
+ ip: resolveIP(request, peer),
385
+ user_agent: request.headers.get("user-agent") ?? void 0,
386
+ headers: headerRecord(request.headers),
387
+ query: url.search ? url.search.slice(1) : void 0,
388
+ timestamp: Date.now()
389
+ };
390
+ const decision = await sdk.protect(metadata, {
391
+ threshold: options.threshold,
392
+ skipLocalAnalysis: options.skipLocalAnalysis,
393
+ metadata: options.metadata
394
+ });
395
+ if (decision.allowed || mode !== "enforce") return { decision };
396
+ return { decision, response: await onBlocked(request, decision) };
397
+ },
398
+ async decorate(response) {
399
+ const current = token;
400
+ if (!current) return response;
401
+ if (!isInjectableHtml(response.headers.get("content-type"))) return response;
402
+ if (response.bodyUsed) return response;
403
+ try {
404
+ const html = await response.text();
405
+ const injected = injectHoneytokenLink(html, current.linkHtml);
406
+ if (injected === html) return new Response(html, response);
407
+ const headers = new Headers(response.headers);
408
+ headers.delete("content-length");
409
+ return new Response(injected, {
410
+ status: response.status,
411
+ statusText: response.statusText,
412
+ headers
413
+ });
414
+ } catch {
415
+ return response;
416
+ }
417
+ }
418
+ };
419
+ }
420
+
2857
421
  // src/detection/weights.ts
2858
422
  var DEFAULT_WEIGHTS = {
2859
423
  vision_ai: 0.15,
@@ -2953,7 +517,7 @@ function cidrContains(cidr, ip) {
2953
517
  const ipLong = ipToLong(ip);
2954
518
  return (ipLong & mask) === rangeStart;
2955
519
  }
2956
- function isDatacenterIP2(ip) {
520
+ function isDatacenterIP(ip) {
2957
521
  if (!isIPv4(ip)) return false;
2958
522
  return DATACENTER_CIDRS.some((cidr) => cidrContains(cidr, ip));
2959
523
  }
@@ -2987,7 +551,7 @@ var InMemoryFingerprintStore = class {
2987
551
  return this.fingerprints.get(`${siteKey}:${fp}`)?.ips.size ?? 0;
2988
552
  }
2989
553
  };
2990
- var InMemoryRateLimiter2 = class {
554
+ var InMemoryRateLimiter = class {
2991
555
  constructor() {
2992
556
  this.requests = /* @__PURE__ */ new Map();
2993
557
  }
@@ -4371,7 +1935,7 @@ var DetectionEngine = class {
4371
1935
  this.weights = options.weights ?? DEFAULT_WEIGHTS;
4372
1936
  this.requirePoW = options.requirePoW ?? true;
4373
1937
  this.fingerprintStore = options.fingerprintStore ?? new InMemoryFingerprintStore();
4374
- this.rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter2();
1938
+ this.rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter();
4375
1939
  }
4376
1940
  /** Score `signals` for the given request context and return a verdict. */
4377
1941
  score(signals, context) {
@@ -4428,7 +1992,7 @@ var DetectionEngine = class {
4428
1992
  ...detectFingerprint(signals, ip, siteKey, this.fingerprintStore),
4429
1993
  ...detectRateAbuse(ip, siteKey, this.rateLimiter)
4430
1994
  );
4431
- if (isDatacenterIP2(ip)) {
1995
+ if (isDatacenterIP(ip)) {
4432
1996
  detections.push({
4433
1997
  category: "datacenter",
4434
1998
  score: 0.6,
@@ -4516,12 +2080,12 @@ var PoWManager = class {
4516
2080
  constructor(options) {
4517
2081
  this.secret = options.secret;
4518
2082
  this.store = options.store ?? new InMemoryChallengeStore();
4519
- this.rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter2();
2083
+ this.rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter();
4520
2084
  }
4521
2085
  /** Difficulty scaled by IP reputation and request rate (4..6). */
4522
2086
  scaleDifficulty(siteKey, ip) {
4523
2087
  let difficulty = 4;
4524
- if (isDatacenterIP2(ip)) difficulty = 5;
2088
+ if (isDatacenterIP(ip)) difficulty = 5;
4525
2089
  const [exceeded, count] = this.rateLimiter.check(`pow:${siteKey}:${ip}`, 60, 20);
4526
2090
  if (count > 10) difficulty = Math.min(6, difficulty + 1);
4527
2091
  if (exceeded) difficulty = 6;
@@ -4660,7 +2224,7 @@ var TokenManager = class {
4660
2224
  var Captcha = class {
4661
2225
  constructor(options = {}) {
4662
2226
  const secret = resolveSecret(options.secret);
4663
- const rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter2();
2227
+ const rateLimiter = options.rateLimiter ?? new InMemoryRateLimiter();
4664
2228
  const fingerprintStore = options.fingerprintStore ?? new InMemoryFingerprintStore();
4665
2229
  this.engine = new DetectionEngine({
4666
2230
  weights: options.weights,
@@ -4750,7 +2314,7 @@ var Captcha = class {
4750
2314
  // src/captcha/http.ts
4751
2315
  var JSON_HEADERS = { "content-type": "application/json" };
4752
2316
  function createCaptchaEndpoints(options = {}) {
4753
- const { basePath = "/__webdecoy", ...captchaOptions } = options;
2317
+ const { basePath = "/__webdecoy", signalStore, ...captchaOptions } = options;
4754
2318
  const captcha = new Captcha(captchaOptions);
4755
2319
  const base = basePath.replace(/\/$/, "");
4756
2320
  function route(pathname) {
@@ -4800,7 +2364,20 @@ function createCaptchaEndpoints(options = {}) {
4800
2364
  ja3Hash,
4801
2365
  action: b.action
4802
2366
  });
4803
- return json(200, result);
2367
+ if (signalStore && b.sessionId) {
2368
+ await signalStore.set({
2369
+ sessionId: b.sessionId,
2370
+ score: result.score,
2371
+ recommendation: result.recommendation,
2372
+ at: Date.now()
2373
+ });
2374
+ }
2375
+ return json(200, {
2376
+ ...result,
2377
+ // Echoed so the widget can set the cookie the rule reads, without the
2378
+ // developer wiring a second endpoint to hand it one.
2379
+ sessionId: b.sessionId ?? null
2380
+ });
4804
2381
  }
4805
2382
  if (sub === "/token/verify" && method === "POST") {
4806
2383
  const b = req.body ?? {};
@@ -4812,14 +2389,23 @@ function createCaptchaEndpoints(options = {}) {
4812
2389
  return { captcha, basePath: base, handle };
4813
2390
  }
4814
2391
  export {
2392
+ ATTACK_SIGNATURE_IDS,
4815
2393
  AgentVerifier,
2394
+ AttackSignatureRule,
4816
2395
  BOT_CATEGORIES,
4817
2396
  BOT_REGISTRY,
2397
+ BotPolicy,
4818
2398
  BotRule,
2399
+ CLIENT_SESSION_COOKIE,
2400
+ CLIENT_SESSION_HEADER,
4819
2401
  Captcha,
2402
+ ClientSignalRule,
2403
+ DEFAULT_CHARACTERISTICS,
4820
2404
  DEFAULT_SIGNED_AGENT_DIRECTORIES,
4821
2405
  DEFAULT_TRIPWIRE_PATHS,
4822
2406
  DEFAULT_WEIGHTS,
2407
+ Decision,
2408
+ DecisionCache,
4823
2409
  DetectionEngine,
4824
2410
  DirectoryCache,
4825
2411
  EDGE_CLASS_HEADER,
@@ -4828,8 +2414,10 @@ export {
4828
2414
  HONEYTOKEN_BASE_PATH,
4829
2415
  InMemoryChallengeStore,
4830
2416
  InMemoryFingerprintStore,
4831
- InMemoryRateLimiter2 as InMemoryRateLimiter,
2417
+ InMemoryRateLimiter,
4832
2418
  InMemoryTokenStore,
2419
+ MemoryClientSignalStore,
2420
+ MemoryRateLimitStore,
4833
2421
  PoWManager,
4834
2422
  RateLimitRule,
4835
2423
  RuleEngine,
@@ -4837,31 +2425,43 @@ export {
4837
2425
  TEST_TRIGGER_USER_AGENT,
4838
2426
  TokenManager,
4839
2427
  TripwireRule,
2428
+ UpstashRateLimitStore,
4840
2429
  WebBotAuthRule,
4841
2430
  WebDecoy,
2431
+ attackSignatures,
2432
+ botPolicy,
4842
2433
  bots,
4843
2434
  calculateCategoryScores,
4844
2435
  calculateFinalScore,
4845
2436
  classifyUserAgent,
2437
+ clientSignals,
2438
+ consoleLogger,
4846
2439
  createAgentVerifier,
4847
2440
  createCaptchaEndpoints,
2441
+ createFetchGuard,
2442
+ deriveKey,
4848
2443
  filter,
2444
+ fromPino,
4849
2445
  honeytoken,
4850
2446
  injectHoneytokenLink,
4851
2447
  ipInCidr,
4852
- isDatacenterIP2 as isDatacenterIP,
2448
+ isDatacenterIP,
4853
2449
  isInjectableHtml,
4854
2450
  isMobileUA,
4855
2451
  isTestTriggerUserAgent,
4856
2452
  matchUserAgent,
2453
+ newDecisionId,
4857
2454
  normalizeIp,
4858
2455
  parseUserAgent,
4859
2456
  rateLimit,
2457
+ readClientSession,
4860
2458
  readEdgeVerdict,
4861
2459
  recommend,
4862
2460
  resolveClientIp,
4863
2461
  resolveSecret,
2462
+ silentLogger,
4864
2463
  siteHoneytoken,
4865
2464
  tripwire,
2465
+ upstashRateLimitStore,
4866
2466
  webBotAuth
4867
2467
  };