From da11ddb2f56aa6f83c7f72ae8a30fc535fc2d9e8 Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sun, 27 Sep 2026 21:58:19 +0800 Subject: [PATCH] fix(navigation): check beforeunload before browser fetches Run browser-initiated main-document checks through the existing asynchronous lifecycle scheduler before Fetch interception or network loading. Project the source turn first, reject superseded navigation tokens, and share navigation finalization so failed checks retain the committed document and release state. Foreground DevTools callers remain pending through the check and load, preserving typed navigation results and the captured target owner. Keep beforeunload and commit unload commands out of nested non-V8 Page-agent dispatch while the owner is debugger-paused. Cover real navigate/reload/history responses, retained documents, pause/resume, supersession, and Fetch ordering. --- moli-core/src/page/history_support.rs | 4 + .../src/protocol_server/tests/mod.rs | 1 + .../tests/navigation_beforeunload.rs | 415 ++++++++++++++++++ .../no_document_navigation.rs | 13 + .../src/devtools/command/nested.rs | 2 + moli-renderer-v8/src/runtime/page_commands.rs | 4 + moli-renderer-v8/src/runtime/page_surface.rs | 1 + .../src/script_vm/child_frame_runtime.rs | 6 + 8 files changed, 446 insertions(+) create mode 100644 moli-protocol-server/src/protocol_server/tests/navigation_beforeunload.rs diff --git a/moli-core/src/page/history_support.rs b/moli-core/src/page/history_support.rs index 1e3fa7d420f..789d6893f87 100644 --- a/moli-core/src/page/history_support.rs +++ b/moli-core/src/page/history_support.rs @@ -3,6 +3,10 @@ use anyhow::Result; use super::{CompletedPageCommand, Page, PendingPageCommand, RendererPageCommand}; impl Page { + pub fn start_check_main_document_beforeunload(&self) -> Result { + self.start_page_command(RendererPageCommand::CheckMainDocumentBeforeUnload) + } + pub fn start_unload_main_document_for_navigation_commit(&self) -> Result { self.start_page_command(RendererPageCommand::UnloadMainDocumentForNavigationCommit) } diff --git a/moli-protocol-server/src/protocol_server/tests/mod.rs b/moli-protocol-server/src/protocol_server/tests/mod.rs index b128b18046b..eb6df986702 100644 --- a/moli-protocol-server/src/protocol_server/tests/mod.rs +++ b/moli-protocol-server/src/protocol_server/tests/mod.rs @@ -1385,6 +1385,7 @@ mod cdp_dynamic_page; mod classic; mod download; mod misc; +mod navigation_beforeunload; mod navigation_unload; mod p6_output_handoff; mod page_endpoint; diff --git a/moli-protocol-server/src/protocol_server/tests/navigation_beforeunload.rs b/moli-protocol-server/src/protocol_server/tests/navigation_beforeunload.rs new file mode 100644 index 00000000000..19dc7f22c21 --- /dev/null +++ b/moli-protocol-server/src/protocol_server/tests/navigation_beforeunload.rs @@ -0,0 +1,415 @@ +use super::*; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +const BEFORE: [&str; 3] = [ + "root:beforeunload", + "child:beforeunload", + "grand:beforeunload", +]; +const SETUP: &str = r#"(() => { + const child = document.querySelector('iframe'); + const grand = child.contentDocument.querySelector('iframe'); + const root = document.documentElement; + const trace = []; + for (const [win, name] of [[window, 'root'], [child.contentWindow, 'child'], + [grand.contentWindow, 'grand']]) { + for (const type of ['beforeunload', 'pagehide', 'unload']) { + win.addEventListener(type, event => { + trace.push(name + ':' + type); + sessionStorage.setItem('browserBeforeUnloadTrace', JSON.stringify(trace)); + reportBeforeUnload(JSON.stringify({phase:'event', event:trace.at(-1), + trusted:event.isTrusted, cancelable:event.cancelable})); + }); + } + } + globalThis.beforeUnloadSnapshot = () => ({phase:'pending', trace:trace.slice(), + url:location.href, documentURL:document.URL, hidden:document.hidden, + sameRoot:document.documentElement === root, child:child.isConnected, + grand:grand.isConnected}); + fetch('/navigation-received').then(() => reportBeforeUnload(JSON.stringify(beforeUnloadSnapshot()))); + return 'armed'; +})()"#; + +struct NavigationGate { + armed: AtomicBool, + requests: AtomicUsize, + received: tokio::sync::Notify, + release: tokio::sync::Semaphore, +} + +fn fixture( + response: &'static str, +) -> ( + std::net::SocketAddr, + DedicatedFixtureServer, + Arc, +) { + let gate = Arc::new(NavigationGate { + armed: AtomicBool::new(false), + requests: AtomicUsize::new(0), + received: tokio::sync::Notify::new(), + release: tokio::sync::Semaphore::new(0), + }); + let serve = gate.clone(); + let app = Router::new().fallback(get(move |uri: axum::http::Uri| { + let gate = serve.clone(); + async move { + if uri.path() == "/navigation-received" { + gate.received.notified().await; + return "ready".into_response(); + } + if matches!(uri.path(), "/source" | "/destination" | "/previous") + && gate.armed.swap(false, Ordering::SeqCst) + { + gate.requests.fetch_add(1, Ordering::SeqCst); + gate.received.notify_one(); + gate.release.acquire().await.unwrap().forget(); + match response { + "204" => return StatusCode::NO_CONTENT.into_response(), + "205" => return StatusCode::RESET_CONTENT.into_response(), + "attachment" => return ([(header::CONTENT_DISPOSITION, "attachment; filename=probe.txt")], "download").into_response(), + _ => {} + } + } + let body = match uri.path() { + "/child" => "", + "/grandchild" => "grandchild", + _ => "", + }; + ([(header::CONTENT_TYPE, "text/html"), (header::CACHE_CONTROL, "no-store")], body).into_response() + } + })); + let (address, server) = spawn_dedicated_fixture_server(app, "navigation-beforeunload"); + (address, server, gate) +} + +#[tokio::test] +async fn websocket_navigation_beforeunload_precedes_fetch_and_only_commit_unloads() { + for method in ["navigate", "reload", "history"] { + for response in ["html", "204", "205", "attachment"] { + run_beforeunload_navigation(method, response, "normal").await; + } + } +} + +#[tokio::test] +async fn websocket_navigation_beforeunload_debugger_pause_delays_fetch() { + run_beforeunload_navigation("navigate", "html", "debugger").await; +} + +#[tokio::test] +async fn websocket_navigation_beforeunload_superseded_check_does_not_start_a_request() { + run_beforeunload_navigation("navigate", "html", "supersede").await; +} + +#[tokio::test] +async fn websocket_navigation_beforeunload_precedes_fetch_interception() { + run_beforeunload_navigation("navigate", "html", "fetch").await; +} + +async fn run_beforeunload_navigation(method: &str, response: &'static str, mode: &str) { + let pause = matches!(mode, "debugger" | "supersede"); + let (address, _fixture, gate) = fixture(response); + let download_root = std::env::temp_dir().join(format!( + "moli-beforeunload-download-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let (cdp_address, server) = spawn_test_protocol_server().await; + let (mut socket, _) = connect_async( + discover_browser_websocket_url(cdp_address) + .await + .expect("discover browser endpoint"), + ) + .await + .unwrap(); + let context = cdp_create_browser_context(&mut socket, 1).await; + let session = cdp_create_attached_target(&mut socket, 2, &context).await; + let session_id = Some(session.session_id.as_str()); + for (id, domain) in [(4, "Page"), (5, "Runtime"), (6, "Network")] { + send_cdp_command( + &mut socket, + id, + &format!("{domain}.enable"), + session_id, + json!({}), + ) + .await; + } + send_cdp_command( + &mut socket, + 7, + "Runtime.addBinding", + session_id, + json!({"name":"reportBeforeUnload"}), + ) + .await; + let source = format!("http://{address}/source"); + let previous = format!("http://{address}/previous"); + if method == "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; + assert_eq!( + cdp_runtime_evaluate_string(&mut socket, &session.session_id, 10, SETUP).await, + "armed" + ); + if response == "attachment" { + send_cdp_command( + &mut socket, + 11, + "Browser.setDownloadBehavior", + None, + json!({"behavior":"allow","downloadPath":download_root,"browserContextId":context}), + ) + .await; + } + if pause { + send_cdp_command(&mut socket, 12, "Debugger.enable", session_id, json!({})).await; + send_cdp_command(&mut socket, 13, "Runtime.evaluate", session_id, + json!({"expression":"addEventListener('beforeunload', () => { debugger; }, {once:true})"})).await; + } + if mode == "fetch" { + send_cdp_command( + &mut socket, + 15, + "Fetch.enable", + session_id, + json!({"patterns":[{"urlPattern":"*/destination","requestStage":"Request"}]}), + ) + .await; + } + let (command, params) = match method { + "reload" => ("Page.reload", json!({})), + "history" => { + let messages = send_cdp_command( + &mut socket, + 14, + "Page.getNavigationHistory", + session_id, + json!({}), + ) + .await; + let history = &messages.iter().find(|message| message["id"] == 14).unwrap()["result"]; + let entry = history["entries"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["url"] == previous) + .unwrap(); + ( + "Page.navigateToHistoryEntry", + json!({"entryId":entry["id"]}), + ) + } + _ => ( + "Page.navigate", + json!({"url":format!("http://{address}/destination")}), + ), + }; + gate.armed.store(true, Ordering::SeqCst); + send_cdp_command_without_wait(&mut socket, 20, command, session_id, params).await; + let mut messages = Vec::new(); + if pause { + messages.extend( + recv_until_match(&mut socket, |message| { + message["method"] == "Debugger.paused" + }) + .await, + ); + assert_eq!( + gate.requests.load(Ordering::SeqCst), + 0, + "fetch must wait for beforeunload" + ); + if mode == "supersede" { + send_cdp_command_without_wait( + &mut socket, + 21, + "Page.navigate", + session_id, + json!({"url":"data:text/html,replacement"}), + ) + .await; + } + messages.extend( + send_cdp_command(&mut socket, 22, "Debugger.resume", session_id, json!({})).await, + ); + } + if mode == "supersede" { + if !messages.iter().any(|message| message["id"] == 20) { + messages.extend(recv_until_id(&mut socket, 20).await); + } + let result = messages.iter().find(|message| message["id"] == 20).unwrap(); + assert_eq!( + result["result"]["errorText"], "net::ERR_ABORTED", + "{messages:?}" + ); + assert_eq!( + gate.requests.load(Ordering::SeqCst), + 0, + "a superseded check must not fetch" + ); + if !messages + .iter() + .any(|message| message["method"] == "Page.loadEventFired") + { + messages.extend( + recv_until_match(&mut socket, |message| { + message["method"] == "Page.loadEventFired" + }) + .await, + ); + } + assert_eq!( + cdp_runtime_evaluate_string(&mut socket, &session.session_id, 23, "document.title") + .await, + "replacement" + ); + } else { + if mode == "fetch" { + messages.extend( + recv_until_match(&mut socket, |message| { + message["method"] == "Fetch.requestPaused" + }) + .await, + ); + assert_eq!(gate.requests.load(Ordering::SeqCst), 0); + let paused = messages.last().unwrap(); + let fetch_request_id = paused["params"]["requestId"].clone(); + for event in BEFORE { + assert!( + messages[..messages.len() - 1] + .iter() + .any(|message| message["method"] == "Runtime.bindingCalled" + && message["params"]["payload"] + .as_str() + .is_some_and(|payload| payload.contains(event))), + "{event} must precede Fetch.requestPaused: {messages:?}" + ); + } + // Fetch continuation currently owns the foreground load. Release + // the fixture before continuing; the pause above already proves + // the lifecycle check precedes interception and any HTTP request. + gate.release.add_permits(1); + send_cdp_command_without_wait( + &mut socket, + 26, + "Fetch.continueRequest", + session_id, + json!({"requestId":fetch_request_id}), + ) + .await; + } + if mode != "fetch" { + messages.extend( + recv_until_match(&mut socket, |message| { + message["method"] == "Runtime.bindingCalled" + && message["params"]["payload"] + .as_str() + .is_some_and(|value| value.contains("\"phase\":\"pending\"")) + }) + .await, + ); + } + let pending = messages.iter().find_map(|message| { + if message["method"] != "Runtime.bindingCalled" { + return None; + } + let value: serde_json::Value = + serde_json::from_str(message["params"]["payload"].as_str()?).ok()?; + (value["phase"] == "pending").then_some(value) + }); + if mode != "fetch" { + assert_eq!( + pending, + Some( + json!({"phase":"pending","trace":BEFORE,"url":source,"documentURL":source, + "hidden":false,"sameRoot":true,"child":true,"grand":true}) + ), + "{method}/{response}" + ); + } + let request = messages + .iter() + .position(|message| { + message["method"] == "Network.requestWillBeSent" + && message["params"]["type"] == "Document" + && message["params"]["frameId"] == session.target_id + }) + .expect("main-document network request"); + for event in BEFORE { + let index = messages + .iter() + .position(|message| { + message["method"] == "Runtime.bindingCalled" + && message["params"]["payload"] + .as_str() + .is_some_and(|value| value.contains(event)) + }) + .expect(event); + assert!( + index < request, + "beforeunload output must precede the request: {messages:?}" + ); + } + gate.release.add_permits(1); + messages.extend( + recv_until_match(&mut socket, |message| { + message["method"] == "Page.frameStoppedLoading" + && message["params"]["frameId"] == session.target_id + }) + .await, + ); + if response == "html" { + let trace = cdp_runtime_evaluate_string( + &mut socket, + &session.session_id, + 24, + "JSON.stringify(beforeUnloadAtFirstScript)", + ) + .await; + assert_eq!( + trace, + serde_json::to_string(&[ + "root:beforeunload", + "child:beforeunload", + "grand:beforeunload", + "root:pagehide", + "root:unload", + "child:pagehide", + "child:unload", + "grand:pagehide", + "grand:unload", + ]) + .unwrap(), + "{method}/{response}" + ); + } else { + let retained = cdp_runtime_evaluate_string( + &mut socket, + &session.session_id, + 25, + "JSON.stringify(beforeUnloadSnapshot())", + ) + .await; + assert_eq!( + serde_json::from_str::(&retained).unwrap(), + pending.unwrap(), + "{method}/{response}" + ); + assert!( + messages + .iter() + .all(|message| message["method"] != "Page.frameNavigated" + || message["params"]["frame"]["id"] != session.target_id) + ); + } + } + let _ = socket.close(None).await; + abort_test_cdp_server(server).await; + let _ = fs::remove_dir_all(download_root); +} diff --git a/moli-protocol/src/domains/page/tests/same_document_history/no_document_navigation.rs b/moli-protocol/src/domains/page/tests/same_document_history/no_document_navigation.rs index cd80b44a156..d8bf8626e6f 100644 --- a/moli-protocol/src/domains/page/tests/same_document_history/no_document_navigation.rs +++ b/moli-protocol/src/domains/page/tests/same_document_history/no_document_navigation.rs @@ -421,6 +421,15 @@ async fn no_document_navigation_preserves_protocol_result_semantics() { FrontendProtocol::WebDriverBidi, ] { let mut page = no_document_page(status, false).await; + page.evaluate( + r#"(() => { + globalThis.protocolBeforeUnload = []; + addEventListener('beforeunload', () => protocolBeforeUnload.push('root')); + document.querySelector('iframe').contentWindow.addEventListener( + 'beforeunload', () => protocolBeforeUnload.push('child')); + })()"#, + ) + .await; let tree = page.command("Page.getFrameTree", json!({})).await; let url = page.base_url.replace("/history.html", "/no-document"); let outcome = tokio::time::timeout( @@ -456,6 +465,10 @@ async fn no_document_navigation_preserves_protocol_result_semantics() { result.error_text.as_deref(), (protocol == FrontendProtocol::Cdp).then_some("net::ERR_ABORTED") ); + assert_eq!( + page.evaluate("protocolBeforeUnload").await, + json!(["root", "child"]) + ); assert_eq!(page.command("Page.getFrameTree", json!({})).await, tree); assert_eq!( page.evaluate("noDocumentSnapshot()").await, diff --git a/moli-renderer-v8/src/devtools/command/nested.rs b/moli-renderer-v8/src/devtools/command/nested.rs index fbb9b5c60fc..f3042afd1df 100644 --- a/moli-renderer-v8/src/devtools/command/nested.rs +++ b/moli-renderer-v8/src/devtools/command/nested.rs @@ -67,6 +67,8 @@ impl RendererPageCommand { | Self::RuntimeConsoleMessagesWithContext | Self::RuntimeHeapUsage | Self::StopDocumentLifecycle + | Self::CheckMainDocumentBeforeUnload + | Self::UnloadMainDocumentForNavigationCommit | Self::ResetNavigationHistory | Self::RenderMarkdown { .. } | Self::PrintToPdf(..) diff --git a/moli-renderer-v8/src/runtime/page_commands.rs b/moli-renderer-v8/src/runtime/page_commands.rs index 23ee8ea142f..74bdf830dac 100644 --- a/moli-renderer-v8/src/runtime/page_commands.rs +++ b/moli-renderer-v8/src/runtime/page_commands.rs @@ -101,6 +101,10 @@ impl PageVm { .vm_mut() .navigate_top_level_same_document_from_browser(&url, replace_current) .map(RendererPageReply::Bool), + RendererPageCommand::CheckMainDocumentBeforeUnload => self + .vm_mut() + .check_main_document_beforeunload() + .map(RendererPageReply::Bool), RendererPageCommand::UnloadMainDocumentForNavigationCommit => self .vm_mut() .unload_main_document_for_navigation_commit() diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rs index ad96d548956..e70cb38505f 100644 --- a/moli-renderer-v8/src/runtime/page_surface.rs +++ b/moli-renderer-v8/src/runtime/page_surface.rs @@ -5041,6 +5041,7 @@ pub enum RendererPageCommand { #[cfg(test)] TakeDocumentLifecycleEvents, StopDocumentLifecycle, + CheckMainDocumentBeforeUnload, UnloadMainDocumentForNavigationCommit, ResetNavigationHistory, AccessibilityTreeNodes { diff --git a/moli-renderer-v8/src/script_vm/child_frame_runtime.rs b/moli-renderer-v8/src/script_vm/child_frame_runtime.rs index 6d72c28ae83..301874b809a 100644 --- a/moli-renderer-v8/src/script_vm/child_frame_runtime.rs +++ b/moli-renderer-v8/src/script_vm/child_frame_runtime.rs @@ -531,6 +531,12 @@ impl ScriptVm { }) } + pub(crate) fn check_main_document_beforeunload(&mut self) -> anyhow::Result { + self.with_default_context_scope(|scope, host_ptr| { + Ok(unsafe { &mut *host_ptr }.dispatch_main_document_tree_beforeunload(scope)) + }) + } + pub(crate) fn unload_main_document_for_navigation_commit(&mut self) -> anyhow::Result<()> { self.with_default_context_scope(|scope, host_ptr| { PageScriptHost::dispatch_main_document_unload_for_navigation_commit(scope, host_ptr);