Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): refuse a chat list past the gateway limit in the form

Yudhi Armyndharis1e7cfd45ac28
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index dd6b7f8a2..63ceeb7d3 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -728,7 +728,8 @@
"chats": {
"label": "الوصول إلى المحادثات (اختياري)",
"hint": "محادثة واحدة في كل سطر: معرّف مجموعة ينتهي بـ @g.us، أو معرّف جهة اتصال ينتهي بـ @c.us أو @lid، أو رقم هاتف. اتركه فارغًا لكل المحادثات. لا يمكن للمفتاح المقيَّد بمحادثات إلا استخدام المسارات المفتوحة لهذا النوع من المفاتيح؛ ويقتصر وصوله عبر WebSocket الأحداث و MCP على هذه المحادثات.",
- "invalid": "ليس معرّف محادثة أو رقم هاتف: {{value}}"
+ "invalid": "ليس معرّف محادثة أو رقم هاتف: {{value}}",
+ "tooMany": "عدد المحادثات كبير جدًا ({{count}}): يمكن أن يضم المفتاح {{max}} كحد أقصى."
},
"expiry": {
"label": "ينتهي في (اختياري)",
diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json
index b09257220..da1e6d8c5 100644
--- a/dashboard/src/i18n/locales/de.json
+++ b/dashboard/src/i18n/locales/de.json
@@ -703,7 +703,8 @@
"chats": {
"label": "Chat-Zugriff (optional)",
"hint": "Ein Chat pro Zeile: eine Gruppen-ID mit @g.us, eine Kontakt-ID mit @c.us oder @lid oder eine Telefonnummer. Leer lassen für alle Chats. Ein auf Chats beschränkter Schlüssel kann nur die für solche Schlüssel freigegebenen Routen nutzen; sein Zugriff über den Events-WebSocket und MCP bleibt auf diese Chats beschränkt.",
- "invalid": "Keine Chat-ID und keine Telefonnummer: {{value}}"
+ "invalid": "Keine Chat-ID und keine Telefonnummer: {{value}}",
+ "tooMany": "Zu viele Chats ({{count}}): Ein Schlüssel darf höchstens {{max}} auflisten."
},
"expiry": {
"label": "Läuft ab am (optional)",
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index 643c7a62e..744d011be 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -703,7 +703,8 @@
"chats": {
"label": "Chat access (optional)",
"hint": "One chat per line: a group ID ending in @g.us, a contact ID ending in @c.us or @lid, or a phone number. Leave empty for every chat. A chat-restricted key can use only the routes open to chat-scoped keys; its events WebSocket and MCP access stay within these chats.",
- "invalid": "Not a chat ID or phone number: {{value}}"
+ "invalid": "Not a chat ID or phone number: {{value}}",
+ "tooMany": "Too many chats ({{count}}): a key may list at most {{max}}."
},
"expiry": {
"label": "Expires at (optional)",
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index 3a6e563f5..10f5542b9 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -659,7 +659,8 @@
"chats": {
"label": "Acceso a chats (opcional)",
"hint": "Un chat por línea: un ID de grupo que termina en @g.us, un ID de contacto que termina en @c.us o @lid, o un número de teléfono. Déjalo vacío para todos los chats. Una clave restringida a chats solo puede usar las rutas abiertas a ese tipo de clave; su acceso por el WebSocket de eventos y MCP se limita a esos chats.",
- "invalid": "No es un ID de chat ni un número de teléfono: {{value}}"
+ "invalid": "No es un ID de chat ni un número de teléfono: {{value}}",
+ "tooMany": "Demasiados chats ({{count}}): una clave puede listar como máximo {{max}}."
},
"expiry": {
"label": "Caduca el (opcional)",
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index e6a2c8e57..2712e930f 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -709,7 +709,8 @@
"chats": {
"label": "Accès aux discussions (facultatif)",
"hint": "Une discussion par ligne : un ID de groupe se terminant par @g.us, un ID de contact se terminant par @c.us ou @lid, ou un numéro de téléphone. Laissez vide pour toutes les discussions. Une clé limitée à des discussions ne peut utiliser que les routes ouvertes à ce type de clé ; son accès par le WebSocket des événements et MCP reste limité à ces discussions.",
- "invalid": "Ni un ID de discussion ni un numéro de téléphone : {{value}}"
+ "invalid": "Ni un ID de discussion ni un numéro de téléphone : {{value}}",
+ "tooMany": "Trop de discussions ({{count}}) : une clé peut en lister au plus {{max}}."
},
"expiry": {
"label": "Expire le (facultatif)",
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index 82cee9414..25ae8e1ca 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -716,7 +716,8 @@
"chats": {
"label": "גישה לצ'אטים (אופציונלי)",
"hint": "צ'אט אחד בכל שורה: מזהה קבוצה שמסתיים ב[email protected], מזהה איש קשר שמסתיים ב[email protected] או ב-@lid, או מספר טלפון. השאירו ריק לכל הצ'אטים. מפתח שמוגבל לצ'אטים יכול להשתמש רק בנתיבים הפתוחים למפתחות כאלה; הגישה שלו דרך ה-WebSocket של האירועים ו-MCP מוגבלת לצ'אטים האלה.",
- "invalid": "אינו מזהה צ'אט או מספר טלפון: {{value}}"
+ "invalid": "אינו מזהה צ'אט או מספר טלפון: {{value}}",
+ "tooMany": "יותר מדי צ'אטים ({{count}}): מפתח יכול לכלול לכל היותר {{max}}."
},
"expiry": {
"label": "תפוגה (אופציונלי)",
diff --git a/dashboard/src/i18n/locales/hi.json b/dashboard/src/i18n/locales/hi.json
index d27cdd37c..9c12490b9 100644
--- a/dashboard/src/i18n/locales/hi.json
+++ b/dashboard/src/i18n/locales/hi.json
@@ -703,7 +703,8 @@
"chats": {
"label": "चैट पहुँच (वैकल्पिक)",
"hint": "हर पंक्ति में एक चैट: @g.us पर समाप्त होने वाली ग्रुप ID, @c.us या @lid पर समाप्त होने वाली संपर्क ID, या फ़ोन नंबर। सभी चैट के लिए खाली छोड़ें। चैट तक सीमित कुंजी केवल ऐसी कुंजियों के लिए खुले रूट उपयोग कर सकती है; इवेंट WebSocket और MCP के ज़रिए उसकी पहुँच इन्हीं चैट तक सीमित रहती है।",
- "invalid": "यह चैट ID या फ़ोन नंबर नहीं है: {{value}}"
+ "invalid": "यह चैट ID या फ़ोन नंबर नहीं है: {{value}}",
+ "tooMany": "बहुत अधिक चैट ({{count}}): एक कुंजी में अधिकतम {{max}} हो सकती हैं।"
},
"expiry": {
"label": "समाप्ति समय (वैकल्पिक)",
diff --git a/dashboard/src/i18n/locales/id.json b/dashboard/src/i18n/locales/id.json
index 592777513..84defb945 100644
--- a/dashboard/src/i18n/locales/id.json
+++ b/dashboard/src/i18n/locales/id.json
@@ -703,7 +703,8 @@
"chats": {
"label": "Akses obrolan (opsional)",
"hint": "Satu obrolan per baris: ID grup yang diakhiri @g.us, ID kontak yang diakhiri @c.us atau @lid, atau nomor telepon. Kosongkan untuk semua obrolan. Kunci yang dibatasi obrolan hanya dapat menggunakan rute yang terbuka untuk kunci dengan cakupan obrolan; akses lewat WebSocket kejadian dan MCP tetap terbatas pada obrolan tersebut.",
- "invalid": "Bukan ID obrolan atau nomor telepon: {{value}}"
+ "invalid": "Bukan ID obrolan atau nomor telepon: {{value}}",
+ "tooMany": "Terlalu banyak obrolan ({{count}}): satu kunci paling banyak memuat {{max}}."
},
"expiry": {
"label": "Kedaluwarsa pada (opsional)",
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index 3f72eb80a..8472020b5 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -709,7 +709,8 @@
"chats": {
"label": "Accesso alle chat (facoltativo)",
"hint": "Una chat per riga: un ID di gruppo che termina con @g.us, un ID di contatto che termina con @c.us o @lid, oppure un numero di telefono. Lascia vuoto per tutte le chat. Una chiave limitata alle chat può usare solo le rotte aperte a questo tipo di chiave; il suo accesso tramite il WebSocket degli eventi e MCP resta limitato a queste chat.",
- "invalid": "Non è un ID chat né un numero di telefono: {{value}}"
+ "invalid": "Non è un ID chat né un numero di telefono: {{value}}",
+ "tooMany": "Troppe chat ({{count}}): una chiave può elencarne al massimo {{max}}."
},
"expiry": {
"label": "Scade il (facoltativo)",
diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.json
index 9cbafffce..5fcbc8f85 100644
--- a/dashboard/src/i18n/locales/ko.json
+++ b/dashboard/src/i18n/locales/ko.json
@@ -703,7 +703,8 @@
"chats": {
"label": "채팅 접근 (선택)",
"hint": "한 줄에 채팅 하나: @g.us로 끝나는 그룹 ID, @c.us 또는 @lid로 끝나는 연락처 ID, 또는 전화번호. 모든 채팅을 허용하려면 비워 두세요. 채팅이 제한된 키는 해당 키에 열린 경로만 사용할 수 있으며, 이벤트 WebSocket과 MCP를 통한 접근도 이 채팅으로 제한됩니다.",
- "invalid": "채팅 ID 또는 전화번호가 아닙니다: {{value}}"
+ "invalid": "채팅 ID 또는 전화번호가 아닙니다: {{value}}",
+ "tooMany": "채팅이 너무 많습니다({{count}}개). 키 하나에는 최대 {{max}}개까지 나열할 수 있습니다."
},
"expiry": {
"label": "만료 시각 (선택)",
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index cb0cdfc1e..e723b7826 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -659,7 +659,8 @@
"chats": {
"label": "Acesso a chats (opcional)",
"hint": "Um chat por linha: um ID de grupo terminado em @g.us, um ID de contato terminado em @c.us ou @lid, ou um número de telefone. Deixe em branco para todos os chats. Uma chave restrita a chats só pode usar as rotas abertas a esse tipo de chave; o acesso dela pelo WebSocket de eventos e pelo MCP fica limitado a esses chats.",
- "invalid": "Não é um ID de chat nem um número de telefone: {{value}}"
+ "invalid": "Não é um ID de chat nem um número de telefone: {{value}}",
+ "tooMany": "Chats demais ({{count}}): uma chave pode listar no máximo {{max}}."
},
"expiry": {
"label": "Expira em (opcional)",
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index 75759aaee..92cad46c9 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -703,7 +703,8 @@
"chats": {
"label": "చాట్ యాక్సెస్ (ఐచ్ఛికం)",
"hint": "ప్రతి పంక్తికి ఒక చాట్: @g.us తో ముగిసే గ్రూప్ ID, @c.us లేదా @lid తో ముగిసే కాంటాక్ట్ ID, లేదా ఫోన్ నంబర్. అన్ని చాట్‌ల కోసం ఖాళీగా వదిలేయండి. చాట్‌లకు పరిమితమైన కీ అలాంటి కీలకు తెరిచిన రూట్‌లను మాత్రమే ఉపయోగించగలదు; ఈవెంట్స్ WebSocket మరియు MCP ద్వారా దాని యాక్సెస్ ఈ చాట్‌లకే పరిమితం.",
- "invalid": "ఇది చాట్ ID లేదా ఫోన్ నంబర్ కాదు: {{value}}"
+ "invalid": "ఇది చాట్ ID లేదా ఫోన్ నంబర్ కాదు: {{value}}",
+ "tooMany": "చాట్‌లు చాలా ఎక్కువగా ఉన్నాయి ({{count}}): ఒక కీలో గరిష్టంగా {{max}} వరకు ఉండవచ్చు."
},
"expiry": {
"label": "గడువు సమయం (ఐచ్ఛికం)",
diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.json
index 19683d60b..ddc05b960 100644
--- a/dashboard/src/i18n/locales/tr.json
+++ b/dashboard/src/i18n/locales/tr.json
@@ -703,7 +703,8 @@
"chats": {
"label": "Sohbet erişimi (isteğe bağlı)",
"hint": "Her satıra bir sohbet: @g.us ile biten bir grup kimliği, @c.us veya @lid ile biten bir kişi kimliği ya da bir telefon numarası. Tüm sohbetler için boş bırakın. Sohbetle sınırlı bir anahtar yalnızca bu tür anahtarlara açık yolları kullanabilir; olay WebSocket'i ve MCP üzerinden erişimi de bu sohbetlerle sınırlı kalır.",
- "invalid": "Sohbet kimliği veya telefon numarası değil: {{value}}"
+ "invalid": "Sohbet kimliği veya telefon numarası değil: {{value}}",
+ "tooMany": "Çok fazla sohbet ({{count}}): bir anahtar en fazla {{max}} sohbet listeleyebilir."
},
"expiry": {
"label": "Son kullanma tarihi (isteğe bağlı)",
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 4affbbfe5..8ee1c8c7f 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -703,7 +703,8 @@
"chats": {
"label": "聊天访问(可选)",
"hint": "每行一个聊天:以 @g.us 结尾的群组 ID、以 @c.us 或 @lid 结尾的联系人 ID,或电话号码。留空则允许所有聊天。受聊天限制的密钥只能使用对此类密钥开放的路由;通过事件 WebSocket 和 MCP 的访问也仅限于这些聊天。",
- "invalid": "不是聊天 ID 或电话号码:{{value}}"
+ "invalid": "不是聊天 ID 或电话号码:{{value}}",
+ "tooMany": "聊天过多({{count}}):一个密钥最多可列出 {{max}} 个。"
},
"expiry": {
"label": "过期时间(可选)",
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index bf3c70801..bc00e55bb 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -703,7 +703,8 @@
"chats": {
"label": "聊天存取(選填)",
"hint": "每行一個聊天:以 @g.us 結尾的群組 ID、以 @c.us 或 @lid 結尾的聯絡人 ID,或電話號碼。留空則允許所有聊天。受聊天限制的金鑰只可使用對此類金鑰開放的路由;透過事件 WebSocket 及 MCP 的存取亦僅限於這些聊天。",
- "invalid": "不是聊天 ID 或電話號碼:{{value}}"
+ "invalid": "不是聊天 ID 或電話號碼:{{value}}",
+ "tooMany": "聊天過多({{count}}):一個金鑰最多可列出 {{max}} 個。"
},
"expiry": {
"label": "到期時間(選填)",
diff --git a/dashboard/src/pages/ApiKeys.test.ts b/dashboard/src/pages/ApiKeys.test.ts
index b654ac3db..afc6e3b4b 100644
--- a/dashboard/src/pages/ApiKeys.test.ts
+++ b/dashboard/src/pages/ApiKeys.test.ts
@@ -570,3 +570,20 @@ test('deleting a key whose name carries markup shows the name as text', async ()
assert.ok(dialog.textContent?.includes(name), 'the name was not shown as typed');
assert.equal(dialog.querySelector('strong[style]'), null, 'the name became an element');
});
+
+// The gateway refuses a list of more than 2000 chats with a 400, which a production gateway answers with a
+// bare "Bad Request"; the form says so before it is sent.
+test('a chat list past the gateway limit blocks Create and says how many it holds', async () => {
+ const { screen, fireEvent } = rtl;
+ const create = await openCreate();
+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'crm-bot' } });
+ const numbers = Array.from({ length: 2001 }, (_, i) => String(628000000000 + i)).join('\n');
+ fireEvent.change(screen.getByLabelText('Chat access (optional)'), { target: { value: numbers } });
+
+ const alert = await screen.findByText(/Too many chats \(2001\): a key may list at most 2000/);
+ assert.ok(alert);
+ assert.equal(create.disabled, true, 'Create is live with a list the gateway refuses');
+
+ fireEvent.change(screen.getByLabelText('Chat access (optional)'), { target: { value: '6281234' } });
+ await rtl.waitFor(() => assert.equal(create.disabled, false));
+});
diff --git a/dashboard/src/pages/ApiKeys.tsx b/dashboard/src/pages/ApiKeys.tsx
index 4f72c63ef..042372c15 100644
--- a/dashboard/src/pages/ApiKeys.tsx
+++ b/dashboard/src/pages/ApiKeys.tsx
@@ -42,6 +42,7 @@ import {
apiKeyPatch,
canScopeSessions,
invalidChatEntry,
+ ALLOWED_CHATS_MAX,
invalidIpEntry,
isExpired,
normalizeChatScope,
@@ -66,19 +67,28 @@ function isSignedInKey(apiKey: ApiKey): boolean {
// The first IP or chat line the gateway would refuse, so the form can name it instead of the bare
// "Bad Request" a production gateway answers with. On an edit, a list left as stored is not sent (see
// apiKeyPatch), so an entry saved before the gateway checked it does not block an unrelated change.
+interface LimitErrors {
+ ip: string | null;
+ chat: string | null;
+ /** How many chats were listed, when that is more than the gateway takes. */
+ chatCount: number | null;
+}
+
function limitErrors(
role: string,
ips: string,
chats: string,
stored?: Pick<ApiKey, 'allowedIps' | 'allowedChats'>,
-): { ip: string | null; chat: string | null } {
+): LimitErrors {
const ipList = parseScopeList(ips);
const chatList = normalizeChatScope(chats);
const unchanged = (list: string[], storedList: string[] | undefined) =>
!!stored && sameSessionScope(list, storedList ?? []);
+ const checksChats = canScopeSessions(role) && !unchanged(chatList, stored?.allowedChats);
return {
ip: unchanged(ipList, stored?.allowedIps) ? null : invalidIpEntry(ipList),
- chat: !canScopeSessions(role) || unchanged(chatList, stored?.allowedChats) ? null : invalidChatEntry(chatList),
+ chat: checksChats ? invalidChatEntry(chatList) : null,
+ chatCount: checksChats && chatList.length > ALLOWED_CHATS_MAX ? chatList.length : null,
};
}
@@ -108,7 +118,7 @@ function KeyLimitFields({
ips: string;
chats: string;
expires: string;
- errors: { ip: string | null; chat: string | null };
+ errors: LimitErrors;
onChange: (patch: { ips?: string; chats?: string; expires?: string }) => void;
disabled?: boolean;
expiresRef: RefObject<HTMLInputElement | null>;
@@ -150,6 +160,11 @@ function KeyLimitFields({
{t('apiKeys.chats.invalid', { value: errors.chat })}
</span>
)}
+ {errors.chatCount !== null && (
+ <span className="key-field-hint error" role="alert">
+ {t('apiKeys.chats.tooMany', { count: errors.chatCount, max: ALLOWED_CHATS_MAX })}
+ </span>
+ )}
<span className="key-field-hint">{t('apiKeys.chats.hint')}</span>
</>
)}
@@ -319,8 +334,14 @@ export function ApiKeys() {
const nameLength = [...newKey.name].length;
const nameTooLong = nameLength > 100;
const canCreate =
- !createMutation.isPending && !nameTooShort && !nameTooLong && newErrors.ip === null && newErrors.chat === null;
- const canSave = !updateMutation.isPending && editErrors?.ip === null && editErrors.chat === null;
+ !createMutation.isPending &&
+ !nameTooShort &&
+ !nameTooLong &&
+ newErrors.ip === null &&
+ newErrors.chat === null &&
+ newErrors.chatCount === null;
+ const canSave =
+ !updateMutation.isPending && editErrors?.ip === null && editErrors.chat === null && editErrors.chatCount === null;
const handleRevoke = async (id: string) => {
try {
@@ -679,7 +700,7 @@ export function ApiKeys() {
ips={editDraft.ips}
chats={editDraft.chats}
expires={editDraft.expires}
- errors={editErrors ?? { ip: null, chat: null }}
+ errors={editErrors ?? { ip: null, chat: null, chatCount: null }}
onChange={patch => setEditDraft(prev => (prev ? { ...prev, ...patch } : prev))}
disabled={updateMutation.isPending}
expiresRef={editExpiresRef}
diff --git a/dashboard/src/utils/sessionScope.ts b/dashboard/src/utils/sessionScope.ts
index a17c6c33f..d7ccef097 100644
--- a/dashboard/src/utils/sessionScope.ts
+++ b/dashboard/src/utils/sessionScope.ts
@@ -70,6 +70,9 @@ export function normalizeChatScope(text: string): string[] {
return [...new Set(parseScopeList(text).map(entry => (/^\d{5,}$/.test(entry) ? `${entry}@c.us` : entry)))];
}
+/** The most chats a key may list: the gateway answers a longer list with 400 (ALLOWED_CHATS_MAX). */
+export const ALLOWED_CHATS_MAX = 2000;
+
/** A stored instant as a `datetime-local` value in this browser's time zone, or '' for none. */
export function toDateTimeLocal(iso: string | null | undefined): string {
if (!iso) return '';