feat(api): wire /api/servers routes, live WS metric/state streaming, and Panic Lock SSH teardown
This commit is contained in:
parent
03e996d743
commit
2d7709035b
3 changed files with 543 additions and 1 deletions
450
src/server/api/routes/servers.routes.ts
Normal file
450
src/server/api/routes/servers.routes.ts
Normal file
|
|
@ -0,0 +1,450 @@
|
|||
import { Router } from 'express';
|
||||
import { ZodError, z } from 'zod';
|
||||
import { EntityIdSchema } from '../../../shared/schemas/common.js';
|
||||
import { ServerConfigSchema } from '../../../shared/schemas/server.schema.js';
|
||||
import type { ConfigManager } from '../../config/config-manager.js';
|
||||
import type { ServerInspector } from '../../monitoring/inspector.js';
|
||||
import type {
|
||||
MetricRange,
|
||||
MonitoringService,
|
||||
} from '../../monitoring/monitoring-service.js';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
import type { AuthService } from '../../security/auth.js';
|
||||
import {
|
||||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
requireStepUp,
|
||||
} from '../../security/guards.js';
|
||||
import type { KeyManager } from '../../ssh/key-manager.js';
|
||||
import type { KnownHostsService } from '../../ssh/known-hosts.js';
|
||||
import type { SSHPool } from '../../ssh/ssh-pool.js';
|
||||
|
||||
export interface ServersRouterDeps {
|
||||
authService: AuthService;
|
||||
configManager: ConfigManager;
|
||||
auditService: AuditService;
|
||||
knownHosts: KnownHostsService;
|
||||
sshPool: SSHPool;
|
||||
keyManager: KeyManager;
|
||||
serverInspector: ServerInspector;
|
||||
monitoringService: MonitoringService;
|
||||
}
|
||||
|
||||
const VALID_RANGES = new Set<MetricRange>(['1h', '6h', '24h', '7d', '30d']);
|
||||
|
||||
export function createServersRouter(deps: ServersRouterDeps): Router {
|
||||
const router = Router();
|
||||
const {
|
||||
authService,
|
||||
configManager,
|
||||
auditService,
|
||||
knownHosts,
|
||||
sshPool,
|
||||
keyManager,
|
||||
serverInspector,
|
||||
monitoringService,
|
||||
} = deps;
|
||||
|
||||
router.get('/', requireAuth(authService), (_req, res) => {
|
||||
const servers = configManager.listServers().map((cfg) => ({
|
||||
config: cfg,
|
||||
runtime: sshPool.getState(cfg.id) ?? { serverId: cfg.id, status: 'disconnected' },
|
||||
telemetry: monitoringService.getLatest(cfg.id) ?? null,
|
||||
}));
|
||||
res.json({ servers });
|
||||
});
|
||||
|
||||
router.get('/known-hosts', requireAuth(authService), (_req, res) => {
|
||||
res.json({
|
||||
knownHosts: knownHosts.listKnownHosts(),
|
||||
pendingTofu: knownHosts.listPendingTofu(),
|
||||
pendingMismatches: knownHosts.listPendingMismatches(),
|
||||
});
|
||||
});
|
||||
|
||||
router.delete(
|
||||
'/known-hosts',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
(req, res) => {
|
||||
const hostPort = typeof req.query.hostPort === 'string' ? req.query.hostPort : '';
|
||||
if (!hostPort) {
|
||||
res.status(400).json({ error: 'MISSING_HOST_PORT' });
|
||||
return;
|
||||
}
|
||||
const deleted = knownHosts.deleteKnownHost(hostPort);
|
||||
auditService.log({
|
||||
action: 'ssh.known_host_delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: hostPort,
|
||||
status: deleted ? 'ok' : 'error',
|
||||
});
|
||||
res.json({ deleted });
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/rotate-keys',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
async (req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
serverIds: z.array(EntityIdSchema).optional(),
|
||||
tag: z.string().min(1).optional(),
|
||||
all: z.boolean().optional(),
|
||||
passphrase: z.string().max(256).optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const allServers = configManager.listServers().filter((s) => s.enabled);
|
||||
let targetIds: string[] = [];
|
||||
if (parsed.data.serverIds && parsed.data.serverIds.length > 0) {
|
||||
targetIds = parsed.data.serverIds;
|
||||
} else if (parsed.data.tag) {
|
||||
targetIds = allServers
|
||||
.filter((s) => s.tags.includes(parsed.data.tag!))
|
||||
.map((s) => s.id);
|
||||
} else if (parsed.data.all) {
|
||||
targetIds = allServers.map((s) => s.id);
|
||||
} else {
|
||||
res.status(400).json({ error: 'MISSING_ROTATION_TARGETS' });
|
||||
return;
|
||||
}
|
||||
|
||||
const results = await keyManager.rotateKeys({
|
||||
serverIds: targetIds,
|
||||
passphrase: parsed.data.passphrase,
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
});
|
||||
monitoringService.syncServers();
|
||||
res.json({ results });
|
||||
},
|
||||
);
|
||||
|
||||
router.post('/', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
try {
|
||||
const parsed = ServerConfigSchema.parse(req.body);
|
||||
const saved = configManager.saveConfigText(
|
||||
`servers/${parsed.id}.json`,
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Registered server via UI',
|
||||
);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.create',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({
|
||||
server: saved.config,
|
||||
warnings: saved.warnings,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid server configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'SERVER_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to save server',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
try {
|
||||
const parsed = ServerConfigSchema.parse({
|
||||
...(req.body ?? {}),
|
||||
id: req.params.id,
|
||||
});
|
||||
const saved = configManager.saveConfigText(
|
||||
`servers/${parsed.id}.json`,
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Updated server via UI',
|
||||
);
|
||||
sshPool.closeServer(parsed.id);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.update',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ server: saved.config, warnings: saved.warnings });
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid server configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'SERVER_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to update server',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
try {
|
||||
const deleted = configManager.deleteEntityFile(`servers/${id}.json`);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
sshPool.closeServer(id);
|
||||
knownHosts.clearServerPending(id);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ deleted: true });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'SERVER_DELETE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to delete server',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/:id/reconnect',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
if (!configManager.getServer(id)) {
|
||||
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await sshPool.reconnect(id);
|
||||
const tick = await monitoringService.pollServerNow(id);
|
||||
res.json({ ok: true, state: sshPool.getState(id), tick });
|
||||
} catch (err) {
|
||||
res.json({
|
||||
ok: false,
|
||||
state: sshPool.getState(id),
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/:id/tofu/approve',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = z.object({ fingerprint: z.string().min(1) }).safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const knownHost = knownHosts.approveTofu(id, parsed.data.fingerprint);
|
||||
auditService.log({
|
||||
action: 'ssh.tofu_approve',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
details: { fingerprint: knownHost.fingerprint, hostPort: knownHost.hostPort },
|
||||
});
|
||||
await sshPool.reconnect(id).catch(() => undefined);
|
||||
await monitoringService.pollServerNow(id).catch(() => undefined);
|
||||
res.json({ ok: true, knownHost, state: sshPool.getState(id) });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'TOFU_APPROVE_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to approve TOFU host key',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/:id/host-key/reset',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = z.object({ fingerprint: z.string().min(1) }).safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const knownHost = knownHosts.resetMismatch(id, parsed.data.fingerprint);
|
||||
auditService.log({
|
||||
action: 'ssh.host_key_reset',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
details: { fingerprint: knownHost.fingerprint, hostPort: knownHost.hostPort },
|
||||
});
|
||||
await sshPool.reconnect(id).catch(() => undefined);
|
||||
await monitoringService.pollServerNow(id).catch(() => undefined);
|
||||
res.json({ ok: true, knownHost, state: sshPool.getState(id) });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'HOST_KEY_RESET_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to reset host key',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.get('/:id/metrics', requireAuth(authService), (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
if (!configManager.getServer(id)) {
|
||||
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
const rawRange = String(req.query.range ?? '1h') as MetricRange;
|
||||
const range: MetricRange = VALID_RANGES.has(rawRange) ? rawRange : '1h';
|
||||
res.json({
|
||||
serverId: id,
|
||||
runtime: sshPool.getState(id),
|
||||
latest: monitoringService.getLatest(id) ?? null,
|
||||
...monitoringService.queryHistory(id, range),
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/:id/inspect', requireAuth(authService), async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
if (!configManager.getServer(id)) {
|
||||
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await serverInspector.inspect(id);
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
res.status(502).json({
|
||||
error: 'INSPECT_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Server inspection failed',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/:id/keys', requireAuth(authService), async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
if (!configManager.getServer(id)) {
|
||||
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const keys = await keyManager.inspectAuthorizedKeys(id);
|
||||
res.json(keys);
|
||||
} catch (err) {
|
||||
res.status(502).json({
|
||||
error: 'KEY_INSPECT_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to inspect authorized_keys',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/:id/keys/deploy',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = z.object({ credentialId: EntityIdSchema }).safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await keyManager.deployVaultKey(id, parsed.data.credentialId, {
|
||||
ip: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
});
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'KEY_DEPLOY_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to deploy SSH key',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/:id/keys/revoke',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
requireStepUp,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = z
|
||||
.object({
|
||||
fingerprint: z.string().min(1),
|
||||
force: z.boolean().optional(),
|
||||
})
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await keyManager.revokeAuthorizedKey(id, parsed.data.fingerprint, {
|
||||
force: parsed.data.force,
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
});
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'KEY_REVOKE_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to revoke SSH key',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue