Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): bound the last writes the library leaves unconfirmed
Yudhi Armyndharisc9115f71c676
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b505e8595..3e7786e7b 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+- **The last fifteen writes that reported success without confirmation now report it** — the addressbook saves, block and unblock, the archive/unread/clear/delete chat actions, delete-for-me and star, the four label writes and a call rejection all go through an engine call that discards its own result, so each answered `200` whether WhatsApp applied the change or never replied; a rejected call was the sharpest case, since the gateway also published a `rejected` outcome for a rejection nothing had acknowledged. All now share the request budget and answer `503` when no confirmation arrives.- **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`.diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex cb9b120bd..d21611df9 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -64,27 +64,30 @@ export class BaileysContacts {// chatModify keys the addressbook app-state patch by the raw jid (no jidNormalizedUser, unlike// the send path), so a raw @c.us index would land under a key WhatsApp never reads and the// write would silently target nothing while the endpoint reports success.- await this.sock().addOrEditContact(this.host.toEngineJid(contactId), {- firstName,- fullName,- saveOnPrimaryAddressbook: false,- });+ await this.confirmed(+ this.sock().addOrEditContact(this.host.toEngineJid(contactId), {+ firstName,+ fullName,+ saveOnPrimaryAddressbook: false,+ }),+ 'the contact save',+ );}async deleteContact(contactId: string): Promise<void> {this.host.ensureReady();// Same app-state key fold as upsertContact — a raw @c.us removal targets a phantom entry.- await this.sock().removeContact(this.host.toEngineJid(contactId));+ await this.confirmed(this.sock().removeContact(this.host.toEngineJid(contactId)), 'the contact removal');}async blockContact(contactId: string): Promise<void> {this.host.ensureReady();- await this.sock().updateBlockStatus(contactId, 'block');+ await this.confirmed(this.sock().updateBlockStatus(contactId, 'block'), 'the block');}async unblockContact(contactId: string): Promise<void> {this.host.ensureReady();- await this.sock().updateBlockStatus(contactId, 'unblock');+ await this.confirmed(this.sock().updateBlockStatus(contactId, 'unblock'), 'the unblock');}async setProfileName(name: string): Promise<void> {@@ -152,9 +155,12 @@ export class BaileysContacts {if (!last) {return false; // Baileys' unread toggle needs the last message; can't synthesize it}- await this.sock().chatModify(- { markRead: false, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },- this.host.toEngineJid(chatId),+ await this.confirmed(+ this.sock().chatModify(+ { markRead: false, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },+ this.host.toEngineJid(chatId),+ ),+ 'the unread mark',);return true;}@@ -165,9 +171,12 @@ export class BaileysContacts {if (!last) {return false; // Baileys' clear needs the last message; can't synthesize it}- await this.sock().chatModify(- { clear: true, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },- this.host.toEngineJid(chatId),+ await this.confirmed(+ this.sock().chatModify(+ { clear: true, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },+ this.host.toEngineJid(chatId),+ ),+ 'the chat clear',);return true;}@@ -178,9 +187,12 @@ export class BaileysContacts {if (!last) {return false; // Baileys' archive toggle needs the last message; can't synthesize it}- await this.sock().chatModify(- { archive, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },- this.host.toEngineJid(chatId),+ await this.confirmed(+ this.sock().chatModify(+ { archive, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },+ this.host.toEngineJid(chatId),+ ),+ 'the archive change',);return true;}@@ -191,9 +203,12 @@ export class BaileysContacts {if (!last) {return false; // Baileys' delete needs the last message; can't synthesize it}- await this.sock().chatModify(- { delete: true, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },- this.host.toEngineJid(chatId),+ await this.confirmed(+ this.sock().chatModify(+ { delete: true, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },+ this.host.toEngineJid(chatId),+ ),+ 'the chat delete',);return true;}diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex 6c5e190ac..d8ebdf674 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -34,6 +34,7 @@ import {import type { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';import { type createLogger } from '../../common/services/logger.service';import { createSilentLogger } from './baileys-logger';+import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';/*** Inbound event handling extracted from BaileysAdapter: the socket event handlers@@ -616,7 +617,11 @@ export class BaileysEvents {if (!sock) {throw new EngineNotReadyError('Cannot reject a call before the engine is initialized.');}- await sock.rejectCall(callId, entry.callFrom);+ await withQueryDeadline(+ sock.rejectCall(callId, entry.callFrom),+ BAILEYS_QUERY_BUDGET_MS,+ 'WhatsApp did not confirm the call rejection in time',+ );// A rejection made HERE produces no inbound `reject` signal to observe, so without this the// one outcome the caller definitely knows about — the one they asked for — was the only one// never published. Emitted only after the socket accepted it, and the entry is already evicted,diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex 0c4aa8ad5..ec2766263 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -21,6 +21,7 @@ import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { MessageNotFoundError } from '../../common/errors/message-not-found.error';import { type createLogger } from '../../common/services/logger.service';import { EngineTransportError } from '../../common/errors/engine-transport.error';+import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';/*** Messaging-domain operations extracted from BaileysAdapter. The adapter keeps the public@@ -75,7 +76,15 @@ export async function resolveMediaBuffer(media: MediaInput): Promise<{ data: Buf}export class BaileysMessaging {- constructor(private readonly host: BaileysMessagingHost) {}+ constructor(+ private readonly host: BaileysMessagingHost,+ private readonly queryBudgetMs: number = BAILEYS_QUERY_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.queryBudgetMs, `WhatsApp did not confirm ${operation} in time`);+ }/** Post-ensureReady socket handle. */private sock(): WASocket {@@ -323,15 +332,18 @@ export class BaileysMessaging {}// Delete-for-me (revoke on this device only): Baileys exposes it as a chat modification, not a// sendMessage. The stored message timestamp (epoch seconds) is part of the payload.- await this.sock().chatModify(- {- deleteForMe: {- deleteMedia: true,- key: target.key,- timestamp: this.host.toUnixSeconds(target.messageTimestamp),+ await this.confirmed(+ this.sock().chatModify(+ {+ deleteForMe: {+ deleteMedia: true,+ key: target.key,+ timestamp: this.host.toUnixSeconds(target.messageTimestamp),+ },},- },- this.host.toEngineJid(chatId),+ this.host.toEngineJid(chatId),+ ),+ 'the delete-for-me',);}@@ -489,9 +501,12 @@ export class BaileysMessaging {// Fold @c.us -> @s.whatsapp.net: chatModify keys the star app-state index by the raw jid (no// jidNormalizedUser, unlike the send path), so a neutral @c.us would index a phantom chat and// the star would silently apply to nothing on a 1:1 conversation.- await this.sock().chatModify(- { star: { messages: [{ id: target.key.id!, fromMe: target.key.fromMe ?? false }], star } },- this.host.toEngineJid(chatId),+ await this.confirmed(+ this.sock().chatModify(+ { star: { messages: [{ id: target.key.id!, fromMe: target.key.fromMe ?? false }], star } },+ this.host.toEngineJid(chatId),+ ),+ 'the star change',);}diff --git a/src/engine/adapters/baileys-remaining-writes.spec.ts b/src/engine/adapters/baileys-remaining-writes.spec.tsnew file mode 100644index 000000000..c5d6cd3e7--- /dev/null+++ b/src/engine/adapters/baileys-remaining-writes.spec.ts@@ -0,0 +1,79 @@+import type { WASocket } from '@whiskeysockets/baileys';+import { BaileysContacts, BaileysContactsHost } from './baileys-contacts';+import { BaileysMessaging, BaileysMessagingHost } from './baileys-messaging';+import { EngineTransportError } from '../../common/errors/engine-transport.error';++/**+ * The last group of writes whose confirmation the library discards. Same reasoning as the group and+ * profile writes: `chatModify`, the addressbook writes and the block toggles all await a query and+ * return void, so the call resolves identically whether WhatsApp applied the change or never+ * answered. One case per call site — a missing wrapper is invisible any other way.+ */+const never = (): Promise<never> => new Promise<never>(() => undefined);+const stub = () => jest.fn(never);+const LAST = { key: { id: 'M1', remoteJid: '[email protected]' }, timestamp: 1 };++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: () => LAST,+ toEngineJid: (j: string) => j,+ } as unknown as BaileysContactsHost;+ return new BaileysContacts(host, budgetMs);+}++function messaging(sock: Record<string, jest.Mock>, budgetMs: number): BaileysMessaging {+ 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]',+ getEphemeralExpiration: () => undefined,+ toUnixSeconds: () => 1,+ loadLib: () => Promise.resolve({} as never),+ getStoredMessage: () => Promise.resolve({ key: { ...LAST.key, fromMe: true }, message: {}, messageTimestamp: 1 }),+ putStoredMessage: () => undefined,+ recordLidMapping: () => undefined,+ getOnMessageCreate: () => undefined,+ mapMessage: () => Promise.resolve({} as never),+ } as unknown as BaileysMessagingHost;+ return new BaileysMessaging(host, budgetMs);+}++describe('contact and chat-state writes report an unconfirmed write', () => {+ it.each([+ ['upsertContact', 'addOrEditContact', (c: BaileysContacts) => c.upsertContact('[email protected]', 'Ada')],+ ['deleteContact', 'removeContact', (c: BaileysContacts) => c.deleteContact('[email protected]')],+ ['blockContact', 'updateBlockStatus', (c: BaileysContacts) => c.blockContact('[email protected]')],+ ['unblockContact', 'updateBlockStatus', (c: BaileysContacts) => c.unblockContact('[email protected]')],+ ['markUnread', 'chatModify', (c: BaileysContacts) => c.markUnread('[email protected]')],+ ['clearChatMessages', 'chatModify', (c: BaileysContacts) => c.clearChatMessages('[email protected]')],+ ['archiveChat', 'chatModify', (c: BaileysContacts) => c.archiveChat('[email protected]', true)],+ ['deleteChat', 'chatModify', (c: BaileysContacts) => c.deleteChat('[email protected]')],+ ])('%s', async (_n, method, call) => {+ await expect(call(contacts({ [method]: stub() }, 15))).rejects.toBeInstanceOf(EngineTransportError);+ });++ it('still resolves when WhatsApp answers inside the budget', async () => {+ const updateBlockStatus = jest.fn().mockResolvedValue(undefined);+ await expect(contacts({ updateBlockStatus }, 500).blockContact('[email protected]')).resolves.toBeUndefined();+ });+});++describe('message chat-state writes report an unconfirmed write', () => {+ it.each([+ ['deleteMessage (for me)', (m: BaileysMessaging) => m.deleteMessage('[email protected]', 'M1', false)],+ ['starMessage', (m: BaileysMessaging) => m.starMessage('[email protected]', 'M1', true)],+ ])('%s', async (_n, call) => {+ await expect(call(messaging({ chatModify: stub() }, 15))).rejects.toBeInstanceOf(EngineTransportError);+ });+});diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex be022f261..c927a521d 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -49,6 +49,7 @@ import { BaileysAdapterConfig } from '../types/baileys.types';import { BaileysSessionStore } from './baileys-session-store';import { inboundMediaConcurrency } from './inbound-media-cap';import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';+import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';// The implementation moved with connectInner to BaileysLifecycle; it remains part of this module's// public surface (imported from './baileys.adapter' by the spec).@@ -577,11 +578,19 @@ export class BaileysAdapter implements IWhatsAppEngine {// reads — reported as success. Same class of no-op the deleteForMe/star folds fixed.async addLabelToChat(chatId: string, labelId: string): Promise<void> {this.ensureReady();- await this.sock!.addChatLabel(this.sessionStore.toEngineJid(chatId), labelId);+ await withQueryDeadline(+ this.sock!.addChatLabel(this.sessionStore.toEngineJid(chatId), labelId),+ BAILEYS_QUERY_BUDGET_MS,+ 'WhatsApp did not confirm the chat label add in time',+ );}async removeLabelFromChat(chatId: string, labelId: string): Promise<void> {this.ensureReady();- await this.sock!.removeChatLabel(this.sessionStore.toEngineJid(chatId), labelId);+ await withQueryDeadline(+ this.sock!.removeChatLabel(this.sessionStore.toEngineJid(chatId), labelId),+ BAILEYS_QUERY_BUDGET_MS,+ 'WhatsApp did not confirm the chat label removal in time',+ );}/*** Create or update a label.@@ -601,13 +610,21 @@ export class BaileysAdapter implements IWhatsAppEngine {// LabelEditAction.encode), so an omitted name really does leave the stored name alone. Colour 0// is a real WhatsApp colour and survives that check — which is why it must never be tested for// truthiness on the way here.- await this.sock!.addLabel(this.ownJidForAppState(), { id: label.id, name: label.name, color: label.color });+ await withQueryDeadline(+ this.sock!.addLabel(this.ownJidForAppState(), { id: label.id, name: label.name, color: label.color }),+ BAILEYS_QUERY_BUDGET_MS,+ 'WhatsApp did not confirm the label save in time',+ );}/** Delete a label. The same `label_edit` write, with the tombstone flag set. */async deleteLabel(labelId: string): Promise<void> {this.ensureReady();- await this.sock!.addLabel(this.ownJidForAppState(), { id: labelId, deleted: true });+ await withQueryDeadline(+ this.sock!.addLabel(this.ownJidForAppState(), { id: labelId, deleted: true }),+ BAILEYS_QUERY_BUDGET_MS,+ 'WhatsApp did not confirm the label delete in time',+ );}/**