File size: 2,356 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
//! TLS fingerprint configuration for Cloudflare bypass
//!
//! The default reqwest+rustls TLS fingerprint can be distinctive and gets
//! blocked by Cloudflare. This module builds reqwest clients with
//! Chrome-aligned headers and HTTP/2 prioritization to reduce detectability.

#![allow(dead_code)]

use reqwest::Client;
use std::time::Duration;

use super::detector::{ChallengeType, CloudflareDetector};
use crate::anti_detection::HeaderGenerator;

/// Build a stealth HTTP client that mimics Chrome's TLS behavior.
pub fn build_stealth_client(proxy_url: Option<&str>) -> Client {
    let header_gen = HeaderGenerator::new();
    let profile = header_gen.random_profile();

    let mut builder = Client::builder()
        .user_agent(&profile.user_agent)
        .timeout(Duration::from_secs(30))
        .pool_max_idle_per_host(8)
        // Negotiate HTTP/2 (Chrome always sends h2 ALPN)
        .http2_prior_knowledge()
        // Follow redirects like a browser
        .redirect(reqwest::redirect::Policy::limited(10))
        // Set realistic default headers
        .default_headers(crate::anti_detection::HeaderGenerator::new().generate_headers());

    // Add proxy if available
    if let Some(proxy) = proxy_url {
        if let Ok(p) = reqwest::Proxy::all(proxy) {
            builder = builder.proxy(p);
        }
    }

    builder
        .build()
        .expect("Failed to build stealth HTTP client")
}

/// Attempt to fetch a URL with Cloudflare bypass awareness.
///
/// Returns Ok(html) if content was retrieved, Err if blocked by Cloudflare.
pub async fn stealth_fetch(
    client: &Client,
    url: &str,
) -> Result<(u16, Vec<(String, String)>, String), reqwest::Error> {
    let resp = client.get(url).send().await?;
    let status = resp.status().as_u16();

    let headers: Vec<(String, String)> = resp
        .headers()
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
        .collect();

    let body = resp.text().await?;

    // Log if we hit a Cloudflare challenge
    let challenge = CloudflareDetector::detect(status, &headers, &body);
    if challenge != ChallengeType::None {
        tracing::debug!(
            "Cloudflare {:?} detected at {} (status: {})",
            challenge,
            url,
            status
        );
    }

    Ok((status, headers, body))
}