captchaforge 0.2.32

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
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
use super::*;

use crate::backends::{SttBackend, SttKind};

// ─── AudioCaptchaSolver ───────────────────────────────────────────────────────

/// Solves reCAPTCHA v2 (and generic) audio challenges.
///
/// Backend selection (auto-detected on construction):
///   - **Local `whisper` CLI** on PATH — preferred. Audio bytes are written
///     to a tempfile and `whisper <tmp> --model tiny --output_format txt`
///     is spawned; the resulting `.txt` is parsed.
///   - **OpenAI Whisper API** if `OPENAI_API_KEY` is set.
///   - **Local HTTP server** at `http://localhost:9000/asr` (the legacy
///     [openai-whisper-asr-webservice] convention).
///
/// The first available backend wins. Override with [`Self::with_stt_backend`]
/// or [`Self::with_stt_endpoint`] for explicit configuration.
///
/// [openai-whisper-asr-webservice]: https://github.com/ahmetoner/whisper-asr-webservice
pub struct AudioCaptchaSolver {
    client: reqwest::Client,
    /// Auto-detected STT backend. `None` means no local backend was found at
    /// construction; the solver falls back to [`Self::stt_endpoint`].
    pub(crate) stt_backend: Option<SttBackend>,
    /// HTTP STT endpoint — used when [`Self::stt_backend`] is `None` or its
    /// kind is `LocalServer`. Default `http://localhost:9000/asr`.
    pub(crate) stt_endpoint: String,
    pub(crate) config: SolveConfig,
}

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

impl AudioCaptchaSolver {
    pub fn new() -> Self {
        let config = SolveConfig::default();
        // Best-effort sync probe for whisper-cli + OPENAI_API_KEY. Fast
        // (PATH walk + env lookup), no network.
        let stt_backend = Self::probe_stt_sync();
        Self {
            client: reqwest::Client::builder()
                .timeout(Duration::from_millis(config.client_http_timeout_ms))
                .build()
                .unwrap_or_else(|_| reqwest::Client::new()),
            stt_backend,
            stt_endpoint: "http://localhost:9000/asr".to_string(),
            config,
        }
    }

    /// Synchronous subset of [`crate::backends::probe`] focused on STT —
    /// safe to call from `new()` (no async, no network). Picks whisper-cli
    /// over OpenAI API when both are present (local is faster + free).
    fn probe_stt_sync() -> Option<SttBackend> {
        if let Some(path) =
            crate::backends::which("whisper").or_else(|| crate::backends::which("whisper-cli"))
        {
            return Some(SttBackend {
                kind: SttKind::WhisperCli,
                endpoint: path,
                model: Some(crate::backends::DEFAULT_WHISPER_MODEL.to_string()),
            });
        }
        if std::env::var("OPENAI_API_KEY").is_ok() {
            return Some(SttBackend {
                kind: SttKind::OpenAIApi,
                endpoint: "https://api.openai.com/v1/audio/transcriptions".to_string(),
                model: Some("whisper-1".to_string()),
            });
        }
        None
    }

    pub fn with_stt_endpoint(mut self, url: impl Into<String>) -> Self {
        self.stt_endpoint = url.into();
        self
    }

    /// Explicitly set the STT backend. Use this when probing should be
    /// skipped (tests, custom pipelines, vendored whisper builds).
    pub fn with_stt_backend(mut self, backend: SttBackend) -> Self {
        self.stt_backend = Some(backend);
        self
    }

    pub fn with_config(mut self, config: SolveConfig) -> Self {
        self.config = config;
        self
    }

    /// Transcribe `audio_bytes` using the configured backend. Public so
    /// callers can reuse the audio→text path without going through a full
    /// page solve (e.g. CLI `captchaforge transcribe foo.mp3`).
    ///
    /// Pre-pipeline: when the input is a WAV container we run it through
    /// [`crate::audio_dsp::preprocess_for_stt`] (denoise → bandpass →
    /// peak-normalise) before handing it to the STT backend. Vendors
    /// deliberately distort accessibility audio; pre-processing typically
    /// lifts whisper accuracy from ~60% to ~90% on the bench fixtures.
    /// Non-WAV inputs (MP3/OGG) pass through unchanged because the
    /// pre-pipeline doesn't ship a container demuxer yet (tracked under
    /// `audio_dsp` module-level docs).
    pub async fn transcribe(&self, audio_bytes: bytes::Bytes) -> Result<String> {
        let prepared = if audio_bytes.starts_with(b"RIFF") {
            match crate::audio_dsp::preprocess_for_stt(&audio_bytes) {
                Ok(pcm) => bytes::Bytes::from(crate::audio_dsp::encode_wav_pcm16(&pcm)),
                Err(e) => {
                    // Pre-processing is best-effort — if the WAV is
                    // malformed we'd rather hand the raw bytes to STT
                    // (whose own decoder may be more forgiving) than
                    // hard-fail the whole solve.
                    tracing::debug!(
                        error = %e,
                        "audio_dsp pre-process failed; sending raw audio to STT"
                    );
                    audio_bytes
                }
            }
        } else {
            audio_bytes
        };
        match &self.stt_backend {
            Some(b) if b.kind == SttKind::WhisperCli => {
                Self::transcribe_via_whisper_cli(b, prepared).await
            }
            Some(b) if b.kind == SttKind::OpenAIApi => {
                self.transcribe_via_openai(b, prepared).await
            }
            _ => self.transcribe_via_http(prepared).await,
        }
    }

    async fn transcribe_via_whisper_cli(
        backend: &SttBackend,
        audio_bytes: bytes::Bytes,
    ) -> Result<String> {
        let model = backend.model.as_deref().unwrap_or("tiny");
        let bin = backend.endpoint.clone();
        // tempfile crate gives a path that auto-deletes on drop; whisper
        // is happy with `.wav` / `.mp3` based on the extension. We sniff
        // the first 4 bytes for a basic format choice.
        let ext = if audio_bytes.starts_with(b"RIFF") {
            "wav"
        } else if audio_bytes.starts_with(b"OggS") {
            "ogg"
        } else {
            "mp3"
        };
        let mut tmp = tempfile::Builder::new()
            .prefix("captchaforge-stt-")
            .suffix(&format!(".{ext}"))
            .tempfile()?;
        use std::io::Write;
        tmp.write_all(&audio_bytes)?;
        tmp.flush()?;
        let audio_path = tmp.path().to_path_buf();
        let outdir = tempfile::tempdir()?;
        let outdir_path = outdir.path().to_path_buf();

        // whisper writes <stem>.txt into --output_dir; spawn synchronously
        // inside spawn_blocking so we don't stall the async runtime.
        let model_owned = model.to_string();
        let result = tokio::task::spawn_blocking(move || -> Result<String> {
            let status = std::process::Command::new(&bin)
                .arg(&audio_path)
                .args(["--model", &model_owned])
                .args(["--output_format", "txt"])
                .arg("--output_dir")
                .arg(&outdir_path)
                // English-only is faster + more accurate for digit
                // CAPTCHAs; whisper auto-detects otherwise (slower).
                .args(["--language", "en"])
                .arg("--fp16=False")
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status()
                .map_err(|e| anyhow::anyhow!("spawning whisper: {e}"))?;
            if !status.success() {
                anyhow::bail!("whisper exited {status}");
            }
            let stem = audio_path
                .file_stem()
                .and_then(|s| s.to_str())
                .ok_or_else(|| anyhow::anyhow!("audio path has no stem"))?;
            let txt_path = outdir_path.join(format!("{stem}.txt"));
            let body = std::fs::read_to_string(&txt_path)
                .map_err(|e| anyhow::anyhow!("reading {}: {e}", txt_path.display()))?;
            Ok(body.trim().to_string())
        })
        .await
        .map_err(|e| anyhow::anyhow!("whisper task join: {e}"))??;
        Ok(result)
    }

    async fn transcribe_via_openai(
        &self,
        backend: &SttBackend,
        audio_bytes: bytes::Bytes,
    ) -> Result<String> {
        let key = std::env::var("OPENAI_API_KEY")
            .map_err(|_| anyhow::anyhow!("OPENAI_API_KEY not set"))?;
        let model = backend.model.as_deref().unwrap_or("whisper-1");
        let part = reqwest::multipart::Part::bytes(audio_bytes.to_vec())
            .file_name("audio.mp3")
            .mime_str("audio/mpeg")?;
        let form = reqwest::multipart::Form::new()
            .text("model", model.to_string())
            .text("response_format", "text")
            .part("file", part);
        let resp = self
            .client
            .post(&backend.endpoint)
            .bearer_auth(key)
            .multipart(form)
            .send()
            .await?;
        if !resp.status().is_success() {
            anyhow::bail!("openai whisper returned {}", resp.status());
        }
        Ok(resp.text().await?.trim().to_string())
    }

    async fn transcribe_via_http(&self, audio_bytes: bytes::Bytes) -> Result<String> {
        let resp = self
            .client
            .post(&self.stt_endpoint)
            .header("Content-Type", "audio/mpeg")
            .body(audio_bytes)
            .send()
            .await?;
        if !resp.status().is_success() {
            anyhow::bail!("local STT returned {}", resp.status());
        }
        Ok(resp.text().await?.trim().to_string())
    }
}

/// Normalize a whisper transcript to a CAPTCHA-friendly answer.
///
/// Captcha answer fields commonly accept either spelled digits ("four two
/// nine") or compact digits ("429"). Whisper most often returns the spelled
/// form for slowly-spoken digit audio. This helper:
///   - lowercases + trims
///   - strips punctuation
///   - converts each spelled-digit token to its digit form
///   - collapses whitespace
///
/// Pure helper — pub so callers can normalize for diffing in tests.
///
/// # Examples
///
/// ```
/// use captchaforge::solver::normalize_transcript;
/// assert_eq!(normalize_transcript("Four two nine."), "429");
/// assert_eq!(normalize_transcript(" SEVEN one zero "), "710");
/// // Mixed numerals + words pass through.
/// assert_eq!(normalize_transcript("4 two 9"), "429");
/// // Non-digit transcripts keep their words (lowercased, single-spaced).
/// assert_eq!(normalize_transcript("Hello World"), "hello world");
/// ```
pub fn normalize_transcript(s: &str) -> String {
    let lowered: String = s
        .to_lowercase()
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { ' ' })
        .collect();
    let tokens: Vec<&str> = lowered.split_whitespace().collect();
    let mut out = Vec::with_capacity(tokens.len());
    let mut all_digits = true;
    for tok in &tokens {
        let digit = match *tok {
            "zero" | "oh" => Some("0"),
            "one" => Some("1"),
            "two" | "to" | "too" => Some("2"),
            "three" => Some("3"),
            "four" | "for" => Some("4"),
            "five" => Some("5"),
            "six" => Some("6"),
            "seven" => Some("7"),
            "eight" | "ate" => Some("8"),
            "nine" => Some("9"),
            t if t.chars().all(|c| c.is_ascii_digit()) => Some(*tok),
            _ => None,
        };
        if let Some(d) = digit {
            out.push(d.to_string());
        } else {
            all_digits = false;
            out.push((*tok).to_string());
        }
    }
    if all_digits {
        out.join("")
    } else {
        out.join(" ")
    }
}

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

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

    fn supports(&self, kind: &crate::captcha_detect::DetectedCaptcha) -> bool {
        use crate::captcha_detect::DetectedCaptcha;
        matches!(
            kind,
            DetectedCaptcha::RecaptchaV2 | DetectedCaptcha::AudioCaptcha
        )
    }

    async fn solve(
        &self,
        page: &Page,
        _captcha_info: &crate::captcha_detect::CaptchaInfo,
    ) -> Result<CaptchaSolveResult> {
        let t0 = Instant::now();

        // Click the audio challenge button — only present on reCAPTCHA v2.
        // Generic audio CAPTCHAs surface the `<audio>` element directly,
        // so a missing button is non-fatal.
        if let Ok(audio_btn) = page
            .find_element("#recaptcha-audio-button, .rc-button-audio")
            .await
        {
            audio_btn.click().await?;
            tokio::time::sleep(Duration::from_millis(self.config.audio_button_delay_ms)).await;
        }

        // Extract the audio source URL. Resolves relative paths against
        // the document's origin so a fixture serving `/audio.wav` works.
        let audio_src = page
            .evaluate(
                r#"(function(){const a=document.querySelector('audio[src],audio source[src]');
                    if(!a)return '';
                    const raw=a.getAttribute('src');
                    if(!raw)return '';
                    try{return new URL(raw, document.baseURI).toString();}catch(e){return raw;}})()"#,
            )
            .await?
            .into_value::<String>()?;

        if audio_src.is_empty() {
            return Ok(CaptchaSolveResult::failure(
                SolveMethod::AudioBypass,
                t0.elapsed().as_millis() as u64,
            ));
        }

        // Download the audio via the BROWSER fetch — this preserves
        // session cookies, follows redirects the same way the page
        // would, and inherits chromium's certificate policy (so
        // self-signed dev origins work when chromium has
        // --ignore-certificate-errors set). reqwest with the default
        // policy would reject self-signed certs.
        let audio_b64 = page
            .evaluate(format!(
                r#"(async (url) => {{
                    try {{
                        const r = await fetch(url, {{ credentials: 'include', cache: 'no-store' }});
                        if (!r.ok) return '';
                        const buf = await r.arrayBuffer();
                        const bytes = new Uint8Array(buf);
                        let bin = '';
                        for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
                        return btoa(bin);
                    }} catch (e) {{ return ''; }}
                }})({})"#,
                serde_json::to_string(&audio_src).unwrap_or_else(|_| "\"\"".into())
            ))
            .await?
            .into_value::<String>()
            .unwrap_or_default();
        if audio_b64.is_empty() {
            return Ok(CaptchaSolveResult::failure(
                SolveMethod::AudioBypass,
                t0.elapsed().as_millis() as u64,
            ));
        }
        use base64::Engine as _;
        let audio_bytes: bytes::Bytes =
            match base64::engine::general_purpose::STANDARD.decode(audio_b64.as_bytes()) {
                Ok(v) => v.into(),
                Err(_) => {
                    return Ok(CaptchaSolveResult::failure(
                        SolveMethod::AudioBypass,
                        t0.elapsed().as_millis() as u64,
                    ));
                }
            };

        // Transcribe via the auto-detected backend (whisper-cli > OpenAI
        // API > local HTTP server). Failures bubble up as solver failure
        // so the chain falls through to the next solver instead of
        // hanging the page.
        let transcript = match self.transcribe(audio_bytes).await {
            Ok(t) if !t.is_empty() => normalize_transcript(&t),
            _ => {
                return Ok(CaptchaSolveResult::failure(
                    SolveMethod::AudioBypass,
                    t0.elapsed().as_millis() as u64,
                ));
            }
        };

        if transcript.is_empty() {
            return Ok(CaptchaSolveResult::failure(
                SolveMethod::AudioBypass,
                t0.elapsed().as_millis() as u64,
            ));
        }

        // Type the transcript into the answer field. Use a JS pierce so
        // we don't depend on element handles (which expire when the
        // page reflows after our typed input fires the fixture's own
        // input-listeners). Selectors cover reCAPTCHA v2 (`#audio-
        // response`, `.rc-response-input`) and generic audio captchas
        // (`input[name="captcha"]`, `input[name="answer"]`,
        // `input[type="text"]` as last resort).
        let typed = page
            .evaluate(format!(
                r#"((answer) => {{
                    const inp = document.querySelector(
                        '#audio-response, .rc-response-input, ' +
                        'input[name="captcha"], input[name="answer"], ' +
                        'input[type="text"]'
                    );
                    if (!inp) return false;
                    inp.focus();
                    /* Char-by-char so the page's input listener fires per
                       keystroke — many fixtures auto-submit when the
                       value matches mid-type. */
                    inp.value = '';
                    for (let i = 0; i < answer.length; i++) {{
                        inp.value += answer[i];
                        inp.dispatchEvent(new Event('input', {{bubbles: true}}));
                    }}
                    inp.dispatchEvent(new Event('change', {{bubbles: true}}));
                    return true;
                }})({})"#,
                serde_json::to_string(&transcript).unwrap_or_else(|_| "\"\"".into())
            ))
            .await?
            .into_value::<bool>()
            .unwrap_or(false);
        if !typed {
            return Ok(CaptchaSolveResult::failure(
                SolveMethod::AudioBypass,
                t0.elapsed().as_millis() as u64,
            ));
        }

        tokio::time::sleep(Duration::from_millis(self.config.audio_submit_delay_ms)).await;

        // Click the verify button if present (reCAPTCHA v2 needs it;
        // generic captchas auto-validate on input).
        if let Ok(verify) = page
            .find_element("#recaptcha-verify-button, .rc-button-default, button[type='submit']")
            .await
        {
            verify.click().await.ok();
        }

        // Success signal: either the reCAPTCHA token is populated, OR
        // the page has transitioned (title/cookie/widget removed). The
        // chain's outcome oracle does the page-transition check at a
        // higher layer, so here we just report success when we typed
        // something and the answer field accepted it; chain will
        // downgrade to failure if the oracle disagrees.
        let has_token = page
            .evaluate(
                r#"(() => {
                    const t = document.querySelector('#g-recaptcha-response, [name="g-recaptcha-response"]');
                    if (t && t.value && t.value.length > 0) return true;
                    /* Title flip is the most common generic success marker. */
                    return /solved|verified|success/i.test(document.title || '');
                })()"#,
            )
            .await?
            .into_value::<bool>()
            .unwrap_or(false);

        let cookies = if has_token {
            crate::cookies::capture_from_page(page)
                .await
                .unwrap_or_default()
        } else {
            Vec::new()
        };

        Ok(CaptchaSolveResult {
            solution: transcript.clone(),
            confidence: if has_token { 0.9 } else { 0.5 },
            method: SolveMethod::AudioBypass,
            time_ms: t0.elapsed().as_millis() as u64,
            success: has_token,
            screenshot: None,
            cookies,
            verified_outcome: None,
        })
    }
}

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

    #[test]
    fn audio_solver_custom_endpoint() {
        let s = AudioCaptchaSolver::new().with_stt_endpoint("http://custom:9999/stt");
        assert_eq!(s.stt_endpoint, "http://custom:9999/stt");
    }
}