Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(events): echo only a short string request id
Yudhi Armyndharisd1cafda82c4a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2131aed9b..1da042bfc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -35,6 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Storage import abort messages name the `STORAGE_IMPORT_MAX_BYTES` or `STORAGE_IMPORT_MAX_ENTRIES` setting that stopped them.- CI and the weekly security scan run `npm audit` over the JavaScript SDK, and Dependabot watches its lockfile.- The Baileys linked-device name defaults to `Ubuntu` instead of `OpenWA`, so phone-number pairing works without setting `BAILEYS_BROWSER_NAME`.+- The `/events` WebSocket echoes a `requestId` only when it is a string of at most 128 characters; any other value is dropped from the reply.### Fixeddiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex d717f9a6c..5b390c2c1 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -7051,12 +7051,12 @@ All client commands are sent on the Socket.IO event named **`message`** using a{ type, sessionId, events, requestId }```-| Field | Type | Applies to | Description |-| ----------- | ---------------------------------------- | ---------------------- | --------------------------------------------------------- |-| `type` | `"subscribe" \| "unsubscribe" \| "ping"` | all | Command discriminator. |-| `sessionId` | string | subscribe, unsubscribe | A session id, or `"*"` for all sessions. |-| `events` | string[] | subscribe | Event names to subscribe to, or `["*"]` for all. |-| `requestId` | string (optional) | all | Echoed back on the matching server reply for correlation. |+| Field | Type | Applies to | Description |+| ----------- | ---------------------------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |+| `type` | `"subscribe" \| "unsubscribe" \| "ping"` | all | Command discriminator. |+| `sessionId` | string | subscribe, unsubscribe | A session id, or `"*"` for all sessions. |+| `events` | string[] | subscribe | Event names to subscribe to, or `["*"]` for all. |+| `requestId` | string (optional) | all | Echoed back on the matching server reply for correlation. At most 128 characters; any other value is dropped and the reply carries none. |A `ping` carries only `{ type: "ping", requestId? }`.diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex 9beb5bbd7..c008aecdd 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -1192,6 +1192,27 @@ describe('EventsGateway rate limiting', () => {};expect(otherSubnet.type).not.toBe('error');});++ it('echoes a request id only when it is a short string, never structure the client built', async () => {+ process.env.WS_RATE_LIMIT_FRAME_PER_SECOND = '1000';+ process.env.WS_RATE_LIMIT_FRAME_BURST = '1000';+ const gw = buildGateway();+ const send = async (message: unknown) =>+ (await gw.handleMessage(asSocket(makeSock('a', {}, '203.0.113.9')), message as WSClientMessage)) as {+ requestId?: unknown;+ code?: string;+ };++ expect((await send({ type: 'ping', requestId: 'r1' })).requestId).toBe('r1');+ expect((await send({ type: 'ping', requestId: 'x'.repeat(128) })).requestId).toBe('x'.repeat(128));+ // A reply that carried client JSON back made the transport serialize whatever the client nested in it.+ for (const hostile of ['x'.repeat(129), { a: { b: 1 } }, ['r'], 7, true, null]) {+ expect((await send({ type: 'ping', requestId: hostile })).requestId).toBeUndefined();+ const refused = await send({ type: 'no-such-type', requestId: hostile });+ expect(refused.code).toBe('INVALID_MESSAGE');+ expect(refused.requestId).toBeUndefined();+ }+ });});describe('per-key simultaneous socket cap', () => {diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 5aa099f49..d472026a4 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -78,6 +78,19 @@ const CHAT_EVENTS = new Set(['event.response',]);+/**+ * The frame with a `requestId` that is not a short string dropped. A reply that carried client JSON back+ * made the transport serialize whatever structure the client nested in it, which is not the client's to+ * choose; the handlers below then never see anything but a string or nothing.+ */+function withSafeRequestId(message: WSClientMessage | null | undefined): WSClientMessage | null | undefined {+ if (typeof message !== 'object' || message === null || Array.isArray(message)) return message;+ const { requestId } = message as { requestId?: unknown };+ if (requestId === undefined) return message;+ if (typeof requestId === 'string' && requestId.length <= MAX_REQUEST_ID_LENGTH) return message;+ return { ...message, requestId: undefined };+}+function chatRoom(sessionId: string, event: string, chatId: string): string {return `${buildRoomName(sessionId, event)}:chat:${encodeURIComponent(chatId)}`;}@@ -117,6 +130,8 @@ const QR_ALLOWED_ROLES: ReadonlySet<string> = new Set([ApiKeyRole.OPERATOR, ApiK* subscription rooms, far above every event of every session a client would follow.*/const MAX_SUBSCRIBE_SESSION_ID_LENGTH = 128;+// A request id only correlates a reply with its request, so only a short string is ever echoed back.+const MAX_REQUEST_ID_LENGTH = 128;const MAX_ROOMS_PER_SOCKET = 4096;/** Why an API key's live WebSocket sockets are being torn down — drives the client-facing message. */@@ -489,7 +504,8 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate@SubscribeMessage('message')// A client may emit 'message' with no payload or with null, so the body is typed as possibly nil and// every read is guarded: such a frame answers INVALID_MESSAGE instead of throwing in the handler.- async handleMessage(@ConnectedSocket() client: Socket, @MessageBody() message: WSClientMessage | null | undefined) {+ async handleMessage(@ConnectedSocket() client: Socket, @MessageBody() incoming: WSClientMessage | null | undefined) {+ const message = withSafeRequestId(incoming);// Per-key token bucket on every inbound frame. Keyed by the validated key id; a socket// whose handshake validation is still in flight has no key yet and is metered by IP.// Over-budget frames get an error frame back and are NOT dispatched to a handler — in