The headless browser for AI agents and web scraping
fix(cdp): support light-DOM node queries
SGavrl717dd92b9d4f
diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rsindex ba2bc7f4..1ffea475 100644--- a/crates/obscura-cdp/src/dispatch.rs+++ b/crates/obscura-cdp/src/dispatch.rs@@ -64,6 +64,7 @@ pub struct CdpContext {/// is announced once and a frame that goes away can be retracted.pub announced_frames: HashMap<String, Vec<String>>,pub pending_events: Vec<CdpEvent>,+ pub(crate) dom_documents: HashMap<Option<String>, domains::dom::DomDocument>,pub(crate) pending_beforeunload_close: HashMap<String, Option<String>>,#[cfg(feature = "render")]pub(crate) screencasts: HashMap<String, ScreencastState>,@@ -179,6 +180,7 @@ impl CdpContext {nav_events_emitted: std::collections::HashSet::new(),announced_frames: HashMap::new(),pending_events: Vec::new(),+ dom_documents: HashMap::new(),pending_beforeunload_close: HashMap::new(),#[cfg(feature = "render")]screencasts: HashMap::new(),@@ -333,6 +335,7 @@ impl CdpContext {}pub fn remove_page(&mut self, id: &str) {+ self.dom_documents.retain(|_, document| document.page_id != id);self.pending_beforeunload_close.remove(id);let removed_sessions: Vec<String> = self.sessions@@ -417,6 +420,13 @@ impl CdpContext {frame_id: &str,origin: &str,) -> Vec<ExecutionContextRecord> {+ self.dom_documents.retain(|session, document| {+ if document.page_id != page_id { return true; }+ self.pending_events.push(CdpEvent {+ method: "DOM.documentUpdated".into(), params: json!({}), session_id: session.clone(),+ });+ false+ });if let Some(previous) = self.page_contexts.remove(page_id) {for id in previous {self.execution_contexts.remove(&id);diff --git a/crates/obscura-cdp/src/domains/dom.rs b/crates/obscura-cdp/src/domains/dom.rsindex 47d53a7f..dc477e8d 100644--- a/crates/obscura-cdp/src/domains/dom.rs+++ b/crates/obscura-cdp/src/domains/dom.rs@@ -1,8 +1,83 @@+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())+}++fn push_children(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 nodes: Vec<_> = children.iter()+ .map(|child| serialize_node(dom, *child, depth - 1, 0)).collect();+ 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(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`@@ -95,13 +170,100 @@ pub async fn handle() -> 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);- page.with_dom(|dom| {- let node = serialize_node(dom, dom.document(), depth as u32, 0);- json!({ "root": node })- }).ok_or_else(|| "No DOM loaded".to_string())+ let root = page.with_dom(|dom| serialize_node(dom, dom.document(), depth as u32, 0))+ .ok_or("No DOM loaded")?;+ 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(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")?;@@ -424,7 +586,7 @@ fn node_value(dom: &DomTree, node_id: NodeId) -> Option<(Value, Vec<NodeId>)> {result["localName"] = json!(name.local.as_ref());result["nodeValue"] = json!("");let cdp_attrs: Vec<String> = attrs.iter()- .flat_map(|a| vec![a.name.local.to_string(), a.value.clone()]).collect();+ .flat_map(|a| [a.qualified_name(), a.value.clone()]).collect();result["attributes"] = json!(cdp_attrs);}NodeData::Text { contents } => {@@ -527,6 +689,33 @@ 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-quoteddiff --git a/crates/obscura-cdp/src/domains/target.rs b/crates/obscura-cdp/src/domains/target.rsindex 28fda2b8..1db15e9f 100644--- a/crates/obscura-cdp/src/domains/target.rs+++ b/crates/obscura-cdp/src/domains/target.rs@@ -225,6 +225,7 @@ pub async fn handle("detachFromTarget" => {if let Some(session_id) = params.get("sessionId").and_then(Value::as_str) {let page_id = ctx.sessions.remove(session_id);+ ctx.dom_documents.remove(&Some(session_id.to_string()));ctx.runtime_enabled_sessions.remove(session_id);ctx.lifecycle_enabled_sessions.remove(session_id);if let Some(page_id) = page_id {diff --git a/crates/obscura-cdp/tests/dom_node_queries.rs b/crates/obscura-cdp/tests/dom_node_queries.rsnew file mode 100644index 00000000..3acec9fb--- /dev/null+++ b/crates/obscura-cdp/tests/dom_node_queries.rs@@ -0,0 +1,140 @@+use obscura_cdp::dispatch::{dispatch, CdpContext};+use obscura_cdp::types::{CdpRequest, CdpResponse};+use serde_json::{json, Value};++async fn call(ctx: &mut CdpContext, session: &str, method: &str, params: Value) -> CdpResponse {+ dispatch(&CdpRequest {+ id: 1, method: format!("DOM.{method}"), params, session_id: Some(session.into()),+ }, ctx).await+}++async fn ok(ctx: &mut CdpContext, session: &str, method: &str, params: Value) -> Value {+ let response = call(ctx, session, method, params).await;+ assert!(response.error.is_none(), "{method}: {:?}", response.error);+ response.result.unwrap()+}++async fn fixture() -> (CdpContext, String, String) {+ let mut ctx = CdpContext::new();+ let page = ctx.create_page();+ let session = format!("{page}-session");+ ctx.sessions.insert(session.clone(), page.clone());+ obscura_cdp::domains::page::handle("navigate", &json!({"url":+ "data:text/html,<main><label id=lab for=c style='position:absolute;left:32px;top:48px;width:120px;height:32px'>agree</label><input id=c></main>"+ }), &mut ctx, &Some(session.clone())).await.unwrap();+ ctx.pending_events.clear();+ (ctx, session, page)+}++fn object(ctx: &mut CdpContext, session: &str, expression: &str) -> String {+ ctx.get_session_page_mut(&Some(session.into())).unwrap().js.as_mut().unwrap()+ .store_object_with_meta(expression).unwrap().object_id.unwrap()+}++#[tokio::test(flavor = "current_thread")]+async fn dom_attributes_preserve_qualified_names_and_reject_invalid_nodes() {+ let (mut ctx, session, _) = fixture().await;+ let node = ok(&mut ctx, &session, "querySelector", json!({"selector":"#lab"})).await["nodeId"].clone();+ ctx.get_session_page_mut(&Some(session.clone())).unwrap().evaluate(+ "document.querySelector('#lab').setAttributeNS('urn:test','x:flag','yes')"+ );+ let attributes = ok(&mut ctx, &session, "getAttributes", json!({"nodeId":node})).await;+ let pairs: std::collections::BTreeMap<_, _> = attributes["attributes"].as_array().unwrap()+ .chunks_exact(2).map(|pair| (pair[0].as_str().unwrap(), pair[1].as_str().unwrap())).collect();+ assert_eq!(pairs["id"], "lab");+ assert_eq!(pairs["for"], "c");+ assert_eq!(pairs["x:flag"], "yes");+ for invalid in [json!({}), json!({"nodeId":999999}), json!({"nodeId":4294967297u64})] {+ assert!(call(&mut ctx, &session, "getAttributes", invalid).await.error.is_some());+ }+}++#[tokio::test(flavor = "current_thread")]+async fn dom_request_node_pushes_ancestors_once_to_the_requesting_session() {+ let (mut ctx, session, page) = fixture().await;+ let oid = object(&mut ctx, &session, "document.querySelector('#lab')");+ assert_eq!(ok(&mut ctx, &session, "requestNode", json!({"objectId":oid})).await["nodeId"], 0);+ ok(&mut ctx, &session, "getDocument", json!({"depth":0})).await;+ ctx.pending_events.clear();+ let node = ok(&mut ctx, &session, "requestNode", json!({"objectId":oid})).await["nodeId"].clone();+ assert_ne!(node, 0);+ let pushes: Vec<_> = ctx.pending_events.iter().filter(|event| event.method == "DOM.setChildNodes").collect();+ assert!(!pushes.is_empty());+ assert!(pushes.iter().all(|event| event.session_id.as_deref() == Some(session.as_str())));+ assert!(pushes.iter().any(|event| event.params["nodes"].as_array().unwrap()+ .iter().any(|child| child["nodeId"] == node && child["nodeName"] == "LABEL")));+ ctx.pending_events.clear();+ ok(&mut ctx, &session, "requestNode", json!({"objectId":oid})).await;+ assert!(ctx.pending_events.is_empty(), "known nodes must not be pushed again");+ ctx.sessions.insert("other".into(), page);+ let other_oid = object(&mut ctx, "other", "document.querySelector('#lab')");+ assert_eq!(ok(&mut ctx, "other", "requestNode", json!({"objectId":other_oid})).await["nodeId"], 0);+ ok(&mut ctx, "other", "getDocument", json!({"depth":0})).await;+ assert_ne!(ok(&mut ctx, "other", "requestNode", json!({"objectId":other_oid})).await["nodeId"], 0);+ assert!(ctx.pending_events.iter().any(|event| event.method == "DOM.setChildNodes"+ && event.session_id.as_deref() == Some("other")));+ for expression in ["({})", "({_nid:1})"] {+ let invalid = object(&mut ctx, &session, expression);+ assert!(call(&mut ctx, &session, "requestNode", json!({"objectId":invalid})).await.error.is_some());+ }+ assert!(call(&mut ctx, &session, "requestNode", json!({"objectId":"missing"})).await.error.is_some());+ ok(&mut ctx, &session, "getDocument", json!({"depth":-1})).await;+ let inserted = object(&mut ctx, &session,+ "document.querySelector('main').appendChild(document.createElement('button'))");+ assert!(call(&mut ctx, &session, "requestNode", json!({"objectId":inserted})).await.error.is_some(),+ "without mutation events, do not return a frontend ID that was never published");+}++#[tokio::test(flavor = "current_thread")]+async fn dom_child_requests_expand_depth_without_repeating_known_children() {+ let (mut ctx, session, _) = fixture().await;+ let root = ok(&mut ctx, &session, "getDocument", json!({"depth":0})).await["root"]["nodeId"].clone();+ ctx.pending_events.clear();+ assert_eq!(ok(&mut ctx, &session, "requestChildNodes", json!({"nodeId":root,"depth":2})).await, json!({}));+ let event = ctx.pending_events.iter().find(|event| event.method == "DOM.setChildNodes").unwrap();+ assert_eq!(event.params["parentId"], root);+ let html = &event.params["nodes"][0];+ assert_eq!(html["nodeName"], "HTML");+ assert_eq!(html["children"][1]["nodeName"], "BODY");+ ctx.pending_events.clear();+ ok(&mut ctx, &session, "requestChildNodes", json!({"nodeId":root,"depth":2})).await;+ assert!(ctx.pending_events.is_empty());+ ok(&mut ctx, &session, "requestChildNodes", json!({"nodeId":root,"depth":-1})).await;+ assert!(ctx.pending_events.iter().any(|event| event.method == "DOM.setChildNodes"));+ for depth in [json!(0), json!(-2), json!("bad")] {+ assert!(call(&mut ctx, &session, "requestChildNodes", json!({"nodeId":root,"depth":depth})).await.error.is_some());+ }+}++#[tokio::test(flavor = "current_thread")]+async fn dom_child_requests_allow_pierce_on_plain_trees_but_reject_unserved_roots() {+ let (mut ctx, session, _) = fixture().await;+ let root = ok(&mut ctx, &session, "getDocument", json!({"depth":0})).await["root"]["nodeId"].clone();+ ok(&mut ctx, &session, "requestChildNodes", json!({"nodeId":root,"depth":-1,"pierce":true})).await;+ assert!(ctx.pending_events.iter().any(|event| event.method == "DOM.setChildNodes"));+ ctx.get_session_page_mut(&Some(session.clone())).unwrap().evaluate(+ "document.querySelector('main').attachShadow({mode:'open'}).innerHTML='<button>shadow</button>'"+ );+ assert!(call(&mut ctx, &session, "requestChildNodes",+ json!({"nodeId":root,"depth":-1,"pierce":true})).await.error.is_some(),+ "a requested shadow tree must not be silently omitted");+}++#[cfg(feature = "render")]+#[tokio::test(flavor = "current_thread")]+async fn dom_hit_lookup_reports_frame_and_only_publishes_requested_node_ids() {+ let (mut ctx, session, page) = fixture().await;+ let params = json!({"x":64,"y":64});+ let before = ok(&mut ctx, &session, "getNodeForLocation", params.clone()).await;+ assert!(before.get("nodeId").is_none());+ assert!(before["backendNodeId"].is_number());+ assert_eq!(before["frameId"], ctx.get_page(&page).unwrap().frame_id);+ ok(&mut ctx, &session, "getDocument", json!({"depth":0})).await;+ let after = ok(&mut ctx, &session, "getNodeForLocation", params).await;+ let description = ok(&mut ctx, &session, "describeNode", json!({"backendNodeId":after["backendNodeId"]})).await;+ assert_eq!(description["node"]["nodeName"], "LABEL");+ assert_eq!(after["nodeId"], description["node"]["nodeId"]);+ assert!(call(&mut ctx, &session, "getNodeForLocation", json!({"x":-1,"y":64})).await.error.is_some());+ ok(&mut ctx, &session, "disable", json!({})).await;+ assert!(ok(&mut ctx, &session, "getNodeForLocation", json!({"x":64,"y":64})).await.get("nodeId").is_none());+}diff --git a/crates/obscura-cdp/tests/integration.rs b/crates/obscura-cdp/tests/integration.rsindex b5012dbe..32a479e7 100644--- a/crates/obscura-cdp/tests/integration.rs+++ b/crates/obscura-cdp/tests/integration.rs@@ -35,6 +35,7 @@ integration_tests!(control_plane_unblocked,document_write_lifecycle,dom_get_outer_html_object_id,+ dom_node_queries,dynamic_script_onload_fires,dynamic_stylesheet_onload_fires,execution_context_ownership,diff --git a/docs/Connect-Puppeteer-or-Playwright.md b/docs/Connect-Puppeteer-or-Playwright.mdindex 09c3b25a..ecce07a9 100644--- a/docs/Connect-Puppeteer-or-Playwright.md+++ b/docs/Connect-Puppeteer-or-Playwright.md@@ -99,6 +99,21 @@ Rendering is included in official binaries and requires `--features render`for source builds. The client-specific guides cover scrolling, raw CDPscreencasting, and current output limits.+## Raw CDP node queries++`DOM.getAttributes`, `DOM.requestNode`, `DOM.requestChildNodes`, and+`DOM.getNodeForLocation` support the top-level light DOM. Request the document+with `DOM.getDocument` before publishing frontend node IDs. Ancestors and+requested children arrive through session-scoped `DOM.setChildNodes` events;+navigation clears the node cache and emits `DOM.documentUpdated`.++Live mutation events are not implemented yet. Request the document again to+publish newly inserted children of an already-published parent. `requestChildNodes` accepts+`pierce: true` on plain light-DOM subtrees, but rejects requests that would+require frame or shadow-tree traversal. Detached-node publication and+`ignorePointerEventsNone: true` hit testing are not supported. The remaining work is tracked in+[#1291](https://github.com/h4ckf0r0day/obscura/issues/1291).+## Current limits- Pages share one V8 isolate. CPU-bound JavaScript on one page can delay others.