From 9cedd83a07145b8624384cabf4bee9d2503ed178 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Thu, 26 Nov 2026 18:24:43 +0000 Subject: [PATCH] feat(server): add Express REST API, security middleware, and multiplexed WebSocket hub --- src/server/api/routes/audit.routes.ts | 30 ++ src/server/api/routes/auth.routes.ts | 376 ++++++++++++++++++++ src/server/api/routes/config.routes.ts | 198 +++++++++++ src/server/api/routes/vault.routes.ts | 463 +++++++++++++++++++++++++ src/server/api/ws-hub.ts | 243 +++++++++++++ src/server/app.ts | 182 ++++++++++ src/server/index.ts | 46 +++ 7 files changed, 1538 insertions(+) create mode 100644 src/server/api/routes/audit.routes.ts create mode 100644 src/server/api/routes/auth.routes.ts create mode 100644 src/server/api/routes/config.routes.ts create mode 100644 src/server/api/routes/vault.routes.ts create mode 100644 src/server/api/ws-hub.ts create mode 100644 src/server/app.ts create mode 100644 src/server/index.ts diff --git a/src/server/api/routes/audit.routes.ts b/src/server/api/routes/audit.routes.ts new file mode 100644 index 0000000..48b66a5 --- /dev/null +++ b/src/server/api/routes/audit.routes.ts @@ -0,0 +1,30 @@ +import { Router } from 'express'; +import type { AuditService } from '../../security/audit.js'; +import type { AuthService } from '../../security/auth.js'; +import { requireAuth } from '../../security/guards.js'; + +export function createAuditRouter( + authService: AuthService, + auditService: AuditService, +): Router { + const router = Router(); + + router.get('/', requireAuth(authService), (req, res) => { + const limit = req.query.limit ? Number(req.query.limit) : 50; + const offset = req.query.offset ? Number(req.query.offset) : 0; + const action = + typeof req.query.action === 'string' && req.query.action.trim() + ? req.query.action.trim() + : undefined; + + res.json( + auditService.list({ + limit: Number.isFinite(limit) ? limit : 50, + offset: Number.isFinite(offset) ? offset : 0, + action, + }), + ); + }); + + return router; +} diff --git a/src/server/api/routes/auth.routes.ts b/src/server/api/routes/auth.routes.ts new file mode 100644 index 0000000..2deb5cd --- /dev/null +++ b/src/server/api/routes/auth.routes.ts @@ -0,0 +1,376 @@ +import { Router, type Request, type Response } from 'express'; +import { z } from 'zod'; +import type { ConfigManager } from '../../config/config-manager.js'; +import type { AuditService } from '../../security/audit.js'; +import { SESSION_COOKIE_NAME, type AuthService } from '../../security/auth.js'; +import { + enforceSafeMode, + extractCookies, + requireAuth, + requireCsrf, + type RateLimiter, +} from '../../security/guards.js'; +import type { VaultService } from '../../security/vault.js'; + +export const CSRF_COOKIE_NAME = 'gcoord_csrf'; + +export interface AuthRouterDeps { + authService: AuthService; + vaultService: VaultService; + configManager: ConfigManager; + auditService: AuditService; + rateLimiter: RateLimiter; + trustCloudflare: boolean; +} + +function isSecureCookie(req: Request, trustCloudflare: boolean): boolean { + return ( + trustCloudflare || + req.secure || + req.headers['x-forwarded-proto'] === 'https' + ); +} + +function setAuthCookies( + res: Response, + req: Request, + sessionToken: string, + csrfToken: string, + trustCloudflare: boolean, +): void { + const secure = isSecureCookie(req, trustCloudflare); + const maxAge = 7 * 24 * 60 * 60 * 1000; + res.cookie(SESSION_COOKIE_NAME, sessionToken, { + httpOnly: true, + sameSite: 'strict', + secure, + path: '/', + maxAge, + }); + res.cookie(CSRF_COOKIE_NAME, csrfToken, { + httpOnly: false, + sameSite: 'strict', + secure, + path: '/', + maxAge, + }); +} + +function clearAuthCookies(res: Response, req: Request, trustCloudflare: boolean): void { + const secure = isSecureCookie(req, trustCloudflare); + res.clearCookie(SESSION_COOKIE_NAME, { path: '/', sameSite: 'strict', secure }); + res.clearCookie(CSRF_COOKIE_NAME, { path: '/', sameSite: 'strict', secure }); +} + +export function createAuthRouter(deps: AuthRouterDeps): Router { + const router = Router(); + const { authService, vaultService, configManager, auditService, rateLimiter, trustCloudflare } = + deps; + + router.get('/status', (req, res) => { + const bootstrapped = authService.isBootstrapped(); + const cookies = extractCookies(req.headers.cookie); + const session = authService.getSessionByToken(cookies[SESSION_COOKIE_NAME]); + const settings = configManager.getSettings(); + + if (!session) { + res.json({ + bootstrapped, + authenticated: false, + vaultState: vaultService.state, + defaultMobileSafeMode: settings.defaultMobileSafeMode, + theme: settings.theme, + }); + return; + } + + res.json({ + bootstrapped, + authenticated: true, + safeMode: session.safeMode, + elevatedUntil: session.elevatedUntil, + vaultState: vaultService.state, + isPanicLocked: vaultService.isPanicLocked, + defaultMobileSafeMode: settings.defaultMobileSafeMode, + theme: settings.theme, + }); + }); + + router.get('/bootstrap', async (req, res) => { + if (authService.isBootstrapped()) { + res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); + return; + } + const username = + typeof req.query.username === 'string' && req.query.username.trim() + ? req.query.username.trim() + : 'admin'; + const data = await authService.beginBootstrap(username); + res.json(data); + }); + + router.post('/bootstrap', async (req, res) => { + if (authService.isBootstrapped()) { + res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('bootstrap', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } + + const bodySchema = z.object({ + username: z.string().min(2).max(64).default('admin'), + password: z.string().min(10).max(256), + totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'), + secretBase32: z.string().optional(), + initialSafeMode: z.boolean().optional(), + }); + const parsed = bodySchema.safeParse(req.body); + if (!parsed.success) { + rateLimiter.recordFailure('bootstrap', ip); + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + try { + const result = await authService.completeBootstrap({ + ...parsed.data, + ip, + userAgent: String(req.headers['user-agent'] ?? 'unknown'), + }); + rateLimiter.recordSuccess('bootstrap', ip); + setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); + auditService.log({ + action: 'auth.bootstrap', + actorIp: ip, + sessionIdHash: result.session.idHash, + target: parsed.data.username, + status: 'ok', + }); + res.status(201).json({ + authenticated: true, + csrfToken: result.csrfToken, + recoveryCodes: result.recoveryCodes, + safeMode: result.session.safeMode, + elevatedUntil: result.session.elevatedUntil, + vaultState: vaultService.state, + }); + } catch (err) { + rateLimiter.recordFailure('bootstrap', ip); + auditService.log({ + action: 'auth.bootstrap', + actorIp: ip, + status: 'error', + details: err instanceof Error ? err.message : 'Bootstrap failed', + }); + res.status(400).json({ + error: 'BOOTSTRAP_FAILED', + message: err instanceof Error ? err.message : 'Bootstrap failed', + }); + } + }); + + router.post('/login', async (req, res) => { + if (!authService.isBootstrapped()) { + res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('login', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } + + const bodySchema = z.object({ + username: z.string().min(1).optional(), + password: z.string().min(1), + code: z.string().min(6).max(32), + initialSafeMode: z.boolean().optional(), + }); + const parsed = bodySchema.safeParse(req.body); + if (!parsed.success) { + rateLimiter.recordFailure('login', ip); + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + const result = await authService.login({ + ...parsed.data, + ip, + userAgent: String(req.headers['user-agent'] ?? 'unknown'), + }); + + if (!result) { + rateLimiter.recordFailure('login', ip); + auditService.log({ + action: 'auth.login', + actorIp: ip, + target: parsed.data.username ?? 'admin', + status: 'denied', + }); + res.status(401).json({ error: 'INVALID_CREDENTIALS' }); + return; + } + + rateLimiter.recordSuccess('login', ip); + setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); + auditService.log({ + action: 'auth.login', + actorIp: ip, + sessionIdHash: result.session.idHash, + target: parsed.data.username ?? 'admin', + status: 'ok', + }); + + res.json({ + authenticated: true, + csrfToken: result.csrfToken, + safeMode: result.session.safeMode, + elevatedUntil: result.session.elevatedUntil, + vaultState: vaultService.state, + }); + }); + + // Exempt from enforceSafeMode + router.post('/logout', requireAuth(authService), requireCsrf, (req, res) => { + const session = req.authSession!; + authService.revokeSessionByHash(session.idHash); + clearAuthCookies(res, req, trustCloudflare); + auditService.log({ + action: 'auth.logout', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: session.idHash, + status: 'ok', + }); + res.json({ ok: true }); + }); + + // Exempt from enforceSafeMode so users can toggle Safe Mode on/off + router.post('/safe-mode', requireAuth(authService), requireCsrf, (req, res) => { + const parsed = z.object({ enabled: z.boolean() }).safeParse(req.body); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + const updated = authService.setSafeMode(req.authSession!.idHash, parsed.data.enabled); + if (!updated) { + res.status(401).json({ error: 'UNAUTHENTICATED' }); + return; + } + auditService.log({ + action: 'auth.safe_mode', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: updated.idHash, + status: 'ok', + details: { enabled: updated.safeMode }, + }); + res.json({ + safeMode: updated.safeMode, + elevatedUntil: updated.elevatedUntil, + }); + }); + + router.post('/step-up', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('step-up', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } + + const parsed = z + .object({ code: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits') }) + .safeParse(req.body); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + const outcome = authService.stepUp(req.authSession!.idHash, parsed.data.code); + if (!outcome.ok) { + rateLimiter.recordFailure('step-up', ip); + auditService.log({ + action: 'auth.step_up', + actorIp: ip, + sessionIdHash: req.authSession!.idHash, + status: 'denied', + details: { reason: outcome.reason }, + }); + res.status(outcome.reason === 'safe_mode_active' ? 423 : 403).json({ + error: 'STEP_UP_FAILED', + reason: outcome.reason, + }); + return; + } + + rateLimiter.recordSuccess('step-up', ip); + auditService.log({ + action: 'auth.step_up', + actorIp: ip, + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); + res.json({ elevatedUntil: outcome.elevatedUntil }); + }); + + router.post('/drop-elevation', requireAuth(authService), requireCsrf, (req, res) => { + authService.dropElevation(req.authSession!.idHash); + res.json({ elevatedUntil: null }); + }); + + router.get('/sessions', requireAuth(authService), (req, res) => { + res.json({ sessions: authService.listSessions(req.authSession!.idHash) }); + }); + + router.delete( + '/sessions/:prefix', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + (req, res) => { + const prefix = String(req.params.prefix ?? ''); + const count = authService.revokeSessionByPrefix(prefix); + auditService.log({ + action: 'auth.session_revoke', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: prefix, + status: count > 0 ? 'ok' : 'error', + }); + res.json({ revoked: count }); + }, + ); + + router.post( + '/sessions/revoke-all', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + (req, res) => { + const keepCurrent = Boolean(req.body?.keepCurrent); + const count = authService.revokeAllSessions( + keepCurrent ? req.authSession!.idHash : undefined, + ); + if (!keepCurrent) { + clearAuthCookies(res, req, trustCloudflare); + } + auditService.log({ + action: 'auth.sessions_revoke_all', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + status: 'ok', + details: { keepCurrent, count }, + }); + res.json({ revoked: count }); + }, + ); + + return router; +} diff --git a/src/server/api/routes/config.routes.ts b/src/server/api/routes/config.routes.ts new file mode 100644 index 0000000..7bcde14 --- /dev/null +++ b/src/server/api/routes/config.routes.ts @@ -0,0 +1,198 @@ +import { Router } from 'express'; +import { ZodError, 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'; + +export interface ConfigRouterDeps { + authService: AuthService; + configManager: ConfigManager; + auditService: AuditService; +} + +export function createConfigRouter(deps: ConfigRouterDeps): Router { + const router = Router(); + const { authService, configManager, auditService } = deps; + + router.get('/overview', requireAuth(authService), (_req, res) => { + res.json({ + files: configManager.listFiles(), + diagnostics: configManager.getDiagnostics(), + servers: configManager.listServers(), + systems: configManager.listSystems(), + workflows: configManager.listWorkflows(), + snippets: configManager.getSnippets(), + alerts: configManager.getAlerts(), + settings: configManager.getSettings(), + }); + }); + + router.get('/file', requireAuth(authService), (req, res) => { + const filePath = typeof req.query.path === 'string' ? req.query.path : ''; + if (!filePath) { + res.status(400).json({ error: 'MISSING_PATH' }); + return; + } + try { + const file = configManager.readRawFile(filePath); + const revisions = configManager.listRevisions(filePath); + res.json({ ...file, revisions }); + } catch (err) { + res.status(404).json({ + error: 'CONFIG_READ_ERROR', + message: err instanceof Error ? err.message : 'Unable to read config file', + }); + } + }); + + router.put('/file', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { + const parsed = z + .object({ + path: z.string().min(1), + content: z.string().min(2), + summary: z.string().max(200).optional(), + }) + .safeParse(req.body); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + try { + const saved = configManager.saveConfigText( + parsed.data.path, + parsed.data.content, + 'ui', + parsed.data.summary, + ); + auditService.log({ + action: 'config.save', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: saved.filePath, + status: 'ok', + }); + res.json(saved); + } catch (err) { + if (err instanceof ZodError) { + res.status(400).json({ + error: 'CONFIG_SCHEMA_ERROR', + message: 'Schema validation failed', + issues: err.issues.map((i) => ({ + path: i.path.join('.') || '(root)', + message: i.message, + })), + }); + return; + } + res.status(400).json({ + error: 'CONFIG_SAVE_ERROR', + message: err instanceof Error ? err.message : 'Unable to save config file', + }); + } + }); + + router.delete( + '/file', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + (req, res) => { + const filePath = typeof req.query.path === 'string' ? req.query.path : ''; + if (!filePath) { + res.status(400).json({ error: 'MISSING_PATH' }); + return; + } + try { + const deleted = configManager.deleteEntityFile(filePath); + if (!deleted) { + res.status(404).json({ error: 'CONFIG_NOT_FOUND' }); + return; + } + auditService.log({ + action: 'config.delete', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: filePath, + status: 'ok', + }); + res.json({ deleted: true }); + } catch (err) { + res.status(400).json({ + error: 'CONFIG_DELETE_ERROR', + message: err instanceof Error ? err.message : 'Unable to delete config file', + }); + } + }, + ); + + router.get('/revisions', requireAuth(authService), (req, res) => { + const filePath = typeof req.query.path === 'string' ? req.query.path : ''; + if (!filePath) { + res.status(400).json({ error: 'MISSING_PATH' }); + return; + } + try { + res.json({ revisions: configManager.listRevisions(filePath) }); + } catch (err) { + res.status(400).json({ + error: 'REVISION_LIST_ERROR', + message: err instanceof Error ? err.message : 'Unable to list revisions', + }); + } + }); + + router.get('/revisions/:id/diff', requireAuth(authService), (req, res) => { + const id = Number(req.params.id); + if (!Number.isInteger(id) || id <= 0) { + res.status(400).json({ error: 'INVALID_REVISION_ID' }); + return; + } + try { + res.json(configManager.diffRevision(id)); + } catch (err) { + res.status(404).json({ + error: 'REVISION_NOT_FOUND', + message: err instanceof Error ? err.message : 'Revision not found', + }); + } + }); + + router.post( + '/revisions/:id/rollback', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + (req, res) => { + const id = Number(req.params.id); + if (!Number.isInteger(id) || id <= 0) { + res.status(400).json({ error: 'INVALID_REVISION_ID' }); + return; + } + try { + const result = configManager.rollbackRevision(id); + auditService.log({ + action: 'config.rollback', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: result.filePath, + status: 'ok', + details: { revisionId: id }, + }); + res.json(result); + } catch (err) { + res.status(400).json({ + error: 'ROLLBACK_FAILED', + message: err instanceof Error ? err.message : 'Rollback failed', + }); + } + }, + ); + + return router; +} diff --git a/src/server/api/routes/vault.routes.ts b/src/server/api/routes/vault.routes.ts new file mode 100644 index 0000000..db427de --- /dev/null +++ b/src/server/api/routes/vault.routes.ts @@ -0,0 +1,463 @@ +import crypto from 'node:crypto'; +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, + requireStepUp, + type RateLimiter, +} from '../../security/guards.js'; +import { + computeOpenSshFingerprint, + generateMasterKeyBuffer, + type VaultCredentialInput, + type VaultService, +} from '../../security/vault.js'; +import type { WsHub } from '../ws-hub.js'; + +export interface VaultRouterDeps { + authService: AuthService; + vaultService: VaultService; + configManager: ConfigManager; + auditService: AuditService; + rateLimiter: RateLimiter; + wsHub: WsHub; +} + +interface PendingKeyRotation { + candidateKeyHex: string; + confirmToken: string; + sessionIdHash: string; + expiresAt: number; +} + +const UpsertCredentialBodySchema = z.discriminatedUnion('type', [ + z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + type: z.literal('ssh-key'), + privateKey: z.string().min(1), + publicKey: z.string().min(1).optional(), + passphrase: z.string().optional(), + fingerprint: z.string().optional(), + }), + z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + type: z.literal('ssh-password'), + password: z.string().min(1), + }), + z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + type: z.literal('sudo-password'), + password: z.string().min(1), + }), + z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + type: z.literal('webhook-secret'), + secret: z.string().min(1), + }), + z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + type: z.literal('api-token'), + token: z.string().min(1), + }), +]); + +export function createVaultRouter(deps: VaultRouterDeps): { + vaultRouter: Router; + panicLockHandler: Router; +} { + const { authService, vaultService, configManager, auditService, rateLimiter, wsHub } = deps; + const vaultRouter = Router(); + const panicLockHandler = Router(); + + let pendingRotation: PendingKeyRotation | null = null; + vaultService.onPanicLock(() => { + pendingRotation = null; + }); + + const notifyConfigReeval = () => { + const warnings = configManager.recomputeWarnings(); + const { errors } = configManager.getDiagnostics(); + wsHub.broadcastChannel('config', { + type: 'config:updated', + entityType: 'all', + warnings, + errors, + }); + }; + + vaultRouter.get('/status', requireAuth(authService), (_req, res) => { + res.json({ + state: vaultService.state, + isPanicLocked: vaultService.isPanicLocked, + }); + }); + + vaultRouter.post('/init', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { + const ip = req.clientIp ?? 'unknown'; + const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + try { + const result = vaultService.initializeNewVault(parsed.data.masterKey); + notifyConfigReeval(); + auditService.log({ + action: 'vault.init', + actorIp: ip, + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); + res.status(201).json({ + state: vaultService.state, + generatedKeyHex: result.generatedKeyHex, + }); + } catch (err) { + res.status(400).json({ + error: 'VAULT_INIT_FAILED', + message: err instanceof Error ? err.message : 'Vault initialization failed', + }); + } + }); + + vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, (req, res) => { + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('vault-unlock', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } + + const parsed = z.object({ masterKey: z.string().min(1) }).safeParse(req.body); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + try { + vaultService.unlock(parsed.data.masterKey); + rateLimiter.recordSuccess('vault-unlock', ip); + notifyConfigReeval(); + auditService.log({ + action: 'vault.unlock', + actorIp: ip, + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); + res.json({ + state: vaultService.state, + isPanicLocked: vaultService.isPanicLocked, + }); + } catch (err) { + rateLimiter.recordFailure('vault-unlock', ip); + auditService.log({ + action: 'vault.unlock', + actorIp: ip, + sessionIdHash: req.authSession!.idHash, + status: 'denied', + }); + res.status(403).json({ + error: 'VAULT_UNLOCK_FAILED', + message: err instanceof Error ? err.message : 'Invalid master key or corrupted vault', + }); + } + }); + + // Panic Lock is ALWAYS reachable when authenticated + CSRF verified (even under Safe Mode!) + panicLockHandler.post('/panic-lock', requireAuth(authService), requireCsrf, (req, res) => { + const session = req.authSession!; + const ip = req.clientIp ?? 'unknown'; + auditService.log({ + action: 'security.panic_lock', + actorIp: ip, + sessionIdHash: session.idHash, + status: 'ok', + }); + vaultService.panicLock(); + res.json({ + ok: true, + vaultState: vaultService.state, + isPanicLocked: vaultService.isPanicLocked, + }); + }); + + vaultRouter.get('/credentials', requireAuth(authService), (_req, res) => { + if (vaultService.state !== 'unlocked') { + res.json({ state: vaultService.state, credentials: [] }); + return; + } + res.json({ + state: vaultService.state, + credentials: vaultService.listMetadata(), + }); + }); + + vaultRouter.get( + '/credentials/:id/reveal', + requireAuth(authService), + requireStepUp, + (req, res) => { + if (vaultService.state !== 'unlocked') { + res.status(423).json({ error: 'VAULT_LOCKED' }); + return; + } + const id = String(req.params.id ?? ''); + const secret = vaultService.getSecret(id); + if (!secret) { + res.status(404).json({ error: 'CREDENTIAL_NOT_FOUND' }); + return; + } + auditService.log({ + action: 'vault.reveal', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: id, + status: 'ok', + }); + res.json({ credential: secret }); + }, + ); + + vaultRouter.post( + '/credentials', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + requireStepUp, + (req, res) => { + if (vaultService.state !== 'unlocked') { + res.status(423).json({ error: 'VAULT_LOCKED' }); + return; + } + const parsed = UpsertCredentialBodySchema.safeParse(req.body); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + const credInput: VaultCredentialInput = { ...parsed.data }; + if ( + credInput.type === 'ssh-key' && + credInput.publicKey && + !credInput.fingerprint + ) { + try { + credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); + } catch { + // Leave fingerprint omitted if user imported an unusual public key format + } + } + const meta = vaultService.upsertCredential(credInput); + notifyConfigReeval(); + auditService.log({ + action: 'vault.upsert', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: meta.id, + status: 'ok', + details: { type: meta.type }, + }); + res.status(201).json({ credential: meta }); + }, + ); + + vaultRouter.put( + '/credentials/:id', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + requireStepUp, + (req, res) => { + if (vaultService.state !== 'unlocked') { + res.status(423).json({ error: 'VAULT_LOCKED' }); + return; + } + const bodyWithId = { ...(req.body ?? {}), id: req.params.id }; + const parsed = UpsertCredentialBodySchema.safeParse(bodyWithId); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + const credInput: VaultCredentialInput = { ...parsed.data }; + if ( + credInput.type === 'ssh-key' && + credInput.publicKey && + !credInput.fingerprint + ) { + try { + credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); + } catch { + // Ignore non-standard public key strings + } + } + const meta = vaultService.upsertCredential(credInput); + notifyConfigReeval(); + auditService.log({ + action: 'vault.upsert', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: meta.id, + status: 'ok', + details: { type: meta.type }, + }); + res.json({ credential: meta }); + }, + ); + + vaultRouter.delete( + '/credentials/:id', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + requireStepUp, + (req, res) => { + if (vaultService.state !== 'unlocked') { + res.status(423).json({ error: 'VAULT_LOCKED' }); + return; + } + const id = String(req.params.id ?? ''); + const removed = vaultService.deleteCredential(id); + if (!removed) { + res.status(404).json({ error: 'CREDENTIAL_NOT_FOUND' }); + return; + } + notifyConfigReeval(); + auditService.log({ + action: 'vault.delete', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: id, + status: 'ok', + }); + res.json({ deleted: true }); + }, + ); + + vaultRouter.post( + '/generate-ed25519', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + requireStepUp, + (req, res) => { + if (vaultService.state !== 'unlocked') { + res.status(423).json({ error: 'VAULT_LOCKED' }); + return; + } + const parsed = z + .object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + comment: z.string().max(120).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 meta = vaultService.generateEd25519Credential(parsed.data); + notifyConfigReeval(); + auditService.log({ + action: 'vault.generate_ed25519', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: meta.id, + status: 'ok', + details: { fingerprint: meta.fingerprint }, + }); + res.status(201).json({ credential: meta }); + }, + ); + + vaultRouter.post( + '/rotate-key/prepare', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + requireStepUp, + (req, res) => { + if (vaultService.state !== 'unlocked') { + res.status(423).json({ error: 'VAULT_LOCKED' }); + return; + } + const candidateKeyHex = generateMasterKeyBuffer().toString('hex'); + const confirmToken = crypto.randomBytes(24).toString('base64url'); + const expiresAt = Date.now() + 5 * 60 * 1000; + pendingRotation = { + candidateKeyHex, + confirmToken, + sessionIdHash: req.authSession!.idHash, + expiresAt, + }; + res.json({ candidateKeyHex, confirmToken, expiresAt }); + }, + ); + + vaultRouter.post( + '/rotate-key/commit', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + requireStepUp, + (req, res) => { + if (vaultService.state !== 'unlocked') { + res.status(423).json({ error: 'VAULT_LOCKED' }); + return; + } + const parsed = z + .object({ + confirmToken: z.string().min(1), + confirmedKeyHex: z.string().min(1).optional(), + }) + .safeParse(req.body); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + if ( + !pendingRotation || + pendingRotation.expiresAt <= Date.now() || + pendingRotation.sessionIdHash !== req.authSession!.idHash || + pendingRotation.confirmToken !== parsed.data.confirmToken + ) { + res.status(400).json({ error: 'ROTATION_TOKEN_INVALID_OR_EXPIRED' }); + return; + } + + if ( + parsed.data.confirmedKeyHex && + parsed.data.confirmedKeyHex.trim().toLowerCase() !== + pendingRotation.candidateKeyHex.toLowerCase() + ) { + res.status(400).json({ error: 'KEY_CONFIRMATION_MISMATCH' }); + return; + } + + const nextHex = pendingRotation.candidateKeyHex; + pendingRotation = null; + vaultService.rotateMasterKey(nextHex); + auditService.log({ + action: 'vault.rotate_key', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); + res.json({ ok: true }); + }, + ); + + return { vaultRouter, panicLockHandler }; +} diff --git a/src/server/api/ws-hub.ts b/src/server/api/ws-hub.ts new file mode 100644 index 0000000..1536556 --- /dev/null +++ b/src/server/api/ws-hub.ts @@ -0,0 +1,243 @@ +import type { IncomingMessage, Server as HttpServer } from 'node:http'; +import { WebSocket, WebSocketServer } from 'ws'; +import { + ClientWsFrameSchema, + type ServerWsFrame, +} from '../../shared/ws-protocol.js'; +import { SESSION_COOKIE_NAME, type AuthService } from '../security/auth.js'; +import { extractCookies } from '../security/guards.js'; +import type { VaultService } from '../security/vault.js'; + +interface WsClientMeta { + ws: WebSocket; + sessionToken: string; + sessionIdHash: string; + channels: Set; + clientSafeMode: boolean; + alive: boolean; +} + +export class WsHub { + private readonly wss = new WebSocketServer({ noServer: true }); + private readonly clients = new Set(); + private readonly pingTimer: NodeJS.Timeout; + + constructor( + httpServer: HttpServer, + private readonly authService: AuthService, + private readonly vaultService: VaultService, + ) { + httpServer.on('upgrade', (req, socket, head) => { + this.handleUpgrade(req, socket, head); + }); + + this.pingTimer = setInterval(() => { + for (const client of this.clients) { + if (!client.alive) { + client.ws.terminate(); + this.clients.delete(client); + continue; + } + client.alive = false; + client.ws.ping(); + } + }, 25_000); + this.pingTimer.unref(); + } + + close(): void { + clearInterval(this.pingTimer); + for (const client of this.clients) { + client.ws.close(1001, 'Server shutting down'); + } + this.clients.clear(); + this.wss.close(); + } + + handlePanicLock(): void { + const payload = JSON.stringify({ type: 'security:panic-lock' } satisfies ServerWsFrame); + for (const client of this.clients) { + try { + if (client.ws.readyState === WebSocket.OPEN) { + client.ws.send(payload); + } + client.ws.close(4001, 'Panic Lock engaged'); + } catch { + // Continue closing remaining sockets + } + } + this.clients.clear(); + } + + broadcastAll(frame: ServerWsFrame): void { + const text = JSON.stringify(frame); + for (const client of this.clients) { + if (client.ws.readyState === WebSocket.OPEN) { + client.ws.send(text); + } + } + } + + broadcastChannel(channel: string, frame: ServerWsFrame): void { + const text = JSON.stringify(frame); + for (const client of this.clients) { + if ( + client.ws.readyState === WebSocket.OPEN && + (client.channels.has(channel) || client.channels.has('*')) + ) { + client.ws.send(text); + } + } + } + + private handleUpgrade( + req: IncomingMessage, + socket: import('node:stream').Duplex, + head: Buffer, + ): void { + const urlPath = (req.url ?? '').split('?')[0]; + if (urlPath !== '/ws') { + socket.write('HTTP/1.1 404 Not Found\r\n\r\n'); + socket.destroy(); + return; + } + + // Validate Origin when provided by browsers to block cross-site WS hijacking + const origin = req.headers.origin; + const host = req.headers.host; + if (origin && host) { + try { + const originUrl = new URL(origin); + if (originUrl.host !== host) { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } catch { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } + + const cookies = extractCookies(req.headers.cookie); + const token = cookies[SESSION_COOKIE_NAME]; + const session = this.authService.getSessionByToken(token); + if (!session || !token) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return; + } + + this.wss.handleUpgrade(req, socket, head, (ws) => { + const meta: WsClientMeta = { + ws, + sessionToken: token, + sessionIdHash: session.idHash, + channels: new Set(['config', 'alerts']), + clientSafeMode: session.safeMode, + alive: true, + }; + this.clients.add(meta); + + this.sendFrame(ws, { + type: 'hello', + vaultState: this.vaultService.state, + safeMode: session.safeMode, + elevatedUntil: session.elevatedUntil, + }); + + ws.on('pong', () => { + meta.alive = true; + }); + + ws.on('message', (raw) => { + this.onMessage(meta, raw); + }); + + ws.on('close', () => { + this.clients.delete(meta); + }); + + ws.on('error', () => { + this.clients.delete(meta); + }); + }); + } + + private onMessage(meta: WsClientMeta, raw: unknown): void { + let parsedJson: unknown; + try { + const text = typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf8'); + parsedJson = JSON.parse(text); + } catch { + this.sendFrame(meta.ws, { + type: 'error', + code: 'BAD_JSON', + message: 'Invalid WebSocket JSON frame', + }); + return; + } + + const result = ClientWsFrameSchema.safeParse(parsedJson); + if (!result.success) { + this.sendFrame(meta.ws, { + type: 'error', + code: 'INVALID_FRAME', + message: 'Unrecognized or malformed WebSocket frame', + }); + return; + } + + const frame = result.data; + switch (frame.type) { + case 'ping': + this.sendFrame(meta.ws, { + type: 'pong', + ts: frame.ts, + serverTs: Date.now(), + }); + break; + case 'sub': + for (const ch of frame.channels) { + meta.channels.add(ch); + } + break; + case 'unsub': + for (const ch of frame.channels) { + meta.channels.delete(ch); + } + break; + case 'safe-mode': + meta.clientSafeMode = frame.enabled; + break; + case 'pty:input': { + const latestSession = this.authService.getSessionByToken(meta.sessionToken); + if (!latestSession) { + meta.ws.close(4001, 'Session expired'); + return; + } + if (latestSession.safeMode || meta.clientSafeMode) { + this.sendFrame(meta.ws, { + type: 'error', + code: 'SAFE_MODE_ACTIVE', + message: 'Safe / Read-Only Mode blocks terminal input.', + }); + return; + } + // Phase 3 PTYManager attaches here + break; + } + case 'pty:resize': + case 'ai:cancel': + // Wired in Phases 3 and 5 + break; + } + } + + private sendFrame(ws: WebSocket, frame: ServerWsFrame): void { + if (ws.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify(frame)); + } + } +} diff --git a/src/server/app.ts b/src/server/app.ts new file mode 100644 index 0000000..b909438 --- /dev/null +++ b/src/server/app.ts @@ -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; +} + +export async function createGCoordinatorServer( + options: ServerOptions, +): Promise { + 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((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((resolve) => { + httpServer.close(() => resolve()); + }); + db.close(); + }, + }; +} diff --git a/src/server/index.ts b/src/server/index.ts new file mode 100644 index 0000000..fbe1059 --- /dev/null +++ b/src/server/index.ts @@ -0,0 +1,46 @@ +import path from 'node:path'; +import { createGCoordinatorServer } from './app.js'; + +async function main(): Promise { + const dataDir = path.resolve(process.env.GCOORD_DATA_DIR ?? './data'); + const port = Number(process.env.PORT ?? 3000); + const host = process.env.HOST ?? '0.0.0.0'; + const trustCloudflare = process.env.TRUST_CLOUDFLARE === 'true'; + const secretFilePath = + process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key'; + const envMasterKey = process.env.GCOORD_MASTER_KEY; + + const instance = await createGCoordinatorServer({ + dataDir, + port: Number.isFinite(port) ? port : 3000, + host, + secretFilePath, + envMasterKey, + trustCloudflare, + }); + + console.log( + `GCoordinator listening on http://${host}:${instance.port} (vault=${instance.vaultService.state}, data=${dataDir})`, + ); + + let shuttingDown = false; + const shutdown = async (signal: string) => { + if (shuttingDown) return; + shuttingDown = true; + console.log(`Received ${signal}; shutting down gracefully...`); + await instance.close(); + process.exit(0); + }; + + process.on('SIGINT', () => { + void shutdown('SIGINT'); + }); + process.on('SIGTERM', () => { + void shutdown('SIGTERM'); + }); +} + +main().catch((err) => { + console.error('Fatal startup error:', err); + process.exit(1); +});