Skip to content

fix(utils): Support crypto.getRandomValues in old Chromium versions #9251

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

Merged
Show file tree
Hide file tree
Changes from all 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
10 changes: 9 additions & 1 deletion packages/utils/src/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,15 @@ export function uuid4(): string {
return crypto.randomUUID().replace(/-/g, '');
}
if (crypto && crypto.getRandomValues) {
getRandomByte = () => crypto.getRandomValues(new Uint8Array(1))[0];
getRandomByte = () => {
// crypto.getRandomValues might return undefined instead of the typed array
// in old Chromium versions (e.g. 23.0.1235.0 (151422))
// However, `typedArray` is still filled in-place.
// @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray
const typedArray = new Uint8Array(1);
crypto.getRandomValues(typedArray);
return typedArray[0];
};
}
} catch (_) {
// some runtimes can crash invoking crypto
Expand Down
19 changes: 19 additions & 0 deletions packages/utils/test/misc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,25 @@ describe('uuid4 generation', () => {
expect(uuid4()).toMatch(uuid4Regex);
}
});

// Corner case related to crypto.getRandomValues being only
// semi-implemented (e.g. Chromium 23.0.1235.0 (151422))
it('returns valid uuid v4 even if crypto.getRandomValues does not return a typed array', () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const cryptoMod = require('crypto');

const getRandomValues = (typedArray: Uint8Array) => {
if (cryptoMod.getRandomValues) {
cryptoMod.getRandomValues(typedArray);
}
};

(global as any).crypto = { getRandomValues };

for (let index = 0; index < 1_000; index++) {
expect(uuid4()).toMatch(uuid4Regex);
}
});
});

describe('arrayify()', () => {
Expand Down