import { randomUUID } from 'node:crypto' /** * One-time browser login codes for single-user mode (`slz rcs one`). * * `slz rcs one` auto-opens the Web UI straight into the freshly created * session — but a fresh browser has no session cookies, so a plain deep * link would bounce off the login page. Instead the CLI mints a * short-lived one-time code in-process (only the server process itself * can mint one), the browser hits GET /otp/, and the server sets * the single admin's session cookies before redirecting to the stored * target path (see registerRoutes.ts). * * Trust model: same as the rest of single-user mode — loopback binding, * the API key is the only real credential, and the code is a random * 122-bit value that is single-use and expires in two minutes. Codes * live in memory only: a server restart invalidates any unspent ones. */ export interface WebLoginCodeRecord { code: string userId: string /** Path the browser is redirected to after login (must start with '/'). */ targetPath: string expiresAt: number } const CODE_TTL_MS = 2 * 60 * 1000 /** Upper bound so a pathological minter can't grow the map forever. */ export const MAX_PENDING_CODES = 64 const pendingCodes = new Map() function pruneExpired(now = Date.now()): void { for (const [code, record] of pendingCodes) { if (record.expiresAt <= now) { pendingCodes.delete(code) } } } /** Clamp a redirect target to a same-origin path ('/…', never '//…'). */ function toSafeTargetPath(targetPath: string): string { return targetPath.startsWith('/') && !targetPath.startsWith('//') ? targetPath : '/' } /** * Mint a one-time login code for a user + redirect target. * The target path is clamped to a same-origin path — protocol-relative * ('//host') and absolute URLs are rejected to block open redirects. */ export function issueWebLoginCode( userId: string, targetPath: string, ): WebLoginCodeRecord { pruneExpired() if (pendingCodes.size >= MAX_PENDING_CODES) { // Drop the oldest — Map preserves insertion order. const oldest = pendingCodes.keys().next().value if (oldest !== undefined) { pendingCodes.delete(oldest) } } const record: WebLoginCodeRecord = { code: `wlc_${randomUUID().replace(/-/g, '')}`, userId, targetPath: toSafeTargetPath(targetPath), expiresAt: Date.now() + CODE_TTL_MS, } pendingCodes.set(record.code, record) return record } /** * Consume a login code (single use). Returns null when the code is * unknown, already used, or expired. */ export function consumeWebLoginCode(code: string): WebLoginCodeRecord | null { pruneExpired() const record = pendingCodes.get(code) if (!record) { return null } pendingCodes.delete(code) if (record.expiresAt <= Date.now()) { return null } return record } /** Test hook — clear all pending codes. */ export function _resetWebLoginCodes(): void { pendingCodes.clear() }