Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(events): cancel a subscribe that an unsubscribe overtook
Yudhi Armyndharisf630f5ac1f4a
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex c9839f374..f1cc9969c 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -493,6 +493,76 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(sessionRoomJoins(sock)).toEqual([]);});+ describe('pending subscription cancellation', () => {+ const pendingSubscribe = async (sessionId = 'sess-1') => {+ const apiKey = { id: 'k1', name: 'k', role: 'viewer', allowedSessions: null };+ authService.validateApiKey.mockResolvedValue(apiKey);+ const sock = makeSocket({ apiKey: 'good' });+ sock.join.mockImplementation((room: string) => sock.rooms.add(room));+ sock.leave.mockImplementation((room: string) => sock.rooms.delete(room));+ await gateway.handleConnection(asSocket(sock));+ let resolve!: (key: typeof apiKey) => void;+ let reject!: (error: Error) => void;+ const validation = new Promise<typeof apiKey>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ let entered!: () => void;+ const started = new Promise<void>(yes => (entered = yes));+ authService.validateApiKey.mockImplementationOnce(() => {+ entered();+ return validation;+ });+ const subscribing = gateway.handleMessage(asSocket(sock), subscribeMsg(sessionId, ['message.received']));+ await started;+ return { sock, apiKey, resolve, reject, subscribing };+ };+ const pendingFor = (sock: MockSocket) =>+ (gateway as unknown as { pendingSubscriptions: WeakMap<Socket, Set<unknown>> }).pendingSubscriptions.get(+ asSocket(sock),+ );++ it.each([+ ['sess-1', 'sess-1'],+ ['sess-1', '*'],+ ['*', '*'],+ ])('cancels a pending subscribe to %s when unsubscribing from %s', async (sessionId, unsubscribe) => {+ const pending = await pendingSubscribe(sessionId);+ expect(+ await gateway.handleMessage(asSocket(pending.sock), { type: 'unsubscribe', sessionId: unsubscribe }),+ ).toMatchObject({ type: 'unsubscribed' });+ pending.resolve(pending.apiKey);+ expect(await pending.subscribing).toMatchObject({ code: 'SUBSCRIPTION_CANCELLED', requestId: 'r1' });+ expect(sessionRoomJoins(pending.sock)).toEqual([]);+ expect(pendingFor(pending.sock)).toBeUndefined();++ expect(+ await gateway.handleMessage(asSocket(pending.sock), subscribeMsg(sessionId, ['message.received'])),+ ).toMatchObject({ type: 'subscribed' });+ expect(pending.sock.rooms.has(buildRoomName(sessionId, 'message.received'))).toBe(true);+ });++ it('does not cancel a pending subscribe when another session is unsubscribed', async () => {+ const pending = await pendingSubscribe();+ expect(+ await gateway.handleMessage(asSocket(pending.sock), { type: 'unsubscribe', sessionId: 'sess-2' }),+ ).toMatchObject({ type: 'unsubscribed' });+ pending.resolve(pending.apiKey);+ expect(await pending.subscribing).toMatchObject({ type: 'subscribed' });+ expect(pending.sock.rooms.has(buildRoomName('sess-1', 'message.received'))).toBe(true);+ });++ it('still refuses failed authorization after a cancellation and clears the pending subscription', async () => {+ const pending = await pendingSubscribe();+ await gateway.handleMessage(asSocket(pending.sock), { type: 'unsubscribe', sessionId: '*' });+ pending.reject(new UnauthorizedException('API key revoked'));+ expect(await pending.subscribing).toMatchObject({ code: 'UNAUTHORIZED' });+ expect(pending.sock.disconnected).toBe(true);+ expect(sessionRoomJoins(pending.sock)).toEqual([]);+ expect(pendingFor(pending.sock)).toBeUndefined();+ });+ });+// Client-IP resolution: an IP-restricted key (allowedIps set) must be ENFORCED at the WS surface,// not blanket-rejected. validateApiKey throws "Client IP could not be determined" when allowedIps is// set but no clientIp is supplied — so the gateway must pass the trusted-proxy-aware IP at connectdiff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 434d914f0..79a17946f 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -184,6 +184,9 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate*/private readonly socketsByKeyId = new Map<string, Set<Socket>>();private readonly chatDeliveries = new Map<string, Promise<void>>();+ // Subscribes still re-validating their key. An unsubscribe answered meanwhile cancels the ones it covers, so+ // they cannot join rooms after the client was told they were left.+ private readonly pendingSubscriptions = new WeakMap<Socket, Set<{ sessionId: string; cancelled: boolean }>>();private authzSweepTimer?: ReturnType<typeof setInterval>;/**@@ -590,6 +593,13 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate// here too, not just at connect.const rawApiKey = (client.data as { rawApiKey?: string }).rawApiKey;const clientIp = this.resolveClientIp(client);+ const subscription = { sessionId, cancelled: false };+ let pending = this.pendingSubscriptions.get(client);+ if (!pending) {+ pending = new Set();+ this.pendingSubscriptions.set(client, pending);+ }+ pending.add(subscription);let subscriberKey: ApiKey | null;try {subscriberKey = rawApiKey ? await this.authService.validateApiKey(rawApiKey, clientIp) : null;@@ -602,6 +612,9 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatemetadata: { surface: 'websocket' },errorMessage: error instanceof Error ? error.message : String(error),});+ } finally {+ pending.delete(subscription);+ if (pending.size === 0) this.pendingSubscriptions.delete(client);}if (!subscriberKey) {client.emit('message', this.createError('UNAUTHORIZED', 'API key is no longer valid', requestId));@@ -697,6 +710,10 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatereturn this.createError('TOO_MANY_SUBSCRIPTIONS', TOO_MANY_SUBSCRIPTIONS_MESSAGE, requestId);}+ if (subscription.cancelled) {+ return this.createError('SUBSCRIPTION_CANCELLED', 'Subscription was cancelled', requestId);+ }+// Join rooms for each session/event combinationfor (const room of rooms) {void client.join(room);@@ -734,6 +751,10 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatereturn this.createError('INVALID_SESSION', 'sessionId must be "*" or a session id', requestId);}+ for (const subscription of this.pendingSubscriptions.get(client) ?? []) {+ if (sessionId === '*' || subscription.sessionId === sessionId) subscription.cancelled = true;+ }+// Leave all rooms for this sessionconst clientRooms = Array.from(client.rooms);const sessionPrefix = `session:${sessionId}:`;