Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): harden uploads, auth flow, socket subscriptions, and restart polling
Yudhi Armyndharise5264d4a97de
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsxindex 0c4cd7efe..bb012a29d 100644--- a/dashboard/src/App.tsx+++ b/dashboard/src/App.tsx@@ -5,11 +5,11 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { Loader2 } from 'lucide-react';import { Layout } from './components/Layout';import { ToastProvider } from './components/Toast';-import { useRole, type UserRole } from './hooks/useRole';+import { useRole } from './hooks/useRole';import { RoleProvider } from './components/RoleProvider';import { ErrorBoundary } from './components/ErrorBoundary';import { API_BASE_URL } from './services/api';-import { clearActorState, resolveStartupValidation } from './utils/authLifecycle';+import { clearActorState, isUserRole, resolveStartupValidation } from './utils/authLifecycle';import './App.css';const Login = lazy(() => import('./pages/Login').then(m => ({ default: m.Login })));@@ -35,30 +35,23 @@ const queryClient = new QueryClient({});function AppContent() {- // Initialize from sessionStorage to avoid setState in effect- const savedKey = sessionStorage.getItem('openwa_api_key');+ // Capture the key ONCE at mount. Read live per render, the null→key transition when+ // handleLogin stores a fresh key would re-fire the startup re-validation effect below and+ // double the /auth/validate request on every sign-in — the effect is for genuine page+ // refreshes with a saved key only.+ const [savedKey] = useState(() => sessionStorage.getItem('openwa_api_key'));const [isAuthenticated, setIsAuthenticated] = useState(!!savedKey);const [, setApiKey] = useState(savedKey || '');const { setRole, role } = useRole();- const handleLogin = async (key: string) => {+ const handleLogin = (key: string, validatedRole?: string) => {setApiKey(key);sessionStorage.setItem('openwa_api_key', key);- // Fetch the role from API- try {- const response = await fetch(`${API_BASE_URL}/auth/validate`, {- method: 'POST',- headers: { 'X-API-Key': key },- });- if (response.ok) {- const data = await response.json();- setRole(data.role as UserRole);- }- } catch {- // Default to viewer if we can't fetch role- setRole('viewer');- }+ // The login page's validate response already carried the role, so no second /auth/validate+ // round-trip is needed here. An absent or unrecognized role falls back to viewer, the+ // least-privileged default.+ setRole(isUserRole(validatedRole) ? validatedRole : 'viewer');setIsAuthenticated(true);};diff --git a/dashboard/src/components/FilterBuilder.tsx b/dashboard/src/components/FilterBuilder.tsxindex 51f2529a3..134ddaff3 100644--- a/dashboard/src/components/FilterBuilder.tsx+++ b/dashboard/src/components/FilterBuilder.tsx@@ -2,6 +2,7 @@ import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { Plus, X } from 'lucide-react';import {+ MESSAGE_TYPES,type Chat,type WebhookFilters,type WebhookFilterCondition,@@ -15,25 +16,9 @@ interface FieldDescriptor {field: string;kind: FieldKind;operators: WebhookFilterOperator[];- enumValues?: string[];+ enumValues?: readonly string[];}-const MESSAGE_TYPES = [- 'text',- 'image',- 'video',- 'audio',- 'voice',- 'document',- 'sticker',- 'location',- 'contact',- 'call',- 'revoked',- 'masked',- 'unknown',-];-// Mirrors the backend message-family field registry (src/modules/webhook/filters/filter-types.ts).const MESSAGE_FIELDS: FieldDescriptor[] = [{ field: 'sender', kind: 'id', operators: ['is', 'isNot'] },diff --git a/dashboard/src/components/chats/ChatComposer.tsx b/dashboard/src/components/chats/ChatComposer.tsxindex f6814ffda..27e65d298 100644--- a/dashboard/src/components/chats/ChatComposer.tsx+++ b/dashboard/src/components/chats/ChatComposer.tsx@@ -20,6 +20,11 @@ const messageTypeFromMime = (mimetype: string): MessageType => {return 'document';};+// Client pre-check before base64-encoding an upload, same cap as the message tester: base64+// inflates ~1.33x, so ~18 MiB raw stays under the backend's default 25 MiB body limit and the+// pick fails here with a toast instead of OOMing the tab on the FileReader.+const MEDIA_UPLOAD_MAX_BYTES = 18 * 1024 * 1024;+/** A picked-but-unsent file, staged until send, removal, or a move to another chat. */export interface StagedAttachment {file: File;@@ -112,8 +117,16 @@ function ChatComposer({// 5. Handle file selection & base64 conversionconst handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {const file = e.target.files?.[0];+ e.target.value = ''; // allow re-picking the same file after a rejection or removalif (!file) return;+ // Reject before base64-encoding: an oversized pick would inflate ~1.33x into the backend body+ // cap, and the 413 only applies after the whole body is uploaded — surface the toast now.+ if (file.size > MEDIA_UPLOAD_MAX_BYTES) {+ showErrorToast(t('chats.errors.fileTooLarge'));+ return;+ }+if (file.type.startsWith('image/')) {setPreviewUrl(URL.createObjectURL(file));} else {diff --git a/dashboard/src/hooks/useRestartFlow.ts b/dashboard/src/hooks/useRestartFlow.tsindex b4c16befd..1ab49eb8b 100644--- a/dashboard/src/hooks/useRestartFlow.ts+++ b/dashboard/src/hooks/useRestartFlow.ts@@ -1,4 +1,4 @@-import { useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { infraApi } from '../services/api';import { restartPollAttempts } from '../utils/restartPoll';@@ -46,6 +46,40 @@ export function useRestartFlow(): RestartFlow {const [dbSwitch, setDbSwitch] = useState(false);const [storageSwitch, setStorageSwitch] = useState(false);+ // Every pending health-poll timeout and the countdown interval are tracked so an unmount (navigating+ // away mid-restart) cancels them instead of letting them fire setState on a dead component. The+ // trailing window.location.reload() on success is kept — a restart that already completed is meant+ // to reload the page.+ const pollTimeoutsRef = useRef<Set<ReturnType<typeof setTimeout>>>(new Set());+ const countdownIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);++ useEffect(() => {+ const pollTimeouts = pollTimeoutsRef.current;+ return () => {+ for (const handle of pollTimeouts) clearTimeout(handle);+ pollTimeouts.clear();+ if (countdownIntervalRef.current) {+ clearInterval(countdownIntervalRef.current);+ countdownIntervalRef.current = null;+ }+ };+ }, []);++ const schedulePollTimeout = (fn: () => void, ms: number) => {+ const handle = setTimeout(() => {+ pollTimeoutsRef.current.delete(handle);+ fn();+ }, ms);+ pollTimeoutsRef.current.add(handle);+ };++ const stopCountdown = () => {+ if (countdownIntervalRef.current) {+ clearInterval(countdownIntervalRef.current);+ countdownIntervalRef.current = null;+ }+ };+const open = ({profiles: newProfiles,dbSwitch: nextDbSwitch,@@ -64,25 +98,25 @@ export function useRestartFlow(): RestartFlow {if (restartStatus === 'idle') setShowRestartModal(false);};- const checkServerHealth = (stopCountdown?: () => void, estimatedTime?: number) => {+ const checkServerHealth = (estimatedTime?: number) => {let attempts = 0;const maxAttempts = restartPollAttempts(estimatedTime);const check = async () => {try {await infraApi.healthCheck();- stopCountdown?.();+ stopCountdown();setRestartCountdown(0);setRestartStatus('success');- setTimeout(() => window.location.reload(), 2000);+ schedulePollTimeout(() => window.location.reload(), 2000);} catch {attempts++;- if (attempts < maxAttempts) setTimeout(check, 1000);+ if (attempts < maxAttempts) schedulePollTimeout(check, 1000);else setRestartStatus('error');}};- setTimeout(check, 3000);+ schedulePollTimeout(check, 3000);};const start = async () => {@@ -103,15 +137,8 @@ export function useRestartFlow(): RestartFlow {}setRestartStatus('waiting');- let intervalRef: ReturnType<typeof setInterval> | null = null;- const stopCountdown = () => {- if (intervalRef) {- clearInterval(intervalRef);- intervalRef = null;- }- };-- intervalRef = setInterval(() => {+ stopCountdown();+ countdownIntervalRef.current = setInterval(() => {setRestartCountdown(prev => {if (prev <= 1) {stopCountdown();@@ -121,7 +148,7 @@ export function useRestartFlow(): RestartFlow {});}, 1000);- checkServerHealth(stopCountdown, estimatedTime);+ checkServerHealth(estimatedTime);};return {diff --git a/dashboard/src/hooks/useSessionFeed.ts b/dashboard/src/hooks/useSessionFeed.tsindex be2a4e0c4..3a02269e3 100644--- a/dashboard/src/hooks/useSessionFeed.ts+++ b/dashboard/src/hooks/useSessionFeed.ts@@ -1,4 +1,4 @@-import { useState, useEffect, useRef, useCallback } from 'react';+import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import type { RefObject } from 'react';import type { Session } from '../services/api';import { useWebSocket } from './useWebSocket';@@ -40,14 +40,22 @@ export function useSessionFeed({// so the fallback runs after `subscribe` exists — the handler can't reference it directly).const [feedErrorFrame, setFeedErrorFrame] = useState<{ code: string } | null>(null);- const { isConnected, subscribe } = useWebSocket({- onQRCode,- onSessionStatus,- onSessionRestriction,- onServerError: useCallback((frame: { code: string }) => {- setFeedErrorFrame(frame);- }, []),- });+ const handleServerError = useCallback((frame: { code: string }) => {+ setFeedErrorFrame(frame);+ }, []);++ // The events object must be referentially stable: useWebSocket re-registers its socket handler+ // on every identity change, so an inline literal would tear down and re-attach per render.+ const wsEvents = useMemo(+ () => ({+ onQRCode,+ onSessionStatus,+ onSessionRestriction,+ onServerError: handleServerError,+ }),+ [onQRCode, onSessionStatus, onSessionRestriction, handleServerError],+ );+ const { isConnected, subscribe } = useWebSocket(wsEvents);// Fold a server error frame into the feed state: a session-scoped key may not join the '*'// room — silently fall back to one subscription per listed session (the list endpoint isdiff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 3818b7bfd..13115ca5c 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -168,7 +168,8 @@"markRead": "فشل تعليم المحادثة كمقروءة","send": "فشل إرسال الرسالة","react": "فشل التفاعل مع الرسالة",- "delete": "فشل حذف الرسالة"+ "delete": "فشل حذف الرسالة",+ "fileTooLarge": "الملف كبير جدًا (الحد الأقصى 18 ميغابايت)"},"loadMessagesError": "تعذّر تحميل الرسائل. تحقّق من سجلّات الخادم."},diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex 003ebba37..64056a87e 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -157,7 +157,8 @@"markRead": "Chat konnte nicht als gelesen markiert werden","send": "Nachricht konnte nicht gesendet werden","react": "Reaktion auf die Nachricht fehlgeschlagen",- "delete": "Nachricht konnte nicht gelöscht werden"+ "delete": "Nachricht konnte nicht gelöscht werden",+ "fileTooLarge": "Die Datei ist zu groß (max. 18 MB)"},"loadMessagesError": "Nachrichten konnten nicht geladen werden. Prüfe die Serverprotokolle."},diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex 4cdd83c6d..18d877ba1 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -157,7 +157,8 @@"markRead": "Failed to mark chat as read","send": "Failed to send message","react": "Failed to react to message",- "delete": "Failed to delete message"+ "delete": "Failed to delete message",+ "fileTooLarge": "File is too large (max 18 MB)"},"loadMessagesError": "Couldn't load messages. Check the server logs."},diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex 791a835bc..53342bb67 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -157,7 +157,8 @@"markRead": "Error al marcar el chat como leído","send": "Error al enviar el mensaje","react": "Error al reaccionar al mensaje",- "delete": "Error al eliminar el mensaje"+ "delete": "Error al eliminar el mensaje",+ "fileTooLarge": "El archivo es demasiado grande (máx. 18 MB)"},"loadMessagesError": "No se pudieron cargar los mensajes. Revisa los registros del servidor."},diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex f17b9c279..f8914f761 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -157,7 +157,8 @@"markRead": "Échec du marquage de la discussion comme lue","send": "Échec de l'envoi du message","react": "Échec de la réaction au message",- "delete": "Échec de la suppression du message"+ "delete": "Échec de la suppression du message",+ "fileTooLarge": "Le fichier est trop volumineux (max 18 Mo)"},"loadMessagesError": "Impossible de charger les messages. Vérifiez les journaux du serveur."},diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex a25015e15..7cfb68f80 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -164,7 +164,8 @@"markRead": "סימון השיחה כנקראה נכשל","send": "שליחת ההודעה נכשלה","react": "התגובה להודעה נכשלה",- "delete": "מחיקת ההודעה נכשלה"+ "delete": "מחיקת ההודעה נכשלה",+ "fileTooLarge": "הקובץ גדול מדי (מקסימום 18 MB)"},"loadMessagesError": "לא ניתן לטעון את ההודעות. בדקו את יומני השרת."},diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 172673c97..b6fb2a01e 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -157,7 +157,8 @@"markRead": "Impossibile contrassegnare la chat come letta","send": "Impossibile inviare il messaggio","react": "Impossibile reagire al messaggio",- "delete": "Impossibile eliminare il messaggio"+ "delete": "Impossibile eliminare il messaggio",+ "fileTooLarge": "Il file è troppo grande (max 18 MB)"},"loadMessagesError": "Impossibile caricare i messaggi. Controlla i log del server."},diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex 51ed56b02..d913c4465 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -157,7 +157,8 @@"markRead": "채팅을 읽음으로 표시하지 못했습니다","send": "메시지를 보내지 못했습니다","react": "메시지에 반응하지 못했습니다",- "delete": "메시지를 삭제하지 못했습니다"+ "delete": "메시지를 삭제하지 못했습니다",+ "fileTooLarge": "파일이 너무 큽니다 (최대 18 MB)"},"loadMessagesError": "메시지를 불러올 수 없습니다. 서버 로그를 확인하세요."},diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 65f54886e..e48effbca 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -157,7 +157,8 @@"markRead": "Erro ao marcar o chat como lido","send": "Erro ao enviar a mensagem","react": "Erro ao reagir à mensagem",- "delete": "Erro ao excluir a mensagem"+ "delete": "Erro ao excluir a mensagem",+ "fileTooLarge": "O arquivo é muito grande (máx. 18 MB)"},"loadMessagesError": "Não foi possível carregar as mensagens. Verifique os registros do servidor."},diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex 2b88f75e6..985e3b2ba 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -157,7 +157,8 @@"markRead": "చాట్ను చదివినట్లుగా గుర్తించడం విఫలమైంది","send": "సందేశాన్ని పంపడం విఫలమైంది","react": "సందేశానికి ప్రతిస్పందించడం విఫలమైంది",- "delete": "సందేశాన్ని తొలగించడం విఫలమైంది"+ "delete": "సందేశాన్ని తొలగించడం విఫలమైంది",+ "fileTooLarge": "ఫైల్ చాలా పెద్దది (గరిష్టం 18 MB)"},"loadMessagesError": "సందేశాలను లోడ్ చేయడం సాధ్యం కాలేదు. సర్వర్ లాగ్లను తనిఖీ చేయండి."},diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.jsonindex 4b534383b..915caca12 100644--- a/dashboard/src/i18n/locales/tr.json+++ b/dashboard/src/i18n/locales/tr.json@@ -157,7 +157,8 @@"markRead": "Sohbet okundu olarak işaretlenemedi","send": "Mesaj gönderilemedi","react": "Mesaja tepki verilemedi",- "delete": "Mesaj silinemedi"+ "delete": "Mesaj silinemedi",+ "fileTooLarge": "Dosya çok büyük (maks 18 MB)"},"loadMessagesError": "Mesajlar yüklenemedi. Sunucu kayıtlarını kontrol edin."},diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex af601f2eb..c9ec9ff99 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -157,7 +157,8 @@"markRead": "将聊天标记为已读失败","send": "发送消息失败","react": "回应消息失败",- "delete": "删除消息失败"+ "delete": "删除消息失败",+ "fileTooLarge": "文件过大(最大 18 MB)"},"loadMessagesError": "无法加载消息。请检查服务器日志。"},diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex aae1b8390..0210d257b 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -157,7 +157,8 @@"markRead": "將聊天標記為已讀失敗","send": "傳送訊息失敗","react": "回應訊息失敗",- "delete": "刪除訊息失敗"+ "delete": "刪除訊息失敗",+ "fileTooLarge": "檔案過大(最大 18 MB)"},"loadMessagesError": "無法載入訊息。請檢查伺服器日誌。"},diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex fd93e689a..416695693 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -517,14 +517,27 @@ export function Chats() {[queryClient],);- const { isConnected, connectionFailed, reconnect, subscribe, unsubscribe } = useWebSocket({- onMessage: handleIncomingMessage,- onMessageAck: handleIncomingMessageAck,- onMessageReaction: handleIncomingMessageReaction,- onMessageRevoked: handleIncomingMessageRevoked,- onMessageEdited: handleIncomingMessageEdited,- onStatusReceived: handleStatusReceived,- });+ // The events object must be referentially stable: useWebSocket re-registers its socket handler+ // on every identity change, so an inline literal would tear down and re-attach per render.+ const wsEvents = useMemo(+ () => ({+ onMessage: handleIncomingMessage,+ onMessageAck: handleIncomingMessageAck,+ onMessageReaction: handleIncomingMessageReaction,+ onMessageRevoked: handleIncomingMessageRevoked,+ onMessageEdited: handleIncomingMessageEdited,+ onStatusReceived: handleStatusReceived,+ }),+ [+ handleIncomingMessage,+ handleIncomingMessageAck,+ handleIncomingMessageReaction,+ handleIncomingMessageRevoked,+ handleIncomingMessageEdited,+ handleStatusReceived,+ ],+ );+ const { isConnected, connectionFailed, reconnect, subscribe, unsubscribe } = useWebSocket(wsEvents);// A transient WebSocket gap means message.received/ack/revoke events were missed, and the chat// cache uses staleTime: Infinity so it won't refetch on its own. On a reconnect (isConnecteddiff --git a/dashboard/src/pages/Infrastructure.test.ts b/dashboard/src/pages/Infrastructure.test.tsindex 8f9978cb2..6c9ab03df 100644--- a/dashboard/src/pages/Infrastructure.test.ts+++ b/dashboard/src/pages/Infrastructure.test.ts@@ -309,8 +309,8 @@ test('a successful save opens the restart modal', async () => {const dialog = await screen.findByRole('dialog');within(dialog).getByText('Configuration saved');- // The idle restart state offers both actions; asserting the button exists (not clicking it) keeps- // this test clear of handleRestart's uncancelled setInterval/setTimeout chain.+ // The idle restart state offers both actions; the click-through (and its timer cleanup on+ // unmount) is covered by the last test in this file.within(dialog).getByRole('button', { name: 'Restart Now' });within(dialog).getByRole('button', { name: 'Restart Later' });});@@ -442,3 +442,29 @@ test('saving while ENGINE_TYPE is pinned does not write the running engine overassert.equal(body.engine?.type, 'baileys');});});++// ── Restart-flow timer cleanup on unmount ────────────────────────────────────++test('unmounting mid-restart cancels the health poll and countdown timers', { timeout: 10_000 }, async () => {+ const { screen, waitFor, fireEvent, within } = rtl;+ resetFetchCalls();+ const { unmount } = renderInfrastructure();++ await screen.findByText('Database Configuration');+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));+ const dialog = await screen.findByRole('dialog');+ fireEvent.click(within(dialog).getByRole('button', { name: 'Restart Now' }));++ // The restart POST resolving is what arms the 3s health-poll timeout chain and the 1s countdown+ // interval in useRestartFlow.+ await waitFor(() => assert.ok(findFetchCall('POST', '/api/infra/restart'), 'expected the restart POST'));++ // Unmount, then outwait the first health poll (fires at 3s): a leaked chain would call+ // /api/health/ready here. Real timers only — mixing fake timers in after the flow has armed+ // would leave the pre-armed real handles un-clearable by the mocked clearTimeout.+ unmount();+ resetFetchCalls();+ await new Promise(resolve => setTimeout(resolve, 4000));++ assert.equal(findFetchCall('GET', '/api/health/ready'), undefined);+});diff --git a/dashboard/src/pages/Login.tsx b/dashboard/src/pages/Login.tsxindex cf2e9d132..6d2b39903 100644--- a/dashboard/src/pages/Login.tsx+++ b/dashboard/src/pages/Login.tsx@@ -8,7 +8,7 @@ import { API_BASE_URL } from '../services/api';import './Login.css';interface LoginProps {- onLogin: (apiKey: string) => void;+ onLogin: (apiKey: string, role?: string) => void;}export function Login({ onLogin }: LoginProps) {@@ -42,7 +42,10 @@ export function Login({ onLogin }: LoginProps) {});if (response.ok) {- onLogin(apiKey);+ // The validate body already carries the key's role — hand it up so the app can set it+ // directly instead of re-validating the same key a second time.+ const data: { role?: string } = await response.json().catch(() => ({}));+ onLogin(apiKey, data.role);} else {const errorData = await response.json().catch(() => ({}));setError(errorData.message || t('login.invalidKey'));diff --git a/dashboard/src/pages/Templates.tsx b/dashboard/src/pages/Templates.tsxindex d883943af..0fb49af6b 100644--- a/dashboard/src/pages/Templates.tsx+++ b/dashboard/src/pages/Templates.tsx@@ -1,9 +1,10 @@import { useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { AlertTriangle, Check, Copy, FileText, Loader2, Plus, Search, Trash2, X } from 'lucide-react';+import { Copy, FileText, Loader2, Plus, Search, Trash2 } from 'lucide-react';import { type MessageTemplate, type TemplatePayload } from '../services/api';import { useDocumentTitle } from '../hooks/useDocumentTitle';import { useRole } from '../hooks/useRole';+import { useToast } from '../hooks/useToast';import {useCreateTemplateMutation,useDeleteTemplateMutation,@@ -60,7 +61,7 @@ export function Templates() {const [form, setForm] = useState<TemplateForm>(emptyForm);const [editingTemplate, setEditingTemplate] = useState<MessageTemplate | null>(null);const [deleteTarget, setDeleteTarget] = useState<MessageTemplate | null>(null);- const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null);+ const toast = useToast();const [previewValues, setPreviewValues] = useState<Record<string, string>>({});const [searchTerm, setSearchTerm] = useState('');@@ -92,12 +93,6 @@ export function Templates() {}}, [selectedSessionId, sessions]);- useEffect(() => {- if (!toast) return;- const timer = setTimeout(() => setToast(null), 4000);- return () => clearTimeout(timer);- }, [toast]);-useEffect(() => {setPreviewValues(current => {const next: Record<string, string> = {};@@ -135,22 +130,21 @@ export function Templates() {id: editingTemplate.id,data: toPayload(form),});- setToast({ type: 'success', message: t('templates.toasts.updated') });+ toast.success(t('templates.toasts.updated'));} else {await createMutation.mutateAsync({sessionId: selectedSessionId,data: toPayload(form),});- setToast({ type: 'success', message: t('templates.toasts.created') });+ toast.success(t('templates.toasts.created'));}resetForm();} catch (err) {- setToast({- type: 'error',- message: t(editingTemplate ? 'templates.toasts.updateFailed' : 'templates.toasts.createFailed', {+ toast.error(+ t(editingTemplate ? 'templates.toasts.updateFailed' : 'templates.toasts.createFailed', {message: err instanceof Error ? err.message : t('common.unknownError'),}),- });+ );}};@@ -158,22 +152,21 @@ export function Templates() {if (!selectedSessionId || !deleteTarget) return;try {await deleteMutation.mutateAsync({ sessionId: selectedSessionId, id: deleteTarget.id });- setToast({ type: 'success', message: t('templates.toasts.deleted') });+ toast.success(t('templates.toasts.deleted'));if (editingTemplate?.id === deleteTarget.id) resetForm();setDeleteTarget(null);} catch (err) {- setToast({- type: 'error',- message: t('templates.toasts.deleteFailed', {+ toast.error(+ t('templates.toasts.deleteFailed', {message: err instanceof Error ? err.message : t('common.unknownError'),}),- });+ );}};const copyName = async (name: string) => {if (await copyToClipboard(name)) {- setToast({ type: 'success', message: t('templates.toasts.copied') });+ toast.success(t('templates.toasts.copied'));}};@@ -187,16 +180,6 @@ export function Templates() {return (<div className="templates-page">- {toast && (- <div className={`toast ${toast.type}`}>- {toast.type === 'success' ? <Check size={18} /> : <AlertTriangle size={18} />}- <span>{toast.message}</span>- <button className="toast-close" onClick={() => setToast(null)} aria-label={t('common.close')}>- <X size={16} />- </button>- </div>- )}-<PageHeadertitle={t('templates.title')}subtitle={t('templates.subtitle')}diff --git a/dashboard/src/pages/Webhooks.tsx b/dashboard/src/pages/Webhooks.tsxindex 790505fef..2d0fb7a2d 100644--- a/dashboard/src/pages/Webhooks.tsx+++ b/dashboard/src/pages/Webhooks.tsx@@ -1,4 +1,4 @@-import { useState, useEffect } from 'react';+import { useState } from 'react';import { useTranslation } from 'react-i18next';import {Plus,@@ -7,16 +7,15 @@ import {Play,ExternalLink,Loader2,- X,Webhook as WebhookIcon,Check,- AlertTriangle,AlertCircle,Filter,} from 'lucide-react';import { webhookApi, type Webhook, type WebhookFilters, type WebhookFilterCondition } from '../services/api';import { useDocumentTitle } from '../hooks/useDocumentTitle';import { useRole } from '../hooks/useRole';+import { useToast } from '../hooks/useToast';import {useWebhooksQuery,useSessionsQuery,@@ -138,7 +137,7 @@ export function Webhooks() {filters: WebhookFilters | null;}>({ url: '', events: ['message.received'], sessionId: '', filters: null });const [testingId, setTestingId] = useState<string | null>(null);- const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null);+ const toast = useToast();// Single source for the contact/group autocomplete in whichever modal is open.const activeSessionId = showEditModal ? (editWebhook?.sessionId ?? '') : newWebhook.sessionId;@@ -149,13 +148,6 @@ export function Webhooks() {return t(`webhooks.eventDescriptions.${name}`, { defaultValue: name });};- useEffect(() => {- if (toast) {- const timer = setTimeout(() => setToast(null), 4000);- return () => clearTimeout(timer);- }- }, [toast]);-const handleCreate = async () => {if (!newWebhook.url || !newWebhook.sessionId) return;try {@@ -168,14 +160,13 @@ export function Webhooks() {});setShowCreateModal(false);setNewWebhook({ url: '', events: ['message.received'], sessionId: '', filters: null });- setToast({ type: 'success', message: t('webhooks.toasts.created') });+ toast.success(t('webhooks.toasts.created'));} catch (err) {- setToast({- type: 'error',- message: t('webhooks.toasts.createFailed', {+ toast.error(+ t('webhooks.toasts.createFailed', {message: err instanceof Error ? err.message : t('common.unknownError'),}),- });+ );}};@@ -190,14 +181,13 @@ export function Webhooks() {await deleteMutation.mutateAsync({ sessionId: deleteTarget.sessionId, id: deleteTarget.id });setShowDeleteModal(false);setDeleteTarget(null);- setToast({ type: 'success', message: t('webhooks.toasts.deleted') });+ toast.success(t('webhooks.toasts.deleted'));} catch (err) {- setToast({- type: 'error',- message: t('webhooks.toasts.deleteFailed', {+ toast.error(+ t('webhooks.toasts.deleteFailed', {message: err instanceof Error ? err.message : t('common.unknownError'),}),- });+ );}};@@ -206,20 +196,16 @@ export function Webhooks() {try {const result = await webhookApi.test(sessionId, id);if (result.success) {- setToast({ type: 'success', message: t('webhooks.toasts.testOk', { status: result.statusCode }) });+ toast.success(t('webhooks.toasts.testOk', { status: result.statusCode }));} else {- setToast({- type: 'error',- message: t('webhooks.toasts.testFailed', { message: result.error || `Status ${result.statusCode}` }),- });+ toast.error(t('webhooks.toasts.testFailed', { message: result.error || `Status ${result.statusCode}` }));}} catch (err) {- setToast({- type: 'error',- message: t('webhooks.toasts.testError', {+ toast.error(+ t('webhooks.toasts.testError', {message: err instanceof Error ? err.message : t('common.unknownError'),}),- });+ );} finally {setTestingId(null);}@@ -246,14 +232,13 @@ export function Webhooks() {});setShowEditModal(false);setEditWebhook(null);- setToast({ type: 'success', message: t('webhooks.toasts.updated') });+ toast.success(t('webhooks.toasts.updated'));} catch (err) {- setToast({- type: 'error',- message: t('webhooks.toasts.updateFailed', {+ toast.error(+ t('webhooks.toasts.updateFailed', {message: err instanceof Error ? err.message : t('common.unknownError'),}),- });+ );}};@@ -287,16 +272,6 @@ export function Webhooks() {return (<div className="webhooks-page">- {toast && (- <div className={`toast ${toast.type}`}>- {toast.type === 'success' ? <Check size={18} /> : <AlertTriangle size={18} />}- <span>{toast.message}</span>- <button className="toast-close" onClick={() => setToast(null)}>- <X size={16} />- </button>- </div>- )}-<PageHeadertitle={t('webhooks.title')}subtitle={t('webhooks.subtitle')}diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex bb46ff8d1..9d2047058 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -592,6 +592,39 @@ export interface SearchResults {// API Client// =============================================================================+// Shared failure handling for every response shape (json/text/blob). On 401 the stored API key is+// invalid/expired/revoked — clear it and return to login so the user isn't stuck on a dashboard that+// 401s every request; the never-settling promise halts this request's chain so callers neither flash+// a generic error toast nor receive an undefined payload while the page navigates away. Otherwise+// throw an Error carrying the HTTP status and, when the gateway supplied one, its machine code.+async function handleErrorResponse<T>(response: Response): Promise<T> {+ if (response.status === 401) {+ sessionStorage.removeItem('openwa_api_key');+ if (typeof window !== 'undefined') {+ window.location.assign('/');+ return new Promise<T>(() => {});+ }+ }++ // On a non-JSON body (e.g. a reverse-proxy 502/503 HTML page) fall through to `HTTP <status>`+ // rather than statusText: the status code is what the toast connection-lost de-dup matches on,+ // and statusText is empty over HTTP/2 anyway.+ const error = await response.json().catch(() => ({}));+ // Carry the HTTP status on the Error (message unchanged, so the toast de-dup still matches) so+ // callers can tell apart a permission 403 from a real server 5xx instead of guessing from text.+ // Carry the machine `code` too: the gateway's stable codes (SESSION_LOGOUT_INCOMPLETE,+ // SESSION_NAME_TEARDOWN_PENDING, …) drive specific recovery UI, and a reverse-proxy 502 that+ // never reached the gateway carries no code at all — that distinction is exactly what the unlink+ // classifier keys on instead of fragile message heuristics.+ const err = new Error(error.message || `HTTP ${response.status}`) as Error & {+ status?: number;+ code?: string;+ };+ err.status = response.status;+ if (typeof error.code === 'string') err.code = error.code;+ throw err;+}+async function request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {const url = `${API_BASE_URL}${endpoint}`;@@ -608,36 +641,8 @@ async function request<T>(endpoint: string, options: RequestInit = {}): Promise<const response = await fetch(url, { ...options, headers });- if (response.status === 401) {- // The stored API key is invalid/expired/revoked — clear it and return to login- // so the user isn't stuck on a dashboard that 401s every request.- sessionStorage.removeItem('openwa_api_key');- if (typeof window !== 'undefined') {- window.location.assign('/');- // The page is navigating away — halt this request's promise chain so callers neither- // throw the generic error below (flashing a toast) nor receive an undefined payload.- return new Promise<T>(() => {});- }- }-if (!response.ok) {- // On a non-JSON body (e.g. a reverse-proxy 502/503 HTML page) fall through to `HTTP <status>`- // rather than statusText: the status code is what the toast connection-lost de-dup matches on,- // and statusText is empty over HTTP/2 anyway.- const error = await response.json().catch(() => ({}));- // Carry the HTTP status on the Error (message unchanged, so the toast de-dup still matches) so- // callers can tell apart a permission 403 from a real server 5xx instead of guessing from text.- // Carry the machine `code` too: the gateway's stable codes (SESSION_LOGOUT_INCOMPLETE,- // SESSION_NAME_TEARDOWN_PENDING, …) drive specific recovery UI, and a reverse-proxy 502 that- // never reached the gateway carries no code at all — that distinction is exactly what the unlink- // classifier keys on instead of fragile message heuristics.- const err = new Error(error.message || `HTTP ${response.status}`) as Error & {- status?: number;- code?: string;- };- err.status = response.status;- if (typeof error.code === 'string') err.code = error.code;- throw err;+ return handleErrorResponse<T>(response);}if (response.status === 204) {@@ -654,17 +659,8 @@ async function requestText(endpoint: string): Promise<string> {headers: { ...(apiKey ? { 'X-API-Key': apiKey } : {}) },});- if (response.status === 401) {- sessionStorage.removeItem('openwa_api_key');- if (typeof window !== 'undefined') {- window.location.assign('/');- return new Promise<string>(() => {});- }- }-if (!response.ok) {- const error = await response.json().catch(() => ({}));- throw new Error(error.message || `HTTP ${response.status}`);+ return handleErrorResponse<string>(response);}return response.text();@@ -683,21 +679,8 @@ async function requestBlob(endpoint: string): Promise<Blob> {const response = await fetch(url, { headers });- if (response.status === 401) {- // The stored API key is invalid/expired/revoked — clear it and return to login- sessionStorage.removeItem('openwa_api_key');- if (typeof window !== 'undefined') {- window.location.assign('/');- // Halt this request's promise chain so callers neither throw nor receive an undefined payload.- return new Promise<Blob>(() => {});- }- }-if (!response.ok) {- const error = await response.json().catch(() => ({}));- const err = new Error(error.message || `HTTP ${response.status}`) as Error & { status?: number };- err.status = response.status;- throw err;+ return handleErrorResponse<Blob>(response);}return response.blob();diff --git a/dashboard/src/utils/authLifecycle.test.ts b/dashboard/src/utils/authLifecycle.test.tsindex 9d7344f22..de3881a14 100644--- a/dashboard/src/utils/authLifecycle.test.ts+++ b/dashboard/src/utils/authLifecycle.test.ts@@ -1,7 +1,10 @@-import { test } from 'node:test';+import '../test-helpers/register-hooks.ts';+import { test, before, afterEach } from 'node:test';import assert from 'node:assert/strict';+import { createElement } from 'react';import { QueryClient } from '@tanstack/react-query';-import { clearActorState, resolveStartupValidation } from './authLifecycle.ts';+import type { installJsdomGlobals as installJsdomGlobalsFn } from '../test-helpers/jsdom.ts';+import { clearActorState, isUserRole, resolveStartupValidation } from './authLifecycle.ts';test('logout cleanup wipes the React Query cache (no cross-actor residue)', () => {const queryClient = new QueryClient();@@ -49,3 +52,147 @@ test('startup validation: ok without a usable role keeps the cached role', () =>assert.deepEqual(resolveStartupValidation(200, { valid: true, role: 'superuser' }), { action: 'keep' });assert.deepEqual(resolveStartupValidation(200, null), { action: 'keep' });});++test('isUserRole accepts exactly the three known roles', () => {+ assert.deepEqual(['admin', 'operator', 'viewer'].filter(isUserRole), ['admin', 'operator', 'viewer']);+ for (const value of ['superuser', '', undefined, null, 42, 'ADMIN']) {+ assert.equal(isUserRole(value), false, `expected ${String(value)} to be rejected`);+ }+});++// ── App-level auth flow: exactly one /auth/validate per sign-in ──────────────+// Render smoke tests of the full App for the two entry paths (fresh sign-in, page reload with a+// saved key). Harness mirrors Infrastructure.test.ts: jsdom globals, a fetch stub recording every+// call, i18n catalogues awaited before render. App brings its own providers, so no wrapper here.++const LOGIN_KEY = 'openwa_api_key';+const ROLE_KEY = 'openwa_user_role';++interface FetchCall {+ method: string;+ path: string;+}++const fetchCalls: FetchCall[] = [];++// Per-test body for POST /auth/validate. The home page's stats endpoints need their object shapes+// ([] would crash Dashboard's overview render); every other request gets an empty list, which the+// post-login pages' React Query hooks tolerate.+let validateBody: { valid?: boolean; role?: string } = { valid: true, role: 'operator' };++function installFetchStub(): void {+ globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ const method = init?.method ?? 'GET';+ const path = url.replace(/^https?:\/\/[^/]+/, '');+ fetchCalls.push({ method, path });++ let body: unknown = [];+ if (method === 'POST' && path === '/api/auth/validate') body = validateBody;+ else if (path === '/api/stats/overview')+ body = { sessions: { active: 0, total: 0, byStatus: {} }, messages: { sent: 0, received: 0, failed: 0, today: { sent: 0, received: 0 } } };+ else if (path.startsWith('/api/stats/messages')) body = { timeSeries: [], byType: {}, bySession: [], topChats: [] };+ return Promise.resolve(+ new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' } }),+ );+ };+}++function validateCallCount(): number {+ return fetchCalls.filter(c => c.method === 'POST' && c.path === '/api/auth/validate').length;+}++type RTL = typeof import('@testing-library/react');+type AppModule = typeof import('../App.tsx');++let rtl: RTL;+let App: AppModule['default'];+let installJsdomGlobals: typeof installJsdomGlobalsFn;++before(async () => {+ ({ installJsdomGlobals } = await import('../test-helpers/jsdom.ts'));+ await installJsdomGlobals();+ installFetchStub();+ // jsdom gaps the authenticated shell hits: useTheme (Layout) reads window.matchMedia, and the+ // lazily-mounted analytics charts construct a ResizeObserver.+ window.matchMedia ??= ((query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addListener() {},+ removeListener() {},+ addEventListener() {},+ removeEventListener() {},+ dispatchEvent() {+ return false;+ },+ })) as typeof window.matchMedia;+ class ResizeObserverStub {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ globalThis.ResizeObserver ??= ResizeObserverStub as unknown as typeof ResizeObserver;+ window.ResizeObserver ??= ResizeObserverStub as unknown as typeof ResizeObserver;+ // Login.tsx reads these Vite compile-time defines at render time; Node has no define step.+ Object.defineProperty(globalThis, '__APP_VERSION__', { value: '0.0.0-test', configurable: true });+ Object.defineProperty(globalThis, '__BUILD_TIME__', { value: new Date(0).toISOString(), configurable: true });+ const { i18nReady } = await import('../i18n/index.ts');+ await i18nReady;+ rtl = await import('@testing-library/react');+ ({ default: App } = await import('../App.tsx'));+});++afterEach(() => {+ rtl.cleanup();+ localStorage.clear();+ sessionStorage.clear();+ fetchCalls.length = 0;+ validateBody = { valid: true, role: 'operator' };+});++// Types a key into the login form and submits it, then waits until App has applied the role from+// the validate response (the synchronous tail of handleLogin).+async function signIn(apiKey: string): Promise<void> {+ const { screen, waitFor, fireEvent } = rtl;+ const input = await screen.findByLabelText('API Key');+ fireEvent.change(input, { target: { value: apiKey } });+ fireEvent.submit(input.closest('form')!);+ await waitFor(() => assert.ok(localStorage.getItem(ROLE_KEY), 'expected a role to be stored after sign-in'));+ // Give the post-login render and its effects a macrotask to fire before counting requests.+ await new Promise(resolve => setTimeout(resolve, 50));+}++test('a fresh sign-in makes exactly one /auth/validate request, feeding the role from its response', async () => {+ rtl.render(createElement(App));++ await signIn('fresh-key');++ // The login page's own validate is the one request; the startup re-validation effect must not+ // re-fire on the null→key transition that storing the fresh key causes.+ assert.equal(validateCallCount(), 1);+ assert.equal(localStorage.getItem(ROLE_KEY), 'operator');+ assert.equal(sessionStorage.getItem(LOGIN_KEY), 'fresh-key');+});++test('a fresh sign-in with a role-less validate response still degrades to viewer', async () => {+ validateBody = { valid: true };+ rtl.render(createElement(App));++ await signIn('fresh-key');++ assert.equal(validateCallCount(), 1);+ assert.equal(localStorage.getItem(ROLE_KEY), 'viewer');+});++test('a page reload with a saved key re-validates once at startup and refreshes the cached role', async () => {+ sessionStorage.setItem(LOGIN_KEY, 'saved-key');+ localStorage.setItem(ROLE_KEY, 'viewer'); // stale cached role+ validateBody = { valid: true, role: 'admin' };+ rtl.render(createElement(App));++ await rtl.waitFor(() => assert.equal(localStorage.getItem(ROLE_KEY), 'admin'));+ await new Promise(resolve => setTimeout(resolve, 50));++ assert.equal(validateCallCount(), 1);+});diff --git a/dashboard/src/utils/authLifecycle.ts b/dashboard/src/utils/authLifecycle.tsindex 8d9d30cd5..3d1a4014e 100644--- a/dashboard/src/utils/authLifecycle.ts+++ b/dashboard/src/utils/authLifecycle.ts@@ -4,7 +4,7 @@ import type { UserRole } from '../types/role';const USER_ROLES: readonly UserRole[] = ['admin', 'operator', 'viewer'];-function isUserRole(value: unknown): value is UserRole {+export function isUserRole(value: unknown): value is UserRole {return typeof value === 'string' && (USER_ROLES as readonly string[]).includes(value);}