diff --git a/src/server/ssh/known-hosts.ts b/src/server/ssh/known-hosts.ts new file mode 100644 index 0000000..a3148f3 --- /dev/null +++ b/src/server/ssh/known-hosts.ts @@ -0,0 +1,287 @@ +import crypto from 'node:crypto'; +import type Database from 'better-sqlite3'; +import type { ServerConfig } from '../../shared/schemas/server.schema.js'; +import type { HostKeyAlert, PendingTofuInfo } from '../../shared/ws-protocol.js'; +import type { AuditService } from '../security/audit.js'; + +export interface KnownHostRecord { + hostPort: string; + algorithm: string; + fingerprint: string; + trustedAt: number; + updatedAt: number; +} + +export function buildHostPortKey(server: Pick): string { + const hostLower = server.host.trim().toLowerCase(); + return server.jumpHostId + ? `${server.jumpHostId}->${hostLower}:${server.port}` + : `${hostLower}:${server.port}`; +} + +export function parseHostKeyBuffer(keyBuf: Buffer): { + algorithm: string; + fingerprint: string; +} { + let algorithm = 'unknown'; + if (keyBuf.length >= 4) { + const algoLen = keyBuf.readUInt32BE(0); + if (algoLen > 0 && 4 + algoLen <= keyBuf.length) { + algorithm = keyBuf.subarray(4, 4 + algoLen).toString('ascii'); + } + } + const digest = crypto + .createHash('sha256') + .update(keyBuf) + .digest('base64') + .replace(/=+$/, ''); + return { + algorithm, + fingerprint: `SHA256:${digest}`, + }; +} + +export class KnownHostsService { + private readonly pendingTofu = new Map(); + private readonly pendingMismatches = new Map(); + private readonly listeners = new Set<() => void>(); + + constructor( + private readonly db: Database.Database, + private readonly auditService?: AuditService, + ) {} + + onChange(listener: () => void): () => void { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + } + + verifyServerHostKey(server: ServerConfig, keyBuf: Buffer): boolean { + const hostPortKey = buildHostPortKey(server); + const { algorithm, fingerprint } = parseHostKeyBuffer(keyBuf); + const now = Date.now(); + + const row = this.db + .prepare( + 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts WHERE host_port = ?', + ) + .get(hostPortKey) as KnownHostRecord | undefined; + + if (row) { + if (row.fingerprint === fingerprint) { + const hadPending = + this.pendingTofu.delete(server.id) || this.pendingMismatches.delete(server.id); + this.db + .prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ?') + .run(now, hostPortKey); + if (hadPending) this.emitChange(); + return true; + } + + const alert: HostKeyAlert = { + serverId: server.id, + hostPortKey, + host: server.host, + port: server.port, + algorithm, + expectedFingerprint: row.fingerprint, + actualFingerprint: fingerprint, + detectedAt: now, + }; + this.pendingTofu.delete(server.id); + this.pendingMismatches.set(server.id, alert); + this.auditService?.log({ + action: 'ssh.host_key_mismatch', + actorIp: 'hub', + target: server.id, + status: 'denied', + details: { + hostPortKey, + expected: row.fingerprint, + actual: fingerprint, + }, + }); + this.emitChange(); + return false; + } + + // No known_hosts entry yet: check optional pre-seeded fingerprint in server JSON + if (server.hostKeyFingerprint) { + const expected = server.hostKeyFingerprint.trim(); + if (expected === fingerprint) { + this.upsertKnownHost(hostPortKey, algorithm, fingerprint, now); + this.pendingTofu.delete(server.id); + this.pendingMismatches.delete(server.id); + this.auditService?.log({ + action: 'ssh.host_key_preseeded', + actorIp: 'hub', + target: server.id, + status: 'ok', + details: { hostPortKey, fingerprint }, + }); + this.emitChange(); + return true; + } + + const alert: HostKeyAlert = { + serverId: server.id, + hostPortKey, + host: server.host, + port: server.port, + algorithm, + expectedFingerprint: expected, + actualFingerprint: fingerprint, + detectedAt: now, + }; + this.pendingMismatches.set(server.id, alert); + this.auditService?.log({ + action: 'ssh.host_key_mismatch', + actorIp: 'hub', + target: server.id, + status: 'denied', + details: { hostPortKey, expected, actual: fingerprint }, + }); + this.emitChange(); + return false; + } + + // Strict TOFU: pause and require explicit admin confirmation + this.pendingMismatches.delete(server.id); + this.pendingTofu.set(server.id, { + serverId: server.id, + hostPortKey, + host: server.host, + port: server.port, + algorithm, + fingerprint, + firstSeenAt: now, + }); + this.emitChange(); + return false; + } + + approveTofu(serverId: string, fingerprint: string): KnownHostRecord { + const pending = this.pendingTofu.get(serverId); + if (!pending) { + throw new Error(`No pending TOFU host key awaiting approval for "${serverId}"`); + } + if (pending.fingerprint !== fingerprint.trim()) { + throw new Error('TOFU fingerprint mismatch; re-verify before approving'); + } + + const now = Date.now(); + this.upsertKnownHost(pending.hostPortKey, pending.algorithm, pending.fingerprint, now); + this.pendingTofu.delete(serverId); + this.emitChange(); + + return { + hostPort: pending.hostPortKey, + algorithm: pending.algorithm, + fingerprint: pending.fingerprint, + trustedAt: now, + updatedAt: now, + }; + } + + resetMismatch(serverId: string, newFingerprint: string): KnownHostRecord { + const mismatch = this.pendingMismatches.get(serverId); + if (!mismatch) { + throw new Error(`No host key mismatch recorded for "${serverId}"`); + } + if (mismatch.actualFingerprint !== newFingerprint.trim()) { + throw new Error('Provided fingerprint does not match observed remote host key'); + } + + const now = Date.now(); + this.upsertKnownHost( + mismatch.hostPortKey, + mismatch.algorithm, + mismatch.actualFingerprint, + now, + ); + this.pendingMismatches.delete(serverId); + this.emitChange(); + + return { + hostPort: mismatch.hostPortKey, + algorithm: mismatch.algorithm, + fingerprint: mismatch.actualFingerprint, + trustedAt: now, + updatedAt: now, + }; + } + + clearServerPending(serverId: string): void { + const changed = + this.pendingTofu.delete(serverId) || this.pendingMismatches.delete(serverId); + if (changed) this.emitChange(); + } + + getPendingTofu(serverId: string): PendingTofuInfo | undefined { + return this.pendingTofu.get(serverId); + } + + listPendingTofu(): PendingTofuInfo[] { + return [...this.pendingTofu.values()]; + } + + getPendingMismatch(serverId: string): HostKeyAlert | undefined { + return this.pendingMismatches.get(serverId); + } + + listPendingMismatches(): HostKeyAlert[] { + return [...this.pendingMismatches.values()]; + } + + listKnownHosts(): KnownHostRecord[] { + return this.db + .prepare( + 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC', + ) + .all() as KnownHostRecord[]; + } + + deleteKnownHost(hostPort: string): boolean { + const res = this.db + .prepare('DELETE FROM known_hosts WHERE host_port = ?') + .run(hostPort); + for (const [sid, p] of this.pendingTofu.entries()) { + if (p.hostPortKey === hostPort) this.pendingTofu.delete(sid); + } + for (const [sid, m] of this.pendingMismatches.entries()) { + if (m.hostPortKey === hostPort) this.pendingMismatches.delete(sid); + } + if (res.changes > 0) this.emitChange(); + return res.changes > 0; + } + + private upsertKnownHost( + hostPortKey: string, + algorithm: string, + fingerprint: string, + now: number, + ): void { + this.db + .prepare( + `INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at) + VALUES (?, ?, ?, ?, ?) + ON CONFLICT(host_port) DO UPDATE SET + algorithm = excluded.algorithm, + fingerprint = excluded.fingerprint, + updated_at = excluded.updated_at`, + ) + .run(hostPortKey, algorithm, fingerprint, now, now); + } + + private emitChange(): void { + for (const listener of this.listeners) { + try { + listener(); + } catch { + // Isolate subscriber failures + } + } + } +} diff --git a/src/server/ssh/ssh-pool.ts b/src/server/ssh/ssh-pool.ts new file mode 100644 index 0000000..e9d925c --- /dev/null +++ b/src/server/ssh/ssh-pool.ts @@ -0,0 +1,757 @@ +import type { Duplex } from 'node:stream'; +import ssh2, { type Client, type ConnectConfig } from 'ssh2'; +import type { ServerConfig } from '../../shared/schemas/server.schema.js'; +import type { + ServerConnectionStatus, + ServerRuntimeState, +} from '../../shared/ws-protocol.js'; +import type { ConfigManager } from '../config/config-manager.js'; +import type { VaultService } from '../security/vault.js'; +import type { KnownHostsService } from './known-hosts.js'; +import { buildEnvPrefix, prepareSudoExecution } from './sudo.js'; + +export interface ExecResult { + stdout: string; + stderr: string; + exitCode: number | null; + signal?: string; + durationMs: number; +} + +export interface ExecOptions { + sudo?: boolean; + timeoutMs?: number; + env?: Record; + stdin?: Buffer | string; + maxBytes?: number; +} + +interface PooledConnection { + serverId: string; + client: Client; + connectedAt: number; + jumpHostId?: string; + childIds: Set; +} + +const DEFAULT_EXEC_TIMEOUT_MS = 30_000; +const DEFAULT_MAX_BYTES = 2 * 1024 * 1024; + +export class SSHPool { + private readonly connections = new Map(); + private readonly inFlight = new Map>(); + private readonly states = new Map(); + private readonly reconnectTimers = new Map(); + private readonly reconnectAttempts = new Map(); + private readonly stateListeners = new Set<(states: ServerRuntimeState[]) => void>(); + private closed = false; + + constructor( + private readonly configManager: ConfigManager, + private readonly vaultService: VaultService, + private readonly knownHosts: KnownHostsService, + ) { + this.knownHosts.onChange(() => { + this.refreshStatesFromKnownHosts(); + }); + } + + onStateChange(listener: (states: ServerRuntimeState[]) => void): () => void { + this.stateListeners.add(listener); + return () => { + this.stateListeners.delete(listener); + }; + } + + getStates(): ServerRuntimeState[] { + const out: ServerRuntimeState[] = []; + for (const server of this.configManager.listServers()) { + out.push(this.buildStateForServer(server)); + } + return out; + } + + getState(serverId: string): ServerRuntimeState | undefined { + const server = this.configManager.getServer(serverId); + return server ? this.buildStateForServer(server) : undefined; + } + + setOsDetected(serverId: string, os: 'linux' | 'bsd' | 'macos'): void { + const prev = this.states.get(serverId) ?? { + serverId, + status: 'connected' as ServerConnectionStatus, + }; + if (prev.osDetected !== os) { + this.states.set(serverId, { ...prev, osDetected: os }); + this.emitStates(); + } + } + + async acquireClient( + serverId: string, + visited: Set = new Set(), + ): Promise { + if (this.closed) { + throw new Error('SSHPool is closed'); + } + + const server = this.configManager.getServer(serverId); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); + } + if (!server.enabled) { + this.updateState(serverId, { status: 'disabled' }); + throw new Error(`Server "${serverId}" is disabled`); + } + if (this.vaultService.state !== 'unlocked') { + this.updateState(serverId, { + status: 'vault_locked', + lastError: 'Vault is locked', + }); + throw new Error('Vault is locked'); + } + + if (visited.has(serverId)) { + throw new Error(`ProxyJump cycle detected involving "${serverId}"`); + } + + const existing = this.connections.get(serverId); + if (existing) { + return existing.client; + } + + const pending = this.inFlight.get(serverId); + if (pending) { + return pending; + } + + const nextVisited = new Set(visited); + nextVisited.add(serverId); + + const connectPromise = this.connectServer(server, nextVisited).finally(() => { + this.inFlight.delete(serverId); + }); + this.inFlight.set(serverId, connectPromise); + return connectPromise; + } + + async exec( + serverId: string, + command: string, + opts: ExecOptions = {}, + ): Promise { + const client = await this.acquireClient(serverId); + const server = this.configManager.getServer(serverId); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); + } + + const envPrefix = buildEnvPrefix(opts.env); + let finalCommand = `${envPrefix}${command}`; + let stdinBuf: Buffer | undefined = + opts.stdin === undefined + ? undefined + : typeof opts.stdin === 'string' + ? Buffer.from(opts.stdin, 'utf8') + : Buffer.from(opts.stdin); + + if (opts.sudo) { + let sudoPassword: string | undefined; + if (server.sudoCredentialId) { + const sudoCred = this.vaultService.getSecret(server.sudoCredentialId); + if (sudoCred && (sudoCred.type === 'sudo-password' || sudoCred.type === 'ssh-password')) { + sudoPassword = sudoCred.password; + } + } + const prepared = prepareSudoExecution(finalCommand, { + sudoPassword, + stdin: stdinBuf, + }); + if (stdinBuf) stdinBuf.fill(0); + finalCommand = prepared.command; + stdinBuf = prepared.stdin; + } + + const timeoutMs = opts.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS; + const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES; + const started = Date.now(); + + return new Promise((resolve, reject) => { + let settled = false; + let timer: NodeJS.Timeout | null = null; + const stdoutChunks: Buffer[] = []; + const stderrChunks: Buffer[] = []; + let totalBytes = 0; + + client.exec(finalCommand, (err, stream) => { + if (err) { + if (stdinBuf) stdinBuf.fill(0); + reject(err); + return; + } + + const finish = (fn: () => void) => { + if (settled) return; + settled = true; + if (timer) clearTimeout(timer); + if (stdinBuf) stdinBuf.fill(0); + fn(); + }; + + timer = setTimeout(() => { + try { + stream.close(); + } catch { + // Ignore close errors on timeout + } + finish(() => + reject(new Error(`SSH exec timed out after ${timeoutMs}ms on "${serverId}"`)), + ); + }, timeoutMs); + + if (stdinBuf && stdinBuf.length > 0) { + stream.stdin.write(stdinBuf); + stdinBuf.fill(0); + } + stream.stdin.end(); + + stream.on('data', (chunk: Buffer) => { + if (totalBytes < maxBytes) { + const slice = + totalBytes + chunk.length > maxBytes + ? chunk.subarray(0, maxBytes - totalBytes) + : chunk; + stdoutChunks.push(slice); + totalBytes += slice.length; + } + }); + + stream.stderr.on('data', (chunk: Buffer) => { + if (totalBytes < maxBytes) { + const slice = + totalBytes + chunk.length > maxBytes + ? chunk.subarray(0, maxBytes - totalBytes) + : chunk; + stderrChunks.push(slice); + totalBytes += slice.length; + } + }); + + stream.on('close', (exitCode: number | null, signal?: string) => { + finish(() => + resolve({ + stdout: Buffer.concat(stdoutChunks).toString('utf8'), + stderr: Buffer.concat(stderrChunks).toString('utf8'), + exitCode: exitCode ?? null, + signal, + durationMs: Date.now() - started, + }), + ); + }); + + stream.on('error', (streamErr: Error) => { + finish(() => reject(streamErr)); + }); + }); + }); + } + + async forwardOutStream( + serverId: string, + dstHost: string, + dstPort: number, + timeoutMs = 10_000, + ): Promise { + const client = await this.acquireClient(serverId); + return forwardOutOnClient(client, '127.0.0.1', 0, dstHost, dstPort, timeoutMs); + } + + async verifyStandaloneKeyAuth( + server: ServerConfig, + privateKey: string, + passphrase?: string, + ): Promise { + if (this.vaultService.state !== 'unlocked') { + throw new Error('Vault is locked'); + } + + let hopStream: Duplex | undefined; + if (server.jumpHostId) { + const bastionClient = await this.acquireClient(server.jumpHostId, new Set([server.id])); + hopStream = await forwardOutOnClient( + bastionClient, + '127.0.0.1', + 0, + server.host, + server.port, + ); + } + + const settings = this.configManager.getSettings(); + const tempClient = new ssh2.Client(); + + try { + await new Promise((resolve, reject) => { + let settled = false; + const done = (err?: Error) => { + if (settled) return; + settled = true; + if (err) reject(err); + else resolve(); + }; + + tempClient.once('ready', () => done()); + tempClient.once('error', (err) => done(err)); + tempClient.once('close', () => done(new Error('Verification connection closed before ready'))); + + const cfg: ConnectConfig = { + username: server.username, + privateKey, + passphrase: passphrase || undefined, + readyTimeout: settings.sshReadyTimeoutMs, + hostVerifier: (keyBuf: Buffer) => + this.knownHosts.verifyServerHostKey(server, keyBuf), + }; + if (hopStream) { + cfg.sock = hopStream; + } else { + cfg.host = server.host; + cfg.port = server.port; + } + tempClient.connect(cfg); + }); + + const res = await new Promise((resolve, reject) => { + tempClient.exec('echo gcoord-key-ok', (err, stream) => { + if (err) { + reject(err); + return; + } + const out: Buffer[] = []; + const errBuf: Buffer[] = []; + stream.on('data', (d: Buffer) => out.push(d)); + stream.stderr.on('data', (d: Buffer) => errBuf.push(d)); + stream.on('close', (exitCode: number | null) => { + resolve({ + stdout: Buffer.concat(out).toString('utf8'), + stderr: Buffer.concat(errBuf).toString('utf8'), + exitCode: exitCode ?? null, + durationMs: 0, + }); + }); + }); + }); + + if (res.exitCode !== 0 || res.stdout.trim() !== 'gcoord-key-ok') { + throw new Error( + `Key verification command failed (exit=${res.exitCode}): ${res.stderr.trim()}`, + ); + } + } finally { + tempClient.end(); + tempClient.destroy(); + hopStream?.destroy(); + } + } + + async reconnect(serverId: string): Promise { + this.closeServer(serverId); + this.reconnectAttempts.delete(serverId); + return this.acquireClient(serverId); + } + + syncWithConfig(): void { + const activeIds = new Set(); + for (const server of this.configManager.listServers()) { + activeIds.add(server.id); + if (!server.enabled) { + this.closeServer(server.id); + this.updateState(server.id, { status: 'disabled' }); + } else if (!this.states.has(server.id)) { + this.updateState(server.id, { + status: this.vaultService.state === 'unlocked' ? 'disconnected' : 'vault_locked', + }); + } + } + + for (const id of [...this.connections.keys()]) { + if (!activeIds.has(id)) { + this.closeServer(id); + } + } + for (const id of [...this.states.keys()]) { + if (!activeIds.has(id)) { + this.states.delete(id); + } + } + this.emitStates(); + } + + closeServer(serverId: string): void { + const timer = this.reconnectTimers.get(serverId); + if (timer) { + clearTimeout(timer); + this.reconnectTimers.delete(serverId); + } + + const conn = this.connections.get(serverId); + if (!conn) return; + + this.connections.delete(serverId); + + // Close dependent ProxyJump children first + for (const childId of [...conn.childIds]) { + this.closeServer(childId); + } + if (conn.jumpHostId) { + this.connections.get(conn.jumpHostId)?.childIds.delete(serverId); + } + + try { + conn.client.end(); + conn.client.destroy(); + } catch { + // Ignore cleanup errors + } + + const prev = this.states.get(serverId); + if (prev && prev.status === 'connected') { + this.updateState(serverId, { status: 'disconnected' }); + } + } + + closeAll(reason: 'panic_lock' | 'shutdown'): void { + if (reason === 'shutdown') { + this.closed = true; + } + + for (const timer of this.reconnectTimers.values()) { + clearTimeout(timer); + } + this.reconnectTimers.clear(); + + for (const id of [...this.connections.keys()]) { + this.closeServer(id); + } + + if (reason === 'panic_lock') { + for (const server of this.configManager.listServers()) { + this.states.set(server.id, { + serverId: server.id, + status: server.enabled ? 'vault_locked' : 'disabled', + lastError: server.enabled ? 'Panic Lock engaged' : undefined, + }); + } + this.emitStates(); + } + } + + private async connectServer( + server: ServerConfig, + visited: Set, + ): Promise { + const cred = this.vaultService.getSecret(server.credentialId); + if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) { + const msg = `Missing or incompatible SSH credential "${server.credentialId}" in Vault`; + this.updateState(server.id, { status: 'auth_error', lastError: msg }); + throw new Error(msg); + } + + this.updateState(server.id, { status: 'connecting', lastError: undefined }); + + let hopStream: Duplex | undefined; + if (server.jumpHostId) { + const bastion = await this.acquireClient(server.jumpHostId, visited); + hopStream = await forwardOutOnClient( + bastion, + '127.0.0.1', + 0, + server.host, + server.port, + ); + } + + const settings = this.configManager.getSettings(); + const client = new ssh2.Client(); + + return new Promise((resolve, reject) => { + let settled = false; + + const failConnect = (err: Error) => { + if (settled) return; + settled = true; + hopStream?.destroy(); + try { + client.destroy(); + } catch { + // Ignore destroy failure + } + + const mismatch = this.knownHosts.getPendingMismatch(server.id); + const tofu = this.knownHosts.getPendingTofu(server.id); + let status: ServerConnectionStatus = 'disconnected'; + if (mismatch) status = 'host_key_mismatch'; + else if (tofu) status = 'tofu_pending'; + else if ( + /authentication|all configured authentication/i.test(err.message) + ) { + status = 'auth_error'; + } + + this.updateState(server.id, { + status, + lastError: err.message, + tofuPending: tofu, + hostKeyMismatch: mismatch, + }); + + reject(err); + }; + + client.once('ready', () => { + if (settled) { + client.end(); + return; + } + settled = true; + this.reconnectAttempts.delete(server.id); + + const pooled: PooledConnection = { + serverId: server.id, + client, + connectedAt: Date.now(), + jumpHostId: server.jumpHostId, + childIds: new Set(), + }; + this.connections.set(server.id, pooled); + if (server.jumpHostId) { + this.connections.get(server.jumpHostId)?.childIds.add(server.id); + } + + this.updateState(server.id, { + status: 'connected', + connectedAt: pooled.connectedAt, + lastError: undefined, + tofuPending: undefined, + hostKeyMismatch: undefined, + }); + + resolve(client); + }); + + client.on('error', (err) => { + if (!settled) { + failConnect(err); + } else { + this.handleRuntimeDisconnect(server.id, err.message); + } + }); + + client.on('close', () => { + if (!settled) { + failConnect(new Error('SSH connection closed during handshake')); + } else { + this.handleRuntimeDisconnect(server.id); + } + }); + + const cfg: ConnectConfig = { + username: server.username, + keepaliveInterval: settings.sshKeepaliveMs, + keepaliveCountMax: 3, + readyTimeout: settings.sshReadyTimeoutMs, + hostVerifier: (keyBuf: Buffer) => + this.knownHosts.verifyServerHostKey(server, keyBuf), + }; + + if (cred.type === 'ssh-key') { + cfg.privateKey = cred.privateKey; + if (cred.passphrase) cfg.passphrase = cred.passphrase; + } else { + cfg.password = cred.password; + } + + if (hopStream) { + cfg.sock = hopStream; + } else { + cfg.host = server.host; + cfg.port = server.port; + } + + client.connect(cfg); + }); + } + + private handleRuntimeDisconnect(serverId: string, errorMsg?: string): void { + const conn = this.connections.get(serverId); + if (!conn) return; + + this.connections.delete(serverId); + for (const childId of [...conn.childIds]) { + this.closeServer(childId); + } + if (conn.jumpHostId) { + this.connections.get(conn.jumpHostId)?.childIds.delete(serverId); + } + + const mismatch = this.knownHosts.getPendingMismatch(serverId); + const tofu = this.knownHosts.getPendingTofu(serverId); + const status: ServerConnectionStatus = mismatch + ? 'host_key_mismatch' + : tofu + ? 'tofu_pending' + : this.vaultService.state !== 'unlocked' + ? 'vault_locked' + : 'disconnected'; + + this.updateState(serverId, { + status, + lastError: errorMsg, + tofuPending: tofu, + hostKeyMismatch: mismatch, + }); + + // Only auto-reconnect on transient network drops while unlocked + if (!this.closed && status === 'disconnected') { + const server = this.configManager.getServer(serverId); + if (server?.enabled && !this.reconnectTimers.has(serverId)) { + const attempt = this.reconnectAttempts.get(serverId) ?? 0; + const delayMs = Math.min(60_000, 1000 * 2 ** Math.min(attempt, 6)); + this.reconnectAttempts.set(serverId, attempt + 1); + const timer = setTimeout(() => { + this.reconnectTimers.delete(serverId); + void this.acquireClient(serverId).catch(() => { + // Reconnect failure updates state via connectServer + }); + }, delayMs); + timer.unref(); + this.reconnectTimers.set(serverId, timer); + } + } + } + + private refreshStatesFromKnownHosts(): void { + let changed = false; + for (const server of this.configManager.listServers()) { + const prev = this.states.get(server.id); + const tofu = this.knownHosts.getPendingTofu(server.id); + const mismatch = this.knownHosts.getPendingMismatch(server.id); + if (mismatch && prev?.status !== 'host_key_mismatch') { + this.states.set(server.id, { + ...(prev ?? { serverId: server.id }), + status: 'host_key_mismatch', + hostKeyMismatch: mismatch, + tofuPending: undefined, + }); + changed = true; + } else if (tofu && prev?.status !== 'tofu_pending') { + this.states.set(server.id, { + ...(prev ?? { serverId: server.id }), + status: 'tofu_pending', + tofuPending: tofu, + hostKeyMismatch: undefined, + }); + changed = true; + } else if (!tofu && !mismatch && (prev?.tofuPending || prev?.hostKeyMismatch)) { + this.states.set(server.id, { + ...prev, + status: this.connections.has(server.id) ? 'connected' : 'disconnected', + tofuPending: undefined, + hostKeyMismatch: undefined, + }); + changed = true; + } + } + if (changed) this.emitStates(); + } + + private buildStateForServer(server: ServerConfig): ServerRuntimeState { + const existing = this.states.get(server.id); + const tofu = this.knownHosts.getPendingTofu(server.id); + const mismatch = this.knownHosts.getPendingMismatch(server.id); + if (!server.enabled) { + return { serverId: server.id, status: 'disabled' }; + } + if (mismatch) { + return { + ...(existing ?? { serverId: server.id }), + status: 'host_key_mismatch', + hostKeyMismatch: mismatch, + }; + } + if (tofu) { + return { + ...(existing ?? { serverId: server.id }), + status: 'tofu_pending', + tofuPending: tofu, + }; + } + if (this.vaultService.state !== 'unlocked') { + return { + ...(existing ?? { serverId: server.id }), + status: 'vault_locked', + }; + } + return ( + existing ?? { + serverId: server.id, + status: this.connections.has(server.id) ? 'connected' : 'disconnected', + } + ); + } + + private updateState( + serverId: string, + patch: Partial>, + ): void { + const prev = this.states.get(serverId) ?? { + serverId, + status: 'disconnected' as ServerConnectionStatus, + }; + this.states.set(serverId, { ...prev, ...patch, serverId }); + this.emitStates(); + } + + private emitStates(): void { + const snapshot = this.getStates(); + for (const listener of this.stateListeners) { + try { + listener(snapshot); + } catch { + // Isolate subscriber errors + } + } + } +} + +function forwardOutOnClient( + client: Client, + srcIp: string, + srcPort: number, + dstHost: string, + dstPort: number, + timeoutMs = 10_000, +): Promise { + return new Promise((resolve, reject) => { + let settled = false; + const timer = setTimeout(() => { + if (settled) return; + settled = true; + reject(new Error(`SSH forwardOut to ${dstHost}:${dstPort} timed out`)); + }, timeoutMs); + + client.forwardOut(srcIp, srcPort, dstHost, dstPort, (err, stream) => { + if (settled) { + if (!err && stream) stream.destroy(); + return; + } + settled = true; + clearTimeout(timer); + if (err) { + reject(err); + } else { + resolve(stream); + } + }); + }); +} diff --git a/src/server/ssh/sudo.ts b/src/server/ssh/sudo.ts new file mode 100644 index 0000000..2f8ebee --- /dev/null +++ b/src/server/ssh/sudo.ts @@ -0,0 +1,50 @@ +export function posixSingleQuote(value: string): string { + return `'${value.replace(/'/g, "'\\''")}'`; +} + +export function buildEnvPrefix(env?: Record): string { + if (!env) return ''; + const parts: string[] = []; + for (const [key, val] of Object.entries(env)) { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) { + throw new Error(`Invalid environment variable name: ${key}`); + } + parts.push(`export ${key}=${posixSingleQuote(val)}`); + } + return parts.length > 0 ? `${parts.join('; ')}; ` : ''; +} + +export function prepareSudoExecution( + command: string, + options: { sudoPassword?: string; stdin?: Buffer | string } = {}, +): { command: string; stdin?: Buffer } { + const quoted = posixSingleQuote(command); + if (options.sudoPassword !== undefined && options.sudoPassword.length > 0) { + const pwPrefix = Buffer.from(`${options.sudoPassword}\n`, 'utf8'); + let combined = pwPrefix; + if (options.stdin !== undefined) { + const extra = + typeof options.stdin === 'string' + ? Buffer.from(options.stdin, 'utf8') + : options.stdin; + combined = Buffer.concat([pwPrefix, extra]); + pwPrefix.fill(0); + } + return { + command: `sudo -S -p '' sh -c ${quoted}`, + stdin: combined, + }; + } + + const extraStdin = + options.stdin === undefined + ? undefined + : typeof options.stdin === 'string' + ? Buffer.from(options.stdin, 'utf8') + : Buffer.from(options.stdin); + + return { + command: `sudo -n sh -c ${quoted}`, + stdin: extraStdin, + }; +} diff --git a/src/shared/ws-protocol.ts b/src/shared/ws-protocol.ts index bae4d68..c57671a 100644 --- a/src/shared/ws-protocol.ts +++ b/src/shared/ws-protocol.ts @@ -2,6 +2,16 @@ import { z } from 'zod'; export type VaultState = 'uninitialized' | 'locked' | 'unlocked'; +export type ServerConnectionStatus = + | 'disconnected' + | 'connecting' + | 'connected' + | 'tofu_pending' + | 'host_key_mismatch' + | 'auth_error' + | 'vault_locked' + | 'disabled'; + export interface ConfigWarning { filePath: string; code: string; @@ -50,12 +60,35 @@ export interface AlertEventSummary { ts: number; } -export interface HostKeyAlert { +export interface PendingTofuInfo { serverId: string; + hostPortKey: string; host: string; port: number; + algorithm: string; + fingerprint: string; + firstSeenAt: number; +} + +export interface HostKeyAlert { + serverId: string; + hostPortKey: string; + host: string; + port: number; + algorithm: string; expectedFingerprint: string; actualFingerprint: string; + detectedAt: number; +} + +export interface ServerRuntimeState { + serverId: string; + status: ServerConnectionStatus; + osDetected?: 'linux' | 'bsd' | 'macos'; + lastError?: string; + connectedAt?: number; + tofuPending?: PendingTofuInfo; + hostKeyMismatch?: HostKeyAlert; } export const ClientWsFrameSchema = z.discriminatedUnion('type', [ @@ -111,6 +144,7 @@ export type ServerWsFrame = } | { type: 'security:panic-lock' } | { type: 'error'; code: string; message: string } + | { type: 'servers:state'; states: ServerRuntimeState[] } | { type: 'metrics:tick'; serverId: string;