From c178aebd83dd6a68fc011ff01847fd22e71e7c13 Mon Sep 17 00:00:00 2001 From: ldm0 Date: Tue, 6 Oct 2026 08:47:38 +0800 Subject: [PATCH] fix(renderer): reconcile native Window lifecycle with protocol Page ownership Use the canonical Window.document and Location objects across related Pages, retain producer identity and inherited about-document settings, and preserve the Page dispatch policy for cross-document history traversal. Route stop and close through exact Document owner actions and apply them through ordered protocol target lanes. Keep unload reentry checks and bootstrap output ordering. Window.opener=null preserves its accessor as specified; adjust the two conflicting protocol expectations while keeping the renderer regression. Register the main realm owner before native HistoryEntry bootstrap so inherited origins remain in committed history; replace an initial-empty entry consistently in both navigate events and Location seeds. Empty URL reuse can retain a focus activation with navigation_requested=false while preserving every document/history/load assertion. The renderer enum producer and exhaustive protocol consumer change together. Formatting, strict workspace Clippy and the complete nextest suite passed against unchanged final source with 32 workers and zero retries. --- .../browser_context/target_session_owner.rs | 26 ++++ moli-protocol/src/conn/state/navigation.rs | 11 +- moli-protocol/src/conn/state/page_slot.rs | 20 +++ moli-protocol/src/conn/state/runtime_slot.rs | 14 ++ .../output_ingress/prepared_outputs.rs | 8 + .../src/domains/activity/output_slot.rs | 5 + moli-protocol/src/domains/page.rs | 4 + moli-protocol/src/domains/page/navigation.rs | 24 ++- moli-protocol/src/domains/page/output.rs | 42 +++++ .../p1_target_multipage.rs | 4 +- moli-renderer-v8/src/context_bootstrap.rs | 3 +- .../src/context_bootstrap/history_mutation.rs | 9 +- .../history_runtime/admission.rs | 4 +- .../context_bootstrap/location_navigation.rs | 91 ++++++++--- .../navigation_cancellation.rs | 8 +- .../src/context_bootstrap/navigation_entry.rs | 4 +- .../navigation_interception.rs | 8 + .../context_bootstrap/navigation_traversal.rs | 46 +++++- .../navigation_traversal_execution.rs | 72 ++++++--- .../context_bootstrap/navigation_window.rs | 24 +-- .../src/context_bootstrap/session_history.rs | 8 +- .../session_history_traversal.rs | 78 +++++----- .../src/context_bootstrap/trusted_types.rs | 2 +- .../window_accessors/document.rs | 28 +++- .../window_runtime/dialogs.rs | 42 ++++- .../src/frame_owner_model/records.rs | 10 +- .../src/frame_owner_model/store.rs | 38 +++++ .../src/frame_owner_model/store_tests.rs | 47 ++++++ .../context_host/child_documents/lifecycle.rs | 1 + .../child_frame_runtime/isolated_world.rs | 2 +- .../child_frame_runtime/window.rs | 21 +++ .../context_host/child_frames/discovery.rs | 7 + .../src/native_bridge/context_host/core.rs | 32 +++- .../context_host/main_document_lifecycle.rs | 33 +++- .../src/native_bridge/context_host/mod.rs | 2 +- .../native_bridge/context_host/navigation.rs | 18 +++ .../src/native_bridge/context_host/popups.rs | 71 ++------- .../context_host/popups/renderer_owned.rs | 61 +++++++- .../context_host/runtime_observable.rs | 18 +-- .../window_execution_context/settings.rs | 2 +- .../element/activation/targets.rs | 144 ++++++++++++++---- .../src/native_bridge/identity.rs | 89 ++++++++--- .../identity/dense_reflector_map.rs | 7 - .../src/runtime/owner_local_store/entry.rs | 6 + .../src/runtime/page_vm/auxiliary_page.rs | 5 +- .../runtime/page_vm/followed_navigation.rs | 26 +++- moli-renderer-v8/src/runtime/page_vm/mod.rs | 6 + .../src/runtime/protocol_output/item.rs | 3 + .../protocol_output/transport_memory.rs | 3 +- moli-renderer-v8/src/script_vm.rs | 38 ++++- .../src/script_vm/document_environment.rs | 73 +++++++-- .../src/script_vm/document_isolate.rs | 17 +++ .../src/script_vm/execution_contexts.rs | 4 +- .../src/script_vm/initial_window_document.rs | 50 ++++-- moli-renderer-v8/src/script_vm/popup_close.rs | 22 +++ moli-renderer-v8/src/script_vm/post_parse.rs | 14 +- .../src/script_vm/related_page.rs | 16 ++ .../browser_api/window_open_empty_url.rs | 9 +- .../tests/extracted/realms_and_teardown.rs | 4 +- moli-renderer-v8/src/script_vm/tests/mod.rs | 1 - moli-renderer-v8/src/window_host.rs | 12 +- moli-window-features/src/lib.rs | 5 - 62 files changed, 1153 insertions(+), 349 deletions(-) diff --git a/moli-protocol/src/conn/browser_context/target_session_owner.rs b/moli-protocol/src/conn/browser_context/target_session_owner.rs index 1f3dfc596d0..399aa84e94f 100644 --- a/moli-protocol/src/conn/browser_context/target_session_owner.rs +++ b/moli-protocol/src/conn/browser_context/target_session_owner.rs @@ -1440,6 +1440,32 @@ impl CdpConnection { .clear_pending_navigation_history_update() } + pub(crate) fn stop_renderer_location_navigation_for_owner( + &mut self, + owner: &CommandOwnerScope, + source_document: moli_core::RendererDocumentLifecycleIdentity, + ) { + let Some(mut resolved) = self.target_session_owner_mut_for_owner(owner) else { + return; + }; + let target = resolved.target_mut(); + // stop() aborts traversal signals and API promises, but script cannot + // cancel the browser's physical cross-document history traversal. + if target + .owner_state + .navigation_history_state + .is_pending_traversal() + { + return; + } + if target + .runtime_slot + .stop_pending_document_navigation(source_document) + { + target.owner_state.clear_pending_navigation_history_update(); + } + } + pub(crate) fn take_crashed_page_for_owner( &mut self, owner: &CommandOwnerScope, diff --git a/moli-protocol/src/conn/state/navigation.rs b/moli-protocol/src/conn/state/navigation.rs index 739919f64bd..9158a40e21d 100644 --- a/moli-protocol/src/conn/state/navigation.rs +++ b/moli-protocol/src/conn/state/navigation.rs @@ -239,6 +239,13 @@ impl TargetNavigationHistoryState { self.pending_update = None; } + pub(crate) fn is_pending_traversal(&self) -> bool { + matches!( + self.pending_update, + Some(PendingNavigationHistoryUpdate::TraverseToEntry(_)) + ) + } + pub(crate) fn is_pending_reload(&self) -> bool { matches!( self.pending_update, @@ -287,8 +294,8 @@ impl TargetNavigationHistoryState { } let mutation = match self.pending_update { Some( - PendingNavigationHistoryUpdate::ReplaceCurrent - | PendingNavigationHistoryUpdate::ReplaceInitialEmptyDocument, + PendingNavigationHistoryUpdate::ReplaceCurrent(_) + | PendingNavigationHistoryUpdate::ReplaceInitialEmptyDocument(_), ) => moli_page_types::NavigationHistoryMutation::Replace, _ => moli_page_types::NavigationHistoryMutation::Push, }; diff --git a/moli-protocol/src/conn/state/page_slot.rs b/moli-protocol/src/conn/state/page_slot.rs index 8d2bd767afe..743fba229c4 100644 --- a/moli-protocol/src/conn/state/page_slot.rs +++ b/moli-protocol/src/conn/state/page_slot.rs @@ -746,6 +746,25 @@ impl TargetPageSlot { } } + pub(crate) fn cancel_uncommitted_document_navigation(&mut self) -> bool { + let Some(token) = self + .pending_navigation_request + .as_ref() + .filter(|request| !request.committed) + .map(|request| request.token.clone()) + else { + return false; + }; + self.cancel_pending_document_navigation(); + if matches!(self.pending_renderer_page.binding.as_ref(), + Some(PendingRendererPageBinding::DocumentNavigation { navigation, .. }) + if navigation == &token) + { + self.replace_pending_renderer_page(None); + } + true + } + pub(crate) fn document_navigation_cancellation_handle( &self, token: &DocumentNavigationToken, @@ -2001,6 +2020,7 @@ mod pending_renderer_page_tests { timestamp: 1.0, session_history_position: None, browsing_context_group: None, + navigation_policy: None, }) } diff --git a/moli-protocol/src/conn/state/runtime_slot.rs b/moli-protocol/src/conn/state/runtime_slot.rs index ad0b99fefd9..8ce3773648f 100644 --- a/moli-protocol/src/conn/state/runtime_slot.rs +++ b/moli-protocol/src/conn/state/runtime_slot.rs @@ -928,6 +928,20 @@ impl TargetRuntimeSlot { self.page_slot.has_pending_document_navigation() } + pub(crate) fn stop_pending_document_navigation( + &mut self, + source_document: RendererDocumentLifecycleIdentity, + ) -> bool { + if self + .committed_renderer_document_binding() + .map(CommittedRendererDocumentBinding::renderer_document_identity) + != Some(source_document) + { + return false; + } + self.page_slot.cancel_uncommitted_document_navigation() + } + pub(crate) fn moli_memory_diagnostics(&self) -> Value { json!({ "hasLoadedPage": self.has_loaded_page(), diff --git a/moli-protocol/src/domains/activity/output_ingress/prepared_outputs.rs b/moli-protocol/src/domains/activity/output_ingress/prepared_outputs.rs index b71ce757ac4..3bd69433a50 100644 --- a/moli-protocol/src/domains/activity/output_ingress/prepared_outputs.rs +++ b/moli-protocol/src/domains/activity/output_ingress/prepared_outputs.rs @@ -398,6 +398,14 @@ impl PreparedProtocolOutputs { ) -> Self { let mut prepared = Self::empty(); match action { + RendererOwnerAction::StopTopLevelLocationNavigation { source_document } => { + crate::domains::page::PagePreparedOutputs::from_renderer_location_navigation_stop( + conn, + owner, + source_document, + ) + .append_to_location_navigation_stop_output_sink(&mut prepared); + } RendererOwnerAction::FileChooser(activation) => { crate::domains::input::InputPreparedOutputs::from_renderer_file_chooser_activation( conn, diff --git a/moli-protocol/src/domains/activity/output_slot.rs b/moli-protocol/src/domains/activity/output_slot.rs index ad0889a7d2d..71a243ae9a3 100644 --- a/moli-protocol/src/domains/activity/output_slot.rs +++ b/moli-protocol/src/domains/activity/output_slot.rs @@ -33,6 +33,7 @@ pub(in crate::domains) enum ProtocolOutputSlot { WebMcp, PendingSubresourceContinueEvents, TopLevelLocationNavigation, + StopTopLevelLocationNavigation, TopLevelHistoryTraversal, FileChooser, Download, @@ -83,6 +84,7 @@ impl ProtocolOutputSlot { | Self::SessionHistoryUpdate | Self::SameDocumentNavigation | Self::TopLevelLocationNavigation + | Self::StopTopLevelLocationNavigation | Self::TopLevelHistoryTraversal => ProtocolOutputDelivery::OwnerAction, Self::WindowOpen | Self::WebMcp @@ -119,6 +121,7 @@ impl ProtocolOutputSlot { | Self::ServiceWorkerTargetLifecycle | Self::ChildFrameActivity | Self::PendingSubresourceContinueEvents + | Self::StopTopLevelLocationNavigation // Blink's file-input activation probe queues // Page.fileChooserOpened synchronously. A script may continue into // document.open(), but Chromium still flushes the chooser event @@ -202,6 +205,7 @@ impl ProtocolOutputSlot { | Self::NavigateAuxiliaryWindow | Self::SessionHistoryUpdate | Self::TopLevelLocationNavigation + | Self::StopTopLevelLocationNavigation | Self::TopLevelHistoryTraversal | Self::SameDocumentNavigation => { return crate::domains::page::project_page_output_finite( @@ -307,6 +311,7 @@ mod tests { BeforeResponse, ), (TopLevelLocationNavigation, OwnerAction, BeforeResponse), + (StopTopLevelLocationNavigation, OwnerAction, BeforeResponse), (TopLevelHistoryTraversal, OwnerAction, BeforeResponse), (CloseAuxiliaryWindow, OwnerAction, BeforeResponse), (NavigateAuxiliaryWindow, OwnerAction, BeforeResponse), diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rs index ce08c257344..8dad824585e 100644 --- a/moli-protocol/src/domains/page.rs +++ b/moli-protocol/src/domains/page.rs @@ -538,6 +538,10 @@ pub(crate) struct PagePreparedOutputs { moli_page_types::SessionHistoryUpdate, )>, top_level_location_navigation: Option, + stopped_location_navigations: Vec<( + crate::conn::TargetPageResidenceIdentity, + RendererDocumentLifecycleIdentity, + )>, top_level_history_traversal: Option>, } diff --git a/moli-protocol/src/domains/page/navigation.rs b/moli-protocol/src/domains/page/navigation.rs index e8fdfa050c1..a454a0ce124 100644 --- a/moli-protocol/src/domains/page/navigation.rs +++ b/moli-protocol/src/domains/page/navigation.rs @@ -1941,17 +1941,9 @@ pub(super) fn start_session_owner_navigation_from_renderer( conn.mark_next_auxiliary_navigation_history_for_owner(owner, kind); } let result_projection = NavigationResultProjection::Cdp(result_payload); - // Top-level Navigation API traversals hand admission to the browser, - // unlike ordinary renderer navigations whose entry points own the - // source check. Keep this separate from the event's initiator. - let beforeunload = if navigation_history - .as_ref() - .is_some_and(|history| history.navigation_type() == Some("traverse")) - { - BeforeUnloadCheck::Required - } else { - BeforeUnloadCheck::RendererHandled - }; + // Renderer entry points check the exact outgoing document tree before + // handing the request to the browser, including named Window reuse. + let beforeunload = BeforeUnloadCheck::RendererHandled; start_navigate_to_url_command_with_background_policy_and_request( conn, None, @@ -2688,9 +2680,13 @@ fn start_navigate_to_url_command_with_background_policy( allow_background_navigation, request_load_policy, initiator, - // Browser commands and renderer History API handoffs reach this - // entry point before checking the outgoing document tree. - BeforeUnloadCheck::Required, + // Renderer History API handoffs have already checked the outgoing + // tree. Browser commands still own that check here. + if matches!(initiator, NavigationStartInitiator::Renderer) { + BeforeUnloadCheck::RendererHandled + } else { + BeforeUnloadCheck::Required + }, None, None, None, diff --git a/moli-protocol/src/domains/page/output.rs b/moli-protocol/src/domains/page/output.rs index ca1e8ce440a..365bcb10f2a 100644 --- a/moli-protocol/src/domains/page/output.rs +++ b/moli-protocol/src/domains/page/output.rs @@ -2,6 +2,30 @@ use super::*; use anyhow::Result; impl PagePreparedOutputs { + pub(crate) fn from_renderer_location_navigation_stop( + conn: &CdpConnection, + owner: &CommandOwnerScope, + source_document: RendererDocumentLifecycleIdentity, + ) -> Self { + let Some(residence) = conn.target_page_residence_identity_for_owner(owner) else { + return Self::default(); + }; + Self { + stopped_location_navigations: vec![(residence, source_document)], + ..Self::default() + } + } + + pub(in crate::domains) fn append_to_location_navigation_stop_output_sink( + self, + sink: &mut (impl ProtocolOutputSink + ?Sized), + ) { + if !self.stopped_location_navigations.is_empty() { + sink.push_produced_slot(ProtocolOutputSlot::StopTopLevelLocationNavigation); + sink.push_prepared_payload(PagePreparedOutputSlot::from_outputs(self).into()); + } + } + pub(crate) fn from_renderer_auxiliary_window_navigation( page_source: Option, window: moli_core::page::RendererAuxiliaryWindow, @@ -433,6 +457,8 @@ impl PagePreparedOutputs { } self.same_document_navigations .extend(other.same_document_navigations); + self.stopped_location_navigations + .extend(other.stopped_location_navigations); if self.top_level_location_navigation.is_none() { self.top_level_location_navigation = other.top_level_location_navigation; } @@ -561,6 +587,7 @@ impl PagePreparedOutputs { child_frame_activities: Vec::new(), same_document_navigations: Vec::new(), session_history_updates: Vec::new(), + stopped_location_navigations: Vec::new(), top_level_location_navigation: None, top_level_history_traversal: None, } @@ -590,6 +617,7 @@ impl PagePreparedOutputs { child_frame_activities: Vec::new(), same_document_navigations: Vec::new(), session_history_updates: Vec::new(), + stopped_location_navigations: Vec::new(), top_level_location_navigation: None, top_level_history_traversal: None, } @@ -676,6 +704,7 @@ impl PagePreparedOutputs { child_frame_activities: vec![activity], same_document_navigations: Vec::new(), session_history_updates: Vec::new(), + stopped_location_navigations: Vec::new(), top_level_location_navigation: None, top_level_history_traversal: None, } @@ -702,6 +731,7 @@ impl PagePreparedOutputs { }) .collect(), session_history_updates: Vec::new(), + stopped_location_navigations: Vec::new(), top_level_location_navigation: None, top_level_history_traversal: None, } @@ -723,6 +753,7 @@ impl PagePreparedOutputs { child_frame_activities: Vec::new(), same_document_navigations: Vec::new(), session_history_updates: Vec::new(), + stopped_location_navigations: Vec::new(), top_level_location_navigation: navigation .map(|navigation| PagePreparedTopLevelLocationNavigation::new(owner, navigation)), top_level_history_traversal: None, @@ -927,6 +958,17 @@ pub(in crate::domains) fn project_page_output_finite( ); context.command.protocol_events_mut().extend(events); } + ProtocolOutputSlot::StopTopLevelLocationNavigation => { + if let Some(slot) = prepared_outputs.page_mut() { + for (residence, source_document) in + std::mem::take(&mut slot.outputs.stopped_location_navigations) + { + if conn.target_page_residence_identity_is_current(&residence) { + conn.stop_renderer_location_navigation_for_owner(&owner, source_document); + } + } + } + } ProtocolOutputSlot::TopLevelHistoryTraversal => { publish_prepared_top_level_history_traversal_owner_action(conn, prepared_outputs); } diff --git a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs index b4e8af2d25d..d6991942f58 100644 --- a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs +++ b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs @@ -1316,7 +1316,7 @@ async fn rust_cdp_chromium_target_named_reuse_updates_dom_opener_before_returnin &mut ctx, &parent_session, 269_027, - "child.opener=null;Object.getOwnPropertyDescriptor(child,'opener').value===null", + "child.opener=null;child.opener===null && typeof Object.getOwnPropertyDescriptor(child,'opener').get==='function'", ) .await; assert_eq!(disowned["result"]["result"]["value"], true); @@ -1324,7 +1324,7 @@ async fn rust_cdp_chromium_target_named_reuse_updates_dom_opener_before_returnin &mut ctx, &sibling_session, 269_028, - "open('', 'child').opener===null", + "open('', 'child').opener===window", ) .await; assert_eq!(shadowed["result"]["result"]["value"], true); diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index 908b146e4f7..f1cc54a2e34 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -218,7 +218,7 @@ pub(crate) use css_fontface_runtime::{ pub(crate) use form_navigation::FormNavigationHistory; pub(crate) use history_mutation::update_history_for_document_open; pub(crate) use location_navigation::{ - HyperlinkNavigationOptions, LocationNavigationKind, + HyperlinkNavigationOptions, LocationNavigationKind, blocks_ancestor_location_navigation, dispatch_top_level_navigation_event_with_source_element, history_entry_seed_for_cross_document_location, is_native_location, navigate_borrowed_location, navigate_child_meta_refresh, navigate_location_object_for_element_fragment, @@ -525,7 +525,6 @@ pub(crate) use self::runtime_state::install_webassembly_runtime_state; #[cfg(feature = "wpt-extensions")] pub(crate) use self::runtime_state::install_wpt_webdriver_runtime_state; pub(crate) use self::runtime_state::set_window_origin_runtime_state; -pub(crate) use self::runtime_state::window_realm_secure_context_available; pub(crate) use self::runtime_state::{ ORIGINAL_WEBASSEMBLY_COMPILE_ERROR_CONSTRUCTOR_SLOT, ORIGINAL_WEBASSEMBLY_GLOBAL_VALUE_GETTER_SLOT, ORIGINAL_WEBASSEMBLY_INSTANCE_CONSTRUCTOR_SLOT, diff --git a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs b/moli-renderer-v8/src/context_bootstrap/history_mutation.rs index fce43c7e04a..62309a717ff 100644 --- a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs +++ b/moli-renderer-v8/src/context_bootstrap/history_mutation.rs @@ -27,7 +27,6 @@ use super::navigation_window::{ runtime_window_is_global, window_history_for_holder, window_location_for_holder, window_navigation_for_holder, }; -use super::*; use crate::context_bootstrap::navigation_entry::wrappers as entry_wrappers; use crate::structured_clone::{deserialize_history_state, serialize_history_state}; use crate::webidl; @@ -210,7 +209,7 @@ fn mutate_history_object<'s>( // Admission follows argument conversion, state serialization and URL // validation, but precedes navigation cancellation and event dispatch. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, owner) else { return; }; let Some(dispatch_scope) = runtime_window_dispatch_scope(scope, owner) else { @@ -411,7 +410,7 @@ fn history_api_base_url<'s>( owner: v8::Local<'s, v8::Object>, current_url: &url::Url, ) -> url::Url { - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, owner) else { return current_url.clone(); }; let host = unsafe { &*host_ptr }; @@ -439,7 +438,7 @@ fn history_document_url<'s>( owner: v8::Local<'s, v8::Object>, current_href: &str, ) -> Option { - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, owner) else { return url::Url::parse(current_href).ok(); }; let host = unsafe { &*host_ptr }; @@ -466,7 +465,7 @@ fn effective_history_mutation_kind<'s>( if !matches!(kind, HistoryMutationKind::Push) { return kind; } - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, owner) else { return kind; }; let host = unsafe { &*host_ptr }; diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/admission.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/admission.rs index e2c80fa9773..084399a306e 100644 --- a/moli-renderer-v8/src/context_bootstrap/history_runtime/admission.rs +++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/admission.rs @@ -1,5 +1,5 @@ use super::super::navigation_window::{navigation_document_is_active, runtime_window_owner}; -use super::super::{context_host_ptr_from_global_bridge, throw_dom_exception_value}; +use super::super::throw_dom_exception_value; /// History API algorithms call this after WebIDL argument conversion. pub(in crate::context_bootstrap) fn require_fully_active_history_owner<'s>( @@ -10,7 +10,7 @@ pub(in crate::context_bootstrap) fn require_fully_active_history_owner<'s>( let is_fully_active = if let Some(popup_id) = crate::native_bridge::lightweight_popup_id_from_window(scope, owner) { - context_host_ptr_from_global_bridge(scope) + super::super::window_accessors::window_host_ptr(scope, owner) .is_some_and(|host_ptr| unsafe { &*host_ptr }.lightweight_popup_is_open(popup_id)) } else { navigation_document_is_active(scope, owner) diff --git a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs index 60945a9e3e3..c4f058b28f6 100644 --- a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs +++ b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs @@ -75,6 +75,7 @@ struct LocationNavigationOptions { dispatch_child_navigate_event_for_all_kinds: bool, force_exact_same_document_navigation: bool, explicit_initiator_url: Option, + explicit_navigation_initiator: Option, user_initiated: bool, source_can_access_target: Option, hyperlink: bool, @@ -85,7 +86,7 @@ pub(crate) struct HyperlinkNavigationOptions { pub(crate) source_document: crate::document_runtime::DomHandle, pub(crate) user_initiated: bool, pub(crate) source_can_access_target: bool, - pub(crate) initiator_url: url::Url, + pub(crate) initiator: crate::runtime::RendererNavigationInitiator, pub(crate) named_popup: Option, } @@ -108,7 +109,8 @@ pub(crate) fn navigate_location_object_for_hyperlink<'s>( source_can_access_target: Some(options.source_can_access_target), hyperlink: true, force_exact_same_document_navigation: true, - explicit_initiator_url: Some(options.initiator_url), + explicit_initiator_url: Some(options.initiator.url().clone()), + explicit_navigation_initiator: Some(options.initiator), named_hyperlink_popup: options.named_popup, ..LocationNavigationOptions::default() }, @@ -371,6 +373,28 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( source_element: Option>, options: LocationNavigationOptions, ) { + if let Some(context) = location.get_creation_context(scope) + && context != scope.get_current_context() + && is_native_location(scope, location) + && crate::util::context_host_ptr_from_context_slot(context) + != context_host_ptr_from_global_bridge(scope) + { + // URL parsing retains the entry settings before entering the native + // receiver's realm. The incumbent source remains available for the + // initiator, origin and about-document inheritance checks below. + let raw_target = + raw_target.map(|raw| resolve_cross_window_location_target(scope, &raw).unwrap_or(raw)); + let scope = &mut v8::ContextScope::new(scope, context); + navigate_location_object_with_source_element_and_child_navigate_event( + scope, + location, + kind, + raw_target, + source_element, + options, + ); + return; + } // The Location setters and methods return before URL parsing when their // relevant Document is null, including when argument conversion removed it. if !location_has_relevant_document(scope, location) { @@ -394,6 +418,7 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( dispatch_child_navigate_event_for_all_kinds, force_exact_same_document_navigation, explicit_initiator_url, + explicit_navigation_initiator, user_initiated, source_can_access_target, hyperlink, @@ -426,7 +451,13 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( let navigation_source = if matches!(kind, LocationNavigationKind::Reload) { None } else { - capture_location_navigation_source(scope, owner, &resolved) + let captured = capture_location_navigation_source(scope, owner, &resolved); + match (explicit_navigation_initiator, captured) { + (Some(initiator), captured) => { + Some((initiator, captured.and_then(|(_, environment)| environment))) + } + (None, captured) => captured, + } }; if resolved.scheme() == "javascript" { let source_context = scope @@ -465,6 +496,14 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( }); let owner = runtime_window_owner(scope, location); let source_can_access_target = source_can_access_target.unwrap_or_else(|| { + if runtime_window_is_global(scope, owner) + && let Some(context) = owner.get_creation_context(scope) + { + let source = scope + .get_incumbent_context() + .unwrap_or_else(|| scope.get_current_context()); + return crate::native_bridge::window_contexts_allow_access(source, context); + } let Some(host_ptr) = context_host_ptr_for_navigation_owner(scope, owner) else { return true; }; @@ -478,6 +517,16 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( target, ) }); + // Child navigations capture the source origin and recheck the target when + // their queued task executes. Preserve that check instead of rejecting the + // Location write synchronously as for a top-level related Page. + if resolved.scheme() == "javascript" + && !source_can_access_target + && runtime_window_is_global(scope, owner) + { + crate::native_bridge::throw_cross_origin_location_security_error(scope); + return; + } let event_source_element = source_element.filter(|_| source_can_access_target); if navigation_unload_event_active(scope, owner) || super::navigation_cancellation::window_navigation_is_stopping(scope, owner) @@ -577,6 +626,9 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( }; let mut navigate_outcome = navigation.map(|navigation| { let _ = cancel_active_navigation_event(scope, navigation); + super::navigation_result::cancel_active_cross_document_navigation( + scope, navigation, None, + ); cancel_pending_precommit_same_document_navigation(scope, navigation); cancel_pending_precommit_history_traversal(scope, navigation); cancel_active_intercepted_same_document_navigation(scope, navigation); @@ -797,6 +849,16 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( return; } + let kind = if kind == LocationNavigationKind::Assign + && resolved.scheme() != "javascript" + && runtime_window_is_global(scope, owner) + && context_host_ptr_for_navigation_owner(scope, owner) + .is_some_and(|host| unsafe { &*host }.main_document_is_initial_empty()) + { + LocationNavigationKind::Replace + } else { + kind + }; let child_handle = if runtime_window_is_global(scope, owner) { None } else { @@ -807,11 +869,7 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( && let Some(navigation) = super::navigation_window::window_navigation_for_holder(scope, owner) { - if popup_id.is_some() { - super::navigation_result::cancel_active_cross_document_navigation( - scope, navigation, None, - ); - } + super::navigation_result::cancel_active_cross_document_navigation(scope, navigation, None); let _ = cancel_active_navigation_event(scope, navigation); cancel_pending_precommit_same_document_navigation(scope, navigation); cancel_pending_precommit_history_traversal(scope, navigation); @@ -866,14 +924,12 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( ); return; } - if popup_id.is_some() { - super::navigation_result::track_cross_document_location_navigation( - scope, - navigation, - outcome.signal, - resolved.as_str(), - ); - } + super::navigation_result::track_cross_document_location_navigation( + scope, + navigation, + outcome.signal, + resolved.as_str(), + ); } if let Some(popup_id) = popup_id { @@ -1008,6 +1064,7 @@ pub(crate) fn is_native_location<'s>( scope: &mut v8::PinScope<'s, '_>, receiver: v8::Local<'s, v8::Object>, ) -> bool { + let receiver = moli_webapi_declare::web_api_object_target(scope, receiver).unwrap_or(receiver); crate::util::get_private_value(scope, receiver, WINDOW_LOCATION_HREF_SLOT).is_some() } @@ -1105,7 +1162,7 @@ fn capture_location_navigation_source<'s>( } } -fn blocks_ancestor_location_navigation<'s>( +pub(crate) fn blocks_ancestor_location_navigation<'s>( scope: &mut v8::PinScope<'s, '_>, owner: v8::Local<'s, v8::Object>, destination: &url::Url, diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_cancellation.rs b/moli-renderer-v8/src/context_bootstrap/navigation_cancellation.rs index 69380d6510d..2709b7a5012 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_cancellation.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_cancellation.rs @@ -16,7 +16,7 @@ use super::{ use crate::native_bridge::{ OwnerDispatchScope, PageScriptHost, WindowDocumentTaskTarget, WindowExecutionContextBinding, }; -use crate::util::{context_host_ptr_from_global_bridge, get_private_value, set_private_value}; +use crate::util::{get_private_value, set_private_value}; const WINDOW_STOP_ACTIVE_SLOT: &str = "__lmWindowStopActive"; @@ -133,7 +133,7 @@ pub(crate) fn stop_navigation_for_window_and_descendants<'s>( window: v8::Local<'s, v8::Object>, binding: WindowExecutionContextBinding, ) { - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, window) else { return; }; let host = unsafe { &*host_ptr }; @@ -216,7 +216,7 @@ pub(super) fn clear_pending_cross_document_navigation_for_window<'s>( scope: &mut v8::PinScope<'s, '_>, window: v8::Local<'s, v8::Object>, ) { - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, window) else { return; }; let host = unsafe { &mut *host_ptr }; @@ -238,7 +238,7 @@ pub(super) fn clear_pending_cross_document_navigation_for_window<'s>( } match dispatch_scope { Some(crate::native_bridge::OwnerDispatchScope::Top) => { - host.clear_pending_location_navigation(); + host.cancel_pending_location_navigation(); } Some(crate::native_bridge::OwnerDispatchScope::Child(handle)) => { host.cancel_pending_child_browsing_context_navigation(handle); diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs index a4d03a4f8bc..3891730da34 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs @@ -178,7 +178,9 @@ pub(super) fn navigation_document_origin<'s>( ) -> String { super::navigation_window::runtime_window_dispatch_scope(scope, owner) .and_then(|dispatch_scope| { - crate::util::context_host_ptr_from_global_bridge(scope) + owner + .get_creation_context(scope) + .and_then(crate::util::context_host_ptr_from_context_slot) .and_then(|host| unsafe { &*host }.window_document_origin(dispatch_scope)) }) .or_else(|| { diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_interception.rs b/moli-renderer-v8/src/context_bootstrap/navigation_interception.rs index 925c9747a56..99b403d8753 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_interception.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_interception.rs @@ -118,6 +118,14 @@ pub(super) fn dispatch_cross_document_navigation_event<'s>( return false; } if !outcome.intercepted { + if !same_document && download_request.is_none() { + super::navigation_result::track_cross_document_location_navigation( + scope, + navigation, + outcome.signal, + href, + ); + } return true; } cancel_pending_same_document_navigation_finishes(scope, navigation); diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs index 6fa79cc4b08..b8ee65863fe 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs @@ -285,9 +285,7 @@ pub(super) fn navigation_reload_callback<'s>( if navigation_can_update_current_entry(scope, args.this()) && let Some(navigation) = window_navigation_for_holder(scope, owner) { - if crate::native_bridge::lightweight_popup_id_from_window(scope, owner).is_some() { - cancel_active_cross_document_navigation(scope, navigation, None); - } + cancel_active_cross_document_navigation(scope, navigation, None); let _ = cancel_active_navigation_event(scope, navigation); cancel_pending_precommit_same_document_navigation(scope, navigation); cancel_pending_precommit_history_traversal(scope, navigation); @@ -397,6 +395,48 @@ pub(super) fn navigation_reload_callback<'s>( rv.set(pending.object.into()); return; } + if super::navigation_window::runtime_window_is_global(scope, owner) + && let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, owner) + && let Some(context) = owner.get_creation_context(scope) + && let Some(entry_seed) = + super::navigation_seed::history_entry_seed_for_reload(scope, owner) + && let Ok(url) = url::Url::parse(¤t_href) + { + let scope = &mut v8::ContextScope::new(scope, context); + if !unsafe { &mut *host_ptr }.dispatch_main_document_tree_beforeunload(scope) { + rv.set( + reload_canceled_after_dispatch_result( + scope, + navigation, + &outcome, + ¤t_href, + ) + .into(), + ); + return; + } + let about_document_state = unsafe { &*host_ptr }.capture_about_document_state( + crate::native_bridge::OwnerDispatchScope::Top, + &url, + None, + ); + unsafe { &mut *host_ptr }.record_pending_location_navigation_with_kind( + url, + Some(entry_seed), + moli_fetch::BrowserNavigationRequestKind::Reload, + about_document_state, + ); + rv.set( + navigation_cross_document_pending_result( + scope, + navigation, + outcome.signal, + ¤t_href, + ) + .into(), + ); + return; + } if let Some(popup_id) = crate::native_bridge::lightweight_popup_id_from_window(scope, owner) && let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) && let Some(entry_seed) = diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs index 0412d3f35e7..99009897e6d 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs @@ -5,14 +5,12 @@ use super::navigation_events::{ NavigationDispatchOutcome, dispatch_navigation_traverse_event_with_outcome, }; use super::navigation_result::{ - cancel_active_cross_document_navigation, navigation_dom_exception, navigation_pending_result, + cancel_active_cross_document_navigation, navigation_dom_exception, navigation_rejected_dom_exception_result, track_cross_document_traversal_navigation, }; use super::navigation_seed::history_entry_seed_for_traversal; use super::navigation_window::{navigation_document_is_active, window_navigation_for_holder}; -use super::navigation_window::{ - runtime_window_is_global, window_history_for_holder, window_task_target_for_runtime_owner, -}; +use super::navigation_window::{window_history_for_holder, window_task_target_for_runtime_owner}; use super::*; use crate::native_bridge::{ PendingCrossDocumentTraversal, PendingHistoryTraversalAction, PendingNavigationResult, @@ -45,7 +43,7 @@ pub(super) fn queue_navigation_traversal_with_result<'s>( "SecurityError", )); } - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, target.owner) else { return Some(navigation_rejected_dom_exception_result( scope, "Navigation was canceled", @@ -60,7 +58,7 @@ pub(super) fn queue_navigation_traversal_with_result<'s>( "AbortError", )); }; - if let Some((target_url, mut seed)) = history_entry_seed_for_traversal( + if let Some((_target_url, mut seed)) = history_entry_seed_for_traversal( scope, target.owner, target.current_index, @@ -68,10 +66,6 @@ pub(super) fn queue_navigation_traversal_with_result<'s>( ) { seed.session_history.target_step = target.joint_step; super::session_history::capture_for_navigation(scope, target.owner, &mut seed); - if runtime_window_is_global(scope, target.owner) { - host.record_pending_location_navigation(target_url, Some(seed.clone()), None); - return Some(navigation_pending_result(scope)); - } let target_key = traversal_target_entry(scope, &target) .map(|entry| entry.borrow().key.as_str().to_owned()); let receiver_context = target @@ -124,7 +118,7 @@ pub(super) fn queue_history_traversal_by_delta<'s>( delta: i64, ) { let owner = super::navigation_window::runtime_window_owner(scope, history); - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, owner) else { return; }; let host = unsafe { &mut *host_ptr }; @@ -175,6 +169,7 @@ fn apply_history_traversal_by_delta( crate::native_bridge::OwnerDispatchScope::Top, crate::native_bridge::OwnerDispatchScope::Top, ) + && host.dispatch_main_document_tree_beforeunload(scope) { host.record_pending_top_level_history_traversal(delta); } @@ -322,14 +317,18 @@ pub(in crate::context_bootstrap) fn apply_pending_cross_document_traversal<'s, ' } // close() queues retirement of this exact Window. Keep its dispatched // event and API results alive until the close task aborts them together. - let closing_popup = matches!(dispatch_scope, - crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id) - if host.lightweight_popup_is_closing(popup_id)) - && host.current_window_document_task_target_for_dispatch_scope(dispatch_scope) - == retiring_document; + let closing_window = match dispatch_scope { + crate::native_bridge::OwnerDispatchScope::Top => host.browsing_context_is_closed(), + crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id) => { + host.lightweight_popup_is_closing(popup_id) + } + crate::native_bridge::OwnerDispatchScope::Child(_) => false, + } && host + .current_window_document_task_target_for_dispatch_scope(dispatch_scope) + == retiring_document; if outcome.proceed && outcome.abort_error.is_none() - && (is_current(scope, host) || closing_popup) + && (is_current(scope, host) || closing_window) && let Some(navigation) = navigation { track_cross_document_traversal_navigation( @@ -344,7 +343,7 @@ pub(in crate::context_bootstrap) fn apply_pending_cross_document_traversal<'s, ' // cross-document traversals cannot be canceled by script. Only continue // while the original Window and Document are still active. if !is_current(scope, host) { - if !closing_popup { + if !closing_window { reject_cross_document_traversal(scope, &traversal); } return false; @@ -366,7 +365,42 @@ pub(in crate::context_bootstrap) fn apply_pending_cross_document_traversal<'s, ' queued } crate::native_bridge::OwnerDispatchScope::Top => { - unreachable!("top-level traversals are handed off to the browser") + if host.page_script_environment().is_none_or(|environment| { + environment.top_level_navigation_dispatch() + == crate::RendererTopLevelNavigationDispatch::DelegateToBrowser + }) { + let Some(step) = traversal.seed.session_history.target_step else { + reject_cross_document_traversal(scope, &traversal); + return false; + }; + let binding = super::session_history::binding(scope, host, owner); + let Some(delta) = host.session_histories.get_mut(binding.popup).delta_to(step) + else { + reject_cross_document_traversal(scope, &traversal); + return false; + }; + if let Some(key) = traversal.target_key { + host.top_level_navigation_history() + .select_joint_traversal(key, step); + } + host.record_pending_top_level_history_traversal(delta); + return true; + } + let Ok(url) = url::Url::parse(&target_url) else { + reject_cross_document_traversal(scope, &traversal); + return false; + }; + if let Some(key) = traversal.target_key + && let Some(step) = traversal.seed.session_history.target_step + { + host.top_level_navigation_history() + .select_joint_traversal(key, step); + } + // The standalone adapter has no browser history controller to + // consume a delta. Retain its concrete destination and seed after + // the shared navigate/beforeunload dispatch above. + host.record_pending_location_navigation(url, Some(traversal.seed), None); + true } } } diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_window.rs b/moli-renderer-v8/src/context_bootstrap/navigation_window.rs index d1dd81d584d..65b7911f185 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_window.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_window.rs @@ -31,7 +31,7 @@ fn navigation_owner_local_window_id<'s>( owner: v8::Local<'s, v8::Object>, ) -> Option { let dispatch_scope = runtime_window_dispatch_scope(scope, owner)?; - let host_ptr = context_host_ptr_from_global_bridge(scope)?; + let host_ptr = super::window_accessors::window_host_ptr(scope, owner)?; let owner = unsafe { &*host_ptr }.current_window_execution_context_owner(dispatch_scope)?; Some(match owner { crate::native_bridge::WindowExecutionContextOwner::Frame(local_window_id) => { @@ -63,7 +63,7 @@ fn navigation_owner_document<'s>( scope: &mut v8::PinScope<'s, '_>, owner: v8::Local<'s, v8::Object>, ) -> Option { - let host_ptr = context_host_ptr_from_global_bridge(scope)?; + let host_ptr = super::window_accessors::window_host_ptr(scope, owner)?; super::window_accessors::window_document_handle(scope, owner, unsafe { &*host_ptr }) } @@ -253,7 +253,7 @@ pub(super) fn navigation_document_is_initial_empty<'s>( scope: &mut v8::PinScope<'s, '_>, owner: v8::Local<'s, v8::Object>, ) -> bool { - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, owner) else { return false; }; let host = unsafe { &*host_ptr }; @@ -276,7 +276,7 @@ pub(super) fn navigation_document_has_disabled_entries<'s>( if navigation_document_has_opaque_origin(scope, owner) { return true; } - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, owner) else { return false; }; let host = unsafe { &*host_ptr }; @@ -285,6 +285,9 @@ pub(super) fn navigation_document_has_disabled_entries<'s>( if let Some(popup_id) = crate::native_bridge::lightweight_popup_id_from_window(scope, owner) { return !host.lightweight_popup_has_committed_navigation(popup_id); } + if runtime_window_is_global(scope, owner) { + return !host.main_document_has_committed_navigation(); + } child_browsing_context_handle_for_runtime_owner(scope, owner) .is_some_and(|handle| !host.child_has_committed_navigation(handle)) } @@ -293,7 +296,7 @@ pub(super) fn navigation_document_has_opaque_origin<'s>( scope: &mut v8::PinScope<'s, '_>, owner: v8::Local<'s, v8::Object>, ) -> bool { - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, owner) else { return false; }; let host = unsafe { &*host_ptr }; @@ -317,7 +320,7 @@ pub(crate) fn navigation_unload_event_active<'s>( ) -> bool { get_private_value(scope, owner, WINDOW_UNLOAD_EVENT_ACTIVE_SLOT) .is_some_and(|value| value.is_true()) - || context_host_ptr_from_global_bridge(scope).is_some_and(|host_ptr| { + || super::window_accessors::window_host_ptr(scope, owner).is_some_and(|host_ptr| { let host = unsafe { &*host_ptr }; super::window_accessors::window_document_handle(scope, owner, host) .is_some_and(|document| host.has_document_unload_counter(document)) @@ -347,7 +350,7 @@ pub(super) fn navigation_document_base_url<'s>( owner: v8::Local<'s, v8::Object>, fallback_href: &str, ) -> Option { - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, owner) else { return url::Url::parse(fallback_href).ok(); }; let host = unsafe { &*host_ptr }; @@ -380,16 +383,17 @@ fn navigation_document_is_live<'s>( owner: v8::Local<'s, v8::Object>, ) -> bool { if let Some(popup_id) = crate::native_bridge::lightweight_popup_id_from_window(scope, owner) { - return context_host_ptr_from_global_bridge(scope) + return super::window_accessors::window_host_ptr(scope, owner) .is_some_and(|host_ptr| unsafe { &*host_ptr }.lightweight_popup_is_open(popup_id)); } if runtime_window_is_global(scope, owner) { - return true; + return super::window_accessors::window_host_ptr(scope, owner) + .is_some_and(|host_ptr| !unsafe { &*host_ptr }.browsing_context_is_closed()); } let Some(handle) = child_browsing_context_handle_for_runtime_owner(scope, owner) else { return false; }; - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::window_accessors::window_host_ptr(scope, owner) else { return false; }; let host = unsafe { &*host_ptr }; diff --git a/moli-renderer-v8/src/context_bootstrap/session_history.rs b/moli-renderer-v8/src/context_bootstrap/session_history.rs index 4feabbd3f01..f37270059a2 100644 --- a/moli-renderer-v8/src/context_bootstrap/session_history.rs +++ b/moli-renderer-v8/src/context_bootstrap/session_history.rs @@ -234,13 +234,15 @@ pub(super) fn length<'s>( scope: &mut v8::PinScope<'s, '_>, owner: v8::Local<'s, v8::Object>, ) -> usize { - if super::navigation_window::navigation_document_is_initial_empty(scope, owner) { - return 1; - } let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { return 1; }; let host = unsafe { &mut *host_ptr }; + if super::navigation_window::runtime_window_is_global(scope, owner) + && !host.main_document_has_committed_navigation() + { + return 0; + } let binding = binding(scope, host, owner); host.session_histories .get_mut(binding.popup) diff --git a/moli-renderer-v8/src/context_bootstrap/session_history_traversal.rs b/moli-renderer-v8/src/context_bootstrap/session_history_traversal.rs index f0d69745eea..a7359098c5e 100644 --- a/moli-renderer-v8/src/context_bootstrap/session_history_traversal.rs +++ b/moli-renderer-v8/src/context_bootstrap/session_history_traversal.rs @@ -92,17 +92,9 @@ pub(super) fn apply_step( if let Some(index) = root { let target = &plan.targets[index]; if runtime_window_is_global(scope, target.owner) { - let Some(delta) = host.session_histories.get_mut(binding.popup).delta_to(step) else { - return; - }; - if let Some(entry) = history_entries(scope, target.history) - .and_then(|entries| entries.get(target.target_index as usize).cloned()) - { - let key = entry.borrow().key.as_str().to_owned(); - host.top_level_navigation_history() - .select_joint_traversal(key, step); + if let Some(traversal) = cross_document_traversal(scope, host, target, step, method) { + apply_pending_cross_document_traversal(scope, host, traversal); } - host.record_pending_top_level_history_traversal(delta); return; } } @@ -130,38 +122,8 @@ pub(super) fn apply_step( host.retain_active_history_delta_position(binding.popup); let accepted = if let Some(index) = root { let target = &plan.targets[index]; - let pending = window_task_target_for_runtime_owner(scope, host, target.owner).zip( - history_entry_seed_for_traversal( - scope, - target.owner, - target.current_index, - target.target_index, - ), - ); - if let Some((exact, (_url, mut seed))) = pending { - seed.session_history.target_step = Some(step); - let key = history_entries(scope, target.history) - .and_then(|entries| entries.get(target.target_index as usize).cloned()) - .map(|entry| entry.borrow().key.as_str().to_owned()); - let (info, results) = method.map_or_else( - || (None, Vec::new()), - |method| (method.info, method.results), - ); - apply_pending_cross_document_traversal( - scope, - host, - PendingCrossDocumentTraversal { - target: exact, - target_index: target.target_index, - target_key: key, - seed, - info, - results, - }, - ) - } else { - false - } + cross_document_traversal(scope, host, target, step, method) + .is_some_and(|traversal| apply_pending_cross_document_traversal(scope, host, traversal)) } else { let history = window_history_for_holder(scope, owner).expect("admitted traversal has a history"); @@ -263,3 +225,35 @@ pub(crate) fn finish_without_document_commit( finish(scope, host_ptr, root, popup, step); } } + +fn cross_document_traversal<'s>( + scope: &mut v8::PinScope<'s, '_>, + host: &PageScriptHost, + target: &super::navigation_traversal_execution::TraversalTarget<'s>, + step: SessionHistoryStepId, + method: Option, +) -> Option { + let exact = window_task_target_for_runtime_owner(scope, host, target.owner)?; + let (_, mut seed) = history_entry_seed_for_traversal( + scope, + target.owner, + target.current_index, + target.target_index, + )?; + seed.session_history.target_step = Some(step); + let key = history_entries(scope, target.history) + .and_then(|entries| entries.get(target.target_index as usize).cloned()) + .map(|entry| entry.borrow().key.as_str().to_owned()); + let (info, results) = method.map_or_else( + || (None, Vec::new()), + |method| (method.info, method.results), + ); + Some(PendingCrossDocumentTraversal { + target: exact, + target_index: target.target_index, + target_key: key, + seed, + info, + results, + }) +} diff --git a/moli-renderer-v8/src/context_bootstrap/trusted_types.rs b/moli-renderer-v8/src/context_bootstrap/trusted_types.rs index d59f11857a1..e24f21c0318 100644 --- a/moli-renderer-v8/src/context_bootstrap/trusted_types.rs +++ b/moli-renderer-v8/src/context_bootstrap/trusted_types.rs @@ -580,7 +580,7 @@ pub(crate) fn trusted_type_string16_or_throw<'s>( ); let default_policy_rejected = match default_policy { DefaultTrustedTypePolicyOutcome::Value(value) => { - return Some(value.utf16_units()); + return Some(value.utf16_units().into_owned()); } DefaultTrustedTypePolicyOutcome::Exception => return None, DefaultTrustedTypePolicyOutcome::Unavailable => false, diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs index 6da432d2a97..5ff7ee74b93 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs @@ -5,8 +5,16 @@ use crate::{ util::{get_private_object, set_private_value}, }; -pub(in crate::context_bootstrap) const WINDOW_DOCUMENT_SLOT: &str = - "__moliWindowAssociatedDocument"; +pub(in crate::context_bootstrap) use super::super::shared::WINDOW_DOCUMENT_SLOT; + +#[derive(moli_webapi_declare::WebApiFunctionTemplate)] +#[webapi(interface = crate::web_api_interfaces::Window, + receiver = crate::context_bootstrap::is_window_receiver)] +struct WindowDocumentAccessorDeclaration { + #[webapi(accessor_property, getter = window_document_getter, + access_policy = crate::context_bootstrap::window_receiver::require_same_origin_window_receiver)] + document: (), +} pub(in crate::context_bootstrap) fn window_document_getter_template<'s>( scope: &mut v8::PinScope<'s, '_, ()>, @@ -19,9 +27,9 @@ pub(in crate::context_bootstrap) fn window_document_getter_template<'s>( None => v8::FunctionTemplate::new(scope, window_document_getter), }; template.remove_prototype(); - // V8 checks the receiver against the actual access Context before - // invoking the callback, including when the getter is borrowed. - template.set_accept_any_receiver(false); + // WindowProxy checks ordinary property reads before using the cache. + // Explicit getter calls must reach our receiver check in the callee's + // realm so a borrowed getter creates errors with the correct intrinsic. template } @@ -30,9 +38,7 @@ pub(crate) fn retain_window_document_in_retired_realm( ) -> Option<()> { let context = scope.get_current_context(); let host_ptr = crate::util::context_host_ptr_from_context_slot(context)?; - let _ = WindowEnvironmentSettings::bind_current_main_document_for_retirement(scope, unsafe { - &*host_ptr - }); + let _ = WindowEnvironmentSettings::bind_current_main_document(scope, unsafe { &*host_ptr }); let window = context.global(scope); if get_private_object(scope, window, WINDOW_DOCUMENT_SLOT).is_some() { return Some(()); @@ -97,6 +103,12 @@ pub(in crate::context_bootstrap) fn window_document_getter<'s>( rv.set(document.into()); return; } + if crate::native_bridge::lightweight_popup_id_from_window(scope, receiver).is_some() { + // Popup bootstrap may precede its Document projection. The opener's + // host Document is never this Window's associated Document. + rv.set_null(); + return; + } let handle = if let Some(settings) = WindowEnvironmentSettings::for_current_realm(scope) { settings.document_handle() } else if let Some(handle) = window_child_context_handle(scope, receiver) { diff --git a/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs b/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs index 6330b95f828..34571803e1b 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs @@ -12,7 +12,6 @@ use crate::{ SpecialBrowsingContextTarget, navigate_existing_browsing_context_target, navigate_iframe_target, }, - entered_child_window_handle, }, runtime::{ RendererPendingJavaScriptDialog, RendererPendingPopupActivation, @@ -85,8 +84,15 @@ pub(crate) fn window_close_callback<'s>( }); if let Some(host_ptr) = receiver_context.and_then(context_host_ptr_from_context_slot) { let host = unsafe { &mut *host_ptr }; - if let Some(window) = host.auxiliary_window() { - host.request_auxiliary_window_close(window); + if let Some(window) = host.auxiliary_window() + && host.request_auxiliary_window_close(window) + && let Some(context) = receiver_context + { + // Closing has its own synchronous beforeunload check, including + // close() called from pagehide. The native close transition above + // rejects reentry; the queued close task owns final retirement. + let scope = &mut v8::ContextScope::new(scope, context); + host.dispatch_main_document_tree_beforeunload_for_close(scope); } } } @@ -136,9 +142,15 @@ pub(crate) fn window_stop_callback<'s>( args: v8::FunctionCallbackArguments<'s>, _rv: v8::ReturnValue<'_, v8::Value>, ) { - let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { + let Some(host_ptr) = super::super::window_accessors::window_host_ptr(scope, args.this()) else { return; }; + let Some(context) = args.this().get_creation_context(scope) else { + return; + }; + // The receiver was authorized above. Its native binding belongs to its + // own host, including when stop() is borrowed from another Window. + let scope = &mut v8::ContextScope::new(scope, context); let receiver = crate::native_bridge::WindowOperationReceiver::capture_after_access_check( scope, args.this(), @@ -432,7 +444,7 @@ pub(crate) fn window_open_callback<'s>( // The entered Window identifies the creator even when `noopener` removes // the opener relationship. Its child marker is more precise than the // ambient dispatch scope while a child callback is running. - let source_child_handle = window_open_receiver_child_handle(scope, entered_window); + let source_child_handle = window_receiver_child_handle(scope, entered_window); let popup_source_scope = source_child_handle .map(OwnerDispatchScope::Child) .unwrap_or(source_scope); @@ -472,6 +484,17 @@ pub(crate) fn window_open_callback<'s>( let renderer_navigation = url .as_deref() .is_some_and(|url| opened.queue_javascript_navigation(scope, url)); + if !parsed.raw_url.is_empty() + && !renderer_navigation + && !opened.prepare_navigation_activation(scope) + { + if suppress_opener { + rv.set_null(); + } else { + rv.set(opened.window_proxy.into()); + } + return; + } let disposition = if opened.pending_page.is_some() || host.protocol_user_gesture_activation() || host.current_input_event().is_some() @@ -532,7 +555,7 @@ pub(crate) fn window_open_callback<'s>( url.as_deref(), entered_base_url, creator_policy_container, - true, + false, ), _ => host.open_lightweight_popup_window( scope, @@ -562,7 +585,9 @@ pub(crate) fn window_open_callback<'s>( let popup_id = opened_popup.popup_id; if opened_popup.created_new_browsing_context { host.set_lightweight_popup_is_popup(popup_id, parsed_features.is_popup()); - } else if url.is_none() || !opened_popup.allows_navigation_activation(scope, host) { + } else if (url.is_none() && host.lightweight_popup_has_pending_document_load(popup_id)) + || !opened_popup.allows_navigation_activation(scope, host) + { if suppress_opener { rv.set(v8::null(scope).into()); } else { @@ -804,7 +829,8 @@ fn open_dialog( if !allows_modals { return None; } - let source_url = window_open_entered_document_url(scope, host).to_string(); + let source_url = + window_open_document_url(host, entered_window_dispatch_scope(scope, host)).to_string(); let dialog_id = host.allocate_javascript_dialog_id(); host.open_modal_javascript_dialog( target, diff --git a/moli-renderer-v8/src/frame_owner_model/records.rs b/moli-renderer-v8/src/frame_owner_model/records.rs index 51534910519..6abd460700e 100644 --- a/moli-renderer-v8/src/frame_owner_model/records.rs +++ b/moli-renderer-v8/src/frame_owner_model/records.rs @@ -932,7 +932,11 @@ impl DocumentLifecycleRecord { self.domcontentloaded_transition_token = None; self.complete_transition_token = None; self.readiness = Some(DocumentReadinessState::Complete); - self.load = DocumentLoadEventProgress::Ready; + self.load = if self.load_delivery_kind == DocumentLoadDeliveryKind::Main { + DocumentLoadEventProgress::Suppressed + } else { + DocumentLoadEventProgress::Ready + }; self.completely_loaded = true; true } @@ -1148,6 +1152,10 @@ impl DocumentLifecycleRecord { Some(finished) } + pub(super) fn unload_has_started(&self) -> bool { + self.unload != DocumentUnloadEventProgress::Pending + } + pub(super) fn begin_unload_dispatch(&mut self) -> bool { if !self.child_load_event_has_started() || self.unload != DocumentUnloadEventProgress::Pending diff --git a/moli-renderer-v8/src/frame_owner_model/store.rs b/moli-renderer-v8/src/frame_owner_model/store.rs index 159afae4679..26573d5b666 100644 --- a/moli-renderer-v8/src/frame_owner_model/store.rs +++ b/moli-renderer-v8/src/frame_owner_model/store.rs @@ -210,6 +210,38 @@ impl FrameOwnerStore { realm_id } + pub(crate) fn mark_main_document_initial_empty(&mut self) { + let owner = self + .current_main_owner_snapshot() + .expect("an initial main Document must have an installed owner"); + let document = self + .documents + .get_mut(&owner.document_id) + .expect("the current main Document must retain its owner record"); + document.creation_kind = DocumentCreationKind::InitialEmpty; + document.has_committed_navigation = false; + } + + pub(crate) fn main_document_has_committed_navigation(&self) -> bool { + self.current_main_owner_snapshot() + .and_then(|owner| self.documents.get(&owner.document_id)) + .is_some_and(|document| document.has_committed_navigation) + } + + pub(crate) fn complete_current_main_initial_empty_document(&mut self) -> bool { + let Some(owner) = self.current_main_document_task_owner() else { + return false; + }; + self.documents + .get_mut(&owner.document_id) + .filter(|document| moli_url::is_about_blank(&document.url)) + .is_some_and(|document| { + document + .lifecycle_progress + .complete_initial_empty_document() + }) + } + pub(crate) fn ensure_child_frame( &mut self, child_handle: DomHandle, @@ -2128,6 +2160,12 @@ impl FrameOwnerStore { }) } + pub(crate) fn current_main_document_unload_has_started(&self) -> bool { + self.current_main_document_task_owner() + .and_then(|owner| self.documents.get(&owner.document_id)) + .is_some_and(|document| document.lifecycle_progress.unload_has_started()) + } + pub(crate) fn begin_current_main_document_unload(&mut self) -> Option { let owner = self.current_main_document_task_owner()?; self.documents diff --git a/moli-renderer-v8/src/frame_owner_model/store_tests.rs b/moli-renderer-v8/src/frame_owner_model/store_tests.rs index 06ee6ae7f40..8d0e6e3d9ea 100644 --- a/moli-renderer-v8/src/frame_owner_model/store_tests.rs +++ b/moli-renderer-v8/src/frame_owner_model/store_tests.rs @@ -381,6 +381,53 @@ fn initial_main_document_commit_prepares_owners_before_replacement_without_turn_ ); } +#[test] +fn main_initial_document_stays_provisional_through_open_until_navigation_commits() { + let mut store = FrameOwnerStore::default(); + store.ensure_main_frame( + handle(1), + url("about:blank"), + url("https://creator.test/"), + "https://creator.test".to_owned(), + policy_container(), + policy_context(), + None, + ); + store.mark_main_document_initial_empty(); + assert!(!store.main_document_has_committed_navigation()); + assert!(store.complete_current_main_initial_empty_document()); + assert!(!store.complete_current_main_initial_empty_document()); + let initial = store.current_main_document_task_owner().unwrap(); + assert_eq!( + store.current_document_is_completely_loaded(initial.document_owner()), + Some(true) + ); + assert_eq!( + store.current_main_document_complete_transition_is_ready(initial), + Some(false) + ); + store + .replace_main_document( + handle(1), + url("https://creator.test/written"), + url("https://creator.test/written"), + ) + .unwrap(); + assert!(!store.main_document_has_committed_navigation()); + let transition = store + .prepare_initial_main_document_owner_transition() + .unwrap(); + store + .replace_initial_main_document( + transition, + handle(2), + url("https://creator.test/committed"), + url("https://creator.test/committed"), + ) + .unwrap(); + assert!(store.main_document_has_committed_navigation()); +} + #[test] fn main_document_replacement_rotates_document_owner_without_replacing_window_or_realm() { let mut store = FrameOwnerStore::default(); diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/lifecycle.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/lifecycle.rs index c4b9bd7f726..11d687350c8 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/lifecycle.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/lifecycle.rs @@ -1238,6 +1238,7 @@ impl PageScriptHost { host_ptr: *mut Self, document_handle: DomHandle, ) { + let _unload = unsafe { &*host_ptr }.enter_document_unload(document_handle); let handles = unsafe { &*host_ptr }.child_browsing_context_handles_in_document_order(); for handle in handles { if unsafe { &*host_ptr } diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/isolated_world.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/isolated_world.rs index 5989288d0c4..f7b5ca9de1f 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/isolated_world.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/isolated_world.rs @@ -151,7 +151,7 @@ impl PageScriptHost { self.retire_window_realm_resources(stale.runtime_observable_context_token); self.retire_window_execution_contexts_for_context_token( stale.runtime_observable_context_token, - config.resource_owner_id, + Some(config.resource_owner_id), ); if self.child_window_proxy_frame_is_current(handle, &stale.frame_id) { stale_context.detach_global(); diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs index 28de0fcc085..89c550b5996 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs @@ -1328,6 +1328,18 @@ impl PageScriptHost { &self, scope: &mut v8::PinScope<'s, '_>, ) -> Option> { + if self.auxiliary_window().is_some() + && let Some(environment) = self.page_script_environment() + { + // Named reuse changes the related Page's opener synchronously. + // Its script environment also records an explicitly disowned + // opener; an older endpoint must not restore that relationship. + let opener = environment.opener_in_scope(scope)?; + let host = opener + .get_creation_context(scope) + .and_then(crate::util::context_host_ptr_from_context_slot)?; + return (!unsafe { &*host }.browsing_context_is_closed()).then_some(opener); + } let (endpoint, opener) = self.top_window_opener.as_ref()?; let opener = v8::Local::new(scope, opener); self.window_opener_endpoint_is_live(scope, *endpoint, opener) @@ -1385,6 +1397,15 @@ impl PageScriptHost { } } + pub(crate) fn child_browsing_context_top_window_for_current_realm<'s>( + &self, + scope: &mut v8::PinScope<'s, '_>, + handle: DomHandle, + ) -> Option> { + self.child_window_proxy_records + .browsing_context_top(scope, handle) + } + pub(in crate::native_bridge::context_host) fn child_browsing_context_parent_window<'s>( &mut self, scope: &mut v8::PinScope<'s, '_>, diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/discovery.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/discovery.rs index 9b7029a8834..a9e3229090d 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/discovery.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/discovery.rs @@ -216,6 +216,13 @@ impl PageScriptHost { } pub(crate) fn child_browsing_context_host_is_active(&self, handle: DomHandle) -> bool { + if self + .dom_host() + .owner_document_handle(handle) + .is_none_or(|document| !self.document_has_browsing_context(document)) + { + return false; + } if self .dom_host() .owner_document_handle(handle) diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rs index 411a6d7fd61..95d3bd8cdb5 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/core.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs @@ -26,6 +26,7 @@ impl PageScriptHost { pub(crate) fn mark_main_document_initial_empty(&mut self) { assert!(moli_url::is_about_blank(self.document_url())); + self.frame_owner_store.mark_main_document_initial_empty(); self.initial_empty_main_document = true; } @@ -33,6 +34,16 @@ impl PageScriptHost { self.initial_empty_main_document } + pub(crate) fn main_document_has_committed_navigation(&self) -> bool { + self.frame_owner_store + .main_document_has_committed_navigation() + } + + pub(crate) fn complete_current_main_initial_empty_document(&mut self) -> bool { + self.frame_owner_store + .complete_current_main_initial_empty_document() + } + pub(crate) fn rebind_initial_main_document_senders( &mut self, resource: RendererResourceCompletionSender, @@ -58,14 +69,18 @@ impl PageScriptHost { &self, origin: &str, inherited_opaque_origin_matches: bool, - inherited_document_domain: Option<&str>, + inherited_origin: Option<&super::WindowAccessOrigin>, policy: &crate::document_runtime::DocumentPolicyContainer, ) -> crate::frame_owner_model::FrameDocumentLocalWindowTransition { - let same_origin = self.document_domain_override.get().as_deref() - == inherited_document_domain - && (inherited_opaque_origin_matches - || moli_url::WebOrigin::from_serialized(&self.main_document_security_origin()) - .same_origin(&moli_url::WebOrigin::from_serialized(origin))); + let same_origin = inherited_opaque_origin_matches + || if let Some(origin @ super::WindowAccessOrigin::Tuple { .. }) = inherited_origin { + self.main_window_access_origin() + .is_some_and(|current| current.can_access(origin)) + } else { + self.document_domain_override.get().is_none() + && moli_url::WebOrigin::from_serialized(&self.main_document_security_origin()) + .same_origin(&moli_url::WebOrigin::from_serialized(origin)) + }; crate::frame_owner_model::FrameDocumentLocalWindowTransition::for_document_commit( self.initial_empty_main_document, same_origin, @@ -181,11 +196,14 @@ impl PageScriptHost { pub(crate) fn request_auxiliary_window_close( &mut self, window: crate::runtime::RendererAuxiliaryWindow, - ) { + ) -> bool { if window.close() { self.append_live_turn_items(vec![crate::runtime::RendererOutputItem::OwnerAction( crate::runtime::RendererOwnerAction::CloseAuxiliaryWindow(window), )]); + true + } else { + false } } diff --git a/moli-renderer-v8/src/native_bridge/context_host/main_document_lifecycle.rs b/moli-renderer-v8/src/native_bridge/context_host/main_document_lifecycle.rs index 1d6707647e7..e342ceac2e4 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/main_document_lifecycle.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/main_document_lifecycle.rs @@ -22,6 +22,21 @@ impl PageScriptHost { pub(crate) fn dispatch_main_document_tree_beforeunload( &mut self, scope: &mut v8::PinScope<'_, '_>, + ) -> bool { + self.dispatch_main_document_tree_beforeunload_with_close(scope, false) + } + + pub(crate) fn dispatch_main_document_tree_beforeunload_for_close( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + ) -> bool { + self.dispatch_main_document_tree_beforeunload_with_close(scope, true) + } + + fn dispatch_main_document_tree_beforeunload_with_close( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + closing: bool, ) -> bool { let Some(owner) = self.current_main_document_task_owner() else { return false; @@ -31,9 +46,14 @@ impl PageScriptHost { }; let scope = &mut v8::ContextScope::new(scope, context); let window = context.global(scope); - if crate::context_bootstrap::navigation_unload_event_active(scope, window) { + if !closing && crate::context_bootstrap::navigation_unload_event_active(scope, window) { return false; } + let was_closed = self.browsing_context_is_closed(); + let is_current = |host: &Self| { + host.main_document_task_owner_is_current(owner) + && host.browsing_context_is_closed() == was_closed + }; let descendants = self.child_document_descendants_unload_snapshot(self.document_handle()); // Keep the navigation target protected while checking its descendants: // a descendant's beforeunload must not erase the target with open/write. @@ -43,11 +63,14 @@ impl PageScriptHost { let previous = crate::context_bootstrap::replace_navigation_unload_event_active(scope, window, true); crate::context_bootstrap::dispatch_beforeunload_for_runtime_owner(scope, window); - self.dispatch_child_documents_beforeunload(scope, descendants, None, |host| { - host.main_document_task_owner_is_current(owner) - }); + self.dispatch_child_documents_beforeunload(scope, descendants, None, is_current); crate::context_bootstrap::replace_navigation_unload_event_active(scope, window, previous); - self.main_document_task_owner_is_current(owner) + is_current(self) + } + + pub(crate) fn main_document_unload_has_started(&self) -> bool { + self.frame_owner_store + .current_main_document_unload_has_started() } pub(crate) fn dispatch_main_document_unload_for_navigation_commit( diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rs index da42c0a7970..4f5276b3306 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs @@ -1513,7 +1513,7 @@ impl PageScriptHost { output.close(); } self.root_document_lifecycle = None; - self.child_default_context_bootstrap = None; + self.window_default_context_bootstrap = None; self.command_turn_output = None; self.lightweight_popup_browsing_contexts.clear(); self.internal_inspector_value_references.clear(); diff --git a/moli-renderer-v8/src/native_bridge/context_host/navigation.rs b/moli-renderer-v8/src/native_bridge/context_host/navigation.rs index ad8f4b7aa39..9a719228c03 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/navigation.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/navigation.rs @@ -487,6 +487,24 @@ impl PageScriptHost { } } + pub(crate) fn cancel_pending_location_navigation(&mut self) { + self.clear_pending_location_navigation(); + // A request already handed to the browser no longer occupies the + // renderer's pending slot. Cancel through the same ordered owner + // channel, retaining the Document that authorized this action. + if let Some(source_document) = self + .root_document_lifecycle + .as_ref() + .map(RendererDocumentLifecycleJournalHandle::identity) + { + self.append_live_turn_owner_action( + crate::runtime::RendererOwnerAction::StopTopLevelLocationNavigation { + source_document, + }, + ); + } + } + pub(crate) fn record_pending_top_level_history_traversal(&mut self, delta: i64) { self.clear_pending_top_level_navigation(); let traversal = RendererPendingTopLevelHistoryTraversal { delta }; diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs index 78040025545..68b02106dbf 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs @@ -216,6 +216,10 @@ impl PendingLightweightPopupHistory { window: v8::Local<'s, v8::Object>, final_url: &Url, ) { + let Some(context) = window.get_creation_context(scope) else { + return; + }; + let scope = &mut v8::ContextScope::new(scope, context); let mut seed = match self.entry_seed() { Some(seed) => seed.clone(), None => { @@ -495,7 +499,7 @@ enum LightweightPopupLifecycle { } pub(super) struct LightweightPopupBrowsingContextRecord { - name: crate::runtime::RendererBrowsingContextName, + pub(in crate::native_bridge::context_host) name: crate::runtime::RendererBrowsingContextName, auxiliary_window: crate::runtime::RendererAuxiliaryWindow, name_lookup_allowed: bool, window_proxy: v8::Global, @@ -515,7 +519,7 @@ impl LightweightPopupBrowsingContextRecord { matches!(self.lifecycle, LightweightPopupLifecycle::Open(_)) } - fn is_open(&self) -> bool { + pub(in crate::native_bridge::context_host) fn is_open(&self) -> bool { self.is_live() && !self.is_closing && !self.auxiliary_window.is_closed() } } @@ -632,7 +636,7 @@ impl LightweightPopupStorageScope { } impl PageScriptHost { - fn lightweight_popup_record( + pub(in crate::native_bridge::context_host) fn lightweight_popup_record( &self, popup_id: u64, ) -> Option<&LightweightPopupBrowsingContextRecord> { @@ -932,7 +936,7 @@ impl PageScriptHost { }) } - fn popup_sandbox_policy_for_source( + pub(in crate::native_bridge::context_host) fn popup_sandbox_policy_for_source( &self, source_scope: OwnerDispatchScope, ) -> Option { @@ -2336,7 +2340,10 @@ impl PageScriptHost { &self, popup_id: u64, ) -> Option { - if !self.lightweight_popup_is_open(popup_id) { + if !self + .lightweight_popup_record(popup_id) + .is_some_and(|record| record.is_live()) + { return None; } self.lightweight_popup_document_record(popup_id) @@ -5956,60 +5963,6 @@ fn lightweight_popup_window_name_setter<'s>( } } -fn lightweight_popup_opener_getter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - let open = lightweight_popup_id_from_window(scope, args.this()) - .and_then(|id| { - context_host_ptr_from_global_bridge(scope) - .map(|host| unsafe { &*host }.lightweight_popup_is_open(id)) - }) - .unwrap_or(false); - if open - && let Some(opener) = get_private_value(scope, args.this(), LIGHTWEIGHT_POPUP_OPENER_SLOT) - { - rv.set(opener); - return; - } - rv.set_null(); -} - -fn lightweight_popup_opener_setter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - _rv: v8::ReturnValue<'_, v8::Value>, -) { - set_private_value( - scope, - args.this(), - LIGHTWEIGHT_POPUP_OPENER_SLOT, - args.get(0), - ); - if args.get(0).is_null() - && let Some(popup_id) = lightweight_popup_id_from_window(scope, args.this()) - && let Some(host) = context_host_ptr_from_global_bridge(scope) - && let Some(record) = unsafe { &mut *host }.lightweight_popup_record_mut(popup_id) - { - record.opener = None; - } -} - -fn lightweight_popup_closed_getter<'s>( - scope: &mut v8::PinScope<'s, '_>, - args: v8::FunctionCallbackArguments<'s>, - mut rv: v8::ReturnValue<'_, v8::Value>, -) { - let closed = lightweight_popup_id_from_window(scope, args.this()) - .and_then(|id| { - context_host_ptr_from_global_bridge(scope) - .and_then(|host| unsafe { &*host }.lightweight_popup_record(id)) - }) - .is_none_or(|record| !record.is_open()); - rv.set(v8::Boolean::new(scope, closed).into()); -} - fn lightweight_popup_window_opener_getter<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups/renderer_owned.rs b/moli-renderer-v8/src/native_bridge/context_host/popups/renderer_owned.rs index da0090c9fe4..626e0196ee8 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups/renderer_owned.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups/renderer_owned.rs @@ -13,10 +13,10 @@ pub(crate) struct OpenedRendererWindow<'s> { Option, } -impl OpenedRendererWindow<'_> { +impl<'s> OpenedRendererWindow<'s> { pub(crate) fn queue_javascript_navigation( &self, - scope: &mut v8::PinScope<'_, '_>, + scope: &mut v8::PinScope<'s, '_>, href: &str, ) -> bool { let Ok(url) = Url::parse(href) else { @@ -32,6 +32,28 @@ impl OpenedRendererWindow<'_> { unsafe { &mut *host }.record_pending_location_navigation(url, None); true } + + pub(crate) fn prepare_navigation_activation(&self, scope: &mut v8::PinScope<'s, '_>) -> bool { + if self + .window + .as_ref() + .is_some_and(|window| window.is_closed()) + || crate::context_bootstrap::navigation_unload_event_active(scope, self.window_proxy) + { + return false; + } + if self.pending_page.is_some() { + return true; + } + let Some(context) = self.window_proxy.get_creation_context(scope) else { + return false; + }; + let Some(host_ptr) = crate::util::context_host_ptr_from_context_slot(context) else { + return false; + }; + let scope = &mut v8::ContextScope::new(scope, context); + unsafe { &mut *host_ptr }.dispatch_main_document_tree_beforeunload(scope) + } } impl PageScriptHost { @@ -187,13 +209,29 @@ impl PageScriptHost { } else { about_blank_url() }; + policy.document_referrer = Url::parse(&policy.document_referrer) + .ok() + .and_then(|source| { + moli_fetch::referrer_value( + &source, + if exposes_opener { + &source + } else { + &initial_url + }, + None, + policy.referrer_policy.as_deref(), + ) + }) + .unwrap_or_default(); let base_url = if exposes_opener { lightweight_popup_initial_base_url(&initial_url, creator_base_url) } else { initial_url.clone() }; - let sandbox = creator_child_handle - .and_then(|handle| self.child_browsing_context_popup_opener_sandbox_policy(handle)); + let sandbox = creator_child_handle.and_then(|handle| { + self.popup_sandbox_policy_for_source(OwnerDispatchScope::Child(handle)) + }); if policy.sandbox.allows_popups_to_escape { policy.sandbox = DocumentSandboxPolicy::default(); } @@ -233,6 +271,19 @@ impl PageScriptHost { crate::runtime::RendererBrowsingContextName::default() }; name.set(trackable_lightweight_popup_window_name(target_name).unwrap_or_default()); + let about_document_state = self + .capture_about_document_state( + creator_child_handle.map_or(OwnerDispatchScope::Top, OwnerDispatchScope::Child), + &initial_url, + None, + ) + .map(|state| { + crate::runtime::RendererAboutDocumentState::new( + state.origin().clone(), + base_url.clone(), + policy.clone(), + ) + }); let env = crate::runtime::PageVmEnvConfig { window_identity: crate::runtime::RendererPageWindowIdentity::new( name.clone(), @@ -270,6 +321,8 @@ impl PageScriptHost { layout_configuration: Default::default(), wpt_extensions_enabled: false, navigation_bootstrap_entry: None, + navigation_history_source: None, + about_document_state, reserved_service_worker_client_id: None, }; let mut dom_host = crate::dom::native::DomHost::from_dom( diff --git a/moli-renderer-v8/src/native_bridge/context_host/runtime_observable.rs b/moli-renderer-v8/src/native_bridge/context_host/runtime_observable.rs index bc71f9d1d6a..9b603240791 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/runtime_observable.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/runtime_observable.rs @@ -165,14 +165,14 @@ impl PageScriptHost { .collect::>(); realm_tokens.sort_unstable(); realm_tokens.dedup(); + let resource_owner_id = self + .window_default_context_bootstrap + .as_ref() + .map(|config| config.resource_owner_id); for realm_token in realm_tokens { self.retire_window_realm_resources(realm_token); - let resource_owner_id = self - .child_default_context_bootstrap - .as_ref() - .map(|config| config.resource_owner_id); - self.retire_window_execution_context_registry(realm_token, resource_owner_id); + self.retire_window_execution_contexts_for_context_token(realm_token, resource_owner_id); } for owner in owners { @@ -511,14 +511,6 @@ impl PageScriptHost { } pub(crate) fn retire_window_execution_contexts_for_context_token( - &mut self, - context_token: RuntimeObservableContextToken, - resource_owner_id: crate::resource_owner::ResourceOwnerId, - ) -> usize { - self.retire_window_execution_context_registry(context_token, Some(resource_owner_id)) - } - - fn retire_window_execution_context_registry( &mut self, context_token: RuntimeObservableContextToken, resource_owner_id: Option, 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.rs index bdcdd881b19..1d9b20ef2ef 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 @@ -59,7 +59,7 @@ impl WindowEnvironmentSettings { scope.get_current_context().get_slot::() } - pub(crate) fn bind_current_main_document_for_retirement( + pub(crate) fn bind_current_main_document( scope: &mut v8::PinScope<'_, '_>, host: &PageScriptHost, ) -> Option<()> { diff --git a/moli-renderer-v8/src/native_bridge/element/activation/targets.rs b/moli-renderer-v8/src/native_bridge/element/activation/targets.rs index 5279795f209..a15d52408a3 100644 --- a/moli-renderer-v8/src/native_bridge/element/activation/targets.rs +++ b/moli-renderer-v8/src/native_bridge/element/activation/targets.rs @@ -265,12 +265,8 @@ fn navigate_element_popup_target( .or_else(|| creator.policy_container.referrer_policy.clone()) }, ); - creator.policy_container.document_referrer = if relations.suppress_opener { - navigation_initiator - .document_referrer(&url::Url::parse(resolved_url).expect("resolved hyperlink URL")) - } else { - navigation_initiator.outgoing_referrer() - }; + creator.policy_container.document_referrer = navigation_initiator + .document_referrer(&url::Url::parse(resolved_url).expect("resolved hyperlink URL")); let opener = (!relations.suppress_opener).then_some(creator.opener); let source_child_handle = match dispatch_scope { crate::native_bridge::OwnerDispatchScope::Child(handle) => Some(handle), @@ -301,6 +297,9 @@ fn navigate_element_popup_target( return false; } }; + if !opened.prepare_navigation_activation(scope) { + return true; + } let disposition = if opened.pending_page.is_some() || runtime.protocol_user_gesture_activation() || runtime.current_input_event().is_some() @@ -456,6 +455,14 @@ pub(in crate::native_bridge) fn choose_form_navigation_target( return None; } let relations = element_popup_relations(unsafe { &*runtime_ptr }, form, target_name); + if let Some(ExistingHyperlinkTarget::RelatedPage(window)) = + existing_hyperlink_target(scope, runtime_ptr, source, form, Some(target_name)) + && crate::context_bootstrap::navigation_unload_event_active(scope, window) + { + // A related Page being unloaded is still the named target. Do not + // fall through to creating a second legacy popup with the same name. + return None; + } let mut creator = element_popup_creator(scope, runtime_ptr, form)?; creator.policy_container.document_referrer = if relations.suppress_referrer { String::new() @@ -487,6 +494,7 @@ pub(in crate::native_bridge) fn choose_form_navigation_target( None, creator.base_url, creator.policy_container, + false, ), _ => runtime.open_lightweight_popup_window( scope, @@ -497,6 +505,7 @@ pub(in crate::native_bridge) fn choose_form_navigation_target( None, creator.base_url, creator.policy_container, + false, ), }?; if !opened.allows_navigation_activation(scope, runtime) { @@ -642,19 +651,26 @@ pub(crate) fn navigate_existing_browsing_context_target<'s>( if navigated { Some(target_window) } else { None } } +#[derive(Clone, Copy)] +enum ExistingHyperlinkTarget<'s> { + Local(crate::native_bridge::OwnerDispatchScope), + RelatedPage(v8::Local<'s, v8::Object>), +} + /// Resolve an existing target without reading script-visible WindowProxy properties. -fn existing_hyperlink_target( - scope: &mut v8::PinScope<'_, '_>, +fn existing_hyperlink_target<'s>( + scope: &mut v8::PinScope<'s, '_>, runtime_ptr: *mut PageScriptHost, source: crate::native_bridge::OwnerDispatchScope, + source_handle: DomHandle, target_name: Option<&str>, -) -> Option { +) -> Option> { use crate::native_bridge::OwnerDispatchScope; - let runtime = unsafe { &*runtime_ptr }; + let runtime = unsafe { &mut *runtime_ptr }; let Some(name) = target_name else { - return Some(source); + return Some(ExistingHyperlinkTarget::Local(source)); }; - match SpecialBrowsingContextTarget::parse(name) { + let local = match SpecialBrowsingContextTarget::parse(name) { Some(SpecialBrowsingContextTarget::Current) => Some(source), Some( special @ (SpecialBrowsingContextTarget::Top | SpecialBrowsingContextTarget::Parent), @@ -669,9 +685,23 @@ fn existing_hyperlink_target( Some(target) } Some(SpecialBrowsingContextTarget::Blank) => None, - None => unsafe { &mut *runtime_ptr } - .browsing_context_target_by_name_for_navigation(scope, name, source), + None => runtime.browsing_context_target_by_name_for_navigation(scope, name, source), + }; + if let Some(local) = local { + return Some(ExistingHyperlinkTarget::Local(local)); } + if SpecialBrowsingContextTarget::parse(name).is_some() + || element_popup_relations(runtime, source_handle, name).suppress_opener + { + return None; + } + let related = runtime + .page_script_environment()? + .named_related_window(name, runtime.browsing_context_name())?; + related + .window_proxy_in_scope(scope) + .ok() + .map(ExistingHyperlinkTarget::RelatedPage) } pub(in crate::native_bridge) fn navigate_element_target_browsing_context( @@ -690,7 +720,9 @@ pub(in crate::native_bridge) fn navigate_element_target_browsing_context( let Some(source) = unsafe { &*runtime_ptr }.owner_dispatch_scope_for_node(source_handle) else { return false; }; - let Some(target) = existing_hyperlink_target(scope, runtime_ptr, source, target_name) else { + let Some(target) = + existing_hyperlink_target(scope, runtime_ptr, source, source_handle, target_name) + else { return target_name.is_some_and(|name| { navigate_element_popup_target( scope, @@ -703,8 +735,10 @@ pub(in crate::native_bridge) fn navigate_element_target_browsing_context( }); }; let runtime = unsafe { &mut *runtime_ptr }; - if url::Url::parse(resolved_url) - .is_ok_and(|destination| runtime.blocks_ancestor_navigation(source, target, &destination)) + if let ExistingHyperlinkTarget::Local(target) = &target + && url::Url::parse(resolved_url).is_ok_and(|destination| { + runtime.blocks_ancestor_navigation(source, *target, &destination) + }) { return true; } @@ -712,29 +746,77 @@ pub(in crate::native_bridge) fn navigate_element_target_browsing_context( return false; }; let initiator_url = runtime.document_url_for_handle(document); - let Some(source_element) = crate::util::node_wrapper_from_handle(scope, source_handle) else { + let initiator = crate::runtime::RendererNavigationInitiator::new( + runtime + .document_referrer_source_url_for_dispatch_scope(source) + .unwrap_or(initiator_url), + runtime + .document_resource_loader_for_dispatch_scope(source) + .map(|loader| loader.fetch_context().request_origin()) + .unwrap_or(moli_url::WebOrigin::Opaque), + if element_popup_relations(runtime, source_handle, target_name.unwrap_or("_self")) + .suppress_referrer + { + Some("no-referrer".to_owned()) + } else { + element_popup_referrer_policy(runtime, source_handle) + .map(str::to_owned) + .or_else(|| { + runtime + .document_policy_container_for_inheritance(source) + .and_then(|policy| policy.referrer_policy) + }) + }, + ); + let Some(source_element) = + runtime + .native_bridge_mut() + .wrap_handle(scope, runtime_ptr, source_handle) + else { return false; }; // Resolve the native target realm before reading its private Location slot. // The source's access check controls event dispatch and sourceElement exposure. - let context = match target { - OwnerDispatchScope::Child(handle) => runtime - .ensure_prebootstrapped_child_default_context(scope, handle) + let context = match &target { + ExistingHyperlinkTarget::Local(OwnerDispatchScope::Child(handle)) => runtime + .ensure_prebootstrapped_child_default_context(scope, *handle) .ok(), - _ => runtime - .current_registered_window_execution_context_identity(target) - .and_then(|identity| runtime.window_execution_context(scope, identity.owner(), target)) + ExistingHyperlinkTarget::Local(OwnerDispatchScope::LightweightPopup(id)) => runtime + .lightweight_popup_window(scope, *id) + .and_then(|window| window.get_creation_context(scope)), + ExistingHyperlinkTarget::Local(target) => runtime + .current_registered_window_execution_context_identity(*target) + .and_then(|identity| runtime.window_execution_context(scope, identity.owner(), *target)) .map(|(_, context)| context), + ExistingHyperlinkTarget::RelatedPage(window) => window.get_creation_context(scope), }; let Some(context) = context else { return false }; + let native_popup_context = matches!(target, ExistingHyperlinkTarget::RelatedPage(_)) + || matches!(target, ExistingHyperlinkTarget::Local(OwnerDispatchScope::LightweightPopup(id)) + if runtime.lightweight_popup_window(scope, id) + .is_some_and(|window| window.strict_equals(context.global(scope).into()))); let can_access = runtime .current_registered_window_execution_context_identity(source) .is_some_and(|identity| { - runtime.window_execution_context_can_access_dispatch_scope(identity, target) + if native_popup_context { + runtime + .window_execution_context(scope, identity.owner(), source) + .is_some_and(|(_, source_context)| { + crate::native_bridge::window_contexts_allow_access(source_context, context) + }) + } else { + let ExistingHyperlinkTarget::Local(target) = target else { + unreachable!("related Pages use native context access checks") + }; + runtime.window_execution_context_can_access_dispatch_scope(identity, target) + } }); let scope = &mut v8::ContextScope::new(scope, context); - let window = match target { - OwnerDispatchScope::LightweightPopup(id) => runtime.lightweight_popup_window(scope, id), + let window = match &target { + ExistingHyperlinkTarget::Local(OwnerDispatchScope::LightweightPopup(id)) => { + runtime.lightweight_popup_window(scope, *id) + } + ExistingHyperlinkTarget::RelatedPage(window) => Some(*window), _ => Some(context.global(scope)), }; let Some(location) = window @@ -751,11 +833,13 @@ pub(in crate::native_bridge) fn navigate_element_target_browsing_context( source_document: document, user_initiated, source_can_access_target: can_access, - initiator_url, + initiator, named_popup: target_name .filter(|name| { - matches!(target, OwnerDispatchScope::LightweightPopup(_)) - && SpecialBrowsingContextTarget::parse(name).is_none() + matches!( + target, + ExistingHyperlinkTarget::Local(OwnerDispatchScope::LightweightPopup(_)) + ) && SpecialBrowsingContextTarget::parse(name).is_none() }) .map(|name| NamedHyperlinkPopup { source_handle, diff --git a/moli-renderer-v8/src/native_bridge/identity.rs b/moli-renderer-v8/src/native_bridge/identity.rs index 706378278e8..939da88fc40 100644 --- a/moli-renderer-v8/src/native_bridge/identity.rs +++ b/moli-renderer-v8/src/native_bridge/identity.rs @@ -453,13 +453,19 @@ pub(crate) fn contexts_share_wrapper_world( crate::native_bridge::isolated_window_world_for_context(right), ) { (Some(left), Some(right)) => left == right, - (None, None) => match ( - left.get_slot::>(), - right.get_slot::>(), - ) { - (Some(left), Some(right)) => Rc::ptr_eq(&left, &right), - _ => false, - }, + (None, None) => { + // Default-world related Pages share JS wrapper identity while each + // native host owns its own reflector IDs and canonical cache. + (left.get_slot::().is_some() + && right.get_slot::().is_some()) + || match ( + left.get_slot::>(), + right.get_slot::>(), + ) { + (Some(left), Some(right)) => Rc::ptr_eq(&left, &right), + _ => false, + } + } _ => false, } } @@ -592,16 +598,40 @@ pub(crate) fn clear_context_wrapper_cache_for_teardown( .map(|token| token.as_u64()); if let Some(cache) = context.get_slot::>() { let mut entries = cache.borrow_mut(); - for entry in entries.wrappers.values_mut() { - if all_entries || entry.creation_realm.map(NonZeroU64::get) == realm { - entry.wrapper.retain_in_realm(scope); + entries + .retired_wrappers + .retain(|_, wrapper| !wrapper.is_empty()); + entries + .retired_live_collection_wrappers + .retain(|_, wrapper| !wrapper.is_empty()); + // A retained realm must preserve wrappers that JS still reaches without + // making every detached node reachable through the realm itself. + let mut retired = Vec::new(); + entries.wrappers.retain(|id, entry| { + if !all_entries && entry.creation_realm.map(NonZeroU64::get) != realm { + return true; } - } - for entry in entries.live_collection_wrappers.values_mut() { - if all_entries || entry.creation_realm.map(NonZeroU64::get) == realm { - entry.wrapper.retain_in_realm(scope); + if let Some(wrapper) = entry.wrapper.to_local(scope) { + retired.push((id, v8::Weak::new(scope, wrapper))); } - } + false + }); + entries.retired_wrappers.extend(retired); + let mut retired_collections = Vec::new(); + entries + .live_collection_wrappers + .retain(|descriptor, entry| { + if !all_entries && entry.creation_realm.map(NonZeroU64::get) != realm { + return true; + } + if let Some(wrapper) = entry.wrapper.to_local(scope) { + retired_collections.push((descriptor.clone(), v8::Weak::new(scope, wrapper))); + } + false + }); + entries + .retired_live_collection_wrappers + .extend(retired_collections); drop(entries); crate::util::retain_context_v8_handle_state_for_safe_release(context, cache); } @@ -629,6 +659,23 @@ pub(super) struct BridgeIdentityStore { } impl BridgeIdentityStore { + fn current_wrapper_cache( + &self, + scope: &mut v8::PinScope<'_, '_>, + ) -> Rc> { + let context = scope.get_current_context(); + if crate::native_bridge::isolated_window_world_for_context(context).is_none() + && context.get_slot::().is_some() + { + // Reflector IDs are local to this native host. A cross-Page call + // in the same default world must use this store's canonical cache, + // not the calling Page's cache with potentially colliding IDs. + self.default_world_wrapper_cache.clone() + } else { + context_wrapper_cache(scope) + } + } + pub(super) fn install_default_world_wrapper_cache(&self, context: v8::Local<'_, v8::Context>) { let _ = context.set_slot(self.default_world_wrapper_cache.clone()); let _ = context.set_slot(Rc::new(SharedWorldWrapperCache)); @@ -707,13 +754,13 @@ impl BridgeIdentityStore { if matches!(self.bridge_handle(reflector_id), Some(BridgeHandle::Window)) { return context_window_wrapper(scope); } - context_wrapper_cache(scope) + self.current_wrapper_cache(scope) .borrow() .wrappers .get(&reflector_id) .and_then(|entry| entry.wrapper.to_local(scope)) .or_else(|| { - context_wrapper_cache(scope) + self.current_wrapper_cache(scope) .borrow() .retired_wrappers .get(&reflector_id) @@ -731,7 +778,7 @@ impl BridgeIdentityStore { set_context_window_wrapper(scope, wrapper); return; } - let cache = context_wrapper_cache(scope); + let cache = self.current_wrapper_cache(scope); let mut cache = cache.borrow_mut(); if scope .get_current_context() @@ -764,13 +811,13 @@ impl BridgeIdentityStore { scope: &mut v8::PinScope<'s, '_>, descriptor: &LiveCollectionDescriptor, ) -> Option> { - context_wrapper_cache(scope) + self.current_wrapper_cache(scope) .borrow() .live_collection_wrappers .get(descriptor) .and_then(|entry| entry.wrapper.to_local(scope)) .or_else(|| { - context_wrapper_cache(scope) + self.current_wrapper_cache(scope) .borrow() .retired_live_collection_wrappers .get(descriptor) @@ -784,7 +831,7 @@ impl BridgeIdentityStore { descriptor: LiveCollectionDescriptor, wrapper: v8::Local<'_, v8::Object>, ) { - let cache = context_wrapper_cache(scope); + let cache = self.current_wrapper_cache(scope); let mut cache = cache.borrow_mut(); if scope .get_current_context() diff --git a/moli-renderer-v8/src/native_bridge/identity/dense_reflector_map.rs b/moli-renderer-v8/src/native_bridge/identity/dense_reflector_map.rs index ad867a9b03b..32973600da2 100644 --- a/moli-renderer-v8/src/native_bridge/identity/dense_reflector_map.rs +++ b/moli-renderer-v8/src/native_bridge/identity/dense_reflector_map.rs @@ -113,13 +113,6 @@ impl DenseReflectorMap { pub(super) fn values(&self) -> impl Iterator { self.dense.iter().flatten().chain(self.sparse.values()) } - - pub(super) fn values_mut(&mut self) -> impl Iterator { - self.dense - .iter_mut() - .flatten() - .chain(self.sparse.values_mut()) - } } #[cfg(test)] diff --git a/moli-renderer-v8/src/runtime/owner_local_store/entry.rs b/moli-renderer-v8/src/runtime/owner_local_store/entry.rs index 3cb85e4740c..ea235f6b619 100644 --- a/moli-renderer-v8/src/runtime/owner_local_store/entry.rs +++ b/moli-renderer-v8/src/runtime/owner_local_store/entry.rs @@ -342,6 +342,12 @@ impl LivePageEntry { dispatch: RendererTopLevelNavigationDispatch, ) { self.top_level_navigation_dispatch = dispatch; + if let Some(environment) = self + .active_page_vm() + .and_then(PageVm::renderer_page_script_environment) + { + environment.set_top_level_navigation_dispatch(dispatch); + } } pub(in crate::runtime) fn top_level_navigation_dispatch( diff --git a/moli-renderer-v8/src/runtime/page_vm/auxiliary_page.rs b/moli-renderer-v8/src/runtime/page_vm/auxiliary_page.rs index eb9826f98dd..ff813a67683 100644 --- a/moli-renderer-v8/src/runtime/page_vm/auxiliary_page.rs +++ b/moli-renderer-v8/src/runtime/page_vm/auxiliary_page.rs @@ -66,7 +66,10 @@ impl PageVm { ); vm.install_page_task_capabilities(capabilities); vm.set_root_document_lifecycle(lifecycle.clone()); - vm.set_document_ready_state(crate::dom::native::DocumentReadyState::Complete)?; + // This Document completed synchronously before window.open returned. + // Complete the native lifecycle too, so parser scheduling cannot emit + // a second load that observers mistake for the requested navigation. + vm.complete_related_initial_empty_document()?; for milestone in [ RendererDocumentLifecycleMilestone::DomContentLoaded, RendererDocumentLifecycleMilestone::Load, diff --git a/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs b/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs index 093db8097d8..0d2f4a0f7ba 100644 --- a/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs +++ b/moli-renderer-v8/src/runtime/page_vm/followed_navigation.rs @@ -1135,20 +1135,26 @@ impl PageVm { pub(in crate::runtime) fn validate_prepared_document_response( &mut self, - request: crate::runtime::owner::RendererCreateStreamingRawPageRequest, + mut request: crate::runtime::owner::RendererCreateStreamingRawPageRequest, mut bootstrap: crate::script_vm::RendererDocumentIsolateBootstrap, reservation: crate::runtime::owner_local_store::RendererDocumentIsolateReservation, ) -> Result { request.validate_bootstrap_configuration()?; - let navigation_bootstrap_entry = match request + // Browser requests retain the destination identity while resolving the + // latest source state at commit. A session-history position alone is + // only a fallback for requests without that explicit history handle. + let navigation_bootstrap_entry = if let Some(history) = request.navigation_history.as_ref() + { + Some(history.resolve(&request.final_url)?) + } else if let Some(position) = request .main_document_commit .as_ref() .and_then(|commit| commit.session_history_position) { - Some(position) => self - .vm_mut() - .capture_inherited_history_for_browser_commit(&request.final_url, position)?, - None => None, + self.vm_mut() + .capture_inherited_history_for_browser_commit(&request.final_url, position)? + } else { + None }; if moli_url::is_about_blank(&request.final_url) && let Some(replacement) = request.document_replacement.as_ref() @@ -1169,6 +1175,14 @@ impl PageVm { ); } } + if let Some(state) = bootstrap + .initial_document_environment + .as_ref() + .and_then(|environment| environment.about_document_state.clone()) + && let Some(history) = request.navigation_history.take() + { + request.navigation_history = Some(history.with_about_document_state(Some(state))); + } ensure!( request.lifecycle_decider.is_none(), "a Page replacement cannot use a Page-creation lifecycle decider" diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rs index 3bc54038f80..dc8d27927e7 100644 --- a/moli-renderer-v8/src/runtime/page_vm/mod.rs +++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs @@ -1957,6 +1957,12 @@ impl PageVm { let Some(vm) = self.vm.as_mut() else { return; }; + // A native auxiliary Window is closed on the protocol owner's task. + // Settle its Navigation API while the exact realm and callbacks remain + // registered, before clearing the context's resources. + if let Err(error) = vm.cancel_closed_main_window_navigation() { + tracing::warn!(%error, "failed to cancel closed Window navigation before retirement"); + } vm.detach_default_inspector_context_for_context_teardown(); vm.close_page_context_resources_for_context_teardown(); } diff --git a/moli-renderer-v8/src/runtime/protocol_output/item.rs b/moli-renderer-v8/src/runtime/protocol_output/item.rs index ec9d5fb47ec..02a7cb5b098 100644 --- a/moli-renderer-v8/src/runtime/protocol_output/item.rs +++ b/moli-renderer-v8/src/runtime/protocol_output/item.rs @@ -75,6 +75,9 @@ pub enum RendererOwnerAction { update: moli_page_types::SessionHistoryUpdate, }, TopLevelLocationNavigation(RendererDocumentSourcedTopLevelLocationNavigation), + StopTopLevelLocationNavigation { + source_document: RendererDocumentLifecycleIdentity, + }, TopLevelHistoryTraversal(RendererPendingTopLevelHistoryTraversal), SubresourceFetchPause { network_pause: Option, diff --git a/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs b/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs index 9e4c014a454..b33d9b373a7 100644 --- a/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs +++ b/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs @@ -321,7 +321,8 @@ fn owner_action_transport_charge_bytes(action: &RendererOwnerAction) -> usize { .unwrap_or_default(), ) .saturating_add(headers_charge(event.request_headers())), - RendererOwnerAction::TopLevelHistoryTraversal(_) => 0, + RendererOwnerAction::TopLevelHistoryTraversal(_) + | RendererOwnerAction::StopTopLevelLocationNavigation { .. } => 0, RendererOwnerAction::SubresourceFetchPause { info, child_document, diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs index cbeca76b81a..775bb026f92 100644 --- a/moli-renderer-v8/src/script_vm.rs +++ b/moli-renderer-v8/src/script_vm.rs @@ -2001,6 +2001,7 @@ pub(crate) struct ScriptVmInitialDocumentEnvironment { pub(crate) policy_container: crate::document_runtime::DocumentPolicyContainer, fallback_base_url: Option, storage_key: Option, + pub(crate) about_document_state: Option, } pub(crate) use document_environment::ScriptVmCapturedDocumentEnvironment; @@ -2036,6 +2037,9 @@ impl ScriptVmPageRealmBootstrap { .initial_document_environment .take() }); + let about_document_state = initial_environment + .as_ref() + .and_then(|environment| environment.about_document_state.clone()); let document_handle = dom_host.document_handle(); if let Some(base) = initial_environment .as_ref() @@ -2187,6 +2191,9 @@ impl ScriptVmPageRealmBootstrap { .bind_deferred_context_host_release_queue( renderer_document_isolate.deferred_context_host_release_queue(), ); + context_host + .borrow_mut() + .set_main_about_document_state(about_document_state); if root_frame_id.is_some() && let Some(group) = browsing_context_group { @@ -2410,10 +2417,39 @@ impl ScriptVmDefaultWorldBootstrap { >, about_document_state: Option, ) -> std::result::Result { + let about_document_state = renderer_document_isolate_bootstrap + .initial_document_environment + .as_ref() + .and_then(|environment| environment.about_document_state.clone()) + .or(about_document_state); let top_level_storage_key = about_document_state .as_ref() .and_then(crate::runtime::RendererAboutDocumentState::storage_key) .or(top_level_storage_key); + let initial_environment = if renderer_document_isolate_bootstrap + .initial_document_environment + .is_none() + { + about_document_state + .as_ref() + .map(|state| ScriptVmInitialDocumentEnvironment { + security_token: None, + opaque_origin: None, + document_domain_override: match state.origin() { + crate::native_bridge::WindowAccessOrigin::Tuple { + document_domain, .. + } => document_domain.clone(), + crate::native_bridge::WindowAccessOrigin::Opaque { .. } => None, + }, + origin: state.origin().serialized_origin(), + policy_container: state.policy_container().clone(), + fallback_base_url: Some(state.base_url().clone()), + storage_key: state.storage_key(), + about_document_state: Some(state.clone()), + }) + } else { + None + }; let mut bootstrap = ScriptVmPageRealmBootstrap::new_from_dom_host( bootstrap_dom_host, document_settings, @@ -2431,7 +2467,7 @@ impl ScriptVmDefaultWorldBootstrap { main_document_commit, top_level_storage_key, reserved_service_worker_client_id, - None, + initial_environment, )?; if let Some(state) = &about_document_state { bootstrap diff --git a/moli-renderer-v8/src/script_vm/document_environment.rs b/moli-renderer-v8/src/script_vm/document_environment.rs index e4e01c1389f..72a905e160f 100644 --- a/moli-renderer-v8/src/script_vm/document_environment.rs +++ b/moli-renderer-v8/src/script_vm/document_environment.rs @@ -98,6 +98,23 @@ impl ScriptVmInitialDocumentEnvironment { host.window_message_source_security(dispatch)? .opaque_origin() }); + let about_document_state = crate::util::context_host_ptr_from_context_slot(context) + .and_then(|host| { + let host = unsafe { &*host }; + let owner = host.window_dispatch_scope_for_context(scope, context)?; + host.capture_about_document_state( + owner, + &Url::parse("about:blank").expect("valid about:blank URL"), + None, + ) + }) + .map(|state| { + crate::runtime::RendererAboutDocumentState::new( + state.origin().clone(), + base_url.clone(), + policy_container.clone(), + ) + }); Ok(Self { security_token, opaque_origin, @@ -106,6 +123,7 @@ impl ScriptVmInitialDocumentEnvironment { policy_container, fallback_base_url: Some(base_url), storage_key: Some(storage_key), + about_document_state, }) } } @@ -434,22 +452,46 @@ impl ScriptVm { Some(host.document_base_url_for_handle(host.document_handle())) }; let mut policy_container = host.document_policy_container().clone(); - let source = if preserve_navigation_referrer { - url::Url::parse(&policy_container.document_referrer).ok() - } else { - Some(host.document_url().clone()) - }; - policy_container.document_referrer = source - .as_ref() - .and_then(|source| { - moli_fetch::referrer_value( - source, - host.document_url(), - None, - policy_container.referrer_policy.as_deref(), - ) - }) + if preserve_navigation_referrer && host.main_document_is_initial_empty() { + // The synchronous initial Document may expose the creator's + // full URL. A browser reload reapplies the navigation policy + // to that retained source for its actual about:blank target. + policy_container.document_referrer = + Url::parse(&policy_container.document_referrer) + .ok() + .and_then(|source| { + moli_fetch::referrer_value( + &source, + host.document_url(), + None, + policy_container.referrer_policy.as_deref(), + ) + }) + .unwrap_or_default(); + } else if !preserve_navigation_referrer { + policy_container.document_referrer = moli_fetch::referrer_value( + host.document_url(), + host.document_url(), + None, + policy_container.referrer_policy.as_deref(), + ) .unwrap_or_default(); + } + let about_document_state = host + .capture_about_document_state( + crate::native_bridge::OwnerDispatchScope::Top, + &Url::parse("about:blank").expect("valid about:blank URL"), + None, + ) + .map(|state| { + crate::runtime::RendererAboutDocumentState::new( + state.origin().clone(), + fallback_base_url + .clone() + .unwrap_or_else(|| host.document_url().clone()), + policy_container.clone(), + ) + }); ScriptVmInitialDocumentEnvironment { security_token, opaque_origin: host @@ -460,6 +502,7 @@ impl ScriptVm { policy_container, fallback_base_url, storage_key: Some(host.top_web_storage_scope().storage_key().clone()), + about_document_state, } }; let environment = self.with_current_main_world_scope(|scope, host_ptr| { diff --git a/moli-renderer-v8/src/script_vm/document_isolate.rs b/moli-renderer-v8/src/script_vm/document_isolate.rs index 347e4256075..78bfc57165e 100644 --- a/moli-renderer-v8/src/script_vm/document_isolate.rs +++ b/moli-renderer-v8/src/script_vm/document_isolate.rs @@ -290,6 +290,7 @@ struct RendererPageScriptEnvironmentInner { window_identity: crate::runtime::RendererPageWindowIdentity, opener: RefCell>>, document_host: RefCell>>, + top_level_navigation_dispatch: Cell, closed: Cell, } @@ -372,6 +373,9 @@ impl RendererPageScriptEnvironment { window_identity, opener: RefCell::new(None), document_host: RefCell::new(Weak::new()), + top_level_navigation_dispatch: Cell::new( + crate::RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter, + ), closed: Cell::new(false), }), }; @@ -392,6 +396,19 @@ impl RendererPageScriptEnvironment { *self.inner.document_host.borrow_mut() = Rc::downgrade(host); } + pub(crate) fn set_top_level_navigation_dispatch( + &self, + dispatch: crate::RendererTopLevelNavigationDispatch, + ) { + self.inner.top_level_navigation_dispatch.set(dispatch); + } + + pub(crate) fn top_level_navigation_dispatch( + &self, + ) -> crate::RendererTopLevelNavigationDispatch { + self.inner.top_level_navigation_dispatch.get() + } + pub(crate) fn enqueue_related_page_turn_completion(&self) { let host = self.inner.document_host.borrow().clone(); self.inner diff --git a/moli-renderer-v8/src/script_vm/execution_contexts.rs b/moli-renderer-v8/src/script_vm/execution_contexts.rs index 60e31c1a62e..b9fe9e09b39 100644 --- a/moli-renderer-v8/src/script_vm/execution_contexts.rs +++ b/moli-renderer-v8/src/script_vm/execution_contexts.rs @@ -514,7 +514,7 @@ impl ScriptVm { host.retire_window_realm_resources(context.runtime_observable_context_token); host.retire_window_execution_contexts_for_context_token( context.runtime_observable_context_token, - self.resource_owner_id, + Some(self.resource_owner_id), ); host.child_window_proxy_frame_is_current(child_handle, &context.frame_id) }; @@ -552,7 +552,7 @@ impl ScriptVm { host.retire_window_realm_resources(context.runtime_observable_context_token); host.retire_window_execution_contexts_for_context_token( context.runtime_observable_context_token, - self.resource_owner_id, + Some(self.resource_owner_id), ); } assert!( diff --git a/moli-renderer-v8/src/script_vm/initial_window_document.rs b/moli-renderer-v8/src/script_vm/initial_window_document.rs index 55722a909df..e3daadaffd9 100644 --- a/moli-renderer-v8/src/script_vm/initial_window_document.rs +++ b/moli-renderer-v8/src/script_vm/initial_window_document.rs @@ -31,17 +31,23 @@ impl ScriptVm { } else { false }; - let inherited_domain = - inherited.map(|environment| environment.document_domain_override.get()); + let inherited_origin = inherited.and_then(|environment| { + let mut origin = environment.about_document_state.as_ref()?.origin().clone(); + if let crate::native_bridge::WindowAccessOrigin::Tuple { + document_domain, .. + } = &mut origin + { + *document_domain = environment.document_domain_override.get(); + } + Some(origin) + }); Ok(self ._context_host .borrow() .main_document_local_window_transition_for_commit( origin, inherited_opaque_origin_matches, - inherited_domain - .as_ref() - .and_then(|domain| domain.as_deref()), + inherited_origin.as_ref(), policy, )) } @@ -128,6 +134,12 @@ impl ScriptVm { environment.document_domain_override.clone(), ); } + host.set_main_about_document_state( + inherited + .as_ref() + .and_then(|environment| environment.about_document_state.clone()) + .or_else(|| env.about_document_state.clone()), + ); host.rebind_initial_main_document_senders( resource_completion, page_task_tx.top_level_navigation_handoff_sender(), @@ -169,19 +181,27 @@ impl ScriptVm { let scope = &mut scope.init(); let context = v8::Local::new(scope, context); let scope = &mut v8::ContextScope::new(scope, context); - crate::context_bootstrap::sync_global_location_runtime_state( - scope, - document_url.as_str(), - ); - let global = context.global(scope); - if let Some(document) = global - .get(scope, crate::util::v8str(scope, "document").into()) - .and_then(|value| v8::Local::::try_from(value).ok()) + let window = context.global(scope); { - crate::context_bootstrap::sync_document_location_runtime_state_from_window( - scope, document, global, + let mut host = vm._context_host.borrow_mut(); + crate::native_bridge::WindowEnvironmentSettings::bind_current_main_document(scope, &host) + .ok_or_else(|| anyhow!("retained Window has no current Document settings"))?; + let host_ptr = &mut *host as *mut PageScriptHost; + let document = host.native_bridge_mut() + .wrap_handle(scope, host_ptr, document_handle) + .ok_or_else(|| anyhow!("retained Window Document could not be wrapped"))?; + crate::util::set_private_value( + scope, + window, + crate::context_bootstrap::WINDOW_DOCUMENT_SLOT, + document.into(), ); } + crate::context_bootstrap::reset_window_location_history_navigation_runtime_state( + scope, + window, + document_url.as_str(), + )?; Ok(()) })?; Ok(()) diff --git a/moli-renderer-v8/src/script_vm/popup_close.rs b/moli-renderer-v8/src/script_vm/popup_close.rs index 8fc4abc753f..320959acd06 100644 --- a/moli-renderer-v8/src/script_vm/popup_close.rs +++ b/moli-renderer-v8/src/script_vm/popup_close.rs @@ -11,6 +11,28 @@ use crate::{ }; impl ScriptVm { + pub(crate) fn cancel_closed_main_window_navigation(&mut self) -> Result<()> { + if !self._context_host.borrow().browsing_context_is_closed() { + return Ok(()); + } + self.with_default_context_scope(|scope, host_ptr| { + let window = scope.get_current_context().global(scope); + // Closing from pagehide/unload must not settle the outgoing + // Document's Navigation API promises after its unload has begun. + if !unsafe { &*host_ptr }.main_document_unload_has_started() { + inform_about_canceled_navigation_for_window( + scope, + window, + NavigationCancellationReason::WindowClose, + ); + } + crate::native_bridge::PageScriptHost::dispatch_main_document_unload_for_navigation_commit( + scope, host_ptr, + ); + Ok(()) + }) + } + pub(crate) fn current_popup_close_owner( &self, popup_id: u64, diff --git a/moli-renderer-v8/src/script_vm/post_parse.rs b/moli-renderer-v8/src/script_vm/post_parse.rs index db28bd1ffed..aad2fa83e16 100644 --- a/moli-renderer-v8/src/script_vm/post_parse.rs +++ b/moli-renderer-v8/src/script_vm/post_parse.rs @@ -661,7 +661,8 @@ impl PendingWindowRealmBootstrapRegistration { realm_token: crate::native_bridge::RuntimeObservableContextToken, resource_owner_id: ResourceOwnerId, ) -> Result> { - let Some((owner, dispatch_scope, access_policy)) = mode.registration() else { + let Some((owner, dispatch_scope, access_policy)) = mode.registration(unsafe { &*host }) + else { return Ok(None); }; if !unsafe { &mut *host }.register_window_execution_context_realm( @@ -690,7 +691,7 @@ impl Drop for PendingWindowRealmBootstrapRegistration { if !self.committed { unsafe { &mut *self.host }.retire_window_execution_contexts_for_context_token( self.realm_token, - self.resource_owner_id, + Some(self.resource_owner_id), ); } } @@ -699,13 +700,20 @@ impl Drop for PendingWindowRealmBootstrapRegistration { impl WindowContextBootstrapMode { fn registration( self, + host: &PageScriptHost, ) -> Option<( crate::native_bridge::WindowExecutionContextOwner, crate::native_bridge::OwnerDispatchScope, crate::native_bridge::WindowExecutionContextAccessPolicy, )> { match self { - Self::MainDefault => None, + Self::MainDefault => Some(( + host.current_window_execution_context_owner( + crate::native_bridge::OwnerDispatchScope::Top, + )?, + crate::native_bridge::OwnerDispatchScope::Top, + crate::native_bridge::WindowExecutionContextAccessPolicy::EnforceWebOrigin, + )), Self::PopupDefault { popup_id, local_window_id, diff --git a/moli-renderer-v8/src/script_vm/related_page.rs b/moli-renderer-v8/src/script_vm/related_page.rs index 2555038accb..c2cdaeabc01 100644 --- a/moli-renderer-v8/src/script_vm/related_page.rs +++ b/moli-renderer-v8/src/script_vm/related_page.rs @@ -1,5 +1,18 @@ use super::*; +impl ScriptVm { + pub(crate) fn complete_related_initial_empty_document(&mut self) -> Result<()> { + anyhow::ensure!( + self._context_host + .borrow_mut() + .complete_current_main_initial_empty_document(), + "related initial Document rejected synchronous completion" + ); + self.document_runtime.note_dom_content_loaded_dispatched(); + self.set_document_ready_state(crate::dom::native::DocumentReadyState::Complete) + } +} + impl ScriptVmDefaultWorldBootstrap { #[allow(clippy::too_many_arguments)] pub(crate) fn related_page_in_scope( @@ -48,6 +61,7 @@ impl ScriptVmDefaultWorldBootstrap { storage_key: None, origin: inherited_origin.clone(), policy_container: env.document_policy_container.clone(), + about_document_state: env.about_document_state.clone(), }), )?; // Noopener blank pages commit a navigation; only pages exposing an @@ -116,6 +130,7 @@ impl ScriptVmPageRealmBootstrap { root_frame_id, context_host, prebootstrapped_child_default_contexts, + popup_default_contexts, page_context_cancel_tx, post_domcontentloaded_page_task_tx, page_runtime_wake_tx, @@ -208,6 +223,7 @@ impl ScriptVmPageRealmBootstrap { root_frame_id, context_host, prebootstrapped_child_default_contexts, + popup_default_contexts, page_context_cancel_tx, post_domcontentloaded_page_task_tx, page_runtime_wake_tx, diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/window_open_empty_url.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/window_open_empty_url.rs index 426463f4f7c..504531b9a42 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/window_open_empty_url.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/window_open_empty_url.rs @@ -132,7 +132,14 @@ setTimeout(() => { "#, ) .unwrap(); - assert!(vm.take_pending_popup_activations().is_empty(), "{kind}"); + // Named reuse may publish a focus/activation record. Its browser + // handoff must explicitly prohibit navigation and another load. + assert!( + vm.take_pending_popup_activations() + .iter() + .all(|activation| !activation.navigation_requested()), + "{kind}" + ); advance_page_task_executor_until_eval_equals( &mut vm, &loader, diff --git a/moli-renderer-v8/src/script_vm/tests/extracted/realms_and_teardown.rs b/moli-renderer-v8/src/script_vm/tests/extracted/realms_and_teardown.rs index 4de0890b23e..be087d0df2c 100644 --- a/moli-renderer-v8/src/script_vm/tests/extracted/realms_and_teardown.rs +++ b/moli-renderer-v8/src/script_vm/tests/extracted/realms_and_teardown.rs @@ -3555,7 +3555,9 @@ async fn borrowed_cross_origin_window_accessors_follow_the_receiver() { } catch (error) { plain = error instanceof TypeError ? "type-error" : String(error && error.name); } - setLocation.call(window, "#pr957-receiver"); + // A relative fragment on srcdoc resolves against the inherited API base URL. + // Use its explicit URL to isolate which Window the borrowed setter navigates. + setLocation.call(window, "about:srcdoc#pr957-receiver"); return JSON.stringify({ plain, normalParentIsSelf: w.parent === w, diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs index d98c98ef7d4..0589c05280f 100644 --- a/moli-renderer-v8/src/script_vm/tests/mod.rs +++ b/moli-renderer-v8/src/script_vm/tests/mod.rs @@ -2340,7 +2340,6 @@ mod svg_length_list_native_receivers; mod element_click; mod eme_owner_interface_exposure_interfaces; mod encoded_video_chunk; -mod encoded_video_chunk_shell; mod event_receivers; mod extracted; mod fetch_integrity; diff --git a/moli-renderer-v8/src/window_host.rs b/moli-renderer-v8/src/window_host.rs index e739f7936e4..b4e5f05efad 100644 --- a/moli-renderer-v8/src/window_host.rs +++ b/moli-renderer-v8/src/window_host.rs @@ -903,10 +903,14 @@ pub(crate) fn window_post_message_callback<'s>( .as_ref() .map(|(identity, _, _)| *identity) .or_else(|| { - active_lightweight_popup_id(scope) - .map(PendingWindowMessageEndpoint::LightweightPopup) - .and_then(|endpoint| current_window_message_source_identity(scope, host, endpoint)) - .or_else(|| incumbent_window_message_source_identity(scope, host)) + incumbent_window_message_source_identity(scope, host) + .or_else(|| { + active_lightweight_popup_id(scope) + .map(PendingWindowMessageEndpoint::LightweightPopup) + .and_then(|endpoint| { + current_window_message_source_identity(scope, host, endpoint) + }) + }) .or_else(|| { host.current_window_message_source().and_then(|endpoint| { current_window_message_source_identity(scope, host, endpoint) diff --git a/moli-window-features/src/lib.rs b/moli-window-features/src/lib.rs index 01061f115d5..02f5012b311 100644 --- a/moli-window-features/src/lib.rs +++ b/moli-window-features/src/lib.rs @@ -143,11 +143,6 @@ impl WindowOpenFeatures { self.noreferrer } - /// Returns whether the features request an independent popup window. - pub fn is_popup(&self) -> bool { - self.is_popup - } - /// Returns the normalized enabled features used by the popup runtime. pub fn enabled_feature_strings(&self) -> Vec { let mut enabled = Vec::new();