Skip to content

Commit ae6c15a

Browse files
Potential fix for code scanning alert no. 92: Insecure randomness
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> Signed-off-by: Dargon789 <64915515+Dargon789@users.noreply.github.com>
1 parent ed245c2 commit ae6c15a

1 file changed

Lines changed: 36 additions & 1 deletion

File tree

  • wagmi-project/packages/core/src/utils

wagmi-project/packages/core/src/utils/uid.ts

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,47 @@ const size = 256
22
let index = size
33
let buffer: string
44

5+
function getRandomBytes(byteLength: number): Uint8Array {
6+
if (
7+
typeof globalThis !== 'undefined' &&
8+
globalThis.crypto &&
9+
typeof globalThis.crypto.getRandomValues === 'function'
10+
) {
11+
const array = new Uint8Array(byteLength)
12+
globalThis.crypto.getRandomValues(array)
13+
return array
14+
}
15+
16+
// Fallback for Node.js environments that expose `require('crypto')`.
17+
try {
18+
// eslint-disable-next-line @typescript-eslint/no-var-requires
19+
const nodeCrypto = require('crypto') as {
20+
randomBytes: (size: number) => { readonly [n: number]: number; length: number }
21+
}
22+
const buf = nodeCrypto.randomBytes(byteLength)
23+
const array = new Uint8Array(byteLength)
24+
for (let i = 0; i < byteLength; i++) array[i] = buf[i]
25+
return array
26+
} catch {
27+
// ignore and fall through to non-cryptographic fallback
28+
}
29+
30+
// Last-resort, non-cryptographic fallback (used only if no crypto APIs are available).
31+
const array = new Uint8Array(byteLength)
32+
for (let i = 0; i < byteLength; i++) {
33+
array[i] = (Math.random() * 256) | 0
34+
}
35+
return array
36+
}
37+
538
export function uid(length = 11) {
639
if (!buffer || index + length > size * 2) {
740
buffer = ''
841
index = 0
42+
const randomBytes = getRandomBytes(size)
943
for (let i = 0; i < size; i++) {
10-
buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1)
44+
const byte = randomBytes[i]
45+
buffer += byte.toString(16).padStart(2, '0')
1146
}
1247
}
1348
return buffer.substring(index, index++ + length)

0 commit comments

Comments
 (0)