Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(events): refuse an unsubscribe with a bad session id
Yudhi Armyndharis4f5021db04bc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f793544b0..d30d09949 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -38,6 +38,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- 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`, because some accounts reject a non-standard name on phone-number pairing (#1857, thanks @yoosufhaffejee).- 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.+- A `/events` WebSocket `unsubscribe` whose `sessionId` is neither `*` nor a session id of at most 128 letters, digits and hyphens answers `INVALID_SESSION`, as `subscribe` does.- The Baileys engine refuses SVG input to its image decoder, so a sticker sent as an SVG answers `400` and an outbound image's thumbnail skips it; raster images convert as before.### Fixeddiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 8f4f84f97..84138319d 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -7111,7 +7111,7 @@ Live events are pushed as a **nested** envelope (note: `data` is under `payload`}```-Error `code` values include `UNAUTHORIZED`, `INVALID_MESSAGE`, `INVALID_SESSION`, `INVALID_EVENTS`, `FORBIDDEN_SESSION`, `FORBIDDEN_EVENTS`, `TOO_MANY_SUBSCRIPTIONS`, and `RATE_LIMITED`. `RATE_LIMITED` is followed by a disconnect when a handshake exceeds the per-IP connection-attempt window or the key's concurrent-socket cap; a frame over the per-key frame budget gets `RATE_LIMITED` and is dropped undispatched, and the socket stays open. A subscribe answers `INVALID_SESSION` when `sessionId` is missing, or is neither `"*"` nor a session id of at most 128 letters, digits and hyphens. An unsubscribe answers `INVALID_SESSION` when `sessionId` is missing, empty or not a string. A subscribe answers `TOO_MANY_SUBSCRIPTIONS` when it would take the connection past 4096 rooms; chat-restricted subscriptions count every literal chat address form for each session and event. Unsubscribe before subscribing to more.+Error `code` values include `UNAUTHORIZED`, `INVALID_MESSAGE`, `INVALID_SESSION`, `INVALID_EVENTS`, `FORBIDDEN_SESSION`, `FORBIDDEN_EVENTS`, `TOO_MANY_SUBSCRIPTIONS`, and `RATE_LIMITED`. `RATE_LIMITED` is followed by a disconnect when a handshake exceeds the per-IP connection-attempt window or the key's concurrent-socket cap; a frame over the per-key frame budget gets `RATE_LIMITED` and is dropped undispatched, and the socket stays open. A subscribe answers `INVALID_SESSION` when `sessionId` is missing, or is neither `"*"` nor a session id of at most 128 letters, digits and hyphens. An unsubscribe answers `INVALID_SESSION` when `sessionId` is missing, empty, not a string, or neither `"*"` nor such a session id. A subscribe answers `TOO_MANY_SUBSCRIPTIONS` when it would take the connection past 4096 rooms; chat-restricted subscriptions count every literal chat address form for each session and event. Unsubscribe before subscribing to more.### Subscribable eventsdiff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex c008aecdd..1970e377d 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -408,6 +408,47 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(sock.leave).not.toHaveBeenCalledWith(buildRoomName('sess-1', 'message.received'));});+ // An unsubscribe is answered with the session id it names, so it is bound like the one a subscribe+ // accepts: a reply holds only "*" or a short session id, never whatever string the client sent.+ it.each([+ ['oversized', 'a'.repeat(129)],+ ['malformed', 'sess:1'],+ ])('refuses an unsubscribe with a %s sessionId instead of echoing it', async (_label, sessionId) => {+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));+ sock.rooms.add(buildRoomName('sess-1', 'message.received'));++ const res = (await gateway.handleMessage(asSocket(sock), {+ type: 'unsubscribe',+ sessionId,+ requestId: 'r1',+ } as unknown as WSClientMessage)) as WSErrorResponse;++ expect(res.code).toBe('INVALID_SESSION');+ expect(res.requestId).toBe('r1');+ expect(JSON.stringify(sock.emit.mock.calls)).not.toContain(sessionId);+ expect(sock.leave).not.toHaveBeenCalled();+ });++ it('still answers an unsubscribe from "*" and from a session id at the length limit', async () => {+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));+ const longest = 'a'.repeat(128);+ sock.rooms.add(buildRoomName(longest, 'message.received'));+ sock.rooms.add(buildRoomName('sess-2', 'message.received'));++ const one = await gateway.handleMessage(asSocket(sock), { type: 'unsubscribe', sessionId: longest } as never);+ expect(one).toMatchObject({ type: 'unsubscribed', sessionId: longest });+ expect(sock.leave).toHaveBeenCalledTimes(1);+ expect(sock.leave).toHaveBeenCalledWith(buildRoomName(longest, 'message.received'));++ const all = await gateway.handleMessage(asSocket(sock), { type: 'unsubscribe', sessionId: '*' } as never);+ expect(all).toMatchObject({ type: 'unsubscribed', sessionId: '*' });+ expect(sock.leave).toHaveBeenCalledWith(buildRoomName('sess-2', 'message.received'));+ });+it('forbids a session-scoped key from subscribing to the * wildcard', async () => {authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: ['sess-1'] });const sock = makeSocket({ apiKey: 'good' });diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 24af80db7..4d5ced985 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -137,6 +137,11 @@ const MAX_REQUEST_ID_LENGTH = 128;const MAX_ROOMS_PER_SOCKET = 4096;const TOO_MANY_SUBSCRIPTIONS_MESSAGE = `A connection may hold at most ${MAX_ROOMS_PER_SOCKET} subscriptions; unsubscribe first`;+/** `*` or a session id: all a subscription room, and a reply that names one, may carry. */+function isSessionSelector(sessionId: string): boolean {+ return sessionId === '*' || (sessionId.length <= MAX_SUBSCRIBE_SESSION_ID_LENGTH && isSafeSessionName(sessionId));+}+/** Why an API key's live WebSocket sockets are being torn down — drives the client-facing message. */export type ApiKeyEvictionReason = 'revoked' | 'deleted' | 'authorization_changed' | 'expired';@@ -562,7 +567,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGateif (!sessionId || typeof sessionId !== 'string') {return this.createError('INVALID_SESSION', 'sessionId is required', requestId);}- if (sessionId !== '*' && !(sessionId.length <= MAX_SUBSCRIBE_SESSION_ID_LENGTH && isSafeSessionName(sessionId))) {+ if (!isSessionSelector(sessionId)) {return this.createError('INVALID_SESSION', 'sessionId must be "*" or a session id', requestId);}@@ -699,11 +704,15 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGateprivate handleUnsubscribe(client: Socket, message: WSUnsubscribeRequest): WSUnsubscribedResponse | WSErrorResponse {const { sessionId, requestId } = message;- // Same check as subscribe: a missing sessionId matched no room, left every subscription in place,- // and was still answered 'unsubscribed'.+ // Same checks as subscribe: a missing sessionId matched no room, left every subscription in place,+ // and was still answered 'unsubscribed'. The reply carries the id back, so one no subscribe could+ // have accepted is refused rather than echoed.if (!sessionId || typeof sessionId !== 'string') {return this.createError('INVALID_SESSION', 'sessionId is required', requestId);}+ if (!isSessionSelector(sessionId)) {+ return this.createError('INVALID_SESSION', 'sessionId must be "*" or a session id', requestId);+ }// Leave all rooms for this sessionconst clientRooms = Array.from(client.rooms);