captchaforge 0.2.38

[DO NOT USE — UNDER ACTIVE DEVELOPMENT, NOT PRODUCTION-READY] Captcha solver scaffolding for Firefox + BiDi-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 / BiDi 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
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! Tier-A operational configuration loaded from `.captchaforge.toml`.
//!
//! Per the CLAUDE.md two-tier configurability rule, captchaforge has
//! two distinct config layers:
//!
//! - **Tier A — operational config (this module)**: timeouts,
//!   concurrency, cache TTL, VLM endpoint/model, third-party service
//!   selection. CLI flags + TOML defaults; CLI wins. Compiled
//!   defaults → `captchaforge.toml` → CLI flags.
//! - **Tier B — community knowledge (`detect::rules`)**: vendor
//!   detection rules, never CLI-flagged. Lives in TOML data files.
//!
//! This module owns Tier A. The shape mirrors the runtime types so
//! callers materialise a config once and apply it to chain / solver /
//! cache constructors.
//!
//! # Search path
//!
//! [`Config::discover`] looks in this order, returning the first hit:
//! 1. `$CAPTCHAFORGE_CONFIG` (explicit path; if unset is skipped)
//! 2. `./.captchaforge.toml` (project-local)
//! 3. `./captchaforge.toml`
//! 4. `$XDG_CONFIG_HOME/captchaforge/config.toml`
//!    (fallback `~/.config/captchaforge/config.toml`)
//!
//! Missing-file is NOT an error from `discover` — it returns
//! [`Config::default`]. Use [`Config::load_from_path`] when you want
//! the strict "must exist" behaviour.
//!
//! # Example file
//!
//! ```toml
//! # Per-solver timeout for the chain. Default 180_000.
//! per_solver_timeout_ms = 60000
//! # Whether to capture a screenshot on full chain failure. Default true.
//! screenshot_on_failure = true
//!
//! [cache]
//! # TTL in seconds for cached solved tokens. Default 60.
//! ttl_seconds = 90
//!
//! [vlm]
//! # Override Ollama endpoint. Beats the CAPTCHAFORGE_VLM_ENDPOINT env var.
//! endpoint = "http://gpu-host:11434"
//! model    = "qwen3-vl:30b"
//!
//! [third_party]
//! # Pick one: "two_captcha" | "cap_monster" | "cap_solver" | "custom"
//! service  = "two_captcha"
//! # Required when service = "custom".
//! base_url = "https://my-gateway.example/2captcha"
//! # API key (or leave blank and use CAPTCHAFORGE_THIRDPARTY_API_KEY env var).
//! api_key  = ""
//! poll_interval_ms = 5000
//! max_polls = 30
//!
//! [solve]
//! # All SolveConfig fields are overridable individually.
//! checkbox_max_attempts = 20
//! token_max_attempts    = 24
//! ```

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

use std::sync::Arc;

use crate::provider::ProviderRegistry;
use crate::solver::{
    CaptchaSolverChain, ChainConfig, MultiStepCaptchaSolver, OcrCaptchaSolver, SolveConfig,
    ThirdPartyCaptchaSolver, ThirdPartyService, TokenCache, VlmCaptchaSolver,
};

const DEFAULT_CACHE_TTL_SECONDS: u64 = 60;

const ENV_CONFIG_PATH: &str = "CAPTCHAFORGE_CONFIG";

/// Top-level Tier-A config. All fields are optional; absent fields
/// fall back to compiled defaults.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
    pub per_solver_timeout_ms: Option<u64>,
    pub screenshot_on_failure: Option<bool>,
    /// Override `ChainConfig::verify_outcome`. Default `None` ⇒
    /// chain default (`true`). Set to `false` to skip the
    /// before/after page snapshot — useful for synthetic fixtures
    /// where a green-checkmark token is the only signal.
    pub verify_outcome: Option<bool>,
    pub cache: CacheConfig,
    pub vlm: VlmConfig,
    pub third_party: ThirdPartyConfig,
    pub solve: SolveOverrides,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CacheConfig {
    pub ttl_seconds: Option<u64>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct VlmConfig {
    pub endpoint: Option<String>,
    pub model: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ThirdPartyConfig {
    /// One of `two_captcha`, `cap_monster`, `cap_solver`, `custom`.
    pub service: Option<String>,
    /// Required when `service = "custom"`. Ignored otherwise.
    pub base_url: Option<String>,
    /// API key. Leave None to fall back to the
    /// `CAPTCHAFORGE_THIRDPARTY_API_KEY` env var.
    pub api_key: Option<String>,
    pub poll_interval_ms: Option<u64>,
    pub max_polls: Option<u32>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SolveOverrides {
    pub checkbox_poll_interval_ms: Option<u64>,
    pub checkbox_max_attempts: Option<u32>,
    pub token_poll_interval_ms: Option<u64>,
    pub token_max_attempts: Option<u32>,
    pub audio_button_delay_ms: Option<u64>,
    pub audio_submit_delay_ms: Option<u64>,
    pub vlm_http_timeout_ms: Option<u64>,
    pub client_http_timeout_ms: Option<u64>,
}

impl Config {
    /// Walk the search path and return the first config found, or
    /// `Config::default()` if none exists. Errors only on a malformed
    /// TOML in a found file.
    pub fn discover() -> anyhow::Result<Self> {
        for path in Self::search_paths() {
            if path.is_file() {
                return Self::load_from_path(&path);
            }
        }
        Ok(Self::default())
    }

    /// The ordered candidate paths Self::discover walks. Public so
    /// CLIs can show users where the file is expected to live.
    pub fn search_paths() -> Vec<PathBuf> {
        Self::search_paths_with_env(|n| std::env::var(n).ok())
    }

    /// Like [`Self::search_paths`] but with an injectable env lookup
    /// so unit tests don't have to mutate process env.
    pub(crate) fn search_paths_with_env<F>(env: F) -> Vec<PathBuf>
    where
        F: Fn(&str) -> Option<String>,
    {
        let mut out = Vec::new();
        if let Some(p) = env(ENV_CONFIG_PATH).filter(|s| !s.is_empty()) {
            out.push(PathBuf::from(p));
        }
        out.push(PathBuf::from(".captchaforge.toml"));
        out.push(PathBuf::from("captchaforge.toml"));
        let xdg = env("XDG_CONFIG_HOME")
            .filter(|s| !s.is_empty())
            .map(PathBuf::from)
            .or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config")));
        if let Some(base) = xdg {
            out.push(base.join("captchaforge").join("config.toml"));
        }
        out
    }

    /// Read + parse a TOML file at `path`. Errors propagate so callers
    /// can distinguish "no config" from "bad config."
    ///
    /// Emits a `tracing::warn!` if the loaded file commits a
    /// third-party API key inline — those keys belong in
    /// `CAPTCHAFORGE_THIRDPARTY_API_KEY` (env var) or a secrets
    /// store, not in a file that gets committed alongside source.
    pub fn load_from_path(path: impl AsRef<Path>) -> anyhow::Result<Self> {
        let path = path.as_ref();
        let body = std::fs::read_to_string(path)
            .map_err(|e| anyhow::anyhow!("reading {}: {e}", path.display()))?;
        let cfg = Self::from_toml_str(&body)
            .map_err(|e| anyhow::anyhow!("parsing {}: {e}", path.display()))?;
        cfg.warn_on_inline_secrets(path);
        Ok(cfg)
    }

    /// Print a `tracing::warn!` for any plaintext secret present in a
    /// loaded config file. Called by [`Self::load_from_path`].
    /// Currently flags `[third_party] api_key`; kept as a separate
    /// method so future secrets gain warnings here without touching
    /// the load-path itself.
    pub fn warn_on_inline_secrets(&self, source: &Path) {
        if self
            .third_party
            .api_key
            .as_deref()
            .is_some_and(|k| !k.is_empty())
        {
            tracing::warn!(
                config = %source.display(),
                "captchaforge: third_party.api_key is set inline — \
                 prefer the CAPTCHAFORGE_THIRDPARTY_API_KEY env var \
                 (or a secrets store) so the key doesn't get committed \
                 to git alongside the config file"
            );
        }
    }

    /// Parse from a TOML string (no I/O — useful in tests).
    pub fn from_toml_str(s: &str) -> Result<Self, toml::de::Error> {
        toml::from_str(s)
    }

    /// Materialise a [`ChainConfig`] from this config, defaulting any
    /// absent field.
    pub fn chain_config(&self) -> ChainConfig {
        let mut c = ChainConfig::default();
        if let Some(v) = self.per_solver_timeout_ms {
            c.per_solver_timeout_ms = v;
        }
        if let Some(v) = self.screenshot_on_failure {
            c.screenshot_on_failure = v;
        }
        if let Some(v) = self.verify_outcome {
            c.verify_outcome = v;
        }
        c
    }

    /// Materialise a [`SolveConfig`] from this config, defaulting any
    /// absent field.
    pub fn solve_config(&self) -> SolveConfig {
        let mut c = SolveConfig::default();
        let s = &self.solve;
        if let Some(v) = s.checkbox_poll_interval_ms {
            c.checkbox_poll_interval_ms = v;
        }
        if let Some(v) = s.checkbox_max_attempts {
            c.checkbox_max_attempts = v;
        }
        if let Some(v) = s.token_poll_interval_ms {
            c.token_poll_interval_ms = v;
        }
        if let Some(v) = s.token_max_attempts {
            c.token_max_attempts = v;
        }
        if let Some(v) = s.audio_button_delay_ms {
            c.audio_button_delay_ms = v;
        }
        if let Some(v) = s.audio_submit_delay_ms {
            c.audio_submit_delay_ms = v;
        }
        if let Some(v) = s.vlm_http_timeout_ms {
            c.vlm_http_timeout_ms = v;
        }
        if let Some(v) = s.client_http_timeout_ms {
            c.client_http_timeout_ms = v;
        }
        c
    }

    /// Build a [`TokenCache`] honouring the configured TTL (default 60s).
    pub fn build_token_cache(&self) -> TokenCache {
        let ttl = self.cache.ttl_seconds.unwrap_or(DEFAULT_CACHE_TTL_SECONDS);
        TokenCache::with_ttl(std::time::Duration::from_secs(ttl))
    }

    /// Build a [`VlmCaptchaSolver`] with TOML overrides applied. TOML
    /// values beat env vars (which beat defaults).
    pub fn build_vlm_solver(&self) -> VlmCaptchaSolver {
        let mut s = VlmCaptchaSolver::new();
        if let Some(ep) = &self.vlm.endpoint {
            s = s.with_endpoint(ep.clone());
        }
        if let Some(m) = &self.vlm.model {
            s = s.with_model(m.clone());
        }
        s.with_config(self.solve_config())
    }

    /// Build a [`ThirdPartyCaptchaSolver`] from the config. Returns
    /// `None` when the [`ThirdPartyConfig`] is fully empty (no
    /// service selected, no key, no overrides) — a signal that the
    /// caller should leave third-party out of the chain entirely.
    pub fn build_third_party_solver(&self) -> Option<ThirdPartyCaptchaSolver> {
        let tp = &self.third_party;
        if tp.service.is_none()
            && tp.base_url.is_none()
            && tp.api_key.is_none()
            && tp.poll_interval_ms.is_none()
            && tp.max_polls.is_none()
        {
            return None;
        }

        let service = match tp.service.as_deref().unwrap_or("two_captcha") {
            "two_captcha" => ThirdPartyService::TwoCaptcha,
            "cap_monster" => ThirdPartyService::CapMonster,
            "cap_solver" => ThirdPartyService::CapSolver,
            // SSRF defence: only the literal `service = "custom"` plus
            // an explicit `base_url` accepts a freeform endpoint.
            // Previously any unrecognised service string was silently
            // mapped to `Custom { base_url: that_string }`, so a typo
            // ("twocaptcha" without underscore) or untrusted config
            // could redirect the captchaforge worker's HTTP traffic to
            // an arbitrary host — including 169.254.169.254 or other
            // internal-only addresses.
            "custom" => {
                let base_url = tp
                    .base_url
                    .as_deref()
                    .filter(|u| !u.is_empty())
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "third_party.service = \"custom\" requires \
                         third_party.base_url to be set (got empty / missing)"
                        )
                    })
                    .ok()?;
                // Reject anything that doesn't parse as an http(s) URL
                // OR that points at a private/loopback/metadata host.
                // Previously only the scheme was checked, so a config
                // typo (or untrusted config file) could still route
                // POST traffic to 169.254.169.254 / 10.x / [::1].
                let parsed = url::Url::parse(base_url).ok()?;
                if !matches!(parsed.scheme(), "http" | "https") {
                    tracing::warn!(
                        scheme = %parsed.scheme(),
                        "rejecting custom third-party service: non-http(s) scheme"
                    );
                    return None;
                }
                if !host_is_safe_for_outbound(&parsed) {
                    tracing::warn!(
                        url = %parsed,
                        "rejecting custom third-party service: host failed SSRF policy \
                         (loopback / private / link-local / metadata)"
                    );
                    return None;
                }
                ThirdPartyService::Custom {
                    base_url: base_url.to_string(),
                }
            }
            other => {
                tracing::warn!(
                    service = %other,
                    "unrecognised third_party.service — refusing to fall back to \
                     freeform URL (SSRF protection). Set service = \"custom\" + \
                     base_url to use a non-built-in endpoint."
                );
                return None;
            }
        };
        let mut s = match service {
            ThirdPartyService::TwoCaptcha => ThirdPartyCaptchaSolver::two_captcha(),
            ThirdPartyService::CapMonster => ThirdPartyCaptchaSolver::cap_monster(),
            ThirdPartyService::CapSolver => ThirdPartyCaptchaSolver::cap_solver(),
            ThirdPartyService::Custom { base_url } => {
                ThirdPartyCaptchaSolver::custom_endpoint(base_url)
            }
        };
        if let Some(key) = tp.api_key.as_deref().filter(|k| !k.is_empty()) {
            s = s.with_api_key(key);
        }
        if let Some(v) = tp.poll_interval_ms {
            s = s.with_poll_interval_ms(v);
        }
        if let Some(v) = tp.max_polls {
            s = s.with_max_polls(v);
        }
        Some(s)
    }

    /// Build a fully-wired [`CaptchaSolverChain`] from this config:
    /// chain config + token cache + provider registry (with bundled
    /// rules) + Behavioral + VLM (configured) + Audio + third-party
    /// (only when the `[third_party]` section is non-empty OR the
    /// API key env var is set).
    ///
    /// Single entry point used by [`crate::auto_solve`] and the CLI's
    /// `solve` subcommand so they share the same chain shape.
    pub fn build_chain(&self) -> anyhow::Result<CaptchaSolverChain> {
        let registry = Arc::new(ProviderRegistry::with_built_in_rules()?);
        // Start from `default_chain` so all 17 production solvers
        // (Akamai/DataDome/PerimeterX/GeeTest/AwsWaf/Arkose/
        // TurnstileInteractive/VLM/RecaptchaAudio etc.) are wired in.
        // Previously `build_chain` open-coded an 11-solver subset,
        // so `auto_solve` / `solve_url` silently lacked dedicated
        // strategies for those vendors and fell through to the
        // generic behavioural solver — a 30%+ reduction in vendor
        // coverage versus the documented default chain.
        let mut chain = CaptchaSolverChain::default_chain()
            .with_config(self.chain_config())
            .with_provider_registry(registry)
            .with_token_cache(Arc::new(self.build_token_cache()));

        // Layer config-driven extensions on top of the base chain:
        //
        // 1. MultiStepCaptchaSolver — wizard / multi-screen captchas
        //    (math → grid → text). Not in the base chain because it's
        //    config-aware (depends on chain-config timeouts).
        chain.add_solver(MultiStepCaptchaSolver::new());

        // 2. OCR fallback. Solver is inert when tesseract isn't on
        //    PATH (`supports()` returns false), so adding it is free
        //    for users without tesseract installed.
        chain.add_solver(OcrCaptchaSolver::new());

        // 3. Override the default VLM solver with the config-driven
        //    one (endpoint + model from TOML). The base chain's VLM
        //    is at a known position; we just append the configured
        //    one — solver chain dispatch picks the first `supports()`
        //    so duplicates don't hurt, and the configured one is
        //    closer to the tail (lower priority by position) than
        //    the default. Acceptable trade-off; the config VLM gets
        //    its turn after the default fails.
        chain.add_solver(self.build_vlm_solver());

        // 4. Third-party — replace the default chain's
        //    two_captcha-with-no-key with the configured version
        //    (which honors api_key + service selection + endpoints).
        if let Some(tp) = self.build_third_party_solver() {
            chain.add_solver(tp);
        }
        // The base chain already includes a no-key ThirdPartyCaptchaSolver,
        // so we don't need to add another one when config is empty.

        Ok(chain)
    }
}

/// SSRF guard for outbound third-party endpoints. Returns true iff
/// the URL's host is safe for outbound HTTP — public IP / public
/// hostname, no loopback / RFC-1918 / link-local / metadata.
/// Mirrors `validate_endpoint_url` in `solver/third_party.rs` and
/// `validate_public_url` in the CLI.
fn host_is_safe_for_outbound(parsed: &url::Url) -> bool {
    let Some(host) = parsed.host() else {
        return false;
    };
    match host {
        url::Host::Ipv4(addr) => {
            !(addr.is_loopback()
                || addr.is_private()
                || addr.is_link_local()
                || addr.is_unspecified())
        }
        url::Host::Ipv6(addr) => {
            if let Some(v4) = addr.to_ipv4_mapped() {
                if v4.is_loopback() || v4.is_private() || v4.is_link_local() {
                    return false;
                }
            }
            let seg = addr.segments();
            !(addr.is_loopback()
                || addr.is_unspecified()
                || (seg[0] & 0xffc0) == 0xfe80
                || (seg[0] & 0xfe00) == 0xfc00)
        }
        url::Host::Domain(d) => {
            let lower = d.to_ascii_lowercase();
            !matches!(
                lower.as_str(),
                "localhost"
                    | "ip6-localhost"
                    | "ip6-loopback"
                    | "metadata.google.internal"
                    | "metadata.aws.internal"
            )
        }
    }
}

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

    #[test]
    fn empty_toml_round_trips_to_defaults() {
        let c = Config::from_toml_str("").unwrap();
        assert!(c.per_solver_timeout_ms.is_none());
        assert!(c.cache.ttl_seconds.is_none());
        assert!(c.vlm.endpoint.is_none());
        assert!(c.third_party.service.is_none());
    }

    #[test]
    fn typo_in_top_level_key_is_a_parse_error() {
        // deny_unknown_fields catches typos like `per_sovler_timeout_ms`
        // so users don't lose hours wondering why their override is
        // ignored.
        let r = Config::from_toml_str("per_sovler_timeout_ms = 100");
        assert!(r.is_err(), "deny_unknown_fields should reject typos");
    }

    #[test]
    fn full_toml_parses_and_materialises() {
        let toml = r#"
per_solver_timeout_ms = 60000
screenshot_on_failure = false

[cache]
ttl_seconds = 120

[vlm]
endpoint = "http://gpu:11434"
model    = "qwen3-vl:7b"

[third_party]
service  = "cap_monster"
api_key  = "xyz"
poll_interval_ms = 7000
max_polls = 12

[solve]
checkbox_max_attempts = 25
vlm_http_timeout_ms   = 30000
"#;
        let c = Config::from_toml_str(toml).unwrap();
        assert_eq!(c.per_solver_timeout_ms, Some(60000));
        assert_eq!(c.screenshot_on_failure, Some(false));
        assert_eq!(c.cache.ttl_seconds, Some(120));
        assert_eq!(c.vlm.endpoint.as_deref(), Some("http://gpu:11434"));
        assert_eq!(c.vlm.model.as_deref(), Some("qwen3-vl:7b"));
        assert_eq!(c.third_party.service.as_deref(), Some("cap_monster"));
        assert_eq!(c.third_party.api_key.as_deref(), Some("xyz"));
        assert_eq!(c.solve.checkbox_max_attempts, Some(25));
        assert_eq!(c.solve.vlm_http_timeout_ms, Some(30000));

        let cc = c.chain_config();
        assert_eq!(cc.per_solver_timeout_ms, 60000);
        assert!(!cc.screenshot_on_failure);

        let sc = c.solve_config();
        assert_eq!(sc.checkbox_max_attempts, 25);
        assert_eq!(sc.vlm_http_timeout_ms, 30000);
        // Untouched fields keep defaults.
        assert_eq!(
            sc.token_max_attempts,
            SolveConfig::default().token_max_attempts
        );
    }

    #[test]
    fn build_vlm_solver_applies_endpoint_and_model() {
        let c = Config::from_toml_str(
            r#"
[vlm]
endpoint = "http://x:11434"
model    = "m:latest"
"#,
        )
        .unwrap();
        let s = c.build_vlm_solver();
        assert_eq!(s.endpoint, "http://x:11434");
        assert_eq!(s.model, "m:latest");
    }

    #[test]
    fn build_third_party_solver_is_none_when_section_empty() {
        let c = Config::default();
        assert!(c.build_third_party_solver().is_none());
    }

    #[test]
    fn build_third_party_solver_dispatches_service_variants() {
        for (toml, expected_base) in [
            (
                r#"[third_party]
service = "two_captcha"
"#,
                "https://2captcha.com",
            ),
            (
                r#"[third_party]
service = "cap_monster"
"#,
                "https://api.capmonster.cloud",
            ),
            (
                r#"[third_party]
service = "cap_solver"
"#,
                "https://api.capsolver.com",
            ),
            (
                r#"[third_party]
service = "custom"
base_url = "https://my.gw"
"#,
                "https://my.gw",
            ),
        ] {
            let c = Config::from_toml_str(toml).unwrap();
            let s = c
                .build_third_party_solver()
                .expect("config has third_party set; should build a solver");
            assert_eq!(s.service.base_url(), expected_base);
        }
    }

    #[test]
    fn build_third_party_solver_applies_api_key_and_polling() {
        let c = Config::from_toml_str(
            r#"
[third_party]
service = "two_captcha"
api_key = "k123"
poll_interval_ms = 9000
max_polls = 7
"#,
        )
        .unwrap();
        let s = c.build_third_party_solver().unwrap();
        assert_eq!(s.api_key.as_deref(), Some("k123"));
        assert_eq!(s.poll_interval_ms, 9000);
        assert_eq!(s.max_polls, 7);
        assert!(s.has_api_key());
    }

    #[test]
    fn build_third_party_solver_skips_empty_api_key() {
        let c = Config::from_toml_str(
            r#"
[third_party]
service = "two_captcha"
api_key = ""
"#,
        )
        .unwrap();
        let s = c.build_third_party_solver().unwrap();
        // Empty api_key in the TOML doesn't override the env-var
        // fallback path (which we mock as "no key set" here).
        assert_eq!(s.api_key.as_deref().unwrap_or(""), "");
    }

    #[test]
    fn build_token_cache_honours_configured_ttl() {
        let c = Config::from_toml_str(
            r#"[cache]
ttl_seconds = 5
"#,
        )
        .unwrap();
        let cache = c.build_token_cache();
        assert_eq!(cache.ttl(), std::time::Duration::from_secs(5));
    }

    #[test]
    fn build_token_cache_defaults_to_60_seconds() {
        let c = Config::default();
        let cache = c.build_token_cache();
        assert_eq!(cache.ttl(), std::time::Duration::from_secs(60));
    }

    #[test]
    fn search_paths_includes_explicit_env_first() {
        let paths = Config::search_paths_with_env(|name| match name {
            "CAPTCHAFORGE_CONFIG" => Some("/tmp/explicit.toml".into()),
            "HOME" => Some("/home/user".into()),
            _ => None,
        });
        assert!(paths
            .first()
            .unwrap()
            .to_string_lossy()
            .contains("explicit"));
    }

    #[test]
    fn search_paths_skips_empty_explicit_env() {
        let paths = Config::search_paths_with_env(|name| match name {
            "CAPTCHAFORGE_CONFIG" => Some(String::new()),
            "HOME" => Some("/home/user".into()),
            _ => None,
        });
        // First path should be the project-local file, not the empty env.
        assert_eq!(paths.first().unwrap(), &PathBuf::from(".captchaforge.toml"));
    }

    #[test]
    fn search_paths_appends_xdg_config_home() {
        let paths = Config::search_paths_with_env(|name| match name {
            "XDG_CONFIG_HOME" => Some("/x".into()),
            _ => None,
        });
        let last = paths.last().unwrap();
        assert!(
            last.to_string_lossy()
                .contains("/x/captchaforge/config.toml"),
            "expected XDG path; got {:?}",
            last
        );
    }

    #[test]
    fn search_paths_falls_back_to_home_dotconfig() {
        let paths = Config::search_paths_with_env(|name| match name {
            "HOME" => Some("/home/u".into()),
            _ => None,
        });
        let last = paths.last().unwrap();
        assert!(
            last.to_string_lossy()
                .contains("/home/u/.config/captchaforge/config.toml"),
            "expected HOME-based fallback; got {:?}",
            last
        );
    }

    #[test]
    fn load_from_path_round_trips_disk_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("captchaforge.toml");
        std::fs::write(&path, "per_solver_timeout_ms = 12345\n").unwrap();
        let c = Config::load_from_path(&path).unwrap();
        assert_eq!(c.per_solver_timeout_ms, Some(12345));
    }

    #[test]
    fn load_from_path_errors_on_missing_file() {
        assert!(Config::load_from_path("/no/such/captchaforge.toml").is_err());
    }

    #[test]
    fn build_chain_default_config_has_all_default_chain_solvers_plus_config_extensions() {
        // Anchor: build_chain must be a strict SUPERSET of
        // default_chain so `auto_solve` / `solve_url` never lack a
        // vendor-specific solver that the documented default chain
        // already provides.
        let default = crate::solver::CaptchaSolverChain::default_chain();
        let configured = Config::default().build_chain().unwrap();
        let default_names: std::collections::HashSet<&str> =
            default.solver_names().into_iter().collect();
        let configured_names: std::collections::HashSet<&str> =
            configured.solver_names().into_iter().collect();
        for name in &default_names {
            assert!(
                configured_names.contains(*name),
                "Config::build_chain dropped solver {name} that default_chain has — \
                 production one-call flow would silently lack this vendor's strategy"
            );
        }
        // And at least one config-driven extension (MultiStep / Ocr / Vlm overlay).
        assert!(
            configured.solvers.len() >= default.solvers.len(),
            "configured chain ({}) shorter than default ({})",
            configured.solvers.len(),
            default.solvers.len()
        );
    }

    #[test]
    fn build_chain_honors_per_solver_timeout_from_toml() {
        let c = Config::from_toml_str("per_solver_timeout_ms = 7777").unwrap();
        let chain = c.build_chain().unwrap();
        assert_eq!(chain.config.per_solver_timeout_ms, 7777);
    }

    #[test]
    fn warn_on_inline_secrets_is_method_callable_idempotent() {
        // The warning is observable only via tracing; here we just
        // assert the method exists, accepts a path, and doesn't panic
        // on either an empty or populated api_key.
        let empty = Config::default();
        empty.warn_on_inline_secrets(std::path::Path::new("test.toml"));

        let with_key = Config::from_toml_str(
            r#"[third_party]
api_key = "secret"
"#,
        )
        .unwrap();
        with_key.warn_on_inline_secrets(std::path::Path::new("test.toml"));
    }

    #[test]
    fn build_chain_uses_configured_third_party_when_section_present() {
        let c = Config::from_toml_str(
            r#"
[third_party]
service = "cap_solver"
api_key = "k"
"#,
        )
        .unwrap();
        let chain = c.build_chain().unwrap();
        // The chain is default_chain (17 solvers) + MultiStep + Ocr +
        // configured Vlm + configured ThirdParty = 21. Anchoring on
        // ≥17 future-proofs against adding more vendor-specific
        // solvers without rewriting this test on every commit.
        assert!(
            chain.solvers.len() >= 17,
            "configured chain shrunk below default_chain size: {}",
            chain.solvers.len()
        );
        // Last solver is the configured third-party (cap_solver here).
        assert_eq!(
            chain.solvers[chain.solvers.len() - 1].name(),
            "ThirdPartyCaptchaSolver"
        );
    }
}