263 lines
7.5 KiB
TypeScript
263 lines
7.5 KiB
TypeScript
import fs from 'node:fs';
|
|
import http from 'node:http';
|
|
import path from 'node:path';
|
|
import type Database from 'better-sqlite3';
|
|
import express, { type Express } from 'express';
|
|
import { ConfigManager } from './config/config-manager.js';
|
|
import { openDatabase } from './db/database.js';
|
|
import { ServerInspector } from './monitoring/inspector.js';
|
|
import { MonitoringService } from './monitoring/monitoring-service.js';
|
|
import { ProbeRunner } from './monitoring/probes.js';
|
|
import { AuditService } from './security/audit.js';
|
|
import { AuthService } from './security/auth.js';
|
|
import { RateLimiter, attachClientIp } from './security/guards.js';
|
|
import { VaultService } from './security/vault.js';
|
|
import { KeyManager } from './ssh/key-manager.js';
|
|
import { KnownHostsService } from './ssh/known-hosts.js';
|
|
import { SSHPool } from './ssh/ssh-pool.js';
|
|
import { createAuditRouter } from './api/routes/audit.routes.js';
|
|
import { createAuthRouter } from './api/routes/auth.routes.js';
|
|
import { createConfigRouter } from './api/routes/config.routes.js';
|
|
import { createServersRouter } from './api/routes/servers.routes.js';
|
|
import { createVaultRouter } from './api/routes/vault.routes.js';
|
|
import { WsHub } from './api/ws-hub.js';
|
|
|
|
export interface ServerOptions {
|
|
dataDir: string;
|
|
port: number;
|
|
host?: string;
|
|
publicDir?: string;
|
|
secretFilePath?: string;
|
|
envMasterKey?: string;
|
|
trustCloudflare?: boolean;
|
|
watchConfig?: boolean;
|
|
}
|
|
|
|
export interface GCoordinatorInstance {
|
|
app: Express;
|
|
httpServer: http.Server;
|
|
db: Database.Database;
|
|
vaultService: VaultService;
|
|
authService: AuthService;
|
|
configManager: ConfigManager;
|
|
auditService: AuditService;
|
|
knownHosts: KnownHostsService;
|
|
sshPool: SSHPool;
|
|
keyManager: KeyManager;
|
|
serverInspector: ServerInspector;
|
|
monitoringService: MonitoringService;
|
|
wsHub: WsHub;
|
|
port: number;
|
|
close(): Promise<void>;
|
|
}
|
|
|
|
export async function createGCoordinatorServer(
|
|
options: ServerOptions,
|
|
): Promise<GCoordinatorInstance> {
|
|
const dataDir = path.resolve(options.dataDir);
|
|
const configDir = path.join(dataDir, 'config');
|
|
const dbPath = path.join(dataDir, 'gcoord.db');
|
|
const vaultPath = path.join(dataDir, 'vault.enc');
|
|
const trustCloudflare = Boolean(options.trustCloudflare);
|
|
|
|
fs.mkdirSync(dataDir, { recursive: true });
|
|
|
|
const db = openDatabase(dbPath);
|
|
const auditService = new AuditService(db);
|
|
const vaultService = new VaultService(vaultPath);
|
|
const authService = new AuthService(db);
|
|
const rateLimiter = new RateLimiter();
|
|
const configManager = new ConfigManager(configDir, db, vaultService);
|
|
|
|
vaultService.tryAutoUnlockFromEnvOrSecret({
|
|
secretFilePath: options.secretFilePath,
|
|
envKey: options.envMasterKey,
|
|
});
|
|
|
|
await configManager.init({ watch: options.watchConfig ?? true });
|
|
|
|
const app = express();
|
|
app.disable('x-powered-by');
|
|
if (trustCloudflare) {
|
|
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 wsHub = new WsHub(httpServer, authService, vaultService);
|
|
|
|
const knownHosts = new KnownHostsService(db, auditService);
|
|
const sshPool = new SSHPool(configManager, vaultService, knownHosts);
|
|
const keyManager = new KeyManager(sshPool, vaultService, configManager, auditService);
|
|
const serverInspector = new ServerInspector(sshPool, configManager);
|
|
const probeRunner = new ProbeRunner(sshPool);
|
|
const monitoringService = new MonitoringService(
|
|
db,
|
|
configManager,
|
|
vaultService,
|
|
sshPool,
|
|
probeRunner,
|
|
);
|
|
|
|
sshPool.onStateChange((states) => {
|
|
wsHub.broadcastChannel('metrics', { type: 'servers:state', states });
|
|
for (const s of states) {
|
|
if (s.hostKeyMismatch) {
|
|
wsHub.broadcastChannel('alerts', {
|
|
type: 'alerts:update',
|
|
activeCount: knownHosts.listPendingMismatches().length,
|
|
hostKeyMismatch: s.hostKeyMismatch,
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
monitoringService.onTick((event) => {
|
|
wsHub.broadcastChannel('metrics', {
|
|
type: 'metrics:tick',
|
|
serverId: event.serverId,
|
|
sample: event.sample,
|
|
disks: event.disks,
|
|
probes: event.probes,
|
|
});
|
|
});
|
|
|
|
monitoringService.start();
|
|
|
|
vaultService.onPanicLock(() => {
|
|
monitoringService.stopAll();
|
|
sshPool.closeAll('panic_lock');
|
|
authService.revokeAllSessions();
|
|
wsHub.handlePanicLock();
|
|
});
|
|
|
|
configManager.onChange((event) => {
|
|
wsHub.broadcastChannel('config', {
|
|
type: 'config:updated',
|
|
entityType: event.entityType,
|
|
id: event.id,
|
|
warnings: event.warnings,
|
|
errors: event.errors,
|
|
});
|
|
if (event.entityType === 'server' || event.entityType === 'settings' || event.entityType === 'all') {
|
|
if (event.entityType === 'server' && event.id) {
|
|
sshPool.closeServer(event.id);
|
|
}
|
|
monitoringService.syncServers();
|
|
}
|
|
});
|
|
|
|
app.get('/api/healthz', (_req, res) => {
|
|
res.json({ ok: true, vaultState: vaultService.state });
|
|
});
|
|
|
|
app.use(
|
|
'/api/auth',
|
|
createAuthRouter({
|
|
authService,
|
|
vaultService,
|
|
configManager,
|
|
auditService,
|
|
rateLimiter,
|
|
trustCloudflare,
|
|
}),
|
|
);
|
|
|
|
const { vaultRouter, panicLockHandler } = createVaultRouter({
|
|
authService,
|
|
vaultService,
|
|
configManager,
|
|
auditService,
|
|
rateLimiter,
|
|
wsHub,
|
|
onVaultUnlocked: () => {
|
|
monitoringService.syncServers();
|
|
},
|
|
});
|
|
|
|
app.use('/api/vault', vaultRouter);
|
|
app.use('/api/security', panicLockHandler);
|
|
app.use(
|
|
'/api/servers',
|
|
createServersRouter({
|
|
authService,
|
|
configManager,
|
|
auditService,
|
|
knownHosts,
|
|
sshPool,
|
|
keyManager,
|
|
serverInspector,
|
|
monitoringService,
|
|
}),
|
|
);
|
|
app.use(
|
|
'/api/config',
|
|
createConfigRouter({ authService, configManager, auditService }),
|
|
);
|
|
app.use('/api/audit', createAuditRouter(authService, auditService));
|
|
|
|
app.use('/api', (_req, res) => {
|
|
res.status(404).json({ error: 'API_ROUTE_NOT_FOUND' });
|
|
});
|
|
|
|
const publicDir =
|
|
options.publicDir ?? path.resolve(process.cwd(), 'dist', 'public');
|
|
if (fs.existsSync(publicDir)) {
|
|
app.use(express.static(publicDir, { index: false }));
|
|
app.get('*', (_req, res) => {
|
|
res.sendFile(path.join(publicDir, 'index.html'));
|
|
});
|
|
}
|
|
|
|
await new Promise<void>((resolve, reject) => {
|
|
httpServer.once('error', reject);
|
|
httpServer.listen(options.port, options.host ?? '0.0.0.0', () => {
|
|
httpServer.off('error', reject);
|
|
resolve();
|
|
});
|
|
});
|
|
|
|
const address = httpServer.address();
|
|
const actualPort =
|
|
typeof address === 'object' && address ? address.port : options.port;
|
|
|
|
return {
|
|
app,
|
|
httpServer,
|
|
db,
|
|
vaultService,
|
|
authService,
|
|
configManager,
|
|
auditService,
|
|
knownHosts,
|
|
sshPool,
|
|
keyManager,
|
|
serverInspector,
|
|
monitoringService,
|
|
wsHub,
|
|
port: actualPort,
|
|
async close() {
|
|
monitoringService.close();
|
|
sshPool.closeAll('shutdown');
|
|
wsHub.close();
|
|
await configManager.close();
|
|
await new Promise<void>((resolve) => {
|
|
httpServer.close(() => resolve());
|
|
});
|
|
db.close();
|
|
},
|
|
};
|
|
}
|