Skip to content

Commit 47227f7

Browse files
committed
chore: implement insecure fallback function
1 parent 7161e49 commit 47227f7

2 files changed

Lines changed: 11 additions & 28 deletions

File tree

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,28 @@
11
import { NativeModules } from 'react-native';
2-
import { fallbackRandomBase64String, BYTE_LENGTH } from './utils';
2+
import { getRandomBase64StringFallback, BYTE_LENGTH } from './utils';
33

44
export default function generateRandomBytes(): string {
55
const globalObject: any = global;
66

77
if (globalObject?.ExpoModules?.ExpoRandom) {
8-
const bytes = globalObject.ExpoModules.ExpoRandom.getRandomBase64String(BYTE_LENGTH);
9-
10-
return bytes;
8+
return globalObject.ExpoModules.ExpoRandom.getRandomBase64String(BYTE_LENGTH);
119
}
1210

1311
if (globalObject?.ExpoModules?.ExpoCrypto) {
14-
const bytes = globalObject.ExpoModules.ExpoCrypto.getRandomBase64String(BYTE_LENGTH);
15-
16-
return bytes;
12+
return globalObject.ExpoModules.ExpoCrypto.getRandomBase64String(BYTE_LENGTH);
1713
}
1814

1915
if (NativeModules.ExpoRandom) {
20-
const bytes = NativeModules.ExpoRandom.getRandomBase64String(BYTE_LENGTH);
21-
22-
return bytes;
16+
return NativeModules.ExpoRandom.getRandomBase64String(BYTE_LENGTH);
2317
}
2418

2519
if (NativeModules.ExpoCrypto) {
26-
const bytes = NativeModules.ExpoCrypto.getRandomBase64String(BYTE_LENGTH);
27-
28-
return bytes;
20+
return NativeModules.ExpoCrypto.getRandomBase64String(BYTE_LENGTH);
2921
}
3022

3123
if (globalObject?.PkceChallenge) {
32-
const bytes = globalObject.PkceChallenge.getRandomBase64String(BYTE_LENGTH);
33-
34-
return bytes;
24+
return globalObject.PkceChallenge.getRandomBase64String(BYTE_LENGTH);
3525
}
3626

37-
const bytes = fallbackRandomBase64String(BYTE_LENGTH);
38-
39-
return bytes;
27+
return getRandomBase64StringFallback(BYTE_LENGTH);
4028
}

src/utils.ts

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,16 +25,11 @@ export function verifyChallenge(verifier: string, challenge: string) {
2525
return correctChallenge === challenge;
2626
}
2727

28-
export function fallbackRandomBase64String(byteLength: number) {
29-
const u8 = new Uint8Array(byteLength);
30-
let r: number;
28+
export function getRandomBase64StringFallback(byteLength: number) {
29+
console.warn('Native getRandomValues function not found. Falling back to insecure Math.random.');
3130

32-
u8.map((_, i) => {
33-
if ((i & 0x03) === 0 || r === undefined) r = Math.random() * 0x100000000;
34-
return (r >>> ((i & 0x03) << 3)) & 0xff;
35-
});
36-
37-
const bytes = base64.encode(String.fromCharCode(...new Uint8Array(u8)));
31+
const buffer = new Uint8Array(byteLength).map(() => Math.floor(Math.random() * 256));
32+
const bytes = base64.encode(String.fromCharCode(...new Uint8Array(buffer)));
3833

3934
return bytes;
4035
}

0 commit comments

Comments
 (0)