fix(random): use crypto.getRandomValues for generated secrets

`src/utils/random.ts` was built on Math.random(), and it backs the token
generator, htpasswd salts and the passphrase suffixes. The PIN code
generator and the database builder's default password called Math.random()
directly. All now go through crypto.getRandomValues() with rejection
sampling, so indices are unbiased, for ranges up to 2^53.

The passphrase generator no longer calls generateSillyPassword(), which also
picks words with Math.random(). It uses the package's word lists with the
secure helpers, and skips pulling lodash and zxcvbn into the bundle.

Behaviour changes that came with it:
- randIntFromInterval() now includes its upper bound. The lorem ipsum
  sliders could never reach their maximum and the passphrase generator never
  put a number on the last word. The coin flipper used `0..10 % 2`, which
  would be biased with an inclusive range, so it now draws 0 or 1.
- randIntFromInterval() orders reversed bounds, rounds fractional ones
  inward and returns NaN for non-finite input instead of throwing.
- The lorem ipsum generator falls back to its defaults for malformed
  `paragraphs`, `sentences` and `words` URL values and clamps them to the
  slider ranges, so a link like `?sentences=[1,4294967297]` cannot freeze
  the page.
- Passphrases whose length equals the min or max length are accepted.
- Multi-word list entries ("wide eyed") count as one word, so the word count
  and number placement match the settings.
- Token generator draws each character independently instead of shuffling
  the alphabet repeated `length` times.

Fixes the CodeQL js/insecure-randomness alert in the passphrase generator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sebastian DanielssonandClaude Opus 5.5 authored and sharevb committed 2026-10-03 21:11:50 +02:00
1 parent d785329e74
commit 0203c2388a
11 files changed
+243 -47

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ import { randIntFromInterval } from '@/utils/random';
const { t } = useI18n();
const [coinFlip, refreshCoinFlip] = computedRefreshable(() => ({
coin: randIntFromInterval(0, 10) % 2 === 0 ? 'Heads' : 'Tails',
coin: randIntFromInterval(0, 1) === 0 ? 'Heads' : 'Tails',
dt: Date.now(),
}));
</script>
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { multiRandFromArray } from '@/utils/random';
const { t } = useI18n();
@@ -15,7 +16,7 @@ const sqlOutput = ref('');
function generateRandomPassword(length = 12) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
return Array.from({ length }, () => chars[Math.floor(Math.random() * chars.length)]).join('');
return multiRandFromArray([...chars], length).join('');
}
function generateSQL() {
@@ -6,23 +6,39 @@ import { computedRefreshable } from '@/composable/computedRefreshable';
import { useCopy } from '@/composable/copy';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { randIntFromInterval } from '@/utils/random';
import { clamp } from '@/modules/shared/number.models';
const { t } = useI18n();
const defaultSentences = [3, 8];
const defaultWords = [8, 15];
const paragraphs = useQueryParamOrStorage({ name: 'paragraphs', storageName: 'lorem:paragraphs', defaultValue: 1 });
const sentences = useQueryParamOrStorage({ name: 'sentences', storageName: 'lorem:sentences', defaultValue: [3, 8] });
const words = useQueryParamOrStorage({ name: 'words', storageName: 'lorem:words', defaultValue: [8, 15] });
const sentences = useQueryParamOrStorage({
name: 'sentences',
storageName: 'lorem:sentences',
defaultValue: defaultSentences,
});
const words = useQueryParamOrStorage({ name: 'words', storageName: 'lorem:words', defaultValue: defaultWords });
const startWithLoremIpsum = ref(true);
const asHTML = useQueryParamOrStorage({ name: 'html', storageName: 'lorem:html', defaultValue: false });
const language = useQueryParamOrStorage({ defaultValue: 'English', storageName: 'lorem:lang', name: 'lang' });
// URL params are neither type-checked nor bounded by the sliders: fall back to the default when the value has the wrong
// shape, and clamp it to the slider range so huge values cannot freeze the page
const sliderValue = (value: unknown, fallback: number, max: number) =>
typeof value === 'number' && Number.isFinite(value) ? clamp({ value, min: 1, max }) : fallback;
const randIntFromSliderRange = (range: unknown, [defaultMin, defaultMax]: number[]) => {
const [min, max] = Array.isArray(range) ? range : [];
return randIntFromInterval(sliderValue(min, defaultMin, 50), sliderValue(max, defaultMax, 50));
};
const supportedLanguages = getSupportedLanguages();
const [loremIpsumText, refreshLoremIpsum] = computedRefreshable(() =>
generateLoremIpsum({
paragraphCount: paragraphs.value,
paragraphCount: sliderValue(paragraphs.value, 1, 20),
asHTML: asHTML.value,
sentencePerParagraph: randIntFromInterval(sentences.value[0], sentences.value[1]),
wordCount: randIntFromInterval(words.value[0], words.value[1]),
sentencePerParagraph: randIntFromSliderRange(sentences.value, defaultSentences),
wordCount: randIntFromSliderRange(words.value, defaultWords),
startWithLoremIpsum: startWithLoremIpsum.value,
language: language.value,
}),
@@ -0,0 +1,34 @@
import { describe, expect, it, vi } from 'vitest';
import { generatePassphrase } from './passphrase-generator.service';
describe('passphrase-generator', () => {
describe('generatePassphrase', () => {
it('does not use Math.random', () => {
const spy = vi.spyOn(Math, 'random');
generatePassphrase({ wordCount: 5, numberCount: 2 });
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
it('generates the requested number of lowercase words', () => {
const passphrase = generatePassphrase({ wordCount: 6, separator: '|' });
expect(passphrase).toMatch(/^[a-z|]+$/);
expect(passphrase.split('|').length).toBeGreaterThanOrEqual(6);
});
it('adds a number to exactly the requested amount of words', () => {
const passphrase = generatePassphrase({ wordCount: 4, numberCount: 4 });
expect(passphrase.match(/\d+/g)).toHaveLength(4);
for (const value of passphrase.match(/\d+/g)!) {
expect(Number(value)).toBeGreaterThanOrEqual(1);
expect(Number(value)).toBeLessThanOrEqual(100);
}
});
it('capitalizes the first letter and appends the salt', () => {
const passphrase = generatePassphrase({ wordCount: 3, capitalize: true, salt: '!?' });
expect(passphrase).toMatch(/^[A-Z]/);
expect(passphrase.endsWith('!?')).toBe(true);
});
});
});
@@ -0,0 +1,36 @@
// Only the MIT-licensed word lists: generateSillyPassword() picks words with Math.random()
import { allCreatures, attributes } from 'silly-password-generator/dist/passwords/words';
import { randFromArray, randIntFromInterval, shuffleArray } from '@/utils/random';
const firstWords = [...new Set(attributes.map((word) => word.toLowerCase()))];
const lastWords = [...new Set(allCreatures.map((word) => word.toLowerCase()))];
const anyWords = [...new Set([...firstWords, ...lastWords])];
export function generatePassphrase({
wordCount,
numberCount = 0,
capitalize = false,
separator = '-',
salt = '',
}: {
wordCount: number;
numberCount?: number;
capitalize?: boolean;
separator?: string;
salt?: string;
}): string {
const count = Math.max(1, wordCount);
const withNumbers = new Set(
shuffleArray(Array.from({ length: count }, (_, i) => i)).slice(0, Math.max(0, numberCount)),
);
const words = Array.from({ length: count }, (_, i) => {
// same shape as silly-password-generator: an attribute first, a creature last
const pool = i === count - 1 ? lastWords : i === 0 ? firstWords : anyWords;
const word = randFromArray(pool)!.split(/\s+/).join(separator);
return withNumbers.has(i) ? word + randIntFromInterval(1, 100) : word;
});
const passphrase = words.join(separator) + salt;
return capitalize ? passphrase.charAt(0).toUpperCase() + passphrase.slice(1) : passphrase;
}
@@ -1,10 +1,9 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { generateSillyPassword } from 'silly-password-generator';
import { generatePassphrase } from './passphrase-generator.service';
import { useCopy } from '@/composable/copy';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { computedRefreshable } from '@/composable/computedRefreshable';
import { randIntFromInterval } from '@/utils/random';
const { t } = useI18n();
@@ -23,37 +22,16 @@ const maxLen = useQueryParamOrStorage({ name: 'maxlen', storageName: 'pass-gener
const [passphrases, refreshPassphrases] = computedRefreshable(() =>
Array.from({ length: count.value }, () => {
const requiredNumbers = Math.min(words.value, numbers.value);
const nums: number[] = [];
if (words.value === requiredNumbers) {
for (let i = 0; i < requiredNumbers; i++) {
nums.push(i);
}
} else {
while (nums.length < requiredNumbers) {
const rndNumber = randIntFromInterval(0, words.value - 1);
if (!nums.includes(rndNumber)) {
nums.push(rndNumber);
}
}
}
let maxIter = 1000;
while (maxIter > 0) {
const passphrase = generateSillyPassword({
capitalize: capitalize.value,
const passphrase = generatePassphrase({
wordCount: words.value,
numberCount: numbers.value,
capitalize: capitalize.value,
separator: separator.value,
salt: saltChars.value,
})
.split(/\s+/g)
.map((word, i) => {
if (nums.includes(i)) {
return word + randIntFromInterval(1, 100);
}
return word;
})
.join(separator.value);
if (minLen.value < passphrase.length && passphrase.length < maxLen.value) {
});
if (minLen.value <= passphrase.length && passphrase.length <= maxLen.value) {
return passphrase;
}
maxIter -= 1;
@@ -1,11 +1,12 @@
import { randIndex } from '@/utils/random';
export function randomNumber({ length, repeatDigits = false }: { length: number; repeatDigits?: boolean }) {
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const result: number[] = [];
const willRepeat = length > 10 || repeatDigits;
while (result.length < length) {
const random = Math.floor(Math.random() * 10); // NOSONAR
const num = arr[random];
const num = arr[randIndex(arr.length)];
if (!willRepeat && result.includes(num)) {
continue;
}
@@ -1,8 +1,15 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import { createToken } from './token-generator.service';
describe('token-generator', () => {
describe('createToken', () => {
it('should not use Math.random', () => {
const spy = vi.spyOn(Math, 'random');
createToken({ length: 64 });
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
it('should generate an empty string when all params are false', () => {
const token = createToken({
withLowercase: false,
@@ -1,4 +1,4 @@
import { shuffleString } from '@/utils/random';
import { multiRandFromArray } from '@/utils/random';
export function createToken({
withUppercase = true,
@@ -35,5 +35,5 @@ export function createToken({
.join('');
const len = length < 1 ? 1 : length;
return shuffleString(allAlphabet.repeat(len)).substring(0, len);
return allAlphabet ? multiRandFromArray(Array.from(allAlphabet), len).join('') : '';
}
+73
View File
@@ -0,0 +1,73 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { randFromArray, randIndex, randIntFromInterval, random, shuffleArray } from './random';
describe('random', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('does not use Math.random', () => {
const spy = vi.spyOn(Math, 'random');
random();
randIndex(10);
shuffleArray([1, 2, 3]);
expect(spy).not.toHaveBeenCalled();
});
it('random() returns floats in [0, 1)', () => {
for (let i = 0; i < 1000; i++) {
const value = random();
expect(value).toBeGreaterThanOrEqual(0);
expect(value).toBeLessThan(1);
}
});
it('randIndex() covers [0, max) and rejects invalid bounds', () => {
const seen = new Set(Array.from({ length: 1000 }, () => randIndex(3)));
expect([...seen].sort((a, b) => a - b)).toEqual([0, 1, 2]);
expect(() => randIndex(0)).toThrow(RangeError);
expect(() => randIndex(1.5)).toThrow(RangeError);
expect(() => randIndex(2 ** 53 + 2)).toThrow(RangeError);
});
it('randIntFromInterval() includes both bounds', () => {
const seen = new Set(Array.from({ length: 1000 }, () => randIntFromInterval(5, 7)));
expect([...seen].sort((a, b) => a - b)).toEqual([5, 6, 7]);
});
it('randIntFromInterval() accepts reversed and fractional bounds', () => {
const reversed = new Set(Array.from({ length: 1000 }, () => randIntFromInterval(8, 3)));
expect([...reversed].sort((a, b) => a - b)).toEqual([3, 4, 5, 6, 7, 8]);
const fractional = new Set(Array.from({ length: 1000 }, () => randIntFromInterval(2.5, 4)));
expect([...fractional].sort((a, b) => a - b)).toEqual([3, 4]);
expect(randIntFromInterval(2.2, 2.8)).toBe(3);
expect(randIntFromInterval(Number.NaN, 4)).toBeNaN();
});
it('randIntFromInterval() handles ranges wider than 2^32', () => {
for (const [min, max] of [
[1, 2 ** 32 + 1],
[-(2 ** 52), 2 ** 52],
[-Number.MAX_VALUE, Number.MAX_VALUE],
]) {
const value = randIntFromInterval(min, max);
expect(Number.isInteger(value)).toBe(true);
expect(value).toBeGreaterThanOrEqual(min);
expect(value).toBeLessThanOrEqual(max);
}
const aboveUint32 = Array.from({ length: 200 }, () => randIntFromInterval(0, 2 ** 40));
expect(aboveUint32.some((value) => value > 2 ** 32)).toBe(true);
});
it('randFromArray() returns undefined for an empty array', () => {
expect(randFromArray([])).toBeUndefined();
expect(randFromArray(['a'])).toBe('a');
});
it('shuffleArray() returns a permutation without mutating the input', () => {
const input = [1, 2, 3, 4, 5];
const shuffled = shuffleArray(input);
expect(input).toEqual([1, 2, 3, 4, 5]);
expect([...shuffled].sort((a, b) => a - b)).toEqual(input);
});
});
+56 -6
View File
@@ -1,16 +1,65 @@
const random = () => Math.random();
// Backed by crypto.getRandomValues(): the token, password, passphrase, PIN and salt generators rely on these helpers.
const randFromArray = (array: unknown[]) => array[Math.floor(random() * array.length)];
const UINT32_RANGE = 2 ** 32;
const UINT53_RANGE = 2 ** 53;
const pool = new Uint32Array(256);
let poolIndex = pool.length;
const multiRandFromArray = (array: unknown[], length: number) =>
Array.from({ length }, () => array[Math.floor(random() * array.length)]);
function randomUint32(): number {
if (poolIndex === pool.length) {
crypto.getRandomValues(pool);
poolIndex = 0;
}
return pool[poolIndex++];
}
const randIntFromInterval = (min: number, max: number) => Math.floor(random() * (max - min) + min);
const randomUint53 = () => (randomUint32() >>> 11) * UINT32_RANGE + randomUint32();
// Uniform integer in [0, max) for max up to 2^53, rejection sampling avoids modulo bias
function randIndex(max: number): number {
if (!Number.isInteger(max) || max < 1 || max > UINT53_RANGE) {
throw new RangeError(`randIndex: max must be an integer between 1 and 2^53, got ${max}`);
}
const [range, next] = max <= UINT32_RANGE ? [UINT32_RANGE, randomUint32] : [UINT53_RANGE, randomUint53];
const limit = range - (range % max);
let value = next();
while (value >= limit) {
value = next();
}
return value % max;
}
// Float in [0, 1) with 53 bits of precision, like Math.random()
const random = () => randomUint53() / UINT53_RANGE;
const randFromArray = <T>(array: T[]): T | undefined => (array.length > 0 ? array[randIndex(array.length)] : undefined);
const multiRandFromArray = <T>(array: T[], length: number) => Array.from({ length }, () => randFromArray(array));
// Integer in [min, max], both bounds included. Bounds can come from URL params, so reversed or fractional ones are
// normalised instead of throwing.
function randIntFromInterval(min: number, max: number): number {
const low = Math.ceil(Math.min(min, max));
const high = Math.floor(Math.max(min, max));
if (!Number.isFinite(low) || !Number.isFinite(high)) {
return Number.NaN;
}
if (high < low) {
return low;
}
const width = high - low + 1;
if (width <= UINT53_RANGE) {
return low + randIndex(width);
}
// Past 2^53 not every integer is representable, so exact uniformity is moot. Interpolate so high - low cannot overflow.
const r = random();
return Math.min(high, Math.max(low, Math.floor(low * (1 - r) + high * r)));
}
// Durstenfeld shuffle
function shuffleArrayMutate<T>(array: T[]): T[] {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const j = randIndex(i + 1);
[array[i], array[j]] = [array[j], array[i]];
}
@@ -26,6 +75,7 @@ const generateRandomId = () => `id-${random().toString(36).substring(2, 12)}`;
export {
randFromArray,
multiRandFromArray,
randIndex,
randIntFromInterval,
random,
shuffleArray,