|
1 | 1 | //! Implementation for WASM based on Web and Node.js |
2 | 2 | use crate::Error; |
3 | | - |
4 | | -extern crate std; |
5 | | -use std::{mem::MaybeUninit, thread_local}; |
| 3 | +use core::mem::MaybeUninit; |
6 | 4 |
|
7 | 5 | pub use crate::util::{inner_u32, inner_u64}; |
8 | 6 |
|
9 | | -#[cfg(not(all(target_arch = "wasm32", target_os = "unknown",)))] |
| 7 | +#[cfg(not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none"))))] |
10 | 8 | compile_error!("`wasm_js` backend can be enabled only for OS-less WASM targets!"); |
11 | 9 |
|
12 | | -use js_sys::{global, Function, Uint8Array}; |
| 10 | +use js_sys::{global, Uint8Array}; |
13 | 11 | use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue}; |
14 | 12 |
|
15 | 13 | // Size of our temporary Uint8Array buffer used with WebCrypto methods |
16 | 14 | // Maximum is 65536 bytes see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues |
17 | | -const WEB_CRYPTO_BUFFER_SIZE: u16 = 256; |
18 | | -// Node.js's crypto.randomFillSync requires the size to be less than 2**31. |
19 | | -const NODE_MAX_BUFFER_SIZE: usize = (1 << 31) - 1; |
20 | | - |
21 | | -enum RngSource { |
22 | | - Node(NodeCrypto), |
23 | | - Web(WebCrypto, Uint8Array), |
24 | | -} |
25 | | - |
26 | | -// JsValues are always per-thread, so we initialize RngSource for each thread. |
27 | | -// See: https://github.com/rustwasm/wasm-bindgen/pull/955 |
28 | | -thread_local!( |
29 | | - static RNG_SOURCE: Result<RngSource, Error> = getrandom_init(); |
30 | | -); |
| 15 | +const CRYPTO_BUFFER_SIZE: u16 = 256; |
31 | 16 |
|
32 | 17 | pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { |
33 | | - RNG_SOURCE.with(|result| { |
34 | | - let source = result.as_ref().map_err(|&e| e)?; |
35 | | - |
36 | | - match source { |
37 | | - RngSource::Node(n) => { |
38 | | - for chunk in dest.chunks_mut(NODE_MAX_BUFFER_SIZE) { |
39 | | - // SAFETY: chunk is never used directly, the memory is only |
40 | | - // modified via the Uint8Array view, which is passed |
41 | | - // directly to JavaScript. Also, crypto.randomFillSync does |
42 | | - // not resize the buffer. We know the length is less than |
43 | | - // u32::MAX because of the chunking above. |
44 | | - // Note that this uses the fact that JavaScript doesn't |
45 | | - // have a notion of "uninitialized memory", this is purely |
46 | | - // a Rust/C/C++ concept. |
47 | | - let res = n.random_fill_sync(unsafe { |
48 | | - Uint8Array::view_mut_raw(chunk.as_mut_ptr().cast::<u8>(), chunk.len()) |
49 | | - }); |
50 | | - if res.is_err() { |
51 | | - return Err(Error::NODE_RANDOM_FILL_SYNC); |
52 | | - } |
53 | | - } |
54 | | - } |
55 | | - RngSource::Web(crypto, buf) => { |
56 | | - // getRandomValues does not work with all types of WASM memory, |
57 | | - // so we initially write to browser memory to avoid exceptions. |
58 | | - for chunk in dest.chunks_mut(WEB_CRYPTO_BUFFER_SIZE.into()) { |
59 | | - let chunk_len: u32 = chunk |
60 | | - .len() |
61 | | - .try_into() |
62 | | - .expect("chunk length is bounded by WEB_CRYPTO_BUFFER_SIZE"); |
63 | | - // The chunk can be smaller than buf's length, so we call to |
64 | | - // JS to create a smaller view of buf without allocation. |
65 | | - let sub_buf = buf.subarray(0, chunk_len); |
66 | | - |
67 | | - if crypto.get_random_values(&sub_buf).is_err() { |
68 | | - return Err(Error::WEB_GET_RANDOM_VALUES); |
69 | | - } |
70 | | - |
71 | | - // SAFETY: `sub_buf`'s length is the same length as `chunk` |
72 | | - unsafe { sub_buf.raw_copy_to_ptr(chunk.as_mut_ptr().cast::<u8>()) }; |
73 | | - } |
74 | | - } |
75 | | - }; |
76 | | - Ok(()) |
77 | | - }) |
78 | | -} |
79 | | - |
80 | | -fn getrandom_init() -> Result<RngSource, Error> { |
81 | 18 | let global: Global = global().unchecked_into(); |
82 | | - |
83 | | - // Get the Web Crypto interface if we are in a browser, Web Worker, Deno, |
84 | | - // or another environment that supports the Web Cryptography API. This |
85 | | - // also allows for user-provided polyfills in unsupported environments. |
86 | 19 | let crypto = global.crypto(); |
87 | | - if crypto.is_object() { |
88 | | - let buf = Uint8Array::new_with_length(WEB_CRYPTO_BUFFER_SIZE.into()); |
89 | | - Ok(RngSource::Web(crypto, buf)) |
90 | | - } else if is_node(&global) { |
91 | | - // If module.require isn't a valid function, we are in an ES module. |
92 | | - let require_fn = Module::require_fn() |
93 | | - .and_then(JsCast::dyn_into::<Function>) |
94 | | - .map_err(|_| Error::NODE_ES_MODULE)?; |
95 | | - let n = require_fn |
96 | | - .call1(&global, &JsValue::from_str("crypto")) |
97 | | - .map_err(|_| Error::NODE_CRYPTO)? |
98 | | - .unchecked_into(); |
99 | | - Ok(RngSource::Node(n)) |
100 | | - } else { |
101 | | - Err(Error::WEB_CRYPTO) |
| 20 | + |
| 21 | + if !crypto.is_object() { |
| 22 | + return Err(Error::WEB_CRYPTO); |
102 | 23 | } |
103 | | -} |
104 | 24 |
|
105 | | -// Taken from https://www.npmjs.com/package/browser-or-node |
106 | | -fn is_node(global: &Global) -> bool { |
107 | | - let process = global.process(); |
108 | | - if process.is_object() { |
109 | | - let versions = process.versions(); |
110 | | - if versions.is_object() { |
111 | | - return versions.node().is_string(); |
| 25 | + // getRandomValues does not work with all types of WASM memory, |
| 26 | + // so we initially write to browser memory to avoid exceptions. |
| 27 | + let buf = Uint8Array::new_with_length(CRYPTO_BUFFER_SIZE.into()); |
| 28 | + for chunk in dest.chunks_mut(CRYPTO_BUFFER_SIZE.into()) { |
| 29 | + let chunk_len: u32 = chunk |
| 30 | + .len() |
| 31 | + .try_into() |
| 32 | + .expect("chunk length is bounded by CRYPTO_BUFFER_SIZE"); |
| 33 | + // The chunk can be smaller than buf's length, so we call to |
| 34 | + // JS to create a smaller view of buf without allocation. |
| 35 | + let sub_buf = buf.subarray(0, chunk_len); |
| 36 | + |
| 37 | + if crypto.get_random_values(&sub_buf).is_err() { |
| 38 | + return Err(Error::WEB_GET_RANDOM_VALUES); |
112 | 39 | } |
| 40 | + |
| 41 | + // SAFETY: `sub_buf`'s length is the same length as `chunk` |
| 42 | + unsafe { sub_buf.raw_copy_to_ptr(chunk.as_mut_ptr().cast::<u8>()) }; |
113 | 43 | } |
114 | | - false |
| 44 | + Ok(()) |
115 | 45 | } |
116 | 46 |
|
117 | 47 | #[wasm_bindgen] |
118 | 48 | extern "C" { |
119 | 49 | // Return type of js_sys::global() |
120 | 50 | type Global; |
121 | | - |
122 | 51 | // Web Crypto API: Crypto interface (https://www.w3.org/TR/WebCryptoAPI/) |
123 | | - type WebCrypto; |
124 | | - // Getters for the WebCrypto API |
| 52 | + type Crypto; |
| 53 | + // Getters for the Crypto API |
125 | 54 | #[wasm_bindgen(method, getter)] |
126 | | - fn crypto(this: &Global) -> WebCrypto; |
127 | | - #[wasm_bindgen(method, getter, js_name = msCrypto)] |
128 | | - fn ms_crypto(this: &Global) -> WebCrypto; |
| 55 | + fn crypto(this: &Global) -> Crypto; |
129 | 56 | // Crypto.getRandomValues() |
130 | 57 | #[wasm_bindgen(method, js_name = getRandomValues, catch)] |
131 | | - fn get_random_values(this: &WebCrypto, buf: &Uint8Array) -> Result<(), JsValue>; |
132 | | - |
133 | | - // Node JS crypto module (https://nodejs.org/api/crypto.html) |
134 | | - type NodeCrypto; |
135 | | - // crypto.randomFillSync() |
136 | | - #[wasm_bindgen(method, js_name = randomFillSync, catch)] |
137 | | - fn random_fill_sync(this: &NodeCrypto, buf: Uint8Array) -> Result<(), JsValue>; |
138 | | - |
139 | | - // Ideally, we would just use `fn require(s: &str)` here. However, doing |
140 | | - // this causes a Webpack warning. So we instead return the function itself |
141 | | - // and manually invoke it using call1. This also lets us to check that the |
142 | | - // function actually exists, allowing for better error messages. See: |
143 | | - // https://github.com/rust-random/getrandom/issues/224 |
144 | | - // https://github.com/rust-random/getrandom/issues/256 |
145 | | - type Module; |
146 | | - #[wasm_bindgen(getter, static_method_of = Module, js_class = module, js_name = require, catch)] |
147 | | - fn require_fn() -> Result<JsValue, JsValue>; |
148 | | - |
149 | | - // Node JS process Object (https://nodejs.org/api/process.html) |
150 | | - #[wasm_bindgen(method, getter)] |
151 | | - fn process(this: &Global) -> Process; |
152 | | - type Process; |
153 | | - #[wasm_bindgen(method, getter)] |
154 | | - fn versions(this: &Process) -> Versions; |
155 | | - type Versions; |
156 | | - #[wasm_bindgen(method, getter)] |
157 | | - fn node(this: &Versions) -> JsValue; |
| 58 | + fn get_random_values(this: &Crypto, buf: &Uint8Array) -> Result<(), JsValue>; |
158 | 59 | } |
0 commit comments