Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: #735 — S3 init without endpoint, engine-selection revert, Message Tester file upload (#742)
Yudhi Armyndharis74d15f884e14
diff --git a/.env.example b/.env.exampleindex 05ea33268..7ca3bb889 100644--- a/.env.example+++ b/.env.example@@ -212,6 +212,8 @@ MINIO_BUILTIN=false # Use built-in MinIO container?STORAGE_LOCAL_PATH=./data/media# S3/MinIO settings (if STORAGE_TYPE=s3, auto-configured if MINIO_BUILTIN=true)+# S3_ENDPOINT is OPTIONAL: leave it unset for standard AWS S3 (derived from region); set it only for+# an S3-compatible store (MinIO, R2, …), which also enables path-style addressing.S3_ENDPOINT=http://localhost:9000S3_BUCKET=openwaS3_REGION=us-east-1diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4f1e941e6..1eb5b4fc2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,7 +13,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Send-response semantics clarified (docs only).** The send endpoints' Swagger response and `docs/06` now state explicitly that `201` means the gateway accepted the message for sending — not that the recipient received it — and that WhatsApp does not reject an unregistered recipient synchronously, so a message to a number that is not on WhatsApp still returns `201` with a `messageId` but never delivers. `GET /sessions/{id}/contacts/check/{number}` is cross-referenced as the way to pre-validate a new recipient, and the async message `status` lifecycle (`sent → delivered → read`, or `failed`) as the source of real delivery state. No behavior change. Refs #738.-### Fixed- **Engine auth-timeout now returns a diagnostic 504 instead of a bare 500.** When the WhatsApp Web@@ -25,6 +24,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0legitimately slow first boots. The outer engine-init hang deadline (`EngineInitTimeoutError`) stillsurfaces as 500 and is tracked separately.+- **S3 storage no longer falls back to local without an `endpoint`.** The S3 client init required an+ `endpoint`, which only S3-compatible stores (MinIO, R2) need — standard AWS S3 (whose endpoint is+ derived from region) silently initialized no client and served all media from local disk (#735).+ `endpoint` and `forcePathStyle` are now applied only when an endpoint is configured, so AWS S3 uses+ its default virtual-hosted addressing while MinIO-compatible stores keep path-style.++- **WhatsApp Engine selection on the Infrastructure page no longer reverts to the running engine.**+ The engine radio was re-stamped from the live `/engines/current` value on every emission, so a late+ first resolution (or a window-focus refetch) overwrote an operator's in-progress, unsaved selection+ (#735). The selection now seeds once and freezes on the first user interaction, matching the+ one-time hydration lock the other infrastructure fields already had.++- **Message Tester supports uploading local media files.** Media messages could previously only be+ sent from a URL; a file picker is now available alongside the URL field (mutually exclusive with+ it), reading the file as base64 (#735). The backend already accepted `base64`; this adds the+ dashboard UI for it. Uploads are client-capped at 18 MiB (the effective base64-over-JSON body+ limit) so an oversized pick surfaces a clear error instead of freezing the tab, and switching the+ message category after picking a file now clears it so stale bytes aren't routed to the wrong+ endpoint.+## [0.8.17] - 2026-07-13### Addeddiff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex c2b8b3988..20b380194 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -539,6 +539,11 @@"messageContent": "محتوى الرسالة","messagePlaceholder": "أدخل رسالتك هنا...","mediaUrl": "رابط الوسائط",+ "uploadFile": "رفع ملف",+ "browse": "استعراض",+ "removeFile": "إزالة الملف",+ "fileReadError": "فشل قراءة الملف",+ "fileTooLarge": "الملف كبير جدًا (الحد الأقصى 18 ميغابايت)","caption": "التعليق","filename": "اسم الملف","captionPlaceholder": "أدخل التعليق...",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex 7b3d0b23a..278bf0dc1 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -535,6 +535,11 @@"messageContent": "Message Content","messagePlaceholder": "Enter your message here...","mediaUrl": "Media URL",+ "uploadFile": "Upload file",+ "browse": "Browse",+ "removeFile": "Remove file",+ "fileReadError": "File read failed",+ "fileTooLarge": "File is too large (max 18 MB)","caption": "Caption","filename": "Filename","captionPlaceholder": "Enter caption...",diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex 7e55be4a2..655c6908a 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -490,6 +490,11 @@"messageContent": "Contenido del mensaje","messagePlaceholder": "Escribe tu mensaje aquí...","mediaUrl": "URL del medio",+ "uploadFile": "Subir archivo",+ "browse": "Examinar",+ "removeFile": "Quitar archivo",+ "fileReadError": "Error al leer el archivo",+ "fileTooLarge": "El archivo es demasiado grande (máx. 18 MB)","caption": "Pie de foto","filename": "Nombre de archivo","captionPlaceholder": "Escribe un pie de foto...",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex 26a86a18a..0c11d56a8 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -535,6 +535,11 @@"messageContent": "Contenu du message","messagePlaceholder": "Entrez votre message ici...","mediaUrl": "URL du média",+ "uploadFile": "Envoyer un fichier",+ "browse": "Parcourir",+ "removeFile": "Supprimer le fichier",+ "fileReadError": "Échec de lecture du fichier",+ "fileTooLarge": "Le fichier est trop volumineux (max 18 Mo)","caption": "Légende","filename": "Nom du fichier","captionPlaceholder": "Entrez une légende...",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex 422a03486..58018a09b 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -536,6 +536,11 @@"messageContent": "תוכן ההודעה","messagePlaceholder": "יש להזין כאן את ההודעה...","mediaUrl": "כתובת המדיה",+ "uploadFile": "העלאת קובץ",+ "browse": "עיון",+ "removeFile": "הסרת קובץ",+ "fileReadError": "קריאת הקובץ נכשלה",+ "fileTooLarge": "הקובץ גדול מדי (מקסימום 18 MB)","caption": "כיתוב","filename": "שם קובץ","captionPlaceholder": "יש להזין כיתוב...",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 304cd46d5..c690d8b92 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -535,6 +535,11 @@"messageContent": "Contenuto del Messaggio","messagePlaceholder": "Inserisci qui il tuo messaggio...","mediaUrl": "URL File Multimediale",+ "uploadFile": "Carica file",+ "browse": "Sfoglia",+ "removeFile": "Rimuovi file",+ "fileReadError": "Lettura del file non riuscita",+ "fileTooLarge": "Il file è troppo grande (max 18 MB)","caption": "Didascalia","filename": "Nome File","captionPlaceholder": "Inserisci una didascalia...",diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex 799f3c0be..766b2ca68 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -535,6 +535,11 @@"messageContent": "메시지 내용","messagePlaceholder": "메시지를 입력하세요...","mediaUrl": "미디어 URL",+ "uploadFile": "파일 업로드",+ "browse": "찾아보기",+ "removeFile": "파일 제거",+ "fileReadError": "파일 읽기 실패",+ "fileTooLarge": "파일이 너무 큽니다 (최대 18 MB)","caption": "설명","filename": "파일 이름","captionPlaceholder": "설명을 입력하세요...",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 1f5680c08..92e9276d3 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -490,6 +490,11 @@"messageContent": "Conteúdo da mensagem","messagePlaceholder": "Digite sua mensagem aqui...","mediaUrl": "URL da mídia",+ "uploadFile": "Enviar arquivo",+ "browse": "Procurar",+ "removeFile": "Remover arquivo",+ "fileReadError": "Falha ao ler o arquivo",+ "fileTooLarge": "O arquivo é muito grande (máx. 18 MB)","caption": "Legenda","filename": "Nome do arquivo","captionPlaceholder": "Digite uma legenda...",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex 65044cf0d..cadecfb30 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -535,6 +535,11 @@"messageContent": "సందేశం కంటెంట్","messagePlaceholder": "మీ సందేశాన్ని ఇక్కడ ఎంటర్ చేయండి...","mediaUrl": "మీడియా URL",+ "uploadFile": "ఫైల్ అప్లోడ్ చేయి",+ "browse": "బ్రౌజ్ చేయి",+ "removeFile": "ఫైల్ను తొలగించు",+ "fileReadError": "ఫైల్ చదవడం విఫలమైంది",+ "fileTooLarge": "ఫైల్ చాలా పెద్దది (గరిష్టం 18 MB)","caption": "క్యాప్షన్","filename": "ఫైల్ పేరు","captionPlaceholder": "క్యాప్షన్ ఎంటర్ చేయండి...",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex ab2d2ddb6..9b4d37546 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -535,6 +535,11 @@"messageContent": "消息内容","messagePlaceholder": "在此输入你的消息...","mediaUrl": "媒体 URL",+ "uploadFile": "上传文件",+ "browse": "浏览",+ "removeFile": "移除文件",+ "fileReadError": "文件读取失败",+ "fileTooLarge": "文件过大(最大 18 MB)","caption": "说明文字","filename": "文件名","captionPlaceholder": "输入说明文字...",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 86f7d021d..a26a933b6 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -535,6 +535,11 @@"messageContent": "訊息內容","messagePlaceholder": "在此輸入你的訊息...","mediaUrl": "媒體 URL",+ "uploadFile": "上傳檔案",+ "browse": "瀏覽",+ "removeFile": "移除檔案",+ "fileReadError": "檔案讀取失敗",+ "fileTooLarge": "檔案過大(最大 18 MB)","caption": "說明文字","filename": "檔案名稱","captionPlaceholder": "輸入說明文字...",diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsxindex 0ee32a2e7..4ad423acb 100644--- a/dashboard/src/pages/Infrastructure.tsx+++ b/dashboard/src/pages/Infrastructure.tsx@@ -154,6 +154,13 @@ export function Infrastructure() {// operator's in-progress, unsaved edits. A successful save restarts → full page reload, re-arming it.const formHydrated = useRef(false);+ // The engine radio seeds ONCE from the running engine (which honours a real ENGINE_TYPE env override+ // over the saved .env.generated value — see the effect below), then is never re-stamped by a background+ // refetch. `engineTouched` additionally wins over a late first resolution: if the operator clicked a+ // different engine before /engines/current resolved, the delayed seed must not revert their selection (#735).+ const engineHydrated = useRef(false);+ const engineTouched = useRef(false);+// LIVE indicators (not editable) — always reflect the running process, every refetch.useEffect(() => {if (!infraStatus) return;@@ -236,9 +243,13 @@ export function Infrastructure() {}, [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.+ // so seed the selected radio from it rather than the saved .env.generated value — but only ONCE, and+ // never after the operator has touched it. Without this guard a background refetch (or a late first+ // resolution racing an early click) re-stamps the running engine over an in-progress selection (#735).useEffect(() => {- if (currentEngine) setEngineConfig(prev => ({ ...prev, type: currentEngine }));+ if (!currentEngine || engineHydrated.current || engineTouched.current) return;+ engineHydrated.current = true;+ setEngineConfig(prev => (prev.type === currentEngine ? prev : { ...prev, type: currentEngine }));}, [currentEngine]);if (loading) {@@ -276,8 +287,10 @@ export function Infrastructure() {setRedisConfig(prev => ({ ...prev, [key]: value }));const updateStorageConfig = (key: keyof StorageConfig, value: string | boolean) =>setStorageConfig(prev => ({ ...prev, [key]: value }));- const updateEngineConfig = (key: keyof EngineConfig, value: string | boolean) =>+ const updateEngineConfig = (key: keyof EngineConfig, value: string | boolean) => {+ if (key === 'type') engineTouched.current = true;setEngineConfig(prev => ({ ...prev, [key]: value }));+ };const handleSaveConfig = async () => {setSaving(true);diff --git a/dashboard/src/pages/MessageTester.css b/dashboard/src/pages/MessageTester.cssindex 3851df4d6..6978c1761 100644--- a/dashboard/src/pages/MessageTester.css+++ b/dashboard/src/pages/MessageTester.css@@ -209,6 +209,63 @@margin: 0;}+.message-tester .browse-btn{+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ padding: 0.625rem 1rem;+ font-size: 0.875rem;+ font-weight: 500;+ color: var(--text-secondary);+ background: var(--bg-white);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ cursor: pointer;+ transition: all 0.2s;+}++.message-tester .browse-btn:hover{+ border-color: var(--primary);+ color: var(--primary);+}++.message-tester .file-selected{+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ padding: 0.625rem 0.875rem;+ background: var(--bg-light);+ border: 1px solid var(--border);+ border-radius: var(--radius);+}++.message-tester .file-name{+ font-size: 0.875rem;+ color: var(--text-primary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.message-tester .remove-file-btn{+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+ flex-shrink: 0;+ font-size: 0.8125rem;+ color: var(--error);+ background: none;+ border: none;+ cursor: pointer;+ padding: 0;+ white-space: nowrap;+}++.message-tester .remove-file-btn:hover{+ text-decoration: underline;+}+@media (max-width: 1000px) {.message-tester .tester-panels{grid-template-columns: 1fr;diff --git a/dashboard/src/pages/MessageTester.tsx b/dashboard/src/pages/MessageTester.tsxindex 66d0a99f2..dfe3386b5 100644--- a/dashboard/src/pages/MessageTester.tsx+++ b/dashboard/src/pages/MessageTester.tsx@@ -1,7 +1,7 @@-import { useState, useEffect } from 'react';+import { useState, useEffect, useRef, type ChangeEvent } from 'react';import { useTranslation } from 'react-i18next';-import { Send, CheckCircle, XCircle, Loader2 } from 'lucide-react';-import { messageApi, contactApi } from '../services/api';+import { Send, CheckCircle, XCircle, Loader2, Upload, X } from 'lucide-react';+import { messageApi, contactApi, type SendMediaPayload } from '../services/api';import { useDocumentTitle } from '../hooks/useDocumentTitle';import { useRole } from '../hooks/useRole';import { useSessionsQuery, useSessionGroupsQuery } from '../hooks/queries';@@ -17,6 +17,31 @@ interface ApiResponse {const messageTypes = ['text', 'image', 'video', 'audio', 'document'] as const;+// Hint the native file picker at the right category (documents accept anything).+const mediaAccept: Record<(typeof messageTypes)[number], string> = {+ text: '*/*',+ image: 'image/*',+ video: 'video/*',+ audio: 'audio/*',+ document: '*/*',+};++// Fallback MIME for when the browser leaves File.type empty (some extensions). The backend requires a+// mimetype on every base64 send, so default by the selected message category.+const fallbackMime: Record<(typeof messageTypes)[number], string> = {+ text: 'text/plain',+ image: 'image/jpeg',+ video: 'video/mp4',+ audio: 'audio/mpeg',+ document: 'application/octet-stream',+};++// Client pre-check before base64-encoding an upload. Aligned with the default request-body limit: base64+// inflates ~1.33x, so ~18 MiB raw stays under the 25 MiB BODY_SIZE_LIMIT and lets the backend reject with a+// clear 413 instead of the tab OOMing on a multi-hundred-MB pick before the request is even sent. The+// backend's MEDIA_DOWNLOAD_MAX_BYTES (default 50 MiB) stays authoritative for URL sends (fetched server-side).+const MEDIA_UPLOAD_MAX_BYTES = 18 * 1024 * 1024;+export function MessageTester() {const { t } = useTranslation();useDocumentTitle(t('messageTester.title'));@@ -30,6 +55,10 @@ export function MessageTester() {const [messageType, setMessageType] = useState<typeof messageTypes[number]>('text');const [content, setContent] = useState('');const [mediaUrl, setMediaUrl] = useState('');+ // A locally-picked media file, read as raw base64 (the engine contract — NOT a data: URI). Mutually+ // exclusive with mediaUrl: picking a file clears the URL field; typing a URL drops the file.+ const [mediaFile, setMediaFile] = useState<{ base64: string; mimetype: string; filename: string } | null>(null);+ const fileInputRef = useRef<HTMLInputElement>(null);const [isLoading, setIsLoading] = useState(false);const [response, setResponse] = useState<ApiResponse | null>(null);@@ -59,6 +88,33 @@ export function MessageTester() {}}, [groups, selectedGroup, recipientType]);+ const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ e.target.value = ''; // allow re-picking the same file after it's removed+ if (!file) return;+ // Reject before base64-encoding so an oversized pick surfaces a clear error instead of OOMing the tab+ // (the backend 413 cap only applies after the whole body is uploaded).+ if (file.size > MEDIA_UPLOAD_MAX_BYTES) {+ setResponse({ success: false, timestamp: new Date().toISOString(), error: t('messageTester.fileTooLarge') });+ return;+ }+ const reader = new FileReader();+ reader.onload = () => {+ const dataUrl = reader.result;+ if (typeof dataUrl !== 'string') return;+ // readAsDataURL yields "data:<mime>;base64,<payload>"; the engine expects raw base64, so strip the prefix.+ const base64 = dataUrl.split(',')[1] ?? '';+ if (!base64) return;+ setMediaFile({ base64, mimetype: file.type || fallbackMime[messageType], filename: file.name });+ setMediaUrl('');+ if (messageType === 'document') setContent(file.name);+ };+ reader.onerror = () => {+ setResponse({ success: false, timestamp: new Date().toISOString(), error: t('messageTester.fileReadError') });+ };+ reader.readAsDataURL(file);+ };+const handleSend = async () => {const targetId = recipientType === 'group' ? selectedGroup : recipient;if (!session || !targetId) return;@@ -85,14 +141,20 @@ export function MessageTester() {let result;if (messageType === 'text') {result = await messageApi.sendText(session, chatId, content);- } else if (messageType === 'image') {- result = await messageApi.sendImage(session, chatId, mediaUrl, content);- } else if (messageType === 'video') {- result = await messageApi.sendVideo(session, chatId, mediaUrl, content);- } else if (messageType === 'audio') {- result = await messageApi.sendAudio(session, chatId, mediaUrl);} else {- result = await messageApi.sendDocument(session, chatId, mediaUrl, content);+ // sendMedia unifies URL and base64 (local file) sends; base64 wins when a file is picked. The+ // backend accepts url XOR base64 and requires a mimetype for base64 (always provided here).+ const payload: SendMediaPayload = mediaFile+ ? { base64: mediaFile.base64, mimetype: mediaFile.mimetype }+ : { url: mediaUrl };+ if ((messageType === 'image' || messageType === 'video') && content) payload.caption = content;+ if (messageType === 'document' && content) payload.filename = content;+ result = await messageApi.sendMedia(+ session,+ chatId,+ messageType as 'image' | 'video' | 'audio' | 'document',+ payload,+ );}setResponse({@@ -196,7 +258,12 @@ export function MessageTester() {<buttonkey={type}className={messageType === type ? 'active' : ''}- onClick={() => setMessageType(type)}+ onClick={() => {+ // A picked file's mimetype is bound to the category active at pick time, so dropping the+ // category would route stale bytes to the wrong send-${type} endpoint — clear it.+ if (type !== messageType) setMediaFile(null);+ setMessageType(type);+ }}>{t(`messageTester.types.${type}`)}</button>@@ -221,8 +288,36 @@ export function MessageTester() {<inputtype="text"value={mediaUrl}- onChange={e => setMediaUrl(e.target.value)}+ onChange={e => {+ setMediaUrl(e.target.value);+ if (mediaFile) setMediaFile(null);+ }}placeholder="https://example.com/file.jpg"+ disabled={!!mediaFile}+ />+ </div>+ <div className="form-group">+ <label>{t('messageTester.uploadFile')}</label>+ {mediaFile ? (+ <div className="file-selected">+ <span className="file-name" title={mediaFile.filename}>+ {mediaFile.filename}+ </span>+ <button type="button" className="remove-file-btn" onClick={() => setMediaFile(null)}>+ <X size={14} /> {t('messageTester.removeFile')}+ </button>+ </div>+ ) : (+ <button type="button" className="browse-btn" onClick={() => fileInputRef.current?.click()}>+ <Upload size={14} /> {t('messageTester.browse')}+ </button>+ )}+ <input+ ref={fileInputRef}+ type="file"+ style={{ display: 'none' }}+ accept={mediaAccept[messageType]}+ onChange={handleFileChange}/></div>{messageType !== 'audio' && (diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.mdindex 94284528f..baef0df45 100644--- a/docs/03-system-architecture.md+++ b/docs/03-system-architecture.md@@ -1542,8 +1542,8 @@ S3_BUCKET=openwa-mediaS3_REGION=ap-southeast-1S3_ACCESS_KEY_ID=xxxS3_SECRET_ACCESS_KEY=xxx-S3_ENDPOINT=https://s3.ap-southeast-1.amazonaws.com-# For MinIO, point S3_ENDPOINT at it (path-style is always on):+# AWS S3 needs NO endpoint (one is derived from the region) — leave S3_ENDPOINT unset for it. An+# endpoint is only for S3-compatible stores (MinIO, R2, …), where setting it also enables path-style:# S3_ENDPOINT=http://minio:9000# Cachediff --git a/src/common/storage/storage.service.s3.spec.ts b/src/common/storage/storage.service.s3.spec.tsnew file mode 100644index 000000000..3680461fc--- /dev/null+++ b/src/common/storage/storage.service.s3.spec.ts@@ -0,0 +1,135 @@+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { ConfigService } from '@nestjs/config';++// `archiver` v8 ships ESM-only, which ts-jest can't parse transitively. These tests never touch the+// export path (archiver's only consumer), so a lightweight stub suffices — same approach as the local+// spec. Must run before importing StorageService.+jest.mock('archiver', () => ({ default: jest.fn() }));++// Mock the AWS SDK so no real network call is made: HeadBucket resolves (bucket reachable), and the+// S3Client constructor is a jest.fn so each test can assert on the exact config it received.+jest.mock('@aws-sdk/client-s3', () => {+ const send = jest.fn().mockResolvedValue({});+ const S3Client = jest.fn().mockImplementation(() => ({ send }));+ return {+ S3Client,+ HeadBucketCommand: jest.fn(),+ CreateBucketCommand: jest.fn(),+ ListObjectsV2Command: jest.fn(),+ GetObjectCommand: jest.fn(),+ PutObjectCommand: jest.fn(),+ };+});++import { S3Client } from '@aws-sdk/client-s3';+import { StorageService } from './storage.service';++// The subset of the AWS SDK's S3Client config this service sets — used purely to type the mock's call+// args so the assertions below are type-checked instead of `any`.+type S3ClientConfig = {+ endpoint?: string;+ region: string;+ forcePathStyle?: boolean;+ credentials: { accessKeyId: string; secretAccessKey: string };+};++const mockedS3Client = S3Client as unknown as jest.Mock<unknown, [S3ClientConfig]>;++const ENV_KEYS = [+ 'S3_ENDPOINT',+ 'S3_ACCESS_KEY_ID',+ 'S3_SECRET_ACCESS_KEY',+ 'S3_REGION',+ 'S3_BUCKET',+ 'S3_ACCESS_KEY',+ 'S3_SECRET_KEY',+];++// initializeS3Bucket() runs as a fire-and-forget promise; let its HeadBucket settle before asserting.+const flush = (): Promise<void> => new Promise(resolve => setImmediate(resolve));++/** The config passed to the most recent S3Client construction (throws if it was never constructed). */+function lastConfig(): S3ClientConfig {+ const last = mockedS3Client.mock.calls.at(-1);+ if (!last) throw new Error('S3Client was never constructed');+ return last[0];+}++describe('StorageService (s3) client init', () => {+ let tmpRoot: string;++ beforeEach(() => {+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-s3-'));+ mockedS3Client.mockClear();+ for (const key of ENV_KEYS) delete process.env[key];+ });++ afterEach(() => {+ fs.rmSync(tmpRoot, { recursive: true, force: true });+ });++ // Build a ConfigService scoped to s3 storage; localPath points at the per-test tmp dir so the+ // constructor's mkdir never touches the repo's ./data/media.+ function makeConfig(s3: Record<string, unknown>): ConfigService {+ return {+ get: (key: string) => {+ if (key === 'storage.type') return 's3';+ if (key === 'storage.localPath') return path.join(tmpRoot, 'media');+ if (key === 'storage.s3') return s3;+ return undefined;+ },+ } as unknown as ConfigService;+ }++ it('initializes for AWS S3 with credentials but NO endpoint (the #735 regression)', async () => {+ const svc = new StorageService(+ makeConfig({ accessKeyId: 'AKIAEXAMPLE', secretAccessKey: 'shhh-secret', region: 'ap-southeast-1' }),+ );+ await flush();++ expect(mockedS3Client).toHaveBeenCalledTimes(1);+ const cfg = lastConfig();+ expect(cfg.endpoint).toBeUndefined(); // AWS derives it from region+ expect(cfg.forcePathStyle).toBeFalsy(); // AWS uses virtual-hosted addressing+ expect(cfg.region).toBe('ap-southeast-1');+ expect(cfg.credentials).toEqual({ accessKeyId: 'AKIAEXAMPLE', secretAccessKey: 'shhh-secret' });+ expect(svc.isS3Available()).toBe(true);+ });++ it('keeps endpoint + forcePathStyle for an S3-compatible store (MinIO)', async () => {+ process.env.S3_ENDPOINT = 'http://minio:9000';+ const svc = new StorageService(+ makeConfig({ accessKeyId: 'minio', secretAccessKey: 'minio123', region: 'us-east-1' }),+ );+ await flush();++ expect(mockedS3Client).toHaveBeenCalledTimes(1);+ const cfg = lastConfig();+ expect(cfg.endpoint).toBe('http://minio:9000');+ expect(cfg.forcePathStyle).toBe(true);+ expect(svc.isS3Available()).toBe(true);+ });++ it('falls back to local (no client) when credentials are missing', async () => {+ const svc = new StorageService(makeConfig({ region: 'us-east-1' }));+ await flush();++ expect(mockedS3Client).not.toHaveBeenCalled();+ expect(svc.isS3Available()).toBe(false);+ expect(svc.getCurrentStorageType()).toBe('s3');+ });++ it('prefers canonical env names (S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY) over config', async () => {+ process.env.S3_ACCESS_KEY_ID = 'ENVKEY';+ process.env.S3_SECRET_ACCESS_KEY = 'ENVSECRET';+ const svc = new StorageService(+ makeConfig({ accessKeyId: 'CFGKEY', secretAccessKey: 'CFGSECRET', region: 'eu-west-1' }),+ );+ await flush();++ expect(lastConfig().credentials).toEqual({ accessKeyId: 'ENVKEY', secretAccessKey: 'ENVSECRET' });+ expect(svc.isS3Available()).toBe(true);+ });+});diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.tsindex acaf9fe2e..0147fefdf 100644--- a/src/common/storage/storage.service.ts+++ b/src/common/storage/storage.service.ts@@ -63,15 +63,19 @@ export class StorageService {const secretAccessKey = process.env.S3_SECRET_ACCESS_KEY || process.env.S3_SECRET_KEY || s3Config.secretAccessKey;const region = process.env.S3_REGION || s3Config.region || 'us-east-1';- if (endpoint && accessKeyId && secretAccessKey) {+ // Standard AWS S3 needs only credentials + region — the SDK derives the regional endpoint, and+ // an `endpoint` is only required for S3-compatible stores (MinIO, R2, …). Requiring it dropped+ // valid AWS configs to a silent local fallback (#735). forcePathStyle is likewise a path-style+ // concern (MinIO/etc.); AWS S3 uses virtual-hosted addressing — so tie both to the endpoint.+ if (accessKeyId && secretAccessKey) {this.s3Client = new S3Client({- endpoint,+ ...(endpoint ? { endpoint } : {}),region,credentials: {accessKeyId,secretAccessKey,},- forcePathStyle: true, // Required for MinIO+ ...(endpoint ? { forcePathStyle: true } : {}), // Required for path-style stores (MinIO)});this.s3Bucket = process.env.S3_BUCKET || s3Config.bucket || 'openwa';void this.initializeS3Bucket();