Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Browser payment floor: Space on a focused button asks like Enter

Ada (kwant bot)6d4891691eda
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 059837e0..bfe444a3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -58,7 +58,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Changed
- **Browser checkouts ask before paying, also behind a plain "Continue".** Before a bot clicks or
- presses Enter in its browser, kwant reads the page: the button the click would really hit, card
+ presses Enter or Space in its browser, kwant reads the page: the button the click would really hit, card
number or CVC fields, a payment provider's card frame (Stripe, Braintree, Adyen, …) and forms that
post to a checkout. Any of these gets the payment card in every approval mode, as before for
"Pay" buttons and checkout addresses. Bots using the browser through the shell can't show a card,
diff --git a/docs/payments.md b/docs/payments.md
index 8120d0fd..1f512d58 100644
--- a/docs/payments.md
+++ b/docs/payments.md
@@ -55,7 +55,7 @@ every MCP tool, through claude's permission prompt and the MCP gateway), in
- Clicking a pay-type label: `Pay`, `Buy`, `Purchase`, `Checkout`/`Check out`, `Subscribe`,
`Upgrade`, `Donate`, `Place order`, `Confirm order`, `Complete payment`, `Book now`, `Top up`,
… or any label with a price on it (`$12.99`, `12,99 €`, `USD 10`).
-- Any click, or Enter, on a checkout page: a payment host (`checkout.stripe.com`, `paypal.com`,
+- Any click, Enter or Space on a checkout page: a payment host (`checkout.stripe.com`, `paypal.com`,
`pay.google.com`, …), a host starting `checkout.`/`pay.`/`payment.`/`billing.`, or a path
segment like `/checkout`, `/payment`, `/pay`, `/billing`, `/buy`, `/subscribe`. The address
comes from the browser, not the bot.
@@ -74,8 +74,9 @@ rules in `payment_floor::page_reason`), so the bot's own words never decide:
"Continue", "Next", "Finish" and "Submit" ask there; buttons starting "Cancel", "Back", "Edit",
"Apply", "Add", … and clicks into the fields don't.
- A submit button whose form posts to a checkout address (`action` or `formaction`).
-- Enter in a card field, in a form with card fields, in a form that posts to a checkout address,
- or anywhere on a page with a payment provider's card frame.
+- Enter or Space in a card field, in a form with card fields, in a form that posts to a checkout
+ address, or anywhere on a page with a payment provider's card frame. Either key on a focused
+ button or link presses it, so the click rules above apply to it, by the text it shows.
The shell bots' browser API (`POST /api/sandbox/:id/act`) can't show a card, so it doesn't do an
action that looks like a payment: the page comes back with `error` ("Not done: this looks like a
diff --git a/src/mcp/payment_floor.rs b/src/mcp/payment_floor.rs
index 0c65479d..cb77a1c6 100644
--- a/src/mcp/payment_floor.rs
+++ b/src/mcp/payment_floor.rs
@@ -112,13 +112,8 @@ fn self_reason(tool: &str, args: &Value, page_url: Option<&str>) -> Option<Strin
}
"type" => card_number(text).then(|| "typing what looks like a card number".to_string()),
"key" => {
- let key = args["key"].as_str().unwrap_or("Enter");
- let submits = matches!(key.to_ascii_lowercase().as_str(), "enter" | "return" | "numpadenter");
- if submits {
- page_url.and_then(checkout_page).map(|page| format!("Enter on a checkout page ({page})"))
- } else {
- None
- }
+ let name = submit_key(args["key"].as_str())?;
+ page_url.and_then(checkout_page).map(|page| format!("{name} on a checkout page ({page})"))
}
_ => None,
}
@@ -187,6 +182,16 @@ fn payment_frame(frame: &FrameSignal) -> Option<String> {
.then(|| frame.title.chars().take(60).collect())
}
+/// The name of a key that can submit or press what has focus: Enter submits a form, and Space
+/// presses a focused button. A missing key means Enter. Every other key is `None`.
+fn submit_key(key: Option<&str>) -> Option<&'static str> {
+ match key.unwrap_or("Enter").to_ascii_lowercase().as_str() {
+ "enter" | "return" | "numpadenter" => Some("Enter"),
+ " " | "space" | "spacebar" => Some("Space"),
+ _ => None,
+ }
+}
+
/// Why a `browser_act` is a payment from what the page shows (see [`PageSignals`]), or `None`.
/// Pure, so the rules are tested as tables; the bot's own words never mark a call as safe.
pub fn page_reason(action: &str, key: Option<&str>, page: &PageSignals) -> Option<String> {
@@ -219,20 +224,23 @@ pub fn page_reason(action: &str, key: Option<&str>, page: &PageSignals) -> Optio
None
}
"key" => {
- let submits = matches!(key.unwrap_or("Enter").to_ascii_lowercase().as_str(), "enter" | "return" | "numpadenter");
- if !submits {
- return None;
- }
+ let name = submit_key(key)?;
if frame.is_some() && page.card_fields == 0 {
- return Some(format!("Enter on a page with {}", card_where()));
+ return Some(format!("{name} on a page with {}", card_where()));
}
let t = target?;
+ // Enter or Space on a focused button or link presses it, so the click rules apply
+ if t.kind == "button" || t.kind == "link" {
+ if let Some(why) = page_reason("click", None, page) {
+ return Some(why);
+ }
+ }
if t.card_field || t.in_form && t.form_card {
- return Some("Enter in a form with card fields".into());
+ return Some(format!("{name} in a form with card fields"));
}
if t.in_form {
if let Some(page) = checkout_page(&t.form_action) {
- return Some(format!("Enter in a form that sends to a checkout ({page})"));
+ return Some(format!("{name} in a form that sends to a checkout ({page})"));
}
}
None
@@ -670,7 +678,19 @@ mod tests {
let mut f = target("Card number (field)", "field");
f.card_field = true;
assert!(key("Enter", &focus(f.clone())).is_some());
+ assert!(key(" ", &focus(f.clone())).is_some(), "Space too");
assert!(key("Tab", &focus(f)).is_none());
+ // Space or Enter on a focused button presses it: the click rules decide
+ let mut finish = target("Finish", "button");
+ finish.in_form = true;
+ finish.form_action = "https://shop.example.com/checkout/complete".into();
+ for k in [" ", "Space", "Spacebar", "Enter"] {
+ assert!(key(k, &focus(finish.clone())).is_some(), "{k:?} on a checkout button");
+ }
+ let place = target("Place order", "button");
+ assert!(key(" ", &focus(place.clone())).expect("Space on Place order").contains("place order"));
+ assert!(key("Tab", &focus(place)).is_none());
+ assert!(key(" ", &focus(target("Help", "button"))).is_none());
let mut name = target("Name on card (field)", "field");
name.in_form = true;
name.form_card = true;
@@ -701,6 +721,11 @@ mod tests {
assert!(act(json!({"action": "click_text", "text": "Continue"}), Some("https://shop.example.com/checkout/step-2")).is_some());
assert!(act(json!({"action": "click_text", "text": "Next"}), Some("https://checkout.stripe.com/c/pay/cs_test")).is_some());
assert!(act(json!({"action": "key", "key": "Enter"}), Some("https://www.paypal.com/checkoutnow?token=x")).is_some());
+ for k in [" ", "Space", "space", "Spacebar"] {
+ let why = act(json!({"action": "key", "key": k}), Some("https://shop.example.com/checkout-step-two.html"));
+ assert!(why.expect(k).starts_with("Space on a checkout page"), "{k:?}");
+ }
+ assert!(act(json!({"action": "key", "key": " "}), Some("https://example.com/search")).is_none());
assert!(act(json!({"action": "key", "key": "Tab"}), Some("https://shop.example.com/checkout")).is_none());
assert!(act(json!({"action": "key", "key": "Enter"}), Some("https://example.com/search")).is_none());
assert!(act(json!({"action": "scroll"}), Some("https://shop.example.com/checkout")).is_none());
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index 4295fc1c..7ae696cb 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -176,7 +176,13 @@ const PAYMENT_SIGNALS_JS: &str = r#"function (needle) {
var a = document.activeElement;
try { while (a && a.shadowRoot && a.shadowRoot.activeElement) a = a.shadowRoot.activeElement; } catch (e) {}
try { while (a && a.tagName === 'IFRAME' && a.contentDocument && a.contentDocument.activeElement) a = a.contentDocument.activeElement; } catch (e) {}
- if (a && a !== document.body && a !== document.documentElement) target = describe(a, (a.getAttribute('aria-label') || a.name || a.id || '').slice(0, 80));
+ if (a && a !== document.body && a !== document.documentElement) {
+ // A focused button or link is named by what it shows, so Enter or Space on "Place order" reads as that
+ var presses = a.tagName === 'BUTTON' || a.tagName === 'A' || /^(button|link)$/i.test(a.getAttribute('role') || '');
+ var shows = presses ? (a.innerText || '') : (a.tagName === 'INPUT' && /^(submit|button)$/i.test(a.type || '') ? a.value : '');
+ var name = a.getAttribute('aria-label') || shows.replace(/\s+/g, ' ').trim() || a.name || a.id || '';
+ target = describe(a, name.slice(0, 80));
+ }
}
return { url: location.href, target: target, card_fields: cards, frames: frames.slice(0, 40) };
}"#;
diff --git a/tests/browser_pay_gate_test.rs b/tests/browser_pay_gate_test.rs
index db0a7edd..20216de6 100644
--- a/tests/browser_pay_gate_test.rs
+++ b/tests/browser_pay_gate_test.rs
@@ -45,6 +45,8 @@ const ORDER_PAGE: &str = "<!doctype html><title>order</title>\
const FORM_PAGE: &str = "<!doctype html><title>form</title><form action='/shop/checkout/confirm' method=post>\
<input name=email placeholder=Email><button type=submit>Continue</button></form>\
<form action='/search'><input name=q placeholder=Search></form>";
+const FINISH_PAGE: &str = "<!doctype html><title>overview</title>\
+<button autofocus onclick=\"document.title='finished'\">Finish</button>";
const PLAIN_PAGE: &str = "<!doctype html><title>plain</title>\
<button onclick=\"document.title='went on'\">Continue</button><input name=q placeholder=Search>";
@@ -64,6 +66,7 @@ async fn serve() -> String {
"/frame" => FRAME_PAGE,
"/order" => ORDER_PAGE,
"/form" => FORM_PAGE,
+ "/checkout-step-two.html" => FINISH_PAGE,
_ => PLAIN_PAGE,
};
let reply = format!(
@@ -186,6 +189,38 @@ async fn the_page_decides_whether_a_browser_click_pays() {
assert_eq!(pay(&e, click("Continue")).await, None);
}
+#[tokio::test]
+async fn space_on_a_focused_button_asks_like_enter() {
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return;
+ }
+ let e = setup().await;
+ let _chrome = ChromeGuard(e.tmp.path().join("local-chrome"));
+ let base = serve().await;
+ let space = json!({"action": "key", "key": " "});
+
+ // An autofocused "Finish" on a checkout page: Space presses it, so it asks like Enter and click
+ let ctrl = open(&e, &format!("{base}/checkout-step-two.html")).await;
+ for args in [space.clone(), json!({"action": "key", "key": "Space"}), json!({"action": "key", "key": "Enter"})] {
+ assert!(pay(&e, args.clone()).await.is_some(), "{args}");
+ }
+ let (status, page) = post_act(&e.app, &e.bot.id, space.clone()).await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(page["error"].as_str().unwrap_or("").starts_with("Not done: this looks like a payment"), "{page}");
+ assert_eq!(title(&ctrl).await, "overview", "Finish was not pressed");
+
+ // A focused "Place order" asks by its label, on any address
+ let ctrl = open(&e, &format!("{base}/order")).await;
+ ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": "document.querySelector('button').focus()"})).await.unwrap();
+ assert!(pay(&e, space.clone()).await.expect("Space on Place order").contains("place order"));
+
+ // Space on a plain page's button runs
+ let ctrl = open(&e, &format!("{base}/plain")).await;
+ ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": "document.querySelector('button').focus()"})).await.unwrap();
+ assert_eq!(pay(&e, space).await, None);
+}
+
#[tokio::test]
async fn approvals_off_still_cards_a_card_form_click_and_the_shell_api_refuses_it() {
if computer::local_chrome_path().is_none() {