Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): cancel pending requests on logout (#1792)
Yudhi Armyndharis8bbbb9ea2361
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1430519a6..1c24a8591 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Stop dashboard multi-page loads and a pending chat mark-as-read from sending requests after logout.- Keep a new dashboard login signed in when a request sent with the previous API key fails afterwards.- Enforce the plugin package size limit before reading `manifest.json`, and reject archive entries whose path starts with `/`.- Refuse Baileys animated stickers over 500 frames and run at most two sticker conversions at once.diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.tsindex 5a550750c..21d250344 100644--- a/dashboard/src/pages/Chats.test.ts+++ b/dashboard/src/pages/Chats.test.ts@@ -1074,6 +1074,33 @@ test('a reconnect refetch that settles after the page was left sends no mark-as-);});+async function leaveWithPendingRead(loggedOut: boolean): Promise<number> {+ const { screen, fireEvent, within } = rtl;+ const { container, unmount } = renderChats();+ await screen.findByText('Main (15551234567)');+ fireEvent.click(await screen.findByText('Alice'));+ await within(container.querySelector('.room-messages') as HTMLElement).findByText('hello from alice');+ // Opening the chat queued its read behind the quiet window; the page goes away inside it.+ resetFetchCalls();+ // Logout removes the key before the authenticated tree unmounts.+ if (loggedOut) window.sessionStorage.removeItem('openwa_api_key');+ try {+ unmount();+ await new Promise(resolve => setTimeout(resolve, 1_000));+ } finally {+ window.sessionStorage.setItem('openwa_api_key', 'test-key');+ }+ return countFetchCalls('POST', `/api/sessions/${SESSION.id}/chats/read`);+}++test('leaving the page sends the pending mark-as-read', async () => {+ assert.equal(await leaveWithPendingRead(false), 1, 'the pending mark-as-read was dropped');+});++test('logging out sends no pending mark-as-read without a key', async () => {+ assert.equal(await leaveWithPendingRead(true), 0, 'a keyless mark-as-read went out after logout');+});+test('a reconnect refetch overtaken by a newer list still marks the open chat read', async () => {const { screen, fireEvent, within, act, waitFor } = rtl;const { container } = renderChats();diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 7acdd7249..dd8cbf6be 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -409,8 +409,15 @@ export function Chats() {// fire-and-forget (a failure only raises a warning toast), so firing on the way out is safe —// and dropping the pending call would leave the last messages of a quickly-exited chat unread.// The flush closure still references the PREVIOUS session on a session switch, which is exactly- // where those queued reads belong.- useEffect(() => () => markReadCoalescer.flush(), [markReadCoalescer]);+ // where those queued reads belong. Logout removes the key before the page unmounts, though: a+ // read flushed then goes out keyless and its 401 reloads the login form, so drop it instead.+ useEffect(+ () => () => {+ if (sessionStorage.getItem('openwa_api_key')) markReadCoalescer.flush();+ else markReadCoalescer.cancel();+ },+ [markReadCoalescer],+ );// Marking a chat read is an operator write; a read-only key would only collect 403 toasts.const markChatRead = useCallback(diff --git a/dashboard/src/utils/fetchAllPages.test.ts b/dashboard/src/utils/fetchAllPages.test.tsindex c08128b57..55e36b245 100644--- a/dashboard/src/utils/fetchAllPages.test.ts+++ b/dashboard/src/utils/fetchAllPages.test.ts@@ -1,7 +1,16 @@-import { test } from 'node:test';+import { test, before, beforeEach } from 'node:test';import assert from 'node:assert/strict';import { fetchAllPages } from './fetchAllPages.ts';+before(async () => {+ const { installJsdomGlobals } = await import('../test-helpers/jsdom.ts');+ await installJsdomGlobals();+});++beforeEach(() => {+ sessionStorage.setItem('openwa_api_key', 'key-a');+});+/** Fake page source: holds `total` rows, but never returns more than `serverMax` per call. */function fakeSource(total: number, serverMax: number) {const calls: Array<{ limit: number; offset: number }> = [];@@ -150,3 +159,53 @@ test('a page still throttled past the one-second tier ends the walk with the rowassert.equal(rows.length, 1_000);assert.equal(attempts, calls.length + 3, 'the refused page was tried more than three times');});++test('a walk stops once the key it started with is signed out or replaced', async () => {+ // Each page request reads the stored key as it goes out, as the API client does.+ const { fetchPage } = fakeSource(1_000, 200);+ const sentWith: Array<string | null> = [];+ const keyedPage = async (limit: number, offset: number) => {+ sentWith.push(sessionStorage.getItem('openwa_api_key'));+ return fetchPage(limit, offset);+ };++ // Signed out while a throttled page waits for its retry: the retry is never sent keyless.+ let throttled = false;+ await assert.rejects(+ fetchAllPages(+ async (limit, offset) => {+ const page = await keyedPage(limit, offset);+ if (offset === 200 && !throttled) {+ throttled = true;+ sessionStorage.removeItem('openwa_api_key');+ throw httpError(429);+ }+ return page;+ },+ { retryDelayMs: 0 },+ ),+ );+ assert.deepEqual(sentWith, ['key-a', 'key-a']);++ // Signed in again with another key while a page was out: no page goes out as the new key.+ sentWith.length = 0;+ sessionStorage.setItem('openwa_api_key', 'key-a');+ await assert.rejects(+ fetchAllPages(async (limit, offset) => {+ const page = await keyedPage(limit, offset);+ if (offset === 200) sessionStorage.setItem('openwa_api_key', 'key-b');+ return page;+ }),+ );+ assert.deepEqual(sentWith, ['key-a', 'key-a']);++ // Signed out while the last page was out: its rows do not come back as a finished walk.+ sessionStorage.setItem('openwa_api_key', 'key-a');+ await assert.rejects(+ fetchAllPages(async (limit, offset) => {+ const page = await fetchPage(limit, offset);+ if (offset === 800) sessionStorage.removeItem('openwa_api_key');+ return page;+ }),+ );+});diff --git a/dashboard/src/utils/fetchAllPages.ts b/dashboard/src/utils/fetchAllPages.tsindex 053b00b40..3d575069b 100644--- a/dashboard/src/utils/fetchAllPages.ts+++ b/dashboard/src/utils/fetchAllPages.ts@@ -47,10 +47,20 @@ export async function fetchAllPages<T>(): Promise<{ items: T[]; truncated: boolean; throttled: boolean }> {const all: T[] = [];let offset = 0;+ // Logout cancels nothing in flight. A walk that outlived its key would send the rest of its pages+ // keyless (a 401 that reloads the login form) or as the next sign-in's key, mixing two actors'+ // rows, and a page answered after logout would still finish it. Stop once the key has changed.+ const key = sessionStorage.getItem('openwa_api_key');+ const fetchOnce = async () => {+ if (sessionStorage.getItem('openwa_api_key') !== key) throw new Error('Signed out');+ const page = await fetchPage(pageSize, offset);+ if (sessionStorage.getItem('openwa_api_key') !== key) throw new Error('Signed out');+ return page;+ };for (;;) {let page: Page<T>;try {- page = await retryThrottled(() => fetchPage(pageSize, offset), retryDelayMs);+ page = await retryThrottled(fetchOnce, retryDelayMs);} catch (err) {if (all.length > 0 && (err as { status?: number }).status === 429) {return { items: all, truncated: true, throttled: true };