mirror of
https://github.com/sharevb/it-tools.git
synced 2026-11-26 23:50:15 +03:00
`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>
86 lines
2.8 KiB
TypeScript
86 lines
2.8 KiB
TypeScript
// Backed by crypto.getRandomValues(): the token, password, passphrase, PIN and salt generators rely on these helpers.
|
|
|
|
const UINT32_RANGE = 2 ** 32;
|
|
const UINT53_RANGE = 2 ** 53;
|
|
const pool = new Uint32Array(256);
|
|
let poolIndex = pool.length;
|
|
|
|
function randomUint32(): number {
|
|
if (poolIndex === pool.length) {
|
|
crypto.getRandomValues(pool);
|
|
poolIndex = 0;
|
|
}
|
|
return pool[poolIndex++];
|
|
}
|
|
|
|
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 = randIndex(i + 1);
|
|
[array[i], array[j]] = [array[j], array[i]];
|
|
}
|
|
|
|
return array;
|
|
}
|
|
|
|
const shuffleArray = <T>(array: T[]): T[] => shuffleArrayMutate([...array]);
|
|
|
|
const shuffleString = (str: string, delimiter = ''): string => shuffleArrayMutate(str.split(delimiter)).join(delimiter);
|
|
|
|
const generateRandomId = () => `id-${random().toString(36).substring(2, 12)}`;
|
|
|
|
export {
|
|
randFromArray,
|
|
multiRandFromArray,
|
|
randIndex,
|
|
randIntFromInterval,
|
|
random,
|
|
shuffleArray,
|
|
shuffleArrayMutate,
|
|
shuffleString,
|
|
generateRandomId,
|
|
};
|