guise 0.1.8

Canonical browser fingerprint bundles, human-behavior timing, and TLS profile re-exports
Documentation
//! Behavioral detector fixture (G178).
//!
//! Implements a minimal timing classifier that scores an event stream by the
//! coefficient of variation (CV) of its inter-event intervals. A near-uniform
//! cadence (the classic bot signature) yields a CV near zero; a human-like
//! cadence yields a higher CV. The fixture lets us run controlled A/B
//! experiments:
//!
//!   * **Human arm**: a stream generated by [`human_typing_stream`], which uses
//!     the canonical bigram-aware keystroke planner + hold-time envelopes.
//!   * **Bot arm**: a stream generated by [`bot_typing_stream`] with a fixed
//!     gap and hold time.
//!
//! The detector is intentionally simple so the lift is attributable to the
//! human layer itself, not to a clever classifier. It mirrors the CV floor
//! used by the probe layer (`probe::redteam::classify_timing_cv`).

use crate::human::keyboard_event::key_to_code;
use crate::human::keystroke::{plan_keystrokes, TypingPlan};
use crate::human::telemetry::BehavioralEvent;
use crate::sampling::coefficient_of_variation;
use rand::{rngs::StdRng, SeedableRng};

/// Generate a behavioral event stream from the canonical human typing model.
///
/// The stream contains alternating `KeyDown`/`KeyUp` events whose timestamps
/// are derived from the per-bigram gaps and hold times produced by
/// [`plan_keystrokes`]. This is the "with human layer" arm of the A/B test.
#[must_use]
pub fn human_typing_stream(text: &str, seed: u64) -> Vec<BehavioralEvent> {
    let mut rng = StdRng::seed_from_u64(seed);
    let plan = TypingPlan::default();
    let keys = plan_keystrokes(text, plan, &mut rng);

    let mut ts = 0u64;
    let mut events = Vec::with_capacity(keys.len() * 2);
    for k in keys {
        ts += u64::from(k.gap_ms_before);
        let key = k.ch.to_string();
        let code = key_to_code(k.ch);
        events.push(BehavioralEvent::KeyDown {
            ts,
            key: key.clone(),
            code: code.clone(),
        });
        ts += u64::from(k.hold_ms);
        events.push(BehavioralEvent::KeyUp { ts, key, code });
    }
    events
}

/// Generate a uniform (bot) typing stream with constant gap and hold times.
///
/// This is the "without human layer" arm: identical character sequence, but
/// every inter-key interval is identical, the shape that real behavioral
/// detectors flag as synthetic.
#[must_use]
pub fn bot_typing_stream(text: &str, gap_ms: u64, hold_ms: u64) -> Vec<BehavioralEvent> {
    let mut ts = 0u64;
    let chs: Vec<char> = text.chars().collect();
    let mut events = Vec::with_capacity(chs.len() * 2);
    for ch in chs {
        ts += gap_ms;
        let key = ch.to_string();
        let code = key_to_code(ch);
        events.push(BehavioralEvent::KeyDown {
            ts,
            key: key.clone(),
            code: code.clone(),
        });
        ts += hold_ms;
        events.push(BehavioralEvent::KeyUp { ts, key, code });
    }
    events
}

/// Score a stream by the coefficient of variation of its inter-keystroke
/// intervals (consecutive `KeyDown` event timestamps).
///
/// A real timing classifier looks at the cadence of key presses, not the
/// alternation of keydown/keyup, so this only measures keydown-to-keydown gaps.
/// Returns `None` when there are fewer than two keydowns.
pub fn timing_cv(events: &[BehavioralEvent]) -> Option<f64> {
    let keydown_ts: Vec<f64> = events
        .iter()
        .filter_map(|e| match e {
            BehavioralEvent::KeyDown { ts, .. } => Some(*ts as f64),
            _ => None,
        })
        .collect();
    if keydown_ts.len() < 3 {
        return None;
    }
    let deltas: Vec<f64> = keydown_ts.windows(2).map(|w| w[1] - w[0]).collect();
    coefficient_of_variation(&deltas)
}

/// Compute the lift ratio of the human score over the bot score.
///
/// A ratio > 1 means the human layer produced a more variable (more human-like)
/// cadence. The returned `f64` is `human / bot`.
pub fn lift_ratio(human_score: f64, bot_score: f64) -> f64 {
    if bot_score == 0.0 {
        return f64::INFINITY;
    }
    human_score / bot_score
}

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

    const SAMPLE_TEXT: &str = "the quick brown fox jumps over 7 lazy dogs";

    #[test]
    fn human_stream_clears_detector_floor() {
        // Try several seeds (the property must be robust, not lucky).
        for seed in 0..16u64 {
            let stream = human_typing_stream(SAMPLE_TEXT, seed);
            let cv = timing_cv(&stream).expect("multi-event stream has a CV");
            assert!(
                cv >= crate::sampling::HUMAN_TIMING_CV_FLOOR,
                "human stream CV {cv:.4} below detector floor {} (seed {seed})",
                crate::sampling::HUMAN_TIMING_CV_FLOOR
            );
        }
    }

    #[test]
    fn bot_stream_fails_detector_floor() {
        let stream = bot_typing_stream(SAMPLE_TEXT, 120, 60);
        let cv = timing_cv(&stream).expect("multi-event stream has a CV");
        assert!(
            cv < crate::sampling::HUMAN_TIMING_CV_FLOOR,
            "uniform bot stream CV {cv:.4} should be below detector floor {}",
            crate::sampling::HUMAN_TIMING_CV_FLOOR
        );
    }

    #[test]
    fn human_stream_has_quantifiable_lift_over_bot() {
        let human_stream = human_typing_stream(SAMPLE_TEXT, 42);
        let bot_stream = bot_typing_stream(SAMPLE_TEXT, 120, 60);
        let human_cv = timing_cv(&human_stream).unwrap();
        let bot_cv = timing_cv(&bot_stream).unwrap();
        let lift = lift_ratio(human_cv, bot_cv);
        assert!(
            lift > 2.0,
            "human CV {human_cv:.4} vs bot CV {bot_cv:.4} gives lift {lift:.2}x; expected >2x"
        );
    }

    #[test]
    fn bot_stream_cv_is_near_zero() {
        // A perfectly uniform cadence has zero dispersion. With integer ms the
        // deltas are identical, so CV should be exactly zero.
        let stream = bot_typing_stream("hello world", 100, 50);
        let cv = timing_cv(&stream).unwrap();
        assert!(cv < 0.001, "uniform cadence CV should be ~0, got {cv}");
    }

    #[test]
    fn short_stream_has_no_cv() {
        // "ab" yields only two keydowns, so the CV is undefined.
        let stream = bot_typing_stream("ab", 100, 50);
        assert_eq!(timing_cv(&stream), None);
    }
}