From decf404b42bc6271e26f2c5f5985fc8c884721dd Mon Sep 17 00:00:00 2001 From: Arkadiusz Filipczak Date: Tue, 20 Aug 2024 12:56:53 +0200 Subject: [PATCH] Remove Math.random from uid. --- packages/ckeditor5-utils/src/uid.ts | 14 +------------- packages/ckeditor5-utils/tests/uid.js | 12 ++++++++++++ 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/packages/ckeditor5-utils/src/uid.ts b/packages/ckeditor5-utils/src/uid.ts index 42587b5940d..b4b44cddaa1 100644 --- a/packages/ckeditor5-utils/src/uid.ts +++ b/packages/ckeditor5-utils/src/uid.ts @@ -26,19 +26,7 @@ const HEX_NUMBERS = new Array( 256 ).fill( '' ) */ export default function uid(): string { // Let's create some positive random 32bit integers first. - // - // 1. Math.random() is a float between 0 and 1. - // 2. 0x100000000 is 2^32 = 4294967296. - // 3. >>> 0 enforces integer (in JS all numbers are floating point). - // - // For instance: - // Math.random() * 0x100000000 = 3366450031.853859 - // but - // Math.random() * 0x100000000 >>> 0 = 3366450031. - const r1 = Math.random() * 0x100000000 >>> 0; - const r2 = Math.random() * 0x100000000 >>> 0; - const r3 = Math.random() * 0x100000000 >>> 0; - const r4 = Math.random() * 0x100000000 >>> 0; + const [ r1, r2, r3, r4 ] = crypto.getRandomValues( new Uint32Array( 4 ) ); // Make sure that id does not start with number. return 'e' + diff --git a/packages/ckeditor5-utils/tests/uid.js b/packages/ckeditor5-utils/tests/uid.js index b60ce941fdc..e4dfd6925ac 100644 --- a/packages/ckeditor5-utils/tests/uid.js +++ b/packages/ckeditor5-utils/tests/uid.js @@ -7,6 +7,10 @@ import uid from '../src/uid.js'; describe( 'utils', () => { describe( 'uid', () => { + afterEach( () => { + sinon.restore(); + } ); + it( 'should return different ids', () => { const id1 = uid(); const id2 = uid(); @@ -22,5 +26,13 @@ describe( 'utils', () => { expect( id2 ).to.match( uuidRegex ); expect( id3 ).to.match( uuidRegex ); } ); + + it( 'should not use Math.random()', () => { + const spy = sinon.spy( Math, 'random' ); + + uid(); + + expect( spy.notCalled ).to.be.true; + } ); } ); } );