use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const CAPTCHA_SOLVER_SWITCH: &str = "--captcha-solver";
pub const CAPTCHA_MODEL_PATH_SWITCH: &str = "--captcha-model-path";
pub const ENABLE_METHOD: &str = "Chromeleon.enable";
pub const DISABLE_METHOD: &str = "Chromeleon.disable";
pub const SOLVER_EVAL_METHOD: &str = "Chromeleon.solverEval";
pub const CAPTCHA_DETECTED: &str = "Chromeleon.captchaDetected";
pub const CAPTCHA_SOLVING: &str = "Chromeleon.captchaSolving";
pub const CAPTCHA_SOLVED: &str = "Chromeleon.captchaSolved";
pub const CAPTCHA_FAILED: &str = "Chromeleon.captchaFailed";
pub const SOLVER_EVAL_RESULT: &str = "Chromeleon.solverEvalResult";
pub const CAPTCHA_EVENTS: &[&str] = &[
CAPTCHA_DETECTED,
CAPTCHA_SOLVING,
CAPTCHA_SOLVED,
CAPTCHA_FAILED,
];
pub fn captcha_launch_args(model_path: Option<&str>) -> Vec<String> {
let mut args = vec![CAPTCHA_SOLVER_SWITCH.to_string()];
if let Some(dir) = model_path {
args.push(format!("{CAPTCHA_MODEL_PATH_SWITCH}={dir}"));
}
args
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SolverEvalParams<'a> {
pub expression: &'a str,
pub frame_url_contains: &'a str,
}
impl SolverEvalParams<'_> {
pub fn to_value(self) -> Value {
serde_json::json!({
"expression": self.expression,
"frameUrlContains": self.frame_url_contains,
})
}
}
pub fn solver_eval_params<'a>(
expression: &'a str,
frame_url_contains: &'a str,
) -> SolverEvalParams<'a> {
SolverEvalParams {
expression,
frame_url_contains,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum SolveMethod {
Audio,
Checkbox,
Slider,
#[serde(rename = "press-hold")]
PressHold,
#[serde(other)]
Other,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum CaptchaEvent {
Detected {
sitekey: String,
},
Solving {
sitekey: String,
method: Option<SolveMethod>,
},
Solved {
sitekey: String,
attempts: u32,
time_ms: f64,
},
Failed {
sitekey: String,
attempts: u32,
reason: String,
},
SolverEvalResult {
result: String,
},
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "camelCase")]
struct RawEvent {
#[serde(default)]
sitekey: String,
#[serde(default)]
method: Option<SolveMethod>,
#[serde(default)]
attempts: u32,
#[serde(default)]
time_ms: f64,
#[serde(default)]
reason: String,
#[serde(default)]
result: String,
}
impl CaptchaEvent {
pub fn parse(method: &str, params: &Value) -> Option<CaptchaEvent> {
let raw: RawEvent = serde_json::from_value(params.clone()).unwrap_or_default();
Some(match method {
CAPTCHA_DETECTED => CaptchaEvent::Detected {
sitekey: raw.sitekey,
},
CAPTCHA_SOLVING => CaptchaEvent::Solving {
sitekey: raw.sitekey,
method: raw.method,
},
CAPTCHA_SOLVED => CaptchaEvent::Solved {
sitekey: raw.sitekey,
attempts: raw.attempts,
time_ms: raw.time_ms,
},
CAPTCHA_FAILED => CaptchaEvent::Failed {
sitekey: raw.sitekey,
attempts: raw.attempts,
reason: raw.reason,
},
SOLVER_EVAL_RESULT => CaptchaEvent::SolverEvalResult { result: raw.result },
_ => return None,
})
}
pub fn sitekey(&self) -> Option<&str> {
match self {
CaptchaEvent::Detected { sitekey }
| CaptchaEvent::Solving { sitekey, .. }
| CaptchaEvent::Solved { sitekey, .. }
| CaptchaEvent::Failed { sitekey, .. } => Some(sitekey),
CaptchaEvent::SolverEvalResult { .. } => None,
}
}
pub fn is_terminal(&self) -> bool {
matches!(
self,
CaptchaEvent::Solved { .. } | CaptchaEvent::Failed { .. }
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn launch_args_stay_minimal_without_a_model_path() {
assert_eq!(captcha_launch_args(None), ["--captcha-solver"]);
assert_eq!(
captcha_launch_args(Some("/opt/models")),
["--captcha-solver", "--captcha-model-path=/opt/models"]
);
}
#[test]
fn events_parse_and_tolerate_drift() {
let solved = CaptchaEvent::parse(
CAPTCHA_SOLVED,
&serde_json::json!({"sitekey": "abc", "attempts": 2, "timeMs": 1234.5, "newField": 1}),
);
assert_eq!(
solved,
Some(CaptchaEvent::Solved {
sitekey: "abc".into(),
attempts: 2,
time_ms: 1234.5
})
);
for (wire, expected) in [
("audio", SolveMethod::Audio),
("checkbox", SolveMethod::Checkbox),
("slider", SolveMethod::Slider),
("press-hold", SolveMethod::PressHold),
("telepathy", SolveMethod::Other),
] {
let solving = CaptchaEvent::parse(
CAPTCHA_SOLVING,
&serde_json::json!({"sitekey": "abc", "method": wire}),
);
assert_eq!(
solving,
Some(CaptchaEvent::Solving {
sitekey: "abc".into(),
method: Some(expected)
}),
"method {wire:?}"
);
}
assert!(CaptchaEvent::parse("Page.loadEventFired", &serde_json::json!({})).is_none());
}
#[test]
fn solver_eval_params_are_camel_case_on_the_wire() {
let params = solver_eval_params("document.title", "");
assert_eq!(
params.to_value(),
serde_json::json!({"expression": "document.title", "frameUrlContains": ""})
);
assert_eq!(serde_json::to_value(params).unwrap(), params.to_value());
}
}