#![allow(dead_code)] //! Anti-Detection HTTP Client for IntentForge v2 //! //! Provides human-like HTTP requests with: //! - User agent rotation //! - Proxy rotation (free proxy lists) //! - Request queuing with rate limiting //! - Cookie handling //! - Retry with exponential backoff //! - HTML scraping fallback when RSS fails use anyhow::{Context, Result}; use rand::Rng; use std::collections::VecDeque; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::sync::{Mutex, RwLock}; /// List of realistic user agents (Chrome, Firefox, Safari on different OS) const USER_AGENTS: &[&str] = &[ // Chrome on Windows "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36", // Chrome on Mac "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36", // Firefox on Windows "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0", // Firefox on Mac "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:133.0) Gecko/20100101 Firefox/133.0", // Safari on Mac "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Safari/605.1.15", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15", // Chrome on Linux "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", // Edge on Windows "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0", ]; /// Common referer headers to appear more human-like const REFERERS: &[&str] = &[ "https://www.google.com/", "https://www.bing.com/", "https://duckduckgo.com/", "https://www.google.co.uk/", "https://www.google.de/", "", ]; /// Accept-Language headers for different regions const ACCEPT_LANGUAGES: &[&str] = &[ "en-US,en;q=0.9", "en-US,en;q=0.9,es;q=0.8", "en-GB,en;q=0.9", "en-US,en;q=0.9,de;q=0.8", "en;q=0.9", ]; /// Proxy configuration #[derive(Debug, Clone)] pub struct Proxy { pub url: String, pub proxy_type: ProxyType, pub latency_ms: u64, pub last_used: Option, pub fail_count: u32, } #[derive(Debug, Clone, PartialEq)] pub enum ProxyType { Http, Https, Socks5, } /// Token bucket rate limiter pub struct RateLimiter { tokens: f64, max_tokens: f64, refill_rate: f64, // tokens per second last_refill: Instant, } impl RateLimiter { pub fn new(max_tokens: f64, refill_rate: f64) -> Self { Self { tokens: max_tokens, max_tokens, refill_rate, last_refill: Instant::now(), } } pub async fn acquire(&mut self) { loop { self.refill(); if self.tokens >= 1.0 { self.tokens -= 1.0; return; } // Wait for a token to become available let wait_time = Duration::from_secs_f64((1.0 - self.tokens) / self.refill_rate); tokio::time::sleep(wait_time).await; } } fn refill(&mut self) { let now = Instant::now(); let elapsed = now.duration_since(self.last_refill).as_secs_f64(); self.tokens = (self.tokens + elapsed * self.refill_rate).min(self.max_tokens); self.last_refill = now; } } /// Anti-detection HTTP client pub struct AntiDetectionClient { client: reqwest::Client, proxies: Arc>>, rate_limiters: Arc>>, request_queue: Arc>>, cookie_jar: Arc>>, } struct QueuedRequest { url: String, domain: String, created_at: Instant, } impl AntiDetectionClient { /// Create a new anti-detection client pub async fn new() -> Result { let mut headers = reqwest::header::HeaderMap::new(); headers.insert( reqwest::header::ACCEPT, reqwest::header::HeaderValue::from_static( "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8", ), ); headers.insert( reqwest::header::ACCEPT_ENCODING, reqwest::header::HeaderValue::from_static("gzip, deflate, br"), ); let client = reqwest::Client::builder() .user_agent(USER_AGENTS[0]) .default_headers(headers) .timeout(Duration::from_secs(30)) .pool_max_idle_per_host(2) .pool_idle_timeout(Duration::from_secs(30)) .tcp_keepalive(Duration::from_secs(60)) .build() .context("Failed to create HTTP client")?; let proxies = Arc::new(RwLock::new(Vec::new())); let rate_limiters = Arc::new(RwLock::new(std::collections::HashMap::new())); let request_queue = Arc::new(Mutex::new(VecDeque::new())); let cookie_jar = Arc::new(RwLock::new(std::collections::HashMap::new())); let instance = Self { client, proxies, rate_limiters, request_queue, cookie_jar, }; // Load initial proxies instance.load_proxies().await?; Ok(instance) } /// Load proxies from free proxy lists async fn load_proxies(&self) -> Result<()> { let proxy_sources = vec![ "https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=10000&country=all&ssl=all&anonymity=all", "https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt", "https://raw.githubusercontent.com/clarketm/proxy-list/master/proxy-list-raw.txt", ]; let mut proxies = self.proxies.write().await; proxies.clear(); for source in proxy_sources { match self.client.get(source).send().await { Ok(resp) => { if let Ok(text) = resp.text().await { for line in text.lines() { let line = line.trim(); if !line.is_empty() && line.contains(':') { let url = if line.starts_with("http") { line.to_string() } else { format!("http://{}", line) }; proxies.push(Proxy { url, proxy_type: ProxyType::Http, latency_ms: 0, last_used: None, fail_count: 0, }); } } } } Err(e) => { tracing::warn!("Failed to load proxies from {}: {}", source, e); } } } tracing::info!("Loaded {} proxies", proxies.len()); Ok(()) } /// Get a random user agent fn random_user_agent() -> &'static str { let mut rng = rand::thread_rng(); USER_AGENTS[rng.gen_range(0..USER_AGENTS.len())] } /// Get a random referer fn random_referer() -> &'static str { let mut rng = rand::thread_rng(); REFERERS[rng.gen_range(0..REFERERS.len())] } /// Get a random accept language fn random_accept_language() -> &'static str { let mut rng = rand::thread_rng(); ACCEPT_LANGUAGES[rng.gen_range(0..ACCEPT_LANGUAGES.len())] } /// Get rate limiter for a domain async fn get_rate_limiter(&self, domain: &str) -> RateLimiter { let mut limiters = self.rate_limiters.write().await; limiters .entry(domain.to_string()) .or_insert_with(|| { // Default: 2 requests per second per domain RateLimiter::new(5.0, 2.0) }) .clone() } /// Add random delay between requests (200-800ms) async fn random_delay() { let mut rng = rand::thread_rng(); let delay_ms = rng.gen_range(200..800); tokio::time::sleep(Duration::from_millis(delay_ms)).await; } /// Extract domain from URL fn extract_domain(url: &str) -> String { url::Url::parse(url) .ok() .and_then(|u| u.host_str().map(|h| h.to_string())) .unwrap_or_default() } /// Make a GET request with anti-detection measures pub async fn get(&self, url: &str) -> Result { let domain = Self::extract_domain(url); // Rate limit per domain { let mut limiters = self.rate_limiters.write().await; let limiter = limiters .entry(domain.clone()) .or_insert_with(|| RateLimiter::new(5.0, 2.0)); limiter.acquire().await; } // Random delay Self::random_delay().await; // Build request with human-like headers let user_agent = Self::random_user_agent(); let referer = Self::random_referer(); let accept_language = Self::random_accept_language(); let mut request = self .client .get(url) .header("User-Agent", user_agent) .header("Accept-Language", accept_language) .header("DNT", "1") .header("Connection", "keep-alive") .header("Upgrade-Insecure-Requests", "1") .header("Sec-Fetch-Dest", "document") .header("Sec-Fetch-Mode", "navigate") .header("Sec-Fetch-Site", "none") .header("Sec-Fetch-User", "?1") .header("Cache-Control", "max-age=0"); if !referer.is_empty() { request = request.header("Referer", referer); } // Add cookies if we have any for this domain { let cookies = self.cookie_jar.read().await; if let Some(cookie) = cookies.get(&domain) { request = request.header("Cookie", cookie); } } // Send request with retry let response = self.send_with_retry(request, url, 3).await?; // Store cookies from response if let Some(set_cookie) = response.headers().get("set-cookie") { if let Ok(cookie_str) = set_cookie.to_str() { let mut cookies = self.cookie_jar.write().await; cookies.insert(domain, cookie_str.to_string()); } } Ok(response) } /// Send request with retry and exponential backoff async fn send_with_retry( &self, request: reqwest::RequestBuilder, url: &str, max_retries: u32, ) -> Result { let mut last_error = None; for attempt in 0..max_retries { let req = request.try_clone().context("Failed to clone request")?; match req.send().await { Ok(response) => { let status = response.status(); // Handle rate limiting (429) if status == 429 { let retry_after = response .headers() .get("retry-after") .and_then(|v| v.to_str().ok()) .and_then(|v| v.parse::().ok()) .unwrap_or(60); tracing::warn!( "Rate limited on {} (attempt {}/{}), waiting {}s", url, attempt + 1, max_retries, retry_after ); tokio::time::sleep(Duration::from_secs(retry_after)).await; continue; } // Handle 403 Forbidden - try with different user agent if status == 403 && attempt < max_retries - 1 { tracing::warn!( "403 Forbidden on {} (attempt {}/{}), retrying with different headers", url, attempt + 1, max_retries ); // Wait before retry with exponential backoff let wait_time = Duration::from_secs(2u64.pow(attempt)); tokio::time::sleep(wait_time).await; continue; } return Ok(response); } Err(e) => { last_error = Some(e); if attempt < max_retries - 1 { let wait_time = Duration::from_secs(2u64.pow(attempt)); tracing::warn!( "Request failed on {} (attempt {}/{}): retrying in {:?}", url, attempt + 1, max_retries, wait_time ); tokio::time::sleep(wait_time).await; } } } } Err(last_error .map(|e| anyhow::anyhow!("{}", e)) .unwrap_or_else(|| anyhow::anyhow!("Request failed after {} attempts", max_retries))) } /// Try fetching with proxy pub async fn get_with_proxy(&self, url: &str) -> Result { let proxies = self.proxies.read().await; if proxies.is_empty() { return self.get(url).await; } // Try up to 3 different proxies let mut rng = rand::thread_rng(); for _ in 0..3 { let proxy_idx = rng.gen_range(0..proxies.len()); let proxy = &proxies[proxy_idx]; let proxy_client = reqwest::Client::builder() .user_agent(Self::random_user_agent()) .timeout(Duration::from_secs(15)) .proxy(reqwest::Proxy::all(&proxy.url)?) .build(); if let Ok(client) = proxy_client { match client.get(url).send().await { Ok(resp) if resp.status().is_success() => { return Ok(resp); } _ => continue, } } } // Fall back to direct request self.get(url).await } /// Scrape content from HTML page (fallback when RSS fails) pub async fn scrape_html(&self, url: &str) -> Result> { let response = self.get(url).await?; let html = response.text().await?; let mut items = Vec::new(); // Simple link extraction (for article-like pages) let link_regex = regex::Regex::new(r#"]+href="([^"]+)"[^>]*>([^<]+)"#).unwrap(); for cap in link_regex.captures_iter(&html) { if let (Some(href), Some(title)) = (cap.get(1), cap.get(2)) { let href = href.as_str(); let title = title.as_str().trim(); // Filter for article-like links if title.len() > 20 && title.len() < 200 && !href.starts_with('#') && !href.starts_with("javascript:") && (href.starts_with("http") || href.starts_with('/')) { let full_url = if href.starts_with('/') { let base = url::Url::parse(url)?; base.join(href)?.to_string() } else { href.to_string() }; items.push(ScrapedItem { title: title.to_string(), url: full_url, description: None, }); } } } // Limit to reasonable number items.truncate(20); Ok(items) } } /// Scraped item from HTML #[derive(Debug, Clone)] pub struct ScrapedItem { pub title: String, pub url: String, pub description: Option, } impl Clone for RateLimiter { fn clone(&self) -> Self { Self { tokens: self.tokens, max_tokens: self.max_tokens, refill_rate: self.refill_rate, last_refill: Instant::now(), } } } #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn test_rate_limiter() { let mut limiter = RateLimiter::new(5.0, 10.0); // Should be able to acquire 5 tokens immediately for _ in 0..5 { limiter.acquire().await; } // 6th token should require waiting let start = Instant::now(); limiter.acquire().await; let elapsed = start.elapsed(); // Should have waited approximately 0.1 seconds (1/10 tokens per second) assert!(elapsed >= Duration::from_millis(50)); } #[test] fn test_extract_domain() { assert_eq!( AntiDetectionClient::extract_domain("https://example.com/path"), "example.com" ); assert_eq!( AntiDetectionClient::extract_domain("http://sub.example.com:8080/path"), "sub.example.com" ); } #[test] fn test_user_agent_rotation() { let mut agents = std::collections::HashSet::new(); for _ in 0..20 { agents.insert(AntiDetectionClient::random_user_agent()); } // Should have at least 3 different user agents assert!(agents.len() >= 3); } }