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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
use futures::{SinkExt, StreamExt};
use super::credentials::CredentialStore;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use thiserror::Error;
use tokio::net::TcpStream;
use tokio::sync::{Mutex, RwLock, OwnedRwLockWriteGuard};
use tokio::time::timeout;
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
pub(crate) type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
/// The DevTools WebSocket request for `url`. Chrome refuses a DevTools connection whose Host is a
/// name other than localhost (500 on the upgrade), so a plain-ws name such as the compose service
/// `browser` gets `Host: localhost`, as the `/json` requests do. IPs and wss (a hosted service
/// that may need its own Host) are left alone.
pub(crate) fn cdp_ws_request(url: &str) -> Result<tokio_tungstenite::tungstenite::handshake::client::Request, BrowserError> {
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
let mut req = url.into_client_request().map_err(|e| BrowserError::Ws(e.to_string()))?;
let named_host = req.uri().scheme_str() == Some("ws")
&& req.uri().host().is_some_and(|h| h != "localhost" && h.trim_matches(['[', ']']).parse::<std::net::IpAddr>().is_err());
if named_host {
req.headers_mut().insert(reqwest::header::HOST, reqwest::header::HeaderValue::from_static("localhost"));
}
Ok(req)
}
/// Opens a DevTools WebSocket (see [`cdp_ws_request`]).
/// Keeps every document of the page from opening another app (see [`super::app_links`]), for as
/// long as this DevTools connection lasts. Nobody listens for the guard's binding here.
async fn guard_app_links(ws: &mut WsStream, msg_id: &AtomicU64) {
let id = msg_id.fetch_add(1, Ordering::SeqCst);
let request = json!({
"id": id,
"method": "Page.addScriptToEvaluateOnNewDocument",
"params": {"source": super::app_links::guard_js(), "worldName": super::app_links::WORLD, "runImmediately": true},
});
let sent = match ws.send(Message::Text(request.to_string())).await {
Ok(()) => timeout(Duration::from_secs(5), await_reply(ws, id)).await.map_err(|_| BrowserError::Timeout).and_then(|r| r.and_then(|r| r)),
Err(e) => Err(BrowserError::Ws(e.to_string())),
};
if let Err(e) = sent {
tracing::warn!(error = %e, "couldn't guard the browser against links to other apps");
}
}
pub(crate) async fn connect_cdp(url: &str) -> Result<WsStream, BrowserError> {
// A browser starved of memory can accept the TCP connection and never finish the upgrade:
// that is a timeout (busy, try again), not a dead browser.
let (ws, _) = timeout(CDP_CONNECT_TIMEOUT, connect_async(cdp_ws_request(url)?)).await
.map_err(|_| BrowserError::Timeout)?
.map_err(|e| BrowserError::Ws(e.to_string()))?;
Ok(ws)
}
/// One command on `ws` before it is handed out (waking a page), with a short deadline.
async fn raw_call(ws: &mut WsStream, msg_id: &AtomicU64, method: &str, params: Value) -> Result<Value, BrowserError> {
let id = msg_id.fetch_add(1, Ordering::SeqCst);
let request = json!({"id": id, "method": method, "params": params});
ws.send(Message::Text(request.to_string())).await.map_err(|e| BrowserError::Ws(e.to_string()))?;
timeout(Duration::from_secs(5), await_reply(ws, id)).await.map_err(|_| BrowserError::Timeout)?.and_then(|r| r)
}
/// How long opening a DevTools WebSocket may take.
const CDP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
/// A DevTools `/json` request that failed: [`BrowserError::Timeout`] when it timed out, so a busy
/// browser is told apart from one that isn't there; otherwise the error with its causes ("error
/// sending request" alone doesn't say the connection was refused).
fn http_error(error: reqwest::Error) -> BrowserError {
if error.is_timeout() {
return BrowserError::Timeout;
}
let mut text = error.to_string();
let mut source = std::error::Error::source(&error);
while let Some(cause) = source {
text.push_str(": ");
text.push_str(&cause.to_string());
source = cause.source();
}
BrowserError::Http(text)
}
/// Why the browser couldn't be used, as far as what to do next goes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outage {
/// It is there but didn't answer in time (overloaded, out of memory, mid-restart): retry soon.
Busy,
/// Nothing listens at its address, the name doesn't resolve, or Docker isn't running.
Unreachable,
/// Anything else (Chrome refused a command, a person holds the page, ...).
Other,
}
/// Classifies a failed browser call (see [`Outage`]). Only a refused connection, a failed name
/// lookup or a Docker failure is [`Outage::Unreachable`]; a timeout or a dropped connection is
/// [`Outage::Busy`].
pub fn outage(error: &BrowserError) -> Outage {
const UNREACHABLE: [&str; 9] = [
"connection refused", "dns error", "failed to lookup address", "name or service not known",
"no such host", "network is unreachable", "no route to host", "cannot connect to the docker daemon",
"docker:",
];
match error {
BrowserError::Timeout => Outage::Busy,
BrowserError::Http(text) | BrowserError::Ws(text) | BrowserError::Protocol(text) => {
let text = text.to_ascii_lowercase();
if UNREACHABLE.iter().any(|u| text.contains(u)) {
Outage::Unreachable
} else if matches!(error, BrowserError::Protocol(_)) && !text.contains("connection closed before response") {
Outage::Other
} else {
Outage::Busy
}
}
_ => Outage::Other,
}
}
/// Reads `ws` until the reply to command `id`. The outer `Err` means the connection broke (closed
/// or a socket error); the inner one is Chrome's own error reply on a healthy connection.
async fn await_reply(ws: &mut WsStream, id: u64) -> Result<Result<Value, BrowserError>, BrowserError> {
while let Some(msg) = ws.next().await {
match msg {
Ok(Message::Text(txt)) => {
let Ok(parsed) = serde_json::from_str::<Value>(&txt) else { continue };
if parsed.get("id").and_then(|v| v.as_u64()) != Some(id) {
continue;
}
if let Some(err) = parsed.get("error") {
return Ok(Err(BrowserError::Protocol(err.to_string())));
}
return Ok(Ok(parsed.get("result").cloned().unwrap_or(Value::Null)));
}
Ok(Message::Close(_)) => return Err(BrowserError::Protocol("Connection closed before response".into())),
Err(e) => return Err(BrowserError::Ws(e.to_string())),
_ => continue,
}
}
Err(BrowserError::Protocol("Connection closed before response".into()))
}
/// `function(needle, probe)` evaluated in the page. Collects visible interactive elements (incl.
/// open shadow roots and same-origin iframes), topmost first. After them it lists, at most 40 of
/// each, controls that show only on hover (opacity 0 or visibility hidden inside a shown card: a
/// tile's ⋮ button), with the card to hover, and then clickable cards (the outermost element with
/// a pointer cursor whose parent has none: a tile with a JS click listener), so tiles never push
/// ordinary controls out of a capped list. An icon-only control
/// is named by its aria-label or title, else by its icon word (`more_vert` reads "More").
/// With a needle, picks the best label match (controls listed before cards and hover controls
/// existed first) and either returns its viewport center (when nothing covers it), clicks it
/// directly, or, for a control shown on hover, keeps it for `REF_JS('hovered')` and says
/// `hover: true`. With `probe`, returns the matched item itself (with its element and the label
/// the payment floor judged before icon words were read) and touches nothing; with no needle
/// either, returns all items (with their elements).
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]';
// Clickable cards (a div with a JS click listener) and controls shown only on hover are listed
// at most this many each, after the ordinary controls, so a busy page doesn't flood the list
var CARD_CAP = 40, HOVER_CAP = 40;
// The word a person reads for an icon-only control's icon-font word (Material icons and symbols)
var ICONS = { more_vert: 'More', more_horiz: 'More', download: 'Download', file_download: 'Download',
close: 'Close', delete: 'Delete', delete_outline: 'Delete', edit: 'Edit', share: 'Share', ios_share: 'Share',
content_copy: 'Copy', play_arrow: 'Play', pause: 'Pause', search: 'Search', menu: 'Menu', settings: 'Settings',
upload: 'Upload', file_upload: 'Upload', add: 'Add', arrow_back: 'Back', favorite: 'Like', favorite_border: 'Like' };
var ICON_SEL = 'i,mat-icon,[class*=icon],[class*=Icon],[class*=symbol],[class*=Symbol]';
var items = [], cards = [], hovers = [], seq = 0;
var styles = new Map(), fades = new Map();
function clean(s) { return (s || '').replace(/\s+/g, ' ').trim().slice(0, 80); }
function style(el) { var s = styles.get(el); if (!s) { s = getComputedStyle(el); styles.set(el, s); } return s; }
// The parent element, also out of a shadow root (to its host); null at a document's top
function up(el) { return el.parentElement || (el.parentNode && el.parentNode.host) || null; }
// Whether el or an element around it is fully see-through (opacity 0)
function faded(el) {
if (!el || el.nodeType !== 1) return false;
if (fades.has(el)) return fades.get(el);
var f = Number(style(el).opacity) === 0 || faded(up(el));
fades.set(el, f);
return f;
}
// innerText leaves out the text of a visibility:hidden element; a control shown on hover still has a name
function textOf(el) {
var t = el.innerText;
if (!clean(t) && style(el).visibility !== 'visible') t = el.textContent;
return t || '';
}
// A control a role for the ref list: what it is, in one word
function roleOf(el) {
var role = (el.getAttribute('role') || '').toLowerCase();
if (role) return role;
var tag = el.tagName, t = (el.type || '').toLowerCase();
if (tag === 'A') return 'link';
if (tag === 'SELECT') return 'select';
if (tag === 'LABEL') return 'label';
if (tag === 'INPUT' && (t === 'checkbox' || t === 'radio')) return t;
if (tag === 'TEXTAREA' || (tag === 'INPUT' && ['submit', 'button', 'image', 'reset'].indexOf(t) < 0)) return 'field';
return 'button';
}
// The icon-font word an icon-only control shows (its whole text, in an icon element), or ''
function iconWord(el, text) {
if (!/^[a-z][a-z0-9]*(_[a-z0-9]+)*$/.test(text)) return '';
var icons = [el].concat(Array.prototype.slice.call(el.querySelectorAll(ICON_SEL)));
for (var i = 0; i < icons.length; i++) {
if ((i > 0 || el.matches(ICON_SEL)) && clean(icons[i].textContent) === text) return text;
}
return '';
}
// With old, the name as it was before icon words were read (the payment floor judges that one)
function nameOf(el, old) {
var tag = el.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') {
var t = (el.type || '').toLowerCase();
if (t === 'submit' || t === 'button') return clean(el.value);
if (t === 'hidden') return '';
return clean(el.getAttribute('aria-label') || el.placeholder || el.name || el.id);
}
if (old) return clean(el.innerText || el.getAttribute('aria-label') || el.title || el.value);
var text = textOf(el), word = iconWord(el, clean(text));
if (word) return clean(el.getAttribute('aria-label') || el.title) || (ICONS.hasOwnProperty(word) ? ICONS[word] : word);
return clean(text || el.getAttribute('aria-label') || el.title || el.value);
}
function labelOf(el, old) {
var name = nameOf(el, old), tag = el.tagName, t = (el.type || '').toLowerCase();
if (!name || !(tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') || t === 'submit' || t === 'button') return name;
return name + ' (' + (t === 'checkbox' || t === 'radio' ? t : 'field') + ')';
}
// A card's name: its aria-label or title, else its first line of text that isn't one of its own
// controls or icons (a tile's ⋮ button reads more_vert), else an image's alt text
function cardLabel(el) {
var named = clean(el.getAttribute('aria-label') || el.title);
if (named) return named.slice(0, 60);
var own = new Set(), inner = el.querySelectorAll(SEL + ',' + ICON_SEL);
for (var i = 0; i < inner.length; i++) {
var ls = (inner[i].innerText || inner[i].textContent || '').split('\n');
for (var k = 0; k < ls.length; k++) own.add(clean(ls[k]));
}
var lines = (el.innerText || '').split('\n');
for (var j = 0; j < lines.length; j++) {
var line = clean(lines[j]);
if (line && !own.has(line)) return line.slice(0, 60);
}
var img = el.querySelector('img[alt]:not([alt=""])');
return img ? clean(img.alt).slice(0, 60) : '';
}
// The text that tells a repeated control apart (the product a repeated "Add to cart" belongs
// to): the first line of the largest block around it that holds no other control of that name
function contextOf(el, name, twins) {
var block = null;
for (var a = el.parentElement, depth = 0; a && depth < 10; a = a.parentElement, depth++) {
var shared = false;
for (var t = 0; t < twins.length; t++) if (twins[t] !== el && a.contains(twins[t])) { shared = true; break; }
if (shared) break;
block = a;
}
var lines = block ? (block.innerText || '').split('\n') : [];
for (var i = 0; i < lines.length; i++) {
var line = clean(lines[i]).slice(0, 50);
if (line && line !== name) return line;
}
return '';
}
// The visible element to hover so that el shows: the nearest one around it that is shown and
// larger than el (the tile, not a wrapper of the button's own size)
function cardFor(el, r0) {
for (var a = up(el), d = 0; a && d < 12; a = up(a), d++) {
if (a.tagName === 'BODY' || a.tagName === 'HTML') return null;
var r = a.getBoundingClientRect();
if (r.width < r0.width + 8 && r.height < r0.height + 8) continue;
var cs = style(a);
if (cs.display === 'none' || cs.visibility !== 'visible' || faded(a)) continue;
return a;
}
return null;
}
// A card: the outermost element with a pointer cursor that isn't (in) a listed control
function isCard(el) {
if (el.tagName === 'BODY' || el.tagName === 'HTML' || style(el).cursor !== 'pointer') return false;
var p = up(el);
if (p && style(p).cursor === 'pointer') return false;
return !el.closest(SEL);
}
// One control covers (nearly) all of it: that control is listed itself
function filled(el, r) {
var inner = el.querySelectorAll(SEL);
for (var i = 0; i < inner.length; i++) {
var q = inner[i].getBoundingClientRect();
if (q.width * q.height >= 0.8 * r.width * r.height) return true;
}
return false;
}
function place(el, r, root, ox, oy) {
var lx = r.left + r.width / 2, ly = r.top + r.height / 2;
var x = ox + lx, y = oy + ly;
var inView = x >= 0 && y >= 0 && x <= innerWidth && y <= innerHeight;
var onTop = false;
if (inView) {
var hit = root.elementFromPoint ? root.elementFromPoint(lx, ly) : null;
onTop = !hit || hit === el || el.contains(hit) || hit.contains(el);
}
return { x: Math.round(x), y: Math.round(y), inView: inView, onTop: onTop };
}
function walk(root, ox, oy) {
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, ox, oy);
if (el.tagName === 'IFRAME') {
try { var d = el.contentDocument; if (d) { var fr = el.getBoundingClientRect(); walk(d, ox + fr.left, oy + fr.top); } } catch (e) {}
continue;
}
var r, cs, p;
if (!el.matches(SEL)) {
if (!isCard(el)) continue;
r = el.getBoundingClientRect();
var win = el.ownerDocument.defaultView || window;
if (r.width < 16 || r.height < 16 || (r.width >= win.innerWidth * 0.95 && r.height >= win.innerHeight * 0.95)) continue;
cs = style(el);
if (cs.visibility !== 'visible' || cs.display === 'none' || faded(el) || filled(el, r)) continue;
var name = cardLabel(el);
if (!name) continue;
p = place(el, r, root, ox, oy);
cards.push({ seq: seq++, label: name, old: name, name: name, role: 'card', kind: 'card', x: p.x, y: p.y, inView: p.inView, onTop: p.onTop, el: el, tier: 1 });
continue;
}
r = el.getBoundingClientRect();
if (r.width < 2 || r.height < 2) continue;
cs = style(el);
if (cs.display === 'none') continue;
// Hidden only until the mouse is over something around it: a ⋮ button at opacity 0 on a tile
var hidden = cs.visibility === 'hidden' || Number(cs.opacity) === 0;
var role = roleOf(el), card = null;
if (hidden || faded(up(el))) card = role === 'field' || role === 'checkbox' || role === 'radio' || role === 'select' ? null : cardFor(el, r);
if (hidden && !card) continue;
var label = labelOf(el, false);
if (!label) continue;
p = place(el, r, root, ox, oy);
var item = { seq: seq++, label: label, old: labelOf(el, true), name: nameOf(el, false), role: role, kind: 'control',
x: p.x, y: p.y, inView: p.inView, onTop: p.onTop, el: el, tier: hidden ? 1 : 0,
card: card, cardLabel: card ? cardLabel(card) : '' };
(hidden ? hovers : items).push(item);
}
}
walk(document, 0, 0);
// Each kind topmost first, then in page order. Ordinary controls come first, then the ones shown
// on hover, then cards, so a page of many tiles never pushes its buttons out of a capped list
function order(a, b) { return (b.onTop - a.onTop) || (b.inView - a.inView) || (a.seq - b.seq); }
items = items.sort(order).concat(hovers.sort(order).slice(0, HOVER_CAP), cards.sort(order).slice(0, CARD_CAP));
function registry() {
var reg = window[Symbol.for('kwnt.refs')];
if (!reg) {
reg = { gen: 0 };
try { Object.defineProperty(window, Symbol.for('kwnt.refs'), { value: reg }); } catch (e) {}
}
return reg;
}
var match = null;
if (needle) {
// The controls listed before cards and hover-only controls existed first, so a label that
// matched one of those still picks the same element (the payment floor judges that one)
var n = clean(needle).toLowerCase(), best = 0;
for (var tier = 0; tier < 2 && !best; tier++) {
for (var j = 0; j < items.length; j++) {
if (items[j].tier !== tier) continue;
var l = items[j].label.toLowerCase();
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 ? { el: match.el, label: match.old || match.label, item: match } : null;
if (match) {
var m = match.el;
if (match.card) {
// Shown on hover: the click hovers its card first (see REF_JS 'hovered')
registry().hovered = { el: m, label: match.label, old: match.old, kind: match.kind, card: match.card, cardLabel: match.cardLabel };
match = { label: match.label, hover: true, clicked: false };
} else if (!match.onTop) {
m.scrollIntoView({ block: 'center' });
if (typeof m.focus === 'function') m.focus();
m.click();
match = { label: match.label, clicked: true };
} else {
match = { label: match.label, x: match.x, y: match.y, clicked: false };
}
}
}
if (!needle) {
// Listed, a control inside a see-through wrapper (shown on hover too, but matched with the
// ordinary controls, as before cards existed) joins the other hover controls
var plain = [], onHover = [], tiles = [];
items.forEach(function (i) { (i.kind === 'card' ? tiles : i.card ? onHover : plain).push(i); });
items = plain.concat(onHover.sort(order), tiles);
}
// A peek (no needle, probe): the items with their elements, without numbering them
if (!needle && probe) return items;
if (!needle) {
// A listing numbers the controls (ref = position + 1) and keeps their elements in the page,
// so the next `act` by ref hits exactly this element or says it is gone
var twins = {};
for (var k = 0; k < items.length; k++) (twins[items[k].name] = twins[items[k].name] || []).push(items[k].el);
var reg = registry();
// A control is new when its element wasn't in this page's previous list (a dropdown's
// options, a dialog's buttons). The first list of a page, and one after the address changed
// (other than its #fragment), marks nothing
var here = location.href.split('#')[0];
var before = reg.items && reg.href === here ? new Set(reg.items.map(function (i) { return i.el; })) : null;
reg.gen += 1;
reg.href = here;
reg.items = items.map(function (i) { return { el: i.el, label: i.label, old: i.old, kind: i.kind, card: i.card, cardLabel: i.cardLabel }; });
reg.labelOf = labelOf;
reg.cardLabel = cardLabel;
return { gen: reg.gen, items: items.map(function (i, k) {
return { ref: k + 1, label: i.label, name: i.name, role: i.role, onTop: i.onTop, hover: !!i.card,
new: !!before && !before.has(i.el),
context: i.card ? i.cardLabel : twins[i.name].length > 1 ? contextOf(i.el, i.name, twins[i.name]) : '' };
}) };
}
return { items: items.map(function (i) { return { label: i.label, onTop: i.onTop }; }), match: match };
}"#;
/// Finds control `ref` from the last listing (see [`CLICKABLES_JS`]), or with `"hovered"` the
/// hover-only control a click by label picked. With `probe` true, returns `{el, label}` (or
/// null) and touches nothing. Otherwise checks it can still be clicked: still in the page, shown,
/// the same label, and on top at its center after scrolling it into view (so a cookie banner or
/// modal over it is reported, not clicked through). Returns `{ok: true, x, y, label, hovered}` in
/// top-page pixels, or `{ok: false, why}`. A control that shows on hover and isn't shown yet
/// returns `{ok: false, hover: {x, y, card}}`: where to put the mouse first; with `probe` 'spot'
/// that place comes back as `{ok: true, x, y, label, card}`.
const REF_JS: &str = r#"function (ref, probe) {
function clean(s) { return (s || '').replace(/\s+/g, ' ').trim().slice(0, 80); }
var reg = window[Symbol.for('kwnt.refs')];
// 'hovered': the control a click by label picked that shows only on hover
var item = ref === 'hovered' ? reg && reg.hovered : reg && reg.items && reg.items[ref - 1];
if (probe === true) return item ? { el: item.el, label: item.old || item.label } : null;
if (!item) return { ok: false, why: reg ? 'there is no ref ' + ref + ' in the last list' : 'this page has no list of refs yet (it changed or reloaded)' };
var el = item.el;
if (!el.isConnected) return { ok: false, why: 'it is no longer on the page' };
var label = item.kind === 'card' ? (reg.cardLabel ? reg.cardLabel(el) : item.label) : reg.labelOf ? reg.labelOf(el) : item.label;
if (label !== item.label) return { ok: false, why: 'it now reads "' + label + '", not "' + item.label + '"' };
// A control shown on hover counts as shown only when nothing around it is see-through either
function seeThrough(node) {
for (var a = node; a && a.nodeType === 1; a = a.parentElement || (a.parentNode && a.parentNode.host)) {
if (Number(getComputedStyle(a).opacity) === 0) return true;
}
return false;
}
function shown(node, whole) {
var r = node.getBoundingClientRect();
if (r.width < 2 || r.height < 2) return null;
var cs = getComputedStyle(node);
if (cs.visibility === 'hidden' || cs.display === 'none' || Number(cs.opacity) === 0) return null;
if (whole && (cs.visibility !== 'visible' || seeThrough(node))) return null;
return r;
}
function covers(hit, target) { return !hit || hit === target || target.contains(hit) || hit.contains(target); }
function what(hit) {
var t = clean(hit.innerText || hit.getAttribute('aria-label') || '').slice(0, 40);
return hit.tagName.toLowerCase() + (t ? ' "' + t + '"' : '');
}
// Where to put the mouse on node, in top-page pixels: its center, scrolled into view, and
// nothing over it (so a cookie banner or modal over it is reported, not clicked through)
function spot(node, whole) {
var r = shown(node, whole);
if (!r) return { ok: false, why: 'it is hidden now' };
var win = node.ownerDocument.defaultView;
if (r.top < 0 || r.left < 0 || r.bottom > win.innerHeight || r.right > win.innerWidth) {
node.scrollIntoView({ block: 'center', inline: 'center' });
r = shown(node, whole);
if (!r) return { ok: false, why: 'it is hidden now' };
}
var lx = r.left + r.width / 2, ly = r.top + r.height / 2;
// The top-page point: add the offsets of the (same-origin) frames it sits in
var x = lx, y = ly, frames = [];
for (var w = win; w !== w.top && w.frameElement; w = w.parent) {
var fr = w.frameElement.getBoundingClientRect();
x += fr.left; y += fr.top;
frames.push(w.frameElement);
}
if (x < 0 || y < 0 || x > innerWidth || y > innerHeight) return { ok: false, why: 'it is outside the window' };
var root = node.getRootNode();
var hit = root.elementFromPoint ? root.elementFromPoint(lx, ly) : null;
if (!covers(hit, node)) return { ok: false, why: 'it is covered by ' + what(hit) };
if (frames.length) {
var top = document.elementFromPoint(x, y), outer = frames[frames.length - 1];
if (!covers(top, outer)) return { ok: false, why: 'it is covered by ' + what(top) };
}
return { ok: true, x: Math.round(x), y: Math.round(y) };
}
var card = item.card;
if (card && !shown(el, true)) {
// Shown only on hover: say where to hover (its card), or why that can't be done
if (!card.isConnected) return { ok: false, why: 'it is hidden now' };
var c = spot(card, true);
if (!c.ok) return { ok: false, why: 'it shows on hover, and its card "' + item.cardLabel + '" ' + c.why.replace(/^it /, '') };
if (probe === 'spot') return { ok: true, x: c.x, y: c.y, label: item.label, card: item.cardLabel };
return { ok: false, hover: { x: c.x, y: c.y, card: item.cardLabel }, label: item.label };
}
var s = spot(el, !!card);
if (!s.ok) return s;
return { ok: true, x: s.x, y: s.y, label: item.label, hovered: !!card };
}"#;
/// `function(target)`: a label or a ref to hover. Finds it (as a click would), keeps what is
/// shown now (for [`APPEARED_JS`]) and returns where to put the mouse: the card of a control that
/// shows on hover, else the control itself, as `{ok, x, y, label, card}` or `{ok: false, why}`.
const HOVER_JS: &str = r#"function (target) {
var CLICK = __CLICKABLES__;
var REF = __REF__;
var key = target;
if (typeof target === 'string') {
var m = CLICK(target, true);
if (!m) return { ok: false, why: 'nothing on the page matches "' + target + '"' };
var reg = window[Symbol.for('kwnt.refs')];
if (!reg) {
reg = { gen: 0 };
try { Object.defineProperty(window, Symbol.for('kwnt.refs'), { value: reg }); } catch (e) {}
}
var i = m.item;
reg.hovered = { el: i.el, label: i.label, old: i.old, kind: i.kind, card: i.card, cardLabel: i.cardLabel };
key = 'hovered';
}
var spot = REF(key, 'spot');
if (spot.ok) {
// What is shown now, to tell what the hover brings up
var shown = new Set();
var now = CLICK(null, true);
for (var k = 0; k < now.length; k++) if (!now[k].card) shown.add(now[k].el);
window[Symbol.for('kwnt.refs')].shownBefore = shown;
}
return spot;
}"#;
/// `function()` after a hover: the controls shown now that weren't before it (at most 12), as
/// `Label (role)`.
const APPEARED_JS: &str = r#"function () {
var CLICK = __CLICKABLES__;
var reg = window[Symbol.for('kwnt.refs')];
var before = reg && reg.shownBefore;
if (!before) return [];
reg.shownBefore = null;
var now = CLICK(null, true), out = [];
for (var k = 0; k < now.length && out.length < 12; k++) {
if (!now[k].card && !before.has(now[k].el)) out.push(now[k].label + ' (' + now[k].role + ')');
}
return out;
}"#;
/// 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 REF = __REF__;
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 = typeof needle === 'number' ? REF(needle, true) : 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) {
// 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) };
}"#;
#[derive(Error, Debug)]
pub enum BrowserError {
#[error("HTTP error connecting to CDP: {0}")]
Http(String),
#[error("WebSocket connection to browser failed: {0}")]
Ws(String),
#[error("Protocol error: {0}")]
Protocol(String),
#[error("Operation timed out")]
Timeout,
#[error("Browser is controlled by a person. Retry after control is returned.")]
HumanControl,
/// Take over from a live view while another of the person's live views has control (not a
/// bot finishing a step): retrying can't win until that view hands back.
#[error("You're controlling this browser in another window. Press Hand back there to take over here.")]
HeldByPerson,
/// The person's live view sent input without taking control, and nobody else has it.
#[error("Take control of the browser first.")]
NotInControl,
/// The browser works, but the page itself could not be loaded (DNS, TLS, refused, ...).
#[error("Page could not be loaded: {0}")]
Navigation(String),
/// A file path (or file:// address) handed to the browser; see [`refuse_file_path`].
#[error("{0}")]
NotWebAddress(String),
/// A ref from the control list that can't be clicked any more (gone, hidden, covered).
#[error("{0}")]
StaleRef(String),
/// The driving bot's site rules refused the page (see [`super::site_guard`]).
#[error("{}", .0.message)]
SiteRule(super::site_guard::Refusal),
/// A key press kwnt can't describe to Chrome as a real key (see [`key_press_params`]).
#[error("{0}")]
UnsupportedKey(String),
}
/// The `KeyboardEvent.code` (and whether Shift is held, on a US layout) for a key a bot or the
/// v1 live view names without one: named keys, single letters, digits, space and punctuation.
fn code_for_key(key: &str) -> Option<(String, bool)> {
use crate::server::browser_input::virtual_key_code;
let named = match key {
"Shift" => Some("ShiftLeft"),
"Control" => Some("ControlLeft"),
"Alt" => Some("AltLeft"),
"Meta" => Some("MetaLeft"),
_ => None,
};
if let Some(code) = named {
return Some((code.into(), false));
}
let mut chars = key.chars();
let (Some(c), None) = (chars.next(), chars.next()) else {
// Enter, Tab, Escape, Backspace, arrows, Home, F5...: the key is its own code
return virtual_key_code(key).map(|_| (key.to_string(), false));
};
let shifted = "~!@#$%^&*()_+{}|:\"<>?";
let code = match c {
'a'..='z' | 'A'..='Z' => format!("Key{}", c.to_ascii_uppercase()),
'0'..='9' => format!("Digit{c}"),
' ' => "Space".into(),
'`' | '~' => "Backquote".into(),
'!' => "Digit1".into(),
'@' => "Digit2".into(),
'#' => "Digit3".into(),
'$' => "Digit4".into(),
'%' => "Digit5".into(),
'^' => "Digit6".into(),
'&' => "Digit7".into(),
'*' => "Digit8".into(),
'(' => "Digit9".into(),
')' => "Digit0".into(),
'-' | '_' => "Minus".into(),
'=' | '+' => "Equal".into(),
'[' | '{' => "BracketLeft".into(),
']' | '}' => "BracketRight".into(),
'\\' | '|' => "Backslash".into(),
';' | ':' => "Semicolon".into(),
'\'' | '"' => "Quote".into(),
',' | '<' => "Comma".into(),
'.' | '>' => "Period".into(),
'/' | '?' => "Slash".into(),
_ => return None,
};
Some((code, c.is_ascii_uppercase() || shifted.contains(c)))
}
/// One key press (down, then up) as `Input.dispatchKeyEvent` params: the same event the person's
/// live view sends ([`crate::server::browser_input::key_params`]), with the Windows key code and,
/// for a key that types, `keyDown` with its text. Enter carries `\r`, which is what makes Chrome
/// submit a form; a bare `rawKeyDown` with only `key` and `code` fired keydown and nothing else.
/// `code` is worked out from `key` when the caller leaves it out. "Space"/"Spacebar" mean the
/// space bar, "Return" Enter and "Esc" Escape.
pub fn key_press_params(key: &str, code: Option<&str>) -> Result<[Value; 2], BrowserError> {
use crate::server::browser_input::{key_params, KeyEvent, KeyKind, SHIFT};
let key = match key {
"Space" | "Spacebar" => " ",
"Return" => "Enter",
"Esc" => "Escape",
k => k,
};
let unsupported = || {
let shown: String = key.chars().take(32).collect();
BrowserError::UnsupportedKey(format!(
"Can't press \"{shown}\": press one key, such as Enter, Tab, Escape, Backspace, an arrow key or a single character. To enter text, type it."
))
};
let (code, shift) = match code.filter(|c| !c.is_empty()) {
Some(c) => (c.to_string(), false),
None => code_for_key(key).ok_or_else(unsupported)?,
};
let event = |kind| KeyEvent {
kind,
key,
code: &code,
text: None,
modifiers: if shift { SHIFT } else { 0 },
location: None,
auto_repeat: false,
};
let down = key_params(&event(KeyKind::Down)).map_err(|_| unsupported())?;
let up = key_params(&event(KeyKind::Up)).map_err(|_| unsupported())?;
Ok([down, up])
}
/// A live view's control of the browser ([`BrowserController::take_control`]): the write lock,
/// counted as a view's while it lives. The count goes down before the lock is let go.
pub struct PersonLease {
views: Arc<AtomicUsize>,
_guard: OwnedRwLockWriteGuard<()>,
}
impl Drop for PersonLease {
fn drop(&mut self) {
self.views.fetch_sub(1, Ordering::SeqCst);
}
}
impl std::fmt::Debug for PersonLease {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("PersonLease")
}
}
/// What a click aims at: a label to match, or a numbered ref from the last control list.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClickTarget {
Text(String),
Ref(u32),
}
impl ClickTarget {
/// From `browser_act`/`/act` arguments: `ref` (a number, or digits) wins; a text that starts
/// with a listed ref (`[3] button "Add to cart"`, copied whole from the list) is that ref.
pub fn from_args(args: &Value) -> Option<ClickTarget> {
let r = &args["ref"];
let num = r.as_u64().or_else(|| r.as_str().and_then(|t| unmarked(t.trim()).trim_start_matches('[').trim_end_matches(']').parse().ok()));
if let Some(n) = num.and_then(|n| u32::try_from(n).ok()).filter(|n| *n > 0) {
return Some(ClickTarget::Ref(n));
}
let text = args["text"].as_str().map(str::trim).filter(|t| !t.is_empty())?;
// Only a whole copied line: a bare "[1]" is a footnote link's label (Wikipedia)
if let Some((n, rest)) = unmarked(text).strip_prefix('[').and_then(|t| t.split_once(']')) {
if let Some(n) = n.trim().parse::<u32>().ok().filter(|n| *n > 0 && rest.contains('"')) {
return Some(ClickTarget::Ref(n));
}
}
Some(ClickTarget::Text(text.to_string()))
}
}
/// One line of the control list: `[3] button "Add to cart" · Sauce Labs Backpack`. The context
/// (nearby text) is only there when several controls share a name, or, for a control that shows
/// on hover (marked [`HOVER_MARK`]), it is the card to hover. A control that wasn't in the
/// page's previous list starts with [`NEW_MARK`]: `*[12] option "Large"`.
pub fn ref_line(item: &Value) -> Option<String> {
let r = item["ref"].as_u64()?;
let name = item["name"].as_str().filter(|n| !n.is_empty()).or(item["label"].as_str())?;
let role = item["role"].as_str().filter(|r| !r.is_empty()).unwrap_or("button");
let mark = if item["new"].as_bool() == Some(true) { NEW_MARK } else { "" };
let mut line = format!("{mark}[{r}] {role} \"{name}\"");
if item["hover"].as_bool() == Some(true) {
line.push_str(HOVER_MARK);
}
if let Some(ctx) = item["context"].as_str().filter(|c| !c.is_empty()) {
line.push_str(" · ");
line.push_str(ctx);
}
Some(line)
}
/// Marks a control that shows only when the mouse is over its card (the card follows as the
/// context): `[7] button "More" (on hover) · Clip 1`. A click on it hovers the card first.
pub const HOVER_MARK: &str = " (on hover)";
/// How long a page gets to show what it shows on hover (a CSS transition, a JS mouseenter).
const HOVER_SETTLE: Duration = Duration::from_millis(200);
/// What a hover brought up, for the bot: `Hovered over "Clip 1". Appeared: More (button)`.
pub fn hover_summary(over: &str, appeared: &[String]) -> String {
if appeared.is_empty() {
format!("Hovered over \"{over}\". Nothing new appeared.")
} else {
format!("Hovered over \"{over}\". Appeared: {}", appeared.join(", "))
}
}
/// Marks a control line as new since the page's previous list (see [`ref_line`]).
pub const NEW_MARK: &str = "*";
/// `line` without its [`NEW_MARK`], to compare lines across reads.
pub fn unmarked(line: &str) -> &str {
line.strip_prefix(NEW_MARK).unwrap_or(line)
}
/// Refuses an address that is a file on the computer before it reaches Chrome, so it is never
/// read as a page on the site already open. file:// is refused in every mode: in Local mode it
/// would show the bot any file on the person's computer, past the folders and approvals its
/// file tools keep to.
pub fn refuse_file_path(target: &str) -> Result<(), BrowserError> {
let t = target.trim();
if t.get(..5).is_some_and(|scheme| scheme.eq_ignore_ascii_case("file:")) {
return Err(BrowserError::NotWebAddress(format!(
"{t} is a file:// address, which the browser doesn't open. Read local files with your file tools \
(Read, or cat in the shell); the browser opens http:// and https:// pages."
)));
}
let b = t.as_bytes();
let drive = b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && matches!(b[2], b'\\' | b'/');
let path = drive || ["/", "~", "\\", "./", "../", ".\\", "..\\"].iter().any(|p| t.starts_with(p));
if path {
return Err(BrowserError::NotWebAddress(format!(
"{t} is a file path on the computer, not a web address, so the browser didn't open it. \
Read local files with your file tools (Read, or cat in the shell); the browser opens \
http:// and https:// pages."
)));
}
Ok(())
}
/// A link to another app (`tiktok://`, `snssdk1233://`, `intent:`) is refused before it reaches
/// Chrome: Chrome would put up an "Open <app>?" prompt the bot can't see or answer, and the tab
/// ignores every click and key until a cross-site navigation (see [`super::app_links`]).
pub fn refuse_app_link(target: &str) -> Result<(), BrowserError> {
match super::app_links::refused_scheme(target) {
Some(scheme) => Err(BrowserError::NotWebAddress(super::app_links::refused_text(target, &scheme))),
None => Ok(()),
}
}
/// The address a navigate hands Chrome, the same for a bot and for the live view. A file path is
/// refused first (`C:\Users\…` would otherwise read as a link to an app called `c:`), then a
/// link to another app; a web address written as `host:port` (`localhost:8080/x`) gets its
/// scheme, because Chrome would read `localhost:` as one and hand it to the operating system.
pub fn web_address(target: &str) -> Result<std::borrow::Cow<'_, str>, BrowserError> {
refuse_file_path(target)?;
refuse_app_link(target)?;
Ok(match super::app_links::host_port(target) {
Some(443) => format!("https://{}", target.trim()).into(),
Some(_) => format!("http://{}", target.trim()).into(),
None => target.into(),
})
}
/// Longest page text a wall phrase counts on: a check page is short (Cloudflare, Amazon,
/// PerimeterX and Google's "sorry" page are all well under this), while an article or a help page
/// that only quotes "verify you are human" is not a wall.
pub const WALL_TEXT_MAX_CHARS: usize = 3000;
/// Phrases a human-check page shows (lower case, straight apostrophes). Each one names the check
/// itself, never a passing mention: "press and hold" alone is a power button, "captcha" alone is
/// an article.
const WALL_PHRASES: &[&str] = &[
"i'm not a robot",
"i am not a robot",
"are you a robot",
"make sure you're not a robot",
"confirm you're not a robot",
"verify you're not a robot",
"prove you're not a robot",
"confirm you are not a robot",
"confirm that you are not a robot",
"verify you are not a robot",
"verify that you are not a robot",
"verify you are human",
"verify you are a human",
"verify that you are human",
"verify that you are a human",
"verify you're human",
"verifying you are human",
"confirm you are human",
"confirm you are a human",
"confirm that you are human",
"prove you're human",
"prove you are human",
"complete the captcha",
"solve the captcha",
"complete the security check",
"complete the following challenge",
"enter the characters you see",
"type the characters you see",
"press & hold to confirm",
"press and hold to confirm",
"performing security verification",
"bots use duckduckgo too",
];
/// Whether a page address is a CAPTCHA page by itself: a host or a path segment about one
/// (`geo.captcha-delivery.com`, `/errors/validateCaptcha`, `/showcaptcha`), not a query that only
/// mentions it.
fn captcha_url(url: &str) -> bool {
let Ok(u) = url::Url::parse(url) else { return false };
u.host_str().is_some_and(|h| h.contains("captcha")) || u.path().to_lowercase().split('/').any(|seg| seg.contains("captcha"))
}
/// Recognises CAPTCHA / anti-bot interstitials that replace the requested content.
///
/// Phrases count only on a short page (or in the title): a check page carries little else. A
/// widget on an otherwise normal page is the job of [`CAPTCHA_PROBE_JS`].
pub fn detect_bot_wall(url: &str, title: &str, text: &str) -> Option<&'static str> {
// Curly apostrophes ("you’re") read as straight ones
let norm = |s: &str| s.to_lowercase().replace(['\u{2019}', '\u{2018}'], "'");
let title = norm(title);
let text = norm(text);
let lower_url = url.to_lowercase();
let short = text.chars().count() <= WALL_TEXT_MAX_CHARS;
if lower_url.contains("google.") && lower_url.contains("/sorry/") || text.contains("unusual traffic from your computer network") {
return Some("Google \"unusual traffic\" CAPTCHA");
}
if title.starts_with("just a moment")
|| title.starts_with("attention required! | cloudflare")
|| title.starts_with("checking your browser")
|| title.starts_with("checking if the site connection is secure")
|| short && (text.contains("checking your browser") || text.contains("checking if the site connection is secure"))
{
return Some("Cloudflare bot check");
}
if WALL_PHRASES.iter().any(|m| title.contains(m) || short && text.contains(m)) || short && captcha_url(url) {
return Some("CAPTCHA / human verification");
}
None
}
fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write;
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
#[cfg(unix)]
{ use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?; }
}
let tmp = path.with_extension("tmp");
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{ use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); }
let mut file = options.open(&tmp)?;
file.write_all(bytes)?;
file.sync_all()?;
std::fs::rename(&tmp, path)
}
pub(crate) const FOCUSED_EDITABLE_JS: &str = r#"(() => {
let el = document.activeElement;
for (let i = 0; el && i < 8; i++) {
if (el.shadowRoot && el.shadowRoot.activeElement) { el = el.shadowRoot.activeElement; continue; }
if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
try { const inner = el.contentDocument && el.contentDocument.activeElement; if (inner) { el = inner; continue; } } catch (e) {}
return false;
}
break;
}
if (!el) return false;
if (el.isContentEditable) return true;
if (el.tagName === 'TEXTAREA') return !el.readOnly && !el.disabled;
if (el.tagName !== 'INPUT') return false;
const t = (el.type || 'text').toLowerCase();
return !el.readOnly && !el.disabled && ['text','search','email','url','tel','password','number','date','datetime-local','month','time','week'].includes(t);
})()"#;
/// Finds a visible CAPTCHA widget in the page (document, open shadow roots and same-origin
/// frames) and returns `{kind, x, y, width, height}` in viewport pixels, or null. Never scrolls:
/// a widget below the fold comes back with `offscreen: true` and no usable box.
///
/// Look-alikes are skipped: a reCAPTCHA v2 checkbox only counts while its challenge (bframe) is
/// open or the page is otherwise a wall (no field to fill, little text), and phrases like
/// "press and hold" only count inside an element whose id or class looks like a CAPTCHA.
/// Whether the page is a sign-in wall (0.9.5): a visible one-time-code field is `"two_factor"`,
/// a visible password field `"sign_in"`, else `null`. Only fields a person can see count, so a
/// hidden login form in a page's header or a modal that isn't open doesn't.
pub const SIGN_IN_PROBE_JS: &str = r##"(function () {
function shown(el) {
if (!el || el.disabled || el.type === 'hidden') return false;
var r = el.getBoundingClientRect();
if (r.width < 4 || r.height < 4) return false;
var s = window.getComputedStyle(el);
return s.visibility !== 'hidden' && s.display !== 'none' && Number(s.opacity) > 0.05;
}
var inputs = Array.prototype.slice.call(document.querySelectorAll('input'));
var otp = inputs.some(function (el) {
if (!shown(el)) return false;
var ac = (el.getAttribute('autocomplete') || '').toLowerCase();
if (ac === 'one-time-code') return true;
var hint = ((el.name || '') + ' ' + (el.id || '')).toLowerCase();
return /(^|[^a-z])(otp|totp|2fa|mfa)([^a-z]|$)|verification.?code|one.?time/.test(hint);
});
if (otp) return 'two_factor';
if (inputs.some(function (el) { return el.type === 'password' && shown(el); })) return 'sign_in';
return null;
})()"##;
/// The kind of sign-in wall a page shows ([`SIGN_IN_PROBE_JS`]): `"sign_in"` or `"two_factor"`.
pub fn sign_in_kind(value: &Value) -> Option<&'static str> {
match value.as_str() {
Some("sign_in") => Some("sign_in"),
Some("two_factor") => Some("two_factor"),
_ => None,
}
}
pub const CAPTCHA_PROBE_JS: &str = r##"(function () {
var VENDORS = [
['recaptcha', /(^|\.)google\.com\/recaptcha\/|recaptcha\.net\/recaptcha\//i],
['hcaptcha', /(^|\/\/|\.)hcaptcha\.com\//i],
['turnstile', /challenges\.cloudflare\.com\//i],
['arkose', /arkoselabs\.com|funcaptcha\.com/i],
['datadome', /captcha-delivery\.com/i],
['geetest', /geetest\.com/i]
];
var SELECTORS = [
['geetest', '.geetest_panel, .geetest_box, .geetest_holder, .geetest_widget, .geetest_captcha'],
['arkose', '#FunCaptcha, #arkose, [data-e2e="enforcement-frame"]'],
['perimeterx', '#px-captcha'],
['datadome', '#ddv1-captcha-container, .captcha__human'],
['tiktok', '#captcha_container, #captcha-verify-container-main-page, .captcha_verify_container, .captcha-verify-container, [class*="captcha_verify"], [class*="captcha-verify"], [id^="tiktok-verify"]']
];
var PHRASES = /drag the slider|drag the puzzle piece|slide to complete the puzzle|drag the puzzle|slide to verify|select all images with|press (and|&) hold/i;
// ids/classes a real challenge box carries; a cookie or newsletter dialog doesn't
var CAPTCHA_LIKE = /captcha|challenge|verif(y|ication)|secsdk|geetest|(^|[\s_-])(px|dd)[-_]/;
var vw = window.innerWidth, vh = window.innerHeight;
function visible(el, rect) {
if (rect.width < 30 || rect.height < 30) return false;
var st = getComputedStyle(el);
return st.display !== 'none' && st.visibility !== 'hidden' && parseFloat(st.opacity || '1') > 0.05;
}
function frameOffset(win) {
var x = 0, y = 0;
try {
while (win && win !== window && win.frameElement) {
var r = win.frameElement.getBoundingClientRect();
x += r.left; y += r.top; win = win.parent;
}
} catch (e) {}
return [x, y];
}
function box(kind, el) {
var r = el.getBoundingClientRect();
if (!visible(el, r)) return null;
var off = frameOffset(el.ownerDocument.defaultView);
var left = r.left + off[0], top = r.top + off[1];
var x = Math.max(0, left), y = Math.max(0, top);
var w = Math.min(vw, left + r.width) - x, h = Math.min(vh, top + r.height) - y;
if (w < 10 || h < 10) return {kind: kind, offscreen: true, x: 0, y: 0, width: 0, height: 0};
return {kind: kind, x: Math.round(x), y: Math.round(y), width: Math.round(w), height: Math.round(h)};
}
function captchaLike(n) {
var tag = ((n.id || '') + ' ' + (typeof n.className === 'string' ? n.className : '')).toLowerCase();
return CAPTCHA_LIKE.test(tag);
}
function container(el) {
for (var n = el, i = 0; n && i < 12; i++) {
if (n.nodeType === 1 && captchaLike(n)) return n;
n = n.parentNode || n.host;
}
return null;
}
// A page that is nothing but the check (Google's "sorry" page, a bare verify form): no field a
// person would fill in and little text. A contact form or a page with a footer form isn't.
function wallPage() {
var fields = document.querySelectorAll('input, textarea, select');
for (var i = 0; i < fields.length; i++) {
var t = (fields[i].getAttribute('type') || 'text').toLowerCase();
if (fields[i].tagName === 'INPUT' && /^(hidden|submit|button|image|reset|checkbox|radio)$/.test(t)) continue;
var r = fields[i].getBoundingClientRect();
if (r.width > 0 && r.height > 0) return false;
}
return ((document.body && document.body.innerText) || '').trim().length < 1000;
}
var roots = [];
function collect(root, depth) {
if (!root || depth > 6) return;
roots.push(root);
var all = root.querySelectorAll('*');
for (var i = 0; i < all.length; i++) {
var el = all[i];
if (el.shadowRoot) collect(el.shadowRoot, depth + 1);
if (el.tagName === 'IFRAME' || el.tagName === 'FRAME') {
try { if (el.contentDocument) collect(el.contentDocument, depth + 1); } catch (e) {}
}
}
}
collect(document, 0);
var found = null, anchor = null;
for (var ri = 0; ri < roots.length && !found; ri++) {
var frames = roots[ri].querySelectorAll('iframe');
for (var f = 0; f < frames.length && !found; f++) {
var src = frames[f].getAttribute('src') || '';
if (frames[f].closest && frames[f].closest('.grecaptcha-badge')) continue;
if (/recaptcha\/(api2|enterprise)\/anchor.*[?&]size=invisible/i.test(src)) continue;
for (var v = 0; v < VENDORS.length; v++) {
if (!VENDORS[v][1].test(src)) continue;
if (VENDORS[v][0] === 'recaptcha') {
if (/recaptcha\/(api2|enterprise)\/bframe/i.test(src)) {
// Google parks a closed challenge at top:-10000px and hides it
var b = box('recaptcha', frames[f]);
if (b && frames[f].getBoundingClientRect().top + window.scrollY > -1000) found = b;
} else if (!anchor) {
anchor = frames[f];
}
} else {
found = box(VENDORS[v][0], frames[f]);
}
break;
}
}
}
if (!found && anchor && wallPage()) found = box('recaptcha', anchor);
// Turnstile now draws its iframe inside a closed shadow root, so on Cloudflare's own check page
// (or a bare Turnstile form) only its host box is visible. On a page with fields to fill, a
// Turnstile box is part of a form the person submits, not a wall.
if (!found && wallPage()) {
// the widget's own box first, then the stage Cloudflare wraps it in
var TS = ['.cf-turnstile, #cf-turnstile', '#turnstile-wrapper, #challenge-stage'];
for (var q = 0; q < TS.length && !found; q++) {
for (var rt = 0; rt < roots.length && !found; rt++) {
var ts = roots[rt].querySelectorAll(TS[q]);
for (var t = 0; t < ts.length && !found; t++) found = box('turnstile', ts[t]);
}
}
}
for (var ri2 = 0; ri2 < roots.length && !found; ri2++) {
for (var s = 0; s < SELECTORS.length && !found; s++) {
var els = roots[ri2].querySelectorAll(SELECTORS[s][1]);
for (var e = 0; e < els.length && !found; e++) found = box(SELECTORS[s][0], els[e]);
}
}
for (var ri3 = 0; ri3 < roots.length && !found; ri3++) {
var root = roots[ri3];
var walker = (root.ownerDocument || root).createTreeWalker(root, NodeFilter.SHOW_TEXT);
var node;
while (!found && (node = walker.nextNode())) {
if (!PHRASES.test(node.nodeValue || '')) continue;
var c = container(node.parentNode);
if (c) found = box(/tiktok/i.test(location.hostname) ? 'tiktok' : 'puzzle', c);
}
}
return found;
})()"##;
pub const CAPTCHA_KINDS: &[&str] = &["recaptcha", "hcaptcha", "turnstile", "arkose", "geetest", "datadome", "perimeterx", "tiktok", "puzzle"];
/// Where a CAPTCHA widget sits in the viewport, so the person's view can point at it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CaptchaHit {
pub kind: String,
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
/// The widget is on the page but outside the viewport (the probe never scrolls), so the box
/// is empty and shouldn't be pointed at.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub offscreen: bool,
}
impl CaptchaHit {
/// Validates what the page returned: a known kind and a finite box inside the viewport, or an
/// off-screen widget without a box.
pub fn parse(value: &Value) -> Option<Self> {
let kind = value.get("kind")?.as_str()?;
if !CAPTCHA_KINDS.contains(&kind) { return None; }
if value.get("offscreen").and_then(Value::as_bool) == Some(true) {
return Some(Self { kind: kind.to_string(), x: 0.0, y: 0.0, width: 0.0, height: 0.0, offscreen: true });
}
let num = |k: &str| value.get(k).and_then(Value::as_f64).filter(|n| n.is_finite());
let (x, y) = (num("x")?.clamp(0.0, 1280.0), num("y")?.clamp(0.0, 800.0));
let width = num("width")?.clamp(0.0, 1280.0 - x);
let height = num("height")?.clamp(0.0, 800.0 - y);
if width < 1.0 || height < 1.0 { return None; }
Some(Self { kind: kind.to_string(), x, y, width, height, offscreen: false })
}
/// The box, when it's on screen and worth pointing the person's view at.
pub fn on_screen(self) -> Option<Self> {
(!self.offscreen).then_some(self)
}
pub fn label(&self) -> &'static str {
match self.kind.as_str() {
"recaptcha" => "reCAPTCHA",
"hcaptcha" => "hCaptcha",
"turnstile" => "Cloudflare Turnstile check",
"arkose" => "Arkose (FunCaptcha) puzzle",
"geetest" => "GeeTest puzzle",
"datadome" => "DataDome check",
"perimeterx" => "PerimeterX press-and-hold check",
"tiktok" => "TikTok slider puzzle",
_ => "slider / puzzle CAPTCHA",
}
}
}
/// Clicks only "reject" / "decline optional" in known cookie banners (OneTrust, Cookiebot,
/// Didomi, Usercentrics, Quantcast, Google, TikTok) and in containers that are clearly a
/// consent banner. Never accepts. Returns the clicked label or null.
pub const CONSENT_REJECT_JS: &str = r##"(function () {
var KNOWN = ['#onetrust-reject-all-handler', '#CybotCookiebotDialogBodyButtonDecline',
'#didomi-notice-disagree-button', '[data-testid="uc-deny-all-button"]',
'.qc-cmp2-summary-buttons button[mode="secondary"]', '#truste-consent-required',
'.cmpboxbtnno', '#cmpwelcomebtnno a', '.fc-cta-do-not-consent', 'button#W0wltc'];
var REJECT = /^\s*(reject( all| optional)?( cookies)?|decline( all| optional)?( cookies)?|deny( all)?|refuse( all)?|only (necessary|essential|required)( cookies)?|use necessary cookies only|necessary cookies only|continue without accepting|alle ablehnen|ablehnen|tout refuser|refuser|rechazar( todo)?|rifiuta( tutto)?|weiger(en)?|odrzuć|відхилити|отклонить)\s*$/i;
var ACCEPT = /accept|allow|agree|consent|got it|^\s*ok\s*$|akzept|accepter|aceptar|accetta|zustimmen/i;
var NEGATED = /\b(not|don't|reject|decline|deny|refuse|necessary|essential|required)\b|ablehnen|refuser|rechazar|rifiuta/i;
var BANNER = /cookie|consent|gdpr|cmp|privacy|onetrust|didomi|usercentrics|cookiebot|qc-cmp|truste/i;
function label(el) { return (el.innerText || el.textContent || el.getAttribute('aria-label') || el.value || '').replace(/\s+/g, ' ').trim(); }
function shown(el) { var r = el.getBoundingClientRect(); var st = getComputedStyle(el); return r.width > 0 && r.height > 0 && st.visibility !== 'hidden' && st.display !== 'none'; }
function click(el) { var l = label(el); if (ACCEPT.test(l) && !NEGATED.test(l)) return null; el.click(); return l || 'reject'; }
var roots = [];
(function collect(root, d) { if (!root || d > 4) return; roots.push(root);
var all = root.querySelectorAll('*');
for (var i = 0; i < all.length; i++) { if (all[i].shadowRoot) collect(all[i].shadowRoot, d + 1);
if (all[i].tagName === 'IFRAME') { try { if (all[i].contentDocument) collect(all[i].contentDocument, d + 1); } catch (e) {} } }
})(document, 0);
for (var r = 0; r < roots.length; r++) {
for (var k = 0; k < KNOWN.length; k++) {
var el = roots[r].querySelector(KNOWN[k]);
if (el && shown(el)) { var c = click(el); if (c) return c; }
}
}
for (var r2 = 0; r2 < roots.length; r2++) {
var host = roots[r2].host;
var buttons = roots[r2].querySelectorAll('button, [role="button"], a[href="#"], input[type="button"]');
for (var b = 0; b < buttons.length; b++) {
var btn = buttons[b], text = label(btn);
if (!REJECT.test(text) || !shown(btn)) continue;
var inBanner = false;
for (var n = btn, i = 0; n && i < 10; i++, n = n.parentNode || n.host) {
if (n.nodeType !== 1) continue;
var tag = (n.id || '') + ' ' + (typeof n.className === 'string' ? n.className : '') + ' ' + (n.getAttribute('aria-label') || '') + ' ' + n.tagName;
if (BANNER.test(tag)) { inBanner = true; break; }
}
if (!inBanner && host) inBanner = BANNER.test(host.tagName + ' ' + (host.id || '') + ' ' + (host.className || ''));
if (inBanner) { btn.click(); return text; }
}
}
return null;
})()"##;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NavigationResult {
pub url: String,
pub title: String,
pub status_code: u16,
}
/// A password the person typed into a page, waiting for them to confirm saving it. The origin is
/// the frame's real URL as Chrome reports it, never anything the page says about itself.
#[derive(Clone, Serialize, PartialEq)]
pub struct PendingCapture {
pub origin: String,
pub username: String,
#[serde(skip)]
pub password: String,
pub captured_at: String,
}
impl std::fmt::Debug for PendingCapture {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PendingCapture")
.field("origin", &self.origin)
.field("username", &self.username)
.finish_non_exhaustive()
}
}
/// The store and owner (team, channel or bot id) a browser fills passwords from.
#[derive(Clone)]
pub struct Vault {
pub store: Arc<dyn CredentialStore>,
pub owner: String,
}
/// Name of the isolated world kwnt's autofill and capture run in: the page's own scripts share
/// the DOM but not its JavaScript globals, so they can't read or forge the capture.
const KWNT_WORLD: &str = "kwnt-autofill";
/// Runs in [`KWNT_WORLD`]; `window` here is that world's own global, not the page's.
const AUTOFILL_SCRIPT: &str = r#"
(function(creds) {
var USER = 'input[type="text"], input[type="email"], input:not([type]), input[name*="user"], input[name*="login"], input[name*="email"], input[id*="user"], input[id*="login"]';
function visible(el) {
var r = el.getBoundingClientRect();
var s = window.getComputedStyle(el);
return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none';
}
function postsHere(input) {
var f = input.form;
if (!f || !f.getAttribute('action')) return true;
try { return new URL(f.action, location.href).origin === location.origin; } catch (e) { return false; }
}
function set(input, value) {
input.value = value;
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
}
function fill() {
if (!creds || location.origin !== creds.origin) return;
var pass = Array.prototype.find.call(document.querySelectorAll('input[type="password"]'), function(p) {
return visible(p) && postsHere(p);
});
if (!pass || pass.value) return;
var scope = pass.form || document;
var user = Array.prototype.find.call(scope.querySelectorAll(USER), visible);
if (user && !user.value && creds.username) set(user, creds.username);
set(pass, creds.password);
}
fill();
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fill);
setTimeout(fill, 600);
setTimeout(fill, 1800);
if (window.__kwntCaptureInstalled) return;
window.__kwntCaptureInstalled = true;
function record(scope) {
if (!scope) return;
var pass = scope.querySelector('input[type="password"]');
if (!pass || !pass.value) return;
var user = scope.querySelector(USER);
window.__kwntCaptured = { username: user ? user.value : '', password: pass.value };
}
document.addEventListener('submit', function(e) { record(e.target); }, true);
document.addEventListener('click', function(e) {
var btn = e.target.closest && e.target.closest('button, input[type="submit"], [role="button"]');
if (btn) record(btn.closest('form') || document);
}, true);
})(__KWNT_CREDS__);
"#;
const COLLECT_SCRIPT: &str = r#"
(function() {
var c = window.__kwntCaptured;
window.__kwntCaptured = null;
return c ? JSON.stringify(c) : null;
})()
"#;
/// Mouse buttons held down by the person's live-view input: a CDP `buttons` bitmask (left 1,
/// right 2, middle 4, back 8, forward 16) and where the pointer was last seen.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct HeldPointer {
pub x: f64,
pub y: f64,
pub buttons: u8,
}
/// One live view's own page size: the size its stage asked for with `resize`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ViewClaim {
pub socket: u64,
pub width: u32,
pub height: u32,
pub dpr: f64,
}
/// What a live view letting go of its size leaves the page at.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ViewRelease {
/// It had no size of its own, or a newer view's size is on the page: nothing changes.
Keep,
/// Its size was on the page and another view still has one: the newest of those.
Reapply(ViewClaim),
/// The last sized view let go: the bot's own viewport comes back.
Restore,
}
/// The sizes the open live views asked for, oldest first. The newest is the one on the page:
/// the last resize wins, and the bot's viewport comes back when the last sized view lets go.
#[derive(Debug, Default)]
pub struct ViewClaims(Vec<ViewClaim>);
impl ViewClaims {
/// `claim` resized the page: it replaces that view's earlier size and becomes the newest.
pub fn claim(&mut self, claim: ViewClaim) {
self.0.retain(|c| c.socket != claim.socket);
self.0.push(claim);
}
/// The view on `socket` hands back, goes to the background or closes.
pub fn release(&mut self, socket: u64) -> ViewRelease {
let Some(at) = self.0.iter().position(|c| c.socket == socket) else { return ViewRelease::Keep };
let newest = at + 1 == self.0.len();
self.0.remove(at);
match (newest, self.0.last()) {
(false, _) => ViewRelease::Keep,
(true, Some(next)) => ViewRelease::Reapply(*next),
(true, None) => ViewRelease::Restore,
}
}
/// A view asking again for the size it already has while a newer view's size is on the page:
/// the desktop stage re-asking when the page doesn't match it, which would take the page back
/// from the phone that opened after it. Only a new size wins.
pub fn repeats_older(&self, claim: &ViewClaim) -> bool {
self.0.last().is_some_and(|newest| newest.socket != claim.socket) && self.0.contains(claim)
}
pub fn is_empty(&self) -> bool { self.0.is_empty() }
}
/// CDP button names for each bit of a `buttons` mask, in bit order.
pub const MOUSE_BUTTON_BITS: [(u8, &str); 5] = [(1, "left"), (2, "right"), (4, "middle"), (8, "back"), (16, "forward")];
#[derive(Clone)]
pub struct BrowserController {
pub cdp_port: u16,
pub current_url: Arc<Mutex<Option<String>>>,
pub current_title: Arc<Mutex<Option<String>>>,
pub last_screenshot: Arc<Mutex<Option<String>>>,
vault: Arc<Mutex<Option<Vault>>>,
/// A password captured on the page, waiting for the person's OK.
pending_capture: Arc<Mutex<Option<PendingCapture>>>,
/// kwnt's isolated world in the current document.
capture_world: Arc<Mutex<Option<i64>>>,
msg_id: Arc<AtomicU64>,
ws_conn: Arc<Mutex<Option<WsStream>>>,
endpoint: String,
target_id: Option<String>,
browser_level: bool,
pub control: Arc<RwLock<()>>,
/// Held while a human step (sign in, CAPTCHA) waits on the person: bot actions get
/// `HumanControl` and the person's live-view input goes through without taking control.
held_for_person: Arc<std::sync::Mutex<Option<OwnedRwLockWriteGuard<()>>>>,
/// How many [`PersonLease`]s live views hold (0 or 1): tells a takeover refused because the
/// person has the browser in another window from one refused because a bot is mid-step.
view_leases: Arc<AtomicUsize>,
/// Which mouse buttons live-view input holds down, and where, if any.
pointer_held: Arc<std::sync::Mutex<Option<HeldPointer>>>,
/// The page sizes open live views asked for. Async: a resize holds it while it applies, so
/// two views resizing at once leave the newest claim's size on the page.
view_claims: Arc<Mutex<ViewClaims>>,
/// VM mode: this bot's cookies, saved outside the throwaway browser context.
cookie_jar: Arc<std::sync::Mutex<Option<std::path::PathBuf>>>,
/// The fixed viewport set for a windowless browser, restored after a bot's sized screenshot.
/// `None`: the page follows its real window.
viewport: Arc<std::sync::Mutex<Option<(u32, u32)>>>,
/// The bot's recent actions, for the loop stop (see [`super::progress::Tracker`]).
pub progress: Arc<std::sync::Mutex<super::progress::Tracker>>,
/// Which read each bot saw last, for "unchanged since your last read" (see [`super::reads`]).
pub reads: Arc<std::sync::Mutex<super::reads::Reads>>,
/// The driving bot's site rules and the task enforcing them (see [`super::site_guard`]).
pub site_guard: Arc<super::site_guard::SiteGuard>,
/// The popups the bot's page opened: the newest still open is the page commands go to (see
/// [`super::popups`]).
popups: Arc<super::popups::Popups>,
/// [`super::popups::Popups::generation`] when `ws_conn` was opened: a newer one means the
/// page in front changed and the next command reconnects to it.
ws_generation: Arc<AtomicU64>,
/// The page may be frozen (see [`Self::freeze`]): the next command wakes it first.
needs_wake: Arc<AtomicBool>,
/// How many live views show this page now: a watched page is never frozen.
watchers: Arc<AtomicUsize>,
/// The bot session's own download/chooser connection (see [`super::browser_downloads`]),
/// started once this controller has a working folder to land downloads in.
downloads: Arc<std::sync::Mutex<Option<super::browser_downloads::DownloadCenter>>>,
}
/// Stops media in a page that is put to rest, so a feed or video doesn't keep decoding. Media it
/// muted is unmuted when the page wakes ([`UNMUTE_SCRIPT`]); nothing resumes playing by itself.
const REST_MEDIA_SCRIPT: &str = r#"(() => { let n = 0;
for (const m of document.querySelectorAll('video, audio')) {
if (!m.paused) { m.pause(); n++; }
if (!m.muted) { m.muted = true; m.dataset.kwntMuted = '1'; }
}
return n; })()"#;
const UNMUTE_SCRIPT: &str = r#"(() => { for (const m of document.querySelectorAll('[data-kwnt-muted]')) { m.muted = false; delete m.dataset.kwntMuted; } })()"#;
/// Counts one live view of a page while it lives (see [`BrowserController::watch`]).
pub struct WatchGuard(Arc<AtomicUsize>);
impl Drop for WatchGuard {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
/// Widest screenshot a bot gets, in pixels, and the narrowest width it may ask for.
pub const AGENT_SHOT_MAX_WIDTH: u32 = 1280;
pub const AGENT_SHOT_MIN_WIDTH: u32 = 320;
/// Tallest viewport a bot's screenshot uses, so a tall window doesn't make a huge image.
const AGENT_SHOT_MAX_HEIGHT: u32 = 1600;
/// A screenshot taken for a bot: base64 JPEG and its size in pixels.
#[derive(Debug, Clone)]
pub struct AgentShot {
pub data: String,
pub width: u32,
pub height: u32,
}
/// The viewport a bot's screenshot is taken at: `None` keeps the page as it is (already at most
/// [`AGENT_SHOT_MAX_WIDTH`] wide at scale 1), else a temporary `(width, height, mobile)`.
pub fn agent_shot_viewport(asked: Option<u32>, now: (u32, u32), scale: f64) -> Option<(u32, u32, bool)> {
let (w, h) = now;
match asked {
Some(asked) => {
let width = asked.clamp(AGENT_SHOT_MIN_WIDTH, AGENT_SHOT_MAX_WIDTH);
let mobile = width <= 600;
let height = if mobile { 844 } else { 800 };
Some((width, height, mobile))
}
None if w <= AGENT_SHOT_MAX_WIDTH && h <= AGENT_SHOT_MAX_HEIGHT && (scale - 1.0).abs() < 0.01 => None,
None => Some((w.clamp(1, AGENT_SHOT_MAX_WIDTH), h.clamp(1, AGENT_SHOT_MAX_HEIGHT), false)),
}
}
impl std::fmt::Debug for BrowserController {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BrowserController")
.field("cdp_port", &self.cdp_port)
.finish()
}
}
impl BrowserController {
pub fn new(cdp_port: u16) -> Self {
Self {
cdp_port,
current_url: Arc::new(Mutex::new(None)),
current_title: Arc::new(Mutex::new(None)),
last_screenshot: Arc::new(Mutex::new(None)),
vault: Arc::new(Mutex::new(None)),
pending_capture: Arc::new(Mutex::new(None)),
capture_world: Arc::new(Mutex::new(None)),
msg_id: Arc::new(AtomicU64::new(1)),
ws_conn: Arc::new(Mutex::new(None)),
endpoint: format!("http://127.0.0.1:{cdp_port}"),
target_id: None,
browser_level: false,
control: Arc::new(RwLock::new(())),
held_for_person: Arc::default(),
view_leases: Arc::default(),
pointer_held: Arc::default(),
view_claims: Arc::default(),
cookie_jar: Arc::default(),
viewport: Arc::default(),
progress: Arc::default(),
reads: Arc::default(),
site_guard: Arc::default(),
popups: Arc::default(),
ws_generation: Arc::default(),
needs_wake: Arc::default(),
watchers: Arc::default(),
downloads: Arc::default(),
}
}
/// Puts an idle page to rest: pauses its media, then freezes it (Chrome stops its timers,
/// animation frames and network tasks; the page keeps its state and still answers DevTools).
/// The next command through this controller, or any controller of the page made later,
/// wakes it first (see [`Self::wake_before_use`]).
pub async fn freeze(&self) -> Result<(), BrowserError> {
self.send_cdp_command("Runtime.evaluate", json!({"expression": REST_MEDIA_SCRIPT, "returnByValue": true})).await?;
// marked and frozen under the connection's lock, so no command slips in between and
// finds the page frozen but unmarked
let mut guard = self.ws_conn.lock().await;
self.ensure_connected(&mut guard).await?;
self.needs_wake.store(true, Ordering::SeqCst);
let frozen = raw_call(guard.as_mut().unwrap(), &self.msg_id, "Page.setWebLifecycleState", json!({"state": "frozen"})).await;
if frozen.is_err() { *guard = None; }
frozen.map(|_| ())
}
/// Sends the page to about:blank (a team page idle for hours: its site's memory is freed; the
/// team's cookies are kept in its jar first).
pub async fn blank(&self) -> Result<(), BrowserError> {
self.persist_cookies().await;
self.send_cdp_command("Page.navigate", json!({"url": "about:blank"})).await?;
*self.current_url.lock().await = Some("about:blank".into());
*self.current_title.lock().await = Some(String::new());
Ok(())
}
/// Whether the page may be frozen, so its next command wakes it.
pub fn needs_wake(&self) -> bool { self.needs_wake.load(Ordering::SeqCst) }
/// Marks the page as possibly frozen, by an earlier controller or an earlier run of kwant:
/// its next command wakes it.
pub fn wake_before_use(&self) { self.needs_wake.store(true, Ordering::SeqCst); }
/// Wakes the page now if it may be frozen (the live view, which talks to the page on its own
/// connection, calls this first).
pub async fn wake(&self) -> Result<(), BrowserError> {
if self.needs_wake() {
self.send_cdp_command("Runtime.evaluate", json!({"expression": "1", "returnByValue": true})).await?;
}
Ok(())
}
/// Counts a live view of this page until the guard drops: a watched page is never frozen.
pub fn watch(&self) -> WatchGuard {
self.watchers.fetch_add(1, Ordering::SeqCst);
WatchGuard(self.watchers.clone())
}
/// How many live views show this page now.
pub fn watchers(&self) -> usize { self.watchers.load(Ordering::SeqCst) }
/// On `ws`, the page's own connection: makes the page active again and shows its window
/// once more. Chrome keeps a page that was frozen "hidden" after it is made active (its
/// screencast sends no frames and `requestAnimationFrame` never runs); minimizing its window
/// and restoring it makes it visible again (checked on kwnt-browser's Chrome 156).
async fn wake_page(&self, ws: &mut WsStream) -> Result<(), BrowserError> {
let id = &self.msg_id;
// Chrome refusing the method (an error reply, which await_reply gives as the error's
// JSON) leaves nothing frozen to wake; a page that doesn't answer, or a dead socket, fails
match raw_call(ws, id, "Page.setWebLifecycleState", json!({"state": "active"})).await {
Err(BrowserError::Protocol(reply)) if reply.starts_with('{') => {}
Err(error) => return Err(error),
Ok(_) => {}
}
if let Ok(window) = raw_call(ws, id, "Browser.getWindowForTarget", json!({})).await {
if let Some(window) = window["windowId"].as_i64() {
for state in ["minimized", "normal"] {
let bounds = json!({"windowId": window, "bounds": {"windowState": state}});
let _ = raw_call(ws, id, "Browser.setWindowBounds", bounds).await;
}
}
}
let _ = raw_call(ws, id, "Runtime.evaluate", json!({"expression": UNMUTE_SCRIPT})).await;
Ok(())
}
/// Sets the fixed viewport of a windowless browser, and remembers it so a sized screenshot
/// can put it back.
pub async fn set_viewport(&self, width: u32, height: u32) -> Result<(), BrowserError> {
self.send_cdp_command(
"Emulation.setDeviceMetricsOverride",
json!({"width": width, "height": height, "deviceScaleFactor": 1, "mobile": false}),
)
.await?;
*self.viewport.lock().unwrap_or_else(|e| e.into_inner()) = Some((width, height));
Ok(())
}
/// Fills and captures passwords for `owner` from `store`.
pub async fn attach_vault(&self, store: Arc<dyn CredentialStore>, owner: &str) {
*self.vault.lock().await = Some(Vault { store, owner: owner.to_string() });
}
pub fn at_endpoint(endpoint: &str, target_id: Option<String>, browser_level: bool) -> Self {
let mut ctrl = Self::new(0);
ctrl.endpoint = endpoint.trim_end_matches('/').to_string();
ctrl.target_id = target_id;
ctrl.browser_level = browser_level;
ctrl
}
/// Starts this session's own download/chooser connection, landing downloads under
/// `workspace/downloads/` and reporting (but not auto-answering) file pickers it opens.
/// Idempotent: a session already running its own connection keeps it. `home`, `context_id`
/// and `staging_root` are passed straight to [`super::browser_downloads::DownloadCenter::start`].
pub async fn configure_downloads(
&self,
workspace: std::path::PathBuf,
home: super::browser_downloads::DownloadHome,
context_id: Option<String>,
staging_root: std::path::PathBuf,
) {
if self.downloads.lock().unwrap_or_else(|e| e.into_inner()).is_some() {
return;
}
// `run` only calls `get_ws_url()`, never touches `downloads` — give it a clone with that
// field cut so the center isn't kept alive by its own background task (ctrl -> downloads
// -> jobs Sender -> the Receiver `run` awaits forever), which would leak its connection.
let mut ctrl = self.clone();
ctrl.downloads = Arc::default();
let center = super::browser_downloads::DownloadCenter::start(ctrl, workspace, home, context_id, staging_root).await;
let mut guard = self.downloads.lock().unwrap_or_else(|e| e.into_inner());
if guard.is_none() {
*guard = Some(center);
}
}
/// One line worth telling the bot about its most recent download, if the session has its own
/// connection running and there's something new to say.
pub fn latest_download_report(&self) -> Option<serde_json::Value> {
self.downloads.lock().unwrap_or_else(|e| e.into_inner()).as_ref()?.report()
}
/// The current download's status, like `latest_download_report`, but without consuming a
/// terminal state: for a page read that's a side effect of something else, so the bot's own
/// dedicated "did it finish" check still gets to see the terminal state once.
pub fn peek_download_report(&self) -> Option<serde_json::Value> {
self.downloads.lock().unwrap_or_else(|e| e.into_inner()).as_ref()?.peek()
}
/// The currently open file picker on this session, if any.
pub fn open_chooser_report(&self) -> Option<serde_json::Value> {
self.downloads.lock().unwrap_or_else(|e| e.into_inner()).as_ref()?.open_chooser()
}
/// Answers the currently open chooser on this session with `files`. Refuses with a plain
/// message if no download/chooser connection is running (the session was never configured)
/// or no picker is open.
pub async fn answer_upload(&self, local: bool, files: Vec<super::browser_downloads::UploadFile>) -> Result<Vec<String>, String> {
let center = self.downloads.lock().unwrap_or_else(|e| e.into_inner()).clone();
let Some(center) = center else {
return Err("This session isn't set up to answer file pickers yet.".into());
};
center.answer_chooser(local, files).await
}
/// The person's control for one live view. Refused with [`BrowserError::HeldByPerson`] while
/// another live view has it, and with [`BrowserError::HumanControl`] while a bot is mid-step.
pub async fn take_control(&self) -> Result<PersonLease, BrowserError> {
match self.control.clone().try_write_owned() {
Ok(guard) => {
self.view_leases.fetch_add(1, Ordering::SeqCst);
Ok(PersonLease { views: self.view_leases.clone(), _guard: guard })
}
Err(_) if self.view_leases.load(Ordering::SeqCst) > 0 => Err(BrowserError::HeldByPerson),
Err(_) => Err(BrowserError::HumanControl),
}
}
/// Locks the browser to the person until [`Self::release_person_hold`]. Waits briefly for a
/// bot action in flight; `false` if it couldn't (the person already has control, say).
pub async fn hold_for_person(&self) -> bool {
if self.is_held_for_person() {
return true;
}
let Ok(guard) = timeout(std::time::Duration::from_secs(5), self.control.clone().write_owned()).await else {
return false;
};
*self.held_for_person.lock().unwrap_or_else(|e| e.into_inner()) = Some(guard);
true
}
pub fn release_person_hold(&self) {
self.held_for_person.lock().unwrap_or_else(|e| e.into_inner()).take();
}
pub fn is_held_for_person(&self) -> bool {
self.held_for_person.lock().unwrap_or_else(|e| e.into_inner()).is_some()
}
pub fn is_managed_session(&self) -> bool { self.target_id.is_some() }
pub(crate) fn pointer_held_slot(&self) -> &std::sync::Mutex<Option<HeldPointer>> { &self.pointer_held }
pub(crate) fn view_claims(&self) -> &Mutex<ViewClaims> { &self.view_claims }
/// The fixed viewport of a windowless browser (normally 1280x800), or `None` when the page
/// follows a real window. The live view restores it when the person hands back.
pub fn fixed_viewport(&self) -> Option<(u32, u32)> {
*self.viewport.lock().unwrap_or_else(|e| e.into_inner())
}
pub async fn refresh_location(&self) -> Result<(), BrowserError> {
let result = self.send_cdp_command("Runtime.evaluate", json!({
"expression": "({url: location.href, title: document.title})", "returnByValue": true
})).await?;
if let Some(url) = result["result"]["value"]["url"].as_str() {
*self.current_url.lock().await = Some(url.to_string());
}
if let Some(title) = result["result"]["value"]["title"].as_str() {
*self.current_title.lock().await = Some(title.to_string());
}
Ok(())
}
// Chromium advertises its own hostname; the configured endpoint may be a Docker service or proxy.
fn reachable_ws_url(&self, advertised: &str) -> Result<String, BrowserError> {
if self.cdp_port != 0 { return Ok(advertised.to_string()); } // legacy/test direct endpoints
let mut url = reqwest::Url::parse(&self.endpoint).map_err(|e| BrowserError::Protocol(e.to_string()))?;
let target = reqwest::Url::parse(advertised).map_err(|e| BrowserError::Protocol(e.to_string()))?;
let scheme = if url.scheme() == "https" { "wss" } else { "ws" };
url.set_scheme(scheme).map_err(|_| BrowserError::Protocol("Invalid CDP scheme".into()))?;
url.set_path(target.path());
url.set_query(target.query());
Ok(url.to_string())
}
/// Bumped each time the page in front changes: a popup the bot's page opened, or its close.
pub fn page_changes(&self) -> tokio::sync::watch::Receiver<u64> { self.popups.changes() }
/// The DevTools address of the page commands go to: the bot's page, or the newest popup it
/// opened that is still open (see [`super::popups`]).
pub async fn get_ws_url(&self) -> Result<String, BrowserError> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(3))
.build()
.map_err(|e| BrowserError::Http(e.to_string()))?;
// 1. Try /json/list to get active Page target
let list_url = format!("{}/json/list", self.endpoint);
if !self.browser_level {
let listed = client.get(&list_url).header(reqwest::header::HOST, "localhost").send().await;
// a page's own list request that timed out or was refused is the browser's state, not a
// sign its page is gone
if let Err(e) = &listed {
if self.target_id.is_some() || e.is_timeout() {
return Err(http_error(listed.err().unwrap()));
}
}
if let Ok(resp) = listed {
if let Ok(targets) = resp.json::<Vec<Value>>().await {
let pages: Vec<&Value> = targets.iter().filter(|t| t["type"] == "page").collect();
let chain = self.popups.chain();
let listed = |id: &str| pages.iter().copied().find(|t| t["id"] == id);
// the bot's page: its session's page, else the one it had while it is open, else
// the first page that isn't a popup it opened
let home = match &self.target_id {
Some(id) => listed(id),
None => chain.home().and_then(listed).or_else(|| {
pages.iter().copied().find(|t| !chain.is_popup(t["id"].as_str().unwrap_or_default()))
}),
};
if let Some(page) = home {
if let Some(ws) = page["webSocketDebuggerUrl"].as_str() {
let ws = self.reachable_ws_url(ws)?;
// a DevTools endpoint that names no page ids (a proxy, a test double):
// its page as before, with no popups to follow
let Some(id) = page["id"].as_str() else { return Ok(ws) };
self.popups.set_home(id);
self.follow_popups().await;
// a popup that just closed may still be in front until its close arrives
let chain = self.popups.chain();
if let Some(popup) = chain.active().filter(|a| Some(*a) != chain.home() && listed(a).is_some()) {
return Ok(super::popups::page_ws_url(&ws, popup));
}
return Ok(ws);
}
}
}
}
if self.target_id.is_some() { return Err(BrowserError::Protocol("Browser session no longer exists".into())); }
}
// 2. Fallback to /json/version
let url = format!("{}/json/version", self.endpoint);
let resp = client
.get(&url)
.header(reqwest::header::HOST, "localhost")
.send()
.await
.map_err(http_error)?;
let json: Value = resp.json().await.map_err(http_error)?;
let advertised = json["webSocketDebuggerUrl"]
.as_str()
.ok_or_else(|| BrowserError::Protocol("Missing webSocketDebuggerUrl".into()))?;
self.reachable_ws_url(advertised)
}
/// GET `{endpoint}{path}` as JSON (the DevTools `/json/...` routes).
async fn devtools_json(&self, path: &str) -> Result<Value, BrowserError> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(3))
.build()
.map_err(|e| BrowserError::Http(e.to_string()))?;
let resp = client
.get(format!("{}{path}", self.endpoint))
.header(reqwest::header::HOST, "localhost")
.send()
.await
.map_err(http_error)?;
resp.json().await.map_err(http_error)
}
/// The browser-level DevTools address of this controller's browser.
async fn browser_ws(&self) -> Option<String> {
let version = self.devtools_json("/json/version").await.ok()?;
let advertised = version["webSocketDebuggerUrl"].as_str()?;
self.reachable_ws_url(advertised).ok()
}
/// Makes sure every page, popup and worker of this browser tells sites what it really is,
/// without the headless token ([`super::identity`]). Cheap once its keeper runs.
pub async fn keep_identity(&self) {
if let Some(browser_ws) = self.browser_ws().await {
super::identity::keep(browser_ws).await;
}
}
/// Starts following the popups the bot's page opens, unless that is already running. Also
/// starts the identity keeper again if the browser restarted under this controller.
async fn follow_popups(&self) {
if self.popups.is_watching() {
return;
}
let Some(browser_ws) = self.browser_ws().await else { return };
super::identity::keep(browser_ws.clone()).await;
self.popups.watch(browser_ws).await;
}
/// The DevTools target id of this controller's page (the bot's page, never a popup it opened:
/// the site guard follows those from it).
async fn page_target_id(&self) -> Result<String, BrowserError> {
if let Some(id) = &self.target_id {
return Ok(id.clone());
}
if let Some(home) = self.popups.chain().home() {
return Ok(home.to_string());
}
let targets = self.devtools_json("/json/list").await?;
targets
.as_array()
.and_then(|t| t.iter().find(|t| t["type"] == "page"))
.and_then(|t| t["id"].as_str())
.map(str::to_string)
.ok_or_else(|| BrowserError::Protocol("No page to guard".into()))
}
/// Applies the driving bot's site rules: empty rules stop the guard; others start it if it
/// isn't running, and return once it intercepts. `Err` when it couldn't be started, so the
/// bot's action isn't done unguarded.
pub async fn apply_site_rules(&self, rules: super::site_guard::SiteRules) -> Result<(), BrowserError> {
if !self.site_guard.set_rules(rules) {
return Ok(());
}
let page = self.page_target_id().await?;
let version = self.devtools_json("/json/version").await?;
let advertised = version["webSocketDebuggerUrl"]
.as_str()
.ok_or_else(|| BrowserError::Protocol("Missing webSocketDebuggerUrl".into()))?;
let browser_ws = self.reachable_ws_url(advertised)?;
let (tx, rx) = tokio::sync::oneshot::channel();
let task = tokio::spawn(super::site_guard::run(Arc::downgrade(&self.site_guard), browser_ws, page, self.control.clone(), tx));
self.site_guard.set_task(task);
match timeout(Duration::from_secs(8), rx).await {
Ok(Ok(true)) => Ok(()),
_ => Err(BrowserError::Protocol("The browser couldn't turn on this bot's site rules".into())),
}
}
async fn ensure_connected(
&self,
guard: &mut tokio::sync::MutexGuard<'_, Option<WsStream>>,
) -> Result<(), BrowserError> {
// a popup came to the front or closed since this connection opened: go to the page in front
let generation = self.popups.generation();
if guard.is_some() && generation != self.ws_generation.load(Ordering::SeqCst) {
tracing::debug!("the page in front changed; reconnecting to it");
**guard = None;
// kwnt's isolated world belonged to the other page
if let Ok(mut world) = self.capture_world.try_lock() {
*world = None;
}
}
if guard.is_none() {
let ws_url = self.get_ws_url().await?;
// after: finding the page may itself have announced the bot's page or a popup
self.ws_generation.store(self.popups.generation(), Ordering::SeqCst);
let mut ws = connect_cdp(&ws_url).await?;
tracing::debug!(target_id = ?self.target_id, "opened a DevTools connection");
self.reapply_viewport(&mut ws).await;
// the browser-level endpoint has no page to guard (Page.* isn't found there)
if ws_url.contains("/devtools/page/") {
guard_app_links(&mut ws, &self.msg_id).await;
}
**guard = Some(ws);
}
Ok(())
}
/// Chrome drops a session's `Emulation` overrides when its DevTools connection closes, so a
/// new connection would show the page at the window's own size (1280×713 in a 1280×800
/// headless window). Puts the fixed viewport back on it before anything else is sent.
async fn reapply_viewport(&self, ws: &mut WsStream) {
let Some((width, height)) = *self.viewport.lock().unwrap_or_else(|e| e.into_inner()) else { return };
let id = self.msg_id.fetch_add(1, Ordering::SeqCst);
let request = json!({
"id": id,
"method": "Emulation.setDeviceMetricsOverride",
"params": {"width": width, "height": height, "deviceScaleFactor": 1, "mobile": false},
});
let sent = match ws.send(Message::Text(request.to_string())).await {
Ok(()) => timeout(Duration::from_secs(5), await_reply(ws, id)).await.map_err(|_| BrowserError::Timeout).and_then(|r| r.and_then(|r| r)),
Err(e) => Err(BrowserError::Ws(e.to_string())),
};
if let Err(e) = sent {
tracing::warn!(error = %e, "couldn't put the browser viewport back on a new DevTools connection");
}
}
pub async fn send_cdp_command(
&self,
method: &str,
params: Value,
) -> Result<Value, BrowserError> {
let mut guard = self.ws_conn.lock().await;
self.ensure_connected(&mut guard).await?;
if !self.browser_level && self.needs_wake.load(Ordering::SeqCst) {
match self.wake_page(guard.as_mut().unwrap()).await {
Ok(()) => self.needs_wake.store(false, Ordering::SeqCst),
Err(e) => {
// stays marked, so the next command tries again on a new connection
*guard = None;
return Err(e);
}
}
}
let id = self.msg_id.fetch_add(1, Ordering::SeqCst);
let request = json!({
"id": id,
"method": method,
"params": params
});
let ws = guard.as_mut().unwrap();
if ws.send(Message::Text(request.to_string())).await.is_err() {
// Reconnect and retry send once if disconnected
*guard = None;
self.ensure_connected(&mut guard).await?;
let ws = guard.as_mut().unwrap();
ws.send(Message::Text(request.to_string()))
.await
.map_err(|e| BrowserError::Ws(e.to_string()))?;
}
let deadline = Duration::from_secs(15);
let ws = guard.as_mut().unwrap();
match timeout(deadline, await_reply(ws, id)).await {
// Chrome answered with an error: the connection is fine, and replacing it would
// drop the session's overrides (the fixed viewport), so keep it
Ok(Ok(reply)) => {
if let Err(e) = &reply {
tracing::debug!(method, error = %e, "DevTools error reply; keeping the connection");
}
reply
}
Ok(Err(e)) => {
tracing::debug!(method, error = %e, "DevTools connection lost; the next command opens a new one");
*guard = None;
Err(e)
}
Err(_) => {
tracing::debug!(method, "DevTools command timed out; the next command opens a new one");
*guard = None;
Err(BrowserError::Timeout)
}
}
}
async fn vault(&self) -> Option<Vault> {
self.vault.lock().await.clone()
}
/// The main frame's id and real URL, as Chrome reports them.
async fn main_frame(&self) -> Option<(String, String)> {
let tree = self.send_cdp_command("Page.getFrameTree", json!({})).await.ok()?;
let frame = &tree["frameTree"]["frame"];
Some((frame["id"].as_str()?.to_string(), frame["url"].as_str()?.to_string()))
}
fn web_origin(url: &str) -> Option<String> {
let u = url::Url::parse(url).ok()?;
matches!(u.scheme(), "http" | "https").then(|| u.origin().ascii_serialization())
}
/// Sets up autofill and capture in kwnt's isolated world of the current document. The saved
/// password goes only to a page whose real origin (scheme, host and port) is exactly the
/// saved one, into a visible password field whose form posts to the same origin.
pub async fn inject_autofill_and_capture(&self) -> Result<(), BrowserError> {
*self.capture_world.lock().await = None;
let Some(vault) = self.vault().await else { return Ok(()) };
let Some((frame_id, url)) = self.main_frame().await else { return Ok(()) };
let Some(origin) = Self::web_origin(&url) else { return Ok(()) };
let world = self
.send_cdp_command("Page.createIsolatedWorld", json!({"frameId": frame_id, "worldName": KWNT_WORLD}))
.await?;
let Some(context) = world["executionContextId"].as_i64() else { return Ok(()) };
*self.capture_world.lock().await = Some(context);
let fill = match vault.store.for_origin(&vault.owner, &origin).await {
Ok(Some(c)) => json!({"origin": origin, "username": c.meta.username, "password": c.password}),
_ => Value::Null,
};
let script = AUTOFILL_SCRIPT.replace("__KWNT_CREDS__", &fill.to_string());
let _ = self
.send_cdp_command(
"Runtime.evaluate",
json!({ "expression": script, "contextId": context, "returnByValue": false }),
)
.await;
Ok(())
}
/// Takes a password the person submitted on the page into [`Self::pending_capture`], to be
/// saved only when they confirm. The origin comes from the frame's URL, read before and
/// after, so a capture is never filed under another site. A capture that equals the saved
/// credential (the autofill itself) is dropped.
pub async fn collect_captured_credentials(&self) -> Option<PendingCapture> {
let context = (*self.capture_world.lock().await)?;
let (_, before) = self.main_frame().await?;
let r = self
.send_cdp_command(
"Runtime.evaluate",
json!({ "expression": COLLECT_SCRIPT, "contextId": context, "returnByValue": true }),
)
.await
.ok()?;
let raw = r["result"]["value"].as_str()?;
let (_, after) = self.main_frame().await?;
let origin = Self::web_origin(&before)?;
if Self::web_origin(&after).as_deref() != Some(origin.as_str()) {
return None;
}
let val: Value = serde_json::from_str(raw).ok()?;
let username = val["username"].as_str().unwrap_or("").to_string();
let password = val["password"].as_str().unwrap_or("").to_string();
if password.is_empty() {
return None;
}
if let Some(vault) = self.vault().await {
if let Ok(Some(saved)) = vault.store.for_origin(&vault.owner, &origin).await {
if saved.meta.username == username && saved.password == password {
return None;
}
}
}
let capture = PendingCapture { origin, username, password, captured_at: chrono::Utc::now().to_rfc3339() };
self.hold_for_confirmation(capture.clone()).await;
Some(capture)
}
/// Holds a captured password until the person saves or discards it (replacing an older one).
pub async fn hold_for_confirmation(&self, capture: PendingCapture) {
*self.pending_capture.lock().await = Some(capture);
}
/// The capture waiting for the person, if any.
pub async fn pending(&self) -> Option<PendingCapture> {
self.pending_capture.lock().await.clone()
}
pub async fn take_pending(&self) -> Option<PendingCapture> {
self.pending_capture.lock().await.take()
}
/// A bot opens `target_url`: its site rules are checked first, and a redirect they refuse
/// fails the same way. The person's own navigation is [`Self::navigate_unlocked`].
pub async fn navigate(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {
let _permit = self.control.try_read().map_err(|_| BrowserError::HumanControl)?;
let address = web_address(target_url)?;
self.site_guard.set_actor(super::site_guard::Actor::Bot);
self.site_guard.check(&address).await.map_err(BrowserError::SiteRule)?;
let _ = self.site_guard.take_refusal();
let navigated = self.navigate_unlocked(&address).await;
if let Some(refusal) = self.site_guard.take_refusal() {
self.leave_refused_page().await;
return Err(BrowserError::SiteRule(refusal));
}
let result = navigated?;
// Bot navigation only: the person decides banners themselves in the live view
if let Some(clicked) = self.reject_consent().await {
tracing::debug!("Declined cookie banner via \"{}\"", clicked);
let _ = self.capture_screenshot().await;
}
self.persist_cookies().await;
Ok(result)
}
/// After a page the site rules refused: Chrome shows its own error page in its place, so
/// go back to the page before it (when there is one), where the bot was.
pub async fn leave_refused_page(&self) {
let on_error = |v: &Value| v["result"]["value"].as_str().is_some_and(|u| u.starts_with("chrome-error:"));
let href = json!({"expression": "location.href", "returnByValue": true});
// The error page commits just after the refused request
let mut erred = false;
for _ in 0..10 {
if self.send_cdp_command("Runtime.evaluate", href.clone()).await.is_ok_and(|v| on_error(&v)) {
erred = true;
break;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
if !erred {
return;
}
let Ok(history) = self.send_cdp_command("Page.getNavigationHistory", json!({})).await else { return };
let index = history["currentIndex"].as_u64().unwrap_or(0) as usize;
let Some(entry) = index.checked_sub(1).and_then(|i| history["entries"].get(i)) else { return };
let _ = self.send_cdp_command("Page.navigateToHistoryEntry", json!({"entryId": entry["id"]})).await;
for _ in 0..30 {
tokio::time::sleep(Duration::from_millis(100)).await;
if self.send_cdp_command("Runtime.evaluate", href.clone()).await.is_ok_and(|v| !on_error(&v)) {
break;
}
}
let _ = self.refresh_location().await;
}
pub async fn navigate_unlocked(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {
let address = web_address(target_url)?;
let target_url: &str = &address;
self.progress.lock().unwrap_or_else(|e| e.into_inner()).reset();
let _ = self.collect_captured_credentials().await;
let _ = self.send_cdp_command("Page.enable", json!({})).await;
let res = self
.send_cdp_command("Page.navigate", json!({ "url": target_url }))
.await?;
if let Some(error) = res["errorText"].as_str() {
// Chrome shows its own error page; reflect it in the viewer
tokio::time::sleep(Duration::from_millis(200)).await;
let _ = self.sync_location().await;
let _ = self.capture_screenshot().await;
return Err(BrowserError::Navigation(error.to_string()));
}
*self.last_screenshot.lock().await = None;
// Report where the browser actually ended up (redirects, e.g. to a CAPTCHA page)
let (url, title) = match self.sync_location().await {
Some(loc) => loc,
None => {
*self.current_url.lock().await = Some(target_url.to_string());
*self.current_title.lock().await = Some(target_url.to_string());
(target_url.to_string(), target_url.to_string())
}
};
// Automatically inject autofill and capture hooks
let _ = self.inject_autofill_and_capture().await;
// Automatically capture fresh screenshot on navigation
self.capture_screenshot().await?;
Ok(NavigationResult {
url,
title,
status_code: 200,
})
}
pub async fn capture_screenshot(&self) -> Result<String, BrowserError> {
let res = self
.send_cdp_command(
"Page.captureScreenshot",
json!({ "format": "jpeg", "quality": 75 }),
)
.await?;
let b64 = res["data"]
.as_str()
.ok_or_else(|| BrowserError::Protocol("Screenshot data missing".into()))?
.to_string();
*self.last_screenshot.lock().await = Some(b64.clone());
Ok(b64)
}
/// A screenshot for a bot to look at, optionally at a given page width (390 for a phone, 1280
/// for a desktop). The viewport is put back afterwards, and the live panel's picture is left
/// alone. Refused while the person has the browser.
pub async fn capture_for_agent(&self, width: Option<u32>) -> Result<AgentShot, BrowserError> {
let _permit = self.control.try_read().map_err(|_| BrowserError::HumanControl)?;
let res = self
.send_cdp_command(
"Runtime.evaluate",
json!({"expression": "[innerWidth, innerHeight, devicePixelRatio]", "returnByValue": true}),
)
.await?;
let v = &res["result"]["value"];
let num = |i: usize, d: f64| v[i].as_f64().filter(|n| n.is_finite() && *n > 0.0).unwrap_or(d);
let now = (num(0, 1280.0).round() as u32, num(1, 800.0).round() as u32);
let scale = num(2, 1.0);
let Some((w, h, mobile)) = agent_shot_viewport(width, now, scale) else {
let data = self.jpeg().await?;
return Ok(AgentShot { data, width: now.0, height: now.1 });
};
self.send_cdp_command(
"Emulation.setDeviceMetricsOverride",
json!({"width": w, "height": h, "deviceScaleFactor": 1, "mobile": mobile}),
)
.await?;
// Let responsive layouts settle at the new width
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
let shot = self.jpeg().await;
let fixed = *self.viewport.lock().unwrap_or_else(|e| e.into_inner());
let restored = match fixed {
Some((fw, fh)) => {
self.send_cdp_command(
"Emulation.setDeviceMetricsOverride",
json!({"width": fw, "height": fh, "deviceScaleFactor": 1, "mobile": false}),
)
.await
}
None => self.send_cdp_command("Emulation.clearDeviceMetricsOverride", json!({})).await,
};
if let Err(e) = restored {
tracing::warn!(error = %e, "couldn't restore the browser viewport after a screenshot");
}
Ok(AgentShot { data: shot?, width: w, height: h })
}
async fn jpeg(&self) -> Result<String, BrowserError> {
let res = self
.send_cdp_command("Page.captureScreenshot", json!({"format": "jpeg", "quality": 70}))
.await?;
res["data"]
.as_str()
.filter(|d| !d.is_empty())
.map(str::to_string)
.ok_or_else(|| BrowserError::Protocol("Screenshot data missing".into()))
}
/// The page as one [`Snapshot`](super::progress::Snapshot) (url, title, the rendered text in
/// lines, scroll and field state, and focus), in one read. Also updates the stored location.
pub async fn snapshot(&self) -> Option<super::progress::Snapshot> {
let expression = r#"
(function() {
// The rendered text, laid out in lines (hidden parts, scripts and styles left out)
var text = document.body ? document.body.innerText.substring(0, 10000) : '';
// Lengths and checks only: a field's value never leaves the page
var fields = [];
document.querySelectorAll('input,textarea,select').forEach(function (el) {
fields.push((el.value || '').length + (el.checked ? 'c' : ''));
});
var a = document.activeElement;
var focus = a ? a.tagName + '#' + (a.id || a.name || '') : '';
return [location.href, document.title, text, Math.round(scrollX) + ',' + Math.round(scrollY) + '|' + fields.join(','), focus];
})()
"#;
let res = self
.send_cdp_command("Runtime.evaluate", json!({ "expression": expression, "returnByValue": true }))
.await
.ok()?;
let v = res["result"]["value"].as_array()?;
let s = |i: usize| v.get(i).and_then(Value::as_str).unwrap_or_default().to_string();
let snap = super::progress::Snapshot { url: s(0), title: s(1), text: s(2), state: s(3), focus: s(4) };
if snap.url.is_empty() {
return None;
}
*self.current_url.lock().await = Some(snap.url.clone());
*self.current_title.lock().await = Some(snap.title.clone());
Some(snap)
}
/// The page's rendered text and its same-origin frames', each with its own address (the page
/// first), for citing what a bot read ([`super::cite`]). Frames from other sites can't be read
/// from the page, so they are left out.
pub async fn frame_texts(&self) -> Option<Vec<super::cite::FrameText>> {
let expression = r#"
(function() {
var out = [];
function walk(win, depth) {
var doc;
try { doc = win.document; if (!doc) return; } catch (e) { return; }
// A frame without an address of its own (about:blank, srcdoc) can't be linked to
var href = String(win.location.href);
if (depth === 0 || !/^about:/.test(href)) {
out.push([href, doc.body ? doc.body.innerText.substring(0, 200000) : '']);
}
if (depth > 3 || out.length > 20) return;
for (var i = 0; i < win.frames.length; i++) {
try { walk(win.frames[i], depth + 1); } catch (e) {}
}
}
walk(window, 0);
return out;
})()
"#;
let res = self
.send_cdp_command("Runtime.evaluate", json!({ "expression": expression, "returnByValue": true }))
.await
.ok()?;
let frames: Vec<super::cite::FrameText> = res["result"]["value"]
.as_array()?
.iter()
.filter_map(|f| {
let url = f.get(0)?.as_str()?.to_string();
let text = f.get(1)?.as_str()?.to_string();
Some(super::cite::FrameText { url, text })
})
.collect();
(!frames.is_empty() && !frames[0].url.is_empty()).then_some(frames)
}
pub async fn extract_content(&self) -> Result<String, BrowserError> {
let expression = r#"
(function() {
if (!document.body) return '';
var clone = document.body.cloneNode(true);
var scripts = clone.getElementsByTagName('script');
while(scripts.length > 0) { scripts[0].parentNode.removeChild(scripts[0]); }
var styles = clone.getElementsByTagName('style');
while(styles.length > 0) { styles[0].parentNode.removeChild(styles[0]); }
return clone.innerText.substring(0, 10000);
})()
"#;
let res = self
.send_cdp_command(
"Runtime.evaluate",
json!({ "expression": expression, "returnByValue": true }),
)
.await?;
let text = res["result"]["value"].as_str().unwrap_or("").to_string();
Ok(text)
}
pub async fn click(&self, selector: &str) -> Result<(), BrowserError> {
let _permit = self.control.try_read().map_err(|_| BrowserError::HumanControl)?;
let sel_json = serde_json::to_string(selector)
.map_err(|e| BrowserError::Protocol(e.to_string()))?;
let expression = format!(
"var el = document.querySelector({}); if (el) {{ el.click(); true; }} else {{ false; }}",
sel_json
);
let res = self
.send_cdp_command(
"Runtime.evaluate",
json!({ "expression": expression, "returnByValue": true }),
)
.await?;
if res["result"]["value"].as_bool() != Some(true) {
return Err(BrowserError::Protocol("Element not found for selector".into()));
}
tokio::time::sleep(Duration::from_millis(500)).await;
let _ = self.collect_captured_credentials().await;
let _ = self.capture_screenshot().await;
Ok(())
}
pub async fn type_text(&self, selector: &str, text: &str) -> Result<(), BrowserError> {
let _permit = self.control.try_read().map_err(|_| BrowserError::HumanControl)?;
let sel_json = serde_json::to_string(selector)
.map_err(|e| BrowserError::Protocol(e.to_string()))?;
let text_json = serde_json::to_string(text)
.map_err(|e| BrowserError::Protocol(e.to_string()))?;
let expression = format!(
"var el = document.querySelector({}); if (el) {{ el.value = {}; el.dispatchEvent(new Event('input', {{ bubbles: true }})); true; }} else {{ false; }}",
sel_json,
text_json
);
let res = self
.send_cdp_command(
"Runtime.evaluate",
json!({ "expression": expression, "returnByValue": true }),
)
.await?;
if res["result"]["value"].as_bool() != Some(true) {
return Err(BrowserError::Protocol("Element not found for selector".into()));
}
tokio::time::sleep(Duration::from_millis(300)).await;
let _ = self.capture_screenshot().await;
Ok(())
}
/// Whether the page's focused element takes typing (a text field or editable area), followed
/// into open shadow roots and same-origin frames. The live view opens the phone keyboard on it.
pub async fn focused_editable(&self) -> bool {
let Ok(res) = self.send_cdp_command("Runtime.evaluate", json!({
"expression": FOCUSED_EDITABLE_JS, "returnByValue": true
})).await else { return false };
res["result"]["value"].as_bool().unwrap_or(false)
}
/// A visible CAPTCHA widget on the page, if any. `Err` when the page couldn't be read
/// (mid-navigation, say): callers treat that as unknown, never as "gone".
pub async fn probe_captcha(&self) -> Result<Option<CaptchaHit>, BrowserError> {
let res = self.send_cdp_command("Runtime.evaluate", json!({
"expression": CAPTCHA_PROBE_JS, "returnByValue": true
})).await?;
if res.get("exceptionDetails").is_some() {
return Err(BrowserError::Protocol("CAPTCHA probe failed".into()));
}
Ok(CaptchaHit::parse(&res["result"]["value"]))
}
/// The sign-in wall the page shows, if any (see [`SIGN_IN_PROBE_JS`]).
pub async fn probe_sign_in(&self) -> Result<Option<&'static str>, BrowserError> {
let res = self.send_cdp_command("Runtime.evaluate", json!({
"expression": SIGN_IN_PROBE_JS, "returnByValue": true
})).await?;
if res.get("exceptionDetails").is_some() {
return Err(BrowserError::Protocol("sign-in probe failed".into()));
}
Ok(sign_in_kind(&res["result"]["value"]))
}
/// Declines optional cookies on a known consent banner. Never accepts.
pub async fn reject_consent(&self) -> Option<String> {
// Consent managers often render a moment after load: look twice
for attempt in 0..2 {
if attempt > 0 { tokio::time::sleep(Duration::from_millis(700)).await; }
let Ok(res) = self.send_cdp_command("Runtime.evaluate", json!({
"expression": CONSENT_REJECT_JS, "returnByValue": true
})).await else { return None };
if let Some(label) = res["result"]["value"].as_str() {
tokio::time::sleep(Duration::from_millis(300)).await;
return Some(label.chars().take(80).collect());
}
}
None
}
/// VM mode keeps cookies in a file because the browser's profile lives on tmpfs.
pub fn set_cookie_jar(&self, path: Option<std::path::PathBuf>) {
*self.cookie_jar.lock().unwrap_or_else(|e| e.into_inner()) = path;
}
fn cookie_jar_path(&self) -> Option<std::path::PathBuf> {
self.cookie_jar.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
/// Saves this page's browser-context cookies to the jar (owner-only file, written atomically).
pub async fn persist_cookies(&self) {
let Some(path) = self.cookie_jar_path() else { return };
let Ok(res) = self.send_cdp_command("Network.getAllCookies", json!({})).await else { return };
let Some(cookies) = res["cookies"].as_array() else { return };
// session cookies die with the browser anyway; keep only persistent ones
let kept: Vec<&Value> = cookies.iter().filter(|c| c["session"].as_bool() != Some(true)).collect();
if let Err(error) = write_private(&path, &serde_json::to_vec(&kept).unwrap_or_default()) {
tracing::warn!("Could not save browser cookies: {}", error);
}
}
/// Loads the jar into a fresh browser context. Returns how many cookies were restored.
pub async fn restore_cookies(&self) -> usize {
let Some(path) = self.cookie_jar_path() else { return 0 };
let Ok(bytes) = std::fs::read(&path) else { return 0 };
let Ok(Value::Array(cookies)) = serde_json::from_slice::<Value>(&bytes) else { return 0 };
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0);
let params: Vec<Value> = cookies.iter().filter(|c| c["expires"].as_f64().is_some_and(|e| e > now)).map(|c| {
let mut p = json!({});
for key in ["name", "value", "domain", "path", "secure", "httpOnly", "sameSite", "expires", "priority", "sameParty", "sourceScheme", "partitionKey"] {
if let Some(v) = c.get(key) { if !v.is_null() { p[key] = v.clone(); } }
}
p
}).collect();
if params.is_empty() { return 0; }
let count = params.len();
match self.send_cdp_command("Network.setCookies", json!({"cookies": params})).await {
Ok(_) => count,
Err(error) => { tracing::warn!("Could not restore browser cookies: {}", error); 0 }
}
}
/// Re-reads the page's real URL and title, since user clicks/keys can navigate
/// without going through `navigate()`.
pub async fn sync_location(&self) -> Option<(String, String)> {
let res = self
.send_cdp_command(
"Runtime.evaluate",
json!({ "expression": "[location.href, document.title]", "returnByValue": true }),
)
.await
.ok()?;
let vals = res["result"]["value"].as_array()?;
let url = vals.first()?.as_str()?.to_string();
let title = vals.get(1).and_then(|v| v.as_str()).unwrap_or("").to_string();
if url.is_empty() {
return None;
}
*self.current_url.lock().await = Some(url.clone());
*self.current_title.lock().await = Some(title.clone());
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, target: Option<&ClickTarget>) -> Result<Value, BrowserError> {
let needle = match target {
Some(ClickTarget::Text(t)) => json!(t),
Some(ClickTarget::Ref(n)) => json!(n),
None => Value::Null,
};
let script = PAYMENT_SIGNALS_JS.replace("__CLICKABLES__", CLICKABLES_JS).replace("__REF__", REF_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())
}
/// The page's controls as numbered refs (see [`ref_line`]), topmost (e.g. modal buttons)
/// first. Listing also re-indexes the page, so the refs a bot was last shown are the ones
/// [`Self::click_ref`] resolves.
pub async fn list_clickables(&self, limit: usize) -> Vec<String> {
let expression = format!("({})(null)", CLICKABLES_JS);
let Ok(res) = self
.send_cdp_command(
"Runtime.evaluate",
json!({ "expression": expression, "returnByValue": true }),
)
.await
else {
return Vec::new();
};
res["result"]["value"]["items"]
.as_array()
.map(|items| items.iter().filter_map(ref_line).take(limit).collect())
.unwrap_or_default()
}
/// Clicks control `r` from the last list with a real mouse click at its center, after
/// checking it is still in the page, shown, unchanged and not covered (see [`REF_JS`]). A
/// control that shows only on hover (a tile's ⋮ button) gets the mouse over its card first.
/// Otherwise clicks nothing and says why ([`BrowserError::StaleRef`]); the page state the
/// caller returns next re-lists the controls.
pub async fn click_ref(&self, r: u32) -> Result<String, BrowserError> {
self.click_checked(json!(r), &format!("ref {r}")).await
}
/// One [`REF_JS`] check of `key` (a ref, or `"hovered"`).
async fn ref_check(&self, key: &Value) -> Result<Value, BrowserError> {
let res = self
.send_cdp_command(
"Runtime.evaluate",
json!({ "expression": format!("({REF_JS})({key}, false)"), "returnByValue": true }),
)
.await?;
if let Some(err) = res.get("exceptionDetails") {
return Err(BrowserError::Protocol(format!("ref check failed: {}", err["text"])));
}
Ok(res["result"]["value"].clone())
}
/// Clicks `key` (see [`Self::ref_check`]) after checking it. A control shown only on hover
/// gets the mouse over its card, a moment to show, and the check again: still hidden means
/// nothing is clicked. `what` names it in the error ("ref 3", "\"More\"").
async fn click_checked(&self, key: Value, what: &str) -> Result<String, BrowserError> {
let mut v = self.ref_check(&key).await?;
if let Some(h) = v.get("hover").filter(|h| h.is_object()).cloned() {
self.mouse_move(h["x"].as_i64().unwrap_or(0), h["y"].as_i64().unwrap_or(0)).await?;
tokio::time::sleep(HOVER_SETTLE).await;
v = self.ref_check(&key).await?;
if v.get("hover").is_some_and(Value::is_object) {
let card = h["card"].as_str().unwrap_or_default();
return Err(BrowserError::StaleRef(format!(
"Didn't click {what}: it stayed hidden after hovering over \"{card}\". The clickable list was read again just now; pick from the new list."
)));
}
}
if v["ok"].as_bool() != Some(true) {
let why = v["why"].as_str().unwrap_or("it can't be found");
return Err(BrowserError::StaleRef(format!(
"Didn't click {what}: {why}. The clickable list was read again just now; pick from the new list."
)));
}
let (x, y) = (v["x"].as_i64().unwrap_or(0), v["y"].as_i64().unwrap_or(0));
if v["hovered"].as_bool() == Some(true) {
// From the card onto the control, so the hover that shows it holds through the click
self.mouse_move(x, y).await?;
}
self.interact_click(x, y).await?;
tokio::time::sleep(Duration::from_millis(250)).await;
let _ = self.sync_location().await;
let _ = self.capture_screenshot().await;
Ok(v["label"].as_str().unwrap_or_default().to_string())
}
/// Moves the mouse to `x`, `y` (top-page pixels): what makes a page show what it shows on hover.
pub async fn mouse_move(&self, x: i64, y: i64) -> Result<(), BrowserError> {
self.send_cdp_command("Input.dispatchMouseEvent", json!({ "type": "mouseMoved", "x": x, "y": y })).await?;
Ok(())
}
/// Hovers `target` (a ref or a label, matched as a click would be; a control that shows on
/// hover is hovered through its card) and says what appeared: `Hovered over "Clip 1".
/// Appeared: More (button), Download (menuitem)`. Clicks nothing.
pub async fn hover_target(&self, target: &ClickTarget) -> Result<String, BrowserError> {
let arg = match target {
ClickTarget::Ref(r) => json!(r),
ClickTarget::Text(t) => json!(t),
};
let script = HOVER_JS.replace("__CLICKABLES__", CLICKABLES_JS).replace("__REF__", REF_JS);
let res = self
.send_cdp_command(
"Runtime.evaluate",
json!({ "expression": format!("({script})({arg})"), "returnByValue": true }),
)
.await?;
if let Some(err) = res.get("exceptionDetails") {
return Err(BrowserError::Protocol(format!("hover check failed: {}", err["text"])));
}
let v = &res["result"]["value"];
let what = match target {
ClickTarget::Ref(r) => format!("ref {r}"),
ClickTarget::Text(t) => format!("\"{t}\""),
};
if v["ok"].as_bool() != Some(true) {
let why = v["why"].as_str().unwrap_or("it can't be found");
return Err(BrowserError::StaleRef(format!(
"Didn't hover over {what}: {why}. The clickable list was read again just now; pick from the new list."
)));
}
self.mouse_move(v["x"].as_i64().unwrap_or(0), v["y"].as_i64().unwrap_or(0)).await?;
tokio::time::sleep(HOVER_SETTLE + Duration::from_millis(50)).await;
let res = self
.send_cdp_command(
"Runtime.evaluate",
json!({ "expression": format!("({})()", APPEARED_JS.replace("__CLICKABLES__", CLICKABLES_JS)), "returnByValue": true }),
)
.await?;
let appeared: Vec<String> = res["result"]["value"]
.as_array()
.map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_string)).collect())
.unwrap_or_default();
let _ = self.capture_screenshot().await;
let over = v["card"].as_str().or(v["label"].as_str()).unwrap_or_default();
Ok(hover_summary(over, &appeared))
}
/// Clicks `target`: a ref with [`Self::click_ref`], a label with [`Self::click_text`].
pub async fn click_target(&self, target: &ClickTarget) -> Result<String, BrowserError> {
match target {
ClickTarget::Ref(r) => self.click_ref(*r).await,
ClickTarget::Text(t) => self.click_text(t).await,
}
}
/// Clicks the visible element whose label best matches `text` (exact > prefix > contains,
/// topmost first). Returns the clicked label, or an error listing the available ones.
pub async fn click_text(&self, text: &str) -> Result<String, BrowserError> {
let needle = serde_json::to_string(text).map_err(|e| BrowserError::Protocol(e.to_string()))?;
let expression = format!("({})({})", CLICKABLES_JS, needle);
let res = self
.send_cdp_command(
"Runtime.evaluate",
json!({ "expression": expression, "returnByValue": true }),
)
.await?;
let value = &res["result"]["value"];
let Some(label) = value["match"]["label"].as_str().map(str::to_string) else {
let options: Vec<&str> = value["items"]
.as_array()
.map(|a| a.iter().filter_map(|i| i["label"].as_str()).take(25).collect())
.unwrap_or_default();
return Err(BrowserError::Protocol(format!(
"No clickable element matching \"{}\". Visible options: {}",
text,
options.join(" | ")
)));
};
if value["match"]["hover"].as_bool() == Some(true) {
// Shown only on hover: CLICKABLES_JS kept it as 'hovered' for the checked click
return self.click_checked(json!("hovered"), &format!("\"{label}\"")).await;
}
if value["match"]["clicked"].as_bool() == Some(true) {
tokio::time::sleep(Duration::from_millis(300)).await;
let _ = self.sync_location().await;
let _ = self.capture_screenshot().await;
} else {
let x = value["match"]["x"].as_i64().unwrap_or(0);
let y = value["match"]["y"].as_i64().unwrap_or(0);
self.interact_click(x, y).await?;
// Give navigations/animations triggered by the click a moment to settle
tokio::time::sleep(Duration::from_millis(250)).await;
let _ = self.sync_location().await;
let _ = self.capture_screenshot().await;
}
Ok(label)
}
pub async fn interact_click(&self, x: i64, y: i64) -> Result<String, BrowserError> {
self.send_cdp_command(
"Input.dispatchMouseEvent",
json!({
"type": "mousePressed",
"x": x,
"y": y,
"button": "left",
"clickCount": 1
}),
)
.await?;
self.send_cdp_command(
"Input.dispatchMouseEvent",
json!({
"type": "mouseReleased",
"x": x,
"y": y,
"button": "left",
"clickCount": 1
}),
)
.await?;
tokio::time::sleep(Duration::from_millis(150)).await;
let _ = self.collect_captured_credentials().await;
let _ = self.sync_location().await;
self.capture_screenshot().await
}
pub async fn interact_type(&self, text: &str) -> Result<String, BrowserError> {
self.send_cdp_command(
"Input.insertText",
json!({ "text": text }),
)
.await?;
tokio::time::sleep(Duration::from_millis(150)).await;
let _ = self.collect_captured_credentials().await;
let _ = self.sync_location().await;
self.capture_screenshot().await
}
pub async fn interact_key(&self, key: &str, code: Option<&str>) -> Result<String, BrowserError> {
let [down, up] = key_press_params(key, code)?;
self.send_cdp_command("Input.dispatchKeyEvent", down).await?;
self.send_cdp_command("Input.dispatchKeyEvent", up).await?;
tokio::time::sleep(Duration::from_millis(150)).await;
let _ = self.collect_captured_credentials().await;
let _ = self.sync_location().await;
self.capture_screenshot().await
}
pub async fn interact_scroll(&self, x: i64, y: i64, delta_x: f64, delta_y: f64) -> Result<String, BrowserError> {
self.send_cdp_command(
"Input.dispatchMouseEvent",
json!({
"type": "mouseWheel",
"x": x,
"y": y,
"deltaX": delta_x,
"deltaY": delta_y
}),
)
.await?;
tokio::time::sleep(Duration::from_millis(150)).await;
let _ = self.sync_location().await;
self.capture_screenshot().await
}
}
#[cfg(test)]
mod key_tests {
use super::{key_press_params, BrowserError};
fn down(key: &str, code: Option<&str>) -> serde_json::Value {
key_press_params(key, code).unwrap()[0].clone()
}
/// F-1 (0.8.0): a bot's Enter went out as a bare rawKeyDown with only key and code, so Chrome
/// fired keydown and never submitted the form. It's now the live view's event: keyDown with
/// "\r" and key code 13, then keyUp.
#[test]
fn enter_is_a_key_down_with_text_and_key_code() {
for code in [None, Some("Enter")] {
let [d, u] = key_press_params("Enter", code).unwrap();
assert_eq!(d["type"], "keyDown", "{d}");
assert_eq!(d["text"], "\r");
assert_eq!(d["unmodifiedText"], "\r");
assert_eq!(d["windowsVirtualKeyCode"], 13);
assert_eq!(d["code"], "Enter");
assert_eq!(u["type"], "keyUp");
assert_eq!(u["windowsVirtualKeyCode"], 13);
assert!(u.get("text").is_none(), "{u}");
}
assert_eq!(down("Return", None)["text"], "\r");
}
#[test]
fn keys_without_text_are_raw_with_their_key_code() {
for (key, vk) in [("Tab", 9), ("Escape", 27), ("Esc", 27), ("Backspace", 8), ("Delete", 46), ("ArrowLeft", 37), ("ArrowDown", 40), ("Home", 36), ("End", 35), ("PageDown", 34), ("F5", 116)] {
let d = down(key, None);
assert_eq!((d["type"].as_str(), d["windowsVirtualKeyCode"].as_u64()), (Some("rawKeyDown"), Some(vk)), "{key}: {d}");
assert!(d.get("text").is_none(), "{key}: {d}");
}
assert_eq!(down("Shift", None)["code"], "ShiftLeft");
}
#[test]
fn single_characters_type_with_their_code() {
for (key, code, vk, shift) in [
("a", "KeyA", 65, false),
("Z", "KeyZ", 90, true),
("7", "Digit7", 55, false),
("!", "Digit1", 49, true),
("/", "Slash", 191, false),
("?", "Slash", 191, true),
(" ", "Space", 32, false),
("Space", "Space", 32, false),
("Spacebar", "Space", 32, false),
] {
let d = down(key, None);
let text = if key.len() == 1 { key } else { " " };
assert_eq!(d["type"], "keyDown", "{key}: {d}");
assert_eq!(d["text"], text, "{key}: {d}");
assert_eq!(d["code"], code, "{key}");
assert_eq!(d["windowsVirtualKeyCode"], vk, "{key}");
assert_eq!(d["modifiers"], if shift { 8 } else { 0 }, "{key}");
}
}
#[test]
fn a_key_kwnt_cant_describe_is_refused_with_a_hint() {
for key in ["", "Control+a", "hello", "é", "Unidentified", "\u{7}"] {
match key_press_params(key, None) {
Err(e @ BrowserError::UnsupportedKey(_)) => assert!(e.to_string().contains("type it"), "{key}: {e}"),
other => panic!("{key:?}: {other:?}"),
}
}
// a code Chrome has no key number for is refused too, as in the live view
assert!(matches!(key_press_params("x", Some("NotAKey")), Err(BrowserError::UnsupportedKey(_))));
}
}
#[cfg(test)]
mod tests {
use super::cdp_ws_request;
fn host(url: &str) -> String {
cdp_ws_request(url).unwrap().headers()["host"].to_str().unwrap().to_string()
}
#[test]
fn cdp_ws_host_is_localhost_for_service_names() {
// Chrome answers 500 to a DevTools upgrade with Host: browser:9222
assert_eq!(host("ws://browser:9222/devtools/browser/x"), "localhost");
assert_eq!(host("ws://127.0.0.1:9223/devtools/page/x"), "127.0.0.1:9223");
assert_eq!(host("ws://[::1]:9222/devtools/page/x"), "[::1]:9222");
assert_eq!(host("ws://localhost:9222/devtools/page/x"), "localhost:9222");
assert_eq!(host("wss://cdp.example.com/devtools/browser/x"), "cdp.example.com");
}
}
#[cfg(test)]
mod agent_shot_tests {
use super::agent_shot_viewport;
#[test]
fn a_bots_screenshot_is_at_most_1280_wide_at_scale_1() {
assert_eq!(agent_shot_viewport(None, (1280, 800), 1.0), None);
assert_eq!(agent_shot_viewport(None, (1024, 700), 1.0), None);
assert_eq!(agent_shot_viewport(None, (1512, 860), 2.0), Some((1280, 860, false)));
assert_eq!(agent_shot_viewport(None, (1000, 700), 2.0), Some((1000, 700, false)));
assert_eq!(agent_shot_viewport(None, (1280, 4000), 1.0), Some((1280, 1600, false)));
assert_eq!(agent_shot_viewport(Some(390), (1280, 800), 1.0), Some((390, 844, true)));
assert_eq!(agent_shot_viewport(Some(1280), (1280, 800), 1.0), Some((1280, 800, false)));
assert_eq!(agent_shot_viewport(Some(10), (1280, 800), 1.0), Some((320, 844, true)));
assert_eq!(agent_shot_viewport(Some(9000), (1280, 800), 1.0), Some((1280, 800, false)));
}
}
#[cfg(test)]
mod ref_tests {
use super::{hover_summary, ref_line, ClickTarget, CLICKABLES_JS, PAYMENT_SIGNALS_JS, REF_JS};
use serde_json::json;
#[test]
fn a_click_aims_at_a_ref_or_a_label() {
let t = |a| ClickTarget::from_args(&a);
assert_eq!(t(json!({"ref": 3})), Some(ClickTarget::Ref(3)));
assert_eq!(t(json!({"ref": "7"})), Some(ClickTarget::Ref(7)));
assert_eq!(t(json!({"ref": "[7]", "text": "Login"})), Some(ClickTarget::Ref(7)), "ref wins over text");
assert_eq!(t(json!({"text": "[4] button \"Add to cart\" · Backpack"})), Some(ClickTarget::Ref(4)), "a whole copied line");
assert_eq!(t(json!({"text": "*[5] option \"Large\""})), Some(ClickTarget::Ref(5)), "a copied new line");
assert_eq!(t(json!({"ref": "*5"})), Some(ClickTarget::Ref(5)));
assert_eq!(t(json!({"text": "[1]"})), Some(ClickTarget::Text("[1]".into())), "a footnote link stays a label");
assert_eq!(t(json!({"text": " Login "})), Some(ClickTarget::Text("Login".into())));
assert_eq!(t(json!({"ref": 0, "text": "Login"})), Some(ClickTarget::Text("Login".into())));
assert_eq!(t(json!({"ref": -2})), None);
assert_eq!(t(json!({"ref": null, "text": " "})), None);
}
#[test]
fn a_ref_line_names_role_and_context_only_when_needed() {
let line = |v| ref_line(&v);
assert_eq!(line(json!({"ref": 3, "role": "button", "name": "Add to cart", "context": "Sauce Labs Backpack"})).as_deref(),
Some("[3] button \"Add to cart\" · Sauce Labs Backpack"));
assert_eq!(line(json!({"ref": 1, "role": "field", "name": "Username", "label": "Username (field)", "context": ""})).as_deref(),
Some("[1] field \"Username\""));
assert_eq!(line(json!({"ref": 2, "label": "Menu"})).as_deref(), Some("[2] button \"Menu\""));
assert_eq!(line(json!({"label": "No ref"})), None);
assert_eq!(line(json!({"ref": 12, "role": "option", "name": "Large", "new": true})).as_deref(), Some("*[12] option \"Large\""));
assert_eq!(line(json!({"ref": 12, "role": "option", "name": "Large", "new": false})).as_deref(), Some("[12] option \"Large\""));
}
/// A control that shows only on hover says so, with its card as the context; a copied line
/// of it is still that ref.
#[test]
fn a_hover_control_line_names_its_card() {
let l = ref_line(&json!({"ref": 7, "role": "button", "name": "More", "hover": true, "context": "Self-checkout"})).unwrap();
assert_eq!(l, "[7] button \"More\" (on hover) · Self-checkout");
assert_eq!(ClickTarget::from_args(&json!({"text": l})), Some(ClickTarget::Ref(7)));
let card = ref_line(&json!({"ref": 6, "role": "card", "name": "Self-checkout", "hover": false})).unwrap();
assert_eq!(card, "[6] card \"Self-checkout\"");
assert_eq!(ref_line(&json!({"ref": 6, "role": "card", "name": "Self-checkout", "hover": true, "new": true})).unwrap(),
"*[6] card \"Self-checkout\" (on hover)");
}
#[test]
fn a_hover_says_what_appeared() {
assert_eq!(hover_summary("Clip 1", &["More (button)".into(), "Download (menuitem)".into()]),
"Hovered over \"Clip 1\". Appeared: More (button), Download (menuitem)");
assert_eq!(hover_summary("More", &[]), "Hovered over \"More\". Nothing new appeared.");
}
/// The words icon-only controls get, and the caps on cards and hover controls, are the ones
/// the brief names (the real-Chrome test in tests/browser_hover_test.rs checks them on a page).
#[test]
fn icon_words_and_caps_are_the_named_ones() {
for pair in ["more_vert: 'More'", "more_horiz: 'More'", "download: 'Download'", "close: 'Close'",
"delete: 'Delete'", "edit: 'Edit'", "share: 'Share'"] {
assert!(CLICKABLES_JS.contains(pair), "{pair}");
}
assert!(CLICKABLES_JS.contains("var CARD_CAP = 40, HOVER_CAP = 40;"));
// display:none is never a hover control: it is dropped before the hover check
let none = CLICKABLES_JS.find("if (cs.display === 'none') continue;").unwrap();
assert!(none < CLICKABLES_JS.find("var hidden = cs.visibility === 'hidden'").unwrap());
}
/// The payment floor's script still embeds the click matcher and the ref check, and both still
/// hand it the label it judged before icon words were read (`old`).
#[test]
fn the_payment_check_judges_the_old_label() {
assert!(PAYMENT_SIGNALS_JS.contains("__CLICKABLES__") && PAYMENT_SIGNALS_JS.contains("__REF__"));
assert!(CLICKABLES_JS.contains("label: match.old || match.label, item: match"));
assert!(REF_JS.contains("if (probe === true) return item ? { el: item.el, label: item.old || item.label } : null;"));
}
}
#[cfg(test)]
mod view_claim_tests {
use super::{ViewClaim, ViewClaims, ViewRelease};
fn size(socket: u64, width: u32) -> ViewClaim { ViewClaim { socket, width, height: 700, dpr: 2.0 } }
#[test]
fn one_view_restores_when_it_lets_go() {
let mut claims = ViewClaims::default();
claims.claim(size(1, 390));
claims.claim(size(1, 412)); // a rotate replaces its own claim
assert_eq!(claims.release(1), ViewRelease::Restore);
assert!(claims.is_empty());
assert_eq!(claims.release(1), ViewRelease::Keep, "letting go twice changes nothing");
}
#[test]
fn a_view_without_a_size_changes_nothing() {
let mut claims = ViewClaims::default();
claims.claim(size(1, 390));
assert_eq!(claims.release(2), ViewRelease::Keep);
assert_eq!(claims.release(1), ViewRelease::Restore);
}
#[test]
fn last_resize_wins_and_restore_waits_for_the_last_view() {
// the desktop stage (1) then the phone overlay (2)
let mut claims = ViewClaims::default();
claims.claim(size(1, 1100));
claims.claim(size(2, 390));
// the phone closes: the desktop's size comes back, not 1280
assert_eq!(claims.release(2), ViewRelease::Reapply(size(1, 1100)));
assert_eq!(claims.release(1), ViewRelease::Restore);
}
#[test]
fn an_older_view_closing_leaves_the_newest_size_on_the_page() {
let mut claims = ViewClaims::default();
claims.claim(size(1, 1100));
claims.claim(size(2, 390));
assert_eq!(claims.release(1), ViewRelease::Keep);
assert_eq!(claims.release(2), ViewRelease::Restore);
}
#[test]
fn repeating_an_older_size_does_not_take_the_page_back() {
let mut claims = ViewClaims::default();
claims.claim(size(1, 1100));
assert!(!claims.repeats_older(&size(1, 1100)), "the newest view re-asking applies again (a navigation reset)");
claims.claim(size(2, 390));
assert!(claims.repeats_older(&size(1, 1100)));
assert!(!claims.repeats_older(&size(1, 1000)), "a new size wins");
assert!(!claims.repeats_older(&size(2, 390)));
assert!(!claims.repeats_older(&size(3, 1100)), "another view's size is not a repeat");
}
#[test]
fn a_view_that_resizes_again_becomes_the_newest() {
let mut claims = ViewClaims::default();
claims.claim(size(1, 1100));
claims.claim(size(2, 390));
claims.claim(size(1, 1000));
assert_eq!(claims.release(1), ViewRelease::Reapply(size(2, 390)));
assert_eq!(claims.release(2), ViewRelease::Restore);
}
}
#[cfg(test)]
mod sign_in_probe_tests {
use super::{sign_in_kind, SIGN_IN_PROBE_JS};
use serde_json::json;
#[test]
fn only_the_two_wall_kinds_count() {
assert_eq!(sign_in_kind(&json!("sign_in")), Some("sign_in"));
assert_eq!(sign_in_kind(&json!("two_factor")), Some("two_factor"));
assert_eq!(sign_in_kind(&json!(null)), None);
assert_eq!(sign_in_kind(&json!("captcha")), None);
assert_eq!(sign_in_kind(&json!({"kind": "sign_in"})), None);
// The probe looks only at visible fields, and a code field wins over a password field
assert!(SIGN_IN_PROBE_JS.contains("one-time-code"));
assert!(SIGN_IN_PROBE_JS.find("'two_factor'").unwrap() < SIGN_IN_PROBE_JS.find("'sign_in'").unwrap());
}
}
#[cfg(test)]
mod outage_tests {
use super::{outage, BrowserError, Outage};
#[test]
fn a_browser_that_does_not_answer_in_time_is_busy() {
assert_eq!(outage(&BrowserError::Timeout), Outage::Busy);
// a socket that broke mid-answer, or a /json request that failed some other way
assert_eq!(outage(&BrowserError::Ws("Connection reset without closing handshake".into())), Outage::Busy);
assert_eq!(outage(&BrowserError::Http("error sending request: connection closed before message completed".into())), Outage::Busy);
// Chrome dropped the page's socket before it answered
assert_eq!(outage(&BrowserError::Protocol("Connection closed before response".into())), Outage::Busy);
}
#[test]
fn nothing_at_the_address_is_unreachable() {
for text in [
"error sending request for url (http://127.0.0.1:9/json/version): client error (Connect): tcp connect error: Connection refused (os error 111)",
"error sending request: dns error: failed to lookup address information: Name or service not known",
"IO error: Connection refused (os error 111)",
] {
assert_eq!(outage(&BrowserError::Http(text.into())), Outage::Unreachable, "{text}");
assert_eq!(outage(&BrowserError::Ws(text.into())), Outage::Unreachable, "{text}");
}
assert_eq!(outage(&BrowserError::Protocol("docker: Cannot connect to the Docker daemon".into())), Outage::Unreachable);
}
#[test]
fn everything_else_is_neither() {
assert_eq!(outage(&BrowserError::Protocol("{\"code\":-32000,\"message\":\"No target with given id\"}".into())), Outage::Other);
assert_eq!(outage(&BrowserError::HumanControl), Outage::Other);
assert_eq!(outage(&BrowserError::Navigation("net::ERR_NAME_NOT_RESOLVED".into())), Outage::Other);
}
}