Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): stop a retired import from acting for another key
Yudhi Armyndharis2b5eda72c72d
diff --git a/dashboard/src/hooks/useDataBackup.test.ts b/dashboard/src/hooks/useDataBackup.test.tsindex 88c452961..8603b431c 100644--- a/dashboard/src/hooks/useDataBackup.test.ts+++ b/dashboard/src/hooks/useDataBackup.test.ts@@ -4,7 +4,7 @@import '../test-helpers/register-hooks.ts';import { test, before, afterEach } from 'node:test';import assert from 'node:assert/strict';-import { createElement, type ReactNode } from 'react';+import { createElement, StrictMode, type ReactNode } from 'react';import type { useDataBackup as useDataBackupFn } from './useDataBackup.ts';import type { ToastContext as ToastContextType } from './useToast.ts';@@ -18,7 +18,8 @@ let ToastContext: typeof ToastContextType;let exportAnswer: Promise<Response> = new Promise(() => {});const saved: HTMLAnchorElement[] = [];// Answers of the import route in order, and what it was sent.-let importAnswers: Response[] = [];+let importAnswers: Array<Response | Promise<Response>> = [];+const importKeys: Array<string | null> = [];const importBodies: Array<Record<string, unknown>> = [];const toastLog: Array<{ kind: string; title: string; detail?: string }> = [];let i18nT: (key: string, options?: Record<string, unknown>) => string;@@ -42,6 +43,7 @@ before(async () => {globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;if (url.endsWith('/api/infra/import-data')) {+ importKeys.push((init?.headers as Record<string, string> | undefined)?.['X-API-Key'] ?? null);importBodies.push(JSON.parse(String(init?.body ?? '{}')) as Record<string, unknown>);return Promise.resolve(importAnswers.shift() ?? json({ imported: true, counts: {}, warnings: [] }, 201));}@@ -64,10 +66,11 @@ afterEach(() => {document.createElement = createElementOriginal;importAnswers = [];importBodies.length = 0;+ importKeys.length = 0;toastLog.length = 0;});-function renderBackup() {+function renderBackup(strict = false) {const noop = () => {};const record = (kind: string) => (title: string, detail?: string) => void toastLog.push({ kind, title, detail });const value = {@@ -79,7 +82,10 @@ function renderBackup() {warning: record('warning'),info: record('info'),};- const wrapper = ({ children }: { children: ReactNode }) => createElement(ToastContext.Provider, { value }, children);+ const wrapper = ({ children }: { children: ReactNode }) => {+ const wrapped = createElement(ToastContext.Provider, { value }, children);+ return strict ? createElement(StrictMode, null, wrapped) : wrapped;+ };// Record each file the hook saves by capturing the link it clicks, instead of letting jsdom navigate.document.createElement = ((tag: string, options?: ElementCreationOptions) => {const element = createElementOriginal.call(document, tag, options);@@ -248,3 +254,291 @@ test('a backup over the request body cap gets the actionable message, not a bare},]);});++function heldValue<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<T>((accept, refuse) => {+ resolve = accept;+ reject = refuse;+ });+ return { promise, resolve, reject };+}++function selectedFile(text: Promise<string>): File {+ const file = backupFile('');+ Object.defineProperty(file, 'text', { value: () => text });+ return file;+}++async function importTurn(action: () => void): Promise<void> {+ await rtl.act(async () => {+ action();+ for (let i = 0; i < 16; i++) await Promise.resolve();+ await new Promise<void>(resolve => setImmediate(resolve));+ });+}++const retirements = ['signed-out', 'replacement-key', 'unmounted', 'same-key-relogin'] as const;+function retireImport(view: ReturnType<typeof renderBackup>, kind: (typeof retirements)[number]) {+ if (kind === 'signed-out') sessionStorage.removeItem('openwa_api_key');+ if (kind === 'replacement-key') sessionStorage.setItem('openwa_api_key', 'key-b');+ if (kind === 'unmounted') view.unmount();+ if (kind === 'same-key-relogin') {+ view.unmount();+ sessionStorage.removeItem('openwa_api_key');+ sessionStorage.setItem('openwa_api_key', 'key-a');+ renderBackup();+ }+}++// A restore already sent is reported to whoever is on the page, unless another key has taken over.+const reportedAfter = (kind: (typeof retirements)[number]) =>+ kind === 'unmounted' || kind === 'same-key-relogin' ? 1 : 0;++const importBody = JSON.stringify({ tables: { dummyRows: [{ label: 'selected' }] } });+const importEffects = (prompts: string[]) => ({+ prompts: prompts.length,+ requests: importBodies.length,+ toasts: toastLog.length,+});++for (const kind of retirements) {+ test(`a file read retired by ${kind} causes no prompt, request or toast`, async () => {+ sessionStorage.setItem('openwa_api_key', 'key-a');+ const read = heldValue<string>(),+ view = renderBackup(),+ prompts = answerConfirms(true, true);+ await importTurn(() => {+ void view.result.current.importBackup(selectedFile(read.promise));+ });+ await importTurn(() => retireImport(view, kind));+ await importTurn(() => read.resolve(importBody));+ assert.deepEqual(importEffects(prompts), { prompts: 0, requests: 0, toasts: 0 });+ });+ test(`a failed file read retired by ${kind} reports no stale error`, async () => {+ sessionStorage.setItem('openwa_api_key', 'key-a');+ const read = heldValue<string>(),+ view = renderBackup(),+ prompts = answerConfirms(true, true);+ await importTurn(() => {+ void view.result.current.importBackup(selectedFile(read.promise));+ });+ await importTurn(() => retireImport(view, kind));+ await importTurn(() => read.reject(new Error('Dummy file read failure')));+ assert.deepEqual(importEffects(prompts), { prompts: 0, requests: 0, toasts: 0 });+ });+ test(`a refusal after ${kind} opens no orphan retry and is reported only to the same key`, async () => {+ sessionStorage.setItem('openwa_api_key', 'key-a');+ const answer = heldValue<Response>();+ importAnswers.push(answer.promise);+ const view = renderBackup(),+ prompts = answerConfirms(true, true);+ await importTurn(() => {+ void view.result.current.importBackup(backupFile(importBody));+ });+ assert.deepEqual(importEffects(prompts), { prompts: 1, requests: 1, toasts: 0 });+ assert.deepEqual(importKeys, ['key-a']);+ await importTurn(() => retireImport(view, kind));+ await importTurn(() => answer.resolve(orphanRefusal()));+ assert.deepEqual(importEffects(prompts), { prompts: 1, requests: 1, toasts: reportedAfter(kind) });+ assert.deepEqual(+ toastLog.map(entry => entry.kind),+ reportedAfter(kind) ? ['error'] : [],+ );+ });+ for (const status of [200, 503]) {+ test(`an import answered with ${status} after ${kind} is reported only to the same key`, async () => {+ sessionStorage.setItem('openwa_api_key', 'key-a');+ const answer = heldValue<Response>();+ importAnswers.push(answer.promise);+ const view = renderBackup(),+ prompts = answerConfirms(true);+ await importTurn(() => {+ void view.result.current.importBackup(backupFile(importBody));+ });+ assert.equal(importBodies.length, 1);+ await importTurn(() => retireImport(view, kind));+ await importTurn(() =>+ answer.resolve(+ status === 200 ? json({ imported: true, counts: {}, warnings: [] }) : json({ message: 'Dummy failure' }, 503),+ ),+ );+ assert.deepEqual(importEffects(prompts), { prompts: 1, requests: 1, toasts: reportedAfter(kind) });+ });+ }+}++for (const key of [null, '']) {+ test(`an import begun with ${key === null ? 'no' : 'an empty'} key reads and sends nothing`, async () => {+ if (key === null) sessionStorage.removeItem('openwa_api_key');+ else sessionStorage.setItem('openwa_api_key', key);+ let reads = 0;+ const file = backupFile(importBody);+ Object.defineProperty(file, 'text', {+ value: async () => {+ reads++;+ return importBody;+ },+ });+ const view = renderBackup(),+ prompts = answerConfirms(true);+ await importTurn(() => {+ void view.result.current.importBackup(file);+ });+ assert.deepEqual({ ...importEffects(prompts), reads }, { prompts: 0, requests: 0, toasts: 0, reads: 0 });+ });+}++test('a row confirmation cannot dispatch with a key changed while it was open', async () => {+ sessionStorage.setItem('openwa_api_key', 'key-a');+ const view = renderBackup();+ let prompts = 0;+ window.confirm = () => {+ prompts++;+ sessionStorage.setItem('openwa_api_key', 'key-b');+ return true;+ };+ await importTurn(() => {+ void view.result.current.importBackup(backupFile(importBody));+ });+ assert.equal(prompts, 1);+ assert.deepEqual(importBodies, []);+ assert.deepEqual(toastLog, []);+});++test('an orphan confirmation cannot retry with a key changed while it was open', async () => {+ sessionStorage.setItem('openwa_api_key', 'key-a');+ importAnswers.push(orphanRefusal());+ const view = renderBackup();+ let prompts = 0;+ window.confirm = () => {+ if (++prompts === 2) sessionStorage.setItem('openwa_api_key', 'key-b');+ return true;+ };+ await importTurn(() => {+ void view.result.current.importBackup(backupFile(importBody));+ });+ assert.equal(prompts, 2);+ assert.deepEqual(importKeys, ['key-a']);+ assert.equal(importBodies.length, 1);+ assert.deepEqual(toastLog, []);+});++for (const outcome of ['success', 'read-failure', 'invalid-json'] as const) {+ test(`an older selection ending with ${outcome} cannot replace the newer selection`, async () => {+ sessionStorage.setItem('openwa_api_key', 'key-a');+ const oldRead = heldValue<string>(),+ freshRead = heldValue<string>();+ const view = renderBackup(),+ prompts = answerConfirms(true, true);+ await importTurn(() => {+ void view.result.current.importBackup(selectedFile(oldRead.promise));+ });+ await importTurn(() => {+ void view.result.current.importBackup(selectedFile(freshRead.promise));+ });+ const fresh = { tables: { dummyRows: [{ label: 'newer' }] } };+ await importTurn(() => freshRead.resolve(JSON.stringify(fresh)));+ assert.deepEqual(importBodies, [fresh]);+ if (outcome === 'read-failure') await importTurn(() => oldRead.reject(new Error('Dummy old read failure')));+ else await importTurn(() => oldRead.resolve(outcome === 'invalid-json' ? 'not json' : importBody));+ assert.deepEqual(importBodies, [fresh]);+ assert.deepEqual(importEffects(prompts), { prompts: 1, requests: 1, toasts: 1 });+ assert.equal(toastLog[0].kind, 'success');+ });+}++test('an old response cannot clear the busy state of a newer file read', async () => {+ sessionStorage.setItem('openwa_api_key', 'key-a');+ const oldAnswer = heldValue<Response>(),+ freshRead = heldValue<string>();+ importAnswers.push(oldAnswer.promise);+ const view = renderBackup(),+ prompts = answerConfirms(true, false);+ await importTurn(() => {+ void view.result.current.importBackup(backupFile(importBody));+ });+ assert.equal(importBodies.length, 1);+ await importTurn(() => {+ void view.result.current.importBackup(selectedFile(freshRead.promise));+ });+ assert.equal(view.result.current.migrating, true);+ await importTurn(() => oldAnswer.resolve(json({ imported: true, counts: {}, warnings: [] })));+ assert.equal(view.result.current.migrating, true);+ assert.deepEqual(importEffects(prompts), { prompts: 1, requests: 1, toasts: 1 });+ await importTurn(() => freshRead.resolve(importBody));+ assert.equal(view.result.current.migrating, false);+ assert.deepEqual(importEffects(prompts), { prompts: 2, requests: 1, toasts: 1 });+});++test('a declined newer selection still retires an older file read', async () => {+ sessionStorage.setItem('openwa_api_key', 'key-a');+ const oldRead = heldValue<string>(),+ view = renderBackup(),+ prompts = answerConfirms(false, true);+ await importTurn(() => {+ void view.result.current.importBackup(selectedFile(oldRead.promise));+ });+ await importTurn(() => {+ void view.result.current.importBackup(backupFile(importBody));+ });+ assert.equal(view.result.current.migrating, false);+ await importTurn(() => oldRead.resolve(importBody));+ assert.deepEqual(importEffects(prompts), { prompts: 1, requests: 0, toasts: 0 });+});++test('an import remains usable after StrictMode effect replay', async () => {+ sessionStorage.setItem('openwa_api_key', 'key-a');+ const view = renderBackup(true),+ prompts = answerConfirms(true);+ await importTurn(() => {+ void view.result.current.importBackup(backupFile(importBody));+ });+ assert.deepEqual(importEffects(prompts), { prompts: 1, requests: 1, toasts: 1 });+ assert.equal(toastLog[0].kind, 'success');+ assert.equal(view.result.current.migrating, false);+});++for (const stage of ['file-read', 'response'] as const) {+ for (const change of ['remove-key', 'replace-key'] as const) {+ test(`a canceled ${stage} after ${change} clears busy state before a fresh B selection`, async () => {+ sessionStorage.setItem('openwa_api_key', 'key-a');+ const read = heldValue<string>(),+ answer = heldValue<Response>();+ const view = renderBackup(),+ prompts = answerConfirms(true, true);+ if (stage === 'response') importAnswers.push(answer.promise);+ await importTurn(() => {+ void view.result.current.importBackup(+ stage === 'file-read' ? selectedFile(read.promise) : backupFile(importBody),+ );+ });+ assert.equal(view.result.current.migrating, true);+ assert.equal(importBodies.length, stage === 'response' ? 1 : 0);+ if (change === 'remove-key') sessionStorage.removeItem('openwa_api_key');+ else sessionStorage.setItem('openwa_api_key', 'key-b');+ await importTurn(() => {+ if (stage === 'file-read') read.resolve(importBody);+ else answer.resolve(json({ imported: true, counts: {}, warnings: [] }));+ });+ const canceled = { ...importEffects(prompts), migrating: view.result.current.migrating };+ sessionStorage.setItem('openwa_api_key', 'key-b');+ const fresh = { tables: { dummyRows: [{ label: 'fresh-B-selection' }] } };+ await importTurn(() => {+ void view.result.current.importBackup(backupFile(fresh));+ });+ assert.deepEqual(canceled, {+ prompts: stage === 'response' ? 1 : 0,+ requests: stage === 'response' ? 1 : 0,+ toasts: 0,+ migrating: false,+ });+ assert.deepEqual(importBodies.at(-1), fresh);+ assert.equal(importKeys.at(-1), 'key-b');+ assert.equal(view.result.current.migrating, false);+ assert.equal(toastLog.length, 1);+ assert.equal(toastLog[0].kind, 'success');+ });+ }+}diff --git a/dashboard/src/hooks/useDataBackup.ts b/dashboard/src/hooks/useDataBackup.tsindex 6a426aa48..ac3a6dd6c 100644--- a/dashboard/src/hooks/useDataBackup.ts+++ b/dashboard/src/hooks/useDataBackup.ts@@ -1,4 +1,4 @@-import { useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { shouldOfferStopOrphansRetry } from '../utils/importRefusal';import { keepsSameKey } from '../utils/authLifecycle';import { useTranslation } from 'react-i18next';@@ -20,6 +20,14 @@ export function useDataBackup(): DataBackup {const { t } = useTranslation();const toast = useToast();const [migrating, setMigrating] = useState(false);+ const importOwnerRef = useRef<object | null>(null);++ useEffect(() => {+ importOwnerRef.current = {};+ return () => {+ importOwnerRef.current = null;+ };+ }, []);// Download a JSON backup of all Data-DB tables. Called BEFORE a DB switch (while still on the old// database) so the data can be re-imported into the new one — switching otherwise starts empty (#488).@@ -68,9 +76,17 @@ export function useDataBackup(): DataBackup {// retrying one with stopOrphans would run a second destructive replace the operator never asked// for. force=true is deliberately not offered (the api client does not even send it): it leaves// the engines running until a restart.- const runImport = async (tables: Record<string, unknown[]>, stopOrphans = false): Promise<void> => {+ const runImport = async (+ tables: Record<string, unknown[]>,+ isCurrent: () => boolean,+ sameKey: () => boolean,+ stopOrphans = false,+ ): Promise<void> => {+ if (!isCurrent()) return;try {const res = await infraApi.importData(tables, stopOrphans ? { stopOrphans: true } : undefined);+ // The replace has run: its outcome is reported wherever the operator is now, unless another key took over.+ if (!sameKey()) return;if (res.imported) {// notices carry non-fatal operator messages (orphan teardown details); restartRequired// means a teardown failed and only a restart guarantees cleanup — surface both on success.@@ -86,13 +102,21 @@ export function useDataBackup(): DataBackup {);}} catch (err) {+ if (!sameKey()) return;const status = (err as { status?: number } | null)?.status;const code = (err as { code?: string } | null)?.code;if (shouldOfferStopOrphansRetry(status, code, stopOrphans) && err instanceof Error) {// The confirm doubles as the refusal display: OK retries with stopOrphans=true, Cancel// leaves the engines (and the current data) untouched. A 409 on the retry itself (an// engine started mid-import) falls through to the plain error toast — no confirm loop.- if (window.confirm(err.message)) await runImport(tables, true);+ // Not put to an operator who has left the page: the refusal is reported and nothing is stopped.+ if (!isCurrent()) {+ toast.error(t('infrastructure.migration.importFailed'), err.message);+ return;+ }+ const retry = window.confirm(err.message);+ if (!isCurrent()) return;+ if (retry) await runImport(tables, isCurrent, sameKey, true);else toast.error(t('infrastructure.migration.importFailed'), err.message);return;}@@ -111,24 +135,35 @@ export function useDataBackup(): DataBackup {// Restore a previously-exported backup into the CURRENT database (use after switching + restart).// Import REPLACES all current data, so validate + confirm (showing the row count) before any call.const importBackup = async (file: File) => {- let parsed: { tables?: Record<string, unknown[]> };- try {- parsed = JSON.parse(await file.text()) as { tables?: Record<string, unknown[]> };- } catch {- toast.error(t('infrastructure.migration.importFailed'), t('infrastructure.migration.invalidFile'));- return;- }- if (!parsed?.tables || typeof parsed.tables !== 'object') {- toast.error(t('infrastructure.migration.importFailed'), t('infrastructure.migration.invalidFile'));- return;- }- const rows = Object.values(parsed.tables).reduce((n, a) => n + (Array.isArray(a) ? a.length : 0), 0);- if (!window.confirm(t('infrastructure.migration.importConfirm', { rows }))) return;+ if (!sessionStorage.getItem('openwa_api_key') || importOwnerRef.current === null) return;+ // A newer selection or an unmount retires what has not been sent yet, including a delayed refusal retry.+ const owner = {};+ importOwnerRef.current = owner;+ const sameKey = keepsSameKey();+ const isCurrent = () => importOwnerRef.current === owner && sameKey();setMigrating(true);try {- await runImport(parsed.tables);+ let parsed: { tables?: Record<string, unknown[]> };+ try {+ const text = await file.text();+ if (!isCurrent()) return;+ parsed = JSON.parse(text) as { tables?: Record<string, unknown[]> };+ } catch {+ if (isCurrent()) {+ toast.error(t('infrastructure.migration.importFailed'), t('infrastructure.migration.invalidFile'));+ }+ return;+ }+ if (!isCurrent()) return;+ if (!parsed?.tables || typeof parsed.tables !== 'object') {+ toast.error(t('infrastructure.migration.importFailed'), t('infrastructure.migration.invalidFile'));+ return;+ }+ const rows = Object.values(parsed.tables).reduce((n, a) => n + (Array.isArray(a) ? a.length : 0), 0);+ if (!window.confirm(t('infrastructure.migration.importConfirm', { rows })) || !isCurrent()) return;+ await runImport(parsed.tables, isCurrent, sameKey);} finally {- setMigrating(false);+ if (importOwnerRef.current === owner) setMigrating(false);}};