The headless browser for AI agents and web scraping
use std::collections::HashMap;
use obscura_browser::Page;
use obscura_dom::{DomTree, NodeData, NodeId};
use serde_json::{json, Value};
use crate::dispatch::CdpContext;
use crate::types::CdpEvent;
pub(crate) struct DomDocument {
pub page_id: String,
children_sent: HashMap<NodeId, bool>,
}
impl DomDocument {
fn remember(&mut self, root: &Value) {
let mut pending = vec![root];
while let Some(node) = pending.pop() {
if let Some(id) = node["nodeId"].as_u64().and_then(|id| u32::try_from(id).ok()) {
self.children_sent.insert(NodeId::new(id),
node["children"].is_array() || node["childNodeCount"] == 0);
}
if let Some(children) = node["children"].as_array() {
pending.extend(children);
}
}
}
}
fn node_id_param(params: &Value) -> Result<NodeId, String> {
params["nodeId"].as_u64().and_then(|id| u32::try_from(id).ok())
.map(NodeId::new).ok_or_else(|| "valid nodeId required".into())
}
// CDP DOM.querySelector* searches descendants of the requested node, not the
// whole document. Keep the historic omitted/zero nodeId fallback for clients
// that have not requested a DOM document yet.
fn query_root(dom: &DomTree, params: &Value) -> Result<NodeId, String> {
let Some(raw) = params.get("nodeId") else { return Ok(dom.document()) };
if raw.as_u64() == Some(0) { return Ok(dom.document()); }
let id = raw.as_u64().and_then(|id| u32::try_from(id).ok())
.map(NodeId::new).ok_or("Invalid nodeId")?;
if dom.get_node(id).is_none() { return Err("No node with given id found".into()); }
Ok(id)
}
fn annotate_frame_owners(page: &Page, parent_frame_id: u32, root: &mut Value) {
let Some(js) = page.js.as_ref() else { return };
let mut pending = vec![root];
while let Some(node) = pending.pop() {
if matches!(node["localName"].as_str(), Some("iframe" | "frame")) {
if let Some(frame) = node["backendNodeId"].as_u64()
.and_then(|id| u32::try_from(id).ok())
.and_then(|id| js.child_frame_for_node(parent_frame_id, NodeId::new(id)))
{
node["frameId"] = json!(super::page::child_frame_id(&page.frame_id, frame));
}
}
if let Some(children) = node.get_mut("children").and_then(Value::as_array_mut) {
pending.extend(children.iter_mut());
}
}
}
fn push_children(page: &Page, dom: &DomTree, state: &mut DomDocument, node: NodeId, depth: u32,
session_id: &Option<String>, events: &mut Vec<CdpEvent>) {
let mut pending = vec![(node, depth.min(MAX_SERIALIZE_DEPTH))];
while let Some((parent, depth)) = pending.pop() {
let Some(sent) = state.children_sent.get(&parent).copied() else { continue };
let children = dom.children(parent);
if !sent {
let mut nodes: Vec<_> = children.iter()
.map(|child| serialize_node(dom, *child, depth - 1, 0)).collect();
for node in &mut nodes { annotate_frame_owners(page, 0, node); }
for node in &nodes { state.remember(node); }
state.children_sent.insert(parent, true);
events.push(CdpEvent {
method: "DOM.setChildNodes".into(),
params: json!({"parentId":parent.index(), "nodes":nodes}),
session_id: session_id.clone(),
});
} else if depth > 1 {
pending.extend(children.into_iter().rev().map(|child| (child, depth - 1)));
}
}
}
fn push_node(ctx: &mut CdpContext, session_id: &Option<String>, node: NodeId) -> Result<u32, String> {
let Some(mut state) = ctx.dom_documents.remove(session_id) else { return Ok(0) };
let mut events = Vec::new();
let result = ctx.get_session_page(session_id).and_then(|page| page.with_dom(|dom| {
if dom.get_node(node).is_none() { return Err("No node with given id found".into()); }
if !state.children_sent.contains_key(&node) {
let path = dom.ancestors(node);
if path.last().copied() != Some(dom.document()) {
return Err("Node is outside the requested light-DOM document".into());
}
for parent in path.into_iter().rev() {
push_children(page, dom, &mut state, parent, 1, session_id, &mut events);
}
if !state.children_sent.contains_key(&node) {
// shortcut: refresh inserted children until live DOM mutation events publish them.
return Err("Node requires DOM mutation events; request the document again".into());
}
}
Ok(node.index() as u32)
})).unwrap_or_else(|| Err("No DOM loaded".into()));
ctx.dom_documents.insert(session_id.clone(), state);
ctx.pending_events.extend(events);
result
}
/// Resolve a DOM `nodeId` from CDP params. Honors `nodeId`, `backendNodeId`,
/// and `objectId` in that order. Playwright commonly passes only `objectId`
/// (returned by a prior `DOM.resolveNode`); without this fallback those
/// requests silently default to node 0 and click the wrong element.
fn resolve_node_id(page: &mut Page, params: &Value) -> Result<u64, String> {
if let Some(nid) = params.get("nodeId").and_then(|v| v.as_u64()) {
return Ok(nid);
}
if let Some(nid) = params.get("backendNodeId").and_then(|v| v.as_u64()) {
return Ok(nid);
}
if let Some(oid) = params.get("objectId").and_then(|v| v.as_str()) {
let code = format!(
"(function() {{ var o = globalThis.__obscura_objects && globalThis.__obscura_objects[{}]; \
return (o && typeof o._nid === 'number') ? o._nid : -1; }})()",
crate::util::object_id_literal(oid)
);
let result = page.evaluate(&code);
let nid = result.as_f64().map(|n| n as i64).unwrap_or(-1);
if nid < 0 {
return Err(format!("objectId {oid} could not be resolved to a node"));
}
return Ok(nid as u64);
}
Err("nodeId, backendNodeId, or objectId required".to_string())
}
async fn run_file_input_command(page: &mut Page, function: &str, object_id: Option<&str>,
specs: Value, validate_only: bool) -> Result<(), String> {
let specs = serde_json::to_string(&specs).map_err(|error| error.to_string())?;
let command = format!("function() {{ return ({function}).call(this, {specs}, {validate_only}); }}");
let result = page.call_function_on_for_cdp_with_timeout(&command, object_id,
&[], true, false, 30_000).await?;
if result.thrown {
return Err(format!("Could not set input files: {}", result.description));
}
match result.value.as_ref().and_then(Value::as_str) {
Some("ok") => Ok(()),
Some("missing") => Err("Could not find node with given id".into()),
Some("invalid") => Err("Node is not a file input element".into()),
_ => Err("Could not set files on the input element".into()),
}
}
/// Standard base64 (with padding). Used to ferry file bytes to the JS layer for
/// DOM.setFileInputFiles without pulling in a dependency.
fn encode_base64(input: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity((input.len() + 2) / 3 * 4);
for chunk in input.chunks(3) {
let b0 = chunk[0] as u32;
let b1 = *chunk.get(1).unwrap_or(&0) as u32;
let b2 = *chunk.get(2).unwrap_or(&0) as u32;
let n = (b0 << 16) | (b1 << 8) | b2;
out.push(T[((n >> 18) & 63) as usize] as char);
out.push(T[((n >> 12) & 63) as usize] as char);
out.push(if chunk.len() > 1 { T[((n >> 6) & 63) as usize] as char } else { '=' });
out.push(if chunk.len() > 2 { T[(n & 63) as usize] as char } else { '=' });
}
out
}
/// Best-effort MIME type from a file extension, for the File objects created by
/// DOM.setFileInputFiles. Defaults to application/octet-stream.
fn guess_mime(path: &str) -> &'static str {
let ext = std::path::Path::new(path)
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
match ext.as_str() {
"jpg" | "jpeg" => "image/jpeg",
"png" => "image/png",
"gif" => "image/gif",
"webp" => "image/webp",
"svg" => "image/svg+xml",
"bmp" => "image/bmp",
"ico" => "image/x-icon",
"pdf" => "application/pdf",
"txt" => "text/plain",
"html" | "htm" => "text/html",
"css" => "text/css",
"js" | "mjs" => "text/javascript",
"json" => "application/json",
"xml" => "application/xml",
"csv" => "text/csv",
"zip" => "application/zip",
"gz" => "application/gzip",
"mp4" => "video/mp4",
"webm" => "video/webm",
"mp3" => "audio/mpeg",
"wav" => "audio/wav",
"doc" => "application/msword",
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"xls" => "application/vnd.ms-excel",
"xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
_ => "application/octet-stream",
}
}
pub async fn handle(
method: &str,
params: &Value,
ctx: &mut CdpContext,
session_id: &Option<String>,
) -> Result<Value, String> {
match method {
"enable" => Ok(json!({})),
"disable" => {
ctx.dom_documents.remove(session_id);
Ok(json!({}))
}
"getDocument" => {
let page = ctx.get_session_page(session_id).ok_or("No page")?;
let depth = params.get("depth").and_then(|v| v.as_i64()).unwrap_or(2);
let mut root = page.with_dom(|dom| serialize_node(dom, dom.document(), depth as u32, 0))
.ok_or("No DOM loaded")?;
annotate_frame_owners(page, 0, &mut root);
let mut state = DomDocument { page_id: page.id.clone(), children_sent: HashMap::new() };
state.remember(&root);
ctx.dom_documents.insert(session_id.clone(), state);
Ok(json!({"root":root}))
}
"getAttributes" => {
let node_id = node_id_param(params)?;
let page = ctx.get_session_page(session_id).ok_or("No page")?;
let attributes = page.with_dom(|dom| {
let node = dom.get_node(node_id).ok_or("No node with given id found")?;
let attrs = node.attrs().ok_or("Node is not an Element")?;
Ok::<_, &str>(attrs.iter().flat_map(|attr| [attr.qualified_name(), attr.value.clone()]).collect::<Vec<_>>())
}).ok_or("No DOM loaded")?.map_err(str::to_string)?;
Ok(json!({"attributes":attributes}))
}
"requestChildNodes" => {
let node = node_id_param(params)?;
let depth = match params.get("depth") {
None => 1,
Some(value) => match value.as_i64() {
Some(-1) => u32::MAX,
Some(value) if value > 0 => u32::try_from(value).unwrap_or(u32::MAX),
_ => return Err("depth must be positive or -1".into()),
},
};
if params["pierce"].as_bool() == Some(true) {
let page = ctx.get_session_page(session_id).ok_or("No page")?;
let needs_piercing = page.with_dom(|dom| {
let mut pending = vec![(node, depth.min(MAX_SERIALIZE_DEPTH))];
while let Some((id, remaining)) = pending.pop() {
if dom.shadow_root(id).is_some() || dom.get_node(id).is_some_and(|node|
node.as_element().is_some_and(|name| name.ns.as_ref() == "http://www.w3.org/1999/xhtml"
&& matches!(name.local.as_ref(), "iframe" | "frame"))) {
return true;
}
if remaining > 0 {
pending.extend(dom.children(id).into_iter().map(|child| (child, remaining - 1)));
}
}
false
}).unwrap_or(false);
if needs_piercing {
return Err("Piercing frame and shadow trees is not supported".into());
}
}
if let Some(mut state) = ctx.dom_documents.remove(session_id) {
let mut events = Vec::new();
if let Some(page) = ctx.get_session_page(session_id) {
page.with_dom(|dom| push_children(page, dom, &mut state, node, depth, session_id, &mut events));
}
ctx.dom_documents.insert(session_id.clone(), state);
ctx.pending_events.extend(events);
}
Ok(json!({}))
}
"requestNode" => {
let oid = params["objectId"].as_str().ok_or("objectId required")?;
let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
let code = format!(
"(function() {{ var o = globalThis.__obscura_objects && globalThis.__obscura_objects[{}]; \
return o instanceof Node && (o === document || o.ownerDocument === document) ? o._nid : -1; }})()",
crate::util::object_id_literal(oid)
);
let id = page.evaluate(&code).as_f64().filter(|id|
id.is_finite() && *id >= 0.0 && *id <= u32::MAX as f64 && id.fract() == 0.0)
.ok_or("Object id does not reference a Node in this document")? as u32;
Ok(json!({"nodeId":push_node(ctx, session_id, NodeId::new(id))?}))
}
"getNodeForLocation" => {
let x = params["x"].as_i64().ok_or("integer x required")?;
let y = params["y"].as_i64().ok_or("integer y required")?;
if params["ignorePointerEventsNone"].as_bool() == Some(true) {
return Err("Ignoring pointer-events in hit testing is not supported".into());
}
let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
let frame = page.frame_id.clone();
let id = page.evaluate(&format!(
"(function() {{ var node = document.elementFromPoint({x},{y}); return node ? node._nid : -1; }})()"
)).as_f64().filter(|id| *id >= 0.0 && *id <= u32::MAX as f64)
.ok_or("No node found at given location")? as u32;
let mut result = json!({"backendNodeId":id,"frameId":frame});
if ctx.dom_documents.contains_key(session_id) {
result["nodeId"] = json!(push_node(ctx, session_id, NodeId::new(id))?);
}
Ok(result)
}
"querySelector" => {
let page = ctx.get_session_page(session_id).ok_or("No page")?;
let selector = params.get("selector").and_then(|v| v.as_str()).ok_or("selector required")?;
let result = page.with_dom(|dom| {
dom.query_selector_from(query_root(dom, params)?, selector)
}).ok_or("No DOM loaded")??;
Ok(json!({ "nodeId": result.map(|id| id.index()).unwrap_or(0) }))
}
"querySelectorAll" => {
let page = ctx.get_session_page(session_id).ok_or("No page")?;
let selector = params.get("selector").and_then(|v| v.as_str()).ok_or("selector required")?;
let ids = page.with_dom(|dom| {
dom.query_selector_all_from(query_root(dom, params)?, selector)
}).ok_or("No DOM loaded")??;
Ok(json!({ "nodeIds": ids.iter().map(|id| id.index()).collect::<Vec<_>>() }))
}
"getOuterHTML" => {
// go-rod asks for the HTML of an element handle it already holds and
// sends `objectId` only (rod/element.go DOMGetOuterHTML). Chromium
// accepts all three identifiers here; accepting nodeId alone made
// every rod page.HTML() fail with "nodeId required".
let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
if params["nodeId"].as_u64().is_none() && params["backendNodeId"].as_u64().is_none() {
if let Some(object_id) = params["objectId"].as_str() {
let html = page.js.as_mut().ok_or("No JS runtime")?
.with_remote_dom_node(object_id, |dom, node_id, _, _, _| dom.outer_html(node_id))?;
return Ok(json!({"outerHTML":html}));
}
}
let node_id = resolve_node_id(page, params)?;
let html = page.with_dom(|dom| {
dom.outer_html(NodeId::new(node_id as u32))
}).unwrap_or_default();
Ok(json!({ "outerHTML": html }))
}
"describeNode" => {
let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
let depth = params.get("depth").and_then(|v| v.as_i64()).unwrap_or(0);
if params["nodeId"].as_u64().is_none() && params["backendNodeId"].as_u64().is_none() {
if let Some(object_id) = params["objectId"].as_str() {
let page_frame_id = page.frame_id.clone();
let (mut node, owner_frame_id) = page.js.as_mut().ok_or("No JS runtime")?
.with_remote_dom_node(object_id, |dom, node_id, frame_id, url, base| {
let mut node = serialize_node(dom, node_id, depth as u32, 0);
let document_element = dom.children(dom.document()).into_iter().find(|id| {
dom.with_node(*id, |node| matches!(node.data, NodeData::Element { .. }))
== Some(true)
}).map(|id| id.index() as u64);
let protocol_frame = if frame_id == 0 { page_frame_id.clone() }
else { super::page::child_frame_id(&page_frame_id, frame_id) };
let mut pending = vec![&mut node];
while let Some(node) = pending.pop() {
if node["nodeType"] == 9 {
node["documentURL"] = json!(url);
node["baseURL"] = json!(base);
}
if document_element.is_some() && node["backendNodeId"].as_u64() == document_element {
node["frameId"] = json!(protocol_frame);
}
if let Some(children) = node["children"].as_array_mut() {
pending.extend(children.iter_mut());
}
}
(node, frame_id)
})?;
annotate_frame_owners(page, owner_frame_id, &mut node);
return Ok(json!({"node":node}));
}
}
let node_id = if let Some(nid) = params.get("nodeId").and_then(|v| v.as_u64())
.or_else(|| params.get("backendNodeId").and_then(|v| v.as_u64()))
{
nid
} else if let Some(oid) = params.get("objectId").and_then(|v| v.as_str()) {
let code = format!(
"(function() {{ var o = globalThis.__obscura_objects[{}]; if (!o) return -1; return (typeof o._nid === 'number') ? o._nid : -1; }})()",
crate::util::object_id_literal(oid)
);
let result = page.evaluate(&code);
// JS returns -1 for an unresolvable object; `-1.0 as u64` would
// saturate to 0 (the document root), so check before casting.
let nid = result.as_f64().map(|n| n as i64).unwrap_or(-1);
if nid < 0 {
return Err(format!("objectId {oid} could not be resolved to a node"));
}
nid as u64
} else {
return Err("nodeId or objectId required".to_string());
};
let mut node = page.with_dom(|dom| {
serialize_node(dom, NodeId::new(node_id as u32), depth as u32, 0)
}).unwrap_or(json!(null));
annotate_frame_owners(page, 0, &mut node);
Ok(json!({ "node": node }))
}
"resolveNode" => {
let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
let node_id = if let Some(nid) = params.get("nodeId").and_then(|v| v.as_u64())
.or_else(|| params.get("backendNodeId").and_then(|v| v.as_u64()))
{
nid
} else if let Some(oid) = params.get("objectId").and_then(|v| v.as_str()) {
let code = format!(
"(function() {{ var o = globalThis.__obscura_objects[{}]; return (o && typeof o._nid === 'number') ? o._nid : -1; }})()",
crate::util::object_id_literal(oid)
);
let result = page.evaluate(&code);
// JS returns -1 for an unresolvable object; `-1.0 as u64` would
// saturate to 0 (the document root), so check before casting.
let nid = result.as_f64().map(|n| n as i64).unwrap_or(-1);
if nid < 0 {
return Err(format!("objectId {oid} could not be resolved to a node"));
}
nid as u64
} else {
return Err("nodeId or objectId required".to_string());
};
let js_code = format!("globalThis._wrap({node_id})");
let info = if let Some(js) = &mut page.js {
match js.store_object_with_meta(&js_code) {
Ok(info) => info,
Err(_) => {
return Ok(json!({
"object": {
"type": "object",
"subtype": "node",
"className": "HTMLElement",
"objectId": format!("node-{}", node_id),
}
}));
}
}
} else {
return Err("No JS runtime".to_string());
};
Ok(json!({
"object": {
"type": "object",
"subtype": "node",
"className": if info.class_name.is_empty() { "HTMLElement".to_string() } else { info.class_name },
"description": info.description,
"objectId": info.object_id.unwrap_or_else(|| format!("node-{}", node_id)),
}
}))
}
"setAttributeValue" => Ok(json!({})),
"removeNode" => Ok(json!({})),
"focus" => {
// No layout engine, but obscura's JS focus() sets document.activeElement,
// which Input.dispatchKeyEvent targets. CDP clients (browser-use) focus an
// input via DOM.focus before typing; without this their keystrokes land on
// nothing and the field stays empty.
let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
let node_id = resolve_node_id(page, params)?;
let code = format!(
"(function() {{ var el = globalThis._wrap && globalThis._wrap({0}); \
if (el && typeof el.focus === 'function') {{ el.focus(); return true; }} return false; }})()",
node_id
);
let _ = page.evaluate(&code);
Ok(json!({}))
}
"scrollIntoViewIfNeeded" => {
let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
let node_id = resolve_node_id(page, params)?;
// Share the DOM shim's nested-scrollport handling. Fully visible
// boxes stay put; clipped boxes are centered only where needed.
let code = format!(
"(function() {{ var el = globalThis._wrap && globalThis._wrap({0}); \
if (!el || typeof el.scrollIntoViewIfNeeded !== 'function') return false; \
el.scrollIntoViewIfNeeded(); return true; }})()",
node_id
);
let did_scroll = page.evaluate(&code).as_bool().unwrap_or(false);
if !did_scroll {
return Err(format!(
"node {node_id} could not be resolved to a scrollable element"
));
}
Ok(json!({}))
}
"setFileInputFiles" => {
// Puppeteer's ElementHandle.uploadFile / Playwright's setInputFiles
// drive an <input type=file> through this CDP call (issue #359). Read
// each local file, then hand its bytes (base64) to the JS layer, which
// builds real File objects and fires input+change like a real
// selection so page code can read/upload them.
let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
// setFileInputFiles reads local files and hands their bytes to page
// JS. Anyone who can reach the CDP port (default localhost, but
// Docker images bind 0.0.0.0) could otherwise read any file the
// process can read — the same threat as Page.navigate to file://, so
// it honours the same opt-in and is off by default.
if !page.context.allow_file_access {
return Err("DOM.setFileInputFiles is disabled. Restart with `obscura serve --allow-file-access` to enable local file uploads.".to_string());
}
let files = params.get("files").and_then(Value::as_array)
.ok_or("DOM.setFileInputFiles requires a files array")?;
let paths: Vec<&str> = files.iter().map(|file| file.as_str()
.ok_or_else(|| "DOM.setFileInputFiles requires string file paths".to_string()))
.collect::<Result<_, _>>()?;
// Keep remote handles intact: a child-frame node's numeric id
// belongs to its own DOM, not the page's root DOM.
let (object_id, receiver) = if params.get("nodeId").is_some()
|| params.get("backendNodeId").is_some() {
let node_id = params.get("nodeId").or_else(|| params.get("backendNodeId"))
.and_then(Value::as_u64).ok_or("valid nodeId or backendNodeId required")?;
let exists = u32::try_from(node_id).ok().and_then(|id| {
page.with_dom(|dom| dom.get_node(NodeId::new(id)).is_some())
}).unwrap_or(false);
if !exists { return Err("Could not find node with given id".into()); }
(None, format!("globalThis._wrap({node_id})"))
} else {
let object_id = params.get("objectId").and_then(Value::as_str)
.ok_or("nodeId, backendNodeId, or objectId required")?;
(Some(object_id), "this".to_string())
};
let function = format!(
"function(specs, validateOnly) {{\
var el = {receiver};\
if (!el || !el.nodeType) return 'missing';\
var owner = el.ownerDocument && el.ownerDocument.defaultView || globalThis;\
if (typeof owner.__obscura_setInputFiles !== 'function')\
throw new Error('File input helper unavailable');\
return owner.__obscura_setInputFiles(el, specs, validateOnly) === true\
? 'ok' : (validateOnly ? 'invalid' : 'failed');\
}}"
);
run_file_input_command(page, &function, object_id, json!([]), true).await?;
let mut specs = Vec::with_capacity(paths.len());
for p in &paths {
let bytes = std::fs::read(p)
.map_err(|e| format!("setFileInputFiles: cannot read '{}': {}", p, e))?;
let name = std::path::Path::new(p)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("file")
.to_string();
specs.push(json!({ "name": name, "type": guess_mime(p), "b64": encode_base64(&bytes) }));
}
run_file_input_command(page, &function, object_id, json!(specs), false).await?;
Ok(json!({}))
}
"getBoxModel" => {
let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
let node_id = match resolve_node_id(page, params) {
Ok(nid) => nid,
Err(_) => return Ok(json!(null)),
};
let code = format!(
"(function() {{\
var el = globalThis._wrap && globalThis._wrap({0});\
if (!el || typeof el.getBoundingClientRect !== 'function') return null;\
var r = el.getBoundingClientRect();\
return [r.left, r.top, r.right, r.top, r.right, r.bottom, r.left, r.bottom,\
r.width, r.height];\
}})()",
node_id
);
let val = page.evaluate(&code);
let (quad, w, h) = if let Some(arr) = val.as_array() {
let nums: Vec<f64> = arr.iter().filter_map(|v| v.as_f64()).collect();
if nums.len() >= 10 {
let q: Vec<Value> = nums[..8].iter().map(|n| coord_value(*n)).collect();
(q, nums[8], nums[9])
} else {
(vec![json!(8),json!(8),json!(108),json!(8),json!(108),json!(28),json!(8),json!(28)], 100.0, 20.0)
}
} else {
(vec![json!(8),json!(8),json!(108),json!(8),json!(108),json!(28),json!(8),json!(28)], 100.0, 20.0)
};
Ok(json!({
"model": {
"content": quad.clone(),
"padding": quad.clone(),
"border": quad.clone(),
"margin": quad,
"width": coord_value(w), "height": coord_value(h),
}
}))
}
"getContentQuads" => {
let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
let node_id = match resolve_node_id(page, params) {
Ok(nid) => nid,
Err(_) => return Ok(json!(null)),
};
let code = format!(
"(function() {{\
var el = globalThis._wrap && globalThis._wrap({0});\
if (!el || typeof el.getBoundingClientRect !== 'function') return null;\
var r = el.getBoundingClientRect();\
return [r.left, r.top, r.right, r.top, r.right, r.bottom, r.left, r.bottom];\
}})()",
node_id
);
let val = page.evaluate(&code);
let quad = if let Some(arr) = val.as_array() {
let nums: Vec<f64> = arr.iter().filter_map(|v| v.as_f64()).collect();
if nums.len() == 8 { nums.iter().map(|n| coord_value(*n)).collect::<Vec<_>>() }
else { vec![json!(8),json!(8),json!(108),json!(8),json!(108),json!(28),json!(8),json!(28)] }
} else {
vec![json!(8),json!(8),json!(108),json!(8),json!(108),json!(28),json!(8),json!(28)]
};
Ok(json!({ "quads": [quad] }))
}
_ => Err(format!("Unknown DOM method: {}", method)),
}
}
/// Serialize a CDP box-model coordinate the way Chrome does: an integral double
/// (e.g. `256.0`) becomes a JSON integer (`256`), while a genuinely fractional
/// value (`206.0390625`) stays a float. serde_json always writes an `f64` with a
/// decimal point, so `json!(256.0)` yields `256.0` — which strict CDP clients
/// (Hermes Agent) deserialize as `i64` and reject, breaking every click-by-
/// coordinate flow. Chrome only widens fractional coordinates, so mirroring that
/// keeps those clients working. (issue #576)
fn coord_value(n: f64) -> Value {
// Collapse to an integer only when the value is exactly integral and fits an
// i64 losslessly; NaN/inf and out-of-range doubles fall through unchanged.
if n.is_finite() && n.fract() == 0.0 && n >= i64::MIN as f64 && n <= i64::MAX as f64 {
json!(n as i64)
} else {
json!(n)
}
}
// Hard cap on how deep a getDocument/describeNode response may nest, independent
// of the requested `depth`. DOM.getDocument{depth:-1} arrives here as u32::MAX,
// which on a pathologically deep DOM (trivially scriptable, unbounded by
// html5ever) produces a Value nested that far. Even built without recursion,
// serde_json's own serialization and the Value's Drop recurse over that nesting
// and overflow the stack — on tokio's ~2 MiB worker stacks especially. Bounding
// the depth keeps the response safe to serialize and drop. Real DOMs are shallow
// (deep React trees are a few hundred), so this only truncates pathological
// nesting, which beats crashing the worker (AGENTS.md: "one page must never
// crash a worker"). Mirrors DOMSnapshot's MAX_NODES guard (issue #341).
//
// The number is sized for the ~2 MiB stack of a tokio worker thread (where the
// CDP processor runs, and where `#[test]` threads also run): each DOM level
// becomes two nested JSON containers (object -> "children" array -> object ...),
// so serde_json's recursive serialization and the Value's recursive Drop descend
// ~2x this depth. 256 keeps that a few hundred frames deep with wide margin,
// while still far exceeding any real page. Clients needing a deeper subtree
// re-request it with DOM.requestChildNodes / describeNode on a specific node.
const MAX_SERIALIZE_DEPTH: u32 = 256;
/// Build the CDP Node object for a single node (without its `children` array),
/// returning it together with that node's child ids. `None` for a missing node.
fn node_value(dom: &DomTree, node_id: NodeId) -> Option<(Value, Vec<NodeId>)> {
let node = dom.get_node(node_id)?;
let children_ids = dom.children(node_id);
let child_count = children_ids.len();
let mut result = json!({ "nodeId": node_id.index(), "backendNodeId": node_id.index(), "childNodeCount": child_count });
match &node.data {
NodeData::Document => {
result["nodeType"] = json!(9); result["nodeName"] = json!("#document");
result["localName"] = json!(""); result["nodeValue"] = json!("");
result["documentURL"] = json!(""); result["baseURL"] = json!(""); result["xmlVersion"] = json!("");
}
NodeData::Doctype { name, public_id, system_id } => {
result["nodeType"] = json!(10); result["nodeName"] = json!(name);
result["localName"] = json!(""); result["nodeValue"] = json!("");
result["publicId"] = json!(public_id); result["systemId"] = json!(system_id);
}
NodeData::Element { name, attrs, .. } => {
result["nodeType"] = json!(1);
result["nodeName"] = json!(name.local.as_ref().to_ascii_uppercase());
result["localName"] = json!(name.local.as_ref());
result["nodeValue"] = json!("");
let cdp_attrs: Vec<String> = attrs.iter()
.flat_map(|a| [a.qualified_name(), a.value.clone()]).collect();
result["attributes"] = json!(cdp_attrs);
}
NodeData::Text { contents } => {
result["nodeType"] = json!(3); result["nodeName"] = json!("#text");
result["localName"] = json!(""); result["nodeValue"] = json!(contents);
}
NodeData::Comment { contents } => {
result["nodeType"] = json!(8); result["nodeName"] = json!("#comment");
result["localName"] = json!(""); result["nodeValue"] = json!(contents);
}
NodeData::ProcessingInstruction { target, data } => {
result["nodeType"] = json!(7); result["nodeName"] = json!(target);
result["localName"] = json!(""); result["nodeValue"] = json!(data);
}
}
Some((result, children_ids))
}
/// Serialize a node and its descendants into the CDP Node tree, iteratively.
/// The requested `max_depth` is clamped to `current_depth + MAX_SERIALIZE_DEPTH`
/// so a `depth:-1` (u32::MAX) request on a very deep DOM cannot produce a Value
/// that overflows the stack when serde_json later serializes or drops it. An
/// explicit heap worklist keeps the builder itself off the call stack.
fn serialize_node(dom: &DomTree, node_id: NodeId, max_depth: u32, current_depth: u32) -> Value {
let max_depth = max_depth.min(current_depth.saturating_add(MAX_SERIALIZE_DEPTH));
struct Frame {
value: Value,
children: Vec<NodeId>,
next: usize,
built: Vec<Value>,
depth: u32,
expand: bool,
}
let (root_value, root_children) = match node_value(dom, node_id) {
Some(v) => v,
None => return json!(null),
};
let root_expand = current_depth < max_depth && !root_children.is_empty();
let mut stack = vec![Frame {
value: root_value,
children: root_children,
next: 0,
built: Vec::new(),
depth: current_depth,
expand: root_expand,
}];
loop {
// Decide the next step without holding a borrow across a push.
let next_child = {
let top = stack.last_mut().expect("stack is non-empty in loop");
if top.expand && top.next < top.children.len() {
let cid = top.children[top.next];
top.next += 1;
Some(cid)
} else {
None
}
};
match next_child {
Some(cid) => {
let child_depth = stack.last().unwrap().depth + 1;
match node_value(dom, cid) {
Some((cval, cchildren)) => {
let cexpand = child_depth < max_depth && !cchildren.is_empty();
stack.push(Frame {
value: cval,
children: cchildren,
next: 0,
built: Vec::new(),
depth: child_depth,
expand: cexpand,
});
}
// Missing child: match the old recursive behavior of emitting null.
None => stack.last_mut().unwrap().built.push(json!(null)),
}
}
None => {
// This node's children are all built; finalize and fold into parent.
let mut frame = stack.pop().unwrap();
if !frame.built.is_empty() {
frame.value["children"] = json!(frame.built);
}
match stack.last_mut() {
Some(parent) => parent.built.push(frame.value),
None => return frame.value,
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dispatch::CdpContext;
#[tokio::test(flavor = "current_thread")]
async fn dom_node_tracking_is_released_on_navigation_detach_and_close() {
let mut ctx = CdpContext::new();
let page = ctx.create_page();
let session = Some(format!("{page}-session"));
ctx.sessions.insert(session.clone().unwrap(), page.clone());
crate::domains::page::handle("navigate", &json!({"url":"data:text/html,<p>first</p>"}),
&mut ctx, &session).await.unwrap();
handle("getDocument", &json!({"depth":-1}), &mut ctx, &session).await.unwrap();
ctx.pending_events.clear();
crate::domains::page::handle("navigate", &json!({"url":"data:text/html,<p>second</p>"}),
&mut ctx, &session).await.unwrap();
assert!(ctx.dom_documents.is_empty(), "navigation must release the old node cache");
assert!(ctx.pending_events.iter().any(|event| event.method == "DOM.documentUpdated"
&& event.session_id == session));
handle("getDocument", &json!({}), &mut ctx, &session).await.unwrap();
crate::domains::target::handle("detachFromTarget", &json!({"sessionId":session}),
&mut ctx, &None).await.unwrap();
assert!(ctx.dom_documents.is_empty(), "detach must release session-owned nodes");
let closing_session = Some("closing".to_string());
ctx.sessions.insert(closing_session.clone().unwrap(), page.clone());
handle("getDocument", &json!({}), &mut ctx, &closing_session).await.unwrap();
assert_eq!(ctx.dom_documents.len(), 1);
ctx.remove_page(&page);
assert!(ctx.dom_documents.is_empty(), "close must release the target's node cache");
}
// The escaping this file used to own now lives in `util::object_id_literal`,
// which is where its tests went with it: the three lookup sites here embed
// the id as a JSON literal rather than splicing it into a single-quoted
// string, so there is no per-domain escaping left to assert on.
// A stale/invalid objectId resolves to -1 in JS. describeNode/resolveNode
// must surface an error, not cast -1 to nodeId 0 (the document root) and
// return the wrong node. See #917.
#[tokio::test]
async fn describe_node_errors_on_unresolvable_object_id() {
let mut ctx = CdpContext::new();
let page_id = ctx.create_page();
let session = Some(format!("{page_id}-session"));
ctx.sessions.insert(session.clone().unwrap(), page_id.clone());
crate::domains::page::handle(
"navigate",
&json!({ "url": "data:text/html,<p>hi</p>", "waitUntil": "load" }),
&mut ctx,
&session,
)
.await
.expect("navigate should succeed");
let res = handle(
"describeNode",
&json!({ "objectId": "no-such-object" }),
&mut ctx,
&session,
)
.await;
assert!(
res.is_err(),
"describeNode must error on an unresolvable objectId, got: {res:?}"
);
}
#[tokio::test]
async fn resolve_node_errors_on_unresolvable_object_id() {
let mut ctx = CdpContext::new();
let page_id = ctx.create_page();
let session = Some(format!("{page_id}-session"));
ctx.sessions.insert(session.clone().unwrap(), page_id.clone());
crate::domains::page::handle(
"navigate",
&json!({ "url": "data:text/html,<p>hi</p>", "waitUntil": "load" }),
&mut ctx,
&session,
)
.await
.expect("navigate should succeed");
let res = handle(
"resolveNode",
&json!({ "objectId": "no-such-object" }),
&mut ctx,
&session,
)
.await;
assert!(
res.is_err(),
"resolveNode must error on an unresolvable objectId, got: {res:?}"
);
}
#[tokio::test]
async fn dom_focus_sets_active_element() {
// CDP clients (browser-use) focus an input via DOM.focus before typing;
// dispatchKeyEvent then targets document.activeElement. DOM.focus must
// actually move focus or keystrokes land on nothing.
let mut ctx = CdpContext::new();
let page_id = ctx.create_page();
let session = Some(format!("{page_id}-session"));
ctx.sessions.insert(session.clone().unwrap(), page_id.clone());
crate::domains::page::handle(
"navigate",
&json!({ "url": "data:text/html,<input id=q>", "waitUntil": "load" }),
&mut ctx,
&session,
)
.await
.expect("navigate should succeed");
let qs = handle("querySelector", &json!({ "selector": "input" }), &mut ctx, &session)
.await
.expect("querySelector should succeed");
let nid = qs["nodeId"].as_u64().expect("input nodeId");
assert!(nid > 0, "the input element should be found");
handle("focus", &json!({ "nodeId": nid }), &mut ctx, &session)
.await
.expect("DOM.focus should succeed");
let active = ctx
.get_session_page_mut(&session)
.unwrap()
.evaluate("(function(){return document.activeElement?document.activeElement.tagName:'NONE';})()");
assert_eq!(
active,
json!("INPUT"),
"DOM.focus must set document.activeElement to the focused input"
);
}
#[tokio::test(flavor = "current_thread")]
async fn resolve_node_preserves_identity_and_specialized_wrappers() {
let mut ctx = CdpContext::new();
let page_id = ctx.create_page();
let session = Some(format!("{page_id}-session"));
ctx.sessions.insert(session.clone().unwrap(), page_id);
crate::domains::page::handle("navigate", &json!({
"url": "data:text/html,<html><body><textarea id=field></textarea><a id=link href=https://example.com>Next</a></body></html>"
}), &mut ctx, &session).await.unwrap();
for (id, constructor) in [
("field", "HTMLTextAreaElement"),
("link", "HTMLAnchorElement"),
] {
let selector = format!("#{id}");
let query = handle(
"querySelector",
&json!({"selector": selector}),
&mut ctx,
&session,
)
.await
.unwrap();
let resolved = handle(
"resolveNode",
&json!({"backendNodeId": query["nodeId"]}),
&mut ctx,
&session,
)
.await
.unwrap();
let object_id = resolved["object"]["objectId"].as_str().unwrap();
let expression = format!(
"(() => {{ const node = globalThis.__obscura_objects[{}]; return node === document.getElementById({}) && node instanceof {}; }})()",
serde_json::to_string(object_id).unwrap(),
serde_json::to_string(id).unwrap(),
constructor
);
assert_eq!(
ctx.get_session_page_mut(&session)
.unwrap()
.evaluate(&expression),
json!(true)
);
}
let document = handle("getDocument", &json!({}), &mut ctx, &session)
.await
.unwrap();
let resolved = handle(
"resolveNode",
&json!({"nodeId": document["root"]["nodeId"]}),
&mut ctx,
&session,
)
.await
.unwrap();
let object_id = resolved["object"]["objectId"].as_str().unwrap();
let expression = format!(
"globalThis.__obscura_objects[{}] === document",
serde_json::to_string(object_id).unwrap()
);
assert_eq!(
ctx.get_session_page_mut(&session)
.unwrap()
.evaluate(&expression),
json!(true)
);
}
#[tokio::test(flavor = "current_thread")]
async fn scroll_into_view_if_needed_resolves_all_node_identifiers() {
let mut ctx = CdpContext::new();
let page_id = ctx.create_page();
let session = Some(format!("{page_id}-session"));
ctx.sessions.insert(session.clone().unwrap(), page_id);
crate::domains::page::handle(
"navigate",
&json!({
"url": "data:text/html,<main><button id=target>Go</button></main>",
"waitUntil": "load"
}),
&mut ctx,
&session,
)
.await
.expect("navigate should succeed");
let query = handle(
"querySelector",
&json!({ "selector": "#target" }),
&mut ctx,
&session,
)
.await
.expect("querySelector should succeed");
let node_id = query["nodeId"].as_u64().expect("button nodeId");
let resolved = handle(
"resolveNode",
&json!({ "nodeId": node_id }),
&mut ctx,
&session,
)
.await
.expect("resolveNode should succeed");
let object_id = resolved["object"]["objectId"]
.as_str()
.expect("button objectId")
.to_string();
for params in [
json!({ "nodeId": node_id }),
json!({ "backendNodeId": node_id }),
json!({ "objectId": object_id }),
] {
ctx.get_session_page_mut(&session)
.unwrap()
.evaluate("globalThis.__obscura_click_target = null");
handle("scrollIntoViewIfNeeded", ¶ms, &mut ctx, &session)
.await
.expect("scrollIntoViewIfNeeded should succeed");
let target_id = ctx
.get_session_page_mut(&session)
.unwrap()
.evaluate("globalThis.__obscura_click_target && globalThis.__obscura_click_target.id");
assert_eq!(target_id, json!("target"));
}
}
#[tokio::test(flavor = "current_thread")]
#[cfg(feature = "render")]
async fn scroll_into_view_if_needed_preserves_visible_positions() {
let mut ctx = CdpContext::new();
let page_id = ctx.create_page();
let session = Some(format!("{page_id}-session"));
ctx.sessions.insert(session.clone().unwrap(), page_id);
crate::domains::page::handle("navigate", &json!({
"url": "data:text/html,<body style='margin:0;height:1800px'><div style='height:200px'></div><button id=target style='height:40px'>Go</button></body>",
"waitUntil": "load"
}), &mut ctx, &session).await.unwrap();
let node = handle("querySelector", &json!({"selector":"#target"}), &mut ctx, &session).await.unwrap();
handle("scrollIntoViewIfNeeded", &json!({"nodeId":node["nodeId"]}), &mut ctx, &session).await.unwrap();
let position = ctx.get_session_page_mut(&session).unwrap()
.evaluate("[scrollY, document.getElementById('target').getBoundingClientRect().top]");
assert_eq!(position, json!([0, 200]));
}
#[tokio::test(flavor = "current_thread")]
async fn scroll_into_view_if_needed_requires_a_node_identifier() {
let mut ctx = CdpContext::new();
let page_id = ctx.create_page();
let session = Some(format!("{page_id}-session"));
ctx.sessions.insert(session.clone().unwrap(), page_id);
let error = handle(
"scrollIntoViewIfNeeded",
&json!({}),
&mut ctx,
&session,
)
.await
.expect_err("missing node identifier should fail");
assert_eq!(error, "nodeId, backendNodeId, or objectId required");
let error = handle(
"scrollIntoViewIfNeeded",
&json!({ "nodeId": 999_999 }),
&mut ctx,
&session,
)
.await
.expect_err("an unknown node should fail");
assert_eq!(
error,
"node 999999 could not be resolved to a scrollable element"
);
}
// A hostile or heavy page can nest nodes tens of thousands deep (trivially
// scriptable, and html5ever puts no cap on generic nesting). DOM.getDocument
// with the standard depth:-1 (which becomes u32::MAX here) must handle such a
// tree without crashing the worker (AGENTS.md: "one page must never crash a
// worker"). Two failure modes: (1) a recursive serialize_node overflows the
// stack building the Value, and (2) even an iterative builder would emit a
// Value so deeply nested that serde_json's own recursive serialize/Drop
// overflow. The fix derecurses the builder AND bounds the depth, so the
// response is always safe to serialize and drop. With the old recursive
// serialize_node this test aborts with SIGABRT.
#[test]
fn get_document_deep_tree_does_not_overflow() {
use obscura_dom::{DomTree, NodeData};
// Build the deep chain directly (no parser) so setup is O(n) and fast.
let dom = DomTree::new();
let mut parent = dom.document();
let depth = 50_000usize;
for _ in 0..depth {
let n = dom.new_node(NodeData::Text { contents: String::new() });
dom.append_child(parent, n);
parent = n;
}
// Mirror getDocument {"depth": -1}: as_i64() == -1, then `depth as u32`.
let node = serialize_node(&dom, dom.document(), (-1i64) as u32, 0);
// serde_json's own serialization recurses over the Value nesting; this
// must not overflow either. That is why the fix bounds depth, not just
// the builder.
let s = serde_json::to_string(&node).expect("serialize");
assert!(!s.is_empty());
// Output nesting is bounded well below the tree's true depth (truncated,
// not crashed) yet still serializes a meaningful prefix.
let mut cur = &node;
let mut levels = 0usize;
while let Some(children) = cur.get("children").and_then(|c| c.as_array()) {
let Some(first) = children.first() else { break };
cur = first;
levels += 1;
}
assert!(levels >= 100, "should serialize a deep prefix, got {levels}");
assert!(
levels < depth,
"nesting must be bounded below the tree's true depth, got {levels}"
);
}
/// SEC-003 / #579 — DOM.setFileInputFiles reads local files and hands
/// their bytes to page JS. Without a gate, any CDP client (e.g. against a
/// Docker image that binds the port to 0.0.0.0) gets an arbitrary
/// file-read primitive. It must honour the same `allow_file_access` opt-in
/// as Page.navigate to `file://`, which defaults to off.
#[tokio::test(flavor = "current_thread")]
async fn set_file_input_files_refuses_without_allow_file_access() {
let mut ctx = CdpContext::new();
let page_id = ctx.create_page();
let session = Some(format!("{page_id}-session"));
ctx.sessions.insert(session.clone().unwrap(), page_id);
crate::domains::page::handle(
"navigate",
&json!({ "url": "data:text/html,<input type=file id=f>", "waitUntil": "load" }),
&mut ctx,
&session,
)
.await
.expect("navigate should succeed");
let qs = handle("querySelector", &json!({ "selector": "input" }), &mut ctx, &session)
.await
.expect("querySelector should succeed");
let nid = qs["nodeId"].as_u64().expect("input nodeId");
// A real, readable file. Without the gate the handler slurps it and
// returns Ok; with the gate it must refuse before touching the disk.
let existing = format!("{}/Cargo.toml", env!("CARGO_MANIFEST_DIR"));
let err = handle(
"setFileInputFiles",
&json!({ "nodeId": nid, "files": [existing] }),
&mut ctx,
&session,
)
.await
.expect_err("setFileInputFiles must be gated behind --allow-file-access");
assert!(
err.contains("allow-file-access"),
"error must point at the allow-file-access flag: {err}"
);
}
// issue #576: DOM.getBoxModel / getContentQuads build their quad from f64
// pixel values, so serde_json emits integral coordinates as `256.0`. Strict
// CDP clients (Hermes Agent) deserialize the quad as i64 and reject the
// float. coord_value must serialize integral coordinates as integers, the way
// Chrome does, while leaving genuinely fractional ones as floats.
#[test]
fn box_model_integral_coordinates_serialize_as_integers() {
assert_eq!(serde_json::to_string(&coord_value(256.0)).unwrap(), "256");
assert_eq!(serde_json::to_string(&coord_value(0.0)).unwrap(), "0");
// fractional coordinates stay floats
assert_eq!(serde_json::to_string(&coord_value(206.0390625)).unwrap(), "206.0390625");
// a full quad mixes both, exactly as DOM.getBoxModel returns it
let quad: Vec<Value> = [
256.0, 206.0390625, 347.25, 206.0390625, 347.25, 225.0390625, 256.0, 225.0390625,
]
.iter()
.map(|n| coord_value(*n))
.collect();
assert_eq!(
serde_json::to_string(&quad).unwrap(),
"[256,206.0390625,347.25,206.0390625,347.25,225.0390625,256,225.0390625]"
);
}
}