Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): fence Baileys store writes before an unlink wipes them

Yudhi Armyndharis5f823565ae6c
diff --git a/src/engine/adapters/baileys-lifecycle.spec.ts b/src/engine/adapters/baileys-lifecycle.spec.ts
index 7ab42e26a..e22f283df 100644
--- a/src/engine/adapters/baileys-lifecycle.spec.ts
+++ b/src/engine/adapters/baileys-lifecycle.spec.ts
@@ -28,3 +28,49 @@ describe('BaileysLifecycle.connect', () => {
expect(authLogger).toBe(logger);
});
});
+
+describe('BaileysLifecycle unlink cleanup', () => {
+ function lifecycle() {
+ const noCallback = (): undefined => undefined;
+ const fenceStoredWrites = jest.fn();
+ const messageStore = { clearSession: jest.fn().mockResolvedValue(undefined) };
+ const host = {
+ authPath: '/nonexistent/openwa-lifecycle-spec/session-sess-1',
+ logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },
+ config: { sessionId: 'sess-1', dbSessionId: 'db-1', messageStore },
+ liveCalls: new Map(),
+ fenceStoredWrites,
+ getOnStateChanged: noCallback,
+ getOnDisconnected: noCallback,
+ getOnError: noCallback,
+ getOnCredentialTeardownStarted: noCallback,
+ } as unknown as BaileysLifecycleHost;
+ const sock = {
+ user: { id: '628999:[email protected]' },
+ query: jest.fn().mockResolvedValue({ tag: 'iq' }),
+ generateMessageTag: () => 'tag-1',
+ end: jest.fn(),
+ };
+ const engine = new BaileysLifecycle(host);
+ engine.sock = sock as unknown as BaileysLifecycle['sock'];
+ return { engine, fenceStoredWrites, clearSession: messageStore.clearSession };
+ }
+
+ // A message still being processed must not recreate a row of the unlinked account after its store
+ // is wiped, so the store writes are fenced first.
+ it('fences stored writes before wiping the message store on an API logout', async () => {
+ const { engine, fenceStoredWrites, clearSession } = lifecycle();
+ await engine.logout();
+ expect(clearSession).toHaveBeenCalledWith('db-1');
+ expect(fenceStoredWrites).toHaveBeenCalledTimes(1);
+ expect(fenceStoredWrites.mock.invocationCallOrder[0]).toBeLessThan(clearSession.mock.invocationCallOrder[0]);
+ });
+
+ it('fences stored writes before wiping the message store on a WhatsApp-side logout', async () => {
+ const { engine, fenceStoredWrites, clearSession } = lifecycle();
+ await (engine as unknown as { handleRemoteLoggedOut(): Promise<void> }).handleRemoteLoggedOut();
+ expect(clearSession).toHaveBeenCalledWith('db-1');
+ expect(fenceStoredWrites).toHaveBeenCalledTimes(1);
+ expect(fenceStoredWrites.mock.invocationCallOrder[0]).toBeLessThan(clearSession.mock.invocationCallOrder[0]);
+ });
+});
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index c8dce3624..9c1d28bcf 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -154,6 +154,8 @@ export interface BaileysLifecycleHost {
handleGroupJoinRequest: BaileysEvents['handleGroupJoinRequest'];
handleCallEvents: BaileysEvents['handleCallEvents'];
handlePresenceUpdate: BaileysEvents['handlePresenceUpdate'];
+ /** Drop the store writes of messages still being processed; called before an unlink wipes the store. */
+ fenceStoredWrites: BaileysEvents['fenceStoredWrites'];
captureHistoryMessages: BaileysHistory['captureHistoryMessages'];
/** Backfill names the initial sync skipped (runs on connection 'open'). */
hydrateNames: BaileysHistory['hydrateNames'];
@@ -890,6 +892,7 @@ export class BaileysLifecycle {
// Acknowledged. End/null the captured socket, clear live call handles, and drop to
// 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);
// Wipe the multi-file auth dir so a fresh link starts clean — stale creds would otherwise be
@@ -955,6 +958,8 @@ export class BaileysLifecycle {
// Cached call handles die with the connection — drop them so a later rejectCall() reports
// not-found (404) instead of acting on a dead socket (mirrors disconnect/logout/destroy).
this.host.liveCalls.clear();
+ // A message still being processed must not recreate a row of the unlinked account after the wipe below.
+ this.host.fenceStoredWrites();
void dead?.end(undefined);
const cleanup = (async (): Promise<void> => {
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index b75594266..a1f41f622 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -200,6 +200,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
handleGroupJoinRequest: event => this.events.handleGroupJoinRequest(event),
handleCallEvents: calls => this.events.handleCallEvents(calls),
handlePresenceUpdate: update => this.events.handlePresenceUpdate(update),
+ fenceStoredWrites: () => this.events.fenceStoredWrites(),
captureHistoryMessages: messages => this.history.captureHistoryMessages(messages),
hydrateNames: () => this.history.hydrateNames(),
restoreAddressbookSnapshot: () => this.history.restoreAddressbookSnapshot(),