-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.js
More file actions
47 lines (41 loc) · 1.17 KB
/
index.js
File metadata and controls
47 lines (41 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const nodeCrypto = require('node:crypto');
const window = require('window-or-global');
/**
* @template {ArrayBufferView<ArrayBuffer>} T
* @param {T} buf
* @returns {T}
*/
function getRandomValues(buf) {
if (window.crypto?.getRandomValues) {
return window.crypto.getRandomValues(buf);
}
if (
typeof window.msCrypto === 'object' &&
typeof window.msCrypto.getRandomValues === 'function'
) {
return window.msCrypto.getRandomValues(buf);
}
if (nodeCrypto.randomBytes) {
if (!(buf instanceof Uint8Array)) {
throw new TypeError('expected Uint8Array');
}
if (buf.length > 65_536) {
const e = new Error(
"Failed to execute 'getRandomValues' on 'Crypto': The " +
"ArrayBufferView's byte length (" +
buf.length +
') exceeds the ' +
'number of bytes of entropy available via this API (65536).'
);
// @ts-expect-error
e.code = 22;
e.name = 'QuotaExceededError';
throw e;
}
const bytes = nodeCrypto.randomBytes(buf.length);
buf.set(bytes);
return buf;
}
throw new Error('No secure random number generator available.');
}
module.exports = getRandomValues;