Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): keep pre-initialize teardown retired

Yudhi Armyndharis47688a624f45
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 92832e703..36f21cb3c 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -381,6 +381,46 @@ describe('BaileysAdapter lifecycle & status', () => {
expect(adapter.getStatus()).toBe(EngineStatus.FAILED);
expect(onError).toHaveBeenCalledWith('network error');
});
+
+ // Teardown-before-initialize: the adapter is single-use once torn down. The intentionalClose latch
+ // is set by disconnect()/destroy()/forceDestroy()/logout() and must NEVER be re-armed by a later
+ // initialize() — otherwise a retired adapter opens a fresh socket no caller is tracking.
+ describe('teardown-before-initialize (single-use adapter)', () => {
+ const makeWASocket = (): jest.Mock =>
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ jest.requireMock('@whiskeysockets/baileys').default as jest.Mock;
+
+ it.each([{ method: 'disconnect' as const }, { method: 'destroy' as const }, { method: 'forceDestroy' as const }])(
+ '%s() before initialize() does not create a socket, and a later initialize() still does not',
+ async ({ method }) => {
+ makeWASocket().mockClear();
+ const adapter = newAdapter();
+ // A brand-new adapter has never connected: tearing it down must not touch the socket factory.
+ await adapter[method]();
+ expect(makeWASocket()).not.toHaveBeenCalled();
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+
+ // The teardown latch must NOT be re-armed by initialize(): a retired adapter stays retired.
+ makeWASocket().mockClear();
+ await adapter.initialize(noopCallbacks({}));
+ expect(makeWASocket()).not.toHaveBeenCalled();
+ },
+ );
+
+ it('logout() before initialize() rejects (no socket) and a subsequent initialize() still does not make a socket', async () => {
+ makeWASocket().mockClear();
+ const adapter = newAdapter();
+ // No socket was ever created, so the unlink cannot be sent.
+ await expect(adapter.logout()).rejects.toThrow(/no live whatsapp socket/i);
+ expect(makeWASocket()).not.toHaveBeenCalled();
+
+ // The teardown latch set by logout() must hold: initialize() must not open a fresh socket on a
+ // retired adapter.
+ makeWASocket().mockClear();
+ await adapter.initialize(noopCallbacks({}));
+ expect(makeWASocket()).not.toHaveBeenCalled();
+ });
+ });
});
describe('BaileysAdapter reconnect policy — unlimited backoff (I4 hardening)', () => {
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 0b04a6235..f5e72ceb5 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -207,7 +207,15 @@ export class BaileysAdapter implements IWhatsAppEngine {
async initialize(callbacks: EngineEventCallbacks): Promise<void> {
this.callbacks = callbacks;
- this.intentionalClose = false;
+ // Single-use after teardown: disconnect()/destroy()/forceDestroy()/logout() set this latch, and
+ // it must NOT be re-armed here. A retired adapter (e.g. one whose session was stopped/deleted
+ // during the service's pre-initialize window) would otherwise open a fresh socket no caller is
+ // tracking. A new adapter starts with the latch false, so the first initialize() proceeds; a
+ // later teardown leaves it true for the adapter's lifetime. connectInner() re-checks the latch
+ // after its auth/version awaits as a fence against teardown during those I/O steps.
+ if (this.intentionalClose) {
+ return;
+ }
try {
await this.connect();
} catch (err) {
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index bf56d3201..2972cae9b 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -119,6 +119,7 @@ describe('SessionService', () => {
destroy: jest.fn().mockResolvedValue(undefined),
forceDestroy: jest.fn().mockResolvedValue(undefined),
disconnect: jest.fn().mockResolvedValue(undefined),
+ logout: jest.fn().mockResolvedValue(undefined),
getQRCode: jest.fn().mockReturnValue(null),
getGroups: jest.fn().mockResolvedValue([]),
getChats: jest.fn().mockResolvedValue([]),
@@ -4618,4 +4619,192 @@ describe('SessionService', () => {
expect(startSpy).toHaveBeenCalledTimes(2);
});
});
+
+ // ── pre-initialize retirement race (lifecycle control during the INITIALIZING DB write) ──
+ describe('pre-initialize retirement race', () => {
+ type Internals = {
+ engines: Map<string, unknown>;
+ stoppingSessions: Set<string>;
+ initializingSessions: Set<string>;
+ reconnectStates: Map<string, unknown>;
+ sessionErrors: Map<string, string>;
+ pendingInitialStatuses: Map<string, { engine: unknown; promise: Promise<void> }>;
+ };
+ const intern = () => service as unknown as Internals;
+
+ /** Polls `check` until it stops throwing, with a bounded number of event-loop flushes. */
+ async function waitFor(check: () => void, ticks = 200): Promise<void> {
+ for (let i = 0; i < ticks; i++) {
+ try {
+ check();
+ return;
+ } catch {
+ await new Promise(r => setImmediate(r));
+ }
+ }
+ check();
+ }
+
+ /**
+ * Drives service.start() until the engine is registered in the map but engine.initialize() has
+ * NOT yet been called — i.e. start() is parked inside the deferred `updateStatus(INITIALIZING)`
+ * DB write. Yields the handle that settles the deferred write plus a `settleOrder` log that
+ * records every persisted mutation' SETTLEMENT (not invocation) so a test can prove the
+ * INITIALIZING write settled BEFORE the control action's final write.
+ */
+ async function startUntilPreInit(): Promise<{
+ resolveInit: () => void;
+ settleOrder: string[];
+ recordTxn: (mark: string) => void;
+ startPromise: Promise<unknown>;
+ }> {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+
+ const settleOrder: string[] = [];
+ let resolveInit: () => void = () => undefined;
+ const initWrite = new Promise<void>(resolve => {
+ resolveInit = resolve;
+ });
+
+ (repository.update as jest.Mock).mockImplementation((id: unknown, payload: { status?: SessionStatus }) => {
+ if (id === 'sess-uuid-1' && payload?.status === SessionStatus.INITIALIZING) {
+ return initWrite.then(() => {
+ settleOrder.push('INITIALIZING');
+ return { affected: 1 };
+ });
+ }
+ // All other writes settle immediately and record their settlement order relative to the
+ // deferred INITIALIZING write (settlement order, not invocation order, is what persists last).
+ return Promise.resolve({ affected: 1 }).then(res => {
+ settleOrder.push(payload?.status ?? 'OTHER');
+ return res;
+ });
+ });
+
+ // Wrap the shared transaction mock so a test can record the delete transaction's commit point
+ // into the same settlement-order log (delete's "final mutation" is the row removal, not a
+ // status write, so it has no SessionStatus value to key on). The shared transaction mock is
+ // re-installed per test by beforeEach, so this override need not be restored.
+ const recordTxn = (mark: string): void => {
+ (dataSource.transaction as jest.Mock).mockImplementation(async (cb: (m: unknown) => Promise<unknown>) => {
+ const manager = {
+ save: jest.fn().mockImplementation((entity: unknown) => Promise.resolve(entity)),
+ remove: jest.fn().mockResolvedValue(undefined),
+ delete: jest.fn().mockResolvedValue({ affected: 0 }),
+ };
+ const res = await cb(manager);
+ settleOrder.push(mark);
+ return res;
+ });
+ };
+
+ // Clear any prior calls so the assertions below only see this start()'s lifecycle.
+ mockEngine.initialize.mockClear();
+
+ const startPromise = service.start('sess-uuid-1');
+ // Wait until the engine is registered (engines.set happens before the INITIALIZING write).
+ await waitFor(() => expect(intern().engines.has('sess-uuid-1')).toBe(true));
+ // The engine is in the map but initialize() must not have fired yet (it's gated behind the
+ // deferred INITIALIZING write).
+ expect(mockEngine.initialize).not.toHaveBeenCalled();
+
+ return { resolveInit, settleOrder, recordTxn, startPromise };
+ }
+
+ const expectNoInitializeAfterRetire = (): void => {
+ expect(mockEngine.initialize).not.toHaveBeenCalled();
+ };
+
+ it.each([
+ { action: 'stop' as const },
+ { action: 'logout' as const },
+ { action: 'delete' as const },
+ { action: 'forceKill' as const },
+ ])(
+ 'pre-initialize: $action during the INITIALIZING write retires the engine without calling initialize',
+ async ({ action }) => {
+ const { resolveInit, settleOrder, recordTxn, startPromise } = await startUntilPreInit();
+ const oldEngine = intern().engines.get('sess-uuid-1');
+
+ // For delete, record its row-removal transaction commit into the settlement-order log so the
+ // ordering assertion below is meaningful (delete's final mutation is the transaction).
+ if (action === 'delete') recordTxn('DELETE_TXN');
+
+ // Kick off the control action while start() is parked behind the deferred INITIALIZING write.
+ // In the fixed service this awaits the captured engine's pending initial-status promise
+ // (blocked until resolveInit); in the buggy service it completes immediately. Either way it
+ // must retire the engine without initialize(). logout may reject if the mock unlink fails.
+ const control = ((): Promise<unknown> => {
+ switch (action) {
+ case 'stop':
+ return service.stop('sess-uuid-1');
+ case 'logout':
+ return service.logout('sess-uuid-1').catch(() => undefined);
+ case 'delete':
+ return service.delete('sess-uuid-1');
+ case 'forceKill':
+ return service.forceKill('sess-uuid-1');
+ }
+ })();
+
+ // Settle the delayed INITIALIZING write so any control action parked on the pending-status
+ // await can proceed, then let both control and start() finish. start() may reject (e.g. a
+ // post-init guard) — the control action owns the persisted outcome, so swallow that here.
+ resolveInit();
+ await control;
+ await startPromise.catch(() => undefined);
+ await waitFor(() => expect(intern().initializingSessions.has('sess-uuid-1')).toBe(false));
+
+ // The adapter was NEVER initialized — no fresh socket on a retired engine.
+ expectNoInitializeAfterRetire();
+
+ // The engine is retired: not in the map.
+ expect(intern().engines.get('sess-uuid-1')).not.toBe(oldEngine);
+ expect(intern().engines.has('sess-uuid-1')).toBe(false);
+
+ // Prove exact persisted ordering: the deferred INITIALIZING write settled BEFORE the control
+ // action's final persisted mutation (DISCONNECTED for stop/logout/forceKill, the row-removal
+ // transaction for delete). This is settlement order, not just the call set — the control
+ // action must remain the final persisted owner.
+ const initIdx = settleOrder.indexOf('INITIALIZING');
+ expect(initIdx).toBeGreaterThanOrEqual(0);
+ const finalMark = action === 'delete' ? 'DELETE_TXN' : SessionStatus.DISCONNECTED;
+ const finalIdx = settleOrder.lastIndexOf(finalMark);
+ expect(finalIdx).toBeGreaterThanOrEqual(0);
+ expect(initIdx).toBeLessThan(finalIdx);
+
+ // A retired start must leave no INITIALIZING persisted (the ordering assertion above), no
+ // reconnect timer, no error entry, and no concurrency slot. stop()/forceKill() intentionally
+ // leave the stop mark set (a later start() clears it), so that is not asserted here; delete()
+ // clears it in its finally.
+ expect(intern().initializingSessions.has('sess-uuid-1')).toBe(false);
+ expect(intern().reconnectStates.has('sess-uuid-1')).toBe(false);
+ expect(intern().sessionErrors.has('sess-uuid-1')).toBe(false);
+ },
+ );
+
+ it('pre-initialize: a swapped map record must not be initialized by the original pending-write path (identity fence)', async () => {
+ // The pending initial-status entry is keyed by id but carries the EXACT engine it belongs to.
+ // If the map record is replaced before the deferred INITIALIZING write settles, settling that
+ // write must NOT initialize the original (now-superseded) engine, and must NOT delete/await a
+ // pending entry belonging to a different engine. Guards a naive id-only implementation.
+ const { resolveInit, startPromise } = await startUntilPreInit();
+ const original = intern().engines.get('sess-uuid-1');
+
+ // Simulate a replacement swapping the live map record out from under the original engine.
+ const replacement = { ...mockEngine, initialize: jest.fn().mockResolvedValue(undefined) };
+ intern().engines.set('sess-uuid-1', replacement);
+
+ resolveInit();
+ await startPromise.catch(() => undefined);
+ await waitFor(() => expect(intern().initializingSessions.has('sess-uuid-1')).toBe(false));
+
+ // The original engine is no longer the live one, so its initialize() must NOT fire from the
+ // original start()'s post-write path (object-identity fence via isLiveEngine).
+ expect((original as { initialize: jest.Mock }).initialize).not.toHaveBeenCalled();
+ // The injected replacement was never driven by THIS start()'s deferred-write path either.
+ expect(replacement.initialize).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 4bd301352..a55e2c837 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -239,6 +239,17 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// wait (bounded) for settlement before touching that path. Entries self-remove on settlement.
private readonly pendingTeardowns = new Map<string, Promise<void>>();
+ // The in-flight `updateStatus(INITIALIZING)` write keyed by id, carrying the EXACT engine it
+ // belongs to. initializeEngine registers the engine, then awaits this write before calling
+ // adapter initialize(); a lifecycle control (stop/logout/delete/forceKill) can retire the engine
+ // during that awaited write. To keep the control action the final persisted owner, every retiring
+ // control awaits the captured engine's exact pending promise (looked up by object identity) after
+ // setting the stop mark + cancelling reconnect and BEFORE its teardown / final DISCONNECTED write
+ // / parent-row deletion. Settlement and removal are identity-checked on both {engine, promise} so
+ // a delayed INITIALIZING for engine A can never be awaited as / delete the entry of a replacement
+ // engine B the control action did not capture.
+ private readonly pendingInitialStatuses = new Map<string, { engine: IWhatsAppEngine; promise: Promise<void> }>();
+
constructor(
@InjectRepository(Session, 'data')
private readonly sessionRepository: Repository<Session>,
@@ -448,6 +459,38 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
}
+ /**
+ * Wait for the captured `engine`'s exact in-flight `updateStatus(INITIALIZING)` write to settle.
+ * Called by every retiring lifecycle control (stop/logout/delete/forceKill) AFTER the stop mark is
+ * set and reconnect cancelled, and BEFORE teardown / the final DISCONNECTED write / parent-row
+ * deletion. This keeps the control action the final persisted owner: a delayed INITIALIZING write
+ * always settles first, so it can never land after the DISCONNECTED write or the row removal.
+ *
+ * Identity-checked on the engine object: a control action that captured engine A awaits ONLY A's
+ * pending promise, never a replacement B's entry (and never deletes it). A bounded wait mirrors
+ * awaitPendingTeardown — the INITIALIZING write is a single DB update, but a wedged DB must not
+ * block retirement indefinitely.
+ */
+ private async awaitInitialStatus(id: string, engine: IWhatsAppEngine): Promise<void> {
+ const pending = this.pendingInitialStatuses.get(id);
+ if (!pending || pending.engine !== engine) return;
+
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const settled = await Promise.race([
+ pending.promise.then(() => true),
+ new Promise<boolean>(resolve => {
+ timer = setTimeout(() => resolve(false), 10_000);
+ }),
+ ]);
+ if (timer) clearTimeout(timer);
+ if (!settled) {
+ this.logger.warn(`Proceeding to retire session ${id} while its INITIALIZING status write is still wedged`, {
+ sessionId: id,
+ action: 'pending_initial_status_wait_exhausted',
+ });
+ }
+ }
+
/**
* Evict a terminally-failed or abandoned engine from the map and SIGKILL its browser process
* (best-effort, time-bounded via teardownEngineSafely). An engine left in the map keeps holding a
@@ -564,6 +607,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// no session state worth saving, and a wedged Chromium must be reaped, not left to time out.
const engine = this.engines.get(id);
if (engine) {
+ // Await THIS engine's in-flight INITIALIZING write before teardown and the parent-row
+ // deletion below, so a delayed pre-initialize status update can never settle after the row
+ // is gone (delete cannot be followed by a late status write). Identity-checked.
+ await this.awaitInitialStatus(id, engine);
await this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');
if (this.isLiveEngine(id, engine)) this.engines.delete(id);
}
@@ -961,7 +1008,42 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// Mark INITIALIZING before engine.initialize(): the engine drives status forward
// (QR_READY -> AUTHENTICATING -> READY) through the callbacks below while it
// initializes, so writing INITIALIZING afterwards would clobber that progress.
- await this.updateStatus(id, SessionStatus.INITIALIZING);
+ //
+ // The INITIALIZING write is awaited here, and a lifecycle control (stop/logout/delete/forceKill)
+ // can retire this engine during that await. To keep the control action the final persisted owner,
+ // the in-flight write is tracked in pendingInitialStatuses (carrying this exact engine) so each
+ // retiring control can await ITS captured engine's write before its own final mutation. After the
+ // await, ownership is re-validated by object identity + the synchronous stop mark before the
+ // adapter is allowed to initialize — a retired engine must never reach initialize() (which would
+ // re-arm a torn-down adapter and open an untracked socket).
+ const initialStatusPromise = this.updateStatus(id, SessionStatus.INITIALIZING);
+ this.pendingInitialStatuses.set(id, { engine, promise: initialStatusPromise });
+ try {
+ await initialStatusPromise;
+ } finally {
+ // Remove ONLY this engine's entry: a replacement created by a concurrent start()/reconnect
+ // (different engine object) must not have its pending entry evicted by this settlement.
+ const pending = this.pendingInitialStatuses.get(id);
+ if (pending && pending.engine === engine && pending.promise === initialStatusPromise) {
+ this.pendingInitialStatuses.delete(id);
+ }
+ }
+
+ // After the awaited DB write, re-validate ownership before scheduling initialization. The stop
+ // mark is set synchronously by every retiring control BEFORE it awaits this engine's pending
+ // write, so checking it here (no DB read on the healthy path) closes the pre-initialize window
+ // without changing reconnect-when-reload-fails semantics. isLiveEngine guards the stop-mark-less
+ // timeout path and any replacement. There is intentionally NO await between these checks and
+ // engine.initialize() below — an intervening await would re-open the retirement window.
+ if (!this.isLiveEngine(id, engine)) {
+ return;
+ }
+ if (this.stoppingSessions.has(id)) {
+ return;
+ }
+ if (!this.isLiveEngine(id, engine)) {
+ return;
+ }
const initPromise = engine.initialize({
onQRCode: (qr: string): void => {
@@ -2211,6 +2293,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// behaviour: a later start() clears it; it guards against a late reconnect resurrecting the id.)
const engine = this.engines.get(id);
if (engine) {
+ // Await THIS engine's in-flight INITIALIZING write before teardown / the final DISCONNECTED
+ // write so a delayed pre-initialize status update can never settle after the retirement and
+ // become the last persisted status. Identity-checked: only the captured engine's promise.
+ await this.awaitInitialStatus(id, engine);
await this.teardownEngineSafely(id, engine, e => e.disconnect(), 'disconnect');
if (this.isLiveEngine(id, engine)) this.engines.delete(id);
}
@@ -2263,6 +2349,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// Cancel any reconnection attempts
this.cancelReconnect(id);
+ // Await THIS engine's in-flight INITIALIZING write before teardown / the final DISCONNECTED
+ // write so a delayed pre-initialize status update can never settle after the retirement.
+ await this.awaitInitialStatus(id, engine);
const unlinked = await this.teardownEngineSafely(id, engine, e => e.logout(), 'logout');
if (this.isLiveEngine(id, engine)) this.engines.delete(id);
await this.updateStatus(id, SessionStatus.DISCONNECTED);
@@ -2314,6 +2403,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
this.stoppingSessions.add(id);
this.cancelReconnect(id);
+ // Await THIS engine's in-flight INITIALIZING write before teardown / the final DISCONNECTED
+ // write so a delayed pre-initialize status update can never settle after the retirement.
+ await this.awaitInitialStatus(id, engine);
await this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');
if (this.isLiveEngine(id, engine)) this.engines.delete(id);