From 15aa1e20a11dc2702b736e8421f39f5e91fcd443 Mon Sep 17 00:00:00 2001 From: gonzaloriestra <14979109+gonzaloriestra@users.noreply.github.com> Date: Sun, 24 May 2026 01:05:29 +0000 Subject: [PATCH] [Security] Harden random selection in takeRandomFromArray Replaced Math.random() with crypto.randomInt() in takeRandomFromArray to ensure cryptographically secure random selection. This reduces predictability in generated names and other random selections. Added unit tests to verify the fix and handle empty array edge cases. --- packages/cli-kit/src/public/common/array.test.ts | 16 +++++++++++++++- packages/cli-kit/src/public/common/array.ts | 4 +++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/cli-kit/src/public/common/array.test.ts b/packages/cli-kit/src/public/common/array.test.ts index 720becbac0b..ce95f124beb 100644 --- a/packages/cli-kit/src/public/common/array.test.ts +++ b/packages/cli-kit/src/public/common/array.test.ts @@ -1,6 +1,20 @@ -import {difference, uniq, uniqBy} from './array.js' +import {difference, takeRandomFromArray, uniq, uniqBy} from './array.js' import {describe, test, expect} from 'vitest' +describe('takeRandomFromArray', () => { + test('returns an element from the array', () => { + const array = [1, 2, 3] + const got = takeRandomFromArray(array) + expect(array).toContain(got) + }) + + test('returns undefined for an empty array', () => { + const array: number[] = [] + const got = takeRandomFromArray(array) + expect(got).toBeUndefined() + }) +}) + describe('uniqBy', () => { test('removes duplicates', () => { // When diff --git a/packages/cli-kit/src/public/common/array.ts b/packages/cli-kit/src/public/common/array.ts index 8b22c0b7b93..b2f78dcc59d 100644 --- a/packages/cli-kit/src/public/common/array.ts +++ b/packages/cli-kit/src/public/common/array.ts @@ -1,5 +1,6 @@ import lodashUniqBy from 'lodash/uniqBy.js' import lodashDifference from 'lodash/difference.js' +import {randomInt} from 'node:crypto' import type {List, ValueIteratee} from 'lodash' /** @@ -9,7 +10,8 @@ import type {List, ValueIteratee} from 'lodash' * @returns A random element from the array. */ export function takeRandomFromArray(array: T[]): T { - return array[Math.floor(Math.random() * array.length)]! + if (array.length === 0) return undefined as unknown as T + return array[randomInt(array.length)]! } /**