Initial commit

This commit is contained in:
amurcanov committed 2026-10-03 04:20:28 +03:00
commit 71712b07db
263 files changed
+83991

No files matched your search

+146
View File
@@ -0,0 +1,146 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.89"
name = "primp"
version = "1.3.1"
authors = ["deedy5"]
build = false
include = [
"README.md",
"Cargo.toml",
"LICENSE-MIT",
"src/**/*.rs",
]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "HTTP client with browser impersonation capabilities"
readme = "README.md"
keywords = [
"http",
"request",
"client",
"impersonate",
]
categories = ["web-programming::http-client"]
license = "MIT"
repository = "https://github.com/deedy5/primp"
resolver = "3"
[package.metadata.docs.rs]
features = [
"impersonate",
"socks",
"hickory-dns",
"rustls-no-provider",
]
rustdoc-args = [
"--cfg",
"docsrs",
"--cfg",
"reqwest_unstable",
]
rustc-args = [
"--cfg",
"reqwest_unstable",
]
targets = [
"x86_64-unknown-linux-gnu",
"wasm32-unknown-unknown",
]
[features]
brotli = ["reqwest/brotli"]
cookies = ["reqwest/cookies"]
default = ["impersonate"]
default-tls = ["reqwest/default-tls"]
deflate = ["reqwest/deflate"]
form = ["reqwest/form"]
gzip = ["reqwest/gzip"]
hickory-dns = ["reqwest/hickory-dns"]
http2 = ["reqwest/http2"]
http3 = ["reqwest/http3"]
impersonate = [
"dep:rand",
"default-tls",
"http2",
"cookies",
"gzip",
"brotli",
"zstd",
"deflate",
]
json = ["reqwest/json"]
multipart = ["reqwest/multipart"]
query = ["reqwest/query"]
rustls-no-provider = ["reqwest/rustls-no-provider"]
socks = ["reqwest/socks"]
stream = ["reqwest/stream"]
system-proxy = ["reqwest/system-proxy"]
zstd = ["reqwest/zstd"]
[lib]
name = "primp"
path = "src/lib.rs"
[dependencies.http]
version = "1.1"
[dependencies.rand]
version = "0.10"
optional = true
[dependencies.reqwest]
version = "0.13"
default-features = false
package = "primp-reqwest"
[dependencies.url]
version = "2.4"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.h2]
version = "0.4"
features = ["unstable"]
package = "primp-h2"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.rustls]
version = "0.23"
features = [
"std",
"tls12",
"impersonate",
"zlib",
]
default-features = false
package = "primp-rustls"
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies.criterion]
version = "0.7"
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies.serde]
version = "1.0"
features = ["derive"]
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies.serde_json]
version = "1.0"
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies.tokio]
version = "1.0"
features = [
"macros",
"rt-multi-thread",
]
default-features = false
+298
View File
@@ -0,0 +1,298 @@
//! Chrome browser impersonation settings.
//!
//! This module provides configuration for impersonating various Chrome browser versions.
//! Each version has its own TLS fingerprint, ALPN protocols, and default HTTP headers
//! that mimic the real Chrome browser behavior.
//!
//! # Usage
//!
//! ```rust
//! use primp::{Client, Impersonate};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = Client::builder()
//! .impersonate(Impersonate::ChromeV144)
//! .build()?;
//!
//! //let response = client.get("https://example.com").send().await?;
//! Ok(())
//! }
//! ```
pub use crate::imp::Impersonate;
#[cfg(feature = "http2")]
use crate::imp::{PseudoId, PseudoOrder, SettingId, SettingsOrder};
use http::header::*;
use rustls::client::{BrowserEmulator, BrowserType, BrowserVersion};
use rustls::crypto::emulation;
use std::sync::{Arc, OnceLock};
/// Builds browser settings for a specific Chrome version and OS.
pub(crate) fn build_chrome_settings(
chrome: Impersonate,
os: crate::imp::ImpersonateOS,
) -> crate::imp::BrowserSettings {
let os = if matches!(os, crate::imp::ImpersonateOS::Random) {
crate::imp::random_impersonate_os()
} else {
os
};
let user_agent = build_user_agent(chrome, os);
let sec_ch_ua = build_sec_ch_ua(chrome, os);
let mut headers = base_chrome_headers().clone();
headers.insert(USER_AGENT, http::HeaderValue::from_static(user_agent));
headers.insert("sec-ch-ua", http::HeaderValue::from_static(sec_ch_ua));
headers.insert(
"sec-ch-ua-mobile",
http::HeaderValue::from_static(
if matches!(
os,
crate::imp::ImpersonateOS::Android | crate::imp::ImpersonateOS::IOS
) {
"?1"
} else {
"?0"
},
),
);
headers.insert(
"sec-ch-ua-platform",
http::HeaderValue::from_static(crate::imp::os_platform(os)),
);
// Get cached browser emulator for Chrome (avoids Vec allocations on each call)
let browser_emulator = chrome_emulator(chrome);
let http2 = build_http2_settings(chrome);
crate::imp::BrowserSettings {
browser_emulator,
http2,
headers,
gzip: true,
brotli: true,
zstd: true,
deflate: true,
}
}
/// Builds a User-Agent string for a Chrome version and OS.
fn build_user_agent(chrome: Impersonate, os: crate::imp::ImpersonateOS) -> &'static str {
match chrome {
Impersonate::ChromeV144 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Mobile Safari/537.36",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/144.0.0.0 Mobile/15E148 Safari/604.1",
_ => unreachable!(),
},
Impersonate::ChromeV145 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Mobile Safari/537.36",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/145.0.0.0 Mobile/15E148 Safari/604.1",
_ => unreachable!(),
},
Impersonate::ChromeV146 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Mobile Safari/537.36",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/146.0.0.0 Mobile/15E148 Safari/604.1",
_ => unreachable!(),
},
Impersonate::ChromeV147 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Mobile Safari/537.36",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/147.0.0.0 Mobile/15E148 Safari/604.1",
_ => unreachable!(),
},
Impersonate::ChromeV148 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Mobile Safari/537.36",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/148.0.0.0 Mobile/15E148 Safari/604.1",
_ => unreachable!(),
},
_ => unreachable!(),
}
}
/// Builds a sec-ch-ua header value for a Chrome version and OS.
fn build_sec_ch_ua(chrome: Impersonate, _os: crate::imp::ImpersonateOS) -> &'static str {
match chrome {
Impersonate::ChromeV144 => {
r#""Not(A:Brand";v="8", "Chromium";v="144", "Google Chrome";v="144""#
}
Impersonate::ChromeV145 => {
r#""Not:A-Brand";v="99", "Google Chrome";v="145", "Chromium";v="145""#
}
Impersonate::ChromeV146 => {
r#""Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146""#
}
Impersonate::ChromeV147 => {
r#""Google Chrome";v="147", "Not.A/Brand";v="8", "Chromium";v="147""#
}
Impersonate::ChromeV148 => {
r#""Chromium";v="148", "Google Chrome";v="148", "Not/A)Brand";v="99""#
}
_ => unreachable!(),
}
}
/// Builds HTTP/2 settings for a Chrome version.
#[cfg(feature = "http2")]
fn build_http2_settings(chrome: Impersonate) -> crate::imp::Http2Data {
// Chrome 148 uses different header order (sec-ch-ua after sec-fetch-*)
let headers_order = if matches!(chrome, Impersonate::ChromeV148) {
Some(crate::imp::header_order_upgrade_first_sec_chua_last().clone())
} else {
Some(crate::imp::header_order_sec_chua_first().clone())
};
crate::imp::Http2Data {
settings_order: Some(chrome_settings_order().clone()),
headers_pseudo_order: Some(chrome_pseudo_order().clone()),
headers_order,
headers_priority: Some((255, 0, true)),
initial_stream_window_size: Some(crate::imp::CHROME_INITIAL_STREAM_WINDOW),
initial_connection_window_size: Some(crate::imp::CHROME_INITIAL_CONNECTION_WINDOW),
max_header_list_size: Some(crate::imp::CHROME_MAX_HEADER_LIST_SIZE),
header_table_size: Some(crate::imp::CHROME_HEADER_TABLE_SIZE),
..Default::default()
}
}
fn chrome_emulator(chrome: Impersonate) -> Arc<BrowserEmulator> {
match chrome {
Impersonate::ChromeV144 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_chrome_emulator(144)))
.clone()
}
Impersonate::ChromeV145 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_chrome_emulator(145)))
.clone()
}
Impersonate::ChromeV146 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_chrome_emulator(146)))
.clone()
}
Impersonate::ChromeV147 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_chrome_emulator(147)))
.clone()
}
Impersonate::ChromeV148 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_chrome_emulator(148)))
.clone()
}
_ => unreachable!(),
}
}
fn new_chrome_emulator(major: u16) -> BrowserEmulator {
let mut emulator = BrowserEmulator::new(BrowserType::Chrome, BrowserVersion::new(major, 0, 0));
emulator.cipher_suites = Some(emulation::cipher_suites::CHROME.to_vec());
emulator.signature_algorithms = Some(emulation::signature_algorithms::CHROME.to_vec());
emulator.named_groups = Some(emulation::named_groups::CHROME.to_vec());
emulator.extension_order_seed = Some(emulation::extension_order::CHROME);
emulator
}
fn base_chrome_headers() -> &'static http::HeaderMap {
static BASE: OnceLock<http::HeaderMap> = OnceLock::new();
BASE.get_or_init(|| {
let mut headers = http::HeaderMap::with_capacity(13);
headers.insert(ACCEPT, http::HeaderValue::from_static("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"));
headers.insert("accept-encoding", http::HeaderValue::from_static("gzip, deflate, br, zstd"));
headers.insert("accept-language", http::HeaderValue::from_static("en-US,en;q=0.9"));
headers.insert("upgrade-insecure-requests", http::HeaderValue::from_static("1"));
headers.insert("sec-fetch-site", http::HeaderValue::from_static("none"));
headers.insert("sec-fetch-mode", http::HeaderValue::from_static("navigate"));
headers.insert("sec-fetch-dest", http::HeaderValue::from_static("document"));
headers.insert("sec-fetch-user", http::HeaderValue::from_static("?1"));
headers.insert("priority", http::HeaderValue::from_static("u=0, i"));
headers
})
}
#[cfg(feature = "http2")]
fn chrome_settings_order() -> &'static SettingsOrder {
static ORDER: OnceLock<SettingsOrder> = OnceLock::new();
ORDER.get_or_init(|| {
SettingsOrder::builder()
.push(SettingId::HeaderTableSize)
.push(SettingId::EnablePush)
.push(SettingId::InitialWindowSize)
.push(SettingId::MaxHeaderListSize)
.build_without_extend()
})
}
#[cfg(feature = "http2")]
fn chrome_pseudo_order() -> &'static PseudoOrder {
static ORDER: OnceLock<PseudoOrder> = OnceLock::new();
ORDER.get_or_init(|| {
PseudoOrder::builder()
.push(PseudoId::Method)
.push(PseudoId::Authority)
.push(PseudoId::Scheme)
.push(PseudoId::Path)
.build()
})
}
#[cfg(test)]
mod tests {
use crate::imp::Impersonate;
use crate::Client;
use serde::{Deserialize, Serialize};
/// BrowserLeaks.com API response structure
#[derive(Debug, Serialize, Deserialize)]
pub struct BrowserLeaksResponse {
pub user_agent: String,
pub ja4: String,
pub akamai_hash: String,
pub akamai_text: String,
}
const CHROME146_USER_AGENT: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36";
const CHROME146_JA4: &str = "t13d1516h2_8daaf6152771_d8a2da3f94cd";
const CHROME146_AKAMAI_HASH: &str = "52d84b11737d980aef856699f885ca86";
const CHROME146_AKAMAI_TEXT: &str = "1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p";
#[tokio::test]
#[cfg(feature = "impersonate")]
async fn test_chrome146() {
let client = Client::builder()
.impersonate_os(crate::imp::ImpersonateOS::Linux)
.impersonate(Impersonate::ChromeV146)
.build()
.unwrap();
let response = client
.get("https://tls.browserleaks.com/json")
.send()
.await
.unwrap();
let json: BrowserLeaksResponse = response.json().await.unwrap();
assert_eq!(json.user_agent, CHROME146_USER_AGENT);
assert_eq!(json.ja4, CHROME146_JA4);
assert_eq!(json.akamai_hash, CHROME146_AKAMAI_HASH);
assert_eq!(json.akamai_text, CHROME146_AKAMAI_TEXT);
}
}
+297
View File
@@ -0,0 +1,297 @@
//! Edge browser impersonation settings.
//!
//! This module provides configuration for impersonating various Edge browser versions.
//! Edge uses Chrome-based TLS/HTTP2 configs but with Edge-specific headers.
//! Each version has its own TLS fingerprint, ALPN protocols, and default HTTP headers
//! that mimic the real Edge browser behavior.
//!
//! # Usage
//!
//! ```rust
//! use primp::{Client, Impersonate};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = Client::builder()
//! .impersonate(Impersonate::EdgeV144)
//! .build()?;
//!
//! //let response = client.get("https://example.com").send().await?;
//! Ok(())
//! }
//! ```
pub use crate::imp::Impersonate;
#[cfg(feature = "http2")]
use crate::imp::{PseudoId, PseudoOrder, SettingId, SettingsOrder};
use http::header::*;
use rustls::client::{BrowserEmulator, BrowserType, BrowserVersion};
use rustls::crypto::emulation;
use std::sync::{Arc, OnceLock};
/// Builds browser settings for a specific Edge version and OS.
pub(crate) fn build_edge_settings(
edge: Impersonate,
os: crate::imp::ImpersonateOS,
) -> crate::imp::BrowserSettings {
let os = if matches!(os, crate::imp::ImpersonateOS::Random) {
crate::imp::random_impersonate_os()
} else {
os
};
let user_agent = build_user_agent(edge, os);
let sec_ch_ua = build_sec_ch_ua(edge, os);
let mut headers = base_edge_headers().clone();
headers.insert(USER_AGENT, http::HeaderValue::from_static(user_agent));
headers.insert("sec-ch-ua", http::HeaderValue::from_static(sec_ch_ua));
headers.insert(
"sec-ch-ua-mobile",
http::HeaderValue::from_static(
if matches!(
os,
crate::imp::ImpersonateOS::Android | crate::imp::ImpersonateOS::IOS
) {
"?1"
} else {
"?0"
},
),
);
headers.insert(
"sec-ch-ua-platform",
http::HeaderValue::from_static(crate::imp::os_platform(os)),
);
// Get cached browser emulator for Edge (avoids Vec allocations on each call)
let browser_emulator = edge_emulator(edge);
let http2 = build_http2_settings(edge);
crate::imp::BrowserSettings {
browser_emulator,
http2,
headers,
gzip: true,
brotli: true,
zstd: true,
deflate: true,
}
}
/// Builds a User-Agent string for an Edge version and OS.
fn build_user_agent(edge: Impersonate, os: crate::imp::ImpersonateOS) -> &'static str {
match edge {
Impersonate::EdgeV144 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 Edg/144.0.0.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 Edg/144.0.0.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 Edg/144.0.0.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; Pixel 3 XL) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Mobile Safari/537.36 EdgA/144.0.0.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 EdgiOS/144.0.0.0 Mobile/15E148 Safari/605.1.15",
_ => unreachable!(),
},
Impersonate::EdgeV145 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 Edg/145.0.0.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 Edg/145.0.0.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 Edg/145.0.0.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; Pixel 3 XL) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Mobile Safari/537.36 EdgA/145.0.0.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 EdgiOS/145.0.0.0 Mobile/15E148 Safari/605.1.15",
_ => unreachable!(),
},
Impersonate::EdgeV146 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 Edg/146.0.0.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 Edg/146.0.0.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 Edg/146.0.0.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; Pixel 3 XL) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Mobile Safari/537.36 EdgA/146.0.0.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 EdgiOS/146.0.0.0 Mobile/15E148 Safari/605.1.15",
_ => unreachable!(),
},
Impersonate::EdgeV147 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 Edg/147.0.3912.51",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 Edg/147.0.3912.51",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 Edg/147.0.3912.51",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Mobile Safari/537.36 EdgA/147.0.3912.51",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 EdgiOS/147.0.3912.51 Mobile/15E148 Safari/605.1.15",
_ => unreachable!(),
},
Impersonate::EdgeV148 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36 Edg/148.0.0.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36 Edg/148.0.0.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36 Edg/148.0.0.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; Pixel 3 XL) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Mobile Safari/537.36 EdgA/148.0.0.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 EdgiOS/148.0.0.0 Mobile/15E148 Safari/605.1.15",
_ => unreachable!(),
},
_ => unreachable!(),
}
}
/// Builds a sec-ch-ua header value for an Edge version and OS.
fn build_sec_ch_ua(edge: Impersonate, _os: crate::imp::ImpersonateOS) -> &'static str {
match edge {
Impersonate::EdgeV144 => {
r#""Not(A:Brand";v="8", "Chromium";v="144", "Microsoft Edge";v="144""#
}
Impersonate::EdgeV145 => {
r#""Not:A-Brand";v="99", "Microsoft Edge";v="145", "Chromium";v="145""#
}
Impersonate::EdgeV146 => {
r#""Chromium";v="146", "Not-A.Brand";v="24", "Microsoft Edge";v="146""#
}
Impersonate::EdgeV147 => {
r#""Microsoft Edge";v="147", "Not.A/Brand";v="8", "Chromium";v="147""#
}
Impersonate::EdgeV148 => {
r#""Chromium";v="148", "Microsoft Edge";v="148", "Not/A)Brand";v="99""#
}
_ => unreachable!(),
}
}
/// Builds HTTP/2 settings for an Edge version.
#[cfg(feature = "http2")]
fn build_http2_settings(edge: Impersonate) -> crate::imp::Http2Data {
// Edge 146+ uses different header order (sec-ch-ua after sec-fetch-*)
let headers_order = if matches!(
edge,
Impersonate::EdgeV146 | Impersonate::EdgeV147 | Impersonate::EdgeV148
) {
Some(crate::imp::header_order_upgrade_first_sec_chua_last().clone())
} else {
Some(crate::imp::header_order_sec_chua_first().clone())
};
crate::imp::Http2Data {
settings_order: Some(edge_settings_order().clone()),
headers_pseudo_order: Some(edge_pseudo_order().clone()),
headers_order,
headers_priority: Some((255, 0, true)),
initial_stream_window_size: Some(crate::imp::CHROME_INITIAL_STREAM_WINDOW),
initial_connection_window_size: Some(crate::imp::CHROME_INITIAL_CONNECTION_WINDOW),
max_header_list_size: Some(crate::imp::CHROME_MAX_HEADER_LIST_SIZE),
header_table_size: Some(crate::imp::CHROME_HEADER_TABLE_SIZE),
..Default::default()
}
}
fn edge_emulator(edge: Impersonate) -> Arc<BrowserEmulator> {
match edge {
Impersonate::EdgeV144 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_edge_emulator(144))).clone()
}
Impersonate::EdgeV145 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_edge_emulator(145))).clone()
}
Impersonate::EdgeV146 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_edge_emulator(146))).clone()
}
Impersonate::EdgeV147 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_edge_emulator(147))).clone()
}
Impersonate::EdgeV148 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_edge_emulator(148))).clone()
}
_ => unreachable!(),
}
}
fn new_edge_emulator(major: u16) -> BrowserEmulator {
let mut emulator = BrowserEmulator::new(BrowserType::Edge, BrowserVersion::new(major, 0, 0));
emulator.cipher_suites = Some(emulation::cipher_suites::EDGE.to_vec());
emulator.signature_algorithms = Some(emulation::signature_algorithms::EDGE.to_vec());
emulator.named_groups = Some(emulation::named_groups::EDGE.to_vec());
emulator.extension_order_seed = Some(emulation::extension_order::EDGE);
emulator
}
fn base_edge_headers() -> &'static http::HeaderMap {
static BASE: OnceLock<http::HeaderMap> = OnceLock::new();
BASE.get_or_init(|| {
let mut headers = http::HeaderMap::with_capacity(13);
headers.insert(ACCEPT, http::HeaderValue::from_static("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"));
headers.insert("accept-encoding", http::HeaderValue::from_static("gzip, deflate, br, zstd"));
headers.insert("accept-language", http::HeaderValue::from_static("en-US,en;q=0.9"));
headers.insert("upgrade-insecure-requests", http::HeaderValue::from_static("1"));
headers.insert("sec-fetch-site", http::HeaderValue::from_static("none"));
headers.insert("sec-fetch-mode", http::HeaderValue::from_static("navigate"));
headers.insert("sec-fetch-dest", http::HeaderValue::from_static("document"));
headers.insert("sec-fetch-user", http::HeaderValue::from_static("?1"));
headers.insert("priority", http::HeaderValue::from_static("u=0, i"));
headers
})
}
#[cfg(feature = "http2")]
fn edge_settings_order() -> &'static SettingsOrder {
static ORDER: OnceLock<SettingsOrder> = OnceLock::new();
ORDER.get_or_init(|| {
SettingsOrder::builder()
.push(SettingId::HeaderTableSize)
.push(SettingId::EnablePush)
.push(SettingId::InitialWindowSize)
.push(SettingId::MaxHeaderListSize)
.build_without_extend()
})
}
#[cfg(feature = "http2")]
fn edge_pseudo_order() -> &'static PseudoOrder {
static ORDER: OnceLock<PseudoOrder> = OnceLock::new();
ORDER.get_or_init(|| {
PseudoOrder::builder()
.push(PseudoId::Method)
.push(PseudoId::Authority)
.push(PseudoId::Scheme)
.push(PseudoId::Path)
.build()
})
}
#[cfg(test)]
mod tests {
use crate::imp::Impersonate;
use crate::Client;
use serde::{Deserialize, Serialize};
/// BrowserLeaks.com API response structure
#[derive(Debug, Serialize, Deserialize)]
pub struct BrowserLeaksResponse {
pub user_agent: String,
pub ja4: String,
pub akamai_hash: String,
pub akamai_text: String,
}
const EDGE146_USER_AGENT: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 Edg/146.0.0.0";
const EDGE146_JA4: &str = "t13d1516h2_8daaf6152771_d8a2da3f94cd";
const EDGE146_AKAMAI_HASH: &str = "52d84b11737d980aef856699f885ca86";
const EDGE146_AKAMAI_TEXT: &str = "1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p";
#[tokio::test]
#[cfg(feature = "impersonate")]
async fn test_edge146() {
let client = Client::builder()
.impersonate_os(crate::imp::ImpersonateOS::Linux)
.impersonate(Impersonate::EdgeV146)
.build()
.unwrap();
let response = client
.get("https://tls.browserleaks.com/json")
.send()
.await
.unwrap();
let json: BrowserLeaksResponse = response.json().await.unwrap();
assert_eq!(json.user_agent, EDGE146_USER_AGENT);
assert_eq!(json.ja4, EDGE146_JA4);
assert_eq!(json.akamai_hash, EDGE146_AKAMAI_HASH);
assert_eq!(json.akamai_text, EDGE146_AKAMAI_TEXT);
}
}
+288
View File
@@ -0,0 +1,288 @@
//! Firefox browser impersonation settings.
pub use crate::imp::Impersonate;
use rustls::client::{BrowserEmulator, BrowserType, BrowserVersion};
use rustls::crypto::emulation;
use std::sync::{Arc, OnceLock};
/// Builds browser settings for a specific Firefox version and OS.
pub(crate) fn build_firefox_settings(
firefox: Impersonate,
os: crate::imp::ImpersonateOS,
) -> crate::imp::BrowserSettings {
let os = if matches!(os, crate::imp::ImpersonateOS::Random) {
crate::imp::random_impersonate_os()
} else {
os
};
let user_agent = build_user_agent(firefox, os);
let headers = build_headers(user_agent);
let browser_emulator = match firefox {
Impersonate::FirefoxV140 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_firefox_emulator(140)))
.clone()
}
Impersonate::FirefoxV146 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_firefox_emulator(146)))
.clone()
}
Impersonate::FirefoxV147 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_firefox_emulator(147)))
.clone()
}
Impersonate::FirefoxV148 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_firefox_emulator(148)))
.clone()
}
_ => unreachable!(),
};
crate::imp::BrowserSettings {
browser_emulator,
http2: build_http2_settings(),
headers,
gzip: true,
brotli: true,
zstd: true,
deflate: true,
}
}
fn new_firefox_emulator(major: u16) -> BrowserEmulator {
let mut emulator = BrowserEmulator::new(BrowserType::Firefox, BrowserVersion::new(major, 0, 0));
emulator.cipher_suites = Some(emulation::cipher_suites::FIREFOX.to_vec());
emulator.signature_algorithms = Some(emulation::signature_algorithms::FIREFOX.to_vec());
emulator.named_groups = Some(emulation::named_groups::FIREFOX.to_vec());
emulator.extension_order_seed = Some(emulation::extension_order::FIREFOX);
emulator
}
/// Builds a User-Agent string for a Firefox version and OS.
fn build_user_agent(firefox: Impersonate, os: crate::imp::ImpersonateOS) -> &'static str {
match firefox {
Impersonate::FirefoxV140 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 14.7; rv:140.0) Gecko/20100101 Firefox/140.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Android 14; Mobile; rv:140.0) Gecko/140.0 Firefox/140.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 17_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/140.0 Mobile/15E148 Safari/605.1",
_ => unreachable!(),
},
Impersonate::FirefoxV146 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:146.0) Gecko/20100101 Firefox/146.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 14.7; rv:146.0) Gecko/20100101 Firefox/146.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64; rv:146.0) Gecko/20100101 Firefox/146.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Android 14; Mobile; rv:146.0) Gecko/146.0 Firefox/146.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 17_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/146.0 Mobile/15E148 Safari/605.1",
_ => unreachable!(),
},
Impersonate::FirefoxV147 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:147.0) Gecko/20100101 Firefox/147.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 14.7; rv:147.0) Gecko/20100101 Firefox/147.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64; rv:147.0) Gecko/20100101 Firefox/147.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Android 14; Mobile; rv:147.0) Gecko/147.0 Firefox/147.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 17_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/147.0 Mobile/15E148 Safari/605.1",
_ => unreachable!(),
},
Impersonate::FirefoxV148 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:148.0) Gecko/20100101 Firefox/148.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 14.7; rv:148.0) Gecko/20100101 Firefox/148.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64; rv:148.0) Gecko/20100101 Firefox/148.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Android 14; Mobile; rv:148.0) Gecko/148.0 Firefox/148.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 17_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/148.0 Mobile/15E148 Safari/605.1",
_ => unreachable!(),
},
_ => unreachable!(),
}
}
fn firefox_base_headers() -> &'static http::HeaderMap {
static BASE: OnceLock<http::HeaderMap> = OnceLock::new();
BASE.get_or_init(|| {
let mut headers = http::HeaderMap::with_capacity(12);
headers.insert(
http::header::ACCEPT,
http::HeaderValue::from_static(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
),
);
headers.insert(
"accept-language",
http::HeaderValue::from_static("en-US,en;q=0.5"),
);
headers.insert(
"accept-encoding",
http::HeaderValue::from_static("gzip, deflate, br, zstd"),
);
headers.insert("dnt", http::HeaderValue::from_static("1"));
headers.insert("sec-gpc", http::HeaderValue::from_static("1"));
headers.insert(
"upgrade-insecure-requests",
http::HeaderValue::from_static("1"),
);
headers.insert("sec-fetch-dest", http::HeaderValue::from_static("document"));
headers.insert("sec-fetch-mode", http::HeaderValue::from_static("navigate"));
headers.insert("sec-fetch-site", http::HeaderValue::from_static("none"));
headers.insert("sec-fetch-user", http::HeaderValue::from_static("?1"));
headers.insert("priority", http::HeaderValue::from_static("u=0, i"));
headers.insert("te", http::HeaderValue::from_static("trailers"));
headers
})
}
/// Builds default headers for Firefox.
fn build_headers(user_agent: &'static str) -> http::HeaderMap {
let mut headers = firefox_base_headers().clone();
headers.insert(
http::header::USER_AGENT,
http::HeaderValue::from_static(user_agent),
);
headers
}
/// Builds HTTP/2 settings for Firefox.
#[cfg(feature = "http2")]
fn build_http2_settings() -> crate::imp::Http2Data {
crate::imp::Http2Data {
initial_stream_window_size: Some(crate::imp::FIREFOX_INITIAL_STREAM_WINDOW),
initial_connection_window_size: Some(crate::imp::FIREFOX_INITIAL_CONNECTION_WINDOW),
max_frame_size: Some(16384),
header_table_size: Some(crate::imp::FIREFOX_HEADER_TABLE_SIZE),
enable_push: Some(false),
settings_order: Some(firefox_settings_order().clone()),
headers_pseudo_order: Some(firefox_pseudo_order().clone()),
headers_priority: Some((41, 0, false)),
headers_order: Some(firefox_headers_order().clone()),
initial_stream_id: Some(3),
initial_stream_window_size_increment: Some(12451840),
..Default::default()
}
}
#[cfg(feature = "http2")]
fn firefox_settings_order() -> &'static crate::imp::SettingsOrder {
static ORDER: OnceLock<crate::imp::SettingsOrder> = OnceLock::new();
ORDER.get_or_init(|| {
crate::imp::SettingsOrder::builder()
.push(crate::imp::SettingId::HeaderTableSize)
.push(crate::imp::SettingId::EnablePush)
.push(crate::imp::SettingId::InitialWindowSize)
.push(crate::imp::SettingId::MaxFrameSize)
.build_without_extend()
})
}
#[cfg(feature = "http2")]
fn firefox_pseudo_order() -> &'static crate::imp::PseudoOrder {
static ORDER: OnceLock<crate::imp::PseudoOrder> = OnceLock::new();
ORDER.get_or_init(|| {
crate::imp::PseudoOrder::builder()
.push(crate::imp::PseudoId::Method)
.push(crate::imp::PseudoId::Path)
.push(crate::imp::PseudoId::Authority)
.push(crate::imp::PseudoId::Scheme)
.build()
})
}
#[cfg(feature = "http2")]
fn firefox_headers_order() -> &'static Vec<http::HeaderName> {
static ORDER: OnceLock<Vec<http::HeaderName>> = OnceLock::new();
ORDER.get_or_init(|| {
vec![
http::HeaderName::from_static("user-agent"),
http::HeaderName::from_static("accept"),
http::HeaderName::from_static("accept-language"),
http::HeaderName::from_static("accept-encoding"),
http::HeaderName::from_static("dnt"),
http::HeaderName::from_static("sec-gpc"),
http::HeaderName::from_static("upgrade-insecure-requests"),
http::HeaderName::from_static("sec-fetch-dest"),
http::HeaderName::from_static("sec-fetch-mode"),
http::HeaderName::from_static("sec-fetch-site"),
http::HeaderName::from_static("sec-fetch-user"),
http::HeaderName::from_static("priority"),
http::HeaderName::from_static("te"),
]
})
}
#[cfg(test)]
mod tests {
use crate::imp::Impersonate;
use crate::Client;
use serde::{Deserialize, Serialize};
/// BrowserLeaks.com API response structure
#[derive(Debug, Serialize, Deserialize)]
pub struct BrowserLeaksResponse {
pub user_agent: String,
pub ja4: String,
pub akamai_hash: String,
pub akamai_text: String,
}
const FIREFOX140_USER_AGENT: &str =
"Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0";
const FIREFOX140_JA4: &str = "t13d1717h2_5b57614c22b0_3cbfd9057e0d";
// Firefox 140 sends: 1:65536, 2:0, 4:131072, 5:16384 (no MAX_HEADER_LIST_SIZE)
const FIREFOX140_AKAMAI_HASH: &str = "6ea73faa8fc5aac76bded7bd238f6433";
const FIREFOX140_AKAMAI_TEXT: &str = "1:65536;2:0;4:131072;5:16384|12517377|0|m,p,a,s";
#[tokio::test]
#[cfg(feature = "impersonate")]
async fn test_firefox140() {
let client = Client::builder()
.impersonate_os(crate::imp::ImpersonateOS::Linux)
.impersonate(Impersonate::FirefoxV140)
.build()
.unwrap();
let response = client
.get("https://tls.browserleaks.com/json")
.send()
.await
.unwrap();
let json: BrowserLeaksResponse = response.json().await.unwrap();
assert_eq!(json.user_agent, FIREFOX140_USER_AGENT);
assert_eq!(json.ja4, FIREFOX140_JA4);
assert_eq!(json.akamai_hash, FIREFOX140_AKAMAI_HASH);
assert_eq!(json.akamai_text, FIREFOX140_AKAMAI_TEXT);
}
const FIREFOX148_USER_AGENT: &str =
"Mozilla/5.0 (X11; Linux x86_64; rv:148.0) Gecko/20100101 Firefox/148.0";
const FIREFOX148_JA4: &str = "t13d1717h2_5b57614c22b0_3cbfd9057e0d";
const FIREFOX148_AKAMAI_HASH: &str = "6ea73faa8fc5aac76bded7bd238f6433";
const FIREFOX148_AKAMAI_TEXT: &str = "1:65536;2:0;4:131072;5:16384|12517377|0|m,p,a,s";
#[tokio::test]
#[cfg(feature = "impersonate")]
async fn test_firefox148() {
let client = Client::builder()
.impersonate_os(crate::imp::ImpersonateOS::Linux)
.impersonate(Impersonate::FirefoxV148)
.build()
.unwrap();
let response = client
.get("https://tls.browserleaks.com/json")
.send()
.await
.unwrap();
let json: BrowserLeaksResponse = response.json().await.unwrap();
assert_eq!(json.user_agent, FIREFOX148_USER_AGENT);
assert_eq!(json.ja4, FIREFOX148_JA4);
assert_eq!(json.akamai_hash, FIREFOX148_AKAMAI_HASH);
assert_eq!(json.akamai_text, FIREFOX148_AKAMAI_TEXT);
}
}
+512
View File
@@ -0,0 +1,512 @@
//! Holds structs and information to aid in impersonating browsers.
//!
//! This module provides configuration for impersonating various browser versions,
//! including TLS settings, HTTP/2 parameters, and default headers.
//!
//! # Example
//!
//! ```rust
//! use primp::{Client, Impersonate};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Specific version
//! let client = Client::builder()
//! .impersonate(Impersonate::ChromeV146)
//! .build()?;
//!
//! // Or pick a random version from Chrome family
//! let client = Client::builder()
//! .impersonate(Impersonate::Chrome)
//! .build()?;
//!
//! Ok(())
//! }
//! ```
use http::HeaderMap;
use rand::prelude::*;
use rustls::client::BrowserEmulator;
use std::sync::{Arc, OnceLock};
// Re-export h2 types for HTTP/2 fingerprinting when http2 feature is enabled
#[cfg(feature = "http2")]
pub use h2::frame::{
PseudoId, PseudoOrder, PseudoOrderBuilder, SettingId, SettingsOrder, SettingsOrderBuilder,
};
pub mod chrome;
pub mod edge;
pub mod firefox;
pub mod opera;
pub mod safari;
// HTTP/2 magic numbers grouped by browser family.
pub(crate) const CHROME_INITIAL_STREAM_WINDOW: u32 = 6291456;
pub(crate) const CHROME_INITIAL_CONNECTION_WINDOW: u32 = 15728640;
pub(crate) const CHROME_MAX_HEADER_LIST_SIZE: u32 = 262144;
pub(crate) const CHROME_HEADER_TABLE_SIZE: u32 = 65536;
pub(crate) const FIREFOX_INITIAL_STREAM_WINDOW: u32 = 131072;
pub(crate) const FIREFOX_INITIAL_CONNECTION_WINDOW: u32 = 12517377 + 65535; // 12582912
pub(crate) const FIREFOX_HEADER_TABLE_SIZE: u32 = 65536;
pub(crate) const SAFARI_INITIAL_STREAM_WINDOW: u32 = 2097152;
pub(crate) const SAFARI_INITIAL_CONNECTION_WINDOW: u32 = 10485760;
pub(crate) const SAFARI_MAX_HEADER_LIST_SIZE: u32 = 262144;
/// Browser TLS and HTTP/2 configuration settings.
///
/// This struct contains all the configuration needed to impersonate a specific
/// browser version, including TLS connection settings, HTTP/2 parameters, and
/// default request headers.
#[derive(Clone)]
pub struct BrowserSettings {
/// Rustls browser emulator configuration
pub(crate) browser_emulator: Arc<BrowserEmulator>,
/// HTTP/2 configuration data
pub http2: Http2Data,
/// Default headers to include with requests
pub headers: HeaderMap,
/// Whether to enable gzip compression
pub gzip: bool,
/// Whether to enable brotli compression
pub brotli: bool,
/// Whether to enable zstd compression
pub zstd: bool,
/// Whether to enable deflate compression
pub deflate: bool,
}
impl std::fmt::Debug for BrowserSettings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BrowserSettings")
.field("browser_emulator", &self.browser_emulator)
.field("http2", &self.http2)
.field("headers", &self.headers)
.field("gzip", &self.gzip)
.field("brotli", &self.brotli)
.field("zstd", &self.zstd)
.field("deflate", &self.deflate)
.finish()
}
}
/// HTTP/2 configuration parameters.
///
/// Controls various HTTP/2 connection settings used during browser impersonation.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Http2Data {
/// Initial HTTP/2 stream window size (in bytes)
///
/// Default: 6291456 (6 MiB)
pub initial_stream_window_size: Option<u32>,
/// Initial HTTP/2 connection window size (in bytes)
///
/// Default: 15728640 (15 MiB)
pub initial_connection_window_size: Option<u32>,
/// Maximum number of concurrent HTTP/2 streams
///
/// Default: 1000
pub max_concurrent_streams: Option<u32>,
/// Maximum size of HTTP/2 frames (in bytes)
///
/// Default: 16384
pub max_frame_size: Option<u32>,
/// Maximum size of HTTP/2 header list (in bytes)
///
/// Default: 262144 (256 KiB)
pub max_header_list_size: Option<u32>,
/// HTTP/2 header table size (in bytes)
///
/// Default: 65536 (64 KiB)
pub header_table_size: Option<u32>,
/// Whether HTTP/2 server push is enabled
///
/// Default: false
pub enable_push: Option<bool>,
/// Whether to enable Extended CONNECT protocol
///
/// Default: false
pub enable_connect_protocol: Option<bool>,
/// Whether to disable RFC 7540 Stream Priorities
///
/// Default: false
pub no_rfc7540_priorities: Option<bool>,
/// HTTP/2 SETTINGS frame order
///
/// Controls the order of settings in the SETTINGS frame for fingerprinting.
pub settings_order: Option<h2::frame::SettingsOrder>,
/// HTTP/2 pseudo-header order
///
/// Controls the order of pseudo-headers in HEADERS frames for fingerprinting.
pub headers_pseudo_order: Option<h2::frame::PseudoOrder>,
/// Whether to include PRIORITY flag in HEADERS frames
///
/// When true, HEADERS frames include priority data (weight=0, stream_dependency=0,
/// exclusive=1) matching Chrome's HTTP/2 fingerprint behavior.
/// Whether to include PRIORITY flag in HEADERS frames and its parameters (weight, dep, exclusive)
///
/// None = no PRIORITY flag, Some((w,d,e)) = PRIORITY with those values.
/// Chrome: Some((0, 0, true)), Firefox: Some((42, 0, false))
pub headers_priority: Option<(u8, u32, bool)>,
/// Optional ordering for HTTP/2 regular headers
///
/// When set, headers are encoded in the specified order instead of hash-based order.
pub headers_order: Option<Vec<http::HeaderName>>,
/// Optional initial stream ID for HTTP/2 (odd number for client-initiated streams)
///
/// Default: 1 (standard HTTP/2 behavior)
/// Firefox uses 3 (skips stream 1)
pub initial_stream_id: Option<u32>,
/// Extra receive window capacity to add to new locally-initiated streams.
///
/// When set, after creating a new stream, a WINDOW_UPDATE frame will be sent
/// to increase the stream's receive window by this amount.
/// This is used for browser fingerprinting (e.g. Firefox adds 12451840
/// to the first stream's receive window).
pub initial_stream_window_size_increment: Option<u32>,
}
impl Default for Http2Data {
fn default() -> Self {
Self {
initial_stream_window_size: Some(6291456),
initial_connection_window_size: Some(15728640),
max_concurrent_streams: Some(1000),
max_frame_size: Some(16384),
max_header_list_size: Some(262144),
header_table_size: Some(65536),
enable_push: Some(false),
enable_connect_protocol: Some(false),
no_rfc7540_priorities: Some(false),
settings_order: None,
headers_pseudo_order: None,
headers_priority: None,
headers_order: None,
initial_stream_id: None,
initial_stream_window_size_increment: None,
}
}
}
/// Available browser versions for impersonation.
///
/// Each variant represents a specific browser version with its corresponding
/// TLS fingerprint and default headers.
///
/// # Note
///
/// Not all browser versions are equally effective for bypassing detection.
/// Newer versions generally provide better fingerprinting resistance.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg(feature = "impersonate")]
#[allow(missing_docs)]
pub enum Impersonate {
// Chrome variants
ChromeV144,
ChromeV145,
ChromeV146,
ChromeV147,
ChromeV148,
/// Random Chrome version
Chrome,
// Edge variants
EdgeV144,
EdgeV145,
EdgeV146,
EdgeV147,
EdgeV148,
/// Random Edge version
Edge,
// Opera variants
OperaV126,
OperaV127,
OperaV128,
OperaV129,
OperaV130,
OperaV131,
/// Random Opera version
Opera,
// Safari variants
SafariV18_5,
SafariV26,
SafariV26_3,
/// Random Safari version
Safari,
// Firefox variants
FirefoxV140,
FirefoxV146,
FirefoxV147,
FirefoxV148,
/// Random Firefox version
Firefox,
/// Random browser and version
Random,
}
/// Operating system platforms for browser impersonation.
///
/// Specifies the OS platform to mimic when generating browser fingerprints.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum ImpersonateOS {
/// Windows operating system
#[default]
Windows,
/// macOS operating system
MacOS,
/// Linux operating system
Linux,
/// Android mobile operating system
Android,
/// iOS mobile operating system
IOS,
/// Random OS selection
Random,
}
/// Randomly selects a browser version for impersonation.
///
/// This function can be used when you want to randomize the browser fingerprint
/// across requests to avoid detection based on repeated patterns.
///
/// # Returns
///
/// A randomly selected `Impersonate` variant from all available browser versions.
#[cfg(feature = "impersonate")]
pub fn random_impersonate() -> Impersonate {
const IMPERSONATE_VARIANTS: &[Impersonate] = &[
Impersonate::ChromeV144,
Impersonate::ChromeV145,
Impersonate::ChromeV146,
Impersonate::ChromeV147,
Impersonate::ChromeV148,
Impersonate::EdgeV144,
Impersonate::EdgeV145,
Impersonate::EdgeV146,
Impersonate::EdgeV147,
Impersonate::EdgeV148,
Impersonate::OperaV126,
Impersonate::OperaV127,
Impersonate::OperaV128,
Impersonate::OperaV129,
Impersonate::OperaV130,
Impersonate::OperaV131,
Impersonate::SafariV26,
Impersonate::SafariV26_3,
Impersonate::SafariV18_5,
Impersonate::FirefoxV140,
Impersonate::FirefoxV146,
Impersonate::FirefoxV147,
Impersonate::FirefoxV148,
];
*IMPERSONATE_VARIANTS.choose(&mut rand::rng()).unwrap()
}
/// Resolves an unnumbered `Impersonate` variant to a random specific version.
#[cfg(feature = "impersonate")]
pub fn resolve_impersonate(version: Impersonate) -> Impersonate {
match version {
Impersonate::Chrome => {
const CHROME: &[Impersonate] = &[
Impersonate::ChromeV144,
Impersonate::ChromeV145,
Impersonate::ChromeV146,
Impersonate::ChromeV147,
Impersonate::ChromeV148,
];
*CHROME.choose(&mut rand::rng()).unwrap()
}
Impersonate::Edge => {
const EDGE: &[Impersonate] = &[
Impersonate::EdgeV144,
Impersonate::EdgeV145,
Impersonate::EdgeV146,
Impersonate::EdgeV147,
Impersonate::EdgeV148,
];
*EDGE.choose(&mut rand::rng()).unwrap()
}
Impersonate::Opera => {
const OPERA: &[Impersonate] = &[
Impersonate::OperaV126,
Impersonate::OperaV127,
Impersonate::OperaV128,
Impersonate::OperaV129,
Impersonate::OperaV130,
Impersonate::OperaV131,
];
*OPERA.choose(&mut rand::rng()).unwrap()
}
Impersonate::Safari => {
const SAFARI: &[Impersonate] = &[
Impersonate::SafariV18_5,
Impersonate::SafariV26,
Impersonate::SafariV26_3,
];
*SAFARI.choose(&mut rand::rng()).unwrap()
}
Impersonate::Firefox => {
const FIREFOX: &[Impersonate] = &[
Impersonate::FirefoxV140,
Impersonate::FirefoxV146,
Impersonate::FirefoxV147,
Impersonate::FirefoxV148,
];
*FIREFOX.choose(&mut rand::rng()).unwrap()
}
Impersonate::Random => random_impersonate(),
other => other,
}
}
/// Randomly selects an operating system for impersonation.
///
/// # Returns
///
/// A randomly selected `ImpersonateOS` variant.
pub fn random_impersonate_os() -> ImpersonateOS {
const OS_VARIANTS: &[ImpersonateOS] = &[
ImpersonateOS::Windows,
ImpersonateOS::MacOS,
ImpersonateOS::Linux,
ImpersonateOS::Android,
ImpersonateOS::IOS,
];
*OS_VARIANTS.choose(&mut rand::rng()).unwrap()
}
/// Returns the OS-specific sec-ch-ua-platform header value.
pub(crate) fn os_platform(os: ImpersonateOS) -> &'static str {
let os = if matches!(os, ImpersonateOS::Random) {
random_impersonate_os()
} else {
os
};
match os {
ImpersonateOS::Windows => r#""Windows""#,
ImpersonateOS::MacOS => r#""macOS""#,
ImpersonateOS::Linux => r#""Linux""#,
ImpersonateOS::Android => r#""Android""#,
ImpersonateOS::IOS => r#""iOS""#,
ImpersonateOS::Random => unreachable!(),
}
}
/// Standard Chrome/Edge/Opera header order with sec-ch-ua first.
pub(crate) fn header_order_sec_chua_first() -> &'static Vec<http::HeaderName> {
static ORDER: OnceLock<Vec<http::HeaderName>> = OnceLock::new();
ORDER.get_or_init(|| {
vec![
http::HeaderName::from_static("sec-ch-ua"),
http::HeaderName::from_static("sec-ch-ua-mobile"),
http::HeaderName::from_static("sec-ch-ua-platform"),
http::HeaderName::from_static("upgrade-insecure-requests"),
http::HeaderName::from_static("user-agent"),
http::HeaderName::from_static("accept"),
http::HeaderName::from_static("sec-fetch-site"),
http::HeaderName::from_static("sec-fetch-mode"),
http::HeaderName::from_static("sec-fetch-user"),
http::HeaderName::from_static("sec-fetch-dest"),
http::HeaderName::from_static("accept-encoding"),
http::HeaderName::from_static("accept-language"),
http::HeaderName::from_static("priority"),
]
})
}
/// Chrome 148+ / Edge 146+ header order with sec-ch-ua after sec-fetch-*.
pub(crate) fn header_order_upgrade_first_sec_chua_last() -> &'static Vec<http::HeaderName> {
static ORDER: OnceLock<Vec<http::HeaderName>> = OnceLock::new();
ORDER.get_or_init(|| {
vec![
http::HeaderName::from_static("upgrade-insecure-requests"),
http::HeaderName::from_static("user-agent"),
http::HeaderName::from_static("accept"),
http::HeaderName::from_static("sec-fetch-site"),
http::HeaderName::from_static("sec-fetch-mode"),
http::HeaderName::from_static("sec-fetch-user"),
http::HeaderName::from_static("sec-fetch-dest"),
http::HeaderName::from_static("sec-ch-ua"),
http::HeaderName::from_static("sec-ch-ua-mobile"),
http::HeaderName::from_static("sec-ch-ua-platform"),
http::HeaderName::from_static("accept-encoding"),
http::HeaderName::from_static("accept-language"),
http::HeaderName::from_static("priority"),
]
})
}
/// Opera 131+ header order with cache-control first.
pub(crate) fn header_order_cache_control_first() -> &'static Vec<http::HeaderName> {
static ORDER: OnceLock<Vec<http::HeaderName>> = OnceLock::new();
ORDER.get_or_init(|| {
vec![
http::HeaderName::from_static("cache-control"),
http::HeaderName::from_static("sec-ch-ua"),
http::HeaderName::from_static("sec-ch-ua-mobile"),
http::HeaderName::from_static("sec-ch-ua-platform"),
http::HeaderName::from_static("upgrade-insecure-requests"),
http::HeaderName::from_static("user-agent"),
http::HeaderName::from_static("accept"),
http::HeaderName::from_static("sec-fetch-site"),
http::HeaderName::from_static("sec-fetch-mode"),
http::HeaderName::from_static("sec-fetch-user"),
http::HeaderName::from_static("sec-fetch-dest"),
http::HeaderName::from_static("accept-encoding"),
http::HeaderName::from_static("accept-language"),
http::HeaderName::from_static("priority"),
]
})
}
/// Gets browser settings for impersonation.
///
/// # Arguments
///
/// * `version` - The browser version to impersonate
/// * `os_type` - Optional OS to impersonate
///
/// # Returns
///
/// BrowserSettings with TLS, HTTP/2, and header configuration
#[cfg(feature = "impersonate")]
pub fn get_browser_settings(
version: Impersonate,
os_type: Option<ImpersonateOS>,
) -> BrowserSettings {
let version = resolve_impersonate(version);
let os_type = os_type.unwrap_or_default();
match version {
Impersonate::ChromeV144
| Impersonate::ChromeV145
| Impersonate::ChromeV146
| Impersonate::ChromeV147
| Impersonate::ChromeV148 => chrome::build_chrome_settings(version, os_type),
Impersonate::EdgeV144
| Impersonate::EdgeV145
| Impersonate::EdgeV146
| Impersonate::EdgeV147
| Impersonate::EdgeV148 => edge::build_edge_settings(version, os_type),
Impersonate::OperaV126
| Impersonate::OperaV127
| Impersonate::OperaV128
| Impersonate::OperaV129
| Impersonate::OperaV130
| Impersonate::OperaV131 => opera::build_opera_settings(version, os_type),
Impersonate::SafariV26 | Impersonate::SafariV26_3 | Impersonate::SafariV18_5 => {
safari::build_safari_settings(version, os_type)
}
Impersonate::FirefoxV140
| Impersonate::FirefoxV146
| Impersonate::FirefoxV147
| Impersonate::FirefoxV148 => firefox::build_firefox_settings(version, os_type),
_ => unreachable!(),
}
}
+314
View File
@@ -0,0 +1,314 @@
//! Opera browser impersonation settings.
//!
//! This module provides configuration for impersonating various Opera browser versions.
//! Opera uses Chrome-based TLS/HTTP2 configs but with Opera-specific headers.
//! Each version has its own TLS fingerprint, ALPN protocols, and default HTTP headers
//! that mimic the real Opera browser behavior.
//!
//! # Usage
//!
//! ```rust
//! use primp::{Client, Impersonate};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = Client::builder()
//! .impersonate(Impersonate::OperaV126)
//! .build()?;
//!
//! //let response = client.get("https://example.com").send().await?;
//! Ok(())
//! }
//! ```
pub use crate::imp::Impersonate;
#[cfg(feature = "http2")]
use crate::imp::{PseudoId, PseudoOrder, SettingId, SettingsOrder};
use http::header::*;
use rustls::client::{BrowserEmulator, BrowserType, BrowserVersion};
use rustls::crypto::emulation;
use std::sync::{Arc, OnceLock};
/// Builds browser settings for a specific Opera version and OS.
pub(crate) fn build_opera_settings(
opera: Impersonate,
os: crate::imp::ImpersonateOS,
) -> crate::imp::BrowserSettings {
let os = if matches!(os, crate::imp::ImpersonateOS::Random) {
crate::imp::random_impersonate_os()
} else {
os
};
let user_agent = build_user_agent(opera, os);
let sec_ch_ua = build_sec_ch_ua(opera, os);
let mut headers = base_opera_headers().clone();
headers.insert(USER_AGENT, http::HeaderValue::from_static(user_agent));
headers.insert("sec-ch-ua", http::HeaderValue::from_static(sec_ch_ua));
headers.insert(
"sec-ch-ua-mobile",
http::HeaderValue::from_static(
if matches!(
os,
crate::imp::ImpersonateOS::Android | crate::imp::ImpersonateOS::IOS
) {
"?1"
} else {
"?0"
},
),
);
headers.insert(
"sec-ch-ua-platform",
http::HeaderValue::from_static(crate::imp::os_platform(os)),
);
// Opera 131+ adds cache-control as the first header
if matches!(opera, Impersonate::OperaV131) {
headers.insert("cache-control", http::HeaderValue::from_static("max-age=0"));
}
// Get cached browser emulator for Opera (avoids Vec allocations on each call)
let browser_emulator = opera_emulator(opera);
let http2 = build_http2_settings(opera);
crate::imp::BrowserSettings {
browser_emulator,
http2,
headers,
gzip: true,
brotli: true,
zstd: true,
deflate: true,
}
}
/// Builds a User-Agent string for an Opera version and OS.
fn build_user_agent(opera: Impersonate, os: crate::imp::ImpersonateOS) -> &'static str {
match opera {
// Opera 126 is based on Chrome 142, but uses Chrome 144's fingerprints
Impersonate::OperaV126 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_7_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 OPR/126.0.0.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; SM-G970F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Mobile Safari/537.36 OPR/126.0.0.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPiOS/126.0.0.0 Mobile/15E148 Safari/605.1.15",
_ => unreachable!(),
},
// Opera 127 is based on Chrome 143
Impersonate::OperaV127 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 OPR/127.0.0.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_7_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 OPR/127.0.0.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 OPR/127.0.0.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; SM-G970F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Mobile Safari/537.36 OPR/127.0.0.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPiOS/127.0.0.0 Mobile/15E148 Safari/605.1.15",
_ => unreachable!(),
},
// Opera 128 is based on Chrome 144
Impersonate::OperaV128 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 OPR/128.0.0.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_7_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 OPR/128.0.0.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 OPR/128.0.0.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; SM-G970F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Mobile Safari/537.36 OPR/128.0.0.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPiOS/128.0.0.0 Mobile/15E148 Safari/605.1.15",
_ => unreachable!(),
},
// Opera 129 is based on Chrome 145
Impersonate::OperaV129 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 OPR/129.0.0.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_7_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 OPR/129.0.0.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 OPR/129.0.0.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; SM-G970F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Mobile Safari/537.36 OPR/129.0.0.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPiOS/129.0.0.0 Mobile/15E148 Safari/605.1.15",
_ => unreachable!(),
},
// Opera 130 is based on Chrome 146
Impersonate::OperaV130 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 OPR/130.0.0.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_7_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 OPR/130.0.0.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 OPR/130.0.0.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; SM-G970F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Mobile Safari/537.36 OPR/130.0.0.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPiOS/130.0.0.0 Mobile/15E148 Safari/605.1.15",
_ => unreachable!(),
},
// Opera 131 is based on Chrome 147
Impersonate::OperaV131 => match os {
crate::imp::ImpersonateOS::Windows => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 OPR/131.0.0.0",
crate::imp::ImpersonateOS::MacOS => "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_7_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 OPR/131.0.0.0",
crate::imp::ImpersonateOS::Linux => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 OPR/131.0.0.0",
crate::imp::ImpersonateOS::Android => "Mozilla/5.0 (Linux; Android 10; SM-G970F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Mobile Safari/537.36 OPR/131.0.0.0",
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPiOS/131.0.0.0 Mobile/15E148 Safari/605.1.15",
_ => unreachable!(),
},
_ => unreachable!(),
}
}
/// Builds a sec-ch-ua header value for an Opera version and OS.
fn build_sec_ch_ua(opera: Impersonate, _os: crate::imp::ImpersonateOS) -> &'static str {
match opera {
Impersonate::OperaV126 => r#""Chromium";v="142", "Opera";v="126", "Not_A Brand";v="99""#,
Impersonate::OperaV127 => r#""Opera";v="127", "Chromium";v="143", "Not A(Brand";v="24""#,
Impersonate::OperaV128 => r#""Not(A:Brand";v="8", "Chromium";v="144", "Opera";v="128""#,
Impersonate::OperaV129 => r#""Not:A-Brand";v="99", "Opera";v="129", "Chromium";v="145""#,
Impersonate::OperaV130 => r#""Chromium";v="146", "Not-A.Brand";v="24", "Opera";v="130""#,
Impersonate::OperaV131 => r#""Opera";v="131", "Not.A/Brand";v="8", "Chromium";v="147""#,
_ => unreachable!(),
}
}
/// Builds HTTP/2 settings for an Opera version.
#[cfg(feature = "http2")]
fn build_http2_settings(opera: Impersonate) -> crate::imp::Http2Data {
// Opera 131 uses cache-control-first header order
let headers_order = if matches!(opera, Impersonate::OperaV131) {
Some(crate::imp::header_order_cache_control_first().clone())
} else {
Some(crate::imp::header_order_sec_chua_first().clone())
};
crate::imp::Http2Data {
settings_order: Some(opera_settings_order().clone()),
headers_pseudo_order: Some(opera_pseudo_order().clone()),
headers_order,
headers_priority: Some((255, 0, true)),
initial_stream_window_size: Some(crate::imp::CHROME_INITIAL_STREAM_WINDOW),
initial_connection_window_size: Some(crate::imp::CHROME_INITIAL_CONNECTION_WINDOW),
max_header_list_size: Some(crate::imp::CHROME_MAX_HEADER_LIST_SIZE),
header_table_size: Some(crate::imp::CHROME_HEADER_TABLE_SIZE),
..Default::default()
}
}
fn opera_emulator(opera: Impersonate) -> Arc<BrowserEmulator> {
match opera {
Impersonate::OperaV126 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_opera_emulator(126)))
.clone()
}
Impersonate::OperaV127 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_opera_emulator(127)))
.clone()
}
Impersonate::OperaV128 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_opera_emulator(128)))
.clone()
}
Impersonate::OperaV129 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_opera_emulator(129)))
.clone()
}
Impersonate::OperaV130 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_opera_emulator(130)))
.clone()
}
Impersonate::OperaV131 => {
static EMU: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU.get_or_init(|| Arc::new(new_opera_emulator(131)))
.clone()
}
_ => unreachable!(),
}
}
fn new_opera_emulator(major: u16) -> BrowserEmulator {
let mut emulator = BrowserEmulator::new(BrowserType::Opera, BrowserVersion::new(major, 0, 0));
emulator.cipher_suites = Some(emulation::cipher_suites::CHROME.to_vec());
emulator.signature_algorithms = Some(emulation::signature_algorithms::CHROME.to_vec());
emulator.named_groups = Some(emulation::named_groups::CHROME.to_vec());
emulator.extension_order_seed = Some(emulation::extension_order::CHROME);
emulator
}
fn base_opera_headers() -> &'static http::HeaderMap {
static BASE: OnceLock<http::HeaderMap> = OnceLock::new();
BASE.get_or_init(|| {
let mut headers = http::HeaderMap::with_capacity(13);
headers.insert(ACCEPT, http::HeaderValue::from_static("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"));
headers.insert("accept-encoding", http::HeaderValue::from_static("gzip, deflate, br, zstd"));
headers.insert("accept-language", http::HeaderValue::from_static("en-US,en;q=0.9"));
headers.insert("upgrade-insecure-requests", http::HeaderValue::from_static("1"));
headers.insert("sec-fetch-site", http::HeaderValue::from_static("none"));
headers.insert("sec-fetch-mode", http::HeaderValue::from_static("navigate"));
headers.insert("sec-fetch-dest", http::HeaderValue::from_static("document"));
headers.insert("sec-fetch-user", http::HeaderValue::from_static("?1"));
headers.insert("priority", http::HeaderValue::from_static("u=0, i"));
headers
})
}
#[cfg(feature = "http2")]
fn opera_settings_order() -> &'static SettingsOrder {
static ORDER: OnceLock<SettingsOrder> = OnceLock::new();
ORDER.get_or_init(|| {
SettingsOrder::builder()
.push(SettingId::HeaderTableSize)
.push(SettingId::EnablePush)
.push(SettingId::InitialWindowSize)
.push(SettingId::MaxHeaderListSize)
.build_without_extend()
})
}
#[cfg(feature = "http2")]
fn opera_pseudo_order() -> &'static PseudoOrder {
static ORDER: OnceLock<PseudoOrder> = OnceLock::new();
ORDER.get_or_init(|| {
PseudoOrder::builder()
.push(PseudoId::Method)
.push(PseudoId::Authority)
.push(PseudoId::Scheme)
.push(PseudoId::Path)
.build()
})
}
#[cfg(test)]
mod tests {
use crate::imp::Impersonate;
use crate::Client;
use serde::{Deserialize, Serialize};
/// BrowserLeaks.com API response structure
#[derive(Debug, Serialize, Deserialize)]
pub struct BrowserLeaksResponse {
pub user_agent: String,
pub ja4: String,
pub akamai_hash: String,
pub akamai_text: String,
}
const OPERA129_USER_AGENT: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 OPR/129.0.0.0";
const OPERA129_JA4: &str = "t13d1516h2_8daaf6152771_d8a2da3f94cd";
const OPERA129_AKAMAI_HASH: &str = "52d84b11737d980aef856699f885ca86";
const OPERA129_AKAMAI_TEXT: &str = "1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p";
#[tokio::test]
#[cfg(feature = "impersonate")]
async fn test_opera129() {
let client = Client::builder()
.impersonate_os(crate::imp::ImpersonateOS::Linux)
.impersonate(Impersonate::OperaV129)
.build()
.unwrap();
let response = client
.get("https://tls.browserleaks.com/json")
.send()
.await
.unwrap();
let json: BrowserLeaksResponse = response.json().await.unwrap();
assert_eq!(json.user_agent, OPERA129_USER_AGENT);
assert_eq!(json.ja4, OPERA129_JA4);
assert_eq!(json.akamai_hash, OPERA129_AKAMAI_HASH);
assert_eq!(json.akamai_text, OPERA129_AKAMAI_TEXT);
}
}
+452
View File
@@ -0,0 +1,452 @@
//! Safari browser impersonation settings.
//!
//! This module provides configuration for impersonating various Safari browser versions.
//! Each version has its own TLS fingerprint, ALPN protocols, and default HTTP headers
//! that mimic the real Safari browser behavior.
//!
//! # Usage
//!
//! ```rust
//! use primp::{Client, Impersonate};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let client = Client::builder()
//! .impersonate(Impersonate::SafariV26)
//! .build()?;
//!
//! //let response = client.get("https://example.com").send().await?;
//! Ok(())
//! }
//! ```
pub use crate::imp::Impersonate;
#[cfg(feature = "http2")]
use crate::imp::{PseudoId, PseudoOrder, SettingId, SettingsOrder};
use rustls::client::{BrowserEmulator, BrowserEmulatorOS, BrowserType, BrowserVersion};
use rustls::crypto::emulation;
use std::sync::{Arc, OnceLock};
/// Builds browser settings for a specific Safari version and OS.
pub(crate) fn build_safari_settings(
safari: Impersonate,
os: crate::imp::ImpersonateOS,
) -> crate::imp::BrowserSettings {
let os = if matches!(os, crate::imp::ImpersonateOS::Random) {
crate::imp::random_impersonate_os()
} else {
os
};
let user_agent = build_user_agent(safari, os);
let headers = build_safari_base_headers(user_agent);
// Convert ImpersonateOS to BrowserEmulatorOS
let browser_os = match os {
crate::imp::ImpersonateOS::MacOS => BrowserEmulatorOS::MacOS,
crate::imp::ImpersonateOS::IOS => BrowserEmulatorOS::IOS,
_ => BrowserEmulatorOS::MacOS,
};
// Get cached browser emulator for Safari (Arc clone = cheap refcount increment)
let browser_emulator = safari_emulator(safari, browser_os);
let http2 = build_http2_settings();
crate::imp::BrowserSettings {
browser_emulator,
http2,
headers,
gzip: true,
brotli: true,
zstd: false,
deflate: true,
}
}
/// Builds a User-Agent string for a Safari version and OS.
/// Safari only supports MacOS and iOS; other OSes default to MacOS.
fn build_user_agent(safari: Impersonate, os: crate::imp::ImpersonateOS) -> &'static str {
// Random is resolved before this is called; only MacOS and IOS reach here
let os = match os {
crate::imp::ImpersonateOS::IOS => crate::imp::ImpersonateOS::IOS,
_ => crate::imp::ImpersonateOS::MacOS,
};
match safari {
Impersonate::SafariV18_5 => match os {
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1",
_ => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15",
},
Impersonate::SafariV26 => match os {
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 26_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1",
_ => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15",
},
// Safari 26.3: macOS uses Safari 26 UA, iOS uses Safari 18.5 UA
Impersonate::SafariV26_3 => match os {
crate::imp::ImpersonateOS::IOS => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1",
_ => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.3 Safari/605.1.15",
},
_ => unreachable!(),
}
}
/// Builds default headers for Safari using cached base.
fn build_safari_base_headers(user_agent: &'static str) -> http::HeaderMap {
let mut headers = safari_base_headers().clone();
headers.insert(
http::header::USER_AGENT,
http::HeaderValue::from_static(user_agent),
);
headers
}
/// Builds HTTP/2 settings for Safari.
#[cfg(feature = "http2")]
fn build_http2_settings() -> crate::imp::Http2Data {
crate::imp::Http2Data {
initial_stream_window_size: Some(crate::imp::SAFARI_INITIAL_STREAM_WINDOW),
initial_connection_window_size: Some(crate::imp::SAFARI_INITIAL_CONNECTION_WINDOW),
max_concurrent_streams: Some(100),
max_header_list_size: Some(crate::imp::SAFARI_MAX_HEADER_LIST_SIZE),
no_rfc7540_priorities: Some(true),
settings_order: Some(safari_settings_order().clone()),
headers_pseudo_order: Some(safari_pseudo_order().clone()),
..Default::default()
}
}
fn safari_emulator(safari: Impersonate, browser_os: BrowserEmulatorOS) -> Arc<BrowserEmulator> {
match safari {
Impersonate::SafariV18_5 => match browser_os {
BrowserEmulatorOS::IOS => {
static EMU_IOS: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU_IOS
.get_or_init(|| {
let mut emu = new_safari_18_5_emulator();
emu.os_type = Some(BrowserEmulatorOS::IOS);
Arc::new(emu)
})
.clone()
}
_ => {
static EMU_MACOS: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU_MACOS
.get_or_init(|| {
let mut emu = new_safari_18_5_emulator();
emu.os_type = Some(BrowserEmulatorOS::MacOS);
Arc::new(emu)
})
.clone()
}
},
Impersonate::SafariV26 => match browser_os {
BrowserEmulatorOS::IOS => {
static EMU_IOS: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU_IOS
.get_or_init(|| {
let mut emu = new_safari_26_emulator();
emu.os_type = Some(BrowserEmulatorOS::IOS);
Arc::new(emu)
})
.clone()
}
_ => {
static EMU_MACOS: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU_MACOS
.get_or_init(|| {
let mut emu = new_safari_26_emulator();
emu.os_type = Some(BrowserEmulatorOS::MacOS);
Arc::new(emu)
})
.clone()
}
},
Impersonate::SafariV26_3 => {
if browser_os == BrowserEmulatorOS::IOS {
static EMU_IOS: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU_IOS
.get_or_init(|| Arc::new(new_safari_26_3_ios_emulator()))
.clone()
} else {
static EMU_MACOS: OnceLock<Arc<BrowserEmulator>> = OnceLock::new();
EMU_MACOS
.get_or_init(|| Arc::new(new_safari_26_3_macos_emulator()))
.clone()
}
}
_ => unreachable!(),
}
}
fn new_safari_18_5_emulator() -> BrowserEmulator {
let mut emulator = BrowserEmulator::new(BrowserType::Safari, BrowserVersion::new(18, 5, 0));
emulator.cipher_suites = Some(emulation::cipher_suites::SAFARI.to_vec());
emulator.named_groups = Some(emulation::named_groups::SAFARI.to_vec());
emulator.signature_algorithms = Some(emulation::signature_algorithms::SAFARI.to_vec());
emulator.extension_order_seed = Some(emulation::extension_order::SAFARI_18_5);
emulator.include_status_request_v2 = true;
emulator
}
fn new_safari_26_emulator() -> BrowserEmulator {
let mut emulator = BrowserEmulator::new(BrowserType::Safari, BrowserVersion::new(26, 0, 0));
emulator.cipher_suites = Some(emulation::cipher_suites::SAFARI.to_vec());
emulator.named_groups = Some(emulation::named_groups::SAFARI.to_vec());
emulator.signature_algorithms = Some(emulation::signature_algorithms::SAFARI.to_vec());
emulator.extension_order_seed = Some(emulation::extension_order::SAFARI_26);
emulator
}
fn new_safari_26_3_ios_emulator() -> BrowserEmulator {
let mut emulator = BrowserEmulator::new(BrowserType::Safari, BrowserVersion::new(26, 3, 0));
emulator.cipher_suites = Some(emulation::cipher_suites::SAFARI.to_vec());
emulator.named_groups = Some(emulation::named_groups::SAFARI.to_vec());
emulator.signature_algorithms = Some(emulation::signature_algorithms::SAFARI.to_vec());
emulator.extension_order_seed = Some(emulation::extension_order::SAFARI_26);
emulator.os_type = Some(BrowserEmulatorOS::IOS);
emulator
}
fn new_safari_26_3_macos_emulator() -> BrowserEmulator {
let mut emulator = BrowserEmulator::new(BrowserType::Safari, BrowserVersion::new(26, 3, 0));
emulator.cipher_suites = Some(emulation::cipher_suites::SAFARI.to_vec());
emulator.named_groups = Some(emulation::named_groups::SAFARI.to_vec());
emulator.signature_algorithms = Some(emulation::signature_algorithms::SAFARI.to_vec());
emulator.extension_order_seed = Some(emulation::extension_order::SAFARI_18_5);
emulator.include_status_request_v2 = true;
emulator.os_type = Some(BrowserEmulatorOS::MacOS);
emulator
}
fn safari_base_headers() -> &'static http::HeaderMap {
static BASE: OnceLock<http::HeaderMap> = OnceLock::new();
BASE.get_or_init(|| {
let mut headers = http::HeaderMap::with_capacity(8);
headers.insert(
http::header::ACCEPT,
http::HeaderValue::from_static(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
),
);
headers.insert(
http::header::ACCEPT_LANGUAGE,
http::HeaderValue::from_static("en-US,en;q=0.9"),
);
headers.insert(
"accept-encoding",
http::HeaderValue::from_static("gzip, deflate, br"),
);
headers.insert("sec-fetch-dest", http::HeaderValue::from_static("document"));
headers.insert("sec-fetch-mode", http::HeaderValue::from_static("navigate"));
headers.insert("sec-fetch-site", http::HeaderValue::from_static("none"));
headers.insert("priority", http::HeaderValue::from_static("u=0, i"));
headers
})
}
#[cfg(feature = "http2")]
fn safari_settings_order() -> &'static SettingsOrder {
static ORDER: OnceLock<SettingsOrder> = OnceLock::new();
ORDER.get_or_init(|| {
SettingsOrder::builder()
.push(SettingId::EnablePush)
.push(SettingId::MaxConcurrentStreams)
.push(SettingId::InitialWindowSize)
.push(SettingId::NoRfc7540Priorities)
.build_without_extend()
})
}
#[cfg(feature = "http2")]
fn safari_pseudo_order() -> &'static PseudoOrder {
static ORDER: OnceLock<PseudoOrder> = OnceLock::new();
ORDER.get_or_init(|| {
PseudoOrder::builder()
.push(PseudoId::Method)
.push(PseudoId::Scheme)
.push(PseudoId::Authority)
.push(PseudoId::Path)
.build()
})
}
#[cfg(test)]
mod tests {
use crate::imp::{Impersonate, ImpersonateOS};
use crate::Client;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct BrowserLeaksResponse {
pub user_agent: String,
pub ja4: String,
pub akamai_hash: String,
pub akamai_text: String,
}
// Safari 18.5 test constants
const SAFARI185_USER_AGENT: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15";
const SAFARI185_JA4: &str = "t13d2014h2_a09f3c656075_e42f34c56612";
const SAFARI185_AKAMAI_HASH: &str = "c52879e43202aeb92740be6e8c86ea96";
const SAFARI185_AKAMAI_TEXT: &str = "2:0;3:100;4:2097152;9:1|10420225|0|m,s,a,p";
const SAFARI185_IOS_USER_AGENT: &str = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1";
const SAFARI185_IOS_JA4: &str = "t13d2014h2_a09f3c656075_e42f34c56612";
const SAFARI185_IOS_AKAMAI_HASH: &str = "c52879e43202aeb92740be6e8c86ea96";
const SAFARI185_IOS_AKAMAI_TEXT: &str = "2:0;3:100;4:2097152;9:1|10420225|0|m,s,a,p";
const SAFARI26_USER_AGENT: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15";
const SAFARI26_JA4: &str = "t13d2013h2_a09f3c656075_7f0f34a4126d";
const SAFARI26_AKAMAI_HASH: &str = "c52879e43202aeb92740be6e8c86ea96";
const SAFARI26_AKAMAI_TEXT: &str = "2:0;3:100;4:2097152;9:1|10420225|0|m,s,a,p";
const SAFARI26_IOS_USER_AGENT: &str = "Mozilla/5.0 (iPhone; CPU iPhone OS 26_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Mobile/15E148 Safari/604.1";
const SAFARI26_IOS_JA4: &str = "t13d2013h2_a09f3c656075_7f0f34a4126d";
const SAFARI26_IOS_AKAMAI_HASH: &str = "c52879e43202aeb92740be6e8c86ea96";
const SAFARI26_IOS_AKAMAI_TEXT: &str = "2:0;3:100;4:2097152;9:1|10420225|0|m,s,a,p";
#[tokio::test]
#[cfg(feature = "impersonate")]
async fn test_safari185() {
let client = Client::builder()
.impersonate_os(ImpersonateOS::MacOS)
.impersonate(Impersonate::SafariV18_5)
.build()
.unwrap();
let response = client
.get("https://tls.browserleaks.com/json")
.send()
.await
.unwrap();
let json: BrowserLeaksResponse = response.json().await.unwrap();
assert_eq!(json.user_agent, SAFARI185_USER_AGENT);
assert_eq!(json.ja4, SAFARI185_JA4);
assert_eq!(json.akamai_hash, SAFARI185_AKAMAI_HASH);
assert_eq!(json.akamai_text, SAFARI185_AKAMAI_TEXT);
}
#[tokio::test]
#[cfg(feature = "impersonate")]
async fn test_safari185_ios() {
let client = Client::builder()
.impersonate_os(ImpersonateOS::IOS)
.impersonate(Impersonate::SafariV18_5)
.build()
.unwrap();
let response = client
.get("https://tls.browserleaks.com/json")
.send()
.await
.unwrap();
let json: BrowserLeaksResponse = response.json().await.unwrap();
assert_eq!(json.user_agent, SAFARI185_IOS_USER_AGENT);
assert_eq!(json.ja4, SAFARI185_IOS_JA4);
assert_eq!(json.akamai_hash, SAFARI185_IOS_AKAMAI_HASH);
assert_eq!(json.akamai_text, SAFARI185_IOS_AKAMAI_TEXT);
}
#[tokio::test]
#[cfg(feature = "impersonate")]
async fn test_safari26() {
let client = Client::builder()
.impersonate_os(ImpersonateOS::MacOS)
.impersonate(Impersonate::SafariV26)
.build()
.unwrap();
let response = client
.get("https://tls.browserleaks.com/json")
.send()
.await
.unwrap();
let json: BrowserLeaksResponse = response.json().await.unwrap();
assert_eq!(json.user_agent, SAFARI26_USER_AGENT);
assert_eq!(json.ja4, SAFARI26_JA4);
assert_eq!(json.akamai_hash, SAFARI26_AKAMAI_HASH);
assert_eq!(json.akamai_text, SAFARI26_AKAMAI_TEXT);
}
#[tokio::test]
#[cfg(feature = "impersonate")]
async fn test_safari26_ios() {
let client = Client::builder()
.impersonate_os(ImpersonateOS::IOS)
.impersonate(Impersonate::SafariV26)
.build()
.unwrap();
let response = client
.get("https://tls.browserleaks.com/json")
.send()
.await
.unwrap();
let json: BrowserLeaksResponse = response.json().await.unwrap();
assert_eq!(json.user_agent, SAFARI26_IOS_USER_AGENT);
assert_eq!(json.ja4, SAFARI26_IOS_JA4);
assert_eq!(json.akamai_hash, SAFARI26_IOS_AKAMAI_HASH);
assert_eq!(json.akamai_text, SAFARI26_IOS_AKAMAI_TEXT);
}
const SAFARI26_3_MACOS_USER_AGENT: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.3 Safari/605.1.15";
const SAFARI26_3_MACOS_JA4: &str = "t13d2014h2_a09f3c656075_e42f34c56612";
const SAFARI26_3_MACOS_AKAMAI_HASH: &str = "c52879e43202aeb92740be6e8c86ea96";
const SAFARI26_3_MACOS_AKAMAI_TEXT: &str = "2:0;3:100;4:2097152;9:1|10420225|0|m,s,a,p";
#[tokio::test]
#[cfg(feature = "impersonate")]
async fn test_safari26_3_macos() {
let client = Client::builder()
.impersonate_os(ImpersonateOS::MacOS)
.impersonate(Impersonate::SafariV26_3)
.build()
.unwrap();
let response = client
.get("https://tls.browserleaks.com/json")
.send()
.await
.unwrap();
let json: BrowserLeaksResponse = response.json().await.unwrap();
assert_eq!(json.user_agent, SAFARI26_3_MACOS_USER_AGENT);
assert_eq!(json.ja4, SAFARI26_3_MACOS_JA4);
assert_eq!(json.akamai_hash, SAFARI26_3_MACOS_AKAMAI_HASH);
assert_eq!(json.akamai_text, SAFARI26_3_MACOS_AKAMAI_TEXT);
}
const SAFARI26_3_IOS_USER_AGENT: &str = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1";
const SAFARI26_3_IOS_JA4: &str = "t13d2013h2_a09f3c656075_7f0f34a4126d";
const SAFARI26_3_IOS_AKAMAI_HASH: &str = "c52879e43202aeb92740be6e8c86ea96";
const SAFARI26_3_IOS_AKAMAI_TEXT: &str = "2:0;3:100;4:2097152;9:1|10420225|0|m,s,a,p";
#[tokio::test]
#[cfg(feature = "impersonate")]
async fn test_safari26_3_ios() {
let client = Client::builder()
.impersonate_os(ImpersonateOS::IOS)
.impersonate(Impersonate::SafariV26_3)
.build()
.unwrap();
let response = client
.get("https://tls.browserleaks.com/json")
.send()
.await
.unwrap();
let json: BrowserLeaksResponse = response.json().await.unwrap();
assert_eq!(json.user_agent, SAFARI26_3_IOS_USER_AGENT);
assert_eq!(json.ja4, SAFARI26_3_IOS_JA4);
assert_eq!(json.akamai_hash, SAFARI26_3_IOS_AKAMAI_HASH);
assert_eq!(json.akamai_text, SAFARI26_3_IOS_AKAMAI_TEXT);
}
}
+755
View File
@@ -0,0 +1,755 @@
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
#![cfg_attr(test, deny(warnings))]
//! # primp
//!
//! The `primp` crate provides an HTTP client with browser impersonation capabilities.
//! It wraps `primp-reqwest` and adds browser fingerprinting features.
//!
//! ## Features
//!
//! - All features from `primp-reqwest` (HTTP client, TLS, cookies, etc.)
//! - Browser impersonation (Chrome, Firefox, Safari, Edge, Opera)
//! - TLS fingerprint matching
//! - HTTP/2 fingerprint matching
// Re-export everything from primp-reqwest
pub use reqwest::*;
/// Impersonation module for browser fingerprinting
#[cfg(not(target_arch = "wasm32"))]
pub mod imp;
/// Re-export impersonation types
#[cfg(not(target_arch = "wasm32"))]
pub use imp::{BrowserSettings, Http2Data, Impersonate, ImpersonateOS};
/// Re-export h2 frame types used in the public HTTP/2 API
#[cfg(all(feature = "http2", not(target_arch = "wasm32")))]
pub use h2::frame::{
PseudoId, PseudoOrder, PseudoOrderBuilder, SettingId, SettingsOrder, SettingsOrderBuilder,
};
/// An HTTP Client with impersonation support
#[derive(Debug, Clone)]
pub struct Client {
inner: reqwest::Client,
}
/// A builder for configuring a Client with impersonation support
#[derive(Debug)]
pub struct ClientBuilder {
inner: reqwest::ClientBuilder,
#[cfg(not(target_arch = "wasm32"))]
impersonate: Option<Impersonate>,
#[cfg(not(target_arch = "wasm32"))]
os_type: Option<ImpersonateOS>,
#[cfg(not(target_arch = "wasm32"))]
root_certs: Vec<reqwest::Certificate>,
}
impl Default for ClientBuilder {
fn default() -> Self {
Self::new()
}
}
impl ClientBuilder {
/// Constructs a new `ClientBuilder`.
pub fn new() -> Self {
Self {
inner: reqwest::ClientBuilder::new()
.timeout(std::time::Duration::from_secs(30))
.connect_timeout(std::time::Duration::from_secs(30)),
#[cfg(not(target_arch = "wasm32"))]
impersonate: None,
#[cfg(not(target_arch = "wasm32"))]
os_type: None,
#[cfg(not(target_arch = "wasm32"))]
root_certs: Vec::new(),
}
}
/// Returns a `Client` that uses this `ClientBuilder` configuration.
pub fn build(self) -> crate::Result<Client> {
#[cfg(not(target_arch = "wasm32"))]
let inner = match (self.impersonate, self.os_type) {
(None, None) => self.inner.build()?,
_ => {
let imp = self.impersonate.unwrap_or(Impersonate::Random);
let os = self.os_type.unwrap_or(ImpersonateOS::Random);
let settings = imp::get_browser_settings(imp, Some(os));
apply_impersonation(self.inner, settings, &self.root_certs)?
}
};
#[cfg(target_arch = "wasm32")]
let inner = self.inner.build()?;
Ok(Client { inner })
}
/// Sets the browser to impersonate.
#[cfg(not(target_arch = "wasm32"))]
pub fn impersonate(mut self, version: Impersonate) -> Self {
self.impersonate = Some(version);
self
}
/// Sets the OS to impersonate.
#[cfg(not(target_arch = "wasm32"))]
pub fn impersonate_os(mut self, os_type: ImpersonateOS) -> Self {
self.os_type = Some(os_type);
self
}
/// Sets the `User-Agent` header.
pub fn user_agent<V>(mut self, value: V) -> Self
where
V: TryInto<http::HeaderValue>,
V::Error: Into<http::Error>,
{
self.inner = self.inner.user_agent(value);
self
}
/// Sets the default headers for every request.
pub fn default_headers(mut self, headers: http::HeaderMap) -> Self {
self.inner = self.inner.default_headers(headers);
self
}
/// Enable a persistent cookie store.
pub fn cookie_store(mut self, enable: bool) -> Self {
self.inner = self.inner.cookie_store(enable);
self
}
/// Set the cookie provider.
pub fn cookie_provider<C: reqwest::cookie::CookieStore + 'static>(
mut self,
cookie_store: std::sync::Arc<C>,
) -> Self {
self.inner = self.inner.cookie_provider(cookie_store);
self
}
/// Enable auto gzip decompression.
pub fn gzip(mut self, enable: bool) -> Self {
self.inner = self.inner.gzip(enable);
self
}
/// Enable auto brotli decompression.
pub fn brotli(mut self, enable: bool) -> Self {
self.inner = self.inner.brotli(enable);
self
}
/// Enable auto zstd decompression.
pub fn zstd(mut self, enable: bool) -> Self {
self.inner = self.inner.zstd(enable);
self
}
/// Enable auto deflate decompression.
#[cfg(feature = "deflate")]
pub fn deflate(mut self, enable: bool) -> Self {
self.inner = self.inner.deflate(enable);
self
}
/// Disable auto gzip decompression.
pub fn no_gzip(mut self) -> Self {
self.inner = self.inner.no_gzip();
self
}
/// Disable auto brotli decompression.
pub fn no_brotli(mut self) -> Self {
self.inner = self.inner.no_brotli();
self
}
/// Disable auto zstd decompression.
pub fn no_zstd(mut self) -> Self {
self.inner = self.inner.no_zstd();
self
}
/// Disable auto deflate decompression.
#[cfg(feature = "deflate")]
pub fn no_deflate(mut self) -> Self {
self.inner = self.inner.no_deflate();
self
}
/// Set a redirect policy.
pub fn redirect(mut self, policy: reqwest::redirect::Policy) -> Self {
self.inner = self.inner.redirect(policy);
self
}
/// Enable or disable automatic Referer header.
pub fn referer(mut self, enable: bool) -> Self {
self.inner = self.inner.referer(enable);
self
}
/// Add a proxy.
pub fn proxy(mut self, proxy: reqwest::Proxy) -> Self {
self.inner = self.inner.proxy(proxy);
self
}
/// Clear all proxies.
pub fn no_proxy(mut self) -> Self {
self.inner = self.inner.no_proxy();
self
}
/// Enables a total request timeout.
pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
self.inner = self.inner.timeout(timeout);
self
}
/// Enables a read timeout.
pub fn read_timeout(mut self, timeout: std::time::Duration) -> Self {
self.inner = self.inner.read_timeout(timeout);
self
}
/// Set a timeout for only the connect phase.
pub fn connect_timeout(mut self, timeout: std::time::Duration) -> Self {
self.inner = self.inner.connect_timeout(timeout);
self
}
/// Set whether connections should emit verbose logs.
pub fn connection_verbose(mut self, verbose: bool) -> Self {
self.inner = self.inner.connection_verbose(verbose);
self
}
/// Set an optional timeout for idle sockets being kept-alive.
pub fn pool_idle_timeout<D>(mut self, val: D) -> Self
where
D: Into<Option<std::time::Duration>>,
{
self.inner = self.inner.pool_idle_timeout(val);
self
}
/// Sets the maximum idle connection per host allowed in the pool.
pub fn pool_max_idle_per_host(mut self, max: usize) -> Self {
self.inner = self.inner.pool_max_idle_per_host(max);
self
}
/// Send headers as title case instead of lowercase.
pub fn http1_title_case_headers(mut self) -> Self {
self.inner = self.inner.http1_title_case_headers();
self
}
/// Only use HTTP/1.
pub fn http1_only(mut self) -> Self {
self.inner = self.inner.http1_only();
self
}
/// Allow HTTP/0.9 responses.
pub fn http09_responses(mut self) -> Self {
self.inner = self.inner.http09_responses();
self
}
/// Only use HTTP/2.
pub fn http2_prior_knowledge(mut self) -> Self {
self.inner = self.inner.http2_prior_knowledge();
self
}
/// Sets the HTTP2 stream-level initial window size.
pub fn http2_initial_stream_window_size(mut self, sz: impl Into<Option<u32>>) -> Self {
self.inner = self.inner.http2_initial_stream_window_size(sz);
self
}
/// Sets the HTTP2 connection-level initial window size.
pub fn http2_initial_connection_window_size(mut self, sz: impl Into<Option<u32>>) -> Self {
self.inner = self.inner.http2_initial_connection_window_size(sz);
self
}
/// Sets whether to use an adaptive flow control.
pub fn http2_adaptive_window(mut self, enabled: bool) -> Self {
self.inner = self.inner.http2_adaptive_window(enabled);
self
}
/// Sets the maximum frame size to use for HTTP2.
pub fn http2_max_frame_size(mut self, sz: impl Into<Option<u32>>) -> Self {
self.inner = self.inner.http2_max_frame_size(sz);
self
}
/// Sets the maximum size of received header frames for HTTP2.
pub fn http2_max_header_list_size(mut self, max_header_size_bytes: u32) -> Self {
self.inner = self.inner.http2_max_header_list_size(max_header_size_bytes);
self
}
/// Sets an interval for HTTP2 Ping frames.
pub fn http2_keep_alive_interval(
mut self,
interval: impl Into<Option<std::time::Duration>>,
) -> Self {
self.inner = self.inner.http2_keep_alive_interval(interval);
self
}
/// Sets a timeout for receiving an acknowledgement of the keep-alive ping.
pub fn http2_keep_alive_timeout(mut self, timeout: std::time::Duration) -> Self {
self.inner = self.inner.http2_keep_alive_timeout(timeout);
self
}
/// Sets whether HTTP2 keep-alive should apply while the connection is idle.
pub fn http2_keep_alive_while_idle(mut self, enabled: bool) -> Self {
self.inner = self.inner.http2_keep_alive_while_idle(enabled);
self
}
/// Sets the HTTP/2 SETTINGS_HEADER_TABLE_SIZE value.
pub fn http2_header_table_size(mut self, size: impl Into<Option<u32>>) -> Self {
self.inner = self.inner.http2_header_table_size(size);
self
}
/// Sets the HTTP/2 SETTINGS_MAX_CONCURRENT_STREAMS value.
pub fn http2_max_concurrent_streams(mut self, max: impl Into<Option<u32>>) -> Self {
self.inner = self.inner.http2_max_concurrent_streams(max);
self
}
/// Sets the HTTP/2 SETTINGS_ENABLE_PUSH value.
pub fn http2_enable_push(mut self, enabled: impl Into<Option<bool>>) -> Self {
self.inner = self.inner.http2_enable_push(enabled);
self
}
/// Sets the HTTP/2 SETTINGS_NO_RFC7540_PRIORITIES value.
pub fn http2_no_rfc7540_priorities(mut self, enabled: impl Into<Option<bool>>) -> Self {
self.inner = self.inner.http2_no_rfc7540_priorities(enabled);
self
}
/// Sets the HTTP/2 SETTINGS frame order for fingerprinting.
#[cfg(not(target_arch = "wasm32"))]
pub fn http2_settings_order(mut self, order: h2::frame::SettingsOrder) -> Self {
self.inner = self.inner.http2_settings_order(order);
self
}
/// Sets the HTTP/2 pseudo-header order for fingerprinting.
#[cfg(not(target_arch = "wasm32"))]
pub fn http2_headers_pseudo_order(mut self, order: h2::frame::PseudoOrder) -> Self {
self.inner = self.inner.http2_headers_pseudo_order(order);
self
}
#[allow(missing_docs)]
pub fn http2_headers_order(mut self, order: Vec<http::HeaderName>) -> Self {
self.inner = self.inner.http2_headers_order(order);
self
}
/// Sets whether to include PRIORITY flag in HTTP/2 HEADERS frames.
pub fn http2_headers_priority(mut self, data: Option<(u8, u32, bool)>) -> Self {
self.inner = self.inner.http2_headers_priority(data);
self
}
/// Set whether sockets have TCP_NODELAY enabled.
pub fn tcp_nodelay(mut self, enabled: bool) -> Self {
self.inner = self.inner.tcp_nodelay(enabled);
self
}
/// Bind to a local IP Address.
pub fn local_address<T>(mut self, addr: T) -> Self
where
T: Into<Option<std::net::IpAddr>>,
{
self.inner = self.inner.local_address(addr);
self
}
/// Set that all sockets have SO_KEEPALIVE set.
pub fn tcp_keepalive<D>(mut self, val: D) -> Self
where
D: Into<Option<std::time::Duration>>,
{
self.inner = self.inner.tcp_keepalive(val);
self
}
/// Add custom certificate roots.
pub fn add_root_certificate(mut self, cert: reqwest::Certificate) -> Self {
#[cfg(not(target_arch = "wasm32"))]
self.root_certs.push(cert.clone());
self.inner = self.inner.add_root_certificate(cert);
self
}
/// Sets the identity to be used for client certificate authentication.
pub fn identity(mut self, identity: reqwest::Identity) -> Self {
self.inner = self.inner.identity(identity);
self
}
/// Controls the use of hostname verification.
pub fn danger_accept_invalid_hostnames(mut self, accept_invalid_hostname: bool) -> Self {
self.inner = self
.inner
.danger_accept_invalid_hostnames(accept_invalid_hostname);
self
}
/// Controls the use of certificate validation.
pub fn danger_accept_invalid_certs(mut self, accept_invalid_certs: bool) -> Self {
self.inner = self.inner.danger_accept_invalid_certs(accept_invalid_certs);
self
}
/// Use a preconfigured TLS backend.
pub fn use_preconfigured_tls(mut self, tls: impl std::any::Any) -> Self {
self.inner = self.inner.use_preconfigured_tls(tls);
self
}
/// Restrict the Client to be used with HTTPS only requests.
pub fn https_only(mut self, enabled: bool) -> Self {
self.inner = self.inner.https_only(enabled);
self
}
/// Override DNS resolution for specific domains.
pub fn resolve(mut self, domain: &str, addr: std::net::SocketAddr) -> Self {
self.inner = self.inner.resolve(domain, addr);
self
}
/// Override DNS resolution for specific domains to particular IP addresses.
pub fn resolve_to_addrs(mut self, domain: &str, addrs: &[std::net::SocketAddr]) -> Self {
self.inner = self.inner.resolve_to_addrs(domain, addrs);
self
}
/// Override the DNS resolver implementation.
///
/// Accepts any type implementing `IntoResolve`, such as `GaiResolver`,
/// or a `Vec` of resolvers for fallback.
///
/// **Note:** `DohResolver`, `DotResolver`, and `PlainDnsResolver` require the `hickory-dns` feature.
pub fn dns_resolver<R>(mut self, resolver: R) -> Self
where
R: crate::dns::IntoResolve,
{
self.inner = self.inner.dns_resolver(resolver);
self
}
}
impl Client {
/// Constructs a new `Client`.
pub fn new() -> Client {
ClientBuilder::new().build().expect("Client::new()")
}
/// Creates a `ClientBuilder` to configure a `Client`.
pub fn builder() -> ClientBuilder {
ClientBuilder::new()
}
/// Convenience method to make a `GET` request to a URL.
pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
self.inner.get(url)
}
/// Convenience method to make a `POST` request to a URL.
pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder {
self.inner.post(url)
}
/// Convenience method to make a `PUT` request to a URL.
pub fn put<U: IntoUrl>(&self, url: U) -> RequestBuilder {
self.inner.put(url)
}
/// Convenience method to make a `PATCH` request to a URL.
pub fn patch<U: IntoUrl>(&self, url: U) -> RequestBuilder {
self.inner.patch(url)
}
/// Convenience method to make a `DELETE` request to a URL.
pub fn delete<U: IntoUrl>(&self, url: U) -> RequestBuilder {
self.inner.delete(url)
}
/// Convenience method to make a `HEAD` request to a URL.
pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder {
self.inner.head(url)
}
/// Start building a `Request` with the `Method` and `Url`.
pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
self.inner.request(method, url)
}
/// Executes a `Request`.
pub async fn execute(&self, request: Request) -> Result<Response> {
self.inner.execute(request).await
}
/// Get the default headers.
pub fn headers(&self) -> &http::HeaderMap {
self.inner.headers()
}
/// Get a mutable reference to the default headers.
pub fn headers_mut(&mut self) -> &mut http::HeaderMap {
self.inner.headers_mut()
}
/// Get cookies for the given URL.
pub fn get_cookies(&self, url: &url::Url) -> Option<http::HeaderValue> {
self.inner.get_cookies(url)
}
/// Set cookies for the given URL.
pub fn set_cookies(&self, url: &url::Url, cookies: Vec<http::HeaderValue>) {
self.inner.set_cookies(url, cookies)
}
/// Set proxies for the client.
pub fn set_proxies(&mut self, proxies: Vec<reqwest::Proxy>) {
self.inner.set_proxies(proxies)
}
/// Set the redirect policy for the client.
///
/// This allows changing redirect behavior at runtime without rebuilding the client.
/// Use `Policy::none()` to disable redirects, or `Policy::limited(n)` to set a limit.
pub fn set_redirect_policy(&mut self, policy: reqwest::redirect::Policy) {
self.inner.set_redirect_policy(policy);
}
}
impl Default for Client {
fn default() -> Self {
Self::new()
}
}
/// Shortcut method to quickly make a `GET` request.
pub async fn get<T: IntoUrl>(url: T) -> crate::Result<Response> {
Client::builder().build()?.get(url).send().await
}
#[cfg(not(target_arch = "wasm32"))]
fn apply_impersonation(
builder: reqwest::ClientBuilder,
settings: BrowserSettings,
custom_certs: &[reqwest::Certificate],
) -> crate::Result<reqwest::Client> {
// Build rustls::ClientConfig with impersonation TLS settings
let tls_config = build_impersonate_tls_config(&settings, custom_certs)?;
// Apply TLS configuration
let builder = builder.use_preconfigured_tls(tls_config);
// Apply HTTP/2 settings
let builder = apply_http2_settings(builder, &settings.http2);
// Apply headers
let builder = builder.default_headers(settings.headers);
// Apply compression settings
let mut builder = builder;
if !settings.gzip {
builder = builder.no_gzip();
}
if !settings.brotli {
builder = builder.no_brotli();
}
if !settings.zstd {
builder = builder.no_zstd();
}
if !settings.deflate {
builder = builder.no_deflate();
}
builder.build()
}
#[cfg(not(target_arch = "wasm32"))]
fn build_impersonate_tls_config(
settings: &BrowserSettings,
custom_certs: &[reqwest::Certificate],
) -> crate::Result<rustls::ClientConfig> {
use rustls::client::EchMode;
use std::sync::{Arc, OnceLock};
// Cache the CryptoProvider to avoid repeated lookups and allocations
static CRYPTO_PROVIDER: OnceLock<Arc<rustls::crypto::CryptoProvider>> = OnceLock::new();
let provider = CRYPTO_PROVIDER
.get_or_init(|| {
rustls::crypto::CryptoProvider::get_default()
.cloned()
.unwrap_or_else(|| Arc::new(rustls::crypto::aws_lc_rs::default_provider()))
})
.clone();
// Cache the default root store to avoid cloning hundreds of certs on every build
static DEFAULT_ROOT_STORE: OnceLock<Arc<rustls::RootCertStore>> = OnceLock::new();
let root_store = if custom_certs.is_empty() {
DEFAULT_ROOT_STORE
.get_or_init(|| Arc::new(reqwest::tls::default_root_store().clone()))
.clone()
} else {
Arc::new(reqwest::tls::merged_root_store(custom_certs.to_vec())?)
};
// ECH GREASE is only used for Chrome-based browsers and Firefox to match JA4 fingerprint
// Safari does NOT use ECH GREASE
let needs_ech_grease =
settings.browser_emulator.is_chrome_based() || settings.browser_emulator.is_firefox();
let mut config = if needs_ech_grease {
rustls::ClientConfig::builder_with_provider(provider)
.with_ech(EchMode::Grease(get_ech_grease_config()))
.expect("ECH GREASE config should be valid")
.with_root_certificates(root_store)
.with_no_client_auth()
} else {
rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.expect("TLS versions should be valid")
.with_root_certificates(root_store)
.with_no_client_auth()
};
// Set browser emulation
config.browser_emulation = Some((*settings.browser_emulator).clone());
// Set ALPN protocols
config.alpn_protocols = vec!["h2".into(), "http/1.1".into()];
// Filter cert_decompressors to match real browser behavior
// Chrome/Edge/Opera only advertise brotli; Firefox advertises zlib,brotli
if settings.browser_emulator.is_chrome_based() {
config.cert_decompressors.retain(|d| {
matches!(
d.algorithm(),
rustls::CertificateCompressionAlgorithm::Brotli
)
});
} else if settings.browser_emulator.is_firefox() {
// Firefox sends zlib before brotli
config.cert_decompressors.sort_by(|a, b| {
let a_is_zlib = matches!(a.algorithm(), rustls::CertificateCompressionAlgorithm::Zlib);
let b_is_zlib = matches!(b.algorithm(), rustls::CertificateCompressionAlgorithm::Zlib);
b_is_zlib.cmp(&a_is_zlib) // zlib first
});
}
Ok(config)
}
#[cfg(not(target_arch = "wasm32"))]
fn apply_http2_settings(
builder: reqwest::ClientBuilder,
http2: &Http2Data,
) -> reqwest::ClientBuilder {
let mut builder = builder;
if let Some(size) = http2.initial_stream_window_size {
builder = builder.http2_initial_stream_window_size(size);
}
if let Some(size) = http2.initial_connection_window_size {
builder = builder.http2_initial_connection_window_size(size);
}
if let Some(max) = http2.max_concurrent_streams {
builder = builder.http2_max_concurrent_streams(max);
}
if let Some(size) = http2.max_frame_size {
builder = builder.http2_max_frame_size(size);
}
if let Some(size) = http2.max_header_list_size {
builder = builder.http2_max_header_list_size(size);
}
if let Some(size) = http2.header_table_size {
builder = builder.http2_header_table_size(size);
}
if let Some(enabled) = http2.enable_push {
builder = builder.http2_enable_push(enabled);
}
if let Some(order) = http2.settings_order.clone() {
builder = builder.http2_settings_order(order);
}
if let Some(order) = http2.headers_pseudo_order.clone() {
builder = builder.http2_headers_pseudo_order(order);
}
if let Some(data) = http2.headers_priority {
builder = builder.http2_headers_priority(Some(data));
}
if let Some(ref order) = http2.headers_order {
builder = builder.http2_headers_order(order.clone());
}
if let Some(enabled) = http2.no_rfc7540_priorities {
builder = builder.http2_no_rfc7540_priorities(enabled);
}
if let Some(val) = http2.enable_connect_protocol {
builder = builder.http2_enable_connect_protocol(if val { 1u32 } else { 0u32 });
}
if let Some(stream_id) = http2.initial_stream_id {
builder = builder.http2_initial_stream_id(stream_id);
}
if let Some(incr) = http2.initial_stream_window_size_increment {
builder = builder.http2_initial_stream_window_size_increment(incr);
}
builder
}
#[cfg(not(target_arch = "wasm32"))]
fn get_ech_grease_config() -> rustls::client::EchGreaseConfig {
use rustls::client::EchGreaseConfig;
use rustls::crypto::aws_lc_rs::hpke::DH_KEM_X25519_HKDF_SHA256_AES_128;
use rustls::crypto::hpke::HpkePublicKey;
use std::sync::OnceLock;
/// GREASE_25519_PUBKEY - placeholder ECH public key for GREASE
const GREASE_25519_PUBKEY: &[u8] = &[
0x67, 0x35, 0xCA, 0x50, 0x21, 0xFC, 0x4F, 0xE6, 0x29, 0x3B, 0x31, 0x2C, 0xB5, 0xE0, 0x97,
0xD8, 0x55, 0x1A, 0x8F, 0x8B, 0xA4, 0x77, 0xAB, 0xFA, 0xBE, 0xA4, 0x53, 0xA3, 0x82, 0x7C,
0x8A, 0x4B,
];
static ECH_GREASE_CONFIG: OnceLock<rustls::client::EchGreaseConfig> = OnceLock::new();
ECH_GREASE_CONFIG
.get_or_init(|| {
EchGreaseConfig::new(
DH_KEM_X25519_HKDF_SHA256_AES_128,
HpkePublicKey(GREASE_25519_PUBKEY.to_vec()),
)
})
.clone()
}