Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): key no chat write to a guessed lid

Yudhi Armyndharis17c3c7dc861b
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 319b0d9d5..8d0679643 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -975,12 +975,16 @@ adapter boundary — none silently stubs.
four `chatModify` actions (archive, clear, delete, unread) are keyed to the chat's newest message:
the one the session holds in memory, else the newest one the gateway stored (#1891). The patch is
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 phone
- jid; an own group message goes without its participant. A key that does not belong to the chat is
- 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 sent
+ a stored one under the lid its row is filed under, or the chat's only reported lid, else a lid the
+ session's cache holds for it, else its phone jid; an own group message goes without its participant.
+ A stored message filed under the phone of a chat the persisted table maps to two or more lids, or
+ received in a group from a sender it maps to two or more, is not used, since keying it to any one of
+ them would be a guess: the write proceeds as for a chat with no stored message. A key that does not
+ belong to the chat is 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 sent
without a range for a chat the session knows (a chat record, a persisted state row or a stored
message) whose jid belongs to it, and resolve `false` otherwise; unread also resolves `false` for an
archived chat, which the phone leaves unmarked without a range. `sendSeen`
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 81252291d..3f4ec6199 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -9403,7 +9403,7 @@ describe('SessionService', () => {
]);
});
- it('takes the lid the row is filed under when the table maps the phone to two, and none from a phone row', async () => {
+ it('takes the lid the row is filed under when the table maps the phone to two, and no row filed under the phone', async () => {
(lidMappingStore.findLidsForPhone as jest.Mock).mockResolvedValue(['998', '999']);
const row = (chatId: string) => ({
waMessageId: 'S1',
@@ -9420,13 +9420,32 @@ describe('SessionService', () => {
lid: '999@lid',
});
- // Filed under the phone, the row names neither lid, so the engine gets none to guess from.
+ // Filed under the phone, the row names neither lid, and either would be a guess: no write is keyed to it.
(messageRepository.findOne as jest.Mock).mockResolvedValueOnce(row('[email protected]'));
- await expect(lookupOf('markUnread', () => service.markUnread('sess-uuid-1', '[email protected]'))).resolves.toEqual({
- id: 'S1',
- fromMe: false,
- timestamp: 1690000000,
+ await expect(lookupOf('markUnread', () => service.markUnread('sess-uuid-1', '[email protected]'))).resolves.toBeNull();
+ });
+
+ it('takes no group message whose sender the table maps to two lids, and keeps the cache to a sender with none', async () => {
+ (lidMappingStore.findLidsForPhone as jest.Mock).mockImplementation((phone: string) =>
+ Promise.resolve(phone === '628222' ? ['554', '555'] : []),
+ );
+ const row = (author: string) => ({
+ waMessageId: 'G1',
+ chatId: '[email protected]',
+ direction: MessageDirection.INCOMING,
+ author,
+ timestamp: 1690000001,
});
+ (messageRepository.findOne as jest.Mock).mockResolvedValueOnce(row('[email protected]'));
+ await expect(
+ lookupOf('clearChatMessages', () => service.clearChatMessages('sess-uuid-1', '[email protected]')),
+ ).resolves.toBeNull();
+
+ // A sender the table maps to no lid keeps its row: the engine falls back to the lid it knows, if any.
+ (messageRepository.findOne as jest.Mock).mockResolvedValueOnce(row('[email protected]'));
+ await expect(
+ lookupOf('clearChatMessages', () => service.clearChatMessages('sess-uuid-1', '[email protected]')),
+ ).resolves.toEqual({ id: 'G1', fromMe: false, author: '[email protected]', timestamp: 1690000001 });
});
it('for a read receipt, takes only a received message', async () => {
@@ -9461,6 +9480,10 @@ describe('SessionService', () => {
row('[email protected]', 'TWO-OLD', MessageDirection.OUTGOING, 100),
row('462@lid', 'TWO-NEW', MessageDirection.INCOMING, 200),
row('461@lid', 'TWO-OLDER', MessageDirection.INCOMING, 50),
+ row('782@lid', 'PHONE-OLD', MessageDirection.INCOMING, 100),
+ row('[email protected]', 'PHONE-NEW', MessageDirection.OUTGOING, 200),
+ row('[email protected]', 'AMBIGUOUS-OWN', MessageDirection.OUTGOING, 100),
+ row('[email protected]', 'AMBIGUOUS-IN', MessageDirection.INCOMING, 200, '[email protected]'),
] as QueryDeepPartialEntity<Message>[]);
});
@@ -9470,8 +9493,14 @@ describe('SessionService', () => {
beforeEach(() => {
Object.assign(service as unknown as Record<string, unknown>, { messageRepository: messages });
+ const lids: Record<string, string[]> = {
+ 123: ['999'],
+ 456: ['461', '462'],
+ 789: ['781', '782'],
+ 628333: ['5551', '5552'],
+ };
(lidMappingStore.findLidsForPhone as jest.Mock).mockImplementation((phone: string) =>
- Promise.resolve(phone === '123' ? ['999'] : phone === '456' ? ['461', '462'] : []),
+ Promise.resolve(lids[phone] ?? []),
);
});
@@ -9493,6 +9522,14 @@ describe('SessionService', () => {
});
});
+ it('takes no message filed under a phone the table maps to two lids, nor one from a sender it maps to two', async () => {
+ await expect(lookupOf('markUnread', () => service.markUnread('sess-uuid-1', '[email protected]'))).resolves.toBeNull();
+ await expect(
+ lookupOf('clearChatMessages', () => service.clearChatMessages('sess-uuid-1', '[email protected]')),
+ ).resolves.toBeNull();
+ await expect(lookupOf('sendSeen', () => service.sendSeen('sess-uuid-1', '[email protected]'))).resolves.toBeNull();
+ });
+
it('in a group, skips a received message without its sender, and a receipt takes only a received one', async () => {
await expect(
lookupOf('clearChatMessages', () => service.clearChatMessages('sess-uuid-1', '[email protected]')),
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 5cba2eebf..f57d72319 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -1552,11 +1552,18 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
if (!row) return null;
// The lid the engine keys a lid-migrated chat by, read from the persisted mapping: the engine's
// own cache can lack it (#1901). A phone can map to more than one lid, so the lid the row is
- // filed under wins; a row filed under the phone takes the table's lid only when it lists one.
+ // filed under wins, and a row filed under the phone takes the table's lid when it lists one. With
+ // two or more, for the chat or for the sender of a received group message, any one is a guess
+ // (the engine's cache would pick the oldest), so no write is keyed to the row at all.
const filed = parseWaId(row.chatId);
const lids = expanded.filter(candidate => parseWaId(candidate).kind === 'lid');
- const lid = filed.kind === 'lid' ? `${filed.userPart}@lid` : lids.length === 1 ? lids[0] : undefined;
- const authorLid = row.author ? await this.persistedLidOf(row.author) : undefined;
+ if (filed.kind !== 'lid' && lids.length > 1) return null;
+ const lid = filed.kind === 'lid' ? `${filed.userPart}@lid` : lids[0];
+ const sender =
+ parseWaId(chatId).kind === 'group' && row.direction === MessageDirection.INCOMING ? row.author : undefined;
+ const authorLids = sender ? await this.persistedLidsOf(sender) : [];
+ if (authorLids.length > 1) return null;
+ const authorLid = authorLids[0];
return {
id: row.waMessageId,
fromMe: row.direction === MessageDirection.OUTGOING,
@@ -1568,13 +1575,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
};
}
- /** The `<lid>@lid` the persisted mapping holds for a person, or undefined. */
- private async persistedLidOf(jid: string): Promise<string | undefined> {
+ /** Every `<lid>@lid` the persisted mapping holds for a person (the lid itself for a lid). */
+ private async persistedLidsOf(jid: string): Promise<string[]> {
const parsed = parseWaId(jid);
- if (parsed.kind === 'lid') return `${parsed.userPart}@lid`;
- if (parsed.kind !== 'user') return undefined;
- const [lid] = await this.lidMappingStore.findLidsForPhone(parsed.userPart);
- return lid ? `${lid}@lid` : undefined;
+ if (parsed.kind === 'lid') return [`${parsed.userPart}@lid`];
+ if (parsed.kind !== 'user') return [];
+ return (await this.lidMappingStore.findLidsForPhone(parsed.userPart)).map(lid => `${lid}@lid`);
}
/**