Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Retrieve crypto from global instead of Window in WASM #1508

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,8 @@ once_cell = { version = "1.8.0", default-features = false, features=["std"] }

[target.'cfg(all(target_arch = "wasm32", target_vendor = "unknown", target_os = "unknown", target_env = ""))'.dependencies]
web-sys = { version = "0.3.51", default-features = false, features = ["Crypto", "Window"], optional = true }
wasm-bindgen = { version = "0.2.80" }
js-sys = { version = "0.3.51" }

[target.'cfg(target_os = "windows")'.dependencies]
winapi = { version = "0.3.9", default-features = false, features = ["ntsecapi", "wtypesbase", "processthreadsapi"] }
Expand Down
21 changes: 17 additions & 4 deletions src/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,20 @@ mod sysrand_chunk {
))]
mod sysrand_chunk {
use crate::error;
use js_sys::Reflect;
use wasm_bindgen::{JsValue, JsCast};
use web_sys::Crypto;

/**
* Gets a handle to Crypto in both normal and worker environments. Based on
* the discussion in https://github.com/rustwasm/wasm-bindgen/issues/2148
* and the approach taken here: https://github.com/devashishdxt/rexie/commit/8637e4ebc2d2dfc6b33cd60dc85b99e46d6afa96
*/
fn get_crypto() -> Result<Crypto, error::Unspecified> {
Reflect::get(&js_sys::global(), &JsValue::from("crypto"))
.map_err(|_| error::Unspecified)?
.dyn_into::<Crypto>().map_err(|_| error::Unspecified)
}

pub fn chunk(mut dest: &mut [u8]) -> Result<usize, error::Unspecified> {
// This limit is specified in
Expand All @@ -247,10 +261,9 @@ mod sysrand_chunk {
dest = &mut dest[..MAX_LEN];
};

let _ = web_sys::window()
.ok_or(error::Unspecified)?
.crypto()
.map_err(|_| error::Unspecified)?
let crypto = get_crypto()?;

let _ = crypto
.get_random_values_with_u8_array(dest)
.map_err(|_| error::Unspecified)?;

Expand Down