@webdecoy/node 0.11.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -20,14 +20,23 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ ATTACK_SIGNATURE_IDS: () => ATTACK_SIGNATURE_IDS,
23
24
  AgentVerifier: () => AgentVerifier,
25
+ AttackSignatureRule: () => AttackSignatureRule,
24
26
  BOT_CATEGORIES: () => BOT_CATEGORIES,
25
27
  BOT_REGISTRY: () => BOT_REGISTRY,
28
+ BotPolicy: () => BotPolicy,
26
29
  BotRule: () => BotRule,
30
+ CLIENT_SESSION_COOKIE: () => CLIENT_SESSION_COOKIE,
31
+ CLIENT_SESSION_HEADER: () => CLIENT_SESSION_HEADER,
27
32
  Captcha: () => Captcha,
33
+ ClientSignalRule: () => ClientSignalRule,
34
+ DEFAULT_CHARACTERISTICS: () => DEFAULT_CHARACTERISTICS,
28
35
  DEFAULT_SIGNED_AGENT_DIRECTORIES: () => DEFAULT_SIGNED_AGENT_DIRECTORIES,
29
36
  DEFAULT_TRIPWIRE_PATHS: () => DEFAULT_TRIPWIRE_PATHS,
30
37
  DEFAULT_WEIGHTS: () => DEFAULT_WEIGHTS,
38
+ Decision: () => Decision,
39
+ DecisionCache: () => DecisionCache,
31
40
  DetectionEngine: () => DetectionEngine,
32
41
  DirectoryCache: () => DirectoryCache,
33
42
  EDGE_CLASS_HEADER: () => EDGE_CLASS_HEADER,
@@ -38,6 +47,8 @@ __export(index_exports, {
38
47
  InMemoryFingerprintStore: () => InMemoryFingerprintStore,
39
48
  InMemoryRateLimiter: () => InMemoryRateLimiter2,
40
49
  InMemoryTokenStore: () => InMemoryTokenStore,
50
+ MemoryClientSignalStore: () => MemoryClientSignalStore,
51
+ MemoryRateLimitStore: () => MemoryRateLimitStore,
41
52
  PoWManager: () => PoWManager,
42
53
  RateLimitRule: () => RateLimitRule,
43
54
  RuleEngine: () => RuleEngine,
@@ -45,29 +56,44 @@ __export(index_exports, {
45
56
  TEST_TRIGGER_USER_AGENT: () => TEST_TRIGGER_USER_AGENT,
46
57
  TokenManager: () => TokenManager,
47
58
  TripwireRule: () => TripwireRule,
59
+ UpstashRateLimitStore: () => UpstashRateLimitStore,
48
60
  WebBotAuthRule: () => WebBotAuthRule,
49
61
  WebDecoy: () => WebDecoy,
62
+ attackSignatures: () => attackSignatures,
63
+ botPolicy: () => botPolicy,
50
64
  bots: () => bots,
51
65
  calculateCategoryScores: () => calculateCategoryScores,
52
66
  calculateFinalScore: () => calculateFinalScore,
53
67
  classifyUserAgent: () => classifyUserAgent,
68
+ clientSignals: () => clientSignals,
69
+ consoleLogger: () => consoleLogger,
54
70
  createAgentVerifier: () => createAgentVerifier,
55
71
  createCaptchaEndpoints: () => createCaptchaEndpoints,
72
+ createFetchGuard: () => createFetchGuard,
73
+ deriveKey: () => deriveKey,
56
74
  filter: () => filter,
75
+ fromPino: () => fromPino,
57
76
  honeytoken: () => honeytoken,
58
77
  injectHoneytokenLink: () => injectHoneytokenLink,
78
+ ipInCidr: () => ipInCidr,
59
79
  isDatacenterIP: () => isDatacenterIP2,
60
80
  isInjectableHtml: () => isInjectableHtml,
61
81
  isMobileUA: () => isMobileUA,
62
82
  isTestTriggerUserAgent: () => isTestTriggerUserAgent,
63
83
  matchUserAgent: () => matchUserAgent,
84
+ newDecisionId: () => newDecisionId,
85
+ normalizeIp: () => normalizeIp,
64
86
  parseUserAgent: () => parseUserAgent,
65
87
  rateLimit: () => rateLimit,
88
+ readClientSession: () => readClientSession,
66
89
  readEdgeVerdict: () => readEdgeVerdict,
67
90
  recommend: () => recommend,
91
+ resolveClientIp: () => resolveClientIp,
68
92
  resolveSecret: () => resolveSecret,
93
+ silentLogger: () => silentLogger,
69
94
  siteHoneytoken: () => siteHoneytoken,
70
95
  tripwire: () => tripwire,
96
+ upstashRateLimitStore: () => upstashRateLimitStore,
71
97
  webBotAuth: () => webBotAuth
72
98
  });
73
99
  module.exports = __toCommonJS(index_exports);
@@ -380,9 +406,19 @@ var RuleEngine = class {
380
406
  */
381
407
  evaluate(context) {
382
408
  const violations = [];
409
+ const results = [];
383
410
  let decidingResult = null;
384
411
  for (const rule of this.rules) {
385
412
  const result = rule.evaluate(context);
413
+ const dryRun = result.metadata?.dryRun === true;
414
+ results.push({
415
+ rule: result.rule,
416
+ state: result.state ?? (dryRun ? "DRY_RUN" : "RUN"),
417
+ conclusion: dryRun || result.action !== "ALLOW" ? "DENY" : "ALLOW",
418
+ action: result.action,
419
+ reason: result.reason,
420
+ metadata: result.metadata
421
+ });
386
422
  if (result.action !== "ALLOW") {
387
423
  violations.push({
388
424
  rule: result.rule,
@@ -394,10 +430,10 @@ var RuleEngine = class {
394
430
  reason: result.reason,
395
431
  clearance: result.rule === "tripwire" ? extractClearance(context.headers) : void 0,
396
432
  metadata: result.metadata,
397
- dryRun: result.metadata?.dryRun === true,
433
+ dryRun,
398
434
  timestamp: new Date(context.timestamp).toISOString()
399
435
  });
400
- if (!decidingResult && !result.metadata?.dryRun) {
436
+ if (!decidingResult && !dryRun) {
401
437
  decidingResult = result;
402
438
  }
403
439
  }
@@ -408,12 +444,14 @@ var RuleEngine = class {
408
444
  rule: decidingResult.rule,
409
445
  reason: decidingResult.reason,
410
446
  metadata: decidingResult.metadata,
411
- violations
447
+ violations,
448
+ results
412
449
  };
413
450
  }
414
451
  return {
415
452
  action: "ALLOW",
416
- violations
453
+ violations,
454
+ results
417
455
  };
418
456
  }
419
457
  /**
@@ -507,11 +545,25 @@ var InMemoryRateLimiter = class {
507
545
  }
508
546
  };
509
547
 
548
+ // src/rules/rate-limit-store.ts
549
+ var MemoryRateLimitStore = class {
550
+ constructor() {
551
+ this.sync = true;
552
+ this.limiter = new InMemoryRateLimiter();
553
+ }
554
+ consume({ key, max, windowMs, algorithm }) {
555
+ return algorithm === "sliding" ? this.limiter.checkSlidingWindow(key, max, windowMs) : this.limiter.checkFixedWindow(key, max, windowMs);
556
+ }
557
+ destroy() {
558
+ this.limiter.destroy();
559
+ }
560
+ };
561
+
510
562
  // src/rules/rate-limit-rule.ts
511
563
  var RateLimitRule = class {
512
564
  constructor(config) {
513
565
  this.name = `rate-limit:${config.max}/${config.window}s`;
514
- this.limiter = new InMemoryRateLimiter();
566
+ this.store = config.store ?? new MemoryRateLimitStore();
515
567
  this.config = {
516
568
  max: config.max,
517
569
  window: config.window,
@@ -521,10 +573,47 @@ var RateLimitRule = class {
521
573
  dryRun: config.dryRun ?? false
522
574
  };
523
575
  }
576
+ /**
577
+ * Which bucket this request counts against.
578
+ *
579
+ * Precedence: this rule's own keyBy, then the SDK-wide characteristics, then
580
+ * the IP. `context.key` is always populated, so the last fallback only matters
581
+ * for a context built by hand.
582
+ */
583
+ keyFor(context) {
584
+ return this.config.keyBy ? this.config.keyBy(context) : context.key ?? context.ip;
585
+ }
586
+ consumption(context) {
587
+ return {
588
+ key: this.keyFor(context),
589
+ max: this.config.max,
590
+ windowMs: this.config.window * 1e3,
591
+ algorithm: this.config.algorithm
592
+ };
593
+ }
594
+ /** Consume from a networked store before evaluation. No-op for a sync store. */
595
+ async prepare(context) {
596
+ if (this.store.sync) return;
597
+ const outcome = await this.store.consume(this.consumption(context));
598
+ context.prepared ?? (context.prepared = {});
599
+ context.prepared[this.name] = outcome;
600
+ }
524
601
  evaluate(context) {
525
- const key = this.config.keyBy ? this.config.keyBy(context) : context.ip;
526
- const windowMs = this.config.window * 1e3;
527
- const result = this.config.algorithm === "sliding" ? this.limiter.checkSlidingWindow(key, this.config.max, windowMs) : this.limiter.checkFixedWindow(key, this.config.max, windowMs);
602
+ let result;
603
+ if (this.store.sync) {
604
+ result = this.store.consume(this.consumption(context));
605
+ } else {
606
+ const prepared = context.prepared?.[this.name];
607
+ if (!prepared) {
608
+ return {
609
+ action: "ALLOW",
610
+ rule: this.name,
611
+ state: "NOT_RUN",
612
+ reason: "Rate limit uses an async store and was not prepared \u2014 call protect() or evaluateRulesAsync()"
613
+ };
614
+ }
615
+ result = prepared;
616
+ }
528
617
  if (!result.allowed) {
529
618
  const retryAfter = Math.ceil((result.resetAt - Date.now()) / 1e3);
530
619
  return {
@@ -551,7 +640,7 @@ var RateLimitRule = class {
551
640
  };
552
641
  }
553
642
  destroy() {
554
- this.limiter.destroy();
643
+ void this.store.destroy?.();
555
644
  }
556
645
  };
557
646
 
@@ -756,7 +845,7 @@ var Parser = class {
756
845
  return this.comparison();
757
846
  }
758
847
  comparison() {
759
- let left = this.primary();
848
+ const left = this.primary();
760
849
  if (this.match("EQ" /* EQ */)) return { kind: "binary", op: "==", left, right: this.primary() };
761
850
  if (this.match("NEQ" /* NEQ */)) return { kind: "binary", op: "!=", left, right: this.primary() };
762
851
  if (this.match("GT" /* GT */)) return { kind: "binary", op: ">", left, right: this.primary() };
@@ -1013,6 +1102,14 @@ var FilterRule = class {
1013
1102
  this.ast = parser.parse();
1014
1103
  }
1015
1104
  evaluate(context) {
1105
+ if (!context.enrichment && this.expression.includes("ip.")) {
1106
+ return {
1107
+ action: "ALLOW",
1108
+ rule: this.name,
1109
+ state: "NOT_RUN",
1110
+ reason: "No IP enrichment available \u2014 filter needs an API key"
1111
+ };
1112
+ }
1016
1113
  const result = evaluate(this.ast, context);
1017
1114
  if (result) {
1018
1115
  return {
@@ -1122,1199 +1219,1690 @@ var BotRule = class {
1122
1219
  }
1123
1220
  };
1124
1221
 
1125
- // src/rules/web-bot-auth-rule.ts
1126
- var WebBotAuthRule = class {
1127
- constructor(config = {}) {
1128
- this.name = "web-bot-auth";
1129
- this.onImpersonation = config.onImpersonation ?? "DENY";
1130
- this.onClaimed = config.onClaimed ?? "ALLOW";
1131
- this.allowCategories = config.allowCategories ? new Set(config.allowCategories) : void 0;
1132
- this.dryRun = config.dryRun ?? false;
1133
- }
1134
- evaluate(context) {
1135
- const verdict = context.agent;
1136
- if (!verdict || verdict.status === "none") return this.allow();
1137
- if (verdict.status === "impersonation") {
1138
- return this.act(this.onImpersonation, "agent_impersonation", {
1139
- agentName: verdict.agentName,
1140
- category: verdict.category,
1141
- keyId: verdict.keyId,
1142
- detail: verdict.reason
1143
- });
1144
- }
1145
- if (verdict.status === "claimed") {
1146
- return this.act(this.onClaimed, "agent_unverifiable", {
1147
- keyId: verdict.keyId,
1148
- detail: verdict.reason
1149
- });
1150
- }
1151
- if (this.allowCategories && verdict.category && !this.allowCategories.has(verdict.category)) {
1152
- return this.act(this.onClaimed, "agent_category_not_allowed", {
1153
- agentName: verdict.agentName,
1154
- category: verdict.category,
1155
- keyId: verdict.keyId
1156
- });
1157
- }
1158
- return this.allow();
1159
- }
1160
- act(action, verdict, detail) {
1161
- if (action === "ALLOW") return this.allow();
1162
- return {
1163
- action: this.dryRun ? "ALLOW" : action,
1164
- rule: this.name,
1165
- reason: reasonFor(verdict),
1166
- metadata: { verdict, dryRun: this.dryRun, ...detail }
1167
- };
1168
- }
1169
- allow() {
1170
- return { action: "ALLOW", rule: this.name };
1171
- }
1172
- };
1173
- function reasonFor(verdict) {
1174
- switch (verdict) {
1175
- case "agent_impersonation":
1176
- return "Web Bot Auth signature failed verification (agent impersonation)";
1177
- case "agent_unverifiable":
1178
- return "Web Bot Auth signature could not be verified";
1179
- case "agent_category_not_allowed":
1180
- return "Verified agent category is not allowed";
1181
- default:
1182
- return "Web Bot Auth rule triggered";
1183
- }
1184
- }
1185
- function webBotAuth(config = {}) {
1186
- return new WebBotAuthRule(config);
1187
- }
1188
-
1189
- // src/webcrypto.ts
1190
- var encoder = new TextEncoder();
1191
- function toHex(bytes) {
1192
- let hex = "";
1193
- for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
1194
- return hex;
1195
- }
1196
- async function sha256Hex(data) {
1197
- const digest2 = await crypto.subtle.digest("SHA-256", encoder.encode(data));
1198
- return toHex(new Uint8Array(digest2));
1199
- }
1200
- async function hmacSha256Hex(secret, data) {
1201
- const key = await crypto.subtle.importKey(
1202
- "raw",
1203
- encoder.encode(secret),
1204
- { name: "HMAC", hash: "SHA-256" },
1205
- false,
1206
- ["sign"]
1207
- );
1208
- const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(data));
1209
- return toHex(new Uint8Array(sig));
1210
- }
1211
- function randomHex(bytes) {
1212
- const buf = new Uint8Array(bytes);
1213
- crypto.getRandomValues(buf);
1214
- return toHex(buf);
1215
- }
1216
- function timingSafeEqualStr(a, b) {
1217
- if (a.length !== b.length) return false;
1218
- let diff = 0;
1219
- for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
1220
- return diff === 0;
1221
- }
1222
- function base64urlEncode(data) {
1223
- const bytes = encoder.encode(data);
1224
- let binary = "";
1225
- for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1226
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1227
- }
1228
- function base64urlDecode(data) {
1229
- const b64 = data.replace(/-/g, "+").replace(/_/g, "/");
1230
- const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
1231
- const binary = atob(padded);
1232
- const bytes = new Uint8Array(binary.length);
1233
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1234
- return new TextDecoder().decode(bytes);
1235
- }
1236
- function fnv1a64Hex(data) {
1237
- const PRIME = 0x100000001b3n;
1238
- const MASK = 0xffffffffffffffffn;
1239
- let hash = 0xcbf29ce484222325n;
1240
- const bytes = encoder.encode(data);
1241
- for (let i = 0; i < bytes.length; i++) {
1242
- hash ^= BigInt(bytes[i]);
1243
- hash = hash * PRIME & MASK;
1244
- }
1245
- return hash.toString(16).padStart(16, "0");
1246
- }
1247
-
1248
- // src/rules/honeytoken.ts
1249
- function honeytoken(options = {}) {
1250
- const base = (options.basePath ?? "/__wd").replace(/\/+$/, "");
1251
- const token = options.token ?? randomHex(6);
1252
- const path = `${base}/${token}`;
1253
- const text = options.text ?? ".";
1254
- 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>`;
1255
- return { path, linkHtml };
1256
- }
1257
-
1258
- // src/rules/honeytoken-site.ts
1259
- var HONEYTOKEN_BASE_PATH = "/__wd";
1260
- var TOKEN_LEN = 12;
1261
- function utcDay(offsetDays = 0) {
1262
- const d = new Date(Date.now() + offsetDays * 864e5);
1263
- return d.toISOString().slice(0, 10);
1264
- }
1265
- function escapeHtml(v) {
1266
- return v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1267
- }
1268
- function linkFor(path, text) {
1269
- text = escapeHtml(text);
1270
- 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>`;
1271
- }
1272
- var HIDDEN_STYLE = {
1273
- position: "absolute",
1274
- left: "-9999px",
1275
- top: "auto",
1276
- width: "1px",
1277
- height: "1px",
1278
- overflow: "hidden"
1279
- };
1280
- function propsFor(path, text) {
1281
- return {
1282
- href: path,
1283
- rel: "nofollow noindex",
1284
- tabIndex: -1,
1285
- "aria-hidden": "true",
1286
- style: HIDDEN_STYLE,
1287
- text
1288
- };
1289
- }
1290
- async function siteHoneytoken(options) {
1291
- const base = (options.basePath ?? HONEYTOKEN_BASE_PATH).replace(/\/+$/, "");
1292
- const text = options.text ?? ".";
1293
- const derive = async (label) => `${base}/${(await hmacSha256Hex(options.secret, label)).slice(0, TOKEN_LEN)}`;
1294
- if (!options.rotate) {
1295
- const path = await derive("stable");
1296
- return {
1297
- primaryPath: path,
1298
- activePaths: [path],
1299
- linkHtml: linkFor(path, text),
1300
- linkProps: propsFor(path, text)
1301
- };
1302
- }
1303
- const today = await derive(`day:${utcDay(0)}`);
1304
- const yesterday = await derive(`day:${utcDay(-1)}`);
1305
- return {
1306
- primaryPath: today,
1307
- // Yesterday stays armed so a crawler that read the page before midnight and
1308
- // follows the link after it still trips.
1309
- activePaths: Array.from(/* @__PURE__ */ new Set([today, yesterday])),
1310
- linkHtml: linkFor(today, text),
1311
- linkProps: propsFor(today, text)
1312
- };
1313
- }
1314
- function injectHoneytokenLink(html, linkHtml) {
1315
- if (!html || html.includes(linkHtml)) return html;
1316
- const lower = html.toLowerCase();
1317
- for (const close of ["</body>", "</html>"]) {
1318
- const at = lower.lastIndexOf(close);
1319
- if (at !== -1) {
1320
- return html.slice(0, at) + linkHtml + html.slice(at);
1321
- }
1322
- }
1323
- return html;
1324
- }
1325
- function isInjectableHtml(contentType) {
1326
- if (!contentType) return false;
1327
- return contentType.toLowerCase().split(";")[0].trim() === "text/html";
1328
- }
1329
-
1330
- // src/rules/index.ts
1331
- function rateLimit(config) {
1332
- return new RateLimitRule(config);
1333
- }
1334
- function filter(config) {
1335
- return new FilterRule(config);
1336
- }
1337
- function tripwire(config = {}) {
1338
- return new TripwireRule(config);
1339
- }
1340
- function bots(config = {}) {
1341
- return new BotRule(config);
1342
- }
1343
-
1344
- // src/violation-reporter.ts
1345
- var ViolationReporter = class {
1346
- constructor(client, config = {}) {
1347
- this.buffer = [];
1348
- this.flushing = false;
1349
- this.client = client;
1350
- this.maxBufferSize = config.maxBufferSize ?? 50;
1351
- this.debug = config.debug ?? false;
1352
- const flushInterval = config.flushInterval ?? 5e3;
1353
- this.flushTimer = setInterval(() => this.flush(), flushInterval);
1354
- if (this.flushTimer.unref) {
1355
- this.flushTimer.unref();
1222
+ // src/bots/registry.generated.ts
1223
+ var BOT_CATEGORIES = [
1224
+ "training_crawler",
1225
+ "ai_search_crawler",
1226
+ "ai_agent",
1227
+ "ai_assistant",
1228
+ "search_crawler",
1229
+ "seo_crawler",
1230
+ "security_scanner",
1231
+ "generic_scraper",
1232
+ "archiver",
1233
+ "fetcher",
1234
+ "monitoring",
1235
+ "headless_browser",
1236
+ "feed_reader",
1237
+ "commercial_scraper",
1238
+ "none"
1239
+ ];
1240
+ var BOT_REGISTRY = [
1241
+ { id: "gptbot", name: "GPTBot", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["gptbot"] },
1242
+ { id: "chatgpt-user", name: "ChatGPT-User", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["chatgpt-user", "chatgpt"] },
1243
+ { id: "oai-searchbot", name: "OAI-SearchBot", category: "training_crawler", organization: "OpenAI", baseScore: 80, respectsRobots: true, uaPatterns: ["oai-searchbot"] },
1244
+ { id: "claudebot", name: "ClaudeBot", category: "training_crawler", organization: "Anthropic", baseScore: 85, respectsRobots: true, uaPatterns: ["claudebot"] },
1245
+ { id: "anthropic", name: "Anthropic", category: "training_crawler", organization: "Anthropic", baseScore: 85, respectsRobots: true, uaPatterns: ["anthropic"] },
1246
+ { id: "ccbot", name: "CCBot", category: "training_crawler", organization: "Common Crawl", baseScore: 80, respectsRobots: true, uaPatterns: ["ccbot"] },
1247
+ { id: "google-extended", name: "Google-Extended", category: "training_crawler", organization: "Google", baseScore: 80, respectsRobots: true, uaPatterns: ["google-extended"] },
1248
+ { id: "bytespider", name: "ByteSpider", category: "training_crawler", organization: "ByteDance", baseScore: 75, respectsRobots: false, uaPatterns: ["bytespider"] },
1249
+ { id: "amazonbot", name: "Amazonbot", category: "training_crawler", organization: "Amazon", baseScore: 70, respectsRobots: true, uaPatterns: ["amazonbot"] },
1250
+ { id: "facebookbot", name: "FacebookBot", category: "training_crawler", organization: "Meta", baseScore: 70, respectsRobots: true, uaPatterns: ["facebookbot"] },
1251
+ { id: "meta-externalagent", name: "Meta-ExternalAgent", category: "training_crawler", organization: "Meta", baseScore: 75, respectsRobots: true, uaPatterns: ["meta-externalagent"] },
1252
+ { id: "cohere-ai", name: "Cohere", category: "training_crawler", organization: "Cohere", baseScore: 80, respectsRobots: true, uaPatterns: ["cohere-ai", "cohere"] },
1253
+ { id: "perplexitybot", name: "PerplexityBot", category: "training_crawler", organization: "Perplexity AI", baseScore: 80, respectsRobots: true, uaPatterns: ["perplexitybot"] },
1254
+ { id: "applebot-extended", name: "Applebot-Extended", category: "training_crawler", organization: "Apple", baseScore: 75, respectsRobots: true, uaPatterns: ["applebot-extended"] },
1255
+ { id: "youbot", name: "YouBot", category: "training_crawler", organization: "You.com", baseScore: 75, respectsRobots: true, uaPatterns: ["youbot"] },
1256
+ { id: "mistral", name: "MistralBot", category: "training_crawler", organization: "Mistral AI", baseScore: 80, respectsRobots: true, uaPatterns: ["mistral"] },
1257
+ { id: "gemini", name: "Gemini", category: "training_crawler", organization: "Google", baseScore: 80, respectsRobots: true, uaPatterns: ["gemini"] },
1258
+ { id: "ai2bot", name: "AI2Bot", category: "training_crawler", organization: "Allen Institute for AI", baseScore: 75, respectsRobots: true, uaPatterns: ["ai2bot"] },
1259
+ { id: "deepseek", name: "DeepSeek", category: "training_crawler", organization: "DeepSeek", baseScore: 80, respectsRobots: true, uaPatterns: ["deepseek"] },
1260
+ { id: "qwen", name: "Qwen", category: "training_crawler", organization: "Alibaba", baseScore: 75, respectsRobots: true, uaPatterns: ["qwen"] },
1261
+ { id: "webzio", name: "Webz.io", category: "training_crawler", organization: "Webz.io", baseScore: 70, respectsRobots: false, uaPatterns: ["webzio"] },
1262
+ { id: "sentibot", name: "Sentibot", category: "training_crawler", organization: "Sentibot", baseScore: 70, respectsRobots: false, uaPatterns: ["sentibot"] },
1263
+ { id: "omgili", name: "Omgili", category: "training_crawler", organization: "Webz.io", baseScore: 70, respectsRobots: false, uaPatterns: ["omgili"] },
1264
+ { id: "img2dataset", name: "img2dataset", category: "training_crawler", organization: "LAION", baseScore: 75, respectsRobots: false, uaPatterns: ["img2dataset"] },
1265
+ { id: "timpibot", name: "Timpibot", category: "training_crawler", organization: "Timpi", baseScore: 70, respectsRobots: true, uaPatterns: ["timpibot"] },
1266
+ { id: "velenpublicwebcrawler", name: "VelenPublicWebCrawler", category: "training_crawler", organization: "Velen", baseScore: 70, respectsRobots: false, uaPatterns: ["velenpublicwebcrawler"] },
1267
+ { id: "isscyberriskcrawler", name: "ISSCyberRiskCrawler", category: "training_crawler", organization: "ISS", baseScore: 65, respectsRobots: false, uaPatterns: ["isscyberriskcrawler"] },
1268
+ { id: "friendlycrawler", name: "FriendlyCrawler", category: "training_crawler", organization: "Unknown", baseScore: 65, respectsRobots: true, uaPatterns: ["friendlycrawler"] },
1269
+ { id: "searchgpt", name: "SearchGPT", category: "ai_search_crawler", organization: "OpenAI", baseScore: 75, respectsRobots: true, uaPatterns: ["searchgpt"] },
1270
+ { id: "phind", name: "Phind", category: "ai_search_crawler", organization: "Phind", baseScore: 70, respectsRobots: true, uaPatterns: ["phind"] },
1271
+ { id: "kagi", name: "Kagi", category: "ai_search_crawler", organization: "Kagi", baseScore: 65, respectsRobots: true, uaPatterns: ["kagi"] },
1272
+ { id: "exa", name: "Exa", category: "ai_search_crawler", organization: "Exa AI", baseScore: 70, respectsRobots: true, uaPatterns: ["exa.ai", "exabot"] },
1273
+ { id: "metaphor", name: "Metaphor", category: "ai_search_crawler", organization: "Metaphor", baseScore: 70, respectsRobots: true, uaPatterns: ["metaphor"] },
1274
+ { id: "tavily", name: "Tavily", category: "ai_search_crawler", organization: "Tavily", baseScore: 70, respectsRobots: true, uaPatterns: ["tavily"] },
1275
+ { id: "brave-search", name: "BraveSearch", category: "ai_search_crawler", organization: "Brave", baseScore: 65, respectsRobots: true, uaPatterns: ["bravesearch"] },
1276
+ { id: "neeva", name: "NeevaBot", category: "ai_search_crawler", organization: "Neeva", baseScore: 65, respectsRobots: true, uaPatterns: ["neevabot"] },
1277
+ { id: "operator", name: "Operator", category: "ai_agent", organization: "OpenAI", baseScore: 75, respectsRobots: true, uaPatterns: ["operator"] },
1278
+ { id: "claude-user", name: "Claude-User", category: "ai_agent", organization: "Anthropic", baseScore: 75, respectsRobots: true, uaPatterns: ["claude-user"] },
1279
+ { id: "gemini-user", name: "Gemini-User", category: "ai_agent", organization: "Google", baseScore: 75, respectsRobots: true, uaPatterns: ["gemini-user"] },
1280
+ { id: "googleagent-mariner", name: "GoogleAgent-Mariner", category: "ai_agent", organization: "Google", baseScore: 75, respectsRobots: true, uaPatterns: ["googleagent-mariner", "mariner"] },
1281
+ { id: "amazon-buyforme", name: "AmazonBuyForMe", category: "ai_agent", organization: "Amazon", baseScore: 70, respectsRobots: true, uaPatterns: ["amazonbuyforme", "buyforme"] },
1282
+ { id: "browser-use", name: "Browser-Use", category: "ai_agent", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["browser-use"] },
1283
+ { id: "stagehand", name: "Stagehand", category: "ai_agent", organization: "Browserbase", baseScore: 70, respectsRobots: false, uaPatterns: ["stagehand"] },
1284
+ { id: "multion", name: "MultiOn", category: "ai_agent", organization: "MultiOn", baseScore: 70, respectsRobots: false, uaPatterns: ["multion"] },
1285
+ { id: "googlebot", name: "Googlebot", category: "search_crawler", organization: "Google", baseScore: 30, respectsRobots: true, uaPatterns: ["googlebot"] },
1286
+ { id: "bingbot", name: "Bingbot", category: "search_crawler", organization: "Microsoft", baseScore: 30, respectsRobots: true, uaPatterns: ["bingbot"] },
1287
+ { id: "yandexbot", name: "YandexBot", category: "search_crawler", organization: "Yandex", baseScore: 35, respectsRobots: true, uaPatterns: ["yandexbot"] },
1288
+ { id: "baiduspider", name: "Baiduspider", category: "search_crawler", organization: "Baidu", baseScore: 40, respectsRobots: true, uaPatterns: ["baiduspider"] },
1289
+ { id: "duckduckbot", name: "DuckDuckBot", category: "search_crawler", organization: "DuckDuckGo", baseScore: 30, respectsRobots: true, uaPatterns: ["duckduckbot"] },
1290
+ { id: "applebot", name: "Applebot", category: "search_crawler", organization: "Apple", baseScore: 30, respectsRobots: true, uaPatterns: ["applebot"] },
1291
+ { id: "sogou", name: "Sogou Spider", category: "search_crawler", organization: "Sogou", baseScore: 40, respectsRobots: true, uaPatterns: ["sogou"] },
1292
+ { id: "qwantify", name: "Qwantify", category: "search_crawler", organization: "Qwant", baseScore: 35, respectsRobots: true, uaPatterns: ["qwantify"] },
1293
+ { id: "naver", name: "Naver", category: "search_crawler", organization: "Naver", baseScore: 35, respectsRobots: true, uaPatterns: ["naver", "yeti"] },
1294
+ { id: "seznam", name: "SeznamBot", category: "search_crawler", organization: "Seznam", baseScore: 35, respectsRobots: true, uaPatterns: ["seznambot"] },
1295
+ { id: "ecosia", name: "Ecosia", category: "search_crawler", organization: "Ecosia", baseScore: 30, respectsRobots: true, uaPatterns: ["ecosia"] },
1296
+ { id: "mojeek", name: "MojeekBot", category: "search_crawler", organization: "Mojeek", baseScore: 35, respectsRobots: true, uaPatterns: ["mojeekbot"] },
1297
+ { id: "yahoo-slurp", name: "Yahoo! Slurp", category: "search_crawler", organization: "Yahoo", baseScore: 30, respectsRobots: true, uaPatterns: ["slurp"] },
1298
+ { id: "ahrefsbot", name: "AhrefsBot", category: "seo_crawler", organization: "Ahrefs", baseScore: 50, respectsRobots: true, uaPatterns: ["ahrefsbot", "ahrefs"] },
1299
+ { id: "semrushbot", name: "SemrushBot", category: "seo_crawler", organization: "Semrush", baseScore: 50, respectsRobots: true, uaPatterns: ["semrushbot", "semrush"] },
1300
+ { id: "mj12bot", name: "MJ12bot", category: "seo_crawler", organization: "Majestic", baseScore: 50, respectsRobots: true, uaPatterns: ["mj12bot"] },
1301
+ { id: "dotbot", name: "DotBot", category: "seo_crawler", organization: "Moz", baseScore: 50, respectsRobots: true, uaPatterns: ["dotbot"] },
1302
+ { id: "rogerbot", name: "Rogerbot", category: "seo_crawler", organization: "Moz", baseScore: 50, respectsRobots: true, uaPatterns: ["rogerbot"] },
1303
+ { id: "screaming-frog", name: "Screaming Frog", category: "seo_crawler", organization: "Screaming Frog", baseScore: 55, respectsRobots: true, uaPatterns: ["screaming frog"] },
1304
+ { id: "sitebulb", name: "Sitebulb", category: "seo_crawler", organization: "Sitebulb", baseScore: 55, respectsRobots: true, uaPatterns: ["sitebulb"] },
1305
+ { id: "deepcrawl", name: "DeepCrawl", category: "seo_crawler", organization: "Lumar", baseScore: 50, respectsRobots: true, uaPatterns: ["deepcrawl"] },
1306
+ { id: "oncrawl", name: "OnCrawl", category: "seo_crawler", organization: "OnCrawl", baseScore: 50, respectsRobots: true, uaPatterns: ["oncrawl"] },
1307
+ { id: "botify", name: "Botify", category: "seo_crawler", organization: "Botify", baseScore: 50, respectsRobots: true, uaPatterns: ["botify"] },
1308
+ { id: "contentking", name: "ContentKing", category: "seo_crawler", organization: "ContentKing", baseScore: 50, respectsRobots: true, uaPatterns: ["contentking"] },
1309
+ { id: "sistrix", name: "SISTRIX", category: "seo_crawler", organization: "SISTRIX", baseScore: 50, respectsRobots: true, uaPatterns: ["sistrix"] },
1310
+ { id: "serpstat", name: "Serpstat", category: "seo_crawler", organization: "Serpstat", baseScore: 50, respectsRobots: true, uaPatterns: ["serpstat"] },
1311
+ { id: "spyfu", name: "SpyFu", category: "seo_crawler", organization: "SpyFu", baseScore: 50, respectsRobots: true, uaPatterns: ["spyfu"] },
1312
+ { id: "nessus", name: "Nessus", category: "security_scanner", organization: "Tenable", baseScore: 70, respectsRobots: false, uaPatterns: ["nessus"] },
1313
+ { id: "qualys", name: "Qualys", category: "security_scanner", organization: "Qualys", baseScore: 70, respectsRobots: false, uaPatterns: ["qualys"] },
1314
+ { id: "shodan", name: "Shodan", category: "security_scanner", organization: "Shodan", baseScore: 75, respectsRobots: false, uaPatterns: ["shodan"] },
1315
+ { id: "censys", name: "Censys", category: "security_scanner", organization: "Censys", baseScore: 75, respectsRobots: false, uaPatterns: ["censys"] },
1316
+ { id: "nmap", name: "Nmap", category: "security_scanner", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["nmap"] },
1317
+ { id: "zap", name: "OWASP ZAP", category: "security_scanner", organization: "OWASP", baseScore: 70, respectsRobots: false, uaPatterns: ["zap/"] },
1318
+ { id: "burp", name: "Burp Suite", category: "security_scanner", organization: "PortSwigger", baseScore: 70, respectsRobots: false, uaPatterns: ["burp"] },
1319
+ { id: "nikto", name: "Nikto", category: "security_scanner", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["nikto"] },
1320
+ { id: "nuclei", name: "Nuclei", category: "security_scanner", organization: "ProjectDiscovery", baseScore: 70, respectsRobots: false, uaPatterns: ["nuclei"] },
1321
+ { id: "acunetix", name: "Acunetix", category: "security_scanner", organization: "Invicti", baseScore: 70, respectsRobots: false, uaPatterns: ["acunetix"] },
1322
+ { id: "netsparker", name: "Netsparker", category: "security_scanner", organization: "Invicti", baseScore: 70, respectsRobots: false, uaPatterns: ["netsparker"] },
1323
+ { id: "detectify", name: "Detectify", category: "security_scanner", organization: "Detectify", baseScore: 65, respectsRobots: false, uaPatterns: ["detectify"] },
1324
+ { id: "intruder", name: "Intruder", category: "security_scanner", organization: "Intruder", baseScore: 65, respectsRobots: false, uaPatterns: ["intruder"] },
1325
+ { id: "python-requests", name: "Python-Requests", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["python-requests"] },
1326
+ { id: "python-urllib", name: "Python-urllib", category: "generic_scraper", organization: "Python", baseScore: 55, respectsRobots: false, uaPatterns: ["python-urllib"] },
1327
+ { id: "python", name: "Python", category: "generic_scraper", organization: "Python", baseScore: 50, respectsRobots: false, uaPatterns: ["python/"] },
1328
+ { id: "scrapy", name: "Scrapy", category: "generic_scraper", organization: "Scrapy", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapy"] },
1329
+ { id: "httpx", name: "HTTPX", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["httpx"] },
1330
+ { id: "aiohttp", name: "aiohttp", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["aiohttp"] },
1331
+ { id: "beautifulsoup", name: "BeautifulSoup", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["beautifulsoup"] },
1332
+ { id: "node-fetch", name: "node-fetch", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["node-fetch"] },
1333
+ { id: "axios", name: "Axios", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["axios/"] },
1334
+ { id: "got", name: "Got", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["got/"] },
1335
+ { id: "undici", name: "Undici", category: "generic_scraper", organization: "Node.js", baseScore: 55, respectsRobots: false, uaPatterns: ["undici"] },
1336
+ { id: "go-http-client", name: "Go-HTTP-Client", category: "generic_scraper", organization: "Go", baseScore: 55, respectsRobots: false, uaPatterns: ["go-http-client"] },
1337
+ { id: "colly", name: "Colly", category: "generic_scraper", organization: "Open Source", baseScore: 65, respectsRobots: true, uaPatterns: ["colly"] },
1338
+ { id: "java", name: "Java", category: "generic_scraper", organization: "Oracle", baseScore: 50, respectsRobots: false, uaPatterns: ["java/"] },
1339
+ { id: "okhttp", name: "OkHttp", category: "generic_scraper", organization: "Square", baseScore: 55, respectsRobots: false, uaPatterns: ["okhttp"] },
1340
+ { id: "apache-httpclient", name: "Apache-HttpClient", category: "generic_scraper", organization: "Apache", baseScore: 55, respectsRobots: false, uaPatterns: ["apache-httpclient"] },
1341
+ { id: "jsoup", name: "Jsoup", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["jsoup"] },
1342
+ { id: "guzzlehttp", name: "GuzzleHttp", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["guzzlehttp"] },
1343
+ { id: "php", name: "PHP", category: "generic_scraper", organization: "PHP", baseScore: 50, respectsRobots: false, uaPatterns: ["php/"] },
1344
+ { id: "ruby", name: "Ruby", category: "generic_scraper", organization: "Ruby", baseScore: 50, respectsRobots: false, uaPatterns: ["ruby"] },
1345
+ { id: "faraday", name: "Faraday", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["faraday"] },
1346
+ { id: "mechanize", name: "Mechanize", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["mechanize"] },
1347
+ { id: "headlesschrome", name: "HeadlessChrome", category: "headless_browser", organization: "Google", baseScore: 70, respectsRobots: false, uaPatterns: ["headlesschrome"] },
1348
+ { id: "puppeteer", name: "Puppeteer", category: "headless_browser", organization: "Google", baseScore: 70, respectsRobots: false, uaPatterns: ["puppeteer"] },
1349
+ { id: "playwright", name: "Playwright", category: "headless_browser", organization: "Microsoft", baseScore: 70, respectsRobots: false, uaPatterns: ["playwright"] },
1350
+ { id: "selenium", name: "Selenium", category: "headless_browser", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["selenium"] },
1351
+ { id: "phantomjs", name: "PhantomJS", category: "headless_browser", organization: "Open Source", baseScore: 75, respectsRobots: false, uaPatterns: ["phantomjs"] },
1352
+ { id: "splash", name: "Splash", category: "headless_browser", organization: "Scrapinghub", baseScore: 70, respectsRobots: false, uaPatterns: ["splash"] },
1353
+ { id: "browserless", name: "Browserless", category: "headless_browser", organization: "Browserless", baseScore: 65, respectsRobots: false, uaPatterns: ["browserless"] },
1354
+ { id: "browserbase", name: "Browserbase", category: "headless_browser", organization: "Browserbase", baseScore: 65, respectsRobots: false, uaPatterns: ["browserbase"] },
1355
+ { id: "ia-archiver", name: "Internet Archive", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["ia_archiver"] },
1356
+ { id: "archive-org-bot", name: "Archive.org", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["archive.org_bot"] },
1357
+ { id: "wayback", name: "Wayback Machine", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["wayback"] },
1358
+ { id: "heritrix", name: "Heritrix", category: "archiver", organization: "Internet Archive", baseScore: 30, respectsRobots: true, uaPatterns: ["heritrix"] },
1359
+ { id: "brozzler", name: "Brozzler", category: "archiver", organization: "Internet Archive", baseScore: 30, respectsRobots: true, uaPatterns: ["brozzler"] },
1360
+ { id: "facebookexternalhit", name: "Facebook", category: "fetcher", organization: "Meta", baseScore: 25, respectsRobots: true, uaPatterns: ["facebookexternalhit"] },
1361
+ { id: "twitterbot", name: "Twitterbot", category: "fetcher", organization: "X Corp", baseScore: 25, respectsRobots: true, uaPatterns: ["twitterbot"] },
1362
+ { id: "linkedinbot", name: "LinkedInBot", category: "fetcher", organization: "LinkedIn", baseScore: 25, respectsRobots: true, uaPatterns: ["linkedinbot"] },
1363
+ { id: "slackbot", name: "Slackbot", category: "fetcher", organization: "Slack", baseScore: 25, respectsRobots: true, uaPatterns: ["slackbot"] },
1364
+ { id: "telegrambot", name: "TelegramBot", category: "fetcher", organization: "Telegram", baseScore: 25, respectsRobots: true, uaPatterns: ["telegrambot"] },
1365
+ { id: "whatsapp", name: "WhatsApp", category: "fetcher", organization: "Meta", baseScore: 25, respectsRobots: true, uaPatterns: ["whatsapp"] },
1366
+ { id: "discordbot", name: "Discordbot", category: "fetcher", organization: "Discord", baseScore: 25, respectsRobots: true, uaPatterns: ["discordbot"] },
1367
+ { id: "pinterestbot", name: "Pinterest", category: "fetcher", organization: "Pinterest", baseScore: 30, respectsRobots: true, uaPatterns: ["pinterest"] },
1368
+ { id: "tumblr", name: "Tumblr", category: "fetcher", organization: "Automattic", baseScore: 30, respectsRobots: true, uaPatterns: ["tumblr"] },
1369
+ { id: "reddit", name: "Reddit", category: "fetcher", organization: "Reddit", baseScore: 30, respectsRobots: true, uaPatterns: ["reddit"] },
1370
+ { id: "embedly", name: "Embedly", category: "fetcher", organization: "Medium", baseScore: 30, respectsRobots: true, uaPatterns: ["embedly"] },
1371
+ { id: "iframely", name: "Iframely", category: "fetcher", organization: "Iframely", baseScore: 30, respectsRobots: true, uaPatterns: ["iframely"] },
1372
+ { id: "curl", name: "cURL", category: "fetcher", organization: "Open Source", baseScore: 45, respectsRobots: false, uaPatterns: ["curl/"] },
1373
+ { id: "wget", name: "Wget", category: "fetcher", organization: "GNU", baseScore: 45, respectsRobots: false, uaPatterns: ["wget/"] },
1374
+ { id: "libwww-perl", name: "libwww-perl", category: "fetcher", organization: "Perl", baseScore: 50, respectsRobots: false, uaPatterns: ["libwww-perl"] },
1375
+ { id: "lwp", name: "LWP", category: "fetcher", organization: "Perl", baseScore: 50, respectsRobots: false, uaPatterns: ["lwp-"] },
1376
+ { id: "httrack", name: "HTTrack", category: "fetcher", organization: "Open Source", baseScore: 60, respectsRobots: true, uaPatterns: ["httrack"] },
1377
+ { id: "webdecoybot", name: "WebDecoyBot", category: "monitoring", organization: "WebDecoy", baseScore: 5, respectsRobots: true, uaPatterns: ["webdecoybot"] },
1378
+ { id: "uptimerobot", name: "UptimeRobot", category: "monitoring", organization: "UptimeRobot", baseScore: 20, respectsRobots: true, uaPatterns: ["uptimerobot"] },
1379
+ { id: "pingdom", name: "Pingdom", category: "monitoring", organization: "SolarWinds", baseScore: 20, respectsRobots: true, uaPatterns: ["pingdom"] },
1380
+ { id: "statuscake", name: "StatusCake", category: "monitoring", organization: "StatusCake", baseScore: 20, respectsRobots: true, uaPatterns: ["statuscake"] },
1381
+ { id: "better-uptime", name: "Better Uptime", category: "monitoring", organization: "Better Stack", baseScore: 20, respectsRobots: true, uaPatterns: ["betteruptime"] },
1382
+ { id: "datadog-synthetics", name: "Datadog Synthetics", category: "monitoring", organization: "Datadog", baseScore: 25, respectsRobots: true, uaPatterns: ["datadog"] },
1383
+ { id: "newrelic", name: "New Relic", category: "monitoring", organization: "New Relic", baseScore: 25, respectsRobots: true, uaPatterns: ["newrelic"] },
1384
+ { id: "site24x7", name: "Site24x7", category: "monitoring", organization: "Zoho", baseScore: 20, respectsRobots: true, uaPatterns: ["site24x7"] },
1385
+ { id: "freshping", name: "Freshping", category: "monitoring", organization: "Freshworks", baseScore: 20, respectsRobots: true, uaPatterns: ["freshping"] },
1386
+ { id: "hetrixtools", name: "HetrixTools", category: "monitoring", organization: "HetrixTools", baseScore: 20, respectsRobots: true, uaPatterns: ["hetrixtools"] },
1387
+ { id: "nodeping", name: "NodePing", category: "monitoring", organization: "NodePing", baseScore: 20, respectsRobots: true, uaPatterns: ["nodeping"] },
1388
+ { id: "feedly", name: "Feedly", category: "feed_reader", organization: "Feedly", baseScore: 25, respectsRobots: true, uaPatterns: ["feedly"] },
1389
+ { id: "newsblur", name: "NewsBlur", category: "feed_reader", organization: "NewsBlur", baseScore: 25, respectsRobots: true, uaPatterns: ["newsblur"] },
1390
+ { id: "inoreader", name: "Inoreader", category: "feed_reader", organization: "Inoreader", baseScore: 25, respectsRobots: true, uaPatterns: ["inoreader"] },
1391
+ { id: "theoldreader", name: "The Old Reader", category: "feed_reader", organization: "The Old Reader", baseScore: 25, respectsRobots: true, uaPatterns: ["theoldreader"] },
1392
+ { id: "feedbin", name: "Feedbin", category: "feed_reader", organization: "Feedbin", baseScore: 25, respectsRobots: true, uaPatterns: ["feedbin"] },
1393
+ { id: "miniflux", name: "Miniflux", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["miniflux"] },
1394
+ { id: "freshrss", name: "FreshRSS", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["freshrss"] },
1395
+ { id: "commafeed", name: "CommaFeed", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["commafeed"] },
1396
+ { id: "diffbot", name: "Diffbot", category: "commercial_scraper", organization: "Diffbot", baseScore: 70, respectsRobots: true, uaPatterns: ["diffbot"] },
1397
+ { id: "import-io", name: "Import.io", category: "commercial_scraper", organization: "Import.io", baseScore: 65, respectsRobots: true, uaPatterns: ["import.io"] },
1398
+ { id: "bright-data", name: "Bright Data", category: "commercial_scraper", organization: "Bright Data", baseScore: 70, respectsRobots: false, uaPatterns: ["brightdata", "luminati"] },
1399
+ { id: "oxylabs", name: "Oxylabs", category: "commercial_scraper", organization: "Oxylabs", baseScore: 70, respectsRobots: false, uaPatterns: ["oxylabs"] },
1400
+ { id: "scrapingbee", name: "ScrapingBee", category: "commercial_scraper", organization: "ScrapingBee", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapingbee"] },
1401
+ { id: "scrapingant", name: "ScrapingAnt", category: "commercial_scraper", organization: "ScrapingAnt", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapingant"] },
1402
+ { id: "zyte", name: "Zyte", category: "commercial_scraper", organization: "Zyte", baseScore: 65, respectsRobots: true, uaPatterns: ["zyte", "scrapinghub"] },
1403
+ { id: "apify", name: "Apify", category: "commercial_scraper", organization: "Apify", baseScore: 65, respectsRobots: true, uaPatterns: ["apify"] },
1404
+ { id: "crawlbase", name: "Crawlbase", category: "commercial_scraper", organization: "Crawlbase", baseScore: 65, respectsRobots: true, uaPatterns: ["crawlbase"] },
1405
+ { id: "webscrapingapi", name: "WebScrapingAPI", category: "commercial_scraper", organization: "WebScrapingAPI", baseScore: 65, respectsRobots: true, uaPatterns: ["webscrapingapi"] },
1406
+ { id: "gemini-deep-research", name: "Gemini-Deep-Research", category: "ai_assistant", organization: "Google", baseScore: 65, respectsRobots: true, uaPatterns: ["gemini-deep-research"] },
1407
+ { id: "copilot", name: "Microsoft Copilot", category: "ai_assistant", organization: "Microsoft", baseScore: 65, respectsRobots: true, uaPatterns: ["copilot"] },
1408
+ { id: "cortana", name: "Cortana", category: "ai_assistant", organization: "Microsoft", baseScore: 60, respectsRobots: true, uaPatterns: ["cortana"] },
1409
+ { id: "siri", name: "Siri", category: "ai_assistant", organization: "Apple", baseScore: 60, respectsRobots: true, uaPatterns: ["siri"] }
1410
+ ];
1411
+
1412
+ // src/bots/index.ts
1413
+ var AI_CATEGORIES = /* @__PURE__ */ new Set([
1414
+ "training_crawler",
1415
+ "ai_search_crawler",
1416
+ "ai_agent",
1417
+ "ai_assistant"
1418
+ ]);
1419
+ var UNKNOWN = Object.freeze({
1420
+ known: false,
1421
+ category: "none",
1422
+ score: 0,
1423
+ isAI: false
1424
+ });
1425
+ var MAX_CACHE = 1e3;
1426
+ var cache = /* @__PURE__ */ new Map();
1427
+ function matchUserAgent(userAgent) {
1428
+ if (!userAgent) return void 0;
1429
+ const cached = cache.get(userAgent);
1430
+ if (cached !== void 0) return cached ?? void 0;
1431
+ const ua = userAgent.toLowerCase();
1432
+ let found = null;
1433
+ for (const agent of BOT_REGISTRY) {
1434
+ for (const pattern of agent.uaPatterns) {
1435
+ if (ua.includes(pattern)) {
1436
+ found = agent;
1437
+ break;
1438
+ }
1439
+ }
1440
+ if (found) break;
1441
+ }
1442
+ if (cache.size >= MAX_CACHE) cache.clear();
1443
+ cache.set(userAgent, found);
1444
+ return found ?? void 0;
1445
+ }
1446
+ function classifyUserAgent(userAgent) {
1447
+ const agent = matchUserAgent(userAgent);
1448
+ if (!agent) return UNKNOWN;
1449
+ return {
1450
+ known: true,
1451
+ id: agent.id,
1452
+ name: agent.name,
1453
+ category: agent.category,
1454
+ organization: agent.organization,
1455
+ score: agent.baseScore,
1456
+ respectsRobots: agent.respectsRobots,
1457
+ isAI: AI_CATEGORIES.has(agent.category)
1458
+ };
1459
+ }
1460
+
1461
+ // src/rules/bot-policy.ts
1462
+ var AI_CATEGORIES2 = /* @__PURE__ */ new Set([
1463
+ "training_crawler",
1464
+ "ai_search_crawler",
1465
+ "ai_agent",
1466
+ "ai_assistant"
1467
+ ]);
1468
+ var BotPolicy = class {
1469
+ constructor(options = {}) {
1470
+ const deny = options.deny ?? [];
1471
+ const allow = new Set((options.allow ?? []).map((a) => a.toLowerCase()));
1472
+ const categories = /* @__PURE__ */ new Set();
1473
+ const agents = /* @__PURE__ */ new Set();
1474
+ let ai = false;
1475
+ for (const token of deny) {
1476
+ if (token === "ai") ai = true;
1477
+ else if (BOT_CATEGORIES.includes(token)) categories.add(token);
1478
+ else agents.add(token.toLowerCase());
1356
1479
  }
1480
+ this.config = {
1481
+ categories: [...categories],
1482
+ agents: [...agents],
1483
+ ai,
1484
+ allow: options.allow,
1485
+ action: options.action,
1486
+ dryRun: options.dryRun
1487
+ };
1488
+ this.matched = BOT_REGISTRY.filter((agent) => {
1489
+ if (allow.has(agent.id) || allow.has(agent.name.toLowerCase())) return false;
1490
+ return ai && AI_CATEGORIES2.has(agent.category) || categories.has(agent.category) || agents.has(agent.id) || agents.has(agent.name.toLowerCase());
1491
+ });
1357
1492
  }
1358
1493
  /**
1359
- * Add violations to the buffer. Auto-flushes when buffer reaches maxBufferSize.
1494
+ * Agents in the deny set whose operator does not document honouring
1495
+ * robots.txt. Publishing still declares the policy; only the rule enforces it
1496
+ * against these.
1360
1497
  */
1361
- report(violations) {
1362
- this.buffer.push(...violations);
1363
- if (this.buffer.length >= this.maxBufferSize) {
1364
- this.flush().catch(() => {
1365
- });
1498
+ get unenforceable() {
1499
+ return this.matched.filter((a) => a.respectsRobots !== true);
1500
+ }
1501
+ /** The enforcing rule. Denies exactly the agents in {@link matched}. */
1502
+ rule() {
1503
+ return new BotRule(this.config);
1504
+ }
1505
+ /** The published policy, as a `robots.txt` body. */
1506
+ robotsTxt(options = {}) {
1507
+ const { allowOthers = true, annotate = true } = options;
1508
+ const lines = [];
1509
+ if (annotate) {
1510
+ lines.push("# Managed by WebDecoy \u2014 published and enforced from one policy.");
1511
+ const ignoring = this.unenforceable;
1512
+ if (ignoring.length > 0) {
1513
+ lines.push(
1514
+ "# These do not document honouring robots.txt, so the lines below are a",
1515
+ "# request only. The bots() rule is what actually stops them:",
1516
+ ...ignoring.map((a) => `# ${a.name}${a.organization ? ` (${a.organization})` : ""}`)
1517
+ );
1518
+ }
1519
+ lines.push("");
1520
+ }
1521
+ for (const agent of this.matched) {
1522
+ lines.push(`User-agent: ${agent.name}`, "Disallow: /", "");
1366
1523
  }
1524
+ if (allowOthers) {
1525
+ lines.push("User-agent: *");
1526
+ for (const path of options.disallow ?? []) lines.push(`Disallow: ${path}`);
1527
+ if ((options.disallow ?? []).length === 0) lines.push("Disallow:");
1528
+ if (options.crawlDelay !== void 0) lines.push(`Crawl-delay: ${options.crawlDelay}`);
1529
+ lines.push("");
1530
+ }
1531
+ if (options.sitemap) lines.push(`Sitemap: ${options.sitemap}`, "");
1532
+ return lines.join("\n").replace(/\n{3,}/g, "\n\n").trimStart();
1367
1533
  }
1368
- /**
1369
- * Flush buffered violations to the backend
1370
- */
1371
- async flush() {
1372
- if (this.flushing || this.buffer.length === 0) return;
1373
- this.flushing = true;
1374
- const events = this.buffer.splice(0, this.buffer.length);
1534
+ };
1535
+ function botPolicy(options = {}) {
1536
+ return new BotPolicy(options);
1537
+ }
1538
+
1539
+ // src/rules/attack-signatures.ts
1540
+ var SIGNATURES = [
1541
+ // --- SQL injection -------------------------------------------------------
1542
+ { id: "sqli_union", label: "SQL UNION SELECT", test: /\bunion\b[\s/*]+\bselect\b/i },
1543
+ {
1544
+ id: "sqli_tautology",
1545
+ label: "SQL tautology",
1546
+ // ' OR 1=1 / " or 'a'='a — the quote is required, which is what keeps this
1547
+ // off ordinary query strings containing "or".
1548
+ test: /['"`]\s*(?:or|and)\s+(?:\d+\s*=\s*\d+|['"`][^'"`]{0,32}['"`]\s*=\s*['"`])/i
1549
+ },
1550
+ {
1551
+ id: "sqli_stacked",
1552
+ label: "Stacked SQL statement",
1553
+ test: /;\s*(?:drop|truncate|alter|create|insert|update|delete)\s+(?:table|database|from|into)\b/i
1554
+ },
1555
+ {
1556
+ id: "sqli_timing",
1557
+ label: "SQL timing function",
1558
+ test: /\b(?:sleep|pg_sleep|benchmark|waitfor\s+delay)\s*\(/i
1559
+ },
1560
+ { id: "sqli_probe", label: "SQL metadata probe", test: /\binformation_schema\.[a-z_]+/i },
1561
+ // --- Cross-site scripting -----------------------------------------------
1562
+ { id: "xss_script_tag", label: "Inline <script>", test: /<\s*script[\s>/]/i },
1563
+ { id: "xss_javascript_uri", label: "javascript: URI", test: /javascript\s*:[^\s]{0,64}\(/i },
1564
+ {
1565
+ id: "xss_event_handler",
1566
+ label: "Inline event handler",
1567
+ // Requires a tag context, so `onerror` as a bare parameter name is not a hit.
1568
+ test: /<[a-z][a-z0-9]{0,15}[^>]{0,256}\son(?:error|load|click|mouseover|focus)\s*=/i
1569
+ },
1570
+ { id: "xss_svg_onload", label: "SVG onload", test: /<\s*svg[^>]{0,128}\bonload\b/i },
1571
+ // --- Path traversal ------------------------------------------------------
1572
+ {
1573
+ id: "traversal",
1574
+ label: "Path traversal",
1575
+ // Two or more segments: a single `../` shows up in legitimately relative
1576
+ // redirect targets often enough to be worth the extra evidence.
1577
+ test: /(?:\.\.[/\\]){2,}/
1578
+ },
1579
+ { id: "traversal_etc", label: "Sensitive file path", test: /\/etc\/(?:passwd|shadow)\b/i },
1580
+ // --- Command injection ---------------------------------------------------
1581
+ {
1582
+ id: "cmdi_shell",
1583
+ label: "Shell command injection",
1584
+ test: /[;|&`]\s*(?:cat|curl|wget|nc|bash|sh|python|perl|chmod)\s+[-/\w]/i
1585
+ },
1586
+ { id: "cmdi_subshell", label: "Shell substitution", test: /\$\([a-z][^)]{0,64}\)/i },
1587
+ // --- Template / expression injection -------------------------------------
1588
+ { id: "ssti_jndi", label: "JNDI lookup (Log4Shell)", test: /\$\{\s*jndi\s*:/i },
1589
+ { id: "ssti_expression", label: "Template expression", test: /\{\{\s*[\w.]+\s*[(*]/ }
1590
+ ];
1591
+ function decodeBounded(input) {
1592
+ const forms = [input];
1593
+ let current = input;
1594
+ for (let i = 0; i < 2; i++) {
1595
+ if (!current.includes("%")) break;
1596
+ let next;
1375
1597
  try {
1376
- for (let i = 0; i < events.length; i += 100) {
1377
- const batch = events.slice(i, i + 100);
1378
- await this.client.sendViolations(batch);
1379
- if (this.debug) {
1380
- console.log(`[WebDecoy] Flushed ${batch.length} violation events`);
1598
+ next = decodeURIComponent(current);
1599
+ } catch {
1600
+ break;
1601
+ }
1602
+ if (next === current) break;
1603
+ forms.push(next);
1604
+ current = next;
1605
+ }
1606
+ return forms;
1607
+ }
1608
+ var AttackSignatureRule = class {
1609
+ constructor(config = {}) {
1610
+ this.name = "attack-signatures";
1611
+ this.inspect = new Set(config.inspect ?? ["path", "query"]);
1612
+ this.maxBytes = config.maxBytes ?? 8192;
1613
+ const excluded = new Set(config.exclude ?? []);
1614
+ this.signatures = SIGNATURES.filter((s) => !excluded.has(s.id));
1615
+ this.action = config.action ?? "DENY";
1616
+ this.dryRun = config.dryRun ?? false;
1617
+ }
1618
+ evaluate(context) {
1619
+ for (const [where, raw] of this.parts(context)) {
1620
+ if (!raw) continue;
1621
+ const truncated = raw.length > this.maxBytes ? raw.slice(0, this.maxBytes) : raw;
1622
+ for (const form of decodeBounded(truncated)) {
1623
+ for (const signature of this.signatures) {
1624
+ if (!signature.test.test(form)) continue;
1625
+ return {
1626
+ action: this.dryRun ? "ALLOW" : this.action,
1627
+ rule: this.name,
1628
+ reason: `${signature.label} in request ${where}`,
1629
+ metadata: {
1630
+ signature: signature.id,
1631
+ label: signature.label,
1632
+ where,
1633
+ dryRun: this.dryRun
1634
+ }
1635
+ };
1381
1636
  }
1382
1637
  }
1383
- } catch (error) {
1384
- if (this.debug) {
1385
- console.error("[WebDecoy] Failed to flush violations:", error);
1386
- }
1387
- } finally {
1388
- this.flushing = false;
1389
1638
  }
1639
+ return { action: "ALLOW", rule: this.name };
1390
1640
  }
1391
- /**
1392
- * Flush remaining events and stop the timer
1393
- */
1394
- async destroy() {
1395
- clearInterval(this.flushTimer);
1396
- await this.flush();
1641
+ parts(context) {
1642
+ const out = [];
1643
+ if (this.inspect.has("path")) out.push(["path", context.path]);
1644
+ if (this.inspect.has("query")) out.push(["query", context.query]);
1645
+ if (this.inspect.has("body")) out.push(["body", context.body]);
1646
+ if (this.inspect.has("headers")) {
1647
+ for (const [name, value] of Object.entries(context.headers ?? {})) {
1648
+ if (name === "cookie") continue;
1649
+ out.push([`header:${name}`, value]);
1650
+ }
1651
+ }
1652
+ return out;
1397
1653
  }
1398
1654
  };
1655
+ function attackSignatures(config = {}) {
1656
+ return new AttackSignatureRule(config);
1657
+ }
1658
+ var ATTACK_SIGNATURE_IDS = SIGNATURES.map((s) => s.id);
1399
1659
 
1400
- // src/ip-enrichment.ts
1401
- var IPEnrichmentClient = class {
1402
- constructor(client, ttlMs = 36e5) {
1403
- this.cache = /* @__PURE__ */ new Map();
1404
- this.pending = /* @__PURE__ */ new Map();
1405
- this.client = client;
1406
- this.ttlMs = ttlMs;
1660
+ // src/rules/web-bot-auth-rule.ts
1661
+ var WebBotAuthRule = class {
1662
+ constructor(config = {}) {
1663
+ this.name = "web-bot-auth";
1664
+ this.onImpersonation = config.onImpersonation ?? "DENY";
1665
+ this.onClaimed = config.onClaimed ?? "ALLOW";
1666
+ this.allowCategories = config.allowCategories ? new Set(config.allowCategories) : void 0;
1667
+ this.dryRun = config.dryRun ?? false;
1407
1668
  }
1408
- /**
1409
- * Get enrichment data for an IP address.
1410
- * Returns cached data if available (1h TTL), otherwise fetches from API.
1411
- * Returns null if enrichment fails (fail-open).
1412
- */
1413
- async enrich(ip) {
1414
- const cached = this.cache.get(ip);
1415
- if (cached && cached.expiresAt > Date.now()) {
1416
- return cached.data;
1669
+ evaluate(context) {
1670
+ const verdict = context.agent;
1671
+ if (!verdict) {
1672
+ return {
1673
+ action: "ALLOW",
1674
+ rule: this.name,
1675
+ state: "NOT_RUN",
1676
+ reason: "Request lacked the host information needed to verify a signature"
1677
+ };
1417
1678
  }
1418
- const inflight = this.pending.get(ip);
1419
- if (inflight) {
1420
- return inflight;
1679
+ if (verdict.status === "none") return this.allow();
1680
+ if (verdict.status === "impersonation") {
1681
+ return this.act(this.onImpersonation, "agent_impersonation", {
1682
+ agentName: verdict.agentName,
1683
+ category: verdict.category,
1684
+ keyId: verdict.keyId,
1685
+ detail: verdict.reason
1686
+ });
1421
1687
  }
1422
- const promise = this.fetchAndCache(ip);
1423
- this.pending.set(ip, promise);
1424
- try {
1425
- return await promise;
1426
- } finally {
1427
- this.pending.delete(ip);
1688
+ if (verdict.status === "claimed") {
1689
+ return this.act(this.onClaimed, "agent_unverifiable", {
1690
+ keyId: verdict.keyId,
1691
+ detail: verdict.reason
1692
+ });
1428
1693
  }
1429
- }
1430
- async fetchAndCache(ip) {
1431
- const data = await this.client.getIPEnrichment(ip);
1432
- if (data) {
1433
- this.cache.set(ip, {
1434
- data,
1435
- expiresAt: Date.now() + this.ttlMs
1694
+ if (this.allowCategories && verdict.category && !this.allowCategories.has(verdict.category)) {
1695
+ return this.act(this.onClaimed, "agent_category_not_allowed", {
1696
+ agentName: verdict.agentName,
1697
+ category: verdict.category,
1698
+ keyId: verdict.keyId
1436
1699
  });
1437
1700
  }
1438
- return data;
1701
+ return this.allow();
1439
1702
  }
1440
- /**
1441
- * Clear the cache
1442
- */
1443
- clearCache() {
1444
- this.cache.clear();
1703
+ act(action, verdict, detail) {
1704
+ if (action === "ALLOW") return this.allow();
1705
+ return {
1706
+ action: this.dryRun ? "ALLOW" : action,
1707
+ rule: this.name,
1708
+ reason: reasonFor(verdict),
1709
+ metadata: { verdict, dryRun: this.dryRun, ...detail }
1710
+ };
1711
+ }
1712
+ allow() {
1713
+ return { action: "ALLOW", rule: this.name };
1445
1714
  }
1446
1715
  };
1716
+ function reasonFor(verdict) {
1717
+ switch (verdict) {
1718
+ case "agent_impersonation":
1719
+ return "Web Bot Auth signature failed verification (agent impersonation)";
1720
+ case "agent_unverifiable":
1721
+ return "Web Bot Auth signature could not be verified";
1722
+ case "agent_category_not_allowed":
1723
+ return "Verified agent category is not allowed";
1724
+ default:
1725
+ return "Web Bot Auth rule triggered";
1726
+ }
1727
+ }
1728
+ function webBotAuth(config = {}) {
1729
+ return new WebBotAuthRule(config);
1730
+ }
1447
1731
 
1448
- // src/agent/thumbprint.ts
1449
- var encoder2 = new TextEncoder();
1450
- async function rsaThumbprint(n, e) {
1451
- return digest(`{"e":${JSON.stringify(e)},"kty":"RSA","n":${JSON.stringify(n)}}`);
1732
+ // src/webcrypto.ts
1733
+ var encoder = new TextEncoder();
1734
+ function toHex(bytes) {
1735
+ let hex = "";
1736
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
1737
+ return hex;
1452
1738
  }
1453
- async function okpThumbprint(crv, x) {
1454
- return digest(`{"crv":${JSON.stringify(crv)},"kty":"OKP","x":${JSON.stringify(x)}}`);
1739
+ async function sha256Hex(data) {
1740
+ const digest2 = await crypto.subtle.digest("SHA-256", encoder.encode(data));
1741
+ return toHex(new Uint8Array(digest2));
1455
1742
  }
1456
- async function jwkThumbprint(k) {
1457
- switch (k.kty) {
1458
- case "OKP":
1459
- if (!k.crv || !k.x) throw new Error("thumbprint: OKP JWK missing crv or x");
1460
- return okpThumbprint(k.crv, k.x);
1461
- case "RSA":
1462
- if (!k.n || !k.e) throw new Error("thumbprint: RSA JWK missing n or e");
1463
- return rsaThumbprint(k.n, k.e);
1464
- default:
1465
- throw new Error(`thumbprint: unsupported kty ${JSON.stringify(k.kty)}`);
1466
- }
1743
+ async function hmacSha256Hex(secret, data) {
1744
+ const key = await crypto.subtle.importKey(
1745
+ "raw",
1746
+ encoder.encode(secret),
1747
+ { name: "HMAC", hash: "SHA-256" },
1748
+ false,
1749
+ ["sign"]
1750
+ );
1751
+ const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(data));
1752
+ return toHex(new Uint8Array(sig));
1467
1753
  }
1468
- async function digest(canonical) {
1469
- const buf = await crypto.subtle.digest("SHA-256", encoder2.encode(canonical));
1470
- return base64urlBytes(new Uint8Array(buf));
1754
+ function randomHex(bytes) {
1755
+ const buf = new Uint8Array(bytes);
1756
+ crypto.getRandomValues(buf);
1757
+ return toHex(buf);
1471
1758
  }
1472
- function base64urlBytes(bytes) {
1759
+ function timingSafeEqualStr(a, b) {
1760
+ if (a.length !== b.length) return false;
1761
+ let diff = 0;
1762
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
1763
+ return diff === 0;
1764
+ }
1765
+ function base64urlEncode(data) {
1766
+ const bytes = encoder.encode(data);
1473
1767
  let binary = "";
1474
1768
  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1475
1769
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1476
1770
  }
1771
+ function base64urlDecode(data) {
1772
+ const b64 = data.replace(/-/g, "+").replace(/_/g, "/");
1773
+ const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
1774
+ const binary = atob(padded);
1775
+ const bytes = new Uint8Array(binary.length);
1776
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1777
+ return new TextDecoder().decode(bytes);
1778
+ }
1779
+ function fnv1a64Hex(data) {
1780
+ const PRIME = 0x100000001b3n;
1781
+ const MASK = 0xffffffffffffffffn;
1782
+ let hash = 0xcbf29ce484222325n;
1783
+ const bytes = encoder.encode(data);
1784
+ for (let i = 0; i < bytes.length; i++) {
1785
+ hash ^= BigInt(bytes[i]);
1786
+ hash = hash * PRIME & MASK;
1787
+ }
1788
+ return hash.toString(16).padStart(16, "0");
1789
+ }
1477
1790
 
1478
- // src/agent/directory.ts
1479
- var WELL_KNOWN = "/.well-known/http-message-signatures-directory";
1480
- var COLD_RETRY_BACKOFF_MS = 3e4;
1481
- var DEFAULT_SIGNED_AGENT_DIRECTORIES = [
1482
- { name: "OpenAI", category: "ai_crawlers", directory: "https://operator.openai.com" },
1483
- { name: "OpenAI ChatGPT", category: "ai_crawlers", directory: "https://chatgpt.com" }
1484
- ];
1485
- var DirectoryCache = class {
1486
- constructor(opts) {
1487
- this.keys = /* @__PURE__ */ new Map();
1488
- this.refreshedAt = 0;
1489
- this.nextColdRetryAt = 0;
1490
- this.inflight = null;
1491
- /** Resolve a keyid to a verification key, fetching/refreshing as needed. */
1492
- this.resolveKey = async (keyId) => {
1493
- await this.ensureFresh();
1494
- return this.keys.get(keyId);
1495
- };
1496
- this.opts = opts;
1791
+ // src/rules/honeytoken.ts
1792
+ function honeytoken(options = {}) {
1793
+ const base = (options.basePath ?? "/__wd").replace(/\/+$/, "");
1794
+ const token = options.token ?? randomHex(6);
1795
+ const path = `${base}/${token}`;
1796
+ const text = options.text ?? ".";
1797
+ 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>`;
1798
+ return { path, linkHtml };
1799
+ }
1800
+
1801
+ // src/rules/upstash-store.ts
1802
+ var UpstashRateLimitStore = class {
1803
+ constructor(options) {
1804
+ this.sync = false;
1805
+ if (!options.url) throw new Error("upstashRateLimitStore: `url` is required");
1806
+ if (!options.token) throw new Error("upstashRateLimitStore: `token` is required");
1807
+ this.url = options.url.replace(/\/+$/, "");
1808
+ this.token = options.token;
1809
+ this.prefix = options.prefix ?? "wd:rl:";
1810
+ this.timeout = options.timeout ?? 1e3;
1811
+ this.failOpen = (options.onError ?? "open") === "open";
1812
+ }
1813
+ async consume(input) {
1814
+ try {
1815
+ return input.algorithm === "sliding" ? await this.sliding(input) : await this.fixed(input);
1816
+ } catch {
1817
+ const now = Date.now();
1818
+ return {
1819
+ allowed: this.failOpen,
1820
+ current: 0,
1821
+ resetAt: now + input.windowMs
1822
+ };
1823
+ }
1497
1824
  }
1498
- /** Kick off a fetch without blocking — call at startup to warm the cache. */
1499
- prime() {
1500
- if (this.keys.size === 0 && Date.now() >= this.nextColdRetryAt) void this.refresh();
1825
+ /**
1826
+ * Fixed window: one counter per key per window.
1827
+ *
1828
+ * The window id is in the key rather than tracked separately, so expiry is the
1829
+ * only cleanup needed and two processes incrementing concurrently cannot
1830
+ * disagree about which window they are in.
1831
+ */
1832
+ async fixed({ key, max, windowMs }) {
1833
+ const now = Date.now();
1834
+ const windowStart = Math.floor(now / windowMs) * windowMs;
1835
+ const redisKey = `${this.prefix}f:${key}:${windowStart}`;
1836
+ const ttlSeconds = Math.ceil(windowMs / 1e3);
1837
+ const [incr] = await this.pipeline([
1838
+ ["INCR", redisKey],
1839
+ ["EXPIRE", redisKey, String(ttlSeconds), "NX"]
1840
+ ]);
1841
+ const current = toCount(incr);
1842
+ return { allowed: current <= max, current, resetAt: windowStart + windowMs };
1501
1843
  }
1502
- /** Number of keys currently cached (diagnostics/tests). */
1503
- get size() {
1504
- return this.keys.size;
1505
- }
1506
- async ensureFresh() {
1844
+ /**
1845
+ * Sliding window: a sorted set of request timestamps, trimmed on every read.
1846
+ *
1847
+ * The member is timestamp plus random bytes because two requests in the same
1848
+ * millisecond would otherwise be one ZADD that overwrites rather than two that
1849
+ * count — undercounting exactly when the limit matters.
1850
+ */
1851
+ async sliding({ key, max, windowMs }) {
1507
1852
  const now = Date.now();
1508
- const stale = now - this.refreshedAt > this.opts.cacheTtlMs;
1509
- if (this.keys.size > 0) {
1510
- if (stale) void this.refresh();
1511
- return;
1512
- }
1513
- if (now < this.nextColdRetryAt) return;
1514
- await this.refresh();
1515
- }
1516
- /** Re-fetch every directory. De-duplicated: concurrent callers share one run. */
1517
- refresh() {
1518
- if (this.inflight) return this.inflight;
1519
- this.inflight = this.doRefresh().finally(() => {
1520
- this.inflight = null;
1521
- });
1522
- return this.inflight;
1523
- }
1524
- async doRefresh() {
1525
- const results = await Promise.all(
1526
- this.opts.directories.map((src) => this.fetchDirectory(src))
1527
- );
1528
- const next = new Map(this.keys);
1529
- let fetchedAny = false;
1530
- for (const keys of results) {
1531
- if (keys === null) continue;
1532
- fetchedAny = true;
1533
- for (const k of keys) next.set(k.thumbprint, k.key);
1534
- }
1535
- if (fetchedAny) {
1536
- this.keys = next;
1537
- this.refreshedAt = Date.now();
1538
- this.nextColdRetryAt = 0;
1539
- this.debug(`refreshed: ${this.keys.size} key(s) across ${this.opts.directories.length} directories`);
1540
- } else if (this.keys.size === 0) {
1541
- this.nextColdRetryAt = Date.now() + COLD_RETRY_BACKOFF_MS;
1542
- this.debug("all directories unreachable; backing off cold retry");
1543
- }
1544
- }
1545
- async fetchDirectory(src) {
1546
- const url = directoryUrl(src.directory);
1853
+ const redisKey = `${this.prefix}s:${key}`;
1854
+ const cutoff = now - windowMs;
1855
+ const ttlSeconds = Math.ceil(windowMs / 1e3) + 1;
1856
+ const results = await this.pipeline([
1857
+ ["ZREMRANGEBYSCORE", redisKey, "0", String(cutoff)],
1858
+ ["ZADD", redisKey, String(now), `${now}-${randomHex(4)}`],
1859
+ ["ZCARD", redisKey],
1860
+ ["EXPIRE", redisKey, String(ttlSeconds)]
1861
+ ]);
1862
+ const current = toCount(results[2]);
1863
+ return { allowed: current <= max, current, resetAt: now + windowMs };
1864
+ }
1865
+ async pipeline(commands) {
1547
1866
  const controller = new AbortController();
1548
- const timer = setTimeout(() => controller.abort(), this.opts.fetchTimeoutMs);
1867
+ const timer = setTimeout(() => controller.abort(), this.timeout);
1549
1868
  try {
1550
- const res = await this.opts.fetchImpl(url, {
1551
- signal: controller.signal,
1869
+ const response = await fetch(`${this.url}/pipeline`, {
1870
+ method: "POST",
1552
1871
  headers: {
1553
- Accept: "application/http-message-signatures-directory+json, application/jwk-set+json, application/json"
1872
+ Authorization: `Bearer ${this.token}`,
1873
+ "Content-Type": "application/json"
1554
1874
  },
1555
- redirect: "follow"
1875
+ body: JSON.stringify(commands),
1876
+ signal: controller.signal
1556
1877
  });
1557
- if (!res.ok) {
1558
- this.debug(`${src.name}: HTTP ${res.status}`);
1559
- return null;
1878
+ if (!response.ok) {
1879
+ throw new Error(`Upstash responded ${response.status}`);
1560
1880
  }
1561
- const body = await res.json();
1562
- if (!body || !Array.isArray(body.keys)) {
1563
- this.debug(`${src.name}: no keys in directory`);
1564
- return null;
1565
- }
1566
- const out = [];
1567
- for (const jwk of body.keys) {
1568
- const resolved = await importKey(jwk, src);
1569
- if (resolved) out.push(resolved);
1881
+ const body = await response.json();
1882
+ if (!Array.isArray(body)) throw new Error("Upstash returned a non-pipeline body");
1883
+ for (const entry of body) {
1884
+ if (entry?.error) throw new Error(`Upstash command failed: ${entry.error}`);
1570
1885
  }
1571
- this.debug(`${src.name}: ${out.length} key(s)`);
1572
- return out;
1573
- } catch (err) {
1574
- this.debug(`${src.name}: fetch failed \u2014 ${err.message}`);
1575
- return null;
1886
+ return body.map((entry) => entry?.result);
1576
1887
  } finally {
1577
1888
  clearTimeout(timer);
1578
1889
  }
1579
1890
  }
1580
- debug(msg) {
1581
- if (this.opts.debug) console.log(`[WebDecoy][web-bot-auth] ${msg}`);
1582
- }
1583
1891
  };
1584
- function directoryUrl(directory) {
1585
- const u = new URL(directory);
1586
- if (u.pathname && u.pathname !== "/") return u.toString();
1587
- u.pathname = WELL_KNOWN;
1588
- return u.toString();
1589
- }
1590
- async function importKey(jwk, src) {
1591
- try {
1592
- let cryptoKey;
1593
- let verifyParams;
1594
- let algorithm;
1595
- if (jwk.kty === "OKP") {
1596
- if (jwk.crv !== "Ed25519" || !jwk.x) return null;
1597
- cryptoKey = await crypto.subtle.importKey(
1598
- "jwk",
1599
- { kty: "OKP", crv: "Ed25519", x: jwk.x },
1600
- { name: "Ed25519" },
1601
- false,
1602
- ["verify"]
1603
- );
1604
- verifyParams = { name: "Ed25519" };
1605
- algorithm = "ed25519";
1606
- } else if (jwk.kty === "RSA") {
1607
- if (!jwk.n || !jwk.e) return null;
1608
- cryptoKey = await crypto.subtle.importKey(
1609
- "jwk",
1610
- { kty: "RSA", n: jwk.n, e: jwk.e },
1611
- { name: "RSA-PSS", hash: "SHA-512" },
1612
- false,
1613
- ["verify"]
1614
- );
1615
- verifyParams = { name: "RSA-PSS", saltLength: 64 };
1616
- algorithm = "rsa-pss-sha512";
1617
- } else {
1618
- return null;
1619
- }
1620
- const thumbprint = await jwkThumbprint(jwk);
1621
- return {
1622
- thumbprint,
1623
- key: {
1624
- cryptoKey,
1625
- verifyParams,
1626
- algorithm,
1627
- name: src.name,
1628
- category: src.category,
1629
- nbf: normalizeEpoch(jwk.nbf),
1630
- exp: normalizeEpoch(jwk.exp)
1631
- }
1632
- };
1633
- } catch {
1634
- return null;
1635
- }
1892
+ function toCount(value) {
1893
+ const n = typeof value === "string" ? Number(value) : value;
1894
+ return typeof n === "number" && Number.isFinite(n) ? n : 0;
1636
1895
  }
1637
- function normalizeEpoch(v) {
1638
- if (v === void 0 || v === 0) return void 0;
1639
- return v > 1e12 ? Math.floor(v / 1e3) : v;
1896
+ function upstashRateLimitStore(options) {
1897
+ return new UpstashRateLimitStore(options);
1640
1898
  }
1641
1899
 
1642
- // src/agent/sfv.ts
1643
- var Cursor = class {
1644
- constructor(s, i = 0) {
1645
- this.s = s;
1646
- this.i = i;
1647
- }
1648
- eof() {
1649
- return this.i >= this.s.length;
1650
- }
1651
- peek() {
1652
- return this.s[this.i];
1653
- }
1654
- skipSP() {
1655
- while (!this.eof() && (this.peek() === " " || this.peek() === " ")) this.i++;
1656
- }
1900
+ // src/rules/honeytoken-site.ts
1901
+ var HONEYTOKEN_BASE_PATH = "/__wd";
1902
+ var TOKEN_LEN = 12;
1903
+ function utcDay(offsetDays = 0) {
1904
+ const d = new Date(Date.now() + offsetDays * 864e5);
1905
+ return d.toISOString().slice(0, 10);
1906
+ }
1907
+ function escapeHtml(v) {
1908
+ return v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1909
+ }
1910
+ function linkFor(path, text) {
1911
+ text = escapeHtml(text);
1912
+ 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>`;
1913
+ }
1914
+ var HIDDEN_STYLE = {
1915
+ position: "absolute",
1916
+ left: "-9999px",
1917
+ top: "auto",
1918
+ width: "1px",
1919
+ height: "1px",
1920
+ overflow: "hidden"
1657
1921
  };
1658
- function parseDictionary(input) {
1659
- const p = new Cursor(input);
1660
- const out = [];
1661
- p.skipSP();
1662
- while (!p.eof()) {
1663
- const key = parseKey(p);
1664
- const entry = { key, raw: "", isList: false, items: [], params: /* @__PURE__ */ new Map() };
1665
- if (!p.eof() && p.peek() === "=") {
1666
- p.i++;
1667
- const start = p.i;
1668
- if (!p.eof() && p.peek() === "(") {
1669
- entry.isList = true;
1670
- parseInnerList(p, entry);
1671
- } else {
1672
- entry.items.push(parseItem(p));
1673
- entry.params = entry.items[0].params;
1674
- }
1675
- entry.raw = input.slice(start, p.i);
1676
- } else {
1677
- entry.params = parseParams(p);
1678
- entry.items.push({ value: true, params: /* @__PURE__ */ new Map() });
1679
- entry.raw = "?1";
1680
- }
1681
- out.push(entry);
1682
- p.skipSP();
1683
- if (p.eof()) break;
1684
- if (p.peek() !== ",") throw new Error(`sfv: expected ',' at ${p.i}`);
1685
- p.i++;
1686
- p.skipSP();
1687
- if (p.eof()) throw new Error("sfv: trailing comma");
1922
+ function propsFor(path, text) {
1923
+ return {
1924
+ href: path,
1925
+ rel: "nofollow noindex",
1926
+ tabIndex: -1,
1927
+ "aria-hidden": "true",
1928
+ style: HIDDEN_STYLE,
1929
+ text
1930
+ };
1931
+ }
1932
+ async function siteHoneytoken(options) {
1933
+ const base = (options.basePath ?? HONEYTOKEN_BASE_PATH).replace(/\/+$/, "");
1934
+ const text = options.text ?? ".";
1935
+ const derive = async (label) => `${base}/${(await hmacSha256Hex(options.secret, label)).slice(0, TOKEN_LEN)}`;
1936
+ if (!options.rotate) {
1937
+ const path = await derive("stable");
1938
+ return {
1939
+ primaryPath: path,
1940
+ activePaths: [path],
1941
+ linkHtml: linkFor(path, text),
1942
+ linkProps: propsFor(path, text)
1943
+ };
1688
1944
  }
1689
- return out;
1945
+ const today = await derive(`day:${utcDay(0)}`);
1946
+ const yesterday = await derive(`day:${utcDay(-1)}`);
1947
+ return {
1948
+ primaryPath: today,
1949
+ // Yesterday stays armed so a crawler that read the page before midnight and
1950
+ // follows the link after it still trips.
1951
+ activePaths: Array.from(/* @__PURE__ */ new Set([today, yesterday])),
1952
+ linkHtml: linkFor(today, text),
1953
+ linkProps: propsFor(today, text)
1954
+ };
1690
1955
  }
1691
- function parseInnerList(p, entry) {
1692
- p.i++;
1693
- for (; ; ) {
1694
- p.skipSP();
1695
- if (p.eof()) throw new Error("sfv: unterminated inner list");
1696
- if (p.peek() === ")") {
1697
- p.i++;
1698
- break;
1956
+ function injectHoneytokenLink(html, linkHtml) {
1957
+ if (!html || html.includes(linkHtml)) return html;
1958
+ const lower = html.toLowerCase();
1959
+ for (const close of ["</body>", "</html>"]) {
1960
+ const at = lower.lastIndexOf(close);
1961
+ if (at !== -1) {
1962
+ return html.slice(0, at) + linkHtml + html.slice(at);
1699
1963
  }
1700
- entry.items.push(parseItem(p));
1701
- if (p.eof()) throw new Error("sfv: unterminated inner list");
1702
- const c = p.peek();
1703
- if (c !== " " && c !== ")") throw new Error(`sfv: bad inner list at ${p.i}`);
1704
1964
  }
1705
- entry.params = parseParams(p);
1965
+ return html;
1706
1966
  }
1707
- function parseItem(p) {
1708
- const { value, bytes } = parseBareItem(p);
1709
- const params = parseParams(p);
1710
- return bytes ? { value, params, bytes } : { value, params };
1967
+ function isInjectableHtml(contentType) {
1968
+ if (!contentType) return false;
1969
+ return contentType.toLowerCase().split(";")[0].trim() === "text/html";
1711
1970
  }
1712
- function parseParams(p) {
1713
- const params = /* @__PURE__ */ new Map();
1714
- while (!p.eof() && p.peek() === ";") {
1715
- p.i++;
1716
- p.skipSP();
1717
- const key = parseKey(p);
1718
- let val = true;
1719
- if (!p.eof() && p.peek() === "=") {
1720
- p.i++;
1721
- val = parseBareItem(p).value;
1722
- }
1723
- params.set(key, val);
1724
- }
1725
- return params;
1726
- }
1727
- function parseKey(p) {
1728
- const c = p.peek();
1729
- if (!c || !/[a-z*]/.test(c)) throw new Error(`sfv: invalid key at ${p.i}`);
1730
- const start = p.i;
1731
- while (!p.eof() && /[a-z0-9_\-.*]/.test(p.peek())) p.i++;
1732
- return p.s.slice(start, p.i);
1733
- }
1734
- function parseBareItem(p) {
1735
- const c = p.peek();
1736
- if (c === '"') return { value: parseString(p) };
1737
- if (c === ":") return { value: "", bytes: parseByteSequence(p) };
1738
- if (c === "?") {
1739
- p.i++;
1740
- const b = p.s[p.i++];
1741
- if (b === "1") return { value: true };
1742
- if (b === "0") return { value: false };
1743
- throw new Error("sfv: bad boolean");
1744
- }
1745
- if (c === "-" || /[0-9]/.test(c)) return { value: parseNumber(p) };
1746
- if (/[a-zA-Z*]/.test(c)) return { value: parseToken(p) };
1747
- throw new Error(`sfv: invalid bare item at ${p.i}`);
1748
- }
1749
- function parseString(p) {
1750
- p.i++;
1751
- let out = "";
1752
- while (!p.eof()) {
1753
- const c = p.s[p.i++];
1754
- if (c === '"') return out;
1755
- if (c === "\\") {
1756
- const e = p.s[p.i++];
1757
- if (e !== '"' && e !== "\\") throw new Error("sfv: bad escape");
1758
- out += e;
1759
- } else {
1760
- const code = c.charCodeAt(0);
1761
- if (code < 32 || code > 126) throw new Error("sfv: bad char in string");
1762
- out += c;
1763
- }
1764
- }
1765
- throw new Error("sfv: unterminated string");
1766
- }
1767
- function parseByteSequence(p) {
1768
- p.i++;
1769
- const start = p.i;
1770
- while (!p.eof() && p.peek() !== ":") p.i++;
1771
- if (p.eof()) throw new Error("sfv: unterminated byte sequence");
1772
- const b64 = p.s.slice(start, p.i);
1773
- p.i++;
1774
- return base64StdToBytes(b64);
1971
+
1972
+ // src/rules/index.ts
1973
+ function rateLimit(config) {
1974
+ return new RateLimitRule(config);
1775
1975
  }
1776
- function parseNumber(p) {
1777
- const start = p.i;
1778
- if (p.peek() === "-") p.i++;
1779
- while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
1780
- if (!p.eof() && p.peek() === ".") {
1781
- p.i++;
1782
- while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
1783
- }
1784
- return Number(p.s.slice(start, p.i));
1976
+ function filter(config) {
1977
+ return new FilterRule(config);
1785
1978
  }
1786
- function parseToken(p) {
1787
- const start = p.i;
1788
- p.i++;
1789
- while (!p.eof() && /[a-zA-Z0-9!#$%&'*+\-.^_`|~:/]/.test(p.peek())) p.i++;
1790
- return p.s.slice(start, p.i);
1979
+ function tripwire(config = {}) {
1980
+ return new TripwireRule(config);
1791
1981
  }
1792
- function base64StdToBytes(s) {
1793
- const bin = atob(s);
1794
- const out = new Uint8Array(bin.length);
1795
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
1796
- return out;
1982
+ function bots(config = {}) {
1983
+ return new BotRule(config);
1797
1984
  }
1798
1985
 
1799
- // src/agent/signature.ts
1800
- var TAG = "web-bot-auth";
1801
- var encoder3 = new TextEncoder();
1802
- async function verifyWebBotAuth(req, resolveKey, toleranceSec) {
1803
- const sigInput = req.headers.get("signature-input");
1804
- const sigHeader = req.headers.get("signature");
1805
- if (!sigInput && !sigHeader) return { outcome: "none" };
1806
- if (!sigInput || !sigHeader) return { outcome: "claimed", reason: "incomplete-signature" };
1807
- let members;
1808
- let sigs;
1809
- try {
1810
- members = parseSignatureInput(sigInput);
1811
- sigs = parseSignatureBytes(sigHeader);
1812
- } catch {
1813
- return { outcome: "claimed", reason: "malformed-signature" };
1814
- }
1815
- const now = Date.now() / 1e3;
1816
- let best = { outcome: "none" };
1817
- for (const m of members) {
1818
- if (m.params.get("tag") !== TAG) continue;
1819
- if (best.outcome === "none") best = { outcome: "claimed", reason: "unverifiable" };
1820
- const sig = sigs.get(m.label);
1821
- if (!sig) continue;
1822
- const keyid = m.params.get("keyid");
1823
- if (typeof keyid !== "string") continue;
1824
- if (!m.components.some((c) => c.name === "@authority" || c.name === "@target-uri")) continue;
1825
- const key = await resolveKey(keyid);
1826
- if (!key) {
1827
- best = higher(best, { outcome: "claimed", keyId: keyid, reason: "unknown-key" });
1828
- continue;
1829
- }
1830
- const created = numeric(m.params.get("created"));
1831
- const expires = numeric(m.params.get("expires"));
1832
- if (expires !== void 0 && now > expires + toleranceSec) {
1833
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "expired" });
1834
- continue;
1986
+ // src/violation-reporter.ts
1987
+ var ViolationReporter = class {
1988
+ constructor(client, config = {}) {
1989
+ this.buffer = [];
1990
+ this.flushing = false;
1991
+ this.client = client;
1992
+ this.maxBufferSize = config.maxBufferSize ?? 50;
1993
+ this.debug = config.debug ?? false;
1994
+ const flushInterval = config.flushInterval ?? 5e3;
1995
+ this.flushTimer = setInterval(() => void this.flush(), flushInterval);
1996
+ if (this.flushTimer.unref) {
1997
+ this.flushTimer.unref();
1835
1998
  }
1836
- if (created !== void 0 && now + toleranceSec < created) {
1837
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "not-yet-valid" });
1838
- continue;
1999
+ }
2000
+ /**
2001
+ * Add violations to the buffer. Auto-flushes when buffer reaches maxBufferSize.
2002
+ */
2003
+ report(violations) {
2004
+ this.buffer.push(...violations);
2005
+ if (this.buffer.length >= this.maxBufferSize) {
2006
+ this.flush().catch(() => {
2007
+ });
1839
2008
  }
1840
- if (key.exp !== void 0 && now > key.exp + toleranceSec) {
1841
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-expired" });
1842
- continue;
2009
+ }
2010
+ /**
2011
+ * Flush buffered violations to the backend
2012
+ */
2013
+ async flush() {
2014
+ if (this.flushing || this.buffer.length === 0) return;
2015
+ this.flushing = true;
2016
+ const events = this.buffer.splice(0, this.buffer.length);
2017
+ try {
2018
+ for (let i = 0; i < events.length; i += 100) {
2019
+ const batch = events.slice(i, i + 100);
2020
+ await this.client.sendViolations(batch);
2021
+ if (this.debug) {
2022
+ console.log(`[WebDecoy] Flushed ${batch.length} violation events`);
2023
+ }
2024
+ }
2025
+ } catch (error) {
2026
+ if (this.debug) {
2027
+ console.error("[WebDecoy] Failed to flush violations:", error);
2028
+ }
2029
+ } finally {
2030
+ this.flushing = false;
1843
2031
  }
1844
- if (key.nbf !== void 0 && now + toleranceSec < key.nbf) {
1845
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-not-yet-valid" });
1846
- continue;
2032
+ }
2033
+ /**
2034
+ * Flush remaining events and stop the timer
2035
+ */
2036
+ async destroy() {
2037
+ clearInterval(this.flushTimer);
2038
+ await this.flush();
2039
+ }
2040
+ };
2041
+
2042
+ // src/ip-enrichment.ts
2043
+ var IPEnrichmentClient = class {
2044
+ constructor(client, ttlMs = 36e5) {
2045
+ this.cache = /* @__PURE__ */ new Map();
2046
+ this.pending = /* @__PURE__ */ new Map();
2047
+ this.client = client;
2048
+ this.ttlMs = ttlMs;
2049
+ }
2050
+ /**
2051
+ * Get enrichment data for an IP address.
2052
+ * Returns cached data if available (1h TTL), otherwise fetches from API.
2053
+ * Returns null if enrichment fails (fail-open).
2054
+ */
2055
+ async enrich(ip) {
2056
+ const cached = this.cache.get(ip);
2057
+ if (cached && cached.expiresAt > Date.now()) {
2058
+ return cached.data;
1847
2059
  }
1848
- let base;
1849
- try {
1850
- base = buildSignatureBase(req, m);
1851
- } catch {
1852
- best = higher(best, { outcome: "claimed", keyId: keyid, reason: "uncoverable-component" });
1853
- continue;
2060
+ const inflight = this.pending.get(ip);
2061
+ if (inflight) {
2062
+ return inflight;
1854
2063
  }
1855
- let ok = false;
2064
+ const promise = this.fetchAndCache(ip);
2065
+ this.pending.set(ip, promise);
1856
2066
  try {
1857
- ok = await crypto.subtle.verify(
1858
- key.verifyParams,
1859
- key.cryptoKey,
1860
- sig,
1861
- encoder3.encode(base)
1862
- );
1863
- } catch {
1864
- ok = false;
2067
+ return await promise;
2068
+ } finally {
2069
+ this.pending.delete(ip);
1865
2070
  }
1866
- if (ok) {
1867
- return { outcome: "verified", keyId: keyid, key };
2071
+ }
2072
+ async fetchAndCache(ip) {
2073
+ const data = await this.client.getIPEnrichment(ip);
2074
+ if (data) {
2075
+ this.cache.set(ip, {
2076
+ data,
2077
+ expiresAt: Date.now() + this.ttlMs
2078
+ });
1868
2079
  }
1869
- best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "bad-signature" });
2080
+ return data;
1870
2081
  }
1871
- return best;
2082
+ /**
2083
+ * Clear the cache
2084
+ */
2085
+ clearCache() {
2086
+ this.cache.clear();
2087
+ }
2088
+ };
2089
+
2090
+ // src/agent/thumbprint.ts
2091
+ var encoder2 = new TextEncoder();
2092
+ async function rsaThumbprint(n, e) {
2093
+ return digest(`{"e":${JSON.stringify(e)},"kty":"RSA","n":${JSON.stringify(n)}}`);
1872
2094
  }
1873
- var PRECEDENCE = { none: 0, claimed: 1, impersonation: 2, verified: 3 };
1874
- function higher(a, b) {
1875
- return PRECEDENCE[b.outcome] >= PRECEDENCE[a.outcome] ? b : a;
1876
- }
1877
- function numeric(v) {
1878
- return typeof v === "number" ? v : void 0;
2095
+ async function okpThumbprint(crv, x) {
2096
+ return digest(`{"crv":${JSON.stringify(crv)},"kty":"OKP","x":${JSON.stringify(x)}}`);
1879
2097
  }
1880
- function buildSignatureBase(req, m) {
1881
- const lines = [];
1882
- for (const c of m.components) {
1883
- lines.push(`${serializeComponentId(c)}: ${componentValue(req, c)}`);
2098
+ async function jwkThumbprint(k) {
2099
+ switch (k.kty) {
2100
+ case "OKP":
2101
+ if (!k.crv || !k.x) throw new Error("thumbprint: OKP JWK missing crv or x");
2102
+ return okpThumbprint(k.crv, k.x);
2103
+ case "RSA":
2104
+ if (!k.n || !k.e) throw new Error("thumbprint: RSA JWK missing n or e");
2105
+ return rsaThumbprint(k.n, k.e);
2106
+ default:
2107
+ throw new Error(`thumbprint: unsupported kty ${JSON.stringify(k.kty)}`);
1884
2108
  }
1885
- lines.push(`"@signature-params": ${m.raw.trim()}`);
1886
- return lines.join("\n");
1887
2109
  }
1888
- function serializeComponentId(c) {
1889
- const base = `"${c.name.toLowerCase()}"`;
1890
- return c.keyParam !== void 0 ? `${base};key="${c.keyParam}"` : base;
2110
+ async function digest(canonical) {
2111
+ const buf = await crypto.subtle.digest("SHA-256", encoder2.encode(canonical));
2112
+ return base64urlBytes(new Uint8Array(buf));
1891
2113
  }
1892
- function componentValue(req, c) {
1893
- const name = c.name.toLowerCase();
1894
- switch (name) {
1895
- case "@method":
1896
- return req.method.toUpperCase();
1897
- case "@authority":
1898
- return canonicalAuthority(req.url);
1899
- case "@scheme":
1900
- return req.url.protocol.replace(/:$/, "").toLowerCase();
1901
- case "@target-uri":
1902
- return `${req.url.protocol}//${canonicalAuthority(req.url)}${req.url.pathname}${req.url.search}`;
1903
- case "@path":
1904
- return req.url.pathname;
1905
- case "@query":
1906
- return req.url.search === "" ? "?" : req.url.search;
1907
- case "signature-agent": {
1908
- const header = req.headers.get("signature-agent");
1909
- if (header === null) throw new Error("signature-agent covered but absent");
1910
- if (c.keyParam !== void 0) return dictMemberValue(header, c.keyParam);
1911
- return header.trim().replace(/\s+/g, " ");
1912
- }
1913
- default: {
1914
- if (name.startsWith("@")) throw new Error(`unsupported derived component ${name}`);
1915
- const header = req.headers.get(name);
1916
- if (header === null) throw new Error(`covered header ${name} absent`);
1917
- return header.trim().replace(/\s+/g, " ");
1918
- }
1919
- }
2114
+ function base64urlBytes(bytes) {
2115
+ let binary = "";
2116
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
2117
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1920
2118
  }
1921
- function canonicalAuthority(url) {
1922
- const host = url.hostname.toLowerCase();
1923
- const port = url.port;
1924
- if (!port) return host;
1925
- if (url.protocol === "https:" && port === "443" || url.protocol === "http:" && port === "80") {
1926
- return host;
2119
+
2120
+ // src/agent/directory.ts
2121
+ var WELL_KNOWN = "/.well-known/http-message-signatures-directory";
2122
+ var COLD_RETRY_BACKOFF_MS = 3e4;
2123
+ var DEFAULT_SIGNED_AGENT_DIRECTORIES = [
2124
+ { name: "OpenAI", category: "ai_crawlers", directory: "https://operator.openai.com" },
2125
+ { name: "OpenAI ChatGPT", category: "ai_crawlers", directory: "https://chatgpt.com" }
2126
+ ];
2127
+ var DirectoryCache = class {
2128
+ constructor(opts) {
2129
+ this.keys = /* @__PURE__ */ new Map();
2130
+ this.refreshedAt = 0;
2131
+ this.nextColdRetryAt = 0;
2132
+ this.inflight = null;
2133
+ /** Resolve a keyid to a verification key, fetching/refreshing as needed. */
2134
+ this.resolveKey = async (keyId) => {
2135
+ await this.ensureFresh();
2136
+ return this.keys.get(keyId);
2137
+ };
2138
+ this.opts = opts;
1927
2139
  }
1928
- return `${host}:${port}`;
1929
- }
1930
- function dictMemberValue(header, key) {
1931
- const dict = parseDictionary(header);
1932
- const found = dict.find((d) => d.key === key);
1933
- if (!found) throw new Error(`signature-agent has no member ${key}`);
1934
- return found.raw;
1935
- }
1936
- function parseSignatureInput(value) {
1937
- return parseDictionary(value).map((d) => {
1938
- if (!d.isList) throw new Error(`Signature-Input member ${d.key} is not an inner list`);
1939
- const components = d.items.map((it) => {
1940
- if (typeof it.value !== "string") throw new Error("component identifier is not a string");
1941
- const keyParam = it.params.get("key");
1942
- return { name: it.value, keyParam: typeof keyParam === "string" ? keyParam : void 0 };
1943
- });
1944
- return { label: d.key, components, params: d.params, raw: d.raw };
1945
- });
1946
- }
1947
- function parseSignatureBytes(value) {
1948
- const out = /* @__PURE__ */ new Map();
1949
- for (const d of parseDictionary(value)) {
1950
- if (d.isList || d.items.length !== 1 || !d.items[0].bytes) {
1951
- throw new Error(`Signature member ${d.key} is not a byte sequence`);
2140
+ /** Kick off a fetch without blocking — call at startup to warm the cache. */
2141
+ prime() {
2142
+ if (this.keys.size === 0 && Date.now() >= this.nextColdRetryAt) void this.refresh();
2143
+ }
2144
+ /** Number of keys currently cached (diagnostics/tests). */
2145
+ get size() {
2146
+ return this.keys.size;
2147
+ }
2148
+ async ensureFresh() {
2149
+ const now = Date.now();
2150
+ const stale = now - this.refreshedAt > this.opts.cacheTtlMs;
2151
+ if (this.keys.size > 0) {
2152
+ if (stale) void this.refresh();
2153
+ return;
1952
2154
  }
1953
- out.set(d.key, d.items[0].bytes);
2155
+ if (now < this.nextColdRetryAt) return;
2156
+ await this.refresh();
1954
2157
  }
1955
- return out;
1956
- }
1957
-
1958
- // src/agent/verifier.ts
1959
- var DEFAULT_TTL_MS = 6 * 60 * 60 * 1e3;
1960
- var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
1961
- var DEFAULT_TOLERANCE_SEC = 300;
1962
- var AgentVerifier = class {
1963
- constructor(options = {}) {
1964
- this.toleranceSec = options.toleranceSec ?? DEFAULT_TOLERANCE_SEC;
1965
- this.cache = new DirectoryCache({
1966
- directories: options.directories ?? DEFAULT_SIGNED_AGENT_DIRECTORIES,
1967
- cacheTtlMs: options.cacheTtlMs ?? DEFAULT_TTL_MS,
1968
- fetchTimeoutMs: options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,
1969
- debug: options.debug ?? false,
1970
- fetchImpl: options.fetchImpl ?? fetch
2158
+ /** Re-fetch every directory. De-duplicated: concurrent callers share one run. */
2159
+ refresh() {
2160
+ if (this.inflight) return this.inflight;
2161
+ this.inflight = this.doRefresh().finally(() => {
2162
+ this.inflight = null;
1971
2163
  });
2164
+ return this.inflight;
1972
2165
  }
1973
- /** Pre-fetch trusted directories so the first request verifies warm. */
1974
- warmup() {
1975
- this.cache.prime();
2166
+ async doRefresh() {
2167
+ const results = await Promise.all(
2168
+ this.opts.directories.map((src) => this.fetchDirectory(src))
2169
+ );
2170
+ const next = new Map(this.keys);
2171
+ let fetchedAny = false;
2172
+ for (const keys of results) {
2173
+ if (keys === null) continue;
2174
+ fetchedAny = true;
2175
+ for (const k of keys) next.set(k.thumbprint, k.key);
2176
+ }
2177
+ if (fetchedAny) {
2178
+ this.keys = next;
2179
+ this.refreshedAt = Date.now();
2180
+ this.nextColdRetryAt = 0;
2181
+ this.debug(`refreshed: ${this.keys.size} key(s) across ${this.opts.directories.length} directories`);
2182
+ } else if (this.keys.size === 0) {
2183
+ this.nextColdRetryAt = Date.now() + COLD_RETRY_BACKOFF_MS;
2184
+ this.debug("all directories unreachable; backing off cold retry");
2185
+ }
1976
2186
  }
1977
- /** Verify a request's Web Bot Auth signature (if any) locally. */
1978
- async verify(request) {
1979
- let req;
2187
+ async fetchDirectory(src) {
2188
+ const url = directoryUrl(src.directory);
2189
+ const controller = new AbortController();
2190
+ const timer = setTimeout(() => controller.abort(), this.opts.fetchTimeoutMs);
1980
2191
  try {
1981
- req = normalize(request);
1982
- } catch {
1983
- return { status: "none" };
1984
- }
1985
- const result = await verifyWebBotAuth(req, this.cache.resolveKey, this.toleranceSec);
1986
- switch (result.outcome) {
1987
- case "verified":
1988
- return {
1989
- status: "verified",
1990
- method: "signature",
1991
- keyId: result.keyId,
1992
- agentName: result.key?.name,
1993
- category: result.key?.category,
1994
- algorithm: result.key?.algorithm
1995
- };
1996
- case "impersonation":
1997
- return {
1998
- status: "impersonation",
1999
- method: "signature",
2000
- keyId: result.keyId,
2001
- agentName: result.key?.name,
2002
- category: result.key?.category,
2003
- reason: result.reason
2004
- };
2005
- case "claimed":
2006
- return { status: "claimed", keyId: result.keyId, reason: result.reason };
2007
- default:
2008
- return { status: "none" };
2192
+ const res = await this.opts.fetchImpl(url, {
2193
+ signal: controller.signal,
2194
+ headers: {
2195
+ Accept: "application/http-message-signatures-directory+json, application/jwk-set+json, application/json"
2196
+ },
2197
+ redirect: "follow"
2198
+ });
2199
+ if (!res.ok) {
2200
+ this.debug(`${src.name}: HTTP ${res.status}`);
2201
+ return null;
2202
+ }
2203
+ const body = await res.json();
2204
+ if (!body || !Array.isArray(body.keys)) {
2205
+ this.debug(`${src.name}: no keys in directory`);
2206
+ return null;
2207
+ }
2208
+ const out = [];
2209
+ for (const jwk of body.keys) {
2210
+ const resolved = await importKey(jwk, src);
2211
+ if (resolved) out.push(resolved);
2212
+ }
2213
+ this.debug(`${src.name}: ${out.length} key(s)`);
2214
+ return out;
2215
+ } catch (err) {
2216
+ this.debug(`${src.name}: fetch failed \u2014 ${err.message}`);
2217
+ return null;
2218
+ } finally {
2219
+ clearTimeout(timer);
2009
2220
  }
2010
2221
  }
2011
- /** Cached-key count (diagnostics/tests). */
2012
- get cachedKeyCount() {
2013
- return this.cache.size;
2222
+ debug(msg) {
2223
+ if (this.opts.debug) console.log(`[WebDecoy][web-bot-auth] ${msg}`);
2014
2224
  }
2015
2225
  };
2016
- function createAgentVerifier(options = {}) {
2017
- return new AgentVerifier(options);
2018
- }
2019
- function normalize(input) {
2020
- if (isRequest(input)) {
2021
- return { method: input.method, url: new URL(input.url), headers: input.headers };
2022
- }
2023
- const headers = input.headers instanceof Headers ? input.headers : toHeaders(input.headers);
2024
- return { method: input.method, url: new URL(input.url), headers };
2025
- }
2026
- function isRequest(input) {
2027
- return typeof Request !== "undefined" && input instanceof Request && typeof input.url === "string";
2226
+ function directoryUrl(directory) {
2227
+ const u = new URL(directory);
2228
+ if (u.pathname && u.pathname !== "/") return u.toString();
2229
+ u.pathname = WELL_KNOWN;
2230
+ return u.toString();
2028
2231
  }
2029
- function toHeaders(record) {
2030
- const h = new Headers();
2031
- for (const [k, v] of Object.entries(record)) {
2032
- if (v !== void 0 && v !== null) h.set(k, String(v));
2232
+ async function importKey(jwk, src) {
2233
+ try {
2234
+ let cryptoKey;
2235
+ let verifyParams;
2236
+ let algorithm;
2237
+ if (jwk.kty === "OKP") {
2238
+ if (jwk.crv !== "Ed25519" || !jwk.x) return null;
2239
+ cryptoKey = await crypto.subtle.importKey(
2240
+ "jwk",
2241
+ { kty: "OKP", crv: "Ed25519", x: jwk.x },
2242
+ { name: "Ed25519" },
2243
+ false,
2244
+ ["verify"]
2245
+ );
2246
+ verifyParams = { name: "Ed25519" };
2247
+ algorithm = "ed25519";
2248
+ } else if (jwk.kty === "RSA") {
2249
+ if (!jwk.n || !jwk.e) return null;
2250
+ cryptoKey = await crypto.subtle.importKey(
2251
+ "jwk",
2252
+ { kty: "RSA", n: jwk.n, e: jwk.e },
2253
+ { name: "RSA-PSS", hash: "SHA-512" },
2254
+ false,
2255
+ ["verify"]
2256
+ );
2257
+ verifyParams = { name: "RSA-PSS", saltLength: 64 };
2258
+ algorithm = "rsa-pss-sha512";
2259
+ } else {
2260
+ return null;
2261
+ }
2262
+ const thumbprint = await jwkThumbprint(jwk);
2263
+ return {
2264
+ thumbprint,
2265
+ key: {
2266
+ cryptoKey,
2267
+ verifyParams,
2268
+ algorithm,
2269
+ name: src.name,
2270
+ category: src.category,
2271
+ nbf: normalizeEpoch(jwk.nbf),
2272
+ exp: normalizeEpoch(jwk.exp)
2273
+ }
2274
+ };
2275
+ } catch {
2276
+ return null;
2033
2277
  }
2034
- return h;
2278
+ }
2279
+ function normalizeEpoch(v) {
2280
+ if (v === void 0 || v === 0) return void 0;
2281
+ return v > 1e12 ? Math.floor(v / 1e3) : v;
2035
2282
  }
2036
2283
 
2037
- // src/edge.ts
2038
- var EDGE_CLEARANCE_HEADER = "x-wd-clearance";
2039
- var EDGE_CLASS_HEADER = "x-wd-class";
2040
- var EDGE_CLASSES = ["verified", "crawler", "script", "browser"];
2041
- function absent() {
2042
- return {
2043
- present: false,
2044
- isVerified: false,
2045
- isCrawler: false,
2046
- isScript: false,
2047
- isBrowser: false,
2048
- isUnattestedNonBrowser: false
2049
- };
2284
+ // src/agent/sfv.ts
2285
+ var Cursor = class {
2286
+ constructor(s, i = 0) {
2287
+ this.s = s;
2288
+ this.i = i;
2289
+ }
2290
+ eof() {
2291
+ return this.i >= this.s.length;
2292
+ }
2293
+ peek() {
2294
+ return this.s[this.i];
2295
+ }
2296
+ skipSP() {
2297
+ while (!this.eof() && (this.peek() === " " || this.peek() === " ")) this.i++;
2298
+ }
2299
+ };
2300
+ function parseDictionary(input) {
2301
+ const p = new Cursor(input);
2302
+ const out = [];
2303
+ p.skipSP();
2304
+ while (!p.eof()) {
2305
+ const key = parseKey(p);
2306
+ const entry = { key, raw: "", isList: false, items: [], params: /* @__PURE__ */ new Map() };
2307
+ if (!p.eof() && p.peek() === "=") {
2308
+ p.i++;
2309
+ const start = p.i;
2310
+ if (!p.eof() && p.peek() === "(") {
2311
+ entry.isList = true;
2312
+ parseInnerList(p, entry);
2313
+ } else {
2314
+ entry.items.push(parseItem(p));
2315
+ entry.params = entry.items[0].params;
2316
+ }
2317
+ entry.raw = input.slice(start, p.i);
2318
+ } else {
2319
+ entry.params = parseParams(p);
2320
+ entry.items.push({ value: true, params: /* @__PURE__ */ new Map() });
2321
+ entry.raw = "?1";
2322
+ }
2323
+ out.push(entry);
2324
+ p.skipSP();
2325
+ if (p.eof()) break;
2326
+ if (p.peek() !== ",") throw new Error(`sfv: expected ',' at ${p.i}`);
2327
+ p.i++;
2328
+ p.skipSP();
2329
+ if (p.eof()) throw new Error("sfv: trailing comma");
2330
+ }
2331
+ return out;
2050
2332
  }
2051
- function normaliseClass(raw) {
2052
- if (!raw) return void 0;
2053
- const v = raw.trim().toLowerCase();
2054
- return EDGE_CLASSES.includes(v) ? v : void 0;
2333
+ function parseInnerList(p, entry) {
2334
+ p.i++;
2335
+ for (; ; ) {
2336
+ p.skipSP();
2337
+ if (p.eof()) throw new Error("sfv: unterminated inner list");
2338
+ if (p.peek() === ")") {
2339
+ p.i++;
2340
+ break;
2341
+ }
2342
+ entry.items.push(parseItem(p));
2343
+ if (p.eof()) throw new Error("sfv: unterminated inner list");
2344
+ const c = p.peek();
2345
+ if (c !== " " && c !== ")") throw new Error(`sfv: bad inner list at ${p.i}`);
2346
+ }
2347
+ entry.params = parseParams(p);
2055
2348
  }
2056
- function readEdgeVerdict(headers) {
2057
- if (!headers) return absent();
2058
- let clearanceRaw;
2059
- let classRaw;
2060
- for (const key of Object.keys(headers)) {
2061
- const k = key.toLowerCase();
2062
- if (k === EDGE_CLEARANCE_HEADER) clearanceRaw = headers[key];
2063
- else if (k === EDGE_CLASS_HEADER) classRaw = headers[key];
2349
+ function parseItem(p) {
2350
+ const { value, bytes } = parseBareItem(p);
2351
+ const params = parseParams(p);
2352
+ return bytes ? { value, params, bytes } : { value, params };
2353
+ }
2354
+ function parseParams(p) {
2355
+ const params = /* @__PURE__ */ new Map();
2356
+ while (!p.eof() && p.peek() === ";") {
2357
+ p.i++;
2358
+ p.skipSP();
2359
+ const key = parseKey(p);
2360
+ let val = true;
2361
+ if (!p.eof() && p.peek() === "=") {
2362
+ p.i++;
2363
+ val = parseBareItem(p).value;
2364
+ }
2365
+ params.set(key, val);
2064
2366
  }
2065
- const clearance = clearanceRaw?.trim() || void 0;
2066
- const cls = normaliseClass(classRaw);
2067
- if (!clearance && !cls) return absent();
2068
- return {
2069
- present: true,
2070
- clearance,
2071
- class: cls,
2072
- isVerified: cls === "verified",
2073
- isCrawler: cls === "crawler",
2074
- isScript: cls === "script",
2075
- isBrowser: cls === "browser",
2076
- isUnattestedNonBrowser: cls === "script" || cls === "crawler"
2077
- };
2367
+ return params;
2368
+ }
2369
+ function parseKey(p) {
2370
+ const c = p.peek();
2371
+ if (!c || !/[a-z*]/.test(c)) throw new Error(`sfv: invalid key at ${p.i}`);
2372
+ const start = p.i;
2373
+ while (!p.eof() && /[a-z0-9_\-.*]/.test(p.peek())) p.i++;
2374
+ return p.s.slice(start, p.i);
2375
+ }
2376
+ function parseBareItem(p) {
2377
+ const c = p.peek();
2378
+ if (c === '"') return { value: parseString(p) };
2379
+ if (c === ":") return { value: "", bytes: parseByteSequence(p) };
2380
+ if (c === "?") {
2381
+ p.i++;
2382
+ const b = p.s[p.i++];
2383
+ if (b === "1") return { value: true };
2384
+ if (b === "0") return { value: false };
2385
+ throw new Error("sfv: bad boolean");
2386
+ }
2387
+ if (c === "-" || /[0-9]/.test(c)) return { value: parseNumber(p) };
2388
+ if (/[a-zA-Z*]/.test(c)) return { value: parseToken(p) };
2389
+ throw new Error(`sfv: invalid bare item at ${p.i}`);
2390
+ }
2391
+ function parseString(p) {
2392
+ p.i++;
2393
+ let out = "";
2394
+ while (!p.eof()) {
2395
+ const c = p.s[p.i++];
2396
+ if (c === '"') return out;
2397
+ if (c === "\\") {
2398
+ const e = p.s[p.i++];
2399
+ if (e !== '"' && e !== "\\") throw new Error("sfv: bad escape");
2400
+ out += e;
2401
+ } else {
2402
+ const code = c.charCodeAt(0);
2403
+ if (code < 32 || code > 126) throw new Error("sfv: bad char in string");
2404
+ out += c;
2405
+ }
2406
+ }
2407
+ throw new Error("sfv: unterminated string");
2408
+ }
2409
+ function parseByteSequence(p) {
2410
+ p.i++;
2411
+ const start = p.i;
2412
+ while (!p.eof() && p.peek() !== ":") p.i++;
2413
+ if (p.eof()) throw new Error("sfv: unterminated byte sequence");
2414
+ const b64 = p.s.slice(start, p.i);
2415
+ p.i++;
2416
+ return base64StdToBytes(b64);
2417
+ }
2418
+ function parseNumber(p) {
2419
+ const start = p.i;
2420
+ if (p.peek() === "-") p.i++;
2421
+ while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
2422
+ if (!p.eof() && p.peek() === ".") {
2423
+ p.i++;
2424
+ while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
2425
+ }
2426
+ return Number(p.s.slice(start, p.i));
2427
+ }
2428
+ function parseToken(p) {
2429
+ const start = p.i;
2430
+ p.i++;
2431
+ while (!p.eof() && /[a-zA-Z0-9!#$%&'*+\-.^_`|~:/]/.test(p.peek())) p.i++;
2432
+ return p.s.slice(start, p.i);
2433
+ }
2434
+ function base64StdToBytes(s) {
2435
+ const bin = atob(s);
2436
+ const out = new Uint8Array(bin.length);
2437
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
2438
+ return out;
2078
2439
  }
2079
2440
 
2080
- // src/bots/registry.generated.ts
2081
- var BOT_CATEGORIES = [
2082
- "training_crawler",
2083
- "ai_search_crawler",
2084
- "ai_agent",
2085
- "ai_assistant",
2086
- "search_crawler",
2087
- "seo_crawler",
2088
- "security_scanner",
2089
- "generic_scraper",
2090
- "archiver",
2091
- "fetcher",
2092
- "monitoring",
2093
- "headless_browser",
2094
- "feed_reader",
2095
- "commercial_scraper",
2096
- "none"
2097
- ];
2098
- var BOT_REGISTRY = [
2099
- { id: "gptbot", name: "GPTBot", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["gptbot"] },
2100
- { id: "chatgpt-user", name: "ChatGPT-User", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["chatgpt-user", "chatgpt"] },
2101
- { id: "oai-searchbot", name: "OAI-SearchBot", category: "training_crawler", organization: "OpenAI", baseScore: 80, respectsRobots: true, uaPatterns: ["oai-searchbot"] },
2102
- { id: "claudebot", name: "ClaudeBot", category: "training_crawler", organization: "Anthropic", baseScore: 85, respectsRobots: true, uaPatterns: ["claudebot"] },
2103
- { id: "anthropic", name: "Anthropic", category: "training_crawler", organization: "Anthropic", baseScore: 85, respectsRobots: true, uaPatterns: ["anthropic"] },
2104
- { id: "ccbot", name: "CCBot", category: "training_crawler", organization: "Common Crawl", baseScore: 80, respectsRobots: true, uaPatterns: ["ccbot"] },
2105
- { id: "google-extended", name: "Google-Extended", category: "training_crawler", organization: "Google", baseScore: 80, respectsRobots: true, uaPatterns: ["google-extended"] },
2106
- { id: "bytespider", name: "ByteSpider", category: "training_crawler", organization: "ByteDance", baseScore: 75, respectsRobots: false, uaPatterns: ["bytespider"] },
2107
- { id: "amazonbot", name: "Amazonbot", category: "training_crawler", organization: "Amazon", baseScore: 70, respectsRobots: true, uaPatterns: ["amazonbot"] },
2108
- { id: "facebookbot", name: "FacebookBot", category: "training_crawler", organization: "Meta", baseScore: 70, respectsRobots: true, uaPatterns: ["facebookbot"] },
2109
- { id: "meta-externalagent", name: "Meta-ExternalAgent", category: "training_crawler", organization: "Meta", baseScore: 75, respectsRobots: true, uaPatterns: ["meta-externalagent"] },
2110
- { id: "cohere-ai", name: "Cohere", category: "training_crawler", organization: "Cohere", baseScore: 80, respectsRobots: true, uaPatterns: ["cohere-ai", "cohere"] },
2111
- { id: "perplexitybot", name: "PerplexityBot", category: "training_crawler", organization: "Perplexity AI", baseScore: 80, respectsRobots: true, uaPatterns: ["perplexitybot"] },
2112
- { id: "applebot-extended", name: "Applebot-Extended", category: "training_crawler", organization: "Apple", baseScore: 75, respectsRobots: true, uaPatterns: ["applebot-extended"] },
2113
- { id: "youbot", name: "YouBot", category: "training_crawler", organization: "You.com", baseScore: 75, respectsRobots: true, uaPatterns: ["youbot"] },
2114
- { id: "mistral", name: "MistralBot", category: "training_crawler", organization: "Mistral AI", baseScore: 80, respectsRobots: true, uaPatterns: ["mistral"] },
2115
- { id: "gemini", name: "Gemini", category: "training_crawler", organization: "Google", baseScore: 80, respectsRobots: true, uaPatterns: ["gemini"] },
2116
- { id: "ai2bot", name: "AI2Bot", category: "training_crawler", organization: "Allen Institute for AI", baseScore: 75, respectsRobots: true, uaPatterns: ["ai2bot"] },
2117
- { id: "deepseek", name: "DeepSeek", category: "training_crawler", organization: "DeepSeek", baseScore: 80, respectsRobots: true, uaPatterns: ["deepseek"] },
2118
- { id: "qwen", name: "Qwen", category: "training_crawler", organization: "Alibaba", baseScore: 75, respectsRobots: true, uaPatterns: ["qwen"] },
2119
- { id: "webzio", name: "Webz.io", category: "training_crawler", organization: "Webz.io", baseScore: 70, respectsRobots: false, uaPatterns: ["webzio"] },
2120
- { id: "sentibot", name: "Sentibot", category: "training_crawler", organization: "Sentibot", baseScore: 70, respectsRobots: false, uaPatterns: ["sentibot"] },
2121
- { id: "omgili", name: "Omgili", category: "training_crawler", organization: "Webz.io", baseScore: 70, respectsRobots: false, uaPatterns: ["omgili"] },
2122
- { id: "img2dataset", name: "img2dataset", category: "training_crawler", organization: "LAION", baseScore: 75, respectsRobots: false, uaPatterns: ["img2dataset"] },
2123
- { id: "timpibot", name: "Timpibot", category: "training_crawler", organization: "Timpi", baseScore: 70, respectsRobots: true, uaPatterns: ["timpibot"] },
2124
- { id: "velenpublicwebcrawler", name: "VelenPublicWebCrawler", category: "training_crawler", organization: "Velen", baseScore: 70, respectsRobots: false, uaPatterns: ["velenpublicwebcrawler"] },
2125
- { id: "isscyberriskcrawler", name: "ISSCyberRiskCrawler", category: "training_crawler", organization: "ISS", baseScore: 65, respectsRobots: false, uaPatterns: ["isscyberriskcrawler"] },
2126
- { id: "friendlycrawler", name: "FriendlyCrawler", category: "training_crawler", organization: "Unknown", baseScore: 65, respectsRobots: true, uaPatterns: ["friendlycrawler"] },
2127
- { id: "searchgpt", name: "SearchGPT", category: "ai_search_crawler", organization: "OpenAI", baseScore: 75, respectsRobots: true, uaPatterns: ["searchgpt"] },
2128
- { id: "phind", name: "Phind", category: "ai_search_crawler", organization: "Phind", baseScore: 70, respectsRobots: true, uaPatterns: ["phind"] },
2129
- { id: "kagi", name: "Kagi", category: "ai_search_crawler", organization: "Kagi", baseScore: 65, respectsRobots: true, uaPatterns: ["kagi"] },
2130
- { id: "exa", name: "Exa", category: "ai_search_crawler", organization: "Exa AI", baseScore: 70, respectsRobots: true, uaPatterns: ["exa.ai", "exabot"] },
2131
- { id: "metaphor", name: "Metaphor", category: "ai_search_crawler", organization: "Metaphor", baseScore: 70, respectsRobots: true, uaPatterns: ["metaphor"] },
2132
- { id: "tavily", name: "Tavily", category: "ai_search_crawler", organization: "Tavily", baseScore: 70, respectsRobots: true, uaPatterns: ["tavily"] },
2133
- { id: "brave-search", name: "BraveSearch", category: "ai_search_crawler", organization: "Brave", baseScore: 65, respectsRobots: true, uaPatterns: ["bravesearch"] },
2134
- { id: "neeva", name: "NeevaBot", category: "ai_search_crawler", organization: "Neeva", baseScore: 65, respectsRobots: true, uaPatterns: ["neevabot"] },
2135
- { id: "operator", name: "Operator", category: "ai_agent", organization: "OpenAI", baseScore: 75, respectsRobots: true, uaPatterns: ["operator"] },
2136
- { id: "claude-user", name: "Claude-User", category: "ai_agent", organization: "Anthropic", baseScore: 75, respectsRobots: true, uaPatterns: ["claude-user"] },
2137
- { id: "gemini-user", name: "Gemini-User", category: "ai_agent", organization: "Google", baseScore: 75, respectsRobots: true, uaPatterns: ["gemini-user"] },
2138
- { id: "googleagent-mariner", name: "GoogleAgent-Mariner", category: "ai_agent", organization: "Google", baseScore: 75, respectsRobots: true, uaPatterns: ["googleagent-mariner", "mariner"] },
2139
- { id: "amazon-buyforme", name: "AmazonBuyForMe", category: "ai_agent", organization: "Amazon", baseScore: 70, respectsRobots: true, uaPatterns: ["amazonbuyforme", "buyforme"] },
2140
- { id: "browser-use", name: "Browser-Use", category: "ai_agent", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["browser-use"] },
2141
- { id: "stagehand", name: "Stagehand", category: "ai_agent", organization: "Browserbase", baseScore: 70, respectsRobots: false, uaPatterns: ["stagehand"] },
2142
- { id: "multion", name: "MultiOn", category: "ai_agent", organization: "MultiOn", baseScore: 70, respectsRobots: false, uaPatterns: ["multion"] },
2143
- { id: "googlebot", name: "Googlebot", category: "search_crawler", organization: "Google", baseScore: 30, respectsRobots: true, uaPatterns: ["googlebot"] },
2144
- { id: "bingbot", name: "Bingbot", category: "search_crawler", organization: "Microsoft", baseScore: 30, respectsRobots: true, uaPatterns: ["bingbot"] },
2145
- { id: "yandexbot", name: "YandexBot", category: "search_crawler", organization: "Yandex", baseScore: 35, respectsRobots: true, uaPatterns: ["yandexbot"] },
2146
- { id: "baiduspider", name: "Baiduspider", category: "search_crawler", organization: "Baidu", baseScore: 40, respectsRobots: true, uaPatterns: ["baiduspider"] },
2147
- { id: "duckduckbot", name: "DuckDuckBot", category: "search_crawler", organization: "DuckDuckGo", baseScore: 30, respectsRobots: true, uaPatterns: ["duckduckbot"] },
2148
- { id: "applebot", name: "Applebot", category: "search_crawler", organization: "Apple", baseScore: 30, respectsRobots: true, uaPatterns: ["applebot"] },
2149
- { id: "sogou", name: "Sogou Spider", category: "search_crawler", organization: "Sogou", baseScore: 40, respectsRobots: true, uaPatterns: ["sogou"] },
2150
- { id: "qwantify", name: "Qwantify", category: "search_crawler", organization: "Qwant", baseScore: 35, respectsRobots: true, uaPatterns: ["qwantify"] },
2151
- { id: "naver", name: "Naver", category: "search_crawler", organization: "Naver", baseScore: 35, respectsRobots: true, uaPatterns: ["naver", "yeti"] },
2152
- { id: "seznam", name: "SeznamBot", category: "search_crawler", organization: "Seznam", baseScore: 35, respectsRobots: true, uaPatterns: ["seznambot"] },
2153
- { id: "ecosia", name: "Ecosia", category: "search_crawler", organization: "Ecosia", baseScore: 30, respectsRobots: true, uaPatterns: ["ecosia"] },
2154
- { id: "mojeek", name: "MojeekBot", category: "search_crawler", organization: "Mojeek", baseScore: 35, respectsRobots: true, uaPatterns: ["mojeekbot"] },
2155
- { id: "yahoo-slurp", name: "Yahoo! Slurp", category: "search_crawler", organization: "Yahoo", baseScore: 30, respectsRobots: true, uaPatterns: ["slurp"] },
2156
- { id: "ahrefsbot", name: "AhrefsBot", category: "seo_crawler", organization: "Ahrefs", baseScore: 50, respectsRobots: true, uaPatterns: ["ahrefsbot", "ahrefs"] },
2157
- { id: "semrushbot", name: "SemrushBot", category: "seo_crawler", organization: "Semrush", baseScore: 50, respectsRobots: true, uaPatterns: ["semrushbot", "semrush"] },
2158
- { id: "mj12bot", name: "MJ12bot", category: "seo_crawler", organization: "Majestic", baseScore: 50, respectsRobots: true, uaPatterns: ["mj12bot"] },
2159
- { id: "dotbot", name: "DotBot", category: "seo_crawler", organization: "Moz", baseScore: 50, respectsRobots: true, uaPatterns: ["dotbot"] },
2160
- { id: "rogerbot", name: "Rogerbot", category: "seo_crawler", organization: "Moz", baseScore: 50, respectsRobots: true, uaPatterns: ["rogerbot"] },
2161
- { id: "screaming-frog", name: "Screaming Frog", category: "seo_crawler", organization: "Screaming Frog", baseScore: 55, respectsRobots: true, uaPatterns: ["screaming frog"] },
2162
- { id: "sitebulb", name: "Sitebulb", category: "seo_crawler", organization: "Sitebulb", baseScore: 55, respectsRobots: true, uaPatterns: ["sitebulb"] },
2163
- { id: "deepcrawl", name: "DeepCrawl", category: "seo_crawler", organization: "Lumar", baseScore: 50, respectsRobots: true, uaPatterns: ["deepcrawl"] },
2164
- { id: "oncrawl", name: "OnCrawl", category: "seo_crawler", organization: "OnCrawl", baseScore: 50, respectsRobots: true, uaPatterns: ["oncrawl"] },
2165
- { id: "botify", name: "Botify", category: "seo_crawler", organization: "Botify", baseScore: 50, respectsRobots: true, uaPatterns: ["botify"] },
2166
- { id: "contentking", name: "ContentKing", category: "seo_crawler", organization: "ContentKing", baseScore: 50, respectsRobots: true, uaPatterns: ["contentking"] },
2167
- { id: "sistrix", name: "SISTRIX", category: "seo_crawler", organization: "SISTRIX", baseScore: 50, respectsRobots: true, uaPatterns: ["sistrix"] },
2168
- { id: "serpstat", name: "Serpstat", category: "seo_crawler", organization: "Serpstat", baseScore: 50, respectsRobots: true, uaPatterns: ["serpstat"] },
2169
- { id: "spyfu", name: "SpyFu", category: "seo_crawler", organization: "SpyFu", baseScore: 50, respectsRobots: true, uaPatterns: ["spyfu"] },
2170
- { id: "nessus", name: "Nessus", category: "security_scanner", organization: "Tenable", baseScore: 70, respectsRobots: false, uaPatterns: ["nessus"] },
2171
- { id: "qualys", name: "Qualys", category: "security_scanner", organization: "Qualys", baseScore: 70, respectsRobots: false, uaPatterns: ["qualys"] },
2172
- { id: "shodan", name: "Shodan", category: "security_scanner", organization: "Shodan", baseScore: 75, respectsRobots: false, uaPatterns: ["shodan"] },
2173
- { id: "censys", name: "Censys", category: "security_scanner", organization: "Censys", baseScore: 75, respectsRobots: false, uaPatterns: ["censys"] },
2174
- { id: "nmap", name: "Nmap", category: "security_scanner", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["nmap"] },
2175
- { id: "zap", name: "OWASP ZAP", category: "security_scanner", organization: "OWASP", baseScore: 70, respectsRobots: false, uaPatterns: ["zap/"] },
2176
- { id: "burp", name: "Burp Suite", category: "security_scanner", organization: "PortSwigger", baseScore: 70, respectsRobots: false, uaPatterns: ["burp"] },
2177
- { id: "nikto", name: "Nikto", category: "security_scanner", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["nikto"] },
2178
- { id: "nuclei", name: "Nuclei", category: "security_scanner", organization: "ProjectDiscovery", baseScore: 70, respectsRobots: false, uaPatterns: ["nuclei"] },
2179
- { id: "acunetix", name: "Acunetix", category: "security_scanner", organization: "Invicti", baseScore: 70, respectsRobots: false, uaPatterns: ["acunetix"] },
2180
- { id: "netsparker", name: "Netsparker", category: "security_scanner", organization: "Invicti", baseScore: 70, respectsRobots: false, uaPatterns: ["netsparker"] },
2181
- { id: "detectify", name: "Detectify", category: "security_scanner", organization: "Detectify", baseScore: 65, respectsRobots: false, uaPatterns: ["detectify"] },
2182
- { id: "intruder", name: "Intruder", category: "security_scanner", organization: "Intruder", baseScore: 65, respectsRobots: false, uaPatterns: ["intruder"] },
2183
- { id: "python-requests", name: "Python-Requests", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["python-requests"] },
2184
- { id: "python-urllib", name: "Python-urllib", category: "generic_scraper", organization: "Python", baseScore: 55, respectsRobots: false, uaPatterns: ["python-urllib"] },
2185
- { id: "python", name: "Python", category: "generic_scraper", organization: "Python", baseScore: 50, respectsRobots: false, uaPatterns: ["python/"] },
2186
- { id: "scrapy", name: "Scrapy", category: "generic_scraper", organization: "Scrapy", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapy"] },
2187
- { id: "httpx", name: "HTTPX", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["httpx"] },
2188
- { id: "aiohttp", name: "aiohttp", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["aiohttp"] },
2189
- { id: "beautifulsoup", name: "BeautifulSoup", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["beautifulsoup"] },
2190
- { id: "node-fetch", name: "node-fetch", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["node-fetch"] },
2191
- { id: "axios", name: "Axios", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["axios/"] },
2192
- { id: "got", name: "Got", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["got/"] },
2193
- { id: "undici", name: "Undici", category: "generic_scraper", organization: "Node.js", baseScore: 55, respectsRobots: false, uaPatterns: ["undici"] },
2194
- { id: "go-http-client", name: "Go-HTTP-Client", category: "generic_scraper", organization: "Go", baseScore: 55, respectsRobots: false, uaPatterns: ["go-http-client"] },
2195
- { id: "colly", name: "Colly", category: "generic_scraper", organization: "Open Source", baseScore: 65, respectsRobots: true, uaPatterns: ["colly"] },
2196
- { id: "java", name: "Java", category: "generic_scraper", organization: "Oracle", baseScore: 50, respectsRobots: false, uaPatterns: ["java/"] },
2197
- { id: "okhttp", name: "OkHttp", category: "generic_scraper", organization: "Square", baseScore: 55, respectsRobots: false, uaPatterns: ["okhttp"] },
2198
- { id: "apache-httpclient", name: "Apache-HttpClient", category: "generic_scraper", organization: "Apache", baseScore: 55, respectsRobots: false, uaPatterns: ["apache-httpclient"] },
2199
- { id: "jsoup", name: "Jsoup", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["jsoup"] },
2200
- { id: "guzzlehttp", name: "GuzzleHttp", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["guzzlehttp"] },
2201
- { id: "php", name: "PHP", category: "generic_scraper", organization: "PHP", baseScore: 50, respectsRobots: false, uaPatterns: ["php/"] },
2202
- { id: "ruby", name: "Ruby", category: "generic_scraper", organization: "Ruby", baseScore: 50, respectsRobots: false, uaPatterns: ["ruby"] },
2203
- { id: "faraday", name: "Faraday", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["faraday"] },
2204
- { id: "mechanize", name: "Mechanize", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["mechanize"] },
2205
- { id: "headlesschrome", name: "HeadlessChrome", category: "headless_browser", organization: "Google", baseScore: 70, respectsRobots: false, uaPatterns: ["headlesschrome"] },
2206
- { id: "puppeteer", name: "Puppeteer", category: "headless_browser", organization: "Google", baseScore: 70, respectsRobots: false, uaPatterns: ["puppeteer"] },
2207
- { id: "playwright", name: "Playwright", category: "headless_browser", organization: "Microsoft", baseScore: 70, respectsRobots: false, uaPatterns: ["playwright"] },
2208
- { id: "selenium", name: "Selenium", category: "headless_browser", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["selenium"] },
2209
- { id: "phantomjs", name: "PhantomJS", category: "headless_browser", organization: "Open Source", baseScore: 75, respectsRobots: false, uaPatterns: ["phantomjs"] },
2210
- { id: "splash", name: "Splash", category: "headless_browser", organization: "Scrapinghub", baseScore: 70, respectsRobots: false, uaPatterns: ["splash"] },
2211
- { id: "browserless", name: "Browserless", category: "headless_browser", organization: "Browserless", baseScore: 65, respectsRobots: false, uaPatterns: ["browserless"] },
2212
- { id: "browserbase", name: "Browserbase", category: "headless_browser", organization: "Browserbase", baseScore: 65, respectsRobots: false, uaPatterns: ["browserbase"] },
2213
- { id: "ia-archiver", name: "Internet Archive", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["ia_archiver"] },
2214
- { id: "archive-org-bot", name: "Archive.org", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["archive.org_bot"] },
2215
- { id: "wayback", name: "Wayback Machine", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["wayback"] },
2216
- { id: "heritrix", name: "Heritrix", category: "archiver", organization: "Internet Archive", baseScore: 30, respectsRobots: true, uaPatterns: ["heritrix"] },
2217
- { id: "brozzler", name: "Brozzler", category: "archiver", organization: "Internet Archive", baseScore: 30, respectsRobots: true, uaPatterns: ["brozzler"] },
2218
- { id: "facebookexternalhit", name: "Facebook", category: "fetcher", organization: "Meta", baseScore: 25, respectsRobots: true, uaPatterns: ["facebookexternalhit"] },
2219
- { id: "twitterbot", name: "Twitterbot", category: "fetcher", organization: "X Corp", baseScore: 25, respectsRobots: true, uaPatterns: ["twitterbot"] },
2220
- { id: "linkedinbot", name: "LinkedInBot", category: "fetcher", organization: "LinkedIn", baseScore: 25, respectsRobots: true, uaPatterns: ["linkedinbot"] },
2221
- { id: "slackbot", name: "Slackbot", category: "fetcher", organization: "Slack", baseScore: 25, respectsRobots: true, uaPatterns: ["slackbot"] },
2222
- { id: "telegrambot", name: "TelegramBot", category: "fetcher", organization: "Telegram", baseScore: 25, respectsRobots: true, uaPatterns: ["telegrambot"] },
2223
- { id: "whatsapp", name: "WhatsApp", category: "fetcher", organization: "Meta", baseScore: 25, respectsRobots: true, uaPatterns: ["whatsapp"] },
2224
- { id: "discordbot", name: "Discordbot", category: "fetcher", organization: "Discord", baseScore: 25, respectsRobots: true, uaPatterns: ["discordbot"] },
2225
- { id: "pinterestbot", name: "Pinterest", category: "fetcher", organization: "Pinterest", baseScore: 30, respectsRobots: true, uaPatterns: ["pinterest"] },
2226
- { id: "tumblr", name: "Tumblr", category: "fetcher", organization: "Automattic", baseScore: 30, respectsRobots: true, uaPatterns: ["tumblr"] },
2227
- { id: "reddit", name: "Reddit", category: "fetcher", organization: "Reddit", baseScore: 30, respectsRobots: true, uaPatterns: ["reddit"] },
2228
- { id: "embedly", name: "Embedly", category: "fetcher", organization: "Medium", baseScore: 30, respectsRobots: true, uaPatterns: ["embedly"] },
2229
- { id: "iframely", name: "Iframely", category: "fetcher", organization: "Iframely", baseScore: 30, respectsRobots: true, uaPatterns: ["iframely"] },
2230
- { id: "curl", name: "cURL", category: "fetcher", organization: "Open Source", baseScore: 45, respectsRobots: false, uaPatterns: ["curl/"] },
2231
- { id: "wget", name: "Wget", category: "fetcher", organization: "GNU", baseScore: 45, respectsRobots: false, uaPatterns: ["wget/"] },
2232
- { id: "libwww-perl", name: "libwww-perl", category: "fetcher", organization: "Perl", baseScore: 50, respectsRobots: false, uaPatterns: ["libwww-perl"] },
2233
- { id: "lwp", name: "LWP", category: "fetcher", organization: "Perl", baseScore: 50, respectsRobots: false, uaPatterns: ["lwp-"] },
2234
- { id: "httrack", name: "HTTrack", category: "fetcher", organization: "Open Source", baseScore: 60, respectsRobots: true, uaPatterns: ["httrack"] },
2235
- { id: "webdecoybot", name: "WebDecoyBot", category: "monitoring", organization: "WebDecoy", baseScore: 5, respectsRobots: true, uaPatterns: ["webdecoybot"] },
2236
- { id: "uptimerobot", name: "UptimeRobot", category: "monitoring", organization: "UptimeRobot", baseScore: 20, respectsRobots: true, uaPatterns: ["uptimerobot"] },
2237
- { id: "pingdom", name: "Pingdom", category: "monitoring", organization: "SolarWinds", baseScore: 20, respectsRobots: true, uaPatterns: ["pingdom"] },
2238
- { id: "statuscake", name: "StatusCake", category: "monitoring", organization: "StatusCake", baseScore: 20, respectsRobots: true, uaPatterns: ["statuscake"] },
2239
- { id: "better-uptime", name: "Better Uptime", category: "monitoring", organization: "Better Stack", baseScore: 20, respectsRobots: true, uaPatterns: ["betteruptime"] },
2240
- { id: "datadog-synthetics", name: "Datadog Synthetics", category: "monitoring", organization: "Datadog", baseScore: 25, respectsRobots: true, uaPatterns: ["datadog"] },
2241
- { id: "newrelic", name: "New Relic", category: "monitoring", organization: "New Relic", baseScore: 25, respectsRobots: true, uaPatterns: ["newrelic"] },
2242
- { id: "site24x7", name: "Site24x7", category: "monitoring", organization: "Zoho", baseScore: 20, respectsRobots: true, uaPatterns: ["site24x7"] },
2243
- { id: "freshping", name: "Freshping", category: "monitoring", organization: "Freshworks", baseScore: 20, respectsRobots: true, uaPatterns: ["freshping"] },
2244
- { id: "hetrixtools", name: "HetrixTools", category: "monitoring", organization: "HetrixTools", baseScore: 20, respectsRobots: true, uaPatterns: ["hetrixtools"] },
2245
- { id: "nodeping", name: "NodePing", category: "monitoring", organization: "NodePing", baseScore: 20, respectsRobots: true, uaPatterns: ["nodeping"] },
2246
- { id: "feedly", name: "Feedly", category: "feed_reader", organization: "Feedly", baseScore: 25, respectsRobots: true, uaPatterns: ["feedly"] },
2247
- { id: "newsblur", name: "NewsBlur", category: "feed_reader", organization: "NewsBlur", baseScore: 25, respectsRobots: true, uaPatterns: ["newsblur"] },
2248
- { id: "inoreader", name: "Inoreader", category: "feed_reader", organization: "Inoreader", baseScore: 25, respectsRobots: true, uaPatterns: ["inoreader"] },
2249
- { id: "theoldreader", name: "The Old Reader", category: "feed_reader", organization: "The Old Reader", baseScore: 25, respectsRobots: true, uaPatterns: ["theoldreader"] },
2250
- { id: "feedbin", name: "Feedbin", category: "feed_reader", organization: "Feedbin", baseScore: 25, respectsRobots: true, uaPatterns: ["feedbin"] },
2251
- { id: "miniflux", name: "Miniflux", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["miniflux"] },
2252
- { id: "freshrss", name: "FreshRSS", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["freshrss"] },
2253
- { id: "commafeed", name: "CommaFeed", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["commafeed"] },
2254
- { id: "diffbot", name: "Diffbot", category: "commercial_scraper", organization: "Diffbot", baseScore: 70, respectsRobots: true, uaPatterns: ["diffbot"] },
2255
- { id: "import-io", name: "Import.io", category: "commercial_scraper", organization: "Import.io", baseScore: 65, respectsRobots: true, uaPatterns: ["import.io"] },
2256
- { id: "bright-data", name: "Bright Data", category: "commercial_scraper", organization: "Bright Data", baseScore: 70, respectsRobots: false, uaPatterns: ["brightdata", "luminati"] },
2257
- { id: "oxylabs", name: "Oxylabs", category: "commercial_scraper", organization: "Oxylabs", baseScore: 70, respectsRobots: false, uaPatterns: ["oxylabs"] },
2258
- { id: "scrapingbee", name: "ScrapingBee", category: "commercial_scraper", organization: "ScrapingBee", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapingbee"] },
2259
- { id: "scrapingant", name: "ScrapingAnt", category: "commercial_scraper", organization: "ScrapingAnt", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapingant"] },
2260
- { id: "zyte", name: "Zyte", category: "commercial_scraper", organization: "Zyte", baseScore: 65, respectsRobots: true, uaPatterns: ["zyte", "scrapinghub"] },
2261
- { id: "apify", name: "Apify", category: "commercial_scraper", organization: "Apify", baseScore: 65, respectsRobots: true, uaPatterns: ["apify"] },
2262
- { id: "crawlbase", name: "Crawlbase", category: "commercial_scraper", organization: "Crawlbase", baseScore: 65, respectsRobots: true, uaPatterns: ["crawlbase"] },
2263
- { id: "webscrapingapi", name: "WebScrapingAPI", category: "commercial_scraper", organization: "WebScrapingAPI", baseScore: 65, respectsRobots: true, uaPatterns: ["webscrapingapi"] },
2264
- { id: "gemini-deep-research", name: "Gemini-Deep-Research", category: "ai_assistant", organization: "Google", baseScore: 65, respectsRobots: true, uaPatterns: ["gemini-deep-research"] },
2265
- { id: "copilot", name: "Microsoft Copilot", category: "ai_assistant", organization: "Microsoft", baseScore: 65, respectsRobots: true, uaPatterns: ["copilot"] },
2266
- { id: "cortana", name: "Cortana", category: "ai_assistant", organization: "Microsoft", baseScore: 60, respectsRobots: true, uaPatterns: ["cortana"] },
2267
- { id: "siri", name: "Siri", category: "ai_assistant", organization: "Apple", baseScore: 60, respectsRobots: true, uaPatterns: ["siri"] }
2268
- ];
2441
+ // src/agent/signature.ts
2442
+ var TAG = "web-bot-auth";
2443
+ var encoder3 = new TextEncoder();
2444
+ async function verifyWebBotAuth(req, resolveKey, toleranceSec) {
2445
+ const sigInput = req.headers.get("signature-input");
2446
+ const sigHeader = req.headers.get("signature");
2447
+ if (!sigInput && !sigHeader) return { outcome: "none" };
2448
+ if (!sigInput || !sigHeader) return { outcome: "claimed", reason: "incomplete-signature" };
2449
+ let members;
2450
+ let sigs;
2451
+ try {
2452
+ members = parseSignatureInput(sigInput);
2453
+ sigs = parseSignatureBytes(sigHeader);
2454
+ } catch {
2455
+ return { outcome: "claimed", reason: "malformed-signature" };
2456
+ }
2457
+ const now = Date.now() / 1e3;
2458
+ let best = { outcome: "none" };
2459
+ for (const m of members) {
2460
+ if (m.params.get("tag") !== TAG) continue;
2461
+ if (best.outcome === "none") best = { outcome: "claimed", reason: "unverifiable" };
2462
+ const sig = sigs.get(m.label);
2463
+ if (!sig) continue;
2464
+ const keyid = m.params.get("keyid");
2465
+ if (typeof keyid !== "string") continue;
2466
+ if (!m.components.some((c) => c.name === "@authority" || c.name === "@target-uri")) continue;
2467
+ const key = await resolveKey(keyid);
2468
+ if (!key) {
2469
+ best = higher(best, { outcome: "claimed", keyId: keyid, reason: "unknown-key" });
2470
+ continue;
2471
+ }
2472
+ const created = numeric(m.params.get("created"));
2473
+ const expires = numeric(m.params.get("expires"));
2474
+ if (expires !== void 0 && now > expires + toleranceSec) {
2475
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "expired" });
2476
+ continue;
2477
+ }
2478
+ if (created !== void 0 && now + toleranceSec < created) {
2479
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "not-yet-valid" });
2480
+ continue;
2481
+ }
2482
+ if (key.exp !== void 0 && now > key.exp + toleranceSec) {
2483
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-expired" });
2484
+ continue;
2485
+ }
2486
+ if (key.nbf !== void 0 && now + toleranceSec < key.nbf) {
2487
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-not-yet-valid" });
2488
+ continue;
2489
+ }
2490
+ let base;
2491
+ try {
2492
+ base = buildSignatureBase(req, m);
2493
+ } catch {
2494
+ best = higher(best, { outcome: "claimed", keyId: keyid, reason: "uncoverable-component" });
2495
+ continue;
2496
+ }
2497
+ let ok = false;
2498
+ try {
2499
+ ok = await crypto.subtle.verify(
2500
+ key.verifyParams,
2501
+ key.cryptoKey,
2502
+ sig,
2503
+ encoder3.encode(base)
2504
+ );
2505
+ } catch {
2506
+ ok = false;
2507
+ }
2508
+ if (ok) {
2509
+ return { outcome: "verified", keyId: keyid, key };
2510
+ }
2511
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "bad-signature" });
2512
+ }
2513
+ return best;
2514
+ }
2515
+ var PRECEDENCE = { none: 0, claimed: 1, impersonation: 2, verified: 3 };
2516
+ function higher(a, b) {
2517
+ return PRECEDENCE[b.outcome] >= PRECEDENCE[a.outcome] ? b : a;
2518
+ }
2519
+ function numeric(v) {
2520
+ return typeof v === "number" ? v : void 0;
2521
+ }
2522
+ function buildSignatureBase(req, m) {
2523
+ const lines = [];
2524
+ for (const c of m.components) {
2525
+ lines.push(`${serializeComponentId(c)}: ${componentValue(req, c)}`);
2526
+ }
2527
+ lines.push(`"@signature-params": ${m.raw.trim()}`);
2528
+ return lines.join("\n");
2529
+ }
2530
+ function serializeComponentId(c) {
2531
+ const base = `"${c.name.toLowerCase()}"`;
2532
+ return c.keyParam !== void 0 ? `${base};key="${c.keyParam}"` : base;
2533
+ }
2534
+ function componentValue(req, c) {
2535
+ const name = c.name.toLowerCase();
2536
+ switch (name) {
2537
+ case "@method":
2538
+ return req.method.toUpperCase();
2539
+ case "@authority":
2540
+ return canonicalAuthority(req.url);
2541
+ case "@scheme":
2542
+ return req.url.protocol.replace(/:$/, "").toLowerCase();
2543
+ case "@target-uri":
2544
+ return `${req.url.protocol}//${canonicalAuthority(req.url)}${req.url.pathname}${req.url.search}`;
2545
+ case "@path":
2546
+ return req.url.pathname;
2547
+ case "@query":
2548
+ return req.url.search === "" ? "?" : req.url.search;
2549
+ case "signature-agent": {
2550
+ const header = req.headers.get("signature-agent");
2551
+ if (header === null) throw new Error("signature-agent covered but absent");
2552
+ if (c.keyParam !== void 0) return dictMemberValue(header, c.keyParam);
2553
+ return header.trim().replace(/\s+/g, " ");
2554
+ }
2555
+ default: {
2556
+ if (name.startsWith("@")) throw new Error(`unsupported derived component ${name}`);
2557
+ const header = req.headers.get(name);
2558
+ if (header === null) throw new Error(`covered header ${name} absent`);
2559
+ return header.trim().replace(/\s+/g, " ");
2560
+ }
2561
+ }
2562
+ }
2563
+ function canonicalAuthority(url) {
2564
+ const host = url.hostname.toLowerCase();
2565
+ const port = url.port;
2566
+ if (!port) return host;
2567
+ if (url.protocol === "https:" && port === "443" || url.protocol === "http:" && port === "80") {
2568
+ return host;
2569
+ }
2570
+ return `${host}:${port}`;
2571
+ }
2572
+ function dictMemberValue(header, key) {
2573
+ const dict = parseDictionary(header);
2574
+ const found = dict.find((d) => d.key === key);
2575
+ if (!found) throw new Error(`signature-agent has no member ${key}`);
2576
+ return found.raw;
2577
+ }
2578
+ function parseSignatureInput(value) {
2579
+ return parseDictionary(value).map((d) => {
2580
+ if (!d.isList) throw new Error(`Signature-Input member ${d.key} is not an inner list`);
2581
+ const components = d.items.map((it) => {
2582
+ if (typeof it.value !== "string") throw new Error("component identifier is not a string");
2583
+ const keyParam = it.params.get("key");
2584
+ return { name: it.value, keyParam: typeof keyParam === "string" ? keyParam : void 0 };
2585
+ });
2586
+ return { label: d.key, components, params: d.params, raw: d.raw };
2587
+ });
2588
+ }
2589
+ function parseSignatureBytes(value) {
2590
+ const out = /* @__PURE__ */ new Map();
2591
+ for (const d of parseDictionary(value)) {
2592
+ if (d.isList || d.items.length !== 1 || !d.items[0].bytes) {
2593
+ throw new Error(`Signature member ${d.key} is not a byte sequence`);
2594
+ }
2595
+ out.set(d.key, d.items[0].bytes);
2596
+ }
2597
+ return out;
2598
+ }
2269
2599
 
2270
- // src/bots/index.ts
2271
- var AI_CATEGORIES = /* @__PURE__ */ new Set([
2272
- "training_crawler",
2273
- "ai_search_crawler",
2274
- "ai_agent",
2275
- "ai_assistant"
2276
- ]);
2277
- var UNKNOWN = Object.freeze({
2278
- known: false,
2279
- category: "none",
2280
- score: 0,
2281
- isAI: false
2282
- });
2283
- var MAX_CACHE = 1e3;
2284
- var cache = /* @__PURE__ */ new Map();
2285
- function matchUserAgent(userAgent) {
2286
- if (!userAgent) return void 0;
2287
- const cached = cache.get(userAgent);
2288
- if (cached !== void 0) return cached ?? void 0;
2289
- const ua = userAgent.toLowerCase();
2290
- let found = null;
2291
- for (const agent of BOT_REGISTRY) {
2292
- for (const pattern of agent.uaPatterns) {
2293
- if (ua.includes(pattern)) {
2294
- found = agent;
2295
- break;
2296
- }
2600
+ // src/agent/verifier.ts
2601
+ var DEFAULT_TTL_MS = 6 * 60 * 60 * 1e3;
2602
+ var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
2603
+ var DEFAULT_TOLERANCE_SEC = 300;
2604
+ var AgentVerifier = class {
2605
+ constructor(options = {}) {
2606
+ this.toleranceSec = options.toleranceSec ?? DEFAULT_TOLERANCE_SEC;
2607
+ this.cache = new DirectoryCache({
2608
+ directories: options.directories ?? DEFAULT_SIGNED_AGENT_DIRECTORIES,
2609
+ cacheTtlMs: options.cacheTtlMs ?? DEFAULT_TTL_MS,
2610
+ fetchTimeoutMs: options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,
2611
+ debug: options.debug ?? false,
2612
+ fetchImpl: options.fetchImpl ?? fetch
2613
+ });
2614
+ }
2615
+ /** Pre-fetch trusted directories so the first request verifies warm. */
2616
+ warmup() {
2617
+ this.cache.prime();
2618
+ }
2619
+ /** Verify a request's Web Bot Auth signature (if any) locally. */
2620
+ async verify(request) {
2621
+ let req;
2622
+ try {
2623
+ req = normalize(request);
2624
+ } catch {
2625
+ return { status: "none" };
2297
2626
  }
2298
- if (found) break;
2627
+ const result = await verifyWebBotAuth(req, this.cache.resolveKey, this.toleranceSec);
2628
+ switch (result.outcome) {
2629
+ case "verified":
2630
+ return {
2631
+ status: "verified",
2632
+ method: "signature",
2633
+ keyId: result.keyId,
2634
+ agentName: result.key?.name,
2635
+ category: result.key?.category,
2636
+ algorithm: result.key?.algorithm
2637
+ };
2638
+ case "impersonation":
2639
+ return {
2640
+ status: "impersonation",
2641
+ method: "signature",
2642
+ keyId: result.keyId,
2643
+ agentName: result.key?.name,
2644
+ category: result.key?.category,
2645
+ reason: result.reason
2646
+ };
2647
+ case "claimed":
2648
+ return { status: "claimed", keyId: result.keyId, reason: result.reason };
2649
+ default:
2650
+ return { status: "none" };
2651
+ }
2652
+ }
2653
+ /** Cached-key count (diagnostics/tests). */
2654
+ get cachedKeyCount() {
2655
+ return this.cache.size;
2656
+ }
2657
+ };
2658
+ function createAgentVerifier(options = {}) {
2659
+ return new AgentVerifier(options);
2660
+ }
2661
+ function normalize(input) {
2662
+ if (isRequest(input)) {
2663
+ return { method: input.method, url: new URL(input.url), headers: input.headers };
2299
2664
  }
2300
- if (cache.size >= MAX_CACHE) cache.clear();
2301
- cache.set(userAgent, found);
2302
- return found ?? void 0;
2665
+ const headers = input.headers instanceof Headers ? input.headers : toHeaders(input.headers);
2666
+ return { method: input.method, url: new URL(input.url), headers };
2303
2667
  }
2304
- function classifyUserAgent(userAgent) {
2305
- const agent = matchUserAgent(userAgent);
2306
- if (!agent) return UNKNOWN;
2668
+ function isRequest(input) {
2669
+ return typeof Request !== "undefined" && input instanceof Request && typeof input.url === "string";
2670
+ }
2671
+ function toHeaders(record) {
2672
+ const h = new Headers();
2673
+ for (const [k, v] of Object.entries(record)) {
2674
+ if (v !== void 0 && v !== null) h.set(k, String(v));
2675
+ }
2676
+ return h;
2677
+ }
2678
+
2679
+ // src/edge.ts
2680
+ var EDGE_CLEARANCE_HEADER = "x-wd-clearance";
2681
+ var EDGE_CLASS_HEADER = "x-wd-class";
2682
+ var EDGE_CLASSES = ["verified", "crawler", "script", "browser"];
2683
+ function absent() {
2307
2684
  return {
2308
- known: true,
2309
- id: agent.id,
2310
- name: agent.name,
2311
- category: agent.category,
2312
- organization: agent.organization,
2313
- score: agent.baseScore,
2314
- respectsRobots: agent.respectsRobots,
2315
- isAI: AI_CATEGORIES.has(agent.category)
2685
+ present: false,
2686
+ isVerified: false,
2687
+ isCrawler: false,
2688
+ isScript: false,
2689
+ isBrowser: false,
2690
+ isUnattestedNonBrowser: false
2691
+ };
2692
+ }
2693
+ function normaliseClass(raw) {
2694
+ if (!raw) return void 0;
2695
+ const v = raw.trim().toLowerCase();
2696
+ return EDGE_CLASSES.includes(v) ? v : void 0;
2697
+ }
2698
+ function readEdgeVerdict(headers) {
2699
+ if (!headers) return absent();
2700
+ let clearanceRaw;
2701
+ let classRaw;
2702
+ for (const key of Object.keys(headers)) {
2703
+ const k = key.toLowerCase();
2704
+ if (k === EDGE_CLEARANCE_HEADER) clearanceRaw = headers[key];
2705
+ else if (k === EDGE_CLASS_HEADER) classRaw = headers[key];
2706
+ }
2707
+ const clearance = clearanceRaw?.trim() || void 0;
2708
+ const cls = normaliseClass(classRaw);
2709
+ if (!clearance && !cls) return absent();
2710
+ return {
2711
+ present: true,
2712
+ clearance,
2713
+ class: cls,
2714
+ isVerified: cls === "verified",
2715
+ isCrawler: cls === "crawler",
2716
+ isScript: cls === "script",
2717
+ isBrowser: cls === "browser",
2718
+ isUnattestedNonBrowser: cls === "script" || cls === "crawler"
2719
+ };
2720
+ }
2721
+
2722
+ // src/logger.ts
2723
+ var PREFIX = "[WebDecoy]";
2724
+ function consoleLogger(debug) {
2725
+ const emit = (fn, gated) => (message, fields) => {
2726
+ if (gated && !debug) return;
2727
+ if (fields) fn(`${PREFIX} ${message}`, fields);
2728
+ else fn(`${PREFIX} ${message}`);
2729
+ };
2730
+ return {
2731
+ debug: emit(console.log, true),
2732
+ info: emit(console.log, true),
2733
+ // Warnings and errors are not debug output. A violation that failed to
2734
+ // report, or a key that was rejected, is something the operator needs to
2735
+ // see whether or not they opted into diagnostics.
2736
+ warn: emit(console.warn, false),
2737
+ error: emit(console.error, false)
2738
+ };
2739
+ }
2740
+ var silentLogger = {
2741
+ debug() {
2742
+ },
2743
+ info() {
2744
+ },
2745
+ warn() {
2746
+ },
2747
+ error() {
2748
+ }
2749
+ };
2750
+ function fromPino(pino) {
2751
+ return {
2752
+ debug: (m, f) => pino.debug(f ?? {}, m),
2753
+ info: (m, f) => pino.info(f ?? {}, m),
2754
+ warn: (m, f) => pino.warn(f ?? {}, m),
2755
+ error: (m, f) => pino.error(f ?? {}, m)
2316
2756
  };
2317
2757
  }
2758
+ function resolveLogger(provided, debug) {
2759
+ return provided ?? consoleLogger(debug);
2760
+ }
2761
+
2762
+ // src/decision.ts
2763
+ function newDecisionId() {
2764
+ return `dec_${randomHex(12)}`;
2765
+ }
2766
+ var Decision = class _Decision {
2767
+ constructor(init) {
2768
+ this.id = init.id ?? newDecisionId();
2769
+ this.conclusion = init.conclusion;
2770
+ this.results = Object.freeze([...init.results ?? []]);
2771
+ this.reason = init.reason;
2772
+ this.detection = init.detection;
2773
+ this.error = init.error;
2774
+ this.ruleResult = init.ruleResult;
2775
+ this.agent = init.agent;
2776
+ this.edge = init.edge;
2777
+ this.key = init.key;
2778
+ this.ttl = init.ttl ?? 0;
2779
+ }
2780
+ get allowed() {
2781
+ return this.conclusion === "ALLOW" || this.conclusion === "ERROR";
2782
+ }
2783
+ isAllowed() {
2784
+ return this.conclusion === "ALLOW";
2785
+ }
2786
+ isDenied() {
2787
+ return this.conclusion === "DENY";
2788
+ }
2789
+ isChallenged() {
2790
+ return this.conclusion === "CHALLENGE";
2791
+ }
2792
+ isErrored() {
2793
+ return this.conclusion === "ERROR";
2794
+ }
2795
+ deniedBy(rule) {
2796
+ return this.results.some(
2797
+ (r) => r.rule === rule && r.state === "RUN" && r.conclusion === "DENY"
2798
+ );
2799
+ }
2800
+ /** A copy of this decision with the edge verdict attached. */
2801
+ withEdge(edge) {
2802
+ return new _Decision({ ...this.init(), edge });
2803
+ }
2804
+ /** A copy marked as served from cache, with every rule re-stated as CACHED. */
2805
+ asCached() {
2806
+ return new _Decision({
2807
+ ...this.init(),
2808
+ results: this.results.map((r) => ({ ...r, state: "CACHED" }))
2809
+ });
2810
+ }
2811
+ init() {
2812
+ return {
2813
+ id: this.id,
2814
+ conclusion: this.conclusion,
2815
+ results: [...this.results],
2816
+ reason: this.reason,
2817
+ detection: this.detection,
2818
+ error: this.error,
2819
+ ruleResult: this.ruleResult,
2820
+ agent: this.agent,
2821
+ edge: this.edge,
2822
+ key: this.key,
2823
+ ttl: this.ttl
2824
+ };
2825
+ }
2826
+ };
2827
+
2828
+ // src/characteristics.ts
2829
+ var DEFAULT_CHARACTERISTICS = ["ip"];
2830
+ function resolveOne(context, c) {
2831
+ if (typeof c === "function") {
2832
+ try {
2833
+ return c(context) || void 0;
2834
+ } catch {
2835
+ return void 0;
2836
+ }
2837
+ }
2838
+ switch (c) {
2839
+ case "ip":
2840
+ return context.ip || void 0;
2841
+ case "path":
2842
+ return context.path || void 0;
2843
+ case "method":
2844
+ return context.method || void 0;
2845
+ case "userAgent":
2846
+ return context.userAgent || void 0;
2847
+ }
2848
+ }
2849
+ function deriveKey(context, characteristics = DEFAULT_CHARACTERISTICS) {
2850
+ if (characteristics.length === 0) return context.ip;
2851
+ const parts = [];
2852
+ for (const c of characteristics) {
2853
+ const value = resolveOne(context, c);
2854
+ if (value === void 0) return context.ip;
2855
+ parts.push(value);
2856
+ }
2857
+ return parts.join("|");
2858
+ }
2859
+
2860
+ // src/decision-cache.ts
2861
+ var DecisionCache = class {
2862
+ constructor(options = {}) {
2863
+ // Insertion-ordered, which is what makes the eviction below oldest-first.
2864
+ this.entries = /* @__PURE__ */ new Map();
2865
+ this.ttl = options.ttl ?? 6e4;
2866
+ this.max = options.max ?? 1e4;
2867
+ }
2868
+ /** A cached decision for this key, or undefined. Expired entries are dropped. */
2869
+ get(key) {
2870
+ const entry = this.entries.get(key);
2871
+ if (!entry) return void 0;
2872
+ if (entry.expiresAt <= Date.now()) {
2873
+ this.entries.delete(key);
2874
+ return void 0;
2875
+ }
2876
+ return entry.decision;
2877
+ }
2878
+ /**
2879
+ * Remember a decision, if it is one of the kinds worth remembering.
2880
+ * Returns whether it was stored, so a caller can assert on the policy rather
2881
+ * than infer it.
2882
+ */
2883
+ set(key, decision) {
2884
+ if (decision.conclusion !== "DENY" && decision.conclusion !== "CHALLENGE") return false;
2885
+ if (this.ttl <= 0) return false;
2886
+ this.entries.delete(key);
2887
+ this.entries.set(key, { decision, expiresAt: Date.now() + this.ttl });
2888
+ while (this.entries.size > this.max) {
2889
+ const oldest = this.entries.keys().next();
2890
+ if (oldest.done) break;
2891
+ this.entries.delete(oldest.value);
2892
+ }
2893
+ return true;
2894
+ }
2895
+ clear() {
2896
+ this.entries.clear();
2897
+ }
2898
+ get size() {
2899
+ return this.entries.size;
2900
+ }
2901
+ /** How long entries live, in milliseconds. Reported on the decision. */
2902
+ get lifetime() {
2903
+ return this.ttl;
2904
+ }
2905
+ };
2318
2906
 
2319
2907
  // src/test-trigger.ts
2320
2908
  var TEST_TRIGGER_UA_PREFIX = "WebDecoy-Test/";
@@ -2331,6 +2919,7 @@ var WebDecoy = class {
2331
2919
  this.ipEnrichmentClient = null;
2332
2920
  this._hasFilterRules = false;
2333
2921
  this._hasAgentRules = false;
2922
+ this._preparingRules = [];
2334
2923
  this.agentVerifier = null;
2335
2924
  const hasApiKey = !!config.apiKey;
2336
2925
  if (hasApiKey) {
@@ -2349,6 +2938,7 @@ var WebDecoy = class {
2349
2938
  debug: config.debug ?? false,
2350
2939
  tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true
2351
2940
  };
2941
+ this.log = resolveLogger(config.logger, this.config.debug);
2352
2942
  if (hasApiKey) {
2353
2943
  this.client = new WebDecoyClient({
2354
2944
  apiKey: config.apiKey,
@@ -2359,16 +2949,17 @@ var WebDecoy = class {
2359
2949
  });
2360
2950
  } else {
2361
2951
  this.client = null;
2362
- if (this.config.debug) {
2363
- console.log("[WebDecoy] Running in local-only mode (no API key). Rules will still evaluate.");
2364
- }
2952
+ this.log.info("Running in local-only mode (no API key). Rules will still evaluate.");
2365
2953
  }
2366
2954
  this.webBotAuthOptions = config.webBotAuth;
2955
+ this.characteristics = config.characteristics ?? DEFAULT_CHARACTERISTICS;
2956
+ this.decisionCache = config.decisionCache === false ? null : new DecisionCache(config.decisionCache ?? {});
2367
2957
  const rules = config.rules ?? [tripwire()];
2368
2958
  if (rules.length > 0) {
2369
2959
  this.ruleEngine = new RuleEngine(rules);
2370
2960
  this._hasFilterRules = rules.some((r) => r.name.startsWith("filter:"));
2371
2961
  this._hasAgentRules = rules.some((r) => r.name === "web-bot-auth");
2962
+ this._preparingRules = rules.filter((r) => typeof r.prepare === "function");
2372
2963
  if (this._hasAgentRules) {
2373
2964
  this.getAgentVerifier().warmup();
2374
2965
  }
@@ -2384,15 +2975,13 @@ var WebDecoy = class {
2384
2975
  });
2385
2976
  this.setViolationReporter(reporter);
2386
2977
  }
2387
- if (this.config.debug) {
2388
- console.log("[WebDecoy] Initialized with config:", {
2389
- apiUrl: this.config.apiUrl,
2390
- enableTLSFingerprinting: this.config.enableTLSFingerprinting,
2391
- threatScoreThreshold: this.config.threatScoreThreshold,
2392
- hasApiKey,
2393
- rulesCount: rules.length
2394
- });
2395
- }
2978
+ this.log.debug("Initialized", {
2979
+ apiUrl: this.config.apiUrl,
2980
+ enableTLSFingerprinting: this.config.enableTLSFingerprinting,
2981
+ threatScoreThreshold: this.config.threatScoreThreshold,
2982
+ hasApiKey,
2983
+ rulesCount: rules.length
2984
+ });
2396
2985
  }
2397
2986
  /**
2398
2987
  * Evaluate rules against request metadata (synchronous).
@@ -2428,15 +3017,18 @@ var WebDecoy = class {
2428
3017
  }
2429
3018
  if (rule.name.startsWith("filter:")) this._hasFilterRules = true;
2430
3019
  if (rule.name === "web-bot-auth") this._hasAgentRules = true;
3020
+ if (typeof rule.prepare === "function") this._preparingRules.push(rule);
2431
3021
  }
2432
3022
  /** Build the base (synchronous) rule context from request metadata. */
2433
3023
  buildContext(metadata) {
2434
- return {
3024
+ const context = {
2435
3025
  ip: metadata.ip,
2436
3026
  path: metadata.path,
2437
3027
  method: metadata.method,
2438
3028
  userAgent: metadata.user_agent,
2439
3029
  headers: metadata.headers,
3030
+ query: metadata.query,
3031
+ body: metadata.body,
2440
3032
  timestamp: metadata.timestamp || Date.now(),
2441
3033
  // Parsed synchronously and unconditionally: it is two header reads,
2442
3034
  // it needs no network, and a rule that has to check whether the edge
@@ -2448,6 +3040,8 @@ var WebDecoy = class {
2448
3040
  // ran.
2449
3041
  bot: classifyUserAgent(metadata.user_agent)
2450
3042
  };
3043
+ context.key = deriveKey(context, this.characteristics);
3044
+ return context;
2451
3045
  }
2452
3046
  /**
2453
3047
  * Build a rule context with async signals resolved: IP enrichment (for
@@ -2464,6 +3058,9 @@ var WebDecoy = class {
2464
3058
  if (this._hasAgentRules) {
2465
3059
  context.agent = await this.computeAgentVerdict(metadata);
2466
3060
  }
3061
+ if (this._preparingRules.length > 0) {
3062
+ await Promise.all(this._preparingRules.map((rule) => rule.prepare(context)));
3063
+ }
2467
3064
  return context;
2468
3065
  }
2469
3066
  /** Evaluate rules against a prepared context and report any violations. */
@@ -2532,14 +3129,16 @@ var WebDecoy = class {
2532
3129
  *
2533
3130
  * @param metadata - Request metadata to analyze
2534
3131
  * @param options - Optional configuration for this specific request
2535
- * @returns Protection result with decision and detection details
3132
+ * @returns The decision — `conclusion`, every rule's outcome, and the
3133
+ * narrowing helpers. Satisfies `ProtectResult`.
2536
3134
  */
2537
3135
  async protect(metadata, options = {}) {
2538
3136
  const edge = readEdgeVerdict(metadata.headers);
2539
- const result = await this.decide(metadata, options);
2540
- return { ...result, edge };
3137
+ return (await this.decide(metadata, options)).withEdge(edge);
2541
3138
  }
2542
3139
  async decide(metadata, options = {}) {
3140
+ const id = newDecisionId();
3141
+ let key = metadata.ip || "unknown";
2543
3142
  try {
2544
3143
  if (!metadata.ip) {
2545
3144
  throw new Error("IP address is required in request metadata");
@@ -2548,62 +3147,53 @@ var WebDecoy = class {
2548
3147
  metadata.timestamp = Date.now();
2549
3148
  }
2550
3149
  if (isTestTriggerUserAgent(metadata.user_agent)) {
2551
- return this.reportTestTrigger(metadata);
2552
- }
2553
- let ruleResult;
2554
- let agentVerdict;
2555
- if (this.ruleEngine && (this._hasFilterRules || this._hasAgentRules)) {
2556
- const context = await this.buildAsyncContext(metadata);
2557
- agentVerdict = context.agent;
2558
- ruleResult = this.runRules(context);
2559
- } else {
2560
- ruleResult = this.evaluateRules(metadata);
2561
- }
2562
- if (ruleResult && ruleResult.action === "DENY") {
2563
- return {
2564
- allowed: false,
2565
- detection: {
2566
- decision: "block",
2567
- confidence: 100,
2568
- threat_level: "HIGH",
2569
- bot_detected: false,
2570
- detection_id: "rule_" + Date.now(),
2571
- rule_enforced: true
2572
- },
2573
- ruleResult,
2574
- agent: agentVerdict
2575
- };
3150
+ return this.reportTestTrigger(metadata, id);
2576
3151
  }
2577
- if (ruleResult && ruleResult.action === "THROTTLE") {
2578
- return {
2579
- allowed: false,
3152
+ const needsAsync = this._hasFilterRules || this._hasAgentRules || this._preparingRules.length > 0;
3153
+ const context = needsAsync ? await this.buildAsyncContext(metadata) : this.buildContext(metadata);
3154
+ key = context.key ?? key;
3155
+ const agentVerdict = context.agent;
3156
+ const ruleResult = this.ruleEngine ? this.runRules(context) : null;
3157
+ if (ruleResult && ruleResult.action !== "ALLOW") {
3158
+ const throttled = ruleResult.action === "THROTTLE";
3159
+ return new Decision({
3160
+ conclusion: "DENY",
3161
+ reason: ruleResult.reason,
2580
3162
  detection: {
2581
3163
  decision: "block",
2582
3164
  confidence: 100,
2583
- threat_level: "MEDIUM",
3165
+ threat_level: throttled ? "MEDIUM" : "HIGH",
2584
3166
  bot_detected: false,
2585
- detection_id: "rule_" + Date.now(),
3167
+ detection_id: id,
2586
3168
  rule_enforced: true
2587
3169
  },
3170
+ id,
3171
+ results: ruleResult.results,
2588
3172
  ruleResult,
2589
- agent: agentVerdict
2590
- };
3173
+ agent: agentVerdict,
3174
+ key
3175
+ });
2591
3176
  }
2592
3177
  if (!this.client) {
2593
- return {
2594
- allowed: true,
3178
+ return new Decision({
3179
+ conclusion: "ALLOW",
2595
3180
  detection: {
2596
3181
  decision: "allow",
2597
3182
  confidence: 0,
2598
3183
  threat_level: "MINIMAL",
2599
3184
  bot_detected: false,
2600
- detection_id: "local_" + Date.now(),
3185
+ detection_id: id,
2601
3186
  rule_enforced: false
2602
3187
  },
3188
+ id,
3189
+ results: ruleResult?.results ?? [],
2603
3190
  ruleResult: ruleResult ?? void 0,
2604
- agent: agentVerdict
2605
- };
3191
+ agent: agentVerdict,
3192
+ key
3193
+ });
2606
3194
  }
3195
+ const cached = this.decisionCache?.get(key);
3196
+ if (cached) return cached.asCached();
2607
3197
  const localAnalysis = options.skipLocalAnalysis ? {
2608
3198
  suspicious_headers: false,
2609
3199
  missing_sec_ch_ua: false,
@@ -2612,62 +3202,70 @@ var WebDecoy = class {
2612
3202
  needs_verification: true,
2613
3203
  flags: ["local_analysis_skipped"]
2614
3204
  } : analyzeRequest(metadata);
2615
- if (this.config.debug) {
2616
- console.log("[WebDecoy] Local analysis result:", localAnalysis);
2617
- }
3205
+ this.log.debug("Local analysis", { ...localAnalysis });
2618
3206
  const detectionRequest = {
2619
3207
  request_metadata: metadata,
2620
3208
  local_analysis: localAnalysis
2621
3209
  };
2622
3210
  const shouldCallServer = localAnalysis.needs_verification || this.config.enableTLSFingerprinting && metadata.tls_info;
2623
3211
  if (!shouldCallServer && localAnalysis.local_score < 50) {
2624
- return {
2625
- allowed: true,
3212
+ return new Decision({
3213
+ conclusion: "ALLOW",
2626
3214
  detection: {
2627
3215
  decision: "allow",
2628
3216
  confidence: 100 - localAnalysis.local_score,
2629
3217
  threat_level: "MINIMAL",
2630
3218
  bot_detected: false,
2631
- detection_id: "local_" + Date.now(),
3219
+ detection_id: id,
2632
3220
  rule_enforced: false
2633
3221
  },
3222
+ id,
3223
+ results: ruleResult?.results ?? [],
2634
3224
  ruleResult: ruleResult ?? void 0,
2635
- agent: agentVerdict
2636
- };
3225
+ agent: agentVerdict,
3226
+ key
3227
+ });
2637
3228
  }
2638
3229
  const detection = await this.client.detect(detectionRequest);
2639
3230
  const threshold = options.threshold ?? this.config.threatScoreThreshold;
2640
3231
  const allowed = detection.decision === "allow" || detection.confidence < threshold;
2641
- if (this.config.debug) {
2642
- console.log("[WebDecoy] Server detection result:", {
2643
- decision: detection.decision,
2644
- confidence: detection.confidence,
2645
- allowed
2646
- });
2647
- }
2648
- return {
2649
- allowed,
3232
+ this.log.debug("Server detection", {
3233
+ decision: detection.decision,
3234
+ confidence: detection.confidence,
3235
+ allowed
3236
+ });
3237
+ const conclusion = allowed ? "ALLOW" : detection.decision === "challenge" ? "CHALLENGE" : "DENY";
3238
+ const decision = new Decision({
3239
+ conclusion,
3240
+ reason: allowed ? void 0 : `Threat score ${detection.confidence} (threshold ${threshold})`,
2650
3241
  detection,
3242
+ id,
3243
+ results: ruleResult?.results ?? [],
2651
3244
  ruleResult: ruleResult ?? void 0,
2652
- agent: agentVerdict
2653
- };
3245
+ agent: agentVerdict,
3246
+ key,
3247
+ ttl: this.decisionCache && !allowed ? this.decisionCache.lifetime : 0
3248
+ });
3249
+ if (this.decisionCache) this.decisionCache.set(key, decision);
3250
+ return decision;
2654
3251
  } catch (error) {
2655
- if (this.config.debug) {
2656
- console.error("[WebDecoy] Protection error:", error);
2657
- }
2658
- return {
2659
- allowed: true,
2660
- // Fail open to avoid blocking legitimate users
3252
+ this.log.error("Protection error", {
3253
+ error: error instanceof Error ? error.message : String(error)
3254
+ });
3255
+ return new Decision({
3256
+ conclusion: "ERROR",
2661
3257
  detection: {
2662
3258
  decision: "allow",
2663
3259
  confidence: 0,
2664
3260
  threat_level: "MINIMAL",
2665
3261
  bot_detected: false,
2666
- detection_id: "error_" + Date.now(),
3262
+ detection_id: id,
2667
3263
  rule_enforced: false
2668
3264
  },
3265
+ id,
3266
+ key,
2669
3267
  error: error instanceof Error ? error.message : "Unknown error"
2670
- };
3268
+ });
2671
3269
  }
2672
3270
  }
2673
3271
  /**
@@ -2681,22 +3279,24 @@ var WebDecoy = class {
2681
3279
  * Without an API key nothing can reach the dashboard, so the verdict says
2682
3280
  * so via `error` instead of pretending the test ran.
2683
3281
  */
2684
- async reportTestTrigger(metadata) {
3282
+ async reportTestTrigger(metadata, id) {
2685
3283
  const blocked = {
2686
3284
  decision: "block",
2687
3285
  confidence: 100,
2688
3286
  threat_level: "HIGH",
2689
3287
  bot_detected: true,
2690
3288
  bot_type: "test_trigger",
2691
- detection_id: "test_" + Date.now(),
3289
+ detection_id: id,
2692
3290
  rule_enforced: false
2693
3291
  };
2694
3292
  if (!this.client) {
2695
- return {
2696
- allowed: false,
3293
+ return new Decision({
3294
+ id,
3295
+ conclusion: "DENY",
3296
+ reason: "Reserved test trigger",
2697
3297
  detection: blocked,
2698
3298
  error: "Test trigger recognized, but no apiKey is configured \u2014 nothing was reported to the dashboard."
2699
- };
3299
+ });
2700
3300
  }
2701
3301
  try {
2702
3302
  const detection = await this.client.detect({
@@ -2710,13 +3310,20 @@ var WebDecoy = class {
2710
3310
  flags: ["test_trigger"]
2711
3311
  }
2712
3312
  });
2713
- return { allowed: false, detection };
3313
+ return new Decision({
3314
+ id,
3315
+ conclusion: "DENY",
3316
+ reason: "Reserved test trigger",
3317
+ detection
3318
+ });
2714
3319
  } catch (error) {
2715
- return {
2716
- allowed: false,
3320
+ return new Decision({
3321
+ id,
3322
+ conclusion: "DENY",
3323
+ reason: "Reserved test trigger",
2717
3324
  detection: blocked,
2718
3325
  error: error instanceof Error ? error.message : "Failed to report test detection"
2719
- };
3326
+ });
2720
3327
  }
2721
3328
  }
2722
3329
  /**
@@ -2785,6 +3392,368 @@ function agentInputFromMetadata(metadata) {
2785
3392
  }
2786
3393
  }
2787
3394
 
3395
+ // src/client-ip.ts
3396
+ var IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
3397
+ function ipv4ToBytes(ip) {
3398
+ const m = IPV4.exec(ip);
3399
+ if (!m) return null;
3400
+ const out = new Uint8Array(4);
3401
+ for (let i = 0; i < 4; i++) {
3402
+ const part = m[i + 1];
3403
+ if (part.length > 1 && part[0] === "0") return null;
3404
+ const n = Number(part);
3405
+ if (n > 255) return null;
3406
+ out[i] = n;
3407
+ }
3408
+ return out;
3409
+ }
3410
+ function ipv6ToBytes(input) {
3411
+ let s = input.toLowerCase();
3412
+ const lastColon = s.lastIndexOf(":");
3413
+ if (lastColon !== -1 && s.slice(lastColon + 1).includes(".")) {
3414
+ const tail = ipv4ToBytes(s.slice(lastColon + 1));
3415
+ if (!tail) return null;
3416
+ const g1 = (tail[0] << 8 | tail[1]).toString(16);
3417
+ const g2 = (tail[2] << 8 | tail[3]).toString(16);
3418
+ s = `${s.slice(0, lastColon + 1)}${g1}:${g2}`;
3419
+ }
3420
+ const halves = s.split("::");
3421
+ if (halves.length > 2) return null;
3422
+ const parseGroups = (part) => {
3423
+ if (part === "") return [];
3424
+ const groups2 = part.split(":");
3425
+ const out = [];
3426
+ for (const g of groups2) {
3427
+ if (!/^[0-9a-f]{1,4}$/.test(g)) return null;
3428
+ out.push(parseInt(g, 16));
3429
+ }
3430
+ return out;
3431
+ };
3432
+ const head = parseGroups(halves[0]);
3433
+ if (head === null) return null;
3434
+ let groups;
3435
+ if (halves.length === 2) {
3436
+ const tail = parseGroups(halves[1]);
3437
+ if (tail === null) return null;
3438
+ const fill = 8 - head.length - tail.length;
3439
+ if (fill < 1) return null;
3440
+ groups = [...head, ...new Array(fill).fill(0), ...tail];
3441
+ } else {
3442
+ groups = head;
3443
+ }
3444
+ if (groups.length !== 8) return null;
3445
+ const bytes = new Uint8Array(16);
3446
+ for (let i = 0; i < 8; i++) {
3447
+ bytes[i * 2] = groups[i] >> 8;
3448
+ bytes[i * 2 + 1] = groups[i] & 255;
3449
+ }
3450
+ return bytes;
3451
+ }
3452
+ function ipToBytes(ip) {
3453
+ return ipv4ToBytes(ip) ?? ipv6ToBytes(ip);
3454
+ }
3455
+ function normalizeIp(raw) {
3456
+ if (!raw) return null;
3457
+ let v = raw.trim();
3458
+ if (!v) return null;
3459
+ if (v.startsWith("[")) {
3460
+ const close = v.indexOf("]");
3461
+ if (close === -1) return null;
3462
+ v = v.slice(1, close);
3463
+ } else if (v.includes(".") && v.split(":").length === 2) {
3464
+ v = v.slice(0, v.indexOf(":"));
3465
+ }
3466
+ const pct = v.indexOf("%");
3467
+ if (pct !== -1) v = v.slice(0, pct);
3468
+ if (ipv4ToBytes(v)) return v;
3469
+ const bytes = ipv6ToBytes(v);
3470
+ if (!bytes) return null;
3471
+ const mapped = bytes.subarray(0, 10).every((b) => b === 0) && bytes[10] === 255 && bytes[11] === 255;
3472
+ if (mapped) return `${bytes[12]}.${bytes[13]}.${bytes[14]}.${bytes[15]}`;
3473
+ return v.toLowerCase();
3474
+ }
3475
+ function ipInCidr(ip, cidr) {
3476
+ const slash = cidr.indexOf("/");
3477
+ const network = normalizeIp(slash === -1 ? cidr : cidr.slice(0, slash));
3478
+ const address = normalizeIp(ip);
3479
+ if (!network || !address) return false;
3480
+ const netBytes = ipToBytes(network);
3481
+ const addrBytes = ipToBytes(address);
3482
+ if (!netBytes || !addrBytes || netBytes.length !== addrBytes.length) return false;
3483
+ const totalBits = netBytes.length * 8;
3484
+ let bits = totalBits;
3485
+ if (slash !== -1) {
3486
+ const raw = cidr.slice(slash + 1);
3487
+ bits = Number(raw);
3488
+ if (raw === "" || !Number.isInteger(bits) || bits < 0 || bits > totalBits) return false;
3489
+ }
3490
+ const wholeBytes = bits >> 3;
3491
+ for (let i = 0; i < wholeBytes; i++) {
3492
+ if (netBytes[i] !== addrBytes[i]) return false;
3493
+ }
3494
+ const remainder = bits & 7;
3495
+ if (remainder) {
3496
+ const mask = 255 << 8 - remainder & 255;
3497
+ if ((netBytes[wholeBytes] & mask) !== (addrBytes[wholeBytes] & mask)) return false;
3498
+ }
3499
+ return true;
3500
+ }
3501
+ function readHeader(headers, name) {
3502
+ if (typeof headers.get === "function") {
3503
+ return headers.get(name) ?? void 0;
3504
+ }
3505
+ const bag = headers;
3506
+ const value = bag[name] ?? bag[name.toLowerCase()];
3507
+ if (Array.isArray(value)) return value.join(",");
3508
+ return value;
3509
+ }
3510
+ function forwardedChain(headers) {
3511
+ const raw = readHeader(headers, "x-forwarded-for");
3512
+ if (!raw) return [];
3513
+ return raw.split(",").map((part) => part.trim()).filter((part) => part !== "").map((part) => normalizeIp(part));
3514
+ }
3515
+ function resolveClientIp(options) {
3516
+ const { headers, trustProxy = false } = options;
3517
+ const peer = normalizeIp(options.peer) ?? void 0;
3518
+ if (trustProxy === false || trustProxy === 0) return peer;
3519
+ if (trustProxy === "cloudflare") {
3520
+ return normalizeIp(readHeader(headers, "cf-connecting-ip")) ?? peer;
3521
+ }
3522
+ const chain = forwardedChain(headers);
3523
+ if (typeof trustProxy === "number") {
3524
+ if (!Number.isInteger(trustProxy) || trustProxy < 0) return peer;
3525
+ const index = chain.length - trustProxy;
3526
+ if (index < 0 || index >= chain.length) return peer;
3527
+ return chain[index] ?? peer;
3528
+ }
3529
+ const full = peer ? [...chain, peer] : [...chain];
3530
+ for (let i = full.length - 1; i >= 0; i--) {
3531
+ const candidate = full[i];
3532
+ if (candidate === null) return peer;
3533
+ if (!trustProxy.some((range) => ipInCidr(candidate, range))) return candidate;
3534
+ }
3535
+ return full[0] ?? void 0 ?? peer;
3536
+ }
3537
+
3538
+ // src/client-signals.ts
3539
+ var MemoryClientSignalStore = class {
3540
+ constructor(options = {}) {
3541
+ this.sync = true;
3542
+ this.entries = /* @__PURE__ */ new Map();
3543
+ this.ttl = options.ttl ?? 9e5;
3544
+ this.max = options.max ?? 1e4;
3545
+ }
3546
+ get(sessionId) {
3547
+ const entry = this.entries.get(sessionId);
3548
+ if (!entry) return void 0;
3549
+ if (Date.now() - entry.at > this.ttl) {
3550
+ this.entries.delete(sessionId);
3551
+ return void 0;
3552
+ }
3553
+ return entry;
3554
+ }
3555
+ set(verdict) {
3556
+ this.entries.delete(verdict.sessionId);
3557
+ this.entries.set(verdict.sessionId, verdict);
3558
+ while (this.entries.size > this.max) {
3559
+ const oldest = this.entries.keys().next();
3560
+ if (oldest.done) break;
3561
+ this.entries.delete(oldest.value);
3562
+ }
3563
+ }
3564
+ get size() {
3565
+ return this.entries.size;
3566
+ }
3567
+ };
3568
+ var CLIENT_SESSION_COOKIE = "wd_cs";
3569
+ var CLIENT_SESSION_HEADER = "x-wd-session";
3570
+ function readClientSession(headers) {
3571
+ const cookie = headers["cookie"];
3572
+ if (cookie) {
3573
+ for (const part of cookie.split(";")) {
3574
+ const eq = part.indexOf("=");
3575
+ if (eq < 0) continue;
3576
+ if (part.slice(0, eq).trim() === CLIENT_SESSION_COOKIE) {
3577
+ const value = part.slice(eq + 1).trim();
3578
+ if (value) return value;
3579
+ }
3580
+ }
3581
+ }
3582
+ const header = headers[CLIENT_SESSION_HEADER];
3583
+ return header || void 0;
3584
+ }
3585
+ var ClientSignalRule = class {
3586
+ constructor(config) {
3587
+ this.name = "client-signals";
3588
+ this.store = config.store;
3589
+ this.minScore = config.minScore;
3590
+ this.action = config.action ?? "DENY";
3591
+ this.dryRun = config.dryRun ?? false;
3592
+ }
3593
+ async prepare(context) {
3594
+ if (this.store.sync) return;
3595
+ const sessionId = readClientSession(context.headers);
3596
+ if (!sessionId) return;
3597
+ const verdict = await this.store.get(sessionId);
3598
+ if (verdict) {
3599
+ context.prepared ?? (context.prepared = {});
3600
+ context.prepared[this.name] = verdict;
3601
+ }
3602
+ }
3603
+ evaluate(context) {
3604
+ const sessionId = readClientSession(context.headers);
3605
+ if (!sessionId) {
3606
+ return {
3607
+ action: "ALLOW",
3608
+ rule: this.name,
3609
+ state: "NOT_RUN",
3610
+ reason: "No browser session \u2014 the client widget did not run for this request"
3611
+ };
3612
+ }
3613
+ const verdict = this.store.sync ? this.store.get(sessionId) : context.prepared?.[this.name];
3614
+ if (!verdict) {
3615
+ return {
3616
+ action: "ALLOW",
3617
+ rule: this.name,
3618
+ state: "NOT_RUN",
3619
+ reason: "No signals recorded for this session yet"
3620
+ };
3621
+ }
3622
+ const bad = this.minScore !== void 0 ? verdict.score >= this.minScore : verdict.recommendation === "block";
3623
+ if (!bad) {
3624
+ return {
3625
+ action: "ALLOW",
3626
+ rule: this.name,
3627
+ metadata: { score: verdict.score, recommendation: verdict.recommendation }
3628
+ };
3629
+ }
3630
+ return {
3631
+ action: this.dryRun ? "ALLOW" : this.action,
3632
+ rule: this.name,
3633
+ reason: `Client signals scored ${verdict.score.toFixed(2)} (${verdict.recommendation})`,
3634
+ metadata: {
3635
+ score: verdict.score,
3636
+ recommendation: verdict.recommendation,
3637
+ sessionId,
3638
+ dryRun: this.dryRun
3639
+ }
3640
+ };
3641
+ }
3642
+ };
3643
+ function clientSignals(config) {
3644
+ return new ClientSignalRule(config);
3645
+ }
3646
+
3647
+ // src/fetch-guard.ts
3648
+ function defaultBlocked(_request, decision) {
3649
+ const throttled = decision.ruleResult?.action === "THROTTLE";
3650
+ const retryAfter = Number(decision.ruleResult?.metadata?.retryAfter ?? 60);
3651
+ if (throttled) {
3652
+ return new Response(
3653
+ JSON.stringify({
3654
+ error: "Too Many Requests",
3655
+ message: decision.reason ?? "Rate limit exceeded",
3656
+ retry_after: retryAfter,
3657
+ detection_id: decision.id
3658
+ }),
3659
+ {
3660
+ status: 429,
3661
+ headers: {
3662
+ "content-type": "application/json",
3663
+ "retry-after": String(retryAfter)
3664
+ }
3665
+ }
3666
+ );
3667
+ }
3668
+ return new Response(
3669
+ JSON.stringify({
3670
+ error: "Forbidden",
3671
+ message: "Access denied by Web Decoy protection",
3672
+ detection_id: decision.id
3673
+ }),
3674
+ { status: 403, headers: { "content-type": "application/json" } }
3675
+ );
3676
+ }
3677
+ function matches(pathname, patterns) {
3678
+ if (!patterns || patterns.length === 0) return false;
3679
+ return patterns.some(
3680
+ (p) => typeof p === "string" ? pathname === p || pathname.startsWith(p) : p.test(pathname)
3681
+ );
3682
+ }
3683
+ function headerRecord(headers) {
3684
+ const out = {};
3685
+ headers.forEach((value, key) => {
3686
+ out[key.toLowerCase()] = value;
3687
+ });
3688
+ return out;
3689
+ }
3690
+ function createFetchGuard(options = {}) {
3691
+ const sdk = new WebDecoy(options);
3692
+ const mode = options.mode ?? "monitor";
3693
+ const onBlocked = options.onBlocked ?? defaultBlocked;
3694
+ let token = null;
3695
+ if ((options.honeytoken ?? true) && options.apiKey) {
3696
+ void siteHoneytoken({ secret: options.apiKey }).then((t) => {
3697
+ token = t;
3698
+ sdk.addRule(tripwire({ paths: t.activePaths, includeDefaults: false }));
3699
+ }).catch(() => {
3700
+ });
3701
+ }
3702
+ function resolveIP(request, peer) {
3703
+ if (options.getIP) return options.getIP(request);
3704
+ return resolveClientIp({
3705
+ headers: request.headers,
3706
+ peer,
3707
+ trustProxy: options.trustProxy ?? 1
3708
+ }) ?? normalizeIp(peer) ?? "127.0.0.1";
3709
+ }
3710
+ return {
3711
+ sdk,
3712
+ skips(pathname) {
3713
+ return matches(pathname, options.skipPaths);
3714
+ },
3715
+ async check(request, peer) {
3716
+ const url = new URL(request.url);
3717
+ const metadata = {
3718
+ method: request.method,
3719
+ path: url.pathname,
3720
+ ip: resolveIP(request, peer),
3721
+ user_agent: request.headers.get("user-agent") ?? void 0,
3722
+ headers: headerRecord(request.headers),
3723
+ query: url.search ? url.search.slice(1) : void 0,
3724
+ timestamp: Date.now()
3725
+ };
3726
+ const decision = await sdk.protect(metadata, {
3727
+ threshold: options.threshold,
3728
+ skipLocalAnalysis: options.skipLocalAnalysis,
3729
+ metadata: options.metadata
3730
+ });
3731
+ if (decision.allowed || mode !== "enforce") return { decision };
3732
+ return { decision, response: await onBlocked(request, decision) };
3733
+ },
3734
+ async decorate(response) {
3735
+ const current = token;
3736
+ if (!current) return response;
3737
+ if (!isInjectableHtml(response.headers.get("content-type"))) return response;
3738
+ if (response.bodyUsed) return response;
3739
+ try {
3740
+ const html = await response.text();
3741
+ const injected = injectHoneytokenLink(html, current.linkHtml);
3742
+ if (injected === html) return new Response(html, response);
3743
+ const headers = new Headers(response.headers);
3744
+ headers.delete("content-length");
3745
+ return new Response(injected, {
3746
+ status: response.status,
3747
+ statusText: response.statusText,
3748
+ headers
3749
+ });
3750
+ } catch {
3751
+ return response;
3752
+ }
3753
+ }
3754
+ };
3755
+ }
3756
+
2788
3757
  // src/detection/weights.ts
2789
3758
  var DEFAULT_WEIGHTS = {
2790
3759
  vision_ai: 0.15,
@@ -2925,7 +3894,7 @@ var InMemoryRateLimiter2 = class {
2925
3894
  check(key, windowSeconds = 60, maxRequests = 10) {
2926
3895
  const now = Date.now();
2927
3896
  const cutoff = now - windowSeconds * 1e3;
2928
- let timestamps = (this.requests.get(key) ?? []).filter((t) => t > cutoff);
3897
+ const timestamps = (this.requests.get(key) ?? []).filter((t) => t > cutoff);
2929
3898
  const count = timestamps.length;
2930
3899
  if (count >= maxRequests) {
2931
3900
  this.requests.set(key, timestamps);
@@ -4681,7 +5650,7 @@ var Captcha = class {
4681
5650
  // src/captcha/http.ts
4682
5651
  var JSON_HEADERS = { "content-type": "application/json" };
4683
5652
  function createCaptchaEndpoints(options = {}) {
4684
- const { basePath = "/__webdecoy", ...captchaOptions } = options;
5653
+ const { basePath = "/__webdecoy", signalStore, ...captchaOptions } = options;
4685
5654
  const captcha = new Captcha(captchaOptions);
4686
5655
  const base = basePath.replace(/\/$/, "");
4687
5656
  function route(pathname) {
@@ -4731,7 +5700,20 @@ function createCaptchaEndpoints(options = {}) {
4731
5700
  ja3Hash,
4732
5701
  action: b.action
4733
5702
  });
4734
- return json(200, result);
5703
+ if (signalStore && b.sessionId) {
5704
+ await signalStore.set({
5705
+ sessionId: b.sessionId,
5706
+ score: result.score,
5707
+ recommendation: result.recommendation,
5708
+ at: Date.now()
5709
+ });
5710
+ }
5711
+ return json(200, {
5712
+ ...result,
5713
+ // Echoed so the widget can set the cookie the rule reads, without the
5714
+ // developer wiring a second endpoint to hand it one.
5715
+ sessionId: b.sessionId ?? null
5716
+ });
4735
5717
  }
4736
5718
  if (sub === "/token/verify" && method === "POST") {
4737
5719
  const b = req.body ?? {};
@@ -4744,14 +5726,23 @@ function createCaptchaEndpoints(options = {}) {
4744
5726
  }
4745
5727
  // Annotate the CommonJS export names for ESM import in node:
4746
5728
  0 && (module.exports = {
5729
+ ATTACK_SIGNATURE_IDS,
4747
5730
  AgentVerifier,
5731
+ AttackSignatureRule,
4748
5732
  BOT_CATEGORIES,
4749
5733
  BOT_REGISTRY,
5734
+ BotPolicy,
4750
5735
  BotRule,
5736
+ CLIENT_SESSION_COOKIE,
5737
+ CLIENT_SESSION_HEADER,
4751
5738
  Captcha,
5739
+ ClientSignalRule,
5740
+ DEFAULT_CHARACTERISTICS,
4752
5741
  DEFAULT_SIGNED_AGENT_DIRECTORIES,
4753
5742
  DEFAULT_TRIPWIRE_PATHS,
4754
5743
  DEFAULT_WEIGHTS,
5744
+ Decision,
5745
+ DecisionCache,
4755
5746
  DetectionEngine,
4756
5747
  DirectoryCache,
4757
5748
  EDGE_CLASS_HEADER,
@@ -4762,6 +5753,8 @@ function createCaptchaEndpoints(options = {}) {
4762
5753
  InMemoryFingerprintStore,
4763
5754
  InMemoryRateLimiter,
4764
5755
  InMemoryTokenStore,
5756
+ MemoryClientSignalStore,
5757
+ MemoryRateLimitStore,
4765
5758
  PoWManager,
4766
5759
  RateLimitRule,
4767
5760
  RuleEngine,
@@ -4769,28 +5762,43 @@ function createCaptchaEndpoints(options = {}) {
4769
5762
  TEST_TRIGGER_USER_AGENT,
4770
5763
  TokenManager,
4771
5764
  TripwireRule,
5765
+ UpstashRateLimitStore,
4772
5766
  WebBotAuthRule,
4773
5767
  WebDecoy,
5768
+ attackSignatures,
5769
+ botPolicy,
4774
5770
  bots,
4775
5771
  calculateCategoryScores,
4776
5772
  calculateFinalScore,
4777
5773
  classifyUserAgent,
5774
+ clientSignals,
5775
+ consoleLogger,
4778
5776
  createAgentVerifier,
4779
5777
  createCaptchaEndpoints,
5778
+ createFetchGuard,
5779
+ deriveKey,
4780
5780
  filter,
5781
+ fromPino,
4781
5782
  honeytoken,
4782
5783
  injectHoneytokenLink,
5784
+ ipInCidr,
4783
5785
  isDatacenterIP,
4784
5786
  isInjectableHtml,
4785
5787
  isMobileUA,
4786
5788
  isTestTriggerUserAgent,
4787
5789
  matchUserAgent,
5790
+ newDecisionId,
5791
+ normalizeIp,
4788
5792
  parseUserAgent,
4789
5793
  rateLimit,
5794
+ readClientSession,
4790
5795
  readEdgeVerdict,
4791
5796
  recommend,
5797
+ resolveClientIp,
4792
5798
  resolveSecret,
5799
+ silentLogger,
4793
5800
  siteHoneytoken,
4794
5801
  tripwire,
5802
+ upstashRateLimitStore,
4795
5803
  webBotAuth
4796
5804
  });