Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): key stored and rangeless chat writes by engine ids only
Yudhi Armyndharis6da8ad931a50
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 14a873571..319b0d9d5 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -977,7 +977,10 @@ adapter boundary — none silently stubs.indexed by the same jid as that message's key: a message in memory under the jid it arrived with,a stored one under the lid its row is filed under, or the chat's only reported lid, else its phonejid; an own group message goes without its participant. A key that does not belong to the chat is- not used. With no usable message, clear and delete resolve `false`, and archive and unread are sent+ not used. A chat id not spelled the way the engine keys chats (`<id>@g.us`, `<lid>@lid` or a phone+ jid, lowercase, with no device suffix), such as `[email protected]` or a bare number, is served only by a+ message in memory: without one, the four writes and a `sendSeen` without message ids resolve `false`. With no usable+ message, clear and delete resolve `false`, and archive and unread are sentwithout a range for a chat the session knows (a chat record, a persisted state row or a storedmessage) whose jid belongs to it, and resolve `false` otherwise; unread also resolves `false` for anarchived chat, which the phone leaves unmarked without a range. `sendSeen`diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex f0ae8beb0..6efcf77ab 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -446,6 +446,7 @@ export class BaileysContacts {// stands in, rebuilt the way a chat write keys it.const last = this.host.lastInboundMessage(chatId);if (last && (await this.matchesChat(last.key, chatId, socket))) return [last.key];+ if (!isEngineChatId(chatId)) return [];const row = await this.readStored(chatId, storedLast);const received = row && !row.fromMe ? this.storedTarget(chatId, row) : null;return received && (await this.matchesChat(received.key, chatId, socket)) ? [received.key] : [];@@ -524,6 +525,10 @@ export class BaileysContacts {* With neither, `rangeless()` allows a patch without a range: it is indexed by the chat's jid, and* only for a chat the session knows (a message in memory or stored, or a chat record or state row* the listing holds) whose jid passes the same check. Otherwise the answer is null.+ *+ * Only the message in memory serves an id spelled any other way than the engine keys chats+ * ({@link isEngineChatId}): the stored lookup normalizes the id and finds the chat's rows, but the+ * patch would still be indexed by the misspelled id, which names no chat on the phone.*/private async chatWriteRange(socket: WASocket,@@ -534,6 +539,7 @@ export class BaileysContacts {const last = this.host.lastMessage(chatId);const inMemory = last ? this.memoryTarget(chatId, last.key, last.timestamp) : null;if (inMemory && (await this.matchesChat(inMemory.key, chatId, socket))) return toRange(inMemory);+ if (!isEngineChatId(chatId)) return null;const row = await this.readStored(chatId, stored);const fromStore = row ? this.storedTarget(chatId, row) : null;if (fromStore && (await this.matchesChat(fromStore.key, chatId, socket))) return toRange(fromStore);@@ -689,3 +695,16 @@ function target(function toRange(write: WriteTarget): ChatWriteRange {return { jid: write.jid, lastMessages: [{ key: write.key, messageTimestamp: write.timestamp }] };}++/**+ * Whether a chat id is spelled the way the engine keys chats: `<id>@g.us`, `<lid>@lid` or a phone in+ * either user dialect, lowercase, with no device suffix or surrounding space. chatJid folds a phone's+ * two dialects and nothing else, so `[email protected]` or a bare `628111` would index a patch by a jid that+ * names no chat.+ */+function isEngineChatId(chatId: string): boolean {+ const { kind, userPart: id } = parseWaId(chatId);+ const domains =+ kind === 'group' ? ['g.us'] : kind === 'lid' ? ['lid'] : kind === 'user' ? ['c.us', 's.whatsapp.net'] : [];+ return domains.some(domain => chatId === `${id}@${domain}`);+}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 0156ef73c..e52b19098 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -8435,6 +8435,46 @@ describe('BaileysAdapter chat writes keyed to a message (#1891)', () => {);});+ // The stored lookup normalizes the id and finds the chat's rows, but the patch would be indexed by the+ // id as written, which names no chat on the phone.+ it.each(['[email protected]', '628111', ' [email protected]', '628111:[email protected]', '[email protected]'])(+ 'keys no write to a stored message or to none for %j, which is not how the engine keys a chat',+ async chatId => {+ const adapter = await ready();+ fakeSock.fire('chats.upsert', [{ id: '[email protected]' }, { id: '[email protected]' }]);+ const stored = lookup({ id: 'S1', fromMe: true, author: '[email protected]', timestamp: 1690000000 });++ await expect(adapter.clearChatMessages(chatId, stored)).resolves.toBe(false);+ await expect(adapter.deleteChat(chatId, stored)).resolves.toBe(false);+ await expect(adapter.archiveChat(chatId, true, stored)).resolves.toBe(false);+ await expect(adapter.markUnread(chatId, stored)).resolves.toBe(false);+ await expect(+ adapter.sendSeen(chatId, undefined, undefined, lookup({ id: 'S2', fromMe: false, timestamp: 1690000001 })),+ ).resolves.toBe(false);+ expect(stored).not.toHaveBeenCalled();+ expect(fakeSock.chatModify).not.toHaveBeenCalled();+ expect(fakeSock.readMessages).not.toHaveBeenCalled();+ },+ );++ it('still keys a write to the message in memory for a phone id spelled in upper case', async () => {+ const adapter = await ready();+ await upsert({ remoteJid: '[email protected]', fromMe: true, id: 'OWN' });+ const stored = lookup(null);++ await expect(adapter.clearChatMessages('[email protected]', stored)).resolves.toBe(true);+ expect(fakeSock.chatModify).toHaveBeenCalledWith(+ {+ clear: true,+ lastMessages: [+ { key: { remoteJid: '[email protected]', fromMe: true, id: 'OWN' }, messageTimestamp: 1700000020 },+ ],+ },+ '[email protected]',+ );+ expect(stored).not.toHaveBeenCalled();+ });+it.each([['archiveChat', (a: BaileysAdapter) => a.archiveChat('[email protected]', true, lookup(null)), { archive: true }],['markUnread', (a: BaileysAdapter) => a.markUnread('[email protected]', lookup(null)), { markRead: false }],