// Unique ID generation utilities import { randomBytes, randomUUID } from 'crypto'; const BASE62_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; // Largest multiple of 62 that fits in a byte (62 * 4 = 248). Bytes >= 248 // are rejected so every character is drawn with uniform probability // (avoids modulo bias from `byte % 62`). const REJECTION_THRESHOLD = Math.floor(256 / BASE62_CHARS.length) * BASE62_CHARS.length; /** * Generate a random base62 string of the specified length. * Uses cryptographically secure random bytes with rejection sampling * to eliminate modulo bias. */ export function generateSessionId(length: number = 12): string { let result = ''; while (result.length < length) { // Over-fetch a little to reduce the number of syscalls when rejecting. const bytes = randomBytes(length); for (let i = 0; i < bytes.length && result.length < length; i++) { const byte = bytes[i]; if (byte >= REJECTION_THRESHOLD) { continue; // reject to avoid bias } result += BASE62_CHARS[byte % BASE62_CHARS.length]; } } return result; } /** * Generate a UUID v4 for request IDs using the crypto module. */ export function generateRequestId(): string { return randomUUID(); }