feat(api): mount terminal, SFTP, tunnels, /proxy HTTP+WS, and systems routes

This commit is contained in:
tyuXX 2026-11-26 21:43:05 +00:00
parent ec3f9c88b5
commit 98d36c8288
5 changed files with 1077 additions and 15 deletions

View file

@ -0,0 +1,383 @@
import { Router, type Response } from 'express';
import { z } from 'zod';
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 { SftpServiceError, type SftpService } from '../../ssh/sftp-service.js';
export interface SftpRouterDeps {
authService: AuthService;
configManager: ConfigManager;
auditService: AuditService;
sftpService: SftpService;
}
function sendSftpError(res: Response, err: unknown): void {
if (err instanceof SftpServiceError) {
const status =
err.code === 'NOT_FOUND'
? 404
: err.code === 'CONFLICT'
? 409
: err.code === 'FILE_TOO_LARGE'
? 413
: 400;
res.status(status).json({ error: err.code, message: err.message });
return;
}
const msg = err instanceof Error ? err.message : String(err);
const status = /no such file|not found|enoent/i.test(msg) ? 404 : 502;
res.status(status).json({ error: 'SFTP_ERROR', message: msg });
}
export function createSftpRouter(deps: SftpRouterDeps): Router {
const router = Router({ mergeParams: true });
const { authService, configManager, auditService, sftpService } = deps;
const ensureServer = (serverId: string, res: Response): boolean => {
if (!configManager.getServer(serverId)) {
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
return false;
}
return true;
};
router.get('/list', requireAuth(authService), async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const reqPath = typeof req.query.path === 'string' ? req.query.path : undefined;
try {
const listing = await sftpService.listDirectory(serverId, reqPath);
res.json(listing);
} catch (err) {
sendSftpError(res, err);
}
});
router.get('/stat', requireAuth(authService), async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const targetPath = typeof req.query.path === 'string' ? req.query.path : '';
if (!targetPath) {
res.status(400).json({ error: 'MISSING_PATH' });
return;
}
try {
const entry = await sftpService.statPath(serverId, targetPath);
res.json({ entry });
} catch (err) {
sendSftpError(res, err);
}
});
router.get('/download', requireAuth(authService), async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const targetPath = typeof req.query.path === 'string' ? req.query.path : '';
if (!targetPath) {
res.status(400).json({ error: 'MISSING_PATH' });
return;
}
try {
const dl = await sftpService.openDownloadStream(serverId, targetPath);
const safeName = dl.fileName.replace(/["\r\n\\]/g, '_');
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', `attachment; filename="${safeName}"`);
if (Number.isFinite(dl.size)) {
res.setHeader('Content-Length', String(dl.size));
}
res.once('close', () => {
if (!res.writableEnded) {
dl.stream.destroy();
dl.cleanup();
}
});
dl.stream.on('error', (streamErr) => {
dl.cleanup();
if (!res.headersSent) {
sendSftpError(res, streamErr);
} else {
res.destroy();
}
});
dl.stream.pipe(res);
} catch (err) {
sendSftpError(res, err);
}
});
router.get('/archive', requireAuth(authService), async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const targetPath = typeof req.query.path === 'string' ? req.query.path : '';
const formatRaw = typeof req.query.format === 'string' ? req.query.format : 'auto';
const format =
formatRaw === 'tar.zst' || formatRaw === 'tar.gz' ? formatRaw : 'auto';
if (!targetPath) {
res.status(400).json({ error: 'MISSING_PATH' });
return;
}
try {
const arch = await sftpService.streamDirectoryArchive(serverId, targetPath, format);
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader(
'Content-Disposition',
`attachment; filename="${arch.archiveFileName}"`,
);
res.setHeader('X-Archive-Format', arch.resolvedFormat);
res.once('close', () => {
if (!res.writableEnded) {
arch.abort();
}
});
arch.stream.on('error', () => {
arch.abort();
if (!res.headersSent) {
res.status(502).json({ error: 'ARCHIVE_STREAM_ERROR' });
} else {
res.destroy();
}
});
arch.stream.pipe(res);
} catch (err) {
sendSftpError(res, err);
}
});
router.post(
'/upload',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const targetPath = typeof req.query.path === 'string' ? req.query.path : '';
if (!targetPath) {
res.status(400).json({ error: 'MISSING_PATH' });
return;
}
try {
const result = await sftpService.uploadStream(serverId, targetPath, req);
auditService.log({
action: 'sftp.upload',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${result.path}`,
status: 'ok',
details: { bytesWritten: result.bytesWritten },
});
res.status(201).json({ ok: true, ...result });
} catch (err) {
sendSftpError(res, err);
}
},
);
router.post(
'/mkdir',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const parsed = z.object({ path: z.string().min(1) }).safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
try {
const created = await sftpService.mkdir(serverId, parsed.data.path);
auditService.log({
action: 'sftp.mkdir',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${created}`,
status: 'ok',
});
res.status(201).json({ ok: true, path: created });
} catch (err) {
sendSftpError(res, err);
}
},
);
router.post(
'/rename',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const parsed = z
.object({ fromPath: z.string().min(1), toPath: z.string().min(1) })
.safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
try {
const renamed = await sftpService.rename(
serverId,
parsed.data.fromPath,
parsed.data.toPath,
);
auditService.log({
action: 'sftp.rename',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${renamed.from}`,
status: 'ok',
details: { to: renamed.to },
});
res.json({ ok: true, ...renamed });
} catch (err) {
sendSftpError(res, err);
}
},
);
router.post(
'/chmod',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const parsed = z
.object({
path: z.string().min(1),
mode: z.union([z.string().min(3).max(4), z.number().int()]),
})
.safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
try {
const result = await sftpService.chmod(serverId, parsed.data.path, parsed.data.mode);
auditService.log({
action: 'sftp.chmod',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${result.path}`,
status: 'ok',
details: { mode: result.permissionsOctal },
});
res.json({ ok: true, ...result });
} catch (err) {
sendSftpError(res, err);
}
},
);
router.delete(
'/entry',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const targetPath = typeof req.query.path === 'string' ? req.query.path : '';
const recursive = req.query.recursive === '1' || req.query.recursive === 'true';
if (!targetPath) {
res.status(400).json({ error: 'MISSING_PATH' });
return;
}
try {
const deletedPath = await sftpService.deletePath(serverId, targetPath, recursive);
auditService.log({
action: 'sftp.delete',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${deletedPath}`,
status: 'ok',
details: { recursive },
});
res.json({ deleted: true, path: deletedPath });
} catch (err) {
sendSftpError(res, err);
}
},
);
router.get('/text', requireAuth(authService), async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const targetPath = typeof req.query.path === 'string' ? req.query.path : '';
const sudo = req.query.sudo === '1' || req.query.sudo === 'true';
if (!targetPath) {
res.status(400).json({ error: 'MISSING_PATH' });
return;
}
try {
const file = await sftpService.readTextFile(serverId, targetPath, { sudo });
res.json({ file });
} catch (err) {
sendSftpError(res, err);
}
});
router.put(
'/text',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
async (req, res) => {
const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return;
const parsed = z
.object({
path: z.string().min(1),
content: z.string(),
expectedSha256: z.string().optional(),
force: z.boolean().optional(),
sudo: z.boolean().optional(),
})
.safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
try {
const saved = await sftpService.writeTextFileAtomic(
serverId,
parsed.data.path,
parsed.data.content,
{
expectedSha256: parsed.data.expectedSha256,
force: parsed.data.force,
sudo: parsed.data.sudo,
},
);
auditService.log({
action: 'sftp.edit_save',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${saved.path}`,
status: 'ok',
details: { sha256: saved.sha256, sudo: Boolean(parsed.data.sudo) },
});
res.json({ ok: true, ...saved });
} catch (err) {
sendSftpError(res, err);
}
},
);
return router;
}

View file

@ -0,0 +1,214 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AuditService } from '../../security/audit.js';
import type { AuthService } from '../../security/auth.js';
import {
enforceSafeMode,
requireAuth,
requireCsrf,
} from '../../security/guards.js';
import type { CustomSystemsEngine } from '../../systems/systems-engine.js';
export interface SystemsRouterDeps {
authService: AuthService;
auditService: AuditService;
systemsEngine: CustomSystemsEngine;
}
export function createSystemsRouter(deps: SystemsRouterDeps): Router {
const router = Router();
const { authService, auditService, systemsEngine } = deps;
router.get('/', requireAuth(authService), (_req, res) => {
res.json({ systems: systemsEngine.listSystemsOverview() });
});
router.get('/:systemId', requireAuth(authService), async (req, res) => {
const systemId = String(req.params.systemId ?? '');
const serverId = typeof req.query.serverId === 'string' ? req.query.serverId : undefined;
const forceRefresh = req.query.refresh === '1' || req.query.refresh === 'true';
try {
const data = await systemsEngine.getSystemAcrossServers(systemId, {
serverId,
forceRefresh,
});
res.json(data);
} catch (err) {
res.status(404).json({
error: 'SYSTEM_LOAD_FAILED',
message: err instanceof Error ? err.message : 'Unable to load system',
});
}
});
router.put(
'/:systemId/servers/:serverId/attach',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
(req, res) => {
const systemId = String(req.params.systemId ?? '');
const serverId = String(req.params.serverId ?? '');
const parsed = z
.object({ params: z.record(z.unknown()).default({}) })
.safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
try {
const server = systemsEngine.attachSystemToServer(
serverId,
systemId,
parsed.data.params,
);
auditService.log({
action: 'system.attach',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${systemId}`,
status: 'ok',
});
res.json({ server });
} catch (err) {
res.status(400).json({
error: 'SYSTEM_ATTACH_FAILED',
message: err instanceof Error ? err.message : 'Unable to attach system',
});
}
},
);
router.delete(
'/:systemId/servers/:serverId/attach',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
(req, res) => {
const systemId = String(req.params.systemId ?? '');
const serverId = String(req.params.serverId ?? '');
try {
const server = systemsEngine.detachSystemFromServer(serverId, systemId);
auditService.log({
action: 'system.detach',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${systemId}`,
status: 'ok',
});
res.json({ server });
} catch (err) {
res.status(400).json({
error: 'SYSTEM_DETACH_FAILED',
message: err instanceof Error ? err.message : 'Unable to detach system',
});
}
},
);
router.put(
'/:systemId/servers/:serverId/items/:item/files',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
(req, res) => {
const systemId = String(req.params.systemId ?? '');
const serverId = String(req.params.serverId ?? '');
const itemName = String(req.params.item ?? '');
const parsed = z
.object({ activeFiles: z.array(z.string().min(1)).min(1) })
.safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
try {
const server = systemsEngine.updateItemActiveFiles(
serverId,
systemId,
itemName,
parsed.data.activeFiles,
);
auditService.log({
action: 'system.overlay_update',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${systemId}:${itemName}`,
status: 'ok',
details: { activeFiles: parsed.data.activeFiles },
});
res.json({ server });
} catch (err) {
res.status(400).json({
error: 'OVERLAY_UPDATE_FAILED',
message: err instanceof Error ? err.message : 'Unable to update activeFiles',
});
}
},
);
router.post(
'/:systemId/servers/:serverId/actions/:actionId',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
async (req, res) => {
const systemId = String(req.params.systemId ?? '');
const serverId = String(req.params.serverId ?? '');
const actionId = String(req.params.actionId ?? '');
const parsed = z
.object({
itemName: z.string().min(1).optional(),
subItemName: z.string().min(1).optional(),
cols: z.number().int().min(10).max(500).optional(),
rows: z.number().int().min(4).max(200).optional(),
})
.safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
try {
const result = await systemsEngine.executeAction({
serverId,
systemId,
actionId,
...parsed.data,
});
auditService.log({
action: 'system.action',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${systemId}:${actionId}`,
status: 'ok',
details: {
itemName: parsed.data.itemName,
subItemName: parsed.data.subItemName,
mode: result.mode,
},
});
res.json(result);
} catch (err) {
res.status(400).json({
error: 'SYSTEM_ACTION_FAILED',
message: err instanceof Error ? err.message : 'Unable to execute system action',
});
}
},
);
router.post(
'/streams/:jobId/cancel',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
(req, res) => {
const jobId = String(req.params.jobId ?? '');
res.json({ cancelled: systemsEngine.cancelStream(jobId) });
},
);
return router;
}

View file

@ -0,0 +1,138 @@
import { Router } from 'express';
import { z } from 'zod';
import { EntityIdSchema } from '../../../shared/schemas/common.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 { PTYManager } from '../../ssh/pty-manager.js';
export interface TerminalRouterDeps {
authService: AuthService;
configManager: ConfigManager;
auditService: AuditService;
ptyManager: PTYManager;
}
export function createTerminalRouter(deps: TerminalRouterDeps): Router {
const router = Router();
const { authService, configManager, auditService, ptyManager } = deps;
router.get('/sessions', requireAuth(authService), (_req, res) => {
res.json({ sessions: ptyManager.listSessions() });
});
router.post(
'/sessions',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
async (req, res) => {
const parsed = z
.object({
serverId: EntityIdSchema,
cols: z.number().int().min(10).max(500).optional(),
rows: z.number().int().min(4).max(200).optional(),
cwd: z.string().max(1024).optional(),
title: z.string().max(120).optional(),
})
.safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
if (!configManager.getServer(parsed.data.serverId)) {
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
return;
}
try {
const session = await ptyManager.openSession(parsed.data);
auditService.log({
action: 'pty.open',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: `${parsed.data.serverId}:${session.sessionId}`,
status: 'ok',
});
res.status(201).json({ session });
} catch (err) {
res.status(502).json({
error: 'PTY_OPEN_FAILED',
message: err instanceof Error ? err.message : 'Unable to open PTY session',
});
}
},
);
router.post(
'/sessions/:sessionId/resize',
requireAuth(authService),
requireCsrf,
(req, res) => {
const sessionId = String(req.params.sessionId ?? '');
const parsed = z
.object({
cols: z.number().int().min(10).max(500),
rows: z.number().int().min(4).max(200),
})
.safeParse(req.body ?? {});
if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
const ok = ptyManager.resize(sessionId, parsed.data.cols, parsed.data.rows);
if (!ok) {
res.status(404).json({ error: 'PTY_SESSION_NOT_ACTIVE' });
return;
}
res.json({ ok: true, session: ptyManager.getSession(sessionId) });
},
);
router.get('/sessions/:sessionId/export', requireAuth(authService), (req, res) => {
const sessionId = String(req.params.sessionId ?? '');
const format = req.query.format === 'ansi' ? 'ansi' : 'plain';
const exported = ptyManager.exportScrollback(sessionId, format);
if (!exported) {
res.status(404).json({ error: 'PTY_SESSION_NOT_FOUND' });
return;
}
const safeFile = exported.filename.replace(/[^A-Za-z0-9._-]/g, '_');
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="${safeFile}"`);
res.send(exported.content);
});
router.delete(
'/sessions/:sessionId',
requireAuth(authService),
requireCsrf,
enforceSafeMode,
(req, res) => {
const sessionId = String(req.params.sessionId ?? '');
const closed = ptyManager.closeSession(sessionId);
if (!closed) {
res.status(404).json({ error: 'PTY_SESSION_NOT_FOUND' });
return;
}
auditService.log({
action: 'pty.close',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: sessionId,
status: 'ok',
});
res.json({ closed: true });
},
);
return router;
}

View file

@ -0,0 +1,212 @@
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;
}

View file

@ -19,11 +19,19 @@ import { EmergencyRecoveryService } from './security/recovery-store.js';
import { VaultService } from './security/vault.js'; import { VaultService } from './security/vault.js';
import { KeyManager } from './ssh/key-manager.js'; import { KeyManager } from './ssh/key-manager.js';
import { KnownHostsService } from './ssh/known-hosts.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 { SSHPool } from './ssh/ssh-pool.js';
import { TunnelManager } from './ssh/tunnel-manager.js';
import { CustomSystemsEngine } from './systems/systems-engine.js';
import { createAuditRouter } from './api/routes/audit.routes.js'; import { createAuditRouter } from './api/routes/audit.routes.js';
import { createAuthRouter } from './api/routes/auth.routes.js'; import { createAuthRouter } from './api/routes/auth.routes.js';
import { createConfigRouter } from './api/routes/config.routes.js'; import { createConfigRouter } from './api/routes/config.routes.js';
import { createServersRouter } from './api/routes/servers.routes.js'; import { createServersRouter } from './api/routes/servers.routes.js';
import { createSftpRouter } from './api/routes/sftp.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 { createVaultRouter } from './api/routes/vault.routes.js';
import { WsHub } from './api/ws-hub.js'; import { WsHub } from './api/ws-hub.js';
@ -50,6 +58,10 @@ export interface GCoordinatorInstance {
knownHosts: KnownHostsService; knownHosts: KnownHostsService;
sshPool: SSHPool; sshPool: SSHPool;
keyManager: KeyManager; keyManager: KeyManager;
ptyManager: PTYManager;
sftpService: SftpService;
tunnelManager: TunnelManager;
customSystemsEngine: CustomSystemsEngine;
serverInspector: ServerInspector; serverInspector: ServerInspector;
monitoringService: MonitoringService; monitoringService: MonitoringService;
wsHub: WsHub; wsHub: WsHub;
@ -103,26 +115,22 @@ export async function createGCoordinatorServer(
app.set('trust proxy', 1); app.set('trust proxy', 1);
} }
app.use((_req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Referrer-Policy', 'no-referrer');
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ws: wss:; frame-ancestors 'none'; base-uri 'self'",
);
next();
});
app.use(attachClientIp(trustCloudflare));
app.use(express.json({ limit: '2mb' }));
const httpServer = http.createServer(app); const httpServer = http.createServer(app);
const wsHub = new WsHub(httpServer, authService, vaultService); const wsHub = new WsHub(httpServer, authService, vaultService);
const knownHosts = new KnownHostsService(db, auditService); const knownHosts = new KnownHostsService(db, auditService);
const sshPool = new SSHPool(configManager, vaultService, knownHosts); const sshPool = new SSHPool(configManager, vaultService, knownHosts);
const keyManager = new KeyManager(sshPool, vaultService, configManager, auditService); const keyManager = new KeyManager(sshPool, vaultService, configManager, auditService);
const ptyManager = new PTYManager(sshPool, configManager, wsHub);
const sftpService = new SftpService(sshPool);
const tunnelManager = new TunnelManager(sshPool, configManager, vaultService, authService);
const customSystemsEngine = new CustomSystemsEngine(
sshPool,
configManager,
vaultService,
ptyManager,
wsHub,
);
const serverInspector = new ServerInspector(sshPool, configManager); const serverInspector = new ServerInspector(sshPool, configManager);
const probeRunner = new ProbeRunner(sshPool); const probeRunner = new ProbeRunner(sshPool);
const monitoringService = new MonitoringService( const monitoringService = new MonitoringService(
@ -133,6 +141,71 @@ export async function createGCoordinatorServer(
probeRunner, probeRunner,
); );
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.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);
for (const frame of customSystemsEngine.getStreamReplayFrames(jobId)) {
ctx.send(frame);
}
}
});
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'no-referrer');
if (!req.path.startsWith('/proxy/')) {
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 'self' ws: wss:; frame-ancestors 'none'; base-uri 'self'",
);
}
next();
});
app.use(attachClientIp(trustCloudflare));
// 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' });
app.use((req, res, next) => {
if (req.path.endsWith('/sftp/upload')) {
next();
return;
}
jsonParser(req, res, next);
});
sshPool.onStateChange((states) => { sshPool.onStateChange((states) => {
wsHub.broadcastChannel('metrics', { type: 'servers:state', states }); wsHub.broadcastChannel('metrics', { type: 'servers:state', states });
for (const s of states) { for (const s of states) {
@ -157,9 +230,15 @@ export async function createGCoordinatorServer(
}); });
monitoringService.start(); monitoringService.start();
void tunnelManager.syncAutoStart();
customSystemsEngine.syncBackgroundChecks();
vaultService.onPanicLock(() => { vaultService.onPanicLock(() => {
monitoringService.stopAll(); monitoringService.stopAll();
customSystemsEngine.stopBackgroundChecks();
customSystemsEngine.cancelAllStreams();
tunnelManager.stopAll();
ptyManager.closeAll(true);
sshPool.closeAll('panic_lock'); sshPool.closeAll('panic_lock');
authService.revokeAllSessions(); authService.revokeAllSessions();
wsHub.handlePanicLock(); wsHub.handlePanicLock();
@ -173,14 +252,28 @@ export async function createGCoordinatorServer(
warnings: event.warnings, warnings: event.warnings,
errors: event.errors, errors: event.errors,
}); });
if (event.entityType === 'server' || event.entityType === 'settings' || event.entityType === 'all') { if (
event.entityType === 'server' ||
event.entityType === 'system' ||
event.entityType === 'settings' ||
event.entityType === 'all'
) {
if (event.entityType === 'server' && event.id) { if (event.entityType === 'server' && event.id) {
sshPool.closeServer(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 {
customSystemsEngine.invalidateCache();
} }
if (event.entityType === 'settings') { if (event.entityType === 'settings') {
authService.syncRecovery(); authService.syncRecovery();
} }
monitoringService.syncServers(); monitoringService.syncServers();
customSystemsEngine.syncBackgroundChecks();
void tunnelManager.syncAutoStart();
} }
}); });
@ -216,6 +309,8 @@ export async function createGCoordinatorServer(
stepUpGuard, stepUpGuard,
onVaultUnlocked: () => { onVaultUnlocked: () => {
monitoringService.syncServers(); monitoringService.syncServers();
customSystemsEngine.syncBackgroundChecks();
void tunnelManager.syncAutoStart();
}, },
onVaultChanged: (snapshotReason) => { onVaultChanged: (snapshotReason) => {
authService.syncRecovery({ snapshotReason }); authService.syncRecovery({ snapshotReason });
@ -224,6 +319,19 @@ export async function createGCoordinatorServer(
app.use('/api/vault', vaultRouter); app.use('/api/vault', vaultRouter);
app.use('/api/security', panicLockHandler); app.use('/api/security', panicLockHandler);
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 }),
);
app.use(
'/api/servers/:id/sftp',
createSftpRouter({ authService, configManager, auditService, sftpService }),
);
app.use( app.use(
'/api/servers', '/api/servers',
createServersRouter({ createServersRouter({
@ -284,12 +392,19 @@ export async function createGCoordinatorServer(
knownHosts, knownHosts,
sshPool, sshPool,
keyManager, keyManager,
ptyManager,
sftpService,
tunnelManager,
customSystemsEngine,
serverInspector, serverInspector,
monitoringService, monitoringService,
wsHub, wsHub,
port: actualPort, port: actualPort,
async close() { async close() {
monitoringService.close(); monitoringService.close();
customSystemsEngine.close();
tunnelManager.stopAll();
ptyManager.close();
sshPool.closeAll('shutdown'); sshPool.closeAll('shutdown');
wsHub.close(); wsHub.close();
await configManager.close(); await configManager.close();