Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(ingress): honor a declared ack content type when it is safe (#1640)
Yudhi Armyndharis269406d98c4f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 67f858498..b8b762776 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- An ingress route's declared ack `content-type` reaches the provider instead of being overwritten with `text/plain`, so a provider that requires `application/json` on a 200 or 202 accepts the ack; a type a browser could execute is still forced to `text/plain` ([#1637](https://github.com/rmyndharis/OpenWA/issues/1637)). Thanks @wesamdev for the report.- Restoring a data archive into PostgreSQL from a gateway that does not run in UTC no longer shifts every timestamp by the host offset, and no longer shifts it again on each further restore ([#1624](https://github.com/rmyndharis/OpenWA/issues/1624)).- Retention sweeps on PostgreSQL delete the rows their window names instead of taking up to the host's UTC offset of younger rows with them, and the `today` message counts cover the host's local day.- Session leases on PostgreSQL compare as instants across nodes in different time zones and across a daylight-saving change.diff --git a/src/modules/integration/ingress-ack.spec.ts b/src/modules/integration/ingress-ack.spec.tsindex e190ace4a..d8396892e 100644--- a/src/modules/integration/ingress-ack.spec.ts+++ b/src/modules/integration/ingress-ack.spec.ts@@ -1,4 +1,4 @@-import { renderAck } from './ingress-ack';+import { ackContentType, renderAck } from './ingress-ack';const ctx = { rawBody: '{"a":1}', timestamp: '1700000000', id: 'd1' };@@ -29,3 +29,31 @@ describe('renderAck', () => {expect(renderAck({ status: 204 }, ctx)).toEqual({ status: 204 });});});++describe('ackContentType', () => {+ it('falls back to text/plain when no headers or no content-type are declared', () => {+ expect(ackContentType(undefined)).toBe('text/plain');+ expect(ackContentType({})).toBe('text/plain');+ expect(ackContentType({ 'x-ack': '1' })).toBe('text/plain');+ });++ it('honors an allowlisted type, keeping the declared value verbatim', () => {+ expect(ackContentType({ 'content-type': 'application/json' })).toBe('application/json');+ expect(ackContentType({ 'content-type': 'application/json; charset=utf-8' })).toBe(+ 'application/json; charset=utf-8',+ );+ });++ it('matches the header name and the media type case-insensitively', () => {+ expect(ackContentType({ 'Content-Type': 'Application/JSON' })).toBe('Application/JSON');+ });++ it('forces text/plain for anything a browser could execute', () => {+ expect(ackContentType({ 'content-type': 'text/html' })).toBe('text/plain');+ expect(ackContentType({ 'content-type': 'image/svg+xml' })).toBe('text/plain');+ expect(ackContentType({ 'content-type': 'application/xhtml+xml' })).toBe('text/plain');+ // A prefix that merely starts with an allowlisted type must not slip through.+ expect(ackContentType({ 'content-type': 'application/json-but-html' })).toBe('text/plain');+ expect(ackContentType({ 'content-type': '' })).toBe('text/plain');+ });+});diff --git a/src/modules/integration/ingress-ack.ts b/src/modules/integration/ingress-ack.tsindex c897bb02a..fbfa73c22 100644--- a/src/modules/integration/ingress-ack.ts+++ b/src/modules/integration/ingress-ack.ts@@ -25,6 +25,26 @@ export function renderAck(spec: IngressResponseContract['ack'] | undefined, ctx:return result;}+/**+ * Media types a route's declared ack Content-Type may actually put on the wire. Express types a bare+ * send() as text/html, which would make a reflected body (a GET challenge echo, an ack template+ * interpolating {rawBody}) XSS material on this origin. A declared type is therefore honored only when+ * a browser will not execute it, and anything else falls back to text/plain. `noSniff` (configure-app)+ * stops a browser re-sniffing an honored type as HTML. Providers that validate the ack need+ * application/json (Supabase Auth rejects a 200 or 202 that is not), and nothing needs more than that.+ */+const HONORED_ACK_MEDIA_TYPES = new Set(['application/json', 'text/plain']);++/** The Content-Type to emit for an ack: the declared value when allowlisted, else text/plain. Total. */+export function ackContentType(headers: Record<string, string> | undefined): string {+ const declared = headers+ ? Object.entries(headers).find(([name]) => name.toLowerCase() === 'content-type')?.[1]+ : undefined;+ if (!declared) return 'text/plain';+ const mediaType = declared.split(';', 1)[0].trim().toLowerCase();+ return HONORED_ACK_MEDIA_TYPES.has(mediaType) ? declared : 'text/plain';+}+function substitute(template: string, ctx: AckRenderCtx): string {// split/join avoids `$`-interpretation that String.replace applies to the replacement string.return templatediff --git a/src/modules/integration/ingress.controller.spec.ts b/src/modules/integration/ingress.controller.spec.tsindex 2592e831d..98cb7776c 100644--- a/src/modules/integration/ingress.controller.spec.ts+++ b/src/modules/integration/ingress.controller.spec.ts@@ -6,10 +6,14 @@ import { IngressService } from './ingress.service';// key order, and a trailing newline. The controller must forward the RAW bytes, not a re-serialized body.const RAW = '{\n "event": "message_created",\n "id": 42\n}\n';+// Models Express's header precedence: set() and type() write the same Content-Type slot, so the LAST+// writer wins. Recording them in separate fields hid the override, which let one test assert a declared+// application/json and another the forced text/plain with neither noticing they contradicted.function fakeRes() {- const captured: { status?: number; body?: string; headers?: Record<string, string>; contentType?: string } = {};+ const headers: Record<string, string> = {};+ const captured: { status?: number; body?: string; headers: Record<string, string> } = { headers };const type = jest.fn((contentType: string) => {- captured.contentType = contentType;+ headers['content-type'] = contentType;return res;});const res = {@@ -22,8 +26,8 @@ function fakeRes() {captured.body = body;return res;}),- set: jest.fn((headers: Record<string, string>) => {- captured.headers = headers;+ set: jest.fn((incoming: Record<string, string>) => {+ for (const [name, value] of Object.entries(incoming)) headers[name.toLowerCase()] = value;return res;}),} as unknown as Response;@@ -46,7 +50,47 @@ describe('reflection content type', () => {await controller.receive('chatwoot', 'acct1', {}, req, res);- expect(captured.contentType).toBe('text/plain');+ expect(captured.headers['content-type']).toBe('text/plain');+ });++ it('forces text/plain over a declared type a browser would execute', async () => {+ const handle = jest.fn().mockResolvedValue({+ status: 200,+ body: '<script>alert(1)</script>',+ headers: { 'content-type': 'text/html' },+ });+ const controller = new IngressController({ handle } as unknown as IngressService);+ const { res, captured } = fakeRes();+ const req = {+ method: 'POST',+ params: { path: ['send-sms'] },+ headers: { 'x-delivery': 'd1' },+ rawBody: Buffer.from('{}', 'utf8'),+ } as unknown as Request & { rawBody?: Buffer };++ await controller.receive('p', 'i1', {}, req, res);++ expect(captured.headers['content-type']).toBe('text/plain');+ });++ it('emits a declared application/json, which a provider may require on a 200', async () => {+ const handle = jest.fn().mockResolvedValue({+ status: 200,+ body: '{"ok":true}',+ headers: { 'content-type': 'application/json' },+ });+ const controller = new IngressController({ handle } as unknown as IngressService);+ const { res, captured } = fakeRes();+ const req = {+ method: 'POST',+ params: { path: ['send-sms'] },+ headers: { 'x-delivery': 'd1' },+ rawBody: Buffer.from('{}', 'utf8'),+ } as unknown as Request & { rawBody?: Buffer };++ await controller.receive('p', 'i1', {}, req, res);++ expect(captured.headers['content-type']).toBe('application/json');});});diff --git a/src/modules/integration/ingress.controller.ts b/src/modules/integration/ingress.controller.tsindex dc1707ff2..b2c30a242 100644--- a/src/modules/integration/ingress.controller.ts+++ b/src/modules/integration/ingress.controller.ts@@ -3,6 +3,7 @@ import { SkipThrottle } from '@nestjs/throttler';import { ApiTags, ApiOkResponse, ApiParam, ApiResponse } from '@nestjs/swagger';import type { Request, Response } from 'express';import { Public } from '../auth/decorators/auth.decorators';+import { ackContentType } from './ingress-ack';import { IngressService } from './ingress.service';import { InstanceThrottlerGuard } from './instance-throttler.guard';@@ -93,9 +94,10 @@ export class IngressController {});if (result.headers) res.set(result.headers);// Both reflections echo provider-controlled strings (hub.challenge, the ack template). Express- // types a bare send() as text/html, which turns a reflection into XSS material on this origin —- // force text/plain so the browser refuses to parse it.- res.type('text/plain');+ // types a bare send() as text/html, which turns a reflection into XSS material on this origin, so+ // only a non-executable declared type survives and everything else is forced to text/plain. This+ // runs AFTER res.set on purpose: both write the same Content-Type slot and the last writer wins.+ res.type(ackContentType(result.headers));res.status(result.status).send(result.body ?? '');}}