2626 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2727 */
2828
29+ // The Node.js crypto module is used as a fallback for the Web Crypto API. When
30+ // building for the browser, inclusion of the crypto module should be disabled,
31+ // which the package hints at in its package.json for bundlers that support it.
32+ import nodeCrypto from "crypto" ;
33+
2934/**
3035 * The random implementation to use as a fallback.
3136 * @type {?function(number):!Array.<number> }
@@ -41,18 +46,16 @@ var randomFallback = null;
4146 * @throws {Error } If no random implementation is available
4247 * @inner
4348 */
44- function random ( len ) {
45- // Web Crypto API
49+ function randomBytes ( len ) {
50+ // Web Crypto API. Globally available in the browser and in Node.js >=23.
4651 try {
4752 return crypto . getRandomValues ( new Uint8Array ( len ) ) ;
4853 } catch { }
49- // Node.js crypto
50- if ( typeof require === "function" ) {
51- try {
52- return require ( "crypto" ) . randomBytes ( len ) ;
53- } catch { }
54- }
55- // Fallback
54+ // Node.js crypto module for non-browser environments.
55+ try {
56+ return nodeCrypto . randomBytes ( len ) ;
57+ } catch { }
58+ // Custom fallback specified with `setRandomFallback`.
5659 if ( ! randomFallback ) {
5760 throw Error (
5861 "Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative" ,
@@ -97,7 +100,7 @@ export function genSaltSync(rounds, seed_length) {
97100 if ( rounds < 10 ) salt . push ( "0" ) ;
98101 salt . push ( rounds . toString ( ) ) ;
99102 salt . push ( "$" ) ;
100- salt . push ( base64_encode ( random ( BCRYPT_SALT_LEN ) , BCRYPT_SALT_LEN ) ) ; // May throw
103+ salt . push ( base64_encode ( randomBytes ( BCRYPT_SALT_LEN ) , BCRYPT_SALT_LEN ) ) ; // May throw
101104 return salt . join ( "" ) ;
102105}
103106
0 commit comments