From 23a25af0688d1db2c396deb09229d2271cc24f6c Mon Sep 17 00:00:00 2001 From: Willian Agostini Date: Tue, 18 Feb 2025 09:36:51 -0300 Subject: [PATCH] fix(utils): replace getRandomValues with crypto module (#6788) --- lib/utils.js | 7 +++++-- test/unit/utils/utils.js | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/lib/utils.js b/lib/utils.js index 32679da..45529b4 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -1,6 +1,7 @@ 'use strict'; import bind from './helpers/bind.js'; +import crypto from 'crypto'; // utils is a library of generic helper functions non-specific to axios @@ -615,8 +616,10 @@ const ALPHABET = { const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { let str = ''; const {length} = alphabet; - while (size--) { - str += alphabet[Math.random() * length|0] + const randomValues = new Uint32Array(size); + crypto.randomFillSync(randomValues); + for (let i = 0; i < size; i++) { + str += alphabet[randomValues[i] % length]; } return str; diff --git a/test/unit/utils/utils.js b/test/unit/utils/utils.js index 8d40250..8ce76e4 100644 --- a/test/unit/utils/utils.js +++ b/test/unit/utils/utils.js @@ -80,4 +80,24 @@ describe('utils', function (){ assert.strictEqual(JSON.stringify(jsonObject), JSON.stringify({x: 1, y:2, obj: {ok: 1}})) }); }); + + describe('generateString', function () { + it('should generate a string of the specified length using the default alphabet', function () { + const size = 10; + const str = utils.generateString(size); + + assert.strictEqual(str.length, size); + }); + + it('should generate a string using only characters from the default alphabet', function () { + const size = 10; + const alphabet = utils.ALPHABET.ALPHA_DIGIT; + + const str = utils.generateString(size, alphabet); + + for (let char of str) { + assert.ok(alphabet.includes(char), `Character ${char} is not in the alphabet`); + } + }); + }); });