Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): forget chat mute, archive and pin state on an unlink
Yudhi Armyndharis14b71367c731
diff --git a/src/engine/adapters/baileys-chat-state-store.service.spec.ts b/src/engine/adapters/baileys-chat-state-store.service.spec.tsindex d2d753d85..2c8d9938d 100644--- a/src/engine/adapters/baileys-chat-state-store.service.spec.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.spec.ts@@ -25,6 +25,10 @@ function makeRepo(initial: Partial<ChatState>[] = []) {rows.set(KEY(v.sessionId, v.chatId), { ...v });return Promise.resolve(undefined);}),+ delete: jest.fn(({ sessionId }: { sessionId: string }) => {+ for (const [k, r] of rows) if (r.sessionId === sessionId) rows.delete(k);+ return Promise.resolve(undefined);+ }),};return repo;}@@ -48,6 +52,19 @@ describe('ChatStateStoreService', () => {expect(svc.get('s', 'c')).toEqual({ muteEndTime: 123, archived: true, pinned: false });});+ it('clearSession drops one session from the table and the cache, and leaves the others', async () => {+ const repo = makeRepo([+ { sessionId: 's', chatId: 'c', archived: true },+ { sessionId: 't', chatId: 'c', pinned: true },+ ]);+ const svc = svcWith(repo);+ await svc.reload();+ await svc.clearSession('s');+ expect([...repo.rows.values()].map(r => r.sessionId)).toEqual(['t']);+ expect(svc.get('s', 'c')).toBeUndefined();+ expect(svc.get('t', 'c')).toEqual({ muteEndTime: null, archived: false, pinned: true });+ });+it('returns undefined for an unknown chat', () => {expect(svcWith(makeRepo()).get('s', 'nope')).toBeUndefined();});diff --git a/src/engine/adapters/baileys-chat-state-store.service.ts b/src/engine/adapters/baileys-chat-state-store.service.tsindex 6015808ee..685c8b5d8 100644--- a/src/engine/adapters/baileys-chat-state-store.service.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.ts@@ -20,6 +20,8 @@ export interface ChatStateStore {remember(sessionId: string, chatId: string, patch: Partial<ChatStateValue>): Promise<void>;/** (Re)load the in-memory mirror from the table (boot, and after a full-replace restore). */reload(): Promise<void>;+ /** Forget every chat state of one session (an unlink: the next account to link it starts clean). */+ clearSession(sessionId: string): Promise<void>;}const DEFAULT_STATE: ChatStateValue = { muteEndTime: null, archived: false, pinned: false };@@ -123,6 +125,15 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {}}+ async clearSession(sessionId: string): Promise<void> {+ await this.repo.delete({ sessionId });+ // Evicted after the delete, so a read-through that raced it cannot leave a deleted row cached.+ const prefix = `${sessionId}${SEP}`;+ for (const k of [...this.states.keys()]) {+ if (k.startsWith(prefix)) this.states.delete(k);+ }+ }+/** Warm a cache miss from the table. This lookup still returns undefined (the read cannot await); the next hits. */private warmFromTable(k: string, sessionId: string, chatId: string): void {if (this.pendingLookups.has(k)) return;diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex 74fa17851..f7b78cb41 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -845,6 +845,7 @@ export class BaileysLifecycle {// DISCONNECTED before the awaited cleanup so no send/path observes a half-torn-down socket.this.localSocketShutdown(sourceSock);await this.host.config.messageStore?.clearSession(this.host.config.dbSessionId).catch(() => undefined);+ await this.host.config.chatStateStore?.clearSession(this.host.config.sessionId).catch(() => undefined);// Wipe the multi-file auth dir so a fresh link starts clean — stale creds would otherwise be// reloaded on the next connect() and block re-linking (Baileys retries them, no QR emitted).// A removal failure propagates: completion requires cleanup, so the operation is incomplete.@@ -912,9 +913,11 @@ export class BaileysLifecycle {const cleanup = (async (): Promise<void> => {try {- // The unlinked account's messages go with it, as they do on an API logout: the next account- // to link this session must not reply to, forward or retry them.+ // The unlinked account's messages and chat states go with it, as they do on an API logout: the+ // next account to link this session must not reply to, forward or retry them, nor inherit its+ // muted, archived and pinned chats.await this.host.config.messageStore?.clearSession(this.host.config.dbSessionId).catch(() => undefined);+ await this.host.config.chatStateStore?.clearSession(this.host.config.sessionId).catch(() => undefined);await this.clearAuthState();} catch (err) {// A failed credential removal is terminal: report FAILED + onError instead of looking like adiff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex 686317d11..dc14dddb2 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -20,6 +20,9 @@ class FakeChatStateStore implements ChatStateStore {reload(): Promise<void> {return Promise.resolve();}+ clearSession(): Promise<void> {+ return Promise.resolve();+ }}describe('BaileysSessionStore', () => {diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex f23c05450..9af7639ab 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -4251,6 +4251,52 @@ describe('BaileysAdapter store-backed ops', () => {await adapter.logout();expect(fakeStore.clearSession).toHaveBeenCalledWith('db-uuid-1');});++ describe('persisted chat states on an unlink', () => {+ const chatStateStore = {+ get: jest.fn(),+ remember: jest.fn().mockResolvedValue(undefined),+ reload: jest.fn().mockResolvedValue(undefined),+ clearSession: jest.fn(),+ };+ const linked = async (onDisconnected = jest.fn()): Promise<BaileysAdapter> => {+ // A failing clear must not change how either unlink ends.+ chatStateStore.clearSession.mockRejectedValue(new Error('SQLITE_BUSY'));+ const adapter = new BaileysAdapter({+ sessionId: 'sess-1',+ dbSessionId: 'db-uuid-1',+ authDir: './data/baileys',+ messageStore: fakeStore,+ chatStateStore,+ });+ await adapter.initialize({ onDisconnected });+ fakeSock.fire('connection.update', { connection: 'open' });+ return adapter;+ };++ it('clears them on logout', async () => {+ const adapter = await linked();+ await expect(adapter.logout()).resolves.toBeUndefined();+ expect(chatStateStore.clearSession).toHaveBeenCalledWith('sess-1');+ });++ it('clears them when WhatsApp unlinks the device', async () => {+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ try {+ const onDisconnected = jest.fn();+ await linked(onDisconnected);+ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 401 } } },+ });+ await new Promise(r => setImmediate(r));+ expect(chatStateStore.clearSession).toHaveBeenCalledWith('sess-1');+ expect(onDisconnected).toHaveBeenCalledWith('logged out');+ } finally {+ rmSpy.mockRestore();+ }+ });+ });});describe('BaileysAdapter group management', () => {