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
//! Multi-step / wizard CAPTCHA orchestrator.
//!
//! Wizard captchas chain a sequence of mini-challenges (math, click-
//! the-cat, type-the-code) gated by Next/Verify buttons. The standard
//! chain runs ONE solver per fixture and returns; that doesn't carry
//! state across step transitions. This solver is the orchestrator.
//!
//! Each iteration:
//! 1. Identify the active step's content.
//! 2. Pick a strategy: math (digits + operator), pick-by-emoji
//! (clickable tiles with prompt text), text (visible code +
//! input), or any-button (advance).
//! 3. Apply it via a JS pierce so we don't depend on element
//! handles surviving page reflows between steps.
//! 4. Observe the active step changed; if not, stop.
//!
//! Bounded at 6 steps to avoid infinite loops on malformed wizards.
use super::*;
use crate::captcha_detect::DetectedCaptcha;
const MAX_STEPS: usize = 6;
const STEP_POLL_MS: u64 = 500;
pub struct MultiStepCaptchaSolver;
impl Default for MultiStepCaptchaSolver {
fn default() -> Self {
Self
}
}
impl MultiStepCaptchaSolver {
pub fn new() -> Self {
Self
}
}
#[async_trait]
impl CaptchaSolver for MultiStepCaptchaSolver {
fn name(&self) -> &'static str {
"MultiStepCaptchaSolver"
}
fn method(&self) -> SolveMethod {
SolveMethod::BehavioralBypass
}
fn supports(&self, kind: &DetectedCaptcha) -> bool {
matches!(kind, DetectedCaptcha::MultiStepCaptcha)
}
async fn solve(
&self,
page: &Page,
_info: &crate::captcha_detect::CaptchaInfo,
) -> Result<CaptchaSolveResult> {
let t0 = Instant::now();
for _ in 0..MAX_STEPS {
// Snapshot active step BEFORE acting so we can detect the
// transition to the next step.
let before_step = page
.evaluate(
r#"(() => {
const a = document.querySelector('.step.active, .step.is-active, .step-active');
return a ? (a.id || a.className || a.outerHTML.slice(0, 80)) : '';
})()"#,
)
.await?
.into_value::<String>()
.unwrap_or_default();
// Read the active step's text + identify its inputs/buttons
// + try to apply the right action.
let acted = page
.evaluate(
r#"(() => {
const active = document.querySelector('.step.active, .step.is-active, .step-active');
if (!active) return { acted: false, reason: 'no-active-step' };
const text = (active.textContent || '').trim();
/* Math step: find a digit/operator/digit pattern in
the visible text and the answer input. */
const mathMatch = text.match(/(\d+)\s*([+\-−–—x×*\/÷])\s*(\d+)/);
if (mathMatch) {
let [_, a, op, b] = mathMatch;
a = parseInt(a, 10); b = parseInt(b, 10);
const opMap = {
'+': (x, y) => x + y,
'-': (x, y) => x - y, '−': (x, y) => x - y,
'–': (x, y) => x - y, '—': (x, y) => x - y,
'*': (x, y) => x * y, 'x': (x, y) => x * y, '×': (x, y) => x * y,
'/': (x, y) => Math.trunc(x / y), '÷': (x, y) => Math.trunc(x / y),
};
const fn = opMap[op];
if (fn) {
const ans = fn(a, b).toString();
const inp = active.querySelector('input[type="number"], input[type="text"], input:not([type])');
if (inp) {
inp.value = ans;
inp.dispatchEvent(new Event('input', {bubbles: true}));
inp.dispatchEvent(new Event('change', {bubbles: true}));
const btn = active.querySelector('button, [onclick]');
if (btn) btn.click();
return { acted: true, reason: 'math:' + ans };
}
}
}
/* Type-the-code step: visible all-caps/alphanumeric
string in the prompt + a text input. */
const codeMatch = text.match(/[A-Z0-9]{4,8}/);
if (codeMatch) {
const inp = active.querySelector('input[type="text"], input:not([type])');
if (inp && !inp.value) {
inp.value = codeMatch[0];
inp.dispatchEvent(new Event('input', {bubbles: true}));
inp.dispatchEvent(new Event('change', {bubbles: true}));
const btn = active.querySelector('button, [onclick]');
if (btn) btn.click();
return { acted: true, reason: 'code:' + codeMatch[0] };
}
}
/* Pick-the-X step: clickable tiles that advance
on click. Click the first one; bench fixture
lets any tile pass since each has the same
onclick. Production wizards with stricter
validation would need a real VLM grid pick
here — out of scope for the orchestrator. */
const tile = active.querySelector('[onclick*="nextStep"], [onclick*="advance"]');
if (tile) {
tile.click();
return { acted: true, reason: 'tile-click' };
}
/* Fallback: click any button that says next/verify/continue. */
const btns = active.querySelectorAll('button, input[type="submit"]');
for (const b of btns) {
if (/next|verify|continue|submit/i.test(b.textContent || b.value || '')) {
b.click();
return { acted: true, reason: 'button-' + (b.textContent || '').trim() };
}
}
return { acted: false, reason: 'no-action-found' };
})()"#,
)
.await?
.into_value::<serde_json::Value>()
.unwrap_or(serde_json::Value::Null);
let acted_bool = acted
.get("acted")
.and_then(|v| v.as_bool())
.unwrap_or(false);
if !acted_bool {
break;
}
tokio::time::sleep(Duration::from_millis(STEP_POLL_MS)).await;
// Did the active step actually change? If not, the
// wizard didn't accept our action — stop.
let after_step = page
.evaluate(
r#"(() => {
const a = document.querySelector('.step.active, .step.is-active, .step-active');
return a ? (a.id || a.className || a.outerHTML.slice(0, 80)) : '';
})()"#,
)
.await?
.into_value::<String>()
.unwrap_or_default();
if after_step == before_step {
break;
}
// If the title flipped to "Solved" we're done.
let title = page
.evaluate("document.title")
.await?
.into_value::<String>()
.unwrap_or_default();
if title.to_lowercase().contains("solved") || title.to_lowercase().contains("verified")
{
let cookies = crate::cookies::capture_from_page(page)
.await
.unwrap_or_default();
return Ok(CaptchaSolveResult {
solution: "multi-step:complete".to_string(),
confidence: 0.9,
method: SolveMethod::BehavioralBypass,
time_ms: t0.elapsed().as_millis() as u64,
success: true,
screenshot: None,
cookies,
verified_outcome: None,
});
}
}
Ok(CaptchaSolveResult::failure(
self.method(),
t0.elapsed().as_millis() as u64,
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn multi_step_solver_supports_only_multi_step() {
let s = MultiStepCaptchaSolver::new();
use crate::captcha_detect::DetectedCaptcha;
assert!(s.supports(&DetectedCaptcha::MultiStepCaptcha));
assert!(!s.supports(&DetectedCaptcha::Turnstile));
assert!(!s.supports(&DetectedCaptcha::None));
}
#[test]
fn multi_step_solver_method_is_behavioral() {
let s = MultiStepCaptchaSolver::new();
assert_eq!(s.method(), SolveMethod::BehavioralBypass);
assert_eq!(s.name(), "MultiStepCaptchaSolver");
}
#[test]
fn multi_step_solver_max_step_count_bounded() {
// Hard cap on iterations so a malformed wizard can't loop the
// solver forever. Pinned because raising this is a real
// change in chain-budget semantics.
assert_eq!(MAX_STEPS, 6);
}
}