Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): report an unconfirmed group or profile write instead of success
Yudhi Armyndharis7ad91636f96c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5aec83041..4de746ab5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **Twelve group and profile writes no longer report success for a change WhatsApp never confirmed** — `groupLeave`, the subject/description/settings/picture/member-add-mode/disappearing-timer writes and the three profile writes all resolve through a Baileys call that awaits its query and then discards the result, and `query()` swallows its own timeout and resolves rather than throwing, so leaving a group you are still in and locking a group that stayed open both answered `200 done`; each now has a deadline of its own and answers `503` when no confirmation arrives, which does mean a genuinely slow write that lands just after the deadline is reported as unconfirmed.- **A post-connect app-state resync can no longer spin for the life of the session** — Baileys' `resyncAppState` loops until every collection reports no more patches, but every exit from that loop, including the attempt counter its own comment introduces to "ensure we don't enter a loop that cannot be exited from", sits inside a `for…in` over the decoded patches; an unanswered query decodes to an empty object, so nothing was removed, nothing was counted, and the walk re-asked every sixty seconds until the socket closed. A postinstall patch ends the walk when the decode is empty, and fails the install rather than silently skipping if the upstream shape moves.- **A number check no longer answers "not on WhatsApp" when WhatsApp simply did not answer** — Baileys' `onWhatsApp` has no else branch after its result check, so an unanswered lookup resolved `undefined`, which the adapter folded into the same `null` a genuine miss produces; `GET /contacts/check/{number}` then reported `exists: false` and `checkNumberExists` returned false — a confident verdict about a number the gateway had heard nothing about, on the one route the send documentation tells callers to trust before sending. An empty result is still a real answer and still reports `false`; only the absent one now raises `503`.- **A group invite code now says why it could not be read** — fetching one is admin-only, but the groups list returns every group the account belongs to whatever its role, so the request lands on ids the caller was just handed: Baileys let WhatsApp's refusal escape as a bare `500` (13 of 16 groups on the test account) while whatsapp-web.js stringified its missing result into `{"inviteCode":"undefined"}` and the link `https://chat.whatsapp.com/undefined` behind a `200` (53 of 101). Both engines now answer `403`, the same status the group writes have answered since they were fixed, and an unanswered query answers `503` instead of the codeless link `https://chat.whatsapp.com/`.diff --git a/src/engine/adapters/baileys-catalog.ts b/src/engine/adapters/baileys-catalog.tsindex 49f7c7977..2ade4042a 100644--- a/src/engine/adapters/baileys-catalog.ts+++ b/src/engine/adapters/baileys-catalog.ts@@ -1,6 +1,7 @@import type { Product as BaileysProduct, WASocket } from '@whiskeysockets/baileys';import { Catalog, PaginatedProducts, Product, ProductQueryOptions } from '../interfaces/whatsapp-engine.interface';import { EngineTransportError } from '../../common/errors/engine-transport.error';+import { withQueryDeadline } from './baileys-query-deadline';import { type createLogger } from '../../common/services/logger.service';/**@@ -29,38 +30,6 @@ const CATALOG_PAGE_SIZE = 50;*/export const CATALOG_QUERY_BUDGET_MS = 30_000;-/**- * Bound one catalog query against the request's remaining budget.- *- * Baileys catches its own query timeout and resolves `undefined` rather than throwing- * (Socket/socket.js: "Catch timeout and return undefined instead of throwing"), and the catalog- * parsers are null-safe, so an unanswered IQ is byte-identical to a genuinely empty catalog. No- * inspection of the value can separate them — only a clock we own. Shape follows- * withInboundDownloadTimeout (inbound-media-cap.ts): unref'd timer, cleared in a finally, and the- * abandoned query's late rejection defused.- */-async function withDeadline<T>(work: Promise<T>, remainingMs: number): Promise<T> {- let timer: NodeJS.Timeout | undefined;- // Defuse a post-settle rejection from the query we may stop awaiting.- work.catch(() => undefined);- try {- return await Promise.race([- work,- new Promise<never>((_, reject) => {- timer = setTimeout(- () => reject(new EngineTransportError('WhatsApp did not answer the catalog query in time')),- Math.max(0, remainingMs),- );- timer.unref?.();- }),- ]);- } finally {- if (timer) {- clearTimeout(timer);- }- }-}-export class BaileysCatalog {constructor(private readonly host: BaileysCatalogHost,@@ -70,7 +39,7 @@ export class BaileysCatalog {/** Spend part of one request-wide budget on a single query, and say so when it runs out. */private async bounded<T>(work: Promise<T>, deadline: number): Promise<T> {try {- return await withDeadline(work, deadline - Date.now());+ return await withQueryDeadline(work, deadline - Date.now(), 'WhatsApp did not answer the catalog query in time');} catch (error) {if (error instanceof EngineTransportError) {// Baileys' own "timed out waiting for message" warn is silent at the defaultdiff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 719e7d5ca..1f44d7f88 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -2,6 +2,7 @@ import type { WAMessageKey, WASocket } from '@whiskeysockets/baileys';import { ChatSummary, Contact, MediaInput } from '../interfaces/whatsapp-engine.interface';import { resolveMediaBuffer } from './baileys-messaging';import { type createLogger } from '../../common/services/logger.service';+import { BAILEYS_WRITE_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';/*** Contacts/profile/chats-domain operations extracted from BaileysAdapter. The adapter keeps the@@ -25,7 +26,15 @@ export interface BaileysContactsHost {}export class BaileysContacts {- constructor(private readonly host: BaileysContactsHost) {}+ constructor(+ private readonly host: BaileysContactsHost,+ private readonly writeBudgetMs: number = BAILEYS_WRITE_BUDGET_MS,+ ) {}++ /** Bound a write whose confirmation the library discards; see baileys-query-deadline.ts. */+ private confirmed<T>(work: Promise<T>, operation: string): Promise<T> {+ return withQueryDeadline(work, this.writeBudgetMs, `WhatsApp did not confirm ${operation} in time`);+ }/** Post-ensureReady socket handle. */private sock(): WASocket {@@ -80,12 +89,12 @@ export class BaileysContacts {async setProfileName(name: string): Promise<void> {this.host.ensureReady();- await this.sock().updateProfileName(name);+ await this.confirmed(this.sock().updateProfileName(name), 'the profile name change');}async setProfileStatus(status: string): Promise<void> {this.host.ensureReady();- await this.sock().updateProfileStatus(status);+ await this.confirmed(this.sock().updateProfileStatus(status), 'the profile status change');}async setProfilePicture(media: MediaInput): Promise<void> {@@ -97,7 +106,7 @@ export class BaileysContacts {// updateProfilePicture takes a WAMediaUpload; resolveMediaBuffer covers Buffer | base64 | URL,// the same conversion the media sends use.const { data } = await resolveMediaBuffer(media);- await this.sock().updateProfilePicture(selfJid, data);+ await this.confirmed(this.sock().updateProfilePicture(selfJid, data), 'the profile picture change');}// eslint-disable-next-line @typescript-eslint/require-awaitdiff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.tsindex 162672ab6..cb841a7d7 100644--- a/src/engine/adapters/baileys-groups.ts+++ b/src/engine/adapters/baileys-groups.ts@@ -14,6 +14,7 @@ import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';import { type createLogger } from '../../common/services/logger.service';+import { BAILEYS_WRITE_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';/*** Group-domain operations extracted from BaileysAdapter. The adapter keeps the public@@ -79,7 +80,15 @@ export function toEngineParticipants(participants: string[], toEngineJid: (jid:}export class BaileysGroups {- constructor(private readonly host: BaileysGroupsHost) {}+ constructor(+ private readonly host: BaileysGroupsHost,+ private readonly writeBudgetMs: number = BAILEYS_WRITE_BUDGET_MS,+ ) {}++ /** Bound a write whose confirmation the library discards; see baileys-query-deadline.ts. */+ private confirmed<T>(work: Promise<T>, operation: string): Promise<T> {+ return withQueryDeadline(work, this.writeBudgetMs, `WhatsApp did not confirm ${operation} in time`);+ }/** Post-ensureReady socket handle. */private sock(): WASocket {@@ -176,18 +185,20 @@ export class BaileysGroups {async leaveGroup(groupId: string): Promise<void> {this.host.ensureReady();- await this.sock().groupLeave(groupId);+ await this.confirmed(this.sock().groupLeave(groupId), 'leaving the group');}async setGroupSubject(groupId: string, subject: string): Promise<void> {this.host.ensureReady();- await mapServerRefusal('Setting the group subject', () => this.sock().groupUpdateSubject(groupId, subject));+ await mapServerRefusal('Setting the group subject', () =>+ this.confirmed(this.sock().groupUpdateSubject(groupId, subject), 'the group subject change'),+ );}async setGroupDescription(groupId: string, description: string): Promise<void> {this.host.ensureReady();await mapServerRefusal('Setting the group description', () =>- this.sock().groupUpdateDescription(groupId, description),+ this.confirmed(this.sock().groupUpdateDescription(groupId, description), 'the group description change'),);}@@ -282,14 +293,20 @@ export class BaileysGroups {async setGroupMessagesAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {this.host.ensureReady();await mapServerRefusal('Setting who may send messages', () =>- this.sock().groupSettingUpdate(groupId, adminsOnly ? 'announcement' : 'not_announcement'),+ this.confirmed(+ this.sock().groupSettingUpdate(groupId, adminsOnly ? 'announcement' : 'not_announcement'),+ 'the who-may-send change',+ ),);}async setGroupInfoAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {this.host.ensureReady();await mapServerRefusal('Setting who may edit group info', () =>- this.sock().groupSettingUpdate(groupId, adminsOnly ? 'locked' : 'unlocked'),+ this.confirmed(+ this.sock().groupSettingUpdate(groupId, adminsOnly ? 'locked' : 'unlocked'),+ 'the who-may-edit change',+ ),);}@@ -297,26 +314,33 @@ export class BaileysGroups {this.host.ensureReady();// Same socket call as the own-account picture, addressed at the group JID.const { data } = await resolveMediaBuffer(media);- await mapServerRefusal('Setting the group picture', () => this.sock().updateProfilePicture(groupId, data));+ await mapServerRefusal('Setting the group picture', () =>+ this.confirmed(this.sock().updateProfilePicture(groupId, data), 'the group picture change'),+ );}async deleteGroupPicture(groupId: string): Promise<void> {this.host.ensureReady();- await mapServerRefusal('Removing the group picture', () => this.sock().removeProfilePicture(groupId));+ await mapServerRefusal('Removing the group picture', () =>+ this.confirmed(this.sock().removeProfilePicture(groupId), 'the group picture removal'),+ );}async setGroupMemberAddMode(groupId: string, mode: GroupMemberAddMode): Promise<void> {this.host.ensureReady();// A dedicated socket call, not a groupSettingUpdate option.await mapServerRefusal('Setting the member-add mode', () =>- this.sock().groupMemberAddMode(groupId, mode === 'admins' ? 'admin_add' : 'all_member_add'),+ this.confirmed(+ this.sock().groupMemberAddMode(groupId, mode === 'admins' ? 'admin_add' : 'all_member_add'),+ 'the member-add-mode change',+ ),);}async setGroupEphemeral(groupId: string, durationSec: number): Promise<void> {this.host.ensureReady();await mapServerRefusal('Setting the disappearing-message timer', () =>- this.sock().groupToggleEphemeral(groupId, durationSec),+ this.confirmed(this.sock().groupToggleEphemeral(groupId, durationSec), 'the disappearing-message timer change'),);}}diff --git a/src/engine/adapters/baileys-query-deadline.ts b/src/engine/adapters/baileys-query-deadline.tsnew file mode 100644index 000000000..832371379--- /dev/null+++ b/src/engine/adapters/baileys-query-deadline.ts@@ -0,0 +1,56 @@+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * A deadline OpenWA owns, for Baileys calls whose outcome cannot be read from their return value.+ *+ * Baileys' `query()` catches its own `defaultQueryTimeoutMs` and RESOLVES `undefined` rather than+ * throwing (Socket/socket.js: "Catch timeout and return undefined instead of throwing"). Callers+ * downstream of that split two ways:+ *+ * - those that can still tell the cases apart from the value — `onWhatsApp` resolves `undefined`+ * where a real answer is an array — and those check the value directly instead of using this;+ * - those that cannot, because the library discards the result. Every group and profile WRITE is+ * in this second group: `groupLeave`, `groupUpdateSubject`, `groupSettingUpdate` and their+ * siblings all `await groupQuery(...)` and return void, so the call resolves identically whether+ * WhatsApp confirmed the change or never answered at all.+ *+ * For the second group a clock is the only discriminator there is. Shape follows+ * `withInboundDownloadTimeout` (inbound-media-cap.ts): an unref'd timer, cleared in a `finally`,+ * and the abandoned call's late rejection defused so it cannot surface unhandled.+ *+ * Abandoning the call does NOT cancel it — the underlying query settles on Baileys' own 60s clock+ * and is discarded. That is harmless here because nothing loops on it; where an unanswered query+ * drives a loop instead (`resyncAppState`), a deadline would hide the leak rather than stop it and+ * the fix belongs in the library.+ */+export async function withQueryDeadline<T>(work: Promise<T>, timeoutMs: number, detail: string): Promise<T> {+ let timer: NodeJS.Timeout | undefined;+ // Defuse a post-settle rejection from the call we may stop awaiting.+ work.catch(() => undefined);+ try {+ return await Promise.race([+ work,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new EngineTransportError(detail)), Math.max(0, timeoutMs));+ timer.unref?.();+ }),+ ]);+ } finally {+ // clearTimeout tolerates undefined, so no guard — a guard here would be a branch no test can+ // reach, since the race always assigns the timer before it can settle.+ clearTimeout(timer);+ }+}++/**+ * Budget for a single Baileys write. Anchored to MEDIA_DOWNLOAD_TIMEOUT_MS (inbound-media-cap.ts),+ * this repo's existing figure for one bounded network round trip over WhatsApp. It must stay under+ * Baileys' 60s `defaultQueryTimeoutMs` to be observable at all, and under `session.proxyTimeoutMs`+ * so a multi-node deployment does not race two deadlines against each other.+ *+ * A WhatsApp IQ normally answers in well under a second, so reaching this means something is wrong+ * — but a genuinely slow write that succeeds just after the deadline WILL be reported as+ * unconfirmed. That is the deliberate trade: an honest "not confirmed" beats a "done" for a change+ * WhatsApp never acknowledged, and every write bounded here is safe to repeat.+ */+export const BAILEYS_WRITE_BUDGET_MS = 30_000;diff --git a/src/engine/adapters/baileys-write-deadline.spec.ts b/src/engine/adapters/baileys-write-deadline.spec.tsnew file mode 100644index 000000000..444a6ee50--- /dev/null+++ b/src/engine/adapters/baileys-write-deadline.spec.ts@@ -0,0 +1,92 @@+import type { WASocket } from '@whiskeysockets/baileys';+import { BaileysGroups, BaileysGroupsHost } from './baileys-groups';+import { BaileysContacts, BaileysContactsHost } from './baileys-contacts';+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * Every group and profile WRITE goes through a Baileys method that awaits `groupQuery`/`query` and+ * then discards the result, so the call resolves the same way whether WhatsApp confirmed the change+ * or never answered — and `query()` catches its own timeout and resolves rather than throwing.+ *+ * There is no value left to inspect, so these pin the only thing that can separate the two: a+ * deadline OpenWA owns. One case per call site, because a missed wrapper is invisible otherwise.+ */++const never = (): Promise<never> => new Promise<never>(() => undefined);+const stub = () => jest.fn(never);++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);+}++function contacts(sock: Record<string, jest.Mock>, budgetMs: number): BaileysContacts {+ const host = {+ ensureReady: () => undefined,+ getSocket: () => sock as unknown as WASocket,+ logger: { warn: jest.fn(), debug: jest.fn(), info: jest.fn(), error: jest.fn() },+ normalizedSelfJid: () => '[email protected]',+ listContacts: () => [],+ findContact: () => null,+ resolvePhone: () => null,+ listChats: () => [],+ lastMessage: () => null,+ toEngineJid: (j: string) => j,+ } as unknown as BaileysContactsHost;+ return new BaileysContacts(host, budgetMs);+}++const PNG = { mimetype: 'image/png', data: Buffer.from('x') };++describe('group writes report an unconfirmed write rather than success', () => {+ it.each([+ ['leaveGroup', 'groupLeave', (g: BaileysGroups) => g.leaveGroup('[email protected]')],+ ['setGroupSubject', 'groupUpdateSubject', (g: BaileysGroups) => g.setGroupSubject('[email protected]', 'X')],+ ['setGroupDescription', 'groupUpdateDescription', (g: BaileysGroups) => g.setGroupDescription('[email protected]', 'X')],+ [+ 'setGroupMessagesAdminsOnly',+ 'groupSettingUpdate',+ (g: BaileysGroups) => g.setGroupMessagesAdminsOnly('[email protected]', true),+ ],+ ['setGroupInfoAdminsOnly', 'groupSettingUpdate', (g: BaileysGroups) => g.setGroupInfoAdminsOnly('[email protected]', true)],+ ['setGroupPicture', 'updateProfilePicture', (g: BaileysGroups) => g.setGroupPicture('[email protected]', PNG)],+ ['deleteGroupPicture', 'removeProfilePicture', (g: BaileysGroups) => g.deleteGroupPicture('[email protected]')],+ [+ 'setGroupMemberAddMode',+ 'groupMemberAddMode',+ (g: BaileysGroups) => g.setGroupMemberAddMode('[email protected]', 'admins'),+ ],+ ['setGroupEphemeral', 'groupToggleEphemeral', (g: BaileysGroups) => g.setGroupEphemeral('[email protected]', 604800)],+ ])('%s', async (_name, sockMethod, call) => {+ await expect(call(groups({ [sockMethod]: stub() }, 15))).rejects.toBeInstanceOf(EngineTransportError);+ });++ it('still resolves when WhatsApp answers inside the budget', async () => {+ const groupLeave = jest.fn().mockResolvedValue(undefined);+ await expect(groups({ groupLeave }, 500).leaveGroup('[email protected]')).resolves.toBeUndefined();+ expect(groupLeave).toHaveBeenCalledWith('[email protected]');+ });+});++describe('profile writes report an unconfirmed write rather than success', () => {+ it.each([+ ['setProfileName', 'updateProfileName', (c: BaileysContacts) => c.setProfileName('Ada')],+ ['setProfileStatus', 'updateProfileStatus', (c: BaileysContacts) => c.setProfileStatus('busy')],+ ['setProfilePicture', 'updateProfilePicture', (c: BaileysContacts) => c.setProfilePicture(PNG)],+ ])('%s', async (_name, sockMethod, call) => {+ await expect(call(contacts({ [sockMethod]: stub() }, 15))).rejects.toBeInstanceOf(EngineTransportError);+ });++ it('still resolves when WhatsApp answers inside the budget', async () => {+ const updateProfileName = jest.fn().mockResolvedValue(undefined);+ await expect(contacts({ updateProfileName }, 500).setProfileName('Ada')).resolves.toBeUndefined();+ expect(updateProfileName).toHaveBeenCalledWith('Ada');+ });+});