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
25 changes: 21 additions & 4 deletions crates/tinycomputer-browser/src/surface/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ pub struct BrowserSurface {
platform: Platform,
cursor: Arc<ScreenCursor>,
perception: Perception,
/// Keep values from editable form controls out of every task observation.
/// The private `SecretHost` can type and verify them through the host APIs.
hide_form_values: bool,
settle: Settle,
denoised: Arc<Mutex<Denoised>>,
/// Set once the surface is let go ([`BrowserSurface::close`]): it is
Expand Down Expand Up @@ -180,6 +183,7 @@ impl BrowserSurface {
platform: Platform::current(),
cursor: Arc::new(ScreenCursor::off()),
perception: Perception::default(),
hide_form_values: false,
settle: Settle::default(),
denoised: Arc::new(Mutex::new(Denoised::default())),
closed: Arc::new(AtomicBool::new(false)),
Expand Down Expand Up @@ -233,6 +237,15 @@ impl BrowserSurface {
self
}

/// Hides values held by editable form controls from observations while
/// retaining their labels, roles, states, and refs. Host-side reads and
/// secret-fill verification continue to use the live control value.
#[must_use]
pub fn without_form_values(mut self) -> Self {
self.hide_form_values = true;
self
}

/// The same surface, drawing on `cursor` — the screen's one agent
/// cursor, shared with the desktop surface — whenever its session has a
/// window on screen. The cursor is cosmetic: every action is performed
Expand Down Expand Up @@ -360,11 +373,15 @@ impl BrowserSurface {
fn see(&self, root: Option<&str>) -> Option<Screen> {
self.keep_denoised(Denoised::default());
let id = self.ensure_session().ok()?;
let script = if self.hide_form_values {
sight::script_without_form_values(root)
} else {
sight::script(root)
};
// The timer is made inside the runtime `block` enters, not before.
let reading = self.browser.command(
&id,
json!({"action": "evaluate", "script": sight::script(root)}),
);
let reading = self
.browser
.command(&id, json!({"action": "evaluate", "script": script}));
let reply = self
.block(async { tokio::time::timeout(READ_TIMEOUT, reading).await })
.ok()?
Expand Down
85 changes: 84 additions & 1 deletion crates/tinycomputer-browser/src/surface/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ impl Surface for BrowserSurface {
if !app.is_empty() {
app.clone_into(&mut screen.app);
}
if self.hide_form_values {
hide_form_values(&mut screen);
}
return Ok(screen);
}
let request = SnapshotRequest {
Expand All @@ -68,7 +71,11 @@ impl Surface for BrowserSurface {
})
})
.map_err(|error| Box::new(failure("snapshot", &error)))?;
let mut screen = tree::screen(&snapshot.tree, &snapshot.title);
let mut screen = if self.hide_form_values {
tree::screen_without_form_values(&snapshot.tree, &snapshot.title)
} else {
tree::screen(&snapshot.tree, &snapshot.title)
};
if !app.is_empty() {
app.clone_into(&mut screen.app);
}
Expand Down Expand Up @@ -342,6 +349,38 @@ impl Surface for BrowserSurface {
}
}

/// Removes editable control values from the screen returned to all task
/// models. The candidate's live ref, role, labels, state and actions remain,
/// and `Surface::read_value` still obtains the value directly for host-side
/// checks.
fn hide_form_values(screen: &mut Screen) {
fn hide(candidate: &mut Candidate) {
let editable = candidate
.available_actions
.iter()
.any(|action| matches!(action.as_str(), "SetValue" | "TypeText"))
|| matches!(
candidate.role.as_str(),
"textbox" | "searchbox" | "combobox" | "textarea" | "spinbutton"
)
|| tree::is_form_role(&candidate.role);
if editable {
candidate.value = None;
}
for child in &mut candidate.children {
hide(child);
}
}

for candidate in screen
.candidates
.iter_mut()
.chain(screen.text_nodes.iter_mut())
{
hide(candidate);
}
}

impl BrowserSurface {
/// Loads `request`'s address in session `id`. A heavy page can be read
/// long before its `load` event fires.
Expand Down Expand Up @@ -444,3 +483,47 @@ pub(crate) fn browser_key(combo: &str, platform: Platform) -> String {
.collect::<Vec<_>>()
.join("+")
}

#[cfg(test)]
mod private_value_tests {
use serde_json::json;
use tinycomputer_core::surface::{Candidate, Screen};

use super::hide_form_values;

#[test]
fn private_observations_hide_editable_values_and_keep_useful_structure() {
let mut screen = Screen {
app: "browser".into(),
window: None,
surface: "window".into(),
candidates: vec![Candidate {
ref_id: "field-1".into(),
role: "textbox".into(),
name: Some("Address".into()),
value: Some(json!("restored form content")),
available_actions: vec!["Click".into(), "SetValue".into()],
..Candidate::default()
}],
context: vec!["A lamp is ready to buy.".into()],
unexplored: Vec::new(),
text_nodes: vec![Candidate {
ref_id: "rich-field".into(),
role: "document".into(),
name: Some("Message body".into()),
value: Some(json!("restored rich text")),
available_actions: vec!["SetValue".into()],
..Candidate::default()
}],
};

hide_form_values(&mut screen);

assert_eq!(screen.candidates[0].value, None);
assert_eq!(screen.candidates[0].name.as_deref(), Some("Address"));
assert_eq!(screen.candidates[0].ref_id, "field-1");
assert_eq!(screen.text_nodes[0].value, None);
assert_eq!(screen.text_nodes[0].name.as_deref(), Some("Message body"));
assert_eq!(screen.context, ["A lamp is ready to buy."]);
}
}
11 changes: 11 additions & 0 deletions crates/tinycomputer-browser/src/surface/sight/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,24 @@ const MAX_CONTEXT_LINES: usize = 60;
/// ref from an earlier screen.
#[must_use]
pub(crate) fn script(root: Option<&str>) -> String {
script_with_form_values(root, true)
}

/// The Sight observation script for a host that keeps form values private.
#[must_use]
pub(crate) fn script_without_form_values(root: Option<&str>) -> String {
script_with_form_values(root, false)
}

fn script_with_form_values(root: Option<&str>, include_form_values: bool) -> String {
let root = root.map_or(Value::Null, |reference| Value::String(selector(reference)));
let limits = json!({
"controls": MAX_CONTROLS,
"texts": MAX_TEXTS,
"labels": MAX_LABELS,
"name": MAX_NAME,
"text": MAX_TEXT,
"hideFormValues": !include_form_values,
});
format!(
"({})({root}, {limits})",
Expand Down
18 changes: 16 additions & 2 deletions crates/tinycomputer-browser/src/surface/sight/sight.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,18 @@
}
return false;
};
const PRIVATE_FIELD_ROLES = [
'textbox', 'searchbox', 'combobox', 'textarea', 'document', 'spinbutton',
'checkbox', 'radio', 'switch', 'menuitemcheckbox', 'menuitemradio',
];
const privateField = (element) => ['input', 'select', 'textarea'].includes(tag(element))
|| takesText(element) || PRIVATE_FIELD_ROLES.includes(role(element));
const insidePrivateField = (element) => {
for (let parent = element; parent; parent = parent.parentElement) {
if (privateField(parent)) return true;
}
return false;
};

// A box that takes typed text: a text-like input, a text area, or the
// outermost editable region. Whatever role the page gives it.
Expand Down Expand Up @@ -1204,7 +1216,8 @@
const parent = node.parentElement;
if (!parent || !squash(node.data) || texts >= limits.texts) continue;
if (lastText && lastText.contains(parent)) continue;
if (controls.has(parent) || insideControl(parent) || insideText(parent) || !shown(parent)) continue;
if (controls.has(parent) || insideControl(parent) || insideText(parent) || !shown(parent)
|| (limits.hideFormValues && insidePrivateField(parent))) continue;
const rect = box(parent);
if (rect.bottom < -height || rect.top > 2 * height) continue;
const dropped = noiseRoot(parent);
Expand All @@ -1218,6 +1231,7 @@
continue;
}
const element = node;
if (limits.hideFormValues && insidePrivateField(element.parentElement)) continue;
const dropped = noiseRoot(element);
// An ad's own frame or picture is an ad whether or not it shows words.
if (dropped === element && ['iframe', 'img'].includes(tag(element))
Expand Down Expand Up @@ -1308,7 +1322,7 @@
role: what,
name,
description,
value: valueOf(element, what),
value: limits.hideFormValues && privateField(element) ? '' : valueOf(element, what),
states: statesOf(element, what),
box: [box(element).x, box(element).y, box(element).width, box(element).height].map(Math.round),
path: pathOf(element),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use serde_json::json;

#[cfg(feature = "agent-browser")]
use crate::surface::sight::script;
use crate::surface::sight::{script, script_without_form_values};

/// Reads `html` by sight in a real browser: `None` unless
/// `TINYCOMPUTER_LIVE_BROWSER=1`, since CI has no browser to launch. The
Expand Down Expand Up @@ -165,6 +165,35 @@ async fn live_ad_iframes_and_sponsored_blocks_are_removed() {
);
}

#[cfg(feature = "agent-browser")]
#[tokio::test]
async fn live_private_sight_omits_editable_descendant_content() {
const UNKNOWN: &str = "profile-autofill-unknown-7Qz9";
let html = format!(
r#"<main>
<div contenteditable="true" aria-label="Message">
<span>{UNKNOWN}</span>
<button aria-label="{UNKNOWN} action">Send</button>
</div>
<p>Order total is $12.50</p>
</main>"#
);
let Some(mut readings) =
live_results(&html, &[script_without_form_values(None), script(None)]).await
else {
return;
};
let private = readings.remove(0);
let public = readings.remove(0);
let private_text = private.to_string();
let public_text = public.to_string();

assert!(!private_text.contains(UNKNOWN));
assert!(private_text.contains("Message"));
assert!(private_text.contains("Order total is $12.50"));
assert!(public_text.contains(UNKNOWN));
}

#[cfg(feature = "agent-browser")]
#[tokio::test]
async fn live_blank_containers_are_dropped() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,18 @@

use serde_json::json;

use crate::surface::sight::{Denoised, denoised, is_seen, screen, script, selector};
use crate::surface::sight::{
Denoised, denoised, is_seen, screen, script, script_without_form_values, selector,
};

#[test]
fn private_sight_script_skips_form_content_descendants() {
let private = script_without_form_values(None);
let public = script(None);

assert!(private.contains("\"hideFormValues\":true"));
assert!(public.contains("\"hideFormValues\":false"));
}

/// A booking widget as sight reads it: a cookie dialog in front, a field
/// named by the words above it, a city row a page marked `combobox`, and an
Expand Down Expand Up @@ -108,7 +119,7 @@ fn the_script_is_called_with_its_root_and_limits() {
assert!(whole.contains("data-tc-seen"));
assert!(
whole.ends_with(
r#"(null, {"controls":800,"labels":3000,"name":120,"text":160,"texts":400})"#
r#"(null, {"controls":800,"hideFormValues":false,"labels":3000,"name":120,"text":160,"texts":400})"#
)
);
let under = script(Some("seen:7"));
Expand Down
Loading
Loading