Skip to content

Commit

Permalink
Improvements to getRandom
Browse files Browse the repository at this point in the history
  • Loading branch information
corrideat committed Aug 9, 2023
1 parent 8185a03 commit 5c8dda3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
12 changes: 9 additions & 3 deletions src/untrusted/lib/getRandomSecret.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* PERFORMANCE OF THIS SOFTWARE.
*/

import { S, aJoin, aMap, cGRC, mR, sFromCharCode, u8Alloc } from './utils.js';
import { aJoin, aMap, cGRC, mR, sFromCharCode, u8Alloc } from './utils.js';

/**
* Converts a given buffer into a Base16 string (using a custom logic)
Expand All @@ -34,7 +34,7 @@ import { S, aJoin, aMap, cGRC, mR, sFromCharCode, u8Alloc } from './utils.js';
* @param buffer - The buffer that will be converted to a string
* @returns The string representation of the buffer using the custom logic.
*/
const bufferToHex = (buffer: Uint8Array) =>
const bufferToHex = (buffer: Uint8Array | number[]) =>
aJoin(
aMap(buffer as unknown as number[], (v) =>
sFromCharCode(
Expand All @@ -59,6 +59,12 @@ const getRandomSecret = cGRC
bufferToHex(
(cGRC as unknown as Crypto['getRandomValues'])(u8Alloc(16)),
)
: () => S(mR());
: () =>
bufferToHex(
aMap(
u8Alloc(16) as unknown as number[],
() => (mR() * 256) | 0,
),
);

export default getRandomSecret;
7 changes: 3 additions & 4 deletions src/untrusted/lib/nodejsLoadWebcrypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* PERFORMANCE OF THIS SOFTWARE.
*/

// Node.js version 18 and lower don't have globalThis.webcrypto defined
// Node.js version 18 and lower don't have globalThis.crypto defined
// by default
if (
typeof process === 'object' &&
Expand All @@ -22,9 +22,8 @@ if (
!Reflect.has(globalThis, 'crypto') &&
typeof require === 'function'
) {
const webcrypto = Reflect.apply(require, null, ['node:crypto'])[
'webcrypto'
];
// eslint-disable-next-line @typescript-eslint/no-var-requires
const webcrypto = require('node:crypto')['webcrypto'];
if (webcrypto) {
Object.defineProperty(globalThis, 'crypto', {
['enumerable']: true,
Expand Down

0 comments on commit 5c8dda3

Please sign in to comment.