Skip to content

Commit 574d690

Browse files
committed
Adapt crypto module usage for ESM environments
1 parent e746547 commit 574d690

File tree

2 files changed

+16
-10
lines changed

2 files changed

+16
-10
lines changed

index.js

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@
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

package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@
6363
"LICENSE",
6464
"README.md"
6565
],
66+
"browser": {
67+
"crypto": false
68+
},
6669
"devDependencies": {
6770
"bcrypt": "^5.1.1",
6871
"esm2umd": "^0.2.2",

0 commit comments

Comments
 (0)