Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): hide Logs and Show QR from roles the API refuses
Yudhi Armyndharisb57fcf95ade0
diff --git a/dashboard/src/App.test.ts b/dashboard/src/App.test.tsnew file mode 100644index 000000000..eda54efb4--- /dev/null+++ b/dashboard/src/App.test.ts@@ -0,0 +1,86 @@+// Role gating of the Logs page under the bare `node --test` runner, rendered through the real App so+// both halves are covered: the sidebar entry (Layout) and the route itself (App). GET /audit is+// ADMIN-only, so an operator or viewer reaching /logs only ever saw a load error over an empty table.+import './test-helpers/register-hooks.ts';+import { test, before, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { createElement } from 'react';++let role = 'operator';++function jsonResponse(data: unknown, status = 200): Response {+ return new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } });+}++function installFetchStub(): void {+ globalThis.fetch = ((input: RequestInfo | URL): Promise<Response> => {+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;+ const path = url.replace(/^https?:\/\/[^/]+/, '');+ if (path === '/api/auth/validate') return Promise.resolve(jsonResponse({ valid: true, role }));+ if (path === '/api/audit' || path.startsWith('/api/audit?'))+ return Promise.resolve(jsonResponse({ data: [], total: 0 }));+ if (path === '/api/sessions' || path === '/api/webhooks') return Promise.resolve(jsonResponse([]));+ return Promise.resolve(jsonResponse({ message: `unstubbed ${path}` }, 404));+ }) as typeof fetch;+}++let rtl: typeof import('@testing-library/react');+let App: (typeof import('./App.tsx'))['default'];++before(async () => {+ const { installJsdomGlobals } = await import('./test-helpers/jsdom.ts');+ await installJsdomGlobals('http://localhost/logs');+ (globalThis as Record<string, unknown>).__APP_VERSION__ = '0.0.0-test';+ // jsdom has no matchMedia; the theme hook reads it for the system preference.+ window.matchMedia = ((query: string) => ({+ matches: false,+ media: query,+ addEventListener: () => undefined,+ removeEventListener: () => undefined,+ })) as unknown as typeof window.matchMedia;+ installFetchStub();+ // App owns a module-level QueryClient this file cannot clear, and its five-minute gcTime timers would+ // hold the test process open after the last case. Unref them so they never keep the runner alive.+ const { timeoutManager } = await import('@tanstack/react-query');+ const unref = (id: ReturnType<typeof setTimeout>): ReturnType<typeof setTimeout> => id.unref();+ timeoutManager.setTimeoutProvider({+ setTimeout: (callback, delay) => unref(setTimeout(callback, delay)),+ clearTimeout: id => clearTimeout(id),+ setInterval: (callback, delay) => unref(setInterval(callback, delay)),+ clearInterval: id => clearInterval(id),+ });+ const { i18nReady } = await import('./i18n/index.ts');+ await i18nReady;+ rtl = await import('@testing-library/react');+ ({ default: App } = await import('./App.tsx'));+});++afterEach(() => {+ rtl.cleanup();+});++function renderAt(path: string, as: string): void {+ role = as;+ window.history.replaceState(null, '', path);+ window.sessionStorage.setItem('openwa_api_key', 'test-key');+ window.localStorage.setItem('openwa_user_role', as);+ rtl.render(createElement(App));+}++const logsLink = (): Element | null => document.querySelector('a[href="/logs"]');++test('an operator gets no Logs entry and /logs sends them home', async () => {+ renderAt('/logs', 'operator');+ // The sidebar renders once the lazy route resolves; wait for a nav entry every role has.+ await rtl.waitFor(() => assert.ok(document.querySelector('a[href="/sessions"]')));+ assert.equal(logsLink() === null, true, 'the Logs nav entry is shown to an operator');+ await rtl.waitFor(() => assert.equal(window.location.pathname, '/'));+});++test('an admin keeps the Logs entry and the route', async () => {+ renderAt('/logs', 'admin');+ await rtl.waitFor(() => assert.ok(logsLink(), 'the Logs nav entry is missing for an admin'));+ // Give the router a chance to redirect before asserting that it did not.+ await new Promise(resolve => setTimeout(resolve, 50));+ assert.equal(window.location.pathname, '/logs');+});diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsxindex bb012a29d..50b257810 100644--- a/dashboard/src/App.tsx+++ b/dashboard/src/App.tsx@@ -115,7 +115,7 @@ function AppContent() {<Route path="webhooks" element={<Webhooks />} /><Route path="templates" element={<Templates />} />{role === 'admin' && <Route path="api-keys" element={<ApiKeys />} />}- <Route path="logs" element={<Logs />} />+ {role === 'admin' && <Route path="logs" element={<Logs />} />}<Route path="message-tester" element={<MessageTester />} />{role === 'admin' && <Route path="infrastructure" element={<Infrastructure />} />}{role === 'admin' && <Route path="plugins" element={<Plugins />} />}diff --git a/dashboard/src/components/Layout.tsx b/dashboard/src/components/Layout.tsxindex 8a18963a3..4e9c1b551 100644--- a/dashboard/src/components/Layout.tsx+++ b/dashboard/src/components/Layout.tsx@@ -44,7 +44,8 @@ const allNavItems = [// Backend /infra/* is ADMIN-only; hide the nav item from non-admins (UX + defense-in-depth).{ to: '/infrastructure', icon: Server, key: 'infrastructure' as const, adminOnly: true },{ to: '/plugins', icon: Puzzle, key: 'plugins' as const, adminOnly: true },- { to: '/logs', icon: FileText, key: 'logs' as const, adminOnly: false },+ // Backend /audit is ADMIN-only too.+ { to: '/logs', icon: FileText, key: 'logs' as const, adminOnly: true },];const themeIcons = { light: Sun, dark: Moon, system: Monitor };diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.tsindex 8af0acc7d..6cbd75c21 100644--- a/dashboard/src/pages/Sessions.test.ts+++ b/dashboard/src/pages/Sessions.test.ts@@ -566,6 +566,21 @@ test('a failed mount read is retried when the feed first connects after its ownassert.equal(screen.queryByText('gateway unavailable') === null, true, 'the failed read error is still shown');});+test('a read-only key gets no Show QR button, since the QR is operator-only', async () => {+ const { screen, within } = rtl;+ resetFetchCalls();+ window.localStorage.setItem('openwa_user_role', 'viewer');+ try {+ renderSessions();+ const card = (await screen.findByText('new-device')).closest('.session-card') as HTMLElement;+ // The pairing placeholder still renders; only the action that would poll a 403 is gone.+ assert.ok(card.querySelector('.qr-placeholder'));+ assert.equal(within(card).queryByRole('button', { name: 'Show QR' }) === null, true);+ } finally {+ window.localStorage.setItem('openwa_user_role', 'admin');+ }+});+// ── Auto-reject toggle ───────────────────────────────────────────────────────async function openDetailFor(name: string): Promise<HTMLInputElement> {diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex fbca7cb05..23e425982 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -1077,13 +1077,17 @@ export function Sessions() {<div className="qr-placeholder"><QrCode size={80} className="qr-icon" /><p>{session.status === 'qr_ready' ? t('sessions.qr.scanToConnect') : t('sessions.qr.preparing')}</p>- <button- className="btn-sm"- onClick={() => handleShowQR(session.id)}- disabled={session.status !== 'qr_ready'}- >- {session.status === 'qr_ready' ? t('sessions.qr.showQr') : t('sessions.qr.loading')}- </button>+ {/* The QR is operator-only over REST and the socket, so a read-only key would open a+ modal that never gets a code. */}+ {canWrite && (+ <button+ className="btn-sm"+ onClick={() => handleShowQR(session.id)}+ disabled={session.status !== 'qr_ready'}+ >+ {session.status === 'qr_ready' ? t('sessions.qr.showQr') : t('sessions.qr.loading')}+ </button>+ )}</div>) : (<div className="session-info">