guise 0.1.2

Canonical browser fingerprint bundles, human-behavior timing, and TLS profile re-exports for the Santh fleet
Documentation
//! Shared random sampling primitives for stealth timing models.

use rand::Rng;

/// Minimum coefficient of variation (σ/μ) that separates human-shaped timing
/// dispersion from a near-uniform machine cadence.
///
/// This is a single source of truth consumed from BOTH sides of the disguise:
/// the **detector** ([`crate::probe`]'s `classify_timing_cv`) gates a live
/// browser's busy-loop scheduler jitter on it, and the **generator** (the
/// `human` layer's keystroke/pacing timing) is held to the same floor by
/// `keystroke::tests::generated_typing_rhythm_clears_human_cv_floor`. Closing
/// that loop means the rhythm guise *emits* clears the very bar a behavioural
/// classifier (and our own probe) would fail it on. Drawn from behavioural-
/// biometrics literature: human inter-event intervals run CV ≈ 0.15–0.4, while
/// uniform automated schedulers sit near 0.
pub(crate) const HUMAN_TIMING_CV_FLOOR: f64 = 0.1;

/// Soft floor between [`HUMAN_TIMING_CV_FLOOR`] and a hard machine tell. A CV in
/// `[CV_DRIFT_FLOOR, HUMAN_TIMING_CV_FLOOR)` is suspiciously low but not provably
/// synthetic (drift); below it is a near-uniform timer (critical).
pub(crate) const CV_DRIFT_FLOOR: f64 = 0.03;

/// Sample a standard normal variate using the Box-Muller transform.
///
/// Consumed by the `human` timing/motion models; in a `human`-less build (e.g.
/// `--features browser` alone) it is legitimately unused.
#[cfg_attr(not(feature = "human"), allow(dead_code))]
pub(crate) fn standard_normal<R: Rng + ?Sized>(rng: &mut R) -> f64 {
    let u1: f64 = rng.gen::<f64>().max(1e-12);
    let u2: f64 = rng.gen::<f64>();
    (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()
}

/// Population coefficient of variation (σ/μ) of a sample.
///
/// Returns `None` when the dispersion is undefined: fewer than two points, or a
/// non-positive mean. Used to score whether a generated timing stream (keystroke
/// gaps, pacing intervals) carries human-like dispersion against
/// [`HUMAN_TIMING_CV_FLOOR`] — the Rust-side mirror of the JS busy-loop CV the
/// probe computes in the page.
///
/// Consumed by the `human` keystroke-rhythm realism test; unused in a
/// `human`-less build.
#[cfg_attr(not(feature = "human"), allow(dead_code))]
pub(crate) fn coefficient_of_variation(samples: &[f64]) -> Option<f64> {
    if samples.len() < 2 {
        return None;
    }
    let n = samples.len() as f64;
    let mean = samples.iter().sum::<f64>() / n;
    if mean <= 0.0 {
        return None;
    }
    let variance = samples
        .iter()
        .map(|x| {
            let d = x - mean;
            d * d
        })
        .sum::<f64>()
        / n;
    Some(variance.sqrt() / mean)
}

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

    #[test]
    fn standard_normal_is_finite_and_centered() {
        let mut rng = StdRng::seed_from_u64(42);
        let n = 10_000;
        let samples: Vec<f64> = (0..n).map(|_| standard_normal(&mut rng)).collect();

        assert!(samples.iter().all(|sample| sample.is_finite()));

        let mean = samples.iter().sum::<f64>() / n as f64;
        assert!(mean.abs() < 0.05, "mean too far from zero: {mean}");

        let variance = samples
            .iter()
            .map(|sample| {
                let delta = sample - mean;
                delta * delta
            })
            .sum::<f64>()
            / n as f64;
        assert!(
            (0.90..=1.10).contains(&variance),
            "variance should be near one, got {variance}"
        );
    }

    #[test]
    fn cv_undefined_for_degenerate_samples() {
        assert_eq!(coefficient_of_variation(&[]), None, "empty has no CV");
        assert_eq!(coefficient_of_variation(&[5.0]), None, "single point has no CV");
        assert_eq!(
            coefficient_of_variation(&[0.0, 0.0]),
            None,
            "zero mean makes CV undefined"
        );
    }

    #[test]
    fn cv_zero_for_constant_stream() {
        // A perfectly uniform (machine) cadence has zero dispersion — the tell
        // HUMAN_TIMING_CV_FLOOR is meant to catch.
        let cv = coefficient_of_variation(&[100.0, 100.0, 100.0, 100.0]).unwrap();
        assert!(cv.abs() < 1e-9, "constant stream CV {cv} should be 0");
        assert!(cv < HUMAN_TIMING_CV_FLOOR);
    }

    #[test]
    fn cv_matches_hand_computed_value() {
        // mean = 3, population σ = sqrt(2/3) ≈ 0.8165, CV ≈ 0.2722.
        let cv = coefficient_of_variation(&[2.0, 3.0, 4.0]).unwrap();
        assert!((cv - 0.272_166).abs() < 1e-4, "CV {cv} != hand value");
        assert!(cv >= HUMAN_TIMING_CV_FLOOR, "spread-out stream clears floor");
    }

    #[test]
    fn cv_drift_floor_below_human_floor() {
        assert!(CV_DRIFT_FLOOR < HUMAN_TIMING_CV_FLOOR);
    }
}