Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): hide unscoped-only pages from a session-scoped admin
Yudhi Armyndharisb4a43ab940c3
diff --git a/dashboard/src/components/Layout.test.ts b/dashboard/src/components/Layout.test.tsindex 831657f15..8e1e58567 100644--- a/dashboard/src/components/Layout.test.ts+++ b/dashboard/src/components/Layout.test.ts@@ -1,13 +1,39 @@// The sidebar theme button cycles light, dark and "follow the system". The choice is stored, so a button// that only flipped light and dark lost "System" for good after the first click.import '../test-helpers/register-hooks.ts';-import { test, before, after } from 'node:test';+import { test, before, after, afterEach } from 'node:test';import assert from 'node:assert/strict';import { createElement } from 'react';let rtl: typeof import('@testing-library/react');let Layout: (typeof import('./Layout.tsx'))['Layout'];let MemoryRouter: (typeof import('react-router-dom'))['MemoryRouter'];+let RoleContext: (typeof import('../hooks/useRole.tsx'))['RoleContext'];+// Every URL the layout asked for.+const requested: string[] = [];++/** The layout for an admin key, restricted to selected sessions when `scoped` is set. */+function renderLayout(scoped = false): ReturnType<typeof import('@testing-library/react').render> {+ const role = {+ role: 'admin' as const,+ setRole: () => undefined,+ isAdmin: true,+ isOperator: true,+ isViewer: false,+ canWrite: true,+ engineType: 'whatsapp-web.js',+ setEngineType: () => undefined,+ scoped,+ setScoped: () => undefined,+ };+ return rtl.render(+ createElement(+ RoleContext.Provider,+ { value: role },+ createElement(MemoryRouter, null, createElement(Layout, { onLogout: () => undefined, userRole: 'admin' })),+ ),+ );+}before(async () => {const { installJsdomGlobals } = await import('../test-helpers/jsdom.ts');@@ -20,22 +46,28 @@ before(async () => {addEventListener: () => undefined,removeEventListener: () => undefined,})) as unknown as typeof window.matchMedia;- globalThis.fetch = (() =>- Promise.resolve(new Response(JSON.stringify({ message: 'unstubbed' }), { status: 404 }))) as typeof fetch;+ globalThis.fetch = ((input: RequestInfo | URL) => {+ requested.push(String(input));+ return Promise.resolve(new Response(JSON.stringify({ message: 'unstubbed' }), { status: 404 }));+ }) as typeof fetch;const { i18nReady } = await import('../i18n/index.ts');await i18nReady;rtl = await import('@testing-library/react');({ MemoryRouter } = await import('react-router-dom'));({ Layout } = await import('./Layout.tsx'));+ ({ RoleContext } = await import('../hooks/useRole.tsx'));+});++afterEach(() => {+ rtl.cleanup();+ requested.length = 0;});after(() => rtl.cleanup());test('the theme button can return to following the system', () => {localStorage.removeItem('openwa_theme');- const { container } = rtl.render(- createElement(MemoryRouter, null, createElement(Layout, { onLogout: () => undefined, userRole: 'admin' })),- );+ const { container } = renderLayout();const button = container.querySelector<HTMLButtonElement>('.appearance-menu .theme-toggle-btn')!;const seen = [button.textContent];for (let i = 0; i < 3; i++) {@@ -48,3 +80,26 @@ test('the theme button can return to following the system', () => {assert.deepEqual(seen, ['System', 'Light', 'Dark', 'System']);assert.equal(localStorage.getItem('openwa_theme'), 'system');});++// The key management, infrastructure and plugin routes refuse a key restricted to selected sessions, whatever+// its role, and every refusal lands in the audit log as a failed attempt.+test('an admin key scoped to sessions is not offered the pages that refuse it', async () => {+ renderLayout(true);+ const { screen } = rtl;+ assert.equal(screen.queryByRole('link', { name: 'API Keys' }) === null, true);+ assert.equal(screen.queryByRole('link', { name: 'Infrastructure' }) === null, true);+ assert.equal(screen.queryByRole('link', { name: 'Plugins' }) === null, true);+ // The audit read is filtered to the key's sessions, not refused.+ assert.ok(screen.getByRole('link', { name: 'Logs' }));+ await rtl.waitFor(() => assert.ok(requested.some(url => url.includes('/health'))));+ assert.equal(+ requested.some(url => url.includes('/infra/update-check')),+ false,+ );+});++test('an unscoped admin key still checks for a newer release', async () => {+ renderLayout();+ assert.ok(rtl.screen.getByRole('link', { name: 'Plugins' }));+ await rtl.waitFor(() => assert.ok(requested.some(url => url.includes('/infra/update-check'))));+});diff --git a/dashboard/src/components/Layout.tsx b/dashboard/src/components/Layout.tsxindex 772676df0..fae4fd319 100644--- a/dashboard/src/components/Layout.tsx+++ b/dashboard/src/components/Layout.tsx@@ -23,7 +23,7 @@ import {Languages,} from 'lucide-react';import { useTheme } from '../hooks/useTheme';-import { type UserRole } from '../hooks/useRole';+import { useRole, type UserRole } from '../hooks/useRole';import { languageOptions, resolveSupportedLanguage, rtlLanguages, type SupportedLanguage } from '../i18n';import { healthApi, infraApi } from '../services/api';import './Layout.css';@@ -33,17 +33,18 @@ interface LayoutProps {userRole: UserRole | null;}+// unscopedOnly: every route behind the page refuses a key restricted to selected sessions, whatever its role.const allNavItems = [{ to: '/', icon: LayoutDashboard, key: 'dashboard' as const, adminOnly: false },{ to: '/sessions', icon: Smartphone, key: 'sessions' as const, adminOnly: false },{ to: '/chats', icon: MessageSquare, key: 'chats' as const, adminOnly: false },{ to: '/webhooks', icon: Webhook, key: 'webhooks' as const, adminOnly: false },{ to: '/templates', icon: ClipboardList, key: 'templates' as const, adminOnly: false },- { to: '/api-keys', icon: Key, key: 'apiKeys' as const, adminOnly: true },+ { to: '/api-keys', icon: Key, key: 'apiKeys' as const, adminOnly: true, unscopedOnly: true },{ to: '/message-tester', icon: Send, key: 'messageTester' as const, adminOnly: false },// 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: '/infrastructure', icon: Server, key: 'infrastructure' as const, adminOnly: true, unscopedOnly: true },+ { to: '/plugins', icon: Puzzle, key: 'plugins' as const, adminOnly: true, unscopedOnly: true },// Backend /audit is ADMIN-only too.{ to: '/logs', icon: FileText, key: 'logs' as const, adminOnly: true },];@@ -60,7 +61,10 @@ export function Layout({ onLogout, userRole }: LayoutProps) {value: t(`theme.${theme === 'light' ? 'dark' : theme === 'dark' ? 'system' : 'light'}`),});- const navItems = allNavItems.filter(item => !item.adminOnly || userRole === 'admin');+ const { scoped } = useRole();+ const navItems = allNavItems.filter(+ item => (!item.adminOnly || userRole === 'admin') && (!item.unscopedOnly || !scoped),+ );const [isCollapsed, setIsCollapsed] = useState(false);const [isMobileOpen, setIsMobileOpen] = useState(false);@@ -68,8 +72,8 @@ export function Layout({ onLogout, userRole }: LayoutProps) {// Show the build-time version immediately, then replace it with the live running version from the// backend so a stale-built bundle can't display the wrong number. Falls back silently on error.const [version, setVersion] = useState(__APP_VERSION__);- // A newer published release, shown to admins as a link to its notes. The route is ADMIN-only and- // the backend answers quietly when GitHub is unreachable or the check is turned off.+ // A newer published release, shown to admins as a link to its notes. The route is ADMIN-only, refuses a+ // session-scoped key, and answers quietly when GitHub is unreachable or the check is turned off.const [update, setUpdate] = useState<{ latest: string; url: string } | null>(null);const [isLanguageMenuOpen, setIsLanguageMenuOpen] = useState(false);const languageMenuRef = useRef<HTMLDivElement>(null);@@ -100,7 +104,7 @@ export function Layout({ onLogout, userRole }: LayoutProps) {}, []);useEffect(() => {- if (userRole !== 'admin') return;+ if (userRole !== 'admin' || scoped) return;let active = true;infraApi.getUpdateCheck()@@ -115,7 +119,7 @@ export function Layout({ onLogout, userRole }: LayoutProps) {return () => {active = false;};- }, [userRole]);+ }, [userRole, scoped]);const handleNavClick = () => {if (isMobile) setIsMobileOpen(false);