Likhith Sai Seemala
Deploy IntentForge v2 to HF Spaces
0ca462b
Raw History Blame Contribute Delete
15.4 kB
#![allow(dead_code)]
//! Anti-detection module for IntentForge v2
//!
//! Implements bot detection resilience strategies including:
//! - Header-TLS alignment (Sec-CH-UA hints match User-Agent)
//! - Grease strings ("Not;A Brand" format)
//! - Realistic browser header profiles
//! - Rotating user agents with proper header combinations
use rand::Rng;
use reqwest::header::{
HeaderMap, HeaderValue, ACCEPT, ACCEPT_LANGUAGE, UPGRADE_INSECURE_REQUESTS, USER_AGENT,
};
/// Browser profile with aligned headers and Sec-CH-UA hints
#[derive(Debug, Clone)]
pub struct BrowserProfile {
pub user_agent: String,
pub sec_ch_ua: String,
pub sec_ch_ua_mobile: String,
pub sec_ch_ua_platform: String,
pub accept_language: String,
pub accept_encoding: String,
pub sec_fetch_site: String,
pub sec_fetch_mode: String,
pub sec_fetch_dest: String,
pub sec_fetch_user: Option<String>,
}
/// Chrome browser version profiles
#[derive(Debug, Clone)]
struct ChromeVersion {
major: u16,
full: &'static str,
brand_version: &'static str,
chromium_version: &'static str,
}
/// Known Chrome versions for realistic UA generation
const CHROME_VERSIONS: &[ChromeVersion] = &[
ChromeVersion {
major: 124,
full: "124.0.6367.207",
brand_version: "\"Chromium\";v=\"124\"",
chromium_version: "\"Google Chrome\";v=\"124\"",
},
ChromeVersion {
major: 123,
full: "123.0.6312.122",
brand_version: "\"Chromium\";v=\"123\"",
chromium_version: "\"Google Chrome\";v=\"123\"",
},
ChromeVersion {
major: 122,
full: "122.0.6261.128",
brand_version: "\"Chromium\";v=\"122\"",
chromium_version: "\"Google Chrome\";v=\"122\"",
},
ChromeVersion {
major: 121,
full: "121.0.6167.184",
brand_version: "\"Chromium\";v=\"121\"",
chromium_version: "\"Google Chrome\";v=\"121\"",
},
];
/// Platform configurations
#[derive(Debug, Clone)]
struct PlatformConfig {
platform: &'static str,
platform_version: &'static str,
mobile: bool,
}
const PLATFORMS: &[PlatformConfig] = &[
PlatformConfig {
platform: "\"Windows\"",
platform_version: "\"15.0.0\"",
mobile: false,
},
PlatformConfig {
platform: "\"macOS\"",
platform_version: "\"14.4.0\"",
mobile: false,
},
PlatformConfig {
platform: "\"Linux\"",
platform_version: "\"\"",
mobile: false,
},
PlatformConfig {
platform: "\"Android\"",
platform_version: "\"14.0.0\"",
mobile: true,
},
];
/// Generate a "Not;A Brand" grease string
///
/// Grease strings are randomized brand identifiers used in Sec-CH-UA headers
/// to prevent fingerprinting based on exact brand list.
/// Format: "Not_A Brand" or "Not;A Brand" with varying separators.
fn generate_grease_string(rng: &mut impl Rng) -> String {
let separators = ['_', ';', ' '];
let prefix_words = ["Not", "Not_A", "Not;A"];
let suffix_words = ["Brand", "Browser", "Chromium"];
let sep = separators[rng.gen_range(0..separators.len())];
let prefix = prefix_words[rng.gen_range(0..prefix_words.len())];
let suffix = suffix_words[rng.gen_range(0..suffix_words.len())];
format!("{}{}{}", prefix, sep, suffix)
}
/// Generate realistic Sec-CH-UA header value
///
/// Format: "Not_A Brand";v="8", "Chromium";v="124", "Google Chrome";v="124"
/// The grease string varies in position (usually first or last).
fn generate_sec_ch_ua(version: &ChromeVersion, rng: &mut impl Rng) -> String {
let grease = generate_grease_string(rng);
// Randomly decide if grease goes first or last
let grease_first = rng.gen_bool(0.7);
if grease_first {
format!(
"\"{}\";v=\"{}\", {}, {}",
grease, version.major, version.brand_version, version.chromium_version
)
} else {
format!(
"{}, {}, \"{}\";v=\"{}\"",
version.brand_version, version.chromium_version, grease, version.major
)
}
}
/// Header generator with TLS alignment
///
/// Ensures Sec-CH-UA hints are perfectly aligned with the User-Agent string.
/// This prevents detection through header inconsistencies.
pub struct HeaderGenerator {
profiles: Vec<BrowserProfile>,
}
impl HeaderGenerator {
/// Create a new header generator with pre-computed browser profiles
pub fn new() -> Self {
let mut profiles = Vec::new();
let mut rng = rand::thread_rng();
for version in CHROME_VERSIONS {
for platform in PLATFORMS {
let ua = generate_user_agent(version, platform);
let sec_ch_ua = generate_sec_ch_ua(version, &mut rng);
let sec_ch_ua_mobile = if platform.mobile { "?1" } else { "?0" };
let sec_ch_ua_platform = platform.platform.to_string();
profiles.push(BrowserProfile {
user_agent: ua,
sec_ch_ua,
sec_ch_ua_mobile: sec_ch_ua_mobile.to_string(),
sec_ch_ua_platform,
accept_language: generate_accept_language(&mut rng),
accept_encoding: "gzip, deflate, br".to_string(),
sec_fetch_site: "none".to_string(),
sec_fetch_mode: "navigate".to_string(),
sec_fetch_dest: "document".to_string(),
sec_fetch_user: Some("?1".to_string()),
});
}
}
Self { profiles }
}
/// Get a random browser profile
pub fn random_profile(&self) -> &BrowserProfile {
let mut rng = rand::thread_rng();
let idx = rng.gen_range(0..self.profiles.len());
&self.profiles[idx]
}
/// Get a profile that matches a specific User-Agent
pub fn matching_profile(&self, user_agent: &str) -> Option<&BrowserProfile> {
self.profiles.iter().find(|p| p.user_agent == user_agent)
}
/// Generate headers for a reqwest request
pub fn generate_headers(&self) -> HeaderMap {
let profile = self.random_profile();
self.profile_to_headers(profile)
}
/// Convert a browser profile to reqwest HeaderMap
fn profile_to_headers(&self, profile: &BrowserProfile) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(
USER_AGENT,
HeaderValue::from_str(&profile.user_agent).unwrap(),
);
headers.insert(
ACCEPT,
HeaderValue::from_static(
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
),
);
headers.insert(
ACCEPT_LANGUAGE,
HeaderValue::from_str(&profile.accept_language).unwrap(),
);
headers.insert(
"sec-ch-ua",
HeaderValue::from_str(&profile.sec_ch_ua).unwrap(),
);
headers.insert(
"sec-ch-ua-mobile",
HeaderValue::from_str(&profile.sec_ch_ua_mobile).unwrap(),
);
headers.insert(
"sec-ch-ua-platform",
HeaderValue::from_str(&profile.sec_ch_ua_platform).unwrap(),
);
headers.insert(
"sec-fetch-site",
HeaderValue::from_str(&profile.sec_fetch_site).unwrap(),
);
headers.insert(
"sec-fetch-mode",
HeaderValue::from_str(&profile.sec_fetch_mode).unwrap(),
);
headers.insert(
"sec-fetch-dest",
HeaderValue::from_str(&profile.sec_fetch_dest).unwrap(),
);
if let Some(ref sec_fetch_user) = profile.sec_fetch_user {
headers.insert(
"sec-fetch-user",
HeaderValue::from_str(sec_fetch_user).unwrap(),
);
}
headers.insert(UPGRADE_INSECURE_REQUESTS, HeaderValue::from_static("1"));
headers
}
/// Build a reqwest::Client with realistic headers
pub fn build_client(&self) -> reqwest::Client {
let profile = self.random_profile();
let headers = self.profile_to_headers(profile);
reqwest::Client::builder()
.user_agent(&profile.user_agent)
.default_headers(headers)
.timeout(std::time::Duration::from_secs(30))
.pool_max_idle_per_host(8)
.build()
.expect("Failed to build HTTP client with anti-detection headers")
}
}
impl Default for HeaderGenerator {
fn default() -> Self {
Self::new()
}
}
/// Generate a realistic User-Agent string for Chrome
fn generate_user_agent(version: &ChromeVersion, platform: &PlatformConfig) -> String {
if platform.mobile {
format!(
"Mozilla/5.0 (Linux; Android {}; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{} Mobile Safari/537.36",
"14", version.full
)
} else {
let os = match platform.platform {
"\"Windows\"" => format!("Windows NT {}", platform.platform_version.trim_matches('"')),
"\"macOS\"" => "Macintosh; Intel Mac OS X 10_15_7".to_string(),
"\"Linux\"" => "X11; Linux x86_64".to_string(),
_ => "Windows NT 10.0; Win64; x64".to_string(),
};
format!(
"Mozilla/5.0 ({}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{} Safari/537.36",
os, version.full
)
}
}
/// Generate a realistic Accept-Language header
fn generate_accept_language(rng: &mut impl Rng) -> String {
let languages = [
"en-US,en;q=0.9",
"en-GB,en;q=0.9",
"en-US,en;q=0.9,es;q=0.8",
"en-US,en;q=0.9,fr;q=0.8,de;q=0.7",
"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
"en-US,en;q=0.9,ja;q=0.8",
];
languages[rng.gen_range(0..languages.len())].to_string()
}
/// Rotating user agent pool for high-volume scraping
///
/// Maintains a pool of user agents and rotates through them
/// to avoid pattern-based detection.
pub struct UserAgentRotator {
profiles: Vec<BrowserProfile>,
current: std::sync::atomic::AtomicUsize,
}
impl UserAgentRotator {
pub fn new() -> Self {
let generator = HeaderGenerator::new();
Self {
profiles: generator.profiles,
current: std::sync::atomic::AtomicUsize::new(0),
}
}
/// Get the next user agent in the rotation
pub fn next(&self) -> &BrowserProfile {
use std::sync::atomic::Ordering;
let idx = self.current.fetch_add(1, Ordering::Relaxed) % self.profiles.len();
&self.profiles[idx]
}
/// Get a random user agent
pub fn random(&self) -> &BrowserProfile {
let mut rng = rand::thread_rng();
let idx = rand::Rng::gen_range(&mut rng, 0..self.profiles.len());
&self.profiles[idx]
}
/// Get all available user agents
pub fn all(&self) -> &[BrowserProfile] {
&self.profiles
}
}
impl Default for UserAgentRotator {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_grease_string_generation() {
let mut rng = rand::thread_rng();
for _ in 0..100 {
let grease = generate_grease_string(&mut rng);
assert!(!grease.is_empty());
assert!(
grease.contains("Not") || grease.contains("Brand") || grease.contains("Browser")
);
}
}
#[test]
fn test_sec_ch_ua_format() {
let mut rng = rand::thread_rng();
let version = &CHROME_VERSIONS[0];
let sec_ch_ua = generate_sec_ch_ua(version, &mut rng);
// Should contain the Chrome version
assert!(sec_ch_ua.contains(&format!("\"{}\"", version.major)));
// Should contain Chromium
assert!(sec_ch_ua.contains("Chromium"));
// Should contain Google Chrome
assert!(sec_ch_ua.contains("Google Chrome"));
}
#[test]
fn test_header_generator_profiles() {
let gen = HeaderGenerator::new();
assert!(!gen.profiles.is_empty());
// Should have profiles for each version × platform combination
assert_eq!(gen.profiles.len(), CHROME_VERSIONS.len() * PLATFORMS.len());
}
#[test]
fn test_header_generator_random_profile() {
let gen = HeaderGenerator::new();
let profile = gen.random_profile();
assert!(!profile.user_agent.is_empty());
assert!(!profile.sec_ch_ua.is_empty());
assert!(!profile.accept_language.is_empty());
}
#[test]
fn test_profile_alignment() {
let gen = HeaderGenerator::new();
for profile in gen.profiles.iter().take(5) {
// If UA contains "Mobile", sec-ch-ua-mobile should be "?1"
if profile.user_agent.contains("Mobile") {
assert_eq!(profile.sec_ch_ua_mobile, "?1");
}
// If UA contains "Windows", platform should be "Windows"
if profile.user_agent.contains("Windows") {
assert!(profile.sec_ch_ua_platform.contains("Windows"));
}
// If UA contains "Mac", platform should be "macOS"
if profile.user_agent.contains("Macintosh") {
assert!(profile.sec_ch_ua_platform.contains("macOS"));
}
}
}
#[test]
fn test_user_agent_rotator() {
let rotator = UserAgentRotator::new();
let first = rotator.next().user_agent.clone();
let second = rotator.next().user_agent.clone();
// With enough profiles, rotation should give different results eventually
// (may be same if only 1 profile, but we have many)
assert!(!first.is_empty());
assert!(!second.is_empty());
}
#[test]
fn test_user_agent_format() {
let version = &CHROME_VERSIONS[0];
let desktop = &PLATFORMS[0]; // Windows
let ua = generate_user_agent(version, desktop);
assert!(ua.starts_with("Mozilla/5.0"));
assert!(ua.contains("Chrome/124"));
assert!(ua.contains("Safari/537.36"));
assert!(!ua.contains("Mobile"));
}
#[test]
fn test_mobile_user_agent_format() {
let version = &CHROME_VERSIONS[0];
let mobile = &PLATFORMS[3]; // Android
let ua = generate_user_agent(version, mobile);
assert!(ua.contains("Android"));
assert!(ua.contains("Mobile"));
assert!(ua.contains("Chrome/124"));
}
#[test]
fn test_accept_language_variations() {
let mut rng = rand::thread_rng();
let mut langs = std::collections::HashSet::new();
for _ in 0..50 {
langs.insert(generate_accept_language(&mut rng));
}
// Should have multiple variations
assert!(langs.len() > 1);
}
#[test]
fn test_generate_headers() {
let gen = HeaderGenerator::new();
let headers = gen.generate_headers();
assert!(headers.contains_key("user-agent"));
assert!(headers.contains_key("sec-ch-ua"));
assert!(headers.contains_key("sec-ch-ua-mobile"));
assert!(headers.contains_key("sec-ch-ua-platform"));
assert!(headers.contains_key("accept"));
assert!(headers.contains_key("accept-language"));
}
}