Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): clear stored messages when WhatsApp unlinks the device

Yudhi Armyndharis3954a1ed2694
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index 0dd96193f..74fa17851 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -912,6 +912,9 @@ 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.
+ await this.host.config.messageStore?.clearSession(this.host.config.dbSessionId).catch(() => undefined);
await this.clearAuthState();
} catch (err) {
// A failed credential removal is terminal: report FAILED + onError instead of looking like a
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 19f256740..f23c05450 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -316,6 +316,26 @@ describe('BaileysAdapter lifecycle & status', () => {
}
});
+ it('on a logged-out close: clears the stored messages, as an API logout does', async () => {
+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+ try {
+ const onDisconnected = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({ onDisconnected }));
+ fakeStore.clearSession.mockRejectedValueOnce(new Error('SQLITE_BUSY'));
+ fakeSock.fire('connection.update', {
+ connection: 'close',
+ lastDisconnect: { error: { output: { statusCode: 401 } } },
+ });
+ await new Promise(r => setImmediate(r));
+ expect(fakeStore.clearSession).toHaveBeenCalledWith('db-uuid-1');
+ // A store failure does not turn the unlink into a failed cleanup.
+ expect(onDisconnected).toHaveBeenCalledWith('logged out');
+ } finally {
+ rmSpy.mockRestore();
+ }
+ });
+
it('on a logged-out close: clears the on-disk auth dir so a fresh connect shows a new QR', async () => {
// Root cause of the "QR never appears after logout" bug: the now-invalid multi-file auth dir was
// left on disk, so the next connect() reloaded the dead creds and Baileys retried them instead of