#[cfg(feature = "tier-b-toml")]
use std::path::Path;
use thiserror::Error;
use super::profiles::{profile_to_overrides, StealthProfile, DEFAULT_STEALTH_PROFILE};
#[cfg(feature = "http")]
use crate::fingerprint::tls_profiles::{
default_impersonate_profile_for_stealth_profile, impersonate_profile_matches_stealth_profile,
};
#[cfg(feature = "http")]
use scanclient::tls_impersonate::ImpersonateProfile;
#[cfg(feature = "tier-b-toml")]
use guise_profiles as profile_catalog;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProfileBundle {
pub browser: StealthProfile,
#[cfg(feature = "http")]
pub tls: ImpersonateProfile,
}
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ProfileError {
#[error("profile bundle is internally inconsistent: {0}")]
Incoherent(String),
#[error("failed to read profile TOML: {0}")]
#[cfg(feature = "tier-b-toml")]
TomlRead(String),
#[error("failed to parse profile TOML: {0}")]
#[cfg(feature = "tier-b-toml")]
TomlParse(String),
}
impl ProfileBundle {
#[must_use]
pub fn for_browser(browser: StealthProfile) -> Self {
Self {
browser,
#[cfg(feature = "http")]
tls: default_impersonate_profile_for_stealth_profile(browser),
}
}
#[must_use]
pub fn default_stealth() -> Self {
Self::for_browser(DEFAULT_STEALTH_PROFILE)
}
#[must_use]
pub fn chrome_131_macos() -> Self {
Self::for_browser(StealthProfile::ChromeMacStable)
}
#[must_use]
pub fn chrome_131_windows() -> Self {
Self::for_browser(StealthProfile::ChromeWindowsStable)
}
#[must_use]
pub fn firefox_133() -> Self {
Self::for_browser(StealthProfile::FirefoxLinux)
}
#[must_use]
pub fn firefox_133_windows() -> Self {
Self::for_browser(StealthProfile::FirefoxWindows)
}
#[must_use]
pub fn safari_17_5() -> Self {
Self::for_browser(StealthProfile::SafariMacStable)
}
#[must_use]
pub fn edge_131() -> Self {
Self::for_browser(StealthProfile::EdgeWindowsStable)
}
pub fn validate_browser_coherence(&self) -> Result<(), ProfileError> {
validate_overrides(&profile_to_overrides(&self.browser))
}
#[cfg(feature = "http")]
pub fn validate_full_coherence(&self) -> Result<(), ProfileError> {
self.validate_browser_coherence()?;
validate_tls_family(self.browser, self.tls)
}
#[cfg(feature = "tier-b-toml")]
pub fn from_toml(path: &Path) -> Result<Self, ProfileError> {
let raw = std::fs::read_to_string(path)
.map_err(|e| ProfileError::TomlRead(format!("{}: {e}", path.display())))?;
let doc: TierBProfileDoc =
toml::from_str(&raw).map_err(|e| ProfileError::TomlParse(e.to_string()))?;
let browser = profile_catalog::named_profile(&doc.browser).ok_or_else(|| {
ProfileError::TomlParse(format!("unknown browser profile {}", doc.browser))
})?;
#[cfg(feature = "http")]
let tls = ImpersonateProfile::parse(&doc.tls)
.map_err(|e| ProfileError::TomlParse(e.to_string()))?;
let bundle = Self {
browser,
#[cfg(feature = "http")]
tls,
};
#[cfg(feature = "http")]
bundle.validate_full_coherence()?;
#[cfg(not(feature = "http"))]
bundle.validate_browser_coherence()?;
Ok(bundle)
}
}
pub fn validate_overrides(ov: &super::profiles::ProfileOverrides) -> Result<(), ProfileError> {
if ov.user_agent.contains("Windows") && ov.platform != "Win32" {
return Err(ProfileError::Incoherent(format!(
"UA claims Windows but platform is {}",
ov.platform
)));
}
let ios_ua = ov.user_agent.contains("iPhone") || ov.user_agent.contains("iPad");
if ov.user_agent.contains("Mac OS X") && !ios_ua && ov.platform != "MacIntel" {
return Err(ProfileError::Incoherent(format!(
"UA claims macOS desktop but platform is {}",
ov.platform
)));
}
if ov.user_agent.contains("Android") && !ov.mobile {
return Err(ProfileError::Incoherent(
"Android UA requires mobile=true".into(),
));
}
let chromium_ua = ov.user_agent.contains("Chrome/") || ov.user_agent.contains("Chromium");
if chromium_ua && !ov.user_agent.contains("Firefox/") && ov.brands.is_empty() {
return Err(ProfileError::Incoherent(
"Chromium UA without userAgentData brands".into(),
));
}
if ov.user_agent.contains("Firefox/") && !ov.brands.is_empty() {
return Err(ProfileError::Incoherent(
"Firefox UA must not ship Client Hints brands".into(),
));
}
validate_brand_versions(ov)?;
Ok(())
}
fn validate_brand_versions(ov: &super::profiles::ProfileOverrides) -> Result<(), ProfileError> {
for (brand, version) in &ov.brands {
if !version.chars().all(|c| c.is_ascii_digit()) {
return Err(ProfileError::Incoherent(format!(
"Client Hint brand {brand:?} has non-numeric version {version:?}"
)));
}
let Some(expected) = expected_brand_major(&ov.user_agent, brand) else {
continue;
};
if version != expected {
return Err(ProfileError::Incoherent(format!(
"Client Hint brand {brand:?} version {version} does not match UA major {expected}"
)));
}
}
Ok(())
}
fn expected_brand_major<'a>(ua: &'a str, brand: &str) -> Option<&'a str> {
match brand {
"Chromium" | "Google Chrome" | "Brave" => major_after(ua, "Chrome/"),
"Microsoft Edge" => major_after(ua, "Edg/"),
"Opera" => major_after(ua, "OPR/"),
"Samsung Internet" => major_after(ua, "SamsungBrowser/"),
_ => None,
}
}
fn major_after<'a>(ua: &'a str, token: &str) -> Option<&'a str> {
let after = ua.split_once(token)?.1;
let major = after.split('.').next().unwrap_or(after);
if major.is_empty() {
None
} else {
Some(major)
}
}
#[cfg(feature = "http")]
fn validate_tls_family(
browser: StealthProfile,
tls: ImpersonateProfile,
) -> Result<(), ProfileError> {
if impersonate_profile_matches_stealth_profile(browser, tls) {
Ok(())
} else {
Err(ProfileError::Incoherent(format!(
"browser profile {browser:?} incompatible with TLS profile {tls:?}"
)))
}
}
#[cfg(feature = "tier-b-toml")]
#[derive(Debug, serde::Deserialize)]
struct TierBProfileDoc {
browser: String,
tls: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bundled_profiles_pass_full_coherence() {
for bundle in [
ProfileBundle::default_stealth(),
ProfileBundle::chrome_131_macos(),
ProfileBundle::chrome_131_windows(),
ProfileBundle::firefox_133(),
ProfileBundle::firefox_133_windows(),
ProfileBundle::safari_17_5(),
ProfileBundle::edge_131(),
] {
bundle.validate_browser_coherence().unwrap();
#[cfg(feature = "http")]
bundle.validate_full_coherence().unwrap();
}
}
#[test]
fn detect_incoherent_windows_platform() {
let mut ov = profile_to_overrides(&StealthProfile::ChromeWindowsStable);
ov.platform = "MacIntel".into();
assert!(validate_overrides(&ov).is_err());
}
#[cfg(all(feature = "tier-b-toml", feature = "http"))]
#[test]
fn tier_b_toml_browser_aliases_use_shared_profile_catalog() {
let path =
std::env::temp_dir().join(format!("stealth-tier-b-alias-{}.toml", std::process::id()));
std::fs::write(&path, "browser = \"chrome-win\"\ntls = \"chrome131\"\n")
.expect("write tier-b alias fixture");
let bundle = ProfileBundle::from_toml(&path).expect("shared alias should parse");
assert_eq!(bundle.browser, StealthProfile::ChromeWindowsStable);
assert_eq!(bundle.tls, ImpersonateProfile::Chrome131);
let _ = std::fs::remove_file(path);
}
#[test]
fn default_stealth_bundle_uses_catalog_default_profile() {
assert_eq!(
ProfileBundle::default_stealth().browser,
DEFAULT_STEALTH_PROFILE
);
}
}