Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(bootstrap): run the production HTTP stack in the e2e lane

Yudhi Armyndharis8d26f6fdfb2d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7232061c7..12a244202 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The dashboard CSP nonce is substituted at every occurrence in the served document, not only the first. One placeholder exists today, so a second would have been left reading the literal text and its script refused by the browser.
+### Tests
+
+- The production HTTP stack is assembled by one `configureApp` that `main.ts` and the e2e suites both call, so the nonce, body caps, CORS and the SPA document handler are executed by tests instead of only in production.
+- The serve-static suite drops its own copy of the document handler, which omitted the nonce injection, and exercises the real one.
+
## [0.22.0] - 2026-08-19
### Fixed
diff --git a/docs/04-security-design.md b/docs/04-security-design.md
index 1e0fffc38..bf2c52dbf 100644
--- a/docs/04-security-design.md
+++ b/docs/04-security-design.md
@@ -388,7 +388,7 @@ media shedding, so it is small. The HMAC signature is computed over the exact sh
### Helmet Configuration
-The shipped configuration lives in `src/main.ts` — that file is the source of truth:
+The shipped configuration lives in `src/configure-app.ts` (the HTTP stack `main.ts` and the e2e suites both install), and that file is the source of truth:
```typescript
app.use(helmet({
diff --git a/src/common/security/bull-board-auth.middleware.spec.ts b/src/common/security/bull-board-auth.middleware.spec.ts
index adb380a5b..29b7d8c9b 100644
--- a/src/common/security/bull-board-auth.middleware.spec.ts
+++ b/src/common/security/bull-board-auth.middleware.spec.ts
@@ -441,11 +441,17 @@ describe('a queue-dashboard denial is attributable to the credential', () => {
// The stamp is a no-op outside a request-context scope, so the mount order in main.ts is load
// bearing. Nothing else binds it; a reordering would silently return the null rows this fixed.
it('keeps requestContextMiddleware installed ahead of the queue-dashboard mount', () => {
- const main = fs.readFileSync(path.join(__dirname, '..', '..', 'main.ts'), 'utf8');
- const contextAt = main.indexOf('app.use(requestContextMiddleware)');
+ // The guarantee now spans two files: configure-app.ts installs the middleware, and main.ts
+ // calls it before mounting the board. Reading only one of them would leave half the order
+ // unbound.
+ const read = (...parts: string[]): string => fs.readFileSync(path.join(__dirname, '..', '..', ...parts), 'utf8');
+ expect(read('configure-app.ts')).toContain('app.use(requestContextMiddleware)');
+
+ const main = read('main.ts');
+ const configureAt = main.indexOf('configureApp(app)');
const boardAt = main.indexOf('new BullBoardAuthMiddleware');
- expect(contextAt).toBeGreaterThan(-1);
+ expect(configureAt).toBeGreaterThan(-1);
expect(boardAt).toBeGreaterThan(-1);
- expect(contextAt).toBeLessThan(boardAt);
+ expect(configureAt).toBeLessThan(boardAt);
});
});
diff --git a/src/config/inflight-body-budget.spec.ts b/src/config/inflight-body-budget.spec.ts
index 01230d6d2..0acc75258 100644
--- a/src/config/inflight-body-budget.spec.ts
+++ b/src/config/inflight-body-budget.spec.ts
@@ -664,8 +664,10 @@ describe('compressed request bodies', () => {
describe('body-parser inflate backstop', () => {
const read = (relative: string): string => readFileSync(resolve(__dirname, relative), 'utf8');
- it('disables inflate on both global parsers in main.ts', () => {
- const source = read('../main.ts');
+ it('disables inflate on both global parsers', () => {
+ // The parsers live in configure-app.ts, which is where the production stack is assembled; they
+ // sat inline in main.ts until that stack was extracted so the e2e lane could run it too.
+ const source = read('../configure-app.ts');
expect(source.match(/^\s+inflate: false,$/gm)).toHaveLength(2);
});
diff --git a/src/configure-app.ts b/src/configure-app.ts
new file mode 100644
index 000000000..1b0d29093
--- /dev/null
+++ b/src/configure-app.ts
@@ -0,0 +1,240 @@
+import { INestApplication } from '@nestjs/common';
+import helmet from 'helmet';
+import { Request, Response, NextFunction, json, urlencoded } from 'express';
+import { randomBytes } from 'crypto';
+import { existsSync, readFileSync } from 'fs';
+import { extname, join } from 'path';
+import { DASHBOARD_DIST, dashboardServingEnabled, dashboardBuildPresent } from './app.module';
+import { createInflightBodyBudget, resolveInflightBodyBudgetBytes } from './config/inflight-body-budget';
+import { requestContextMiddleware } from './common/middleware/request-context.middleware';
+import { injectDashboardCspNonce } from './config/dashboard-csp';
+import { resolveCorsPolicy, isUpgradeInsecureRequestsEnabled, resolveBodyLimit } from './config/bootstrap-security';
+
+/** Where the bundled dashboard documents come from, and whether to serve them at all. */
+export interface DashboardSource {
+ distDir: string;
+ enabled: boolean;
+}
+
+export interface ConfigureAppOptions {
+ /**
+ * Defaults to what app.module resolved at import time. An e2e overrides it to point the REAL
+ * document handler at a fixture directory: the path is a module constant derived from __dirname,
+ * so without this seam a suite could only re-implement the handler, and a divergence between the
+ * copy and the original would pass.
+ */
+ dashboard?: DashboardSource;
+}
+
+/** The request-body caps this applied, so the caller can log them. */
+export interface AppliedBodyCaps {
+ bodyLimit: string;
+ inflightBudgetBytes: number;
+}
+
+/**
+ * Everything the production HTTP surface installs on the Express app: the in-flight body budget,
+ * the body parsers, request context, the CSP nonce, helmet, the SPA document handler and CORS.
+ *
+ * It lives here rather than inside bootstrap() so the e2e lane can run the SAME stack. main.ts
+ * boots on import, so a suite cannot import it; the whole stack was therefore executed by nothing,
+ * and the one suite that needed the document handler carried its own copy of it.
+ *
+ * ORDER IS LOAD-BEARING. The budget must precede the parsers (a refused connection must not buffer
+ * a byte), and the nonce must precede helmet (the CSP directive reads res.locals.cspNonce).
+ */
+export function configureApp(app: INestApplication, options: ConfigureAppOptions = {}): AppliedBodyCaps {
+ const dashboard: DashboardSource = options.dashboard ?? {
+ distDir: DASHBOARD_DIST,
+ enabled: dashboardServingEnabled && dashboardBuildPresent,
+ };
+
+ // Aggregate in-flight body budget (DoS hardening): once too many body bytes are being buffered
+ // across ALL connections, new requests get 503 + Retry-After without their body being read.
+ // This is a deliberate PRE-GUARD: the throttler/auth guards run at the Nest routing layer —
+ // AFTER middleware and body buffering — so they can never stop slow-body memory pinning, and
+ // this must run BEFORE the body parser so a rejected connection never buffers a byte. The
+ // per-request BODY_SIZE_LIMIT below is a separate, unchanged cap on each admitted request.
+ const inflightBudgetBytes = resolveInflightBodyBudgetBytes(
+ process.env.INFLIGHT_BODY_BUDGET_BYTES,
+ process.env.BODY_SIZE_LIMIT,
+ );
+ app.use(
+ createInflightBodyBudget(inflightBudgetBytes, {
+ trustedProxies: (process.env.TRUSTED_PROXIES || '')
+ .split(',')
+ .map(p => p.trim())
+ .filter(Boolean),
+ }).middleware,
+ );
+
+ // Cap request body size (DoS hardening). Media sends carry base64 in the JSON body,
+ // so the default is generous; tune with BODY_SIZE_LIMIT.
+ const bodyLimit = resolveBodyLimit(process.env.BODY_SIZE_LIMIT);
+ // The `verify` callback stashes the EXACT bytes json() received on req.rawBody, byte-identical to
+ // what a provider signed, so the @Public ingress controller can HMAC-verify over the raw body
+ // (JSON.stringify(req.body) is NOT byte-identical). Cheap for every route; non-ingress routes ignore it.
+ // `inflate: false` is a backstop, not the guard: the budget middleware above already refuses a
+ // compressed body with 415 before a byte is read. It sits here so a future reordering of these
+ // parsers relative to that middleware cannot silently reopen the gap — an inflated body is
+ // charged to the budget at its compressed size and bounded by nothing. Every other parser in the
+ // process must carry the same flag for that argument to hold; the MCP route-level fallback
+ // (src/modules/mcp/mcp.server.ts) does.
+ app.use(
+ json({
+ limit: bodyLimit,
+ inflate: false,
+ verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {
+ req.rawBody = buf;
+ },
+ }),
+ );
+ app.use(
+ urlencoded({
+ extended: true,
+ limit: bodyLimit,
+ inflate: false,
+ // Form-encoded webhook providers also sign the exact wire bytes. Use the same capture contract
+ // as json(); other content types remain unsupported rather than installing a global catch-all.
+ verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {
+ req.rawBody = buf;
+ },
+ }),
+ );
+
+ // Assign a request id to every inbound request (X-Request-ID), echo it on the response, and run
+ // the whole downstream chain inside its scope so every log line + audit row carries it.
+ app.use(requestContextMiddleware);
+
+ // Give every response a CSP nonce. A bundled dashboard document receives its own value in a meta
+ // element below; plugin config UIs copy it only onto inline scripts in their opaque sandboxed iframe.
+ app.use((req: Request, res: Response, next: NextFunction) => {
+ res.locals.cspNonce = randomBytes(18).toString('base64url');
+ next();
+ });
+
+ // Enhanced Security Headers
+ app.use(
+ helmet({
+ contentSecurityPolicy: {
+ directives: {
+ defaultSrc: ["'self'"],
+ // The bundled dashboard pulls webfonts from Google Fonts (CSS from fonts.googleapis.com,
+ // font files from fonts.gstatic.com). Now that NestJS serves the dashboard under this CSP,
+ // allow those origins or the @import'd fonts are blocked and the UI falls back to system fonts.
+ styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
+ scriptSrc: ["'self'", (_req, res) => `'nonce-${(res as Response).locals.cspNonce as string}'`],
+ // `blob:` is needed for the outgoing image-attachment preview, which the dashboard renders
+ // from a URL.createObjectURL(file) blob before the message is sent (Chats.tsx).
+ imgSrc: ["'self'", 'data:', 'blob:', 'https:'],
+ // Chat media (voice notes, video) is served to the dashboard as data: URIs. Without an
+ // explicit media-src, <audio>/<video> fall back to default-src 'self' and are blocked.
+ // Mirror imgSrc so audio/video render the same way images already do.
+ mediaSrc: ["'self'", 'data:', 'blob:', 'https:'],
+ connectSrc: ["'self'"],
+ fontSrc: ["'self'", 'https://fonts.gstatic.com'],
+ objectSrc: ["'none'"],
+ // Auto-upgrade HTTP→HTTPS in production, unless CSP_UPGRADE_INSECURE_REQUESTS opts out for an
+ // HTTP-only private-network deployment (otherwise the browser forces the dashboard to https). (#611)
+ upgradeInsecureRequests: isUpgradeInsecureRequestsEnabled(
+ process.env.CSP_UPGRADE_INSECURE_REQUESTS,
+ process.env.NODE_ENV,
+ )
+ ? []
+ : null,
+ },
+ },
+ hsts: {
+ maxAge: 31536000,
+ includeSubDomains: true,
+ preload: true,
+ },
+ noSniff: true,
+ referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
+ // Disable for API usage
+ crossOriginResourcePolicy: { policy: 'cross-origin' },
+ }),
+ );
+
+ // Serve SPA documents dynamically so the nonce embedded in this exact document matches its CSP
+ // response header. A shared cookie is deliberately avoided: a second dashboard tab could overwrite
+ // it and make the first tab's srcdoc scripts fail CSP. Assets and Nest-owned routes fall through.
+ if (dashboard.enabled && existsSync(join(dashboard.distDir, 'index.html'))) {
+ const dashboardIndex = readFileSync(join(dashboard.distDir, 'index.html'), 'utf8');
+ app.use((req: Request, res: Response, next: NextFunction) => {
+ const excluded =
+ req.path.startsWith('/api/') ||
+ req.path === '/api' ||
+ req.path.startsWith('/socket.io/') ||
+ req.path === '/socket.io' ||
+ req.path.startsWith('/mcp/') ||
+ req.path === '/mcp' ||
+ req.path.startsWith('/assets/');
+ const documentRequest =
+ req.method === 'GET' &&
+ !excluded &&
+ ((req.headers.accept ?? '').includes('text/html') || extname(req.path) === '');
+ if (!documentRequest) return next();
+
+ res.setHeader('Cache-Control', 'no-store');
+ res.type('html').send(injectDashboardCspNonce(dashboardIndex, res.locals.cspNonce as string));
+ });
+ }
+
+ // CORS Configuration (#221 hardening)
+ const corsPolicy = resolveCorsPolicy(process.env.CORS_ORIGINS, process.env.NODE_ENV);
+ if (process.env.NODE_ENV === 'production' && corsPolicy.origins.length === 0 && !corsPolicy.allowAnyOrigin) {
+ console.warn(
+ '[Bootstrap] No explicit CORS_ORIGINS in production (wildcard "*" is refused): cross-origin browser ' +
+ 'requests will be blocked. Set CORS_ORIGINS to your dashboard origin(s).',
+ );
+ }
+ app.enableCors({
+ origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {
+ // Allow requests with no origin (mobile apps, Postman, server-to-server)
+ if (!origin) return callback(null, true);
+
+ if (corsPolicy.allowAnyOrigin || corsPolicy.origins.includes(origin)) {
+ callback(null, true);
+ } else {
+ // Deny WITHOUT throwing. Throwing here surfaced as a 500 Internal Server Error (#250).
+ // Returning false simply omits the CORS headers: the browser blocks a true cross-origin
+ // request itself (correct), while same-origin requests — e.g. the bundled dashboard served
+ // through the proxy, which the browser never subjects to CORS — keep working. A genuine
+ // cross-origin dashboard still needs its origin in CORS_ORIGINS.
+ callback(null, false);
+ }
+ },
+ credentials: corsPolicy.credentials,
+ methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
+ allowedHeaders: ['Content-Type', 'X-API-Key', 'Authorization', 'X-Request-ID'],
+ // The throttlers are named (short/medium/long, plus instance on ingress), so @nestjs/throttler
+ // suffixes every rate-limit header with the throttler name — the unsuffixed variants are never
+ // sent. Expose the suffixed names so browser clients can actually read them.
+ exposedHeaders: [
+ 'X-RateLimit-Limit-short',
+ 'X-RateLimit-Remaining-short',
+ 'X-RateLimit-Reset-short',
+ 'X-RateLimit-Limit-medium',
+ 'X-RateLimit-Remaining-medium',
+ 'X-RateLimit-Reset-medium',
+ 'X-RateLimit-Limit-long',
+ 'X-RateLimit-Remaining-long',
+ 'X-RateLimit-Reset-long',
+ 'X-RateLimit-Limit-instance',
+ 'X-RateLimit-Remaining-instance',
+ 'X-RateLimit-Reset-instance',
+ 'X-RateLimit-Limit-ingress-ip',
+ 'X-RateLimit-Remaining-ingress-ip',
+ 'X-RateLimit-Reset-ingress-ip',
+ 'Retry-After-short',
+ 'Retry-After-medium',
+ 'Retry-After-long',
+ 'Retry-After-instance',
+ 'Retry-After-ingress-ip',
+ ],
+ maxAge: 86400, // 24 hours
+ });
+
+ return { bodyLimit, inflightBudgetBytes };
+}
diff --git a/src/main.ts b/src/main.ts
index 80b5fa398..28bcd0335 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -6,7 +6,6 @@ import { NestFactory } from '@nestjs/core';
import { INestApplication, ShutdownSignal } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SwaggerModule } from '@nestjs/swagger';
-import helmet from 'helmet';
import { AppModule, DASHBOARD_DIST, dashboardServingEnabled, dashboardBuildPresent } from './app.module';
import { ShutdownService } from './common/services/shutdown.service';
import { LoggerService, LogLevel, createLogger } from './common/services/logger.service';
@@ -15,16 +14,11 @@ import { registerUncaughtExceptionMonitor, registerUnhandledRejectionHandler } f
import { runBootstrapOrExit } from './config/bootstrap-fatal';
import { resolveStorageRoot } from './config/storage-root';
import { applyHttpTimeouts, HttpTimeoutConfig, HttpTimeoutSink } from './config/http-timeouts';
-import { createInflightBodyBudget, resolveInflightBodyBudgetBytes } from './config/inflight-body-budget';
import { applyGlobalValidation } from './config/app-validation';
-import { requestContextMiddleware } from './common/middleware/request-context.middleware';
-import { injectDashboardCspNonce } from './config/dashboard-csp';
+import { configureApp } from './configure-app';
import {
- resolveCorsPolicy,
isSwaggerEnabled,
- isUpgradeInsecureRequestsEnabled,
isDashboardCspUpgradeTrapLikely,
- resolveBodyLimit,
assertNoDefaultSecretsInProduction,
isApiKeyPepperMissingInProduction,
isNodeEnvUnset,
@@ -32,10 +26,7 @@ import {
import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middleware';
import { AuthService } from './modules/auth/auth.service';
import { AuditService } from './modules/audit/audit.service';
-import { Request, Response, NextFunction, json, urlencoded } from 'express';
-import { randomBytes } from 'crypto';
-import { readFileSync } from 'fs';
-import { extname, join } from 'path';
+import { Request, Response, NextFunction } from 'express';
import { RedisIoAdapter } from './modules/events/redis-io.adapter';
// The created app, exposed at module scope so the fatal handler below can run a best-effort teardown
@@ -118,63 +109,11 @@ async function bootstrap() {
// the adapter. Inert (plain in-memory adapter) without REDIS_ENABLED, so single-node pays nothing.
app.useWebSocketAdapter(new RedisIoAdapter(app));
- // Aggregate in-flight body budget (DoS hardening): once too many body bytes are being buffered
- // across ALL connections, new requests get 503 + Retry-After without their body being read.
- // This is a deliberate PRE-GUARD: the throttler/auth guards run at the Nest routing layer —
- // AFTER middleware and body buffering — so they can never stop slow-body memory pinning, and
- // this must run BEFORE the body parser so a rejected connection never buffers a byte. The
- // per-request BODY_SIZE_LIMIT below is a separate, unchanged cap on each admitted request.
- const inflightBudgetBytes = resolveInflightBodyBudgetBytes(
- process.env.INFLIGHT_BODY_BUDGET_BYTES,
- process.env.BODY_SIZE_LIMIT,
- );
- app.use(
- createInflightBodyBudget(inflightBudgetBytes, {
- trustedProxies: (process.env.TRUSTED_PROXIES || '')
- .split(',')
- .map(p => p.trim())
- .filter(Boolean),
- }).middleware,
- );
-
- // Cap request body size (DoS hardening). Media sends carry base64 in the JSON body,
- // so the default is generous; tune with BODY_SIZE_LIMIT.
- const bodyLimit = resolveBodyLimit(process.env.BODY_SIZE_LIMIT);
+ // The production HTTP surface: in-flight body budget, body parsers, request context, the CSP
+ // nonce, helmet, the SPA document handler and CORS. Extracted so the e2e lane runs the SAME
+ // stack instead of a copy of it (src/config/configure-app.ts).
+ const { bodyLimit, inflightBudgetBytes } = configureApp(app);
bootstrapLogger.log(`Request body caps: ${bodyLimit} per request, ${inflightBudgetBytes} bytes aggregate in flight`);
- // The `verify` callback stashes the EXACT bytes json() received on req.rawBody, byte-identical to
- // what a provider signed, so the @Public ingress controller can HMAC-verify over the raw body
- // (JSON.stringify(req.body) is NOT byte-identical). Cheap for every route; non-ingress routes ignore it.
- // `inflate: false` is a backstop, not the guard: the budget middleware above already refuses a
- // compressed body with 415 before a byte is read. It sits here so a future reordering of these
- // parsers relative to that middleware cannot silently reopen the gap — an inflated body is
- // charged to the budget at its compressed size and bounded by nothing. Every other parser in the
- // process must carry the same flag for that argument to hold; the MCP route-level fallback
- // (src/modules/mcp/mcp.server.ts) does.
- app.use(
- json({
- limit: bodyLimit,
- inflate: false,
- verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {
- req.rawBody = buf;
- },
- }),
- );
- app.use(
- urlencoded({
- extended: true,
- limit: bodyLimit,
- inflate: false,
- // Form-encoded webhook providers also sign the exact wire bytes. Use the same capture contract
- // as json(); other content types remain unsupported rather than installing a global catch-all.
- verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {
- req.rawBody = buf;
- },
- }),
- );
-
- // Assign a request id to every inbound request (X-Request-ID), echo it on the response, and run
- // the whole downstream chain inside its scope so every log line + audit row carries it.
- app.use(requestContextMiddleware);
// Let Nest own every shutdown signal EXCEPT SIGTERM/SIGINT — those we route through the bounded
// drain below, so a load balancer / orchestrator observes readiness=503 and stops routing BEFORE
@@ -208,136 +147,6 @@ async function bootstrap() {
});
}
- // Give every response a CSP nonce. A bundled dashboard document receives its own value in a meta
- // element below; plugin config UIs copy it only onto inline scripts in their opaque sandboxed iframe.
- app.use((req: Request, res: Response, next: NextFunction) => {
- res.locals.cspNonce = randomBytes(18).toString('base64url');
- next();
- });
-
- // Enhanced Security Headers
- app.use(
- helmet({
- contentSecurityPolicy: {
- directives: {
- defaultSrc: ["'self'"],
- // The bundled dashboard pulls webfonts from Google Fonts (CSS from fonts.googleapis.com,
- // font files from fonts.gstatic.com). Now that NestJS serves the dashboard under this CSP,
- // allow those origins or the @import'd fonts are blocked and the UI falls back to system fonts.
- styleSrc: ["'self'", "'unsafe-inline'", 'https://fonts.googleapis.com'],
- scriptSrc: ["'self'", (_req, res) => `'nonce-${(res as Response).locals.cspNonce as string}'`],
- // `blob:` is needed for the outgoing image-attachment preview, which the dashboard renders
- // from a URL.createObjectURL(file) blob before the message is sent (Chats.tsx).
- imgSrc: ["'self'", 'data:', 'blob:', 'https:'],
- // Chat media (voice notes, video) is served to the dashboard as data: URIs. Without an
- // explicit media-src, <audio>/<video> fall back to default-src 'self' and are blocked.
- // Mirror imgSrc so audio/video render the same way images already do.
- mediaSrc: ["'self'", 'data:', 'blob:', 'https:'],
- connectSrc: ["'self'"],
- fontSrc: ["'self'", 'https://fonts.gstatic.com'],
- objectSrc: ["'none'"],
- // Auto-upgrade HTTP→HTTPS in production, unless CSP_UPGRADE_INSECURE_REQUESTS opts out for an
- // HTTP-only private-network deployment (otherwise the browser forces the dashboard to https). (#611)
- upgradeInsecureRequests: isUpgradeInsecureRequestsEnabled(
- process.env.CSP_UPGRADE_INSECURE_REQUESTS,
- process.env.NODE_ENV,
- )
- ? []
- : null,
- },
- },
- hsts: {
- maxAge: 31536000,
- includeSubDomains: true,
- preload: true,
- },
- noSniff: true,
- referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
- // Disable for API usage
- crossOriginResourcePolicy: { policy: 'cross-origin' },
- }),
- );
-
- // Serve SPA documents dynamically so the nonce embedded in this exact document matches its CSP
- // response header. A shared cookie is deliberately avoided: a second dashboard tab could overwrite
- // it and make the first tab's srcdoc scripts fail CSP. Assets and Nest-owned routes fall through.
- if (dashboardServingEnabled && dashboardBuildPresent) {
- const dashboardIndex = readFileSync(join(DASHBOARD_DIST, 'index.html'), 'utf8');
- app.use((req: Request, res: Response, next: NextFunction) => {
- const excluded =
- req.path.startsWith('/api/') ||
- req.path === '/api' ||
- req.path.startsWith('/socket.io/') ||
- req.path === '/socket.io' ||
- req.path.startsWith('/mcp/') ||
- req.path === '/mcp' ||
- req.path.startsWith('/assets/');
- const documentRequest =
- req.method === 'GET' &&
- !excluded &&
- ((req.headers.accept ?? '').includes('text/html') || extname(req.path) === '');
- if (!documentRequest) return next();
-
- res.setHeader('Cache-Control', 'no-store');
- res.type('html').send(injectDashboardCspNonce(dashboardIndex, res.locals.cspNonce as string));
- });
- }
-
- // CORS Configuration (#221 hardening)
- const corsPolicy = resolveCorsPolicy(process.env.CORS_ORIGINS, process.env.NODE_ENV);
- if (process.env.NODE_ENV === 'production' && corsPolicy.origins.length === 0 && !corsPolicy.allowAnyOrigin) {
- console.warn(
- '[Bootstrap] No explicit CORS_ORIGINS in production (wildcard "*" is refused): cross-origin browser ' +
- 'requests will be blocked. Set CORS_ORIGINS to your dashboard origin(s).',
- );
- }
- app.enableCors({
- origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {
- // Allow requests with no origin (mobile apps, Postman, server-to-server)
- if (!origin) return callback(null, true);
-
- if (corsPolicy.allowAnyOrigin || corsPolicy.origins.includes(origin)) {
- callback(null, true);
- } else {
- // Deny WITHOUT throwing. Throwing here surfaced as a 500 Internal Server Error (#250).
- // Returning false simply omits the CORS headers: the browser blocks a true cross-origin
- // request itself (correct), while same-origin requests — e.g. the bundled dashboard served
- // through the proxy, which the browser never subjects to CORS — keep working. A genuine
- // cross-origin dashboard still needs its origin in CORS_ORIGINS.
- callback(null, false);
- }
- },
- credentials: corsPolicy.credentials,
- methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
- allowedHeaders: ['Content-Type', 'X-API-Key', 'Authorization', 'X-Request-ID'],
- // The throttlers are named (short/medium/long, plus instance on ingress), so @nestjs/throttler
- // suffixes every rate-limit header with the throttler name — the unsuffixed variants are never
- // sent. Expose the suffixed names so browser clients can actually read them.
- exposedHeaders: [
- 'X-RateLimit-Limit-short',
- 'X-RateLimit-Remaining-short',
- 'X-RateLimit-Reset-short',
- 'X-RateLimit-Limit-medium',
- 'X-RateLimit-Remaining-medium',
- 'X-RateLimit-Reset-medium',
- 'X-RateLimit-Limit-long',
- 'X-RateLimit-Remaining-long',
- 'X-RateLimit-Reset-long',
- 'X-RateLimit-Limit-instance',
- 'X-RateLimit-Remaining-instance',
- 'X-RateLimit-Reset-instance',
- 'X-RateLimit-Limit-ingress-ip',
- 'X-RateLimit-Remaining-ingress-ip',
- 'X-RateLimit-Reset-ingress-ip',
- 'Retry-After-short',
- 'Retry-After-medium',
- 'Retry-After-long',
- 'Retry-After-instance',
- 'Retry-After-ingress-ip',
- ],
- maxAge: 86400, // 24 hours
- });
-
// Shared production/e2e prefix and DTO validation contract.
applyGlobalValidation(app);
diff --git a/test/configure-app.e2e-spec.ts b/test/configure-app.e2e-spec.ts
new file mode 100644
index 000000000..fbdeb1597
--- /dev/null
+++ b/test/configure-app.e2e-spec.ts
@@ -0,0 +1,163 @@
+import { Module, INestApplication, Controller, Post, Body } from '@nestjs/common';
+import { NestFactory } from '@nestjs/core';
+import request from 'supertest';
+import { App } from 'supertest/types';
+import { mkdtempSync, mkdirSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { configureApp } from '../src/configure-app';
+import { applyGlobalValidation } from '../src/config/app-validation';
+import { DASHBOARD_CSP_NONCE_PLACEHOLDER } from '../src/config/dashboard-csp';
+
+/**
+ * The production HTTP surface, run for real. Every other e2e builds a bare Nest app, so the stack
+ * main.ts installs (nonce, helmet, body caps, CORS, the SPA document handler) was executed by
+ * nothing, and the one suite that needed the document handler carried its own copy of it, minus the
+ * nonce injection. These assertions fail if the copy and the original ever diverge again, because
+ * there is no copy left to diverge.
+ */
+@Controller('echo')
+class EchoController {
+ @Post()
+ echo(@Body() body: unknown) {
+ return { received: typeof body };
+ }
+}
+
+@Module({ controllers: [EchoController] })
+class HttpSurfaceModule {}
+
+// A stand-in for the bundled document: the real dashboard/index.html carries the placeholder in a
+// meta element, which Plugins.tsx reads to copy the nonce onto its sandboxed iframe's scripts.
+const distDir = join(mkdtempSync(join(tmpdir(), 'openwa-surface-')), 'dashboard', 'dist');
+mkdirSync(distDir, { recursive: true });
+writeFileSync(
+ join(distDir, 'index.html'),
+ `<!doctype html><html><head><meta name="openwa-csp-nonce" content="${DASHBOARD_CSP_NONCE_PLACEHOLDER}" />` +
+ `</head><body><script nonce="${DASHBOARD_CSP_NONCE_PLACEHOLDER}"></script></body></html>`,
+);
+
+describe('production HTTP surface (configureApp)', () => {
+ let app: INestApplication<App>;
+
+ const previousBodyLimit = process.env.BODY_SIZE_LIMIT;
+ const previousCorsOrigins = process.env.CORS_ORIGINS;
+
+ beforeAll(async () => {
+ // Pin the cap here rather than inheriting the lane's: configureApp reads it at call time, and a
+ // suite that depends on ambient env asserts whatever the runner happened to set. 1mb makes the
+ // aggregate budget 4mb (four times the per-request cap), so the two layers are separable.
+ process.env.BODY_SIZE_LIMIT = '1mb';
+ // Without an explicit allowlist the policy is a wildcard, which allows every origin and would
+ // make the denial assertion below pass on any implementation.
+ process.env.CORS_ORIGINS = 'https://allowed.example';
+ // `bodyParser: false` matches main.ts: configureApp installs the only parsers, with the caps.
+ app = await NestFactory.create<INestApplication<App>>(HttpSurfaceModule, { bodyParser: false, logger: false });
+ configureApp(app, { dashboard: { distDir, enabled: true } });
+ applyGlobalValidation(app);
+ await app.init();
+ });
+
+ afterAll(async () => {
+ await app?.close();
+ if (previousBodyLimit === undefined) delete process.env.BODY_SIZE_LIMIT;
+ else process.env.BODY_SIZE_LIMIT = previousBodyLimit;
+ if (previousCorsOrigins === undefined) delete process.env.CORS_ORIGINS;
+ else process.env.CORS_ORIGINS = previousCorsOrigins;
+ });
+
+ it('serves a document whose nonce matches the one in its own CSP header', async () => {
+ const res = await request(app.getHttpServer()).get('/').set('Accept', 'text/html').expect(200);
+
+ const csp = res.headers['content-security-policy'];
+ const fromHeader = /'nonce-([A-Za-z0-9_-]+)'/.exec(csp)?.[1];
+ expect(fromHeader).toBeTruthy();
+ // The document must carry THAT value, not a placeholder and not a different nonce: a mismatch
+ // means the browser refuses every script the page declares.
+ expect(res.text).toContain(`content="${fromHeader}"`);
+ expect(res.text).toContain(`nonce="${fromHeader}"`);
+ expect(res.text).not.toContain(DASHBOARD_CSP_NONCE_PLACEHOLDER);
+ });
+
+ it('gives each response its own nonce', async () => {
+ const nonceOf = async (): Promise<string | undefined> => {
+ const res = await request(app.getHttpServer()).get('/').set('Accept', 'text/html').expect(200);
+ return /'nonce-([A-Za-z0-9_-]+)'/.exec(res.headers['content-security-policy'])?.[1];
+ };
+ // A shared nonce would let one document's value satisfy another's CSP, which is the whole
+ // reason the document is served dynamically rather than statically.
+ expect(await nonceOf()).not.toEqual(await nonceOf());
+ });
+
+ it('echoes the CORS header for an allowed Origin', async () => {
+ const res = await request(app.getHttpServer())
+ .post('/api/echo')
+ .set('Content-Type', 'application/json')
+ .set('Origin', 'https://allowed.example')
+ .send({});
+
+ expect(res.headers['access-control-allow-origin']).toBe('https://allowed.example');
+ });
+
+ it('denies a disallowed Origin by omitting the CORS headers, not by failing the request', async () => {
+ // Deliberately an /api route: the document handler answers `/` before the CORS layer is
+ // reached, so asserting the denial there passes whatever CORS does.
+ const res = await request(app.getHttpServer())
+ .post('/api/echo')
+ .set('Content-Type', 'application/json')
+ .set('Origin', 'https://evil.example')
+ .send({});
+
+ // Throwing here surfaced as a 500 once (#250). The browser is what must block the response.
+ expect(res.status).toBe(201);
+ expect(res.headers['access-control-allow-origin']).toBeUndefined();
+ });
+
+ it('admits a body under the per-request cap', async () => {
+ const res = await request(app.getHttpServer())
+ .post('/api/echo')
+ .set('Content-Type', 'application/json')
+ .send({ blob: 'x'.repeat(900 * 1024) });
+
+ expect(res.status).toBe(201);
+ });
+
+ it('refuses a body over the per-request cap with 413', async () => {
+ const res = await request(app.getHttpServer())
+ .post('/api/echo')
+ .set('Content-Type', 'application/json')
+ .send({ blob: 'x'.repeat(1100 * 1024) });
+
+ expect(res.status).toBe(413);
+ });
+
+ it('refuses a declared body over the aggregate in-flight budget with 503, a different layer', async () => {
+ // The budget is a PRE-guard: it answers on the DECLARED length, before the parser reads a byte,
+ // which is what stops slow-body memory pinning that no route guard can reach. Asserting it by
+ // actually uploading an oversized body is timing-dependent: the server refuses and destroys
+ // the socket while the client is still writing, so the client sees ECONNRESET instead of the
+ // response often enough to flake. Declaring the size and sending almost nothing tests the same
+ // decision deterministically.
+ const res = await request(app.getHttpServer())
+ .post('/api/echo')
+ .set('Content-Type', 'application/json')
+ .set('Content-Length', String(8 * 1024 * 1024))
+ // Bounded on purpose: if the guard ever stops refusing, the parser waits for a body that is
+ // never coming and this hangs instead of failing. A hang is not a red.
+ .timeout({ deadline: 5000, response: 5000 })
+ .send('{}');
+
+ expect(res.status).toBe(503);
+ expect(res.headers['retry-after']).toBeDefined();
+ });
+
+ it('answers a compressed body with 415 rather than charging the budget its inflated size', async () => {
+ const res = await request(app.getHttpServer())
+ .post('/api/echo')
+ .set('Content-Type', 'application/json')
+ .set('Content-Encoding', 'gzip')
+ .send('{}');
+
+ expect(res.status).toBe(415);
+ });
+});
diff --git a/test/serve-static.e2e-spec.ts b/test/serve-static.e2e-spec.ts
index b29f80b80..c963ef4cc 100644
--- a/test/serve-static.e2e-spec.ts
+++ b/test/serve-static.e2e-spec.ts
@@ -1,13 +1,13 @@
import { Module, INestApplication, Controller, Get } from '@nestjs/common';
import { applyGlobalValidation } from '../src/config/app-validation';
+import { configureApp } from '../src/configure-app';
import { NestFactory } from '@nestjs/core';
import { ServeStaticModule } from '@nestjs/serve-static';
import request from 'supertest';
import { App } from 'supertest/types';
-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, realpathSync } from 'fs';
+import { mkdtempSync, mkdirSync, writeFileSync, realpathSync } from 'fs';
import { tmpdir } from 'os';
-import { join, sep, extname } from 'path';
-import type { Request, Response, NextFunction } from 'express';
+import { join, sep } from 'path';
/**
* Two throwaway dashboard builds, evaluated before the module decorators (forRoot reads rootPath
@@ -61,34 +61,6 @@ class PlainServeStaticModule {}
})
class DottedServeStaticModule {}
-/**
- * Mirrors the SPA document handler main.ts installs (the CSP-nonce one), minus the nonce
- * injection. It is load-bearing, not decoration: it reads the index with `readFileSync` and
- * `res.send`s it, which is what makes client-side routes work at all on a dot-segment install
- * path. Reproducing serve-static WITHOUT it - as this spec used to - tests a stack that does
- * not exist in production and reports a failure the product does not have.
- */
-function applyDashboardDocumentHandler(app: INestApplication<App>, distDir: string): void {
- const dashboardIndex = readFileSync(join(distDir, 'index.html'), 'utf8');
- app.use((req: Request, res: Response, next: NextFunction) => {
- const excluded =
- req.path.startsWith('/api/') ||
- req.path === '/api' ||
- req.path.startsWith('/socket.io/') ||
- req.path === '/socket.io' ||
- req.path.startsWith('/mcp/') ||
- req.path === '/mcp' ||
- req.path.startsWith('/assets/');
- const documentRequest =
- req.method === 'GET' &&
- !excluded &&
- ((req.headers.accept ?? '').includes('text/html') || extname(req.path) === '');
- if (!documentRequest) return next();
- res.setHeader('Cache-Control', 'no-store');
- res.type('html').send(dashboardIndex);
- });
-}
-
describe('serve-static test fixtures', () => {
it('really does cover BOTH install-path shapes', () => {
// Without this, a dotted os.tmpdir() collapses the matrix onto one shape and the
@@ -113,8 +85,11 @@ describe.each([
let app: INestApplication<App>;
beforeAll(async () => {
- app = await NestFactory.create(moduleClass, { logger: false });
- applyDashboardDocumentHandler(app, distDir);
+ // The REAL production stack, pointed at this fixture build. It used to be a copy of the
+ // document handler kept in this file, minus the nonce injection, so a divergence between the
+ // copy and the original passed.
+ app = await NestFactory.create(moduleClass, { bodyParser: false, logger: false });
+ configureApp(app, { dashboard: { distDir, enabled: true } });
applyGlobalValidation(app);
await app.init();
});