captchaforge 0.2.9

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
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
use chromiumoxide::Page;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::{info, warn};

use super::{
    screenshot_b64, AudioCaptchaSolver, BehavioralCaptchaSolver, CaptchaInfo, CaptchaSolveResult,
    CaptchaSolver, CaptchaType, CloudflareInterstitialSolver, MathCaptchaSolver, PatternStore,
    PowCaptchaSolver, SliderCaptchaSolver, SolveMethod, ThirdPartyCaptchaSolver, TokenCache,
    VlmCaptchaSolver, WaitForTokenSolver,
};
use crate::captcha_detect::DetectedCaptcha;
use crate::provider::ProviderRegistry;
use crate::solver::util::{detected_to_type, extract_domain};
use crate::telemetry::{NoopTelemetry, SolveEvent, SolveOutcome, SolverTelemetry};

/// Runtime configuration for the solver chain.
#[derive(Debug, Clone, Copy)]
pub struct ChainConfig {
    /// Maximum time allowed for a single solver attempt (ms).
    pub per_solver_timeout_ms: u64,
    /// Whether to capture a screenshot when all solvers fail.
    pub screenshot_on_failure: bool,
}

impl Default for ChainConfig {
    fn default() -> Self {
        Self {
            per_solver_timeout_ms: 180_000,
            screenshot_on_failure: true,
        }
    }
}

/// Tries registered solvers in order; returns the first successful result.
/// If all solvers fail, returns an unsolved result signalling human fallback.
pub struct CaptchaSolverChain {
    pub(crate) solvers: Vec<Box<dyn CaptchaSolver>>,
    /// Optional crowd-sourced pattern store for reordering by domain intelligence.
    pub(crate) patterns: PatternStore,
    pub(crate) config: ChainConfig,
    /// Telemetry sink — fires once per solver attempt. Default is
    /// [`NoopTelemetry`] so existing callers see no change; opt in via
    /// [`Self::with_telemetry`] to capture metrics.
    pub(crate) telemetry: Arc<dyn SolverTelemetry>,
    /// Per-domain solved-token cache. `None` disables caching (the
    /// default — backward-compatible). Opt in via
    /// [`Self::with_token_cache`].
    pub(crate) cache: Option<Arc<TokenCache>>,
    /// Optional provider registry. When installed, [`DetectedCaptcha::Custom`]
    /// captchas (the TOML-rule layer) route solvers through the
    /// vendor's recommended_solver_methods — without it, Custom
    /// captchas detect successfully but never get solved because the
    /// built-in solvers' `supports()` returns false for Custom kinds.
    pub(crate) providers: Option<Arc<ProviderRegistry>>,
}

impl CaptchaSolverChain {
    /// Build the default chain in the recommended order:
    /// WaitForToken → Behavioral → VLM → Audio → ThirdParty.
    ///
    /// `WaitForTokenSolver` runs first with a short max-wait
    /// (3 seconds) — the common case in production is a passive
    /// auto-pass widget (Turnstile passive mode, reCAPTCHA v3,
    /// hCaptcha invisible) where the response field populates on
    /// its own. When that happens the chain short-circuits and the
    /// expensive solvers (mouse simulation, VLM, third-party API)
    /// never run. When the field stays empty, the chain falls
    /// through to behavioural simulation as before — no behaviour
    /// regression for sites that need real interaction.
    pub fn default_chain() -> Self {
        let mut chain = Self {
            solvers: Vec::new(),
            patterns: PatternStore::default(),
            config: ChainConfig::default(),
            telemetry: Arc::new(NoopTelemetry),
            cache: None,
            providers: None,
        };
        chain.add_solver(WaitForTokenSolver::new().with_max_wait_ms(3_000));
        // Cloudflare interstitial — the "Just a moment..." 5-second
        // JS challenge page that fronts CF-protected sites BEFORE
        // any Turnstile widget. Solver waits for CF's own challenge
        // to complete and harvests the cf_clearance cookie. With
        // proper stealth, the challenge actually passes; without
        // stealth, this returns failure within the budget and the
        // chain falls through to behavioural simulation.
        chain.add_solver(CloudflareInterstitialSolver::new());
        // Math captcha is cheap (parses page text, computes, types).
        // Runs second so trivial WP-style captchas are handled
        // before heavier solvers fire.
        chain.add_solver(MathCaptchaSolver::new());
        // PoW solver handles ALTCHA / Friendly / MCaptcha / Cap.dev
        // by computing the SHA-256 proof in-page or polling for the
        // widget's own worker. Faster than waiting for the chain to
        // fall through to behavioural simulation.
        chain.add_solver(PowCaptchaSolver::new());
        // Slider solver covers GeeTest / DataDome / PerimeterX /
        // AWS WAF Captcha / Akamai's slider variant. Generic
        // gap-detection + bezier drag with overshoot.
        chain.add_solver(SliderCaptchaSolver::new());
        chain.add_solver(BehavioralCaptchaSolver::new());
        chain.add_solver(VlmCaptchaSolver::new());
        chain.add_solver(AudioCaptchaSolver::new());
        // ThirdParty appears in the chain unconditionally but its
        // `supports()` returns false unless an API key is configured
        // (via CAPTCHAFORGE_THIRDPARTY_API_KEY), so a no-key install
        // sees no behaviour change. With a key present, every TOML
        // vendor that recommends ThirdPartyService now actually has
        // a solver to land on.
        chain.add_solver(ThirdPartyCaptchaSolver::two_captcha());
        chain
    }

    pub fn empty() -> Self {
        Self {
            solvers: Vec::new(),
            patterns: PatternStore::default(),
            config: ChainConfig::default(),
            telemetry: Arc::new(NoopTelemetry),
            cache: None,
            providers: None,
        }
    }

    /// Install a [`ProviderRegistry`] so the chain can route
    /// [`DetectedCaptcha::Custom`] captchas through their declared
    /// `recommended_solver_methods`. Without a registry installed,
    /// Custom captchas (the TOML rule layer) detect successfully but
    /// no built-in solver's `supports()` returns true for them, so
    /// the chain returns "unsolved" without trying anything.
    pub fn with_provider_registry(mut self, providers: Arc<ProviderRegistry>) -> Self {
        self.providers = Some(providers);
        self
    }

    /// Install a per-domain solved-token cache. When set, `solve()`
    /// checks the cache first and returns a `CrowdSourced` result
    /// when a fresh token exists, skipping the solver chain entirely.
    /// Production deployments hit the cache for the typical
    /// 60-second token-validity window and avoid redundant solves
    /// against the same site.
    pub fn with_token_cache(mut self, cache: Arc<TokenCache>) -> Self {
        self.cache = Some(cache);
        self
    }

    /// Append a solver to the chain.
    pub fn add_solver<S: CaptchaSolver + 'static>(&mut self, solver: S) {
        self.solvers.push(Box::new(solver));
    }

    /// Provide a custom pattern store (e.g. loaded from disk / shared across workers).
    pub fn with_pattern_store(mut self, store: PatternStore) -> Self {
        self.patterns = store;
        self
    }

    /// Provide a custom chain configuration.
    pub fn with_config(mut self, config: ChainConfig) -> Self {
        self.config = config;
        self
    }

    /// Install a telemetry sink. Called once per solver attempt with a
    /// [`SolveEvent`] describing outcome + timing + metadata. Used by
    /// production deployments to capture per-domain success rates,
    /// p50/p95 latency, and fallback frequency for routing decisions
    /// outside the local pattern store.
    pub fn with_telemetry(mut self, telemetry: Arc<dyn SolverTelemetry>) -> Self {
        self.telemetry = telemetry;
        self
    }

    /// Check the token cache for a fresh entry matching this captcha
    /// without invoking any solver. Returns `Some` on cache hit (and
    /// fires a `Success` telemetry event tagged with
    /// `solver: "TokenCache"`); `None` on miss or when no cache is
    /// installed.
    ///
    /// Useful as a public API: callers that want to short-circuit
    /// before reaching for a `Page` (e.g. retry loops that already
    /// know the captcha info) can poll this directly. Internally,
    /// [`Self::solve`] calls this as its first step.
    pub fn cached_solution(&self, captcha_info: &CaptchaInfo) -> Option<CaptchaSolveResult> {
        let cache = self.cache.as_ref()?;
        let domain = extract_domain(&captcha_info.page_url);
        let captcha_type = detected_to_type(&captcha_info.kind);
        let entry = cache.get(&domain, &captcha_type)?;
        let elapsed_ms = 0;
        self.telemetry.record(&SolveEvent {
            solver: "TokenCache",
            captcha_type: &captcha_type,
            kind: &captcha_info.kind,
            domain: &domain,
            outcome: SolveOutcome::Success,
            time_ms: elapsed_ms,
            confidence: Some(1.0),
            method: &SolveMethod::CrowdSourced,
        });
        Some(CaptchaSolveResult {
            solution: entry.token().to_owned(),
            confidence: 1.0,
            method: SolveMethod::CrowdSourced,
            time_ms: elapsed_ms,
            success: true,
            screenshot: None,
            // Replay the cookies captured at the original solve so the
            // WAF/vendor's trusted session rides along with the token.
            // Empty when the cache entry was put via the back-compat
            // no-cookies path.
            cookies: entry.cookies().to_vec(),
        })
    }

    /// Run the chain. Returns the first successful `CaptchaSolveResult`,
    /// or an unsolved result (optionally with a screenshot) if all strategies are exhausted.
    pub async fn solve(&self, page: &Page, captcha_info: &CaptchaInfo) -> CaptchaSolveResult {
        let domain = extract_domain(&captcha_info.page_url);
        let captcha_type = detected_to_type(&captcha_info.kind);
        let t0 = Instant::now();

        // Cache short-circuit — see [`Self::cached_solution`] for the
        // standalone path. Done here too so `solve()` is a complete
        // top-level entry point.
        if let Some(hit) = self.cached_solution(captcha_info) {
            // Re-stamp time_ms with the wall clock since cached_solution
            // returned 0 (it doesn't know about t0).
            return CaptchaSolveResult {
                time_ms: t0.elapsed().as_millis() as u64,
                ..hit
            };
        }

        // Re-order solvers so the historically-best method for this domain runs first.
        let ordered = self.ordered_solvers(&domain, &captcha_type, &captcha_info.kind);

        for solver in &ordered {
            info!(solver = solver.name(), "attempting captcha solve");
            let timeout = Duration::from_millis(self.config.per_solver_timeout_ms);
            let result = tokio::time::timeout(timeout, solver.solve(page, captcha_info)).await;

            match result {
                Ok(Ok(r)) if r.success => {
                    info!(
                        solver = solver.name(),
                        confidence = r.confidence,
                        time_ms = r.time_ms,
                        "captcha solved"
                    );
                    self.patterns
                        .record(&domain, &captcha_type, true, r.time_ms, r.method.clone());
                    self.telemetry.record(&SolveEvent {
                        solver: solver.name(),
                        captcha_type: &captcha_type,
                        kind: &captcha_info.kind,
                        domain: &domain,
                        outcome: SolveOutcome::Success,
                        time_ms: r.time_ms,
                        confidence: Some(r.confidence),
                        method: &r.method,
                    });
                    if let Some(cache) = &self.cache {
                        // Persist the cookies alongside the token so a
                        // future cache hit replays the same trusted
                        // session — without this the cache layer
                        // returned only the token and the next request
                        // immediately re-triggered the captcha.
                        cache.put_full(
                            &domain,
                            &captcha_type,
                            r.solution.clone(),
                            solver.name(),
                            cache.ttl(),
                            r.cookies.clone(),
                        );
                    }
                    return r;
                }
                Ok(Ok(r)) => {
                    warn!(solver = solver.name(), "solver returned failure result");
                    self.patterns.record(
                        &domain,
                        &captcha_type,
                        false,
                        r.time_ms,
                        r.method.clone(),
                    );
                    self.telemetry.record(&SolveEvent {
                        solver: solver.name(),
                        captcha_type: &captcha_type,
                        kind: &captcha_info.kind,
                        domain: &domain,
                        outcome: SolveOutcome::Failure,
                        time_ms: r.time_ms,
                        confidence: None,
                        method: &r.method,
                    });
                }
                Ok(Err(e)) => {
                    warn!(solver = solver.name(), error = %e, "solver error");
                    let method = solver.method();
                    self.telemetry.record(&SolveEvent {
                        solver: solver.name(),
                        captcha_type: &captcha_type,
                        kind: &captcha_info.kind,
                        domain: &domain,
                        outcome: SolveOutcome::Error,
                        time_ms: 0,
                        confidence: None,
                        method: &method,
                    });
                }
                Err(_) => {
                    warn!(solver = solver.name(), "solver timed out");
                    self.patterns.record(
                        &domain,
                        &captcha_type,
                        false,
                        self.config.per_solver_timeout_ms,
                        solver.method(),
                    );
                    let method = solver.method();
                    self.telemetry.record(&SolveEvent {
                        solver: solver.name(),
                        captcha_type: &captcha_type,
                        kind: &captcha_info.kind,
                        domain: &domain,
                        outcome: SolveOutcome::Timeout,
                        time_ms: self.config.per_solver_timeout_ms,
                        confidence: None,
                        method: &method,
                    });
                }
            }
        }

        // All solvers exhausted — optionally grab a screenshot for human review.
        warn!("all captcha solvers failed, human fallback required");
        let screenshot = if self.config.screenshot_on_failure {
            screenshot_b64(page).await.ok()
        } else {
            None
        };
        CaptchaSolveResult::unsolved(t0.elapsed().as_millis() as u64, screenshot)
    }

    /// Return solvers ordered by routing intelligence:
    ///
    /// 1. If a [`crate::provider::ProviderRegistry`] is installed AND
    ///    the kind has a registered provider, **provider routing** wins:
    ///    - Provider's `recommended_solver_names()` (when non-empty)
    ///      gives an exact, name-keyed list — best for vendors with
    ///      dedicated solvers.
    ///    - Else the provider's `recommended_solver_methods()` is
    ///      consulted — method-keyed, fragile when multiple solvers
    ///      share a method but kept for backwards compat.
    /// 2. Otherwise, fall back to the legacy `supports()`-scan path
    ///    with PatternStore-based reordering.
    ///
    /// Provider routing applies to **all** kinds (built-in AND
    /// `Custom(_)`) — adding a dedicated `TurnstileInteractiveSolver`
    /// no longer collides with `BehavioralCaptchaSolver` because the
    /// provider names which solver to prefer.
    pub(crate) fn ordered_solvers(
        &self,
        domain: &str,
        captcha_type: &CaptchaType,
        kind: &crate::captcha_detect::DetectedCaptcha,
    ) -> Vec<&dyn CaptchaSolver> {
        // Provider-routing path. Three cases:
        //
        // - Provider declares `recommended_solver_names()` (any kind)
        //   → strict name-keyed routing.
        // - Custom kind with a registered provider (no names, just
        //   methods) → method-keyed routing (legacy behaviour).
        // - Custom kind WITHOUT a registered provider → empty list,
        //   so the chain reports "no applicable solvers".
        //
        // For built-in kinds we INTENTIONALLY don't route via
        // method-only providers — the existing macro-emitted
        // `recommended_solver_methods` lists were shipped before name
        // routing existed, and method routing would over-narrow to a
        // single solver per method (vs the supports-scan path which
        // returns every eligible solver). Built-ins fall through to
        // supports-scan unless a provider opts in via names.
        if let Some(reg) = &self.providers {
            if let Some(provider) = reg.find_by_kind(kind) {
                let names = provider.recommended_solver_names();
                if !names.is_empty() {
                    return self.solvers_by_name(names, kind);
                }
                if matches!(kind, DetectedCaptcha::Custom(_)) {
                    let methods = provider.recommended_solver_methods();
                    return self.solvers_by_method(methods, kind);
                }
                // Built-in kind, no names declared → fall through to
                // supports-scan below.
            } else if matches!(kind, DetectedCaptcha::Custom(_)) {
                return Vec::new();
            }
        } else if matches!(kind, DetectedCaptcha::Custom(_)) {
            return Vec::new();
        }

        // Legacy supports-scan + PatternStore reorder.
        let preferred = self.patterns.best_method(domain, captcha_type);
        let mut ordered: Vec<&dyn CaptchaSolver> = self
            .solvers
            .iter()
            .filter(|s| s.supports(kind))
            .map(|s| s.as_ref())
            .collect();

        if let Some(pref) = preferred {
            if let Some(pos) = ordered.iter().position(|s| s.method() == pref) {
                if pos > 0 {
                    let item = ordered.remove(pos);
                    ordered.insert(0, item);
                }
            }
        }
        ordered
    }

    /// Resolve a name-keyed recommendation list to actual solvers.
    /// Each name is matched against `solver.name()` exactly. Solvers
    /// must additionally pass `supports(kind)` so an unkeyed
    /// third-party solver (which says `supports = false` without an
    /// API key) doesn't get picked.
    fn solvers_by_name(
        &self,
        names: &[&'static str],
        kind: &crate::captcha_detect::DetectedCaptcha,
    ) -> Vec<&dyn CaptchaSolver> {
        let mut ordered: Vec<&dyn CaptchaSolver> = Vec::with_capacity(names.len());
        for name in names {
            if let Some(s) = self
                .solvers
                .iter()
                .find(|s| s.name() == *name && s.supports(kind))
            {
                let s_ref: &dyn CaptchaSolver = s.as_ref();
                if !ordered
                    .iter()
                    .any(|existing| std::ptr::eq(*existing, s_ref))
                {
                    ordered.push(s_ref);
                }
            }
        }
        ordered
    }

    /// Resolve a method-keyed recommendation list to actual solvers.
    /// Method-based routing collides when multiple solvers share a
    /// `SolveMethod`; the FIRST chain entry wins. Prefer
    /// [`Self::solvers_by_name`] for vendors with dedicated solvers.
    fn solvers_by_method(
        &self,
        methods: &[SolveMethod],
        kind: &crate::captcha_detect::DetectedCaptcha,
    ) -> Vec<&dyn CaptchaSolver> {
        let mut ordered: Vec<&dyn CaptchaSolver> = Vec::with_capacity(methods.len());
        for method in methods {
            if let Some(s) = self
                .solvers
                .iter()
                .find(|s| s.method() == *method && s.supports(kind))
            {
                let s_ref: &dyn CaptchaSolver = s.as_ref();
                if !ordered
                    .iter()
                    .any(|existing| std::ptr::eq(*existing, s_ref))
                {
                    ordered.push(s_ref);
                }
            }
        }
        ordered
    }
}

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

    #[test]
    fn solver_chain_add_and_count() {
        let mut chain = CaptchaSolverChain::empty();
        chain.add_solver(BehavioralCaptchaSolver::new());
        chain.add_solver(AudioCaptchaSolver::new());
        assert_eq!(chain.solvers.len(), 2);
    }

    #[test]
    fn default_chain_has_nine_solvers_in_documented_order() {
        let chain = CaptchaSolverChain::default_chain();
        assert_eq!(chain.solvers.len(), 9);
        assert_eq!(chain.solvers[0].name(), "WaitForTokenSolver");
        assert_eq!(chain.solvers[1].name(), "CloudflareInterstitialSolver");
        assert_eq!(chain.solvers[2].name(), "MathCaptchaSolver");
        assert_eq!(chain.solvers[3].name(), "PowCaptchaSolver");
        assert_eq!(chain.solvers[4].name(), "SliderCaptchaSolver");
        assert_eq!(chain.solvers[5].name(), "BehavioralCaptchaSolver");
        assert_eq!(chain.solvers[6].name(), "VlmCaptchaSolver");
        assert_eq!(chain.solvers[7].name(), "AudioCaptchaSolver");
        assert_eq!(chain.solvers[8].name(), "ThirdPartyCaptchaSolver");
    }

    #[test]
    fn default_chain_third_party_inert_without_api_key() {
        // Without CAPTCHAFORGE_THIRDPARTY_API_KEY, the third-party solver's
        // supports() returns false everywhere, so adding it to the default
        // chain doesn't surface in ordered_solvers for any kind.
        // (We rely on the env-var being unset in CI; we can't safely set
        // it within a test without affecting other tests in the same
        // process.)
        if std::env::var("CAPTCHAFORGE_THIRDPARTY_API_KEY").is_ok() {
            return;
        }
        let chain = CaptchaSolverChain::default_chain();
        let ordered = chain.ordered_solvers(
            "example.com",
            &CaptchaType::CloudflareTurnstile,
            &crate::captcha_detect::DetectedCaptcha::Turnstile,
        );
        for s in ordered {
            assert_ne!(
                s.name(),
                "ThirdPartyCaptchaSolver",
                "third-party should be filtered out without an API key",
            );
        }
    }

    #[test]
    fn custom_captcha_routes_through_third_party_when_key_present() {
        use crate::provider::ProviderRegistry;
        use crate::solver::ThirdPartyCaptchaSolver;
        // Construct a chain with a third-party solver that has a key,
        // and a provider registry. DataDome recommends
        // [BehavioralBypass, ThirdPartyService] — the chain should now
        // surface BOTH (Behavioral first, ThirdParty second).
        let registry = Arc::new(ProviderRegistry::with_built_in_rules().unwrap());
        let mut chain = CaptchaSolverChain::empty().with_provider_registry(registry);
        chain.add_solver(BehavioralCaptchaSolver::new());
        chain.add_solver(ThirdPartyCaptchaSolver::two_captcha().with_api_key("test-key"));

        let ordered = chain.ordered_solvers(
            "datadome.test",
            &CaptchaType::Custom("datadome".into()),
            &crate::captcha_detect::DetectedCaptcha::Custom("datadome".into()),
        );
        assert_eq!(
            ordered.len(),
            2,
            "with API key, both Behavioral and ThirdParty should be eligible",
        );
        assert_eq!(ordered[0].method(), SolveMethod::BehavioralBypass);
        assert_eq!(ordered[1].method(), SolveMethod::ThirdPartyService);
    }

    #[test]
    fn default_chain_timeout_is_sane() {
        let chain = CaptchaSolverChain::default_chain();
        assert_eq!(chain.config.per_solver_timeout_ms, 180_000);
        assert!(chain.config.screenshot_on_failure);
    }

    #[test]
    fn chain_with_custom_config() {
        let chain = CaptchaSolverChain::empty().with_config(ChainConfig {
            per_solver_timeout_ms: 30_000,
            screenshot_on_failure: false,
        });
        assert_eq!(chain.config.per_solver_timeout_ms, 30_000);
        assert!(!chain.config.screenshot_on_failure);
    }

    #[test]
    fn ordered_solvers_puts_preferred_first() {
        let mut chain = CaptchaSolverChain::empty();
        chain.add_solver(BehavioralCaptchaSolver::new());
        chain.add_solver(VlmCaptchaSolver::new());
        chain.add_solver(AudioCaptchaSolver::new());

        // Seed the pattern store so VisionLLM is preferred for example.com
        chain.patterns.record(
            "example.com",
            &CaptchaType::RecaptchaV2,
            true,
            1000,
            SolveMethod::VisionLLM,
        );

        let ordered = chain.ordered_solvers(
            "example.com",
            &CaptchaType::RecaptchaV2,
            &crate::captcha_detect::DetectedCaptcha::RecaptchaV2,
        );
        assert_eq!(ordered.len(), 3);
        assert_eq!(ordered[0].name(), "VlmCaptchaSolver");
        assert_eq!(ordered[1].name(), "BehavioralCaptchaSolver");
        assert_eq!(ordered[2].name(), "AudioCaptchaSolver");
    }

    #[test]
    fn ordered_solvers_keeps_original_order_when_no_preference() {
        let chain = CaptchaSolverChain::default_chain();
        let ordered = chain.ordered_solvers(
            "unknown.com",
            &CaptchaType::RecaptchaV2,
            &crate::captcha_detect::DetectedCaptcha::RecaptchaV2,
        );
        // WaitForToken now leads the chain; passive-pass widgets get
        // first crack at issuing a token without interaction.
        assert_eq!(ordered[0].name(), "WaitForTokenSolver");
        assert_eq!(ordered[1].name(), "BehavioralCaptchaSolver");
        assert_eq!(ordered[2].name(), "VlmCaptchaSolver");
        assert_eq!(ordered[3].name(), "AudioCaptchaSolver");
    }

    #[test]
    fn custom_captcha_returns_no_solvers_without_provider_registry() {
        let chain = CaptchaSolverChain::default_chain();
        let ordered = chain.ordered_solvers(
            "datadome.test",
            &CaptchaType::Custom("datadome".into()),
            &crate::captcha_detect::DetectedCaptcha::Custom("datadome".into()),
        );
        assert!(
            ordered.is_empty(),
            "without a ProviderRegistry the chain has no way to know which solver to try for a Custom captcha",
        );
    }

    #[test]
    fn custom_captcha_routes_through_provider_recommended_methods() {
        use crate::provider::ProviderRegistry;
        // DataDome recommends [BehavioralBypass, ThirdPartyService].
        // Default chain has multiple BehavioralBypass solvers: Slider
        // (which legitimately handles datadome's slider widget) and
        // Behavioural. The routing finds the FIRST BehavioralBypass
        // solver whose supports(kind) returns true — Slider wins for
        // datadome since it claims the vendor explicitly. Without an
        // API key, ThirdParty filters out, so we get exactly 1 solver.
        let registry = Arc::new(ProviderRegistry::with_built_in_rules().unwrap());
        let chain = CaptchaSolverChain::default_chain().with_provider_registry(registry);

        let ordered = chain.ordered_solvers(
            "datadome.test",
            &CaptchaType::Custom("datadome".into()),
            &crate::captcha_detect::DetectedCaptcha::Custom("datadome".into()),
        );
        assert_eq!(
            ordered.len(),
            1,
            "only one BehavioralBypass solver supports datadome; \
             ThirdPartyService filters out without API key",
        );
        assert_eq!(ordered[0].name(), "SliderCaptchaSolver");
    }

    #[test]
    fn custom_captcha_routes_to_vision_first_when_provider_recommends_it() {
        use crate::provider::ProviderRegistry;
        // arkose_funcaptcha (and others) recommend VisionLLM somewhere
        // in the list. Looking at community.toml: arkose recommends
        // [Behavioral, ThirdParty] same as datadome. Use a vendor
        // whose first recommendation IS in the default chain.
        // Actually all bundled rules recommend Behavioral first; let's
        // just verify the order is preserved as the provider declared.
        let registry = Arc::new(ProviderRegistry::with_built_in_rules().unwrap());
        let chain = CaptchaSolverChain::default_chain().with_provider_registry(registry);

        let ordered = chain.ordered_solvers(
            "x.test",
            &CaptchaType::Custom("perimeterx_human".into()),
            &crate::captcha_detect::DetectedCaptcha::Custom("perimeterx_human".into()),
        );
        // perimeterx_human recommends [BehavioralBypass, ThirdPartyService]
        // — only Behavioral is in the default chain, so we get one solver.
        assert_eq!(ordered.len(), 1);
        assert_eq!(ordered[0].method(), SolveMethod::BehavioralBypass);
    }

    #[test]
    fn custom_captcha_with_unknown_name_returns_no_solvers() {
        use crate::provider::ProviderRegistry;
        let registry = Arc::new(ProviderRegistry::with_built_in_rules().unwrap());
        let chain = CaptchaSolverChain::default_chain().with_provider_registry(registry);

        let ordered = chain.ordered_solvers(
            "unknown.test",
            &CaptchaType::Custom("never-heard-of-it".into()),
            &crate::captcha_detect::DetectedCaptcha::Custom("never-heard-of-it".into()),
        );
        assert!(
            ordered.is_empty(),
            "unknown Custom name has no provider entry → no solvers",
        );
    }

    #[test]
    fn ordered_solvers_keeps_original_order_when_preference_not_in_chain() {
        let mut chain = CaptchaSolverChain::empty();
        chain.add_solver(BehavioralCaptchaSolver::new());
        chain.add_solver(VlmCaptchaSolver::new());

        // Record a preference for AudioBypass, which isn't in the chain
        chain.patterns.record(
            "example.com",
            &CaptchaType::RecaptchaV2,
            true,
            1000,
            SolveMethod::AudioBypass,
        );

        let ordered = chain.ordered_solvers(
            "example.com",
            &CaptchaType::RecaptchaV2,
            &crate::captcha_detect::DetectedCaptcha::RecaptchaV2,
        );
        assert_eq!(ordered[0].name(), "BehavioralCaptchaSolver");
        assert_eq!(ordered[1].name(), "VlmCaptchaSolver");
    }

    #[test]
    fn ordered_solvers_filters_by_supports() {
        let chain = CaptchaSolverChain::default_chain();
        // HCaptcha is supported by WaitForTokenSolver (passive-pass
        // path) and VlmCaptchaSolver (vision fallback). Behavioural
        // and Audio don't claim hCaptcha; Third-party is keyless in
        // tests so it filters out.
        let ordered = chain.ordered_solvers(
            "example.com",
            &CaptchaType::HCaptcha,
            &crate::captcha_detect::DetectedCaptcha::HCaptcha,
        );
        assert_eq!(ordered.len(), 2);
        assert_eq!(ordered[0].name(), "WaitForTokenSolver");
        assert_eq!(ordered[1].name(), "VlmCaptchaSolver");
    }

    #[test]
    fn ordered_solvers_empty_when_no_solver_supports() {
        let chain = CaptchaSolverChain::default_chain();
        // DetectedCaptcha::None genuinely matches no solver — used as
        // the no-captcha sentinel. Slider/Multi-step etc. are now
        // supported by Behavioral and VLM (provider-routed solvers
        // need to attempt page-visible challenges).
        let ordered = chain.ordered_solvers(
            "example.com",
            &CaptchaType::Custom("none".into()),
            &crate::captcha_detect::DetectedCaptcha::None,
        );
        assert!(ordered.is_empty());
    }
}