Skip to main content

script/dom/globalscope/
origin.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 dom_struct::dom_struct;
6use js::rust::{HandleObject, HandleValue};
7use net_traits::pub_domains::is_same_site;
8use script_bindings::reflector::{Reflector, reflect_dom_object_with_proto_and_cx};
9use servo_url::{ImmutableOrigin, ServoUrl};
10
11use crate::dom::bindings::codegen::Bindings::OriginBinding::OriginMethods;
12use crate::dom::bindings::conversions::{
13    ConversionResult, FromJSValConvertible, StringificationBehavior, root_from_handlevalue,
14};
15use crate::dom::bindings::error::{Error, Fallible};
16use crate::dom::bindings::root::DomRoot;
17use crate::dom::bindings::str::DOMString;
18use crate::dom::globalscope::GlobalScope;
19use crate::dom::html::htmlanchorelement::HTMLAnchorElement;
20use crate::dom::html::htmlareaelement::HTMLAreaElement;
21use crate::dom::html::htmlhyperlinkelementutils::{HyperlinkElement, HyperlinkElementTraits};
22use crate::dom::url::URL;
23use crate::dom::window::Window;
24use crate::script_runtime::JSContext;
25
26/// <https://html.spec.whatwg.org/multipage/#the-origin-interface>
27#[dom_struct]
28pub(crate) struct Origin {
29    reflector: Reflector,
30    #[no_trace]
31    origin: ImmutableOrigin,
32}
33
34impl Origin {
35    fn new_inherited(origin: ImmutableOrigin) -> Origin {
36        Origin {
37            reflector: Reflector::new(),
38            origin,
39        }
40    }
41
42    fn new(
43        cx: &mut js::context::JSContext,
44        global: &GlobalScope,
45        proto: Option<HandleObject>,
46        origin: ImmutableOrigin,
47    ) -> DomRoot<Origin> {
48        reflect_dom_object_with_proto_and_cx(
49            Box::new(Origin::new_inherited(origin)),
50            global,
51            proto,
52            cx,
53        )
54    }
55
56    /// <https://html.spec.whatwg.org/multipage/#extract-an-origin>
57    fn extract_an_origin_from_platform_object(
58        value: HandleValue,
59        cx: JSContext,
60        current_global: &GlobalScope,
61    ) -> Option<ImmutableOrigin> {
62        // <https://html.spec.whatwg.org/multipage/#the-origin-interface:extract-an-origin>
63        if let Ok(origin_obj) = root_from_handlevalue::<Origin>(value, cx) {
64            return Some(origin_obj.origin.clone());
65        }
66
67        // <https://url.spec.whatwg.org/#concept-url-origin>
68        if let Ok(url_obj) = root_from_handlevalue::<URL>(value, cx) {
69            return Some(url_obj.origin());
70        }
71
72        // <https://html.spec.whatwg.org/multipage/#window:extract-an-origin>
73        if let Ok(window_obj) = root_from_handlevalue::<Window>(value, cx) {
74            let window_origin = window_obj.origin();
75            if !current_global.origin().same_origin_domain(&window_origin) {
76                return None;
77            }
78            return Some(window_origin.immutable().clone());
79        }
80
81        // <https://html.spec.whatwg.org/multipage/#api-for-a-and-area-elements:extract-an-origin>
82        if let Ok(anchor_obj) = root_from_handlevalue::<HTMLAnchorElement>(value, cx) {
83            anchor_obj.reinitialize_url();
84            if let Some(ref url) = *anchor_obj.get_url().borrow() {
85                return Some(url.origin());
86            }
87            return None;
88        }
89
90        // <https://html.spec.whatwg.org/multipage/#api-for-a-and-area-elements:extract-an-origin>
91        if let Ok(area_obj) = root_from_handlevalue::<HTMLAreaElement>(value, cx) {
92            area_obj.reinitialize_url();
93            if let Some(ref url) = *area_obj.get_url().borrow() {
94                return Some(url.origin());
95            }
96            return None;
97        }
98
99        None
100    }
101}
102
103impl OriginMethods<crate::DomTypeHolder> for Origin {
104    /// <https://html.spec.whatwg.org/multipage/#dom-origin-constructor>
105    fn Constructor(
106        cx: &mut js::context::JSContext,
107        global: &GlobalScope,
108        proto: Option<HandleObject>,
109    ) -> DomRoot<Origin> {
110        Origin::new(cx, global, proto, ImmutableOrigin::new_opaque())
111    }
112
113    /// <https://html.spec.whatwg.org/multipage/#dom-origin-from>
114    fn From(
115        cx: &mut js::context::JSContext,
116        global: &GlobalScope,
117        value: HandleValue,
118    ) -> Fallible<DomRoot<Origin>> {
119        // Step 1. If value is a platform object:
120        //   1. Let origin be the result of executing value's extract an origin operation.
121        //   2. If origin is not null, then return a new Origin object whose origin is origin.
122        if let Some(origin) =
123            Origin::extract_an_origin_from_platform_object(value, cx.into(), global)
124        {
125            return Ok(Origin::new(cx, global, None, origin));
126        }
127
128        // Step 2. If value is a string:
129        if value.get().is_string() {
130            let s = match DOMString::safe_from_jsval(cx, value, StringificationBehavior::Default) {
131                Ok(ConversionResult::Success(s)) => s,
132                _ => return Err(Error::Type(c"Failed to convert value to string".to_owned())),
133            };
134
135            // Step 2.1. Let parsedURL be the result of basic URL parsing value.
136            // Step 2.2. If parsedURL is not failure, then return a new Origin object whose
137            //           origin is set to parsedURL's origin.
138            match ServoUrl::parse(&s.str()) {
139                Ok(url) => return Ok(Origin::new(cx, global, None, url.origin())),
140                Err(_) => return Err(Error::Type(c"Failed to parse URL".to_owned())),
141            }
142        }
143
144        // Step 3. Throw a TypeError.
145        Err(Error::Type(
146            c"Value must be a string or a platform object with an origin".to_owned(),
147        ))
148    }
149
150    /// <https://html.spec.whatwg.org/multipage/#dom-origin-opaque>
151    fn Opaque(&self) -> bool {
152        !self.origin.is_tuple()
153    }
154
155    /// <https://html.spec.whatwg.org/multipage/#dom-origin-issameorigin>
156    fn IsSameOrigin(&self, other: &Origin) -> bool {
157        self.origin == other.origin
158    }
159
160    /// <https://html.spec.whatwg.org/multipage/#dom-origin-issamesite>
161    fn IsSameSite(&self, other: &Origin) -> bool {
162        is_same_site(&self.origin, &other.origin)
163    }
164}