import fs from 'node:fs'; import http from 'node:http'; import path from 'node:path'; import type Database from 'better-sqlite3'; import express, { type Express, type NextFunction, type Request, type Response } from 'express'; import type { ThrottleMode } from '../shared/schemas/settings.schema.js'; import { AiService } from './ai/ai-service.js'; import { AlertEngine } from './alerts/alert-engine.js'; import { BroadcastService } from './automation/broadcast-service.js'; import { TransferEngine } from './automation/transfer-engine.js'; import { WorkflowEngine } from './automation/workflow-engine.js'; import { ConfigManager } from './config/config-manager.js'; import { resolveRuntimeLimits } from './config/runtime-limits.js'; import { applyDatabaseThrottlePragmas, openDatabase } from './db/database.js'; import { ServerInspector } from './monitoring/inspector.js'; import { MonitoringService } from './monitoring/monitoring-service.js'; import { ProbeRunner } from './monitoring/probes.js'; import { createPrometheusHandler } from './monitoring/prometheus.js'; import { AuditService } from './security/audit.js'; import { AuthService } from './security/auth.js'; import { BackupScheduler } from './security/backup-scheduler.js'; import { DEFAULT_TRUSTED_PROXY_CIDRS, RateLimiter, attachClientIp, createStepUpGuard, isTrustedProxyPeer, } from './security/guards.js'; import { EmergencyRecoveryService } from './security/recovery-store.js'; import { VaultService } from './security/vault.js'; import { KeyManager } from './ssh/key-manager.js'; import { KnownHostsService } from './ssh/known-hosts.js'; import { PTYManager } from './ssh/pty-manager.js'; import { SftpService } from './ssh/sftp-service.js'; import { SSHPool } from './ssh/ssh-pool.js'; import { TunnelManager, extractSubdomainTunnel } from './ssh/tunnel-manager.js'; import { CustomSystemsEngine } from './systems/systems-engine.js'; import { createAiRouter } from './api/routes/ai.routes.js'; import { createAlertsRouter } from './api/routes/alerts.routes.js'; import { createAuditRouter } from './api/routes/audit.routes.js'; import { createAuthRouter } from './api/routes/auth.routes.js'; import { createBackupRouter } from './api/routes/backup.routes.js'; import { createConfigRouter } from './api/routes/config.routes.js'; import { createServersRouter } from './api/routes/servers.routes.js'; import { createSftpRouter } from './api/routes/sftp.routes.js'; import { createSnippetsRouter } from './api/routes/snippets.routes.js'; import { createSystemsRouter } from './api/routes/systems.routes.js'; import { createTerminalRouter } from './api/routes/terminal.routes.js'; import { createProxyRouter, createTunnelsRouter } from './api/routes/tunnels.routes.js'; import { createVaultRouter } from './api/routes/vault.routes.js'; import { createWorkflowsRouter } from './api/routes/workflows.routes.js'; import { WsHub } from './api/ws-hub.js'; export interface ServerOptions { dataDir: string; port: number; host?: string; publicDir?: string; secretFilePath?: string; envMasterKey?: string; envDbKey?: string; trustCloudflare?: boolean; trustedProxyCidrs?: string[]; allowLanTunnels?: boolean; proxyBaseDomain?: string; proxyPort?: number; webauthnRpId?: string; webauthnOrigins?: string[]; metricsToken?: string; throttleModeOverride?: ThrottleMode; autoKeyFile?: boolean; watchConfig?: boolean; } export interface GCoordinatorInstance { app: Express; httpServer: http.Server; db: Database.Database; vaultService: VaultService; authService: AuthService; configManager: ConfigManager; auditService: AuditService; recoveryStore: EmergencyRecoveryService; knownHosts: KnownHostsService; sshPool: SSHPool; keyManager: KeyManager; ptyManager: PTYManager; sftpService: SftpService; tunnelManager: TunnelManager; customSystemsEngine: CustomSystemsEngine; serverInspector: ServerInspector; monitoringService: MonitoringService; backupScheduler: BackupScheduler; transferEngine: TransferEngine; workflowEngine: WorkflowEngine; broadcastService: BroadcastService; alertEngine: AlertEngine; aiService: AiService; wsHub: WsHub; port: number; proxyPort?: number; close(): Promise; } export async function createGCoordinatorServer( options: ServerOptions, ): Promise { const dataDir = path.resolve(options.dataDir); const configDir = path.join(dataDir, 'config'); const dbPath = path.join(dataDir, 'gcoord.db'); const vaultPath = path.join(dataDir, 'vault.enc'); const trustCloudflare = Boolean(options.trustCloudflare); const trustedProxyCidrs = options.trustedProxyCidrs ?? DEFAULT_TRUSTED_PROXY_CIDRS; fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 }); try { fs.chmodSync(dataDir, 0o700); } catch { // Best-effort on filesystems without POSIX permissions } const db = openDatabase(dbPath); const auditService = new AuditService(db); const vaultService = new VaultService(vaultPath, { keyFilePath: path.join(dataDir, 'vault.key'), allowLocalKeyFile: options.autoKeyFile ?? true, }); const recoveryStore = new EmergencyRecoveryService(dataDir); const rateLimiter = new RateLimiter({ db }); const configManager = new ConfigManager(configDir, db, vaultService); await configManager.init({ watch: options.watchConfig ?? true }); const getRuntimeLimits = () => resolveRuntimeLimits( configManager.getSettings().runtime?.throttleMode ?? 'low-resource', options.throttleModeOverride, ); applyDatabaseThrottlePragmas(db, getRuntimeLimits()); const authService = new AuthService(db, { getSecuritySettings: () => configManager.getSettings().security, getRuntimeLimits, recoveryStore, vaultService, dataDir, envDbKey: options.envDbKey, }); const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup ? recoveryStore.readSavedMasterKeyHex() : undefined; const runtimeInit = vaultService.initRuntime({ secretFilePath: options.secretFilePath, envKey: options.envMasterKey, backupKey, autoCreateIfMissing: true, }); if (runtimeInit.runtimeReady) { configManager.recomputeWarnings(); if (authService.isBootstrapped()) { authService.syncRecovery(); } } const app = express(); app.locals.auditService = auditService; app.disable('x-powered-by'); if (trustCloudflare) { app.set('trust proxy', (ip: string) => isTrustedProxyPeer(ip, trustedProxyCidrs)); } const httpServer = http.createServer(app); const wsHub = new WsHub(httpServer, authService, vaultService, { trustCloudflare }); authService.onSessionsRevoked((idHashes) => { wsHub.disconnectSessions(idHashes); }); const knownHosts = new KnownHostsService(db, auditService); const sshPool = new SSHPool(configManager, vaultService, knownHosts); const keyManager = new KeyManager(sshPool, vaultService, configManager, auditService); const ptyManager = new PTYManager(sshPool, configManager, wsHub, getRuntimeLimits); const sftpService = new SftpService(sshPool); const tunnelManager = new TunnelManager(sshPool, configManager, vaultService, authService, { getRuntimeLimits, allowLanTunnels: options.allowLanTunnels, proxyBaseDomain: options.proxyBaseDomain, proxyPort: options.proxyPort, trustCloudflare, }); const customSystemsEngine = new CustomSystemsEngine( sshPool, configManager, vaultService, ptyManager, wsHub, getRuntimeLimits, ); const serverInspector = new ServerInspector(sshPool, configManager); const probeRunner = new ProbeRunner(sshPool, configManager); const monitoringService = new MonitoringService( db, configManager, vaultService, sshPool, probeRunner, getRuntimeLimits, ); const transferEngine = new TransferEngine(sshPool, sftpService, configManager, knownHosts); const workflowEngine = new WorkflowEngine( db, configManager, vaultService, sshPool, sftpService, customSystemsEngine, transferEngine, wsHub, auditService, getRuntimeLimits, ); const broadcastService = new BroadcastService( configManager, vaultService, sshPool, wsHub, auditService, db, getRuntimeLimits, ); const alertEngine = new AlertEngine( db, configManager, vaultService, monitoringService, sshPool, customSystemsEngine, workflowEngine, wsHub, auditService, ); const aiService = new AiService( configManager, vaultService, sshPool, wsHub, auditService, getRuntimeLimits, ); const backupScheduler = new BackupScheduler( dataDir, db, configManager, vaultService, sftpService, auditService, getRuntimeLimits, ); wsHub.registerHostUpgradeHandler((req, socket, head) => { const tunnelSub = extractSubdomainTunnel(req.headers.host, options.proxyBaseDomain); if (!tunnelSub) return false; tunnelManager.handleSubdomainProxyWs(req, socket, head, tunnelSub); return true; }); wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => { tunnelManager.handleWsProxyUpgrade(req, socket, head); }); wsHub.attachPtyHandlers({ onInput: (sessionId, data) => { ptyManager.writeInput(sessionId, data); }, onResize: (sessionId, cols, rows) => { ptyManager.resize(sessionId, cols, rows); }, }); wsHub.attachAiHandlers({ onCancel: (chatId) => { aiService.cancelChat(chatId); }, }); wsHub.onChannelSubscribe((ctx, channel) => { if (channel.startsWith('pty:')) { const sessionId = channel.slice('pty:'.length); const scrollback = ptyManager.getScrollback(sessionId); if (scrollback !== null && scrollback.length > 0) { ctx.send({ type: 'pty:output', sessionId, data: scrollback, replay: true, }); } const session = ptyManager.getSession(sessionId); if (session?.exited) { ctx.send({ type: 'pty:exit', sessionId, exitCode: session.exitCode, }); } } else if (channel.startsWith('stream:')) { const jobId = channel.slice('stream:'.length); const replay = jobId.startsWith('wf:') ? workflowEngine.getStreamReplayFrames(jobId) : jobId.startsWith('bcast-') ? broadcastService.getStreamReplayFrames(jobId) : customSystemsEngine.getStreamReplayFrames(jobId); for (const frame of replay) { ctx.send(frame); } } else if (channel.startsWith('ai:')) { const chatId = channel.slice('ai:'.length); for (const frame of aiService.getReplayFrames(chatId)) { ctx.send(frame); } } else if (channel === 'metrics') { ctx.send({ type: 'servers:state', states: sshPool.getStates() }); } }); app.use((req, res, next) => { const tunnelSub = extractSubdomainTunnel(req.headers.host, options.proxyBaseDomain); if (tunnelSub) { tunnelManager.handleSubdomainProxyHttp(req, res, tunnelSub); return; } next(); }); app.use((req, res, next) => { res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('Referrer-Policy', 'no-referrer'); res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()'); if (req.secure || trustCloudflare) { res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains'); } if (req.path.startsWith('/api/')) { res.setHeader('Cache-Control', 'no-store'); res.setHeader('Pragma', 'no-cache'); } if (!req.path.startsWith('/proxy/')) { const rawHost = typeof req.headers.host === 'string' ? req.headers.host.trim() : ''; const safeHost = /^[A-Za-z0-9.\-:\[\]]+$/.test(rawHost) ? rawHost : ''; const connectSrc = safeHost ? `'self' ws://${safeHost} wss://${safeHost}` : `'self'`; res.setHeader('X-Frame-Options', 'DENY'); res.setHeader( 'Content-Security-Policy', `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src ${connectSrc}; object-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'self'`, ); } next(); }); app.use(attachClientIp(trustCloudflare, trustedProxyCidrs)); // Mount /proxy before express.json so proxied POST/PUT payloads stream untouched upstream app.use('/proxy', createProxyRouter({ authService, tunnelManager })); const jsonParser = express.json({ limit: '2mb' }); const backupJsonParser = express.json({ limit: '16mb' }); app.use((req, res, next) => { if (req.path.endsWith('/sftp/upload')) { next(); return; } if (req.path.startsWith('/api/backup/')) { backupJsonParser(req, res, next); return; } jsonParser(req, res, next); }); sshPool.onStateChange((states) => { wsHub.broadcastChannel('metrics', { type: 'servers:state', states }); for (const s of states) { if (s.hostKeyMismatch) { wsHub.broadcastChannel('alerts', { type: 'alerts:update', activeCount: alertEngine.getActiveCount() + knownHosts.listPendingMismatches().length, hostKeyMismatch: s.hostKeyMismatch, }); } } }); monitoringService.onTick((event) => { wsHub.broadcastChannel('metrics', { type: 'metrics:tick', serverId: event.serverId, sample: event.sample, disks: event.disks, probes: event.probes, }); }); authService.setSecurityEventListener((ev) => { void alertEngine.emitSecurityEvent(ev.type, { ip: ev.ip, details: ev.details, message: `${ev.type}${ev.ip ? ` from ${ev.ip}` : ''}`, }); }); knownHosts.onHostKeyMismatch((alert) => { void alertEngine.emitSecurityEvent('ssh.host_key_mismatch', { serverId: alert.serverId, message: `Host key mismatch on ${alert.hostPortKey} (${alert.algorithm})`, }); }); monitoringService.start(); void tunnelManager.syncAutoStart(); customSystemsEngine.syncBackgroundChecks(); workflowEngine.start(); alertEngine.start(); backupScheduler.start(); auditService.pruneOlderThan(configManager.getSettings().auditRetentionDays); vaultService.onSeal(() => { aiService.cancelAll(); backupScheduler.stop(); alertEngine.handlePanicLock(); workflowEngine.handlePanicLock(); broadcastService.cancelAll(); monitoringService.stopAll(); customSystemsEngine.stopBackgroundChecks(); customSystemsEngine.cancelAllStreams(); tunnelManager.stopAll(); ptyManager.closeAll(true); sshPool.closeAll('vault_sealed'); }); vaultService.onPanicLock(() => { void alertEngine.emitSecurityEvent('vault.panic_lock', { message: 'Emergency Panic Lock activated', }); aiService.cancelAll(); backupScheduler.stop(); alertEngine.handlePanicLock(); workflowEngine.handlePanicLock(); broadcastService.cancelAll(); monitoringService.stopAll(); customSystemsEngine.stopBackgroundChecks(); customSystemsEngine.cancelAllStreams(); tunnelManager.stopAll(); ptyManager.closeAll(true); sshPool.closeAll('panic_lock'); wsHub.handlePanicLock(); authService.revokeAllSessions(); }); configManager.onChange((event) => { wsHub.broadcastChannel('config', { type: 'config:updated', entityType: event.entityType, id: event.id, warnings: event.warnings, errors: event.errors, }); if (event.entityType === 'alerts' || event.entityType === 'server' || event.entityType === 'all') { alertEngine.syncWithConfig(); } if ( event.entityType === 'server' || event.entityType === 'system' || event.entityType === 'workflow' || event.entityType === 'settings' || event.entityType === 'all' ) { if (event.entityType === 'server' && event.id) { sshPool.closeServer(event.id); ptyManager.closeServerSessions(event.id); tunnelManager.stopServerTunnels(event.id); customSystemsEngine.invalidateCache(event.id); } else if (event.entityType === 'system' && event.id) { customSystemsEngine.invalidateCache(undefined, event.id); } else if (event.entityType === 'all') { customSystemsEngine.invalidateCache(); } if (event.entityType === 'settings' || event.entityType === 'all') { applyDatabaseThrottlePragmas(db, getRuntimeLimits()); if (!configManager.getSettings().security.enableEmergencySecretsBackup) { recoveryStore.wipeAll(); } else { authService.syncRecovery(); } backupScheduler.sync(); } if (event.entityType === 'server' || event.entityType === 'all') { monitoringService.syncServers(); void tunnelManager.syncAutoStart(); } if ( event.entityType === 'server' || event.entityType === 'system' || event.entityType === 'all' ) { customSystemsEngine.syncBackgroundChecks(); } if (event.entityType === 'workflow' || event.entityType === 'all') { workflowEngine.syncCronJobs(); } } }); const stepUpGuard = createStepUpGuard( authService, () => configManager.getSettings().security.stepUpPolicy, ); app.get('/api/healthz', (_req, res) => { res.json({ ok: true }); }); app.use( '/api/auth', createAuthRouter({ authService, vaultService, configManager, auditService, recoveryStore, rateLimiter, trustCloudflare, webauthnRpId: options.webauthnRpId, webauthnOrigins: options.webauthnOrigins, }), ); const { vaultRouter, panicLockHandler } = createVaultRouter({ authService, vaultService, configManager, auditService, rateLimiter, wsHub, stepUpGuard, onVaultUnlocked: () => { monitoringService.syncServers(); customSystemsEngine.syncBackgroundChecks(); workflowEngine.syncCronJobs(); backupScheduler.sync(); void tunnelManager.syncAutoStart(); }, onVaultChanged: (snapshotReason) => { authService.syncRecovery({ snapshotReason }); }, }); app.use('/api/vault', vaultRouter); app.use('/api/security', panicLockHandler); app.use( '/api/backup', createBackupRouter({ dataDir, db, authService, vaultService, configManager, auditService, stepUpGuard, getRuntimeLimits, backupScheduler, onRestored: async ({ inner, vaultKeyCandidate }) => { if (inner.vaultEnvelopeRaw !== null) { try { vaultService.reloadFromDisk(vaultKeyCandidate); } catch { // Avoid keeping an old runtime master key unlocked against a newly restored foreign vault vaultService.seal(); vaultService.dropLocalKeyFile(); } } knownHosts.replaceAllKnownHosts(inner.knownHosts); configManager.reloadAllFromDisk(); sshPool.syncWithConfig(); backupScheduler.sync(); if ( authService.isBootstrapped() && vaultService.isRuntimeReady && configManager.getSettings().security.enableEmergencySecretsBackup ) { authService.syncRecovery({ snapshotReason: 'backup-restore' }); } wsHub.broadcastAll({ type: 'vault:state', vaultState: vaultService.state, vaultRuntimeReady: vaultService.isRuntimeReady, isPanicLocked: vaultService.isPanicLocked, }); }, }), ); app.use('/api/terminal', createTerminalRouter({ authService, configManager, auditService, ptyManager })); app.use( '/api/tunnels', createTunnelsRouter({ authService, configManager, auditService, tunnelManager }), ); app.use( '/api/systems', createSystemsRouter({ authService, auditService, systemsEngine: customSystemsEngine, stepUpGuard, }), ); app.use( '/api/workflows', createWorkflowsRouter({ authService, configManager, auditService, workflowEngine, broadcastService, }), ); app.use( '/api/snippets', createSnippetsRouter({ authService, configManager, auditService }), ); app.use( '/api/alerts', createAlertsRouter({ authService, configManager, auditService, alertEngine, stepUpGuard }), ); app.use('/api/ai', createAiRouter({ authService, aiService, stepUpGuard })); app.use( '/api/servers/:id/sftp', createSftpRouter({ authService, configManager, auditService, sftpService, stepUpGuard }), ); app.use( '/api/servers', createServersRouter({ authService, configManager, auditService, vaultService, knownHosts, sshPool, keyManager, serverInspector, monitoringService, stepUpGuard, onKeysMutated: (snapshotReason) => { authService.syncRecovery({ snapshotReason }); }, }), ); app.use( '/api/config', createConfigRouter({ authService, configManager, auditService, stepUpGuard }), ); app.use('/api/audit', createAuditRouter(authService, auditService)); app.get( '/metrics', createPrometheusHandler({ configManager, vaultService, sshPool, monitoringService, tunnelManager, alertEngine, }), ); app.use('/api', (_req, res) => { res.status(404).json({ error: 'API_ROUTE_NOT_FOUND' }); }); const publicDir = options.publicDir ?? path.resolve(process.cwd(), 'dist', 'public'); if (fs.existsSync(publicDir)) { app.use(express.static(publicDir, { index: false })); app.get('*', (_req, res) => { res.sendFile(path.join(publicDir, 'index.html')); }); } app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => { const statusErr = err as { status?: number; type?: string; message?: string }; const status = typeof statusErr?.status === 'number' && statusErr.status >= 400 && statusErr.status < 600 ? statusErr.status : 500; if (!res.headersSent) { res.status(status).json({ error: status === 413 || statusErr?.type === 'entity.too.large' ? 'PAYLOAD_TOO_LARGE' : status < 500 ? 'BAD_REQUEST' : 'INTERNAL_SERVER_ERROR', message: status < 500 && statusErr?.message ? statusErr.message : 'Internal server error', }); } }); await tunnelManager.startProxyServer(); await new Promise((resolve, reject) => { httpServer.once('error', reject); httpServer.listen(options.port, options.host ?? '0.0.0.0', () => { httpServer.off('error', reject); resolve(); }); }); const address = httpServer.address(); const actualPort = typeof address === 'object' && address ? address.port : options.port; return { app, httpServer, db, vaultService, authService, configManager, auditService, recoveryStore, knownHosts, sshPool, keyManager, ptyManager, sftpService, tunnelManager, customSystemsEngine, serverInspector, monitoringService, backupScheduler, transferEngine, workflowEngine, broadcastService, alertEngine, aiService, wsHub, port: actualPort, proxyPort: tunnelManager.actualProxyPort, async close() { aiService.close(); backupScheduler.close(); alertEngine.close(); workflowEngine.close(); broadcastService.cancelAll(); monitoringService.close(); customSystemsEngine.close(); tunnelManager.stopAll(); await tunnelManager.stopProxyServer(); ptyManager.close(); sshPool.closeAll('shutdown'); authService.close(); wsHub.close(); await configManager.close(); await new Promise((resolve) => { httpServer.close(() => resolve()); }); db.close(); }, }; }