use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, Result, bail};
pub const HANDOFF_TIMEOUT: Duration = Duration::from_secs(5 * 60);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaptchaKind {
Recaptcha,
Turnstile,
Sitekey,
Generic,
}
impl CaptchaKind {
pub fn label(self) -> &'static str {
match self {
CaptchaKind::Recaptcha => "recaptcha",
CaptchaKind::Turnstile => "cf-turnstile",
CaptchaKind::Sitekey => "data-sitekey",
CaptchaKind::Generic => "captcha",
}
}
}
pub fn detect_captcha(html: &str) -> Option<CaptchaKind> {
let h = html.to_lowercase();
if h.contains("g-recaptcha") || h.contains("recaptcha") {
Some(CaptchaKind::Recaptcha)
} else if h.contains("cf-turnstile") || h.contains("turnstile") {
Some(CaptchaKind::Turnstile)
} else if h.contains("data-sitekey") {
Some(CaptchaKind::Sitekey)
} else if h.contains("captcha") {
Some(CaptchaKind::Generic)
} else {
None
}
}
pub fn open_in_browser(url: &str) {
for prog in ["xdg-open", "open"] {
if std::process::Command::new(prog)
.arg(url)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.is_ok()
{
return;
}
}
}
fn browser_matches(browser: Option<&str>, aliases: &[&str]) -> bool {
match browser {
None => true,
Some(b) => {
let b = b.to_lowercase();
if b == "auto" {
return true;
}
aliases.iter().any(|a| b.contains(a))
}
}
}
fn mtime_of(path: &Path) -> Option<std::time::SystemTime> {
std::fs::metadata(path).and_then(|m| m.modified()).ok()
}
pub fn cookie_candidates(browser: Option<&str>) -> Vec<PathBuf> {
let home = match dirs::home_dir() {
Some(h) => h,
None => return Vec::new(),
};
let mut tagged: Vec<(PathBuf, &'static str)> = Vec::new();
let ff_bases: &[(&str, &[&str])] = &[
(".mozilla/firefox", &["firefox"]),
(".librewolf", &["librewolf"]),
(".zen", &["zen"]),
(".waterwolf", &["waterfox"]),
(".waterfox", &["waterfox"]),
(".tor-browser", &["tor"]),
];
let gecko_group = ["gecko", "firefox-family", "mozilla"];
for (rel, tags) in ff_bases {
let mut aliases: Vec<&str> = tags.to_vec();
aliases.extend(gecko_group);
if !browser_matches(browser, &aliases) {
continue;
}
let base = home.join(rel);
if let Ok(rd) = std::fs::read_dir(&base) {
for e in rd.flatten() {
let p = e.path();
let name = p
.file_name()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
if p.is_dir() && (name.ends_with(".default") || name.contains("default")) {
tagged.push((p.join("cookies.sqlite"), tags[0]));
tagged.push((p.join("cookies.txt"), tags[0]));
}
}
}
}
let ch_roots: &[(&str, &'static str, &[&str])] = &[
("google-chrome", "chrome", &["chrome", "google", "chromium"]),
("chromium", "chromium", &["chromium", "chrome", "ungoogled"]),
("ungoogled-chromium", "chromium", &["ungoogled", "chromium"]),
(
"BraveSoftware/Brave-Browser",
"brave",
&["brave", "chromium"],
),
("microsoft-edge", "edge", &["edge", "microsoft", "chromium"]),
("opera", "opera", &["opera", "chromium"]),
("vivaldi", "vivaldi", &["vivaldi", "chromium"]),
("net.imput.helium", "helium", &["helium", "chromium"]),
("helium", "helium", &["helium", "chromium"]),
("arc", "arc", &["arc", "chromium"]),
("yandex", "yandex", &["yandex", "chromium"]),
];
let profiles = ["Default", "Profile 1", "Profile 2", ""];
for (root, tag, aliases) in ch_roots {
if !browser_matches(browser, aliases) {
continue;
}
for prof in profiles {
let dir = if prof.is_empty() {
home.join(".config").join(root)
} else {
home.join(".config").join(root).join(prof)
};
tagged.push((dir.join("Cookies"), tag));
tagged.push((dir.join("cookies.txt"), tag));
}
}
tagged.sort_by_key(|(p, _)| std::cmp::Reverse(mtime_of(p)));
tagged.into_iter().map(|(p, _)| p).collect()
}
pub fn parse_netscape_jar(text: &str) -> String {
let mut pairs = Vec::new();
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let cols: Vec<&str> = line.split('\t').collect();
if cols.len() >= 7 && !cols[5].is_empty() {
pairs.push(format!("{}={}", cols[5], cols[6]));
}
}
pairs.join("; ")
}
pub fn scan_cookie_tokens(bytes: &[u8]) -> String {
let text = String::from_utf8_lossy(bytes);
let mut pairs = Vec::new();
for tok in text.split(|c: char| c.is_whitespace() || matches!(c, ';' | '"' | '\'' | ',' | '\0'))
{
let tok = tok.trim().trim_matches(|c| c == '"' || c == '\'');
let Some((name, value)) = tok.split_once('=') else {
continue;
};
let name = name.trim();
let value = value.trim();
if !(2..=64).contains(&name.len()) || !(1..=512).contains(&value.len()) {
continue;
}
if !name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
{
continue;
}
if name.eq_ignore_ascii_case("expires") || name.eq_ignore_ascii_case("path") {
continue;
}
let pair = format!("{name}={value}");
if !pairs.contains(&pair) {
pairs.push(pair);
}
if pairs.len() >= 32 {
break;
}
}
pairs.join("; ")
}
pub fn cookies_from_file(path: &Path) -> Result<String> {
let bytes = std::fs::read(path).with_context(|| format!("cannot read {}", path.display()))?;
let text = String::from_utf8_lossy(&bytes);
if text
.lines()
.any(|l| l.starts_with("#HttpOnly") || l.split('\t').count() >= 7)
{
Ok(parse_netscape_jar(&text))
} else {
Ok(scan_cookie_tokens(&bytes))
}
}
pub fn load_session_cookies(browser: Option<&str>) -> Option<String> {
for cand in cookie_candidates(browser) {
if let Ok(header) = cookies_from_file(&cand)
&& !header.trim().is_empty()
{
return Some(header);
}
}
None
}
pub async fn wait_for_manual_solution<F>(timeout: Duration, mut poll: F) -> Result<String>
where
F: FnMut() -> Option<String>,
{
let start = std::time::Instant::now();
loop {
if let Some(s) = poll() {
let s = s.trim().to_string();
if !s.is_empty() {
return Ok(s);
}
}
if start.elapsed() >= timeout {
bail!("captcha: no solution within {}s", timeout.as_secs());
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
pub async fn wait_for_profile_cookies(browser: Option<&str>, timeout: Duration) -> Result<String> {
let b = browser.map(str::to_string);
wait_for_manual_solution(timeout, move || load_session_cookies(b.as_deref())).await
}
pub async fn download_with_cookies(
url: &str,
out_path: &Path,
cookies: &str,
expected_total: Option<u64>,
) -> Result<u64> {
if let Some(parent) = out_path.parent()
&& !parent.as_os_str().is_empty()
{
std::fs::create_dir_all(parent)
.with_context(|| format!("cannot create {}", parent.display()))?;
}
let client = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(10))
.build()
.context("cannot create HTTP client")?;
let total = match expected_total {
Some(t) => t,
None => probe_size_with_cookies(&client, url, cookies)
.await?
.with_context(|| format!("captcha: unknown size for {url}"))?,
};
loop {
let done = std::fs::metadata(out_path).map(|m| m.len()).unwrap_or(0);
if done >= total {
return Ok(done.min(total));
}
let end = (done + 8 * 1024 * 1024).min(total) - 1;
let resp = client
.get(url)
.header("Cookie", cookies)
.header(reqwest::header::RANGE, format!("bytes={done}-{end}"))
.header(reqwest::header::ACCEPT_ENCODING, "identity")
.send()
.await
.with_context(|| format!("captcha: GET {url} failed"))?;
let status = resp.status().as_u16();
if status == 401 || status == 403 {
bail!("captcha: session rejected (HTTP {status}) — solve again");
}
if status != 200 && status != 206 {
bail!("captcha: unexpected HTTP {status} for {url}");
}
let body = resp.bytes().await.context("captcha: cannot read body")?;
append_bytes(out_path, &body)?;
if status == 200 {
let len = std::fs::metadata(out_path).map(|m| m.len()).unwrap_or(0);
if len != total {
bail!("captcha: server ignored Range (got {len}, want {total})");
}
return Ok(len);
}
}
}
async fn probe_size_with_cookies(
client: &reqwest::Client,
url: &str,
cookies: &str,
) -> Result<Option<u64>> {
let resp = client
.get(url)
.header("Cookie", cookies)
.header(reqwest::header::RANGE, "bytes=0-0")
.header(reqwest::header::ACCEPT_ENCODING, "identity")
.send()
.await?;
if resp.status() == reqwest::StatusCode::PARTIAL_CONTENT
&& let Some(v) = resp.headers().get(reqwest::header::CONTENT_RANGE)
&& let Ok(s) = v.to_str()
&& let Some(total) = s
.rsplit('/')
.next()
.and_then(|t| t.trim().parse::<u64>().ok())
{
return Ok(Some(total));
}
Ok(resp
.headers()
.get(reqwest::header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.trim().parse::<u64>().ok()))
}
fn append_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
use std::io::Write;
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.with_context(|| format!("cannot write {}", path.display()))?;
f.write_all(bytes)
.with_context(|| format!("cannot write {}", path.display()))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_all_shapes() {
assert_eq!(
detect_captcha(r#"<div class="g-recaptcha" data-sitekey="abc"></div>"#),
Some(CaptchaKind::Recaptcha)
);
assert_eq!(
detect_captcha(r#"<div class="cf-turnstile" data-sitekey="x"></div>"#),
Some(CaptchaKind::Turnstile)
);
assert_eq!(
detect_captcha(r#"<div data-sitekey="abc">check</div>"#),
Some(CaptchaKind::Sitekey)
);
assert_eq!(
detect_captcha(r#"<html><body><div id="fake-captcha">solve me</div></body></html>"#),
Some(CaptchaKind::Generic)
);
assert_eq!(
detect_captcha("<html><body><a href=/f.bin>dl</a></body></html>"),
None
);
assert_eq!(detect_captcha("binary \x00\x01"), None);
}
#[test]
fn jar_parsing_joins_pairs() {
let jar = "# Netscape HTTP Cookie File\n.example.com\tTRUE\t/\tFALSE\t0\tsession\tabc123\n.example.com\tTRUE\t/\tFALSE\t0\tother\t1\n";
assert_eq!(parse_netscape_jar(jar), "session=abc123; other=1");
assert_eq!(parse_netscape_jar("# only comments\n"), "");
}
#[test]
fn token_scan_finds_session() {
let raw = b"SQLite format 3\x00moz_cookies\x00session=solved42\x00other noise";
let header = scan_cookie_tokens(raw);
assert!(header.contains("session=solved42"), "scan: {header}");
}
#[tokio::test]
async fn mock_captcha_then_session_takeover() {
use axum::response::IntoResponse;
let payload: Vec<u8> = (0..150_000u32).map(|i| (i % 251) as u8).collect();
let payload2 = payload.clone();
let app = axum::Router::new()
.route(
"/page",
axum::routing::get(|| async {
"<html><body><div id=\"fake-captcha\" data-sitekey=\"test-key\">solve me</div></body></html>"
}),
)
.route(
"/file",
axum::routing::get(move |headers: axum::http::HeaderMap| {
let payload = payload2.clone();
async move {
let cookie = headers
.get("cookie")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
if !cookie.contains("session=solved") {
return (
axum::http::StatusCode::FORBIDDEN,
"captcha required".to_string(),
)
.into_response();
}
let total = payload.len() as u64;
let range: Option<(u64, u64)> = headers
.get("range")
.and_then(|v| v.to_str().ok())
.and_then(|s| {
let s = s.strip_prefix("bytes=")?;
let (a, b) = s.split_once('-')?;
Some((a.parse().ok()?, b.parse().ok()?))
});
match range {
Some((from, to)) if from < total => {
let to = to.min(total - 1);
(
axum::http::StatusCode::PARTIAL_CONTENT,
[("content-range", format!("bytes {from}-{to}/{total}"))],
payload[from as usize..=to as usize].to_vec(),
)
.into_response()
}
_ => (axum::http::StatusCode::OK, payload).into_response(),
}
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
let base = format!("http://{addr}");
let client = reqwest::Client::new();
let html = client
.get(format!("{base}/page"))
.send()
.await
.unwrap()
.text()
.await
.unwrap();
assert_eq!(detect_captcha(&html), Some(CaptchaKind::Sitekey));
let denied = client.get(format!("{base}/file")).send().await.unwrap();
assert_eq!(denied.status().as_u16(), 403);
let dir = std::env::temp_dir().join(format!("xget-captcha-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let jar = dir.join("cookies.txt");
std::fs::write(&jar, "# Netscape HTTP Cookie File\n").unwrap();
let jar2 = jar.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(100)).await;
std::fs::write(
&jar2,
"# Netscape HTTP Cookie File\n.example.com\tTRUE\t/\tFALSE\t0\tsession\tsolved\n",
)
.unwrap();
});
let cookies = wait_for_manual_solution(Duration::from_secs(5), || {
cookies_from_file(&jar)
.ok()
.filter(|h| h.contains("session="))
})
.await
.unwrap();
assert!(cookies.contains("session=solved"));
let out = dir.join("f.bin");
let n = download_with_cookies(
&format!("{base}/file"),
&out,
&cookies,
Some(payload.len() as u64),
)
.await
.unwrap();
assert_eq!(n, payload.len() as u64);
assert_eq!(std::fs::read(&out).unwrap(), payload);
let pasted = wait_for_manual_solution(Duration::from_secs(2), || {
Some(format!("{base}/file").replace("http://", "http://"))
})
.await
.unwrap();
assert!(pasted.starts_with("http://"));
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn handoff_timeout_is_readable() {
let err = wait_for_manual_solution(Duration::from_millis(600), || None)
.await
.unwrap_err();
assert!(err.to_string().contains("no solution"), "timeout: {err}");
}
}