The headless browser for AI agents and web scraping
fix(frames): release iframe realms safely
xrip964bace0097d
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex 9f5f2f97..6594b832 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -998,6 +998,7 @@ impl Page {frame.url,cap,);+ self.forget_frame_references(frame.frame_id, frame.parent_frame_id);continue;}let realm = match self.js.as_mut().and_then(|js| {@@ -1006,6 +1007,7 @@ impl Page {Some(realm) => realm,None => {tracing::warn!("could not build a realm for frame {}", frame.url);+ self.forget_frame_references(frame.frame_id, frame.parent_frame_id);continue;}};@@ -1116,6 +1118,59 @@ impl Page {true}+ /// Removes the JS references owned by the iframe's parent realm and by the+ /// page's same-origin frame table. This also covers a frame rejected before+ /// a `FrameRealm` exists, so the normal drop path cannot be skipped.+ fn forget_frame_references(&mut self, frame_id: u32, parent_frame_id: u32) {+ let script = format!(+ "if (globalThis.__obscura_frameElements[{frame_id}] &&\+ globalThis.__obscura_frameElements[{frame_id}]._frameId === {frame_id}) {{\+ globalThis.__obscura_frameElements[{frame_id}]._frameId = 0;\+ if (globalThis.__obscura_frameElements[{frame_id}]._iframeWin)\+ globalThis.__obscura_frameElements[{frame_id}]._iframeWin._frameId = 0;\+ }}\+ delete globalThis.__obscura_frameObjects[{frame_id}];\+ delete globalThis.__obscura_frameWindows[{frame_id}];\+ delete globalThis.__obscura_frameElements[{frame_id}];"+ );+ self.execute_frame_owner_script(parent_frame_id, &script);+ if parent_frame_id != 0 {+ let page_script = format!(+ "delete globalThis.__obscura_frameObjects[{frame_id}];"+ );+ if let Some(js) = self.js.as_mut() {+ if let Err(error) = js.execute_script("<frame-detach>", &page_script) {+ tracing::debug!("releasing page frame reference failed: {error}");+ }+ }+ }+ }++ /// Executes cleanup in the realm that owns the iframe element. Nested+ /// iframe registries live in their parent frame, not in the page realm.+ fn execute_frame_owner_script(&mut self, parent_frame_id: u32, script: &str) {+ if parent_frame_id == 0 {+ if let Some(js) = self.js.as_mut() {+ if let Err(error) = js.execute_script("<frame-detach>", script) {+ tracing::debug!("releasing frame references failed: {error}");+ }+ }+ return;+ }++ let Some(index) = self+ .frames+ .iter()+ .position(|frame| frame.frame_id() == parent_frame_id)+ else {+ return;+ };+ let Some(js) = self.js.as_mut() else { return };+ if let Err(error) = self.frames[index].execute_script(js, script) {+ tracing::debug!("releasing nested frame references failed: {error}");+ }+ }+/// Discards the realms whose iframe element has left the document.////// A browser discards a child browsing context when its element is@@ -1165,29 +1220,23 @@ impl Page {}}- let discarded: Vec<u32> = self+ let discarded: Vec<(u32, u32)> = self.frames.iter()- .map(|frame| frame.frame_id())- .filter(|id| !live.contains(id))+ .map(|frame| (frame.frame_id(), frame.parent_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}");- }+ // Clean owner realms before dropping any parent. This matters for a+ // nested child whose iframe registry lives in a parent that is also+ // being removed during this pass.+ for &(frame_id, parent_frame_id) in &discarded {+ self.forget_frame_references(frame_id, parent_frame_id);}+ self.frames.retain(|frame| live.contains(&frame.frame_id()));tracing::debug!("discarded {} detached frame realm(s)", discarded.len());}@@ -2623,10 +2672,16 @@ impl Page {/// higher-priority automation commands.#[doc(hidden)]pub async fn run_autonomous_event_loop_turn(&mut self) -> Result<bool, String> {- match self.js.as_mut() {+ let reached_idle = match self.js.as_mut() {Some(js) => js.run_autonomous_event_loop_turn().await,None => Ok(true),- }+ }?;+ // Dynamic iframe fetches finish on the page event loop, but their+ // realms must be built by Page between turns. Keep the autonomous CDP+ // pump on the same generic frame path as settle(), so a client that+ // stays attached can observe and run child documents as they arrive.+ let frame_work = self.advance_frames().await;+ Ok(reached_idle && !frame_work)}async fn settle_runtime_for_duration(js: &mut ObscuraJsRuntime, duration_ms: u64) {@@ -3080,6 +3135,7 @@ impl Page {}pub fn navigate_blank(&mut self) {+ self.frames.clear();self.js = None;self.url = Some(Url::parse("about:blank").unwrap());self.dom = Some(parse_html(@@ -4868,7 +4924,7 @@ mod tests {true,));let mut page = super::Page::new("suspend-frames".to_string(), context);- page.navigate(&base).await.unwrap();+ page.navigate(&format!("{base}plain.html")).await.unwrap();assert_eq!(page.frame_urls().len(),1,@@ -4885,7 +4941,7 @@ mod tests {// The page still works afterwards: resuming rebuilds the runtime, and// navigating again builds the frames of the new document.page.resume_js();- page.navigate(&base).await.unwrap();+ page.navigate(&format!("{base}plain.html")).await.unwrap();assert_eq!(page.frame_urls().len(), 1);}diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rsindex 03bc5075..7036d096 100644--- a/crates/obscura-cdp/src/dispatch.rs+++ b/crates/obscura-cdp/src/dispatch.rs@@ -290,6 +290,7 @@ impl CdpContext {pub fn remove_page(&mut self, id: &str) {self.pages.retain(|p| p.id != id);self.current_loader_ids.remove(id);+ self.announced_frames.remove(id);#[cfg(feature = "render")]{let removed: Vec<String> = selfdiff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 3b4e507c..51a9e163 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -17,8 +17,8 @@'__obscura_platform', '__obscura_ua_platform', '__obscura_ua_platform_version','__obscura_stealth', '__obscura_markTrusted', '__obscura_core_handoff','__obscura_frameId', '__obscura_parentFrameId', '__obscura_frameWindows',- '__obscura_frameObjects', '__obscura_deliverMessage',- '__obscura_frameElements', '__obscura_liveFrameIds', '__obscura_forgetFrame',+ '__obscura_frameObjects', '__obscura_frameElements', '__obscura_deliverMessage',+ '__obscura_liveFrameIds', '__obscura_forgetFrame','__obscura_registerLinkedStylesheet','__markParserScripts', '__obscura_hasPendingDynamicScripts','__obscura_hasPendingLoadDelayingScripts',@@ -762,9 +762,10 @@ globalThis.console = {};let _tid = 0;-const _clearedTimers = new Set();const _intervals = new Set();const _nativeTimerIds = new Map();+const _timerStates = new Map();+const _frameTimerStates = new Map();const __obscuraPendingTimeoutDeadlines = new Map();Object.defineProperty(globalThis, '__obscura_nextPendingTimeoutDelay', {value: function() {@@ -805,11 +806,16 @@ const _scheduleAfter = (delay, fn) => {// because its continuation is an ordinary microtask, V8 reports the frame as// the microtask context and the ops the callback makes still resolve against// the frame's own document. Frame timer ids are negative so clearTimeout can- // tell the two queues apart.+ // tell the two queues apart. Keep cancellation state by native id and remove+ // it on either fire or clear, so repeated clearTimeout calls do not grow a+ // permanent set.if (globalThis.__obscura_frameId) {const frameTimerId = -(++_frameTimerSeq);+ const state = { cancelled: false };+ _frameTimerStates.set(frameTimerId, state);Deno.core.ops.op_sleep(d).then(() => {- if (_cancelledFrameTimers.delete(frameTimerId)) return;+ _frameTimerStates.delete(frameTimerId);+ if (state.cancelled) return;Deno.core.ops.op_begin_render_task?.();fn();});@@ -827,7 +833,11 @@ const _scheduleAfter = (delay, fn) => {};const _cancelScheduled = (nativeId) => {- if (nativeId < 0) _cancelledFrameTimers.add(nativeId);+ if (nativeId < 0) {+ const state = _frameTimerStates.get(nativeId);+ if (state) state.cancelled = true;+ _frameTimerStates.delete(nativeId);+ }else Deno.core.cancelTimer(nativeId);};@@ -855,13 +865,16 @@ globalThis.setTimeout = (fn, delay = 0, ...args) => {if (f === null) return ++_tid;const id = ++_tid;const normalizedDelay = Math.max(0, Number(delay) || 0);+ const state = { cancelled: false };const nativeId = _scheduleAfter(normalizedDelay, () => {+ _timerStates.delete(id);_nativeTimerIds.delete(id);__obscuraPendingTimeoutDeadlines.delete(id);- if (_clearedTimers.has(id)) return;+ if (state.cancelled) return;try { f(...args); } catch(e) { console.error("Timer error:", e); }});if (nativeId !== undefined) {+ _timerStates.set(id, state);_nativeTimerIds.set(id, nativeId);__obscuraPendingTimeoutDeadlines.set(id, performance.now() + normalizedDelay);}@@ -869,7 +882,9 @@ globalThis.setTimeout = (fn, delay = 0, ...args) => {};globalThis.clearTimeout = (id) => {- _clearedTimers.add(id);+ const state = _timerStates.get(id);+ if (state) state.cancelled = true;+ _timerStates.delete(id);__obscuraPendingTimeoutDeadlines.delete(id);const nativeId = _nativeTimerIds.get(id);if (nativeId !== undefined) {@@ -3146,6 +3161,10 @@ class Element extends Node {: null;const value = String(v);_dom("set_attribute", this._nid, n + "\0" + value);+ if (n === "src" && this.localName === "iframe") {+ if (value && value !== "about:blank") this._loadIframeSrc(value);+ else this._resetIframeFrame();+ }if (this._nullNamespaceAttrs instanceof Map) {this._nullNamespaceAttrs.set(n, value);}@@ -3828,9 +3847,18 @@ class Element extends Node {}set src(v) {this.setAttribute("src", v);- if (this.localName === 'iframe' && v && v !== 'about:blank') {- this._loadIframeSrc(v);+ }+ _resetIframeFrame() {+ const oldId = this._frameId;+ if (oldId) {+ delete globalThis.__obscura_frameElements[oldId];+ delete globalThis.__obscura_frameWindows[oldId];}+ this._frameId = 0;+ this._iframeLoadingUrl = null;+ this._iframeDoc = new _IframeDocument(+ '<!DOCTYPE html><html><head></head><body></body></html>', 'about:blank', this);+ this._iframeWin = new _IframeWindow(this._iframeDoc, 'about:blank');}_loadIframeSrc(url) {let fullUrl = url;@@ -3840,9 +3868,11 @@ class Element extends Node {// Both the src setter and the parser sweep in __obscura_init reach here, so// a frame the page assigned before init must not be fetched a second time.if (this._iframeLoadingUrl === fullUrl) return;+ this._resetIframeFrame();this._iframeLoadingUrl = fullUrl;const el = this;fetch(fullUrl, {mode: 'no-cors'}).then(async resp => {+ if (el._iframeLoadingUrl !== fullUrl) return;if (resp.ok || resp.type === 'opaque') {const html = await resp.text();// Hand the document to the host, which gives this frame a realm of its@@ -3852,16 +3882,17 @@ class Element extends Node {const box = el.getBoundingClientRect();el._frameId = Deno.core.ops.op_frame_document_ready(fullUrl, html, Math.round(box.width) || 300, Math.round(box.height) || 150);+ if (el._frameId) globalThis.__obscura_frameElements[el._frameId] = el;el._iframeDoc = new _IframeDocument(html, fullUrl, el);el._iframeWin = new _IframeWindow(el._iframeDoc, fullUrl);// Bind the window to the realm the host just queued. This is what makes// posting into the frame reach the frame's own listeners, and makes a// 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;+ if (el._frameId) {+ el._iframeWin._frameId = el._frameId;+ globalThis.__obscura_frameWindows[el._frameId] = el._iframeWin;+ 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);@@ -3872,6 +3903,7 @@ class Element extends Node {// directly bypasses listeners registered via addEventListener.el.dispatchEvent(new Event('load'));}).catch(() => {+ if (el._iframeLoadingUrl !== fullUrl) return;el._iframeDoc = new _IframeDocument('<!DOCTYPE html><html><head></head><body></body></html>', fullUrl, el);el._iframeWin = new _IframeWindow(el._iframeDoc, fullUrl);@@ -11648,15 +11680,15 @@ 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 -> the iframe element that owns it. The host uses this composed-tree+// registry to retain frames inside closed shadow roots without keeping removed+// elements alive after their browsing context is released.+globalThis.__obscura_frameElements = Object.create(null);// 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 insidediff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 4f837ce9..dc8c7707 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -145,6 +145,8 @@ pub struct ObscuraState {// `op_frame_document_ready` queues here and the Page drains it between// event loop turns. Same shape as `pending_binding_calls`.pub pending_frames: Vec<PendingFrame>,+ /// Total URL and HTML bytes held by `pending_frames`.+ pub pending_frame_bytes: usize,pub frame_id_counter: u32,/// Which frame this state belongs to; 0 is the page's own realm.pub frame_id: u32,@@ -297,6 +299,7 @@ impl ObscuraState {fetched_urls: Vec::new(),js_network_events: Vec::new(),pending_frames: Vec::new(),+ pending_frame_bytes: 0,frame_id_counter: 0,frame_id: 0,pending_frame_messages: Vec::new(),@@ -3507,8 +3510,12 @@ async fn op_sleep(#[number] millis: u64) {tokio::time::sleep(std::time::Duration::from_millis(millis)).await;}+const MAX_PENDING_FRAME_DOCUMENTS: usize = 64;+const MAX_PENDING_FRAME_BYTES: usize = 32 * 1024 * 1024;+// Hands a fetched frame document to the host and returns the id the frame will-// have. The realm itself is built later, by whoever owns the runtime.+// have. The realm itself is built later, by whoever owns the runtime. A zero+// id means the bounded native queue refused the document.#[op2(fast)]fn op_frame_document_ready(scope: &mut v8::HandleScope,@@ -3524,8 +3531,23 @@ fn op_frame_document_ready(let parent_frame_id = realm_state(scope, state).borrow().frame_id;let gs = state.borrow::<SharedState>().clone();let mut gs = gs.borrow_mut();- gs.frame_id_counter += 1;- let frame_id = gs.frame_id_counter;+ let bytes = url.len().saturating_add(html.len());+ if gs.pending_frames.len() >= MAX_PENDING_FRAME_DOCUMENTS+ || gs.pending_frame_bytes.saturating_add(bytes) > MAX_PENDING_FRAME_BYTES+ {+ tracing::warn!(+ "dropping frame document: {} pending documents, {} bytes",+ gs.pending_frames.len(),+ gs.pending_frame_bytes,+ );+ return 0;+ }+ let Some(frame_id) = gs.frame_id_counter.checked_add(1) else {+ tracing::warn!("frame id space exhausted");+ return 0;+ };+ gs.frame_id_counter = frame_id;+ gs.pending_frame_bytes = gs.pending_frame_bytes.saturating_add(bytes);gs.pending_frames.push(PendingFrame {frame_id,url: url.to_string(),diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 95ace9be..92c2dc13 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -706,7 +706,9 @@ impl ObscuraJsRuntime {/// The op queues onto the page's state whichever frame asked, so a frame/// nested inside a frame is drained here too.pub fn take_pending_frames(&self) -> Vec<crate::ops::PendingFrame> {- std::mem::take(&mut self.state.borrow_mut().pending_frames)+ let mut state = self.state.borrow_mut();+ state.pending_frame_bytes = 0;+ std::mem::take(&mut state.pending_frames)}/// postMessage traffic waiting to be delivered to another realm.diff --git a/crates/obscura/tests/child_frame_scripts.rs b/crates/obscura/tests/child_frame_scripts.rsindex acd0e75f..e850b202 100644--- a/crates/obscura/tests/child_frame_scripts.rs+++ b/crates/obscura/tests/child_frame_scripts.rs@@ -15,6 +15,34 @@ const PARENT_HTML: &str = r#"<!doctype html><html><head><title>parent</title></h</script></body></html>"#;+const ATTRIBUTE_PARENT_HTML: &str = r#"<!doctype html><html><head><title>parent</title></head><body>+<script>+ var f = document.createElement('iframe');+ f.setAttribute('src', '/child.html');+ document.body.appendChild(f);+</script>+</body></html>"#;++const SHADOW_PARENT_HTML: &str = r#"<!doctype html><html><head><title>parent</title></head><body>+<script>+ var host = document.createElement('div');+ var root = host.attachShadow({mode: 'open'});+ var f = document.createElement('iframe');+ f.setAttribute('src', '/child.html');+ root.appendChild(f);+ document.body.appendChild(host);+</script>+</body></html>"#;++const RESET_PARENT_HTML: &str = r#"<!doctype html><html><head><title>parent</title></head><body>+<script>+ var f = document.createElement('iframe');+ f.src = '/child.html';+ document.body.appendChild(f);+ setTimeout(function () { f.src = 'about:blank'; }, 150);+</script>+</body></html>"#;+const STATIC_PARENT_HTML: &str = r#"<!doctype html><html><head><title>parent</title></head><body><iframe src="/child.html"></iframe></body></html>"#;@@ -119,6 +147,48 @@ async fn a_child_frame_runs_its_own_script() {assert_eq!(page.evaluate("window.__ran"), serde_json::Value::Null);}+#[tokio::test]+async fn a_child_frame_set_by_attribute_runs_its_own_script() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let base = spawn_server(ATTRIBUTE_PARENT_HTML);++ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&base).await.unwrap();+ page.settle(2000).await;++ assert_eq!(+ page.frame_urls(),+ vec![format!("{base}/child.html")],+ "setAttribute('src') did not start the child document"+ );+ assert_eq!(+ page.evaluate_in_frame(0, "window.__ran").unwrap(),+ serde_json::json!("YES"),+ );+}++#[tokio::test]+async fn a_shadow_dom_child_frame_stays_alive_and_runs_its_script() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let base = spawn_server(SHADOW_PARENT_HTML);++ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&base).await.unwrap();+ page.settle(2000).await;++ assert_eq!(+ page.frame_urls(),+ vec![format!("{base}/child.html")],+ "a shadow-root iframe realm was released as detached"+ );+ assert_eq!(+ page.evaluate_in_frame(0, "window.__ran").unwrap(),+ serde_json::json!("YES"),+ );+}+/// The whole point of a child frame having a scripting context: it can report/// its result back out. This is the reporter's `parentGot` assertion.#[tokio::test]@@ -219,3 +289,65 @@ async fn a_static_child_frame_runs_its_own_script() {serde_json::json!("YES"),);}++#[tokio::test]+async fn a_rejected_child_frame_does_not_leave_js_references() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ std::env::set_var("OBSCURA_MAX_LIVE_FRAMES", "0");+ let base = spawn_server(STATIC_PARENT_HTML);++ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&base).await.unwrap();+ page.settle(2000).await;++ assert!(page.frame_urls().is_empty(), "the frame cap was not applied");+ for registry in [+ "__obscura_frameObjects",+ "__obscura_frameWindows",+ "__obscura_frameElements",+ ] {+ assert_eq!(+ page.evaluate(&format!("Object.keys(globalThis.{registry}).length"))+ .as_f64(),+ Some(0.0),+ "rejected frame stayed in {registry}",+ );+ }+}++#[tokio::test]+async fn navigating_blank_releases_child_realms() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let base = spawn_server(STATIC_PARENT_HTML);++ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&base).await.unwrap();+ page.settle(2000).await;+ assert_eq!(page.frame_urls().len(), 1);++ page.goto("about:blank").await.unwrap();+ assert!(page.frame_urls().is_empty(), "old frame realm survived navigation");+}++#[tokio::test]+async fn changing_iframe_src_releases_the_previous_realm() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let base = spawn_server(RESET_PARENT_HTML);++ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&base).await.unwrap();+ page.settle(1000).await;++ assert!(page.frame_urls().is_empty(), "old src realm survived replacement");+ for registry in ["__obscura_frameWindows", "__obscura_frameElements"] {+ assert_eq!(+ page.evaluate(&format!("Object.keys(globalThis.{registry}).length"))+ .as_f64(),+ Some(0.0),+ "old iframe stayed in {registry}",+ );+ }+}