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.

19.0 KB
Raw Blame
//! Show it once: the recorder script in a real Chrome/Chromium, typed into with real key events
//! (`Input.dispatchKeyEvent`, the in-app viewer's path), its payloads read by the server's own
//! parser. Covers S-F2 (a field a script filled and the person then edited is masked) and S-F5
//! (a field left by kwnt's own navigation, with no blur, is committed first, masked). Skipped
//! when no Chrome is installed.

#[path = "support/skip.rs"]
mod skip;

#[path = "support/chrome_guard.rs"]
mod chrome_guard;
use chrome_guard::ChromeGuard;
use kwnt::sandbox::{
    computer::{self, ComputerMode},
    service::BrowserService,
    BrowserController,
};
use kwnt::server::show_once::capture;
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

/// One field per case. `upper` reformats in the page's own input handler (an input mask).
const PAGE: &str = "<!doctype html><title>form</title><body>\
<input id=plain name=plain>\
<input id=filled name=filled>\
<input id=prefilled name=prefilled value=Prefilled>\
<input id=appended name=appended>\
<input id=upper name=upper oninput=\"this.value=this.value.toUpperCase()\">\
<input id=events name=events>\
<input id=pw name=pw type=password>\
<textarea id=area name=area></textarea>";

/// A select wrapped by its label (named after the label's own words, not its options), and a
/// textarea wrapped the same way whose prefilled text must not become its name.
const SELECT_PAGE: &str = "<!doctype html><title>orders</title><body>\
<label>Status <select id=status name=status><option>All</option><option>Paid</option>\
<option>Refunded</option><option disabled>Pending</option></select></label>\
<label>Note <textarea id=note>Prefilled words</textarea></label>";

async fn serve_page() -> String {
    serve(PAGE).await
}

async fn serve(page: &'static str) -> 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; 2048];
                let _ = stream.read(&mut buf).await;
                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}/form")
}

/// Runs `expr` in the page's own world (what the page's scripts can do).
async fn page_js(ctrl: &BrowserController, expr: &str) -> Value {
    let r = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": expr, "returnByValue": true})).await.unwrap();
    r["result"]["value"].clone()
}

/// The person typing `text`, one real key event pair per character.
async fn person_types(ctrl: &BrowserController, text: &str) {
    for ch in text.chars() {
        let key = ch.to_string();
        let code = if ch.is_ascii_alphabetic() { format!("Key{}", ch.to_ascii_uppercase()) } else { String::new() };
        let vk = ch.to_ascii_uppercase() as u32;
        let down = json!({"type": "keyDown", "key": key, "code": code, "text": key, "unmodifiedText": key, "windowsVirtualKeyCode": vk});
        ctrl.send_cdp_command("Input.dispatchKeyEvent", down).await.unwrap();
        let up = json!({"type": "keyUp", "key": key, "code": code, "windowsVirtualKeyCode": vk});
        ctrl.send_cdp_command("Input.dispatchKeyEvent", up).await.unwrap();
        // the recorder's after-the-page update runs between keys, as it does for a person
        tokio::time::sleep(Duration::from_millis(30)).await;
    }
}

async fn focus(ctrl: &BrowserController, id: &str) {
    page_js(ctrl, &format!("document.getElementById('{id}').focus()")).await;
}

#[tokio::test]
async fn the_recorder_masks_any_field_whose_text_is_not_all_the_persons_own_typing() {
    std::env::remove_var("DISPLAY");
    std::env::remove_var("WAYLAND_DISPLAY");
    if computer::local_chrome_path().is_none() {
        skip::skip_or_fail("Chrome or Chromium", skip::CHROME_FIX);
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let _chrome = ChromeGuard(tmp.path().join("local-chrome"));
    let service = BrowserService::new(tmp.path().to_path_buf(), None);
    service.set_mode(ComputerMode::Local).await;
    let ctrl = service.session("bot", tmp.path()).await.expect("local session");
    let url = serve_page().await;
    ctrl.navigate(&url).await.unwrap();

    // The recorder in its own world, as kwant installs it; `kwntRecord` there collects what it
    // sends (in the app it's the CDP binding)
    let tree = ctrl.send_cdp_command("Page.getFrameTree", json!({})).await.unwrap();
    let frame = tree["frameTree"]["frame"]["id"].as_str().unwrap().to_string();
    let world = ctrl.send_cdp_command("Page.createIsolatedWorld", json!({"frameId": frame, "worldName": capture::WORLD})).await.unwrap();
    let ctx = world["executionContextId"].clone();
    let in_world = |expr: String| {
        let ctrl = &ctrl;
        let ctx = ctx.clone();
        async move {
            let r = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": expr, "contextId": ctx, "returnByValue": true})).await.unwrap();
            assert!(r.get("exceptionDetails").is_none(), "{r}");
            r["result"]["value"].clone()
        }
    };
    in_world(format!("globalThis.__sent = []; globalThis.{} = function (s) {{ __sent.push(s); }}; true", capture::BINDING)).await;
    in_world(capture::recorder_js()).await;

    // plain: the person types into an empty field
    focus(&ctrl, "plain").await;
    person_types(&ctrl, "abc").await;
    // filled (S-F2): a script sets the value with no event, then the person types one character
    page_js(&ctrl, "document.getElementById('filled').value = 'Script text'").await;
    focus(&ctrl, "filled").await;
    person_types(&ctrl, "x").await;
    // prefilled: the page's own value attribute, then one character
    focus(&ctrl, "prefilled").await;
    person_types(&ctrl, "x").await;
    // appended: the person types, a script adds to it silently, the person types again
    focus(&ctrl, "appended").await;
    person_types(&ctrl, "ab").await;
    page_js(&ctrl, "document.getElementById('appended').value += 'Z'").await;
    person_types(&ctrl, "c").await;
    // upper: the page's input mask reformats every keystroke; still the person's own text
    focus(&ctrl, "upper").await;
    person_types(&ctrl, "ab").await;
    // events: a script fills with an input event (untrusted), then the person types
    page_js(&ctrl, "var e = document.getElementById('events'); e.value = 'From script'; e.dispatchEvent(new Event('input', {bubbles: true})); true").await;
    focus(&ctrl, "events").await;
    person_types(&ctrl, "y").await;
    // a password field the person types
    focus(&ctrl, "pw").await;
    person_types(&ctrl, "hunter").await;
    // a textarea the person types, left focused: it comes from the flush at the stop
    focus(&ctrl, "area").await;
    person_types(&ctrl, "note").await;

    let all = in_world(format!("JSON.stringify(__sent.concat({}))", capture::FLUSH)).await;
    let payloads: Vec<String> = serde_json::from_str(all.as_str().unwrap()).unwrap();
    let mut steps: BTreeMap<String, (Option<String>, Option<String>)> = BTreeMap::new();
    for p in &payloads {
        let c = capture::parse(p).unwrap_or_else(|| panic!("the server reads every payload: {p}"));
        if c.step.kind == "type" {
            steps.insert(c.step.label.clone().unwrap_or_default(), (c.step.value.clone(), c.step.masked.clone()));
        }
    }
    let raw = payloads.join("\n");
    for secret in ["Script text", "Prefilled", "From script", "abZ", "hunter"] {
        assert!(!raw.contains(secret), "{secret:?} left the page: {raw}");
    }
    let saved = |v: &str| (None::<String>, Some(v.to_string()));
    assert_eq!(steps.get("plain"), Some(&(Some("abc".to_string()), None)), "{steps:?}");
    assert_eq!(steps.get("filled"), Some(&saved("saved_login")), "S-F2: script fills, the person types one character");
    assert_eq!(steps.get("prefilled"), Some(&saved("saved_login")), "a prefilled value isn't the person's");
    assert_eq!(steps.get("appended"), Some(&saved("saved_login")), "a silent script change in the middle");
    assert_eq!(steps.get("upper"), Some(&(Some("AB".to_string()), None)), "the page's own input mask is still the person's text");
    assert_eq!(steps.get("events"), Some(&saved("saved_login")), "an untrusted input event");
    assert_eq!(steps.get("pw"), Some(&saved("password")));
    assert_eq!(steps.get("area"), Some(&(Some("note".to_string()), None)), "the pending edit at the stop");
}

/// The person picks `index` of the select `id` in kwant's own drawn option list, the way the
/// stream's `select_option` does it: the page's `<select>` as a remote object, set with the
/// stream's own SELECT_SET_FN (untrusted events), then handed to the recorder with
/// `capture::record_pick`. Returns what `record_pick` returned.
async fn person_picks(ctrl: &BrowserController, id: &str, index: i64) -> bool {
    let probe = json!({"expression": format!("document.getElementById('{id}')"), "returnByValue": false});
    let found = ctrl.send_cdp_command("Runtime.evaluate", probe).await.unwrap();
    let object = found["result"]["objectId"].as_str().unwrap().to_string();
    let set = json!({"objectId": object, "functionDeclaration": kwnt::server::browser_input::SELECT_SET_FN,
        "arguments": [{"value": [index]}], "returnByValue": true});
    let r = ctrl.send_cdp_command("Runtime.callFunctionOn", set).await.unwrap();
    assert_eq!(r["result"]["value"], true, "the stream set the select: {r}");
    let call = |method: &'static str, params: Value| async move { ctrl.send_cdp_command(method, params).await.ok() };
    capture::record_pick(call, &object, &[index]).await
}

#[tokio::test]
async fn a_pick_in_the_drawn_list_is_a_select_step_and_a_wrapping_label_names_the_field() {
    std::env::remove_var("DISPLAY");
    std::env::remove_var("WAYLAND_DISPLAY");
    if computer::local_chrome_path().is_none() {
        skip::skip_or_fail("Chrome or Chromium", skip::CHROME_FIX);
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let _chrome = ChromeGuard(tmp.path().join("local-chrome"));
    let service = BrowserService::new(tmp.path().to_path_buf(), None);
    service.set_mode(ComputerMode::Local).await;
    let ctrl = service.session("bot", tmp.path()).await.expect("local session");
    let url = serve(SELECT_PAGE).await;
    ctrl.navigate(&url).await.unwrap();

    let tree = ctrl.send_cdp_command("Page.getFrameTree", json!({})).await.unwrap();
    let frame = tree["frameTree"]["frame"]["id"].as_str().unwrap().to_string();
    let world = ctrl.send_cdp_command("Page.createIsolatedWorld", json!({"frameId": frame, "worldName": capture::WORLD})).await.unwrap();
    let ctx = world["executionContextId"].clone();
    let in_world = |expr: String| {
        let ctrl = &ctrl;
        let ctx = ctx.clone();
        async move {
            let r = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": expr, "contextId": ctx, "returnByValue": true})).await.unwrap();
            assert!(r.get("exceptionDetails").is_none(), "{r}");
            r["result"]["value"].clone()
        }
    };
    let sent = || in_world("JSON.stringify(__sent.splice(0))".to_string());
    let take = |v: Value| -> Vec<String> { serde_json::from_str(v.as_str().unwrap()).unwrap() };
    in_world(format!("globalThis.__sent = []; globalThis.{} = function (s) {{ __sent.push(s); }}; true", capture::BINDING)).await;

    // no recording on: no recorder in its world, so a pick records nothing
    assert!(!person_picks(&ctrl, "status", 2).await, "no recorder, nothing taken");
    assert!(take(sent().await).is_empty());

    in_world(capture::recorder_js()).await;

    // a page script changes the same select and fires change: never a step (S-F2)
    page_js(&ctrl, "var s = document.getElementById('status'); s.selectedIndex = 2; \
        s.dispatchEvent(new Event('input', {bubbles: true})); s.dispatchEvent(new Event('change', {bubbles: true})); true").await;
    assert!(take(sent().await).is_empty(), "a script's change is never recorded");
    // nor can the page's world reach the recorder's pick
    assert_eq!(page_js(&ctrl, "typeof globalThis.__kwntRecorderPicked").await, "undefined");

    // the person picks "Paid" in kwant's drawn list: exactly one select step
    assert!(person_picks(&ctrl, "status", 1).await, "the recorder took the pick");
    let payloads = take(sent().await);
    assert_eq!(payloads.len(), 1, "{payloads:?}");
    let raw: Value = serde_json::from_str(&payloads[0]).unwrap();
    assert_eq!(raw["field"]["script_filled"], false, "the person's pick isn't script-changed: {raw}");
    let c = capture::parse(&payloads[0]).expect("the server reads the pick");
    assert_eq!(c.step.kind, "select");
    assert_eq!(c.step.label.as_deref(), Some("Status"), "the label's own words, not its options");
    assert_eq!(c.step.value.as_deref(), Some("Paid"));
    assert_eq!(c.step.masked, None);

    // a second pick after the script's change: still the person's, still unmasked
    assert!(person_picks(&ctrl, "status", 2).await);
    let payloads = take(sent().await);
    assert_eq!(payloads.len(), 1, "{payloads:?}");
    let c = capture::parse(&payloads[0]).unwrap();
    assert_eq!((c.step.value.as_deref(), c.step.masked.as_deref()), (Some("Refunded"), None));

    // a wrapped textarea is named "Note": its prefilled text is never its name
    focus(&ctrl, "note").await;
    person_types(&ctrl, "x").await;
    let flushed = in_world(format!("JSON.stringify({})", capture::FLUSH)).await;
    let payloads = take(flushed);
    assert_eq!(payloads.len(), 1, "{payloads:?}");
    assert!(!payloads[0].contains("Prefilled"), "{}", payloads[0]);
    let c = capture::parse(&payloads[0]).unwrap();
    assert_eq!(c.step.label.as_deref(), Some("Note"));
}

/// A sign-in form: a password field and a one-time code field.
const SIGN_IN_PAGE: &str = "<!doctype html><title>sign in</title><body>\
<input id=user name=user>\
<input id=pw name=pw type=password>\
<input id=otp name=otp autocomplete=one-time-code>";

#[tokio::test]
async fn leaving_by_the_address_bar_with_no_blur_records_the_secret_fields_masked() {
    std::env::remove_var("DISPLAY");
    std::env::remove_var("WAYLAND_DISPLAY");
    if computer::local_chrome_path().is_none() {
        skip::skip_or_fail("Chrome or Chromium", skip::CHROME_FIX);
        return;
    }
    let tmp = tempfile::tempdir().unwrap();
    let _chrome = ChromeGuard(tmp.path().join("local-chrome"));
    let service = BrowserService::new(tmp.path().to_path_buf(), None);
    service.set_mode(ComputerMode::Local).await;
    let ctrl = service.session("bot", tmp.path()).await.expect("local session");
    let url = serve(SIGN_IN_PAGE).await;
    ctrl.navigate(&url).await.unwrap();

    let tree = ctrl.send_cdp_command("Page.getFrameTree", json!({})).await.unwrap();
    let frame = tree["frameTree"]["frame"]["id"].as_str().unwrap().to_string();
    let world = ctrl.send_cdp_command("Page.createIsolatedWorld", json!({"frameId": frame, "worldName": capture::WORLD})).await.unwrap();
    let ctx = world["executionContextId"].clone();
    let in_world = |expr: String| {
        let ctrl = &ctrl;
        let ctx = ctx.clone();
        async move {
            let r = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": expr, "contextId": ctx, "returnByValue": true})).await.unwrap();
            assert!(r.get("exceptionDetails").is_none(), "{r}");
            r["result"]["value"].clone()
        }
    };
    let sent = || in_world("JSON.stringify(__sent.splice(0))".to_string());
    let take = |v: Value| -> Vec<String> { serde_json::from_str(v.as_str().unwrap()).unwrap() };
    let ctrl_ref = &ctrl;
    let commit = || {
        let call = move |method: &'static str, params: Value| async move { ctrl_ref.send_cdp_command(method, params).await.ok() };
        capture::commit_pending(call)
    };
    in_world(format!("globalThis.__sent = []; globalThis.{} = function (s) {{ __sent.push(s); }}; true", capture::BINDING)).await;

    // no recording on: no recorder in its world, nothing taken
    assert!(!commit().await, "no recorder, nothing committed");
    in_world(capture::recorder_js()).await;
    // the page's own scripts can't reach the commit
    assert_eq!(page_js(&ctrl, "typeof globalThis.__kwntRecorderCommit").await, "undefined");

    // the person types the user name, the password, then the code, and never leaves the code
    // field: its edit is still pending
    focus(&ctrl, "user").await;
    person_types(&ctrl, "sam").await;
    focus(&ctrl, "pw").await;
    person_types(&ctrl, "hunter").await;
    focus(&ctrl, "otp").await;
    person_types(&ctrl, "4821").await;
    let before = take(sent().await);
    let labels = |ps: &[String]| -> Vec<String> { ps.iter().filter_map(|p| capture::parse(p)).map(|c| c.step.label.unwrap_or_default()).collect() };
    assert!(!labels(&before).contains(&"otp".to_string()), "the code isn't a step yet: {before:?}");
    // an address-bar navigation moves no focus, so kwnt's server commits before it navigates
    assert!(commit().await, "the recorder took the commit");
    let committed = take(sent().await);
    assert!(labels(&committed).contains(&"otp".to_string()), "the pending code field: {committed:?}");

    let all = [before, committed].concat();
    let raw = all.join("\n");
    for secret in ["hunter", "4821"] {
        assert!(!raw.contains(secret), "{secret:?} left the page: {raw}");
    }
    let mut steps: BTreeMap<String, (Option<String>, Option<String>, String)> = BTreeMap::new();
    for p in &all {
        let c = capture::parse(p).unwrap_or_else(|| panic!("the server reads every payload: {p}"));
        assert_eq!(c.step.kind, "type");
        assert_eq!(c.page.path, "/form", "recorded on the page being left");
        assert!(steps.insert(c.step.label.clone().unwrap_or_default(), (c.step.value, c.step.masked, c.page.path)).is_none(), "one step per field: {all:?}");
    }
    assert_eq!(steps.len(), 3, "{steps:?}");
    assert_eq!(steps["user"].0.as_deref(), Some("sam"));
    assert_eq!((steps["pw"].0.as_deref(), steps["pw"].1.as_deref()), (None, Some("password")), "recorded, masked");
    assert_eq!((steps["otp"].0.as_deref(), steps["otp"].1.as_deref()), (None, Some("code")), "recorded, masked");

    // nothing is left pending, and a second commit adds nothing
    assert!(commit().await);
    assert!(take(sent().await).is_empty(), "no duplicate step");
    assert!(take(in_world(format!("JSON.stringify({})", capture::FLUSH)).await).is_empty());

    // the same with a password left focused
    focus(&ctrl, "pw").await;
    person_types(&ctrl, "x").await;
    assert!(commit().await);
    let committed = take(sent().await);
    assert_eq!(committed.len(), 1, "{committed:?}");
    let c = capture::parse(&committed[0]).unwrap();
    assert_eq!((c.step.value.as_deref(), c.step.masked.as_deref()), (None, Some("password")));
    assert!(!committed[0].contains("hunterx"));
}