Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): key mute, pin, star and label writes by the chat's jid

Yudhi Armyndharisdf111a2f68f6
diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.ts
index eca824f33..2e1d9c5f2 100644
--- a/src/engine/adapters/baileys-contacts.ts
+++ b/src/engine/adapters/baileys-contacts.ts
@@ -39,6 +39,8 @@ export interface BaileysContactsHost {
getStoredMessages(messageIds: string[]): Promise<WAMessage[]> | undefined;
/** Fold a neutral @c.us id to the engine @s.whatsapp.net form used as the app-state index key. */
toEngineJid(jid: string): string;
+ /** The id the chat is keyed under (its lid for a lid-migrated contact), the app-state index key. */
+ chatJid(chatId: string): string;
/** Fold an engine jid back to the neutral dialect before it crosses the engine boundary. */
toNeutralJid(jid: string): string;
}
@@ -446,7 +448,7 @@ export class BaileysContacts {
this.host.ensureReady();
// Deliberately no lastMessage lookup: the `mute` member of ChatModification carries no
// `lastMessages`, unlike archive/clear/delete, so a chat with no known history mutes fine.
- await this.confirmed(this.sock().chatModify({ mute: muteUntil }, this.host.toEngineJid(chatId)), 'the mute change');
+ await this.confirmed(this.sock().chatModify({ mute: muteUntil }, this.host.chatJid(chatId)), 'the mute change');
}
async pinChat(chatId: string, pin: boolean): Promise<boolean> {
@@ -455,7 +457,7 @@ export class BaileysContacts {
// archive/clear/delete, so a chat with no known history pins fine. Always true — Baileys writes
// the app-state patch and reports nothing back, so it has no equivalent of the whatsapp-web.js
// three-pin refusal to surface.
- await this.confirmed(this.sock().chatModify({ pin }, this.host.toEngineJid(chatId)), 'the pin change');
+ await this.confirmed(this.sock().chatModify({ pin }, this.host.chatJid(chatId)), 'the pin change');
return true;
}
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index a821aa8f6..1712ebe1c 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -594,7 +594,9 @@ export class BaileysMessaging {
timestamp: this.host.toUnixSeconds(target.messageTimestamp),
},
},
- this.host.toEngineJid(chatId),
+ // Indexed by the chat the message is stored in: for a lid-keyed chat that is its lid, which the
+ // @c.us id the listing publishes does not fold to.
+ this.host.toEngineJid(chatJid),
),
'the delete-for-me',
);
@@ -880,13 +882,14 @@ export class BaileysMessaging {
this.assertStoredInChat(target, chatId, messageId);
// fromMe is load-bearing: the same message id addresses a different message depending on
// direction, so omitting it would star the wrong side of the conversation.
- // 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.
+ // chatModify keys the star app-state index by the raw jid (no jidNormalizedUser, unlike the send
+ // path), so it takes the chat the message is stored in, folded to the engine form: a neutral @c.us,
+ // or the phone jid of a chat keyed by the contact's lid, would index a phantom chat and the star
+ // would silently apply to nothing.
await this.confirmed(
this.sock().chatModify(
{ star: { messages: [{ id: target.key.id!, fromMe: target.key.fromMe ?? false }], star } },
- this.host.toEngineJid(chatId),
+ this.host.toEngineJid(target.key.remoteJid ?? chatId),
),
'the star change',
);
diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.ts
index d203e6384..0fa483690 100644
--- a/src/engine/adapters/baileys-session-store.ts
+++ b/src/engine/adapters/baileys-session-store.ts
@@ -524,10 +524,20 @@ export class BaileysSessionStore {
return [...this.chats.values()].map(c => this.toNeutralChat(c));
}
+ /**
+ * The id the chat is keyed under, for an app-state write addressed with any spelling of it (the
+ * listing's @c.us id of a lid-keyed chat resolves to the lid). Baileys indexes the patch by this jid
+ * and replays it locally under the same id, so any other spelling names a chat the phone does not
+ * hold and lands the echo on a second record.
+ */
+ chatJid(chatId: string): string {
+ return this.chatKey(chatId);
+ }
+
/** The chat's newest message, with `jid`, the id the chat itself is keyed under. */
lastMessage(chatId: string): { key: WAMessageKey; timestamp: number; jid: string } | null {
const m = this.newestAcrossTwins(this.lastMessages, chatId);
- return m ? { key: m.key, timestamp: m.timestamp, jid: this.chatKey(chatId) } : null;
+ return m ? { key: m.key, timestamp: m.timestamp, jid: this.chatJid(chatId) } : null;
}
/** The newest message the chat received (not one this account sent), or null when none is known. */
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 46a46920f..562eb2f28 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -6204,6 +6204,67 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
);
});
+ // The writes that need no last message resolve the chat the same way. Keyed by the phone jid, the
+ // patch named a chat the phone does not hold, and its local echo added a second row to GET /chats
+ // under the same @c.us id, carrying the mute or pin the listed row never showed.
+ describe('writes without a last message on a lid-keyed chat called with the listed @c.us id', () => {
+ const lidKeyedChat = async (): Promise<BaileysAdapter> => {
+ const adapter = newAdapter();
+ await adapter.initialize({});
+ fakeSock.fire('connection.update', { connection: 'open' });
+ fakeSock.fire('chats.upsert', [{ id: '484848@lid', name: 'Alice' }]);
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { remoteJid: '484848@lid', remoteJidAlt: '[email protected]', fromMe: false, id: 'M1' },
+ message: { conversation: 'hi' },
+ messageTimestamp: 1700000020,
+ },
+ ],
+ });
+ await new Promise(r => setImmediate(r));
+ expect((await adapter.getChats()).map(c => c.id)).toEqual(['[email protected]']);
+ return adapter;
+ };
+
+ it.each([
+ ['muteChat', (a: BaileysAdapter) => a.muteChat('[email protected]', 1900000000), { muteEndTime: 1900000000 }],
+ ['pinChat', (a: BaileysAdapter) => a.pinChat('[email protected]', true), { pinned: 1700000030 }],
+ ])('%s keeps the listed row the only one', async (_n, act, echo) => {
+ const adapter = await lidKeyedChat();
+ await act(adapter);
+ const [, jid] = fakeSock.chatModify.mock.calls[0] as [unknown, string];
+ expect(jid).toBe('484848@lid');
+ // Baileys replays its own patch as chats.update under the jid the patch was indexed by.
+ fakeSock.fire('chats.update', [{ id: jid, ...echo }]);
+ expect(await adapter.getChats()).toEqual([expect.objectContaining({ id: '[email protected]', name: 'Alice' })]);
+ });
+
+ it.each([
+ ['addLabelToChat', 'addChatLabel', (a: BaileysAdapter) => a.addLabelToChat('[email protected]', 'L1')],
+ ['removeLabelFromChat', 'removeChatLabel', (a: BaileysAdapter) => a.removeLabelFromChat('[email protected]', 'L1')],
+ ] as const)('%s labels the chat under its lid', async (_n, method, act) => {
+ const adapter = await lidKeyedChat();
+ await act(adapter);
+ expect(fakeSock[method]).toHaveBeenCalledWith('484848@lid', 'L1');
+ });
+
+ it.each([
+ ['starMessage', (a: BaileysAdapter) => a.starMessage('[email protected]', 'M1', true)],
+ ['deleteMessage for me', (a: BaileysAdapter) => a.deleteMessage('[email protected]', 'M1', false)],
+ ])("%s indexes the patch by the stored message's chat", async (_n, act) => {
+ fakeStore.getMessage.mockResolvedValue({
+ key: { remoteJid: '484848@lid', fromMe: false, id: 'M1' },
+ message: { conversation: 'hi' },
+ messageTimestamp: 1700000020,
+ });
+ const adapter = await lidKeyedChat();
+ await act(adapter);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith(expect.anything(), '484848@lid');
+ });
+ });
+
it('clearChatMessages returns false for a chat with no known history', async () => {
const adapter = newAdapter();
await adapter.initialize({});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index ac88c5f1c..cf2637e63 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -153,6 +153,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
getOnCallOutcome: () => this.callbacks.onCallOutcome,
ensureReady: () => this.ensureReady(),
toEngineJid: jid => this.sessionStore.toEngineJid(jid),
+ chatJid: chatId => this.sessionStore.chatJid(chatId),
getEphemeralExpiration: chatId => this.sessionStore.getEphemeralExpiration(chatId),
getStoredMessage: messageId => this.config.messageStore?.getMessage(this.config.dbSessionId, messageId),
getStoredMessages: messageIds => this.config.messageStore?.getMessages(this.config.dbSessionId, messageIds),
@@ -609,7 +610,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
this.ensureReady();
this.assertLabelable(chatId);
await withQueryDeadline(
- this.sock!.addChatLabel(this.sessionStore.toEngineJid(chatId), labelId),
+ this.sock!.addChatLabel(this.sessionStore.chatJid(chatId), labelId),
BAILEYS_QUERY_BUDGET_MS,
'WhatsApp did not confirm the chat label add in time',
);
@@ -618,7 +619,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
this.ensureReady();
this.assertLabelable(chatId);
await withQueryDeadline(
- this.sock!.removeChatLabel(this.sessionStore.toEngineJid(chatId), labelId),
+ this.sock!.removeChatLabel(this.sessionStore.chatJid(chatId), labelId),
BAILEYS_QUERY_BUDGET_MS,
'WhatsApp did not confirm the chat label removal in time',
);
diff --git a/src/engine/adapters/chat-mute.spec.ts b/src/engine/adapters/chat-mute.spec.ts
index 5d9e6b7d9..13940ca64 100644
--- a/src/engine/adapters/chat-mute.spec.ts
+++ b/src/engine/adapters/chat-mute.spec.ts
@@ -175,6 +175,8 @@ describe('BaileysContacts.muteChat', () => {
listChats: () => [],
lastMessage: () => opts.lastMessage ?? null,
toEngineJid: (j: string) => j.replace('@c.us', '@s.whatsapp.net'),
+ // A chat the store holds no record for resolves to its engine form, as the session store does.
+ chatJid: (j: string) => j.replace('@c.us', '@s.whatsapp.net'),
} as unknown as BaileysContactsHost;
return new BaileysContacts(host, opts.budgetMs ?? 500);
}
diff --git a/src/engine/adapters/chat-pin.spec.ts b/src/engine/adapters/chat-pin.spec.ts
index a52f0440c..5a9dbadd6 100644
--- a/src/engine/adapters/chat-pin.spec.ts
+++ b/src/engine/adapters/chat-pin.spec.ts
@@ -127,6 +127,8 @@ describe('BaileysContacts.pinChat', () => {
listChats: () => [],
lastMessage: () => opts.lastMessage ?? null,
toEngineJid: (j: string) => j.replace('@c.us', '@s.whatsapp.net'),
+ // A chat the store holds no record for resolves to its engine form, as the session store does.
+ chatJid: (j: string) => j.replace('@c.us', '@s.whatsapp.net'),
} as unknown as BaileysContactsHost;
return new BaileysContacts(host, opts.budgetMs ?? 500);
}