The headless browser for AI agents and web scraping
fix(js): load iframe srcdoc in native child realms
SGavrl911c45cf50f7
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex 76faf947..1f245f04 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -1527,6 +1527,13 @@ impl Page {}}}+ // A synchronously initialized parent may not be in self.frames yet.+ // Its children's native owner chain still proves they are connected.+ if let Some(js) = &self.js {+ for pending in &self.pending_frame_work {+ if js.frame_is_active(pending.frame_id()) { live.push(pending.frame_id()); }+ }+ }let mut discarded_ids: std::collections::HashSet<u32> = self.frames.iter()@@ -7105,6 +7112,201 @@ mod tests {(format!("http://{addr}"), requests)}+ async fn pump_srcdoc_frames(page: &mut super::Page) {+ for _ in 0..4 {+ tokio::time::timeout(std::time::Duration::from_secs(2),+ page.js.as_mut().unwrap().run_event_loop()).await.unwrap().unwrap();+ if !page.advance_frames().await { break; }+ }+ }++ #[tokio::test(flavor = "current_thread")]+ async fn iframe_srcdoc_loads_parser_and_inserted_documents_in_their_own_realms() {+ let mut page = import_map_test_page("srcdoc", "https://parent.test",+ r#"<html><head><base href="https://assets.test/dir/"></head><body>+ <iframe id="parsed" src="data:text/html,FALLBACK" srcdoc="<p>parsed</p>"></iframe>+ </body></html>"#);+ page.evaluate_script(r#"(() => {+ globalThis.loads = [];+ localStorage.setItem('shared', 'parent');+ const frame = document.createElement('iframe'); frame.id = 'inserted';+ frame.srcdoc = '<p>inserted</p><script>globalThis.childOnly=42;document.body.dataset.ready="yes";</script>';+ frame.onload = () => loads.push([frame.contentDocument.URL,+ frame.contentDocument.body.dataset.ready, frame.contentWindow.childOnly]);+ document.body.appendChild(frame);+ return 1;+ })()"#).unwrap();+ pump_srcdoc_frames(&mut page).await;+ let value = page.evaluate_script(r#"(() => {+ const parsed = document.getElementById('parsed').contentDocument;+ const f = document.getElementById('inserted'), d = f.contentDocument;+ const a = d.createElement('a'); a.href = 'next';+ return [parsed.URL, parsed.body.textContent, d.URL, d.baseURI, a.href,+ f.contentWindow.localStorage.getItem('shared'), typeof globalThis.childOnly,+ loads, d.defaultView === f.contentWindow, parsed.compatMode];+ })()"#).unwrap();+ assert_eq!(value, serde_json::json!(["about:srcdoc", "parsed", "about:srcdoc",+ "https://assets.test/dir/", "https://assets.test/dir/next", "parent", "undefined",+ [["about:srcdoc", "yes", 42]], true, "CSS1Compat"]));+ assert_eq!(page.frame_urls(), vec!["about:srcdoc", "about:srcdoc"]);+ }++ #[tokio::test(flavor = "current_thread")]+ async fn iframe_srcdoc_replacement_cancels_stale_documents() {+ let mut page = import_map_test_page("srcdoc-replace", "https://parent.test", "<body></body>");+ page.evaluate_script(r#"(() => {+ globalThis.executed = []; globalThis.loaded = [];+ const host = document.createElement('div');+ host.innerHTML = '<iframe id="f" srcdoc="first"></iframe>';+ document.body.appendChild(host);+ const f = document.getElementById('f');+ f.onload = () => loaded.push(f.contentDocument.body.textContent);+ f.setAttributeNS(null, 'srcdoc', '<script>parent.executed.push("stale")</script>stale');+ f.srcdoc = '<script>parent.executed.push("latest")</script><p>latest</p>';+ return 1;+ })()"#).unwrap();+ pump_srcdoc_frames(&mut page).await;+ assert_eq!(page.evaluate_script("[executed, loaded.map(text => text.endsWith('latest')), document.getElementById('f').srcdoc.includes('<p>latest</p>')]").unwrap(),+ serde_json::json!([["latest"], [true], true]));+ page.evaluate_script("document.getElementById('f').removeAttribute('srcdoc'); 1").unwrap();+ pump_srcdoc_frames(&mut page).await;+ assert_eq!(page.evaluate_script("document.getElementById('f').contentDocument.URL").unwrap(),+ serde_json::json!("about:blank"));+ assert!(page.frames.len() <= 1, "replaced srcdoc realms must be released");+ }++ #[tokio::test(flavor = "current_thread")]+ async fn iframe_srcdoc_sandbox_blocks_scripts_and_opaque_document_access() {+ let mut page = import_map_test_page("srcdoc-sandbox", "https://parent.test", "<body></body>");+ page.evaluate_script(r#"(() => {+ globalThis.escaped = false;+ for (const [id, policy] of [['opaque', 'ALLOW-SCRIPTS'], ['inert', 'ALLOW-SAME-ORIGIN']]) {+ const f = document.createElement('iframe'); f.id = id;+ f.setAttribute('sandbox', policy);+ f.srcdoc = '<button onclick="parent.escaped=true">hello</button><script>globalThis.ran=true;try{parent.escaped=true}catch(e){}</script><noscript><i>fallback</i></noscript>';+ document.body.appendChild(f);+ }+ return 1;+ })()"#).unwrap();+ pump_srcdoc_frames(&mut page).await;+ assert_eq!(page.evaluate_script(r#"(() => {+ const opaque = document.getElementById('opaque');+ const inert = document.getElementById('inert');+ inert.contentDocument.querySelector('button').click();+ return [opaque.contentDocument === null, inert.contentDocument.URL,+ inert.contentDocument.querySelector('button').textContent,+ typeof inert.contentWindow.ran, escaped,+ inert.contentDocument.querySelector('noscript i')?.textContent];+ })()"#).unwrap(), serde_json::json!([true, "about:srcdoc", "hello", "undefined", false, "fallback"]));+ assert_eq!(page.evaluate_in_frame(0, "[document.URL, globalThis.ran, location.origin]").unwrap(),+ serde_json::json!(["about:srcdoc", true, "null"]));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn iframe_srcdoc_nested_and_empty_documents_keep_the_creator_base() {+ let mut page = import_map_test_page("srcdoc-nested", "https://parent.test", "<body></body>");+ page.evaluate_script(r#"(() => {+ const f = document.createElement('iframe'); f.id = 'outer';+ f.srcdoc = '<base href="https://nested.test/path/"><iframe srcdoc=""></iframe>';+ document.body.appendChild(f); return 1;+ })()"#).unwrap();+ pump_srcdoc_frames(&mut page).await;+ assert_eq!(page.evaluate_script(r#"(() => {+ const child = document.getElementById('outer').contentDocument.querySelector('iframe');+ return [child.contentDocument.URL, child.contentDocument.baseURI,+ child.contentDocument.body.textContent,+ child.contentWindow.parent === document.getElementById('outer').contentWindow];+ })()"#).unwrap(), serde_json::json!(["about:srcdoc", "https://nested.test/path/", "", true]));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn iframe_srcdoc_from_connected_inner_html_survives_initial_document_reads() {+ let mut page = import_map_test_page("srcdoc-connected", "https://parent.test", "<body></body>");+ page.evaluate_script(r#"(() => {+ document.body.innerHTML = '<iframe id="f" srcdoc="hello"></iframe>';+ globalThis.initial = document.getElementById('f').contentDocument.URL;+ return 1;+ })()"#).unwrap();+ pump_srcdoc_frames(&mut page).await;+ assert_eq!(page.evaluate_script("[initial, document.getElementById('f').contentDocument.URL, document.getElementById('f').contentDocument.body.textContent]").unwrap(),+ serde_json::json!(["about:blank", "about:srcdoc", "hello"]));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn iframe_srcdoc_external_scripts_resolve_against_the_creator() {+ let (base, requests) = spawn_nested_pending_frame_server().await;+ let mut page = import_map_test_page("srcdoc-script-base", &base,+ r#"<body><iframe srcdoc="<script src=child.js></script>"></iframe></body>"#);+ pump_srcdoc_frames(&mut page).await;+ assert_eq!(*requests.lock().unwrap(), vec!["/app/child.js"]);+ assert_eq!(page.evaluate_script("document.querySelector('iframe').contentWindow.__mustNotRun").unwrap(),+ serde_json::json!(true));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn iframe_srcdoc_inherits_sandbox_restrictions_in_nested_documents() {+ let mut page = import_map_test_page("srcdoc-inherited-sandbox", "https://parent.test", "<body></body>");+ page.evaluate_script(r#"(() => {+ for (const policy of ['allow-scripts', 'allow-same-origin']) {+ const f = document.createElement('iframe'); f.id = policy; f.setAttribute('sandbox', policy);+ f.srcdoc = '<iframe srcdoc="<script>globalThis.ran=true</script>"></iframe>';+ document.body.appendChild(f);+ }+ return 1;+ })()"#).unwrap();+ pump_srcdoc_frames(&mut page).await;+ assert_eq!(page.evaluate_in_frame(0, "document.querySelector('iframe').contentDocument === null").unwrap(),+ serde_json::json!(true));+ assert_eq!(page.evaluate_script("typeof document.getElementById('allow-same-origin').contentDocument.querySelector('iframe').contentWindow.ran").unwrap(),+ serde_json::json!("undefined"));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn iframe_srcdoc_ignores_absent_attributes_and_non_html_elements() {+ let mut page = import_map_test_page("srcdoc-noop", "https://parent.test", "<body></body>");+ let values = page.evaluate_script(r#"(() => {+ globalThis.escaped = false;+ const f = document.createElement('iframe'); document.body.appendChild(f);+ f.contentWindow.kept = 73;+ f.removeAttribute('srcdoc');+ const first = f.contentWindow.kept;+ f.removeAttributeNS(null, 'srcdoc');+ const second = f.contentWindow.kept;+ const plain = document.createElement('div'); plain.srcdoc = 'expando';+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'iframe');+ svg.setAttribute('srcdoc', '<script>parent.escaped=true</script>');+ const host = document.createElement('div'); host.appendChild(svg);+ document.body.appendChild(host);+ return [first, second, plain.hasAttribute('srcdoc')];+ })()"#).unwrap();+ pump_srcdoc_frames(&mut page).await;+ assert_eq!(values, serde_json::json!([73, 73, false]));+ assert_eq!(page.evaluate_script("escaped").unwrap(), serde_json::json!(false));+ assert_eq!(page.frames.len(), 1, "SVG iframe is not a browsing context");+ }++ #[tokio::test(flavor = "current_thread")]+ async fn iframe_srcdoc_navigation_waits_until_after_the_microtask_checkpoint() {+ let mut page = import_map_test_page("srcdoc-task", "https://parent.test", "<body></body>");+ page.evaluate_script(r#"(() => {+ const f = document.createElement('iframe'); f.srcdoc = 'hello';+ document.body.appendChild(f);+ Promise.resolve().then(() => { globalThis.beforeNavigation = f.contentDocument.URL; });+ return 1;+ })()"#).unwrap();+ pump_srcdoc_frames(&mut page).await;+ assert_eq!(page.evaluate_script("[beforeNavigation, document.querySelector('iframe').contentDocument.URL]").unwrap(),+ serde_json::json!(["about:blank", "about:srcdoc"]));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn iframe_srcdoc_is_ready_after_data_document_navigation() {+ let mut page = import_map_test_page("srcdoc-data-navigation", "https://parent.test", "<body></body>");+ page.navigate("data:text/html,%3Ciframe%20srcdoc%3D%22HELLO%22%3E%3C%2Fiframe%3E").await.unwrap();+ assert_eq!(page.evaluate_script("[document.querySelector('iframe').contentDocument.URL, document.querySelector('iframe').contentDocument.body.textContent]").unwrap(),+ serde_json::json!(["about:srcdoc", "HELLO"]));+ }+#[tokio::test(flavor = "current_thread")]async fn iframe_load_waits_for_the_real_document_and_author_scripts() {let (base, _, _) = spawn_slow_frame_script_server().await;diff --git a/crates/obscura-dom/src/lib.rs b/crates/obscura-dom/src/lib.rsindex 1ec230f7..d9be64a4 100644--- a/crates/obscura-dom/src/lib.rs+++ b/crates/obscura-dom/src/lib.rs@@ -10,4 +10,4 @@ pub use tree::{AttachShadowError, Attribute, DomTree, Node, NodeData, NodeId, ShadowRoot,ShadowRootMode,};-pub use tree_sink::{parse_fragment, parse_fragment_with_context, parse_html};+pub use tree_sink::{parse_fragment, parse_fragment_with_context, parse_html, parse_srcdoc};diff --git a/crates/obscura-dom/src/tree_sink.rs b/crates/obscura-dom/src/tree_sink.rsindex d015166c..be5a9127 100644--- a/crates/obscura-dom/src/tree_sink.rs+++ b/crates/obscura-dom/src/tree_sink.rs@@ -362,6 +362,17 @@ pub fn parse_html(html: &str) -> DomTree {.one(html.as_bytes())}+/// Parse an iframe srcdoc with its standards-mode and scripting rules.+pub fn parse_srcdoc(html: &str, scripting_enabled: bool) -> DomTree {+ use html5ever::tendril::TendrilSink;+ let tree = DomTree::new();+ tree.set_allow_declarative_shadow_roots(true);+ let mut opts = html5ever::ParseOpts::default();+ opts.tree_builder.iframe_srcdoc = true;+ opts.tree_builder.scripting_enabled = scripting_enabled;+ html5ever::parse_document(tree, opts).from_utf8().one(html.as_bytes())+}+pub fn parse_fragment(html: &str) -> DomTree {let context_name = QualName::new(None, ns!(html), local_name!("body"));parse_fragment_with_context(html, context_name)diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 8fb3cad3..905b12af 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -2161,7 +2161,10 @@ function _domEventDispatch(target, event) {// browser custom-element implementations.const _customElementConstructionStack = [];+let _scriptingEnabled = true;+let _sandboxOpaqueOrigin = false;function __prepareInsertedScript(script) {+ if (!_scriptingEnabled) return;if (!__obscuraCore.ops.op_script_try_start(script._nid)) return;const scriptType = (script.getAttribute('type') || '').trim().toLowerCase();const isModule = scriptType === 'module';@@ -2338,11 +2341,12 @@ function __prepareInsertedSubtree(root) {if (!root || !root.isConnected) return;const scripts = [];const seen = new Set();- if (root.nodeType === 1 && root.tagName === 'SCRIPT') {+ if (root.nodeType === 1 && (root.tagName === 'SCRIPT'+ || (root.tagName === 'IFRAME' && root.hasAttribute('srcdoc')))) {scripts.push(root);seen.add(root._nid);}- const ids = _domParse("query_selector_all_scoped", root._nid, "script") || [];+ const ids = _domParse("query_selector_all_scoped", root._nid, "script,iframe[srcdoc]") || [];for (const nid of ids) {const script = _wrapEl(+nid);if (script && !seen.has(script._nid)) {@@ -2352,7 +2356,8 @@ function __prepareInsertedSubtree(root) {}for (const script of scripts) {if (_postConnection) _postConnection.cursor = script;- __prepareInsertedScript(script);+ if (script.localName === 'iframe') script._loadIframeSrcdoc();+ else __prepareInsertedScript(script);}}@@ -4121,12 +4126,14 @@ class Element extends Node {if (globalThis.__mutationObservers?.length) {oldChildren = _domParse("child_nodes", this._nid) || [];}- _dom("set_inner_html", this._nid, String(v ?? ""));+ const html = String(v ?? "");+ _dom("set_inner_html", this._nid, html);// HTML fragment parsing can introduce IDs without calling the JS// setAttribute path. Register those elements for Window named access// before script can synchronously read `window.someId`._registerWindowNamedTree(this);_reconcileWindowNamedProperties(previousWindowNames);+ _connectSrcdocFrames(this, html);if (globalThis.__mutationObservers?.length) {newChildren = _domParse("child_nodes", this._nid) || [];globalThis.__notifyMutation('childList', this._nid, newChildren, oldChildren);@@ -4249,13 +4256,14 @@ class Element extends Node {const observedOldValue = _attributeOldValuesWanted() ? this.getAttribute(n) : null;const value = String(v);_dom("set_attribute", this._nid, n + "\0" + value);- if (n === "src" && this.localName === "iframe") {+ if (n === "src" && this.localName === "iframe" && !this.hasAttribute('srcdoc')) {if (value && value !== "about:blank") this._loadIframeSrc(value);else this._resetIframeFrame();}if (this._nullNamespaceAttrs instanceof Map) {this._nullNamespaceAttrs.set(n, value);}+ if (n === 'srcdoc' && this.localName === 'iframe') this._loadIframeSrcdoc(true);if (n === "id" || (n === "name" && _windowNameEligibleElement(this))) {if (this.getRootNode() === globalThis.document) {_ensureWindowNamedProperty(value);@@ -4296,10 +4304,12 @@ class Element extends Node {// while changing its qualified name. Fall back to native reads afterwards// instead of maintaining a second, subtly different key space here.this._nullNamespaceAttrs = null;+ if (ns === '' && n === 'srcdoc' && this.localName === 'iframe') this._loadIframeSrcdoc(true);if (ns === "" && n === "style") this._style._replaceFromAttribute(value);}removeAttribute(n) {n = _htmlAttrName(this, n);+ if (n === 'srcdoc' && this.localName === 'iframe' && !this.hasAttribute(n)) return;const popoverPrev = (n === "popover") ? this.popover : undefined;const previousWindowName = (n === "id" || n === "name")? this.getAttribute(n)@@ -4310,6 +4320,7 @@ class Element extends Node {if (this._nullNamespaceAttrs instanceof Map) {this._nullNamespaceAttrs.delete(n);}+ if (n === 'srcdoc' && this.localName === 'iframe') this._loadIframeSrc(this.getAttribute('src') || 'about:blank');if (previousWindowName&& (n === "id" || (n === "name" && _windowNameEligibleElement(this)))) {_reconcileWindowNamedProperty(previousWindowName);@@ -4335,10 +4346,12 @@ class Element extends Node {removeAttributeNS(ns, n) {ns = String(ns == null ? "" : ns);n = String(n);+ if (ns === '' && n === 'srcdoc' && this.localName === 'iframe' && this.getAttributeNS(ns, n) === null) return;const observedOldValue = _hasMutationObservers() ? this.getAttributeNS(ns, n) : null;_dom("remove_attribute_ns", this._nid, ns + "\0" + n);if (observedOldValue !== null) _queueAttributeMutationRecord(this, n, ns || null, observedOldValue);this._nullNamespaceAttrs = null;+ if (ns === '' && n === 'srcdoc' && this.localName === 'iframe') this._loadIframeSrc(this.getAttribute('src') || 'about:blank');if (ns === "" && n === "style") this._style._replaceFromAttribute("");}hasAttribute(n) { return this.getAttribute(n) !== null; }@@ -4471,6 +4484,7 @@ class Element extends Node {return _domEventDispatch(this, event);}_resolveInlineHandler(name) {+ if (!_scriptingEnabled) return null;// name = 'onclick' / 'onsubmit' / etc. Compile the content attribute// as a function body on first read and cache it on the instance.const cache = this.__inlineHandlerCache || (this.__inlineHandlerCache = {});@@ -5080,6 +5094,8 @@ class Element extends Node {_resetIframeElement(this);}_loadIframeSrc(url) {+ if (this.hasAttribute('srcdoc')) { this._loadIframeSrcdoc(); return; }+ if (url === 'about:blank' || !url) { this._resetIframeFrame(); return; }let fullUrl = url;if (!url.includes('://')) {try { fullUrl = new URL(url, _domParse("document_url") || "about:blank").href; } catch(e) {}@@ -5102,6 +5118,7 @@ class Element extends Node {const html = response.body || '';const loadedUrl = response.url || fullUrl;el._iframeLoadedUrl = loadedUrl;+ el._iframeOpaque = _sandboxOpaqueOrigin;// The host fires load after creating the realm and running its scripts.const box = el.getBoundingClientRect();if (el._frameId) globalThis.__obscura_forgetFrame(el._frameId);@@ -5138,10 +5155,33 @@ class Element extends Node {el.dispatchEvent(new Event('load'));});}+ _loadIframeSrcdoc(force = false) {+ if (this.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !this.isConnected) return;+ const html = this.getAttribute('srcdoc');+ if (html === null) return;+ if (!force && this._iframeLoadingUrl === 'about:srcdoc' && this._iframeSrcdoc === html) return;+ this._resetIframeFrame();+ this._iframeLoadingUrl = 'about:srcdoc';+ this._iframeSrcdoc = html;+ // Coalesce attribute writes into one navigation task, after microtasks.+ if (this._iframeSrcdocTaskPending) return;+ this._iframeSrcdocTaskPending = true;+ _browserPostedTaskEnqueue(() => {+ this._iframeSrcdocTaskPending = false;+ if (!this.isConnected || this._iframeLoadingUrl !== 'about:srcdoc' || !this.hasAttribute('srcdoc')) return;+ if (this._frameId) globalThis.__obscura_forgetFrame(this._frameId);+ this._frameId = 0;+ _ensureInitialFrameRealm(this, this._iframeSrcdoc);+ this._iframeLoadedUrl = 'about:srcdoc';+ }, _schedulerPriorityRank['user-visible'] * 2, _browserPostedTaskGeneration(), () => {+ this._iframeSrcdocTaskPending = false;+ });+ }get contentDocument() {if (this.localName !== 'iframe') return undefined;if (_postConnection && _iframeConnectionPending(this)) return null;if (_ensureInitialFrameRealm(this) === false) return null;+ if (this._iframeOpaque) return null;const real = _frameObjectsFor(this);if (real?.document) return real.document;if (this._iframeDoc) {@@ -5165,6 +5205,7 @@ class Element extends Node {if (this.localName !== 'iframe') return undefined;if (_postConnection && _iframeConnectionPending(this)) return null;if (_ensureInitialFrameRealm(this) === false) return null;+ if (this._iframeOpaque && this._frameId) return _remoteWindow(this._frameId);if (_frameObjectsFor(this)) {const win = _frameWindowFor(this._frameId);if (win) return win;@@ -6921,6 +6962,7 @@ class DocumentFragment extends Node {} else {_dom("set_inner_html", this._nid, html);}+ _connectSrcdocFrames(this, html);}querySelector(s) { return _wrapEl(+_dom("query_selector_scoped", this._nid, s)); }querySelectorAll(s) {@@ -13916,7 +13958,10 @@ globalThis.HTMLTableElement = Element;// element passed `instanceof HTMLIFrameElement`, so style-loader's// "insert target is an iframe" branch took `contentDocument.head` of <head>// itself and failed with "Couldn't find a style target".-globalThis.HTMLIFrameElement = class HTMLIFrameElement extends Element {};+globalThis.HTMLIFrameElement = class HTMLIFrameElement extends Element {+ get srcdoc() { return this.getAttribute('srcdoc') || ''; }+ set srcdoc(value) { this.setAttribute('srcdoc', value); }+};globalThis.HTMLCanvasElement = Element;// HTMLVideoElement and HTMLAudioElement are defined above with canPlayType support.globalThis.HTMLScriptElement = Element;@@ -15252,12 +15297,20 @@ function _frameObjectsFor(element) {return entry || null;}-function _ensureInitialFrameRealm(element) {+function _connectSrcdocFrames(root, html) {+ if (root.isConnected && /<iframe[\s/>]/i.test(html)) {+ _runPostConnectionSteps(Array.from(root.querySelectorAll('iframe[srcdoc]')));+ }+}++function _ensureInitialFrameRealm(element, srcdoc) {if (element._frameId || !element.isConnected) return;// An opaque sandbox must never receive the creator's security token.- if (element.hasAttribute('sandbox') &&- !element.getAttribute('sandbox').split(/\s+/).includes('allow-same-origin')) return;- const frameId = __obscuraCore.ops.op_initial_frame(_realmFrameId, (child, id) => {+ let opaque = element.hasAttribute('sandbox') &&+ !element.getAttribute('sandbox').toLowerCase().split(/\s+/).includes('allow-same-origin');+ if (opaque && srcdoc === undefined) return false;+ const frameId = __obscuraCore.ops.op_initial_frame(_realmFrameId, (child, id, sandboxOpaque) => {+ opaque = sandboxOpaque;const core = child.__obscura_core_handoff;for (const name of Object.keys(__obscuraCore.ops)) core.ops[name] = __obscuraCore.ops[name];delete child.__obscura_core_handoff;@@ -15270,19 +15323,20 @@ function _ensureInitialFrameRealm(element) {child.__obscura_frameId = id;child.__obscura_parentFrameId = _realmFrameId;child.__obscura_init();- Object.defineProperties(child, {- parent: { value: globalThis, configurable: true },- top: { value: globalThis.top, configurable: true },- frameElement: { value: element, configurable: true },- });+ if (!opaque) Object.defineProperties(child, {+ parent: { value: globalThis, configurable: true },+ top: { value: globalThis.top, configurable: true },+ frameElement: { value: element, configurable: true },+ });child.innerWidth = 300;child.innerHeight = 150;globalThis.__obscura_frameObjects[id] = {window: child, document: child.document, initial: true,};- }, element._nid);+ }, element._nid, srcdoc);if (frameId) {element._frameId = frameId;+ element._iframeOpaque = opaque;element._iframeWin = globalThis.__obscura_frameObjects[frameId].window;element._iframeDoc = globalThis.__obscura_frameObjects[frameId].document;globalThis.__obscura_frameElements[frameId] = element;@@ -15293,6 +15347,7 @@ function _ensureInitialFrameRealm(element) {function _resetIframeElement(element) {if (element._frameId) globalThis.__obscura_forgetFrame(element._frameId);element._frameId = 0;+ element._iframeOpaque = false;element._iframeLoadingUrl = null;element._iframeLoadedUrl = 'about:blank';element._iframeDoc = new _IframeDocument(@@ -15432,8 +15487,14 @@ class _IframeWindow {this.outerWidth = 300;this.outerHeight = 150;this.devicePixelRatio = globalThis.devicePixelRatio;- this.localStorage = globalThis.localStorage;- this.sessionStorage = globalThis.sessionStorage;+ // Storage can throw for an opaque creator. Constructing its initial+ // window must still succeed; enforce access restrictions on reads.+ for (const name of ['localStorage', 'sessionStorage']) {+ Object.defineProperty(this, name, {+ configurable: true, enumerable: true,+ get() { return globalThis[name]; },+ });+ }this.performance = globalThis.performance;this.crypto = globalThis.crypto;this.console = globalThis.console;@@ -18124,6 +18185,8 @@ const _documentMembers = Object.freeze(Object.fromEntries([globalThis.__obscura_init = function() {// The host sets __obscura_frameId on a frame realm before calling this._realmFrameId = globalThis.__obscura_frameId >>> 0;+ _scriptingEnabled = _domParse('scripting_enabled') !== false;+ _sandboxOpaqueOrigin = _domParse('sandbox_opaque_origin') === true;globalThis.__obscura_update_media_preferences();const caretMembers = _installCaretGeometry();__obscuraCore.ops.op_register_document_realm(@@ -18212,7 +18275,8 @@ globalThis.__obscura_init = function() {// its parent.for (const frame of globalThis.document.querySelectorAll('iframe')) {const src = frame.getAttribute('src');- if (src && src !== 'about:blank') frame._loadIframeSrc(src);+ if (frame.hasAttribute('srcdoc')) frame._loadIframeSrcdoc();+ else if (src && src !== 'about:blank') frame._loadIframeSrc(src);}// Hide internals (_*, obscura, Obscura). The set of keys is static atdiff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rsindex cfeb283b..31b70493 100644--- a/crates/obscura-js/src/frame.rs+++ b/crates/obscura-js/src/frame.rs@@ -91,7 +91,12 @@ impl FrameRealm {// 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 (scripting_enabled, sandbox_opaque_origin) = realms.borrow().by_frame_id(parent_frame_id)+ .map(|creator| {+ let creator = creator.borrow();+ (creator.scripting_enabled, creator.sandbox_opaque_origin)+ }).unwrap_or((true, false));+ let origin = if sandbox_opaque_origin { "null".to_string() } else { origin_of(url) };let same_origin = origin != "null" && origin == parent.page_origin();if same_origin {parent.share_security_token_with_realm(&context);@@ -102,6 +107,9 @@ impl FrameRealm {state.dom = Some(parse_html(html));state.url = url.to_string();state.frame_id = frame_id;+ state.scripting_enabled = scripting_enabled;+ state.sandbox_opaque_origin = sandbox_opaque_origin;+ if sandbox_opaque_origin { state.inherited_origin = Some("null".to_string()); }parent.share_resources_with(&mut state);let realms = parent.realm_states();@@ -356,6 +364,14 @@ impl FrameRealm {/// 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 {+ if self.url == "about:srcdoc" {+ if let Some(base) = self.realms.borrow().by_frame_id(self.frame_id)+ .and_then(|state| crate::ops::document_base_url(&state.borrow()))+ {+ return url::Url::parse(&base).and_then(|base| base.join(src))+ .map(|url| url.to_string()).unwrap_or_else(|_| src.to_string());+ }+ }url::Url::parse(&self.url).and_then(|base| base.join(src)).map(|url| url.to_string())@@ -367,6 +383,7 @@ impl FrameRealm {let state = self.realms.borrow().by_frame_id(self.frame_id).ok_or_else(|| "could not list frame scripts: missing realm".to_string())?;let state = state.borrow();+ if !state.scripting_enabled { return Ok(Vec::new()); }let dom = state.dom.as_ref().ok_or_else(|| "could not list frame scripts: missing document".to_string())?;let nodes = dom.query_selector_all("script")?;diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex c1f499dd..a4bbd8cc 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -325,9 +325,11 @@ struct StorageOriginCache {pub struct ObscuraState {pub dom: Option<DomTree>,pub url: String,- /// Initial about:blank documents retain their creator's base URL and origin.+ /// Initial about:blank and srcdoc documents retain their creator's base and origin.pub(crate) about_base_url: Option<String>,pub(crate) inherited_origin: Option<String>,+ pub(crate) scripting_enabled: bool,+ pub(crate) sandbox_opaque_origin: bool,storage_origin_cache: RefCell<StorageOriginCache>,/// WHATWG canonical name of the document's character encoding (e.g./// "UTF-8", "EUC-JP"). Backs `document.characterSet` and the URL query@@ -629,6 +631,8 @@ impl ObscuraState {url: "about:blank".to_string(),about_base_url: None,inherited_origin: None,+ scripting_enabled: true,+ sandbox_opaque_origin: false,storage_origin_cache: RefCell::new(StorageOriginCache { origin: "null".into(), ..Default::default() }),encoding: "UTF-8".to_string(),content_type: String::new(),@@ -1162,7 +1166,7 @@ impl RealmStates {}).owner = Some((Rc::downgrade(parent), node, generation));}- fn frame_timers_active(&self, mut frame_id: u32) -> Option<bool> {+ pub(crate) fn frame_timers_active(&self, mut frame_id: u32) -> Option<bool> {// A child document is active only while all of its owners are active.// Keep the walk bounded even if an invalid frame-parent chain arrives.for _ in 0..=self.frame_timers.len() {@@ -2385,6 +2389,8 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->serde_json::to_string(&title).unwrap_or("\"\"".into())}"document_url" => serde_json::to_string(&gs.url).unwrap_or("\"\"".into()),+ "scripting_enabled" => gs.scripting_enabled.to_string(),+ "sandbox_opaque_origin" => gs.sandbox_opaque_origin.to_string(),"document_origin" => serde_json::to_string(&gs.inherited_origin.clone().unwrap_or_else(|| {url::Url::parse(&gs.url).map(|url| url.origin().ascii_serialization()).unwrap_or_else(|_| "null".to_string())@@ -6596,22 +6602,25 @@ pub fn max_live_frames() -> usize {.and_then(|value| value.parse().ok()).unwrap_or(64)}-/// An initial about:blank needs its own realm before the next JS statement.-#[op2(nofast)]+/// Initial blank and srcdoc documents share their creator's realm setup.+#[op2]fn op_initial_frame(scope: &mut v8::PinScope,state: &OpState,parent_frame_id: u32,initialize: v8::Local<v8::Function>,owner_node: u32,+ #[string] srcdoc: Option<String>,) -> u32 {std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {let registry = state.borrow::<Rc<RefCell<RealmStates>>>().clone();let page = state.borrow::<SharedState>().clone();let parent_state = frame_state(state, parent_frame_id);+ let frame_url = if srcdoc.is_some() { "about:srcdoc" } else { "about:blank" };+ let bytes = frame_url.len().saturating_add(srcdoc.as_ref().map_or(0, String::len));if registry.borrow().live_count() >= max_live_frames()|| page.borrow().pending_frames.len() >= MAX_PENDING_FRAME_DOCUMENTS- || page.borrow().pending_frame_bytes.saturating_add("about:blank".len()) > MAX_PENDING_FRAME_BYTES+ || page.borrow().pending_frame_bytes.saturating_add(bytes) > MAX_PENDING_FRAME_BYTES{return 0;}@@ -6635,16 +6644,31 @@ fn op_initial_frame(let mut child = ObscuraState::new();#[cfg(feature = "render")]child.set_viewport(300.0, 150.0);+ let opaque;{let parent = parent_state.borrow();- child.dom = Some(obscura_dom::parse_html(- "<html><head></head><body></body></html>"));+ let sandbox = srcdoc.as_ref().and_then(|_| parent.dom.as_ref())+ .and_then(|dom| dom.with_node(NodeId::new(owner_node), |node|+ node.get_attribute("sandbox").map(str::to_owned)).flatten());+ opaque = parent.sandbox_opaque_origin || sandbox.as_deref().is_some_and(|value|+ !value.split_ascii_whitespace().any(|token| token.eq_ignore_ascii_case("allow-same-origin")));+ child.sandbox_opaque_origin = opaque;+ child.url = frame_url.to_string();child.frame_id = frame_id;child.about_base_url = document_base_url(&parent);- child.inherited_origin = Some(parent.inherited_origin.clone().unwrap_or_else(|| {+ child.scripting_enabled = parent.scripting_enabled && sandbox.as_deref().is_none_or(|value|+ value.split_ascii_whitespace().any(|token| token.eq_ignore_ascii_case("allow-scripts")));+ child.dom = Some(if let Some(html) = srcdoc.as_deref() {+ obscura_dom::parse_srcdoc(html, child.scripting_enabled)+ } else {+ obscura_dom::parse_html("<html><head></head><body></body></html>")+ });+ child.inherited_origin = Some(if opaque { "null".to_string() } else {+ parent.inherited_origin.clone().unwrap_or_else(|| {url::Url::parse(&parent.url).map(|url| url.origin().ascii_serialization()).unwrap_or_else(|_| "null".to_string())- }));+ })+ });child.inherit_resources(&parent);}let handle = v8::Global::new(scope, context);@@ -6653,16 +6677,20 @@ fn op_initial_frame(let window = context.global(scope);let id = v8::Integer::new_from_unsigned(scope, frame_id);let receiver = v8::undefined(scope);- if initialize.call(scope, receiver.into(), &[window.into(), id.into()]).is_none() {+ let opaque_value = v8::Boolean::new(scope, opaque);+ if initialize.call(scope, receiver.into(), &[window.into(), id.into(), opaque_value.into()]).is_none() {registry.borrow_mut().forget(&handle);return 0;}+ // Initialization needs the creator's token; author code must never+ // retain it when the sandbox requires an opaque origin.+ if opaque { context.use_default_security_token(); }let mut page = page.borrow_mut();- page.pending_frame_bytes = page.pending_frame_bytes.saturating_add("about:blank".len());+ page.pending_frame_bytes = page.pending_frame_bytes.saturating_add(bytes);page.pending_frames.push(PendingFrame {frame_id,parent_frame_id,- url: "about:blank".to_string(),+ url: frame_url.to_string(),html: String::new(),viewport_width: 300,viewport_height: 150,diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex cab9e962..114dc7c2 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -1013,6 +1013,11 @@ impl ObscuraJsRuntime {self.realm_states().borrow_mut().forget_frame(frame_id);}+ /// Pending initial realms can already own children before Page adopts them.+ pub fn frame_is_active(&self, frame_id: u32) -> bool {+ self.realm_states().borrow().frame_timers_active(frame_id) != Some(false)+ }+/// 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 {diff --git a/docs/Architecture-overview.md b/docs/Architecture-overview.mdindex 16ed9f91..61b61bb7 100644--- a/docs/Architecture-overview.md+++ b/docs/Architecture-overview.md@@ -86,6 +86,26 @@ The dispatcher routes long-running operations (navigation, eval) through `procesThis is why `Target.createTarget` from many concurrent clients works: each `newPage` returns immediately while the actual navigation runs in a spawned task.+## Child frames++`iframe srcdoc` uses a native child realm and document, not a copy in the+parent DOM. Its URL is `about:srcdoc`; relative URLs inherit the creator's+document base, and unsandboxed Web Storage uses the creator's origin.+`srcdoc` takes precedence over `src`, including an empty value. Parser input,+connected `innerHTML`, property/attribute changes and removal use the same+loading path. Replaced or detached documents are retired before stale loads+can run. The iframe's `load` event follows classic author scripts.+Navigation runs as a posted task, after microtasks. Parsing uses srcdoc+standards mode without requiring a doctype and honors script-disabled+`noscript` content.++Sandboxed `srcdoc` enforces opaque document access and script disabling,+including inherited restrictions on nested frames. This does not implement+every HTML sandbox policy. Frame module scripts remain unsupported.+Child-frame CDP evaluation routing and iframe content compositing remain+separate compatibility gaps; loading a document does not establish support+for Playwright frame locators or iframe screenshot fidelity.+## RobustnessOne page cannot hang or crash the process. `obscura-js/runtime.rs` provides a V8 termination watchdog (`arm_watchdog`, `run_event_loop_bounded`) that terminates the isolate from a separate thread when synchronous work overruns a budget, because `tokio::time::timeout` cannot preempt synchronous V8. It bounds the post-load settle, the navigation event-loop pumps, and `--eval`. The complete script phase is bounded by `OBSCURA_SCRIPT_DEADLINE_MS`; enhancement modules have a shorter per-module graph-loading/evaluation budget controlled by `OBSCURA_MODULE_BUDGET_MS`, while modules mounting an empty SPA shell receive the full script deadline. `obscura-js/cdp_watchdog.rs` is a single shared watchdog the dispatcher arms around every CDP command, so a runaway page cannot hold the V8 lock and wedge other sessions (tunable via `OBSCURA_CDP_COMMAND_TIMEOUT_MS`). `op_dom` is wrapped in `catch_unwind` so a DOM-op panic degrades to a null result instead of aborting the process through V8's FFI frame, and `obscura-dom/tree.rs` rejects cyclic reparenting that would make tree walks loop forever. Scripted `fetch()`/XHR and module network requests are timeout-bounded (`OBSCURA_FETCH_TIMEOUT_MS`), and the one-shot `fetch` CLI has a process-level hard deadline as a final backstop.