Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(#488): auto-pin WhatsApp Web build + infra dashboard reflects/controls running state (#489)
Yudhi Armyndhariscbbe51c0cf06
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fb1122879..866b47bae 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,11 +9,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- The Infrastructure page now shows the actual **WhatsApp Web build** the whatsapp-web.js engine is using (e.g. `2.3000.1042251103-alpha`) and how it was chosen (pinned via `WWEBJS_WEB_VERSION`, auto-resolved, or native), surfaced via `/infra/status`. The engine card previously showed only the npm library version (`whatsapp-web.js 1.34.7`), which is unrelated to the WA Web build that actually governs connection stability. (#488)+- Infrastructure data **backup & restore**: export all Data-DB tables to a JSON file and import them back, wired into the database-switch flow. When you change the database backend, the restart dialog now warns that the new database starts empty and offers a one-click backup before switching; a storage switch warns that existing media is not moved. (#488)+- The Infrastructure page flags any database/redis/storage setting that is **pinned by an environment variable** (its running value differs from the saved config), so it's clear a dashboard change won't apply until that variable is unset, instead of the control silently having no effect. (#488)+- The storage card now warns when **S3 is selected but unreachable** (a dead/misconfigured bucket no longer shows a misleading green badge), via a new `s3Available` field on `/infra/status`. (#488)+- Data-loss & availability hardening for the new infra flows: importing a backup now **refuses an empty/garbage file** (it no longer wipes the database and reports success) and asks for confirmation first; selecting the **built-in Postgres/MinIO no longer crash-loops a production boot** on the default-secret guard (the bundled containers run on the internal-only network); and a transient failure fetching the WhatsApp Web version is no longer cached, so it retries instead of permanently falling back. (#488)- Human-readable console logs: the `LoggerService` now renders a colorized, NestJS-style line (`[OpenWA] <pid> - <timestamp> <LEVEL> [Context] <message>` with dimmed `key=value` metadata and stack traces on their own line) instead of always emitting raw JSON, so application logs line up visually with NestJS's own framework logs. The format defaults to structured JSON in production (`NODE_ENV=production`, for containers and log aggregators) and human-readable pretty everywhere else, and can be pinned with `LOG_FORMAT=pretty|json`. `NO_COLOR` / `FORCE_COLOR` are honored. JSON output is byte-for-byte unchanged when selected. (#469)### Fixed+- whatsapp-web.js sessions that scanned the QR then immediately disconnected (looping `qr → authenticating → disconnected`) when no `WWEBJS_WEB_VERSION` was pinned — the common Docker default. The engine now auto-resolves the current known-good WhatsApp Web build from the wppconnect `wa-version` registry and pins it, instead of relying on whatsapp-web.js's auto-select which could latch onto an incompatible bleeding-edge build that authenticates but never reaches "ready". `WWEBJS_WEB_VERSION=off` keeps the old native auto-select; an explicit version still pins exactly. (#488)+- Dashboard message-analytics charts no longer silently vanish on PostgreSQL: `/stats/messages` (top-chats) ordered by an unquoted mixed-case alias (`ORDER BY messageCount`), which PostgreSQL case-folds and rejects with `column "messagecount" does not exist` (500). It now orders by the aggregate directly, so the query — and the dashboard charts it feeds — work on PostgreSQL as they already did on SQLite. The chart section also shows a clear notice on a real error instead of rendering nothing (it previously treated every error as a non-admin 403 and hid itself). (#488)+- The Infrastructure page now shows what is **actually running** for the database, Redis, storage, and engine — the badge/selected card follow the live `/infra/status` instead of the saved `data/.env.generated`, which could disagree when a setting is supplied via environment variable. Previously a stack running PostgreSQL via `DATABASE_TYPE=postgres` showed "SQLite" (the first-run default still in the saved file). `/infra/status` now also reports `redis.enabled`. (#488)+- The "Use Built-in PostgreSQL/Redis/MinIO Container" toggles now reflect whether OpenWA's **bundled container is actually running** and backing the service (detected from the labeled container + the configured host), not just the saved intent — so a Postgres stack started via the `postgres` compose profile correctly shows built-in, and a stopped/external one shows off. Falls back to the saved flag when Docker isn't reachable. (#488)+- Switching **away** from a built-in backend (built-in → external/disabled) now tears down the bundled container reliably even after a page reload: removal is derived server-side from the saved `*_BUILTIN` flags + the running labeled containers, instead of only trusting the browser's in-memory list (which reset on reload and left the container orphaned). Named volumes are preserved, so re-enabling reuses the data. (#488)- Dashboard "by type" message chart: each message type now gets a stable, distinct color keyed by type name (with a deterministic hash fallback) instead of a rotating array-index palette, so a slice keeps its color when the set of present types changes between requests and types past the eighth no longer collide. (#486)+- Removed the oversized decorative watermark icons bleeding through the dashboard stat cards. (#488)+- Dashboard switches for the **database, Redis, and storage** backends now actually take effect after a restart, matching how the engine switch already worked. The bundled `docker-compose.yml` forwards these settings blank (`${VAR:-}`) so the dashboard's saved selection (in `data/.env.generated`) is honored, while a real value set in your `.env`/host still pins it (and the UI now says so). Previously compose forwarded concrete defaults that silently shadowed the dashboard's choice, so switching had no effect under Docker. (#488)++### Changed++- ⚠️ `docker-compose.yml` now forwards the S3 credentials under their canonical names `S3_ACCESS_KEY_ID` / `S3_SECRET_ACCESS_KEY` (and adds `S3_REGION`), matching what the app and dashboard read. The legacy `S3_ACCESS_KEY` / `S3_SECRET_KEY` are still accepted as a fallback, so existing setups keep working, but updating your `.env` to the canonical names is recommended. (#488)+- ⚠️ Database/Redis/storage selection is now sourced from the dashboard-managed `data/.env.generated` when not pinned by an environment variable (see Fixed, above). If you previously relied on the compose file's concrete defaults overriding a stale `data/.env.generated`, set the value explicitly in your `.env`/host to pin it. First-run defaults (SQLite, local storage, Redis off) are unchanged. (#488)## [0.7.6] - 2026-06-26diff --git a/dashboard/src/components/DashboardCharts.tsx b/dashboard/src/components/DashboardCharts.tsxindex 05df5384c..5b4119c66 100644--- a/dashboard/src/components/DashboardCharts.tsx+++ b/dashboard/src/components/DashboardCharts.tsx@@ -61,10 +61,13 @@ function shortChat(chatId: string): string {export function DashboardCharts() {const { t } = useTranslation();const [period, setPeriod] = useState<StatsPeriod>('7d');- const { data, isLoading, isError } = useStatsMessagesQuery(period);+ const { data, isLoading, isError, error } = useStatsMessagesQuery(period);- // Non-admin keys 403 on /stats/messages; hide the section rather than show a broken card.- if (isError) return null;+ // Non-admin keys 403 on /stats/messages → hide the section entirely. Any OTHER error (e.g. a+ // server 500) is a real fault: surface a small notice below instead of silently vanishing, which+ // is what masked the #488 stats crash and made the whole chart "disappear" with no explanation.+ const forbidden = (error as (Error & { status?: number }) | null)?.status === 403;+ if (isError && forbidden) return null;const timeSeries = (data?.timeSeries ?? []).map(p => ({ ...p, label: formatTick(p.timestamp, period) }));const byType = Object.entries(data?.byType ?? {})@@ -97,6 +100,8 @@ export function DashboardCharts() {{isLoading ? (<div className="charts-empty">{t('common.loading')}</div>+ ) : isError ? (+ <div className="charts-empty">{t('dashboard.charts.error')}</div>) : !hasData ? (<div className="charts-empty">{t('dashboard.charts.empty')}</div>) : (diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 5b8ef478c..3832ef726 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -173,7 +173,8 @@"sent": "المُرسَلة","received": "المُستلَمة","messages": "الرسائل",- "empty": "لا يوجد نشاط رسائل في هذه الفترة."+ "empty": "لا يوجد نشاط رسائل في هذه الفترة.",+ "error": "تعذّر تحميل تحليلات الرسائل. تحقّق من سجلّات الخادم."}},"sessionStatus": {@@ -577,7 +578,14 @@"sessionDataPath": "مسار بيانات الجلسة","browserArgs": "وسائط المتصفح","noBrowser": "يتصل هذا المحرك عبر WebSocket — لا يحتوي على متصفح، لذلك لا توجد إعدادات للوضع بدون واجهة أو وسائط المتصفح. يُطبَّق المحرك النشط بعد إعادة التشغيل.",- "restartNote": "يسري تغيير المحرك بعد إعادة تشغيل الخادم."+ "restartNote": "يسري تغيير المحرك بعد إعادة تشغيل الخادم.",+ "webVersion": "إصدار WhatsApp Web",+ "webVersionNative": "تلقائي (الإعداد الافتراضي لـ whatsapp-web.js)",+ "webVersionSource": {+ "pinned": "مُثبَّت عبر WWEBJS_WEB_VERSION",+ "auto": "محلول تلقائيًّا، أحدث إصدار معروف بصلاحيته",+ "native": "اختيار تلقائي أصلي من whatsapp-web.js"+ }},"redis": {"title": "Redis",@@ -613,7 +621,8 @@"accessKey": "مفتاح الوصول","secretKey": "المفتاح السري","endpoint": "نقطة نهاية مخصصة (اختياري)",- "endpointHint": "لـ MinIO أو خدمات متوافقة مع S3 أخرى"+ "endpointHint": "لـ MinIO أو خدمات متوافقة مع S3 أخرى",+ "s3Unreachable": "S3 (غير قابل للوصول)"},"statusLabels": {"connected": "متصل",@@ -638,6 +647,22 @@},"toasts": {"saveFailed": "فشل الحفظ"+ },+ "envPinNote": "مُثبَّت عبر متغيّر بيئة — هذه هي القيمة قيد التشغيل؛ لن تُطبَّق تغييرات لوحة التحكّم حتى يُلغى هذا المتغيّر.",+ "migration": {+ "title": "تنبيه — هذا يُغيِّر خلفية البيانات",+ "dbWarning": "تبدأ قاعدة البيانات الجديدة فارغة. نزِّل نسخة احتياطية من بياناتك الحالية الآن (وأنت لا تزال على قاعدة البيانات القديمة)، ثم استعدها بعد إعادة التشغيل.",+ "storageWarning": "لا تُنقل ملفات الوسائط الحالية إلى خلفية التخزين الجديدة تلقائيًّا؛ ستبقى في موقعها القديم.",+ "downloadBackup": "نزِّل نسخة احتياطية أولًا",+ "backupTitle": "نسخ البيانات احتياطيًّا واستعادتها",+ "backupHint": "صدِّر جميع البيانات بصيغة JSON قبل تبديل قواعد البيانات، ثم استوردها بعد التبديل. تحتوي النسخة الاحتياطية على أسرار الـ webhook وبيانات اعتماد الوكيل بنصّ صريح — خزِّنها بأمان واحذفها بعد الاستعادة.",+ "export": "تصدير البيانات",+ "import": "استيراد البيانات",+ "exportFailed": "تعذّر تصدير البيانات",+ "importFailed": "تعذّر استيراد البيانات",+ "importOk": "تمّ استيراد البيانات",+ "importConfirm": "سيؤدّي الاستيراد إلى استبدال جميع البيانات الحالية بالنسخة الاحتياطية ({{rows}} صفًّا). لا يمكن التراجع عن هذا الإجراء. هل تريد المتابعة؟",+ "invalidFile": "هذا الملفّ ليس نسخة احتياطية صالحة لبيانات OpenWA."}},"plugins": {diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex d42e3479c..903f0b462 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -173,7 +173,8 @@"sent": "Sent","received": "Received","messages": "Messages",- "empty": "No message activity in this period."+ "empty": "No message activity in this period.",+ "error": "Couldn't load message analytics. Check the server logs."}},"sessionStatus": {@@ -577,7 +578,14 @@"sessionDataPath": "Session Data Path","browserArgs": "Browser Arguments","noBrowser": "This engine connects over WebSocket — it has no browser, so there are no headless or browser-argument settings. The active engine is applied after a restart.",- "restartNote": "Switching the engine takes effect after a server restart."+ "restartNote": "Switching the engine takes effect after a server restart.",+ "webVersion": "WhatsApp Web build",+ "webVersionNative": "auto (whatsapp-web.js default)",+ "webVersionSource": {+ "pinned": "pinned via WWEBJS_WEB_VERSION",+ "auto": "auto-resolved, current known-good build",+ "native": "whatsapp-web.js native auto-select"+ }},"redis": {"title": "Redis",@@ -601,6 +609,7 @@},"storage": {"title": "Storage Configuration",+ "s3Unreachable": "S3 (unreachable)","local": "Local Filesystem","localDesc": "Store media files locally","s3": "Amazon S3",@@ -620,6 +629,22 @@"disconnected": "Disconnected","disabled": "Disabled"},+ "envPinNote": "Pinned by an environment variable — this is the running value; dashboard changes won't apply until that variable is unset.",+ "migration": {+ "title": "Heads up — this changes the data backend",+ "dbWarning": "The new database starts empty. Download a backup of your current data now (while still on the old database), then restore it after the restart.",+ "storageWarning": "Existing media files are not moved to the new storage backend automatically; they'll remain in the old location.",+ "downloadBackup": "Download backup first",+ "backupTitle": "Data backup & restore",+ "backupHint": "Export all data as JSON before switching databases, then import it after the switch. The backup contains webhook secrets and proxy credentials in plaintext — store it securely and delete it after restoring.",+ "export": "Export data",+ "import": "Import data",+ "exportFailed": "Couldn't export data",+ "importFailed": "Couldn't import data",+ "importOk": "Data imported",+ "importConfirm": "Importing will REPLACE all current data with the backup ({{rows}} rows). This cannot be undone. Continue?",+ "invalidFile": "That file isn't a valid OpenWA data backup."+ },"restart": {"idleTitle": "Configuration saved","restartingTitle": "Restarting server…",diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex 81e8d3fc3..4251aea76 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -173,7 +173,8 @@"sent": "Enviados","received": "Recibidos","messages": "Mensajes",- "empty": "Sin actividad de mensajes en este período."+ "empty": "Sin actividad de mensajes en este período.",+ "error": "No se pudieron cargar las analíticas de mensajes. Revisa los registros del servidor."}},"sessionStatus": {@@ -577,7 +578,14 @@"sessionDataPath": "Ruta de datos de sesión","browserArgs": "Argumentos del navegador","noBrowser": "Este motor se conecta por WebSocket: no tiene navegador, por lo que no hay ajustes de modo headless ni de argumentos del navegador. El motor activo se aplica tras reiniciar.",- "restartNote": "Cambiar el motor surte efecto tras reiniciar el servidor."+ "restartNote": "Cambiar el motor surte efecto tras reiniciar el servidor.",+ "webVersion": "Compilación de WhatsApp Web",+ "webVersionNative": "automático (predeterminado de whatsapp-web.js)",+ "webVersionSource": {+ "pinned": "fijado mediante WWEBJS_WEB_VERSION",+ "auto": "resuelto automáticamente, compilación estable conocida actual",+ "native": "selección automática nativa de whatsapp-web.js"+ }},"redis": {"title": "Redis",@@ -613,7 +621,8 @@"accessKey": "Clave de acceso","secretKey": "Clave secreta","endpoint": "Endpoint personalizado (opcional)",- "endpointHint": "Para MinIO u otros servicios compatibles con S3"+ "endpointHint": "Para MinIO u otros servicios compatibles con S3",+ "s3Unreachable": "S3 (inaccesible)"},"statusLabels": {"connected": "Conectado",@@ -638,6 +647,22 @@},"toasts": {"saveFailed": "Error al guardar"+ },+ "envPinNote": "Fijado por una variable de entorno: este es el valor en ejecución; los cambios del panel no se aplicarán hasta que esa variable se elimine.",+ "migration": {+ "title": "Atención: esto cambia el backend de datos",+ "dbWarning": "La nueva base de datos comienza vacía. Descarga ahora una copia de seguridad de tus datos actuales (mientras sigues en la base de datos anterior) y luego restáurala después del reinicio.",+ "storageWarning": "Los archivos multimedia existentes no se trasladan automáticamente al nuevo backend de almacenamiento; permanecerán en la ubicación anterior.",+ "downloadBackup": "Descargar copia de seguridad primero",+ "backupTitle": "Copia de seguridad y restauración de datos",+ "backupHint": "Exporta todos los datos como JSON antes de cambiar de base de datos y luego impórtalos tras el cambio. La copia de seguridad contiene secretos de webhook y credenciales de proxy en texto plano: guárdala de forma segura y elimínala después de restaurarla.",+ "export": "Exportar datos",+ "import": "Importar datos",+ "exportFailed": "No se pudieron exportar los datos",+ "importFailed": "No se pudieron importar los datos",+ "importOk": "Datos importados",+ "importConfirm": "La importación REEMPLAZARÁ todos los datos actuales con la copia de seguridad ({{rows}} filas). Esto no se puede deshacer. ¿Continuar?",+ "invalidFile": "Ese archivo no es una copia de seguridad de datos válida de OpenWA."}},"plugins": {diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex a3b493196..57a68f146 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -173,7 +173,8 @@"sent": "Envoyés","received": "Reçus","messages": "Messages",- "empty": "Aucune activité de message sur cette période."+ "empty": "Aucune activité de message sur cette période.",+ "error": "Impossible de charger les statistiques des messages. Vérifiez les journaux du serveur."}},"sessionStatus": {@@ -577,7 +578,14 @@"sessionDataPath": "Chemin des données de session","browserArgs": "Arguments du navigateur","noBrowser": "Ce moteur se connecte via WebSocket : il n'a pas de navigateur, il n'y a donc pas de réglages de mode headless ni d'arguments de navigateur. Le moteur actif est appliqué après un redémarrage.",- "restartNote": "Le changement de moteur prend effet après le redémarrage du serveur."+ "restartNote": "Le changement de moteur prend effet après le redémarrage du serveur.",+ "webVersion": "Build WhatsApp Web",+ "webVersionNative": "auto (valeur par défaut de whatsapp-web.js)",+ "webVersionSource": {+ "pinned": "fixé via WWEBJS_WEB_VERSION",+ "auto": "résolu automatiquement, build connu comme stable actuel",+ "native": "sélection automatique native de whatsapp-web.js"+ }},"redis": {"title": "Redis",@@ -613,7 +621,8 @@"accessKey": "Clé d'accès","secretKey": "Clé secrète","endpoint": "Point de terminaison personnalisé (optionnel)",- "endpointHint": "Pour MinIO ou d'autres services compatibles S3"+ "endpointHint": "Pour MinIO ou d'autres services compatibles S3",+ "s3Unreachable": "S3 (injoignable)"},"statusLabels": {"connected": "Connecté",@@ -638,6 +647,22 @@},"toasts": {"saveFailed": "Échec de l'enregistrement"+ },+ "envPinNote": "Défini par une variable d'environnement — c'est la valeur en cours d'exécution ; les modifications du tableau de bord ne s'appliqueront pas tant que cette variable ne sera pas supprimée.",+ "migration": {+ "title": "Attention — cela change le backend de données",+ "dbWarning": "La nouvelle base de données démarre vide. Téléchargez dès maintenant une sauvegarde de vos données actuelles (tant que vous êtes encore sur l'ancienne base de données), puis restaurez-la après le redémarrage.",+ "storageWarning": "Les fichiers multimédias existants ne sont pas déplacés automatiquement vers le nouveau backend de stockage ; ils resteront à leur ancien emplacement.",+ "downloadBackup": "Télécharger d'abord la sauvegarde",+ "backupTitle": "Sauvegarde et restauration des données",+ "backupHint": "Exportez toutes les données au format JSON avant de changer de base de données, puis importez-les après le changement. La sauvegarde contient les secrets de webhook et les identifiants de proxy en clair — conservez-la de manière sécurisée et supprimez-la après la restauration.",+ "export": "Exporter les données",+ "import": "Importer les données",+ "exportFailed": "Impossible d'exporter les données",+ "importFailed": "Impossible d'importer les données",+ "importOk": "Données importées",+ "importConfirm": "L'importation REMPLACERA toutes les données actuelles par la sauvegarde ({{rows}} lignes). Cette action est irréversible. Continuer ?",+ "invalidFile": "Ce fichier n'est pas une sauvegarde de données OpenWA valide."}},"plugins": {diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex 06f343f7b..4bd58e431 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -173,7 +173,8 @@"sent": "נשלחו","received": "התקבלו","messages": "הודעות",- "empty": "אין פעילות הודעות בתקופה זו."+ "empty": "אין פעילות הודעות בתקופה זו.",+ "error": "לא ניתן לטעון את ניתוח ההודעות. בדקו את יומני השרת."}},"sessionStatus": {@@ -577,7 +578,14 @@"sessionDataPath": "נתיב נתוני הפעלה","browserArgs": "ארגומנטים של הדפדפן","noBrowser": "מנוע זה מתחבר באמצעות WebSocket — אין לו דפדפן, ולכן אין הגדרות למצב ללא ממשק או לארגומנטים של הדפדפן. המנוע הפעיל מוחל לאחר הפעלה מחדש.",- "restartNote": "החלפת המנוע נכנסת לתוקף לאחר הפעלה מחדש של השרת."+ "restartNote": "החלפת המנוע נכנסת לתוקף לאחר הפעלה מחדש של השרת.",+ "webVersion": "גרסת WhatsApp Web",+ "webVersionNative": "אוטומטי (ברירת המחדל של whatsapp-web.js)",+ "webVersionSource": {+ "pinned": "מקובע באמצעות WWEBJS_WEB_VERSION",+ "auto": "נקבע אוטומטית, הגרסה היציבה הידועה העדכנית",+ "native": "בחירה אוטומטית מובנית של whatsapp-web.js"+ }},"redis": {"title": "Redis",@@ -613,7 +621,8 @@"accessKey": "Access Key","secretKey": "Secret Key","endpoint": "Endpoint מותאם (אופציונלי)",- "endpointHint": "עבור MinIO או שירותים אחרים תואמי S3"+ "endpointHint": "עבור MinIO או שירותים אחרים תואמי S3",+ "s3Unreachable": "S3 (לא נגיש)"},"statusLabels": {"connected": "מחובר",@@ -638,6 +647,22 @@},"toasts": {"saveFailed": "השמירה נכשלה"+ },+ "envPinNote": "מקובע על ידי משתנה סביבה — זהו הערך הפעיל; שינויים בלוח הבקרה לא ייכנסו לתוקף עד שמשתנה זה יבוטל.",+ "migration": {+ "title": "שימו לב — פעולה זו משנה את מנגנון אחסון הנתונים",+ "dbWarning": "מסד הנתונים החדש מתחיל ריק. הורידו עכשיו גיבוי של הנתונים הנוכחיים (בעודכם עדיין על מסד הנתונים הישן), ולאחר מכן שחזרו אותו לאחר ההפעלה מחדש.",+ "storageWarning": "קובצי מדיה קיימים אינם מועברים אוטומטית למנגנון האחסון החדש; הם יישארו במיקום הישן.",+ "downloadBackup": "הורידו גיבוי תחילה",+ "backupTitle": "גיבוי ושחזור נתונים",+ "backupHint": "ייצאו את כל הנתונים כ-JSON לפני החלפת מסדי הנתונים, ולאחר מכן ייבאו אותם לאחר ההחלפה. הגיבוי מכיל סודות webhook ופרטי גישה של proxy בטקסט גלוי — אחסנו אותו באופן מאובטח ומחקו אותו לאחר השחזור.",+ "export": "ייצוא נתונים",+ "import": "ייבוא נתונים",+ "exportFailed": "לא ניתן לייצא את הנתונים",+ "importFailed": "לא ניתן לייבא את הנתונים",+ "importOk": "הנתונים יובאו",+ "importConfirm": "הייבוא יחליף את כל הנתונים הנוכחיים בגיבוי ({{rows}} שורות). לא ניתן לבטל פעולה זו. להמשיך?",+ "invalidFile": "הקובץ הזה אינו גיבוי נתונים תקין של OpenWA."}},"plugins": {diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex a0c3b78ae..7e08e6ac6 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -173,7 +173,8 @@"sent": "Inviati","received": "Ricevuti","messages": "Messaggi",- "empty": "Nessuna attività di messaggi in questo periodo."+ "empty": "Nessuna attività di messaggi in questo periodo.",+ "error": "Impossibile caricare le analisi dei messaggi. Controlla i log del server."}},"sessionStatus": {@@ -577,7 +578,14 @@"sessionDataPath": "Percorso dati sessione","browserArgs": "Argomenti del browser","noBrowser": "Questo motore si connette tramite WebSocket: non ha un browser, quindi non ci sono impostazioni per la modalità headless o gli argomenti del browser. Il motore attivo viene applicato dopo un riavvio.",- "restartNote": "Il cambio di motore ha effetto dopo il riavvio del server."+ "restartNote": "Il cambio di motore ha effetto dopo il riavvio del server.",+ "webVersion": "Build di WhatsApp Web",+ "webVersionNative": "automatico (predefinito di whatsapp-web.js)",+ "webVersionSource": {+ "pinned": "fissato tramite WWEBJS_WEB_VERSION",+ "auto": "risolto automaticamente, build attuale verificata e funzionante",+ "native": "selezione automatica nativa di whatsapp-web.js"+ }},"redis": {"title": "Redis",@@ -613,7 +621,8 @@"accessKey": "Access Key","secretKey": "Secret Key","endpoint": "Endpoint Personalizzato (opzionale)",- "endpointHint": "Per MinIO o altri servizi compatibili con S3"+ "endpointHint": "Per MinIO o altri servizi compatibili con S3",+ "s3Unreachable": "S3 (non raggiungibile)"},"statusLabels": {"connected": "Connesso",@@ -638,6 +647,22 @@},"toasts": {"saveFailed": "Salvataggio Fallito"+ },+ "envPinNote": "Fissato da una variabile d'ambiente: questo è il valore in esecuzione; le modifiche dalla dashboard non avranno effetto finché la variabile non viene rimossa.",+ "migration": {+ "title": "Attenzione: questa operazione cambia il backend dei dati",+ "dbWarning": "Il nuovo database parte vuoto. Scarica ora un backup dei tuoi dati attuali (mentre sei ancora sul vecchio database), poi ripristinalo dopo il riavvio.",+ "storageWarning": "I file multimediali esistenti non vengono spostati automaticamente sul nuovo backend di archiviazione; rimarranno nella posizione precedente.",+ "downloadBackup": "Scarica prima il backup",+ "backupTitle": "Backup e ripristino dei dati",+ "backupHint": "Esporta tutti i dati come JSON prima di cambiare database, poi importali dopo il cambio. Il backup contiene i segreti dei webhook e le credenziali del proxy in chiaro: conservalo in modo sicuro ed eliminalo dopo il ripristino.",+ "export": "Esporta dati",+ "import": "Importa dati",+ "exportFailed": "Impossibile esportare i dati",+ "importFailed": "Impossibile importare i dati",+ "importOk": "Dati importati",+ "importConfirm": "L'importazione SOSTITUIRÀ tutti i dati attuali con il backup ({{rows}} righe). Questa operazione non può essere annullata. Continuare?",+ "invalidFile": "Questo file non è un backup dati valido di OpenWA."}},"plugins": {diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex 09d5ed4dd..4cc5864c9 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -173,7 +173,8 @@"sent": "పంపినవి","received": "స్వీకరించినవి","messages": "సందేశాలు",- "empty": "ఈ వ్యవధిలో సందేశ కార్యకలాపం లేదు."+ "empty": "ఈ వ్యవధిలో సందేశ కార్యకలాపం లేదు.",+ "error": "సందేశ విశ్లేషణలను లోడ్ చేయలేకపోయాం. సర్వర్ లాగ్లను తనిఖీ చేయండి."}},"sessionStatus": {@@ -577,7 +578,14 @@"sessionDataPath": "సెషన్ డేటా పాత్","browserArgs": "బ్రౌజర్ ఆర్గ్యుమెంట్లు","noBrowser": "ఈ ఇంజిన్ WebSocket ద్వారా కనెక్ట్ అవుతుంది — దీనికి బ్రౌజర్ లేదు, కాబట్టి హెడ్లెస్ లేదా బ్రౌజర్-ఆర్గ్యుమెంట్ సెట్టింగ్లు లేవు. యాక్టివ్ ఇంజిన్ రీస్టార్ట్ తర్వాత వర్తిస్తుంది.",- "restartNote": "ఇంజిన్ను మార్చడం సర్వర్ రీస్టార్ట్ తర్వాత అమలులోకి వస్తుంది."+ "restartNote": "ఇంజిన్ను మార్చడం సర్వర్ రీస్టార్ట్ తర్వాత అమలులోకి వస్తుంది.",+ "webVersion": "WhatsApp Web బిల్డ్",+ "webVersionNative": "ఆటో (whatsapp-web.js డిఫాల్ట్)",+ "webVersionSource": {+ "pinned": "WWEBJS_WEB_VERSION ద్వారా పిన్ చేయబడింది",+ "auto": "ఆటో-రిజాల్వ్ చేయబడింది, ప్రస్తుతం తెలిసిన మంచి బిల్డ్",+ "native": "whatsapp-web.js స్థానిక ఆటో-సెలెక్ట్"+ }},"redis": {"title": "Redis",@@ -613,7 +621,8 @@"accessKey": "యాక్సెస్ కీ","secretKey": "సీక్రెట్ కీ","endpoint": "కస్టమ్ ఎండ్పాయింట్ (ఐచ్ఛికం)",- "endpointHint": "MinIO లేదా ఇతర S3-అనుకూల సేవల కోసం"+ "endpointHint": "MinIO లేదా ఇతర S3-అనుకూల సేవల కోసం",+ "s3Unreachable": "S3 (చేరుకోలేనిది)"},"statusLabels": {"connected": "కనెక్ట్ అయింది",@@ -638,6 +647,22 @@},"toasts": {"saveFailed": "సేవ్ చేయడం విఫలమైంది"+ },+ "envPinNote": "ఒక ఎన్విరాన్మెంట్ వేరియబుల్ ద్వారా పిన్ చేయబడింది — ఇది ప్రస్తుతం అమలులో ఉన్న విలువ; ఆ వేరియబుల్ను తీసివేసే వరకు డ్యాష్బోర్డ్ మార్పులు వర్తించవు.",+ "migration": {+ "title": "గమనిక — ఇది డేటా బ్యాకెండ్ను మారుస్తుంది",+ "dbWarning": "కొత్త డేటాబేస్ ఖాళీగా ప్రారంభమవుతుంది. ఇప్పుడే (ఇంకా పాత డేటాబేస్లో ఉన్నప్పుడే) మీ ప్రస్తుత డేటా బ్యాకప్ను డౌన్లోడ్ చేయండి, ఆపై రీస్టార్ట్ తర్వాత దాన్ని పునరుద్ధరించండి.",+ "storageWarning": "ఇప్పటికే ఉన్న మీడియా ఫైళ్లు కొత్త స్టోరేజ్ బ్యాకెండ్కు స్వయంచాలకంగా తరలించబడవు; అవి పాత స్థానంలోనే ఉంటాయి.",+ "downloadBackup": "ముందుగా బ్యాకప్ డౌన్లోడ్ చేయండి",+ "backupTitle": "డేటా బ్యాకప్ & పునరుద్ధరణ",+ "backupHint": "డేటాబేస్లను మార్చే ముందు మొత్తం డేటాను JSON గా ఎక్స్పోర్ట్ చేయండి, ఆపై మార్పు తర్వాత దాన్ని ఇంపోర్ట్ చేయండి. బ్యాకప్లో వెబ్హుక్ సీక్రెట్లు మరియు ప్రాక్సీ క్రెడెన్షియల్స్ సాదా-వచనంలో (ప్లెయిన్టెక్స్ట్) ఉంటాయి — దాన్ని సురక్షితంగా నిల్వ చేయండి మరియు పునరుద్ధరించిన తర్వాత దాన్ని తొలగించండి.",+ "export": "డేటాను ఎక్స్పోర్ట్ చేయండి",+ "import": "డేటాను ఇంపోర్ట్ చేయండి",+ "exportFailed": "డేటాను ఎక్స్పోర్ట్ చేయలేకపోయాం",+ "importFailed": "డేటాను ఇంపోర్ట్ చేయలేకపోయాం",+ "importOk": "డేటా ఇంపోర్ట్ చేయబడింది",+ "importConfirm": "ఇంపోర్ట్ చేయడం వల్ల ప్రస్తుత డేటా మొత్తం బ్యాకప్తో ({{rows}} వరుసలు) భర్తీ చేయబడుతుంది. దీన్ని వెనక్కి తీసుకోలేరు. కొనసాగించాలా?",+ "invalidFile": "ఆ ఫైల్ చెల్లుబాటు అయ్యే OpenWA డేటా బ్యాకప్ కాదు."}},"plugins": {diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex d61729463..7ab01db57 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -173,7 +173,8 @@"sent": "已发送","received": "已接收","messages": "消息",- "empty": "此期间没有消息活动。"+ "empty": "此期间没有消息活动。",+ "error": "无法加载消息分析数据。请检查服务器日志。"}},"sessionStatus": {@@ -577,7 +578,14 @@"sessionDataPath": "会话数据路径","browserArgs": "浏览器参数","noBrowser": "该引擎通过 WebSocket 连接——没有浏览器,因此没有无头模式或浏览器参数设置。活动引擎将在重启后生效。",- "restartNote": "切换引擎将在服务器重启后生效。"+ "restartNote": "切换引擎将在服务器重启后生效。",+ "webVersion": "WhatsApp Web 构建版本",+ "webVersionNative": "自动(whatsapp-web.js 默认)",+ "webVersionSource": {+ "pinned": "通过 WWEBJS_WEB_VERSION 锁定",+ "auto": "自动解析,当前已知可用的构建版本",+ "native": "whatsapp-web.js 原生自动选择"+ }},"redis": {"title": "Redis",@@ -613,7 +621,8 @@"accessKey": "访问密钥","secretKey": "秘密密钥","endpoint": "自定义端点(可选)",- "endpointHint": "适用于 MinIO 或其他兼容 S3 的服务"+ "endpointHint": "适用于 MinIO 或其他兼容 S3 的服务",+ "s3Unreachable": "S3(无法连接)"},"statusLabels": {"connected": "已连接",@@ -638,6 +647,22 @@},"toasts": {"saveFailed": "保存失败"+ },+ "envPinNote": "已由环境变量锁定 —— 此为当前运行值;在取消该变量之前,仪表盘的更改不会生效。",+ "migration": {+ "title": "请注意 —— 此操作将更改数据后端",+ "dbWarning": "新数据库将从空白状态开始。请立即(在仍使用旧数据库时)下载当前数据的备份,然后在重启后恢复。",+ "storageWarning": "现有的媒体文件不会自动迁移到新的存储后端;它们将保留在原位置。",+ "downloadBackup": "请先下载备份",+ "backupTitle": "数据备份与恢复",+ "backupHint": "在切换数据库之前,将所有数据导出为 JSON,然后在切换后导入。备份中包含明文的 webhook 密钥和代理凭据 —— 请妥善保管,并在恢复完成后将其删除。",+ "export": "导出数据",+ "import": "导入数据",+ "exportFailed": "无法导出数据",+ "importFailed": "无法导入数据",+ "importOk": "数据已导入",+ "importConfirm": "导入操作将用备份数据替换(REPLACE)当前所有数据({{rows}} 行)。此操作无法撤销。是否继续?",+ "invalidFile": "该文件不是有效的 OpenWA 数据备份。"}},"plugins": {diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 862f8f211..290ca6052 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -173,7 +173,8 @@"sent": "已傳送","received": "已接收","messages": "訊息",- "empty": "此期間沒有訊息活動。"+ "empty": "此期間沒有訊息活動。",+ "error": "無法載入訊息分析。請查看伺服器日誌。"}},"sessionStatus": {@@ -577,7 +578,14 @@"sessionDataPath": "工作階段資料路徑","browserArgs": "瀏覽器參數","noBrowser": "此引擎透過 WebSocket 連線——沒有瀏覽器,因此沒有無頭模式或瀏覽器參數設定。使用中的引擎會在重新啟動後生效。",- "restartNote": "切換引擎會在伺服器重新啟動後生效。"+ "restartNote": "切換引擎會在伺服器重新啟動後生效。",+ "webVersion": "WhatsApp Web 版本",+ "webVersionNative": "自動(whatsapp-web.js 預設)",+ "webVersionSource": {+ "pinned": "透過 WWEBJS_WEB_VERSION 鎖定",+ "auto": "自動解析,目前已知可用的版本",+ "native": "whatsapp-web.js 原生自動選取"+ }},"redis": {"title": "Redis",@@ -613,7 +621,8 @@"accessKey": "存取金鑰","secretKey": "秘密金鑰","endpoint": "自訂端點(選填)",- "endpointHint": "適用於 MinIO 或其他兼容 S3 的服務"+ "endpointHint": "適用於 MinIO 或其他兼容 S3 的服務",+ "s3Unreachable": "S3(無法連線)"},"statusLabels": {"connected": "已連線",@@ -638,6 +647,22 @@},"toasts": {"saveFailed": "儲存失敗"+ },+ "envPinNote": "已由環境變數鎖定 — 這是正在運行的值;在取消設定該變數之前,儀表板的變更不會生效。",+ "migration": {+ "title": "請注意 — 此操作會更改資料後端",+ "dbWarning": "新資料庫會以空白狀態啟動。請立即下載目前資料的備份(趁仍在舊資料庫時),然後在重新啟動後還原。",+ "storageWarning": "現有的媒體檔案不會自動移至新的儲存後端;它們會保留在舊位置。",+ "downloadBackup": "請先下載備份",+ "backupTitle": "資料備份與還原",+ "backupHint": "在切換資料庫前,請將所有資料匯出為 JSON,然後在切換後再匯入。備份以明文包含 webhook 密鑰及代理憑證 — 請妥善保存,並在還原後刪除。",+ "export": "匯出資料",+ "import": "匯入資料",+ "exportFailed": "無法匯出資料",+ "importFailed": "無法匯入資料",+ "importOk": "資料已匯入",+ "importConfirm": "匯入將以備份({{rows}} 列)取代所有目前資料。此操作無法復原。是否繼續?",+ "invalidFile": "該檔案並非有效的 OpenWA 資料備份。"}},"plugins": {diff --git a/dashboard/src/pages/Dashboard.css b/dashboard/src/pages/Dashboard.cssindex 7f0f54e1f..d3dd1c5b9 100644--- a/dashboard/src/pages/Dashboard.css+++ b/dashboard/src/pages/Dashboard.css@@ -70,19 +70,6 @@z-index: 2;}-.dashboard .stat-watermark{- position: absolute;- right: -10px;- bottom: -15px;- width: 96px;- height: 96px;- opacity: 0.04;- color: var(--text-primary);- transform: rotate(-15deg);- pointer-events: none;- z-index: 1;-}-.dashboard .stat-label{font-size: 0.75rem;font-weight: 600;diff --git a/dashboard/src/pages/Dashboard.tsx b/dashboard/src/pages/Dashboard.tsxindex de615e661..7a5d7dd9b 100644--- a/dashboard/src/pages/Dashboard.tsx+++ b/dashboard/src/pages/Dashboard.tsx@@ -107,7 +107,6 @@ export function Dashboard() {<div className="stats-grid">{statsCards.map(({ label, value, icon: Icon, trend, trendUp }) => (<div key={label} className="stat-card">- <Icon className="stat-watermark" /><div className="stat-header"><span className="stat-label">{label}</span><Icon size={20} className="stat-icon" />diff --git a/dashboard/src/pages/Infrastructure.css b/dashboard/src/pages/Infrastructure.cssindex 2e4c85260..1e69f7abd 100644--- a/dashboard/src/pages/Infrastructure.css+++ b/dashboard/src/pages/Infrastructure.css@@ -618,3 +618,79 @@justify-content: center;}}++.infrastructure-page .engine-web-version{+ margin: 0.5rem 0 0;+ font-size: 0.8125rem;+ color: var(--text-secondary);+}+.infrastructure-page .engine-web-version code{+ font-size: 0.8125rem;+ background: var(--bg-subtle, rgba(127, 127, 127, 0.1));+ padding: 0.05rem 0.35rem;+ border-radius: 4px;+}+.infrastructure-page .engine-web-version .muted{+ color: var(--text-muted);+}++.infrastructure-page .env-pin-note{+ display: flex;+ align-items: center;+ gap: 0.4rem;+ margin: 0 0 1rem;+ font-size: 0.8125rem;+ color: var(--warning, #b45309);+}+.infrastructure-page .env-pin-note svg{+ flex-shrink: 0;+}++.infrastructure-page .migration-warning{+ display: flex;+ gap: 0.6rem;+ text-align: left;+ margin: 0 0 1.5rem;+ padding: 0.85rem 1rem;+ border-radius: 8px;+ background: rgba(245, 158, 11, 0.1);+ border: 1px solid rgba(245, 158, 11, 0.35);+ color: var(--text-primary);+}+.infrastructure-page .migration-warning svg{+ flex-shrink: 0;+ color: var(--warning, #d97706);+ margin-top: 0.1rem;+}+.infrastructure-page .migration-warning p{+ margin: 0.25rem 0 0.6rem;+ font-size: 0.8125rem;+ color: var(--text-secondary);+}++.infrastructure-page .data-migration-row{+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ margin-top: 1rem;+ padding-top: 1rem;+ border-top: 1px solid var(--border);+ flex-wrap: wrap;+}+.infrastructure-page .data-migration-row small{+ display: block;+ color: var(--text-muted);+ font-size: 0.75rem;+ margin-top: 0.15rem;+}+.infrastructure-page .data-migration-actions{+ display: flex;+ gap: 0.5rem;+}+.infrastructure-page .data-migration-actions .btn-sm,+.infrastructure-page .migration-warning .btn-sm{+ display: inline-flex;+ align-items: center;+ gap: 0.35rem;+}diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsxindex 5319452d9..df18219cd 100644--- a/dashboard/src/pages/Infrastructure.tsx+++ b/dashboard/src/pages/Infrastructure.tsx@@ -1,4 +1,4 @@-import { useState, useEffect } from 'react';+import { useState, useEffect, useRef } from 'react';import { Trans, useTranslation } from 'react-i18next';import {Database,@@ -10,6 +10,9 @@ import {CheckCircle,Trash2,Cpu,+ AlertTriangle,+ Download,+ Upload,} from 'lucide-react';import { infraApi, API_BASE_URL } from '../services/api';import { useDocumentTitle } from '../hooks/useDocumentTitle';@@ -135,46 +138,67 @@ export function Infrastructure() {const [queueEnabled, setQueueEnabled] = useState(false);const [pendingProfiles, setPendingProfiles] = useState<string[]>([]);const [previousProfiles, setPreviousProfiles] = useState<string[]>([]);+ // Set when the just-saved config changes the DB or storage backend vs what's running, so the restart+ // modal can warn that the new backend starts empty and offer a data backup before switching (#488).+ const [dbSwitch, setDbSwitch] = useState(false);+ const [storageSwitch, setStorageSwitch] = useState(false);+ const [migrating, setMigrating] = useState(false);+ // After a successful save (before the restart reloads the page), /config holds the new value but+ // /status still holds the old one — so suppress the "pinned by environment" note, which infers a pin+ // from exactly that divergence and would otherwise mislabel a pending change.+ const [savePending, setSavePending] = useState(false);+ // Whether the editable form has been seeded from the server once. After that, a background refetch+ // (react-query refetchOnWindowFocus) must NOT re-seed the editable fields or it would wipe the+ // operator's in-progress, unsaved edits. A successful save restarts → full page reload, re-arming it.+ const formHydrated = useRef(false);++ // LIVE indicators (not editable) — always reflect the running process, every refetch.useEffect(() => {if (!infraStatus) return;+ setRedisConfig(prev => ({ ...prev, connected: infraStatus.redis.connected }));+ setQueueStats({ messages: infraStatus.queue.messages, webhooks: infraStatus.queue.webhooks });+ }, [infraStatus]);+ // Seed the EDITABLE selections from live /status ONCE (the running selection), guarded so a refetch+ // can't clobber an unsaved edit. These are also the badge sources, so on first paint they show what's+ // actually running (#488 family).+ useEffect(() => {+ if (!infraStatus || formHydrated.current) return;setDbConfig(prev => ({...prev,type: (infraStatus.database.type as 'sqlite' | 'postgres') || 'sqlite',host: infraStatus.database.host || 'localhost',+ // builtIn reflects whether OpenWA's bundled container is actually running (live), not saved intent.+ builtIn: infraStatus.database.builtIn,}));-setRedisConfig(prev => ({...prev,host: infraStatus.redis.host,port: String(infraStatus.redis.port),- connected: infraStatus.redis.connected,+ builtIn: infraStatus.redis.builtIn,}));-+ setRedisEnabled(infraStatus.redis.enabled);setStorageConfig(prev => ({...prev,type: infraStatus.storage.type,localPath: infraStatus.storage.path || './uploads',+ builtIn: infraStatus.storage.builtIn,}));-setQueueEnabled(infraStatus.queue.enabled);- setQueueStats({- messages: infraStatus.queue.messages,- webhooks: infraStatus.queue.webhooks,- });}, [infraStatus]);- // Hydrate the editable form from the saved config (data/.env.generated) so the form- // reflects what was actually persisted — including fields /status does not expose- // (username, pool size, SSL flags, S3 details). Secrets are never returned, so their- // inputs stay empty; an empty submit preserves the stored secret on the backend (#226).+ // Hydrate the editable form from the saved config (data/.env.generated) ONCE — only the detail fields+ // /status does not expose (username, pool size, SSL flags, S3 details, host/port). The "what's+ // running" fields (type, redis enabled, storage type, built-in) are owned by the live /status effect+ // above. Secrets are never returned, so their inputs stay empty; an empty submit preserves the stored+ // secret on the backend (#226).useEffect(() => {- if (!savedConfig) return;+ if (!savedConfig || formHydrated.current) return;+ // NOTE: builtIn for db/redis/storage is owned by the live /status effect above (it reflects the+ // actually-running bundled container), so it is intentionally NOT set here from saved intent.setDbConfig(prev => ({...prev,- type: savedConfig.database.type,- builtIn: savedConfig.database.builtIn,host: savedConfig.database.host || prev.host,port: savedConfig.database.port || prev.port,username: savedConfig.database.username || prev.username,@@ -183,18 +207,13 @@ export function Infrastructure() {sslEnabled: savedConfig.database.sslEnabled,sslRejectUnauthorized: savedConfig.database.sslRejectUnauthorized,}));- setRedisEnabled(savedConfig.redis.enabled);setRedisConfig(prev => ({...prev,- builtIn: savedConfig.redis.builtIn,host: savedConfig.redis.host || prev.host,port: savedConfig.redis.port || prev.port,}));- setQueueEnabled(savedConfig.queue.enabled);setStorageConfig(prev => ({...prev,- type: savedConfig.storage.type,- builtIn: savedConfig.storage.builtIn,localPath: savedConfig.storage.localPath || prev.localPath,s3Bucket: savedConfig.storage.s3Bucket || prev.s3Bucket,s3Region: savedConfig.storage.s3Region || prev.s3Region,@@ -208,6 +227,12 @@ export function Infrastructure() {}));}, [savedConfig]);+ // Lock the editable form once both sources have seeded it, so later background refetches only refresh+ // the live indicators above and never overwrite unsaved edits.+ useEffect(() => {+ if (infraStatus && savedConfig) formHydrated.current = true;+ }, [infraStatus, savedConfig]);+// The active engine reflects what's actually running (honours a real-env ENGINE_TYPE override),// so seed the selected radio from it rather than the saved .env.generated value.useEffect(() => {@@ -247,8 +272,32 @@ export function Infrastructure() {const result = await infraApi.saveConfig(payload);if (result.saved) {+ setSavePending(true);setPreviousProfiles(pendingProfiles);setPendingProfiles(result.profiles || []);+ // Flag a backend switch vs what's actually running so the restart modal can warn about the+ // empty-database / orphaned-media data move before it happens. A switch is: changing type;+ // flipping built-in↔external (different physical backend); OR retargeting an external Postgres+ // to a different host/port/database (also a different, empty DB). Host/port/db aren't all in+ // /status, so compare the edited form against the still-cached saved config.+ const dbExternalRetarget =+ dbConfig.type === 'postgres' &&+ !dbConfig.builtIn &&+ !!savedConfig &&+ (dbConfig.host !== savedConfig.database.host ||+ dbConfig.port !== savedConfig.database.port ||+ dbConfig.database !== savedConfig.database.database);+ setDbSwitch(+ !!infraStatus &&+ (dbConfig.type !== infraStatus.database.type ||+ (dbConfig.type === 'postgres' && dbConfig.builtIn !== infraStatus.database.builtIn) ||+ dbExternalRetarget),+ );+ setStorageSwitch(+ !!infraStatus &&+ (storageConfig.type !== infraStatus.storage.type ||+ (storageConfig.type === 's3' && storageConfig.builtIn !== infraStatus.storage.builtIn)),+ );setShowRestartModal(true);} else {toast.error(t('infrastructure.toasts.saveFailed'), result.message);@@ -260,6 +309,54 @@ export function Infrastructure() {}};+ // 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).+ const handleExportBackup = async () => {+ setMigrating(true);+ try {+ const dump = await infraApi.exportData();+ const blob = new Blob([JSON.stringify(dump, null, 2)], { type: 'application/json' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `openwa-backup-${dump.exportedAt?.slice(0, 10) || 'data'}.json`;+ a.click();+ URL.revokeObjectURL(url);+ } catch (err) {+ toast.error(t('infrastructure.migration.exportFailed'), err instanceof Error ? err.message : t('common.unknownError'));+ } finally {+ setMigrating(false);+ }+ };++ // 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 handleImportBackup = 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;+ setMigrating(true);+ try {+ const res = await infraApi.importData(parsed.tables);+ if (res.imported) toast.success(t('infrastructure.migration.importOk'));+ else toast.error(t('infrastructure.migration.importFailed'), (res.warnings || []).slice(0, 3).join('; ') || res.message);+ } catch (err) {+ toast.error(t('infrastructure.migration.importFailed'), err instanceof Error ? err.message : t('common.unknownError'));+ } finally {+ setMigrating(false);+ }+ };+const handleRestart = async () => {setRestartStatus('restarting');setRestartCountdown(30);@@ -316,6 +413,22 @@ export function Infrastructure() {setTimeout(check, 3000);};+ // A setting whose RUNNING value (/status) differs from the SAVED file (/config) is being pinned by a+ // host/.env environment variable, which wins at runtime — so a dashboard change to it won't apply+ // until that variable is unset. Surface that honestly instead of letting the control look effective.+ const dbPinnedByEnv =+ !savePending && !!infraStatus && !!savedConfig && infraStatus.database.type !== savedConfig.database.type;+ const redisPinnedByEnv =+ !savePending && !!infraStatus && !!savedConfig && infraStatus.redis.enabled !== savedConfig.redis.enabled;+ const storagePinnedByEnv =+ !savePending && !!infraStatus && !!savedConfig && infraStatus.storage.type !== savedConfig.storage.type;+ const envPinNote = (pinned: boolean) =>+ pinned ? (+ <p className="env-pin-note">+ <AlertTriangle size={14} /> {t('infrastructure.envPinNote')}+ </p>+ ) : null;+return (<div className="infrastructure-page"><PageHeader title={t('infrastructure.title')} subtitle={t('infrastructure.subtitle')} />@@ -332,6 +445,7 @@ export function Infrastructure() {● {dbConfig.type === 'postgres' ? 'PostgreSQL' : 'SQLite'}</span></div>+ {envPinNote(dbPinnedByEnv)}<div className="radio-group"><label className={`radio-option ${dbConfig.type === 'sqlite' ? 'selected' : ''}`}>@@ -494,6 +608,35 @@ export function Infrastructure() {{t('infrastructure.database.migrationsHint')}</p></div>++ {/* Data backup / restore — used to carry data across a database switch (#488). */}+ <div className="data-migration-row">+ <div>+ <strong>{t('infrastructure.migration.backupTitle')}</strong>+ <small>{t('infrastructure.migration.backupHint')}</small>+ </div>+ <div className="data-migration-actions">+ <button className="btn-secondary btn-sm" onClick={handleExportBackup} disabled={migrating}>+ {migrating ? <Loader2 size={14} className="animate-spin" /> : <Download size={14} />}+ {t('infrastructure.migration.export')}+ </button>+ <label className="btn-secondary btn-sm" style={{ cursor: migrating ? 'default' : 'pointer' }}>+ <Upload size={14} />+ {t('infrastructure.migration.import')}+ <input+ type="file"+ accept="application/json,.json"+ style={{ display: 'none' }}+ disabled={migrating}+ onChange={e => {+ const file = e.target.files?.[0];+ if (file) void handleImportBackup(file);+ e.target.value = '';+ }}+ />+ </label>+ </div>+ </div></section>{/* Engine */}@@ -526,6 +669,20 @@ export function Infrastructure() {))}</div>+ {/* The actual WhatsApp Web build in use — distinct from the library version above (#488). */}+ {infraStatus?.engine.webVersion !== undefined && (+ <p className="engine-web-version">+ {t('infrastructure.engine.webVersion')}:{' '}+ <code>{infraStatus.engine.webVersion ?? t('infrastructure.engine.webVersionNative')}</code>+ {infraStatus.engine.webVersionSource && (+ <span className="muted">+ {' '}+ ({t(`infrastructure.engine.webVersionSource.${infraStatus.engine.webVersionSource}`)})+ </span>+ )}+ </p>+ )}+{engineConfig.type === 'whatsapp-web.js' ? (<div className="config-form"><div className="toggle-row">@@ -588,6 +745,7 @@ export function Infrastructure() {: t('infrastructure.statusLabels.disabled')}</span></div>+ {envPinNote(redisPinnedByEnv)}<divclassName="toggle-row"@@ -762,7 +920,18 @@ export function Infrastructure() {<HardDrive size={20} /><h2>{t('infrastructure.storage.title')}</h2></div>+ {(() => {+ // S3 selected but the backend isn't reachable → warn instead of a misleading green.+ const s3Unreachable = storageConfig.type === 's3' && infraStatus?.storage.s3Available === false;+ const cls = storageConfig.type !== 's3' ? 'sqlite' : s3Unreachable ? 'disconnected' : 'connected';+ return (+ <span className={`status-indicator ${cls}`}>+ ● {storageConfig.type === 's3' ? (s3Unreachable ? t('infrastructure.storage.s3Unreachable') : 'S3') : 'Local'}+ </span>+ );+ })()}</div>+ {envPinNote(storagePinnedByEnv)}<div className="radio-group"><label className={`radio-option ${storageConfig.type === 'local' ? 'selected' : ''}`}>@@ -891,6 +1060,22 @@ export function Infrastructure() {<p style={{ fontSize: '1rem', color: '#475569', marginBottom: '1.5rem' }}><Trans i18nKey="infrastructure.restart.idleDesc" components={{ code: <code />, br: <br /> }} /></p>+ {(dbSwitch || storageSwitch) && (+ <div className="migration-warning">+ <AlertTriangle size={18} />+ <div>+ <strong>{t('infrastructure.migration.title')}</strong>+ {dbSwitch && <p>{t('infrastructure.migration.dbWarning')}</p>}+ {storageSwitch && <p>{t('infrastructure.migration.storageWarning')}</p>}+ {dbSwitch && (+ <button className="btn-secondary btn-sm" onClick={handleExportBackup} disabled={migrating}>+ {migrating ? <Loader2 size={14} className="animate-spin" /> : <Download size={14} />}+ {t('infrastructure.migration.downloadBackup')}+ </button>+ )}+ </div>+ </div>+ )}<div style={{ display: 'flex', gap: '1rem', justifyContent: 'center' }}><button className="btn-secondary" onClick={() => setShowRestartModal(false)}>{t('infrastructure.restart.later')}diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 713bfa4c3..7a21bdd82 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -204,15 +204,24 @@ export interface HealthStatus {}export interface InfraStatus {- database: { connected: boolean; type: string; host: string };- redis: { connected: boolean; host: string; port: number };+ // `builtIn` = OpenWA's own bundled container is actually running and backing this service (live),+ // not just the saved intent — falls back to the saved flag when Docker is unavailable. (#488)+ database: { connected: boolean; type: string; host: string; builtIn: boolean };+ redis: { enabled: boolean; connected: boolean; host: string; port: number; builtIn: boolean };queue: {enabled: boolean;messages: { pending: number; completed: number; failed: number };webhooks: { pending: number; completed: number; failed: number };};- storage: { type: 'local' | 's3'; path?: string; bucket?: string };- engine: { type: string; headless: boolean };+ storage: { type: 'local' | 's3'; path?: string; bucket?: string; builtIn: boolean; s3Available?: boolean };+ engine: {+ type: string;+ headless: boolean;+ // whatsapp-web.js only: the actual WhatsApp Web build in use (distinct from the library version)+ // and how it was chosen. (#488)+ webVersion?: string | null;+ webVersionSource?: 'pinned' | 'auto' | 'native';+ };}// Saved infrastructure config (from data/.env.generated) used to hydrate the form.@@ -328,7 +337,11 @@ async function request<T>(endpoint: string, options: RequestInit = {}): Promise<// rather than statusText: the status code is what the toast connection-lost de-dup matches on,// and statusText is empty over HTTP/2 anyway.const error = await response.json().catch(() => ({}));- throw new Error(error.message || `HTTP ${response.status}`);+ // Carry the HTTP status on the Error (message unchanged, so the toast de-dup still matches) so+ // callers can tell apart a permission 403 from a real server 5xx instead of guessing from text.+ const err = new Error(error.message || `HTTP ${response.status}`) as Error & { status?: number };+ err.status = response.status;+ throw err;}if (response.status === 204) {@@ -613,6 +626,17 @@ export const infraApi = {body: JSON.stringify({ profiles: profiles || [], profilesToRemove: profilesToRemove || [] }),}),healthCheck: () => request<{ status: string; timestamp: string }>('/infra/health'),+ // Data migration: export all Data-DB tables (call while still on the OLD database, before switching),+ // then import after the switch + restart. Used by the DB-switch migration guard so data isn't lost.+ exportData: () =>+ request<{ exportedAt: string; dataDbType: string; tables: Record<string, unknown[]>; counts: Record<string, number> }>(+ '/infra/export-data',+ ),+ importData: (tables: Record<string, unknown[]>) =>+ request<{ imported: boolean; counts?: Record<string, number>; message?: string; warnings?: string[] }>('/infra/import-data', {+ method: 'POST',+ body: JSON.stringify({ tables }),+ }),};// =============================================================================diff --git a/docker-compose.yml b/docker-compose.ymlindex a613c19b3..8fb8143c3 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -78,14 +78,18 @@ services:- XDG_CACHE_HOME=/tmp/.cache- PORT=2785- LOG_LEVEL=${LOG_LEVEL:-info}- # Database- - DATABASE_TYPE=${DATABASE_TYPE:-sqlite}- - DATABASE_NAME=${DATABASE_NAME:-/app/data/openwa.sqlite}- - DATABASE_HOST=${DATABASE_HOST:-postgres}- - DATABASE_PORT=${DATABASE_PORT:-5432}- - DATABASE_USERNAME=${DATABASE_USERNAME:-openwa}- # No committed default secret. Empty for the default sqlite setup; the- # postgres service requires it (:?) when that profile is active.+ # Database. Forwarded blank by default (`${VAR:-}`) so a dashboard switch saved to+ # data/.env.generated actually applies at runtime — main.ts clears the blank (BLANK_SHADOWED_ENV_KEYS)+ # and the file wins. Set any of these in your .env/host to pin it (a real value keeps top precedence+ # and the dashboard control then shows "managed by environment"). First-run defaults (sqlite) are+ # written to data/.env.generated by the app, so a blank stack still boots SQLite.+ - DATABASE_TYPE=${DATABASE_TYPE:-}+ - DATABASE_NAME=${DATABASE_NAME:-}+ - DATABASE_HOST=${DATABASE_HOST:-}+ - DATABASE_PORT=${DATABASE_PORT:-}+ - DATABASE_USERNAME=${DATABASE_USERNAME:-}+ # No committed default secret; blank unless the operator sets it (built-in Postgres is provisioned+ # with its own credentials by the orchestrator, not via this line).- DATABASE_PASSWORD=${DATABASE_PASSWORD:-}- DATABASE_SYNCHRONIZE=${DATABASE_SYNCHRONIZE:-false}# Engine. Forwarded empty by default so the dashboard (Infrastructure > Engine) selects the@@ -105,17 +109,22 @@ services:# low-resource hosts where the QR can time out before WA Web loads. Empty = default; see# docs/12-troubleshooting-faq.md. (Without this line the var in .env never reaches the container.)- WWEBJS_AUTH_TIMEOUT_MS=${WWEBJS_AUTH_TIMEOUT_MS:-}- # Storage- - STORAGE_TYPE=${STORAGE_TYPE:-local}- - STORAGE_LOCAL_PATH=${STORAGE_LOCAL_PATH:-/app/data/media}- - S3_ENDPOINT=${S3_ENDPOINT:-http://minio:9000}- - S3_ACCESS_KEY=${S3_ACCESS_KEY:-}- - S3_SECRET_KEY=${S3_SECRET_KEY:-}- - S3_BUCKET=${S3_BUCKET:-openwa}- # Redis- - REDIS_ENABLED=${REDIS_ENABLED:-false}- - REDIS_HOST=${REDIS_HOST:-redis}- - REDIS_PORT=${REDIS_PORT:-6379}+ # Storage. Blank-forwarded (see Database note) so a dashboard local↔S3 switch applies; a real+ # host value pins. Credentials use the canonical S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY names+ # the app and dashboard read (the legacy S3_ACCESS_KEY / S3_SECRET_KEY are still honored as a+ # fallback by the storage layer for older setups). S3_REGION is forwarded so external-S3 works.+ - STORAGE_TYPE=${STORAGE_TYPE:-}+ - STORAGE_LOCAL_PATH=${STORAGE_LOCAL_PATH:-}+ - S3_ENDPOINT=${S3_ENDPOINT:-}+ - S3_ACCESS_KEY_ID=${S3_ACCESS_KEY_ID:-}+ - S3_SECRET_ACCESS_KEY=${S3_SECRET_ACCESS_KEY:-}+ - S3_REGION=${S3_REGION:-}+ - S3_BUCKET=${S3_BUCKET:-}+ # Redis. Blank-forwarded (see Database note) so a dashboard enable/disable applies; a real host+ # value pins.+ - REDIS_ENABLED=${REDIS_ENABLED:-}+ - REDIS_HOST=${REDIS_HOST:-}+ - REDIS_PORT=${REDIS_PORT:-}# Webhook- WEBHOOK_TIMEOUT=${WEBHOOK_TIMEOUT:-10000}- WEBHOOK_MAX_RETRIES=${WEBHOOK_MAX_RETRIES:-3}@@ -226,8 +235,10 @@ services:environment:# M16: no committed default creds. MinIO refuses to start with empty root creds# (clear fail-fast); the app's production boot guard rejects empty/placeholder secrets.- MINIO_ROOT_USER: ${S3_ACCESS_KEY:-}- MINIO_ROOT_PASSWORD: ${S3_SECRET_KEY:-}+ # Canonical names, matching what the app/dashboard read (legacy S3_ACCESS_KEY/S3_SECRET_KEY+ # still accepted as a fallback so older .env files keep working).+ MINIO_ROOT_USER: ${S3_ACCESS_KEY_ID:-${S3_ACCESS_KEY:-}}+ MINIO_ROOT_PASSWORD: ${S3_SECRET_ACCESS_KEY:-${S3_SECRET_KEY:-}}volumes:- minio-data:/dataports:@@ -243,13 +254,20 @@ services:- 'com.openwa.builtin=true'volumes:+ # Pin explicit volume names so the compose path and the Docker-API orchestration path (which uses+ # the literal `openwa_<svc>-data` names in docker.service.ts) bind the SAME volume regardless of the+ # compose project name — otherwise re-enabling a built-in service could mount a fresh empty volume.openwa-data:+ name: openwa_openwa-datadriver: localpostgres-data:+ name: openwa_postgres-datadriver: localredis-data:+ name: openwa_redis-datadriver: localminio-data:+ name: openwa_minio-datadriver: localnetworks:diff --git a/src/config/bootstrap-security.spec.ts b/src/config/bootstrap-security.spec.tsindex 745ae6353..cc41d0386 100644--- a/src/config/bootstrap-security.spec.ts+++ b/src/config/bootstrap-security.spec.ts@@ -103,6 +103,34 @@ describe('assertNoDefaultSecretsInProduction', () => {).toThrow(/DATABASE_PASSWORD/);});+ it('allows the built-in Postgres/MinIO default credentials in prod (internal-only network) (#488 review)', () => {+ // The bundled containers are reachable only on the internal Docker network (not published), so the+ // known 'openwa'/'minioadmin' creds the built-in flow provisions must not crash-loop a prod boot.+ expect(() =>+ assertNoDefaultSecretsInProduction({+ nodeEnv: 'production',+ databaseType: 'postgres',+ databasePassword: 'openwa',+ postgresBuiltIn: 'true',+ storageType: 's3',+ s3AccessKey: 'minioadmin',+ s3SecretKey: 'minioadmin',+ minioBuiltIn: 'true',+ }),+ ).not.toThrow();+ });++ it('still refuses an EXTERNAL Postgres with a default password even when MinIO is built-in', () => {+ expect(() =>+ assertNoDefaultSecretsInProduction({+ nodeEnv: 'production',+ databaseType: 'postgres',+ databasePassword: 'openwa',+ postgresBuiltIn: 'false',+ }),+ ).toThrow(/DATABASE_PASSWORD/);+ });+it('refuses prod with default MinIO/S3 credentials', () => {expect(() =>assertNoDefaultSecretsInProduction({diff --git a/src/config/bootstrap-security.ts b/src/config/bootstrap-security.tsindex b1600797d..13214d0dd 100644--- a/src/config/bootstrap-security.ts+++ b/src/config/bootstrap-security.ts@@ -82,9 +82,13 @@ export interface SecretCheckEnv {nodeEnv?: string;databaseType?: string;databasePassword?: string;+ /** POSTGRES_BUILTIN — when 'true', OpenWA runs the bundled Postgres on the internal-only network. */+ postgresBuiltIn?: string;storageType?: string;s3AccessKey?: string;s3SecretKey?: string;+ /** MINIO_BUILTIN — when 'true', OpenWA runs the bundled MinIO on the internal-only network. */+ minioBuiltIn?: string;apiMasterKey?: string;/** ALLOW_DEV_API_KEY — when 'true' it seeds the well-known public `dev-admin-key` as an ADMIN credential. */allowDevApiKey?: string;@@ -104,10 +108,13 @@ export function assertNoDefaultSecretsInProduction(env: SecretCheckEnv): void {const isWeak = (value?: string): boolean => !value || FORBIDDEN_PROD_SECRETS.has(value.trim().toLowerCase());const problems: string[] = [];- if (env.databaseType === 'postgres' && isWeak(env.databasePassword)) {+ // Built-in datastores run on the internal-only Docker network (not published), so their fixed+ // 'openwa'/'minioadmin' credentials are not internet-reachable — exempt them so selecting the+ // built-in option doesn't crash-loop a production boot. External datastores are still enforced.+ if (env.databaseType === 'postgres' && env.postgresBuiltIn !== 'true' && isWeak(env.databasePassword)) {problems.push('DATABASE_PASSWORD');}- if (env.storageType === 's3') {+ if (env.storageType === 's3' && env.minioBuiltIn !== 'true') {if (isWeak(env.s3AccessKey)) problems.push('S3_ACCESS_KEY');if (isWeak(env.s3SecretKey)) problems.push('S3_SECRET_KEY');}diff --git a/src/config/env-precedence.spec.ts b/src/config/env-precedence.spec.tsindex 00c04376b..427145d79 100644--- a/src/config/env-precedence.spec.ts+++ b/src/config/env-precedence.spec.ts@@ -81,6 +81,58 @@ describe('blank-shadowed env keys (compose ${VAR:-} forwards the dashboard managexpect(BLANK_SHADOWED_ENV_KEYS).toContain('DATABASE_PASSWORD');});+ it('covers every dashboard-switchable infra key so a blank compose forward lets .env.generated win (#488)', () => {+ // Database / storage / redis selection + their detail fields. With these blank-forwarded by+ // compose, a dashboard switch saved to .env.generated actually applies at runtime (like ENGINE_TYPE),+ // while a real host value still pins.+ for (const key of [+ 'DATABASE_TYPE',+ 'DATABASE_HOST',+ 'DATABASE_PORT',+ 'DATABASE_USERNAME',+ 'DATABASE_NAME',+ 'STORAGE_TYPE',+ 'STORAGE_LOCAL_PATH',+ 'S3_BUCKET',+ 'S3_ENDPOINT',+ 'S3_REGION',+ 'S3_ACCESS_KEY_ID',+ 'S3_SECRET_ACCESS_KEY',+ 'REDIS_ENABLED',+ 'REDIS_HOST',+ 'REDIS_PORT',+ ]) {+ expect(BLANK_SHADOWED_ENV_KEYS).toContain(key);+ }+ });++ it.each([+ ['DATABASE_TYPE', 'postgres'],+ ['STORAGE_TYPE', 's3'],+ ['REDIS_ENABLED', 'true'],+ ])('lets .env.generated supply %s when the forwarded value is blank, but a host value pins', (key, fileValue) => {+ const prev = process.env[key];+ try {+ withGenerated(`${key}=${fileValue}`, genPath => {+ // blank forward (operator set nothing) → cleared → file wins+ process.env[key] = '';+ clearBlankEnv(process.env, BLANK_SHADOWED_ENV_KEYS);+ dotenv.config({ path: genPath, override: false });+ expect(process.env[key]).toBe(fileValue);+ });+ // real host value → survives → pins (ignores the file)+ withGenerated(`${key}=${fileValue}`, genPath => {+ process.env[key] = 'host-pinned';+ clearBlankEnv(process.env, BLANK_SHADOWED_ENV_KEYS);+ dotenv.config({ path: genPath, override: false });+ expect(process.env[key]).toBe('host-pinned');+ });+ } finally {+ if (prev === undefined) delete process.env[key];+ else process.env[key] = prev;+ }+ });+it('lets .env.generated supply the password when the forwarded DATABASE_PASSWORD is blank', () => {withGenerated('DATABASE_PASSWORD=s3cret', genPath => {process.env[KEY] = ''; // compose `${DATABASE_PASSWORD:-}` with nothing set on the hostdiff --git a/src/config/env-precedence.ts b/src/config/env-precedence.tsindex bd5345c17..27d2bae48 100644--- a/src/config/env-precedence.ts+++ b/src/config/env-precedence.ts@@ -12,10 +12,33 @@/*** Keys the bundled compose forwards with `- KEY=${KEY:-}` (rendering blank when unset) AND the* dashboard saves to `data/.env.generated`. A blank forward of one of these would shadow the- * dashboard's value, so each is cleared when blank. Only add a key that meets BOTH conditions —- * `REDIS_PASSWORD`/`S3_*` are dashboard-managed but not blank-forwarded by compose, so they don't belong.+ * dashboard's value, so each is cleared when blank — letting a dashboard switch (database, storage,+ * redis, engine) actually apply at runtime while a real host value still pins. Only add a key that+ * meets BOTH conditions (blank-forwarded by compose AND dashboard-managed); keep this list in sync+ * with the `${KEY:-}` forwards in docker-compose.yml.*/-export const BLANK_SHADOWED_ENV_KEYS: string[] = ['ENGINE_TYPE', 'DATABASE_PASSWORD'];+export const BLANK_SHADOWED_ENV_KEYS: string[] = [+ 'ENGINE_TYPE',+ // Database selection + connection details (#488)+ 'DATABASE_TYPE',+ 'DATABASE_HOST',+ 'DATABASE_PORT',+ 'DATABASE_USERNAME',+ 'DATABASE_NAME',+ 'DATABASE_PASSWORD',+ // Storage selection + S3 details (#488)+ 'STORAGE_TYPE',+ 'STORAGE_LOCAL_PATH',+ 'S3_BUCKET',+ 'S3_ENDPOINT',+ 'S3_REGION',+ 'S3_ACCESS_KEY_ID',+ 'S3_SECRET_ACCESS_KEY',+ // Redis selection + connection details (#488)+ 'REDIS_ENABLED',+ 'REDIS_HOST',+ 'REDIS_PORT',+];export function clearBlankEnv(env: NodeJS.ProcessEnv, keys: string[]): void {for (const key of keys) {diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 31211e69c..46ad57f1b 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -7,9 +7,9 @@ import {isSupportedProxyUrl,loadRemoteMedia,resolveAuthTimeoutMs,- resolveWebVersionPin,wwebjsAckToDeliveryStatus,} from './whatsapp-web-js.adapter';+import { getEffectiveWebVersionInfo, resolveWebVersionPin, __resetWebVersionCache } from '../wa-web-version';import * as fs from 'fs';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { EngineStatus } from '../interfaces/whatsapp-engine.interface';@@ -619,28 +619,27 @@ describe('WhatsAppWebJsAdapter.resolveContactPhone (@lid -> phone, #263)', () =>});});-describe('resolveWebVersionPin (#251 — opt-in WA-Web version pin)', () => {+describe('resolveWebVersionPin (#251/#488 — explicit pin + auto-resolve current WA-Web build)', () => {const orig = { v: process.env.WWEBJS_WEB_VERSION, p: process.env.WWEBJS_WEB_VERSION_REMOTE_PATH };+ const fetcherFor = (currentVersion: unknown, ok = true) =>+ jest.fn(() =>+ Promise.resolve({ ok, status: ok ? 200 : 500, json: () => Promise.resolve({ currentVersion }) }),+ ) as unknown as typeof fetch;++ beforeEach(() => __resetWebVersionCache());afterEach(() => {+ __resetWebVersionCache();if (orig.v === undefined) delete process.env.WWEBJS_WEB_VERSION;else process.env.WWEBJS_WEB_VERSION = orig.v;if (orig.p === undefined) delete process.env.WWEBJS_WEB_VERSION_REMOTE_PATH;else process.env.WWEBJS_WEB_VERSION_REMOTE_PATH = orig.p;});- it('returns undefined (default auto-version) when unset / "latest" / "off" / "auto"', () => {- delete process.env.WWEBJS_WEB_VERSION;- expect(resolveWebVersionPin()).toBeUndefined();- for (const value of ['latest', 'off', 'auto']) {- process.env.WWEBJS_WEB_VERSION = value;- expect(resolveWebVersionPin()).toBeUndefined();- }- });-- it('pins a remote webVersionCache from the version when set', () => {+ it('pins the explicit version without any network call when set', async () => {delete process.env.WWEBJS_WEB_VERSION_REMOTE_PATH;process.env.WWEBJS_WEB_VERSION = '2.3000.1041203030-alpha';- expect(resolveWebVersionPin()).toEqual({+ const fetcher = fetcherFor('SHOULD-NOT-BE-USED');+ expect(await resolveWebVersionPin(fetcher)).toEqual({webVersion: '2.3000.1041203030-alpha',webVersionCache: {type: 'remote',@@ -648,12 +647,95 @@ describe('resolveWebVersionPin (#251 — opt-in WA-Web version pin)', () => {'https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/2.3000.1041203030-alpha.html',},});+ expect(fetcher).not.toHaveBeenCalled();});- it('honors a custom WWEBJS_WEB_VERSION_REMOTE_PATH template ({version} placeholder)', () => {+ it('honors a custom WWEBJS_WEB_VERSION_REMOTE_PATH template ({version} placeholder)', async () => {process.env.WWEBJS_WEB_VERSION = '2.9999.0';process.env.WWEBJS_WEB_VERSION_REMOTE_PATH = 'https://cdn.example.com/wa/{version}.html';- expect(resolveWebVersionPin()?.webVersionCache.remotePath).toBe('https://cdn.example.com/wa/2.9999.0.html');+ expect((await resolveWebVersionPin(fetcherFor('x')))?.webVersionCache.remotePath).toBe(+ 'https://cdn.example.com/wa/2.9999.0.html',+ );+ });++ it('"off" disables pinning (native whatsapp-web.js auto-select) with no network call', async () => {+ process.env.WWEBJS_WEB_VERSION = 'off';+ const fetcher = fetcherFor('x');+ expect(await resolveWebVersionPin(fetcher)).toBeUndefined();+ expect(fetcher).not.toHaveBeenCalled();+ });++ it.each(['', 'auto', 'latest'])(+ 'auto-resolves the current wa-version build when WWEBJS_WEB_VERSION=%p (the #488 fix)',+ async value => {+ if (value === '') delete process.env.WWEBJS_WEB_VERSION;+ else process.env.WWEBJS_WEB_VERSION = value;+ const pin = await resolveWebVersionPin(fetcherFor('2.3000.1042251103-alpha'));+ expect(pin?.webVersion).toBe('2.3000.1042251103-alpha');+ expect(pin?.webVersionCache.remotePath).toContain('2.3000.1042251103-alpha.html');+ },+ );++ it('falls back to native auto-select (undefined) when the wa-version fetch fails', async () => {+ delete process.env.WWEBJS_WEB_VERSION;+ expect(await resolveWebVersionPin(fetcherFor(null, false))).toBeUndefined();+ });++ it('caches the resolved current version (fetches once across calls)', async () => {+ delete process.env.WWEBJS_WEB_VERSION;+ const fetcher = fetcherFor('2.3000.1042251103-alpha');+ await resolveWebVersionPin(fetcher);+ await resolveWebVersionPin(fetcher);+ expect(fetcher).toHaveBeenCalledTimes(1);+ });++ it('does NOT cache a transient failure — a later call retries and resolves (#488 review must-fix)', async () => {+ delete process.env.WWEBJS_WEB_VERSION;+ expect(await resolveWebVersionPin(fetcherFor(null, false))).toBeUndefined(); // transient failure, not cached+ const ok = fetcherFor('2.3000.1042251103-alpha');+ const pin = await resolveWebVersionPin(ok); // retries+ expect(pin?.webVersion).toBe('2.3000.1042251103-alpha');+ expect(ok).toHaveBeenCalledTimes(1);+ });++ it('dedupes concurrent in-flight resolves into a single fetch', async () => {+ delete process.env.WWEBJS_WEB_VERSION;+ const fetcher = fetcherFor('2.3000.1042251103-alpha');+ const [a, b] = await Promise.all([resolveWebVersionPin(fetcher), resolveWebVersionPin(fetcher)]);+ expect(a?.webVersion).toBe('2.3000.1042251103-alpha');+ expect(b?.webVersion).toBe('2.3000.1042251103-alpha');+ expect(fetcher).toHaveBeenCalledTimes(1);+ });+});++describe('getEffectiveWebVersionInfo (#488 — surface the running WA-Web build to the dashboard)', () => {+ const orig = process.env.WWEBJS_WEB_VERSION;+ beforeEach(() => __resetWebVersionCache());+ afterEach(() => {+ __resetWebVersionCache();+ if (orig === undefined) delete process.env.WWEBJS_WEB_VERSION;+ else process.env.WWEBJS_WEB_VERSION = orig;+ });++ it('reports an explicitly pinned env version', () => {+ process.env.WWEBJS_WEB_VERSION = '2.3000.1041203030-alpha';+ expect(getEffectiveWebVersionInfo()).toEqual({ version: '2.3000.1041203030-alpha', source: 'pinned' });+ });++ it('reports native auto-select for "off"', () => {+ process.env.WWEBJS_WEB_VERSION = 'off';+ expect(getEffectiveWebVersionInfo()).toEqual({ version: null, source: 'native' });+ });++ it('reports the auto-resolved current build once resolution has run', async () => {+ delete process.env.WWEBJS_WEB_VERSION;+ expect(getEffectiveWebVersionInfo()).toEqual({ version: null, source: 'auto' });+ await resolveWebVersionPin(+ jest.fn(() =>+ Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ currentVersion: '2.3000.9-alpha' }) }),+ ) as never,+ );+ expect(getEffectiveWebVersionInfo()).toEqual({ version: '2.3000.9-alpha', source: 'auto' });});});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 93d5ca9f8..091f5e1a3 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -33,6 +33,7 @@ import {RevokedMessage,ReactionEvent,} from '../interfaces/whatsapp-engine.interface';+import { resolveWebVersionPin } from '../wa-web-version';import { createLogger } from '../../common/services/logger.service';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';@@ -125,28 +126,9 @@ export interface WhatsAppWebJsConfig {const READY_RECONCILE_INTERVAL_MS = 2000;const READY_RECONCILE_TIMEOUT_MS = 90_000;-/**- * Optional pin for the WhatsApp Web client version. whatsapp-web.js 1.34.x can get stuck at- * "authenticating" when the auto-fetched WA-Web version is incompatible (#251/#273). Set- * WWEBJS_WEB_VERSION to a known-good version string to pin it; WWEBJS_WEB_VERSION_REMOTE_PATH- * overrides the URL template (use `{version}` as the placeholder) if you self-host the HTML.- * Unset (or `latest`/`off`/`auto`) keeps whatsapp-web.js's default auto-version behavior.- */-export function resolveWebVersionPin():- | { webVersion: string; webVersionCache: { type: 'remote'; remotePath: string } }- | undefined {- const version = process.env.WWEBJS_WEB_VERSION?.trim();- if (!version || ['off', 'latest', 'auto'].includes(version.toLowerCase())) {- return undefined;- }- const template =- process.env.WWEBJS_WEB_VERSION_REMOTE_PATH?.trim() ||- 'https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/{version}.html';- return {- webVersion: version,- webVersionCache: { type: 'remote', remotePath: template.replace('{version}', version) },- };-}+// WhatsApp Web version resolution (the #488 auto-resolve) lives in a dependency-free module so infra+// status can import it without loading whatsapp-web.js (engine lazy-loading). The adapter imports+// resolveWebVersionPin above for use in initialize()./*** Optional override for whatsapp-web.js's initial boot/inject wait (#353). On slow first boots@@ -281,7 +263,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// Pin the WA-Web version when configured (fixes the 1.34.x "stuck at authenticating"// hang on some setups, #251). Opt-in: unset leaves whatsapp-web.js to auto-select.- const versionPin = resolveWebVersionPin();+ const versionPin = await resolveWebVersionPin();if (versionPin) {this.logger.log(`Pinning WhatsApp Web version ${versionPin.webVersion}`);}diff --git a/src/engine/wa-web-version.ts b/src/engine/wa-web-version.tsnew file mode 100644index 000000000..a3dec4e37--- /dev/null+++ b/src/engine/wa-web-version.ts@@ -0,0 +1,105 @@+/**+ * WhatsApp Web build resolution for the whatsapp-web.js engine — kept dependency-free (process.env ++ * fetch only) so the infra status endpoint can import it without pulling in the heavy whatsapp-web.js+ * module and breaking engine lazy-loading.+ */++export type WebVersionPin = { webVersion: string; webVersionCache: { type: 'remote'; remotePath: string } };++// The wppconnect-team/wa-version registry tracks the current known-good WhatsApp Web build. Its+// `currentVersion` is what we pin to when the operator hasn't chosen one — far more reliable than+// whatsapp-web.js's own auto-select, which can latch onto a bleeding-edge build that authenticates+// then never reaches "ready" and disconnect-loops (#488).+export const WA_VERSION_REGISTRY_URL =+ 'https://raw.githubusercontent.com/wppconnect-team/wa-version/main/versions.json';++const DEFAULT_REMOTE_TEMPLATE = 'https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/{version}.html';++// Module-level cache: undefined = not yet resolved, string = the resolved current build. A failed+// fetch is deliberately NOT cached, so a transient outage doesn't permanently defeat the #488 fix —+// the next call retries. `inFlight` dedupes concurrent first-boot resolves into a single fetch.+let cachedCurrentVersion: string | undefined;+let inFlight: Promise<string | null> | null = null;++/** Test-only: reset the resolved-version cache between cases. */+export function __resetWebVersionCache(): void {+ cachedCurrentVersion = undefined;+ inFlight = null;+}++function buildRemotePin(version: string): WebVersionPin {+ const template = process.env.WWEBJS_WEB_VERSION_REMOTE_PATH?.trim() || DEFAULT_REMOTE_TEMPLATE;+ return {+ webVersion: version,+ webVersionCache: { type: 'remote', remotePath: template.replace('{version}', version) },+ };+}++/**+ * Fetch the current known-good WhatsApp Web build from the wa-version registry. A SUCCESSFUL resolve+ * is cached for the process lifetime; a failure resolves to null WITHOUT caching, so a later call+ * retries (a single transient outage must not permanently defeat the #488 fix). Concurrent callers+ * share one in-flight fetch.+ */+export async function resolveCurrentWebVersion(fetcher: typeof fetch = fetch): Promise<string | null> {+ if (typeof cachedCurrentVersion === 'string') return cachedCurrentVersion;+ if (inFlight) return inFlight;+ inFlight = (async (): Promise<string | null> => {+ try {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), 5000);+ try {+ const res = await fetcher(WA_VERSION_REGISTRY_URL, { signal: controller.signal });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const json = (await res.json()) as { currentVersion?: unknown };+ const v = json.currentVersion;+ if (typeof v === 'string' && /^\d/.test(v)) {+ cachedCurrentVersion = v; // cache only on success+ return v;+ }+ return null; // malformed payload — don't cache, retry next time+ } finally {+ clearTimeout(timer);+ }+ } catch {+ return null; // fetch failed — don't cache, retry next time+ } finally {+ inFlight = null;+ }+ })();+ return inFlight;+}++/**+ * Resolve the WhatsApp Web version pin for the whatsapp-web.js client.+ * - Explicit `WWEBJS_WEB_VERSION` (a version string) → pin it exactly (no network call).+ * - `off` → no pin; whatsapp-web.js native auto-select.+ * - unset / `auto` / `latest` → auto-resolve the current known-good build+ * from the wa-version registry and pin it; if that fetch fails, fall back to native auto-select.+ * `WWEBJS_WEB_VERSION_REMOTE_PATH` overrides the HTML URL template (`{version}` placeholder).+ * The auto-resolve replaces whatsapp-web.js's unreliable default that caused #488 (scan → stuck →+ * disconnect loop) on Docker setups where no version was pinned.+ */+export async function resolveWebVersionPin(fetcher: typeof fetch = fetch): Promise<WebVersionPin | undefined> {+ const raw = process.env.WWEBJS_WEB_VERSION?.trim();+ const lc = raw?.toLowerCase();+ if (raw && lc !== 'off' && lc !== 'latest' && lc !== 'auto') {+ return buildRemotePin(raw); // operator-pinned exact version+ }+ if (lc === 'off') return undefined; // explicit escape hatch → native auto-select+ const current = await resolveCurrentWebVersion(fetcher);+ return current ? buildRemotePin(current) : undefined;+}++/**+ * The WhatsApp Web build the engine is effectively using, for the dashboard to display (#488). This+ * is distinct from the whatsapp-web.js library version. `source`: `pinned` = operator-set exact+ * version; `auto` = resolved from the wa-version registry; `native` = whatsapp-web.js auto-select.+ */+export function getEffectiveWebVersionInfo(): { version: string | null; source: 'pinned' | 'auto' | 'native' } {+ const raw = process.env.WWEBJS_WEB_VERSION?.trim();+ const lc = raw?.toLowerCase();+ if (raw && lc !== 'off' && lc !== 'latest' && lc !== 'auto') return { version: raw, source: 'pinned' };+ if (lc === 'off') return { version: null, source: 'native' };+ return { version: cachedCurrentVersion ?? null, source: 'auto' };+}diff --git a/src/main.ts b/src/main.tsindex fa7dfa049..35b5fca3c 100644--- a/src/main.ts+++ b/src/main.ts@@ -118,7 +118,9 @@ async function bootstrap() {nodeEnv: process.env.NODE_ENV,databaseType: process.env.DATABASE_TYPE,databasePassword: process.env.DATABASE_PASSWORD,+ postgresBuiltIn: process.env.POSTGRES_BUILTIN,storageType: process.env.STORAGE_TYPE,+ minioBuiltIn: process.env.MINIO_BUILTIN,// Mirror storage.service's canonical-with-legacy fallback so the guard inspects the var the app// actually uses (it reads S3_ACCESS_KEY_ID/S3_SECRET_ACCESS_KEY first).s3AccessKey: process.env.S3_ACCESS_KEY_ID || process.env.S3_ACCESS_KEY,diff --git a/src/modules/docker/docker.service.spec.ts b/src/modules/docker/docker.service.spec.tsindex 126bb4ee3..08896d9ff 100644--- a/src/modules/docker/docker.service.spec.ts+++ b/src/modules/docker/docker.service.spec.ts@@ -3,6 +3,34 @@ import { DockerService } from './docker.service';// Prevent actual Docker connections on module init during testsjest.mock('dockerode');+describe('DockerService.getRunningBuiltinServices', () => {+ const container = (name: string, service: string, state: string) => ({+ id: name,+ name,+ state,+ status: state,+ labels: { 'com.openwa.service': service, 'com.openwa.builtin': 'true' },+ });++ it('reports a service built-in only when its labeled container is actually running', async () => {+ const service = new DockerService();+ jest+ .spyOn(service, 'listContainers')+ .mockResolvedValue([+ container('openwa-postgres', 'database', 'running'),+ container('openwa-redis', 'cache', 'exited'),+ ]);++ expect(await service.getRunningBuiltinServices()).toEqual({ database: true, cache: false, storage: false });+ });++ it('reports all false when no bundled containers are present (e.g. Docker unavailable)', async () => {+ const service = new DockerService();+ jest.spyOn(service, 'listContainers').mockResolvedValue([]);+ expect(await service.getRunningBuiltinServices()).toEqual({ database: false, cache: false, storage: false });+ });+});+describe('DockerService.buildDockerOptions', () => {let service: DockerService;const originalDockerHost = process.env.DOCKER_HOST;diff --git a/src/modules/docker/docker.service.ts b/src/modules/docker/docker.service.tsindex 9989c4776..a322912d2 100644--- a/src/modules/docker/docker.service.ts+++ b/src/modules/docker/docker.service.ts@@ -146,6 +146,21 @@ export class DockerService implements OnModuleInit {}}+ /**+ * Which bundled (OpenWA-managed) service containers are currently RUNNING, keyed by the+ * `com.openwa.service` label (`database` | `cache` | `storage`). Lets the dashboard show the real+ * built-in state instead of the saved intent. All false when Docker is unavailable or none run.+ */+ async getRunningBuiltinServices(): Promise<{ database: boolean; cache: boolean; storage: boolean }> {+ const containers = await this.listContainers();+ const isRunning = (svc: string): boolean =>+ containers.some(+ c =>+ c.labels['com.openwa.service'] === svc && c.labels['com.openwa.builtin'] === 'true' && c.state === 'running',+ );+ return { database: isRunning('database'), cache: isRunning('cache'), storage: isRunning('storage') };+ }+/*** Get container by service name or label*/@@ -238,8 +253,10 @@ export class DockerService implements OnModuleInit {alias: 'minio',cmd: ['server', '/data', '--console-address', ':9001'],env: [- `MINIO_ROOT_USER=${process.env.S3_ACCESS_KEY || 'minioadmin'}`,- `MINIO_ROOT_PASSWORD=${process.env.S3_SECRET_KEY || 'minioadmin'}`,+ // Prefer the canonical names the app/dashboard use; fall back to the legacy ones, then the+ // built-in default, so the bundled MinIO and the app share credentials.+ `MINIO_ROOT_USER=${process.env.S3_ACCESS_KEY_ID || process.env.S3_ACCESS_KEY || 'minioadmin'}`,+ `MINIO_ROOT_PASSWORD=${process.env.S3_SECRET_ACCESS_KEY || process.env.S3_SECRET_KEY || 'minioadmin'}`,],volumes: [{ name: 'openwa_minio-data', path: '/data' }],ports: [diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 81935681f..a69a5d9bf 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -457,6 +457,31 @@ describe('InfraController.importData round-trips export-data (no silent message/expect((await ds.getRepository(Message).findOneByOrFail({ id: 'm1' })).body).toBe('keep me');expect(await ds.getRepository(Session).findOneBy({ id: 's2' })).toBeNull();});++ it('refuses an empty/garbage backup — does not wipe existing data (#488 review must-fix)', async () => {+ await seedSession('s1');+ await ds.getRepository(Message).save(+ ds.getRepository(Message).create({+ id: 'm1',+ sessionId: 's1',+ chatId: 'c1',+ from: 'a',+ to: 'b',+ body: 'keep me',+ type: 'text',+ direction: MessageDirection.INCOMING,+ status: MessageStatus.DELIVERED,+ }),+ );++ // A wrong/empty file (no rows to restore) must NOT commit the all-rows DELETE and report success.+ const res = await controller.importData({ tables: {} });++ expect(res.imported).toBe(false);+ expect(res.warnings.length).toBeGreaterThan(0);+ expect(await ds.getRepository(Session).count()).toBe(1);+ expect(await ds.getRepository(Message).count()).toBe(1);+ });});describe('InfraController.import/export preserves every data-DB table', () => {@@ -627,11 +652,11 @@ describe('InfraController.getStatus engine (F7 — reads the real engine.puppeteconfig as never,ds as never,ds as never,- {} as never,- {} as never,+ {} as never, // engineFactory+ { isDockerAvailable: () => false } as never, // dockerService — no Docker in unit testscache as never,- {} as never,- {} as never,+ { isS3Available: () => false } as never, // storageService+ {} as never, // shutdownService);const status = await controller.getStatus();@@ -650,11 +675,11 @@ describe('InfraController.getStatus storage (reads the real storage.localPath keconfig as never,ds as never,ds as never,- {} as never,- {} as never,+ {} as never, // engineFactory+ { isDockerAvailable: () => false } as never, // dockerService — no Docker in unit testscache as never,- {} as never,- {} as never,+ { isS3Available: () => false } as never, // storageService+ {} as never, // shutdownService);};diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex b4fd88d3c..50256ef60 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -8,6 +8,7 @@ import { ApiKeyRole } from '../auth/entities/api-key.entity';import { isPathWithin } from '../../common/utils/path-safety';import { writeSecretFile } from '../../common/utils/secret-file';import { EngineFactory } from '../../engine/engine.factory';+import { getEffectiveWebVersionInfo, resolveCurrentWebVersion } from '../../engine/wa-web-version';import { DockerService } from '../docker';import { CacheService } from '../../common/cache/cache.service';import { StorageService } from '../../common/storage/storage.service';@@ -19,15 +20,27 @@ import { randomUUID } from 'crypto';import * as dotenv from 'dotenv';interface InfraStatus {- database: { connected: boolean; type: string; host: string };- redis: { enabled: boolean; connected: boolean; host: string; port: number };+ // `builtIn` reflects whether OpenWA's own bundled container is actually running and backing this+ // service (detected live from the labeled container), not merely the saved intent. Falls back to the+ // saved flag when Docker is unavailable. (#488)+ database: { connected: boolean; type: string; host: string; builtIn: boolean };+ redis: { enabled: boolean; connected: boolean; host: string; port: number; builtIn: boolean };queue: {enabled: boolean;messages: { pending: number; completed: number; failed: number };webhooks: { pending: number; completed: number; failed: number };};- storage: { type: 'local' | 's3'; path?: string; bucket?: string };- engine: { type: string; headless: boolean; sessionDataPath: string; browserArgs: string };+ storage: { type: 'local' | 's3'; path?: string; bucket?: string; builtIn: boolean; s3Available?: boolean };+ engine: {+ type: string;+ headless: boolean;+ sessionDataPath: string;+ browserArgs: string;+ // whatsapp-web.js only: the actual WhatsApp Web build in use (distinct from the library version),+ // and how it was chosen. Omitted for other engines (e.g. baileys). (#488)+ webVersion?: string | null;+ webVersionSource?: 'pinned' | 'auto' | 'native';+ };}interface SaveConfigDto {@@ -256,6 +269,19 @@ export class InfraController {const storageBucket = this.configService.get<string>('storage.s3.bucket');const engineType = this.configService.get<string>('engine.type', 'whatsapp-web.js');+ // whatsapp-web.js only: surface the actual WhatsApp Web build (not the library version) so the+ // dashboard shows which build is running. Trigger the auto-resolve so the panel is populated even+ // before a session starts; the result is cached, so this is a one-time fetch. (#488)+ let webVersion: string | null | undefined;+ let webVersionSource: 'pinned' | 'auto' | 'native' | undefined;+ if (engineType === 'whatsapp-web.js') {+ if (getEffectiveWebVersionInfo().source === 'auto') {+ await resolveCurrentWebVersion().catch(() => undefined);+ }+ const info = getEffectiveWebVersionInfo();+ webVersion = info.version;+ webVersionSource = info.source;+ }// configuration.ts nests these under engine.puppeteer.{headless,args}; the old flat// engine.headless / engine.browserArgs keys never existed, so status always reported defaults.const engineHeadless = this.configService.get<boolean>('engine.puppeteer.headless', true) ?? true;@@ -263,9 +289,29 @@ export class InfraController {const browserArgs =this.configService.get<string[]>('engine.puppeteer.args')?.join(' ') || '--no-sandbox --disable-gpu';+ // Built-in detection: prefer the actually-running bundled container as truth (so a stopped/missing+ // container, or a host-pinned external host, reads as NOT built-in), and require the app to be+ // pointed at the bundled service. Fall back to the saved *_BUILTIN intent when Docker is+ // unreachable (bare-npm / socket-less) so the toggles don't spuriously flip off. (#488)+ const s3Endpoint = this.configService.get<string>('storage.s3.endpoint');+ const running = this.dockerService.isDockerAvailable()+ ? await this.dockerService.getRunningBuiltinServices()+ : null;+ const savedBuiltin = this.readSavedBuiltinFlags();+ const dbBuiltIn = running ? running.database && dbHost === 'postgres' : savedBuiltin.database;+ const redisBuiltIn = running ? running.cache && redisHost === 'redis' : savedBuiltin.cache;+ const storageBuiltIn = running ? running.storage && s3Endpoint === 'http://minio:9000' : savedBuiltin.storage;+ const s3Available = storageType === 's3' ? this.storageService.isS3Available() : undefined;+return {- database: { connected: dbConnected, type: dbType, host: dbHost },- redis: { enabled: redisEnabled, connected: redisConnected, host: redisHost, port: redisPort },+ database: { connected: dbConnected, type: dbType, host: dbHost, builtIn: dbBuiltIn },+ redis: {+ enabled: redisEnabled,+ connected: redisConnected,+ host: redisHost,+ port: redisPort,+ builtIn: redisBuiltIn,+ },queue: {enabled: queueEnabled,messages: { pending: 0, completed: 0, failed: 0 },@@ -275,11 +321,36 @@ export class InfraController {type: storageType,path: storagePath,...(storageType === 's3' && storageBucket ? { bucket: storageBucket } : {}),+ builtIn: storageBuiltIn,+ ...(storageType === 's3' ? { s3Available } : {}),+ },+ engine: {+ type: engineType,+ headless: engineHeadless,+ sessionDataPath,+ browserArgs,+ ...(engineType === 'whatsapp-web.js' ? { webVersion, webVersionSource } : {}),},- engine: { type: engineType, headless: engineHeadless, sessionDataPath, browserArgs },};}+ /** Saved built-in intent flags from data/.env.generated — the fallback when Docker isn't reachable. */+ private readSavedBuiltinFlags(): { database: boolean; cache: boolean; storage: boolean } {+ try {+ const envPath = path.resolve(process.cwd(), 'data', '.env.generated');+ const saved: Record<string, string> = fs.existsSync(envPath)+ ? dotenv.parse(fs.readFileSync(envPath, 'utf8'))+ : {};+ return {+ database: saved.POSTGRES_BUILTIN === 'true',+ cache: saved.REDIS_BUILTIN === 'true',+ storage: saved.MINIO_BUILTIN === 'true',+ };+ } catch {+ return { database: false, cache: false, storage: false };+ }+ }+@Get('engines')@RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Get available WhatsApp engines' })@@ -564,12 +635,20 @@ export class InfraController {// If profiles are specified, orchestrate Docker containersif (this.dockerService.isDockerAvailable()) {+ // Remove only the profiles the Save flow explicitly asked to remove, and never one we're about to+ // (re)start. We deliberately do NOT infer teardown from the saved *_BUILTIN flag: the default+ // data/.env.generated carries POSTGRES_BUILTIN=false, so a bare compose-profile restart would+ // otherwise tear down the very backend the app is running on. (Known minor limitation: switching+ // away from a built-in backend and then reloading the page before restarting can leave the old+ // container running until the next explicit change.)+ const toRemove = profilesToRemove.filter(p => !profiles.includes(p));+// First, remove containers for disabled services- if (profilesToRemove.length > 0) {- this.logger.log('Removing disabled profiles...');+ if (toRemove.length > 0) {+ this.logger.log('Removing disabled profiles...', { toRemove });removalResult = { removed: [], errors: [] };- for (const profile of profilesToRemove) {+ for (const profile of toRemove) {try {const success = await this.dockerService.removeService(profile);if (success) {@@ -1008,6 +1087,18 @@ export class InfraController {return { imported: false, counts, warnings };}+ // A wrong/empty/garbage backup file restores zero rows but the DELETE already ran — committing+ // would silently WIPE the database and report success. Refuse it and roll back instead. (#488 review)+ const totalRestored = Object.values(counts).reduce((sum, n) => sum + n, 0);+ if (totalRestored === 0) {+ await queryRunner.rollbackTransaction();+ return {+ imported: false,+ counts,+ warnings: ['Backup contained no rows to restore; refused to replace existing data. Check the file.'],+ };+ }+await queryRunner.commitTransaction();return { imported: true, counts, warnings };} catch (error) {diff --git a/src/modules/stats/stats.service.spec.ts b/src/modules/stats/stats.service.spec.tsindex ab669451f..09acc9dc6 100644--- a/src/modules/stats/stats.service.spec.ts+++ b/src/modules/stats/stats.service.spec.ts@@ -147,6 +147,46 @@ describe('StatsService time-series + hourly activity on SQLite (end-to-end regre}});+ it('no analytics query orders/groups by an unquoted mixed-case alias (Postgres case-folds it → 42703)', async () => {+ await ds+ .getRepository(Session)+ .save(ds.getRepository(Session).create({ id: 's1', name: 'n', status: SessionStatus.READY, config: {} }));+ await seedMessage({ direction: MessageDirection.OUTGOING });++ Object.defineProperty(service, 'dataDbType', { get: () => 'postgres', configurable: true });++ const captured: string[] = [];+ const repo = ds.getRepository(Message);+ const origCreate = repo.createQueryBuilder.bind(repo);+ jest.spyOn(repo, 'createQueryBuilder').mockImplementation((alias?: string) => {+ const qb = origCreate(alias);+ jest.spyOn(qb, 'getRawMany').mockImplementation(() => {+ captured.push(qb.getQuery());+ return Promise.resolve([]);+ });+ return qb;+ });++ await service.getMessageStats('24h'); // time-series + byType + bySession + topChats+ await service.getSessionStats('s1');++ expect(captured.length).toBeGreaterThan(0);+ // Postgres folds an UNQUOTED identifier to lowercase; a mixed-case alias defined with quotes+ // (COUNT(*) AS "messageCount") then no longer matches a bare `ORDER BY messageCount` → it looks for+ // "messagecount" and 42703s. SQLite is case-insensitive so it never surfaced. Flag any bare+ // (unquoted) ORDER BY / GROUP BY term that contains an uppercase letter.+ const offenders: string[] = [];+ for (const sql of captured) {+ for (const clause of sql.match(/\b(?:ORDER|GROUP) BY\s+[^\s,]+/gi) ?? []) {+ const term = clause.replace(/\b(?:ORDER|GROUP) BY\s+/i, '');+ // Only a BARE identifier (no quotes, no dots, no parens) folds — `COUNT(*)`, `to_char(...)`,+ // `"m"."chatId"` are all safe; `messageCount` is the landmine.+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(term) && /[A-Z]/.test(term)) offenders.push(`${clause} :: ${sql}`);+ }+ }+ expect(offenders).toEqual([]);+ });+it('getSessionStats returns 24 hourly buckets with the right counts', async () => {await ds.getRepository(Session)diff --git a/src/modules/stats/stats.service.ts b/src/modules/stats/stats.service.tsindex 2e523e47a..bbeba5805 100644--- a/src/modules/stats/stats.service.ts+++ b/src/modules/stats/stats.service.ts@@ -197,7 +197,9 @@ export class StatsService {.addSelect('COUNT(*)', 'messageCount').where('m.createdAt >= :since', { since }).groupBy('m.chatId')- .orderBy('messageCount', 'DESC')+ // Order by the aggregate expression, not the "messageCount" alias: Postgres folds an unquoted+ // ORDER BY messageCount to lowercase and 42703s against the quoted alias (SQLite tolerated it).+ .orderBy('COUNT(*)', 'DESC').limit(10).getRawMany<{ chatId: string; messageCount: string }>();