Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): bound the channel operations against an unanswered query
Yudhi Armyndharis05c77fc7ad55
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex aaa1993b4..e3efe6b11 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+- **Channel operations no longer answer a bare `500` when WhatsApp stays silent** — every one goes through a query helper that reports an absent answer as a malformed one, which the refusal classifier cannot place, so the raw error escaped with its message discarded; the channel lookup, invite lookup, subscribe, unsubscribe, delete and mute/unmute now share the same 30-second budget and answer `503`. Creating a channel is deliberately left unbounded for the same reason as creating a group — it is non-idempotent, and `503` is a status the Go SDK retries for `POST`.- **The three group-metadata reads no longer answer a bare `500` when WhatsApp stays silent** — `extractGroupMetadata` throws a Boom whose `data` is normalised to null, so the refusal classifier cannot place it and the raw error escaped with its message discarded; `GET /groups/{id}` and `GET /groups/join-info` now spend the same 30-second budget as the rest and answer `503`, and creating a group maps a genuine WhatsApp refusal to `403` instead of the same bare `500`. Group creation is deliberately left unbounded: it is the one non-idempotent call, and `503` is a status the Go SDK retries for `POST`, which could leave duplicate groups behind.- **A group list WhatsApp never answered is no longer served as "you are in no groups"** — `groupFetchAllParticipating` fills its result only behind an `if (groupsChild)`, so an unanswered query returns the same empty object an account with no groups produces, and `GET /sessions/{id}/groups` answered `200` with an empty array after a silent minute; there is nothing in the value to tell the two apart, so the read now shares the same 30-second budget as the group writes and answers `503` instead.- **A dead socket is no longer reported as a permissions problem** — the helper that decides whether a Baileys failure was a server refusal or a transport death guarded on `data !== undefined`, but Boom's constructor defaults `data` to `null`, so the guard matched every Boom ever thrown and a `Connection Closed` (428) was classified as a 4xx refusal: twelve group and profile writes answered `403 admin rights or permissions may be missing`, joining by invite answered `400 invalid invite code`, and reading invite info answered `404`, all for a socket that was simply down. The numeric code that `assertNodeErrorFree` attaches is the only discriminator needed and every genuine refusal still maps as before, so transport failures now propagate as a 5xx instead — **a change of status code on the gateway surface for those cases**. The tests that were meant to cover this passed because their fixture was a bare `Error` rather than a real `Boom`, and now use one.diff --git a/openapi.json b/openapi.jsonindex 6476c61a6..516f15d96 100644--- a/openapi.json+++ b/openapi.json@@ -5738,6 +5738,9 @@},"404": {"description": "Channel not found"+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget — the operation may or may not have applied."}},"summary": "Get a specific channel by ID",@@ -5777,6 +5780,9 @@}}}+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget — the operation may or may not have applied."}},"summary": "Unsubscribe from a channel",@@ -5878,6 +5884,9 @@},"403": {"description": "The engine refused — not found, or this account does not own it"+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget — the operation may or may not have applied."}},"summary": "Delete a channel this account owns",@@ -5936,6 +5945,9 @@},"403": {"description": "The engine refused"+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget — the operation may or may not have applied."}},"summary": "Mute or unmute a channel",@@ -5988,6 +6000,9 @@}}}+ },+ "503": {+ "description": "WhatsApp did not answer within the request budget — the operation may or may not have applied."}},"summary": "Subscribe to a channel using invite code",diff --git a/src/engine/adapters/baileys-channels.spec.ts b/src/engine/adapters/baileys-channels.spec.tsnew file mode 100644index 000000000..f06d088e6--- /dev/null+++ b/src/engine/adapters/baileys-channels.spec.ts@@ -0,0 +1,73 @@+import { Boom } from '@hapi/boom';+import type { WASocket } from '@whiskeysockets/baileys';+import { BaileysChannels, BaileysChannelsHost } from './baileys-channels';+import { EngineTransportError } from '../../common/errors/engine-transport.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';++/**+ * Every channel operation goes through Baileys' `executeWMexQuery`, which on an unanswered query+ * falls past its `if (child?.content)` guard and throws+ * `Boom('Failed to …, unexpected response structure.', { statusCode: 400, data: result })` with+ * result undefined — so `data` is null, `refusedStatusCode` cannot place it, and the raw Boom+ * escapes as a bare 500.+ *+ * `newsletterCreate` is deliberately left unbounded, for the same reason as `groupCreate`: it is+ * non-idempotent, and 503 is a status the Go SDK retries for POST.+ */++const never = (): Promise<never> => new Promise<never>(() => undefined);+/** What executeWMexQuery throws when nothing came back. */+const noAnswer = () => new Boom('Failed to newsletter metadata, unexpected response structure.', { statusCode: 400 });++function channels(sock: Record<string, jest.Mock>, budgetMs: number): BaileysChannels {+ const host = {+ ensureReady: () => undefined,+ getSocket: () => sock as unknown as WASocket,+ } as unknown as BaileysChannelsHost;+ return new BaileysChannels(host, budgetMs);+}++const META = { id: '120363000000000000@newsletter', name: 'Release notes' };++describe('channel operations report an unanswered query instead of a bare 500', () => {+ it.each([+ ['getChannelById', 'newsletterMetadata', (c: BaileysChannels) => c.getChannelById('120363@newsletter')],+ ['subscribeToChannel', 'newsletterMetadata', (c: BaileysChannels) => c.subscribeToChannel('CODE')],+ ['deleteChannel', 'newsletterDelete', (c: BaileysChannels) => c.deleteChannel('120363@newsletter')],+ ['muteChannel', 'newsletterMute', (c: BaileysChannels) => c.muteChannel('120363@newsletter', true)],+ ['unmuteChannel', 'newsletterUnmute', (c: BaileysChannels) => c.muteChannel('120363@newsletter', false)],+ ['unsubscribeFromChannel', 'newsletterUnfollow', (c: BaileysChannels) => c.unsubscribeFromChannel('120363@n')],+ ])('%s', async (_name, sockMethod, call) => {+ await expect(call(channels({ [sockMethod]: jest.fn(never) }, 15))).rejects.toBeInstanceOf(EngineTransportError);+ });++ it('subscribeToChannel is bounded on the follow too, not only the metadata read', async () => {+ const sock = {+ newsletterMetadata: jest.fn().mockResolvedValue(META),+ newsletterFollow: jest.fn(never),+ };+ await expect(channels(sock, 15).subscribeToChannel('CODE')).rejects.toBeInstanceOf(EngineTransportError);+ expect(sock.newsletterMetadata).toHaveBeenCalled();+ });+});++describe('channel operations that must not change', () => {+ it('createChannel maps a WA refusal to a refusal', async () => {+ const newsletterCreate = jest.fn().mockRejectedValue(new Boom('not-authorized', { data: 403 }));+ await expect(channels({ newsletterCreate }, 500).createChannel('N')).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it('createChannel lets an unanswered query propagate — deliberately NOT a 503', async () => {+ // Non-idempotent: 503 is retried for POST by the Go SDK, which would risk duplicate channels.+ const err = noAnswer();+ const newsletterCreate = jest.fn().mockRejectedValue(err);+ await expect(channels({ newsletterCreate }, 500).createChannel('N')).rejects.toBe(err);+ });++ it('still returns the channel when WhatsApp answers inside the budget', async () => {+ const newsletterMetadata = jest.fn().mockResolvedValue(META);+ await expect(channels({ newsletterMetadata }, 500).getChannelById('120363@newsletter')).resolves.toMatchObject({+ id: '120363000000000000@newsletter',+ });+ });+});diff --git a/src/engine/adapters/baileys-channels.ts b/src/engine/adapters/baileys-channels.tsindex 738b53964..9543d7362 100644--- a/src/engine/adapters/baileys-channels.ts+++ b/src/engine/adapters/baileys-channels.ts@@ -2,6 +2,7 @@ import type { WASocket } from '@whiskeysockets/baileys';import { Channel } from '../interfaces/whatsapp-engine.interface';import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';import { mapServerRefusal } from './baileys-groups';+import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';/*** Channel-domain operations extracted from BaileysAdapter. The adapter keeps the public@@ -15,7 +16,19 @@ export interface BaileysChannelsHost {}export class BaileysChannels {- constructor(private readonly host: BaileysChannelsHost) {}+ constructor(+ private readonly host: BaileysChannelsHost,+ private readonly queryBudgetMs: number = BAILEYS_QUERY_BUDGET_MS,+ ) {}++ /**+ * Bound a channel call. executeWMexQuery throws Boom(..., { statusCode: 400, data: result }) when+ * nothing came back, and with result undefined Boom normalises data to null — so the refusal+ * classifier cannot place it and the raw Boom escapes as a bare 500.+ */+ private bounded<T>(work: Promise<T>, operation: string): Promise<T> {+ return withQueryDeadline(work, this.queryBudgetMs, `WhatsApp did not answer ${operation} in time`);+ }/** Post-ensureReady socket handle. */private sock(): WASocket {@@ -25,20 +38,25 @@ export class BaileysChannels {async getChannelById(channelId: string): Promise<Channel | null> {this.host.ensureReady();// newsletterMetadata resolves ANY channel by jid (richer than the wwjs subscribed-list lookup).- const meta = await this.sock().newsletterMetadata('jid', channelId);+ const meta = await this.bounded(this.sock().newsletterMetadata('jid', channelId), 'the channel lookup');return meta ? this.toChannel(meta) : null;}async subscribeToChannel(inviteCode: string): Promise<Channel> {this.host.ensureReady();- const meta = await this.sock().newsletterMetadata('invite', inviteCode);+ const meta = await this.bounded(this.sock().newsletterMetadata('invite', inviteCode), 'the invite lookup');if (!meta) {throw new ChannelNotFoundError(inviteCode);}- await this.sock().newsletterFollow(meta.id);+ await this.bounded(this.sock().newsletterFollow(meta.id), 'the channel subscribe');return this.toChannel(meta);}+ /**+ * Deliberately NOT bounded, unlike every other call here: creating a channel is non-idempotent,+ * and 503 is a backpressure status the Go SDK retries three times for POST (sdk/go/retry.go).+ * A deadline abandons without cancelling, so a slow-but-succeeding create could leave duplicates.+ */async createChannel(name: string, description?: string): Promise<Channel> {this.host.ensureReady();const meta = await mapServerRefusal('Creating the channel', () => this.sock().newsletterCreate(name, description));@@ -47,19 +65,24 @@ export class BaileysChannels {async deleteChannel(channelId: string): Promise<void> {this.host.ensureReady();- await mapServerRefusal('Deleting the channel', () => this.sock().newsletterDelete(channelId));+ await mapServerRefusal('Deleting the channel', () =>+ this.bounded(this.sock().newsletterDelete(channelId), 'the channel delete'),+ );}async muteChannel(channelId: string, mute: boolean): Promise<void> {this.host.ensureReady();await mapServerRefusal(mute ? 'Muting the channel' : 'Unmuting the channel', () =>- mute ? this.sock().newsletterMute(channelId) : this.sock().newsletterUnmute(channelId),+ this.bounded(+ mute ? this.sock().newsletterMute(channelId) : this.sock().newsletterUnmute(channelId),+ mute ? 'the channel mute' : 'the channel unmute',+ ),);}async unsubscribeFromChannel(channelId: string): Promise<void> {this.host.ensureReady();- await this.sock().newsletterUnfollow(channelId);+ await this.bounded(this.sock().newsletterUnfollow(channelId), 'the channel unsubscribe');}/** Map a Baileys NewsletterMetadata to the neutral Channel shape (optionals only when present). */diff --git a/src/modules/channel/channel.controller.ts b/src/modules/channel/channel.controller.tsindex 104c4d19b..49ec518cf 100644--- a/src/modules/channel/channel.controller.ts+++ b/src/modules/channel/channel.controller.ts@@ -27,6 +27,10 @@ export class ChannelController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'channelId', description: 'Channel ID' })@ApiResponse({ status: 200, description: 'Channel details', type: ChannelDto })+ @ApiResponse({+ status: 503,+ description: 'WhatsApp did not answer within the request budget — the operation may or may not have applied.',+ })@ApiResponse({ status: 404, description: 'Channel not found' })async findOne(@Param('sessionId') sessionId: string, @Param('channelId') channelId: string) {return this.channelService.getChannelById(sessionId, channelId);@@ -85,6 +89,10 @@ export class ChannelController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'channelId', description: 'Channel ID' })@ApiResponse({ status: 200, description: 'Channel deleted', type: ChannelAckResponseDto })+ @ApiResponse({+ status: 503,+ description: 'WhatsApp did not answer within the request budget — the operation may or may not have applied.',+ })@ApiResponse({ status: 400, description: 'Session not started' })@ApiResponse({ status: 403, description: 'The engine refused — not found, or this account does not own it' })async remove(@@ -106,6 +114,10 @@ export class ChannelController {@ApiParam({ name: 'channelId', description: 'Channel ID' })@ApiBody({ type: MuteChannelDto })@ApiResponse({ status: 200, description: 'Channel muted or unmuted', type: ChannelAckResponseDto })+ @ApiResponse({+ status: 503,+ description: 'WhatsApp did not answer within the request budget — the operation may or may not have applied.',+ })@ApiResponse({ status: 400, description: 'Session not started, or validation failed' })@ApiResponse({ status: 403, description: 'The engine refused' })async mute(@@ -135,6 +147,10 @@ export class ChannelController {},})@ApiResponse({ status: 201, description: 'Successfully subscribed to channel', type: ChannelDto })+ @ApiResponse({+ status: 503,+ description: 'WhatsApp did not answer within the request budget — the operation may or may not have applied.',+ })async subscribe(@Param('sessionId') sessionId: string, @Body() body: SubscribeChannelDto) {return this.channelService.subscribeToChannel(sessionId, body.inviteCode);}@@ -145,6 +161,10 @@ export class ChannelController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiParam({ name: 'channelId', description: 'Channel ID to unsubscribe from' })@ApiResponse({ status: 200, description: 'Successfully unsubscribed from channel', type: ChannelAckResponseDto })+ @ApiResponse({+ status: 503,+ description: 'WhatsApp did not answer within the request budget — the operation may or may not have applied.',+ })async unsubscribe(@Param('sessionId') sessionId: string, @Param('channelId') channelId: string) {await this.channelService.unsubscribeFromChannel(sessionId, channelId);return { success: true };