import { WebSocket } from 'ws'; import { IService, ServiceHealth } from './service-manager'; import { CONFIG } from '../config'; const HOST_TERMINAL_MAX_MESSAGE_BYTES = 16 * 1024; export class TerminalSession { private shell: any; private alive = true; private idleTimer!: ReturnType; // Bumped from 5m. Clients now send a liveness ping every ~15s, which // resets the idle timer — so a fully-idle session is one the user really // walked away from. 60m caps the worst-case abandoned-session exposure. private static IDLE_TIMEOUT_MS = 60 * 60 * 1000; private resetIdleTimer(): void { clearTimeout(this.idleTimer); this.idleTimer = setTimeout(() => { console.log('[Terminal] Session idle timeout reached, destroying'); if (this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify({ type: 'error', message: 'Session timed out due to inactivity' })); this.ws.close(1000, 'Idle timeout'); } this.destroy(); }, TerminalSession.IDLE_TIMEOUT_MS); } constructor(private ws: WebSocket) { const pty = require('node-pty'); this.shell = pty.spawn('bash', [], { name: 'xterm-256color', cols: 80, rows: 24, cwd: '/app', env: { HOME: process.env.HOME, PATH: process.env.PATH, TERM: 'xterm-256color' } }); this.resetIdleTimer(); this.shell.onData((data: string) => { if (this.alive) { ws.send(JSON.stringify({ type: 'output', data })); } }); ws.on('message', (msg: string) => { if (Buffer.byteLength(msg.toString()) > HOST_TERMINAL_MAX_MESSAGE_BYTES) { ws.send(JSON.stringify({ type: 'error', message: 'Terminal message too large' })); ws.close(1009, 'Message too large'); this.destroy(); return; } try { const parsed = JSON.parse(msg.toString()); if (parsed.type === 'ping') { // Heartbeat — prove the socket is alive without touching the PTY. // Reset idle timer so heartbeats keep the session warm. this.resetIdleTimer(); if (this.alive && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ type: 'pong', ts: Date.now() })); } return; } if (parsed.type === 'input') { this.resetIdleTimer(); this.shell.write(parsed.data); } else if (parsed.type === 'resize' && parsed.data) { this.shell.resize(parsed.data.cols, parsed.data.rows); } } catch { // Plain text input this.resetIdleTimer(); this.shell.write(msg.toString()); } }); } destroy(): void { if (!this.alive) return; this.alive = false; clearTimeout(this.idleTimer); this.shell.kill(); } } export class TerminalManager implements IService { readonly name = 'terminal'; readonly type = 'terminal' as const; private sessions = new Set(); private maxConnections: number; constructor(maxConnections = 15) { this.maxConnections = maxConnections; } createSession(ws: WebSocket): TerminalSession | null { if (!CONFIG.ENABLE_TERMINAL_WS) { ws.send(JSON.stringify({ type: 'error', message: 'Host terminal WebSocket disabled. Set SUBSTRATE_ENABLE_TERMINAL_WS=true to enable.' })); ws.close(1008, 'Terminal disabled'); return null; } // The host-terminal WS exposes bash inside the substrate container itself // (not a user container) — full access to /data, the Docker socket, and // inherited env. Log prominently so ops can notice unexpected usage. console.warn('[Terminal] Host-terminal session requested — unrestricted bash inside substrate container. ' + 'Prefer /ws?type=container-terminal which scopes to a user container.'); if (this.sessions.size >= this.maxConnections) { ws.send(JSON.stringify({ type: 'error', message: `Terminal connection limit reached (max ${this.maxConnections})` })); ws.close(1008, 'Connection limit'); return null; } try { const session = new TerminalSession(ws); this.sessions.add(session); ws.on('close', () => { this.sessions.delete(session); }); return session; } catch (error) { console.error('[Terminal] PTY Error:', error); ws.send(JSON.stringify({ type: 'error', message: 'PTY not available' })); return null; } } async start(): Promise { // Terminal manager is always ready — sessions are created on demand } async stop(): Promise { for (const session of this.sessions) { session.destroy(); } this.sessions.clear(); } async health(): Promise { return { status: 'running', details: { activeSessions: this.sessions.size, maxConnections: this.maxConnections } }; } }