captchaforge 0.2.11

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
//! [`CaptchaProvider`] — bundles a captcha's detector with its
//! recommended solver routing in one self-contained unit.
//!
//! Adding a new captcha type to captchaforge previously meant editing
//! at least four places: the `DetectedCaptcha` enum, the
//! `parse_detection_result` mapper, the `DetectorRegistry`, and the
//! `detected_to_type` mapper in `solver/util.rs` — easy to forget one,
//! easy to disagree across the four. With [`CaptchaProvider`], a new
//! captcha is one struct with three trait impls (`Detector`,
//! `CaptchaProvider`) in one file.
//!
//! The provider does NOT own the [`Detector`] — it borrows it via
//! [`CaptchaProvider::detector`]. This means existing zero-size
//! detector structs (`TurnstileDetector` etc.) implement both traits
//! themselves; no wrapper allocation, no extra registry sync to keep.
//!
//! Backward compatibility: [`DetectorRegistry`] still works. A new
//! [`ProviderRegistry`] surface is added; consumers can use either,
//! and `ProviderRegistry::detectors()` returns the same set the legacy
//! registry would have produced.
use crate::captcha_detect::{
    AudioCaptchaDetector, CanvasCaptchaDetector, ChallengePageDetector, DetectedCaptcha, Detector,
    HCaptchaDetector, ImageCaptchaDetector, MultiStepCaptchaDetector, PowCaptchaDetector,
    RecaptchaDetector, ShadowDomDetector, SliderCaptchaDetector, TurnstileDetector,
};
use crate::solver::{CaptchaType, SolveMethod};

/// One captcha vendor / type, fully described.
///
/// New captchas implement this trait alongside [`Detector`] in a single
/// file under `src/detect/`. The bundled metadata lets the orchestrator
/// dispatch detection AND make an informed first guess about which
/// solver to try first — without depending on the [`PatternStore`]
/// having seen the domain before.
///
/// `recommended_solver_methods` is a HINT, not a constraint: the
/// solver chain may override the order based on per-domain learned
/// success rates from the pattern store.
pub trait CaptchaProvider: Send + Sync {
    /// Stable identifier — same value as [`Detector::name`] by
    /// convention so logs and reports correlate.
    fn name(&self) -> &'static str;

    /// The [`DetectedCaptcha`] variant this provider produces.
    fn detected_kind(&self) -> DetectedCaptcha;

    /// The [`CaptchaType`] used by the solver chain to look up
    /// per-type behaviour.
    fn captcha_type(&self) -> CaptchaType;

    /// Solver methods, ordered by recommended preference for this
    /// captcha. The chain consults this for cold-start routing; once
    /// the pattern store has data for the domain, learned ordering
    /// takes priority.
    ///
    /// Method-based routing collides when multiple solvers share a
    /// `SolveMethod` (Math, Pow, Slider, Behavioral all return
    /// `BehavioralBypass`) — the chain has to fall back to the
    /// first solver whose `supports()` returns true, which is
    /// fragile. New code SHOULD implement
    /// [`Self::recommended_solver_names`] instead; that path is
    /// name-based and avoids collisions. This method stays for
    /// backwards compatibility and is the fallback when
    /// `recommended_solver_names()` returns empty.
    fn recommended_solver_methods(&self) -> &'static [SolveMethod];

    /// Solver `name()`s, ordered by recommended preference. When
    /// non-empty, the chain prefers this list over
    /// [`Self::recommended_solver_methods`] — every name is matched
    /// against `solver.name()` exactly. Empty default means the
    /// chain falls back to method-based routing (the older path).
    ///
    /// Use this for vendors with dedicated solvers
    /// (`TurnstileInteractiveSolver`, `DataDomeSolver`, etc.) so the
    /// vendor's specific solver wins over the generic one even when
    /// both implement the same `SolveMethod`.
    fn recommended_solver_names(&self) -> &'static [&'static str] {
        &[]
    }

    /// Borrow the page-side detector this provider is bound to.
    fn detector(&self) -> &dyn Detector;
}

/// Registry of all known captcha providers. Replaces the standalone
/// [`DetectorRegistry`] for new code; existing code can still use the
/// detector-only registry.
///
/// The default-constructed registry contains every built-in provider
/// in priority order (matching the legacy detector registry exactly).
/// Custom providers can be appended via [`ProviderRegistry::push`].
pub struct ProviderRegistry {
    providers: Vec<Box<dyn CaptchaProvider>>,
}

impl ProviderRegistry {
    /// Construct a registry containing the built-in providers.
    pub fn new() -> Self {
        let mut providers: Vec<Box<dyn CaptchaProvider>> = vec![
            Box::new(ChallengePageDetector),
            Box::new(TurnstileDetector),
            Box::new(RecaptchaDetector),
            Box::new(HCaptchaDetector),
            Box::new(ImageCaptchaDetector),
            Box::new(AudioCaptchaDetector),
            Box::new(PowCaptchaDetector),
            Box::new(CanvasCaptchaDetector),
            Box::new(SliderCaptchaDetector),
            Box::new(MultiStepCaptchaDetector),
            Box::new(ShadowDomDetector),
        ];
        providers.sort_by_key(|p| p.detector().priority());
        Self { providers }
    }

    /// Built-in providers PLUS every rule from the bundled
    /// `community.toml` rule pack — DataDome, Akamai, PerimeterX/HUMAN,
    /// Arkose, Geetest v3+v4, AWS WAF, Friendly Captcha, MTCaptcha,
    /// WordPress math captchas, and any other rules added to the pack.
    ///
    /// The single-call entry point for production deployments that
    /// want maximum coverage out of the box.
    ///
    /// Returns `Err` if the bundled TOML somehow fails to parse —
    /// which only happens if the in-tree `community.toml` has been
    /// corrupted, since it is `include_str!`-ed at compile time.
    pub fn with_built_in_rules() -> anyhow::Result<Self> {
        use crate::detect::rules::{built_in_rules, RuleDetector};

        let mut reg = Self::new();
        let rules = built_in_rules()?;
        for rule in rules.providers {
            reg.providers.push(Box::new(RuleDetector::from(rule)));
        }
        reg.providers.sort_by_key(|p| p.detector().priority());
        Ok(reg)
    }

    /// Append a custom provider.
    pub fn push<P: CaptchaProvider + 'static>(&mut self, provider: P) {
        self.providers.push(Box::new(provider));
        self.providers.sort_by_key(|p| p.detector().priority());
    }

    /// Borrow the providers in priority order.
    pub fn providers(&self) -> &[Box<dyn CaptchaProvider>] {
        &self.providers
    }

    /// Look up a provider by its [`DetectedCaptcha`] kind. Returns
    /// `None` if no registered provider claims the kind. Used by the
    /// solver chain to find the recommended solver list for a freshly
    /// detected captcha without re-running detection.
    pub fn find_by_kind(&self, kind: &DetectedCaptcha) -> Option<&dyn CaptchaProvider> {
        self.providers
            .iter()
            .find(|p| p.detected_kind() == *kind)
            .map(|b| b.as_ref())
    }
}

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

// ─── Built-in CaptchaProvider impls ─────────────────────────────────────────
//
// Each existing detector picks up a CaptchaProvider impl here so the new
// trait is functional without touching every per-detector file. New
// captchas added in future PRs SHOULD put their CaptchaProvider impl in
// the same file as their Detector impl — the impls living here is a
// migration convenience, not a long-term pattern.

macro_rules! provider_impl {
    (
        $detector:ident,
        kind = $kind:ident,
        type = $captcha_type:expr,
        methods = [$($method:ident),+ $(,)?],
    ) => {
        impl CaptchaProvider for $detector {
            fn name(&self) -> &'static str {
                <Self as Detector>::name(self)
            }
            fn detected_kind(&self) -> DetectedCaptcha {
                DetectedCaptcha::$kind
            }
            fn captcha_type(&self) -> CaptchaType {
                $captcha_type
            }
            fn recommended_solver_methods(&self) -> &'static [SolveMethod] {
                &[$(SolveMethod::$method),+]
            }
            fn detector(&self) -> &dyn Detector {
                self
            }
        }
    };
}

provider_impl!(
    ChallengePageDetector,
    kind = Turnstile,
    type = CaptchaType::CloudflareTurnstile,
    methods = [BehavioralBypass, ThirdPartyService],
);
provider_impl!(
    TurnstileDetector,
    kind = Turnstile,
    type = CaptchaType::CloudflareTurnstile,
    methods = [BehavioralBypass, ThirdPartyService],
);
provider_impl!(
    RecaptchaDetector,
    kind = RecaptchaV2,
    type = CaptchaType::RecaptchaV2,
    methods = [BehavioralBypass, AudioBypass, VisionLLM, ThirdPartyService],
);
provider_impl!(
    HCaptchaDetector,
    kind = HCaptcha,
    type = CaptchaType::HCaptcha,
    methods = [VisionLLM, AudioBypass, ThirdPartyService],
);
provider_impl!(
    ImageCaptchaDetector,
    kind = ImageCaptcha,
    type = CaptchaType::ImageGrid,
    methods = [VisionLLM, ThirdPartyService],
);
provider_impl!(
    AudioCaptchaDetector,
    kind = AudioCaptcha,
    type = CaptchaType::AudioCaptcha,
    methods = [AudioBypass, ThirdPartyService],
);
provider_impl!(
    PowCaptchaDetector,
    kind = PowCaptcha,
    type = CaptchaType::PowCaptcha,
    methods = [BehavioralBypass],
);
provider_impl!(
    SliderCaptchaDetector,
    kind = SliderCaptcha,
    type = CaptchaType::Slider,
    methods = [BehavioralBypass, VisionLLM, ThirdPartyService],
);
provider_impl!(
    CanvasCaptchaDetector,
    kind = CanvasCaptcha,
    type = CaptchaType::CanvasCaptcha,
    methods = [VisionLLM, ThirdPartyService],
);
provider_impl!(
    ShadowDomDetector,
    kind = ShadowDomCaptcha,
    type = CaptchaType::ShadowDomCaptcha,
    methods = [VisionLLM, BehavioralBypass],
);
provider_impl!(
    MultiStepCaptchaDetector,
    kind = MultiStepCaptcha,
    type = CaptchaType::MultiStepCaptcha,
    methods = [BehavioralBypass, VisionLLM],
);

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

    #[test]
    fn registry_contains_every_builtin_provider() {
        let reg = ProviderRegistry::new();
        let names: Vec<_> = reg.providers().iter().map(|p| p.name()).collect();
        for expected in [
            "challenge_page",
            "turnstile",
            "recaptcha",
            "hcaptcha",
            "image_captcha",
            "audio_captcha",
            "pow_captcha",
            "canvas_captcha",
            "slider_captcha",
            "multi_step_captcha",
            "shadow_dom",
        ] {
            assert!(names.contains(&expected), "missing provider: {expected}");
        }
    }

    #[test]
    fn registry_is_priority_ordered() {
        let reg = ProviderRegistry::new();
        let prios: Vec<i32> = reg
            .providers()
            .iter()
            .map(|p| p.detector().priority())
            .collect();
        let mut sorted = prios.clone();
        sorted.sort_unstable();
        assert_eq!(prios, sorted, "registry must be priority-ordered");
    }

    #[test]
    fn find_by_kind_locates_known_kinds() {
        let reg = ProviderRegistry::new();
        let p = reg
            .find_by_kind(&DetectedCaptcha::HCaptcha)
            .expect("hcaptcha provider");
        assert_eq!(p.name(), "hcaptcha");
        assert_eq!(p.captcha_type(), CaptchaType::HCaptcha);
    }

    #[test]
    fn find_by_kind_returns_none_for_unhandled_kind() {
        let reg = ProviderRegistry::new();
        assert!(reg.find_by_kind(&DetectedCaptcha::None).is_none());
    }

    #[test]
    fn turnstile_recommends_behavioral_first() {
        let reg = ProviderRegistry::new();
        let p = reg.find_by_kind(&DetectedCaptcha::Turnstile).unwrap();
        assert_eq!(
            p.recommended_solver_methods().first(),
            Some(&SolveMethod::BehavioralBypass),
            "Turnstile should try BehavioralBypass first; was: {:?}",
            p.recommended_solver_methods(),
        );
    }

    #[test]
    fn image_captcha_recommends_vision_llm_first() {
        let reg = ProviderRegistry::new();
        let p = reg.find_by_kind(&DetectedCaptcha::ImageCaptcha).unwrap();
        assert_eq!(
            p.recommended_solver_methods().first(),
            Some(&SolveMethod::VisionLLM),
            "ImageCaptcha should try VisionLLM first",
        );
    }

    #[test]
    fn with_built_in_rules_includes_built_in_providers() {
        let reg = ProviderRegistry::with_built_in_rules().expect("bundled rules parse");
        let names: Vec<_> = reg.providers().iter().map(|p| p.name()).collect();
        // Built-ins must still be present.
        for expected in ["turnstile", "hcaptcha", "recaptcha"] {
            assert!(names.contains(&expected), "lost built-in: {expected}");
        }
    }

    #[test]
    fn with_built_in_rules_includes_community_rules() {
        let reg = ProviderRegistry::with_built_in_rules().unwrap();
        let names: Vec<_> = reg.providers().iter().map(|p| p.name()).collect();
        for expected in [
            "datadome",
            "akamai_bot_manager",
            "perimeterx_human",
            "arkose_funcaptcha",
            "geetest_v3",
            "geetest_v4",
            "aws_waf_captcha",
            "friendly_captcha",
            "mtcaptcha",
            "wp_math_captcha",
            // Round-12 vendors
            "imperva_incapsula",
            "kasada",
            "f5_distributed_cloud",
            "yandex_smartcaptcha",
            "tencent_captcha",
            "keycaptcha",
        ] {
            assert!(
                names.contains(&expected),
                "missing community rule: {expected}"
            );
        }
    }

    #[test]
    fn with_built_in_rules_keeps_priority_order_across_built_in_and_rules() {
        let reg = ProviderRegistry::with_built_in_rules().unwrap();
        let prios: Vec<i32> = reg
            .providers()
            .iter()
            .map(|p| p.detector().priority())
            .collect();
        let mut sorted = prios.clone();
        sorted.sort_unstable();
        assert_eq!(prios, sorted, "merged registry must be priority-sorted");
    }

    #[test]
    fn community_rules_route_to_custom_captcha_type() {
        let reg = ProviderRegistry::with_built_in_rules().unwrap();
        let datadome = reg
            .providers()
            .iter()
            .find(|p| p.name() == "datadome")
            .expect("datadome registered");
        // TOML rules surface as Custom kind / type so downstream
        // routing can key on the vendor identifier.
        assert!(
            matches!(datadome.detected_kind(), DetectedCaptcha::Custom(ref s) if s == "datadome"),
            "datadome.detected_kind should be Custom(datadome)",
        );
        assert!(
            matches!(datadome.captcha_type(), CaptchaType::Custom(ref s) if s == "datadome"),
            "datadome.captcha_type should be Custom(datadome)",
        );
    }

    #[test]
    fn custom_provider_can_be_pushed_and_sorted() {
        struct DummyDetector;
        #[async_trait::async_trait]
        impl Detector for DummyDetector {
            fn name(&self) -> &'static str {
                "dummy"
            }
            fn priority(&self) -> i32 {
                1
            }
            async fn detect(
                &self,
                _page: &chromiumoxide::Page,
            ) -> anyhow::Result<Option<crate::captcha_detect::CaptchaInfo>> {
                Ok(None)
            }
        }
        impl CaptchaProvider for DummyDetector {
            fn name(&self) -> &'static str {
                "dummy"
            }
            fn detected_kind(&self) -> DetectedCaptcha {
                DetectedCaptcha::None
            }
            fn captcha_type(&self) -> CaptchaType {
                CaptchaType::Custom("dummy".into())
            }
            fn recommended_solver_methods(&self) -> &'static [SolveMethod] {
                &[SolveMethod::BehavioralBypass]
            }
            fn detector(&self) -> &dyn Detector {
                self
            }
        }

        let mut reg = ProviderRegistry::new();
        reg.push(DummyDetector);
        // priority(1) is below all built-ins (lowest is challenge_page=5),
        // so the custom provider should sort to the front.
        assert_eq!(reg.providers().first().unwrap().name(), "dummy");
    }
}