Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

CAPTCHA hand-off backend: pointer drags, captcha probe with box, auto-resolve and time-out

Lin (kwant bot)df4643472316
diff --git a/src/db/human_steps.rs b/src/db/human_steps.rs
index dbcb7b5c..db9139aa 100644
--- a/src/db/human_steps.rs
+++ b/src/db/human_steps.rs
@@ -1,6 +1,7 @@
//! Steps only the person can do in the bot browser (`request_human_step`): sign in, solve a
//! CAPTCHA, or something else. A step is `open` until the person marks it done or declines it,
-//! or its turn is stopped (`cancelled`).
+//! or its turn is stopped (`cancelled`). A CAPTCHA step also closes by itself when the check
+//! is gone from the page (`resolved_auto`) or nobody solved it in time (`timed_out`).
use super::models::{Message, MessageExtra, NewMessage};
use super::{Database, DbError};
@@ -15,8 +16,9 @@ pub const MAX_URL_CHARS: usize = 300;
pub const MAX_OPEN_PER_KWANT: i64 = 5;
pub const HUMAN_STEP_KINDS: [&str; 4] = ["sign_in", "captcha", "two_factor", "other"];
-/// "open", "done", "declined" or "cancelled" (its turn was stopped).
-pub const HUMAN_STEP_STATUSES: [&str; 4] = ["open", "done", "declined", "cancelled"];
+/// "open", "done", "declined", "cancelled" (its turn was stopped), "resolved_auto" (the
+/// CAPTCHA went away on its own or the person solved it without pressing Done) or "timed_out".
+pub const HUMAN_STEP_STATUSES: [&str; 6] = ["open", "done", "declined", "cancelled", "resolved_auto", "timed_out"];
#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
pub struct HumanStep {
@@ -33,6 +35,10 @@ pub struct HumanStep {
pub url: Option<String>,
/// The bot browser it happens in (team, channel or kwant id).
pub sandbox_target: Option<String>,
+ /// CAPTCHA steps: where the widget is, `{kind, x, y, width, height}` in viewport pixels,
+ /// kept as JSON text and sent as an object.
+ #[serde(serialize_with = "target_object")]
+ pub target: Option<String>,
/// "bot" (the agent asked) or "auto" (kwnt saw a CAPTCHA).
pub source: String,
pub status: String,
@@ -42,6 +48,11 @@ pub struct HumanStep {
pub closed_at: Option<DateTime<Utc>>,
}
+fn target_object<S: serde::Serializer>(target: &Option<String>, s: S) -> Result<S::Ok, S::Error> {
+ use serde::Serialize as _;
+ target.as_deref().and_then(|t| serde_json::from_str::<serde_json::Value>(t).ok()).serialize(s)
+}
+
impl HumanStep {
/// The chat id the step was asked in: channel, thread or the direct chat's kwant.
pub fn context_id(&self) -> String {
@@ -124,42 +135,60 @@ pub struct HumanStepPlace {
/// A new step (with `true`), or the turn's step that is already open (with `false`).
pub type Created = (HumanStep, bool, Option<Message>);
+const CREATE_HUMAN_STEPS: &str = "CREATE TABLE IF NOT EXISTS human_steps (
+ id TEXT PRIMARY KEY,
+ kwant_id TEXT NOT NULL,
+ channel_id TEXT,
+ direct_kwant_id TEXT,
+ thread_id TEXT,
+ turn_id TEXT,
+ kind TEXT NOT NULL CHECK (kind IN ('sign_in', 'captcha', 'two_factor', 'other')),
+ reason TEXT NOT NULL,
+ url TEXT,
+ sandbox_target TEXT,
+ target TEXT,
+ source TEXT NOT NULL CHECK (source IN ('bot', 'auto')),
+ status TEXT NOT NULL CHECK (status IN ('open', 'done', 'declined', 'cancelled', 'resolved_auto', 'timed_out')),
+ message_id TEXT,
+ created_at TIMESTAMP NOT NULL,
+ closed_at TIMESTAMP
+)";
+
impl Database {
pub(super) async fn migrate_human_steps(&self) -> Result<(), DbError> {
- for stmt in [
- "CREATE TABLE IF NOT EXISTS human_steps (
- id TEXT PRIMARY KEY,
- kwant_id TEXT NOT NULL,
- channel_id TEXT,
- direct_kwant_id TEXT,
- thread_id TEXT,
- turn_id TEXT,
- kind TEXT NOT NULL CHECK (kind IN ('sign_in', 'captcha', 'two_factor', 'other')),
- reason TEXT NOT NULL,
- url TEXT,
- sandbox_target TEXT,
- source TEXT NOT NULL CHECK (source IN ('bot', 'auto')),
- status TEXT NOT NULL CHECK (status IN ('open', 'done', 'declined', 'cancelled')),
- message_id TEXT,
- created_at TIMESTAMP NOT NULL,
- closed_at TIMESTAMP
- )",
- "CREATE INDEX IF NOT EXISTS human_steps_by_status ON human_steps (status, kwant_id)",
- ] {
- sqlx::query(stmt).execute(&self.pool).await?;
+ sqlx::query(CREATE_HUMAN_STEPS).execute(&self.pool).await?;
+ // Tables made before CAPTCHA auto-resolve lack `target` and the two new statuses, which
+ // a CHECK can't gain in place: rebuild them once
+ let sql: Option<(String,)> = sqlx::query_as("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'human_steps'")
+ .fetch_optional(&self.pool)
+ .await?;
+ if sql.is_some_and(|(sql,)| !sql.contains("'timed_out'")) {
+ let columns = "id, kwant_id, channel_id, direct_kwant_id, thread_id, turn_id, kind, reason, url, sandbox_target, source, status, message_id, created_at, closed_at";
+ let mut tx = self.pool.begin().await?;
+ sqlx::query("DROP INDEX IF EXISTS human_steps_by_status").execute(&mut *tx).await?;
+ sqlx::query("ALTER TABLE human_steps RENAME TO human_steps_old").execute(&mut *tx).await?;
+ sqlx::query(CREATE_HUMAN_STEPS).execute(&mut *tx).await?;
+ sqlx::query(&format!("INSERT INTO human_steps ({columns}) SELECT {columns} FROM human_steps_old"))
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("DROP TABLE human_steps_old").execute(&mut *tx).await?;
+ tx.commit().await?;
}
+ sqlx::query("CREATE INDEX IF NOT EXISTS human_steps_by_status ON human_steps (status, kwant_id)").execute(&self.pool).await?;
Ok(())
}
/// Saves a step together with the chat message that shows it (built by `card`), in one
/// transaction. A turn that asks again while its step is open gets that step back, so a
/// retrying agent (or the CAPTCHA check firing on every page) doesn't pile up cards.
+ #[allow(clippy::too_many_arguments)]
pub async fn create_human_step_with_card(
&self,
place: &HumanStepPlace,
kind: &str,
reason: &str,
url: Option<&str>,
+ target: Option<&str>,
source: &str,
card: impl FnOnce(&HumanStep) -> Option<(NewMessage, MessageExtra)>,
) -> Result<Created, HumanStepError> {
@@ -168,8 +197,8 @@ impl Database {
// Writes first so the transaction holds SQLite's write lock before it reads
let id = Uuid::new_v4().to_string();
let inserted = sqlx::query(
- "INSERT INTO human_steps (id, kwant_id, channel_id, direct_kwant_id, thread_id, turn_id, kind, reason, url, sandbox_target, source, status, created_at)
- SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 'open', ?12
+ "INSERT INTO human_steps (id, kwant_id, channel_id, direct_kwant_id, thread_id, turn_id, kind, reason, url, sandbox_target, source, status, created_at, target)
+ SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 'open', ?12, ?14
WHERE (SELECT COUNT(*) FROM human_steps WHERE kwant_id = ?2 AND status = 'open') < ?13
AND NOT EXISTS (SELECT 1 FROM human_steps WHERE status = 'open' AND ?6 IS NOT NULL AND turn_id = ?6)",
)
@@ -186,6 +215,7 @@ impl Database {
.bind(source)
.bind(Utc::now())
.bind(MAX_OPEN_PER_KWANT)
+ .bind(target)
.execute(&mut *tx)
.await?;
if inserted.rows_affected() == 0 {
@@ -262,6 +292,17 @@ impl Database {
Ok(n > 0)
}
+ /// Moves an open step's CAPTCHA box (the widget showed up, or moved).
+ pub async fn set_human_step_target(&self, id: &str, target: &str) -> Result<bool, DbError> {
+ let done = sqlx::query("UPDATE human_steps SET target = ? WHERE id = ? AND status = 'open' AND target IS NOT ?")
+ .bind(target)
+ .bind(id)
+ .bind(target)
+ .execute(&self.pool)
+ .await?;
+ Ok(done.rows_affected() == 1)
+ }
+
/// Closes an open step; `false` when it wasn't open any more (someone else closed it).
pub async fn close_human_step(&self, id: &str, status: &str) -> Result<bool, DbError> {
let done = sqlx::query("UPDATE human_steps SET status = ?, closed_at = ? WHERE id = ? AND status = 'open'")
@@ -302,11 +343,11 @@ mod tests {
sandbox_target: Some("k".into()),
..Default::default()
};
- let (s, new, _) = db.create_human_step_with_card(&place("t1"), "sign_in", "Log in", None, "bot", |_| None).await.unwrap();
+ let (s, new, _) = db.create_human_step_with_card(&place("t1"), "sign_in", "Log in", None, None, "bot", |_| None).await.unwrap();
assert!(new);
assert_eq!(s.context_id(), "k");
assert!(db.human_step_open_in("k").await.unwrap());
- let (again, new, _) = db.create_human_step_with_card(&place("t1"), "captcha", "Solve", None, "auto", |_| None).await.unwrap();
+ let (again, new, _) = db.create_human_step_with_card(&place("t1"), "captcha", "Solve", None, None, "auto", |_| None).await.unwrap();
assert!(!new);
assert_eq!(again.id, s.id);
assert_eq!(db.open_human_steps_for_turn("t1").await.unwrap().len(), 1);
@@ -317,10 +358,41 @@ mod tests {
assert!(closed.closed_at.is_some());
assert!(!db.human_step_open_in("k").await.unwrap());
for i in 0..MAX_OPEN_PER_KWANT {
- db.create_human_step_with_card(&place(&format!("t{}", i + 10)), "other", "Do it", None, "bot", |_| None).await.unwrap();
+ db.create_human_step_with_card(&place(&format!("t{}", i + 10)), "other", "Do it", None, None, "bot", |_| None).await.unwrap();
}
- let full = db.create_human_step_with_card(&place("t99"), "other", "Do it", None, "bot", |_| None).await;
+ let full = db.create_human_step_with_card(&place("t99"), "other", "Do it", None, None, "bot", |_| None).await;
assert_eq!(full.err(), Some(HumanStepError::TooManyOpen));
assert_eq!(db.list_human_steps(Some("open"), Some("k"), None).await.unwrap().len() as i64, MAX_OPEN_PER_KWANT);
}
+
+ #[tokio::test]
+ async fn old_tables_gain_target_and_the_auto_statuses_and_keep_their_rows() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ // Recreate the table as it was before CAPTCHA auto-resolve, with one row
+ sqlx::query("DROP TABLE human_steps").execute(&db.pool).await.unwrap();
+ sqlx::query(
+ "CREATE TABLE human_steps (id TEXT PRIMARY KEY, kwant_id TEXT NOT NULL, channel_id TEXT, direct_kwant_id TEXT,
+ thread_id TEXT, turn_id TEXT, kind TEXT NOT NULL CHECK (kind IN ('sign_in', 'captcha', 'two_factor', 'other')),
+ reason TEXT NOT NULL, url TEXT, sandbox_target TEXT, source TEXT NOT NULL CHECK (source IN ('bot', 'auto')),
+ status TEXT NOT NULL CHECK (status IN ('open', 'done', 'declined', 'cancelled')), message_id TEXT,
+ created_at TIMESTAMP NOT NULL, closed_at TIMESTAMP)",
+ ).execute(&db.pool).await.unwrap();
+ sqlx::query("INSERT INTO human_steps (id, kwant_id, kind, reason, source, status, created_at) VALUES ('old', 'k', 'captcha', 'Solve', 'auto', 'open', ?)")
+ .bind(Utc::now()).execute(&db.pool).await.unwrap();
+ db.migrate_human_steps().await.unwrap();
+ db.migrate_human_steps().await.unwrap();
+ let old = db.get_human_step("old").await.unwrap().unwrap();
+ assert_eq!((old.status.as_str(), old.target), ("open", None));
+ assert!(db.set_human_step_target("old", r#"{"kind":"tiktok","x":1,"y":2,"width":30,"height":40}"#).await.unwrap());
+ assert!(db.close_human_step("old", "resolved_auto").await.unwrap());
+ let json = serde_json::to_value(db.get_human_step("old").await.unwrap().unwrap()).unwrap();
+ assert_eq!(json["status"], "resolved_auto");
+ assert_eq!(json["target"]["kind"], "tiktok");
+ assert_eq!(json["target"]["width"], 30);
+ let place = HumanStepPlace { kwant_id: "k".into(), turn_id: Some("t".into()), ..Default::default() };
+ let (s, ..) = db.create_human_step_with_card(&place, "captcha", "Solve", None, None, "auto", |_| None).await.unwrap();
+ assert!(db.close_human_step(&s.id, "timed_out").await.unwrap());
+ assert!(serde_json::to_value(db.get_human_step(&s.id).await.unwrap().unwrap()).unwrap()["target"].is_null());
+ }
}
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index 338d363f..477885d5 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -376,7 +376,8 @@ impl TurnInput {
format!("http://127.0.0.1:{}/api/sandbox/{}", crate::config::DEFAULT_PORT, sandbox_target)
});
let control_rules = "A 409 / \"taken control\" answer means the user is using the browser: stop browser actions and wait for the user to hand it back. Never bypass the control API or connect to CDP directly.\n\
- Report browser errors honestly. Never claim a page opened unless navigation succeeded, and only describe content that appears in the returned page text. If a response has \"blocked\": true (CAPTCHA / bot check), follow its \"notice\" instead of claiming results.";
+ Report browser errors honestly. Never claim a page opened unless navigation succeeded, and only describe content that appears in the returned page text. If a response has \"blocked\": true (CAPTCHA / bot check), follow its \"notice\" instead of claiming results.\n\
+ On a CAPTCHA, stop and wait for the person to solve it: never try to solve, bypass or click through it yourself. Prefer sites you are already signed in to and official APIs over scraping pages that challenge bots.";
let browser_block = match browser {
BrowserAccess::Tools => format!(
"\n\n[Bot Browser]\n\
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index 19012118..a2338a60 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -142,6 +142,215 @@ pub fn detect_bot_wall(url: &str, title: &str, text: &str) -> Option<&'static st
None
}
+fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
+ use std::io::Write;
+ if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; }
+ let tmp = path.with_extension("tmp");
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); }
+ let mut file = options.open(&tmp)?;
+ file.write_all(bytes)?;
+ file.sync_all()?;
+ std::fs::rename(&tmp, path)
+}
+
+/// Finds a visible CAPTCHA widget in the page (document, open shadow roots and same-origin
+/// frames) and returns `{kind, x, y, width, height}` in viewport pixels, or null. Scrolls an
+/// off-screen widget into view first so the person sees it in the live view.
+pub const CAPTCHA_PROBE_JS: &str = r##"(function () {
+ var VENDORS = [
+ ['recaptcha', /(^|\.)google\.com\/recaptcha\/|recaptcha\.net\/recaptcha\//i],
+ ['hcaptcha', /(^|\/\/|\.)hcaptcha\.com\//i],
+ ['turnstile', /challenges\.cloudflare\.com\//i],
+ ['arkose', /arkoselabs\.com|funcaptcha\.com/i],
+ ['datadome', /captcha-delivery\.com/i],
+ ['geetest', /geetest\.com/i]
+ ];
+ var SELECTORS = [
+ ['geetest', '.geetest_panel, .geetest_box, .geetest_holder, .geetest_widget, .geetest_captcha'],
+ ['arkose', '#FunCaptcha, #arkose, [data-e2e="enforcement-frame"]'],
+ ['perimeterx', '#px-captcha'],
+ ['datadome', '#ddv1-captcha-container, .captcha__human'],
+ ['tiktok', '#captcha_container, #captcha-verify-container-main-page, .captcha_verify_container, .captcha-verify-container, [class*="captcha_verify"], [class*="captcha-verify"], [id^="tiktok-verify"]']
+ ];
+ var PHRASES = /drag the slider|drag the puzzle piece|slide to complete the puzzle|drag the puzzle|slide to verify|select all images with|press (and|&) hold/i;
+ var vw = window.innerWidth, vh = window.innerHeight;
+ function visible(el, rect) {
+ if (rect.width < 30 || rect.height < 30) return false;
+ var st = getComputedStyle(el);
+ return st.display !== 'none' && st.visibility !== 'hidden' && parseFloat(st.opacity || '1') > 0.05;
+ }
+ function frameOffset(win) {
+ var x = 0, y = 0;
+ try {
+ while (win && win !== window && win.frameElement) {
+ var r = win.frameElement.getBoundingClientRect();
+ x += r.left; y += r.top; win = win.parent;
+ }
+ } catch (e) {}
+ return [x, y];
+ }
+ function box(kind, el) {
+ var r = el.getBoundingClientRect();
+ if (!visible(el, r)) return null;
+ var off = frameOffset(el.ownerDocument.defaultView);
+ var left = r.left + off[0], top = r.top + off[1];
+ if (top + r.height <= 0 || top >= vh || left + r.width <= 0 || left >= vw) {
+ try { el.scrollIntoView({block: 'center', inline: 'center'}); } catch (e) {}
+ r = el.getBoundingClientRect(); off = frameOffset(el.ownerDocument.defaultView);
+ left = r.left + off[0]; top = r.top + off[1];
+ }
+ var x = Math.max(0, left), y = Math.max(0, top);
+ var w = Math.min(vw, left + r.width) - x, h = Math.min(vh, top + r.height) - y;
+ if (w < 10 || h < 10) return null;
+ return {kind: kind, x: Math.round(x), y: Math.round(y), width: Math.round(w), height: Math.round(h)};
+ }
+ function container(el) {
+ for (var n = el, i = 0; n && i < 12; i++) {
+ if (n.nodeType === 1) {
+ var tag = ((n.id || '') + ' ' + (typeof n.className === 'string' ? n.className : '')).toLowerCase();
+ if (/captcha|verify|challenge/.test(tag)) return n;
+ if (n.getAttribute('role') === 'dialog' || n.getAttribute('aria-modal') === 'true') return n;
+ var pos = getComputedStyle(n).position;
+ if ((pos === 'fixed' || pos === 'sticky') && n !== n.ownerDocument.body) return n;
+ }
+ n = n.parentNode || n.host;
+ }
+ return null;
+ }
+ var roots = [];
+ function collect(root, depth) {
+ if (!root || depth > 6) return;
+ roots.push(root);
+ var all = root.querySelectorAll('*');
+ for (var i = 0; i < all.length; i++) {
+ var el = all[i];
+ if (el.shadowRoot) collect(el.shadowRoot, depth + 1);
+ if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
+ try { if (el.contentDocument) collect(el.contentDocument, depth + 1); } catch (e) {}
+ }
+ }
+ }
+ collect(document, 0);
+ var found = null;
+ for (var ri = 0; ri < roots.length && !found; ri++) {
+ var frames = roots[ri].querySelectorAll('iframe');
+ for (var f = 0; f < frames.length && !found; f++) {
+ var src = frames[f].getAttribute('src') || '';
+ if (frames[f].closest && frames[f].closest('.grecaptcha-badge')) continue;
+ if (/recaptcha\/(api2|enterprise)\/anchor.*[?&]size=invisible/i.test(src)) continue;
+ for (var v = 0; v < VENDORS.length; v++) {
+ if (VENDORS[v][1].test(src)) { found = box(VENDORS[v][0], frames[f]); break; }
+ }
+ }
+ }
+ for (var ri2 = 0; ri2 < roots.length && !found; ri2++) {
+ for (var s = 0; s < SELECTORS.length && !found; s++) {
+ var els = roots[ri2].querySelectorAll(SELECTORS[s][1]);
+ for (var e = 0; e < els.length && !found; e++) found = box(SELECTORS[s][0], els[e]);
+ }
+ }
+ for (var ri3 = 0; ri3 < roots.length && !found; ri3++) {
+ var root = roots[ri3];
+ var walker = (root.ownerDocument || root).createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ var node;
+ while (!found && (node = walker.nextNode())) {
+ if (!PHRASES.test(node.nodeValue || '')) continue;
+ var c = container(node.parentNode);
+ if (c) found = box(/tiktok/i.test(location.hostname) ? 'tiktok' : 'puzzle', c);
+ }
+ }
+ return found;
+})()"##;
+
+pub const CAPTCHA_KINDS: &[&str] = &["recaptcha", "hcaptcha", "turnstile", "arkose", "geetest", "datadome", "perimeterx", "tiktok", "puzzle"];
+
+/// Where a CAPTCHA widget sits in the viewport, so the person's view can point at it.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct CaptchaHit {
+ pub kind: String,
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
+
+impl CaptchaHit {
+ /// Validates what the page returned: a known kind and a finite box inside the viewport.
+ pub fn parse(value: &Value) -> Option<Self> {
+ let kind = value.get("kind")?.as_str()?;
+ if !CAPTCHA_KINDS.contains(&kind) { return None; }
+ let num = |k: &str| value.get(k).and_then(Value::as_f64).filter(|n| n.is_finite());
+ let (x, y) = (num("x")?.clamp(0.0, 1280.0), num("y")?.clamp(0.0, 800.0));
+ let width = num("width")?.clamp(0.0, 1280.0 - x);
+ let height = num("height")?.clamp(0.0, 800.0 - y);
+ if width < 1.0 || height < 1.0 { return None; }
+ Some(Self { kind: kind.to_string(), x, y, width, height })
+ }
+
+ pub fn label(&self) -> &'static str {
+ match self.kind.as_str() {
+ "recaptcha" => "reCAPTCHA",
+ "hcaptcha" => "hCaptcha",
+ "turnstile" => "Cloudflare Turnstile check",
+ "arkose" => "Arkose (FunCaptcha) puzzle",
+ "geetest" => "GeeTest puzzle",
+ "datadome" => "DataDome check",
+ "perimeterx" => "PerimeterX press-and-hold check",
+ "tiktok" => "TikTok slider puzzle",
+ _ => "slider / puzzle CAPTCHA",
+ }
+ }
+}
+
+/// Clicks only "reject" / "decline optional" in known cookie banners (OneTrust, Cookiebot,
+/// Didomi, Usercentrics, Quantcast, Google, TikTok) and in containers that are clearly a
+/// consent banner. Never accepts. Returns the clicked label or null.
+pub const CONSENT_REJECT_JS: &str = r##"(function () {
+ var KNOWN = ['#onetrust-reject-all-handler', '#CybotCookiebotDialogBodyButtonDecline',
+ '#didomi-notice-disagree-button', '[data-testid="uc-deny-all-button"]',
+ '.qc-cmp2-summary-buttons button[mode="secondary"]', '#truste-consent-required',
+ '.cmpboxbtnno', '#cmpwelcomebtnno a', '.fc-cta-do-not-consent', 'button#W0wltc'];
+ var REJECT = /^\s*(reject( all| optional)?( cookies)?|decline( all| optional)?( cookies)?|deny( all)?|refuse( all)?|only (necessary|essential|required)( cookies)?|use necessary cookies only|necessary cookies only|continue without accepting|alle ablehnen|ablehnen|tout refuser|refuser|rechazar( todo)?|rifiuta( tutto)?|weiger(en)?|odrzuć|відхилити|отклонить)\s*$/i;
+ var ACCEPT = /accept|allow|agree|consent|got it|^\s*ok\s*$|akzept|accepter|aceptar|accetta|zustimmen/i;
+ var NEGATED = /\b(not|don't|reject|decline|deny|refuse|necessary|essential|required)\b|ablehnen|refuser|rechazar|rifiuta/i;
+ var BANNER = /cookie|consent|gdpr|cmp|privacy|onetrust|didomi|usercentrics|cookiebot|qc-cmp|truste/i;
+ function label(el) { return (el.innerText || el.textContent || el.getAttribute('aria-label') || el.value || '').replace(/\s+/g, ' ').trim(); }
+ function shown(el) { var r = el.getBoundingClientRect(); var st = getComputedStyle(el); return r.width > 0 && r.height > 0 && st.visibility !== 'hidden' && st.display !== 'none'; }
+ function click(el) { var l = label(el); if (ACCEPT.test(l) && !NEGATED.test(l)) return null; el.click(); return l || 'reject'; }
+ var roots = [];
+ (function collect(root, d) { if (!root || d > 4) return; roots.push(root);
+ var all = root.querySelectorAll('*');
+ for (var i = 0; i < all.length; i++) { if (all[i].shadowRoot) collect(all[i].shadowRoot, d + 1);
+ if (all[i].tagName === 'IFRAME') { try { if (all[i].contentDocument) collect(all[i].contentDocument, d + 1); } catch (e) {} } }
+ })(document, 0);
+ for (var r = 0; r < roots.length; r++) {
+ for (var k = 0; k < KNOWN.length; k++) {
+ var el = roots[r].querySelector(KNOWN[k]);
+ if (el && shown(el)) { var c = click(el); if (c) return c; }
+ }
+ }
+ for (var r2 = 0; r2 < roots.length; r2++) {
+ var host = roots[r2].host;
+ var buttons = roots[r2].querySelectorAll('button, [role="button"], a[href="#"], input[type="button"]');
+ for (var b = 0; b < buttons.length; b++) {
+ var btn = buttons[b], text = label(btn);
+ if (!REJECT.test(text) || !shown(btn)) continue;
+ var inBanner = false;
+ for (var n = btn, i = 0; n && i < 10; i++, n = n.parentNode || n.host) {
+ if (n.nodeType !== 1) continue;
+ var tag = (n.id || '') + ' ' + (typeof n.className === 'string' ? n.className : '') + ' ' + (n.getAttribute('aria-label') || '') + ' ' + n.tagName;
+ if (BANNER.test(tag)) { inBanner = true; break; }
+ }
+ if (!inBanner && host) inBanner = BANNER.test(host.tagName + ' ' + (host.id || '') + ' ' + (host.className || ''));
+ if (inBanner) { btn.click(); return text; }
+ }
+ }
+ return null;
+})()"##;
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NavigationResult {
pub url: String,
@@ -260,6 +469,10 @@ pub struct BrowserController {
/// Held while a human step (sign in, CAPTCHA) waits on the person: bot actions get
/// `HumanControl` and the person's live-view input goes through without taking control.
held_for_person: Arc<std::sync::Mutex<Option<OwnedRwLockWriteGuard<()>>>>,
+ /// Where the left button is held down from live-view pointer input, if it is.
+ pointer_held: Arc<std::sync::Mutex<Option<(f64, f64)>>>,
+ /// VM mode: this bot's cookies, saved outside the throwaway browser context.
+ cookie_jar: Arc<std::sync::Mutex<Option<std::path::PathBuf>>>,
}
impl std::fmt::Debug for BrowserController {
@@ -287,6 +500,8 @@ impl BrowserController {
browser_level: false,
control: Arc::new(RwLock::new(())),
held_for_person: Arc::default(),
+ pointer_held: Arc::default(),
+ cookie_jar: Arc::default(),
}
}
@@ -330,6 +545,8 @@ impl BrowserController {
pub fn is_managed_session(&self) -> bool { self.target_id.is_some() }
+ pub(crate) fn pointer_held_slot(&self) -> &std::sync::Mutex<Option<(f64, f64)>> { &self.pointer_held }
+
pub async fn refresh_location(&self) -> Result<(), BrowserError> {
let result = self.send_cdp_command("Runtime.evaluate", json!({
"expression": "({url: location.href, title: document.title})", "returnByValue": true
@@ -568,7 +785,14 @@ impl BrowserController {
pub async fn navigate(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {
let _permit = self.control.try_read().map_err(|_| BrowserError::HumanControl)?;
- self.navigate_unlocked(target_url).await
+ let result = self.navigate_unlocked(target_url).await?;
+ // Bot navigation only: the person decides banners themselves in the live view
+ if let Some(clicked) = self.reject_consent().await {
+ tracing::debug!("Declined cookie banner via \"{}\"", clicked);
+ let _ = self.capture_screenshot().await;
+ }
+ self.persist_cookies().await;
+ Ok(result)
}
pub async fn navigate_unlocked(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {
@@ -697,6 +921,76 @@ impl BrowserController {
Ok(())
}
+ /// A visible CAPTCHA widget on the page, if any. `Err` when the page couldn't be read
+ /// (mid-navigation, say): callers treat that as unknown, never as "gone".
+ pub async fn probe_captcha(&self) -> Result<Option<CaptchaHit>, BrowserError> {
+ let res = self.send_cdp_command("Runtime.evaluate", json!({
+ "expression": CAPTCHA_PROBE_JS, "returnByValue": true
+ })).await?;
+ if res.get("exceptionDetails").is_some() {
+ return Err(BrowserError::Protocol("CAPTCHA probe failed".into()));
+ }
+ Ok(CaptchaHit::parse(&res["result"]["value"]))
+ }
+
+ /// Declines optional cookies on a known consent banner. Never accepts.
+ pub async fn reject_consent(&self) -> Option<String> {
+ // Consent managers often render a moment after load: look twice
+ for attempt in 0..2 {
+ if attempt > 0 { tokio::time::sleep(Duration::from_millis(700)).await; }
+ let Ok(res) = self.send_cdp_command("Runtime.evaluate", json!({
+ "expression": CONSENT_REJECT_JS, "returnByValue": true
+ })).await else { return None };
+ if let Some(label) = res["result"]["value"].as_str() {
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ return Some(label.chars().take(80).collect());
+ }
+ }
+ None
+ }
+
+ /// VM mode keeps cookies in a file because the browser's profile lives on tmpfs.
+ pub fn set_cookie_jar(&self, path: Option<std::path::PathBuf>) {
+ *self.cookie_jar.lock().unwrap_or_else(|e| e.into_inner()) = path;
+ }
+
+ fn cookie_jar_path(&self) -> Option<std::path::PathBuf> {
+ self.cookie_jar.lock().unwrap_or_else(|e| e.into_inner()).clone()
+ }
+
+ /// Saves this page's browser-context cookies to the jar (owner-only file, written atomically).
+ pub async fn persist_cookies(&self) {
+ let Some(path) = self.cookie_jar_path() else { return };
+ let Ok(res) = self.send_cdp_command("Network.getAllCookies", json!({})).await else { return };
+ let Some(cookies) = res["cookies"].as_array() else { return };
+ // session cookies die with the browser anyway; keep only persistent ones
+ let kept: Vec<&Value> = cookies.iter().filter(|c| c["session"].as_bool() != Some(true)).collect();
+ if let Err(error) = write_private(&path, &serde_json::to_vec(&kept).unwrap_or_default()) {
+ tracing::warn!("Could not save browser cookies: {}", error);
+ }
+ }
+
+ /// Loads the jar into a fresh browser context. Returns how many cookies were restored.
+ pub async fn restore_cookies(&self) -> usize {
+ let Some(path) = self.cookie_jar_path() else { return 0 };
+ let Ok(bytes) = std::fs::read(&path) else { return 0 };
+ let Ok(Value::Array(cookies)) = serde_json::from_slice::<Value>(&bytes) else { return 0 };
+ let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0);
+ let params: Vec<Value> = cookies.iter().filter(|c| c["expires"].as_f64().is_some_and(|e| e > now)).map(|c| {
+ let mut p = json!({});
+ for key in ["name", "value", "domain", "path", "secure", "httpOnly", "sameSite", "expires", "priority", "sameParty", "sourceScheme", "partitionKey"] {
+ if let Some(v) = c.get(key) { if !v.is_null() { p[key] = v.clone(); } }
+ }
+ p
+ }).collect();
+ if params.is_empty() { return 0; }
+ let count = params.len();
+ match self.send_cdp_command("Network.setCookies", json!({"cookies": params})).await {
+ Ok(_) => count,
+ Err(error) => { tracing::warn!("Could not restore browser cookies: {}", error); 0 }
+ }
+ }
+
/// Re-reads the page's real URL and title, since user clicks/keys can navigate
/// without going through `navigate()`.
pub async fn sync_location(&self) -> Option<(String, String)> {
diff --git a/src/sandbox/service.rs b/src/sandbox/service.rs
index 301a0fe7..50f286a2 100644
--- a/src/sandbox/service.rs
+++ b/src/sandbox/service.rs
@@ -286,6 +286,7 @@ impl BrowserService {
let existing = state.sessions.get(id).filter(|session| targets["targetInfos"].as_array()
.is_some_and(|targets| targets.iter().any(|target| target["targetId"] == session.target)));
let local = self.mode() == ComputerMode::Local;
+ let fresh_context = existing.is_none() && !local;
let session = if let Some(existing) = existing { existing.clone() } else if local {
// Local pages share the kwant profile's default context, so a sign-in in the window
// is kept. (`context` stays empty.) Each bot gets its own window, not a tab: Chrome
@@ -314,6 +315,16 @@ impl BrowserService {
state.sessions.insert(id.to_string(), session.clone());
self.save_sessions(&state.sessions).await?;
let ctrl = BrowserController::at_endpoint(&state.endpoint, Some(session.target), false);
+ if !local {
+ // The VM browser's profile is on tmpfs, so its contexts' cookies go when the
+ // container restarts: keep them per bot in the data folder (local mode's on-disk
+ // profile already keeps them).
+ ctrl.set_cookie_jar(Some(self.cookie_jar(id)));
+ if fresh_context {
+ let restored = ctrl.restore_cookies().await;
+ if restored > 0 { tracing::debug!("Restored {} browser cookies for {}", restored, id); }
+ }
+ }
// A real window keeps its own size; a windowless browser gets the viewer's fixed viewport.
if !local || !self.local_window() {
ctrl.send_cdp_command("Emulation.setDeviceMetricsOverride", json!({
@@ -324,7 +335,15 @@ impl BrowserService {
Ok(ctrl)
}
+ /// Where a bot's VM-browser cookies are kept between container restarts.
+ pub fn cookie_jar(&self, id: &str) -> PathBuf {
+ let name: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).take(120).collect();
+ self.root.join("browser-cookies").join(format!("{name}.json"))
+ }
+
pub async fn reset(&self, id: &str) -> Result<(), BrowserError> {
+ // A reset is a clean slate, including the saved sign-ins
+ let _ = std::fs::remove_file(self.cookie_jar(id));
let mut lock = self.state.lock().await;
if lock.is_none() && self.sessions_file().exists() {
*lock = Some(self.connect().await?);
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index 7eedfc69..fea63bcf 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -16,6 +16,11 @@ pub enum BrowserInput {
Key { key: String, code: Option<String> },
Scroll { x: f64, y: f64, delta_x: f64, delta_y: f64 },
Navigate { url: String },
+ /// Left button down, for drags such as slider CAPTCHAs. Held until `pointer_up`, control
+ /// release or disconnect.
+ PointerDown { x: f64, y: f64 },
+ PointerMove { x: f64, y: f64 },
+ PointerUp { x: f64, y: f64 },
}
impl BrowserController {
@@ -51,6 +56,26 @@ impl BrowserController {
if !delta_x.is_finite() || !delta_y.is_finite() { return Err(BrowserError::Protocol("Invalid scroll".into())); }
self.send_cdp_command("Input.dispatchMouseEvent", json!({"type":"mouseWheel","x":x,"y":y,"deltaX":delta_x,"deltaY":delta_y})).await?;
}
+ BrowserInput::PointerDown { x, y } => {
+ point(x, y)?;
+ // A second press without a release (lost pointerup) lets go of the first one
+ self.release_pointer().await;
+ self.send_cdp_command("Input.dispatchMouseEvent", json!({"type":"mousePressed","x":x,"y":y,"button":"left","buttons":1,"clickCount":1})).await?;
+ self.set_pointer_held(Some((x, y)));
+ }
+ BrowserInput::PointerMove { x, y } => {
+ point(x, y)?;
+ let held = self.pointer_held().is_some();
+ self.send_cdp_command("Input.dispatchMouseEvent", json!({"type":"mouseMoved","x":x,"y":y,"button": if held {"left"} else {"none"},"buttons": if held {1} else {0}})).await?;
+ if held { self.set_pointer_held(Some((x, y))); }
+ }
+ BrowserInput::PointerUp { x, y } => {
+ point(x, y)?;
+ if self.pointer_held().is_some() {
+ self.set_pointer_held(None);
+ self.send_cdp_command("Input.dispatchMouseEvent", json!({"type":"mouseReleased","x":x,"y":y,"button":"left","buttons":0,"clickCount":1})).await?;
+ }
+ }
BrowserInput::Navigate { url } => {
let parsed = reqwest::Url::parse(&url).map_err(|e| BrowserError::Protocol(e.to_string()))?;
if !matches!(parsed.scheme(), "http"|"https") { return Err(BrowserError::Protocol("Use an HTTP or HTTPS URL".into())); }
@@ -59,6 +84,23 @@ impl BrowserController {
}
Ok(())
}
+
+ pub fn pointer_held(&self) -> Option<(f64, f64)> {
+ *self.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ fn set_pointer_held(&self, at: Option<(f64, f64)>) {
+ *self.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()) = at;
+ }
+
+ /// Lets go of a held left button where it was last seen, so a dropped socket or released
+ /// control never leaves the page mid-drag.
+ pub async fn release_pointer(&self) {
+ let held = self.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()).take();
+ if let Some((x, y)) = held {
+ let _ = self.send_cdp_command("Input.dispatchMouseEvent", json!({"type":"mouseReleased","x":x,"y":y,"button":"left","buttons":0,"clickCount":1})).await;
+ }
+ }
}
pub async fn upgrade(State(state): State<AppState>, Path(id): Path<String>, headers: HeaderMap, ws: WebSocketUpgrade) -> Result<Response, StatusCode> {
@@ -160,6 +202,7 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
send(&mut socket, json!({"type":"control","active":true})).await?;
}
"release_control" => {
+ ctrl.release_pointer().await;
lease = None;
send(&mut socket, json!({"type":"control","active":false})).await?;
}
@@ -179,7 +222,9 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
}
}
}
- // Dropping the lease releases bot actions even on disconnect or timeout.
+ // Let go of a drag in progress, then drop the lease so bot actions resume even on
+ // disconnect or timeout.
+ ctrl.release_pointer().await;
drop(lease);
let _ = cdp.close(None).await;
Ok(())
diff --git a/src/server/human_steps.rs b/src/server/human_steps.rs
index 2f9098c6..2d43266c 100644
--- a/src/server/human_steps.rs
+++ b/src/server/human_steps.rs
@@ -5,6 +5,11 @@
//! turn waits until they press Done or Decline (`POST /api/human-steps/:id/done|decline`). If
//! nobody answers in time the tool tells the agent to wrap up, and a later answer starts a new
//! turn in the same chat with the outcome. Stopping the turn cancels the step.
+//!
+//! A CAPTCHA step is also watched: the page is probed every couple of seconds, and once the check
+//! is gone the step closes as `resolved_auto` and the bot carries on by itself. Nobody solving it
+//! within `captcha_timeout_minutes` (default 10) closes it as `timed_out`, and the bot is told to
+//! move on rather than wait.
use super::continuity::{notify, Notification, SelfScope};
use super::routes::{scope_for, try_kwant_turn, TurnOpts};
@@ -12,6 +17,7 @@ use super::AppState;
use crate::db::human_steps::{clean_request, HumanStep, HumanStepError, HumanStepPlace, HUMAN_STEP_STATUSES};
use crate::db::models::{MessageExtra, NewMessage};
use crate::drivers::events::RuntimeEvent;
+use crate::sandbox::browser::{detect_bot_wall, BrowserController, CaptchaHit};
use axum::{
extract::{Path, Query, State},
http::StatusCode,
@@ -33,6 +39,10 @@ pub const TOOL: &str = "request_human_step";
pub enum Outcome {
Done,
Declined,
+ /// The CAPTCHA left the page (solved, or it passed by itself).
+ ResolvedAuto,
+ /// Nobody solved the CAPTCHA within the time limit.
+ TimedOut,
}
impl Outcome {
@@ -40,14 +50,26 @@ impl Outcome {
match self {
Outcome::Done => "done",
Outcome::Declined => "declined",
+ Outcome::ResolvedAuto => "resolved_auto",
+ Outcome::TimedOut => "timed_out",
}
}
}
+pub const CAPTCHA_TIMEOUT_SETTING: &str = "captcha_timeout_minutes";
+pub const DEFAULT_CAPTCHA_TIMEOUT_MINUTES: u64 = 10;
+pub const MAX_CAPTCHA_TIMEOUT_MINUTES: u64 = 60;
+/// Consecutive probes without the check before a step counts as solved: a page re-rendering
+/// between two looks doesn't close it.
+const GONE_AFTER_MISSES: u32 = 2;
+
/// The turns waiting on a human step, by step id. Empty (no cost) when unused.
pub struct HumanStepHub {
waiters: Mutex<HashMap<String, oneshot::Sender<Outcome>>>,
wait_ms: AtomicU64,
+ /// Tests only: CAPTCHA time limit and probe interval in ms (0 = setting / default).
+ captcha_timeout_ms: AtomicU64,
+ probe_ms: AtomicU64,
}
impl Default for HumanStepHub {
@@ -56,6 +78,8 @@ impl Default for HumanStepHub {
waiters: Mutex::default(),
// Shorter than the CLIs' tool timeout (approval timeout + 30 s), so the tool answers first
wait_ms: AtomicU64::new((crate::mcp::APPROVAL_TIMEOUT_SECS - 10) * 1000),
+ captcha_timeout_ms: AtomicU64::new(0),
+ probe_ms: AtomicU64::new(0),
}
}
}
@@ -70,6 +94,19 @@ impl HumanStepHub {
Duration::from_millis(self.wait_ms.load(Ordering::Relaxed))
}
+ /// Tests: a short CAPTCHA time limit and probe interval instead of the setting and 2 s.
+ pub fn set_captcha_timing(&self, timeout: Duration, probe: Duration) {
+ self.captcha_timeout_ms.store(timeout.as_millis() as u64, Ordering::Relaxed);
+ self.probe_ms.store(probe.as_millis() as u64, Ordering::Relaxed);
+ }
+
+ fn probe_interval(&self) -> Duration {
+ match self.probe_ms.load(Ordering::Relaxed) {
+ 0 => Duration::from_secs(2),
+ ms => Duration::from_millis(ms),
+ }
+ }
+
fn register(&self, id: &str) -> oneshot::Receiver<Outcome> {
let (tx, rx) = oneshot::channel();
self.waiters.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), tx);
@@ -122,9 +159,23 @@ fn card_meta(s: &HumanStep) -> Value {
"sandbox_target": s.sandbox_target,
"source": s.source,
"status": s.status,
+ "target": s.target.as_deref().and_then(|t| serde_json::from_str::<Value>(t).ok()),
})
}
+/// How long the person has to solve a CAPTCHA: `captcha_timeout_minutes` (1 to 60, default 10).
+pub async fn captcha_timeout(state: &AppState) -> Duration {
+ match state.human_steps.captcha_timeout_ms.load(Ordering::Relaxed) {
+ 0 => {}
+ ms => return Duration::from_millis(ms),
+ }
+ let minutes = state.db.get_setting(CAPTCHA_TIMEOUT_SETTING).await.ok().flatten()
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .filter(|m| (1..=MAX_CAPTCHA_TIMEOUT_MINUTES).contains(m))
+ .unwrap_or(DEFAULT_CAPTCHA_TIMEOUT_MINUTES);
+ Duration::from_secs(minutes * 60)
+}
+
fn place_message(s: &HumanStep, role: &str, sender: &str, text: String) -> (NewMessage, MessageExtra) {
(
NewMessage {
@@ -166,8 +217,13 @@ async fn release_browser(state: &AppState, target: Option<&str>) {
if state.db.human_step_open_in(target).await.unwrap_or(false) {
return;
}
- if let Some(ctrl) = state.browser_controllers.lock().await.get(target) {
+ let ctrl = state.browser_controllers.lock().await.get(target).cloned();
+ if let Some(ctrl) = ctrl {
+ // never hand the bot a page with the person's drag still held down
+ ctrl.release_pointer().await;
ctrl.release_person_hold();
+ // a solved CAPTCHA usually sets a clearance cookie: keep it past a browser restart
+ ctrl.persist_cookies().await;
}
}
@@ -224,14 +280,14 @@ pub async fn tool_request(state: &AppState, scope: &SelfScope, args: &Value) ->
Ok(v) => v,
Err(e) => return (e.to_string(), true),
};
- match raise(state, scope, &kind, &reason, url.as_deref(), "bot").await {
- Ok(outcome) => (outcome_text(outcome), false),
+ match raise(state, scope, &kind, &reason, url.as_deref(), None, "bot").await {
+ Ok(outcome) => (outcome_text(outcome, kind == "captcha"), false),
Err(e) => (e, true),
}
}
/// What the agent is told about the outcome.
-fn outcome_text(outcome: Option<Outcome>) -> String {
+fn outcome_text(outcome: Option<Outcome>, captcha: bool) -> String {
match outcome {
Some(Outcome::Done) => "The person says the step is done and handed the browser back. Look at the page \
again (browser_page) before you continue."
@@ -239,6 +295,17 @@ fn outcome_text(outcome: Option<Outcome>) -> String {
Some(Outcome::Declined) => "The person declined the step. Don't ask again: carry on without it if you can, or \
end your turn and say plainly what is blocked."
.into(),
+ Some(Outcome::ResolvedAuto) => "The human check is gone from the page (solved or passed), and the browser is \
+ yours again. Look at the page again (browser_page) and continue."
+ .into(),
+ Some(Outcome::TimedOut) => "The person didn't solve the CAPTCHA in time, so the step was closed. Don't wait for \
+ it or ask again now: skip this site and use another source (an official API or a site you're signed in to), \
+ or tell the person you'll try this site later."
+ .into(),
+ None if captcha => "The person hasn't solved the CAPTCHA yet. Don't ask again: end your turn now with a short \
+ note on what you're waiting for. The step closes by itself once the check is gone or the time runs out, \
+ and you'll get a new turn either way."
+ .into(),
None => "The person hasn't done the step yet. Don't ask again: end your turn now with a short note on what \
you're waiting for. When they finish, you'll get a new turn."
.into(),
@@ -253,6 +320,7 @@ pub async fn raise(
kind: &str,
reason: &str,
url: Option<&str>,
+ target: Option<&CaptchaHit>,
source: &str,
) -> Result<Option<Outcome>, String> {
let (Some(origin), Some(cancel)) = (&scope.origin, &scope.cancel) else {
@@ -268,16 +336,21 @@ pub async fn raise(
};
// Like ask_user, the step, its card and the waiter appear together
let hub = &state.human_steps;
+ let target_json = target.and_then(|t| serde_json::to_string(t).ok());
let mut waiter = None;
let created = state
.db
- .create_human_step_with_card(&place, kind, reason, url, source, |s| {
+ .create_human_step_with_card(&place, kind, reason, url, target_json.as_deref(), source, |s| {
waiter = Some((s.id.clone(), hub.register(&s.id)));
let mut text = format!("{}: {}", kind_label(&s.kind), s.reason);
if let Some(u) = &s.url {
text.push_str(&format!("\n{u}"));
}
- text.push_str("\n\nDo it in the browser panel, then press Done.");
+ text.push_str(if s.kind == "captcha" {
+ "\n\nSolve it in the browser panel. The bot carries on by itself once the check is gone (or press Done)."
+ } else {
+ "\n\nDo it in the browser panel, then press Done."
+ });
let (msg, extra) = place_message(s, "kwant", &scope.kwant_id, text);
Some((msg, MessageExtra { meta: Some(card_meta(s)), ..extra }))
})
@@ -300,8 +373,21 @@ pub async fn raise(
None => hub.register(&step.id),
};
let _guard = WaiterGuard { hub, id: step.id.clone() };
+ let mut wait = hub.wait();
+ if step.kind == "captcha" {
+ let limit = captcha_timeout(state).await;
+ let left = (step.created_at + chrono::Duration::from_std(limit).unwrap_or_default() - chrono::Utc::now())
+ .to_std()
+ .unwrap_or_default();
+ // A little past the limit, so the watcher's timed_out wakes the turn before the wait ends
+ wait = wait.min(left + hub.probe_interval() * 2);
+ }
if is_new {
hold_browser(state, step.sandbox_target.as_deref()).await;
+ if step.kind == "captcha" && step.sandbox_target.is_some() {
+ // a CAPTCHA kwnt saw is on the page already; one the bot named must show up first
+ tokio::spawn(watch_captcha(state.clone(), step.id.clone(), source == "auto"));
+ }
if let Some(card) = card {
if let Some(t) = &step.thread_id {
let _ = state.db.touch_thread(t).await;
@@ -334,7 +420,7 @@ pub async fn raise(
close(state, &step.id, "cancelled").await;
Err("The user stopped this turn. End it now.".into())
}
- _ = tokio::time::sleep(hub.wait()) => {
+ _ = tokio::time::sleep(wait) => {
hub.take(&step.id);
// An answer that arrived just as the wait ran out still counts
Ok(rx.try_recv().ok())
@@ -347,18 +433,86 @@ pub async fn raise(
pub async fn raise_for_bot_wall(state: &AppState, scope: &SelfScope, page: &Value) -> Option<String> {
scope.origin.as_ref()?;
scope.cancel.as_ref()?;
+ let target = CaptchaHit::parse(&page["captcha"]);
let url = page["url"].as_str().and_then(crate::db::human_steps::clean_url);
let host = url.as_deref().and_then(|u| url::Url::parse(u).ok()).and_then(|u| u.host_str().map(str::to_string));
let reason = match host {
Some(h) => format!("{h} is showing a CAPTCHA / human check to the bot browser. Please solve it."),
None => "The page is showing a CAPTCHA / human check to the bot browser. Please solve it.".into(),
};
- Some(match raise(state, scope, "captcha", &reason, url.as_deref(), "auto").await {
- Ok(outcome) => format!("A CAPTCHA blocked the page, so the person was asked to solve it. {}", outcome_text(outcome)),
+ Some(match raise(state, scope, "captcha", &reason, url.as_deref(), target.as_ref(), "auto").await {
+ Ok(outcome) => format!("A CAPTCHA blocked the page, so the person was asked to solve it. {}", outcome_text(outcome, true)),
Err(e) => e,
})
}
+/// Whether the page still shows a human check: a CAPTCHA widget, or a bot-wall page (Cloudflare's
+/// "just a moment", Google's "unusual traffic"). `None` when the page couldn't be read.
+async fn wall_on_page(ctrl: &BrowserController) -> Option<(bool, Option<CaptchaHit>)> {
+ if let Some(hit) = ctrl.probe_captcha().await.ok()? {
+ return Some((true, Some(hit)));
+ }
+ let (url, title) = ctrl.sync_location().await?;
+ let text = ctrl.extract_content().await.ok()?;
+ Some((detect_bot_wall(&url, &title, &text).is_some(), None))
+}
+
+/// Watches an open CAPTCHA step until it closes: keeps its box current, closes it as
+/// `resolved_auto` once the check is gone, or as `timed_out` at the time limit, and tells the bot.
+async fn watch_captcha(state: AppState, id: String, mut seen: bool) {
+ let limit = captcha_timeout(&state).await;
+ let started = tokio::time::Instant::now();
+ let interval = state.human_steps.probe_interval();
+ let mut misses = 0u32;
+ loop {
+ tokio::time::sleep(interval.min(limit.saturating_sub(started.elapsed()))).await;
+ let Ok(Some(step)) = state.db.get_human_step(&id).await else { return };
+ if step.status != "open" {
+ return;
+ }
+ if started.elapsed() >= limit {
+ settle(&state, &id, Outcome::TimedOut).await;
+ return;
+ }
+ let Some(target) = step.sandbox_target.as_deref() else { return };
+ let ctrl = state.browser_controllers.lock().await.get(target).cloned();
+ let Some(ctrl) = ctrl else { continue };
+ match wall_on_page(&ctrl).await {
+ // unreadable (mid-navigation, say): unknown, never "gone"
+ None => {}
+ Some((true, hit)) => {
+ seen = true;
+ misses = 0;
+ if let Some(target_json) = hit.and_then(|h| serde_json::to_string(&h).ok()) {
+ if state.db.set_human_step_target(&id, &target_json).await.unwrap_or(false) {
+ if let Ok(Some(s)) = state.db.get_human_step(&id).await {
+ changed(&state, &s).await;
+ }
+ }
+ }
+ }
+ Some((false, _)) if seen => {
+ misses += 1;
+ if misses >= GONE_AFTER_MISSES {
+ settle(&state, &id, Outcome::ResolvedAuto).await;
+ return;
+ }
+ }
+ Some((false, _)) => {}
+ }
+ }
+}
+
+/// Closes a CAPTCHA step kwnt decided on (gone or timed out) and tells the bot: the waiting turn
+/// at once, or a new turn in the chat if it already ended.
+async fn settle(state: &AppState, id: &str, outcome: Outcome) {
+ let Some(s) = close(state, id, outcome.status()).await else { return };
+ tracing::info!(human_step_id = %s.id, status = %s.status, "CAPTCHA step closed by kwnt");
+ if !state.human_steps.wake(&s.id, outcome) {
+ resume(state, &s, outcome).await;
+ }
+}
+
// Routes
#[derive(Deserialize)]
@@ -429,8 +583,8 @@ async fn finish(state: &AppState, id: &str, outcome: Outcome) -> Response {
return error(StatusCode::CONFLICT, "the step was just closed");
};
let text = match outcome {
- Outcome::Done => "Done",
Outcome::Declined => "Declined",
+ _ => "Done",
};
let (msg, extra) = place_message(&s, "user", "user", text.into());
let meta = json!({"kind": "human_step_reply", "human_step_id": s.id, "status": s.status});
@@ -469,6 +623,15 @@ async fn resume(state: &AppState, s: &HumanStep, outcome: Outcome) {
"[The person declined the browser step you asked for earlier]\nStep: {}\n\nDon't ask again. Carry on without it if you can, or say plainly what is blocked.",
s.reason
),
+ Outcome::ResolvedAuto => format!(
+ "[The human check in the browser is gone, so the browser is yours again]\nStep: {}\n\nLook at the browser page again and continue the task.",
+ s.reason
+ ),
+ Outcome::TimedOut => format!(
+ "[Nobody solved the CAPTCHA in time, so the step was closed]\nStep: {}\n\nDon't wait for it or ask again now. Skip this site and \
+ continue with another source (an official API or a site you're signed in to), or tell the person you'll try this site later.",
+ s.reason
+ ),
};
tokio::spawn(async move {
let _job = job;
@@ -504,8 +667,14 @@ mod tests {
#[test]
fn the_agent_hears_each_outcome_plainly() {
- assert!(outcome_text(Some(Outcome::Done)).contains("Look at the page"));
- assert!(outcome_text(Some(Outcome::Declined)).contains("declined"));
- assert!(outcome_text(None).contains("end your turn"));
+ assert!(outcome_text(Some(Outcome::Done), false).contains("Look at the page"));
+ assert!(outcome_text(Some(Outcome::Declined), false).contains("declined"));
+ assert!(outcome_text(None, false).contains("end your turn"));
+ assert!(outcome_text(Some(Outcome::ResolvedAuto), true).contains("continue"));
+ let timed_out = outcome_text(Some(Outcome::TimedOut), true);
+ assert!(timed_out.contains("skip this site") && timed_out.contains("another source"));
+ assert!(outcome_text(None, true).contains("closes by itself"));
+ assert_eq!(Outcome::ResolvedAuto.status(), "resolved_auto");
+ assert_eq!(Outcome::TimedOut.status(), "timed_out");
}
}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 1ae244c0..fa69d0ed 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1715,7 +1715,9 @@ async fn run_kwant_turn_inner(
timestamp: chrono::Utc::now().to_rfc3339(),
});
}
- final_prompt = if let Some(kind) = crate::sandbox::detect_bot_wall(&nav.url, &nav.title, &page_text) {
+ let captcha = ctrl.probe_captcha().await.ok().flatten();
+ let wall = crate::sandbox::detect_bot_wall(&nav.url, &nav.title, &page_text).or(captcha.as_ref().map(|c| c.label()));
+ final_prompt = if let Some(kind) = wall {
format!(
"{}\n\n[Sandbox Browser State: Tried to open {} in the right-panel bot browser. {}]",
prompt, target_url, bot_wall_notice(kind, &nav.url)
@@ -2851,6 +2853,8 @@ pub struct SettingsResponse {
pub timezone: String,
/// The person's city as they typed it, "" when not set.
pub location: String,
+ /// How long a CAPTCHA step waits for the person before the bot moves on (1–60).
+ pub captcha_timeout_minutes: u64,
}
/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of
@@ -2877,6 +2881,7 @@ pub struct SaveSettingsPayload {
pub timezone_default: Option<String>,
/// The person's city, plain text ("Ljubljana"); "" clears it. Never looked up anywhere.
pub location: Option<String>,
+ pub captcha_timeout_minutes: Option<u64>,
}
pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {
@@ -2909,6 +2914,10 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settings
agent_tools: super::continuity::agent_tools_enabled(&state).await,
timezone: state.db.get_setting(super::bot_actions::TIMEZONE_SETTING).await.ok().flatten().unwrap_or_default(),
location: state.db.get_setting(super::bot_actions::LOCATION_SETTING).await.ok().flatten().unwrap_or_default(),
+ captcha_timeout_minutes: state.db.get_setting(super::human_steps::CAPTCHA_TIMEOUT_SETTING).await.ok().flatten()
+ .and_then(|v| v.parse::<u64>().ok())
+ .filter(|m| (1..=super::human_steps::MAX_CAPTCHA_TIMEOUT_MINUTES).contains(m))
+ .unwrap_or(super::human_steps::DEFAULT_CAPTCHA_TIMEOUT_MINUTES),
}))
}
@@ -2944,6 +2953,10 @@ pub async fn save_settings(
return bad(format!("delegation_follow_up_minutes must be 0–{max_minutes}"));
}
let check_tz = |tz: &str| crate::routines::Schedule::Daily { time: "09:00".into(), tz: tz.to_string() }.validate();
+ let max_captcha = super::human_steps::MAX_CAPTCHA_TIMEOUT_MINUTES;
+ if payload.captcha_timeout_minutes.is_some_and(|m| !(1..=max_captcha).contains(&m)) {
+ return bad(format!("captcha_timeout_minutes must be 1–{max_captcha}"));
+ }
let timezone = payload.timezone.as_deref().map(crate::routines::canonical_tz);
if let Some(tz) = timezone.as_deref().filter(|t| !t.is_empty()) {
if let Err(e) = check_tz(tz) {
@@ -3000,6 +3013,9 @@ pub async fn save_settings(
super::engine_routes::recheck_all(&state, &SpaceId::default_space()).await;
});
}
+ if let Some(minutes) = payload.captcha_timeout_minutes {
+ let _ = state.db.set_setting(super::human_steps::CAPTCHA_TIMEOUT_SETTING, &minutes.to_string()).await;
+ }
if payload.max_turns_per_agent.is_some() || payload.max_turns_global.is_some() {
let (per_agent, global) = state.turns.limiter.limits();
let per_agent = payload.max_turns_per_agent.unwrap_or(per_agent);
@@ -3595,10 +3611,17 @@ async fn sandbox_page_state(ctrl: &crate::sandbox::BrowserController) -> serde_j
"clickable": clickable,
"blocked": false,
});
- if let Some(kind) = crate::sandbox::detect_bot_wall(&url, &title, &text) {
+ // A CAPTCHA widget on an otherwise normal page (TikTok's slider over the feed, a
+ // reCAPTCHA on a form) counts too; its box tells the person's view where to look
+ let captcha = ctrl.probe_captcha().await.ok().flatten();
+ let wall = crate::sandbox::detect_bot_wall(&url, &title, &text).or(captcha.as_ref().map(|c| c.label()));
+ if let Some(kind) = wall {
page["blocked"] = json!(true);
page["notice"] = json!(bot_wall_notice(kind, &url));
}
+ if let Some(captcha) = captcha {
+ page["captcha"] = json!(captcha);
+ }
page
}
diff --git a/tests/browser_stream_test.rs b/tests/browser_stream_test.rs
index e2acb69e..f022b27e 100644
--- a/tests/browser_stream_test.rs
+++ b/tests/browser_stream_test.rs
@@ -151,6 +151,92 @@ async fn stream_input_control_lease_and_origin_protection() {
app_task.abort(); cdp_task.abort();
}
+async fn mouse_events(mock: &Mock) -> Vec<(String, i64, String)> {
+ mock.commands.lock().await.iter().filter(|c| c["method"] == "Input.dispatchMouseEvent").map(|c| (
+ c["params"]["type"].as_str().unwrap().to_string(),
+ c["params"]["buttons"].as_i64().unwrap_or(-1),
+ c["params"]["button"].as_str().unwrap_or("").to_string(),
+ )).collect()
+}
+
+#[tokio::test]
+async fn pointer_drags_press_move_release_in_order_and_let_go_on_release_or_disconnect() {
+ let (mock, cdp_task) = mock().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let config = Config {data_dir:tmp.path().into(),browser_cdp_url:Some(format!("http://127.0.0.1:{}",mock.port)),..Config::default()};
+ let db = Database::init(tmp.path()).await.unwrap();
+ let id=db.list_kwants(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap()[0].id.clone();
+ let state=AppState::new(config.clone(),db,ToolRunner::new(tmp.path().join("workspace")),PermissionBroker::new(),LayaRouter::new(config.laya_url));
+ let ctrl=kwnt::server::routes::get_or_create_browser_controller(&state,&id).await.unwrap();
+ let listener=TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port=listener.local_addr().unwrap().port();
+ let app=create_router(state);
+ let app_task=tokio::spawn(async move {axum::serve(listener,app).await.unwrap();});
+ let connect = || async {
+ let mut request=format!("ws://127.0.0.1:{port}/api/sandbox/{id}/stream").into_client_request().unwrap();
+ request.headers_mut().insert("Origin",format!("http://127.0.0.1:{port}").parse().unwrap());
+ let (mut ws,_)=connect_async(request).await.unwrap();
+ receive(&mut ws,"frame").await;
+ ws.send(WsMessage::Text(json!({"action":"take_control"}).to_string())).await.unwrap();
+ assert_eq!(receive(&mut ws,"control").await["active"],true);
+ ws
+ };
+ let mut ws = connect().await;
+ let send = |payload: Value| WsMessage::Text(payload.to_string());
+
+ // pointer input is bounds-checked like a click
+ mock.commands.lock().await.clear();
+ ws.send(send(json!({"action":"pointer_down","x":10,"y":10,"id":"out"}))).await.unwrap();
+ assert_eq!(receive(&mut ws,"ack").await["id"],"out");
+ ws.send(send(json!({"action":"pointer_down","x":1280,"y":10,"id":"edge"}))).await.unwrap();
+ assert!(receive(&mut ws,"error").await["error"].as_str().unwrap().contains("outside"), "same bounds as click");
+ ws.send(send(json!({"action":"pointer_up","x":10,"y":10,"id":"reset"}))).await.unwrap();
+ receive(&mut ws,"ack").await;
+ mock.commands.lock().await.clear();
+
+ // a slider drag: press, two moves while held, release
+ for (i, (action, x)) in [("pointer_down",100),("pointer_move",150),("pointer_move",220),("pointer_up",220),("pointer_move",230),("pointer_up",230)].into_iter().enumerate() {
+ ws.send(send(json!({"action":action,"x":x,"y":400,"id":i}))).await.unwrap();
+ assert_eq!(receive(&mut ws,"ack").await["id"],i);
+ }
+ assert_eq!(mouse_events(&mock).await, vec![
+ ("mousePressed".into(),1,"left".into()),
+ ("mouseMoved".into(),1,"left".into()),
+ ("mouseMoved".into(),1,"left".into()),
+ ("mouseReleased".into(),0,"left".into()),
+ // a hover after the drag is a plain move, and a stray pointer_up sends nothing
+ ("mouseMoved".into(),0,"none".into()),
+ ]);
+ assert!(ctrl.pointer_held().is_none());
+
+ // pressed, then control released: the button is let go where it was
+ mock.commands.lock().await.clear();
+ ws.send(send(json!({"action":"pointer_down","x":300,"y":400,"id":"d1"}))).await.unwrap();
+ receive(&mut ws,"ack").await;
+ ws.send(send(json!({"action":"pointer_move","x":340,"y":405,"id":"m1"}))).await.unwrap();
+ receive(&mut ws,"ack").await;
+ ws.send(send(json!({"action":"release_control"}))).await.unwrap();
+ assert_eq!(receive(&mut ws,"control").await["active"],false);
+ let events = mouse_events(&mock).await;
+ assert_eq!(events.last().unwrap(), &("mouseReleased".into(),0,"left".into()));
+ let released = mock.commands.lock().await.iter().rev().find(|c| c["params"]["type"]=="mouseReleased").cloned().unwrap();
+ assert_eq!((released["params"]["x"].as_f64(), released["params"]["y"].as_f64()), (Some(340.0), Some(405.0)));
+ ws.close(None).await.unwrap();
+
+ // pressed, then the socket drops mid-drag: released too, and bot actions come back
+ let mut ws = connect().await;
+ mock.commands.lock().await.clear();
+ ws.send(send(json!({"action":"pointer_down","x":500,"y":420,"id":"d2"}))).await.unwrap();
+ receive(&mut ws,"ack").await;
+ drop(ws);
+ timeout(Duration::from_secs(5),async {loop {
+ if ctrl.control.try_read().is_ok() && ctrl.pointer_held().is_none() {break;}
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }}).await.unwrap();
+ assert_eq!(mouse_events(&mock).await, vec![("mousePressed".into(),1,"left".into()),("mouseReleased".into(),0,"left".into())]);
+ app_task.abort(); cdp_task.abort();
+}
+
/// Opt in after building docker/browser.Dockerfile. Uses disposable data and a local HTML page.
#[tokio::test]
#[ignore = "requires Docker and the kwnt-browser:v2 image"]
diff --git a/tests/captcha_test.rs b/tests/captcha_test.rs
new file mode 100644
index 00000000..a0faccdf
--- /dev/null
+++ b/tests/captcha_test.rs
@@ -0,0 +1,372 @@
+//! CAPTCHA hand-off: the page probe finds each vendor's widget (and its box) and ignores
+//! look-alikes, bot navigation declines cookie banners but never accepts them, VM-mode cookies
+//! outlive a browser restart, and a bot that lands on a slider gets a step with the widget's box
+//! that closes by itself once the slider is dragged, or times out so the turn moves on.
+//!
+//! The browser parts run a real windowless Chrome as the "VM" browser (an external CDP endpoint)
+//! and are skipped when none is installed; the time-out part needs no browser.
+
+#[path = "support/chrome_guard.rs"]
+mod chrome_guard;
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrome_guard::ChromeGuard;
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{spaces::SpaceId, Database},
+ router::LayaRouter,
+ sandbox::{computer, service::BrowserService, BrowserController},
+ server::{
+ browser_stream::BrowserInput,
+ continuity::{SelfScope, TurnOrigin},
+ create_router, mcp_runtime, AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::{path::Path, time::Duration};
+use tempfile::{tempdir, TempDir};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tower::ServiceExt;
+
+/// Serves `tests/fixtures/captcha/<name>` on 127.0.0.1, plus `/set-cookie` (a persistent cookie).
+async fn serve_fixtures() -> String {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/captcha");
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ let dir = dir.clone();
+ tokio::spawn(async move {
+ let mut buf = [0u8; 4096];
+ let n = stream.read(&mut buf).await.unwrap_or(0);
+ let request = String::from_utf8_lossy(&buf[..n]);
+ let path = request.split_whitespace().nth(1).unwrap_or("/").trim_start_matches('/').to_string();
+ let (status, extra, body) = if path == "set-cookie" {
+ ("200 OK", "set-cookie: kwnt_test=kept; Max-Age=86400; Path=/\r\n", "<title>cookie set</title>".to_string())
+ } else if path.contains("..") || path.contains('/') {
+ ("404 Not Found", "", String::new())
+ } else {
+ match std::fs::read_to_string(dir.join(&path)) {
+ Ok(body) => ("200 OK", "", body),
+ Err(_) => ("404 Not Found", "", String::new()),
+ }
+ };
+ let reply = format!(
+ "HTTP/1.1 {status}\r\ncontent-type: text/html\r\n{extra}content-length: {}\r\nconnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = stream.write_all(reply.as_bytes()).await;
+ });
+ }
+ });
+ format!("http://127.0.0.1:{port}/")
+}
+
+/// A windowless Chrome on its own profile, standing in for the VM browser.
+async fn start_chrome(profile: &Path) -> Option<(String, ChromeGuard)> {
+ if computer::local_chrome_path().is_none() {
+ eprintln!("browser part skipped: no Chrome or Chromium installed");
+ return None;
+ }
+ let (endpoint, _) = computer::ensure_local_chrome(profile, true).await.expect("Chrome starts");
+ Some((endpoint, ChromeGuard(profile.to_path_buf())))
+}
+
+async fn state_with(tmp: &TempDir, endpoint: Option<String>) -> AppState {
+ // the VM path (per-bot contexts, cookie jar) on an external endpoint, as in Docker
+ std::env::set_var("KWNT_COMPUTER_MODE", "vm");
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), browser_cdp_url: endpoint, ..Config::default() };
+ AppState::new(config.clone(), db, ToolRunner::new(tmp.path().join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url))
+}
+
+async fn open(ctrl: &BrowserController, url: &str) {
+ ctrl.navigate_unlocked(url).await.unwrap();
+ for _ in 0..50 {
+ let ready = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": "document.readyState", "returnByValue": true})).await.unwrap();
+ if ready["result"]["value"] == "complete" {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+}
+
+async fn title(ctrl: &BrowserController) -> String {
+ ctrl.sync_location().await.map(|(_, t)| t).unwrap_or_default()
+}
+
+/// The kind and the box size a fixture should give.
+type Expected = (&'static str, f64, f64);
+
+#[tokio::test]
+async fn the_probe_finds_each_vendor_with_its_box_and_ignores_lookalikes() {
+ let tmp = tempdir().unwrap();
+ let Some((endpoint, _chrome)) = start_chrome(&tmp.path().join("chrome")).await else { return };
+ let state = state_with(&tmp, Some(endpoint)).await;
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].id.clone();
+ let ctrl = kwnt::server::routes::get_or_create_browser_controller(&state, &bot).await.expect("browser");
+ let base = serve_fixtures().await;
+ let cases: [(&str, Option<Expected>); 15] = [
+ ("recaptcha.html", Some(("recaptcha", 304.0, 78.0))),
+ ("hcaptcha.html", Some(("hcaptcha", 303.0, 78.0))),
+ ("turnstile.html", Some(("turnstile", 300.0, 65.0))),
+ ("arkose.html", Some(("arkose", 400.0, 400.0))),
+ ("datadome.html", Some(("datadome", 400.0, 500.0))),
+ ("geetest.html", Some(("geetest", 342.0, 382.0))),
+ ("perimeterx.html", Some(("perimeterx", 312.0, 102.0))),
+ ("tiktok_slider.html", Some(("tiktok", 360.0, 380.0))),
+ ("shadow.html", Some(("tiktok", 360.0, 300.0))),
+ // a slider prompt in a modal on a site without a known vendor
+ ("dialog_puzzle.html", Some(("puzzle", 402.0, 322.0))),
+ // scrolled into view, so the box is on screen
+ ("offscreen.html", Some(("hcaptcha", 303.0, 78.0))),
+ // reCAPTCHA v3's badge is no challenge, a hidden widget isn't shown, an article about
+ // sliders is just text
+ ("recaptcha_v3_badge.html", None),
+ ("hidden.html", None),
+ ("article.html", None),
+ ("consent_onetrust.html", None),
+ ];
+ for (file, want) in cases {
+ open(&ctrl, &format!("{base}{file}")).await;
+ let hit = ctrl.probe_captcha().await.unwrap();
+ match (want, hit) {
+ (None, None) => {}
+ (Some((kind, w, h)), Some(hit)) => {
+ assert_eq!(hit.kind, kind, "{file}");
+ assert!((hit.width - w).abs() <= 2.0 && (hit.height - h).abs() <= 2.0, "{file}: {hit:?}");
+ assert!(hit.x >= 0.0 && hit.y >= 0.0 && hit.x + hit.width <= 1280.0 && hit.y + hit.height <= 800.0, "{file}: {hit:?}");
+ }
+ (want, hit) => panic!("{file}: wanted {want:?}, got {hit:?}"),
+ }
+ }
+ open(&ctrl, &format!("{base}tiktok_slider.html")).await;
+ let hit = ctrl.probe_captcha().await.unwrap().unwrap();
+ assert_eq!((hit.x, hit.y), (460.0, 180.0));
+}
+
+#[tokio::test]
+async fn bot_navigation_declines_cookie_banners_and_never_accepts_one() {
+ let tmp = tempdir().unwrap();
+ let Some((endpoint, _chrome)) = start_chrome(&tmp.path().join("chrome")).await else { return };
+ let state = state_with(&tmp, Some(endpoint)).await;
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].id.clone();
+ let ctrl = kwnt::server::routes::get_or_create_browser_controller(&state, &bot).await.expect("browser");
+ let base = serve_fixtures().await;
+ for (file, want) in [
+ ("consent_onetrust.html", "rejected"),
+ ("consent_tiktok.html", "declined"),
+ // only accept buttons: left alone for the person
+ ("consent_accept_only.html", "untouched"),
+ ] {
+ ctrl.navigate(&format!("{base}{file}")).await.unwrap();
+ assert_eq!(title(&ctrl).await, want, "{file}");
+ }
+ // The person's own navigation from the live view never touches banners
+ ctrl.navigate_unlocked(&format!("{base}consent_onetrust.html")).await.unwrap();
+ tokio::time::sleep(Duration::from_millis(1200)).await;
+ assert_eq!(title(&ctrl).await, "OneTrust");
+}
+
+async fn cookie_names(ctrl: &BrowserController) -> Vec<String> {
+ let all = ctrl.send_cdp_command("Network.getAllCookies", json!({})).await.unwrap();
+ all["cookies"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap().to_string()).collect()
+}
+
+#[tokio::test]
+async fn vm_cookies_are_kept_per_bot_across_a_browser_restart() {
+ let tmp = tempdir().unwrap();
+ let Some((endpoint, chrome)) = start_chrome(&tmp.path().join("chrome")).await else { return };
+ std::env::set_var("KWNT_COMPUTER_MODE", "vm");
+ let root = tmp.path().join("data");
+ std::fs::create_dir_all(&root).unwrap();
+ let base = serve_fixtures().await;
+ let service = BrowserService::new(root.clone(), Some(endpoint));
+ let a = service.session("bot-a", &root).await.unwrap();
+ let b = service.session("bot-b", &root).await.unwrap();
+ a.navigate(&format!("{base}set-cookie")).await.unwrap();
+ assert!(cookie_names(&a).await.contains(&"kwnt_test".to_string()));
+ assert!(!cookie_names(&b).await.contains(&"kwnt_test".to_string()), "each bot's context has its own cookies");
+ let jar = service.cookie_jar("bot-a");
+ let saved = std::fs::read_to_string(&jar).expect("bot navigation saves the jar");
+ assert!(saved.contains("kwnt_test"));
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(std::fs::metadata(&jar).unwrap().permissions().mode() & 0o777, 0o600);
+ }
+ assert!(!service.cookie_jar("bot-b").exists() || !std::fs::read_to_string(service.cookie_jar("bot-b")).unwrap().contains("kwnt_test"));
+
+ // The container restarts: a new browser on an empty (tmpfs) profile
+ drop((a, b, service, chrome));
+ let _ = computer::wait_local_chrome_gone(&tmp.path().join("chrome")).await;
+ let Some((endpoint, _chrome)) = start_chrome(&tmp.path().join("chrome-after-restart")).await else { return };
+ let service = BrowserService::new(root.clone(), Some(endpoint));
+ let a = service.session("bot-a", &root).await.unwrap();
+ assert!(cookie_names(&a).await.contains(&"kwnt_test".to_string()), "restored into the fresh context");
+ open(&a, &format!("{base}article.html")).await;
+ let cookie = a.send_cdp_command("Runtime.evaluate", json!({"expression": "document.cookie", "returnByValue": true})).await.unwrap();
+ assert_eq!(cookie["result"]["value"], "kwnt_test=kept");
+ let b = service.session("bot-b", &root).await.unwrap();
+ assert!(!cookie_names(&b).await.contains(&"kwnt_test".to_string()));
+
+ // A reset is a clean slate
+ service.reset("bot-a").await.unwrap();
+ assert!(!jar.exists());
+}
+
+// The bot's turn, through kwnt's own MCP tools
+
+async fn post(app: &Router, uri: &str, token: &str, body: Value) -> Value {
+ let req = Request::builder()
+ .method("POST")
+ .uri(uri)
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {token}"));
+ let resp = app.clone().oneshot(req.body(Body::from(body.to_string())).unwrap()).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap()
+}
+
+async fn turn(state: &AppState, turn_id: &str) -> String {
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);
+ let scope = SelfScope {
+ kwant_id: bot.id.clone(),
+ kwant_name: bot.name.clone(),
+ origin: Some(TurnOrigin { direct_kwant_id: Some(bot.id.clone()), ..Default::default() }),
+ cancel: Some(tokio_util::sync::CancellationToken::new()),
+ turn_id: Some(turn_id.into()),
+ sandbox_target: Some(bot.id.clone()),
+ ..Default::default()
+ };
+ mcp_runtime::prepare_turn_with_self(state, &bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1
+}
+
+/// Calls a self tool in the background, as the CLI would while the turn waits.
+fn call(app: &Router, token: &str, name: &str, args: Value) -> tokio::task::JoinHandle<(String, bool)> {
+ let (app, token, name) = (app.clone(), token.to_string(), name.to_string());
+ tokio::spawn(async move {
+ let v = post(&app, "/api/mcp/self", &token, json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": {"name": name, "arguments": args}})).await;
+ (v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string(), v["result"]["isError"].as_bool().unwrap_or(false))
+ })
+}
+
+async fn open_step(state: &AppState) -> kwnt::db::human_steps::HumanStep {
+ for _ in 0..200 {
+ if let Some(s) = state.db.list_human_steps(Some("open"), None, None).await.unwrap().pop() {
+ return s;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ panic!("no step was raised");
+}
+
+#[tokio::test]
+async fn a_bot_landing_on_a_slider_gets_a_step_with_its_box_that_closes_once_solved_or_times_out() {
+ let tmp = tempdir().unwrap();
+ let Some((endpoint, _chrome)) = start_chrome(&tmp.path().join("chrome")).await else { return };
+ let state = state_with(&tmp, Some(endpoint)).await;
+ state.human_steps.set_captcha_timing(Duration::from_secs(60), Duration::from_millis(200));
+ let app = create_router(state.clone());
+ let base = serve_fixtures().await;
+ let token = turn(&state, "turn-solve").await;
+
+ // The bot opens a page that shows TikTok's slider: a step opens with the widget's box
+ let task = call(&app, &token, "browser_open", json!({"url": format!("{base}tiktok_slider.html")}));
+ let step = open_step(&state).await;
+ assert_eq!((step.kind.as_str(), step.source.as_str()), ("captcha", "auto"));
+ let json = serde_json::to_value(&step).unwrap();
+ assert_eq!(json["target"], json!({"kind": "tiktok", "x": 460.0, "y": 180.0, "width": 360.0, "height": 380.0}), "{json}");
+ let card = state.db.get_message(step.message_id.as_deref().unwrap()).await.unwrap().unwrap();
+ let meta: Value = serde_json::from_str(card.meta.as_deref().unwrap()).unwrap();
+ assert_eq!(meta["target"]["kind"], "tiktok");
+ let ctrl = state.browser_controllers.lock().await.get(step.sandbox_target.as_deref().unwrap()).cloned().unwrap();
+ assert!(ctrl.is_held_for_person());
+ assert!(!task.is_finished(), "the turn waits for the person");
+
+ // The person drags the slider in the live view: press, move with the button held, release
+ let knob = (510.0, 500.0);
+ for input in [
+ BrowserInput::PointerDown { x: knob.0, y: knob.1 },
+ BrowserInput::PointerMove { x: knob.0 + 80.0, y: knob.1 },
+ BrowserInput::PointerMove { x: knob.0 + 240.0, y: knob.1 + 2.0 },
+ BrowserInput::PointerUp { x: knob.0 + 240.0, y: knob.1 + 2.0 },
+ ] {
+ ctrl.dispatch_input(input).await.unwrap();
+ }
+ let log = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": "window.dragLog ? dragLog.join(',') : ''", "returnByValue": true})).await.unwrap();
+ assert_eq!(log["result"]["value"], "down:1,move:1,move:1,up:0", "the page sees a real held drag");
+
+ // Nobody presses Done: the check is gone, so the step closes and the bot carries on
+ let (text, is_error) = tokio::time::timeout(Duration::from_secs(20), task).await.expect("the turn resumes").unwrap();
+ assert!(!is_error, "{text}");
+ assert!(text.contains("human check is gone"), "{text}");
+ assert!(text.contains("TikTok - solved"), "the bot sees the page after: {text}");
+ let closed = state.db.get_human_step(&step.id).await.unwrap().unwrap();
+ assert_eq!(closed.status, "resolved_auto");
+ assert!(!ctrl.is_held_for_person(), "the browser is the bot's again");
+
+ // Nobody solves the next one: it times out and the bot is told to move on, never hanging
+ state.human_steps.set_captcha_timing(Duration::from_millis(1500), Duration::from_millis(200));
+ let token = turn(&state, "turn-timeout").await;
+ let task = call(&app, &token, "browser_open", json!({"url": format!("{base}tiktok_slider.html")}));
+ let step = open_step(&state).await;
+ let (text, is_error) = tokio::time::timeout(Duration::from_secs(20), task).await.expect("the turn never hangs").unwrap();
+ assert!(!is_error, "{text}");
+ assert!(text.contains("didn't solve the CAPTCHA in time") && text.contains("skip this site"), "{text}");
+ assert_eq!(state.db.get_human_step(&step.id).await.unwrap().unwrap().status, "timed_out");
+ assert!(!ctrl.is_held_for_person());
+ // Done after the fact is refused, the step is settled
+ let resp = app.clone().oneshot(Request::builder().method("POST").uri(format!("/api/human-steps/{}/done", step.id)).body(Body::empty()).unwrap()).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::CONFLICT);
+}
+
+#[tokio::test]
+async fn a_captcha_step_nobody_solves_times_out_without_a_browser() {
+ let tmp = tempdir().unwrap();
+ let state = state_with(&tmp, None).await;
+ state.human_steps.set_captcha_timing(Duration::from_millis(800), Duration::from_millis(100));
+ let app = create_router(state.clone());
+ let token = turn(&state, "turn-ask").await;
+ let started = std::time::Instant::now();
+ let task = call(&app, &token, "request_human_step", json!({"kind": "captcha", "reason": "Solve the check on example.com"}));
+ let step = open_step(&state).await;
+ assert!(step.target.is_none());
+ let (text, is_error) = tokio::time::timeout(Duration::from_secs(15), task).await.expect("the turn never hangs").unwrap();
+ assert!(!is_error, "{text}");
+ assert!(text.contains("didn't solve the CAPTCHA in time"), "{text}");
+ assert!(started.elapsed() < Duration::from_secs(10));
+ assert_eq!(state.db.get_human_step(&step.id).await.unwrap().unwrap().status, "timed_out");
+}
+
+#[tokio::test]
+async fn the_captcha_time_limit_is_a_checked_setting() {
+ let tmp = tempdir().unwrap();
+ let state = state_with(&tmp, None).await;
+ let app = create_router(state.clone());
+ let get = || async {
+ let resp = app.clone().oneshot(Request::builder().uri("/api/settings").body(Body::empty()).unwrap()).await.unwrap();
+ let v: Value = serde_json::from_slice(&to_bytes(resp.into_body(), usize::MAX).await.unwrap()).unwrap();
+ v["captcha_timeout_minutes"].clone()
+ };
+ let save = |body: Value| {
+ let app = app.clone();
+ async move {
+ app.oneshot(Request::builder().method("POST").uri("/api/settings").header("content-type", "application/json")
+ .body(Body::from(body.to_string())).unwrap()).await.unwrap().status()
+ }
+ };
+ assert_eq!(get().await, 10);
+ assert_eq!(kwnt::server::human_steps::captcha_timeout(&state).await, Duration::from_secs(600));
+ assert_eq!(save(json!({"captcha_timeout_minutes": 0})).await, StatusCode::BAD_REQUEST);
+ assert_eq!(save(json!({"captcha_timeout_minutes": 61})).await, StatusCode::BAD_REQUEST);
+ assert_eq!(save(json!({"captcha_timeout_minutes": 3})).await, StatusCode::OK);
+ assert_eq!(get().await, 3);
+ assert_eq!(kwnt::server::human_steps::captcha_timeout(&state).await, Duration::from_secs(180));
+}
diff --git a/tests/fixtures/captcha/arkose.html b/tests/fixtures/captcha/arkose.html
new file mode 100644
index 00000000..cf2a5e47
--- /dev/null
+++ b/tests/fixtures/captcha/arkose.html
@@ -0,0 +1 @@
+<!doctype html><title>Arkose</title><body style="margin:0;font:16px sans-serif"><h1>Sign up</h1><form><iframe title="widget" style="width:400px;height:400px;border:0" src="https://client-api.arkoselabs.com/fc/gc/?token=abc" srcdoc="&lt;p&gt;widget&lt;/p&gt;"></iframe></form></body>
diff --git a/tests/fixtures/captcha/article.html b/tests/fixtures/captcha/article.html
new file mode 100644
index 00000000..c059bb97
--- /dev/null
+++ b/tests/fixtures/captcha/article.html
@@ -0,0 +1,4 @@
+<!doctype html><title>How slider CAPTCHAs work</title><body style="font:16px sans-serif">
+<article><h1>How slider CAPTCHAs work</h1>
+<p>Many sites ask you to drag the slider or drag the puzzle piece into place. Researchers found these checks easy for bots.</p>
+<p>Slide to complete the puzzle is the usual prompt.</p></article></body>
diff --git a/tests/fixtures/captcha/consent_accept_only.html b/tests/fixtures/captcha/consent_accept_only.html
new file mode 100644
index 00000000..67f035ba
--- /dev/null
+++ b/tests/fixtures/captcha/consent_accept_only.html
@@ -0,0 +1,5 @@
+<!doctype html><title>untouched</title><body style="font:16px sans-serif"><p>Shop</p>
+<div class="cookie-consent" style="position:fixed;bottom:0;left:0;right:0;height:100px;background:#fff">
+ We use cookies. <button onclick="document.title='accepted'">Accept all</button>
+ <button onclick="document.title='accepted'">OK</button> <button onclick="document.title='settings'">Manage settings</button>
+</div></body>
diff --git a/tests/fixtures/captcha/consent_onetrust.html b/tests/fixtures/captcha/consent_onetrust.html
new file mode 100644
index 00000000..f0987eb1
--- /dev/null
+++ b/tests/fixtures/captcha/consent_onetrust.html
@@ -0,0 +1,5 @@
+<!doctype html><title>OneTrust</title><body style="font:16px sans-serif"><p>News</p>
+<div id="onetrust-banner-sdk" style="position:fixed;bottom:0;left:0;right:0;height:120px;background:#fff">
+ <button id="onetrust-accept-btn-handler" onclick="document.title='accepted'">Accept All Cookies</button>
+ <button id="onetrust-reject-all-handler" onclick="document.title='rejected'">Reject All</button>
+</div></body>
diff --git a/tests/fixtures/captcha/consent_tiktok.html b/tests/fixtures/captcha/consent_tiktok.html
new file mode 100644
index 00000000..55dfabcb
--- /dev/null
+++ b/tests/fixtures/captcha/consent_tiktok.html
@@ -0,0 +1,10 @@
+<!doctype html><title>untouched</title><body style="font:16px sans-serif"><p>For You</p>
+<tiktok-cookie-banner></tiktok-cookie-banner>
+<button onclick="document.title='wrong'">Decline</button>
+<script>
+ const root = document.querySelector('tiktok-cookie-banner').attachShadow({mode: 'open'});
+ root.innerHTML = '<div class="tiktok-cookie-banner" style="position:fixed;bottom:0;left:0;right:0;height:100px;background:#fff">'
+ + '<button id="a">Allow all</button> <button id="d">Decline optional cookies</button></div>';
+ root.getElementById('a').onclick = () => document.title = 'accepted';
+ root.getElementById('d').onclick = () => document.title = 'declined';
+</script></body>
diff --git a/tests/fixtures/captcha/datadome.html b/tests/fixtures/captcha/datadome.html
new file mode 100644
index 00000000..bae7f8f0
--- /dev/null
+++ b/tests/fixtures/captcha/datadome.html
@@ -0,0 +1 @@
+<!doctype html><title>DataDome</title><body style="margin:0;font:16px sans-serif"><h1>Sign up</h1><form><iframe title="widget" style="width:400px;height:500px;border:0" src="https://geo.captcha-delivery.com/captcha/?initialCid=abc&amp;cid=def" srcdoc="&lt;p&gt;widget&lt;/p&gt;"></iframe></form></body>
diff --git a/tests/fixtures/captcha/dialog_puzzle.html b/tests/fixtures/captcha/dialog_puzzle.html
new file mode 100644
index 00000000..d6d97644
--- /dev/null
+++ b/tests/fixtures/captcha/dialog_puzzle.html
@@ -0,0 +1,4 @@
+<!doctype html><title>Feed</title><body style="margin:0;font:16px sans-serif">
+<main style="height:1200px">Posts</main>
+<div role="dialog" aria-modal="true" style="position:fixed;left:440px;top:200px;width:400px;height:320px;background:#fff;border:1px solid #999">
+ <p>Drag the slider to fit the puzzle</p></div></body>
diff --git a/tests/fixtures/captcha/geetest.html b/tests/fixtures/captcha/geetest.html
new file mode 100644
index 00000000..dd64a510
--- /dev/null
+++ b/tests/fixtures/captcha/geetest.html
@@ -0,0 +1 @@
+<!doctype html><title>GeeTest</title><body style="margin:0;font:16px sans-serif"><h1>Sign up</h1><form><div class="geetest_box" style="width:340px;height:380px;border:1px solid #ccc"><div class="geetest_slider">Drag the slider</div></div></form></body>
diff --git a/tests/fixtures/captcha/hcaptcha.html b/tests/fixtures/captcha/hcaptcha.html
new file mode 100644
index 00000000..ad5e0f6c
--- /dev/null
+++ b/tests/fixtures/captcha/hcaptcha.html
@@ -0,0 +1 @@
+<!doctype html><title>hCaptcha</title><body style="margin:0;font:16px sans-serif"><h1>Sign up</h1><form><iframe title="widget" style="width:303px;height:78px;border:0" src="https://newassets.hcaptcha.com/captcha/v1/abc/static/hcaptcha.html#frame=checkbox" srcdoc="&lt;p&gt;widget&lt;/p&gt;"></iframe></form></body>
diff --git a/tests/fixtures/captcha/hidden.html b/tests/fixtures/captcha/hidden.html
new file mode 100644
index 00000000..9ebf3630
--- /dev/null
+++ b/tests/fixtures/captcha/hidden.html
@@ -0,0 +1 @@
+<!doctype html><title>Hidden hCaptcha</title><body style="margin:0;font:16px sans-serif"><h1>Sign up</h1><form><div style="display:none"><iframe title="widget" style="width:303px;height:78px;border:0" src="https://newassets.hcaptcha.com/captcha/v1/abc/static/hcaptcha.html" srcdoc="&lt;p&gt;widget&lt;/p&gt;"></iframe></div></form></body>
diff --git a/tests/fixtures/captcha/offscreen.html b/tests/fixtures/captcha/offscreen.html
new file mode 100644
index 00000000..44b9b112
--- /dev/null
+++ b/tests/fixtures/captcha/offscreen.html
@@ -0,0 +1 @@
+<!doctype html><title>Off-screen hCaptcha</title><body style="margin:0;font:16px sans-serif"><h1>Sign up</h1><form><div style="height:2000px">Long form</div><iframe title="widget" style="width:303px;height:78px;border:0" src="https://newassets.hcaptcha.com/captcha/v1/abc/static/hcaptcha.html" srcdoc="&lt;p&gt;widget&lt;/p&gt;"></iframe></form></body>
diff --git a/tests/fixtures/captcha/perimeterx.html b/tests/fixtures/captcha/perimeterx.html
new file mode 100644
index 00000000..fb335749
--- /dev/null
+++ b/tests/fixtures/captcha/perimeterx.html
@@ -0,0 +1 @@
+<!doctype html><title>PerimeterX</title><body style="margin:0;font:16px sans-serif"><h1>Sign up</h1><form><div id="px-captcha" style="width:310px;height:100px;border:1px solid #ccc">Press &amp; Hold</div></form></body>
diff --git a/tests/fixtures/captcha/recaptcha.html b/tests/fixtures/captcha/recaptcha.html
new file mode 100644
index 00000000..34bc8c2a
--- /dev/null
+++ b/tests/fixtures/captcha/recaptcha.html
@@ -0,0 +1 @@
+<!doctype html><title>reCAPTCHA</title><body style="margin:0;font:16px sans-serif"><h1>Sign up</h1><form><iframe title="widget" style="width:304px;height:78px;border:0" src="https://www.google.com/recaptcha/api2/anchor?ar=1&amp;k=test&amp;size=normal" srcdoc="&lt;p&gt;widget&lt;/p&gt;"></iframe></form></body>
diff --git a/tests/fixtures/captcha/recaptcha_v3_badge.html b/tests/fixtures/captcha/recaptcha_v3_badge.html
new file mode 100644
index 00000000..8a8c9518
--- /dev/null
+++ b/tests/fixtures/captcha/recaptcha_v3_badge.html
@@ -0,0 +1 @@
+<!doctype html><title>Invisible reCAPTCHA</title><body style="margin:0;font:16px sans-serif"><h1>Sign up</h1><form><div class="grecaptcha-badge" style="position:fixed;bottom:14px;right:0;width:256px;height:60px"><iframe style="width:256px;height:60px;border:0" src="https://www.google.com/recaptcha/api2/anchor?ar=1&amp;k=test&amp;size=invisible" srcdoc="badge"></iframe></div><p>Newsletter</p></form></body>
diff --git a/tests/fixtures/captcha/shadow.html b/tests/fixtures/captcha/shadow.html
new file mode 100644
index 00000000..80f9df21
--- /dev/null
+++ b/tests/fixtures/captcha/shadow.html
@@ -0,0 +1,6 @@
+<!doctype html><title>Shadow host</title><body style="margin:0">
+<div id="host"></div>
+<script>
+ const root = document.getElementById('host').attachShadow({mode: 'open'});
+ root.innerHTML = '<div class="captcha-verify-container" style="position:fixed;left:100px;top:100px;width:360px;height:300px;background:#eee">Verify</div>';
+</script></body>
diff --git a/tests/fixtures/captcha/tiktok_slider.html b/tests/fixtures/captcha/tiktok_slider.html
new file mode 100644
index 00000000..81ec856d
--- /dev/null
+++ b/tests/fixtures/captcha/tiktok_slider.html
@@ -0,0 +1,30 @@
+<!doctype html><title>TikTok - Make Your Day</title>
+<style>
+ body{margin:0;font:16px sans-serif} main{height:2000px;padding:20px}
+ #captcha-verify-container-main-page{position:fixed;left:460px;top:180px;width:360px;height:380px;background:#fff;
+ border-radius:8px;box-shadow:0 0 0 9999px rgba(0,0,0,.5)}
+ #track{position:absolute;left:20px;top:300px;width:320px;height:40px;background:#eee;border-radius:20px}
+ #knob{position:absolute;left:0;top:0;width:60px;height:40px;background:#fe2c55;border-radius:20px;cursor:grab}
+</style>
+<main><h1>For You</h1><p>Video feed</p></main>
+<div id="captcha-verify-container-main-page" class="TUXModal captcha-verify-container">
+ <div class="captcha_verify_bar">Drag the puzzle piece into place</div>
+ <div id="track"><div id="knob"></div></div>
+</div>
+<script>
+ // Solved when the knob is dragged at least 200px with the button held, like TikTok's slider
+ const knob = document.getElementById('knob'), modal = document.getElementById('captcha-verify-container-main-page');
+ let start = null; window.dragLog = [];
+ knob.addEventListener('mousedown', e => { start = e.clientX; dragLog.push('down:' + e.buttons); });
+ document.addEventListener('mousemove', e => {
+ if (start === null) return;
+ dragLog.push('move:' + e.buttons);
+ knob.style.left = Math.max(0, Math.min(260, e.clientX - start)) + 'px';
+ });
+ document.addEventListener('mouseup', e => {
+ if (start === null) return;
+ dragLog.push('up:' + e.buttons);
+ const moved = e.clientX - start; start = null;
+ if (moved >= 200) { modal.remove(); document.title = 'TikTok - solved'; } else { knob.style.left = '0px'; }
+ });
+</script>
diff --git a/tests/fixtures/captcha/turnstile.html b/tests/fixtures/captcha/turnstile.html
new file mode 100644
index 00000000..719319d3
--- /dev/null
+++ b/tests/fixtures/captcha/turnstile.html
@@ -0,0 +1 @@
+<!doctype html><title>Turnstile</title><body style="margin:0;font:16px sans-serif"><h1>Sign up</h1><form><iframe title="widget" style="width:300px;height:65px;border:0" src="https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/if/ov2/av0/rcv0/0/abc/light/normal" srcdoc="&lt;p&gt;widget&lt;/p&gt;"></iframe></form></body>