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
//! GeeTest v3 + v4 dedicated solver.
//!
//! GeeTest is the dominant bot-management captcha vendor in mainland
//! China and second-largest globally for slider-style puzzles
//! (~3% of top-1M sites per BuiltWith Q1 2026, far higher inside CN).
//! Two on-the-wire protocols coexist:
//!
//! - **v3**: the legacy `initGeetest({ gt, challenge, ... })` API.
//!   On a successful solve, JS populates three values
//!   (`geetest_challenge`, `geetest_validate`, `geetest_seccode`)
//!   either on `window` or on hidden form inputs. The triple is what
//!   the host server uses to verify the solve.
//! - **v4**: the `initGeetest4({ captchaId, ... })` API. On
//!   success, JS surfaces a quad (`lot_number`, `pass_token`,
//!   `gen_time`, `captcha_output`) inside the callback payload, which
//!   sites typically stash on hidden inputs or window globals.
//!
//! Both versions render a slider OR a click-puzzle in an iframe.
//! The actual *interaction* (drag the slider / click the icons) is
//! still handled by [`super::super::SliderCaptchaSolver`] for
//! sliders or [`super::super::VlmCaptchaSolver`] for click-puzzles 
//! we don't reinvent that here. What this solver adds is the
//! version-aware **token-watch**: poll for the v3 triple or v4 quad
//! to populate, return success when they do, return failure when
//! they don't (so the chain falls through to the appropriate
//! interaction solver). The pattern matches
//! [`super::super::WaitForTokenSolver`] but is narrower
//! and emits a richer solution payload that downstream verification
//! can use directly.

use super::super::*;
use crate::captcha_detect::DetectedCaptcha;
use std::time::{Duration, Instant};

/// Default total wait budget. GeeTest's auto-pass scenarios
/// (low-risk session, valid `_pxhd`-equivalent device cookie)
/// resolve in ≤3s; 12s upper bound matches `WaitForTokenSolver`.
const DEFAULT_MAX_WAIT_MS: u64 = 12_000;

/// GeeTest v3 + v4 token-watch solver.
pub struct GeeTestSolver {
    max_wait_ms: u64,
}

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

impl GeeTestSolver {
    pub fn new() -> Self {
        Self {
            max_wait_ms: DEFAULT_MAX_WAIT_MS,
        }
    }

    pub fn with_max_wait_ms(mut self, ms: u64) -> Self {
        self.max_wait_ms = ms;
        self
    }
}

/// Which on-the-wire protocol the page uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GeeTestProtocol {
    /// Legacy `initGeetest({ gt, challenge })` API.
    V3,
    /// Current `initGeetest4({ captchaId })` API.
    V4,
}

/// JS that probes the page for GeeTest state. Returns one of:
///   - `{ phase: "v3_passed", triple: { challenge, validate, seccode } }`
///: v3 success triple populated
///   - `{ phase: "v4_passed", quad: { lot_number, pass_token, gen_time, captcha_output } }`
///: v4 success quad populated
///   - `{ phase: "v3_pending" }` / `{ phase: "v4_pending" }` 
///     widget present, no token yet
///   - `{ phase: "unknown" }`: neither GeeTest version detected
const PHASE_PROBE_JS: &str = r#"
(() => {
    /* v4 token quad, read from window.captcha4Result (custom
       integration), hidden inputs (the most common shape), or the
       documented onSuccess callback payload that sites usually
       stash on window. */
    const readField = (sel) => {
        const el = document.querySelector(sel);
        return el ? (el.value || el.getAttribute('value') || '') : '';
    };
    const v4 = {
        lot_number: readField('input[name="lot_number"], input[name="geetest_lot_number"]') || (window.captcha4Result && window.captcha4Result.lot_number) || '',
        pass_token: readField('input[name="pass_token"], input[name="geetest_pass_token"]') || (window.captcha4Result && window.captcha4Result.pass_token) || '',
        gen_time:   readField('input[name="gen_time"], input[name="geetest_gen_time"]')   || (window.captcha4Result && window.captcha4Result.gen_time)   || '',
        captcha_output: readField('input[name="captcha_output"], input[name="geetest_captcha_output"]') || (window.captcha4Result && window.captcha4Result.captcha_output) || '',
    };
    if (v4.lot_number && v4.pass_token && v4.captcha_output) {
        return { phase: 'v4_passed', quad: v4 };
    }
    /* v3 token triple, the canonical hidden inputs, also commonly
       window.geetest_validate etc. */
    const v3 = {
        challenge: readField('input[name="geetest_challenge"]') || window.geetest_challenge || '',
        validate:  readField('input[name="geetest_validate"]')  || window.geetest_validate  || '',
        seccode:   readField('input[name="geetest_seccode"]')   || window.geetest_seccode   || '',
    };
    if (v3.challenge && v3.validate && v3.seccode) {
        return { phase: 'v3_passed', triple: v3 };
    }
    /* Detect which version is on the page so the host can pick the
       right wait/interaction strategy. */
    const v4Present =
        !!document.querySelector('.geetest_box, .geetest_panel, [data-gt]') ||
        typeof window.initGeetest4 !== 'undefined';
    if (v4Present) return { phase: 'v4_pending' };
    const v3Present =
        !!document.querySelector('.geetest_holder, .geetest_radar_btn, .geetest_slider_button') ||
        typeof window.initGeetest !== 'undefined';
    if (v3Present) return { phase: 'v3_pending' };
    return { phase: 'unknown' };
})()
"#;

#[derive(Debug, serde::Deserialize)]
struct PhaseProbe {
    phase: String,
    #[serde(default)]
    triple: Option<V3Triple>,
    #[serde(default)]
    quad: Option<V4Quad>,
}

#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
#[allow(non_snake_case)]
struct V3Triple {
    challenge: String,
    validate: String,
    seccode: String,
}

#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
#[allow(non_snake_case)]
struct V4Quad {
    lot_number: String,
    pass_token: String,
    gen_time: String,
    captcha_output: String,
}

/// Pure validator for a v3 token triple. Each field non-empty
/// AND `seccode` matches the documented `<32 hex chars>|jordan` shape.
///
/// # Examples
///
/// ```
/// use captchaforge::solver::vendors::geetest::is_valid_v3_triple;
///
/// assert!(!is_valid_v3_triple("", "validated", "abc|jordan"));
/// assert!(!is_valid_v3_triple("c", "v", ""));
/// assert!(is_valid_v3_triple("c", "v", "0123456789abcdef0123456789abcdef|jordan"));
/// ```
pub fn is_valid_v3_triple(challenge: &str, validate: &str, seccode: &str) -> bool {
    if challenge.is_empty() || validate.is_empty() || seccode.is_empty() {
        return false;
    }
    // Documented shape: `<hash>|jordan` where the suffix may be
    // "jordan" (the documented sentinel) or absent on some legacy
    // tenants. We require the pipe-separated structure OR a 32+ char
    // hex prefix; either is enough to distinguish a real seccode
    // from an empty string masquerading as set.
    seccode.contains('|') || seccode.chars().filter(|c| c.is_ascii_hexdigit()).count() >= 32
}

/// Pure validator for a v4 token quad. Each field non-empty AND
/// `gen_time` parses as a unix timestamp.
///
/// # Examples
///
/// ```
/// use captchaforge::solver::vendors::geetest::is_valid_v4_quad;
///
/// assert!(!is_valid_v4_quad("", "p", "1234567890", "{\"x\":1}"));
/// assert!(!is_valid_v4_quad("l", "p", "not-a-timestamp", "{}"));
/// assert!(is_valid_v4_quad("l", "p", "1736899200", "{\"x\":1}"));
/// ```
pub fn is_valid_v4_quad(
    lot_number: &str,
    pass_token: &str,
    gen_time: &str,
    captcha_output: &str,
) -> bool {
    if lot_number.is_empty()
        || pass_token.is_empty()
        || gen_time.is_empty()
        || captcha_output.is_empty()
    {
        return false;
    }
    // gen_time must parse as a unix epoch (seconds). Sanity range
    // 2020-01-01 .. 2100-01-01 (anything outside is suspicious).
    let Ok(t) = gen_time.trim().parse::<u64>() else {
        return false;
    };
    (1_577_836_800..4_102_444_800).contains(&t)
}

#[async_trait]
impl CaptchaSolver for GeeTestSolver {
    fn name(&self) -> &'static str {
        "GeeTestSolver"
    }

    fn method(&self) -> SolveMethod {
        SolveMethod::AutoPass
    }

    fn supports(&self, kind: &DetectedCaptcha) -> bool {
        // GeeTest is detected as Custom("geetest_v3") / ("geetest_v4")
        // by the bundled community rules. SliderCaptcha is also
        // accepted because GeeTest is the most common slider vendor.
        matches!(
            kind,
            DetectedCaptcha::Custom(_) | DetectedCaptcha::SliderCaptcha
        )
    }

    async fn solve(&self, page: &Page, _info: &CaptchaInfo) -> Result<CaptchaSolveResult> {
        let t0 = Instant::now();
        let deadline = t0 + Duration::from_millis(self.max_wait_ms);

        loop {
            let raw = page
                .evaluate(PHASE_PROBE_JS)
                .await
                .map_err(|e| anyhow!("GeeTest probe failed: {e}"))?;
            let probe: PhaseProbe = match raw.into_value() {
                Ok(p) => p,
                Err(_) => PhaseProbe {
                    phase: "unknown".into(),
                    triple: None,
                    quad: None,
                },
            };

            match probe.phase.as_str() {
                "v3_passed" => {
                    if let Some(t) = probe.triple.as_ref() {
                        if is_valid_v3_triple(&t.challenge, &t.validate, &t.seccode) {
                            let cookies = crate::cookies::capture_from_page(page)
                                .await
                                .unwrap_or_default();
                            return Ok(CaptchaSolveResult {
                                solution: serde_json::to_string(t).unwrap_or_default(),
                                confidence: 1.0,
                                method: SolveMethod::AutoPass,
                                time_ms: t0.elapsed().as_millis() as u64,
                                success: true,
                                screenshot: None,
                                cookies,
                                verified_outcome: None,
                            });
                        }
                    }
                }
                "v4_passed" => {
                    if let Some(q) = probe.quad.as_ref() {
                        if is_valid_v4_quad(
                            &q.lot_number,
                            &q.pass_token,
                            &q.gen_time,
                            &q.captcha_output,
                        ) {
                            let cookies = crate::cookies::capture_from_page(page)
                                .await
                                .unwrap_or_default();
                            return Ok(CaptchaSolveResult {
                                solution: serde_json::to_string(q).unwrap_or_default(),
                                confidence: 1.0,
                                method: SolveMethod::AutoPass,
                                time_ms: t0.elapsed().as_millis() as u64,
                                success: true,
                                screenshot: None,
                                cookies,
                                verified_outcome: None,
                            });
                        }
                    }
                }
                _ => {} // pending / unknown, keep waiting
            }

            if Instant::now() >= deadline {
                return Ok(CaptchaSolveResult::failure(
                    SolveMethod::AutoPass,
                    t0.elapsed().as_millis() as u64,
                ));
            }
            tokio::time::sleep(Duration::from_millis(400)).await;
        }
    }
}

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

    #[test]
    fn defaults_are_sane() {
        assert_eq!(GeeTestSolver::new().max_wait_ms, 12_000);
    }

    #[test]
    fn builders_override() {
        assert_eq!(
            GeeTestSolver::new().with_max_wait_ms(5_000).max_wait_ms,
            5_000
        );
    }

    #[test]
    fn name_method_stable() {
        let s = GeeTestSolver::new();
        assert_eq!(s.name(), "GeeTestSolver");
        assert_eq!(s.method(), SolveMethod::AutoPass);
    }

    #[test]
    fn supports_custom_and_slider() {
        let s = GeeTestSolver::new();
        assert!(s.supports(&DetectedCaptcha::Custom("geetest_v3".into())));
        assert!(s.supports(&DetectedCaptcha::Custom("geetest_v4".into())));
        assert!(s.supports(&DetectedCaptcha::SliderCaptcha));
        assert!(!s.supports(&DetectedCaptcha::Turnstile));
        assert!(!s.supports(&DetectedCaptcha::HCaptcha));
        assert!(!s.supports(&DetectedCaptcha::RecaptchaV2));
    }

    #[test]
    fn is_valid_v3_triple_rejects_empty() {
        assert!(!is_valid_v3_triple("", "v", "abc|jordan"));
        assert!(!is_valid_v3_triple("c", "", "abc|jordan"));
        assert!(!is_valid_v3_triple("c", "v", ""));
    }

    #[test]
    fn is_valid_v3_triple_accepts_pipe_seccode() {
        assert!(is_valid_v3_triple(
            "c",
            "v",
            "0123456789abcdef0123456789abcdef|jordan"
        ));
    }

    #[test]
    fn is_valid_v3_triple_accepts_hex_only_seccode() {
        // Some legacy tenants drop the `|jordan` sentinel; raw hex
        // is enough as long as it's >=32 chars.
        assert!(is_valid_v3_triple(
            "c",
            "v",
            "0123456789abcdef0123456789abcdef"
        ));
    }

    #[test]
    fn is_valid_v3_triple_rejects_non_hex_short_seccode() {
        // No pipe + <32 hex chars = not a real seccode.
        assert!(!is_valid_v3_triple("c", "v", "deadbeef"));
    }

    #[test]
    fn is_valid_v4_quad_rejects_empty() {
        assert!(!is_valid_v4_quad("", "p", "1736899200", "{}"));
        assert!(!is_valid_v4_quad("l", "", "1736899200", "{}"));
        assert!(!is_valid_v4_quad("l", "p", "", "{}"));
        assert!(!is_valid_v4_quad("l", "p", "1736899200", ""));
    }

    #[test]
    fn is_valid_v4_quad_rejects_unparseable_gen_time() {
        assert!(!is_valid_v4_quad("l", "p", "not-a-timestamp", "{}"));
        assert!(!is_valid_v4_quad("l", "p", "abc", "{}"));
    }

    #[test]
    fn is_valid_v4_quad_rejects_out_of_range_gen_time() {
        // Pre-2020 = pre-GeeTest-v4-launch; post-2100 = obvious garbage.
        assert!(!is_valid_v4_quad("l", "p", "1000000000", "{}")); // 2001
        assert!(!is_valid_v4_quad("l", "p", "5000000000", "{}")); // 2128
    }

    #[test]
    fn is_valid_v4_quad_accepts_real_shape() {
        assert!(is_valid_v4_quad(
            "ed8a6a87aaad4d3582a5af33d8a89aef",
            "f01d6049ce17ce0b08fa5b3c1c5d3a8c",
            "1736899200",
            "{\"captcha_id\":\"f01d6049ce17ce0b08fa5b3c1c5d3a8c\"}",
        ));
    }

    #[test]
    fn phase_probe_js_covers_documented_signals() {
        for needle in [
            "geetest_challenge",
            "geetest_validate",
            "geetest_seccode",
            "lot_number",
            "pass_token",
            "gen_time",
            "captcha_output",
            "geetest_box",
            "geetest_holder",
            "initgeetest",
        ] {
            assert!(
                PHASE_PROBE_JS.to_lowercase().contains(needle),
                "PHASE_PROBE_JS must reference: {needle}"
            );
        }
    }

    #[test]
    fn phase_probe_js_emits_canonical_phases() {
        for phase in [
            "v3_passed",
            "v4_passed",
            "v3_pending",
            "v4_pending",
            "unknown",
        ] {
            assert!(
                PHASE_PROBE_JS.contains(&format!("'{phase}'")),
                "PHASE_PROBE_JS must emit phase: {phase}"
            );
        }
    }
}