refactor(server): bootstrap and middleware read config via app-config

This commit is contained in:
jubnl
2026-07-25 15:17:33 +02:00
parent e17f165e44
commit a34ab288f5
9 changed files with 45 additions and 22 deletions
+2 -1
View File
@@ -1,5 +1,6 @@
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { readEnv } from '../app-config';
import { db } from '../db/database';
import { JWT_SECRET } from '../config';
import { AuthRequest, OptionalAuthRequest, User } from '../types';
@@ -109,7 +110,7 @@ const adminOnly = (req: Request, res: Response, next: NextFunction): void => {
const demoUploadBlock = (req: Request, res: Response, next: NextFunction): void => {
const authReq = req as AuthRequest;
if (process.env.DEMO_MODE?.toLowerCase() === 'true' && isDemoEmail(authReq.user?.email)) {
if (readEnv().demo.enabled && isDemoEmail(authReq.user?.email)) {
res.status(403).json({ error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' });
return;
}
+17 -11
View File
@@ -3,6 +3,7 @@ import compression from 'compression';
import cors from 'cors';
import helmet from 'helmet';
import cookieParser from 'cookie-parser';
import { readEnv, type AppEnv } from '../app-config';
import { logDebug, logWarn, logError } from '../services/auditLog';
import { enforceGlobalMfaPolicy } from './mfaPolicy';
@@ -20,13 +21,18 @@ import { enforceGlobalMfaPolicy } from './mfaPolicy';
*/
export function applyGlobalMiddleware(
app: express.Application,
opts: { bodyParser?: boolean } = {},
opts: { bodyParser?: boolean; http?: AppEnv['http'] } = {},
): void {
const { bodyParser = true } = opts;
// The whole pipeline is configured at APPLY time (the per-request closures
// capture these values), so a snapshot is the correct semantic. bootstrap
// threads in the DI-loaded httpConfig; direct callers fall back to an
// apply-time readEnv() — same values, same freeze point.
const { bodyParser = true, http = readEnv().http } = opts;
const { nodeEnv, isProduction } = readEnv().app;
// Trust first proxy (nginx/Docker) for correct req.ip
if (process.env.NODE_ENV?.toLowerCase() === 'production' || process.env.TRUST_PROXY) {
app.set('trust proxy', Number.parseInt(process.env.TRUST_PROXY) || 1);
if (isProduction || http.trustProxyRaw) {
app.set('trust proxy', http.trustProxy);
}
// Compress responses (gzip via Accept-Encoding). The Atlas admin-0 country
@@ -44,9 +50,7 @@ export function applyGlobalMiddleware(
}),
);
const allowedOrigins = process.env.ALLOWED_ORIGINS
? process.env.ALLOWED_ORIGINS.split(',').map(o => o.trim()).filter(Boolean)
: null;
const allowedOrigins = http.corsOrigins;
let corsOrigin: cors.CorsOptions['origin'];
if (allowedOrigins) {
@@ -54,13 +58,13 @@ export function applyGlobalMiddleware(
if (!origin || allowedOrigins.includes(origin)) callback(null, true);
else callback(new Error('Not allowed by CORS'));
};
} else if (process.env.NODE_ENV?.toLowerCase() === 'production') {
} else if (isProduction) {
corsOrigin = false;
} else {
corsOrigin = true;
}
const shouldForceHttps = process.env.FORCE_HTTPS?.toLowerCase() === 'true';
const shouldForceHttps = http.forceHttps;
// HSTS is worth enabling any time we're serving production traffic,
// not only when FORCE_HTTPS is set. Self-hosters behind Traefik /
// Caddy / Cloudflare Tunnel typically leave FORCE_HTTPS unset (the
@@ -72,8 +76,10 @@ export function applyGlobalMiddleware(
// sibling subdomain the same operator may still be running over plain
// HTTP. Operators who want the stricter policy opt in with
// `HSTS_INCLUDE_SUBDOMAINS=true`.
const hstsActive = shouldForceHttps || process.env.NODE_ENV === 'production';
const hstsIncludeSubdomains = process.env.HSTS_INCLUDE_SUBDOMAINS === 'true';
// nodeEnv compared case-sensitively here on purpose (legacy parity — the
// trust-proxy/CORS checks above are the case-insensitive ones).
const hstsActive = shouldForceHttps || nodeEnv === 'production';
const hstsIncludeSubdomains = http.hstsIncludeSubdomains;
// RFC 8414 / RFC 9728 / RFC 7591: discovery docs and DCR are world-readable/writable.
// /mcp needs open CORS so external MCP clients (ChatGPT, Claude.ai, Inspector) can call it
+2 -1
View File
@@ -1,4 +1,5 @@
import { Request, Response, NextFunction } from 'express';
import { readEnv } from '../app-config';
import { db } from '../db/database';
import { extractToken, verifyJwtAndLoadUser } from './auth';
import { DEMO_EMAILS } from '../services/demo';
@@ -76,7 +77,7 @@ export function enforceGlobalMfaPolicy(req: Request, res: Response, next: NextFu
return;
}
if (process.env.DEMO_MODE?.toLowerCase() === 'true' && verified.email && DEMO_EMAILS.has(verified.email)) {
if (readEnv().demo.enabled && verified.email && DEMO_EMAILS.has(verified.email)) {
next();
return;
}