guise 0.1.2

Canonical browser fingerprint bundles, human-behavior timing, and TLS profile re-exports for the Santh fleet
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/// Human-like typing simulation.
///
/// Models realistic typing behaviour:
/// - Log-normal inter-key delays derived from a configurable WPM target
/// - 3 % typo rate with immediate backspace correction
/// - Burst mode for common English words; slower for uncommon ones
/// - Shift-key pause before upper-case characters
/// - Distinct speed distributions for digits, symbols, and letters
use anyhow::Result;
use rand::Rng;
use runtime_foxdriver::Page;
use std::time::Duration;

use crate::choice::{chance_with_rng, random_item_with_rng};
use crate::sampling::standard_normal;

// ── Common English words that humans type fast ─────────────────────────────
const COMMON_WORDS: &[&str] = &[
    "the", "be", "to", "of", "and", "a", "in", "that", "have", "it", "for", "not", "on", "with",
    "he", "as", "you", "do", "at", "this", "but", "his", "by", "from", "they", "we", "say", "her",
    "she", "or", "an", "will", "my", "one", "all", "would", "there", "their", "what", "so", "up",
    "out", "if", "about", "who", "get", "which", "go", "me", "when", "make", "can", "like", "time",
    "no", "just", "him", "know", "take", "into", "your", "good", "some", "could", "them", "see",
    "other", "than", "then", "now", "look", "only", "come", "its", "over", "think", "also", "back",
    "after", "use", "two", "how", "our", "work", "first", "well", "way", "even", "new", "want",
    "because", "any", "these", "give", "day", "most", "us",
];

/// Keyboard rows for adjacency-based typos (QWERTY layout).
const KEYBOARD_ROWS: &[&[char]] = &[
    &['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'],
    &['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'],
    &['z', 'x', 'c', 'v', 'b', 'n', 'm'],
];

/// Configuration for the human typer.
#[derive(Debug, Clone)]
pub struct TypingConfig {
    /// Target words-per-minute (40–80 is realistic for most people).
    pub wpm: f64,
    /// Probability of producing a typo on any given character (0.0–1.0).
    pub typo_rate: f64,
    /// Extra delay before uppercase characters to simulate shift-key press (ms).
    pub shift_delay_ms: u64,
    /// Delay multiplier for digit characters (digits take longer to reach).
    pub digit_speed_factor: f64,
    /// Delay multiplier for symbol/special characters.
    pub symbol_speed_factor: f64,
}

impl Default for TypingConfig {
    fn default() -> Self {
        Self {
            wpm: 60.0,
            typo_rate: 0.03,
            shift_delay_ms: 80,
            digit_speed_factor: 1.4,
            symbol_speed_factor: 1.8,
        }
    }
}

impl TypingConfig {
    /// Build a config targeting the given WPM (clamped to 40–80).
    pub fn with_wpm(wpm: f64) -> Self {
        Self {
            wpm: wpm.clamp(40.0, 80.0),
            ..Default::default()
        }
    }
}

/// Human-like typer.  Construct once and reuse across multiple calls.
pub struct HumanTyper {
    config: TypingConfig,
}

impl HumanTyper {
    /// Create a typer with the supplied cadence and typo configuration.
    pub fn new(config: TypingConfig) -> Self {
        Self { config }
    }

    /// Type `text` into the currently focused element on `page`.
    pub async fn type_text(&self, page: &Page, text: &str) -> Result<()> {
        let mut rng = rand::thread_rng();
        // Split into "words" so we can detect common words for burst mode.
        // We re-join with any whitespace/punctuation found in the original.
        let chars: Vec<char> = text.chars().collect();
        let mut i = 0;

        while i < chars.len() {
            // Try to extract a word at this position for burst detection.
            let word_len = Self::word_len_at(&chars, i);
            let word: String = chars[i..i + word_len].iter().collect();
            let is_common = is_common_word(&word);

            for j in 0..word_len {
                let ch = chars[i + j];
                self.type_char(page, ch, is_common, &mut rng).await?;
            }
            i += word_len;

            // If we consumed a word, check for trailing non-word chars.
            if word_len == 0 {
                let ch = chars[i];
                self.type_char(page, ch, false, &mut rng).await?;
                i += 1;
            }
        }

        Ok(())
    }

    /// Type a single character with all the human-like effects.
    async fn type_char<R: Rng>(
        &self,
        page: &Page,
        ch: char,
        is_common_word_context: bool,
        rng: &mut R,
    ) -> Result<()> {
        // Possibly introduce a typo (but never on whitespace).
        if !ch.is_whitespace() && chance_with_rng(self.config.typo_rate, rng) {
            // Pick an adjacent key as the typo character.
            if let Some(typo_ch) = adjacent_key(ch, rng) {
                let typo_str = typo_ch.to_string();
                page.type_text(&typo_str).await?;
                tokio::time::sleep(Duration::from_millis(rng.gen_range(80..180))).await;
                // Backspace correction
                page.type_text("\u{0008}").await?;
                tokio::time::sleep(Duration::from_millis(rng.gen_range(60..140))).await;
            }
        }

        // Shift-key pause before uppercase.
        if ch.is_uppercase() {
            tokio::time::sleep(Duration::from_millis(
                self.config.shift_delay_ms + rng.gen_range(0..40),
            ))
            .await;
        }

        let ch_str = ch.to_string();
        page.type_text(&ch_str).await?;

        // Key-press hold time: 30–80 ms.
        tokio::time::sleep(Duration::from_millis(rng.gen_range(30..80))).await;

        // Compute inter-key delay.
        let base_delay = self.base_delay_ms();
        let delay = self.inter_key_delay(ch, is_common_word_context, base_delay, rng);
        tokio::time::sleep(Duration::from_millis(delay)).await;

        Ok(())
    }

    /// Base delay in ms derived from WPM (5 chars/word assumed).
    fn base_delay_ms(&self) -> f64 {
        // WPM → chars per second → ms per char
        let chars_per_sec = self.config.wpm * 5.0 / 60.0;
        1000.0 / chars_per_sec
    }

    /// Full inter-key delay with log-normal noise, category multiplier,
    /// and occasional thinking pauses.
    fn inter_key_delay<R: Rng>(&self, ch: char, is_common: bool, base_ms: f64, rng: &mut R) -> u64 {
        // Category multiplier.
        let category_factor = if ch.is_ascii_digit() {
            self.config.digit_speed_factor
        } else if !ch.is_alphabetic() && !ch.is_whitespace() {
            self.config.symbol_speed_factor
        } else if is_common {
            0.7 // common words → burst mode
        } else {
            1.0
        };

        // Log-normal noise: μ=0, σ=0.3 gives ≈ 30% standard deviation.
        let sigma = 0.3_f64;
        let z = standard_normal(rng);
        let lognormal = (sigma * z).exp();

        let jittered = base_ms * category_factor * lognormal;

        // Occasional "thinking" pauses (~5% of keystrokes).
        let extra = if chance_with_rng(0.05, rng) {
            rng.gen_range(300..800) as f64
        } else {
            0.0
        };

        (jittered + extra).round() as u64
    }

    /// Length of the alphabetic word starting at `pos` in `chars`.
    fn word_len_at(chars: &[char], pos: usize) -> usize {
        chars[pos..]
            .iter()
            .take_while(|c| c.is_alphabetic() || **c == '\'')
            .count()
    }
}

impl Default for HumanTyper {
    fn default() -> Self {
        Self::new(TypingConfig::default())
    }
}

// ── Helpers ─────────────────────────────────────────────────────────────────

/// Returns `true` if the lower-cased word is in the common-word list.
fn is_common_word(word: &str) -> bool {
    let lower = word.to_lowercase();
    COMMON_WORDS.contains(&lower.as_str())
}

/// Return an adjacent QWERTY key character for `ch`, or `None` if not found.
fn adjacent_key<R: Rng>(ch: char, rng: &mut R) -> Option<char> {
    let lower = ch.to_lowercase().next()?;
    for (ri, row) in KEYBOARD_ROWS.iter().enumerate() {
        if let Some(ci) = row.iter().position(|&k| k == lower) {
            let mut candidates: Vec<char> = Vec::new();
            // Same row neighbours
            if ci > 0 {
                candidates.push(row[ci - 1]);
            }
            if ci + 1 < row.len() {
                candidates.push(row[ci + 1]);
            }
            // Row above
            if ri > 0 {
                let above = KEYBOARD_ROWS[ri - 1];
                let mapped = ci.min(above.len().saturating_sub(1));
                candidates.push(above[mapped]);
            }
            // Row below
            if ri + 1 < KEYBOARD_ROWS.len() {
                let below = KEYBOARD_ROWS[ri + 1];
                let mapped = ci.min(below.len().saturating_sub(1));
                candidates.push(below[mapped]);
            }
            if candidates.is_empty() {
                return None;
            }
            return random_item_with_rng(&candidates, rng).copied();
        }
    }
    None
}

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

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

    #[test]
    fn default_config_wpm_in_range() {
        let cfg = TypingConfig::default();
        assert!(cfg.wpm >= 40.0 && cfg.wpm <= 80.0);
    }

    #[test]
    fn default_typer_uses_default_config() {
        let typer = HumanTyper::default();
        assert_eq!(typer.config.wpm, TypingConfig::default().wpm);
        assert_eq!(typer.config.typo_rate, TypingConfig::default().typo_rate);
    }

    #[test]
    fn with_wpm_clamps_low() {
        let cfg = TypingConfig::with_wpm(10.0);
        assert_eq!(cfg.wpm, 40.0);
    }

    #[test]
    fn with_wpm_clamps_high() {
        let cfg = TypingConfig::with_wpm(200.0);
        assert_eq!(cfg.wpm, 80.0);
    }

    #[test]
    fn with_wpm_exact() {
        let cfg = TypingConfig::with_wpm(55.0);
        assert!((cfg.wpm - 55.0).abs() < f64::EPSILON);
    }

    #[test]
    fn base_delay_at_60wpm_is_200ms() {
        let typer = HumanTyper::new(TypingConfig::with_wpm(60.0));
        let d = typer.base_delay_ms();
        // 60 WPM × 5 chars = 300 chars/min → 200 ms/char
        assert!((d - 200.0).abs() < 1.0, "expected ≈200 ms, got {d}");
    }

    #[test]
    fn base_delay_at_40wpm_is_300ms() {
        let typer = HumanTyper::new(TypingConfig::with_wpm(40.0));
        let d = typer.base_delay_ms();
        assert!((d - 300.0).abs() < 1.0, "expected ≈300 ms, got {d}");
    }

    #[test]
    fn inter_key_delay_digits_slower() {
        let typer = HumanTyper::new(TypingConfig::default());
        let base = typer.base_delay_ms();
        let mut rng = rand::thread_rng();
        // Sample many times to overcome lognormal noise
        let sum_digit: f64 = (0..200)
            .map(|_| typer.inter_key_delay('7', false, base, &mut rng) as f64)
            .sum();
        let sum_alpha: f64 = (0..200)
            .map(|_| typer.inter_key_delay('a', false, base, &mut rng) as f64)
            .sum();
        // Digits should average slower than letters
        assert!(
            sum_digit > sum_alpha,
            "digits avg {:.0} should exceed alpha avg {:.0}",
            sum_digit / 200.0,
            sum_alpha / 200.0
        );
    }

    #[test]
    fn inter_key_delay_common_word_faster() {
        let typer = HumanTyper::new(TypingConfig::default());
        let base = typer.base_delay_ms();
        let mut rng = rand::thread_rng();
        let sum_common: f64 = (0..200)
            .map(|_| typer.inter_key_delay('a', true, base, &mut rng) as f64)
            .sum();
        let sum_rare: f64 = (0..200)
            .map(|_| typer.inter_key_delay('a', false, base, &mut rng) as f64)
            .sum();
        assert!(
            sum_common < sum_rare,
            "common avg {:.0} should be below rare avg {:.0}",
            sum_common / 200.0,
            sum_rare / 200.0
        );
    }

    #[test]
    fn sample_normal_reasonable_range() {
        let mut rng = rand::thread_rng();
        let samples: Vec<f64> = (0..1000).map(|_| standard_normal(&mut rng)).collect();
        let mean = samples.iter().sum::<f64>() / samples.len() as f64;
        // Mean should be close to 0
        assert!(mean.abs() < 0.15, "normal mean {mean:.3} should be near 0");
    }

    #[test]
    fn adjacent_key_returns_different_char() {
        let mut rng = rand::thread_rng();
        // 'f' has neighbours e, g, r, v, d
        let typo = adjacent_key('f', &mut rng);
        assert!(typo.is_some());
        assert_ne!(typo.unwrap(), 'f');
    }

    #[test]
    fn adjacent_key_unknown_returns_none() {
        let mut rng = rand::thread_rng();
        // '🦀' is not on the keyboard
        let typo = adjacent_key('🦀', &mut rng);
        assert!(typo.is_none());
    }

    #[test]
    fn is_common_word_recognizes_the() {
        assert!(is_common_word("the"));
        assert!(is_common_word("The"));
        assert!(is_common_word("THE"));
    }

    #[test]
    fn is_common_word_rejects_rare() {
        assert!(!is_common_word("supercalifragilistic"));
        assert!(!is_common_word("xylophone"));
    }

    #[test]
    fn word_len_at_extracts_word() {
        let chars: Vec<char> = "hello world".chars().collect();
        assert_eq!(HumanTyper::word_len_at(&chars, 0), 5);
        assert_eq!(HumanTyper::word_len_at(&chars, 6), 5);
    }

    #[test]
    fn word_len_at_non_alpha_is_zero() {
        let chars: Vec<char> = ", test".chars().collect();
        assert_eq!(HumanTyper::word_len_at(&chars, 0), 0);
    }

    #[test]
    fn config_typo_rate_default() {
        let cfg = TypingConfig::default();
        assert!((cfg.typo_rate - 0.03).abs() < f64::EPSILON);
    }

    #[test]
    fn config_shift_delay_positive() {
        let cfg = TypingConfig::default();
        assert!(cfg.shift_delay_ms > 0);
    }

    #[test]
    fn config_symbol_speed_factor_gt_digit() {
        let cfg = TypingConfig::default();
        assert!(cfg.symbol_speed_factor > cfg.digit_speed_factor);
    }
}