Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): drop a download answered after sign-out
Yudhi Armyndharis63a551b2e727
diff --git a/dashboard/src/components/chats/ChatThread.test.ts b/dashboard/src/components/chats/ChatThread.test.tsindex 3e80febf3..920b7b873 100644--- a/dashboard/src/components/chats/ChatThread.test.ts+++ b/dashboard/src/components/chats/ChatThread.test.ts@@ -218,6 +218,52 @@ test('archive-only media previews inline from the media route; a plain omitted m}});+test('a media download answered after sign-out saves no file', async () => {+ // Logout cancels nothing in flight: a download the operator started just before it would otherwise+ // land in the downloads folder with the login form already showing.+ const message: ChatMessageView = {+ ...PROMPT,+ id: 'big',+ waMessageId: 'wamid.big',+ body: '',+ type: 'document',+ metadata: { media: { mimetype: 'application/pdf', filename: 'report.pdf', omitted: true, sizeBytes: 10 } },+ };+ window.sessionStorage.setItem('openwa_api_key', 'key-a');+ const fetchOriginal = globalThis.fetch;+ const createOriginal = URL.createObjectURL;+ const revokeOriginal = URL.revokeObjectURL;+ const createElementOriginal = document.createElement;+ const saved: string[] = [];+ let answer!: (response: Response) => void;+ globalThis.fetch = (() => new Promise<Response>(resolve => (answer = resolve))) as typeof fetch;+ URL.createObjectURL = () => 'blob:report';+ URL.revokeObjectURL = () => {};+ document.createElement = ((tag: string, options?: ElementCreationOptions) => {+ const element = createElementOriginal.call(document, tag, options);+ if (tag === 'a')+ (element as HTMLAnchorElement).click = () => void saved.push((element as HTMLAnchorElement).download);+ return element;+ }) as typeof document.createElement;+ try {+ const { container } = renderThread('viewer', [message]);+ const button = container.querySelector('[data-wa-message-id="wamid.big"] button.message-media-omitted');+ assert.ok(button, 'the over-budget document did not render its download button');+ rtl.fireEvent.click(button);+ await rtl.waitFor(() => assert.ok(answer, 'the download did not start'));+ window.sessionStorage.removeItem('openwa_api_key');+ answer(new Response(new Blob(['x']), { status: 200 }));+ await new Promise(resolve => setTimeout(resolve, 50));+ assert.deepEqual(saved, [], 'the media file was saved after the sign-out');+ } finally {+ globalThis.fetch = fetchOriginal;+ URL.createObjectURL = createOriginal;+ URL.revokeObjectURL = revokeOriginal;+ document.createElement = createElementOriginal;+ window.sessionStorage.removeItem('openwa_api_key');+ }+});+test('poll messages display exact choices, including outgoing and legacy polls', () => {const poll = { name: 'Where?', options: [' Park ', '<script>Beach</script>'], allowMultipleAnswers: false };const { container } = renderThread('viewer', [diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsxindex da9b9feb2..9e2d67cd0 100644--- a/dashboard/src/components/chats/ChatThread.tsx+++ b/dashboard/src/components/chats/ChatThread.tsx@@ -11,6 +11,7 @@ import {type ChatMessageView,} from '../../utils/chatMessages';import { shouldFetchOlderMessages } from '../../utils/scrollDecision';+import { keepsSameKey } from '../../utils/authLifecycle';import ArchivedMediaPreview, { type ArchivedMediaKind } from './ArchivedMediaPreview';import MessageBody from './MessageBody';@@ -107,8 +108,10 @@ function ChatThread({if (!sessionId || !messageId) return;setMediaFetch(prev => ({ ...prev, [messageId]: 'loading' }));let objectUrl: string | null = null;+ const sameKey = keepsSameKey();try {const blob = await sessionApi.getMessageMediaBlob(sessionId, activeChat.id, messageId);+ if (!sameKey()) return;objectUrl = URL.createObjectURL(blob);const link = document.createElement('a');link.href = objectUrl;diff --git a/dashboard/src/hooks/useDataBackup.test.ts b/dashboard/src/hooks/useDataBackup.test.tsnew file mode 100644index 000000000..6aaf0be86--- /dev/null+++ b/dashboard/src/hooks/useDataBackup.test.ts@@ -0,0 +1,95 @@+// The backup export saves a file with every integration instance's secrets in plaintext, so an export+// still in flight when the operator signs out must not save it over the login form.+import '../test-helpers/register-hooks.ts';+import { test, before, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { createElement, type ReactNode } from 'react';+import type { useDataBackup as useDataBackupFn } from './useDataBackup.ts';+import type { ToastContext as ToastContextType } from './useToast.ts';++type RTL = typeof import('@testing-library/react');++let rtl: RTL;+let useDataBackup: typeof useDataBackupFn;+let ToastContext: typeof ToastContextType;++// Answer of the export route, per test; a pending one is an export still in flight.+let exportAnswer: Promise<Response> = new Promise(() => {});+const saved: HTMLAnchorElement[] = [];+let createElementOriginal: typeof document.createElement;++function dump(): Response {+ const body = { exportedAt: '2026-10-09T10:00:00.000Z', dataDbType: 'sqlite', tables: {}, counts: {} };+ return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } });+}++before(async () => {+ const { installJsdomGlobals } = await import('../test-helpers/jsdom.ts');+ await installJsdomGlobals();+ createElementOriginal = document.createElement;+ const { i18nReady } = await import('../i18n/index.ts');+ await i18nReady;+ globalThis.fetch = (input: RequestInfo | URL): Promise<Response> => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ return url.endsWith('/api/infra/export-data')+ ? exportAnswer+ : Promise.resolve(new Response('{}', { status: 404, headers: { 'Content-Type': 'application/json' } }));+ };+ URL.createObjectURL = () => 'blob:backup';+ URL.revokeObjectURL = () => {};+ rtl = await import('@testing-library/react');+ ({ useDataBackup } = await import('./useDataBackup.ts'));+ ({ ToastContext } = await import('./useToast.ts'));+});++afterEach(() => {+ rtl.cleanup();+ saved.length = 0;+ exportAnswer = new Promise(() => {});+ window.sessionStorage.removeItem('openwa_api_key');+ document.createElement = createElementOriginal;+});++function renderBackup() {+ const noop = () => {};+ const value = {+ toasts: [],+ addToast: noop,+ removeToast: noop,+ success: noop,+ error: noop,+ warning: noop,+ info: noop,+ };+ const wrapper = ({ children }: { children: ReactNode }) => createElement(ToastContext.Provider, { value }, children);+ // Record each file the hook saves by capturing the link it clicks, instead of letting jsdom navigate.+ document.createElement = ((tag: string, options?: ElementCreationOptions) => {+ const element = createElementOriginal.call(document, tag, options);+ if (tag === 'a') (element as HTMLAnchorElement).click = () => void saved.push(element as HTMLAnchorElement);+ return element;+ }) as typeof document.createElement;+ return rtl.renderHook(() => useDataBackup(), { wrapper });+}++test('an export that completes while signed in saves the backup file', async () => {+ window.sessionStorage.setItem('openwa_api_key', 'key-a');+ exportAnswer = Promise.resolve(dump());+ const { result } = renderBackup();+ await rtl.act(() => result.current.exportBackup());+ assert.deepEqual(+ saved.map(link => link.download),+ ['openwa-backup-2026-10-09.json'],+ );+});++test('an export answered after sign-out saves no file', async () => {+ window.sessionStorage.setItem('openwa_api_key', 'key-a');+ let answer!: (response: Response) => void;+ exportAnswer = new Promise<Response>(resolve => (answer = resolve));+ const { result } = renderBackup();+ const exporting = rtl.act(() => result.current.exportBackup());+ window.sessionStorage.removeItem('openwa_api_key');+ answer(dump());+ await exporting;+ assert.deepEqual(saved, [], 'a backup of the whole database was saved after the sign-out');+});diff --git a/dashboard/src/hooks/useDataBackup.ts b/dashboard/src/hooks/useDataBackup.tsindex b925769cb..6a426aa48 100644--- a/dashboard/src/hooks/useDataBackup.ts+++ b/dashboard/src/hooks/useDataBackup.ts@@ -1,5 +1,6 @@import { useState } from 'react';import { shouldOfferStopOrphansRetry } from '../utils/importRefusal';+import { keepsSameKey } from '../utils/authLifecycle';import { useTranslation } from 'react-i18next';import { infraApi } from '../services/api';import { useToast } from './useToast';@@ -24,8 +25,11 @@ export function useDataBackup(): DataBackup {// database) so the data can be re-imported into the new one — switching otherwise starts empty (#488).const exportBackup = async () => {setMigrating(true);+ const sameKey = keepsSameKey();try {const dump = await infraApi.exportData();+ // The dump holds every integration instance's secrets in plaintext: not for a signed-out page.+ if (!sameKey()) return;const blob = new Blob([JSON.stringify(dump, null, 2)], { type: 'application/json' });const url = URL.createObjectURL(blob);const a = document.createElement('a');diff --git a/dashboard/src/utils/authLifecycle.ts b/dashboard/src/utils/authLifecycle.tsindex 32b4b7f39..675e793cd 100644--- a/dashboard/src/utils/authLifecycle.ts+++ b/dashboard/src/utils/authLifecycle.ts@@ -22,6 +22,16 @@ export function clearActorState(...caches: ClearableCache[]): void {for (const cache of caches) cache.clear();}+/**+ * Captures the stored API key now and returns a check that holds only while it is still the stored+ * one. Logout cancels nothing in flight, so a download started before it must not save its file once+ * the key is gone or another sign-in's has replaced it.+ */+export function keepsSameKey(): () => boolean {+ const key = sessionStorage.getItem('openwa_api_key');+ return () => sessionStorage.getItem('openwa_api_key') === key;+}+const IP_REFUSALS: ReadonlySet<string> = new Set(['IP address not allowed', 'Client IP could not be determined']);/**