fix(navigation): preserve inherited top-level about:blank state

This commit is contained in:
ldm0
2026-11-24 14:36:03 +08:00
parent c2ca6be3f0
commit efca9affd1
50 changed files with 921 additions and 132 deletions
+3 -2
View File
@@ -25,8 +25,9 @@ pub use moli_renderer_v8::{
ExceptionOrigin, ProcessEnvironmentOwner,
};
pub use moli_renderer_v8::{
PageId, RendererBrowserContextRuntimeId, RendererDocumentLifecycleIdentity,
RendererDocumentTitleChanged, RendererNavigationHistory, RendererNavigationHistoryRequest, RendererOutputCursor, RendererOutputFence,
PageId, RendererAboutDocumentState, RendererBrowserContextRuntimeId,
RendererDocumentLifecycleIdentity, RendererDocumentTitleChanged, RendererNavigationHistory,
RendererNavigationHistoryRequest, RendererOutputCursor, RendererOutputFence,
RendererOutputFenceLeaseId, RendererOutputItem, RendererOutputPublication,
RendererOutputPublicationOrdering, RendererOutputRecord, RendererOutputResidenceIdentity,
RendererOutputStreamCloseReason, RendererOutputStreamControl, RendererOutputStreamEpoch,
@@ -216,6 +216,21 @@ impl PreparedRendererNavigation {
)
}
crate::conn::TopLevelNavigationRequest::Location(navigation) => {
let navigation_history = url::Url::parse(navigation.url())
.ok()
.and_then(|url| {
conn.renderer_navigation_request_for_owner(
&owner,
&url,
navigation.browser_navigation_kind()
== moli_fetch::BrowserNavigationRequestKind::Reload,
navigation.navigation_history().cloned(),
)
})
.map(|history| {
history
.with_about_document_state(navigation.about_document_state().cloned())
});
let start = super::navigation::start_session_owner_navigation_from_renderer(
conn,
&owner,
@@ -224,7 +239,7 @@ impl PreparedRendererNavigation {
navigation.request_body(),
navigation.request_headers(),
navigation.browser_navigation_kind(),
navigation.navigation_history().cloned(),
navigation_history,
navigation.web_mcp_invocation(),
Some(match navigation.browser_navigation_kind() {
moli_fetch::BrowserNavigationRequestKind::Reload => {
@@ -435,3 +435,4 @@ mod resources;
mod runtime;
mod same_document_history;
mod scripts;
mod top_level_about_blank;
@@ -0,0 +1,385 @@
use super::*;
async fn about_blank_server() -> (String, tokio::task::JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let task = tokio::spawn(async move {
axum::serve(
listener,
axum::Router::new()
.route(
"/sandbox",
axum::routing::get(|| async {
(
[(
"Content-Security-Policy",
"sandbox allow-scripts allow-top-navigation",
)],
axum::response::Html("<!doctype html><body>opaque source"),
)
}),
)
.route(
"/csp",
axum::routing::get(|| async {
(
[("Content-Security-Policy", "script-src 'none'")],
axum::response::Html("<!doctype html><body>protected source"),
)
}),
)
.route(
"/parent",
axum::routing::get(|| async {
axum::response::Html("<!doctype html><iframe id=f src='/child'></iframe>")
}),
)
.fallback(|| async { axum::response::Html("<!doctype html><body>source") }),
)
.await
.unwrap();
});
(origin, task)
}
async fn about_blank_command(
ctx: &mut TestContext,
method: &str,
params: serde_json::Value,
) -> serde_json::Value {
ctx.process_and_wait_for_response_async(json!({
"id": 1, "sessionId": "SID-1", "method": method, "params": params,
}))
.await;
let response = take_response_by_id(ctx, 1);
assert!(response.get("error").is_none(), "{method}: {response:?}");
response["result"].clone()
}
async fn about_blank_evaluate(ctx: &mut TestContext, expression: &str) -> serde_json::Value {
let result = about_blank_command(
ctx,
"Runtime.evaluate",
json!({
"expression": expression, "returnByValue": true, "userGesture": true,
}),
)
.await;
assert!(
result.get("exceptionDetails").is_none(),
"{expression}: {result:?}"
);
result["result"]["value"].clone()
}
async fn about_blank_load(ctx: &mut TestContext, method: &str, params: serde_json::Value) {
ctx.sent.clear();
let result = about_blank_command(ctx, method, params).await;
assert!(result.get("errorText").is_none(), "{result:?}");
wait_until_frame_stopped_loading(ctx, "TID-1").await;
}
async fn about_blank_context(url: &str) -> TestContext {
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
ctx.enable_page_events_for_test(Some("SID-1"));
about_blank_load(&mut ctx, "Page.navigate", json!({"url": url})).await;
ctx
}
async fn about_blank_state(ctx: &mut TestContext) -> serde_json::Value {
about_blank_evaluate(
ctx,
r#"(() => {
const attempt = f => { try { return f(); } catch (e) { return e.name; } };
return {url:location.href, origin, locationOrigin:location.origin,
base:document.baseURI, domain:document.domain, secure:isSecureContext,
referrer:document.referrer,
storage:attempt(() => localStorage.getItem('about-blank-origin')),
entries:navigation.entries().map(e => e.url),
current:navigation.currentEntry?.url ?? null,
from:navigation.activation?.from?.url ?? null};
})()"#,
)
.await
}
#[tokio::test(flavor = "multi_thread")]
async fn top_level_about_blank_inherits_native_state_through_reload_and_traversal() {
let (origin, server) = about_blank_server().await;
let source = format!("{origin}/source");
let destination = format!("{origin}/destination");
for script in [
"location.assign('about:blank'); true",
"navigation.navigate('about:blank'); true",
"const a=document.createElement('a'); a.href='about:blank'; document.body.append(a); a.click(); true",
] {
let mut ctx = about_blank_context(&source).await;
about_blank_evaluate(
&mut ctx,
r#"
localStorage.setItem('about-blank-origin', 'source');
const base=document.createElement('base');
base.href='https://base.example/first/'; document.head.append(base);
addEventListener('beforeunload', () => base.href='https://base.example/second/');
Object.defineProperty(globalThis, 'origin', {value:'https://spoof.example'});
Object.defineProperty(document, 'baseURI', {value:'https://spoof.example/'});
true;
"#,
)
.await;
ctx.sent.clear();
about_blank_evaluate(&mut ctx, script).await;
wait_until_frame_stopped_loading(&mut ctx, "TID-1").await;
let mut expected = json!({
"url":"about:blank", "origin":origin, "locationOrigin":"null",
"base":"https://base.example/first/", "domain":"127.0.0.1", "secure":true,
"referrer":format!("{origin}/"), "storage":"source",
"entries":[source, "about:blank"], "current":"about:blank", "from":source,
});
assert_eq!(about_blank_state(&mut ctx).await, expected, "{script}");
about_blank_evaluate(&mut ctx, "globalThis.oldRealm=true; true").await;
about_blank_load(&mut ctx, "Page.reload", json!({})).await;
assert_eq!(
about_blank_evaluate(&mut ctx, "typeof oldRealm").await,
"undefined"
);
expected["from"] = json!("about:blank");
assert_eq!(
about_blank_state(&mut ctx).await,
expected,
"reload: {script}"
);
let history = about_blank_command(&mut ctx, "Page.getNavigationHistory", json!({})).await;
let blank_id =
history["entries"][history["currentIndex"].as_u64().unwrap() as usize]["id"].clone();
about_blank_load(&mut ctx, "Page.navigate", json!({"url": destination})).await;
let departed = about_blank_state(&mut ctx).await;
assert_eq!(departed["base"], destination);
assert_eq!(
departed["entries"],
json!([source, "about:blank", destination])
);
about_blank_load(
&mut ctx,
"Page.navigateToHistoryEntry",
json!({"entryId":blank_id}),
)
.await;
expected["entries"] = json!([source, "about:blank", destination]);
expected["from"] = json!(destination);
assert_eq!(
about_blank_state(&mut ctx).await,
expected,
"traversal: {script}"
);
}
server.abort();
}
#[tokio::test(flavor = "multi_thread")]
async fn top_level_about_blank_without_author_initiator_stays_opaque() {
let (origin, server) = about_blank_server().await;
for source in ["about:blank".to_owned(), format!("{origin}/source")] {
let mut ctx = about_blank_context(&source).await;
about_blank_load(&mut ctx, "Page.navigate", json!({"url":"about:blank"})).await;
for reload in [false, true] {
if reload {
about_blank_load(&mut ctx, "Page.reload", json!({})).await;
}
assert_eq!(
about_blank_state(&mut ctx).await,
json!({
"url":"about:blank", "origin":"null", "locationOrigin":"null",
"base":"about:blank", "domain":"", "secure":false, "referrer":"",
"storage":"SecurityError", "entries":[], "current":null, "from":null,
}),
"{source}, reload={reload}"
);
}
}
server.abort();
}
#[tokio::test(flavor = "multi_thread")]
async fn top_level_about_blank_inherits_opaque_source_base_without_enabling_navigation() {
let (origin, server) = about_blank_server().await;
for source in [
format!("{origin}/sandbox"),
"data:text/html,source".to_owned(),
] {
let mut ctx = about_blank_context(&source).await;
ctx.sent.clear();
about_blank_evaluate(&mut ctx, "location.href='about:blank'; true").await;
wait_until_frame_stopped_loading(&mut ctx, "TID-1").await;
for reload in [false, true] {
if reload {
about_blank_load(&mut ctx, "Page.reload", json!({})).await;
}
assert_eq!(
about_blank_state(&mut ctx).await,
json!({
"url":"about:blank", "origin":"null", "locationOrigin":"null",
"base":source, "domain":"", "secure":false, "referrer":"",
"storage":"SecurityError", "entries":[], "current":null, "from":null,
}),
"{source}, reload={reload}"
);
}
}
server.abort();
}
#[tokio::test(flavor = "multi_thread")]
async fn top_level_about_blank_inherits_response_and_meta_csp() {
let (origin, server) = about_blank_server().await;
for source in ["/csp", "/meta-csp"] {
let mut ctx = about_blank_context(&format!("{origin}{source}")).await;
if source == "/meta-csp" {
about_blank_evaluate(
&mut ctx,
r#"
const m=document.createElement('meta'); m.httpEquiv='Content-Security-Policy';
m.content="script-src 'none'"; document.head.append(m); true;
"#,
)
.await;
}
ctx.sent.clear();
about_blank_evaluate(&mut ctx, "location.href='about:blank'; true").await;
wait_until_frame_stopped_loading(&mut ctx, "TID-1").await;
for reload in [false, true] {
if reload {
about_blank_load(&mut ctx, "Page.reload", json!({})).await;
}
assert_eq!(
about_blank_evaluate(
&mut ctx,
r#"(() => {
const s=document.createElement('script'); s.textContent='globalThis.inlineRan=true';
document.head.append(s); return globalThis.inlineRan === true;
})()"#
)
.await,
false,
"{source}, reload={reload}"
);
}
}
server.abort();
}
#[tokio::test(flavor = "multi_thread")]
async fn top_level_about_blank_uses_the_navigation_initiator_document_base() {
let (origin, server) = about_blank_server().await;
for (script, base_path) in [
("top.location.href='about:blank'", "/child"),
("top.navigation.navigate('about:blank')", "/parent"),
(
"const a=document.createElement('a'); a.href='about:blank'; a.target='_top'; document.body.append(a); a.click()",
"/child",
),
] {
let mut ctx = about_blank_context(&format!("{origin}/parent")).await;
ctx.sent.clear();
about_blank_evaluate(
&mut ctx,
&format!("f.contentWindow.eval({}); true", json!(script)),
)
.await;
wait_until_frame_stopped_loading(&mut ctx, "TID-1").await;
let state = about_blank_state(&mut ctx).await;
assert_eq!(state["origin"], origin, "{script}");
assert_eq!(state["base"], format!("{origin}{base_path}"), "{script}");
assert_eq!(state["url"], "about:blank");
}
// The caller can be in the parent realm while activating a child link.
// The link's node Document, rather than the incumbent script, is the source.
let mut ctx = about_blank_context(&format!("{origin}/parent")).await;
ctx.sent.clear();
about_blank_evaluate(&mut ctx, "const a=f.contentDocument.createElement('a'); a.href='about:blank'; a.target='_top'; f.contentDocument.body.append(a); a.click(); true").await;
wait_until_frame_stopped_loading(&mut ctx, "TID-1").await;
assert_eq!(
about_blank_state(&mut ctx).await["base"],
format!("{origin}/child")
);
server.abort();
}
#[tokio::test(flavor = "multi_thread")]
async fn top_level_about_blank_preserves_the_selected_referrer() {
let (origin, server) = about_blank_server().await;
let source = format!("{origin}/source");
for (script, expected) in [
(
"const m=document.createElement('meta'); m.name='referrer'; m.content='no-referrer'; document.head.append(m); location.href='about:blank'; true",
"",
),
(
"const a=document.createElement('a'); a.href='about:blank'; a.rel='noreferrer'; document.body.append(a); a.click(); true",
"",
),
(
"const a=document.createElement('a'); a.href='about:blank'; a.referrerPolicy='no-referrer'; document.body.append(a); a.click(); true",
"",
),
(
"const a=document.createElement('a'); a.href='about:blank'; a.referrerPolicy='unsafe-url'; document.body.append(a); a.click(); true",
source.as_str(),
),
] {
let mut ctx = about_blank_context(&source).await;
ctx.sent.clear();
about_blank_evaluate(&mut ctx, script).await;
wait_until_frame_stopped_loading(&mut ctx, "TID-1").await;
assert_eq!(
about_blank_state(&mut ctx).await["referrer"],
expected,
"{script}"
);
about_blank_load(&mut ctx, "Page.reload", json!({})).await;
assert_eq!(
about_blank_state(&mut ctx).await["referrer"],
expected,
"reload: {script}"
);
}
server.abort();
}
#[tokio::test(flavor = "multi_thread")]
async fn top_level_about_blank_shares_its_storage_partition_with_same_origin_http_children() {
let (origin, server) = about_blank_server().await;
let mut ctx = about_blank_context(&format!("{origin}/source")).await;
ctx.sent.clear();
about_blank_evaluate(&mut ctx, "localStorage.setItem('blank-child','local'); sessionStorage.setItem('blank-child','session'); location.href='about:blank'; true").await;
wait_until_frame_stopped_loading(&mut ctx, "TID-1").await;
let child_url = json!(format!("{origin}/child"));
let result = about_blank_command(
&mut ctx,
"Runtime.evaluate",
json!({
"expression": format!(r#"new Promise(resolve => {{
const f=document.createElement('iframe');
f.onload=() => {{
resolve([f.contentWindow.location.href, f.contentWindow.origin,
f.contentWindow.isSecureContext,
f.contentWindow.localStorage.getItem('blank-child'),
f.contentWindow.sessionStorage.getItem('blank-child')]);
f.remove();
}};
f.src={child_url}; document.body.append(f);
}})"#),
"awaitPromise": true, "returnByValue": true,
}),
)
.await;
assert!(result.get("exceptionDetails").is_none(), "{result}");
assert_eq!(
result["result"]["value"],
json!([child_url, origin, true, "local", "session"])
);
server.abort();
}
@@ -334,6 +334,7 @@ pub(crate) fn queue_related_popup_navigation<'s>(
Some(navigation_source),
false,
None,
None,
);
}
@@ -581,6 +582,19 @@ fn navigate_location_object_with_options<'s>(
}
}
let exact_same_href = current_href == resolved.as_str();
let about_document_state = context_host_ptr_from_global_bridge(scope).and_then(|host_ptr| {
let host = unsafe { &*host_ptr };
let source_handle = source_element
.and_then(|element| {
crate::native_bridge::node_runtime_and_handle_from_object(scope, element).ok()
})
.map(|(_, handle)| handle);
host.capture_about_document_state(
location_navigation_initiator_scope(scope, host),
&resolved,
source_handle,
)
});
let owner = runtime_window_owner(scope, location);
let source_can_access_target = source_can_access_target.unwrap_or_else(|| {
let Some(host_ptr) = context_host_ptr_for_navigation_owner(scope, owner) else {
@@ -1017,6 +1031,7 @@ fn navigate_location_object_with_options<'s>(
navigation_source,
browser_owned_hyperlink,
named_hyperlink_popup,
about_document_state,
);
}
@@ -1037,6 +1052,7 @@ fn navigate_top_level_cross_document_location<'s>(
navigation_source: Option<LocationNavigationSource>,
browser_owned_hyperlink: bool,
named_hyperlink_popup: Option<crate::native_bridge::element::NamedHyperlinkPopup>,
about_document_state: Option<crate::runtime::RendererAboutDocumentState>,
) {
let popup_id = crate::native_bridge::lightweight_popup_id_from_window(scope, owner);
if let Some(event) = navigate_event
@@ -1143,6 +1159,7 @@ fn navigate_top_level_cross_document_location<'s>(
moli_fetch::BrowserNavigationRequestKind::Navigate
},
navigation_source,
about_document_state,
);
}
@@ -216,6 +216,13 @@ pub(in crate::context_bootstrap) fn navigation_navigate_callback<'s>(
return;
};
let current_url = url::Url::parse(&current_href).ok();
let about_document_state = context_host_ptr_from_global_bridge(scope).and_then(|host_ptr| {
unsafe { &*host_ptr }.capture_about_document_state(
crate::native_bridge::OwnerDispatchScope::Top,
&next_url,
None,
)
});
let can_update_current_entry = navigation_can_update_current_entry(scope, args.this());
// History behavior chooses which entry changes, not whether the navigation
// replaces the Document. Even an empty fragment is a fragment navigation.
@@ -641,6 +648,7 @@ pub(in crate::context_bootstrap) fn navigation_navigate_callback<'s>(
&next_url,
navigate_history_kind,
Some((navigation, outcome.signal)),
about_document_state,
));
return;
}
@@ -651,6 +659,7 @@ pub(in crate::context_bootstrap) fn navigation_navigate_callback<'s>(
&next_url,
navigate_history_kind,
None,
about_document_state,
));
}
@@ -25,6 +25,7 @@ pub(super) fn handle_navigation_navigate_cross_document<'s>(
next_url: &url::Url,
navigate_history_kind: NavigationNavigateHistoryKind,
navigation_signal: Option<(v8::Local<'s, v8::Object>, Option<v8::Local<'s, v8::Object>>)>,
about_document_state: Option<crate::runtime::RendererAboutDocumentState>,
) -> v8::Local<'s, v8::Value> {
let current_navigation_index = navigation_current_entry_index(scope, owner).unwrap_or(0);
let current_index = history_index(scope, history);
@@ -73,8 +74,11 @@ pub(super) fn handle_navigation_navigate_cross_document<'s>(
let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
return v8::undefined(scope).into();
};
unsafe { &mut *host_ptr }
.record_pending_location_navigation(next_url.clone(), Some(entry_seed));
unsafe { &mut *host_ptr }.record_pending_location_navigation(
next_url.clone(),
Some(entry_seed),
about_document_state,
);
return navigation_signal
.map(|(navigation, signal)| {
navigation_cross_document_pending_result(
@@ -1,8 +1,5 @@
use super::history_runtime::native;
use super::navigation_window::{
runtime_window_dispatch_scope, runtime_window_owner,
runtime_window_uses_top_level_history_model,
};
use super::navigation_window::runtime_window_dispatch_scope;
use crate::context_bootstrap::navigation_entry::wrappers as entry_wrappers;
use crate::util::{context_host_ptr_from_global_bridge, serialize_v8_iter_array};
use moli_history::HistoryEntryRef;
@@ -64,14 +61,6 @@ fn visible_navigation_entries<'s>(
if url::Url::parse(&current_entry.borrow().url).is_err() {
return vec![current_entry];
}
let owner = runtime_window_owner(scope, current_wrapper);
let top_level = runtime_window_uses_top_level_history_model(scope, owner);
let hidden = |entry: &HistoryEntryRef| {
top_level
&& !Rc::ptr_eq(entry, &current_entry)
&& entry.borrow().inherited_origin.is_none()
&& entry.borrow().url.split('#').next() == Some("about:blank")
};
let same_origin = |entry: &HistoryEntryRef| {
let current = current_entry.borrow();
let candidate = entry.borrow();
@@ -82,7 +71,7 @@ fn visible_navigation_entries<'s>(
let mut start = current_index;
while start > 0 {
let candidate = &entries[start - 1];
if !hidden(candidate) && !same_origin(candidate) {
if !same_origin(candidate) {
break;
}
start -= 1;
@@ -90,7 +79,7 @@ fn visible_navigation_entries<'s>(
let mut end = current_index;
while end + 1 < entries.len() {
let candidate = &entries[end + 1];
if !hidden(candidate) && !same_origin(candidate) {
if !same_origin(candidate) {
break;
}
end += 1;
@@ -102,9 +91,6 @@ fn visible_navigation_entries<'s>(
} else {
entry
};
if hidden(entry) {
continue;
}
let index = entry.borrow().index;
if let Some(position) = visible
.iter()
@@ -117,8 +117,9 @@ pub(super) fn publish_top_level_navigation_history<'s>(
&mut entries,
);
let traversable = host.session_histories.get_mut(None).clone();
host.top_level_navigation_history()
.publish(NavigationHistoryEntrySeed {
let about_document_state = host.current_about_document_state();
host.top_level_navigation_history().publish(
NavigationHistoryEntrySeed {
session_history: moli_page_types::SessionHistorySeed {
traversable: Some(Box::new(traversable)),
..Default::default()
@@ -128,7 +129,9 @@ pub(super) fn publish_top_level_navigation_history<'s>(
// Activation belongs to the navigation operation, not the source
// history. Reading public activation properties could invoke JS here.
activation: None,
});
},
about_document_state,
);
}
pub(super) fn serialize_navigation_entry_object<'s>(
@@ -70,7 +70,7 @@ 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()));
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)
@@ -303,13 +303,7 @@ pub(super) fn navigation_document_has_opaque_origin<'s>(
.is_some_and(|origin| origin == "null");
}
if runtime_window_is_global(scope, owner) {
// A response sandbox can make an HTTP(S) Document opaque without
// changing its URL. Use the active Document's policy, not just the URL.
return host
.document_policy_container()
.sandbox
.forces_opaque_origin
|| top_level_navigation_document_has_opaque_origin(host.document_url());
return host.main_document_origin() == "null";
}
let Some(handle) = child_browsing_context_handle_for_runtime_owner(scope, owner) else {
return false;
@@ -348,14 +342,6 @@ pub(crate) fn replace_navigation_unload_event_active<'s>(
previous
}
pub(super) fn url_is_about_blank_document(url: &url::Url) -> bool {
moli_url::is_about_blank(url)
}
fn top_level_navigation_document_has_opaque_origin(url: &url::Url) -> bool {
!url_is_about_blank_document(url) && url.origin().ascii_serialization() == "null"
}
pub(super) fn navigation_document_base_url<'s>(
scope: &mut v8::PinScope<'s, '_>,
owner: v8::Local<'s, v8::Object>,
@@ -556,7 +556,7 @@ fn clipboard_permission_denied<'s>(
};
let scope = &mut v8::ContextScope::new(scope, context);
let host = unsafe { &mut *host_ptr };
let embedding_origin = moli_url::origin_ascii_serialization(host.document_url());
let embedding_origin = host.main_document_origin();
let Some(requesting_origin) = host
.current_runtime_window_execution_context_identity(scope)
.and_then(|identity| host.storage_context_for_window_execution_context_identity(identity))
@@ -1870,11 +1870,15 @@ fn install_window_runtime_state<'s>(
global,
runtime.document_url().as_str(),
)?;
let origin = if runtime.document_sandbox_policy().forces_opaque_origin {
"null".into()
} else {
moli_url::origin_ascii_serialization(runtime.document_url())
};
let origin = context_host_ptr_from_global_bridge(scope)
.map(|host| unsafe { &*host }.main_document_origin())
.unwrap_or_else(|| {
if runtime.document_sandbox_policy().forces_opaque_origin {
"null".into()
} else {
moli_url::origin_ascii_serialization(runtime.document_url())
}
});
set_window_origin_runtime_state(scope, global, &origin)?;
let console = ConsoleObjectDeclaration::default()
@@ -178,7 +178,7 @@ fn current_window_storage_access_request_context(
.storage_key()
.serialized_storage_key();
let storage_key = moli_storage_key::deserialize_serialized_storage_key(&ambient_storage_key)?;
let embedding_origin = moli_url::origin_ascii_serialization(host.document_url());
let embedding_origin = host.main_document_origin();
let permission = StorageAccessPermissionState::from_label(host.permission_state_for_origins(
"storage-access",
storage_key.origin(),
+1 -1
View File
@@ -244,7 +244,7 @@ pub use runtime::{
CompletedWorkerRuntimeInspectorCommandDispatch, DetachedParserScriptFetchContinuation,
DevToolsSessionKey, ExternalRawDocumentBodyStream, JsRuntime, JsRuntimeOwner, PageId,
PendingHtmlPage, PendingRendererPageReplacement, PendingWorkerRuntimeInspectorSessionResponse,
PreparedRendererDocument, RendererAccessibilityPayloadsForObjectId,
PreparedRendererDocument, RendererAboutDocumentState, RendererAccessibilityPayloadsForObjectId,
RendererActivityDiagnostics, RendererAgentAttachmentId, RendererAutofillAddressField,
RendererAutofillCreditCard, RendererAutofillTriggerOutcome, RendererAutofillTriggerRequest,
RendererAuxiliaryDocumentResponse, RendererAuxiliaryNavigationKind, RendererAuxiliaryWindow,
@@ -43,10 +43,7 @@ impl PageScriptHost {
};
let scripting_enabled = self.child_browsing_context_scripting_enabled(handle);
let parent_scope = self
.child_browsing_context_web_storage_scope(
handle,
&moli_url::origin_ascii_serialization(self.document_url()),
)
.child_browsing_context_web_storage_scope(handle, &self.main_document_origin())
.unwrap_or_else(|| self.top_web_storage_scope());
snapshots.push(DetachedChildBrowsingContextDocumentSnapshot {
parent_frame_id: parent_frame_id.clone(),
@@ -26,10 +26,7 @@ impl PageScriptHost {
self.child_browsing_context_snapshot_markup(handle)
.map(|snapshot| {
let parent_scope = self
.child_browsing_context_web_storage_scope(
handle,
&moli_url::origin_ascii_serialization(self.document_url()),
)
.child_browsing_context_web_storage_scope(handle, &self.main_document_origin())
.unwrap_or_else(|| self.top_web_storage_scope());
self.detached_child_browsing_context_frame_tree_snapshot(
"",
@@ -142,10 +142,7 @@ impl PageScriptHost {
}
current = self.child_browsing_context_parent_handle(current_handle);
}
let top_url = self
.current_main_document_resource_loader()
.and_then(|loader| Url::parse(loader.fetch_context().origin()).ok())
.unwrap_or_else(|| self.document_url().clone());
let top_url = self.main_document_secure_context_url();
// about:blank/srcdoc inherit their creator's trustworthiness, but a
// trustworthy descendant cannot override an insecure ancestor.
if moli_url::is_potentially_trustworthy_url(&top_url) {
@@ -314,7 +311,7 @@ impl PageScriptHost {
.get(&handle)
.copied()
});
let top_level_site = site_for_url(self.document_url());
let top_level_site = self.top_level_storage_site();
let origin = self.child_browsing_context_network_partition_origin(handle)?;
let relation =
StoragePartitionRelation::from_sites(&site_for_url(&current_url), &top_level_site);
@@ -331,7 +328,7 @@ impl PageScriptHost {
bootstrap: &ChildBrowsingContextBootstrap,
credentialless_storage_nonce: Option<OpaqueOriginNonce>,
) -> Option<String> {
let top_level_site = site_for_url(self.document_url());
let top_level_site = self.top_level_storage_site();
let origin =
self.child_browsing_context_navigation_network_partition_origin(handle, bootstrap)?;
let target_url = Self::child_browsing_context_bootstrap_url(bootstrap)?;
@@ -350,7 +347,7 @@ impl PageScriptHost {
}
fn child_browsing_context_ancestor_chain_is_cross_site(&self, handle: DomHandle) -> bool {
let top_level_site = site_for_url(self.document_url());
let top_level_site = self.top_level_storage_site();
let mut current = self.child_browsing_context_parent_handle(handle);
let mut depth = 0;
while let Some(parent) = current {
@@ -467,7 +464,7 @@ impl PageScriptHost {
return None;
}
match identity.dispatch_scope() {
OwnerDispatchScope::Top => Some(self.document_url().clone()),
OwnerDispatchScope::Top => Some(self.main_document_secure_context_url()),
OwnerDispatchScope::Child(handle) => {
self.child_browsing_context_secure_context_url(handle)
}
@@ -481,7 +478,7 @@ impl PageScriptHost {
&mut self,
handle: DomHandle,
) -> Option<ActiveStorageContext> {
let top_origin = moli_url::origin_ascii_serialization(self.document_url());
let top_origin = self.main_document_origin();
self.child_browsing_context_web_storage_scope(handle, &top_origin)
.map(|scope| ActiveStorageContext::new(scope.into_storage_context()))
}
@@ -495,7 +492,7 @@ impl PageScriptHost {
}
pub(crate) fn top_document_storage_context(&mut self) -> ActiveStorageContext {
let top_origin = moli_url::origin_ascii_serialization(self.document_url());
let top_origin = self.main_document_origin();
ActiveStorageContext::new(
self.web_storage_scope_for_top_document_origin(&top_origin)
.into_storage_context(),
@@ -523,7 +520,7 @@ impl PageScriptHost {
}
pub(crate) fn top_web_storage_scope(&mut self) -> WebStorageScope {
let top_origin = moli_url::origin_ascii_serialization(self.document_url());
let top_origin = self.main_document_origin();
self.web_storage_scope_for_top_document_origin(&top_origin)
}
@@ -548,7 +545,7 @@ impl PageScriptHost {
let parent_has_cross_site_ancestor = parent_scope.storage_key().has_cross_site_ancestor();
if self.child_browsing_context_has_opaque_origin(handle) {
let url = self.child_browsing_context_current_url(handle)?;
let top_level_site = site_for_url(self.document_url());
let top_level_site = self.top_level_storage_site();
let relation = if moli_url::is_about_blank(&url) {
StoragePartitionRelation::Unknown
} else {
@@ -580,7 +577,7 @@ impl PageScriptHost {
parent_scope.origin(),
)
};
let top_level_site = site_for_url(self.document_url());
let top_level_site = self.top_level_storage_site();
let mut storage_key = web_storage_key_for_origin_and_top_level_site_with_nonce(
&origin,
top_level_site,
@@ -599,7 +596,7 @@ impl PageScriptHost {
&url,
parent_scope.origin(),
);
let top_level_site = site_for_url(self.document_url());
let top_level_site = self.top_level_storage_site();
let mut storage_key =
web_storage_key_for_origin_and_top_level_site_with_nonce(&origin, top_level_site, None);
if parent_has_cross_site_ancestor {
@@ -621,7 +618,7 @@ impl PageScriptHost {
.is_some_and(|sandbox| sandbox_attribute_forces_opaque_origin(&sandbox))
|| url.scheme() == "data"
{
let top_level_site = site_for_url(self.document_url());
let top_level_site = self.top_level_storage_site();
let relation = if moli_url::is_about_blank(url) {
StoragePartitionRelation::Unknown
} else {
@@ -645,13 +642,20 @@ impl PageScriptHost {
url,
parent_scope.origin(),
);
let top_level_site = site_for_url(self.document_url());
let top_level_site = self.top_level_storage_site();
WebStorageScope::new(
origin.clone(),
web_storage_key_for_origin_and_top_level_site_with_nonce(&origin, top_level_site, None),
)
}
pub(in crate::native_bridge::context_host) fn top_level_storage_site(&self) -> String {
self.top_level_storage_key
.as_ref()
.map(|key| key.top_level_site().to_owned())
.unwrap_or_else(|| site_for_url(self.document_url()))
}
fn web_storage_scope_for_top_document_origin(&mut self, origin: &str) -> WebStorageScope {
if let Some(storage_key) = self.top_level_storage_key.as_ref() {
return WebStorageScope::new(storage_key.origin().to_owned(), storage_key.clone());
@@ -426,6 +426,7 @@ impl PageScriptHost {
force_reused_isolated_proxy_bootstrap_failure: std::cell::Cell::new(false),
child_browsing_context_document_handles: HashMap::new(),
document_domain_override: DocumentDomainState::default(),
about_document_state: None,
next_child_document_load_id: 0,
next_child_classic_script_load_id: 0,
pending_child_document_navigations: HashMap::new(),
@@ -178,7 +178,7 @@ impl PageScriptHost {
}
fn main_document_domain_host(&self) -> Option<String> {
Url::parse(&self.main_document_security_origin())
Url::parse(&self.main_document_origin())
.ok()
.and_then(|origin| url_host_domain(&origin))
}
@@ -197,7 +197,9 @@ mod window_document_tasks;
mod window_execution_context;
mod window_security_tokens;
mod window_world;
pub(crate) use window_security_tokens::{WindowSecurityOrigin, window_contexts_allow_access};
pub(crate) use window_security_tokens::{
WindowAccessOrigin, WindowSecurityOrigin, window_contexts_allow_access,
};
mod workers;
pub(crate) use window_security_tokens::DocumentDomainState;
pub(crate) use window_security_tokens::set_window_security_token;
@@ -960,6 +962,7 @@ pub(crate) struct PageScriptHost {
force_reused_isolated_proxy_bootstrap_failure: std::cell::Cell<bool>,
child_browsing_context_document_handles: HashMap<DomHandle, DomHandle>,
document_domain_override: DocumentDomainState,
about_document_state: Option<crate::runtime::RendererAboutDocumentState>,
next_child_document_load_id: u64,
next_child_classic_script_load_id: u64,
pending_child_document_navigations: HashMap<u64, PendingChildDocumentNavigation>,
@@ -69,6 +69,7 @@ pub(crate) struct PendingLocationNavigation {
pub(crate) entry_seed: Option<NavigationHistoryEntrySeed>,
/// Resolved history handling for requests without a prebuilt entry seed.
pub(crate) history_mutation: Option<NavigationHistoryMutation>,
pub(crate) about_document_state: Option<crate::runtime::RendererAboutDocumentState>,
pub(crate) reserved_service_worker_client: Option<PendingReservedServiceWorkerClient>,
pub(crate) service_worker_client_navigate:
Option<crate::types::ServiceWorkerClientNavigateContinuation>,
@@ -287,12 +288,14 @@ impl PageScriptHost {
&mut self,
url: Url,
entry_seed: Option<NavigationHistoryEntrySeed>,
about_document_state: Option<crate::runtime::RendererAboutDocumentState>,
) {
self.record_pending_location_navigation_with_kind(
url,
entry_seed,
BrowserNavigationRequestKind::Navigate,
None,
about_document_state,
);
}
@@ -302,6 +305,7 @@ impl PageScriptHost {
entry_seed: Option<NavigationHistoryEntrySeed>,
browser_navigation_kind: BrowserNavigationRequestKind,
source: Option<LocationNavigationSource>,
about_document_state: Option<crate::runtime::RendererAboutDocumentState>,
) {
self.record_pending_location_navigation_request(
url,
@@ -311,6 +315,7 @@ impl PageScriptHost {
entry_seed,
browser_navigation_kind,
source,
about_document_state,
);
}
@@ -323,6 +328,7 @@ impl PageScriptHost {
entry_seed: Option<NavigationHistoryEntrySeed>,
browser_navigation_kind: BrowserNavigationRequestKind,
source: Option<LocationNavigationSource>,
about_document_state: Option<crate::runtime::RendererAboutDocumentState>,
) {
self.cancel_planned_form_navigation_for_url(OwnerDispatchScope::Top, Some(&url));
self.clear_pending_top_level_navigation();
@@ -350,6 +356,7 @@ impl PageScriptHost {
initial_document_environment,
entry_seed,
history_mutation: None,
about_document_state,
reserved_service_worker_client,
service_worker_client_navigate: None,
web_mcp_invocation: None,
@@ -384,6 +391,7 @@ impl PageScriptHost {
initial_document_environment: None,
entry_seed: None,
history_mutation: None,
about_document_state: None,
reserved_service_worker_client,
service_worker_client_navigate: Some(continuation),
web_mcp_invocation: None,
@@ -52,7 +52,6 @@ use crate::{
use anyhow::Result;
use moli_fetch::Request;
use moli_storage_key::{MoliStorageKey, StoragePartitionRelation, site_for_url};
use moli_url::origin_ascii_serialization;
use moli_webapi::events::fallback::{PlainEventDeclaration, PlainPopStateEventDeclaration};
use moli_webapi_declare::{ObjectLiteralDeclaration, WebApiObject};
use std::{
@@ -1776,7 +1775,7 @@ impl PageScriptHost {
&mut self,
url: &Url,
) -> LightweightPopupStorageScope {
let top_level_site = site_for_url(self.document_url());
let top_level_site = self.top_level_storage_site();
let relation = StoragePartitionRelation::from_sites(&site_for_url(url), &top_level_site);
let storage_key = MoliStorageKey::new(
"null".to_owned(),
@@ -1808,7 +1807,7 @@ impl PageScriptHost {
.map(LightweightPopupStorageScope::from_web_storage_scope);
}
if let Some(handle) = opener_child_handle {
let top_origin = origin_ascii_serialization(self.document_url());
let top_origin = self.main_document_origin();
return self
.child_browsing_context_web_storage_scope(handle, &top_origin)
.map(LightweightPopupStorageScope::from_web_storage_scope);
@@ -55,7 +55,7 @@ impl<'s> OpenedRendererWindow<'s> {
let host = crate::util::context_host_ptr_from_window_object(scope, self.window_proxy)
.expect("a related Window retains its native host");
// Run the URL after the opening script returns, without a network load.
unsafe { &mut *host }.record_pending_location_navigation(url, None);
unsafe { &mut *host }.record_pending_location_navigation(url, None, None);
return true;
}
#[cfg(feature = "molio")]
@@ -23,6 +23,7 @@ use crate::{
util::get_private_value,
v8_execution_watchdog::V8ExecutionWatchdog,
};
use url::Url;
#[derive(Debug)]
#[must_use = "the caller must stop a request when CSP blocks it"]
@@ -246,12 +247,102 @@ impl PageScriptHost {
// Meta policies are delivered separately from response headers.
// Capture their current list so later creator mutations cannot
// change the new Document's policy container.
policy.inherited_meta_content_security_policies = unsafe { &*self.runtime }
policy.inherited_meta_content_security_policies = unsafe { &*self.document_runtime }
.meta_content_security_policy_strings_for_document(document);
}
Some(policy)
}
pub(crate) fn capture_about_document_state(
&self,
owner: OwnerDispatchScope,
destination: &Url,
source_element: Option<DomHandle>,
) -> Option<crate::runtime::RendererAboutDocumentState> {
if !moli_url::is_about_blank(destination) {
return None;
}
let owner = source_element
.and_then(|element| self.owner_dispatch_scope_for_node(element))
.unwrap_or(owner);
let snapshot = self.owner_document_policy_snapshot(owner)?;
let origin = self.window_access_origin_for_dispatch_scope(owner)?;
let mut policy_container = self.document_policy_container_for_inheritance(owner)?;
if let Some(document) = snapshot.document_handle {
policy_container.referrer_policy =
crate::context_bootstrap::document_referrer_policy_for_native_document(
self, document,
);
}
let element_referrer_policy = source_element
.and_then(|handle| self.dom_host().node(handle))
.and_then(|node| node.as_element())
.and_then(|element| {
if element.attribute("rel").is_some_and(|rel| {
rel.split_ascii_whitespace()
.any(|token| token.eq_ignore_ascii_case("noreferrer"))
}) {
Some("no-referrer".to_owned())
} else {
element
.attribute("referrerpolicy")
.and_then(crate::referrer_policy::normalize_referrer_policy)
}
});
policy_container.document_referrer = if origin.serialized_origin() == "null" {
String::new()
} else {
moli_fetch::referrer_value(
&snapshot.document_url,
destination,
element_referrer_policy.as_deref(),
policy_container.referrer_policy.as_deref(),
)
.unwrap_or_default()
};
let base_url = snapshot
.document_handle
.map(|document| self.document_base_url_for_handle(document))
.unwrap_or(snapshot.document_url);
Some(crate::runtime::RendererAboutDocumentState::new(
origin,
base_url,
policy_container,
))
}
pub(crate) fn current_about_document_state(
&self,
) -> Option<crate::runtime::RendererAboutDocumentState> {
let state = self.about_document_state.as_ref()?;
Some(crate::runtime::RendererAboutDocumentState::new(
self.window_access_origin_for_dispatch_scope(OwnerDispatchScope::Top)?,
state.base_url().clone(),
self.document_policy_container_for_inheritance(OwnerDispatchScope::Top)?,
))
}
pub(crate) fn set_main_about_document_state(
&mut self,
state: Option<crate::runtime::RendererAboutDocumentState>,
) {
let state = state.filter(|_| moli_url::is_about_blank(self.document_url()));
let document = self.document_handle();
self.dom_host_mut()
.set_document_fallback_base_url_for_handle(
document,
state.as_ref().map(|state| state.base_url().clone()),
);
if let Some(super::WindowAccessOrigin::Tuple {
document_domain: Some(domain),
..
}) = state.as_ref().map(|state| state.origin())
{
self.document_domain_override.set(domain.clone());
}
self.about_document_state = state;
}
pub(crate) fn document_connect_policy_snapshot_for_owner(
&self,
owner: OwnerDispatchScope,
@@ -259,7 +350,7 @@ impl PageScriptHost {
let snapshot = self.owner_document_policy_snapshot(owner)?;
// SAFETY: PageScriptHost belongs to the ScriptVm that owns this runtime.
Some(
unsafe { &*self.runtime }.document_connect_policy_snapshot_for_document(
unsafe { &*self.document_runtime }.document_connect_policy_snapshot_for_document(
snapshot.document_handle,
&snapshot.policy_container,
),
@@ -130,7 +130,7 @@ impl PageScriptHost {
area_key: &str,
) -> Vec<WindowTaskTarget> {
let mut targets = Vec::new();
let top_origin = moli_url::origin_ascii_serialization(self.document_url());
let top_origin = self.main_document_origin();
let top_is_eligible = source_scope != Some(OwnerDispatchScope::Top)
&& (!is_session
@@ -471,7 +471,7 @@ impl PageScriptHost {
if self.document_sandbox_policy().forces_opaque_origin {
return None;
}
let origin = self.main_document_security_origin();
let origin = self.main_document_origin();
if self.document_domain_override.get().is_some() {
return None;
}
@@ -500,7 +500,7 @@ impl PageScriptHost {
return None;
}
window_isolated_world_security_token_key(
self.main_document_security_origin(),
self.main_document_origin(),
self.document_domain_override.get().is_some(),
)
}
@@ -986,9 +986,15 @@ impl PageScriptHost {
.is_some_and(|(source, target)| source.can_access(&target))
}
pub(crate) fn window_document_origin(&self, scope: OwnerDispatchScope) -> Option<String> {
self.window_access_origin_for_dispatch_scope(scope)
pub(crate) fn main_document_origin(&self) -> String {
self.main_window_access_origin()
.map(|origin| origin.serialized_origin())
.unwrap_or_else(|| "null".to_owned())
}
pub(crate) fn main_document_secure_context_url(&self) -> url::Url {
url::Url::parse(&self.main_document_origin())
.unwrap_or_else(|_| self.document_url().clone())
}
pub(in crate::native_bridge::context_host) fn window_access_origin_for_dispatch_scope(
@@ -1007,6 +1013,21 @@ impl PageScriptHost {
pub(in crate::native_bridge::context_host) fn main_window_access_origin(
&self,
) -> Option<WindowAccessOrigin> {
if !self
.document_policy_container()
.sandbox
.forces_opaque_origin
&& let Some(state) = &self.about_document_state
{
let mut origin = state.origin().clone();
if let WindowAccessOrigin::Tuple {
document_domain, ..
} = &mut origin
{
*document_domain = self.document_domain_override.get();
}
return Some(origin);
}
let serialized_origin = self.main_document_security_origin();
if self.document_sandbox_policy().forces_opaque_origin || serialized_origin == "null" {
return Some(WindowAccessOrigin::opaque(
@@ -1081,7 +1102,7 @@ impl PageScriptHost {
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::native_bridge::context_host) enum WindowAccessOrigin {
pub(crate) enum WindowAccessOrigin {
Opaque {
identity: Option<WindowExecutionContextOwner>,
},
@@ -1200,7 +1221,31 @@ impl WindowAccessOrigin {
}
}
pub(in crate::native_bridge::context_host) fn serialized_origin(&self) -> String {
pub(in crate::native_bridge::context_host) fn has_same_origin(&self, target: &Self) -> bool {
match (self, target) {
(
Self::Opaque {
identity: Some(origin),
},
Self::Opaque {
identity: Some(target_origin),
},
) => origin == target_origin,
(
Self::Tuple {
serialized_origin: origin,
..
},
Self::Tuple {
serialized_origin: target_origin,
..
},
) => origin == target_origin,
_ => false,
}
}
pub(crate) fn serialized_origin(&self) -> String {
match self {
Self::Opaque { .. } => "null".to_owned(),
Self::Tuple {
+10 -9
View File
@@ -1279,16 +1279,17 @@ fn document_referrer_getter_function<'s>(
return;
};
let runtime = unsafe { &*runtime_ptr };
let referrer = runtime
.child_browsing_context_referrer_for_document_handle(handle)
.or_else(|| runtime.lightweight_popup_referrer_for_document_handle(handle))
let referrer = (handle == runtime.document_handle())
.then(|| {
runtime
.document_policy_container()
.document_referrer
.as_str()
})
.or_else(|| {
(handle == runtime.document_handle()).then(|| {
runtime
.document_policy_container()
.document_referrer
.as_str()
})
runtime
.child_browsing_context_referrer_for_document_handle(handle)
.or_else(|| runtime.lightweight_popup_referrer_for_document_handle(handle))
})
.unwrap_or("");
set_document_string_return_value(scope, &mut rv, referrer);
@@ -53,12 +53,14 @@ pub(super) fn queue_top_level_location_navigation(
runtime_ptr: *mut PageScriptHost,
resolved_url: &str,
history: NavigationHistoryMutation,
source: crate::native_bridge::OwnerDispatchScope,
) -> bool {
let Ok(url) = url::Url::parse(resolved_url) else {
return false;
};
let runtime = unsafe { &mut *runtime_ptr };
runtime.record_pending_location_navigation(url, None);
let about_document_state = runtime.capture_about_document_state(source, &url, None);
runtime.record_pending_location_navigation(url, None, about_document_state);
runtime.set_pending_location_navigation_history(history);
true
}
@@ -1005,6 +1005,7 @@ pub(in crate::native_bridge) fn apply_planned_form_navigation(
initiator: request.initiator,
initial_document_environment: None,
}),
None,
);
crate::context_bootstrap::web_mcp::bind_root_navigation(runtime, navigation.form);
true
+1 -1
View File
@@ -9,7 +9,7 @@ mod current_input;
pub(crate) use context_host::{
ChildDocumentFetch, DocumentDomainState, LayoutPublicationRequest, PageScriptHost, PageScriptHostTaskCapabilities,
PendingScrollObservableEffects, PostParseAutofocusAdmission, ServiceWorkerWindowOwner,
SharedResourceTimingBufferRegistry, caller_can_access_window,
SharedResourceTimingBufferRegistry, WindowAccessOrigin, caller_can_access_window,
contexts_can_script_access as window_contexts_allow_access,
};
#[cfg(feature = "devtools")]
+3 -1
View File
@@ -60,7 +60,9 @@ mod lifecycle_decision;
mod main_document_ready_gate;
mod navigation;
mod navigation_history;
pub use navigation_history::{RendererNavigationHistory, RendererNavigationHistoryRequest};
pub use navigation_history::{
RendererAboutDocumentState, RendererNavigationHistory, RendererNavigationHistoryRequest,
};
#[cfg(feature = "devtools")]
mod nested_main;
mod owner;
@@ -1,4 +1,4 @@
use std::sync::Arc;
use std::{collections::HashMap, sync::Arc};
use anyhow::{Result, anyhow};
use moli_page_types::{
@@ -16,6 +16,52 @@ use crate::native_bridge::{
NestedHistoryStore,
};
/// Native state inherited by an about:blank Document. The protocol transports
/// this snapshot without reconstructing an origin from a URL or JS property.
/// History retains it by Document identity for reload and traversal.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RendererAboutDocumentState(Arc<AboutDocumentState>);
#[derive(Debug, PartialEq, Eq)]
struct AboutDocumentState {
origin: crate::native_bridge::WindowAccessOrigin,
base_url: Url,
policy_container: crate::document_runtime::DocumentPolicyContainer,
}
impl RendererAboutDocumentState {
pub(crate) fn new(
origin: crate::native_bridge::WindowAccessOrigin,
base_url: Url,
policy_container: crate::document_runtime::DocumentPolicyContainer,
) -> Self {
Self(Arc::new(AboutDocumentState {
origin,
base_url,
policy_container,
}))
}
pub(crate) fn origin(&self) -> &crate::native_bridge::WindowAccessOrigin {
&self.0.origin
}
pub(crate) fn base_url(&self) -> &Url {
&self.0.base_url
}
pub(crate) fn policy_container(&self) -> &crate::document_runtime::DocumentPolicyContainer {
&self.0.policy_container
}
pub(crate) fn storage_key(&self) -> Option<moli_storage_key::MoliStorageKey> {
if self.policy_container().sandbox.forces_opaque_origin {
return None;
}
Url::parse(&self.origin().serialized_origin())
.ok()
.map(|url| moli_storage_key::MoliStorageKey::first_party_from_url(&url, None))
}
}
/// The committed history of a renderer's top-level Document. Publishing a
/// snapshot happens at a history mutation, never while capturing Page state.
/// Browser navigation can read this handle without entering V8, including
@@ -26,6 +72,7 @@ pub struct RendererNavigationHistory {
joint: Arc<Mutex<Option<JointSessionHistory>>>,
nested: NestedHistoryStore,
selected_step: Arc<Mutex<Option<(String, SessionHistoryStepId)>>>,
about_documents: Arc<Mutex<HashMap<NavigationHistoryDocumentId, RendererAboutDocumentState>>>,
}
impl PartialEq for RendererNavigationHistory {
@@ -109,6 +156,7 @@ impl RendererNavigationHistory {
joint: Arc::new(Mutex::new(joint)),
nested: self.nested.clone(),
selected_step: Arc::default(),
about_documents: self.about_documents.clone(),
}
}
@@ -117,10 +165,27 @@ impl RendererNavigationHistory {
*history = joint;
}
}
pub(crate) fn publish(&self, seed: NavigationHistoryEntrySeed) {
pub(crate) fn publish(
&self,
seed: NavigationHistoryEntrySeed,
state: Option<RendererAboutDocumentState>,
) {
if let Some(history) = seed.session_history.traversable.as_deref() {
*self.joint.lock() = Some(history.clone());
}
let mut documents = self.about_documents.lock();
documents.retain(|document, _| {
seed.entries
.iter()
.any(|entry| &entry.document_id == document)
});
if let Some(state) = state
&& let Some(entry) = current_entry(&seed)
{
documents.insert(entry.document_id.clone(), state);
}
// Publish the seed only after its inherited state is available to a
// browser navigation reading this handle from another thread.
*self.snapshot.lock() = Some(Arc::new(seed));
}
@@ -212,12 +277,15 @@ impl RendererNavigationHistory {
seed: NavigationHistoryEntrySeed,
) -> RendererNavigationHistoryRequest {
let source_index = self.snapshot().map(|source| source.current_index);
let about_document_state = current_entry(&seed)
.and_then(|entry| self.about_documents.lock().get(&entry.document_id).cloned());
RendererNavigationHistoryRequest {
source: self.clone(),
requested: Arc::new(seed),
source_index,
initial_empty_source: false,
selected_step: self.selected_step.lock().clone(),
about_document_state,
}
}
}
@@ -233,6 +301,7 @@ pub struct RendererNavigationHistoryRequest {
source_index: Option<u32>,
initial_empty_source: bool,
selected_step: Option<(String, SessionHistoryStepId)>,
about_document_state: Option<RendererAboutDocumentState>,
}
impl PartialEq for RendererNavigationHistoryRequest {
@@ -240,12 +309,31 @@ impl PartialEq for RendererNavigationHistoryRequest {
self.source == other.source
&& Arc::ptr_eq(&self.requested, &other.requested)
&& self.initial_empty_source == other.initial_empty_source
&& self.about_document_state == other.about_document_state
}
}
impl Eq for RendererNavigationHistoryRequest {}
impl RendererNavigationHistoryRequest {
/// A new about:blank navigation inherits its initiator's frozen state.
/// Reload and traversal retain the destination Document's recorded state.
pub fn with_about_document_state(mut self, state: Option<RendererAboutDocumentState>) -> Self {
if !matches!(self.navigation_type(), Some("reload" | "traverse")) {
self.about_document_state = state;
}
self
}
pub(crate) fn about_document_state(
&self,
final_url: &Url,
) -> Option<RendererAboutDocumentState> {
moli_url::is_about_blank(final_url)
.then(|| self.about_document_state.clone())
.flatten()
}
pub(crate) fn source_history(&self) -> RendererNavigationHistory {
let mut source = self.source.clone();
source.selected_step = Arc::new(Mutex::new(self.selected_step.clone()));
@@ -314,7 +402,7 @@ impl RendererNavigationHistoryRequest {
.ok_or_else(|| anyhow!("missing navigation history destination"))?;
let current =
current_entry(&source).ok_or_else(|| anyhow!("missing navigation history source"))?;
let seed = match self.navigation_type() {
let mut seed = match self.navigation_type() {
Some("push" | "replace") => {
let mutation = if self.navigation_type() == Some("replace") {
NavigationHistoryMutation::Replace
@@ -362,6 +450,26 @@ impl RendererNavigationHistoryRequest {
}
_ => self.requested.as_ref().clone(),
};
// about:blank's URL does not identify its inherited origin. Use the
// destination Document state and the source's native history record.
let destination_origin = self
.about_document_state(final_url)
.map(|state| state.origin().serialized_origin())
.unwrap_or_else(|| moli_url::origin_ascii_serialization(final_url));
let traversed_indices = source.current_index.min(seed.current_index)
..=source.current_index.max(seed.current_index);
let source_is_contiguous = self.navigation_type() != Some("traverse")
|| source
.entries
.iter()
.filter(|entry| traversed_indices.contains(&entry.history_index))
.all(|entry| entry.document_origin == destination_origin);
if let Some(activation) = &mut seed.activation {
activation.from = (destination_origin != "null"
&& current.document_origin == destination_origin
&& source_is_contiguous)
.then(|| current.clone());
}
Ok(self.finish_seed(seed, final_url))
}
}
@@ -85,11 +85,19 @@ impl RendererCreateStreamingRawPageRequest {
network_offline,
&blocked_url_patterns,
);
let document_policy_container = DocumentPolicyContainer::from_navigation_response_headers(
&response_headers,
&final_url,
)
.with_content_security_policy_bypass(document_settings.bypass_content_security_policy);
let about_document_state = navigation_history
.as_ref()
.and_then(|request| request.about_document_state(&final_url));
let document_policy_container = about_document_state
.as_ref()
.map(|state| state.policy_container().clone())
.unwrap_or_else(|| {
DocumentPolicyContainer::from_navigation_response_headers(
&response_headers,
&final_url,
)
})
.with_content_security_policy_bypass(document_settings.bypass_content_security_policy);
let document_default_language =
crate::document_language::document_default_language_from_headers(&response_headers);
let document_last_modified =
@@ -105,6 +113,7 @@ impl RendererCreateStreamingRawPageRequest {
extra_http_headers,
navigator_identity,
document_policy_container,
about_document_state,
document_default_language,
document_last_modified,
document_settings,
@@ -873,11 +873,19 @@ impl RendererOwnerHandle {
))
.into();
}
let document_policy_container = DocumentPolicyContainer::from_navigation_response_headers(
&response_headers,
&final_url,
)
.with_content_security_policy_bypass(document_settings.bypass_content_security_policy);
let about_document_state = navigation_history
.as_ref()
.and_then(|request| request.about_document_state(&final_url));
let document_policy_container = about_document_state
.as_ref()
.map(|state| state.policy_container().clone())
.unwrap_or_else(|| {
DocumentPolicyContainer::from_navigation_response_headers(
&response_headers,
&final_url,
)
})
.with_content_security_policy_bypass(document_settings.bypass_content_security_policy);
let document_default_language =
crate::document_language::document_default_language_from_headers(&response_headers);
let document_last_modified =
@@ -919,6 +927,7 @@ impl RendererOwnerHandle {
extra_http_headers,
navigator_identity,
document_policy_container,
about_document_state,
document_default_language,
document_last_modified,
document_settings,
@@ -389,6 +389,7 @@ struct RendererTopLevelNavigationRequest {
browser_navigation_kind: moli_fetch::BrowserNavigationRequestKind,
history_mutation: moli_page_types::NavigationHistoryMutation,
navigation_history: Option<super::RendererNavigationHistoryRequest>,
about_document_state: Option<super::RendererAboutDocumentState>,
}
impl RendererDocumentSourcedTopLevelLocationNavigation {
@@ -432,6 +433,7 @@ impl RendererDocumentSourcedTopLevelLocationNavigation {
browser_navigation_kind,
history_mutation: moli_page_types::NavigationHistoryMutation::Push,
navigation_history: None,
about_document_state: None,
}),
runtime_command_cause,
navigation_initiator: None,
@@ -497,6 +499,18 @@ impl RendererDocumentSourcedTopLevelLocationNavigation {
self.request.navigation_history.as_ref()
}
pub(crate) fn with_about_document_state(
mut self,
state: Option<super::RendererAboutDocumentState>,
) -> Self {
self.request.about_document_state = state;
self
}
pub fn about_document_state(&self) -> Option<&super::RendererAboutDocumentState> {
self.request.about_document_state.as_ref()
}
pub fn url(&self) -> &str {
&self.request.url
}
@@ -631,6 +631,7 @@ pub(in crate::runtime) struct PageVmPreparedFollowedNavigationCommit {
loaded: LoadedFollowedLocationNavigation,
initial_document_environment: Option<RendererCapturedDocumentEnvironment>,
navigation_bootstrap_entry: Option<crate::native_bridge::NavigationHistoryEntrySeed>,
about_document_state: Option<crate::runtime::RendererAboutDocumentState>,
reserved_service_worker_client_id: Option<crate::service_worker_runtime::ServiceWorkerClientId>,
service_worker_client_navigate: Option<crate::types::ServiceWorkerClientNavigateContinuation>,
web_mcp_invocation: Option<moli_page_types::RendererWebMcpNavigation>,
@@ -892,6 +893,16 @@ impl PageVm {
let request_body = pending.request_body.clone();
let request_headers = pending.request_headers.clone();
let browser_navigation_kind = pending.browser_navigation_kind;
let navigation_history = pending.entry_seed.as_ref().map(|seed| {
self.vm()
.top_level_navigation_history()
.request(seed.clone())
.with_about_document_state(pending.about_document_state.clone())
});
let about_document_state = navigation_history.as_ref().map_or_else(
|| pending.about_document_state.clone(),
|history| history.about_document_state(&url),
);
let reserved_service_worker_client_id = pending
.reserved_service_worker_client
.map(|reserved| reserved.release());
@@ -1009,6 +1020,17 @@ impl PageVm {
| LoadedFollowedLocationNavigation::ExternalDocument { .. }) => loaded,
};
let final_url = match &loaded {
LoadedFollowedLocationNavigation::StreamingDocument { response, .. } => {
&response.final_url
}
LoadedFollowedLocationNavigation::ExternalDocument { final_url, .. } => final_url,
_ => unreachable!("only a Document response reaches navigation commit"),
};
let navigation_bootstrap_entry = navigation_history
.as_ref()
.map(|history| history.resolve(final_url))
.transpose()?;
Ok(PageVmDocumentCommitPreparation::Prepared(Box::new(
PageVmPreparedFollowedNavigationCommit {
initiator_url,
@@ -1016,6 +1038,7 @@ impl PageVm {
loaded,
initial_document_environment: pending.initial_document_environment,
navigation_bootstrap_entry,
about_document_state,
reserved_service_worker_client_id,
service_worker_client_navigate,
web_mcp_invocation,
@@ -1034,6 +1057,7 @@ impl PageVm {
initiator_url,
loaded,
navigation_bootstrap_entry,
about_document_state,
reserved_service_worker_client_id,
service_worker_client_navigate,
web_mcp_invocation,
@@ -1044,6 +1068,7 @@ impl PageVm {
.bootstrap_followed_location_navigation(
loaded,
navigation_bootstrap_entry,
about_document_state,
reserved_service_worker_client_id,
web_mcp_invocation,
stage,
@@ -1147,12 +1172,14 @@ impl PageVm {
loaded,
initial_document_environment,
navigation_bootstrap_entry,
about_document_state,
reserved_service_worker_client_id,
service_worker_client_navigate,
web_mcp_invocation,
stage,
} = prepared;
let env = self.followed_location_navigation_env();
let mut env = self.followed_location_navigation_env();
env.about_document_state = about_document_state;
let mut runtime_hooks = self.runtime_hooks.clone().for_cross_document_commit();
runtime_hooks.web_mcp_navigation = web_mcp_invocation.clone();
#[cfg(test)]
@@ -1604,6 +1631,7 @@ impl PageVm {
root_frame_id: self.vm().root_frame_id().map(str::to_owned),
top_level_storage_key: None,
navigation_bootstrap_entry: None,
about_document_state: None,
navigation_history_source: Some(self.vm().top_level_navigation_history()),
reserved_service_worker_client_id: None,
}
@@ -1614,6 +1642,7 @@ impl PageVm {
&mut self,
loaded: LoadedFollowedLocationNavigation,
navigation_bootstrap_entry: Option<crate::native_bridge::NavigationHistoryEntrySeed>,
about_document_state: Option<crate::runtime::RendererAboutDocumentState>,
reserved_service_worker_client_id: Option<
crate::service_worker_runtime::ServiceWorkerClientId,
>,
@@ -1630,7 +1659,8 @@ impl PageVm {
LoadedFollowedLocationNavigation::StreamingDocument { .. }
| LoadedFollowedLocationNavigation::ExternalDocument { .. }
));
let env = self.followed_location_navigation_env();
let mut env = self.followed_location_navigation_env();
env.about_document_state = about_document_state;
let mut runtime_hooks = self.runtime_hooks.clone().for_cross_document_commit();
runtime_hooks.web_mcp_navigation = web_mcp_invocation;
if runtime_hooks.renderer_page_script_environment.is_some() {
+18 -5
View File
@@ -1136,6 +1136,7 @@ pub(crate) struct PageVmEnvConfig {
pub(crate) layout_configuration: moli_page_types::LayoutConfiguration,
pub(crate) wpt_extensions_enabled: bool,
pub(crate) navigation_bootstrap_entry: Option<crate::native_bridge::NavigationHistoryEntrySeed>,
pub(crate) about_document_state: Option<crate::runtime::RendererAboutDocumentState>,
pub(crate) navigation_history_source: Option<crate::runtime::RendererNavigationHistory>,
pub(crate) reserved_service_worker_client_id:
Option<crate::service_worker_runtime::ServiceWorkerClientId>,
@@ -1149,14 +1150,25 @@ impl PageVmEnvConfig {
) {
let document_referrer =
std::mem::take(&mut self.document_policy_container.document_referrer);
self.document_policy_container =
crate::document_runtime::DocumentPolicyContainer::from_navigation_response_headers(
headers, final_url,
)
self.about_document_state = self
.about_document_state
.take()
.filter(|_| moli_url::is_about_blank(final_url));
self.document_policy_container = self
.about_document_state
.as_ref()
.map(|state| state.policy_container().clone())
.unwrap_or_else(|| {
crate::document_runtime::DocumentPolicyContainer::from_navigation_response_headers(
headers, final_url,
)
})
.with_content_security_policy_bypass(
self.document_settings.bypass_content_security_policy,
);
self.document_policy_container.document_referrer = document_referrer;
if self.about_document_state.is_none() {
self.document_policy_container.document_referrer = document_referrer;
}
self.apply_main_document_commit_referrer();
debug_assert!(
self.document_policy_container
@@ -4488,6 +4500,7 @@ impl PageVm {
env.main_document_commit.clone().map(|commit| (document_lifecycle_identity, commit)),
env.top_level_storage_key.clone(),
env.reserved_service_worker_client_id,
env.about_document_state.clone(),
)?;
vm_bootstrap.finish()?
};
@@ -743,6 +743,7 @@ fn minimal_test_page_vm_env_config() -> PageVmEnvConfig {
},
wpt_extensions_enabled: false,
navigation_bootstrap_entry: None,
about_document_state: None,
navigation_history_source: None,
reserved_service_worker_client_id: None,
}
@@ -39,6 +39,7 @@ fn default_runtime_hooks_reject_direct_no_owner_page_vm_construction() {
},
wpt_extensions_enabled: false,
navigation_bootstrap_entry: None,
about_document_state: None,
navigation_history_source: None,
reserved_service_worker_client_id: None,
},
@@ -707,6 +707,7 @@ fn test_page_vm_with_loader_dom_host_hooks_and_response_referrer_policy(
},
wpt_extensions_enabled: false,
navigation_bootstrap_entry: None,
about_document_state: None,
navigation_history_source: None,
reserved_service_worker_client_id: None,
},
@@ -701,6 +701,7 @@ mod tests {
},
wpt_extensions_enabled: false,
navigation_bootstrap_entry: None,
about_document_state: None,
navigation_history_source: None,
reserved_service_worker_client_id: None,
}
@@ -1085,6 +1085,7 @@ mod tests {
},
wpt_extensions_enabled: false,
navigation_bootstrap_entry: None,
about_document_state: None,
navigation_history_source: None,
reserved_service_worker_client_id: None,
}
@@ -668,6 +668,8 @@ fn parser_owner_boundary_with_live_backend_queues_document_turn_before_runtime_w
reserved_service_worker_client_id: None,
navigation_history_source: None,
about_document_state: None,
},
PageVmRuntimeHooks::standalone_without_owner_reservation_for_test(),
crate::dom::native::DomHost::from_dom(NativeDom::new(
@@ -958,6 +960,8 @@ fn parser_connected_head_script_does_not_push_later_head_tokens_into_body() {
reserved_service_worker_client_id: None,
navigation_history_source: None,
about_document_state: None,
},
PageVmRuntimeHooks::standalone_without_owner_reservation_for_test(),
parser_dom_host,
@@ -1136,6 +1140,8 @@ fn parser_connected_external_head_script_with_live_head_and_body_mutation_keeps_
reserved_service_worker_client_id: None,
navigation_history_source: None,
about_document_state: None,
},
PageVmRuntimeHooks::standalone_without_owner_reservation_for_test(),
parser_dom_host,
@@ -1736,6 +1742,8 @@ fn parser_owner_body_stylesheet_pause_preserves_unconsumed_tail_on_live_page_vm(
reserved_service_worker_client_id: None,
navigation_history_source: None,
about_document_state: None,
},
PageVmRuntimeHooks::standalone_without_owner_reservation_for_test(),
parser_dom_host,
@@ -363,6 +363,8 @@ fn external_async_handoff_marks_parser_stream_already_started_on_live_backend()
reserved_service_worker_client_id: None,
navigation_history_source: None,
about_document_state: None,
},
PageVmRuntimeHooks::standalone_without_owner_reservation_for_test(),
parser_dom_host,
@@ -488,6 +490,8 @@ fn blocking_classic_handoff_registers_parser_owned_handle_on_live_backend() {
reserved_service_worker_client_id: None,
navigation_history_source: None,
about_document_state: None,
},
PageVmRuntimeHooks::standalone_without_owner_reservation_for_test(),
parser_dom_host,
@@ -623,6 +627,8 @@ fn non_async_post_parse_handoff_registers_pending_before_source_and_seals_withou
reserved_service_worker_client_id: None,
navigation_history_source: None,
about_document_state: None,
},
PageVmRuntimeHooks::standalone_without_owner_reservation_for_test(),
parser_dom_host,
@@ -793,6 +799,8 @@ fn parser_owned_external_module_handoff_starts_pending_script_tree_root_fetch()
reserved_service_worker_client_id: None,
navigation_history_source: None,
about_document_state: None,
},
PageVmRuntimeHooks::standalone_without_owner_reservation_for_test(),
parser_dom_host,
@@ -1109,6 +1117,8 @@ fn parser_owned_inline_importmap_handoff_registers_parser_owned_handle_on_live_b
reserved_service_worker_client_id: None,
navigation_history_source: None,
about_document_state: None,
},
PageVmRuntimeHooks::standalone_without_owner_reservation_for_test(),
parser_dom_host,
@@ -1275,6 +1285,8 @@ fn parser_owner_style_import_handoff_is_stylesheet_gated_on_live_page_vm() {
reserved_service_worker_client_id: None,
navigation_history_source: None,
about_document_state: None,
},
PageVmRuntimeHooks::standalone_without_owner_reservation_for_test(),
parser_dom_host,
@@ -1157,6 +1157,8 @@ fn parser_connected_head_document_write_keeps_later_head_tokens_in_head() {
reserved_service_worker_client_id: None,
navigation_history_source: None,
about_document_state: None,
},
PageVmRuntimeHooks::standalone_without_owner_reservation_for_test(),
parser_dom_host,
+26 -3
View File
@@ -2401,6 +2401,7 @@ impl ScriptVmDefaultWorldBootstrap {
None,
None,
None,
None,
)
}
@@ -2427,8 +2428,13 @@ impl ScriptVmDefaultWorldBootstrap {
reserved_service_worker_client_id: Option<
crate::service_worker_runtime::ServiceWorkerClientId,
>,
about_document_state: Option<crate::runtime::RendererAboutDocumentState>,
) -> std::result::Result<Self, ScriptVmBootstrapError> {
ScriptVmPageRealmBootstrap::new_from_dom_host(
let top_level_storage_key = about_document_state
.as_ref()
.and_then(crate::runtime::RendererAboutDocumentState::storage_key)
.or(top_level_storage_key);
let mut bootstrap = ScriptVmPageRealmBootstrap::new_from_dom_host(
bootstrap_dom_host,
document_settings,
page_task_tx,
@@ -2446,8 +2452,25 @@ impl ScriptVmDefaultWorldBootstrap {
top_level_storage_key,
reserved_service_worker_client_id,
None,
)?
.bootstrap_default_world()
)?;
if let Some(state) = &about_document_state {
bootstrap
.document_runtime
.set_main_navigation_policy_container(state.policy_container().clone());
bootstrap
.document_runtime
.initialize_inherited_meta_content_security_policies(
bootstrap.document_runtime.document_handle(),
&state
.policy_container()
.inherited_meta_content_security_policies,
);
}
bootstrap
.context_host
.borrow_mut()
.set_main_about_document_state(about_document_state);
bootstrap.bootstrap_default_world()
}
fn capture_baseline_globals_and_attach_context(
@@ -583,6 +583,7 @@ impl ScriptVm {
.with_navigation_history(
pending.entry_seed.map(|seed| self.top_level_navigation_history().request(seed)),
)
.with_about_document_state(pending.about_document_state)
.with_web_mcp_invocation(pending.web_mcp_invocation)
.with_history_mutation(history_mutation)
.with_navigation_source(
+1 -4
View File
@@ -410,10 +410,7 @@ impl ScriptVmContextBootstrap {
WindowContextBootstrapMode::MainDefault
| WindowContextBootstrapMode::Isolated {
child_handle: None, ..
} => unsafe { &*host_ptr }
.current_main_document_resource_loader()
.and_then(|loader| url::Url::parse(loader.fetch_context().origin()).ok())
.unwrap_or_else(|| unsafe { &*host_ptr }.document_url().clone()),
} => unsafe { &*host_ptr }.main_document_secure_context_url(),
};
if let WindowContextBootstrapMode::Isolated { child_handle, .. } = mode {
let owner_context = match child_handle {
+1 -5
View File
@@ -1809,11 +1809,7 @@ fn window_message_endpoint_origin(
endpoint: PendingWindowMessageEndpoint,
) -> Option<String> {
match endpoint {
PendingWindowMessageEndpoint::TopWindow => Some(
host.current_main_document_resource_loader()
.map(|loader| loader.fetch_context().origin().to_owned())
.unwrap_or_else(|| moli_url::origin_ascii_serialization(host.document_url())),
),
PendingWindowMessageEndpoint::TopWindow => Some(host.main_document_origin()),
PendingWindowMessageEndpoint::ChildWindow(handle) => {
host.child_browsing_context_target_origin(handle)
}