Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): map server-refused group and channel writes to their documented statuses

Yudhi Armyndharis80398e6d889c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5f3995385..408ad004d 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
- A media-storage root the app cannot write to is caught at boot with a clear error, instead of failing on the first write (#1066).
- The bundled `docker-compose.yml` now forwards the `SEND_PACING_*`, `MEDIA_CONVERSION_*`/`FFMPEG_PATH` and session-ownership (`NODE_ID`, `NODE_URL`, lease/sweep) variables — previously these features could not be enabled from `.env` in a compose deployment at all.
- The four label write tools (`LabelUpsert`, `LabelDelete`, `LabelAddToChat`, `LabelRemoveFromChat`) answered `Internal error` over MCP even though the write had succeeded on WhatsApp, prompting agents to retry a completed operation; they now return `{ success: true }`.
+- **Baileys refusals now answer their documented statuses instead of 500:** an invalid/expired group invite previews as 404, admin-refused group writes (subject, description, announce/locked, picture, member-add mode) and refused channel writes (create/delete/mute) answer 403 — matching the whatsapp-web.js engine. Transport failures still propagate unchanged.
- **Multi-node request routing hardening:** forwarded requests now carry the client address in `x-forwarded-for` (so `allowedIps` keys and per-IP throttling see the real client once peer nodes are listed in `TRUSTED_PROXIES`), a malformed session id no longer 500s on Postgres in routed mode, and the client-settable forwarded marker is verified — a marked request landing on a live non-owner answers 409 instead of executing there.
- **Send pacing accounting:** forwards now pass through the cold-reachout gate (they were ungated while still draining the budget), replying to someone who wrote first today no longer spends the cold budget, and a pacing 429 inside a bulk batch is recorded as `SEND_PACING_LIMITED` instead of a generic `SEND_FAILED`.
- **Multi-node: a session claim could outlive its engine and pin the session to one node forever.** A failed start, a logout, a force-kill or an exhausted reconnect kept the ownership claim, and the heartbeat renewed it indefinitely — the session could not be started on any peer and the takeover sweep never saw it. Claims are now released on every teardown path, and the heartbeat only renews claims that still cover a live engine, an in-flight start or a pending reconnect. Starting a nonexistent session also answers 404 again instead of a misleading 409 "running on another node".
diff --git a/src/engine/adapters/baileys-channels.ts b/src/engine/adapters/baileys-channels.ts
index d198fdecc..738b53964 100644
--- a/src/engine/adapters/baileys-channels.ts
+++ b/src/engine/adapters/baileys-channels.ts
@@ -1,6 +1,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';
/**
* Channel-domain operations extracted from BaileysAdapter. The adapter keeps the public
@@ -40,18 +41,20 @@ export class BaileysChannels {
async createChannel(name: string, description?: string): Promise<Channel> {
this.host.ensureReady();
- const meta = await this.sock().newsletterCreate(name, description);
+ const meta = await mapServerRefusal('Creating the channel', () => this.sock().newsletterCreate(name, description));
return this.toChannel(meta);
}
async deleteChannel(channelId: string): Promise<void> {
this.host.ensureReady();
- await this.sock().newsletterDelete(channelId);
+ await mapServerRefusal('Deleting the channel', () => this.sock().newsletterDelete(channelId));
}
async muteChannel(channelId: string, mute: boolean): Promise<void> {
this.host.ensureReady();
- await (mute ? this.sock().newsletterMute(channelId) : this.sock().newsletterUnmute(channelId));
+ await mapServerRefusal(mute ? 'Muting the channel' : 'Unmuting the channel', () =>
+ mute ? this.sock().newsletterMute(channelId) : this.sock().newsletterUnmute(channelId),
+ );
}
async unsubscribeFromChannel(channelId: string): Promise<void> {
diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.ts
index e534f228b..d8e8df6f8 100644
--- a/src/engine/adapters/baileys-groups.ts
+++ b/src/engine/adapters/baileys-groups.ts
@@ -48,6 +48,27 @@ export function refusedStatusCode(error: unknown): number | undefined {
return undefined;
}
+/**
+ * Run a socket write and map a SERVER refusal (a 4xx-class WA code: admin rights missing, not
+ * permitted, not acceptable) to EngineRefusedError — HTTP 403, the same status the whatsapp-web.js
+ * adapter gives these causes — instead of letting the raw Boom escape as a 500. Transport/local
+ * failures (dropped socket, timeout) propagate untouched: folding them in would report a dead
+ * connection as a permissions problem.
+ */
+export async function mapServerRefusal<T>(operation: string, op: () => Promise<T>): Promise<T> {
+ try {
+ return await op();
+ } catch (error) {
+ const code = refusedStatusCode(error);
+ if (code !== undefined && code >= 400 && code < 500) {
+ throw new EngineRefusedError(
+ `${operation} was refused by WhatsApp (code ${code}) — admin rights or permissions may be missing`,
+ );
+ }
+ throw error;
+ }
+}
+
/**
* Fold neutral `<phone>@c.us` participant ids back to the engine wire dialect (`@s.whatsapp.net`) before
* a group write. `@lid` (a first-class addressing mode) and the group id itself are left untouched.
@@ -159,12 +180,14 @@ export class BaileysGroups {
async setGroupSubject(groupId: string, subject: string): Promise<void> {
this.host.ensureReady();
- await this.sock().groupUpdateSubject(groupId, subject);
+ await mapServerRefusal('Setting the group subject', () => this.sock().groupUpdateSubject(groupId, subject));
}
async setGroupDescription(groupId: string, description: string): Promise<void> {
this.host.ensureReady();
- await this.sock().groupUpdateDescription(groupId, description);
+ await mapServerRefusal('Setting the group description', () =>
+ this.sock().groupUpdateDescription(groupId, description),
+ );
}
async getGroupInviteCode(groupId: string): Promise<string> {
@@ -187,7 +210,18 @@ export class BaileysGroups {
*/
async getGroupJoinInfo(inviteCode: string): Promise<GroupJoinInfo> {
this.host.ensureReady();
- const meta = await this.sock().groupGetInviteInfo(inviteCode);
+ let meta: Awaited<ReturnType<WASocket['groupGetInviteInfo']>>;
+ try {
+ meta = await this.sock().groupGetInviteInfo(inviteCode);
+ } catch (error) {
+ // Baileys throws a Boom carrying the WA code for an invalid/expired/revoked invite — the
+ // route's documented 404 (matching whatsapp-web.js), not a 500. Transport failures propagate.
+ const code = refusedStatusCode(error);
+ if (code !== undefined && code >= 400 && code < 500) {
+ throw new GroupNotFoundError(inviteCode);
+ }
+ throw error;
+ }
if (!meta?.id) {
throw new GroupNotFoundError(inviteCode);
}
@@ -230,30 +264,36 @@ export class BaileysGroups {
async setGroupMessagesAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {
this.host.ensureReady();
- await this.sock().groupSettingUpdate(groupId, adminsOnly ? 'announcement' : 'not_announcement');
+ await mapServerRefusal('Setting who may send messages', () =>
+ this.sock().groupSettingUpdate(groupId, adminsOnly ? 'announcement' : 'not_announcement'),
+ );
}
async setGroupInfoAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {
this.host.ensureReady();
- await this.sock().groupSettingUpdate(groupId, adminsOnly ? 'locked' : 'unlocked');
+ await mapServerRefusal('Setting who may edit group info', () =>
+ this.sock().groupSettingUpdate(groupId, adminsOnly ? 'locked' : 'unlocked'),
+ );
}
async setGroupPicture(groupId: string, media: MediaInput): Promise<void> {
this.host.ensureReady();
// Same socket call as the own-account picture, addressed at the group JID.
const { data } = await resolveMediaBuffer(media);
- await this.sock().updateProfilePicture(groupId, data);
+ await mapServerRefusal('Setting the group picture', () => this.sock().updateProfilePicture(groupId, data));
}
async deleteGroupPicture(groupId: string): Promise<void> {
this.host.ensureReady();
- await this.sock().removeProfilePicture(groupId);
+ await mapServerRefusal('Removing the group picture', () => this.sock().removeProfilePicture(groupId));
}
async setGroupMemberAddMode(groupId: string, mode: GroupMemberAddMode): Promise<void> {
this.host.ensureReady();
// A dedicated socket call, not a groupSettingUpdate option.
- await this.sock().groupMemberAddMode(groupId, mode === 'admins' ? 'admin_add' : 'all_member_add');
+ await mapServerRefusal('Setting the member-add mode', () =>
+ this.sock().groupMemberAddMode(groupId, mode === 'admins' ? 'admin_add' : 'all_member_add'),
+ );
}
async setGroupEphemeral(groupId: string, durationSec: number): Promise<void> {
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 9cc32a088..35e772342 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -44,6 +44,8 @@ class FakeSock extends EventEmitter {
public groupAcceptInvite = jest.fn();
public groupSettingUpdate = jest.fn().mockResolvedValue(undefined);
public groupToggleEphemeral = jest.fn().mockResolvedValue(undefined);
+ public groupGetInviteInfo = jest.fn();
+ public groupMemberAddMode = jest.fn().mockResolvedValue(undefined);
public profilePictureUrl = jest.fn();
public updateProfileName = jest.fn().mockResolvedValue(undefined);
public updateProfileStatus = jest.fn().mockResolvedValue(undefined);
@@ -138,6 +140,7 @@ import { MessageNotFoundError } from '../../common/errors/message-not-found.erro
import { CallNotFoundError } from '../../common/errors/call-not-found.error';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';
+import { GroupNotFoundError } from '../../common/errors/group-not-found.error';
import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';
import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';
@@ -2988,6 +2991,81 @@ describe('BaileysAdapter group management', () => {
await expect(adapter.joinGroupViaInviteCode('CODE123')).rejects.toBe(connectionClosed);
});
+ it('getGroupJoinInfo maps the preview fields, neutralizing ids', async () => {
+ fakeSock.groupGetInviteInfo.mockResolvedValue({
+ subject: 'Preview me',
+ desc: 'About us',
+ owner: '[email protected]',
+ creation: 1720000000,
+ size: 12,
+ });
+ const adapter = await ready();
+ await expect(adapter.getGroupJoinInfo('CODE123')).resolves.toEqual({
+ name: 'Preview me',
+ description: 'About us',
+ owner: '[email protected]',
+ createdAt: 1720000000,
+ participantCount: 12,
+ });
+ });
+
+ it('getGroupJoinInfo maps a refused invite to GroupNotFoundError (404), not a raw Boom 500', async () => {
+ // The vendored extractGroupMetadata throws a Boom carrying the WA code for an invalid/expired
+ // invite; whatsapp-web.js answers the same cause with a 404, and the route documents 404.
+ fakeSock.groupGetInviteInfo.mockRejectedValue(Object.assign(new Error('item-not-found'), { data: 404 }));
+ const adapter = await ready();
+ await expect(adapter.getGroupJoinInfo('BAD')).rejects.toBeInstanceOf(GroupNotFoundError);
+ });
+
+ it('getGroupJoinInfo lets a transport death propagate — a dead socket is not a bad invite', async () => {
+ const connectionClosed = Object.assign(new Error('Connection Closed'), { output: { statusCode: 428 } });
+ fakeSock.groupGetInviteInfo.mockRejectedValue(connectionClosed);
+ const adapter = await ready();
+ await expect(adapter.getGroupJoinInfo('CODE123')).rejects.toBe(connectionClosed);
+ });
+
+ // The raw Boom used to escape as a 500 on every admin-refused group write, while the controller
+ // documents 403 and the whatsapp-web.js adapter answers 403 for the same causes.
+ it.each([
+ ['setGroupSubject', (a: BaileysAdapter) => a.setGroupSubject('[email protected]', 'X'), 'groupUpdateSubject'],
+ [
+ 'setGroupDescription',
+ (a: BaileysAdapter) => a.setGroupDescription('[email protected]', 'X'),
+ 'groupUpdateDescription',
+ ],
+ [
+ 'setGroupMessagesAdminsOnly',
+ (a: BaileysAdapter) => a.setGroupMessagesAdminsOnly('[email protected]', true),
+ 'groupSettingUpdate',
+ ],
+ [
+ 'setGroupInfoAdminsOnly',
+ (a: BaileysAdapter) => a.setGroupInfoAdminsOnly('[email protected]', true),
+ 'groupSettingUpdate',
+ ],
+ ['deleteGroupPicture', (a: BaileysAdapter) => a.deleteGroupPicture('[email protected]'), 'removeProfilePicture'],
+ [
+ 'setGroupMemberAddMode',
+ (a: BaileysAdapter) => a.setGroupMemberAddMode('[email protected]', 'admins'),
+ 'groupMemberAddMode',
+ ],
+ ])('%s maps an admin-refused write to EngineRefusedError (403)', async (_name, call, sockMethod) => {
+ (fakeSock as unknown as Record<string, jest.Mock>)[sockMethod].mockRejectedValueOnce(
+ Object.assign(new Error('not-authorized'), { data: 401 }),
+ );
+ const adapter = await ready();
+ await expect(call(adapter)).rejects.toBeInstanceOf(EngineRefusedError);
+ });
+
+ it('a transport death on a group write propagates untouched — not folded into a 403', async () => {
+ const connectionClosed = Object.assign(new Error('Connection Closed'), { output: { statusCode: 428 } });
+ fakeSock.groupUpdateSubject.mockRejectedValueOnce(connectionClosed);
+ const adapter = await ready();
+ await expect(adapter.setGroupSubject('[email protected]', 'X')).rejects.toBe(connectionClosed);
+ });
+
it('addParticipants maps the per-participant [{status, jid}] array — a partial refusal does not throw', async () => {
fakeSock.groupParticipantsUpdate.mockResolvedValueOnce([
{ status: '200', jid: '[email protected]', content: {} },
@@ -4557,6 +4635,19 @@ describe('BaileysAdapter channel administration', () => {
await adapter.muteChannel(CHANNEL, false);
expect(fakeSock.newsletterUnmute).toHaveBeenCalledWith(CHANNEL);
});
+
+ // The raw Boom from executeWMexQuery used to escape as a 500 on every refused channel write.
+ it.each([
+ ['createChannel', (a: BaileysAdapter) => a.createChannel('X'), 'newsletterCreate'],
+ ['deleteChannel', (a: BaileysAdapter) => a.deleteChannel(CHANNEL), 'newsletterDelete'],
+ ['muteChannel', (a: BaileysAdapter) => a.muteChannel(CHANNEL, true), 'newsletterMute'],
+ ])('%s maps a server refusal to EngineRefusedError (403)', async (_name, call, sockMethod) => {
+ (fakeSock as unknown as Record<string, jest.Mock>)[sockMethod].mockRejectedValueOnce(
+ Object.assign(new Error('not-authorized'), { data: 401 }),
+ );
+ const adapter = await readyAdapter();
+ await expect(call(adapter)).rejects.toBeInstanceOf(EngineRefusedError);
+ });
});
// The load-bearing risk here is an ended call re-entering the incoming-call path: a decline would