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' 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) 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() // 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) } const reapInterval = setInterval( () => { try { const db = getDb() reapExpiredSessions(db) } 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'))