Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(window): check native receivers before crossing realms
ldm09f11881c1a5c
diff --git a/moli-renderer-v8/src/context_bootstrap/bar_prop.rs b/moli-renderer-v8/src/context_bootstrap/bar_prop.rsindex 0b31ddcd7..e570061ae 100644--- a/moli-renderer-v8/src/context_bootstrap/bar_prop.rs+++ b/moli-renderer-v8/src/context_bootstrap/bar_prop.rs@@ -38,7 +38,7 @@ struct BarPropPrototypeDeclaration {}#[derive(WebApiObject)]-#[webapi(plain)]+#[webapi(plain, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowBarPropsDeclaration<'s> {locationbar_data: v8::Local<'s, v8::Value>,menubar_data: v8::Local<'s, v8::Value>,@@ -48,21 +48,27 @@ struct WindowBarPropsDeclaration<'s> {toolbar_data: v8::Local<'s, v8::Value>,#[webapi(accessor_property, enumerable, getter = bar_getter, setter = bar_setter,data = self.locationbar_data, setter_data = self.locationbar_data)]+ #[webapi(receiver_access_check = "setter")]locationbar: (),#[webapi(accessor_property, enumerable, getter = bar_getter, setter = bar_setter,data = self.menubar_data, setter_data = self.menubar_data)]+ #[webapi(receiver_access_check = "setter")]menubar: (),#[webapi(accessor_property, enumerable, getter = bar_getter, setter = bar_setter,data = self.personalbar_data, setter_data = self.personalbar_data)]+ #[webapi(receiver_access_check = "setter")]personalbar: (),#[webapi(accessor_property, enumerable, getter = bar_getter, setter = bar_setter,data = self.scrollbars_data, setter_data = self.scrollbars_data)]+ #[webapi(receiver_access_check = "setter")]scrollbars: (),#[webapi(accessor_property, enumerable, getter = bar_getter, setter = bar_setter,data = self.statusbar_data, setter_data = self.statusbar_data)]+ #[webapi(receiver_access_check = "setter")]statusbar: (),#[webapi(accessor_property, enumerable, getter = bar_getter, setter = bar_setter,data = self.toolbar_data, setter_data = self.toolbar_data)]+ #[webapi(receiver_access_check = "setter")]toolbar: (),}diff --git a/moli-renderer-v8/src/context_bootstrap/location_runtime/surface.rs b/moli-renderer-v8/src/context_bootstrap/location_runtime/surface.rsindex f97a35f39..f5d2c3552 100644--- a/moli-renderer-v8/src/context_bootstrap/location_runtime/surface.rs+++ b/moli-renderer-v8/src/context_bootstrap/location_runtime/surface.rs@@ -4,7 +4,7 @@ use crate::webidl;use moli_webapi_declare::WebApiObject;#[derive(Default, WebApiObject)]-#[webapi(plain)]+#[webapi(plain, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowLocationAccessorDeclaration {#[webapi(accessor_property,@@ -17,7 +17,7 @@ struct WindowLocationAccessorDeclaration {}#[derive(Default, WebApiObject)]-#[webapi(plain)]+#[webapi(plain, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowHistoryAccessorDeclaration {#[webapi(accessor_property,@@ -28,7 +28,7 @@ struct WindowHistoryAccessorDeclaration {}#[derive(Default, WebApiObject)]-#[webapi(plain)]+#[webapi(plain, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowNavigationAccessorDeclaration {#[webapi(accessor_property,diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rsindex 792160220..ca3cc94a9 100644--- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs+++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs@@ -138,7 +138,7 @@ struct DocumentPrototypeRuntimeDeclaration {}#[derive(Default, WebApiObject)]-#[webapi(plain)]+#[webapi(plain, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowComputedStyleMethodDeclaration {#[webapi(method,@@ -150,7 +150,7 @@ struct WindowComputedStyleMethodDeclaration {}#[derive(WebApiObject)]-#[webapi(plain)]+#[webapi(plain, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowLegacySurfaceAccessorsDeclaration<'scope> {navigator_slot: v8::Local<'scope, v8::Value>,external_slot: v8::Local<'scope, v8::Value>,@@ -162,6 +162,7 @@ struct WindowLegacySurfaceAccessorsDeclaration<'scope> {data = self.navigator_slot,setter_data = callback_data_index_value(scope, window_surface_replaceable_name_index("clientInformation").unwrap()))]+ #[webapi(receiver_access_check = "setter")]client_information: (),#[webapi(accessor_property,@@ -171,11 +172,15 @@ struct WindowLegacySurfaceAccessorsDeclaration<'scope> {data = self.external_slot,setter_data = callback_data_index_value(scope, window_surface_replaceable_name_index("external").unwrap()))]+ #[webapi(receiver_access_check = "setter")]external: (),}+// SameObject getters authorize in bound_callback_data_item so an original+// getter can return its captured object after Realm retirement. Setters use+// V8's receiver check; live WindowProxy receivers always require authorization.#[derive(WebApiObject)]-#[webapi(plain)]+#[webapi(plain, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowPublicSurfaceAccessorsDeclaration<'scope> {history_slot: v8::Local<'scope, v8::Value>,navigation_slot: v8::Local<'scope, v8::Value>,@@ -198,6 +203,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> {getter = window_surface_slot_getter,data = self.history_slot)]+ #[webapi(receiver_access_check = "setter")]history: (),#[webapi(accessor_property,@@ -207,6 +213,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> {data = self.navigation_slot,setter_data = self.navigation_name)]+ #[webapi(receiver_access_check = "setter")]navigation: (),#[webapi(accessor_property,@@ -214,6 +221,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> {getter = window_surface_slot_getter,data = self.navigator_slot)]+ #[webapi(receiver_access_check = "setter")]navigator: (),#[webapi(accessor_property,@@ -223,6 +231,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> {data = self.screen_slot,setter_data = self.screen_name)]+ #[webapi(receiver_access_check = "setter")]screen: (),#[webapi(accessor_property = "speechSynthesis",@@ -230,6 +239,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> {getter = window_surface_slot_getter,data = self.speech_synthesis_slot)]+ #[webapi(receiver_access_check = "setter")]speech_synthesis: (),#[webapi(accessor_property = "customElements",@@ -237,6 +247,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> {getter = window_surface_slot_getter,data = self.custom_elements_slot)]+ #[webapi(receiver_access_check = "setter")]custom_elements: (),#[webapi(accessor_property,@@ -244,6 +255,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> {getter = window_surface_slot_getter,data = self.crypto_slot)]+ #[webapi(receiver_access_check = "setter")]crypto: (),#[webapi(accessor_property,@@ -253,6 +265,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> {data = self.performance_slot,setter_data = self.performance_name)]+ #[webapi(receiver_access_check = "setter")]performance: (),#[webapi(accessor_property = "visualViewport",@@ -262,6 +275,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> {data = self.visual_viewport_slot,setter_data = self.visual_viewport_name)]+ #[webapi(receiver_access_check = "setter")]visual_viewport: (),#[webapi(accessor_property = "localStorage",@@ -281,6 +295,7 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> {getter = window_surface_slot_getter,data = self.indexed_db_slot)]+ #[webapi(receiver_access_check = "setter")]indexed_db: (),#[webapi(accessor_property,@@ -299,32 +314,36 @@ struct WindowPublicSurfaceAccessorsDeclaration<'scope> {}#[derive(Default, WebApiObject)]-#[webapi(plain, enumerable)]+#[webapi(plain, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowLegacyAliasAccessorsDeclaration {#[webapi(accessor_property,getter = legacy_unforgeable_self_getter,setter = replaceable_self_setter)]+ #[webapi(receiver_access_check = "setter")]self_: (),#[webapi(accessor_property,getter = legacy_unforgeable_parent_getter,setter = replaceable_parent_setter)]+ #[webapi(receiver_access_check = "setter")]parent: (),#[webapi(accessor_property, dont_delete, getter = legacy_unforgeable_top_getter)]+ #[webapi(receiver_access_check = "setter")]top: (),#[webapi(accessor_property,getter = legacy_unforgeable_frames_getter,setter = replaceable_frames_setter)]+ #[webapi(receiver_access_check = "setter")]frames: (),}#[derive(WebApiObject)]-#[webapi(fragment, prototype = "Window", enumerable)]+#[webapi(fragment, prototype = "Window", enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowAdditionalReplaceableAccessorsDeclaration<'scope> {origin_name: v8::Local<'scope, v8::Value>,inner_width_name: v8::Local<'scope, v8::Value>,@@ -356,6 +375,7 @@ struct WindowAdditionalReplaceableAccessorsDeclaration<'scope> {setter = window_surface_replaceable_setter,setter_data = self.length_name)]+ #[webapi(receiver_access_check = "setter")]length: (),#[webapi(accessor_property,@@ -811,11 +831,11 @@ fn window_surface_slot_getter<'s>(return;};let receiver = callback_this_object(scope, &args);+ if let Some(value) = detached_fallback {+ rv.set(value);+ return;+ }if slot == WINDOW_INDEXED_DB_SURFACE_SLOT {- if let Some(value) = detached_fallback {- rv.set(value);- return;- }match ensure_indexed_db_runtime_state(scope).map(Into::into) {Some(value) => rv.set(value),None => rv.set_undefined(),@@ -828,9 +848,7 @@ fn window_surface_slot_getter<'s>(&& crate::native_bridge::lightweight_popup_id_from_window(scope, receiver).is_some(){rv.set(- get_private_value(scope, receiver, slot)- .or(detached_fallback)- .unwrap_or_else(|| v8::undefined(scope).into()),+ get_private_value(scope, receiver, slot).unwrap_or_else(|| v8::undefined(scope).into()),);return;}@@ -848,7 +866,7 @@ fn window_surface_slot_getter<'s>(return;}}- match hidden_slot_value_for_receiver(scope, receiver, slot).or(detached_fallback) {+ match hidden_slot_value_for_receiver(scope, receiver, slot) {Some(value) => rv.set(value),None => rv.set_undefined(),}diff --git a/moli-renderer-v8/src/context_bootstrap/web_storage/install.rs b/moli-renderer-v8/src/context_bootstrap/web_storage/install.rsindex d4ab7350e..6af2943b9 100644--- a/moli-renderer-v8/src/context_bootstrap/web_storage/install.rs+++ b/moli-renderer-v8/src/context_bootstrap/web_storage/install.rs@@ -45,7 +45,7 @@ struct StoragePrototypeMetadataDeclaration {}#[derive(Default, WebApiObject)]-#[webapi(plain, enumerable)]+#[webapi(plain, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct StorageAliasesDeclaration {#[webapi(accessor_property = "localStorage", getter = window_local_storage_getter)]local_storage: (),diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rsindex 6e21f9784..79ea3a039 100644--- a/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs+++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs@@ -42,7 +42,7 @@ pub(in crate::context_bootstrap) fn window_indexed_property_getter<'s>(};let host = unsafe { &mut *host_ptr };let window = if owner.child_window().is_none() {- host.child_browsing_context_window_proxy_for_top(scope, handle)+ host.child_browsing_context_window_proxy_for_accessing_context(scope, handle)} else {host.child_browsing_context_window_wrapper(scope, handle)};@@ -108,7 +108,7 @@ pub(in crate::context_bootstrap) fn window_indexed_property_descriptor<'s>(};let host = unsafe { &mut *host_ptr };let window = if owner.child_window().is_none() {- host.child_browsing_context_window_proxy_for_top(scope, handle)+ host.child_browsing_context_window_proxy_for_accessing_context(scope, handle)} else {host.child_browsing_context_window_wrapper(scope, handle)};diff --git a/moli-renderer-v8/src/context_bootstrap/window_events/install.rs b/moli-renderer-v8/src/context_bootstrap/window_events/install.rsindex 4c97bf8b2..f4436a41e 100644--- a/moli-renderer-v8/src/context_bootstrap/window_events/install.rs+++ b/moli-renderer-v8/src/context_bootstrap/window_events/install.rs@@ -43,7 +43,7 @@ pub(crate) fn clear_simple_window_event_handler_values<'s>(}#[derive(Default, WebApiObject)]-#[webapi(fragment, prototype = "Window")]+#[webapi(fragment, prototype = "Window", receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowGlobalEventHandlerAccessorsDeclaration {#[webapi(accessor_property,diff --git a/moli-renderer-v8/src/context_bootstrap/window_receiver.rs b/moli-renderer-v8/src/context_bootstrap/window_receiver.rsindex b619477b1..9ee5020ef 100644--- a/moli-renderer-v8/src/context_bootstrap/window_receiver.rs+++ b/moli-renderer-v8/src/context_bootstrap/window_receiver.rs@@ -79,11 +79,36 @@ pub(in crate::context_bootstrap) fn bound_callback_data_item<'s>(throw_type_error(scope, "Window getter called on incompatible receiver.");return None;}+ let current = scope.get_current_context();+ let receiver_context = args.this().get_creation_context(scope);+ let current_is_retired = context_host_ptr_from_context_slot(current)+ .map(|host| {+ let host = unsafe { &*host };+ host.window_execution_context_identity_for_access_check(current)+ .map(|identity| !host.window_execution_context_identity_is_current(identity))+ .unwrap_or_else(|| {+ current+ .get_slot::<crate::native_bridge::WindowEnvironmentSettings>()+ .is_some()+ })+ })+ .unwrap_or(true);+ let original_retired_receiver = (expected_receiver && receiver_context.is_none())+ || (live_receiver && receiver_context == Some(current) && current_is_retired);+ // The original getter can return its captured SameObject after retirement.+ // A live receiver, including a reused WindowProxy, must pass authorization+ // before any private cache read or entry into its relevant Realm.+ if !original_retired_receiver+ && !crate::native_bridge::caller_can_access_window(scope, args.this())+ {+ crate::native_bridge::throw_cross_origin_location_security_error(scope);+ return None;+ }let Some(item) = index.and_then(|index| items.get(index)).copied() else {throw_type_error(scope, &format!("Invalid callback data for {context}."));return None;};- let detached_fallback = (!live_receiver)+ let detached_fallback = (!live_receiver || original_retired_receiver).then(|| data.and_then(|data| data.get_index(scope, 2))).flatten();Some((item, detached_fallback))diff --git a/moli-renderer-v8/src/context_bootstrap/window_template.rs b/moli-renderer-v8/src/context_bootstrap/window_template.rsindex bcbbcdf6d..41f8f2c24 100644--- a/moli-renderer-v8/src/context_bootstrap/window_template.rs+++ b/moli-renderer-v8/src/context_bootstrap/window_template.rs@@ -23,7 +23,7 @@ use anyhow::{Result, anyhow};use moli_webapi_declare::WebApiFunctionTemplate;#[derive(WebApiFunctionTemplate)]-#[webapi(interface = web_api_interfaces::Window, enumerable)]+#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowEarlyTemplateMethodsDeclaration {#[webapi(method, length = 1, callback = window_host::window_set_timeout_callback)]set_timeout: (),@@ -38,6 +38,7 @@ struct WindowEarlyTemplateMethodsDeclaration {clear_interval: (),#[webapi(method, length = 1, callback = window_host::window_post_message_callback)]+ #[webapi(receiver_access_check = false)]post_message: (),#[webapi(@@ -70,12 +71,15 @@ struct WindowEarlyTemplateMethodsDeclaration {open: (),#[webapi(method, length = 0, callback = window_close_callback)]+ #[webapi(receiver_access_check = false)]close: (),#[webapi(method, length = 0, callback = window_noop_callback)]+ #[webapi(receiver_access_check = false)]focus: (),#[webapi(method, length = 0, callback = window_noop_callback)]+ #[webapi(receiver_access_check = false)]blur: (),#[webapi(method, length = 0, callback = window_const_false_callback)]@@ -83,7 +87,7 @@ struct WindowEarlyTemplateMethodsDeclaration {}#[derive(WebApiFunctionTemplate)]-#[webapi(interface = web_api_interfaces::Window, enumerable)]+#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowObsoleteTemplateMethodsDeclaration {#[webapi(method, length = 0, callback = window_obsolete_noop_callback)]capture_events: (),@@ -93,7 +97,7 @@ struct WindowObsoleteTemplateMethodsDeclaration {}#[derive(WebApiFunctionTemplate)]-#[webapi(interface = web_api_interfaces::Window, enumerable)]+#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowPostNetworkTemplateMethodsDeclaration {#[webapi(method = "createImageBitmap",@@ -159,37 +163,43 @@ struct WindowPostNetworkTemplateMethodsDeclaration {}#[derive(WebApiFunctionTemplate)]-#[webapi(interface = web_api_interfaces::Window, enumerable)]+#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowSelectionTemplateMethodsDeclaration {#[webapi(method, length = 0, callback = window_get_selection_callback)]get_selection: (),}#[derive(WebApiFunctionTemplate)]-#[webapi(interface = web_api_interfaces::Window, enumerable)]+#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowMediaTemplateMethodsDeclaration {#[webapi(method, length = 1, callback = window_match_media_callback)]match_media: (),}#[derive(WebApiFunctionTemplate)]-#[webapi(interface = web_api_interfaces::Window, enumerable)]+#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowIdentityAccessorsDeclaration {#[webapi(accessor_property, getter = window_closed_getter)]+ #[webapi(receiver_access_check = false)]closed: (),#[webapi(accessor_property, getter = window_window_getter)]+ #[webapi(receiver_access_check = false)]window: (),#[webapi(accessor_property = "self", getter = window_self_getter)]+ #[webapi(receiver_access_check = false)]self_: (),#[webapi(accessor_property, getter = window_top_getter)]+ #[webapi(receiver_access_check = false)]top: (),#[webapi(accessor_property, getter = window_parent_getter)]+ #[webapi(receiver_access_check = false)]parent: (),#[webapi(accessor_property, getter = window_frames_getter)]+ #[webapi(receiver_access_check = false)]frames: (),#[webapi(accessor_property, getter = window_frame_element_getter)]@@ -201,6 +211,7 @@ struct WindowIdentityAccessorsDeclaration {getter = window_location_getter,setter = window_location_setter)]+ #[webapi(receiver_access_check = false)]location: (),#[webapi(accessor_property, getter = window_console_getter)]@@ -236,9 +247,10 @@ struct WindowIdentityAccessorsDeclaration {}#[derive(WebApiFunctionTemplate)]-#[webapi(interface = web_api_interfaces::Window, enumerable)]+#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowPostRuntimeAccessorsDeclaration {#[webapi(accessor_property, getter = window_opener_getter, setter = window_opener_setter)]+ #[webapi(receiver_access_check = "setter")]opener: (),#[webapi(accessor_property, getter = window_inner_width_getter)]@@ -307,7 +319,7 @@ struct WindowPostRuntimeAccessorsDeclaration {}#[derive(WebApiFunctionTemplate)]-#[webapi(interface = web_api_interfaces::Window, enumerable)]+#[webapi(interface = web_api_interfaces::Window, enumerable, receiver_access_check, receiver = crate::context_bootstrap::is_window_receiver)]struct WindowStorageAccessorsDeclaration {#[webapi(accessor_property, getter = window_local_storage_getter)]local_storage: (),@@ -325,6 +337,7 @@ struct WindowStorageAccessorsDeclaration {custom_elements: (),#[webapi(accessor_property, getter = window_length_getter)]+ #[webapi(receiver_access_check = false)]length: (),}diff --git a/moli-renderer-v8/src/native_bridge/bindings.rs b/moli-renderer-v8/src/native_bridge/bindings.rsindex 4bae92947..af00e4855 100644--- a/moli-renderer-v8/src/native_bridge/bindings.rs+++ b/moli-renderer-v8/src/native_bridge/bindings.rs@@ -317,7 +317,6 @@ impl NativeBridgeBindings {// properties, especially non-configurable Window.location, before// its cross-origin accessors are installed.let global_template = v8::Local::new(scope, &self.cross_origin_window_global_template);- let parent_security_token = scope.get_current_context().get_security_token(scope);let context = v8::Context::new(scope,v8::ContextOptions {@@ -325,7 +324,8 @@ impl NativeBridgeBindings {..Default::default()},);- context.set_security_token(parent_security_token);+ // A facade has no LocalWindow identity. Its unique default token must+ // force every external access through the cross-origin handlers.let global = context.global(scope);(global, v8::Global::new(scope, context))}diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rsindex 5936c115c..5553016b4 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs@@ -8,7 +8,8 @@ mod window;pub(super) use crate::context_bootstrap::WINDOW_EVENT_HANDLER_PROPERTIES;pub(in crate::native_bridge::context_host) use window::ChildWindowProxyRecords;pub(crate) use window::{- cross_origin_lightweight_popup_id, install_child_window_proxy_access_check_handlers,- is_cross_origin_location_proxy, is_cross_origin_top_window_proxy,- throw_cross_origin_location_security_error, throw_cross_origin_type_error,+ caller_can_access_window, cross_origin_lightweight_popup_id,+ install_child_window_proxy_access_check_handlers, is_cross_origin_location_proxy,+ is_cross_origin_top_window_proxy, throw_cross_origin_location_security_error,+ throw_cross_origin_type_error,};diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rsindex ed587174f..00cc30adb 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs@@ -257,15 +257,6 @@ impl ChildWindowProxyRecords {.map(|proxy| v8::Local::new(scope, proxy))}- pub(in crate::native_bridge::context_host) fn has_cross_origin_proxy(- &self,- handle: DomHandle,- ) -> bool {- self.records- .get(&handle)- .is_some_and(|record| record.cross_origin_window_proxy.is_some())- }-pub(in crate::native_bridge::context_host) fn set_cross_origin_proxy(&mut self,scope: &mut v8::PinScope<'_, '_>,@@ -674,7 +665,7 @@ fn contexts_can_script_access<'s>(host.window_execution_context_can_access(accessing_identity, accessed_identity)}-fn caller_can_access_window<'s>(+pub(crate) fn caller_can_access_window<'s>(scope: &mut v8::PinScope<'s, '_>,window: v8::Local<'s, v8::Object>,) -> bool {@@ -1064,12 +1055,13 @@ impl JsContextHost {.live_window_exposed_to_top(handle)}- pub(crate) fn child_browsing_context_window_proxy_for_top<'s>(+ pub(crate) fn child_browsing_context_window_proxy_for_accessing_context<'s>(&mut self,scope: &mut v8::PinScope<'s, '_>,handle: DomHandle,) -> Option<v8::Local<'s, v8::Object>> {- if self.child_browsing_context_is_same_origin_with_top(handle) {+ let accessing = cross_origin_accessing_context(scope);+ if self.accessing_context_can_access_child_window(accessing, handle) {return self.child_browsing_context_window_wrapper(scope, handle);}if let Some(proxy) = self.child_window_proxy_records.live_window(scope, handle) {@@ -1106,6 +1098,8 @@ impl JsContextHost {.child_window_proxy_records.cross_origin_proxy(scope, handle){+ let context = proxy.get_creation_context(scope)?;+ let scope = &mut v8::ContextScope::new(scope, context);let top = Self::child_window_object_slot(scope, proxy, "top").unwrap_or_else(|| scope.get_current_context().global(scope));install_cross_origin_window_index_slots(scope, proxy, child_frame_count, proxy, top)?;@@ -1118,23 +1112,33 @@ impl JsContextHost {}let (proxy, facade_context) = self.bridge.bindings.instantiate_window_proxy_shell(scope);- set_null_prototype(scope, proxy);let global = scope.get_current_context().global(scope);let top = self.child_browsing_context_root_window(scope, handle, global);let parent = self.child_browsing_context_parent_window(scope, handle, top);self.child_window_proxy_records.set_browsing_context_parent_top(scope, handle, parent, top);let named_indices = self.child_browsing_context_child_frame_named_indices(handle);- install_live_cross_origin_child_window_surface(- scope,- proxy,- handle,- parent,- top,- proxy,- child_frame_count,- &named_indices,- )?;+ let context = v8::Local::new(scope, &facade_context);+ crate::util::install_context_host_pointer_slot(+ context,+ self as *mut Self,+ self.context_host_lifecycle_handle(),+ );+ context.set_slot(Rc::new(ChildWindowProxyFacadeContextHandle(handle)));+ {+ let scope = &mut v8::ContextScope::new(scope, context);+ set_null_prototype(scope, proxy);+ install_live_cross_origin_child_window_surface(+ scope,+ proxy,+ handle,+ parent,+ top,+ proxy,+ child_frame_count,+ &named_indices,+ )?;+ }self.child_window_proxy_records.set_facade_context(handle, facade_context);self.child_window_proxy_records@@ -1200,17 +1204,6 @@ impl JsContextHost {bind_materialized_child_window_indexed_db_factory(scope, wrapper, handle);return (Some(wrapper), ready_work);}- if self- .child_window_proxy_records- .has_cross_origin_proxy(handle)- && !self.child_browsing_context_is_same_origin_with_top(handle)- {- return (- self.child_window_proxy_records- .cross_origin_proxy(scope, handle),- ready_work,- );- }if !self.child_browsing_contexts.contains_key(&handle) {return (None, ready_work);}diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rsindex 3ccb6533a..2e7457b42 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs@@ -159,7 +159,8 @@ impl<'s> WindowTarget<'s> {index: u32,) -> Option<v8::Local<'s, v8::Object>> {let handle = self.children(scope).get(index as usize).copied()?;- unsafe { &mut *self.host }.child_browsing_context_window_proxy_for_top(scope, handle)+ unsafe { &mut *self.host }+ .child_browsing_context_window_proxy_for_accessing_context(scope, handle)}fn named(@@ -173,7 +174,7 @@ impl<'s> WindowTarget<'s> {self.sync_children(scope);let host = unsafe { &mut *self.host };let handle = host.child_browsing_context_named_child_handle(self.child, name)?;- host.child_browsing_context_window_proxy_for_top(scope, handle)+ host.child_browsing_context_window_proxy_for_accessing_context(scope, handle)}}@@ -484,8 +485,8 @@ pub(super) fn child_window_cross_origin_indexed_descriptor<'s>(throw_cross_origin_location_security_error(scope);return v8::Intercepted::kYes;};- if let Some(value) =- unsafe { &mut *target.host }.child_browsing_context_window_proxy_for_top(scope, handle)+ if let Some(value) = unsafe { &mut *target.host }+ .child_browsing_context_window_proxy_for_accessing_context(scope, handle){let context = cross_origin_accessing_context(scope);let scope = &mut v8::ContextScope::new(scope, context);diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rsindex 51662f75a..8c943928c 100644--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs@@ -179,7 +179,7 @@ use child_documents::{ChildDocumentParserStore, PendingChildDocumentNavigation};use child_events::ChildWindowEventListenerEntry;use child_frame_runtime::ChildWindowProxyRecords;pub(crate) use child_frame_runtime::{- cross_origin_lightweight_popup_id, is_cross_origin_location_proxy,+ caller_can_access_window, cross_origin_lightweight_popup_id, is_cross_origin_location_proxy,is_cross_origin_top_window_proxy, throw_cross_origin_location_security_error,throw_cross_origin_type_error,};diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rsindex a3bf59e72..d1827734a 100644--- a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs@@ -207,6 +207,46 @@ impl JsContextHost {.is_some_and(|(owner, child)| owner.can_access(&child))}+ pub(in crate::native_bridge::context_host) fn accessing_context_can_access_child_window(+ &self,+ context: v8::Local<'_, v8::Context>,+ handle: DomHandle,+ ) -> bool {+ let Some(host_ptr) = crate::util::context_host_ptr_from_context_slot(context) else {+ return false;+ };+ let accessing_host = unsafe { &*host_ptr };+ let Some(identity) = accessing_host+ .window_execution_context_identity_for_access_check(context)+ .filter(|identity| {+ accessing_host.window_execution_context_identity_is_current(*identity)+ })+ else {+ return false;+ };+ let target = OwnerDispatchScope::Child(handle);+ if std::ptr::eq(accessing_host, self) {+ return self.window_execution_context_can_access_dispatch_scope(identity, target);+ }+ if identity.grants_universal_access() {+ return true;+ }+ // Opaque identities are host-local; only tuple origins can be compared+ // between hosts before the target has materialized a V8 Context.+ accessing_host+ .window_access_origin(identity)+ .zip(self.child_window_access_origin(handle))+ .is_some_and(|(origin, target)| {+ matches!(+ (&origin, &target),+ (+ WindowAccessOrigin::Tuple { .. },+ WindowAccessOrigin::Tuple { .. }+ )+ ) && origin.can_access(&target)+ })+ }+pub(in crate::native_bridge::context_host) fn child_window_can_access_lightweight_popup(&self,handle: DomHandle,diff --git a/moli-renderer-v8/src/native_bridge/element/resource_elements.rs b/moli-renderer-v8/src/native_bridge/element/resource_elements.rsindex 0299d9c52..560842184 100644--- a/moli-renderer-v8/src/native_bridge/element/resource_elements.rs+++ b/moli-renderer-v8/src/native_bridge/element/resource_elements.rs@@ -1401,9 +1401,12 @@ pub(super) fn frame_owner_content_window_getter_function<'s>(}let runtime = unsafe { &mut *runtime_ptr };runtime.refresh_child_browsing_context(scope, handle);- let exposes_same_origin_wrapper =- runtime.child_browsing_context_is_same_origin_with_top(handle);- let window = runtime.child_browsing_context_window_proxy_for_top(scope, handle);+ let exposes_same_origin_wrapper = runtime.frame_owner_can_access_content_document(handle);+ let window = if exposes_same_origin_wrapper {+ runtime.child_browsing_context_window_wrapper(scope, handle)+ } else {+ runtime.child_browsing_context_window_proxy_for_accessing_context(scope, handle)+ };if window.is_some() {runtime.mark_child_browsing_context_window_wrapper_exposed_to_top(handle);}@@ -1412,7 +1415,7 @@ pub(super) fn frame_owner_content_window_getter_function<'s>(}match window {Some(window) => {- if runtime.child_browsing_context_is_same_origin_with_top(handle) {+ if exposes_same_origin_wrapper {runtime.set_cached_detached_iframe_content_window(scope, handle, window);}rv.set(window.into());diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rsindex fb533529f..9906555fb 100644--- a/moli-renderer-v8/src/native_bridge/mod.rs+++ b/moli-renderer-v8/src/native_bridge/mod.rs@@ -9,6 +9,7 @@ mod current_input;pub(crate) use context_host::{JsContextHost, JsContextHostPageTaskCapabilities, MouseReleaseFollowUp,PendingScrollObservableEffects, PostParseAutofocusAdmission, ServiceWorkerWindowOwner,+ caller_can_access_window,};pub(crate) use current_input::{CurrentInputEvent, CurrentInputEventScope, InputNavigationPolicy, navigation_policy_from_event,diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rsindex ce935b8a1..1fabdf282 100644--- a/moli-renderer-v8/src/script_vm/tests/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs@@ -2231,6 +2231,7 @@ mod websocket;mod webtransport_stream_interface_exposure;mod window_execution_context;mod window_getter_consolidation;+mod window_receiver_access;mod worklet_interfaces;mod string_timers;diff --git a/moli-renderer-v8/src/script_vm/tests/window_receiver_access.rs b/moli-renderer-v8/src/script_vm/tests/window_receiver_access.rsnew file mode 100644index 000000000..ffe788cae--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/window_receiver_access.rs@@ -0,0 +1,259 @@+use super::frame_owner_origin_access::child_context_for_element;+use super::*;++#[tokio::test(flavor = "current_thread")]+async fn borrowed_window_callbacks_check_receiver_access_before_conversion_or_realm_entry() {+ const ROOT: &str = "root.window-receiver.test";+ const CHILD: &str = "child.window-receiver.test";+ let server = StaticHttpServer::spawn_with_responder(+ 1,+ "Content-Type: text/html; charset=utf-8\r\n",+ |_, _| "<!doctype html><body><script>top.postMessage('ready', '*')</script>".to_owned(),+ )+ .await;+ let loader = static_http_loader([server.resolve_entry(ROOT), server.resolve_entry(CHILD)]);+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(+ server.url_for_host(ROOT, "/root").as_str(),+ &loader,+ );+ vm.eval(&format!(r#"+ globalThis.ready = false;+ onmessage = event => {{ if (event.data === 'ready') ready = true; }};+ const root = document.documentElement || document.appendChild(document.createElement('html'));+ const body = document.body || root.appendChild(document.createElement('body'));+ body.appendChild(Object.assign(document.createElement('iframe'), {{id: 'foreign', src: {:?}}}));+ "#, server.url_for_host(CHILD, "/child").as_str())).unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(ready)",+ "true",+ "the foreign Window must have a committed Realm",+ )+ .await;+ let child = child_context_for_element(&mut vm, "foreign");+ let result = vm.eval_in_child_default_context(child, r#"+ const probe = callback => {+ try { callback(); return 'exposed'; }+ catch (error) { return error.name; }+ };+ let conversions = 0;+ const argument = {toString() { ++conversions; return 'all'; }};+ const getters = ['navigator', 'performance', 'customElements', 'screen', 'history', 'indexedDB', 'name', 'origin', 'innerWidth', 'locationbar'];+ JSON.stringify({+ getters: getters.map(key => probe(() => Object.getOwnPropertyDescriptor(window, key).get.call(top))),+ methods: [+ probe(() => matchMedia.call(top, argument)),+ probe(() => setTimeout.call(top, argument)),+ probe(() => stop.call(top))+ ],+ setters: [+ probe(() => Object.getOwnPropertyDescriptor(window, 'name').set.call(top, argument)),+ probe(() => Object.getOwnPropertyDescriptor(window, 'performance').set.call(top, argument))+ ],+ conversions,+ forgedGetters: ['name', 'origin', 'navigator', 'performance', 'indexedDB'].map(key =>+ probe(() => Object.getOwnPropertyDescriptor(window, key).get.call({}))),+ forgedMethods: [+ probe(() => btoa.call({}, 'x')),+ probe(() => setTimeout.call({}, () => {})),+ probe(() => queueMicrotask.call({}, () => {})),+ probe(() => structuredClone.call({}, {}))+ ],+ allowed: [window.postMessage.call(top, 'allowed', '*') === undefined, top.parent === top, top.frames === top]+ })+ "#).unwrap();+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),+ serde_json::json!({+ "getters": vec!["SecurityError"; 10],+ "methods": vec!["SecurityError"; 3],+ "setters": vec!["SecurityError"; 2],+ "conversions": 0,+ "forgedGetters": vec!["TypeError"; 5],+ "forgedMethods": vec!["TypeError"; 4],+ "allowed": [true, true, true]+ })+ );+ for universal in [false, true] {+ let world = vm+ .create_isolated_world(+ if universal {+ "receiver-universal"+ } else {+ "receiver-restricted"+ },+ universal,+ )+ .unwrap();+ assert_eq!(+ vm.eval_in_isolated_context(+ world,+ r#"+ (() => {+ const target = document.getElementById('foreign').contentWindow;+ const getter = Object.getOwnPropertyDescriptor(window, 'navigator').get;+ try { getter.call(target); return 'exposed'; }+ catch (error) { return error.name; }+ })()+ "#+ )+ .unwrap(),+ if universal {+ "exposed"+ } else {+ "SecurityError"+ }+ );+ }+ assert_eq!(server.finish().await.len(), 1);+}++#[test]+fn cross_origin_facades_do_not_share_the_creators_security_token() {+ let mut vm = new_storage_test_vm("https://facade-receiver.test/");+ vm.eval(+ r#"+ const frame = document.createElement('iframe');+ frame.src = 'data:text/html,<p>foreign</p>';+ (document.body || document.documentElement || document).appendChild(frame);+ "#,+ )+ .unwrap();+ vm.drain_pending_child_frame_work_for_test();+ assert_eq!(vm.eval(r#"+ const foreign = frame.contentWindow;+ const probe = callback => { try { callback(); return 'exposed'; } catch (error) { return error.name; } };+ JSON.stringify([+ probe(() => foreign.arbitrary),+ probe(() => { foreign.arbitrary = 1; }),+ probe(() => Object.getOwnPropertyDescriptor(foreign, 'arbitrary')),+ probe(() => Object.getOwnPropertyDescriptor(window, 'document').get.call(foreign)),+ foreign.parent === window,+ foreign === frame.contentWindow+ ])+ "#).unwrap(), r#"["SecurityError","SecurityError","SecurityError","SecurityError",true,true]"#);+}++#[tokio::test(flavor = "current_thread")]+async fn nested_initial_windows_materialize_for_their_parent_and_preserve_proxy_identity() {+ const ROOT: &str = "root.initial-window.test";+ const PARENT: &str = "parent.initial-window.test";+ let server = StaticHttpServer::spawn_with_responder(+ 1,+ "Content-Type: text/html; charset=utf-8\r\n",+ |_, _| {+ r#"<!doctype html><body><iframe id="blank"></iframe>+ <iframe id="srcdoc" srcdoc="<p>inherited</p>"></iframe>+ <iframe id="opaque" sandbox srcdoc="<p>opaque</p>"></iframe>+ <script>top.postMessage('ready', '*')</script>"#+ .to_owned()+ },+ )+ .await;+ let loader = static_http_loader([server.resolve_entry(ROOT), server.resolve_entry(PARENT)]);+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(+ server.url_for_host(ROOT, "/root").as_str(),+ &loader,+ );+ vm.eval(&format!(r#"+ globalThis.ready = false;+ onmessage = event => {{ if (event.data === 'ready') ready = true; }};+ const root = document.documentElement || document.appendChild(document.createElement('html'));+ const body = document.body || root.appendChild(document.createElement('body'));+ body.appendChild(Object.assign(document.createElement('iframe'), {{id: 'parent', src: {:?}}}));+ "#, server.url_for_host(PARENT, "/parent").as_str())).unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(ready)",+ "true",+ "the parent document must commit",+ )+ .await;+ vm.eval(+ "globalThis.retainedBlank = document.getElementById('parent').contentWindow[0]; 'retained'",+ )+ .unwrap();+ let parent = child_context_for_element(&mut vm, "parent");+ assert_eq!(vm.eval_in_child_default_context(parent, r#"+ JSON.stringify(['blank', 'srcdoc'].map((id, index) => {+ const frame = document.getElementById(id);+ const child = frames[index];+ return child === frame.contentWindow && frame.contentDocument !== null && child.document === frame.contentDocument && child.parent === window && child.top === top;+ }).concat(document.getElementById('opaque').contentDocument === null))+ "#).unwrap(), "[true,true,true]");+ assert_eq!(+ vm.eval(+ r#"+ JSON.stringify([+ document.getElementById('parent').contentWindow[0] === retainedBlank,+ (() => { try { return retainedBlank.document; } catch(error) { return error.name; } })()+ ])+ "#+ )+ .unwrap(),+ r#"[true,"SecurityError"]"#+ );+ assert_eq!(server.finish().await.len(), 1);+}++#[tokio::test(flavor = "current_thread")]+async fn retained_window_callbacks_cannot_follow_a_foreign_document_after_navigation() {+ const ROOT: &str = "root.retained-callback.test";+ const FOREIGN: &str = "foreign.retained-callback.test";+ let server = StaticHttpServer::spawn_with_responder(+ 2,+ "Content-Type: text/html; charset=utf-8\r\n",+ |_, _| {+ "<!doctype html><body><script>top.postMessage(location.pathname, '*')</script>"+ .to_owned()+ },+ )+ .await;+ let loader = static_http_loader([server.resolve_entry(ROOT), server.resolve_entry(FOREIGN)]);+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(+ server.url_for_host(ROOT, "/root").as_str(),+ &loader,+ );+ vm.eval(&format!(r#"+ globalThis.loaded = new Set();+ onmessage = event => loaded.add(event.data);+ const root = document.documentElement || document.appendChild(document.createElement('html'));+ const body = document.body || root.appendChild(document.createElement('body'));+ body.appendChild(Object.assign(document.createElement('iframe'), {{id: 'target', src: {:?}}}));+ "#, server.url_for_host(ROOT, "/initial").as_str())).unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(loaded.has('/initial'))",+ "true",+ "the initial same-origin document must commit",+ )+ .await;+ vm.eval(&format!(r#"+ globalThis.retainedWindow = document.getElementById('target').contentWindow;+ globalThis.retainedGetter = Object.getOwnPropertyDescriptor(retainedWindow, 'navigator').get;+ globalThis.retainedMethod = retainedWindow.matchMedia;+ document.getElementById('target').src = {:?};+ "#, server.url_for_host(FOREIGN, "/foreign").as_str())).unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(loaded.has('/foreign'))",+ "true",+ "the foreign document must replace the old Realm",+ )+ .await;+ assert_eq!(vm.eval(r#"+ const probe = f => {try {f(); return 'exposed'} catch(error) {return error.name}};+ let conversions = 0;+ JSON.stringify([+ retainedWindow === document.getElementById('target').contentWindow,+ probe(() => retainedGetter.call(retainedWindow)),+ probe(() => retainedMethod.call(retainedWindow, {toString() {++conversions; return 'all'}})),+ conversions+ ])+ "#).unwrap(), r#"[true,"SecurityError","SecurityError",0]"#);+ assert_eq!(server.finish().await.len(), 2);+}diff --git a/moli-renderer-v8/src/window_host.rs b/moli-renderer-v8/src/window_host.rsindex 9a5d4b64e..86a0da2f0 100644--- a/moli-renderer-v8/src/window_host.rs+++ b/moli-renderer-v8/src/window_host.rs@@ -1713,7 +1713,7 @@ fn child_window_message_source<'s>(host: &mut JsContextHost,handle: crate::document_runtime::DomHandle,) -> Option<v8::Local<'s, v8::Object>> {- host.child_browsing_context_window_proxy_for_top(scope, handle)+ host.child_browsing_context_window_proxy_for_accessing_context(scope, handle)}fn collect_timer_extra_args(diff --git a/moli-webapi-declare-derive/src/attrs.rs b/moli-webapi-declare-derive/src/attrs.rsindex d4b7b2d27..c8fd638ce 100644--- a/moli-webapi-declare-derive/src/attrs.rs+++ b/moli-webapi-declare-derive/src/attrs.rs@@ -72,6 +72,7 @@ pub(crate) enum RenameRule {#[derive(Default)]pub(crate) struct ObjectAttrs {pub(crate) receiver: Option<ReceiverAttr>,+ pub(crate) receiver_access_check: bool,pub(crate) role: Option<ObjectRole>,pub(crate) prototype: Option<Expr>,pub(crate) own_to_string_tag: Option<Expr>,@@ -89,6 +90,7 @@ pub(crate) struct ObjectAttrs {pub(crate) struct FunctionTemplateAttrs {pub(crate) interface: Option<Path>,pub(crate) receiver: Option<ReceiverAttr>,+ pub(crate) receiver_access_check: bool,pub(crate) name: Option<LitStr>,pub(crate) constructor: Option<ConstructorAttr>,pub(crate) constructor_length: Option<i32>,@@ -119,9 +121,53 @@ pub(crate) enum FieldKind {ToStringTag,}+#[derive(Clone, Copy, Default, PartialEq)]+pub(crate) enum ReceiverAccessCheck {+ #[default]+ None,+ All,+ Getter,+ Setter,+}++impl ReceiverAccessCheck {+ fn parse(value: Expr) -> Result<Self, Error> {+ let policy = match &value {+ Expr::Lit(ExprLit {+ lit: Lit::Bool(value),+ ..+ }) => Some(if value.value { Self::All } else { Self::None }),+ Expr::Lit(ExprLit {+ lit: Lit::Str(value),+ ..+ }) => match value.value().as_str() {+ "getter" => Some(Self::Getter),+ "setter" => Some(Self::Setter),+ _ => None,+ },+ _ => None,+ };+ policy.ok_or_else(|| {+ Error::new_spanned(+ value,+ "receiver_access_check expects true, false, \"getter\", or \"setter\"",+ )+ })+ }++ pub(crate) fn checks_getter(self) -> bool {+ matches!(self, Self::All | Self::Getter)+ }++ pub(crate) fn checks_setter(self) -> bool {+ matches!(self, Self::All | Self::Setter)+ }+}+#[derive(Clone, Copy, Default)]pub(crate) struct FieldDefaults<'a> {pub(crate) receiver: Option<&'a ReceiverAttr>,+ pub(crate) receiver_access_check: bool,pub(crate) data_properties: bool,pub(crate) enumerable: bool,}@@ -129,6 +175,7 @@ pub(crate) struct FieldDefaults<'a> {#[derive(Clone, Default)]pub(crate) struct FieldAttrs {pub(crate) receiver: Option<ReceiverAttr>,+ pub(crate) receiver_access_check: Option<ReceiverAccessCheck>,pub(crate) returns_promise: bool,pub(crate) kind: FieldKind,pub(crate) enumerable: bool,@@ -201,6 +248,7 @@ impl FieldAttrs {pub(crate) fn has_installation_attribute(&self) -> bool {self.receiver.is_some()+ || self.receiver_access_check.is_some()|| self.returns_promise|| self.enumerable|| self.readonly@@ -226,6 +274,10 @@ pub(crate) fn parse_object_attrs(attrs: &[syn::Attribute]) -> Result<ObjectAttrslet mut interface_receiver = None;for attr in attrs.iter().filter(|attr| attr.path().is_ident("webapi")) {attr.parse_nested_meta(|meta| {+ if meta.path.is_ident("receiver_access_check") {+ parsed.receiver_access_check = true;+ return Ok(());+ }if meta.path.is_ident("receiver") {if meta.input.peek(Token![=]) {parsed.receiver = Some(meta.value()?.parse()?);@@ -309,6 +361,10 @@ pub(crate) fn parse_function_template_attrs(let mut interface_receiver = None;for attr in attrs.iter().filter(|attr| attr.path().is_ident("webapi")) {attr.parse_nested_meta(|meta| {+ if meta.path.is_ident("receiver_access_check") {+ parsed.receiver_access_check = true;+ return Ok(());+ }if meta.path.is_ident("receiver") {if meta.input.peek(Token![=]) {parsed.receiver = Some(meta.value()?.parse()?);@@ -418,6 +474,19 @@ pub(crate) fn parse_field_attrs_with_defaults(.filter(|attr| attr.path().is_ident("webapi")){attr.parse_nested_meta(|meta| {+ if meta.path.is_ident("receiver_access_check") {+ let policy = if meta.input.peek(Token![=]) {+ ReceiverAccessCheck::parse(meta.value()?.parse()?)?+ } else {+ ReceiverAccessCheck::All+ };+ if parsed.receiver_access_check.replace(policy).is_some() {+ return Err(+ meta.error("field receiver_access_check can only be specified once")+ );+ }+ return Ok(());+ }if meta.path.is_ident("receiver") {if parsed.receiver.replace(meta.value()?.parse()?).is_some() {return Err(meta.error("field receiver can only be specified once"));@@ -646,6 +715,33 @@ pub(crate) fn parse_field_attrs_with_defaults());}parsed.inherit_receiver(defaults.receiver)?;+ if parsed.receiver_access_check.is_some()+ && (!matches!(parsed.kind, FieldKind::Method | FieldKind::AccessorProperty)+ || parsed.getter_value.is_some())+ {+ return Err(Error::new(+ field.span(),+ "receiver_access_check requires a method or native accessor callback",+ ));+ }+ if parsed.receiver_access_check.is_none()+ && defaults.receiver_access_check+ && matches!(parsed.kind, FieldKind::Method | FieldKind::AccessorProperty)+ && parsed.getter_value.is_none()+ {+ parsed.receiver_access_check = Some(ReceiverAccessCheck::All);+ }+ if matches!(parsed.kind, FieldKind::Method)+ && matches!(+ parsed.receiver_access_check,+ Some(ReceiverAccessCheck::Getter | ReceiverAccessCheck::Setter)+ )+ {+ return Err(Error::new(+ field.span(),+ "method receiver_access_check expects true or false",+ ));+ }if parsed.value.is_some() && parsed.init.is_some() {return Err(Error::new(@@ -1046,6 +1142,7 @@ mod tests {receiver: Some(&receiver),data_properties: true,enumerable: true,+ ..FieldDefaults::default()};let fields: [Field; 5] = [syn::parse_quote!(value: u32),diff --git a/moli-webapi-declare-derive/src/expand.rs b/moli-webapi-declare-derive/src/expand.rsindex 1a2d0400c..0b68aaeec 100644--- a/moli-webapi-declare-derive/src/expand.rs+++ b/moli-webapi-declare-derive/src/expand.rs@@ -129,6 +129,7 @@ pub(crate) fn expand_webapi_function_template(attrs.rename_all,FieldDefaults {receiver: attrs.receiver.as_ref(),+ receiver_access_check: attrs.receiver_access_check,enumerable: attrs.default_enumerable,..FieldDefaults::default()},@@ -295,6 +296,7 @@ pub(crate) fn expand_webapi_object(input: DeriveInput) -> Result<proc_macro2::Toattrs.rename_all,FieldDefaults {receiver: attrs.receiver.as_ref(),+ receiver_access_check: attrs.receiver_access_check,data_properties: attrs.default_data_properties,enumerable: attrs.default_enumerable,},@@ -630,6 +632,10 @@ fn expand_function_template_method_field(template_name,&name,function_name,+ attrs+ .receiver_access_check+ .unwrap_or_default()+ .checks_getter(),);let field_read = field.ident@@ -714,6 +720,17 @@ fn expand_function_template_accessor_property_field(template_name,&name,quote!(#class_name),+ if is_setter {+ attrs+ .receiver_access_check+ .unwrap_or_default()+ .checks_setter()+ } else {+ attrs+ .receiver_access_check+ .unwrap_or_default()+ .checks_getter()+ },)});let Some(getter_member) = getter_member else {@@ -1074,7 +1091,19 @@ fn expand_accessor_property_field(}let (getter, setter) = expand_accessor_callbacks(attrs, |callback, is_setter, data| {let accessor_name = if is_setter { "setter" } else { "getter" };- let function = expand_function_builder(callback, i32::from(is_setter), data, &name);+ let check_receiver = if is_setter {+ attrs+ .receiver_access_check+ .unwrap_or_default()+ .checks_setter()+ } else {+ attrs+ .receiver_access_check+ .unwrap_or_default()+ .checks_getter()+ };+ let function =+ expand_function_builder(callback, i32::from(is_setter), data, &name, check_receiver);quote! {#function.ok_or_else(|| {::moli_webapi_declare::BindError::new(@@ -1164,7 +1193,16 @@ fn expand_object_method_field(let writable = !attrs.readonly;let configurable = !attrs.dont_delete;let callback = expand_callback(callback, attrs, false);- let build_function = expand_function_builder(&callback, length, attrs.data.as_ref(), &name);+ let build_function = expand_function_builder(+ &callback,+ length,+ attrs.data.as_ref(),+ &name,+ attrs+ .receiver_access_check+ .unwrap_or_default()+ .checks_getter(),+ );let install_method = quote! {let function = #build_function.ok_or_else(|| {::moli_webapi_declare::BindError::new(@@ -1404,6 +1442,7 @@ fn expand_function_builder(length: i32,data: Option<&syn::Expr>,display_name: &proc_macro2::TokenStream,+ receiver_access_check: bool,) -> proc_macro2::TokenStream {// Evaluate callback state during installation, where both `scope` and// `self` exist. Merely carrying Rust state does not expose a JS property.@@ -1419,6 +1458,18 @@ fn expand_function_builder(})?;});let attach_data = data.map(|_| quote!(.data(__webapi_callback_data)));+ if receiver_access_check {+ return quote! {{+ #convert_data+ let template = ::moli_webapi_declare::v8::FunctionTemplate::builder(#callback)+ .length(#length)+ #attach_data+ .constructor_behavior(::moli_webapi_declare::v8::ConstructorBehavior::Throw)+ .build(scope);+ template.set_accept_any_receiver(false);+ template.get_function(scope)+ }};+ }quote! {{#convert_data::moli_webapi_declare::v8::Function::builder(#callback)@@ -1436,6 +1487,7 @@ fn expand_template_function_member(template_name: &proc_macro2::TokenStream,display_name: &proc_macro2::TokenStream,class_name: proc_macro2::TokenStream,+ receiver_access_check: bool,) -> proc_macro2::TokenStream {let data = match data {Some(data) => quote! {@@ -1466,6 +1518,7 @@ fn expand_template_function_member(length: #length,data: #data,class_name: #class_name,+ receiver_access_check: #receiver_access_check,}}}diff --git a/moli-webapi-declare-derive/src/expand/cross_origin.rs b/moli-webapi-declare-derive/src/expand/cross_origin.rsindex c65d2a0f4..67322373f 100644--- a/moli-webapi-declare-derive/src/expand/cross_origin.rs+++ b/moli-webapi-declare-derive/src/expand/cross_origin.rs@@ -18,6 +18,7 @@ pub(crate) fn expand_webapi_cross_origin(|| attrs.scope_lifetime.is_some()|| attrs.default_data_properties|| attrs.default_enumerable+ || attrs.receiver_access_check{return Err(Error::new_spanned(input,@@ -41,6 +42,7 @@ pub(crate) fn expand_webapi_cross_origin(|| attrs.returns_promise|| attrs.symbol.is_some()|| attrs.getter_value.is_some()+ || attrs.receiver_access_check.is_some()|| attrs.value.is_some()|| attrs.init.is_some()|| attrs.enumerablediff --git a/moli-webapi-declare/src/__private.rs b/moli-webapi-declare/src/__private.rsindex 95575b88b..0cebc519b 100644--- a/moli-webapi-declare/src/__private.rs+++ b/moli-webapi-declare/src/__private.rs@@ -17,6 +17,7 @@ pub struct FunctionTemplateMember<'s> {pub length: i32,pub data: Option<v8::Local<'s, v8::Value>>,pub class_name: Option<v8::Local<'s, v8::String>>,+ pub receiver_access_check: bool,}#[inline(always)]@@ -31,6 +32,9 @@ fn build_function_template_member<'s>(Some(data) => builder.data(data).build(scope),None => builder.build(scope),};+ if member.receiver_access_check {+ function.set_accept_any_receiver(false);+ }if let Some(class_name) = member.class_name {function.set_class_name(class_name);}diff --git a/moli-webapi-declare/src/lib.rs b/moli-webapi-declare/src/lib.rsindex 0574a1ee7..45cf50e82 100644--- a/moli-webapi-declare/src/lib.rs+++ b/moli-webapi-declare/src/lib.rs@@ -197,6 +197,13 @@//! execute JavaScript or throw. Use it for checks that additionally require//! native resource state; ordinary interface checks should use their descriptor.//!+//! `receiver_access_check` enables V8's receiver access check before invoking+//! native methods and accessor callbacks. Window bindings use it to reject+//! cross-origin borrowed calls before argument conversion or a realm switch.+//! It can be a struct default or a member policy. A member can use `false` to+//! allow cross-origin calls, or `"getter"` / `"setter"` to check only that half+//! of an accessor. Interface brand checks remain a separate policy.+//!//! `returns_promise` on a method (including a static method) or accessor getter//! converts synchronous exceptions from both the receiver check and the callback//! into rejected Promises in the callback's realm. Successful return values are