Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(window): retain iframe document identity after removal
ldm00c89c93abd7c
diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rsindex 93bc4ca9c..284fc0b23 100644--- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs+++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs@@ -16,6 +16,7 @@ use super::{web_storage::{install_storage_runtime_state, window_local_storage_getter, window_session_storage_getter,},+ window_accessors::window_document_getter,window_runtime::{build_legacy_storage_info_object, window_noop_callback},window_template::install_window_named_properties_object,};@@ -1254,36 +1255,6 @@ const WINDOW_SURFACE_REPLACEABLE_NAMES: &[&str] = &["screenY",];-fn legacy_unforgeable_document_getter<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let receiver = args.this();- let Some(host_ptr) = context_host_ptr_from_window_object(scope, receiver)- .or_else(|| context_host_ptr_from_global_bridge(scope))- else {- rv.set_null();- return;- };- if let Some(child_handle) = child_context_handle_from_owner(scope, receiver) {- match unsafe { &mut *host_ptr }.child_browsing_context_document_wrapper(scope, child_handle)- {- Some(document) => rv.set(document.into()),- None => rv.set_null(),- }- return;- }- let handle = unsafe { &*host_ptr }.document_handle();- match unsafe { &mut *host_ptr }- .native_bridge_mut()- .wrap_handle(scope, host_ptr, handle)- {- Some(document) => rv.set(document.into()),- None => rv.set_null(),- }-}-fn child_context_handle_from_owner<'s>(scope: &mut v8::PinScope<'s, '_>,owner: v8::Local<'s, v8::Object>,@@ -1561,7 +1532,7 @@ fn define_legacy_unforgeable_document_property<'s>(scope: &mut v8::PinScope<'s, '_>,object: v8::Local<'s, v8::Object>,) -> Result<()> {- let getter = v8::Function::builder(legacy_unforgeable_document_getter)+ let getter = v8::Function::builder(window_document_getter).build(scope).ok_or_else(|| anyhow!("failed to build document getter"))?;getter.set_name(v8str(scope, "get document"));diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/child_context.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/child_context.rsindex eb71616a5..a0548e424 100644--- a/moli-renderer-v8/src/context_bootstrap/window_accessors/child_context.rs+++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/child_context.rs@@ -2,6 +2,7 @@ use super::helpers::{window_child_context_handle, window_hidden_value, window_host_ptr, window_receiver,};use super::*;+use crate::native_bridge::WindowEnvironmentSettings;pub(in crate::context_bootstrap) fn window_length_getter<'s>(scope: &mut v8::PinScope<'s, '_>,@@ -104,14 +105,43 @@ pub(in crate::context_bootstrap) fn window_document_getter<'s>(rv.set_null();return;};- if let Some(handle) = window_child_context_handle(scope, receiver) {+ let Some(context) = receiver.get_creation_context(scope) else {+ rv.set_null();+ return;+ };+ // A borrowed getter runs in its function's realm. Resolve both settings+ // and wrappers in the receiver's realm, including a retained old Window.+ let scope = &mut v8::ContextScope::new(scope, context);+ let handle = if let Some(settings) = WindowEnvironmentSettings::for_current_realm(scope) {+ let window = context.global(scope);+ if let Some(document) = window_hidden_value(+ scope,+ window,+ WindowEnvironmentSettings::DOCUMENT_WRAPPER_SLOT,+ ) {+ rv.set(document);+ return;+ }+ settings.document_handle()+ } else if let Some(handle) = window_child_context_handle(scope, receiver) {+ // During bootstrap the Document wrapper can precede settings binding.+ // Only this exact live Window may follow the child's current route.+ let host = unsafe { &*host_ptr };+ if host+ .window_execution_context_identity_for_access_check(context)+ .is_none_or(|identity| !host.window_execution_context_identity_is_current(identity))+ {+ rv.set_null();+ return;+ }match unsafe { &mut *host_ptr }.child_browsing_context_document_wrapper(scope, handle) {Some(document) => rv.set(document.into()),None => rv.set_null(),}return;- }- let handle = unsafe { &*host_ptr }.document_handle();+ } else {+ unsafe { &*host_ptr }.document_handle()+ };match unsafe { &mut *host_ptr }.native_bridge_mut().wrap_handle(scope, host_ptr, handle)diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rsindex b59e0a7db..728592a6d 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs@@ -112,7 +112,9 @@ impl JsContextHost {self.clear_child_browsing_context_live_foreign_pairings(scope, document_handle);install_child_document_stream_methods(scope, document, handle);if let Some(window) = window {- let _ = WindowEnvironmentSettings::bind_current_child_document(scope, self, handle);+ let _ = WindowEnvironmentSettings::bind_current_child_document(+ scope, self, handle, document,+ );sync_child_document_window_slots(scope,document,diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/initialize.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/initialize.rsindex c80563b0c..142116a59 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/initialize.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/initialize.rs@@ -65,7 +65,7 @@ pub(in crate::native_bridge::context_host::child_frame_runtime) fn initialize_chsync_child_document_window_slots(scope, document, global, true);set_object_slot(scope, global, "document", document.into());validate_child_window_realm_snapshot(host, &snapshot)?;- bind_document_settings(host, scope, &snapshot)?;+ bind_document_settings(host, scope, &snapshot, document)?;Ok(ChildWindowRealmProjection {parent,@@ -127,15 +127,16 @@ pub(in crate::native_bridge::context_host::child_frame_runtime) fn rebind_child_sync_child_document_window_slots(scope, document, global, true);set_object_slot(scope, global, "document", document.into());validate_child_window_realm_snapshot(host, &snapshot)?;- bind_document_settings(host, scope, &snapshot)+ bind_document_settings(host, scope, &snapshot, document)}-fn bind_document_settings(+fn bind_document_settings<'s>(host: &JsContextHost,- scope: &mut v8::PinScope<'_, '_>,+ scope: &mut v8::PinScope<'s, '_>,snapshot: &super::model::ChildWindowRealmSnapshot,+ document: v8::Local<'s, v8::Object>,) -> Result<()> {- WindowEnvironmentSettings::bind_current_child_document(scope, host, snapshot.handle)+ WindowEnvironmentSettings::bind_current_child_document(scope, host, snapshot.handle, document).ok_or_else(|| anyhow::anyhow!("missing current child settings Document"))}diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rsindex 96be323e8..f87081d33 100644--- a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs@@ -2,6 +2,7 @@ use super::super::JsContextHost;use super::super::OwnerDispatchScope;use super::WindowExecutionContextIdentity;use crate::document_runtime::DomHandle;+use crate::util::set_private_value;use moli_url::WebOrigin;use std::rc::Rc;use url::Url;@@ -21,10 +22,13 @@ pub(crate) struct WindowEnvironmentSettings {}impl WindowEnvironmentSettings {- pub(in crate::native_bridge::context_host) fn bind_current_child_document(- scope: &mut v8::PinScope<'_, '_>,+ pub(crate) const DOCUMENT_WRAPPER_SLOT: &'static str = "__moliWindowAssociatedDocument";++ pub(in crate::native_bridge::context_host) fn bind_current_child_document<'s>(+ scope: &mut v8::PinScope<'s, '_>,host: &JsContextHost,child_handle: DomHandle,+ document_wrapper: v8::Local<'s, v8::Object>,) -> Option<()> {// A reused element can point to a new Window. Only a currently// registered realm may change its associated Document; a retained old@@ -37,7 +41,18 @@ impl WindowEnvironmentSettings {let document = host.child_browsing_context_document_handle(child_handle)?;let owner = host.frame_owner_current_child_snapshot(child_handle)?;let origin = WebOrigin::from_serialized(&owner.settings.origin);- let _previous = scope.get_current_context().set_slot(Rc::new(Self {+ let context = scope.get_current_context();+ let window = context.global(scope);+ // Realm retirement clears the shared wrapper cache. Keep the original+ // Document as a private V8 edge so Window.document retains object+ // identity without a Rust Global keeping this Context alive.+ set_private_value(+ scope,+ window,+ Self::DOCUMENT_WRAPPER_SLOT,+ document_wrapper.into(),+ );+ let _previous = context.set_slot(Rc::new(Self {document,origin,execution_identity,@@ -49,6 +64,10 @@ impl WindowEnvironmentSettings {scope.get_current_context().get_slot::<Self>()}+ pub(crate) fn document_handle(&self) -> DomHandle {+ self.document+ }+pub(crate) fn api_base_url(&self, host: &JsContextHost) -> Option<Url> {let document = host.dom_host().node(self.document)?.as_document()?;// Preserve the existing bootstrap view while an initial empty Documentdiff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/document_navigator.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/document_navigator.rsindex c981b3749..b9c82e4fc 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/document_navigator.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/document_navigator.rs@@ -603,8 +603,9 @@ fn request_relative_urls_follow_live_srcdoc_iframe_base_urls() {fn assert_retained_request_uses_child_document(vm: &mut ScriptVm, fallback_base: &str) {vm.exec(r#"-globalThis.retainedChildDocument = requestBaseFrame.contentDocument;-globalThis.RetainedChildRequest = requestBaseFrame.contentWindow.Request;+globalThis.retainedChildWindow = requestBaseFrame.contentWindow;+globalThis.retainedChildDocument = retainedChildWindow.document;+globalThis.RetainedChildRequest = retainedChildWindow.Request;retainedChildDocument.head.innerHTML = '<base href="https://fixture.test/child/">';"#,None,@@ -623,6 +624,7 @@ const controller = new AbortController();controller.abort('retained-reason');const request = new RetainedChildRequest('item', {{signal: controller.signal}});return JSON.stringify({{+ documentIdentity: retainedChildWindow.document === retainedChildDocument,urls: ['item', '../item?q#f', '?q', '#f'].map(input => new RetainedChildRequest(input).url),referrer: new RetainedChildRequest('item', {{referrer: 'referrer'}}).referrer,allowedReferrer: new RetainedChildRequest('item', {{referrer: {allowed_referrer}}}).referrer,@@ -648,6 +650,7 @@ return JSON.stringify({{assert_eq!(actual,serde_json::json!({+ "documentIdentity": true,"urls": expected_urls,"referrer": expected_referrer,"allowedReferrer": allowed_referrer.as_str(),@@ -695,6 +698,25 @@ return JSON.stringify({{"https://replacement.test/new/item");assert_base(vm, fallback_base);+ assert_eq!(+ vm.eval(+ r#"+(() => {+ const replacement = requestBaseFrame.contentDocument;+ replacement.body.textContent = 'REPLACEMENT';+ retainedChildWindow.document.body.textContent = 'WRITTEN VIA OLD WINDOW';+ return JSON.stringify([+ retainedChildWindow !== requestBaseFrame.contentWindow,+ retainedChildDocument !== replacement,+ retainedChildDocument.body.textContent,+ replacement.body.textContent+ ]);+})()+"#,+ )+ .expect("retained Window writes should remain confined to its original Document"),+ r#"[true,true,"WRITTEN VIA OLD WINDOW","REPLACEMENT"]"#+ );}#[test]diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/window_and_frame_surfaces.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/window_and_frame_surfaces.rsindex 515e58bdd..d430f43d3 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/window_and_frame_surfaces.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/window_and_frame_surfaces.rs@@ -1,5 +1,119 @@use super::*;+#[test]+fn window_document_retains_original_document_after_iframe_removal_and_reinsertion() {+ for cleanup_before_reinsertion in [false, true] {+ let mut vm = new_storage_test_vm("https://retained-window-document.test/");+ vm.exec(+ r#"+globalThis.documentFrame = document.createElement('iframe');+(document.body || document.documentElement || document).appendChild(documentFrame);+globalThis.originalWindow = documentFrame.contentWindow;+globalThis.originalDocument = originalWindow.document;+globalThis.parentDocumentGetter = Object.getOwnPropertyDescriptor(window, 'document').get;+globalThis.childDocumentGetter = Object.getOwnPropertyDescriptor(originalWindow, 'document').get;+originalDocument.body.textContent = 'ORIGINAL';+documentFrame.remove();+"#,+ None,+ )+ .expect("iframe Window and Document should be retained before removal");++ let assert_original_document = |vm: &mut ScriptVm, stage: &str| {+ assert_eq!(+ vm.eval(+ r#"JSON.stringify([+originalWindow.document === originalDocument,+parentDocumentGetter.call(originalWindow) === originalDocument,+childDocumentGetter.call(originalWindow) === originalDocument,+childDocumentGetter.call(window) === document+])"#,+ )+ .expect("retained and borrowed Document getters should evaluate"),+ "[true,true,true,true]",+ "{stage}, cleanup before reinsertion: {cleanup_before_reinsertion}"+ );+ };+ assert_original_document(&mut vm, "after removal");+ if cleanup_before_reinsertion {+ assert!(vm.live_child_default_runtime_realm_inventory().is_empty());+ assert_original_document(&mut vm, "after cleanup");+ }++ vm.exec(+ r#"+(document.body || document.documentElement || document).appendChild(documentFrame);+globalThis.replacementWindow = documentFrame.contentWindow;+globalThis.replacementDocument = documentFrame.contentDocument;+replacementDocument.body.textContent = 'REPLACEMENT';+"#,+ None,+ )+ .expect("the same iframe element should acquire a new Window and Document");+ vm.live_child_default_runtime_realm_inventory();+ assert_original_document(&mut vm, "after reinsertion");+ assert_eq!(+ vm.eval(+ r#"+(() => {+ const replacementGetter = Object.getOwnPropertyDescriptor(replacementWindow, 'document').get;+ originalWindow.document.body.textContent = 'WRITTEN VIA OLD WINDOW';+ return JSON.stringify([+ originalWindow !== replacementWindow,+ originalDocument !== replacementDocument,+ replacementWindow.document === replacementDocument,+ childDocumentGetter.call(replacementWindow) === replacementDocument,+ replacementGetter.call(originalWindow) === originalDocument,+ originalDocument.body.textContent,+ replacementDocument.body.textContent+ ]);+})()+"#,+ )+ .expect("writing through the retained Window should affect only its own Document"),+ r#"[true,true,true,true,true,"WRITTEN VIA OLD WINDOW","REPLACEMENT"]"#,+ "cleanup before reinsertion: {cleanup_before_reinsertion}"+ );+ }+}++#[test]+fn window_document_getter_follows_the_receiver_window_proxy_across_navigation() {+ let mut vm = new_storage_test_vm("https://navigated-window-document.test/");+ vm.exec(+ r#"+globalThis.documentFrame = document.createElement('iframe');+(document.body || document.documentElement || document).appendChild(documentFrame);+globalThis.retainedWindow = documentFrame.contentWindow;+globalThis.originalDocument = retainedWindow.document;+globalThis.parentDocumentGetter = Object.getOwnPropertyDescriptor(window, 'document').get;+globalThis.childDocumentGetter = Object.getOwnPropertyDescriptor(retainedWindow, 'document').get;+"#,+ None,+ )+ .expect("the initial WindowProxy and document getters should be retained");+ vm.drain_pending_child_frame_work_for_test();+ vm.exec("documentFrame.srcdoc = '<body>DESTINATION</body>';", None)+ .expect("same-origin cross-document navigation should start");+ vm.drain_pending_child_frame_work_for_test();++ assert_eq!(+ vm.eval(+ r#"JSON.stringify([+retainedWindow === documentFrame.contentWindow,+originalDocument !== documentFrame.contentDocument,+retainedWindow.document === documentFrame.contentDocument,+parentDocumentGetter.call(retainedWindow) === documentFrame.contentDocument,+childDocumentGetter.call(retainedWindow) === documentFrame.contentDocument,+childDocumentGetter.call(window) === document,+retainedWindow.document.body.textContent+])"#,+ )+ .expect("retained WindowProxy and borrowed getters should read the destination Document"),+ r#"[true,true,true,true,true,true,"DESTINATION"]"#+ );+}+#[test]fn detached_native_xml_text_content_queues_child_list_record() {let mut vm = new_storage_test_vm("https://detached-xml-text-content-mutation.test/");