captchaforge 0.2.28

Automatic CAPTCHA detection and multi-strategy solving for chromiumoxide-driven headless browsers (Cloudflare Turnstile, reCAPTCHA v2/v3, hCaptcha, image grids, audio, sliders).
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
//! Multi-hop captcha planner.
//!
//! Some sites stack captchas: a Cloudflare interstitial fronts the
//! login page, the login page itself surfaces a Turnstile widget,
//! and a high-risk login attempt triggers a second hCaptcha
//! checkpoint. Today the chain treats each detection as terminal:
//! solve once, return. Stacked challenges fail because the chain
//! never re-detects after the first solve clears the page.
//!
//! [`MultiHopPlanner`] re-detects after each successful solve,
//! continues until either:
//!
//! - **Success** — `detect()` reports `NotACaptcha` and the page
//!   exposes the resource the caller wanted.
//! - **Stable failure** — N consecutive solves left the same
//!   challenge active (page didn't advance), so retrying won't
//!   help. Returns the last attempt's result.
//! - **Hard block** — page transitioned to a known block screen
//!   ("access denied", "you have been blocked"). Stop trying.
//! - **Budget exhausted** — wall-clock or hop-count limit hit.
//!
//! The planner is BYO-solver: it takes any `Fn(&Page, &CaptchaInfo)
//! -> Future<Output = CaptchaSolveResult>` so callers can pass in
//! `chain.solve` for production or a stub closure for tests.
//!
//! ## Why a separate module
//!
//! `CaptchaSolverChain::solve` is structured around "one challenge,
//! one chain pass" — wedging multi-hop into it complicates the
//! single-shot path that 90% of callers use. Keeping the planner
//! separate lets the simple case stay simple and lets multi-hop
//! consumers explicitly opt in.

use crate::detect::{detect, is_captcha, CaptchaInfo, DetectedCaptcha};
use crate::solver::CaptchaSolveResult;
use anyhow::Result;
use chromiumoxide::Page;
use std::future::Future;
use std::time::{Duration, Instant};

/// Bounds + behaviour knobs for [`MultiHopPlanner::run`].
#[derive(Debug, Clone)]
pub struct PlannerConfig {
    /// Max hops before giving up. Real-world stacks rarely exceed
    /// 3 (interstitial → widget → high-risk recheck); 5 is generous.
    pub max_hops: u32,
    /// Total wall-clock budget across all hops. The chain is async,
    /// so a per-hop budget would let a slow VLM consume the full
    /// budget on hop 1 and starve later hops.
    pub total_budget: Duration,
    /// Pause between hops to let post-solve page state settle (e.g.
    /// CF clearance cookie propagating to the iframe). 500ms is the
    /// 90th-percentile settle time observed in production.
    pub inter_hop_pause: Duration,
    /// Number of consecutive same-challenge hops before declaring
    /// the page stuck. 2 is a defensible default: one solve + one
    /// "did the solve advance the page?" probe.
    pub stuck_threshold: u32,
}

impl Default for PlannerConfig {
    fn default() -> Self {
        Self {
            max_hops: 5,
            total_budget: Duration::from_secs(120),
            inter_hop_pause: Duration::from_millis(500),
            stuck_threshold: 2,
        }
    }
}

/// What happened across the whole multi-hop run. Distinct from
/// per-hop [`CaptchaSolveResult`] because the planner has its own
/// success criterion ("page is now captcha-free") that's a
/// superset of any individual hop's success.
#[derive(Debug, Clone)]
pub struct PlannerOutcome {
    /// Per-hop solve outcomes, in execution order. Always non-empty
    /// when at least one hop ran; empty when the page started
    /// without a captcha and the planner exited immediately.
    pub hops: Vec<HopOutcome>,
    /// Why the planner stopped.
    pub terminal: PlannerTerminal,
    /// Total wall-clock elapsed.
    pub elapsed: Duration,
}

impl PlannerOutcome {
    /// True iff the planner reached the success terminal AND every
    /// hop along the way reported a successful solve. The most
    /// common "did this work" check.
    pub fn fully_succeeded(&self) -> bool {
        matches!(self.terminal, PlannerTerminal::PageCaptchaFree)
            && self.hops.iter().all(|h| h.solve.success)
    }

    /// True when ANY hop's solve was a real success (vs. all being
    /// human-fallback / decoy-token failures). Useful for partial-
    /// progress reporting in long flows.
    pub fn any_solve_succeeded(&self) -> bool {
        self.hops.iter().any(|h| h.solve.success)
    }
}

/// One hop's bookkeeping.
#[derive(Debug, Clone)]
pub struct HopOutcome {
    /// 1-indexed for human-friendly logs.
    pub hop_index: u32,
    /// What the planner detected at the start of this hop.
    pub detected: DetectedCaptcha,
    /// What the solver returned. Captures method, confidence,
    /// timing, verified outcome.
    pub solve: CaptchaSolveResult,
}

/// Why the planner stopped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlannerTerminal {
    /// Best case — `detect()` reports no captcha after the last hop.
    PageCaptchaFree,
    /// `max_hops` consumed; page still has a captcha.
    HopBudgetExhausted,
    /// `total_budget` wall-clock elapsed mid-hop.
    TimeBudgetExhausted,
    /// `stuck_threshold` consecutive hops left the same challenge
    /// kind active. Retrying won't help.
    Stuck { kind: DetectedCaptcha, hops: u32 },
    /// Page transitioned to a known block screen
    /// ("access denied" / "blocked" / "rate limited").
    HardBlocked,
}

/// Multi-hop captcha planner.
///
/// Construct with [`MultiHopPlanner::with_config`] and drive with
/// [`MultiHopPlanner::run`]. The solver is a closure passed to
/// `run` rather than stored on the planner so the same instance
/// can be reused with different chains in tests / staging /
/// production.
pub struct MultiHopPlanner {
    config: PlannerConfig,
}

impl MultiHopPlanner {
    pub fn new() -> Self {
        Self::with_config(PlannerConfig::default())
    }

    pub fn with_config(config: PlannerConfig) -> Self {
        Self { config }
    }

    /// Drive the multi-hop loop on `page` with `solver`.
    ///
    /// `solver` is invoked once per hop with the current page +
    /// the freshly-detected `CaptchaInfo`. It must return a
    /// `CaptchaSolveResult` (failure cases produce a result with
    /// `success: false`, never an error — errors should bubble up
    /// from the planner only when the BROWSER is broken, not when
    /// a single hop fails to solve).
    pub async fn run<F, Fut>(&self, page: &Page, mut solver: F) -> Result<PlannerOutcome>
    where
        F: FnMut(&Page, CaptchaInfo) -> Fut,
        Fut: Future<Output = CaptchaSolveResult>,
    {
        let started = Instant::now();
        let mut hops: Vec<HopOutcome> = Vec::with_capacity(self.config.max_hops as usize);
        let mut consecutive_same: u32 = 0;
        let mut last_detected: Option<DetectedCaptcha> = None;

        for hop_index in 1..=self.config.max_hops {
            // Time budget check BEFORE the next detect — without
            // this we could overshoot by a hop's worth of wall-clock.
            if started.elapsed() >= self.config.total_budget {
                return Ok(PlannerOutcome {
                    hops,
                    terminal: PlannerTerminal::TimeBudgetExhausted,
                    elapsed: started.elapsed(),
                });
            }

            let info = detect(page).await?;
            if !is_captcha(&info) {
                return Ok(PlannerOutcome {
                    hops,
                    terminal: PlannerTerminal::PageCaptchaFree,
                    elapsed: started.elapsed(),
                });
            }
            if is_hard_block(&info.kind) {
                return Ok(PlannerOutcome {
                    hops,
                    terminal: PlannerTerminal::HardBlocked,
                    elapsed: started.elapsed(),
                });
            }

            // "Stuck" check — same kind two hops in a row means the
            // last solve didn't advance the page.
            if last_detected.as_ref() == Some(&info.kind) {
                consecutive_same += 1;
                if consecutive_same >= self.config.stuck_threshold {
                    return Ok(PlannerOutcome {
                        hops,
                        terminal: PlannerTerminal::Stuck {
                            kind: info.kind.clone(),
                            hops: consecutive_same,
                        },
                        elapsed: started.elapsed(),
                    });
                }
            } else {
                consecutive_same = 1;
            }
            last_detected = Some(info.kind.clone());

            let solve = solver(page, info.clone()).await;
            hops.push(HopOutcome {
                hop_index,
                detected: info.kind.clone(),
                solve,
            });

            // Inter-hop settle pause — gives post-solve cookies +
            // postMessage relays time to land before we re-detect.
            tokio::time::sleep(self.config.inter_hop_pause).await;
        }

        Ok(PlannerOutcome {
            hops,
            terminal: PlannerTerminal::HopBudgetExhausted,
            elapsed: started.elapsed(),
        })
    }
}

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

/// Recognise a captcha kind that will never resolve via solving —
/// these are hard-block screens shown after a WAF has decided the
/// visitor is unwanted.
///
/// Today the kinds are limited; as the rule pack grows
/// (challenge-page-block / fly-io-block / linkedin-security
/// challenges that can't be solved without a real account), this
/// matcher gains more entries.
fn is_hard_block(kind: &DetectedCaptcha) -> bool {
    use DetectedCaptcha::Custom;
    if let Custom(name) = kind {
        return matches!(
            name.as_str(),
            "akamai_reference_block"
                | "imperva_block_text"
                | "fly_io_block"
                | "linode_block"
                | "digitalocean_block"
                | "hetzner_block"
                | "scaleway_block"
                | "vultr_block"
                | "render_block"
                | "kinsta_block"
        );
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::detect::CaptchaInfo;
    use crate::solver::SolveMethod;

    /// Build a minimal `CaptchaSolveResult` for tests. Real solvers
    /// fill in cookies + screenshot + verified_outcome; the planner
    /// doesn't read those fields, only `success` and `method`.
    fn solve_ok() -> CaptchaSolveResult {
        CaptchaSolveResult {
            success: true,
            confidence: 1.0,
            method: SolveMethod::BehavioralBypass,
            time_ms: 100,
            solution: "ok".into(),
            screenshot: None,
            cookies: Vec::new(),
            verified_outcome: None,
        }
    }

    fn solve_fail() -> CaptchaSolveResult {
        CaptchaSolveResult {
            success: false,
            confidence: 0.0,
            method: SolveMethod::CrowdSourced,
            time_ms: 50,
            solution: String::new(),
            screenshot: None,
            cookies: Vec::new(),
            verified_outcome: None,
        }
    }

    #[test]
    fn default_config_has_reasonable_bounds() {
        let c = PlannerConfig::default();
        assert!(c.max_hops >= 3, "must allow at least 3 hops for stacked WAF + Turnstile + recheck flows");
        assert!(c.total_budget.as_secs() >= 60);
        assert!(c.stuck_threshold >= 2);
    }

    #[test]
    fn fully_succeeded_requires_terminal_plus_all_hops_ok() {
        let mut o = PlannerOutcome {
            hops: vec![
                HopOutcome {
                    hop_index: 1,
                    detected: DetectedCaptcha::Turnstile,
                    solve: solve_ok(),
                },
            ],
            terminal: PlannerTerminal::PageCaptchaFree,
            elapsed: Duration::from_millis(100),
        };
        assert!(o.fully_succeeded());

        // Even one failed hop drops the verdict.
        o.hops.push(HopOutcome {
            hop_index: 2,
            detected: DetectedCaptcha::HCaptcha,
            solve: solve_fail(),
        });
        assert!(!o.fully_succeeded());
    }

    #[test]
    fn any_solve_succeeded_picks_up_partial_progress() {
        let o = PlannerOutcome {
            hops: vec![
                HopOutcome {
                    hop_index: 1,
                    detected: DetectedCaptcha::Turnstile,
                    solve: solve_ok(),
                },
                HopOutcome {
                    hop_index: 2,
                    detected: DetectedCaptcha::HCaptcha,
                    solve: solve_fail(),
                },
            ],
            terminal: PlannerTerminal::HopBudgetExhausted,
            elapsed: Duration::from_secs(60),
        };
        assert!(o.any_solve_succeeded());
        assert!(!o.fully_succeeded());
    }

    #[test]
    fn empty_outcome_does_not_falsely_report_success() {
        let o = PlannerOutcome {
            hops: vec![],
            terminal: PlannerTerminal::PageCaptchaFree,
            elapsed: Duration::ZERO,
        };
        // Vacuously true on the iterator, paired with PageCaptchaFree
        // — represents "page never had a captcha at all".
        assert!(o.fully_succeeded());
        assert!(!o.any_solve_succeeded());
    }

    #[test]
    fn is_hard_block_recognises_known_block_screens() {
        assert!(is_hard_block(&DetectedCaptcha::Custom("akamai_reference_block".into())));
        assert!(is_hard_block(&DetectedCaptcha::Custom("fly_io_block".into())));
        assert!(is_hard_block(&DetectedCaptcha::Custom("digitalocean_block".into())));
    }

    #[test]
    fn is_hard_block_rejects_unknown_custom_names() {
        assert!(!is_hard_block(&DetectedCaptcha::Custom("some_random_vendor".into())));
    }

    #[test]
    fn is_hard_block_rejects_built_in_kinds() {
        // Built-in Turnstile / hCaptcha / etc. are SOLVABLE — never
        // classify them as hard blocks.
        assert!(!is_hard_block(&DetectedCaptcha::Turnstile));
        assert!(!is_hard_block(&DetectedCaptcha::HCaptcha));
        assert!(!is_hard_block(&DetectedCaptcha::RecaptchaV2));
        assert!(!is_hard_block(&DetectedCaptcha::SliderCaptcha));
    }

    /// Test the planner's terminal-classification logic in isolation
    /// from the (browser-bound) `run` path. Construct an outcome and
    /// match on its terminal field — this is the surface most call
    /// sites actually consume.
    #[test]
    fn planner_terminal_variants_round_trip_via_pattern_match() {
        let cases = [
            PlannerTerminal::PageCaptchaFree,
            PlannerTerminal::HopBudgetExhausted,
            PlannerTerminal::TimeBudgetExhausted,
            PlannerTerminal::Stuck {
                kind: DetectedCaptcha::Turnstile,
                hops: 2,
            },
            PlannerTerminal::HardBlocked,
        ];
        for t in cases {
            // Each variant must be matchable as the documented shape.
            // Compile-fail catches accidental non-exhaustive removal.
            match &t {
                PlannerTerminal::PageCaptchaFree => {}
                PlannerTerminal::HopBudgetExhausted => {}
                PlannerTerminal::TimeBudgetExhausted => {}
                PlannerTerminal::Stuck { kind: _, hops: _ } => {}
                PlannerTerminal::HardBlocked => {}
            }
        }
    }

    /// Suppress "unused — for documentation only" warnings on imports
    /// the planner depends on transitively. Without this rustc warns
    /// about unused `CaptchaInfo`, `SolveMethod` in the test module.
    #[test]
    fn smoke_test_imports() {
        let _: Option<CaptchaInfo> = None;
        let _ = SolveMethod::BehavioralBypass;
    }
}