@webdecoy/node 0.12.0 → 0.13.0

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