Files
homelab-topology/server/routes/terminal.ts
Christopher Mayor 0910c966a5 feat: migrate from static config to database and add authentication
- Replaced static hosts.json and staticConfig.ts with SQLite database (Prisma)

- Implemented JWT authentication and Login UI

- Added dynamic API routes for hosts, topology, and settings

- Updated UI components to fetch and manage state dynamically

- Added Settings interface for managing hosts and topology nodes
2026-02-25 14:07:11 -08:00

61 lines
1.7 KiB
TypeScript

import { Router } from 'express';
import { execSync } from 'child_process';
import { homedir } from 'os';
import { getHostConfigs } from '../config';
const router = Router();
interface TerminalRequest {
host: string;
command: string;
}
router.post('/terminal/exec', async (req, res) => {
try {
const { host: hostName, command }: TerminalRequest = req.body;
if (!hostName || !command) {
return res.status(400).json({ error: 'Missing host or command' });
}
const hosts = await getHostConfigs();
const hostConfig = hosts.find(h => h.name === hostName);
if (!hostConfig) {
return res.status(404).json({ error: `Host not found: ${hostName}` });
}
const keyPath = (hostConfig.sshKeyPath || `${homedir()}/.ssh/id_ed25519`).replace(/^~/, homedir());
const keyArg = `-i ${keyPath}`;
const portArg = hostConfig.sshPort && hostConfig.sshPort !== 22 ? `-p ${hostConfig.sshPort}` : '';
const fullCommand = `ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no ${keyArg} ${portArg} ${hostConfig.sshUser}@${hostConfig.ip} ${command} 2>&1`;
const output = execSync(fullCommand, { encoding: 'utf-8', timeout: 30000 });
res.json({ output, error: null });
} catch (error: any) {
res.status(500).json({
output: '',
error: error.message || 'Command execution failed'
});
}
});
router.get('/terminal/hosts', async (_req, res) => {
try {
const hosts = await getHostConfigs();
res.json({
hosts: hosts.map(h => ({
name: h.name,
ip: h.ip,
user: h.sshUser
}))
});
} catch (error: any) {
res.status(500).json({ error: error.message });
}
});
export default router;