import { randomUUID } from 'node:crypto' import type { Database } from 'bun:sqlite' import { getDb } from '../db/sqlite' import { hashPasswordAsync } from '../auth/password' /** * Single-user mode (`slz rcs one`) — the server runs with exactly one * admin account, auto-created on first deployment. Every worker that * binds is owned by this account (no X-User-Id, no claim flow), and * self-registration / invitation joins are disabled (see auth-routes). * Intended for local deployments (host binds 127.0.0.1) where multi-user * auth is ceremony, not protection. */ export const SINGLE_USER_USERNAME = 'admin' export const SINGLE_USER_DEFAULT_PASSWORD = 'admin123' interface UserRow { id: string username: string role: string } export interface SingleUserAdmin { userId: string username: string /** True when this call created the account (first deployment). */ created: boolean } /** * Idempotent bootstrap of the single-user admin account. * * Resolution order: * 1. An existing user named `admin` — reuse it (previously initialized * single-user DB, or a full-mode DB where someone already chose that * name). * 2. Any existing admin — reuse the first one (full-mode DB set up via * /setup: that admin IS the single user; never mint a second account). * 3. Empty users table — create `admin` / `admin123` with role=admin. * * Returns null only when the users table has rows but none is an admin * and none is named `admin` (a corrupted/mixed DB) — the caller decides * whether that is fatal. */ export async function ensureSingleUserAdmin( db?: Database, ): Promise { const database = db ?? getDb() const byName = database .query('SELECT id, username, role FROM users WHERE username = $u LIMIT 1') .get({ $u: SINGLE_USER_USERNAME }) as UserRow | null if (byName) { return { userId: byName.id, username: byName.username, created: false } } const anyAdmin = database .query( 'SELECT id, username, role FROM users WHERE role = $r ORDER BY created_at LIMIT 1', ) .get({ $r: 'admin' }) as UserRow | null if (anyAdmin) { return { userId: anyAdmin.id, username: anyAdmin.username, created: false } } const count = database.query('SELECT COUNT(*) as count FROM users').get() as { count: number } if (count.count > 0) { // Users exist but no admin and no `admin` — cannot pick a single user // without silently granting it admin rights. Let the caller surface it. return null } const userId = `usr_${randomUUID().replace(/-/g, '')}` const passwordHash = await hashPasswordAsync(SINGLE_USER_DEFAULT_PASSWORD) const now = new Date().toISOString() database .query( `INSERT OR IGNORE INTO users (id, username, password_hash, role, created_at) VALUES ($id, $username, $passwordHash, 'admin', $now)`, ) .run({ $id: userId, $username: SINGLE_USER_USERNAME, $passwordHash: passwordHash, $now: now, }) const inserted = database .query('SELECT id, username, role FROM users WHERE username = $u LIMIT 1') .get({ $u: SINGLE_USER_USERNAME }) as UserRow | null if (!inserted) { // INSERT OR IGNORE lost a race (concurrent bootstrap) — resolve the winner. return ensureSingleUserAdmin(database) } return { userId: inserted.id, username: inserted.username, created: true } } /** * Resolve the single-user admin's users.id for worker auto-ownership. * * Sync and cheap — called on every unowned worker registration in * single-user mode. Returns null when no admin exists yet (bootstrap not * run / DB error) — the caller falls back to the regular claim flow. */ export function getSingleUserAdminUuid(db?: Database): string | null { try { const database = db ?? getDb() const row = database .query( `SELECT id FROM users WHERE username = $u OR role = $r ORDER BY CASE WHEN username = $u THEN 0 ELSE 1 END, created_at LIMIT 1`, ) .get({ $u: SINGLE_USER_USERNAME, $r: 'admin' }) as { id: string } | null return row?.id ?? null } catch (err) { console.error('[single-user] admin lookup failed:', err) return null } }