Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): reject a QR rescan by a different WhatsApp account

Yudhi Armyndharis8e556d132905
diff --git a/openapi.json b/openapi.json
index 208724c80..84f4e2304 100644
--- a/openapi.json
+++ b/openapi.json
@@ -31,6 +31,7 @@
"session_disconnected",
"session_restricted",
"session_restriction_lifted",
+ "session_rebind_rejected",
"message_sent",
"message_failed",
"send_pacing_blocked",
diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.ts
index 25f9c2bfd..75ba7ff10 100644
--- a/src/modules/audit/entities/audit-log.entity.ts
+++ b/src/modules/audit/entities/audit-log.entity.ts
@@ -33,6 +33,10 @@ export enum AuditAction {
// an account was restricted and for how long.
SESSION_RESTRICTED = 'session_restricted',
SESSION_RESTRICTION_LIFTED = 'session_restriction_lifted',
+ // A ready link was refused because a different WhatsApp number scanned a session already bound to
+ // another. Rare, security-relevant, and the in-memory error store that serves the reason to the API
+ // does not survive a restart, so the audit row is the only durable record that a rebind was blocked.
+ SESSION_REBIND_REJECTED = 'session_rebind_rejected',
// Message events
MESSAGE_SENT = 'message_sent',
diff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.ts
index 23b0526a3..da48432e7 100644
--- a/src/modules/session/logout-teardown-race.spec.ts
+++ b/src/modules/session/logout-teardown-race.spec.ts
@@ -140,6 +140,43 @@ describe('SessionService logout() name-scoped teardown fence', () => {
const lastStatusOf = () =>
(lifecycle as unknown as { lastDispatchedStatus: Map<string, unknown> }).lastDispatchedStatus;
+ const rejectRebind = (previous: string, incoming: string, engine: unknown) =>
+ (
+ lifecycle as unknown as {
+ rejectRebind: (id: string, e: unknown, name: string, prev: string, inc: string) => Promise<void>;
+ }
+ ).rejectRebind(SESSION_UUID, engine, SESSION_NAME, previous, incoming);
+
+ it('rejectRebind logs the wrong account out, fails the session, and keeps the original binding', async () => {
+ const logout = jest.fn().mockResolvedValue(undefined);
+ const engine = { logout };
+ enginesOf().set(SESSION_UUID, engine);
+
+ await rejectRebind('628111', '628999', engine);
+
+ // The wrong account is torn down, the session is parked in FAILED with a reason naming both
+ // numbers, and the engine is dropped. The original binding is preserved: no `{ phone: null }`.
+ expect(logout).toHaveBeenCalledTimes(1);
+ expect(lastStatusOf().get(SESSION_UUID)).toBe(SessionStatus.FAILED);
+ expect(errorsOf().get(SESSION_UUID)).toEqual(expect.stringContaining('628111'));
+ expect(errorsOf().get(SESSION_UUID)).toEqual(expect.stringContaining('628999'));
+ expect(enginesOf().has(SESSION_UUID)).toBe(false);
+ expect(stoppingOf().has(SESSION_UUID)).toBe(true);
+ expect(repository.update).not.toHaveBeenCalledWith(SESSION_UUID, { phone: null });
+ });
+
+ it('rejectRebind on a stale engine does nothing (isLiveEngine gate)', async () => {
+ const logout = jest.fn().mockResolvedValue(undefined);
+ const staleEngine = { logout };
+ // A DIFFERENT engine is the live one, so the stale handler must not log out or fail the session.
+ enginesOf().set(SESSION_UUID, { logout: jest.fn() });
+
+ await rejectRebind('628111', '628999', staleEngine);
+
+ expect(logout).not.toHaveBeenCalled();
+ expect(lastStatusOf().get(SESSION_UUID)).not.toBe(SessionStatus.FAILED);
+ });
+
it('quick-settling teardown: start waits for it, then proceeds', async () => {
let releaseLogout!: () => void;
const wedgedLogout = new Promise<void>(res => {
diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.ts
index 6184c43ba..366b622ac 100644
--- a/src/modules/session/session-engine-event-wiring.ts
+++ b/src/modules/session/session-engine-event-wiring.ts
@@ -18,6 +18,7 @@ import {
CallOutcomeEvent,
} from '../../engine/interfaces/whatsapp-engine.interface';
import { type createLogger } from '../../common/services/logger.service';
+import { userPart } from '../../engine/identity/wa-id';
import { SessionEngineLeafEvents } from './session-engine-leaf-events';
/**
@@ -41,6 +42,18 @@ export interface SessionEngineWiringHost {
*/
ownsSession(id: string): boolean;
handleEngineReady(id: string, engine: IWhatsAppEngine, phone: string, pushName: string): void;
+ /**
+ * Refuse a ready link whose account differs from the one this session is bound to: tear the wrong
+ * account's engine down (logout wipes its credentials), land the session in FAILED, and record why.
+ * Never persists the incoming account, and deliberately keeps the original binding.
+ */
+ rejectRebind(
+ id: string,
+ engine: IWhatsAppEngine,
+ sessionName: string,
+ previousPhone: string,
+ incomingPhone: string,
+ ): Promise<void>;
handleEngineDisconnected(id: string, engine: IWhatsAppEngine, reason: string): Promise<void>;
updateStatus(id: string, status: SessionStatus): Promise<void>;
cancelReconnect(id: string): void;
@@ -86,8 +99,10 @@ export class SessionEngineEventWiring {
}
/**
- * `previouslyLinked` is whether the session row carried a phone when this engine started, i.e.
- * it had completed a link before. A QR from such an engine means the stored credentials are gone
+ * `previousPhone` is the phone the session row carried when this engine started (null on a fresh
+ * session), i.e. it had completed a link before. Its presence drives the relink warning below; its
+ * value gates the onReady account-binding check that refuses a different number's rescan.
+ * A QR from a previously-linked engine means the stored credentials are gone
* or no longer accepted, and when that happened while the engine was down nothing else in the
* log says so, hence the warning below. One-shot per engine start: a lifecycle reconnect builds a
* new table from the row, which still carries the phone, and warns again.
@@ -97,8 +112,11 @@ export class SessionEngineEventWiring {
engine: IWhatsAppEngine,
sessionName: string,
host: SessionEngineWiringHost,
- previouslyLinked = false,
+ previousPhone: string | null = null,
): EngineEventCallbacks {
+ // The phone this session was bound to when this engine started (null on a fresh session). Its
+ // presence is the relink signal used below; its value gates onReady's account-binding check.
+ const previouslyLinked = Boolean(previousPhone);
let relinkWarned = false;
/**
* Persist an engine-driven status, but only while this node still owns the session.
@@ -163,7 +181,17 @@ export class SessionEngineEventWiring {
persistStatus(SessionStatus.QR_READY);
},
- onReady: (phone, pushName): void => host.handleEngineReady(id, engine, phone, pushName),
+ onReady: (phone, pushName): void => {
+ // Account-binding guard: a ready link whose number differs from the one this session is
+ // already bound to is a different account scanning its QR (a takeover), not a re-link. Refuse
+ // it rather than silently overwrite the binding. An empty incoming phone (wwjs can report one)
+ // is not identifiable, so it is never treated as a mismatch.
+ if (previousPhone && phone && userPart(phone) !== userPart(previousPhone)) {
+ void host.rejectRebind(id, engine, sessionName, previousPhone, phone);
+ return;
+ }
+ host.handleEngineReady(id, engine, phone, pushName);
+ },
onMessage: (message): void => host.messages.handleInboundMessage(id, engine, message),
onHistoryMessages: (messages): void => {
if (!host.isLiveEngine(id, engine)) return;
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 669f765ba..68ca45009 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -292,6 +292,8 @@ export class SessionEngineLifecycle {
isLiveEngine: (id, engine) => this.isLiveEngine(id, engine),
ownsSession: id => this.ownsSession(id),
handleEngineReady: (id, engine, phone, pushName) => this.handleEngineReady(id, engine, phone, pushName),
+ rejectRebind: (id, engine, sessionName, previousPhone, incomingPhone) =>
+ this.rejectRebind(id, engine, sessionName, previousPhone, incomingPhone),
handleEngineDisconnected: (id, engine, reason) => this.handleEngineDisconnected(id, engine, reason),
updateStatus: (id, status) => this.updateStatus(id, status),
cancelReconnect: id => this.cancelReconnect(id),
@@ -599,7 +601,7 @@ export class SessionEngineLifecycle {
// lifecycle's live methods/state through the wiringHost built in the constructor.
// `session.name` is handed over as the immutable snapshot onCredentialTeardownStarted keys on.
const initPromise = engine.initialize(
- this.eventWiring.buildCallbacks(id, engine, session.name, this.wiringHost, Boolean(session.phone)),
+ this.eventWiring.buildCallbacks(id, engine, session.name, this.wiringHost, session.phone ?? null),
);
// engine.initialize() launches Chromium and navigates to WhatsApp Web with no internal timeout:
@@ -673,6 +675,67 @@ export class SessionEngineLifecycle {
}
}
+ /**
+ * Refuse a ready link whose account differs from the one this session is bound to. Reached only via
+ * the account-binding guard in SessionEngineEventWiring, i.e. the session already carries a phone and
+ * a DIFFERENT number scanned its QR. The incoming account is never persisted: log the reason, tear
+ * the wrong account's engine down (logout wipes its on-disk credentials and unlinks the device), land
+ * the session in FAILED, and audit it. The original `phone` binding is deliberately left in place so
+ * a subsequent stranger scan is rejected the same way, and the operator can see which number it is
+ * bound to. A caller-initiated logout latches its own teardown flags on both engines, so the
+ * disconnected handler (which would null the stored phone) never fires here.
+ */
+ private async rejectRebind(
+ id: string,
+ engine: IWhatsAppEngine,
+ sessionName: string,
+ previousPhone: string,
+ incomingPhone: string,
+ ): Promise<void> {
+ if (!this.isLiveEngine(id, engine)) return;
+ const reason =
+ `Link rejected: this session is bound to ${previousPhone}, but a different WhatsApp number ` +
+ `(${incomingPhone}) scanned its QR. Re-pair the original number, or delete the session to bind a new one.`;
+ this.logger.warn('Rejected a QR link from a different WhatsApp account', {
+ sessionId: id,
+ previousPhone,
+ incomingPhone,
+ action: 'rebind_rejected',
+ });
+ // Terminal, not a flap: suppress the reconnect/re-init auto-recovery and stop the watchdog. FAILED
+ // (persisted) already excludes the session from boot auto-start and the takeover sweep; a manual
+ // start() clears stoppingSessions. cancelReconnect is defensive: a caller-initiated logout does not
+ // schedule a reconnect, but a stray timer from before the ready must not fire against a dead engine.
+ this.stoppingSessions.add(id);
+ this.cancelReconnect(id);
+ this.watchdog.clear(id);
+ this.sessionErrors.set(id, reason);
+ // Record the rejection before the teardown, so it lands even if a concurrent start() replaces the
+ // engine while logout runs and the re-fence below returns early.
+ void this.auditService?.logWarn(AuditAction.SESSION_REBIND_REJECTED, {
+ sessionId: id,
+ metadata: { previousPhone, incomingPhone },
+ errorMessage: reason,
+ });
+ // logout() wipes the wrong account's credentials and removes this device from that account.
+ await this.teardownEngineSafely(id, engine, e => e.logout(), 'logout', sessionName);
+ // Re-fence after the await, as handleEngineDisconnected does: a concurrent start() may have
+ // replaced the engine while logout ran. If this handler is now stale it must not delete the new
+ // engine or write FAILED over a fresh start.
+ if (!this.isLiveEngine(id, engine)) return;
+ this.engines.deleteIfLive(id, engine);
+ // Fenced on ownership like every engine-driven terminal write: a lapsed lease must not park a
+ // peer's session unrecoverably in FAILED. Defensively caught like handleEngineReady's row write.
+ if (this.ownsSession(id)) {
+ await this.updateStatus(id, SessionStatus.FAILED).catch(err =>
+ this.logger.warn('Failed to persist the rebind-rejected FAILED state', {
+ sessionId: id,
+ error: err instanceof Error ? err.message : String(err),
+ }),
+ );
+ }
+ }
+
/** Engine callback body, lifted out of initializeEngine so the wiring table stays readable. */
private handleEngineReady(id: string, engine: IWhatsAppEngine, phone: string, pushName: string): void {
if (!this.isLiveEngine(id, engine)) return;
diff --git a/src/modules/session/session-ownership-status-fence.spec.ts b/src/modules/session/session-ownership-status-fence.spec.ts
index 62b42ed2f..d074e215c 100644
--- a/src/modules/session/session-ownership-status-fence.spec.ts
+++ b/src/modules/session/session-ownership-status-fence.spec.ts
@@ -75,6 +75,68 @@ describe('engine status writes are fenced by ownership', () => {
});
});
+describe('onReady account-binding guard (rejects a different number rescanning a bound session)', () => {
+ const ENGINE = { logout: jest.fn() } as unknown as IWhatsAppEngine;
+
+ const build = (previousPhone: string | null) => {
+ const handleEngineReady = jest.fn();
+ const rejectRebind = jest.fn().mockResolvedValue(undefined);
+ const host = {
+ isLiveEngine: () => true,
+ ownsSession: () => true,
+ handleEngineReady,
+ rejectRebind,
+ updateStatus: jest.fn().mockResolvedValue(undefined),
+ cancelReconnect: jest.fn(),
+ sessionErrors: { set: jest.fn(), clear: jest.fn(), get: jest.fn() },
+ sessionRestrictions: { set: jest.fn(), clear: jest.fn(), get: jest.fn() },
+ presence: { set: jest.fn(), clear: jest.fn() },
+ messages: { handleInboundMessage: jest.fn(), handleHistoryMessages: jest.fn() },
+ webhookService: { dispatch: jest.fn() },
+ eventsGateway: { emitQRCode: jest.fn(), emitSessionStatus: jest.fn() },
+ hookManager: { execute: jest.fn().mockResolvedValue(undefined) },
+ } as unknown as SessionEngineWiringHost;
+ const wiring = new SessionEngineEventWiring({ logger: createLogger('test') });
+ const cb = wiring.buildCallbacks('sess-1', ENGINE, 'sess-1-name', host, previousPhone);
+ return { cb, handleEngineReady, rejectRebind };
+ };
+
+ it('rejects a ready link whose number differs from the stored binding', () => {
+ const { cb, handleEngineReady, rejectRebind } = build('628111');
+ cb.onReady?.('628999', 'Stranger');
+ expect(rejectRebind).toHaveBeenCalledWith('sess-1', ENGINE, 'sess-1-name', '628111', '628999');
+ expect(handleEngineReady).not.toHaveBeenCalled();
+ });
+
+ it('accepts a re-link from the SAME number (no reject)', () => {
+ const { cb, handleEngineReady, rejectRebind } = build('628111');
+ cb.onReady?.('628111', 'Owner');
+ expect(handleEngineReady).toHaveBeenCalledWith('sess-1', ENGINE, '628111', 'Owner');
+ expect(rejectRebind).not.toHaveBeenCalled();
+ });
+
+ it('accepts the first link on a fresh session (no stored phone)', () => {
+ const { cb, handleEngineReady, rejectRebind } = build(null);
+ cb.onReady?.('628111', 'Owner');
+ expect(handleEngineReady).toHaveBeenCalledWith('sess-1', ENGINE, '628111', 'Owner');
+ expect(rejectRebind).not.toHaveBeenCalled();
+ });
+
+ it('treats a device-suffixed id as the same number (userPart compare, not raw)', () => {
+ const { cb, handleEngineReady, rejectRebind } = build('628111');
+ cb.onReady?.('628111:3', 'Owner');
+ expect(handleEngineReady).toHaveBeenCalled();
+ expect(rejectRebind).not.toHaveBeenCalled();
+ });
+
+ it('never rejects on an empty incoming phone (an account it could not identify)', () => {
+ const { cb, handleEngineReady, rejectRebind } = build('628111');
+ cb.onReady?.('', '');
+ expect(handleEngineReady).toHaveBeenCalledWith('sess-1', ENGINE, '', '');
+ expect(rejectRebind).not.toHaveBeenCalled();
+ });
+});
+
describe('SessionOwnershipService.owns', () => {
/**
* Populated through the REAL claim()/release() path, not by poking the Set.