Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): keep a new login on stale key failures (#1791)

Yudhi Armyndharisf1e941f52a38
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5f867d1e7..1430519a6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- Keep a new dashboard login signed in when a request sent with the previous API key fails afterwards.
- Enforce the plugin package size limit before reading `manifest.json`, and reject archive entries whose path starts with `/`.
- Refuse Baileys animated stickers over 500 frames and run at most two sticker conversions at once.
- Stop pending webhook deliveries from holding over-cap inline media already omitted from their payload.
diff --git a/dashboard/src/services/api.test.ts b/dashboard/src/services/api.test.ts
index 55a1842a9..4458390fe 100644
--- a/dashboard/src/services/api.test.ts
+++ b/dashboard/src/services/api.test.ts
@@ -6,6 +6,7 @@ import { test, before, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
let sessionApi: (typeof import('./api.ts'))['sessionApi'];
+let pluginsApi: (typeof import('./api.ts'))['pluginsApi'];
const navigations: string[] = [];
before(async () => {
@@ -17,7 +18,7 @@ before(async () => {
configurable: true,
writable: true,
});
- ({ sessionApi } = await import('./api.ts'));
+ ({ sessionApi, pluginsApi } = await import('./api.ts'));
});
beforeEach(() => {
@@ -69,6 +70,124 @@ test('a role 403 keeps the key and rejects with the status', async () => {
assert.deepEqual(navigations, []);
});
+// Each response shape the client reads, so the key check covers every path into the failure handler.
+const shapes = [
+ ['JSON', () => sessionApi.list()],
+ ['text', () => pluginsApi.getConfigUi('p1')],
+ ['blob', () => sessionApi.getMessageMediaBlob('s1', '[email protected]', 'WA1')],
+] as const;
+
+// Hold every response until the test releases them, recording the key each request was sent with.
+function deferAnswers(status: number, message: string): { sentKeys: (string | undefined)[]; release: () => void } {
+ const sentKeys: (string | undefined)[] = [];
+ const releases: (() => void)[] = [];
+ globalThis.fetch = ((_input: RequestInfo | URL, init?: RequestInit) => {
+ sentKeys.push((init?.headers as Record<string, string> | undefined)?.['X-API-Key']);
+ return new Promise<Response>(resolve => {
+ releases.push(() =>
+ resolve(
+ new Response(JSON.stringify({ statusCode: status, message }), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ }),
+ ),
+ );
+ });
+ }) as typeof fetch;
+ return { sentKeys, release: () => releases.forEach(release => release()) };
+}
+
+// Both answers that prove a key unusable: a 401, and a 403 because the key's allowedIps refuse this client.
+const keyFailures = [
+ [401, 'API key is revoked'],
+ [403, 'IP address not allowed'],
+] as const;
+
+// A stale answer wrongly left pending drains the event loop, and node:test then cancels every later test;
+// holding a timer open past the per-test timeout lets that timeout fail just the one test instead.
+const stale = { timeout: 2000 };
+async function rejectsWithStatus(result: Promise<unknown>, status: number): Promise<void> {
+ const hold = setTimeout(() => {}, 3000);
+ try {
+ await assert.rejects(result, (err: Error & { status?: number }) => err.status === status);
+ } finally {
+ clearTimeout(hold);
+ }
+}
+
+for (const [status, message] of keyFailures) {
+ for (const [shape, call] of shapes) {
+ test(`a late ${status} ${shape} answer for a key signed out since keeps the key signed in now`, stale, async () => {
+ const pending = deferAnswers(status, message);
+ const result = call();
+ await new Promise(resolve => setImmediate(resolve));
+ assert.deepEqual(pending.sentKeys, ['stored-key']);
+ sessionStorage.removeItem('openwa_api_key');
+ sessionStorage.setItem('openwa_api_key', 'next-key');
+ pending.release();
+ await rejectsWithStatus(result, status);
+ assert.equal(sessionStorage.getItem('openwa_api_key'), 'next-key');
+ assert.deepEqual(navigations, []);
+ });
+
+ test(`a ${status} ${shape} answer for the key still in use clears it and returns to login`, async () => {
+ const pending = deferAnswers(status, message);
+ const result = call();
+ await new Promise(resolve => setImmediate(resolve));
+ pending.release();
+ assert.equal(await settled(result), false, 'the call settled, so its caller would render the failure');
+ assert.equal(sessionStorage.getItem('openwa_api_key'), null);
+ assert.deepEqual(navigations, ['/']);
+ });
+
+ test(`a late ${status} ${shape} answer while signed out stays silent and stays on the login form`, async () => {
+ const pending = deferAnswers(status, message);
+ const result = call();
+ await new Promise(resolve => setImmediate(resolve));
+ assert.deepEqual(pending.sentKeys, ['stored-key']);
+ sessionStorage.removeItem('openwa_api_key');
+ pending.release();
+ assert.equal(await settled(result), false, 'the call settled, so its caller would render the failure');
+ assert.equal(sessionStorage.getItem('openwa_api_key'), null);
+ assert.deepEqual(navigations, []);
+ });
+ }
+
+ test(`a burst of ${status}s for the key still in use keeps every call pending and navigates once`, async () => {
+ const pending = deferAnswers(status, message);
+ const results = shapes.map(([, call]) => call());
+ await new Promise(resolve => setImmediate(resolve));
+ assert.deepEqual(pending.sentKeys, ['stored-key', 'stored-key', 'stored-key']);
+ pending.release();
+ for (const result of results) {
+ assert.equal(await settled(result), false, 'the call settled, so its caller would render the failure');
+ }
+ assert.equal(sessionStorage.getItem('openwa_api_key'), null);
+ assert.deepEqual(navigations, ['/']);
+ });
+}
+
+test('a 401 for a request sent without a key while none is stored returns to login', async () => {
+ sessionStorage.removeItem('openwa_api_key');
+ answer(401, 'API key is required');
+ const result = sessionApi.list();
+ assert.equal(await settled(result), false, 'the call settled, so its caller would render the failure');
+ assert.deepEqual(navigations, ['/']);
+});
+
+test('a late 401 for a request sent while signed out keeps the key signed in since', stale, async () => {
+ sessionStorage.removeItem('openwa_api_key');
+ const pending = deferAnswers(401, 'API key is required');
+ const result = sessionApi.list();
+ await new Promise(resolve => setImmediate(resolve));
+ assert.deepEqual(pending.sentKeys, [undefined]);
+ sessionStorage.setItem('openwa_api_key', 'next-key');
+ pending.release();
+ await rejectsWithStatus(result, 401);
+ assert.equal(sessionStorage.getItem('openwa_api_key'), 'next-key');
+ assert.deepEqual(navigations, []);
+});
+
test('archived media forwards cancellation through fetch and the response body', async () => {
const controller = new AbortController();
let requested: string | undefined;
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index d00b2a3e4..1e576b659 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -740,15 +740,21 @@ export interface SearchResults {
// fails; the never-settling promise halts this request's chain so callers neither flash a generic
// error toast nor receive an undefined payload while the page navigates away. Otherwise throw an
// Error carrying the HTTP status and, when the gateway supplied one, its machine code.
-async function handleErrorResponse<T>(response: Response): Promise<T> {
+// `sentKey` is the key the request carried (null when none). Logout aborts nothing in flight, so an
+// answer can arrive after the stored key changed. With a key sent but none stored, a sign-out is
+// already under way (an earlier failure of the same burst, or the user on the login form): stay
+// silent and do not navigate again. With another key stored, the answer speaks for a key no longer
+// in use and must not sign out the current one, so it fails like any other error.
+async function handleErrorResponse<T>(response: Response, sentKey: string | null): Promise<T> {
// On a non-JSON body (e.g. a reverse-proxy 502/503/504 HTML page) fall through to `HTTP <status>`
// rather than statusText: the toast folds an exact `HTTP 502`/`HTTP 503` into its connection-lost
// toast (a 504 keeps its own), and statusText is empty over HTTP/2 anyway.
const error = await response.json().catch(() => ({}));
- if (isKeyUnusable(response.status, error.message)) {
+ const storedKey = sessionStorage.getItem('openwa_api_key');
+ if (isKeyUnusable(response.status, error.message) && (storedKey === sentKey || storedKey === null)) {
sessionStorage.removeItem('openwa_api_key');
if (typeof window !== 'undefined') {
- window.location.assign('/');
+ if (storedKey === sentKey) window.location.assign('/');
return new Promise<T>(() => {});
}
}
@@ -784,7 +790,7 @@ async function request<T>(endpoint: string, options: RequestInit = {}): Promise<
const response = await fetch(url, { ...options, headers });
if (!response.ok) {
- return handleErrorResponse<T>(response);
+ return handleErrorResponse<T>(response, apiKey);
}
if (response.status === 204) {
@@ -802,7 +808,7 @@ async function requestText(endpoint: string): Promise<string> {
});
if (!response.ok) {
- return handleErrorResponse<string>(response);
+ return handleErrorResponse<string>(response, apiKey);
}
return response.text();
@@ -822,7 +828,7 @@ async function requestBlob(endpoint: string, signal?: AbortSignal): Promise<Blob
const response = await fetch(url, { headers, signal });
if (!response.ok) {
- return handleErrorResponse<Blob>(response);
+ return handleErrorResponse<Blob>(response, apiKey);
}
return response.blob();