Skip to content

Commit 053b5ac

Browse files
🎉 Fallback to Math.random when debugger is attached (#8)
Normally this calls a synchronous native method, which is more secure and of course the point of this library, but calling synchronous native methods is not supported when the debugger is attached. Co-authored-by: Linus Unnebäck <linus@folkdatorn.se>
1 parent 7a2db1e commit 053b5ac

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

index.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,21 @@ const base64Decode = require('fast-base64-decode')
44
class TypeMismatchError extends Error {}
55
class QuotaExceededError extends Error {}
66

7+
let warned = false
8+
function insecureRandomValues (array) {
9+
if (!warned) {
10+
console.warn('Using an insecure random number generator, this should only happen when running in a debugger without support for crypto.getRandomValues')
11+
warned = true
12+
}
13+
14+
for (let i = 0, r; i < array.length; i++) {
15+
if ((i & 0x03) === 0) r = Math.random() * 0x100000000
16+
array[i] = (r >>> ((i & 0x03) << 3)) & 0xff
17+
}
18+
19+
return array
20+
}
21+
722
/**
823
* @param {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Uint8ClampedArray} array
924
*/
@@ -16,6 +31,15 @@ function getRandomValues (array) {
1631
throw new QuotaExceededError('Can only request a maximum of 65536 bytes')
1732
}
1833

34+
// Calling RNGetRandomValues.getRandomBase64 in debug mode leads to the error
35+
// "Calling synchronous methods on native modules is not supported in Chrome".
36+
// So in that specific case we fall back to just using Math.random.
37+
if (__DEV__) {
38+
if (typeof global.nativeCallSyncHook === 'undefined') {
39+
return insecureRandomValues(array)
40+
}
41+
}
42+
1943
base64Decode(RNGetRandomValues.getRandomBase64(array.byteLength), new Uint8Array(array.buffer, array.byteOffset, array.byteLength))
2044

2145
return array

0 commit comments

Comments
 (0)