Spaces:
Build error
Build error
File size: 15,363 Bytes
0ca462b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 | #![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"));
}
}
|