script/dom/
dissimilaroriginwindow.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use base::id::PipelineId;
6use constellation_traits::{ScriptToConstellationMessage, StructuredSerializedData};
7use dom_struct::dom_struct;
8use js::jsapi::{Heap, JSObject};
9use js::jsval::UndefinedValue;
10use js::rust::{CustomAutoRooter, CustomAutoRooterGuard, HandleValue, MutableHandleValue};
11use servo_url::ServoUrl;
12
13use crate::dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding;
14use crate::dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding::DissimilarOriginWindowMethods;
15use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowPostMessageOptions;
16use crate::dom::bindings::error::{Error, ErrorResult};
17use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
18use crate::dom::bindings::str::USVString;
19use crate::dom::bindings::structuredclone;
20use crate::dom::bindings::trace::RootedTraceableBox;
21use crate::dom::dissimilaroriginlocation::DissimilarOriginLocation;
22use crate::dom::globalscope::GlobalScope;
23use crate::dom::windowproxy::WindowProxy;
24use crate::script_runtime::{CanGc, JSContext};
25
26/// Represents a dissimilar-origin `Window` that exists in another script thread.
27///
28/// Since the `Window` is in a different script thread, we cannot access it
29/// directly, but some of its accessors (for example `window.parent`)
30/// still need to function.
31///
32/// In `windowproxy.rs`, we create a custom window proxy for these windows,
33/// that throws security exceptions for most accessors. This is not a replacement
34/// for XOWs, but provides belt-and-braces security.
35#[dom_struct]
36pub(crate) struct DissimilarOriginWindow {
37    /// The global for this window.
38    globalscope: GlobalScope,
39
40    /// The window proxy for this window.
41    window_proxy: Dom<WindowProxy>,
42
43    /// The location of this window, initialized lazily.
44    location: MutNullableDom<DissimilarOriginLocation>,
45}
46
47impl DissimilarOriginWindow {
48    #[allow(unsafe_code)]
49    pub(crate) fn new(
50        global_to_clone_from: &GlobalScope,
51        window_proxy: &WindowProxy,
52    ) -> DomRoot<Self> {
53        let cx = GlobalScope::get_cx();
54        let win = Box::new(Self {
55            globalscope: GlobalScope::new_inherited(
56                PipelineId::new(),
57                global_to_clone_from.devtools_chan().cloned(),
58                global_to_clone_from.mem_profiler_chan().clone(),
59                global_to_clone_from.time_profiler_chan().clone(),
60                global_to_clone_from.script_to_constellation_chan().clone(),
61                global_to_clone_from.script_to_embedder_chan().clone(),
62                global_to_clone_from.resource_threads().clone(),
63                global_to_clone_from.origin().clone(),
64                global_to_clone_from.creation_url().clone(),
65                global_to_clone_from.top_level_creation_url().clone(),
66                // FIXME(nox): The microtask queue is probably not important
67                // here, but this whole DOM interface is a hack anyway.
68                global_to_clone_from.microtask_queue().clone(),
69                #[cfg(feature = "webgpu")]
70                global_to_clone_from.wgpu_id_hub(),
71                Some(global_to_clone_from.is_secure_context()),
72                false,
73                global_to_clone_from.font_context().cloned(),
74            ),
75            window_proxy: Dom::from_ref(window_proxy),
76            location: Default::default(),
77        });
78        DissimilarOriginWindowBinding::Wrap::<crate::DomTypeHolder>(cx, win)
79    }
80
81    pub(crate) fn window_proxy(&self) -> DomRoot<WindowProxy> {
82        DomRoot::from_ref(&*self.window_proxy)
83    }
84}
85
86impl DissimilarOriginWindowMethods<crate::DomTypeHolder> for DissimilarOriginWindow {
87    // https://html.spec.whatwg.org/multipage/#dom-window
88    fn Window(&self) -> DomRoot<WindowProxy> {
89        self.window_proxy()
90    }
91
92    // https://html.spec.whatwg.org/multipage/#dom-self
93    fn Self_(&self) -> DomRoot<WindowProxy> {
94        self.window_proxy()
95    }
96
97    // https://html.spec.whatwg.org/multipage/#dom-frames
98    fn Frames(&self) -> DomRoot<WindowProxy> {
99        self.window_proxy()
100    }
101
102    // https://html.spec.whatwg.org/multipage/#dom-parent
103    fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
104        // Steps 1-3.
105        if self.window_proxy.is_browsing_context_discarded() {
106            return None;
107        }
108        // Step 4.
109        if let Some(parent) = self.window_proxy.parent() {
110            return Some(DomRoot::from_ref(parent));
111        }
112        // Step 5.
113        Some(DomRoot::from_ref(&*self.window_proxy))
114    }
115
116    // https://html.spec.whatwg.org/multipage/#dom-top
117    fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
118        // Steps 1-3.
119        if self.window_proxy.is_browsing_context_discarded() {
120            return None;
121        }
122        // Steps 4-5.
123        Some(DomRoot::from_ref(self.window_proxy.top()))
124    }
125
126    // https://html.spec.whatwg.org/multipage/#dom-length
127    fn Length(&self) -> u32 {
128        // TODO: Implement x-origin length
129        0
130    }
131
132    // https://html.spec.whatwg.org/multipage/#dom-window-close
133    fn Close(&self) {
134        // TODO: Implement x-origin close
135    }
136
137    // https://html.spec.whatwg.org/multipage/#dom-window-closed
138    fn Closed(&self) -> bool {
139        // TODO: Implement x-origin close
140        false
141    }
142
143    /// <https://html.spec.whatwg.org/multipage/#dom-window-postmessage>
144    fn PostMessage(
145        &self,
146        cx: JSContext,
147        message: HandleValue,
148        target_origin: USVString,
149        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
150    ) -> ErrorResult {
151        self.post_message_impl(&target_origin, cx, message, transfer)
152    }
153
154    /// <https://html.spec.whatwg.org/multipage/#dom-window-postmessage-options>
155    fn PostMessage_(
156        &self,
157        cx: JSContext,
158        message: HandleValue,
159        options: RootedTraceableBox<WindowPostMessageOptions>,
160    ) -> ErrorResult {
161        let mut rooted = CustomAutoRooter::new(
162            options
163                .parent
164                .transfer
165                .iter()
166                .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get())
167                .collect(),
168        );
169        let transfer = CustomAutoRooterGuard::new(*cx, &mut rooted);
170
171        self.post_message_impl(&options.targetOrigin, cx, message, transfer)
172    }
173
174    // https://html.spec.whatwg.org/multipage/#dom-opener
175    fn Opener(&self, _: JSContext, mut retval: MutableHandleValue) {
176        // TODO: Implement x-origin opener
177        retval.set(UndefinedValue());
178    }
179
180    // https://html.spec.whatwg.org/multipage/#dom-opener
181    fn SetOpener(&self, _: JSContext, _: HandleValue) {
182        // TODO: Implement x-origin opener
183    }
184
185    // https://html.spec.whatwg.org/multipage/#dom-window-blur
186    fn Blur(&self) {
187        // > User agents are encouraged to ignore calls to this `blur()` method
188        // > entirely.
189    }
190
191    // https://html.spec.whatwg.org/multipage/#dom-window-focus
192    fn Focus(&self) {
193        self.window_proxy().focus();
194    }
195
196    // https://html.spec.whatwg.org/multipage/#dom-location
197    fn Location(&self, can_gc: CanGc) -> DomRoot<DissimilarOriginLocation> {
198        self.location
199            .or_init(|| DissimilarOriginLocation::new(self, can_gc))
200    }
201}
202
203impl DissimilarOriginWindow {
204    /// <https://html.spec.whatwg.org/multipage/#window-post-message-steps>
205    fn post_message_impl(
206        &self,
207        target_origin: &USVString,
208        cx: JSContext,
209        message: HandleValue,
210        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
211    ) -> ErrorResult {
212        // Step 6-7.
213        let data = structuredclone::write(cx, message, Some(transfer))?;
214
215        self.post_message(target_origin, data)
216    }
217
218    /// <https://html.spec.whatwg.org/multipage/#window-post-message-steps>
219    pub(crate) fn post_message(
220        &self,
221        target_origin: &USVString,
222        data: StructuredSerializedData,
223    ) -> ErrorResult {
224        // Step 1.
225        let target = self.window_proxy.browsing_context_id();
226        // Step 2.
227        let incumbent = match GlobalScope::incumbent() {
228            None => panic!("postMessage called with no incumbent global"),
229            Some(incumbent) => incumbent,
230        };
231
232        let source_origin = incumbent.origin().immutable().clone();
233
234        // Step 3-5.
235        let target_origin = match target_origin.0[..].as_ref() {
236            "*" => None,
237            "/" => Some(source_origin.clone()),
238            url => match ServoUrl::parse(url) {
239                Ok(url) => Some(url.origin().clone()),
240                Err(_) => return Err(Error::Syntax(None)),
241            },
242        };
243        let msg = ScriptToConstellationMessage::PostMessage {
244            target,
245            source: incumbent.pipeline_id(),
246            source_origin,
247            target_origin,
248            data,
249        };
250        // Step 8
251        let _ = incumbent.script_to_constellation_chan().send(msg);
252        Ok(())
253    }
254}