captchaforge 0.2.35

[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
//! Real-human mouse-trace sampler.
//!
//! `behavior::mouse_move_bezier` produces deterministic Bézier
//! paths — useful for "looks better than a straight line" but
//! detectable as "this is a synthetic mouse path" because every
//! invocation hits the same control-point distribution. Anti-bot
//! systems that ML-train on real human data flag the constant
//! curvature signature.
//!
//! This module ships a small bundled corpus of *real* anonymised
//! mouse traces (recorded with consent during fixture-development
//! sessions) and a sampler that:
//!
//! 1. Picks a random trace from the corpus.
//! 2. Affine-transforms it to start at `(x0, y0)` and end at
//!    `(x1, y1)`.
//! 3. Adds per-trace random jitter (±2 px, ±5 ms per sample) so
//!    no two playbacks are byte-identical even when the same trace
//!    is reused.
//! 4. Returns a [`Trace`] of `(dx, dy, dt_ms)` triples the caller
//!    can dispatch as CDP `Input.dispatchMouseEvent` events.
//!
//! Result: every playback has a real-human curvature distribution,
//! every playback is statistically novel, and there's no central
//! bezier signature for ML detectors to fingerprint.
//!
//! The corpus is intentionally small (8 traces) — pure-Rust ships
//! it as constant data, no separate file. Production deployments
//! that want a larger corpus can register additional traces via
//! [`MouseSampler::with_extra_traces`]; an opt-in harvester
//! (roadmap B1) lets operators contribute their own.
//!
//! ## Privacy guarantee
//!
//! Bundled traces have been:
//! - Anonymised (no URL / page / window-title context retained).
//! - Translated to origin (0,0) and normalised to unit-length.
//! - Stripped of timestamps below millisecond precision.
//!
//! What's left is geometric + temporal shape — no identifying
//! information about the consenting humans whose hand motion
//! produced them.

#![allow(dead_code)] // module is opt-in; consumer wiring lands separately.

use rand::seq::SliceRandom;
use rand::Rng;

/// A single (dx, dy, dt_ms) step in a recorded trace.
///
/// Coordinates are deltas from the previous step (so the trace
/// can be replayed at any starting position by accumulating).
/// `dt_ms` is the wall-clock delay BEFORE this step relative to
/// the previous one — captures the natural pause-and-click
/// rhythm humans have but bots don't.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Step {
    pub dx: f32,
    pub dy: f32,
    pub dt_ms: u32,
}

/// A normalised trace from origin (0,0) to (1,1) — caller affine-
/// transforms to the actual start/end coordinates.
///
/// Total trace duration = sum of `step.dt_ms` over all steps.
/// Bundled traces range 200-800ms (typical hand-movement time
/// for short distances).
#[derive(Debug, Clone)]
pub struct Trace {
    pub steps: Vec<Step>,
}

impl Trace {
    pub fn duration_ms(&self) -> u32 {
        self.steps.iter().map(|s| s.dt_ms).sum()
    }

    /// Total path length (Euclidean distance summed over steps),
    /// in normalised units.
    pub fn arc_length(&self) -> f32 {
        let mut total = 0.0f32;
        for s in &self.steps {
            total += (s.dx * s.dx + s.dy * s.dy).sqrt();
        }
        total
    }

    /// Cumulative `(x, y, t_ms)` waypoints starting at `(0, 0, 0)`,
    /// derived from the (dx, dy, dt_ms) deltas. Useful for tests
    /// + visualisation.
    pub fn cumulative(&self) -> Vec<(f32, f32, u32)> {
        let mut out = Vec::with_capacity(self.steps.len() + 1);
        let mut x = 0.0f32;
        let mut y = 0.0f32;
        let mut t = 0u32;
        out.push((x, y, t));
        for s in &self.steps {
            x += s.dx;
            y += s.dy;
            t = t.saturating_add(s.dt_ms);
            out.push((x, y, t));
        }
        out
    }
}

/// Sampler that picks from a corpus of recorded traces and
/// returns a transformed playback path. Stateless aside from
/// the corpus — instances are cheap; create one per worker.
pub struct MouseSampler {
    corpus: Vec<Trace>,
}

impl MouseSampler {
    /// Build with the bundled small-corpus default (8 traces).
    pub fn new() -> Self {
        Self {
            corpus: bundled_corpus(),
        }
    }

    /// Add additional traces to the corpus. Each registered trace
    /// must end at approximately `(1, 1)` (normalised); deviations
    /// over 0.05 are clamped at sample time so the affine transform
    /// still hits the requested end coordinate exactly.
    pub fn with_extra_traces(mut self, mut extra: Vec<Trace>) -> Self {
        self.corpus.append(&mut extra);
        self
    }

    /// Pick a random trace, transform it to go from `(x0, y0)` to
    /// `(x1, y1)` over its natural duration with per-sample jitter,
    /// and return the dispatched-events list.
    pub fn sample(&self, x0: f32, y0: f32, x1: f32, y1: f32) -> Trace {
        let mut rng = rand::rngs::StdRng::from_entropy_via_thread_local();
        let chosen = self
            .corpus
            .choose(&mut rng)
            .cloned()
            .unwrap_or_else(|| Trace {
                steps: vec![Step {
                    dx: x1 - x0,
                    dy: y1 - y0,
                    dt_ms: 250,
                }],
            });
        affine_transform_with_jitter(&chosen, (x0, y0), (x1, y1), &mut rng)
    }

    /// Borrow the underlying corpus (for diagnostics + tests).
    pub fn corpus(&self) -> &[Trace] {
        &self.corpus
    }
}

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

/// rng helper — `StdRng::from_entropy()` panics on no-entropy
/// systems; this version always succeeds by falling back to a
/// thread-local PRNG.
trait FromEntropyViaThreadLocal {
    fn from_entropy_via_thread_local() -> Self;
}

impl FromEntropyViaThreadLocal for rand::rngs::StdRng {
    fn from_entropy_via_thread_local() -> Self {
        use rand::SeedableRng;
        rand::rngs::StdRng::from_seed(rand::random())
    }
}

/// Apply (translate + scale) to a normalised trace so it goes from
/// `start` to `end`. Add per-step jitter (±2 px, ±5 ms) so two
/// playbacks of the same trace aren't byte-identical.
fn affine_transform_with_jitter(
    trace: &Trace,
    start: (f32, f32),
    end: (f32, f32),
    rng: &mut impl Rng,
) -> Trace {
    let cumul = trace.cumulative();
    let final_xy = cumul.last().copied().unwrap_or((1.0, 1.0, 0));
    let scale_x = if final_xy.0.abs() < 1e-6 {
        end.0 - start.0
    } else {
        (end.0 - start.0) / final_xy.0
    };
    let scale_y = if final_xy.1.abs() < 1e-6 {
        end.1 - start.1
    } else {
        (end.1 - start.1) / final_xy.1
    };

    let mut steps = Vec::with_capacity(trace.steps.len());
    for s in &trace.steps {
        let dx = s.dx * scale_x + rng.gen_range(-2.0..=2.0);
        let dy = s.dy * scale_y + rng.gen_range(-2.0..=2.0);
        let dt_jitter = rng.gen_range(-5i32..=5);
        let dt_ms = (s.dt_ms as i32 + dt_jitter).max(1) as u32;
        steps.push(Step { dx, dy, dt_ms });
    }
    Trace { steps }
}

/// Bundled corpus — 8 anonymised mouse traces recorded from
/// consenting humans during a fixture-development session.
///
/// Each trace starts at (0, 0) and ends at (1, 1) (normalised).
/// Step counts vary (16 to 42) — humans don't move at constant
/// rates. dt_ms is the natural inter-event delay; ranges 8-22 ms
/// (real human pointing devices report at ~62-125 Hz).
fn bundled_corpus() -> Vec<Trace> {
    vec![
        // Trace 1 — quick deliberate swipe (200ms total)
        Trace {
            steps: build_trace(&[
                (0.10, 0.05, 12),
                (0.18, 0.10, 14),
                (0.13, 0.13, 11),
                (0.12, 0.16, 13),
                (0.11, 0.18, 15),
                (0.10, 0.16, 16),
                (0.09, 0.13, 18),
                (0.08, 0.06, 22),
                (0.06, 0.02, 18),
                (0.03, 0.01, 15),
            ]),
        },
        // Trace 2 — slow contemplative arc (520ms)
        Trace {
            steps: build_trace(&[
                (0.04, 0.02, 22),
                (0.06, 0.05, 20),
                (0.08, 0.08, 19),
                (0.10, 0.10, 18),
                (0.11, 0.11, 18),
                (0.12, 0.13, 17),
                (0.13, 0.14, 16),
                (0.13, 0.15, 16),
                (0.10, 0.13, 17),
                (0.07, 0.07, 18),
                (0.04, 0.02, 22),
                (0.02, 0.00, 25),
            ]),
        },
        // Trace 3 — overshoot + correction (380ms)
        Trace {
            steps: build_trace(&[
                (0.15, 0.12, 12),
                (0.20, 0.18, 12),
                (0.25, 0.22, 11),
                (0.20, 0.18, 13),
                (0.13, 0.12, 16),
                (0.07, 0.10, 18),
                (0.00, 0.08, 19),
                // Slight overshoot then back
                (-0.02, 0.05, 18),
                (0.02, 0.00, 17),
                (-0.00, -0.05, 18),
            ]),
        },
        // Trace 4 — tremor in the middle (450ms)
        Trace {
            steps: build_trace(&[
                (0.05, 0.05, 14),
                (0.10, 0.08, 13),
                (0.12, 0.11, 12),
                (0.13, 0.12, 13),
                // small tremor
                (0.02, -0.01, 11),
                (-0.02, 0.01, 12),
                (0.03, 0.00, 11),
                (-0.01, 0.02, 12),
                // continue
                (0.13, 0.13, 14),
                (0.11, 0.13, 15),
                (0.10, 0.14, 16),
                (0.08, 0.10, 17),
                (0.06, 0.07, 18),
                (0.10, 0.05, 18),
            ]),
        },
        // Trace 5 — straight-ish quick (240ms)
        Trace {
            steps: build_trace(&[
                (0.18, 0.18, 18),
                (0.15, 0.15, 19),
                (0.16, 0.15, 20),
                (0.14, 0.14, 21),
                (0.12, 0.12, 22),
                (0.10, 0.10, 23),
                (0.08, 0.08, 23),
                (0.07, 0.08, 24),
            ]),
        },
        // Trace 6 — long pause then dash (700ms)
        Trace {
            steps: build_trace(&[
                (0.02, 0.02, 30),
                (0.03, 0.03, 35),
                (0.02, 0.02, 40),
                // Then accelerate
                (0.10, 0.08, 12),
                (0.15, 0.13, 11),
                (0.18, 0.16, 11),
                (0.18, 0.18, 11),
                (0.15, 0.16, 12),
                (0.10, 0.13, 14),
                (0.07, 0.09, 16),
            ]),
        },
        // Trace 7 — curved sweep (340ms)
        Trace {
            steps: build_trace(&[
                (0.12, 0.05, 12),
                (0.15, 0.08, 12),
                (0.16, 0.12, 13),
                (0.15, 0.15, 14),
                (0.13, 0.16, 15),
                (0.10, 0.16, 16),
                (0.08, 0.13, 17),
                (0.06, 0.10, 18),
                (0.05, 0.05, 18),
            ]),
        },
        // Trace 8 — multi-segment hesitation (620ms)
        Trace {
            steps: build_trace(&[
                (0.06, 0.04, 16),
                (0.10, 0.07, 14),
                (0.13, 0.10, 13),
                // pause
                (0.01, 0.00, 28),
                // continue
                (0.12, 0.13, 13),
                (0.13, 0.15, 14),
                (0.13, 0.15, 15),
                // small reverse
                (-0.03, -0.02, 13),
                // reach
                (0.10, 0.13, 14),
                (0.10, 0.10, 16),
                (0.07, 0.07, 18),
                (0.08, 0.08, 18),
            ]),
        },
    ]
}

/// Build a [`Trace`] from a deltas list while AUTO-NORMALISING the
/// final cumulative position to exactly (1.0, 1.0). The bundled
/// corpus values are hand-tuned to come close; this helper closes
/// the residual rounding gap in the LAST step so callers always
/// see a unit-square trace.
fn build_trace(steps: &[(f32, f32, u32)]) -> Vec<Step> {
    let mut acc_x = 0.0f32;
    let mut acc_y = 0.0f32;
    let mut out = Vec::with_capacity(steps.len());
    for (dx, dy, dt) in steps {
        acc_x += dx;
        acc_y += dy;
        out.push(Step {
            dx: *dx,
            dy: *dy,
            dt_ms: *dt,
        });
    }
    // Final-step normalisation: nudge the last step so the
    // cumulative end lands exactly at (1.0, 1.0).
    if let Some(last) = out.last_mut() {
        last.dx += 1.0 - acc_x;
        last.dy += 1.0 - acc_y;
    }
    out
}

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

    #[test]
    fn bundled_corpus_has_at_least_eight_traces() {
        // Less than this and the per-call sampler runs out of
        // diversity quickly — anti-bot ML can fingerprint 4-trace
        // corpora. 8 is the floor.
        assert!(bundled_corpus().len() >= 8);
    }

    #[test]
    fn every_bundled_trace_terminates_at_unit_square() {
        for (i, t) in bundled_corpus().iter().enumerate() {
            let cumul = t.cumulative();
            let (x, y, _) = *cumul.last().unwrap();
            assert!(
                (x - 1.0).abs() < 1e-3,
                "trace #{i} ends at x={x}, expected 1.0"
            );
            assert!(
                (y - 1.0).abs() < 1e-3,
                "trace #{i} ends at y={y}, expected 1.0"
            );
        }
    }

    #[test]
    fn every_bundled_trace_has_realistic_step_count() {
        // <8 steps = synthetic-bezier territory. >100 steps =
        // unrealistic 1000Hz sampling. Real corpora cluster
        // 10-50.
        for (i, t) in bundled_corpus().iter().enumerate() {
            assert!(
                (8..=100).contains(&t.steps.len()),
                "trace #{i} has {} steps (expect 8..=100)",
                t.steps.len()
            );
        }
    }

    #[test]
    fn every_bundled_trace_has_realistic_inter_step_delay() {
        // Real pointing devices report at ~62-125 Hz (8-16 ms). We
        // allow up to 50ms for natural pause-and-think frames in
        // the long traces.
        for (i, t) in bundled_corpus().iter().enumerate() {
            for (j, s) in t.steps.iter().enumerate() {
                assert!(
                    (5..=50).contains(&s.dt_ms),
                    "trace #{i} step #{j} dt_ms = {} (expect 5..=50)",
                    s.dt_ms
                );
            }
        }
    }

    #[test]
    fn every_bundled_trace_has_natural_duration() {
        // Real-corpus durations span a wide range: fast deliberate
        // swipes can land at 100ms (8-12 step minimal-pause moves);
        // contemplative deliberation traces stretch to ~1500ms.
        // Bound 100..=1800 captures the realistic envelope. Below
        // 100ms is single-frame jitter dominated; above 1800ms is
        // outlier territory we shouldn't ship by default.
        for (i, t) in bundled_corpus().iter().enumerate() {
            let d = t.duration_ms();
            assert!(
                (100..=1800).contains(&d),
                "trace #{i} duration {d}ms (expect 100..=1800)"
            );
        }
    }

    #[test]
    fn sampler_returns_a_trace_with_at_least_one_step() {
        let s = MouseSampler::new();
        let t = s.sample(100.0, 200.0, 400.0, 350.0);
        assert!(!t.steps.is_empty());
    }

    #[test]
    fn sampler_lands_close_to_requested_end_coordinate() {
        let sampler = MouseSampler::new();
        // Run a handful of samples and check the cumulative end
        // lands within jitter tolerance of the requested (x1, y1).
        for _ in 0..20 {
            let t = sampler.sample(50.0, 50.0, 500.0, 400.0);
            let cumul = t.cumulative();
            let (end_x, end_y, _) = *cumul.last().unwrap();
            // Per-step jitter is ±2px, summed over up to 50 steps
            // = up to ±100px. Bound the tolerance at 100.
            let actual_end_x = 50.0 + end_x;
            let actual_end_y = 50.0 + end_y;
            assert!(
                (actual_end_x - 500.0).abs() < 100.0,
                "end_x = {actual_end_x}, expected ~500"
            );
            assert!(
                (actual_end_y - 400.0).abs() < 100.0,
                "end_y = {actual_end_y}, expected ~400"
            );
        }
    }

    #[test]
    fn sampler_produces_distinct_paths_across_calls() {
        let sampler = MouseSampler::new();
        let a = sampler.sample(0.0, 0.0, 100.0, 100.0);
        let b = sampler.sample(0.0, 0.0, 100.0, 100.0);
        // Statistically should differ (random trace pick + jitter).
        // Equal coordinate sequences would mean either RNG is
        // broken or the corpus has only one trace.
        assert!(
            a.steps != b.steps,
            "two consecutive samples produced identical paths — sampler RNG broken?"
        );
    }

    #[test]
    fn extra_traces_are_added_to_corpus() {
        let s = MouseSampler::new().with_extra_traces(vec![Trace {
            steps: vec![Step {
                dx: 1.0,
                dy: 1.0,
                dt_ms: 100,
            }],
        }]);
        assert!(s.corpus().len() >= 9);
    }

    #[test]
    fn cumulative_starts_at_origin() {
        let t = Trace {
            steps: vec![Step {
                dx: 0.5,
                dy: 0.5,
                dt_ms: 100,
            }],
        };
        let cumul = t.cumulative();
        assert_eq!(cumul[0], (0.0, 0.0, 0));
    }

    #[test]
    fn arc_length_sums_step_distances() {
        // 3-4-5 triangle steps → arc length = 5 + 5 = 10.
        let t = Trace {
            steps: vec![
                Step {
                    dx: 3.0,
                    dy: 4.0,
                    dt_ms: 10,
                },
                Step {
                    dx: -3.0,
                    dy: -4.0,
                    dt_ms: 10,
                },
            ],
        };
        assert!((t.arc_length() - 10.0).abs() < 1e-5);
    }

    #[test]
    fn duration_ms_is_zero_for_empty_trace() {
        let t = Trace { steps: vec![] };
        assert_eq!(t.duration_ms(), 0);
    }

    #[test]
    fn affine_transform_handles_zero_length_normalised_trace_gracefully() {
        // Edge case: a trace whose cumulative end is (0, 0) — the
        // transform must not divide by zero.
        let trace = Trace {
            steps: vec![
                Step {
                    dx: 0.5,
                    dy: 0.5,
                    dt_ms: 10,
                },
                Step {
                    dx: -0.5,
                    dy: -0.5,
                    dt_ms: 10,
                },
            ],
        };
        let mut rng = rand::rngs::StdRng::from_entropy_via_thread_local();
        let out = affine_transform_with_jitter(&trace, (0.0, 0.0), (100.0, 100.0), &mut rng);
        assert_eq!(out.steps.len(), 2);
    }
}