The headless browser for AI agents and web scraping
Track child windows by browsing context across frame lifetimes
SGavrlbcf6d03be2ec
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex a5e8a2aa..2f451c57 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -1419,8 +1419,9 @@ impl Page {if message.target_frame_id == 0 {let Some(js) = self.js.as_mut() else { continue };let script = format!(- "globalThis.__obscura_deliverMessage({escaped_data}, {escaped_origin}, {}, {escaped_target_origin});",+ "globalThis.__obscura_deliverMessage({escaped_data}, {escaped_origin}, {}, {escaped_target_origin}, {});",message.source_frame_id,+ message.source_context_id.map_or(-1i64, i64::from),);if let Err(error) = js.execute_script("<frame-message>", &script) {tracing::debug!("message to the page failed: {error}");@@ -1438,13 +1439,7 @@ impl Page {continue;};let Some(js) = self.js.as_mut() else { continue };- if let Err(error) = self.frames[index].deliver_message(- js,- &message.data_json,- &message.origin,- message.source_frame_id,- &message.target_origin,- ) {+ if let Err(error) = self.frames[index].deliver_queued_message(js, &message) {tracing::debug!("message to frame {} failed: {error}", message.target_frame_id);}}@@ -1462,7 +1457,8 @@ impl Page {"if (globalThis.__obscura_frameElements[{frame_id}] &&\globalThis.__obscura_frameElements[{frame_id}]._frameId === {frame_id}) {{\globalThis.__obscura_frameElements[{frame_id}]._frameId = 0;\- if (globalThis.__obscura_frameElements[{frame_id}]._iframeWin)\+ if (globalThis.__obscura_frameElements[{frame_id}]._iframeWin &&\+ !globalThis.__obscura_frameElements[{frame_id}]._iframeOpaque)\globalThis.__obscura_frameElements[{frame_id}]._iframeWin._frameId = 0;\}}\delete globalThis.__obscura_frameObjects[{frame_id}];\diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 9a4f9c98..ddd7db5f 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -164,6 +164,7 @@ const _DOM_TREE_MUTATION_COMMANDS = new Set([// makes `iframe.contentDocument.title` read the frame's document rather than// the caller's. Set by __obscura_init; 0 is the page.let _realmFrameId = 0;+let _realmContextId = 0;const _dom = (cmd, a1, a2) => {let result = __obscuraCore.ops.op_dom(cmd, String(a1 ?? ""), String(a2 ?? ""), _realmFrameId);@@ -2469,6 +2470,7 @@ function __prepareInsertedSubtree(root) {if (_postConnection) _postConnection.cursor = script;if (script.localName === 'iframe') {if (script.namespaceURI !== 'http://www.w3.org/1999/xhtml') continue;+ _connectFrameContext(script);if (script.hasAttribute('srcdoc')) script._loadIframeSrcdoc();else {const src = script.getAttribute('src');@@ -5327,6 +5329,7 @@ class Element extends Node {_resetIframeElement(this);}_loadIframeSrc(url, submission) {+ _connectFrameContext(this);if (!submission && this.hasAttribute('srcdoc')) { this._loadIframeSrcdoc(); return; }if (url === 'about:blank' || !url) { this._resetIframeFrame(); if (submission) _ensureInitialFrameRealm(this); return; }let fullUrl = url;@@ -5364,7 +5367,12 @@ class Element extends Node {loadedUrl, html, Math.round(box.width) || 300, Math.round(box.height) || 150, el._nid);if (el._frameId) globalThis.__obscura_frameElements[el._frameId] = el;el._iframeDoc = el._iframeOpaque ? null : new _IframeDocument(html, loadedUrl, el);- el._iframeWin = el._iframeOpaque ? _remoteWindow(el._frameId) : new _IframeWindow(el._iframeDoc, loadedUrl);+ if (el._iframeOpaque) {+ const contextId = _connectFrameContext(el);+ el._iframeWin = contextId < 0 ? null : _remoteContextWindow(contextId);+ } else {+ el._iframeWin = new _IframeWindow(el._iframeDoc, loadedUrl);+ }// Bind the window to the realm the host just queued. This is what makes// posting into the frame reach the frame's own listeners, and makes a// message coming back out arrive with this window as its `source`.@@ -5395,6 +5403,7 @@ class Element extends Node {}_loadIframeSrcdoc(force = false) {if (this.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !this.isConnected) return;+ _connectFrameContext(this);const html = this.getAttribute('srcdoc');if (html === null) return;if (!force && this._iframeLoadingUrl === 'about:srcdoc' && this._iframeSrcdoc === html) return;@@ -5442,7 +5451,10 @@ class Element extends Node {get contentWindow() {if (this.localName !== 'iframe') return undefined;if (_postConnection && _iframeConnectionPending(this)) return null;- if (_ensureInitialFrameRealm(this) === false) return null;+ if (_ensureInitialFrameRealm(this) === false) {+ const contextId = _connectFrameContext(this);+ return contextId < 0 ? null : _remoteContextWindow(contextId);+ }if (this._iframeOpaque && this._frameId) return _remoteWindow(this._frameId);if (_frameObjectsFor(this)) {const win = _frameWindowFor(this._frameId);@@ -8227,7 +8239,7 @@ Object.defineProperty(globalThis, 'constructor', {// Remove the static _iframeRegistry and replace with dynamic getters.Object.defineProperty(globalThis, 'length', {get() {- return document.querySelectorAll('iframe').length;+ return __obscuraCore.ops.op_frame_relation(_realmContextId, 0, 0, '');},configurable: true,enumerable: true@@ -8237,11 +8249,8 @@ Object.defineProperty(globalThis, 'length', {for (let i = 0; i < 50; i++) {Object.defineProperty(globalThis, i, {get() {- const iframes = document.querySelectorAll('iframe');- if (i < iframes.length) {- return iframes[i].contentWindow;- }- return undefined;+ const id = __obscuraCore.ops.op_frame_relation(_realmContextId, 2, i, '');+ return id < 0 ? undefined : _windowForContext(id);},configurable: true,enumerable: false@@ -15546,14 +15555,11 @@ function _windowNamedCandidates(name) {}function _windowNamedValue(name) {- const matches = _windowNamedCandidates(name);+ const contextId = __obscuraCore.ops.op_frame_relation(_realmContextId, 3, 0, name);+ if (contextId >= 0) return _windowForContext(contextId);+ const matches = _windowNamedCandidates(name).filter(([nid, namedFrame]) =>+ !namedFrame || _domParse('get_attribute', nid, 'id') === name);if (matches.length === 0) return undefined;- for (const [nid, namedFrame] of matches) {- if (namedFrame) {- const window = _wrapEl(nid).contentWindow;- if (window) return window;- }- }if (matches.length > 1) return HTMLCollection._from(matches.map(([nid]) => _wrapEl(nid)));return _wrapEl(matches[0][0]);}@@ -16337,7 +16343,6 @@ globalThis.__obscura_liveFrameIds = function () {// surviving reference keeps the frame's context and DOM tree alive.globalThis.__obscura_forgetFrame = function (frameId) {_dom('retire_frame', frameId);- _remoteWindows.delete(frameId);delete globalThis.__obscura_frameElements[frameId];delete globalThis.__obscura_frameObjects[frameId];delete globalThis.__obscura_frameWindows[frameId];@@ -16363,7 +16368,7 @@ function _targetOriginAllows(targetOrigin, receiverOrigin, senderOrigin) {return receiverOrigin === expected;}-function _sendRealmMessage(targetFrameId, data, targetOrigin) {+function _serializeFrameMessage(data) {let json;// Structured clone cannot cross realms here. JSON carries what postMessage is// actually used for; anything else throws the same DataCloneError a browser@@ -16374,6 +16379,18 @@ function _sendRealmMessage(targetFrameId, data, targetOrigin) {throw new DOMException('The object could not be cloned.', 'DataCloneError');}if (json === undefined) json = '{"v":null}';+ return json;+}++function _sendContextMessage(contextId, data, targetOrigin) {+ const frameId = __obscuraCore.ops.op_frame_relation(contextId, 5, 0, '');+ if (frameId >= 0) return _sendRealmMessage(frameId, data, targetOrigin);+ _serializeFrameMessage(data);+ if (targetOrigin !== undefined && targetOrigin !== null) String(targetOrigin);+}++function _sendRealmMessage(targetFrameId, data, targetOrigin) {+ const json = _serializeFrameMessage(data);// An unspecified targetOrigin stays permissive (empty string); the receiver// enforces a specified one against its own origin in __obscura_deliverMessage.const to = (targetOrigin === undefined || targetOrigin === null) ? '' : String(targetOrigin);@@ -16416,6 +16433,7 @@ function _connectInsertedFrames(root, html) {function _ensureInitialFrameRealm(element, srcdoc) {if (element._frameId || !element.isConnected) return;+ _connectFrameContext(element);// An opaque sandbox must never receive the creator's security token.let opaque = element.hasAttribute('sandbox') &&!element.getAttribute('sandbox').toLowerCase().split(/\s+/).includes('allow-same-origin');@@ -16490,7 +16508,8 @@ function _resetIframeElement(element) {// here". Calling the frame's own postMessage would make the frame both sender// and receiver, losing the sender's origin and source.function _frameWindowFor(frameId) {- if (!frameId) return null;+ if (frameId === _realmFrameId) return globalThis;+ if (!frameId) return _remoteWindow(0);const real = globalThis.__obscura_frameObjects?.[frameId]?.window;const existing = globalThis.__obscura_frameWindows[frameId];if (!real) return existing || _remoteWindow(frameId);@@ -16498,8 +16517,9 @@ function _frameWindowFor(frameId) {if (existing && existing.__obscura_wrapsRealm) return existing;const parentId = Reflect.get(real, '__obscura_parentFrameId') || 0;+ const contextId = __obscuraCore.ops.op_frame_context(frameId);const post = _markNative(function (data, targetOrigin, _transfer) {- _sendRealmMessage(frameId, data, targetOrigin);+ _sendContextMessage(contextId, data, targetOrigin);});const win = new Proxy(real, {get(target, prop) {@@ -16523,7 +16543,7 @@ function _frameWindowFor(frameId) {}// The host calls this inside the target realm.-globalThis.__obscura_deliverMessage = function(dataJson, origin, sourceFrameId, targetOrigin) {+globalThis.__obscura_deliverMessage = function(dataJson, origin, sourceFrameId, targetOrigin, sourceContextId = -1) {// Enforce postMessage's targetOrigin against THIS (the receiving) realm's// origin, the same check a real browser does at delivery time. A mismatch// drops the message silently.@@ -16531,7 +16551,8 @@ globalThis.__obscura_deliverMessage = function(dataJson, origin, sourceFrameId,let data = null;try { data = JSON.parse(dataJson).v; } catch (_) {}// Who to reply to: the frame above, or one of the frames below.- const source = (globalThis.__obscura_frameId !== 0+ const source = sourceContextId >= 0 ? _windowForContext(sourceContextId)+ : (globalThis.__obscura_frameId !== 0&& sourceFrameId === globalThis.__obscura_parentFrameId)? globalThis.parent: _frameWindowFor(sourceFrameId);@@ -16547,17 +16568,17 @@ globalThis.__obscura_deliverMessage = function(dataJson, origin, sourceFrameId,}};-function _remoteWindowChildren(frameId) {- try {- return JSON.parse(__obscuraCore.ops.op_frame_children(frameId >>> 0));- } catch (_) {- return [];- }+function _connectFrameContext(element) {+ if (!element.isConnected || element.namespaceURI !== 'http://www.w3.org/1999/xhtml') return -1;+ return __obscuraCore.ops.op_connect_frame(_realmFrameId, element._nid);}-function _resolveFrameWindow(frameId) {- if (frameId === _realmFrameId) return globalThis;- return _frameWindowFor(frameId) || _remoteWindow(frameId);+function _windowForContext(contextId) {+ if (contextId === _realmContextId) return globalThis;+ const owner = __obscuraCore.ops.op_frame_relation(contextId, 6, _realmFrameId, '');+ if (owner >= 0) return _wrapEl(owner).contentWindow;+ const frameId = __obscuraCore.ops.op_frame_relation(contextId, 5, 0, '');+ return frameId < 0 ? _remoteContextWindow(contextId) : _frameWindowFor(frameId);}// A window in another browsing context, as seen from this one.@@ -16567,108 +16588,117 @@ function _resolveFrameWindow(frameId) {// across origins anyway. Widgets use postMessage regardless, which is what it// is for.class _RemoteWindow {- constructor(frameId) {- Object.defineProperty(this, '_frameId', { value: frameId, enumerable: false });+ postMessage(data, targetOrigin, _transfer) {+ _sendContextMessage(_remoteContextId(this), data, targetOrigin);}- postMessage(data, targetOrigin, _transfer) { _sendRealmMessage(this._frameId, data, targetOrigin); }- get self() { return this; }- get window() { return this; }- get frames() { return this; }+ get self() { return this.closed ? null : this; }+ get window() { return this.closed ? null : this; }+ get frames() { return this.closed ? null : this; }get parent() {- if (this._frameId === 0) return this;- const pid = __obscuraCore.ops.op_frame_parent(this._frameId);- return pid === _realmFrameId ? globalThis : _remoteWindow(pid);- }- get top() {- return this._frameId === 0 ? this : (0 === _realmFrameId ? globalThis : _remoteWindow(0));+ const id = __obscuraCore.ops.op_frame_relation(_remoteContextId(this), 1, 0, '');+ return id < 0 ? null : _windowForContext(id);}+ get top() { return this.closed ? null : _windowForContext(0); }get opener() { return null; }- get closed() { return false; }- get length() { return _remoteWindowChildren(this._frameId).length; }+ get closed() { return __obscuraCore.ops.op_frame_relation(_remoteContextId(this), 4, 0, '') !== 1; }+ get length() { return __obscuraCore.ops.op_frame_relation(_remoteContextId(this), 0, 0, ''); }focus() {}blur() {}close() {}- get [Symbol.toStringTag]() { return 'Window'; }}_markNative(_RemoteWindow.prototype.postMessage);+const _remoteContextIds = new WeakMap();+function _remoteContextId(window) {+ const id = _remoteContextIds.get(window);+ if (id === undefined) throw new TypeError('Illegal invocation');+ return id;+}+function _remoteIndex(property) {+ return typeof property === 'string' && /^(0|[1-9][0-9]*)$/.test(property)+ && Number(property) < 4294967295;+}+function _remoteChild(id, property) {+ if (typeof property !== 'string') return -1;+ return _remoteIndex(property)+ ? __obscuraCore.ops.op_frame_relation(id, 2, Number(property), '')+ : __obscuraCore.ops.op_frame_relation(id, 3, 0, property);+}+function _remoteAllowed(property) {+ return property !== 'constructor' && Object.prototype.hasOwnProperty.call(_RemoteWindow.prototype, property);+}+const _remoteFallbacks = ['then', Symbol.toStringTag, Symbol.hasInstance, Symbol.isConcatSpreadable];+function _remoteAccessError() {+ return new DOMException('Blocked cross-origin Window access', 'SecurityError');+}const _remoteWindowProxyHandler = {+ getPrototypeOf() { return null; },+ setPrototypeOf() { throw _remoteAccessError(); },+ defineProperty() { throw _remoteAccessError(); },+ deleteProperty() { throw _remoteAccessError(); },+ set() { throw _remoteAccessError(); },+ preventExtensions() { throw _remoteAccessError(); },get(target, prop, receiver) {- if (prop === 'length') {- return _remoteWindowChildren(target._frameId).length;- }- if (typeof prop === 'string') {- const index = Number(prop);- if (Number.isInteger(index) && index >= 0 && String(index) === prop) {- const children = _remoteWindowChildren(target._frameId);- if (index < children.length) {- return _resolveFrameWindow(children[index][0]);- }- return undefined;- }- }- if (prop in target) {- return Reflect.get(target, prop, receiver);- }- if (typeof prop === 'string' && prop !== '') {- const children = _remoteWindowChildren(target._frameId);- for (let i = 0; i < children.length; i++) {- if (children[i][1] === prop) {- return _resolveFrameWindow(children[i][0]);- }- }- }- return Reflect.get(target, prop, receiver);+ if (_remoteAllowed(prop)) return Reflect.get(target, prop, receiver);+ if (prop === '__obscura_wrapsRealm') return false;+ const child = _remoteChild(_remoteContextId(target), prop);+ if (child >= 0) return _windowForContext(child);+ if (_remoteFallbacks.includes(prop)) return undefined;+ throw _remoteAccessError();},has(target, prop) {- if (Reflect.has(target, prop)) return true;- if (typeof prop === 'string') {- const index = Number(prop);- if (Number.isInteger(index) && index >= 0 && String(index) === prop) {- return index < _remoteWindowChildren(target._frameId).length;- }- const children = _remoteWindowChildren(target._frameId);- return children.some(c => c[1] && c[1] === prop);- }- return false;+ if (_remoteAllowed(prop) || (typeof prop === 'symbol' && _remoteFallbacks.includes(prop))) return true;+ if (_remoteIndex(prop) && _remoteChild(_remoteContextId(target), prop) >= 0) return true;+ throw _remoteAccessError();},ownKeys(target) {- const keys = Reflect.ownKeys(target);- const count = _remoteWindowChildren(target._frameId).length;- for (let i = 0; i < count; i++) {- const key = String(i);- if (!keys.includes(key)) keys.push(key);- }- return keys;+ const count = __obscuraCore.ops.op_frame_relation(_remoteContextId(target), 0, 0, '');+ return [...Array.from({length:count}, (_, index) => String(index)),+ ...Object.getOwnPropertyNames(_RemoteWindow.prototype).filter(_remoteAllowed), ..._remoteFallbacks];},getOwnPropertyDescriptor(target, prop) {- if (typeof prop === 'string') {- const index = Number(prop);- if (Number.isInteger(index) && index >= 0 && String(index) === prop) {- const children = _remoteWindowChildren(target._frameId);- if (index < children.length) {- return {- value: _resolveFrameWindow(children[index][0]),- writable: false,- enumerable: true,- configurable: true,- };- }- }- }- return Reflect.getOwnPropertyDescriptor(target, prop);+ const receiver = _remoteContextWindow(_remoteContextId(target));+ return {value:receiver[prop], writable:false, enumerable:_remoteIndex(prop), configurable:true};},};const _remoteWindows = new Map();-function _remoteWindow(frameId) {- let win = _remoteWindows.get(frameId);+const _remoteWindowFinalizer = new FinalizationRegistry(({id, reference}) => {+ if (_remoteWindows.get(id) === reference) _remoteWindows.delete(id);+});+function _remoteContextWindow(contextId) {+ if (contextId === _realmContextId) return globalThis;+ let win = _remoteWindows.get(contextId)?.deref();if (!win) {- win = new Proxy(new _RemoteWindow(frameId), _remoteWindowProxyHandler);- _remoteWindows.set(frameId, win);+ const target = new _RemoteWindow();+ win = new Proxy(target, _remoteWindowProxyHandler);+ _remoteContextIds.set(target, contextId);+ _remoteContextIds.set(win, contextId);+ const reference = new WeakRef(win);+ _remoteWindows.set(contextId, reference);+ _remoteWindowFinalizer.register(win, {id:contextId, reference});}return win;}+function _remoteWindow(frameId) {+ const contextId = __obscuraCore.ops.op_frame_context(frameId);+ return contextId < 0 ? null : _remoteContextWindow(contextId);+}++Object.defineProperty(globalThis, 'closed', {+ get() { return __obscuraCore.ops.op_frame_relation(_realmContextId, 4, 0, '') !== 1; },+ enumerable:true, configurable:true,+});+let _windowName = '';+Object.defineProperty(globalThis, 'name', {+ get() { return _realmContextId === 0 ? _windowName : __obscuraCore.ops.op_frame_name(_realmContextId, undefined); },+ set(value) {+ const name = `${value}`;+ if (_realmContextId === 0) _windowName = name;+ else __obscuraCore.ops.op_frame_name(_realmContextId, name);+ },+ enumerable:true, configurable:true,+});// Installs `parent` and `top` for a framed document. Called from// __obscura_init, before any of the document's own scripts run: `parent ===@@ -19562,6 +19592,7 @@ globalThis.__obscura_init_frames = function() {globalThis.__obscura_init = (function() {// The host sets __obscura_frameId on a frame realm before calling this._realmFrameId = globalThis.__obscura_frameId >>> 0;+ _realmContextId = __obscuraCore.ops.op_frame_context(_realmFrameId);_formCacheEpoch = null;_formOwnerSnapshots = new WeakMap();_formControlSnapshots = new WeakMap();diff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rsindex 1dcaa3de..8bd1986e 100644--- a/crates/obscura-js/src/frame.rs+++ b/crates/obscura-js/src/frame.rs@@ -211,6 +211,22 @@ impl FrameRealm {)}+ /// Delivers a queued message without losing a retired sender's Window identity.+ pub fn deliver_queued_message(+ &self,+ parent: &mut ObscuraJsRuntime,+ message: &crate::ops::PendingFrameMessage,+ ) -> Result<(), String> {+ self.execute_script(parent, &format!(+ "globalThis.__obscura_deliverMessage({}, {}, {}, {}, {});",+ encode_json_argument(&message.data_json),+ encode_json_argument(&message.origin),+ message.source_frame_id,+ encode_json_argument(&message.target_origin),+ message.source_context_id.map_or(-1i64, i64::from),+ ))+ }+pub fn frame_id(&self) -> u32 {self.frame_id}@@ -807,7 +823,7 @@ mod tests {__obscura_deliverMessage('{"v":"grandchild"}', 'https://parent.example', 2, '*');sourceParent.postMessage('reply', '*');"#).unwrap();- assert_eq!(parent.evaluate("[sourceParent !== window, sourceParent.document === undefined]").unwrap(),+ assert_eq!(parent.evaluate("[sourceParent !== window, (() => { try { sourceParent.document; return false; } catch (e) { return e.name === 'SecurityError'; } })()]").unwrap(),serde_json::json!([true, true]));let messages = parent.take_pending_frame_messages();assert_eq!(messages.iter().map(|message| (@@ -1935,7 +1951,20 @@ mod tests {}#[tokio::test(flavor = "current_thread")]- async fn cross_origin_child_frame_sees_parent_frames_and_named_siblings() {+ async fn parsed_frame_metadata_exists_without_eager_realms_or_started_loads() {+ let mut parent = page("https://parent.example/",+ "<html><body><iframe name='a' src='https://other.example/a'></iframe>\+ <iframe name='b' src='https://other.example/b'></iframe></body></html>");+ assert_eq!(parent.evaluate("frames.length").unwrap().as_f64(), Some(2.0));+ assert_eq!(parent.realm_states().borrow().live_count(), 0);+ assert!(parent.take_pending_frames().is_empty());+ assert_eq!(parent.evaluate(+ "[frames.a === frames[0], frames.b === frames[1], frames[0] !== frames[1]]"+ ).unwrap(), serde_json::json!([true, true, true]));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn unowned_frame_realms_do_not_alias_connected_frame_owners() {let mut parent = page("https://parent.example/","<html><body>\@@ -1943,6 +1972,7 @@ mod tests {<iframe name=\"b\" src=\"https://other.example/b\"></iframe>\</body></html>",);+ parent.evaluate_script("__obscura_init_frames();").unwrap();let frame_a = FrameRealm::new(&mut parent,1,@@ -1965,13 +1995,14 @@ mod tests {parent.frames[0] === window,parent.frames[1] === window,typeof parent.frames.b,+ parent.frames.a !== window,parent.frames.b !== window,parent.parent === parent,parent.top === parent,]"#).unwrap();assert_eq!(result_a, serde_json::json!([- 2, 2, true, false, "object", true, true, true+ 2, 2, false, false, "object", true, true, true, true]));let result_b = frame_b.evaluate(&mut parent, r#"@@ -1985,48 +2016,15 @@ mod tests {]"#).unwrap();assert_eq!(result_b, serde_json::json!([- 2, 2, false, true, true, "object"+ 2, 2, false, false, false, "object"]));frame_a.execute_script(&mut parent, r#"parent.frames.b.postMessage('hello from a', '*');"#).unwrap();- let mut messages = parent.take_pending_frame_messages();- assert_eq!(messages.len(), 1);- assert_eq!(messages[0].target_frame_id, 2);- assert_eq!(messages[0].source_frame_id, 1);-- let message = messages.pop().unwrap();- frame_b.execute_script(&mut parent, r#"- globalThis.received = [];- addEventListener('message', event => {- received.push({- data: event.data,- sourceIsA: event.source === parent.frames[0],- });- event.source.postMessage('reply from b', '*');- });- "#).unwrap();- frame_b.deliver_message(- &mut parent,- &message.data_json,- &message.origin,- message.source_frame_id,- &message.target_origin,- ).unwrap();-- let received = frame_b.evaluate(&mut parent, "globalThis.received").unwrap();- assert_eq!(received, serde_json::json!([{- "data": "hello from a",- "sourceIsA": true,- }]));-- let replies = parent.take_pending_frame_messages();- assert_eq!(replies.len(), 1);- assert_eq!(replies[0].target_frame_id, 1);- assert_eq!(replies[0].source_frame_id, 2);+ assert!(parent.take_pending_frame_messages().is_empty(),+ "an unowned realm must not receive a pending owner's message");- // Grandchild frame C inside frame A (parent_frame_id: 1)let frame_c = FrameRealm::new(&mut parent,3,@@ -2038,8 +2036,9 @@ mod tests {[parent.parent === top,parent.parent.frames.length,+ parent.parent.frames.a === parent,]"#).unwrap();- assert_eq!(result_c, serde_json::json!([true, 2]));+ assert_eq!(result_c, serde_json::json!([true, 2, false]));}}diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 1acffd3f..dcfb1152 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -673,6 +673,8 @@ pub struct PendingFrameMessage {pub target_frame_id: u32,/// Where it came from, so the receiver can reply through `event.source`.pub source_frame_id: u32,+ /// The sender's browsing context, even if its document retires before delivery.+ pub source_context_id: Option<u32>,/// The sender's origin, for `event.origin`.pub origin: String,/// The origin the sender restricted delivery to (postMessage's@@ -1236,12 +1238,24 @@ pub type SharedState = Rc<RefCell<ObscuraState>>;pub struct RealmStates {entries: Vec<(v8::Global<v8::Context>, u32, SharedState)>,frame_timers: HashMap<u32, FrameTimers>,+ frame_contexts: HashMap<u32, FrameContext>,+ frame_context_owners: HashMap<(*const RefCell<ObscuraState>, NodeId, u64), u32>,+ frame_context_children: HashMap<u32, Vec<u32>>,+ last_frame_context: u32,pub(crate) frame_preload_scripts: Vec<String>,}struct FrameTimers {owner: Option<(std::rc::Weak<RefCell<ObscuraState>>, NodeId, u64)>,cancel: Rc<CancelHandle>,+ context_id: Option<u32>,+}++struct FrameContext {+ owner: Option<(std::rc::Weak<RefCell<ObscuraState>>, NodeId, u64)>,+ parent: Option<u32>,+ frame_id: Option<u32>,+ name: String,}impl RealmStates {@@ -1259,10 +1273,10 @@ impl RealmStates {}pub(crate) fn forget_frame(&mut self, frame_id: u32) {- self.cancel_frame_timers(frame_id);+ self.retire_frame(frame_id);self.entries.retain(|(_, id, _)| *id != frame_id);self.frame_timers.remove(&frame_id);- self.cancel_inactive_frame_timers();+ self.prune_frame_contexts();}pub fn register(&mut self,@@ -1270,9 +1284,17 @@ impl RealmStates {frame_id: u32,state: SharedState,) {+ let context_id = self.frame_timers.get(&frame_id).and_then(|frame| frame.context_id)+ .or_else(|| {+ let parent = self.context_for_frame(state.borrow().parent_frame_id);+ self.allocate_frame_context(FrameContext {+ owner: None, parent, frame_id: Some(frame_id), name: String::new(),+ })+ });self.frame_timers.entry(frame_id).or_insert_with(|| FrameTimers {- owner: None, cancel: CancelHandle::new_rc(),+ owner: None, cancel: CancelHandle::new_rc(), context_id,});+ self.connect_document_frames(&state);self.entries.push((context, frame_id, state));}@@ -1284,11 +1306,148 @@ impl RealmStates {}}- fn own_frame(&mut self, frame_id: u32, parent: &SharedState, node: NodeId) {+ pub(crate) fn own_frame(&mut self, frame_id: u32, parent: &SharedState, node: NodeId) {let generation = parent.borrow().document_generation;- self.frame_timers.entry(frame_id).or_insert_with(|| FrameTimers {- owner: None, cancel: CancelHandle::new_rc(),- }).owner = Some((Rc::downgrade(parent), node, generation));+ let context_id = self.connect_frame_context(parent, node);+ if let Some(context_id) = context_id {+ let context = self.frame_contexts.get_mut(&context_id).unwrap();+ if let Some(previous) = context.frame_id.replace(frame_id).filter(|id| *id != frame_id) {+ if let Some(frame) = self.frame_timers.get(&previous) { frame.cancel.cancel(); }+ }+ }+ let previous = self.frame_timers.get(&frame_id).and_then(|frame| frame.context_id);+ if previous != context_id {+ if let Some(previous) = previous.filter(|id|+ self.frame_contexts.get(id).is_some_and(|context| context.owner.is_none()))+ {+ self.frame_contexts.remove(&previous);+ }+ }+ let frame = self.frame_timers.entry(frame_id).or_insert_with(|| FrameTimers {+ owner: None, cancel: CancelHandle::new_rc(), context_id,+ });+ frame.owner = Some((Rc::downgrade(parent), node, generation));+ frame.context_id = context_id;+ }++ fn allocate_frame_context(&mut self, context: FrameContext) -> Option<u32> {+ let Some(id) = self.last_frame_context.checked_add(1) else {+ tracing::error!("frame context id space exhausted");+ return None;+ };+ self.last_frame_context = id;+ if context.owner.is_some() {+ if let Some(parent) = context.parent {+ self.frame_context_children.entry(parent).or_default().push(id);+ }+ }+ self.frame_contexts.insert(id, context);+ Some(id)+ }++ fn context_for_frame(&self, frame_id: u32) -> Option<u32> {+ if frame_id == 0 { return Some(0); }+ self.frame_timers.get(&frame_id).and_then(|frame| frame.context_id)+ }++ fn connect_frame_context(&mut self, parent: &SharedState, node: NodeId) -> Option<u32> {+ let state = parent.borrow();+ if state.frame_id != 0 && self.frame_timers_active(state.frame_id) != Some(true) {+ return None;+ }+ let dom = state.dom.as_ref()?;+ if !dom.is_connected(node) || !dom.with_node(node, |node|+ node.as_element().is_some_and(|tag| tag.ns.as_ref() == "http://www.w3.org/1999/xhtml"+ && matches!(tag.local.as_ref(), "iframe" | "frame"))).unwrap_or(false)+ {+ return None;+ }+ let key = (Rc::as_ptr(parent), node, state.document_generation);+ if let Some(id) = self.frame_context_owners.get(&key) { return Some(*id); }+ let parent_context = self.context_for_frame(state.frame_id)?;+ let name = dom.with_node(node, |node|+ node.get_attribute("name").unwrap_or("").to_owned()).unwrap_or_default();+ let id = self.allocate_frame_context(FrameContext {+ owner: Some((Rc::downgrade(parent), node, state.document_generation)),+ parent: Some(parent_context), frame_id: None, name,+ })?;+ self.frame_context_owners.insert(key, id);+ Some(id)+ }++ pub(crate) fn connect_document_frames(&mut self, parent: &SharedState) {+ let nodes = {+ let parent = parent.borrow();+ let Some(dom) = &parent.dom else { return };+ match dom.query_selector_all("iframe,frame") {+ Ok(nodes) => nodes,+ Err(error) => {+ tracing::error!(%error, "cannot enumerate parsed frame owners");+ return;+ }+ }+ };+ for node in nodes { self.connect_frame_context(parent, node); }+ }++ fn frame_context_active(&self, mut id: u32) -> Option<bool> {+ for _ in 0..=self.frame_contexts.len() {+ if id == 0 { return Some(true); }+ let Some(context) = self.frame_contexts.get(&id) else { return Some(false) };+ if let Some((parent, node, generation)) = &context.owner {+ let Some(parent) = parent.upgrade() else { return Some(false) };+ let parent = parent.try_borrow().ok()?;+ if parent.document_generation != *generation+ || !parent.dom.as_ref().is_some_and(|dom| dom.is_connected(*node))+ {+ return Some(false);+ }+ return if parent.frame_id == 0 { Some(true) }+ else { self.frame_timers_active(parent.frame_id) };+ }+ match context.frame_id.and_then(|frame| self.frame_timers_active(frame)) {+ Some(true) => {}+ Some(false) => return Some(false),+ None if context.frame_id.is_some() => return None,+ None => return Some(false),+ }+ let Some(parent) = context.parent else { return Some(false) };+ id = parent;+ }+ Some(false)+ }++ fn retire_frame(&mut self, frame_id: u32) {+ self.cancel_frame_timers(frame_id);+ if let Some(context) = self.context_for_frame(frame_id)+ .and_then(|id| self.frame_contexts.get_mut(&id))+ {+ if context.frame_id == Some(frame_id) { context.frame_id = None; }+ }+ self.prune_frame_contexts();+ }++ fn retire_frame_contexts(&mut self, ids: &std::collections::HashSet<u32>) {+ for id in ids {+ if let Some(context) = self.frame_contexts.remove(id) {+ if let Some(frame) = context.frame_id.and_then(|id| self.frame_timers.get(&id)) {+ frame.cancel.cancel();+ }+ if let Some((owner, node, generation)) = context.owner {+ self.frame_context_owners.remove(&(owner.as_ptr(), node, generation));+ }+ self.frame_context_children.remove(id);+ }+ }+ for children in self.frame_context_children.values_mut() {+ children.retain(|id| !ids.contains(id));+ }+ }++ pub(crate) fn prune_frame_contexts(&mut self) {+ let retired = self.frame_contexts.keys().copied()+ .filter(|id| self.frame_context_active(*id) == Some(false)).collect();+ self.retire_frame_contexts(&retired);}pub(crate) fn frame_timers_active(&self, mut frame_id: u32) -> Option<bool> {@@ -1325,9 +1484,9 @@ impl RealmStates {}fn frames_removed_by(&self, shared: &SharedState, cmd: &str, arg1: &str, arg2: &str)- -> Vec<(u32, u32)>+ -> Vec<(u32, u32, u32)>{- if self.frame_timers.is_empty() { return Vec::new(); }+ if self.frame_contexts.is_empty() { return Vec::new(); }let (root, inclusive) = match cmd {"append_child" => (arg2, true),"insert_before" | "remove_child" => (arg1, true),@@ -1339,13 +1498,13 @@ impl RealmStates {let root = NodeId::new(root);let state = shared.borrow();let Some(dom) = &state.dom else { return Vec::new() };+ if inclusive && !dom.is_connected(root) { return Vec::new(); }let mut removed = Vec::new();- // ponytail: scan the bounded live-frame registry only on structural- // mutations; index owners by document if frame-heavy profiling warrants it.- for (id, timers) in &self.frame_timers {- let Some((parent, node, generation)) = &timers.owner else { continue };+ // Only structural mutations inspect the bounded live-frame registry.+ for (id, context) in &self.frame_contexts {+ let Some((parent, node, generation)) = &context.owner else { continue };if parent.as_ptr() != Rc::as_ptr(shared) || *generation != state.document_generation- || timers.cancel.is_canceled() || !dom.is_connected(*node)+ || self.frame_context_active(*id) != Some(true){continue;}@@ -1353,7 +1512,7 @@ impl RealmStates {for _ in 0..=dom.len() {let Some(current_node) = current else { break };if current_node == root && (inclusive || current_node != *node) {- removed.push((*id, node.index() as u32));+ removed.push((*id, context.frame_id.unwrap_or(0), node.index() as u32));break;}current = dom.with_node(current_node, |node| node.parent).flatten()@@ -2307,20 +2466,20 @@ fn op_dom(std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {let registry = state.borrow::<Rc<RefCell<RealmStates>>>();if cmd == "retire_frame" {- if let Ok(id) = arg1.parse::<u32>() { registry.borrow().cancel_frame_timers(id); }+ if let Ok(id) = arg1.parse::<u32>() { registry.borrow_mut().retire_frame(id); }return "true".into();}let removed = registry.borrow().frames_removed_by(&shared, &cmd, &arg1, &arg2);let result = op_dom_inner(shared, cmd, arg1, arg2);if result == "true" && !removed.is_empty() {- let registry = registry.borrow();- for (id, _) in &removed {- if let Some(timers) = registry.frame_timers.get(id) { timers.cancel.cancel(); }- }+ let mut registry = registry.borrow_mut();+ registry.retire_frame_contexts(&removed.iter().map(|(id, _, _)| *id).collect());registry.cancel_inactive_frame_timers();+ registry.prune_frame_contexts();// The bootstrap unwraps this private mutation result before any// DOM caller sees it, and resets only the retired iframe identities.- serde_json::json!({"__obscuraFrameRetirements":removed,"result":result}).to_string()+ let retired: Vec<_> = removed.into_iter().map(|(_, frame, node)| (frame, node)).collect();+ serde_json::json!({"__obscuraFrameRetirements":retired,"result":result}).to_string()} else {result}@@ -6937,6 +7096,8 @@ fn op_post_frame_message(.unwrap_or_else(|_| "null".to_string())});drop(source);+ let source_context_id = state.borrow::<Rc<RefCell<RealmStates>>>().borrow()+ .context_for_frame(source_frame_id);let gs = state.borrow::<SharedState>().clone();let mut gs = gs.borrow_mut();let over_entries = gs.pending_frame_messages.len() >= frame_message_queue_entry_limit();@@ -6959,6 +7120,7 @@ fn op_post_frame_message(gs.pending_frame_messages.push(PendingFrameMessage {target_frame_id,source_frame_id,+ source_context_id,origin,target_origin: target_origin.to_string(),data_json: data_json.to_string(),@@ -7311,8 +7473,8 @@ fn op_initial_frame(child.inherit_resources(&parent);}let handle = v8::Global::new(scope, context);- registry.borrow_mut().register(handle.clone(), frame_id, Rc::new(RefCell::new(child)));registry.borrow_mut().own_frame(frame_id, &parent_state, NodeId::new(owner_node));+ registry.borrow_mut().register(handle.clone(), frame_id, Rc::new(RefCell::new(child)));let window = context.global(scope);let id = v8::Integer::new_from_unsigned(scope, frame_id);let receiver = v8::undefined(scope);@@ -8426,78 +8588,100 @@ fn op_frame_preload_scripts(state: &OpState) -> String {}#[op2(fast)]-fn op_frame_parent(state: &OpState, target_frame_id: u32) -> u32 {- if target_frame_id == 0 {- return 0;- }- frame_state(state, target_frame_id).borrow().parent_frame_id+fn op_connect_frame(state: &OpState, parent_frame_id: u32, node_id: u32) -> f64 {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let parent = if parent_frame_id == 0 { Some(state.borrow::<SharedState>().clone()) }+ else { state.borrow::<Rc<RefCell<RealmStates>>>().borrow().by_frame_id(parent_frame_id) };+ let id = parent.and_then(|parent|+ state.borrow::<Rc<RefCell<RealmStates>>>().borrow_mut()+ .connect_frame_context(&parent, NodeId::new(node_id)));+ if id.is_none() {+ tracing::warn!(parent_frame_id, node_id, "rejecting inactive frame owner");+ }+ id.map_or(-1.0, f64::from)+ })).unwrap_or_else(|_| {+ tracing::error!("op_connect_frame panicked");+ -1.0+ })}-#[op2]-#[string]-fn op_frame_children(state: &OpState, target_frame_id: u32) -> String {+#[op2(fast)]+fn op_frame_context(state: &OpState, frame_id: u32) -> f64 {std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- let registry = state.borrow::<Rc<RefCell<RealmStates>>>();- let target_state = frame_state(state, target_frame_id);- let target = target_state.borrow();- let generation = target.document_generation;- let mut children: Vec<(u32, String)> = Vec::new();- let reg = registry.borrow();-- let matching_entries: Vec<u32> = reg- .entries- .iter()- .filter(|(_, id, child_state)| {- *id != target_frame_id && child_state.borrow().parent_frame_id == target_frame_id- })- .map(|(_, id, _)| *id)- .collect();+ state.borrow::<Rc<RefCell<RealmStates>>>().borrow()+ .context_for_frame(frame_id).map_or(-1.0, f64::from)+ })).unwrap_or_else(|_| {+ tracing::error!("op_frame_context panicked");+ -1.0+ })+}- if let Some(dom) = target.dom.as_ref() {- let mut frame_index = 0;- for node_id in dom.descendants(dom.document()) {- let is_frame = dom.with_node(node_id, |node| {- node.as_element().is_some_and(|tag| {- tag.ns.as_ref() == "http://www.w3.org/1999/xhtml"- && (tag.local.as_ref() == "iframe" || tag.local.as_ref() == "frame")- })- }).unwrap_or(false);- if !is_frame {- continue;- }- let name = dom.with_node(node_id, |node| {- node.get_attribute("name")- .or_else(|| node.get_attribute_ns("", "name"))- .or_else(|| node.get_attribute("id"))- .or_else(|| node.get_attribute_ns("", "id"))- .map(str::to_owned)- }).flatten().unwrap_or_default();- let child_id = reg.child_frame_for_node(&target_state, node_id)- .or_else(|| {- reg.frame_timers.iter().find_map(|(&id, timers)| {- let (owner, owner_node, owner_generation) = timers.owner.as_ref()?;- (owner.as_ptr() == std::rc::Rc::as_ptr(&target_state)- && *owner_node == node_id- && *owner_generation == generation)- .then_some(id)- })- })- .or_else(|| matching_entries.get(frame_index).copied());- frame_index += 1;- if let Some(child_id) = child_id {- children.push((child_id, name));- }- }+// Relations: child count, parent, indexed/named child, liveness, realm, local owner.+#[op2(fast)]+fn op_frame_relation(+ state: &OpState, context_id: u32, relation: u32, index: u32, #[string] name: &str,+) -> f64 {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let registry = state.borrow::<Rc<RefCell<RealmStates>>>().borrow();+ let active = registry.frame_context_active(context_id) == Some(true);+ if relation == 4 { return if active { 1.0 } else { 0.0 }; }+ if !active { return if relation == 0 { 0.0 } else { -1.0 }; }+ if relation == 1 {+ return if context_id == 0 { 0.0 } else {+ registry.frame_contexts.get(&context_id).and_then(|context| context.parent)+ .map_or(-1.0, f64::from)+ };}-- if children.is_empty() {- for id in matching_entries {- children.push((id, String::new()));- }+ if relation == 5 {+ return if context_id == 0 { 0.0 } else {+ registry.frame_contexts.get(&context_id).and_then(|context| context.frame_id)+ .filter(|id| registry.frame_timers_active(*id) == Some(true))+ .map_or(-1.0, f64::from)+ };+ }+ if relation == 6 {+ let Some((owner, node, generation)) = registry.frame_contexts.get(&context_id)+ .and_then(|context| context.owner.as_ref()) else { return -1.0 };+ let caller = if index == 0 { Some(state.borrow::<SharedState>().clone()) }+ else { registry.by_frame_id(index) };+ return caller.filter(|caller| owner.as_ptr() == Rc::as_ptr(caller)+ && caller.borrow().document_generation == *generation)+ .map_or(-1.0, |_| node.index() as f64);+ }+ let mut children = registry.frame_context_children.get(&context_id).into_iter().flatten()+ .copied().filter(|id| registry.frame_context_active(*id) == Some(true));+ match relation {+ 0 => children.count() as f64,+ 2 => children.skip(index as usize).next().map_or(-1.0, f64::from),+ 3 if !name.is_empty() => children.find(|id| {+ let context = ®istry.frame_contexts[id];+ if context.name != name { return false; }+ let Some((owner, node, _)) = &context.owner else { return false };+ owner.upgrade().is_some_and(|owner|+ owner.borrow().dom.as_ref().is_some_and(|dom|+ dom.with_node(*node, |node| node.get_attribute("name") == Some(name))+ .unwrap_or(false)))+ }).map_or(-1.0, f64::from),+ _ => -1.0,}+ })).unwrap_or_else(|_| {+ tracing::error!("op_frame_relation panicked");+ -1.0+ })+}- serde_json::to_string(&children).unwrap_or_else(|_| "[]".to_string())- })).unwrap_or_else(|_| "[]".to_string())+#[op2]+#[string]+fn op_frame_name(state: &OpState, context_id: u32, #[string] value: Option<String>) -> String {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let mut registry = state.borrow::<Rc<RefCell<RealmStates>>>().borrow_mut();+ let Some(context) = registry.frame_contexts.get_mut(&context_id) else { return String::new() };+ if let Some(value) = value { context.name = value; }+ context.name.clone()+ })).unwrap_or_else(|_| {+ tracing::error!("op_frame_name panicked");+ String::new()+ })}pub fn build_extension() -> Extension {@@ -8536,8 +8720,10 @@ pub fn build_extension() -> Extension {op_history_traverse(),op_frame_document_ready(),op_initial_frame(),- op_frame_parent(),- op_frame_children(),+ op_connect_frame(),+ op_frame_context(),+ op_frame_relation(),+ op_frame_name(),op_document_realm_member(),op_register_document_realm(),op_post_frame_message(),diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 69279c16..89a2e5c6 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -1377,7 +1377,11 @@ impl ObscuraJsRuntime {gs.resolved_scroll = None;}drop(gs);- self.realm_states().borrow().cancel_inactive_frame_timers();+ let realms = self.realm_states();+ let mut realms = realms.borrow_mut();+ realms.cancel_inactive_frame_timers();+ realms.prune_frame_contexts();+ realms.connect_document_frames(&self.state);}pub fn set_url(&self, url: &str) {@@ -10713,7 +10717,7 @@ mod tests {second.remove();results.push(window.namedContext===collision);byId.name = 'idOnlyFrame';- results.push(window.idOnlyFrame===byId.contentWindow);+ results.push(window.idOnlyFrame===byId && byId.contentWindow.name==='');byId.removeAttribute('name');results.push(window.idOnlyFrame===byId);const duplicate = document.createElement('div'); duplicate.id = 'idOnlyFrame';diff --git a/crates/obscura/tests/stale_frame_metadata.rs b/crates/obscura/tests/stale_frame_metadata.rsnew file mode 100644index 00000000..b30d215b--- /dev/null+++ b/crates/obscura/tests/stale_frame_metadata.rs@@ -0,0 +1,346 @@+use obscura::Browser;+use serde_json::json;+use tokio::io::{AsyncReadExt, AsyncWriteExt};++async fn serve(body: String) -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ tokio::spawn(async move {+ loop {+ let (mut stream, _) = listener.accept().await.unwrap();+ let body = body.clone();+ tokio::spawn(async move {+ let mut request = [0; 4096];+ let bytes = stream.read(&mut request).await.unwrap();+ if request[..bytes].starts_with(b"GET /pending ") {+ tokio::time::sleep(std::time::Duration::from_secs(2)).await;+ }+ let header = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n",+ body.len(),+ );+ stream.write_all(header.as_bytes()).await.unwrap();+ stream.write_all(b"\r\n").await.unwrap();+ stream.write_all(body.as_bytes()).await.unwrap();+ stream.shutdown().await.unwrap();+ });+ }+ });+ format!("http://{address}")+}++#[tokio::test]+async fn pending_replacement_must_not_alias_a_retired_sibling() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let foreign = serve("<!doctype html><p>child</p>".into()).await;+ let parent = serve(format!(+ r#"<!doctype html><iframe name="a" src="{foreign}/a"></iframe>+ <iframe id="b" name="b" src="{foreign}/b"></iframe>"#,+ )).await;+ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&parent).await.unwrap();+ page.settle(500).await;+ let a = page.frame_urls().iter().position(|url| url.ends_with("/a")).unwrap();+ assert_eq!(+ page.evaluate_in_frame(a,+ "(() => { globalThis.retiredSibling = parent.frames.b; return true; })()").unwrap(),+ json!(true),+ );+ assert_eq!(page.evaluate(&format!(+ r#"(() => {{+ document.querySelector('#b').remove();+ const replacement = document.createElement('iframe');+ replacement.name = 'replacement';+ replacement.src = '{foreign}/pending';+ document.body.appendChild(replacement);+ return replacement.isConnected;+ }})()"#,+ )), json!(true));+ assert_eq!(+ page.evaluate_in_frame(a,+ "[parent.frames.length, parent.frames[0] === self, parent.frames[1] === retiredSibling]"+ ).unwrap(),+ json!([2, true, false]),+ );+}++fn child_index(urls: &[String], suffix: &str) -> usize {+ urls.iter().position(|url| url.ends_with(suffix)).unwrap()+}++#[tokio::test]+async fn remote_parent_exposes_siblings_and_preserves_message_sources() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let foreign = serve(r#"<!doctype html><p>child</p><script>+ globalThis.initial = [parent.frames.length, parent.length,+ parent.frames.a === (location.pathname === '/a' ? self : parent.frames[0]),+ typeof parent.frames.b, parent.frames === parent, parent.top === top];+ globalThis.received = [];+ addEventListener('message', event => {+ received.push([event.data, event.source === parent.frames.a,+ event.source === parent.frames.b, event.origin]);+ if (event.data === 'ping') event.source.postMessage('pong', event.origin);+ });+ </script>"#.into()).await;+ let parent = serve(format!(+ r#"<!doctype html><iframe name="a" src="{foreign}/a"></iframe>+ <iframe name="b" src="{foreign}/b"></iframe>+ <iframe name="c" srcdoc="<p>same-origin</p>"></iframe>+ <script>globalThis.earlyFrameCount = frames.length;</script>"#,+ )).await;+ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&parent).await.unwrap();+ page.settle(1000).await;+ assert_eq!(page.evaluate("earlyFrameCount").as_f64(), Some(3.0));+ let urls = page.frame_urls();+ let a = child_index(&urls, "/a");+ let b = child_index(&urls, "/b");+ for index in [a, b] {+ assert_eq!(page.evaluate_in_frame(index, "initial").unwrap(),+ json!([3, 3, true, "object", true, true]));+ assert_eq!(page.evaluate_in_frame(index, r#"[+ parent.frames[0] === parent.frames.a,+ parent.frames[1] === parent.frames.b,+ parent.frames.b.parent === parent,+ parent.frames.b.top === top,+ parent.frames.b.frames === parent.frames.b,+ parent.frames.b.closed,+ (() => { try { parent.frames[99]; return false; } catch (e) { return e.name === 'SecurityError'; } })(),+ 0 in parent.frames,+ (() => { try { 'b' in parent.frames; return false; } catch (e) { return e.name === 'SecurityError'; } })(),+ (() => { try { parent.document; return false; } catch (e) { return e.name === 'SecurityError'; } })(),+ Object.keys(parent).join(','),+ (() => { try { parent.constructor; return false; } catch (e) { return e.name === 'SecurityError'; } })(),+ (() => { try { parent.toString; return false; } catch (e) { return e.name === 'SecurityError'; } })(),+ parent.then === undefined,+ parent[Symbol.toStringTag] === undefined,+ (() => { try { 'then' in parent; return false; } catch (e) { return e.name === 'SecurityError'; } })(),+ Symbol.toStringTag in parent,+ (() => { const descriptor = Object.getOwnPropertyDescriptor(parent, 'b');+ return [descriptor.value === parent.frames[1], descriptor.enumerable,+ descriptor.configurable, descriptor.writable]; })(),+ Object.getPrototypeOf(parent) === null,+ (() => { try { Reflect.setPrototypeOf(parent, {}); return false; } catch (e) { return e.name === 'SecurityError'; } })(),+ (() => { try { Reflect.defineProperty(parent, 'forbidden', {value:1}); return false; } catch (e) { return e.name === 'SecurityError'; } })(),+ (() => { try { Reflect.deleteProperty(parent, 'forbidden'); return false; } catch (e) { return e.name === 'SecurityError'; } })(),+ (() => { try { Reflect.set(parent, 'forbidden', 1); return false; } catch (e) { return e.name === 'SecurityError'; } })(),+ (() => { try { Reflect.preventExtensions(parent); return false; } catch (e) { return e.name === 'SecurityError'; } })()+ ]"#).unwrap(), json!([true, true, true, true, true, false, true, true, true, true,+ "0,1,2", true, true, true, true, true, true, [true, false, true, false],+ true, true, true, true, true, true]));+ }+ page.evaluate_in_frame(a,+ "(() => { parent.frames.b.postMessage('ping', location.origin); return true; })()").unwrap();+ page.settle(200).await;+ assert_eq!(page.evaluate_in_frame(b, "received").unwrap(),+ json!([["ping", true, false, foreign]]));+ assert_eq!(page.evaluate_in_frame(a, "received").unwrap(),+ json!([["pong", false, true, foreign]]));+ page.evaluate_in_frame(a,+ "(() => { parent.frames.b.postMessage('wrong-target', 'https://unrelated.example'); return true; })()").unwrap();+ page.settle(100).await;+ assert_eq!(page.evaluate_in_frame(b, "received.length").unwrap(), json!(1));+}++#[tokio::test]+async fn remote_siblings_track_connection_order_names_and_retired_contexts() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let foreign = serve("<!doctype html><p>child</p>".into()).await;+ let parent = serve(format!(+ r#"<!doctype html><iframe id="a" name="a" src="{foreign}/a"></iframe>+ <iframe id="b" name="b" src="{foreign}/b"></iframe>"#,+ )).await;+ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&parent).await.unwrap();+ page.settle(1000).await;+ let a = child_index(&page.frame_urls(), "/a");+ page.evaluate_in_frame(a, "(() => { globalThis.oldSibling = parent.frames.b; return true; })()").unwrap();+ assert_eq!(page.evaluate("(() => { document.body.insertBefore(document.querySelector('#b'), document.querySelector('#a')); return true; })()"), json!(true));+ page.settle(500).await;+ let a = child_index(&page.frame_urls(), "/a");+ assert_eq!(page.evaluate_in_frame(a,+ "[parent.length, parent.frames[0] === self, parent.frames[1] === parent.frames.b, oldSibling.closed]"+ ).unwrap(), json!([2, true, true, true]));+ assert_eq!(page.evaluate("document.querySelector('#a').name = 'b'"), json!("b"));+ assert_eq!(page.evaluate_in_frame(a, "parent.frames.b === parent.frames[0]").unwrap(), json!(false));+ assert_eq!(page.evaluate("document.querySelector('#b').name = 'renamed'"), json!("renamed"));+ assert_eq!(page.evaluate_in_frame(a,+ "[name, (() => { try { parent.frames.b; return false; } catch (e) { return e.name === 'SecurityError'; } })(), (() => { try { parent.frames.renamed; return false; } catch (e) { return e.name === 'SecurityError'; } })()]"+ ).unwrap(), json!(["a", true, true]));+ assert_eq!(page.evaluate_in_frame(a, "name = 'b'").unwrap(), json!("b"));+ let b = child_index(&page.frame_urls(), "/b");+ assert_eq!(page.evaluate_in_frame(b, "name = 'renamed'").unwrap(), json!("renamed"));+ assert_eq!(page.evaluate_in_frame(a,+ "[parent.frames.b === self, parent.frames.renamed === parent.frames[1], (() => { try { parent.frames.missing; return false; } catch (e) { return e.name === 'SecurityError'; } })()]"+ ).unwrap(), json!([true, true, true]));+ assert_eq!(page.evaluate("(() => { globalThis.savedOwner = document.querySelector('#b'); savedOwner.remove(); return !savedOwner.isConnected; })()"), json!(true));+ assert_eq!(page.evaluate_in_frame(a,+ "[parent.length, parent.frames[0] === self, (() => { try { parent.frames.renamed; return false; } catch (e) { return e.name === 'SecurityError'; } })()]"+ ).unwrap(), json!([1, true, true]));+ assert_eq!(page.evaluate("(() => { document.body.appendChild(savedOwner); return savedOwner.isConnected; })()"), json!(true));+ page.settle(500).await;+ let a = child_index(&page.frame_urls(), "/a");+ assert_eq!(page.evaluate_in_frame(a,+ "[parent.length, parent.frames[0] === self, parent.frames.renamed === parent.frames[1], oldSibling.closed]"+ ).unwrap(), json!([2, true, true, true]));+}++#[tokio::test]+async fn opaque_nested_frame_resolves_its_actual_parent_and_top() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let parent = serve(r#"<!doctype html><iframe name="outer" sandbox="allow-scripts"+ srcdoc="<iframe name='inner' sandbox='allow-scripts' srcdoc='<p>nested</p>'></iframe>"></iframe>"#.into()).await;+ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&parent).await.unwrap();+ page.settle(500).await;+ let nested = (0..page.frame_urls().len()).find(|index|+ page.evaluate_in_frame(*index, "document.querySelector('p') !== null").unwrap() == json!(true)+ ).unwrap();+ assert_eq!(page.evaluate_in_frame(nested, r#"[+ parent !== top, parent.parent === top, parent.top === top,+ parent.frames[0] === self, parent.length,+ top.frames.outer === parent, top.length+ ]"#).unwrap(), json!([true, true, true, true, 1, true, 1]));+}++#[tokio::test]+async fn remote_proxy_survives_navigation_and_posts_to_the_current_document() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let foreign = serve(r#"<!doctype html><script>+ globalThis.received = [];+ addEventListener('message', event => received.push(event.data));+ </script>"#.into()).await;+ let parent = serve(format!(+ r#"<!doctype html><iframe name="a" src="{foreign}/a"></iframe>+ <iframe id="b" name="b" src="{foreign}/b"></iframe>"#,+ )).await;+ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&parent).await.unwrap();+ page.settle(500).await;+ let a = child_index(&page.frame_urls(), "/a");+ page.evaluate_in_frame(a,+ "(() => { globalThis.savedSibling = parent.frames.b; return true; })()").unwrap();+ assert_eq!(page.evaluate(&format!(+ "document.querySelector('#b').src = '{foreign}/b-next'"+ )), json!(format!("{foreign}/b-next")));+ page.settle(500).await;+ let a = child_index(&page.frame_urls(), "/a");+ assert_eq!(page.evaluate_in_frame(a,+ "[savedSibling === parent.frames.b, savedSibling.closed, parent.frames[0] === self]"+ ).unwrap(), json!([true, false, true]));+ page.evaluate_in_frame(a,+ "(() => { savedSibling.postMessage('new-document', '*'); return true; })()").unwrap();+ page.settle(100).await;+ let b = child_index(&page.frame_urls(), "/b-next");+ assert_eq!(page.evaluate_in_frame(b, "received").unwrap(), json!(["new-document"]));+}++#[tokio::test]+async fn queued_message_keeps_its_source_identity_after_the_sender_is_removed() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let foreign = serve("<!doctype html><p>child</p>".into()).await;+ let parent = serve(format!(+ r#"<!doctype html><iframe id="a" name="a" src="{foreign}/a"></iframe>+ <iframe name="b" src="{foreign}/b"></iframe>"#,+ )).await;+ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&parent).await.unwrap();+ page.settle(500).await;+ let a = child_index(&page.frame_urls(), "/a");+ let b = child_index(&page.frame_urls(), "/b");+ page.evaluate_in_frame(b, r#"(() => {+ globalThis.savedSource = parent.frames.a;+ globalThis.received = [];+ addEventListener('message', event => received.push([+ event.data, event.source === savedSource, event.source?.closed,+ savedSource.self === null, savedSource.window === null,+ savedSource.frames === null, savedSource.parent === null,+ savedSource.top === null, savedSource.length, savedSource.opener === null+ ]));+ return true;+ })()"#).unwrap();+ page.evaluate_in_frame(a,+ "(() => { parent.frames.b.postMessage('before-removal', '*'); return true; })()").unwrap();+ assert_eq!(page.evaluate(+ "(() => { document.querySelector('#a').remove(); return true; })()"+ ), json!(true));+ page.settle(100).await;+ let b = child_index(&page.frame_urls(), "/b");+ assert_eq!(page.evaluate_in_frame(b, "received").unwrap(),+ json!([["before-removal", true, true, true, true, true, true, true, 0, true]]));+}++#[tokio::test]+async fn root_and_remote_named_access_share_context_order_and_name_matching() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let foreign = serve("<!doctype html><p>child</p>".into()).await;+ let parent = serve(format!(+ r#"<!doctype html><iframe id="a" name="a" src="{foreign}/a"></iframe>+ <iframe id="b" name="b" src="{foreign}/b"></iframe>"#,+ )).await;+ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&parent).await.unwrap();+ page.settle(500).await;+ assert_eq!(page.evaluate(r#"(() => {+ globalThis.ownerA = document.querySelector('#a');+ globalThis.ownerB = document.querySelector('#b');+ document.body.insertBefore(ownerB, ownerA);+ ownerA.name = 'b';+ ownerB.name = 'renamed';+ return true;+ })()"#), json!(true));+ page.settle(500).await;+ assert_eq!(page.evaluate(+ "[frames.b === ownerA.contentWindow, frames.b === ownerB.contentWindow, frames.renamed === undefined, frames.a === ownerA.contentWindow]"+ ), json!([false, false, true, false]));+ assert_eq!(page.evaluate("ownerB.name = 'b'"), json!("b"));+ let a = child_index(&page.frame_urls(), "/a");+ assert_eq!(page.evaluate_in_frame(a, "name = 'b'").unwrap(), json!("b"));+ assert_eq!(page.evaluate_in_frame(a,+ "[parent.frames.b === self, parent.frames[0] === self]"+ ).unwrap(), json!([true, true]));+ assert_eq!(page.evaluate("frames.b === ownerA.contentWindow"), json!(true));+ assert_eq!(page.evaluate(+ "(() => {ownerA.id = 'fallback'; ownerA.name = 'fallback'; return true;})()"+ ), json!(true));+ assert_eq!(page.evaluate("frames.fallback === ownerA"), json!(true));+}++#[tokio::test]+async fn rejected_frame_keeps_metadata_without_aliasing_root_or_retaining_realm_references() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ std::env::set_var("OBSCURA_MAX_LIVE_FRAMES", "1");+ let foreign = serve("<!doctype html><p>child</p>".into()).await;+ let parent = serve(format!(+ r#"<!doctype html><iframe name="a" src="{foreign}/a"></iframe>+ <iframe name="b" src="{foreign}/b"></iframe>"#,+ )).await;+ let browser = Browser::new().unwrap();+ let mut page = browser.new_page().await.unwrap();+ page.goto(&parent).await.unwrap();+ page.settle(500).await;+ assert_eq!(page.frame_urls().len(), 1);+ assert_eq!(page.evaluate(r#"(() => {+ const owners = Array.from(document.querySelectorAll('iframe'));+ const pending = owners.find(owner => !owner._frameId);+ let conversions = 0;+ pending.contentWindow.postMessage({get value(){conversions++;return 7;}},+ {toString(){conversions++;return '*';}});+ const cyclic = {}; cyclic.self = cyclic;+ let cloneError = false;+ try {pending.contentWindow.postMessage(cyclic, '*');}+ catch (error) {cloneError = error.name === 'DataCloneError';}+ return [frames.length, pending.contentWindow !== window,+ pending._iframeWin !== window,+ Object.keys(__obscura_frameWindows).length,+ Object.keys(__obscura_frameElements).length, conversions, cloneError,+ pending.contentWindow === frames[owners.indexOf(pending)]];+ })()"#), json!([2, true, true, 1, 1, 2, true, true]));+}diff --git a/docs/Architecture-overview.md b/docs/Architecture-overview.mdindex 7c215c94..76361424 100644--- a/docs/Architecture-overview.md+++ b/docs/Architecture-overview.md@@ -129,6 +129,15 @@ Serialized iframe owner elements identify their live child frame in`DOM.describeNode`, `DOM.getDocument`, and `DOM.setChildNodes`. Native ownershiprecords distinguish nested documents and omit retired or detached contexts,allowing clients to resolve iframe elements to their child frames.+Native browsing-context records also back `parent`, `top`, indexed and named+cross-origin sibling access, and `frames.length`. They exist before a fetched+document arrives, so a pending frame never aliases an unrelated retired realm.+Navigation preserves the context's position and remote Window identity;+removal and reinsertion create a new context at the end of connection order.+Named cross-origin access requires both the owner's current `name` attribute+and the context's retained name to match. Missing or forbidden cross-origin+properties throw `SecurityError`. Queued messages retain their source context+even when its document is retired before delivery.Live child frames advertise their default CDP execution contexts.`Runtime.evaluate` and `Runtime.callFunctionOn`, including awaited calls,enter the frame's actual V8 realm and use its document. Remote objects remaindiff --git a/scripts/ci/perf_smoke.py b/scripts/ci/perf_smoke.pyindex 28e7742f..05020bed 100755--- a/scripts/ci/perf_smoke.py+++ b/scripts/ci/perf_smoke.py@@ -129,6 +129,18 @@ SCENARIOS = {"(() => {document.body.innerHTML='<form id=f></form><input id=input form=f>'+'<div id=extra></div>'.repeat(1000);const input=document.getElementById('input');let n=0;for(let i=0;i<10000;i++){input.className='state'+i;n+=typeof input.form==='object';}return n})()",10000,),+ "frame-content-window-hot": (+ "(() => {const e=document.createElement('iframe');document.body.appendChild(e);const w=e.contentWindow;let n=0;for(let i=0;i<50000;i++)n+=e.contentWindow===w;return n})()",+ 50000,+ ),+ "frame-indexed-root-hot": (+ "(() => {document.body.innerHTML='<iframe></iframe>'.repeat(3);const w=frames[0];let n=0;for(let i=0;i<10000;i++)n+=frames[0]===w;return n})()",+ 10000,+ ),+ "frame-live-owner-dom-build": (+ "(() => {document.body.innerHTML='<iframe></iframe>'.repeat(16);for(let i=0;i<5000;i++)document.body.appendChild(document.createElement('div'));return document.querySelectorAll('div').length+frames.length})()",+ 5016,+ ),}SCENARIOS.update({f"html-parse-depth-{depth}": (@@ -140,6 +152,17 @@ SCENARIOS.update({)for depth in (4, 32, 128, 300)})+SCENARIOS.update({+ f"frame-length-{count}-dom-{padding}": (+ "(() => {document.body.innerHTML='<div></div>'.repeat(" + str(padding)+ + ")+'<iframe></iframe>'.repeat(" + str(count)+ + ");let n=0;for(let i=0;i<" + str(iterations)+ + ";i++)n+=frames.length;return n})()",+ count * iterations,+ )+ for count, iterations, padding in ((0, 100000, 0), (3, 10000, 0),+ (32, 10000, 0), (3, 1000, 2500))+})class Handler(BaseHTTPRequestHandler):