Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): keep the signed-in role per tab with its API key

Yudhi Armyndharisc40d3dff314d
diff --git a/dashboard/src/App.test.ts b/dashboard/src/App.test.ts
index eda54efb4..d18782401 100644
--- a/dashboard/src/App.test.ts
+++ b/dashboard/src/App.test.ts
@@ -63,7 +63,7 @@ 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);
+ window.sessionStorage.setItem('openwa_user_role', as);
rtl.render(createElement(App));
}
diff --git a/dashboard/src/components/RoleProvider.tsx b/dashboard/src/components/RoleProvider.tsx
index bf3587630..d409a6818 100644
--- a/dashboard/src/components/RoleProvider.tsx
+++ b/dashboard/src/components/RoleProvider.tsx
@@ -3,17 +3,19 @@ import type { UserRole, RoleContextType } from '../types/role';
import { RoleContext } from '../hooks/useRole';
export function RoleProvider({ children }: { children: ReactNode }) {
+ // Per tab, next to the API key it was validated for: a role outliving its key (or shared with
+ // another tab signed in with a different key) would gate the UI for the wrong actor.
const [role, setRoleState] = useState<UserRole | null>(() => {
- const saved = localStorage.getItem('openwa_user_role');
+ const saved = sessionStorage.getItem('openwa_user_role');
return (saved as UserRole) || null;
});
const setRole = useCallback((newRole: UserRole | null) => {
setRoleState(newRole);
if (newRole) {
- localStorage.setItem('openwa_user_role', newRole);
+ sessionStorage.setItem('openwa_user_role', newRole);
} else {
- localStorage.removeItem('openwa_user_role');
+ sessionStorage.removeItem('openwa_user_role');
}
}, []);
diff --git a/dashboard/src/components/chats/ChatThread.test.ts b/dashboard/src/components/chats/ChatThread.test.ts
index dbff7612c..8437c223d 100644
--- a/dashboard/src/components/chats/ChatThread.test.ts
+++ b/dashboard/src/components/chats/ChatThread.test.ts
@@ -25,7 +25,7 @@ before(async () => {
afterEach(() => {
rtl.cleanup();
- window.localStorage.removeItem('openwa_user_role');
+ window.sessionStorage.removeItem('openwa_user_role');
});
const CHAT: Chat = {
@@ -59,7 +59,7 @@ function renderThread(
role: string,
messages: ChatMessageView[] = [PROMPT],
): { clicks: string[]; container: HTMLElement } {
- window.localStorage.setItem('openwa_user_role', role);
+ window.sessionStorage.setItem('openwa_user_role', role);
const clicks: string[] = [];
const noop = () => {};
const { container } = rtl.render(
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index 63e3059e9..bc35752d7 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -354,9 +354,9 @@ before(async () => {
({ installJsdomGlobals } = await import('../test-helpers/jsdom.ts'));
await installJsdomGlobals();
installFetchStub();
- // RoleProvider initializes from localStorage; 'admin' makes canWrite true so the composer
+ // RoleProvider initializes from sessionStorage; 'admin' makes canWrite true so the composer
// controls render enabled.
- window.localStorage.setItem('openwa_user_role', 'admin');
+ window.sessionStorage.setItem('openwa_user_role', 'admin');
// 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');
@@ -638,7 +638,7 @@ test('Escape dismisses the message search results instead of the conversation be
test('a read-only key is offered no status compose trigger', async () => {
const { screen, fireEvent } = rtl;
- window.localStorage.setItem('openwa_user_role', 'viewer');
+ window.sessionStorage.setItem('openwa_user_role', 'viewer');
try {
renderChats();
await screen.findByText('Main (15551234567)');
@@ -647,7 +647,7 @@ test('a read-only key is offered no status compose trigger', async () => {
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');
+ window.sessionStorage.setItem('openwa_user_role', 'admin');
}
});
@@ -695,7 +695,7 @@ test('a chat whose newest message has no text does not claim to have no messages
test('a read-only key opening a chat sends no mark-as-read', async () => {
const { screen, fireEvent, within, waitFor } = rtl;
resetFetchCalls();
- window.localStorage.setItem('openwa_user_role', 'viewer');
+ window.sessionStorage.setItem('openwa_user_role', 'viewer');
try {
const { container } = renderChats();
await screen.findByText('Main (15551234567)');
@@ -734,7 +734,7 @@ test('a read-only key opening a chat sends no mark-as-read', async () => {
assert.ok(screen.queryByLabelText('3 unread messages'), 'the open chat did not count the arrival'),
);
} finally {
- window.localStorage.setItem('openwa_user_role', 'admin');
+ window.sessionStorage.setItem('openwa_user_role', 'admin');
}
});
diff --git a/dashboard/src/pages/Dashboard.test.ts b/dashboard/src/pages/Dashboard.test.ts
index eb14f0273..f7b43260f 100644
--- a/dashboard/src/pages/Dashboard.test.ts
+++ b/dashboard/src/pages/Dashboard.test.ts
@@ -70,7 +70,7 @@ before(async () => {
disconnect(): void {}
};
installFetchStub();
- window.localStorage.setItem('openwa_user_role', 'viewer');
+ window.sessionStorage.setItem('openwa_user_role', 'viewer');
const { i18nReady } = await import('../i18n/index.ts');
await i18nReady;
rtl = await import('@testing-library/react');
@@ -87,7 +87,7 @@ afterEach(() => {
sessionList = [];
stopStatus = 200;
sessionsStatus = 200;
- window.localStorage.setItem('openwa_user_role', 'viewer');
+ window.sessionStorage.setItem('openwa_user_role', 'viewer');
});
function renderDashboard(): void {
@@ -152,7 +152,7 @@ test('a failed stop is reported, not swallowed', async () => {
webhooksStatus = 200;
sessionList = [READY_SESSION];
stopStatus = 400;
- window.localStorage.setItem('openwa_user_role', 'operator');
+ window.sessionStorage.setItem('openwa_user_role', 'operator');
renderDashboard();
const disconnect = await rtl.screen.findByRole('button', { name: 'Disconnect' });
// The session changed on the server even though the stop answered an error: the list is re-read.
diff --git a/dashboard/src/pages/MessageTester.test.ts b/dashboard/src/pages/MessageTester.test.ts
index ea7449ab8..7e5a9e4e5 100644
--- a/dashboard/src/pages/MessageTester.test.ts
+++ b/dashboard/src/pages/MessageTester.test.ts
@@ -45,7 +45,7 @@ afterEach(() => {
rtl.cleanup();
textReads = 0;
globalThis.fetch = emptyFetch;
- window.localStorage.removeItem('openwa_user_role');
+ window.sessionStorage.removeItem('openwa_user_role');
});
interface BulkItem {
@@ -88,7 +88,7 @@ function stubGateway(): { bulkBodies: { messages: BulkItem[] }[] } {
}
async function renderBulkAsWriter(): Promise<HTMLElement> {
- window.localStorage.setItem('openwa_user_role', 'admin');
+ window.sessionStorage.setItem('openwa_user_role', 'admin');
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1_000 } } });
const { container } = rtl.render(
createElement(QueryClientProvider, { client }, createElement(RoleProvider, null, createElement(MessageTester))),
@@ -137,7 +137,7 @@ let restoreFetch: (() => void) | null = null;
afterEach(() => {
restoreFetch?.();
restoreFetch = null;
- window.localStorage.removeItem('openwa_user_role');
+ window.sessionStorage.removeItem('openwa_user_role');
});
function groupJsonResponse(data: unknown, status = 200): Response {
@@ -170,7 +170,7 @@ function stubGroupGateway(groups: { id: string; name?: string }[], refuseFirstWi
}
async function renderGroupsAsWriter(): Promise<void> {
- window.localStorage.setItem('openwa_user_role', 'admin');
+ window.sessionStorage.setItem('openwa_user_role', 'admin');
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1_000 } } });
rtl.render(
createElement(QueryClientProvider, { client }, createElement(RoleProvider, null, createElement(MessageTester))),
@@ -291,7 +291,7 @@ test('a session that stops being ready is replaced by what the selector shows',
}
return Promise.resolve(jsonResponse([]));
}) as typeof fetch;
- window.localStorage.setItem('openwa_user_role', 'admin');
+ window.sessionStorage.setItem('openwa_user_role', 'admin');
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1_000 } } });
const { container } = rtl.render(
createElement(QueryClientProvider, { client }, createElement(RoleProvider, null, createElement(MessageTester))),
diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.ts
index 4133a010c..a00cfa186 100644
--- a/dashboard/src/pages/Sessions.test.ts
+++ b/dashboard/src/pages/Sessions.test.ts
@@ -285,9 +285,9 @@ before(async () => {
({ installJsdomGlobals } = await import('../test-helpers/jsdom.ts'));
await installJsdomGlobals();
installFetchStub();
- // RoleProvider seeds from localStorage; 'admin' makes canWrite true, or every action button
+ // RoleProvider seeds from sessionStorage; 'admin' makes canWrite true, or every action button
// (New Session, Stop/Start, Unlink, Delete, Kill Stuck) is hidden and there is nothing to test.
- window.localStorage.setItem('openwa_user_role', 'admin');
+ window.sessionStorage.setItem('openwa_user_role', 'admin');
// Deliberately NOT setting sessionStorage['openwa_api_key'] here: useWebSocket.connect() bails
// with a console.warn when it's absent, so the page opens no socket. A case that drives the live
// feed sets the key itself; the client it reaches is the socket.io double, which dials nothing.
@@ -1184,7 +1184,7 @@ test('a connect retries a failed list read once, even when each failure carries
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');
+ window.sessionStorage.setItem('openwa_user_role', 'viewer');
try {
renderSessions();
const card = (await screen.findByText('new-device')).closest('.session-card') as HTMLElement;
@@ -1192,7 +1192,7 @@ test('a read-only key gets no Show QR button, since the QR is operator-only', as
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');
+ window.sessionStorage.setItem('openwa_user_role', 'admin');
}
});
diff --git a/dashboard/src/pages/Templates.test.ts b/dashboard/src/pages/Templates.test.ts
index ecad26fb2..c0b78da67 100644
--- a/dashboard/src/pages/Templates.test.ts
+++ b/dashboard/src/pages/Templates.test.ts
@@ -60,7 +60,7 @@ before(async () => {
const { installJsdomGlobals } = await import('../test-helpers/jsdom.ts');
await installJsdomGlobals();
installFetchStub();
- window.localStorage.setItem('openwa_user_role', 'viewer');
+ window.sessionStorage.setItem('openwa_user_role', 'viewer');
const { i18nReady } = await import('../i18n/index.ts');
await i18nReady;
rtl = await import('@testing-library/react');
@@ -94,7 +94,7 @@ test('a write key can delete a template from its row, and a read-only key cannot
templates = [{ id: 'tpl-1', name: 'invoice-reminder', body: 'Hi {{name}}' }];
deleted.length = 0;
- window.localStorage.setItem('openwa_user_role', 'operator');
+ window.sessionStorage.setItem('openwa_user_role', 'operator');
renderTemplates();
const row = (await screen.findByText('invoice-reminder')).closest('.template-list-row') as HTMLElement;
@@ -107,7 +107,7 @@ test('a write key can delete a template from its row, and a read-only key cannot
await waitFor(() => assert.deepEqual(deleted, ['tpl-1'], 'the delete never reached the API'));
rtl.cleanup();
- window.localStorage.setItem('openwa_user_role', 'viewer');
+ window.sessionStorage.setItem('openwa_user_role', 'viewer');
templates = [{ id: 'tpl-1', name: 'invoice-reminder', body: 'Hi {{name}}' }];
renderTemplates();
diff --git a/dashboard/src/pages/Webhooks.test.ts b/dashboard/src/pages/Webhooks.test.ts
index a125eb017..7d1efc7ac 100644
--- a/dashboard/src/pages/Webhooks.test.ts
+++ b/dashboard/src/pages/Webhooks.test.ts
@@ -40,7 +40,7 @@ before(async () => {
const { installJsdomGlobals } = await import('../test-helpers/jsdom.ts');
await installJsdomGlobals();
installFetchStub();
- window.localStorage.setItem('openwa_user_role', 'viewer');
+ window.sessionStorage.setItem('openwa_user_role', 'viewer');
const { i18nReady } = await import('../i18n/index.ts');
await i18nReady;
rtl = await import('@testing-library/react');
diff --git a/dashboard/src/utils/authLifecycle.test.ts b/dashboard/src/utils/authLifecycle.test.ts
index 8a3494b88..3bc90434f 100644
--- a/dashboard/src/utils/authLifecycle.test.ts
+++ b/dashboard/src/utils/authLifecycle.test.ts
@@ -161,7 +161,7 @@ async function signIn(apiKey: string): Promise<void> {
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'));
+ await waitFor(() => assert.ok(sessionStorage.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));
}
@@ -174,7 +174,7 @@ test('a fresh sign-in makes exactly one /auth/validate request, feeding the role
// 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(ROLE_KEY), 'operator');
assert.equal(sessionStorage.getItem(LOGIN_KEY), 'fresh-key');
});
@@ -185,16 +185,16 @@ test('a fresh sign-in with a role-less validate response still degrades to viewe
await signIn('fresh-key');
assert.equal(validateCallCount(), 1);
- assert.equal(localStorage.getItem(ROLE_KEY), 'viewer');
+ assert.equal(sessionStorage.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
+ sessionStorage.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 rtl.waitFor(() => assert.equal(sessionStorage.getItem(ROLE_KEY), 'admin'));
await new Promise(resolve => setTimeout(resolve, 50));
assert.equal(validateCallCount(), 1);