From 84023a3804a7019cd369f642aedda9066f1c36ba Mon Sep 17 00:00:00 2001 From: tyuXX Date: Thu, 26 Nov 2026 21:41:25 +0000 Subject: [PATCH] feat(ssh): implement SftpService and TunnelManager with HTTP/WS proxy and TCP forwards --- src/server/ssh/sftp-service.ts | 592 +++++++++++++++++++++++++++++++ src/server/ssh/tunnel-manager.ts | 584 ++++++++++++++++++++++++++++++ 2 files changed, 1176 insertions(+) create mode 100644 src/server/ssh/sftp-service.ts create mode 100644 src/server/ssh/tunnel-manager.ts diff --git a/src/server/ssh/sftp-service.ts b/src/server/ssh/sftp-service.ts new file mode 100644 index 0000000..ee9ba12 --- /dev/null +++ b/src/server/ssh/sftp-service.ts @@ -0,0 +1,592 @@ +import crypto from 'node:crypto'; +import path from 'node:path'; +import type { Readable } from 'node:stream'; +import type { FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2'; +import type { SSHPool } from './ssh-pool.js'; +import { posixSingleQuote } from './sudo.js'; + +export type SftpEntryType = 'dir' | 'file' | 'symlink' | 'other'; + +export interface SftpListEntry { + name: string; + path: string; + type: SftpEntryType; + size: number; + mode: number; + permissionsOctal: string; + mtimeMs: number; + uid: number; + gid: number; +} + +export interface SftpTextFile { + path: string; + content: string; + sha256: string; + size: number; + mode: number; +} + +export class SftpServiceError extends Error { + constructor( + public readonly code: + | 'NOT_FOUND' + | 'NOT_A_DIRECTORY' + | 'IS_A_DIRECTORY' + | 'FILE_TOO_LARGE' + | 'BINARY_FILE_NOT_EDITABLE' + | 'CONFLICT' + | 'INVALID_PATH' + | 'INVALID_MODE', + message: string, + ) { + super(message); + } +} + +const DEFAULT_MAX_TEXT_BYTES = 512 * 1024; +const DEFAULT_MAX_UPLOAD_BYTES = 512 * 1024 * 1024; + +function modeToType(mode: number): SftpEntryType { + const kind = mode & 0o170000; + if (kind === 0o040000) return 'dir'; + if (kind === 0o100000) return 'file'; + if (kind === 0o120000) return 'symlink'; + return 'other'; +} + +function sha256Buffer(buf: Buffer): string { + return crypto.createHash('sha256').update(buf).digest('hex'); +} + +function promisifySftp( + fn: (cb: (err: Error | undefined | null, result: T) => void) => void, +): Promise { + return new Promise((resolve, reject) => { + fn((err, result) => { + if (err) reject(err); + else resolve(result); + }); + }); +} + +function promisifySftpVoid( + fn: (cb: (err?: Error | null) => void) => void, +): Promise { + return new Promise((resolve, reject) => { + fn((err) => { + if (err) reject(err); + else resolve(); + }); + }); +} + +export class SftpService { + constructor(private readonly sshPool: SSHPool) {} + + async listDirectory( + serverId: string, + requestedPath?: string, + ): Promise<{ path: string; parentPath: string | null; entries: SftpListEntry[] }> { + return this.withSftp(serverId, async (sftp) => { + const resolved = await this.resolveRemotePath(sftp, requestedPath); + const stats = await promisifySftp((cb) => sftp.stat(resolved, cb)); + if (modeToType(stats.mode) !== 'dir') { + throw new SftpServiceError('NOT_A_DIRECTORY', `Not a directory: ${resolved}`); + } + + const rawEntries = await promisifySftp((cb) => + sftp.readdir(resolved, cb), + ); + + const entries: SftpListEntry[] = []; + for (const item of rawEntries) { + if (item.filename === '.' || item.filename === '..') continue; + const mode = item.attrs.mode ?? 0; + const type = modeToType(mode); + entries.push({ + name: item.filename, + path: path.posix.join(resolved, item.filename), + type, + size: item.attrs.size ?? 0, + mode, + permissionsOctal: (mode & 0o7777).toString(8).padStart(4, '0'), + mtimeMs: (item.attrs.mtime ?? 0) * 1000, + uid: item.attrs.uid ?? 0, + gid: item.attrs.gid ?? 0, + }); + } + + entries.sort((a, b) => { + if (a.type === 'dir' && b.type !== 'dir') return -1; + if (a.type !== 'dir' && b.type === 'dir') return 1; + return a.name.localeCompare(b.name); + }); + + const parentPath = resolved === '/' ? null : path.posix.dirname(resolved); + return { path: resolved, parentPath, entries }; + }); + } + + async statPath(serverId: string, remotePath: string): Promise { + return this.withSftp(serverId, async (sftp) => { + const resolved = await this.resolveRemotePath(sftp, remotePath); + const stats = await promisifySftp((cb) => sftp.stat(resolved, cb)); + const mode = stats.mode ?? 0; + return { + name: path.posix.basename(resolved) || '/', + path: resolved, + type: modeToType(mode), + size: stats.size ?? 0, + mode, + permissionsOctal: (mode & 0o7777).toString(8).padStart(4, '0'), + mtimeMs: (stats.mtime ?? 0) * 1000, + uid: stats.uid ?? 0, + gid: stats.gid ?? 0, + }; + }); + } + + async openDownloadStream( + serverId: string, + remotePath: string, + ): Promise<{ + path: string; + fileName: string; + size: number; + stream: Readable; + cleanup: () => void; + }> { + const sftp = await this.sshPool.openSftp(serverId); + const cleanup = () => { + try { + sftp.end(); + } catch { + // Ignore close error + } + }; + + try { + const resolved = await this.resolveRemotePath(sftp, remotePath); + const stats = await promisifySftp((cb) => sftp.stat(resolved, cb)); + if (modeToType(stats.mode) === 'dir') { + throw new SftpServiceError( + 'IS_A_DIRECTORY', + 'Cannot download a directory as a single file; use /archive instead.', + ); + } + const stream = sftp.createReadStream(resolved); + stream.once('close', cleanup); + stream.once('error', cleanup); + return { + path: resolved, + fileName: path.posix.basename(resolved), + size: stats.size ?? 0, + stream, + cleanup, + }; + } catch (err) { + cleanup(); + throw err; + } + } + + async uploadStream( + serverId: string, + remotePath: string, + source: Readable, + maxBytes = DEFAULT_MAX_UPLOAD_BYTES, + ): Promise<{ path: string; bytesWritten: number }> { + return this.withSftp(serverId, async (sftp) => { + const resolved = await this.resolveRemotePath(sftp, remotePath); + const dest = sftp.createWriteStream(resolved); + + let bytesWritten = 0; + return new Promise<{ path: string; bytesWritten: number }>((resolve, reject) => { + let settled = false; + const fail = (err: Error) => { + if (settled) return; + settled = true; + try { + source.destroy(); + } catch { + // Ignore + } + try { + dest.destroy(); + } catch { + // Ignore + } + reject(err); + }; + + source.on('data', (chunk: Buffer) => { + bytesWritten += chunk.length; + if (bytesWritten > maxBytes) { + fail( + new SftpServiceError( + 'FILE_TOO_LARGE', + `Upload exceeded limit of ${maxBytes} bytes`, + ), + ); + } + }); + + source.on('error', fail); + dest.on('error', fail); + dest.on('close', () => { + if (settled) return; + settled = true; + resolve({ path: resolved, bytesWritten }); + }); + + source.pipe(dest); + }); + }); + } + + async mkdir(serverId: string, remotePath: string): Promise { + return this.withSftp(serverId, async (sftp) => { + const resolved = await this.resolveRemotePath(sftp, remotePath); + await promisifySftpVoid((cb) => sftp.mkdir(resolved, cb)); + return resolved; + }); + } + + async rename(serverId: string, fromPath: string, toPath: string): Promise<{ from: string; to: string }> { + return this.withSftp(serverId, async (sftp) => { + const resolvedFrom = await this.resolveRemotePath(sftp, fromPath); + const resolvedTo = await this.resolveRemotePath(sftp, toPath); + await this.renameSftpPath(sftp, resolvedFrom, resolvedTo); + return { from: resolvedFrom, to: resolvedTo }; + }); + } + + async chmod(serverId: string, remotePath: string, modeInput: string | number): Promise<{ path: string; permissionsOctal: string }> { + const parsedMode = + typeof modeInput === 'number' + ? modeInput + : /^[0-7]{3,4}$/.test(modeInput.trim()) + ? Number.parseInt(modeInput.trim(), 8) + : Number.NaN; + if (!Number.isInteger(parsedMode) || parsedMode < 0 || parsedMode > 0o7777) { + throw new SftpServiceError('INVALID_MODE', `Invalid POSIX mode: ${String(modeInput)}`); + } + + return this.withSftp(serverId, async (sftp) => { + const resolved = await this.resolveRemotePath(sftp, remotePath); + await promisifySftpVoid((cb) => sftp.chmod(resolved, parsedMode, cb)); + return { + path: resolved, + permissionsOctal: parsedMode.toString(8).padStart(4, '0'), + }; + }); + } + + async deletePath( + serverId: string, + remotePath: string, + recursive = false, + ): Promise { + return this.withSftp(serverId, async (sftp) => { + const resolved = await this.resolveRemotePath(sftp, remotePath); + if (resolved === '/' || resolved === '.') { + throw new SftpServiceError('INVALID_PATH', 'Refusing to delete root directory'); + } + await this.deleteResolved(sftp, resolved, recursive); + return resolved; + }); + } + + async readTextFile( + serverId: string, + remotePath: string, + opts: { sudo?: boolean; maxBytes?: number } = {}, + ): Promise { + const maxBytes = opts.maxBytes ?? DEFAULT_MAX_TEXT_BYTES; + + if (opts.sudo) { + const resolved = await this.resolvePathNoStat(serverId, remotePath); + const quoted = posixSingleQuote(resolved); + const statRes = await this.sshPool.exec( + serverId, + `test -f ${quoted} && wc -c < ${quoted} && (stat -c '%a' ${quoted} 2>/dev/null || stat -f '%Lp' ${quoted} 2>/dev/null || echo 644)`, + { sudo: true }, + ); + if (statRes.exitCode !== 0) { + throw new SftpServiceError( + 'NOT_FOUND', + statRes.stderr.trim() || `Unable to read file ${resolved}`, + ); + } + const [sizeLine, modeLine] = statRes.stdout.trim().split(/\r?\n/); + const size = Number.parseInt(sizeLine ?? '0', 10) || 0; + if (size > maxBytes) { + throw new SftpServiceError( + 'FILE_TOO_LARGE', + `File "${resolved}" (${size}B) exceeds inline editor limit (${maxBytes}B)`, + ); + } + const mode = Number.parseInt(modeLine ?? '644', 8) || 0o644; + + const catRes = await this.sshPool.exec(serverId, `cat -- ${quoted}`, { + sudo: true, + maxBytes: maxBytes + 16, + }); + if (catRes.exitCode !== 0) { + throw new SftpServiceError( + 'NOT_FOUND', + catRes.stderr.trim() || `Unable to read ${resolved}`, + ); + } + const buf = Buffer.from(catRes.stdout, 'utf8'); + if (buf.includes(0)) { + throw new SftpServiceError('BINARY_FILE_NOT_EDITABLE', 'Binary file cannot be opened in inline editor'); + } + return { + path: resolved, + content: catRes.stdout, + sha256: sha256Buffer(buf), + size: buf.length, + mode, + }; + } + + return this.withSftp(serverId, async (sftp) => { + const resolved = await this.resolveRemotePath(sftp, remotePath); + const stats = await promisifySftp((cb) => sftp.stat(resolved, cb)); + if (modeToType(stats.mode) === 'dir') { + throw new SftpServiceError('IS_A_DIRECTORY', `${resolved} is a directory`); + } + if ((stats.size ?? 0) > maxBytes) { + throw new SftpServiceError( + 'FILE_TOO_LARGE', + `File "${resolved}" (${stats.size}B) exceeds inline editor limit (${maxBytes}B)`, + ); + } + const buf = await promisifySftp((cb) => sftp.readFile(resolved, cb)); + if (buf.length > maxBytes) { + throw new SftpServiceError('FILE_TOO_LARGE', 'File exceeds inline editor limit'); + } + if (buf.includes(0)) { + throw new SftpServiceError('BINARY_FILE_NOT_EDITABLE', 'Binary file cannot be opened in inline editor'); + } + return { + path: resolved, + content: buf.toString('utf8'), + sha256: sha256Buffer(buf), + size: buf.length, + mode: stats.mode & 0o7777, + }; + }); + } + + async writeTextFileAtomic( + serverId: string, + remotePath: string, + content: string, + opts: { expectedSha256?: string; force?: boolean; sudo?: boolean } = {}, + ): Promise<{ path: string; sha256: string; size: number }> { + const newBuf = Buffer.from(content, 'utf8'); + const newSha = sha256Buffer(newBuf); + + if (opts.sudo) { + const resolved = await this.resolvePathNoStat(serverId, remotePath); + if (opts.expectedSha256 && !opts.force) { + try { + const existing = await this.readTextFile(serverId, resolved, { sudo: true }); + if (existing.sha256 !== opts.expectedSha256) { + throw new SftpServiceError( + 'CONFLICT', + `Remote file "${resolved}" changed on disk since you loaded it.`, + ); + } + } catch (err) { + if (err instanceof SftpServiceError && err.code === 'CONFLICT') throw err; + } + } + + const dir = path.posix.dirname(resolved); + const tmp = path.posix.join(dir, `.gcoord-tmp-${crypto.randomBytes(6).toString('hex')}`); + const qDst = posixSingleQuote(resolved); + const qTmp = posixSingleQuote(tmp); + const res = await this.sshPool.exec( + serverId, + `umask 077 && cat > ${qTmp} && { [ ! -e ${qDst} ] || chmod --reference=${qDst} ${qTmp} 2>/dev/null || true; } && mv -f ${qTmp} ${qDst}`, + { sudo: true, stdin: newBuf }, + ); + if (res.exitCode !== 0) { + throw new Error(res.stderr.trim() || `Atomic sudo write failed for ${resolved}`); + } + return { path: resolved, sha256: newSha, size: newBuf.length }; + } + + return this.withSftp(serverId, async (sftp) => { + const resolved = await this.resolveRemotePath(sftp, remotePath); + let existingMode: number | undefined; + try { + const stats = await promisifySftp((cb) => sftp.stat(resolved, cb)); + existingMode = stats.mode & 0o7777; + if (opts.expectedSha256 && !opts.force) { + const prevBuf = await promisifySftp((cb) => sftp.readFile(resolved, cb)); + if (sha256Buffer(prevBuf) !== opts.expectedSha256) { + throw new SftpServiceError( + 'CONFLICT', + `Remote file "${resolved}" changed on disk since you loaded it.`, + ); + } + } + } catch (err) { + if (err instanceof SftpServiceError && err.code === 'CONFLICT') throw err; + // File does not yet exist or could not be pre-read + } + + const dir = path.posix.dirname(resolved); + const tmp = path.posix.join(dir, `.gcoord-tmp-${crypto.randomBytes(6).toString('hex')}`); + try { + await promisifySftpVoid((cb) => sftp.writeFile(tmp, newBuf, cb)); + if (existingMode !== undefined) { + await promisifySftpVoid((cb) => sftp.chmod(tmp, existingMode!, cb)).catch( + () => undefined, + ); + } + await this.renameSftpPath(sftp, tmp, resolved); + } catch (err) { + await promisifySftpVoid((cb) => sftp.unlink(tmp, cb)).catch(() => undefined); + throw err; + } + + return { path: resolved, sha256: newSha, size: newBuf.length }; + }); + } + + async streamDirectoryArchive( + serverId: string, + remotePath: string, + requestedFormat: 'auto' | 'tar.zst' | 'tar.gz' = 'auto', + ): Promise<{ + path: string; + resolvedFormat: 'tar.zst' | 'tar.gz'; + archiveFileName: string; + stream: Readable; + done: Promise<{ exitCode: number | null; signal?: string }>; + abort: () => void; + }> { + const resolved = await this.withSftp(serverId, async (sftp) => { + const p = await this.resolveRemotePath(sftp, remotePath); + const stats = await promisifySftp((cb) => sftp.stat(p, cb)); + if (modeToType(stats.mode) !== 'dir') { + throw new SftpServiceError('NOT_A_DIRECTORY', `Not a directory: ${p}`); + } + return p; + }); + + let resolvedFormat: 'tar.zst' | 'tar.gz' = + requestedFormat === 'auto' ? 'tar.gz' : requestedFormat; + + if (requestedFormat === 'auto') { + const probe = await this.sshPool + .exec(serverId, 'command -v zstd >/dev/null 2>&1', { timeoutMs: 8_000 }) + .catch(() => ({ exitCode: 1 })); + if (probe.exitCode === 0) { + resolvedFormat = 'tar.zst'; + } + } + + const parentDir = resolved === '/' ? '/' : path.posix.dirname(resolved); + const baseName = resolved === '/' ? '.' : path.posix.basename(resolved); + const safeName = (resolved === '/' ? 'root' : baseName).replace(/[^A-Za-z0-9._-]/g, '_'); + const archiveFileName = `${safeName}.${resolvedFormat}`; + + const compressCmd = resolvedFormat === 'tar.zst' ? 'zstd -T0 -c' : 'gzip -c'; + const cmd = `set -o pipefail 2>/dev/null || true; tar -C ${posixSingleQuote(parentDir)} -cf - ${posixSingleQuote(baseName)} | ${compressCmd}`; + const handle = await this.sshPool.execStream(serverId, cmd); + + return { + path: resolved, + resolvedFormat, + archiveFileName, + stream: handle.channel, + done: handle.done, + abort: handle.abort, + }; + } + + private async withSftp( + serverId: string, + fn: (sftp: SFTPWrapper) => Promise, + ): Promise { + const sftp = await this.sshPool.openSftp(serverId); + try { + return await fn(sftp); + } finally { + try { + sftp.end(); + } catch { + // Ignore close errors + } + } + } + + private async resolvePathNoStat(serverId: string, requestedPath?: string): Promise { + const trimmed = requestedPath?.trim() ?? ''; + if (trimmed.startsWith('/')) { + return path.posix.normalize(trimmed); + } + return this.withSftp(serverId, (sftp) => this.resolveRemotePath(sftp, requestedPath)); + } + + private async resolveRemotePath(sftp: SFTPWrapper, requestedPath?: string): Promise { + const trimmed = requestedPath?.trim() ?? ''; + if (!trimmed || trimmed === '.' || trimmed === '~') { + const home = await promisifySftp((cb) => sftp.realpath('.', cb)); + return path.posix.normalize(home || '/'); + } + if (trimmed.startsWith('~/')) { + const home = await promisifySftp((cb) => sftp.realpath('.', cb)); + return path.posix.normalize(path.posix.join(home || '/', trimmed.slice(2))); + } + if (!trimmed.startsWith('/')) { + const home = await promisifySftp((cb) => sftp.realpath('.', cb)); + return path.posix.normalize(path.posix.join(home || '/', trimmed)); + } + return path.posix.normalize(trimmed); + } + + private async renameSftpPath( + sftp: SFTPWrapper, + fromPath: string, + toPath: string, + ): Promise { + try { + await promisifySftpVoid((cb) => sftp.ext_openssh_rename(fromPath, toPath, cb)); + } catch { + await promisifySftpVoid((cb) => sftp.unlink(toPath, cb)).catch(() => undefined); + await promisifySftpVoid((cb) => sftp.rename(fromPath, toPath, cb)); + } + } + + private async deleteResolved( + sftp: SFTPWrapper, + resolved: string, + recursive: boolean, + ): Promise { + const stats = await promisifySftp((cb) => sftp.lstat(resolved, cb)); + if (modeToType(stats.mode) !== 'dir') { + await promisifySftpVoid((cb) => sftp.unlink(resolved, cb)); + return; + } + + if (recursive) { + const entries = await promisifySftp((cb) => + sftp.readdir(resolved, cb), + ); + for (const entry of entries) { + if (entry.filename === '.' || entry.filename === '..') continue; + await this.deleteResolved(sftp, path.posix.join(resolved, entry.filename), true); + } + } + + await promisifySftpVoid((cb) => sftp.rmdir(resolved, cb)); + } +} diff --git a/src/server/ssh/tunnel-manager.ts b/src/server/ssh/tunnel-manager.ts new file mode 100644 index 0000000..e527904 --- /dev/null +++ b/src/server/ssh/tunnel-manager.ts @@ -0,0 +1,584 @@ +import http, { type IncomingMessage } from 'node:http'; +import net, { type Socket } from 'node:net'; +import type { Duplex } from 'node:stream'; +import type { Request, Response } from 'express'; +import type { Client, TcpConnectionDetails } from 'ssh2'; +import type { ServerTunnel } from '../../shared/schemas/server.schema.js'; +import type { ConfigManager } from '../config/config-manager.js'; +import { SESSION_COOKIE_NAME, type AuthService } from '../security/auth.js'; +import { extractCookies } from '../security/guards.js'; +import type { VaultService } from '../security/vault.js'; +import type { SSHPool } from './ssh-pool.js'; + +export interface TunnelRuntimeInfo { + key: string; + serverId: string; + tunnel: ServerTunnel; + active: boolean; + localBoundHost?: string; + localBoundPort?: number; + remoteBoundPort?: number; + proxyPath?: string; + activeConnections: number; + totalConnections: number; + bytesIn: number; + bytesOut: number; + startedAt?: number; + lastError?: string; +} + +interface ActiveTunnelHandle { + key: string; + serverId: string; + tunnel: ServerTunnel; + localBoundHost?: string; + localBoundPort?: number; + remoteBoundPort?: number; + activeConnections: number; + totalConnections: number; + bytesIn: number; + bytesOut: number; + startedAt: number; + lastError?: string; + tcpServer?: net.Server; + remoteClient?: Client; + sockets: Set; +} + +function makeTunnelKey(serverId: string, tunnelId: string): string { + return `${serverId}--${tunnelId}`; +} + +function stripHubCookies(cookieHeader: string | string[] | undefined): string | undefined { + if (!cookieHeader) return undefined; + const raw = Array.isArray(cookieHeader) ? cookieHeader.join('; ') : cookieHeader; + const kept = raw + .split(';') + .map((part) => part.trim()) + .filter((part) => { + const name = part.split('=')[0]?.trim(); + return name && name !== SESSION_COOKIE_NAME && name !== 'gcoord_csrf'; + }); + return kept.length > 0 ? kept.join('; ') : undefined; +} + +export class TunnelManager { + private readonly active = new Map(); + private readonly remoteDispatch = new WeakMap< + Client, + Map Duplex, reject: () => void) => void> + >(); + + constructor( + private readonly sshPool: SSHPool, + private readonly configManager: ConfigManager, + private readonly vaultService: VaultService, + private readonly authService: AuthService, + ) {} + + listTunnels(): TunnelRuntimeInfo[] { + const out: TunnelRuntimeInfo[] = []; + const seenKeys = new Set(); + + for (const server of this.configManager.listServers()) { + for (const tunnel of server.tunnels) { + const key = makeTunnelKey(server.id, tunnel.id); + seenKeys.add(key); + const live = this.active.get(key); + out.push(this.toRuntimeInfo(server.id, tunnel, live)); + } + } + + for (const [key, live] of this.active.entries()) { + if (!seenKeys.has(key)) { + out.push(this.toRuntimeInfo(live.serverId, live.tunnel, live)); + } + } + + return out; + } + + async syncAutoStart(): Promise { + if (this.vaultService.state !== 'unlocked') return; + for (const server of this.configManager.listServers()) { + if (!server.enabled) continue; + for (const tunnel of server.tunnels) { + if (!tunnel.autoStart) continue; + const key = makeTunnelKey(server.id, tunnel.id); + if (!this.active.has(key)) { + await this.startTunnel(server.id, tunnel.id).catch(() => undefined); + } + } + } + } + + async startTunnel(serverId: string, tunnelId: string): Promise { + const server = this.configManager.getServer(serverId); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); + } + const tunnel = server.tunnels.find((t) => t.id === tunnelId); + if (!tunnel) { + throw new Error(`Tunnel "${tunnelId}" not found on server "${serverId}"`); + } + if (this.vaultService.state !== 'unlocked') { + throw new Error('Vault must be unlocked before starting SSH tunnels'); + } + + const key = makeTunnelKey(serverId, tunnelId); + const existing = this.active.get(key); + if (existing) { + return this.toRuntimeInfo(serverId, tunnel, existing); + } + + if (tunnel.mode === 'remote-tcp') { + return this.startRemoteTunnel(serverId, tunnel); + } + return this.startLocalListenerTunnel(serverId, tunnel); + } + + async stopTunnel(serverId: string, tunnelId: string): Promise { + const key = makeTunnelKey(serverId, tunnelId); + const handle = this.active.get(key); + if (!handle) return false; + this.active.delete(key); + await this.teardownHandle(handle); + return true; + } + + stopServerTunnels(serverId: string): void { + for (const [key, handle] of this.active.entries()) { + if (handle.serverId === serverId) { + this.active.delete(key); + void this.teardownHandle(handle); + } + } + } + + stopAll(): void { + for (const [key, handle] of this.active.entries()) { + this.active.delete(key); + void this.teardownHandle(handle); + } + } + + resolveProxyTarget(idOrKey: string): TunnelRuntimeInfo | undefined { + const direct = this.active.get(idOrKey); + if (direct && direct.tunnel.mode === 'http-proxy' && direct.localBoundPort) { + return this.toRuntimeInfo(direct.serverId, direct.tunnel, direct); + } + + const matches = [...this.active.values()].filter( + (h) => h.tunnel.mode === 'http-proxy' && h.localBoundPort && h.tunnel.id === idOrKey, + ); + if (matches.length === 1) { + const m = matches[0]!; + return this.toRuntimeInfo(m.serverId, m.tunnel, m); + } + return undefined; + } + + handleHttpProxy(req: Request, res: Response, idOrKey: string, subPath: string): void { + const target = this.resolveProxyTarget(idOrKey); + if (!target || !target.localBoundPort) { + res.status(502).json({ + error: 'TUNNEL_NOT_ACTIVE', + message: `HTTP proxy tunnel "${idOrKey}" is not active`, + }); + return; + } + + const live = this.active.get(target.key); + const qsIndex = req.originalUrl.indexOf('?'); + const qs = qsIndex >= 0 ? req.originalUrl.slice(qsIndex) : ''; + const upstreamPath = `${subPath.startsWith('/') ? subPath : `/${subPath}`}${qs}`; + + const headers: http.OutgoingHttpHeaders = {}; + for (const [hKey, hVal] of Object.entries(req.headers)) { + if (hVal === undefined) continue; + const lower = hKey.toLowerCase(); + if ( + lower === 'connection' || + lower === 'keep-alive' || + lower === 'transfer-encoding' || + lower === 'upgrade' || + lower === 'host' + ) { + continue; + } + if (lower === 'cookie') { + const filtered = stripHubCookies(hVal); + if (filtered) headers.cookie = filtered; + continue; + } + headers[hKey] = hVal; + } + headers.host = `${target.tunnel.targetHost}:${target.tunnel.targetPort}`; + headers['x-forwarded-host'] = req.headers.host ?? ''; + headers['x-forwarded-proto'] = req.protocol; + headers['x-forwarded-prefix'] = `/proxy/${idOrKey}`; + + const proxyReq = http.request( + { + host: '127.0.0.1', + port: target.localBoundPort, + method: req.method, + path: upstreamPath, + headers, + }, + (proxyRes) => { + const resHeaders: http.OutgoingHttpHeaders = { ...proxyRes.headers }; + if (typeof resHeaders.location === 'string' && resHeaders.location.startsWith('/')) { + resHeaders.location = `/proxy/${idOrKey}${resHeaders.location}`; + } + res.writeHead(proxyRes.statusCode ?? 502, resHeaders); + proxyRes.pipe(res); + }, + ); + + proxyReq.on('error', (err) => { + if (live) live.lastError = err.message; + if (!res.headersSent) { + res.status(502).json({ error: 'UPSTREAM_PROXY_ERROR', message: err.message }); + } else { + res.end(); + } + }); + + req.pipe(proxyReq); + } + + handleWsProxyUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void { + const rawUrl = req.url ?? '/'; + const parsedUrl = new URL(rawUrl, `http://${req.headers.host ?? 'localhost'}`); + const match = /^\/proxy\/([^/]+)(\/.*)?$/.exec(parsedUrl.pathname); + if (!match) { + socket.write('HTTP/1.1 404 Not Found\r\n\r\n'); + socket.destroy(); + return; + } + + const origin = req.headers.origin; + const host = req.headers.host; + if (origin && host) { + try { + if (new URL(origin).host !== host) { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } catch { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } + + const cookies = extractCookies(req.headers.cookie); + const session = this.authService.getSessionByToken(cookies[SESSION_COOKIE_NAME]); + if (!session) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return; + } + + const idOrKey = decodeURIComponent(match[1]!); + const subPath = match[2] || '/'; + const target = this.resolveProxyTarget(idOrKey); + const live = target ? this.active.get(target.key) : undefined; + if (!target || !live || !target.localBoundPort) { + socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); + socket.destroy(); + return; + } + + const upstreamPath = `${subPath}${parsedUrl.search}`; + const upstream = net.connect(target.localBoundPort, '127.0.0.1', () => { + const headerLines: string[] = [ + `${req.method ?? 'GET'} ${upstreamPath} HTTP/1.1`, + `Host: ${target.tunnel.targetHost}:${target.tunnel.targetPort}`, + ]; + for (const [k, v] of Object.entries(req.headers)) { + if (v === undefined) continue; + const lower = k.toLowerCase(); + if (lower === 'host') continue; + if (lower === 'cookie') { + const filtered = stripHubCookies(v); + if (filtered) headerLines.push(`Cookie: ${filtered}`); + continue; + } + const vals = Array.isArray(v) ? v : [v]; + for (const item of vals) { + headerLines.push(`${k}: ${item}`); + } + } + upstream.write(`${headerLines.join('\r\n')}\r\n\r\n`); + if (head.length > 0) upstream.write(head); + + live.sockets.add(socket); + live.sockets.add(upstream); + socket.pipe(upstream); + upstream.pipe(socket); + }); + + const cleanup = () => { + live.sockets.delete(socket); + live.sockets.delete(upstream); + socket.destroy(); + upstream.destroy(); + }; + upstream.on('error', cleanup); + upstream.on('close', cleanup); + socket.on('error', cleanup); + socket.on('close', cleanup); + } + + private async startLocalListenerTunnel( + serverId: string, + tunnel: ServerTunnel, + ): Promise { + // Verify SSH reachability upfront so callers get immediate handshake/TOFU/vault feedback + await this.sshPool.acquireClient(serverId); + + const bindHost = + tunnel.mode === 'http-proxy' ? '127.0.0.1' : tunnel.bindHost ?? '127.0.0.1'; + const bindPort = tunnel.mode === 'http-proxy' ? 0 : tunnel.bindPort ?? 0; + const key = makeTunnelKey(serverId, tunnel.id); + + const handle: ActiveTunnelHandle = { + key, + serverId, + tunnel, + localBoundHost: bindHost, + activeConnections: 0, + totalConnections: 0, + bytesIn: 0, + bytesOut: 0, + startedAt: Date.now(), + sockets: new Set(), + }; + + const tcpServer = net.createServer((clientSocket: Socket) => { + this.bridgeLocalSocket(handle, clientSocket); + }); + handle.tcpServer = tcpServer; + + await new Promise((resolve, reject) => { + tcpServer.once('error', reject); + tcpServer.listen(bindPort, bindHost, () => { + tcpServer.off('error', reject); + const addr = tcpServer.address(); + if (typeof addr === 'object' && addr) { + handle.localBoundPort = addr.port; + } + resolve(); + }); + }); + + tcpServer.on('error', (err) => { + handle.lastError = err.message; + }); + + this.active.set(key, handle); + return this.toRuntimeInfo(serverId, tunnel, handle); + } + + private bridgeLocalSocket(handle: ActiveTunnelHandle, clientSocket: Socket): void { + handle.activeConnections += 1; + handle.totalConnections += 1; + handle.sockets.add(clientSocket); + + let decremented = false; + const markClosed = () => { + handle.sockets.delete(clientSocket); + if (!decremented) { + decremented = true; + handle.activeConnections = Math.max(0, handle.activeConnections - 1); + } + }; + + this.sshPool + .forwardOutStream(handle.serverId, handle.tunnel.targetHost, handle.tunnel.targetPort) + .then((sshStream) => { + if (clientSocket.destroyed || !this.active.has(handle.key)) { + sshStream.destroy(); + clientSocket.destroy(); + markClosed(); + return; + } + handle.sockets.add(sshStream); + + clientSocket.on('data', (chunk: Buffer) => { + handle.bytesOut += chunk.length; + }); + sshStream.on('data', (chunk: Buffer) => { + handle.bytesIn += chunk.length; + }); + + clientSocket.pipe(sshStream); + sshStream.pipe(clientSocket); + + const cleanup = () => { + handle.sockets.delete(sshStream); + sshStream.destroy(); + clientSocket.destroy(); + markClosed(); + }; + sshStream.once('close', cleanup); + sshStream.once('error', cleanup); + clientSocket.once('close', cleanup); + clientSocket.once('error', cleanup); + }) + .catch((err) => { + handle.lastError = err instanceof Error ? err.message : String(err); + clientSocket.destroy(); + markClosed(); + }); + } + + private async startRemoteTunnel( + serverId: string, + tunnel: ServerTunnel, + ): Promise { + const client = await this.sshPool.acquireClient(serverId); + const bindHost = tunnel.bindHost ?? '127.0.0.1'; + const bindPort = tunnel.bindPort ?? 0; + const key = makeTunnelKey(serverId, tunnel.id); + + const handle: ActiveTunnelHandle = { + key, + serverId, + tunnel, + localBoundHost: bindHost, + activeConnections: 0, + totalConnections: 0, + bytesIn: 0, + bytesOut: 0, + startedAt: Date.now(), + remoteClient: client, + sockets: new Set(), + }; + + let portMap = this.remoteDispatch.get(client); + if (!portMap) { + portMap = new Map(); + this.remoteDispatch.set(client, portMap); + client.on('tcp connection', (details, accept, reject) => { + const handler = this.remoteDispatch.get(client)?.get(details.destPort); + if (!handler) { + reject(); + return; + } + handler(details, accept, reject); + }); + } + + const actualPort = await new Promise((resolve, reject) => { + client.forwardIn(bindHost, bindPort, (err, boundPort) => { + if (err) { + reject(err); + return; + } + resolve(boundPort ?? bindPort); + }); + }); + + handle.remoteBoundPort = actualPort; + portMap.set(actualPort, (_details, accept, _reject) => { + const channel = accept(); + handle.activeConnections += 1; + handle.totalConnections += 1; + handle.sockets.add(channel); + + const targetSock = net.connect(tunnel.targetPort, tunnel.targetHost); + handle.sockets.add(targetSock); + + let decremented = false; + const cleanup = () => { + handle.sockets.delete(channel); + handle.sockets.delete(targetSock); + channel.destroy(); + targetSock.destroy(); + if (!decremented) { + decremented = true; + handle.activeConnections = Math.max(0, handle.activeConnections - 1); + } + }; + + channel.on('data', (chunk: Buffer) => { + handle.bytesIn += chunk.length; + }); + targetSock.on('data', (chunk: Buffer) => { + handle.bytesOut += chunk.length; + }); + + channel.pipe(targetSock); + targetSock.pipe(channel); + channel.once('close', cleanup); + channel.once('error', cleanup); + targetSock.once('close', cleanup); + targetSock.once('error', cleanup); + }); + + this.active.set(key, handle); + return this.toRuntimeInfo(serverId, tunnel, handle); + } + + private async teardownHandle(handle: ActiveTunnelHandle): Promise { + for (const sock of handle.sockets) { + try { + sock.destroy(); + } catch { + // Ignore socket destroy errors + } + } + handle.sockets.clear(); + + if (handle.tcpServer) { + await new Promise((resolve) => { + handle.tcpServer!.close(() => resolve()); + }).catch(() => undefined); + } + + if (handle.remoteClient && handle.remoteBoundPort !== undefined) { + const portMap = this.remoteDispatch.get(handle.remoteClient); + portMap?.delete(handle.remoteBoundPort); + const host = handle.localBoundHost ?? '127.0.0.1'; + await new Promise((resolve) => { + handle.remoteClient!.unforwardIn(host, handle.remoteBoundPort!, () => resolve()); + }).catch(() => undefined); + } + } + + private toRuntimeInfo( + serverId: string, + tunnel: ServerTunnel, + live?: ActiveTunnelHandle, + ): TunnelRuntimeInfo { + const key = makeTunnelKey(serverId, tunnel.id); + const sameIdCount = this.configManager + .listServers() + .flatMap((s) => s.tunnels) + .filter((t) => t.id === tunnel.id && t.mode === 'http-proxy').length; + const proxyId = sameIdCount <= 1 ? tunnel.id : key; + return { + key, + serverId, + tunnel: { ...tunnel }, + active: Boolean(live), + localBoundHost: live?.localBoundHost, + localBoundPort: live?.localBoundPort, + remoteBoundPort: live?.remoteBoundPort, + proxyPath: + tunnel.mode === 'http-proxy' && live?.localBoundPort + ? `/proxy/${proxyId}/` + : undefined, + activeConnections: live?.activeConnections ?? 0, + totalConnections: live?.totalConnections ?? 0, + bytesIn: live?.bytesIn ?? 0, + bytesOut: live?.bytesOut ?? 0, + startedAt: live?.startedAt, + lastError: live?.lastError, + }; + } +}