captchaforge 0.2.38

[DO NOT USE — UNDER ACTIVE DEVELOPMENT, NOT PRODUCTION-READY] Captcha solver scaffolding for Firefox + BiDi-driven browsers. The architecture is in place (vendor solvers, retry-loop iframe walking, VLM provider abstraction, real-WAF bench harness) but the live-vendor success rate is still 0% — Cloudflare Turnstile / hCaptcha / reCAPTCHA detect us at a TLS / BiDi fingerprint layer that no flag-based stealth has cleared. Watch the repo; do not depend on this for any real workload.
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
//! reCAPTCHA v2 — audio-challenge fallback solver.
//!
//! When the v2 checkbox click is rejected (low-trust IP, headless
//! signal residue, mouse pattern flagged), Google falls back to a
//! visual image-grid challenge inside the `api2/bframe` iframe. The
//! grid carries a small accessibility shortcut: an audio button that
//! switches the same challenge to a single-clip speech-to-text task.
//!
//! The audio path is DRAMATICALLY easier than vision for a bot:
//!
//! - No multi-tile click loop, no "select more squares" reprompt.
//! - One MP3 download, one STT call, one text submission.
//! - The audio clips are unaltered English numbers / words; modern
//!   STT (Whisper-tiny on CPU, Whisper-large on GPU) hits ~98%
//!   transcription accuracy on the corpus.
//!
//! Why this lives in `vendors/` and not the generic
//! [`super::super::AudioCaptchaSolver`]:
//!
//! 1. The whole audio widget is inside a cross-origin iframe (the
//!    `api2/bframe`). The generic solver calls `page.find_element`
//!    which only sees the main document — so it would always miss
//!    the controls in production.
//! 2. reCAPTCHA throttles the audio path aggressively. After ~3
//!    same-IP attempts in a short window, the audio button serves a
//!    "Try again later" interstitial with no audio src. Detecting
//!    that surface deterministically (rather than waiting on a
//!    timeout) is vendor-specific.
//! 3. The verify button has both a "submit answer" and a "reload"
//!    role depending on widget state; a generic solver doesn't know
//!    when to retry vs give up.
//!
//! # Strategy
//!
//! 1. Walk the bframe via [`crate::frame`] helpers — the shared
//!    cross-origin iframe-evaluation layer used by the Turnstile,
//!    behavioural and other solvers.
//! 2. Click `#recaptcha-audio-button` with mouse-on-iframe geometry
//!    and realistic timing. If the button isn't found, the bframe
//!    isn't open yet (someone needs to click the v2 checkbox first
//!    — that's the BehavioralCaptchaSolver's job, this one runs
//!    after) and we yield with failure.
//! 3. Wait for `audio` element `src` to populate. Detect the
//!    "Try again later" rate-limit interstitial and yield without
//!    burning more attempts at it.
//! 4. Download the MP3 with the page's User-Agent + cookies replayed,
//!    so Google's edge sees a session-coherent request rather than
//!    a bare reqwest fetch.
//! 5. POST audio to the STT endpoint. Default points at a local
//!    Whisper-compatible API but is reconfigurable per-instance.
//! 6. Clean the transcript (lowercase, collapse whitespace, strip
//!    leading/trailing punctuation that STT loves to add).
//! 7. Type the transcript into `#audio-response` with the realistic
//!    keystroke cadence helper — bots that paste with `set value`
//!    are caught by reCAPTCHA's input-event timing model.
//! 8. Click `#recaptcha-verify-button`. Poll
//!    `g-recaptcha-response` across all frames; if it populates we
//!    succeed; if a fresh audio clip appears (multi-clip retry),
//!    loop with a short ceiling.
//!
//! Failure modes returned without retrying:
//!
//! - Bframe absent → [`SolveMethod::AudioBypass`] failure with empty
//!   solution. Lets BehavioralCaptchaSolver have a turn.
//! - Rate-limit interstitial → solution literal `"recaptcha:rate_limited"`
//!   in the failure result so callers can surface it.
//! - STT endpoint unreachable / empty transcript → failure; chain
//!   may try VLM next.

use rand::{rngs::StdRng, Rng, SeedableRng};
use tracing::{debug, info, warn};

use super::super::*;

/// Selector matching the v2 challenge bframe (the iframe containing
/// the image-grid OR audio widget after the user has clicked the v2
/// checkbox). Stable since v2 GA in 2014; google.com/recaptcha/api2
/// is the canonical host.
pub const RECAPTCHA_BFRAME_SELECTOR: &str = r#"iframe[src*="google.com/recaptcha/api2/bframe"]"#;

/// In-bframe selector for the "play audio challenge" button.
pub const AUDIO_BUTTON_SELECTOR: &str = "#recaptcha-audio-button";

/// In-bframe selector for the audio element holding the MP3 src after
/// the audio button is clicked.
pub const AUDIO_ELEMENT_SELECTOR: &str = "#audio-source, audio";

/// In-bframe selector for the typed-answer input.
pub const RESPONSE_INPUT_SELECTOR: &str = "#audio-response";

/// In-bframe selector for the submit-answer button.
pub const VERIFY_BUTTON_SELECTOR: &str = "#recaptcha-verify-button";

/// Hidden token field reCAPTCHA populates on success — lives in the
/// PARENT page, not the bframe.
pub const TOKEN_INPUT_NAME: &str = "g-recaptcha-response";

/// Maximum number of audio-clip retries within a single solve call.
/// Google occasionally serves "submit answer to additional audio"
/// follow-ups; retrying twice covers the legitimate cases without
/// burning IP reputation on a hard-throttled session.
pub const MAX_AUDIO_RETRIES: usize = 2;

/// Phrases that appear in the bframe body when reCAPTCHA decides the
/// session is exhausted. Matched case-insensitively as substrings.
pub const RATE_LIMIT_PHRASES: &[&str] = &[
    "Your computer or network may be sending automated queries",
    "Try again later",
    "we have detected unusual traffic",
];

/// Solver for reCAPTCHA v2 via the audio-fallback path.
pub struct RecaptchaAudioSolver {
    client: reqwest::Client,
    /// Single-endpoint speech-to-text URL. Used when
    /// [`Self::stt_pipeline`] is `None`. Defaults to a local
    /// Whisper-compatible HTTP server.
    pub stt_endpoint: String,
    /// Multi-endpoint STT ladder. When set, takes precedence over
    /// [`Self::stt_endpoint`] — the solver tries each endpoint in order
    /// until one returns a non-empty transcript. Lets a deployment
    /// configure local Whisper → OpenAI Whisper → 2captcha audio as
    /// a fault-tolerant chain rather than a single point of failure.
    pub stt_pipeline: Option<crate::stt::SttPipeline>,
    pub config: SolveConfig,
}

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

impl RecaptchaAudioSolver {
    pub fn new() -> Self {
        let config = SolveConfig::default();
        Self {
            client: recaptcha_audio_client(Duration::from_millis(config.client_http_timeout_ms)),
            stt_endpoint: "http://localhost:9000/asr".to_string(),
            stt_pipeline: None,
            config,
        }
    }

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

    /// Install an STT fallback ladder. The ladder takes precedence
    /// over the single-endpoint URL when both are set.
    pub fn with_stt_pipeline(mut self, pipeline: crate::stt::SttPipeline) -> Self {
        self.stt_pipeline = Some(pipeline);
        self
    }

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

    /// Locate a control inside ANY frame (the helper handles iframe
    /// origin walks). Returns `None` after polling for
    /// `checkbox_max_attempts`.
    async fn poll_for_control(&self, page: &Page, selector: &str) -> Option<(f64, f64)> {
        for _ in 0..self.config.checkbox_max_attempts {
            if let Ok(Some(c)) = crate::frame::find_element_centre_in_frames(page, selector).await {
                return Some(c);
            }
            tokio::time::sleep(Duration::from_millis(self.config.checkbox_poll_interval_ms)).await;
        }
        None
    }

    /// Poll bframe text for a known rate-limit phrase. Returns `true`
    /// on the first match. Cheap — one BiDi eval per attempt.
    async fn rate_limited(&self, page: &Page) -> bool {
        let js = r#"(() => document.body ? document.body.innerText || '' : '')()"#;
        let texts: Vec<String> = crate::frame::evaluate_in_all_frames(page, js)
            .await
            .unwrap_or_default();
        texts.iter().any(|t| is_rate_limited(t))
    }

    /// Pull the audio src from any frame. Returns `None` until the
    /// element is present AND its `src` is non-empty.
    async fn poll_for_audio_src(&self, page: &Page) -> Option<String> {
        let js = format!(
            r#"(() => {{
                const el = document.querySelector({sel});
                if (!el) return null;
                const s = el.getAttribute('src') || '';
                return s.length > 0 ? s : null;
            }})()"#,
            sel = serde_json::to_string(AUDIO_ELEMENT_SELECTOR).unwrap(),
        );
        for _ in 0..self.config.token_max_attempts {
            tokio::time::sleep(Duration::from_millis(self.config.token_poll_interval_ms)).await;
            let urls: Vec<String> = crate::frame::evaluate_in_all_frames(page, &js)
                .await
                .unwrap_or_default();
            if let Some(u) = urls.into_iter().find(|s| looks_like_audio_url(s)) {
                return Some(u);
            }
        }
        None
    }
}

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

    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,
        _info: &crate::captcha_detect::CaptchaInfo,
    ) -> Result<CaptchaSolveResult> {
        let t0 = Instant::now();
        let mut rng = StdRng::from_entropy();

        // Step 0 — token may already be there (passive auto-pass).
        if crate::frame::verify_token_in_frames(page, TOKEN_INPUT_NAME)
            .await
            .unwrap_or(false)
        {
            info!("reCAPTCHA token already populated, no audio path needed");
            return Ok(CaptchaSolveResult {
                solution: "recaptcha:passive".into(),
                confidence: 0.95,
                method: SolveMethod::AutoPass,
                time_ms: t0.elapsed().as_millis() as u64,
                success: true,
                screenshot: None,
                cookies: crate::cookies::capture_from_page(page)
                    .await
                    .unwrap_or_default(),
                verified_outcome: None,
            });
        }

        // Step 1 — click the audio button.
        let (ax, ay) = match self.poll_for_control(page, AUDIO_BUTTON_SELECTOR).await {
            Some(c) => c,
            None => {
                debug!("audio button not found — bframe not open / wrong vendor");
                return Ok(CaptchaSolveResult::failure(
                    SolveMethod::AudioBypass,
                    t0.elapsed().as_millis() as u64,
                ));
            }
        };
        let approach_x = ax + rng.gen_range(-120.0..120.0);
        let approach_y = ay + rng.gen_range(-60.0..60.0);
        crate::behavior::mouse_move_human(page, approach_x, approach_y, ax, ay).await?;
        crate::behavior::click_realistic(page, ax, ay).await?;
        tokio::time::sleep(Duration::from_millis(self.config.audio_button_delay_ms)).await;

        // Step 2 — audio retry loop. reCAPTCHA sometimes asks for a
        // second clip after a correct first answer; we loop a small
        // bounded number of times.
        for attempt in 0..MAX_AUDIO_RETRIES {
            // Rate-limit short-circuit before paying for STT.
            if self.rate_limited(page).await {
                warn!(attempt, "reCAPTCHA audio path is rate-limited — yielding");
                return Ok(CaptchaSolveResult {
                    solution: "recaptcha:rate_limited".into(),
                    confidence: 0.0,
                    method: SolveMethod::AudioBypass,
                    time_ms: t0.elapsed().as_millis() as u64,
                    success: false,
                    screenshot: super::super::screenshot_b64(page).await.ok(),
                    cookies: Vec::new(),
                    verified_outcome: None,
                });
            }

            let audio_src = match self.poll_for_audio_src(page).await {
                Some(u) => u,
                None => {
                    debug!(attempt, "no audio src after click");
                    return Ok(CaptchaSolveResult::failure(
                        SolveMethod::AudioBypass,
                        t0.elapsed().as_millis() as u64,
                    ));
                }
            };

            // Step 3 — fetch the MP3 with the same browser-shaped
            // request surface and URL-scoped cookie state the page
            // would expose to an audio element.
            let audio_url = match reqwest::Url::parse(&audio_src) {
                Ok(url) => url,
                Err(e) => {
                    warn!(attempt, error = %e, "audio src is not a valid URL");
                    return Ok(CaptchaSolveResult::failure(
                        SolveMethod::AudioBypass,
                        t0.elapsed().as_millis() as u64,
                    ));
                }
            };
            let mut audio_request = self.client.get(audio_url.clone());
            match crate::cookies::capture_from_page(page).await {
                Ok(cookies) => {
                    if let Some(cookie_header) = recaptcha_audio_cookie_header(&cookies, &audio_url)
                    {
                        audio_request =
                            audio_request.header(reqwest::header::COOKIE, cookie_header);
                    }
                }
                Err(e) => warn!(
                    attempt,
                    error = %e,
                    "could not capture page cookies for reCAPTCHA audio download"
                ),
            }
            let bytes = match audio_request.send().await {
                Ok(r) if r.status().is_success() => r.bytes().await.ok(),
                Ok(r) => {
                    warn!(status = r.status().as_u16(), "audio download non-2xx");
                    None
                }
                Err(e) => {
                    warn!(error = %e, "audio download failed");
                    None
                }
            };
            let Some(bytes) = bytes else {
                return Ok(CaptchaSolveResult::failure(
                    SolveMethod::AudioBypass,
                    t0.elapsed().as_millis() as u64,
                ));
            };

            // Step 4 — STT. Pipeline takes precedence over the
            // single-endpoint URL when configured.
            let transcript_raw = if let Some(pipeline) = &self.stt_pipeline {
                match pipeline.transcribe(bytes.to_vec()).await {
                    Ok(t) => t,
                    Err(e) => {
                        warn!(attempt, error = %e, "STT pipeline exhausted");
                        String::new()
                    }
                }
            } else {
                let stt = self
                    .client
                    .post(&self.stt_endpoint)
                    .header("Content-Type", "audio/mpeg")
                    .body(bytes)
                    .send()
                    .await;
                match stt {
                    Ok(r) if r.status().is_success() => r.text().await.unwrap_or_default(),
                    _ => String::new(),
                }
            };
            let transcript = clean_transcript(&transcript_raw);
            if transcript.is_empty() {
                warn!(attempt, "STT returned empty transcript");
                return Ok(CaptchaSolveResult::failure(
                    SolveMethod::AudioBypass,
                    t0.elapsed().as_millis() as u64,
                ));
            }
            debug!(attempt, len = transcript.len(), "got STT transcript");

            // Step 5 — type the answer.
            let (rx, ry) = match self.poll_for_control(page, RESPONSE_INPUT_SELECTOR).await {
                Some(c) => c,
                None => {
                    return Ok(CaptchaSolveResult::failure(
                        SolveMethod::AudioBypass,
                        t0.elapsed().as_millis() as u64,
                    ));
                }
            };
            crate::behavior::mouse_move_human(page, ax, ay, rx, ry).await?;
            crate::behavior::click_realistic(page, rx, ry).await?;
            crate::behavior::type_human(page, &transcript).await?;
            tokio::time::sleep(Duration::from_millis(self.config.audio_submit_delay_ms)).await;

            // Step 6 — submit.
            let (vx, vy) = match self.poll_for_control(page, VERIFY_BUTTON_SELECTOR).await {
                Some(c) => c,
                None => {
                    return Ok(CaptchaSolveResult::failure(
                        SolveMethod::AudioBypass,
                        t0.elapsed().as_millis() as u64,
                    ));
                }
            };
            crate::behavior::mouse_move_human(page, rx, ry, vx, vy).await?;
            crate::behavior::click_realistic(page, vx, vy).await?;

            // Step 7 — poll for the parent-page token.
            for _ in 0..self.config.token_max_attempts {
                tokio::time::sleep(Duration::from_millis(self.config.token_poll_interval_ms)).await;
                if crate::frame::verify_token_in_frames(page, TOKEN_INPUT_NAME)
                    .await
                    .unwrap_or(false)
                {
                    info!(attempt, "g-recaptcha-response populated");
                    return Ok(CaptchaSolveResult {
                        solution: transcript,
                        confidence: 0.9,
                        method: SolveMethod::AudioBypass,
                        time_ms: t0.elapsed().as_millis() as u64,
                        success: true,
                        screenshot: None,
                        cookies: crate::cookies::capture_from_page(page)
                            .await
                            .unwrap_or_default(),
                        verified_outcome: None,
                    });
                }
            }

            // No token yet. If reCAPTCHA queued a follow-up clip the
            // audio src will rotate; the next loop iteration will pick
            // it up. If the answer was rejected outright, the bframe
            // re-renders the same widget — same loop handles both.
            debug!(attempt, "no token after submit, retrying");
        }

        Ok(CaptchaSolveResult::failure(
            SolveMethod::AudioBypass,
            t0.elapsed().as_millis() as u64,
        ))
    }
}

// ─── Pure helpers (doctested) ────────────────────────────────────────────────

fn recaptcha_audio_client(timeout: Duration) -> reqwest::Client {
    reqwest::Client::builder()
        .timeout(timeout)
        .no_gzip()
        .no_brotli()
        .default_headers(recaptcha_audio_headers())
        .build()
        .expect("reCAPTCHA audio reqwest client must build with rustls-tls enabled")
}

fn recaptcha_audio_headers() -> reqwest::header::HeaderMap {
    guise::http::default_browser_request_header_map_without_compression(
        guise::http::BrowserRequestKind::AudioSubresource,
    )
    .expect("canonical stealth audio-subresource headers must be valid")
}

fn recaptcha_audio_cookie_header(
    cookies: &[crate::cookies::CapturedCookie],
    audio_url: &reqwest::Url,
) -> Option<reqwest::header::HeaderValue> {
    let pairs = cookies
        .iter()
        .filter(|cookie| cookie_matches_url(cookie, audio_url))
        .filter(|cookie| cookie_pair_is_header_safe(&cookie.name, &cookie.value))
        .map(|cookie| format!("{}={}", cookie.name, cookie.value))
        .collect::<Vec<_>>();

    if pairs.is_empty() {
        return None;
    }

    reqwest::header::HeaderValue::from_str(&pairs.join("; ")).ok()
}

fn cookie_matches_url(cookie: &crate::cookies::CapturedCookie, url: &reqwest::Url) -> bool {
    if cookie.is_expired_now() {
        return false;
    }
    if cookie.secure && url.scheme() != "https" {
        return false;
    }
    let Some(host) = url.host_str() else {
        return false;
    };
    domain_matches(&cookie.domain, host) && path_matches(&cookie.path, url.path())
}

fn domain_matches(cookie_domain: &str, host: &str) -> bool {
    let cookie_domain = cookie_domain.trim().to_ascii_lowercase();
    if cookie_domain.is_empty() {
        return false;
    }
    let host = host.to_ascii_lowercase();
    let Some(domain) = cookie_domain.strip_prefix('.') else {
        return host == cookie_domain;
    };

    host == domain || host.ends_with(&format!(".{domain}"))
}

fn path_matches(cookie_path: &str, request_path: &str) -> bool {
    let cookie_path = if cookie_path.is_empty() {
        "/"
    } else {
        cookie_path
    };
    if cookie_path == "/" || request_path == cookie_path {
        return true;
    }
    request_path.starts_with(cookie_path)
        && (cookie_path.ends_with('/')
            || request_path
                .as_bytes()
                .get(cookie_path.len())
                .is_some_and(|byte| *byte == b'/'))
}

fn cookie_pair_is_header_safe(name: &str, value: &str) -> bool {
    !name.is_empty()
        && name
            .bytes()
            .all(|byte| byte.is_ascii_graphic() && !matches!(byte, b'=' | b';' | b',' | b'"'))
        && value
            .bytes()
            .all(|byte| byte.is_ascii_graphic() && !matches!(byte, b';'))
}

/// Normalise an STT transcript for typing into the audio-response field.
///
/// reCAPTCHA's audio answers are space-separated words/digits; STT
/// engines love to add capitalisation and trailing punctuation. The
/// response field is matched case-insensitively but stray punctuation
/// counts as wrong characters.
///
/// # Examples
///
/// ```
/// use captchaforge::solver::clean_transcript;
/// assert_eq!(clean_transcript("  Hello, World.  "), "hello world");
/// assert_eq!(clean_transcript("five seven, nine!"), "five seven nine");
/// assert_eq!(clean_transcript("\nthree\tfour\n"), "three four");
/// assert_eq!(clean_transcript(""), "");
/// ```
pub fn clean_transcript(raw: &str) -> String {
    let lowered = raw.to_lowercase();
    let mut buf = String::with_capacity(lowered.len());
    let mut last_space = true;
    for ch in lowered.chars() {
        if ch.is_alphanumeric() {
            buf.push(ch);
            last_space = false;
        } else if ch.is_whitespace() || matches!(ch, ',' | '.' | '!' | '?' | ';' | ':') {
            if !last_space {
                buf.push(' ');
                last_space = true;
            }
        } else {
            // Ignore other punctuation entirely — STT noise.
        }
    }
    buf.trim().to_string()
}

/// True when `text` matches a known reCAPTCHA rate-limit interstitial.
///
/// # Examples
///
/// ```
/// use captchaforge::solver::is_rate_limited;
/// assert!(is_rate_limited(
///     "Your computer or network may be sending automated queries"
/// ));
/// assert!(is_rate_limited("please TRY AGAIN LATER"));
/// assert!(!is_rate_limited("Press PLAY to listen"));
/// ```
pub fn is_rate_limited(text: &str) -> bool {
    let lower = text.to_lowercase();
    RATE_LIMIT_PHRASES
        .iter()
        .any(|p| lower.contains(&p.to_lowercase()))
}

/// True when `s` is a plausible reCAPTCHA audio MP3 URL. Non-empty,
/// http(s), and either the recaptcha host or a `.mp3` suffix.
///
/// # Examples
///
/// ```
/// use captchaforge::solver::looks_like_audio_url;
/// assert!(looks_like_audio_url(
///     "https://www.google.com/recaptcha/api2/payload?p=clip.mp3"
/// ));
/// assert!(looks_like_audio_url("http://cdn.example.com/x.mp3"));
/// assert!(!looks_like_audio_url(""));
/// assert!(!looks_like_audio_url("data:audio/mpeg;base64,abc"));
/// assert!(!looks_like_audio_url("blob:https://x"));
/// ```
pub fn looks_like_audio_url(s: &str) -> bool {
    if !(s.starts_with("https://") || s.starts_with("http://")) {
        return false;
    }
    s.contains("google.com/recaptcha") || s.to_lowercase().ends_with(".mp3")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cookies::CapturedCookie;
    use guise::fingerprint::default_profile_facts;

    #[test]
    fn clean_transcript_strips_punctuation_and_lowercases() {
        assert_eq!(clean_transcript("Five Seven, Nine!"), "five seven nine");
    }

    #[test]
    fn clean_transcript_collapses_whitespace() {
        assert_eq!(clean_transcript("a   b\t\tc\nd"), "a b c d");
    }

    #[test]
    fn clean_transcript_keeps_numbers() {
        assert_eq!(clean_transcript("5 7 9 2 6"), "5 7 9 2 6");
    }

    #[test]
    fn clean_transcript_drops_unicode_punctuation() {
        // STT engines occasionally emit smart quotes; we're just
        // ignoring them rather than mapping them to an alphabet
        // character — alphanumeric() catches letters across scripts
        // and the rest is dropped.
        assert_eq!(clean_transcript("\u{201C}hello\u{201D}"), "hello");
    }

    #[test]
    fn clean_transcript_empty_input_is_empty() {
        assert_eq!(clean_transcript(""), "");
        assert_eq!(clean_transcript("   "), "");
        assert_eq!(clean_transcript(",,,..."), "");
    }

    #[test]
    fn rate_limit_matches_known_phrases() {
        for p in RATE_LIMIT_PHRASES {
            assert!(is_rate_limited(p), "should match: {p}");
            assert!(
                is_rate_limited(&p.to_uppercase()),
                "case-insensitive match should hold for: {p}",
            );
        }
    }

    #[test]
    fn rate_limit_substring_match_works() {
        assert!(is_rate_limited(
            "Sorry — please try again later. We have detected unusual traffic from your network."
        ));
    }

    #[test]
    fn rate_limit_does_not_match_normal_prompts() {
        assert!(!is_rate_limited(
            "Press PLAY to listen and type what you hear"
        ));
        assert!(!is_rate_limited(""));
    }

    #[test]
    fn audio_url_accepts_recaptcha_host() {
        assert!(looks_like_audio_url(
            "https://www.google.com/recaptcha/api2/payload?p=ASDF"
        ));
    }

    #[test]
    fn audio_url_accepts_mp3_suffix_on_other_hosts() {
        assert!(looks_like_audio_url("https://cdn.example.com/clip.mp3"));
        assert!(looks_like_audio_url("http://x.test/y.mp3"));
    }

    #[test]
    fn audio_url_rejects_data_blob_relative_empty() {
        assert!(!looks_like_audio_url(""));
        assert!(!looks_like_audio_url("data:audio/mpeg;base64,abc"));
        assert!(!looks_like_audio_url("blob:https://x.test/abc"));
        assert!(!looks_like_audio_url("//google.com/recaptcha/x.mp3"));
        assert!(!looks_like_audio_url("/relative/clip.mp3"));
    }

    #[test]
    fn solver_constructs_with_default_endpoint() {
        let s = RecaptchaAudioSolver::new();
        assert_eq!(s.stt_endpoint, "http://localhost:9000/asr");
        assert_eq!(s.name(), "RecaptchaAudioSolver");
        assert_eq!(s.method(), SolveMethod::AudioBypass);
    }

    fn captured_header<'a>(raw: &'a str, name: &str) -> Option<&'a str> {
        raw.lines().find_map(|line| {
            let (key, value) = line.split_once(':')?;
            key.eq_ignore_ascii_case(name).then(|| value.trim())
        })
    }

    #[tokio::test]
    async fn recaptcha_audio_client_uses_shared_audio_subresource_headers() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}/clip.mp3", listener.local_addr().unwrap());
        let server = tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.unwrap();
            let mut request = Vec::new();
            let mut buf = [0_u8; 1024];
            loop {
                let n = socket.read(&mut buf).await.unwrap();
                if n == 0 {
                    break;
                }
                request.extend_from_slice(&buf[..n]);
                if request.windows(4).any(|window| window == b"\r\n\r\n") {
                    break;
                }
            }
            socket
                .write_all(
                    b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
                )
                .await
                .unwrap();
            String::from_utf8(request).unwrap()
        });

        let response = RecaptchaAudioSolver::new()
            .client
            .get(&url)
            .send()
            .await
            .expect("reCAPTCHA audio request");
        assert_eq!(response.status(), reqwest::StatusCode::NO_CONTENT);

        let raw_request = server.await.unwrap();
        let facts = default_profile_facts();
        assert_eq!(
            captured_header(&raw_request, "User-Agent"),
            Some(facts.user_agent)
        );
        assert_eq!(captured_header(&raw_request, "Accept"), Some("*/*"));
        assert_eq!(
            captured_header(&raw_request, "Accept-Language"),
            Some(facts.accept_language)
        );
        assert_eq!(
            captured_header(&raw_request, "Sec-Fetch-Dest"),
            Some("audio")
        );
        assert_eq!(
            captured_header(&raw_request, "Sec-Fetch-Mode"),
            Some("no-cors")
        );
        assert_eq!(
            captured_header(&raw_request, "Sec-Fetch-Site"),
            Some("cross-site")
        );
        assert!(captured_header(&raw_request, "Accept-Encoding").is_none());
        assert!(captured_header(&raw_request, "Upgrade-Insecure-Requests").is_none());
        assert!(captured_header(&raw_request, "Sec-Fetch-User").is_none());
    }

    fn ck(name: &str, value: &str, domain: &str, path: &str, secure: bool) -> CapturedCookie {
        CapturedCookie {
            name: name.into(),
            value: value.into(),
            domain: domain.into(),
            path: path.into(),
            expires: None,
            secure,
            http_only: false,
            same_site: None,
        }
    }

    #[test]
    fn recaptcha_audio_cookie_header_replays_only_url_scoped_safe_cookies() {
        let url =
            reqwest::Url::parse("https://www.google.com/recaptcha/api2/payload?p=clip").unwrap();
        let mut expired = ck("expired", "old", ".google.com", "/", false);
        expired.expires = Some(1);
        let cookies = vec![
            ck("NID", "abc", ".google.com", "/", false),
            ck(
                "__Secure-3PSID",
                "secure",
                ".google.com",
                "/recaptcha",
                true,
            ),
            ck(
                "host_only",
                "one",
                "www.google.com",
                "/recaptcha/api2",
                false,
            ),
            ck("wrong_host", "skip", ".example.com", "/", false),
            ck("wrong_path", "skip", ".google.com", "/accounts", false),
            ck("bad;name", "skip", ".google.com", "/", false),
            ck("bad_value", "skip;me", ".google.com", "/", false),
            expired,
        ];

        let header = recaptcha_audio_cookie_header(&cookies, &url)
            .expect("matching cookies should produce a header");

        assert_eq!(
            header.to_str().unwrap(),
            "NID=abc; __Secure-3PSID=secure; host_only=one"
        );
    }

    #[test]
    fn solver_with_custom_endpoint() {
        let s = RecaptchaAudioSolver::new().with_stt_endpoint("http://stt.test:5000/v1");
        assert_eq!(s.stt_endpoint, "http://stt.test:5000/v1");
    }

    #[test]
    fn solver_supports_recaptcha_v2_and_audio_kinds() {
        use crate::captcha_detect::DetectedCaptcha;
        let s = RecaptchaAudioSolver::new();
        assert!(s.supports(&DetectedCaptcha::RecaptchaV2));
        assert!(s.supports(&DetectedCaptcha::AudioCaptcha));
        assert!(!s.supports(&DetectedCaptcha::HCaptcha));
        assert!(!s.supports(&DetectedCaptcha::Turnstile));
        assert!(!s.supports(&DetectedCaptcha::None));
    }

    #[test]
    fn selectors_are_stable_strings() {
        // These are the contract — if Google ever changes them, the
        // change shows up here as a diff and a regression fixture
        // gets added at the same time.
        assert_eq!(AUDIO_BUTTON_SELECTOR, "#recaptcha-audio-button");
        assert_eq!(RESPONSE_INPUT_SELECTOR, "#audio-response");
        assert_eq!(VERIFY_BUTTON_SELECTOR, "#recaptcha-verify-button");
        assert_eq!(TOKEN_INPUT_NAME, "g-recaptcha-response");
        assert!(RECAPTCHA_BFRAME_SELECTOR.contains("api2/bframe"));
    }

    #[test]
    fn max_audio_retries_is_bounded_small() {
        // A high cap would burn IP reputation on a single solve; a
        // cap of 0 would defeat the multi-clip flow Google sometimes
        // serves. Two is the sweet spot — pin it so future edits
        // notice if someone bumps it.
        assert_eq!(MAX_AUDIO_RETRIES, 2);
    }
}