interface CryptoPolyfill extends Crypto { randomBytes : (length: number) => Uint8Array } /** Maximum allowed length for random bytes (1MB) */ const MAX_RANDOM_LENGTH = 1024 * 1024 /** * Generates cryptographically secure random bytes. * Uses Web Crypto API (crypto.getRandomValues) when available, * with fallback to Node.js crypto.randomBytes for legacy environments. * @param length - Number of random bytes to generate (default: 32, max: 1MB) * @returns Uint8Array containing the random bytes * @throws {TypeError} If length is not a non-negative integer * @throws {RangeError} If length exceeds maximum allowed (1MB) * @throws {Error} If no crypto implementation is available */ export function get_random_bytes (length = 32) : Uint8Array { if (!Number.isInteger(length) || length < 0) { throw new TypeError('Length must be a non-negative integer') } if (length > MAX_RANDOM_LENGTH) { throw new RangeError(`Length exceeds maximum allowed: ${length} > ${MAX_RANDOM_LENGTH}`) } if ( crypto && typeof crypto.getRandomValues === 'function' ) { return crypto.getRandomValues(new Uint8Array(length)) } // Legacy Node Polyfill const pcrypto = crypto as CryptoPolyfill if ( pcrypto && pcrypto.randomBytes !== undefined && typeof pcrypto.randomBytes === 'function' ) { return pcrypto.randomBytes(length) } throw new Error('getRandomValues from crypto library is undefined'); }