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 reads the page: card forms, payment frames, checkout forms

Lin (kwant bot)6bab495c74ce
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c510a235..059837e0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -57,6 +57,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
the notification toggles. This is step 4 of Automation Discovery.
### 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
+ 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,
+ so they leave that step to you. Clicks by screen position are now for your live view only.
- **kwant.si footer says "Made in Germany with ❤️".** The line sits under the trademark note on every
page; screen readers read it as "Made in Germany with love".
diff --git a/docs/payments.md b/docs/payments.md
index f65548ee..8120d0fd 100644
--- a/docs/payments.md
+++ b/docs/payments.md
@@ -62,6 +62,26 @@ every MCP tool, through claude's permission prompt and the MCP gateway), in
- Typing anything that looks like a card number: 13–19 digits (spaces or dashes allowed) that
pass the Luhn check.
+Before the click or key, kwnt also reads the page itself (`BrowserController::payment_signals`,
+rules in `payment_floor::page_reason`), so the bot's own words never decide:
+
+- The element the click would really hit (the same match `click_text` makes) has a pay-type
+ label: the bot wrote "order", the button is "Place order".
+- A button on a page with card fields: a card number or CVC field (`autocomplete="cc-number"`,
+ `cc-csc`, `cc-exp`, or a name/id/placeholder like `cardnumber`, `cvc`, `cvv`), in open shadow
+ roots and same-origin frames too, or a payment provider's card frame (`js.stripe.com`,
+ Braintree, Adyen, Square, PayPal, … or a frame titled like "Secure card payment input frame").
+ "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.
+
+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
+payment …") and `payment` (why), and the bot is told to leave that step to the person in the live
+browser panel. Clicks by position (`/api/sandbox/:id/interact`) are the person's live view only.
+
`WebFetch` never pays (it only reads). kwnt's own other tools don't pay, and
`self_tools_have_no_money_words` fails if one is added with a money word in its name until it is
classified here.
@@ -69,10 +89,11 @@ classified here.
## What it doesn't catch
- A plain "Continue", "Next" or "Confirm" button on a checkout page whose address doesn't look
- like one (no checkout word in the host or path).
+ like one and that shows no card fields or payment frame (e.g. a review step with a saved card).
- A card the website already has saved, one-click buying, and Apple Pay or Google Pay sheets.
-- Payment fields inside another site's frame on a normal-looking page (the address checked is
- the page's, not the frame's).
+- A payment frame from a provider missing from the lists, with no card-like title.
+- A page kwnt can't read before the click (the browser didn't answer): only the label and address
+ rules count then.
- A card number typed in pieces (one field for each group of 4 digits).
- Shell commands that hide the host or method: variables (`$URL`), scripts, config files, other
languages' HTTP libraries without `.post(`, and SDKs (`stripe.Charge.create(...)` in Python).
@@ -88,5 +109,6 @@ a `/billing` page. That's accepted: an extra card costs a tap, a missed payment
## Tests
-`cargo test --test payment_floor_test` and the tables in `src/mcp/payment_floor.rs`
+`cargo test --test payment_floor_test`, `cargo test --test browser_pay_gate_test` (a real
+Chrome on local card pages; `-- --ignored` also walks saucedemo.com to "Finish") and the tables in `src/mcp/payment_floor.rs`
(`cargo test --lib payment_floor`).
diff --git a/src/mcp/payment_floor.rs b/src/mcp/payment_floor.rs
index 3b91849d..0c65479d 100644
--- a/src/mcp/payment_floor.rs
+++ b/src/mcp/payment_floor.rs
@@ -91,6 +91,11 @@ fn builtin_reason(tool: &str, input: &Value) -> Option<String> {
}
}
+/// kwnt's `browser_act` by its arguments and the page address alone (before the page is read).
+pub fn browser_act_reason(args: &Value, page_url: Option<&str>) -> Option<String> {
+ self_reason("browser_act", args, page_url)
+}
+
/// kwnt's own tools: only `browser_act` can pay today. A new self tool with a money word in its
/// name fails `self_tools_have_no_money_words` until it is classified here.
fn self_reason(tool: &str, args: &Value, page_url: Option<&str>) -> Option<String> {
@@ -119,6 +124,123 @@ fn self_reason(tool: &str, args: &Value, page_url: Option<&str>) -> Option<Strin
}
}
+/// What kwnt's browser sees on the page before a `browser_act`, read by
+/// `BrowserController::payment_signals`: the element the action would hit, card fields and
+/// payment frames. Read from the page itself, so a plain "Continue" on a card form still asks.
+#[derive(Debug, Default, Clone, serde::Deserialize)]
+#[serde(default)]
+pub struct PageSignals {
+ /// The element a click would hit, or the focused one for a key.
+ pub target: Option<TargetSignals>,
+ /// Visible card number / CVC fields on the page (open shadow roots and same-origin frames too).
+ pub card_fields: u32,
+ /// Frames on the page as (host, title): a payment provider's card frame is cross-origin.
+ pub frames: Vec<FrameSignal>,
+}
+
+#[derive(Debug, Default, Clone, serde::Deserialize)]
+#[serde(default)]
+pub struct TargetSignals {
+ pub label: String,
+ /// `button`, `link`, `field` or `other`.
+ pub kind: String,
+ /// Inside a form (or the form a button submits).
+ pub in_form: bool,
+ /// The form's address when it names one (`action` or the button's `formaction`).
+ pub form_action: String,
+ /// The form has a card number or CVC field.
+ pub form_card: bool,
+ /// The element itself is a card field.
+ pub card_field: bool,
+}
+
+#[derive(Debug, Default, Clone, serde::Deserialize)]
+#[serde(default)]
+pub struct FrameSignal {
+ pub host: String,
+ pub title: String,
+}
+
+/// Card-field frame hosts that aren't in [`PAYMENT_HOSTS`].
+const PAY_FRAME_HOSTS: &[&str] = &[
+ "braintreegateway.com", "braintree-api.com", "squarecdn.com", "paddle.com", "worldpay.com", "cybersource.com",
+ "spreedly.com", "globalpay.com", "chargebee.com", "recurly.com", "hsforms.com",
+];
+
+/// First words of buttons that never pay, even on a card form.
+const NEVER_PAYS: &[&str] = &[
+ "cancel", "back", "close", "remove", "edit", "change", "help", "menu", "logout", "log", "sign", "show", "hide", "view",
+ "apply", "use", "add",
+];
+
+/// Why a payment frame is one: its host, or a card-input title ("Secure card payment input frame").
+fn payment_frame(frame: &FrameSignal) -> Option<String> {
+ let host = frame.host.trim_end_matches('.').to_lowercase();
+ let listed = !host.is_empty()
+ && (payment_host(&host) || PAY_FRAME_HOSTS.iter().any(|h| host == *h || host.ends_with(&format!(".{h}"))));
+ if listed {
+ return Some(host);
+ }
+ let title = words(&frame.title.to_lowercase());
+ let has = |w: &str| title.iter().any(|t| t == w);
+ (has("card") && (has("payment") || has("number") || has("input")) || has("payment") && has("input"))
+ .then(|| frame.title.chars().take(60).collect())
+}
+
+/// 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> {
+ let frame = page.frames.iter().find_map(payment_frame);
+ let card_on_page = page.card_fields > 0 || frame.is_some();
+ let card_where = || match &frame {
+ Some(f) if page.card_fields == 0 => format!("a payment frame ({f})"),
+ _ => "card fields".to_string(),
+ };
+ let target = page.target.as_ref();
+ match action {
+ "click_text" | "click" => {
+ let t = target?;
+ // The label of the element it really hits, not the words the bot wrote
+ if let Some(why) = pay_label(&t.label) {
+ return Some(why);
+ }
+ let presses = t.kind == "button" || t.kind == "link";
+ if presses && t.in_form {
+ if let Some(page) = checkout_page(&t.form_action) {
+ return Some(format!("a button that sends a checkout form ({page})"));
+ }
+ }
+ let first = words(&t.label.to_lowercase()).into_iter().next().unwrap_or_default();
+ let never = NEVER_PAYS.contains(&first.as_str()) || has_phrase(&t.label.to_lowercase(), "continue shopping");
+ if presses && !never && (t.form_card || card_on_page) {
+ let label = t.label.chars().take(40).collect::<String>();
+ return Some(format!("\"{label}\" on a page with {}", card_where()));
+ }
+ None
+ }
+ "key" => {
+ let submits = matches!(key.unwrap_or("Enter").to_ascii_lowercase().as_str(), "enter" | "return" | "numpadenter");
+ if !submits {
+ return None;
+ }
+ if frame.is_some() && page.card_fields == 0 {
+ return Some(format!("Enter on a page with {}", card_where()));
+ }
+ let t = target?;
+ if t.card_field || t.in_form && t.form_card {
+ return Some("Enter in a form with card fields".into());
+ }
+ 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})"));
+ }
+ }
+ None
+ }
+ _ => None,
+ }
+}
+
/// An MCP tool (incl. Composio): by its name and server, the Composio slugs it runs, and for
/// browser-type tools, the label it clicks or the card number it types.
fn mcp_reason(server: &str, tool: &str, args: &Value) -> Option<String> {
@@ -499,6 +621,72 @@ mod tests {
assert!(mcp("discord", "get_message", json!({"id": "4242424242424242"})).is_none());
}
+ fn target(label: &str, kind: &str) -> TargetSignals {
+ TargetSignals { label: label.into(), kind: kind.into(), ..Default::default() }
+ }
+
+ #[test]
+ fn the_page_decides_what_a_click_really_hits() {
+ let click = |page: &PageSignals| page_reason("click_text", None, page);
+ // The bot wrote "Order" but the element it hits is "Place order"
+ let hits = |t: TargetSignals| PageSignals { target: Some(t), ..Default::default() };
+ assert!(click(&hits(target("Place order", "button"))).is_some());
+ assert!(click(&hits(target("Pay $12.99", "button"))).is_some());
+ assert!(click(&hits(target("Continue", "button"))).is_none(), "a plain button on a plain page");
+ // A plain "Continue" on a page with card fields asks; Cancel, Back and the fields don't
+ let card = |t: TargetSignals| PageSignals { target: Some(t), card_fields: 2, ..Default::default() };
+ for label in ["Continue", "Next", "Finish", "Submit", "Confirm", "Review"] {
+ assert!(click(&card(target(label, "button"))).is_some(), "{label}");
+ }
+ for label in ["Cancel", "Back to cart", "Continue shopping", "Apply coupon", "Edit address"] {
+ assert!(click(&card(target(label, "button"))).is_none(), "{label}");
+ }
+ assert!(click(&card(target("Card number (field)", "field"))).is_none(), "clicking into a field");
+ // A card frame from Stripe (cross-origin) counts, as does its title
+ let frame = |host: &str, title: &str, t: TargetSignals| PageSignals {
+ target: Some(t),
+ frames: vec![FrameSignal { host: host.into(), title: title.into() }],
+ ..Default::default()
+ };
+ let why = click(&frame("js.stripe.com", "", target("Continue", "button"))).unwrap();
+ assert!(why.contains("js.stripe.com"), "{why}");
+ assert!(click(&frame("pay.example-psp.io", "Secure card payment input frame", target("Next", "button"))).is_some());
+ assert!(click(&frame("www.youtube.com", "YouTube video player", target("Next", "button"))).is_none());
+ // A submit button whose form posts to a checkout address
+ let mut t = target("Continue", "button");
+ t.in_form = true;
+ t.form_action = "https://shop.example.com/checkout/confirm".into();
+ assert!(click(&hits(t.clone())).is_some());
+ t.form_action = "https://shop.example.com/search".into();
+ assert!(click(&hits(t)).is_none());
+ // Nothing found under the label: no page rule (the label and address rules still run)
+ assert!(click(&PageSignals { card_fields: 3, ..Default::default() }).is_none());
+ }
+
+ #[test]
+ fn enter_asks_in_a_card_form_or_a_checkout_form() {
+ let key = |k: &str, page: &PageSignals| page_reason("key", Some(k), page);
+ let focus = |t: TargetSignals| PageSignals { target: Some(t), ..Default::default() };
+ let mut f = target("Card number (field)", "field");
+ f.card_field = true;
+ assert!(key("Enter", &focus(f.clone())).is_some());
+ assert!(key("Tab", &focus(f)).is_none());
+ let mut name = target("Name on card (field)", "field");
+ name.in_form = true;
+ name.form_card = true;
+ assert!(key("Enter", &focus(name)).is_some());
+ let mut search = target("Search (field)", "field");
+ search.in_form = true;
+ search.form_action = "https://example.com/search".into();
+ assert!(key("Enter", &focus(search.clone())).is_none());
+ search.form_action = "https://example.com/billing/upgrade".into();
+ assert!(key("Enter", &focus(search)).is_some());
+ let stripe = PageSignals { frames: vec![FrameSignal { host: "js.stripe.com".into(), title: String::new() }], ..Default::default() };
+ assert!(key("Enter", &stripe).is_some());
+ assert!(page_reason("scroll", None, &stripe).is_none());
+ assert!(page_reason("type", None, &stripe).is_none(), "typing alone doesn't pay; the submit does");
+ }
+
#[test]
fn kwnt_browser_act() {
let act = |a: Value, url: Option<&str>| self_reason("browser_act", &a, url);
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index 39d68568..4295fc1c 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -38,8 +38,9 @@ pub(crate) async fn connect_cdp(url: &str) -> Result<WsStream, BrowserError> {
/// `function(needle)` evaluated in the page. Collects visible interactive elements (incl. open
/// shadow roots and same-origin iframes), topmost first. With a needle, picks the best label match
-/// and either returns its viewport center (when nothing covers it) or clicks it directly.
-const CLICKABLES_JS: &str = r#"function (needle) {
+/// and either returns its viewport center (when nothing covers it) or clicks it directly. With
+/// `probe`, returns the matched item itself (with its element) and touches nothing.
+const CLICKABLES_JS: &str = r#"function (needle, probe) {
var SEL = 'button,a[href],[role=button],[role=link],[role=menuitem],[role=tab],[role=checkbox],[role=option],input,textarea,select,summary,label,[onclick]';
var items = [];
function clean(s) { return (s || '').replace(/\s+/g, ' ').trim().slice(0, 80); }
@@ -92,6 +93,7 @@ const CLICKABLES_JS: &str = r#"function (needle) {
var s = l === n ? 3 : l.indexOf(n) === 0 ? 2 : l.indexOf(n) >= 0 ? 1 : 0;
if (s > best) { best = s; match = items[j]; }
}
+ if (probe) return match;
if (match) {
var m = match.el;
if (!match.onTop) {
@@ -107,6 +109,78 @@ const CLICKABLES_JS: &str = r#"function (needle) {
return { items: items.map(function (i) { return { label: i.label, onTop: i.onTop }; }), match: match };
}"#;
+/// What the payment floor needs from the page before a `browser_act` (see
+/// `payment_floor::PageSignals`): the element a click on `needle` would hit (the same match as
+/// `click_text`) or, with no needle, the focused element; visible card fields; and frames by host.
+const PAYMENT_SIGNALS_JS: &str = r#"function (needle) {
+ var CLICK = __CLICKABLES__;
+ var CARD = /card.?num|cardnumber|cc.?num|credit.?card|card.?cvc|\bcvc2?\b|\bcvv2?\b/i;
+ function isCard(el) {
+ if (!el || el.tagName !== 'INPUT') return false;
+ var t = (el.type || '').toLowerCase();
+ if (['hidden', 'checkbox', 'radio', 'submit', 'button', 'image', 'reset'].indexOf(t) >= 0) return false;
+ var ac = (el.getAttribute('autocomplete') || '').toLowerCase();
+ if (/\bcc-(number|csc|exp)/.test(ac)) return true;
+ return CARD.test([el.name, el.id, el.placeholder, el.getAttribute('aria-label'), el.getAttribute('data-stripe')].join(' '));
+ }
+ function shown(el) {
+ var r = el.getBoundingClientRect();
+ if (r.width < 2 || r.height < 2) return false;
+ var cs = getComputedStyle(el);
+ return cs.visibility !== 'hidden' && cs.display !== 'none';
+ }
+ var cards = 0, frames = [];
+ function walk(root) {
+ var all;
+ try { all = root.querySelectorAll('*'); } catch (e) { return; }
+ for (var i = 0; i < all.length; i++) {
+ var el = all[i];
+ if (el.shadowRoot) walk(el.shadowRoot);
+ if (el.tagName === 'IFRAME') {
+ var host = '';
+ try { host = new URL(el.src, location.href).hostname; } catch (e) {}
+ if (shown(el)) frames.push({ host: host, title: (el.title || el.name || '').slice(0, 120) });
+ try { var d = el.contentDocument; if (d) walk(d); } catch (e) {}
+ continue;
+ }
+ if (isCard(el) && shown(el)) cards++;
+ }
+ }
+ walk(document);
+ function formOf(el) {
+ var f = el.form || (el.closest && el.closest('form'));
+ return f || null;
+ }
+ function describe(el, label) {
+ if (!el) return null;
+ var tag = el.tagName, role = (el.getAttribute('role') || '').toLowerCase(), t = (el.type || '').toLowerCase();
+ var kind = 'other';
+ if (tag === 'BUTTON' || role === 'button' || (tag === 'INPUT' && ['submit', 'button', 'image', 'reset'].indexOf(t) >= 0)
+ || el.hasAttribute('onclick') || tag === 'SUMMARY') kind = 'button';
+ else if (tag === 'A' || role === 'link') kind = 'link';
+ else if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') kind = 'field';
+ var f = formOf(el), action = '', formCard = false;
+ if (f) {
+ var a = el.getAttribute && el.getAttribute('formaction') ? el.formAction : (f.getAttribute('action') ? f.action : '');
+ action = String(a || '');
+ var inputs = f.querySelectorAll('input');
+ for (var i = 0; i < inputs.length; i++) if (isCard(inputs[i])) { formCard = true; break; }
+ }
+ return { label: label || '', kind: kind, in_form: !!f, form_action: action, form_card: formCard, card_field: isCard(el) };
+ }
+ var target = null;
+ if (needle) {
+ var m = CLICK(needle, true);
+ if (m) target = describe(m.el, m.label);
+ } else {
+ 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));
+ }
+ return { url: location.href, target: target, card_fields: cards, frames: frames.slice(0, 40) };
+}"#;
+
#[derive(Error, Debug)]
pub enum BrowserError {
#[error("HTTP error connecting to CDP: {0}")]
@@ -1210,6 +1284,23 @@ impl BrowserController {
Some((url, title))
}
+ /// What the page shows for the payment floor before `action` (see [`PAYMENT_SIGNALS_JS`]):
+ /// for a click the element `needle` would hit, for a key the focused element. Reads only.
+ pub async fn payment_signals(&self, needle: Option<&str>) -> Result<Value, BrowserError> {
+ let needle = serde_json::to_string(&needle).map_err(|e| BrowserError::Protocol(e.to_string()))?;
+ let script = PAYMENT_SIGNALS_JS.replace("__CLICKABLES__", CLICKABLES_JS);
+ let res = self
+ .send_cdp_command(
+ "Runtime.evaluate",
+ json!({ "expression": format!("({script})({needle})"), "returnByValue": true }),
+ )
+ .await?;
+ if let Some(err) = res.get("exceptionDetails") {
+ return Err(BrowserError::Protocol(format!("payment check failed: {}", err["text"])));
+ }
+ Ok(res["result"]["value"].clone())
+ }
+
/// Labels of visible interactive elements, topmost (e.g. modal buttons) first.
pub async fn list_clickables(&self, limit: usize) -> Vec<String> {
let expression = format!("({})(null)", CLICKABLES_JS);
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 0fda1a8f..f0f176a2 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -315,6 +315,9 @@ pub fn person_only(method: &Method, path: &str) -> bool {
let segs: Vec<&str> = path.trim_end_matches('/').split('/').collect();
match segs.as_slice() {
["", "api", "sandbox", _, "passwords", ..] => true,
+ // Raw clicks by position are the person's live view: a bot clicking by coordinates would
+ // skip the payment floor, which reads the element under a label (bots use /act)
+ ["", "api", "sandbox", _, "interact"] => true,
["", "api", "passwords", ..] => true,
// Loose ends read the person's mail: bots never see or change them
["", "api", "zombie", ..] => true,
@@ -863,6 +866,8 @@ mod tests {
assert!(person_only(&get, "/api/sandbox/t1/passwords"));
assert!(person_only(&post, "/api/sandbox/t1/passwords/c1/reveal"));
assert!(person_only(&del, "/api/sandbox/t1/passwords/c1"));
+ assert!(person_only(&post, "/api/sandbox/t1/interact"));
+ assert!(!person_only(&post, "/api/sandbox/t1/act"));
assert!(person_only(&get, "/api/passwords/store"));
assert!(person_only(&post, "/api/messages/m1/decisions/0/change"));
assert!(person_only(&post, "/api/work-ahead/run"));
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index a6b43352..46b05e0a 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -373,11 +373,11 @@ impl ToolApprover for SelfToolsApprover {
// The payment floor (D8): a click or key on a checkout page, a pay-type button or a typed
// card number gets a card in every mode. The address comes from the browser, not the bot.
if req.server == SELF_SERVER_NAME && req.tool == BROWSER_ACT {
- let url = match &self.browser {
- Some((state, target)) => page_url(state, target).await,
- None => None,
+ let why = match &self.browser {
+ Some((state, target)) => browser_act_payment(state, target, &req.arguments).await,
+ None => crate::mcp::payment_floor::reason(&req, None),
};
- if let Some(why) = crate::mcp::payment_floor::reason(&req, url.as_deref()) {
+ if let Some(why) = why {
req.payment = Some(why);
return self.inner.decide(req).await;
}
@@ -418,11 +418,42 @@ fn outside_turn(scope: &SelfScope) -> Option<&str> {
scope.turn_id.as_deref().filter(|t| super::missions::truth_ledger::is_tainted(t))
}
-/// The address the turn's browser shows now, without starting a browser.
-async fn page_url(state: &AppState, target: &str) -> Option<String> {
- let ctrl = state.browser_controllers.lock().await.get(target).cloned()?;
- let url = ctrl.current_url.lock().await.clone();
- url
+/// Why a `browser_act` on `target`'s browser is a payment (D8), or `None`. First the label the bot
+/// wrote and the address the browser shows; then the page itself: the element the click really
+/// hits, a form that posts to a checkout, card fields and payment frames (`page_reason`). Uses
+/// only a browser that is already open. If the page can't be read, only the first rules count.
+pub async fn browser_act_payment(state: &AppState, target: &str, args: &Value) -> Option<String> {
+ use crate::mcp::payment_floor::{browser_act_reason, page_reason, PageSignals};
+ let ctrl = state.browser_controllers.lock().await.get(target).cloned();
+ let url = match &ctrl {
+ Some(ctrl) => ctrl.current_url.lock().await.clone(),
+ None => None,
+ };
+ if let Some(why) = browser_act_reason(args, url.as_deref()) {
+ return Some(why);
+ }
+ let ctrl = ctrl?;
+ let action = args["action"].as_str().unwrap_or("");
+ let needle = match action {
+ "click_text" | "click" => Some(args["text"].as_str().map(str::trim).filter(|t| !t.is_empty())?),
+ "key" => None,
+ _ => return None,
+ };
+ let page = match ctrl.payment_signals(needle).await {
+ Ok(page) => page,
+ Err(e) => {
+ tracing::warn!(error = %e, "payment floor could not read the page");
+ return None;
+ }
+ };
+ // The address the page reports now (the stored one can lag a client-side navigation)
+ if let Some(now) = page["url"].as_str().filter(|u| Some(*u) != url.as_deref()) {
+ if let Some(why) = browser_act_reason(args, Some(now)) {
+ return Some(why);
+ }
+ }
+ let signals: PageSignals = serde_json::from_value(page).unwrap_or_default();
+ page_reason(action, args["key"].as_str(), &signals)
}
/// The tools a turn's kwant server lists: `skill_draft` only while the bot has a Skill Foundry
@@ -609,7 +640,7 @@ async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, na
}
async fn run_browser_tool(state: &AppState, target: &str, name: &str, args: &Value) -> (String, bool) {
- use super::routes::{act_sandbox, get_sandbox_page, navigate_sandbox, InteractPayload, NavigatePayload};
+ use super::routes::{act_sandbox_allowed, get_sandbox_page, navigate_sandbox, InteractPayload, NavigatePayload};
let state = State(state.clone());
let target = Path(target.to_string());
let result = match name {
@@ -634,7 +665,8 @@ async fn run_browser_tool(state: &AppState, target: &str, name: &str, args: &Val
delta_x: None,
delta_y: args["delta_y"].as_f64(),
};
- act_sandbox(state, target, Json(payload)).await
+ // SelfToolsApprover already gave a payment its card (browser_act_payment)
+ act_sandbox_allowed(state, target, Json(payload)).await
}
};
match result {
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 715020f0..12100cae 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -4386,12 +4386,37 @@ pub async fn get_sandbox_page(
Ok(Json(sandbox_page_state(&ctrl).await))
}
-/// Agent-facing action endpoint: performs one action and returns the resulting page state,
-/// so an agent can act and answer without extra round-trips.
+/// Agent-facing action endpoint (`POST /api/sandbox/:id/act`, the shell bots' browser API):
+/// performs one action and returns the resulting page state, so an agent can act and answer
+/// without extra round-trips. This path has no approval card to show, so an action that looks
+/// like a payment (D8, `continuity::browser_act_payment`) is not done here: the bot is told to
+/// leave that step to the person. `browser_act` asks with a card and then runs [`act_sandbox_allowed`].
pub async fn act_sandbox(
State(state): State<AppState>,
Path(team_id): Path<String>,
Json(payload): Json<InteractPayload>,
+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
+ let ctrl = get_or_create_browser_controller(&state, &team_id)
+ .await
+ .ok_or_else(|| browser_unavailable(&state))?;
+ let args = json!({"action": payload.action, "text": payload.text, "key": payload.key});
+ if let Some(why) = super::continuity::browser_act_payment(&state, &team_id, &args).await {
+ let mut page = sandbox_page_state(&ctrl).await;
+ page["payment"] = json!(why);
+ page["error"] = json!(format!(
+ "Not done: this looks like a payment ({why}). Payments always need the person's OK, and this browser API can't ask for it. \
+ Tell the person what you were about to do and ask them to finish this step themselves in the live browser panel (Take Control)."
+ ));
+ return Ok(Json(page));
+ }
+ act_sandbox_allowed(State(state), Path(team_id), Json(payload)).await
+}
+
+/// [`act_sandbox`] without the payment check: for `browser_act`, whose approver already asked.
+pub async fn act_sandbox_allowed(
+ State(state): State<AppState>,
+ Path(team_id): Path<String>,
+ Json(payload): Json<InteractPayload>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let ctrl = get_or_create_browser_controller(&state, &team_id)
.await
diff --git a/tests/browser_pay_gate_test.rs b/tests/browser_pay_gate_test.rs
new file mode 100644
index 00000000..db0a7edd
--- /dev/null
+++ b/tests/browser_pay_gate_test.rs
@@ -0,0 +1,290 @@
+//! The payment floor reads the page in kwnt's own browser before a `browser_act` (D8): a plain
+//! "Continue" on a card form, a label that matches a "Place order" button, a submit into a
+//! checkout form, and Enter in a card form all ask, with approvals off, through a real Chrome.
+//! The shell bots' `/act` API can't show a card, so it refuses those and does nothing.
+//! Skipped when no Chrome is installed. `saucedemo_checkout_asks_before_finish` (ignored, needs
+//! the network) walks a real demo shop to its last step.
+#[path = "support/chrome_guard.rs"]
+mod chrome_guard;
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrome_guard::ChromeGuard;
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::Kwant, spaces::SpaceId, Database},
+ mcp::{ApprovalOutcome, ToolApprovalRequest, ToolApprover, SELF_SERVER_NAME},
+ router::LayaRouter,
+ sandbox::computer,
+ server::{
+ continuity::{browser_act_payment, SelfToolsApprover},
+ create_router, mcp_runtime,
+ routes::get_or_create_browser_controller,
+ AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::{sync::Arc, time::Duration};
+use tempfile::{tempdir, TempDir};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tower::ServiceExt;
+
+const CARD_PAGE: &str = "<!doctype html><title>card</title><form onsubmit=\"document.title='sent';return false\">\
+<input name=name placeholder='Name on card'><input autocomplete=cc-number placeholder='1234 1234 1234 1234'>\
+<input name=cvc placeholder=CVC><button type=button onclick=\"history.back()\">Cancel</button>\
+<button type=submit>Continue</button></form>";
+const FRAME_PAGE: &str = "<!doctype html><title>frame</title>\
+<iframe title='Secure card payment input frame' srcdoc='<input>' style='width:300px;height:40px'></iframe>\
+<button onclick=\"document.title='next'\">Next</button>";
+const ORDER_PAGE: &str = "<!doctype html><title>order</title>\
+<button onclick=\"document.title='ordered'\">Place order</button><a href='#help'>Help</a>";
+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 PLAIN_PAGE: &str = "<!doctype html><title>plain</title>\
+<button onclick=\"document.title='went on'\">Continue</button><input name=q placeholder=Search>";
+
+/// A small HTTP server for the pages above on 127.0.0.1, so the test needs no network.
+async fn serve() -> String {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ tokio::spawn(async move {
+ let mut buf = [0u8; 4096];
+ let n = stream.read(&mut buf).await.unwrap_or(0);
+ let req = String::from_utf8_lossy(&buf[..n]).to_string();
+ let path = req.split_whitespace().nth(1).unwrap_or("/").to_string();
+ let page = match path.as_str() {
+ "/card" => CARD_PAGE,
+ "/frame" => FRAME_PAGE,
+ "/order" => ORDER_PAGE,
+ "/form" => FORM_PAGE,
+ _ => PLAIN_PAGE,
+ };
+ let reply = format!(
+ "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{page}",
+ page.len()
+ );
+ let _ = stream.write_all(reply.as_bytes()).await;
+ });
+ }
+ });
+ format!("http://127.0.0.1:{port}")
+}
+
+struct Env {
+ app: Router,
+ state: AppState,
+ bot: Kwant,
+ tmp: TempDir,
+}
+
+/// kwnt in Local mode, so the bot's browser is a real Chrome on this machine.
+async fn setup() -> Env {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ db.set_setting(computer::SETTING_KEY, "local").await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap()[0].clone();
+ Env { app: create_router(state.clone()), state, bot, tmp }
+}
+
+async fn open(e: &Env, url: &str) -> kwnt::sandbox::BrowserController {
+ let ctrl = get_or_create_browser_controller(&e.state, &e.bot.id).await.expect("local Chrome session");
+ ctrl.navigate(url).await.unwrap();
+ ctrl
+}
+
+async fn title(ctrl: &kwnt::sandbox::BrowserController) -> String {
+ ctrl.sync_location().await.map(|(_, t)| t).unwrap_or_default()
+}
+
+async fn pay(e: &Env, args: Value) -> Option<String> {
+ browser_act_payment(&e.state, &e.bot.id, &args).await
+}
+
+fn act_request(e: &Env, args: Value) -> ToolApprovalRequest {
+ ToolApprovalRequest {
+ kwant_id: e.bot.id.clone(),
+ kwant_name: e.bot.name.clone(),
+ turn_id: "t-pay".into(),
+ tool_name: format!("mcp__{SELF_SERVER_NAME}__browser_act"),
+ server: SELF_SERVER_NAME.into(),
+ tool: "browser_act".into(),
+ arguments: args,
+ builtin: None,
+ smart: None,
+ payment: None,
+ }
+}
+
+async fn post_act(app: &Router, bot: &str, body: Value) -> (StatusCode, Value) {
+ let req = Request::builder()
+ .method("POST")
+ .uri(format!("/api/sandbox/{bot}/act"))
+ .header("content-type", "application/json")
+ .body(Body::from(body.to_string()))
+ .unwrap();
+ let resp = app.clone().oneshot(req).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+#[tokio::test]
+async fn the_page_decides_whether_a_browser_click_pays() {
+ 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 click = |label: &str| json!({"action": "click_text", "text": label});
+
+ // A plain "Continue" on a card form asks; Cancel and clicking into a field don't
+ open(&e, &format!("{base}/card")).await;
+ let why = pay(&e, click("Continue")).await.expect("Continue on a card form");
+ assert!(why.contains("card fields"), "{why}");
+ assert_eq!(pay(&e, click("Cancel")).await, None);
+ assert_eq!(pay(&e, click("CVC")).await, None, "clicking into a field");
+ // Enter in the card form asks too (focus the CVC field first)
+ let ctrl = open(&e, &format!("{base}/card")).await;
+ ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": "document.querySelector('[name=cvc]').focus()"})).await.unwrap();
+ assert!(pay(&e, json!({"action": "key", "key": "Enter"})).await.is_some());
+ assert_eq!(pay(&e, json!({"action": "key", "key": "Tab"})).await, None);
+
+ // A card frame from a payment provider, known by its title
+ open(&e, &format!("{base}/frame")).await;
+ assert!(pay(&e, click("Next")).await.expect("Next beside a card frame").contains("payment frame"));
+
+ // The bot writes "order"; the button it would really hit is "Place order"
+ open(&e, &format!("{base}/order")).await;
+ assert!(pay(&e, click("order")).await.expect("matched Place order").contains("place order"));
+ assert_eq!(pay(&e, click("Help")).await, None);
+
+ // A submit whose form posts to a checkout address; the search form's Enter doesn't ask
+ let ctrl = open(&e, &format!("{base}/form")).await;
+ assert!(pay(&e, click("Continue")).await.expect("checkout form").contains("checkout"));
+ ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": "document.querySelector('[name=q]').focus()"})).await.unwrap();
+ assert_eq!(pay(&e, json!({"action": "key", "key": "Enter"})).await, None);
+
+ // Nothing to pay on a plain page
+ open(&e, &format!("{base}/plain")).await;
+ assert_eq!(pay(&e, click("Continue")).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() {
+ 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 req = Request::builder()
+ .method("PUT")
+ .uri(format!("/api/kwants/{}/approvals", e.bot.id))
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {}", e.state.api_token.reveal()))
+ .body(Body::from(json!({"approvals": "off"}).to_string()))
+ .unwrap();
+ assert_eq!(e.app.clone().oneshot(req).await.unwrap().status(), StatusCode::OK);
+ let inner = mcp_runtime::BrokerApprover {
+ db: e.state.db.clone(),
+ data_dir: e.state.config.data_dir.clone(),
+ broker: e.state.broker.clone(),
+ events: e.state.event_sender.clone(),
+ timeout: Duration::from_millis(300),
+ conversation: "c-pay".into(),
+ chat: None,
+ always_ask: false,
+ };
+ let approver = SelfToolsApprover {
+ inner: Arc::new(inner),
+ always_ask: false,
+ browser: Some((e.state.clone(), e.bot.id.clone())),
+ };
+ let ctrl = open(&e, &format!("{base}/card")).await;
+ let continue_ = json!({"action": "click_text", "text": "Continue"});
+ // Unanswered: the card was shown and nobody answered it in time
+ assert_eq!(approver.decide(act_request(&e, continue_.clone())).await, ApprovalOutcome::Unanswered);
+ // The shell bots' API can't ask, so it doesn't click and says why
+ let (status, page) = post_act(&e.app, &e.bot.id, continue_).await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(page["error"].as_str().unwrap().starts_with("Not done: this looks like a payment"), "{page}");
+ assert!(page["payment"].as_str().unwrap().contains("card fields"), "{page}");
+ assert_eq!(title(&ctrl).await, "card", "the form was not sent");
+
+ // On a plain page both run without a card
+ let ctrl = open(&e, &format!("{base}/plain")).await;
+ assert_eq!(
+ approver.decide(act_request(&e, json!({"action": "click_text", "text": "Continue"}))).await,
+ ApprovalOutcome::Allowed
+ );
+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click_text", "text": "Continue"})).await;
+ assert!(page.get("error").is_none(), "{page}");
+ assert_eq!(title(&ctrl).await, "went on");
+}
+
+/// A real demo shop (needs the network): sign in, add a backpack, go through checkout. Nothing on
+/// the way asks; "Finish" on the overview page does. Run with `--ignored`.
+#[tokio::test]
+#[ignore]
+async fn saucedemo_checkout_asks_before_finish() {
+ 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 ctrl = open(&e, "https://www.saucedemo.com/").await;
+ let js = |expr: &str| json!({"expression": expr, "awaitPromise": true});
+ let fill = |sel: &str, v: &str| {
+ format!(
+ "(function(){{var el=document.querySelector('{sel}');var set=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set;set.call(el,'{v}');el.dispatchEvent(new Event('input',{{bubbles:true}}));}})()"
+ )
+ };
+ ctrl.send_cdp_command("Runtime.evaluate", js(&fill("#user-name", "standard_user"))).await.unwrap();
+ ctrl.send_cdp_command("Runtime.evaluate", js(&fill("#password", "secret_sauce"))).await.unwrap();
+ let step = |label: &'static str| {
+ let e = &e;
+ async move {
+ let args = json!({"action": "click_text", "text": label});
+ assert_eq!(pay(e, args.clone()).await, None, "{label} should not ask");
+ let (_, page) = post_act(&e.app, &e.bot.id, args).await;
+ assert!(page.get("error").is_none(), "{label}: {page}");
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+ };
+ step("Login").await;
+ step("Add to cart").await;
+ ctrl.navigate("https://www.saucedemo.com/cart.html").await.unwrap();
+ // The cart page itself isn't a checkout page; the button names it, so it asks
+ assert!(pay(&e, json!({"action": "click_text", "text": "Checkout"})).await.is_some());
+ ctrl.navigate("https://www.saucedemo.com/checkout-step-one.html").await.unwrap();
+ for (sel, v) in [("#first-name", "Ada"), ("#last-name", "Lovelace"), ("#postal-code", "10115")] {
+ ctrl.send_cdp_command("Runtime.evaluate", js(&fill(sel, v))).await.unwrap();
+ }
+ let why = pay(&e, json!({"action": "click_text", "text": "Continue"})).await;
+ assert!(why.is_some(), "a click on checkout-step-one asks by its address");
+ ctrl.navigate("https://www.saucedemo.com/checkout-step-two.html").await.unwrap();
+ let why = pay(&e, json!({"action": "click_text", "text": "Finish"})).await.expect("Finish asks");
+ eprintln!("Finish: {why}");
+ let (_, page) = post_act(&e.app, &e.bot.id, json!({"action": "click_text", "text": "Finish"})).await;
+ assert!(page["error"].as_str().unwrap_or("").starts_with("Not done"), "{page}");
+ assert!(page["url"].as_str().unwrap().contains("checkout-step-two"), "{page}");
+}