Skip to content

Commit

Permalink
feat: remove insecure fallback random number generator
Browse files Browse the repository at this point in the history
BREAKING CHANGE: Remove builtin support for insecure random number
generators in the browser. Users who want that will have to supply their
own random number generator function.

Fixes #173.
  • Loading branch information
ctavan committed Jan 20, 2020
1 parent d4e31d4 commit 8f71d27
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 40 deletions.
35 changes: 8 additions & 27 deletions src/rng-browser.js
Expand Up @@ -11,31 +11,12 @@ var getRandomValues =
typeof window.msCrypto.getRandomValues == 'function' &&
msCrypto.getRandomValues.bind(msCrypto));

let rng;

if (getRandomValues) {
// WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef

rng = function whatwgRNG() {
getRandomValues(rnds8);
return rnds8;
};
} else {
// Math.random()-based (RNG)
//
// If all else fails, use Math.random(). It's fast, but is of unspecified
// quality.
var rnds = new Array(16);

rng = function mathRNG() {
for (var i = 0, r; i < 16; i++) {
if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
rnds[i] = (r >>> ((i & 0x03) << 3)) & 0xff;
}

return rnds;
};
var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
export default function rng() {
if (!getRandomValues) {
throw new Error(
'uuid: This browser does not seem to support crypto.getRandomValues(). If you need to support this browser, please provide a custom random number generator through options.rng',
);
}
return getRandomValues(rnds8);
}

export default rng;
2 changes: 1 addition & 1 deletion src/rng.js
@@ -1,5 +1,5 @@
import crypto from 'crypto';

export default function nodeRNG() {
export default function rng() {
return crypto.randomBytes(16);
}
6 changes: 6 additions & 0 deletions test/browser/ie.test.js
Expand Up @@ -14,4 +14,10 @@ browserTest('ie', 9003, [
os: 'Windows',
os_version: '7',
},
{
browserName: 'IE',
browser_version: '8.0',
os: 'Windows',
os_version: '7',
},
]);
17 changes: 5 additions & 12 deletions test/unit/unit.test.js
Expand Up @@ -10,9 +10,7 @@ import v3 from '../../src/v3.js';
import v5 from '../../src/v5.js';

describe('rng', () => {
test('nodeRNG', () => {
assert.equal(rng.name, 'nodeRNG');

test('Node.js RNG', () => {
var bytes = rng();
assert.equal(bytes.length, 16);

Expand All @@ -21,15 +19,10 @@ describe('rng', () => {
}
});

test('mathRNG', () => {
assert.equal(rngBrowser.name, 'mathRNG');

var bytes = rng();
assert.equal(bytes.length, 16);

for (var i = 0; i < bytes.length; i++) {
assert.equal(typeof bytes[i], 'number');
}
test('Browser without crypto.getRandomValues()', () => {
assert.throws(() => {
rngBrowser();
});
});

// Test of whatwgRNG missing for now since with esmodules we can no longer manipulate the
Expand Down

0 comments on commit 8f71d27

Please sign in to comment.