guise 0.1.2

Canonical browser fingerprint bundles, human-behavior timing, and TLS profile re-exports for the Santh fleet
Documentation
//! Human-like scroll simulation with momentum physics (lifted from archived
//! golemn-browser).
//!
//! Models:
//! - Flick scrolling: initial velocity decays via a friction coefficient.
//! - Variable scroll amounts (not uniform steps) via a Dirichlet-like split.
//! - Occasional overshoot + correction.
//! - Behaviour modes: Reading, Scanning, Searching, Idle — each with a distinct
//!   velocity / friction / overshoot / cadence profile.
//!
//! This is the fleet's canonical scroll engine; [`super::behavior::scroll_realistic`]
//! is a thin convenience wrapper that routes through [`HumanScroller`]. Requires
//! the `browser` feature (drives a [`runtime_foxdriver::Page`]).

use anyhow::Result;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use runtime_foxdriver::Page;
use std::time::Duration;

use crate::choice::chance_with_rng;

// ── ScrollBehavior ────────────────────────────────────────────────────────

/// Describes the user's intent while scrolling — each mode produces
/// a distinct velocity/cadence profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollBehavior {
    /// Slow, steady downward scroll while reading line by line.
    Reading,
    /// Moderate speed, skimming sections.
    Scanning,
    /// Fast scroll looking for a specific piece of content.
    Searching,
    /// Occasional small movements, mostly paused.
    Idle,
}

impl ScrollBehavior {
    /// Initial flick velocity in px (mean).
    fn base_velocity(self) -> f64 {
        match self {
            ScrollBehavior::Reading => 80.0,
            ScrollBehavior::Scanning => 200.0,
            ScrollBehavior::Searching => 420.0,
            ScrollBehavior::Idle => 30.0,
        }
    }

    /// Friction coefficient per tick (0–1; higher = stops faster).
    fn friction(self) -> f64 {
        match self {
            ScrollBehavior::Reading => 0.72,
            ScrollBehavior::Scanning => 0.65,
            ScrollBehavior::Searching => 0.55,
            ScrollBehavior::Idle => 0.80,
        }
    }

    /// Probability of overshoot on a given flick (0–1).
    fn overshoot_probability(self) -> f64 {
        match self {
            ScrollBehavior::Reading => 0.05,
            ScrollBehavior::Scanning => 0.12,
            ScrollBehavior::Searching => 0.20,
            ScrollBehavior::Idle => 0.02,
        }
    }

    /// Inter-flick pause range (ms).
    fn pause_range_ms(self) -> (u64, u64) {
        match self {
            ScrollBehavior::Reading => (600, 2000),
            ScrollBehavior::Scanning => (200, 700),
            ScrollBehavior::Searching => (50, 200),
            ScrollBehavior::Idle => (2000, 8000),
        }
    }
}

// ── HumanScroller ────────────────────────────────────────────────────────

/// Configures the scroller.
#[derive(Debug, Clone)]
pub struct HumanScrollConfig {
    /// Total pixel distance to scroll over the session.
    pub total_px: i32,
    /// How the user intends to scroll.
    pub behavior: ScrollBehavior,
    /// Number of flick gestures to spread the total distance across.
    pub flick_count: usize,
    /// Whether scrolling is predominantly downward (`true`) or upward.
    pub scroll_down: bool,
}

impl Default for HumanScrollConfig {
    fn default() -> Self {
        Self {
            total_px: 800,
            behavior: ScrollBehavior::Reading,
            flick_count: 5,
            scroll_down: true,
        }
    }
}

/// Human-like scroller driving a [`runtime_foxdriver::Page`] with momentum physics.
pub struct HumanScroller {
    config: HumanScrollConfig,
}

impl HumanScroller {
    /// Build a scroller from a [`HumanScrollConfig`].
    #[must_use]
    pub fn new(config: HumanScrollConfig) -> Self {
        Self { config }
    }

    /// Perform a full scroll session on `page` matching the configured behaviour.
    ///
    /// # Errors
    ///
    /// Returns any error raised while evaluating the `window.scrollBy` calls on
    /// the page.
    pub async fn scroll(&self, page: &Page) -> Result<()> {
        // Send-safe RNG so the future stays `Send` across the await points.
        let mut rng = StdRng::from_entropy();
        let direction: f64 = if self.config.scroll_down { 1.0 } else { -1.0 };

        // Distribute the total distance unevenly across flicks.
        let flick_amounts = self.distribute_flicks(&mut rng);

        for flick_px in flick_amounts {
            self.execute_flick(page, flick_px * direction, &mut rng)
                .await?;

            // Possible overshoot + correction.
            if chance_with_rng(self.config.behavior.overshoot_probability(), &mut rng) {
                let overshoot = rng.gen_range(30..120) as f64 * direction;
                Self::scroll_by(page, overshoot).await?;
                tokio::time::sleep(Duration::from_millis(rng.gen_range(100..300))).await;
                // Scroll back ~60-90 % of the overshoot.
                let correction = overshoot * rng.gen_range(0.6_f64..0.9);
                Self::scroll_by(page, -correction).await?;
                tokio::time::sleep(Duration::from_millis(rng.gen_range(80..200))).await;
            }

            // Pause between flicks.
            let (lo, hi) = self.config.behavior.pause_range_ms();
            let pause = rng.gen_range(lo..hi);
            tokio::time::sleep(Duration::from_millis(pause)).await;
        }

        Ok(())
    }

    /// Execute a single flick: initial velocity decays by friction each tick.
    async fn execute_flick<R: Rng + ?Sized>(
        &self,
        page: &Page,
        target_px: f64,
        rng: &mut R,
    ) -> Result<()> {
        let friction = self.config.behavior.friction();
        let base_v = self.config.behavior.base_velocity();
        // Jitter the initial velocity ±20 %.
        let mut velocity = base_v * (1.0 + rng.gen_range(-0.20_f64..0.20)) * target_px.signum();

        let mut remaining = target_px.abs();
        let tick_ms: u64 = rng.gen_range(16..32); // ~30-60 fps

        while remaining > 1.0 && velocity.abs() > 1.0 {
            let step = velocity.abs().min(remaining);
            Self::scroll_by(page, step * target_px.signum()).await?;
            remaining -= step;
            velocity *= friction;
            // Add tiny noise per tick so velocity decay isn't perfectly smooth.
            velocity += rng.gen_range(-2.0_f64..2.0);
            tokio::time::sleep(Duration::from_millis(tick_ms)).await;
        }

        Ok(())
    }

    /// Distribute `total_px` among `flick_count` flicks using a Dirichlet-like
    /// random split: produces unequal amounts summing to `total_px`.
    fn distribute_flicks<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec<f64> {
        let n = self.config.flick_count.max(1);
        // Draw exponential-ish weights.
        let weights: Vec<f64> = (0..n)
            .map(|_| {
                let u: f64 = rng.gen::<f64>().max(1e-12);
                -u.ln() // exponential distribution
            })
            .collect();
        let total_w: f64 = weights.iter().sum();
        weights
            .iter()
            .map(|w| (w / total_w) * f64::from(self.config.total_px))
            .collect()
    }

    /// Fire a `window.scrollBy(0, dy)` JS call.
    async fn scroll_by(page: &Page, dy: f64) -> Result<()> {
        let js = format!("window.scrollBy(0, {dy:.1})");
        page.evaluate(js).await?;
        Ok(())
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    // ── ScrollBehavior parameter contracts ──────────────────────────────

    #[test]
    fn searching_faster_than_reading() {
        assert!(
            ScrollBehavior::Searching.base_velocity() > ScrollBehavior::Reading.base_velocity()
        );
    }

    #[test]
    fn idle_slowest_velocity() {
        assert!(ScrollBehavior::Idle.base_velocity() < ScrollBehavior::Reading.base_velocity());
    }

    #[test]
    fn friction_between_zero_and_one() {
        for b in [
            ScrollBehavior::Reading,
            ScrollBehavior::Scanning,
            ScrollBehavior::Searching,
            ScrollBehavior::Idle,
        ] {
            let f = b.friction();
            assert!(
                (0.0..=1.0).contains(&f),
                "friction {f} out of range for {b:?}"
            );
        }
    }

    #[test]
    fn searching_lowest_friction() {
        assert!(ScrollBehavior::Searching.friction() < ScrollBehavior::Reading.friction());
    }

    #[test]
    fn overshoot_probability_valid() {
        for b in [
            ScrollBehavior::Reading,
            ScrollBehavior::Scanning,
            ScrollBehavior::Searching,
            ScrollBehavior::Idle,
        ] {
            let p = b.overshoot_probability();
            assert!(
                (0.0..=1.0).contains(&p),
                "overshoot prob {p} out of range for {b:?}"
            );
        }
    }

    #[test]
    fn searching_highest_overshoot_prob() {
        assert!(
            ScrollBehavior::Searching.overshoot_probability()
                > ScrollBehavior::Reading.overshoot_probability()
        );
    }

    #[test]
    fn pause_range_lo_lt_hi() {
        for b in [
            ScrollBehavior::Reading,
            ScrollBehavior::Scanning,
            ScrollBehavior::Searching,
            ScrollBehavior::Idle,
        ] {
            let (lo, hi) = b.pause_range_ms();
            assert!(lo < hi, "pause range lo {lo} >= hi {hi} for {b:?}");
        }
    }

    #[test]
    fn idle_has_longest_pauses() {
        let (_, idle_hi) = ScrollBehavior::Idle.pause_range_ms();
        let (_, scanning_hi) = ScrollBehavior::Scanning.pause_range_ms();
        assert!(idle_hi > scanning_hi);
    }

    // ── distribute_flicks ────────────────────────────────────────────────

    #[test]
    fn distribute_flicks_correct_count() {
        let scroller = HumanScroller::new(HumanScrollConfig {
            flick_count: 7,
            ..Default::default()
        });
        let mut rng = StdRng::seed_from_u64(1);
        let flicks = scroller.distribute_flicks(&mut rng);
        assert_eq!(flicks.len(), 7);
    }

    #[test]
    fn distribute_flicks_sum_matches_total() {
        let total = 1200;
        let scroller = HumanScroller::new(HumanScrollConfig {
            total_px: total,
            flick_count: 6,
            ..Default::default()
        });
        let mut rng = StdRng::seed_from_u64(2);
        let flicks = scroller.distribute_flicks(&mut rng);
        let sum: f64 = flicks.iter().sum();
        assert!(
            (sum - f64::from(total)).abs() < 1.0,
            "sum {sum:.1} != {total}"
        );
    }

    #[test]
    fn distribute_flicks_all_positive() {
        let scroller = HumanScroller::new(HumanScrollConfig::default());
        let mut rng = StdRng::seed_from_u64(3);
        for _ in 0..20 {
            let flicks = scroller.distribute_flicks(&mut rng);
            for f in flicks {
                assert!(f > 0.0);
            }
        }
    }

    #[test]
    fn distribute_flicks_unequal() {
        // With random exponential weights, it is astronomically unlikely
        // that all flick amounts are identical.
        let scroller = HumanScroller::new(HumanScrollConfig {
            flick_count: 5,
            total_px: 1000,
            ..Default::default()
        });
        let mut rng = StdRng::seed_from_u64(4);
        let flicks = scroller.distribute_flicks(&mut rng);
        let first = flicks[0];
        let all_same = flicks.iter().all(|&f| (f - first).abs() < 0.01);
        assert!(!all_same, "expected unequal flick distribution");
    }

    // ── HumanScrollConfig defaults ────────────────────────────────────────

    #[test]
    fn default_config_sane() {
        let cfg = HumanScrollConfig::default();
        assert!(cfg.total_px > 0);
        assert!(cfg.flick_count > 0);
        assert!(cfg.scroll_down);
        assert_eq!(cfg.behavior, ScrollBehavior::Reading);
    }
}