feat(server): add Express REST API, security middleware, and multiplexed WebSocket hub
This commit is contained in:
parent
6520b81d82
commit
9cedd83a07
7 changed files with 1538 additions and 0 deletions
182
src/server/app.ts
Normal file
182
src/server/app.ts
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
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 { 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 { createAuditRouter } from './api/routes/audit.routes.js';
|
||||
import { createAuthRouter } from './api/routes/auth.routes.js';
|
||||
import { createConfigRouter } from './api/routes/config.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;
|
||||
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);
|
||||
|
||||
vaultService.onPanicLock(() => {
|
||||
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,
|
||||
});
|
||||
});
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
app.use('/api/vault', vaultRouter);
|
||||
app.use('/api/security', panicLockHandler);
|
||||
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,
|
||||
wsHub,
|
||||
port: actualPort,
|
||||
async close() {
|
||||
wsHub.close();
|
||||
await configManager.close();
|
||||
await new Promise<void>((resolve) => {
|
||||
httpServer.close(() => resolve());
|
||||
});
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue