Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): stop reporting a dead connection as a bad invite or a refusal
Yudhi Armyndharis5e66b84ba26e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bfa4bc5bb..b505e8595 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+- **A dead connection is no longer reported as a bad invite code or a permissions refusal** — joining by invite and updating participants both fail without ever entering their `catch`, because the engine resolves an unanswered query rather than rejecting it: the join landed on the same "invite code may be invalid" `400` as a genuinely bad code, and a participant update on the same `403` as a missing admin right. Both now share the request budget and answer `503`; an answered-but-empty result still means what it meant.- **Marking a chat read no longer answers a bare `500` when WhatsApp stays silent** — the read receipt reaches a library helper that destructures the query result, so an unanswered one threw a raw `TypeError` that nothing could classify; it now shares the same 30-second budget and answers `503`. The media send path fails the same way and is deliberately left alone: a send is not repeatable, and `503` is a status the SDKs retry, so making it one would trade an opaque failure for duplicate messages.- **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.diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.tsindex f5c777f56..87430a4f6 100644--- a/src/engine/adapters/baileys-groups.ts+++ b/src/engine/adapters/baileys-groups.ts@@ -186,7 +186,13 @@ export class BaileysGroups {action: 'add' | 'remove' | 'promote' | 'demote',): Promise<ParticipantOperationResult[]> {this.host.ensureReady();- const raw = await this.sock().groupParticipantsUpdate(groupId, this.toEngineParticipants(participants), action);+ // An unanswered query yields [], which the empty-results guard below would report as a refusal+ // — a dead transport sold to the caller as a permissions problem.+ const raw = await withQueryDeadline(+ this.sock().groupParticipantsUpdate(groupId, this.toEngineParticipants(participants), action),+ this.queryBudgetMs,+ `WhatsApp did not answer the participant ${action} in time`,+ );const results: ParticipantOperationResult[] = (raw ?? []).map(entry => ({id: entry.jid ? this.host.toNeutralJid(entry.jid) : '',success: entry.status === '200',@@ -299,9 +305,17 @@ export class BaileysGroups {// and rejects with an IQ error (e.g. not-authorized / gone) for the same client-facing cause.// Both map to a 400. A transport failure (dropped socket, timeout) is NOT a refused invite:// folding it into the 400 makes a dead connection look like a bad code, so it propagates.+ //+ // That guarantee needs the deadline to hold at all. An UNANSWERED query also resolves undefined+ // — it never reaches the catch — so without a clock of our own it lands on the same `if (!jid)`+ // as a genuinely bad code and answers 400, which is precisely what the paragraph above forbids.let jid: string | undefined;try {- jid = await this.sock().groupAcceptInvite(inviteCode);+ jid = await withQueryDeadline(+ this.sock().groupAcceptInvite(inviteCode),+ this.queryBudgetMs,+ 'WhatsApp did not answer the group join in time',+ );} catch (error) {const code = refusedStatusCode(error);if (code === undefined || code < 400 || code >= 500) {diff --git a/src/engine/adapters/baileys-transport-status.spec.ts b/src/engine/adapters/baileys-transport-status.spec.tsnew file mode 100644index 000000000..189988a16--- /dev/null+++ b/src/engine/adapters/baileys-transport-status.spec.ts@@ -0,0 +1,77 @@+import { Boom } from '@hapi/boom';+import type { WASocket } from '@whiskeysockets/baileys';+import { BaileysGroups, BaileysGroupsHost } from './baileys-groups';+import { EngineTransportError } from '../../common/errors/engine-transport.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';++/**+ * Two sites turn a transport fault into a CLIENT error, which is the one thing their own comments+ * say must not happen. Neither goes through a catch on the timeout path:+ *+ * - groupAcceptInvite RESOLVES undefined rather than throwing, so `if (!jid)` raises a 400 —+ * "the invite code may be invalid" — for a query that never came back.+ * - groupParticipantsUpdate yields [], so the empty-results guard raises a 403 refusal.+ */+const never = (): Promise<never> => new Promise<never>(() => undefined);++function groups(sock: Record<string, jest.Mock>, budgetMs: number): BaileysGroups {+ const host = {+ ensureReady: () => undefined,+ getSocket: () => sock as unknown as WASocket,+ logger: { warn: jest.fn(), debug: jest.fn(), info: jest.fn(), error: jest.fn() },+ toNeutralJid: (j: string) => j,+ toEngineJid: (j: string) => j,+ normalizedSelfJid: () => '[email protected]',+ } as unknown as BaileysGroupsHost;+ return new BaileysGroups(host, budgetMs);+}++describe('joinGroupViaInviteCode', () => {+ it('reports an unanswered join instead of calling the invite code invalid', async () => {+ await expect(+ groups({ groupAcceptInvite: jest.fn(never) }, 15).joinGroupViaInviteCode('CODE'),+ ).rejects.toBeInstanceOf(EngineTransportError);+ });++ it('still calls a genuinely refused invite invalid', async () => {+ const groupAcceptInvite = jest.fn().mockRejectedValue(new Boom('gone', { data: 410 }));+ await expect(groups({ groupAcceptInvite }, 500).joinGroupViaInviteCode('BAD')).rejects.toBeInstanceOf(+ InvalidInviteCodeError,+ );+ });++ it('still calls an answered-but-empty result invalid — that is a real refusal', async () => {+ const groupAcceptInvite = jest.fn().mockResolvedValue(undefined);+ await expect(groups({ groupAcceptInvite }, 500).joinGroupViaInviteCode('BAD')).rejects.toBeInstanceOf(+ InvalidInviteCodeError,+ );+ });++ it('still returns the joined group id', async () => {+ const groupAcceptInvite = jest.fn().mockResolvedValue('[email protected]');+ await expect(groups({ groupAcceptInvite }, 500).joinGroupViaInviteCode('CODE')).resolves.toBe('[email protected]');+ });+});++describe('participant updates', () => {+ it('reports an unanswered update instead of a permissions refusal', async () => {+ await expect(+ groups({ groupParticipantsUpdate: jest.fn(never) }, 15).addParticipants('[email protected]', ['[email protected]']),+ ).rejects.toBeInstanceOf(EngineTransportError);+ });++ it('still reports an answered-but-empty outcome as a refusal', async () => {+ const groupParticipantsUpdate = jest.fn().mockResolvedValue([]);+ await expect(+ groups({ groupParticipantsUpdate }, 500).addParticipants('[email protected]', ['[email protected]']),+ ).rejects.toBeInstanceOf(EngineRefusedError);+ });++ it('still maps a per-participant outcome', async () => {+ const groupParticipantsUpdate = jest.fn().mockResolvedValue([{ status: '200', jid: '[email protected]' }]);+ await expect(+ groups({ groupParticipantsUpdate }, 500).addParticipants('[email protected]', ['[email protected]']),+ ).resolves.toEqual([{ id: '[email protected]', success: true, status: 200 }]);+ });+});