eoka 0.14.3

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
Documentation
//! Evasion scripts to bypass bot detection
//!
//! These scripts are injected before any page content loads to patch
//! detectable browser properties.

use crate::stealth::fingerprint::{Fingerprint, GENERIC_FONTS};
use crate::StealthConfig;

/// Prelude: native-function masking (`_eoka_mark`), the shared prototype patch
/// helpers (`_eoka_patchMethod`/`_eoka_patchGetter`/`_eoka_instance`) and the
/// noise PRNG step (`_eoka_lcg`).
pub const NATIVE_TOSTRING_EVASION: &str = include_str!("evasions/scripts/native_tostring.js");

/// Navigator properties (languages, platform, hardware) filled from the fingerprint.
pub const NAVIGATOR_PROPS_EVASION: &str = include_str!("evasions/scripts/navigator_props.js");

/// Battery API fix - Proxy over the real BatteryManager with spoofed values.
pub const BATTERY_EVASION: &str = include_str!("evasions/scripts/battery.js");

/// WebGL vendor/renderer spoof, gated by `StealthConfig::fingerprint_spoofing`.
pub const WEBGL_EVASION: &str = include_str!("evasions/scripts/webgl.js");

/// Worker navigator values matching the page's.
pub(crate) const WORKER_PROPS_EVASION: &str = include_str!("evasions/scripts/worker_props.js");

/// Canvas readback/export noise, gated by `StealthConfig::fingerprint_spoofing`.
pub const CANVAS_EVASION: &str = include_str!("evasions/scripts/canvas.js");

/// Audio buffer noise, gated by `StealthConfig::fingerprint_spoofing`.
pub const AUDIO_EVASION: &str = include_str!("evasions/scripts/audio.js");

/// Combined fingerprint evasion (WebGL + Canvas + Audio).
pub const FINGERPRINT_EVASION: &str = concat!(
    include_str!("evasions/scripts/webgl.js"),
    include_str!("evasions/scripts/canvas.js"),
    include_str!("evasions/scripts/audio.js"),
);

/// Speech synthesis - headless Chrome has 0 voices, real Chrome has many.
/// The fallback list is fingerprint data (`__EOKA_SPEECH_VOICES__`, JSON):
/// platform-aware and stable per identity.
pub const SPEECH_EVASION: &str = include_str!("evasions/scripts/speech.js");

/// Media devices - headless returns empty array. The fake device list is
/// fingerprint data (`__EOKA_MEDIA_DEVICES__`, JSON) derived from the noise
/// seed, so IDs are stable per identity and never shared across sessions.
pub const MEDIA_DEVICES_EVASION: &str = include_str!("evasions/scripts/media_devices.js");

/// Bluetooth API - only filled on platforms whose Chrome ships Web Bluetooth.
/// Stock Linux Chrome exposes no `navigator.bluetooth`, so claiming it on a
/// Linux identity is a platform tell; the script leaves that platform untouched.
pub const BLUETOOTH_EVASION: &str = include_str!("evasions/scripts/bluetooth.js");

/// System-font probing via `document.fonts.check(font, text)`: stock Chrome
/// resolves installed system fonts, so detectors enumerate font names through
/// it. Only the identity's claimed fonts (plus CSS generic families) resolve;
/// everything else reports missing. The claimed set is fingerprint data
/// (`__EOKA_FONTS__`, JSON array).
pub const FONTS_EVASION: &str = include_str!("evasions/scripts/fonts.js");

/// `navigator.keyboard.getLayoutMap()` — stock Chrome exposes the Keyboard
/// API on Windows/macOS/ChromeOS but not Linux, so Linux passes through.
/// The map is fingerprint data (`__EOKA_KEYBOARD_MAP__`, JSON or null):
/// US ANSI, matching the identity's en-US locale.
pub const KEYBOARD_EVASION: &str = include_str!("evasions/scripts/keyboard.js");

/// Build the complete evasion script for the given config and fingerprint.
pub fn build_evasion_script_for(config: &StealthConfig, fp: &Fingerprint) -> String {
    let mut scripts = vec![
        NATIVE_TOSTRING_EVASION, // must be first: defines the _eoka_* helpers
        NAVIGATOR_PROPS_EVASION,
        BATTERY_EVASION,
        SPEECH_EVASION,
        MEDIA_DEVICES_EVASION,
        FONTS_EVASION,
        KEYBOARD_EVASION,
        BLUETOOTH_EVASION,
    ];

    if config.fingerprint_spoofing {
        scripts.extend([WEBGL_EVASION, CANVAS_EVASION, AUDIO_EVASION]);
    }

    fill_placeholders(&format!("(function(){{{}}})();", scripts.join("\n")), fp)
}

/// The evasions that apply inside a dedicated worker: the shared prelude,
/// WorkerNavigator values and (when enabled) WebGL and canvas noise on
/// `OffscreenCanvas`.
pub(crate) fn build_worker_evasion_script(config: &StealthConfig, fp: &Fingerprint) -> String {
    let mut scripts = vec![NATIVE_TOSTRING_EVASION, WORKER_PROPS_EVASION];
    if config.fingerprint_spoofing {
        scripts.extend([WEBGL_EVASION, CANVAS_EVASION]);
    }
    fill_placeholders(&format!("(function(){{{}}})();", scripts.join("\n")), fp)
}

/// Escape a string for safe use in JavaScript string literals (single pass).
fn escape_js_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(ch) = chars.next() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '\'' => out.push_str("\\'"),
            '"' => out.push_str("\\\""),
            '`' => out.push_str("\\`"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\0' => out.push_str("\\x00"),
            '\u{2028}' => out.push_str("\\u2028"),
            '\u{2029}' => out.push_str("\\u2029"),
            '$' if chars.peek() == Some(&'{') => {
                out.push_str("\\${");
                chars.next();
            }
            _ => out.push(ch),
        }
    }
    out
}

fn fill_placeholders(script: &str, fp: &Fingerprint) -> String {
    let languages_json = format!(
        "[{}]",
        fp.languages
            .iter()
            .map(|l| format!("'{}'", escape_js_string(l)))
            .collect::<Vec<_>>()
            .join(",")
    );
    let language = fp.languages.first().cloned().unwrap_or_default();
    let noise_seed = fp.noise_seed;

    // Single fill-point: every placeholder value comes from the fingerprint
    // (or config). No placeholder may survive this fold — guarded by
    // `test_placeholders_are_filled`.
    let placeholders: Vec<(&str, String)> = vec![
        ("__EOKA_PLATFORM__", escape_js_string(fp.nav_platform())),
        ("__EOKA_LANGUAGES__", languages_json),
        ("__EOKA_LANGUAGE__", escape_js_string(&language)),
        ("__EOKA_MEM__", fp.device_memory.to_string()),
        ("__EOKA_WEBGL_VENDOR__", escape_js_string(&fp.webgl_vendor)),
        (
            "__EOKA_WEBGL_RENDERER__",
            escape_js_string(&fp.webgl_renderer),
        ),
        ("__EOKA_NOISE_SEED__", noise_seed.to_string()),
        (
            "__EOKA_SPEECH_VOICES__",
            serde_json::to_string(&fp.voices).unwrap_or_else(|_| "[]".to_string()),
        ),
        ("__EOKA_MEDIA_DEVICES__", fp.media_devices_json()),
        (
            "__EOKA_FONTS__",
            serde_json::to_string(&fp.fonts).unwrap_or_else(|_| "[]".to_string()),
        ),
        (
            "__EOKA_GENERIC_FONTS__",
            serde_json::to_string(GENERIC_FONTS).unwrap_or_else(|_| "[]".to_string()),
        ),
        ("__EOKA_KEYBOARD_MAP__", fp.keyboard_map_json()),
    ];
    placeholders
        .into_iter()
        .fold(script.to_owned(), |acc, (placeholder, value)| {
            acc.replace(placeholder, &value)
        })
}

/// Build the complete evasion script based on config.
pub fn build_evasion_script(config: &StealthConfig) -> String {
    let fp = Fingerprint::resolve(config.user_agent.as_deref(), config.timezone.as_deref());
    build_evasion_script_for(config, &fp)
}

#[cfg(test)]
mod tests;