The headless browser for AI agents and web scraping
fix(js): expose parent child frames and named siblings across origins
Kushagra Kumar12b40f69fed1
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex 0f9f912e..a5e8a2aa 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -8126,6 +8126,47 @@ mod tests {assert_eq!(evaluated.value.unwrap(), serde_json::json!([true, true, true]));}+ // Issue #1490: cross-origin child frame sees parent.frames.length,+ // parent.length, indexed access to self/siblings, and named access to siblings.+ #[tokio::test(flavor = "current_thread")]+ async fn cross_origin_child_frame_sees_parent_frames_and_named_siblings() {+ let (base, _, _) = spawn_slow_frame_script_server().await;+ let mut page = import_map_test_page(+ "cross-origin-frames",+ &base,+ "<html><body>\+ <iframe name=\"a\" src=\"/child.html?a\"></iframe>\+ <iframe name=\"b\" src=\"/child.html?b\"></iframe>\+ </body></html>",+ );+ let script = "new Promise(resolve => {\+ const iframes = document.querySelectorAll('iframe');\+ let loaded = 0;\+ const onLoaded = () => {\+ if (++loaded === 2) {\+ const a = iframes[0].contentWindow;\+ const b = iframes[1].contentWindow;\+ resolve([\+ a.parent.frames.length,\+ a.parent.length,\+ a.parent.frames[0] === a,\+ a.parent.frames[1] === a,\+ typeof a.parent.frames.b,\+ b.parent.frames.length,\+ b.parent.frames[1] === b,\+ b.parent.frames.b === b,\+ ]);\+ }\+ };\+ iframes[0].onload = onLoaded;\+ iframes[1].onload = onLoaded;\+ })";+ let evaluated = page.evaluate_for_cdp_with_timeout(script, true, true, 2_000).await.unwrap();+ assert_eq!(evaluated.value.unwrap(), serde_json::json!([+ 2, 2, true, false, "object", 2, true, true+ ]));+ }+#[tokio::test(flavor = "current_thread")]async fn cancelling_frame_script_fetch_keeps_all_siblings_resumable() {let (mut page, requests, slow_seen) =diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 279c63de..9a4f9c98 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -16493,7 +16493,7 @@ function _frameWindowFor(frameId) {if (!frameId) return null;const real = globalThis.__obscura_frameObjects?.[frameId]?.window;const existing = globalThis.__obscura_frameWindows[frameId];- if (!real) return existing || _remoteWindows.get(frameId) || null;+ if (!real) return existing || _remoteWindow(frameId);if (globalThis.__obscura_frameObjects[frameId].initial) return real;if (existing && existing.__obscura_wrapsRealm) return existing;@@ -16547,6 +16547,19 @@ globalThis.__obscura_deliverMessage = function(dataJson, origin, sourceFrameId,}};+function _remoteWindowChildren(frameId) {+ try {+ return JSON.parse(__obscuraCore.ops.op_frame_children(frameId >>> 0));+ } catch (_) {+ return [];+ }+}++function _resolveFrameWindow(frameId) {+ if (frameId === _realmFrameId) return globalThis;+ return _frameWindowFor(frameId) || _remoteWindow(frameId);+}+// A window in another browsing context, as seen from this one.//// Only the cross-origin surface is exposed: reaching synchronously into another@@ -16561,22 +16574,97 @@ class _RemoteWindow {get self() { return this; }get window() { return this; }get frames() { return this; }- get parent() { return this; }- get top() { return this; }+ get parent() {+ if (this._frameId === 0) return this;+ const pid = __obscuraCore.ops.op_frame_parent(this._frameId);+ return pid === _realmFrameId ? globalThis : _remoteWindow(pid);+ }+ get top() {+ return this._frameId === 0 ? this : (0 === _realmFrameId ? globalThis : _remoteWindow(0));+ }get opener() { return null; }get closed() { return false; }- get length() { return 0; }+ get length() { return _remoteWindowChildren(this._frameId).length; }focus() {}blur() {}close() {}+ get [Symbol.toStringTag]() { return 'Window'; }}_markNative(_RemoteWindow.prototype.postMessage);+const _remoteWindowProxyHandler = {+ get(target, prop, receiver) {+ if (prop === 'length') {+ return _remoteWindowChildren(target._frameId).length;+ }+ if (typeof prop === 'string') {+ const index = Number(prop);+ if (Number.isInteger(index) && index >= 0 && String(index) === prop) {+ const children = _remoteWindowChildren(target._frameId);+ if (index < children.length) {+ return _resolveFrameWindow(children[index][0]);+ }+ return undefined;+ }+ }+ if (prop in target) {+ return Reflect.get(target, prop, receiver);+ }+ if (typeof prop === 'string' && prop !== '') {+ const children = _remoteWindowChildren(target._frameId);+ for (let i = 0; i < children.length; i++) {+ if (children[i][1] === prop) {+ return _resolveFrameWindow(children[i][0]);+ }+ }+ }+ return Reflect.get(target, prop, receiver);+ },+ has(target, prop) {+ if (Reflect.has(target, prop)) return true;+ if (typeof prop === 'string') {+ const index = Number(prop);+ if (Number.isInteger(index) && index >= 0 && String(index) === prop) {+ return index < _remoteWindowChildren(target._frameId).length;+ }+ const children = _remoteWindowChildren(target._frameId);+ return children.some(c => c[1] && c[1] === prop);+ }+ return false;+ },+ ownKeys(target) {+ const keys = Reflect.ownKeys(target);+ const count = _remoteWindowChildren(target._frameId).length;+ for (let i = 0; i < count; i++) {+ const key = String(i);+ if (!keys.includes(key)) keys.push(key);+ }+ return keys;+ },+ getOwnPropertyDescriptor(target, prop) {+ if (typeof prop === 'string') {+ const index = Number(prop);+ if (Number.isInteger(index) && index >= 0 && String(index) === prop) {+ const children = _remoteWindowChildren(target._frameId);+ if (index < children.length) {+ return {+ value: _resolveFrameWindow(children[index][0]),+ writable: false,+ enumerable: true,+ configurable: true,+ };+ }+ }+ }+ return Reflect.getOwnPropertyDescriptor(target, prop);+ },+};+const _remoteWindows = new Map();function _remoteWindow(frameId) {let win = _remoteWindows.get(frameId);if (!win) {- win = new _RemoteWindow(frameId);+ win = new Proxy(new _RemoteWindow(frameId), _remoteWindowProxyHandler);_remoteWindows.set(frameId, win);}return win;diff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rsindex dc5676b2..1dcaa3de 100644--- a/crates/obscura-js/src/frame.rs+++ b/crates/obscura-js/src/frame.rs@@ -107,6 +107,7 @@ impl FrameRealm {state.dom = Some(parse_html(html));state.url = url.to_string();state.frame_id = frame_id;+ state.parent_frame_id = parent_frame_id;state.scripting_enabled = scripting_enabled;state.sandbox_opaque_origin = sandbox_opaque_origin;if sandbox_opaque_origin { state.inherited_origin = Some("null".to_string()); }@@ -1932,4 +1933,113 @@ mod tests {"iterableIterator": true}));}++ #[tokio::test(flavor = "current_thread")]+ async fn cross_origin_child_frame_sees_parent_frames_and_named_siblings() {+ let mut parent = page(+ "https://parent.example/",+ "<html><body>\+ <iframe name=\"a\" src=\"https://other.example/a\"></iframe>\+ <iframe name=\"b\" src=\"https://other.example/b\"></iframe>\+ </body></html>",+ );+ let frame_a = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://other.example/a",+ "<html><body></body></html>",+ ).unwrap();+ let frame_b = FrameRealm::new(+ &mut parent,+ 2,+ 0,+ "https://other.example/b",+ "<html><body></body></html>",+ ).unwrap();++ let result_a = frame_a.evaluate(&mut parent, r#"+ [+ parent.frames.length,+ parent.length,+ parent.frames[0] === window,+ parent.frames[1] === window,+ typeof parent.frames.b,+ parent.frames.b !== window,+ parent.parent === parent,+ parent.top === parent,+ ]+ "#).unwrap();+ assert_eq!(result_a, serde_json::json!([+ 2, 2, true, false, "object", true, true, true+ ]));++ let result_b = frame_b.evaluate(&mut parent, r#"+ [+ parent.frames.length,+ parent.length,+ parent.frames[0] === window,+ parent.frames[1] === window,+ parent.frames.b === window,+ typeof parent.frames.a,+ ]+ "#).unwrap();+ assert_eq!(result_b, serde_json::json!([+ 2, 2, false, true, true, "object"+ ]));++ frame_a.execute_script(&mut parent, r#"+ parent.frames.b.postMessage('hello from a', '*');+ "#).unwrap();+ let mut messages = parent.take_pending_frame_messages();+ assert_eq!(messages.len(), 1);+ assert_eq!(messages[0].target_frame_id, 2);+ assert_eq!(messages[0].source_frame_id, 1);++ let message = messages.pop().unwrap();+ frame_b.execute_script(&mut parent, r#"+ globalThis.received = [];+ addEventListener('message', event => {+ received.push({+ data: event.data,+ sourceIsA: event.source === parent.frames[0],+ });+ event.source.postMessage('reply from b', '*');+ });+ "#).unwrap();+ frame_b.deliver_message(+ &mut parent,+ &message.data_json,+ &message.origin,+ message.source_frame_id,+ &message.target_origin,+ ).unwrap();++ let received = frame_b.evaluate(&mut parent, "globalThis.received").unwrap();+ assert_eq!(received, serde_json::json!([{+ "data": "hello from a",+ "sourceIsA": true,+ }]));++ let replies = parent.take_pending_frame_messages();+ assert_eq!(replies.len(), 1);+ assert_eq!(replies[0].target_frame_id, 1);+ assert_eq!(replies[0].source_frame_id, 2);++ // Grandchild frame C inside frame A (parent_frame_id: 1)+ let frame_c = FrameRealm::new(+ &mut parent,+ 3,+ 1,+ "https://other.example/c",+ "<html><body></body></html>",+ ).unwrap();+ let result_c = frame_c.evaluate(&mut parent, r#"+ [+ parent.parent === top,+ parent.parent.frames.length,+ ]+ "#).unwrap();+ assert_eq!(result_c, serde_json::json!([true, 2]));+ }}diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 7f0672ee..1acffd3f 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -509,6 +509,8 @@ pub struct ObscuraState {pub frame_id_counter: u32,/// Which frame this state belongs to; 0 is the page's own realm.pub frame_id: u32,+ /// Which frame is the parent browsing context; 0 is the page's own realm.+ pub parent_frame_id: u32,// postMessage traffic between realms, waiting to be delivered. A realm// cannot reach another realm's context on its own, so the message is queued// here and the Page dispatches it, the same way frames themselves are@@ -792,6 +794,7 @@ impl ObscuraState {pending_frame_bytes: 0,frame_id_counter: 0,frame_id: 0,+ parent_frame_id: 0,pending_frame_messages: Vec::new(),pending_frame_message_bytes: 0,page_in_flight: Arc::new(std::sync::atomic::AtomicU32::new(0)),@@ -7290,6 +7293,7 @@ fn op_initial_frame(child.sandbox_opaque_origin = opaque;child.url = frame_url.to_string();child.frame_id = frame_id;+ child.parent_frame_id = parent_frame_id;child.about_base_url = document_base_url(&parent);child.scripting_enabled = parent.scripting_enabled && sandbox.as_deref().is_none_or(|value|value.split_ascii_whitespace().any(|token| token.eq_ignore_ascii_case("allow-scripts")));@@ -8421,6 +8425,81 @@ fn op_frame_preload_scripts(state: &OpState) -> String {})}+#[op2(fast)]+fn op_frame_parent(state: &OpState, target_frame_id: u32) -> u32 {+ if target_frame_id == 0 {+ return 0;+ }+ frame_state(state, target_frame_id).borrow().parent_frame_id+}++#[op2]+#[string]+fn op_frame_children(state: &OpState, target_frame_id: u32) -> String {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let registry = state.borrow::<Rc<RefCell<RealmStates>>>();+ let target_state = frame_state(state, target_frame_id);+ let target = target_state.borrow();+ let generation = target.document_generation;+ let mut children: Vec<(u32, String)> = Vec::new();+ let reg = registry.borrow();++ let matching_entries: Vec<u32> = reg+ .entries+ .iter()+ .filter(|(_, id, child_state)| {+ *id != target_frame_id && child_state.borrow().parent_frame_id == target_frame_id+ })+ .map(|(_, id, _)| *id)+ .collect();++ if let Some(dom) = target.dom.as_ref() {+ let mut frame_index = 0;+ for node_id in dom.descendants(dom.document()) {+ let is_frame = dom.with_node(node_id, |node| {+ node.as_element().is_some_and(|tag| {+ tag.ns.as_ref() == "http://www.w3.org/1999/xhtml"+ && (tag.local.as_ref() == "iframe" || tag.local.as_ref() == "frame")+ })+ }).unwrap_or(false);+ if !is_frame {+ continue;+ }+ let name = dom.with_node(node_id, |node| {+ node.get_attribute("name")+ .or_else(|| node.get_attribute_ns("", "name"))+ .or_else(|| node.get_attribute("id"))+ .or_else(|| node.get_attribute_ns("", "id"))+ .map(str::to_owned)+ }).flatten().unwrap_or_default();+ let child_id = reg.child_frame_for_node(&target_state, node_id)+ .or_else(|| {+ reg.frame_timers.iter().find_map(|(&id, timers)| {+ let (owner, owner_node, owner_generation) = timers.owner.as_ref()?;+ (owner.as_ptr() == std::rc::Rc::as_ptr(&target_state)+ && *owner_node == node_id+ && *owner_generation == generation)+ .then_some(id)+ })+ })+ .or_else(|| matching_entries.get(frame_index).copied());+ frame_index += 1;+ if let Some(child_id) = child_id {+ children.push((child_id, name));+ }+ }+ }++ if children.is_empty() {+ for id in matching_entries {+ children.push((id, String::new()));+ }+ }++ serde_json::to_string(&children).unwrap_or_else(|_| "[]".to_string())+ })).unwrap_or_else(|_| "[]".to_string())+}+pub fn build_extension() -> Extension {let mut ops = vec![op_dom(),@@ -8457,6 +8536,8 @@ pub fn build_extension() -> Extension {op_history_traverse(),op_frame_document_ready(),op_initial_frame(),+ op_frame_parent(),+ op_frame_children(),op_document_realm_member(),op_register_document_realm(),op_post_frame_message(),