- Uniform auth responses remove the session-enumeration oracle: unknown session and wrong password now return an identical 401 at the API layer and an identical WS handshake/close; desktop-status and the 503 "not connected" signal are only exposed after successful auth. - Session-count cap re-checked after bcrypt.hash so concurrent creates can't overshoot maxSessions. - Relay web client reconnect backoff resets only after a successful auth response (an accept-then-close server no longer defeats the backoff). - idGenerator comment corrected to match the rejection-sampling; drop unused recordFailure return value. - DEPLOY.md: document ALLOWED_ORIGINS for reverse-proxy deployments. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
45 lines
1.5 KiB
TypeScript
45 lines
1.5 KiB
TypeScript
// 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) {
|
|
// Fetch exactly `length` random bytes per pass. Bytes at or above the
|
|
// rejection threshold are skipped to avoid modulo bias, so a pass may
|
|
// yield fewer than `length` characters; the outer while then runs another
|
|
// pass until we have enough. (No over-fetching — each pass draws exactly
|
|
// `length` bytes.)
|
|
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();
|
|
}
|