Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix: migration-CLI env, dashboard cache sync, and dead-code cleanup (#479)

Yudhi Armyndharis3a2da4486359
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bf70a664c..e4e643f7c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The data export/import now includes the `lid_mappings` resolution cache, so a backup/restore or a SQLite↔PostgreSQL migration no longer drops it. (#477)
- The JavaScript client SDK applies the JSON `Content-Type` and `X-API-Key` after caller-supplied headers, so they can no longer be overridden by `defaultHeaders` (matching the Python and PHP SDKs); an unfollowed redirect (HTTP status `0`) now raises a clear error instead of `OpenWA API 0`. (#478)
- The infrastructure status endpoint reports the active S3 bucket when storage is in S3 mode, instead of only the unused local media path. (#478)
+- The migration CLI now honors the dashboard-written `data/.env.generated`, so `migration:run:prod` targets the configured database (e.g. PostgreSQL) instead of silently defaulting to SQLite. (#479)
+- The first-run generated config writes `STORAGE_LOCAL_PATH` (the key the backend reads) instead of the dead `STORAGE_PATH`. (#479)
+- The Sessions page now keeps the shared dashboard cache in sync, so creating/stopping/deleting a session no longer leaves the Dashboard showing stale session counts or status until a refresh. (#479)
### Security
diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsx
index f2df010f5..09d4613d0 100644
--- a/dashboard/src/pages/Sessions.tsx
+++ b/dashboard/src/pages/Sessions.tsx
@@ -1,7 +1,9 @@
import { useState, useEffect, useCallback, useRef } from 'react';
+import { useQueryClient } from '@tanstack/react-query';
import { Trans, useTranslation } from 'react-i18next';
import { Plus, QrCode, RefreshCw, Trash2, Eye, Loader2, Play, Square, X, Search, Filter, Skull } from 'lucide-react';
import { sessionApi, type Session } from '../services/api';
+import { queryKeys } from '../hooks/queries';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useToast } from '../components/Toast';
import { useWebSocket } from '../hooks/useWebSocket';
@@ -14,6 +16,7 @@ export function Sessions() {
useDocumentTitle(t('sessions.title'));
const toast = useToast();
const { canWrite } = useRole();
+ const queryClient = useQueryClient();
const [sessions, setSessions] = useState<Session[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -32,6 +35,14 @@ export function Sessions() {
setLoading(true);
const data = await sessionApi.list();
setSessions(data);
+ // Keep the shared React Query cache (read by the Dashboard via useSessionsQuery /
+ // useSessionStatsQuery) in sync after this page's mutations reload local state — otherwise the
+ // Dashboard shows stale session counts/status. This runs on every reload (mount / WS-failed /
+ // mutation), which is harmless: the Sessions page holds no active observer on a ['sessions', …]
+ // query, so invalidation only marks the shared cache stale (no refetch here, no loop) and the
+ // Dashboard/other views refetch lazily on next mount. Prefix-matches every session-scoped key
+ // (sessions, sessionStats, per-session groups/chats/templates).
+ void queryClient.invalidateQueries({ queryKey: queryKeys.sessions });
return data;
} catch (err) {
setError(err instanceof Error ? err.message : t('sessions.create.errorDefault'));
@@ -39,7 +50,7 @@ export function Sessions() {
} finally {
setLoading(false);
}
- }, [t]);
+ }, [t, queryClient]);
const { isConnected, subscribe } = useWebSocket({
onSessionStatus: useCallback(
diff --git a/src/database/data-source-main.ts b/src/database/data-source-main.ts
index 45df8a2d4..630f13e58 100644
--- a/src/database/data-source-main.ts
+++ b/src/database/data-source-main.ts
@@ -1,8 +1,8 @@
import { DataSource } from 'typeorm';
-import { config } from 'dotenv';
+import { loadCliEnv } from './load-cli-env';
-// Load environment variables (mirrors data-source.ts).
-config();
+// Load environment variables with the app's precedence (mirrors data-source.ts / main.ts).
+loadCliEnv();
/**
* Standalone TypeORM CLI DataSource for the MAIN connection (auth + audit).
diff --git a/src/database/data-source.ts b/src/database/data-source.ts
index f5b6cadb3..3bb99d74d 100644
--- a/src/database/data-source.ts
+++ b/src/database/data-source.ts
@@ -1,8 +1,9 @@
import { DataSource } from 'typeorm';
-import { config } from 'dotenv';
+import { loadCliEnv } from './load-cli-env';
-// Load environment variables
-config();
+// Load env with the same precedence as the app (process.env > .env > data/.env.generated), so the
+// migration CLI targets the SAME database the dashboard configured — not the default SQLite DB.
+loadCliEnv();
const dbType = process.env.DATABASE_TYPE || 'sqlite';
diff --git a/src/database/load-cli-env.spec.ts b/src/database/load-cli-env.spec.ts
new file mode 100644
index 000000000..ad406786b
--- /dev/null
+++ b/src/database/load-cli-env.spec.ts
@@ -0,0 +1,51 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { loadCliEnv } from './load-cli-env';
+
+describe('loadCliEnv (migration CLI env precedence)', () => {
+ let dir: string;
+ const KEY = 'DATABASE_TYPE';
+ let original: string | undefined;
+
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-cli-env-'));
+ fs.mkdirSync(path.join(dir, 'data'), { recursive: true });
+ original = process.env[KEY];
+ delete process.env[KEY];
+ });
+
+ afterEach(() => {
+ fs.rmSync(dir, { recursive: true, force: true });
+ if (original === undefined) delete process.env[KEY];
+ else process.env[KEY] = original;
+ });
+
+ it('reads data/.env.generated (the dashboard-written config) when the var is unset', () => {
+ fs.writeFileSync(path.join(dir, 'data', '.env.generated'), 'DATABASE_TYPE=postgres\n');
+
+ loadCliEnv(dir);
+
+ // Without this load the CLI would default to sqlite and migrate the wrong database.
+ expect(process.env[KEY]).toBe('postgres');
+ });
+
+ it('does not let .env.generated override an explicit process.env value (precedence holds)', () => {
+ process.env[KEY] = 'postgres';
+ fs.writeFileSync(path.join(dir, 'data', '.env.generated'), 'DATABASE_TYPE=sqlite\n');
+
+ loadCliEnv(dir);
+
+ expect(process.env[KEY]).toBe('postgres');
+ });
+
+ it('lets .env win over data/.env.generated (the middle layer), matching main.ts ordering', () => {
+ // Guards against a future edit that reorders the two loads or flips override — .env must win.
+ fs.writeFileSync(path.join(dir, '.env'), 'DATABASE_TYPE=postgres\n');
+ fs.writeFileSync(path.join(dir, 'data', '.env.generated'), 'DATABASE_TYPE=sqlite\n');
+
+ loadCliEnv(dir);
+
+ expect(process.env[KEY]).toBe('postgres');
+ });
+});
diff --git a/src/database/load-cli-env.ts b/src/database/load-cli-env.ts
new file mode 100644
index 000000000..051c12541
--- /dev/null
+++ b/src/database/load-cli-env.ts
@@ -0,0 +1,20 @@
+import { config } from 'dotenv';
+import * as fs from 'fs';
+import * as path from 'path';
+import { clearBlankEnv, BLANK_SHADOWED_ENV_KEYS } from '../config/env-precedence';
+
+/**
+ * Load environment for the standalone TypeORM CLI data-sources with the SAME precedence as
+ * src/main.ts: `process.env` > `.env` > `data/.env.generated` (all dotenv `override: false`), with
+ * blank compose-forwarded keys cleared first. Without this, the migration CLI ignored the
+ * dashboard-written `data/.env.generated` and ran against the default SQLite DB even when the
+ * deployment was configured (via the dashboard) for PostgreSQL — i.e. `migration:run:prod` targeted
+ * the wrong database. `cwd` is injectable for testing.
+ */
+export function loadCliEnv(cwd: string = process.cwd()): void {
+ clearBlankEnv(process.env, BLANK_SHADOWED_ENV_KEYS);
+ const userEnvPath = path.resolve(cwd, '.env');
+ const generatedEnvPath = path.resolve(cwd, 'data', '.env.generated');
+ if (fs.existsSync(userEnvPath)) config({ path: userEnvPath, override: false });
+ if (fs.existsSync(generatedEnvPath)) config({ path: generatedEnvPath, override: false });
+}
diff --git a/src/main.ts b/src/main.ts
index e093e0e7a..39ac59078 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -88,7 +88,7 @@ QUEUE_ENABLED=false
# Storage (Local filesystem)
STORAGE_TYPE=local
MINIO_BUILTIN=false
-STORAGE_PATH=./data/media
+STORAGE_LOCAL_PATH=./data/media
# Docker Profiles: none (minimal setup)
`;
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.ts
index a3ba43004..46e89bf8e 100644
--- a/src/modules/events/events.gateway.spec.ts
+++ b/src/modules/events/events.gateway.spec.ts
@@ -257,9 +257,7 @@ describe('event catalog ⇔ emitter invariants (drift guard)', () => {
(gateway as unknown as { server: unknown }).server = { to: () => op };
const proto = Object.getPrototypeOf(gateway) as object;
- const emitMethods = Object.getOwnPropertyNames(proto).filter(
- n => n.startsWith('emit') && n !== 'emitToRooms' && n !== 'emitWebhookStatus',
- );
+ const emitMethods = Object.getOwnPropertyNames(proto).filter(n => n.startsWith('emit') && n !== 'emitToRooms');
for (const name of emitMethods) {
(gateway as unknown as Record<string, (...a: unknown[]) => void>)[name]('sess-1', {});
}
diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.ts
index 894f0adde..ab0993f24 100644
--- a/src/modules/events/events.gateway.ts
+++ b/src/modules/events/events.gateway.ts
@@ -324,17 +324,4 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
emitMessageReaction(sessionId: string, data: Record<string, unknown>) {
this.emitToRooms(sessionId, 'message.reaction', data);
}
-
- /**
- * Emit webhook delivery status (broadcast to all - no session context)
- */
- emitWebhookStatus(webhookId: string, success: boolean, error?: string) {
- // This one broadcasts to all since webhooks don't have session context in the same way
- this.server.emit('webhook:delivery', {
- webhookId,
- success,
- error,
- timestamp: new Date().toISOString(),
- });
- }
}
diff --git a/src/modules/template/template.service.ts b/src/modules/template/template.service.ts
index 9d31bb206..2d8200ac8 100644
--- a/src/modules/template/template.service.ts
+++ b/src/modules/template/template.service.ts
@@ -4,18 +4,7 @@ import { Repository } from 'typeorm';
import { Template } from './entities/template.entity';
import { CreateTemplateDto, UpdateTemplateDto } from './dto';
import { createLogger } from '../../common/services/logger.service';
-
-/** True for a UNIQUE-constraint violation across both the SQLite and PostgreSQL drivers. */
-function isUniqueViolation(err: unknown): boolean {
- const e = err as { code?: string; message?: string; driverError?: { code?: string } };
- return (
- e?.code === '23505' || // PostgreSQL unique_violation
- e?.driverError?.code === '23505' ||
- e?.code === 'SQLITE_CONSTRAINT' ||
- e?.driverError?.code === 'SQLITE_CONSTRAINT' ||
- (typeof e?.message === 'string' && /unique constraint/i.test(e.message))
- );
-}
+import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
@Injectable()
export class TemplateService {
@@ -40,7 +29,7 @@ export class TemplateService {
this.logger.log('Template created', { sessionId, templateId: saved.id, name: saved.name });
return saved;
} catch (err) {
- if (isUniqueViolation(err)) {
+ if (isUniqueConstraintError(err)) {
throw new ConflictException(`A template named '${dto.name}' already exists for this session`);
}
throw err;
@@ -100,7 +89,7 @@ export class TemplateService {
try {
return await this.templateRepository.save(template);
} catch (err) {
- if (isUniqueViolation(err)) {
+ if (isUniqueConstraintError(err)) {
throw new ConflictException(`A template named '${template.name}' already exists for this session`);
}
throw err;