Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): fence auth reuse behind name-scoped teardown
Yudhi Armyndharis811aa53f8322
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 82c378e8d..5a41fcf4e 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -906,6 +906,110 @@ describe('WhatsAppWebJsAdapter.forceDestroy (recover a wedged session, #351)', (});});+// Credential teardown is the only operation that removes this session's on-disk WhatsApp credentials+// (the LocalAuth profile dir). Two code paths reach it: the adapter's own logout() (client.logout()+// chains authStrategy.logout() → fs.rm) and a WhatsApp-initiated unlink (the lib emits+// disconnected:LOGOUT, THEN awaits authStrategy.logout() → fs.rm). Both must surface the destructive+// promise to the lifecycle via onCredentialTeardownStarted SYNCHRONOUSLY, before the awaited settle,+// so a concurrent start()/delete()/reconnect for the same session NAME sees the in-flight rm and waits+// for it instead of re-creating/purging credentials the rm is about to delete.+describe('WhatsAppWebJsAdapter credential-teardown observation', () => {+ const newAdapter = (): WhatsAppWebJsAdapter =>+ new WhatsAppWebJsAdapter({ sessionId: 'sess-1', sessionDataPath: './data/sessions', puppeteer: {} });+ type FakeClient = EventEmitter & {+ info?: { wid?: { user?: string }; pushname?: string };+ getState: jest.Mock;+ pupPage: { evaluate: jest.Mock };+ destroy?: jest.Mock;+ logout?: jest.Mock;+ };++ // Mirrors the ready-reconciliation helper but wires the credential-teardown callback too.+ const attach = (+ adapter: WhatsAppWebJsAdapter,+ overrides: Partial<FakeClient> = {},+ ): { client: FakeClient; onCredentialTeardownStarted: jest.Mock } => {+ const client = Object.assign(new EventEmitter(), {+ info: { wid: { user: '628123' }, pushname: 'Tester' },+ getState: jest.fn().mockResolvedValue(WAState.CONNECTED),+ pupPage: { evaluate: jest.fn().mockResolvedValue(true) },+ ...overrides,+ }) as FakeClient;+ const onCredentialTeardownStarted = jest.fn();+ (adapter as unknown as { client: unknown }).client = client;+ (adapter as unknown as { callbacks: unknown }).callbacks = { onCredentialTeardownStarted };+ (adapter as unknown as { setupEventHandlers: () => void }).setupEventHandlers();+ return { client, onCredentialTeardownStarted };+ };++ afterEach(() => {+ jest.useRealTimers();+ });++ it('logout() registers the client.logout() promise via onCredentialTeardownStarted before awaiting it', async () => {+ const adapter = newAdapter();+ let resolveLogout!: () => void;+ const logoutPromise = new Promise<void>(res => {+ resolveLogout = res;+ });+ const { onCredentialTeardownStarted } = attach(adapter, {+ logout: jest.fn().mockReturnValue(logoutPromise),+ destroy: jest.fn().mockResolvedValue(undefined),+ });++ // Fire logout but do NOT settle it yet — the callback must already have been handed the promise.+ const logoutCall = adapter.logout();+ await Promise.resolve(); // flush the synchronous portion of logout()++ expect(onCredentialTeardownStarted).toHaveBeenCalledTimes(1);+ const [tracked] = onCredentialTeardownStarted.mock.calls[0] as [Promise<void>];+ expect(tracked).toBeInstanceOf(Promise);+ // The tracked promise is the SAME destructive operation the adapter is awaiting: settling it+ // settles logout().+ resolveLogout();+ await expect(tracked).resolves.toBeUndefined();+ await expect(logoutCall).resolves.toBeUndefined();+ });++ it('a WhatsApp-originated disconnected:LOGOUT registers the credential-teardown promise synchronously before the event loop can run', async () => {+ // The lib emits disconnected:LOGOUT BEFORE it awaits authStrategy.logout() (the fs.rm). The adapter+ // must register the destructive cleanup synchronously within the event handler so a start()/reconnect+ // that races on the next tick observes the in-flight rm.+ const adapter = newAdapter();+ const { client, onCredentialTeardownStarted } = attach(adapter);++ client.emit('disconnected', 'LOGOUT');++ // Synchronous: the callback was handed a promise before any await settled.+ expect(onCredentialTeardownStarted).toHaveBeenCalledTimes(1);+ const [tracked] = onCredentialTeardownStarted.mock.calls[0] as [Promise<void>];+ expect(tracked).toBeInstanceOf(Promise);+ // The fence survives until the tracked rm settles (here it resolves).+ await expect(tracked).resolves.toBeUndefined();+ });++ it('does not register a credential teardown for a non-LOGOUT disconnect (a transient drop, not credential removal)', () => {+ const adapter = newAdapter();+ const { client, onCredentialTeardownStarted } = attach(adapter);++ client.emit('disconnected', 'NAVIGATION');++ expect(onCredentialTeardownStarted).not.toHaveBeenCalled();+ });++ it('does not register a credential teardown for a deliberate (tearingDown) LOGOUT — the caller already owns that cleanup', () => {+ // client.logout() during adapter.logout() also fires disconnected:LOGOUT; the adapter must not+ // double-track (the explicit logout() path already registered the promise).+ const adapter = newAdapter();+ const { client, onCredentialTeardownStarted } = attach(adapter);+ (adapter as unknown as { tearingDown: boolean }).tearingDown = true;++ client.emit('disconnected', 'LOGOUT');++ expect(onCredentialTeardownStarted).not.toHaveBeenCalled();+ });+});+describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {const newAdapter = (): WhatsAppWebJsAdapter =>new WhatsAppWebJsAdapter({ sessionId: 'sess-1', sessionDataPath: './data/sessions', puppeteer: {} });diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex f00a49a13..76bf95887 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -934,21 +934,30 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// raises this event: client.logout() triggers the in-page Cmd 'logout' → framenavigated →// DISCONNECTED 'LOGOUT' while we are still awaiting it. The unlink is already acknowledged by// the API response and the session service writes DISCONNECTED itself, so report nothing here- // (mirrors the puppeteer-death gate). A WhatsApp-initiated unlink arrives with- // tearingDown=false and still flows through.+ // (mirrors the puppeteer-death gate). The credential-teardown promise for that path was already+ // registered by logout() itself, so do NOT double-register here. A WhatsApp-initiated unlink+ // arrives with tearingDown=false and still flows through.if (this.tearingDown) return;this.clearReadyReconcile();// #982: LOGOUT is not a transient drop. whatsapp-web.js emits it when WhatsApp Web itself ran a- // logout (its in-page `Cmd` logout bus), and by then it has ALREADY deleted this session's- // credentials — LocalAuth.logout() removes the profile dir before the event reaches us. So the- // lifecycle's reconnect cannot restore the link; it can only come back with a fresh QR. Say that- // here rather than leaving the operator with an opaque engine token that reads like any other drop.+ // logout (its in-page `Cmd` logout bus). The library emits `disconnected: LOGOUT` BEFORE it+ // awaits `authStrategy.logout()` (LocalAuth.logout() → fs.rm of this session's profile dir), so+ // at this moment the credentials are ABOUT to be removed, not already gone. The lifecycle's+ // reconnect cannot restore the link; it can only come back with a fresh QR. Say that here rather+ // than leaving the operator with an opaque engine token that reads like any other drop.if (reason === 'LOGOUT') {+ // Surface the destructive credential cleanup to the lifecycle SYNCHRONOUSLY, before the event+ // loop can run a start()/reconnect: the lib's authStrategy.logout() (the rm) is about to settle+ // right after this handler returns. We can't grab the lib's internal promise, so the adapter+ // runs its own idempotent clearLocalAuth() (fs.rm with force:true races the lib's rm safely) as+ // the tracked operation. A concurrent start()/delete() under the SAME session name then sees the+ // in-flight rm and waits for it instead of re-creating/purging credentials the rm is deleting.+ const cleanup = this.clearLocalAuth();+ this.callbacks.onCredentialTeardownStarted?.(cleanup);this.logger.warn(- 'WhatsApp unlinked this device (LOGOUT). whatsapp-web.js has already deleted the stored ' +- 'credentials for this session, so reconnecting cannot restore the link — the session comes ' +- 'back with a fresh QR and must be re-scanned. If this was not expected, check Linked devices ' +- 'on the phone.',+ 'WhatsApp unlinked this device (LOGOUT). whatsapp-web.js is deleting the stored credentials ' ++ 'for this session, so reconnecting cannot restore the link — the session comes back with a ' ++ 'fresh QR and must be re-scanned. If this was not expected, check Linked devices on the phone.',);}this.setStatus(EngineStatus.DISCONNECTED);@@ -1548,9 +1557,22 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginthrow new Error('No live WhatsApp Web client — the unlink was not sent');}+ // client.logout() chains authStrategy.logout() (LocalAuth) → fs.rm of this session's profile dir.+ // Surface that destructive operation to the lifecycle SYNCHRONOUSLY, before the await, so a+ // concurrent start()/delete()/reconnect for the same session NAME observes the in-flight rm and+ // waits for it instead of re-creating/purging credentials the rm is about to delete. Register+ // BEFORE awaiting so the callback fires even if the await never settles.+ const logoutOp = client.logout();+ this.callbacks.onCredentialTeardownStarted?.(+ logoutOp.then(+ () => undefined,+ () => undefined,+ ),+ );+try {// Logout clears session data - user will need to scan QR again- await client.logout();+ await logoutOp;} catch (error) {this.logger.warn('Logout failed:', { error: String(error) });// Fall back to destroy so the session still dies locally — but rethrow so the callerdiff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex a37d350c4..bb537cac6 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -549,6 +549,23 @@ export interface EngineEventCallbacks {* recoverable and triggers reconnection.*/onError?: (reason: string) => void;+ /**+ * Fired SYNCHRONOUSLY the instant a credential-teardown operation begins — i.e. the moment the+ * adapter kicks off the call that ends in an `fs.rm` of this session's on-disk WhatsApp auth+ * directory. The argument is the SAME promise the adapter is about to await (or, for a+ * WhatsApp-originated unlink, a promise the adapter controls that represents the same rm).+ *+ * Unlike the other callbacks, this one is NOT guarded on the engine still being live: a logout+ * that captured the engine registers its destructive promise even as a concurrent stop()/delete()+ * evicts that engine, because the rm it ends in targets the session NAME's auth dir and would+ * otherwise race a (re)created session under that same name. The lifecycle tracks the promise+ * (keyed by the immutable captured session NAME) so start()/delete()/executeReconnect can wait+ * (bounded, fail-closed) for it to settle before touching that path.+ *+ * Adapters that never remove credentials on their own (e.g. Baileys until a later task wires its+ * WhatsApp-originated cleanup) simply never invoke this.+ */+ onCredentialTeardownStarted?: (operation: Promise<void>) => void;}export interface IWhatsAppEngine {diff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.tsindex fee705fb4..2128f5dc0 100644--- a/src/modules/session/logout-teardown-race.spec.ts+++ b/src/modules/session/logout-teardown-race.spec.ts@@ -1,7 +1,7 @@import { Test, TestingModule } from '@nestjs/testing';import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';import { Repository, DataSource } from 'typeorm';-import { BadGatewayException } from '@nestjs/common';+import { BadGatewayException, ConflictException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { SessionService } from './session.service';import { Session, SessionStatus } from './entities/session.entity';@@ -13,10 +13,13 @@ import { WebhookService } from '../webhook/webhook.service';import { HookManager } from '../../core/hooks';import { StatusStoreService } from '../status-store/status-store.service';+const SESSION_NAME = 'test-session';+const SESSION_UUID = 'sess-uuid-1';+function createMockSession(overrides: Partial<Session> = {}): Session {return {- id: 'sess-uuid-1',- name: 'test-session',+ id: SESSION_UUID,+ name: SESSION_NAME,status: SessionStatus.CREATED,phone: null,pushName: null,@@ -31,7 +34,26 @@ function createMockSession(overrides: Partial<Session> = {}): Session {};}-describe('SessionService logout() concurrent teardown tracking', () => {+// Shared machine-code contract for the name-scoped teardown fence. Attaches a handler synchronously+// so a promise that already settled (or settles during a fake-timer advance before the await) is not+// flagged as an unhandled rejection. A resolved promise fails the assertion (the operation must NOT+// have proceeded); a rejected one asserts the stable code.+async function expectNameTeardownPending(p: Promise<unknown>): Promise<void> {+ // Attach a handler synchronously to mark the rejection as handled.+ const captured = p.then(+ () => undefined as unknown,+ (e: unknown) => e,+ );+ const err = await captured;+ // Nest serializes an object-response ConflictException into { statusCode, message, error, ...fields }.+ // The stable code is attached on the response object so REST callers can branch on it without parsing+ // the human message.+ const thrown = err as { response?: { code?: string } } | undefined;+ expect(thrown).toBeInstanceOf(ConflictException);+ expect(thrown?.response?.code).toBe('SESSION_NAME_TEARDOWN_PENDING');+}++describe('SessionService logout() name-scoped teardown fence', () => {let service: SessionService;let repository: jest.Mocked<Partial<Repository<Session>>>;let engineFactory: jest.Mocked<Partial<EngineFactory>>;@@ -87,78 +109,333 @@ describe('SessionService logout() concurrent teardown tracking', () => {const enginesOf = () => (service as unknown as { engines: Map<string, unknown> }).engines;const pendingOf = () => (service as unknown as { pendingTeardowns: Map<string, Promise<void>> }).pendingTeardowns;+ const stoppingOf = () => (service as unknown as { stoppingSessions: Set<string> }).stoppingSessions;+ const reconnectStatesOf = () => (service as unknown as { reconnectStates: Map<string, unknown> }).reconnectStates;+ const errorsOf = () => (service as unknown as { sessionErrors: Map<string, string> }).sessionErrors;+ const lastStatusOf = () =>+ (service as unknown as { lastDispatchedStatus: Map<string, unknown> }).lastDispatchedStatus;- it('keeps the first teardown tracked when a second logout arrives mid-flight, so start() waits for it', async () => {- // The first logout's teardown wedges (its profile fs.rm outlives the request); the second- // logout's adapter call refuses immediately (the client is already being torn down).- let settleFirst: () => void = () => undefined;- const wedgedLogout = new Promise<void>(resolve => {- settleFirst = resolve;+ it('quick-settling teardown: start waits for it, then proceeds', async () => {+ let releaseLogout!: () => void;+ const wedgedLogout = new Promise<void>(res => {+ releaseLogout = res;});+ const engine = { logout: jest.fn().mockReturnValue(wedgedLogout) };+ enginesOf().set(SESSION_UUID, engine);- const logout = jest- .fn()- .mockReturnValueOnce(wedgedLogout)- .mockReturnValueOnce(Promise.reject(new Error('No live WhatsApp Web client — the unlink was not sent')));+ jest.useFakeTimers();+ try {+ const logoutCall = service.logout(SESSION_UUID);+ await jest.advanceTimersByTimeAsync(10_000); // logout loses its deadline race → 502+ await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);+ // Tracked under the session NAME, not the UUID.+ expect(pendingOf().has(SESSION_NAME)).toBe(true);+ expect(pendingOf().has(SESSION_UUID)).toBe(false);++ const startCall = service.start(SESSION_UUID);+ await jest.advanceTimersByTimeAsync(1_000); // inside the bounded wait+ expect(engineFactory.create).not.toHaveBeenCalled();++ releaseLogout();+ await startCall;+ expect(engineFactory.create).toHaveBeenCalledTimes(1);+ expect(pendingOf().has(SESSION_NAME)).toBe(false); // self-removed on settlement+ } finally {+ jest.useRealTimers();+ }+ });- enginesOf().set('sess-uuid-1', { logout });+ it('quick-settling teardown: delete waits for it, then proceeds and purges', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ id: SESSION_UUID, name: SESSION_NAME }));++ let releaseLogout!: () => void;+ const wedgedLogout = new Promise<void>(res => {+ releaseLogout = res;+ });+ enginesOf().set(SESSION_UUID, { logout: jest.fn().mockReturnValue(wedgedLogout) });jest.useFakeTimers();try {- const first = service.logout('sess-uuid-1');- // let logout1 get past findOne and register its pendingTeardowns entry- await jest.advanceTimersByTimeAsync(0);- expect(pendingOf().has('sess-uuid-1')).toBe(true);+ const logoutCall = service.logout(SESSION_UUID);+ await jest.advanceTimersByTimeAsync(10_000);+ await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);+ expect(pendingOf().has(SESSION_NAME)).toBe(true);- // ---- a separate HTTP request, a macrotask later ----- const second = service.logout('sess-uuid-1');- await expect(second).rejects.toBeInstanceOf(BadGatewayException);- expect(logout).toHaveBeenCalledTimes(2); // engine still in the map => 2nd logout passed the guard+ const deleteCall = service.delete(SESSION_UUID);+ await jest.advanceTimersByTimeAsync(1_000); // inside the bounded wait+ expect(engineFactory.purgeSessionData).not.toHaveBeenCalled();- // The first (still-running) teardown must stay tracked: its late profile rm must gate start().- expect(pendingOf().has('sess-uuid-1')).toBe(true);+ releaseLogout();+ await deleteCall;+ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith(SESSION_NAME);+ expect(pendingOf().has(SESSION_NAME)).toBe(false);+ } finally {+ jest.useRealTimers();+ }+ });- // start() must NOT re-create the profile while the first teardown's rm is pending.- const startCall = service.start('sess-uuid-1');- await jest.advanceTimersByTimeAsync(0);+ it('old-name teardown still pending past 10s: start rejects 409 and does not create the engine', async () => {+ // The wedged logout never settles: its rm sits behind the wedge but is still "in flight" against+ // this session NAME. A start() for a (re)created session under the SAME name must refuse rather+ // than re-create credentials the rm could still hit.+ const neverSettles = new Promise<void>(() => undefined);+ const engine = { logout: jest.fn().mockReturnValue(neverSettles) };+ enginesOf().set(SESSION_UUID, engine);++ jest.useFakeTimers();+ try {+ const logoutCall = service.logout(SESSION_UUID);+ await jest.advanceTimersByTimeAsync(10_000); // logout loses its race → 502; raw keeps running+ await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);+ expect(pendingOf().has(SESSION_NAME)).toBe(true);++ const startCall = service.start(SESSION_UUID);+ startCall.catch(() => undefined); // mark rejection handled across the timer advance below+ await jest.advanceTimersByTimeAsync(10_000); // bounded wait exhausts → fail CLOSED+ await expectNameTeardownPending(startCall);expect(engineFactory.create).not.toHaveBeenCalled();+ // The fence is NOT dropped on a refused start.+ expect(pendingOf().has(SESSION_NAME)).toBe(true);+ } finally {+ jest.useRealTimers();+ }+ });- // Once the first teardown settles, start() proceeds.- settleFirst();+ it('old-name teardown still pending past 10s: delete rejects 409, transaction parent removal and purgeSessionData not called (unique name still reserved)', async () => {+ const manager = { delete: jest.fn().mockResolvedValue({ affected: 1 }), remove: jest.fn() };+ const dataSource: Partial<DataSource> = {+ transaction: jest.fn(async (cb: (m: unknown) => Promise<void>) =>+ cb(manager),+ ) as unknown as DataSource['transaction'],+ };+ // Swap in a dataSource whose transaction we can assert was NOT run.+ (service as unknown as { dataSource: unknown }).dataSource = dataSource;+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ id: SESSION_UUID, name: SESSION_NAME }));++ const neverSettles = new Promise<void>(() => undefined);+ enginesOf().set(SESSION_UUID, { logout: jest.fn().mockReturnValue(neverSettles) });++ jest.useFakeTimers();+ try {+ const logoutCall = service.logout(SESSION_UUID);+ await jest.advanceTimersByTimeAsync(10_000);+ await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);+ expect(pendingOf().has(SESSION_NAME)).toBe(true);++ const deleteCall = service.delete(SESSION_UUID);+ deleteCall.catch(() => undefined); // mark rejection handled across the timer advance below+ await jest.advanceTimersByTimeAsync(10_000); // first fence already pending → fail fast+ await expectNameTeardownPending(deleteCall);+ expect(dataSource.transaction).not.toHaveBeenCalled();+ expect(engineFactory.purgeSessionData).not.toHaveBeenCalled();+ // Name still reserved: the fence survives the refused delete.+ expect(pendingOf().has(SESSION_NAME)).toBe(true);+ } finally {+ jest.useRealTimers();+ }+ });++ it('on a first-fence 409, start does not touch reconnect timer / engine / last status / error / recovery state', async () => {+ // Arm a reconnect timer + a stale FAILED error + a last-dispatched status BEFORE the start attempt,+ // then ensure a refused start (409) leaves ALL of them untouched.+ const neverSettles = new Promise<void>(() => undefined);+ enginesOf().set(SESSION_UUID, { logout: jest.fn().mockReturnValue(neverSettles) });++ jest.useFakeTimers();+ try {+ const logoutCall = service.logout(SESSION_UUID);+ await jest.advanceTimersByTimeAsync(10_000);+ await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);++ // Seed lifecycle state that a buggy "clear on 409" would wipe.+ reconnectStatesOf().set(SESSION_UUID, {+ attempts: 3,+ timer: setTimeout(() => undefined, 999_999),+ maxAttempts: 5,+ baseDelay: 1000,+ });+ errorsOf().set(SESSION_UUID, 'previously failed');+ lastStatusOf().set(SESSION_UUID, SessionStatus.FAILED);+ // The prior logout already cleared the engine from the map; capture membership NOW so the+ // assertion checks the start's 409 did not mutate it (rather than the prior logout's effect).+ const enginePresentBefore = enginesOf().has(SESSION_UUID);++ const startCall = service.start(SESSION_UUID);+ startCall.catch(() => undefined); // mark rejection handled across the timer advance below+ await jest.advanceTimersByTimeAsync(10_000);+ await expectNameTeardownPending(startCall);++ // None of the pre-existing lifecycle state was cleared by the refused start.+ expect(reconnectStatesOf().has(SESSION_UUID)).toBe(true);+ expect(errorsOf().get(SESSION_UUID)).toBe('previously failed');+ expect(lastStatusOf().get(SESSION_UUID)).toBe(SessionStatus.FAILED);+ // The engine map was not mutated by the refused start either.+ expect(enginesOf().has(SESSION_UUID)).toBe(enginePresentBefore);+ } finally {+ jest.useRealTimers();+ }+ });++ it('a refused delete does NOT drop the pending fence', async () => {+ const neverSettles = new Promise<void>(() => undefined);+ enginesOf().set(SESSION_UUID, { logout: jest.fn().mockReturnValue(neverSettles) });++ jest.useFakeTimers();+ try {+ const logoutCall = service.logout(SESSION_UUID);+ await jest.advanceTimersByTimeAsync(10_000);+ await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);+ expect(pendingOf().has(SESSION_NAME)).toBe(true);++ const deleteCall = service.delete(SESSION_UUID);+ deleteCall.catch(() => undefined); // mark rejection handled across the timer advance below+ await jest.advanceTimersByTimeAsync(10_000); // first fence exhausts its bounded wait → fail CLOSED+ await expectNameTeardownPending(deleteCall);+ // The fence is owned by the session NAME and outlives the refused delete.+ expect(pendingOf().has(SESSION_NAME)).toBe(true);+ } finally {+ jest.useRealTimers();+ }+ });++ it('a logout starting after delete first fence but before engine eviction is caught by the second fence', async () => {+ // delete() runs two fences: one right after findOne, one right after the engine is evicted. A logout+ // that slips past fence #1 (no pending teardown yet) but captures the live engine before eviction+ // must register its destructive promise synchronously (the adapter fires onCredentialTeardownStarted+ // the instant engine.logout() begins), so fence #2 sees it and the delete refuses instead of freeing+ // the name while an old remover is live.+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ id: SESSION_UUID, name: SESSION_NAME }));++ let releaseLogout!: () => void;+ const logoutPromise = new Promise<void>(res => {+ releaseLogout = res;+ });+ // The engine is torn down via forceDestroy during delete. A concurrent logout that captured this+ // engine fires its credential-teardown callback synchronously inside that teardown window — between+ // fence #1 and fence #2. Drive the service's own tracking the same way the adapter would.+ const trackPending = (+ service as unknown as {+ trackPendingCredentialTeardown: (name: string, raw: Promise<void>) => void;+ }+ ).trackPendingCredentialTeardown.bind(service);+ enginesOf().set(SESSION_UUID, {+ forceDestroy: jest.fn().mockImplementation(() => {+ // Simulate the adapter firing onCredentialTeardownStarted for a logout that captured this+ // engine mid-delete — registers under the session name synchronously, before fence #2 runs.+ trackPending(SESSION_NAME, logoutPromise);+ return Promise.resolve();+ }),+ });++ jest.useFakeTimers();+ try {+ const deleteCall = service.delete(SESSION_UUID);+ deleteCall.catch(() => undefined); // mark rejection handled across the timer advance below+ await jest.advanceTimersByTimeAsync(10_000); // second fence exhausts its bounded wait+ await expectNameTeardownPending(deleteCall);+ expect(engineFactory.purgeSessionData).not.toHaveBeenCalled();+ // Row/name still reserved: the second fence refused before the transaction.+ expect(pendingOf().has(SESSION_NAME)).toBe(true);++ // After the raw teardown settles, the name is released.+ releaseLogout();+ await jest.advanceTimersByTimeAsync(0);+ expect(pendingOf().has(SESSION_NAME)).toBe(false);+ } finally {+ jest.useRealTimers();+ }+ });++ it('after the raw teardown resolves, retry start succeeds and the entry self-removes', async () => {+ let releaseLogout!: () => void;+ const wedgedLogout = new Promise<void>(res => {+ releaseLogout = res;+ });+ const engine = { logout: jest.fn().mockReturnValue(wedgedLogout) };+ enginesOf().set(SESSION_UUID, engine);++ jest.useFakeTimers();+ try {+ const logoutCall = service.logout(SESSION_UUID);+ await jest.advanceTimersByTimeAsync(10_000);+ await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);++ const startCall = service.start(SESSION_UUID);+ startCall.catch(() => undefined); // mark rejection handled across the timer advance below+ await jest.advanceTimersByTimeAsync(10_000);+ await expectNameTeardownPending(startCall);++ releaseLogout();await jest.advanceTimersByTimeAsync(0);- await expect(first).resolves.toMatchObject({ id: 'sess-uuid-1' });+ expect(pendingOf().has(SESSION_NAME)).toBe(false);++ // Retry start now proceeds cleanly.+ const retry = service.start(SESSION_UUID);await jest.advanceTimersByTimeAsync(0);+ await retry;expect(engineFactory.create).toHaveBeenCalledTimes(1);- await startCall;-- // Entry cleaned up after everything settled.- expect(pendingOf().has('sess-uuid-1')).toBe(false);} finally {jest.useRealTimers();}});- it('drops a wedged logout teardown entry when the session is deleted', async () => {- // A logout teardown that never settles keeps its pendingTeardowns entry past the bounded waits;- // deleting the session must drop it — the UUID can never be read again, so leaving it would- // grow the map without bound across logout-fail/delete churn.- const wedgedLogout = new Promise<void>(() => undefined);- const logout = jest.fn().mockReturnValue(wedgedLogout);- enginesOf().set('sess-uuid-1', { logout });+ it('two concurrent logouts for the same name keep the fence until BOTH settle', async () => {+ // The first logout's raw wedges (its profile rm outlives the request); the second logout's raw+ // rejects fast (the client is already tearing down). The fence must stay until the FIRST+ // (still-running) raw settles — otherwise the second's fast settlement would drop the entry while+ // the first rm is still pending.+ let settleFirst!: () => void;+ const wedgedLogout = new Promise<void>(res => {+ settleFirst = res;+ });+ const logout = jest+ .fn()+ .mockImplementationOnce(() => wedgedLogout)+ .mockImplementationOnce(() =>+ // The client is already tearing down after the first logout captured it; mirror the adapter's+ // own "no live client" refusal. Built lazily so no stray unhandled rejection is created.+ Promise.reject(new Error('No live WhatsApp Web client — the unlink was not sent')),+ );++ enginesOf().set(SESSION_UUID, { logout });jest.useFakeTimers();try {- const logoutCall = service.logout('sess-uuid-1');- await jest.advanceTimersByTimeAsync(10_000); // teardown loses its deadline race- await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);- expect(pendingOf().has('sess-uuid-1')).toBe(true); // the wedged raw keeps its entry+ const first = service.logout(SESSION_UUID);+ first.catch(() => undefined); // mark rejection handled across the timer advances below+ await jest.advanceTimersByTimeAsync(0);+ expect(pendingOf().has(SESSION_NAME)).toBe(true);- const deleteCall = service.delete('sess-uuid-1');- await jest.advanceTimersByTimeAsync(10_000); // delete's bounded wait elapses- await deleteCall;- expect(pendingOf().has('sess-uuid-1')).toBe(false);+ const second = service.logout(SESSION_UUID);+ await expect(second).rejects.toBeInstanceOf(BadGatewayException);++ // The second's fast-rejecting raw has settled, but the FIRST raw is still wedged → fence stays.+ expect(pendingOf().has(SESSION_NAME)).toBe(true);++ // The first loses its 10s deadline race → 502 (unconfirmed), but its raw keeps running.+ await jest.advanceTimersByTimeAsync(10_000);+ await expect(first).rejects.toBeInstanceOf(BadGatewayException);+ // Still wedged → fence STILL up (the fast settlement of the second did not drop it).+ expect(pendingOf().has(SESSION_NAME)).toBe(true);++ settleFirst();+ await jest.advanceTimersByTimeAsync(0);+ expect(pendingOf().has(SESSION_NAME)).toBe(false);} finally {jest.useRealTimers();}});++ it('map assertions use the session name, not the UUID', async () => {+ // Regression guard: the key MUST be the session name (the on-disk auth-dir key), never the UUID.+ const engine = { logout: jest.fn().mockResolvedValue(undefined) };+ enginesOf().set(SESSION_UUID, engine);++ await service.logout(SESSION_UUID);++ expect(pendingOf().has(SESSION_UUID)).toBe(false);+ // A quick-settling logout self-removes, so neither key is present.+ expect(pendingOf().has(SESSION_NAME)).toBe(false);+ expect(stoppingOf().has(SESSION_UUID)).toBe(true);+ });});diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 434588a3d..06fed7376 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -386,9 +386,10 @@ describe('SessionService', () => {await jest.advanceTimersByTimeAsync(10_000); // deadline fires; the race is lost// The deadline loss means the unlink is unconfirmed, so logout() rejects 502 — but the// local teardown already ran and the losing promise is still tracked in pendingTeardowns- // (it settles only when releaseLogout() fires below).+ // (it settles only when releaseLogout() fires below). The fence is keyed by the session+ // NAME — the on-disk auth-dir key — not the UUID.await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);- expect(pendingTeardownsOf().has('sess-uuid-1')).toBe(true); // still running past the race+ expect(pendingTeardownsOf().has('test-session')).toBe(true); // still running past the raceconst startCall = service.start('sess-uuid-1');await jest.advanceTimersByTimeAsync(1_000); // inside the bounded wait@@ -397,7 +398,7 @@ describe('SessionService', () => {releaseLogout(); // the stale rm now lands BEFORE any fresh credentials existawait startCall;expect(engineFactory.create).toHaveBeenCalledTimes(1);- expect(pendingTeardownsOf().has('sess-uuid-1')).toBe(false); // self-removed on settlement+ expect(pendingTeardownsOf().has('test-session')).toBe(false); // self-removed on settlement} finally {jest.useRealTimers();}@@ -422,7 +423,7 @@ describe('SessionService', () => {const logoutCall = service.logout('sess-uuid-1');await jest.advanceTimersByTimeAsync(10_000);await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);- expect(pendingTeardownsOf().has('sess-uuid-1')).toBe(true);+ expect(pendingTeardownsOf().has('test-session')).toBe(true);const deleteCall = service.delete('sess-uuid-1');await jest.advanceTimersByTimeAsync(1_000); // inside the bounded wait@@ -431,13 +432,16 @@ describe('SessionService', () => {releaseLogout();await deleteCall;expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');- expect(pendingTeardownsOf().has('sess-uuid-1')).toBe(false);+ expect(pendingTeardownsOf().has('test-session')).toBe(false);} finally {jest.useRealTimers();}});- it('start() proceeds after the bounded wait when the teardown stays wedged', async () => {+ it('start() fails CLOSED with 409 (SESSION_NAME_TEARDOWN_PENDING) when the teardown stays wedged past the bounded wait', async () => {+ // The fence is fail-closed: a teardown that never settles could still land its rm on credentials+ // a (re)created session under the same name would write, so start() must refuse rather than+ // proceed and let the stale rm race the fresh profile.(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });const engine = { logout: jest.fn().mockReturnValue(new Promise<void>(() => undefined)) };@@ -447,16 +451,19 @@ describe('SessionService', () => {try {const logoutCall = service.logout('sess-uuid-1');await jest.advanceTimersByTimeAsync(10_000);- // The wedged logout never unlinks within the deadline, so it rejects 502; the losing- // promise keeps running and start()'s bounded wait eventually gives up on it below.await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);const startCall = service.start('sess-uuid-1');- await jest.advanceTimersByTimeAsync(10_000); // bounded wait exhausted- await startCall;- // The operator is not blocked indefinitely; the still-wedged teardown's stale rm sits- // behind the wedge, and the residual window is logged (pending_teardown_wait_exhausted).- expect(engineFactory.create).toHaveBeenCalledTimes(1);+ startCall.catch(() => undefined); // mark rejection handled across the timer advance below+ await jest.advanceTimersByTimeAsync(10_000); // bounded wait exhausted → fail CLOSED+ const thrown = await startCall.catch((e: unknown) => e);+ expect(thrown).toBeInstanceOf(ConflictException);+ expect((thrown as ConflictException).getResponse()).toMatchObject({+ code: 'SESSION_NAME_TEARDOWN_PENDING',+ });+ // No engine created, and the fence is NOT dropped.+ expect(engineFactory.create).not.toHaveBeenCalled();+ expect(pendingTeardownsOf().has('test-session')).toBe(true);} finally {jest.useRealTimers();}diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 1416cce2d..4cf8e7927 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -233,10 +233,16 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// order when different mutation kinds for the same message arrive together.private messageMutationChains: Map<string, Promise<void>> = new Map();- // Raw teardown promises that outlived their deadline race in teardownEngineSafely. A losing- // logout() promise keeps running and ends in an fs.rm of the session's on-disk profile — the- // same deterministic path a later start() re-creates — so start()/delete() consult this map and- // wait (bounded) for settlement before touching that path. Entries self-remove on settlement.+ // Destructive credential-teardown promises (logout rms of the session's on-disk WhatsApp auth+ // dir), keyed by session NAME — the on-disk auth-dir key (EngineFactory.wwjsAuthDir/baileysAuthDir+ // and adapter clearLocalAuth all build the path from Session.name), NOT the UUID. A losing+ // logout() promise keeps running past its deadline race and ends in an fs.rm of that dir — the+ // same path a later start() under the SAME name re-creates — so start()/delete()/executeReconnect+ // consult this map and wait (bounded, fail-closed) for settlement before touching that path. After+ // an old UUID's session is deleted and the name is recreated, a late logout from the old UUID+ // still targets the new session's dir (same name → same path), so keying by name keeps the fence+ // attached to the credential path that is actually at risk. Entries self-remove on settlement+ // (identity-checked); nothing else evicts them (delete()'s finally no longer drops them).private readonly pendingTeardowns = new Map<string, Promise<void>>();// The in-flight `updateStatus(INITIALIZING)` write keyed by id, carrying the EXACT engine it@@ -384,32 +390,20 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat** A teardown that loses the deadline race keeps running past the caller's return. For 'logout'* that leftover promise ends in an fs.rm of the session's on-disk profile — the same path a- * later start() re-creates — so the raw promise is registered in pendingTeardowns and start()/- * delete() wait (bounded) for it to settle before touching that path.+ * later start() re-creates — so the raw promise is registered in pendingTeardowns (keyed by the+ * session NAME, which is the auth-dir key) and start()/delete() wait (bounded, fail-closed) for+ * it to settle before touching that path.*/private async teardownEngineSafely(sessionId: string,engine: IWhatsAppEngine,teardown: (e: IWhatsAppEngine) => Promise<void>,label: 'destroy' | 'disconnect' | 'force-destroy' | 'logout',+ sessionName?: string,): Promise<boolean> {const raw = teardown(engine);- if (label === 'logout') {- // Settlement marker only — never rejects, so it can't drive the race below to a false- // "completed"; the race still observes the raw promise. A concurrent logout chains onto the- // previous entry instead of overwriting it, so start()/delete() keep waiting until EVERY- // in-flight teardown for this session has settled — otherwise the second logout's fast- // settlement would drop the entry while the first teardown's profile rm is still pending.- // Identity-checked on removal so a newer teardown's entry isn't evicted by an older one settling.- const tracked = raw.catch(() => undefined);- const previous = this.pendingTeardowns.get(sessionId);- const entry: Promise<void> = previous ? Promise.allSettled([previous, tracked]).then(() => undefined) : tracked;- this.pendingTeardowns.set(sessionId, entry);- void entry.finally(() => {- if (this.pendingTeardowns.get(sessionId) === entry) {- this.pendingTeardowns.delete(sessionId);- }- });+ if (label === 'logout' && sessionName) {+ this.trackPendingCredentialTeardown(sessionName, raw);}let timer: ReturnType<typeof setTimeout> | undefined;try {@@ -431,15 +425,46 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}}+ /**+ * Track a destructive credential-teardown promise under the session NAME (the on-disk auth-dir+ * key — NOT the UUID). A logout's `engine.logout()` ends in an `fs.rm` of the same directory a+ * later start() under the same name re-creates, so start()/delete()/executeReconnect consult this+ * map and wait (bounded, fail-closed) before touching that path.+ *+ * Settlement marker only — never rejects, so it can't drive a caller's deadline race to a false+ * "completed". A concurrent teardown for the same name CHAINS onto the previous entry instead of+ * overwriting it (Promise.allSettled), so callers keep waiting until EVERY in-flight teardown for+ * that name has settled — otherwise a second logout's fast settlement would drop the entry while+ * the first teardown's profile rm is still pending. Identity-checked on removal is the ONLY path+ * that evicts the entry, so a newer teardown's entry is never dropped by an older one settling.+ */+ private trackPendingCredentialTeardown(sessionName: string, raw: Promise<void>): void {+ const tracked = raw.catch(() => undefined);+ const previous = this.pendingTeardowns.get(sessionName);+ const entry: Promise<void> = previous ? Promise.allSettled([previous, tracked]).then(() => undefined) : tracked;+ this.pendingTeardowns.set(sessionName, entry);+ void entry.finally(() => {+ if (this.pendingTeardowns.get(sessionName) === entry) {+ this.pendingTeardowns.delete(sessionName);+ }+ });+ }+/*** Wait (bounded) for a teardown that lost its deadline race to settle. A losing logout() promise* ends in an fs.rm of the on-disk profile — the same deterministic path start() re-creates and- * delete() purges — so those paths call this before touching disk. If the teardown is still- * wedged past the bound, proceed anyway: its rm sits behind the wedge, blocking the operator- * indefinitely is worse, and the residual window is logged.+ * delete() purges — so those paths call this before touching disk. The fence is FAIL CLOSED: a+ * teardown still wedged past the bound could still land its rm on credentials a (re)created session+ * under the same name would write, so the operation refuses with a retryable 409+ * (SESSION_NAME_TEARDOWN_PENDING) instead of proceeding. The entry is NOT dropped on timeout — a+ * retry after the rm eventually settles will see it gone and proceed.+ *+ * Keyed by the session NAME: the auth directories are built from `Session.name`, so two sessions+ * sharing a name (a deleted UUID recreated under the same name) share the credential path and must+ * share the fence.*/- private async awaitPendingTeardown(id: string): Promise<void> {- const pending = this.pendingTeardowns.get(id);+ private async awaitPendingTeardown(sessionName: string): Promise<void> {+ const pending = this.pendingTeardowns.get(sessionName);if (!pending) return;let timer: ReturnType<typeof setTimeout> | undefined;@@ -451,11 +476,16 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat]);if (timer) clearTimeout(timer);if (!settled) {- this.logger.warn(- `Proceeding while a previous logout teardown for session ${id} is still wedged — its ` +- 'stale profile cleanup may land late',- { sessionId: id, action: 'pending_teardown_wait_exhausted' },- );+ // Fail closed: do NOT proceed. The stale rm could still hit a fresh profile under this name.+ // Message is operator-facing and retryable, with no internal path leak.+ throw new ConflictException({+ statusCode: HttpStatus.CONFLICT,+ message:+ `A credential teardown for session '${sessionName}' is still in flight. Wait for it to ` ++ 'settle and retry.',+ error: 'Conflict',+ code: 'SESSION_NAME_TEARDOWN_PENDING',+ });}}@@ -595,11 +625,25 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatasync delete(id: string): Promise<void> {const session = await this.findOne(id);+ // FENCE #1 — fail-fast on an ALREADY-PENDING credential teardown for this session NAME, BEFORE+ // any lifecycle mutation. A logout teardown that lost its deadline race is still running and ends+ // in an fs.rm of this session's on-disk auth dir (keyed by name). Releasing the name via the DB+ // delete below while that rm is live would let a recreated session under the same name race the+ // stale rm. The fence is keyed by session NAME and fails CLOSED (409). On a 409 NOTHING else runs:+ // no stop mark, no reconnect cancel, no engine teardown, no state cleanup — delete() simply did+ // not happen, and the entry stays reserved.+ await this.awaitPendingTeardown(session.name);+// Mark as tearing down BEFORE cleanup so an in-flight reconnect can't resurrect it.this.stoppingSessions.add(id);// Cancel any reconnection attemptsthis.cancelReconnect(id);+ // Set only after the transaction actually removes the parent row. lastDispatchedStatus /+ // sessionErrors (and the recovery budget, Task 8) are cleared ONLY on a committed delete; a+ // rejected 409 from fence #2 leaves them intact (the session still exists).+ let parentDeleted = false;+try {// Stop engine if running — time-bounded + isolated so a stuck Chromium can't wedge the delete;// the Map is reconciled and the DB removal proceeds regardless of the outcome. Use forceDestroy()@@ -615,6 +659,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatif (this.isLiveEngine(id, engine)) this.engines.delete(id);}+ // FENCE #2 — immediately after the current engine is evicted, BEFORE the session:deleted hook+ // and the DB transaction. A logout that started concurrently AFTER fence #1 but captured this+ // engine before eviction registers its destructive promise synchronously (via the engine's+ // onCredentialTeardownStarted callback), so this fence sees it and refuses — the row/name stay+ // reserved and the transaction does not run. After eviction a NEW logout can't create a+ // destructive promise (no live engine); one that already captured the engine is observed here.+ await this.awaitPendingTeardown(session.name);+// Execute hook BEFORE delete so plugins can access session dataawait this.hookManager.execute('session:deleted',@@ -646,6 +698,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatawait manager.delete(BaileysStoredMessage, { sessionId: id });await manager.remove(session);});+ parentDeleted = true;this.logger.log(`Session deleted: ${session.name}`, {sessionId: id,action: 'delete',@@ -656,20 +709,25 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// session NAME and live independently of the (now torn-down, and on delete often never-loaded)// engine instance, so the teardown above doesn't touch them. Without this, recreating a session// under the same name reloads a stale store. Best-effort inside the factory — never fails an- // otherwise-successful delete. A wedged logout teardown from before this delete may still hold- // a pending fs.rm of the same dirs — wait (bounded) for it to settle first.- await this.awaitPendingTeardown(id);+ // otherwise-successful delete. By this point both fences passed, so no old remover is live+ // against this name (the transaction freed the name; the dirs are safe to purge).await this.engineFactory.purgeSessionData(session.name);} finally {- // Always clear the teardown mark so a later recreate/start with this id isn't suppressed.+ // Always clear the teardown mark so a later recreate/start with this id isn't suppressed. This+ // stop mark was set after fence #1, so clearing it on a rejected 409 only undoes what THIS+ // delete added — it does NOT touch reconnect timer / engine / last status / error / recovery+ // state (those are gated on parentDeleted below).this.stoppingSessions.delete(id);- this.lastDispatchedStatus.delete(id);- // Drop the FAILED-reason entry too: it's keyed by a now-deleted UUID that can never be read- // again, so leaving it would grow the map without bound across create/fail/delete churn.- this.sessionErrors.delete(id);- // Same for a wedged logout-teardown entry: the wait above is only bounded, so a teardown- // that never settles would otherwise pin its entry (and its promise chain) forever.- this.pendingTeardowns.delete(id);+ if (parentDeleted) {+ this.lastDispatchedStatus.delete(id);+ // Drop the FAILED-reason entry too: it's keyed by a now-deleted UUID that can never be read+ // again, so leaving it would grow the map without bound across create/fail/delete churn.+ this.sessionErrors.delete(id);+ }+ // NOTE: pendingTeardowns is intentionally NOT cleared here. It is keyed by session NAME and+ // its entries self-remove on settlement (identity-checked). A delete that refused at either+ // fence MUST leave the entry in place — the name is still reserved against the live remover —+ // and a delete that succeeded already saw both fences pass, so no live remover exists.}}@@ -706,6 +764,17 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}}+ // Credential-teardown fence — runs IMMEDIATELY after the read-only findOne + duplicate/cap+ // checks and BEFORE any lifecycle mutation (stop-mark clear, hook, reconnect-state, engine+ // creation, recovery-budget reset) or auth-dir access. A logout teardown that lost its deadline+ // race is still running and ends in an fs.rm of this session's on-disk profile — the same path+ // initializeEngine is about to populate. The fence is keyed by session NAME (the auth-dir key)+ // and FAIL CLOSED: a still-wedged teardown could still rm a fresh profile under this name, so+ // refuse with a retryable 409 instead of proceeding. On a 409, NO lifecycle state is touched+ // (the stop mark, reconnect timer, engine, last status/error, and recovery budget are left as+ // they were) — start() simply did not happen.+ await this.awaitPendingTeardown(session.name);+// A fresh start intentionally (re-)creates the engine — clear any stale stop/delete mark.this.stoppingSessions.delete(id);@@ -730,11 +799,6 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst { maxAttempts, baseDelay } = resolveReconnectConfig(session.config);this.reconnectStates.set(id, { attempts: 0, timer: null, maxAttempts, baseDelay });- // A logout teardown that lost its deadline race may still be running, and it ends in an- // fs.rm of this session's on-disk profile — the same path initializeEngine is about to- // populate. Wait (bounded) for it to settle so the stale rm can't land on fresh credentials.- await this.awaitPendingTeardown(id);-try {await this.initializeEngine(id, session);} catch (err) {@@ -1686,6 +1750,16 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// make the next start() reject the session as "already started" instead of re-initializing it.this.evictAndForceDestroy(id, engine);},+ onCredentialTeardownStarted: (operation: Promise<void>): void => {+ // The adapter fired the moment it began the call that ends in an fs.rm of this session's+ // on-disk auth dir. Track it under the captured session NAME (the auth-dir key) — NOT the+ // UUID, and NOT guarded on this engine still being live: a logout that captured this engine+ // must register its destructive promise even as a concurrent stop()/delete() evicts it,+ // because the rm targets the session name's dir and would otherwise race a (re)created+ // session under that same name. `session.name` is the immutable snapshot captured at+ // initializeEngine entry, so a row delete/recreate under the same name cannot poison the key.+ this.trackPendingCredentialTeardown(session.name, operation);+ },});// engine.initialize() launches Chromium and navigates to WhatsApp Web with no internal timeout:@@ -2254,6 +2328,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatif (this.isLiveEngine(id, oldEngine)) this.engines.delete(id);}+ // Credential-teardown fence — BEFORE engineFactory.create (inside initializeEngine). A logout+ // teardown that lost its deadline race is still running and ends in an fs.rm of this session's+ // on-disk profile — the same path initializeEngine is about to populate. Keyed by session NAME+ // (the auth-dir key) and FAIL CLOSED: a timeout becomes a failed reconnect attempt that is+ // rescheduled WITHOUT touching the auth dir (the catch below schedules the next attempt; no+ // engine was created, so there is nothing to evict and no dir to purge).+ await this.awaitPendingTeardown(session.name);+// Re-initializeawait this.initializeEngine(id, session);@@ -2381,7 +2463,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// 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');+ // The credential fence is keyed by session NAME (the auth-dir key). Captured immutably here so a+ // raw logout that outlives its deadline race is tracked under the right name even if the row is+ // later deleted/recreated.+ const unlinked = await this.teardownEngineSafely(id, engine, e => e.logout(), 'logout', session.name);if (this.isLiveEngine(id, engine)) this.engines.delete(id);await this.updateStatus(id, SessionStatus.DISCONNECTED);