Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions crates/tinycomputer-browser/src/action_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
93 changes: 93 additions & 0 deletions crates/tinycomputer-browser/src/sessions/page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Value> {
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<Value> {
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<Value> {
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
Expand Down
125 changes: 124 additions & 1 deletion crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ObservationKind>, Option<String>);

#[derive(Default)]
struct CaptureGate(std::sync::Mutex<Vec<GateObservation>>);

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| {
Expand Down
5 changes: 1 addition & 4 deletions crates/tinycomputer-browser/src/surface/card.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
52 changes: 41 additions & 11 deletions crates/tinycomputer-browser/src/surface/cover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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) {
Expand All @@ -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;
Expand Down Expand Up @@ -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)) => {
Expand Down
32 changes: 28 additions & 4 deletions crates/tinycomputer-browser/src/surface/envelope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,9 @@ pub(super) fn reply(command: &str, result: Result<Value>) -> 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 {
Expand Down Expand Up @@ -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));
}
}
Loading
Loading