Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): read every bundled host spelling with the server's rule
Yudhi Armyndharisda7fe2564e5c
diff --git a/dashboard/src/pages/Infrastructure.test.ts b/dashboard/src/pages/Infrastructure.test.tsindex d434d2088..e3c66294f 100644--- a/dashboard/src/pages/Infrastructure.test.ts+++ b/dashboard/src/pages/Infrastructure.test.ts@@ -18,6 +18,7 @@ import type { installJsdomGlobals as installJsdomGlobalsFn } from '../test-helpeimport {EXPECTED_MODE,FILE_STATES,+ HOST_SPELLINGS,PIN_STATES,SERVICES,pinnedHost,@@ -2112,6 +2113,98 @@ test('a host pinned to the container name still reaches the container, which isassert.deepEqual(body, { profiles: ['postgres'], profilesToRemove: ['redis', 'minio'] });});+// Every spelling of the bundled host the server reads as the bundled container (the shared table), taken i-th for+// each service at once: its alias, another letter case, a trailing dot, the container name.+const spellingRounds = Math.max(...Object.values(HOST_SPELLINGS).map(s => s.reach.length));+const spelling = (service: ServiceName, round: number) =>+ HOST_SPELLINGS[service].reach[round % HOST_SPELLINGS[service].reach.length];++for (let round = 0; round < spellingRounds; round++) {+ const db = spelling('database', round);+ const redisHost = spelling('redis', round);+ const s3 = spelling('storage', round);++ // A pin that still reaches the container: the server keeps it, so the page neither asks for nor names its stop.+ test(`hosts pinned to ${JSON.stringify([db, redisHost, s3])} keep the containers OpenWA created`, async () => {+ resetFetchCalls();+ const status: InfraStatus = {+ ...PINNED_AWAY,+ database: { ...PINNED_AWAY.database, host: db, builtIn: true },+ redis: { ...PINNED_AWAY.redis, host: redisHost, builtIn: true },+ storage: { ...PINNED_AWAY.storage, endpoint: s3, bucket: 'openwa', builtIn: true },+ };+ const saved: SavedConfig = {+ ...PINNED_AWAY_SAVED,+ database: { ...PINNED_AWAY_SAVED.database, host: db, builtIn: true },+ redis: { ...PINNED_AWAY_SAVED.redis, host: redisHost, builtIn: true },+ storage: { ...PINNED_AWAY_SAVED.storage, s3Endpoint: s3, s3Bucket: 'openwa', builtIn: true },+ };+ overrides = { status, saved, saveProfiles: ['postgres', 'redis', 'minio'] };++ const { dialogText, names, body } = await saveAndRestart();++ assert.deepEqual(names, []);+ assert.doesNotMatch(dialogText, /openwa-/);+ assert.deepEqual(body, { profiles: ['postgres', 'redis', 'minio'], profilesToRemove: [] });+ });++ // A saved built-in choice beside a stopped container the server already dials switches nothing.+ test(`no pending note beside a stopped container the server dials as ${JSON.stringify([db, redisHost, s3])}`, async () => {+ const { screen } = rtl;+ resetFetchCalls();+ overrides = {+ status: {+ ...RUNNING_BUNDLED,+ database: { ...RUNNING_BUNDLED.database, host: db, builtIn: false, running: false },+ redis: { ...RUNNING_BUNDLED.redis, host: redisHost, builtIn: false, running: false },+ storage: { ...RUNNING_BUNDLED.storage, endpoint: s3, builtIn: false, running: false },+ },+ saved: {+ ...SAVED_BUNDLED,+ database: { ...SAVED_BUNDLED.database, host: db },+ redis: { enabled: true, builtIn: true, builtInSet: true, host: redisHost, port: '6379', passwordSet: false },+ storage: { ...SAVED_BUNDLED.storage, s3Endpoint: s3 },+ },+ };+ const { container } = renderInfrastructure();++ await screen.findByText('Database Configuration');+ await awaitSeeded(container);+ assert.equal(+ screen.queryByText(PENDING_BUILT_IN_NOTE) === null,+ true,+ 'a pending switch the restart would not make',+ );+ });++ // The bundled container under another spelling is the database and storage the server runs on now: no switch.+ test(`no data-backend warning for a built-in save over ${JSON.stringify([db, s3])}`, async () => {+ const { screen, fireEvent } = rtl;+ resetFetchCalls();+ overrides = {+ status: {+ ...RUNNING_BUNDLED,+ database: { ...RUNNING_BUNDLED.database, host: db },+ storage: { ...RUNNING_BUNDLED.storage, endpoint: s3 },+ },+ saved: {+ ...SAVED_BUNDLED,+ database: { ...SAVED_BUNDLED.database, host: db, builtInSet: true },+ storage: { ...SAVED_BUNDLED.storage, s3Endpoint: s3, s3Bucket: 'openwa', builtInSet: true },+ },+ };+ const { container } = renderInfrastructure();++ await screen.findByText('Database Configuration');+ await awaitSeeded(container);+ fireEvent.click(toggleInput(container, 'Headless Mode'));+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));++ const dialog = await screen.findByRole('dialog');+ assert.doesNotMatch(dialog.textContent ?? '', /The new database starts empty|not moved to the new storage/);+ });+}+// ── Restart-flow timer cleanup on unmount ────────────────────────────────────test('unmounting mid-restart cancels the health poll and countdown timers', { timeout: 10_000 }, async () => {diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsxindex 1d5cad10c..0a4074229 100644--- a/dashboard/src/pages/Infrastructure.tsx+++ b/dashboard/src/pages/Infrastructure.tsx@@ -16,6 +16,7 @@ import {} from 'lucide-react';import { API_BASE_URL, infraApi, type SavedConfig } from '../services/api';import { copyToClipboard } from '../utils/clipboard';+import { CONTAINER_OF, namesBundledContainer, sameHost } from '../utils/bundledHost';import { useDocumentTitle } from '../hooks/useDocumentTitle';import { useInfraStatusQuery, useInfraConfigQuery, useEnginesQuery, useCurrentEngineQuery } from '../hooks/queries';import { savedBuiltIn, useInfraConfigForm } from '../hooks/useInfraConfigForm';@@ -38,32 +39,6 @@ interface QueueStats {failed: number;}-// The container each managed profile runs, as the restart dialog names it.-const CONTAINER_OF: Record<string, string> = {- postgres: 'openwa-postgres',- redis: 'openwa-redis',- minio: 'openwa-minio',-};--/**- * Whether a host (for minio, the host of an S3 endpoint) reaches the profile's bundled container: its network alias- * (the profile name) or its container name, in any letter case, with or without a trailing dot. The same rule as the- * server's namesBundledContainer, which never lets a restart stop such a container.- */-function namesBundledContainer(profile: string, value: string | undefined): boolean {- if (!CONTAINER_OF[profile] || value === undefined) return false;- let host = value.trim();- if (profile === 'minio') {- try {- host = new URL(host).hostname;- } catch {- return false;- }- }- host = host.toLowerCase().replace(/\.$/, '');- return host === profile || host === CONTAINER_OF[profile];-}-/** The host the next boot dials for a profile, as GET /config reports it: the environment's, else the saved one. */const nextBootHost = (profile: string, config: SavedConfig): string =>profile === 'postgres' ? config.database.host : profile === 'redis' ? config.redis.host : config.storage.s3Endpoint;@@ -99,11 +74,11 @@ export function Infrastructure() {// move before it happens. A switch is a next boot that connects somewhere else than the server does// now: another type, host, port or database name, or another S3 endpoint or bucket. The next boot// connects to a value the environment pins whatever the form says, and to the bundled container for- // a built-in choice. Whether that container runs right now is no part of it: a stopped one is started- // again on the same volume. /status reports the type, host, endpoint and bucket in use; the port and- // the database name are not on it, so those compare with the saved config as the page loaded it. A- // key with nothing saved reads '', and runs on the same fallback the form was seeded with. A new local- // path is no switch.+ // a built-in choice; two spellings of that container are one host. Whether it runs right now is no part+ // of it: a stopped one is started again on the same volume. /status reports the type, host, endpoint and+ // bucket in use; the port and the database name are not on it, so those compare with the saved config as+ // the page loaded it. A key with nothing saved reads '', and runs on the same fallback the form was seeded+ // with. A new local path is no switch.const loaded = loadedConfig.current;const pinned = (key: string) => (infraStatus?.envPinned?.includes(key) ? loaded : undefined);const db = configForm.dbConfig;@@ -117,7 +92,7 @@ export function Infrastructure() {const dbSwitch =!!infraStatus &&(dbType !== infraStatus.database.type ||- (dbType === 'postgres' && (dbHost !== infraStatus.database.host || dbExternalRetarget)));+ (dbType === 'postgres' && (!sameHost('postgres', dbHost, infraStatus.database.host) || dbExternalRetarget)));const storage = configForm.storageConfig;const storageType = pinned('STORAGE_TYPE')?.storage.type ?? storage.type;// The storage section takes the bundled bucket for a flag sent as true only: beside a pinned endpoint an untouched@@ -130,7 +105,7 @@ export function Infrastructure() {!!infraStatus &&(storageType !== infraStatus.storage.type ||(storageType === 's3' &&- (endpoint !== (infraStatus.storage.endpoint ?? '') ||+ (!sameHost('minio', endpoint, infraStatus.storage.endpoint ?? '') ||bucket !== (infraStatus.storage.bucket || 'openwa'))));// The built-in containers running now, so the restart stops each one the new config dropped. With no// status read there is nothing to go on, and nothing is stopped.@@ -365,7 +340,7 @@ export function Infrastructure() {infraStatus.database.type === 'postgres' && savedConfig.database.type === 'postgres',infraStatus.database.builtIn,savedBuiltIn(savedConfig.database, infraStatus.database.builtIn),- infraStatus.database.host === 'postgres',+ namesBundledContainer('postgres', infraStatus.database.host),)}{pinNote('DATABASE_HOST')}@@ -670,7 +645,7 @@ export function Infrastructure() {infraStatus.redis.enabled && savedConfig.redis.enabled,infraStatus.redis.builtIn,savedBuiltIn(savedConfig.redis, infraStatus.redis.builtIn),- infraStatus.redis.host === 'redis',+ namesBundledContainer('redis', infraStatus.redis.host),)}{pinNote('REDIS_HOST')}@@ -871,7 +846,7 @@ export function Infrastructure() {infraStatus.storage.type === 's3' && savedConfig.storage.type === 's3',infraStatus.storage.builtIn,savedBuiltIn(savedConfig.storage, infraStatus.storage.builtIn),- infraStatus.storage.endpoint === 'http://minio:9000',+ namesBundledContainer('minio', infraStatus.storage.endpoint),)}{pinNote('S3_ENDPOINT')}diff --git a/dashboard/src/utils/bundledHost.test.ts b/dashboard/src/utils/bundledHost.test.tsnew file mode 100644index 000000000..f362b25a6--- /dev/null+++ b/dashboard/src/utils/bundledHost.test.ts@@ -0,0 +1,57 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { namesBundledContainer, sameHost } from './bundledHost.ts';+import { namesBundledContainer as serverRule } from '../../../src/modules/docker/bundled-host.ts';+import { HOST_SPELLINGS, type ServiceName } from '../../../test/fixtures/builtin-mode-cases.ts';++const PROFILE: Record<ServiceName, string> = { database: 'postgres', redis: 'redis', storage: 'minio' };++// Every host spelling the shared table lists, plus generated ones: letter cases, trailing dots and spaces around the+// alias, the container name and a few other names, bare and inside endpoint URLs.+function candidates(): string[] {+ const names = ['postgres', 'redis', 'minio', 'openwa-postgres', 'openwa-redis', 'openwa-minio', 'localhost', 'db.x'];+ const cases = (n: string) => [n, n.toUpperCase(), n[0].toUpperCase() + n.slice(1)];+ const hosts = names.flatMap(cases).flatMap(h => ['', '.', '..', ' ', '. '].map(tail => h + tail));+ const urls = hosts.flatMap(h =>+ ['http://', 'https://', 'HTTP://'].flatMap(scheme =>+ ['', ':9000', ':9000/', '/bucket'].map(rest => `${scheme}${h.trim()}${rest}`),+ ),+ );+ const listed = Object.values(HOST_SPELLINGS).flatMap(s => [...s.reach, ...s.elsewhere]);+ return [...new Set([...listed, ...hosts, ...urls, '', ' ', 'not a url'])];+}++test('the page reads every host spelling the way the server does', () => {+ const values = candidates();+ let compared = 0;+ for (const profile of ['postgres', 'redis', 'minio', 'other']) {+ for (const value of [...values, undefined]) {+ assert.equal(+ namesBundledContainer(profile, value),+ serverRule(profile, value),+ `${profile} ${JSON.stringify(value)}`,+ );+ compared++;+ }+ }+ assert.ok(compared > 1000, `only ${compared} cases`);+});++test('the shared spellings reach the bundled container, the others do not', () => {+ for (const [service, { reach, elsewhere }] of Object.entries(HOST_SPELLINGS) as [+ ServiceName,+ typeof HOST_SPELLINGS.database,+ ][]) {+ for (const host of reach) assert.ok(namesBundledContainer(PROFILE[service], host), `${service} ${host}`);+ for (const host of elsewhere) assert.ok(!namesBundledContainer(PROFILE[service], host), `${service} ${host}`);+ }+});++test('two spellings of the bundled container are the same host, other hosts only when equal', () => {+ assert.ok(sameHost('postgres', 'postgres', 'OpenWA-Postgres.'));+ assert.ok(sameHost('minio', 'http://minio:9000', 'http://MINIO:9000/'));+ assert.ok(sameHost('postgres', 'db.example.com', 'db.example.com'));+ assert.ok(!sameHost('postgres', 'db.example.com', 'DB.example.com'));+ assert.ok(!sameHost('postgres', 'postgres', 'db.example.com'));+ assert.ok(!sameHost('redis', undefined, 'redis'));+});diff --git a/dashboard/src/utils/bundledHost.ts b/dashboard/src/utils/bundledHost.tsnew file mode 100644index 000000000..3980532f5--- /dev/null+++ b/dashboard/src/utils/bundledHost.ts@@ -0,0 +1,30 @@+// The container each managed profile runs, as the restart dialog names it.+export const CONTAINER_OF: Record<string, string> = {+ postgres: 'openwa-postgres',+ redis: 'openwa-redis',+ minio: 'openwa-minio',+};++/**+ * Whether a host (for minio, the host of an S3 endpoint) reaches the profile's bundled container: its network alias+ * (the profile name) or its container name, in any letter case, with or without a trailing dot. The server's+ * namesBundledContainer (src/modules/docker/bundled-host.ts) decides what the boot starts, what a restart stops and+ * which credentials a save keeps; bundledHost.test.ts holds this copy to its answers.+ */+export function namesBundledContainer(profile: string, value: string | undefined): boolean {+ if (!CONTAINER_OF[profile] || value === undefined) return false;+ let host = value.trim();+ if (profile === 'minio') {+ try {+ host = new URL(host).hostname;+ } catch {+ return false;+ }+ }+ host = host.toLowerCase().replace(/\.$/, '');+ return host === profile || host === CONTAINER_OF[profile];+}++/** Whether two hosts lead to the same server: the same value, or both the profile's bundled container. */+export const sameHost = (profile: string, a: string | undefined, b: string | undefined): boolean =>+ a === b || (namesBundledContainer(profile, a) && namesBundledContainer(profile, b));diff --git a/src/modules/docker/bundled-host.ts b/src/modules/docker/bundled-host.tsnew file mode 100644index 000000000..3dbc116fb--- /dev/null+++ b/src/modules/docker/bundled-host.ts@@ -0,0 +1,26 @@+/** The env key and value that point the app at each managed profile's bundled container. */+export const BUNDLED_SERVICE_ENV: Record<string, [string, string]> = {+ postgres: ['DATABASE_HOST', 'postgres'],+ redis: ['REDIS_HOST', 'redis'],+ minio: ['S3_ENDPOINT', 'http://minio:9000'],+};++/**+ * Whether a host (for minio, the host of an S3 endpoint) reaches the profile's bundled container: its network alias+ * (the profile name) or its container name, in any letter case and with or without the trailing dot of an absolute+ * DNS name. The one rule for every decision that asks it; the dashboard's copy (dashboard/src/utils/bundledHost.ts) is+ * held to the same answers by its test. Imports nothing, so that test can load this file.+ */+export function namesBundledContainer(profile: string, value: string | undefined): boolean {+ if (!BUNDLED_SERVICE_ENV[profile] || value === undefined) return false;+ let host = value.trim();+ if (profile === 'minio') {+ try {+ host = new URL(host).hostname;+ } catch {+ return false;+ }+ }+ host = host.toLowerCase().replace(/\.$/, '');+ return host === profile || host === `openwa-${profile}`;+}diff --git a/src/modules/docker/docker.service.ts b/src/modules/docker/docker.service.tsindex fe2a57b02..8268d101e 100644--- a/src/modules/docker/docker.service.ts+++ b/src/modules/docker/docker.service.ts@@ -3,6 +3,7 @@ import { createLogger } from '../../common/services/logger.service';import Docker from 'dockerode';import { isEnvPinned, isOsProvidedEnv } from '../../config/env-precedence';import { readGeneratedEnv } from '../infra/generated-env';+import { BUNDLED_SERVICE_ENV, namesBundledContainer } from './bundled-host';/*** The only Docker profiles OpenWA manages (and may start/stop). Used to bound teardown so a@@ -20,32 +21,6 @@ export function datastoreInUse(profile: string, read: (key: string) => string |return ['REDIS_ENABLED', 'QUEUE_ENABLED', 'CACHE_ENABLED'].some(key => read(key) === 'true');}-/** The env key and value that point the app at each managed profile's bundled container. */-export const BUNDLED_SERVICE_ENV: Record<string, [string, string]> = {- postgres: ['DATABASE_HOST', 'postgres'],- redis: ['REDIS_HOST', 'redis'],- minio: ['S3_ENDPOINT', 'http://minio:9000'],-};--/**- * Whether a host (for minio, the host of an S3 endpoint) reaches the profile's bundled container: its network alias- * (the profile name) or its container name, in any letter case and with or without the trailing dot of an absolute- * DNS name.- */-export function namesBundledContainer(profile: string, value: string | undefined): boolean {- if (!BUNDLED_SERVICE_ENV[profile] || value === undefined) return false;- let host = value.trim();- if (profile === 'minio') {- try {- host = new URL(host).hostname;- } catch {- return false;- }- }- host = host.toLowerCase().replace(/\.$/, '');- return host === profile || host === `openwa-${profile}`;-}-/*** Whether the environment (or the project .env) pins the profile's host to anything but its bundled container, in* any spelling namesBundledContainer accepts. The pin outranks the saved file at every boot, so a container starteddiff --git a/src/modules/docker/index.ts b/src/modules/docker/index.tsindex c4f16f538..0a6909316 100644--- a/src/modules/docker/index.ts+++ b/src/modules/docker/index.ts@@ -1,2 +1,3 @@export * from './docker.module';export * from './docker.service';+export * from './bundled-host';