import { Router } from 'express'; import { z } from 'zod'; import { EntityIdSchema } from '../../../shared/schemas/common.js'; import { ServerTunnelSchema } from '../../../shared/schemas/server.schema.js'; import type { ConfigManager } from '../../config/config-manager.js'; import type { AuditService } from '../../security/audit.js'; import type { AuthService } from '../../security/auth.js'; import { enforceSafeMode, requireAuth, requireCsrf, } from '../../security/guards.js'; import type { TunnelManager } from '../../ssh/tunnel-manager.js'; export interface TunnelsRouterDeps { authService: AuthService; configManager: ConfigManager; auditService: AuditService; tunnelManager: TunnelManager; } export function createTunnelsRouter(deps: TunnelsRouterDeps): Router { const router = Router(); const { authService, configManager, auditService, tunnelManager } = deps; router.get('/', requireAuth(authService), (_req, res) => { res.json({ tunnels: tunnelManager.listTunnels() }); }); router.post( '/', requireAuth(authService), requireCsrf, enforceSafeMode, async (req, res) => { const parsed = z .object({ serverId: EntityIdSchema, tunnel: ServerTunnelSchema, start: z.boolean().optional(), }) .safeParse(req.body ?? {}); if (!parsed.success) { res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); return; } const server = configManager.getServer(parsed.data.serverId); if (!server) { res.status(404).json({ error: 'SERVER_NOT_FOUND' }); return; } const idx = server.tunnels.findIndex((t) => t.id === parsed.data.tunnel.id); const nextTunnels = idx >= 0 ? server.tunnels.map((t, i) => (i === idx ? parsed.data.tunnel : t)) : [...server.tunnels, parsed.data.tunnel]; if (idx >= 0) { await tunnelManager.stopTunnel(server.id, parsed.data.tunnel.id); } configManager.saveConfigText( `servers/${server.id}.json`, JSON.stringify({ ...server, tunnels: nextTunnels }, null, 2), 'ui', `Saved tunnel "${parsed.data.tunnel.id}"`, ); let startedError: string | undefined; if (parsed.data.start || parsed.data.tunnel.autoStart) { try { await tunnelManager.startTunnel(server.id, parsed.data.tunnel.id); } catch (err) { startedError = err instanceof Error ? err.message : String(err); } } auditService.log({ action: 'tunnel.save', actorIp: req.clientIp ?? 'unknown', sessionIdHash: req.authSession!.idHash, target: `${server.id}:${parsed.data.tunnel.id}`, status: startedError ? 'error' : 'ok', details: startedError ? { error: startedError } : undefined, }); res.status(201).json({ tunnels: tunnelManager.listTunnels(), startError: startedError, }); }, ); router.delete( '/:serverId/:tunnelId', requireAuth(authService), requireCsrf, enforceSafeMode, async (req, res) => { const serverId = String(req.params.serverId ?? ''); const tunnelId = String(req.params.tunnelId ?? ''); const server = configManager.getServer(serverId); if (!server) { res.status(404).json({ error: 'SERVER_NOT_FOUND' }); return; } await tunnelManager.stopTunnel(serverId, tunnelId); const filtered = server.tunnels.filter((t) => t.id !== tunnelId); if (filtered.length === server.tunnels.length) { res.status(404).json({ error: 'TUNNEL_NOT_FOUND' }); return; } configManager.saveConfigText( `servers/${server.id}.json`, JSON.stringify({ ...server, tunnels: filtered }, null, 2), 'ui', `Removed tunnel "${tunnelId}"`, ); auditService.log({ action: 'tunnel.delete', actorIp: req.clientIp ?? 'unknown', sessionIdHash: req.authSession!.idHash, target: `${serverId}:${tunnelId}`, status: 'ok', }); res.json({ deleted: true, tunnels: tunnelManager.listTunnels() }); }, ); router.post( '/:serverId/:tunnelId/start', requireAuth(authService), requireCsrf, enforceSafeMode, async (req, res) => { const serverId = String(req.params.serverId ?? ''); const tunnelId = String(req.params.tunnelId ?? ''); try { const info = await tunnelManager.startTunnel(serverId, tunnelId); auditService.log({ action: 'tunnel.start', actorIp: req.clientIp ?? 'unknown', sessionIdHash: req.authSession!.idHash, target: `${serverId}:${tunnelId}`, status: 'ok', }); res.json({ tunnel: info }); } catch (err) { res.status(400).json({ error: 'TUNNEL_START_FAILED', message: err instanceof Error ? err.message : 'Unable to start tunnel', }); } }, ); router.post( '/:serverId/:tunnelId/stop', requireAuth(authService), requireCsrf, enforceSafeMode, async (req, res) => { const serverId = String(req.params.serverId ?? ''); const tunnelId = String(req.params.tunnelId ?? ''); const stopped = await tunnelManager.stopTunnel(serverId, tunnelId); auditService.log({ action: 'tunnel.stop', actorIp: req.clientIp ?? 'unknown', sessionIdHash: req.authSession!.idHash, target: `${serverId}:${tunnelId}`, status: 'ok', }); res.json({ stopped }); }, ); return router; } export function createProxyRouter(deps: { authService: AuthService; tunnelManager: TunnelManager; }): Router { const router = Router(); const { authService, tunnelManager } = deps; router.use('/:tunnelId', requireAuth(authService), (req, res) => { const method = req.method.toUpperCase(); if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') { const clientSafeHeader = req.headers['x-gcoord-safe-mode'] === '1'; if (req.authSession?.safeMode || clientSafeHeader) { res.status(423).json({ error: 'SAFE_MODE_ACTIVE', message: 'Disable Safe / Read-Only Mode before mutating proxied apps.', }); return; } } const tunnelId = String(req.params.tunnelId ?? ''); const subPath = req.url || '/'; tunnelManager.handleHttpProxy(req, res, tunnelId, subPath); }); return router; }