Skip to content

Commit cfdad53

Browse files
authored
Merge pull request #284 from rust-random/webcrypto
Rework JS feature detection
2 parents d3aa089 + 9962c70 commit cfdad53

File tree

3 files changed

+79
-45
lines changed

3 files changed

+79
-45
lines changed

src/error.rs

+11-7
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,19 @@ impl Error {
4343
pub const FAILED_RDRAND: Error = internal_error(5);
4444
/// RDRAND instruction unsupported on this target.
4545
pub const NO_RDRAND: Error = internal_error(6);
46-
/// The browser does not have support for `self.crypto`.
46+
/// The environment does not support the Web Crypto API.
4747
pub const WEB_CRYPTO: Error = internal_error(7);
48-
/// The browser does not have support for `crypto.getRandomValues`.
48+
/// Calling Web Crypto API `crypto.getRandomValues` failed.
4949
pub const WEB_GET_RANDOM_VALUES: Error = internal_error(8);
5050
/// On VxWorks, call to `randSecure` failed (random number generator is not yet initialized).
5151
pub const VXWORKS_RAND_SECURE: Error = internal_error(11);
52-
/// NodeJS does not have support for the `crypto` module.
52+
/// Node.js does not have the `crypto` CommonJS module.
5353
pub const NODE_CRYPTO: Error = internal_error(12);
54-
/// NodeJS does not have support for `crypto.randomFillSync`.
54+
/// Calling Node.js function `crypto.randomFillSync` failed.
5555
pub const NODE_RANDOM_FILL_SYNC: Error = internal_error(13);
56+
/// Called from an ES module on Node.js. This is unsupported, see:
57+
/// <https://docs.rs/getrandom#nodejs-es-module-support>.
58+
pub const NODE_ES_MODULE: Error = internal_error(14);
5659

5760
/// Codes below this point represent OS Errors (i.e. positive i32 values).
5861
/// Codes at or above this point, but below [`Error::CUSTOM_START`] are
@@ -166,10 +169,11 @@ fn internal_desc(error: Error) -> Option<&'static str> {
166169
Error::FAILED_RDRAND => Some("RDRAND: failed multiple times: CPU issue likely"),
167170
Error::NO_RDRAND => Some("RDRAND: instruction not supported"),
168171
Error::WEB_CRYPTO => Some("Web Crypto API is unavailable"),
169-
Error::WEB_GET_RANDOM_VALUES => Some("Web API crypto.getRandomValues is unavailable"),
172+
Error::WEB_GET_RANDOM_VALUES => Some("Calling Web API crypto.getRandomValues failed"),
170173
Error::VXWORKS_RAND_SECURE => Some("randSecure: VxWorks RNG module is not initialized"),
171-
Error::NODE_CRYPTO => Some("Node.js crypto module is unavailable"),
172-
Error::NODE_RANDOM_FILL_SYNC => Some("Node.js API crypto.randomFillSync is unavailable"),
174+
Error::NODE_CRYPTO => Some("Node.js crypto CommonJS module is unavailable"),
175+
Error::NODE_RANDOM_FILL_SYNC => Some("Calling Node.js API crypto.randomFillSync failed"),
176+
Error::NODE_ES_MODULE => Some("Node.js ES modules are not directly supported, see https://docs.rs/getrandom#nodejs-es-module-support"),
173177
_ => None,
174178
}
175179
}

src/js.rs

+51-36
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,16 @@ use crate::Error;
1010
extern crate std;
1111
use std::thread_local;
1212

13-
use js_sys::{global, Uint8Array};
13+
use js_sys::{global, Function, Uint8Array};
1414
use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
1515

16+
// Size of our temporary Uint8Array buffer used with WebCrypto methods
1617
// Maximum is 65536 bytes see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
17-
const BROWSER_CRYPTO_BUFFER_SIZE: usize = 256;
18+
const WEB_CRYPTO_BUFFER_SIZE: usize = 256;
1819

1920
enum RngSource {
2021
Node(NodeCrypto),
21-
Browser(BrowserCrypto, Uint8Array),
22+
Web(WebCrypto, Uint8Array),
2223
}
2324

2425
// JsValues are always per-thread, so we initialize RngSource for each thread.
@@ -37,10 +38,10 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
3738
return Err(Error::NODE_RANDOM_FILL_SYNC);
3839
}
3940
}
40-
RngSource::Browser(crypto, buf) => {
41+
RngSource::Web(crypto, buf) => {
4142
// getRandomValues does not work with all types of WASM memory,
4243
// so we initially write to browser memory to avoid exceptions.
43-
for chunk in dest.chunks_mut(BROWSER_CRYPTO_BUFFER_SIZE) {
44+
for chunk in dest.chunks_mut(WEB_CRYPTO_BUFFER_SIZE) {
4445
// The chunk can be smaller than buf's length, so we call to
4546
// JS to create a smaller view of buf without allocation.
4647
let sub_buf = buf.subarray(0, chunk.len() as u32);
@@ -58,25 +59,33 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
5859

5960
fn getrandom_init() -> Result<RngSource, Error> {
6061
let global: Global = global().unchecked_into();
61-
if is_node(&global) {
62-
let crypto = NODE_MODULE
63-
.require("crypto")
64-
.map_err(|_| Error::NODE_CRYPTO)?;
65-
return Ok(RngSource::Node(crypto));
66-
}
6762

68-
// Assume we are in some Web environment (browser or web worker). We get
69-
// `self.crypto` (called `msCrypto` on IE), so we can call
70-
// `crypto.getRandomValues`. If `crypto` isn't defined, we assume that
71-
// we are in an older web browser and the OS RNG isn't available.
72-
let crypto = match (global.crypto(), global.ms_crypto()) {
73-
(c, _) if c.is_object() => c,
74-
(_, c) if c.is_object() => c,
75-
_ => return Err(Error::WEB_CRYPTO),
63+
// Get the Web Crypto interface if we are in a browser, Web Worker, Deno,
64+
// or another environment that supports the Web Cryptography API. This
65+
// also allows for user-provided polyfills in unsupported environments.
66+
let crypto = match global.crypto() {
67+
// Standard Web Crypto interface
68+
c if c.is_object() => c,
69+
// Node.js CommonJS Crypto module
70+
_ if is_node(&global) => {
71+
// If module.require isn't a valid function, we are in an ES module.
72+
match Module::require_fn().and_then(JsCast::dyn_into::<Function>) {
73+
Ok(require_fn) => match require_fn.call1(&global, &JsValue::from_str("crypto")) {
74+
Ok(n) => return Ok(RngSource::Node(n.unchecked_into())),
75+
Err(_) => return Err(Error::NODE_CRYPTO),
76+
},
77+
Err(_) => return Err(Error::NODE_ES_MODULE),
78+
}
79+
}
80+
// IE 11 Workaround
81+
_ => match global.ms_crypto() {
82+
c if c.is_object() => c,
83+
_ => return Err(Error::WEB_CRYPTO),
84+
},
7685
};
7786

78-
let buf = Uint8Array::new_with_length(BROWSER_CRYPTO_BUFFER_SIZE as u32);
79-
Ok(RngSource::Browser(crypto, buf))
87+
let buf = Uint8Array::new_with_length(WEB_CRYPTO_BUFFER_SIZE as u32);
88+
Ok(RngSource::Web(crypto, buf))
8089
}
8190

8291
// Taken from https://www.npmjs.com/package/browser-or-node
@@ -93,30 +102,36 @@ fn is_node(global: &Global) -> bool {
93102

94103
#[wasm_bindgen]
95104
extern "C" {
96-
type Global; // Return type of js_sys::global()
105+
// Return type of js_sys::global()
106+
type Global;
97107

98-
// Web Crypto API (https://www.w3.org/TR/WebCryptoAPI/)
99-
#[wasm_bindgen(method, getter, js_name = "msCrypto")]
100-
fn ms_crypto(this: &Global) -> BrowserCrypto;
108+
// Web Crypto API: Crypto interface (https://www.w3.org/TR/WebCryptoAPI/)
109+
type WebCrypto;
110+
// Getters for the WebCrypto API
101111
#[wasm_bindgen(method, getter)]
102-
fn crypto(this: &Global) -> BrowserCrypto;
103-
type BrowserCrypto;
112+
fn crypto(this: &Global) -> WebCrypto;
113+
#[wasm_bindgen(method, getter, js_name = msCrypto)]
114+
fn ms_crypto(this: &Global) -> WebCrypto;
115+
// Crypto.getRandomValues()
104116
#[wasm_bindgen(method, js_name = getRandomValues, catch)]
105-
fn get_random_values(this: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>;
117+
fn get_random_values(this: &WebCrypto, buf: &Uint8Array) -> Result<(), JsValue>;
106118

107-
// We use a "module" object here instead of just annotating require() with
108-
// js_name = "module.require", so that Webpack doesn't give a warning. See:
109-
// https://github.com/rust-random/getrandom/issues/224
110-
type NodeModule;
111-
#[wasm_bindgen(js_name = module)]
112-
static NODE_MODULE: NodeModule;
113119
// Node JS crypto module (https://nodejs.org/api/crypto.html)
114-
#[wasm_bindgen(method, catch)]
115-
fn require(this: &NodeModule, s: &str) -> Result<NodeCrypto, JsValue>;
116120
type NodeCrypto;
121+
// crypto.randomFillSync()
117122
#[wasm_bindgen(method, js_name = randomFillSync, catch)]
118123
fn random_fill_sync(this: &NodeCrypto, buf: &mut [u8]) -> Result<(), JsValue>;
119124

125+
// Ideally, we would just use `fn require(s: &str)` here. However, doing
126+
// this causes a Webpack warning. So we instead return the function itself
127+
// and manually invoke it using call1. This also lets us to check that the
128+
// function actually exists, allowing for better error messages. See:
129+
// https://github.com/rust-random/getrandom/issues/224
130+
// https://github.com/rust-random/getrandom/issues/256
131+
type Module;
132+
#[wasm_bindgen(getter, static_method_of = Module, js_class = module, js_name = require, catch)]
133+
fn require_fn() -> Result<JsValue, JsValue>;
134+
120135
// Node JS process Object (https://nodejs.org/api/process.html)
121136
#[wasm_bindgen(method, getter)]
122137
fn process(this: &Global) -> Process;

src/lib.rs

+17-2
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
//! | Emscripten | `*‑emscripten` | `/dev/random` (identical to `/dev/urandom`)
3232
//! | WASI | `wasm32‑wasi` | [`random_get`]
3333
//! | Web Browser | `wasm32‑*‑unknown` | [`Crypto.getRandomValues`], see [WebAssembly support]
34-
//! | Node.js | `wasm32‑*‑unknown` | [`crypto.randomBytes`], see [WebAssembly support]
34+
//! | Node.js | `wasm32‑*‑unknown` | [`crypto.randomFillSync`], see [WebAssembly support]
3535
//! | SOLID | `*-kmc-solid_*` | `SOLID_RNG_SampleRandomBytes`
3636
//! | Nintendo 3DS | `armv6k-nintendo-3ds` | [`getrandom`][1]
3737
//!
@@ -91,6 +91,18 @@
9191
//!
9292
//! This feature has no effect on targets other than `wasm32-unknown-unknown`.
9393
//!
94+
//! #### Node.js ES module support
95+
//!
96+
//! Node.js supports both [CommonJS modules] and [ES modules]. Due to
97+
//! limitations in wasm-bindgen's [`module`] support, we cannot directly
98+
//! support ES Modules running on Node.js. However, on Node v15 and later, the
99+
//! module author can add a simple shim to support the Web Cryptography API:
100+
//! ```js
101+
//! import { webcrypto } from 'node:crypto'
102+
//! globalThis.crypto = webcrypto
103+
//! ```
104+
//! This crate will then use the provided `webcrypto` implementation.
105+
//!
94106
//! ### Custom implementations
95107
//!
96108
//! The [`register_custom_getrandom!`] macro allows a user to mark their own
@@ -154,11 +166,14 @@
154166
//! [`RDRAND`]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide
155167
//! [`SecRandomCopyBytes`]: https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc
156168
//! [`cprng_draw`]: https://fuchsia.dev/fuchsia-src/zircon/syscalls/cprng_draw
157-
//! [`crypto.randomBytes`]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback
169+
//! [`crypto.randomFillSync`]: https://nodejs.org/api/crypto.html#cryptorandomfillsyncbuffer-offset-size
158170
//! [`esp_fill_random`]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t
159171
//! [`random_get`]: https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#-random_getbuf-pointeru8-buf_len-size---errno
160172
//! [WebAssembly support]: #webassembly-support
161173
//! [`wasm-bindgen`]: https://github.com/rustwasm/wasm-bindgen
174+
//! [`module`]: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-js-imports/module.html
175+
//! [CommonJS modules]: https://nodejs.org/api/modules.html
176+
//! [ES modules]: https://nodejs.org/api/esm.html
162177
163178
#![doc(
164179
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",

0 commit comments

Comments
 (0)