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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
CAPTCHA probe: skip look-alikes and never scroll
Lin (kwant bot)90dc601fba04
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex a2338a60..abb017af 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -144,7 +144,11 @@ pub fn detect_bot_wall(url: &str, title: &str, text: &str) -> Option<&'static stfn 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)?; }+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir)?;+ #[cfg(unix)]+ { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?; }+ }let tmp = path.with_extension("tmp");let mut options = std::fs::OpenOptions::new();options.write(true).create(true).truncate(true);@@ -157,8 +161,12 @@ fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {}/// 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.+/// frames) and returns `{kind, x, y, width, height}` in viewport pixels, or null. Never scrolls:+/// a widget below the fold comes back with `offscreen: true` and no usable box.+///+/// Look-alikes are skipped: a reCAPTCHA v2 checkbox only counts while its challenge (bframe) is+/// open or the page is otherwise a wall (no field to fill, little text), and phrases like+/// "press and hold" only count inside an element whose id or class looks like a CAPTCHA.pub const CAPTCHA_PROBE_JS: &str = r##"(function () {var VENDORS = [['recaptcha', /(^|\.)google\.com\/recaptcha\/|recaptcha\.net\/recaptcha\//i],@@ -176,6 +184,8 @@ pub const CAPTCHA_PROBE_JS: &str = r##"(function () {['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;+ // ids/classes a real challenge box carries; a cookie or newsletter dialog doesn't+ var CAPTCHA_LIKE = /captcha|challenge|verif(y|ication)|secsdk|geetest|(^|[\s_-])(px|dd)[-_]/;var vw = window.innerWidth, vh = window.innerHeight;function visible(el, rect) {if (rect.width < 30 || rect.height < 30) return false;@@ -197,29 +207,34 @@ pub const CAPTCHA_PROBE_JS: &str = r##"(function () {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;+ if (w < 10 || h < 10) return {kind: kind, offscreen: true, x: 0, y: 0, width: 0, height: 0};return {kind: kind, x: Math.round(x), y: Math.round(y), width: Math.round(w), height: Math.round(h)};}+ function captchaLike(n) {+ var tag = ((n.id || '') + ' ' + (typeof n.className === 'string' ? n.className : '')).toLowerCase();+ return CAPTCHA_LIKE.test(tag);+ }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;- }+ if (n.nodeType === 1 && captchaLike(n)) return n;n = n.parentNode || n.host;}return null;}+ // A page that is nothing but the check (Google's "sorry" page, a bare verify form): no field a+ // person would fill in and little text. A contact form or a page with a footer form isn't.+ function wallPage() {+ var fields = document.querySelectorAll('input, textarea, select');+ for (var i = 0; i < fields.length; i++) {+ var t = (fields[i].getAttribute('type') || 'text').toLowerCase();+ if (fields[i].tagName === 'INPUT' && /^(hidden|submit|button|image|reset|checkbox|radio)$/.test(t)) continue;+ var r = fields[i].getBoundingClientRect();+ if (r.width > 0 && r.height > 0) return false;+ }+ return ((document.body && document.body.innerText) || '').trim().length < 1000;+ }var roots = [];function collect(root, depth) {if (!root || depth > 6) return;@@ -234,7 +249,7 @@ pub const CAPTCHA_PROBE_JS: &str = r##"(function () {}}collect(document, 0);- var found = null;+ var found = null, anchor = 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++) {@@ -242,10 +257,23 @@ pub const CAPTCHA_PROBE_JS: &str = r##"(function () {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; }+ if (!VENDORS[v][1].test(src)) continue;+ if (VENDORS[v][0] === 'recaptcha') {+ if (/recaptcha\/(api2|enterprise)\/bframe/i.test(src)) {+ // Google parks a closed challenge at top:-10000px and hides it+ var b = box('recaptcha', frames[f]);+ if (b && frames[f].getBoundingClientRect().top + window.scrollY > -1000) found = b;+ } else if (!anchor) {+ anchor = frames[f];+ }+ } else {+ found = box(VENDORS[v][0], frames[f]);+ }+ break;}}}+ if (!found && anchor && wallPage()) found = box('recaptcha', anchor);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]);@@ -275,19 +303,32 @@ pub struct CaptchaHit {pub y: f64,pub width: f64,pub height: f64,+ /// The widget is on the page but outside the viewport (the probe never scrolls), so the box+ /// is empty and shouldn't be pointed at.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub offscreen: bool,}impl CaptchaHit {- /// Validates what the page returned: a known kind and a finite box inside the viewport.+ /// Validates what the page returned: a known kind and a finite box inside the viewport, or an+ /// off-screen widget without a box.pub fn parse(value: &Value) -> Option<Self> {let kind = value.get("kind")?.as_str()?;if !CAPTCHA_KINDS.contains(&kind) { return None; }+ if value.get("offscreen").and_then(Value::as_bool) == Some(true) {+ return Some(Self { kind: kind.to_string(), x: 0.0, y: 0.0, width: 0.0, height: 0.0, offscreen: true });+ }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 })+ Some(Self { kind: kind.to_string(), x, y, width, height, offscreen: false })+ }++ /// The box, when it's on screen and worth pointing the person's view at.+ pub fn on_screen(self) -> Option<Self> {+ (!self.offscreen).then_some(self)}pub fn label(&self) -> &'static str {diff --git a/src/server/human_steps.rs b/src/server/human_steps.rsindex 2d43266c..cea54c1a 100644--- a/src/server/human_steps.rs+++ b/src/server/human_steps.rs@@ -433,7 +433,7 @@ 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 target = CaptchaHit::parse(&page["captcha"]).and_then(CaptchaHit::on_screen);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 {@@ -483,7 +483,7 @@ async fn watch_captcha(state: AppState, id: String, mut seen: bool) {Some((true, hit)) => {seen = true;misses = 0;- if let Some(target_json) = hit.and_then(|h| serde_json::to_string(&h).ok()) {+ if let Some(target_json) = hit.and_then(CaptchaHit::on_screen).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;diff --git a/tests/captcha_test.rs b/tests/captcha_test.rsindex a0faccdf..efafda26 100644--- a/tests/captcha_test.rs+++ b/tests/captcha_test.rs@@ -111,8 +111,11 @@ async fn the_probe_finds_each_vendor_with_its_box_and_ignores_lookalikes() {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] = [+ let cases: [(&str, Option<Expected>); 20] = [+ // a bare sign-up form with nothing but the checkbox counts as a wall("recaptcha.html", Some(("recaptcha", 304.0, 78.0))),+ // an open image challenge counts on any page, with the challenge's box+ ("recaptcha_challenge.html", Some(("recaptcha", 400.0, 580.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))),@@ -121,24 +124,38 @@ async fn the_probe_finds_each_vendor_with_its_box_and_ignores_lookalikes() {("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+ // a slider prompt in a captcha-like box 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),+ // look-alikes: a v2 checkbox on a contact form or in a footer form is something to tick+ // when submitting, not a wall, and neither is its closed challenge; "press and hold" in a+ // newsletter dialog or a sticky cookie bar isn't a CAPTCHA+ ("contact_recaptcha.html", None),+ ("footer_recaptcha.html", None),+ ("recaptcha_challenge_closed.html", None),+ ("consent_dialog_phrases.html", None),+ // below the fold: found, but without a box, and the page isn't scrolled+ ("offscreen.html", Some(("hcaptcha", 0.0, 0.0))),];for (file, want) in cases {open(&ctrl, &format!("{base}{file}")).await;let hit = ctrl.probe_captcha().await.unwrap();+ let scrolled = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": "window.scrollX + window.scrollY", "returnByValue": true})).await.unwrap();+ assert_eq!(scrolled["result"]["value"].as_f64(), Some(0.0), "{file}: the probe must never scroll");match (want, hit) {(None, None) => {}+ (Some((kind, 0.0, 0.0)), Some(hit)) => {+ assert_eq!(hit.kind, kind, "{file}");+ assert!(hit.offscreen && hit.clone().on_screen().is_none(), "{file}: {hit:?}");+ }(Some((kind, w, h)), Some(hit)) => {assert_eq!(hit.kind, kind, "{file}");+ assert!(!hit.offscreen, "{file}: {hit:?}");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:?}");}@@ -199,6 +216,7 @@ async fn vm_cookies_are_kept_per_bot_across_a_browser_restart() {{use std::os::unix::fs::PermissionsExt;assert_eq!(std::fs::metadata(&jar).unwrap().permissions().mode() & 0o777, 0o600);+ assert_eq!(std::fs::metadata(jar.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700);}assert!(!service.cookie_jar("bot-b").exists() || !std::fs::read_to_string(service.cookie_jar("bot-b")).unwrap().contains("kwnt_test"));diff --git a/tests/fixtures/captcha/consent_dialog_phrases.html b/tests/fixtures/captcha/consent_dialog_phrases.htmlnew file mode 100644index 00000000..240534b5--- /dev/null+++ b/tests/fixtures/captcha/consent_dialog_phrases.html@@ -0,0 +1,6 @@+<!doctype html><title>Shop</title><body style="margin:0;font:16px sans-serif"><main style="height:1200px">Products</main>+<div role="dialog" aria-modal="true" class="newsletter-modal" style="position:fixed;left:440px;top:200px;width:400px;height:320px;background:#fff;border:1px solid #999">+ <p>Join our newsletter! Press and hold the bell to get alerts, or drag the slider to pick how often we write.</p>+ <input type="range"><button>No thanks</button></div>+<div class="cookie-banner" style="position:sticky;bottom:0;height:90px;background:#fff">We use cookies. Press & hold to see details. <button>Reject all</button></div>+</body>diff --git a/tests/fixtures/captcha/contact_recaptcha.html b/tests/fixtures/captcha/contact_recaptcha.htmlnew file mode 100644index 00000000..ac60fdbb--- /dev/null+++ b/tests/fixtures/captcha/contact_recaptcha.html@@ -0,0 +1,5 @@+<!doctype html><title>Contact us</title><body style="margin:0;font:16px sans-serif"><h1>Contact us</h1>+<form><label>Name <input name="name"></label><br><label>Email <input type="email" name="email"></label><br>+<label>Message <textarea name="message"></textarea></label><br>+<iframe title="reCAPTCHA" style="width:304px;height:78px;border:0" src="https://www.google.com/recaptcha/api2/anchor?ar=1&k=test&size=normal" srcdoc="<p>I'm not a robot</p>"></iframe>+<button>Send</button></form></body>diff --git a/tests/fixtures/captcha/dialog_puzzle.html b/tests/fixtures/captcha/dialog_puzzle.htmlindex d6d97644..c1ca7b95 100644--- a/tests/fixtures/captcha/dialog_puzzle.html+++ b/tests/fixtures/captcha/dialog_puzzle.html@@ -1,4 +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">+<div role="dialog" aria-modal="true" class="slider-verify-modal" 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/footer_recaptcha.html b/tests/fixtures/captcha/footer_recaptcha.htmlnew file mode 100644index 00000000..62fab494--- /dev/null+++ b/tests/fixtures/captcha/footer_recaptcha.html@@ -0,0 +1,5 @@+<!doctype html><title>Blog</title><body style="margin:0;font:16px sans-serif">+<article style="height:2400px"><h1>Ten tips for better sleep</h1><p>Keep a regular schedule, dim the lights an hour before bed, and leave the phone in another room.</p></article>+<footer><p>Get the newsletter</p><form><input type="email" placeholder="Email">+<iframe title="reCAPTCHA" style="width:304px;height:78px;border:0" src="https://www.google.com/recaptcha/api2/anchor?ar=1&k=test&size=normal" srcdoc="<p>I'm not a robot</p>"></iframe>+<button>Subscribe</button></form></footer></body>diff --git a/tests/fixtures/captcha/recaptcha_challenge.html b/tests/fixtures/captcha/recaptcha_challenge.htmlnew file mode 100644index 00000000..cf15cf16--- /dev/null+++ b/tests/fixtures/captcha/recaptcha_challenge.html@@ -0,0 +1,5 @@+<!doctype html><title>Contact us</title><body style="margin:0;font:16px sans-serif"><h1>Contact us</h1>+<form><label>Email <input type="email" name="email"></label><br>+<iframe title="reCAPTCHA" style="width:304px;height:78px;border:0" src="https://www.google.com/recaptcha/api2/anchor?ar=1&k=test&size=normal" srcdoc="<p>I'm not a robot</p>"></iframe></form>+<div style="visibility:visible;position:absolute;left:300px;top:100px;z-index:2000000000"><iframe title="recaptcha challenge expires in two minutes" style="width:400px;height:580px;border:0" src="https://www.google.com/recaptcha/api2/bframe?hl=en&k=test" srcdoc="<p>Select all images with buses</p>"></iframe></div>+</body>diff --git a/tests/fixtures/captcha/recaptcha_challenge_closed.html b/tests/fixtures/captcha/recaptcha_challenge_closed.htmlnew file mode 100644index 00000000..5f7c5520--- /dev/null+++ b/tests/fixtures/captcha/recaptcha_challenge_closed.html@@ -0,0 +1,5 @@+<!doctype html><title>Contact us</title><body style="margin:0;font:16px sans-serif"><h1>Contact us</h1>+<form><label>Email <input type="email" name="email"></label><br>+<iframe title="reCAPTCHA" style="width:304px;height:78px;border:0" src="https://www.google.com/recaptcha/api2/anchor?ar=1&k=test&size=normal" srcdoc="<p>I'm not a robot</p>"></iframe></form>+<div style="visibility:hidden;position:absolute;left:0;top:-10000px;z-index:2000000000"><iframe title="recaptcha challenge expires in two minutes" style="width:400px;height:580px;border:0" src="https://www.google.com/recaptcha/api2/bframe?hl=en&k=test" srcdoc="x"></iframe></div>+</body>