captchaforge 0.2.39

Captcha detection and solving for Firefox and BiDi-driven browsers. Detection, vendor solver scaffolding, trusted cross-origin click delivery into nested OOPIFs, and stealth personas are implemented and tested; broad live-vendor solve rates are not yet benchmarked.
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
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_twentyone_solvers_in_documented_order() {
    let chain = CaptchaSolverChain::default_chain();
    assert_eq!(chain.solvers.len(), 21);
    assert_eq!(chain.solvers[0].name(), "WaitForTokenSolver");
    assert_eq!(chain.solvers[1].name(), "CloudflareInterstitialSolver");
    assert_eq!(chain.solvers[2].name(), "AkamaiInterstitialSolver");
    assert_eq!(chain.solvers[3].name(), "DataDomeSolver");
    assert_eq!(chain.solvers[4].name(), "PerimeterXSolver");
    assert_eq!(chain.solvers[5].name(), "GeeTestSolver");
    assert_eq!(chain.solvers[6].name(), "AwsWafSolver");
    assert_eq!(chain.solvers[7].name(), "ArkoseSolver");
    assert_eq!(chain.solvers[8].name(), "ImpervaSolver");
    assert_eq!(chain.solvers[9].name(), "KasadaSolver");
    assert_eq!(chain.solvers[10].name(), "MathCaptchaSolver");
    assert_eq!(chain.solvers[11].name(), "PowCaptchaSolver");
    assert_eq!(chain.solvers[12].name(), "SliderCaptchaSolver");
    assert_eq!(chain.solvers[13].name(), "TurnstileInteractiveSolver");
    assert_eq!(chain.solvers[14].name(), "BehavioralCaptchaSolver");
    assert_eq!(chain.solvers[15].name(), "YoloGridSolver");
    assert_eq!(chain.solvers[16].name(), "CrnnTextSolver");
    assert_eq!(chain.solvers[17].name(), "VlmCaptchaSolver");
    // Vendor-specific reCAPTCHA audio comes BEFORE the generic
    // AudioCaptchaSolver so the bframe-aware path wins.
    assert_eq!(chain.solvers[18].name(), "RecaptchaAudioSolver");
    assert_eq!(chain.solvers[19].name(), "AudioCaptchaSolver");
    assert_eq!(chain.solvers[20].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);
    // Outcome verification is on by default, that's the
    // "no green-checkmark lies" guarantee. If this assertion
    // ever flips to assert!(!) without explicit user request,
    // it's a regression that silently re-enables the failure
    // mode the oracle was built to close.
    assert!(chain.config.verify_outcome);
}

#[test]
fn oracle_for_kind_resolves_each_built_in_to_a_documented_oracle() {
    use crate::captcha_detect::DetectedCaptcha as K;
    // Each built-in vendor with a documented token shape MUST
    // resolve. Adding a new vendor variant without registering
    // here would silently bypass the decoy check, this test
    // catches that.
    for kind in [K::Turnstile, K::RecaptchaV2, K::RecaptchaV3, K::HCaptcha] {
        assert!(
            oracle_for_kind(&kind).is_some(),
            "{kind:?} must have a token-shape oracle wired"
        );
    }
}

#[test]
fn oracle_for_kind_returns_none_for_kinds_without_documented_token_shape() {
    use crate::captcha_detect::DetectedCaptcha as K;
    // Captchas whose "token" is application-defined (canvas /
    // slider / multi-step / image-grid VLM) deliberately have
    // no oracle. The chain skips the decoy check and falls
    // through to the existing oracle::classify path.
    for kind in [
        K::SliderCaptcha,
        K::CanvasCaptcha,
        K::MultiStepCaptcha,
        K::ImageCaptcha,
        K::PowCaptcha,
    ] {
        assert!(
            oracle_for_kind(&kind).is_none(),
            "{kind:?} must NOT have a token-shape oracle (token is app-defined)"
        );
    }
}

#[test]
fn oracle_for_kind_resolves_recaptcha_enterprise_custom_rule_to_enterprise_oracle() {
    use crate::captcha_detect::DetectedCaptcha as K;
    let oracle = oracle_for_kind(&K::Custom("recaptcha_enterprise".into()))
        .expect("recaptcha_enterprise must resolve via Custom-name match");
    assert_eq!(oracle.vendor(), "recaptcha-enterprise");
}

#[test]
fn oracle_for_kind_resolves_hcaptcha_enterprise_to_hcaptcha_oracle() {
    // hCaptcha Enterprise tokens have the same wire shape as
    // free-tier hCaptcha tokens (both share one oracle).
    use crate::captcha_detect::DetectedCaptcha as K;
    let oracle = oracle_for_kind(&K::Custom("hcaptcha_enterprise".into()))
        .expect("hcaptcha_enterprise must resolve");
    assert_eq!(oracle.vendor(), "hcaptcha");
}

#[test]
fn oracle_for_kind_returns_none_for_unrecognised_custom_rule() {
    use crate::captcha_detect::DetectedCaptcha as K;
    assert!(oracle_for_kind(&K::Custom("totally_unknown_vendor".into())).is_none());
}

#[test]
fn verify_outcome_downgrades_success_when_oracle_disagrees() {
    // Exercise the REAL classify() function with real PageSnapshot
    // values rather than asserting that
    // `matches!(Advanced, Advanced)` is true (which it always is).
    // This catches a refactor that breaks the verdict mapping.
    use crate::solver::oracle::{classify, OutcomeClassification, PageSnapshot};

    // Cookie-only change → Advanced (success-keep).
    let before = PageSnapshot {
        url: "/x".into(),
        title: "T".into(),
        body_excerpt: "b".into(),
        captcha_present: Some(true),
        cookie_names: vec!["__cf_bm".into()],
    };
    let after_advanced = PageSnapshot {
        captcha_present: Some(false),
        cookie_names: vec!["__cf_bm".into(), "sessionid".into()],
        ..before.clone()
    };
    assert_eq!(
        classify(&before, &after_advanced),
        OutcomeClassification::Advanced
    );

    // Widget still present → Recycled (success-downgrade).
    let after_recycled = PageSnapshot {
        captcha_present: Some(true),
        ..before.clone()
    };
    assert_eq!(
        classify(&before, &after_recycled),
        OutcomeClassification::Recycled
    );

    // Body says "access denied" → HardBlock.
    let after_blocked = PageSnapshot {
        captcha_present: Some(false),
        body_excerpt: "access denied, bot detected".into(),
        ..before.clone()
    };
    assert_eq!(
        classify(&before, &after_blocked),
        OutcomeClassification::HardBlock
    );

    // Nothing moved → SilentFail.
    let after_silent = PageSnapshot {
        captcha_present: Some(false),
        ..before.clone()
    };
    assert_eq!(
        classify(&before, &after_silent),
        OutcomeClassification::SilentFail
    );
}

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

#[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");
    // YoloGridSolver only claims RecaptchaV2 when the `vision`
    // feature is enabled (disabled by default).
    #[cfg(feature = "vision")]
    {
        assert_eq!(ordered[2].name(), "YoloGridSolver");
        assert_eq!(ordered[3].name(), "VlmCaptchaSolver");
        assert_eq!(ordered[4].name(), "RecaptchaAudioSolver");
        assert_eq!(ordered[5].name(), "AudioCaptchaSolver");
    }
    #[cfg(not(feature = "vision"))]
    {
        assert_eq!(ordered[2].name(), "VlmCaptchaSolver");
        // Vendor-specific reCAPTCHA audio routes BEFORE the generic
        // AudioCaptchaSolver, the bframe-aware path needs first crack
        // before the generic page-only fallback gets a turn.
        assert_eq!(ordered[3].name(), "RecaptchaAudioSolver");
        assert_eq!(ordered[4].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).
    // YoloGridSolver only claims HCaptcha when the `vision`
    // feature is enabled (disabled by default).
    // 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,
    );
    #[cfg(feature = "vision")]
    {
        assert_eq!(ordered.len(), 3);
        assert_eq!(ordered[0].name(), "WaitForTokenSolver");
        assert_eq!(ordered[1].name(), "YoloGridSolver");
        assert_eq!(ordered[2].name(), "VlmCaptchaSolver");
    }
    #[cfg(not(feature = "vision"))]
    {
        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());
}