2026-01-05 19:46:33 -08:00
|
|
|
// Unique ID generation utilities
|
|
|
|
|
|
2026-07-17 10:15:23 -07:00
|
|
|
import { randomBytes, randomUUID } from 'crypto';
|
2026-01-05 19:46:33 -08:00
|
|
|
|
|
|
|
|
const BASE62_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
|
|
|
|
2026-07-17 10:15:23 -07:00
|
|
|
// 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;
|
|
|
|
|
|
2026-01-05 19:46:33 -08:00
|
|
|
/**
|
2026-07-17 10:15:23 -07:00
|
|
|
* Generate a random base62 string of the specified length.
|
|
|
|
|
* Uses cryptographically secure random bytes with rejection sampling
|
|
|
|
|
* to eliminate modulo bias.
|
2026-01-05 19:46:33 -08:00
|
|
|
*/
|
2026-07-17 10:15:23 -07:00
|
|
|
export function generateSessionId(length: number = 12): string {
|
2026-01-05 19:46:33 -08:00
|
|
|
let result = '';
|
|
|
|
|
|
2026-07-17 10:15:23 -07:00
|
|
|
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];
|
|
|
|
|
}
|
2026-01-05 19:46:33 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2026-07-17 10:15:23 -07:00
|
|
|
* Generate a UUID v4 for request IDs using the crypto module.
|
2026-01-05 19:46:33 -08:00
|
|
|
*/
|
|
|
|
|
export function generateRequestId(): string {
|
2026-07-17 10:15:23 -07:00
|
|
|
return randomUUID();
|
2026-01-05 19:46:33 -08:00
|
|
|
}
|