Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): offer chat write actions to writer keys only

Yudhi Armyndharisb93d05f32804
diff --git a/dashboard/src/components/chats/ChatSidebar.tsx b/dashboard/src/components/chats/ChatSidebar.tsx
index 0b2889cc0..7da251ecc 100644
--- a/dashboard/src/components/chats/ChatSidebar.tsx
+++ b/dashboard/src/components/chats/ChatSidebar.tsx
@@ -2,6 +2,7 @@ import { useTranslation } from 'react-i18next';
import { AlertCircle, CircleDashed, Loader2, Megaphone, Plus, Search } from 'lucide-react';
import type { UseQueryResult } from '@tanstack/react-query';
import type { Channel, Chat, ContactStatusGroup, Session } from '../../services/api';
+import { useRole } from '../../hooks/useRole';
import ChatAvatar from './ChatAvatar';
export type ChatsTab = 'chats' | 'channels' | 'status';
@@ -57,6 +58,8 @@ function ChatSidebar({
statusTab,
}: ChatSidebarProps) {
const { t } = useTranslation();
+ // Posting a status needs an operator key; a read-only key would only reach a 403.
+ const { canWrite } = useRole();
const formatLastMessageSnippet = (chat: Chat) => chat.lastMessage || '';
@@ -164,7 +167,7 @@ function ChatSidebar({
</div>
{/* Compose a new status — only meaningful on the Status tab. */}
- {activeTab === 'status' && (
+ {activeTab === 'status' && canWrite && (
<button type="button" className="btn-primary status-compose-trigger" onClick={onComposeStatus}>
<Plus size={16} />
{t('chats.status.compose')}
diff --git a/dashboard/src/components/chats/ChatThread.test.ts b/dashboard/src/components/chats/ChatThread.test.ts
new file mode 100644
index 000000000..2fbd5b7d9
--- /dev/null
+++ b/dashboard/src/components/chats/ChatThread.test.ts
@@ -0,0 +1,107 @@
+// Render test for the chat thread's write actions. The gateway answers reply, react, delete and a
+// prompt-button tap only for an operator key, so a read-only key must not be offered them.
+import '../../test-helpers/register-hooks.ts';
+import { test, before, afterEach } from 'node:test';
+import assert from 'node:assert/strict';
+import { createElement, createRef } from 'react';
+import type { Chat } from '../../services/api.ts';
+import type { ChatMessageView } from '../../utils/chatMessages.ts';
+
+type RTL = typeof import('@testing-library/react');
+
+let rtl: RTL;
+let ChatThread: typeof import('./ChatThread.tsx').default;
+let RoleProvider: typeof import('../RoleProvider.tsx').RoleProvider;
+
+before(async () => {
+ const { installJsdomGlobals } = await import('../../test-helpers/jsdom.ts');
+ await installJsdomGlobals();
+ const { i18nReady } = await import('../../i18n/index.ts');
+ await i18nReady;
+ rtl = await import('@testing-library/react');
+ ({ RoleProvider } = await import('../RoleProvider.tsx'));
+ ({ default: ChatThread } = await import('./ChatThread.tsx'));
+});
+
+afterEach(() => {
+ rtl.cleanup();
+ window.localStorage.removeItem('openwa_user_role');
+});
+
+const CHAT: Chat = {
+ name: 'Alice',
+ isGroup: false,
+ kind: 'individual',
+ unreadCount: 0,
+ timestamp: 1_700_000_000,
+ archived: false,
+ pinned: false,
+ muted: false,
+};
+
+const PROMPT: ChatMessageView = {
+ id: 'db-1',
+ waMessageId: 'wamid.1',
+ chatId: CHAT.id,
+ from: CHAT.id,
+ to: 'me',
+ body: 'Confirm?',
+ type: 'text',
+ direction: 'incoming',
+ status: 'delivered',
+ timestamp: 1_700_000_000,
+ createdAt: new Date(1_700_000_000_000).toISOString(),
+ metadata: { buttons: [{ id: 'y', text: 'Yes' }] },
+};
+
+function renderThread(role: string): { clicks: string[]; container: HTMLElement } {
+ window.localStorage.setItem('openwa_user_role', role);
+ const clicks: string[] = [];
+ const noop = () => {};
+ const { container } = rtl.render(
+ createElement(
+ RoleProvider,
+ null,
+ createElement(ChatThread, {
+ sessionId: 's1',
+ activeChat: CHAT,
+ messages: [PROMPT],
+ loadingMessages: false,
+ messagesError: false,
+ messagesContainerRef: createRef<HTMLDivElement>(),
+ hasMoreMessages: false,
+ loadingOlderMessages: false,
+ onLoadOlderMessages: noop,
+ onMediaLoad: noop,
+ measureMedia: noop,
+ onOpenImage: noop,
+ onReply: noop,
+ onReact: noop,
+ onDelete: noop,
+ onClickButton: async (_message, button) => {
+ clicks.push(button.id);
+ },
+ }),
+ ),
+ );
+ return { clicks, container };
+}
+
+test('a read-only key sees prompt choices disabled and no reply, react or delete actions', () => {
+ const { clicks, container } = renderThread('viewer');
+ const yes = rtl.screen.getByRole('button', { name: 'Yes' });
+ assert.equal(yes.matches(':disabled'), true);
+ rtl.fireEvent.click(yes);
+ assert.deepEqual(clicks, []);
+ assert.ok(!container.querySelector('.message-actions-menu'));
+});
+
+test('an operator key can tap a prompt choice and gets the message actions', async () => {
+ const { clicks, container } = renderThread('operator');
+ const yes = rtl.screen.getByRole('button', { name: 'Yes' });
+ assert.equal(yes.matches(':disabled'), false);
+ rtl.fireEvent.click(yes);
+ await rtl.waitFor(() => assert.deepEqual(clicks, ['y']));
+ assert.ok(container.querySelector('.message-actions-menu'));
+});
diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsx
index 456fa3355..fa00b527a 100644
--- a/dashboard/src/components/chats/ChatThread.tsx
+++ b/dashboard/src/components/chats/ChatThread.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState, type RefObject } from 'react';
import { useTranslation } from 'react-i18next';
import { AlertCircle, ChevronDown, CornerUpLeft, Loader2, MessageSquare, Smile, Trash2 } from 'lucide-react';
+import { useRole } from '../../hooks/useRole';
import { sessionApi, type Chat } from '../../services/api';
import { getMediaSrc, senderKey, type ChatMessageView } from '../../utils/chatMessages';
import { shouldFetchOlderMessages } from '../../utils/scrollDecision';
@@ -62,6 +63,9 @@ function ChatThread({
onClickButton,
}: ChatThreadProps) {
const { t } = useTranslation();
+ // Reply, react, delete and prompt taps all need an operator key, like the composer; a viewer
+ // would only reach a 403.
+ const { canWrite } = useRole();
// Media the message list did not inline. The route serves the bytes as an attachment
// (Content-Disposition), and the list only carries payloads up to
@@ -427,7 +431,7 @@ function ChatThread({
key={`${idx}:${btn.id}`}
type="button"
className={`message-prompt-button${state?.selectedId === btn.id ? ' selected' : ''}${state?.done ? ' answered' : ''}`}
- disabled={disabled}
+ disabled={disabled || !canWrite}
onClick={() => void handleClickButton(msg, btn)}
>
{loading ? <Loader2 size={14} className="animate-spin" /> : btn.text}
@@ -476,7 +480,7 @@ function ChatThread({
</div>
{/* Message actions menu (hover) */}
- {!isRevoked && (
+ {canWrite && !isRevoked && (
<div className="message-actions-menu">
<button
type="button"
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index a3d67bdd4..62731c73a 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -611,6 +611,21 @@ test('Escape dismisses the message search results instead of the conversation be
await waitFor(() => assert.ok(!screen.queryByRole('button', { name: 'Back' }), 'Escape did not close the room'));
});
+test('a read-only key is offered no status compose trigger', async () => {
+ const { screen, fireEvent } = rtl;
+ window.localStorage.setItem('openwa_user_role', 'viewer');
+ try {
+ renderChats();
+ await screen.findByText('Main (15551234567)');
+ fireEvent.click(screen.getByRole('tab', { name: 'Status' }));
+ // Reading statuses stays open to a viewer; only posting one is withheld.
+ await screen.findByText('No contacts have an active status.');
+ assert.ok(!screen.queryByRole('button', { name: 'Post a status' }), 'a viewer key was offered status compose');
+ } finally {
+ window.localStorage.setItem('openwa_user_role', 'admin');
+ }
+});
+
// Stage a file in the open room and wait for the preview banner. A non-image type is used on
// purpose: the image branch calls URL.createObjectURL, which JSDOM does not implement.
//