Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(dashboard): set a webhook signing secret and custom headers

Yudhi Armyndharis741e61f73791
diff --git a/dashboard/src/hooks/queries.ts b/dashboard/src/hooks/queries.ts
index 1afdb6e2c..e6dc8ecdb 100644
--- a/dashboard/src/hooks/queries.ts
+++ b/dashboard/src/hooks/queries.ts
@@ -9,8 +9,8 @@ import {
pluginsApi,
pluginInstancesApi,
statsApi,
- type Webhook,
- type WebhookFilters,
+ type CreateWebhookRequest,
+ type UpdateWebhookRequest,
type TemplatePayload,
type StatsPeriod,
type CreateInstanceInput,
@@ -101,8 +101,8 @@ export function useWebhooksQuery() {
export function useCreateWebhookMutation() {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: (params: { sessionId: string; url: string; events: string[]; filters?: WebhookFilters | null }) =>
- webhookApi.create(params.sessionId, { url: params.url, events: params.events, filters: params.filters }),
+ mutationFn: ({ sessionId, ...body }: CreateWebhookRequest & { sessionId: string }) =>
+ webhookApi.create(sessionId, body),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.webhooks });
},
@@ -112,7 +112,7 @@ export function useCreateWebhookMutation() {
export function useUpdateWebhookMutation() {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: (params: { sessionId: string; id: string; data: Partial<Webhook> }) =>
+ mutationFn: (params: { sessionId: string; id: string; data: UpdateWebhookRequest }) =>
webhookApi.update(params.sessionId, params.id, params.data),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.webhooks });
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index 0f24c9de3..4df0ea1a3 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -564,6 +564,33 @@
"call.missed": "عندما لا يتم الرد على مكالمة",
"status.received": "عندما تنشر جهة اتصال حالة",
"all": "كل الأحداث"
+ },
+ "auth": {
+ "title": "مصادقة التسليم",
+ "hint": "اختياري. لا تُعرض القيم المخزنة مرة أخرى بعد الحفظ.",
+ "editHint": "لا يُعرض السر والترويسات المخزنة أبدًا. اترك هذا القسم دون تغيير للاحتفاظ بها.",
+ "secret": "سر التوقيع",
+ "secretHint": "من 16 إلى 255 حرفًا. يحمل كل تسليم توقيع HMAC-SHA256 في الترويسة X-OpenWA-Signature.",
+ "secretKeepPlaceholder": "اتركه فارغًا للاحتفاظ بالسر الحالي",
+ "generateSecret": "توليد",
+ "copySecret": "نسخ",
+ "secretCopied": "تم نسخ سر التوقيع",
+ "removeSecret": "إيقاف توقيع عمليات التسليم (إزالة السر)",
+ "headers": "ترويسات مخصصة",
+ "headerName": "اسم الترويسة",
+ "headerValue": "قيمة الترويسة",
+ "addHeader": "إضافة ترويسة",
+ "removeHeader": "إزالة الترويسة",
+ "replaceHeaders": "استبدال الترويسات المخصصة",
+ "replaceHint": "تستبدل هذه الصفوف كل الترويسات المخزنة. عند عدم وجود صفوف تُزال الترويسات المخزنة.",
+ "errors": {
+ "headerName": "يمكن أن تحتوي أسماء الترويسات على الحروف والأرقام والشرطات فقط.",
+ "headerValue": "قيم الترويسات محدودة بـ 1024 حرفًا، دون أحرف تحكم أو أحرف خارج Latin-1.",
+ "headerReserved": "ترويسات Content-Type و User-Agent و X-OpenWA-* وترويسات الاتصال تضبطها البوابة ولا يمكن استخدامها.",
+ "headerDuplicate": "لا يمكن استخدام اسم الترويسة إلا مرة واحدة.",
+ "tooMany": "يُسمح بـ 50 ترويسة مخصصة كحد أقصى.",
+ "secretLength": "يجب أن يتراوح طول سر التوقيع بين 16 و 255 حرفًا."
+ }
}
},
"templates": {
diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json
index 8df63c045..55bef91c1 100644
--- a/dashboard/src/i18n/locales/de.json
+++ b/dashboard/src/i18n/locales/de.json
@@ -539,6 +539,33 @@
"call.missed": "Wenn ein Anruf unbeantwortet bleibt",
"status.received": "Wenn ein Kontakt einen Status veröffentlicht",
"all": "Alle Ereignisse"
+ },
+ "auth": {
+ "title": "Zustellungsauthentifizierung",
+ "hint": "Optional. Gespeicherte Werte werden nach dem Speichern nie wieder angezeigt.",
+ "editHint": "Das gespeicherte Geheimnis und die Header werden nie angezeigt. Lass diesen Abschnitt unverändert, um sie zu behalten.",
+ "secret": "Signaturgeheimnis",
+ "secretHint": "16 bis 255 Zeichen. Jede Zustellung trägt eine HMAC-SHA256-Signatur im Header X-OpenWA-Signature.",
+ "secretKeepPlaceholder": "Leer lassen, um das aktuelle Geheimnis zu behalten",
+ "generateSecret": "Generieren",
+ "copySecret": "Kopieren",
+ "secretCopied": "Signaturgeheimnis kopiert",
+ "removeSecret": "Zustellungen nicht mehr signieren (Geheimnis entfernen)",
+ "headers": "Benutzerdefinierte Header",
+ "headerName": "Header-Name",
+ "headerValue": "Header-Wert",
+ "addHeader": "Header hinzufügen",
+ "removeHeader": "Header entfernen",
+ "replaceHeaders": "Benutzerdefinierte Header ersetzen",
+ "replaceHint": "Diese Zeilen ersetzen alle gespeicherten Header. Ohne Zeilen werden die gespeicherten Header entfernt.",
+ "errors": {
+ "headerName": "Header-Namen dürfen nur Buchstaben, Ziffern und Bindestriche enthalten.",
+ "headerValue": "Header-Werte sind auf 1024 Zeichen begrenzt, ohne Steuerzeichen und ohne Zeichen außerhalb von Latin-1.",
+ "headerReserved": "Content-Type, User-Agent, X-OpenWA-* und Verbindungs-Header setzt das Gateway selbst; sie können nicht verwendet werden.",
+ "headerDuplicate": "Jeder Header-Name darf nur einmal vorkommen.",
+ "tooMany": "Höchstens 50 benutzerdefinierte Header sind erlaubt.",
+ "secretLength": "Das Signaturgeheimnis muss 16 bis 255 Zeichen lang sein."
+ }
}
},
"templates": {
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index 29f21e5ec..567d61d7b 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -539,6 +539,33 @@
"call.missed": "When a call goes unanswered",
"status.received": "When a contact posts a status",
"all": "All events"
+ },
+ "auth": {
+ "title": "Delivery authentication",
+ "hint": "Optional. Stored values are never shown again after saving.",
+ "editHint": "The stored secret and headers are never shown. Leave this section untouched to keep them.",
+ "secret": "Signing secret",
+ "secretHint": "16 to 255 characters. Each delivery carries an HMAC-SHA256 signature in the X-OpenWA-Signature header.",
+ "secretKeepPlaceholder": "Leave blank to keep the current secret",
+ "generateSecret": "Generate",
+ "copySecret": "Copy",
+ "secretCopied": "Signing secret copied",
+ "removeSecret": "Stop signing deliveries (remove the secret)",
+ "headers": "Custom headers",
+ "headerName": "Header name",
+ "headerValue": "Header value",
+ "addHeader": "Add header",
+ "removeHeader": "Remove header",
+ "replaceHeaders": "Replace custom headers",
+ "replaceHint": "These rows replace every stored header. With no rows, the stored headers are removed.",
+ "errors": {
+ "headerName": "Header names may contain only letters, digits and hyphens.",
+ "headerValue": "Header values are limited to 1024 characters, without control characters or characters outside Latin-1.",
+ "headerReserved": "Content-Type, User-Agent, X-OpenWA-* and connection headers are set by the gateway and cannot be used.",
+ "headerDuplicate": "Each header name can be used only once.",
+ "tooMany": "At most 50 custom headers are allowed.",
+ "secretLength": "The signing secret must be 16 to 255 characters long."
+ }
}
},
"templates": {
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index 6acbc8ec2..44d3cba7e 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -545,6 +545,33 @@
"call.missed": "Cuando una llamada no se contesta",
"status.received": "Cuando un contacto publica un estado",
"all": "Todos los eventos"
+ },
+ "auth": {
+ "title": "Autenticación de entrega",
+ "hint": "Opcional. Los valores guardados no se vuelven a mostrar después de guardar.",
+ "editHint": "El secreto y los encabezados guardados nunca se muestran. Deja esta sección sin cambios para conservarlos.",
+ "secret": "Secreto de firma",
+ "secretHint": "De 16 a 255 caracteres. Cada entrega lleva una firma HMAC-SHA256 en el encabezado X-OpenWA-Signature.",
+ "secretKeepPlaceholder": "Déjalo vacío para conservar el secreto actual",
+ "generateSecret": "Generar",
+ "copySecret": "Copiar",
+ "secretCopied": "Secreto de firma copiado",
+ "removeSecret": "Dejar de firmar las entregas (eliminar el secreto)",
+ "headers": "Encabezados personalizados",
+ "headerName": "Nombre del encabezado",
+ "headerValue": "Valor del encabezado",
+ "addHeader": "Añadir encabezado",
+ "removeHeader": "Quitar encabezado",
+ "replaceHeaders": "Reemplazar los encabezados personalizados",
+ "replaceHint": "Estas filas reemplazan todos los encabezados guardados. Sin filas, se eliminan los encabezados guardados.",
+ "errors": {
+ "headerName": "Los nombres de encabezado solo pueden contener letras, dígitos y guiones.",
+ "headerValue": "Los valores de encabezado tienen un máximo de 1024 caracteres, sin caracteres de control ni caracteres fuera de Latin-1.",
+ "headerReserved": "Content-Type, User-Agent, X-OpenWA-* y los encabezados de conexión los establece la pasarela y no se pueden usar.",
+ "headerDuplicate": "Cada nombre de encabezado solo puede usarse una vez.",
+ "tooMany": "Se permiten como máximo 50 encabezados personalizados.",
+ "secretLength": "El secreto de firma debe tener entre 16 y 255 caracteres."
+ }
}
},
"apiKeys": {
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index ef5a714d6..4a932b6ef 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -545,6 +545,33 @@
"call.missed": "Lorsqu'un appel reste sans réponse",
"status.received": "Lorsqu'un contact publie un statut",
"all": "Tous les événements"
+ },
+ "auth": {
+ "title": "Authentification des livraisons",
+ "hint": "Facultatif. Les valeurs enregistrées ne sont plus jamais affichées.",
+ "editHint": "Le secret et les en-têtes enregistrés ne sont jamais affichés. Laissez cette section intacte pour les conserver.",
+ "secret": "Secret de signature",
+ "secretHint": "De 16 à 255 caractères. Chaque livraison porte une signature HMAC-SHA256 dans l'en-tête X-OpenWA-Signature.",
+ "secretKeepPlaceholder": "Laissez vide pour conserver le secret actuel",
+ "generateSecret": "Générer",
+ "copySecret": "Copier",
+ "secretCopied": "Secret de signature copié",
+ "removeSecret": "Ne plus signer les livraisons (supprimer le secret)",
+ "headers": "En-têtes personnalisés",
+ "headerName": "Nom de l'en-tête",
+ "headerValue": "Valeur de l'en-tête",
+ "addHeader": "Ajouter un en-tête",
+ "removeHeader": "Retirer l'en-tête",
+ "replaceHeaders": "Remplacer les en-têtes personnalisés",
+ "replaceHint": "Ces lignes remplacent tous les en-têtes enregistrés. Sans ligne, les en-têtes enregistrés sont supprimés.",
+ "errors": {
+ "headerName": "Les noms d'en-tête ne peuvent contenir que des lettres, des chiffres et des tirets.",
+ "headerValue": "Les valeurs d'en-tête sont limitées à 1024 caractères, sans caractères de contrôle ni caractères hors Latin-1.",
+ "headerReserved": "Content-Type, User-Agent, X-OpenWA-* et les en-têtes de connexion sont définis par la passerelle et ne peuvent pas être utilisés.",
+ "headerDuplicate": "Chaque nom d'en-tête ne peut être utilisé qu'une seule fois.",
+ "tooMany": "50 en-têtes personnalisés au maximum sont autorisés.",
+ "secretLength": "Le secret de signature doit comporter entre 16 et 255 caractères."
+ }
}
},
"templates": {
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index 34e1002e8..2f65e2d03 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -546,6 +546,33 @@
"call.missed": "כאשר שיחה לא נענית",
"status.received": "כאשר איש קשר מפרסם סטטוס",
"all": "כל האירועים"
+ },
+ "auth": {
+ "title": "אימות משלוח",
+ "hint": "אופציונלי. ערכים שמורים לא מוצגים שוב לאחר השמירה.",
+ "editHint": "הסוד והכותרות השמורים לעולם אינם מוצגים. השאירו את החלק הזה ללא שינוי כדי לשמור אותם.",
+ "secret": "סוד חתימה",
+ "secretHint": "16 עד 255 תווים. כל משלוח נושא חתימת HMAC-SHA256 בכותרת X-OpenWA-Signature.",
+ "secretKeepPlaceholder": "השאירו ריק כדי לשמור את הסוד הנוכחי",
+ "generateSecret": "יצירה",
+ "copySecret": "העתקה",
+ "secretCopied": "סוד החתימה הועתק",
+ "removeSecret": "הפסקת חתימת המשלוחים (הסרת הסוד)",
+ "headers": "כותרות מותאמות",
+ "headerName": "שם הכותרת",
+ "headerValue": "ערך הכותרת",
+ "addHeader": "הוספת כותרת",
+ "removeHeader": "הסרת כותרת",
+ "replaceHeaders": "החלפת הכותרות המותאמות",
+ "replaceHint": "השורות האלה מחליפות את כל הכותרות השמורות. ללא שורות, הכותרות השמורות מוסרות.",
+ "errors": {
+ "headerName": "שמות כותרות יכולים להכיל רק אותיות, ספרות ומקפים.",
+ "headerValue": "ערכי כותרות מוגבלים ל-1024 תווים, ללא תווי בקרה או תווים מחוץ ל-Latin-1.",
+ "headerReserved": "Content-Type, User-Agent, X-OpenWA-* וכותרות חיבור נקבעות על ידי השער ואי אפשר להשתמש בהן.",
+ "headerDuplicate": "ניתן להשתמש בכל שם כותרת פעם אחת בלבד.",
+ "tooMany": "מותרות לכל היותר 50 כותרות מותאמות.",
+ "secretLength": "אורך סוד החתימה חייב להיות בין 16 ל-255 תווים."
+ }
}
},
"templates": {
diff --git a/dashboard/src/i18n/locales/hi.json b/dashboard/src/i18n/locales/hi.json
index e895fdc5c..974361095 100644
--- a/dashboard/src/i18n/locales/hi.json
+++ b/dashboard/src/i18n/locales/hi.json
@@ -539,6 +539,33 @@
"call.missed": "जब कोई कॉल अनुत्तरित हो जाती है",
"status.received": "जब कोई संपर्क स्टेटस पोस्ट करता है",
"all": "सभी घटनाएँ"
+ },
+ "auth": {
+ "title": "डिलीवरी प्रमाणीकरण",
+ "hint": "वैकल्पिक। सहेजने के बाद संग्रहीत मान फिर कभी नहीं दिखाए जाते।",
+ "editHint": "संग्रहीत सीक्रेट और हेडर कभी नहीं दिखाए जाते। उन्हें बनाए रखने के लिए इस भाग को न बदलें।",
+ "secret": "साइनिंग सीक्रेट",
+ "secretHint": "16 से 255 वर्ण। हर डिलीवरी X-OpenWA-Signature हेडर में HMAC-SHA256 हस्ताक्षर के साथ भेजी जाती है।",
+ "secretKeepPlaceholder": "मौजूदा सीक्रेट रखने के लिए खाली छोड़ें",
+ "generateSecret": "जनरेट करें",
+ "copySecret": "कॉपी करें",
+ "secretCopied": "साइनिंग सीक्रेट कॉपी हो गया",
+ "removeSecret": "डिलीवरी पर हस्ताक्षर बंद करें (सीक्रेट हटाएँ)",
+ "headers": "कस्टम हेडर",
+ "headerName": "हेडर का नाम",
+ "headerValue": "हेडर का मान",
+ "addHeader": "हेडर जोड़ें",
+ "removeHeader": "हेडर हटाएँ",
+ "replaceHeaders": "कस्टम हेडर बदलें",
+ "replaceHint": "ये पंक्तियाँ सभी संग्रहीत हेडर की जगह लेती हैं। कोई पंक्ति न होने पर संग्रहीत हेडर हटा दिए जाते हैं।",
+ "errors": {
+ "headerName": "हेडर के नाम में केवल अक्षर, अंक और हाइफ़न हो सकते हैं।",
+ "headerValue": "हेडर के मान अधिकतम 1024 वर्ण के हो सकते हैं, और उनमें नियंत्रण वर्ण या Latin-1 से बाहर के वर्ण नहीं हो सकते।",
+ "headerReserved": "Content-Type, User-Agent, X-OpenWA-* और कनेक्शन हेडर गेटवे स्वयं सेट करता है; इनका उपयोग नहीं किया जा सकता।",
+ "headerDuplicate": "हर हेडर नाम केवल एक बार उपयोग किया जा सकता है।",
+ "tooMany": "अधिकतम 50 कस्टम हेडर की अनुमति है।",
+ "secretLength": "साइनिंग सीक्रेट 16 से 255 वर्णों का होना चाहिए।"
+ }
}
},
"templates": {
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index 49e3bc30a..bac66a731 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -545,6 +545,33 @@
"call.missed": "Quando una chiamata resta senza risposta",
"status.received": "Quando un contatto pubblica uno stato",
"all": "Tutti gli eventi"
+ },
+ "auth": {
+ "title": "Autenticazione delle consegne",
+ "hint": "Facoltativo. I valori salvati non vengono più mostrati.",
+ "editHint": "Il segreto e le intestazioni salvati non vengono mai mostrati. Lascia invariata questa sezione per mantenerli.",
+ "secret": "Segreto di firma",
+ "secretHint": "Da 16 a 255 caratteri. Ogni consegna include una firma HMAC-SHA256 nell'intestazione X-OpenWA-Signature.",
+ "secretKeepPlaceholder": "Lascia vuoto per mantenere il segreto attuale",
+ "generateSecret": "Genera",
+ "copySecret": "Copia",
+ "secretCopied": "Segreto di firma copiato",
+ "removeSecret": "Smetti di firmare le consegne (rimuovi il segreto)",
+ "headers": "Intestazioni personalizzate",
+ "headerName": "Nome intestazione",
+ "headerValue": "Valore intestazione",
+ "addHeader": "Aggiungi intestazione",
+ "removeHeader": "Rimuovi intestazione",
+ "replaceHeaders": "Sostituisci le intestazioni personalizzate",
+ "replaceHint": "Queste righe sostituiscono tutte le intestazioni salvate. Senza righe, le intestazioni salvate vengono rimosse.",
+ "errors": {
+ "headerName": "I nomi delle intestazioni possono contenere solo lettere, cifre e trattini.",
+ "headerValue": "I valori delle intestazioni sono limitati a 1024 caratteri, senza caratteri di controllo né caratteri al di fuori di Latin-1.",
+ "headerReserved": "Content-Type, User-Agent, X-OpenWA-* e le intestazioni di connessione sono impostate dal gateway e non possono essere usate.",
+ "headerDuplicate": "Ogni nome di intestazione può essere usato una sola volta.",
+ "tooMany": "Sono consentite al massimo 50 intestazioni personalizzate.",
+ "secretLength": "Il segreto di firma deve essere lungo da 16 a 255 caratteri."
+ }
}
},
"templates": {
diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.json
index c436543d7..be64525a7 100644
--- a/dashboard/src/i18n/locales/ko.json
+++ b/dashboard/src/i18n/locales/ko.json
@@ -539,6 +539,33 @@
"call.missed": "통화에 응답하지 않았을 때",
"status.received": "연락처가 상태를 게시했을 때",
"all": "모든 이벤트"
+ },
+ "auth": {
+ "title": "전송 인증",
+ "hint": "선택 사항입니다. 저장된 값은 저장 후 다시 표시되지 않습니다.",
+ "editHint": "저장된 시크릿과 헤더는 표시되지 않습니다. 유지하려면 이 섹션을 변경하지 마세요.",
+ "secret": "서명 시크릿",
+ "secretHint": "16~255자. 모든 전송에는 X-OpenWA-Signature 헤더에 HMAC-SHA256 서명이 포함됩니다.",
+ "secretKeepPlaceholder": "현재 시크릿을 유지하려면 비워 두세요",
+ "generateSecret": "생성",
+ "copySecret": "복사",
+ "secretCopied": "서명 시크릿이 복사되었습니다",
+ "removeSecret": "전송 서명 중지 (시크릿 제거)",
+ "headers": "사용자 지정 헤더",
+ "headerName": "헤더 이름",
+ "headerValue": "헤더 값",
+ "addHeader": "헤더 추가",
+ "removeHeader": "헤더 제거",
+ "replaceHeaders": "사용자 지정 헤더 교체",
+ "replaceHint": "이 행들이 저장된 모든 헤더를 대체합니다. 행이 없으면 저장된 헤더가 제거됩니다.",
+ "errors": {
+ "headerName": "헤더 이름에는 문자, 숫자, 하이픈만 사용할 수 있습니다.",
+ "headerValue": "헤더 값은 최대 1024자이며 제어 문자나 Latin-1 범위 밖의 문자를 사용할 수 없습니다.",
+ "headerReserved": "Content-Type, User-Agent, X-OpenWA-* 및 연결 헤더는 게이트웨이가 설정하므로 사용할 수 없습니다.",
+ "headerDuplicate": "각 헤더 이름은 한 번만 사용할 수 있습니다.",
+ "tooMany": "사용자 지정 헤더는 최대 50개까지 허용됩니다.",
+ "secretLength": "서명 시크릿은 16~255자여야 합니다."
+ }
}
},
"templates": {
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index 2135b6242..2f0cf89e4 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -545,6 +545,33 @@
"call.missed": "Quando uma chamada não é atendida",
"status.received": "Quando um contato publica um status",
"all": "Todos os eventos"
+ },
+ "auth": {
+ "title": "Autenticação de entrega",
+ "hint": "Opcional. Os valores salvos nunca mais são exibidos.",
+ "editHint": "O segredo e os cabeçalhos salvos nunca são exibidos. Deixe esta seção inalterada para mantê-los.",
+ "secret": "Segredo de assinatura",
+ "secretHint": "De 16 a 255 caracteres. Cada entrega leva uma assinatura HMAC-SHA256 no cabeçalho X-OpenWA-Signature.",
+ "secretKeepPlaceholder": "Deixe em branco para manter o segredo atual",
+ "generateSecret": "Gerar",
+ "copySecret": "Copiar",
+ "secretCopied": "Segredo de assinatura copiado",
+ "removeSecret": "Parar de assinar as entregas (remover o segredo)",
+ "headers": "Cabeçalhos personalizados",
+ "headerName": "Nome do cabeçalho",
+ "headerValue": "Valor do cabeçalho",
+ "addHeader": "Adicionar cabeçalho",
+ "removeHeader": "Remover cabeçalho",
+ "replaceHeaders": "Substituir os cabeçalhos personalizados",
+ "replaceHint": "Estas linhas substituem todos os cabeçalhos salvos. Sem linhas, os cabeçalhos salvos são removidos.",
+ "errors": {
+ "headerName": "Nomes de cabeçalho podem conter apenas letras, dígitos e hifens.",
+ "headerValue": "Valores de cabeçalho são limitados a 1024 caracteres, sem caracteres de controle nem caracteres fora do Latin-1.",
+ "headerReserved": "Content-Type, User-Agent, X-OpenWA-* e cabeçalhos de conexão são definidos pelo gateway e não podem ser usados.",
+ "headerDuplicate": "Cada nome de cabeçalho pode ser usado apenas uma vez.",
+ "tooMany": "São permitidos no máximo 50 cabeçalhos personalizados.",
+ "secretLength": "O segredo de assinatura deve ter de 16 a 255 caracteres."
+ }
}
},
"apiKeys": {
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index 0ed9e3aa1..c0cfd60f9 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -539,6 +539,33 @@
"call.missed": "కాల్‌కు ఎవరూ సమాధానం ఇవ్వనప్పుడు",
"status.received": "కాంటాక్ట్ స్టేటస్ పోస్ట్ చేసినప్పుడు",
"all": "అన్ని ఈవెంట్స్"
+ },
+ "auth": {
+ "title": "డెలివరీ ప్రామాణీకరణ",
+ "hint": "ఐచ్ఛికం. సేవ్ చేసిన తర్వాత నిల్వ చేసిన విలువలు మళ్లీ చూపబడవు.",
+ "editHint": "నిల్వ చేసిన సీక్రెట్ మరియు హెడర్‌లు ఎప్పుడూ చూపబడవు. వాటిని ఉంచడానికి ఈ విభాగాన్ని మార్చకండి.",
+ "secret": "సైనింగ్ సీక్రెట్",
+ "secretHint": "16 నుండి 255 అక్షరాలు. ప్రతి డెలివరీ X-OpenWA-Signature హెడర్‌లో HMAC-SHA256 సంతకాన్ని కలిగి ఉంటుంది.",
+ "secretKeepPlaceholder": "ప్రస్తుత సీక్రెట్‌ను ఉంచడానికి ఖాళీగా వదిలేయండి",
+ "generateSecret": "రూపొందించు",
+ "copySecret": "కాపీ చేయి",
+ "secretCopied": "సైనింగ్ సీక్రెట్ కాపీ అయింది",
+ "removeSecret": "డెలివరీలపై సంతకం ఆపండి (సీక్రెట్‌ను తీసివేయండి)",
+ "headers": "కస్టమ్ హెడర్‌లు",
+ "headerName": "హెడర్ పేరు",
+ "headerValue": "హెడర్ విలువ",
+ "addHeader": "హెడర్ జోడించండి",
+ "removeHeader": "హెడర్ తీసివేయండి",
+ "replaceHeaders": "కస్టమ్ హెడర్‌లను భర్తీ చేయండి",
+ "replaceHint": "ఈ వరుసలు నిల్వ చేసిన అన్ని హెడర్‌లను భర్తీ చేస్తాయి. వరుసలు లేకపోతే నిల్వ చేసిన హెడర్‌లు తీసివేయబడతాయి.",
+ "errors": {
+ "headerName": "హెడర్ పేర్లలో అక్షరాలు, అంకెలు మరియు హైఫన్‌లు మాత్రమే ఉండవచ్చు.",
+ "headerValue": "హెడర్ విలువలు గరిష్టంగా 1024 అక్షరాలు, నియంత్రణ అక్షరాలు లేదా Latin-1 వెలుపలి అక్షరాలు లేకుండా ఉండాలి.",
+ "headerReserved": "Content-Type, User-Agent, X-OpenWA-* మరియు కనెక్షన్ హెడర్‌లను గేట్‌వే సెట్ చేస్తుంది; వాటిని ఉపయోగించలేరు.",
+ "headerDuplicate": "ప్రతి హెడర్ పేరును ఒకసారి మాత్రమే ఉపయోగించవచ్చు.",
+ "tooMany": "గరిష్టంగా 50 కస్టమ్ హెడర్‌లు అనుమతించబడతాయి.",
+ "secretLength": "సైనింగ్ సీక్రెట్ 16 నుండి 255 అక్షరాల పొడవు ఉండాలి."
+ }
}
},
"templates": {
diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.json
index 0391a6622..9380ca2e4 100644
--- a/dashboard/src/i18n/locales/tr.json
+++ b/dashboard/src/i18n/locales/tr.json
@@ -539,6 +539,33 @@
"call.missed": "Bir arama yanıtsız kaldığında",
"status.received": "Bir kişi durum paylaştığında",
"all": "Tüm olaylar"
+ },
+ "auth": {
+ "title": "Teslimat kimlik doğrulaması",
+ "hint": "İsteğe bağlı. Kaydedilen değerler bir daha gösterilmez.",
+ "editHint": "Kayıtlı gizli anahtar ve başlıklar hiçbir zaman gösterilmez. Korumak için bu bölüme dokunmayın.",
+ "secret": "İmzalama gizli anahtarı",
+ "secretHint": "16 ile 255 karakter arası. Her teslimat, X-OpenWA-Signature başlığında bir HMAC-SHA256 imzası taşır.",
+ "secretKeepPlaceholder": "Mevcut gizli anahtarı korumak için boş bırakın",
+ "generateSecret": "Oluştur",
+ "copySecret": "Kopyala",
+ "secretCopied": "İmzalama gizli anahtarı kopyalandı",
+ "removeSecret": "Teslimatları imzalamayı durdur (gizli anahtarı kaldır)",
+ "headers": "Özel başlıklar",
+ "headerName": "Başlık adı",
+ "headerValue": "Başlık değeri",
+ "addHeader": "Başlık ekle",
+ "removeHeader": "Başlığı kaldır",
+ "replaceHeaders": "Özel başlıkları değiştir",
+ "replaceHint": "Bu satırlar kayıtlı tüm başlıkların yerini alır. Satır yoksa kayıtlı başlıklar kaldırılır.",
+ "errors": {
+ "headerName": "Başlık adları yalnızca harf, rakam ve kısa çizgi içerebilir.",
+ "headerValue": "Başlık değerleri en fazla 1024 karakter olabilir; kontrol karakterleri ve Latin-1 dışındaki karakterler kullanılamaz.",
+ "headerReserved": "Content-Type, User-Agent, X-OpenWA-* ve bağlantı başlıkları ağ geçidi tarafından ayarlanır ve kullanılamaz.",
+ "headerDuplicate": "Her başlık adı yalnızca bir kez kullanılabilir.",
+ "tooMany": "En fazla 50 özel başlığa izin verilir.",
+ "secretLength": "İmzalama gizli anahtarı 16 ile 255 karakter arasında olmalıdır."
+ }
}
},
"templates": {
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 3a9969665..528aee951 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -539,6 +539,33 @@
"call.missed": "来电未接听时",
"status.received": "联系人发布状态时",
"all": "所有事件"
+ },
+ "auth": {
+ "title": "投递认证",
+ "hint": "可选。保存后,已存储的值不会再次显示。",
+ "editHint": "已存储的密钥和请求头永远不会显示。保持此部分不变即可保留它们。",
+ "secret": "签名密钥",
+ "secretHint": "16 到 255 个字符。每次投递都会在 X-OpenWA-Signature 请求头中携带 HMAC-SHA256 签名。",
+ "secretKeepPlaceholder": "留空以保留当前密钥",
+ "generateSecret": "生成",
+ "copySecret": "复制",
+ "secretCopied": "已复制签名密钥",
+ "removeSecret": "停止为投递签名(删除密钥)",
+ "headers": "自定义请求头",
+ "headerName": "请求头名称",
+ "headerValue": "请求头值",
+ "addHeader": "添加请求头",
+ "removeHeader": "移除请求头",
+ "replaceHeaders": "替换自定义请求头",
+ "replaceHint": "这些行将替换所有已存储的请求头。没有任何行时,将删除已存储的请求头。",
+ "errors": {
+ "headerName": "请求头名称只能包含字母、数字和连字符。",
+ "headerValue": "请求头值最多 1024 个字符,不能包含控制字符或 Latin-1 以外的字符。",
+ "headerReserved": "Content-Type、User-Agent、X-OpenWA-* 和连接类请求头由网关设置,不能使用。",
+ "headerDuplicate": "每个请求头名称只能使用一次。",
+ "tooMany": "最多允许 50 个自定义请求头。",
+ "secretLength": "签名密钥长度必须为 16 到 255 个字符。"
+ }
}
},
"templates": {
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 1a5286755..a924164ea 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -539,6 +539,33 @@
"call.missed": "來電未接聽時",
"status.received": "聯絡人發佈狀態時",
"all": "所有事件"
+ },
+ "auth": {
+ "title": "傳送驗證",
+ "hint": "選填。儲存後,已儲存的值不會再次顯示。",
+ "editHint": "已儲存的密鑰及標頭永遠不會顯示。保持此部分不變即可保留它們。",
+ "secret": "簽署密鑰",
+ "secretHint": "16 至 255 個字元。每次傳送都會在 X-OpenWA-Signature 標頭中附上 HMAC-SHA256 簽署。",
+ "secretKeepPlaceholder": "留空以保留目前的密鑰",
+ "generateSecret": "產生",
+ "copySecret": "複製",
+ "secretCopied": "已複製簽署密鑰",
+ "removeSecret": "停止為傳送簽署(移除密鑰)",
+ "headers": "自訂標頭",
+ "headerName": "標頭名稱",
+ "headerValue": "標頭值",
+ "addHeader": "新增標頭",
+ "removeHeader": "移除標頭",
+ "replaceHeaders": "取代自訂標頭",
+ "replaceHint": "這些列會取代所有已儲存的標頭。沒有任何列時,已儲存的標頭會被移除。",
+ "errors": {
+ "headerName": "標頭名稱只可包含字母、數字及連字號。",
+ "headerValue": "標頭值最多 1024 個字元,不可包含控制字元或 Latin-1 以外的字元。",
+ "headerReserved": "Content-Type、User-Agent、X-OpenWA-* 及連線類標頭由閘道設定,不可使用。",
+ "headerDuplicate": "每個標頭名稱只可使用一次。",
+ "tooMany": "最多允許 50 個自訂標頭。",
+ "secretLength": "簽署密鑰長度必須為 16 至 255 個字元。"
+ }
}
},
"templates": {
diff --git a/dashboard/src/pages/Webhooks.css b/dashboard/src/pages/Webhooks.css
index 86088166b..3a364d8e0 100644
--- a/dashboard/src/pages/Webhooks.css
+++ b/dashboard/src/pages/Webhooks.css
@@ -29,6 +29,49 @@
color: var(--error-text);
}
+.webhooks-page .webhook-auth {
+ margin-bottom: 0.75rem;
+}
+
+.webhooks-page .webhook-auth > label {
+ display: block;
+ font-size: 0.8125rem;
+ font-weight: 600;
+ color: var(--text-secondary);
+}
+
+.webhooks-page .webhook-auth > label.webhook-auth-check {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-weight: 400;
+ color: var(--text-primary);
+}
+
+.webhooks-page .webhook-auth > .hint.error {
+ font-size: 0.75rem;
+ color: var(--error-text);
+}
+
+.webhooks-page .secret-row {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.webhooks-page .secret-row input {
+ flex: 1 1 0;
+ min-width: 0;
+}
+
+.webhooks-page .header-row input {
+ flex: 1 1 0;
+ min-width: 0;
+ height: 2.25rem;
+ padding: 0 0.625rem;
+ font-size: 0.8125rem;
+}
+
.webhooks-page .modal-body > .event-tags {
display: flex;
flex-wrap: wrap;
diff --git a/dashboard/src/pages/Webhooks.test.ts b/dashboard/src/pages/Webhooks.test.ts
index aa4a9029c..e31c33524 100644
--- a/dashboard/src/pages/Webhooks.test.ts
+++ b/dashboard/src/pages/Webhooks.test.ts
@@ -12,6 +12,8 @@ let webhookList: unknown[] = [];
let sessionList: unknown[] = [];
let createCalls = 0;
let updateCalls = 0;
+let createBody: Record<string, unknown> | undefined;
+let updateBody: Record<string, unknown> | undefined;
function jsonResponse(data: unknown, status = 200): Response {
return new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } });
@@ -25,10 +27,12 @@ function installFetchStub(): void {
if (init?.method === 'POST' && path === '/api/sessions/sess-1/webhooks') {
// Never answers: the create stays in flight, like one held up by the gateway's URL check.
createCalls++;
+ createBody = JSON.parse(String(init.body));
return new Promise<Response>(() => {});
}
if (init?.method === 'PUT' && path === '/api/sessions/sess-1/webhooks/w1') {
updateCalls++;
+ updateBody = JSON.parse(String(init.body));
return new Promise<Response>(() => {});
}
if (path === '/api/webhooks') {
@@ -69,6 +73,8 @@ afterEach(() => {
sessionList = [];
createCalls = 0;
updateCalls = 0;
+ createBody = undefined;
+ updateBody = undefined;
window.sessionStorage.setItem('openwa_user_role', 'viewer');
});
@@ -224,7 +230,15 @@ test('Create stays disabled with a hint while no event is selected', async () =>
async function openEditModal(): Promise<HTMLButtonElement> {
webhooksStatus = 200;
webhookList = [
- { id: 'w1', sessionId: 'sess-1', url: 'https://example.test/hook', events: ['message.received'], active: true },
+ {
+ id: 'w1',
+ sessionId: 'sess-1',
+ url: 'https://example.test/hook',
+ events: ['message.received'],
+ active: true,
+ secret: 'stray-secret-from-a-payload',
+ headers: { 'X-Stray': 'value' },
+ },
];
window.sessionStorage.setItem('openwa_user_role', 'operator');
renderWebhooks();
@@ -265,3 +279,135 @@ test('a second click on Save while the first update is in flight sends nothing',
await new Promise(resolve => setTimeout(resolve, 50));
assert.equal(updateCalls, 1);
});
+
+async function openCreateModal(): Promise<HTMLButtonElement> {
+ const { screen, fireEvent } = rtl;
+ webhooksStatus = 200;
+ sessionList = [{ id: 'sess-1', name: 'Main', status: 'ready', createdAt: '2026-01-01T00:00:00.000Z' }];
+ window.sessionStorage.setItem('openwa_user_role', 'operator');
+ renderWebhooks();
+ fireEvent.click(await screen.findByRole('button', { name: 'Add Webhook' }));
+ const sessionSelect = screen.getByLabelText<HTMLSelectElement>('Session');
+ await rtl.findByText(sessionSelect, 'Main');
+ fireEvent.change(sessionSelect, { target: { value: 'sess-1' } });
+ fireEvent.change(screen.getByLabelText('URL'), { target: { value: 'https://example.test/hook' } });
+ return screen.getByRole<HTMLButtonElement>('button', { name: 'Create' });
+}
+
+function addHeaderRow(name: string, value: string): void {
+ const { screen, fireEvent } = rtl;
+ fireEvent.click(screen.getByRole('button', { name: 'Add header' }));
+ const names = screen.getAllByLabelText('Header name');
+ const values = screen.getAllByLabelText('Header value');
+ fireEvent.change(names[names.length - 1], { target: { value: name } });
+ fireEvent.change(values[values.length - 1], { target: { value: value } });
+}
+
+test('a create with the authentication section left empty sends neither a secret nor headers', async () => {
+ const create = await openCreateModal();
+ rtl.fireEvent.click(create);
+ await rtl.waitFor(() => assert.equal(createCalls, 1));
+ assert.deepEqual(Object.keys(createBody!).sort(), ['events', 'filters', 'url']);
+});
+
+test('a create sends the signing secret and custom headers exactly as typed', async () => {
+ const { screen, fireEvent } = rtl;
+ const create = await openCreateModal();
+ fireEvent.change(screen.getByLabelText('Signing secret'), { target: { value: ' a-secret-of-20-chars' } });
+ addHeaderRow('Authorization', 'Bearer abc');
+ addHeaderRow('', '');
+ fireEvent.click(create);
+ await rtl.waitFor(() => assert.equal(createCalls, 1));
+ assert.equal(createBody!.secret, ' a-secret-of-20-chars');
+ assert.deepEqual(createBody!.headers, { Authorization: 'Bearer abc' });
+});
+
+test('Generate fills a 64-hex secret, and that exact value is sent', async () => {
+ const { screen, fireEvent } = rtl;
+ const create = await openCreateModal();
+ const secret = screen.getByLabelText<HTMLInputElement>('Signing secret');
+ assert.equal(screen.getByRole<HTMLButtonElement>('button', { name: 'Copy' }).disabled, true, 'nothing to copy yet');
+ fireEvent.click(screen.getByRole('button', { name: 'Generate' }));
+ assert.match(secret.value, /^[0-9a-f]{64}$/);
+ assert.equal(screen.getByRole<HTMLButtonElement>('button', { name: 'Copy' }).disabled, false);
+ fireEvent.click(create);
+ await rtl.waitFor(() => assert.equal(createCalls, 1));
+ assert.equal(createBody!.secret, secret.value);
+});
+
+test('a short secret or a bad header keeps Create disabled and says why', async () => {
+ const { screen, fireEvent } = rtl;
+ const create = await openCreateModal();
+ fireEvent.change(screen.getByLabelText('Signing secret'), { target: { value: 'too-short' } });
+ assert.equal(create.disabled, true);
+ screen.getByText('The signing secret must be 16 to 255 characters long.');
+
+ fireEvent.change(screen.getByLabelText('Signing secret'), { target: { value: '' } });
+ addHeaderRow('X-OpenWA-Signature', 'forged');
+ assert.equal(create.disabled, true);
+ screen.getByText(
+ 'Content-Type, User-Agent, X-OpenWA-* and connection headers are set by the gateway and cannot be used.',
+ );
+ fireEvent.click(create);
+ await new Promise(resolve => setTimeout(resolve, 50));
+ assert.equal(createCalls, 0);
+});
+
+test('an edit that leaves the authentication section alone sends neither a secret nor headers', async () => {
+ const { screen, fireEvent } = rtl;
+ // A stray credential in the list payload must never reach the form or the update.
+ const save = await openEditModal();
+ fireEvent.change(screen.getByLabelText('URL'), { target: { value: 'https://example.test/other' } });
+ fireEvent.click(save);
+ await rtl.waitFor(() => assert.equal(updateCalls, 1));
+ assert.equal(updateBody!.url, 'https://example.test/other');
+ assert.equal('secret' in updateBody!, false);
+ assert.equal('headers' in updateBody!, false);
+});
+
+test('an edit sends a replacement secret, or an empty one to stop signing', async () => {
+ const { screen, fireEvent } = rtl;
+ const save = await openEditModal();
+ const secret = screen.getByLabelText<HTMLInputElement>('Signing secret');
+ assert.equal(secret.value, '');
+ fireEvent.change(secret, { target: { value: 'too-short' } });
+ assert.equal(save.disabled, true);
+ fireEvent.click(screen.getByLabelText('Stop signing deliveries (remove the secret)'));
+ assert.equal(secret.disabled, true);
+ assert.equal(save.disabled, false);
+ fireEvent.click(save);
+ await rtl.waitFor(() => assert.equal(updateCalls, 1));
+ assert.equal(updateBody!.secret, '');
+ assert.equal('headers' in updateBody!, false);
+});
+
+test('an edit sends a typed secret', async () => {
+ const { screen, fireEvent } = rtl;
+ const save = await openEditModal();
+ fireEvent.change(screen.getByLabelText('Signing secret'), { target: { value: 'a-new-secret-value-1' } });
+ fireEvent.click(save);
+ await rtl.waitFor(() => assert.equal(updateCalls, 1));
+ assert.equal(updateBody!.secret, 'a-new-secret-value-1');
+});
+
+test('replacing headers sends the whole map, and no rows sends an empty map', async () => {
+ const { screen, fireEvent } = rtl;
+ let save = await openEditModal();
+ fireEvent.click(screen.getByLabelText('Replace custom headers'));
+ addHeaderRow('X-Token', '\u20ac5');
+ assert.equal(save.disabled, true, 'a value outside Latin-1 is refused');
+ fireEvent.change(screen.getByLabelText('Header value'), { target: { value: 'abc' } });
+ fireEvent.click(save);
+ await rtl.waitFor(() => assert.equal(updateCalls, 1));
+ assert.deepEqual(updateBody!.headers, { 'X-Token': 'abc' });
+ assert.equal('secret' in updateBody!, false);
+
+ rtl.cleanup();
+ queryClient?.clear();
+ updateCalls = 0;
+ save = await openEditModal();
+ fireEvent.click(screen.getByLabelText('Replace custom headers'));
+ fireEvent.click(save);
+ await rtl.waitFor(() => assert.equal(updateCalls, 1));
+ assert.deepEqual(updateBody!.headers, {});
+});
diff --git a/dashboard/src/pages/Webhooks.tsx b/dashboard/src/pages/Webhooks.tsx
index 7bc246cec..befbe1b13 100644
--- a/dashboard/src/pages/Webhooks.tsx
+++ b/dashboard/src/pages/Webhooks.tsx
@@ -11,11 +11,14 @@ import {
Check,
AlertCircle,
Filter,
+ X,
} from 'lucide-react';
import { webhookApi, type Webhook, type WebhookFilters, type WebhookFilterCondition } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { availableEventNames } from '../utils/webhookEvents';
import { filterValueLabel } from '../utils/enumLabels';
+import { buildHeaderMap, generateSecret, secretError, type HeaderRow } from '../utils/webhookAuth';
+import { copyToClipboard } from '../utils/clipboard';
import { useRole } from '../hooks/useRole';
import { useToast } from '../hooks/useToast';
import {
@@ -88,6 +91,103 @@ function FilterBadge({ filters }: { filters: WebhookFilters }) {
);
}
+// Name/value rows for the webhook's custom delivery headers. Values are plain text on purpose: a
+// password field could be autofilled with the dashboard's own API key and sent to the receiver.
+function HeaderRowsEditor({ rows, onChange }: { rows: HeaderRow[]; onChange: (rows: HeaderRow[]) => void }) {
+ const { t } = useTranslation();
+ const update = (index: number, patch: Partial<HeaderRow>) =>
+ onChange(rows.map((row, i) => (i === index ? { ...row, ...patch } : row)));
+ return (
+ <>
+ {rows.map((row, index) => (
+ <div key={index} className="filter-row header-row">
+ <input
+ type="text"
+ aria-label={t('webhooks.auth.headerName')}
+ placeholder={t('webhooks.auth.headerName')}
+ autoComplete="off"
+ spellCheck={false}
+ value={row.name}
+ onChange={e => update(index, { name: e.target.value })}
+ />
+ <input
+ type="text"
+ aria-label={t('webhooks.auth.headerValue')}
+ placeholder={t('webhooks.auth.headerValue')}
+ autoComplete="off"
+ spellCheck={false}
+ value={row.value}
+ onChange={e => update(index, { value: e.target.value })}
+ />
+ <button
+ type="button"
+ className="filter-remove"
+ title={t('webhooks.auth.removeHeader')}
+ aria-label={t('webhooks.auth.removeHeader')}
+ onClick={() => onChange(rows.filter((_, i) => i !== index))}
+ >
+ <X size={16} />
+ </button>
+ </div>
+ ))}
+ <button type="button" className="filter-add" onClick={() => onChange([...rows, { name: '', value: '' }])}>
+ <Plus size={14} />
+ {t('webhooks.auth.addHeader')}
+ </button>
+ </>
+ );
+}
+
+// The secret input with Generate and Copy. The field stays a password input, so Copy is how a generated
+// value reaches the receiver's configuration.
+function SecretField({
+ id,
+ value,
+ onChange,
+ placeholder,
+ disabled,
+}: {
+ id: string;
+ value: string;
+ onChange: (value: string) => void;
+ placeholder?: string;
+ disabled?: boolean;
+}) {
+ const { t } = useTranslation();
+ const toast = useToast();
+ return (
+ <div className="secret-row">
+ <input
+ id={id}
+ type="password"
+ autoComplete="new-password"
+ placeholder={placeholder}
+ disabled={disabled}
+ value={value}
+ onChange={e => onChange(e.target.value)}
+ />
+ <button type="button" className="btn-secondary" disabled={disabled} onClick={() => onChange(generateSecret())}>
+ {t('webhooks.auth.generateSecret')}
+ </button>
+ <button
+ type="button"
+ className="btn-secondary"
+ disabled={disabled || !value}
+ onClick={async () => {
+ if (await copyToClipboard(value)) toast.success(t('webhooks.auth.secretCopied'));
+ }}
+ >
+ {t('webhooks.auth.copySecret')}
+ </button>
+ </div>
+ );
+}
+
+const emptyNewAuth = { secret: '', headers: [] as HeaderRow[] };
+// The stored secret and headers are never returned, so an edit starts blank and sends neither unless
+// the operator acts: leaving the section alone keeps whatever the webhook already has.
+const emptyEditAuth = { secret: '', removeSecret: false, replaceHeaders: false, headers: [] as HeaderRow[] };
+
export function Webhooks() {
const { t } = useTranslation();
useDocumentTitle(t('webhooks.title'));
@@ -109,6 +209,8 @@ export function Webhooks() {
sessionId: string;
filters: WebhookFilters | null;
}>({ url: '', events: ['message.received'], sessionId: '', filters: null });
+ const [newAuth, setNewAuth] = useState(emptyNewAuth);
+ const [editAuth, setEditAuth] = useState(emptyEditAuth);
const [testingId, setTestingId] = useState<string | null>(null);
const toast = useToast();
@@ -123,10 +225,24 @@ export function Webhooks() {
// The gateway requires a URL and at least one event, so the buttons stay disabled until both are set
// instead of surfacing the raw validation message in a toast.
+ const newHeaders = buildHeaderMap(newAuth.headers);
+ const newAuthError = secretError(newAuth.secret) ?? (newHeaders.ok ? null : newHeaders.error);
+ const editHeaders = buildHeaderMap(editAuth.headers);
+ const editAuthError =
+ (editAuth.removeSecret ? null : secretError(editAuth.secret)) ??
+ (editAuth.replaceHeaders && !editHeaders.ok ? editHeaders.error : null);
const canCreate =
- !createMutation.isPending && !!newWebhook.url.trim() && !!newWebhook.sessionId && newWebhook.events.length > 0;
+ !createMutation.isPending &&
+ !!newWebhook.url.trim() &&
+ !!newWebhook.sessionId &&
+ newWebhook.events.length > 0 &&
+ !newAuthError;
const canSave =
- !!editWebhook && !updateMutation.isPending && !!editWebhook.url.trim() && editWebhook.events.length > 0;
+ !!editWebhook &&
+ !updateMutation.isPending &&
+ !!editWebhook.url.trim() &&
+ editWebhook.events.length > 0 &&
+ !editAuthError;
const handleCreate = async () => {
// The gateway saves every create it receives, so a double click would register the webhook twice.
@@ -138,9 +254,13 @@ export function Webhooks() {
events: newWebhook.events,
// Don't persist message-filters when no message events are selected (the filter UI is hidden).
filters: supportsFilters(newWebhook.events) ? newWebhook.filters : null,
+ // Both are optional: an empty secret would be refused (minimum 16), and no rows means no headers.
+ ...(newAuth.secret ? { secret: newAuth.secret } : {}),
+ ...(newHeaders.ok && Object.keys(newHeaders.headers).length > 0 ? { headers: newHeaders.headers } : {}),
});
setShowCreateModal(false);
setNewWebhook({ url: '', events: ['message.received'], sessionId: '', filters: null });
+ setNewAuth(emptyNewAuth);
toast.success(t('webhooks.toasts.created'));
} catch (err) {
toast.error(
@@ -194,6 +314,7 @@ export function Webhooks() {
const openEdit = (webhook: Webhook) => {
setEditWebhook({ ...webhook });
+ setEditAuth(emptyEditAuth);
setShowEditModal(true);
};
@@ -209,10 +330,15 @@ export function Webhooks() {
active: editWebhook.active,
// Clear message-filters if the edit removed all message events (the filter UI is hidden then).
filters: supportsFilters(editWebhook.events) ? (editWebhook.filters ?? null) : null,
+ // Only an explicit action touches the stored credentials: '' removes the secret, and
+ // `headers` replaces the whole stored map ({} clears it).
+ ...(editAuth.removeSecret ? { secret: '' } : editAuth.secret ? { secret: editAuth.secret } : {}),
+ ...(editAuth.replaceHeaders && editHeaders.ok ? { headers: editHeaders.headers } : {}),
},
});
setShowEditModal(false);
setEditWebhook(null);
+ setEditAuth(emptyEditAuth);
toast.success(t('webhooks.toasts.updated'));
} catch (err) {
toast.error(
@@ -342,6 +468,26 @@ export function Webhooks() {
chats={chats}
/>
)}
+ <div className="filter-builder webhook-auth">
+ <div className="filter-builder-head">
+ <span className="filter-builder-title">{t('webhooks.auth.title')}</span>
+ <span className="filter-builder-hint">{t('webhooks.auth.hint')}</span>
+ </div>
+ <label htmlFor="wh-secret">{t('webhooks.auth.secret')}</label>
+ <SecretField
+ id="wh-secret"
+ value={newAuth.secret}
+ onChange={secret => setNewAuth(prev => ({ ...prev, secret }))}
+ />
+ <span className="filter-builder-hint">{t('webhooks.auth.secretHint')}</span>
+ <span className="filter-builder-title">{t('webhooks.auth.headers')}</span>
+ <HeaderRowsEditor rows={newAuth.headers} onChange={headers => setNewAuth(prev => ({ ...prev, headers }))} />
+ {newAuthError && (
+ <span className="hint error" role="status">
+ {t(newAuthError)}
+ </span>
+ )}
+ </div>
</Modal>
)}
@@ -398,6 +544,50 @@ export function Webhooks() {
chats={chats}
/>
)}
+ <div className="filter-builder webhook-auth">
+ <div className="filter-builder-head">
+ <span className="filter-builder-title">{t('webhooks.auth.title')}</span>
+ <span className="filter-builder-hint">{t('webhooks.auth.editHint')}</span>
+ </div>
+ <label htmlFor="wh-edit-secret">{t('webhooks.auth.secret')}</label>
+ <SecretField
+ id="wh-edit-secret"
+ placeholder={t('webhooks.auth.secretKeepPlaceholder')}
+ disabled={editAuth.removeSecret}
+ value={editAuth.secret}
+ onChange={secret => setEditAuth(prev => ({ ...prev, secret }))}
+ />
+ <label className="webhook-auth-check">
+ <input
+ type="checkbox"
+ checked={editAuth.removeSecret}
+ onChange={e => setEditAuth(prev => ({ ...prev, removeSecret: e.target.checked, secret: '' }))}
+ />
+ {t('webhooks.auth.removeSecret')}
+ </label>
+ <label className="webhook-auth-check">
+ <input
+ type="checkbox"
+ checked={editAuth.replaceHeaders}
+ onChange={e => setEditAuth(prev => ({ ...prev, replaceHeaders: e.target.checked }))}
+ />
+ {t('webhooks.auth.replaceHeaders')}
+ </label>
+ {editAuth.replaceHeaders && (
+ <>
+ <span className="filter-builder-hint">{t('webhooks.auth.replaceHint')}</span>
+ <HeaderRowsEditor
+ rows={editAuth.headers}
+ onChange={headers => setEditAuth(prev => ({ ...prev, headers }))}
+ />
+ </>
+ )}
+ {editAuthError && (
+ <span className="hint error" role="status">
+ {t(editAuthError)}
+ </span>
+ )}
+ </div>
<div className="toggle-group">
<span className="toggle-label" id="webhook-active-label">
{t('common.status')}
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 80c5e6c43..14c57972f 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -155,6 +155,26 @@ export interface Webhook {
updatedAt: string;
}
+// Request bodies for webhook writes. `secret` and `headers` are write-only: no webhook read returns them.
+export interface CreateWebhookRequest {
+ url: string;
+ events: string[];
+ filters?: WebhookFilters | null;
+ secret?: string;
+ headers?: Record<string, string>;
+}
+
+export interface UpdateWebhookRequest {
+ url?: string;
+ events?: string[];
+ active?: boolean;
+ filters?: WebhookFilters | null;
+ /** An empty string removes the stored secret. */
+ secret?: string;
+ /** Replaces the stored map wholesale; `{}` removes every custom header. */
+ headers?: Record<string, string>;
+}
+
export interface MessageTemplate {
id: string;
sessionId: string;
@@ -893,12 +913,12 @@ export const sessionApi = {
export const webhookApi = {
listBySession: (sessionId: string) => request<Webhook[]>(`/sessions/${sessionId}/webhooks`),
listAll: () => request<Webhook[]>('/webhooks'),
- create: (sessionId: string, data: { url: string; events: string[]; filters?: WebhookFilters | null }) =>
+ create: (sessionId: string, data: CreateWebhookRequest) =>
request<Webhook>(`/sessions/${sessionId}/webhooks`, {
method: 'POST',
body: JSON.stringify(data),
}),
- update: (sessionId: string, id: string, data: Partial<Webhook>) =>
+ update: (sessionId: string, id: string, data: UpdateWebhookRequest) =>
request<Webhook>(`/sessions/${sessionId}/webhooks/${id}`, {
method: 'PUT',
body: JSON.stringify(data),
diff --git a/dashboard/src/utils/webhookAuth.test.ts b/dashboard/src/utils/webhookAuth.test.ts
new file mode 100644
index 000000000..d752fd810
--- /dev/null
+++ b/dashboard/src/utils/webhookAuth.test.ts
@@ -0,0 +1,83 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { buildHeaderMap, generateSecret, secretError } from './webhookAuth.ts';
+
+const err = (rows: { name: string; value: string }[]) => {
+ const result = buildHeaderMap(rows);
+ return result.ok ? null : result.error;
+};
+
+test('a valid map is built with values exactly as typed and blank rows skipped', () => {
+ assert.deepEqual(
+ buildHeaderMap([
+ { name: 'Authorization', value: ' Bearer abc ' },
+ { name: '', value: '' },
+ { name: 'X-Empty', value: '' },
+ { name: 'X-Latin', value: 'café' },
+ ]),
+ { ok: true, headers: { Authorization: ' Bearer abc ', 'X-Empty': '', 'X-Latin': 'café' } },
+ );
+ assert.deepEqual(buildHeaderMap([]), { ok: true, headers: {} });
+});
+
+test('names outside letters, digits and hyphens are refused', () => {
+ for (const name of ['X Auth', 'a:b', 'X_Auth', '']) {
+ assert.equal(err([{ name, value: 'v' }]), 'webhooks.auth.errors.headerName', JSON.stringify(name));
+ }
+});
+
+test('values with control characters, DEL, non-Latin-1 characters or over 1024 characters are refused', () => {
+ for (const value of ['a\tb', 'a\r\nb', 'a\u007fb', '€5', 'x'.repeat(1025)]) {
+ assert.equal(err([{ name: 'X-A', value }]), 'webhooks.auth.errors.headerValue', JSON.stringify(value));
+ }
+ assert.equal(err([{ name: 'X-A', value: 'x'.repeat(1024) }]), null);
+});
+
+test('names the gateway drops at delivery are refused', () => {
+ const names = [
+ 'Content-Type',
+ 'User-Agent',
+ 'user-agent',
+ 'X-OpenWA-Signature',
+ 'Transfer-Encoding',
+ 'connection',
+ 'TE',
+ ];
+ for (const name of names) {
+ assert.equal(err([{ name, value: 'v' }]), 'webhooks.auth.errors.headerReserved', name);
+ }
+ assert.equal(err([{ name: 'Tenant', value: 'v' }]), null);
+});
+
+test('a name repeated in another case is refused', () => {
+ assert.equal(
+ err([
+ { name: 'X-A', value: '1' },
+ { name: 'x-a', value: '2' },
+ ]),
+ 'webhooks.auth.errors.headerDuplicate',
+ );
+});
+
+test('more than 50 headers are refused', () => {
+ const rows = (n: number) => Array.from({ length: n }, (_, i) => ({ name: `X-H${i}`, value: 'v' }));
+ assert.equal(err(rows(50)), null);
+ assert.equal(err(rows(51)), 'webhooks.auth.errors.tooMany');
+});
+
+test('a secret is empty or 16 to 255 characters, and is not trimmed', () => {
+ assert.equal(secretError(''), null);
+ assert.equal(secretError('x'.repeat(15)), 'webhooks.auth.errors.secretLength');
+ assert.equal(secretError('x'.repeat(16)), null);
+ assert.equal(secretError('x'.repeat(255)), null);
+ assert.equal(secretError('x'.repeat(256)), 'webhooks.auth.errors.secretLength');
+ assert.equal(secretError(` ${'x'.repeat(12)} `), null);
+ assert.equal(secretError(` ${'x'.repeat(10)} `), 'webhooks.auth.errors.secretLength');
+});
+
+test('a generated secret is 64 hex characters and passes the length check', () => {
+ const secret = generateSecret();
+ assert.match(secret, /^[0-9a-f]{64}$/);
+ assert.equal(secretError(secret), null);
+ assert.notEqual(generateSecret(), secret);
+});
diff --git a/dashboard/src/utils/webhookAuth.ts b/dashboard/src/utils/webhookAuth.ts
new file mode 100644
index 000000000..b7737bb52
--- /dev/null
+++ b/dashboard/src/utils/webhookAuth.ts
@@ -0,0 +1,64 @@
+/**
+ * Client-side checks for the webhook forms' custom headers and signing secret, mirroring
+ * `IsHeaderMap` and the secret bounds in src/modules/webhook/dto so a bad value is caught inline
+ * instead of coming back as a raw validation message. Errors are i18n keys.
+ */
+
+export interface HeaderRow {
+ name: string;
+ value: string;
+}
+
+export type HeaderMapResult = { ok: true; headers: Record<string, string> } | { ok: false; error: string };
+
+const HEADER_NAME = /^[A-Za-z0-9-]+$/;
+const MAX_HEADERS = 50;
+const MAX_VALUE_LENGTH = 1024;
+
+// The gateway accepts these names but drops them at delivery (sanitizeCustomHeaders in
+// deliver-once.ts), so a row naming one would be saved and silently never sent.
+function isDroppedAtDelivery(name: string): boolean {
+ return (
+ /^(content-type|x-openwa-)/i.test(name) ||
+ /^(connection|content-length|expect|keep-alive|te|trailer|transfer-encoding|upgrade|user-agent)$/i.test(name)
+ );
+}
+
+// Header values go out as Latin-1 bytes: control characters, DEL and anything above U+00FF are refused.
+function hasInvalidValueChar(value: string): boolean {
+ for (let i = 0; i < value.length; i++) {
+ const c = value.charCodeAt(i);
+ if (c < 0x20 || c === 0x7f || c > 0xff) return true;
+ }
+ return false;
+}
+
+/** Build the `headers` map from the editor rows. Fully blank rows are skipped; values are sent as typed. */
+export function buildHeaderMap(rows: readonly HeaderRow[]): HeaderMapResult {
+ const headers: Record<string, string> = {};
+ const seen = new Set<string>();
+ for (const { name, value } of rows) {
+ if (!name && !value) continue;
+ if (!HEADER_NAME.test(name)) return { ok: false, error: 'webhooks.auth.errors.headerName' };
+ if (isDroppedAtDelivery(name)) return { ok: false, error: 'webhooks.auth.errors.headerReserved' };
+ if (seen.has(name.toLowerCase())) return { ok: false, error: 'webhooks.auth.errors.headerDuplicate' };
+ if (value.length > MAX_VALUE_LENGTH || hasInvalidValueChar(value)) {
+ return { ok: false, error: 'webhooks.auth.errors.headerValue' };
+ }
+ seen.add(name.toLowerCase());
+ headers[name] = value;
+ }
+ if (seen.size > MAX_HEADERS) return { ok: false, error: 'webhooks.auth.errors.tooMany' };
+ return { ok: true, headers };
+}
+
+/** Null when the secret is acceptable: empty (not sent) or 16 to 255 characters. Never trimmed. */
+export function secretError(secret: string): string | null {
+ if (secret === '' || (secret.length >= 16 && secret.length <= 255)) return null;
+ return 'webhooks.auth.errors.secretLength';
+}
+
+/** A random signing secret: 32 bytes as 64 hex characters. getRandomValues also works over plain HTTP. */
+export function generateSecret(): string {
+ return Array.from(crypto.getRandomValues(new Uint8Array(32)), byte => byte.toString(16).padStart(2, '0')).join('');
+}