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): isolate retired Window named and indexed queries
ldm0066501d2ac63
diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rsindex 284fc0b23..f929a920c 100644--- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs+++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs@@ -16,7 +16,7 @@ use super::{web_storage::{install_storage_runtime_state, window_local_storage_getter, window_session_storage_getter,},- window_accessors::window_document_getter,+ window_accessors::{window_document_getter, window_length_getter},window_runtime::{build_legacy_storage_info_object, window_noop_callback},window_template::install_window_named_properties_object,};@@ -33,8 +33,8 @@ use crate::{network_host,util::{callback_data_index_value, callback_data_item, context_host_ptr_from_global_bridge,- context_host_ptr_from_window_object, create_script_origin_with_base_url, get_private_value,- script_base_url_continuation_data, set_private_value, throw_type_error, v8_string, v8str,+ create_script_origin_with_base_url, get_private_value, script_base_url_continuation_data,+ set_private_value, throw_type_error, v8_string, v8str,},webidl,webidl_iterator::install_webidl_collection_iterator_intrinsics,@@ -349,7 +349,7 @@ struct WindowAdditionalReplaceableAccessorsDeclaration<'scope> {inner_width: (),#[webapi(accessor_property,- getter = window_length_replaceable_getter,+ getter = window_length_getter,setter = window_surface_replaceable_setter,setter_data = self.length_name)]@@ -637,24 +637,6 @@ fn window_outer_height_replaceable_getter<'s>(rv.set(v8::Number::new(scope, value).into());}-fn window_length_replaceable_getter<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: v8::FunctionCallbackArguments<'s>,- mut rv: v8::ReturnValue<'s, v8::Value>,-) {- let Some(host_ptr) = context_host_ptr_from_window_object(scope, args.this())- .or_else(|| context_host_ptr_from_global_bridge(scope))- else {- rv.set(v8::Integer::new(scope, 0).into());- return;- };- let host = unsafe { &mut *host_ptr };- let count = child_context_handle_from_owner(scope, args.this())- .map(|handle| host.child_browsing_context_child_frame_count(handle))- .unwrap_or_else(|| host.child_browsing_context_count());- rv.set(v8::Number::new(scope, count as f64).into());-}-fn window_event_replaceable_getter<'s>(scope: &mut v8::PinScope<'s, '_>,_args: v8::FunctionCallbackArguments<'s>,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 873632f0b..ed0b83a66 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@@ -1,5 +1,6 @@use super::helpers::{- window_child_context_handle, window_hidden_value, window_host_ptr, window_receiver,+ window_child_context_handle, window_current_dispatch_scope, window_hidden_value,+ window_host_ptr, window_receiver,};use super::*;@@ -16,7 +17,11 @@ pub(in crate::context_bootstrap) fn window_length_getter<'s>(return;};let runtime = unsafe { &mut *host_ptr };- let count = if let Some(handle) = window_child_context_handle(scope, receiver) {+ let Some(owner) = window_current_dispatch_scope(scope, receiver, runtime) else {+ rv.set(v8::Number::new(scope, 0.0).into());+ return;+ };+ let count = if let Some(handle) = owner.child_window() {runtime.child_browsing_context_child_frame_count(handle)} else {runtime.child_browsing_context_count()diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/helpers.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/helpers.rsindex 19860fa70..a59b29d4f 100644--- a/moli-renderer-v8/src/context_bootstrap/window_accessors/helpers.rs+++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/helpers.rs@@ -1,4 +1,5 @@use super::*;+use crate::native_bridge::OwnerDispatchScope;use crate::util::get_private_value;use crate::webidl;@@ -100,6 +101,19 @@ pub(crate) fn window_host_ptr(.or_else(|| context_host_ptr_from_global_bridge(scope))}+pub(super) fn window_current_dispatch_scope<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ receiver: v8::Local<'s, v8::Object>,+ host: &JsContextHost,+) -> Option<OwnerDispatchScope> {+ // The receiver's concrete realm identifies its LocalWindow. An iframe+ // element's marker survives removal and can belong to a replacement Window.+ let context = receiver.get_creation_context(scope)?;+ let identity = host.window_execution_context_identity_for_access_check(context)?;+ host.window_execution_context_identity_is_current(identity)+ .then(|| identity.dispatch_scope())+}+pub(super) fn window_receiver<'s>(scope: &mut v8::PinScope<'s, '_>,args: &v8::FunctionCallbackArguments<'s>,@@ -138,12 +152,6 @@ pub(in crate::context_bootstrap) fn window_has_discarded_child_browsing_context<// Container removal disconnects the DOM node before its unload callbacks.// The captured LocalWindow remains current until those callbacks finish;// checking its identity also keeps reattachment from reviving an old realm.- let Some(context) = receiver.get_creation_context(scope) else {- return true;- };- host.window_execution_context_identity_for_access_check(context)- .is_none_or(|identity| {- identity.dispatch_scope() != crate::native_bridge::OwnerDispatchScope::Child(handle)- || !host.window_execution_context_identity_is_current(identity)- })+ window_current_dispatch_scope(scope, receiver, host)+ .is_none_or(|owner| owner != OwnerDispatchScope::Child(handle))}diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rsindex e4311f9fe..18034b2b9 100644--- a/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs+++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs@@ -1,7 +1,9 @@-use super::helpers::{window_child_context_handle, window_host_ptr};+use super::helpers::{window_current_dispatch_scope, window_host_ptr};+use crate::document_runtime::DomHandle;use crate::native_bridge::named_access::{build_window_named_items_collection, window_named_item_handles,};+use crate::native_bridge::{JsContextHost, OwnerDispatchScope};use crate::util::serialize_v8_iter_array;use moli_webapi_declare::DataPropertyDescriptorDeclaration;@@ -13,22 +15,19 @@ fn window_indexed_child_handle<'s>(scope: &mut v8::PinScope<'s, '_>,holder: v8::Local<'s, v8::Object>,index: u32,-) -> Option<(- *mut crate::native_bridge::JsContextHost,- crate::document_runtime::DomHandle,-)> {+) -> Option<(*mut JsContextHost, DomHandle, OwnerDispatchScope)> {let host_ptr = window_host_ptr(scope, holder)?;let host = unsafe { &mut *host_ptr };- let handle = if let Some(parent) = window_child_context_handle(scope, holder) {- if let Some(document) = host.child_browsing_context_document_handle(parent) {- host.sync_child_browsing_context_subtree(scope, document);- }+ let owner = window_current_dispatch_scope(scope, holder, host)?;+ let handle = if let Some(parent) = owner.child_window() {+ let document = host.child_browsing_context_document_handle(parent)?;+ host.sync_child_browsing_context_subtree(scope, document);host.child_browsing_context_child_frame_handle_by_index(parent, index as usize)} else {host.sync_child_browsing_context_subtree(scope, host.document_handle());host.child_browsing_context_handle_by_index(index as usize)}?;- Some((host_ptr, handle))+ Some((host_ptr, handle, owner))}pub(in crate::context_bootstrap) fn window_indexed_property_getter<'s>(@@ -38,11 +37,11 @@ pub(in crate::context_bootstrap) fn window_indexed_property_getter<'s>(mut rv: v8::ReturnValue<'_, v8::Value>,) -> v8::Intercepted {let holder = args.holder();- let Some((host_ptr, handle)) = window_indexed_child_handle(scope, holder, index) else {+ let Some((host_ptr, handle, owner)) = window_indexed_child_handle(scope, holder, index) else {return v8::Intercepted::kNo;};let host = unsafe { &mut *host_ptr };- let window = if window_child_context_handle(scope, holder).is_none() {+ let window = if owner.child_window().is_none() {host.child_browsing_context_window_proxy_for_top(scope, handle)} else {host.child_browsing_context_window_wrapper(scope, handle)@@ -78,7 +77,11 @@ pub(in crate::context_bootstrap) fn window_indexed_property_enumerator<'s>(return;};let host = unsafe { &mut *host_ptr };- let count = if let Some(parent) = window_child_context_handle(scope, holder) {+ let Some(owner) = window_current_dispatch_scope(scope, holder, host) else {+ rv.set(v8::Array::new(scope, 0));+ return;+ };+ let count = if let Some(parent) = owner.child_window() {if let Some(document) = host.child_browsing_context_document_handle(parent) {host.sync_child_browsing_context_subtree(scope, document);}@@ -99,12 +102,12 @@ pub(in crate::context_bootstrap) fn window_indexed_property_descriptor<'s>(args: v8::PropertyCallbackArguments<'s>,mut rv: v8::ReturnValue<'_, v8::Value>,) -> v8::Intercepted {- let Some((host_ptr, handle)) = window_indexed_child_handle(scope, args.holder(), index) else {+ let Some((host_ptr, handle, owner)) = window_indexed_child_handle(scope, args.holder(), index)+ else {return v8::Intercepted::kNo;};- let holder = args.holder();let host = unsafe { &mut *host_ptr };- let window = if window_child_context_handle(scope, holder).is_none() {+ let window = if owner.child_window().is_none() {host.child_browsing_context_window_proxy_for_top(scope, handle)} else {host.child_browsing_context_window_wrapper(scope, handle)@@ -187,7 +190,8 @@ fn window_named_access_value<'s>(return None;}let host_ptr = window_host_ptr(scope, holder)?;- let child_handle = window_child_context_handle(scope, holder);+ let host = unsafe { &*host_ptr };+ let child_handle = window_current_dispatch_scope(scope, holder, host)?.child_window();// Browsing-context names win over document id/name exposure, matching the// Window named access ordering. Both paths are fast miss paths now: child// contexts return immediately when empty, and document name lookup is indexed.@@ -199,9 +203,10 @@ fn window_named_access_value<'s>(return Some(window.into());}let host = unsafe { &*host_ptr };- let document = child_handle- .and_then(|child_handle| host.child_browsing_context_document_handle(child_handle))- .unwrap_or_else(|| host.document_handle());+ let document = match child_handle {+ Some(handle) => host.child_browsing_context_document_handle(handle)?,+ None => host.document_handle(),+ };let handles = window_named_item_handles(host.dom_host(), document, &key_name);if moli_trace::window_message_trace_enabled() {tracing::info!(diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rsindex fd96c5724..d317b4436 100644--- a/moli-renderer-v8/src/script_vm.rs+++ b/moli-renderer-v8/src/script_vm.rs@@ -2091,6 +2091,10 @@ impl ScriptVmPageRealmBootstrap {.install_page_default_context(scope, local_context);let scope = &mut v8::ContextScope::new(scope, local_context);super::context_bootstrap::initialize_main_session_history(scope);+ // Initial frames must be discovered independently of Window+ // property enumeration during bootstrap.+ let host = unsafe { &mut *context_host.as_ptr() };+ host.sync_child_browsing_context_subtree(scope, host.document_handle());Ok(())}){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 d430f43d3..507cd2b32 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,134 @@use super::*;+#[test]+fn retired_window_named_and_indexed_access_cannot_follow_a_reinserted_iframe() {+ for cleanup_before_reinsertion in [false, true] {+ let mut vm = new_storage_html_test_vm("https://retained-window-properties.test/");+ vm.exec(+ r#"+globalThis.parentMarker = document.createElement('div');+parentMarker.id = '__retainedParentMarker';+parentMarker.textContent = 'PARENT';+document.body.appendChild(parentMarker);+globalThis.frame = document.createElement('iframe');+document.body.appendChild(frame);+globalThis.oldWindow = frame.contentWindow;+globalThis.oldDocument = oldWindow.document;+oldDocument.body.innerHTML = '<div id="__retainedOldMarker">ORIGINAL</div><iframe name="__retainedOldChild"></iframe>';+globalThis.parentLengthGetter = Object.getOwnPropertyDescriptor(window, 'length').get;+globalThis.childLengthGetter = Object.getOwnPropertyDescriptor(oldWindow, 'length').get;+globalThis.retiredProperties = function(w) {+ return JSON.stringify([+ w.__retainedParentMarker === undefined,+ w.__retainedOldMarker === undefined,+ w.__retainedNewMarker === undefined,+ w.__retainedNewChild === undefined,+ !('__retainedParentMarker' in w),+ !('__retainedNewMarker' in w),+ !('__retainedNewChild' in w),+ w.length === 0,+ w[0] === undefined,+ !('0' in w),+ !Object.prototype.hasOwnProperty.call(w, '0'),+ !Reflect.ownKeys(w).includes('0'),+ Object.getOwnPropertyDescriptor(w, '0') === undefined+ ]);+};+globalThis.readRetiredProperties = oldWindow.Function('return (' + retiredProperties.toString() + ')(window)');+"#,+ None,+ )+ .expect("live Window properties and a function in its own realm should be retained");+ assert_eq!(+ vm.eval(+ r#"JSON.stringify([+oldWindow.__retainedOldMarker === oldDocument.getElementById('__retainedOldMarker'),+oldWindow.__retainedOldChild === oldWindow[0],+oldWindow.length === 1,+parentLengthGetter.call(oldWindow) === 1,+childLengthGetter.call(window) === 1+])"#,+ )+ .expect("live Window named access and borrowed length getters should work"),+ "[true,true,true,true,true]"+ );+ vm.exec("frame.remove();", None)+ .expect("the original browsing context should be removed");++ let assert_retired_properties = |vm: &mut ScriptVm, stage: &str| {+ let expected = "[true,true,true,true,true,true,true,true,true,true,true,true,true]";+ assert_eq!(+ vm.eval("retiredProperties(oldWindow)")+ .expect("retired Window properties should be accessible from the parent realm"),+ expected,+ "{stage}, cleanup before reinsertion: {cleanup_before_reinsertion}"+ );+ assert_eq!(+ vm.eval("readRetiredProperties()")+ .expect("retired Window properties should be accessible from its own realm"),+ expected,+ "{stage}, cleanup before reinsertion: {cleanup_before_reinsertion}"+ );+ assert_eq!(+ vm.eval(+ "parentLengthGetter.call(oldWindow) + '|' + childLengthGetter.call(oldWindow)"+ )+ .expect("borrowed length getters should use the receiver's execution identity"),+ "0|0",+ "{stage}, cleanup before reinsertion: {cleanup_before_reinsertion}"+ );+ };+ if cleanup_before_reinsertion {+ assert!(vm.live_child_default_runtime_realm_inventory().is_empty());+ assert_retired_properties(&mut vm, "after cleanup");+ }+ vm.exec(+ r#"+document.body.appendChild(frame);+globalThis.newWindow = frame.contentWindow;+globalThis.newDocument = frame.contentDocument;+newDocument.body.innerHTML = '<div id="__retainedNewMarker">REPLACEMENT</div><iframe name="__retainedNewChild"></iframe>';+globalThis.newChild = newWindow[0];+newChild.document.body.textContent = 'NEW CHILD';+"#,+ None,+ )+ .expect("the reinserted iframe should acquire a new document and child frame");+ vm.live_child_default_runtime_realm_inventory();+ assert_retired_properties(&mut vm, "after reinsertion");+ assert_eq!(+ vm.eval(+ r#"+(() => {+ if (oldWindow.__retainedParentMarker)+ oldWindow.__retainedParentMarker.textContent = 'WRITTEN VIA OLD WINDOW';+ if (oldWindow[0])+ oldWindow[0].document.body.textContent = 'WRITTEN VIA OLD WINDOW';+ return JSON.stringify([+ oldWindow !== newWindow,+ oldWindow.document === oldDocument,+ oldDocument.body.textContent,+ parentMarker.textContent,+ newDocument.body.textContent,+ newChild.document.body.textContent,+ newWindow.__retainedNewMarker === newDocument.getElementById('__retainedNewMarker'),+ newWindow.__retainedNewChild === newChild,+ newWindow.length === 1,+ newWindow[0] === newChild,+ parentLengthGetter.call(newWindow) === 1,+ childLengthGetter.call(newWindow) === 1,+ Object.getOwnPropertyDescriptor(newWindow, '0').value === newChild+ ]);+})()+"#,+ )+ .expect("only the live Window should expose its document names and child frames"),+ r#"[true,true,"ORIGINAL","PARENT","REPLACEMENT","NEW CHILD",true,true,true,true,true,true,true]"#,+ "cleanup before reinsertion: {cleanup_before_reinsertion}"+ );+ }+}+#[test]fn window_document_retains_original_document_after_iframe_removal_and_reinsertion() {for cleanup_before_reinsertion in [false, true] {@@ -93,7 +222,7 @@ globalThis.childDocumentGetter = Object.getOwnPropertyDescriptor(retainedWindow,).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)+ vm.exec("documentFrame.srcdoc = '<body><div id=destinationMarker>DESTINATION</div><iframe name=destinationChild></iframe></body>';", None).expect("same-origin cross-document navigation should start");vm.drain_pending_child_frame_work_for_test();@@ -106,11 +235,16 @@ retainedWindow.document === documentFrame.contentDocument,parentDocumentGetter.call(retainedWindow) === documentFrame.contentDocument,childDocumentGetter.call(retainedWindow) === documentFrame.contentDocument,childDocumentGetter.call(window) === document,-retainedWindow.document.body.textContent+retainedWindow.document.body.textContent,+retainedWindow.destinationMarker === documentFrame.contentDocument.getElementById('destinationMarker'),+retainedWindow.destinationChild === retainedWindow[0],+retainedWindow.length === 1,+'0' in retainedWindow,+Object.getOwnPropertyDescriptor(retainedWindow, '0').value === retainedWindow[0]])"#,).expect("retained WindowProxy and borrowed getters should read the destination Document"),- r#"[true,true,true,true,true,true,"DESTINATION"]"#+ r#"[true,true,true,true,true,true,"DESTINATION",true,true,true,true,true]"#);}