Skip to content

Commit

Permalink
fix: support webworkers
Browse files Browse the repository at this point in the history
Edge does not appear to make a global `crypto` variable available in
WebWorkers however the WebCrypto seems to be exposed on the `self`
variable, see sodium-friends/sodium-javascript#8

Since window.self also points to the window object in browsers checking
self should work both, in the browser as well as in WebWorkers.

Fixes #392
  • Loading branch information
ctavan committed Mar 2, 2020
1 parent bb2c8e4 commit 713053f
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/rng-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@

// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
// find the complete implementation of crypto (msCrypto) on IE11.
// Use self in order to support WebWorkers as well, see
// https://developer.mozilla.org/en-US/docs/Web/API/Window/self
var getRandomValues =
(typeof crypto != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
(typeof msCrypto != 'undefined' &&
typeof window.msCrypto.getRandomValues == 'function' &&
msCrypto.getRandomValues.bind(msCrypto));
typeof self !== 'undefined' &&
((typeof self.crypto !== 'undefined' &&
self.crypto.getRandomValues &&
self.crypto.getRandomValues.bind(self.crypto)) ||
(typeof self.msCrypto !== 'undefined' &&
self.msCrypto.getRandomValues &&
self.msCrypto.getRandomValues.bind(self.msCrypto)));

var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
export default function rng() {
Expand Down

2 comments on commit 713053f

@broofa
Copy link
Member

@broofa broofa commented on 713053f Mar 2, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this actually fix the problem? Edge 18 provides self in webworkers, yes, but the self.crypto and self.msCrypto are undefined... at least, from what I can see.

image

@ctavan
Copy link
Member Author

@ctavan ctavan commented on 713053f Mar 2, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was on a wrong path here, mislead by this issue https://github.com/sodium-friends/sodium-javascript/issues/8…

It fixes nothing and I have removed this branch again, see #392 (comment).

Please sign in to comment.