Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): wait for a losing logout teardown before re-creating its profile (#999)

Yudhi Armyndharis493331633295
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 04e18df38..11490814b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,6 +36,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **A wedged logout can no longer delete a freshly re-paired profile** (#994). `teardownEngineSafely`
+ races an engine teardown against a 10s deadline, but the losing promise kept running — and
+ `logout()`'s ends in an `fs.rm` of the session's on-disk profile, the same deterministic path a
+ later `start()` re-creates. A `pupBrowser.close()` wedged past the deadline could therefore land
+ that `rm` on credentials written by a subsequent pairing. Losing `logout()` teardowns are now
+ tracked, and `start()`/`delete()` wait (bounded) for them to settle before touching the profile
+ path; a teardown still wedged past the bound no longer blocks the operator, and that residual
+ window is logged.
+
- **`npm install` from source no longer fails on native Windows, and the whatsapp-web.js backport
actually applies there** (#889). A unified diff's lines must begin with a space, `+`, `-` or `@`, so
neither applier accepts one whose lines end CRLF — both stop at this patch's first empty context
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 8b401da0d..ab749eb68 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -356,6 +356,65 @@ describe('SessionService', () => {
expect(stoppingOf().has('sess-uuid-1')).toBe(false);
});
+ const pendingTeardownsOf = () =>
+ (service as unknown as { pendingTeardowns: Map<string, Promise<void>> }).pendingTeardowns;
+
+ it('start() waits for a logout teardown that lost its deadline race before creating the engine', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ // A logout whose engine promise hangs past the 10s deadline loses the race but keeps
+ // running — and it ends in an fs.rm of the profile that start() is about to re-create.
+ let releaseLogout!: () => void;
+ const wedgedLogout = new Promise<void>(res => {
+ releaseLogout = res;
+ });
+ const engine = { logout: jest.fn().mockReturnValue(wedgedLogout) };
+ enginesOf().set('sess-uuid-1', engine);
+
+ jest.useFakeTimers();
+ try {
+ const logoutCall = service.logout('sess-uuid-1');
+ await jest.advanceTimersByTimeAsync(10_000); // deadline fires; the race is lost
+ await logoutCall;
+ expect(pendingTeardownsOf().has('sess-uuid-1')).toBe(true); // still running past the race
+
+ const startCall = service.start('sess-uuid-1');
+ await jest.advanceTimersByTimeAsync(1_000); // inside the bounded wait
+ expect(engineFactory.create).not.toHaveBeenCalled(); // fresh profile not written yet
+
+ releaseLogout(); // the stale rm now lands BEFORE any fresh credentials exist
+ await startCall;
+ expect(engineFactory.create).toHaveBeenCalledTimes(1);
+ expect(pendingTeardownsOf().has('sess-uuid-1')).toBe(false); // self-removed on settlement
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('start() proceeds after the bounded wait when the teardown stays wedged', async () => {
+ (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)) };
+ enginesOf().set('sess-uuid-1', engine);
+
+ jest.useFakeTimers();
+ try {
+ const logoutCall = service.logout('sess-uuid-1');
+ await jest.advanceTimersByTimeAsync(10_000);
+ await logoutCall;
+
+ 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);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
it('forceKill() force-destroys the engine, reconciles the map, and marks the session stopping', async () => {
(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index fe082b5f8..33b460e13 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -233,6 +233,12 @@ 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.
+ private readonly pendingTeardowns = new Map<string, Promise<void>>();
+
constructor(
@InjectRepository(Session, 'data')
private readonly sessionRepository: Repository<Session>,
@@ -363,6 +369,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
* Resolves to whether the teardown actually completed: `false` means it threw or hit the 10s
* deadline, so the underlying Chromium/socket may still be alive (a caller with an operator-facing
* outcome, like stopOrphanEngines, must surface that instead of reporting a clean stop).
+ *
+ * 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.
*/
private async teardownEngineSafely(
sessionId: string,
@@ -370,10 +381,23 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
teardown: (e: IWhatsAppEngine) => Promise<void>,
label: 'destroy' | 'disconnect' | 'force-destroy' | 'logout',
): 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. Identity-checked on removal so a
+ // newer teardown's entry isn't evicted by an older one settling.
+ const tracked = raw.catch(() => undefined);
+ this.pendingTeardowns.set(sessionId, tracked);
+ void tracked.finally(() => {
+ if (this.pendingTeardowns.get(sessionId) === tracked) {
+ this.pendingTeardowns.delete(sessionId);
+ }
+ });
+ }
let timer: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
- teardown(engine),
+ raw,
new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error(`engine.${label}() timed out`)), 10_000);
}),
@@ -390,6 +414,34 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
}
+ /**
+ * 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.
+ */
+ private async awaitPendingTeardown(id: string): Promise<void> {
+ const pending = this.pendingTeardowns.get(id);
+ if (!pending) return;
+
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const settled = await Promise.race([
+ pending.then(() => true),
+ new Promise<boolean>(resolve => {
+ timer = setTimeout(() => resolve(false), 10_000);
+ }),
+ ]);
+ 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' },
+ );
+ }
+ }
+
/**
* 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
@@ -547,7 +599,9 @@ 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.
+ // 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);
await this.engineFactory.purgeSessionData(session.name);
} finally {
// Always clear the teardown mark so a later recreate/start with this id isn't suppressed.
@@ -616,6 +670,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
const { 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) {