From 005c82e6bf39bc1f545368cdf3a98f19871ee4b4 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 22:18:02 +0000 Subject: [PATCH] security(egress,guards,docker): add Zero-Trust egress guard, SQLite rate limiter, proxy CIDR trust & Docker hardening --- .dockerignore | 12 ++ docker/Dockerfile | 14 +- docker/docker-compose.lan.yml | 1 + docker/docker-compose.yml | 18 +- src/server/app.ts | 79 ++++++-- src/server/index.ts | 21 +++ src/server/security/egress-guard.ts | 244 +++++++++++++++++++++++++ src/server/security/guards.ts | 269 +++++++++++++++++++++++++--- 8 files changed, 616 insertions(+), 42 deletions(-) create mode 100644 .dockerignore create mode 100644 src/server/security/egress-guard.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..98b322b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +node_modules/ +dist/ +data/ +docker/secrets/ +.git/ +.env +.env.* +*.gcoord.enc +*.tsbuildinfo +coverage/ +tests/ +.DS_Store diff --git a/docker/Dockerfile b/docker/Dockerfile index c473dcc..f2993fc 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -18,19 +18,21 @@ FROM node:22-bookworm-slim AS runtime WORKDIR /app RUN apt-get update && apt-get install -y --no-install-recommends \ - ca-certificates openssh-client rsync zstd tar \ + ca-certificates \ && rm -rf /var/lib/apt/lists/* \ - && mkdir -p /data && chown -R 1000:1000 /app /data + && mkdir -p /data && chown 1000:1000 /data && chmod 0700 /data -COPY --from=builder --chown=1000:1000 /app/package.json ./ -COPY --from=builder --chown=1000:1000 /app/node_modules ./node_modules -COPY --from=builder --chown=1000:1000 /app/dist ./dist +COPY --from=builder /app/package.json ./ +COPY --from=builder /app/node_modules ./node_modules +COPY --from=builder /app/dist ./dist USER 1000:1000 ENV NODE_ENV=production \ PORT=3000 \ - GCOORD_DATA_DIR=/data + HOST=0.0.0.0 \ + GCOORD_DATA_DIR=/data \ + NODE_OPTIONS="--max-old-space-size=384" EXPOSE 3000 diff --git a/docker/docker-compose.lan.yml b/docker/docker-compose.lan.yml index 1b38964..2ccd7dc 100644 --- a/docker/docker-compose.lan.yml +++ b/docker/docker-compose.lan.yml @@ -2,6 +2,7 @@ services: gcoordinator: environment: - TRUST_CLOUDFLARE=false + - GCOORD_ALLOW_LAN_TUNNELS=${GCOORD_ALLOW_LAN_TUNNELS:-false} ports: - "${GCOORD_LAN_BIND:-127.0.0.1}:3000:3000" - "${GCOORD_LAN_BIND:-127.0.0.1}:20000-20020:20000-20020" diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 5451cf0..15a1e1f 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -7,13 +7,22 @@ services: restart: unless-stopped user: "1000:1000" read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + mem_limit: ${GCOORD_MEM_LIMIT:-512m} + pids_limit: 128 tmpfs: - - /tmp + - /tmp:rw,noexec,nosuid,nodev,size=64m environment: - NODE_ENV=production - PORT=3000 + - HOST=0.0.0.0 - GCOORD_DATA_DIR=/data - TRUST_CLOUDFLARE=true + - GCOORD_THROTTLE_MODE=${GCOORD_THROTTLE_MODE:-low-resource} + - NODE_OPTIONS=--max-old-space-size=${GCOORD_NODE_MAX_OLD_SPACE:-384} secrets: - gcoord_master_key volumes: @@ -26,6 +35,13 @@ services: image: cloudflare/cloudflared:latest container_name: gcoordinator-tunnel restart: unless-stopped + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + mem_limit: 128m + pids_limit: 64 command: tunnel --no-autoupdate run environment: - TUNNEL_TOKEN=${CLOUDFLARED_TUNNEL_TOKEN} diff --git a/src/server/app.ts b/src/server/app.ts index 3a0ba6e..a4f433b 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -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((resolve, reject) => { httpServer.once('error', reject); httpServer.listen(options.port, options.host ?? '0.0.0.0', () => { diff --git a/src/server/index.ts b/src/server/index.ts index fbe1059..67672d9 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -1,14 +1,26 @@ import path from 'node:path'; import { createGCoordinatorServer } from './app.js'; +import { normalizeThrottleMode } from './config/runtime-limits.js'; + +function parseCsvList(raw: string | undefined): string[] | undefined { + if (!raw || !raw.trim()) return undefined; + const list = raw + .split(',') + .map((s) => s.trim()) + .filter(Boolean); + return list.length > 0 ? list : undefined; +} 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 trustedProxyCidrs = parseCsvList(process.env.TRUSTED_PROXY_CIDRS); const secretFilePath = process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key'; const envMasterKey = process.env.GCOORD_MASTER_KEY; + const proxyPortRaw = process.env.GCOORD_PROXY_PORT ? Number(process.env.GCOORD_PROXY_PORT) : undefined; const instance = await createGCoordinatorServer({ dataDir, @@ -17,6 +29,15 @@ async function main(): Promise { secretFilePath, envMasterKey, trustCloudflare, + trustedProxyCidrs, + allowLanTunnels: process.env.GCOORD_ALLOW_LAN_TUNNELS === 'true', + proxyBaseDomain: process.env.GCOORD_PROXY_BASE_DOMAIN?.trim() || undefined, + proxyPort: proxyPortRaw && Number.isFinite(proxyPortRaw) ? proxyPortRaw : undefined, + webauthnRpId: process.env.GCOORD_WEBAUTHN_RP_ID?.trim() || undefined, + webauthnOrigins: parseCsvList(process.env.GCOORD_WEBAUTHN_ORIGINS), + metricsToken: process.env.GCOORD_METRICS_TOKEN?.trim() || undefined, + throttleModeOverride: normalizeThrottleMode(process.env.GCOORD_THROTTLE_MODE), + autoKeyFile: process.env.GCOORD_AUTO_KEYFILE === 'true', }); console.log( diff --git a/src/server/security/egress-guard.ts b/src/server/security/egress-guard.ts new file mode 100644 index 0000000..aae5c4b --- /dev/null +++ b/src/server/security/egress-guard.ts @@ -0,0 +1,244 @@ +import dns from 'node:dns'; +import net from 'node:net'; + +export class EgressBlockedError extends Error { + readonly code = 'EGRESS_BLOCKED'; + + constructor(message: string) { + super(message); + this.name = 'EgressBlockedError'; + } +} + +interface ParsedCidr { + family: 4 | 6; + network: bigint; + mask: bigint; +} + +const DEFAULT_BLOCKED_CIDR_STRINGS = [ + '0.0.0.0/8', + '10.0.0.0/8', + '100.64.0.0/10', + '127.0.0.0/8', + '169.254.0.0/16', + '172.16.0.0/12', + '192.0.0.0/24', + '192.168.0.0/16', + '198.18.0.0/15', + '224.0.0.0/4', + '240.0.0.0/4', + '::/128', + '::1/128', + 'fc00::/7', + 'fe80::/10', + 'ff00::/8', + 'fd00:ec2::254/128', +]; + +function stripZoneAndBrackets(raw: string): { ip: string; hasZone: boolean } { + let s = raw.trim(); + if (s.startsWith('[') && s.endsWith(']')) { + s = s.slice(1, -1); + } + const pct = s.indexOf('%'); + if (pct >= 0) { + return { ip: s.slice(0, pct), hasZone: true }; + } + return { ip: s, hasZone: false }; +} + +function parseIpv4ToBigInt(ip: string): bigint | null { + const parts = ip.split('.'); + if (parts.length !== 4) return null; + let val = 0n; + for (const part of parts) { + if (!/^\d{1,3}$/.test(part)) return null; + const n = Number(part); + if (n < 0 || n > 255) return null; + val = (val << 8n) | BigInt(n); + } + return val; +} + +function parseIpv6ToBigInt(ip: string): bigint | null { + let s = ip.toLowerCase(); + const lastColon = s.lastIndexOf(':'); + if (lastColon >= 0 && s.includes('.')) { + const v4Part = s.slice(lastColon + 1); + const v4 = parseIpv4ToBigInt(v4Part); + if (v4 === null) return null; + const hi = Number((v4 >> 16n) & 0xffffn).toString(16); + const lo = Number(v4 & 0xffffn).toString(16); + s = `${s.slice(0, lastColon)}:${hi}:${lo}`; + } + + const dblIdx = s.indexOf('::'); + let groups: string[]; + if (dblIdx >= 0) { + if (s.indexOf('::', dblIdx + 2) >= 0) return null; + const left = dblIdx === 0 ? [] : s.slice(0, dblIdx).split(':'); + const right = dblIdx + 2 >= s.length ? [] : s.slice(dblIdx + 2).split(':'); + const missing = 8 - (left.length + right.length); + if (missing < 1) return null; + groups = [...left, ...Array(missing).fill('0'), ...right]; + } else { + groups = s.split(':'); + if (groups.length !== 8) return null; + } + + let out = 0n; + for (const g of groups) { + if (!/^[0-9a-f]{1,4}$/.test(g)) return null; + out = (out << 16n) | BigInt(parseInt(g, 16)); + } + return out; +} + +function parseIpNormalized(rawIp: string): { family: 4 | 6; value: bigint; hasZone: boolean } | null { + const { ip, hasZone } = stripZoneAndBrackets(rawIp); + const kind = net.isIP(ip); + if (kind === 4) { + const value = parseIpv4ToBigInt(ip); + return value === null ? null : { family: 4, value, hasZone }; + } + if (kind === 6) { + const v6 = parseIpv6ToBigInt(ip); + if (v6 === null) return null; + // Unwrap IPv4-mapped IPv6 addresses (::ffff:0:0/96) + if ((v6 >> 32n) === 0xffffn) { + return { family: 4, value: v6 & 0xffffffffn, hasZone }; + } + return { family: 6, value: v6, hasZone }; + } + return null; +} + +export function parseCidr(raw: string): ParsedCidr | null { + const trimmed = raw.trim(); + if (!trimmed) return null; + const slash = trimmed.indexOf('/'); + const ipStr = slash >= 0 ? trimmed.slice(0, slash) : trimmed; + const parsed = parseIpNormalized(ipStr); + if (!parsed) return null; + + const totalBits = parsed.family === 4 ? 32 : 128; + const prefixLen = + slash >= 0 ? Number(trimmed.slice(slash + 1)) : totalBits; + if (!Number.isInteger(prefixLen) || prefixLen < 0 || prefixLen > totalBits) { + return null; + } + + const shift = BigInt(totalBits - prefixLen); + const fullMask = parsed.family === 4 ? 0xffffffffn : (1n << 128n) - 1n; + const mask = prefixLen === 0 ? 0n : (fullMask << shift) & fullMask; + return { + family: parsed.family, + network: parsed.value & mask, + mask, + }; +} + +const DEFAULT_BLOCKED_CIDRS: ParsedCidr[] = DEFAULT_BLOCKED_CIDR_STRINGS + .map((c) => parseCidr(c)!) + .filter(Boolean); + +export function isIpInCidrs(rawIp: string, cidrs: string[]): boolean { + const parsed = parseIpNormalized(rawIp); + if (!parsed) return false; + for (const rawCidr of cidrs) { + const cidr = parseCidr(rawCidr); + if (!cidr || cidr.family !== parsed.family) continue; + if ((parsed.value & cidr.mask) === cidr.network) { + return true; + } + } + return false; +} + +export function isBlockedByDefaultIp(rawIp: string): boolean { + const parsed = parseIpNormalized(rawIp); + if (!parsed || parsed.hasZone) return true; + for (const cidr of DEFAULT_BLOCKED_CIDRS) { + if (cidr.family === parsed.family && (parsed.value & cidr.mask) === cidr.network) { + return true; + } + } + return false; +} + +export async function assertEgressHostAllowed( + rawHost: string, + allowedCidrs: string[] = [], +): Promise { + const { ip: cleanHost } = stripZoneAndBrackets(rawHost); + if (!cleanHost) { + throw new EgressBlockedError('Empty egress destination host'); + } + + if (net.isIP(cleanHost) !== 0) { + if (isBlockedByDefaultIp(rawHost) && !isIpInCidrs(rawHost, allowedCidrs)) { + throw new EgressBlockedError( + `Egress to non-public IP "${cleanHost}" is blocked by Zero-Trust egress policy`, + ); + } + return; + } + + let records: dns.LookupAddress[]; + try { + records = await dns.promises.lookup(cleanHost, { all: true, verbatim: true }); + } catch (err) { + throw new EgressBlockedError( + `Failed to resolve egress host "${cleanHost}": ${err instanceof Error ? err.message : String(err)}`, + ); + } + + if (records.length === 0) { + throw new EgressBlockedError(`Egress host "${cleanHost}" resolved to no addresses`); + } + + for (const rec of records) { + if (isBlockedByDefaultIp(rec.address) && !isIpInCidrs(rec.address, allowedCidrs)) { + throw new EgressBlockedError( + `Egress host "${cleanHost}" resolved to blocked address ${rec.address}`, + ); + } + } +} + +export async function assertEgressUrlAllowed( + rawUrl: string, + allowedCidrs: string[] = [], +): Promise { + let url: URL; + try { + url = new URL(rawUrl); + } catch { + throw new EgressBlockedError(`Invalid URL "${rawUrl}"`); + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new EgressBlockedError(`Unsupported egress URL scheme "${url.protocol}"`); + } + await assertEgressHostAllowed(url.hostname, allowedCidrs); + return url; +} + +export async function fetchWithEgressGuard( + rawUrl: string, + init: RequestInit = {}, + opts: { allowedCidrs?: string[]; timeoutMs?: number } = {}, +): Promise { + const url = await assertEgressUrlAllowed(rawUrl, opts.allowedCidrs ?? []); + const timeoutMs = Math.max(500, Math.min(300_000, opts.timeoutMs ?? 15_000)); + const timeoutSignal = AbortSignal.timeout(timeoutMs); + const signal = init.signal + ? AbortSignal.any([init.signal, timeoutSignal]) + : timeoutSignal; + + return fetch(url.toString(), { + ...init, + redirect: 'error', + signal, + }); +} diff --git a/src/server/security/guards.ts b/src/server/security/guards.ts index 470383d..cf445b5 100644 --- a/src/server/security/guards.ts +++ b/src/server/security/guards.ts @@ -1,12 +1,16 @@ import crypto from 'node:crypto'; -import type { NextFunction, Request, Response } from 'express'; +import net from 'node:net'; +import type Database from 'better-sqlite3'; +import type { NextFunction, Request, RequestHandler, Response } from 'express'; import type { StepUpPolicy } from '../../shared/schemas/settings.schema.js'; +import type { AuditService } from './audit.js'; import { SESSION_COOKIE_NAME, sha256Hex, type AuthService, type AuthSession, } from './auth.js'; +import { isIpInCidrs } from './egress-guard.js'; declare global { namespace Express { @@ -17,54 +21,207 @@ declare global { } } +export const DEFAULT_TRUSTED_PROXY_CIDRS = [ + '127.0.0.0/8', + '::1/128', + '10.0.0.0/8', + '172.16.0.0/12', + '192.168.0.0/16', + 'fc00::/7', +]; + interface RateBucketState { failures: number; lockedUntil: number; + updatedAt: number; } +const DECAY_WINDOW_MS = 60 * 60 * 1000; +const MAX_INMEM_BUCKETS = 2000; +const GLOBAL_LOGIN_THRESHOLD = 20; + export class RateLimiter { private readonly buckets = new Map(); + private readonly inFlightCounts = new Map(); + private readonly db?: Database.Database; + private lastPruneAt = 0; + + constructor(options: { db?: Database.Database } = {}) { + this.db = options.db; + } check(scope: string, ip: string): { allowed: boolean; retryAfterSec: number } { const key = `${scope}:${ip}`; - const state = this.buckets.get(key); - if (!state) return { allowed: true, retryAfterSec: 0 }; - + const state = this.readBucket(key); const now = Date.now(); - if (state.lockedUntil > now) { + if (state && state.lockedUntil > now) { return { allowed: false, retryAfterSec: Math.max(1, Math.ceil((state.lockedUntil - now) / 1000)), }; } + + if (scope === 'login') { + const globalState = this.readBucket('login:__global__'); + if (globalState && globalState.lockedUntil > now) { + return { + allowed: false, + retryAfterSec: Math.max(1, Math.ceil((globalState.lockedUntil - now) / 1000)), + }; + } + } + return { allowed: true, retryAfterSec: 0 }; } - recordFailure(scope: string, ip: string): number { + acquireInFlight(scope: string, ip: string, maxConcurrent = 2): boolean { const key = `${scope}:${ip}`; - const prev = this.buckets.get(key) ?? { failures: 0, lockedUntil: 0 }; - const failures = prev.failures + 1; + const cur = this.inFlightCounts.get(key) ?? 0; + if (cur >= maxConcurrent) return false; + this.inFlightCounts.set(key, cur + 1); + return true; + } + + releaseInFlight(scope: string, ip: string): void { + const key = `${scope}:${ip}`; + const cur = this.inFlightCounts.get(key) ?? 0; + if (cur <= 1) { + this.inFlightCounts.delete(key); + } else { + this.inFlightCounts.set(key, cur - 1); + } + } + + recordFailure(scope: string, ip: string): { lockedUntil: number; failures: number; globalTriggered: boolean } { + const now = Date.now(); + const key = `${scope}:${ip}`; + const prev = this.readBucket(key); + const baseFailures = + prev && (now - prev.updatedAt <= DECAY_WINDOW_MS || prev.lockedUntil > now) + ? prev.failures + : 0; + const failures = baseFailures + 1; let lockedUntil = 0; if (failures >= 5) { const delayMs = Math.min(300_000, 2000 * 2 ** (failures - 5)); - lockedUntil = Date.now() + delayMs; + lockedUntil = now + delayMs; } - this.buckets.set(key, { failures, lockedUntil }); - return lockedUntil; + this.writeBucket(key, { failures, lockedUntil, updatedAt: now }); + + let globalTriggered = false; + if (scope === 'login') { + const gPrev = this.readBucket('login:__global__'); + const gBase = + gPrev && (now - gPrev.updatedAt <= 15 * 60 * 1000 || gPrev.lockedUntil > now) + ? gPrev.failures + : 0; + const gFailures = gBase + 1; + let gLockedUntil = gPrev?.lockedUntil ?? 0; + if (gFailures >= GLOBAL_LOGIN_THRESHOLD) { + const gDelay = Math.min(300_000, 60_000 * 2 ** Math.min(3, Math.floor((gFailures - GLOBAL_LOGIN_THRESHOLD) / 5))); + gLockedUntil = now + gDelay; + globalTriggered = true; + } + this.writeBucket('login:__global__', { + failures: gFailures, + lockedUntil: gLockedUntil, + updatedAt: now, + }); + } + + return { lockedUntil, failures, globalTriggered }; } recordSuccess(scope: string, ip: string): void { - this.buckets.delete(`${scope}:${ip}`); + this.deleteBucket(`${scope}:${ip}`); + if (scope === 'login') { + this.deleteBucket('login:__global__'); + } + } + + private readBucket(key: string): RateBucketState | undefined { + if (this.db) { + try { + const row = this.db + .prepare( + 'SELECT failures, locked_until AS lockedUntil, updated_at AS updatedAt FROM rate_limits WHERE scope_key = ?', + ) + .get(key) as RateBucketState | undefined; + if (!row) return undefined; + const now = Date.now(); + if (row.lockedUntil <= now && now - row.updatedAt > DECAY_WINDOW_MS) { + this.deleteBucket(key); + return undefined; + } + return row; + } catch { + // Fallback to in-memory map if DB unavailable + } + } + + const mem = this.buckets.get(key); + if (!mem) return undefined; + const now = Date.now(); + if (mem.lockedUntil <= now && now - mem.updatedAt > DECAY_WINDOW_MS) { + this.buckets.delete(key); + return undefined; + } + return mem; + } + + private writeBucket(key: string, state: RateBucketState): void { + if (this.db) { + try { + this.db + .prepare( + `INSERT INTO rate_limits (scope_key, failures, locked_until, updated_at) + VALUES (?, ?, ?, ?) + ON CONFLICT(scope_key) DO UPDATE SET + failures = excluded.failures, + locked_until = excluded.locked_until, + updated_at = excluded.updated_at`, + ) + .run(key, state.failures, state.lockedUntil, state.updatedAt); + + if (state.updatedAt - this.lastPruneAt > 10 * 60 * 1000) { + this.lastPruneAt = state.updatedAt; + this.db + .prepare('DELETE FROM rate_limits WHERE locked_until <= ? AND updated_at < ?') + .run(state.updatedAt, state.updatedAt - DECAY_WINDOW_MS); + } + return; + } catch { + // Fallback below + } + } + + if (this.buckets.size >= MAX_INMEM_BUCKETS && !this.buckets.has(key)) { + const oldestKey = this.buckets.keys().next().value; + if (oldestKey) this.buckets.delete(oldestKey); + } + this.buckets.set(key, state); + } + + private deleteBucket(key: string): void { + if (this.db) { + try { + this.db.prepare('DELETE FROM rate_limits WHERE scope_key = ?').run(key); + } catch { + // Ignore DB error + } + } + this.buckets.delete(key); } } export function extractCookies(cookieHeader: string | undefined): Record { - const result: Record = {}; + const result = Object.create(null) as Record; if (!cookieHeader) return result; for (const part of cookieHeader.split(';')) { const eq = part.indexOf('='); if (eq <= 0) continue; const key = part.slice(0, eq).trim(); + if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue; const rawVal = part.slice(eq + 1).trim(); try { result[key] = decodeURIComponent(rawVal); @@ -75,23 +232,54 @@ export function extractCookies(cookieHeader: string | undefined): Record 0) { - return cf.split(',')[0]!.trim(); - } - } - return req.ip || req.socket.remoteAddress || 'unknown'; +export function isTrustedProxyPeer( + remoteAddr: string | undefined, + trustedProxyCidrs: string[] = DEFAULT_TRUSTED_PROXY_CIDRS, +): boolean { + if (!remoteAddr) return false; + return isIpInCidrs(remoteAddr, trustedProxyCidrs); } -export function attachClientIp(trustCloudflare: boolean) { +export function resolveClientIp( + req: Request, + trustCloudflare: boolean, + trustedProxyCidrs: string[] = DEFAULT_TRUSTED_PROXY_CIDRS, +): string { + const peerIp = req.socket?.remoteAddress; + if (trustCloudflare && isTrustedProxyPeer(peerIp, trustedProxyCidrs)) { + const cf = req.headers['cf-connecting-ip']; + if (typeof cf === 'string' && cf.trim().length > 0) { + const candidate = cf.split(',')[0]!.trim(); + if (net.isIP(candidate) !== 0) { + return candidate; + } + } + } + return req.ip || peerIp || 'unknown'; +} + +export function attachClientIp( + trustCloudflare: boolean, + trustedProxyCidrs: string[] = DEFAULT_TRUSTED_PROXY_CIDRS, +) { return (req: Request, _res: Response, next: NextFunction): void => { - req.clientIp = resolveClientIp(req, trustCloudflare); + req.clientIp = resolveClientIp(req, trustCloudflare, trustedProxyCidrs); next(); }; } +export function asyncHandler( + fn: (req: Request, res: Response, next: NextFunction) => Promise | void, +): RequestHandler { + return (req, res, next) => { + Promise.resolve(fn(req, res, next)).catch(next); + }; +} + +function getAudit(req: Request): AuditService | undefined { + return req.app?.locals?.auditService as AuditService | undefined; +} + export function requireAuth(authService: AuthService) { return (req: Request, res: Response, next: NextFunction): void => { const cookies = extractCookies(req.headers.cookie); @@ -118,6 +306,13 @@ export function requireCsrf(req: Request, res: Response, next: NextFunction): vo } const headerToken = req.headers['x-csrf-token']; if (typeof headerToken !== 'string' || headerToken.length < 16) { + getAudit(req)?.log({ + action: 'security.csrf_denied', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: session.idHash, + target: `${req.method} ${req.path}`, + status: 'denied', + }); res.status(403).json({ error: 'CSRF_INVALID' }); return; } @@ -127,6 +322,13 @@ export function requireCsrf(req: Request, res: Response, next: NextFunction): vo providedHash.length !== expectedHash.length || !crypto.timingSafeEqual(providedHash, expectedHash) ) { + getAudit(req)?.log({ + action: 'security.csrf_denied', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: session.idHash, + target: `${req.method} ${req.path}`, + status: 'denied', + }); res.status(403).json({ error: 'CSRF_INVALID' }); return; } @@ -140,6 +342,13 @@ export function enforceSafeMode(req: Request, res: Response, next: NextFunction) } const clientSafeHeader = req.headers['x-gcoord-safe-mode'] === '1'; if (req.authSession?.safeMode || clientSafeHeader) { + getAudit(req)?.log({ + action: 'security.safe_mode_denied', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession?.idHash ?? null, + target: `${req.method} ${req.path}`, + status: 'denied', + }); res.status(423).json({ error: 'SAFE_MODE_ACTIVE', message: 'Disable Safe / Read-Only Mode before performing mutating actions.', @@ -167,6 +376,13 @@ export function createStepUpGuard( } if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) { + getAudit(req)?.log({ + action: 'security.stepup_denied', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: session.idHash, + target: `${req.method} ${req.path}`, + status: 'denied', + }); res.status(403).json({ error: 'STEP_UP_REQUIRED', message: 'Re-authentication verification is required for this sensitive operation.', @@ -189,6 +405,13 @@ export function requireStepUp(req: Request, res: Response, next: NextFunction): return; } if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) { + getAudit(req)?.log({ + action: 'security.stepup_denied', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: session.idHash, + target: `${req.method} ${req.path}`, + status: 'denied', + }); res.status(403).json({ error: 'STEP_UP_REQUIRED', message: 'Re-authentication verification is required for this sensitive operation.',