Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(cdp): harden popup realm transitions

ldm0f9837b4ad575
diff --git a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
index 960e91e05..011dc5c3a 100644
--- a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
+++ b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
@@ -2,6 +2,7 @@ use super::*;
mod auto_attach_startup;
mod auxiliary_page_identity;
+mod auxiliary_page_retirement;
mod blank_navigation_inheritance;
mod noopener_blank_inheritance;
mod popup_navigation_referrer;
diff --git a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page/auxiliary_page_identity.rs b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page/auxiliary_page_identity.rs
index 45be2e888..2ce8dc9c4 100644
--- a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page/auxiliary_page_identity.rs
+++ b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page/auxiliary_page_identity.rs
@@ -8,6 +8,15 @@ pub(super) async fn open_auxiliary(
addr: std::net::SocketAddr,
opener: &mut TestCdpSocket,
synchronous_script: &str,
+) -> (String, TestCdpSocket) {
+ open_auxiliary_with_url(addr, opener, "about:blank", synchronous_script).await
+}
+
+pub(super) async fn open_auxiliary_with_url(
+ addr: std::net::SocketAddr,
+ opener: &mut TestCdpSocket,
+ url: &str,
+ synchronous_script: &str,
) -> (String, TestCdpSocket) {
let baseline = fetch_server_json(addr, "/json/list").await;
let ids: Vec<_> = baseline
@@ -16,9 +25,18 @@ pub(super) async fn open_auxiliary(
.iter()
.map(|t| t["id"].clone())
.collect();
- assert_eq!(evaluate_window_name_probe(opener, 90, &format!(
- "window.p = open('about:blank', 'actual-page'); {synchronous_script}; p.opener === window"
- )).await, true);
+ assert_eq!(
+ evaluate_window_name_probe(
+ opener,
+ 90,
+ &format!(
+ "window.p = open({}, 'actual-page'); {synchronous_script}; p.opener === window",
+ json!(url)
+ )
+ )
+ .await,
+ true
+ );
let targets = wait_for_target_list(addr, "the exact initial Page is adopted", |targets| {
targets.len() == ids.len() + 1
})
@@ -45,6 +63,31 @@ async fn wait_for_value(page: &mut TestCdpSocket, expression: &str, expected: se
.unwrap_or_else(|_| panic!("{expression} did not become {expected}"));
}
+pub(super) async fn resume_auxiliary(browser: &mut TestCdpSocket, target_id: &str) {
+ let events = recv_until_match(browser, |message| {
+ message["method"] == "Target.attachedToTarget"
+ && message["params"]["targetInfo"]["targetId"] == target_id
+ })
+ .await;
+ let session = events
+ .iter()
+ .find(|message| {
+ message["method"] == "Target.attachedToTarget"
+ && message["params"]["targetInfo"]["targetId"] == target_id
+ })
+ .unwrap()["params"]["sessionId"]
+ .as_str()
+ .unwrap();
+ send_cdp_command(
+ browser,
+ 21,
+ "Runtime.runIfWaitingForDebugger",
+ Some(session),
+ json!({}),
+ )
+ .await;
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn auxiliary_page_borrowed_close_uses_the_window_receiver() {
let (addr, server) = spawn_test_protocol_server().await;
@@ -447,7 +490,9 @@ async fn auxiliary_page_cross_origin_surface_delivers_messages_and_blocks_javasc
(()=>{
const attempt=f=>{try{f();return 'allowed'}catch(e){return e.name}};
return [p.closed,p.top===p,p.parent===p,p.opener===window,p.length,
- attempt(()=>p.document),attempt(()=>p.location.href),
+ attempt(()=>p.document),
+ attempt(()=>Object.getOwnPropertyDescriptor(window,'document').get.call(p)),
+ attempt(()=>p.location.href),
attempt(()=>p.location='javascript:window.crossOriginScriptRan=true'),
attempt(()=>p.location.href=' \nJaVaScRiPt:window.crossOriginScriptRan=true'),
attempt(()=>p.location.replace('java\tscript:window.crossOriginScriptRan=true'))];
@@ -465,6 +510,7 @@ async fn auxiliary_page_cross_origin_surface_delivers_messages_and_blocks_javasc
"SecurityError",
"SecurityError",
"SecurityError",
+ "SecurityError",
"SecurityError"
])
);
@@ -1042,12 +1088,18 @@ async fn initial_same_origin_popup_commit_preserves_window_and_replaces_document
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn initial_popup_commit_recreates_isolated_worlds_for_all_frontends() {
+ let release = Arc::new(tokio::sync::Notify::new());
+ let child_response = Arc::clone(&release);
let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(
- Router::new().fallback(get(|uri: axum::http::Uri| async move {
- if uri.path() == "/child" {
- axum::response::Html("<main>popup document</main>")
- } else {
- axum::response::Html("<main>opener document</main>")
+ Router::new().fallback(get(move |uri: axum::http::Uri| {
+ let child_response = Arc::clone(&child_response);
+ async move {
+ if uri.path() == "/child" {
+ child_response.notified().await;
+ axum::response::Html("<main>popup document</main>")
+ } else {
+ axum::response::Html("<main>opener document</main>")
+ }
}
})),
"initial-popup-isolated-worlds",
@@ -1062,8 +1114,21 @@ async fn initial_popup_commit_recreates_isolated_worlds_for_all_frontends() {
let mut opener = connect_dynamic_page(addr, &opener_id).await;
send_cdp_command(&mut opener, 1, "Page.enable", None, json!({})).await;
navigate_dynamic_page_and_wait_for_load(&mut opener, 2, &format!("{base}/opener")).await;
- let (child_id, mut child) =
- open_auxiliary(addr, &mut opener, "p.marker=73;window.oldArray=p.Array").await;
+ send_cdp_command(
+ &mut browser,
+ 20,
+ "Target.setAutoAttach",
+ None,
+ json!({"autoAttach":true,"waitForDebuggerOnStart":true,"flatten":true}),
+ )
+ .await;
+ let (child_id, mut child) = open_auxiliary_with_url(
+ addr,
+ &mut opener,
+ "/child",
+ "p.marker=73;window.oldArray=p.Array",
+ )
+ .await;
send_cdp_command(&mut child, 2, "Runtime.enable", None, json!({})).await;
let tree = send_cdp_command(&mut child, 3, "Page.getFrameTree", None, json!({})).await;
let frame_id = response_by_id(&tree, 3)["result"]["frameTree"]["frame"]["id"]
@@ -1139,10 +1204,8 @@ async fn initial_popup_commit_recreates_isolated_worlds_for_all_frontends() {
.as_i64()
.unwrap();
- assert_eq!(
- evaluate_window_name_probe(&mut opener, 3, "p.location.href='/child';true").await,
- true
- );
+ release.notify_one();
+ resume_auxiliary(&mut browser, &child_id).await;
wait_for_value(&mut child, "document.URL", json!(format!("{base}/child"))).await;
wait_for_value(&mut child, "document.readyState", json!("complete")).await;
assert_eq!(
@@ -1335,13 +1398,15 @@ async fn initial_same_origin_popup_commit_rebinds_xml_and_text_parsers() {
.into_iter()
.enumerate()
{
- let (child_id, mut child) = open_auxiliary(
+ let (child_id, mut child) = open_auxiliary_with_url(
addr,
&mut opener,
+ path,
"p.marker=73;window.oldDocument=p.document;window.oldArray=p.Array;",
)
.await;
- navigate_dynamic_page_and_wait_for_load(&mut child, 2, &format!("{base}{path}")).await;
+ wait_for_value(&mut child, "document.URL", json!(format!("{base}{path}"))).await;
+ wait_for_value(&mut child, "document.readyState", json!("complete")).await;
assert_eq!(
evaluate_window_name_probe(
&mut opener,
diff --git a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page/auxiliary_page_retirement.rs b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page/auxiliary_page_retirement.rs
new file mode 100644
index 000000000..45823e190
--- /dev/null
+++ b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page/auxiliary_page_retirement.rs
@@ -0,0 +1,331 @@
+use super::auxiliary_page_identity::{open_auxiliary, open_auxiliary_with_url, resume_auxiliary};
+use super::*;
+
+async fn wait_for_value(page: &mut TestCdpSocket, expression: &str, expected: serde_json::Value) {
+ let mut actual = serde_json::Value::Null;
+ timeout(Duration::from_secs(5), async {
+ loop {
+ actual = evaluate_window_name_probe(page, 900, expression).await;
+ if actual == expected {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ })
+ .await
+ .unwrap_or_else(|_| panic!("{expression} did not become {expected}; last value was {actual}"));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn initial_popup_commit_keeps_window_timers_and_service_worker_completion() {
+ let release = Arc::new(tokio::sync::Notify::new());
+ let response = Arc::clone(&release);
+ let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(
+ Router::new().fallback(get(move |uri: axum::http::Uri| {
+ let response = Arc::clone(&response);
+ async move {
+ if uri.path() == "/worker.js" {
+ return ([("content-type", "text/javascript")], "self.addEventListener('install',e=>e.waitUntil(self.skipWaiting()));self.addEventListener('activate',e=>e.waitUntil(self.clients.claim()));");
+ }
+ if uri.path() == "/child" {
+ response.notified().await;
+ }
+ ([("content-type", "text/html")], "<p>loaded</p>")
+ }
+ })),
+ "initial-popup-window-tasks",
+ );
+ let base = format!("http://{fixture_addr}");
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ let opener_id = create_dynamic_target(&mut browser, 1).await;
+ let mut opener = connect_dynamic_page(addr, &opener_id).await;
+ send_cdp_command(&mut opener, 1, "Page.enable", None, json!({})).await;
+ navigate_dynamic_page_and_wait_for_load(&mut opener, 2, &format!("{base}/opener")).await;
+ send_cdp_command(
+ &mut browser,
+ 20,
+ "Target.setAutoAttach",
+ None,
+ json!({"autoAttach":true,"waitForDebuggerOnStart":true,"flatten":true}),
+ )
+ .await;
+ let (child_id, mut child) = open_auxiliary_with_url(addr, &mut opener, "/child", "").await;
+ evaluate_window_name_probe(&mut child, 2, "window.ticks=0;window.timerFired=false;window.timeoutId=setTimeout(()=>timerFired=true,900);window.intervalId=setInterval(()=>ticks++,200);true").await;
+ wait_for_value(&mut child, "ticks>0", json!(true)).await;
+ let ticks = evaluate_window_name_probe(&mut child, 3, "ticks")
+ .await
+ .as_u64()
+ .unwrap();
+ release.notify_one();
+ resume_auxiliary(&mut browser, &child_id).await;
+ wait_for_value(&mut child, "document.URL", json!(format!("{base}/child"))).await;
+ wait_for_value(&mut child, "timerFired", json!(true)).await;
+ wait_for_value(&mut child, &format!("ticks>{ticks}"), json!(true)).await;
+ send_cdp_command(
+ &mut browser,
+ 22,
+ "Target.setAutoAttach",
+ None,
+ json!({"autoAttach":false,"waitForDebuggerOnStart":false,"flatten":true}),
+ )
+ .await;
+ evaluate_window_name_probe(&mut child, 4, "window.registered='pending';navigator.serviceWorker.register('/worker.js').then(()=>registered='success',e=>registered=e.name);true").await;
+ wait_for_value(&mut child, "registered", json!("success")).await;
+ assert_eq!(
+ evaluate_window_name_probe(&mut child, 5, "clearInterval(intervalId);typeof timeoutId")
+ .await,
+ "number"
+ );
+ abort_test_cdp_server(server).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn isolated_popup_navigation_releases_indexed_db_connections() {
+ let release = Arc::new(tokio::sync::Notify::new());
+ let response = Arc::clone(&release);
+ let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(
+ Router::new().fallback(get(move |uri: axum::http::Uri| {
+ let response = Arc::clone(&response);
+ async move {
+ if uri.path() == "/child" {
+ response.notified().await;
+ }
+ axum::response::Html("<p>loaded</p>")
+ }
+ })),
+ "isolated-popup-idb-retirement",
+ );
+ let base = format!("http://{fixture_addr}");
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ let opener_id = create_dynamic_target(&mut browser, 1).await;
+ let mut opener = connect_dynamic_page(addr, &opener_id).await;
+ send_cdp_command(&mut opener, 1, "Page.enable", None, json!({})).await;
+ navigate_dynamic_page_and_wait_for_load(&mut opener, 2, &format!("{base}/opener")).await;
+ send_cdp_command(
+ &mut browser,
+ 20,
+ "Target.setAutoAttach",
+ None,
+ json!({"autoAttach":true,"waitForDebuggerOnStart":true,"flatten":true}),
+ )
+ .await;
+ let (child_id, mut child) = open_auxiliary_with_url(addr, &mut opener, "/child", "").await;
+ let tree = send_cdp_command(&mut child, 2, "Page.getFrameTree", None, json!({})).await;
+ let world = send_cdp_command(&mut child, 3, "Page.createIsolatedWorld", None, json!({"frameId":response_by_id(&tree,2)["result"]["frameTree"]["frame"]["id"],"worldName":"idb-retirement"})).await;
+ let context_id = response_by_id(&world, 3)["result"]["executionContextId"].clone();
+ let opened = send_cdp_command(&mut child, 4, "Runtime.evaluate", None, json!({"contextId":context_id,"expression":"new Promise((resolve,reject)=>{window.retained=new Array(1024*1024).fill(3);const r=indexedDB.open('isolated-retirement',1);r.onsuccess=()=>{window.db=r.result;resolve('opened')};r.onerror=()=>reject(r.error)})","awaitPromise":true,"returnByValue":true})).await;
+ assert_eq!(
+ response_by_id(&opened, 4)["result"]["result"]["value"],
+ "opened"
+ );
+ release.notify_one();
+ resume_auxiliary(&mut browser, &child_id).await;
+ wait_for_value(&mut child, "document.URL", json!(format!("{base}/child"))).await;
+ evaluate_window_name_probe(&mut child, 5, "window.upgrade='pending';const r=indexedDB.open('isolated-retirement',2);r.onblocked=()=>upgrade='blocked';r.onerror=()=>upgrade=r.error.name;r.onsuccess=()=>{upgrade='success';r.result.close()};true").await;
+ wait_for_value(&mut child, "upgrade", json!("success")).await;
+ abort_test_cdp_server(server).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn iframe_popup_location_navigation_uses_incumbent_document_referrer() {
+ let requests = Arc::new(parking_lot::Mutex::new(Vec::<(String, String)>::new()));
+ let captured = Arc::clone(&requests);
+ let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(
+ Router::new().fallback(get(
+ move |uri: axum::http::Uri, headers: axum::http::HeaderMap| {
+ let captured = Arc::clone(&captured);
+ async move {
+ captured.lock().push((
+ uri.path().to_owned(),
+ headers
+ .get("referer")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("")
+ .to_owned(),
+ ));
+ axum::response::Html(if uri.path() == "/frame/inner" {
+ "<script>onmessage=()=>parent.p.location.href='next'</script>"
+ } else {
+ "<p>loaded</p>"
+ })
+ }
+ },
+ )),
+ "iframe-popup-location-referrer",
+ );
+ let base = format!("http://{fixture_addr}");
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ let opener_id = create_dynamic_target(&mut browser, 1).await;
+ let mut opener = connect_dynamic_page(addr, &opener_id).await;
+ send_cdp_command(&mut opener, 1, "Page.enable", None, json!({})).await;
+ navigate_dynamic_page_and_wait_for_load(&mut opener, 2, &format!("{base}/source/start")).await;
+ let (_, mut child) = open_auxiliary(addr, &mut opener, "").await;
+ evaluate_window_name_probe(
+ &mut opener,
+ 3,
+ "document.body.innerHTML='<iframe src=/frame/inner></iframe>';true",
+ )
+ .await;
+ wait_for_value(&mut opener,"document.querySelector('iframe').contentDocument.URL.endsWith('/frame/inner') && document.querySelector('iframe').contentDocument.readyState==='complete'",json!(true)).await;
+ evaluate_window_name_probe(
+ &mut opener,
+ 4,
+ "document.querySelector('iframe').contentWindow.postMessage('navigate','*');true",
+ )
+ .await;
+ wait_for_value(
+ &mut child,
+ "document.URL",
+ json!(format!("{base}/frame/next")),
+ )
+ .await;
+ assert_eq!(
+ evaluate_window_name_probe(&mut child, 3, "document.referrer").await,
+ format!("{base}/frame/inner")
+ );
+ assert_eq!(
+ requests
+ .lock()
+ .iter()
+ .find(|(path, _)| path == "/frame/next")
+ .unwrap()
+ .1,
+ format!("{base}/frame/inner")
+ );
+ abort_test_cdp_server(server).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn cross_window_blank_reload_keeps_target_base_and_referrer() {
+ let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(
+ Router::new().fallback(get(|| async { axum::response::Html("<p>loaded</p>") })),
+ "cross-window-blank-reload-environment",
+ );
+ let base = format!("http://{fixture_addr}");
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ let opener_id = create_dynamic_target(&mut browser, 1).await;
+ let mut opener = connect_dynamic_page(addr, &opener_id).await;
+ send_cdp_command(&mut opener, 1, "Page.enable", None, json!({})).await;
+ navigate_dynamic_page_and_wait_for_load(&mut opener, 2, &format!("{base}/source/start")).await;
+ let (_,mut child) = open_auxiliary(addr,&mut opener, "p.document.head.innerHTML='<base href=\"https://popup-base.test/dir/\">';p.document.body.textContent='old'").await;
+ evaluate_window_name_probe(&mut opener, 3, "p.location.reload();true").await;
+ wait_for_value(&mut child, "document.body.textContent", json!("")).await;
+ assert_eq!(
+ evaluate_window_name_probe(&mut child, 3, "[document.baseURI,document.referrer,origin]")
+ .await,
+ json!(["https://popup-base.test/dir/", "", base])
+ );
+ abort_test_cdp_server(server).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn cross_origin_location_functions_accept_other_location_receivers() {
+ let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(
+ Router::new().fallback(get(|| async { axum::response::Html("<p>loaded</p>") })),
+ "borrowed-cross-origin-location-functions",
+ );
+ let base = format!("http://{fixture_addr}");
+ let cross = format!("http://localhost:{}", fixture_addr.port());
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ let opener_id = create_dynamic_target(&mut browser, 1).await;
+ let mut opener = connect_dynamic_page(addr, &opener_id).await;
+ send_cdp_command(&mut opener, 1, "Page.enable", None, json!({})).await;
+ navigate_dynamic_page_and_wait_for_load(&mut opener, 2, &format!("{base}/opener")).await;
+ let (_, mut child) = open_auxiliary(addr, &mut opener, "").await;
+ navigate_dynamic_page_and_wait_for_load(&mut child, 2, &format!("{cross}/child")).await;
+ assert_eq!(
+ evaluate_window_name_probe(
+ &mut opener,
+ 3,
+ r#"
+ (()=>{
+ const setter=Object.getOwnPropertyDescriptor(p.location,'href').set;
+ const replace=p.location.replace;
+ const attempt=f=>{try{f();return 'allowed'}catch(e){return e.name}};
+ const invalid=[attempt(()=>setter.call({},'#bad')),attempt(()=>replace.call({},'#bad'))];
+ setter.call(location,'#setter');
+ const first=location.hash;
+ replace.call(location,'#replace');
+ return [first,location.hash,...invalid];
+ })()
+ "#
+ )
+ .await,
+ json!(["#setter", "#replace", "TypeError", "TypeError"])
+ );
+ assert_eq!(
+ evaluate_window_name_probe(&mut child, 3, "location.href").await,
+ format!("{cross}/child")
+ );
+ abort_test_cdp_server(server).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn saved_popup_locations_cannot_navigate_a_replacement_document() {
+ let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(
+ Router::new().fallback(get(|| async { axum::response::Html("<p>loaded</p>") })),
+ "saved-popup-location-retirement",
+ );
+ let base = format!("http://{fixture_addr}");
+ let cross = format!("http://localhost:{}", fixture_addr.port());
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ let opener_id = create_dynamic_target(&mut browser, 1).await;
+ let mut opener = connect_dynamic_page(addr, &opener_id).await;
+ send_cdp_command(&mut opener, 1, "Page.enable", None, json!({})).await;
+ navigate_dynamic_page_and_wait_for_load(&mut opener, 2, &format!("{base}/opener")).await;
+ for target in [&base, &cross] {
+ let (child_id, mut child) = open_auxiliary(addr, &mut opener, "").await;
+ navigate_dynamic_page_and_wait_for_load(&mut child, 2, &format!("{target}/one")).await;
+ evaluate_window_name_probe(&mut opener, 3, "window.savedLocation=p.location;true").await;
+ navigate_dynamic_page_and_wait_for_load(&mut child, 3, &format!("{target}/two")).await;
+ assert_eq!(
+ evaluate_window_name_probe(
+ &mut opener,
+ 4,
+ &format!(
+ "savedLocation.replace({});true",
+ json!(format!("{target}/stale"))
+ )
+ )
+ .await,
+ true
+ );
+ // A subsequent command observes any synchronously admitted navigation.
+ evaluate_window_name_probe(&mut child, 4, "true").await;
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ assert_eq!(
+ evaluate_window_name_probe(&mut child, 5, "location.href").await,
+ format!("{target}/two")
+ );
+ evaluate_window_name_probe(&mut child, 6, "window.close();true").await;
+ wait_for_target_list(addr, "closed popup removed", |targets| {
+ !targets.iter().any(|target| target["id"] == child_id)
+ })
+ .await;
+ }
+ abort_test_cdp_server(server).await;
+}
diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs
index c88ac7884..4b15b4579 100644
--- a/moli-renderer-v8/src/context_bootstrap.rs
+++ b/moli-renderer-v8/src/context_bootstrap.rs
@@ -146,7 +146,8 @@ pub(crate) use crypto::{
pub(crate) use css_fontface_runtime::{new_font_face_set, rebuild_font_face_set_faces};
pub(crate) use location_navigation::{
LocationNavigationKind, dispatch_top_level_form_navigation_event,
- dispatch_top_level_navigation_event_with_source_element, meta_refresh_navigation_kind,
+ dispatch_top_level_navigation_event_with_source_element, is_native_location,
+ meta_refresh_navigation_kind, navigate_borrowed_location,
navigate_location_object_with_child_navigate_event,
navigate_location_object_with_source_element, navigate_top_level_meta_refresh,
navigate_top_level_same_document_from_browser, resolve_cross_window_location_target,
@@ -286,8 +287,8 @@ pub(crate) use self::image_data::{
pub(crate) use self::indexed_db::{
IndexedDbTaskId, discard_indexed_db_task_by_id, flush_blocked_indexed_db_requests,
flush_indexed_db_task_by_id, flush_next_indexed_db_task, indexed_db_has_pending_tasks,
- install_worker_indexed_db_runtime_state, set_indexed_db_manager_for_context,
- set_worker_indexed_db_task_wake_for_context,
+ install_worker_indexed_db_runtime_state, retain_indexed_db_state_in_retired_realm,
+ set_indexed_db_manager_for_context, set_worker_indexed_db_task_wake_for_context,
};
pub use self::indexed_db::{
Key as IndexedDbKey, ObjectStoreOptions as IndexedDbObjectStoreOptions,
diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/mod.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/mod.rs
index 3651de691..516df89f7 100644
--- a/moli-renderer-v8/src/context_bootstrap/indexed_db/mod.rs
+++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/mod.rs
@@ -54,6 +54,7 @@ pub(crate) use self::tasks::{
};
pub(crate) use self::typed_state::IndexedDbTaskId;
pub(crate) use self::typed_state::deactivate_indexed_db_transaction_after_microtask_checkpoint;
+pub(crate) use self::typed_state::retain_indexed_db_state_in_retired_realm;
pub(in crate::context_bootstrap::indexed_db) use self::typed_state::schedule_indexed_db_transaction_deactivation_after_microtask_checkpoint;
pub(crate) fn flush_blocked_indexed_db_requests(scope: &mut v8::PinScope<'_, '_>) {
diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state.rs
index 1f1249d68..3ffc44720 100644
--- a/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state.rs
+++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::util::RealmValueHandle;
use moli_storage_service::StorageBucketIdentity;
use std::{cell::RefCell, collections::BTreeMap, rc::Rc};
@@ -201,8 +202,8 @@ impl IndexedDbTaskState {
}
struct IndexedDbDatabasesSettleTaskPayload {
- resolver: v8::Global<v8::Value>,
- value: v8::Global<v8::Value>,
+ resolver: RealmValueHandle,
+ value: RealmValueHandle,
reject: bool,
}
@@ -215,30 +216,30 @@ impl IndexedDbDatabasesSettleTaskPayload {
) -> Self {
let resolver: v8::Local<'_, v8::Value> = resolver.into();
Self {
- resolver: v8::Global::new(scope, resolver),
- value: v8::Global::new(scope, value),
+ resolver: RealmValueHandle::new(scope, resolver),
+ value: RealmValueHandle::new(scope, value),
reject,
}
}
}
struct IndexedDbRequestDispatchTaskPayload {
- request: v8::Global<v8::Value>,
+ request: RealmValueHandle,
}
impl IndexedDbRequestDispatchTaskPayload {
fn new(scope: &mut v8::PinScope<'_, '_>, request: v8::Local<'_, v8::Object>) -> Self {
let request: v8::Local<'_, v8::Value> = request.into();
Self {
- request: v8::Global::new(scope, request),
+ request: RealmValueHandle::new(scope, request),
}
}
}
struct IndexedDbOpenTaskPayload {
- request: v8::Global<v8::Value>,
- database: v8::Global<v8::Value>,
- transaction: v8::Global<v8::Value>,
+ request: RealmValueHandle,
+ database: RealmValueHandle,
+ transaction: RealmValueHandle,
old_version: u64,
new_version: u64,
}
@@ -256,9 +257,9 @@ impl IndexedDbOpenTaskPayload {
let database: v8::Local<'_, v8::Value> = database.into();
let transaction: v8::Local<'_, v8::Value> = transaction.into();
Self {
- request: v8::Global::new(scope, request),
- database: v8::Global::new(scope, database),
- transaction: v8::Global::new(scope, transaction),
+ request: RealmValueHandle::new(scope, request),
+ database: RealmValueHandle::new(scope, database),
+ transaction: RealmValueHandle::new(scope, transaction),
old_version,
new_version,
}
@@ -266,7 +267,7 @@ impl IndexedDbOpenTaskPayload {
}
struct IndexedDbBlockedTaskPayload {
- request: v8::Global<v8::Value>,
+ request: RealmValueHandle,
origin: String,
name: String,
version: Option<u64>,
@@ -287,7 +288,7 @@ impl IndexedDbBlockedTaskPayload {
) -> Self {
let request: v8::Local<'_, v8::Value> = request.into();
Self {
- request: v8::Global::new(scope, request),
+ request: RealmValueHandle::new(scope, request),
origin: origin.into(),
name: name.into(),
version,
@@ -315,28 +316,28 @@ struct IndexedDbVersionChangeTaskPayload {
}
struct IndexedDbTransactionTaskPayload {
- transaction: v8::Global<v8::Value>,
+ transaction: RealmValueHandle,
}
impl IndexedDbTransactionTaskPayload {
fn new(scope: &mut v8::PinScope<'_, '_>, transaction: v8::Local<'_, v8::Object>) -> Self {
let transaction: v8::Local<'_, v8::Value> = transaction.into();
Self {
- transaction: v8::Global::new(scope, transaction),
+ transaction: RealmValueHandle::new(scope, transaction),
}
}
}
struct IndexedDbRequestLifecycleState {
- source: v8::Global<v8::Value>,
- transaction: v8::Global<v8::Value>,
+ source: RealmValueHandle,
+ transaction: RealmValueHandle,
ready_state: String,
- result: v8::Global<v8::Value>,
- error: v8::Global<v8::Value>,
+ result: RealmValueHandle,
+ error: RealmValueHandle,
blocked_dispatched: bool,
- pending_result: Option<v8::Global<v8::Value>>,
- pending_error: Option<v8::Global<v8::Value>>,
- pending_cursor: Option<v8::Global<v8::Value>>,
+ pending_result: Option<RealmValueHandle>,
+ pending_error: Option<RealmValueHandle>,
+ pending_cursor: Option<RealmValueHandle>,
pending_cursor_position: Option<f64>,
}
@@ -350,11 +351,11 @@ impl IndexedDbRequestLifecycleState {
let result: v8::Local<'_, v8::Value> = v8::undefined(scope).into();
let error: v8::Local<'_, v8::Value> = v8::null(scope).into();
Self {
- source: v8::Global::new(scope, source),
- transaction: v8::Global::new(scope, transaction),
+ source: RealmValueHandle::new(scope, source),
+ transaction: RealmValueHandle::new(scope, transaction),
ready_state: "pending".to_owned(),
- result: v8::Global::new(scope, result),
- error: v8::Global::new(scope, error),
+ result: RealmValueHandle::new(scope, result),
+ error: RealmValueHandle::new(scope, error),
blocked_dispatched,
pending_result: None,
pending_error: None,
@@ -455,7 +456,7 @@ struct IndexedDbDatabaseLifecycleState {
storage_scope: IndexedDbStorageScope,
closed: bool,
metadata: BTreeMap<String, IndexedDbObjectStoreMetadata>,
- upgrade_transaction: Option<v8::Global<v8::Value>>,
+ upgrade_transaction: Option<RealmValueHandle>,
}
impl IndexedDbDatabaseLifecycleState {
@@ -476,8 +477,8 @@ impl IndexedDbDatabaseLifecycleState {
}
struct IndexedDbCursorLifecycleState {
- request: v8::Global<v8::Value>,
- entries: v8::Global<v8::Value>,
+ request: RealmValueHandle,
+ entries: RealmValueHandle,
key_only: bool,
position: f64,
}
@@ -493,8 +494,8 @@ impl IndexedDbCursorLifecycleState {
let request: v8::Local<'_, v8::Value> = request.into();
let entries: v8::Local<'_, v8::Value> = entries.into();
Self {
- request: v8::Global::new(scope, request),
- entries: v8::Global::new(scope, entries),
+ request: RealmValueHandle::new(scope, request),
+ entries: RealmValueHandle::new(scope, entries),
key_only,
position,
}
@@ -502,8 +503,8 @@ impl IndexedDbCursorLifecycleState {
}
struct IndexedDbObjectStoreLifecycleState {
- transaction: v8::Global<v8::Value>,
- database: v8::Global<v8::Value>,
+ transaction: RealmValueHandle,
+ database: RealmValueHandle,
name: String,
metadata: IndexedDbObjectStoreMetadata,
}
@@ -517,8 +518,8 @@ impl IndexedDbObjectStoreLifecycleState {
) -> Self {
let name = metadata.info.name.clone();
Self {
- transaction: v8::Global::new(scope, v8::Local::<v8::Value>::from(transaction)),
- database: v8::Global::new(scope, v8::Local::<v8::Value>::from(database)),
+ transaction: RealmValueHandle::new(scope, v8::Local::<v8::Value>::from(transaction)),
+ database: RealmValueHandle::new(scope, v8::Local::<v8::Value>::from(database)),
name,
metadata,
}
@@ -526,7 +527,7 @@ impl IndexedDbObjectStoreLifecycleState {
}
struct IndexedDbIndexLifecycleState {
- object_store: v8::Global<v8::Value>,
+ object_store: RealmValueHandle,
info: IndexInfo,
marker: bool,
}
@@ -538,7 +539,7 @@ impl IndexedDbIndexLifecycleState {
info: IndexInfo,
) -> Self {
Self {
- object_store: v8::Global::new(scope, v8::Local::<v8::Value>::from(object_store)),
+ object_store: RealmValueHandle::new(scope, v8::Local::<v8::Value>::from(object_store)),
info,
marker: true,
}
@@ -630,6 +631,64 @@ fn ensure_indexed_db_runtime_state_table_for_context(
table
}
+pub(crate) fn retain_indexed_db_state_in_retired_realm(scope: &mut v8::PinScope<'_, '_>) {
+ let context = scope.get_current_context();
+ let Some(table) = context.get_slot::<RefCell<IndexedDbRuntimeStateTable>>() else {
+ return;
+ };
+ {
+ let mut state = table.borrow_mut();
+ state.tasks.clear();
+ state.databases_settle_tasks.clear();
+ state.request_dispatch_tasks.clear();
+ state.open_tasks.clear();
+ state.blocked_tasks.clear();
+ state.transaction_tasks.clear();
+ for request in state.requests.values_mut() {
+ for value in [
+ &mut request.source,
+ &mut request.transaction,
+ &mut request.result,
+ &mut request.error,
+ ] {
+ value.retain_in_realm(scope);
+ }
+ for value in [
+ &mut request.pending_result,
+ &mut request.pending_error,
+ &mut request.pending_cursor,
+ ]
+ .into_iter()
+ .flatten()
+ {
+ value.retain_in_realm(scope);
+ }
+ }
+ for transaction in state.transactions.values_mut() {
+ transaction.active = false;
+ transaction.operations_waiting_for_start.clear();
+ }
+ for database in state.databases.values_mut() {
+ database.closed = true;
+ if let Some(value) = &mut database.upgrade_transaction {
+ value.retain_in_realm(scope);
+ }
+ }
+ for cursor in state.cursors.values_mut() {
+ cursor.request.retain_in_realm(scope);
+ cursor.entries.retain_in_realm(scope);
+ }
+ for store in state.object_stores.values_mut() {
+ store.transaction.retain_in_realm(scope);
+ store.database.retain_in_realm(scope);
+ }
+ for index in state.indexes.values_mut() {
+ index.object_store.retain_in_realm(scope);
+ }
+ }
+ crate::util::retain_context_v8_handle_state_for_safe_release(context, table);
+}
+
fn indexed_db_runtime_state_table_for_object(
scope: &mut v8::PinScope<'_, '_>,
object: v8::Local<'_, v8::Object>,
@@ -1013,10 +1072,10 @@ pub(super) fn indexed_db_databases_settle_task_payload<'s>(
let table = indexed_db_runtime_state_table_for_object(scope, task);
let table = table.borrow();
let payload = table.databases_settle_tasks.get(&id)?;
- let resolver = v8::Local::new(scope, &payload.resolver);
+ let resolver = payload.resolver.to_local(scope);
let resolver = v8::Local::<v8::Object>::try_from(resolver).ok()?;
let resolver = unsafe { v8::Local::<v8::PromiseResolver>::cast_unchecked(resolver) };
- let value = v8::Local::new(scope, &payload.value);
+ let value = payload.value.to_local(scope);
Some((resolver, value, payload.reject))
}
@@ -1050,7 +1109,7 @@ pub(super) fn indexed_db_request_dispatch_task_request<'s>(
let table = indexed_db_runtime_state_table_for_object(scope, task);
let table = table.borrow();
let payload = table.request_dispatch_tasks.get(&id)?;
- let request = v8::Local::new(scope, &payload.request);
+ let request = payload.request.to_local(scope);
v8::Local::<v8::Object>::try_from(request).ok()
}
@@ -1101,9 +1160,9 @@ pub(super) fn indexed_db_open_task_payload<'s>(
let table = indexed_db_runtime_state_table_for_object(scope, task);
let table = table.borrow();
let payload = table.open_tasks.get(&id)?;
- let request = v8::Local::new(scope, &payload.request);
- let database = v8::Local::new(scope, &payload.database);
- let transaction = v8::Local::new(scope, &payload.transaction);
+ let request = payload.request.to_local(scope);
+ let database = payload.database.to_local(scope);
+ let transaction = payload.transaction.to_local(scope);
Some((
v8::Local::<v8::Object>::try_from(request).ok()?,
v8::Local::<v8::Object>::try_from(database).ok()?,
@@ -1197,7 +1256,7 @@ pub(super) fn indexed_db_blocked_task_payload<'s>(
let table = indexed_db_runtime_state_table_for_object(scope, task);
let table = table.borrow();
let payload = table.blocked_tasks.get(&id)?;
- let request = v8::Local::new(scope, &payload.request);
+ let request = payload.request.to_local(scope);
Some(IndexedDbBlockedTaskPayloadLocals {
request: v8::Local::<v8::Object>::try_from(request).ok()?,
origin: payload.origin.clone(),
@@ -1327,7 +1386,7 @@ pub(super) fn indexed_db_transaction_task_transaction<'s>(
let table = indexed_db_runtime_state_table_for_object(scope, task);
let table = table.borrow();
let payload = table.transaction_tasks.get(&id)?;
- let transaction = v8::Local::new(scope, &payload.transaction);
+ let transaction = payload.transaction.to_local(scope);
v8::Local::<v8::Object>::try_from(transaction).ok()
}
@@ -1468,7 +1527,7 @@ pub(super) fn indexed_db_object_store_transaction<'s>(
let id = indexed_db_typed_state_id(scope, store)?;
let table = indexed_db_runtime_state_table_for_object(scope, store);
let table = table.borrow();
- let transaction = v8::Local::new(scope, &table.object_stores.get(&id)?.transaction);
+ let transaction = table.object_stores.get(&id)?.transaction.to_local(scope);
v8::Local::<v8::Object>::try_from(transaction).ok()
}
@@ -1479,7 +1538,7 @@ pub(super) fn indexed_db_object_store_database<'s>(
let id = indexed_db_typed_state_id(scope, store)?;
let table = indexed_db_runtime_state_table_for_object(scope, store);
let table = table.borrow();
- let database = v8::Local::new(scope, &table.object_stores.get(&id)?.database);
+ let database = table.object_stores.get(&id)?.database.to_local(scope);
v8::Local::<v8::Object>::try_from(database).ok()
}
@@ -1503,7 +1562,7 @@ pub(super) fn indexed_db_index_object_store<'s>(
let id = indexed_db_typed_state_id(scope, index)?;
let table = indexed_db_runtime_state_table_for_object(scope, index);
let table = table.borrow();
- let object_store = v8::Local::new(scope, &table.indexes.get(&id)?.object_store);
+ let object_store = table.indexes.get(&id)?.object_store.to_local(scope);
v8::Local::<v8::Object>::try_from(object_store).ok()
}
@@ -1687,28 +1746,28 @@ fn indexed_db_typed_request_slot_value<'s>(
key: &str,
) -> Option<v8::Local<'s, v8::Value>> {
match key {
- INDEXED_DB_REQUEST_SOURCE_SLOT => Some(v8::Local::new(scope, &request.source)),
- INDEXED_DB_REQUEST_TRANSACTION_SLOT => Some(v8::Local::new(scope, &request.transaction)),
+ INDEXED_DB_REQUEST_SOURCE_SLOT => Some(request.source.to_local(scope)),
+ INDEXED_DB_REQUEST_TRANSACTION_SLOT => Some(request.transaction.to_local(scope)),
INDEXED_DB_REQUEST_READY_STATE_SLOT => {
v8_string(scope, &request.ready_state).map(Into::into)
}
- INDEXED_DB_REQUEST_RESULT_SLOT => Some(v8::Local::new(scope, &request.result)),
- INDEXED_DB_REQUEST_ERROR_SLOT => Some(v8::Local::new(scope, &request.error)),
+ INDEXED_DB_REQUEST_RESULT_SLOT => Some(request.result.to_local(scope)),
+ INDEXED_DB_REQUEST_ERROR_SLOT => Some(request.error.to_local(scope)),
INDEXED_DB_REQUEST_BLOCKED_DISPATCHED_SLOT => {
Some(v8::Boolean::new(scope, request.blocked_dispatched).into())
}
INDEXED_DB_PENDING_RESULT_SLOT => request
.pending_result
.as_ref()
- .map(|value| v8::Local::new(scope, value)),
+ .map(|value| value.to_local(scope)),
INDEXED_DB_PENDING_ERROR_SLOT => request
.pending_error
.as_ref()
- .map(|value| v8::Local::new(scope, value)),
+ .map(|value| value.to_local(scope)),
INDEXED_DB_PENDING_CURSOR_SLOT => request
.pending_cursor
.as_ref()
- .map(|value| v8::Local::new(scope, value)),
+ .map(|value| value.to_local(scope)),
INDEXED_DB_PENDING_CURSOR_POSITION_SLOT => request
.pending_cursor_position
.map(|position| v8::Number::new(scope, position).into()),
@@ -1724,11 +1783,11 @@ fn set_indexed_db_typed_request_slot_value(
) -> bool {
match key {
INDEXED_DB_REQUEST_SOURCE_SLOT => {
- request.source = v8::Global::new(scope, value);
+ request.source = RealmValueHandle::new(scope, value);
true
}
INDEXED_DB_REQUEST_TRANSACTION_SLOT => {
- request.transaction = v8::Global::new(scope, value);
+ request.transaction = RealmValueHandle::new(scope, value);
true
}
INDEXED_DB_REQUEST_READY_STATE_SLOT => {
@@ -1739,11 +1798,11 @@ fn set_indexed_db_typed_request_slot_value(
true
}
INDEXED_DB_REQUEST_RESULT_SLOT => {
- request.result = v8::Global::new(scope, value);
+ request.result = RealmValueHandle::new(scope, value);
true
}
INDEXED_DB_REQUEST_ERROR_SLOT => {
- request.error = v8::Global::new(scope, value);
+ request.error = RealmValueHandle::new(scope, value);
true
}
INDEXED_DB_REQUEST_BLOCKED_DISPATCHED_SLOT => {
@@ -1751,15 +1810,15 @@ fn set_indexed_db_typed_request_slot_value(
true
}
INDEXED_DB_PENDING_RESULT_SLOT => {
- request.pending_result = Some(v8::Global::new(scope, value));
+ request.pending_result = Some(RealmValueHandle::new(scope, value));
true
}
INDEXED_DB_PENDING_ERROR_SLOT => {
- request.pending_error = Some(v8::Global::new(scope, value));
+ request.pending_error = Some(RealmValueHandle::new(scope, value));
true
}
INDEXED_DB_PENDING_CURSOR_SLOT => {
- request.pending_cursor = Some(v8::Global::new(scope, value));
+ request.pending_cursor = Some(RealmValueHandle::new(scope, value));
true
}
INDEXED_DB_PENDING_CURSOR_POSITION_SLOT => {
@@ -1910,7 +1969,7 @@ fn indexed_db_typed_database_slot_value<'s>(
INDEXED_DB_DATABASE_UPGRADE_TRANSACTION_SLOT => database
.upgrade_transaction
.as_ref()
- .map(|value| v8::Local::new(scope, value)),
+ .map(|value| value.to_local(scope)),
_ => None,
}
}
@@ -1952,7 +2011,7 @@ fn set_indexed_db_typed_database_slot_value(
database.upgrade_transaction = if value.is_null_or_undefined() {
None
} else {
- Some(v8::Global::new(scope, value))
+ Some(RealmValueHandle::new(scope, value))
};
true
}
@@ -1966,8 +2025,8 @@ fn indexed_db_typed_cursor_slot_value<'s>(
key: &str,
) -> Option<v8::Local<'s, v8::Value>> {
match key {
- INDEXED_DB_CURSOR_REQUEST_SLOT => Some(v8::Local::new(scope, &cursor.request)),
- INDEXED_DB_CURSOR_ENTRIES_SLOT => Some(v8::Local::new(scope, &cursor.entries)),
+ INDEXED_DB_CURSOR_REQUEST_SLOT => Some(cursor.request.to_local(scope)),
+ INDEXED_DB_CURSOR_ENTRIES_SLOT => Some(cursor.entries.to_local(scope)),
INDEXED_DB_CURSOR_KEY_ONLY_SLOT => Some(v8::Boolean::new(scope, cursor.key_only).into()),
INDEXED_DB_CURSOR_POSITION_SLOT => Some(v8::Number::new(scope, cursor.position).into()),
_ => None,
@@ -1982,11 +2041,11 @@ fn set_indexed_db_typed_cursor_slot_value(
) -> bool {
match key {
INDEXED_DB_CURSOR_REQUEST_SLOT => {
- cursor.request = v8::Global::new(scope, value);
+ cursor.request = RealmValueHandle::new(scope, value);
true
}
INDEXED_DB_CURSOR_ENTRIES_SLOT => {
- cursor.entries = v8::Global::new(scope, value);
+ cursor.entries = RealmValueHandle::new(scope, value);
true
}
INDEXED_DB_CURSOR_KEY_ONLY_SLOT => {
diff --git a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs
index 14862bad3..70005f2e6 100644
--- a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs
+++ b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs
@@ -234,6 +234,17 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>(
force_exact_same_document_navigation: bool,
) {
let owner = runtime_window_owner(scope, location);
+ if let Some(context) = location.get_creation_context(scope)
+ && let Some(host_ptr) = crate::util::context_host_ptr_from_context_slot(context)
+ {
+ let host = unsafe { &*host_ptr };
+ if host
+ .window_execution_context_identity_for_access_check(context)
+ .is_none_or(|identity| !host.window_execution_context_identity_is_current(identity))
+ {
+ return;
+ }
+ }
let location = window_location_for_holder(scope, owner).unwrap_or(location);
let current_href = location_href_slot(scope, location).unwrap_or_default();
let current_url = url::Url::parse(&current_href).ok();
@@ -259,7 +270,11 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>(
};
// Entering the destination realm must not turn it into the initiator.
// Freeze the incumbent Document before navigation events can run script.
- let navigation_source = capture_location_navigation_source(scope, owner, &resolved);
+ let navigation_source = if matches!(kind, LocationNavigationKind::Reload) {
+ None
+ } else {
+ capture_location_navigation_source(scope, owner, &resolved)
+ };
let exact_same_href = current_href == resolved.as_str();
if !matches!(kind, LocationNavigationKind::Reload)
&& exact_same_href
@@ -663,6 +678,43 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>(
}
}
+/// Cross-origin Location functions are borrowable onto any concrete Location.
+/// Validate the native wrapper instead of the function's original receiver.
+pub(crate) fn is_native_location<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ receiver: v8::Local<'s, v8::Object>,
+) -> bool {
+ crate::util::get_private_value(scope, receiver, WINDOW_LOCATION_HREF_SLOT).is_some()
+}
+
+pub(crate) fn navigate_borrowed_location<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ receiver: v8::Local<'s, v8::Object>,
+ value: v8::Local<'s, v8::Value>,
+ kind: LocationNavigationKind,
+) -> bool {
+ if !is_native_location(scope, receiver) {
+ return false;
+ }
+ let raw = match crate::webidl::convert::<crate::webidl::UsvString>(
+ scope,
+ value,
+ crate::webidl::Context::member("Location", "href"),
+ ) {
+ Ok(value) => value.0,
+ Err(error) => {
+ crate::webidl::throw_error(scope, &error);
+ return true;
+ }
+ };
+ let Some(context) = receiver.get_creation_context(scope) else {
+ return true;
+ };
+ let scope = &mut v8::ContextScope::new(scope, context);
+ navigate_location_object_with_child_navigate_event(scope, receiver, kind, Some(raw));
+ true
+}
+
fn capture_location_navigation_source<'s>(
scope: &mut v8::PinScope<'s, '_>,
target: v8::Local<'s, v8::Object>,
@@ -686,7 +738,9 @@ fn capture_location_navigation_source<'s>(
.map(|window| window.frame_sandbox());
let scope = &mut v8::ContextScope::new(scope, source_context);
let host = unsafe { &mut *source_host };
- let dispatch = host.entered_owner_dispatch_scope(scope);
+ let dispatch = host
+ .window_execution_context_identity_for_access_check(source_context)?
+ .dispatch_scope();
let loader = host.document_resource_loader_for_dispatch_scope(dispatch)?;
let initiator_url = host
.document_referrer_source_url_for_dispatch_scope(dispatch)
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 77cc60425..ebc001a37 100644
--- a/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs
+++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs
@@ -30,6 +30,10 @@ pub(in crate::context_bootstrap) fn window_document_getter<'s>(
let Some(receiver) = window_receiver(scope, &args) else {
return;
};
+ if !crate::native_bridge::caller_can_access_window(scope, receiver) {
+ crate::native_bridge::throw_cross_origin_location_security_error(scope);
+ return;
+ }
let Some(host_ptr) = window_host_ptr(scope, receiver) else {
rv.set_null();
return;
diff --git a/moli-renderer-v8/src/document_runtime/events.rs b/moli-renderer-v8/src/document_runtime/events.rs
index 9e8b1feef..55ca49e5a 100644
--- a/moli-renderer-v8/src/document_runtime/events.rs
+++ b/moli-renderer-v8/src/document_runtime/events.rs
@@ -24,6 +24,9 @@ impl DocumentRuntime {
/// The new Document has a fresh handle and receives no old listeners.
pub(crate) fn retain_event_targets_from_initial_document(&mut self, initial: &mut Self) {
self.events = std::mem::take(&mut initial.events);
+ // Timers belong to the retained LocalWindow and concrete realm. Child
+ // and isolated-realm timers have already been canceled by retirement.
+ self.timeouts = std::mem::take(&mut initial.timeouts);
}
pub(crate) fn clear_event_state_for_document_replacement(
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs
index 5936c115c..5553016b4 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs
@@ -8,7 +8,8 @@ mod window;
pub(super) use crate::context_bootstrap::WINDOW_EVENT_HANDLER_PROPERTIES;
pub(in crate::native_bridge::context_host) use window::ChildWindowProxyRecords;
pub(crate) use window::{
- cross_origin_lightweight_popup_id, install_child_window_proxy_access_check_handlers,
- is_cross_origin_location_proxy, is_cross_origin_top_window_proxy,
- throw_cross_origin_location_security_error, throw_cross_origin_type_error,
+ caller_can_access_window, cross_origin_lightweight_popup_id,
+ install_child_window_proxy_access_check_handlers, is_cross_origin_location_proxy,
+ is_cross_origin_top_window_proxy, throw_cross_origin_location_security_error,
+ throw_cross_origin_type_error,
};
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 4ae5b7a5a..0409ead87 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
@@ -644,6 +644,17 @@ fn contexts_can_script_access<'s>(
host.window_execution_context_can_access(accessing_identity, accessed_identity)
}
+pub(crate) fn caller_can_access_window<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ window: v8::Local<'s, v8::Object>,
+) -> bool {
+ let Some(accessed) = window.get_creation_context(scope) else {
+ return false;
+ };
+ let accessing = cross_origin_accessing_context(scope);
+ contexts_can_script_access(scope, accessing, accessed)
+}
+
impl JsContextHost {
pub(in crate::native_bridge::context_host) fn refresh_child_window_access_surfaces_after_origin_mutation(
&mut self,
@@ -2097,7 +2108,6 @@ fn install_cross_origin_location_href<'s>(
) {
let Some(setter) = v8::Function::builder(cross_origin_location_navigate_setter_callback)
.length(1)
- .data(location.into())
.build(scope)
else {
return;
@@ -2700,12 +2710,13 @@ fn cross_origin_location_navigate_setter_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
- if let Ok(expected_receiver) = v8::Local::<v8::Object>::try_from(args.data()) {
- let receiver = cross_origin_proxy_storage_object(scope, args.this());
- if !receiver.strict_equals(expected_receiver.into()) {
- throw_cross_origin_illegal_invocation(scope);
- return;
- }
+ if crate::context_bootstrap::navigate_borrowed_location(
+ scope,
+ args.this(),
+ args.get(0),
+ crate::context_bootstrap::LocationNavigationKind::Assign,
+ ) {
+ return;
}
let _ = cross_origin_location_navigate(scope, args.this(), args.get(0));
}
@@ -2780,6 +2791,22 @@ fn cross_origin_location_replace_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
_rv: v8::ReturnValue<'_, v8::Value>,
) {
+ if crate::context_bootstrap::is_native_location(scope, args.this()) {
+ let Some(parsed) = webidl::parse_args::<CrossOriginLocationReplaceArgs>(scope, &args)
+ else {
+ return;
+ };
+ let Some(value) = v8_string(scope, &parsed.url) else {
+ return;
+ };
+ crate::context_bootstrap::navigate_borrowed_location(
+ scope,
+ args.this(),
+ value.into(),
+ crate::context_bootstrap::LocationNavigationKind::Replace,
+ );
+ return;
+ }
if main_page::is_main_location(scope, args.this()) {
let Some(parsed) = webidl::parse_args::<CrossOriginLocationReplaceArgs>(scope, &args)
else {
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/main_page.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/main_page.rs
index b62a123fa..75e5cbef9 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/main_page.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/main_page.rs
@@ -138,7 +138,6 @@ fn build_accessing_surface<'s>(
);
let setter = v8::Function::builder(cross_origin_location_navigate_setter_callback)
.length(1)
- .data(cross_origin_proxy_storage_object(scope, location).into())
.constructor_behavior(v8::ConstructorBehavior::Throw)
.build(scope)
.expect("cross-origin Location href setter should initialize");
@@ -240,6 +239,12 @@ pub(super) fn navigate<'s>(
let Some(window) = main_location_window(scope, receiver) else {
return false;
};
+ // The stable WindowProxy follows its successor, but a Location belongs to
+ // the Window realm that created it. An old Location must not gain the new
+ // Document's navigation authority through that proxy.
+ if receiver.get_creation_context(scope) != window.get_creation_context(scope) {
+ return false;
+ }
navigate_window(scope, window, value, kind, true)
}
@@ -311,17 +316,6 @@ fn require_window_receiver<'s>(
None
}
-fn caller_can_access_window<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- window: v8::Local<'s, v8::Object>,
-) -> bool {
- let Some(accessed) = window.get_creation_context(scope) else {
- return false;
- };
- let accessing = cross_origin_accessing_context(scope);
- contexts_can_script_access(scope, accessing, accessed)
-}
-
fn shared_cross_origin_location<'s>(
scope: &mut v8::PinScope<'s, '_>,
window: v8::Local<'s, v8::Object>,
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 b560116d0..f88cd1e47 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/core.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs
@@ -26,9 +26,11 @@ impl JsContextHost {
&mut self,
resource: RendererResourceCompletionSender,
navigation: crate::page_task_queue::RendererTopLevelNavigationHandoffSender,
+ service_worker: crate::page_task_queue::RendererPageServiceWorkerTaskSender,
) {
self.resource_completion_tx = resource;
self.top_level_navigation_handoff_tx = navigation;
+ self.service_worker_task_tx = service_worker;
self.page_task_capabilities
.take()
.expect("a reused Window must have its previous complete Page task capabilities");
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 cbe35a0ec..97fec62e5 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
@@ -178,7 +178,7 @@ use child_documents::{ChildDocumentParserStore, PendingChildDocumentNavigation};
use child_events::ChildWindowEventListenerEntry;
use child_frame_runtime::ChildWindowProxyRecords;
pub(crate) use child_frame_runtime::{
- cross_origin_lightweight_popup_id, is_cross_origin_location_proxy,
+ caller_can_access_window, cross_origin_lightweight_popup_id, is_cross_origin_location_proxy,
is_cross_origin_top_window_proxy, throw_cross_origin_location_security_error,
throw_cross_origin_type_error,
};
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 849412d49..f42a208a7 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
@@ -571,6 +571,10 @@ impl JsContextHost {
context_token: RuntimeObservableContextToken,
) -> usize {
crate::observer_runtime::retire_context_token(self, context_token);
+ let indexed_db_retirement = self.retire_indexed_db_context(context_token);
+ if let Some(manager) = self.indexed_db_manager.as_ref() {
+ let _ = manager.close_database_handles(indexed_db_retirement.retired_connections);
+ }
let retired_realm_count = self
.window_execution_context_realms
.remove_token(context_token);
diff --git a/moli-renderer-v8/src/native_bridge/identity.rs b/moli-renderer-v8/src/native_bridge/identity.rs
index 8f0780e63..cc2b5643d 100644
--- a/moli-renderer-v8/src/native_bridge/identity.rs
+++ b/moli-renderer-v8/src/native_bridge/identity.rs
@@ -588,6 +588,7 @@ pub(crate) fn clear_context_wrapper_cache_for_teardown(
crate::util::retain_context_v8_handle_state_for_safe_release(context, wrapper);
}
crate::context_bootstrap::exposed_interfaces::retain_intrinsic_interfaces_in_realm(scope);
+ crate::context_bootstrap::retain_indexed_db_state_in_retired_realm(scope);
}
#[derive(Debug, Default)]
diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rs
index 7e677c128..314856edd 100644
--- a/moli-renderer-v8/src/native_bridge/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/mod.rs
@@ -8,7 +8,7 @@ mod context_host;
mod current_input;
pub(crate) use context_host::{
JsContextHost, JsContextHostPageTaskCapabilities, PendingScrollObservableEffects,
- PostParseAutofocusAdmission, ServiceWorkerWindowOwner,
+ PostParseAutofocusAdmission, ServiceWorkerWindowOwner, caller_can_access_window,
};
pub(crate) use current_input::{
CurrentInputEvent, CurrentInputEventScope, InputNavigationPolicy, navigation_policy_from_event,
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 77852e48f..152678521 100644
--- a/moli-renderer-v8/src/script_vm/initial_window_document.rs
+++ b/moli-renderer-v8/src/script_vm/initial_window_document.rs
@@ -114,6 +114,7 @@ impl ScriptVm {
host.rebind_initial_main_document_senders(
resource_completion,
page_task_tx.top_level_navigation_handoff_sender(),
+ page_task_tx.service_worker_task_sender(),
);
host.retire_document_resource_loader(
crate::native_bridge::WindowDocumentOwner::Frame(
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 521b0bda1..699e240de 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
@@ -488,6 +488,85 @@ fn isolated_realm_destruction_retires_pending_opfs_task() {
"destroying the Promise relevant realm must release its OPFS resolver"
);
}
+
+#[test]
+fn isolated_realm_destruction_releases_indexed_db_without_closing_default_world() {
+ let mut page = new_storage_page_task_executor_test_vm("https://isolated-idb-retirement.test/");
+ page.eval(
+ "window.defaultOpen=false;const request=indexedDB.open('default-idb',1);request.onupgradeneeded=()=>request.result.createObjectStore('store');request.onsuccess=()=>{window.defaultDb=request.result;defaultOpen=true}",
+ ).unwrap();
+ assert_eq!(
+ page.eval_after_selected_page_tasks("defaultOpen").unwrap(),
+ "true"
+ );
+ let isolated_id = page.create_isolated_world("idb-retirement", false).unwrap();
+ page.eval_in_isolated_context(
+ isolated_id,
+ "window.opened=false;window.payload=new Array(1024*1024).fill(17);const request=indexedDB.open('isolated-idb',1);request.onsuccess=()=>{window.db=request.result;opened=true}",
+ ).unwrap();
+ page.eval_after_selected_page_tasks("true").unwrap();
+ assert_eq!(
+ page.eval_in_isolated_context(isolated_id, "opened")
+ .unwrap(),
+ "true"
+ );
+ let context_ptr = &page
+ .page_isolated_world_contexts
+ .context(isolated_id)
+ .unwrap()
+ .context as *const _;
+ let weak = page
+ .with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, host_ptr| {
+ let context = scope.get_current_context();
+ let window = context.global(scope);
+ let db_key = crate::util::v8str(scope, "db");
+ let db = window.get(scope, db_key.into()).unwrap();
+ let default = unsafe { &*host_ptr }.page_default_context(scope).unwrap();
+ let retained_key = crate::util::v8str(scope, "retainedIsolatedDb");
+ default.global(scope).set(scope, retained_key.into(), db);
+ Ok(v8::Weak::new(scope, context))
+ })
+ .unwrap();
+ page.destroy_isolated_world_context(isolated_id);
+ for _ in 0..5 {
+ page.renderer_document_isolate
+ .with_renderer_document_isolate_mut(|isolate| isolate.low_memory_notification());
+ }
+ assert_eq!(
+ page.eval("retainedIsolatedDb.name").unwrap(),
+ "isolated-idb",
+ "a retained IndexedDB wrapper must preserve its native data after realm retirement"
+ );
+ assert!(
+ page.with_default_context_scope_and_checkpoint_for_test(|scope, _| Ok(weak
+ .to_local(scope)
+ .is_some()))
+ .unwrap()
+ );
+ page.eval("delete window.retainedIsolatedDb").unwrap();
+ for _ in 0..5 {
+ page.renderer_document_isolate
+ .with_renderer_document_isolate_mut(|isolate| isolate.low_memory_notification());
+ }
+ assert!(
+ page.with_default_context_scope_and_checkpoint_for_test(|scope, _| Ok(weak
+ .to_local(scope)
+ .is_none()))
+ .unwrap(),
+ "no IndexedDB host handle may keep a retired isolated realm alive"
+ );
+ assert_eq!(
+ page.eval("defaultDb.transaction('store').objectStore('store').name")
+ .unwrap(),
+ "store",
+ "retiring one token must leave the default world's connection open"
+ );
+ page.eval("defaultDb.close();window.upgraded=false;const upgrade=indexedDB.open('isolated-idb',2);upgrade.onsuccess=()=>{upgraded=true;upgrade.result.close()}").unwrap();
+ assert_eq!(
+ page.eval_after_selected_page_tasks("upgraded").unwrap(),
+ "true"
+ );
+}
#[test]
fn page_context_teardown_releases_opfs_handle_and_directory_iterator_registrations() {
let mut vm = new_storage_page_task_executor_test_vm("https://opfs-iterator-teardown.test/");
diff --git a/moli-renderer-v8/src/util.rs b/moli-renderer-v8/src/util.rs
index fe42493e7..13a40f1b6 100644
--- a/moli-renderer-v8/src/util.rs
+++ b/moli-renderer-v8/src/util.rs
@@ -141,6 +141,52 @@ impl RealmObjectHandle {
}
}
+/// Value edges owned by native state become ordinary V8 edges when a realm
+/// retires. A private holder supports primitives as well as objects and keeps
+/// cross-realm values attached to the realm that owns the native state.
+pub(crate) enum RealmValueHandle {
+ Strong(v8::Global<v8::Value>),
+ Traced(RealmObjectHandle),
+}
+
+impl RealmValueHandle {
+ const VALUE: &str = "__moliRetainedRealmValue";
+
+ pub(crate) fn new(scope: &mut v8::PinScope<'_, '_>, value: v8::Local<'_, v8::Value>) -> Self {
+ if page_context_is_detached_document(scope.get_current_context()) {
+ Self::traced(scope, value)
+ } else {
+ Self::Strong(v8::Global::new(scope, value))
+ }
+ }
+
+ fn traced(scope: &mut v8::PinScope<'_, '_>, value: v8::Local<'_, v8::Value>) -> Self {
+ let holder = v8::Object::new(scope);
+ set_private_value(scope, holder, Self::VALUE, value);
+ Self::Traced(RealmObjectHandle::traced(scope, holder))
+ }
+
+ pub(crate) fn to_local<'s>(
+ &self,
+ scope: &mut v8::PinScope<'s, '_>,
+ ) -> v8::Local<'s, v8::Value> {
+ match self {
+ Self::Strong(value) => v8::Local::new(scope, value),
+ Self::Traced(holder) => holder
+ .to_local(scope)
+ .and_then(|holder| get_private_value(scope, holder, Self::VALUE))
+ .unwrap_or_else(|| v8::undefined(scope).into()),
+ }
+ }
+
+ pub(crate) fn retain_in_realm(&mut self, scope: &mut v8::PinScope<'_, '_>) {
+ if let Self::Strong(value) = self {
+ let value = v8::Local::new(scope, &*value);
+ *self = Self::traced(scope, value);
+ }
+ }
+}
+
/// Materializes the unexposed prototype described by a WebIDL iterator
/// FunctionTemplate. The temporary constructor is an implementation detail, so
/// its back-reference must not leak onto the iterator prototype.