The headless browser for AI agents and web scraping
fix(js): give child iframes a realm so their scripts run
xrip6a4683df356a
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex 975c6ec7..345e6f10 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -2,6 +2,7 @@ use std::sync::Arc;use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};use obscura_dom::{parse_html, DomTree};+use obscura_js::frame::FrameRealm;use obscura_js::runtime::ObscuraJsRuntime;use obscura_net::{CallbackRegistry, ObscuraHttpClient, ObscuraNetError, RequestCallback, ResourceRequest,@@ -218,6 +219,10 @@ pub struct Page {pub frame_id: String,pub url: Option<Url>,pub dom: Option<DomTree>,+ /// Live child frame realms, in creation order. Declared before `js` on+ /// purpose: a realm holds a V8 handle into that isolate, and fields drop in+ /// declaration order, so the frames must go first.+ pub frames: Vec<FrameRealm>,pub js: Option<ObscuraJsRuntime>,pub lifecycle: LifecycleState,pub http_client: Arc<ObscuraHttpClient>,@@ -888,6 +893,7 @@ impl Page {frame_id,url: None,dom: None,+ frames: Vec::new(),js: None,lifecycle: LifecycleState::Idle,http_client,@@ -950,6 +956,107 @@ impl Page {false}+ /// Gives every frame document the page has fetched a realm of its own, and+ /// runs the scripts that came with it (issue #600).+ ///+ /// Building a realm needs the whole runtime, which an op cannot reach, so+ /// the JS side queues the fetched document and this drains the queue between+ /// event loop turns. Reports whether anything was attached, so a caller can+ /// settle and come back for frames that these frames created.+ async fn attach_pending_frames(&mut self) -> bool {+ let pending = match self.js.as_ref() {+ Some(js) => js.take_pending_frames(),+ None => return false,+ };+ if pending.is_empty() {+ return false;+ }++ for frame in pending {+ let realm = match self.js.as_mut().and_then(|js| {+ FrameRealm::new(js, frame.frame_id, frame.parent_frame_id, &frame.url, &frame.html)+ }) {+ Some(realm) => realm,+ None => {+ tracing::warn!("could not build a realm for frame {}", frame.url);+ continue;+ }+ };++ // A frame's scripts resolve and are fetched against the frame's own+ // URL, so they need fetching before run_document_scripts, which+ // resolves sources synchronously.+ let wanted = match self.js.as_mut() {+ Some(js) => realm.external_script_urls(js),+ None => Vec::new(),+ };+ let mut sources: std::collections::HashMap<String, String> =+ std::collections::HashMap::new();+ for url in wanted {+ let Ok(parsed) = Url::parse(&url) else { continue };+ if self.should_block_url(&url) {+ continue;+ }+ match self.do_fetch(&parsed).await {+ Ok(response) => {+ sources.insert(url, String::from_utf8_lossy(&response.body).into_owned());+ }+ Err(error) => {+ tracing::warn!("frame script {} failed: {}", url, error);+ }+ }+ }++ if let Some(js) = self.js.as_mut() {+ if let Err(error) = realm.set_viewport(+ js,+ frame.viewport_width as f64,+ frame.viewport_height as f64,+ ) {+ tracing::debug!("frame {} viewport setup failed: {error}", frame.url);+ }+ // Page.addScriptToEvaluateOnNewDocument applies to every new+ // document, including child frames. Debug hooks and browser+ // automation setup must be present before frame scripts run.+ for source in &self.preload_scripts {+ if let Err(error) = realm.execute_script(js, source) {+ tracing::debug!("frame {} preload failed: {error}", frame.url);+ }+ }+ for problem in realm.run_document_scripts(js, |url| sources.get(url).cloned()) {+ tracing::debug!("frame {}: {}", frame.url, problem);+ }+ // The frame's scripts have run, so its document is loaded. Say+ // so: everything a widget defers to DOMContentLoaded or load+ // hangs on this, which is most of its interface.+ if let Err(error) = realm.dispatch_load_events(js) {+ tracing::debug!("frame {} load events failed: {error}", frame.url);+ }+ }+ self.frames.push(realm);+ }+ true+ }++ /// URLs of the page's live child frames, in creation order.+ pub fn frame_urls(&self) -> Vec<String> {+ self.frames+ .iter()+ .map(|frame| frame.url().to_string())+ .collect()+ }++ /// Evaluates an expression inside one of the page's child frames.+ pub fn evaluate_in_frame(+ &mut self,+ index: usize,+ expression: &str,+ ) -> Result<serde_json::Value, String> {+ let realm = self.frames.get(index).ok_or("no such frame")?;+ let js = self.js.as_mut().ok_or("no runtime")?;+ realm.evaluate(js, expression)+ }+/// Update the page's CSS viewport. Calling this before navigation makes/// responsive scripts observe it from their first instruction; calling it/// on a live page mirrors CDP's device-metrics override surfaces.@@ -1076,6 +1183,9 @@ impl Page {// attacker-controlled state, trigger a navigation, and then// run code in the next document's context.if self.js.is_some() {+ // Every frame realm holds a V8 handle into this isolate, so the+ // frames of the outgoing document must go before the runtime does.+ self.frames.clear();let _ = self.js.take();}@@ -2276,17 +2386,30 @@ impl Page {return;}let settle_started = std::time::Instant::now();- if let Some(js) = &mut self.js {- if std::env::var_os("OBSCURA_STRICT_SETTLE").is_some() {- Self::settle_runtime_for_duration(js, max_ms).await;- } else {- // A deno_core event loop remains "busy" for any future timer,- // including analytics intervals and animation loops which do- // not make the page more ready. Require a short window without- // observable document/network/script activity instead. The- // absolute caller budget and V8 watchdog still bound both- // asynchronous work and synchronous microtask storms.- let _ = js.run_event_loop_until_quiescent(max_ms, 150).await;+ // Pump, then give any frame document that finished fetching a realm of+ // its own. Attaching one runs its scripts, which can start timers,+ // fetches and further frames, so keep alternating until no new frame+ // appears or the budget is gone (issue #600).+ loop {+ let remaining = max_ms.saturating_sub(settle_started.elapsed().as_millis() as u64);+ if remaining == 0 {+ break;+ }+ if let Some(js) = &mut self.js {+ if std::env::var_os("OBSCURA_STRICT_SETTLE").is_some() {+ Self::settle_runtime_for_duration(js, remaining).await;+ } else {+ // A deno_core event loop remains "busy" for any future timer,+ // including analytics intervals and animation loops which do+ // not make the page more ready. Require a short window without+ // observable document/network/script activity instead. The+ // absolute caller budget and V8 watchdog still bound both+ // asynchronous work and synchronous microtask storms.+ let _ = js.run_event_loop_until_quiescent(remaining, 150).await;+ }+ }+ if !self.attach_pending_frames().await {+ break;}}#[cfg(feature = "render")]@@ -2321,6 +2444,11 @@ impl Page {if let Some(js) = &mut self.js {Self::settle_runtime_for_duration(js, duration_ms).await;}+ // A fixed wait must retain its full wall clock, so frames get their+ // realms once at the end instead of being interleaved as in `settle`.+ // Their document scripts still run; only their own deferred work is+ // left for a later settle.+ self.attach_pending_frames().await;}/// Advance one wake-driven browser task for a continuously owned page.diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex e8495742..2a7cb706 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -15,7 +15,8 @@'__obscura_errors', '__obscura_init', '__obscura_hide_list','__obscura_objects', '__obscura_oid', '__obscura_ua','__obscura_platform', '__obscura_ua_platform', '__obscura_ua_platform_version',- '__obscura_stealth', '__obscura_markTrusted',+ '__obscura_stealth', '__obscura_markTrusted', '__obscura_core_handoff',+ '__obscura_frameId', '__obscura_parentFrameId','__obscura_registerLinkedStylesheet','__markParserScripts', '__obscura_hasPendingDynamicScripts','__obscura_hasPendingLoadDelayingScripts',@@ -64,6 +65,14 @@}})();+// Handoff for child frame realms. deno_core binds ops into the main context+// only, so a realm restored from the snapshot arrives with its own empty+// `Deno.core.ops`. The host reads this to take the main realm's bound op table+// and to find each new realm's own table to fill, then deletes the global in+// the same step, so page script never sees it (see runtime.rs+// `take_ops_handoff` / `share_ops_with_realm`).+globalThis.__obscura_core_handoff = Deno.core;+globalThis.__obscura_errors = [];globalThis.addEventListener = globalThis.addEventListener || function(){};@@ -762,6 +771,9 @@ Object.defineProperty(globalThis, '__obscura_nextPendingTimeoutDelay', {configurable: false,});+let _frameTimerSeq = 0;+const _cancelledFrameTimers = new Set();+const _scheduleAfter = (delay, fn) => {const d = Math.max(0, Number(delay) || 0);// HTML timers queue tasks even when their delay is zero. Treating a@@ -777,6 +789,23 @@ const _scheduleAfter = (delay, fn) => {if (!Deno.core.ops.op_async_runtime_available()) {return undefined;}+ // A child frame realm cannot use deno_core's timer queue: op_timer_queue+ // reads per-context state that only a deno_core-created context carries, and+ // a realm restored from the snapshot has none, so queueing from a frame+ // dereferences uninitialized memory. A host sleep does the same job, and+ // 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.+ if (globalThis.__obscura_frameId) {+ const frameTimerId = -(++_frameTimerSeq);+ Deno.core.ops.op_sleep(d).then(() => {+ if (_cancelledFrameTimers.delete(frameTimerId)) return;+ Deno.core.ops.op_begin_render_task?.();+ fn();+ });+ return frameTimerId;+ }// The callback runs only when the embedder pumps the event loop, after the// current microtask checkpoint.return Deno.core.queueUserTimer(0, false, d, () => {@@ -788,6 +817,11 @@ const _scheduleAfter = (delay, fn) => {});};+const _cancelScheduled = (nativeId) => {+ if (nativeId < 0) _cancelledFrameTimers.add(nativeId);+ else Deno.core.cancelTimer(nativeId);+};+// Timers accept a string first arg per the HTML spec (e.g. the Aliyun WAF// `acw_sc__v2` challenge drives `setTimeout('reload(arg2)', 2)`). A string is// compiled and run in global scope, identical to a real browser; otherwise the@@ -830,7 +864,7 @@ globalThis.clearTimeout = (id) => {__obscuraPendingTimeoutDeadlines.delete(id);const nativeId = _nativeTimerIds.get(id);if (nativeId !== undefined) {- Deno.core.cancelTimer(nativeId);+ _cancelScheduled(nativeId);_nativeTimerIds.delete(id);}};@@ -3794,10 +3828,21 @@ class Element extends Node {if (!url.includes('://')) {try { fullUrl = new URL(url, _domParse("document_url") || "about:blank").href; } catch(e) {}}+ // 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._iframeLoadingUrl = fullUrl;const el = this;fetch(fullUrl, {mode: 'no-cors'}).then(async resp => {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+ // own and runs the scripts that came with it (issue #600). The shim+ // document below stays: it is what the parent reads through+ // contentDocument.+ 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);el._iframeDoc = new _IframeDocument(html, fullUrl, el);el._iframeWin = new _IframeWindow(el._iframeDoc, fullUrl);} else {@@ -14050,6 +14095,16 @@ globalThis.__obscura_init = function() {// version from navigator.userAgent and read the platform from the page// globals, so every stealth surface agrees without a per-mode override.+ // A parser-created <iframe src> never went through the src setter, so+ // nothing had started its load and the frame stayed empty (issue #600).+ // This also runs inside a frame realm, so a frame nested in a frame loads+ // by the same path, with op_frame_document_ready recording the caller as+ // its parent.+ for (const frame of globalThis.document.querySelectorAll('iframe')) {+ const src = frame.getAttribute('src');+ if (src && src !== 'about:blank') frame._loadIframeSrc(src);+ }+// Hide internals (_*, obscura, Obscura). The set of keys is static at// snapshot-build time, so we precompute it ONCE below (after this// function definition) and reuse it on every page init. Was andiff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rsnew file mode 100644index 00000000..e4592e1c--- /dev/null+++ b/crates/obscura-js/src/frame.rs@@ -0,0 +1,731 @@+//! Child frame realms.+//!+//! An iframe is a separate browsing context: its own JavaScript realm, its own+//! DOM tree, and its own origin. Without this, a frame's HTML is fetched and its+//! body dropped into a detached document in the *parent's* realm, so no script+//! inside a frame ever runs (issue #600).+//!+//! A frame realm is a second `v8::Context` in the page's isolate. Three things+//! make that practical:+//!+//! - The startup snapshot already contains the whole bootstrap, so a restored+//! context arrives with every DOM class installed. A realm costs a context+//! restore, not a re-parse.+//! - The realm's op table is filled from the page realm's, so every shim in the+//! frame can call ops.+//! - Each realm registers its document in `RealmStates`, and an op looks up the+//! realm that called it. Making a realm current around the host's calls into+//! it is not enough, because a frame's timers and settled promises re-enter+//! JavaScript straight from the event loop.+//!+//! Staying in one isolate is what lets same-origin frames share objects with+//! their parent, the way `iframe.contentWindow.document` does in a browser. A+//! second isolate could never do that.++use std::rc::Rc;++use obscura_dom::parse_html;++use crate::ops::{ObscuraState, RealmStates};+use crate::runtime::ObscuraJsRuntime;++/// One child browsing context: its own realm, document and origin, living in+/// the page's isolate.+pub struct FrameRealm {+ context: deno_core::v8::Global<deno_core::v8::Context>,+ /// Held so the frame's entry can be taken out again when the frame dies.+ realms: Rc<std::cell::RefCell<RealmStates>>,+ frame_id: u32,+ parent_frame_id: u32,+ url: String,+ origin: String,+}++impl Drop for FrameRealm {+ fn drop(&mut self) {+ self.realms.borrow_mut().forget(&self.context);+ }+}++impl FrameRealm {+ /// Builds a frame realm around an already-fetched document.+ ///+ /// The frame inherits the page's browser identity and its shared resources,+ /// by copying them from the parent rather than by being told them, so the+ /// two cannot drift apart.+ pub fn new(+ parent: &mut ObscuraJsRuntime,+ frame_id: u32,+ parent_frame_id: u32,+ url: &str,+ html: &str,+ ) -> Option<Self> {+ let context = parent.create_realm_context()?;+ if !parent.share_ops_with_realm(&context) {+ return None;+ }+ parent.copy_identity_to_realm(&context);++ let mut state = ObscuraState::new();+ state.dom = Some(parse_html(html));+ state.url = url.to_string();+ state.frame_id = frame_id;+ parent.share_resources_with(&mut state);++ let realms = parent.realm_states();+ realms+ .borrow_mut()+ .register(context.clone(), Rc::new(std::cell::RefCell::new(state)));++ let realm = FrameRealm {+ context,+ realms,+ frame_id,+ parent_frame_id,+ url: url.to_string(),+ origin: origin_of(url),+ };+ // Both ids before init, not after: init is what installs `parent` and+ // `top`, and a document that runs even one script believing it is+ // top-level has already taken the wrong branch.+ realm+ .run(+ parent,+ &format!(+ "globalThis.__obscura_frameId = {frame_id};\+ globalThis.__obscura_parentFrameId = {parent_frame_id};\+ globalThis.__obscura_init();"+ ),+ )+ .ok()?;+ Some(realm)+ }++ /// Fires the frame document's lifecycle events, in spec order.+ ///+ /// The page's own document gets these; a frame's did not, and a document+ /// that is never told it finished loading will not run any of the work+ /// scripts defer until then. That is most of what a widget does: a frame+ /// can talk to its parent perfectly and still never build its interface,+ /// which looks like a rendering problem and is a lifecycle one.+ pub fn dispatch_load_events(&self, parent: &mut ObscuraJsRuntime) -> Result<(), String> {+ self.execute_script(+ parent,+ "globalThis.__documentReadyState__ = 'interactive';\+ try { document.dispatchEvent(new Event('DOMContentLoaded', \+ { bubbles: false, cancelable: false })); } catch (_) {}\+ try { window.dispatchEvent(new Event('DOMContentLoaded', \+ { bubbles: false, cancelable: false })); } catch (_) {}\+ globalThis.__documentReadyState__ = 'complete';\+ try { document.dispatchEvent(new Event('readystatechange')); } catch (_) {}\+ if (typeof window.onload === 'function') { try { window.onload(); } catch (_) {} }\+ try { window.dispatchEvent(new Event('load', \+ { bubbles: false, cancelable: false })); } catch (_) {}",+ )+ }++ pub fn frame_id(&self) -> u32 {+ self.frame_id+ }++ /// Sets the frame document's viewport before any of its scripts run.+ pub fn set_viewport(+ &self,+ parent: &mut ObscuraJsRuntime,+ width: f64,+ height: f64,+ ) -> Result<(), String> {+ let width = if width.is_finite() && width > 0.0 {+ width+ } else {+ 300.0+ };+ let height = if height.is_finite() && height > 0.0 {+ height+ } else {+ 150.0+ };+ self.execute_script(+ parent,+ &format!(+ "globalThis.innerWidth={width};globalThis.innerHeight={height};\+ if(globalThis.visualViewport){{\+ globalThis.visualViewport.width={width};\+ globalThis.visualViewport.height={height};\+ }}"+ ),+ )+ }++ pub fn parent_frame_id(&self) -> u32 {+ self.parent_frame_id+ }++ pub fn url(&self) -> &str {+ &self.url+ }++ /// The frame's origin, or `"null"` for a document with an opaque origin.+ pub fn origin(&self) -> &str {+ &self.origin+ }++ /// Whether script from `other_origin` may reach into this frame's DOM. Two+ /// opaque origins are never same-origin, which is why `"null"` never+ /// matches.+ pub fn is_same_origin_as(&self, other_origin: &str) -> bool {+ self.origin != "null" && self.origin == other_origin+ }++ /// Runs `source` in the frame's realm. Ops called from it find the frame's+ /// document by looking up the realm they were called from.+ fn run(&self, parent: &mut ObscuraJsRuntime, source: &str) -> Result<String, String> {+ parent.eval_in_realm(&self.context, source)+ }++ /// Runs a script inside the frame, reporting a script error as `Err`.+ pub fn execute_script(+ &self,+ parent: &mut ObscuraJsRuntime,+ source: &str,+ ) -> Result<(), String> {+ self.run(parent, source).map(|_| ())+ }++ /// Evaluates an expression inside the frame and decodes it as JSON.+ pub fn evaluate(+ &self,+ parent: &mut ObscuraJsRuntime,+ expression: &str,+ ) -> Result<serde_json::Value, String> {+ let json = self.run(parent, &format!("JSON.stringify({expression})"))?;+ serde_json::from_str(&json).map_err(|error| error.to_string())+ }++ /// Runs the frame document's classic scripts, in document order.+ ///+ /// `load_external` resolves a `src=` script to its source text; returning+ /// `None` skips it, which is what a failed subresource fetch looks like to+ /// the page. One script throwing does not stop the ones after it, matching+ /// how a browser treats separate classic scripts.+ ///+ /// Module scripts are skipped and reported: they need the frame's own module+ /// loader, which is not wired up yet.+ ///+ /// Returns one message per script that failed or was skipped.+ pub fn run_document_scripts(+ &self,+ parent: &mut ObscuraJsRuntime,+ load_external: impl Fn(&str) -> Option<String>,+ ) -> Vec<String> {+ let scripts = match self.list_scripts(parent) {+ Ok(scripts) => scripts,+ Err(error) => return vec![error],+ };++ let mut problems = Vec::new();+ for (index, script) in scripts.iter().enumerate() {+ if !script.is_classic() {+ if script.type_attribute == "module" {+ problems.push(format!("frame module script {index} skipped: not supported"));+ }+ continue;+ }++ let (name, source) = if script.src.is_empty() {+ (format!("inline {index}"), script.text.clone())+ } else {+ let resolved = self.resolve(&script.src);+ match load_external(&resolved) {+ Some(source) => (resolved, source),+ None => {+ problems.push(format!("frame script {resolved} could not be loaded"));+ continue;+ }+ }+ };+ if source.trim().is_empty() {+ continue;+ }+ if let Err(error) = self.execute_script(parent, &source) {+ problems.push(format!("frame script {name} failed: {error}"));+ }+ }+ problems+ }++ /// Absolute URLs of the frame's `src=` classic scripts, in document order.+ ///+ /// A caller that fetches over the network needs the list before running+ /// anything, because `run_document_scripts` resolves sources synchronously.+ pub fn external_script_urls(&self, parent: &mut ObscuraJsRuntime) -> Vec<String> {+ self.list_scripts(parent)+ .unwrap_or_default()+ .iter()+ .filter(|script| script.is_classic() && !script.src.is_empty())+ .map(|script| self.resolve(&script.src))+ .collect()+ }++ /// Resolves a subresource URL against the frame's own document URL, not the+ /// parent's. A relative `src` in a frame is relative to the frame.+ fn resolve(&self, src: &str) -> String {+ url::Url::parse(&self.url)+ .and_then(|base| base.join(src))+ .map(|url| url.to_string())+ .unwrap_or_else(|_| src.to_string())+ }++ fn list_scripts(&self, parent: &mut ObscuraJsRuntime) -> Result<Vec<DocumentScript>, String> {+ let listed = self.evaluate(+ parent,+ r#"[...document.querySelectorAll('script')].map(node => ({+ src: node.getAttribute('src') || '',+ type: (node.getAttribute('type') || '').toLowerCase(),+ text: node.textContent || '',+ }))"#,+ );+ match listed {+ Ok(value) => Ok(serde_json::from_value(value).unwrap_or_default()),+ Err(error) => Err(format!("could not list frame scripts: {error}")),+ }+ }+}++#[derive(serde::Deserialize)]+struct DocumentScript {+ src: String,+ #[serde(rename = "type")]+ type_attribute: String,+ text: String,+}++impl DocumentScript {+ /// An empty type, or a JavaScript MIME type, is a classic script. Anything+ /// else is data or a module.+ fn is_classic(&self) -> bool {+ self.type_attribute.is_empty()+ || matches!(+ self.type_attribute.as_str(),+ "text/javascript" | "application/javascript" | "text/ecmascript"+ )+ }+}++/// Serializes an origin the way `location.origin` does, using `"null"` for+/// schemes that have no tuple origin.+fn origin_of(url: &str) -> String {+ match url::Url::parse(url) {+ Ok(parsed) => {+ let origin = parsed.origin();+ if origin.is_tuple() {+ origin.ascii_serialization()+ } else {+ "null".to_string()+ }+ }+ Err(_) => "null".to_string(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::cell::RefCell;++ fn page(url: &str, html: &str) -> ObscuraJsRuntime {+ let mut runtime = ObscuraJsRuntime::new();+ runtime.set_dom(parse_html(html));+ runtime.set_url(url);+ runtime.run_page_init();+ runtime+ }++ #[test]+ fn frame_has_its_own_realm_dom_and_origin() {+ let mut parent = page(+ "https://parent.example/page",+ "<html><body><h1>Parent</h1></body></html>",+ );+ parent+ .execute_script("p", "globalThis.marker = 'parent';")+ .unwrap();++ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://child.example/frame",+ "<html><body><h1>Child</h1></body></html>",+ )+ .expect("frame realm");++ frame+ .execute_script(&mut parent, "globalThis.marker = 'child';")+ .unwrap();++ // Separate realm: own globals, own DOM, own URL.+ assert_eq!(+ frame+ .evaluate(&mut parent, "document.querySelector('h1').textContent")+ .unwrap(),+ serde_json::json!("Child")+ );+ assert_eq!(+ frame.evaluate(&mut parent, "globalThis.marker").unwrap(),+ serde_json::json!("child")+ );+ assert_eq!(+ frame.evaluate(&mut parent, "location.href").unwrap(),+ serde_json::json!("https://child.example/frame")+ );++ // The parent keeps its own document and globals throughout.+ assert_eq!(+ parent+ .evaluate("document.querySelector('h1').textContent")+ .unwrap(),+ serde_json::json!("Parent")+ );+ assert_eq!(+ parent.evaluate("globalThis.marker").unwrap(),+ serde_json::json!("parent")+ );++ assert_eq!(frame.origin(), "https://child.example");+ assert_eq!(frame.frame_id(), 1);+ assert!(!frame.is_same_origin_as("https://parent.example"));+ assert!(frame.is_same_origin_as("https://child.example"));+ }++ #[test]+ fn frame_uses_its_embedding_viewport() {+ let mut parent = page(+ "https://parent.example/page",+ "<html><body><iframe style='width:300px;height:65px'></iframe></body></html>",+ );+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://child.example/frame",+ "<html><body></body></html>",+ )+ .expect("frame realm");++ frame.set_viewport(&mut parent, 300.0, 65.0).unwrap();+ assert_eq!(+ frame+ .evaluate(+ &mut parent,+ "[innerWidth,innerHeight,visualViewport.width,visualViewport.height]",+ )+ .unwrap(),+ serde_json::json!([300, 65, 300, 65]),+ );+ }++ /// A frame must not look like a different browser than its parent. Anti-bot+ /// code fingerprints inside the frame and compares it with the top document.+ #[test]+ fn frame_inherits_the_parent_browser_identity() {+ let user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) TestAgent/150.0.0.0";+ let mut parent = ObscuraJsRuntime::new();+ parent.set_user_agent(user_agent);+ parent.set_platform("Win32", "Windows", "19.0.0");+ parent.set_dom(parse_html("<html><body></body></html>"));+ parent.set_url("https://parent.example/");+ parent.run_page_init();++ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://child.example/f",+ "<html><body></body></html>",+ )+ .expect("frame realm");++ for surface in [+ "navigator.userAgent",+ "navigator.platform",+ "navigator.userAgentData.platform",+ ] {+ assert_eq!(+ frame.evaluate(&mut parent, surface).unwrap(),+ parent.evaluate(surface).unwrap(),+ "frame and parent disagree on {surface}"+ );+ }+ assert_eq!(+ frame.evaluate(&mut parent, "navigator.userAgent").unwrap(),+ serde_json::json!(user_agent)+ );+ }++ /// The capability the frame realm exists for: scripts that arrived with the+ /// frame's document run, in order, against the frame's own DOM.+ #[test]+ fn frame_runs_its_document_scripts_in_order() {+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://child.example/dir/page",+ r#"<html><body><div id="out"></div>+ <script>window.log = ['inline1'];</script>+ <script src="first.js"></script>+ <script src="/second.js"></script>+ <script>window.log.push('inline2');+ document.getElementById('out').textContent = window.log.join(',');</script>+ </body></html>"#,+ )+ .expect("frame realm");++ let requested = RefCell::new(Vec::new());+ let problems = frame.run_document_scripts(&mut parent, |url| {+ requested.borrow_mut().push(url.to_string());+ match url {+ "https://child.example/dir/first.js" => Some("window.log.push('ext1');".into()),+ "https://child.example/second.js" => Some("window.log.push('ext2');".into()),+ _ => None,+ }+ });++ assert!(problems.is_empty(), "unexpected problems: {problems:?}");+ // Relative and root-relative src resolve against the frame's URL, not+ // the parent's.+ assert_eq!(+ requested.into_inner(),+ vec![+ "https://child.example/dir/first.js".to_string(),+ "https://child.example/second.js".to_string(),+ ]+ );+ assert_eq!(+ frame+ .evaluate(&mut parent, "document.getElementById('out').textContent")+ .unwrap(),+ serde_json::json!("inline1,ext1,ext2,inline2")+ );+ // The frame's document writes never touch the parent's DOM.+ assert_eq!(+ parent.evaluate("document.body.innerHTML").unwrap(),+ serde_json::json!("")+ );+ }++ #[test]+ fn one_bad_frame_script_does_not_stop_the_rest() {+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://child.example/",+ r#"<html><body>+ <script>window.log = ['a'];</script>+ <script>throw new Error('boom');</script>+ <script src="missing.js"></script>+ <script type="module">window.log.push('module');</script>+ <script>window.log.push('b');</script>+ </body></html>"#,+ )+ .expect("frame realm");++ let problems = frame.run_document_scripts(&mut parent, |_| None);++ assert_eq!(+ frame.evaluate(&mut parent, "window.log.join(',')").unwrap(),+ serde_json::json!("a,b")+ );+ assert_eq!(problems.len(), 3, "problems: {problems:?}");+ assert!(problems.iter().any(|p| p.contains("boom")), "{problems:?}");+ assert!(+ problems.iter().any(|p| p.contains("missing.js")),+ "{problems:?}"+ );+ assert!(problems.iter().any(|p| p.contains("module")), "{problems:?}");+ }++ #[test]+ fn many_frames_can_be_alive_at_once() {+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ let frames: Vec<FrameRealm> = (0..4)+ .map(|index| {+ FrameRealm::new(+ &mut parent,+ index,+ 0,+ &format!("https://f{index}.example/"),+ &format!("<html><body><h1>{index}</h1></body></html>"),+ )+ .expect("frame realm")+ })+ .collect();++ for (index, frame) in frames.iter().enumerate() {+ frame+ .execute_script(&mut parent, &format!("globalThis.n = {index};"))+ .unwrap();+ }+ // Out-of-order access must be safe: each frame carries its own state.+ for (index, frame) in frames.iter().enumerate().rev() {+ assert_eq!(+ frame.evaluate(&mut parent, "globalThis.n").unwrap().as_f64(),+ Some(index as f64)+ );+ assert_eq!(+ frame+ .evaluate(&mut parent, "document.querySelector('h1').textContent")+ .unwrap(),+ serde_json::json!(index.to_string())+ );+ }+ }++ /// The hard case. A frame's deferred work re-enters JavaScript from the+ /// event loop, long after the host last called into the frame, so nothing+ /// can have made the frame "current" for it. It has to find its own+ /// document anyway.+ #[tokio::test(flavor = "current_thread")]+ async fn a_frames_deferred_work_still_sees_the_frames_document() {+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://child.example/",+ "<html><body></body></html>",+ )+ .expect("frame realm");++ // 50ms, not 0: a zero delay drains as a microtask while the host is+ // still inside the frame, which would hide the bug this guards.+ frame+ .execute_script(+ &mut parent,+ "setTimeout(() => { document.body.setAttribute('data-who', location.href); }, 50);",+ )+ .unwrap();+ parent.run_event_loop_bounded(300).await.unwrap();++ assert_eq!(+ frame+ .evaluate(&mut parent, "document.body.getAttribute('data-who')")+ .unwrap(),+ serde_json::json!("https://child.example/"),+ "the frame's timer did not write to the frame's own document"+ );+ assert_eq!(+ parent+ .evaluate("document.body.getAttribute('data-who')")+ .unwrap(),+ serde_json::Value::Null,+ "the frame's timer wrote to the parent's document"+ );+ }++ /// A frame's timers cannot go through deno_core's queue: `op_timer_queue`+ /// reads per-context state that only a deno_core-created context carries,+ /// and queueing from a snapshot realm dereferences uninitialized memory,+ /// which aborts the process rather than failing a test. This is the guard+ /// against that path ever being restored.+ #[tokio::test(flavor = "current_thread")]+ async fn a_frame_timer_fires_without_deno_cores_timer_queue() {+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://child.example/",+ "<html><body></body></html>",+ )+ .expect("frame realm");+ frame+ .execute_script(&mut parent, "setTimeout(() => { globalThis.fired = 1; }, 50);")+ .unwrap();+ parent.run_event_loop_bounded(300).await.unwrap();+ assert_eq!(+ frame.evaluate(&mut parent, "globalThis.fired || 0").unwrap(),+ serde_json::json!(1),+ "the frame's timer callback never ran"+ );+ }++ /// Frame timers run on a separate queue from the page's, so cancelling one+ /// has its own path and its own way to go wrong.+ #[tokio::test(flavor = "current_thread")]+ async fn clear_timeout_cancels_a_frame_timer() {+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://child.example/",+ "<html><body></body></html>",+ )+ .expect("frame realm");+ frame+ .execute_script(+ &mut parent,+ "globalThis.kept = 0;\+ const cancelled = setTimeout(() => { globalThis.kept = 1; }, 50);\+ setTimeout(() => { globalThis.kept = 2; }, 50);\+ clearTimeout(cancelled);",+ )+ .unwrap();+ parent.run_event_loop_bounded(300).await.unwrap();+ assert_eq!(+ frame.evaluate(&mut parent, "globalThis.kept").unwrap(),+ serde_json::json!(2),+ "clearTimeout did not cancel exactly the frame timer it was given"+ );+ }++ /// V8 reports the frame as the microtask context, so a promise continuation+ /// resolves ops against the frame without any help from the host.+ #[tokio::test(flavor = "current_thread")]+ async fn a_frames_promise_continuation_sees_the_frames_document() {+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://child.example/",+ "<html><body></body></html>",+ )+ .expect("frame realm");+ frame+ .execute_script(+ &mut parent,+ "Promise.resolve().then(() => { \+ document.body.setAttribute('data-who', location.href); });",+ )+ .unwrap();+ parent.run_event_loop_bounded(300).await.unwrap();+ assert_eq!(+ frame+ .evaluate(&mut parent, "document.body.getAttribute('data-who')")+ .unwrap(),+ serde_json::json!("https://child.example/"),+ );+ }++ #[test]+ fn opaque_origin_frames_are_never_same_origin() {+ let mut parent = page("https://parent.example/", "<html><body></body></html>");+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "about:blank",+ "<html><body></body></html>",+ )+ .expect("frame realm");+ assert_eq!(frame.origin(), "null");+ assert!(!frame.is_same_origin_as("null"));+ assert!(!frame.is_same_origin_as("https://parent.example"));+ }+}diff --git a/crates/obscura-js/src/lib.rs b/crates/obscura-js/src/lib.rsindex 81944929..d071cdfe 100644--- a/crates/obscura-js/src/lib.rs+++ b/crates/obscura-js/src/lib.rs@@ -1,4 +1,5 @@pub mod cdp_watchdog;+pub mod frame;mod import_map;pub mod markdown;pub mod module_loader;diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 029aafbf..9857058f 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -8,6 +8,7 @@ use deno_core::op2;use deno_core::Extension;#[cfg(feature = "render")]use deno_core::JsBuffer;+use deno_core::v8;use deno_core::OpState;use obscura_dom::{DomTree, NodeData, NodeId};use obscura_dom::tree::{AttachShadowError, ShadowRootMode};@@ -139,6 +140,14 @@ pub struct ObscuraState {// drained by the Page into its network_events so the CDP layer emits// Network.requestWillBeSent / responseReceived for them (issue #406).pub js_network_events: Vec<JsNetworkEvent>,+ // Frame documents that have been fetched and are waiting for a realm.+ // Building one needs the whole runtime, which an op cannot reach, so+ // `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>,+ pub frame_id_counter: u32,+ /// Which frame this state belongs to; 0 is the page's own realm.+ pub frame_id: u32,/// Requests initiated by this runtime only. Browser contexts share their/// transport client across pages, so the client's aggregate counter cannot/// be used as a page-readiness signal.@@ -228,6 +237,17 @@ pub struct ObscuraState {pub(crate) already_started_scripts: RefCell<HashSet<NodeId>>,}+/// A frame document waiting to be given a realm.+pub struct PendingFrame {+ pub frame_id: u32,+ pub url: String,+ pub html: String,+ pub viewport_width: u64,+ pub viewport_height: u64,+ /// The frame that holds this one; 0 when the page does.+ pub parent_frame_id: u32,+}+impl ObscuraState {pub fn new() -> Self {ObscuraState {@@ -252,6 +272,9 @@ impl ObscuraState {network_response_body_counter: 0,fetched_urls: Vec::new(),js_network_events: Vec::new(),+ pending_frames: Vec::new(),+ frame_id_counter: 0,+ frame_id: 0,page_in_flight: Arc::new(std::sync::atomic::AtomicU32::new(0)),activity_generation: 0,document_generation: 0,@@ -400,6 +423,56 @@ fn response_body_byte_limit() -> usize {pub type SharedState = Rc<RefCell<ObscuraState>>;+/// Which document belongs to which realm.+///+/// An op has to read the state of the realm that *called* it. Making a realm+/// "current" around the host's own calls into it is not enough: a frame's+/// deferred work, a timer firing or a promise settling, re-enters JavaScript+/// from the event loop, where nothing had the chance to swap anything. Without+/// this a frame's `setTimeout` callback runs with the frame's globals but+/// writes to the *parent's* DOM.+#[derive(Default)]+pub struct RealmStates {+ entries: Vec<(v8::Global<v8::Context>, SharedState)>,+}++impl RealmStates {+ pub fn register(&mut self, context: v8::Global<v8::Context>, state: SharedState) {+ self.entries.push((context, state));+ }++ pub fn forget(&mut self, context: &v8::Global<v8::Context>) {+ self.entries.retain(|(known, _)| known != context);+ }+}++/// The state of the realm running right now, or the page's when the caller is+/// the page itself.+///+/// A page with no frames pays only an `is_empty` check: looking up the current+/// context is not free, and `op_dom` is the hottest op in the system.+pub fn realm_state(scope: &mut v8::HandleScope, op_state: &OpState) -> SharedState {+ let page = || op_state.borrow::<SharedState>().clone();+ let registry = match op_state.try_borrow::<Rc<RefCell<RealmStates>>>() {+ Some(registry) => registry.clone(),+ None => return page(),+ };+ let registry = registry.borrow();+ if registry.entries.is_empty() {+ return page();+ }+ // Not `get_current_context`: an op is a native function bound in the page+ // realm, so V8 reports that realm as current no matter who called it. This+ // one answers "whose code is running", which is the question.+ let current = scope.get_entered_or_microtask_context();+ registry+ .entries+ .iter()+ .find(|(context, _)| *context == current)+ .map(|(_, state)| state.clone())+ .unwrap_or_else(page)+}+#[derive(Clone, Copy, Debug, Default)]struct RenderMutationImpact {connected: bool,@@ -937,11 +1010,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,) -> String {+ let shared = realm_state(scope, state);// 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 or@@ -949,7 +1024,7 @@ fn op_dom(// No per-call clone: on the happy path this is just a landing pad, so the// hot DOM path (querySelector/getAttribute/...) pays nothing measurable.std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {- op_dom_inner(state, cmd, arg1, arg2)+ op_dom_inner(shared, cmd, arg1, arg2)})).unwrap_or_else(|_| {tracing::error!("op_dom panicked; returning null");@@ -957,8 +1032,7 @@ fn op_dom(})}-fn op_dom_inner(state: &OpState, cmd: String, arg1: String, arg2: String) -> String {- let shared = state.borrow::<SharedState>().clone();+fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) -> String {{// Scroll offsets belong to a node at its current tree position.// Temporary box/style loss keeps that latent state, but DOM removal,@@ -3261,8 +3335,8 @@ fn validate_fetch_url(url: &url::Url, allow_private_network: bool) -> Result<(),#[op2]#[string]-fn op_get_cookies(state: &OpState) -> String {- let gs = state.borrow::<SharedState>().clone();+fn op_get_cookies(scope: &mut v8::HandleScope, state: &OpState) -> String {+ let gs = realm_state(scope, state);let gs = gs.borrow();let jar = match &gs.cookie_jar {Some(j) => j,@@ -3276,8 +3350,8 @@ fn op_get_cookies(state: &OpState) -> String {}#[op2(fast)]-fn op_set_cookie(state: &OpState, #[string] cookie_str: &str) {- let gs = state.borrow::<SharedState>().clone();+fn op_set_cookie(scope: &mut v8::HandleScope, state: &OpState, #[string] cookie_str: &str) {+ let gs = realm_state(scope, state);let gs = gs.borrow();let jar = match &gs.cookie_jar {Some(j) => j,@@ -3290,14 +3364,64 @@ fn op_set_cookie(state: &OpState, #[string] cookie_str: &str) {jar.set_cookie_from_js(cookie_str, &url);}+// A frame that navigates itself must not move the top document. Recording the+// navigation against the calling realm keeps it inside that frame.#[op2(fast)]-fn op_navigate(state: &OpState, #[string] url: &str, #[string] method: &str, #[string] body: &str) {- let gs = state.borrow::<SharedState>().clone();+fn op_navigate(+ scope: &mut v8::HandleScope,+ state: &OpState,+ #[string] url: &str,+ #[string] method: &str,+ #[string] body: &str,+) {+ let gs = realm_state(scope, state);let mut gs = gs.borrow_mut();gs.url = url.to_string();gs.pending_navigation = Some((url.to_string(), method.to_string(), body.to_string()));}+/// Resolves after `millis`, as the timer source for child frame realms.+///+/// deno_core's own timer queue is not usable from a frame: `op_timer_queue`+/// resolves per-context state that only a deno_core-created context carries,+/// and a snapshot-restored realm has none. This resolves an ordinary promise+/// instead, and V8 reports the frame as the microtask context, so the ops a+/// timer callback makes still find the frame's own document.+#[op2(async)]+async fn op_sleep(#[number] millis: u64) {+ tokio::time::sleep(std::time::Duration::from_millis(millis)).await;+}++// 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.+#[op2(fast)]+fn op_frame_document_ready(+ scope: &mut v8::HandleScope,+ state: &OpState,+ #[string] url: &str,+ #[string] html: &str,+ #[number] viewport_width: u64,+ #[number] viewport_height: u64,+) -> u32 {+ // Whoever called this is the new frame's parent, which is how a frame+ // nested two deep gets `parent` pointing at the frame above it rather than+ // at the page.+ 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;+ gs.pending_frames.push(PendingFrame {+ frame_id,+ url: url.to_string(),+ html: html.to_string(),+ viewport_width,+ viewport_height,+ parent_frame_id,+ });+ frame_id+}+/// Whether async host work can be scheduled without aborting the isolate.////// Some low-level embedders intentionally execute a synchronous expression@@ -4021,6 +4145,8 @@ pub fn build_extension() -> Extension {op_get_cookies(),op_set_cookie(),op_navigate(),+ op_frame_document_ready(),+ op_sleep(),op_async_runtime_available(),op_posted_task(),op_binding_called(),diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 5e593cf9..c2385750 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -145,6 +145,21 @@ pub struct ObscuraJsRuntime {/// those URLs so a dependency later encountered as a top-level script is a/// browser-style no-op instead of a second deno_core `mod_evaluate` call.evaluated_module_specifiers: HashMap<String, Result<(), String>>,+ /// The bound op table, taken from bootstrap at construction and removed from+ /// the global in the same step. Child frame realms are handed this object so+ /// their shims can call ops; nothing else can reach it, including page+ /// script.+ ops_handoff: Option<deno_core::v8::Global<deno_core::v8::Value>>,+}++/// Renders a caught V8 exception as a message for realm evaluation errors.+fn exception_text(+ scope: &mut deno_core::v8::TryCatch<'_, deno_core::v8::HandleScope<'_>>,+) -> String {+ match scope.exception() {+ Some(exception) => exception.to_rust_string_lossy(scope),+ None => "unknown error".to_string(),+ }}/// A fetched and instantiated module graph whose evaluation is intentionally@@ -297,7 +312,14 @@ impl ObscuraJsRuntime {..Default::default()});- runtime.op_state().borrow_mut().put(state_clone);+ {+ let op_state = runtime.op_state();+ let mut op_state = op_state.borrow_mut();+ op_state.put(state_clone);+ // Empty until a frame realm exists, which is what keeps the+ // lookup free for pages that have no frames.+ op_state.put(Rc::new(RefCell::new(crate::ops::RealmStates::default())));+ }let isolate_handle = runtime.v8_isolate().thread_safe_handle();let heap_limit_state = std::sync::Arc::new(HeapLimitState::default());@@ -317,7 +339,7 @@ impl ObscuraJsRuntime {(runtime, isolate_handle, heap_limit_state)};- ObscuraJsRuntime {+ let mut instance = ObscuraJsRuntime {runtime,state,object_store: HashMap::new(),@@ -329,7 +351,259 @@ impl ObscuraJsRuntime {module_evaluations: HashMap::new(),loaded_module_specifiers,evaluated_module_specifiers: HashMap::new(),+ ops_handoff: None,+ };+ // Take the op table before any page script can run, and drop the global+ // that exposed it in the same step.+ instance.ops_handoff = instance.take_ops_handoff();+ instance+ }++ /// Creates an additional realm in this isolate: a second `v8::Context`.+ ///+ /// The startup snapshot already contains the whole bootstrap (see+ /// `build.rs`), so a context restored from it arrives with every DOM class+ /// and shim installed. Building a realm is therefore a context restore, not+ /// a re-parse of the whole bootstrap.+ ///+ /// The new context has no ops: deno_core binds those into the main context+ /// only. Use [`Self::share_ops_with_realm`] to give it the same `Deno.core`+ /// object, which is legal because native function objects are shareable+ /// between contexts of one isolate.+ pub(crate) fn create_realm_context(+ &mut self,+ ) -> Option<deno_core::v8::Global<deno_core::v8::Context>> {+ let context = {+ let isolate = self.runtime.v8_isolate();+ let scope = &mut deno_core::v8::HandleScope::new(isolate);+ let context = deno_core::v8::Context::from_snapshot(+ scope,+ 1,+ deno_core::v8::ContextOptions::default(),+ )+ .or_else(|| {+ deno_core::v8::Context::from_snapshot(+ scope,+ 0,+ deno_core::v8::ContextOptions::default(),+ )+ })?;+ deno_core::v8::Global::new(scope, context)+ };+ Some(context)+ }++ /// Takes the ops object bootstrap handed out, and removes the handoff from+ /// the global so page script can never reach `Deno.core.ops`.+ ///+ /// deno_core hides `globalThis.Deno` after setup and bootstrap keeps its+ /// reference in a private const, so this handoff is the only way for the+ /// host to reach the bound op functions and pass them to a child realm.+ fn take_ops_handoff(&mut self) -> Option<deno_core::v8::Global<deno_core::v8::Value>> {+ use deno_core::v8;++ let main = self.runtime.main_context();+ let isolate = self.runtime.v8_isolate();+ let scope = &mut v8::HandleScope::new(isolate);+ let context = v8::Local::new(scope, main);+ let scope = &mut v8::ContextScope::new(scope, context);++ let handoff_key = v8::String::new(scope, "__obscura_core_handoff")?;+ let ops_key = v8::String::new(scope, "ops")?;+ let global = context.global(scope);++ let core = global.get(scope, handoff_key.into())?;+ let core = core.to_object(scope)?;+ let ops = core.get(scope, ops_key.into())?;+ if !ops.is_object() {+ return None;}+ let ops = v8::Global::new(scope, ops);+ global.delete(scope, handoff_key.into());+ Some(ops)+ }++ /// Points a child realm's `Deno.core.ops` at the main realm's ops object.+ ///+ /// A realm restored from the snapshot has its own `Deno.core` with an empty+ /// ops table, and its bootstrap captured that exact object, so filling the+ /// `ops` table on it is enough to give every shim in that realm a working+ /// op surface. The functions are shared, not copied: same isolate.+ pub(crate) fn share_ops_with_realm(+ &mut self,+ realm: &deno_core::v8::Global<deno_core::v8::Context>,+ ) -> bool {+ use deno_core::v8;++ let Some(ops) = self.ops_handoff.clone() else {+ return false;+ };+ let isolate = self.runtime.v8_isolate();+ let scope = &mut v8::HandleScope::new(isolate);+ let context = v8::Local::new(scope, realm);+ let scope = &mut v8::ContextScope::new(scope, context);++ let Some(handoff_key) = v8::String::new(scope, "__obscura_core_handoff") else {+ return false;+ };+ let Some(ops_key) = v8::String::new(scope, "ops") else {+ return false;+ };+ let global = context.global(scope);+ let Some(core) = global.get(scope, handoff_key.into()) else {+ return false;+ };+ let Some(core) = core.to_object(scope) else {+ return false;+ };+ // `Deno.core.ops` is non-writable and non-configurable, so the table+ // cannot be swapped wholesale: V8 reports success and changes nothing.+ // Copy the bound op functions into the realm's existing table instead.+ let Some(target) = core+ .get(scope, ops_key.into())+ .and_then(|value| value.to_object(scope))+ else {+ return false;+ };+ let source = v8::Local::new(scope, ops);+ let Some(source) = source.to_object(scope) else {+ return false;+ };+ let Some(names) = source.get_own_property_names(scope, Default::default()) else {+ return false;+ };+ let mut copied = 0;+ for index in 0..names.length() {+ let Some(key) = names.get_index(scope, index) else {+ continue;+ };+ let Some(value) = source.get(scope, key) else {+ continue;+ };+ if target.set(scope, key, value).unwrap_or(false) {+ copied += 1;+ }+ }+ // The child realm must not expose the handoff to frame script either.+ global.delete(scope, handoff_key.into());+ copied > 0+ }++ /// Runs `source` inside `realm` and returns its value as a string. Errors+ /// come back as `Err(message)`.+ pub(crate) fn eval_in_realm(+ &mut self,+ realm: &deno_core::v8::Global<deno_core::v8::Context>,+ source: &str,+ ) -> Result<String, String> {+ use deno_core::v8;++ let isolate = self.runtime.v8_isolate();+ let scope = &mut v8::HandleScope::new(isolate);+ let context = v8::Local::new(scope, realm);+ let scope = &mut v8::ContextScope::new(scope, context);+ let scope = &mut v8::TryCatch::new(scope);++ let code = v8::String::new(scope, source).ok_or("source too large")?;+ let script = match v8::Script::compile(scope, code, None) {+ Some(script) => script,+ None => return Err(exception_text(scope)),+ };+ match script.run(scope) {+ Some(value) => Ok(value.to_rust_string_lossy(scope)),+ None => Err(exception_text(scope)),+ }+ }++ /// Copies the browser-identity globals from the main realm into `realm`.+ ///+ /// A frame must present the same identity as its parent: anti-bot code+ /// fingerprints inside the frame and compares it with the top document.+ /// Copying the values the parent already has makes that true by+ /// construction, instead of relying on a caller to reapply the same+ /// settings to both.+ pub(crate) fn copy_identity_to_realm(+ &mut self,+ realm: &deno_core::v8::Global<deno_core::v8::Context>,+ ) {+ use deno_core::v8;++ const IDENTITY_GLOBALS: [&str; 7] = [+ "__obscura_ua",+ "__obscura_platform",+ "__obscura_ua_platform",+ "__obscura_ua_platform_version",+ "__obscura_stealth",+ "__obscura_geo_lat",+ "__obscura_geo_lon",+ ];++ let main = self.runtime.main_context();+ let isolate = self.runtime.v8_isolate();+ let scope = &mut v8::HandleScope::new(isolate);++ let main_context = v8::Local::new(scope, main);+ let mut carried = Vec::new();+ {+ let scope = &mut v8::ContextScope::new(scope, main_context);+ let global = main_context.global(scope);+ for name in IDENTITY_GLOBALS {+ let Some(key) = v8::String::new(scope, name) else {+ continue;+ };+ match global.get(scope, key.into()) {+ Some(value) if !value.is_undefined() => {+ carried.push((name, v8::Global::new(scope, value)));+ }+ _ => {}+ }+ }+ }++ let realm_context = v8::Local::new(scope, realm);+ let scope = &mut v8::ContextScope::new(scope, realm_context);+ let global = realm_context.global(scope);+ for (name, value) in carried {+ let Some(key) = v8::String::new(scope, name) else {+ continue;+ };+ let value = v8::Local::new(scope, value);+ global.set(scope, key.into(), value);+ }+ }++ /// Gives a frame's state the resources the page owns: cookie jar, HTTP+ /// client, callbacks and the stealth transport. A frame shares these with+ /// its page, exactly as it shares them in a browser.+ pub(crate) fn share_resources_with(&self, frame: &mut ObscuraState) {+ let parent = self.state.borrow();+ frame.cookie_jar = parent.cookie_jar.clone();+ frame.http_client = parent.http_client.clone();+ frame.callbacks = parent.callbacks.clone();+ frame.encoding = parent.encoding.clone();+ frame.blocked_urls = parent.blocked_urls.clone();+ frame.intercept_enabled = parent.intercept_enabled;+ frame.page_in_flight = parent.page_in_flight.clone();+ #[cfg(feature = "stealth")]+ {+ frame.stealth_client = parent.stealth_client.clone();+ }+ }++ /// The table ops consult to find the calling realm's document.+ pub(crate) fn realm_states(&self) -> Rc<RefCell<crate::ops::RealmStates>> {+ self.runtime+ .op_state()+ .borrow()+ .borrow::<Rc<RefCell<crate::ops::RealmStates>>>()+ .clone()+ }++ /// Frame documents fetched by any realm that still need one of their own.+ /// 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)}/// Restore the configured V8 heap limit after the emergency headroom hasdiff --git a/crates/obscura/src/page.rs b/crates/obscura/src/page.rsindex 38fb2d25..ad02b517 100644--- a/crates/obscura/src/page.rs+++ b/crates/obscura/src/page.rs@@ -39,6 +39,17 @@ impl Page {self.inner.evaluate(expression)}+ /// URLs of the page's child frames, in creation order.+ pub fn frame_urls(&self) -> Vec<String> {+ self.inner.frame_urls()+ }++ /// Execute JS inside one of the page's child frames. Each frame is its own+ /// realm with its own document, so this is the only way to observe one.+ pub fn evaluate_in_frame(&mut self, index: usize, expression: &str) -> Result<Value, String> {+ self.inner.evaluate_in_frame(index, expression)+ }+/// Get page HTML content.pub fn content(&mut self) -> String {let val = self.evaluate("document.documentElement.outerHTML");diff --git a/crates/obscura/tests/child_frame_scripts.rs b/crates/obscura/tests/child_frame_scripts.rsnew file mode 100644index 00000000..2b500298--- /dev/null+++ b/crates/obscura/tests/child_frame_scripts.rs@@ -0,0 +1,115 @@+//! Regression test for issue #600: a child iframe's document was fetched and+//! parsed, but the frame never got a scripting context, so a `<script>` inside+//! it stayed an inert node. This is the reporter's loopback repro, reduced to+//! the part that needs no network: two documents on one local server.++use std::io::{Read, Write};++use obscura::Browser;++const 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);+</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>"#;++const CHILD_HTML: &str = r#"<!doctype html><html><head><title>BEFORE</title></head><body>+<p>child</p>+<script>+ window.__ran = "YES";+ document.title = "RAN-IN-CHILD";+</script>+</body></html>"#;++/// Minimal HTTP/1.1 server serving the parent document at `/` and the child at+/// `/child.html`.+fn spawn_server(parent_html: &'static str) -> String {+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap();+ std::thread::spawn(move || {+ for incoming in listener.incoming() {+ let mut stream = match incoming {+ Ok(stream) => stream,+ Err(_) => continue,+ };+ let mut buf = [0u8; 2048];+ let read = stream.read(&mut buf).unwrap_or(0);+ let body = if buf[..read].starts_with(b"GET /child.html ") {+ CHILD_HTML+ } else {+ parent_html+ };+ let headers = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",+ body.len()+ );+ let _ = stream.write_all(headers.as_bytes());+ let _ = stream.write_all(body.as_bytes());+ let _ = stream.shutdown(std::net::Shutdown::Both);+ }+ });+ format!("http://{addr}")+}++#[tokio::test]+async fn a_child_frame_runs_its_own_script() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let base = spawn_server(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")],+ "the child document never became a frame"+ );+ assert_eq!(+ page.evaluate_in_frame(0, "window.__ran").unwrap(),+ serde_json::json!("YES"),+ "the child frame's script did not run"+ );+ // The child's own script wrote this over the static <title>, so it proves+ // the script ran against the frame's document rather than anywhere else.+ assert_eq!(+ page.evaluate_in_frame(0, "document.title").unwrap(),+ serde_json::json!("RAN-IN-CHILD"),+ );+ // The frame's writes must not reach the parent's document.+ assert_eq!(+ page.evaluate("document.title").as_str().unwrap_or(""),+ "parent",+ );+ assert_eq!(page.evaluate("window.__ran"), serde_json::Value::Null);+}++/// A parser-created `<iframe src>` never goes through the `src` setter, so+/// nothing used to start its load at all.+#[tokio::test]+async fn a_static_child_frame_runs_its_own_script() {+ 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(),+ vec![format!("{base}/child.html")],+ "a static iframe never started loading"+ );+ assert_eq!(+ page.evaluate_in_frame(0, "window.__ran").unwrap(),+ serde_json::json!("YES"),+ );+}