diff --git a/crates/tinycomputer-browser/src/action_gate.rs b/crates/tinycomputer-browser/src/action_gate.rs index f44778320..2c4214a5e 100644 --- a/crates/tinycomputer-browser/src/action_gate.rs +++ b/crates/tinycomputer-browser/src/action_gate.rs @@ -39,6 +39,12 @@ pub enum ObservationKind { ReadPage, /// A screenshot of the page. Screenshot, + /// A fixed browser-surface page-stability watcher. This exposes only + /// whether the page changed, not its content. + PageStability, + /// A fixed-purpose hit-test used by the browser surface before it decides + /// whether a target's pointer action is covered. + TargetCheck, } /// Information a trusted host may inspect before the browser acts or returns diff --git a/crates/tinycomputer-browser/src/sessions/page.rs b/crates/tinycomputer-browser/src/sessions/page.rs index 258c4ccde..a0c5f22d7 100644 --- a/crates/tinycomputer-browser/src/sessions/page.rs +++ b/crates/tinycomputer-browser/src/sessions/page.rs @@ -420,6 +420,99 @@ impl Browser { Ok(data) } + /// Runs the browser surface's fixed-purpose stability watcher. This is + /// crate-private so callers cannot label arbitrary evaluation as an + /// observation or bypass the host action gate. + pub(crate) async fn observe_page_stability( + &self, + id: &SessionId, + script: String, + ) -> Result { + let session = self.session(id)?; + let mut session = session.lock().await; + session.check_if_readable(false).await?; + let current_url = session + .action_url() + .await + .ok_or_else(|| Error::invalid_input("the current page URL is unknown"))?; + self.check_action(&ActionRequest::observation( + ObservationKind::PageStability, + Some(current_url), + &session.action_context, + ))?; + let data = session + .run(serde_json::json!({"action": "evaluate", "script": script})) + .await?; + let page = session.page().await?; + let page = session.admit(page).await?; + self.check_action(&ActionRequest::observation( + ObservationKind::PageStability, + Some(page.url.clone()), + &session.action_context, + ))?; + session.info.url.clone_from(&page.url); + Ok(data) + } + + /// Runs the browser surface's fixed-purpose cover hit-test. This stays + /// crate-private so arbitrary evaluations cannot claim observation status. + pub(crate) async fn observe_target_check( + &self, + id: &SessionId, + script: String, + ) -> Result { + let session = self.session(id)?; + let mut session = session.lock().await; + session.check_if_readable(false).await?; + let current_url = session + .action_url() + .await + .ok_or_else(|| Error::invalid_input("the current page URL is unknown"))?; + self.check_action(&ActionRequest::observation( + ObservationKind::TargetCheck, + Some(current_url), + &session.action_context, + ))?; + let data = session + .run(serde_json::json!({"action": "evaluate", "script": script})) + .await?; + let page = session.page().await?; + let page = session.admit(page).await?; + self.check_action(&ActionRequest::observation( + ObservationKind::TargetCheck, + Some(page.url.clone()), + &session.action_context, + ))?; + session.info.url.clone_from(&page.url); + Ok(data) + } + + /// Runs the browser surface's Sight snapshot script. This is crate-private + /// so raw evaluations cannot claim Snapshot observation authority. + pub(crate) async fn observe_sight(&self, id: &SessionId, script: String) -> Result { + let session = self.session(id)?; + let mut session = session.lock().await; + session.check_if_readable(false).await?; + let current_url = session.action_url().await; + self.check_action(&ActionRequest::observation( + ObservationKind::Snapshot, + current_url, + &session.action_context, + ))?; + let data = session + .run(serde_json::json!({"action": "evaluate", "script": script})) + .await?; + let page = session.page().await?; + let page = session.admit(page).await?; + self.check_action(&ActionRequest::observation( + ObservationKind::Snapshot, + Some(page.url.clone()), + &session.action_context, + ))?; + session.info.url.clone_from(&page.url); + Ok(data) + } + /// Evaluates JavaScript in the page and returns its value. /// /// # Errors diff --git a/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs b/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs index 93b3a4e5a..55f6054cc 100644 --- a/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs +++ b/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs @@ -12,9 +12,132 @@ use tinycomputer_bus::browser::{ use super::open; use crate::error::Error; use crate::fake::{Fake, failure, ok}; -use crate::{ActionContext, ActionGate, ActionRequest, ActionVerdict, Browser}; +use crate::{ActionContext, ActionGate, ActionRequest, ActionVerdict, Browser, ObservationKind}; use crate::{ActionObservation, ActionObserver, ObservedAction}; +type GateObservation = (String, Option, Option); + +#[derive(Default)] +struct CaptureGate(std::sync::Mutex>); + +impl ActionGate for CaptureGate { + fn check(&self, request: &ActionRequest) -> ActionVerdict { + self.0.lock().unwrap().push(( + request.payload["action"] + .as_str() + .unwrap_or_default() + .to_owned(), + request.observation, + request.current_url.clone(), + )); + ActionVerdict::Allow + } +} + +#[tokio::test] +async fn only_the_fixed_page_stability_helper_is_classified_as_an_observation() { + let fake = Fake::scripted(|command| match command["action"].as_str() { + Some("url") => Some(ok(&json!({"url": "https://shop.test/"}))), + Some("navigate") => Some(ok(&json!({ + "url": command["url"], + "title": "Shop" + }))), + Some("evaluate") => Some(ok(&json!({"result": true}))), + _ => None, + }); + let gate = Arc::new(CaptureGate::default()); + let browser = Browser::with_scratch( + Arc::new(fake), + std::env::temp_dir().join(format!("tinycomputer-stability-{}", std::process::id())), + ) + .with_action_gate(gate.clone()); + let id = browser + .open_session(SessionOptions::default()) + .await + .unwrap() + .id; + browser + .navigate(&id, NavigateRequest::new("https://shop.test/")) + .await + .unwrap(); + gate.0.lock().unwrap().clear(); + + let script = + "new Promise(resolve => { const watcher = new MutationObserver(() => resolve(true)); })"; + browser + .observe_page_stability(&id, script.to_owned()) + .await + .unwrap(); + assert_eq!( + gate.0.lock().unwrap().as_slice(), + [ + ( + "observe".to_owned(), + Some(ObservationKind::PageStability), + Some("https://shop.test/".to_owned()) + ), + ( + "observe".to_owned(), + Some(ObservationKind::PageStability), + Some("https://shop.test/".to_owned()) + ) + ] + ); + + gate.0.lock().unwrap().clear(); + browser + .observe_target_check(&id, script.to_owned()) + .await + .unwrap(); + assert_eq!( + gate.0.lock().unwrap().as_slice(), + [ + ( + "observe".to_owned(), + Some(ObservationKind::TargetCheck), + Some("https://shop.test/".to_owned()) + ), + ( + "observe".to_owned(), + Some(ObservationKind::TargetCheck), + Some("https://shop.test/".to_owned()) + ) + ] + ); + + gate.0.lock().unwrap().clear(); + browser.observe_sight(&id, script.to_owned()).await.unwrap(); + assert_eq!( + gate.0.lock().unwrap().as_slice(), + [ + ( + "observe".to_owned(), + Some(ObservationKind::Snapshot), + Some("https://shop.test/".to_owned()) + ), + ( + "observe".to_owned(), + Some(ObservationKind::Snapshot), + Some("https://shop.test/".to_owned()) + ) + ] + ); + + gate.0.lock().unwrap().clear(); + browser + .command(&id, json!({"action": "evaluate", "script": script})) + .await + .unwrap(); + assert_eq!( + gate.0.lock().unwrap().as_slice(), + [( + "evaluate".to_owned(), + None, + Some("https://shop.test/".to_owned()) + )] + ); +} + #[tokio::test] async fn navigation_reports_the_page_and_refusals_are_typed() { let fake = Fake::scripted(|command| { diff --git a/crates/tinycomputer-browser/src/surface/card.rs b/crates/tinycomputer-browser/src/surface/card.rs index c15f7b3d6..0776fa73e 100644 --- a/crates/tinycomputer-browser/src/surface/card.rs +++ b/crates/tinycomputer-browser/src/surface/card.rs @@ -122,10 +122,7 @@ impl BrowserSurface { serde_json::to_string(&name).ok()? ); let same_card = self - .block( - self.browser - .command(&id, json!({"action": "evaluate", "script": script})), - ) + .block(self.browser.observe_target_check(&id, script)) .ok()?; if same_card.get("result") != Some(&Value::Bool(true)) { return None; diff --git a/crates/tinycomputer-browser/src/surface/cover.rs b/crates/tinycomputer-browser/src/surface/cover.rs index f7137e5eb..4c43756f1 100644 --- a/crates/tinycomputer-browser/src/surface/cover.rs +++ b/crates/tinycomputer-browser/src/surface/cover.rs @@ -29,7 +29,7 @@ use super::sight; /// a pointer, nothing of the element), on an even grid ([`SPOT_GRID`] cells /// a side), or `null` when there is none. The layer stops taking the /// pointer only for the instant each point beneath it is read. -pub(crate) const COVER_JS: &str = r#"((x, y, exact, press, grid) => { +pub(crate) const COVER_JS: &str = r#"((x, y, exact, press, grid, hideFormValues = false) => { const squash = (text) => (text || '').replace(/\s+/g, ' ').trim(); const cut = (text) => (text.length > 60 ? `${text.slice(0, 59)}…` : text); // Up from a node, across shadow roots to their hosts. @@ -42,6 +42,33 @@ pub(crate) const COVER_JS: &str = r#"((x, y, exact, press, grid) => { for (let at = node; at; at = above(at)) if (at.matches && at.matches(selector)) return at; return null; }; + const PRIVATE_FIELD_ROLES = [ + 'textbox', 'searchbox', 'combobox', 'textarea', 'document', 'spinbutton', + 'checkbox', 'radio', 'switch', 'menuitemcheckbox', 'menuitemradio', + ]; + const privateField = (element) => { + if (!element || !element.tagName) return false; + const tag = element.tagName.toLowerCase(); + const role = (element.getAttribute('role') || '').toLowerCase().split(/\s+/)[0]; + return ['input', 'select', 'textarea'].includes(tag) + || element.isContentEditable || PRIVATE_FIELD_ROLES.includes(role); + }; + const insidePrivateField = (element) => { + for (let at = element; at; at = above(at)) if (privateField(at)) return true; + return false; + }; + const safeText = (element) => { + if (!hideFormValues) return squash(element.innerText); + if (insidePrivateField(element)) return ''; + // A generic cover can aggregate text from editable descendants. + const clone = element.cloneNode(true); + const fields = [ + 'input', 'select', 'textarea', '[contenteditable=""]', '[contenteditable=true]', + ...PRIVATE_FIELD_ROLES.map((role) => `[role~="${role}"]`), + ].join(', '); + clone.querySelectorAll(fields).forEach((field) => field.remove()); + return squash(clone.innerText || clone.textContent); + }; const topAt = (px, py) => { let node = document.elementFromPoint(px, py); while (node && node.shadowRoot) { @@ -62,22 +89,25 @@ pub(crate) const COVER_JS: &str = r#"((x, y, exact, press, grid) => { const control = nearest(hit, CONTROL); if (control) { const role = control.getAttribute('role') || ROLES[control.tagName.toLowerCase()] || 'control'; - const name = cut(squash(control.getAttribute('aria-label') || control.innerText - || control.getAttribute('title') || control.getAttribute('placeholder'))); + const attributeName = squash(control.getAttribute('aria-label') + || control.getAttribute('title') || control.getAttribute('placeholder')); + const nestedInField = hideFormValues && insidePrivateField(above(control)); + const name = cut(nestedInField ? '' : (attributeName || safeText(control))); return { said: name ? `${role} "${name}"` : `an unnamed ${role}`, bare: false, spot: null }; } const dialog = nearest(hit, 'dialog, [role=dialog], [role=alertdialog], [aria-modal=true]'); if (dialog) { - const name = cut(squash(dialog.getAttribute('aria-label') || dialog.innerText)); + const name = cut(squash(dialog.getAttribute('aria-label') || safeText(dialog))); return { said: name ? `a dialog showing "${name}"` : 'a dialog', bare: false, spot: null }; } - const own = squash([...hit.childNodes].filter((node) => node.nodeType === 3) + const own = hideFormValues && insidePrivateField(hit) ? '' : squash([...hit.childNodes] + .filter((node) => node.nodeType === 3) .map((node) => node.textContent).join(' ')); if (own) return { said: `a layer showing "${cut(own)}"`, bare: false, spot: null }; if (nearest(hit, 'img, svg, video, canvas, iframe, picture, object, embed')) { return { said: 'a picture', bare: false, spot: null }; } - const held = cut(squash(hit.innerText)); + const held = cut(safeText(hit)); const said = held ? `a layer holding "${held}"` : 'an empty layer'; const component = hit.getRootNode() !== document || Boolean(hit.shadowRoot) || hit.tagName.includes('-'); let placed = false; @@ -150,12 +180,12 @@ impl BrowserSurface { } else { "null".to_owned() }; - let script = format!("{COVER_JS}({x}, {y}, {exact}, {press}, {SPOT_GRID})"); + let script = format!( + "{COVER_JS}({x}, {y}, {exact}, {press}, {SPOT_GRID}, {})", + self.hide_form_values + ); let data = self - .block( - self.browser - .command(&id, json!({"action": "evaluate", "script": script})), - ) + .block(self.browser.observe_target_check(&id, script)) .map_err(|error| error.to_string())?; match data.get("result") { Some(cover) if cover.get("unread") == Some(&Value::Bool(true)) => { diff --git a/crates/tinycomputer-browser/src/surface/envelope.rs b/crates/tinycomputer-browser/src/surface/envelope.rs index f79710b22..2740b69e4 100644 --- a/crates/tinycomputer-browser/src/surface/envelope.rs +++ b/crates/tinycomputer-browser/src/surface/envelope.rs @@ -17,10 +17,9 @@ pub(super) fn reply(command: &str, result: Result) -> DesktopResponse { /// name in `SCREAMING_SNAKE_CASE`, such as `STALE_REF`. /// Whether a click was refused because another element covers its target. pub(super) fn covered(reply: &DesktopResponse) -> bool { - reply - .error - .as_ref() - .is_some_and(|error| error.message.contains("is covered by")) + reply.error.as_ref().is_some_and(|error| { + error.code != "ACTION_REFUSED" && error.message.contains("is covered by") + }) } pub(super) fn failure(command: &str, error: &Error) -> DesktopResponse { @@ -49,3 +48,28 @@ pub(super) fn not_a_text_field() -> DesktopResponse { ), ) } + +#[cfg(test)] +mod tests { + use tinycomputer_bus::{DesktopError, DesktopResponse}; + + use super::covered; + + #[test] + fn a_host_policy_refusal_is_not_retried_as_a_cover() { + let refused = DesktopResponse::err( + "click", + DesktopError::new( + "ACTION_REFUSED", + "Refused: the target is covered by policy.", + ), + ); + assert!(!covered(&refused)); + + let covered_by_page = DesktopResponse::err( + "click", + DesktopError::new("NOT_ACTIONABLE", "The element is covered by a banner."), + ); + assert!(covered(&covered_by_page)); + } +} diff --git a/crates/tinycomputer-browser/src/surface/mod.rs b/crates/tinycomputer-browser/src/surface/mod.rs index 75eda39bc..cc7129d7a 100644 --- a/crates/tinycomputer-browser/src/surface/mod.rs +++ b/crates/tinycomputer-browser/src/surface/mod.rs @@ -379,9 +379,7 @@ impl BrowserSurface { sight::script(root) }; // The timer is made inside the runtime `block` enters, not before. - let reading = self - .browser - .command(&id, json!({"action": "evaluate", "script": script})); + let reading = self.browser.observe_sight(&id, script); let reply = self .block(async { tokio::time::timeout(READ_TIMEOUT, reading).await }) .ok()? diff --git a/crates/tinycomputer-browser/src/surface/operations.rs b/crates/tinycomputer-browser/src/surface/operations.rs index 58e43c0e0..755336494 100644 --- a/crates/tinycomputer-browser/src/surface/operations.rs +++ b/crates/tinycomputer-browser/src/surface/operations.rs @@ -313,10 +313,9 @@ impl Surface for BrowserSurface { let Some(id) = self.session() else { return true; }; - let watching = self.browser.command( - &id, - json!({"action": "evaluate", "script": watch::change_script(ms)}), - ); + let watching = self + .browser + .observe_page_stability(&id, watch::change_script(ms)); self.block(async { tokio::time::timeout(watch::deadline(ms), watching).await }) .ok() .and_then(Result::ok) @@ -412,10 +411,9 @@ impl BrowserSurface { /// a deadline: a call sent while a page is being replaced can wait out /// the browser's own 30 s. fn await_still(&self, id: &SessionId) { - let still = self.browser.command( - id, - json!({"action": "evaluate", "script": watch::still_script()}), - ); + let still = self + .browser + .observe_page_stability(id, watch::still_script()); let _still = self.block(async { tokio::time::timeout(watch::deadline(SETTLE_MS), still).await }); } diff --git a/crates/tinycomputer-browser/src/surface/sight/sight_tests/live_cover_tests.rs b/crates/tinycomputer-browser/src/surface/sight/sight_tests/live_cover_tests.rs index 96d782d43..c830b1092 100644 --- a/crates/tinycomputer-browser/src/surface/sight/sight_tests/live_cover_tests.rs +++ b/crates/tinycomputer-browser/src/surface/sight/sight_tests/live_cover_tests.rs @@ -267,3 +267,86 @@ async fn live_a_target_is_centred_at_once_on_a_page_that_scrolls_smoothly() { browser.close_session(&info.id).await.unwrap(); assert_eq!(centred["result"], json!([true, true])); } + +#[cfg(feature = "agent-browser")] +#[tokio::test] +async fn live_private_cover_hides_editable_hits_and_overlay_aggregates() { + const UNKNOWN: &str = "profile-autofill-unknown-7Qz9"; + let html = format!( + r#" +
+
+

Overlay privacy notice

+
{UNKNOWN} + +
+
+ +
"# + ); + let Some((browser, info)) = live_page(&html).await else { + return; + }; + let bounds = browser + .command( + &info.id, + json!({"action": "boundingbox", "selector": "#editor"}), + ) + .await + .unwrap(); + let x = bounds["x"].as_f64().unwrap() + bounds["width"].as_f64().unwrap() / 2.0; + let y = bounds["y"].as_f64().unwrap() + bounds["height"].as_f64().unwrap() / 2.0; + let button_bounds = browser + .command( + &info.id, + json!({"action": "boundingbox", "selector": "#aggregate"}), + ) + .await + .unwrap(); + let button_x = button_bounds["x"].as_f64().unwrap() + 8.0; + let button_y = button_bounds["y"].as_f64().unwrap() + 8.0; + let read = |x: f64, y: f64, private: bool| { + format!("{COVER_JS}({x}, {y}, null, false, {SPOT_GRID}, {private})") + }; + let mut results = Vec::new(); + for (x, y, private) in [ + (x, y, true), + (x, y, false), + (button_x, button_y, true), + (button_x, button_y, false), + (10.0, 10.0, true), + (10.0, 10.0, false), + ] { + results.push( + browser + .command( + &info.id, + json!({"action": "evaluate", "script": read(x, y, private)}), + ) + .await + .unwrap()["result"] + .clone(), + ); + } + browser.close_session(&info.id).await.unwrap(); + + assert!(!results[0].to_string().contains(UNKNOWN)); + assert!(results[1].to_string().contains(UNKNOWN)); + assert!(!results[2].to_string().contains(UNKNOWN)); + assert!(results[2].to_string().contains("Overlay button notice")); + assert!(results[3].to_string().contains(UNKNOWN)); + assert!(!results[4].to_string().contains(UNKNOWN)); + assert!(results[4].to_string().contains("Overlay privacy notice")); + assert!(results[4].to_string().contains("Overlay button notice")); + assert!(results[5].to_string().contains(UNKNOWN)); +} diff --git a/crates/tinycomputer-browser/src/surface/surface_tests/cover_tests.rs b/crates/tinycomputer-browser/src/surface/surface_tests/cover_tests.rs index 48eecd61e..a1d86a8a3 100644 --- a/crates/tinycomputer-browser/src/surface/surface_tests/cover_tests.rs +++ b/crates/tinycomputer-browser/src/surface/surface_tests/cover_tests.rs @@ -62,7 +62,7 @@ fn a_press_still_covered_says_what_covers_it() { assert_eq!( cover_scripts(&fake), [format!( - r#"{COVER_JS}(60, 40, "[data-tc-seen=\"5\"]", false, {SPOT_GRID})"# + r#"{COVER_JS}(60, 40, "[data-tc-seen=\"5\"]", false, {SPOT_GRID}, false)"# )] ); // The retry before it brought the target to the middle at once: a page @@ -102,6 +102,23 @@ fn a_press_still_covered_says_what_covers_it() { assert!(error.details.is_none()); } +#[test] +fn a_private_surface_requests_structurally_masked_cover_text() { + let Harness { fake, surface, .. } = harness( + "covered-named-private", + covering_fake(json!({"said": "an unnamed textbox", "bare": false, "spot": null})), + ); + let surface = surface.without_form_values(); + let _reply = surface.dismiss_cover(&basket()); + + assert_eq!( + cover_scripts(&fake), + [format!( + r#"{COVER_JS}(60, 40, "[data-tc-seen=\"5\"]", true, {SPOT_GRID}, true)"# + )] + ); +} + #[test] fn an_empty_layer_is_pressed_where_nothing_lies_beneath_it() { let Harness { fake, surface, .. } = harness( @@ -114,7 +131,7 @@ fn an_empty_layer_is_pressed_where_nothing_lies_beneath_it() { assert_eq!( cover_scripts(&fake), [format!( - r#"{COVER_JS}(60, 40, "[data-tc-seen=\"5\"]", true, {SPOT_GRID})"# + r#"{COVER_JS}(60, 40, "[data-tc-seen=\"5\"]", true, {SPOT_GRID}, false)"# )] ); let pressed = fake @@ -143,7 +160,9 @@ fn an_empty_layer_is_pressed_where_nothing_lies_beneath_it() { covering_fake(json!({"said": "an empty layer", "bare": true, "spot": [300.0, 450.0]})), ); assert!(surface.dismiss_cover(&node("e9", &["Click"])).ok); - assert!(cover_scripts(&fake)[0].ends_with(&format!("(60, 40, null, true, {SPOT_GRID})"))); + assert!( + cover_scripts(&fake)[0].ends_with(&format!("(60, 40, null, true, {SPOT_GRID}, false)")) + ); } #[test]