@webdecoy/node 0.21.3 → 0.22.1

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/vercel.js CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var vercel_exports = {};
22
22
  __export(vercel_exports, {
23
23
  clearanceMiddleware: () => clearanceMiddleware,
24
+ createVercelMiddleware: () => createVercelMiddleware,
24
25
  default: () => vercel_default,
25
26
  toMiddlewareResponse: () => toMiddlewareResponse
26
27
  });
@@ -1125,7 +1126,7 @@ async function wr(e, t, r) {
1125
1126
  return false;
1126
1127
  }
1127
1128
  }
1128
- var Ye = [["reflectionbot", "Reflectionbot", "reflectionbot", "crawler"], ["gptbot", "GPTBot", "gptbot", "crawler"], ["claudebot", "ClaudeBot", "claudebot", "crawler"], ["anthropic-ai", "Anthropic", "anthropic", "crawler"], ["claude-web", "Claude-Web", "claude-web", "crawler"], ["ccbot", "CCBot", "ccbot", "crawler"], ["google-extended", "Google-Extended", "google-extended", "crawler"], ["bytespider", "ByteSpider", "bytespider", "crawler"], ["amazonbot", "Amazonbot", "amazonbot", "crawler"], ["facebookbot", "FacebookBot", "facebookbot", "crawler"], ["meta-externalagent", "Meta-ExternalAgent", "meta-externalagent", "crawler"], ["cohere-ai", "Cohere", "cohere-ai", "crawler"], ["cohere", "Cohere", "cohere-ai", "crawler"], ["applebot-extended", "Applebot-Extended", "applebot-extended", "crawler"], ["youbot", "YouBot", "youbot", "crawler"], ["mistralbot", "MistralBot", "mistral", "crawler"], ["gemini", "Gemini", "gemini", "crawler"], ["ai2bot", "AI2Bot", "ai2bot", "crawler"], ["deepseek", "DeepSeek", "deepseek", "crawler"], ["qwen", "Qwen", "qwen", "crawler"], ["webzio", "Webz.io", "webzio", "crawler"], ["sentibot", "Sentibot", "sentibot", "crawler"], ["omgili", "Omgili", "omgili", "crawler"], ["img2dataset", "img2dataset", "img2dataset", "crawler"], ["timpibot", "Timpibot", "timpibot", "crawler"], ["velenpublicwebcrawler", "VelenPublicWebCrawler", "velenpublicwebcrawler", "crawler"], ["isscyberriskcrawler", "ISSCyberRiskCrawler", "isscyberriskcrawler", "crawler"], ["friendlycrawler", "FriendlyCrawler", "friendlycrawler", "crawler"], ["duckassistbot", "DuckAssistBot", "duckassistbot", "crawler"], ["sofyabot", "SofyaBot", "sofyabot", "crawler"], ["xai-searchbot", "xAI-SearchBot", "xai-searchbot", "crawler"], ["linkupbot", "LinkupBot", "linkupbot", "crawler"], ["perplexitybot", "PerplexityBot", "perplexitybot", "crawler"], ["claude-searchbot", "Claude-SearchBot", "claude-searchbot", "crawler"], ["oai-searchbot", "OAI-SearchBot", "oai-searchbot", "crawler"], ["searchgpt", "SearchGPT", "searchgpt", "crawler"], ["phind", "Phind", "phind", "crawler"], ["kagi", "Kagi", "kagi", "crawler"], ["exasearchbot", "Exa", "exa", "crawler"], ["exabot", "Exa", "exa", "crawler"], ["shapbot", "ShapBot", "shapbot", "crawler"], ["meta-webindexer", "Meta-WebIndexer", "meta-webindexer", "crawler"], ["metaphor", "Metaphor", "metaphor", "crawler"], ["tavily", "Tavily", "tavily", "crawler"], ["bravesearch", "BraveSearch", "brave-search", "crawler"], ["neevabot", "NeevaBot", "neeva", "crawler"], ["operator", "Operator", "operator", "crawler"], ["claude-user", "Claude-User", "claude-user", "crawler"], ["gemini-user", "Gemini-User", "gemini-user", "crawler"], ["googleagent-mariner", "GoogleAgent-Mariner", "googleagent-mariner", "crawler"], ["mariner", "GoogleAgent-Mariner", "googleagent-mariner", "crawler"], ["amazonbuyforme", "AmazonBuyForMe", "amazon-buyforme", "crawler"], ["buyforme", "AmazonBuyForMe", "amazon-buyforme", "crawler"], ["browser-use", "Browser-Use", "browser-use", "crawler"], ["stagehand", "Stagehand", "stagehand", "crawler"], ["manus-user", "Manus-User", "manus-user", "crawler"], ["multion", "MultiOn", "multion", "crawler"], ["iboubot", "IbouBot", "iboubot", "crawler"], ["googlebot", "Googlebot", "googlebot", "crawler"], ["google-inspectiontool", "Google-InspectionTool", "google-inspectiontool", "crawler"], ["bingbot", "Bingbot", "bingbot", "crawler"], ["msnbot", "MSNBot", "msnbot", "crawler"], ["yandexbot", "YandexBot", "yandexbot", "crawler"], ["baiduspider", "Baiduspider", "baiduspider", "crawler"], ["duckduckbot", "DuckDuckBot", "duckduckbot", "crawler"], ["applebot", "Applebot", "applebot", "crawler"], ["sogou", "Sogou Spider", "sogou", "crawler"], ["qwantify", "Qwantify", "qwantify", "crawler"], ["naver", "Naver", "naver", "crawler"], ["yeti", "Naver", "naver", "crawler"], ["seznambot", "SeznamBot", "seznam", "crawler"], ["ecosia", "Ecosia", "ecosia", "crawler"], ["mojeekbot", "MojeekBot", "mojeek", "crawler"], ["slurp", "Yahoo! Slurp", "yahoo-slurp", "crawler"], ["ahrefsbot", "AhrefsBot", "ahrefsbot", "crawler"], ["ahrefs", "AhrefsBot", "ahrefsbot", "crawler"], ["semrushbot", "SemrushBot", "semrushbot", "crawler"], ["semrush", "SemrushBot", "semrushbot", "crawler"], ["mj12bot", "MJ12bot", "mj12bot", "crawler"], ["dotbot", "DotBot", "dotbot", "crawler"], ["rogerbot", "Rogerbot", "rogerbot", "crawler"], ["screaming frog", "Screaming Frog", "screaming-frog", "crawler"], ["sitebulb", "Sitebulb", "sitebulb", "crawler"], ["deepcrawl", "DeepCrawl", "deepcrawl", "crawler"], ["oncrawl", "OnCrawl", "oncrawl", "crawler"], ["botify", "Botify", "botify", "crawler"], ["contentking", "ContentKing", "contentking", "crawler"], ["sistrix", "SISTRIX", "sistrix", "crawler"], ["serpstat", "Serpstat", "serpstat", "crawler"], ["spyfu", "SpyFu", "spyfu", "crawler"], ["nessus", "Nessus", "nessus", "crawler"], ["qualys", "Qualys", "qualys", "crawler"], ["shodan", "Shodan", "shodan", "crawler"], ["censys", "Censys", "censys", "crawler"], ["nmap", "Nmap", "nmap", "crawler"], ["zap/", "OWASP ZAP", "zap", "crawler"], ["burp", "Burp Suite", "burp", "crawler"], ["nikto", "Nikto", "nikto", "crawler"], ["nuclei", "Nuclei", "nuclei", "crawler"], ["acunetix", "Acunetix", "acunetix", "crawler"], ["netsparker", "Netsparker", "netsparker", "crawler"], ["detectify", "Detectify", "detectify", "crawler"], ["intruder", "Intruder", "intruder", "crawler"], ["python-requests", "Python-Requests", "python-requests", "tool"], ["python-urllib", "Python-urllib", "python-urllib", "tool"], ["python/", "Python", "python", "tool"], ["scrapy", "Scrapy", "scrapy", "tool"], ["httpx", "HTTPX", "httpx", "tool"], ["aiohttp", "aiohttp", "aiohttp", "tool"], ["beautifulsoup", "BeautifulSoup", "beautifulsoup", "tool"], ["node-fetch", "node-fetch", "node-fetch", "tool"], ["axios/", "Axios", "axios", "tool"], ["got/", "Got", "got", "tool"], ["undici", "Undici", "undici", "tool"], ["go-http-client", "Go-HTTP-Client", "go-http-client", "tool"], ["colly", "Colly", "colly", "tool"], ["java/", "Java", "java", "tool"], ["okhttp", "OkHttp", "okhttp", "tool"], ["apache-httpclient", "Apache-HttpClient", "apache-httpclient", "tool"], ["jsoup", "Jsoup", "jsoup", "tool"], ["guzzlehttp", "GuzzleHttp", "guzzlehttp", "tool"], ["php/", "PHP", "php", "tool"], ["ruby", "Ruby", "ruby", "tool"], ["faraday", "Faraday", "faraday", "tool"], ["mechanize", "Mechanize", "mechanize", "tool"], ["headlesschrome", "HeadlessChrome", "headlesschrome", "tool"], ["puppeteer", "Puppeteer", "puppeteer", "tool"], ["playwright", "Playwright", "playwright", "tool"], ["selenium", "Selenium", "selenium", "tool"], ["phantomjs", "PhantomJS", "phantomjs", "tool"], ["splash", "Splash", "splash", "tool"], ["browserless", "Browserless", "browserless", "tool"], ["browserbase", "Browserbase", "browserbase", "tool"], ["ia_archiver", "Internet Archive", "ia-archiver", "crawler"], ["archive.org_bot", "Archive.org", "archive-org-bot", "crawler"], ["wayback", "Wayback Machine", "wayback", "crawler"], ["heritrix", "Heritrix", "heritrix", "crawler"], ["brozzler", "Brozzler", "brozzler", "crawler"], ["facebookexternalhit", "Facebook", "facebookexternalhit", "crawler"], ["facebot", "Facebot", "facebot", "crawler"], ["twitterbot", "Twitterbot", "twitterbot", "crawler"], ["linkedinbot", "LinkedInBot", "linkedinbot", "crawler"], ["slackbot", "Slackbot", "slackbot", "crawler"], ["telegrambot", "TelegramBot", "telegrambot", "crawler"], ["whatsapp", "WhatsApp", "whatsapp", "crawler"], ["discordbot", "Discordbot", "discordbot", "crawler"], ["pinterest", "Pinterest", "pinterestbot", "crawler"], ["tumblr", "Tumblr", "tumblr", "crawler"], ["reddit", "Reddit", "reddit", "crawler"], ["embedly", "Embedly", "embedly", "crawler"], ["iframely", "Iframely", "iframely", "crawler"], ["curl/", "cURL", "curl", "tool"], ["wget/", "Wget", "wget", "tool"], ["libwww-perl", "libwww-perl", "libwww-perl", "tool"], ["lwp-", "LWP", "lwp", "tool"], ["httrack", "HTTrack", "httrack", "tool"], ["webdecoybot", "WebDecoyBot", "webdecoybot", "crawler"], ["uptimerobot", "UptimeRobot", "uptimerobot", "crawler"], ["pingdom", "Pingdom", "pingdom", "crawler"], ["statuscake", "StatusCake", "statuscake", "crawler"], ["betteruptime", "Better Uptime", "better-uptime", "crawler"], ["datadog", "Datadog Synthetics", "datadog-synthetics", "crawler"], ["newrelic", "New Relic", "newrelic", "crawler"], ["site24x7", "Site24x7", "site24x7", "crawler"], ["freshping", "Freshping", "freshping", "crawler"], ["hetrixtools", "HetrixTools", "hetrixtools", "crawler"], ["nodeping", "NodePing", "nodeping", "crawler"], ["gtmetrix", "GTmetrix", "gtmetrix", "crawler"], ["chrome-lighthouse", "Lighthouse", "chrome-lighthouse", "crawler"], ["google page speed", "Lighthouse", "chrome-lighthouse", "crawler"], ["feedly", "Feedly", "feedly", "crawler"], ["feedfetcher", "Feedfetcher-Google", "feedfetcher-google", "crawler"], ["newsblur", "NewsBlur", "newsblur", "crawler"], ["inoreader", "Inoreader", "inoreader", "crawler"], ["theoldreader", "The Old Reader", "theoldreader", "crawler"], ["feedbin", "Feedbin", "feedbin", "crawler"], ["miniflux", "Miniflux", "miniflux", "crawler"], ["freshrss", "FreshRSS", "freshrss", "crawler"], ["commafeed", "CommaFeed", "commafeed", "crawler"], ["diffbot", "Diffbot", "diffbot", "crawler"], ["import.io", "Import.io", "import-io", "crawler"], ["brightdata", "Bright Data", "bright-data", "crawler"], ["luminati", "Bright Data", "bright-data", "crawler"], ["oxylabs", "Oxylabs", "oxylabs", "crawler"], ["scrapingbee", "ScrapingBee", "scrapingbee", "crawler"], ["scrapingant", "ScrapingAnt", "scrapingant", "crawler"], ["zyte", "Zyte", "zyte", "crawler"], ["scrapinghub", "Zyte", "zyte", "crawler"], ["apify", "Apify", "apify", "crawler"], ["crawlbase", "Crawlbase", "crawlbase", "crawler"], ["webscrapingapi", "WebScrapingAPI", "webscrapingapi", "crawler"], ["chatgpt-user", "ChatGPT-User", "chatgpt-user", "crawler"], ["perplexity-user", "Perplexity-User", "perplexity-user", "crawler"], ["mistralai-user", "MistralAI-User", "mistralai-user", "crawler"], ["exauser", "ExaUser", "exauser", "crawler"], ["shap-user", "Shap-User", "shap-user", "crawler"], ["meta-externalfetcher", "Meta-ExternalFetcher", "meta-externalfetcher", "crawler"], ["gemini-deep-research", "Gemini-Deep-Research", "gemini-deep-research", "crawler"], ["copilot", "Microsoft Copilot", "copilot", "crawler"], ["cortana", "Cortana", "cortana", "crawler"], ["siri", "Siri", "siri", "crawler"]];
1129
+ var Ye = [["reflectionbot", "Reflectionbot", "reflectionbot", "crawler"], ["gptbot", "GPTBot", "gptbot", "crawler"], ["claudebot", "ClaudeBot", "claudebot", "crawler"], ["anthropic-ai", "Anthropic", "anthropic", "crawler"], ["claude-web", "Claude-Web", "claude-web", "crawler"], ["ccbot", "CCBot", "ccbot", "crawler"], ["google-extended", "Google-Extended", "google-extended", "crawler"], ["bytespider", "ByteSpider", "bytespider", "crawler"], ["amazonbot", "Amazonbot", "amazonbot", "crawler"], ["facebookbot", "FacebookBot", "facebookbot", "crawler"], ["meta-externalagent", "Meta-ExternalAgent", "meta-externalagent", "crawler"], ["cohere-ai", "Cohere", "cohere-ai", "crawler"], ["cohere", "Cohere", "cohere-ai", "crawler"], ["applebot-extended", "Applebot-Extended", "applebot-extended", "crawler"], ["youbot", "YouBot", "youbot", "crawler"], ["mistralbot", "MistralBot", "mistral", "crawler"], ["gemini", "Gemini", "gemini", "crawler"], ["ai2bot", "AI2Bot", "ai2bot", "crawler"], ["deepseek", "DeepSeek", "deepseek", "crawler"], ["qwen", "Qwen", "qwen", "crawler"], ["webzio", "Webz.io", "webzio", "crawler"], ["sentibot", "Sentibot", "sentibot", "crawler"], ["omgili", "Omgili", "omgili", "crawler"], ["img2dataset", "img2dataset", "img2dataset", "crawler"], ["timpibot", "Timpibot", "timpibot", "crawler"], ["velenpublicwebcrawler", "VelenPublicWebCrawler", "velenpublicwebcrawler", "crawler"], ["isscyberriskcrawler", "ISSCyberRiskCrawler", "isscyberriskcrawler", "crawler"], ["friendlycrawler", "FriendlyCrawler", "friendlycrawler", "crawler"], ["duckassistbot", "DuckAssistBot", "duckassistbot", "crawler"], ["sofyabot", "SofyaBot", "sofyabot", "crawler"], ["xai-searchbot", "xAI-SearchBot", "xai-searchbot", "crawler"], ["linkupbot", "LinkupBot", "linkupbot", "crawler"], ["perplexitybot", "PerplexityBot", "perplexitybot", "crawler"], ["claude-searchbot", "Claude-SearchBot", "claude-searchbot", "crawler"], ["oai-searchbot", "OAI-SearchBot", "oai-searchbot", "crawler"], ["searchgpt", "SearchGPT", "searchgpt", "crawler"], ["phind", "Phind", "phind", "crawler"], ["kagi", "Kagi", "kagi", "crawler"], ["exasearchbot", "Exa", "exa", "crawler"], ["exabot", "Exa", "exa", "crawler"], ["shapbot", "ShapBot", "shapbot", "crawler"], ["meta-webindexer", "Meta-WebIndexer", "meta-webindexer", "crawler"], ["metaphor", "Metaphor", "metaphor", "crawler"], ["tavily", "Tavily", "tavily", "crawler"], ["bravesearch", "BraveSearch", "brave-search", "crawler"], ["neevabot", "NeevaBot", "neeva", "crawler"], ["operator", "Operator", "operator", "crawler"], ["claude-user", "Claude-User", "claude-user", "crawler"], ["gemini-user", "Gemini-User", "gemini-user", "crawler"], ["googleagent-mariner", "GoogleAgent-Mariner", "googleagent-mariner", "crawler"], ["mariner", "GoogleAgent-Mariner", "googleagent-mariner", "crawler"], ["amazonbuyforme", "AmazonBuyForMe", "amazon-buyforme", "crawler"], ["buyforme", "AmazonBuyForMe", "amazon-buyforme", "crawler"], ["browser-use", "Browser-Use", "browser-use", "crawler"], ["stagehand", "Stagehand", "stagehand", "crawler"], ["manus-user", "Manus-User", "manus-user", "crawler"], ["multion", "MultiOn", "multion", "crawler"], ["iboubot", "IbouBot", "iboubot", "crawler"], ["googlebot", "Googlebot", "googlebot", "crawler"], ["google-inspectiontool", "Google-InspectionTool", "google-inspectiontool", "crawler"], ["bingbot", "Bingbot", "bingbot", "crawler"], ["msnbot", "MSNBot", "msnbot", "crawler"], ["yandexbot", "YandexBot", "yandexbot", "crawler"], ["baiduspider", "Baiduspider", "baiduspider", "crawler"], ["petalbot", "PetalBot", "petalbot", "crawler"], ["duckduckbot", "DuckDuckBot", "duckduckbot", "crawler"], ["applebot", "Applebot", "applebot", "crawler"], ["sogou", "Sogou Spider", "sogou", "crawler"], ["qwantify", "Qwantify", "qwantify", "crawler"], ["naver", "Naver", "naver", "crawler"], ["yeti", "Naver", "naver", "crawler"], ["seznambot", "SeznamBot", "seznam", "crawler"], ["ecosia", "Ecosia", "ecosia", "crawler"], ["mojeekbot", "MojeekBot", "mojeek", "crawler"], ["slurp", "Yahoo! Slurp", "yahoo-slurp", "crawler"], ["ahrefsbot", "AhrefsBot", "ahrefsbot", "crawler"], ["ahrefs", "AhrefsBot", "ahrefsbot", "crawler"], ["semrushbot", "SemrushBot", "semrushbot", "crawler"], ["semrush", "SemrushBot", "semrushbot", "crawler"], ["mj12bot", "MJ12bot", "mj12bot", "crawler"], ["dotbot", "DotBot", "dotbot", "crawler"], ["rogerbot", "Rogerbot", "rogerbot", "crawler"], ["screaming frog", "Screaming Frog", "screaming-frog", "crawler"], ["sitebulb", "Sitebulb", "sitebulb", "crawler"], ["deepcrawl", "DeepCrawl", "deepcrawl", "crawler"], ["oncrawl", "OnCrawl", "oncrawl", "crawler"], ["botify", "Botify", "botify", "crawler"], ["contentking", "ContentKing", "contentking", "crawler"], ["sistrix", "SISTRIX", "sistrix", "crawler"], ["serpstat", "Serpstat", "serpstat", "crawler"], ["spyfu", "SpyFu", "spyfu", "crawler"], ["nessus", "Nessus", "nessus", "crawler"], ["qualys", "Qualys", "qualys", "crawler"], ["shodan", "Shodan", "shodan", "crawler"], ["censys", "Censys", "censys", "crawler"], ["nmap", "Nmap", "nmap", "crawler"], ["zap/", "OWASP ZAP", "zap", "crawler"], ["burp", "Burp Suite", "burp", "crawler"], ["nikto", "Nikto", "nikto", "crawler"], ["nuclei", "Nuclei", "nuclei", "crawler"], ["acunetix", "Acunetix", "acunetix", "crawler"], ["netsparker", "Netsparker", "netsparker", "crawler"], ["detectify", "Detectify", "detectify", "crawler"], ["intruder", "Intruder", "intruder", "crawler"], ["python-requests", "Python-Requests", "python-requests", "tool"], ["python-urllib", "Python-urllib", "python-urllib", "tool"], ["python/", "Python", "python", "tool"], ["scrapy", "Scrapy", "scrapy", "tool"], ["httpx", "HTTPX", "httpx", "tool"], ["aiohttp", "aiohttp", "aiohttp", "tool"], ["beautifulsoup", "BeautifulSoup", "beautifulsoup", "tool"], ["node-fetch", "node-fetch", "node-fetch", "tool"], ["axios/", "Axios", "axios", "tool"], ["got/", "Got", "got", "tool"], ["undici", "Undici", "undici", "tool"], ["go-http-client", "Go-HTTP-Client", "go-http-client", "tool"], ["colly", "Colly", "colly", "tool"], ["java/", "Java", "java", "tool"], ["okhttp", "OkHttp", "okhttp", "tool"], ["apache-httpclient", "Apache-HttpClient", "apache-httpclient", "tool"], ["jsoup", "Jsoup", "jsoup", "tool"], ["guzzlehttp", "GuzzleHttp", "guzzlehttp", "tool"], ["php/", "PHP", "php", "tool"], ["ruby", "Ruby", "ruby", "tool"], ["faraday", "Faraday", "faraday", "tool"], ["mechanize", "Mechanize", "mechanize", "tool"], ["headlesschrome", "HeadlessChrome", "headlesschrome", "tool"], ["puppeteer", "Puppeteer", "puppeteer", "tool"], ["playwright", "Playwright", "playwright", "tool"], ["selenium", "Selenium", "selenium", "tool"], ["phantomjs", "PhantomJS", "phantomjs", "tool"], ["splash", "Splash", "splash", "tool"], ["browserless", "Browserless", "browserless", "tool"], ["browserbase", "Browserbase", "browserbase", "tool"], ["ia_archiver", "Internet Archive", "ia-archiver", "crawler"], ["archive.org_bot", "Archive.org", "archive-org-bot", "crawler"], ["wayback", "Wayback Machine", "wayback", "crawler"], ["heritrix", "Heritrix", "heritrix", "crawler"], ["brozzler", "Brozzler", "brozzler", "crawler"], ["facebookexternalhit", "Facebook", "facebookexternalhit", "crawler"], ["facebot", "Facebot", "facebot", "crawler"], ["twitterbot", "Twitterbot", "twitterbot", "crawler"], ["linkedinbot", "LinkedInBot", "linkedinbot", "crawler"], ["slackbot", "Slackbot", "slackbot", "crawler"], ["telegrambot", "TelegramBot", "telegrambot", "crawler"], ["whatsapp", "WhatsApp", "whatsapp", "crawler"], ["discordbot", "Discordbot", "discordbot", "crawler"], ["pinterest", "Pinterest", "pinterestbot", "crawler"], ["tumblr", "Tumblr", "tumblr", "crawler"], ["reddit", "Reddit", "reddit", "crawler"], ["embedly", "Embedly", "embedly", "crawler"], ["iframely", "Iframely", "iframely", "crawler"], ["curl/", "cURL", "curl", "tool"], ["wget/", "Wget", "wget", "tool"], ["libwww-perl", "libwww-perl", "libwww-perl", "tool"], ["lwp-", "LWP", "lwp", "tool"], ["httrack", "HTTrack", "httrack", "tool"], ["webdecoybot", "WebDecoyBot", "webdecoybot", "crawler"], ["uptimerobot", "UptimeRobot", "uptimerobot", "crawler"], ["pingdom", "Pingdom", "pingdom", "crawler"], ["statuscake", "StatusCake", "statuscake", "crawler"], ["betteruptime", "Better Uptime", "better-uptime", "crawler"], ["datadog", "Datadog Synthetics", "datadog-synthetics", "crawler"], ["newrelic", "New Relic", "newrelic", "crawler"], ["site24x7", "Site24x7", "site24x7", "crawler"], ["freshping", "Freshping", "freshping", "crawler"], ["hetrixtools", "HetrixTools", "hetrixtools", "crawler"], ["nodeping", "NodePing", "nodeping", "crawler"], ["gtmetrix", "GTmetrix", "gtmetrix", "crawler"], ["chrome-lighthouse", "Lighthouse", "chrome-lighthouse", "crawler"], ["google page speed", "Lighthouse", "chrome-lighthouse", "crawler"], ["feedly", "Feedly", "feedly", "crawler"], ["feedfetcher", "Feedfetcher-Google", "feedfetcher-google", "crawler"], ["newsblur", "NewsBlur", "newsblur", "crawler"], ["inoreader", "Inoreader", "inoreader", "crawler"], ["theoldreader", "The Old Reader", "theoldreader", "crawler"], ["feedbin", "Feedbin", "feedbin", "crawler"], ["miniflux", "Miniflux", "miniflux", "crawler"], ["freshrss", "FreshRSS", "freshrss", "crawler"], ["commafeed", "CommaFeed", "commafeed", "crawler"], ["diffbot", "Diffbot", "diffbot", "crawler"], ["import.io", "Import.io", "import-io", "crawler"], ["brightdata", "Bright Data", "bright-data", "crawler"], ["luminati", "Bright Data", "bright-data", "crawler"], ["oxylabs", "Oxylabs", "oxylabs", "crawler"], ["scrapingbee", "ScrapingBee", "scrapingbee", "crawler"], ["scrapingant", "ScrapingAnt", "scrapingant", "crawler"], ["zyte", "Zyte", "zyte", "crawler"], ["scrapinghub", "Zyte", "zyte", "crawler"], ["apify", "Apify", "apify", "crawler"], ["crawlbase", "Crawlbase", "crawlbase", "crawler"], ["webscrapingapi", "WebScrapingAPI", "webscrapingapi", "crawler"], ["chatgpt-user", "ChatGPT-User", "chatgpt-user", "crawler"], ["perplexity-user", "Perplexity-User", "perplexity-user", "crawler"], ["mistralai-user", "MistralAI-User", "mistralai-user", "crawler"], ["exauser", "ExaUser", "exauser", "crawler"], ["shap-user", "Shap-User", "shap-user", "crawler"], ["meta-externalfetcher", "Meta-ExternalFetcher", "meta-externalfetcher", "crawler"], ["gemini-deep-research", "Gemini-Deep-Research", "gemini-deep-research", "crawler"], ["copilot", "Microsoft Copilot", "copilot", "crawler"], ["cortana", "Cortana", "cortana", "crawler"], ["siri", "Siri", "siri", "crawler"]];
1129
1130
  function br(e) {
1130
1131
  for (let [t, r, n, o] of Ye) if (e.includes(t)) return { name: r, id: n, kind: o };
1131
1132
  return null;
@@ -1171,7 +1172,7 @@ function kr(e = fetch) {
1171
1172
  function Qe(e, t, r, n = fetch) {
1172
1173
  return Ze(e, t, r, kr(n));
1173
1174
  }
1174
- var ne = "vercel-2f65cde49015";
1175
+ var ne = "vercel-158ba59289ce";
1175
1176
  var et = "https://in.webdecoy.com";
1176
1177
  function tt(e) {
1177
1178
  let t = new Headers(e.headers);
@@ -1386,6 +1387,2778 @@ function createClearanceGate(options = {}) {
1386
1387
  };
1387
1388
  }
1388
1389
 
1390
+ // src/report-headers.ts
1391
+ var CREDENTIAL_HEADER = /cookie|auth|token|secret|passw|session|credential|csrf|xsrf|api[-_]?key|access[-_]?key|private[-_]?key/i;
1392
+ var CLEARANCE_COOKIE = "wd_clearance";
1393
+ function reportableHeaders(headers) {
1394
+ const out = {};
1395
+ for (const [name, value] of Object.entries(headers)) {
1396
+ if (!CREDENTIAL_HEADER.test(name)) {
1397
+ out[name] = value;
1398
+ continue;
1399
+ }
1400
+ out[name] = name.toLowerCase() === "cookie" ? clearanceCookieOnly(value) : "";
1401
+ }
1402
+ return out;
1403
+ }
1404
+ function clearanceCookieOnly(cookie) {
1405
+ return String(cookie ?? "").split(";").map((pair) => pair.trim()).filter((pair) => pair.slice(0, pair.indexOf("=")).trim() === CLEARANCE_COOKIE).join("; ");
1406
+ }
1407
+
1408
+ // src/client.ts
1409
+ var WebDecoyUnavailableError = class extends Error {
1410
+ constructor(retryAt) {
1411
+ super("WebDecoy is temporarily unavailable; requests are paused");
1412
+ this.retryAt = retryAt;
1413
+ this.name = "WebDecoyUnavailableError";
1414
+ Object.setPrototypeOf(this, new.target.prototype);
1415
+ }
1416
+ };
1417
+ var PAUSE_BASE_MS = 1e3;
1418
+ var PAUSE_MAX_MS = 6e4;
1419
+ var RETRY_AFTER_MAX_MS = 3e5;
1420
+ var WebDecoyClient = class {
1421
+ constructor(config) {
1422
+ /** No request is made before this time (epoch ms). */
1423
+ this.pausedUntil = 0;
1424
+ this.consecutiveFailures = 0;
1425
+ this.config = config;
1426
+ this.baseUrl = config.apiUrl.replace(/\/+$/, "");
1427
+ this.headers = {
1428
+ "Content-Type": "application/json",
1429
+ Authorization: `Bearer ${config.apiKey}`,
1430
+ "User-Agent": "webdecoy-node-sdk/0.1.0"
1431
+ };
1432
+ if (config.tlsRejectUnauthorized === false && config.debug) {
1433
+ console.warn(
1434
+ "[WebDecoy] tlsRejectUnauthorized=false is not supported by the fetch transport and is ignored; for local self-signed certs, trust your CA via NODE_EXTRA_CA_CERTS=/path/to/ca.pem."
1435
+ );
1436
+ }
1437
+ }
1438
+ /**
1439
+ * Whether a request would be attempted right now. False while paused after
1440
+ * WebDecoy refused work (429, 5xx) or did not answer, so a caller with
1441
+ * something to keep (a buffer) can hold it rather than lose it.
1442
+ */
1443
+ isAvailable(now = Date.now()) {
1444
+ return now >= this.pausedUntil;
1445
+ }
1446
+ /**
1447
+ * Pause every call to WebDecoy after a refusal or no answer: the Retry-After
1448
+ * when one was given, otherwise 1s doubling per consecutive failure up to
1449
+ * 60s. Without this, each request during an outage waited out the full
1450
+ * timeout in the caller's request path.
1451
+ */
1452
+ pause(retryAfter) {
1453
+ const seconds = retryAfter ? Number(retryAfter) : NaN;
1454
+ const ms = Number.isFinite(seconds) && seconds > 0 ? Math.min(Math.max(seconds * 1e3, PAUSE_BASE_MS), RETRY_AFTER_MAX_MS) : Math.min(PAUSE_BASE_MS * 2 ** this.consecutiveFailures, PAUSE_MAX_MS);
1455
+ this.consecutiveFailures++;
1456
+ this.pausedUntil = Date.now() + ms;
1457
+ }
1458
+ async request(method, path, body) {
1459
+ if (!this.isAvailable()) {
1460
+ throw new WebDecoyUnavailableError(this.pausedUntil);
1461
+ }
1462
+ const controller = new AbortController();
1463
+ const timer = setTimeout(() => controller.abort(), this.config.timeout);
1464
+ if (typeof timer.unref === "function") {
1465
+ timer.unref();
1466
+ }
1467
+ if (this.config.debug) {
1468
+ console.log("[WebDecoy] Request:", { method, url: this.baseUrl + path, data: body });
1469
+ }
1470
+ try {
1471
+ const response = await fetch(this.baseUrl + path, {
1472
+ method,
1473
+ headers: this.headers,
1474
+ body: body === void 0 ? void 0 : JSON.stringify(body),
1475
+ signal: controller.signal
1476
+ });
1477
+ let data;
1478
+ const text = await response.text();
1479
+ if (text) {
1480
+ try {
1481
+ data = JSON.parse(text);
1482
+ } catch {
1483
+ data = void 0;
1484
+ }
1485
+ }
1486
+ if (this.config.debug) {
1487
+ console.log("[WebDecoy] Response:", { status: response.status, data });
1488
+ }
1489
+ if (response.status === 429 || response.status >= 500) {
1490
+ this.pause(response.headers.get("retry-after"));
1491
+ } else {
1492
+ this.consecutiveFailures = 0;
1493
+ }
1494
+ return { status: response.status, data };
1495
+ } catch (error) {
1496
+ this.pause(null);
1497
+ if (this.config.debug) {
1498
+ console.error("[WebDecoy] Error:", {
1499
+ message: error instanceof Error ? error.message : String(error)
1500
+ });
1501
+ }
1502
+ throw error;
1503
+ } finally {
1504
+ clearTimeout(timer);
1505
+ }
1506
+ }
1507
+ /**
1508
+ * Send a detection request to the ingest service
1509
+ */
1510
+ async detect(request) {
1511
+ let response;
1512
+ try {
1513
+ response = await this.request(
1514
+ "POST",
1515
+ "/api/v1/sdk/detect",
1516
+ toWireDetectionRequest(request)
1517
+ );
1518
+ } catch (error) {
1519
+ if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) {
1520
+ throw new Error("Request timeout. The Web Decoy service did not respond in time.");
1521
+ }
1522
+ if (error instanceof TypeError) {
1523
+ throw new Error("Unable to connect to Web Decoy service. Please check your network.");
1524
+ }
1525
+ throw error;
1526
+ }
1527
+ if (response.status === 401) {
1528
+ throw new Error("Invalid API key. Please check your Web Decoy configuration.");
1529
+ }
1530
+ if (response.status === 429) {
1531
+ throw new Error("Rate limit exceeded. Please try again later.");
1532
+ }
1533
+ if (response.status >= 400) {
1534
+ if (response.data?.error || response.data?.message) {
1535
+ throw new Error(response.data.error || response.data.message || "API error");
1536
+ }
1537
+ throw new Error(`API request failed: HTTP ${response.status}`);
1538
+ }
1539
+ return response.data;
1540
+ }
1541
+ /**
1542
+ * Send violation events to the ingest service
1543
+ */
1544
+ async sendViolations(events) {
1545
+ try {
1546
+ await this.request("POST", "/api/v1/sdk/violations/batch", { events });
1547
+ } catch (error) {
1548
+ if (this.config.debug) {
1549
+ console.error("[WebDecoy] Failed to send violations:", error);
1550
+ }
1551
+ }
1552
+ }
1553
+ /**
1554
+ * Send AI referral counts. Resolves true when the batch needs no retry:
1555
+ * accepted, or refused for a reason a retry cannot fix (a 4xx). Only a
1556
+ * server error or a network failure resolves false, so the caller retries
1557
+ * the same batch id.
1558
+ */
1559
+ async sendAIReferrals(batch) {
1560
+ try {
1561
+ const response = await this.request("POST", "/api/v1/sdk/ai-referrals", batch);
1562
+ return response.status < 500 && response.status !== 429;
1563
+ } catch (error) {
1564
+ if (this.config.debug) {
1565
+ console.error("[WebDecoy] Failed to send AI referrals:", error);
1566
+ }
1567
+ return false;
1568
+ }
1569
+ }
1570
+ /**
1571
+ * Get IP enrichment data from the ingest service
1572
+ */
1573
+ async getIPEnrichment(ip) {
1574
+ try {
1575
+ const response = await this.request(
1576
+ "GET",
1577
+ `/api/v1/sdk/ip/${encodeURIComponent(ip)}/enrichment`
1578
+ );
1579
+ if (response.status >= 400) return null;
1580
+ return response.data ?? null;
1581
+ } catch (error) {
1582
+ if (this.config.debug) {
1583
+ console.error("[WebDecoy] Failed to get IP enrichment:", error);
1584
+ }
1585
+ return null;
1586
+ }
1587
+ }
1588
+ /**
1589
+ * Validate the API key by making a test request
1590
+ */
1591
+ async validateAPIKey() {
1592
+ try {
1593
+ const testRequest = {
1594
+ request_metadata: {
1595
+ method: "GET",
1596
+ path: "/__webdecoy_test__",
1597
+ ip: "127.0.0.1",
1598
+ headers: {},
1599
+ timestamp: Date.now()
1600
+ },
1601
+ local_analysis: {
1602
+ suspicious_headers: false,
1603
+ missing_sec_ch_ua: false,
1604
+ datacenter_ip: false,
1605
+ local_score: 0,
1606
+ needs_verification: false,
1607
+ flags: ["api_key_validation"]
1608
+ }
1609
+ };
1610
+ await this.detect(testRequest);
1611
+ return true;
1612
+ } catch (error) {
1613
+ if (error instanceof Error && error.message.includes("Invalid API key")) {
1614
+ return false;
1615
+ }
1616
+ return true;
1617
+ }
1618
+ }
1619
+ };
1620
+ function toWireDetectionRequest(request) {
1621
+ const metadata = {
1622
+ ...request.request_metadata,
1623
+ headers: reportableHeaders(request.request_metadata.headers ?? {})
1624
+ };
1625
+ const tls = metadata.tls_info;
1626
+ if (tls && tls.alpn_protocols !== void 0) {
1627
+ const { alpn_protocols, ...rest } = tls;
1628
+ metadata.tls_info = { ...rest, alpn: rest.alpn ?? alpn_protocols };
1629
+ }
1630
+ return { ...request, request_metadata: metadata };
1631
+ }
1632
+
1633
+ // src/bots/registry.generated.ts
1634
+ var BOT_REGISTRY = [
1635
+ { id: "reflectionbot", name: "Reflectionbot", category: "training_crawler", organization: "Reflection AI", baseScore: 70, respectsRobots: true, uaPatterns: ["reflectionbot"] },
1636
+ { id: "gptbot", name: "GPTBot", category: "training_crawler", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["gptbot"] },
1637
+ { id: "claudebot", name: "ClaudeBot", category: "training_crawler", organization: "Anthropic", baseScore: 85, respectsRobots: true, uaPatterns: ["claudebot"] },
1638
+ { id: "anthropic", name: "Anthropic", category: "training_crawler", organization: "Anthropic", baseScore: 85, respectsRobots: true, uaPatterns: ["anthropic-ai"] },
1639
+ { id: "claude-web", name: "Claude-Web", category: "training_crawler", organization: "Anthropic", baseScore: 85, respectsRobots: true, uaPatterns: ["claude-web"] },
1640
+ { id: "ccbot", name: "CCBot", category: "training_crawler", organization: "Common Crawl", baseScore: 80, respectsRobots: true, uaPatterns: ["ccbot"] },
1641
+ { id: "google-extended", name: "Google-Extended", category: "training_crawler", organization: "Google", baseScore: 80, respectsRobots: true, uaPatterns: ["google-extended"] },
1642
+ { id: "bytespider", name: "ByteSpider", category: "training_crawler", organization: "ByteDance", baseScore: 75, respectsRobots: false, uaPatterns: ["bytespider"] },
1643
+ { id: "amazonbot", name: "Amazonbot", category: "training_crawler", organization: "Amazon", baseScore: 70, respectsRobots: true, uaPatterns: ["amazonbot"] },
1644
+ { id: "facebookbot", name: "FacebookBot", category: "training_crawler", organization: "Meta", baseScore: 70, respectsRobots: true, uaPatterns: ["facebookbot"] },
1645
+ { id: "meta-externalagent", name: "Meta-ExternalAgent", category: "training_crawler", organization: "Meta", baseScore: 75, respectsRobots: true, uaPatterns: ["meta-externalagent"] },
1646
+ { id: "cohere-ai", name: "Cohere", category: "training_crawler", organization: "Cohere", baseScore: 80, respectsRobots: true, uaPatterns: ["cohere-ai", "cohere"] },
1647
+ { id: "applebot-extended", name: "Applebot-Extended", category: "training_crawler", organization: "Apple", baseScore: 75, respectsRobots: true, uaPatterns: ["applebot-extended"] },
1648
+ { id: "youbot", name: "YouBot", category: "training_crawler", organization: "You.com", baseScore: 75, respectsRobots: true, uaPatterns: ["youbot"] },
1649
+ { id: "mistral", name: "MistralBot", category: "training_crawler", organization: "Mistral AI", baseScore: 80, respectsRobots: true, uaPatterns: ["mistralbot"] },
1650
+ { id: "gemini", name: "Gemini", category: "training_crawler", organization: "Google", baseScore: 80, respectsRobots: true, uaPatterns: ["gemini"] },
1651
+ { id: "ai2bot", name: "AI2Bot", category: "training_crawler", organization: "Allen Institute for AI", baseScore: 75, respectsRobots: true, uaPatterns: ["ai2bot"] },
1652
+ { id: "deepseek", name: "DeepSeek", category: "training_crawler", organization: "DeepSeek", baseScore: 80, respectsRobots: true, uaPatterns: ["deepseek"] },
1653
+ { id: "qwen", name: "Qwen", category: "training_crawler", organization: "Alibaba", baseScore: 75, respectsRobots: true, uaPatterns: ["qwen"] },
1654
+ { id: "webzio", name: "Webz.io", category: "training_crawler", organization: "Webz.io", baseScore: 70, respectsRobots: false, uaPatterns: ["webzio"] },
1655
+ { id: "sentibot", name: "Sentibot", category: "training_crawler", organization: "Sentibot", baseScore: 70, respectsRobots: false, uaPatterns: ["sentibot"] },
1656
+ { id: "omgili", name: "Omgili", category: "training_crawler", organization: "Webz.io", baseScore: 70, respectsRobots: false, uaPatterns: ["omgili"] },
1657
+ { id: "img2dataset", name: "img2dataset", category: "training_crawler", organization: "LAION", baseScore: 75, respectsRobots: false, uaPatterns: ["img2dataset"] },
1658
+ { id: "timpibot", name: "Timpibot", category: "training_crawler", organization: "Timpi", baseScore: 70, respectsRobots: true, uaPatterns: ["timpibot"] },
1659
+ { id: "velenpublicwebcrawler", name: "VelenPublicWebCrawler", category: "training_crawler", organization: "Velen", baseScore: 70, respectsRobots: false, uaPatterns: ["velenpublicwebcrawler"] },
1660
+ { id: "isscyberriskcrawler", name: "ISSCyberRiskCrawler", category: "training_crawler", organization: "ISS", baseScore: 65, respectsRobots: false, uaPatterns: ["isscyberriskcrawler"] },
1661
+ { id: "friendlycrawler", name: "FriendlyCrawler", category: "training_crawler", organization: "Unknown", baseScore: 65, respectsRobots: true, uaPatterns: ["friendlycrawler"] },
1662
+ { id: "duckassistbot", name: "DuckAssistBot", category: "ai_search_crawler", organization: "DuckDuckGo", baseScore: 65, respectsRobots: true, uaPatterns: ["duckassistbot"] },
1663
+ { id: "sofyabot", name: "SofyaBot", category: "ai_search_crawler", organization: "Sofya", baseScore: 65, respectsRobots: true, uaPatterns: ["sofyabot"] },
1664
+ { id: "xai-searchbot", name: "xAI-SearchBot", category: "ai_search_crawler", organization: "xAI", baseScore: 70, respectsRobots: true, uaPatterns: ["xai-searchbot"] },
1665
+ { id: "linkupbot", name: "LinkupBot", category: "ai_search_crawler", organization: "Linkup", baseScore: 65, respectsRobots: true, uaPatterns: ["linkupbot"] },
1666
+ { id: "perplexitybot", name: "PerplexityBot", category: "ai_search_crawler", organization: "Perplexity AI", baseScore: 80, respectsRobots: true, uaPatterns: ["perplexitybot"] },
1667
+ { id: "claude-searchbot", name: "Claude-SearchBot", category: "ai_search_crawler", organization: "Anthropic", baseScore: 75, respectsRobots: true, uaPatterns: ["claude-searchbot"] },
1668
+ { id: "oai-searchbot", name: "OAI-SearchBot", category: "ai_search_crawler", organization: "OpenAI", baseScore: 80, respectsRobots: true, uaPatterns: ["oai-searchbot"] },
1669
+ { id: "searchgpt", name: "SearchGPT", category: "ai_search_crawler", organization: "OpenAI", baseScore: 75, respectsRobots: true, uaPatterns: ["searchgpt"] },
1670
+ { id: "phind", name: "Phind", category: "ai_search_crawler", organization: "Phind", baseScore: 70, respectsRobots: true, uaPatterns: ["phind"] },
1671
+ { id: "kagi", name: "Kagi", category: "ai_search_crawler", organization: "Kagi", baseScore: 65, respectsRobots: true, uaPatterns: ["kagi"] },
1672
+ { id: "exa", name: "Exa", category: "ai_search_crawler", organization: "Exa AI", baseScore: 70, respectsRobots: true, uaPatterns: ["exasearchbot", "exabot"] },
1673
+ { id: "shapbot", name: "ShapBot", category: "ai_search_crawler", organization: "Parallel Web Systems", baseScore: 65, respectsRobots: true, uaPatterns: ["shapbot"] },
1674
+ { id: "meta-webindexer", name: "Meta-WebIndexer", category: "ai_search_crawler", organization: "Meta", baseScore: 70, respectsRobots: true, uaPatterns: ["meta-webindexer"] },
1675
+ { id: "metaphor", name: "Metaphor", category: "ai_search_crawler", organization: "Metaphor", baseScore: 70, respectsRobots: true, uaPatterns: ["metaphor"] },
1676
+ { id: "tavily", name: "Tavily", category: "ai_search_crawler", organization: "Tavily", baseScore: 70, respectsRobots: true, uaPatterns: ["tavily"] },
1677
+ { id: "brave-search", name: "BraveSearch", category: "ai_search_crawler", organization: "Brave", baseScore: 65, respectsRobots: true, uaPatterns: ["bravesearch"] },
1678
+ { id: "neeva", name: "NeevaBot", category: "ai_search_crawler", organization: "Neeva", baseScore: 65, respectsRobots: true, uaPatterns: ["neevabot"] },
1679
+ { id: "operator", name: "Operator", category: "ai_agent", organization: "OpenAI", baseScore: 75, respectsRobots: true, uaPatterns: ["operator"] },
1680
+ { id: "claude-user", name: "Claude-User", category: "ai_agent", organization: "Anthropic", baseScore: 75, respectsRobots: true, uaPatterns: ["claude-user"] },
1681
+ { id: "gemini-user", name: "Gemini-User", category: "ai_agent", organization: "Google", baseScore: 75, respectsRobots: true, uaPatterns: ["gemini-user"] },
1682
+ { id: "googleagent-mariner", name: "GoogleAgent-Mariner", category: "ai_agent", organization: "Google", baseScore: 75, respectsRobots: true, uaPatterns: ["googleagent-mariner", "mariner"] },
1683
+ { id: "amazon-buyforme", name: "AmazonBuyForMe", category: "ai_agent", organization: "Amazon", baseScore: 70, respectsRobots: true, uaPatterns: ["amazonbuyforme", "buyforme"] },
1684
+ { id: "browser-use", name: "Browser-Use", category: "ai_agent", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["browser-use"] },
1685
+ { id: "stagehand", name: "Stagehand", category: "ai_agent", organization: "Browserbase", baseScore: 70, respectsRobots: false, uaPatterns: ["stagehand"] },
1686
+ { id: "manus-user", name: "Manus-User", category: "ai_agent", organization: "Manus", baseScore: 70, respectsRobots: false, uaPatterns: ["manus-user"] },
1687
+ { id: "multion", name: "MultiOn", category: "ai_agent", organization: "MultiOn", baseScore: 70, respectsRobots: false, uaPatterns: ["multion"] },
1688
+ { id: "iboubot", name: "IbouBot", category: "search_crawler", organization: "Ibou", baseScore: 30, respectsRobots: true, uaPatterns: ["iboubot"] },
1689
+ { id: "googlebot", name: "Googlebot", category: "search_crawler", organization: "Google", baseScore: 30, respectsRobots: true, uaPatterns: ["googlebot"] },
1690
+ { id: "google-inspectiontool", name: "Google-InspectionTool", category: "search_crawler", organization: "Google", baseScore: 30, respectsRobots: true, uaPatterns: ["google-inspectiontool"] },
1691
+ { id: "bingbot", name: "Bingbot", category: "search_crawler", organization: "Microsoft", baseScore: 30, respectsRobots: true, uaPatterns: ["bingbot"] },
1692
+ { id: "msnbot", name: "MSNBot", category: "search_crawler", organization: "Microsoft", baseScore: 30, respectsRobots: true, uaPatterns: ["msnbot"] },
1693
+ { id: "yandexbot", name: "YandexBot", category: "search_crawler", organization: "Yandex", baseScore: 35, respectsRobots: true, uaPatterns: ["yandexbot"] },
1694
+ { id: "baiduspider", name: "Baiduspider", category: "search_crawler", organization: "Baidu", baseScore: 40, respectsRobots: true, uaPatterns: ["baiduspider"] },
1695
+ { id: "petalbot", name: "PetalBot", category: "search_crawler", organization: "Huawei", baseScore: 40, respectsRobots: true, uaPatterns: ["petalbot"] },
1696
+ { id: "duckduckbot", name: "DuckDuckBot", category: "search_crawler", organization: "DuckDuckGo", baseScore: 30, respectsRobots: true, uaPatterns: ["duckduckbot"] },
1697
+ { id: "applebot", name: "Applebot", category: "search_crawler", organization: "Apple", baseScore: 30, respectsRobots: true, uaPatterns: ["applebot"] },
1698
+ { id: "sogou", name: "Sogou Spider", category: "search_crawler", organization: "Sogou", baseScore: 40, respectsRobots: true, uaPatterns: ["sogou"] },
1699
+ { id: "qwantify", name: "Qwantify", category: "search_crawler", organization: "Qwant", baseScore: 35, respectsRobots: true, uaPatterns: ["qwantify"] },
1700
+ { id: "naver", name: "Naver", category: "search_crawler", organization: "Naver", baseScore: 35, respectsRobots: true, uaPatterns: ["naver", "yeti"] },
1701
+ { id: "seznam", name: "SeznamBot", category: "search_crawler", organization: "Seznam", baseScore: 35, respectsRobots: true, uaPatterns: ["seznambot"] },
1702
+ { id: "ecosia", name: "Ecosia", category: "search_crawler", organization: "Ecosia", baseScore: 30, respectsRobots: true, uaPatterns: ["ecosia"] },
1703
+ { id: "mojeek", name: "MojeekBot", category: "search_crawler", organization: "Mojeek", baseScore: 35, respectsRobots: true, uaPatterns: ["mojeekbot"] },
1704
+ { id: "yahoo-slurp", name: "Yahoo! Slurp", category: "search_crawler", organization: "Yahoo", baseScore: 30, respectsRobots: true, uaPatterns: ["slurp"] },
1705
+ { id: "ahrefsbot", name: "AhrefsBot", category: "seo_crawler", organization: "Ahrefs", baseScore: 50, respectsRobots: true, uaPatterns: ["ahrefsbot", "ahrefs"] },
1706
+ { id: "semrushbot", name: "SemrushBot", category: "seo_crawler", organization: "Semrush", baseScore: 50, respectsRobots: true, uaPatterns: ["semrushbot", "semrush"] },
1707
+ { id: "mj12bot", name: "MJ12bot", category: "seo_crawler", organization: "Majestic", baseScore: 50, respectsRobots: true, uaPatterns: ["mj12bot"] },
1708
+ { id: "dotbot", name: "DotBot", category: "seo_crawler", organization: "Moz", baseScore: 50, respectsRobots: true, uaPatterns: ["dotbot"] },
1709
+ { id: "rogerbot", name: "Rogerbot", category: "seo_crawler", organization: "Moz", baseScore: 50, respectsRobots: true, uaPatterns: ["rogerbot"] },
1710
+ { id: "screaming-frog", name: "Screaming Frog", category: "seo_crawler", organization: "Screaming Frog", baseScore: 55, respectsRobots: true, uaPatterns: ["screaming frog"] },
1711
+ { id: "sitebulb", name: "Sitebulb", category: "seo_crawler", organization: "Sitebulb", baseScore: 55, respectsRobots: true, uaPatterns: ["sitebulb"] },
1712
+ { id: "deepcrawl", name: "DeepCrawl", category: "seo_crawler", organization: "Lumar", baseScore: 50, respectsRobots: true, uaPatterns: ["deepcrawl"] },
1713
+ { id: "oncrawl", name: "OnCrawl", category: "seo_crawler", organization: "OnCrawl", baseScore: 50, respectsRobots: true, uaPatterns: ["oncrawl"] },
1714
+ { id: "botify", name: "Botify", category: "seo_crawler", organization: "Botify", baseScore: 50, respectsRobots: true, uaPatterns: ["botify"] },
1715
+ { id: "contentking", name: "ContentKing", category: "seo_crawler", organization: "ContentKing", baseScore: 50, respectsRobots: true, uaPatterns: ["contentking"] },
1716
+ { id: "sistrix", name: "SISTRIX", category: "seo_crawler", organization: "SISTRIX", baseScore: 50, respectsRobots: true, uaPatterns: ["sistrix"] },
1717
+ { id: "serpstat", name: "Serpstat", category: "seo_crawler", organization: "Serpstat", baseScore: 50, respectsRobots: true, uaPatterns: ["serpstat"] },
1718
+ { id: "spyfu", name: "SpyFu", category: "seo_crawler", organization: "SpyFu", baseScore: 50, respectsRobots: true, uaPatterns: ["spyfu"] },
1719
+ { id: "nessus", name: "Nessus", category: "security_scanner", organization: "Tenable", baseScore: 70, respectsRobots: false, uaPatterns: ["nessus"] },
1720
+ { id: "qualys", name: "Qualys", category: "security_scanner", organization: "Qualys", baseScore: 70, respectsRobots: false, uaPatterns: ["qualys"] },
1721
+ { id: "shodan", name: "Shodan", category: "security_scanner", organization: "Shodan", baseScore: 75, respectsRobots: false, uaPatterns: ["shodan"] },
1722
+ { id: "censys", name: "Censys", category: "security_scanner", organization: "Censys", baseScore: 75, respectsRobots: false, uaPatterns: ["censys"] },
1723
+ { id: "nmap", name: "Nmap", category: "security_scanner", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["nmap"] },
1724
+ { id: "zap", name: "OWASP ZAP", category: "security_scanner", organization: "OWASP", baseScore: 70, respectsRobots: false, uaPatterns: ["zap/"] },
1725
+ { id: "burp", name: "Burp Suite", category: "security_scanner", organization: "PortSwigger", baseScore: 70, respectsRobots: false, uaPatterns: ["burp"] },
1726
+ { id: "nikto", name: "Nikto", category: "security_scanner", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["nikto"] },
1727
+ { id: "nuclei", name: "Nuclei", category: "security_scanner", organization: "ProjectDiscovery", baseScore: 70, respectsRobots: false, uaPatterns: ["nuclei"] },
1728
+ { id: "acunetix", name: "Acunetix", category: "security_scanner", organization: "Invicti", baseScore: 70, respectsRobots: false, uaPatterns: ["acunetix"] },
1729
+ { id: "netsparker", name: "Netsparker", category: "security_scanner", organization: "Invicti", baseScore: 70, respectsRobots: false, uaPatterns: ["netsparker"] },
1730
+ { id: "detectify", name: "Detectify", category: "security_scanner", organization: "Detectify", baseScore: 65, respectsRobots: false, uaPatterns: ["detectify"] },
1731
+ { id: "intruder", name: "Intruder", category: "security_scanner", organization: "Intruder", baseScore: 65, respectsRobots: false, uaPatterns: ["intruder"] },
1732
+ { id: "python-requests", name: "Python-Requests", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["python-requests"] },
1733
+ { id: "python-urllib", name: "Python-urllib", category: "generic_scraper", organization: "Python", baseScore: 55, respectsRobots: false, uaPatterns: ["python-urllib"] },
1734
+ { id: "python", name: "Python", category: "generic_scraper", organization: "Python", baseScore: 50, respectsRobots: false, uaPatterns: ["python/"] },
1735
+ { id: "scrapy", name: "Scrapy", category: "generic_scraper", organization: "Scrapy", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapy"] },
1736
+ { id: "httpx", name: "HTTPX", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["httpx"] },
1737
+ { id: "aiohttp", name: "aiohttp", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["aiohttp"] },
1738
+ { id: "beautifulsoup", name: "BeautifulSoup", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["beautifulsoup"] },
1739
+ { id: "node-fetch", name: "node-fetch", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["node-fetch"] },
1740
+ { id: "axios", name: "Axios", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["axios/"] },
1741
+ { id: "got", name: "Got", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["got/"] },
1742
+ { id: "undici", name: "Undici", category: "generic_scraper", organization: "Node.js", baseScore: 55, respectsRobots: false, uaPatterns: ["undici"] },
1743
+ { id: "go-http-client", name: "Go-HTTP-Client", category: "generic_scraper", organization: "Go", baseScore: 55, respectsRobots: false, uaPatterns: ["go-http-client"] },
1744
+ { id: "colly", name: "Colly", category: "generic_scraper", organization: "Open Source", baseScore: 65, respectsRobots: true, uaPatterns: ["colly"] },
1745
+ { id: "java", name: "Java", category: "generic_scraper", organization: "Oracle", baseScore: 50, respectsRobots: false, uaPatterns: ["java/"] },
1746
+ { id: "okhttp", name: "OkHttp", category: "generic_scraper", organization: "Square", baseScore: 55, respectsRobots: false, uaPatterns: ["okhttp"] },
1747
+ { id: "apache-httpclient", name: "Apache-HttpClient", category: "generic_scraper", organization: "Apache", baseScore: 55, respectsRobots: false, uaPatterns: ["apache-httpclient"] },
1748
+ { id: "jsoup", name: "Jsoup", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["jsoup"] },
1749
+ { id: "guzzlehttp", name: "GuzzleHttp", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["guzzlehttp"] },
1750
+ { id: "php", name: "PHP", category: "generic_scraper", organization: "PHP", baseScore: 50, respectsRobots: false, uaPatterns: ["php/"] },
1751
+ { id: "ruby", name: "Ruby", category: "generic_scraper", organization: "Ruby", baseScore: 50, respectsRobots: false, uaPatterns: ["ruby"] },
1752
+ { id: "faraday", name: "Faraday", category: "generic_scraper", organization: "Open Source", baseScore: 55, respectsRobots: false, uaPatterns: ["faraday"] },
1753
+ { id: "mechanize", name: "Mechanize", category: "generic_scraper", organization: "Open Source", baseScore: 60, respectsRobots: false, uaPatterns: ["mechanize"] },
1754
+ { id: "headlesschrome", name: "HeadlessChrome", category: "headless_browser", organization: "Google", baseScore: 70, respectsRobots: false, uaPatterns: ["headlesschrome"] },
1755
+ { id: "puppeteer", name: "Puppeteer", category: "headless_browser", organization: "Google", baseScore: 70, respectsRobots: false, uaPatterns: ["puppeteer"] },
1756
+ { id: "playwright", name: "Playwright", category: "headless_browser", organization: "Microsoft", baseScore: 70, respectsRobots: false, uaPatterns: ["playwright"] },
1757
+ { id: "selenium", name: "Selenium", category: "headless_browser", organization: "Open Source", baseScore: 70, respectsRobots: false, uaPatterns: ["selenium"] },
1758
+ { id: "phantomjs", name: "PhantomJS", category: "headless_browser", organization: "Open Source", baseScore: 75, respectsRobots: false, uaPatterns: ["phantomjs"] },
1759
+ { id: "splash", name: "Splash", category: "headless_browser", organization: "Scrapinghub", baseScore: 70, respectsRobots: false, uaPatterns: ["splash"] },
1760
+ { id: "browserless", name: "Browserless", category: "headless_browser", organization: "Browserless", baseScore: 65, respectsRobots: false, uaPatterns: ["browserless"] },
1761
+ { id: "browserbase", name: "Browserbase", category: "headless_browser", organization: "Browserbase", baseScore: 65, respectsRobots: false, uaPatterns: ["browserbase"] },
1762
+ { id: "ia-archiver", name: "Internet Archive", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["ia_archiver"] },
1763
+ { id: "archive-org-bot", name: "Archive.org", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["archive.org_bot"] },
1764
+ { id: "wayback", name: "Wayback Machine", category: "archiver", organization: "Internet Archive", baseScore: 25, respectsRobots: true, uaPatterns: ["wayback"] },
1765
+ { id: "heritrix", name: "Heritrix", category: "archiver", organization: "Internet Archive", baseScore: 30, respectsRobots: true, uaPatterns: ["heritrix"] },
1766
+ { id: "brozzler", name: "Brozzler", category: "archiver", organization: "Internet Archive", baseScore: 30, respectsRobots: true, uaPatterns: ["brozzler"] },
1767
+ { id: "facebookexternalhit", name: "Facebook", category: "fetcher", organization: "Meta", baseScore: 25, respectsRobots: true, uaPatterns: ["facebookexternalhit"] },
1768
+ { id: "facebot", name: "Facebot", category: "fetcher", organization: "Meta", baseScore: 25, respectsRobots: true, uaPatterns: ["facebot"] },
1769
+ { id: "twitterbot", name: "Twitterbot", category: "fetcher", organization: "X Corp", baseScore: 25, respectsRobots: true, uaPatterns: ["twitterbot"] },
1770
+ { id: "linkedinbot", name: "LinkedInBot", category: "fetcher", organization: "LinkedIn", baseScore: 25, respectsRobots: true, uaPatterns: ["linkedinbot"] },
1771
+ { id: "slackbot", name: "Slackbot", category: "fetcher", organization: "Slack", baseScore: 25, respectsRobots: true, uaPatterns: ["slackbot"] },
1772
+ { id: "telegrambot", name: "TelegramBot", category: "fetcher", organization: "Telegram", baseScore: 25, respectsRobots: true, uaPatterns: ["telegrambot"] },
1773
+ { id: "whatsapp", name: "WhatsApp", category: "fetcher", organization: "Meta", baseScore: 25, respectsRobots: true, uaPatterns: ["whatsapp"] },
1774
+ { id: "discordbot", name: "Discordbot", category: "fetcher", organization: "Discord", baseScore: 25, respectsRobots: true, uaPatterns: ["discordbot"] },
1775
+ { id: "pinterestbot", name: "Pinterest", category: "fetcher", organization: "Pinterest", baseScore: 30, respectsRobots: true, uaPatterns: ["pinterest"] },
1776
+ { id: "tumblr", name: "Tumblr", category: "fetcher", organization: "Automattic", baseScore: 30, respectsRobots: true, uaPatterns: ["tumblr"] },
1777
+ { id: "reddit", name: "Reddit", category: "fetcher", organization: "Reddit", baseScore: 30, respectsRobots: true, uaPatterns: ["reddit"] },
1778
+ { id: "embedly", name: "Embedly", category: "fetcher", organization: "Medium", baseScore: 30, respectsRobots: true, uaPatterns: ["embedly"] },
1779
+ { id: "iframely", name: "Iframely", category: "fetcher", organization: "Iframely", baseScore: 30, respectsRobots: true, uaPatterns: ["iframely"] },
1780
+ { id: "curl", name: "cURL", category: "fetcher", organization: "Open Source", baseScore: 45, respectsRobots: false, uaPatterns: ["curl/"] },
1781
+ { id: "wget", name: "Wget", category: "fetcher", organization: "GNU", baseScore: 45, respectsRobots: false, uaPatterns: ["wget/"] },
1782
+ { id: "libwww-perl", name: "libwww-perl", category: "fetcher", organization: "Perl", baseScore: 50, respectsRobots: false, uaPatterns: ["libwww-perl"] },
1783
+ { id: "lwp", name: "LWP", category: "fetcher", organization: "Perl", baseScore: 50, respectsRobots: false, uaPatterns: ["lwp-"] },
1784
+ { id: "httrack", name: "HTTrack", category: "fetcher", organization: "Open Source", baseScore: 60, respectsRobots: true, uaPatterns: ["httrack"] },
1785
+ { id: "webdecoybot", name: "WebDecoyBot", category: "monitoring", organization: "WebDecoy", baseScore: 5, respectsRobots: true, uaPatterns: ["webdecoybot"] },
1786
+ { id: "uptimerobot", name: "UptimeRobot", category: "monitoring", organization: "UptimeRobot", baseScore: 20, respectsRobots: true, uaPatterns: ["uptimerobot"] },
1787
+ { id: "pingdom", name: "Pingdom", category: "monitoring", organization: "SolarWinds", baseScore: 20, respectsRobots: true, uaPatterns: ["pingdom"] },
1788
+ { id: "statuscake", name: "StatusCake", category: "monitoring", organization: "StatusCake", baseScore: 20, respectsRobots: true, uaPatterns: ["statuscake"] },
1789
+ { id: "better-uptime", name: "Better Uptime", category: "monitoring", organization: "Better Stack", baseScore: 20, respectsRobots: true, uaPatterns: ["betteruptime"] },
1790
+ { id: "datadog-synthetics", name: "Datadog Synthetics", category: "monitoring", organization: "Datadog", baseScore: 25, respectsRobots: true, uaPatterns: ["datadog"] },
1791
+ { id: "newrelic", name: "New Relic", category: "monitoring", organization: "New Relic", baseScore: 25, respectsRobots: true, uaPatterns: ["newrelic"] },
1792
+ { id: "site24x7", name: "Site24x7", category: "monitoring", organization: "Zoho", baseScore: 20, respectsRobots: true, uaPatterns: ["site24x7"] },
1793
+ { id: "freshping", name: "Freshping", category: "monitoring", organization: "Freshworks", baseScore: 20, respectsRobots: true, uaPatterns: ["freshping"] },
1794
+ { id: "hetrixtools", name: "HetrixTools", category: "monitoring", organization: "HetrixTools", baseScore: 20, respectsRobots: true, uaPatterns: ["hetrixtools"] },
1795
+ { id: "nodeping", name: "NodePing", category: "monitoring", organization: "NodePing", baseScore: 20, respectsRobots: true, uaPatterns: ["nodeping"] },
1796
+ { id: "gtmetrix", name: "GTmetrix", category: "monitoring", organization: "GTmetrix", baseScore: 20, respectsRobots: true, uaPatterns: ["gtmetrix"] },
1797
+ { id: "chrome-lighthouse", name: "Lighthouse", category: "monitoring", organization: "Google", baseScore: 20, respectsRobots: true, uaPatterns: ["chrome-lighthouse", "google page speed"] },
1798
+ { id: "feedly", name: "Feedly", category: "feed_reader", organization: "Feedly", baseScore: 25, respectsRobots: true, uaPatterns: ["feedly"] },
1799
+ { id: "feedfetcher-google", name: "Feedfetcher-Google", category: "feed_reader", organization: "Google", baseScore: 25, respectsRobots: true, uaPatterns: ["feedfetcher"] },
1800
+ { id: "newsblur", name: "NewsBlur", category: "feed_reader", organization: "NewsBlur", baseScore: 25, respectsRobots: true, uaPatterns: ["newsblur"] },
1801
+ { id: "inoreader", name: "Inoreader", category: "feed_reader", organization: "Inoreader", baseScore: 25, respectsRobots: true, uaPatterns: ["inoreader"] },
1802
+ { id: "theoldreader", name: "The Old Reader", category: "feed_reader", organization: "The Old Reader", baseScore: 25, respectsRobots: true, uaPatterns: ["theoldreader"] },
1803
+ { id: "feedbin", name: "Feedbin", category: "feed_reader", organization: "Feedbin", baseScore: 25, respectsRobots: true, uaPatterns: ["feedbin"] },
1804
+ { id: "miniflux", name: "Miniflux", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["miniflux"] },
1805
+ { id: "freshrss", name: "FreshRSS", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["freshrss"] },
1806
+ { id: "commafeed", name: "CommaFeed", category: "feed_reader", organization: "Open Source", baseScore: 25, respectsRobots: true, uaPatterns: ["commafeed"] },
1807
+ { id: "diffbot", name: "Diffbot", category: "commercial_scraper", organization: "Diffbot", baseScore: 70, respectsRobots: true, uaPatterns: ["diffbot"] },
1808
+ { id: "import-io", name: "Import.io", category: "commercial_scraper", organization: "Import.io", baseScore: 65, respectsRobots: true, uaPatterns: ["import.io"] },
1809
+ { id: "bright-data", name: "Bright Data", category: "commercial_scraper", organization: "Bright Data", baseScore: 70, respectsRobots: false, uaPatterns: ["brightdata", "luminati"] },
1810
+ { id: "oxylabs", name: "Oxylabs", category: "commercial_scraper", organization: "Oxylabs", baseScore: 70, respectsRobots: false, uaPatterns: ["oxylabs"] },
1811
+ { id: "scrapingbee", name: "ScrapingBee", category: "commercial_scraper", organization: "ScrapingBee", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapingbee"] },
1812
+ { id: "scrapingant", name: "ScrapingAnt", category: "commercial_scraper", organization: "ScrapingAnt", baseScore: 65, respectsRobots: true, uaPatterns: ["scrapingant"] },
1813
+ { id: "zyte", name: "Zyte", category: "commercial_scraper", organization: "Zyte", baseScore: 65, respectsRobots: true, uaPatterns: ["zyte", "scrapinghub"] },
1814
+ { id: "apify", name: "Apify", category: "commercial_scraper", organization: "Apify", baseScore: 65, respectsRobots: true, uaPatterns: ["apify"] },
1815
+ { id: "crawlbase", name: "Crawlbase", category: "commercial_scraper", organization: "Crawlbase", baseScore: 65, respectsRobots: true, uaPatterns: ["crawlbase"] },
1816
+ { id: "webscrapingapi", name: "WebScrapingAPI", category: "commercial_scraper", organization: "WebScrapingAPI", baseScore: 65, respectsRobots: true, uaPatterns: ["webscrapingapi"] },
1817
+ { id: "chatgpt-user", name: "ChatGPT-User", category: "ai_assistant", organization: "OpenAI", baseScore: 85, respectsRobots: true, uaPatterns: ["chatgpt-user"] },
1818
+ { id: "perplexity-user", name: "Perplexity-User", category: "ai_assistant", organization: "Perplexity AI", baseScore: 75, respectsRobots: false, uaPatterns: ["perplexity-user"] },
1819
+ { id: "mistralai-user", name: "MistralAI-User", category: "ai_assistant", organization: "Mistral AI", baseScore: 75, respectsRobots: true, uaPatterns: ["mistralai-user"] },
1820
+ { id: "exauser", name: "ExaUser", category: "ai_assistant", organization: "Exa AI", baseScore: 70, respectsRobots: false, uaPatterns: ["exauser"] },
1821
+ { id: "shap-user", name: "Shap-User", category: "ai_assistant", organization: "Parallel Web Systems", baseScore: 65, respectsRobots: false, uaPatterns: ["shap-user"] },
1822
+ { id: "meta-externalfetcher", name: "Meta-ExternalFetcher", category: "ai_assistant", organization: "Meta", baseScore: 70, respectsRobots: false, uaPatterns: ["meta-externalfetcher"] },
1823
+ { id: "gemini-deep-research", name: "Gemini-Deep-Research", category: "ai_assistant", organization: "Google", baseScore: 65, respectsRobots: true, uaPatterns: ["gemini-deep-research"] },
1824
+ { id: "copilot", name: "Microsoft Copilot", category: "ai_assistant", organization: "Microsoft", baseScore: 65, respectsRobots: true, uaPatterns: ["copilot"] },
1825
+ { id: "cortana", name: "Cortana", category: "ai_assistant", organization: "Microsoft", baseScore: 60, respectsRobots: true, uaPatterns: ["cortana"] },
1826
+ { id: "siri", name: "Siri", category: "ai_assistant", organization: "Apple", baseScore: 60, respectsRobots: true, uaPatterns: ["siri"] }
1827
+ ];
1828
+
1829
+ // src/bots/index.ts
1830
+ var AI_CATEGORIES = /* @__PURE__ */ new Set([
1831
+ "training_crawler",
1832
+ "ai_search_crawler",
1833
+ "ai_agent",
1834
+ "ai_assistant"
1835
+ ]);
1836
+ var UNKNOWN = Object.freeze({
1837
+ known: false,
1838
+ category: "none",
1839
+ score: 0,
1840
+ isAI: false
1841
+ });
1842
+ var MAX_CACHE = 1e3;
1843
+ var cache = /* @__PURE__ */ new Map();
1844
+ function matchUserAgent(userAgent) {
1845
+ if (!userAgent) return void 0;
1846
+ const cached = cache.get(userAgent);
1847
+ if (cached !== void 0) return cached ?? void 0;
1848
+ const ua = userAgent.toLowerCase();
1849
+ let found = null;
1850
+ for (const agent of BOT_REGISTRY) {
1851
+ for (const pattern of agent.uaPatterns) {
1852
+ if (ua.includes(pattern)) {
1853
+ found = agent;
1854
+ break;
1855
+ }
1856
+ }
1857
+ if (found) break;
1858
+ }
1859
+ if (cache.size >= MAX_CACHE) cache.clear();
1860
+ cache.set(userAgent, found);
1861
+ return found ?? void 0;
1862
+ }
1863
+ function classifyUserAgent(userAgent) {
1864
+ const agent = matchUserAgent(userAgent);
1865
+ if (!agent) return UNKNOWN;
1866
+ return {
1867
+ known: true,
1868
+ id: agent.id,
1869
+ name: agent.name,
1870
+ category: agent.category,
1871
+ organization: agent.organization,
1872
+ score: agent.baseScore,
1873
+ respectsRobots: agent.respectsRobots,
1874
+ isAI: AI_CATEGORIES.has(agent.category)
1875
+ };
1876
+ }
1877
+
1878
+ // src/local-analysis.ts
1879
+ var DATACENTER_RANGES = [
1880
+ // AWS
1881
+ "3.0.0.0/8",
1882
+ "13.0.0.0/8",
1883
+ "18.0.0.0/8",
1884
+ "52.0.0.0/8",
1885
+ "54.0.0.0/8",
1886
+ // Google Cloud
1887
+ "34.0.0.0/8",
1888
+ "35.0.0.0/8",
1889
+ // Azure
1890
+ "13.64.0.0/11",
1891
+ "20.0.0.0/8",
1892
+ "40.0.0.0/8",
1893
+ "104.0.0.0/8",
1894
+ // DigitalOcean
1895
+ "159.65.0.0/16",
1896
+ "178.62.0.0/16",
1897
+ // Hetzner
1898
+ "88.99.0.0/16",
1899
+ "116.203.0.0/16"
1900
+ ];
1901
+ var SUSPICIOUS_PATTERNS = {
1902
+ userAgents: [
1903
+ /bot/i,
1904
+ /crawler/i,
1905
+ /spider/i,
1906
+ /scraper/i,
1907
+ /curl/i,
1908
+ /wget/i,
1909
+ /python/i,
1910
+ /java/i,
1911
+ /go-http-client/i,
1912
+ /axios/i,
1913
+ /okhttp/i
1914
+ ],
1915
+ missingHeaders: [
1916
+ "accept",
1917
+ "accept-language",
1918
+ "accept-encoding"
1919
+ ]
1920
+ };
1921
+ function isIPInRange(ip, cidr) {
1922
+ const ipParts = ip.split(".").map(Number);
1923
+ const [range, bits] = cidr.split("/");
1924
+ const rangeParts = range.split(".").map(Number);
1925
+ const mask = ~(2 ** (32 - parseInt(bits)) - 1);
1926
+ const ipNum = (ipParts[0] << 24) + (ipParts[1] << 16) + (ipParts[2] << 8) + ipParts[3];
1927
+ const rangeNum = (rangeParts[0] << 24) + (rangeParts[1] << 16) + (rangeParts[2] << 8) + rangeParts[3];
1928
+ return (ipNum & mask) === (rangeNum & mask);
1929
+ }
1930
+ function isDatacenterIP(ip) {
1931
+ if (ip.includes(":")) {
1932
+ return false;
1933
+ }
1934
+ return DATACENTER_RANGES.some((range) => isIPInRange(ip, range));
1935
+ }
1936
+ function hasSuspiciousHeaders(metadata) {
1937
+ const userAgent = metadata.user_agent || "";
1938
+ const headers = metadata.headers || {};
1939
+ const hasBotUA = SUSPICIOUS_PATTERNS.userAgents.some((pattern) => pattern.test(userAgent)) || matchUserAgent(userAgent) !== void 0;
1940
+ const missingCommonHeaders = SUSPICIOUS_PATTERNS.missingHeaders.filter(
1941
+ (header2) => !headers[header2] && !headers[header2.toLowerCase()]
1942
+ );
1943
+ return hasBotUA || missingCommonHeaders.length > 0;
1944
+ }
1945
+ function isMissingSecCHUA(metadata) {
1946
+ const headers = metadata.headers || {};
1947
+ return !headers["sec-ch-ua"] && !headers["Sec-CH-UA"];
1948
+ }
1949
+ function calculateLocalScore(suspiciousHeaders, missingSecCHUA, datacenterIP) {
1950
+ let score = 0;
1951
+ if (suspiciousHeaders) score += 30;
1952
+ if (missingSecCHUA) score += 20;
1953
+ if (datacenterIP) score += 40;
1954
+ return Math.min(score, 100);
1955
+ }
1956
+ function needsVerification(suspiciousHeaders, hasTLSInfo) {
1957
+ return hasTLSInfo || suspiciousHeaders;
1958
+ }
1959
+ function buildFlags(suspiciousHeaders, missingSecCHUA, datacenterIP, metadata) {
1960
+ const flags = [];
1961
+ if (suspiciousHeaders) {
1962
+ flags.push("suspicious_headers");
1963
+ }
1964
+ if (missingSecCHUA) {
1965
+ flags.push("missing_sec_ch_ua");
1966
+ }
1967
+ if (datacenterIP) {
1968
+ flags.push("datacenter_ip");
1969
+ }
1970
+ const headerCount = Object.keys(metadata.headers || {}).length;
1971
+ if (headerCount < 5) {
1972
+ flags.push("minimal_headers");
1973
+ }
1974
+ if (!metadata.headers?.referer && !metadata.headers?.Referer) {
1975
+ flags.push("missing_referer");
1976
+ }
1977
+ return flags;
1978
+ }
1979
+ function analyzeRequest(metadata) {
1980
+ const suspiciousHeaders = hasSuspiciousHeaders(metadata);
1981
+ const missingSecCHUA = isMissingSecCHUA(metadata);
1982
+ const datacenterIP = isDatacenterIP(metadata.ip);
1983
+ const localScore = calculateLocalScore(suspiciousHeaders, missingSecCHUA, datacenterIP);
1984
+ const hasTLSInfo = Boolean(metadata.tls_info);
1985
+ const needsVerify = needsVerification(suspiciousHeaders, hasTLSInfo);
1986
+ const flags = buildFlags(suspiciousHeaders, missingSecCHUA, datacenterIP, metadata);
1987
+ return {
1988
+ suspicious_headers: suspiciousHeaders,
1989
+ missing_sec_ch_ua: missingSecCHUA,
1990
+ datacenter_ip: datacenterIP,
1991
+ local_score: localScore,
1992
+ needs_verification: needsVerify,
1993
+ flags
1994
+ };
1995
+ }
1996
+
1997
+ // src/rules/rule-engine.ts
1998
+ function extractClearance(headers) {
1999
+ const cookie = headers["cookie"];
2000
+ if (!cookie) return void 0;
2001
+ for (const part of cookie.split(";")) {
2002
+ const eq = part.indexOf("=");
2003
+ if (eq < 0) continue;
2004
+ if (part.slice(0, eq).trim() === "wd_clearance") {
2005
+ return part.slice(eq + 1).trim() || void 0;
2006
+ }
2007
+ }
2008
+ return void 0;
2009
+ }
2010
+ var RuleEngine = class {
2011
+ constructor(rules) {
2012
+ this.rules = rules;
2013
+ }
2014
+ /**
2015
+ * Append a rule after construction.
2016
+ *
2017
+ * Exists for signals that cannot be known synchronously at construction —
2018
+ * currently the site honeytoken, whose path is derived by async HMAC.
2019
+ * Evaluation order is append order, matching the constructor.
2020
+ */
2021
+ add(rule) {
2022
+ this.rules.push(rule);
2023
+ }
2024
+ /**
2025
+ * Evaluate all rules against the request context.
2026
+ * First DENY or THROTTLE result wins. Violations are recorded for all non-ALLOW results.
2027
+ */
2028
+ evaluate(context) {
2029
+ const violations = [];
2030
+ const results = [];
2031
+ let decidingResult = null;
2032
+ for (const rule of this.rules) {
2033
+ const result = rule.evaluate(context);
2034
+ const dryRun = result.metadata?.dryRun === true;
2035
+ results.push({
2036
+ rule: result.rule,
2037
+ state: result.state ?? (dryRun ? "DRY_RUN" : "RUN"),
2038
+ conclusion: dryRun || result.action !== "ALLOW" ? "DENY" : "ALLOW",
2039
+ action: result.action,
2040
+ reason: result.reason,
2041
+ metadata: result.metadata
2042
+ });
2043
+ if (result.action !== "ALLOW") {
2044
+ violations.push({
2045
+ rule: result.rule,
2046
+ action: result.action,
2047
+ ip: context.ip,
2048
+ path: context.path,
2049
+ method: context.method,
2050
+ userAgent: context.userAgent,
2051
+ reason: result.reason,
2052
+ clearance: result.rule === "tripwire" ? extractClearance(context.headers) : void 0,
2053
+ metadata: result.metadata,
2054
+ dryRun,
2055
+ timestamp: new Date(context.timestamp).toISOString()
2056
+ });
2057
+ if (!decidingResult && !dryRun) {
2058
+ decidingResult = result;
2059
+ }
2060
+ }
2061
+ }
2062
+ if (decidingResult) {
2063
+ return {
2064
+ action: decidingResult.action,
2065
+ rule: decidingResult.rule,
2066
+ reason: decidingResult.reason,
2067
+ metadata: decidingResult.metadata,
2068
+ violations,
2069
+ results
2070
+ };
2071
+ }
2072
+ return {
2073
+ action: "ALLOW",
2074
+ violations,
2075
+ results
2076
+ };
2077
+ }
2078
+ /**
2079
+ * Clean up all rule resources
2080
+ */
2081
+ destroy() {
2082
+ for (const rule of this.rules) {
2083
+ rule.destroy?.();
2084
+ }
2085
+ }
2086
+ };
2087
+
2088
+ // src/rules/tripwire-rule.ts
2089
+ var DEFAULT_TRIPWIRE_PATHS = [
2090
+ "/.git/config",
2091
+ "/.git/HEAD",
2092
+ "/.env",
2093
+ "/.env.local",
2094
+ "/.env.production",
2095
+ "/wp-config.php",
2096
+ "/config.php",
2097
+ "/.aws/credentials",
2098
+ "/.ssh/id_rsa",
2099
+ "/backup.zip",
2100
+ "/backup.sql",
2101
+ "/database.sql",
2102
+ "/dump.sql",
2103
+ "/.DS_Store",
2104
+ "/phpinfo.php",
2105
+ "/server-status",
2106
+ "/actuator/env",
2107
+ "/.vscode/sftp.json"
2108
+ ];
2109
+ function canonicalizeTripwirePath(path) {
2110
+ const noQuery = path.split("?")[0].split("#")[0];
2111
+ return cleanSlashesAndDots(decodePercentAscii(noQuery));
2112
+ }
2113
+ function decodePercentAscii(s) {
2114
+ for (let i = 0; i < 4; i++) {
2115
+ const next = decodePercentAsciiOnce(s);
2116
+ if (next === s) break;
2117
+ s = next;
2118
+ }
2119
+ return s;
2120
+ }
2121
+ function decodePercentAsciiOnce(s) {
2122
+ if (!s.includes("%")) return s;
2123
+ let out = "";
2124
+ for (let i = 0; i < s.length; i++) {
2125
+ if (s[i] === "%" && i + 2 < s.length) {
2126
+ const hi = unhexNibble(s.charCodeAt(i + 1));
2127
+ const lo = unhexNibble(s.charCodeAt(i + 2));
2128
+ if (hi >= 0 && lo >= 0) {
2129
+ const v = hi << 4 | lo;
2130
+ if (v < 128) {
2131
+ out += String.fromCharCode(v);
2132
+ i += 2;
2133
+ continue;
2134
+ }
2135
+ }
2136
+ }
2137
+ out += s[i];
2138
+ }
2139
+ return out;
2140
+ }
2141
+ function unhexNibble(c) {
2142
+ if (c >= 48 && c <= 57) return c - 48;
2143
+ if (c >= 97 && c <= 102) return c - 97 + 10;
2144
+ if (c >= 65 && c <= 70) return c - 65 + 10;
2145
+ return -1;
2146
+ }
2147
+ function cleanSlashesAndDots(s) {
2148
+ if (s === "") return s;
2149
+ const hadTrailing = s.length > 1 && s[s.length - 1] === "/";
2150
+ const stack = [];
2151
+ for (const p of s.split("/")) {
2152
+ if (p === "" || p === ".") continue;
2153
+ if (p === "..") {
2154
+ if (stack.length > 0) stack.pop();
2155
+ continue;
2156
+ }
2157
+ stack.push(p);
2158
+ }
2159
+ let res = "/" + stack.join("/");
2160
+ if (hadTrailing && res !== "/") res += "/";
2161
+ return res;
2162
+ }
2163
+ var TripwireRule = class {
2164
+ constructor(config = {}) {
2165
+ this.name = "tripwire";
2166
+ const paths = [...config.paths ?? []];
2167
+ if (config.includeDefaults ?? true) paths.push(...DEFAULT_TRIPWIRE_PATHS);
2168
+ this.exact = new Set(paths.map(canonicalizeTripwirePath));
2169
+ this.prefixes = (config.prefixes ?? []).map(canonicalizeTripwirePath);
2170
+ this.patterns = config.patterns ?? [];
2171
+ this.action = config.action ?? "DENY";
2172
+ this.dryRun = config.dryRun ?? false;
2173
+ }
2174
+ evaluate(context) {
2175
+ const path = canonicalizeTripwirePath(context.path);
2176
+ const hit = this.exact.has(path) || this.prefixes.some((prefix) => path.startsWith(prefix)) || this.patterns.some((re2) => re2.test(path));
2177
+ if (hit) {
2178
+ return {
2179
+ action: this.dryRun ? "ALLOW" : this.action,
2180
+ rule: this.name,
2181
+ reason: `Tripwire hit: ${path} \u2014 hidden honeypot path, deterministic automated-intent signal`,
2182
+ metadata: { path, dryRun: this.dryRun, confidence: 100 }
2183
+ };
2184
+ }
2185
+ return { action: "ALLOW", rule: this.name };
2186
+ }
2187
+ };
2188
+
2189
+ // src/rules/attack-signatures.ts
2190
+ var SIGNATURES = [
2191
+ // --- SQL injection -------------------------------------------------------
2192
+ { id: "sqli_union", label: "SQL UNION SELECT", test: /\bunion\b[\s/*]+\bselect\b/i },
2193
+ {
2194
+ id: "sqli_tautology",
2195
+ label: "SQL tautology",
2196
+ // ' OR 1=1 / " or 'a'='a — the quote is required, which is what keeps this
2197
+ // off ordinary query strings containing "or".
2198
+ test: /['"`]\s*(?:or|and)\s+(?:\d+\s*=\s*\d+|['"`][^'"`]{0,32}['"`]\s*=\s*['"`])/i
2199
+ },
2200
+ {
2201
+ id: "sqli_stacked",
2202
+ label: "Stacked SQL statement",
2203
+ test: /;\s*(?:drop|truncate|alter|create|insert|update|delete)\s+(?:table|database|from|into)\b/i
2204
+ },
2205
+ {
2206
+ id: "sqli_timing",
2207
+ label: "SQL timing function",
2208
+ test: /\b(?:sleep|pg_sleep|benchmark|waitfor\s+delay)\s*\(/i
2209
+ },
2210
+ { id: "sqli_probe", label: "SQL metadata probe", test: /\binformation_schema\.[a-z_]+/i },
2211
+ // --- Cross-site scripting -----------------------------------------------
2212
+ { id: "xss_script_tag", label: "Inline <script>", test: /<\s*script[\s>/]/i },
2213
+ { id: "xss_javascript_uri", label: "javascript: URI", test: /javascript\s*:[^\s]{0,64}\(/i },
2214
+ {
2215
+ id: "xss_event_handler",
2216
+ label: "Inline event handler",
2217
+ // Requires a tag context, so `onerror` as a bare parameter name is not a hit.
2218
+ test: /<[a-z][a-z0-9]{0,15}[^>]{0,256}\son(?:error|load|click|mouseover|focus)\s*=/i
2219
+ },
2220
+ { id: "xss_svg_onload", label: "SVG onload", test: /<\s*svg[^>]{0,128}\bonload\b/i },
2221
+ // --- Path traversal ------------------------------------------------------
2222
+ {
2223
+ id: "traversal",
2224
+ label: "Path traversal",
2225
+ // Two or more segments: a single `../` shows up in legitimately relative
2226
+ // redirect targets often enough to be worth the extra evidence.
2227
+ test: /(?:\.\.[/\\]){2,}/
2228
+ },
2229
+ { id: "traversal_etc", label: "Sensitive file path", test: /\/etc\/(?:passwd|shadow)\b/i },
2230
+ // --- Command injection ---------------------------------------------------
2231
+ {
2232
+ id: "cmdi_shell",
2233
+ label: "Shell command injection",
2234
+ test: /[;|&`]\s*(?:cat|curl|wget|nc|bash|sh|python|perl|chmod)\s+[-/\w]/i
2235
+ },
2236
+ { id: "cmdi_subshell", label: "Shell substitution", test: /\$\([a-z][^)]{0,64}\)/i },
2237
+ // --- Template / expression injection -------------------------------------
2238
+ { id: "ssti_jndi", label: "JNDI lookup (Log4Shell)", test: /\$\{\s*jndi\s*:/i },
2239
+ { id: "ssti_expression", label: "Template expression", test: /\{\{\s*[\w.]+\s*[(*]/ }
2240
+ ];
2241
+ var ATTACK_SIGNATURE_IDS = SIGNATURES.map((s) => s.id);
2242
+
2243
+ // src/webcrypto.ts
2244
+ var encoder = new TextEncoder();
2245
+ function toHex(bytes) {
2246
+ let hex = "";
2247
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
2248
+ return hex;
2249
+ }
2250
+ async function hmacSha256Hex(secret, data) {
2251
+ const key = await crypto.subtle.importKey(
2252
+ "raw",
2253
+ encoder.encode(secret),
2254
+ { name: "HMAC", hash: "SHA-256" },
2255
+ false,
2256
+ ["sign"]
2257
+ );
2258
+ const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(data));
2259
+ return toHex(new Uint8Array(sig));
2260
+ }
2261
+ function randomHex(bytes) {
2262
+ const buf = new Uint8Array(bytes);
2263
+ crypto.getRandomValues(buf);
2264
+ return toHex(buf);
2265
+ }
2266
+
2267
+ // src/rules/honeytoken-site.ts
2268
+ var HONEYTOKEN_BASE_PATH = "/__wd";
2269
+ var TOKEN_LEN = 12;
2270
+ function utcDay(offsetDays = 0) {
2271
+ const d = new Date(Date.now() + offsetDays * 864e5);
2272
+ return d.toISOString().slice(0, 10);
2273
+ }
2274
+ function escapeHtml(v) {
2275
+ return v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2276
+ }
2277
+ function linkFor(path, text) {
2278
+ text = escapeHtml(text);
2279
+ 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>`;
2280
+ }
2281
+ var HIDDEN_STYLE = {
2282
+ position: "absolute",
2283
+ left: "-9999px",
2284
+ top: "auto",
2285
+ width: "1px",
2286
+ height: "1px",
2287
+ overflow: "hidden"
2288
+ };
2289
+ function propsFor(path, text) {
2290
+ return {
2291
+ href: path,
2292
+ rel: "nofollow noindex",
2293
+ tabIndex: -1,
2294
+ "aria-hidden": "true",
2295
+ style: HIDDEN_STYLE,
2296
+ text
2297
+ };
2298
+ }
2299
+ async function siteHoneytoken(options) {
2300
+ const base = (options.basePath ?? HONEYTOKEN_BASE_PATH).replace(/\/+$/, "");
2301
+ const text = options.text ?? ".";
2302
+ const derive = async (label) => `${base}/${(await hmacSha256Hex(options.secret, label)).slice(0, TOKEN_LEN)}`;
2303
+ if (!options.rotate) {
2304
+ const path = await derive("stable");
2305
+ return {
2306
+ primaryPath: path,
2307
+ activePaths: [path],
2308
+ linkHtml: linkFor(path, text),
2309
+ linkProps: propsFor(path, text)
2310
+ };
2311
+ }
2312
+ const today = await derive(`day:${utcDay(0)}`);
2313
+ const yesterday = await derive(`day:${utcDay(-1)}`);
2314
+ return {
2315
+ primaryPath: today,
2316
+ // Yesterday stays armed so a crawler that read the page before midnight and
2317
+ // follows the link after it still trips.
2318
+ activePaths: Array.from(/* @__PURE__ */ new Set([today, yesterday])),
2319
+ linkHtml: linkFor(today, text),
2320
+ linkProps: propsFor(today, text)
2321
+ };
2322
+ }
2323
+ function injectHoneytokenLink(html, linkHtml) {
2324
+ if (!html || html.includes(linkHtml)) return html;
2325
+ const lower = html.toLowerCase();
2326
+ for (const close of ["</body>", "</html>"]) {
2327
+ const at2 = lower.lastIndexOf(close);
2328
+ if (at2 !== -1) {
2329
+ return html.slice(0, at2) + linkHtml + html.slice(at2);
2330
+ }
2331
+ }
2332
+ return html;
2333
+ }
2334
+ function isInjectableHtml(contentType) {
2335
+ if (!contentType) return false;
2336
+ return contentType.toLowerCase().split(";")[0].trim() === "text/html";
2337
+ }
2338
+
2339
+ // src/rules/index.ts
2340
+ function tripwire(config = {}) {
2341
+ return new TripwireRule(config);
2342
+ }
2343
+
2344
+ // src/violation-reporter.ts
2345
+ var MAX_BUFFERED_VIOLATIONS = 1e3;
2346
+ var ViolationReporter = class {
2347
+ constructor(client, config = {}) {
2348
+ this.buffer = [];
2349
+ this.flushing = false;
2350
+ this.client = client;
2351
+ this.maxBufferSize = config.maxBufferSize ?? 50;
2352
+ this.debug = config.debug ?? false;
2353
+ const flushInterval = config.flushInterval ?? 5e3;
2354
+ this.flushTimer = setInterval(() => void this.flush(), flushInterval);
2355
+ if (this.flushTimer.unref) {
2356
+ this.flushTimer.unref();
2357
+ }
2358
+ }
2359
+ /**
2360
+ * Add violations to the buffer. Auto-flushes when buffer reaches maxBufferSize.
2361
+ */
2362
+ report(violations) {
2363
+ this.buffer.push(...violations);
2364
+ if (this.buffer.length > MAX_BUFFERED_VIOLATIONS) {
2365
+ this.buffer.splice(0, this.buffer.length - MAX_BUFFERED_VIOLATIONS);
2366
+ }
2367
+ if (this.buffer.length >= this.maxBufferSize) {
2368
+ this.flush().catch(() => {
2369
+ });
2370
+ }
2371
+ }
2372
+ /**
2373
+ * Flush buffered violations to the backend
2374
+ */
2375
+ async flush() {
2376
+ if (this.flushing || this.buffer.length === 0 || !this.client.isAvailable()) return;
2377
+ this.flushing = true;
2378
+ const events = this.buffer.splice(0, this.buffer.length);
2379
+ try {
2380
+ for (let i = 0; i < events.length; i += 100) {
2381
+ const batch = events.slice(i, i + 100);
2382
+ await this.client.sendViolations(batch);
2383
+ if (this.debug) {
2384
+ console.log(`[WebDecoy] Flushed ${batch.length} violation events`);
2385
+ }
2386
+ }
2387
+ } catch (error) {
2388
+ if (this.debug) {
2389
+ console.error("[WebDecoy] Failed to flush violations:", error);
2390
+ }
2391
+ } finally {
2392
+ this.flushing = false;
2393
+ }
2394
+ }
2395
+ /**
2396
+ * Flush remaining events and stop the timer
2397
+ */
2398
+ async destroy() {
2399
+ clearInterval(this.flushTimer);
2400
+ await this.flush();
2401
+ }
2402
+ };
2403
+
2404
+ // src/referrals/llm-platforms.generated.ts
2405
+ var LLM_PLATFORMS = {
2406
+ "chat.deepseek.com": "DeepSeek",
2407
+ "chat.openai.com": "ChatGPT",
2408
+ "chatgpt.com": "ChatGPT",
2409
+ "claude.ai": "Claude",
2410
+ "copilot.microsoft.com": "Copilot",
2411
+ "deepseek.com": "DeepSeek",
2412
+ "gemini.google.com": "Gemini",
2413
+ "grok.com": "Grok",
2414
+ "kagi.com": "Kagi",
2415
+ "meta.ai": "Meta AI",
2416
+ "perplexity.ai": "Perplexity",
2417
+ "phind.com": "Phind",
2418
+ "www.deepseek.com": "DeepSeek",
2419
+ "www.grok.com": "Grok",
2420
+ "www.kagi.com": "Kagi",
2421
+ "www.meta.ai": "Meta AI",
2422
+ "www.perplexity.ai": "Perplexity",
2423
+ "www.phind.com": "Phind",
2424
+ "www.you.com": "You.com",
2425
+ "you.com": "You.com"
2426
+ };
2427
+
2428
+ // src/referrals/llm-referral.ts
2429
+ var TAG_KEYS = ["utm_source", "ref", "utm_medium"];
2430
+ function classifyReferral(referer, pageUrl) {
2431
+ const ref = (referer ?? "").trim();
2432
+ if (ref) {
2433
+ try {
2434
+ return LLM_PLATFORMS[new URL(ref).hostname.toLowerCase()] ?? "";
2435
+ } catch {
2436
+ return "";
2437
+ }
2438
+ }
2439
+ let url;
2440
+ try {
2441
+ url = new URL(pageUrl);
2442
+ } catch {
2443
+ return "";
2444
+ }
2445
+ for (const key of TAG_KEYS) {
2446
+ for (const value of url.searchParams.getAll(key)) {
2447
+ const platform = platformForTag(value);
2448
+ if (platform) return platform;
2449
+ }
2450
+ }
2451
+ return "";
2452
+ }
2453
+ var squash = (s) => s.replace(/[ \-_.]/g, "");
2454
+ function platformForTag(raw) {
2455
+ let value = raw.trim().toLowerCase();
2456
+ if (!value) return "";
2457
+ try {
2458
+ const host = new URL(value).hostname;
2459
+ if (host) value = host.toLowerCase();
2460
+ } catch {
2461
+ }
2462
+ value = value.replace(/\.$/, "");
2463
+ if (LLM_PLATFORMS[value]) return LLM_PLATFORMS[value];
2464
+ const normalized = squash(value);
2465
+ for (const [domain, name] of Object.entries(LLM_PLATFORMS)) {
2466
+ if (normalized === squash(name.toLowerCase()) || normalized === domain.replace(/^www\./, "").replace(/\./g, "")) {
2467
+ return name;
2468
+ }
2469
+ }
2470
+ return "";
2471
+ }
2472
+
2473
+ // src/referrals/referral-counter.ts
2474
+ var MAX_PATH = 500;
2475
+ var MAX_ENTRIES = 500;
2476
+ var header = (headers, name) => {
2477
+ const v = headers[name] ?? headers[name.toLowerCase()];
2478
+ if (v !== void 0) return v;
2479
+ for (const [k2, value] of Object.entries(headers)) if (k2.toLowerCase() === name) return value;
2480
+ return "";
2481
+ };
2482
+ var AIReferralCounter = class {
2483
+ constructor(sender, config = {}) {
2484
+ this.sender = sender;
2485
+ this.counts = /* @__PURE__ */ new Map();
2486
+ /** A batch that failed to send, retried under the same id so it counts once. */
2487
+ this.pending = null;
2488
+ this.flushing = false;
2489
+ this.timer = setInterval(() => void this.flush(), config.flushInterval ?? 6e4);
2490
+ this.timer.unref?.();
2491
+ }
2492
+ /** Count the request if it is a page visit an AI product sent. Never throws. */
2493
+ observe(metadata) {
2494
+ try {
2495
+ if ((metadata.method ?? "").toUpperCase() !== "GET") return;
2496
+ const headers = metadata.headers ?? {};
2497
+ if (header(headers, "sec-fetch-mode") !== "navigate") return;
2498
+ const dest = header(headers, "sec-fetch-dest");
2499
+ if (dest && dest !== "document") return;
2500
+ const path = (metadata.path || "/").split("?")[0] || "/";
2501
+ const query = metadata.query ? `?${metadata.query}` : "";
2502
+ const platform = classifyReferral(header(headers, "referer"), `https://site.invalid${path}${query}`);
2503
+ if (!platform) return;
2504
+ const landing = path.length > MAX_PATH ? path.slice(0, MAX_PATH) : path;
2505
+ const key = `${platform}
2506
+ ${landing}`;
2507
+ const entry = this.counts.get(key);
2508
+ if (entry) {
2509
+ entry.count++;
2510
+ } else {
2511
+ if (this.pending && this.counts.size >= MAX_ENTRIES) return;
2512
+ this.counts.set(key, { platform, path: landing, count: 1 });
2513
+ if (this.counts.size >= MAX_ENTRIES && !this.pending) void this.flush();
2514
+ }
2515
+ } catch {
2516
+ }
2517
+ }
2518
+ /** Send what has been counted. Never rejects. */
2519
+ async flush() {
2520
+ if (this.flushing) return;
2521
+ this.flushing = true;
2522
+ try {
2523
+ if (!this.pending && this.counts.size > 0) {
2524
+ this.pending = { report_id: crypto.randomUUID(), source: "sdk", referrals: [...this.counts.values()] };
2525
+ this.counts = /* @__PURE__ */ new Map();
2526
+ }
2527
+ if (this.pending && await this.sender.sendAIReferrals(this.pending)) {
2528
+ this.pending = null;
2529
+ }
2530
+ } catch {
2531
+ } finally {
2532
+ this.flushing = false;
2533
+ }
2534
+ }
2535
+ /** Stop the timer and send what is left. */
2536
+ async destroy() {
2537
+ clearInterval(this.timer);
2538
+ await this.flush();
2539
+ }
2540
+ };
2541
+
2542
+ // src/ip-enrichment.ts
2543
+ var MAX_ENRICHMENT_ENTRIES = 1e4;
2544
+ var IPEnrichmentClient = class {
2545
+ constructor(client, ttlMs = 36e5) {
2546
+ this.cache = /* @__PURE__ */ new Map();
2547
+ this.pending = /* @__PURE__ */ new Map();
2548
+ this.client = client;
2549
+ this.ttlMs = ttlMs;
2550
+ }
2551
+ /**
2552
+ * Get enrichment data for an IP address.
2553
+ * Returns cached data if available (1h TTL), otherwise fetches from API.
2554
+ * Returns null if enrichment fails (fail-open).
2555
+ */
2556
+ async enrich(ip) {
2557
+ const cached = this.cache.get(ip);
2558
+ if (cached && cached.expiresAt > Date.now()) {
2559
+ return cached.data;
2560
+ }
2561
+ const inflight = this.pending.get(ip);
2562
+ if (inflight) {
2563
+ return inflight;
2564
+ }
2565
+ const promise = this.fetchAndCache(ip);
2566
+ this.pending.set(ip, promise);
2567
+ try {
2568
+ return await promise;
2569
+ } finally {
2570
+ this.pending.delete(ip);
2571
+ }
2572
+ }
2573
+ async fetchAndCache(ip) {
2574
+ const data = await this.client.getIPEnrichment(ip);
2575
+ if (data) {
2576
+ this.cache.delete(ip);
2577
+ this.cache.set(ip, {
2578
+ data,
2579
+ expiresAt: Date.now() + this.ttlMs
2580
+ });
2581
+ if (this.cache.size > MAX_ENRICHMENT_ENTRIES) {
2582
+ const oldest = this.cache.keys().next();
2583
+ if (!oldest.done) this.cache.delete(oldest.value);
2584
+ }
2585
+ }
2586
+ return data;
2587
+ }
2588
+ /**
2589
+ * Clear the cache
2590
+ */
2591
+ clearCache() {
2592
+ this.cache.clear();
2593
+ }
2594
+ };
2595
+
2596
+ // src/agent/thumbprint.ts
2597
+ var encoder2 = new TextEncoder();
2598
+ async function rsaThumbprint(n, e) {
2599
+ return digest(`{"e":${JSON.stringify(e)},"kty":"RSA","n":${JSON.stringify(n)}}`);
2600
+ }
2601
+ async function okpThumbprint(crv, x2) {
2602
+ return digest(`{"crv":${JSON.stringify(crv)},"kty":"OKP","x":${JSON.stringify(x2)}}`);
2603
+ }
2604
+ async function jwkThumbprint(k2) {
2605
+ switch (k2.kty) {
2606
+ case "OKP":
2607
+ if (!k2.crv || !k2.x) throw new Error("thumbprint: OKP JWK missing crv or x");
2608
+ return okpThumbprint(k2.crv, k2.x);
2609
+ case "RSA":
2610
+ if (!k2.n || !k2.e) throw new Error("thumbprint: RSA JWK missing n or e");
2611
+ return rsaThumbprint(k2.n, k2.e);
2612
+ default:
2613
+ throw new Error(`thumbprint: unsupported kty ${JSON.stringify(k2.kty)}`);
2614
+ }
2615
+ }
2616
+ async function digest(canonical) {
2617
+ const buf = await crypto.subtle.digest("SHA-256", encoder2.encode(canonical));
2618
+ return base64urlBytes(new Uint8Array(buf));
2619
+ }
2620
+ function base64urlBytes(bytes) {
2621
+ let binary = "";
2622
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
2623
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2624
+ }
2625
+
2626
+ // src/agent/directory.ts
2627
+ var WELL_KNOWN = "/.well-known/http-message-signatures-directory";
2628
+ var COLD_RETRY_BACKOFF_MS = 3e4;
2629
+ var DEFAULT_SIGNED_AGENT_DIRECTORIES = [
2630
+ { name: "OpenAI ChatGPT", category: "ai_crawlers", directory: "https://chatgpt.com" },
2631
+ { name: "Google Agent", category: "ai_crawlers", directory: "https://agent.bot.goog" },
2632
+ { name: "WebDecoyBot", category: "monitoring", directory: "https://bot.webdecoy.com" }
2633
+ ];
2634
+ var DirectoryCache = class {
2635
+ constructor(opts) {
2636
+ this.keys = /* @__PURE__ */ new Map();
2637
+ this.refreshedAt = 0;
2638
+ this.nextColdRetryAt = 0;
2639
+ this.inflight = null;
2640
+ /** Resolve a keyid to a verification key, fetching/refreshing as needed. */
2641
+ this.resolveKey = async (keyId) => {
2642
+ await this.ensureFresh();
2643
+ return this.keys.get(keyId);
2644
+ };
2645
+ this.opts = opts;
2646
+ }
2647
+ /** Kick off a fetch without blocking — call at startup to warm the cache. */
2648
+ prime() {
2649
+ if (this.keys.size === 0 && Date.now() >= this.nextColdRetryAt) void this.refresh();
2650
+ }
2651
+ /** Number of keys currently cached (diagnostics/tests). */
2652
+ get size() {
2653
+ return this.keys.size;
2654
+ }
2655
+ async ensureFresh() {
2656
+ const now = Date.now();
2657
+ const stale = now - this.refreshedAt > this.opts.cacheTtlMs;
2658
+ if (this.keys.size > 0) {
2659
+ if (stale) void this.refresh();
2660
+ return;
2661
+ }
2662
+ if (now < this.nextColdRetryAt) return;
2663
+ await this.refresh();
2664
+ }
2665
+ /** Re-fetch every directory. De-duplicated: concurrent callers share one run. */
2666
+ refresh() {
2667
+ if (this.inflight) return this.inflight;
2668
+ this.inflight = this.doRefresh().finally(() => {
2669
+ this.inflight = null;
2670
+ });
2671
+ return this.inflight;
2672
+ }
2673
+ async doRefresh() {
2674
+ const results = await Promise.all(
2675
+ this.opts.directories.map((src) => this.fetchDirectory(src))
2676
+ );
2677
+ const next = new Map(this.keys);
2678
+ let fetchedAny = false;
2679
+ for (const keys of results) {
2680
+ if (keys === null) continue;
2681
+ fetchedAny = true;
2682
+ for (const k2 of keys) next.set(k2.thumbprint, k2.key);
2683
+ }
2684
+ if (fetchedAny) {
2685
+ this.keys = next;
2686
+ this.refreshedAt = Date.now();
2687
+ this.nextColdRetryAt = 0;
2688
+ this.debug(`refreshed: ${this.keys.size} key(s) across ${this.opts.directories.length} directories`);
2689
+ } else if (this.keys.size === 0) {
2690
+ this.nextColdRetryAt = Date.now() + COLD_RETRY_BACKOFF_MS;
2691
+ this.debug("all directories unreachable; backing off cold retry");
2692
+ }
2693
+ }
2694
+ async fetchDirectory(src) {
2695
+ const url = directoryUrl(src.directory);
2696
+ const controller = new AbortController();
2697
+ const timer = setTimeout(() => controller.abort(), this.opts.fetchTimeoutMs);
2698
+ try {
2699
+ const res = await this.opts.fetchImpl(url, {
2700
+ signal: controller.signal,
2701
+ headers: {
2702
+ Accept: "application/http-message-signatures-directory+json, application/jwk-set+json, application/json"
2703
+ },
2704
+ redirect: "follow"
2705
+ });
2706
+ if (!res.ok) {
2707
+ this.debug(`${src.name}: HTTP ${res.status}`);
2708
+ return null;
2709
+ }
2710
+ const body = await res.json();
2711
+ if (!body || !Array.isArray(body.keys)) {
2712
+ this.debug(`${src.name}: no keys in directory`);
2713
+ return null;
2714
+ }
2715
+ const out = [];
2716
+ for (const jwk of body.keys) {
2717
+ const resolved = await importKey(jwk, src);
2718
+ if (resolved) out.push(resolved);
2719
+ }
2720
+ this.debug(`${src.name}: ${out.length} key(s)`);
2721
+ return out;
2722
+ } catch (err) {
2723
+ this.debug(`${src.name}: fetch failed \u2014 ${err.message}`);
2724
+ return null;
2725
+ } finally {
2726
+ clearTimeout(timer);
2727
+ }
2728
+ }
2729
+ debug(msg) {
2730
+ if (this.opts.debug) console.log(`[WebDecoy][web-bot-auth] ${msg}`);
2731
+ }
2732
+ };
2733
+ function directoryUrl(directory) {
2734
+ const u = new URL(directory);
2735
+ if (u.pathname && u.pathname !== "/") return u.toString();
2736
+ u.pathname = WELL_KNOWN;
2737
+ return u.toString();
2738
+ }
2739
+ async function importKey(jwk, src) {
2740
+ try {
2741
+ let cryptoKey;
2742
+ let verifyParams;
2743
+ let algorithm;
2744
+ if (jwk.kty === "OKP") {
2745
+ if (jwk.crv !== "Ed25519" || !jwk.x) return null;
2746
+ cryptoKey = await crypto.subtle.importKey(
2747
+ "jwk",
2748
+ { kty: "OKP", crv: "Ed25519", x: jwk.x },
2749
+ { name: "Ed25519" },
2750
+ false,
2751
+ ["verify"]
2752
+ );
2753
+ verifyParams = { name: "Ed25519" };
2754
+ algorithm = "ed25519";
2755
+ } else if (jwk.kty === "RSA") {
2756
+ if (!jwk.n || !jwk.e) return null;
2757
+ cryptoKey = await crypto.subtle.importKey(
2758
+ "jwk",
2759
+ { kty: "RSA", n: jwk.n, e: jwk.e },
2760
+ { name: "RSA-PSS", hash: "SHA-512" },
2761
+ false,
2762
+ ["verify"]
2763
+ );
2764
+ verifyParams = { name: "RSA-PSS", saltLength: 64 };
2765
+ algorithm = "rsa-pss-sha512";
2766
+ } else {
2767
+ return null;
2768
+ }
2769
+ const thumbprint = await jwkThumbprint(jwk);
2770
+ return {
2771
+ thumbprint,
2772
+ key: {
2773
+ cryptoKey,
2774
+ verifyParams,
2775
+ algorithm,
2776
+ name: src.name,
2777
+ category: src.category,
2778
+ nbf: normalizeEpoch(jwk.nbf),
2779
+ exp: normalizeEpoch(jwk.exp)
2780
+ }
2781
+ };
2782
+ } catch {
2783
+ return null;
2784
+ }
2785
+ }
2786
+ function normalizeEpoch(v) {
2787
+ if (v === void 0 || v === 0) return void 0;
2788
+ return v > 1e12 ? Math.floor(v / 1e3) : v;
2789
+ }
2790
+
2791
+ // src/agent/sfv.ts
2792
+ var Cursor = class {
2793
+ constructor(s, i = 0) {
2794
+ this.s = s;
2795
+ this.i = i;
2796
+ }
2797
+ eof() {
2798
+ return this.i >= this.s.length;
2799
+ }
2800
+ peek() {
2801
+ return this.s[this.i];
2802
+ }
2803
+ skipSP() {
2804
+ while (!this.eof() && (this.peek() === " " || this.peek() === " ")) this.i++;
2805
+ }
2806
+ };
2807
+ function parseDictionary(input) {
2808
+ const p = new Cursor(input);
2809
+ const out = [];
2810
+ p.skipSP();
2811
+ while (!p.eof()) {
2812
+ const key = parseKey(p);
2813
+ const entry = { key, raw: "", isList: false, items: [], params: /* @__PURE__ */ new Map() };
2814
+ if (!p.eof() && p.peek() === "=") {
2815
+ p.i++;
2816
+ const start = p.i;
2817
+ if (!p.eof() && p.peek() === "(") {
2818
+ entry.isList = true;
2819
+ parseInnerList(p, entry);
2820
+ } else {
2821
+ entry.items.push(parseItem(p));
2822
+ entry.params = entry.items[0].params;
2823
+ }
2824
+ entry.raw = input.slice(start, p.i);
2825
+ } else {
2826
+ entry.params = parseParams(p);
2827
+ entry.items.push({ value: true, params: /* @__PURE__ */ new Map() });
2828
+ entry.raw = "?1";
2829
+ }
2830
+ out.push(entry);
2831
+ p.skipSP();
2832
+ if (p.eof()) break;
2833
+ if (p.peek() !== ",") throw new Error(`sfv: expected ',' at ${p.i}`);
2834
+ p.i++;
2835
+ p.skipSP();
2836
+ if (p.eof()) throw new Error("sfv: trailing comma");
2837
+ }
2838
+ return out;
2839
+ }
2840
+ function parseInnerList(p, entry) {
2841
+ p.i++;
2842
+ for (; ; ) {
2843
+ p.skipSP();
2844
+ if (p.eof()) throw new Error("sfv: unterminated inner list");
2845
+ if (p.peek() === ")") {
2846
+ p.i++;
2847
+ break;
2848
+ }
2849
+ entry.items.push(parseItem(p));
2850
+ if (p.eof()) throw new Error("sfv: unterminated inner list");
2851
+ const c = p.peek();
2852
+ if (c !== " " && c !== ")") throw new Error(`sfv: bad inner list at ${p.i}`);
2853
+ }
2854
+ entry.params = parseParams(p);
2855
+ }
2856
+ function parseItem(p) {
2857
+ const { value, bytes } = parseBareItem(p);
2858
+ const params = parseParams(p);
2859
+ return bytes ? { value, params, bytes } : { value, params };
2860
+ }
2861
+ function parseParams(p) {
2862
+ const params = /* @__PURE__ */ new Map();
2863
+ while (!p.eof() && p.peek() === ";") {
2864
+ p.i++;
2865
+ p.skipSP();
2866
+ const key = parseKey(p);
2867
+ let val = true;
2868
+ if (!p.eof() && p.peek() === "=") {
2869
+ p.i++;
2870
+ val = parseBareItem(p).value;
2871
+ }
2872
+ params.set(key, val);
2873
+ }
2874
+ return params;
2875
+ }
2876
+ function parseKey(p) {
2877
+ const c = p.peek();
2878
+ if (!c || !/[a-z*]/.test(c)) throw new Error(`sfv: invalid key at ${p.i}`);
2879
+ const start = p.i;
2880
+ while (!p.eof() && /[a-z0-9_\-.*]/.test(p.peek())) p.i++;
2881
+ return p.s.slice(start, p.i);
2882
+ }
2883
+ function parseBareItem(p) {
2884
+ const c = p.peek();
2885
+ if (c === '"') return { value: parseString(p) };
2886
+ if (c === ":") return { value: "", bytes: parseByteSequence(p) };
2887
+ if (c === "?") {
2888
+ p.i++;
2889
+ const b = p.s[p.i++];
2890
+ if (b === "1") return { value: true };
2891
+ if (b === "0") return { value: false };
2892
+ throw new Error("sfv: bad boolean");
2893
+ }
2894
+ if (c === "-" || /[0-9]/.test(c)) return { value: parseNumber(p) };
2895
+ if (/[a-zA-Z*]/.test(c)) return { value: parseToken(p) };
2896
+ throw new Error(`sfv: invalid bare item at ${p.i}`);
2897
+ }
2898
+ function parseString(p) {
2899
+ p.i++;
2900
+ let out = "";
2901
+ while (!p.eof()) {
2902
+ const c = p.s[p.i++];
2903
+ if (c === '"') return out;
2904
+ if (c === "\\") {
2905
+ const e = p.s[p.i++];
2906
+ if (e !== '"' && e !== "\\") throw new Error("sfv: bad escape");
2907
+ out += e;
2908
+ } else {
2909
+ const code = c.charCodeAt(0);
2910
+ if (code < 32 || code > 126) throw new Error("sfv: bad char in string");
2911
+ out += c;
2912
+ }
2913
+ }
2914
+ throw new Error("sfv: unterminated string");
2915
+ }
2916
+ function parseByteSequence(p) {
2917
+ p.i++;
2918
+ const start = p.i;
2919
+ while (!p.eof() && p.peek() !== ":") p.i++;
2920
+ if (p.eof()) throw new Error("sfv: unterminated byte sequence");
2921
+ const b64 = p.s.slice(start, p.i);
2922
+ p.i++;
2923
+ return base64StdToBytes(b64);
2924
+ }
2925
+ function parseNumber(p) {
2926
+ const start = p.i;
2927
+ if (p.peek() === "-") p.i++;
2928
+ while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
2929
+ if (!p.eof() && p.peek() === ".") {
2930
+ p.i++;
2931
+ while (!p.eof() && /[0-9]/.test(p.peek())) p.i++;
2932
+ }
2933
+ return Number(p.s.slice(start, p.i));
2934
+ }
2935
+ function parseToken(p) {
2936
+ const start = p.i;
2937
+ p.i++;
2938
+ while (!p.eof() && /[a-zA-Z0-9!#$%&'*+\-.^_`|~:/]/.test(p.peek())) p.i++;
2939
+ return p.s.slice(start, p.i);
2940
+ }
2941
+ function base64StdToBytes(s) {
2942
+ const bin = atob(s);
2943
+ const out = new Uint8Array(bin.length);
2944
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
2945
+ return out;
2946
+ }
2947
+
2948
+ // src/agent/signature.ts
2949
+ var TAG = "web-bot-auth";
2950
+ var encoder3 = new TextEncoder();
2951
+ async function verifyWebBotAuth(req, resolveKey, toleranceSec) {
2952
+ const sigInput = req.headers.get("signature-input");
2953
+ const sigHeader = req.headers.get("signature");
2954
+ if (!sigInput && !sigHeader) return { outcome: "none" };
2955
+ if (!sigInput || !sigHeader) return { outcome: "claimed", reason: "incomplete-signature" };
2956
+ let members;
2957
+ let sigs;
2958
+ try {
2959
+ members = parseSignatureInput(sigInput);
2960
+ sigs = parseSignatureBytes(sigHeader);
2961
+ } catch {
2962
+ return { outcome: "claimed", reason: "malformed-signature" };
2963
+ }
2964
+ const now = Date.now() / 1e3;
2965
+ let best = { outcome: "none" };
2966
+ for (const m of members) {
2967
+ if (m.params.get("tag") !== TAG) continue;
2968
+ if (best.outcome === "none") best = { outcome: "claimed", reason: "unverifiable" };
2969
+ const sig = sigs.get(m.label);
2970
+ if (!sig) continue;
2971
+ const keyid = m.params.get("keyid");
2972
+ if (typeof keyid !== "string") continue;
2973
+ if (!m.components.some((c) => c.name === "@authority" || c.name === "@target-uri")) continue;
2974
+ const key = await resolveKey(keyid);
2975
+ if (!key) {
2976
+ best = higher(best, { outcome: "claimed", keyId: keyid, reason: "unknown-key" });
2977
+ continue;
2978
+ }
2979
+ const created = numeric(m.params.get("created"));
2980
+ const expires = numeric(m.params.get("expires"));
2981
+ if (expires !== void 0 && now > expires + toleranceSec) {
2982
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "expired" });
2983
+ continue;
2984
+ }
2985
+ if (created !== void 0 && now + toleranceSec < created) {
2986
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "not-yet-valid" });
2987
+ continue;
2988
+ }
2989
+ if (key.exp !== void 0 && now > key.exp + toleranceSec) {
2990
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-expired" });
2991
+ continue;
2992
+ }
2993
+ if (key.nbf !== void 0 && now + toleranceSec < key.nbf) {
2994
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "key-not-yet-valid" });
2995
+ continue;
2996
+ }
2997
+ let base;
2998
+ try {
2999
+ base = buildSignatureBase(req, m);
3000
+ } catch {
3001
+ best = higher(best, { outcome: "claimed", keyId: keyid, reason: "uncoverable-component" });
3002
+ continue;
3003
+ }
3004
+ let ok = false;
3005
+ try {
3006
+ ok = await crypto.subtle.verify(
3007
+ key.verifyParams,
3008
+ key.cryptoKey,
3009
+ sig,
3010
+ encoder3.encode(base)
3011
+ );
3012
+ } catch {
3013
+ ok = false;
3014
+ }
3015
+ if (ok) {
3016
+ return { outcome: "verified", keyId: keyid, key };
3017
+ }
3018
+ best = higher(best, { outcome: "impersonation", keyId: keyid, key, reason: "bad-signature" });
3019
+ }
3020
+ return best;
3021
+ }
3022
+ var PRECEDENCE = { none: 0, claimed: 1, impersonation: 2, verified: 3 };
3023
+ function higher(a, b) {
3024
+ return PRECEDENCE[b.outcome] >= PRECEDENCE[a.outcome] ? b : a;
3025
+ }
3026
+ function numeric(v) {
3027
+ return typeof v === "number" ? v : void 0;
3028
+ }
3029
+ function buildSignatureBase(req, m) {
3030
+ const lines = [];
3031
+ for (const c of m.components) {
3032
+ lines.push(`${serializeComponentId(c)}: ${componentValue(req, c)}`);
3033
+ }
3034
+ lines.push(`"@signature-params": ${m.raw.trim()}`);
3035
+ return lines.join("\n");
3036
+ }
3037
+ function serializeComponentId(c) {
3038
+ const base = `"${c.name.toLowerCase()}"`;
3039
+ return c.keyParam !== void 0 ? `${base};key="${c.keyParam}"` : base;
3040
+ }
3041
+ function componentValue(req, c) {
3042
+ const name = c.name.toLowerCase();
3043
+ switch (name) {
3044
+ case "@method":
3045
+ return req.method.toUpperCase();
3046
+ case "@authority":
3047
+ return canonicalAuthority(req.url);
3048
+ case "@scheme":
3049
+ return req.url.protocol.replace(/:$/, "").toLowerCase();
3050
+ case "@target-uri":
3051
+ return `${req.url.protocol}//${canonicalAuthority(req.url)}${req.url.pathname}${req.url.search}`;
3052
+ case "@path":
3053
+ return req.url.pathname;
3054
+ case "@query":
3055
+ return req.url.search === "" ? "?" : req.url.search;
3056
+ case "signature-agent": {
3057
+ const header2 = req.headers.get("signature-agent");
3058
+ if (header2 === null) throw new Error("signature-agent covered but absent");
3059
+ if (c.keyParam !== void 0) return dictMemberValue(header2, c.keyParam);
3060
+ return header2.trim().replace(/\s+/g, " ");
3061
+ }
3062
+ default: {
3063
+ if (name.startsWith("@")) throw new Error(`unsupported derived component ${name}`);
3064
+ const header2 = req.headers.get(name);
3065
+ if (header2 === null) throw new Error(`covered header ${name} absent`);
3066
+ return header2.trim().replace(/\s+/g, " ");
3067
+ }
3068
+ }
3069
+ }
3070
+ function canonicalAuthority(url) {
3071
+ const host = url.hostname.toLowerCase();
3072
+ const port = url.port;
3073
+ if (!port) return host;
3074
+ if (url.protocol === "https:" && port === "443" || url.protocol === "http:" && port === "80") {
3075
+ return host;
3076
+ }
3077
+ return `${host}:${port}`;
3078
+ }
3079
+ function dictMemberValue(header2, key) {
3080
+ const dict = parseDictionary(header2);
3081
+ const found = dict.find((d) => d.key === key);
3082
+ if (!found) throw new Error(`signature-agent has no member ${key}`);
3083
+ return found.raw;
3084
+ }
3085
+ function parseSignatureInput(value) {
3086
+ return parseDictionary(value).map((d) => {
3087
+ if (!d.isList) throw new Error(`Signature-Input member ${d.key} is not an inner list`);
3088
+ const components = d.items.map((it2) => {
3089
+ if (typeof it2.value !== "string") throw new Error("component identifier is not a string");
3090
+ const keyParam = it2.params.get("key");
3091
+ return { name: it2.value, keyParam: typeof keyParam === "string" ? keyParam : void 0 };
3092
+ });
3093
+ return { label: d.key, components, params: d.params, raw: d.raw };
3094
+ });
3095
+ }
3096
+ function parseSignatureBytes(value) {
3097
+ const out = /* @__PURE__ */ new Map();
3098
+ for (const d of parseDictionary(value)) {
3099
+ if (d.isList || d.items.length !== 1 || !d.items[0].bytes) {
3100
+ throw new Error(`Signature member ${d.key} is not a byte sequence`);
3101
+ }
3102
+ out.set(d.key, d.items[0].bytes);
3103
+ }
3104
+ return out;
3105
+ }
3106
+
3107
+ // src/agent/verifier.ts
3108
+ var DEFAULT_TTL_MS = 6 * 60 * 60 * 1e3;
3109
+ var DEFAULT_FETCH_TIMEOUT_MS = 5e3;
3110
+ var DEFAULT_TOLERANCE_SEC = 300;
3111
+ var AgentVerifier = class {
3112
+ constructor(options = {}) {
3113
+ this.toleranceSec = options.toleranceSec ?? DEFAULT_TOLERANCE_SEC;
3114
+ this.cache = new DirectoryCache({
3115
+ directories: options.directories ?? DEFAULT_SIGNED_AGENT_DIRECTORIES,
3116
+ cacheTtlMs: options.cacheTtlMs ?? DEFAULT_TTL_MS,
3117
+ fetchTimeoutMs: options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS,
3118
+ debug: options.debug ?? false,
3119
+ fetchImpl: options.fetchImpl ?? fetch
3120
+ });
3121
+ }
3122
+ /** Pre-fetch trusted directories so the first request verifies warm. */
3123
+ warmup() {
3124
+ this.cache.prime();
3125
+ }
3126
+ /** Verify a request's Web Bot Auth signature (if any) locally. */
3127
+ async verify(request) {
3128
+ let req;
3129
+ try {
3130
+ req = normalize(request);
3131
+ } catch {
3132
+ return { status: "none" };
3133
+ }
3134
+ const result = await verifyWebBotAuth(req, this.cache.resolveKey, this.toleranceSec);
3135
+ switch (result.outcome) {
3136
+ case "verified":
3137
+ return {
3138
+ status: "verified",
3139
+ method: "signature",
3140
+ keyId: result.keyId,
3141
+ agentName: result.key?.name,
3142
+ category: result.key?.category,
3143
+ algorithm: result.key?.algorithm
3144
+ };
3145
+ case "impersonation":
3146
+ return {
3147
+ status: "impersonation",
3148
+ method: "signature",
3149
+ keyId: result.keyId,
3150
+ agentName: result.key?.name,
3151
+ category: result.key?.category,
3152
+ reason: result.reason
3153
+ };
3154
+ case "claimed":
3155
+ return { status: "claimed", keyId: result.keyId, reason: result.reason };
3156
+ default:
3157
+ return { status: "none" };
3158
+ }
3159
+ }
3160
+ /** Cached-key count (diagnostics/tests). */
3161
+ get cachedKeyCount() {
3162
+ return this.cache.size;
3163
+ }
3164
+ };
3165
+ function normalize(input) {
3166
+ if (isRequest(input)) {
3167
+ return { method: input.method, url: new URL(input.url), headers: input.headers };
3168
+ }
3169
+ const headers = input.headers instanceof Headers ? input.headers : toHeaders(input.headers);
3170
+ return { method: input.method, url: new URL(input.url), headers };
3171
+ }
3172
+ function isRequest(input) {
3173
+ return typeof Request !== "undefined" && input instanceof Request && typeof input.url === "string";
3174
+ }
3175
+ function toHeaders(record) {
3176
+ const h = new Headers();
3177
+ for (const [k2, v] of Object.entries(record)) {
3178
+ if (v !== void 0 && v !== null) h.set(k2, String(v));
3179
+ }
3180
+ return h;
3181
+ }
3182
+
3183
+ // src/edge.ts
3184
+ var EDGE_CLEARANCE_HEADER = "x-wd-clearance";
3185
+ var EDGE_CLASS_HEADER = "x-wd-class";
3186
+ var EDGE_CLASSES = ["verified", "crawler", "script", "browser"];
3187
+ function absent() {
3188
+ return {
3189
+ present: false,
3190
+ isVerified: false,
3191
+ isCrawler: false,
3192
+ isScript: false,
3193
+ isBrowser: false,
3194
+ isUnattestedNonBrowser: false
3195
+ };
3196
+ }
3197
+ function normaliseClass(raw) {
3198
+ if (!raw) return void 0;
3199
+ const v = raw.trim().toLowerCase();
3200
+ return EDGE_CLASSES.includes(v) ? v : void 0;
3201
+ }
3202
+ function readEdgeVerdict(headers) {
3203
+ if (!headers) return absent();
3204
+ let clearanceRaw;
3205
+ let classRaw;
3206
+ for (const key of Object.keys(headers)) {
3207
+ const k2 = key.toLowerCase();
3208
+ if (k2 === EDGE_CLEARANCE_HEADER) clearanceRaw = headers[key];
3209
+ else if (k2 === EDGE_CLASS_HEADER) classRaw = headers[key];
3210
+ }
3211
+ const clearance = clearanceRaw?.trim() || void 0;
3212
+ const cls = normaliseClass(classRaw);
3213
+ if (!clearance && !cls) return absent();
3214
+ return {
3215
+ present: true,
3216
+ clearance,
3217
+ class: cls,
3218
+ isVerified: cls === "verified",
3219
+ isCrawler: cls === "crawler",
3220
+ isScript: cls === "script",
3221
+ isBrowser: cls === "browser",
3222
+ isUnattestedNonBrowser: cls === "script" || cls === "crawler"
3223
+ };
3224
+ }
3225
+
3226
+ // src/logger.ts
3227
+ var PREFIX = "[WebDecoy]";
3228
+ function consoleLogger(debug) {
3229
+ const emit = (fn, gated) => (message, fields) => {
3230
+ if (gated && !debug) return;
3231
+ if (fields) fn(`${PREFIX} ${message}`, fields);
3232
+ else fn(`${PREFIX} ${message}`);
3233
+ };
3234
+ return {
3235
+ debug: emit(console.log, true),
3236
+ info: emit(console.log, true),
3237
+ // Warnings and errors are not debug output. A violation that failed to
3238
+ // report, or a key that was rejected, is something the operator needs to
3239
+ // see whether or not they opted into diagnostics.
3240
+ warn: emit(console.warn, false),
3241
+ error: emit(console.error, false)
3242
+ };
3243
+ }
3244
+ function resolveLogger(provided, debug) {
3245
+ return provided ?? consoleLogger(debug);
3246
+ }
3247
+
3248
+ // src/tracing.ts
3249
+ var STATUS_ERROR = 2;
3250
+ var NOOP_SPAN = {
3251
+ setAttribute: () => void 0,
3252
+ end: () => void 0
3253
+ };
3254
+ function startSpan(tracer, name) {
3255
+ if (!tracer) return NOOP_SPAN;
3256
+ try {
3257
+ return tracer.startSpan(name) ?? NOOP_SPAN;
3258
+ } catch {
3259
+ return NOOP_SPAN;
3260
+ }
3261
+ }
3262
+ function setAttribute(span, key, value) {
3263
+ try {
3264
+ span.setAttribute(key, value);
3265
+ } catch {
3266
+ }
3267
+ }
3268
+ function recordError(span, error) {
3269
+ try {
3270
+ span.recordException?.(error);
3271
+ span.setStatus?.({
3272
+ code: STATUS_ERROR,
3273
+ message: error instanceof Error ? error.message : String(error)
3274
+ });
3275
+ } catch {
3276
+ }
3277
+ }
3278
+ function endSpan(span) {
3279
+ try {
3280
+ span.end();
3281
+ } catch {
3282
+ }
3283
+ }
3284
+
3285
+ // src/decision.ts
3286
+ function newDecisionId() {
3287
+ return `dec_${randomHex(12)}`;
3288
+ }
3289
+ var Decision = class _Decision {
3290
+ constructor(init) {
3291
+ this.id = init.id ?? newDecisionId();
3292
+ this.conclusion = init.conclusion;
3293
+ this.results = Object.freeze([...init.results ?? []]);
3294
+ this.reason = init.reason;
3295
+ this.detection = init.detection;
3296
+ this.error = init.error;
3297
+ this.ruleResult = init.ruleResult;
3298
+ this.agent = init.agent;
3299
+ this.edge = init.edge;
3300
+ this.key = init.key;
3301
+ this.ttl = init.ttl ?? 0;
3302
+ }
3303
+ get allowed() {
3304
+ return this.conclusion === "ALLOW" || this.conclusion === "ERROR";
3305
+ }
3306
+ isAllowed() {
3307
+ return this.conclusion === "ALLOW";
3308
+ }
3309
+ isDenied() {
3310
+ return this.conclusion === "DENY";
3311
+ }
3312
+ isChallenged() {
3313
+ return this.conclusion === "CHALLENGE";
3314
+ }
3315
+ isErrored() {
3316
+ return this.conclusion === "ERROR";
3317
+ }
3318
+ deniedBy(rule) {
3319
+ return this.results.some(
3320
+ (r) => r.rule === rule && r.state === "RUN" && r.conclusion === "DENY"
3321
+ );
3322
+ }
3323
+ /** A copy of this decision with the edge verdict attached. */
3324
+ withEdge(edge) {
3325
+ return new _Decision({ ...this.init(), edge });
3326
+ }
3327
+ /** A copy marked as served from cache, with every rule re-stated as CACHED. */
3328
+ asCached() {
3329
+ return new _Decision({
3330
+ ...this.init(),
3331
+ results: this.results.map((r) => ({ ...r, state: "CACHED" }))
3332
+ });
3333
+ }
3334
+ init() {
3335
+ return {
3336
+ id: this.id,
3337
+ conclusion: this.conclusion,
3338
+ results: [...this.results],
3339
+ reason: this.reason,
3340
+ detection: this.detection,
3341
+ error: this.error,
3342
+ ruleResult: this.ruleResult,
3343
+ agent: this.agent,
3344
+ edge: this.edge,
3345
+ key: this.key,
3346
+ ttl: this.ttl
3347
+ };
3348
+ }
3349
+ };
3350
+
3351
+ // src/characteristics.ts
3352
+ var DEFAULT_CHARACTERISTICS = ["ip"];
3353
+ function resolveOne(context, c) {
3354
+ if (typeof c === "function") {
3355
+ try {
3356
+ return c(context) || void 0;
3357
+ } catch {
3358
+ return void 0;
3359
+ }
3360
+ }
3361
+ switch (c) {
3362
+ case "ip":
3363
+ return context.ip || void 0;
3364
+ case "path":
3365
+ return context.path || void 0;
3366
+ case "method":
3367
+ return context.method || void 0;
3368
+ case "userAgent":
3369
+ return context.userAgent || void 0;
3370
+ }
3371
+ }
3372
+ function deriveKey(context, characteristics = DEFAULT_CHARACTERISTICS) {
3373
+ if (characteristics.length === 0) return context.ip;
3374
+ const parts = [];
3375
+ for (const c of characteristics) {
3376
+ const value = resolveOne(context, c);
3377
+ if (value === void 0) return context.ip;
3378
+ parts.push(value);
3379
+ }
3380
+ return parts.join("|");
3381
+ }
3382
+
3383
+ // src/decision-cache.ts
3384
+ var DecisionCache = class {
3385
+ constructor(options = {}) {
3386
+ // Insertion-ordered, which is what makes the eviction below oldest-first.
3387
+ this.entries = /* @__PURE__ */ new Map();
3388
+ this.ttl = options.ttl ?? 6e4;
3389
+ this.max = options.max ?? 1e4;
3390
+ }
3391
+ /** A cached decision for this key, or undefined. Expired entries are dropped. */
3392
+ get(key) {
3393
+ const entry = this.entries.get(key);
3394
+ if (!entry) return void 0;
3395
+ if (entry.expiresAt <= Date.now()) {
3396
+ this.entries.delete(key);
3397
+ return void 0;
3398
+ }
3399
+ return entry.decision;
3400
+ }
3401
+ /**
3402
+ * Remember a decision, if it is one of the kinds worth remembering.
3403
+ * Returns whether it was stored, so a caller can assert on the policy rather
3404
+ * than infer it.
3405
+ */
3406
+ set(key, decision) {
3407
+ if (decision.conclusion !== "DENY" && decision.conclusion !== "CHALLENGE") return false;
3408
+ if (this.ttl <= 0) return false;
3409
+ this.entries.delete(key);
3410
+ this.entries.set(key, { decision, expiresAt: Date.now() + this.ttl });
3411
+ while (this.entries.size > this.max) {
3412
+ const oldest = this.entries.keys().next();
3413
+ if (oldest.done) break;
3414
+ this.entries.delete(oldest.value);
3415
+ }
3416
+ return true;
3417
+ }
3418
+ clear() {
3419
+ this.entries.clear();
3420
+ }
3421
+ get size() {
3422
+ return this.entries.size;
3423
+ }
3424
+ /** How long entries live, in milliseconds. Reported on the decision. */
3425
+ get lifetime() {
3426
+ return this.ttl;
3427
+ }
3428
+ };
3429
+
3430
+ // src/test-trigger.ts
3431
+ var TEST_TRIGGER_UA_PREFIX = "WebDecoy-Test/";
3432
+ function isTestTriggerUserAgent(userAgent) {
3433
+ if (!userAgent) return false;
3434
+ return userAgent.trimStart().toLowerCase().startsWith(TEST_TRIGGER_UA_PREFIX.toLowerCase());
3435
+ }
3436
+
3437
+ // src/sdk.ts
3438
+ var WebDecoy = class {
3439
+ constructor(config = {}) {
3440
+ this.referralCounter = null;
3441
+ this.violationReporter = null;
3442
+ this.ipEnrichmentClient = null;
3443
+ this._hasFilterRules = false;
3444
+ this._hasAgentRules = false;
3445
+ this._preparingRules = [];
3446
+ this.agentVerifier = null;
3447
+ const hasApiKey = !!config.apiKey;
3448
+ if (hasApiKey) {
3449
+ if (!config.apiKey.startsWith("sk_live_") && !config.apiKey.startsWith("sk_test_")) {
3450
+ throw new Error(
3451
+ 'Invalid API key format. API key should start with "sk_live_" or "sk_test_".'
3452
+ );
3453
+ }
3454
+ }
3455
+ this.config = {
3456
+ apiKey: config.apiKey,
3457
+ apiUrl: config.apiUrl || "https://in.webdecoy.com",
3458
+ enableTLSFingerprinting: config.enableTLSFingerprinting ?? true,
3459
+ threatScoreThreshold: config.threatScoreThreshold ?? 80,
3460
+ timeout: config.timeout ?? 5e3,
3461
+ debug: config.debug ?? false,
3462
+ tlsRejectUnauthorized: config.tlsRejectUnauthorized ?? true,
3463
+ countAIReferrals: config.countAIReferrals ?? true
3464
+ };
3465
+ this.log = resolveLogger(config.logger, this.config.debug);
3466
+ this.tracer = config.tracer;
3467
+ if (hasApiKey) {
3468
+ this.client = new WebDecoyClient({
3469
+ apiKey: config.apiKey,
3470
+ apiUrl: this.config.apiUrl,
3471
+ timeout: this.config.timeout,
3472
+ debug: this.config.debug,
3473
+ tlsRejectUnauthorized: this.config.tlsRejectUnauthorized
3474
+ });
3475
+ } else {
3476
+ this.client = null;
3477
+ this.log.info("Running in local-only mode (no API key). Rules will still evaluate.");
3478
+ }
3479
+ this.webBotAuthOptions = config.webBotAuth;
3480
+ this.characteristics = config.characteristics ?? DEFAULT_CHARACTERISTICS;
3481
+ this.decisionCache = config.decisionCache === false ? null : new DecisionCache(config.decisionCache ?? {});
3482
+ const rules = config.rules ?? [tripwire()];
3483
+ if (rules.length > 0) {
3484
+ this.ruleEngine = new RuleEngine(rules);
3485
+ this._hasFilterRules = rules.some((r) => r.name.startsWith("filter:"));
3486
+ this._hasAgentRules = rules.some((r) => r.name === "web-bot-auth");
3487
+ this._preparingRules = rules.filter((r) => typeof r.prepare === "function");
3488
+ if (this._hasAgentRules) {
3489
+ this.getAgentVerifier().warmup();
3490
+ }
3491
+ } else {
3492
+ this.ruleEngine = null;
3493
+ }
3494
+ if (this.client && this._hasFilterRules) {
3495
+ this.ipEnrichmentClient = new IPEnrichmentClient(this.client);
3496
+ }
3497
+ if (this.client && this.config.countAIReferrals !== false) {
3498
+ this.referralCounter = new AIReferralCounter(this.client);
3499
+ }
3500
+ if (this.client && this.ruleEngine) {
3501
+ const reporter = new ViolationReporter(this.client, {
3502
+ debug: this.config.debug
3503
+ });
3504
+ this.setViolationReporter(reporter);
3505
+ }
3506
+ this.log.debug("Initialized", {
3507
+ apiUrl: this.config.apiUrl,
3508
+ enableTLSFingerprinting: this.config.enableTLSFingerprinting,
3509
+ threatScoreThreshold: this.config.threatScoreThreshold,
3510
+ hasApiKey,
3511
+ rulesCount: rules.length
3512
+ });
3513
+ }
3514
+ /**
3515
+ * Evaluate rules against request metadata (synchronous).
3516
+ * Returns null if no rules are configured.
3517
+ */
3518
+ evaluateRules(metadata) {
3519
+ if (!this.ruleEngine) return null;
3520
+ return this.runRules(this.buildContext(metadata));
3521
+ }
3522
+ /**
3523
+ * Evaluate rules with async pre-fetch (IP enrichment, Web Bot Auth
3524
+ * verification). Use this instead of evaluateRules() when filter rules or
3525
+ * webBotAuth() rules are present.
3526
+ */
3527
+ async evaluateRulesAsync(metadata) {
3528
+ if (!this.ruleEngine) return null;
3529
+ const context = await this.buildAsyncContext(metadata);
3530
+ return this.runRules(context);
3531
+ }
3532
+ /**
3533
+ * Register a rule after construction.
3534
+ *
3535
+ * For signals whose definition is not available synchronously — the site
3536
+ * honeytoken's path is derived by async HMAC, so the adapter arms it once the
3537
+ * derivation settles. Creates the engine if there was none, so an SDK built
3538
+ * with `rules: []` can still gain one.
3539
+ */
3540
+ addRule(rule) {
3541
+ if (!this.ruleEngine) {
3542
+ this.ruleEngine = new RuleEngine([rule]);
3543
+ } else {
3544
+ this.ruleEngine.add(rule);
3545
+ }
3546
+ if (rule.name.startsWith("filter:")) this._hasFilterRules = true;
3547
+ if (rule.name === "web-bot-auth") this._hasAgentRules = true;
3548
+ if (typeof rule.prepare === "function") this._preparingRules.push(rule);
3549
+ }
3550
+ /** Build the base (synchronous) rule context from request metadata. */
3551
+ buildContext(metadata) {
3552
+ const context = {
3553
+ ip: metadata.ip,
3554
+ path: metadata.path,
3555
+ method: metadata.method,
3556
+ userAgent: metadata.user_agent,
3557
+ headers: metadata.headers,
3558
+ query: metadata.query,
3559
+ body: metadata.body,
3560
+ timestamp: metadata.timestamp || Date.now(),
3561
+ // Parsed synchronously and unconditionally: it is two header reads,
3562
+ // it needs no network, and a rule that has to check whether the edge
3563
+ // verdict was populated is a rule people will get wrong.
3564
+ edge: readEdgeVerdict(metadata.headers),
3565
+ // Same reasoning as `edge`, and the same cost profile: a memoised
3566
+ // substring scan over a static table, no network, no async. Populating it
3567
+ // unconditionally means a rule never has to ask whether classification
3568
+ // ran.
3569
+ bot: classifyUserAgent(metadata.user_agent)
3570
+ };
3571
+ context.key = deriveKey(context, this.characteristics);
3572
+ return context;
3573
+ }
3574
+ /**
3575
+ * Build a rule context with async signals resolved: IP enrichment (for
3576
+ * filter rules) and the Web Bot Auth verdict (for webBotAuth() rules).
3577
+ */
3578
+ async buildAsyncContext(metadata) {
3579
+ const context = this.buildContext(metadata);
3580
+ if (this._hasFilterRules && this.ipEnrichmentClient) {
3581
+ const enrichment = await this.ipEnrichmentClient.enrich(metadata.ip);
3582
+ if (enrichment) {
3583
+ context.enrichment = enrichment;
3584
+ }
3585
+ }
3586
+ if (this._hasAgentRules) {
3587
+ context.agent = await this.computeAgentVerdict(metadata);
3588
+ }
3589
+ if (this._preparingRules.length > 0) {
3590
+ await Promise.all(this._preparingRules.map((rule) => rule.prepare(context)));
3591
+ }
3592
+ return context;
3593
+ }
3594
+ /** Evaluate rules against a prepared context and report any violations. */
3595
+ runRules(context) {
3596
+ if (!this.ruleEngine) return null;
3597
+ const span = startSpan(this.tracer, "webdecoy.rules");
3598
+ const result = this.ruleEngine.evaluate(context);
3599
+ setAttribute(span, "webdecoy.rules.action", result.action);
3600
+ setAttribute(span, "webdecoy.rules.evaluated", result.results.length);
3601
+ setAttribute(span, "webdecoy.rules.violations", result.violations.length);
3602
+ if (result.rule) setAttribute(span, "webdecoy.rules.deciding", result.rule);
3603
+ endSpan(span);
3604
+ if (result.violations.length > 0 && this.violationReporter) {
3605
+ this.violationReporter.report(result.violations);
3606
+ }
3607
+ return result;
3608
+ }
3609
+ /** Lazily construct the shared Web Bot Auth verifier (one directory cache). */
3610
+ getAgentVerifier() {
3611
+ if (!this.agentVerifier) {
3612
+ this.agentVerifier = new AgentVerifier({
3613
+ debug: this.config.debug,
3614
+ ...this.webBotAuthOptions
3615
+ });
3616
+ }
3617
+ return this.agentVerifier;
3618
+ }
3619
+ /**
3620
+ * Verify a request's Web Bot Auth signature locally, deriving the request
3621
+ * URL/authority from its metadata. Returns undefined when the request lacks
3622
+ * the host information needed to verify (verdict is then simply absent).
3623
+ */
3624
+ async computeAgentVerdict(metadata) {
3625
+ const input = agentInputFromMetadata(metadata);
3626
+ if (!input) return void 0;
3627
+ return this.getAgentVerifier().verify(input);
3628
+ }
3629
+ /**
3630
+ * Verify an inbound request's Web Bot Auth signature locally (RFC 9421, tag
3631
+ * "web-bot-auth"). Returns whether it is a cryptographically `verified`
3632
+ * agent, an `impersonation` of a known one, an unverifiable `claimed`
3633
+ * signature, or `none`. No network on the warm path.
3634
+ *
3635
+ * Accepts a WHATWG `Request` (edge/Next.js) or a `{ method, url, headers }`
3636
+ * object (Node).
3637
+ *
3638
+ * @example
3639
+ * ```ts
3640
+ * const verdict = await webdecoy.detectBot(request);
3641
+ * if (verdict.status === 'impersonation') return new Response('Forbidden', { status: 403 });
3642
+ * if (verdict.status === 'verified') console.log('verified agent:', verdict.agentName);
3643
+ * ```
3644
+ */
3645
+ async detectBot(request) {
3646
+ return this.getAgentVerifier().verify(request);
3647
+ }
3648
+ /**
3649
+ * Whether this SDK instance has filter rules that need async enrichment
3650
+ */
3651
+ get hasFilterRules() {
3652
+ return this._hasFilterRules;
3653
+ }
3654
+ /**
3655
+ * Whether this SDK instance has Web Bot Auth rules that need async
3656
+ * verification before evaluation.
3657
+ */
3658
+ get hasAgentRules() {
3659
+ return this._hasAgentRules;
3660
+ }
3661
+ /**
3662
+ * Protect a request by checking it against Web Decoy's bot detection
3663
+ *
3664
+ * @param metadata - Request metadata to analyze
3665
+ * @param options - Optional configuration for this specific request
3666
+ * @returns The decision — `conclusion`, every rule's outcome, and the
3667
+ * narrowing helpers. Satisfies `ProtectResult`.
3668
+ */
3669
+ async protect(metadata, options = {}) {
3670
+ const edge = readEdgeVerdict(metadata.headers);
3671
+ this.referralCounter?.observe(metadata);
3672
+ const span = startSpan(this.tracer, "webdecoy.protect");
3673
+ try {
3674
+ const decision = (await this.decide(metadata, options)).withEdge(edge);
3675
+ setAttribute(span, "webdecoy.decision.id", decision.id);
3676
+ setAttribute(span, "webdecoy.decision.conclusion", decision.conclusion);
3677
+ setAttribute(span, "webdecoy.decision.allowed", decision.allowed);
3678
+ setAttribute(span, "webdecoy.rules.evaluated", decision.results.length);
3679
+ if (decision.ruleResult?.rule) {
3680
+ setAttribute(span, "webdecoy.decision.rule", decision.ruleResult.rule);
3681
+ }
3682
+ setAttribute(
3683
+ span,
3684
+ "webdecoy.remote",
3685
+ decision.detection.detection_id !== decision.id
3686
+ );
3687
+ if (decision.error) {
3688
+ setAttribute(span, "webdecoy.error", decision.error);
3689
+ }
3690
+ return decision;
3691
+ } catch (error) {
3692
+ recordError(span, error);
3693
+ throw error;
3694
+ } finally {
3695
+ endSpan(span);
3696
+ }
3697
+ }
3698
+ async decide(metadata, options = {}) {
3699
+ const id = newDecisionId();
3700
+ let key = metadata.ip || "unknown";
3701
+ try {
3702
+ if (!metadata.ip) {
3703
+ throw new Error("IP address is required in request metadata");
3704
+ }
3705
+ if (!metadata.timestamp) {
3706
+ metadata.timestamp = Date.now();
3707
+ }
3708
+ if (isTestTriggerUserAgent(metadata.user_agent)) {
3709
+ return this.reportTestTrigger(metadata, id);
3710
+ }
3711
+ const needsAsync = this._hasFilterRules || this._hasAgentRules || this._preparingRules.length > 0;
3712
+ const context = needsAsync ? await this.buildAsyncContext(metadata) : this.buildContext(metadata);
3713
+ key = context.key ?? key;
3714
+ const agentVerdict = context.agent;
3715
+ const ruleResult = this.ruleEngine ? this.runRules(context) : null;
3716
+ if (ruleResult && ruleResult.action !== "ALLOW") {
3717
+ const throttled = ruleResult.action === "THROTTLE";
3718
+ return new Decision({
3719
+ conclusion: "DENY",
3720
+ reason: ruleResult.reason,
3721
+ detection: {
3722
+ decision: "block",
3723
+ confidence: 100,
3724
+ threat_level: throttled ? "MEDIUM" : "HIGH",
3725
+ bot_detected: false,
3726
+ detection_id: id,
3727
+ rule_enforced: true
3728
+ },
3729
+ id,
3730
+ results: ruleResult.results,
3731
+ ruleResult,
3732
+ agent: agentVerdict,
3733
+ key
3734
+ });
3735
+ }
3736
+ if (!this.client) {
3737
+ return new Decision({
3738
+ conclusion: "ALLOW",
3739
+ detection: {
3740
+ decision: "allow",
3741
+ confidence: 0,
3742
+ threat_level: "MINIMAL",
3743
+ bot_detected: false,
3744
+ detection_id: id,
3745
+ rule_enforced: false
3746
+ },
3747
+ id,
3748
+ results: ruleResult?.results ?? [],
3749
+ ruleResult: ruleResult ?? void 0,
3750
+ agent: agentVerdict,
3751
+ key
3752
+ });
3753
+ }
3754
+ const cached = this.decisionCache?.get(key);
3755
+ if (cached) return cached.asCached();
3756
+ const localAnalysis = options.skipLocalAnalysis ? {
3757
+ suspicious_headers: false,
3758
+ missing_sec_ch_ua: false,
3759
+ datacenter_ip: false,
3760
+ local_score: 0,
3761
+ needs_verification: true,
3762
+ flags: ["local_analysis_skipped"]
3763
+ } : analyzeRequest(metadata);
3764
+ this.log.debug("Local analysis", { ...localAnalysis });
3765
+ const detectionRequest = {
3766
+ request_metadata: metadata,
3767
+ local_analysis: localAnalysis
3768
+ };
3769
+ const shouldCallServer = localAnalysis.needs_verification || this.config.enableTLSFingerprinting && metadata.tls_info;
3770
+ if (!shouldCallServer) {
3771
+ return new Decision({
3772
+ conclusion: "ALLOW",
3773
+ detection: {
3774
+ decision: "allow",
3775
+ confidence: 100 - localAnalysis.local_score,
3776
+ threat_level: "MINIMAL",
3777
+ bot_detected: false,
3778
+ detection_id: id,
3779
+ rule_enforced: false
3780
+ },
3781
+ id,
3782
+ results: ruleResult?.results ?? [],
3783
+ ruleResult: ruleResult ?? void 0,
3784
+ agent: agentVerdict,
3785
+ key
3786
+ });
3787
+ }
3788
+ const detection = await this.client.detect(detectionRequest);
3789
+ const threshold = options.threshold ?? this.config.threatScoreThreshold;
3790
+ const allowed = detection.decision === "allow" || detection.confidence < threshold;
3791
+ this.log.debug("Server detection", {
3792
+ decision: detection.decision,
3793
+ confidence: detection.confidence,
3794
+ allowed
3795
+ });
3796
+ const conclusion = allowed ? "ALLOW" : detection.decision === "challenge" ? "CHALLENGE" : "DENY";
3797
+ const decision = new Decision({
3798
+ conclusion,
3799
+ reason: allowed ? void 0 : `Threat score ${detection.confidence} (threshold ${threshold})`,
3800
+ detection,
3801
+ id,
3802
+ results: ruleResult?.results ?? [],
3803
+ ruleResult: ruleResult ?? void 0,
3804
+ agent: agentVerdict,
3805
+ key,
3806
+ ttl: this.decisionCache && !allowed ? this.decisionCache.lifetime : 0
3807
+ });
3808
+ if (this.decisionCache) this.decisionCache.set(key, decision);
3809
+ return decision;
3810
+ } catch (error) {
3811
+ const log = error instanceof WebDecoyUnavailableError ? this.log.debug.bind(this.log) : this.log.error.bind(this.log);
3812
+ log("Protection error", {
3813
+ error: error instanceof Error ? error.message : String(error)
3814
+ });
3815
+ return new Decision({
3816
+ conclusion: "ERROR",
3817
+ detection: {
3818
+ decision: "allow",
3819
+ confidence: 0,
3820
+ threat_level: "MINIMAL",
3821
+ bot_detected: false,
3822
+ detection_id: id,
3823
+ rule_enforced: false
3824
+ },
3825
+ id,
3826
+ key,
3827
+ error: error instanceof Error ? error.message : "Unknown error"
3828
+ });
3829
+ }
3830
+ }
3831
+ /**
3832
+ * Report a test-trigger request and return a blocking verdict.
3833
+ *
3834
+ * The verdict is `allowed: false` so an enforce-mode adapter answers the
3835
+ * curl with a 403 — a visibly different response that tells the developer
3836
+ * their middleware acted, Arcjet-quickstart style. (The default monitor
3837
+ * mode still serves the request; the dashboard row is the real receipt.)
3838
+ *
3839
+ * Without an API key nothing can reach the dashboard, so the verdict says
3840
+ * so via `error` instead of pretending the test ran.
3841
+ */
3842
+ async reportTestTrigger(metadata, id) {
3843
+ const blocked = {
3844
+ decision: "block",
3845
+ confidence: 100,
3846
+ threat_level: "HIGH",
3847
+ bot_detected: true,
3848
+ bot_type: "test_trigger",
3849
+ detection_id: id,
3850
+ rule_enforced: false
3851
+ };
3852
+ if (!this.client) {
3853
+ return new Decision({
3854
+ id,
3855
+ conclusion: "DENY",
3856
+ reason: "Reserved test trigger",
3857
+ detection: blocked,
3858
+ error: "Test trigger recognized, but no apiKey is configured \u2014 nothing was reported to the dashboard."
3859
+ });
3860
+ }
3861
+ try {
3862
+ const detection = await this.client.detect({
3863
+ request_metadata: metadata,
3864
+ local_analysis: {
3865
+ suspicious_headers: false,
3866
+ missing_sec_ch_ua: false,
3867
+ datacenter_ip: false,
3868
+ local_score: 100,
3869
+ needs_verification: true,
3870
+ flags: ["test_trigger"]
3871
+ }
3872
+ });
3873
+ return new Decision({
3874
+ id,
3875
+ conclusion: "DENY",
3876
+ reason: "Reserved test trigger",
3877
+ detection
3878
+ });
3879
+ } catch (error) {
3880
+ return new Decision({
3881
+ id,
3882
+ conclusion: "DENY",
3883
+ reason: "Reserved test trigger",
3884
+ detection: blocked,
3885
+ error: error instanceof Error ? error.message : "Failed to report test detection"
3886
+ });
3887
+ }
3888
+ }
3889
+ /**
3890
+ * Validate the API key configuration
3891
+ * Useful for testing integration during setup
3892
+ */
3893
+ async validateConfig() {
3894
+ if (!this.client) {
3895
+ return { valid: false, error: "No API key configured" };
3896
+ }
3897
+ try {
3898
+ const isValid = await this.client.validateAPIKey();
3899
+ return { valid: isValid };
3900
+ } catch (error) {
3901
+ return {
3902
+ valid: false,
3903
+ error: error instanceof Error ? error.message : "Unknown error"
3904
+ };
3905
+ }
3906
+ }
3907
+ /**
3908
+ * Attach a violation reporter for sending violations to the backend.
3909
+ * Called internally when apiKey is present and rules are configured.
3910
+ */
3911
+ setViolationReporter(reporter) {
3912
+ this.violationReporter = reporter;
3913
+ }
3914
+ /**
3915
+ * Get the API client (for use by violation reporter, enrichment, etc.)
3916
+ */
3917
+ getClient() {
3918
+ return this.client;
3919
+ }
3920
+ /**
3921
+ * Get the current configuration
3922
+ */
3923
+ getConfig() {
3924
+ return { ...this.config };
3925
+ }
3926
+ /**
3927
+ * Clean up resources (timers, flush pending violations)
3928
+ */
3929
+ async destroy() {
3930
+ this.ruleEngine?.destroy();
3931
+ if (this.violationReporter) {
3932
+ await this.violationReporter.destroy();
3933
+ }
3934
+ await this.referralCounter?.destroy();
3935
+ }
3936
+ };
3937
+ function agentInputFromMetadata(metadata) {
3938
+ const headers = metadata.headers || {};
3939
+ const host = headers["host"] || headers[":authority"] || headers["x-forwarded-host"] || headers["Host"];
3940
+ if (!host) return null;
3941
+ const proto = headers["x-forwarded-proto"] || headers["X-Forwarded-Proto"];
3942
+ const scheme = (proto ? proto.split(",")[0].trim() : "https") || "https";
3943
+ const rawPath = metadata.path || "/";
3944
+ const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
3945
+ try {
3946
+ return {
3947
+ method: metadata.method,
3948
+ url: `${scheme}://${host}${path}`,
3949
+ headers
3950
+ };
3951
+ } catch {
3952
+ return null;
3953
+ }
3954
+ }
3955
+
3956
+ // src/adapter-core.ts
3957
+ function shouldSkipPath(path, patterns) {
3958
+ if (!patterns || patterns.length === 0) return false;
3959
+ return patterns.some(
3960
+ (pattern) => typeof pattern === "string" ? path === pattern || path.startsWith(pattern) : pattern.test(path)
3961
+ );
3962
+ }
3963
+ function ruleBlockResponse(decision) {
3964
+ const rr2 = decision.ruleResult;
3965
+ if (decision.allowed || !rr2) return null;
3966
+ if (rr2.action === "THROTTLE") {
3967
+ const retryAfter = Number(rr2.metadata?.retryAfter ?? 60);
3968
+ return {
3969
+ status: 429,
3970
+ headers: { "Retry-After": String(retryAfter) },
3971
+ body: {
3972
+ error: "Too Many Requests",
3973
+ message: rr2.reason || "Rate limit exceeded",
3974
+ retry_after: retryAfter
3975
+ }
3976
+ };
3977
+ }
3978
+ if (rr2.action === "DENY") {
3979
+ return {
3980
+ status: 403,
3981
+ headers: {},
3982
+ body: {
3983
+ error: "Forbidden",
3984
+ message: rr2.reason || "Access denied by rule",
3985
+ rule: rr2.rule
3986
+ }
3987
+ };
3988
+ }
3989
+ return null;
3990
+ }
3991
+ function armSiteHoneytoken(sdk, options) {
3992
+ let token = null;
3993
+ void deriveAndArm(sdk, options).then((t) => {
3994
+ token = t;
3995
+ });
3996
+ return () => token;
3997
+ }
3998
+ async function deriveAndArm(sdk, options) {
3999
+ const enabled = (options.enabled ?? true) && Boolean(options.apiKey);
4000
+ if (!enabled) return null;
4001
+ try {
4002
+ const token = await siteHoneytoken({ secret: options.apiKey });
4003
+ sdk.addRule(tripwire({ paths: token.activePaths, includeDefaults: false }));
4004
+ return token;
4005
+ } catch (error) {
4006
+ options.onError?.(error);
4007
+ return null;
4008
+ }
4009
+ }
4010
+
4011
+ // src/fetch-guard.ts
4012
+ function defaultBlocked(_request, decision) {
4013
+ const block = ruleBlockResponse(decision) ?? {
4014
+ status: 403,
4015
+ headers: {},
4016
+ body: { error: "Forbidden", message: "Access denied by Web Decoy protection" }
4017
+ };
4018
+ return new Response(JSON.stringify({ ...block.body, detection_id: decision.id }), {
4019
+ status: block.status,
4020
+ headers: { "content-type": "application/json", ...block.headers }
4021
+ });
4022
+ }
4023
+ function headerRecord(headers) {
4024
+ const out = {};
4025
+ headers.forEach((value, key) => {
4026
+ out[key.toLowerCase()] = value;
4027
+ });
4028
+ return out;
4029
+ }
4030
+ function createFetchGuard(options = {}) {
4031
+ const sdk = new WebDecoy(options);
4032
+ const mode = options.mode ?? "monitor";
4033
+ const onBlocked = options.onBlocked ?? defaultBlocked;
4034
+ const getToken = armSiteHoneytoken(sdk, {
4035
+ apiKey: options.apiKey,
4036
+ enabled: options.honeytoken
4037
+ });
4038
+ function resolveIP(request, peer) {
4039
+ if (options.getIP) return options.getIP(request);
4040
+ return resolveClientIp({
4041
+ headers: request.headers,
4042
+ peer,
4043
+ trustProxy: options.trustProxy ?? 1
4044
+ }) ?? normalizeIp(peer) ?? "127.0.0.1";
4045
+ }
4046
+ return {
4047
+ sdk,
4048
+ skips(pathname) {
4049
+ return shouldSkipPath(pathname, options.skipPaths);
4050
+ },
4051
+ async check(request, peer) {
4052
+ const url = new URL(request.url);
4053
+ const metadata = {
4054
+ method: request.method,
4055
+ path: url.pathname,
4056
+ ip: resolveIP(request, peer),
4057
+ user_agent: request.headers.get("user-agent") ?? void 0,
4058
+ headers: headerRecord(request.headers),
4059
+ query: url.search ? url.search.slice(1) : void 0,
4060
+ timestamp: Date.now()
4061
+ };
4062
+ const decision = await sdk.protect(metadata, {
4063
+ threshold: options.threshold,
4064
+ skipLocalAnalysis: options.skipLocalAnalysis,
4065
+ metadata: options.metadata
4066
+ });
4067
+ if (decision.allowed || mode !== "enforce") return { decision };
4068
+ return { decision, response: await onBlocked(request, decision) };
4069
+ },
4070
+ async decorate(response) {
4071
+ const current = getToken();
4072
+ if (!current) return response;
4073
+ if (!isInjectableHtml(response.headers.get("content-type"))) return response;
4074
+ if (response.bodyUsed) return response;
4075
+ try {
4076
+ const html = await response.text();
4077
+ const injected = injectHoneytokenLink(html, current.linkHtml);
4078
+ if (injected === html) return new Response(html, response);
4079
+ const headers = new Headers(response.headers);
4080
+ headers.delete("content-length");
4081
+ return new Response(injected, {
4082
+ status: response.status,
4083
+ statusText: response.statusText,
4084
+ headers
4085
+ });
4086
+ } catch {
4087
+ return response;
4088
+ }
4089
+ }
4090
+ };
4091
+ }
4092
+
4093
+ // src/detect-and-gate.ts
4094
+ var DECISION_HEADER = "x-webdecoy-decision";
4095
+ var DETECTION_ID_HEADER = "x-webdecoy-detection-id";
4096
+ var WOULD_BLOCK_HEADER = "x-webdecoy-would-block";
4097
+ var warnedBadKey = false;
4098
+ function createDetectAndGate(options = {}) {
4099
+ const gate = createClearanceGate(options);
4100
+ const trustProxy = options.trustProxy ?? 1;
4101
+ let guard = null;
4102
+ let guardKey = "";
4103
+ let failedKey = "";
4104
+ function guardFor(apiKey) {
4105
+ if (guard && guardKey === apiKey) return guard;
4106
+ if (failedKey === apiKey) return null;
4107
+ try {
4108
+ guard = createFetchGuard({ ...options, apiKey, trustProxy, honeytoken: false, mode: options.mode ?? "monitor" });
4109
+ guardKey = apiKey;
4110
+ return guard;
4111
+ } catch (error) {
4112
+ failedKey = apiKey;
4113
+ if (!warnedBadKey) {
4114
+ warnedBadKey = true;
4115
+ console.warn(
4116
+ `[WebDecoy] detection is off: ${error instanceof Error ? error.message : "the API key was rejected"}`
4117
+ );
4118
+ }
4119
+ return null;
4120
+ }
4121
+ }
4122
+ async function detect(request, apiKey) {
4123
+ try {
4124
+ const g = guardFor(apiKey);
4125
+ if (!g) return null;
4126
+ if (shouldSkipPath(new URL(request.url).pathname, options.skipPaths)) return null;
4127
+ return await g.check(request);
4128
+ } catch {
4129
+ return null;
4130
+ }
4131
+ }
4132
+ async function runGate(request, context) {
4133
+ try {
4134
+ return await gate(request, context);
4135
+ } catch {
4136
+ return { action: "continue", headers: null, verdict: null };
4137
+ }
4138
+ }
4139
+ return async (request, context) => {
4140
+ const apiKey = (options.apiKey ?? fromEnv("WEBDECOY_API_KEY")).trim();
4141
+ if (!apiKey) return { outcome: await runGate(request, context), decision: null };
4142
+ const [guarded, gated] = await Promise.all([detect(request, apiKey), runGate(request, context)]);
4143
+ if (!guarded) return { outcome: gated, decision: null };
4144
+ const { decision, response } = guarded;
4145
+ if (response) return { outcome: { action: "respond", response }, decision };
4146
+ if (gated.action === "respond") return { outcome: gated, decision };
4147
+ try {
4148
+ const headers = gated.headers ? new Headers(gated.headers) : tt(request);
4149
+ headers.delete(DECISION_HEADER);
4150
+ headers.delete(DETECTION_ID_HEADER);
4151
+ headers.delete(WOULD_BLOCK_HEADER);
4152
+ headers.set(DECISION_HEADER, decision.detection?.decision ?? "");
4153
+ headers.set(DETECTION_ID_HEADER, decision.detection?.detection_id ?? "");
4154
+ headers.set(WOULD_BLOCK_HEADER, String(!decision.allowed));
4155
+ return { outcome: { action: "continue", headers, verdict: gated.verdict }, decision };
4156
+ } catch {
4157
+ return { outcome: gated, decision };
4158
+ }
4159
+ };
4160
+ }
4161
+
1389
4162
  // src/vercel.ts
1390
4163
  function toMiddlewareResponse(outcome) {
1391
4164
  if (outcome.action === "respond") return outcome.response;
@@ -1409,10 +4182,21 @@ function clearanceMiddleware(options = {}) {
1409
4182
  }
1410
4183
  };
1411
4184
  }
1412
- var middleware = clearanceMiddleware();
4185
+ function createVercelMiddleware(options = {}) {
4186
+ const decide = createDetectAndGate(options);
4187
+ return async (request, context) => {
4188
+ try {
4189
+ return toMiddlewareResponse((await decide(request, context)).outcome);
4190
+ } catch {
4191
+ return void 0;
4192
+ }
4193
+ };
4194
+ }
4195
+ var middleware = createVercelMiddleware();
1413
4196
  var vercel_default = middleware;
1414
4197
  // Annotate the CommonJS export names for ESM import in node:
1415
4198
  0 && (module.exports = {
1416
4199
  clearanceMiddleware,
4200
+ createVercelMiddleware,
1417
4201
  toMiddlewareResponse
1418
4202
  });