guise 0.1.2

Canonical browser fingerprint bundles, human-behavior timing, and TLS profile re-exports for the Santh fleet
Documentation
/// Enhanced human-like mouse simulation (BiDi/Firefox).
///
/// Extends basic movement with Fitts' Law, overshoots, and persona styles.
use anyhow::Result;
use rand::Rng;
use runtime_foxdriver::browser::Page;
use std::time::Duration;

use crate::choice::chance_with_rng;

// ── MousePersona ──────────────────────────────────────────────────────────

/// Describes the overall mouse behaviour style of a simulated user.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MousePersona {
    /// Moves slowly, hovers before clicking, rarely overshoots.
    Careful,
    /// Balanced speed and accuracy — the default.
    Normal,
    /// Fast movement, sometimes imprecise, clicks quickly.
    Rushed,
    /// Very fast, direct paths, almost no hesitation.
    PowerUser,
}

impl MousePersona {
    fn speed_px_per_sec(&self) -> f64 {
        match self {
            MousePersona::Careful => 300.0,
            MousePersona::Normal => 600.0,
            MousePersona::Rushed => 1_000.0,
            MousePersona::PowerUser => 1_500.0,
        }
    }

    fn overshoot_prob(&self) -> f64 {
        match self {
            MousePersona::Careful => 0.05,
            MousePersona::Normal => 0.12,
            MousePersona::Rushed => 0.25,
            MousePersona::PowerUser => 0.08,
        }
    }

    fn curve_noise_px(&self) -> f64 {
        match self {
            MousePersona::Careful => 10.0,
            MousePersona::Normal => 25.0,
            MousePersona::Rushed => 40.0,
            MousePersona::PowerUser => 15.0,
        }
    }

    fn click_hold_range_ms(&self) -> (u64, u64) {
        match self {
            MousePersona::Careful => (80, 200),
            MousePersona::Normal => (50, 150),
            MousePersona::Rushed => (30, 80),
            MousePersona::PowerUser => (20, 60),
        }
    }

    fn drift_amplitude_px(&self) -> f64 {
        match self {
            MousePersona::Careful => 3.0,
            MousePersona::Normal => 5.0,
            MousePersona::Rushed => 2.0,
            MousePersona::PowerUser => 1.0,
        }
    }
}

// ── HumanMouse ───────────────────────────────────────────────────────────

/// Enhanced mouse that respects Fitts' Law, overshoots, and persona styles.
pub struct HumanMouse {
    persona: MousePersona,
    /// Current horizontal cursor position, tracked locally.
    pub cursor_x: f64,
    /// Current vertical cursor position, tracked locally.
    pub cursor_y: f64,
}

impl HumanMouse {
    /// Create a mouse simulator at the viewport origin.
    pub fn new(persona: MousePersona) -> Self {
        Self {
            persona,
            cursor_x: 0.0,
            cursor_y: 0.0,
        }
    }

    /// Create a mouse simulator with an existing cursor position.
    pub fn with_position(persona: MousePersona, x: f64, y: f64) -> Self {
        Self {
            persona,
            cursor_x: x,
            cursor_y: y,
        }
    }

    /// Move the cursor to `(tx, ty)` with persona-specific curves.
    pub async fn move_to(
        &mut self,
        page: &Page,
        tx: f64,
        ty: f64,
        target_size_px: f64,
    ) -> Result<()> {
        let mut rng = rand::thread_rng();
        let x0 = self.cursor_x;
        let y0 = self.cursor_y;

        let dist = distance(x0, y0, tx, ty).max(1.0);
        let w = target_size_px.max(1.0);
        let fitts_id = (2.0 * dist / w).log2().max(0.5);
        let base_steps = fitts_steps(fitts_id, self.persona.speed_px_per_sec(), dist);
        let steps = base_steps.clamp(6, 40);
        let noise = self.persona.curve_noise_px();

        let cx1 = x0 + (tx - x0) * rng.gen_range(0.2..0.5) + rng.gen_range(-noise..noise);
        let cy1 = y0 + (ty - y0) * rng.gen_range(0.1..0.4) + rng.gen_range(-noise..noise);
        let cx2 = x0 + (tx - x0) * rng.gen_range(0.55..0.85) + rng.gen_range(-noise..noise);
        let cy2 = y0 + (ty - y0) * rng.gen_range(0.5..0.8) + rng.gen_range(-noise..noise);

        for i in 0..=steps {
            let t = i as f64 / steps as f64;
            let u = 1.0 - t;
            let x = cubic_bezier(u, x0, cx1, cx2, tx, t);
            let y = cubic_bezier(u, y0, cy1, cy2, ty, t);

            dispatch_mouse_moved(page, x, y).await?;

            let ease = (std::f64::consts::PI * t).sin();
            let step_ms =
                step_delay_ms(dist, steps, self.persona.speed_px_per_sec(), ease, &mut rng);
            tokio::time::sleep(Duration::from_millis(step_ms)).await;
        }

        // Overshoot on small targets.
        if target_size_px < 20.0 && chance_with_rng(self.persona.overshoot_prob(), &mut rng) {
            let overshoot_px = rng.gen_range(3.0_f64..12.0);
            let angle = (ty - y0).atan2(tx - x0);
            let ox = tx + overshoot_px * angle.cos();
            let oy = ty + overshoot_px * angle.sin();
            dispatch_mouse_moved(page, ox, oy).await?;
            tokio::time::sleep(Duration::from_millis(rng.gen_range(40..100))).await;
            dispatch_mouse_moved(page, tx, ty).await?;
            tokio::time::sleep(Duration::from_millis(rng.gen_range(30..80))).await;
        }

        self.cursor_x = tx;
        self.cursor_y = ty;
        Ok(())
    }

    /// Click at `(x, y)` with persona-specific hold time.
    pub async fn click(&mut self, page: &Page, x: f64, y: f64, target_size_px: f64) -> Result<()> {
        let mut rng = rand::thread_rng();
        self.move_to(page, x, y, target_size_px).await?;
        let (lo, hi) = self.persona.click_hold_range_ms();
        let hold_ms = rng.gen_range(lo..hi);
        page.click_at(x, y).await?;
        tokio::time::sleep(Duration::from_millis(hold_ms)).await;
        Ok(())
    }

    /// Simulate cursor idle drift.
    pub async fn idle_drift(
        &mut self,
        page: &Page,
        duration: Duration,
        interval_ms: u64,
    ) -> Result<()> {
        let mut rng = rand::thread_rng();
        let ticks = (duration.as_millis() / interval_ms.max(1) as u128) as u32;
        let amp = self.persona.drift_amplitude_px();

        for _ in 0..ticks {
            let dx = rng.gen_range(-amp..amp);
            let dy = rng.gen_range(-amp..amp);
            let nx = (self.cursor_x + dx).max(0.0);
            let ny = (self.cursor_y + dy).max(0.0);
            dispatch_mouse_moved(page, nx, ny).await?;
            self.cursor_x = nx;
            self.cursor_y = ny;
            tokio::time::sleep(Duration::from_millis(interval_ms)).await;
        }
        Ok(())
    }
}

// ── helpers ───────────────────────────────────────────────────────────────

fn distance(x0: f64, y0: f64, x1: f64, y1: f64) -> f64 {
    ((x1 - x0).powi(2) + (y1 - y0).powi(2)).sqrt()
}

fn fitts_steps(fitts_id: f64, speed_px_s: f64, dist_px: f64) -> usize {
    let mt_ms = (dist_px / speed_px_s * 1000.0) * (1.0 + fitts_id * 0.3);
    (mt_ms / 16.0).round() as usize
}

fn step_delay_ms<R: Rng>(dist: f64, steps: usize, speed_px_s: f64, ease: f64, rng: &mut R) -> u64 {
    let total_ms = dist / speed_px_s * 1000.0;
    let avg_ms = (total_ms / steps as f64).max(4.0);
    let adjusted = avg_ms * (1.5 - ease * 0.5);
    let jitter: f64 = rng.gen_range(-3.0..3.0);
    (adjusted + jitter).clamp(4.0, 60.0) as u64
}

fn cubic_bezier(u: f64, p0: f64, p1: f64, p2: f64, p3: f64, t: f64) -> f64 {
    u * u * u * p0 + 3.0 * u * u * t * p1 + 3.0 * u * t * t * p2 + t * t * t * p3
}

async fn dispatch_mouse_moved(page: &Page, x: f64, y: f64) -> Result<()> {
    // TRUSTED dispatch. A synthetic `document.dispatchEvent(new
    // MouseEvent('mousemove', …))` arrives with `isTrusted === false` — the
    // single cheapest tell an anti-bot scorer has, which would nullify this
    // whole Fitts-law / persona trajectory. Route the point through the real
    // BiDi pointer-move path so every sampled move is indistinguishable from a
    // hardware mouse and reaches cross-origin frames.
    page.move_mouse_to(x, y).await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn power_user_faster_than_careful() {
        assert!(
            MousePersona::PowerUser.speed_px_per_sec() > MousePersona::Careful.speed_px_per_sec()
        );
    }

    #[test]
    fn rushed_has_highest_overshoot() {
        assert!(MousePersona::Rushed.overshoot_prob() > MousePersona::Careful.overshoot_prob());
    }

    #[test]
    fn careful_has_smallest_noise() {
        assert!(MousePersona::Careful.curve_noise_px() < MousePersona::Rushed.curve_noise_px());
    }

    #[test]
    fn click_hold_lo_lt_hi() {
        for persona in [
            MousePersona::Careful,
            MousePersona::Normal,
            MousePersona::Rushed,
            MousePersona::PowerUser,
        ] {
            let (lo, hi) = persona.click_hold_range_ms();
            assert!(lo < hi, "{persona:?}: hold range lo {lo} >= hi {hi}");
        }
    }

    #[test]
    fn all_personas_have_positive_drift() {
        for persona in [
            MousePersona::Careful,
            MousePersona::Normal,
            MousePersona::Rushed,
            MousePersona::PowerUser,
        ] {
            assert!(persona.drift_amplitude_px() > 0.0);
        }
    }

    #[test]
    fn fitts_steps_increases_with_distance() {
        let steps_near = fitts_steps(1.0, 600.0, 50.0);
        let steps_far = fitts_steps(1.0, 600.0, 500.0);
        assert!(steps_far > steps_near);
    }

    #[test]
    fn bezier_at_t0_equals_p0() {
        let v = cubic_bezier(1.0, 100.0, 200.0, 300.0, 400.0, 0.0);
        assert!((v - 100.0).abs() < 1e-6);
    }

    #[test]
    fn bezier_at_t1_equals_p3() {
        let v = cubic_bezier(0.0, 100.0, 200.0, 300.0, 400.0, 1.0);
        assert!((v - 400.0).abs() < 1e-6);
    }

    #[test]
    fn distance_3_4_5_triangle() {
        let d = distance(0.0, 0.0, 3.0, 4.0);
        assert!((d - 5.0).abs() < 1e-6);
    }

    #[test]
    fn new_mouse_starts_at_origin() {
        let m = HumanMouse::new(MousePersona::Normal);
        assert_eq!(m.cursor_x, 0.0);
        assert_eq!(m.cursor_y, 0.0);
    }
}