captchaforge 0.2.6

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
//! Cross-origin iframe evaluation helpers.
//!
//! CAPTCHA providers (reCAPTCHA, hCaptcha, Turnstile) render their challenges
//! inside sandboxed cross-origin iframes.  JavaScript running in the parent
//! page cannot pierce these iframes via `contentDocument` or
//! `contentWindow.document` — doing so throws a `SecurityError`.
//!
//! This module uses the Chrome DevTools Protocol to evaluate expressions in
//! each frame's own execution context, which works regardless of origin.

use anyhow::{anyhow, Result};
use chromiumoxide::cdp::js_protocol::runtime::EvaluateParams;
use chromiumoxide::Page;

/// Escape a Rust string so it is safe to embed in a JavaScript string literal
/// surrounded by either single or double quotes.
///
/// Handles the following escapes:
/// - `\`  → `\\`
/// - `'`  → `\'`
/// - `"`  → `\"`
/// - `\n` → `\\n`
/// - `\r` → `\\r`
/// - `\t` → `\\t`
/// - `\0` → `\\0`
fn escape_js_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '\'' => out.push_str("\\'"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\0' => out.push_str("\\0"),
            c => out.push(c),
        }
    }
    out
}

/// Look up the iframe offset for a given URL and optional iframe index.
///
/// `iframe_offsets` is a Vec of `(idx, src, id, x, y)` tuples collected from
/// the main frame in DOM order.  If `iframe_idx` is non-negative we prefer an
/// exact index match to disambiguate duplicate URLs.
fn lookup_iframe_offset(
    iframe_offsets: &[(usize, String, String, f64, f64)],
    url: &str,
    iframe_idx: i64,
) -> (f64, f64) {
    if iframe_idx >= 0 {
        iframe_offsets
            .iter()
            .find(|(idx, src, id, _, _)| *idx == iframe_idx as usize && (src == url || id == url))
            .map(|(_, _, _, x, y)| (*x, *y))
    } else {
        iframe_offsets
            .iter()
            .find(|(_, src, id, _, _)| src == url || id == url)
            .map(|(_, _, _, x, y)| (*x, *y))
    }
    .unwrap_or((0.0, 0.0))
}

/// Evaluate `expression` in every frame of the page (main document + all
/// iframes) and return the deserialized results from every frame that
/// produced a valid value.
///
/// This is the robust replacement for parent-page JS that tries to walk
/// into `iframe.contentDocument`.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::frame::evaluate_in_all_frames;
/// # async fn example(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// let titles: Vec<String> = evaluate_in_all_frames(page, "document.title").await?;
/// # Ok(()) }
/// ```
pub async fn evaluate_in_all_frames<T>(page: &Page, expression: &str) -> Result<Vec<T>>
where
    T: serde::de::DeserializeOwned,
{
    let frame_ids = page.frames().await?;
    let mut out = Vec::with_capacity(frame_ids.len());
    for fid in frame_ids {
        if let Some(ctx) = page.frame_execution_context(fid.clone()).await? {
            let params = EvaluateParams::builder()
                .expression(expression)
                .context_id(ctx)
                .build()
                .map_err(|e| anyhow!("EvaluateParams build failed: {e}"))?;
            let eval = page.evaluate_expression(params).await?;
            if let Ok(v) = eval.into_value::<T>() {
                out.push(v);
            }
        }
    }
    Ok(out)
}

/// Evaluate `expression` in every frame and return the **first** result that
/// passes `filter`.  If no frame produces a matching result, `default` is
/// returned.
pub async fn evaluate_in_frames_first<T, F>(
    page: &Page,
    expression: &str,
    filter: F,
    default: T,
) -> Result<T>
where
    T: serde::de::DeserializeOwned + Clone,
    F: Fn(&T) -> bool,
{
    let all = evaluate_in_all_frames::<T>(page, expression).await?;
    Ok(all.into_iter().find(filter).unwrap_or(default))
}

/// Search every frame for a DOM element matching `selector` and return its
/// bounding-box centre coordinates **relative to the main viewport**.
///
/// For elements inside cross-origin iframes this sums the iframe's own
/// bounding box with the element's position inside the iframe so the
/// resulting coordinates are safe to pass to `Input.dispatchMouseEvent`.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::frame::find_element_centre_in_frames;
/// # async fn example(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// let centre = find_element_centre_in_frames(page, "#submit-btn").await?;
/// if let Some((x, y)) = centre {
///     // x, y are viewport-relative coordinates
/// }
/// # Ok(()) }
/// ```
pub async fn find_element_centre_in_frames(
    page: &Page,
    selector: &str,
) -> Result<Option<(f64, f64)>> {
    let frame_ids = page.frames().await?;
    let main_frame = page.mainframe().await?;

    // Build a Vec of iframe offsets keyed by the iframe's index in the
    // DOM querySelectorAll result combined with src/id.  Using a Vec
    // prevents HashMap collisions when two iframes share the same src.
    let mut iframe_offsets: Vec<(usize, String, String, f64, f64)> = Vec::new();
    if let Some(ref main) = main_frame {
        let js = r#"
            (function() {
                const out = [];
                const frames = document.querySelectorAll('iframe');
                for (let i = 0; i < frames.length; i++) {
                    const f = frames[i];
                    const r = f.getBoundingClientRect();
                    out.push({ idx: i, src: f.src, id: f.id, x: r.left, y: r.top });
                }
                return out;
            })()
        "#;
        if let Some(ctx) = page.frame_execution_context(main.clone()).await? {
            let params = EvaluateParams::builder()
                .expression(js)
                .context_id(ctx)
                .build()
                .map_err(|e| anyhow!("EvaluateParams build failed: {e}"))?;
            let eval = page.evaluate_expression(params).await?;
            if let Ok(vals) = eval.into_value::<Vec<serde_json::Value>>() {
                for v in vals {
                    if let (Some(idx), Some(x), Some(y)) =
                        (v["idx"].as_u64(), v["x"].as_f64(), v["y"].as_f64())
                    {
                        let src = v["src"].as_str().unwrap_or("").to_string();
                        let id = v["id"].as_str().unwrap_or("").to_string();
                        iframe_offsets.push((idx as usize, src, id, x, y));
                    }
                }
            }
        }
    }

    let escaped = escape_js_string(selector);
    let js = format!(
        r#"(function() {{
            const el = document.querySelector('{}');
            if (!el) return null;
            const r = el.getBoundingClientRect();
            let iframeIdx = -1;
            try {{
                const frames = window.parent.frames;
                for (let i = 0; i < frames.length; i++) {{
                    if (frames[i] === window) {{
                        iframeIdx = i;
                        break;
                    }}
                }}
            }} catch (e) {{}}
            return {{ x: r.left + r.width / 2, y: r.top + r.height / 2, url: window.location.href, iframeIdx: iframeIdx }};
        }})()"#,
        escaped
    );

    for fid in frame_ids {
        if let Some(ctx) = page.frame_execution_context(fid.clone()).await? {
            let params = EvaluateParams::builder()
                .expression(&js)
                .context_id(ctx)
                .build()
                .map_err(|e| anyhow!("EvaluateParams build failed: {e}"))?;
            let eval = page.evaluate_expression(params).await?;
            if let Ok(val) = eval.into_value::<serde_json::Value>() {
                if let (Some(x), Some(y)) = (val["x"].as_f64(), val["y"].as_f64()) {
                    let url = val["url"].as_str().unwrap_or("");
                    let iframe_idx = val["iframeIdx"].as_i64().unwrap_or(-1);
                    let (offset_x, offset_y) = if Some(&fid) == main_frame.as_ref() {
                        (0.0, 0.0)
                    } else {
                        lookup_iframe_offset(&iframe_offsets, url, iframe_idx)
                    };
                    return Ok(Some((x + offset_x, y + offset_y)));
                }
            }
        }
    }
    Ok(None)
}

/// Check whether a CAPTCHA response token exists in **any** frame.
/// Used for post-solve verification when the provider may inject the token
/// into a hidden input in the main document or inside an iframe.
///
/// # Example
///
/// ```rust,no_run
/// use captchaforge::frame::verify_token_in_frames;
/// # async fn example(page: &chromiumoxide::Page) -> anyhow::Result<()> {
/// let found = verify_token_in_frames(page, "g-recaptcha-response").await?;
/// assert!(found);
/// # Ok(()) }
/// ```
pub async fn verify_token_in_frames(page: &Page, token_input_name: &str) -> Result<bool> {
    let escaped = escape_js_string(token_input_name);
    let js = format!(
        r#"!!document.querySelector('input[name="{}"][value]:not([value=""])')"#,
        escaped
    );
    let results = evaluate_in_all_frames::<bool>(page, &js).await?;
    Ok(results.into_iter().any(|v| v))
}

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

    #[test]
    fn escape_js_string_all_special_chars() {
        let input = "\\'\"\n\r\t\0";
        assert_eq!(escape_js_string(input), "\\\\\\\'\\\"\\n\\r\\t\\0");
    }

    #[test]
    fn escape_js_string_backslash() {
        assert_eq!(escape_js_string(r"\"), "\\\\");
    }

    #[test]
    fn escape_js_string_single_quote() {
        assert_eq!(escape_js_string("'"), "\\'");
    }

    #[test]
    fn escape_js_string_double_quote() {
        assert_eq!(escape_js_string("\""), "\\\"");
    }

    #[test]
    fn escape_js_string_newline() {
        assert_eq!(escape_js_string("a\nb"), "a\\nb");
    }

    #[test]
    fn escape_js_string_carriage_return() {
        assert_eq!(escape_js_string("a\rb"), "a\\rb");
    }

    #[test]
    fn escape_js_string_tab() {
        assert_eq!(escape_js_string("a\tb"), "a\\tb");
    }

    #[test]
    fn escape_js_string_null_byte() {
        assert_eq!(escape_js_string("a\0b"), "a\\0b");
    }

    #[test]
    fn escape_js_string_mixed() {
        let input = "line1\nline2\tcol\0end\\\"'";
        assert_eq!(
            escape_js_string(input),
            "line1\\nline2\\tcol\\0end\\\\\\\"\\'"
        );
    }

    #[test]
    fn escape_js_string_no_special_chars() {
        assert_eq!(escape_js_string("#simple-id"), "#simple-id");
    }

    #[test]
    fn lookup_iframe_offset_by_index_and_url() {
        let offsets = vec![
            (0, "a.html".into(), "".into(), 10.0, 20.0),
            (1, "b.html".into(), "".into(), 30.0, 40.0),
        ];
        assert_eq!(lookup_iframe_offset(&offsets, "a.html", 0), (10.0, 20.0));
        assert_eq!(lookup_iframe_offset(&offsets, "b.html", 1), (30.0, 40.0));
    }

    #[test]
    fn lookup_iframe_offset_fallback_when_index_missing() {
        let offsets = vec![(0, "a.html".into(), "".into(), 10.0, 20.0)];
        assert_eq!(lookup_iframe_offset(&offsets, "a.html", -1), (10.0, 20.0));
    }

    #[test]
    fn lookup_iframe_offset_disambiguates_duplicate_src() {
        let offsets = vec![
            (0, "same.html".into(), "".into(), 10.0, 20.0),
            (1, "same.html".into(), "".into(), 30.0, 40.0),
        ];
        // With index we can tell them apart.
        assert_eq!(lookup_iframe_offset(&offsets, "same.html", 0), (10.0, 20.0));
        assert_eq!(lookup_iframe_offset(&offsets, "same.html", 1), (30.0, 40.0));
        // Without index, fallback to first match.
        assert_eq!(
            lookup_iframe_offset(&offsets, "same.html", -1),
            (10.0, 20.0)
        );
    }

    #[test]
    fn lookup_iframe_offset_empty_src_and_id() {
        let offsets = vec![
            (0, "".into(), "".into(), 5.0, 5.0),
            (1, "".into(), "".into(), 15.0, 15.0),
        ];
        assert_eq!(lookup_iframe_offset(&offsets, "", 0), (5.0, 5.0));
        assert_eq!(lookup_iframe_offset(&offsets, "", 1), (15.0, 15.0));
    }

    #[test]
    fn lookup_iframe_offset_no_match() {
        let offsets = vec![(0, "a.html".into(), "".into(), 10.0, 20.0)];
        assert_eq!(
            lookup_iframe_offset(&offsets, "missing.html", -1),
            (0.0, 0.0)
        );
    }

    #[test]
    fn find_element_js_contains_query_selector() {
        let selector = "#btn";
        let escaped = escape_js_string(selector);
        let js = format!(
            r#"(function() {{ const el = document.querySelector('{}'); if (!el) return null; const r = el.getBoundingClientRect(); return {{ x: r.left + r.width / 2, y: r.top + r.height / 2, url: window.location.href }}; }})()"#,
            escaped
        );
        assert!(js.contains("document.querySelector"));
        assert!(js.contains("getBoundingClientRect"));
    }

    #[test]
    fn verify_token_js_contains_input_selector() {
        let name = "g-recaptcha-response";
        let escaped = escape_js_string(name);
        let js = format!(
            r#"!!document.querySelector('input[name="{}"][value]:not([value=""])')"#,
            escaped
        );
        assert!(js.contains("input[name="));
        assert!(js.contains("value]:not([value=\"\"])"));
    }

    #[test]
    fn verify_token_escapes_quotes() {
        let name = r#"token"value"#;
        let escaped = escape_js_string(name);
        assert!(escaped.contains("\\\""));
        for (i, ch) in escaped.char_indices() {
            if ch == '"' {
                assert!(
                    i > 0 && escaped.as_bytes()[i - 1] == b'\\',
                    "quote at {} not escaped",
                    i
                );
            }
        }
    }

    #[test]
    fn verify_token_escapes_null_and_newline() {
        let name = "token\0value\n";
        let escaped = escape_js_string(name);
        assert!(escaped.contains("\\0"));
        assert!(escaped.contains("\\n"));
        assert!(!escaped.contains('\0'));
        assert!(!escaped.contains('\n'));
    }
}