Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): log a failed wipe when a Baileys session is unlinked

Yudhi Armyndharis140ec7fae7b2
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index f90f26d4d..93082521a 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -953,8 +953,7 @@ export class BaileysLifecycle {
// DISCONNECTED before the awaited cleanup so no send/path observes a half-torn-down socket.
this.localSocketShutdown(sourceSock);
this.host.fenceStoredWrites();
- 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.clearStoredAccountState();
// 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.
@@ -1029,8 +1028,7 @@ export class BaileysLifecycle {
// 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.clearStoredAccountState();
await this.clearAuthState();
} catch (err) {
// A failed credential removal is terminal: report FAILED + onError instead of looking like a
@@ -1050,6 +1048,25 @@ export class BaileysLifecycle {
await cleanup;
}
+ /**
+ * Drop the stored messages and chat states of the account being unlinked. A failure does not fail the
+ * unlink, whose completion is the credential removal that follows, but it is logged: the rows that
+ * survive resurface under the next account to link this session (its chat list picks up the old
+ * account's pin, mute and archive flags), and nothing else says why.
+ */
+ private async clearStoredAccountState(): Promise<void> {
+ const { messageStore, chatStateStore, dbSessionId, sessionId } = this.host.config;
+ const warn =
+ (what: string) =>
+ (err: unknown): void =>
+ this.host.logger.warn(`Failed to clear the stored ${what} of an unlinked account`, {
+ sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ await messageStore?.clearSession(dbSessionId).catch(warn('messages'));
+ await chatStateStore?.clearSession(sessionId).catch(warn('chat states'));
+ }
+
/**
* Delete this session's on-disk multi-file auth state (`authDir/sessionId`). Required after a terminal
* logout: Baileys would otherwise reload the now-invalid creds on the next connect() and retry them
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 8f6d7340e..06a0698e4 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -5347,6 +5347,49 @@ describe('BaileysAdapter store-backed ops', () => {
rmSpy.mockRestore();
}
});
+
+ // The rows that survive a failed clear resurface under the next account to link the session, so the
+ // failure is non-fatal for the unlink but must not pass without a trace.
+ const warnOf = (adapter: BaileysAdapter) =>
+ jest
+ .spyOn((adapter as unknown as { logger: { warn: (m: string, ctx?: unknown) => void } }).logger, 'warn')
+ .mockImplementation(() => undefined);
+ const clearFailure = (what: string) => [
+ `Failed to clear the stored ${what} of an unlinked account`,
+ expect.objectContaining({ sessionId: 'sess-1', error: 'SQLITE_BUSY' }) as unknown,
+ ];
+
+ it('logs a failed clear on logout while the unlink still completes', async () => {
+ const adapter = await linked();
+ fakeStore.clearSession.mockRejectedValueOnce(new Error('SQLITE_BUSY'));
+ const warn = warnOf(adapter);
+
+ await expect(adapter.logout()).resolves.toBeUndefined();
+
+ expect(warn).toHaveBeenCalledWith(...clearFailure('messages'));
+ expect(warn).toHaveBeenCalledWith(...clearFailure('chat states'));
+ });
+
+ it('logs a failed clear when WhatsApp unlinks the device while the unlink still completes', async () => {
+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+ try {
+ const onDisconnected = jest.fn();
+ const adapter = await linked(onDisconnected);
+ fakeStore.clearSession.mockRejectedValueOnce(new Error('SQLITE_BUSY'));
+ const warn = warnOf(adapter);
+ fakeSock.fire('connection.update', {
+ connection: 'close',
+ lastDisconnect: { error: { output: { statusCode: 401 } } },
+ });
+ await new Promise(r => setImmediate(r));
+
+ expect(warn).toHaveBeenCalledWith(...clearFailure('messages'));
+ expect(warn).toHaveBeenCalledWith(...clearFailure('chat states'));
+ expect(onDisconnected).toHaveBeenCalledWith('logged out');
+ } finally {
+ rmSpy.mockRestore();
+ }
+ });
});
});