Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): skip cross-session stats for a session-scoped key

Yudhi Armyndharis7901079d16c0
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index 8bce0b0eb..250c6c494 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, setEngineType } = useRole();
+ const { setRole, role, setEngineType, setScoped } = useRole();
- const handleLogin = (key: string, validatedRole?: string, engineType?: string) => {
+ const handleLogin = (key: string, validatedRole?: string, engineType?: string, scoped = false) => {
setApiKey(key);
sessionStorage.setItem('openwa_api_key', key);
@@ -53,6 +53,7 @@ function AppContent() {
// least-privileged default.
setRole(isUserRole(validatedRole) ? validatedRole : 'viewer');
setEngineType(engineType ?? null);
+ setScoped(scoped);
setIsAuthenticated(true);
};
@@ -62,12 +63,13 @@ function AppContent() {
setIsAuthenticated(false);
setRole(null);
setEngineType(null);
+ setScoped(false);
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, setEngineType]);
+ }, [setRole, setEngineType, setScoped]);
// Re-validate and refresh the role on mount if already authenticated
useEffect(() => {
@@ -87,6 +89,7 @@ function AppContent() {
handleLogout();
} else if (decision.action === 'role') {
setRole(decision.role);
+ setScoped(decision.scoped);
if (decision.engineType) setEngineType(decision.engineType);
}
})
@@ -94,7 +97,7 @@ function AppContent() {
// 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, setEngineType, handleLogout]);
+ }, [savedKey, setRole, setEngineType, setScoped, 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 c5fd899a8..fe532224a 100644
--- a/dashboard/src/components/RoleProvider.tsx
+++ b/dashboard/src/components/RoleProvider.tsx
@@ -40,6 +40,19 @@ export function RoleProvider({ children }: { children: ReactNode }) {
}
}, []);
+ // Session-scoped keys are refused on the cross-session routes (e.g. /stats/overview) whatever their
+ // role, so the UI needs the scope beside the role to avoid sending them.
+ const [scoped, setScopedState] = useState(() => sessionStorage.getItem('openwa_key_scoped') === 'true');
+
+ const setScoped = useCallback((newScoped: boolean) => {
+ setScopedState(newScoped);
+ if (newScoped) {
+ sessionStorage.setItem('openwa_key_scoped', 'true');
+ } else {
+ sessionStorage.removeItem('openwa_key_scoped');
+ }
+ }, []);
+
const value: RoleContextType = {
role,
setRole,
@@ -49,6 +62,8 @@ export function RoleProvider({ children }: { children: ReactNode }) {
canWrite: role === 'admin' || role === 'operator',
engineType,
setEngineType,
+ scoped,
+ setScoped,
};
return <RoleContext.Provider value={value}>{children}</RoleContext.Provider>;
diff --git a/dashboard/src/components/chats/ChatComposer.test.ts b/dashboard/src/components/chats/ChatComposer.test.ts
index fab4fbd5f..ac39c8be4 100644
--- a/dashboard/src/components/chats/ChatComposer.test.ts
+++ b/dashboard/src/components/chats/ChatComposer.test.ts
@@ -62,6 +62,8 @@ before(async () => {
canWrite: true,
engineType: null,
setEngineType: () => undefined,
+ scoped: false,
+ setScoped: () => undefined,
};
wrap = children =>
createElement(
diff --git a/dashboard/src/components/chats/ChatSidebar.test.ts b/dashboard/src/components/chats/ChatSidebar.test.ts
index 7dc7ce446..df88ebd35 100644
--- a/dashboard/src/components/chats/ChatSidebar.test.ts
+++ b/dashboard/src/components/chats/ChatSidebar.test.ts
@@ -47,6 +47,8 @@ function renderSidebar(activeTab: ChatsTab, chats: Chat[], channels: { all: Chan
canWrite: true,
engineType: 'whatsapp-web.js',
setEngineType: () => undefined,
+ scoped: false,
+ setScoped: () => undefined,
};
const query = { isLoading: false, error: null, data: channels.all } as unknown as UseQueryResult<Channel[], Error>;
return rtl.render(
diff --git a/dashboard/src/components/chats/StatusComposeModal.test.ts b/dashboard/src/components/chats/StatusComposeModal.test.ts
index 4d4e7fa9b..a0b30e860 100644
--- a/dashboard/src/components/chats/StatusComposeModal.test.ts
+++ b/dashboard/src/components/chats/StatusComposeModal.test.ts
@@ -49,6 +49,8 @@ before(async () => {
canWrite: true,
engineType: 'whatsapp-web.js',
setEngineType: () => undefined,
+ scoped: false,
+ setScoped: () => undefined,
};
render = () =>
rtl.render(
diff --git a/dashboard/src/pages/Dashboard.test.ts b/dashboard/src/pages/Dashboard.test.ts
index d4936a955..e2e5bf59e 100644
--- a/dashboard/src/pages/Dashboard.test.ts
+++ b/dashboard/src/pages/Dashboard.test.ts
@@ -98,6 +98,7 @@ afterEach(() => {
holdWebhooks = false;
requested.length = 0;
window.sessionStorage.setItem('openwa_user_role', 'viewer');
+ window.sessionStorage.removeItem('openwa_key_scoped');
});
function renderDashboard(): void {
@@ -260,6 +261,17 @@ test('an admin key loads the chart section', async () => {
await rtl.waitFor(() => assert.ok(requested.some(p => p.startsWith('/api/stats/messages'))));
});
+test('a session-scoped admin key never loads the cross-session statistics', async () => {
+ // GET /stats/overview and /stats/messages refuse a key restricted to selected sessions, whatever its role.
+ window.sessionStorage.setItem('openwa_user_role', 'admin');
+ window.sessionStorage.setItem('openwa_key_scoped', 'true');
+ renderDashboard();
+ await rtl.waitFor(() => assert.ok(requested.includes('/api/sessions')));
+ await new Promise(resolve => setTimeout(resolve, 50));
+ assert.ok(!requested.includes('/api/stats/overview'), 'the overview was requested');
+ assert.ok(!requested.some(p => p.startsWith('/api/stats/messages')), 'the charts asked for /stats/messages');
+});
+
// The session table renders `status-pill ${session.status}`, so every status needs its own colour.
test('the status pill styles every session status and nothing else', () => {
const entity = readFileSync(
diff --git a/dashboard/src/pages/Dashboard.tsx b/dashboard/src/pages/Dashboard.tsx
index 4b3fba8ed..c546f4d5c 100644
--- a/dashboard/src/pages/Dashboard.tsx
+++ b/dashboard/src/pages/Dashboard.tsx
@@ -18,14 +18,16 @@ import { isSessionStarted } from '../utils/sessionActions';
import './Dashboard.css';
// recharts is heavy (~116 kB gzip); load the analytics section on demand so it never bloats the
-// main/login bundle, and only for an admin key: /stats/messages refuses every other role.
+// main/login bundle, and only for an unscoped admin key: /stats/messages refuses every other key.
const DashboardCharts = lazy(() => import('../components/DashboardCharts').then(m => ({ default: m.DashboardCharts })));
export function Dashboard() {
const { t } = useTranslation();
useDocumentTitle(t('dashboard.title'));
const navigate = useNavigate();
- const { canWrite, isAdmin } = useRole();
+ const { canWrite, isAdmin, scoped } = useRole();
+ // The cross-session statistics also refuse a session-scoped key, whatever its role.
+ const canReadStats = isAdmin && !scoped;
const toast = useToast();
const {
data: sessions = [],
@@ -38,7 +40,7 @@ export function Dashboard() {
// them, since the gateway audits every refusal as a failed authentication; their cards show the
// unavailable placeholder.
const { data: webhooks } = useWebhooksQuery(canWrite);
- const { data: overview } = useStatsOverviewQuery(isAdmin);
+ const { data: overview } = useStatsOverviewQuery(canReadStats);
const stopMutation = useStopSessionMutation();
const unavailable = '—';
const messagesToday = overview ? overview.messages.today.sent + overview.messages.today.received : unavailable;
@@ -138,7 +140,7 @@ export function Dashboard() {
))}
</div>
- {isAdmin && (
+ {canReadStats && (
<Suspense fallback={null}>
<DashboardCharts />
</Suspense>
diff --git a/dashboard/src/pages/Login.tsx b/dashboard/src/pages/Login.tsx
index 8d7725db0..9d92506c3 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, engineType?: string) => void;
+ onLogin: (apiKey: string, role?: string, engineType?: string, scoped?: boolean) => void;
}
export function Login({ onLogin }: LoginProps) {
@@ -46,8 +46,13 @@ 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; engineType?: string } = await response.json().catch(() => ({}));
- onLogin(key, data.role, typeof data.engineType === 'string' ? data.engineType : undefined);
+ const data: { role?: string; engineType?: string; scoped?: unknown } = await response.json().catch(() => ({}));
+ onLogin(
+ key,
+ data.role,
+ typeof data.engineType === 'string' ? data.engineType : undefined,
+ data.scoped === true,
+ );
} else {
// A 5xx, or a body that is not the gateway's JSON (a proxy error page while it restarts), says
// nothing about the key; a refusal keeps the gateway's reason (expired, revoked, rate limited).
diff --git a/dashboard/src/types/role.ts b/dashboard/src/types/role.ts
index 366362a77..8c7c30fa8 100644
--- a/dashboard/src/types/role.ts
+++ b/dashboard/src/types/role.ts
@@ -11,4 +11,7 @@ export interface RoleContextType {
/** Engine the gateway runs, as POST /auth/validate reported it; null until it has answered. */
engineType: string | null;
setEngineType: (engineType: string | null) => void;
+ /** Whether the key is restricted to selected sessions, so the cross-session routes refuse it. */
+ scoped: boolean;
+ setScoped: (scoped: boolean) => void;
}
diff --git a/dashboard/src/utils/authLifecycle.test.ts b/dashboard/src/utils/authLifecycle.test.ts
index 5b131b21b..2e3f254b0 100644
--- a/dashboard/src/utils/authLifecycle.test.ts
+++ b/dashboard/src/utils/authLifecycle.test.ts
@@ -44,6 +44,7 @@ test('startup validation: ok + role refreshes the cached role from the server',
assert.deepEqual(resolveStartupValidation(200, { valid: true, role: 'viewer' }), {
action: 'role',
role: 'viewer',
+ scoped: false,
});
});
@@ -51,10 +52,25 @@ 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',
+ scoped: false,
engineType: 'baileys',
});
});
+test('startup validation: ok + role carries whether the key is session-scoped', () => {
+ assert.deepEqual(resolveStartupValidation(200, { valid: true, role: 'admin', scoped: true }), {
+ action: 'role',
+ role: 'admin',
+ scoped: true,
+ });
+ // Anything but a literal true is unscoped.
+ assert.deepEqual(resolveStartupValidation(200, { valid: true, role: 'admin', scoped: 'yes' }), {
+ action: 'role',
+ role: 'admin',
+ scoped: false,
+ });
+});
+
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' });
@@ -76,6 +92,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';
+const SCOPED_KEY = 'openwa_key_scoped';
interface FetchCall {
method: string;
@@ -87,7 +104,7 @@ 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; engineType?: string } = {
+let validateBody: { valid?: boolean; role?: string; engineType?: string; scoped?: boolean } = {
valid: true,
role: 'operator',
engineType: 'whatsapp-web.js',
@@ -231,3 +248,40 @@ test('a role or scope 403 and other failures keep the key', () => {
assert.equal(isKeyUnusable(429, undefined), false);
assert.equal(isKeyUnusable(500, undefined), false);
});
+
+test('a fresh sign-in with a session-scoped admin key keeps the scope from the validate response', async () => {
+ validateBody = { valid: true, role: 'admin', engineType: 'baileys', scoped: true };
+ rtl.render(createElement(App));
+
+ await signIn('scoped-key');
+
+ assert.equal(sessionStorage.getItem(ROLE_KEY), 'admin');
+ assert.equal(sessionStorage.getItem(SCOPED_KEY), 'true');
+});
+
+test('a page reload refreshes the cached scope from the server', async () => {
+ sessionStorage.setItem(LOGIN_KEY, 'saved-key');
+ sessionStorage.setItem(ROLE_KEY, 'admin');
+ sessionStorage.setItem(SCOPED_KEY, 'true'); // stale: the key has since been unscoped
+ validateBody = { valid: true, role: 'admin', engineType: 'baileys', scoped: false };
+ rtl.render(createElement(App));
+
+ await rtl.waitFor(() => assert.equal(sessionStorage.getItem(SCOPED_KEY), null));
+});
+
+test('a startup 401 drops the cached scope with the role', async () => {
+ sessionStorage.setItem(LOGIN_KEY, 'revoked-key');
+ sessionStorage.setItem(ROLE_KEY, 'admin');
+ sessionStorage.setItem(SCOPED_KEY, 'true');
+ const stub = globalThis.fetch;
+ // Only the validate answer is refused: a 401 on any other read sends the page back to '/' first.
+ globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit) =>
+ String(input).endsWith('/auth/validate') ? Promise.resolve(new Response('{}', { status: 401 })) : stub(input, init);
+ try {
+ rtl.render(createElement(App));
+ await rtl.waitFor(() => assert.equal(sessionStorage.getItem(ROLE_KEY), null));
+ assert.equal(sessionStorage.getItem(SCOPED_KEY), null);
+ } finally {
+ globalThis.fetch = stub;
+ }
+});
diff --git a/dashboard/src/utils/authLifecycle.ts b/dashboard/src/utils/authLifecycle.ts
index bbb3d6ce3..32b4b7f39 100644
--- a/dashboard/src/utils/authLifecycle.ts
+++ b/dashboard/src/utils/authLifecycle.ts
@@ -34,7 +34,7 @@ export function isKeyUnusable(status: number, message: unknown): boolean {
}
export type StartupValidation =
- { action: 'role'; role: UserRole; engineType?: string } | { action: 'logout' } | { action: 'keep' };
+ { action: 'role'; role: UserRole; scoped: boolean; engineType?: string } | { action: 'logout' } | { action: 'keep' };
/**
* Fold the startup /auth/validate answer into an auth decision:
@@ -43,21 +43,22 @@ export type StartupValidation =
* - 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),
- * along with the engine it reports.
+ * along with its session scope and 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; engineType?: string } | null,
+ body: { valid?: boolean; role?: string; engineType?: string; scoped?: unknown } | null,
): StartupValidation {
if (status === 401 || status === 403) return { action: 'logout' };
if (status < 200 || status >= 300) return { action: 'keep' };
if (body?.valid && isUserRole(body.role)) {
+ const scoped = body.scoped === true;
return typeof body.engineType === 'string'
- ? { action: 'role', role: body.role, engineType: body.engineType }
- : { action: 'role', role: body.role };
+ ? { action: 'role', role: body.role, scoped, engineType: body.engineType }
+ : { action: 'role', role: body.role, scoped };
}
return { action: 'keep' };
}