captchaforge 0.2.36

[DO NOT USE — UNDER ACTIVE DEVELOPMENT, NOT PRODUCTION-READY] Captcha solver scaffolding for chromiumoxide-driven browsers. The architecture is in place (vendor solvers, retry-loop iframe walking, VLM provider abstraction, real-WAF bench harness) but the live-vendor success rate is still 0% — Cloudflare Turnstile / hCaptcha / reCAPTCHA detect us at a TLS / CDP fingerprint layer that no flag-based stealth has cleared. Watch the repo; do not depend on this for any real workload.
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
/// Human behavior simulation — realistic mouse, keyboard, and scroll patterns.
///
/// Anti-bot detectors analyze:
///   - Mouse trajectory (bots move in straight lines)
///   - Typing cadence (bots type at constant speed)
///   - Scroll patterns (bots scroll uniformly)
///   - Idle time (bots never pause)
///
/// This module generates Bézier-curve mouse paths, variable typing delays,
/// and natural scroll increments. All async fns use SmallRng (Send-safe) so
/// futures remain Send-compatible for multi-threaded Tokio runtimes.
use chromiumoxide::cdp::browser_protocol::input::{
    DispatchKeyEventParams, DispatchKeyEventType, DispatchMouseEventParams, DispatchMouseEventType,
    MouseButton,
};
use chromiumoxide::Page;
use rand::{Rng, SeedableRng};
use std::time::Duration;

/// Move mouse along a Bézier curve from (x0,y0) to (x1,y1).
/// Generates 8-20 intermediate points with realistic timing.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::mouse_move_bezier;
/// # async fn example(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// mouse_move_bezier(page, 0.0, 0.0, 400.0, 300.0).await?;
/// # Ok(()) }
/// ```
pub async fn mouse_move_bezier(
    page: &Page,
    x0: f64,
    y0: f64,
    x1: f64,
    y1: f64,
) -> anyhow::Result<()> {
    let mut rng = rand::rngs::StdRng::from_entropy();
    let steps = rng.gen_range(8..=20);

    // Two random control points for the cubic Bézier
    let cx1 = x0 + (x1 - x0) * rng.gen_range(0.2..0.5) + rng.gen_range(-30.0..30.0);
    let cy1 = y0 + (y1 - y0) * rng.gen_range(0.1..0.4) + rng.gen_range(-20.0..20.0);
    let cx2 = x0 + (x1 - x0) * rng.gen_range(0.6..0.9) + rng.gen_range(-20.0..20.0);
    let cy2 = y0 + (y1 - y0) * rng.gen_range(0.5..0.8) + rng.gen_range(-15.0..15.0);

    for i in 0..=steps {
        let t = i as f64 / steps as f64;
        let u = 1.0 - t;

        // Cubic Bézier: B(t) = (1-t)³P0 + 3(1-t)²tP1 + 3(1-t)t²P2 + t³P3
        let x = u * u * u * x0 + 3.0 * u * u * t * cx1 + 3.0 * u * t * t * cx2 + t * t * t * x1;
        let y = u * u * u * y0 + 3.0 * u * u * t * cy1 + 3.0 * u * t * t * cy2 + t * t * t * y1;

        let params = DispatchMouseEventParams::builder()
            .r#type(DispatchMouseEventType::MouseMoved)
            .x(x)
            .y(y)
            .build()
            .map_err(anyhow::Error::msg)?;
        page.execute(params).await?;

        // Variable delay: faster in middle, slower at start/end (ease-in-out)
        let ease = (std::f64::consts::PI * t).sin(); // 0 at endpoints, 1 at midpoint
        let base_ms = rng.gen_range(8..25);
        let delay_ms = base_ms + ((1.0 - ease) * 15.0) as u64;
        tokio::time::sleep(Duration::from_millis(delay_ms)).await;
    }

    Ok(())
}

/// Move along a real-human recorded trajectory rather than a parametric
/// Bézier. Modern bot detectors (Akamai, DataDome, PerimeterX) train
/// classifiers on per-event features that distinguish parametric
/// curves from biomechanical motion — see [`crate::mouse_traces`] for
/// the full motivation.
///
/// Picks a random trace from the bundled library, rotates and scales
/// it onto the requested `(x0, y0) → (x1, y1)`, and dispatches one
/// mouse-event per trace point with the recorded inter-event delay
/// and ±1.5 px per-axis jitter.
///
/// Per-call cost depends on the picked trace — short-direct
/// (`direct_fast`, ~370ms) to long-careful (`slow_careful`, ~750ms).
/// Use [`mouse_move_bezier`] when you need a tight upper bound on
/// move time; use this when staying inside the detector envelope
/// matters more than ~hundreds-of-ms tail latency.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::mouse_move_human;
/// # async fn example(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// mouse_move_human(page, 0.0, 0.0, 400.0, 300.0).await?;
/// # Ok(()) }
/// ```
pub async fn mouse_move_human(
    page: &Page,
    x0: f64,
    y0: f64,
    x1: f64,
    y1: f64,
) -> anyhow::Result<()> {
    let mut rng = rand::rngs::StdRng::from_entropy();
    let trace = crate::mouse_traces::pick_trace(&mut rng);
    crate::mouse_traces::replay_trace(page, x0, y0, x1, y1, trace, 1.5).await
}

/// Click at position with realistic mouse-down delay.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::click_realistic;
/// # async fn example(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// click_realistic(page, 200.0, 150.0).await?;
/// # Ok(()) }
/// ```
pub async fn click_realistic(page: &Page, x: f64, y: f64) -> anyhow::Result<()> {
    let mut rng = rand::rngs::StdRng::from_entropy();

    // Mouse down
    let down = DispatchMouseEventParams::builder()
        .r#type(DispatchMouseEventType::MousePressed)
        .x(x)
        .y(y)
        .button(MouseButton::Left)
        .click_count(1)
        .build()
        .map_err(anyhow::Error::msg)?;
    page.execute(down).await?;

    // Realistic hold time: 50-150ms
    tokio::time::sleep(Duration::from_millis(rng.gen_range(50..150))).await;

    // Mouse up
    let up = DispatchMouseEventParams::builder()
        .r#type(DispatchMouseEventType::MouseReleased)
        .x(x)
        .y(y)
        .button(MouseButton::Left)
        .click_count(1)
        .build()
        .map_err(anyhow::Error::msg)?;
    page.execute(up).await?;

    Ok(())
}

/// Type text with human-like cadence: variable inter-key delays, occasional pauses.
/// Average typing speed: ~200ms per character (60 WPM) with variance.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::type_realistic;
/// # async fn example(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// type_realistic(page, "hello world").await?;
/// # Ok(()) }
/// ```
pub async fn type_realistic(page: &Page, text: &str) -> anyhow::Result<()> {
    let mut rng = rand::rngs::StdRng::from_entropy();

    for (i, ch) in text.chars().enumerate() {
        let key_text = ch.to_string();

        // Key down
        let down = DispatchKeyEventParams::builder()
            .r#type(DispatchKeyEventType::KeyDown)
            .text(&key_text)
            .build()
            .map_err(anyhow::Error::msg)?;
        page.execute(down).await?;

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

        // Key up
        let up = DispatchKeyEventParams::builder()
            .r#type(DispatchKeyEventType::KeyUp)
            .text(&key_text)
            .build()
            .map_err(anyhow::Error::msg)?;
        page.execute(up).await?;

        // Inter-key delay: 80-250ms with occasional longer pauses
        let base = rng.gen_range(80..250);
        let pause = if i > 0 && i % rng.gen_range(4..10) == 0 {
            rng.gen_range(200..600) // "thinking" pause every few characters
        } else {
            0
        };
        tokio::time::sleep(Duration::from_millis(base + pause)).await;
    }

    Ok(())
}

/// Type text with bigram-aware human keystroke timing.
///
/// Uses [`crate::keystroke_timing::plan_keystrokes`] to produce a
/// schedule whose per-bigram inter-key gaps and per-character
/// hold-times match real-human envelopes (Dhakal et al. CHI 2018
/// envelope), then dispatches each keydown/keyup with the planned
/// timing.
///
/// Compared to [`type_realistic`] (which uses uniform 80–250ms gaps):
///
/// - Hot bigrams (`th`, `he`, `in`, ...) are typed at 60–110ms
///   intervals — over-trained motor programs are FAST.
/// - Cold bigrams (`qz`, `xj`, ...) are typed at 180–320ms intervals.
/// - Digit-pairs use a slower envelope because the number row is
///   not over-trained.
/// - Optional typo injection: at low probability (1.5% by default),
///   types a QWERTY-neighbour wrong character then a backspace then
///   the correct character — exactly the pattern detectors look for
///   to confirm a human typist.
/// - Optional thinking pauses (200–600ms) at the configured rate.
///
/// Backspaces (Unicode BS, `\u{0008}`) emitted by the planner are
/// dispatched as the `Backspace` named key via CDP.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::type_human;
/// # async fn example(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// type_human(page, "the quick brown fox").await?;
/// # Ok(()) }
/// ```
pub async fn type_human(page: &Page, text: &str) -> anyhow::Result<()> {
    use crate::keystroke_timing::{plan_keystrokes, TypingPlan};
    let mut rng = rand::rngs::StdRng::from_entropy();
    let plan = plan_keystrokes(text, TypingPlan::default(), &mut rng);
    for k in plan {
        if k.gap_ms_before > 0 {
            tokio::time::sleep(Duration::from_millis(k.gap_ms_before as u64)).await;
        }
        let down_builder = if k.ch == '\u{0008}' {
            DispatchKeyEventParams::builder()
                .r#type(DispatchKeyEventType::KeyDown)
                .key("Backspace")
                .windows_virtual_key_code(8)
        } else {
            let key_text = k.ch.to_string();
            DispatchKeyEventParams::builder()
                .r#type(DispatchKeyEventType::KeyDown)
                .text(key_text)
        };
        page.execute(down_builder.build().map_err(anyhow::Error::msg)?)
            .await?;
        tokio::time::sleep(Duration::from_millis(k.hold_ms as u64)).await;
        let up_builder = if k.ch == '\u{0008}' {
            DispatchKeyEventParams::builder()
                .r#type(DispatchKeyEventType::KeyUp)
                .key("Backspace")
                .windows_virtual_key_code(8)
        } else {
            let key_text = k.ch.to_string();
            DispatchKeyEventParams::builder()
                .r#type(DispatchKeyEventType::KeyUp)
                .text(key_text)
        };
        page.execute(up_builder.build().map_err(anyhow::Error::msg)?)
            .await?;
    }
    Ok(())
}

/// Scroll with human-like pattern: variable speed, direction micro-corrections.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::{scroll_realistic, ScrollDirection};
/// # async fn example(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// scroll_realistic(page, ScrollDirection::Down, 500).await?;
/// # Ok(()) }
/// ```
pub async fn scroll_realistic(
    page: &Page,
    direction: ScrollDirection,
    amount: u32,
) -> anyhow::Result<()> {
    let mut rng = rand::rngs::StdRng::from_entropy();
    let steps = rng.gen_range(3..=8).min(amount);
    let per_step = (amount as f64 / steps as f64) as i32;

    for _ in 0..steps {
        let delta = match direction {
            ScrollDirection::Down => per_step + rng.gen_range(-20..20),
            ScrollDirection::Up => -(per_step + rng.gen_range(-20..20)),
        };

        let js = format!("window.scrollBy(0, {})", delta);
        page.evaluate(js).await?;

        // Variable scroll delay: 100-400ms
        tokio::time::sleep(Duration::from_millis(rng.gen_range(100..400))).await;
    }

    Ok(())
}

/// Random idle pause — simulates reading/thinking time.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::idle_pause;
///
/// # async fn example() {
/// idle_pause().await;
/// # }
/// ```
pub async fn idle_pause() {
    let ms = rand::rngs::StdRng::from_entropy().gen_range(500..2000);
    tokio::time::sleep(Duration::from_millis(ms)).await;
}

/// Short micro-pause between actions (100-400ms).
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::micro_pause;
///
/// # async fn example() {
/// micro_pause().await;
/// # }
/// ```
pub async fn micro_pause() {
    let ms = rand::rngs::StdRng::from_entropy().gen_range(100..400);
    tokio::time::sleep(Duration::from_millis(ms)).await;
}

/// Pause for a uniformly-random duration in `[min_ms, max_ms]`.
///
/// General-purpose human-pacing primitive that complements
/// [`idle_pause`] (1-3s) and [`micro_pause`] (100-400ms) — pick this
/// when you need a specific window without doing the maths yourself.
/// Panics if `min_ms > max_ms`.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::random_pause;
/// # async fn run() {
/// random_pause(150, 600).await;
/// # }
/// ```
pub async fn random_pause(min_ms: u64, max_ms: u64) {
    assert!(
        min_ms <= max_ms,
        "random_pause: min_ms ({min_ms}) > max_ms ({max_ms})"
    );
    if min_ms == max_ms {
        tokio::time::sleep(Duration::from_millis(min_ms)).await;
        return;
    }
    let ms = rand::rngs::StdRng::from_entropy().gen_range(min_ms..=max_ms);
    tokio::time::sleep(Duration::from_millis(ms)).await;
}

/// Triple-click at `(x, y)` to select all text in an input/textarea.
///
/// Shortcut for "select-all-then-type" patterns common when filling
/// captcha answer fields that pre-populate with placeholder text.
/// Three real CDP `MousePressed`/`MouseReleased` pairs at the same
/// coordinate with the click counter incrementing each time — that's
/// what chromium uses to detect a triple-click and apply line-select.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::triple_click;
/// # async fn run(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// triple_click(page, 320.0, 200.0).await?;
/// # Ok(()) }
/// ```
pub async fn triple_click(page: &Page, x: f64, y: f64) -> anyhow::Result<()> {
    use chromiumoxide::cdp::browser_protocol::input::DispatchMouseEventParams;
    for click_count in 1i64..=3 {
        let down = DispatchMouseEventParams::builder()
            .r#type(DispatchMouseEventType::MousePressed)
            .x(x)
            .y(y)
            .button(MouseButton::Left)
            .click_count(click_count)
            .build()
            .map_err(anyhow::Error::msg)?;
        page.execute(down).await?;
        let up = DispatchMouseEventParams::builder()
            .r#type(DispatchMouseEventType::MouseReleased)
            .x(x)
            .y(y)
            .button(MouseButton::Left)
            .click_count(click_count)
            .build()
            .map_err(anyhow::Error::msg)?;
        page.execute(up).await?;
        // Real triple-clicks land within ~80-120ms of each other;
        // anything beyond ~250ms triggers a click + double-click +
        // single-click rather than the line-select gesture.
        tokio::time::sleep(Duration::from_millis(60)).await;
    }
    Ok(())
}

/// Hover the mouse over a viewport coordinate WITHOUT clicking, then
/// dwell for 200-700ms — triggers `mouseenter` / `mouseover` listeners
/// that anti-bot widgets watch for to confirm the visitor's pointer
/// is actually traversing the page (real users rest the cursor on
/// elements; bots warp to coordinates and click).
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::hover_dwell;
/// # async fn run(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// hover_dwell(page, 320.0, 240.0).await?;
/// # Ok(()) }
/// ```
pub async fn hover_dwell(page: &Page, x: f64, y: f64) -> anyhow::Result<()> {
    use chromiumoxide::cdp::browser_protocol::input::DispatchMouseEventParams;
    let mv = DispatchMouseEventParams::builder()
        .r#type(DispatchMouseEventType::MouseMoved)
        .x(x)
        .y(y)
        .build()
        .map_err(anyhow::Error::msg)?;
    page.execute(mv).await?;
    let ms = rand::rngs::StdRng::from_entropy().gen_range(200..700);
    tokio::time::sleep(Duration::from_millis(ms)).await;
    Ok(())
}

/// Touch-style swipe gesture between two viewport coordinates.
///
/// Unlike a desktop drag, mobile swipes have higher initial velocity
/// and a brief decelerating tail. Useful for slider widgets in mobile
/// stealth profiles ([`crate::stealth_profiles::StealthProfile::SafariIphone`],
/// [`crate::stealth_profiles::StealthProfile::ChromeAndroid`]).
///
/// `duration_ms` controls the total swipe time (typical 250-500ms for
/// a fast gesture, 700-1200ms for a deliberate one). 25 sub-steps
/// gives a smooth-enough trajectory without spamming events.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::touch_swipe;
/// # async fn run(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// // Swipe a slider knob 280px to the right.
/// touch_swipe(page, 40.0, 200.0, 320.0, 200.0, 350).await?;
/// # Ok(()) }
/// ```
pub async fn touch_swipe(
    page: &Page,
    x0: f64,
    y0: f64,
    x1: f64,
    y1: f64,
    duration_ms: u64,
) -> anyhow::Result<()> {
    use chromiumoxide::cdp::browser_protocol::input::DispatchMouseEventParams;
    let down = DispatchMouseEventParams::builder()
        .r#type(DispatchMouseEventType::MousePressed)
        .x(x0)
        .y(y0)
        .button(MouseButton::Left)
        .click_count(1)
        .build()
        .map_err(anyhow::Error::msg)?;
    page.execute(down).await?;
    let steps = 25;
    let step_ms = (duration_ms / steps as u64).max(8);
    for s in 1..=steps {
        // Ease-out: faster at start, slower at end.
        let t = s as f64 / steps as f64;
        let eased = 1.0 - (1.0 - t).powi(2);
        let x = x0 + (x1 - x0) * eased;
        let y = y0 + (y1 - y0) * eased;
        let mv = DispatchMouseEventParams::builder()
            .r#type(DispatchMouseEventType::MouseMoved)
            .x(x)
            .y(y)
            .build()
            .map_err(anyhow::Error::msg)?;
        page.execute(mv).await?;
        tokio::time::sleep(Duration::from_millis(step_ms)).await;
    }
    let up = DispatchMouseEventParams::builder()
        .r#type(DispatchMouseEventType::MouseReleased)
        .x(x1)
        .y(y1)
        .button(MouseButton::Left)
        .click_count(1)
        .build()
        .map_err(anyhow::Error::msg)?;
    page.execute(up).await?;
    Ok(())
}

/// Scrub the mouse along a sinusoidal jitter path while standing
/// still — simulates the imperceptible micro-tremor of a real
/// pointing device that anti-bot heuristics use as a humanity signal.
///
/// `cycles` of ±2-4px around the centroid over `cycle_ms` each.
/// 3 cycles × 80ms is a good default; longer dwells benefit from 5-8
/// cycles. Runs synchronously from the CDP perspective but yields
/// to the runtime between events so the page can process them.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::behavior::pointer_jitter;
/// # async fn run(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// pointer_jitter(page, 400.0, 300.0, 5, 80).await?;
/// # Ok(()) }
/// ```
#[cfg(test)]
mod random_pause_tests {
    use super::*;
    use std::time::Instant;

    #[tokio::test]
    async fn random_pause_returns_within_window() {
        let start = Instant::now();
        random_pause(50, 80).await;
        let elapsed_ms = start.elapsed().as_millis() as u64;
        // Allow a generous +50ms scheduler tolerance — tokio sleeps
        // are "at least", not "exactly".
        assert!(
            (50..=130).contains(&elapsed_ms),
            "random_pause(50, 80) elapsed {elapsed_ms}ms (expected 50..=130)"
        );
    }

    #[tokio::test]
    async fn random_pause_with_equal_bounds_does_not_panic() {
        let start = Instant::now();
        random_pause(40, 40).await;
        let elapsed_ms = start.elapsed().as_millis() as u64;
        assert!(elapsed_ms >= 40);
    }

    #[tokio::test]
    #[should_panic(expected = "random_pause: min_ms")]
    async fn random_pause_panics_when_min_exceeds_max() {
        random_pause(200, 100).await;
    }
}

pub async fn pointer_jitter(
    page: &Page,
    cx: f64,
    cy: f64,
    cycles: u32,
    cycle_ms: u64,
) -> anyhow::Result<()> {
    use chromiumoxide::cdp::browser_protocol::input::DispatchMouseEventParams;
    let mut rng = rand::rngs::StdRng::from_entropy();
    for c in 0..cycles {
        let amp_x: f64 = rng.gen_range(2.0..4.5);
        let amp_y: f64 = rng.gen_range(2.0..4.5);
        let phase: f64 = rng.gen_range(0.0..std::f64::consts::TAU);
        let steps = 8u64;
        for s in 0..steps {
            let theta = phase + (c as f64 + s as f64 / steps as f64) * std::f64::consts::TAU;
            let x = cx + amp_x * theta.sin();
            let y = cy + amp_y * (theta * 1.7).cos();
            let mv = DispatchMouseEventParams::builder()
                .r#type(DispatchMouseEventType::MouseMoved)
                .x(x)
                .y(y)
                .build()
                .map_err(anyhow::Error::msg)?;
            page.execute(mv).await?;
            tokio::time::sleep(Duration::from_millis(cycle_ms / steps)).await;
        }
    }
    Ok(())
}

/// Direction for realistic scroll simulation.
///
/// # Example
///
/// ```
/// use captchaforge::behavior::ScrollDirection;
///
/// let down = ScrollDirection::Down;
/// let up = ScrollDirection::Up;
/// assert_ne!(down, up);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollDirection {
    Up,
    Down,
}

#[cfg(test)]
mod tests {
    #[test]
    fn bezier_control_points_within_range() {
        let (x0, _y0) = (100.0, 200.0);
        let (x1, _y1) = (500.0, 400.0);
        let t0 = 0.0_f64;
        let t1 = 1.0_f64;
        let u0 = 1.0 - t0;
        let u1 = 1.0 - t1;
        let bx0 = u0.powi(3) * x0 + t0.powi(3) * x1;
        let bx1 = u1.powi(3) * x0 + t1.powi(3) * x1;
        assert!((bx0 - x0).abs() < 0.001);
        assert!((bx1 - x1).abs() < 0.001);
    }

    use super::*;

    #[test]
    fn scroll_direction_clone_copy() {
        let d = ScrollDirection::Down;
        let d2 = d;
        assert_eq!(d, d2);
    }

    #[test]
    fn scroll_direction_debug() {
        let d = ScrollDirection::Up;
        assert!(format!("{:?}", d).contains("Up"));
    }

    #[test]
    fn bezier_midpoint_t_0_5() {
        let x0 = 0.0;
        let y0 = 0.0;
        let x1 = 100.0;
        let y1 = 0.0;
        let cx1 = 25.0;
        let cy1 = 50.0;
        let cx2 = 75.0;
        let cy2 = 50.0;
        let t = 0.5;
        let u = 1.0 - t;
        let x = u * u * u * x0 + 3.0 * u * u * t * cx1 + 3.0 * u * t * t * cx2 + t * t * t * x1;
        let y = u * u * u * y0 + 3.0 * u * u * t * cy1 + 3.0 * u * t * t * cy2 + t * t * t * y1;
        assert!((x - 50.0_f64).abs() < 1.0);
        assert!((y - 37.5_f64).abs() < 1.0);
    }

    #[test]
    fn bezier_is_linear_when_control_points_on_line() {
        let x0 = 0.0;
        let x1 = 100.0;
        let cx1 = 33.0;
        let cx2 = 66.0;
        for i in 0..=10 {
            let t = i as f64 / 10.0;
            let u = 1.0 - t;
            let x = u * u * u * x0 + 3.0 * u * u * t * cx1 + 3.0 * u * t * t * cx2 + t * t * t * x1;
            assert!((x - (t * 100.0)).abs() < 1.0, "t={} x={}", t, x);
        }
    }

    #[test]
    fn ease_function_zero_at_endpoints() {
        let ease_0 = (std::f64::consts::PI * 0.0).sin();
        let ease_1 = (std::f64::consts::PI * 1.0).sin();
        assert!((ease_0).abs() < 0.001);
        assert!((ease_1).abs() < 0.001);
    }

    #[test]
    fn ease_function_max_at_midpoint() {
        let ease = (std::f64::consts::PI * 0.5).sin();
        assert!((ease - 1.0).abs() < 0.001);
    }

    #[test]
    fn bezier_formula_degenerate_case_same_point() {
        let x0 = 50.0;
        let x1 = 50.0;
        let cx1 = 50.0;
        let cx2 = 50.0;
        for i in 0..=10 {
            let t = i as f64 / 10.0;
            let u = 1.0 - t;
            let x = u * u * u * x0 + 3.0 * u * u * t * cx1 + 3.0 * u * t * t * cx2 + t * t * t * x1;
            assert!((x - 50.0).abs() < 0.001);
        }
    }
}