Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(http): keep parser errors on /api when the dashboard is served

Yudhi Armyndharis0ae5553c2b65
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2688a2ed9..3ec948c37 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -319,6 +319,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The message list reads its page rows by primary key on SQLite, which cuts a 100 row read of a 300k row session from about 70 ms to 5 ms.
- Fix the PHP SDK reading a `Retry-After` header of 309 or more digits as 0 seconds; it is now capped like a smaller oversized value.
- Do not mark a patch release on an older line as the GitHub Latest release, which the update check reads.
+- Answer a body over `BODY_SIZE_LIMIT`, malformed JSON, a body nested past the bound and an undecodable path parameter under `/api` and `/mcp` with 413 or 400 when the bundled dashboard is served, where they answered `404 Cannot POST` ([#1921](https://github.com/rmyndharis/OpenWA/issues/1921)). Thanks @ScalingMBA for the report.
### Dependencies
diff --git a/docs/17-dashboard-design.md b/docs/17-dashboard-design.md
index de2c665b9..16b27294c 100644
--- a/docs/17-dashboard-design.md
+++ b/docs/17-dashboard-design.md
@@ -773,9 +773,10 @@ How it fits together:
- `npm run build:all` builds the API (`dist/`) **and** the dashboard (`dashboard/dist/`). The root
`Dockerfile` does this in its builder stage and copies `dashboard/dist` into the runtime image.
- `ServeStaticModule` is registered conditionally in `src/app.module.ts`: it only activates when
- `dashboard/dist/index.html` exists, serves it with SPA fallback, and `exclude`s `/api` and
- `/socket.io` so those keep returning real API/WebSocket responses. Opt out with
- `SERVE_DASHBOARD=false`.
+ `dashboard/dist/index.html` exists and serves the built assets. Its own SPA fallback is off:
+ `configure-app.ts` answers the dashboard documents, with the per-response CSP nonce, for GET paths
+ outside `/api`, `/socket.io`, `/mcp` and `/assets`, so those keep returning real API/WebSocket
+ responses and the body parsers' own 413 and 400. Opt out with `SERVE_DASHBOARD=false`.
- Run it directly with `npm run prod` (build + serve) or `node dist/main` against a prebuilt image.
In development the build is absent, so serve-static stays inert and the Vite dev server (port
diff --git a/src/app.module.ts b/src/app.module.ts
index 3a71685a9..3504dfef0 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -1,5 +1,5 @@
import { Module, DynamicModule, Type } from '@nestjs/common';
-import { ServeStaticModule } from '@nestjs/serve-static';
+import { ServeStaticModule, ServeStaticModuleOptions } from '@nestjs/serve-static';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import * as path from 'path';
@@ -91,29 +91,29 @@ export const DASHBOARD_DIST = path.resolve(__dirname, '..', 'dashboard', 'dist')
export const dashboardServingEnabled = process.env.SERVE_DASHBOARD !== 'false';
export const dashboardBuildPresent = fs.existsSync(path.join(DASHBOARD_DIST, 'index.html'));
+// Everything but the root, exported so the e2e suite boots these options and not a copy of them.
+export const DASHBOARD_STATIC_OPTIONS: Omit<ServeStaticModuleOptions, 'rootPath'> = {
+ // No `exclude`: the module's error handler rewrites every error raised on an excluded path into
+ // 404 "Cannot <method> <url>", which hid the body parsers' 413 and 400 under /api, /socket.io and
+ // /mcp. Nest answers unknown routes there on its own now that the fallback below is off.
+ // Disable this module's OWN catch-all SPA fallback. configure-app.ts already serves dashboard
+ // documents (it injects the per-response CSP nonce, which is why it must own them), and
+ // that handler is correctly narrow: it skips /assets and only answers extensionless paths
+ // or explicit text/html navigations. The built-in fallback here is not narrow — it answers
+ // EVERY unmatched GET with index.html, so a mistyped `<script src>` came back 200 HTML and
+ // the browser reported a JavaScript parse error instead of the real 404, hiding broken
+ // builds behind a confusing symptom. It is also outright broken when the install path
+ // contains a dot-segment (~/.openwa, a checkout under ~/.cache): it sends the index by
+ // ABSOLUTE path and Express's `send` refuses dot-segments, 404ing every client-side route.
+ // Turning it off fixes both, and makes behaviour identical on either path shape.
+ // ServeStaticModule has no explicit off switch, so this is a renderPath literal that no
+ // real request can match.
+ renderPath: '/__openwa_spa_fallback_owned_by_main_ts__',
+};
+
const serveStaticModules: Array<Type | DynamicModule> = [];
if (dashboardServingEnabled && dashboardBuildPresent) {
- serveStaticModules.push(
- ServeStaticModule.forRoot({
- rootPath: DASHBOARD_DIST,
- // Let Nest own these so unknown API/socket routes return real 404s/JSON rather
- // than the SPA index.html fallback (Express 5 / path-to-regexp v8 wildcard syntax).
- exclude: ['/api/{*splat}', '/socket.io/{*splat}', '/mcp', '/mcp/{*splat}'],
- // Disable this module's OWN catch-all SPA fallback. configure-app.ts already serves dashboard
- // documents (it injects the per-response CSP nonce, which is why it must own them), and
- // that handler is correctly narrow: it skips /assets and only answers extensionless paths
- // or explicit text/html navigations. The built-in fallback here is not narrow — it answers
- // EVERY unmatched GET with index.html, so a mistyped `<script src>` came back 200 HTML and
- // the browser reported a JavaScript parse error instead of the real 404, hiding broken
- // builds behind a confusing symptom. It is also outright broken when the install path
- // contains a dot-segment (~/.openwa, a checkout under ~/.cache): it sends the index by
- // ABSOLUTE path and Express's `send` refuses dot-segments, 404ing every client-side route.
- // Turning it off fixes both, and makes behaviour identical on either path shape.
- // ServeStaticModule has no explicit off switch, so this is a renderPath literal that no
- // real request can match.
- renderPath: '/__openwa_spa_fallback_owned_by_main_ts__',
- }),
- );
+ serveStaticModules.push(ServeStaticModule.forRoot({ rootPath: DASHBOARD_DIST, ...DASHBOARD_STATIC_OPTIONS }));
}
@Module({
diff --git a/test/serve-static.e2e-spec.ts b/test/serve-static.e2e-spec.ts
index 3262382a9..8c768f93e 100644
--- a/test/serve-static.e2e-spec.ts
+++ b/test/serve-static.e2e-spec.ts
@@ -1,4 +1,5 @@
-import { Module, INestApplication, Controller, Get } from '@nestjs/common';
+import { Module, INestApplication, Controller, Get, Post, Body, Param } from '@nestjs/common';
+import { DASHBOARD_STATIC_OPTIONS } from '../src/app.module';
import { applyGlobalValidation } from '../src/config/app-validation';
import { configureApp } from '../src/configure-app';
import { NestFactory } from '@nestjs/core';
@@ -48,22 +49,27 @@ class PingController {
ping() {
return { ok: true };
}
-}
-const EXCLUDE = ['/api/{*splat}', '/socket.io/{*splat}'];
-// Mirrors app.module.ts: the module's own catch-all fallback is off, main.ts's document
-// handler owns SPA routes. Without this the module answers every unmatched GET with the
-// shell, which is the behaviour the missing-asset test below exists to prevent.
-const RENDER_DISABLED = '/__openwa_spa_fallback_owned_by_main_ts__';
+ @Post('echo')
+ echo(@Body() body: unknown) {
+ return { body };
+ }
+ @Get('items/:id')
+ item(@Param('id') id: string) {
+ return { id };
+ }
+}
+
+// The options app.module.ts passes to the module, so a change there is what these tests exercise.
@Module({
- imports: [ServeStaticModule.forRoot({ rootPath: plainDist, exclude: EXCLUDE, renderPath: RENDER_DISABLED })],
+ imports: [ServeStaticModule.forRoot({ rootPath: plainDist, ...DASHBOARD_STATIC_OPTIONS })],
controllers: [PingController],
})
class PlainServeStaticModule {}
@Module({
- imports: [ServeStaticModule.forRoot({ rootPath: dottedDist, exclude: EXCLUDE, renderPath: RENDER_DISABLED })],
+ imports: [ServeStaticModule.forRoot({ rootPath: dottedDist, ...DASHBOARD_STATIC_OPTIONS })],
controllers: [PingController],
})
class DottedServeStaticModule {}
@@ -79,19 +85,20 @@ describe('serve-static test fixtures', () => {
/**
* Regression lock for single-port dashboard serving (app.module.ts + main.ts). Bootstraps the SAME
- * serve-static config (rootPath + exclude) AND the same document handler against a throwaway build:
- * the SPA must be served at `/` with client-side fallback, while Nest keeps ownership of `/api` so
- * unknown API routes return JSON 404s (not the SPA index.html). Pins the Express 5 /
- * path-to-regexp v8 wildcard syntax (`/api/{*splat}`) - if a dep bump breaks it, /api/* would start
- * returning index.html and these tests fail.
+ * serve-static options AND the same document handler against a throwaway build: the SPA must be
+ * served at `/` with client-side fallback, while Nest keeps ownership of `/api` so unknown API routes
+ * return JSON 404s (not the SPA index.html) and a request the body parsers refuse keeps its own 413
+ * or 400 instead of the module's `404 Cannot POST`.
*/
describe.each([
['a plain install path', PlainServeStaticModule, plainDist],
['an install path with a dot-segment', DottedServeStaticModule, dottedDist],
])('Dashboard serve-static (e2e) - %s', (_label, moduleClass, distDir) => {
let app: INestApplication<App>;
+ const previousBodyLimit = process.env.BODY_SIZE_LIMIT;
beforeAll(async () => {
+ process.env.BODY_SIZE_LIMIT = '1kb';
// 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.
@@ -102,6 +109,8 @@ describe.each([
});
afterAll(async () => {
+ if (previousBodyLimit === undefined) delete process.env.BODY_SIZE_LIMIT;
+ else process.env.BODY_SIZE_LIMIT = previousBodyLimit;
await app?.close();
});
@@ -183,4 +192,32 @@ describe.each([
const res = await request(app.getHttpServer()).post('/sessions');
expect(res.status).not.toBe(200);
});
+
+ describe('a request the body parsers refuse, under /api', () => {
+ // The serve-static error handler used to rewrite each of these into `404 Cannot POST /api/echo`.
+ // The oversized body stays under the in-flight budget the 1kb limit implies (4 KB), so the
+ // parser answers and not the budget.
+ const postJson = (body: string) => request(app.getHttpServer()).post('/api/echo').type('json').send(body);
+
+ it('answers 413 for a body over BODY_SIZE_LIMIT', async () => {
+ const res = await postJson(JSON.stringify({ text: 'x'.repeat(2048) }));
+ expect(res.status).toBe(413);
+ });
+
+ it('answers 400 for malformed JSON', async () => {
+ const res = await postJson('{"text":');
+ expect(res.status).toBe(400);
+ });
+
+ it('answers 400 for a body nested past the bound', async () => {
+ const res = await postJson(`${'['.repeat(150)}${']'.repeat(150)}`);
+ expect(res.status).toBe(400);
+ expect(res.body).toMatchObject({ statusCode: 400, error: 'Bad Request' });
+ });
+
+ it('answers 400 for a path parameter that cannot be decoded', async () => {
+ const res = await request(app.getHttpServer()).get('/api/items/%FF');
+ expect(res.status).toBe(400);
+ });
+ });
});