Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): stop auto-start resurrecting terminally unlinked sessions

Yudhi Armyndharis7de141f18d5a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5a7334001..ae823eac6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -33,6 +33,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
emitting until then, so a repeat pairing request answers 409 instead of overwriting the linked identity.
- Baileys: a QR that finishes rendering after its socket dropped is discarded instead of marking the session
`qr_ready`.
+- A WhatsApp-initiated unlink now clears the session's `phone` the way an operator logout does, so a restart
+ no longer relaunches the unlinked session into a QR nobody asked for; the next successful link sets it
+ again.
## [0.23.2] - 2026-08-23
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index a6b1d9dcb..5f548d74d 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -614,7 +614,8 @@ the old credentials remain usable depends on where the failure happened, and the
report which.
With `AUTO_START_SESSIONS=true`, auto-start selects sessions whose `phone` is non-null. Both a `200`
-and a `502` logout clear `phone`, so neither is auto-started on boot — an incomplete-logout (`502`)
+and a `502` logout clear `phone`, and a WhatsApp-initiated unlink reported by a running engine clears
+it the same way, so none of those are auto-started on boot — an incomplete-logout (`502`)
session must be started explicitly and the logout retried by hand. A session that must stay down can
simply be left as-is.
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 8be6f79a1..f98f4d555 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -518,11 +518,13 @@ export class SessionEngineLifecycle {
* gateway always has one and this fence is live single-node too.
*
* SCOPE, stated plainly so the guarantee is not read wider than it is. Fenced: the three status
- * writes in the event wiring, the exhausted-reconnect FAILED, and the start-path FAILED in
- * controls. NOT fenced: handleEngineReady's direct row write and handleEngineDisconnected's
- * DISCONNECTED — both statuses are in the boot reset's activeStatuses AND in TAKEOVER_STATUSES,
- * so a wrong one self-heals, unlike FAILED. The gate is also a point-in-time read: `owned` can
- * change while the awaited write is in flight, so this narrows the window rather than closing it.
+ * writes in the event wiring, the exhausted-reconnect FAILED, the start-path FAILED in controls,
+ * and the terminal-unlink phone clear in handleEngineDisconnected (like FAILED, a wrongly nulled
+ * phone does not self-heal until the owner's next READY). NOT fenced: handleEngineReady's direct
+ * row write and handleEngineDisconnected's DISCONNECTED — both statuses are in the boot reset's
+ * activeStatuses AND in TAKEOVER_STATUSES, so a wrong one self-heals, unlike FAILED. The gate is
+ * also a point-in-time read: `owned` can change while the awaited write is in flight, so this
+ * narrows the window rather than closing it.
*/
private ownsSession(id: string): boolean {
return nodeOwnsSession(this.ownership, id);
@@ -837,6 +839,23 @@ export class SessionEngineLifecycle {
metadata: { reason },
errorMessage: `WhatsApp unlinked this device (${reason}); the session must be re-paired with a fresh QR`,
});
+ // The unlink is terminal: reconnecting can only land on a QR, so the next boot must not
+ // resurrect the session (auto-start and the takeover sweep both key on a non-null phone),
+ // exactly what logout() already ensures for operator-driven unlinks. The reconnect scheduled
+ // below still runs and shows one QR now; `session` was captured above, so its previouslyLinked
+ // flag is unaffected by this row write. onReady rewrites phone on the next successful link.
+ // Fenced on ownership, unlike the DISCONNECTED write below: a wrongly nulled phone does not
+ // self-heal until the owner's next READY, the same reason the exhausted-reconnect FAILED write
+ // is fenced. Fire-and-forget: no await may sit between the identity fences above and below.
+ if (this.ownsSession(id)) {
+ void this.sessionRepository.update(id, { phone: null }).catch((err: unknown) =>
+ this.logger.warn('Failed to clear phone after a terminal unlink', {
+ sessionId: id,
+ error: String(err),
+ action: 'unlink_phone_clear_failed',
+ }),
+ );
+ }
}
void this.webhookService.dispatch(id, 'session.disconnected', { sessionId: id, reason });
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index a13d10183..3162a1a45 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -2865,6 +2865,63 @@ describe('SessionService', () => {
expect(auditService.logWarn).not.toHaveBeenCalled();
});
+ // A terminal unlink leaves credentials that can never reach READY again, so the row must leave
+ // the boot auto-start query and the takeover sweep (both key on a non-null phone), exactly as
+ // logout() already ensures. The in-process reconnect still shows one QR: scheduleReconnect gets
+ // the row object captured before the write, so its previouslyLinked flag survives.
+ it.each(['LOGOUT', 'UNPAIRED', 'UNPAIRED_IDLE', 'logged out'])(
+ 'clears phone on a terminal unlink (%s) without touching the captured reconnect row',
+ async reason => {
+ const callbacks = await startAndCapture();
+ const reconnectSpy = jest
+ .spyOn(lifecycle as unknown as { scheduleReconnect: (id: string, s: unknown) => void }, 'scheduleReconnect')
+ .mockImplementation(() => {});
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ phone: '628123' }));
+ (repository.update as jest.Mock).mockClear();
+
+ await disconnectAndFlush(callbacks, reason);
+
+ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { phone: null });
+ const [, passedSession] = reconnectSpy.mock.calls[0] as [string, Session];
+ expect(passedSession.phone).toBe('628123');
+ },
+ );
+
+ it.each(['TIMEOUT', 'NAVIGATION', 'socket closed'])(
+ 'does not clear phone on a transient drop (%s)',
+ async reason => {
+ const callbacks = await startAndCapture();
+ jest
+ .spyOn(lifecycle as unknown as { scheduleReconnect: (id: string, s: unknown) => void }, 'scheduleReconnect')
+ .mockImplementation(() => {});
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ phone: '628123' }));
+ (repository.update as jest.Mock).mockClear();
+
+ await disconnectAndFlush(callbacks, reason);
+
+ expect(repository.update).not.toHaveBeenCalledWith('sess-uuid-1', { phone: null });
+ },
+ );
+
+ // The phone write is ownership-fenced: unlike the DISCONNECTED status, a wrongly nulled phone
+ // does not self-heal until the owner's next READY, so a node whose lease lapsed must not write
+ // it onto a row a peer now runs (the owner receives the same terminal reason and clears it).
+ it('does not clear phone for a terminal unlink when this node no longer owns the session', async () => {
+ const callbacks = await startAndCapture();
+ jest
+ .spyOn(lifecycle as unknown as { scheduleReconnect: (id: string, s: unknown) => void }, 'scheduleReconnect')
+ .mockImplementation(() => {});
+ Object.assign(lifecycle as unknown as Record<string, unknown>, { ownership: { owns: () => false } });
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ phone: '628123' }));
+ (repository.update as jest.Mock).mockClear();
+ try {
+ await disconnectAndFlush(callbacks, 'LOGOUT');
+ expect(repository.update).not.toHaveBeenCalledWith('sess-uuid-1', { phone: null });
+ } finally {
+ Object.assign(lifecycle as unknown as Record<string, unknown>, { ownership: undefined });
+ }
+ });
+
// The audit row is a disconnect side effect like the webhook and the socket emit, so it belongs
// behind the SAME post-await identity fence. Superseding before the call would only exercise the
// wiring's entry check, which would pass wherever the emit sat — so supersede the engine while
@@ -2892,6 +2949,7 @@ describe('SessionService', () => {
await handled;
expect(auditService.logWarn).not.toHaveBeenCalled();
+ expect(repository.update).not.toHaveBeenCalledWith('sess-uuid-1', { phone: null });
});
it('ignores onReady from an engine that was torn down (post-stop window)', async () => {