import { describe, test, expect, beforeEach, mock } from 'bun:test' import { createMockConfig } from './helpers/mock-config' // Mutable config mock — individual describes flip `singleUser` (and the // derived `allowRegistration`) to exercise both modes against the same // route modules. const configState = createMockConfig() mock.module('../config', () => ({ config: configState, getBaseUrl: () => configState.baseUrl, })) import { Hono } from 'hono' import type { Database } from 'bun:sqlite' import { randomUUID } from 'node:crypto' import { tmpdir } from 'node:os' import { resolve } from 'node:path' import v1Environments from '../routes/v1/environments' import webAuthRoutes from '../routes/web/auth-routes' import { storeReset } from '../store' import { initDatabase, resetDbSingleton, getDb } from '../db/sqlite' import { ensureSingleUserAdmin, getSingleUserAdminUuid, SINGLE_USER_DEFAULT_PASSWORD, SINGLE_USER_USERNAME, } from '../services/single-user' import { createUserDirectly } from './helpers/fixtures' /** * Single-user mode (`slz rcs one`): * - First deployment auto-initializes the sole admin account * (admin / admin123) — login with those credentials works immediately. * - Any worker binding is auto-owned by that account: no X-User-Id, no * X-Username, no claim_token in the register response. * - Self-registration and invitation joins are refused; register-status * reports closed registration so the Web UI hides the sign-up link. * - Full mode (singleUser=false) keeps the claim flow. */ function freshDb(): Database { try { resetDbSingleton() } catch { // ignore cleanup errors } const path = resolve( tmpdir(), `rcs-single-user-${randomUUID().replace(/-/g, '').slice(0, 8)}.db`, ) return initDatabase(path) } const ADMIN_KEY = { Authorization: 'Bearer test-api-key', 'Content-Type': 'application/json', } function createBridgeApp(): Hono { const app = new Hono() app.route('/v1/environments', v1Environments) return app } function createAuthApp(): Hono { const app = new Hono() app.route('/web/auth', webAuthRoutes) return app } describe('ensureSingleUserAdmin', () => { beforeEach(() => { freshDb() storeReset() configState.singleUser = true configState.allowRegistration = false }) test('creates admin/admin123 on an empty users table (first deployment)', async () => { const admin = await ensureSingleUserAdmin() expect(admin).not.toBeNull() expect(admin!.created).toBe(true) expect(admin!.username).toBe(SINGLE_USER_USERNAME) const row = getDb().query('SELECT id, username, role FROM users').get() as { id: string username: string role: string } expect(row.id).toBe(admin!.userId) expect(row.username).toBe(SINGLE_USER_USERNAME) expect(row.role).toBe('admin') // The default credential verifies against the stored argon2id hash. const { verifyPassword } = await import('../auth/password') const hashRow = getDb() .query('SELECT password_hash FROM users WHERE username = $u') .get({ $u: SINGLE_USER_USERNAME }) as { password_hash: string } expect( verifyPassword(SINGLE_USER_DEFAULT_PASSWORD, hashRow.password_hash), ).toBe(true) }) test('is idempotent — second call reuses the account, no duplicates', async () => { const first = await ensureSingleUserAdmin() const second = await ensureSingleUserAdmin() expect(second!.created).toBe(false) expect(second!.userId).toBe(first!.userId) const count = getDb() .query('SELECT COUNT(*) as count FROM users') .get() as { count: number } expect(count.count).toBe(1) }) test('reuses an existing admin instead of creating a second account', async () => { createUserDirectly(getDb(), { username: 'alice', role: 'admin' }) const admin = await ensureSingleUserAdmin() expect(admin!.created).toBe(false) expect(admin!.username).toBe('alice') const count = getDb() .query('SELECT COUNT(*) as count FROM users') .get() as { count: number } expect(count.count).toBe(1) }) test('returns null when users exist but none is an admin', async () => { createUserDirectly(getDb(), { username: 'bob', role: 'member' }) const admin = await ensureSingleUserAdmin() expect(admin).toBeNull() }) test('getSingleUserAdminUuid resolves the admin id', async () => { expect(getSingleUserAdminUuid()).toBeNull() // empty DB const admin = await ensureSingleUserAdmin() expect(getSingleUserAdminUuid()).toBe(admin!.userId) }) }) describe('POST /v1/environments/bridge — single-user auto-ownership', () => { let app: Hono let db: Database beforeEach(() => { db = freshDb() storeReset() app = createBridgeApp() }) test('bare API key registration is owned by the single admin, no claim', async () => { configState.singleUser = true const admin = await ensureSingleUserAdmin() expect(admin).not.toBeNull() const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: ADMIN_KEY, body: JSON.stringify({ machine_name: 'local-worker' }), }) expect(res.status).toBe(200) const body = (await res.json()) as { environment_id: string claim_token?: string claim_url?: string } expect(body.environment_id).toMatch(/^env_/) // No claim flow in single-user mode — the env already has an owner. expect(body.claim_token).toBeUndefined() expect(body.claim_url).toBeUndefined() const row = db .query('SELECT owner_user_id, claim_token FROM environments') .get() as { owner_user_id: string; claim_token: string | null } expect(row.owner_user_id).toBe(admin!.userId) expect(row.claim_token).toBeNull() }) test('reattach keeps the env owned by the single admin', async () => { configState.singleUser = true const admin = await ensureSingleUserAdmin() const first = await app.request('/v1/environments/bridge', { method: 'POST', headers: ADMIN_KEY, body: JSON.stringify({ machine_name: 'w1' }), }) const { environment_id } = (await first.json()) as { environment_id: string } // Restart with the bridge pointer — reattach must not fork or un-own. const second = await app.request('/v1/environments/bridge', { method: 'POST', headers: ADMIN_KEY, body: JSON.stringify({ environment_id, machine_name: 'w1' }), }) expect(second.status).toBe(200) const count = db .query('SELECT COUNT(*) as count FROM environments') .get() as { count: number } expect(count.count).toBe(1) const row = db.query('SELECT owner_user_id FROM environments').get() as { owner_user_id: string } expect(row.owner_user_id).toBe(admin!.userId) }) test('ACP worker session is bound to the single admin', async () => { configState.singleUser = true const admin = await ensureSingleUserAdmin() const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: ADMIN_KEY, body: JSON.stringify({ machine_name: 'acp-agent', worker_type: 'acp', bridge_id: 'grp_local', }), }) expect(res.status).toBe(200) const { session_id } = (await res.json()) as { session_id: string } expect(session_id).toBeDefined() const owner = db .query( `SELECT owner_id FROM session_owners WHERE session_id = $s AND owner_type = 'user'`, ) .get({ $s: session_id }) as { owner_id: string } expect(owner.owner_id).toBe(admin!.userId) }) test('full mode (singleUser=false) keeps the claim flow', async () => { configState.singleUser = false const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: ADMIN_KEY, body: JSON.stringify({ machine_name: 'w1' }), }) expect(res.status).toBe(200) const body = (await res.json()) as { claim_token: string } expect(body.claim_token).toMatch(/^clm_/) const row = db.query('SELECT owner_user_id FROM environments').get() as { owner_user_id: string | null } expect(row.owner_user_id).toBeNull() }) }) describe('web auth routes — single-user mode', () => { let app: Hono beforeEach(() => { freshDb() storeReset() app = createAuthApp() configState.singleUser = true configState.allowRegistration = false }) test('first deployment: bootstrap → login with admin/admin123 works', async () => { const admin = await ensureSingleUserAdmin() expect(admin!.created).toBe(true) const res = await app.request('/web/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: SINGLE_USER_USERNAME, password: SINGLE_USER_DEFAULT_PASSWORD, }), }) expect(res.status).toBe(200) const body = (await res.json()) as { accessToken: string } expect(body.accessToken).toBeDefined() }) test('register-status reports closed registration', async () => { const res = await app.request('/web/auth/register-status') expect(res.status).toBe(200) const body = (await res.json()) as { allowed: boolean } expect(body.allowed).toBe(false) }) test('self-registration is refused', async () => { const res = await app.request('/web/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'intruder', password: 'password123' }), }) expect(res.status).toBe(403) const count = getDb() .query('SELECT COUNT(*) as count FROM users') .get() as { count: number } expect(count.count).toBe(0) }) test('invitation join is refused', async () => { const res = await app.request('/web/auth/join', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ inviteToken: 'inv_whatever', username: 'guest', password: 'password123', }), }) expect(res.status).toBe(403) }) test('setup-status reports no setup needed and the single-user mode', async () => { await ensureSingleUserAdmin() const res = await app.request('/web/auth/setup-status') expect(res.status).toBe(200) const body = (await res.json()) as { needsSetup: boolean singleUser: boolean } expect(body.needsSetup).toBe(false) expect(body.singleUser).toBe(true) }) test('full mode keeps registration open (contrast)', async () => { configState.singleUser = false configState.allowRegistration = true const res = await app.request('/web/auth/register-status') const body = (await res.json()) as { allowed: boolean } expect(body.allowed).toBe(true) }) })