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
Browser takeover: links to another app no longer freeze the tab (#280)
Oleksandr Ivanchenko2142801b56dc
diff --git a/frontend/src/components/BrowserTakeoverStage.tsx b/frontend/src/components/BrowserTakeoverStage.tsxindex 3e3f12f0..1d5b8b09 100644--- a/frontend/src/components/BrowserTakeoverStage.tsx+++ b/frontend/src/components/BrowserTakeoverStage.tsx@@ -188,6 +188,8 @@ export const BrowserTakeoverStage: React.FC<BrowserTakeoverStageProps> = ({ botN// Mouse: moves once a frame, presses and releases as they happen, wheel steps summed per frameconst heldButtons = useRef(0);+ // Where the pointer last was on the page, for releases that happen off the stage+ const lastPoint = useRef<{ x: number; y: number } | null>(null);const lastTouch = useRef(-Infinity);const raf = useCallback((fn: () => void) => {requestAnimationFrame(fn);@@ -226,6 +228,7 @@ export const BrowserTakeoverStage: React.FC<BrowserTakeoverStageProps> = ({ botNconst p = toPage(e.clientX, e.clientY, false);if (!p) return;moves.flush();+ lastPoint.current = p;heldButtons.current |= BUTTON_BIT[e.button] ?? 0;sendRef.current({ action: 'mouse', type: 'down', x: p.x, y: p.y, button: buttonName(e.button), buttons: e.buttons || heldButtons.current, click_count: Math.max(1, e.detail || 1), modifiers: mouseModifiers(e, mac) });};@@ -236,6 +239,7 @@ export const BrowserTakeoverStage: React.FC<BrowserTakeoverStageProps> = ({ botNif (!held && !el.contains(e.target as Node)) return;const p = toPage(e.clientX, e.clientY, held);if (!p) return;+ lastPoint.current = p;moves.push({ ...p, buttons: held ? e.buttons || heldButtons.current : 0, modifiers: mouseModifiers(e, mac) });};const onUp = (e: MouseEvent) => {@@ -244,6 +248,7 @@ export const BrowserTakeoverStage: React.FC<BrowserTakeoverStageProps> = ({ botNheldButtons.current &= ~bit;const p = toPage(e.clientX, e.clientY, true);if (!p) return;+ lastPoint.current = p;moves.flush();sendRef.current({ action: 'mouse', type: 'up', x: p.x, y: p.y, button: buttonName(e.button), buttons: heldButtons.current, click_count: Math.max(1, e.detail || 1), modifiers: mouseModifiers(e, mac) });};@@ -259,9 +264,20 @@ export const BrowserTakeoverStage: React.FC<BrowserTakeoverStageProps> = ({ botNwheel.add(p, wheelPixels(e, pageRef.current.height), mouseModifiers(e, mac));};const onBlurWindow = () => {- // Released outside the window: the page shouldn't think a button is still down- if (!heldButtons.current) return;+ // Released outside the window: this window never sees that release, so send it now, or the+ // page still holds the button and the next press gives it an extra mouseup and click+ const held = heldButtons.current;+ if (!held) return;heldButtons.current = 0;+ const p = lastPoint.current;+ if (!controllingRef.current || !p) return;+ moves.flush();+ let left = held;+ for (const [button, bit] of Object.entries(BUTTON_BIT)) {+ if (!(held & bit)) continue;+ left &= ~bit;+ sendRef.current({ action: 'mouse', type: 'up', x: p.x, y: p.y, button: buttonName(Number(button)), buttons: left, click_count: 1, modifiers: 0 });+ }};el.addEventListener('mousedown', onDown);window.addEventListener('mousemove', onMove);diff --git a/frontend/tests/takeoverBlurRelease.test.mjs b/frontend/tests/takeoverBlurRelease.test.mjsnew file mode 100644index 00000000..195fc6ff--- /dev/null+++ b/frontend/tests/takeoverBlurRelease.test.mjs@@ -0,0 +1,85 @@+// Rigel's L2 (0.6.9 QA): a button held on the takeover stage when the window loses focus. The+// window never sees that release, so the stage sends it on blur; before, it only forgot the button,+// the page still held it, and the next press gave the page an extra mouseup and click.+import assert from 'node:assert/strict';+import test from 'node:test';+import { JSDOM } from 'jsdom';+import { loadBundled } from './bundle.mjs';++const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });+const g = globalThis;+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLImageElement', 'Element', 'Node', 'Event', 'FocusEvent', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });+}+g.ResizeObserver = g.window.ResizeObserver = class { observe() {} unobserve() {} disconnect() {} };+// The page image is drawn 1:1 at the top left, so client points are page points+g.HTMLImageElement.prototype.getBoundingClientRect = () => ({ left: 0, top: 0, right: 800, bottom: 600, width: 800, height: 600, x: 0, y: 0 });++const m = await loadBundled(`+ export { default as React } from 'react';+ export { createRoot } from 'react-dom/client';+ export { BrowserTakeoverStage } from './src/components/BrowserTakeoverStage';+`);+const settle = async () => {+ for (let i = 0; i < 30; i++) await new Promise((r) => setTimeout(r, 0));+};+const act = async (fn) => {+ await fn();+ await settle();+};++async function renderStage() {+ const sent = [];+ const stream = {+ connected: true, controlling: true, busy: false, error: null, frame: { id: 1, width: 800, height: 600 }, location: null, tapFocus: null,+ viewport: null, select: null, dialog: null, cursor: 'default', unsupported: new Set(),+ send: (msg) => sent.push(msg), acknowledgeFrame() {}, clearSelect() {}, clearDialog() {}, clearError() {},+ };+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = m.createRoot(host);+ await act(async () => {+ root.render(m.React.createElement(m.BrowserTakeoverStage, {+ botName: 'Ada', pageUrl: 'https://www.tiktok.com/login', stream, image: 'data:image/png;base64,AAAA', onHandBack() {}, onRetryControl() {},+ }));+ });+ const stage = document.querySelector('[data-browser-stage]');+ const img = document.querySelector('[data-browser-page]');+ assert.ok(stage && img, 'the stage and page image are drawn');+ const mouse = (target, type, x, y, button = 0) => act(async () => {+ target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: y, button, detail: 1 }));+ });+ const blur = () => act(async () => { window.dispatchEvent(new FocusEvent('blur')); });+ const unmount = () => act(async () => { root.unmount(); host.remove(); });+ const presses = () => sent.filter((s) => s.action === 'mouse' && (s.type === 'down' || s.type === 'up')).map((s) => `${s.type} ${s.button} ${s.x},${s.y} buttons=${s.buttons}`);+ return { img, mouse, blur, unmount, presses, sent };+}++test('a button held when the window loses focus is released on the page', async () => {+ const s = await renderStage();+ await s.mouse(s.img, 'mousedown', 100, 120);+ await s.mouse(window, 'mousemove', 140, 160);+ await s.blur();+ assert.deepEqual(s.presses(), ['down left 100,120 buttons=1', 'up left 140,160 buttons=0'], 'blur sends the release the window never saw');+ // The next click is one clean down and up: no extra mouseup, no stray click+ await s.mouse(s.img, 'mousedown', 300, 300);+ await s.mouse(window, 'mouseup', 300, 300);+ assert.deepEqual(s.presses().slice(2), ['down left 300,300 buttons=1', 'up left 300,300 buttons=0']);+ await s.unmount();+});++test('every held button is released, and a blur with none held sends nothing', async () => {+ const s = await renderStage();+ await s.blur();+ assert.deepEqual(s.presses(), []);+ await s.mouse(s.img, 'mousedown', 10, 20, 0);+ await s.mouse(s.img, 'mousedown', 10, 20, 2);+ await s.blur();+ assert.deepEqual(s.presses().slice(2), ['up left 10,20 buttons=2', 'up right 10,20 buttons=0']);+ // A release that arrives later anyway isn't sent twice+ await s.mouse(window, 'mouseup', 10, 20, 0);+ await s.blur();+ assert.equal(s.presses().length, 4);+ await s.unmount();+});diff --git a/src/sandbox/app_links.rs b/src/sandbox/app_links.rsnew file mode 100644index 00000000..68be0ee8--- /dev/null+++ b/src/sandbox/app_links.rs@@ -0,0 +1,326 @@+//! Links that open another app (`tiktok://`, `snssdk1233://`, `intent:`, `itms-apps:`...).+//!+//! Chrome answers one with an "Open <app>?" prompt that is tab-modal: while it is up the tab+//! ignores every click and key, yet scripts, animations and screenshots carry on. A headless+//! browser draws the prompt nowhere the live view can see, and DevTools has no way to answer+//! it. It closes only on a cross-site navigation, so even a reload leaves the page dead.+//!+//! kwnt keeps it from opening in the first place: [`GUARD_JS`] runs in an isolated world of every+//! document and cancels a navigation to such a link before it reaches Chrome. What it can't+//! cancel (a frame whose first address is the link) is caught by [`AppLinkWatch`], which tells+//! the live view to step the tab off the page and back, the one thing that closes the prompt.+//! A link that fired while no live view was open is found when one opens: [`PROBE_ARM_JS`] and+//! [`PROBE_READ_JS`] check that the page still gets a mouse move, and a tab that doesn't is+//! stepped off and back the same way.+use std::{collections::VecDeque, time::Duration};+use tokio::time::Instant;++/// The isolated world the guard runs in: the page's own scripts can't see or undo it.+pub const WORLD: &str = "kwnt-applinks";+/// Called from [`WORLD`] with the scheme of a link the guard stopped.+pub const BINDING: &str = "kwntAppLink";++/// Schemes a tab opens itself; everything else is handed to the operating system.+const IN_BROWSER: &[&str] = &[+ "http", "https", "about", "data", "blob", "javascript", "file", "filesystem", "ws", "wss",+ "chrome", "chrome-error", "chrome-extension", "chrome-untrusted", "devtools", "view-source",+];+/// Handed to the operating system without a prompt, so they can't freeze the tab.+const NO_PROMPT: &[&str] = &["mailto", "news", "snews"];++/// Chrome's console line when it refuses a link outright (no user gesture) instead of asking.+pub const REFUSED_LOG: &str = "Not allowed to launch";++/// Cancels navigations to another app in this document. Runs in [`WORLD`], once per world.+pub const GUARD_JS: &str = r#"(() => {+ if (self.__kwntAppLinks || !self.navigation) return;+ self.__kwntAppLinks = true;+ const inBrowser = new Set(__IN_BROWSER__);+ navigation.addEventListener('navigate', (event) => {+ let scheme;+ try { scheme = new URL(event.destination.url).protocol.slice(0, -1).toLowerCase(); } catch (e) { return; }+ if (inBrowser.has(scheme) || !event.cancelable) return;+ event.preventDefault();+ try { self.__BINDING__(scheme); } catch (e) {}+ });+})()"#;++/// [`GUARD_JS`] with its scheme list and binding filled in.+pub fn guard_js() -> String {+ GUARD_JS+ .replace("__IN_BROWSER__", &serde_json::to_string(IN_BROWSER).unwrap_or_default())+ .replace("__BINDING__", BINDING)+}++/// The scheme of `url` when it opens another app, lowercased. A link the tab opens itself, or+/// one that isn't a URL, gives `None`.+pub fn app_scheme(url: &str) -> Option<String> {+ let (scheme, _) = url.trim_start().split_once(':')?;+ let mut chars = scheme.chars();+ if !chars.next()?.is_ascii_alphabetic() || !chars.all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c)) {+ return None;+ }+ let scheme = scheme.to_ascii_lowercase();+ (!IN_BROWSER.contains(&scheme.as_str())).then_some(scheme)+}++/// The scheme of `url` when it is a link to another app a bot must not open: Chrome would hand it+/// to the operating system or freeze the tab behind an "Open <app>?" prompt. `host:port` without+/// a scheme (`localhost:8080`) isn't one, and neither is a Windows drive (`C:\…`, `c:/…`).+pub fn refused_scheme(url: &str) -> Option<String> {+ let scheme = app_scheme(url).filter(|s| s.len() > 1)?;+ let rest = url.trim_start()[scheme.len() + 1..].trim_start_matches('/');+ (!rest.starts_with(|c: char| c.is_ascii_digit())).then_some(scheme)+}++/// Why a bot's browser didn't open `url`, a link to another app.+pub fn refused_text(url: &str, scheme: &str) -> String {+ let shown: String = url.trim().chars().take(120).collect();+ format!("{shown} opens another app ({scheme}:), not a web page, so the browser didn't open it: kwnt only opens web pages (http:// and https://). \+ Use a web address instead, or another way on the page such as signing in with a password or code.")+}++/// The scheme of `url` when following it makes Chrome ask whether to open another app.+pub fn prompting_scheme(url: &str) -> Option<String> {+ app_scheme(url).filter(|s| !NO_PROMPT.contains(&s.as_str()))+}++/// A scheme as the person may read it: a scheme the guard reported, checked and cut short.+pub fn shown_scheme(raw: &str) -> Option<String> {+ let scheme = raw.trim().trim_end_matches(':');+ (scheme.len() <= 40).then(|| app_scheme(&format!("{scheme}:"))).flatten()+}++/// How long after a link starts loading Chrome may still refuse it outright (no prompt).+pub const SETTLE: Duration = Duration::from_millis(400);+/// At most this many recoveries in [`WINDOW`]: a page that opens its app again on every load+/// would otherwise be stepped off and back forever.+pub const MAX_RECOVERIES: usize = 3;+pub const WINDOW: Duration = Duration::from_secs(60);+/// The person is told about a stopped link at most this often.+pub const NOTICE_GAP: Duration = Duration::from_secs(5);++/// What the live view should do about a link to another app. The scheme is `None` when the+/// tab was found ignoring input without the live view seeing the link (it fired before it opened).+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Verdict {+ /// Chrome is asking: step the tab off the page and back, then tell the person.+ Recover(Option<String>),+ /// Chrome is asking again too often: leave the page as it is and tell the person why.+ GiveUp(Option<String>),+}++/// Marks where a mouse move should land in the page and starts counting the moves that reach+/// it: `[x, y]`, or `null` when there is no point to probe (the page is all frames, or has no+/// size). Runs in the page's main world; the probe removes itself in [`PROBE_READ_JS`].+pub const PROBE_ARM_JS: &str = r#"(() => {+ const w = innerWidth, h = innerHeight, key = Symbol.for('kwnt.inputProbe');+ if (!(w > 32 && h > 32)) return null;+ for (const [x, y] of [[8, 8], [w - 9, h - 9], [8, h - 9], [w - 9, 8], [w >> 1, h >> 1]]) {+ const el = document.elementFromPoint(x, y);+ if (!el || /^(IFRAME|FRAME|EMBED|OBJECT|FENCEDFRAME|PORTAL)$/.test(el.tagName)) continue;+ if (self[key]) removeEventListener('mousemove', self[key].on, true);+ const probe = { n: 0, on: () => { probe.n++; } };+ self[key] = probe;+ addEventListener('mousemove', probe.on, true);+ return [x, y];+ }+ return null;+})()"#;++/// How many probe moves reached the page, or -1 when the probe is gone (a new document).+pub const PROBE_READ_JS: &str = r#"(() => {+ const key = Symbol.for('kwnt.inputProbe'), probe = self[key];+ if (!probe) return -1;+ removeEventListener('mousemove', probe.on, true);+ delete self[key];+ return probe.n;+})()"#;++/// Watches the page's navigations for a link to another app that got past the guard.+#[derive(Debug, Default)]+pub struct AppLinkWatch {+ pending: Option<(String, Instant)>,+ recoveries: VecDeque<Instant>,+ noticed: Option<Instant>,+}++impl AppLinkWatch {+ /// A frame started loading `url`.+ pub fn started(&mut self, url: &str, now: Instant) {+ if self.pending.is_some() { return; }+ if let Some(scheme) = prompting_scheme(url) { self.pending = Some((scheme, now + SETTLE)); }+ }++ /// Chrome logged `text`. A refusal means it didn't ask, so the page still takes input.+ pub fn logged(&mut self, text: &str) {+ if text.starts_with(REFUSED_LOG) { self.pending = None; }+ }++ /// When [`Self::due`] has something to say.+ pub fn deadline(&self) -> Option<Instant> {+ self.pending.as_ref().map(|(_, at)| *at)+ }++ /// What to do once the link has had [`SETTLE`] to be refused.+ pub fn due(&mut self, now: Instant) -> Option<Verdict> {+ let (_, at) = self.pending.as_ref()?;+ if now < *at { return None; }+ let (scheme, _) = self.pending.take()?;+ Some(self.verdict(Some(scheme), now))+ }++ /// The tab was found ignoring input when the live view opened: a link fired before it did.+ /// Counts against the same cap as a link the live view saw.+ pub fn stuck(&mut self, now: Instant) -> Verdict {+ self.verdict(None, now)+ }++ fn verdict(&mut self, scheme: Option<String>, now: Instant) -> Verdict {+ while self.recoveries.front().is_some_and(|t| now.duration_since(*t) >= WINDOW) { self.recoveries.pop_front(); }+ if self.recoveries.len() >= MAX_RECOVERIES { return Verdict::GiveUp(scheme); }+ self.recoveries.push_back(now);+ Verdict::Recover(scheme)+ }++ /// Whether the person may be told about another stopped link now.+ pub fn may_notice(&mut self, now: Instant) -> bool {+ if self.noticed.is_some_and(|t| now.duration_since(t) < NOTICE_GAP) { return false; }+ self.noticed = Some(now);+ true+ }+}++/// Said when the guard stopped a link to another app.+pub fn stopped_text(scheme: &str) -> String {+ format!("This page tried to open another app ({scheme}:), which can't open from here, so kwnt stopped it. Use another way on the page, such as signing in with a password or code.")+}++/// Said after kwnt stepped the tab off the page and back to close Chrome's prompt.+pub fn recovered_text(scheme: Option<&str>) -> String {+ match scheme {+ Some(scheme) => format!("This page tried to open another app ({scheme}:), and the browser stopped taking clicks and keys while it waited. kwnt reloaded the page so you can use it again."),+ None => "This page had stopped taking clicks and keys, most likely because it tried to open another app before you opened the view. kwnt reloaded the page so you can use it again.".into(),+ }+}++/// Said when the page keeps opening its app and kwnt stopped reloading it.+pub fn gave_up_text(scheme: Option<&str>) -> String {+ match scheme {+ Some(scheme) => format!("This page keeps trying to open another app ({scheme}:), and the browser ignores clicks and keys while it does. Open another page from the address bar to carry on."),+ None => "This page keeps ignoring clicks and keys, most likely because it keeps trying to open another app. Open another page from the address bar to carry on.".into(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn links_to_other_apps_are_told_from_pages_the_tab_opens_itself() {+ for url in ["snssdk1233://login?x=1", "tiktok://user", "TikTok://x", "intent://scan/#Intent;scheme=z;end", "itms-apps://a", "zoommtg:join", "web+app:x"] {+ assert!(prompting_scheme(url).is_some(), "{url}");+ }+ assert_eq!(prompting_scheme("TikTok://x").as_deref(), Some("tiktok"));+ for url in ["https://www.tiktok.com/login", "http://a", "about:blank", "about:srcdoc", "data:text/html,x", "blob:https://a/1", "javascript:void(0)",+ "chrome-error://chromewebdata/", "file:///tmp/a", "", "no scheme", "/relative", "1abc:x", "a b:c"] {+ assert_eq!(prompting_scheme(url), None, "{url}");+ }+ // mail links are handed over without a prompt, so they can't freeze the tab+ assert_eq!(app_scheme("mailto:[email protected]").as_deref(), Some("mailto"));+ assert_eq!(prompting_scheme("mailto:[email protected]"), None);+ assert_eq!(shown_scheme("snssdk1233:").as_deref(), Some("snssdk1233"));+ assert_eq!(shown_scheme("https"), None);+ assert_eq!(shown_scheme(&"a".repeat(41)), None);+ assert_eq!(shown_scheme("<b>x</b>"), None);+ }++ #[test]+ fn the_guard_lets_the_tab_open_what_it_opens_itself() {+ let js = guard_js();+ for scheme in IN_BROWSER { assert!(js.contains(&format!("\"{scheme}\"")), "{scheme}"); }+ assert!(js.contains("self.kwntAppLink(scheme)"));+ assert!(js.contains("event.preventDefault()"));+ assert!(!js.contains("__IN_BROWSER__") && !js.contains("__BINDING__"), "{js}");+ }++ #[test]+ fn a_link_chrome_refuses_outright_needs_no_recovery() {+ let mut watch = AppLinkWatch::default();+ let t = Instant::now();+ watch.started("snssdk1233://login", t);+ assert_eq!(watch.deadline(), Some(t + SETTLE));+ watch.logged("Not allowed to launch 'snssdk1233://login' because a user gesture is required.");+ assert_eq!(watch.due(t + SETTLE), None);+ assert_eq!(watch.deadline(), None);+ // web pages and mail links never start one+ watch.started("https://www.tiktok.com/", t);+ watch.started("mailto:[email protected]", t);+ assert_eq!(watch.deadline(), None);+ }++ #[test]+ fn a_prompt_is_recovered_after_it_settles_a_few_times_a_minute_at_most() {+ let mut watch = AppLinkWatch::default();+ let t = Instant::now();+ for i in 0..MAX_RECOVERIES as u64 {+ let at = t + Duration::from_secs(i);+ watch.started("snssdk1233://login", at);+ watch.started("tiktok://second-in-the-same-burst", at);+ assert_eq!(watch.due(at + SETTLE / 2), None, "Chrome may still refuse it");+ assert_eq!(watch.due(at + SETTLE), Some(Verdict::Recover(Some("snssdk1233".into()))));+ assert_eq!(watch.due(at + SETTLE), None, "once per link");+ }+ watch.started("snssdk1233://login", t + Duration::from_secs(10));+ assert_eq!(watch.due(t + Duration::from_secs(11)), Some(Verdict::GiveUp(Some("snssdk1233".into()))));+ // a minute after the first, one may run again+ watch.started("snssdk1233://login", t + WINDOW);+ assert_eq!(watch.due(t + WINDOW + SETTLE), Some(Verdict::Recover(Some("snssdk1233".into()))));+ }++ #[test]+ fn a_tab_found_stuck_is_recovered_under_the_same_cap() {+ let mut watch = AppLinkWatch::default();+ let t = Instant::now();+ assert_eq!(watch.stuck(t), Verdict::Recover(None));+ for i in 1..MAX_RECOVERIES as u64 {+ watch.started("snssdk1233://login", t + Duration::from_secs(i));+ assert!(matches!(watch.due(t + Duration::from_secs(i) + SETTLE), Some(Verdict::Recover(_))));+ }+ assert_eq!(watch.stuck(t + Duration::from_secs(10)), Verdict::GiveUp(None));+ assert_eq!(watch.stuck(t + WINDOW), Verdict::Recover(None));+ assert!(recovered_text(None).contains("reloaded the page"));+ assert!(!gave_up_text(None).contains("reloaded"));+ }++ #[test]+ fn a_bot_is_refused_links_to_other_apps_but_not_web_pages() {+ for (url, scheme) in [("tiktok://open", "tiktok"), ("snssdk1233://login", "snssdk1233"), ("intent://scan/#Intent;scheme=zxing;end", "intent"),+ ("intent:#Intent;end", "intent"), (" TikTok://x", "tiktok"), ("mailto:[email protected]", "mailto"), ("itms-apps://a", "itms-apps"), ("zoommtg:join", "zoommtg")] {+ assert_eq!(refused_scheme(url).as_deref(), Some(scheme), "{url}");+ }+ for url in ["https://www.tiktok.com/login", "http://a", "about:blank", "data:text/html,x", "javascript:void(0)", "chrome://version",+ "localhost:8080", "example.com:443/x", "127.0.0.1:9381", "www.tiktok.com", "", "/relative", "C:\\Users\\me\\file.txt", "c:/Users/me/file.txt"] {+ assert_eq!(refused_scheme(url), None, "{url}");+ }+ let text = refused_text("tiktok://open", "tiktok");+ assert!(text.contains("another app (tiktok:)") && text.contains("only opens web pages"), "{text}");+ assert!(refused_text(&"x".repeat(500), "x").len() < 400, "a long link is cut short");+ }++ #[test]+ fn the_input_probe_skips_frames_and_cleans_up() {+ assert!(PROBE_ARM_JS.contains("elementFromPoint") && PROBE_ARM_JS.contains("IFRAME"));+ assert!(PROBE_ARM_JS.contains("addEventListener('mousemove'") && PROBE_READ_JS.contains("removeEventListener('mousemove'"));+ assert!(PROBE_READ_JS.contains("return -1"), "a new document is no proof the tab is stuck");+ }++ #[test]+ fn notices_are_spaced_out() {+ let mut watch = AppLinkWatch::default();+ let t = Instant::now();+ assert!(watch.may_notice(t));+ assert!(!watch.may_notice(t + NOTICE_GAP / 2));+ assert!(watch.may_notice(t + NOTICE_GAP));+ }+}diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex 26246cc9..f98e0c25 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -31,6 +31,24 @@ pub(crate) fn cdp_ws_request(url: &str) -> Result<tokio_tungstenite::tungstenite}/// Opens a DevTools WebSocket (see [`cdp_ws_request`]).+/// Keeps every document of the page from opening another app (see [`super::app_links`]), for as+/// long as this DevTools connection lasts. Nobody listens for the guard's binding here.+async fn guard_app_links(ws: &mut WsStream, msg_id: &AtomicU64) {+ let id = msg_id.fetch_add(1, Ordering::SeqCst);+ let request = json!({+ "id": id,+ "method": "Page.addScriptToEvaluateOnNewDocument",+ "params": {"source": super::app_links::guard_js(), "worldName": super::app_links::WORLD, "runImmediately": true},+ });+ let sent = match ws.send(Message::Text(request.to_string())).await {+ Ok(()) => timeout(Duration::from_secs(5), await_reply(ws, id)).await.map_err(|_| BrowserError::Timeout).and_then(|r| r.and_then(|r| r)),+ Err(e) => Err(BrowserError::Ws(e.to_string())),+ };+ if let Err(e) = sent {+ tracing::warn!(error = %e, "couldn't guard the browser against links to other apps");+ }+}+pub(crate) async fn connect_cdp(url: &str) -> Result<WsStream, BrowserError> {let (ws, _) = connect_async(cdp_ws_request(url)?).await.map_err(|e| BrowserError::Ws(e.to_string()))?;Ok(ws)@@ -428,6 +446,16 @@ pub fn refuse_file_path(target: &str) -> Result<(), BrowserError> {Ok(())}+/// A link to another app (`tiktok://`, `snssdk1233://`, `intent:`) is refused before it reaches+/// Chrome: Chrome would put up an "Open <app>?" prompt the bot can't see or answer, and the tab+/// ignores every click and key until a cross-site navigation (see [`super::app_links`]).+pub fn refuse_app_link(target: &str) -> Result<(), BrowserError> {+ match super::app_links::refused_scheme(target) {+ Some(scheme) => Err(BrowserError::NotWebAddress(super::app_links::refused_text(target, &scheme))),+ None => Ok(()),+ }+}+/// Recognises CAPTCHA / anti-bot interstitials that replace the requested content.pub fn detect_bot_wall(url: &str, title: &str, text: &str) -> Option<&'static str> {let url = url.to_lowercase();@@ -1106,6 +1134,10 @@ impl BrowserController {let mut ws = connect_cdp(&ws_url).await?;tracing::debug!(target_id = ?self.target_id, "opened a DevTools connection");self.reapply_viewport(&mut ws).await;+ // the browser-level endpoint has no page to guard (Page.* isn't found there)+ if ws_url.contains("/devtools/page/") {+ guard_app_links(&mut ws, &self.msg_id).await;+ }**guard = Some(ws);}Ok(())@@ -1280,6 +1312,9 @@ impl BrowserController {/// fails the same way. The person's own navigation is [`Self::navigate_unlocked`].pub async fn navigate(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {let _permit = self.control.try_read().map_err(|_| BrowserError::HumanControl)?;+ // a path first: `C:\Users\…` would otherwise read as a link to an app called `c:`+ refuse_file_path(target_url)?;+ refuse_app_link(target_url)?;self.site_guard.set_actor(super::site_guard::Actor::Bot);self.site_guard.check(target_url).await.map_err(BrowserError::SiteRule)?;let _ = self.site_guard.take_refusal();@@ -1330,6 +1365,7 @@ impl BrowserController {pub async fn navigate_unlocked(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {refuse_file_path(target_url)?;+ refuse_app_link(target_url)?;self.progress.lock().unwrap_or_else(|e| e.into_inner()).reset();let _ = self.collect_captured_credentials().await;let _ = self.send_cdp_command("Page.enable", json!({})).await;diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex c52c8980..d67c3387 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -1,3 +1,4 @@+pub mod app_links;pub mod bitwarden;pub mod browser;pub mod browser_history;diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rsindex 0a0ce875..86674070 100644--- a/src/server/browser_stream.rs+++ b/src/server/browser_stream.rs@@ -7,6 +7,7 @@//! wait behind a bot's command.use super::browser_input::{self as bi, KeyEvent, KeyKind, MouseButton, RateLimit};use super::{routes::get_or_create_browser_controller, AppState};+use crate::sandbox::app_links::{self, AppLinkWatch, Verdict};use crate::sandbox::browser::{BrowserController, BrowserError, HeldPointer, FOCUSED_EDITABLE_JS, MOUSE_BUTTON_BITS};use crate::sandbox::browser_history::HistoryDirection;use axum::{extract::{Path, State, WebSocketUpgrade, ws::{Message, WebSocket}}, http::{HeaderMap, StatusCode}, response::Response};@@ -244,7 +245,7 @@ impl Cdp {None => Ok(value.get("result").cloned().unwrap_or(Value::Null)),});}- } else if value.get("method").is_some() && event_tx.send(value).await.is_err() {+ } else if value.get("method").is_some() && wanted(&value) && event_tx.send(value).await.is_err() {break;}}@@ -277,6 +278,20 @@ impl Cdp {}}+/// Whether the stream acts on this DevTools event. Runtime and Log are on only for the app-link+/// guard, and turning them on makes Chrome replay everything the page has logged: a page that+/// logged a few hundred lines would fill the event queue before the stream drains it, and every+/// reply behind them (the screencast's start) would wait until it timed out. So the rest of+/// those two domains is dropped as it arrives, and a noisy page can't stall the reader.+fn wanted(event: &Value) -> bool {+ let method = event["method"].as_str().unwrap_or_default();+ match method {+ "Runtime.bindingCalled" => event["params"]["name"] == app_links::BINDING,+ "Log.entryAdded" => event["params"]["entry"]["text"].as_str().is_some_and(|text| text.starts_with(app_links::REFUSED_LOG)),+ _ => !method.starts_with("Runtime.") && !method.starts_with("Log."),+ }+}+async fn settle(reply: Reply, wait: Duration) -> Result<Value, BrowserError> {match timeout(wait, reply).await {Ok(Ok(result)) => result,@@ -867,16 +882,34 @@ async fn stream(let mut lease: Option<OwnedRwLockWriteGuard<()>> = None;let result = async {cdp.call("Page.enable", json!({}), Duration::from_secs(10)).await?;+ guard_app_links(cdp).await;let (w, h) = shared.view();cdp.call("Page.startScreencast", screencast_params(w as u32, h as u32), Duration::from_secs(10)).await?;+ // a link to another app may have fired before the view opened, with nobody to close+ // Chrome's prompt: check the page still gets input, off the loop. Not while a button is+ // held, where a move would be part of someone's drag.+ let held = ctrl.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()).is_some();+ let mut stuck_check = (!held).then(|| { let cdp = cdp.clone(); tokio::spawn(async move { input_is_stuck(&cdp).await }) });let mut last_client = Instant::now();let mut heartbeat = tokio::time::interval(Duration::from_secs(10));let mut frames = FrameGate::default();let mut location_tick = tokio::time::interval(Duration::from_secs(2));let mut moves = RateLimit::new(bi::MOVES_PER_SECOND, 10.0, std::time::Instant::now());let mut dialog_open = false;+ let mut app_links = AppLinkWatch::default();loop {+ let app_link_due = app_links.deadline();tokio::select! {+ _ = async { match app_link_due { Some(at) => tokio::time::sleep_until(at).await, None => std::future::pending().await } } => {+ if let Some(verdict) = app_links.due(Instant::now()) { act_on_app_link(cdp, client_tx, verdict); }+ }+ stuck = async { match stuck_check.as_mut() { Some(check) => check.await, None => std::future::pending().await } } => {+ stuck_check = None;+ if stuck.unwrap_or(false) {+ tracing::info!("the page ignored input when the live view opened; stepping off it and back");+ act_on_app_link(cdp, client_tx, app_links.stuck(Instant::now()));+ }+ }_ = heartbeat.tick() => {if last_client.elapsed() > Duration::from_secs(35) { break; }send(socket, json!({"type":"ping"})).await?;@@ -908,6 +941,17 @@ async fn stream(}if moves_location(method, params) { refresh_location(cdp, ctrl, shared, client_tx); }match method {+ // a link to another app the guard couldn't cancel (a frame's first address)+ "Page.frameStartedNavigating" | "Page.frameRequestedNavigation" => {+ app_links.started(params["url"].as_str().unwrap_or_default(), Instant::now());+ }+ "Log.entryAdded" => app_links.logged(params["entry"]["text"].as_str().unwrap_or_default()),+ "Runtime.bindingCalled" if params["name"] == app_links::BINDING => {+ let scheme = app_links::shown_scheme(params["payload"].as_str().unwrap_or_default());+ if let Some(scheme) = scheme.filter(|_| app_links.may_notice(Instant::now())) {+ send(socket, app_link_notice(&app_links::stopped_text(&scheme))).await?;+ }+ }"Page.screencastFrame" => {let session = params["sessionId"].as_i64().unwrap_or_default();let (dw, dh) = (params["metadata"]["deviceWidth"].as_f64().unwrap_or(0.0), params["metadata"]["deviceHeight"].as_f64().unwrap_or(0.0));@@ -950,7 +994,13 @@ async fn stream(// A pending human step already holds the browser for the personif lease.is_none() && !ctrl.is_held_for_person() {match ctrl.take_control().await {- Ok(guard) => lease = Some(guard),+ Ok(guard) => {+ lease = Some(guard);+ // a button left down by an earlier view would turn the+ // person's first click into a drag+ let held = ctrl.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()).take();+ release_on(cdp, held).await;+ }Err(error) => { send(socket, json!({"type":"error","error":error.to_string()})).await?; continue; }}}@@ -1006,6 +1056,85 @@ async fn stream((result, lease)}+/// Keeps links to another app from freezing the tab while the live view is open (see+/// [`app_links`]), and has the guard say when it stopped one. Runtime is enabled for that call+/// and Log for Chrome's own refusals.+async fn guard_app_links(cdp: &Cdp) {+ for (method, params) in [+ ("Runtime.addBinding", json!({"name": app_links::BINDING, "executionContextName": app_links::WORLD})),+ ("Page.addScriptToEvaluateOnNewDocument", json!({"source": app_links::guard_js(), "worldName": app_links::WORLD, "runImmediately": true})),+ ("Runtime.enable", json!({})),+ ("Log.enable", json!({})),+ ] {+ if let Err(e) = cdp.call(method, params, PROBE_WAIT).await { tracing::debug!(method, "app link guard: {}", e); }+ }+}++/// Recovers the tab from Chrome's "Open <app>?" prompt off the loop and tells the person, or+/// only tells them when it has been recovered too often.+fn act_on_app_link(cdp: &Cdp, client: &mpsc::UnboundedSender<Value>, verdict: Verdict) {+ match verdict {+ Verdict::Recover(scheme) => {+ let (cdp, client) = (cdp.clone(), client.clone());+ tokio::spawn(async move {+ let text = match leave_app_prompt(&cdp).await {+ Ok(()) => app_links::recovered_text(scheme.as_deref()),+ Err(e) => { tracing::debug!("couldn't close an app prompt: {}", e); app_links::gave_up_text(scheme.as_deref()) }+ };+ let _ = client.send(app_link_notice(&text));+ });+ }+ Verdict::GiveUp(scheme) => { let _ = client.send(app_link_notice(&app_links::gave_up_text(scheme.as_deref()))); }+ }+}++/// Whether the page ignores input: scripts run, but a mouse move at a point outside any frame+/// never reaches it. That is what Chrome's "Open <app>?" prompt does to a tab. Anything that+/// can't be told for sure (no point to probe, the page changed or didn't answer) is `false`.+async fn input_is_stuck(cdp: &Cdp) -> bool {+ let eval = |expression: &str| cdp.call("Runtime.evaluate", json!({"expression": expression, "returnByValue": true}), PROBE_WAIT);+ let Ok(armed) = eval(app_links::PROBE_ARM_JS).await else { return false };+ let point = armed["result"]["value"].as_array().and_then(|p| Some((p.first()?.as_f64()?, p.get(1)?.as_f64()?)));+ let Some((x, y)) = point else { return false };+ // two moves, so one is a move even if the pointer already rests on the first point+ for dx in [0.0, 1.0] {+ let moved = json!({"type":"mouseMoved","x":x + dx,"y":y,"button":"none","buttons":0});+ if cdp.call("Input.dispatchMouseEvent", moved, PROBE_WAIT).await.is_err() { break; }+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ let reached = eval(app_links::PROBE_READ_JS).await.ok().and_then(|r| r["result"]["value"].as_i64());+ reached == Some(0)+}++/// Closes Chrome's "Open <app>?" prompt. Only a cross-site navigation does, so the tab steps to+/// about:blank and straight back to the entry it was on: the page loads again, as on a reload.+async fn leave_app_prompt(cdp: &Cdp) -> Result<(), BrowserError> {+ let current = |history: &Value| {+ let index = history["currentIndex"].as_u64()? as usize;+ let entry = history["entries"].get(index)?;+ Some((entry["id"].as_i64()?, entry["url"].as_str().unwrap_or_default().to_string()))+ };+ let history = cdp.call("Page.getNavigationHistory", json!({}), PROBE_WAIT).await?;+ let (entry, _) = current(&history).ok_or_else(|| protocol("No page to go back to"))?;+ cdp.call("Page.navigate", json!({"url": "about:blank"}), Duration::from_secs(10)).await?;+ // Chrome swaps the page's renderer on the way: until it's done, commands on this socket fail+ // with "Not attached to an active page"+ let mut last = Err(protocol("The page didn't come back"));+ for _ in 0..60 {+ tokio::time::sleep(Duration::from_millis(50)).await;+ let Ok(history) = cdp.call("Page.getNavigationHistory", json!({}), PROBE_WAIT).await else { continue };+ if !current(&history).is_some_and(|(id, url)| id != entry && url == "about:blank") { continue; }+ last = cdp.call("Page.navigateToHistoryEntry", json!({"entryId": entry}), Duration::from_secs(10)).await;+ if last.is_ok() { break; }+ }+ last.map(|_| ())+}++/// Tells the person about a link to another app. It has no id, so it shows as a banner.+fn app_link_notice(text: &str) -> Value {+ json!({"type":"error","notice":"app_link","error":text})+}+async fn send(socket: &mut WebSocket, value: Value) -> Result<(), BrowserError> {timeout(Duration::from_secs(5), socket.send(Message::Text(value.to_string()))).await.map_err(|_| BrowserError::Timeout)?.map_err(|e| BrowserError::Ws(e.to_string()))diff --git a/tests/browser_stream_test.rs b/tests/browser_stream_test.rsindex e2b9fe83..8fa58394 100644--- a/tests/browser_stream_test.rs+++ b/tests/browser_stream_test.rs@@ -18,6 +18,11 @@ struct Mock {between_documents: Arc<std::sync::atomic::AtomicBool>,/// Every open DevTools socket, to push page events the way Chromium does.sockets: Arc<Mutex<Vec<tokio::sync::mpsc::UnboundedSender<String>>>>,+ /// Console lines the page logged at load, replayed when Runtime or Log is turned on.+ console_lines: Arc<AtomicUsize>,+ /// How the page answers the live view's input check: 0 not at all, 1 a live tab, 2 a tab+ /// behind Chrome's "Open app?" prompt (scripts run, input never arrives).+ input: Arc<std::sync::atomic::AtomicU8>,}/// Sends a page event on every open DevTools socket.@@ -44,7 +49,27 @@ async fn cdp(State(mock): State<Mock>, Path(_id): Path<String>, ws: WebSocketUpgif socket.send(Message::Text(error.to_string())).await.is_err() { break; }continue;}+ // Chromium replays what the page already logged before it answers+ let replay = |event: &str, n: usize| (0..n).map(|i| match event {+ "Runtime.consoleAPICalled" => json!({"method":event,"params":{"type":"log","args":[{"type":"string","value":format!("line {i}")}],"executionContextId":1,"timestamp":i}}),+ _ => json!({"method":event,"params":{"entry":{"source":"javascript","level":"info","text":format!("line {i}"),"timestamp":i}}}),+ }).collect::<Vec<_>>();+ let lines = mock.console_lines.load(Ordering::SeqCst);+ let replayed = match method {+ "Runtime.enable" => [replay("Runtime.consoleAPICalled", lines), (1..=3).map(|i| json!({"method":"Runtime.executionContextCreated","params":{"context":{"id":i}}})).collect()].concat(),+ "Log.enable" => replay("Log.entryAdded", lines),+ _ => vec![],+ };+ let mut gone = false;+ for event in replayed { if socket.send(Message::Text(event.to_string())).await.is_err() { gone = true; break; } }+ if gone { break; }+ let probe = cmd["params"]["expression"].as_str().is_some_and(|e| e.contains("kwnt.inputProbe")) && mock.input.load(Ordering::SeqCst) != 0;let result = match method {+ "Runtime.evaluate" if probe => {+ let stuck = mock.input.load(Ordering::SeqCst) == 2;+ let arming = cmd["params"]["expression"].as_str().unwrap().contains("elementFromPoint");+ json!({"result":{"value": if arming { json!([8, 8]) } else if stuck { json!(0) } else { json!(2) }}})+ }"Target.createBrowserContext" => json!({"browserContextId":format!("context-{}",mock.contexts.fetch_add(1,Ordering::SeqCst))}),"Target.createTarget" => {assert!(cmd["params"].get("width").is_none(), "viewport dimensions belong in Emulation, not createTarget without newWindow");@@ -70,6 +95,13 @@ async fn cdp(State(mock): State<Mock>, Path(_id): Path<String>, ws: WebSocketUpgjson!({"result":{"value":{"url":url,"title":"Example"}}})}"Page.captureScreenshot" => json!({"data":"fresh-frame"}),+ // the tab is on a sign-in page; it steps to about:blank when told to+ "Page.getNavigationHistory" => {+ let blank = mock.commands.lock().await.iter().any(|c| c["method"] == "Page.navigate" && c["params"]["url"] == "about:blank");+ let mut entries = vec![json!({"id":1,"url":"https://example.com/"}), json!({"id":2,"url":"https://www.tiktok.com/login/qrcode"})];+ if blank { entries.push(json!({"id":3,"url":"about:blank"})); }+ json!({"currentIndex": entries.len() - 1, "entries": entries})+ }_ => json!({}),};if socket.send(Message::Text(json!({"id":cmd["id"],"result":result}).to_string())).await.is_err() { break; }@@ -578,6 +610,67 @@ async fn a_picture_drawn_while_the_client_was_busy_is_sent_next_even_on_a_page_tapp_task.abort(); cdp_task.abort();}+/// The next banner about a link to another app, acking frames on the way.+async fn app_link_notice(ws: &mut Client, within: Duration) -> Option<String> {+ timeout(within, async {+ loop {+ if let WsMessage::Text(text) = ws.next().await.unwrap().unwrap() {+ let value: Value = serde_json::from_str(&text).unwrap();+ match value["type"].as_str().unwrap_or_default() {+ "ping" => ws.send(WsMessage::Text(json!({"action":"pong"}).to_string())).await.unwrap(),+ "frame" => ws.send(WsMessage::Text(json!({"action":"frame_ack","id":value["id"]}).to_string())).await.unwrap(),+ "error" if value["notice"] == "app_link" => {+ assert!(value.get("id").is_none(), "a banner, not the answer to an action");+ return value["error"].as_str().unwrap().to_string();+ }+ _ => {}+ }+ }+ }+ }).await.ok()+}++#[tokio::test]+async fn a_link_to_another_app_is_stopped_or_its_prompt_closed_so_the_tab_keeps_taking_input() {+ let (mock, cdp_task) = mock().await;+ let tmp = tempfile::tempdir().unwrap();+ let (mut ws, _ctrl, app_task) = open_stream(&mock, tmp.path()).await;+ next_frame(&mut ws, Duration::from_secs(5)).await.expect("the stream is up");++ // Chrome answers a link like snssdk1233:// with an "Open app?" prompt that a headless tab+ // never shows and that makes it ignore every click and key, even after a reload. The live+ // view cancels such links in every document, in a world the page can't reach.+ let commands = mock.commands.lock().await.clone();+ let guard = commands.iter().find(|c| c["method"] == "Page.addScriptToEvaluateOnNewDocument" && c["params"]["worldName"] == "kwnt-applinks")+ .expect("the live view guards against links to other apps");+ assert_eq!(guard["params"]["runImmediately"], true, "the page already open is guarded too");+ assert!(guard["params"]["source"].as_str().unwrap().contains("preventDefault"));+ assert!(commands.iter().any(|c| c["method"] == "Runtime.addBinding" && c["params"]["executionContextName"] == "kwnt-applinks"));++ // the guard stopped one: the person learns why their tap did nothing+ push_event(&mock, "Runtime.bindingCalled", json!({"name":"kwntAppLink","payload":"snssdk1233","executionContextId":9})).await;+ let stopped = app_link_notice(&mut ws, Duration::from_secs(2)).await.expect("told the link was stopped");+ assert!(stopped.contains("(snssdk1233:)"), "{stopped}");+ // the page's own script can't put words on the banner+ push_event(&mock, "Runtime.bindingCalled", json!({"name":"kwntAppLink","payload":"<img src=x>","executionContextId":9})).await;++ // Chrome refused one outright (no gesture): no prompt, so nothing to undo+ push_event(&mock, "Page.frameStartedNavigating", json!({"frameId":"F1","url":"snssdk1233://login?a=1","loaderId":"L1","navigationType":"differentDocument"})).await;+ push_event(&mock, "Log.entryAdded", json!({"entry":{"source":"other","level":"error","text":"Not allowed to launch 'snssdk1233://login?a=1' because a user gesture is required."}})).await;+ tokio::time::sleep(Duration::from_millis(900)).await;+ assert!(!mock.commands.lock().await.iter().any(|c| c["method"] == "Page.navigate"), "the page was left alone");++ // one got past the guard (a frame whose first address is the link): Chrome is asking, so the+ // tab steps off to about:blank and straight back to the sign-in page, which closes the prompt+ push_event(&mock, "Page.frameStartedNavigating", json!({"frameId":"F2","url":"snssdk1233://login?b=1","loaderId":"L2","navigationType":"differentDocument"})).await;+ let recovered = app_link_notice(&mut ws, Duration::from_secs(5)).await.expect("told the page was reloaded");+ assert!(recovered.contains("reloaded"), "{recovered}");+ let steps: Vec<Value> = mock.commands.lock().await.iter()+ .filter(|c| matches!(c["method"].as_str(), Some("Page.navigate" | "Page.navigateToHistoryEntry"))).map(|c| c["params"].clone()).collect();+ assert_eq!(steps, vec![json!({"url":"about:blank"}), json!({"entryId":2})]);+ 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"]@@ -678,3 +771,78 @@ async fn a_browser_container_from_an_older_image_is_replaced() {let agent = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": "navigator.userAgent", "returnByValue": true})).await.unwrap();assert!(agent.to_string().contains("Chrome/") && !agent.to_string().contains("Headless"), "{agent}");}++/// F1: turning on Runtime and Log makes Chromium replay everything the page logged. A page+/// that logged 200 lines at load (the TikTok QR page logs ~70) must still start the live view.+#[tokio::test]+async fn a_page_that_logged_hundreds_of_lines_still_starts_the_live_view() {+ let (mock, cdp_task) = mock().await;+ mock.console_lines.store(200, Ordering::SeqCst);+ let tmp = tempfile::tempdir().unwrap();+ let (mut ws, _ctrl, app_task) = open_stream(&mock, tmp.path()).await;+ let first = next_frame(&mut ws, Duration::from_secs(5)).await.expect("the first picture of a noisy page");+ assert_eq!(first["image"], "streamed-frame");+ let commands = mock.commands.lock().await.clone();+ assert!(commands.iter().any(|c| c["method"] == "Runtime.enable") && commands.iter().any(|c| c["method"] == "Log.enable"), "the guard is still on");+ // and the stream is live: the guard's notices and Chrome's refusals still get through+ push_event(&mock, "Runtime.bindingCalled", json!({"name":"kwntAppLink","payload":"snssdk1233","executionContextId":9})).await;+ assert!(app_link_notice(&mut ws, Duration::from_secs(2)).await.expect("told the link was stopped").contains("(snssdk1233:)"));+ app_task.abort(); cdp_task.abort();+}++/// F2: the link fired while no live view was open (the bot opened the sign-in page; the person+/// takes over later). Opening the view finds the tab ignoring input and steps it off and back.+#[tokio::test]+async fn a_tab_frozen_before_the_live_view_opened_is_recovered_when_it_opens() {+ let (mock, cdp_task) = mock().await;+ mock.input.store(2, Ordering::SeqCst);+ let tmp = tempfile::tempdir().unwrap();+ let (mut ws, _ctrl, app_task) = open_stream(&mock, tmp.path()).await;+ let recovered = app_link_notice(&mut ws, Duration::from_secs(5)).await.expect("told the page was reloaded");+ assert!(recovered.contains("reloaded the page"), "{recovered}");+ let commands = mock.commands.lock().await.clone();+ let moves: Vec<&Value> = commands.iter().filter(|c| c["method"] == "Input.dispatchMouseEvent").collect();+ assert!(!moves.is_empty() && moves.iter().all(|c| c["params"]["type"] == "mouseMoved" && c["params"]["buttons"] == 0), "the check only moves the pointer: {moves:?}");+ let steps: Vec<Value> = commands.iter()+ .filter(|c| matches!(c["method"].as_str(), Some("Page.navigate" | "Page.navigateToHistoryEntry"))).map(|c| c["params"].clone()).collect();+ assert_eq!(steps, vec![json!({"url":"about:blank"}), json!({"entryId":2})]);+ app_task.abort(); cdp_task.abort();+}++/// F2: a tab that takes input is left alone when the live view opens: no reload, no banner.+#[tokio::test]+async fn a_live_tab_is_left_alone_when_the_live_view_opens() {+ let (mock, cdp_task) = mock().await;+ mock.input.store(1, Ordering::SeqCst);+ let tmp = tempfile::tempdir().unwrap();+ let (mut ws, _ctrl, app_task) = open_stream(&mock, tmp.path()).await;+ next_frame(&mut ws, Duration::from_secs(5)).await.expect("the stream is up");+ let checked = timeout(Duration::from_secs(3), async { loop {+ if mock.commands.lock().await.iter().filter(|c| c["params"]["expression"].as_str().is_some_and(|e| e.contains("kwnt.inputProbe"))).count() >= 2 { break; }+ tokio::time::sleep(Duration::from_millis(20)).await;+ }}).await;+ assert!(checked.is_ok(), "the view checked the tab");+ assert_eq!(app_link_notice(&mut ws, Duration::from_millis(1500)).await, None, "no banner");+ assert!(!mock.commands.lock().await.iter().any(|c| c["method"] == "Page.navigate"), "no reload");+ app_task.abort(); cdp_task.abort();+}++/// F3: a bot's own navigate to a link that opens another app never reaches Chromium, whose+/// "Open app?" prompt would leave the tab ignoring every click and key. The bot is told why.+#[tokio::test]+async fn a_bot_navigating_to_another_app_is_refused_before_the_browser_sees_it() {+ let (mock, cdp_task) = mock().await;+ let tmp = tempfile::tempdir().unwrap();+ let (_ws, ctrl, app_task) = open_stream(&mock, tmp.path()).await;+ for url in ["tiktok://open", "snssdk1233://login", "intent://scan/#Intent;scheme=zxing;end"] {+ let error = ctrl.navigate(url).await.expect_err(url);+ assert!(matches!(error, kwnt::sandbox::BrowserError::NotWebAddress(_)), "{url}: {error:?}");+ let text = error.to_string();+ assert!(text.contains("opens another app") && text.contains("only opens web pages"), "{text}");+ }+ let navigated: Vec<Value> = mock.commands.lock().await.iter().filter(|c| c["method"] == "Page.navigate").map(|c| c["params"]["url"].clone()).collect();+ assert!(navigated.is_empty(), "nothing reached the browser: {navigated:?}");+ // the bot carries on with web pages+ ctrl.navigate("https://www.tiktok.com/login").await.expect("a web page still opens");+ app_task.abort(); cdp_task.abort();+}