import { Hono } from 'hono' import { cors } from 'hono/cors' import { logger } from 'hono/logger' import { serveStatic, upgradeWebSocket } from 'hono/bun' import { config } from './config' import { closeAllConnections } from './transport/ws-handler' import { closeAllAcpConnections } from './transport/acp-ws-handler' import { closeAllRelayConnections } from './transport/acp-relay-handler' import { startDisconnectMonitor } from './services/disconnect-monitor' import { registerRoutes } from './registerRoutes' import { webCorsOptions } from './auth/cors' import { websocket } from './transport/ws-shared' import { getDb } from './db/sqlite' import { reapExpiredSessions } from './auth/session' import { cleanupExpiredArtifacts } from './services/artifacts' import { ensureSingleUserAdmin, SINGLE_USER_DEFAULT_PASSWORD, SINGLE_USER_USERNAME, } from './services/single-user' console.log('[RCS] In-memory store ready (no SQLite)') const app = new Hono() // Middleware app.use('*', logger()) app.use('*', async (c, next) => { // Normalize double slashes in path (e.g. //v1/environments/bridge → /v1/environments/bridge) const path = new URL(c.req.url).pathname if (path.includes('//')) { const normalized = path.replace(/\/+/g, '/') const url = new URL(c.req.url) url.pathname = normalized return app.fetch(new Request(url.toString(), c.req.raw)) } await next() }) app.use('/web/*', cors(webCorsOptions)) // Health check app.get('/health', c => c.json({ status: 'ok', version: config.version })) // Register all routes with Bun's serveStatic and upgradeWebSocket registerRoutes(app, serveStatic, upgradeWebSocket) // Single-user mode: local convenience — bind loopback unless the operator // explicitly chose a host via RCS_HOST. if (config.singleUser && !process.env.RCS_HOST) { config.host = '127.0.0.1' } const port = config.port const host = config.host console.log(`[RCS] Remote Control Server starting on ${host}:${port}`) console.log('[RCS] API key configuration loaded') console.log(`[RCS] Base URL: ${config.baseUrl || `http://localhost:${port}`}`) console.log(`[RCS] Disconnect timeout: ${config.disconnectTimeout}s`) console.log( `[RCS] WebSocket idle timeout: ${config.wsIdleTimeout}s (protocol-level pings)`, ) console.log( `[RCS] WebSocket keepalive interval: ${config.wsKeepaliveInterval}s (data frames)`, ) // Start disconnect monitor startDisconnectMonitor() // Single-user mode (`slz rcs one` via bun run rcs one): bootstrap the sole // admin account (admin/admin123 on first deployment) before serving // requests, so worker registrations always resolve an owner. if (config.singleUser) { const admin = await ensureSingleUserAdmin() if (!admin) { console.error( '[RCS] Single-user mode requires an empty or admin-bearing users ' + 'table, but the existing DB has neither. Run full mode (no `one` ' + 'argument) or point RCS_DB_PATH at a fresh database.', ) process.exit(1) } console.log('[RCS] Single-user mode (one):') if (admin.created) { console.log( `[RCS] admin account initialized — username: ${SINGLE_USER_USERNAME} password: ${SINGLE_USER_DEFAULT_PASSWORD}`, ) console.log( '[RCS] (local convenience default — change it after first login)', ) } else { console.log(`[RCS] using existing account: ${admin.username}`) } console.log('[RCS] registration disabled — this is the only account') console.log( '[RCS] workers bind zero-config and are owned by this account (no claim)', ) } // Reap expired session tokens at startup and periodically try { const db = getDb() const reaped = reapExpiredSessions(db) if (reaped > 0) { console.log(`[RCS] Reaped ${reaped} expired session tokens`) } } catch (err) { console.warn('[RCS] Failed to reap expired sessions:', err) } // Clean up expired artifacts (7/30-day TTLs) on the same hourly cadence try { cleanupExpiredArtifacts() } catch (err) { console.warn('[RCS] Failed to clean up expired artifacts:', err) } const reapInterval = setInterval( () => { try { const db = getDb() reapExpiredSessions(db) cleanupExpiredArtifacts() } catch { // ignore — DB may not be available } }, 60 * 60 * 1000, ) // every hour if (reapInterval.unref) { reapInterval.unref() } export default { port, hostname: host, fetch: app.fetch, websocket: { ...websocket, idleTimeout: config.wsIdleTimeout, // Bun sends protocol pings after this many seconds of silence }, idleTimeout: config.wsIdleTimeout, // HTTP server idle timeout (seconds) } // Graceful shutdown async function gracefulShutdown(signal: string) { console.log(`\n[RCS] Received ${signal}, shutting down...`) closeAllConnections() closeAllAcpConnections() closeAllRelayConnections() process.exit(0) } process.on('SIGINT', () => gracefulShutdown('SIGINT')) process.on('SIGTERM', () => gracefulShutdown('SIGTERM'))