/** * Node.js-compatible RCS server entry. * * Uses @hono/node-server + @hono/node-ws (available via acp-link workspace). * At build time, Vite bundles these into dist/cli-node.js so the published * npm package needs zero additional dependencies. * * Usage: * slz rcs (zero-config: API key defaults to sk-slz) * slz rcs one (single-user mode: admin/admin123, workers auto-owned) * RCS_API_KEYS=sk-1234 slz rcs */ import { serve } from '@hono/node-server' import { serveStatic } from '@hono/node-server/serve-static' import { createNodeWebSocket } from '@hono/node-ws' import { Hono } from 'hono' import { cors } from 'hono/cors' import { logger } from 'hono/logger' import type { Context, Next } from 'hono' import { config } from './config.js' import { registerRoutes } from './registerRoutes.js' import { webCorsOptions } from './auth/cors.js' import { closeAllConnections } from './transport/ws-handler.js' import { closeAllAcpConnections } from './transport/acp-ws-handler.js' import { closeAllRelayConnections } from './transport/acp-relay-handler.js' import { startDisconnectMonitor } from './services/disconnect-monitor.js' import { setMemoryBackend, type MemoryBackend, } from './services/memoryBackend.js' import { ensureSingleUserAdmin, SINGLE_USER_DEFAULT_PASSWORD, SINGLE_USER_USERNAME, } from './services/single-user.js' export interface RcsServerOptions { apiKeys: string[] port?: number host?: string /** Single-user mode (`slz rcs one`): auto-init admin account, workers * auto-owned, registration disabled, host defaults to 127.0.0.1. */ singleUser?: boolean /** Embedded mode: the server shares its process with something else that * owns the terminal and the process lifecycle (e.g. `slz rcs one` boots * an in-process REPL as the single repl worker). Skips the SIGINT/SIGTERM * handlers — they would process.exit(0) on the REPL's first Ctrl+C — and * skips the block-forever await so the caller can continue booting. */ embedded?: boolean /** In-process memory backend (memdir) for composite hosts (`slz rcs one`). * When provided, the `/web/memory/*` routes serve from it; otherwise they * report mode='sqlite' and the multi-user SQLite store stays in charge. */ memoryBackend?: MemoryBackend } /** Bound server coordinates, as returned by startRcsServer. */ export interface RcsServerInfo { port: number /** The address the server actually bound (may be 0.0.0.0). */ host: string /** Browser-reachable origin (0.0.0.0/:: mapped to localhost). */ webUiUrl: string } export async function startRcsServer( opts: RcsServerOptions, ): Promise { // Set env vars so config module picks them up process.env.RCS_API_KEYS = opts.apiKeys.join(',') // The config module may already be evaluated (static import above) — its // env-derived values are frozen, so apiKeys/host/port must also be applied // to the live object or they would silently no-op. config.apiKeys = opts.apiKeys if (opts.port) { process.env.RCS_PORT = String(opts.port) config.port = opts.port } if (opts.host) { process.env.RCS_HOST = opts.host config.host = opts.host } if (opts.singleUser) process.env.RCS_SINGLE_USER = 'true' if (opts.memoryBackend) setMemoryBackend(opts.memoryBackend) // Effective single-user mode: the `one` argument OR RCS_SINGLE_USER=true // set before process start (config.singleUser already reflects the env). const singleUser = opts.singleUser || config.singleUser // The config module may already be evaluated (static import above), so // reflect single-user mode on the live object too — request-time reads // (allowRegistration, route gates) must see it regardless of import order. if (singleUser) { config.singleUser = true config.allowRegistration = false // Local convenience mode: bind loopback unless the operator explicitly // chose a host (RCS_HOST at process start or opts.host above). if (!process.env.RCS_HOST) { config.host = '127.0.0.1' } } const port = config.port const host = config.host const app = new Hono() // Create Node.js WebSocket adapter const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app }) // Middleware. Per-request hono logger only in standalone mode — embedded // mode shares the terminal with the host flow (`slz rcs one` boots an // in-process REPL on top of the server), so request spam would just be // noise. if (!opts.embedded) { app.use('*', logger()) } app.use('*', async (c: Context, next: Next) => { 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: Context) => c.json({ status: 'ok', version: config.version }), ) // Register all routes with Node.js serveStatic and upgradeWebSocket registerRoutes(app, serveStatic as any, upgradeWebSocket) // Single-user mode: bootstrap the sole admin account (admin/admin123 on // first deployment) BEFORE the server accepts requests, so every worker // registration can resolve an owner and no request ever races the setup. let singleUserAdmin: Awaited> = null if (singleUser) { try { singleUserAdmin = await ensureSingleUserAdmin() } catch (err) { console.error('[RCS] Single-user admin bootstrap failed:', err) throw err } if (!singleUserAdmin) { throw new Error( '[RCS] Single-user mode requires an empty or admin-bearing users ' + 'table, but the existing DB has neither. Run `slz rcs` (full mode) ' + 'or point RCS_DB_PATH at a fresh database.', ) } } // Start HTTP server const server = serve({ fetch: app.fetch, port, hostname: host, }) // Port conflicts (EADDRINUSE) surface asynchronously as an 'error' event — // without a listener the process crashes with an ugly unhandled error. // Embedded mode keeps running (the REPL owns the process; the bridge will // talk to whatever server already owns the port); standalone exits loudly. server.on('error', (err: NodeJS.ErrnoException) => { console.error(`[RCS] Server error: ${err.message}`) if (!opts.embedded) { // eslint-disable-next-line custom-rules/no-process-exit process.exit(1) } if (opts.singleUser && err.code === 'EADDRINUSE') { // Single-user embedded mode (`slz rcs one` / `/rcs one`) breaks // silently when another RCS instance owns the port: the one-time // login codes and the worker-session poll live in THIS process's // memory, while the browser talks to the OTHER server — its /otp/ // route doesn't know the code and bounces the user to the login // page, defeating the auto-open-into-session flow. Fail loudly. console.error( '[RCS] Single-user mode needs this process to own the port ' + '(one-time login codes are in-memory). ' + 'Stop the other RCS instance or set RCS_PORT.', ) // eslint-disable-next-line custom-rules/no-process-exit process.exit(1) } }) // Inject WebSocket support for Node.js injectWebSocket(server) // Start disconnect monitor. Unref'd: the HTTP server (standalone) or the // host process (embedded) owns the event loop — the interval must not // keep an exited REPL's process alive. const monitorTimer = startDisconnectMonitor() if (monitorTimer.unref) { monitorTimer.unref() } console.log( `[RCS] Remote Control Server starting on ${host}:${port} (Node.js)`, ) 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`) // Browsers block 0.0.0.0 (Chrome Private Network Access); show localhost for clickable URL. const webUiHost = host === '0.0.0.0' || host === '::' ? 'localhost' : host console.log(`[RCS] Web UI: http://${webUiHost}:${port}/code/`) if (singleUser) { console.log('[RCS] Single-user mode (slz rcs one):') if (singleUserAdmin?.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: ${singleUserAdmin?.username ?? SINGLE_USER_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)', ) } const workerBaseUrl = config.baseUrl || `http://${webUiHost}:${port}` console.log('[RCS] Worker connect:') console.log( '[RCS] same host: zero config — workers default to http://localhost:3000 + sk-slz', ) if (!singleUser) { console.log( `[RCS] remote host: export SALUZI_BRIDGE_BASE_URL=${workerBaseUrl}`, ) console.log( '[RCS] export SALUZI_BRIDGE_OAUTH_TOKEN=', ) } // Embedded mode: the caller owns the process lifecycle (e.g. `slz rcs one` // boots an in-process REPL as the single repl worker). No signal handlers // — they would process.exit(0) on the REPL's first Ctrl+C — and no // block-forever: return the bound coordinates so the caller can wire the // in-process bridge + browser to it. if (opts.embedded) { return { port, host, webUiUrl: `http://${webUiHost}:${port}` } } // Graceful shutdown function gracefulShutdown(signal: string) { console.log(`\n[RCS] Received ${signal}, shutting down...`) closeAllConnections() closeAllAcpConnections() closeAllRelayConnections() server.close() process.exit(0) } process.on('SIGINT', () => gracefulShutdown('SIGINT')) process.on('SIGTERM', () => gracefulShutdown('SIGTERM')) // Block forever — server keeps running. The promise never resolves; it // only exists so the caller's await parks and the return type holds. return new Promise(() => {}) }