eoka 0.17.1

Stealth browser automation for Rust. Puppeteer/Playwright alternative with anti-bot bypass.
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! Human-like browser interactions
//!
//! Simulates realistic mouse movements and typing patterns to avoid
//! behavior-based bot detection.

mod drag;

use drag::{validate_drag, PendingRelease};
use std::sync::Mutex;
use std::time::Duration;
use tokio::time::sleep;

use crate::cdp::Session;
use crate::error::Result;
use crate::page::{
    coordinated_key_char, coordinated_key_down, coordinated_key_up, coordinated_mouse_down,
    coordinated_mouse_move, coordinated_mouse_up, coordinated_mouse_wheel, MouseButton,
};

/// Speed mode for human simulation
#[derive(Debug, Clone, Copy, Default)]
pub enum HumanSpeed {
    /// Fast mode - minimal delays
    Fast,
    /// Normal mode - balanced
    #[default]
    Normal,
    /// Slow mode - maximum realism
    Slow,
}

impl HumanSpeed {
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "each count is clamped to a small positive range (at most 100)"
    )]
    fn mouse_points(self, distance: f64) -> usize {
        match self {
            HumanSpeed::Fast => (distance / 50.0).clamp(3.0, 10.0) as usize,
            HumanSpeed::Normal => (distance / 10.0).clamp(10.0, 50.0) as usize,
            HumanSpeed::Slow => (distance / 5.0).clamp(20.0, 100.0) as usize,
        }
    }

    fn move_delay_ms(self) -> (u64, u64) {
        match self {
            HumanSpeed::Fast => (1, 5),
            HumanSpeed::Normal => (5, 25),
            HumanSpeed::Slow => (10, 50),
        }
    }

    fn type_delay_ms(self) -> (u64, u64) {
        match self {
            HumanSpeed::Fast => (10, 30),
            HumanSpeed::Normal => (50, 150),
            HumanSpeed::Slow => (100, 300),
        }
    }
}

fn random_range(min: u64, max: u64) -> u64 {
    debug_assert!(
        min < max,
        "random_range: min ({min}) must be less than max ({max})"
    );
    if min >= max {
        return min;
    }
    fastrand::u64(min..max)
}

/// Sleep for a uniformly random duration in `min..max` milliseconds.
async fn pause(min: u64, max: u64) {
    sleep(Duration::from_millis(random_range(min, max))).await;
}

fn random_f64_range(min: f64, max: f64) -> f64 {
    debug_assert!(
        min < max,
        "random_f64_range: min ({min}) must be less than max ({max})"
    );
    if min >= max {
        return min;
    }
    min + fastrand::f64() * (max - min)
}

fn random_bool(probability: f64) -> bool {
    fastrand::f64() < probability
}

/// Point type
type Point = (f64, f64);

/// Generate Bezier curve for natural mouse movement
pub(crate) fn bezier_curve(start: Point, end: Point, num_points: usize) -> Vec<Point> {
    let num_points = num_points.max(2);

    let cp1 = (
        start.0 + (end.0 - start.0) * random_f64_range(0.2, 0.4) + random_f64_range(-50.0, 50.0),
        start.1 + (end.1 - start.1) * random_f64_range(0.0, 0.3) + random_f64_range(-50.0, 50.0),
    );
    let cp2 = (
        start.0 + (end.0 - start.0) * random_f64_range(0.6, 0.8) + random_f64_range(-50.0, 50.0),
        start.1 + (end.1 - start.1) * random_f64_range(0.7, 1.0) + random_f64_range(-50.0, 50.0),
    );

    let mut points = Vec::with_capacity(num_points);

    for i in 0..num_points {
        let t = i as f64 / (num_points - 1) as f64;
        let t2 = t * t;
        let t3 = t2 * t;
        let mt = 1.0 - t;
        let mt2 = mt * mt;
        let mt3 = mt2 * mt;

        // Clamp to >= 0 so we never dispatch a negative mouse position.
        let x =
            (mt3 * start.0 + 3.0 * mt2 * t * cp1.0 + 3.0 * mt * t2 * cp2.0 + t3 * end.0).max(0.0);
        let y =
            (mt3 * start.1 + 3.0 * mt2 * t * cp1.1 + 3.0 * mt * t2 * cp2.1 + t3 * end.1).max(0.0);

        points.push((x, y));
    }

    points
}

/// Where a human path starts: the real pointer, or for an untouched page a
/// random point inside the viewport.
fn approach_start(pointer: Option<Point>, viewport: Point) -> Point {
    pointer.unwrap_or_else(|| {
        (
            random_f64_range(0.0, viewport.0.max(1.0)),
            random_f64_range(0.0, viewport.1.max(1.0)),
        )
    })
}

/// Where wheel events land: the real pointer, or the viewport centre.
fn scroll_origin(pointer: Option<Point>, viewport: Point) -> Point {
    pointer.unwrap_or((viewport.0 / 2.0, viewport.1 / 2.0))
}

/// Human-like interaction helpers
pub struct Human<'a> {
    session: &'a Session,
    speed: HumanSpeed,
    pending_releases: Mutex<Vec<PendingRelease>>,
    cleanup_wait: tokio::sync::Mutex<()>,
}

impl<'a> Human<'a> {
    /// Create a Human helper whose input shares the session's Page coordinator.
    pub fn new(session: &'a Session) -> Self {
        Self {
            session,
            speed: HumanSpeed::Normal,
            pending_releases: Mutex::new(Vec::new()),
            cleanup_wait: tokio::sync::Mutex::new(()),
        }
    }

    /// Set the speed mode
    pub fn with_speed(mut self, speed: HumanSpeed) -> Self {
        self.speed = speed;
        self
    }

    /// `choose` applied to the last dispatched pointer position on this
    /// target (shared with Page input) and the viewport, which is only
    /// measured when no pointer position is known.
    async fn pointer_point(&self, choose: fn(Option<Point>, Point) -> Point) -> Point {
        let pointer = self.session.held_input().lock().await.pointer();
        let viewport = match pointer {
            Some(_) => (0.0, 0.0),
            None => self.viewport().await,
        };
        choose(pointer, viewport)
    }

    /// CSS layout viewport size; a desktop default when metrics are unavailable.
    async fn viewport(&self) -> Point {
        let metrics: Result<serde_json::Value> = self
            .session
            .send("Page.getLayoutMetrics", &serde_json::json!({}))
            .await;
        metrics
            .ok()
            .and_then(|m| {
                let viewport = &m["cssLayoutViewport"];
                Some((
                    viewport["clientWidth"].as_f64()?,
                    viewport["clientHeight"].as_f64()?,
                ))
            })
            .filter(|(w, h)| *w > 0.0 && *h > 0.0)
            .unwrap_or((1280.0, 720.0))
    }

    /// Move mouse to target position with human-like Bezier curve, starting
    /// from the last dispatched pointer position.
    pub async fn move_to(&self, target_x: f64, target_y: f64) -> Result<()> {
        let (start_x, start_y) = self.pointer_point(approach_start).await;

        let distance = ((target_x - start_x).powi(2) + (target_y - start_y).powi(2)).sqrt();
        let num_points = self.speed.mouse_points(distance);
        let (min_delay, max_delay) = self.speed.move_delay_ms();

        let path = bezier_curve((start_x, start_y), (target_x, target_y), num_points);

        for (x, y) in path {
            self.mouse_move(x, y).await?;
            pause(min_delay, max_delay).await;
        }

        Ok(())
    }

    /// Move mouse to target and click
    pub async fn move_and_click(&self, target_x: f64, target_y: f64) -> Result<()> {
        self.move_to(target_x, target_y).await?;

        // Small delay before click
        pause(50, 150).await;

        // Click with slight jitter
        let click_x = target_x + random_f64_range(-2.0, 2.0);
        let click_y = target_y + random_f64_range(-2.0, 2.0);

        self.mouse_down(click_x, click_y).await?;

        pause(50, 120).await;

        self.mouse_up(click_x, click_y).await?;

        // Small delay after click
        pause(30, 100).await;

        Ok(())
    }

    async fn mouse_move(&self, x: f64, y: f64) -> Result<()> {
        coordinated_mouse_move(self.session, x, y).await
    }

    async fn mouse_down(&self, x: f64, y: f64) -> Result<()> {
        coordinated_mouse_down(self.session, x, y, MouseButton::Left).await
    }

    async fn mouse_up(&self, x: f64, y: f64) -> Result<()> {
        coordinated_mouse_up(self.session, x, y, MouseButton::Left).await
    }

    async fn mouse_wheel(&self, x: f64, y: f64, delta_x: f64, delta_y: f64) -> Result<()> {
        coordinated_mouse_wheel(self.session, x, y, delta_x, delta_y).await
    }

    /// Drag by signed `dx` pixels with easing, Y jitter and optional overshoot.
    /// Exclusively holds the target input coordinator until release, preserving
    /// other buttons and rejecting an already-held left button.
    /// Cancellation schedules a bounded release; retain this helper and call
    /// [`Human::finish_drag_cleanup`] before further input.
    pub async fn drag_by(&self, x: f64, y: f64, dx: f64) -> Result<()> {
        validate_drag(x, y, dx)?;
        let mut release = self.approach_drag(x, y).await?;
        pause(80, 200).await;
        let moved = async {
            release.press().await?;
            pause(60, 140).await;

            let overshoot = if dx.abs() > 40.0 {
                random_f64_range(4.0, 14.0).min(dx.abs() * 0.3) * dx.signum()
            } else {
                0.0
            };

            let target_x = (x + dx).max(0.0);
            let over_x = (x + dx + overshoot).max(0.0);
            let end_y = (y + random_f64_range(-3.0, 3.0)).max(0.0);

            let distance = (over_x - x).abs();
            let num_points = self.speed.mouse_points(distance);
            let (min_delay, max_delay) = self.speed.move_delay_ms();

            let path = bezier_curve((x, y), (over_x, end_y), num_points);

            // Increase delays toward the endpoint.
            let n = path.len().max(2);
            for (i, (px, py)) in path.into_iter().enumerate() {
                let t = i as f64 / (n - 1) as f64;
                let jitter_y = if i > 0 && i < n - 1 {
                    random_f64_range(-1.5, 1.5)
                } else {
                    0.0
                };
                release.move_to(px, (py + jitter_y).max(0.0)).await?;
                let delay = random_range(min_delay, max_delay);
                #[allow(
                    clippy::cast_possible_truncation,
                    clippy::cast_sign_loss,
                    reason = "a non-negative delay of at most 50ms scaled by at most 2.5"
                )]
                let eased = (delay as f64 * (0.5 + 2.0 * t * t)) as u64;
                sleep(Duration::from_millis(eased.max(min_delay))).await;
            }

            if overshoot != 0.0 {
                pause(60, 150).await;
                let settle_points = random_range(3, 6);
                for i in 1..=settle_points {
                    let t = i as f64 / settle_points as f64;
                    let sx = over_x + (target_x - over_x) * t;
                    let sy = (end_y + (y - end_y) * t + random_f64_range(-0.8, 0.8)).max(0.0);
                    release.move_to(sx.max(0.0), sy).await?;
                    pause(20, 60).await;
                }
            }

            pause(30, 100).await;
            release.x = target_x;
            release.y = y;
            Ok(())
        }
        .await;
        release.release().await.and(moved)
    }

    /// Drag on a horizontal track without overshoot, reversal or vertical drift.
    /// Intended for bounded sliders whose target is the end of the track.
    /// Shares the ownership and cancellation contract of [`Human::drag_by`].
    pub async fn drag_horizontal_by(&self, x: f64, y: f64, dx: f64) -> Result<()> {
        validate_drag(x, y, dx)?;
        let mut release = self.approach_drag(x, y).await?;
        sleep(Duration::from_millis(100)).await;
        let moved = async {
            release.press().await?;
            let (points, delay) = match self.speed {
                HumanSpeed::Fast => (25, 20),
                HumanSpeed::Normal => (60, 20),
                HumanSpeed::Slow => (100, 25),
            };
            sleep(Duration::from_millis(100)).await;
            for i in 1..=points {
                let t = f64::from(i) / f64::from(points);
                let next_x = x + dx * (t * t * (3.0 - 2.0 * t));
                release.move_to(next_x, y).await?;
                sleep(Duration::from_millis(delay)).await;
            }
            Ok(())
        }
        .await;
        release.release().await.and(moved)
    }

    /// Type text with human-like timing
    pub async fn type_text(&self, text: &str) -> Result<()> {
        let (min_delay, max_delay) = self.speed.type_delay_ms();

        for ch in text.chars() {
            // Type through the shared key coordinator so held modifiers are
            // reflected in the native CDP event.
            coordinated_key_char(self.session, &ch.to_string()).await?;

            // Variable delay based on character
            let base_delay = if ch == ' ' {
                random_range(min_delay + 30, max_delay + 30)
            } else if ch.is_ascii_punctuation() {
                random_range(min_delay + 50, max_delay + 50)
            } else {
                random_range(min_delay, max_delay)
            };

            // Occasional thinking pause
            let delay = if matches!(self.speed, HumanSpeed::Normal | HumanSpeed::Slow)
                && random_bool(0.05)
            {
                base_delay + random_range(200, 500)
            } else {
                base_delay
            };

            sleep(Duration::from_millis(delay)).await;

            // Occasional typo (slow mode only)
            if matches!(self.speed, HumanSpeed::Slow) && random_bool(0.01) && text.len() > 10 {
                #[allow(
                    clippy::cast_possible_truncation,
                    reason = "random_range(0, 26) is below 26"
                )]
                let wrong_char = (b'a' + random_range(0, 26) as u8) as char;
                coordinated_key_char(self.session, &wrong_char.to_string()).await?;
                pause(100, 300).await;

                // Backspace through the shared held-key coordinator.
                coordinated_key_down(self.session, "Backspace").await?;
                coordinated_key_up(self.session, "Backspace").await?;
                pause(50, 150).await;
            }
        }

        Ok(())
    }

    /// Press a key through the session's held-key coordinator.
    pub async fn press_key(&self, key: &str) -> Result<()> {
        coordinated_key_down(self.session, key).await?;
        pause(50, 100).await;
        coordinated_key_up(self.session, key).await
    }

    /// Scroll the page by delta_y pixels (positive = down, negative = up).
    /// Wheel events land at the current pointer, or the viewport centre when
    /// no pointer position is known yet.
    pub async fn scroll(&self, delta_y: f64) -> Result<()> {
        let num_scrolls = random_range(3, 8);
        let per_scroll = delta_y / num_scrolls as f64;
        let (x, y) = self.pointer_point(scroll_origin).await;

        for _ in 0..num_scrolls {
            let jitter = random_f64_range(-20.0, 20.0);
            let scroll_amount = per_scroll + jitter;

            self.mouse_wheel(x, y, 0.0, scroll_amount).await?;

            pause(30, 100).await;
        }

        Ok(())
    }
}

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

    #[test]
    fn test_bezier_curve_endpoints() {
        let start = (50.0, 75.0);
        let end = (200.0, 300.0);

        let points = bezier_curve(start, end, 10);

        let first = points.first().unwrap();
        assert!((first.0 - start.0).abs() < 0.001);
        assert!((first.1 - start.1).abs() < 0.001);

        let last = points.last().unwrap();
        assert!((last.0 - end.0).abs() < 0.001);
        assert!((last.1 - end.1).abs() < 0.001);
    }

    #[test]
    fn test_bezier_curve_clamps_to_nonnegative() {
        // Target very near the origin: the randomized control points can push
        // the raw cubic below zero, so every emitted point must be clamped to
        // >= 0 (and stay finite). Run many iterations since control points and
        // start offsets are randomized.
        for _ in 0..500 {
            let start = (0.0, 0.0);
            let end = (2.0, 2.0);
            let points = bezier_curve(start, end, 25);
            for (x, y) in points {
                assert!(x >= 0.0, "x should be clamped to >= 0, got {x}");
                assert!(y >= 0.0, "y should be clamped to >= 0, got {y}");
                assert!(x.is_finite(), "x should be finite, got {x}");
                assert!(y.is_finite(), "y should be finite, got {y}");
            }
        }
    }

    // Regression: paths started at a random point within 300px of the target
    // instead of the real pointer, so consecutive moves teleported, and wheel
    // events landed at random coordinates regardless of pointer or viewport.
    #[test]
    fn test_paths_and_scrolls_start_at_the_known_pointer() {
        let viewport = (800.0, 600.0);
        assert_eq!(approach_start(Some((12.0, 34.0)), viewport), (12.0, 34.0));
        for _ in 0..200 {
            let (x, y) = approach_start(None, viewport);
            assert!((0.0..800.0).contains(&x) && (0.0..600.0).contains(&y));
        }
        assert_eq!(scroll_origin(Some((5.0, 6.0)), viewport), (5.0, 6.0));
        assert_eq!(scroll_origin(None, (640.0, 360.0)), (320.0, 180.0));
    }

    #[test]
    fn test_human_speed_mouse_points() {
        let distance = 500.0;

        let fast = HumanSpeed::Fast.mouse_points(distance);
        let normal = HumanSpeed::Normal.mouse_points(distance);
        let slow = HumanSpeed::Slow.mouse_points(distance);

        assert!(fast < normal);
        assert!(normal < slow);
    }
}