Skip to main content

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