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
use crate::Page;
use anyhow::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use crate::captcha_detect::CaptchaInfo;
/// The variety of CAPTCHA encountered.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CaptchaType {
RecaptchaV2,
RecaptchaV3,
#[serde(rename = "hcaptcha")]
HCaptcha,
CloudflareTurnstile,
ImageGrid,
TextCaptcha,
AudioCaptcha,
Slider,
PowCaptcha,
CanvasCaptcha,
ShadowDomCaptcha,
MultiStepCaptcha,
Custom(String),
}
impl std::fmt::Display for CaptchaType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CaptchaType::RecaptchaV2 => write!(f, "recaptcha_v2"),
CaptchaType::RecaptchaV3 => write!(f, "recaptcha_v3"),
CaptchaType::HCaptcha => write!(f, "hcaptcha"),
CaptchaType::CloudflareTurnstile => write!(f, "cloudflare_turnstile"),
CaptchaType::ImageGrid => write!(f, "image_grid"),
CaptchaType::TextCaptcha => write!(f, "text_captcha"),
CaptchaType::AudioCaptcha => write!(f, "audio_captcha"),
CaptchaType::Slider => write!(f, "slider"),
CaptchaType::PowCaptcha => write!(f, "pow_captcha"),
CaptchaType::CanvasCaptcha => write!(f, "canvas_captcha"),
CaptchaType::ShadowDomCaptcha => write!(f, "shadow_dom_captcha"),
CaptchaType::MultiStepCaptcha => write!(f, "multi_step_captcha"),
CaptchaType::Custom(s) => write!(f, "custom:{}", s),
}
}
}
/// Which solving strategy produced the result.
///
/// `#[non_exhaustive]` so downstream `match` statements stay
/// forward-compatible across additions (e.g. AutoPass landed in
/// 0.2.5, without `#[non_exhaustive]` that would have been a
/// breaking change to the public enum).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SolveMethod {
// serde's snake_case heuristic mangles consecutive caps:
// `VisionLLM` -> `vision_l_l_m`. Pin the wire form so persisted
// PatternStore entries don't break across solver upgrades.
#[serde(rename = "vision_llm")]
VisionLLM,
AudioBypass,
BehavioralBypass,
ThirdPartyService,
CrowdSourced,
/// Captcha auto-completed without explicit interaction, the
/// vendor script populated the response field on its own (e.g.
/// Cloudflare/hCaptcha/Google test sitekeys, or production
/// passive challenges that pass on a clean fingerprint). The
/// chain just polled for the token and read it. Cheapest possible
/// "solve" (no mouse simulation, no VLM call, no API charge).
AutoPass,
}
/// The outcome of a solve attempt.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaptchaSolveResult {
/// Token or typed answer produced by the solver.
pub solution: String,
/// Confidence in 0.0–1.0 range.
pub confidence: f32,
/// Which strategy was used.
pub method: SolveMethod,
/// Wall-clock time for the solve in milliseconds.
pub time_ms: u64,
/// Whether the solve is considered successful.
pub success: bool,
/// Base64 JPEG screenshot taken at the point of fallback / failure,
/// useful for human-in-the-loop review.
pub screenshot: Option<String>,
/// Browser cookies captured at the point of successful solve.
/// Replay these on subsequent navigations (via
/// [`crate::cookies::apply_to_page`]) to ride the WAF/vendor's
/// trusted session and avoid re-triggering the captcha.
/// Empty for failed solves and for solvers that don't capture
/// cookies (e.g. the cache short-circuit path returns `vec![]`).
#[serde(default)]
pub cookies: Vec<crate::cookies::CapturedCookie>,
/// Outcome the [`crate::solver::oracle`] derived from page-state
/// drift before vs after solve. `None` when the chain ran with
/// `verify_outcome` disabled. `Some(Advanced)` is the only value
/// that *proves* the page is past the challenge, every other
/// variant downgrades a green-checkmark token to "claimed but
/// unverified". When the chain has the oracle on, it overwrites
/// `success` to `false` for HardBlock / Recycled / SilentFail
/// so naive callers can't be fooled.
#[serde(default)]
pub verified_outcome: Option<crate::solver::oracle::OutcomeClassification>,
}
impl CaptchaSolveResult {
pub fn failure(method: SolveMethod, time_ms: u64) -> Self {
Self {
solution: String::new(),
confidence: 0.0,
method,
time_ms,
success: false,
screenshot: None,
cookies: Vec::new(),
verified_outcome: None,
}
}
pub fn unsolved(time_ms: u64, screenshot: Option<String>) -> Self {
Self {
solution: String::new(),
confidence: 0.0,
method: SolveMethod::CrowdSourced,
time_ms,
success: false,
screenshot,
cookies: Vec::new(),
verified_outcome: None,
}
}
/// C046/C047 / Screwdriver (the anti-overclaim invariant).
///
/// A result that claims `success` MUST carry the evidence a success has: a
/// non-empty `solution` (a real token / typed answer). A `success: true` with
/// an empty `solution` is a solve reported with nothing to show for it, the
/// exact "fabricated/fake success" C047 forbids. Returns `true` when the
/// result is in that incoherent state, so the chain and tests can refuse it.
#[must_use]
pub fn claims_success_without_token(&self) -> bool {
self.success && self.solution.trim().is_empty()
}
/// True when the result is self-consistent: a success carries a token AND a
/// non-failure confidence; a non-success makes no claim. The inverse of an
/// overclaim. Cheap; pure.
#[must_use]
pub fn is_coherent(&self) -> bool {
if self.success {
!self.solution.trim().is_empty() && self.confidence > 0.0
} else {
true
}
}
}
/// Timeouts and retry limits for the solving pipeline.
///
/// All durations are in milliseconds for simplicity.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct SolveConfig {
/// How long to wait for a checkbox/iframe to appear (ms per attempt).
pub checkbox_poll_interval_ms: u64,
/// Maximum attempts to find a checkbox before giving up.
pub checkbox_max_attempts: u32,
/// How long to wait for a CAPTCHA token to appear after interaction.
pub token_poll_interval_ms: u64,
/// Maximum attempts to verify a token was produced.
pub token_max_attempts: u32,
/// Delay after clicking the audio challenge button (ms).
pub audio_button_delay_ms: u64,
/// Delay after submitting an audio answer (ms).
pub audio_submit_delay_ms: u64,
/// HTTP timeout for VLM screenshot queries (ms).
pub vlm_http_timeout_ms: u64,
/// HTTP timeout for the reqwest client backing audio/VLM solvers (ms).
pub client_http_timeout_ms: u64,
}
impl Default for SolveConfig {
fn default() -> Self {
Self {
checkbox_poll_interval_ms: 500,
checkbox_max_attempts: 15,
token_poll_interval_ms: 500,
token_max_attempts: 16,
audio_button_delay_ms: 2000,
audio_submit_delay_ms: 2000,
vlm_http_timeout_ms: 120_000,
client_http_timeout_ms: 180_000,
}
}
}
/// Shared trait for all CAPTCHA solvers.
#[async_trait]
pub trait CaptchaSolver: Send + Sync {
/// Attempt to solve the CAPTCHA visible on `page`.
async fn solve(&self, page: &Page, captcha_info: &CaptchaInfo) -> Result<CaptchaSolveResult>;
/// Human-readable name for logging.
fn name(&self) -> &'static str;
/// The [`SolveMethod`] this solver produces on success.
fn method(&self) -> SolveMethod;
/// Whether this solver is capable of handling the detected CAPTCHA kind.
/// The chain uses this to skip solvers that are guaranteed to fail for a
/// given type, avoiding wasted time and API calls.
fn supports(&self, kind: &crate::captcha_detect::DetectedCaptcha) -> bool;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn captcha_type_display() {
assert_eq!(CaptchaType::RecaptchaV2.to_string(), "recaptcha_v2");
assert_eq!(
CaptchaType::CloudflareTurnstile.to_string(),
"cloudflare_turnstile"
);
assert_eq!(
CaptchaType::Custom("banana".to_string()).to_string(),
"custom:banana"
);
assert_eq!(CaptchaType::PowCaptcha.to_string(), "pow_captcha");
assert_eq!(CaptchaType::CanvasCaptcha.to_string(), "canvas_captcha");
assert_eq!(
CaptchaType::ShadowDomCaptcha.to_string(),
"shadow_dom_captcha"
);
assert_eq!(
CaptchaType::MultiStepCaptcha.to_string(),
"multi_step_captcha"
);
}
#[test]
fn captcha_type_serializes() {
let json = serde_json::to_string(&CaptchaType::HCaptcha).unwrap();
assert_eq!(json, r#""hcaptcha""#);
}
#[test]
fn captcha_type_roundtrips_all_variants() {
for variant in [
CaptchaType::RecaptchaV2,
CaptchaType::RecaptchaV3,
CaptchaType::HCaptcha,
CaptchaType::CloudflareTurnstile,
CaptchaType::ImageGrid,
CaptchaType::TextCaptcha,
CaptchaType::AudioCaptcha,
CaptchaType::Slider,
CaptchaType::PowCaptcha,
CaptchaType::CanvasCaptcha,
CaptchaType::ShadowDomCaptcha,
CaptchaType::MultiStepCaptcha,
CaptchaType::Custom("foo".to_string()),
] {
let json = serde_json::to_string(&variant).unwrap();
let rt: CaptchaType = serde_json::from_str(&json).unwrap();
assert_eq!(variant, rt);
}
}
#[test]
fn solve_method_serializes() {
let json = serde_json::to_string(&SolveMethod::VisionLLM).unwrap();
assert_eq!(json, r#""vision_llm""#);
}
#[test]
fn solve_result_failure_constructor() {
let r = CaptchaSolveResult::failure(SolveMethod::AudioBypass, 500);
assert!(!r.success);
assert_eq!(r.time_ms, 500);
assert_eq!(r.confidence, 0.0);
assert!(r.solution.is_empty());
}
#[test]
fn anti_overclaim_invariant_failure_and_unsolved_make_no_claim() {
// C046/C047, the failed-solve constructors must never look like a solve:
// success=false, no token, so they are coherent and not an overclaim.
for r in [
CaptchaSolveResult::failure(SolveMethod::AudioBypass, 10),
CaptchaSolveResult::unsolved(20, None),
] {
assert!(
!r.claims_success_without_token(),
"a failed solve must not claim success"
);
assert!(
r.is_coherent(),
"a failed solve with no token is coherent (makes no claim)"
);
}
}
#[test]
fn anti_overclaim_invariant_flags_a_tokenless_success() {
// The exact fabricated-success shape C047 forbids: success=true with an
// empty token. The invariant must catch it.
let overclaim = CaptchaSolveResult {
success: true,
solution: " ".to_string(), // whitespace-only = no real token
confidence: 0.9,
..CaptchaSolveResult::failure(SolveMethod::BehavioralBypass, 0)
};
assert!(
overclaim.claims_success_without_token(),
"a tokenless success must be flagged"
);
assert!(
!overclaim.is_coherent(),
"a tokenless success is NOT coherent"
);
// A real success, non-empty token + positive confidence, is coherent and
// not an overclaim.
let real = CaptchaSolveResult {
success: true,
solution: "tok_abc123".to_string(),
confidence: 0.95,
..CaptchaSolveResult::failure(SolveMethod::AutoPass, 0)
};
assert!(!real.claims_success_without_token());
assert!(real.is_coherent());
}
#[test]
fn solve_result_round_trips_json() {
let r = CaptchaSolveResult {
solution: "abc123".to_string(),
confidence: 0.9,
method: SolveMethod::BehavioralBypass,
time_ms: 1234,
success: true,
screenshot: None,
cookies: Vec::new(),
verified_outcome: None,
};
let json = serde_json::to_string(&r).unwrap();
let r2: CaptchaSolveResult = serde_json::from_str(&json).unwrap();
assert_eq!(r2.solution, "abc123");
assert_eq!(r2.time_ms, 1234);
assert!(r2.success);
}
#[test]
fn unsolved_result_has_no_screenshot() {
let r = CaptchaSolveResult::unsolved(1234, None);
assert!(!r.success);
assert_eq!(r.time_ms, 1234);
assert!(r.screenshot.is_none());
}
#[test]
fn unsolved_result_can_carry_screenshot() {
let r = CaptchaSolveResult::unsolved(5678, Some("b64img".into()));
assert!(!r.success);
assert_eq!(r.screenshot, Some("b64img".into()));
}
}