script/dom/
crypto.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::jsapi::{JSObject, Type};
7use js::rust::CustomAutoRooterGuard;
8use js::typedarray::{ArrayBufferView, ArrayBufferViewU8, TypedArray};
9use rand::TryRngCore;
10use rand::rngs::OsRng;
11use uuid::Uuid;
12
13use crate::dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods;
14use crate::dom::bindings::error::{Error, Fallible};
15use crate::dom::bindings::reflector::{DomGlobal, Reflector, reflect_dom_object};
16use crate::dom::bindings::root::{DomRoot, MutNullableDom};
17use crate::dom::bindings::str::DOMString;
18use crate::dom::globalscope::GlobalScope;
19use crate::dom::subtlecrypto::SubtleCrypto;
20use crate::script_runtime::{CanGc, JSContext};
21
22// https://developer.mozilla.org/en-US/docs/Web/API/Crypto
23#[dom_struct]
24pub(crate) struct Crypto {
25    reflector_: Reflector,
26    subtle: MutNullableDom<SubtleCrypto>,
27}
28
29impl Crypto {
30    fn new_inherited() -> Crypto {
31        Crypto {
32            reflector_: Reflector::new(),
33            subtle: MutNullableDom::default(),
34        }
35    }
36
37    pub(crate) fn new(global: &GlobalScope, can_gc: CanGc) -> DomRoot<Crypto> {
38        reflect_dom_object(Box::new(Crypto::new_inherited()), global, can_gc)
39    }
40}
41
42impl CryptoMethods<crate::DomTypeHolder> for Crypto {
43    /// <https://w3c.github.io/webcrypto/#dfn-Crypto-attribute-subtle>
44    fn Subtle(&self, can_gc: CanGc) -> DomRoot<SubtleCrypto> {
45        self.subtle
46            .or_init(|| SubtleCrypto::new(&self.global(), can_gc))
47    }
48
49    #[allow(unsafe_code)]
50    /// <https://w3c.github.io/webcrypto/#Crypto-method-getRandomValues>
51    fn GetRandomValues(
52        &self,
53        _cx: JSContext,
54        mut input: CustomAutoRooterGuard<ArrayBufferView>,
55    ) -> Fallible<ArrayBufferView> {
56        let array_type = input.get_array_type();
57
58        if !is_integer_buffer(array_type) {
59            Err(Error::TypeMismatch)
60        } else {
61            let data = unsafe { input.as_mut_slice() };
62            if data.len() > 65536 {
63                return Err(Error::QuotaExceeded {
64                    quota: None,
65                    requested: None,
66                });
67            }
68
69            if OsRng.try_fill_bytes(data).is_err() {
70                return Err(Error::JSFailed);
71            }
72
73            let underlying_object = unsafe { input.underlying_object() };
74            TypedArray::<ArrayBufferViewU8, *mut JSObject>::from(*underlying_object)
75                .map_err(|_| Error::JSFailed)
76        }
77    }
78
79    /// <https://w3c.github.io/webcrypto/#Crypto-method-randomUUID>
80    fn RandomUUID(&self) -> DOMString {
81        let uuid = Uuid::new_v4();
82        uuid.hyphenated()
83            .encode_lower(&mut Uuid::encode_buffer())
84            .to_owned()
85            .into()
86    }
87}
88
89fn is_integer_buffer(array_type: Type) -> bool {
90    matches!(
91        array_type,
92        Type::Uint8 |
93            Type::Uint8Clamped |
94            Type::Int8 |
95            Type::Uint16 |
96            Type::Int16 |
97            Type::Uint32 |
98            Type::Int32 |
99            Type::BigInt64 |
100            Type::BigUint64
101    )
102}