From 5218dd0acc361c4e53d123dff4c86aeeaeb4cded Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sun, 27 Sep 2026 22:14:25 +0800 Subject: [PATCH] fix(navigation): check renderer history traversals before fetching --- .../tests/navigation_beforeunload.rs | 45 +++- moli-protocol/src/domains/page/navigation.rs | 27 ++- .../domains/page/navigation/before_unload.rs | 202 ++++++++++++++++++ 3 files changed, 271 insertions(+), 3 deletions(-) create mode 100644 moli-protocol/src/domains/page/navigation/before_unload.rs diff --git a/moli-protocol-server/src/protocol_server/tests/navigation_beforeunload.rs b/moli-protocol-server/src/protocol_server/tests/navigation_beforeunload.rs index 19dc7f22c21..9fc499b38d7 100644 --- a/moli-protocol-server/src/protocol_server/tests/navigation_beforeunload.rs +++ b/moli-protocol-server/src/protocol_server/tests/navigation_beforeunload.rs @@ -92,6 +92,34 @@ async fn websocket_navigation_beforeunload_precedes_fetch_and_only_commit_unload } } +#[tokio::test] +async fn websocket_renderer_history_beforeunload_precedes_fetch_and_only_commit_unloads() { + for method in [ + "history-back", + "history-go", + "navigation-back", + "navigation-traverse", + ] { + for response in ["html", "204", "205", "attachment"] { + run_beforeunload_navigation(method, response, "normal").await; + } + } +} + +#[tokio::test] +async fn websocket_renderer_history_beforeunload_debugger_pause_delays_fetch() { + for method in ["history-back", "navigation-back"] { + run_beforeunload_navigation(method, "html", "debugger").await; + } +} + +#[tokio::test] +async fn websocket_renderer_history_beforeunload_precedes_fetch_interception() { + for method in ["history-back", "navigation-back"] { + run_beforeunload_navigation(method, "html", "fetch").await; + } +} + #[tokio::test] async fn websocket_navigation_beforeunload_debugger_pause_delays_fetch() { run_beforeunload_navigation("navigate", "html", "debugger").await; @@ -149,7 +177,11 @@ async fn run_beforeunload_navigation(method: &str, response: &'static str, mode: .await; let source = format!("http://{address}/source"); let previous = format!("http://{address}/previous"); - if method == "history" { + let is_history = matches!( + method, + "history" | "history-back" | "history-go" | "navigation-back" | "navigation-traverse" + ); + if is_history { cdp_navigate_and_wait_for_load(&mut socket, 8, &session.session_id, &previous).await; } cdp_navigate_and_wait_for_load(&mut socket, 9, &session.session_id, &source).await; @@ -178,12 +210,21 @@ async fn run_beforeunload_navigation(method: &str, response: &'static str, mode: 15, "Fetch.enable", session_id, - json!({"patterns":[{"urlPattern":"*/destination","requestStage":"Request"}]}), + json!({"patterns":[{"urlPattern":if is_history {"*/previous"} else {"*/destination"},"requestStage":"Request"}]}), ) .await; } let (command, params) = match method { "reload" => ("Page.reload", json!({})), + "history-back" | "history-go" | "navigation-back" | "navigation-traverse" => ( + "Runtime.evaluate", + json!({"expression":match method { + "history-back" => "history.back()", + "history-go" => "history.go(-1)", + "navigation-back" => "navigation.back()", + _ => "navigation.traverseTo(navigation.entries().at(-2).key)", + }}), + ), "history" => { let messages = send_cdp_command( &mut socket, diff --git a/moli-protocol/src/domains/page/navigation.rs b/moli-protocol/src/domains/page/navigation.rs index ed2bd781939..e8fdfa050c1 100644 --- a/moli-protocol/src/domains/page/navigation.rs +++ b/moli-protocol/src/domains/page/navigation.rs @@ -1670,7 +1670,10 @@ pub(super) fn start_session_owner_history_traversal_from_renderer( owner: owner.clone(), result_projection: NavigationResultProjection::Cdp(json!({})), reloaded_after_crash_session_ids, - allow_background_navigation: false, + // This handoff is projected from a renderer turn. The source + // must keep servicing tasks and publishing output while the + // traversal checks beforeunload and loads its destination. + allow_background_navigation: true, }, HistoryTraversalStartSource::Renderer, ) @@ -1938,6 +1941,17 @@ 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 + }; start_navigate_to_url_command_with_background_policy_and_request( conn, None, @@ -1970,6 +1984,7 @@ pub(super) fn start_session_owner_navigation_from_renderer( } }, NavigationStartInitiator::Renderer, + beforeunload, navigation_history, web_mcp_invocation, document_response, @@ -2643,6 +2658,12 @@ fn clear_crash_state_for_renderer_navigation( start } +#[derive(Clone, Copy, PartialEq, Eq)] +enum BeforeUnloadCheck { + Required, + RendererHandled, +} + fn start_navigate_to_url_command_with_background_policy( conn: &mut CdpConnection, command_id: Option, @@ -2667,6 +2688,9 @@ 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, None, None, None, @@ -2696,6 +2720,7 @@ fn start_navigate_to_url_command_with_background_policy_and_request( allow_background_navigation: bool, request_load_policy: NavigationRequestLoadPolicy, initiator: NavigationStartInitiator, + beforeunload: BeforeUnloadCheck, navigation_history: Option, web_mcp_invocation: Option, document_response: Option, diff --git a/moli-protocol/src/domains/page/navigation/before_unload.rs b/moli-protocol/src/domains/page/navigation/before_unload.rs new file mode 100644 index 00000000000..64874a23fd2 --- /dev/null +++ b/moli-protocol/src/domains/page/navigation/before_unload.rs @@ -0,0 +1,202 @@ +use super::*; +use crate::conn::{CommandWorkflowContext, ProtocolWorkflowDriver, TargetPageResidenceIdentity}; +use crate::domains::fetch::NavigationTermination; +use crate::domains::page::{NavigationCommandOutput, PreparedRendererNavigationResult}; + +pub(crate) struct PendingBeforeUnloadNavigationCommand { + source: TargetPageResidenceIdentity, + navigation: PreparedMainDocumentNavigation, + pending: Result, + pub(super) prefix_events: Vec, + termination: Option, +} + +pub(crate) struct CompletedBeforeUnloadNavigationCommand { + source: TargetPageResidenceIdentity, + navigation: PreparedMainDocumentNavigation, + completed: Result, + prefix_events: Vec, + termination: Option, +} + +pub(crate) struct PreparedBeforeUnloadNavigation { + source: TargetPageResidenceIdentity, + navigation: PreparedMainDocumentNavigation, + allowed: Result, + prefix_events: Vec, + projection: Option>, + termination: Option, +} + +pub(crate) enum BeforeUnloadNavigationStep { + Continue(PageCommandTaskStep), + Stop(PreparedRendererNavigationResult), +} + +impl PendingBeforeUnloadNavigationCommand { + pub(super) fn new( + conn: &CdpConnection, + source: TargetPageResidenceIdentity, + navigation: PreparedMainDocumentNavigation, + pending: Result, + prefix_events: Vec, + ) -> Self { + let termination = NavigationTermination::new( + conn, + &navigation.state.owner, + Some(&navigation.token), + &navigation.state, + ); + Self { + source, + navigation, + pending, + prefix_events, + termination, + } + } + + pub(in crate::domains::page) async fn wait(self) -> CompletedBeforeUnloadNavigationCommand { + let completed = match self.pending { + Ok(pending) => pending.wait().await, + Err(error) => Err(error), + }; + CompletedBeforeUnloadNavigationCommand { + source: self.source, + navigation: self.navigation, + completed, + prefix_events: self.prefix_events, + termination: self.termination, + } + } +} + +impl CompletedBeforeUnloadNavigationCommand { + pub(crate) fn prepare( + self, + conn: &mut CdpConnection, + context: &mut CommandWorkflowContext, + ) -> PreparedBeforeUnloadNavigation { + let mut projection = None; + let allowed = self.completed.and_then(|completed| { + let allowed = completed + .bool_reply_value() + .ok_or_else(|| anyhow::anyhow!("beforeunload check did not return a boolean")); + // Settle the exact outgoing Page, including after a peer replaced + // the target. Never refresh a replacement Page from this reply. + let output = conn.settle_page_command_turn_for_owner(&self.source, completed); + let (mut completion, predecessor) = output.into_completion_and_predecessor(); + if let Some(continuation) = completion.take_post_response_continuation() { + continuation.release(); + } + if let Some(predecessor) = predecessor { + let target_id = conn + .target_owner_identity_for_owner(&self.navigation.state.owner) + .and_then(|(_, target_id)| target_id); + projection = + Some(conn.renderer_output_projection_receipt(predecessor.clone(), target_id)); + context + .context_mut() + .set_renderer_output_predecessor(predecessor); + } + allowed + }); + PreparedBeforeUnloadNavigation { + source: self.source, + navigation: self.navigation, + allowed, + prefix_events: self.prefix_events, + projection, + termination: self.termination, + } + } +} + +impl PreparedBeforeUnloadNavigation { + pub(crate) async fn run( + mut self, + driver: &mut ProtocolWorkflowDriver, + context: &mut CommandWorkflowContext, + output_mode: NavigationCommandOutput, + ) -> Result { + if let Some(projection) = self.projection.take() { + projection + .await + .map_err(|_| anyhow::anyhow!("beforeunload output projection was retired"))?; + } + let mut termination = self.termination.take(); + let step = context.with_state(driver, move |state, context| { + state.resume_before_unload_navigation(self, output_mode, context) + })?; + if let Some(termination) = termination.as_mut() { + termination.disarm(); + } + match step { + BeforeUnloadNavigationStep::Continue(step) => Ok(step), + BeforeUnloadNavigationStep::Stop(prepared) => { + Box::pin(prepared.run(driver, context)).await?; + Ok(PageCommandTaskStep::Complete(CommandOutputPlan::default())) + } + } + } + + pub(crate) fn resume( + self, + conn: &mut CdpConnection, + context: &mut CommandWorkflowContext, + output_mode: NavigationCommandOutput, + ) -> BeforeUnloadNavigationStep { + let Self { + source, + navigation, + allowed, + prefix_events, + .. + } = self; + let owner = navigation.state.owner.clone(); + if conn.accepts_pending_document_navigation_for_owner(&owner, &navigation.token) + && conn.target_page_residence_identity_is_current(&source) + && matches!(allowed, Ok(true)) + { + let command_id = navigation.state.navigate_id; + let start = start_prepared_main_document_navigation(conn, navigation, prefix_events); + return BeforeUnloadNavigationStep::Continue( + finish_started_navigation_command_for_parts(conn, command_id, owner, start, &[]), + ); + } + let prepared = + if conn.accepts_pending_document_navigation_for_owner(&owner, &navigation.token) { + let message = allowed.err().map_or_else( + || "Navigation aborted".to_owned(), + |error| error.to_string(), + ); + let failure = network::materialize_navigation_failure_preserving_committed_document( + conn, + &navigation.state, + message, + ); + PreparedRendererNavigationResult::prepare_materialized( + conn, + navigation.token, + navigation.state, + failure, + context, + output_mode, + prefix_events, + ) + } else { + // Stale cleanup belongs to this original request. It must not + // announce a network request or mutate a replacement Document. + PreparedRendererNavigationResult::prepare_with_output( + conn, + navigation.token, + navigation.state, + Err(moli_fetch::FetchCancelled.into()), + context, + output_mode, + prefix_events, + ) + }; + BeforeUnloadNavigationStep::Stop(prepared) + } +}