fix(rebase): reconcile the native runtime with origin/main

This commit is contained in:
ldm0
2026-11-24 14:43:14 +08:00
parent 1376aa7098
commit 32cd63f6a4
67 changed files with 2600 additions and 1730 deletions
Generated
+12 -12
View File
@@ -2501,7 +2501,7 @@ version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef975e30683b2d965054bb0a836f8973857c4ebf6acf274fe46617cd285060d8"
dependencies = [
"foldhash",
"foldhash 0.2.0",
"libm",
"portable-atomic",
"siphasher",
@@ -2922,8 +2922,8 @@ dependencies = [
"libc",
"log",
"rustversion",
"windows-link",
"windows-result",
"windows-link 0.1.3",
"windows-result 0.3.4",
]
[[package]]
@@ -4252,9 +4252,9 @@ dependencies = [
"jni-sys 0.4.1",
"log",
"simd_cesu8",
"thiserror",
"thiserror 2.0.18",
"walkdir",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -4976,7 +4976,7 @@ dependencies = [
"half",
"moli-image",
"moli-web-mime",
"strum",
"strum 0.28.0",
]
[[package]]
@@ -5110,7 +5110,7 @@ dependencies = [
"moli-web-storage",
"moli-wpt-compat",
"parking_lot",
"percent-encoding 2.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
"percent-encoding",
"sanitize-filename",
"serde",
"serde_json",
@@ -5484,7 +5484,7 @@ dependencies = [
"matroska-demuxer",
"ogg",
"shiguredo_libvpx",
"thiserror",
"thiserror 2.0.18",
]
[[package]]
@@ -8084,7 +8084,7 @@ dependencies = [
"rustc-hash 2.1.1",
"rustls",
"socket2",
"thiserror",
"thiserror 2.0.18",
"tokio",
"tracing",
"web-time",
@@ -8109,7 +8109,7 @@ dependencies = [
"rustls-pki-types",
"rustls-platform-verifier",
"slab",
"thiserror",
"thiserror 2.0.18",
"tinyvec",
"tracing",
"web-time",
@@ -11065,7 +11065,7 @@ dependencies = [
"bytes",
"http",
"sfv",
"thiserror",
"thiserror 2.0.18",
"tokio",
"url",
]
@@ -11081,7 +11081,7 @@ dependencies = [
"quinn",
"rustls",
"rustls-native-certs",
"thiserror",
"thiserror 2.0.18",
"tokio",
"tracing",
"url",
+2 -2
View File
@@ -291,10 +291,10 @@ pub fn email_value_type_mismatch(value: &str, multiple: bool) -> bool {
if multiple {
return value
.split(',')
.map(|address| address.trim_matches(is_ascii_whitespace_char))
.map(str::trim_ascii)
.any(|address| address.is_empty() || !is_valid_email_address(address));
}
!is_valid_email_address(value.trim_matches(is_ascii_whitespace_char))
!is_valid_email_address(value.trim_ascii())
}
pub fn is_valid_email_address(value: &str) -> bool {
+4 -1
View File
@@ -72,7 +72,10 @@ fn initial_custom_element_state_for_identity(
fn is_element_reference_attribute(name: &str) -> bool {
matches!(
name,
"aria-activedescendant"
"commandfor"
| "interestfor"
| "popovertarget"
| "aria-activedescendant"
| "aria-controls"
| "aria-describedby"
| "aria-details"
@@ -65,7 +65,7 @@ fn reconnecting_shadow_trees_restores_compacted_frame_candidates() {
host.child_browsing_context_host_candidate_handles()
.is_empty()
);
assert!(frames(&host, outer).is_empty());
assert_eq!(frames(&host, outer), vec![frame]);
assert!(host.append_child(body, outer));
assert_eq!(
@@ -76,7 +76,7 @@ fn reconnecting_shadow_trees_restores_compacted_frame_candidates() {
assert!(host.remove_child(body, outer));
host.compact_child_browsing_context_host_candidates();
assert!(frames(&host, body).is_empty());
assert!(frames(&host, shadow).is_empty());
assert_eq!(frames(&host, shadow), vec![frame]);
assert!(host.append_child(body, outer));
assert_eq!(
@@ -115,7 +115,7 @@ fn cloned_imported_and_adopted_shadow_frames_keep_candidate_membership() {
assert!(host.append_child(secondary, cloned));
host.compact_child_browsing_context_host_candidates();
assert_eq!(frames(&host, body), vec![imported_frame]);
assert!(frames(&host, secondary).is_empty());
assert_eq!(frames(&host, secondary), vec![clone_frame]);
assert_eq!(host.owner_document_handle(clone_frame), Some(secondary));
assert!(host.append_child(body, cloned));
@@ -153,5 +153,5 @@ fn frame_candidates_exclude_inert_template_contents_and_foreign_elements() {
assert_eq!(frames(&host, body), vec![live_frame]);
assert!(frames(&host, template).is_empty());
assert!(frames(&host, contents).is_empty());
assert_eq!(frames(&host, contents), vec![inert_frame]);
}
+6 -5
View File
@@ -61,11 +61,12 @@ pub use layout_tree::{
LayoutFragmentKind, LayoutHit, LayoutIntersectionClip, LayoutIntersectionGeometry,
LayoutNodeOutput, LayoutObjectGeometry, LayoutOutputBoxId, LayoutPaintedSurfaceHit,
LayoutPassMetrics, LayoutPassResult, LayoutPoint, LayoutQuad, LayoutQuery, LayoutQueryAnswer,
LayoutQueryBatch, LayoutRect, LayoutResizeObserverBox, LayoutResizeObserverMetrics, LayoutResizeObserverSize,
LayoutResolvedGridTrackList, LayoutResolvedGridTracks, LayoutScrollContainerMetrics,
LayoutScrollExtent, LayoutScrollIntoViewGeometry, LayoutSize, LayoutTextGeometryRange, LayoutTransform2D,
LayoutTreeRetentionMetrics, LayoutUsedSize, LayoutViewport, MAX_RETAINED_LAYOUT_BOXES,
MAX_RETAINED_LAYOUT_FRAGMENTS, MAX_RETAINED_LAYOUT_TREE_BYTES, ScrollProjectionRefresh,
LayoutQueryBatch, LayoutRect, LayoutResizeObserverBox, LayoutResizeObserverMetrics,
LayoutResizeObserverSize, LayoutResolvedGridTrackList, LayoutResolvedGridTracks,
LayoutScrollContainerMetrics, LayoutScrollExtent, LayoutScrollIntoViewGeometry, LayoutSize,
LayoutTextGeometryRange, LayoutTransform2D, LayoutTreeRetentionMetrics, LayoutUsedSize,
LayoutViewport, MAX_RETAINED_LAYOUT_BOXES, MAX_RETAINED_LAYOUT_FRAGMENTS,
MAX_RETAINED_LAYOUT_TREE_BYTES, ScrollProjectionRefresh,
};
pub use list::{ListCounter, list_marker_text};
pub use normalize::{NormalizedBoxNode, NormalizedBoxTree, NormalizedFormattingContext};
+4 -1
View File
@@ -1,4 +1,7 @@
use std::cell::{Cell, RefCell};
use std::{
cell::{Cell, RefCell},
rc::Rc,
};
use html5ever::{
ParseOpts,
+5 -13
View File
@@ -101,7 +101,6 @@ pub(crate) use indexed_db::{
mod location_history_storage;
mod location_navigation;
mod location_runtime;
pub(crate) use location_runtime::install_constructed_document_location_runtime_state;
mod media_cues;
pub(crate) use media_cues::new_media_error_value;
mod media_file_template;
@@ -272,10 +271,6 @@ pub(crate) use navigation_events::{
dispatch_beforeunload_for_runtime_owner, dispatch_pagehide_for_runtime_owner,
dispatch_pageswap_for_runtime_owner, dispatch_unload_for_runtime_owner,
};
pub(crate) use navigation_events::{
dispatch_cross_document_navigation_navigate_event_for_window_with_form_data,
dispatch_cross_document_navigation_navigate_event_for_window_with_type_and_form_data,
};
pub(crate) use navigation_history_pruning::{
NavigationHistoryPrunePlan, apply_navigation_history_prune_plan,
finalize_navigation_history_prune, plan_navigation_history_prune,
@@ -677,14 +672,11 @@ pub(crate) use self::websocket::{
WebSocketDispatchResult, WebSocketStreamAbortRegistration, dispatch_websocket_event,
};
pub(crate) use self::window_events::{
WINDOW_EVENT_HANDLER_PROPERTIES,
clear_simple_window_event_handler_values, dispatch_window_callback_exception,
dispatch_window_error_event, dispatch_window_error_event_with_details,
dispatch_window_promise_rejection_event, dispatch_window_report_error_message,
event_handler_property_is_exposed, install_secure_window_event_handler_accessors,
install_simple_window_event_handlers,
is_window_event_handler_property, set_window_body_onerror_handler_compiled,
set_window_onerror_handler_value, window_body_onerror_handler_is_compiled,
WINDOW_EVENT_HANDLER_PROPERTIES, clear_simple_window_event_handler_values,
dispatch_window_callback_exception, dispatch_window_error_event,
dispatch_window_error_event_with_details, dispatch_window_promise_rejection_event,
dispatch_window_report_error_message, install_secure_window_event_handler_accessors,
install_simple_window_event_handlers, is_window_event_handler_property,
window_event_handler_properties,
};
#[cfg(test)]
@@ -139,6 +139,10 @@ const NODE_BRIDGE_DESCRIPTORS: &[BridgeDescriptor] = &[
SpecializedTemplateInstaller::None,
SVG_GEOMETRY_RUNTIME_INSTALL_GROUPS,
),
descriptor(
web_api_interfaces::SVGFilterElement::DESCRIPTOR,
ELEMENT_GROUPS,
),
descriptor(
web_api_interfaces::SVGDefsElement::DESCRIPTOR,
ELEMENT_GROUPS,
@@ -414,6 +418,10 @@ const NODE_BRIDGE_DESCRIPTORS: &[BridgeDescriptor] = &[
web_api_interfaces::SVGUseElement::DESCRIPTOR,
ELEMENT_GROUPS,
),
descriptor(
web_api_interfaces::SVGViewElement::DESCRIPTOR,
ELEMENT_GROUPS,
),
specialized_descriptor(
web_api_interfaces::SVGRectElement::DESCRIPTOR,
ELEMENT_GROUPS,
@@ -421,7 +421,9 @@ fn map_property_names<'s>(
style: v8::Local<'s, v8::Object>,
) -> Option<Vec<String>> {
if !native_bridge::element::style_declaration_is_computed(scope, style) {
return Some(detached_css_style::css_declaration_property_names(scope, style));
return Some(detached_css_style::css_declaration_property_names(
scope, style,
));
}
// Computed CSSStyleDeclaration and Typed OM enumerate one public property list.
let mut names = native_bridge::element::style_property_names_from_object(scope, style)?;
@@ -4,22 +4,22 @@ use super::{
event_init_event_callback, mouse_event_init_callback, text_event_init_callback,
},
events::{
composition_event_init_callback, event_bubbles_getter_function,
event_cancel_bubble_getter_function, event_cancel_bubble_setter_function,
event_cancelable_getter_function, event_composed_getter_function,
event_composed_path_callback, event_current_target_getter_function,
event_default_prevented_getter_function, event_event_phase_getter_function,
event_get_modifier_state_callback, event_platform_attribute_getter,
event_prevent_default_callback, event_return_value_getter_function,
event_return_value_setter_function, event_src_element_getter_function,
event_stop_immediate_propagation_callback, event_stop_propagation_callback,
event_target_getter_function, event_time_stamp_getter_function, event_type_getter_function,
event_value_attribute_getter, focus_event_related_target_getter_function,
form_data_event_form_data_getter_function, input_event_get_target_ranges_callback,
interaction_event_source_getter, keyboard_event_init_callback,
mouse_event_related_target_getter_function, pointer_event_get_predicted_events_callback,
submit_event_submitter_getter_function, time_event_init_callback, ui_event_init_callback,
ui_event_pseudo_target_getter_function, ui_event_which_getter_function,
event_bubbles_getter_function, event_cancel_bubble_getter_function,
event_cancel_bubble_setter_function, event_cancelable_getter_function,
event_composed_getter_function, event_composed_path_callback,
event_current_target_getter_function, event_default_prevented_getter_function,
event_event_phase_getter_function, event_get_modifier_state_callback,
event_platform_attribute_getter, event_prevent_default_callback,
event_return_value_getter_function, event_return_value_setter_function,
event_src_element_getter_function, event_stop_immediate_propagation_callback,
event_stop_propagation_callback, event_target_getter_function,
event_time_stamp_getter_function, event_type_getter_function, event_value_attribute_getter,
focus_event_related_target_getter_function, form_data_event_form_data_getter_function,
input_event_get_target_ranges_callback, interaction_event_source_getter,
keyboard_event_init_callback, mouse_event_related_target_getter_function,
pointer_event_get_predicted_events_callback, submit_event_submitter_getter_function,
time_event_init_callback, ui_event_pseudo_target_getter_function,
ui_event_which_getter_function,
},
selection_surface::document_get_selection_callback,
specs::ConstructorSpec,
@@ -28,6 +28,7 @@ use crate::util::v8str;
use crate::web_api_interfaces;
use crate::{native_bridge::document, window_host};
use moli_webapi::events::subclasses::EventTemplateDeclaration;
use moli_webapi::events::ui::{composition_event_init_callback, ui_event_init_callback};
use moli_webapi_declare::WebApiFunctionTemplate;
#[derive(WebApiFunctionTemplate)]
@@ -22,6 +22,7 @@ pub(crate) use moli_webapi::events::subclasses::submit::{
use moli_webapi::events::value;
pub(crate) use subclasses::clear_input_event_target_ranges;
pub(crate) use subclasses::initialize_native_security_policy_violation_event;
pub(in crate::context_bootstrap) use subclasses::input_event_get_target_ranges_callback;
mod time;
mod wrappers;
@@ -12,6 +12,7 @@ use crate::context_bootstrap::{
MEDIA_QUERY_LIST_REGISTRY_SLOT,
};
use crate::context_bootstrap::{global_queue_array, push_object_to_global_registry};
use crate::event_type::EventTypeKey;
use crate::native_bridge::{
PageScriptHost, WindowDocumentTaskTarget, WindowExecutionContextBinding,
};
@@ -148,7 +148,7 @@ impl<'s> SimpleObjectEventListenerSnapshot<'s> {
&self,
scope: &mut v8::PinScope<'s, '_>,
registry: SimpleEventListenerRegistry<'s>,
event_type: &str,
event_type: &(impl EventTypeKey + ?Sized),
) -> Option<Self> {
// Removing and re-adding the same callback creates a different entry.
// The removed entry must stay inactive in an existing dispatch snapshot.
@@ -156,6 +156,27 @@ impl<'s> SimpleObjectEventListenerSnapshot<'s> {
return None;
}
let listener = if self.handler_slot.is_some() {
let target = get_private_value(scope, self.entry, HANDLER_TARGET_SLOT)
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
if let Some(popup_id) = lightweight_popup_id_from_window(scope, target)
&& let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)
{
let value = unsafe { &mut *host_ptr }
.lightweight_popup_event_handler_property_value(
scope,
popup_id,
self.handler_slot.as_deref()?,
)?;
// A failed lazy compilation returns null for this read even
// if its error handler has installed a replacement callback.
if !value.is_object()
|| !simple_object_event_listener_entry_registered(
scope, registry, event_type, self.entry,
)
{
return None;
}
}
// An active handler keeps its registration position, but its value
// and callback contexts can change before dispatch reaches it.
simple_object_event_listener_snapshot_entry(scope, self.entry.into())?
@@ -1095,6 +1116,9 @@ fn simple_object_event_handler_entry_object<'s>(
relevant_identity: Option<WindowExecutionContextIdentity>,
) -> v8::Local<'s, v8::Object> {
let marker = format!("event-handler:{handler_slot_name}");
let value = callback
.map(v8::Local::<v8::Value>::from)
.unwrap_or_else(|| v8::null(scope).into());
let entry = SimpleObjectEventHandlerEntryDeclaration::new(
v8_string(scope, &marker),
v8_string(scope, handler_slot_name).expect("event handler slot"),
@@ -20,7 +20,7 @@ use crate::{
TextEditInputType, contenteditable_editing_host, dispatch_beforeinput,
dispatch_public_event, is_text_control, is_text_control_user_editable,
replace_contenteditable_selection_after_beforeinput,
replace_text_control_selection_after_beforeinput,
replace_text_control_selection_with_input_event,
text_control_set_selection_range_internal, text_control_value,
},
node_owner_document_relevant_context,
@@ -401,7 +401,7 @@ impl ViewportEditing {
revision,
&range,
&text,
TextEditInputType::InsertFromPaste,
TextEditInputType::InsertFromViewportPaste,
);
if existing.is_some() {
composition_event(scope, host_ptr, target, "compositionend", "");
@@ -499,9 +499,7 @@ fn replace_range(
if live.map.is_some() {
replace_contenteditable_selection_after_beforeinput(scope, host, target, text, input_type)
} else {
replace_text_control_selection_after_beforeinput(
scope, host, target, text, input_type, None,
)
replace_text_control_selection_with_input_event(scope, host, target, text, input_type, None)
}
}
@@ -30,6 +30,14 @@ use moli_webapi_declare::WebApiFunctionTemplate;
const WINDOW_NAMED_PROPERTIES_READY_SLOT: &str = "__moliWindowNamedPropertiesReady";
const WINDOW_NAMED_PROPERTIES_REFLECT_SET_SLOT: &str = "__moliWindowNamedPropertiesReflectSet";
pub(in crate::context_bootstrap) fn is_window_named_properties_object<'s>(
scope: &mut v8::PinScope<'s, '_>,
object: v8::Local<'s, v8::Object>,
) -> bool {
get_private_value(scope, object, WINDOW_NAMED_PROPERTIES_READY_SLOT)
.is_some_and(|value| value.is_true())
}
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::Window, enumerable, receiver = crate::context_bootstrap::is_window_receiver)]
struct WindowEarlyTemplateMethodsDeclaration {
@@ -439,6 +439,18 @@ impl DocumentRuntime {
event_type: &(impl EventTypeKey + ?Sized),
registration: crate::host::EventListenerRegistration,
) {
if !self
.events
.has_event_handler_property_entry(target, event_type)
{
let content_attribute_owner =
crate::host::event_handler_content_attribute(self, target, event_type);
self.events.ensure_event_handler_content_attribute(
target,
event_type,
content_attribute_owner,
);
}
self.events
.insert_listener(target, event_type, registration);
}
@@ -775,3 +787,193 @@ fn source_target_for_reference_event(
crate::native_bridge::node_runtime_and_handle_from_object(scope, object).ok()?;
(runtime_ptr == host_ptr).then_some(EventTargetHandle::Node(handle))
}
impl DocumentRuntime {
pub(crate) fn set_compiled_event_handler_property(
&mut self,
target: EventTargetHandle,
event_type: &(impl EventTypeKey + ?Sized),
callback_id: Option<crate::native_bridge::EventCallbackId>,
) -> Option<crate::native_bridge::EventCallbackId> {
self.events
.set_compiled_event_handler_property(target, event_type, callback_id)
}
pub(crate) fn sync_event_handler_content_attribute(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut PageScriptHost,
handle: DomHandle,
name: &str,
namespace: Option<&str>,
value: Option<std::sync::Arc<crate::dom::native::DomStringValue>>,
) -> Option<crate::native_bridge::EventCallbackId> {
if namespace.is_some()
|| !crate::native_bridge::element::element_event_handler_content_attribute_applies(
self.dom_host(),
handle,
name,
)
{
return None;
}
let event_type = name
.strip_prefix("on")
.filter(|event_type| !event_type.is_empty())?;
let event_type =
crate::native_bridge::element::canonical_event_handler_event_type(event_type);
let is_body_or_frameset = self.dom_host().node(handle).is_some_and(|node| {
node.is_html_element_named("body") || node.is_html_element_named("frameset")
});
let reflects_window = is_body_or_frameset
&& crate::native_bridge::element::body_or_frameset_reflects_window_event_type(
event_type,
);
let owner = unsafe { &*host_ptr }.owner_dispatch_scope_for_node(handle);
if reflects_window && owner.is_none() {
return None;
}
let target = if reflects_window {
EventTargetHandle::Window
} else {
EventTargetHandle::Node(handle)
};
let csp_allowed = value.as_ref().and_then(|source| {
let host = unsafe { &mut *host_ptr };
if let Some(owner) = owner {
Some(host.allows_inline_event_handler_by_csp(
scope,
owner,
Some(handle),
source.as_str_lossy(),
))
} else {
host.windowless_inline_event_handler_csp_admission(
scope,
handle,
source.as_str_lossy(),
)
}
});
if csp_allowed == Some(false) {
// A blocked change leaves an existing handler and its listener
// position intact. A fresh blocked attribute must also prevent the
// legacy prebuilt-DOM fallback from compiling its DOM value later.
if (!reflects_window || owner == Some(crate::native_bridge::OwnerDispatchScope::Top))
&& !self
.events
.has_event_handler_property_entry(target, event_type)
{
self.events
.set_event_handler_property(target, event_type, None);
}
return None;
}
// Admission is fixed at the attribute change, using the node
// Document's global. Uncommitted navigation projections retain the
// fallback until their actual settings are available.
let csp_admission = if csp_allowed == Some(true) {
crate::host::EventHandlerCspAdmission::Allowed
} else {
crate::host::EventHandlerCspAdmission::Pending
};
let handler = value.map(|source| crate::host::UncompiledEventHandler {
source,
source_location: crate::host::UncompiledEventHandler::capture_source_location(
scope,
self.dom_host(),
handle,
name,
),
csp_admission,
});
if reflects_window {
match owner {
Some(crate::native_bridge::OwnerDispatchScope::Top) => {}
Some(crate::native_bridge::OwnerDispatchScope::Child(child_handle)) => {
return unsafe { &mut *host_ptr }
.set_child_window_event_handler_content_attribute(
child_handle,
event_type,
handler,
);
}
Some(crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id)) => {
unsafe { &mut *host_ptr }
.set_lightweight_popup_event_handler_content_attribute(
scope, popup_id, event_type, handler,
);
return None;
}
None => return None,
};
}
self.events
.set_event_handler_content_attribute(target, event_type, handler)
}
pub(crate) fn initialize_cloned_event_handler_content_attributes(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut PageScriptHost,
root: DomHandle,
) {
let mut stack = vec![root];
while let Some(handle) = stack.pop() {
stack.extend(self.dom_host.child_handles(handle));
stack.extend(self.dom_host.shadow_root_handle(handle));
let Some(element) = self.dom_host.node(handle).and_then(Node::as_element) else {
continue;
};
stack.extend(element.template_contents());
let names = element
.attributes()
.iter()
.filter(|attribute| {
attribute.namespace().is_empty()
&& crate::native_bridge::element::element_event_handler_content_attribute_applies(
&self.dom_host,
handle,
attribute.local_name(),
)
})
.map(|attribute| attribute.local_name().to_owned())
.collect::<Vec<_>>();
for name in names {
let Some(source) = self
.dom_host
.dom()
.get_attribute_dom_string_value(handle, &name)
else {
continue;
};
let location = crate::host::UncompiledEventHandler::capture_source_location(
scope,
&self.dom_host,
handle,
&name,
);
self.set_attribute_source_location(handle, None, &name, Some(location));
if let Some(previous) = self.sync_event_handler_content_attribute(
scope,
host_ptr,
handle,
&name,
None,
Some(std::sync::Arc::new(source)),
) {
unsafe { &mut *host_ptr }.release_event_callback(previous);
}
}
}
}
pub(crate) fn uncompiled_event_handler_content_attribute(
&self,
target: EventTargetHandle,
event_type: &(impl EventTypeKey + ?Sized),
) -> Option<crate::host::UncompiledEventHandler> {
self.events
.uncompiled_event_handler_content_attribute(target, event_type)
}
}
@@ -74,32 +74,33 @@ impl DocumentSubresourceCspKind {
#[must_use = "report-only and enforced CSP results must be handled together"]
#[derive(Default)]
pub(crate) struct DocumentContentSecurityPolicyCheck<
V = Option<DocumentContentSecurityPolicyViolation>,
> {
report_only_violation: V,
enforced_violation: V,
}
impl<V> DocumentContentSecurityPolicyCheck<V> {
pub(crate) fn into_violations(self) -> (V, V) {
(self.report_only_violation, self.enforced_violation)
}
pub(crate) struct DocumentContentSecurityPolicyCheck {
report_only_violations: Vec<DocumentContentSecurityPolicyViolation>,
enforced_violations: Vec<DocumentContentSecurityPolicyViolation>,
}
impl DocumentContentSecurityPolicyCheck {
pub(crate) fn has_no_violations(&self) -> bool {
self.report_only_violation.is_none() && self.enforced_violation.is_none()
self.report_only_violations.is_empty() && self.enforced_violations.is_empty()
}
pub(crate) fn into_violations(
self,
) -> (
Vec<DocumentContentSecurityPolicyViolation>,
Vec<DocumentContentSecurityPolicyViolation>,
) {
(self.report_only_violations, self.enforced_violations)
}
#[cfg(test)]
fn report_only_violation(&self) -> Option<&DocumentContentSecurityPolicyViolation> {
self.report_only_violation.as_ref()
self.report_only_violations.first()
}
#[cfg(test)]
fn enforced_violation(&self) -> Option<&DocumentContentSecurityPolicyViolation> {
self.enforced_violation.as_ref()
self.enforced_violations.first()
}
}
@@ -472,27 +473,25 @@ impl DocumentPolicyContainer {
) -> DocumentContentSecurityPolicyCheck {
let DocumentNavigationEmbeddingContext::Nested(ancestor_origins) = embedding_context else {
return DocumentContentSecurityPolicyCheck {
report_only_violation: None,
enforced_violation: None,
report_only_violations: Vec::new(),
enforced_violations: Vec::new(),
};
};
DocumentContentSecurityPolicyCheck {
report_only_violation:
content_security_policy_frame_ancestors_violation_with_disposition_and_reporting_endpoints(
&self.response_content_security_report_only_policies,
protected_url,
ancestor_origins,
ContentSecurityPolicyDisposition::Report,
&self.content_security_reporting_endpoints,
),
enforced_violation:
content_security_policy_frame_ancestors_violation_with_disposition_and_reporting_endpoints(
&self.response_content_security_policies,
protected_url,
ancestor_origins,
ContentSecurityPolicyDisposition::Enforce,
&self.content_security_reporting_endpoints,
),
report_only_violations: document_frame_ancestors_policy_violations(
&self.response_content_security_report_only_policies,
protected_url,
ancestor_origins,
ContentSecurityPolicyDisposition::Report,
&self.content_security_reporting_endpoints,
),
enforced_violations: document_frame_ancestors_policy_violations(
&self.response_content_security_policies,
protected_url,
ancestor_origins,
ContentSecurityPolicyDisposition::Enforce,
&self.content_security_reporting_endpoints,
),
}
}
@@ -1014,7 +1013,7 @@ impl DocumentRuntime {
self.set_stylesheet_owner_csp_disposition(
host_ptr,
owner,
super::StylesheetOwnerCspDisposition::from_blocked(enforced_violation.is_some()),
super::StylesheetOwnerCspDisposition::from_blocked(!enforced_violation.is_empty()),
);
for violation in [report_only_violation, enforced_violation]
.into_iter()
@@ -1184,12 +1183,6 @@ impl DocumentRuntime {
self.policy_container.content_security_reporting_endpoints = endpoints;
}
pub(crate) fn content_security_reporting_endpoints(
&self,
) -> &ContentSecurityPolicyReportingEndpoints {
&self.policy_container.content_security_reporting_endpoints
}
#[cfg(test)]
pub(crate) fn script_element_request_csp_violation(
&self,
@@ -1395,7 +1388,7 @@ impl DocumentRuntime {
let document_uri = document_uri.clone();
move |url: &Url, nonce: Option<&str>, redirect_status| {
let check = |policies: &[DocumentContentSecurityPolicy], disposition| {
document_style_element_url_policy_violation_from_document_policies(
document_style_element_url_policy_violations_from_document_policies(
policies,
&policy_url,
url,
@@ -1403,6 +1396,7 @@ impl DocumentRuntime {
disposition,
ContentSecurityPolicyStyleElementRequest { nonce },
)
.into_iter()
.map(|mut violation| {
if let Some(uri) = &document_uri {
violation.document_uri.clone_from(uri);
@@ -1410,6 +1404,7 @@ impl DocumentRuntime {
}
violation
})
.collect::<Vec<_>>()
};
(
check(&report, ContentSecurityPolicyDisposition::Report),
@@ -1450,7 +1445,7 @@ impl DocumentRuntime {
parser_inserted: metadata.parser_inserted,
};
let check = |policies: &[DocumentContentSecurityPolicy], disposition| {
document_module_url_policy_violation_from_document_policies(
document_module_url_policy_violations_from_document_policies(
policies,
&document_url,
url,
@@ -1591,7 +1586,7 @@ impl DocumentRuntime {
&self,
kind: ContentSecurityPolicyNonUrlKind,
source: &str,
) -> DocumentContentSecurityPolicyCheck<Vec<DocumentContentSecurityPolicyViolation>> {
) -> DocumentContentSecurityPolicyCheck {
self.inline_source_csp_check_for_document(
Some(self.document_handle()),
self.document_url(),
@@ -1645,11 +1640,11 @@ impl DocumentRuntime {
policy_container: &DocumentPolicyContainer,
source: &str,
request: ContentSecurityPolicyStyleElementRequest<'_>,
) -> DocumentContentSecurityPolicyCheck<Vec<DocumentContentSecurityPolicyViolation>> {
) -> DocumentContentSecurityPolicyCheck {
if self.bypass_content_security_policy() {
return DocumentContentSecurityPolicyCheck {
report_only_violation: Vec::new(),
enforced_violation: Vec::new(),
report_only_violations: Vec::new(),
enforced_violations: Vec::new(),
};
}
let enforced_policies = self.document_content_security_policies_for_optional_document(
@@ -1678,8 +1673,8 @@ impl DocumentRuntime {
ContentSecurityPolicyDisposition::Report,
);
DocumentContentSecurityPolicyCheck {
report_only_violation,
enforced_violation,
report_only_violations: report_only_violation,
enforced_violations: enforced_violation,
}
}
@@ -1694,14 +1689,15 @@ impl DocumentRuntime {
&self.policy_container.response_content_security_policies,
&self.policy_container.content_security_reporting_endpoints,
);
let enforced_violation = document_style_element_url_policy_violation_from_document_policies(
&enforced_policies,
document_url,
request_url,
ContentSecurityPolicyRedirectStatus::NoRedirect,
ContentSecurityPolicyDisposition::Enforce,
request,
);
let enforced_violation =
document_style_element_url_policy_violations_from_document_policies(
&enforced_policies,
document_url,
request_url,
ContentSecurityPolicyRedirectStatus::NoRedirect,
ContentSecurityPolicyDisposition::Enforce,
request,
);
let report_only_policies = document_response_content_security_policies(
&self
.policy_container
@@ -1709,7 +1705,7 @@ impl DocumentRuntime {
&self.policy_container.content_security_reporting_endpoints,
);
let report_only_violation =
document_style_element_url_policy_violation_from_document_policies(
document_style_element_url_policy_violations_from_document_policies(
&report_only_policies,
document_url,
request_url,
@@ -1718,8 +1714,8 @@ impl DocumentRuntime {
request,
);
DocumentContentSecurityPolicyCheck {
report_only_violation,
enforced_violation,
report_only_violations: report_only_violation,
enforced_violations: enforced_violation,
}
}
@@ -1733,14 +1729,15 @@ impl DocumentRuntime {
&self.policy_container.response_content_security_policies,
&self.policy_container.content_security_reporting_endpoints,
);
let enforced_violation = document_style_element_url_policy_violation_from_document_policies(
&enforced_policies,
document_url,
request_url,
ContentSecurityPolicyRedirectStatus::NoRedirect,
ContentSecurityPolicyDisposition::Enforce,
request,
);
let enforced_violation =
document_style_element_url_policy_violations_from_document_policies(
&enforced_policies,
document_url,
request_url,
ContentSecurityPolicyRedirectStatus::NoRedirect,
ContentSecurityPolicyDisposition::Enforce,
request,
);
let report_only_policies = document_response_content_security_policies(
&self
.policy_container
@@ -1748,7 +1745,7 @@ impl DocumentRuntime {
&self.policy_container.content_security_reporting_endpoints,
);
let report_only_violation =
document_style_element_url_policy_violation_from_document_policies(
document_style_element_url_policy_violations_from_document_policies(
&report_only_policies,
document_url,
request_url,
@@ -1757,8 +1754,8 @@ impl DocumentRuntime {
request,
);
DocumentContentSecurityPolicyCheck {
report_only_violation,
enforced_violation,
report_only_violations: report_only_violation,
enforced_violations: enforced_violation,
}
}
@@ -1772,7 +1769,7 @@ impl DocumentRuntime {
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
source: &str,
request: ContentSecurityPolicyScriptElementRequest<'_>,
) -> DocumentContentSecurityPolicyCheck<Vec<DocumentContentSecurityPolicyViolation>> {
) -> DocumentContentSecurityPolicyCheck {
let enforced_policies = self.document_content_security_policies_for_optional_document(
document_handle,
response_policies,
@@ -1799,8 +1796,8 @@ impl DocumentRuntime {
ContentSecurityPolicyDisposition::Report,
);
DocumentContentSecurityPolicyCheck {
report_only_violation,
enforced_violation,
report_only_violations: report_only_violation,
enforced_violations: enforced_violation,
}
}
@@ -1813,7 +1810,7 @@ impl DocumentRuntime {
response_reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
kind: ContentSecurityPolicyNonUrlKind,
source: &str,
) -> DocumentContentSecurityPolicyCheck<Vec<DocumentContentSecurityPolicyViolation>> {
) -> DocumentContentSecurityPolicyCheck {
let enforced_policies = self.document_content_security_policies_for_optional_document(
document_handle,
response_policies,
@@ -1838,8 +1835,8 @@ impl DocumentRuntime {
ContentSecurityPolicyDisposition::Report,
);
DocumentContentSecurityPolicyCheck {
report_only_violation,
enforced_violation,
report_only_violations: report_only_violation,
enforced_violations: enforced_violation,
}
}
@@ -1858,7 +1855,7 @@ impl DocumentRuntime {
response_policies,
response_reporting_endpoints,
);
let enforced_violation = document_non_url_policy_violation_from_document_policies(
let enforced_violation = document_non_url_policy_violations_from_document_policies(
enforced_policies,
document_url,
kind,
@@ -1869,7 +1866,7 @@ impl DocumentRuntime {
response_report_only_policies,
response_reporting_endpoints,
);
let report_only_violation = document_non_url_policy_violation_from_document_policies(
let report_only_violation = document_non_url_policy_violations_from_document_policies(
report_only_policies,
document_url,
kind,
@@ -1877,8 +1874,8 @@ impl DocumentRuntime {
ContentSecurityPolicyDisposition::Report,
);
DocumentContentSecurityPolicyCheck {
report_only_violation,
enforced_violation,
report_only_violations: report_only_violation,
enforced_violations: enforced_violation,
}
}
@@ -2478,8 +2475,7 @@ impl DocumentRuntime {
None
};
let violation = task.violation();
let event_target =
EventTargetHandle::Node(task.target().unwrap_or_else(|| self.document_handle()));
let event_target = EventTargetHandle::Node(task.target().unwrap_or(dispatch_document));
let event_target_value =
event_target_value(scope, host_ptr, event_target).map_err(anyhow::Error::msg)?;
let context = window_context
@@ -2693,25 +2689,6 @@ impl DocumentRuntime {
}
}
fn document_connect_policy_violation(
policies: &[ContentSecurityPolicy],
reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
document_url: &Url,
request_url: &Url,
redirect_status: ContentSecurityPolicyRedirectStatus,
disposition: ContentSecurityPolicyDisposition,
) -> Option<DocumentContentSecurityPolicyViolation> {
document_url_policy_violation(
policies,
reporting_endpoints,
document_url,
request_url,
ContentSecurityPolicyResourceKind::DocumentConnect,
redirect_status,
disposition,
)
}
fn document_frame_policy_violation(
policies: &[ContentSecurityPolicy],
reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
@@ -2812,25 +2789,6 @@ fn document_response_content_security_policies(
.collect()
}
fn document_connect_policy_violation_from_document_policies(
policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
fallback_self_origin: Option<&Url>,
request_url: &Url,
redirect_status: ContentSecurityPolicyRedirectStatus,
disposition: ContentSecurityPolicyDisposition,
) -> Option<DocumentContentSecurityPolicyViolation> {
document_url_policy_violation_from_document_policies(
policies,
document_url,
fallback_self_origin,
request_url,
ContentSecurityPolicyResourceKind::DocumentConnect,
redirect_status,
disposition,
)
}
fn document_frame_policy_violation_from_document_policies(
policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
@@ -2849,42 +2807,6 @@ fn document_frame_policy_violation_from_document_policies(
)
}
fn document_module_url_policy_violation_from_document_policies(
policies: &[DocumentContentSecurityPolicy],
document_url: &Url,
request_url: &Url,
original_url: &Url,
kind: crate::module_runtime::ModuleKind,
redirect_status: ContentSecurityPolicyRedirectStatus,
request: ContentSecurityPolicyScriptElementRequest<'_>,
disposition: ContentSecurityPolicyDisposition,
) -> Option<DocumentContentSecurityPolicyViolation> {
let resource_kind = crate::content_security_policy::module_csp_resource_kind(
kind,
ContentSecurityPolicyResourceKind::DocumentScriptElement,
);
use crate::content_security_policy::ContentSecurityPolicyUrlRequest;
let request = match resource_kind {
ContentSecurityPolicyResourceKind::DocumentScriptElement => {
ContentSecurityPolicyUrlRequest::Script(request)
}
ContentSecurityPolicyResourceKind::DocumentStyleElement => {
ContentSecurityPolicyUrlRequest::Style(ContentSecurityPolicyStyleElementRequest {
nonce: request.nonce,
})
}
_ => ContentSecurityPolicyUrlRequest::Standard,
};
policies.iter().find_map(|policy| {
let mut violation = crate::content_security_policy::content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request(
std::slice::from_ref(&policy.policy), document_url, None, request_url, original_url,
resource_kind, redirect_status, disposition, &policy.reporting_endpoints, request,
)?;
apply_document_policy_reporting_flags(&mut violation, policy);
Some(violation)
})
}
fn document_url_policy_violation_from_document_policies(
policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
@@ -2920,44 +2842,16 @@ fn document_script_element_url_policy_violation_from_document_policies(
disposition: ContentSecurityPolicyDisposition,
request: ContentSecurityPolicyScriptElementRequest<'_>,
) -> Option<DocumentContentSecurityPolicyViolation> {
policies.into_iter().find_map(|policy| {
let single_policy = [policy.policy.clone()];
let mut violation = document_script_element_url_policy_violation(
&single_policy,
&policy.reporting_endpoints,
document_url,
request_url,
redirect_status,
disposition,
request,
)?;
apply_document_policy_reporting_flags(&mut violation, &policy);
Some(violation)
})
}
fn document_style_element_url_policy_violation_from_document_policies(
policies: &[DocumentContentSecurityPolicy],
document_url: &Url,
request_url: &Url,
redirect_status: ContentSecurityPolicyRedirectStatus,
disposition: ContentSecurityPolicyDisposition,
request: ContentSecurityPolicyStyleElementRequest<'_>,
) -> Option<DocumentContentSecurityPolicyViolation> {
policies.iter().find_map(|policy| {
let single_policy = [policy.policy.clone()];
let mut violation = document_style_element_url_policy_violation(
&single_policy,
&policy.reporting_endpoints,
document_url,
request_url,
redirect_status,
disposition,
request,
)?;
apply_document_policy_reporting_flags(&mut violation, policy);
Some(violation)
})
document_script_element_url_policy_violations_from_document_policies(
policies,
document_url,
request_url,
redirect_status,
disposition,
request,
)
.into_iter()
.next()
}
fn document_non_url_policy_violation_from_document_policies(
@@ -2981,69 +2875,6 @@ fn document_non_url_policy_violation_from_document_policies(
})
}
fn document_inline_source_policy_violations_from_document_policies(
policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
kind: ContentSecurityPolicyNonUrlKind,
source: &str,
disposition: ContentSecurityPolicyDisposition,
) -> Vec<DocumentContentSecurityPolicyViolation> {
policies.into_iter().filter_map(|policy| {
let mut violation = content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
&policy.policy,
document_url,
kind,
source,
disposition,
&policy.reporting_endpoints,
)?;
apply_document_policy_reporting_flags(&mut violation, &policy);
Some(violation)
}).collect()
}
fn document_inline_script_element_policy_violations_from_document_policies(
policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
source: &str,
request: ContentSecurityPolicyScriptElementRequest<'_>,
disposition: ContentSecurityPolicyDisposition,
) -> Vec<DocumentContentSecurityPolicyViolation> {
policies.into_iter().filter_map(|policy| {
let mut violation = content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints(
&policy.policy,
document_url,
source,
request,
disposition,
&policy.reporting_endpoints,
)?;
apply_document_policy_reporting_flags(&mut violation, &policy);
Some(violation)
}).collect()
}
fn document_inline_style_element_policy_violations_from_document_policies(
policies: Vec<DocumentContentSecurityPolicy>,
document_url: &Url,
source: &str,
request: ContentSecurityPolicyStyleElementRequest<'_>,
disposition: ContentSecurityPolicyDisposition,
) -> Vec<DocumentContentSecurityPolicyViolation> {
policies.into_iter().filter_map(|policy| {
let mut violation = content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints(
&policy.policy,
document_url,
source,
request,
disposition,
&policy.reporting_endpoints,
)?;
apply_document_policy_reporting_flags(&mut violation, &policy);
Some(violation)
}).collect()
}
#[cfg(test)]
fn document_trusted_types_sink_policy_violation_from_document_policies(
policies: Vec<DocumentContentSecurityPolicy>,
@@ -3181,11 +3012,320 @@ pub(crate) fn response_content_security_report_only_policies_from_headers(
content_security_policy_report_only_headers(headers)
}
fn document_module_url_policy_violations_from_document_policies(
policies: impl AsRef<[DocumentContentSecurityPolicy]>,
document_url: &Url,
request_url: &Url,
original_url: &Url,
kind: crate::module_runtime::ModuleKind,
redirect_status: ContentSecurityPolicyRedirectStatus,
request: ContentSecurityPolicyScriptElementRequest<'_>,
disposition: ContentSecurityPolicyDisposition,
) -> Vec<DocumentContentSecurityPolicyViolation> {
let resource_kind = crate::content_security_policy::module_csp_resource_kind(
kind,
ContentSecurityPolicyResourceKind::DocumentScriptElement,
);
use crate::content_security_policy::ContentSecurityPolicyUrlRequest;
let request = match resource_kind {
ContentSecurityPolicyResourceKind::DocumentScriptElement => {
ContentSecurityPolicyUrlRequest::Script(request)
}
ContentSecurityPolicyResourceKind::DocumentStyleElement => {
ContentSecurityPolicyUrlRequest::Style(ContentSecurityPolicyStyleElementRequest {
nonce: request.nonce,
})
}
_ => ContentSecurityPolicyUrlRequest::Standard,
};
policies.as_ref().iter().filter_map(|policy| {
let mut violation = crate::content_security_policy::content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request(
std::slice::from_ref(&policy.policy), document_url, None, request_url, original_url,
resource_kind, redirect_status, disposition, &policy.reporting_endpoints, request,
)?;
apply_document_policy_reporting_flags(&mut violation, policy);
Some(violation)
}).collect()
}
fn document_url_policy_violations_from_document_policies(
policies: impl AsRef<[DocumentContentSecurityPolicy]>,
document_url: &Url,
fallback_self_origin: Option<&Url>,
request_url: &Url,
kind: ContentSecurityPolicyResourceKind,
redirect_status: ContentSecurityPolicyRedirectStatus,
disposition: ContentSecurityPolicyDisposition,
) -> Vec<DocumentContentSecurityPolicyViolation> {
policies.as_ref().iter().filter_map(|policy| {
let mut violation = crate::content_security_policy::content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_reporting_endpoints_and_request(
std::slice::from_ref(&policy.policy),
document_url,
fallback_self_origin,
request_url,
request_url,
kind,
redirect_status,
disposition,
&policy.reporting_endpoints,
crate::content_security_policy::ContentSecurityPolicyUrlRequest::Standard,
)?;
apply_document_policy_reporting_flags(&mut violation, policy);
Some(violation)
}).collect()
}
fn document_script_element_url_policy_violations_from_document_policies(
policies: impl AsRef<[DocumentContentSecurityPolicy]>,
document_url: &Url,
request_url: &Url,
redirect_status: ContentSecurityPolicyRedirectStatus,
disposition: ContentSecurityPolicyDisposition,
request: ContentSecurityPolicyScriptElementRequest<'_>,
) -> Vec<DocumentContentSecurityPolicyViolation> {
policies
.as_ref()
.iter()
.filter_map(|policy| {
let single_policy = [policy.policy.clone()];
let mut violation = document_script_element_url_policy_violation(
&single_policy,
&policy.reporting_endpoints,
document_url,
request_url,
redirect_status,
disposition,
request,
)?;
apply_document_policy_reporting_flags(&mut violation, policy);
Some(violation)
})
.collect()
}
fn document_style_element_url_policy_violations_from_document_policies(
policies: impl AsRef<[DocumentContentSecurityPolicy]>,
document_url: &Url,
request_url: &Url,
redirect_status: ContentSecurityPolicyRedirectStatus,
disposition: ContentSecurityPolicyDisposition,
request: ContentSecurityPolicyStyleElementRequest<'_>,
) -> Vec<DocumentContentSecurityPolicyViolation> {
policies
.as_ref()
.iter()
.filter_map(|policy| {
let single_policy = [policy.policy.clone()];
let mut violation = document_style_element_url_policy_violation(
&single_policy,
&policy.reporting_endpoints,
document_url,
request_url,
redirect_status,
disposition,
request,
)?;
apply_document_policy_reporting_flags(&mut violation, policy);
Some(violation)
})
.collect()
}
fn document_non_url_policy_violations_from_document_policies(
policies: impl AsRef<[DocumentContentSecurityPolicy]>,
document_url: &Url,
kind: ContentSecurityPolicyNonUrlKind,
source: Option<&str>,
disposition: ContentSecurityPolicyDisposition,
) -> Vec<DocumentContentSecurityPolicyViolation> {
policies
.as_ref()
.iter()
.filter_map(|policy| {
let mut violation = content_security_policy_non_url_violation_with_source(
&policy.policy,
document_url,
kind,
source,
disposition,
&policy.reporting_endpoints,
)?;
apply_document_policy_reporting_flags(&mut violation, policy);
Some(violation)
})
.collect()
}
fn document_inline_source_policy_violations_from_document_policies(
policies: impl AsRef<[DocumentContentSecurityPolicy]>,
document_url: &Url,
kind: ContentSecurityPolicyNonUrlKind,
source: &str,
disposition: ContentSecurityPolicyDisposition,
) -> Vec<DocumentContentSecurityPolicyViolation> {
policies.as_ref().iter().filter_map(|policy| {
let mut violation = content_security_policy_inline_source_violation_with_disposition_and_reporting_endpoints(
&policy.policy,
document_url,
kind,
source,
disposition,
&policy.reporting_endpoints,
)?;
apply_document_policy_reporting_flags(&mut violation, policy);
Some(violation)
}).collect()
}
fn document_inline_script_element_policy_violations_from_document_policies(
policies: impl AsRef<[DocumentContentSecurityPolicy]>,
document_url: &Url,
source: &str,
request: ContentSecurityPolicyScriptElementRequest<'_>,
disposition: ContentSecurityPolicyDisposition,
) -> Vec<DocumentContentSecurityPolicyViolation> {
policies.as_ref().iter().filter_map(|policy| {
let mut violation = content_security_policy_inline_script_element_violation_with_disposition_and_reporting_endpoints(
&policy.policy,
document_url,
source,
request,
disposition,
&policy.reporting_endpoints,
)?;
apply_document_policy_reporting_flags(&mut violation, policy);
Some(violation)
}).collect()
}
fn document_inline_style_element_policy_violations_from_document_policies(
policies: impl AsRef<[DocumentContentSecurityPolicy]>,
document_url: &Url,
source: &str,
request: ContentSecurityPolicyStyleElementRequest<'_>,
disposition: ContentSecurityPolicyDisposition,
) -> Vec<DocumentContentSecurityPolicyViolation> {
policies.as_ref().iter().filter_map(|policy| {
let mut violation = content_security_policy_inline_style_element_violation_with_disposition_and_reporting_endpoints(
&policy.policy,
document_url,
source,
request,
disposition,
&policy.reporting_endpoints,
)?;
apply_document_policy_reporting_flags(&mut violation, policy);
Some(violation)
}).collect()
}
fn document_url_policy_violations(
policies: &[ContentSecurityPolicy],
reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
document_url: &Url,
request_url: &Url,
kind: ContentSecurityPolicyResourceKind,
redirect_status: ContentSecurityPolicyRedirectStatus,
disposition: ContentSecurityPolicyDisposition,
) -> Vec<DocumentContentSecurityPolicyViolation> {
policies
.iter()
.filter_map(|policy| {
document_url_policy_violation(
std::slice::from_ref(policy),
reporting_endpoints,
document_url,
request_url,
kind,
redirect_status,
disposition,
)
})
.collect()
}
fn document_frame_ancestors_policy_violations(
policies: &[ContentSecurityPolicy],
protected_url: &Url,
ancestor_origins: &[Option<Url>],
disposition: ContentSecurityPolicyDisposition,
reporting_endpoints: &ContentSecurityPolicyReportingEndpoints,
) -> Vec<DocumentContentSecurityPolicyViolation> {
policies.iter().filter_map(|policy| {
content_security_policy_frame_ancestors_violation_with_disposition_and_reporting_endpoints(
std::slice::from_ref(policy), protected_url, ancestor_origins,
disposition, reporting_endpoints,
)
}).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parser::HtmlParser;
#[test]
fn captured_module_and_stylesheet_csp_keep_all_policy_deliveries() {
let mut runtime = runtime_for_html(
r#"<!doctype html><head>
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; report-uri /report">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; report-uri /report">
</head>"#,
);
let policies = vec!["default-src 'none'; report-uri /report".to_owned(); 2];
runtime.set_response_content_security_policies(&policies);
runtime.set_response_content_security_report_only_policies(&policies);
let url = Url::parse("https://example.test/resource").unwrap();
let module = runtime.module_fetch_csp_context(
&url,
crate::module_runtime::ModuleKind::JavaScript,
&crate::module_runtime::ModuleFetchMetadata::default(),
);
assert!(module.check_initial_request(&url).is_err());
assert!(module.check_initial_request(&url).is_err());
let module_violations = module.take_violations();
assert!(module.take_violations().is_empty());
let stylesheet = runtime.stylesheet_fetch_csp_context_for_document(
Some(runtime.document_handle()),
runtime.document_url(),
&runtime.policy_container,
None,
);
let request = stylesheet.for_request(None);
assert!(request(&url, 0).is_err());
assert!(request(&url, 0).is_err());
let style_violations = stylesheet.take_violations();
assert!(stylesheet.take_violations().is_empty());
for violations in [module_violations, style_violations] {
assert_eq!(violations.len(), 6);
assert_eq!(
violations
.iter()
.filter(|v| v.disposition == ContentSecurityPolicyDisposition::Report)
.count(),
2
);
assert_eq!(
violations
.iter()
.filter(|v| v.disposition == ContentSecurityPolicyDisposition::Enforce)
.count(),
4
);
assert_eq!(
violations
.iter()
.filter(|v| !v.report_uri_endpoints.is_empty())
.count(),
4
);
assert!(violations.iter().all(|v| v.original_policy == policies[0]));
}
let another_request = stylesheet.for_request(None);
assert!(another_request(&url, 0).is_err());
assert_eq!(stylesheet.take_violations().len(), 6);
}
fn runtime_for_html(html: &str) -> DocumentRuntime {
let document_url = Url::parse("https://example.test/page").expect("document url");
let document = HtmlParser::SCRIPTING_ENABLED.parse(document_url, html.to_owned());
@@ -3626,8 +3766,6 @@ mod tests {
"trusted-types 'none'; report-uri /report",
]
.map(str::to_owned);
let enforced = enforced.map(moli_csp::ContentSecurityPolicy::from);
let report_only = report_only.map(moli_csp::ContentSecurityPolicy::from);
let reports = runtime.trusted_type_policy_name_csp_violations_for_document(
Some(runtime.document_handle()),
runtime.document_url(),
@@ -4775,12 +4913,14 @@ mod tests {
DocumentNavigationEmbeddingContext::Nested(&ancestors),
)
.into_violations();
assert_eq!(report_only.len(), 1);
assert_eq!(enforced.len(), 1);
assert_eq!(
report_only.unwrap().disposition,
report_only[0].disposition,
ContentSecurityPolicyDisposition::Report
);
assert_eq!(
enforced.unwrap().disposition,
enforced[0].disposition,
ContentSecurityPolicyDisposition::Enforce
);
}
+4 -3
View File
@@ -34,9 +34,10 @@ pub(crate) use self::events::EventListenerRegistration;
pub(super) use self::events::{
DispatchStatus, HostEventTargetRegistry, PublicEventDispatchResult, create_host_event,
dispatch_host_event, dispatch_public_event, dispatch_public_event_with_original_target,
event_dispatch_status, event_target_value, host_event_defaults,
invoke_prepared_before_unload_event_handler, invoke_prepared_event_callback,
report_event_callback_exception, report_event_listener_exception,
event_dispatch_status, event_handler_content_attribute, event_target_value,
host_event_defaults, invoke_prepared_before_unload_event_handler,
invoke_prepared_event_callback, report_event_callback_exception,
report_event_listener_exception,
};
pub(crate) use self::events::{
EventHandlerCspAdmission, EventHandlerPropertyState, ListenerFilter, UncompiledEventHandler,
File diff suppressed because it is too large Load Diff
@@ -215,6 +215,7 @@ impl PageScriptHost {
// resources discovered by the outer step before parking it too.
let discovery_signals = parser.take_discovery_signals();
self.queue_live_child_parser_discovery_signals(
scope,
child_handle,
document_handle,
discovery_signals,
@@ -581,6 +582,7 @@ impl PageScriptHost {
parser.finish(&mut owner)
};
self.queue_live_child_parser_discovery_signals(
scope,
child_handle,
document_handle,
finish_signals.discovery_signals,
@@ -624,6 +626,7 @@ impl PageScriptHost {
fn queue_live_child_parser_discovery_signals(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
child_handle: DomHandle,
document_handle: DomHandle,
discovery_signals: crate::live_document_parser::LiveDocumentParserDiscoverySignals,
@@ -898,6 +901,7 @@ impl PageScriptHost {
return false;
}
self.queue_live_child_parser_discovery_signals(
scope,
child_handle,
document_handle,
insertion.take_discovery_signals(),
@@ -637,10 +637,7 @@ impl PageScriptHost {
true,
)
}
Ok(
outcome @ (ChildDocumentLoadOutcome::Redirect(_)
| ChildDocumentLoadOutcome::Download(_)),
) => (Ok(outcome), false),
Ok(outcome @ ChildDocumentLoadOutcome::Redirect(_)) => (Ok(outcome), false),
Err(error) => (Err(error), true),
}
} else {
@@ -8,20 +8,20 @@ use crate::{
},
document_runtime::DomHandle,
document_runtime::EventTargetHandle,
exception_reporting::invoke_event_handler,
frame_owner_model::{FrameDocumentTaskOwner, LocalWindowId},
host::{
ChildWindowEventTarget, DispatchStatus, create_host_event, event_dispatch_status,
invoke_prepared_before_unload_event_handler, invoke_prepared_event_callback,
ChildWindowEventTarget, DispatchStatus, EventHandlerPropertyState, UncompiledEventHandler,
create_host_event, event_dispatch_status, invoke_prepared_before_unload_event_handler,
invoke_prepared_event_callback,
},
native_bridge::{
ACTIVE_CHILD_WINDOW_HANDLE_SLOT, EventCallbackId, PreparedEventCallback,
element::EventAttributeHandlerScope, element::compile_event_attribute_handler_for_owner,
element::compile_body_window_event_attribute,
},
util::{get_private_value, set_private_value, v8_string, v8str},
util::{get_private_value, set_private_value},
v8_execution_watchdog::V8ExecutionWatchdog,
};
use std::{collections::HashSet, convert::TryFrom};
use std::collections::HashSet;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ChildWindowEventRegistrationKind {
@@ -34,7 +34,7 @@ struct ChildWindowEventRegistrationId(u64);
pub(super) struct ChildWindowEventListenerEntry {
registration_id: ChildWindowEventRegistrationId,
callback_id: EventCallbackId,
callback_state: EventHandlerPropertyState,
registration_kind: ChildWindowEventRegistrationKind,
local_window_id: Option<LocalWindowId>,
capture: bool,
@@ -42,7 +42,7 @@ pub(super) struct ChildWindowEventListenerEntry {
}
struct ChildWindowEventListenerSnapshot {
callback_id: EventCallbackId,
callback_state: EventHandlerPropertyState,
registration_kind: ChildWindowEventRegistrationKind,
local_window_id: Option<LocalWindowId>,
once: bool,
@@ -149,7 +149,7 @@ impl PageScriptHost {
entry.registration_kind == ChildWindowEventRegistrationKind::EventListener
&& entry.capture == capture
})
.map(|entry| entry.callback_id)
.filter_map(|entry| entry.callback_state.callback_id())
.collect()
}
@@ -199,7 +199,7 @@ impl PageScriptHost {
.or_default()
.push(ChildWindowEventListenerEntry {
registration_id,
callback_id,
callback_state: EventHandlerPropertyState::Callback(callback_id),
registration_kind: ChildWindowEventRegistrationKind::EventListener,
local_window_id: Some(target.owner().local_window_id),
capture,
@@ -212,7 +212,7 @@ impl PageScriptHost {
scope: &mut v8::PinScope<'s, '_>,
handle: DomHandle,
handler_name: &str,
handler: Option<v8::Local<'s, v8::Function>>,
handler: Option<v8::Local<'s, v8::Object>>,
callback_relevant_context: v8::Local<'s, v8::Context>,
) {
let Some(event_type) = child_window_event_type_from_handler_name(handler_name) else {
@@ -226,20 +226,51 @@ impl PageScriptHost {
}
return;
};
let owner = self.frame_owner_current_child_snapshot(handle);
let local_window_id = owner.as_ref().map(|owner| owner.local_window_id);
let incumbent_context = scope
.get_incumbent_context()
.unwrap_or_else(|| scope.get_current_context());
let callback = v8::Local::<v8::Object>::from(handler);
let callback_id = self.register_event_callback(
let callback_id = self.register_event_handler_callback(
scope,
callback,
handler,
callback_relevant_context,
incumbent_context,
);
self.capture_event_callback_initiator(scope, callback_id);
let previous_callback_id = self
if let Some(previous) = self.set_child_window_event_handler_state(
handle,
event_type,
EventHandlerPropertyState::Callback(callback_id),
) {
self.release_event_callback(previous);
}
}
pub(crate) fn set_child_window_event_handler_content_attribute(
&mut self,
handle: DomHandle,
event_type: &(impl EventTypeKey + ?Sized),
handler: Option<UncompiledEventHandler>,
) -> Option<EventCallbackId> {
match handler {
Some(handler) => self.set_child_window_event_handler_state(
handle,
event_type,
EventHandlerPropertyState::Uncompiled(handler),
),
None => self.remove_child_window_event_handler_property(handle, event_type),
}
}
fn set_child_window_event_handler_state(
&mut self,
handle: DomHandle,
event_type: &(impl EventTypeKey + ?Sized),
state: EventHandlerPropertyState,
) -> Option<EventCallbackId> {
let local_window_id = self
.frame_owner_current_child_snapshot(handle)
.map(|owner| owner.local_window_id);
if let Some(entry) = self
.child_window_event_listeners
.get_mut(&handle)
.and_then(|target_map| target_map.get_mut(event_type))
@@ -249,15 +280,11 @@ impl PageScriptHost {
== ChildWindowEventRegistrationKind::EventHandlerProperty
})
})
.map(|entry| {
let previous_callback_id = entry.callback_id;
entry.callback_id = callback_id;
entry.local_window_id = local_window_id;
previous_callback_id
});
if let Some(previous_callback_id) = previous_callback_id {
self.release_event_callback(previous_callback_id);
return;
{
let previous = entry.callback_state.callback_id();
entry.callback_state = state;
entry.local_window_id = local_window_id;
return previous;
}
let registration_id = self.allocate_child_window_event_registration_id();
self.child_window_event_listeners
@@ -267,32 +294,99 @@ impl PageScriptHost {
.or_default()
.push(ChildWindowEventListenerEntry {
registration_id,
callback_id,
callback_state: state,
registration_kind: ChildWindowEventRegistrationKind::EventHandlerProperty,
local_window_id,
capture: false,
once: false,
});
None
}
pub(crate) fn child_window_event_handler_property_value<'s>(
&self,
&mut self,
scope: &mut v8::PinScope<'s, '_>,
handle: DomHandle,
handler_name: &str,
) -> Option<v8::Local<'s, v8::Value>> {
let event_type = child_window_event_type_from_handler_name(handler_name)?;
self.child_window_event_listeners
let entry = self
.child_window_event_listeners
.get(&handle)
.and_then(|target_map| target_map.get(event_type))
.and_then(|entries| {
entries.iter().find_map(|entry| {
(entry.registration_kind
== ChildWindowEventRegistrationKind::EventHandlerProperty)
.then(|| self.event_callback_value(scope, entry.callback_id))
.flatten()
entries.iter().find(|entry| {
entry.registration_kind
== ChildWindowEventRegistrationKind::EventHandlerProperty
})
})
})?;
let state = entry.callback_state.clone();
let registration_id = entry.registration_id;
let target = self.current_child_window_event_target(handle)?;
if entry.local_window_id != Some(target.owner().local_window_id) {
return None;
}
match state {
EventHandlerPropertyState::Callback(callback_id) => {
self.event_callback_value(scope, callback_id)
}
EventHandlerPropertyState::Null => Some(v8::null(scope).into()),
EventHandlerPropertyState::Uncompiled(uncompiled) => {
let context = self
.ensure_prebootstrapped_child_default_context(scope, handle)
.ok()?;
let scope = &mut v8::ContextScope::new(scope, context);
// Compilation can report a syntax error and re-enter this getter.
// Keep the listener's position while exposing null during that report.
self.child_window_event_listeners
.get_mut(&handle)?
.get_mut(event_type)?
.iter_mut()
.find(|entry| entry.registration_id == registration_id)?
.callback_state = EventHandlerPropertyState::Null;
let host_ptr = self as *mut PageScriptHost;
let handler = compile_body_window_event_attribute(
scope,
host_ptr,
crate::native_bridge::OwnerDispatchScope::Child(handle),
&uncompiled,
event_type,
);
if !self.child_window_event_target_is_current(target) {
return Some(v8::null(scope).into());
}
// An error listener can replace, remove or reactivate this handler.
// Do not overwrite the replacement after returning from the report.
let unchanged = self
.child_window_event_listeners
.get(&handle)
.and_then(|map| map.get(event_type))
.is_some_and(|entries| {
entries.iter().any(|entry| {
entry.registration_id == registration_id
&& matches!(entry.callback_state, EventHandlerPropertyState::Null)
})
});
if unchanged && let Some(handler) = handler {
let callback_id = self.register_event_handler_callback(
scope,
handler.into(),
context,
context,
);
let _ = self.set_child_window_event_handler_state(
handle,
event_type,
EventHandlerPropertyState::Callback(callback_id),
);
}
Some(
handler
.map(Into::into)
.unwrap_or_else(|| v8::null(scope).into()),
)
}
}
}
fn remove_child_window_event_handler_property(
@@ -307,7 +401,7 @@ impl PageScriptHost {
.find(|entry| {
entry.registration_kind == ChildWindowEventRegistrationKind::EventHandlerProperty
})
.map(|entry| entry.callback_id);
.and_then(|entry| entry.callback_state.callback_id());
entries.retain(|entry| {
entry.registration_kind != ChildWindowEventRegistrationKind::EventHandlerProperty
});
@@ -477,14 +571,6 @@ impl PageScriptHost {
event_type,
slot,
) else {
if let Some(callback_id) = self.remove_child_window_event_registration_by_id(
target.child_handle(),
event_type,
slot.registration_id,
) {
self.unregister_abort_target_listener(callback_id);
self.release_event_callback(callback_id);
}
continue;
};
if ready.once
@@ -603,32 +689,79 @@ impl PageScriptHost {
.unwrap_or_default()
}
fn prepare_child_window_event_listener_invocation(
fn child_window_event_listener_snapshot(
&self,
handle: DomHandle,
event_type: &(impl EventTypeKey + ?Sized),
slot: ChildWindowEventDispatchSlot,
) -> Option<ChildWindowEventListenerSnapshot> {
let entry = self
.child_window_event_listeners
.get(&handle)?
.get(event_type)?
.iter()
.find(|entry| entry.registration_id == slot.registration_id)?;
Some(ChildWindowEventListenerSnapshot {
callback_state: entry.callback_state.clone(),
registration_kind: entry.registration_kind,
local_window_id: entry.local_window_id,
once: entry.once,
})
}
fn retire_child_window_event_registration(
&mut self,
handle: DomHandle,
event_type: &(impl EventTypeKey + ?Sized),
slot: ChildWindowEventDispatchSlot,
) {
if let Some(callback_id) = self.remove_child_window_event_registration_by_id(
handle,
event_type,
slot.registration_id,
) {
self.unregister_abort_target_listener(callback_id);
self.release_event_callback(callback_id);
}
}
fn prepare_child_window_event_listener_invocation(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
handle: DomHandle,
event_type: &(impl EventTypeKey + ?Sized),
slot: ChildWindowEventDispatchSlot,
) -> Option<ReadyChildWindowEventListenerInvocation> {
let entry = self
.child_window_event_listeners
.get(&handle)
.and_then(|target_map| target_map.get(event_type))?
.iter()
.find(|entry| entry.registration_id == slot.registration_id)?;
let snapshot = ChildWindowEventListenerSnapshot {
callback_id: entry.callback_id,
registration_kind: entry.registration_kind,
local_window_id: entry.local_window_id,
once: entry.once,
let mut snapshot = self.child_window_event_listener_snapshot(handle, event_type, slot)?;
let Some(target) = self.current_child_window_event_target(handle) else {
self.retire_child_window_event_registration(handle, event_type, slot);
return None;
};
let target = self.current_child_window_event_target(handle)?;
if snapshot.local_window_id != Some(target.owner().local_window_id) {
self.retire_child_window_event_registration(handle, event_type, slot);
return None;
}
let callback = self.prepare_event_callback(scope, snapshot.callback_id)?;
if matches!(
snapshot.callback_state,
EventHandlerPropertyState::Uncompiled(_)
) {
let value = self.child_window_event_handler_property_value(
scope,
handle,
&format!("on{event_type}"),
)?;
if value.is_null_or_undefined() {
return None;
}
snapshot = self.child_window_event_listener_snapshot(handle, event_type, slot)?;
}
let callback_id = snapshot.callback_state.callback_id()?;
let Some(callback) = self.prepare_event_callback(scope, callback_id) else {
self.retire_child_window_event_registration(handle, event_type, slot);
return None;
};
Some(ReadyChildWindowEventListenerInvocation {
registration_id: entry.registration_id,
registration_id: slot.registration_id,
registration_kind: snapshot.registration_kind,
once: snapshot.once,
target,
@@ -692,14 +825,14 @@ impl PageScriptHost {
let position = entries
.iter()
.position(|entry| entry.registration_id == registration_id)?;
let callback_id = entries.remove(position).callback_id;
let callback_id = entries.remove(position).callback_state.callback_id();
if entries.is_empty() {
target_map.shift_remove(event_type);
}
if target_map.is_empty() {
self.child_window_event_listeners.remove(&handle);
}
Some(callback_id)
callback_id
}
pub(crate) fn remove_child_window_event_listener_by_id(
@@ -716,7 +849,7 @@ impl PageScriptHost {
.and_then(|entries| {
entries.iter().find_map(|entry| {
(entry.registration_kind == ChildWindowEventRegistrationKind::EventListener
&& entry.callback_id == callback_id
&& entry.callback_state.callback_id() == Some(callback_id)
&& entry.capture == capture)
.then_some(entry.registration_id)
})
@@ -737,7 +870,7 @@ impl PageScriptHost {
for callback_id in target_map
.into_values()
.flatten()
.map(|entry| entry.callback_id)
.filter_map(|entry| entry.callback_state.callback_id())
{
self.unregister_abort_target_listener(callback_id);
self.release_event_callback(callback_id);
@@ -750,7 +883,12 @@ impl PageScriptHost {
) {
for target_map in self.child_window_event_listeners.values_mut() {
target_map.retain(|_, entries| {
entries.retain(|entry| !retired.contains(&entry.callback_id));
entries.retain(|entry| {
entry
.callback_state
.callback_id()
.is_none_or(|id| !retired.contains(&id))
});
!entries.is_empty()
});
}
@@ -772,7 +910,8 @@ impl PageScriptHost {
.and_then(|target_map| target_map.get(event_type))
.into_iter()
.flatten()
.filter_map(|entry| self.event_callback_identities_for_test(entry.callback_id))
.filter_map(|entry| entry.callback_state.callback_id())
.filter_map(|id| self.event_callback_identities_for_test(id))
.collect()
}
}
@@ -816,50 +955,6 @@ fn apply_child_window_event_handler_return<'s>(
apply_event_handler_return_value(scope, event, returned, handler_type);
}
fn install_child_body_load_attribute_handler_if_needed<'s>(
scope: &mut v8::PinScope<'s, '_>,
host: &mut PageScriptHost,
handle: DomHandle,
) {
let Some(source) = host
.child_browsing_context_document_handle(handle)
.and_then(|document| {
host.dom_host()
.elements_by_tag_name(document, "body", false)
.into_iter()
.next()
})
.and_then(|body| host.dom_host().get_attribute(body, "onload"))
.filter(|source| !source.trim().is_empty())
else {
return;
};
let Ok(context) = host.ensure_prebootstrapped_child_default_context(scope, handle) else {
return;
};
let scope = &mut v8::ContextScope::new(scope, context);
let Some(window) = host.child_window_proxy_records.live_window(scope, handle) else {
return;
};
if let Some(current) = window.get(scope, v8str(scope, "onload").into())
&& !current.is_null_or_undefined()
{
return;
}
let host_ptr: *mut PageScriptHost = host;
let Some(handler) = compile_event_attribute_handler_for_owner(
scope,
host_ptr,
OwnerDispatchScope::Child(handle),
source.as_ref(),
EventAttributeHandlerScope::ChildWindow,
) else {
let _ = window.set(scope, v8str(scope, "onload").into(), v8::null(scope).into());
return;
};
let _ = window.set(scope, v8str(scope, "onload").into(), handler.into());
}
fn enter_child_window_event_dispatch<'s>(
scope: &mut v8::PinScope<'s, '_>,
handle: DomHandle,
@@ -884,66 +979,3 @@ fn restore_child_window_event_dispatch<'s>(
let global = scope.get_current_context().global(scope);
set_private_value(scope, global, ACTIVE_CHILD_WINDOW_HANDLE_SLOT, previous);
}
fn dispatch_child_body_storage_attribute<'s>(
scope: &mut v8::PinScope<'s, '_>,
window: v8::Local<'s, v8::Object>,
event: v8::Local<'s, v8::Object>,
) {
let Some(document) = window
.get(scope, v8str(scope, "document").into())
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
else {
return;
};
let Some(body) = document
.get(scope, v8str(scope, "body").into())
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
else {
return;
};
let Some(get_attribute) = body
.get(scope, v8str(scope, "getAttribute").into())
.and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
else {
return;
};
let Some(source_value) =
get_attribute.call(scope, body.into(), &[v8str(scope, "onstorage").into()])
else {
return;
};
if source_value.is_null_or_undefined() {
return;
}
let Some(source) = source_value.to_string(scope) else {
return;
};
let source = source.to_rust_string_lossy(scope);
if source.trim().is_empty() {
return;
}
let wrapped = format!("(function(window){{with(window){{{source}}}}})");
let Some(script_source) = v8_string(scope, &wrapped) else {
return;
};
let Some(handler) = v8::Script::compile(scope, script_source, None)
.and_then(|script| crate::script_execution::execute_compiled_script(scope, script))
.and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
else {
return;
};
let event_key = v8str(scope, "event");
let previous_event = window
.get(scope, event_key.into())
.unwrap_or_else(|| v8::undefined(scope).into());
let _ = window.set(scope, event_key.into(), event.into());
let _ = invoke_event_handler(
scope,
"child body onstorage",
handler,
body.into(),
&[window.into()],
);
let _ = window.set(scope, event_key.into(), previous_event);
}
@@ -4,6 +4,7 @@ use super::super::{
child_frames::PendingChildFrameNavigation,
};
use crate::document_runtime::DomHandle;
use moli_page_types::{NavigationHistoryMutation, cross_document_navigation_seed};
use url::Url;
impl PageScriptHost {
@@ -317,69 +318,6 @@ impl PageScriptHost {
}
}
pub(crate) fn queue_deferred_child_browsing_context_navigation_to_url(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
handle: DomHandle,
resolved_url: &str,
) -> bool {
let download_policy = self.capture_child_navigation_download_policy(scope, handle);
if !self.child_browsing_contexts.contains_key(&handle) {
return false;
}
let Some(url) = Url::parse(resolved_url).ok() else {
return false;
};
if let Some(entry) = self.child_browsing_contexts.get_mut(&handle) {
entry.apply_deferred_navigation_to_entry_seed(&url);
}
if self
.set_child_browsing_context_pending_navigation(
handle,
ChildBrowsingContextBootstrap::Url(url),
None,
false,
)
.is_none()
{
return false;
}
let queued = self.queue_child_browsing_context_navigation_commit(handle);
self.remember_child_navigation_download_policy(handle, download_policy, queued)
}
pub(crate) fn queue_deferred_child_browsing_context_navigation_request(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
handle: DomHandle,
request: ChildBrowsingContextNavigationRequest,
) -> bool {
let download_policy = self.capture_child_navigation_download_policy(scope, handle);
if !self.child_browsing_contexts.contains_key(&handle) {
return false;
}
self.reject_replaced_service_worker_child_client_navigation(
handle,
"The navigation was canceled.".to_owned(),
);
if let Some(entry) = self.child_browsing_contexts.get_mut(&handle) {
entry.apply_deferred_navigation_to_entry_seed(&request.url);
}
if self
.set_child_browsing_context_pending_navigation(
handle,
ChildBrowsingContextBootstrap::Request(request),
None,
false,
)
.is_none()
{
return false;
}
let queued = self.queue_child_browsing_context_navigation_commit(handle);
self.remember_child_navigation_download_policy(handle, download_policy, queued)
}
pub(crate) fn child_browsing_context_has_pending_cross_document_traversal(
&self,
handle: DomHandle,
@@ -957,10 +957,6 @@ impl ChildBrowsingContextEntry {
}
}
pub(super) fn apply_deferred_navigation_to_entry_seed(&mut self, url: &Url) {
self.apply_navigation_to_entry_seed(url);
}
pub(super) fn clear_navigation_activation(&mut self) {
self.navigation_entry_seed.activation = None;
}
@@ -4,11 +4,18 @@ use crate::event_type::EventTypeKey;
use moli_webidl_callback::{PreparedWebIdlCallbackInterface, WebIdlCallbackInterface};
use std::collections::{HashMap, HashSet};
#[derive(Clone, Copy, PartialEq, Eq)]
enum EventCallbackKind {
Listener,
Handler,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub(crate) struct EventCallbackId(u64);
struct EventCallbackRecord {
callback: WebIdlCallbackInterface,
kind: EventCallbackKind,
resource_initiator: Option<crate::resource_initiator::CallbackInitiator>,
relevant_identity: Option<WindowExecutionContextIdentity>,
registration_identity: Option<WindowExecutionContextIdentity>,
@@ -18,6 +25,7 @@ struct EventCallbackRecord {
pub(crate) struct PreparedEventCallback {
callback: PreparedWebIdlCallbackInterface,
kind: EventCallbackKind,
resource_initiator: Option<crate::resource_initiator::CallbackInitiator>,
relevant_identity: Option<WindowExecutionContextIdentity>,
relevant_host: *mut PageScriptHost,
@@ -295,12 +303,12 @@ impl PageScriptHost {
scope: &mut v8::PinScope<'s, '_>,
target: crate::document_runtime::EventTargetHandle,
event_type: &(impl EventTypeKey + ?Sized),
handler: Option<v8::Local<'s, v8::Function>>,
handler: Option<v8::Local<'s, v8::Object>>,
) {
let resource_initiator =
handler.map(|_| crate::resource_initiator::CallbackInitiator::capture(scope));
let relevant_context = handler
.and_then(|handler| v8::Local::<v8::Object>::from(handler).get_creation_context(scope))
.and_then(|handler| handler.get_creation_context(scope))
.unwrap_or_else(|| scope.get_current_context());
let incumbent_context = scope
.get_incumbent_context()
@@ -324,15 +332,19 @@ impl PageScriptHost {
handler: Option<v8::Local<'s, v8::Function>>,
target_context: v8::Local<'s, v8::Context>,
) {
self.set_registered_event_handler_property_with_contexts(
scope,
target,
event_type,
handler,
target_context,
target_context,
None,
);
let callback_id = handler.map(|handler| {
self.register_event_handler_callback(
scope,
handler.into(),
target_context,
target_context,
)
});
if let Some(previous) =
self.set_compiled_event_handler_property(target, event_type, callback_id)
{
self.release_event_callback(previous);
}
}
fn set_registered_event_handler_property_with_contexts<'s>(
@@ -340,13 +352,18 @@ impl PageScriptHost {
scope: &mut v8::PinScope<'s, '_>,
target: crate::document_runtime::EventTargetHandle,
event_type: &(impl EventTypeKey + ?Sized),
handler: Option<v8::Local<'s, v8::Function>>,
handler: Option<v8::Local<'s, v8::Object>>,
relevant_context: v8::Local<'s, v8::Context>,
incumbent_context: v8::Local<'s, v8::Context>,
resource_initiator: Option<crate::resource_initiator::CallbackInitiator>,
) {
let callback_id = handler.map(|handler| {
self.register_event_callback(scope, handler.into(), relevant_context, incumbent_context)
self.register_event_handler_callback(
scope,
handler,
relevant_context,
incumbent_context,
)
});
if let Some(id) = callback_id
&& let Some(record) = self.event_callbacks.records.get_mut(&id)
@@ -392,6 +409,27 @@ impl PageScriptHost {
&mut self,
scope: &mut v8::PinScope<'_, '_>,
callback: WebIdlCallbackInterface,
) -> EventCallbackId {
self.register_event_callback_with_kind(scope, callback, EventCallbackKind::Listener)
}
pub(crate) fn register_event_handler_callback<'s>(
&mut self,
scope: &mut v8::PinScope<'s, '_>,
callback: v8::Local<'s, v8::Object>,
relevant_context: v8::Local<'s, v8::Context>,
incumbent_context: v8::Local<'s, v8::Context>,
) -> EventCallbackId {
let callback =
WebIdlCallbackInterface::new(scope, callback, relevant_context, incumbent_context);
self.register_event_callback_with_kind(scope, callback, EventCallbackKind::Handler)
}
fn register_event_callback_with_kind(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
callback: WebIdlCallbackInterface,
kind: EventCallbackKind,
) -> EventCallbackId {
let relevant_context = callback.relevant_context(scope);
// A stored non-callable handler has no invocation realm. Its value
@@ -414,6 +452,7 @@ impl PageScriptHost {
id,
EventCallbackRecord {
callback,
kind,
resource_initiator: None,
relevant_identity,
registration_identity,
@@ -527,6 +566,7 @@ impl PageScriptHost {
}
Some(PreparedEventCallback {
callback: record.callback.prepare(scope),
kind: record.kind,
resource_initiator: record.resource_initiator.clone(),
relevant_identity: record.relevant_identity,
relevant_host,
@@ -296,6 +296,7 @@ impl PageScriptHost {
.frame_viewport(frame)
}
#[cfg(debug_assertions)]
pub(crate) fn style_viewport_generation(&self) -> u64 {
self.style_viewport_generation.get()
}
@@ -609,13 +610,15 @@ impl PageScriptHost {
frames.geometry,
);
} else {
self.document_layout_state.borrow_mut().publish_latest_layout(
document,
tree,
metrics,
#[cfg(feature = "devtools")]
frames.geometry,
);
self.document_layout_state
.borrow_mut()
.publish_latest_layout(
document,
tree,
metrics,
#[cfg(feature = "devtools")]
frames.geometry,
);
}
for (target, size) in sampled_viewports {
self.sample_realtime_frame_viewport(target, size);
@@ -239,7 +239,7 @@ use child_documents::{ChildDocumentParserStore, PendingChildDocumentNavigation};
use child_events::ChildWindowEventListenerEntry;
use child_frame_runtime::ChildWindowProxyRecords;
pub(crate) use child_frame_runtime::{
caller_can_access_window, cross_origin_lightweight_popup_id, is_cross_origin_location_proxy,
cross_origin_lightweight_popup_id, is_cross_origin_location_proxy,
is_cross_origin_top_window_proxy, is_cross_origin_window_proxy,
throw_cross_origin_location_security_error, throw_cross_origin_type_error,
};
@@ -14,11 +14,10 @@ use crate::{
construct_original_event, construct_original_page_transition_event,
deep_clone_shared_web_storage_store,
dispatch_simple_event_target_event_with_original_target,
finish_cross_document_navigation_for_window,
history_entry_seed_for_location_kind, initialize_simple_event_target,
install_navigation_bootstrap_entry_for_holder, install_simple_window_event_handlers,
install_storage_aliases_for_window, navigation_unload_event_active,
new_shared_web_storage_store, scoped_indexed_db_factory,
finish_cross_document_navigation_for_window, history_entry_seed_for_location_kind,
initialize_simple_event_target, install_navigation_bootstrap_entry_for_holder,
install_simple_window_event_handlers, install_storage_aliases_for_window,
navigation_unload_event_active, new_shared_web_storage_store, scoped_indexed_db_factory,
sync_window_location_history_navigation_runtime_surface,
sync_window_location_runtime_state, web_storage_area_key_for_storage_key,
},
@@ -234,7 +233,7 @@ impl PendingLightweightPopupHistory {
let mut seed = match self.entry_seed() {
Some(seed) => seed.clone(),
None => {
let Some(seed) = history_entry_seed_for_cross_document_location(
let Some(seed) = history_entry_seed_for_location_kind(
scope,
window,
final_url,
@@ -259,6 +258,12 @@ impl PendingLightweightPopupHistory {
}
}
#[derive(Clone, Copy)]
enum LightweightPopupParserStep {
Script(DomHandle),
WindowEventHandlers(DomHandle),
}
struct LightweightPopupClassicScriptContinuation {
task: LightweightPopupNavigationTaskToken,
document_handle: DomHandle,
@@ -2144,10 +2149,9 @@ impl PageScriptHost {
return false;
}
let document_owner = navigation_task.document_owner();
let history =
history_entry_seed_for_location_kind(scope, window, &target_url, kind)
.map(PendingLightweightPopupHistory::Navigation)
.unwrap_or(PendingLightweightPopupHistory::Initial);
let history = history_entry_seed_for_location_kind(scope, window, &target_url, kind)
.map(PendingLightweightPopupHistory::Navigation)
.unwrap_or(PendingLightweightPopupHistory::Initial);
if moli_url::is_about_blank(&target_url) {
let inherited_origin = self.window_access_origin_for_dispatch_scope(creator_scope);
let page_swap = history.page_swap_navigation(
@@ -4270,16 +4274,31 @@ impl PageScriptHost {
PopupDocumentLoadBodyActivity::NoPageCodeOrEventDispatch,
);
};
if !scripting_enabled {
return LightweightPopupClassicScriptAdvance::Completed(
PopupDocumentLoadBodyActivity::NoPageCodeOrEventDispatch,
);
}
let Some(document) = self.lightweight_popup_document_record(task.popup_id()) else {
return LightweightPopupClassicScriptAdvance::Completed(
PopupDocumentLoadBodyActivity::NoPageCodeOrEventDispatch,
);
};
// Register body/frameset handlers when execution reaches the element,
// after head scripts and before scripts within its subtree. Keeping
// these steps in the continuation also preserves listener order across
// a parser-blocking external script load.
let mut parser_steps = Vec::new();
let mut stack = vec![document_handle];
while let Some(handle) = stack.pop() {
let Some(node) = self.dom_host().node(handle) else {
continue;
};
if node.is_script_element() && scripting_enabled {
parser_steps.push(LightweightPopupParserStep::Script(handle));
} else if node.is_html_element_named("body") || node.is_html_element_named("frameset") {
parser_steps.push(LightweightPopupParserStep::WindowEventHandlers(handle));
}
stack.extend(self.dom_host().child_handles_reversed(handle));
if let Some(shadow_root) = self.dom_host().shadow_root_handle(handle) {
stack.push(shadow_root);
}
}
let continuation = LightweightPopupClassicScriptContinuation {
task,
document_handle,
@@ -4308,11 +4327,22 @@ impl PageScriptHost {
) -> LightweightPopupClassicScriptAdvance {
let task = continuation.task;
let popup_id = task.popup_id();
while let Some(&script) = continuation.scripts.get(continuation.next_script_index) {
continuation.next_script_index += 1;
while let Some(&step) = continuation.parser_steps.get(continuation.next_step_index) {
continuation.next_step_index += 1;
if !self.lightweight_popup_committed_navigation_task_is_current(task) {
return LightweightPopupClassicScriptAdvance::Completed(body_activity);
}
let script = match step {
LightweightPopupParserStep::Script(script) => script,
LightweightPopupParserStep::WindowEventHandlers(handle) => {
crate::native_bridge::element::initialize_parser_inserted_event_handlers(
scope,
self as *mut PageScriptHost,
handle,
);
continue;
}
};
if continuation.stream_script.is_none()
&& self
.dom_host()
@@ -6433,20 +6463,6 @@ fn set_lightweight_popup_persisted_script_global<'s>(
set_object_slot(scope, window, name, value);
}
fn clear_lightweight_popup_window_document_event_state<'s>(
scope: &mut v8::PinScope<'s, '_>,
window: v8::Local<'s, v8::Object>,
) {
let registry = new_null_prototype_object(scope);
set_private_value(
scope,
window,
SIMPLE_EVENT_TARGET_LISTENERS_SLOT,
registry.into(),
);
clear_simple_window_event_handler_values(scope, window);
}
fn lightweight_popup_effective_navigation_kind(
current_document_is_initial_empty: bool,
kind: crate::context_bootstrap::LocationNavigationKind,
@@ -1277,8 +1277,7 @@ impl PageScriptHost {
owner: OwnerDispatchScope,
kind: ContentSecurityPolicyNonUrlKind,
source: &str,
) -> Option<DocumentContentSecurityPolicyCheck<Vec<DocumentContentSecurityPolicyViolation>>>
{
) -> Option<DocumentContentSecurityPolicyCheck> {
let snapshot = self.owner_document_policy_snapshot(owner)?;
// SAFETY: PageScriptHost is owned by the ScriptVm that owns this DocumentRuntime.
Some(
@@ -1303,8 +1302,7 @@ impl PageScriptHost {
owner: OwnerDispatchScope,
source: &str,
request: ContentSecurityPolicyScriptElementRequest<'_>,
) -> Option<DocumentContentSecurityPolicyCheck<Vec<DocumentContentSecurityPolicyViolation>>>
{
) -> Option<DocumentContentSecurityPolicyCheck> {
let snapshot = self.owner_document_policy_snapshot(owner)?;
// SAFETY: PageScriptHost is owned by the ScriptVm that owns this DocumentRuntime.
Some(
@@ -1479,7 +1477,7 @@ impl PageScriptHost {
request_url,
ContentSecurityPolicyRedirectStatus::NoRedirect,
)
.map(|check| check.into_violations().1.is_none())
.map(|check| check.into_violations().1.is_empty())
.unwrap_or(true)
}
@@ -1641,7 +1639,7 @@ impl PageScriptHost {
include_call_location: bool,
) -> bool {
let (mut report_only_violation, mut enforced_violation) = check.into_violations();
if report_only_violation.is_none() && enforced_violation.is_none() {
if report_only_violation.is_empty() && enforced_violation.is_empty() {
return true;
}
if include_call_location
@@ -1657,7 +1655,7 @@ impl PageScriptHost {
violation.column_number = column_number;
}
}
let allowed = enforced_violation.is_none();
let allowed = enforced_violation.is_empty();
for violation in report_only_violation.iter().chain(&enforced_violation) {
self.queue_content_security_policy_violation_task(scope, owner, None, violation);
}
@@ -1675,6 +1673,8 @@ impl PageScriptHost {
)?
.into_violations()
.1
.into_iter()
.next()
}
pub(crate) fn allows_trusted_type_policy_name_by_csp<'s>(
@@ -6,28 +6,6 @@ use crate::{
util::get_private_value,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum WindowOperationReceiverCaptureError {
IllegalInvocation,
CrossOrigin,
}
impl WindowOperationReceiverCaptureError {
/// Ordinary operation functions report receiver errors in their own realm.
/// Cross-origin WindowProxy/Location access surfaces have a separate error path.
pub(crate) fn throw(self, scope: &mut v8::PinScope<'_, '_>) {
match self {
Self::IllegalInvocation => crate::util::throw_type_error(scope, "Illegal invocation"),
Self::CrossOrigin => crate::native_bridge::throw_dom_exception(
scope,
"SecurityError",
18,
"Blocked access to a cross-origin Window.",
),
}
}
}
/// Window receiver frozen at the start of a WebIDL operation.
///
/// Blink separates three phases in generated Window bindings:
@@ -51,27 +29,12 @@ impl WindowOperationReceiver {
receiver: v8::Local<'s, v8::Object>,
host: &PageScriptHost,
) -> Self {
Self::capture(scope, receiver, host, false).unwrap_or(Self {
let empty = Self {
binding_at_capture: None,
})
}
pub(crate) fn capture_and_authorize<'s>(
scope: &mut v8::PinScope<'s, '_>,
receiver: v8::Local<'s, v8::Object>,
host: &PageScriptHost,
) -> Result<Self, WindowOperationReceiverCaptureError> {
Self::capture(scope, receiver, host, true)
}
fn capture<'s>(
scope: &mut v8::PinScope<'s, '_>,
receiver: v8::Local<'s, v8::Object>,
host: &PageScriptHost,
check_access: bool,
) -> Result<Self, WindowOperationReceiverCaptureError> {
let receiver = moli_webapi_declare::web_api_object_target(scope, receiver)
.ok_or(WindowOperationReceiverCaptureError::IllegalInvocation)?;
};
let Some(receiver) = moli_webapi_declare::web_api_object_target(scope, receiver) else {
return empty;
};
let current_context = scope.get_current_context();
if receiver.strict_equals(current_context.global(scope).into())
&& is_window_receiver(scope, receiver)
@@ -82,15 +45,9 @@ impl WindowOperationReceiver {
// The context registry owns this exact native global, including
// its retirement. Avoid private-slot reads on a detached proxy and
// never resolve its old child marker to a replacement Window.
return Ok(Self {
binding_at_capture: None,
});
return empty;
}
let marked_scope = marked_window_dispatch_scope(scope, receiver);
if marked_scope.is_none() && !is_window_receiver(scope, receiver) {
return Err(WindowOperationReceiverCaptureError::IllegalInvocation);
}
let relevant_context = receiver.get_creation_context(scope);
let relevant_identity = relevant_context.and_then(|context| {
host.window_execution_context_identity_for_v8_context(scope, context)
@@ -111,29 +68,16 @@ impl WindowOperationReceiver {
// the brand check so required-argument conversion can happen first,
// then fail the native operation as a rejected current-realm Promise.
let Some(target_scope) = target_scope else {
return Ok(Self {
binding_at_capture: None,
});
return empty;
};
let Some(target_owner) = host.current_window_execution_context_owner(target_scope) else {
return Ok(Self {
binding_at_capture: None,
});
return empty;
};
let Some(accessing_identity) =
host.current_runtime_window_execution_context_identity(scope)
else {
return Ok(Self {
binding_at_capture: None,
});
};
if check_access
&& !host.window_execution_context_can_access_dispatch_scope(
accessing_identity,
target_scope,
)
if host
.current_runtime_window_execution_context_identity(scope)
.is_none()
{
return Err(WindowOperationReceiverCaptureError::CrossOrigin);
return empty;
}
let binding_at_capture = match target_scope {
@@ -160,7 +104,7 @@ impl WindowOperationReceiver {
}
};
Ok(Self { binding_at_capture })
Self { binding_at_capture }
}
/// Returns only the exact receiver realm captured before argument
@@ -311,7 +311,7 @@ impl PageScriptHost {
};
let opaque_origin = inherited.or_else(|| {
Some(crate::structured_clone::RuntimeMessageOpaqueOrigin::window(
self.child_default_context_bootstrap
self.window_default_context_bootstrap
.as_ref()?
.resource_owner_id,
owner,
+46 -21
View File
@@ -302,21 +302,19 @@ pub(crate) use details_dialog::{
queue_details_toggle_event_for_attribute_change, queue_parser_details_toggle_event,
queue_parser_details_toggle_events_in_subtree,
};
pub(crate) use event_handlers::compile_window_body_onmessageerror_attribute;
use event_handlers::install_global_event_handler_template_bindings as install_global_event_handler_templates_for_owner;
use event_handlers::install_node_event_handler_template_bindings;
pub(crate) use event_handlers::{
EventAttributeHandlerScope, GlobalEventHandlerOwner, ParserAddedEventHandlers, compile_event_attribute_handler_for_owner,
compile_node_content_attribute_for_dispatch, compile_window_body_event_attribute,
event_handler_content_attribute_name, event_handler_content_attribute_names, initialize_parser_inserted_body_window_event_handlers, initialize_parser_inserted_event_handlers,
invalidate_event_handler_content_attribute, is_body_window_event_handler_attribute,
is_global_event_handler_attribute, node_event_handler_getter_function,
node_event_handler_setter_function, node_event_handler_value_from_wrapper,
GlobalEventHandlerOwner, ParserAddedEventHandlers, body_or_frameset_reflects_window_event_type,
canonical_event_handler_event_type, compile_body_window_event_attribute,
compile_node_content_attribute_for_dispatch, compile_window_event_attribute_handler,
element_event_handler_content_attribute_applies, event_handler_content_attribute_name,
event_handler_content_attribute_names, initialize_parser_inserted_event_handlers,
legacy_lenient_this_event_handler, node_event_handler_getter_function,
node_event_handler_setter_function, resolve_window_event_handler_content_attribute,
};
use event_handlers::{
body_onerror_getter_function, body_onerror_setter_function, body_onload_getter_function,
body_onload_setter_function, body_onmessageerror_getter_function,
body_onmessageerror_setter_function,
HtmlBodyWindowEventHandlersDeclaration, HtmlFrameSetWindowEventHandlersDeclaration,
};
#[cfg(any(test, feature = "devtools"))]
pub(crate) use events::construct_keyboard_event;
@@ -333,8 +331,7 @@ pub(crate) use events::{TouchEventPoint, construct_touch_event_with_points};
pub(crate) use events::{
construct_activation_pointer_event, construct_drop_input_event,
construct_mouse_event_for_target, construct_mouse_event_with_detail_for_target,
construct_mouse_event_with_related_target_for_target,
construct_wheel_event_for_target,
construct_mouse_event_with_related_target_for_target, construct_wheel_event_for_target,
};
pub(crate) use events::{construct_clipboard_event, construct_focus_event};
#[cfg(any(test, feature = "devtools"))]
@@ -343,6 +340,8 @@ pub(crate) use events::{construct_drag_event_with_related_target, construct_poin
pub(crate) use focus::focus_live_element_for_inspector;
pub(crate) use focus::is_disabled_form_control;
use focus::is_focusable;
#[cfg(feature = "devtools")]
pub(crate) use focus::perform_mouse_focus_default_action;
pub(crate) use focus::{
apply_document_focus_fixup, contenteditable_editing_host, dispatch_system_focus_change,
focus_element, focus_element_preserving_selection, focus_window_document,
@@ -353,8 +352,6 @@ pub(crate) use focus::{
};
pub(super) use focus::{node_blur_callback, node_focus_callback};
#[cfg(feature = "devtools")]
pub(crate) use focus::perform_mouse_focus_default_action;
#[cfg(feature = "devtools")]
pub(crate) use forms::cache_input_files_from_selected_files;
#[cfg(feature = "devtools")]
pub(crate) use forms::perform_implicit_submission_from_control;
@@ -468,11 +465,7 @@ pub(crate) use forms::{
text_control_value, text_control_value_dom_string,
};
pub(crate) use forms::{form_control_is_effectively_disabled, input_files_for_object};
#[cfg(feature = "molio")]
pub(crate) use forms::{
is_text_control_user_editable, replace_text_control_selection_after_beforeinput,
};
pub(in crate::native_bridge) use forms::{
is_text_control_user_editable, replace_text_control_selection_with_input_event,
};
#[cfg(feature = "devtools")]
@@ -489,7 +482,6 @@ pub(super) use html_streaming::{
};
use rendered_state::{node_check_visibility_callback, node_current_css_zoom_getter_function};
use form_controls::SvgAElementRelListPrototypeDeclaration;
pub use geometry::ClientRect;
#[cfg(feature = "devtools")]
pub(crate) use geometry::observable_input_hit_test;
@@ -1755,12 +1747,12 @@ pub(crate) fn install_element_template_bindings<'s>(
"HTMLOListElement" => install!(HtmlOListElementPrototypeDeclaration),
"HTMLUListElement" => install!(HtmlUListElementPrototypeDeclaration),
"HTMLBodyElement" => install!(
HtmlBodyOrFrameSetEventHandlersPrototypeDeclaration,
HtmlBodyWindowEventHandlersDeclaration,
HtmlBodyElementLegacyPrototypeDeclaration,
),
"HTMLFrameSetElement" => {
install!(
HtmlBodyOrFrameSetEventHandlersPrototypeDeclaration,
HtmlFrameSetWindowEventHandlersDeclaration,
HtmlFrameSetElementLegacyPrototypeDeclaration,
);
}
@@ -2345,6 +2337,39 @@ fn aria_element_reference_attribute_setter_callback<'s>(
rv.set_undefined();
}
pub(in crate::native_bridge::element) fn reflected_element_attribute_handle(
runtime: &PageScriptHost,
owner: DomHandle,
attribute: &str,
) -> Option<DomHandle> {
let candidate = match runtime
.dom_host()
.explicit_element_references(owner, attribute)
{
Some(references) => references.into_iter().next()?,
None => {
let id = runtime.dom_host().get_attribute(owner, attribute)?;
aria_element_by_id_including_disconnected(runtime, owner, &id)?
}
};
if !aria_element_reference_is_in_valid_scope(runtime, owner, candidate) {
return None;
}
runtime
.dom_host()
.resolve_reference_target_chain(candidate)
.map(|_| candidate)
}
pub(in crate::native_bridge::element) fn resolved_reflected_element_attribute_handle(
runtime: &PageScriptHost,
owner: DomHandle,
attribute: &str,
) -> Option<DomHandle> {
reflected_element_attribute_handle(runtime, owner, attribute)
.and_then(|candidate| runtime.dom_host().resolve_reference_target_chain(candidate))
}
#[cfg(feature = "devtools")]
pub(crate) use geometry::read_client_rects;
@@ -1,22 +1,17 @@
use crate::{
context_bootstrap::is_window_event_handler_property,
context_bootstrap::WINDOW_EVENT_HANDLER_PROPERTIES,
document_runtime::EventTargetHandle,
native_bridge::OwnerDispatchScope,
util::{
context_host_ptr_from_global_bridge, get_private_value, node_wrapper_from_handle,
set_private_value, throw_type_error, v8_string, v8str,
},
util::{node_wrapper_from_handle, throw_type_error, v8_string, v8str},
};
use super::super::super::node::{
node_is_document, node_is_element, reference::NativeNodeReference,
};
use super::super::forms::form_associated_form_owner;
use super::super::{element_attribute, queue_text_track_load_if_needed};
use super::super::queue_text_track_load_if_needed;
use super::shared::compile_event_attribute_handler;
const EVENT_HANDLER_SLOT_PREFIX: &str = "__moliEventHandler_";
pub(crate) const GENERIC_EVENT_HANDLER_PROPERTIES: &[&str] = &[
"onclick",
"onauxclick",
@@ -147,19 +142,16 @@ const ELEMENT_SPECIFIC_EVENT_HANDLER_PROPERTIES: &[&str] = &[
pub(in crate::native_bridge::element) fn is_element_event_handler_content_attribute_name(
name: &str,
) -> bool {
GENERIC_EVENT_HANDLER_PROPERTIES.contains(&name)
|| is_window_event_handler_property(name)
|| ELEMENT_FULLSCREEN_EVENT_HANDLER_PROPERTIES.contains(&name)
|| ELEMENT_SPECIFIC_EVENT_HANDLER_PROPERTIES.contains(&name)
event_handler_content_attribute_names().any(|candidate| candidate == name)
}
pub(crate) fn event_handler_content_attribute_names() -> impl Iterator<Item = &'static str> {
GENERIC_EVENT_HANDLER_PROPERTIES
.iter()
.chain(WINDOW_EVENT_HANDLER_PROPERTIES)
.chain(ELEMENT_FULLSCREEN_EVENT_HANDLER_PROPERTIES)
.chain(ELEMENT_SPECIFIC_EVENT_HANDLER_PROPERTIES)
.copied()
.chain(crate::context_bootstrap::window_event_handler_properties())
.chain(["onmessageerror"])
}
@@ -198,7 +190,9 @@ pub(crate) fn element_event_handler_content_attribute_applies(
|| ELEMENT_FULLSCREEN_EVENT_HANDLER_PROPERTIES.contains(&name)
|| interface_specific
|| ((node.is_html_element_named("body") || node.is_html_element_named("frameset"))
&& super::is_body_window_event_handler_attribute(name))
&& name
.strip_prefix("on")
.is_some_and(super::body_or_frameset_reflects_window_event_type))
}
#[derive(Clone, Copy)]
@@ -317,7 +311,7 @@ fn set_event_handler_property_for_target<'s>(
let Some(event_type) = event_handler_event_type(&handler_name) else {
return;
};
let handler = v8::Local::<v8::Function>::try_from(value).ok();
let handler = v8::Local::<v8::Object>::try_from(value).ok();
unsafe { &mut *runtime_ptr }
.set_registered_event_handler_property(scope, target, event_type, handler);
}
@@ -439,34 +433,44 @@ pub(crate) fn node_event_handler_getter_function<'s>(
handle_invalid_event_handler_receiver(scope, &mut rv, &handler_name);
return;
}
let target = unsafe { &*runtime_ptr }.event_handler_attribute_target(handle, &handler_name);
if let Some(event_type) = event_handler_event_type(&handler_name)
&& let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)
&& let Some(current) =
unsafe { &*host_ptr }.registered_event_handler_property_value(scope, target, event_type)
&& let Some(current) = unsafe { &*runtime_ptr }.registered_event_handler_property_value(
scope,
EventTargetHandle::Node(handle),
event_type,
)
{
rv.set(current);
return;
}
if target != EventTargetHandle::Window
&& let Some(current) = node_event_handler_value_from_wrapper(scope, object, &handler_name)
if !handler_name.starts_with("on")
|| !element_event_handler_content_attribute_applies(
unsafe { &*runtime_ptr }.dom_host(),
handle,
&handler_name,
)
{
rv.set(current);
return;
}
if !handler_name.starts_with("on") {
rv.set_null();
return;
}
let Some(source) = element_attribute(unsafe { &*runtime_ptr }, handle, &handler_name) else {
let handler = event_handler_event_type(&handler_name)
.and_then(|event_type| {
unsafe { &*runtime_ptr }.uncompiled_event_handler_content_attribute(
EventTargetHandle::Node(handle),
event_type,
)
})
.or_else(|| {
crate::host::UncompiledEventHandler::from_attribute(
unsafe { &*runtime_ptr }.dom_host(),
handle,
event_handler_event_type(&handler_name)?,
)
});
let Some(handler) = handler else {
rv.set(v8::null(scope).into());
return;
};
if source.is_empty() {
rv.set(v8::null(scope).into());
return;
}
let Some((target_context, owner)) =
node_event_handler_target_context(scope, runtime_ptr, handle)
else {
@@ -485,7 +489,7 @@ pub(crate) fn node_event_handler_getter_function<'s>(
handle,
object,
&handler_name,
&source,
&handler,
)
.map(|handler| v8::Global::new(target_scope, handler));
owner.restore(target_scope, previous);
@@ -520,42 +524,6 @@ fn node_event_handler_target_context<'s>(
.map(|context| (context, owner))
}
pub(crate) fn compile_node_content_attribute_for_dispatch<'s>(
scope: &mut v8::PinScope<'s, '_>,
host_ptr: *mut crate::native_bridge::PageScriptHost,
handle: crate::document_runtime::DomHandle,
event_type: &str,
) -> Option<v8::Local<'s, v8::Function>> {
let name = event_handler_content_attribute_name(event_type)?;
if !GENERIC_EVENT_HANDLER_PROPERTIES.contains(&name.as_str()) {
return None;
}
let source_node = unsafe { &*host_ptr }
.event_handler_content_attribute_node(EventTargetHandle::Node(handle), event_type)?;
let source = element_attribute(unsafe { &*host_ptr }, source_node, &name)?;
let (context, owner) = node_event_handler_target_context(scope, host_ptr, source_node)?;
let handler = {
let target_scope = &mut v8::ContextScope::new(scope, context);
let previous = owner.enter(target_scope);
let handler = node_wrapper_from_handle(target_scope, source_node)
.and_then(|object| {
compile_node_event_attribute_handler(
target_scope,
host_ptr,
owner,
source_node,
object,
&name,
&source,
)
})
.map(|handler| v8::Global::new(target_scope, handler));
owner.restore(target_scope, previous);
handler
}?;
Some(v8::Local::new(scope, &handler))
}
fn compile_node_event_attribute_handler<'s>(
scope: &mut v8::PinScope<'s, '_>,
runtime_ptr: *mut crate::native_bridge::PageScriptHost,
@@ -563,8 +531,21 @@ fn compile_node_event_attribute_handler<'s>(
handle: crate::document_runtime::DomHandle,
object: v8::Local<'s, v8::Object>,
handler_name: &str,
source: &str,
handler: &crate::host::UncompiledEventHandler,
) -> Option<v8::Local<'s, v8::Function>> {
let target = EventTargetHandle::Node(handle);
let event_type = event_handler_event_type(handler_name)?;
let target_context = scope.get_current_context();
// A parse error reports to author code. Re-entrant getters must see null
// without removing the listener's position, and any changes made while
// reporting the error must survive this compilation attempt.
unsafe { &mut *runtime_ptr }.set_registered_content_attribute_event_handler_property(
scope,
target,
event_type,
None,
target_context,
);
let event_argument = v8_string(scope, "event")?;
let mut context_extensions = Vec::with_capacity(4);
let window = match owner {
@@ -591,23 +572,11 @@ fn compile_node_event_attribute_handler<'s>(
}
context_extensions.push(object);
let target = unsafe { &*runtime_ptr }.event_handler_attribute_target(handle, handler_name);
let target_context = scope.get_current_context();
let event_type = event_handler_event_type(handler_name)?;
// A syntax error can invoke script which reads or changes the handler.
// Set its in-progress value before compilation so a nested getter sees null.
unsafe { &mut *runtime_ptr }.set_registered_content_attribute_event_handler_property(
scope,
target,
event_type,
None,
target_context,
);
let handler = compile_event_attribute_handler(
scope,
runtime_ptr,
handle,
source,
handler,
&[event_argument],
&context_extensions,
)?;
@@ -649,27 +618,14 @@ pub(crate) fn node_event_handler_setter_function<'s>(
handle_invalid_event_handler_receiver(scope, &mut rv, &handler_name);
return;
}
let target = unsafe { &*runtime_ptr }.event_handler_attribute_target(handle, &handler_name);
if target != EventTargetHandle::Window {
let stored = if value.is_function() {
value
} else {
v8::null(scope).into()
};
let backing = moli_webapi_declare::web_api_object_target(scope, object).unwrap_or(object);
set_private_value(
scope,
backing,
&event_handler_slot_name(&handler_name),
stored,
);
}
if let Some(event_type) = event_handler_event_type(&handler_name) {
let handler = v8::Local::<v8::Function>::try_from(value).ok();
if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) {
unsafe { &mut *host_ptr }
.set_registered_event_handler_property(scope, target, event_type, handler);
}
let handler = v8::Local::<v8::Object>::try_from(value).ok();
unsafe { &mut *runtime_ptr }.set_registered_event_handler_property(
scope,
EventTargetHandle::Node(handle),
event_type,
handler,
);
}
if matches!(handler_name.as_str(), "onload" | "onerror")
&& unsafe { &*runtime_ptr }
@@ -690,38 +646,13 @@ fn event_handler_name_from_data<'s>(
.map(|name| name.to_rust_string_lossy(scope))
}
fn event_handler_slot_name(name: &str) -> String {
format!("{EVENT_HANDLER_SLOT_PREFIX}{name}")
}
/// An adopted node keeps its original wrapper and callback realm. Read its
/// native handler slot without evaluating an author-defined property getter.
pub(crate) fn node_event_handler_value_from_wrapper<'s>(
scope: &mut v8::PinScope<'s, '_>,
object: v8::Local<'s, v8::Object>,
name: &str,
) -> Option<v8::Local<'s, v8::Value>> {
let backing = moli_webapi_declare::web_api_object_target(scope, object).unwrap_or(object);
get_private_value(scope, backing, &event_handler_slot_name(name))
.filter(|value| !value.is_undefined())
}
pub(crate) fn is_global_event_handler_attribute(name: &str) -> bool {
GENERIC_EVENT_HANDLER_PROPERTIES.contains(&name)
}
fn event_handler_event_type(name: &str) -> Option<&str> {
name.strip_prefix("on")
.filter(|event_type| !event_type.is_empty())
.map(|event_type| match event_type {
"begin" => "beginEvent",
"end" => "endEvent",
"repeat" => "repeatEvent",
event_type => event_type,
})
.map(canonical_event_handler_event_type)
}
fn legacy_lenient_this_event_handler(name: &str) -> bool {
pub(crate) fn legacy_lenient_this_event_handler(name: &str) -> bool {
matches!(name, "onmouseenter" | "onmouseleave" | "onreadystatechange")
}
@@ -737,47 +668,69 @@ fn handle_invalid_event_handler_receiver<'s>(
}
}
pub(super) fn invalidate_event_attribute_handler(
scope: &mut v8::PinScope<'_, '_>,
runtime: &mut super::super::super::PageScriptHost,
handle: crate::document_runtime::DomHandle,
name: &str,
) {
let normalized_name = name.to_ascii_lowercase();
let Some(event_type) = event_handler_event_type(&normalized_name) else {
return;
};
let target = runtime.event_handler_attribute_target(handle, &normalized_name);
if let Some(callback) = runtime.clear_event_handler_property(target, event_type) {
runtime.release_event_callback(callback);
pub(crate) fn canonical_event_handler_event_type(event_type: &str) -> &str {
match event_type {
"begin" => "beginEvent",
"end" => "endEvent",
"repeat" => "repeatEvent",
"webkitanimationend" => "webkitAnimationEnd",
"webkitanimationiteration" => "webkitAnimationIteration",
"webkitanimationstart" => "webkitAnimationStart",
"webkittransitionend" => "webkitTransitionEnd",
event_type => event_type,
}
if target == EventTargetHandle::Window {
return;
}
crate::util::with_cached_node_wrapper_realm(scope, runtime, handle, |scope, wrapper| {
let object = crate::util::get_private_object(
scope,
wrapper,
crate::dom_parser::DOM_PARSER_FOREIGN_NODE_SLOT,
)
.unwrap_or(wrapper);
let backing = moli_webapi_declare::web_api_object_target(scope, object).unwrap_or(object);
set_private_value(
scope,
backing,
&event_handler_slot_name(&normalized_name),
v8::undefined(scope).into(),
);
});
}
pub(crate) fn event_handler_content_attribute_name(event_type: &str) -> Option<String> {
let event_type = match event_type {
// The SVG handlers observe the *Event types, not events named after
// their attributes. Do not invoke onbegin for dispatchEvent("begin").
"begin" | "end" | "repeat" => return None,
"beginEvent" => "begin",
"endEvent" => "end",
"repeatEvent" => "repeat",
"webkitAnimationEnd" => "webkitanimationend",
"webkitAnimationIteration" => "webkitanimationiteration",
"webkitAnimationStart" => "webkitanimationstart",
"webkitTransitionEnd" => "webkittransitionend",
event_type => event_type,
};
Some(format!("on{event_type}"))
}
pub(crate) fn compile_node_content_attribute_for_dispatch<'s>(
scope: &mut v8::PinScope<'s, '_>,
host_ptr: *mut crate::native_bridge::PageScriptHost,
handle: crate::document_runtime::DomHandle,
event_type: &str,
) -> Option<v8::Local<'s, v8::Function>> {
let name = event_handler_content_attribute_name(event_type)?;
if !element_event_handler_content_attribute_applies(
unsafe { &*host_ptr }.dom_host(),
handle,
&name,
) {
return None;
}
let handler = unsafe { &*host_ptr }
.uncompiled_event_handler_content_attribute(EventTargetHandle::Node(handle), event_type)?;
let (context, dispatch_scope) = node_event_handler_target_context(scope, host_ptr, handle)?;
let handler = {
let scope = &mut v8::ContextScope::new(scope, context);
let object = node_wrapper_from_handle(scope, handle)?;
let previous = dispatch_scope.enter(scope);
let compiled = compile_node_event_attribute_handler(
scope,
host_ptr,
dispatch_scope,
handle,
object,
&name,
&handler,
)
.map(|handler| v8::Global::new(scope, handler));
dispatch_scope.restore(scope, previous);
compiled
}?;
Some(v8::Local::new(scope, &handler))
}
@@ -1,58 +1,27 @@
mod body_onload;
mod body_window;
mod generic;
mod parser;
mod shared;
pub(crate) use body_onload::compile_window_body_event_attribute;
pub(crate) use body_onload::initialize_parser_inserted_body_window_event_handlers;
pub(super) use body_onload::{
body_onerror_getter_function, body_onerror_setter_function, body_onload_getter_function,
body_onload_setter_function,
};
pub(crate) use body_window::compile_window_body_onmessageerror_attribute;
pub(super) use body_window::{
body_onmessageerror_getter_function, body_onmessageerror_setter_function,
HtmlBodyWindowEventHandlersDeclaration, HtmlFrameSetWindowEventHandlersDeclaration,
};
pub(crate) use body_window::{
body_or_frameset_reflects_window_event_type, compile_body_window_event_attribute,
compile_window_event_attribute_handler, resolve_window_event_handler_content_attribute,
};
pub(super) use generic::ELEMENT_FULLSCREEN_EVENT_HANDLER_PROPERTIES;
pub(super) use generic::install_node_event_handler_template_bindings;
pub(super) use generic::is_element_event_handler_content_attribute_name;
pub(crate) use generic::{
GlobalEventHandlerOwner, compile_node_content_attribute_for_dispatch,
element_event_handler_content_attribute_applies, event_handler_content_attribute_name, event_handler_content_attribute_names, install_global_event_handler_template_bindings,
is_global_event_handler_attribute, node_event_handler_getter_function,
node_event_handler_setter_function, node_event_handler_value_from_wrapper,
GlobalEventHandlerOwner, canonical_event_handler_event_type,
compile_node_content_attribute_for_dispatch, element_event_handler_content_attribute_applies,
event_handler_content_attribute_name, event_handler_content_attribute_names,
install_global_event_handler_template_bindings, install_node_event_handler_template_bindings,
legacy_lenient_this_event_handler, node_event_handler_getter_function,
node_event_handler_setter_function, shadow_root_event_handler_getter_function,
shadow_root_event_handler_setter_function,
};
pub(crate) use parser::{ParserAddedEventHandlers, initialize_parser_inserted_event_handlers};
pub(crate) use shared::{EventAttributeHandlerScope, compile_event_attribute_handler_for_owner};
pub(crate) fn is_body_window_event_handler_attribute(name: &str) -> bool {
matches!(
name,
"onafterprint"
| "onbeforeprint"
| "onbeforeunload"
| "onblur"
| "onerror"
| "onfocus"
| "onhashchange"
| "onlanguagechange"
| "onload"
| "onmessage"
| "onmessageerror"
| "onoffline"
| "ononline"
| "onpagehide"
| "onpageshow"
| "onpopstate"
| "onrejectionhandled"
| "onresize"
| "onscroll"
| "onstorage"
| "onunhandledrejection"
| "onunload"
)
}
fn is_body_or_frameset_element(
runtime: &super::super::PageScriptHost,
@@ -63,13 +32,12 @@ fn is_body_or_frameset_element(
})
}
pub(crate) fn invalidate_event_handler_content_attribute(
scope: &mut v8::PinScope<'_, '_>,
runtime_ptr: *mut super::super::PageScriptHost,
pub(super) fn body_or_frameset_window_owner(
runtime: &super::super::PageScriptHost,
handle: crate::document_runtime::DomHandle,
name: &str,
) {
let runtime = unsafe { &mut *runtime_ptr };
generic::invalidate_event_attribute_handler(scope, runtime, handle, name);
body_onload::invalidate_body_window_event_attribute_handler(scope, runtime, handle, name);
) -> Option<crate::native_bridge::OwnerDispatchScope> {
if !is_body_or_frameset_element(runtime, handle) {
return None;
}
runtime.owner_dispatch_scope_for_node(handle)
}
@@ -13,17 +13,21 @@ pub(crate) use self::constructors::{
};
#[cfg(any(feature = "devtools", test))]
pub(crate) use self::constructors::{TouchEventPoint, construct_touch_event_with_points};
#[cfg(any(test, feature = "devtools"))]
pub(crate) use self::constructors::{construct_drag_event_with_related_target, construct_pointer_event};
#[cfg(feature = "devtools")]
pub(crate) use self::constructors::{
construct_activation_pointer_event, construct_drop_input_event,
construct_mouse_event_for_target, construct_mouse_event_with_detail_for_target,
construct_mouse_event_with_related_target_for_target,
construct_text_input_event_for_target, construct_wheel_event_for_target,
construct_mouse_event_with_related_target_for_target, construct_text_input_event_for_target,
construct_wheel_event_for_target,
};
#[cfg(any(test, feature = "devtools"))]
pub(crate) use self::constructors::{
construct_drag_event_with_related_target, construct_pointer_event,
};
#[cfg(test)]
pub(crate) use self::constructors::{construct_mouse_event_with_detail_and_modifiers, construct_wheel_event};
pub(crate) use self::constructors::{
construct_mouse_event_with_detail_and_modifiers, construct_wheel_event,
};
pub(crate) use self::dispatch::{
NodePublicEventDispatchOutcome, dispatch_beforeinput, dispatch_public_event,
};
@@ -1,3 +1,5 @@
pub(crate) use moli_webapi::events::subclasses::construct_native_clipboard_event as construct_clipboard_event;
pub(super) use moli_webapi::events::subclasses::construct_native_input_event as construct_editing_input_event;
#[cfg(any(test, feature = "devtools"))]
use moli_webapi::events::subclasses::construct_native_keyboard_event;
pub(crate) use moli_webapi::events::subclasses::{
@@ -6,8 +8,6 @@ pub(crate) use moli_webapi::events::subclasses::{
construct_native_interest_event as construct_interest_event,
construct_native_toggle_event as construct_toggle_event,
};
pub(crate) use moli_webapi::events::subclasses::construct_native_clipboard_event as construct_clipboard_event;
pub(super) use moli_webapi::events::subclasses::construct_native_input_event as construct_editing_input_event;
use moli_webapi::events::subclasses::{
construct_native_focus_event, construct_native_submit_event,
};
@@ -17,10 +17,9 @@ mod devtools;
pub(crate) use devtools::{construct_drag_event_with_related_target, construct_pointer_event};
#[cfg(feature = "devtools")]
pub(crate) use devtools::{
construct_drop_input_event,
construct_mouse_event_for_target, construct_mouse_event_with_detail_for_target,
construct_mouse_event_with_related_target_for_target,
construct_wheel_event_for_target,
construct_drop_input_event, construct_mouse_event_for_target,
construct_mouse_event_with_detail_for_target,
construct_mouse_event_with_related_target_for_target, construct_wheel_event_for_target,
};
#[cfg(test)]
pub(crate) use devtools::{construct_mouse_event_with_detail_and_modifiers, construct_wheel_event};
@@ -54,7 +54,14 @@ pub(crate) fn observable_input_hit_test(
document: DomHandle,
point: LayoutPoint,
) -> Result<Option<DomHandle>, LayoutError> {
Ok(input_surface_hit_test(runtime, document, point, InputHitTestPolicy::INTERACTIVE, InputHitTestMode::Dom)?.target)
Ok(input_surface_hit_test(
runtime,
document,
point,
InputHitTestPolicy::INTERACTIVE,
InputHitTestMode::Dom,
)?
.target)
}
/// Hit tests within an already routed frame. The mouse press can keep that
@@ -128,7 +135,10 @@ pub(crate) fn input_surface_hit_test(
},
);
let is_document = target.is_some_and(|target| {
runtime.dom_host().node(target).is_some_and(|node| node.is_document())
runtime
.dom_host()
.node(target)
.is_some_and(|node| node.is_document())
});
return Ok(InputSurfaceHit {
target: target.filter(|_| !is_document),
@@ -159,7 +169,10 @@ pub(crate) fn observable_deep_hit_test(
point: LayoutPoint,
policy: InputHitTestPolicy,
) -> Result<Option<DomHandle>, LayoutError> {
Ok(input_surface_hit_test(runtime, document, point, policy, InputHitTestMode::Dom)?.document_or_element())
Ok(
input_surface_hit_test(runtime, document, point, policy, InputHitTestMode::Dom)?
.document_or_element(),
)
}
fn input_surface_hit_test_in_tree(
@@ -1,5 +1,7 @@
use style::properties::{LonghandId, PropertyId};
use super::style_object_computation_context;
use crate::{
css_style::{
CssStyleDeclarationItemArgs, CssStyleDeclarationPropertyArgs,
@@ -7,6 +7,7 @@ pub(in crate::native_bridge) enum TrustedAttributeSetter {
SetAttributeNs,
SetAttributeNode,
AttrValue,
SvgAnimatedStringBaseVal,
}
impl TrustedAttributeSetter {
@@ -16,6 +17,7 @@ impl TrustedAttributeSetter {
Self::SetAttributeNs => "setAttributeNS",
Self::SetAttributeNode => "setAttributeNode",
Self::AttrValue => "value",
Self::SvgAnimatedStringBaseVal => "baseVal",
}
}
@@ -27,6 +29,9 @@ impl TrustedAttributeSetter {
crate::webidl::Context::argument("Element setAttributeNode", 1)
}
Self::AttrValue => crate::webidl::Context::member("Attr", "value"),
Self::SvgAnimatedStringBaseVal => {
crate::webidl::Context::member("SVGAnimatedString", "baseVal")
}
}
}
}
@@ -466,4 +471,3 @@ pub(crate) fn prepare_trusted_script_text(
.set_script_text_internal_slot(handle, &source);
Some(source)
}
+5 -4
View File
@@ -8,9 +8,11 @@ mod collections;
mod context_host;
mod current_input;
pub(crate) use context_host::{
ChildDocumentFetch, DecodedImageContent, DocumentDomainState, InputImageRequestId, LayoutPublicationRequest, NavigationImageDocumentCompletion, NavigationImageDocumentLoad, PageScriptHost, PageScriptHostTaskCapabilities,
PendingScrollObservableEffects, PostParseAutofocusAdmission, SelectionBoundarySnapshot, ServiceWorkerWindowOwner,
SharedResourceTimingBufferRegistry, WindowAccessOrigin, WindowOriginKey, caller_can_access_window,
ChildDocumentFetch, DecodedImageContent, DocumentDomainState, InputImageRequestId,
LayoutPublicationRequest, NavigationImageDocumentCompletion, NavigationImageDocumentLoad,
PageScriptHost, PageScriptHostTaskCapabilities, PendingScrollObservableEffects,
PostParseAutofocusAdmission, SelectionBoundarySnapshot, ServiceWorkerWindowOwner,
SharedResourceTimingBufferRegistry, WindowAccessOrigin, WindowOriginKey,
};
#[cfg(feature = "devtools")]
pub(crate) use context_host::{
@@ -98,7 +100,6 @@ pub(crate) use element::{
compute_mock_intersection_client_rect, compute_mock_intersection_scrollport_client_rect,
};
pub(super) use helpers::*;
pub(crate) use node::NativeNodeReference;
pub(crate) use node::branded_node_handle;
pub(crate) use node::{
current_or_live_delegate_node_arg_handle, node_or_foreign_arg_handle_allow_detached,
+2 -2
View File
@@ -4826,7 +4826,7 @@ impl PageVm {
},
)
.into_violations();
if enforced_violation.is_some() {
if !enforced_violation.is_empty() {
return ScannedStylesheetAdmission::DeferredToParser(
ScannedStylesheetDeferral::ContentSecurityPolicy,
);
@@ -4886,7 +4886,7 @@ impl PageVm {
crate::document_runtime::DocumentSubresourceCspKind::Image,
)
.into_violations();
if enforced_violation.is_some() {
if !enforced_violation.is_empty() {
return ScannedImageAdmission::DeferredToParser(
ScannedImageDeferral::ContentSecurityPolicy,
);
@@ -108,14 +108,13 @@ async fn native_pdf_embeds_a_loaded_font_under_its_print_declaration() {
"../../../../../../moli-layout/tests/fixtures/moli-ahem.woff2"
));
for policy in [LayoutPolicy::OnDemand, LayoutPolicy::Realtime] {
let mut page = test_page_vm_with_loader_and_document_url(
let (mut page, _, _) = page_vm_with_bound_task_sources_and_owner_wake(
&loader,
Vec::new(),
Url::parse("https://cached-print-sources.test/")?,
);
page.layout_configuration.policy = policy;
page.vm_mut().set_layout_policy(policy);
let loaded = page.vm_mut().eval(&format!(r#"
page.vm_mut().eval(&format!(r#"
document.head.innerHTML = '<style>' +
'@media screen {{ @font-face {{ font-family: ScreenOnly; src: url(data:font/woff2;base64,{data}) }} }}' +
'@media print {{ @font-face {{ font-family: PrintOnly; src: url(data:font/woff2;base64,{data}) }}' +
@@ -123,9 +122,10 @@ async fn native_pdf_embeds_a_loaded_font_under_its_print_declaration() {
document.body.innerHTML = '<p style="font-size:16px">Cached text</p>';
window.screenFonts = document.fonts;
window.screenFace = [...screenFonts].find(face => face.family === 'ScreenOnly');
screenFace.load();
JSON.stringify([screenFonts.size, screenFace.status]);
void screenFace.load();
"#))?;
drain_page_work_until_no_pending_subresources(&mut page, "load the screen font before printing").await?;
let loaded = page.vm_mut().eval("JSON.stringify([screenFonts.size, screenFace.status])")?;
assert_eq!(loaded, r#"[1,"loaded"]"#);
let fonts = page.vm_mut().document_web_font_counts_for_test();
let publishes = page.vm().layout_snapshot_cache_observability_for_test().2;
@@ -1,6 +1,6 @@
use super::*;
use moli_page_types::{NavigationHistoryMutation, SessionHistoryCommit};
use crate::parser::ParserCustomElementRegistryAssociation;
use moli_page_types::{NavigationHistoryMutation, SessionHistoryCommit};
impl ScriptVm {
pub(crate) fn resync_child_browsing_contexts(&mut self) {
@@ -984,6 +984,9 @@ impl ScriptVm {
.map_or(0, |entry| entry.index),
url,
position,
moli_page_types::NavigationSourceDocument::from_initial_empty(
self._context_host.borrow().main_document_is_initial_empty(),
),
)
}));
}
@@ -33,11 +33,10 @@ use crate::dom::{
use crate::native_bridge::element::{
InputEventCoordinates, InputHitTestMode, InputHitTestPolicy, TextEditInputType,
TextInputSource, TouchEventPoint, activate_handle_after_pointer_release,
activate_handle_after_touch_release, activate_handle_via_click_with_pointer,
activate_handle_via_keyboard, cache_input_files_from_selected_files,
construct_activation_pointer_event, construct_drag_event_with_related_target,
construct_keyboard_event, construct_mouse_event_for_target,
construct_mouse_event_with_detail_for_target,
activate_handle_after_touch_release, activate_handle_via_keyboard,
cache_input_files_from_selected_files, construct_activation_pointer_event,
construct_drag_event_with_related_target, construct_keyboard_event,
construct_mouse_event_for_target, construct_mouse_event_with_detail_for_target,
construct_mouse_event_with_related_target_for_target, construct_pointer_event,
construct_simple_event, construct_touch_event_with_points, construct_wheel_event_for_target,
contenteditable_editing_host, dispatch_public_event, input_surface_hit_test,
@@ -785,9 +784,8 @@ fn dispatch_mouse_pointer_boundaries(
}
};
let previous = if restarting { None } else { previous };
let (leaving, entering) = mouse_boundary::hover_boundary_paths(
unsafe { &*runtime_ptr }, previous, Some(current),
);
let (leaving, entering) =
mouse_boundary::hover_boundary_paths(unsafe { &*runtime_ptr }, previous, Some(current));
let coordinates = previous_coordinates.unwrap_or(data.coordinates);
if let Some(previous) = previous {
dispatch(scope, "pointerout", previous, Some(current), coordinates);
@@ -1001,6 +999,37 @@ impl ScriptVm {
)
}
#[cfg(test)]
pub(crate) fn dispatch_mouse_event_at_point_with_pointer_and_modifiers(
&mut self,
x: f64,
y: f64,
event_name: &str,
button: i32,
buttons: Option<i32>,
click_count: i32,
delta_x: f64,
delta_y: f64,
pointer: RendererPointerEventProperties,
modifiers: u8,
intercept_drags: bool,
) -> Result<RendererInputDispatchOutcome> {
self.dispatch_mouse_input(
x,
y,
event_name,
button,
buttons,
click_count,
delta_x,
delta_y,
pointer,
modifiers,
intercept_drags,
MouseDispatchCompletion::FinishTurn,
)
}
pub(crate) fn dispatch_mouse_input(
&mut self,
x: f64,
@@ -1049,7 +1078,9 @@ impl ScriptVm {
intercept_drags,
);
if is_release {
self._context_host.borrow_mut().clear_mouse_button_press(prepared.button);
self._context_host
.borrow_mut()
.clear_mouse_button_press(prepared.button);
}
if full_release {
self.suppress_compat_mouse_events = false;
@@ -1407,33 +1438,31 @@ impl ScriptVm {
if event_name == "mousemove" && buttons != 1 {
self.pending_drag_gesture = None;
}
let drag_start = if event_name == "mousemove"
&& buttons == 1
&& self.active_drag_session.is_none()
{
if !self._context_host.borrow().has_mouse_button_press(0) {
self.pending_drag_gesture = None;
}
let gesture = self.pending_drag_gesture.filter(|gesture| {
let point = gesture.root_to_frame.map_point(position.layout_point());
#[cfg(target_os = "macos")]
let threshold = 3.0;
#[cfg(not(target_os = "macos"))]
let threshold = 4.0;
(f64::from(point.x).floor() - gesture.x.floor()).abs() >= threshold
|| (f64::from(point.y).floor() - gesture.y.floor()).abs() >= threshold
});
if let Some(gesture) = gesture {
// The gesture is consumed even if dragstart is canceled. A
// held button cannot start another drag until a fresh press.
self.pending_drag_gesture = None;
Some(gesture)
let drag_start =
if event_name == "mousemove" && buttons == 1 && self.active_drag_session.is_none() {
if !self._context_host.borrow().has_mouse_button_press(0) {
self.pending_drag_gesture = None;
}
let gesture = self.pending_drag_gesture.filter(|gesture| {
let point = gesture.root_to_frame.map_point(position.layout_point());
#[cfg(target_os = "macos")]
let threshold = 3.0;
#[cfg(not(target_os = "macos"))]
let threshold = 4.0;
(f64::from(point.x).floor() - gesture.x.floor()).abs() >= threshold
|| (f64::from(point.y).floor() - gesture.y.floor()).abs() >= threshold
});
if let Some(gesture) = gesture {
// The gesture is consumed even if dragstart is canceled. A
// held button cannot start another drag until a fresh press.
self.pending_drag_gesture = None;
Some(gesture)
} else {
None
}
} else {
None
}
} else {
None
};
};
if event_name == "mousedown" && button == 0 && buttons == 1 && click_count <= 1 {
let runtime = self._context_host.borrow();
@@ -1890,9 +1919,9 @@ impl ScriptVm {
&& let Some(event) = construct_activation_pointer_event(
scope,
runtime_ptr,
handle,
pointer_dispatch_handle,
"contextmenu",
coordinates_for(handle),
coordinates_for(pointer_dispatch_handle),
0,
button,
buttons,
@@ -1900,7 +1929,12 @@ impl ScriptVm {
Some(&pointer),
)
{
let _ = dispatch_public_event(scope, runtime_ptr, handle, event);
let _ = dispatch_public_event(
scope,
runtime_ptr,
pointer_dispatch_handle,
event,
);
}
if let Some(target) = unsafe { &mut *runtime_ptr }.take_mouse_click_target(
mouse_dispatch_handle.unwrap_or(pointer_dispatch_handle),
@@ -2510,7 +2544,8 @@ impl ScriptVm {
unsafe { &mut *runtime_ptr }
.notify_close_watcher_input_activation(event_target);
}
if !dispatch_public_event(scope, runtime_ptr, event_target, event).allows_default()
if !dispatch_public_event(scope, runtime_ptr, event_target, event)
.allows_default()
{
tap = None;
}
@@ -3225,7 +3260,7 @@ impl ScriptVm {
}
}
fn mouse_button_mask(button: i32) -> i32 {
pub(super) fn mouse_button_mask(button: i32) -> i32 {
match button {
0 => 1,
1 => 4,
@@ -40,8 +40,7 @@ pub(super) fn dispatch_mouse_boundary_events(
if previous == current {
return;
}
let (leaving, entering) =
hover_boundary_paths(unsafe { &*runtime_ptr }, previous, current);
let (leaving, entering) = hover_boundary_paths(unsafe { &*runtime_ptr }, previous, current);
let mut dispatch = |name, target, related, coordinates| {
let related = related_target_value(scope, related);
if let Some(event) = construct_mouse_event_with_related_target_for_target(
+1 -1
View File
@@ -275,7 +275,7 @@ impl ScriptVm {
.document_subresource_csp_check(url, DocumentSubresourceCspKind::Image)
.into_violations()
.1
.is_none()
.is_empty()
});
urls.into()
}
@@ -28,12 +28,12 @@ impl ScriptVm {
})
}
pub(super) fn prepare_main_document_event<'event>(
pub(super) fn prepare_main_document_event(
&self,
target: EventTargetHandle,
original_target: EventTargetHandle,
event_type: &'event str,
) -> Option<NativeEventDispatch<'event>> {
event_type: &str,
) -> Option<NativeEventDispatch> {
let event = self.document_runtime.prepare_native_event_dispatch(
target,
original_target,
@@ -47,7 +47,7 @@ impl ScriptVm {
.then_some(event)
}
fn dispatch_native_event_body(&mut self, event: NativeEventDispatch<'_>) -> Result<()> {
fn dispatch_native_event_body(&mut self, event: NativeEventDispatch) -> Result<()> {
self.with_main_world_document_scope(|scope, host_ptr, document| {
document
.dispatch_native_event_in_scope(scope, host_ptr, event)
@@ -123,7 +123,13 @@ impl ScriptVm {
.map_err(anyhow::Error::msg);
}
}
dispatch_script_failure_error_body(scope, host_ptr, message, filename, error_value)
dispatch_script_failure_error_body(
scope,
host_ptr,
Some(message),
filename,
error_value,
)
})
}
@@ -140,22 +146,10 @@ impl ScriptVm {
"child module exception reporting owner is no longer current"
);
self.with_frame_realm_scope(realm_id, |scope, host_ptr| {
if let Some(ScriptErrorValue::Retained(id)) = error_value {
let exception = super::native_module::retained_module_exception(scope, id)?;
let (message, source, line, column) =
crate::exception_reporting::exception_message_details(scope, exception);
let filename = if source.is_empty() { filename } else { &source };
return dispatch_window_error_event_with_details(
scope,
host_ptr,
&message,
filename,
line,
column,
Some(exception),
)
.map_err(anyhow::Error::msg);
}
let message = match error_value {
Some(ScriptErrorValue::Retained(_)) => None,
_ => Some(message),
};
dispatch_script_failure_error_body(
scope,
host_ptr,
@@ -170,31 +164,39 @@ impl ScriptVm {
fn dispatch_script_failure_error_body(
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut PageScriptHost,
message: &str,
message: Option<&str>,
filename: Option<&str>,
error_value: Option<ScriptErrorValue>,
) -> Result<()> {
// Script-owned failures are reported inside the script or its rejection
// job, after V8 has already unwound the original JavaScript frames.
let _execution_scope = crate::script_cleanup::ScriptExecutionScope::enter(scope);
let global = scope.get_current_context().global(scope);
let message_value = v8_string(scope, message)
.ok_or_else(|| anyhow!("failed to allocate reportError message"))?;
let retained = matches!(error_value, Some(ScriptErrorValue::Retained(_)));
let error_value = match error_value {
Some(ScriptErrorValue::Retained(id)) => {
super::native_module::retained_module_exception(scope, id)?
}
Some(ScriptErrorValue::Constructor(kind)) => {
window_script_failure_error_value(scope, global, Some(kind), message_value)
}
None => window_script_failure_error_value(scope, global, None, message_value),
let (error_value, retained) = if let Some(ScriptErrorValue::Retained(id)) = error_value {
(
super::native_module::retained_module_exception(scope, id)?,
true,
)
} else {
let constructor = match error_value {
Some(ScriptErrorValue::Constructor(kind)) => Some(kind),
_ => None,
};
let global = scope.get_current_context().global(scope);
let message_value = v8_string(scope, message.unwrap_or_default())
.ok_or_else(|| anyhow!("failed to allocate reportError message"))?;
(
window_script_failure_error_value(scope, global, constructor, message_value),
false,
)
};
// Retained exceptions carry V8 or loader-owned source information.
// Read that metadata, not author-visible stack or location properties, and
// do not replace a dependency's URL with the root script's fallback URL.
let location = retained.then(|| {
let (original_message, original_filename, line, column) = if retained {
let exception_message = v8::Exception::create_message(scope, error_value);
let original_message = message
.is_none()
.then(|| exception_message.get(scope).to_rust_string_lossy(scope));
let filename = exception_message
.get_script_resource_name(scope)
.and_then(|value| v8::Local::<v8::String>::try_from(value).ok())
@@ -212,8 +214,10 @@ fn dispatch_script_failure_error_body(
.checked_add(1)
.and_then(|column| u32::try_from(column).ok())
.unwrap_or(0);
(filename, line, column)
});
(original_message, filename, line, column)
} else {
(None, None, 0, 0)
};
// Location metadata belongs to the ErrorEvent. Never mutate
// the original exception (or invoke an author's setter).
if !retained
@@ -232,14 +236,13 @@ fn dispatch_script_failure_error_body(
dispatch_window_error_event_with_details(
scope,
host_ptr,
message,
location
.as_ref()
.and_then(|(filename, _, _)| filename.as_deref())
message.or(original_message.as_deref()).unwrap_or_default(),
original_filename
.as_deref()
.or(filename)
.unwrap_or(""),
location.as_ref().map_or(0, |(_, line, _)| *line),
location.as_ref().map_or(0, |(_, _, column)| *column),
.unwrap_or_default(),
line,
column,
Some(error_value),
)
.map_err(anyhow::Error::msg)
@@ -65,7 +65,8 @@ impl ScriptVm {
AsyncSubresourceFetchResult::Image { response, encoded } => {
(Some(encoded), Ok(response))
}
AsyncSubresourceFetchResult::Failure(error) => (None, Err(error)),
AsyncSubresourceFetchResult::Failure(error)
| AsyncSubresourceFetchResult::PreloadFailure(error) => (None, Err(error)),
AsyncSubresourceFetchResult::ChildDocumentResponse { .. } => {
unreachable!("body bound above")
}
@@ -211,6 +211,446 @@ fn body_and_frameset_onerror_handlers_use_window_handler_source_text() {
);
}
#[test]
fn body_and_frameset_window_event_handlers_share_owner_and_content_sources() {
let mut vm = new_parsed_test_vm(
"https://body-window-event-handler-owner.test/",
"<!doctype html><html><head></head><body></body></html>",
);
let result = vm
.eval(
r#"
(() => {
const reflectedGlobalHandlers = [
"onblur", "onerror", "onfocus", "onload", "onresize", "onscroll"
];
const windowEventHandlers = [
"onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange",
"onlanguagechange", "onmessage", "onmessageerror", "onoffline",
"ononline", "onpagehide", "onpagereveal", "onpageshow", "onpageswap",
"onpopstate", "onrejectionhandled", "onstorage",
"onunhandledrejection", "onunload"
];
const nonReflectedGlobalHandlers = [
"onbeforeinput", "onbeforematch", "oncommand", "oncontextlost",
"oncontextrestored", "oncuechange", "onformdata",
"onsecuritypolicyviolation", "onwebkitanimationend",
"onwebkitanimationiteration", "onwebkitanimationstart",
"onwebkittransitionend"
];
const handlers = [...reflectedGlobalHandlers, ...windowEventHandlers];
const body = document.createElement("body");
const frameset = document.createElement("frameset");
const idlReflection = handlers.every(name => {
const handler = () => name;
window[name] = null;
body[name] = handler;
const bodyToWindow = window[name] === handler && frameset[name] === handler;
window[name] = null;
frameset[name] = handler;
const framesetToWindow = window[name] === handler && body[name] === handler;
window[name] = null;
return bodyToWindow && framesetToWindow;
});
const contentReflection = handlers.every(name => {
window[name] = null;
body.setAttribute(name, "return 1");
const bodyHandler = window[name];
const bodyReflected =
typeof bodyHandler === "function" && body[name] === bodyHandler;
frameset.setAttribute(name, "return 2");
const framesetHandler = window[name];
const framesetReflected =
typeof framesetHandler === "function" &&
frameset[name] === framesetHandler &&
framesetHandler !== bodyHandler;
frameset.removeAttribute(name);
const removalReflected = window[name] === null && body[name] === null;
body.removeAttribute(name);
return bodyReflected && framesetReflected && removalReflected;
});
let resizeCurrentTargetIsWindow = false;
body.onresize = event => {
resizeCurrentTargetIsWindow = event.currentTarget === window;
};
window.dispatchEvent(new Event("resize"));
window.onresize = null;
const nonReflectedGlobalHandler = nonReflectedGlobalHandlers.every(name => {
const handler = () => name;
window[name] = null;
body[name] = handler;
const staysOnBody =
body[name] === handler && frameset[name] === null && window[name] === null;
body[name] = null;
window[name] = handler;
const staysOnWindow =
window[name] === handler && body[name] === null && frameset[name] === null;
window[name] = null;
return staysOnBody && staysOnWindow;
});
const prefixedEventTypes = new Map([
["onwebkitanimationend", "webkitAnimationEnd"],
["onwebkitanimationiteration", "webkitAnimationIteration"],
["onwebkitanimationstart", "webkitAnimationStart"],
["onwebkittransitionend", "webkitTransitionEnd"]
]);
globalThis.__prefixedEventAttributeRuns = 0;
const prefixedEventResults = [...prefixedEventTypes].map(([name, type]) => {
const element = document.createElement("meta");
let propertyRuns = 0;
element[name] = () => { propertyRuns++; };
const propertyEvent = new Event(type);
element.dispatchEvent(propertyEvent);
const attributeRunsBefore = globalThis.__prefixedEventAttributeRuns;
element.setAttribute(name, "globalThis.__prefixedEventAttributeRuns++");
const attributeEvent = new Event(type);
element.dispatchEvent(attributeEvent);
return [
name,
propertyEvent.type,
attributeEvent.type,
propertyRuns,
globalThis.__prefixedEventAttributeRuns - attributeRunsBefore
];
});
const prefixedEventTypeMapping = prefixedEventResults.every(result =>
result[3] === 1 && result[4] === 1
);
const windowlessDocument = new DOMParser().parseFromString("", "text/html");
const windowlessBody = windowlessDocument.createElement("body");
const windowlessFrameset = windowlessDocument.createElement("frameset");
const windowlessHandlersStayNull = handlers.every(name => {
const windowHandler = () => name;
window[name] = windowHandler;
const initiallyNull =
windowlessBody[name] === null && windowlessFrameset[name] === null;
windowlessBody[name] = () => "body";
windowlessFrameset[name] = () => "frameset";
const settersIgnored =
window[name] === windowHandler &&
windowlessBody[name] === null &&
windowlessFrameset[name] === null;
window[name] = null;
return initiallyNull && settersIgnored;
});
return JSON.stringify({
idlReflection,
contentReflection,
resizeCurrentTargetIsWindow,
nonReflectedGlobalHandler,
prefixedEventTypeMapping,
windowlessHandlersStayNull,
bodyOwnAccessors: handlers.every(name =>
Object.hasOwn(HTMLBodyElement.prototype, name)
),
framesetOwnAccessors: handlers.every(name =>
Object.hasOwn(HTMLFrameSetElement.prototype, name)
)
});
})()
"#,
)
.expect("body and frameset Window event handler owner probe should evaluate");
assert_eq!(
result,
r#"{"idlReflection":true,"contentReflection":true,"resizeCurrentTargetIsWindow":true,"nonReflectedGlobalHandler":true,"prefixedEventTypeMapping":true,"windowlessHandlersStayNull":true,"bodyOwnAccessors":true,"framesetOwnAccessors":true}"#,
);
}
#[test]
fn child_frameset_event_handler_property_reflects_on_its_window() {
let mut vm = new_parsed_test_vm(
"https://child-frameset-window-handler.test/",
"<!doctype html><iframe id='child'></iframe>",
);
let result = vm
.eval(
r#"
(() => {
const frame = document.getElementById("child");
const childWindow = frame.contentWindow;
const childDocument = frame.contentDocument;
const frameset = childDocument.createElement("frameset");
childDocument.documentElement.replaceChild(frameset, childDocument.body);
const errorCalls = [];
const errorHandler = function (...args) {
errorCalls.push([
args.length,
this === childWindow,
args[0],
args[1],
args[2],
args[3],
args[4]
]);
return true;
};
frameset.onerror = errorHandler;
const reflectedErrorHandler =
frameset.onerror === errorHandler && childWindow.onerror === errorHandler;
const error = new ErrorEvent("error", {
bubbles: true,
cancelable: true,
message: "message",
filename: "source",
lineno: 3,
colno: 4,
error: "reason"
});
frameset.dispatchEvent(error);
const ordinaryCalls = [];
const ordinaryHandler = function (...args) {
ordinaryCalls.push([args.length, this === childWindow, args[0].type]);
return true;
};
frameset.onerror = ordinaryHandler;
const reflectedOrdinaryHandler =
frameset.onerror === ordinaryHandler && childWindow.onerror === ordinaryHandler;
const ordinary = new Event("error", { bubbles: true, cancelable: true });
frameset.dispatchEvent(ordinary);
return JSON.stringify({
reflectedErrorHandler,
reflectedOrdinaryHandler,
mainWindowUntouched: window.onerror === null,
errorCalls,
errorDefaultPrevented: error.defaultPrevented,
ordinaryCalls,
ordinaryDefaultPrevented: ordinary.defaultPrevented
});
})()
"#,
)
.expect("child frameset Window event handler probe should evaluate");
assert_eq!(
result,
r#"{"reflectedErrorHandler":true,"reflectedOrdinaryHandler":true,"mainWindowUntouched":true,"errorCalls":[[5,true,"message","source",3,4,"reason"]],"errorDefaultPrevented":true,"ordinaryCalls":[[1,true,"error"]],"ordinaryDefaultPrevented":false}"#,
);
}
#[test]
fn inline_event_handlers_retain_listener_registration_order() {
let mut vm = new_parsed_test_vm(
"https://inline-event-handler-order.test/",
"<!doctype html><html><head></head><body><div id=parsed onclick=\"this.order.push('HANDLER')\"></div></body></html>",
);
let result = vm
.eval(
r#"
(() => {
const invalidForced = [];
const forced = document.createElement("div");
forced.order = invalidForced;
forced.addEventListener("click", () => invalidForced.push("ONE"));
forced.setAttribute("onclick", "window.open(");
forced.addEventListener("click", () => invalidForced.push("THREE"));
void forced.onclick;
forced.setAttribute("onclick", "this.order.push('TWO')");
forced.dispatchEvent(new Event("click"));
const invalidDispatched = [];
const dispatched = document.createElement("div");
dispatched.order = invalidDispatched;
dispatched.addEventListener("click", () => invalidDispatched.push("ONE"));
dispatched.setAttribute("onclick", "window.open(");
dispatched.addEventListener("click", () => invalidDispatched.push("THREE"));
dispatched.dispatchEvent(new Event("click"));
dispatched.setAttribute("onclick", "this.order.push('TWO')");
dispatched.dispatchEvent(new Event("click"));
const property = [];
const propertyTarget = document.createElement("div");
propertyTarget.addEventListener("click", () => property.push("ONE"));
propertyTarget.onclick = () => property.push("OLD");
propertyTarget.addEventListener("click", () => property.push("THREE"));
propertyTarget.onclick = () => property.push("TWO");
propertyTarget.dispatchEvent(new Event("click"));
const propertyReplacement = property.splice(0);
propertyTarget.onclick = null;
propertyTarget.onclick = () => property.push("RE-ADDED");
propertyTarget.dispatchEvent(new Event("click"));
const removedAttribute = [];
const attributeTarget = document.createElement("div");
attributeTarget.order = removedAttribute;
attributeTarget.addEventListener("click", () => removedAttribute.push("ONE"));
attributeTarget.setAttribute("onclick", "this.order.push('OLD')");
attributeTarget.addEventListener("click", () => removedAttribute.push("THREE"));
attributeTarget.removeAttribute("onclick");
attributeTarget.setAttribute("onclick", "this.order.push('RE-ADDED')");
attributeTarget.dispatchEvent(new Event("click"));
const capture = [];
const captureTarget = document.createElement("div");
captureTarget.onclick = () => capture.push("HANDLER");
captureTarget.addEventListener("click", event => {
capture.push("CAPTURE");
event.stopPropagation();
}, true);
captureTarget.addEventListener("click", () => capture.push("CAPTURE-2"), true);
captureTarget.addEventListener("click", () => capture.push("THREE"));
captureTarget.dispatchEvent(new Event("click"));
const parsed = [];
const parsedTarget = document.getElementById("parsed");
parsedTarget.order = parsed;
parsedTarget.addEventListener("click", () => parsed.push("LISTENER"));
parsedTarget.dispatchEvent(new Event("click"));
const bubbling = [];
const parent = document.createElement("div");
const child = parent.appendChild(document.createElement("span"));
parent.order = bubbling;
parent.addEventListener("click", () => bubbling.push("ONE"));
parent.setAttribute("onclick", "this.order.push('TWO')");
parent.addEventListener("click", () => bubbling.push("THREE"));
child.dispatchEvent(new Event("click", { bubbles: true }));
return JSON.stringify({
invalidForced,
invalidDispatched,
propertyReplacement,
propertyReadded: property,
removedAttribute,
capture,
parsed,
bubbling
});
})()
"#,
)
.expect("inline event handler ordering probe should evaluate");
assert_eq!(
result,
r#"{"invalidForced":["ONE","TWO","THREE"],"invalidDispatched":["ONE","THREE","ONE","TWO","THREE"],"propertyReplacement":["ONE","TWO","THREE"],"propertyReadded":["ONE","THREE","RE-ADDED"],"removedAttribute":["ONE","THREE","RE-ADDED"],"capture":["CAPTURE","CAPTURE-2"],"parsed":["HANDLER","LISTENER"],"bubbling":["ONE","TWO","THREE"]}"#,
);
}
#[test]
fn window_reflecting_handlers_share_listener_registration_order() {
let mut vm = new_parsed_test_vm(
"https://window-event-handler-order.test/",
"<!doctype html><html><head></head><body></body></html>",
);
let result = vm
.eval(
r#"
(() => {
globalThis.__bodyErrorOrder = [];
window.addEventListener("error", () => __bodyErrorOrder.push("ONE"));
document.body.setAttribute("onerror", "__bodyErrorOrder.push('TWO'); return true");
window.addEventListener("error", () => __bodyErrorOrder.push("THREE"));
window.dispatchEvent(new ErrorEvent("error"));
globalThis.__bodyLoadOrder = [];
window.addEventListener("load", () => __bodyLoadOrder.push("ONE"));
document.body.setAttribute("onload", "__bodyLoadOrder.push('TWO')");
window.addEventListener("load", () => __bodyLoadOrder.push("THREE"));
window.dispatchEvent(new Event("load"));
globalThis.__bodyMessageErrorOrder = [];
window.addEventListener("messageerror", () => __bodyMessageErrorOrder.push("ONE"));
document.body.setAttribute(
"onmessageerror",
"__bodyMessageErrorOrder.push('TWO')"
);
window.addEventListener("messageerror", () => __bodyMessageErrorOrder.push("THREE"));
window.dispatchEvent(new Event("messageerror"));
const rejectionOrder = [];
window.addEventListener("unhandledrejection", () => rejectionOrder.push("ONE"));
window.onunhandledrejection = () => rejectionOrder.push("TWO");
window.addEventListener("unhandledrejection", () => rejectionOrder.push("THREE"));
const promise = Promise.resolve();
window.dispatchEvent(new PromiseRejectionEvent("unhandledrejection", { promise }));
return JSON.stringify({
bodyError: __bodyErrorOrder,
bodyLoad: __bodyLoadOrder,
bodyMessageError: __bodyMessageErrorOrder,
rejection: rejectionOrder
});
})()
"#,
)
.expect("window-reflecting event handler ordering probe should evaluate");
assert_eq!(
result,
r#"{"bodyError":["ONE","TWO","THREE"],"bodyLoad":["ONE","TWO","THREE"],"bodyMessageError":["ONE","TWO","THREE"],"rejection":["ONE","TWO","THREE"]}"#,
);
}
#[test]
fn window_document_and_shadow_handlers_share_listener_registration_order() {
let mut vm = new_parsed_test_vm(
"https://event-handler-owner-order.test/",
"<!doctype html><html><head></head><body></body></html>",
);
let result = vm
.eval(
r#"
(() => {
const windowOrder = [];
window.addEventListener("message", () => windowOrder.push("ONE"));
window.onmessage = () => windowOrder.push("TWO");
window.addEventListener("message", () => windowOrder.push("THREE"));
window.dispatchEvent(new MessageEvent("message"));
const documentOrder = {};
for (const type of ["readystatechange", "visibilitychange"]) {
const order = documentOrder[type] = [];
document.addEventListener(type, () => order.push("ONE"));
document[`on${type}`] = () => order.push("TWO");
document.addEventListener(type, () => order.push("THREE"));
document.dispatchEvent(new Event(type));
}
const shadowOrder = [];
const shadow = document.createElement("div").attachShadow({ mode: "open" });
shadow.addEventListener("slotchange", () => shadowOrder.push("ONE"));
shadow.onslotchange = () => shadowOrder.push("TWO");
shadow.addEventListener("slotchange", () => shadowOrder.push("THREE"));
shadow.dispatchEvent(new Event("slotchange"));
let customExpandoCalled = false;
const customTarget = document.createElement("div");
customTarget.onmolicustom = () => { customExpandoCalled = true; };
customTarget.dispatchEvent(new Event("molicustom"));
return JSON.stringify({
window: windowOrder,
document: documentOrder,
shadow: shadowOrder,
customExpandoCalled
});
})()
"#,
)
.expect("event handler owner ordering probe should evaluate");
assert_eq!(
result,
r#"{"window":["ONE","TWO","THREE"],"document":{"readystatechange":["ONE","TWO","THREE"],"visibilitychange":["ONE","TWO","THREE"]},"shadow":["ONE","TWO","THREE"],"customExpandoCalled":false}"#,
);
}
#[test]
fn parser_inserted_frameset_window_event_handlers_reflect_on_window() {
let mut vm = new_storage_test_vm("https://parser-frameset-window-handlers.test/");
@@ -386,123 +826,3 @@ fn child_window_onerror_return_values_use_native_cancellation() {
r#"{"rows":[[true,5,"failure"],[true,1,"error"],[true,1,"error"]],"errorAllowed":false,"errorPrevented":true,"ordinaryAllowed":false,"ordinaryPrevented":true,"noncancelableAllowed":true,"noncancelablePrevented":false,"topUntouched":true}"#
);
}
#[test]
fn child_frameset_event_handler_property_reflects_on_its_window() {
let mut vm = new_parsed_test_vm(
"https://child-frameset-window-handler.test/",
"<!doctype html><iframe id='child'></iframe>",
);
let result = vm
.eval(
r#"
(() => {
const frame = document.getElementById("child");
const childWindow = frame.contentWindow;
const childDocument = frame.contentDocument;
const frameset = childDocument.createElement("frameset");
childDocument.documentElement.replaceChild(frameset, childDocument.body);
const errorCalls = [];
const errorHandler = function (...args) {
errorCalls.push([
args.length,
this === childWindow,
args[0],
args[1],
args[2],
args[3],
args[4]
]);
return true;
};
frameset.onerror = errorHandler;
const reflectedErrorHandler =
frameset.onerror === errorHandler && childWindow.onerror === errorHandler;
const error = new ErrorEvent("error", {
bubbles: true,
cancelable: true,
message: "message",
filename: "source",
lineno: 3,
colno: 4,
error: "reason"
});
frameset.dispatchEvent(error);
const ordinaryCalls = [];
const ordinaryHandler = function (...args) {
ordinaryCalls.push([args.length, this === childWindow, args[0].type]);
return true;
};
frameset.onerror = ordinaryHandler;
const reflectedOrdinaryHandler =
frameset.onerror === ordinaryHandler && childWindow.onerror === ordinaryHandler;
const ordinary = new Event("error", { bubbles: true, cancelable: true });
frameset.dispatchEvent(ordinary);
return JSON.stringify({
reflectedErrorHandler,
reflectedOrdinaryHandler,
mainWindowUntouched: window.onerror === null,
errorCalls,
errorDefaultPrevented: error.defaultPrevented,
ordinaryCalls,
ordinaryDefaultPrevented: ordinary.defaultPrevented
});
})()
"#,
)
.expect("child frameset Window event handler probe should evaluate");
assert_eq!(
result,
r#"{"reflectedErrorHandler":true,"reflectedOrdinaryHandler":true,"mainWindowUntouched":true,"errorCalls":[[5,true,"message","source",3,4,"reason"]],"errorDefaultPrevented":true,"ordinaryCalls":[[1,true,"error"]],"ordinaryDefaultPrevented":false}"#,
);
}
#[test]
fn window_document_and_shadow_handlers_share_listener_registration_order() {
let mut vm = new_parsed_test_vm(
"https://event-handler-owner-order.test/",
"<!doctype html><html><head></head><body></body></html>",
);
let result = vm
.eval(
r#"
(() => {
const windowOrder = [];
window.addEventListener("message", () => windowOrder.push("ONE"));
window.onmessage = () => windowOrder.push("TWO");
window.addEventListener("message", () => windowOrder.push("THREE"));
window.dispatchEvent(new MessageEvent("message"));
const documentOrder = {};
for (const type of ["readystatechange", "visibilitychange"]) {
const order = documentOrder[type] = [];
document.addEventListener(type, () => order.push("ONE"));
document[`on${type}`] = () => order.push("TWO");
document.addEventListener(type, () => order.push("THREE"));
document.dispatchEvent(new Event(type));
}
const shadowOrder = [];
const shadow = document.createElement("div").attachShadow({ mode: "open" });
shadow.addEventListener("slotchange", () => shadowOrder.push("ONE"));
shadow.onslotchange = () => shadowOrder.push("TWO");
shadow.addEventListener("slotchange", () => shadowOrder.push("THREE"));
shadow.dispatchEvent(new Event("slotchange"));
let customExpandoCalled = false;
const customTarget = document.createElement("div");
customTarget.onmolicustom = () => { customExpandoCalled = true; };
customTarget.dispatchEvent(new Event("molicustom"));
return JSON.stringify({
window: windowOrder,
document: documentOrder,
shadow: shadowOrder,
customExpandoCalled
});
}
@@ -1561,13 +1561,13 @@ fn stop_propagation_at_target_capture_skips_target_bubble_listeners() {
const handlerTarget = document.createElement("div");
const handlerCalls = [];
handlerTarget.addEventListener("y", () => handlerCalls.push("capture"), { capture: true });
handlerTarget.ony = event => {
handlerTarget.addEventListener("click", () => handlerCalls.push("capture"), { capture: true });
handlerTarget.onclick = event => {
handlerCalls.push("handler");
event.stopPropagation();
};
handlerTarget.addEventListener("y", () => handlerCalls.push("bubble"));
handlerTarget.dispatchEvent(new Event("y", { bubbles: true }));
handlerTarget.addEventListener("click", () => handlerCalls.push("bubble"));
handlerTarget.dispatchEvent(new Event("click", { bubbles: true }));
return `${nativeCalls.join(",")}|${handlerCalls.join(",")}`;
})()
@@ -1575,7 +1575,7 @@ fn stop_propagation_at_target_capture_skips_target_bubble_listeners() {
)
.expect("target stopPropagation dispatch probe should evaluate");
assert_eq!(result, "capture:2,capture2:2|handler,capture");
assert_eq!(result, "capture:2,capture2:2|capture,handler,bubble");
}
#[test]
@@ -1598,21 +1598,21 @@ fn bubble_stop_propagation_keeps_current_ancestor_listeners() {
document.body.appendChild(outer);
const stoppedCalls = [];
outer.onx = event => {
outer.onclick = event => {
stoppedCalls.push("handler");
event.stopPropagation();
};
outer.addEventListener("x", () => stoppedCalls.push("listener"));
document.body.addEventListener("x", () => stoppedCalls.push("body"));
inner.dispatchEvent(new Event("x", { bubbles: true }));
outer.addEventListener("click", () => stoppedCalls.push("listener"));
document.body.addEventListener("click", () => stoppedCalls.push("body"));
inner.dispatchEvent(new Event("click", { bubbles: true }));
const immediateCalls = [];
outer.ony = event => {
outer.ondblclick = event => {
immediateCalls.push("handler");
event.stopImmediatePropagation();
};
outer.addEventListener("y", () => immediateCalls.push("listener"));
inner.dispatchEvent(new Event("y", { bubbles: true }));
outer.addEventListener("dblclick", () => immediateCalls.push("listener"));
inner.dispatchEvent(new Event("dblclick", { bubbles: true }));
const sameTargetCalls = [];
inner.addEventListener("z", event => {
@@ -63,15 +63,15 @@ fn native_event_producers_bypass_author_constructors_dictionaries_and_indexed_se
let active = [
TouchEventPoint {
identifier: 11,
x: 11.0,
y: 12.0,
coordinates,
page: (11.0, 12.0),
target,
is_target_touch: true,
},
TouchEventPoint {
identifier: 12,
x: 21.0,
y: 22.0,
coordinates: element::InputEventCoordinates::from_root(21.0, 22.0),
page: (21.0, 22.0),
target: peer,
is_target_touch: false,
},
@@ -93,8 +93,24 @@ fn native_event_producers_bypass_author_constructors_dictionaries_and_indexed_se
1,
0,
),
element::construct_pointer_event(scope, "pointerdown", coordinates, 0, 1, &pointer, None, 0),
element::construct_drag_event_with_related_target(scope, "dragstart", coordinates, transfer.into(), None, 0),
element::construct_pointer_event(
scope,
"pointerdown",
coordinates,
0,
1,
&pointer,
None,
0,
),
element::construct_drag_event_with_related_target(
scope,
"dragstart",
coordinates,
transfer.into(),
None,
0,
),
element::construct_wheel_event(scope, "wheel", coordinates, 4.0, 5.0, 0, 1, 0),
element::construct_touch_event_with_points(
scope,
@@ -558,7 +574,7 @@ fn native_non_primary_releases_dispatch_pointer_activation_events_in_each_world(
twist: 31.0,
};
let buttons = if event_name == "mousedown" {
super::super::super::input_helpers::mouse_button_mask(button)
super::super::super::input_dispatch::mouse_button_mask(button)
} else {
0
};
@@ -126,14 +126,25 @@ fn detached_body_legacy_accessors_use_owner_prototype() {
}
const detachedDoc = document.implementation.createHTMLDocument("");
for (const [body, label] of [[detachedDoc.body, "detached"], [document.createElement("body"), "created"]]) {
for (const [body, label, usesWindow] of [
[detachedDoc.body, "windowless", false],
[document.createElement("body"), "created", true]
]) {
for (const name of names) {
assert(!own(body, name), `${label}.${name} should not be own before set`);
}
const handler = () => `${label}-load`;
const priorWindowHandler = () => `${label}-prior-window-load`;
window.onload = priorWindowHandler;
body.onload = handler;
assert(window.onload === handler, `${label}.onload setter syncs window.onload`);
assert(body.onload === handler, `${label}.onload getter reads window.onload`);
assert(
window.onload === (usesWindow ? handler : priorWindowHandler),
`${label}.onload setter follows owner browsing context`
);
assert(
body.onload === (usesWindow ? handler : null),
`${label}.onload getter follows owner browsing context`
);
body.text = `${label}-text`;
body.link = `${label}-link`;
body.vLink = `${label}-vlink`;
@@ -155,7 +166,7 @@ fn detached_body_legacy_accessors_use_owner_prototype() {
assert(delete body[name], `${label}.${name} delete`);
assert(!own(body, name), `${label}.${name} should stay inherited`);
}
assert(body.onload === handler, `${label}.onload after delete`);
assert(body.onload === (usesWindow ? handler : null), `${label}.onload after delete`);
assert(body.text === "", `${label}.text after delete`);
}
for (const name of ["text", "link", "vLink", "aLink"]) {
@@ -2322,16 +2322,6 @@ fn svg_animation_elements_use_native_interfaces_and_event_handlers() {
);
}
#[test]
fn svg_filter_primitives_expose_native_dom_attributes() {
let mut vm = new_parsed_test_vm("https://svg-filter-dom.test/", "<html><body></body></html>");
assert_eq!(
vm.eval(include_str!("svg_filter_primitives.js"))
.expect("SVG filter DOM fixture should evaluate"),
"true"
);
}
#[test]
fn svg_animated_integers_use_native_identity_in_windowless_and_child_documents() {
let mut vm = new_parsed_test_vm(
@@ -160,7 +160,7 @@ fn viewport_root_input_in_iframes_preserves_document_boundaries_and_coordinates(
let hit = vm
.observable_deep_hit_test_for_current_document(
moli_layout::LayoutPoint::new(x as f32, y as f32),
false,
crate::native_bridge::element::InputHitTestPolicy::INTERACTIVE,
)
.unwrap()
.expect("the child viewport still has a Document for inspection");
@@ -2270,8 +2270,8 @@ fn touch_contacts_keep_primary_identity_until_the_entire_stream_ends() {
);
assert!(vm.active_touch_points.is_empty());
let host = vm._context_host.borrow();
assert!(!host.pointer_capture_is_active(9));
assert!(!host.pointer_capture_is_active(2));
assert!(host.active_pointer_capture_target(9).is_none());
assert!(host.active_pointer_capture_target(2).is_none());
}
#[test]
@@ -4669,7 +4669,6 @@ fn xhr_response_documents_keep_distinct_source_modification_times() {
redirected: false,
redirect_chain: Vec::new(),
from_cache: false,
cache_state: Default::default(),
negotiated_http_version: None,
};
if streaming {
@@ -170,6 +170,7 @@ fn install_pending_response_for_teardown_test(
moli_fetch::ResponseHead {
final_url: document_url.join("data.json").unwrap(),
status: 200,
status_text: None,
headers: vec![("content-type".to_owned(), b"application/json".to_vec())],
request_cookie_report: None,
request_include_credentials: false,
@@ -2516,7 +2516,6 @@ mod exception_constructor_strings;
mod child_removal;
mod encrypted_media;
mod exception_constructor_strings;
mod hyperlink_null_url_protocol;
mod idb_rejected_request;
mod idb_sqlite_factory;
@@ -2725,7 +2724,6 @@ mod document_range_factory_realm;
mod dom_rect_structured_clone;
mod resize_observer_entries;
mod file_value_receivers;
mod detached_node_producer_host;
@@ -2737,7 +2735,6 @@ mod file_reader_handlers;
mod streams_sync_protocol;
mod performance_user_timing;
mod rtc_encoded_frames;
mod xml_serializer_receivers;
@@ -464,9 +464,11 @@ async fn external_script_redirect_final_url_obeys_script_src_csp() {
);
}
#[test]
fn module_csp_snapshot_checks_cached_middle_hop_and_dispatches_reports_once() {
let mut vm = new_storage_test_vm("https://app.test/page.html");
#[tokio::test]
async fn module_csp_snapshot_checks_cached_middle_hop_and_dispatches_reports_once() {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
let mut vm =
new_storage_page_task_executor_test_vm_with_loader("https://app.test/page.html", &loader);
vm.set_response_content_security_report_only_policies(&["script-src 'self'".to_owned()]);
vm.set_response_content_security_policies(&["script-src 'self'".to_owned()]);
vm.eval(
@@ -519,6 +521,7 @@ fn module_csp_snapshot_checks_cached_middle_hop_and_dispatches_reports_once() {
redirect_chain: vec![redirect(&original, &middle), redirect(&middle, &final_url)],
from_cache: true,
cache_state: moli_fetch::ResponseCacheState::Local,
preload_state: Default::default(),
negotiated_http_version: None,
},
"export default 1;".to_owned(),
@@ -532,7 +535,7 @@ fn module_csp_snapshot_checks_cached_middle_hop_and_dispatches_reports_once() {
vm.dispatch_module_fetch_csp_violations(Some(&context));
vm.dispatch_module_fetch_csp_violations(Some(&context));
assert_eq!(
drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm),
drain_content_security_policy_violation_tasks_for_test(&mut vm, &loader).await,
2
);
assert_eq!(
@@ -547,7 +550,7 @@ fn module_csp_snapshot_checks_cached_middle_hop_and_dispatches_reports_once() {
);
vm.dispatch_module_fetch_csp_violations(Some(&context));
assert_eq!(
drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm),
drain_content_security_policy_violation_tasks_for_test(&mut vm, &loader).await,
0,
"replaying a response must not report the same hop twice"
);
@@ -595,6 +598,7 @@ fn module_csp_admission_reports_once_for_service_worker_response_alias() {
redirect_chain: Vec::new(),
from_cache: false,
cache_state: moli_fetch::ResponseCacheState::None,
preload_state: Default::default(),
negotiated_http_version: None,
},
"export default 42;".to_owned(),
@@ -161,6 +161,11 @@ async fn sqlite_areas_follow_window_lifetime_without_storage_wrapper_finalizers(
vm.eval("globalThis.storagePopup = open('about:blank'); globalThis.retainedPopupStorage = storagePopup.localStorage; retainedPopupStorage.getItem('key');").unwrap();
assert_eq!(host.borrow().local_storage_area_count_for_test(), 2);
vm.eval("storagePopup.close()").unwrap();
assert_eq!(
host.borrow().local_storage_area_count_for_test(),
2,
"close() queues definite Window closure on the DOM-manipulation source"
);
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
@@ -169,18 +174,6 @@ async fn sqlite_areas_follow_window_lifetime_without_storage_wrapper_finalizers(
"popup storage is retired by the close task",
)
.await;
assert_eq!(
host.borrow().local_storage_area_count_for_test(),
2,
"close() queues definite Window closure on the DOM-manipulation source"
);
assert_eq!(
vm.eval_after_selected_page_tasks(
"String(storagePopup.closed && storagePopup.opener === null)"
)
.unwrap(),
"true"
);
assert_eq!(
host.borrow().local_storage_area_count_for_test(),
1,
-2
View File
@@ -63,8 +63,6 @@ const HOST_OBJECT_TAG_RTC_ENCODED_AUDIO_FRAME: u32 = 16;
const HOST_OBJECT_TAG_RTC_ENCODED_VIDEO_FRAME: u32 = 17;
const HOST_OBJECT_TAG_ENCODED_VIDEO_CHUNK: u32 = 13;
const HOST_OBJECT_TAG_VIDEO_FRAME: u32 = 15;
const HOST_OBJECT_TAG_RTC_ENCODED_AUDIO_FRAME: u32 = 16;
const HOST_OBJECT_TAG_RTC_ENCODED_VIDEO_FRAME: u32 = 17;
const HOST_OBJECT_TAG_RTC_CERTIFICATE: u32 = 18;
pub(crate) const HOST_OBJECT_TAG_IMAGE_DATA_GRAPH: u32 = 19;
pub(crate) const HOST_OBJECT_TAG_IMAGE_BITMAP: u32 = 20;
@@ -319,9 +319,8 @@ impl MoliStyleEngine {
{
names.push(LocalName::from(candidate));
if candidate.bytes().any(|byte| byte.is_ascii_uppercase()) {
names.push(LocalName::from(
candidate.to_ascii_lowercase().as_str(),
));
names
.push(LocalName::from(candidate.to_ascii_lowercase().as_str()));
}
}
let references_attribute = |data: &style::stylist::CascadeData| {
@@ -2280,7 +2280,7 @@ impl DocumentRuntime {
return false;
};
if !host.child_browsing_context_scripting_enabled(child)
|| connected_modulepreload_has_non_matching_media(&self.dom_host, handle)
|| self.connected_modulepreload_has_non_matching_media(handle)
{
return true;
}
@@ -2542,7 +2542,10 @@ fn preload_link_media_matches(
.unwrap_or_default();
crate::style_engine::media_list::evaluate_media_query_list(
media,
host.map(PageScriptHost::emulated_media),
host.map(|host| {
host.style_environment_for_document(document.unwrap_or_else(|| host.document_handle()))
})
.unwrap_or_default(),
viewport,
)
}
-1
View File
@@ -1,6 +1,5 @@
use super::document_runtime::DomHandle;
use super::native_bridge::PageScriptHost;
pub(crate) use moli_v8_util::apply_webidl_constructor_prototype_fallback;
pub(crate) use moli_v8_util::v8_string_from_utf16_units;
pub use moli_v8_util::{
array_contains_strict, array_push_value, call_object_method, callable_relevant_context,
@@ -4,12 +4,10 @@ use std::rc::Rc;
use url::Url;
use crate::content_security_policy::{
ContentSecurityPolicy,
ContentSecurityPolicy, ContentSecurityPolicyDisposition, ContentSecurityPolicyNonUrlKind,
ContentSecurityPolicyRedirectStatus, ContentSecurityPolicyResourceKind,
ContentSecurityPolicyUrlViolation, ContentSecurityPolicyViolationEventFields,
content_security_policy_non_url_violation_with_source,
ContentSecurityPolicyNonUrlKind,
ContentSecurityPolicyDisposition, ContentSecurityPolicyRedirectStatus,
ContentSecurityPolicyResourceKind, ContentSecurityPolicyUrlViolation,
ContentSecurityPolicyViolationEventFields,
content_security_policy_trusted_types_policy_violation_with_disposition_and_reporting_endpoints,
content_security_policy_trusted_types_sink_violation_with_disposition_and_reporting_endpoints,
content_security_policy_url_violation_for_checked_url_with_redirect_status_disposition_and_reporting_endpoints,
@@ -276,7 +276,16 @@ async fn worker_module_tree_failure_preserves_admitted_network_actions() {
"import './a.mjs'; import './b.mjs';",
)
.await;
let held = server.request("/worker/held.mjs").await;
let (held, failed) = server
.request_pair("/worker/held.mjs", "/worker/b.mjs")
.await;
ModuleSourceServer::write(
failed,
"503 Service Unavailable",
"text/plain",
"retry later",
)
.await;
handle.post_message(serialize_test_string("join"));
assert_eq!(recv_post_json(&mut handle).await, r#""joined""#);
ModuleSourceServer::write(