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