Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): map w:mex refusals on channel follow, unfollow and lookup

Yudhi Armyndharisdb8ffa894e98
diff --git a/src/engine/adapters/baileys-channels.ts b/src/engine/adapters/baileys-channels.ts
index 46c949929..e35a696c8 100644
--- a/src/engine/adapters/baileys-channels.ts
+++ b/src/engine/adapters/baileys-channels.ts
@@ -28,18 +28,20 @@ export interface BaileysChannelsHost {
* reads. It throws `Boom(msg, { statusCode: errorCode, data: firstError })` instead — the code on
* the Boom, the error node as `data`.
*
- * A non-null OBJECT `data` is the discriminator, and it is safe here specifically: Boom defaults
- * `data` to null, so every transport failure carries null, and so does executeWMexQuery's OTHER
- * throw for an unanswered query (`data: result` with result undefined). Kept local to this file
- * rather than folded into refusedStatusCode, because promiseTimeout's Boom also carries an object
- * `data` with a 4xx code and must never be read as a refusal.
+ * The discriminator is a `data` that is a GraphQL error node, one carrying `message` or
+ * `extensions`. Any object is not enough: promiseTimeout (Utils/generics.js) rejects a stalled send
+ * or an unanswered query with `Boom('Timed Out', { statusCode: 408, data: { stack } })`, and
+ * executeWMexQuery's OTHER throw carries the raw result node as `data`. Both are transport
+ * failures, and reading their 4xx code as a refusal would turn a stalled socket into a 403 or 404.
*/
export function wmexRefusalCode(error: unknown): number | undefined {
const err = error as { data?: unknown; output?: { statusCode?: unknown } } | null | undefined;
if (typeof err?.data === 'number') {
return err.data;
}
- if (err?.data !== null && typeof err?.data === 'object' && typeof err.output?.statusCode === 'number') {
+ const node = err?.data as { message?: unknown; extensions?: unknown } | null | undefined;
+ const isGraphQlError = typeof node === 'object' && node !== null && ('message' in node || 'extensions' in node);
+ if (isGraphQlError && typeof err?.output?.statusCode === 'number') {
return err.output.statusCode;
}
return undefined;
@@ -68,22 +70,42 @@ 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.bounded(this.sock().newsletterMetadata('jid', channelId), 'the channel lookup');
+ const meta = await this.lookup('jid', channelId, 'the channel lookup');
return meta ? this.toChannel(meta) : null;
}
async subscribeToChannel(inviteCode: string): Promise<Channel> {
this.host.ensureReady();
- const meta = await this.bounded(this.sock().newsletterMetadata('invite', inviteCode), 'the invite lookup');
+ const meta = await this.lookup('invite', inviteCode, 'the invite lookup');
if (!meta) {
throw new ChannelNotFoundError(inviteCode);
}
- await mapServerRefusal('Subscribing to the channel', () =>
- this.bounded(this.sock().newsletterFollow(meta.id), 'the channel subscribe'),
+ await mapServerRefusal(
+ 'Subscribing to the channel',
+ () => this.bounded(this.sock().newsletterFollow(meta.id), 'the channel subscribe'),
+ wmexRefusalCode,
);
return this.toChannel(meta);
}
+ /**
+ * A channel lookup that WhatsApp refuses (an unknown id, a bad invite code) comes back as a w:mex
+ * GraphQL error rather than an empty node, so a 4xx refusal is read as "no such channel", the same
+ * way the group invite lookup reads one. A rate limit (429) or a timeout (408) says nothing about
+ * the channel, so it propagates, as does the deadline, which stays inside.
+ */
+ private async lookup(type: 'jid' | 'invite', key: string, operation: string) {
+ try {
+ return await this.bounded(this.sock().newsletterMetadata(type, key), operation);
+ } catch (error) {
+ const code = wmexRefusalCode(error);
+ if (code !== undefined && code >= 400 && code < 500 && code !== 408 && code !== 429) {
+ return null;
+ }
+ throw error;
+ }
+ }
+
/**
* 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).
@@ -161,10 +183,12 @@ export class BaileysChannels {
async unsubscribeFromChannel(channelId: string): Promise<void> {
this.host.ensureReady();
- // The other channel writes map WhatsApp's refusal; this one did not, so unfollowing a channel
- // the account no longer follows answered 500 where whatsapp-web.js answers the documented 403.
- await mapServerRefusal('Unsubscribing from the channel', () =>
- this.bounded(this.sock().newsletterUnfollow(channelId), 'the channel unsubscribe'),
+ // Unfollowing a channel the account no longer follows is refused like the other channel writes,
+ // on either refusal channel, and answers the documented 403 as whatsapp-web.js does.
+ await mapServerRefusal(
+ 'Unsubscribing from the channel',
+ () => this.bounded(this.sock().newsletterUnfollow(channelId), 'the channel unsubscribe'),
+ wmexRefusalCode,
);
}
diff --git a/src/engine/adapters/baileys-wmex-refusal.spec.ts b/src/engine/adapters/baileys-wmex-refusal.spec.ts
index 63bb9bca9..767c2ad98 100644
--- a/src/engine/adapters/baileys-wmex-refusal.spec.ts
+++ b/src/engine/adapters/baileys-wmex-refusal.spec.ts
@@ -3,6 +3,7 @@ import type { WASocket } from '@whiskeysockets/baileys';
import { BaileysChannels, BaileysChannelsHost } from './baileys-channels';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import { EngineTransportError } from '../../common/errors/engine-transport.error';
+import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';
/**
* Channels do not fail like the rest of the adapter. executeWMexQuery reports a server refusal as a
@@ -34,11 +35,24 @@ describe('channel refusals map to 403, not a bare 500', () => {
['deleteChannel', 'newsletterDelete', (c: BaileysChannels) => c.deleteChannel('120363@newsletter')],
['muteChannel', 'newsletterMute', (c: BaileysChannels) => c.muteChannel('120363@newsletter', true)],
['createChannel', 'newsletterCreate', (c: BaileysChannels) => c.createChannel('N')],
+ [
+ 'unsubscribeFromChannel',
+ 'newsletterUnfollow',
+ (c: BaileysChannels) => c.unsubscribeFromChannel('120363@newsletter'),
+ ],
])('%s', async (_n, method, call) => {
const sock = { [method]: jest.fn().mockRejectedValue(wmexRefusal(403)) };
await expect(call(channels(sock, 500))).rejects.toBeInstanceOf(EngineRefusedError);
});
+ it('subscribeToChannel: a refused follow', async () => {
+ const sock = {
+ newsletterMetadata: jest.fn().mockResolvedValue({ id: '120363@newsletter', name: 'N' }),
+ newsletterFollow: jest.fn().mockRejectedValue(wmexRefusal(403)),
+ };
+ await expect(channels(sock, 500).subscribeToChannel('CODE')).rejects.toBeInstanceOf(EngineRefusedError);
+ });
+
it('maps any 4xx the GraphQL payload reports, not only 403', async () => {
const newsletterDelete = jest.fn().mockRejectedValue(wmexRefusal(404));
await expect(channels({ newsletterDelete }, 500).deleteChannel('120363@newsletter')).rejects.toBeInstanceOf(
@@ -47,6 +61,44 @@ describe('channel refusals map to 403, not a bare 500', () => {
});
});
+describe('a refused channel lookup is "no such channel", not a bare 500', () => {
+ it('getChannelById resolves null, which the service answers 404', async () => {
+ const newsletterMetadata = jest.fn().mockRejectedValue(wmexRefusal(404));
+ await expect(channels({ newsletterMetadata }, 500).getChannelById('120363@newsletter')).resolves.toBeNull();
+ });
+
+ it('subscribeToChannel with a refused invite lookup throws ChannelNotFoundError', async () => {
+ const sock = { newsletterMetadata: jest.fn().mockRejectedValue(wmexRefusal(404)), newsletterFollow: jest.fn() };
+ await expect(channels(sock, 500).subscribeToChannel('BAD')).rejects.toBeInstanceOf(ChannelNotFoundError);
+ expect(sock.newsletterFollow).not.toHaveBeenCalled();
+ });
+
+ it('a dead socket or the no-answer shape on the lookup still propagates', async () => {
+ const connectionClosed = new Boom('Connection Closed', { statusCode: 428 });
+ const noAnswer = new Boom('Failed to newsletter metadata, unexpected response structure.', { statusCode: 400 });
+ for (const error of [connectionClosed, noAnswer]) {
+ const newsletterMetadata = jest.fn().mockRejectedValue(error);
+ await expect(channels({ newsletterMetadata }, 500).getChannelById('120363@newsletter')).rejects.toBe(error);
+ }
+ });
+
+ it("Baileys' own send timeout or a rate limit on the lookup propagates, not as 404", async () => {
+ // promiseTimeout (Utils/generics.js) rejects a stalled send with an OBJECT data and a 408 code.
+ const timedOut = new Boom('Timed Out', { statusCode: 408, data: { stack: 'Error\n at x' } });
+ for (const error of [timedOut, wmexRefusal(429)]) {
+ const newsletterMetadata = jest.fn().mockRejectedValue(error);
+ await expect(channels({ newsletterMetadata }, 500).getChannelById('120363@newsletter')).rejects.toBe(error);
+ }
+ });
+
+ it('an unanswered lookup still answers 503', async () => {
+ const newsletterMetadata = jest.fn(() => new Promise<never>(() => undefined));
+ await expect(channels({ newsletterMetadata }, 15).getChannelById('120363@newsletter')).rejects.toBeInstanceOf(
+ EngineTransportError,
+ );
+ });
+});
+
describe('what must NOT be classified as a refusal', () => {
it('a dead socket still propagates rather than becoming a 403', async () => {
const connectionClosed = new Boom('Connection Closed', { statusCode: 428 });
@@ -54,6 +106,14 @@ describe('what must NOT be classified as a refusal', () => {
await expect(channels({ newsletterDelete }, 500).deleteChannel('120363@newsletter')).rejects.toBe(connectionClosed);
});
+ it("Baileys' own send timeout still propagates rather than becoming a 403", async () => {
+ const timedOut = new Boom('Timed Out', { statusCode: 408, data: { stack: 'Error\n at x' } });
+ const newsletterUnfollow = jest.fn().mockRejectedValue(timedOut);
+ await expect(channels({ newsletterUnfollow }, 500).unsubscribeFromChannel('120363@newsletter')).rejects.toBe(
+ timedOut,
+ );
+ });
+
it('an unanswered query still answers 503, not a 403', async () => {
const newsletterDelete = jest.fn(() => new Promise<never>(() => undefined));
await expect(channels({ newsletterDelete }, 15).deleteChannel('120363@newsletter')).rejects.toBeInstanceOf(