feat(api): mount terminal, SFTP, tunnels, /proxy HTTP+WS, and systems routes
This commit is contained in:
parent
ec3f9c88b5
commit
98d36c8288
5 changed files with 1077 additions and 15 deletions
383
src/server/api/routes/sftp.routes.ts
Normal file
383
src/server/api/routes/sftp.routes.ts
Normal 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;
|
||||
}
|
||||
214
src/server/api/routes/systems.routes.ts
Normal file
214
src/server/api/routes/systems.routes.ts
Normal 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;
|
||||
}
|
||||
138
src/server/api/routes/terminal.routes.ts
Normal file
138
src/server/api/routes/terminal.routes.ts
Normal 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;
|
||||
}
|
||||
212
src/server/api/routes/tunnels.routes.ts
Normal file
212
src/server/api/routes/tunnels.routes.ts
Normal 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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue