import { describe, test, expect, beforeEach, mock } from 'bun:test' import { createMockConfig } from './helpers/mock-config' // Mutable config mock — tests flip `singleUser` to exercise the // single-user-only gate on GET /otp/:code. const configState = createMockConfig() mock.module('../config', () => ({ config: configState, getBaseUrl: () => configState.baseUrl, })) import { Hono } from 'hono' import type { MiddlewareHandler } from 'hono/types' import { randomUUID } from 'node:crypto' import { tmpdir } from 'node:os' import { resolve } from 'node:path' import { initDatabase, resetDbSingleton, getDb } from '../db/sqlite' import { registerRoutes } from '../registerRoutes' import { _resetWebLoginCodes, issueWebLoginCode } from '../services/web-login' import { createUserDirectly } from './helpers/fixtures' /** * GET /otp/:code — one-time browser login for `slz rcs one`: * - valid code (single-user mode) → session cookies for the single admin * + redirect to the stored target path; the minted token authenticates * against /web/auth/me * - codes are single-use — a second hit redirects to /login * - unknown/expired codes redirect to /login (manual login still works) * - full mode (singleUser=false) → 404 — the route is one-only */ // Dummy serveStatic — passes through so API routes handle everything. const serveStatic: (opts: Record) => MiddlewareHandler = () => async (_c, next) => { await next() } // Dummy upgradeWebSocket const upgradeWebSocket = (() => { return () => async (_c: import('hono').Context, next: import('hono').Next) => { await next() } }) as unknown as import('hono/ws').UpgradeWebSocket function createApp(): Hono { const app = new Hono() registerRoutes(app, serveStatic, upgradeWebSocket) return app } function setupTestDb(): ReturnType { try { resetDbSingleton() } catch { // ignore } const uniquePath = resolve( tmpdir(), `rcs-otp-${randomUUID().replace(/-/g, '').slice(0, 8)}.db`, ) return initDatabase(uniquePath) } describe('GET /otp/:code', () => { let app: Hono beforeEach(() => { setupTestDb() _resetWebLoginCodes() configState.singleUser = true app = createApp() }) test('valid code sets admin session cookies and redirects to the target', async () => { const db = getDb() const admin = createUserDirectly(db, { username: 'admin', role: 'admin' }) const issued = issueWebLoginCode(admin.id, '/code/session_abc') const res = await app.request(`/otp/${issued.code}`) expect(res.status).toBe(302) expect(res.headers.get('Location')).toBe('/code/session_abc') const cookies = res.headers.getSetCookie() const accessCookie = cookies.find(c => c.startsWith('rcs_access=')) const refreshCookie = cookies.find(c => c.startsWith('rcs_refresh=')) expect(accessCookie).toBeDefined() expect(refreshCookie).toBeDefined() // The minted access token must authenticate as the admin user. const accessToken = accessCookie!.split(';')[0]!.slice('rcs_access='.length) const me = await app.request('/web/auth/me', { headers: { Cookie: `rcs_access=${accessToken}` }, }) expect(me.status).toBe(200) const meBody = (await me.json()) as { userId: string; role: string } expect(meBody.userId).toBe(admin.id) expect(meBody.role).toBe('admin') }) test('codes are single-use — a second hit falls back to /login', async () => { const db = getDb() const admin = createUserDirectly(db, { username: 'admin', role: 'admin' }) const issued = issueWebLoginCode(admin.id, '/code/') const first = await app.request(`/otp/${issued.code}`) expect(first.status).toBe(302) expect(first.headers.get('Location')).toBe('/code/') const second = await app.request(`/otp/${issued.code}`) expect(second.status).toBe(302) expect(second.headers.get('Location')).toBe('/login') }) test('unknown code redirects to /login', async () => { const res = await app.request('/otp/wlc_unknowncodeunknowncode') expect(res.status).toBe(302) expect(res.headers.get('Location')).toBe('/login') }) test('returns 404 in full (non-single-user) mode', async () => { configState.singleUser = false const db = getDb() const admin = createUserDirectly(db, { username: 'admin', role: 'admin' }) const issued = issueWebLoginCode(admin.id, '/code/') const res = await app.request(`/otp/${issued.code}`) expect(res.status).toBe(404) }) })