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::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, cx: &mut js::context::JSContext) -> DomRoot<SubtleCrypto> {
46        self.subtle
47            .or_init(|| SubtleCrypto::new(cx, &self.global()))
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::Operation(Some(
72                    "Failed to generate random values".into(),
73                )));
74            }
75
76            let underlying_object = unsafe { input.underlying_object() };
77            TypedArray::<ArrayBufferViewU8, Box<Heap<*mut JSObject>>>::from(*underlying_object)
78                .map(RootedTraceableBox::new)
79                .map_err(|_| Error::JSFailed)
80        }
81    }
82
83    /// <https://w3c.github.io/webcrypto/#Crypto-method-randomUUID>
84    fn RandomUUID(&self) -> DOMString {
85        let uuid = Uuid::new_v4();
86        uuid.hyphenated()
87            .encode_lower(&mut Uuid::encode_buffer())
88            .to_owned()
89            .into()
90    }
91}
92
93fn is_integer_buffer(array_type: Type) -> bool {
94    matches!(
95        array_type,
96        Type::Uint8 |
97            Type::Uint8Clamped |
98            Type::Int8 |
99            Type::Uint16 |
100            Type::Int16 |
101            Type::Uint32 |
102            Type::Int32 |
103            Type::BigInt64 |
104            Type::BigUint64
105    )
106}