Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): refuse bulk media URL typos and text next to audio
Yudhi Armyndharisa431c1506243
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dbb0855a6..29e66fdf2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,7 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Webhook and automation filters accept a `chatId` condition, so a webhook can be scoped to specific groups or chats instead of only to a sender ([#1634](https://github.com/rmyndharis/OpenWA/issues/1634)). Thanks @krishshah9944 and @bhavyachopra99.- The dashboard Templates list has a delete button on each row, so a template can be deleted without opening it in the editor first. Like the editor's delete button, it shows only for keys that can write templates. Thanks @C24212.- On the dashboard Chats page, Escape closes the open chat, channel or status viewer and returns to the list. It leaves the key alone while a dialog, a menu or the media viewer is open, since those handle Escape themselves. Thanks @C24212.-- The dashboard Message Tester's Bulk mode can attach a file or a media URL, sent as image, video, audio or document with the message text as the caption. An inline file too large to repeat for every recipient is refused before sending. Thanks @C24212.+- The dashboard Message Tester's Bulk mode can attach a file or a media URL, sent as image, video, audio or document, with the message text as the caption of an image, video or document; audio carries none, so text next to audio is refused. An inline file too large to repeat for every recipient is refused before sending. Thanks @C24212.- The dashboard sidebar tells admins when a newer OpenWA release exists, as a link to its release notes next to the version. `GET /api/infra/update-check` (ADMIN) reads the latest published GitHub release through the SSRF-guarded fetch and caches it for six hours, and a failed check never surfaces as an error; `UPDATE_CHECK_ENABLED=false` turns the request off ([#988](https://github.com/rmyndharis/OpenWA/issues/988), [#1678](https://github.com/rmyndharis/OpenWA/issues/1678)). Thanks @voosam and @OneArmArmy for the request.### Changeddiff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 495c8f1d2..6d82aaace 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -722,6 +722,7 @@"bulkMediaTooLarge": "هذا الملف كبير جدًا لإرساله مضمَّنًا إلى {{count}} مستلمين: بهذا العدد يمكن أن يصل حجم الملف إلى {{size}} كحد أقصى. استخدم رابط وسائط عامًا بدلًا منه، أو أرسل إلى عدد أقل من المستلمين.","bulkMediaUrlInvalid": "استخدم عنوانًا كاملًا يبدأ بـ http:// أو https://، مثل https://example.com/file.pdf.","bulkCaptionTooLong": "عند إرفاق ملف تُرسل الرسالة كتعليق عليه، والحد الأقصى للتعليق {{max}} حرفًا (الآن {{count}}).",+ "bulkAudioNoCaption": "يُرسَل الصوت بدون تعليق، لذا لن يُرسَل هذا النص. امسح الرسالة أو اختر نوعًا آخر.","send": "إرسال الرسالة","sending": "جارٍ الإرسال...","viewOnly": "للعرض فقط",diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex d499d0b5e..1aa524d46 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -707,6 +707,7 @@"bulkMediaTooLarge": "Diese Datei ist zu groß, um sie direkt an {{count}} Empfänger zu senden: Bei dieser Anzahl darf eine Datei höchstens {{size}} groß sein. Verwende stattdessen eine öffentliche Medien-URL oder sende an weniger Empfänger.","bulkMediaUrlInvalid": "Gib eine vollständige http://- oder https://-Adresse ein, z. B. https://example.com/file.pdf.","bulkCaptionTooLong": "Mit Anhang wird die Nachricht als dessen Bildunterschrift gesendet, die auf {{max}} Zeichen begrenzt ist (aktuell {{count}}).",+ "bulkAudioNoCaption": "Audio wird ohne Bildunterschrift gesendet, dieser Text würde also nicht verschickt. Leere die Nachricht oder wähle eine andere Art.","send": "Nachricht senden","sending": "Wird gesendet...","viewOnly": "Nur ansehen",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex 1050cd085..f4af00fad 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -707,6 +707,7 @@"bulkMediaTooLarge": "This file is too large to send inline to {{count}} recipients: at that count each file can be at most {{size}}. Use a public media URL instead, or send to fewer recipients.","bulkMediaUrlInvalid": "Use a full http:// or https:// address, like https://example.com/file.pdf.","bulkCaptionTooLong": "With an attachment the message goes out as its caption, which is limited to {{max}} characters ({{count}} now).",+ "bulkAudioNoCaption": "Audio goes out without a caption, so this text would not be sent. Clear the message or pick another kind.","send": "Send Message","sending": "Sending...","viewOnly": "View Only",diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex 3749e5be4..cf7b9a481 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -658,6 +658,7 @@"bulkMediaTooLarge": "Este archivo es demasiado grande para enviarlo directamente a {{count}} destinatarios: con esa cantidad, cada archivo puede ocupar como máximo {{size}}. Usa una URL de medios pública o envía a menos destinatarios.","bulkMediaUrlInvalid": "Usa una dirección completa con http:// o https://, por ejemplo https://example.com/file.pdf.","bulkCaptionTooLong": "Con un adjunto, el mensaje se envía como su pie de foto, que está limitado a {{max}} caracteres (ahora {{count}}).",+ "bulkAudioNoCaption": "El audio se envía sin pie, así que este texto no se enviaría. Borra el mensaje o elige otro tipo.","send": "Enviar mensaje","sending": "Enviando...","viewOnly": "Solo lectura",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex d26ec7a76..ff5b43f85 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -707,6 +707,7 @@"bulkMediaTooLarge": "Ce fichier est trop volumineux pour être envoyé directement à {{count}} destinataires : à ce nombre, chaque fichier peut faire au maximum {{size}}. Utilisez plutôt une URL de média publique ou envoyez à moins de destinataires.","bulkMediaUrlInvalid": "Saisissez une adresse complète en http:// ou https://, par exemple https://example.com/file.pdf.","bulkCaptionTooLong": "Avec une pièce jointe, le message est envoyé comme sa légende, limitée à {{max}} caractères ({{count}} actuellement).",+ "bulkAudioNoCaption": "L'audio est envoyé sans légende, ce texte ne serait donc pas envoyé. Videz le message ou choisissez un autre type.","send": "Envoyer le message","sending": "Envoi...","viewOnly": "Lecture seule",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex c627ba826..9154e904a 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -716,6 +716,7 @@"bulkMediaTooLarge": "הקובץ גדול מדי לשליחה ישירה אל {{count}} נמענים: בכמות כזו כל קובץ יכול להיות בגודל של {{size}} לכל היותר. יש להשתמש בכתובת URL ציבורית למדיה במקום זאת, או לשלוח לפחות נמענים.","bulkMediaUrlInvalid": "יש להזין כתובת מלאה שמתחילה ב-http:// או ב-https://, למשל https://example.com/file.pdf.","bulkCaptionTooLong": "כשמצורף קובץ, ההודעה נשלחת ככיתוב שלו, שמוגבל ל-{{max}} תווים (כרגע {{count}}).",+ "bulkAudioNoCaption": "שמע נשלח ללא כיתוב, ולכן הטקסט הזה לא יישלח. נקה את ההודעה או בחר סוג אחר.","send": "שליחת הודעה","sending": "שולח...","viewOnly": "צפייה בלבד",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 2f51c0967..5f1c1c198 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -707,6 +707,7 @@"bulkMediaTooLarge": "Questo file è troppo grande per inviarlo direttamente a {{count}} destinatari: con questo numero ogni file può essere al massimo di {{size}}. Usa invece un URL multimediale pubblico o invia a meno destinatari.","bulkMediaUrlInvalid": "Usa un indirizzo completo con http:// o https://, per esempio https://example.com/file.pdf.","bulkCaptionTooLong": "Con un allegato il messaggio viene inviato come sua didascalia, limitata a {{max}} caratteri (ora {{count}}).",+ "bulkAudioNoCaption": "L'audio viene inviato senza didascalia, quindi questo testo non verrebbe inviato. Svuota il messaggio o scegli un altro tipo.","send": "Invia Messaggio","sending": "Invio in corso...","viewOnly": "Sola Visualizzazione",diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex 3b4c05154..ad8a84eab 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -707,6 +707,7 @@"bulkMediaTooLarge": "이 파일은 {{count}}명의 수신자에게 직접 보내기에는 너무 큽니다. 이 인원수에서는 파일당 최대 {{size}}까지 가능합니다. 대신 공개 미디어 URL을 사용하거나 수신자 수를 줄이세요.","bulkMediaUrlInvalid": "http:// 또는 https://로 시작하는 전체 주소를 입력하세요. 예: https://example.com/file.pdf","bulkCaptionTooLong": "첨부 파일이 있으면 메시지가 캡션으로 전송되며, 캡션은 최대 {{max}}자입니다(현재 {{count}}자).",+ "bulkAudioNoCaption": "오디오는 캡션 없이 전송되므로 이 텍스트는 전송되지 않습니다. 메시지를 비우거나 다른 유형을 선택하세요.","send": "메시지 보내기","sending": "보내는 중...","viewOnly": "읽기 전용",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex c9bf30bfa..421a3d556 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -658,6 +658,7 @@"bulkMediaTooLarge": "Este arquivo é grande demais para enviar diretamente a {{count}} destinatários: com essa quantidade, cada arquivo pode ter no máximo {{size}}. Use uma URL de mídia pública ou envie para menos destinatários.","bulkMediaUrlInvalid": "Use um endereço completo com http:// ou https://, por exemplo https://example.com/file.pdf.","bulkCaptionTooLong": "Com um anexo, a mensagem é enviada como a legenda dele, que tem limite de {{max}} caracteres (agora {{count}}).",+ "bulkAudioNoCaption": "O áudio é enviado sem legenda, então este texto não seria enviado. Limpe a mensagem ou escolha outro tipo.","send": "Enviar mensagem","sending": "Enviando...","viewOnly": "Somente leitura",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex dae4bc14d..86b154ee2 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -707,6 +707,7 @@"bulkMediaTooLarge": "ఈ ఫైల్ను {{count}} గ్రహీతలకు నేరుగా పంపడానికి ఇది చాలా పెద్దది: ఈ సంఖ్యలో ఒక్కో ఫైల్ గరిష్ఠంగా {{size}} ఉండవచ్చు. దానికి బదులుగా పబ్లిక్ మీడియా URLని ఉపయోగించండి లేదా తక్కువ మంది గ్రహీతలకు పంపండి.","bulkMediaUrlInvalid": "http:// లేదా https://తో మొదలయ్యే పూర్తి చిరునామాను ఉపయోగించండి, ఉదా: https://example.com/file.pdf.","bulkCaptionTooLong": "అటాచ్మెంట్ ఉన్నప్పుడు సందేశం దాని క్యాప్షన్గా పంపబడుతుంది, దాని పరిమితి {{max}} అక్షరాలు (ప్రస్తుతం {{count}}).",+ "bulkAudioNoCaption": "ఆడియో శీర్షిక లేకుండా పంపబడుతుంది, కాబట్టి ఈ వచనం పంపబడదు. సందేశాన్ని ఖాళీ చేయండి లేదా వేరే రకాన్ని ఎంచుకోండి.","send": "సందేశం పంపు","sending": "పంపుతోంది...","viewOnly": "చూడటానికి మాత్రమే",diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.jsonindex 979428bf7..c634cbfd5 100644--- a/dashboard/src/i18n/locales/tr.json+++ b/dashboard/src/i18n/locales/tr.json@@ -707,6 +707,7 @@"bulkMediaTooLarge": "Bu dosya {{count}} alıcıya doğrudan gönderilemeyecek kadar büyük: bu alıcı sayısında dosya en fazla {{size}} olabilir. Bunun yerine herkese açık bir medya URL'si kullanın veya daha az alıcıya gönderin.","bulkMediaUrlInvalid": "http:// veya https:// ile başlayan tam bir adres girin, örneğin https://example.com/file.pdf.","bulkCaptionTooLong": "Dosya eklendiğinde mesaj, dosyanın açıklaması olarak gönderilir ve açıklama en fazla {{max}} karakter olabilir (şu an {{count}}).",+ "bulkAudioNoCaption": "Ses açıklama olmadan gönderilir, bu yüzden bu metin gönderilmez. Mesajı temizleyin veya başka bir tür seçin.","send": "Mesajı Gönder","sending": "Gönderiliyor...","viewOnly": "Yalnızca Görüntüle",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex 4af7d264a..80327b39d 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -707,6 +707,7 @@"bulkMediaTooLarge": "此文件太大,无法直接发送给 {{count}} 位接收者:在这个人数下,每个文件最大只能为 {{size}}。请改用公开的媒体 URL,或减少接收者数量。","bulkMediaUrlInvalid": "请输入以 http:// 或 https:// 开头的完整地址,例如 https://example.com/file.pdf。","bulkCaptionTooLong": "添加附件后,消息将作为附件的说明文字发送,说明文字最多 {{max}} 个字符(当前 {{count}} 个)。",+ "bulkAudioNoCaption": "音频发送时不带说明文字,因此这段文字不会被发送。请清空消息或选择其他类型。","send": "发送消息","sending": "正在发送...","viewOnly": "仅查看",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 0f2703bc6..109e21dde 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -707,6 +707,7 @@"bulkMediaTooLarge": "此檔案太大,無法直接傳送給 {{count}} 位收件人:以這個人數計,每個檔案最大只能為 {{size}}。請改用公開的媒體 URL,或減少收件人數目。","bulkMediaUrlInvalid": "請輸入以 http:// 或 https:// 開頭的完整地址,例如 https://example.com/file.pdf。","bulkCaptionTooLong": "加入附件後,訊息會作為附件的說明文字傳送,說明文字最多 {{max}} 個字元(目前 {{count}} 個)。",+ "bulkAudioNoCaption": "音訊傳送時不附說明文字,因此這段文字不會被傳送。請清除訊息或選擇其他類型。","send": "傳送訊息","sending": "正在傳送...","viewOnly": "僅檢視",diff --git a/dashboard/src/pages/MessageTester.test.ts b/dashboard/src/pages/MessageTester.test.tsindex 88df31d30..fe1578455 100644--- a/dashboard/src/pages/MessageTester.test.ts+++ b/dashboard/src/pages/MessageTester.test.ts@@ -195,7 +195,9 @@ test('a media URL without http(s) keeps Send disabled', async () => {stubGateway();const container = await renderBulkAsWriter();type(container, '#mt-11', '15550000001');- type(container, '#mt-3', 'cdn.example.com/pricelist.pdf');+ // With text present the form is otherwise valid, so only the URL guard can hold Send.+ type(container, '#mt-12', 'Price list attached');+ type(container, '#mt-3', 'https:/cdn.example.com/pricelist.pdf');await rtl.screen.findByText('Use a full http:// or https:// address, like https://example.com/file.pdf.');assert.equal(sendButton().disabled, true);@@ -217,6 +219,19 @@ test('attaching a file holds the message to the caption limit', async () => {assert.equal(sendButton().disabled, true);});+test('text next to an audio attachment keeps Send disabled, since audio carries no caption', async () => {+ stubGateway();+ const container = await renderBulkAsWriter();+ type(container, '#mt-11', '15550000001');+ type(container, '#mt-3', 'https://cdn.example.com/jingle.mp3');+ await rtl.waitFor(() => assert.equal(sendButton().disabled, false));++ type(container, '#mt-12', 'Listen to our new jingle');++ await rtl.screen.findByText(/Audio goes out without a caption/);+ assert.equal(sendButton().disabled, true);+});+test('a media file that cannot be read is reported and not attached', async () => {stubGateway();const readAsDataURL = globalThis.FileReader.prototype.readAsDataURL;diff --git a/dashboard/src/pages/MessageTester.tsx b/dashboard/src/pages/MessageTester.tsxindex 7faf92b27..094017ea1 100644--- a/dashboard/src/pages/MessageTester.tsx+++ b/dashboard/src/pages/MessageTester.tsx@@ -18,6 +18,7 @@ import {BULK_INLINE_MEDIA_MAX_BYTES,BULK_MEDIA_KINDS,buildBulkMessages,+ captionLength,formatFileSize,inlineMediaBudgetBytes,isHttpMediaUrl,@@ -297,7 +298,11 @@ export function MessageTester() {mediaFile.base64.length * bulkRecipientList.length > BULK_INLINE_MEDIA_MAX_BYTES;const bulkMediaUrlInvalid =messageType === 'bulk' && !mediaFile && mediaUrl.trim() !== '' && !isHttpMediaUrl(mediaUrl);- const bulkCaptionTooLong = bulkAttachment !== null && content.length > BULK_CAPTION_MAX_LENGTH;+ // Audio goes out without a caption (the bulk service does not forward one), so text next to an audio+ // attachment would be dropped while the batch reports success. Refuse it instead of sending half.+ const bulkAudioWithText = bulkAttachment?.kind === 'audio' && content.trim().length > 0;+ const bulkCaptionTooLong =+ bulkAttachment !== null && bulkAttachment.kind !== 'audio' && captionLength(content) > BULK_CAPTION_MAX_LENGTH;// Per-type required-field validation for the newer types; text/media keep their original behavior// (the backend stays the authoritative validator either way).@@ -317,6 +322,7 @@ export function MessageTester() {(content.trim().length > 0 || bulkAttachment !== null) &&!bulkMediaTooLarge &&!bulkMediaUrlInvalid &&+ !bulkAudioWithText &&!bulkCaptionTooLong &&bulkRecipientList.length > 0 &&bulkRecipientList.length <= BULK_MAX_RECIPIENTS &&@@ -942,9 +948,14 @@ export function MessageTester() {rows={4}/><span className="hint error" role="status">- {bulkCaptionTooLong- ? t('messageTester.bulkCaptionTooLong', { max: BULK_CAPTION_MAX_LENGTH, count: content.length })- : ''}+ {bulkAudioWithText+ ? t('messageTester.bulkAudioNoCaption')+ : bulkCaptionTooLong+ ? t('messageTester.bulkCaptionTooLong', {+ max: BULK_CAPTION_MAX_LENGTH,+ count: captionLength(content),+ })+ : ''}</span></div>{mediaSourceFields}diff --git a/dashboard/src/utils/bulkMedia.test.ts b/dashboard/src/utils/bulkMedia.test.tsindex 9012a9b9a..50942a924 100644--- a/dashboard/src/utils/bulkMedia.test.ts+++ b/dashboard/src/utils/bulkMedia.test.ts@@ -2,6 +2,7 @@ import { test } from 'node:test';import assert from 'node:assert/strict';import {buildBulkMessages,+ captionLength,filenameFromUrl,formatFileSize,inlineMediaBudgetBytes,@@ -49,6 +50,16 @@ test('only http and https URLs count as media URLs', () => {assert.equal(isHttpMediaUrl('file:///etc/passwd'), false);assert.equal(isHttpMediaUrl('data:application/pdf;base64,QUJD'), false);assert.equal(isHttpMediaUrl('ftp://cdn.example.com/a.pdf'), false);+ // A URL parser repairs these, but the server would decode them as base64.+ assert.equal(isHttpMediaUrl('https:/cdn.example.com/a.pdf'), false);+ assert.equal(isHttpMediaUrl('https:cdn.example.com/a.pdf'), false);+ assert.equal(isHttpMediaUrl('http:\\\\cdn.example.com\\a.pdf'), false);+});++test('counts a caption the way the server does, one per emoji', () => {+ assert.equal(captionLength('hello'), 5);+ assert.equal(captionLength('🎉🔥'), 2);+ assert.equal(captionLength('❤️'), 1);});test('a URL that is not http(s) gives no attachment', () => {diff --git a/dashboard/src/utils/bulkMedia.ts b/dashboard/src/utils/bulkMedia.tsindex 4bfeb4402..7059551bb 100644--- a/dashboard/src/utils/bulkMedia.ts+++ b/dashboard/src/utils/bulkMedia.ts@@ -34,15 +34,28 @@ const KIND_BY_EXTENSION: Record<string, BulkMediaKind> = {wav: 'audio',};+// The server treats a media string as a URL only when it starts with http:// or https:// and decodes+// anything else as base64. A URL parser alone repairs `https:/host/a.pdf` or `https:host/a.pdf`, so the+// raw string has to carry the prefix too, or those typos go out as a file of garbage bytes.export function isHttpMediaUrl(url: string): boolean {+ const trimmed = url.trim();+ if (!/^https?:\/\//i.test(trimmed)) return false;try {- const { protocol } = new URL(url.trim());+ const { protocol } = new URL(trimmed);return protocol === 'http:' || protocol === 'https:';} catch {return false;}}+// Caption length the way the server's @MaxLength counts it (validator.js isLength): a surrogate pair+// is one character and a variation selector is none, so an emoji does not count twice.+export function captionLength(text: string): number {+ const surrogatePairs = text.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g)?.length ?? 0;+ const presentationSequences = text.match(/[^️︎][️︎]/g)?.length ?? 0;+ return text.length - presentationSequences - surrogatePairs;+}+export function inlineMediaBudgetBytes(recipientCount: number): number {return Math.floor((BULK_INLINE_MEDIA_MAX_BYTES / Math.max(recipientCount, 1)) * 0.75);}