Skip to main content

quickjs_jit_stdlib/llrt/llrt_crypto/
lib.rs

1// Vendored from LLRT d9fd873e793c (modules/llrt_crypto/src/lib.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5
6// Compile-time checks for conflicting crypto features
7#[cfg(all(feature = "crypto", any()))]
8compile_error!("Features `crypto-rust` and `crypto-openssl` are mutually exclusive");
9
10#[cfg(all(feature = "crypto", any()))]
11compile_error!("Features `crypto-rust` and `crypto-ring` are mutually exclusive");
12
13#[cfg(all(feature = "crypto", any()))]
14compile_error!("Features `crypto-rust` and `crypto-graviola` are mutually exclusive");
15
16#[cfg(all(any(), any()))]
17compile_error!("Features `crypto-openssl` and `crypto-ring` are mutually exclusive");
18
19#[cfg(all(any(), any()))]
20compile_error!("Features `crypto-openssl` and `crypto-graviola` are mutually exclusive");
21
22#[cfg(all(any(), any()))]
23compile_error!("Features `crypto-ring` and `crypto-graviola` are mutually exclusive");
24
25mod crc32;
26mod hash;
27mod subtle;
28
29mod provider;
30
31use std::slice;
32
33use crate::buffer::Buffer;
34use crate::context::CtxExtension;
35use crate::encoding::{bytes_to_b64_string, bytes_to_hex_string};
36use crate::exceptions::DOMException;
37use crate::utils::{
38    bytes::{get_start_end_indexes, ObjectBytes},
39    error::ErrorExtensions,
40    error_messages::{ERROR_MSG_ARRAY_BUFFER_DETACHED, ERROR_MSG_NOT_ARRAY_BUFFER},
41    module::{export_default, ModuleInfo},
42    result::ResultExt,
43};
44use once_cell::sync::Lazy;
45use rand::RngExt;
46use rquickjs::prelude::Async;
47use rquickjs::{
48    atom::PredefinedAtom,
49    function::{Constructor, Opt},
50    module::{Declarations, Exports, ModuleDef},
51    prelude::{Func, Rest},
52    Class, Ctx, Error, Exception, Function, IntoJs, Null, Object, Result, Value,
53};
54pub use subtle::CryptoKey;
55use subtle::{
56    subtle_decapsulate_bits, subtle_decapsulate_key, subtle_decrypt, subtle_derive_bits,
57    subtle_derive_key, subtle_digest, subtle_encapsulate_bits, subtle_encapsulate_key,
58    subtle_encrypt, subtle_export_key, subtle_generate_key, subtle_import_key, subtle_sign,
59    subtle_unwrap_key, subtle_verify, subtle_wrap_key, SubtleCrypto,
60};
61
62use self::{
63    crc32::{Crc32, Crc32c},
64    hash::{Hash, HashAlgorithm, Hmac},
65};
66
67static CRYPTO_PROVIDER: Lazy<provider::DefaultProvider> =
68    Lazy::new(|| provider::DefaultProvider {});
69
70fn encoded_bytes<'js>(ctx: &Ctx<'js>, bytes: &[u8], encoding: &str) -> Result<Option<Value<'js>>> {
71    match encoding {
72        "hex" => {
73            let hex = bytes_to_hex_string(bytes);
74            let hex = rquickjs::String::from_str(ctx.clone(), &hex)?;
75            Ok(Some(Value::from_string(hex)))
76        }
77        "base64" => {
78            let b64 = bytes_to_b64_string(bytes);
79            let b64 = rquickjs::String::from_str(ctx.clone(), &b64)?;
80            Ok(Some(Value::from_string(b64)))
81        }
82        _ => Ok(None),
83    }
84}
85
86#[inline]
87pub fn random_byte_array(length: usize) -> Vec<u8> {
88    let mut vec = vec![0u8; length];
89    rand::rng().fill(&mut vec[..]);
90    vec
91}
92
93fn get_random_bytes(ctx: Ctx, length: usize) -> Result<Value> {
94    let random_bytes = random_byte_array(length);
95    Buffer(random_bytes).into_js(&ctx)
96}
97
98fn get_random_int(first: i64, second: Opt<i64>) -> Result<i64> {
99    let mut rng = rand::rng();
100    let random_number = match second.0 {
101        Some(max) => rng.random_range(first..max),
102        None => rng.random_range(0..first),
103    };
104
105    Ok(random_number)
106}
107
108fn random_fill<'js>(ctx: Ctx<'js>, obj: Object<'js>, args: Rest<Value<'js>>) -> Result<()> {
109    let args_iter = args.0.into_iter();
110    let mut args_iter = args_iter.rev();
111
112    let callback: Function = args_iter
113        .next()
114        .and_then(|v| v.into_function())
115        .or_throw_msg(&ctx, "Callback required")?;
116    let size = args_iter
117        .next()
118        .and_then(|arg| arg.as_int())
119        .map(|i| i as usize);
120    let offset = args_iter
121        .next()
122        .and_then(|arg| arg.as_int())
123        .map(|i| i as usize);
124
125    ctx.clone().spawn_exit(async move {
126        if let Err(err) = random_fill_sync(ctx.clone(), obj.clone(), Opt(offset), Opt(size)) {
127            let err = err.into_value(&ctx)?;
128            () = callback.call((err,))?;
129
130            return Ok(());
131        }
132        () = callback.call((Null.into_js(&ctx), obj))?;
133        Ok::<_, Error>(())
134    })?;
135    Ok(())
136}
137
138fn random_fill_sync<'js>(
139    ctx: Ctx<'js>,
140    obj: Object<'js>,
141    offset: Opt<usize>,
142    size: Opt<usize>,
143) -> Result<Object<'js>> {
144    let offset = offset.unwrap_or(0);
145
146    if let Some(object_bytes) = ObjectBytes::from_array_buffer(&obj)? {
147        let (array_buffer, source_length, source_offset) = object_bytes
148            .get_array_buffer()?
149            .expect(ERROR_MSG_NOT_ARRAY_BUFFER);
150        let raw = array_buffer
151            .as_raw()
152            .ok_or(ERROR_MSG_ARRAY_BUFFER_DETACHED)
153            .or_throw(&ctx)?;
154
155        if offset > source_length {
156            return Err(Exception::throw_range(
157                &ctx,
158                "The value of \"offset\" is out of range",
159            ));
160        }
161        if let Some(size) = size.0 {
162            if offset + size > source_length {
163                return Err(Exception::throw_range(
164                    &ctx,
165                    "The value of \"size + offset\" is out of range",
166                ));
167            }
168        }
169
170        let (start, end) = get_start_end_indexes(source_length, size.0, offset);
171
172        // SAFETY: source_offset..+source_length stays in the backing buffer;
173        // start/end are clamped to it above.
174        let bytes = unsafe {
175            slice::from_raw_parts_mut(raw.cast::<u8>().as_ptr().add(source_offset), source_length)
176        };
177
178        rand::rng().fill(&mut bytes[start..end]);
179    }
180
181    Ok(obj)
182}
183
184fn get_random_values<'js>(ctx: Ctx<'js>, obj: Object<'js>) -> Result<Object<'js>> {
185    if let Some(object_bytes) = ObjectBytes::from_array_buffer(&obj)? {
186        if matches!(
187            object_bytes,
188            ObjectBytes::F64Array(_)
189                | ObjectBytes::F32Array(_)
190                | ObjectBytes::F16Array(_)
191                | ObjectBytes::DataView(_, _, _)
192        ) {
193            return Err(DOMException::type_mismatch_error(
194                &ctx,
195                "getRandomValues requires an integer TypedArray",
196            ));
197        }
198
199        let (array_buffer, source_length, source_offset) = object_bytes
200            .get_array_buffer()?
201            .expect(ERROR_MSG_NOT_ARRAY_BUFFER);
202        let raw = array_buffer
203            .as_raw()
204            .ok_or(ERROR_MSG_ARRAY_BUFFER_DETACHED)
205            .or_throw(&ctx)?;
206
207        if source_length > 0x10000 {
208            return Err(DOMException::quota_exceeded_error(
209                &ctx,
210                "The requested length exceeds 65,536 bytes",
211            ));
212        }
213
214        let bytes = unsafe {
215            std::slice::from_raw_parts_mut(
216                raw.cast::<u8>().as_ptr().add(source_offset),
217                source_length,
218            )
219        };
220
221        rand::rng().fill(bytes)
222    }
223
224    Ok(obj)
225}
226
227fn uuidv4() -> String {
228    let uuid = rand::random::<u128>() & 0xFFFFFFFFFFFF4FFFBFFFFFFFFFFFFFFF | 0x40008000000000000000;
229
230    static HEX_CHARS: &[u8; 16] = b"0123456789abcdef";
231    let bytes = uuid.to_be_bytes();
232
233    let mut buf = [0u8; 36];
234
235    // Precomputed positions for 32 hex digits (excluding hyphens)
236    static HEX_POS: [usize; 32] = [
237        0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 19, 20, 21, 22, 24, 25, 26, 27, 28,
238        29, 30, 31, 32, 33, 34, 35,
239    ];
240
241    // Map each byte to its hex representation
242    let mut hex_idx = 0;
243    for &byte in &bytes[..] {
244        let high = HEX_CHARS[(byte >> 4) as usize];
245        let low = HEX_CHARS[(byte & 0x0f) as usize];
246
247        buf[HEX_POS[hex_idx]] = high;
248        buf[HEX_POS[hex_idx + 1]] = low;
249        hex_idx += 2;
250    }
251
252    // Insert hyphens at standard positions
253    buf[8] = b'-';
254    buf[13] = b'-';
255    buf[18] = b'-';
256    buf[23] = b'-';
257
258    // SAFETY: The buffer only contains valid UTF-8 characters (hex digits and hyphens)
259    // that were explicitly set from the HEX_CHARS array and hyphen literals
260    unsafe { String::from_utf8_unchecked(buf.to_vec()) }
261}
262
263#[rquickjs::class]
264#[derive(rquickjs::JsLifetime, rquickjs::class::Trace)]
265struct Crypto {}
266
267#[rquickjs::methods]
268impl Crypto {
269    #[qjs(constructor)]
270    pub fn new(ctx: Ctx<'_>) -> Result<Self> {
271        Err(Exception::throw_type(&ctx, "Illegal constructor"))
272    }
273
274    #[qjs(prop, rename = PredefinedAtom::SymbolToStringTag, configurable)]
275    pub fn to_string_tag() -> &'static str {
276        stringify!(Crypto)
277    }
278}
279
280pub fn init(ctx: &Ctx<'_>) -> Result<()> {
281    let globals = ctx.globals();
282
283    Class::<Crypto>::define(&globals)?;
284    let crypto = Class::instance(ctx.clone(), Crypto {})?;
285
286    crypto.set("createHash", Func::from(Hash::new))?;
287    crypto.set("createHmac", Func::from(Hmac::new))?;
288    crypto.set("randomBytes", Func::from(get_random_bytes))?;
289    crypto.set("randomInt", Func::from(get_random_int))?;
290    crypto.set("randomUUID", Func::from(uuidv4))?;
291    crypto.set("randomFillSync", Func::from(random_fill_sync))?;
292    crypto.set("randomFill", Func::from(random_fill))?;
293    crypto.set("getRandomValues", Func::from(get_random_values))?;
294
295    Class::<SubtleCrypto>::define(&globals)?;
296    Class::<CryptoKey>::define(&globals)?;
297
298    let subtle = Class::instance(ctx.clone(), SubtleCrypto {})?;
299    subtle.set(
300        "decapsulateBits",
301        Func::from(Async(subtle_decapsulate_bits)),
302    )?;
303    subtle.set("decapsulateKey", Func::from(Async(subtle_decapsulate_key)))?;
304    subtle.set("decrypt", Func::from(Async(subtle_decrypt)))?;
305    subtle.set("deriveKey", Func::from(Async(subtle_derive_key)))?;
306    subtle.set("deriveBits", Func::from(Async(subtle_derive_bits)))?;
307    subtle.set("digest", Func::from(Async(subtle_digest)))?;
308    subtle.set("encrypt", Func::from(Async(subtle_encrypt)))?;
309    subtle.set(
310        "encapsulateBits",
311        Func::from(Async(subtle_encapsulate_bits)),
312    )?;
313    subtle.set("encapsulateKey", Func::from(Async(subtle_encapsulate_key)))?;
314    subtle.set("exportKey", Func::from(Async(subtle_export_key)))?;
315    subtle.set("generateKey", Func::from(Async(subtle_generate_key)))?;
316    subtle.set("importKey", Func::from(Async(subtle_import_key)))?;
317    subtle.set("sign", Func::from(Async(subtle_sign)))?;
318    subtle.set("verify", Func::from(Async(subtle_verify)))?;
319    subtle.set("wrapKey", Func::from(Async(subtle_wrap_key)))?;
320    subtle.set("unwrapKey", Func::from(Async(subtle_unwrap_key)))?;
321    crypto.set("subtle", subtle)?;
322
323    globals.set("crypto", crypto)?;
324
325    Ok(())
326}
327
328pub struct CryptoModule;
329
330impl ModuleDef for CryptoModule {
331    fn declare(declare: &Declarations) -> Result<()> {
332        declare.declare("createHash")?;
333        declare.declare("createHmac")?;
334        declare.declare("Crc32")?;
335        declare.declare("Crc32c")?;
336        declare.declare("randomBytes")?;
337        declare.declare("randomUUID")?;
338        declare.declare("randomInt")?;
339        declare.declare("randomFillSync")?;
340        declare.declare("randomFill")?;
341        declare.declare("getRandomValues")?;
342
343        for algorithm in HashAlgorithm::iter() {
344            declare.declare(algorithm.class_name())?;
345        }
346
347        declare.declare("crypto")?;
348        declare.declare("webcrypto")?;
349        declare.declare("default")?;
350
351        Ok(())
352    }
353
354    fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
355        export_default(ctx, exports, |default| {
356            for algorithm in HashAlgorithm::iter() {
357                let class_name: &str = algorithm.class_name();
358                let algo_name = String::from(algorithm.as_str());
359
360                let ctor = Constructor::new_class::<Hash, _, _>(
361                    ctx.clone(),
362                    move |ctx: Ctx<'js>, secret: Opt<ObjectBytes<'js>>| match secret.0 {
363                        Some(secret) => Hash::new_hmac(ctx, algo_name.clone(), secret),
364                        None => Hash::new(ctx, algo_name.clone()),
365                    },
366                )?;
367
368                default.set(class_name, ctor)?;
369            }
370
371            let crypto: Object = ctx.globals().get("crypto")?;
372
373            Class::<Crc32>::define(default)?;
374            Class::<Crc32c>::define(default)?;
375
376            default.set("createHash", Func::from(Hash::new))?;
377            default.set("createHmac", Func::from(Hmac::new))?;
378            default.set("randomBytes", Func::from(get_random_bytes))?;
379            default.set("randomInt", Func::from(get_random_int))?;
380            default.set("randomUUID", Func::from(uuidv4))?;
381            default.set("randomFillSync", Func::from(random_fill_sync))?;
382            default.set("randomFill", Func::from(random_fill))?;
383            default.set("getRandomValues", Func::from(get_random_values))?;
384            default.set("crypto", crypto.clone())?;
385            default.set("webcrypto", crypto)?;
386            Ok(())
387        })?;
388
389        Ok(())
390    }
391}
392
393impl From<CryptoModule> for ModuleInfo<CryptoModule> {
394    fn from(val: CryptoModule) -> Self {
395        ModuleInfo {
396            name: "crypto",
397            module: val,
398        }
399    }
400}