Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(config): key the compressed-body refusal on the parser's own body predicate

Yudhi Armyndharise05b34da4a2c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8cedb31ee..4257befd4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,7 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
-- **A request body with a `Content-Encoding` other than `identity` is now refused with `415`** — the aggregate in-flight body cap counts wire bytes, so a compressed body was admitted on its compressed size and then inflated past the memory it was supposed to bound.
+- **An API request body with a `Content-Encoding` other than `identity` is now refused with `415`** — the aggregate in-flight body cap counts wire bytes, so a compressed body was admitted on its compressed size and then inflated past the memory it was supposed to bound.
## [0.14.2] - 2026-08-06
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 13608b556..cb027ac3f 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -102,7 +102,7 @@ Validation failures (`statusCode: 400`) return `message` as an **array** of fiel
| `404` | Not Found | The addressed resource (session, message, webhook, batch, …) does not exist |
| `409` | Conflict | A uniqueness constraint was violated (e.g. duplicate name), or a credential teardown for the same session name is still in flight on `start`/`delete` (retryable; body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`) |
| `413` | Payload Too Large | Base64 media exceeds the media byte cap (see §6.3) |
-| `415` | Unsupported Media Type | The request carries a `Content-Encoding` other than `identity`. Compressed request bodies are not accepted: the aggregate body cap counts wire bytes, so an inflated body would exceed the memory it bounds |
+| `415` | Unsupported Media | The request has a body carrying a `Content-Encoding` other than `identity`; compressed request bodies are not accepted, as the aggregate body cap counts wire bytes |
| `500` | Internal Server Error | Send failed at the WhatsApp engine or an unexpected server error |
### Timestamp Conventions
diff --git a/src/config/inflight-body-budget.spec.ts b/src/config/inflight-body-budget.spec.ts
index 129f0deb2..90749a702 100644
--- a/src/config/inflight-body-budget.spec.ts
+++ b/src/config/inflight-body-budget.spec.ts
@@ -1,4 +1,6 @@
import { EventEmitter } from 'events';
+import { readFileSync } from 'fs';
+import { resolve } from 'path';
import { createServer, request as httpRequest, Server } from 'http';
import { AddressInfo } from 'net';
import { gzipSync } from 'zlib';
@@ -446,7 +448,13 @@ describe('compressed request bodies', () => {
});
req.on('error', (error: NodeJS.ErrnoException) => {
if (reply) return;
- if (error.code === 'ECONNRESET' || error.code === 'EPIPE') return;
+ // A refusal answers and drops the socket without reading the body, so the reset can beat
+ // the parsed response. Settle with a sentinel rather than swallowing it: a bare timeout
+ // would report as "test timed out" instead of "expected 415, got a connection reset".
+ if (error.code === 'ECONNRESET' || error.code === 'EPIPE') {
+ resolve({ status: 0, body: '' });
+ return;
+ }
reject(error);
});
req.end(body);
@@ -492,6 +500,59 @@ describe('compressed request bodies', () => {
expect(reply.status).toBe(503);
});
+ it('refuses a compressed body whose Content-Length is zero', async () => {
+ await listen();
+
+ // `reserved` is 0 here, so a gate keyed on the reservation would wave this through to the
+ // parser and the client would get body-parser's HTML error instead of the documented shape.
+ const reply = await send(
+ { 'Content-Type': 'application/json', 'Content-Encoding': 'gzip', 'Content-Length': '0' },
+ Buffer.alloc(0),
+ );
+
+ expect(reply.status).toBe(415);
+ expect((JSON.parse(reply.body) as { error?: string }).error).toBe('Unsupported Media Type');
+ });
+
+ it('refuses a compressed body whose Content-Length is not a safe integer', async () => {
+ await listen();
+ const gzipped = gzipSync(INFLATED_PAYLOAD);
+
+ // parseDeclaredLength refuses to reserve for this, but type-is `hasBody` still hands it to the
+ // parser — the one shape that escaped both the reservation AND admission control.
+ const reply = await send(
+ {
+ 'Content-Type': 'application/json',
+ 'Content-Encoding': 'gzip',
+ 'Content-Length': String(Number.MAX_SAFE_INTEGER + 2),
+ },
+ gzipped,
+ );
+
+ expect(reply.status).toBe(415);
+ expect((JSON.parse(reply.body) as { error?: string }).error).toBe('Unsupported Media Type');
+ });
+
+ it('refuses an encoding LIST, matching what the parser would do with it', async () => {
+ await listen();
+ const plain = Buffer.from(JSON.stringify({ data: 'small' }));
+
+ // "identity, identity" transforms nothing, but body-parser compares the whole header against
+ // 'identity' and refuses it — so the middleware refuses it too and both layers answer the same
+ // documented shape instead of disagreeing about who rejects it.
+ const reply = await send(
+ {
+ 'Content-Type': 'application/json',
+ 'Content-Encoding': 'identity, identity',
+ 'Content-Length': String(plain.length),
+ },
+ plain,
+ );
+
+ expect(reply.status).toBe(415);
+ expect((JSON.parse(reply.body) as { error?: string }).error).toBe('Unsupported Media Type');
+ });
+
it('admits an ordinary body declaring Content-Encoding: identity', async () => {
await listen();
const plain = Buffer.from(JSON.stringify({ data: 'small' }));
@@ -508,3 +569,22 @@ describe('compressed request bodies', () => {
expect(reply.status).toBe(200);
});
});
+
+/**
+ * The `inflate: false` backstop is unreachable while the guard above stands, so no behavioural test
+ * can lock it — yet it is the only thing standing if the guard is ever bypassed. Assert it in the
+ * source instead, the way load-env.spec.ts locks main.ts's import order.
+ */
+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');
+
+ expect(source.match(/^\s+inflate: false,$/gm)).toHaveLength(2);
+ });
+
+ it('disables inflate on the MCP route-level fallback parser', () => {
+ expect(read('../modules/mcp/mcp.server.ts')).toContain('express.json({ inflate: false })');
+ });
+});
diff --git a/src/config/inflight-body-budget.ts b/src/config/inflight-body-budget.ts
index e8becfb4c..5b76cc149 100644
--- a/src/config/inflight-body-budget.ts
+++ b/src/config/inflight-body-budget.ts
@@ -163,8 +163,20 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflight
// orders of magnitude larger than the whole budget can be buffered without the accounting ever
// seeing it. Refusing here — before admission, before a byte is read — keeps the invariant
// true rather than trying to price an expansion that is not knowable in advance.
+ //
+ // The predicate is body-parser's, NOT `reserved > 0`. They disagree on exactly the cases that
+ // matter: `parseDeclaredLength` rejects a Content-Length that is not a safe integer (reserving
+ // nothing), while type-is `hasBody` accepts anything non-NaN — so `Content-Length: 2**53 + 1`
+ // with a gzip body reserves 0 here yet is still handed to the parser. Mirroring hasBody keeps
+ // the two layers from disagreeing about whether a body exists.
+ const bodyIndicated =
+ req.headers['transfer-encoding'] !== undefined || !Number.isNaN(Number(req.headers['content-length']));
+ // The accepted set is body-parser's, deliberately: it compares the WHOLE header against
+ // 'identity', so even a technically-uncompressed list ("identity, identity") is refused there.
+ // Accepting more here would only move the refusal to the parser, which answers a different
+ // shape — the two layers agreeing matters more than honouring an encoding list nobody sends.
const encoding = (req.headers['content-encoding'] ?? '').trim().toLowerCase();
- if (reserved > 0 && encoding !== '' && encoding !== 'identity') {
+ if (bodyIndicated && encoding !== '' && encoding !== 'identity') {
rejectCompressed(req, res);
return;
}
diff --git a/src/main.ts b/src/main.ts
index 7cfc43aa0..17ab29a78 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -125,9 +125,11 @@ async function bootstrap() {
// 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 middleware reordering,
- // or a route-level parser mounted past that middleware, cannot silently reopen the gap — an
- // inflated body is charged to the budget at its compressed size and bounded by nothing.
+ // 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,
diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.ts
index b27d1ec5f..40fbf0b21 100644
--- a/src/modules/mcp/mcp.server.ts
+++ b/src/modules/mcp/mcp.server.ts
@@ -244,5 +244,8 @@ export function mountMcpServer(
// The route throttle gates the auth DB lookup and per-request MCP server/transport construction. The
// process-wide capped json() in main.ts runs first for all routes; this route-level parser is a
// defensive fallback and no-ops once the global parser has consumed the body.
- adapter.post(basePath, createIpThrottle(ipRateLimiter), express.json(), handler);
+ // `inflate: false` matches the global parsers: a compressed body is refused by the budget
+ // middleware long before this runs, and this keeps the fallback from becoming the one parser that
+ // would still gunzip an unaccounted body if that ordering ever changed.
+ adapter.post(basePath, createIpThrottle(ipRateLimiter), express.json({ inflate: false }), handler);
}