Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ wasi = "0.10"
stdweb = { version = "0.4.18", default-features = false, optional = true }
[target.'cfg(all(target_arch = "wasm32", target_os = "unknown", not(cargo_web)))'.dependencies]
wasm-bindgen = { version = "0.2.62", default-features = false, optional = true }
js-sys = { version = "0.3", optional = true }
[target.'cfg(all(target_arch = "wasm32", target_os = "unknown", not(cargo_web)))'.dev-dependencies]
wasm-bindgen-test = "0.3.18"

Expand All @@ -40,7 +41,7 @@ std = []
# Feature to enable fallback RDRAND-based implementation on x86/x86_64
rdrand = []
# Feature to enable JavaScript bindings on wasm32-unknown-unknown
js = ["stdweb", "wasm-bindgen"]
js = ["stdweb", "wasm-bindgen", "js-sys"]
# Feature to enable custom RNG implementations
custom = []
# Unstable feature to support being a libstd dependency
Expand Down
31 changes: 19 additions & 12 deletions src/wasm-bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@ use crate::Error;
extern crate std;
use std::thread_local;

use js_sys::Uint8Array;
use wasm_bindgen::prelude::*;

// Maximum is 65536 bytes see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
const BROWSER_CRYPTO_BUFFER_SIZE: usize = 256;

enum RngSource {
Node(NodeCrypto),
Browser(BrowserCrypto),
Browser(BrowserCrypto, Uint8Array),
}

// JsValues are always per-thread, so we initialize RngSource for each thread.
Expand All @@ -33,17 +37,18 @@ pub(crate) fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
return Err(Error::NODE_RANDOM_FILL_SYNC);
}
}
RngSource::Browser(n) => {
// see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
//
// where it says:
//
// > A QuotaExceededError DOMException is thrown if the
// > requested length is greater than 65536 bytes.
for chunk in dest.chunks_mut(65536) {
if n.get_random_values(chunk).is_err() {
RngSource::Browser(crypto, buf) => {
// getRandomValues does not work with all types of WASM memory,
// so we initially write to browser memory to avoid exceptions.
for chunk in dest.chunks_mut(BROWSER_CRYPTO_BUFFER_SIZE) {
Comment thread
josephlr marked this conversation as resolved.
// The chunk can be smaller than buf's length, so we call to
// JS to create a smaller view of buf without allocation.
let sub_buf = buf.subarray(0, chunk.len() as u32);

if crypto.get_random_values(&sub_buf).is_err() {
return Err(Error::WEB_GET_RANDOM_VALUES);
}
sub_buf.copy_to(chunk);
}
}
};
Expand All @@ -63,7 +68,9 @@ fn getrandom_init() -> Result<RngSource, Error> {
(_, crypto) if !crypto.is_undefined() => crypto,
_ => return Err(Error::WEB_CRYPTO),
};
return Ok(RngSource::Browser(crypto));

let buf = Uint8Array::new_with_length(BROWSER_CRYPTO_BUFFER_SIZE as u32);
return Ok(RngSource::Browser(crypto, buf));
}

let crypto = MODULE.require("crypto").map_err(|_| Error::NODE_CRYPTO)?;
Expand All @@ -84,7 +91,7 @@ extern "C" {

type BrowserCrypto;
#[wasm_bindgen(method, js_name = getRandomValues, catch)]
fn get_random_values(me: &BrowserCrypto, buf: &mut [u8]) -> Result<(), JsValue>;
fn get_random_values(me: &BrowserCrypto, buf: &Uint8Array) -> Result<(), JsValue>;

#[wasm_bindgen(js_name = module)]
static MODULE: NodeModule;
Expand Down