Files
MP-Server/macropad-relay/src/utils/idGenerator.ts
T

41 lines
1.2 KiB
TypeScript
Raw Normal View History

2026-01-05 19:46:33 -08:00
// Unique ID generation utilities
import { randomBytes, randomUUID } from 'crypto';
2026-01-05 19:46:33 -08:00
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;
2026-01-05 19:46:33 -08: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
*/
export function generateSessionId(length: number = 12): string {
2026-01-05 19:46:33 -08:00
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];
}
2026-01-05 19:46:33 -08:00
}
return result;
}
/**
* Generate a UUID v4 for request IDs using the crypto module.
2026-01-05 19:46:33 -08:00
*/
export function generateRequestId(): string {
return randomUUID();
2026-01-05 19:46:33 -08:00
}