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
//! Token-validation oracle.
//!
//! [`super::oracle`] proves the *page* advanced past the challenge.
//! This proves the *token* actually unlocks the protected resource:
//! we POST it back to a configured verify endpoint and assert the
//! response is non-blocked.
//!
//! Without this layer, "we got a Turnstile token" can mean any of:
//!
//! - Real token, server happily accepts it ✅
//! - Real token, but server-side IP reputation rejects regardless ❌
//! - Real token, but vendor short-lived expiry already elapsed ❌
//! - Demo-sitekey token (`1x00000000000000000000AA`), useless on
//!   production ❌
//! - Token harvested from a non-matching origin (vendor binds tokens
//!   to the page that requested them) ❌
//!
//! The end-to-end oracle catches all five.
//!
//! # Configuration
//!
//! Opt-in. The chain doesn't validate by default — most use cases
//! don't have a verify endpoint to call. Use [`TokenValidator`]
//! manually after a chain solve when you want the proof:
//!
//! ```no_run
//! # async fn run(token: &str) -> anyhow::Result<()> {
//! use captchaforge::solver::token_oracle::{TokenValidator, ValidationVerdict};
//!
//! let validator = TokenValidator::new("https://target.example/verify-captcha");
//! let verdict = validator.validate(token).await?;
//! assert_eq!(verdict, ValidationVerdict::Accepted);
//! # Ok(()) }
//! ```
//!
//! # Verdicts
//!
//! - [`ValidationVerdict::Accepted`] — endpoint returned 2xx with
//!   no block-phrase markers in the body.
//! - [`ValidationVerdict::Rejected`] — endpoint returned 4xx/5xx
//!   OR a 2xx with block-phrase markers.
//! - [`ValidationVerdict::Inconclusive`] — network error,
//!   timeout, or unparseable response. Don't treat as accepted.

use anyhow::Result;
use reqwest::header::{HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use serde::{Deserialize, Serialize};
use std::time::Duration;

use crate::solver::oracle::BLOCK_PHRASES;

/// Verdict from a token-replay attempt.
///
/// `#[non_exhaustive]` so we can add (e.g.) `RateLimited` without
/// breaking downstream `match`es.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ValidationVerdict {
    Accepted,
    Rejected,
    Inconclusive,
}

/// HTTP method for the validation request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidatorMethod {
    Post,
    Get,
}

/// How the token is sent. Most vendor-side endpoints expect POSTed
/// form data with `cf-turnstile-response`/`g-recaptcha-response`/
/// `h-captcha-response` keys. Origin-side endpoints often want
/// JSON. Both supported.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TokenEncoding {
    /// `application/x-www-form-urlencoded` — `field=token`.
    FormUrlEncoded,
    /// `application/json` — `{"field": "token"}`.
    Json,
    /// HTTP header — `Authorization: Bearer <token>`. Useful when
    /// the verify endpoint authenticates with the token directly
    /// rather than a captcha-response field.
    BearerHeader,
}

/// Configuration for [`TokenValidator`].
#[derive(Debug, Clone)]
pub struct TokenValidator {
    pub endpoint: String,
    pub method: ValidatorMethod,
    pub encoding: TokenEncoding,
    /// Form/JSON field name for the token. Default `cf-turnstile-response`.
    pub field: String,
    /// Per-request timeout. Default 10s.
    pub timeout: Duration,
}

struct ValidationRequest {
    method: &'static str,
    url: String,
    headers: Vec<(String, String)>,
    body: Option<Vec<u8>>,
}

impl TokenValidator {
    /// Construct a validator that POSTs the token as
    /// `cf-turnstile-response=<token>` to `endpoint`.
    pub fn new(endpoint: impl Into<String>) -> Self {
        Self {
            endpoint: endpoint.into(),
            method: ValidatorMethod::Post,
            encoding: TokenEncoding::FormUrlEncoded,
            field: "cf-turnstile-response".into(),
            timeout: Duration::from_secs(10),
        }
    }

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

    pub fn with_encoding(mut self, encoding: TokenEncoding) -> Self {
        self.encoding = encoding;
        self
    }

    pub fn with_method(mut self, method: ValidatorMethod) -> Self {
        self.method = method;
        self
    }

    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Send the token to the endpoint and classify the response.
    ///
    /// `Inconclusive` on network/timeout error rather than `Err` —
    /// the caller almost always wants to merge the verdict into a
    /// pipeline that already has its own error handling, and a
    /// network blip on the verify endpoint is not the same kind of
    /// failure as a malformed config.
    pub async fn validate(&self, token: &str) -> Result<ValidationVerdict> {
        let Some(request) = self.validation_request(token) else {
            return Ok(ValidationVerdict::Inconclusive);
        };

        #[cfg(feature = "tls-impersonate")]
        {
            return match crate::waf_gate::send_validation(
                request.method,
                &request.url,
                request.headers,
                request.body,
                self.timeout,
            )
            .await
            {
                Ok((status, body)) => Ok(classify_response(status, body.as_deref())),
                Err(()) => Ok(ValidationVerdict::Inconclusive),
            };
        }

        #[cfg(not(feature = "tls-impersonate"))]
        {
            let client = crate::http_client::timed_client(self.timeout)?;

            let mut req = match request.method {
                "POST" => client.post(&request.url),
                "GET" => client.get(&request.url),
                _ => return Ok(ValidationVerdict::Inconclusive),
            };
            for (name, value) in request.headers {
                req = req.header(name, value);
            }
            if let Some(body) = request.body {
                req = req.body(body);
            }

            let response = match req.send().await {
                Ok(r) => r,
                Err(_) => return Ok(ValidationVerdict::Inconclusive),
            };

            let status = response.status().as_u16();
            // Bound the body read to MAX_VALIDATION_BODY_BYTES. A hostile
            // or buggy verify endpoint streaming an unbounded payload would
            // otherwise allocate a String of arbitrary size and OOM the
            // worker. We only need the first ~64 KiB for block-phrase
            // detection — that's well past every realistic verify-endpoint
            // response body.
            let body = read_capped_body(response, MAX_VALIDATION_BODY_BYTES).await;
            Ok(classify_response(status, body.as_deref()))
        }
    }

    fn validation_request(&self, token: &str) -> Option<ValidationRequest> {
        let mut url = reqwest::Url::parse(&self.endpoint).ok()?;
        let method = match self.method {
            ValidatorMethod::Post => "POST",
            ValidatorMethod::Get => "GET",
        };
        let mut headers = validation_default_header_pairs();
        let mut body = None;

        match (self.method, self.encoding) {
            (ValidatorMethod::Post, TokenEncoding::FormUrlEncoded) => {
                headers.push((
                    CONTENT_TYPE.as_str().to_string(),
                    "application/x-www-form-urlencoded".to_string(),
                ));
                body = Some(
                    url::form_urlencoded::Serializer::new(String::new())
                        .append_pair(&self.field, token)
                        .finish()
                        .into_bytes(),
                );
            }
            (ValidatorMethod::Post, TokenEncoding::Json) => {
                headers.push((
                    CONTENT_TYPE.as_str().to_string(),
                    "application/json".to_string(),
                ));
                body = Some(
                    serde_json::to_vec(&serde_json::json!({
                        self.field.as_str(): token
                    }))
                    .ok()?,
                );
            }
            (ValidatorMethod::Post, TokenEncoding::BearerHeader) => {
                headers.push(authorization_header_pair(token)?);
            }
            (ValidatorMethod::Get, TokenEncoding::FormUrlEncoded) => {
                url.query_pairs_mut().append_pair(&self.field, token);
            }
            (ValidatorMethod::Get, TokenEncoding::Json) => {
                headers.push(("X-Token".to_string(), header_value_string(token)?));
            }
            (ValidatorMethod::Get, TokenEncoding::BearerHeader) => {
                headers.push(authorization_header_pair(token)?);
            }
        }

        Some(ValidationRequest {
            method,
            url: url.to_string(),
            headers,
            body,
        })
    }
}

/// Maximum number of bytes to read from a verify-endpoint response
/// before truncating. Block-phrase detection only needs the first
/// few KiB; this cap is generous to leave room for verbose vendor
/// error JSON without ever allowing an unbounded read.
const MAX_VALIDATION_BODY_BYTES: usize = crate::waf_gate::VALIDATION_BODY_CAP;

fn validation_default_header_pairs() -> Vec<(String, String)> {
    guise::http::default_browser_request_headers_without_compression(
        guise::http::BrowserRequestKind::SameOriginFetch,
    )
    .into_iter()
    .map(|header| (header.name.to_string(), header.value))
    .collect()
}

fn authorization_header_pair(token: &str) -> Option<(String, String)> {
    Some((
        AUTHORIZATION.as_str().to_string(),
        header_value_string(&format!("Bearer {token}"))?,
    ))
}

fn header_value_string(raw: &str) -> Option<String> {
    let value = HeaderValue::from_str(raw).ok()?;
    value.to_str().ok().map(str::to_string)
}

async fn read_capped_body(mut response: reqwest::Response, max: usize) -> Option<String> {
    // Use `Response::chunk()` rather than `bytes_stream()` so the
    // crate doesn't need the `stream` feature of reqwest enabled.
    let mut buf: Vec<u8> = Vec::new();
    loop {
        let chunk = response.chunk().await.ok().flatten();
        match chunk {
            Some(bytes) => {
                if buf.len() + bytes.len() > max {
                    let remaining = max.saturating_sub(buf.len());
                    buf.extend_from_slice(&bytes[..remaining]);
                    break;
                }
                buf.extend_from_slice(&bytes);
            }
            None => break,
        }
    }
    // Truncate on a UTF-8 boundary before lossy-decoding so a block
    // phrase straddling the cap doesn't get split mid-codepoint into
    // an unrecognisable replacement character. Walk back at most 3
    // bytes — that's the max width of a UTF-8 continuation tail.
    let mut end = buf.len();
    for _ in 0..3 {
        if std::str::from_utf8(&buf[..end]).is_ok() {
            break;
        }
        if end == 0 {
            break;
        }
        end -= 1;
    }
    Some(String::from_utf8_lossy(&buf[..end]).into_owned())
}

/// Pure classifier — exposed so synthetic tests can exercise it
/// without spinning up an HTTP server.
pub fn classify_response(status: u16, body: Option<&str>) -> ValidationVerdict {
    if !(200..300).contains(&status) {
        return ValidationVerdict::Rejected;
    }
    if let Some(body) = body {
        let lower = body.to_lowercase();
        if BLOCK_PHRASES.iter().any(|p| lower.contains(p)) {
            return ValidationVerdict::Rejected;
        }
    }
    ValidationVerdict::Accepted
}

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

    #[test]
    fn classify_4xx_rejected() {
        assert_eq!(classify_response(403, None), ValidationVerdict::Rejected);
        assert_eq!(classify_response(429, None), ValidationVerdict::Rejected);
    }

    #[test]
    fn classify_5xx_rejected() {
        assert_eq!(classify_response(500, None), ValidationVerdict::Rejected);
        assert_eq!(classify_response(503, None), ValidationVerdict::Rejected);
    }

    #[test]
    fn classify_2xx_clean_body_accepted() {
        assert_eq!(
            classify_response(200, Some("{\"ok\": true}")),
            ValidationVerdict::Accepted,
        );
        assert_eq!(classify_response(204, None), ValidationVerdict::Accepted,);
    }

    #[test]
    fn classify_2xx_with_block_phrase_rejected() {
        // A vendor that returns 200 with a "Sorry, you have been
        // blocked" body is still a rejection — the token wasn't
        // accepted, the page just didn't bother with a 4xx.
        assert_eq!(
            classify_response(200, Some("Sorry, you have been blocked.")),
            ValidationVerdict::Rejected,
        );
        assert_eq!(
            classify_response(200, Some("Access Denied")),
            ValidationVerdict::Rejected,
        );
        assert_eq!(
            classify_response(200, Some("Pardon Our Interruption")),
            ValidationVerdict::Rejected,
        );
    }

    #[test]
    fn classify_2xx_block_phrase_case_insensitive() {
        assert_eq!(
            classify_response(200, Some("REQUEST BLOCKED")),
            ValidationVerdict::Rejected,
        );
    }

    #[test]
    fn validator_builder_chains() {
        let v = TokenValidator::new("https://x.test/v")
            .with_field("g-recaptcha-response")
            .with_encoding(TokenEncoding::Json)
            .with_method(ValidatorMethod::Get)
            .with_timeout(Duration::from_secs(2));
        assert_eq!(v.endpoint, "https://x.test/v");
        assert_eq!(v.field, "g-recaptcha-response");
        assert_eq!(v.encoding, TokenEncoding::Json);
        assert_eq!(v.method, ValidatorMethod::Get);
        assert_eq!(v.timeout, Duration::from_secs(2));
    }

    #[test]
    fn default_field_is_turnstile() {
        let v = TokenValidator::new("https://x.test/v");
        assert_eq!(v.field, "cf-turnstile-response");
    }

    fn header_from_pairs<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
        headers
            .iter()
            .find(|(key, _)| key.eq_ignore_ascii_case(name))
            .map(|(_, value)| value.as_str())
    }

    #[test]
    fn validation_request_uses_shared_same_origin_fetch_headers() {
        let request = TokenValidator::new("https://app.test/verify")
            .validation_request("tok value")
            .expect("valid request");
        let facts = default_profile_facts();

        assert_eq!(request.method, "POST");
        assert_eq!(request.url, "https://app.test/verify");
        assert_eq!(
            header_from_pairs(&request.headers, "User-Agent"),
            Some(facts.user_agent)
        );
        assert_eq!(header_from_pairs(&request.headers, "Accept"), Some("*/*"));
        assert_eq!(
            header_from_pairs(&request.headers, "Accept-Language"),
            Some(facts.accept_language)
        );
        assert_eq!(
            header_from_pairs(&request.headers, "Sec-Fetch-Dest"),
            Some("empty")
        );
        assert_eq!(
            header_from_pairs(&request.headers, "Sec-Fetch-Mode"),
            Some("cors")
        );
        assert_eq!(
            header_from_pairs(&request.headers, "Sec-Fetch-Site"),
            Some("same-origin")
        );
        assert_eq!(
            header_from_pairs(&request.headers, "Content-Type"),
            Some("application/x-www-form-urlencoded")
        );
        assert!(header_from_pairs(&request.headers, "Accept-Encoding").is_none());
        assert!(header_from_pairs(&request.headers, "Upgrade-Insecure-Requests").is_none());
        assert!(header_from_pairs(&request.headers, "Sec-Fetch-User").is_none());
        assert_eq!(
            String::from_utf8(request.body.expect("form body")).unwrap(),
            "cf-turnstile-response=tok+value"
        );
    }

    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())
        })
    }

    #[cfg(not(feature = "tls-impersonate"))]
    #[tokio::test]
    async fn validator_validate_sends_shared_fetch_headers_and_form_body() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}/verify", 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];
            let mut expected_len = None;
            loop {
                let n = socket.read(&mut buf).await.unwrap();
                if n == 0 {
                    break;
                }
                request.extend_from_slice(&buf[..n]);
                if expected_len.is_none() {
                    if let Some(header_end) = request
                        .windows(4)
                        .position(|window| window == b"\r\n\r\n")
                        .map(|idx| idx + 4)
                    {
                        let headers = String::from_utf8_lossy(&request[..header_end]);
                        let body_len = captured_header(&headers, "Content-Length")
                            .and_then(|value| value.parse::<usize>().ok())
                            .unwrap_or(0);
                        expected_len = Some(header_end + body_len);
                    }
                }
                if expected_len.is_some_and(|len| request.len() >= len) {
                    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 verdict = TokenValidator::new(url)
            .validate("tok value")
            .await
            .expect("validation request");

        assert_eq!(verdict, ValidationVerdict::Accepted);
        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("empty")
        );
        assert_eq!(
            captured_header(&raw_request, "Sec-Fetch-Mode"),
            Some("cors")
        );
        assert_eq!(
            captured_header(&raw_request, "Sec-Fetch-Site"),
            Some("same-origin")
        );
        assert_eq!(
            captured_header(&raw_request, "Content-Type"),
            Some("application/x-www-form-urlencoded")
        );
        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());
        assert!(raw_request.ends_with("cf-turnstile-response=tok+value"));
    }
}