security(egress,guards,docker): add Zero-Trust egress guard, SQLite rate limiter, proxy CIDR trust & Docker hardening
This commit is contained in:
parent
afc2d6358a
commit
005c82e6bf
8 changed files with 616 additions and 42 deletions
|
|
@ -2,23 +2,27 @@ 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 express, { type Express, type NextFunction, type Request, type Response } from 'express';
|
||||
import type { ThrottleMode } from '../shared/schemas/settings.schema.js';
|
||||
import { AiService } from './ai/ai-service.js';
|
||||
import { AlertEngine } from './alerts/alert-engine.js';
|
||||
import { BroadcastService } from './automation/broadcast-service.js';
|
||||
import { TransferEngine } from './automation/transfer-engine.js';
|
||||
import { WorkflowEngine } from './automation/workflow-engine.js';
|
||||
import { ConfigManager } from './config/config-manager.js';
|
||||
import { openDatabase } from './db/database.js';
|
||||
import { resolveRuntimeLimits } from './config/runtime-limits.js';
|
||||
import { applyDatabaseThrottlePragmas, 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 {
|
||||
DEFAULT_TRUSTED_PROXY_CIDRS,
|
||||
RateLimiter,
|
||||
attachClientIp,
|
||||
createStepUpGuard,
|
||||
isTrustedProxyPeer,
|
||||
} from './security/guards.js';
|
||||
import { EmergencyRecoveryService } from './security/recovery-store.js';
|
||||
import { VaultService } from './security/vault.js';
|
||||
|
|
@ -53,6 +57,15 @@ export interface ServerOptions {
|
|||
secretFilePath?: string;
|
||||
envMasterKey?: string;
|
||||
trustCloudflare?: boolean;
|
||||
trustedProxyCidrs?: string[];
|
||||
allowLanTunnels?: boolean;
|
||||
proxyBaseDomain?: string;
|
||||
proxyPort?: number;
|
||||
webauthnRpId?: string;
|
||||
webauthnOrigins?: string[];
|
||||
metricsToken?: string;
|
||||
throttleModeOverride?: ThrottleMode;
|
||||
autoKeyFile?: boolean;
|
||||
watchConfig?: boolean;
|
||||
}
|
||||
|
||||
|
|
@ -92,8 +105,14 @@ export async function createGCoordinatorServer(
|
|||
const dbPath = path.join(dataDir, 'gcoord.db');
|
||||
const vaultPath = path.join(dataDir, 'vault.enc');
|
||||
const trustCloudflare = Boolean(options.trustCloudflare);
|
||||
const trustedProxyCidrs = options.trustedProxyCidrs ?? DEFAULT_TRUSTED_PROXY_CIDRS;
|
||||
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
|
||||
try {
|
||||
fs.chmodSync(dataDir, 0o700);
|
||||
} catch {
|
||||
// Best-effort on filesystems without POSIX permissions
|
||||
}
|
||||
|
||||
const db = openDatabase(dbPath);
|
||||
const auditService = new AuditService(db);
|
||||
|
|
@ -101,11 +120,18 @@ export async function createGCoordinatorServer(
|
|||
keyFilePath: path.join(dataDir, 'vault.key'),
|
||||
});
|
||||
const recoveryStore = new EmergencyRecoveryService(dataDir);
|
||||
const rateLimiter = new RateLimiter();
|
||||
const rateLimiter = new RateLimiter({ db });
|
||||
const configManager = new ConfigManager(configDir, db, vaultService);
|
||||
|
||||
await configManager.init({ watch: options.watchConfig ?? true });
|
||||
|
||||
const getRuntimeLimits = () =>
|
||||
resolveRuntimeLimits(
|
||||
configManager.getSettings().runtime?.throttleMode ?? 'low-resource',
|
||||
options.throttleModeOverride,
|
||||
);
|
||||
applyDatabaseThrottlePragmas(db, getRuntimeLimits());
|
||||
|
||||
const authService = new AuthService(db, {
|
||||
getSecuritySettings: () => configManager.getSettings().security,
|
||||
recoveryStore,
|
||||
|
|
@ -129,9 +155,10 @@ export async function createGCoordinatorServer(
|
|||
}
|
||||
|
||||
const app = express();
|
||||
app.locals.auditService = auditService;
|
||||
app.disable('x-powered-by');
|
||||
if (trustCloudflare) {
|
||||
app.set('trust proxy', 1);
|
||||
app.set('trust proxy', (ip: string) => isTrustedProxyPeer(ip, trustedProxyCidrs));
|
||||
}
|
||||
|
||||
const httpServer = http.createServer(app);
|
||||
|
|
@ -256,17 +283,30 @@ export async function createGCoordinatorServer(
|
|||
app.use((req, res, next) => {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Referrer-Policy', 'no-referrer');
|
||||
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
|
||||
if (req.secure || trustCloudflare) {
|
||||
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
|
||||
}
|
||||
if (req.path.startsWith('/api/')) {
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.setHeader('Pragma', 'no-cache');
|
||||
}
|
||||
if (!req.path.startsWith('/proxy/')) {
|
||||
const rawHost = typeof req.headers.host === 'string' ? req.headers.host.trim() : '';
|
||||
const safeHost = /^[A-Za-z0-9.\-:\[\]]+$/.test(rawHost) ? rawHost : '';
|
||||
const connectSrc = safeHost
|
||||
? `'self' ws://${safeHost} wss://${safeHost}`
|
||||
: `'self'`;
|
||||
res.setHeader('X-Frame-Options', 'DENY');
|
||||
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'",
|
||||
`default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src ${connectSrc}; object-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'self'`,
|
||||
);
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
app.use(attachClientIp(trustCloudflare));
|
||||
app.use(attachClientIp(trustCloudflare, trustedProxyCidrs));
|
||||
// Mount /proxy before express.json so proxied POST/PUT payloads stream untouched upstream
|
||||
app.use('/proxy', createProxyRouter({ authService, tunnelManager }));
|
||||
|
||||
|
|
@ -350,6 +390,7 @@ export async function createGCoordinatorServer(
|
|||
customSystemsEngine.invalidateCache();
|
||||
}
|
||||
if (event.entityType === 'settings') {
|
||||
applyDatabaseThrottlePragmas(db, getRuntimeLimits());
|
||||
authService.syncRecovery();
|
||||
}
|
||||
monitoringService.syncServers();
|
||||
|
|
@ -365,11 +406,7 @@ export async function createGCoordinatorServer(
|
|||
);
|
||||
|
||||
app.get('/api/healthz', (_req, res) => {
|
||||
res.json({
|
||||
ok: true,
|
||||
vaultState: vaultService.state,
|
||||
vaultRuntimeReady: vaultService.isRuntimeReady,
|
||||
});
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.use(
|
||||
|
|
@ -508,6 +545,24 @@ export async function createGCoordinatorServer(
|
|||
});
|
||||
}
|
||||
|
||||
app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {
|
||||
const statusErr = err as { status?: number; type?: string; message?: string };
|
||||
const status =
|
||||
typeof statusErr?.status === 'number' && statusErr.status >= 400 && statusErr.status < 600
|
||||
? statusErr.status
|
||||
: 500;
|
||||
if (!res.headersSent) {
|
||||
res.status(status).json({
|
||||
error: status === 413 || statusErr?.type === 'entity.too.large'
|
||||
? 'PAYLOAD_TOO_LARGE'
|
||||
: status < 500
|
||||
? 'BAD_REQUEST'
|
||||
: 'INTERNAL_SERVER_ERROR',
|
||||
message: status < 500 && statusErr?.message ? statusErr.message : 'Internal server error',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
httpServer.once('error', reject);
|
||||
httpServer.listen(options.port, options.host ?? '0.0.0.0', () => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue