Skip to content

The headless browser for AI agents and web scraping

Preserve remote DOM node ownership

SGavrlc05cf3b49930
diff --git a/crates/obscura-cdp/src/domains/dom.rs b/crates/obscura-cdp/src/domains/dom.rs
index 4142d2a3..d20456ba 100644
--- a/crates/obscura-cdp/src/domains/dom.rs
+++ b/crates/obscura-cdp/src/domains/dom.rs
@@ -306,6 +306,13 @@ pub async fn handle(
// 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))
@@ -315,6 +322,36 @@ pub async fn handle(
"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 node = 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
+ })?;
+ 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()))
diff --git a/crates/obscura-cdp/src/domains/page.rs b/crates/obscura-cdp/src/domains/page.rs
index d9c9a16e..f1f80166 100644
--- a/crates/obscura-cdp/src/domains/page.rs
+++ b/crates/obscura-cdp/src/domains/page.rs
@@ -15,7 +15,7 @@ const DEFAULT_SCREENSHOT_QUALITY: i64 = 80;
/// child's protocol id is derived from its page's. It stays stable for the
/// life of the frame, which is what lets a client match an attach event to the
/// frame it later sees in the tree.
-fn child_frame_id(page_frame_id: &str, frame_id: u32) -> String {
+pub(crate) fn child_frame_id(page_frame_id: &str, frame_id: u32) -> String {
format!("{page_frame_id}-frame-{frame_id}")
}
diff --git a/crates/obscura-cdp/tests/file_upload_integrity.rs b/crates/obscura-cdp/tests/file_upload_integrity.rs
index 385bc12f..bc1dd935 100644
--- a/crates/obscura-cdp/tests/file_upload_integrity.rs
+++ b/crates/obscura-cdp/tests/file_upload_integrity.rs
@@ -24,6 +24,79 @@ async fn call(ws: &mut Ws, id: u64, method: &str, params: Value,
}
}
+#[tokio::test(flavor = "current_thread")]
+async fn remote_documents_have_their_actual_frame_identity_and_dom() {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ drop(listener);
+ tokio::task::LocalSet::new().run_until(async {
+ tokio::task::spawn_local(async move {
+ obscura_cdp::server::start_with_host_and_security(
+ port, "127.0.0.1", None, false, None, false, None).await.unwrap();
+ });
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
+ let (mut ws, _) = loop {
+ match connect_async(format!("ws://127.0.0.1:{port}/devtools/browser")).await {
+ Ok(connection) => break connection,
+ Err(error) => {
+ assert!(tokio::time::Instant::now() < deadline, "server did not start: {error}");
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ }
+ };
+ let created = call(&mut ws, 1, "Target.createTarget", json!({"url":"about:blank"}), None).await;
+ let session = format!("{}-session", created["result"]["targetId"].as_str().unwrap());
+ let sid = Some(session.as_str());
+ let html = "<div id=root>root-only</div>\
+ <iframe id=first srcdoc=\"<p id=one>first-only</p>\"></iframe>\
+ <iframe id=second srcdoc=\"<p id=two>second-only</p>\"></iframe>";
+ let loaded = call(&mut ws, 2, "Page.navigate",
+ json!({"url":format!("data:text/html,{html}"),"waitUntil":"load"}), sid).await;
+ assert!(loaded.get("error").is_none(), "{loaded}");
+ let tree = call(&mut ws, 3, "Page.getFrameTree", json!({}), sid).await;
+ let root_frame = tree["result"]["frameTree"]["frame"]["id"].as_str().unwrap();
+ let children = tree["result"]["frameTree"]["childFrames"].as_array().unwrap();
+ assert_eq!(children.len(), 2, "{tree}");
+ for (index, (element, expected)) in [("first","first-only"),("second","second-only")]
+ .into_iter().enumerate() {
+ let id = 10 + index as u64 * 4;
+ let remote = call(&mut ws, id, "Runtime.evaluate",
+ json!({"expression":format!("document.getElementById('{element}').contentDocument")}), sid).await;
+ let object = remote["result"]["result"]["objectId"].as_str().unwrap();
+ let described = call(&mut ws, id+1, "DOM.describeNode",
+ json!({"objectId":object,"depth":2}), sid).await;
+ let node = &described["result"]["node"];
+ assert_eq!(node["nodeType"], 9, "{described}");
+ assert!(node.get("frameId").is_none(), "{described}");
+ let document_element = node["children"].as_array().unwrap().iter()
+ .find(|node| node["nodeType"] == 1).unwrap();
+ assert_eq!(document_element["frameId"], children[index]["frame"]["id"], "{described}");
+ assert_ne!(document_element["frameId"], root_frame, "{described}");
+ assert_eq!(node["documentURL"], "about:srcdoc", "{described}");
+ assert!(node["baseURL"].as_str().is_some_and(|url| !url.is_empty()), "{described}");
+ let html = call(&mut ws, id+2, "DOM.getOuterHTML", json!({"objectId":object}), sid).await;
+ let html = html["result"]["outerHTML"].as_str().unwrap();
+ assert!(html.contains(expected) && !html.contains("root-only"), "{html}");
+ }
+ let root = call(&mut ws, 20, "Runtime.evaluate", json!({"expression":"document.documentElement"}), sid).await;
+ let root = call(&mut ws, 21, "DOM.describeNode",
+ json!({"objectId":root["result"]["result"]["objectId"]}), sid).await;
+ assert_eq!(root["result"]["node"]["frameId"], root_frame, "{root}");
+ let fake = call(&mut ws, 22, "Runtime.evaluate", json!({"expression":"({_nid:0})"}), sid).await;
+ let fake = call(&mut ws, 23, "DOM.describeNode",
+ json!({"objectId":fake["result"]["result"]["objectId"]}), sid).await;
+ assert!(fake.get("error").is_some(), "{fake}");
+ let removed = call(&mut ws, 24, "Runtime.evaluate",
+ json!({"expression":"document.getElementById('first').contentDocument"}), sid).await;
+ call(&mut ws, 25, "Runtime.evaluate",
+ json!({"expression":"document.getElementById('first').remove()"}), sid).await;
+ let removed = call(&mut ws, 26, "DOM.describeNode",
+ json!({"objectId":removed["result"]["result"]["objectId"]}), sid).await;
+ assert!(removed.get("error").is_some(), "{removed}");
+ ws.close(None).await.unwrap();
+ }).await;
+}
+
#[tokio::test(flavor = "current_thread")]
async fn file_uploads_validate_before_reading_and_preserve_frame_identity() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index a80ba7dc..0f13da45 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -7331,6 +7331,7 @@ class DocumentType extends Node {
}
const _cache = new Map();
+const _nodeCacheGet = Map.prototype.get.bind(_cache);
class TextTrackCue {
constructor(startTime, endTime, text) {
@@ -18911,6 +18912,8 @@ const _installCaretGeometry = (function _installCaretGeometry() {
// Capture late-defined members too, before page code can replace them.
const _nativeElementClick = Element.prototype.click;
+const _nativeDocumentUrl = Function.prototype.call.bind(Object.getOwnPropertyDescriptor(Document.prototype, 'URL').get);
+const _nativeNodeBaseUri = Function.prototype.call.bind(Object.getOwnPropertyDescriptor(Node.prototype, 'baseURI').get);
const _documentMembers = Object.freeze(Object.fromEntries([
...['URL', 'defaultView', 'readyState', 'compatMode', 'contentType', 'getElementById', 'querySelector', 'querySelectorAll', 'open', 'write', 'close', 'elementFromPoint', 'queryCommandSupported'].map(name => {
const descriptor = Object.getOwnPropertyDescriptor(Document.prototype, name);
@@ -18921,6 +18924,13 @@ const _documentMembers = Object.freeze(Object.fromEntries([
}],
['checkVisibility', Element.prototype.checkVisibility],
['elementStyle', function() { return _elementStyle(this); }],
+ ['domNodeReference', function() {
+ const nid = this._nid;
+ if (_nodeCacheGet(nid) !== this) throw new TypeError('Not a current DOM node');
+ const doc = _nodeDocumentOf(this);
+ const url = doc === document && globalThis.__virtualUrl || _nativeDocumentUrl(doc);
+ return [nid, url, _nativeNodeBaseUri(this)];
+ }],
['windowOrigin', _windowOriginDescriptor.get],
['setWindowOrigin', _windowOriginDescriptor.set],
]));
diff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rs
index 2a06d1dd..41809ed8 100644
--- a/crates/obscura-js/src/frame.rs
+++ b/crates/obscura-js/src/frame.rs
@@ -1749,6 +1749,36 @@ mod tests {
);
}
+ #[test]
+ fn remote_dom_nodes_preserve_foreign_document_identity_and_reject_stale_frames() {
+ let mut parent = page("https://example.com/", "<div id=parent>parent</div>");
+ let frame = FrameRealm::new(&mut parent, 1, 0, "https://example.com/child",
+ "<base href='/assets/'><span id=child>child</span>").unwrap();
+ let info = parent.store_object_with_meta(
+ "globalThis.__obscura_frameObjects[1].document.getElementById('child')").unwrap();
+ let object_id = info.object_id.unwrap();
+ let description = parent.with_remote_dom_node(&object_id, |dom, node, frame, url, base| {
+ (frame, url.to_string(), base.to_string(), dom.outer_html(node))
+ }).unwrap();
+ assert_eq!(description, (1, "https://example.com/child".into(),
+ "https://example.com/assets/".into(), "<span id=\"child\">child</span>".into()));
+ frame.execute_script(&mut parent, "history.pushState({},'', '/changed');").unwrap();
+ assert_eq!(parent.with_remote_dom_node(&object_id, |_, _, _, url, base| {
+ (url.to_string(), base.to_string())
+ }).unwrap(), ("https://example.com/changed".into(), "https://example.com/assets/".into()));
+ let document = parent.store_object_with_meta(
+ "globalThis.__obscura_frameObjects[1].document").unwrap().object_id.unwrap();
+ assert_eq!(parent.with_remote_dom_node(&document, |dom, node, frame, _, _| {
+ (node == dom.document(), frame)
+ }).unwrap(), (true, 1));
+ let forged = parent.store_object_with_meta("({_nid:0})").unwrap().object_id.unwrap();
+ parent.execute_script("override", "Map.prototype.get=function(){return this};").unwrap();
+ assert!(parent.with_remote_dom_node(&forged, |_, _, _, _, _| ()).is_err());
+ assert_eq!(parent.with_remote_dom_node(&document, |_, _, frame, _, _| frame).unwrap(), 1);
+ parent.forget_frame_state(frame.frame_id());
+ assert!(parent.with_remote_dom_node(&document, |_, _, _, _, _| ()).is_err());
+ }
+
#[test]
fn opaque_origin_frames_are_never_same_origin() {
let mut parent = page("https://parent.example/", "<html><body></body></html>");
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 42898185..341307ae 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -6892,6 +6892,16 @@ fn op_register_document_realm(
/// Resolve a borrowed document member from the receiver's creation realm, not
/// its public prototype, which a membrane is allowed to replace.
+pub(crate) fn document_realm<'s, 'i>(
+ scope: &mut v8::PinScope<'s, 'i>,
+ receiver: v8::Local<'s, v8::Object>,
+) -> Option<(u32, v8::Local<'s, v8::Object>)> {
+ let context = receiver.get_creation_context(scope)?;
+ let owner = context.get_embedder_data(scope, DOCUMENT_OWNER_SLOT)?.uint32_value(scope)?;
+ let members = context.get_embedder_data(scope, DOCUMENT_MEMBERS_SLOT)?.to_object(scope)?;
+ Some((owner, members))
+}
+
#[op2]
fn op_document_realm_member<'s, 'i>(
scope: &mut v8::PinScope<'s, 'i>,
@@ -6900,10 +6910,8 @@ fn op_document_realm_member<'s, 'i>(
caller_frame_id: u32,
) -> v8::Local<'s, v8::Value> {
let member = (|| {
- let context = receiver.get_creation_context(scope)?;
- let owner = context.get_embedder_data(scope, DOCUMENT_OWNER_SLOT)?.uint32_value(scope)?;
+ let (owner, members) = document_realm(scope, receiver)?;
if owner == caller_frame_id { return None; }
- let members = context.get_embedder_data(scope, DOCUMENT_MEMBERS_SLOT)?.to_object(scope)?;
let key = v8::String::new(scope, name)?;
let value = members.get(scope, key.into())?;
value.is_function().then_some(value)
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index a938a654..0df100cb 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -4161,6 +4161,65 @@ impl ObscuraJsRuntime {
state.dom.as_ref().map(f)
}
+ /// Inspect a genuine remote node in its owning document, including foreign
+ /// handles returned through the parent realm. Detached frame handles fail
+ /// instead of resolving the same numeric node id in the main document.
+ pub fn with_remote_dom_node<R>(&mut self, object_id: &str,
+ inspect: impl FnOnce(&DomTree, NodeId, u32, &str, &str) -> R) -> Result<R, String> {
+ self.begin_javascript_task();
+ // getProperties also stores child handles directly in the realm's table.
+ let retrieval = self.resolve_remote_object(object_id).unwrap_or_else(|| {
+ format!("globalThis.__obscura_objects[{}]", js_string_literal(object_id))
+ });
+ let receiver = self.execute_runtime_script("<cdp-dom-node>", retrieval)
+ .map_err(|error| format!("Could not resolve remote node: {error}"))?;
+ let watchdog = self.arm_watchdog(std::time::Duration::from_secs(5));
+ let reference = (|| {
+ let mut entered = self.runtime();
+ let context = entered.main_context();
+ v8::scope_with_context!(scope, entered.v8_isolate(), context);
+ v8::tc_scope!(let scope, scope);
+ let receiver = v8::Local::new(scope, &receiver);
+ let object = v8::Local::<v8::Object>::try_from(receiver)
+ .map_err(|_| "Remote object is not a DOM node".to_string())?;
+ let (frame_id, members) = crate::ops::document_realm(scope, object)
+ .ok_or("Remote node has no owning document")?;
+ let key = v8::String::new(scope, "domNodeReference").ok_or("DOM member allocation failed")?;
+ let member = members.get(scope, key.into()).ok_or("DOM node member unavailable")?;
+ let function = v8::Local::<v8::Function>::try_from(member)
+ .map_err(|_| "DOM node member is not a function".to_string())?;
+ let value = function.call(scope, receiver, &[])
+ .ok_or_else(|| format!("Could not inspect remote node: {}", exception_text(scope)))?;
+ let metadata = v8::Local::<v8::Array>::try_from(value)
+ .map_err(|_| "Remote node metadata is unavailable".to_string())?;
+ let node_id = metadata.get_index(scope, 0).and_then(|value| value.integer_value(scope))
+ .and_then(|id| u32::try_from(id).ok())
+ .ok_or("Remote object is not a current DOM node")?;
+ let url = metadata.get_index(scope, 1).filter(|value| value.is_string())
+ .ok_or("Remote document URL is unavailable")?.to_rust_string_lossy(scope);
+ let base = metadata.get_index(scope, 2).filter(|value| value.is_string())
+ .ok_or("Remote document base URL is unavailable")?.to_rust_string_lossy(scope);
+ Ok::<_, String>((frame_id, NodeId::new(node_id), url, base))
+ })();
+ let fired = self.disarm_watchdog(watchdog);
+ if fired { return Err("Remote node inspection exceeded its deadline".into()); }
+ let (frame_id, node_id, url, base) = reference?;
+ let state = if frame_id == 0 {
+ self.state.clone()
+ } else {
+ let realms = self.realm_states();
+ let realms = realms.borrow();
+ if realms.frame_timers_active(frame_id) != Some(true) {
+ return Err("Remote node belongs to a detached frame".into());
+ }
+ realms.by_frame_id(frame_id).ok_or("Remote node document is unavailable")?
+ };
+ let state = state.borrow();
+ let dom = state.dom.as_ref().ok_or("Remote node document has no DOM")?;
+ if dom.get_node(node_id).is_none() { return Err("Remote node is no longer available".into()); }
+ Ok(inspect(dom, node_id, frame_id, &url, &base))
+ }
+
#[cfg(feature = "render")]
pub fn accessibility_styles(&self) -> HashMap<NodeId, AccessibilityStyle> {
let mut state = self.state.borrow_mut();
diff --git a/docs/Architecture-overview.md b/docs/Architecture-overview.md
index 463fc9f5..20821b86 100644
--- a/docs/Architecture-overview.md
+++ b/docs/Architecture-overview.md
@@ -120,6 +120,11 @@ standards mode without requiring a doctype and honors script-disabled
Sandboxed `srcdoc` enforces opaque document access and script disabling,
including inherited restrictions on nested frames. This does not implement
every HTML sandbox policy. Frame module scripts remain unsupported.
+CDP `DOM.describeNode` and `DOM.getOuterHTML` resolve remote node handles in
+their native owning document, including handles obtained through the parent.
+The document element carries that document's protocol frame ID, so Playwright
+can discover an element handle's owner frame. Retired frame handles fail
+instead of reading a same-numbered node in the main document.
Child-frame CDP evaluation routing and iframe content compositing remain
separate compatibility gaps; loading a document does not establish support
for Playwright frame locators or iframe screenshot fidelity.