Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): let non-admin keys post a status and open Channels

Yudhi Armyndharis2466c7b281ac
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index 50b257810..634cd3e07 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -42,9 +42,9 @@ function AppContent() {
const [savedKey] = useState(() => sessionStorage.getItem('openwa_api_key'));
const [isAuthenticated, setIsAuthenticated] = useState(!!savedKey);
const [, setApiKey] = useState(savedKey || '');
- const { setRole, role } = useRole();
+ const { setRole, role, setEngineType } = useRole();
- const handleLogin = (key: string, validatedRole?: string) => {
+ const handleLogin = (key: string, validatedRole?: string, engineType?: string) => {
setApiKey(key);
sessionStorage.setItem('openwa_api_key', key);
@@ -52,6 +52,7 @@ function AppContent() {
// round-trip is needed here. An absent or unrecognized role falls back to viewer, the
// least-privileged default.
setRole(isUserRole(validatedRole) ? validatedRole : 'viewer');
+ setEngineType(engineType ?? null);
setIsAuthenticated(true);
};
@@ -60,12 +61,13 @@ function AppContent() {
setApiKey('');
setIsAuthenticated(false);
setRole(null);
+ setEngineType(null);
sessionStorage.removeItem('openwa_api_key');
// Wipe the React Query cache too: it is keyed by resource, not actor, so without a full
// clear a logout → login in the same tab with a different key/scope shows the previous
// actor's sessions/messages/apiKeys/audit rows.
clearActorState(queryClient);
- }, [setRole]);
+ }, [setRole, setEngineType]);
// Re-validate and refresh the role on mount if already authenticated
useEffect(() => {
@@ -81,13 +83,14 @@ function AppContent() {
handleLogout();
} else if (decision.action === 'role') {
setRole(decision.role);
+ if (decision.engineType) setEngineType(decision.engineType);
}
})
.catch(() => {
// Network failure (API unreachable): keep the cached role so a transient outage at
// page load doesn't eject the user — an explicit 401/403 above still logs out.
});
- }, [savedKey, setRole, handleLogout]);
+ }, [savedKey, setRole, setEngineType, handleLogout]);
const loadingFallback = (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh' }}>
diff --git a/dashboard/src/components/RoleProvider.tsx b/dashboard/src/components/RoleProvider.tsx
index d42771229..c5fd899a8 100644
--- a/dashboard/src/components/RoleProvider.tsx
+++ b/dashboard/src/components/RoleProvider.tsx
@@ -27,6 +27,19 @@ export function RoleProvider({ children }: { children: ReactNode }) {
}
}, []);
+ // Kept beside the role because GET /infra/engines/current is admin-only: the validate response is
+ // the one place every role learns which engine it is talking to.
+ const [engineType, setEngineTypeState] = useState<string | null>(() => sessionStorage.getItem('openwa_engine_type'));
+
+ const setEngineType = useCallback((newEngineType: string | null) => {
+ setEngineTypeState(newEngineType);
+ if (newEngineType) {
+ sessionStorage.setItem('openwa_engine_type', newEngineType);
+ } else {
+ sessionStorage.removeItem('openwa_engine_type');
+ }
+ }, []);
+
const value: RoleContextType = {
role,
setRole,
@@ -34,6 +47,8 @@ export function RoleProvider({ children }: { children: ReactNode }) {
isOperator: role === 'operator',
isViewer: role === 'viewer',
canWrite: role === 'admin' || role === 'operator',
+ engineType,
+ setEngineType,
};
return <RoleContext.Provider value={value}>{children}</RoleContext.Provider>;
diff --git a/dashboard/src/components/chats/StatusComposeModal.tsx b/dashboard/src/components/chats/StatusComposeModal.tsx
index 2e435b3ab..8fd2d5598 100644
--- a/dashboard/src/components/chats/StatusComposeModal.tsx
+++ b/dashboard/src/components/chats/StatusComposeModal.tsx
@@ -3,7 +3,7 @@ import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { Loader2 } from 'lucide-react';
import { contactApi, sessionApi } from '../../services/api';
-import { useCurrentEngineQuery } from '../../hooks/queries';
+import { useRole } from '../../hooks/useRole';
import { useToast } from '../../hooks/useToast';
import { Modal } from '../Modal';
@@ -20,12 +20,13 @@ interface Props {
function StatusComposeModal({ sessionId, onClose, onPosted }: Props) {
const { t } = useTranslation();
const { success: showSuccessToast, error: showErrorToast } = useToast();
- const currentEngine = useCurrentEngineQuery();
+ // From the sign-in validate response: GET /infra/engines/current is admin-only, and operators post too.
+ const { engineType } = useRole();
// Baileys targets a status post to an explicit allow-list (statusJidList); whatsapp-web.js has no
// per-recipient concept and broadcasts to the account's status-privacy audience instead, so the
// recipient picker is Baileys-only.
- const isBaileysEngine = currentEngine.data?.engineType === 'baileys';
+ const isBaileysEngine = engineType === 'baileys';
const [composeType, setComposeType] = useState<'text' | 'image'>('text');
const [composeText, setComposeText] = useState<string>('');
@@ -120,7 +121,7 @@ function StatusComposeModal({ sessionId, onClose, onPosted }: Props) {
!composePosting &&
// The engine type decides whether recipients are required (Baileys) or omitted (wwjs) — while
// it's still unknown, a Baileys submit would go out with no recipients and 400.
- Boolean(currentEngine.data) &&
+ Boolean(engineType) &&
(composeType === 'text' ? composeText.trim().length > 0 : Boolean(composeImageBase64 || composeImageUrl.trim())) &&
(!isBaileysEngine || composeRecipients.length > 0);
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index 81ed1cd93..8fb02bb1f 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -220,6 +220,7 @@ function holdMedia(path: string): () => void {
// Contact for the status-compose recipient picker (Baileys requires an explicit allow-list).
const CONTACT = { id: '[email protected]', name: 'Bob', number: '15550002222' };
const STATUS_TEXT = 'status text here';
+const CHANNEL = { id: '120363000000000001@newsletter', name: 'Release notes' };
function jsonResponse(data: unknown, status = 200): Response {
return new Response(JSON.stringify(data), {
@@ -276,9 +277,16 @@ function installFetchStub(): void {
if (thirdSessionStatus) listed.push({ ...SESSION_3, status: thirdSessionStatus });
return Promise.resolve(jsonResponse(listed));
}
+ // ADMIN-only on the server, so any other role gets the 403 a real gateway answers.
if (method === 'GET' && path === '/api/infra/engines/current') {
+ if (window.sessionStorage.getItem('openwa_user_role') !== 'admin') {
+ return Promise.resolve(jsonResponse({ message: 'Insufficient permissions. Required: admin' }, 403));
+ }
return Promise.resolve(jsonResponse({ engineType: 'baileys' }));
}
+ if (method === 'GET' && path === `/api/sessions/${SESSION.id}/channels`) {
+ return Promise.resolve(jsonResponse([CHANNEL]));
+ }
if (method === 'GET' && path === `/api/sessions/${SESSION.id}/chats`) {
if (chatsResponder) return chatsResponder(url.includes(`/sessions/${SESSION_2.id}/`) ? SESSION_2.id : SESSION.id);
return Promise.resolve(jsonResponse([CHAT, CHAT_2]));
@@ -370,6 +378,8 @@ before(async () => {
// RoleProvider initializes from sessionStorage; 'admin' makes canWrite true so the composer
// controls render enabled.
window.sessionStorage.setItem('openwa_user_role', 'admin');
+ // The engine POST /auth/validate reported at sign-in, kept next to the role.
+ window.sessionStorage.setItem('openwa_engine_type', 'baileys');
// useWebSocket.connect() bails without this, so no socket would exist to receive a frame. It
// dials nothing: the client is the double above.
window.sessionStorage.setItem('openwa_api_key', 'test-key');
@@ -667,6 +677,53 @@ test('a read-only key is offered no status compose trigger', async () => {
}
});
+test('an operator key on whatsapp-web.js posts a status without the admin-only engine route', async () => {
+ const { screen, fireEvent, within, waitFor } = rtl;
+ window.sessionStorage.setItem('openwa_user_role', 'operator');
+ window.sessionStorage.setItem('openwa_engine_type', 'whatsapp-web.js');
+ try {
+ resetFetchCalls();
+ renderChats();
+ await screen.findByText('Main (15551234567)');
+ fireEvent.click(screen.getByRole('tab', { name: 'Status' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Post a status' }));
+
+ const dialog = await screen.findByRole('dialog');
+ fireEvent.change(within(dialog).getByPlaceholderText('Text'), { target: { value: STATUS_TEXT } });
+ const postButton = within(dialog).getByRole('button', { name: 'Post' }) as HTMLButtonElement;
+ await waitFor(() => assert.equal(postButton.disabled, false, 'Post never enabled for an operator key'));
+ // whatsapp-web.js has no recipient list, so the picker stays hidden and none are sent.
+ assert.equal(within(dialog).queryByRole('checkbox'), null);
+ fireEvent.click(postButton);
+
+ await waitFor(() => {
+ const call = findFetchCall('POST', `/api/sessions/${SESSION.id}/status/send-text`);
+ assert.ok(call, 'expected a POST to the status send-text endpoint');
+ assert.deepEqual(call.body, { text: STATUS_TEXT });
+ });
+ assert.equal(countFetchCalls('GET', '/api/infra/engines/current'), 0);
+ } finally {
+ window.sessionStorage.setItem('openwa_user_role', 'admin');
+ window.sessionStorage.setItem('openwa_engine_type', 'baileys');
+ }
+});
+
+test('an operator key on whatsapp-web.js lists its channels', async () => {
+ const { screen, fireEvent } = rtl;
+ window.sessionStorage.setItem('openwa_user_role', 'operator');
+ window.sessionStorage.setItem('openwa_engine_type', 'whatsapp-web.js');
+ try {
+ renderChats();
+ await screen.findByText('Main (15551234567)');
+ fireEvent.click(screen.getByRole('tab', { name: 'Channels' }));
+ await screen.findByText(CHANNEL.name);
+ assert.equal(screen.queryByText('Channels are not supported on the Baileys engine.'), null);
+ } finally {
+ window.sessionStorage.setItem('openwa_user_role', 'admin');
+ window.sessionStorage.setItem('openwa_engine_type', 'baileys');
+ }
+});
+
test('a writer key opening a chat clears its unread badge', async () => {
const { screen, fireEvent, within, waitFor } = rtl;
const { container } = renderChats();
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 4857277f8..3fc561188 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -49,7 +49,6 @@ import {
import { useChannelMessages } from '../hooks/useChannelMessages';
import { useContactStatuses } from '../hooks/useContactStatuses';
import { useChatScrollPosition } from '../hooks/useChatScrollPosition';
-import { useCurrentEngineQuery } from '../hooks/queries';
import { createTrailingCoalescer } from '../utils/trailingCoalescer';
import MessageBody from '../components/chats/MessageBody';
import MediaLightbox, { type LightboxItem } from '../components/chats/MediaLightbox';
@@ -122,7 +121,7 @@ export function Chats() {
const { t } = useTranslation();
useDocumentTitle(t('nav.chats'));
const { error: showErrorToast, warning: showWarningToast } = useToast();
- const { canWrite } = useRole();
+ const { canWrite, engineType } = useRole();
// Sessions list & active session
const [sessions, setSessions] = useState<Session[]>([]);
@@ -155,8 +154,8 @@ export function Chats() {
// Channels tab: only whatsapp-web.js implements channel listing/reading — Baileys throws 501 for
// both, so the query is gated off entirely (never fired) rather than left to fail per-request.
- const currentEngine = useCurrentEngineQuery();
- const channelsSupported = currentEngine.data?.engineType === 'whatsapp-web.js';
+ // The engine comes from the sign-in validate response, which every role can read.
+ const channelsSupported = engineType === 'whatsapp-web.js';
const channelsQuery = useQuery({
queryKey: ['channels', selectedSessionId],
queryFn: () => sessionApi.getSubscribedChannels(selectedSessionId!),
@@ -965,7 +964,7 @@ export function Chats() {
onSelectChat: setActiveChat,
}}
channelsTab={{
- engineLoading: currentEngine.isLoading,
+ engineLoading: engineType === null,
supported: channelsSupported,
query: channelsQuery,
channels: filteredChannels,
diff --git a/dashboard/src/pages/Login.tsx b/dashboard/src/pages/Login.tsx
index 6d2b39903..8b1826923 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, role?: string) => void;
+ onLogin: (apiKey: string, role?: string, engineType?: string) => void;
}
export function Login({ onLogin }: LoginProps) {
@@ -44,8 +44,8 @@ export function Login({ onLogin }: LoginProps) {
if (response.ok) {
// 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);
+ const data: { role?: string; engineType?: string } = await response.json().catch(() => ({}));
+ onLogin(apiKey, data.role, typeof data.engineType === 'string' ? data.engineType : undefined);
} else {
const errorData = await response.json().catch(() => ({}));
setError(errorData.message || t('login.invalidKey'));
diff --git a/dashboard/src/types/role.ts b/dashboard/src/types/role.ts
index 50345332e..366362a77 100644
--- a/dashboard/src/types/role.ts
+++ b/dashboard/src/types/role.ts
@@ -8,4 +8,7 @@ export interface RoleContextType {
isOperator: boolean;
isViewer: boolean;
canWrite: boolean;
+ /** Engine the gateway runs, as POST /auth/validate reported it; null until it has answered. */
+ engineType: string | null;
+ setEngineType: (engineType: string | null) => void;
}
diff --git a/dashboard/src/utils/authLifecycle.test.ts b/dashboard/src/utils/authLifecycle.test.ts
index 3bc90434f..f0a072e15 100644
--- a/dashboard/src/utils/authLifecycle.test.ts
+++ b/dashboard/src/utils/authLifecycle.test.ts
@@ -47,6 +47,14 @@ test('startup validation: ok + role refreshes the cached role from the server',
});
});
+test('startup validation: ok + role also carries the engine the server reports', () => {
+ assert.deepEqual(resolveStartupValidation(200, { valid: true, role: 'operator', engineType: 'baileys' }), {
+ action: 'role',
+ role: 'operator',
+ engineType: 'baileys',
+ });
+});
+
test('startup validation: ok without a usable role keeps the cached role', () => {
assert.deepEqual(resolveStartupValidation(200, { valid: false }), { action: 'keep' });
assert.deepEqual(resolveStartupValidation(200, { valid: true, role: 'superuser' }), { action: 'keep' });
@@ -67,6 +75,7 @@ test('isUserRole accepts exactly the three known roles', () => {
const LOGIN_KEY = 'openwa_api_key';
const ROLE_KEY = 'openwa_user_role';
+const ENGINE_KEY = 'openwa_engine_type';
interface FetchCall {
method: string;
@@ -78,7 +87,11 @@ 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' };
+let validateBody: { valid?: boolean; role?: string; engineType?: string } = {
+ valid: true,
+ role: 'operator',
+ engineType: 'whatsapp-web.js',
+};
function installFetchStub(): void {
globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
@@ -151,7 +164,7 @@ afterEach(() => {
localStorage.clear();
sessionStorage.clear();
fetchCalls.length = 0;
- validateBody = { valid: true, role: 'operator' };
+ validateBody = { valid: true, role: 'operator', engineType: 'whatsapp-web.js' };
});
// Types a key into the login form and submits it, then waits until App has applied the role from
@@ -176,6 +189,8 @@ test('a fresh sign-in makes exactly one /auth/validate request, feeding the role
assert.equal(validateCallCount(), 1);
assert.equal(sessionStorage.getItem(ROLE_KEY), 'operator');
assert.equal(sessionStorage.getItem(LOGIN_KEY), 'fresh-key');
+ // The engine comes from the same response: a non-admin key cannot read /infra/engines/current.
+ assert.equal(sessionStorage.getItem(ENGINE_KEY), 'whatsapp-web.js');
});
test('a fresh sign-in with a role-less validate response still degrades to viewer', async () => {
@@ -191,11 +206,12 @@ test('a fresh sign-in with a role-less validate response still degrades to viewe
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');
sessionStorage.setItem(ROLE_KEY, 'viewer'); // stale cached role
- validateBody = { valid: true, role: 'admin' };
+ validateBody = { valid: true, role: 'admin', engineType: 'baileys' };
rtl.render(createElement(App));
await rtl.waitFor(() => assert.equal(sessionStorage.getItem(ROLE_KEY), 'admin'));
await new Promise(resolve => setTimeout(resolve, 50));
assert.equal(validateCallCount(), 1);
+ assert.equal(sessionStorage.getItem(ENGINE_KEY), 'baileys');
});
diff --git a/dashboard/src/utils/authLifecycle.ts b/dashboard/src/utils/authLifecycle.ts
index 3d1a4014e..ac2c5898a 100644
--- a/dashboard/src/utils/authLifecycle.ts
+++ b/dashboard/src/utils/authLifecycle.ts
@@ -22,7 +22,8 @@ export function clearActorState(...caches: ClearableCache[]): void {
for (const cache of caches) cache.clear();
}
-export type StartupValidation = { action: 'role'; role: UserRole } | { action: 'logout' } | { action: 'keep' };
+export type StartupValidation =
+ { action: 'role'; role: UserRole; engineType?: string } | { action: 'logout' } | { action: 'keep' };
/**
* Fold the startup /auth/validate answer into an auth decision:
@@ -30,17 +31,22 @@ export type StartupValidation = { action: 'role'; role: UserRole } | { action: '
* logout; the cached role is a lie.
* - any other non-ok status (429 rate limit, 5xx, a proxy error page) → keep the cached role:
* a transient failure proves nothing about the key, so it must not eject the user.
- * - ok + role → refresh the cached role from the server (a demoted key must lose its old powers).
+ * - ok + role → refresh the cached role from the server (a demoted key must lose its old powers),
+ * along with the engine it reports.
* - anything else (unexpected body shape) → keep the cached role.
* A network throw never reaches this function; the caller keeps the cached role for that case
* so a transient outage at page load doesn't eject the user.
*/
export function resolveStartupValidation(
status: number,
- body: { valid?: boolean; role?: string } | null,
+ body: { valid?: boolean; role?: string; engineType?: string } | null,
): StartupValidation {
if (status === 401 || status === 403) return { action: 'logout' };
if (status < 200 || status >= 300) return { action: 'keep' };
- if (body?.valid && isUserRole(body.role)) return { action: 'role', role: body.role };
+ if (body?.valid && isUserRole(body.role)) {
+ return typeof body.engineType === 'string'
+ ? { action: 'role', role: body.role, engineType: body.engineType }
+ : { action: 'role', role: body.role };
+ }
return { action: 'keep' };
}