guise 0.1.2

Canonical browser fingerprint bundles, human-behavior timing, and TLS profile re-exports for the Santh fleet
Documentation
//! Browser session coherence primitives for HTTP stealth transports.
//!
//! User-Agent, request-header order, HTTP/2 SETTINGS, and per-host profile
//! rotation have to agree. A Chrome user agent paired with Firefox header
//! order is still fingerprintable even when each individual layer looks
//! browser-shaped.

use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::RwLock;

use crate::fingerprint::StealthProfile;
use crate::fingerprint::browser_catalog::HeaderProfile;
use crate::rotation::named_profile;

/// Canonical request-header insertion order for one browser family.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HeaderOrder {
    /// Family name: `"chrome"`, `"firefox"`, or `"safari"`.
    pub family: &'static str,
    /// Header names in the order a browser writes them on navigation requests.
    pub slots: &'static [&'static str],
}

/// Chromium and Edge canonical navigation request-header order.
pub const CHROME_HEADER_ORDER: HeaderOrder = HeaderOrder {
    family: "chrome",
    slots: &[
        "host",
        "connection",
        "cache-control",
        "sec-ch-ua",
        "sec-ch-ua-mobile",
        "sec-ch-ua-platform",
        "upgrade-insecure-requests",
        "user-agent",
        "accept",
        "sec-fetch-site",
        "sec-fetch-mode",
        "sec-fetch-user",
        "sec-fetch-dest",
        "accept-encoding",
        "accept-language",
        "cookie",
    ],
};

/// Firefox canonical navigation request-header order.
pub const FIREFOX_HEADER_ORDER: HeaderOrder = HeaderOrder {
    family: "firefox",
    slots: &[
        "host",
        "user-agent",
        "accept",
        "accept-language",
        "accept-encoding",
        "connection",
        "upgrade-insecure-requests",
        "sec-fetch-dest",
        "sec-fetch-mode",
        "sec-fetch-site",
        "sec-fetch-user",
        "cookie",
    ],
};

/// Safari canonical navigation request-header order.
pub const SAFARI_HEADER_ORDER: HeaderOrder = HeaderOrder {
    family: "safari",
    slots: &[
        "host",
        "accept",
        "accept-encoding",
        "connection",
        "user-agent",
        "accept-language",
        "cookie",
    ],
};

/// HTTP/2 SETTINGS frame values, order, and initial connection window update.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct H2Profile {
    /// Family name; same vocabulary as [`HeaderOrder::family`].
    pub family: &'static str,
    /// `(setting_id, value)` in browser emit order.
    pub settings: &'static [(u16, u32)],
    /// Initial connection window-size increment sent after SETTINGS.
    pub initial_window_increment: u32,
}

/// Chrome and Edge HTTP/2 SETTINGS profile.
pub const CHROME_H2: H2Profile = H2Profile {
    family: "chrome",
    settings: &[(1, 65_536), (2, 0), (4, 6_291_456), (6, 262_144)],
    initial_window_increment: 15_663_105,
};

/// Firefox HTTP/2 SETTINGS profile.
pub const FIREFOX_H2: H2Profile = H2Profile {
    family: "firefox",
    settings: &[(1, 65_536), (4, 131_072), (5, 16_384)],
    initial_window_increment: 12_517_377,
};

/// Safari HTTP/2 SETTINGS profile.
pub const SAFARI_H2: H2Profile = H2Profile {
    family: "safari",
    settings: &[(3, 100), (4, 2_097_152), (8, 1)],
    initial_window_increment: 10_485_760,
};

/// Resolve the coherent `(HeaderOrder, H2Profile)` pair for a canonical browser profile.
#[must_use]
pub fn pair_for_profile(profile: StealthProfile) -> Option<(HeaderOrder, H2Profile)> {
    match profile {
        StealthProfile::ChromeWindowsStable
        | StealthProfile::ChromeWindowsLegacy96
        | StealthProfile::ChromeMacStable
        | StealthProfile::EdgeWindowsStable
        | StealthProfile::ChromeAndroid
        | StealthProfile::ChromeLinux
        | StealthProfile::BraveWindows
        | StealthProfile::OperaWindows
        | StealthProfile::SamsungInternetAndroid => Some((CHROME_HEADER_ORDER, CHROME_H2)),
        StealthProfile::FirefoxLinux | StealthProfile::FirefoxWindows => {
            Some((FIREFOX_HEADER_ORDER, FIREFOX_H2))
        }
        StealthProfile::SafariIphone
        | StealthProfile::SafariIpad
        | StealthProfile::SafariMacStable => Some((SAFARI_HEADER_ORDER, SAFARI_H2)),
        StealthProfile::Ie11Windows => None,
        _ => None,
    }
}

/// Resolve the coherent `(HeaderOrder, H2Profile)` pair for a browser alias.
#[must_use]
pub fn pair_for_name(name: &str) -> Option<(HeaderOrder, H2Profile)> {
    let key = name.to_ascii_lowercase();
    if let Some(profile) = named_profile(&key) {
        if let Some(pair) = pair_for_profile(profile) {
            return Some(pair);
        }
    }

    if key.starts_with("chrome") || key.starts_with("edge") {
        return Some((CHROME_HEADER_ORDER, CHROME_H2));
    }
    if key.starts_with("firefox") {
        return Some((FIREFOX_HEADER_ORDER, FIREFOX_H2));
    }
    if key.starts_with("safari") {
        return Some((SAFARI_HEADER_ORDER, SAFARI_H2));
    }
    None
}

impl HeaderOrder {
    /// Reshape a header bag to this browser family's canonical insertion order.
    ///
    /// Slot matching is case-insensitive, caller casing is preserved, duplicate
    /// headers retain relative order, and non-slot headers are appended in input
    /// order after the browser-shaped block.
    #[must_use]
    pub fn apply_in_order(&self, headers: Vec<(String, String)>) -> Vec<(String, String)> {
        let mut by_name: HashMap<String, Vec<(String, String)>> = HashMap::new();
        let mut input_order: Vec<String> = Vec::new();
        for (name, value) in headers {
            let lower = name.to_ascii_lowercase();
            input_order.push(lower.clone());
            by_name.entry(lower).or_default().push((name, value));
        }

        let mut out = Vec::new();
        let mut consumed = HashSet::new();
        for slot in self.slots {
            let slot_lower = slot.to_ascii_lowercase();
            if let Some(entries) = by_name.remove(&slot_lower) {
                out.extend(entries);
                consumed.insert(slot_lower);
            }
        }

        let mut seen = HashSet::new();
        for lower in input_order {
            if consumed.contains(&lower) || !seen.insert(lower.clone()) {
                continue;
            }
            if let Some(entries) = by_name.remove(&lower) {
                out.extend(entries);
            }
        }
        out
    }
}

/// Per-host browser profile assignment with bounded session lifetime.
pub struct SessionPool {
    profiles: Vec<&'static HeaderProfile>,
    rotate_after_requests: u32,
    bindings: RwLock<HashMap<String, (usize, u32)>>,
    cursor: AtomicUsize,
}

impl SessionPool {
    /// Build a pool over the given browser profiles.
    ///
    /// A zero rotation window is coerced to one so the API stays total.
    ///
    /// # Panics
    ///
    /// Panics if `profiles` is empty.
    #[must_use]
    pub fn new(profiles: Vec<&'static HeaderProfile>, rotate_after_requests: u32) -> Self {
        assert!(
            !profiles.is_empty(),
            "SessionPool::new requires at least one profile"
        );
        Self {
            profiles,
            rotate_after_requests: rotate_after_requests.max(1),
            bindings: RwLock::new(HashMap::new()),
            cursor: AtomicUsize::new(0),
        }
    }

    /// Return the browser profile assigned to `host` for the current window.
    pub fn profile_for(&self, host: &str) -> &'static HeaderProfile {
        debug_assert!(!self.profiles.is_empty());

        let mut bindings = self
            .bindings
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if let Some(entry) = bindings.get_mut(host) {
            let (idx, count) = *entry;
            if count.saturating_add(1) < self.rotate_after_requests {
                entry.1 += 1;
                return self.profiles[idx];
            }
        }

        let idx = self.cursor.fetch_add(1, Ordering::Relaxed) % self.profiles.len();
        bindings.insert(host.to_string(), (idx, 1));
        self.profiles[idx]
    }

    /// Forget every host binding.
    pub fn clear(&self) {
        self.bindings
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clear();
    }

    /// Snapshot of `(host, profile_name, request_count)`.
    #[must_use]
    pub fn snapshot(&self) -> Vec<(String, &'static str, u32)> {
        let bindings = self
            .bindings
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        bindings
            .iter()
            .map(|(host, (idx, count))| (host.clone(), self.profiles[*idx].name, *count))
            .collect()
    }
}

#[cfg(test)]
#[path = "session_coherence/tests.rs"]
mod tests;