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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Human-like timing utilities (lifted from archived golemn-browser).
//!
//! Three independent subsystems, all pure (no browser, no async) so they can be
//! sampled and unit-tested offline; the `browser` feature adds thin `async`
//! sleep wrappers on top:
//!
//! 1. [`ReadingTimeEstimator`] — a realistic pause duration based on the number
//!    of visible words and a 200–250 WPM reading speed with variance.
//! 2. [`ActionDelay`] — pre-action think-time delays (`before_click`,
//!    `form_field_transition`, `after_page_load`, `micro`).
//! 3. [`SessionPacing`] — session-level fatigue and burst/pause rhythm: tracks
//!    elapsed actions and injects burst-end and long idle pauses, with a fatigue
//!    factor that grows over time and gradually slows every delay.
//!
//! The pacing decision is split from the sleep: [`SessionPacing::advance`]
//! mutates the state and *returns* the [`Duration`] to wait (deterministic under
//! a seeded RNG, so it is unit-testable), while the `browser`-only
//! [`SessionPacing::tick`] performs the actual `tokio` sleep.

use rand::Rng;
use std::time::Duration;

use crate::sampling::standard_normal;

// ── ReadingTimeEstimator ─────────────────────────────────────────────────

/// Estimates a realistic reading pause for a block of text.
///
/// Reading speed is drawn from a normal distribution centred at 225 WPM
/// (midpoint of the 200–250 WPM range), σ = 20 WPM.
pub struct ReadingTimeEstimator {
    /// Mean reading speed in words-per-minute.
    wpm_mean: f64,
    /// Standard deviation of reading speed.
    wpm_std: f64,
}

impl Default for ReadingTimeEstimator {
    fn default() -> Self {
        Self {
            wpm_mean: 225.0,
            wpm_std: 20.0,
        }
    }
}

impl ReadingTimeEstimator {
    /// Build an estimator with an explicit mean / standard-deviation WPM.
    #[must_use]
    pub fn new(wpm_mean: f64, wpm_std: f64) -> Self {
        Self { wpm_mean, wpm_std }
    }

    /// Estimate the time a human would spend reading `text`.
    ///
    /// Returns a `Duration` sampled from the configured reading-speed
    /// distribution, clamped to 500 ms – 120 s.
    #[must_use]
    pub fn estimate(&self, text: &str) -> Duration {
        let mut rng = rand::thread_rng();
        let word_count = count_words(text).max(1) as f64;

        // Sample WPM with normal noise.
        let z = standard_normal(&mut rng);
        let wpm = (self.wpm_mean + z * self.wpm_std).max(100.0);

        let minutes = word_count / wpm;
        let ms = (minutes * 60_000.0) as u64;

        // Clamp to a sensible range: 500 ms – 120 s.
        Duration::from_millis(ms.clamp(500, 120_000))
    }

    /// Estimate reading time given a raw word count.
    #[must_use]
    pub fn estimate_words(&self, word_count: usize) -> Duration {
        // Build a string with actual words so count_words() returns the right count.
        let words = "word ".repeat(word_count);
        self.estimate(&words)
    }
}

// ── ActionDelay ──────────────────────────────────────────────────────────

/// Pre-action "think time" delays that mimic human hesitation.
pub struct ActionDelay;

impl ActionDelay {
    /// Pause before a click: 200–800 ms.
    #[must_use]
    pub fn before_click() -> Duration {
        let ms = rand::thread_rng().gen_range(200_u64..=800);
        Duration::from_millis(ms)
    }

    /// Pause when moving between form fields: 300–1 200 ms.
    #[must_use]
    pub fn form_field_transition() -> Duration {
        let ms = rand::thread_rng().gen_range(300_u64..=1_200);
        Duration::from_millis(ms)
    }

    /// Initial pause after a page loads — user "takes in" the page: 800–3 000 ms.
    #[must_use]
    pub fn after_page_load() -> Duration {
        let ms = rand::thread_rng().gen_range(800_u64..=3_000);
        Duration::from_millis(ms)
    }

    /// Short micro-pause between UI events: 50–200 ms.
    #[must_use]
    pub fn micro() -> Duration {
        let ms = rand::thread_rng().gen_range(50_u64..=200);
        Duration::from_millis(ms)
    }

    /// Sleep for a [`before_click`](Self::before_click) duration.
    #[cfg(feature = "browser")]
    pub async fn wait_before_click() {
        tokio::time::sleep(Self::before_click()).await;
    }

    /// Sleep for a [`form_field_transition`](Self::form_field_transition) duration.
    #[cfg(feature = "browser")]
    pub async fn wait_form_transition() {
        tokio::time::sleep(Self::form_field_transition()).await;
    }

    /// Sleep for an [`after_page_load`](Self::after_page_load) duration.
    #[cfg(feature = "browser")]
    pub async fn wait_after_load() {
        tokio::time::sleep(Self::after_page_load()).await;
    }
}

// ── SessionPacing ─────────────────────────────────────────────────────────

/// Tracks session-level pacing: fatigue, burst sequences, and idle breaks.
///
/// Usage pattern (with the `browser` feature):
/// ```no_run
/// # #[cfg(feature = "browser")]
/// # async fn run() {
/// use guise::human::timing::SessionPacing;
/// let mut pacing = SessionPacing::new();
/// loop {
///     pacing.tick().await; // potentially inserts a burst-end / idle pause
///     // … do browser action …
/// #   break;
/// }
/// # }
/// ```
/// Without a browser, call [`SessionPacing::advance`] and sleep on the returned
/// [`Duration`] yourself.
pub struct SessionPacing {
    /// Number of actions taken so far in the session.
    actions_taken: u32,
    /// Actions until next forced idle break.
    next_idle_at: u32,
    /// Cumulative fatigue factor (starts at 1.0, grows toward ~1.5).
    fatigue: f64,
    /// How many consecutive "burst" actions remain before a pause.
    burst_remaining: u32,
}

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

impl SessionPacing {
    /// Start a fresh session with a randomised first idle break and burst length.
    #[must_use]
    pub fn new() -> Self {
        let mut rng = rand::thread_rng();
        Self {
            actions_taken: 0,
            next_idle_at: rng.gen_range(8..20),
            fatigue: 1.0,
            burst_remaining: rng.gen_range(3..8),
        }
    }

    /// Advance one action tick and return how long the caller should pause
    /// before the *next* action, or `None` for no pause.
    ///
    /// This is the pure heart of the pacer: it mutates fatigue / burst / idle
    /// state and computes the (fatigue-scaled) burst-end and idle pauses, but
    /// performs no sleeping itself — so it is deterministic under a seeded RNG.
    pub fn advance<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Option<Duration> {
        self.actions_taken += 1;
        // Fatigue grows slowly, asymptotically approaching 1.5.
        self.fatigue = 1.0 + 0.5 * (1.0 - (-(self.actions_taken as f64) / 60.0).exp());

        let mut total_ms: u64 = 0;

        // Burst tracking.
        if self.burst_remaining == 0 {
            // End-of-burst pause: 800–3 000 ms scaled by fatigue.
            let base_ms = rng.gen_range(800_u64..3_000);
            total_ms += (base_ms as f64 * self.fatigue) as u64;
            // Start a new burst.
            self.burst_remaining = rng.gen_range(3..8);
        } else {
            self.burst_remaining -= 1;
        }

        // Long idle break.
        if self.actions_taken >= self.next_idle_at {
            let idle_ms = rng.gen_range(5_000_u64..15_000);
            total_ms += (idle_ms as f64 * self.fatigue) as u64;
            self.actions_taken = 0;
            self.next_idle_at = rng.gen_range(8..20);
            // Reset burst after a long idle.
            self.burst_remaining = rng.gen_range(3..8);
        }

        (total_ms > 0).then(|| Duration::from_millis(total_ms))
    }

    /// Advance one action tick and sleep for any burst-end / idle pause.
    #[cfg(feature = "browser")]
    pub async fn tick(&mut self) {
        use rand::SeedableRng;
        // Send-safe RNG so the future stays `Send` across the await point.
        let mut rng = rand::rngs::StdRng::from_entropy();
        if let Some(delay) = self.advance(&mut rng) {
            tokio::time::sleep(delay).await;
        }
    }

    /// Current fatigue multiplier (1.0 = fresh, up to ~1.5 = tired).
    #[must_use]
    pub fn fatigue(&self) -> f64 {
        self.fatigue
    }

    /// Total number of actions taken in this session (since the last idle reset).
    #[must_use]
    pub fn actions_taken(&self) -> u32 {
        self.actions_taken
    }

    /// Scale a base delay by the current fatigue factor.
    #[must_use]
    pub fn scale_duration(&self, base: Duration) -> Duration {
        Duration::from_millis((base.as_millis() as f64 * self.fatigue) as u64)
    }
}

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

fn count_words(text: &str) -> usize {
    text.split_whitespace().count()
}

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

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

    // ── ReadingTimeEstimator ─────────────────────────────────────────────

    #[test]
    fn reading_time_minimum_500ms() {
        let est = ReadingTimeEstimator::default();
        // Single word should still give >= 500 ms.
        let d = est.estimate("hello");
        assert!(
            d >= Duration::from_millis(500),
            "expected >= 500 ms, got {d:?}"
        );
    }

    #[test]
    fn reading_time_grows_with_word_count() {
        let est = ReadingTimeEstimator::default();
        let short: u128 = (0..50).map(|_| est.estimate_words(10).as_millis()).sum();
        let long: u128 = (0..50).map(|_| est.estimate_words(100).as_millis()).sum();
        assert!(
            long > short,
            "long text ({long}) should take longer than short ({short})"
        );
    }

    #[test]
    fn reading_time_under_120s() {
        let est = ReadingTimeEstimator::default();
        for _ in 0..50 {
            let d = est.estimate_words(500);
            assert!(
                d <= Duration::from_secs(120),
                "expected <= 120 s, got {d:?}"
            );
        }
    }

    #[test]
    fn reading_time_reasonable_for_200_words() {
        // At 225 WPM, 200 words ≈ 53 s; allow 30–90 s window.
        let est = ReadingTimeEstimator::default();
        let samples: Vec<Duration> = (0..100).map(|_| est.estimate_words(200)).collect();
        let mean_ms: u128 = samples.iter().map(|d| d.as_millis()).sum::<u128>() / 100;
        assert!(
            (30_000..=90_000).contains(&mean_ms),
            "mean {mean_ms} ms out of expected 30–90 s window"
        );
    }

    #[test]
    fn empty_text_returns_minimum() {
        let est = ReadingTimeEstimator::default();
        let d = est.estimate("");
        assert_eq!(d, Duration::from_millis(500));
    }

    // ── ActionDelay ──────────────────────────────────────────────────────

    #[test]
    fn before_click_in_range() {
        for _ in 0..100 {
            let d = ActionDelay::before_click();
            assert!(
                d >= Duration::from_millis(200) && d <= Duration::from_millis(800),
                "before_click {d:?} out of 200–800 ms range"
            );
        }
    }

    #[test]
    fn form_field_transition_in_range() {
        for _ in 0..100 {
            let d = ActionDelay::form_field_transition();
            assert!(
                d >= Duration::from_millis(300) && d <= Duration::from_millis(1_200),
                "form_field_transition {d:?} out of 300–1200 ms range"
            );
        }
    }

    #[test]
    fn after_page_load_in_range() {
        for _ in 0..100 {
            let d = ActionDelay::after_page_load();
            assert!(
                d >= Duration::from_millis(800) && d <= Duration::from_millis(3_000),
                "after_page_load {d:?} out of 800–3000 ms range"
            );
        }
    }

    #[test]
    fn micro_delay_in_range() {
        for _ in 0..100 {
            let d = ActionDelay::micro();
            assert!(
                d >= Duration::from_millis(50) && d <= Duration::from_millis(200),
                "micro delay {d:?} out of 50–200 ms range"
            );
        }
    }

    // ── SessionPacing ────────────────────────────────────────────────────

    #[test]
    fn initial_fatigue_is_one() {
        let pacing = SessionPacing::new();
        assert!((pacing.fatigue() - 1.0).abs() < 0.01);
    }

    #[test]
    fn fatigue_increases_with_actions() {
        let mut pacing = SessionPacing::new();
        let mut rng = StdRng::seed_from_u64(11);
        for _ in 0..30 {
            pacing.advance(&mut rng);
        }
        assert!(
            pacing.fatigue() > 1.0,
            "fatigue should grow above 1.0 after 30 actions"
        );
    }

    #[test]
    fn fatigue_stays_below_1_5() {
        let mut pacing = SessionPacing::new();
        let mut rng = StdRng::seed_from_u64(3);
        for _ in 0..500 {
            pacing.advance(&mut rng);
        }
        assert!(
            pacing.fatigue() < 1.5,
            "fatigue should stay below 1.5, got {}",
            pacing.fatigue()
        );
    }

    #[test]
    fn advance_emits_burst_end_pause() {
        // With burst_remaining forced to 0, the next advance must return a pause.
        let mut pacing = SessionPacing::new();
        pacing.burst_remaining = 0;
        pacing.next_idle_at = u32::MAX; // suppress the idle branch
        let mut rng = StdRng::seed_from_u64(99);
        let pause = pacing.advance(&mut rng).expect("burst-end pause expected");
        // 800–3000 ms scaled by ~1.0 fatigue → comfortably in this window.
        assert!(
            pause >= Duration::from_millis(700) && pause <= Duration::from_millis(5_000),
            "burst pause {pause:?} out of expected window"
        );
        // A fresh burst was started.
        assert!(pacing.burst_remaining >= 3);
    }

    #[test]
    fn advance_no_pause_mid_burst() {
        let mut pacing = SessionPacing::new();
        pacing.burst_remaining = 5;
        pacing.next_idle_at = u32::MAX;
        let mut rng = StdRng::seed_from_u64(7);
        assert!(
            pacing.advance(&mut rng).is_none(),
            "mid-burst tick should not pause"
        );
        assert_eq!(pacing.burst_remaining, 4);
    }

    #[test]
    fn advance_idle_break_resets_counter() {
        let mut pacing = SessionPacing::new();
        pacing.burst_remaining = 5; // avoid the burst branch
        pacing.actions_taken = 0;
        pacing.next_idle_at = 1; // force idle on first advance
        let mut rng = StdRng::seed_from_u64(42);
        let pause = pacing.advance(&mut rng).expect("idle pause expected");
        assert!(
            pause >= Duration::from_millis(5_000),
            "idle pause too short: {pause:?}"
        );
        assert_eq!(
            pacing.actions_taken, 0,
            "idle break should reset the counter"
        );
    }

    #[test]
    fn scale_duration_with_fatigue() {
        let mut pacing = SessionPacing::new();
        // Force fatigue to 1.2.
        pacing.fatigue = 1.2;
        let base = Duration::from_millis(1000);
        let scaled = pacing.scale_duration(base);
        assert!(
            scaled >= Duration::from_millis(1190) && scaled <= Duration::from_millis(1210),
            "scaled {scaled:?} should be ~1200 ms"
        );
    }

    #[test]
    fn count_words_basic() {
        assert_eq!(count_words("hello world foo"), 3);
        assert_eq!(count_words(""), 0);
        assert_eq!(count_words("  spaces  "), 1);
    }

    #[test]
    fn sample_normal_mean_near_zero() {
        let mut rng = StdRng::seed_from_u64(123);
        let n = 2000;
        let mean: f64 = (0..n).map(|_| standard_normal(&mut rng)).sum::<f64>() / n as f64;
        assert!(mean.abs() < 0.1, "normal mean {mean:.4} should be near 0");
    }
}