32 lines
803 B
TypeScript
32 lines
803 B
TypeScript
|
|
// Unique ID generation utilities
|
||
|
|
|
||
|
|
import { randomBytes } from 'crypto';
|
||
|
|
|
||
|
|
const BASE62_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Generate a random base62 string of specified length.
|
||
|
|
* Uses cryptographically secure random bytes.
|
||
|
|
*/
|
||
|
|
export function generateSessionId(length: number = 6): string {
|
||
|
|
const bytes = randomBytes(length);
|
||
|
|
let result = '';
|
||
|
|
|
||
|
|
for (let i = 0; i < length; i++) {
|
||
|
|
result += BASE62_CHARS[bytes[i] % BASE62_CHARS.length];
|
||
|
|
}
|
||
|
|
|
||
|
|
return result;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Generate a UUID v4 for request IDs.
|
||
|
|
*/
|
||
|
|
export function generateRequestId(): string {
|
||
|
|
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
||
|
|
const r = Math.random() * 16 | 0;
|
||
|
|
const v = c === 'x' ? r : (r & 0x3 | 0x8);
|
||
|
|
return v.toString(16);
|
||
|
|
});
|
||
|
|
}
|