Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix: address deep-review regressions in v0.7.7 (infra/compose, prod guard, dashboard, chats) (#495)

Yudhi Armyndharis0ac82837eb44
diff --git a/.env.example b/.env.example
index 9ef425c98..b7bd0cbd7 100644
--- a/.env.example
+++ b/.env.example
@@ -163,9 +163,11 @@ S3_ENDPOINT=http://localhost:9000
S3_BUCKET=openwa
S3_REGION=us-east-1
# MUST set strong, unique values before using S3/MinIO — no defaults shipped.
-# Production refuses to start if these are empty/placeholder when STORAGE_TYPE=s3.
-S3_ACCESS_KEY=
-S3_SECRET_KEY=
+# Production refuses to start if these are empty/placeholder when STORAGE_TYPE=s3 (external).
+# Canonical names (what the app reads first and the dashboard writes); the legacy
+# S3_ACCESS_KEY / S3_SECRET_KEY are still accepted as a fallback for older setups.
+S3_ACCESS_KEY_ID=
+S3_SECRET_ACCESS_KEY=
# =============================================================================
# WEBHOOK
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9b2e53a1b..36caa5ffd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- External-S3 setups no longer silently fall back to local disk after upgrading: `docker-compose.yml` again forwards the legacy `S3_ACCESS_KEY` / `S3_SECRET_KEY` (alongside the canonical `S3_ACCESS_KEY_ID` / `S3_SECRET_ACCESS_KEY`) so an existing `.env` keeps reaching the container, and the legacy names are blank-cleared so they can't shadow the dashboard config. (#488 follow-up)
+- The production default-secret guard no longer skips a weak credential for a host-pinned **external** datastore just because the built-in flag is set: the built-in exemption now requires both the `*_BUILTIN` flag **and** an internal host (`postgres` / `minio`), so an external Postgres/MinIO with a default password is still rejected in production. (#488 follow-up)
+- The Infrastructure page now shows an error + retry (instead of an editable form seeded from defaults) when the live `/infra/status` can't be loaded, so a save can no longer flip a running built-in database/Redis/storage to external+empty. (#488 follow-up)
+- `/infra/status` no longer blocks on the WhatsApp Web version registry fetch, and that fetch is rate-limited after a failure, so a firewalled/offline host no longer stalls up to 5s on every status poll and every session start/reconnect. (#488 follow-up)
+- A replayed `message.sent` WebSocket echo no longer downgrades a chat message already shown as delivered/read; the live-append path now applies the same forward-only delivery-status merge as the ack path. (#484 follow-up)
+
## [0.7.7] - 2026-06-28
### Added
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index 0a94dfdb5..b34cf814e 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -53,7 +53,8 @@
"logout": "تسجيل الخروج",
"refresh": "تحديث",
"errorGeneric": "حدث خطأ",
- "unknownError": "خطأ غير معروف"
+ "unknownError": "خطأ غير معروف",
+ "retry": "إعادة المحاولة"
},
"theme": {
"light": "فاتح",
@@ -665,7 +666,8 @@
"importConfirm": "سيؤدّي الاستيراد إلى استبدال جميع البيانات الحالية بالنسخة الاحتياطية ({{rows}} صفًّا). لا يمكن التراجع عن هذا الإجراء. هل تريد المتابعة؟",
"invalidFile": "هذا الملفّ ليس نسخة احتياطية صالحة لبيانات OpenWA.",
"importTooLarge": "النسخة الاحتياطية أكبر من حدّ الطلب. زِد قيمة BODY_SIZE_LIMIT على الخادم ثم أعد المحاولة."
- }
+ },
+ "statusLoadError": "تعذّر تحميل حالة البنية التحتية الحالية. حدّث الصفحة لإعادة المحاولة."
},
"plugins": {
"title": "الإضافات",
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index da55d596a..0bd039b77 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -53,7 +53,8 @@
"logout": "Logout",
"refresh": "Refresh",
"errorGeneric": "An error occurred",
- "unknownError": "Unknown error"
+ "unknownError": "Unknown error",
+ "retry": "Retry"
},
"theme": {
"light": "Light",
@@ -665,7 +666,8 @@
},
"toasts": {
"saveFailed": "Save Failed"
- }
+ },
+ "statusLoadError": "Couldn't load the current infrastructure status. Refresh to try again."
},
"plugins": {
"title": "Plugins",
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index 49e926046..29d65a072 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -53,7 +53,8 @@
"errorGeneric": "Ha ocurrido un error",
"unknownError": "Error desconocido",
"showApiKey": "Mostrar clave API",
- "hideApiKey": "Ocultar clave API"
+ "hideApiKey": "Ocultar clave API",
+ "retry": "Reintentar"
},
"theme": {
"light": "Claro",
@@ -665,7 +666,8 @@
"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.",
"importTooLarge": "La copia de seguridad supera el límite de la solicitud. Aumenta BODY_SIZE_LIMIT en el servidor e inténtalo de nuevo."
- }
+ },
+ "statusLoadError": "No se pudo cargar el estado actual de la infraestructura. Actualiza para reintentar."
},
"plugins": {
"title": "Plugins",
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index e12f794d8..62edb6a8e 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -53,7 +53,8 @@
"logout": "Déconnexion",
"refresh": "Actualiser",
"errorGeneric": "Une erreur est survenue",
- "unknownError": "Erreur inconnue"
+ "unknownError": "Erreur inconnue",
+ "retry": "Réessayer"
},
"theme": {
"light": "Clair",
@@ -665,7 +666,8 @@
"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.",
"importTooLarge": "La sauvegarde dépasse la limite de la requête. Augmentez BODY_SIZE_LIMIT sur le serveur, puis réessayez."
- }
+ },
+ "statusLoadError": "Impossible de charger l'état actuel de l'infrastructure. Actualisez pour réessayer."
},
"plugins": {
"title": "Plugins",
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index c3fd83864..3325eeccf 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -53,7 +53,8 @@
"logout": "יציאה",
"refresh": "רענון",
"errorGeneric": "אירעה שגיאה",
- "unknownError": "שגיאה לא ידועה"
+ "unknownError": "שגיאה לא ידועה",
+ "retry": "נסה שוב"
},
"theme": {
"light": "בהיר",
@@ -665,7 +666,8 @@
"importConfirm": "הייבוא יחליף את כל הנתונים הנוכחיים בגיבוי ({{rows}} שורות). לא ניתן לבטל פעולה זו. להמשיך?",
"invalidFile": "הקובץ הזה אינו גיבוי נתונים תקין של OpenWA.",
"importTooLarge": "הגיבוי גדול מדי עבור מגבלת הבקשה. הגדילו את BODY_SIZE_LIMIT בשרת ונסו שוב."
- }
+ },
+ "statusLoadError": "לא ניתן לטעון את מצב התשתית הנוכחי. רעננו כדי לנסות שוב."
},
"plugins": {
"title": "תוספים",
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index baa2fc5b3..576451495 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -53,7 +53,8 @@
"logout": "Disconnetti",
"refresh": "Aggiorna",
"errorGeneric": "Si è verificato un errore",
- "unknownError": "Errore sconosciuto"
+ "unknownError": "Errore sconosciuto",
+ "retry": "Riprova"
},
"theme": {
"light": "Chiaro",
@@ -665,7 +666,8 @@
"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.",
"importTooLarge": "Il backup supera il limite della richiesta. Aumenta BODY_SIZE_LIMIT sul server e riprova."
- }
+ },
+ "statusLoadError": "Impossibile caricare lo stato attuale dell'infrastruttura. Aggiorna per riprovare."
},
"plugins": {
"title": "Plugin",
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index 96ab98b7d..a313026df 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -53,7 +53,8 @@
"logout": "లాగౌట్",
"refresh": "రిఫ్రెష్",
"errorGeneric": "ఒక లోపం సంభవించింది",
- "unknownError": "తెలియని లోపం"
+ "unknownError": "తెలియని లోపం",
+ "retry": "మళ్లీ ప్రయత్నించండి"
},
"theme": {
"light": "లైట్",
@@ -665,7 +666,8 @@
"importConfirm": "ఇంపోర్ట్ చేయడం వల్ల ప్రస్తుత డేటా మొత్తం బ్యాకప్‌తో ({{rows}} వరుసలు) భర్తీ చేయబడుతుంది. దీన్ని వెనక్కి తీసుకోలేరు. కొనసాగించాలా?",
"invalidFile": "ఆ ఫైల్ చెల్లుబాటు అయ్యే OpenWA డేటా బ్యాకప్ కాదు.",
"importTooLarge": "బ్యాకప్ అభ్యర్థన పరిమితి కంటే పెద్దది. సర్వర్‌లో BODY_SIZE_LIMIT పెంచి మళ్లీ ప్రయత్నించండి."
- }
+ },
+ "statusLoadError": "ప్రస్తుత ఇన్‌ఫ్రాస్ట్రక్చర్ స్థితిని లోడ్ చేయడం సాధ్యం కాలేదు. మళ్లీ ప్రయత్నించడానికి రిఫ్రెష్ చేయండి."
},
"plugins": {
"title": "ప్లగిన్స్",
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index d8556fb64..cd1790a3f 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -53,7 +53,8 @@
"logout": "退出登录",
"refresh": "刷新",
"errorGeneric": "发生错误",
- "unknownError": "未知错误"
+ "unknownError": "未知错误",
+ "retry": "重试"
},
"theme": {
"light": "浅色",
@@ -665,7 +666,8 @@
"importConfirm": "导入操作将用备份数据替换(REPLACE)当前所有数据({{rows}} 行)。此操作无法撤销。是否继续?",
"invalidFile": "该文件不是有效的 OpenWA 数据备份。",
"importTooLarge": "备份超出请求大小限制。请在服务器上调高 BODY_SIZE_LIMIT 后重试。"
- }
+ },
+ "statusLoadError": "无法加载当前基础设施状态。请刷新重试。"
},
"plugins": {
"title": "插件",
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 250371a37..83d666bcb 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -53,7 +53,8 @@
"logout": "登出",
"refresh": "重新整理",
"errorGeneric": "發生錯誤",
- "unknownError": "未知錯誤"
+ "unknownError": "未知錯誤",
+ "retry": "重試"
},
"theme": {
"light": "淺色",
@@ -665,7 +666,8 @@
"importConfirm": "匯入將以備份({{rows}} 列)取代所有目前資料。此操作無法復原。是否繼續?",
"invalidFile": "該檔案並非有效的 OpenWA 資料備份。",
"importTooLarge": "備份超出請求大小限制。請在伺服器上調高 BODY_SIZE_LIMIT 後重試。"
- }
+ },
+ "statusLoadError": "無法載入目前的基礎設施狀態。請重新整理以重試。"
},
"plugins": {
"title": "外掛",
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index f2a022bca..4c7ec6779 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -24,7 +24,7 @@ import {
type Chat,
type MessageType,
} from '../services/api';
-import { type ChatMessageView } from '../utils/chatMessages';
+import { mergeDeliveryStatus, type ChatMessageView } from '../utils/chatMessages';
import { useWebSocket } from '../hooks/useWebSocket';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useRole } from '../hooks/useRole';
@@ -42,25 +42,8 @@ import './Chats.css';
type MessageMedia = { mimetype: string; filename?: string; data?: string };
-// Delivery acks must only ADVANCE the tick, never regress it. The backend DB update is forward-only
-// (ackStatusTransitionFrom), but the live websocket ack fires on every receipt (incl. pending/sent)
-// and engine acks can arrive out of order or be replayed on reconnect — so a late/duplicate lower
-// ack must not visually downgrade a row already shown as delivered/read. This mirrors the backend's
-// transition rules exactly: pending<sent<delivered<read advances by rank; `failed` only applies from
-// pending/sent (a late failure must not clobber a confirmed delivered/read), and is terminal once set.
-const DELIVERY_RANK: Record<string, number> = { pending: 0, sent: 1, delivered: 2, read: 3 };
-const mergeDeliveryStatus = (
- current: ChatMessageView['status'] | undefined,
- incoming: ChatMessageView['status'] | undefined,
-): ChatMessageView['status'] | undefined => {
- if (!incoming) return current;
- if (!current) return incoming;
- if (current === 'failed') return 'failed'; // terminal — nothing advances from failed
- if (incoming === 'failed') return current === 'pending' || current === 'sent' ? 'failed' : current;
- if (!(incoming in DELIVERY_RANK)) return current; // unknown status — ignore
- if (!(current in DELIVERY_RANK)) return incoming;
- return DELIVERY_RANK[incoming] >= DELIVERY_RANK[current] ? incoming : current;
-};
+// mergeDeliveryStatus (forward-only delivery-tick merge) is shared with mergeOrAppend in utils/chatMessages
+// so the WS append path and the ack path apply the exact same rule.
interface IncomingWsMessage {
id: string;
diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsx
index 518eec1db..008ef57f8 100644
--- a/dashboard/src/pages/Infrastructure.tsx
+++ b/dashboard/src/pages/Infrastructure.tsx
@@ -80,7 +80,7 @@ export function Infrastructure() {
const { t } = useTranslation();
useDocumentTitle(t('infrastructure.title'));
const toast = useToast();
- const { data: infraStatus, isLoading: loading } = useInfraStatusQuery();
+ const { data: infraStatus, isLoading: loading, isError: statusError } = useInfraStatusQuery();
const { data: savedConfig } = useInfraConfigQuery();
const { data: engines = [] } = useEnginesQuery();
const { data: currentEngineData } = useCurrentEngineQuery();
@@ -250,6 +250,24 @@ export function Infrastructure() {
);
}
+ // If the live infrastructure status can't be loaded, do NOT render the editable form: it would seed
+ // from component defaults (sqlite/local/built-in:false) and a Save could flip a running backend to
+ // external+empty. Show an error + retry instead. (#488 review)
+ if (statusError || !infraStatus) {
+ return (
+ <div className="infrastructure-page">
+ <PageHeader title={t('infrastructure.title')} subtitle={t('infrastructure.subtitle')} />
+ <div className="infra-card" style={{ textAlign: 'center', padding: '2.5rem' }}>
+ <AlertTriangle size={32} style={{ color: 'var(--warning, #d97706)', marginBottom: '1rem' }} />
+ <p style={{ margin: 0 }}>{t('infrastructure.statusLoadError')}</p>
+ <button className="btn-secondary" style={{ marginTop: '1.25rem' }} onClick={() => window.location.reload()}>
+ {t('common.retry')}
+ </button>
+ </div>
+ </div>
+ );
+ }
+
const updateDbConfig = (key: keyof DatabaseConfig, value: string | number | boolean) =>
setDbConfig(prev => ({ ...prev, [key]: value }));
const updateRedisConfig = (key: keyof RedisConfig, value: string | boolean) =>
diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.ts
index 1e73ab19e..a1a103a54 100644
--- a/dashboard/src/utils/chatMessages.test.ts
+++ b/dashboard/src/utils/chatMessages.test.ts
@@ -110,6 +110,20 @@ test('mergeOrAppend replaces in place when id matches', () => {
assert.equal(after[1].id, 'm-2');
});
+test('mergeOrAppend does NOT downgrade delivery status (a replayed "sent" echo keeps "read")', () => {
+ const before = [msg({ id: 'm-1', status: 'read' })];
+ const after = mergeOrAppend(before, msg({ id: 'm-1', status: 'sent', body: 'echo' }));
+ assert.equal(after.length, 1);
+ assert.equal(after[0].status, 'read'); // forward-only: not downgraded to sent
+ assert.equal(after[0].body, 'echo'); // other fields still update
+});
+
+test('mergeOrAppend keeps existing metadata when the incoming copy carries none', () => {
+ const before = [msg({ id: 'm-1', metadata: { media: { mimetype: 'image/png' } } })];
+ const after = mergeOrAppend(before, msg({ id: 'm-1', metadata: undefined }));
+ assert.deepEqual(after[0].metadata, { media: { mimetype: 'image/png' } });
+});
+
test('mergeOrAppend dedupes a live WS message against its DB copy (id != id but same waMessageId)', () => {
// DB-persisted copy: id = UUID, waMessageId = WA serialized id.
const dbCopy = msg({ id: 'uuid-1', waMessageId: '[email protected]_WA1', body: 'persisted' });
diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.ts
index ca3ef62a9..a359561bf 100644
--- a/dashboard/src/utils/chatMessages.ts
+++ b/dashboard/src/utils/chatMessages.ts
@@ -48,11 +48,31 @@ export interface ChatMessageView extends ChatMessage {
};
}
+// Delivery ticks only ADVANCE, never regress. Live websocket events (incl. a replayed message.sent on
+// reconnect) and engine acks can arrive out of order, so a late/duplicate lower status must not visually
+// downgrade a row already shown as delivered/read. Mirrors the backend transition rules:
+// pending<sent<delivered<read advances by rank; `failed` only applies from pending/sent and is terminal.
+const DELIVERY_RANK: Record<string, number> = { pending: 0, sent: 1, delivered: 2, read: 3 };
+export function mergeDeliveryStatus(
+ current: ChatMessageView['status'] | undefined,
+ incoming: ChatMessageView['status'] | undefined,
+): ChatMessageView['status'] | undefined {
+ if (!incoming) return current;
+ if (!current) return incoming;
+ if (current === 'failed') return 'failed'; // terminal — nothing advances from failed
+ if (incoming === 'failed') return current === 'pending' || current === 'sent' ? 'failed' : current;
+ if (!(incoming in DELIVERY_RANK)) return current; // unknown status — ignore
+ if (!(current in DELIVERY_RANK)) return incoming;
+ return DELIVERY_RANK[incoming] >= DELIVERY_RANK[current] ? incoming : current;
+}
+
/**
* Append `incoming` to `list`. If an entry with the same identity exists, replace it in place.
* Identity uses the same `waMessageId ?? id` key as mergeChatMessages — a DB row (id=UUID,
* waMessageId=WA id) and a live WS message (id=WA id) for the same WhatsApp message must dedupe,
- * not double-add. Returns a new array — does not mutate the input.
+ * not double-add. On replace, the delivery status only advances (a replayed lower `sent` echo can't
+ * downgrade a delivered/read row) and existing metadata is kept when the incoming copy carries none.
+ * Returns a new array — does not mutate the input.
*/
export function mergeOrAppend(
list: ChatMessageView[],
@@ -60,8 +80,13 @@ export function mergeOrAppend(
): ChatMessageView[] {
const idx = list.findIndex(m => msgKey(m) === msgKey(incoming));
if (idx === -1) return [...list, incoming];
+ const existing = list[idx];
const next = list.slice();
- next[idx] = incoming;
+ next[idx] = {
+ ...incoming,
+ status: mergeDeliveryStatus(existing.status, incoming.status) ?? incoming.status,
+ metadata: incoming.metadata ?? existing.metadata,
+ };
return next;
}
diff --git a/docker-compose.yml b/docker-compose.yml
index 432750d41..ef6c770a9 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -113,14 +113,17 @@ services:
# 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. 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.
+ # host value pins. Credentials use the canonical S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY names the
+ # app and dashboard write; the legacy S3_ACCESS_KEY / S3_SECRET_KEY are ALSO forwarded (and read
+ # as a fallback by the storage layer) so existing .env files keep working unchanged. 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_ACCESS_KEY=${S3_ACCESS_KEY:-}
+ - S3_SECRET_KEY=${S3_SECRET_KEY:-}
- S3_REGION=${S3_REGION:-}
- S3_BUCKET=${S3_BUCKET:-}
# Redis. Blank-forwarded (see Database note) so a dashboard enable/disable applies; a real host
diff --git a/src/config/bootstrap-security.spec.ts b/src/config/bootstrap-security.spec.ts
index cc41d0386..c61f29338 100644
--- a/src/config/bootstrap-security.spec.ts
+++ b/src/config/bootstrap-security.spec.ts
@@ -131,6 +131,47 @@ describe('assertNoDefaultSecretsInProduction', () => {
).toThrow(/DATABASE_PASSWORD/);
});
+ it('does NOT exempt a weak secret when the built-in flag is set but the host is EXTERNAL', () => {
+ // POSTGRES_BUILTIN=true but DATABASE_HOST points at a reachable external DB → still enforced.
+ expect(() =>
+ assertNoDefaultSecretsInProduction({
+ nodeEnv: 'production',
+ databaseType: 'postgres',
+ databasePassword: 'openwa',
+ postgresBuiltIn: 'true',
+ databaseHost: 'db.example.com',
+ }),
+ ).toThrow(/DATABASE_PASSWORD/);
+ // MINIO_BUILTIN=true but S3_ENDPOINT is an external bucket → still enforced.
+ expect(() =>
+ assertNoDefaultSecretsInProduction({
+ nodeEnv: 'production',
+ storageType: 's3',
+ s3AccessKey: 'minioadmin',
+ s3SecretKey: 'minioadmin',
+ minioBuiltIn: 'true',
+ s3Endpoint: 'https://s3.amazonaws.com',
+ }),
+ ).toThrow(/S3_ACCESS_KEY/);
+ });
+
+ it('exempts the built-in defaults when the host is the internal bundled service', () => {
+ expect(() =>
+ assertNoDefaultSecretsInProduction({
+ nodeEnv: 'production',
+ databaseType: 'postgres',
+ databasePassword: 'openwa',
+ postgresBuiltIn: 'true',
+ databaseHost: 'postgres',
+ storageType: 's3',
+ s3AccessKey: 'minioadmin',
+ s3SecretKey: 'minioadmin',
+ minioBuiltIn: 'true',
+ s3Endpoint: 'http://minio:9000',
+ }),
+ ).not.toThrow();
+ });
+
it('refuses prod with default MinIO/S3 credentials', () => {
expect(() =>
assertNoDefaultSecretsInProduction({
diff --git a/src/config/bootstrap-security.ts b/src/config/bootstrap-security.ts
index 13214d0dd..9ec273b88 100644
--- a/src/config/bootstrap-security.ts
+++ b/src/config/bootstrap-security.ts
@@ -78,15 +78,31 @@ export function isApiKeyPepperMissingInProduction(nodeEnv?: string, apiKeyPepper
return nodeEnv === 'production' && !apiKeyPepper?.trim();
}
+/** A built-in S3 endpoint is the bundled MinIO (host `minio`) — or unset (the built-in default). An
+ * external endpoint (e.g. s3.amazonaws.com) is reachable, so its credentials are never exempted. */
+function isInternalS3Endpoint(endpoint?: string): boolean {
+ const e = endpoint?.trim();
+ if (!e) return true;
+ try {
+ return new URL(e).hostname === 'minio';
+ } catch {
+ return false;
+ }
+}
+
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;
+ /** DATABASE_HOST — used to confirm a built-in exemption really points at the internal `postgres`. */
+ databaseHost?: string;
storageType?: string;
s3AccessKey?: string;
s3SecretKey?: string;
+ /** S3_ENDPOINT — used to confirm a built-in exemption really points at the internal `minio`. */
+ s3Endpoint?: string;
/** MINIO_BUILTIN — when 'true', OpenWA runs the bundled MinIO on the internal-only network. */
minioBuiltIn?: string;
apiMasterKey?: string;
@@ -110,11 +126,16 @@ export function assertNoDefaultSecretsInProduction(env: SecretCheckEnv): void {
// 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)) {
+ // built-in option doesn't crash-loop a production boot. The exemption requires BOTH the built-in
+ // flag AND an internal host: a host-pinned EXTERNAL datastore (even with the built-in flag set) is
+ // reachable, so its weak credential is still enforced.
+ const dbHost = env.databaseHost?.trim();
+ const dbExempt = env.postgresBuiltIn === 'true' && (!dbHost || dbHost === 'postgres');
+ if (env.databaseType === 'postgres' && !dbExempt && isWeak(env.databasePassword)) {
problems.push('DATABASE_PASSWORD');
}
- if (env.storageType === 's3' && env.minioBuiltIn !== 'true') {
+ const s3Exempt = env.minioBuiltIn === 'true' && isInternalS3Endpoint(env.s3Endpoint);
+ if (env.storageType === 's3' && !s3Exempt) {
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.ts
index 427145d79..b2545c504 100644
--- a/src/config/env-precedence.spec.ts
+++ b/src/config/env-precedence.spec.ts
@@ -98,6 +98,9 @@ describe('blank-shadowed env keys (compose ${VAR:-} forwards the dashboard manag
'S3_REGION',
'S3_ACCESS_KEY_ID',
'S3_SECRET_ACCESS_KEY',
+ // legacy S3 names forwarded blank for backward compat — must also be cleared when blank
+ 'S3_ACCESS_KEY',
+ 'S3_SECRET_KEY',
'REDIS_ENABLED',
'REDIS_HOST',
'REDIS_PORT',
diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.ts
index 27d2bae48..b5c5b2c0b 100644
--- a/src/config/env-precedence.ts
+++ b/src/config/env-precedence.ts
@@ -34,6 +34,10 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = [
'S3_REGION',
'S3_ACCESS_KEY_ID',
'S3_SECRET_ACCESS_KEY',
+ // Legacy S3 credential names — compose forwards them blank for backward compat, so clear a blank
+ // forward too (otherwise it could shadow a value in data/.env.generated).
+ 'S3_ACCESS_KEY',
+ 'S3_SECRET_KEY',
// Redis selection + connection details (#488)
'REDIS_ENABLED',
'REDIS_HOST',
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 46ad57f1b..465d14fcf 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -689,11 +689,20 @@ describe('resolveWebVersionPin (#251/#488 — explicit pin + auto-resolve curren
expect(fetcher).toHaveBeenCalledTimes(1);
});
- it('does NOT cache a transient failure — a later call retries and resolves (#488 review must-fix)', async () => {
+ it('rate-limits a transient failure (no refetch within the backoff window) but does NOT cache it permanently', async () => {
delete process.env.WWEBJS_WEB_VERSION;
- expect(await resolveWebVersionPin(fetcherFor(null, false))).toBeUndefined(); // transient failure, not cached
+ expect(await resolveWebVersionPin(fetcherFor(null, false))).toBeUndefined(); // transient failure
+
+ // Within the backoff window: a 2nd call returns undefined WITHOUT another network fetch.
+ const blocked = fetcherFor('2.3000.1042251103-alpha');
+ expect(await resolveWebVersionPin(blocked)).toBeUndefined();
+ expect(blocked).not.toHaveBeenCalled();
+
+ // After the window elapses (reset simulates it / a process restart): it retries and resolves —
+ // the failure was never permanently cached (#488 must-fix preserved).
+ __resetWebVersionCache();
const ok = fetcherFor('2.3000.1042251103-alpha');
- const pin = await resolveWebVersionPin(ok); // retries
+ const pin = await resolveWebVersionPin(ok);
expect(pin?.webVersion).toBe('2.3000.1042251103-alpha');
expect(ok).toHaveBeenCalledTimes(1);
});
diff --git a/src/engine/wa-web-version.ts b/src/engine/wa-web-version.ts
index a3dec4e37..9a656e667 100644
--- a/src/engine/wa-web-version.ts
+++ b/src/engine/wa-web-version.ts
@@ -16,15 +16,20 @@ export const WA_VERSION_REGISTRY_URL =
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.
+// fetch is NOT cached permanently — but to avoid re-stalling every call (e.g. each /infra/status poll
+// and every session start/reconnect) on a firewalled/offline host, a failure is rate-limited by
+// `lastFailureAt`: subsequent calls return null instantly for FAILURE_BACKOFF_MS, then retry. `inFlight`
+// dedupes concurrent resolves into a single fetch.
+const FAILURE_BACKOFF_MS = 60_000;
let cachedCurrentVersion: string | undefined;
let inFlight: Promise<string | null> | null = null;
+let lastFailureAt = 0;
/** Test-only: reset the resolved-version cache between cases. */
export function __resetWebVersionCache(): void {
cachedCurrentVersion = undefined;
inFlight = null;
+ lastFailureAt = 0;
}
function buildRemotePin(version: string): WebVersionPin {
@@ -44,6 +49,9 @@ function buildRemotePin(version: string): WebVersionPin {
export async function resolveCurrentWebVersion(fetcher: typeof fetch = fetch): Promise<string | null> {
if (typeof cachedCurrentVersion === 'string') return cachedCurrentVersion;
if (inFlight) return inFlight;
+ // Within the backoff window after a recent failure, return null instantly without a network call so
+ // a firewalled/offline host doesn't re-stall on every status poll / session start.
+ if (lastFailureAt && Date.now() - lastFailureAt < FAILURE_BACKOFF_MS) return null;
inFlight = (async (): Promise<string | null> => {
try {
const controller = new AbortController();
@@ -57,12 +65,14 @@ export async function resolveCurrentWebVersion(fetcher: typeof fetch = fetch): P
cachedCurrentVersion = v; // cache only on success
return v;
}
- return null; // malformed payload — don't cache, retry next time
+ lastFailureAt = Date.now(); // malformed payload — back off, then retry
+ return null;
} finally {
clearTimeout(timer);
}
} catch {
- return null; // fetch failed — don't cache, retry next time
+ lastFailureAt = Date.now(); // fetch failed — back off, then retry
+ return null;
} finally {
inFlight = null;
}
diff --git a/src/main.ts b/src/main.ts
index 35b5fca3c..f780968a5 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -119,8 +119,10 @@ async function bootstrap() {
databaseType: process.env.DATABASE_TYPE,
databasePassword: process.env.DATABASE_PASSWORD,
postgresBuiltIn: process.env.POSTGRES_BUILTIN,
+ databaseHost: process.env.DATABASE_HOST,
storageType: process.env.STORAGE_TYPE,
minioBuiltIn: process.env.MINIO_BUILTIN,
+ s3Endpoint: process.env.S3_ENDPOINT,
// 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/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.ts
index eb4e1a6d0..4bf4c8a70 100644
--- a/src/modules/infra/infra.controller.spec.ts
+++ b/src/modules/infra/infra.controller.spec.ts
@@ -638,6 +638,14 @@ describe('InfraController.getConfig (#226)', () => {
});
describe('InfraController.getStatus engine (F7 — reads the real engine.puppeteer.* keys)', () => {
+ // Pin the WA-Web version so getStatus does not fire the wa-version registry fetch (no network in tests).
+ const savedWebVer = process.env.WWEBJS_WEB_VERSION;
+ beforeAll(() => (process.env.WWEBJS_WEB_VERSION = 'off'));
+ afterAll(() => {
+ if (savedWebVer === undefined) delete process.env.WWEBJS_WEB_VERSION;
+ else process.env.WWEBJS_WEB_VERSION = savedWebVer;
+ });
+
it('reports the saved headless/browserArgs instead of stale defaults from non-existent flat keys', async () => {
const map: Record<string, unknown> = {
'engine.type': 'whatsapp-web.js',
@@ -667,6 +675,14 @@ describe('InfraController.getStatus engine (F7 — reads the real engine.puppete
});
describe('InfraController.getStatus storage (reads the real storage.localPath key)', () => {
+ // Pin the WA-Web version so getStatus does not fire the wa-version registry fetch (no network in tests).
+ const savedWebVer = process.env.WWEBJS_WEB_VERSION;
+ beforeAll(() => (process.env.WWEBJS_WEB_VERSION = 'off'));
+ afterAll(() => {
+ if (savedWebVer === undefined) delete process.env.WWEBJS_WEB_VERSION;
+ else process.env.WWEBJS_WEB_VERSION = savedWebVer;
+ });
+
const buildController = (map: Record<string, unknown>) => {
const config = { get: (key: string, def?: unknown) => (key in map ? map[key] : def) };
const cache = { isAvailable: () => Promise.resolve(false) };
diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.ts
index 56494c309..3ac162cae 100644
--- a/src/modules/infra/infra.controller.ts
+++ b/src/modules/infra/infra.controller.ts
@@ -275,8 +275,11 @@ export class InfraController {
let webVersion: string | null | undefined;
let webVersionSource: 'pinned' | 'auto' | 'native' | undefined;
if (engineType === 'whatsapp-web.js') {
+ // Kick the auto-resolve but DON'T await it — /infra/status is polled frequently and the registry
+ // fetch can take up to 5s on a firewalled host. Read whatever's cached now (null until the first
+ // success); a later poll reflects the resolved build. (#488 review)
if (getEffectiveWebVersionInfo().source === 'auto') {
- await resolveCurrentWebVersion().catch(() => undefined);
+ void resolveCurrentWebVersion().catch(() => undefined);
}
const info = getEffectiveWebVersionInfo();
webVersion = info.version;