Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): drop QR replies that a newer one replaced

Yudhi Armyndharis49bf7d1ffe57
diff --git a/dashboard/src/hooks/useSessionPairing.test.ts b/dashboard/src/hooks/useSessionPairing.test.ts
index fb4fd2641..8ec5c192d 100644
--- a/dashboard/src/hooks/useSessionPairing.test.ts
+++ b/dashboard/src/hooks/useSessionPairing.test.ts
@@ -140,3 +140,236 @@ test('a session that became ready closes the modal without a request', async ()
assert.equal(outcome.pollCalls, 0);
assert.equal(outcome.qrData, null);
});
+
+interface QrReplyPlan {
+ path: string;
+ answer: Response | Promise<Response>;
+ method?: string;
+}
+
+function qrReply(code: string): Response {
+ return new Response(JSON.stringify({ qrCode: code, status: 'qr_ready' }), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+function pendingQrReply(): { promise: Promise<Response>; resolve: (reply: Response) => void } {
+ let resolve!: (reply: Response) => void;
+ const promise = new Promise<Response>(accept => {
+ resolve = accept;
+ });
+ return { promise, resolve };
+}
+
+function planQrReplies(...plans: QrReplyPlan[]): void {
+ mock.method(globalThis, 'fetch', (input: RequestInfo | URL, init?: RequestInit) => {
+ const plan = plans.shift();
+ assert.ok(plan, `No response planned for ${String(input)}`);
+ assert.equal(new URL(String(input), 'http://localhost').pathname, plan.path);
+ assert.equal(init?.method ?? 'GET', plan.method ?? 'GET');
+ return Promise.resolve(plan.answer);
+ });
+}
+
+const settleQrReply = async () => {
+ for (let i = 0; i < 8; i++) await Promise.resolve();
+ await new Promise<void>(resolve => setImmediate(resolve));
+};
+
+function renderQrVisit() {
+ mock.timers.enable({ apis: ['setInterval'] });
+ const sessions = [session, { ...session, id: 's2', name: 'second' }];
+ return rtl.renderHook(() =>
+ useSessionPairing({
+ sessions,
+ sessionsRef: { current: sessions },
+ reloadSessions: async () => sessions,
+ }),
+ );
+}
+
+test('a QR reply from an earlier visit cannot replace the reopened session code', async () => {
+ const old = pendingQrReply(),
+ current = pendingQrReply();
+ planQrReplies(
+ { path: '/api/sessions/s1/qr', answer: old.promise },
+ { path: '/api/sessions/s1/qr', answer: current.promise },
+ );
+ const { result } = renderQrVisit();
+ let first!: Promise<void>, second!: Promise<void>;
+ await rtl.act(async () => {
+ first = result.current.handleShowQR('s1');
+ await settleQrReply();
+ });
+ rtl.act(() => result.current.handleCloseQRModal());
+ await rtl.act(async () => {
+ second = result.current.handleShowQR('s1');
+ await settleQrReply();
+ });
+ await rtl.act(async () => {
+ current.resolve(qrReply('CURRENT'));
+ await second;
+ });
+ assert.equal(result.current.qrData?.qrCode, 'CURRENT');
+ await rtl.act(async () => {
+ old.resolve(qrReply('RETIRED'));
+ await first;
+ });
+ assert.equal(result.current.qrData?.qrCode, 'CURRENT');
+});
+
+test('a newer QR push is kept when an older GET answers', async () => {
+ const old = pendingQrReply();
+ planQrReplies({ path: '/api/sessions/s1/qr', answer: old.promise });
+ const { result } = renderQrVisit();
+ let opening!: Promise<void>;
+ await rtl.act(async () => {
+ opening = result.current.handleShowQR('s1');
+ await settleQrReply();
+ });
+ rtl.act(() => result.current.applyQrPush({ sessionId: 's1', qrCode: 'PUSH' }));
+ await rtl.act(async () => {
+ old.resolve(qrReply('GET'));
+ await opening;
+ });
+ assert.equal(result.current.qrData?.qrCode, 'PUSH');
+});
+
+for (const status of [200, 404]) {
+ test(`an earlier poll status ${status} cannot close a reopened session modal`, async () => {
+ const old = pendingQrReply();
+ const temporaryFailure = new Response(JSON.stringify({ message: 'Temporary failure' }), { status: 503 });
+ planQrReplies(
+ { path: '/api/sessions/s1/qr', answer: qrReply('FIRST') },
+ { path: '/api/sessions/s1/qr', answer: temporaryFailure },
+ { path: '/api/sessions/s1', answer: old.promise },
+ { path: '/api/sessions/s1/qr', answer: qrReply('REOPENED') },
+ );
+ const { result } = renderQrVisit();
+ await rtl.act(async () => {
+ await result.current.handleShowQR('s1');
+ });
+ await rtl.act(async () => {
+ mock.timers.tick(5000);
+ await settleQrReply();
+ });
+ rtl.act(() => result.current.handleCloseQRModal());
+ await rtl.act(async () => {
+ await result.current.handleShowQR('s1');
+ });
+ await rtl.act(async () => {
+ old.resolve(
+ new Response(JSON.stringify(status === 200 ? { ...session, status: 'failed' } : { message: 'Gone' }), {
+ status,
+ }),
+ );
+ await settleQrReply();
+ });
+ assert.equal(result.current.qrData?.qrCode, 'REOPENED');
+ });
+}
+
+for (const firstToAnswer of ['older', 'newer']) {
+ test(`concurrent QR reads keep the latest answer when ${firstToAnswer} resolves first`, async () => {
+ const older = pendingQrReply(),
+ newer = pendingQrReply();
+ planQrReplies(
+ { path: '/api/sessions/s1/qr', answer: older.promise },
+ { path: '/api/sessions/s1/qr', answer: newer.promise },
+ );
+ const { result } = renderQrVisit();
+ let opening!: Promise<void>;
+ await rtl.act(async () => {
+ opening = result.current.handleShowQR('s1');
+ await settleQrReply();
+ });
+ await rtl.act(async () => {
+ mock.timers.tick(5000);
+ await settleQrReply();
+ });
+ await rtl.act(async () => {
+ if (firstToAnswer === 'older') older.resolve(qrReply('OLDER'));
+ else newer.resolve(qrReply('NEWER'));
+ await settleQrReply();
+ });
+ await rtl.act(async () => {
+ if (firstToAnswer === 'older') newer.resolve(qrReply('NEWER'));
+ else older.resolve(qrReply('OLDER'));
+ await opening;
+ await settleQrReply();
+ });
+ assert.equal(result.current.qrData?.qrCode, 'NEWER');
+ });
+}
+
+test('an old QR read cannot change a modal opened for another session', async () => {
+ const old = pendingQrReply();
+ planQrReplies(
+ { path: '/api/sessions/s1/qr', answer: old.promise },
+ { path: '/api/sessions/s2/qr', answer: qrReply('SECOND') },
+ );
+ const { result } = renderQrVisit();
+ let first!: Promise<void>;
+ await rtl.act(async () => {
+ first = result.current.handleShowQR('s1');
+ await settleQrReply();
+ });
+ rtl.act(() => result.current.handleCloseQRModal());
+ await rtl.act(async () => {
+ await result.current.handleShowQR('s2');
+ });
+ await rtl.act(async () => {
+ old.resolve(qrReply('FIRST'));
+ await first;
+ });
+ assert.equal(result.current.qrData?.sessionId, 's2');
+ assert.equal(result.current.qrData?.qrCode, 'SECOND');
+});
+
+test('phone pairing keeps its visit generation when a QR push arrives', async () => {
+ const old = pendingQrReply(),
+ current = pendingQrReply();
+ planQrReplies(
+ { path: '/api/sessions/s1/qr', answer: qrReply('FIRST') },
+ { path: '/api/sessions/s1/pairing-code', method: 'POST', answer: old.promise },
+ { path: '/api/sessions/s1/qr', answer: qrReply('SECOND') },
+ { path: '/api/sessions/s1/pairing-code', method: 'POST', answer: current.promise },
+ );
+ const { result } = renderQrVisit();
+ await rtl.act(async () => {
+ await result.current.handleShowQR('s1');
+ });
+ rtl.act(() => {
+ result.current.selectPairingTab(true);
+ result.current.setPhoneNumber('15550000001');
+ });
+ let first!: Promise<void>, second!: Promise<void>;
+ await rtl.act(async () => {
+ first = result.current.handleGeneratePairingCode();
+ await settleQrReply();
+ });
+ rtl.act(() => result.current.handleCloseQRModal());
+ await rtl.act(async () => {
+ await result.current.handleShowQR('s1');
+ });
+ rtl.act(() => {
+ result.current.selectPairingTab(true);
+ result.current.setPhoneNumber('15550000002');
+ });
+ await rtl.act(async () => {
+ second = result.current.handleGeneratePairingCode();
+ await settleQrReply();
+ });
+ rtl.act(() => result.current.applyQrPush({ sessionId: 's1', qrCode: 'NEW-QR' }));
+ await rtl.act(async () => {
+ current.resolve(new Response(JSON.stringify({ pairingCode: 'NEW-PAIR', status: 'qr_ready' })));
+ await second;
+ });
+ await rtl.act(async () => {
+ old.resolve(new Response(JSON.stringify({ pairingCode: 'OLD-PAIR', status: 'qr_ready' })));
+ await first;
+ });
+ assert.equal(result.current.pairingCode, 'NEW-PAIR');
+ assert.equal(result.current.requestingPairing, false);
+});
diff --git a/dashboard/src/hooks/useSessionPairing.ts b/dashboard/src/hooks/useSessionPairing.ts
index 2e3f59d92..211460240 100644
--- a/dashboard/src/hooks/useSessionPairing.ts
+++ b/dashboard/src/hooks/useSessionPairing.ts
@@ -61,15 +61,34 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Use
// on screen: not in a modal since opened for another session, nor in the same session's modal reset
// to a blank form.
const pairingGen = useRef(0);
+ // QR snapshots belong to one modal visit and cannot replace a newer read or push.
+ const qrVisit = useRef<{ sessionId: string | null; requested: number; applied: number }>({
+ sessionId: null,
+ requested: 0,
+ applied: 0,
+ });
+
+ useEffect(
+ () => () => {
+ qrVisit.current = { sessionId: null, requested: 0, applied: 0 };
+ pairingGen.current += 1;
+ },
+ [],
+ );
const fetchQR = useCallback(
async (sessionId: string) => {
+ const visit = qrVisit.current;
+ if (visit.sessionId !== sessionId) return;
+ const request = ++visit.requested;
+ const isCurrent = () => qrVisit.current === visit && request >= visit.applied;
// Guard: if session is already connected, stop polling immediately. Read the ref (not `sessions`)
// so fetchQR keeps a stable identity — otherwise the polling interval is torn down and restarted on
// every sessions update.
const currentSession = sessionsRef.current.find(s => s.id === sessionId);
if (currentSession?.status === 'ready') {
- setQrData(null);
+ qrVisit.current = { sessionId: null, requested: 0, applied: 0 };
+ setQrData(cur => (cur?.sessionId === sessionId ? null : cur));
return;
}
// Poll only while a QR actually exists to refresh (qr_ready): before that the endpoint 400s
@@ -77,14 +96,16 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Use
if (currentSession?.status !== 'qr_ready') return;
try {
const qr = await sessionApi.getQR(sessionId);
- // Every write after an await is keyed on the session: the modal may have been closed, or
- // opened for another session, while the request was in flight.
+ if (!isCurrent()) return;
+ visit.applied = request;
setQrData(cur => (cur?.sessionId === sessionId ? { ...cur, qrCode: qr.qrCode } : cur));
if (qr.status === 'ready') {
+ qrVisit.current = { sessionId: null, requested: 0, applied: 0 };
setQrData(cur => (cur?.sessionId === sessionId ? null : cur));
reloadSessions();
}
} catch {
+ if (!isCurrent()) return;
// Keep qrData alive so the polling interval keeps retrying until the QR
// is ready. Only stop polling if the session itself has failed. 'authenticating' is included so
// the modal (and the pairing-code panel mounted in it) survives the brief post-link handshake
@@ -100,8 +121,11 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Use
const status = (error as { status?: number }).status;
if (status === undefined || status === 429 || status >= 500) return;
}
+ if (!isCurrent()) return;
+ visit.applied = request;
const stillInitializing = updated && ['initializing', 'qr_ready', 'authenticating'].includes(updated.status);
if (!stillInitializing) {
+ qrVisit.current = { sessionId: null, requested: 0, applied: 0 };
setQrData(cur => (cur?.sessionId === sessionId ? null : cur));
reloadSessions();
}
@@ -123,6 +147,7 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Use
const handleCloseQRModal = useCallback(() => {
pairingGen.current += 1;
+ qrVisit.current = { sessionId: null, requested: 0, applied: 0 };
setRequestingPairing(false);
setQrData(null);
setPairingMode(false);
@@ -172,6 +197,8 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Use
// Reset any pairing sub-state from a previous open so a freshly opened modal never shows a
// stale code/phone belonging to a different session.
pairingGen.current += 1;
+ const visit = { sessionId: id, requested: 0, applied: 0 };
+ qrVisit.current = visit;
setPairingMode(false);
setPhoneNumber('');
setPairingCode(null);
@@ -184,9 +211,11 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Use
// (the engine hasn't produced one), and the WS session.qr push + gated 5s poll deliver it
// without spamming the console with expected failures.
if (session?.status === 'qr_ready') {
+ const request = ++visit.requested;
try {
const qr = await sessionApi.getQR(id);
- // Only into the modal still open for this session, as in fetchQR.
+ if (qrVisit.current !== visit || request < visit.applied) return;
+ visit.applied = request;
setQrData(cur => (cur?.sessionId === id ? { ...cur, qrCode: qr.qrCode } : cur));
} catch (err) {
console.error('Failed to get QR:', err);
@@ -199,6 +228,8 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Use
// Fill the open QR modal straight from the push — the REST endpoint 400s BY DESIGN until a QR
// exists, so fetching it eagerly just spams the console with expected failures.
const applyQrPush = useCallback((event: { sessionId: string; qrCode: string }) => {
+ if (qrVisit.current.sessionId !== event.sessionId) return;
+ qrVisit.current = { sessionId: event.sessionId, requested: 0, applied: 0 };
setQrData(prev => (prev && prev.sessionId === event.sessionId ? { ...prev, qrCode: event.qrCode } : prev));
}, []);
@@ -215,6 +246,9 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Use
// and closing that one is right too. A code arriving AFTER the answer is not covered, and cannot
// be from here; the modal is gone by then and the operator reopens it from the card.
const dismissQrForSession = useCallback((sessionId: string, onlyIfBlank = false) => {
+ if (qrVisit.current.sessionId === sessionId) {
+ qrVisit.current = { sessionId, requested: 0, applied: 0 };
+ }
setQrData(current => {
if (current?.sessionId !== sessionId) return current;
if (onlyIfBlank && current.qrCode) return current;
@@ -228,6 +262,9 @@ export function useSessionPairing({ sessions, sessionsRef, reloadSessions }: Use
// now gone, so scanning it cannot work. The modal falls back to its loading state, and the poll
// fills it again once the session is back at `qr_ready` with a fresh code.
const clearQrCodeForSession = useCallback((sessionId: string) => {
+ if (qrVisit.current.sessionId === sessionId) {
+ qrVisit.current = { sessionId, requested: 0, applied: 0 };
+ }
setQrData(current => (current?.sessionId === sessionId ? { ...current, qrCode: '' } : current));
}, []);