Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): keep receipt lookups on one socket
Yudhi Armyndharis86b79ddc7513
diff --git a/src/engine/adapters/baileys-contacts-identity.spec.ts b/src/engine/adapters/baileys-contacts-identity.spec.tsindex 5b2a46692..9b61bfb5e 100644--- a/src/engine/adapters/baileys-contacts-identity.spec.ts+++ b/src/engine/adapters/baileys-contacts-identity.spec.ts@@ -33,6 +33,70 @@ class User {}}+describe.each(['stored read', 'next key'] as const)('Read receipt identity after %s', phase => {+ it.each(['unchanged', 'retired', 'replaced'] as const)('keeps preparation on the %s socket', async state => {+ let release!: () => void;+ let entered!: () => void;+ const started = new Promise<void>(resolve => {+ entered = resolve;+ });+ const gate = new Promise<void>(resolve => {+ release = resolve;+ });+ const result = (lid: string) => ({ list: [{ id: '[email protected]', lid }] });+ const makeSocket = () => ({+ executeUSyncQuery: jest.fn().mockResolvedValue(result('222@lid')),+ readMessages: jest.fn().mockResolvedValue(undefined),+ });+ const first = makeSocket();+ first.executeUSyncQuery.mockResolvedValueOnce(result('111@lid'));+ const replacement = makeSocket();+ let current: typeof first | null = first;+ const changeSocket = () => {+ if (state === 'retired') current = null;+ if (state === 'replaced') current = replacement;+ };+ const recordLidMapping = jest.fn(() => {+ if (phase === 'next key') changeSocket();+ });+ const host = {+ ensureReady: () => undefined,+ getSocket: () => {+ if (!current) throw new EngineNotReadyError();+ return current as unknown as WASocket;+ },+ loadLib: () => Promise.resolve({ USyncQuery: Query, USyncUser: User }),+ getStoredMessages: async () => {+ if (phase === 'stored read') {+ entered();+ await gate;+ }+ return ['111', '222'].map((lid, i) => ({+ key: { id: `M${i + 1}`, remoteJid: `${lid}@lid`, fromMe: false },+ }));+ },+ findPersistedLidPhone: () => Promise.resolve(null),+ recordLidMapping,+ toEngineJid: (jid: string) => jid.replace('@c.us', '@s.whatsapp.net'),+ } as unknown as BaileysContactsHost;+ const pending = new BaileysContacts(host).sendSeen('[email protected]', ['M1', 'M2']).catch((error: unknown) => error);+ if (phase === 'stored read') {+ await started;+ changeSocket();+ release();+ }+ const outcome: unknown = await pending;+ if (state === 'unchanged') expect(outcome).toBe(true);+ else expect(outcome).toBeInstanceOf(EngineNotReadyError);+ const reports = state === 'unchanged' ? 2 : phase === 'next key' ? 1 : 0;+ expect(recordLidMapping).toHaveBeenCalledTimes(reports);+ expect(first.executeUSyncQuery).toHaveBeenCalledTimes(reports);+ expect(replacement.executeUSyncQuery).not.toHaveBeenCalled();+ expect(first.readMessages).toHaveBeenCalledTimes(state === 'unchanged' ? 1 : 0);+ expect(replacement.readMessages).not.toHaveBeenCalled();+ });+});+describe.each(['persisted', 'fresh', 'library'] as const)('Chat identity prepared through %s mapping', source => {it.each(operations)('does not carry %s across a socket replacement', async (_name, act) => {let release!: () => void;diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 3c2ce314a..efeece4a1 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -386,7 +386,7 @@ export class BaileysContacts {async sendSeen(chatId: string, messageIds?: string[], authors?: ReadonlyMap<string, string>): Promise<boolean> {this.host.ensureReady();const socket = this.sock();- const keys = await this.receiptKeys(chatId, messageIds, authors);+ const keys = await this.receiptKeys(socket, chatId, messageIds, authors);if (keys.length === 0) {return false; // nothing known to mark read}@@ -418,6 +418,7 @@ export class BaileysContacts {* the receipt rather than sent as one WhatsApp may ignore.*/private async receiptKeys(+ socket: WASocket,chatId: string,messageIds?: string[],authors?: ReadonlyMap<string, string>,@@ -428,7 +429,7 @@ export class BaileysContacts {// The newest RECEIVED message, not the preview: after an API reply the preview is an own key,// which Baileys drops from the receipt, so the call would answer true having sent nothing.const last = this.host.lastInboundMessage(chatId);- return last && (await this.matchesChat(last.key, chatId)) ? [last.key] : [];+ return last && (await this.matchesChat(last.key, chatId, socket)) ? [last.key] : [];}if (messageIds.length === 0) {return []; // an explicit empty list asks for nothing to be acknowledged, not for the newest@@ -446,7 +447,7 @@ export class BaileysContacts {// chat, which is exactly what every id ran on before stored keys existed.const keyById = new Map<string, WAMessageKey>();for (const msg of stored) {- if (msg.key?.id && msg.key.remoteJid && (await this.matchesChat(msg.key, chatId))) {+ if (msg.key?.id && msg.key.remoteJid && (await this.matchesChat(msg.key, chatId, socket))) {keyById.set(msg.key.id, msg.key);}}@@ -460,8 +461,8 @@ export class BaileysContacts {});}- private async matchesChat(key: WAMessageKey, chatId: string): Promise<boolean> {- const socket = this.sock();+ private async matchesChat(key: WAMessageKey, chatId: string, expected?: WASocket): Promise<boolean> {+ const socket = this.sock(expected);const persisted = await storedKeyInChatPersisted(key, chatId, jid => this.host.findPersistedLidPhone(jid));this.sock(socket);if (persisted) return true;