The headless browser for AI agents and web scraping
fix(js): let a page reach into its own same-origin frame
xripa954149fd6eb
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex 9e67ea0a..9f5f2f97 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -298,6 +298,18 @@ const MAX_STYLESHEET_IMPORT_DEPTH: u8 = 4;const MAX_STYLESHEET_RESOURCES: usize = 128;const DEFAULT_NAVIGATION_TIMEOUT_MS: u64 = 30_000;+/// How many child frame realms one document may hold at once.+///+/// Real pages use a handful; the cap exists so a page that creates iframes in a+/// loop cannot make the engine hold an unbounded number of contexts and DOM+/// trees. Frames are released when the document is replaced.+fn max_live_frames() -> usize {+ std::env::var("OBSCURA_MAX_LIVE_FRAMES")+ .ok()+ .and_then(|value| value.parse().ok())+ .unwrap_or(64)+}+fn default_navigation_timeout() -> std::time::Duration {navigation_timeout_from_env_value(std::env::var("OBSCURA_NAV_TIMEOUT_MS").ok().as_deref())}@@ -973,6 +985,21 @@ impl Page {}for frame in pending {+ // A realm is a live v8::Context plus a DOM tree, and the page realm+ // holds its window and document, so nothing here can be collected+ // while the document lives. Frames are released when the document+ // is replaced, so a page that churns iframes would otherwise grow+ // the process without bound. Refuse past the cap rather than let a+ // page decide how much memory to take.+ let cap = max_live_frames();+ if self.frames.len() >= cap {+ tracing::warn!(+ "refusing a realm for frame {}: already at the {} live frame cap",+ frame.url,+ cap,+ );+ continue;+ }let realm = match self.js.as_mut().and_then(|js| {FrameRealm::new(js, frame.frame_id, frame.parent_frame_id, &frame.url, &frame.html)}) {@@ -1089,6 +1116,81 @@ impl Page {true}+ /// Discards the realms whose iframe element has left the document.+ ///+ /// A browser discards a child browsing context when its element is+ /// removed: the document and its context are torn down. Nothing here can+ /// be collected on its own, because the page realm holds each frame's+ /// window and document so that `contentWindow` can be the frame's real+ /// object, so a page that replaces an iframe repeatedly would otherwise+ /// accumulate contexts and DOM trees for the life of the document.+ ///+ /// A frame nested inside a discarded frame is reached on a later pass,+ /// once its own parent is gone.+ fn release_detached_frames(&mut self) {+ if self.frames.is_empty() {+ return;+ }+ // Each realm reports its own frames whose element is still connected.+ // Liveness is asked of the element rather than of a document query,+ // because an iframe inside a shadow root is absent from+ // `document.querySelectorAll('iframe')` — the shape a challenge widget+ // uses — and treating it as detached tears down a live frame.+ const LIVE_FRAME_IDS: &str = "__obscura_liveFrameIds()";++ let mut live: Vec<u32> = Vec::new();+ let Some(js) = self.js.as_mut() else { return };+ match js.evaluate(LIVE_FRAME_IDS) {+ Ok(value) => live.extend(serde_json::from_value::<Vec<u32>>(value).unwrap_or_default()),+ // A query that did not run says nothing about which frames are+ // gone, and an empty answer here reads as "all of them". Holding+ // them is bounded by the live-frame cap; discarding a live frame+ // is not recoverable, so leave the tree alone.+ Err(error) => {+ tracing::debug!("could not list the page's live frames: {error}");+ return;+ }+ }+ // A frame's own children are in that frame's document, not the page's.+ for index in 0..self.frames.len() {+ let Some(js) = self.js.as_mut() else { return };+ match self.frames[index].evaluate(js, LIVE_FRAME_IDS) {+ Ok(value) => {+ live.extend(serde_json::from_value::<Vec<u32>>(value).unwrap_or_default())+ }+ Err(error) => {+ tracing::debug!("could not list a frame's live frames: {error}");+ return;+ }+ }+ }++ let discarded: Vec<u32> = self+ .frames+ .iter()+ .map(|frame| frame.frame_id())+ .filter(|id| !live.contains(id))+ .collect();+ if discarded.is_empty() {+ return;+ }++ self.frames.retain(|frame| live.contains(&frame.frame_id()));+ // Dropping the realm is not enough: the page realm still names the+ // frame's window and document, which would keep the whole context+ // reachable.+ let script: String = discarded+ .iter()+ .map(|id| format!("__obscura_forgetFrame({id});"))+ .collect();+ if let Some(js) = self.js.as_mut() {+ if let Err(error) = js.execute_script("<frame-detach>", &script) {+ tracing::debug!("releasing detached frames failed: {error}");+ }+ }+ tracing::debug!("discarded {} detached frame realm(s)", discarded.len());+ }+/// Moves the frame tree forward by one step: give any fetched frame/// document a realm, then hand on any message waiting for a realm.///@@ -1098,6 +1200,7 @@ impl Page {async fn advance_frames(&mut self) -> bool {let attached = self.attach_pending_frames().await;let delivered = self.deliver_frame_messages();+ self.release_detached_frames();attached || delivered}@@ -4712,9 +4815,9 @@ mod tests {assert!(!script_response_is_executable(500));}- /// `/` embeds `/child.html`, which is enough for the page to build one- /// frame realm.- async fn spawn_child_frame_server() -> String {+ /// `/` puts its iframe inside a closed shadow root, `/plain.html` puts the+ /// same iframe straight in the document, and `/child.html` is the frame.+ async fn spawn_shadow_frame_server() -> String {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let addr = listener.local_addr().unwrap();tokio::spawn(async move {@@ -4725,9 +4828,16 @@ mod tests {let read = socket.read(&mut buf).await.unwrap_or(0);let request = String::from_utf8_lossy(&buf[..read]).to_string();let body = if request.starts_with("GET /child.html ") {- "<html><body><script>window.__ran = 1;</script></body></html>"- } else {+ "<html><body><script>window.__ran = 'YES';</script></body></html>"+ } else if request.starts_with("GET /plain.html ") {"<html><body><iframe src=\"/child.html\"></iframe></body></html>"+ } else {+ "<html><body><div id=\"host\"></div><script>\+ var r = document.getElementById('host').attachShadow({mode:'closed'});\+ var f = document.createElement('iframe');\+ f.src = '/child.html';\+ r.appendChild(f);\+ </script></body></html>"};let resp = format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",@@ -4748,7 +4858,7 @@ mod tests {#[tokio::test]async fn suspending_the_runtime_releases_the_frame_realms_it_owns() {std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");- let base = spawn_child_frame_server().await;+ let base = spawn_shadow_frame_server().await;let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network("suspend-frames".to_string(),None,@@ -4779,6 +4889,83 @@ mod tests {assert_eq!(page.frame_urls().len(), 1);}+ fn frame_page(name: &str) -> super::Page {+ let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(+ name.to_string(),+ None,+ false,+ None,+ None,+ true,+ ));+ super::Page::new(name.to_string(), context)+ }++ /// An iframe inside a shadow root is absent from+ /// `document.querySelectorAll('iframe')` — real Chrome reports 0 for it too+ /// — so a liveness check built on that query reads a live frame as detached+ /// and tears it down. That is the shape a challenge widget uses, so the+ /// frame it depends on would be discarded moments after it loaded.+ #[tokio::test(flavor = "current_thread")]+ async fn a_frame_inside_a_shadow_root_survives_the_detach_sweep() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let base = spawn_shadow_frame_server().await;+ let mut page = frame_page("shadow-frame-survives");+ page.navigate(&base).await.unwrap();+ page.settle(1_000).await;++ assert_eq!(+ page.frames.len(),+ 1,+ "the shadow-root frame was discarded as detached: {:?}",+ page.frame_urls()+ );+ // The realm is not merely alive; the page can still reach into it.+ let published = page+ .js+ .as_mut()+ .unwrap()+ .evaluate("Object.keys(globalThis.__obscura_frameObjects).length")+ .unwrap();+ assert_eq!(published.as_f64(), Some(1.0), "the page cannot reach the frame");+ }++ /// The sweep still does its job: an iframe removed from the document has+ /// its realm and every reference the page realm holds to it released.+ #[tokio::test(flavor = "current_thread")]+ async fn removing_an_iframe_releases_its_realm() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let base = spawn_shadow_frame_server().await;+ let mut page = frame_page("detached-frame-released");+ page.navigate(&format!("{base}plain.html")).await.unwrap();+ page.settle(1_000).await;+ assert_eq!(page.frames.len(), 1, "no frame to remove");++ page.js+ .as_mut()+ .unwrap()+ .evaluate("(document.querySelector('iframe').remove(), 1)")+ .unwrap();+ page.release_detached_frames();++ assert!(page.frames.is_empty(), "the detached realm was kept");+ let left = page+ .js+ .as_mut()+ .unwrap()+ .evaluate(+ "Object.keys(globalThis.__obscura_frameObjects).length\+ + Object.keys(globalThis.__obscura_frameWindows).length\+ + Object.keys(globalThis.__obscura_frameElements).length",+ )+ .unwrap();+ assert_eq!(+ left.as_f64(),+ Some(0.0),+ "a reference to the discarded frame survived, so its context cannot be collected"+ );+ }+#[tokio::test(flavor = "current_thread")]async fn suspend_resume_preserves_document_script_start_state() {let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(diff --git a/crates/obscura-cdp/src/domains/dom.rs b/crates/obscura-cdp/src/domains/dom.rsindex 55b8820f..6540fc2a 100644--- a/crates/obscura-cdp/src/domains/dom.rs+++ b/crates/obscura-cdp/src/domains/dom.rs@@ -180,7 +180,7 @@ pub async fn handle(if (globalThis._cache && globalThis._cache.has(nid)) {{\node = globalThis._cache.get(nid);\}} else {{\- var t = +Deno.core.ops.op_dom('node_type', String(nid), '');\+ var t = +Deno.core.ops.op_dom('node_type', String(nid), '', globalThis.__obscura_frameId >>> 0);\if (t === 1) node = new Element(nid);\else if (t === 9) node = globalThis.document;\else node = new Node(nid);\diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 551e7655..3b4e507c 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -16,7 +16,9 @@'__obscura_objects', '__obscura_oid', '__obscura_ua','__obscura_platform', '__obscura_ua_platform', '__obscura_ua_platform_version','__obscura_stealth', '__obscura_markTrusted', '__obscura_core_handoff',- '__obscura_frameId', '__obscura_parentFrameId',+ '__obscura_frameId', '__obscura_parentFrameId', '__obscura_frameWindows',+ '__obscura_frameObjects', '__obscura_deliverMessage',+ '__obscura_frameElements', '__obscura_liveFrameIds', '__obscura_forgetFrame','__obscura_registerLinkedStylesheet','__markParserScripts', '__obscura_hasPendingDynamicScripts','__obscura_hasPendingLoadDelayingScripts',@@ -110,8 +112,15 @@ const _DOM_TREE_MUTATION_COMMANDS = new Set(["append_child", "insert_before", "remove_child","set_inner_html", "set_inner_html_context", "set_fragment_html_executable",]);+// Which realm this bootstrap closure belongs to. Every wrapper's methods come+// from its own realm's prototypes, so a DOM call names the document it belongs+// to instead of letting the host guess from whoever is calling. That is what+// makes `iframe.contentDocument.title` read the frame's document rather than+// the caller's. Set by __obscura_init; 0 is the page.+let _realmFrameId = 0;+const _dom = (cmd, a1, a2) => {- const result = Deno.core.ops.op_dom(cmd, String(a1 ?? ""), String(a2 ?? ""));+ const result = Deno.core.ops.op_dom(cmd, String(a1 ?? ""), String(a2 ?? ""), _realmFrameId);if (_DOM_MUTATION_COMMANDS.has(cmd)) {_domMutationEpoch++;// Resize observation is tied to rendering-invalidating DOM work. The@@ -3850,6 +3859,9 @@ class Element extends Node {// message coming back out arrive with this window as its `source`.el._iframeWin._frameId = el._frameId;globalThis.__obscura_frameWindows[el._frameId] = el._iframeWin;+ // Remember the element, so "is this frame still in the page?" can be+ // asked of the element itself. See __obscura_liveFrameIds.+ globalThis.__obscura_frameElements[el._frameId] = el;} else {el._iframeDoc = new _IframeDocument('<!DOCTYPE html><html><head></head><body></body></html>', fullUrl, el);el._iframeWin = new _IframeWindow(el._iframeDoc, fullUrl);@@ -3868,6 +3880,8 @@ class Element extends Node {}get contentDocument() {if (this.localName !== 'iframe') return undefined;+ const real = _frameObjectsFor(this);+ if (real?.document) return real.document;if (this._iframeDoc) {const pageOrigin = (function(){ try { return new URL(_domParse("document_url")).origin; } catch(e) { return ''; } })();const iframeOrigin = (function(url){ try { return new URL(url).origin; } catch(e) { return ''; } })(this.src);@@ -3884,6 +3898,10 @@ class Element extends Node {}get contentWindow() {if (this.localName !== 'iframe') return undefined;+ if (_frameObjectsFor(this)) {+ const win = _frameWindowFor(this._frameId);+ if (win) return win;+ }if (!this._iframeWin) {if (this.parentNode === null) return null;this.contentDocument;@@ -11630,6 +11648,38 @@ const _iframeWindowProxyHandler = {globalThis.__obscura_frameId = 0; // 0 is the page's own realmglobalThis.__obscura_parentFrameId = 0;globalThis.__obscura_frameWindows = Object.create(null); // frame id -> its window+// frame id -> that frame's real window and document, filled by the host.+// Declared here rather than created by the host at runtime: the hide list is+// computed from this global at snapshot time, so a property the host adds later+// would stay enumerable on `window` and be visible to any script that walks it.+globalThis.__obscura_frameObjects = Object.create(null);+// frame id -> the iframe element that owns it. Holds the element until the+// frame is forgotten, which is bounded by the host's live-frame cap.+globalThis.__obscura_frameElements = Object.create(null);++// The frames of this realm whose element is still in the document.+//+// Liveness is asked of the element, not of a document query: an iframe inside+// a shadow root is absent from `document.querySelectorAll('iframe')` — the+// shape a challenge widget uses — while `isConnected` reports it correctly.+// Treating it as gone would tear down a frame that is still in the page.+globalThis.__obscura_liveFrameIds = function () {+ const live = [];+ for (const id in globalThis.__obscura_frameElements) {+ const element = globalThis.__obscura_frameElements[id];+ if (element && element.isConnected) live.push(id >>> 0);+ }+ return live;+};++// Drop everything this realm holds for a frame the host has discarded. One+// place, so a registry added later cannot be missed by the discard path: any+// surviving reference keeps the frame's context and DOM tree alive.+globalThis.__obscura_forgetFrame = function (frameId) {+ delete globalThis.__obscura_frameElements[frameId];+ delete globalThis.__obscura_frameObjects[frameId];+ delete globalThis.__obscura_frameWindows[frameId];+};function _realmOrigin() {try { return new URL(_domParse('document_url')).origin; } catch (_) { return 'null'; }@@ -11650,6 +11700,54 @@ function _sendRealmMessage(targetFrameId, data) {targetFrameId >>> 0, globalThis.__obscura_frameId >>> 0, _realmOrigin(), json);}+// The frame's own window and document, when this page is allowed to touch+// them. Same isolate, so these are the frame's real objects rather than a copy:+// `contentWindow.someGlobal` reads the frame's global and `contentDocument` is+// the document the frame's own scripts mutated.+//+// A free function, not a getter on Element.prototype: every own property of a+// public interface is visible to anything that walks it, and real Chrome has no+// such member.+function _frameObjectsFor(element) {+ const frameId = element._frameId;+ if (!frameId) return null;+ const entry = globalThis.__obscura_frameObjects[frameId];+ return entry || null;+}++// The window object this realm uses to stand for frame `frameId`, built once+// and reused so `event.source === iframe.contentWindow` holds.+//+// Once the host has published the frame's real global, that is the object,+// wrapped only to keep `postMessage` meaning "send *into* the frame from+// here". Calling the frame's own postMessage would make the frame both sender+// and receiver, losing the sender's origin and source.+function _frameWindowFor(frameId) {+ if (!frameId) return null;+ const real = globalThis.__obscura_frameObjects?.[frameId]?.window;+ const existing = globalThis.__obscura_frameWindows[frameId];+ if (!real) return existing || null;+ if (existing && existing.__obscura_wrapsRealm) return existing;++ const post = _markNative(function (data, _targetOrigin, _transfer) {+ _sendRealmMessage(frameId, data);+ });+ const win = new Proxy(real, {+ get(target, prop) {+ if (prop === 'postMessage') return post;+ if (prop === '__obscura_wrapsRealm') return true;+ // Not `receiver`: an accessor on a real global must run with the global+ // itself as `this`, not with this proxy.+ return Reflect.get(target, prop);+ },+ has(target, prop) {+ return prop === '__obscura_wrapsRealm' || Reflect.has(target, prop);+ },+ });+ globalThis.__obscura_frameWindows[frameId] = win;+ return win;+}+// The host calls this inside the target realm.globalThis.__obscura_deliverMessage = function(dataJson, origin, sourceFrameId) {let data = null;@@ -11658,7 +11756,7 @@ globalThis.__obscura_deliverMessage = function(dataJson, origin, sourceFrameId)const source = (globalThis.__obscura_frameId !== 0&& sourceFrameId === globalThis.__obscura_parentFrameId)? globalThis.parent- : (globalThis.__obscura_frameWindows[sourceFrameId] || null);+ : _frameWindowFor(sourceFrameId);try {// Trusted, because the user agent delivers this event: the sender called// postMessage, it did not dispatch this. Real embedders check the flag and@@ -14167,6 +14265,8 @@ if (typeof ShadowRoot !== 'undefined' && !ShadowRoot.prototype.elementFromPoint)}globalThis.__obscura_init = function() {+ // The host sets __obscura_frameId on a frame realm before calling this.+ _realmFrameId = globalThis.__obscura_frameId >>> 0;_fpSeed = Date.now() ^ (Math.random() * 0xFFFFFFFF >>> 0);_fpCache = null;// A real navigation just completed (this runs after set_url), so drop anydiff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rsindex e94d58e6..a5ef00f3 100644--- a/crates/obscura-js/src/frame.rs+++ b/crates/obscura-js/src/frame.rs@@ -66,6 +66,16 @@ impl FrameRealm {}parent.copy_identity_to_realm(&context);+ // Only a same-origin frame is reachable from the page. Cross-origin+ // keeps its own security token, so V8 answers `undefined` for any+ // property the page tries to read out of it, and nothing about it is+ // published below.+ let origin = origin_of(url);+ let same_origin = origin != "null" && origin == parent.page_origin();+ if same_origin {+ parent.share_security_token_with_realm(&context);+ }+let mut state = ObscuraState::new();state.dom = Some(parse_html(html));state.url = url.to_string();@@ -73,9 +83,11 @@ impl FrameRealm {parent.share_resources_with(&mut state);let realms = parent.realm_states();- realms- .borrow_mut()- .register(context.clone(), Rc::new(std::cell::RefCell::new(state)));+ realms.borrow_mut().register(+ context.clone(),+ frame_id,+ Rc::new(std::cell::RefCell::new(state)),+ );let realm = FrameRealm {context,@@ -83,7 +95,7 @@ impl FrameRealm {frame_id,parent_frame_id,url: url.to_string(),- origin: origin_of(url),+ origin,};// Both ids before init, not after: init is what installs `parent` and// `top`, and a document that runs even one script believing it is@@ -98,6 +110,11 @@ impl FrameRealm {),).ok()?;+ // Only after init, so the document the page reaches through+ // `contentDocument` is the initialized one.+ if same_origin {+ parent.publish_realm_objects(&realm.context, frame_id);+ }Some(realm)}@@ -580,7 +597,9 @@ mod tests {.map(|index| {FrameRealm::new(&mut parent,- index,+ // Frame ids start at 1: 0 names the page itself, which is+ // what a DOM call from an unframed realm reports.+ index + 1,0,&format!("https://f{index}.example/"),&format!("<html><body><h1>{index}</h1></body></html>"),@@ -840,6 +859,139 @@ mod tests {std::env::remove_var("OBSCURA_FRAME_MESSAGE_QUEUE_ENTRIES");}+ /// The page realm holds the frame's window and document, so a discarded+ /// frame leaves the page naming objects from a context the host no longer+ /// holds. Reading one must be safe. A regression here is an access+ /// violation that takes the process down, not a failed assertion.+ ///+ /// It must also not read as anything: V8 severs a global proxy when its+ /// context goes, which is the same thing a browser does to a WindowProxy+ /// when it discards a browsing context.+ #[test]+ fn a_discarded_realm_leaves_the_page_safe_to_run() {+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ {+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://parent.example/child",+ "<html><body><h1>Child</h1></body></html>",+ )+ .expect("frame realm");+ frame+ .execute_script(&mut parent, "globalThis.marker = 'child';")+ .unwrap();+ // Reachable from the page while the frame is alive.+ assert_eq!(+ parent+ .evaluate("globalThis.__obscura_frameObjects[1].window.marker")+ .unwrap(),+ serde_json::json!("child"),+ );+ }++ // Dropping the realm does not free it, and must not make touching it+ // unsafe: the page still names its window, so V8 keeps the context+ // alive and the read still answers. This is exactly why a discarded+ // frame has to have its entry removed rather than merely dropped, and+ // what `Page::release_detached_frames` is for.+ assert_eq!(+ parent+ .evaluate("globalThis.__obscura_frameObjects[1].window.marker")+ .unwrap(),+ serde_json::json!("child"),+ );+ // The page's own DOM work still resolves against the page.+ assert_eq!(+ parent.evaluate("document.body.innerHTML").unwrap(),+ serde_json::json!(""),+ );+ // Dropping the page's reference is what lets the frame be collected.+ parent+ .execute_script("p", "delete globalThis.__obscura_frameObjects[1];")+ .unwrap();+ assert_eq!(+ parent+ .evaluate("globalThis.__obscura_frameObjects[1] === undefined")+ .unwrap(),+ serde_json::json!(true),+ );+ }++ /// A DOM call names the realm it belongs to, so the page reading the+ /// frame's document gets the frame's document. Resolving from the running+ /// context instead would silently answer with the page's own.+ #[test]+ fn the_page_reads_the_frames_document_through_its_own_object() {+ let mut parent = page(+ "https://parent.example/",+ "<html><head><title>parent</title></head><body></body></html>",+ );+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://parent.example/child",+ "<html><head><title>BEFORE</title></head><body><p>child</p></body></html>",+ )+ .expect("frame realm");+ frame+ .execute_script(&mut parent, "document.title = 'RAN-IN-CHILD';")+ .unwrap();++ // Read the frame's document from the *page's* realm.+ assert_eq!(+ parent+ .evaluate("globalThis.__obscura_frameObjects[1].document.title")+ .unwrap(),+ serde_json::json!("RAN-IN-CHILD"),+ );+ assert_eq!(+ parent+ .evaluate("globalThis.__obscura_frameObjects[1].document.querySelector('p').textContent")+ .unwrap(),+ serde_json::json!("child"),+ );+ // The page's own title is untouched by any of that.+ assert_eq!(+ parent.evaluate("document.title").unwrap(),+ serde_json::json!("parent"),+ );+ }++ /// A cross-origin frame must stay opaque. Nothing about it is published to+ /// the page, and V8's own access check answers `undefined` for anything the+ /// page reaches for, because the two realms keep different security tokens.+ #[test]+ fn a_cross_origin_frame_is_not_reachable_from_the_page() {+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://other.example/f",+ "<html><body></body></html>",+ )+ .expect("frame realm");+ frame+ .execute_script(&mut parent, "globalThis.secret = 'do-not-leak';")+ .unwrap();++ assert_eq!(+ parent+ .evaluate("globalThis.__obscura_frameObjects[1] === undefined")+ .unwrap(),+ serde_json::json!(true),+ "a cross-origin frame was published to the page"+ );+ // The frame still works on its own side.+ assert_eq!(+ frame.evaluate(&mut parent, "globalThis.secret").unwrap(),+ serde_json::json!("do-not-leak"),+ );+ }+#[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.rsindex 70e65998..4f837ce9 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -459,16 +459,48 @@ pub type SharedState = Rc<RefCell<ObscuraState>>;/// writes to the *parent's* DOM.#[derive(Default)]pub struct RealmStates {- entries: Vec<(v8::Global<v8::Context>, SharedState)>,+ entries: Vec<(v8::Global<v8::Context>, u32, SharedState)>,}impl RealmStates {- pub fn register(&mut self, context: v8::Global<v8::Context>, state: SharedState) {- self.entries.push((context, state));+ pub fn register(+ &mut self,+ context: v8::Global<v8::Context>,+ frame_id: u32,+ state: SharedState,+ ) {+ self.entries.push((context, frame_id, state));}pub fn forget(&mut self, context: &v8::Global<v8::Context>) {- self.entries.retain(|(known, _)| known != context);+ self.entries.retain(|(known, _, _)| known != context);+ }++ fn by_frame_id(&self, frame_id: u32) -> Option<SharedState> {+ self.entries+ .iter()+ .find(|(_, id, _)| *id == frame_id)+ .map(|(_, _, state)| state.clone())+ }+}++/// The document of the realm a DOM call came from, named rather than inferred.+///+/// A wrapper's methods live on its own realm's prototypes, so the code running+/// for `parentPage.frameDoc.title` is the *frame's* getter even though the+/// caller is the page. Inferring the realm from the running context therefore+/// answers the wrong question for any cross-realm access, and would silently+/// read the page's document. Each realm's bootstrap closure knows its own frame+/// id and passes it, which is both correct here and cheaper than asking V8:+/// a page with no frames resolves on `frame_id == 0` alone.+pub fn frame_state(op_state: &OpState, frame_id: u32) -> SharedState {+ let page = || op_state.borrow::<SharedState>().clone();+ if frame_id == 0 {+ return page();+ }+ match op_state.try_borrow::<Rc<RefCell<RealmStates>>>() {+ Some(registry) => registry.borrow().by_frame_id(frame_id).unwrap_or_else(page),+ None => page(),}}@@ -494,8 +526,8 @@ pub fn realm_state(scope: &mut v8::HandleScope, op_state: &OpState) -> SharedStaregistry.entries.iter()- .find(|(context, _)| *context == current)- .map(|(_, state)| state.clone())+ .find(|(context, _, _)| *context == current)+ .map(|(_, _, state)| state.clone()).unwrap_or_else(page)}@@ -1036,13 +1068,13 @@ fn op_shadow_root_info(state: &OpState, host_nid: u32) -> String {#[op2]#[string]fn op_dom(- scope: &mut v8::HandleScope,state: &OpState,#[string] cmd: String,#[string] arg1: String,#[string] arg2: String,+ frame_id: u32,) -> String {- let shared = realm_state(scope, state);+ let shared = frame_state(state, frame_id);// Anti-panic boundary: a panic in a DOM op would unwind through deno_core// into V8's FFI frame, where V8_Fatal calls abort(3) and takes the whole// engine (and every CDP client) down. Catch it so one malformed selector ordiff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 5a3334c3..95ace9be 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -590,6 +590,109 @@ impl ObscuraJsRuntime {}}+ /// The origin of the document this runtime is running, or `"null"` for a+ /// scheme that has no tuple origin.+ pub(crate) fn page_origin(&self) -> String {+ let url = self.state.borrow().url.clone();+ match url::Url::parse(&url) {+ Ok(parsed) if parsed.origin().is_tuple() => parsed.origin().ascii_serialization(),+ _ => "null".to_string(),+ }+ }++ /// Gives a same-origin frame realm the page's security token.+ ///+ /// V8 access-checks property reads across contexts and answers `undefined`+ /// unless the two carry the same token, which is how a browser keeps one+ /// origin out of another's window. Two contexts of one origin must share a+ /// token, or the page reads its own frame's globals as undefined. Only+ /// ever called after an origin comparison; a cross-origin frame keeps its+ /// own token and stays opaque.+ pub(crate) fn share_security_token_with_realm(+ &mut self,+ realm: &deno_core::v8::Global<deno_core::v8::Context>,+ ) {+ use deno_core::v8;++ let main = self.runtime.main_context();+ let isolate = self.runtime.v8_isolate();+ let scope = &mut v8::HandleScope::new(isolate);+ let main = v8::Local::new(scope, main);+ let realm = v8::Local::new(scope, realm);+ let token = main.get_security_token(scope);+ realm.set_security_token(token);+ }++ /// Publishes a frame realm's own `window` and `document` objects into the+ /// page realm, under `__obscura_frameObjects[frameId]`.+ ///+ /// This is what the single isolate buys. Objects cannot cross isolates, so+ /// a parent could only ever be handed a copy or a shim; within one isolate+ /// it can hold the frame's real globals, which is what a browser gives it+ /// for a same-origin frame. `contentWindow.someGlobal` is then a plain+ /// property read of the frame's own object, and `contentDocument` is the+ /// document the frame's scripts actually mutated.+ pub(crate) fn publish_realm_objects(+ &mut self,+ realm: &deno_core::v8::Global<deno_core::v8::Context>,+ frame_id: u32,+ ) -> bool {+ use deno_core::v8;++ let main = self.runtime.main_context();+ let isolate = self.runtime.v8_isolate();+ let scope = &mut v8::HandleScope::new(isolate);++ // Read the frame's globals first, then install them in the page realm.+ // Both contexts belong to this isolate, so the handles stay valid+ // across the switch.+ let realm_context = v8::Local::new(scope, realm);+ let (frame_window, frame_document) = {+ let scope = &mut v8::ContextScope::new(scope, realm_context);+ let global = realm_context.global(scope);+ let Some(key) = v8::String::new(scope, "document") else {+ return false;+ };+ let document = global.get(scope, key.into());+ (+ v8::Global::new(scope, global),+ document.map(|value| v8::Global::new(scope, value)),+ )+ };++ let main_context = v8::Local::new(scope, main);+ let scope = &mut v8::ContextScope::new(scope, main_context);+ let global = main_context.global(scope);+ let Some(registry_key) = v8::String::new(scope, "__obscura_frameObjects") else {+ return false;+ };+ let registry = match global+ .get(scope, registry_key.into())+ .and_then(|value| value.to_object(scope))+ {+ Some(registry) if !registry.is_null_or_undefined() => registry,+ _ => {+ let fresh = v8::Object::new(scope);+ global.set(scope, registry_key.into(), fresh.into());+ fresh+ }+ };++ let entry = v8::Object::new(scope);+ let window = v8::Local::new(scope, frame_window);+ if let Some(key) = v8::String::new(scope, "window") {+ entry.set(scope, key.into(), window.into());+ }+ if let (Some(key), Some(document)) = (+ v8::String::new(scope, "document"),+ frame_document.map(|document| v8::Local::new(scope, document)),+ ) {+ entry.set(scope, key.into(), document);+ }+ let index = v8::Integer::new_from_unsigned(scope, frame_id);+ registry.set(scope, index.into(), entry.into()).unwrap_or(false)+ }+/// The table ops consult to find the calling realm's document.pub(crate) fn realm_states(&self) -> Rc<RefCell<crate::ops::RealmStates>> {self.runtime