Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(dashboard): edit key expiry, IP allow-list, chats and role
Yudhi Armyndharisff1d0c3b3f5f
diff --git a/README.md b/README.mdindex fc2f00ce6..2ac03a33f 100644--- a/README.md+++ b/README.md@@ -57,7 +57,7 @@ Admin keys stay unscoped in the dashboard so they can keep managing other API ke### Chat-scoped operator & viewer tokens-A session-scoped key still reaches every chat on the sessions it may use. A key can be narrowed further, to **chats** (a chosen set of groups and individual contacts), with `allowedChats` on `POST /auth/api-keys` or `PUT /auth/api-keys/{id}`. The dashboard does not set or show it yet, and editing a key there leaves its chats unchanged.+A session-scoped key still reaches every chat on the sessions it may use. A key can be narrowed further, to **chats** (a chosen set of groups and individual contacts), with `allowedChats` on `POST /auth/api-keys` or `PUT /auth/api-keys/{id}`. The dashboard sets it on operator and viewer keys (one chat id or phone number per line) and shows each key's chat count in the list.- **No chats selected** — the key can reach every chat on its sessions.- **One or more selected** — the key reaches only those chats. Every authenticated REST route not explicitly marked as safe for a chat-scoped key refuses it with `403` (a request naming a session outside `allowedSessions` is refused first, with `403 "API key not authorized for this session"`), including routes added in later releases: the refusal is the default. Inside its chats an operator key can do what the marked routes allow, which is more than reading and sending: it can also delete or clear a chat, leave or rename a group, and block the contact. It cannot change who belongs to a group: adding, removing, promoting or demoting participants, answering join requests and reading or resetting the invite link all stay closed.diff --git a/dashboard/src/hooks/queries.ts b/dashboard/src/hooks/queries.tsindex e6dc8ecdb..6e6ba7687 100644--- a/dashboard/src/hooks/queries.ts+++ b/dashboard/src/hooks/queries.ts@@ -191,6 +191,7 @@ export function useCreateApiKeyMutation() {role: string;allowedIps?: string[];allowedSessions?: string[];+ allowedChats?: string[];expiresAt?: string;}) => apiKeyApi.create(data),onSuccess: () => {@@ -212,7 +213,8 @@ export function useUpdateApiKeyMutation() {role?: string;allowedIps?: string[];allowedSessions?: string[];- expiresAt?: string;+ allowedChats?: string[];+ expiresAt?: string | null;};}) => apiKeyApi.update(id, data),onSuccess: () => {diff --git a/dashboard/src/i18n/locales.test.ts b/dashboard/src/i18n/locales.test.tsindex c787f0a42..1abec4ef6 100644--- a/dashboard/src/i18n/locales.test.ts+++ b/dashboard/src/i18n/locales.test.ts@@ -37,11 +37,18 @@ const SESSION_SCOPE_KEYS = ['apiKeys.sessions.all','apiKeys.sessions.empty','apiKeys.sessions.restricted',- 'apiKeys.sessions.editTitle','apiKeys.sessions.save','apiKeys.sessions.choose','apiKeys.sessions.leaveAll',- 'apiKeys.actions.editSessions',+ 'apiKeys.actions.edit',+ 'apiKeys.edit.title',+ 'apiKeys.edit.signedIn',+ 'apiKeys.columns.restrictions',+ 'apiKeys.restrictions.ips',+ 'apiKeys.restrictions.chats',+ 'apiKeys.ips.label',+ 'apiKeys.chats.label',+ 'apiKeys.expiry.label',];const NEW_PLUGIN_KEYS = [diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 4df0ea1a3..b5cd8f4d8 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -650,6 +650,7 @@"createdTitle": "تم إنشاء مفتاح API","createdHint": "انسخ هذا المفتاح الآن. لن تتمكن من رؤيته مرة أخرى.","namePlaceholder": "مثال: مفتاح الإنتاج",+ "nameTooShort": "استخدم 3 أحرف على الأقل.","rolesTitle": "مرجع الأدوار","roles": {"admin": "مدير",@@ -668,11 +669,13 @@"status": "الحالة","lastUsed": "آخر استخدام","actions": "إجراءات",- "sessions": "الجلسات"+ "sessions": "الجلسات",+ "restrictions": "القيود"},"statuses": {"active": "نشط",- "revoked": "مُلغى"+ "revoked": "مُلغى",+ "expired": "منتهي الصلاحية"},"empty": {"title": "لا توجد مفاتيح API",@@ -693,7 +696,7 @@"copy": "نسخ","revoke": "إلغاء","delete": "حذف",- "editSessions": "تعديل الجلسات"+ "edit": "تعديل الوصول"},"sessions": {"label": "الوصول إلى الجلسات",@@ -701,10 +704,36 @@"all": "كل الجلسات","empty": "لا توجد جلسات بعد. سيتمكن هذا المفتاح من الوصول إلى كل الجلسات عند إنشائها.","restricted": "{{count}} محددة",- "editTitle": "تعديل الوصول إلى الجلسات","save": "حفظ","choose": "اختيار الجلسات","leaveAll": "تركها لجميع الجلسات"+ },+ "edit": {+ "title": "تعديل وصول المفتاح",+ "signedIn": "لوحة التحكم هذه مسجَّلة الدخول بهذا المفتاح. قد يؤدي تغيير دوره أو عناوين IP أو المحادثات أو تاريخ انتهاء صلاحيته إلى تسجيل خروجك."+ },+ "restrictions": {+ "none": "لا يوجد",+ "ips": "عناوين IP: {{count}}",+ "chats": "المحادثات: {{count}}",+ "expires": "ينتهي في {{date}}",+ "expired": "انتهى في {{date}}"+ },+ "ips": {+ "label": "عناوين IP المسموح بها (اختياري)",+ "hint": "عنوان IP واحد أو نطاق CIDR واحد في كل سطر. اتركه فارغًا لقبول أي عنوان.",+ "invalid": "ليس عنوان IPv4 أو نطاق CIDR: {{value}}"+ },+ "chats": {+ "label": "الوصول إلى المحادثات (اختياري)",+ "hint": "محادثة واحدة في كل سطر: معرّف مجموعة ينتهي بـ @g.us، أو معرّف جهة اتصال ينتهي بـ @c.us أو @lid، أو رقم هاتف. اتركه فارغًا لكل المحادثات. لا يمكن للمفتاح المقيَّد بمحادثات إلا استخدام المسارات المفتوحة لهذا النوع من المفاتيح؛ ويرفضه WebSocket الأحداث و MCP.",+ "invalid": "ليس معرّف محادثة أو رقم هاتف: {{value}}"+ },+ "expiry": {+ "label": "ينتهي في (اختياري)",+ "hint": "بالمنطقة الزمنية لهذا المتصفح. اتركه فارغًا لمفتاح لا تنتهي صلاحيته أبدًا.",+ "clear": "إزالة تاريخ الانتهاء",+ "invalid": "أدخل تاريخًا ووقتًا كاملين لا يتجاوزان عام 9999، أو امسح الحقل لمفتاح لا تنتهي صلاحيته أبدًا."}},"logs": {diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex 55bef91c1..8650c7f83 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -625,6 +625,7 @@"createdTitle": "API-Schlüssel erstellt","createdHint": "Kopiere diesen Schlüssel jetzt. Du kannst ihn später nicht erneut anzeigen.","namePlaceholder": "z. B. Produktionsschlüssel",+ "nameTooShort": "Verwende mindestens 3 Zeichen.","rolesTitle": "Rollenübersicht","roles": {"admin": "Administrator",@@ -643,11 +644,13 @@"status": "Status","lastUsed": "Zuletzt verwendet","actions": "Aktionen",- "sessions": "Sitzungen"+ "sessions": "Sitzungen",+ "restrictions": "Einschränkungen"},"statuses": {"active": "Aktiv",- "revoked": "Widerrufen"+ "revoked": "Widerrufen",+ "expired": "Abgelaufen"},"empty": {"title": "Keine API-Schlüssel erstellt",@@ -668,7 +671,7 @@"copy": "Kopieren","revoke": "Widerrufen","delete": "Löschen",- "editSessions": "Sitzungen bearbeiten"+ "edit": "Zugriff bearbeiten"},"sessions": {"label": "Sitzungszugriff",@@ -676,10 +679,36 @@"all": "Alle Sitzungen","empty": "Noch keine Sitzungen. Dieser Schlüssel kann auf alle zugreifen, sobald welche existieren.","restricted": "{{count}} ausgewählt",- "editTitle": "Sitzungszugriff bearbeiten","save": "Speichern","choose": "Sitzungen wählen","leaveAll": "Für alle Sitzungen belassen"+ },+ "edit": {+ "title": "Schlüsselzugriff bearbeiten",+ "signedIn": "Dieses Dashboard ist mit diesem Schlüssel angemeldet. Wenn du Rolle, IP-Adressen, Chats oder Ablauf änderst, kannst du abgemeldet werden."+ },+ "restrictions": {+ "none": "Keine",+ "ips": "IPs: {{count}}",+ "chats": "Chats: {{count}}",+ "expires": "Läuft ab am {{date}}",+ "expired": "Abgelaufen am {{date}}"+ },+ "ips": {+ "label": "Erlaubte IP-Adressen (optional)",+ "hint": "Eine IP-Adresse oder ein CIDR-Bereich pro Zeile. Leer lassen, um jede Adresse zuzulassen.",+ "invalid": "Keine IPv4-Adresse und kein CIDR-Bereich: {{value}}"+ },+ "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; der Events-WebSocket und MCP lehnen ihn ab.",+ "invalid": "Keine Chat-ID und keine Telefonnummer: {{value}}"+ },+ "expiry": {+ "label": "Läuft ab am (optional)",+ "hint": "In der Zeitzone dieses Browsers. Leer lassen für einen Schlüssel, der nie abläuft.",+ "clear": "Ablauf entfernen",+ "invalid": "Datum und Uhrzeit vollständig eingeben, höchstens bis zum Jahr 9999, oder das Feld leeren, damit der Schlüssel nie abläuft."}},"logs": {diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex 567d61d7b..8068ef693 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -625,6 +625,7 @@"createdTitle": "API Key Created","createdHint": "Copy this key now. You won't be able to see it again.","namePlaceholder": "e.g., Production Key",+ "nameTooShort": "Use at least 3 characters.","rolesTitle": "Roles Reference","roles": {"admin": "Admin",@@ -643,11 +644,13 @@"status": "Status","lastUsed": "Last Used","actions": "Actions",- "sessions": "Sessions"+ "sessions": "Sessions",+ "restrictions": "Restrictions"},"statuses": {"active": "Active",- "revoked": "Revoked"+ "revoked": "Revoked",+ "expired": "Expired"},"empty": {"title": "No API keys created",@@ -668,7 +671,7 @@"copy": "Copy","revoke": "Revoke","delete": "Delete",- "editSessions": "Edit sessions"+ "edit": "Edit access"},"sessions": {"label": "Session access",@@ -676,10 +679,36 @@"all": "All sessions","empty": "No sessions yet. This key will be able to access every session once any exist.","restricted": "{{count}} selected",- "editTitle": "Edit session access","save": "Save","choose": "Choose sessions","leaveAll": "Leave for all sessions"+ },+ "edit": {+ "title": "Edit key access",+ "signedIn": "This dashboard is signed in with this key. Changing its role, IP addresses, chats or expiry can sign you out."+ },+ "restrictions": {+ "none": "None",+ "ips": "IPs: {{count}}",+ "chats": "Chats: {{count}}",+ "expires": "Expires {{date}}",+ "expired": "Expired {{date}}"+ },+ "ips": {+ "label": "Allowed IP addresses (optional)",+ "hint": "One IP address or CIDR range per line. Leave empty to accept any address.",+ "invalid": "Not an IPv4 address or CIDR range: {{value}}"+ },+ "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; the events WebSocket and MCP refuse it.",+ "invalid": "Not a chat ID or phone number: {{value}}"+ },+ "expiry": {+ "label": "Expires at (optional)",+ "hint": "In this browser's time zone. Leave empty for a key that never expires.",+ "clear": "Remove expiry",+ "invalid": "Enter a complete date and time no later than the year 9999, or clear the field for a key that never expires."}},"logs": {diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex 44d3cba7e..cf52f194b 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -582,6 +582,7 @@"createdTitle": "Clave API creada","createdHint": "Copia esta clave ahora. No podrás verla de nuevo.","namePlaceholder": "ej., Clave de producción",+ "nameTooShort": "Usa al menos 3 caracteres.","rolesTitle": "Referencia de roles","roles": {"admin": "Administrador",@@ -600,11 +601,13 @@"status": "Estado","lastUsed": "Último uso","actions": "Acciones",- "sessions": "Sesiones"+ "sessions": "Sesiones",+ "restrictions": "Restricciones"},"statuses": {"active": "Activa",- "revoked": "Revocada"+ "revoked": "Revocada",+ "expired": "Caducada"},"empty": {"title": "No hay claves API creadas",@@ -625,7 +628,7 @@"copy": "Copiar","revoke": "Revocar","delete": "Eliminar",- "editSessions": "Editar sesiones"+ "edit": "Editar acceso"},"sessions": {"label": "Acceso a sesiones",@@ -633,10 +636,36 @@"all": "Todas las sesiones","empty": "Todavía no hay sesiones. Esta clave podrá acceder a todas cuando existan.","restricted": "{{count}} seleccionadas",- "editTitle": "Editar acceso a sesiones","save": "Guardar","choose": "Elegir sesiones","leaveAll": "Dejar para todas las sesiones"+ },+ "edit": {+ "title": "Editar acceso de la clave",+ "signedIn": "Este panel ha iniciado sesión con esta clave. Cambiar su rol, direcciones IP, chats o caducidad puede cerrar tu sesión."+ },+ "restrictions": {+ "none": "Ninguna",+ "ips": "IP: {{count}}",+ "chats": "Chats: {{count}}",+ "expires": "Caduca el {{date}}",+ "expired": "Caducó el {{date}}"+ },+ "ips": {+ "label": "Direcciones IP permitidas (opcional)",+ "hint": "Una dirección IP o un rango CIDR por línea. Déjalo vacío para aceptar cualquier dirección.",+ "invalid": "No es una dirección IPv4 ni un rango CIDR: {{value}}"+ },+ "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; el WebSocket de eventos y MCP la rechazan.",+ "invalid": "No es un ID de chat ni un número de teléfono: {{value}}"+ },+ "expiry": {+ "label": "Caduca el (opcional)",+ "hint": "En la zona horaria de este navegador. Déjalo vacío para una clave que nunca caduca.",+ "clear": "Quitar caducidad",+ "invalid": "Introduce una fecha y hora completas, no posteriores al año 9999, o vacía el campo para una clave que nunca caduca."}},"logs": {diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex 4a932b6ef..f5ec729f2 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -631,6 +631,7 @@"createdTitle": "Clé API créée","createdHint": "Copiez cette clé maintenant. Vous ne pourrez plus la revoir.","namePlaceholder": "ex : Clé de Production",+ "nameTooShort": "Utilisez au moins 3 caractères.","rolesTitle": "Référence des rôles","roles": {"admin": "Administrateur",@@ -649,11 +650,13 @@"status": "Statut","lastUsed": "Dernière utilisation","actions": "Actions",- "sessions": "Sessions"+ "sessions": "Sessions",+ "restrictions": "Restrictions"},"statuses": {"active": "Active",- "revoked": "Révoquée"+ "revoked": "Révoquée",+ "expired": "Expirée"},"empty": {"title": "Aucune clé API créée",@@ -674,7 +677,7 @@"copy": "Copier","revoke": "Révoquer","delete": "Supprimer",- "editSessions": "Modifier les sessions"+ "edit": "Modifier l'accès"},"sessions": {"label": "Accès aux sessions",@@ -682,10 +685,36 @@"all": "Toutes les sessions","empty": "Aucune session pour le moment. Cette clé pourra accéder à toutes dès qu’il y en aura.","restricted": "{{count}} sélectionnées",- "editTitle": "Modifier l’accès aux sessions","save": "Enregistrer","choose": "Choisir des sessions","leaveAll": "Laisser pour toutes les sessions"+ },+ "edit": {+ "title": "Modifier l'accès de la clé",+ "signedIn": "Ce tableau de bord est connecté avec cette clé. Modifier son rôle, ses adresses IP, ses discussions ou son expiration peut vous déconnecter."+ },+ "restrictions": {+ "none": "Aucune",+ "ips": "IP : {{count}}",+ "chats": "Discussions : {{count}}",+ "expires": "Expire le {{date}}",+ "expired": "Expirée le {{date}}"+ },+ "ips": {+ "label": "Adresses IP autorisées (facultatif)",+ "hint": "Une adresse IP ou une plage CIDR par ligne. Laissez vide pour accepter toute adresse.",+ "invalid": "Ni une adresse IPv4 ni une plage CIDR : {{value}}"+ },+ "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é ; le WebSocket des événements et MCP la refusent.",+ "invalid": "Ni un ID de discussion ni un numéro de téléphone : {{value}}"+ },+ "expiry": {+ "label": "Expire le (facultatif)",+ "hint": "Dans le fuseau horaire de ce navigateur. Laissez vide pour une clé qui n'expire jamais.",+ "clear": "Retirer l'expiration",+ "invalid": "Saisissez une date et une heure complètes, au plus tard en l'an 9999, ou videz le champ pour une clé qui n'expire jamais."}},"logs": {diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex 2f65e2d03..521ff2edd 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -632,6 +632,7 @@"createdTitle": "מפתח ה-API נוצר","createdHint": "יש להעתיק את המפתח כעת. לא ניתן יהיה לצפות בו שוב.","namePlaceholder": "לדוגמה: Production Key",+ "nameTooShort": "השתמשו לפחות ב-3 תווים.","rolesTitle": "מדריך תפקידים","roles": {"admin": "Admin",@@ -650,11 +651,13 @@"status": "סטטוס","lastUsed": "שימוש אחרון","actions": "פעולות",- "sessions": "סשנים"+ "sessions": "סשנים",+ "restrictions": "הגבלות"},"statuses": {"active": "פעיל",- "revoked": "בוטל"+ "revoked": "בוטל",+ "expired": "פג תוקף"},"empty": {"title": "לא נוצרו מפתחות API",@@ -675,7 +678,7 @@"copy": "העתקה","revoke": "ביטול","delete": "מחיקה",- "editSessions": "עריכת סשנים"+ "edit": "עריכת גישה"},"sessions": {"label": "גישה לסשנים",@@ -683,10 +686,36 @@"all": "כל הסשנים","empty": "עדיין אין סשנים. המפתח הזה יוכל לגשת לכולם ברגע שיהיו.","restricted": "{{count}} נבחרו",- "editTitle": "עריכת גישה לסשנים","save": "שמירה","choose": "בחירת סשנים","leaveAll": "להשאיר לכל הסשנים"+ },+ "edit": {+ "title": "עריכת הגישה של המפתח",+ "signedIn": "לוח הבקרה הזה מחובר עם המפתח הזה. שינוי התפקיד, כתובות ה-IP, הצ'אטים או התפוגה שלו עלול לנתק אתכם."+ },+ "restrictions": {+ "none": "אין",+ "ips": "כתובות IP: {{count}}",+ "chats": "צ'אטים: {{count}}",+ "expires": "פג ב-{{date}}",+ "expired": "פג תוקף ב-{{date}}"+ },+ "ips": {+ "label": "כתובות IP מורשות (אופציונלי)",+ "hint": "כתובת IP אחת או טווח CIDR אחד בכל שורה. השאירו ריק כדי לקבל כל כתובת.",+ "invalid": "אינה כתובת IPv4 או טווח CIDR: {{value}}"+ },+ "chats": {+ "label": "גישה לצ'אטים (אופציונלי)",+ "hint": "צ'אט אחד בכל שורה: מזהה קבוצה שמסתיים ב[email protected], מזהה איש קשר שמסתיים ב[email protected] או ב-@lid, או מספר טלפון. השאירו ריק לכל הצ'אטים. מפתח שמוגבל לצ'אטים יכול להשתמש רק בנתיבים הפתוחים למפתחות כאלה; ה-WebSocket של האירועים ו-MCP דוחים אותו.",+ "invalid": "אינו מזהה צ'אט או מספר טלפון: {{value}}"+ },+ "expiry": {+ "label": "תפוגה (אופציונלי)",+ "hint": "לפי אזור הזמן של הדפדפן הזה. השאירו ריק למפתח שאינו פג לעולם.",+ "clear": "הסרת התפוגה",+ "invalid": "הזינו תאריך ושעה מלאים, לא מאוחר משנת 9999, או רוקנו את השדה למפתח שאינו פג לעולם."}},"logs": {diff --git a/dashboard/src/i18n/locales/hi.json b/dashboard/src/i18n/locales/hi.jsonindex 974361095..722865345 100644--- a/dashboard/src/i18n/locales/hi.json+++ b/dashboard/src/i18n/locales/hi.json@@ -625,6 +625,7 @@"createdTitle": "API कुंजी बनाई गई","createdHint": "इस कुंजी को अभी कॉपी करें। आप इसे फिर से नहीं देख पाएंगे।","namePlaceholder": "उदा. Production Key",+ "nameTooShort": "कम से कम 3 वर्ण उपयोग करें।","rolesTitle": "भूमिका संदर्भ","roles": {"admin": "व्यवस्थापक (Admin)",@@ -643,11 +644,13 @@"status": "स्थिति","lastUsed": "अंतिम बार प्रयुक्त","actions": "कार्रवाइयाँ",- "sessions": "सत्र"+ "sessions": "सत्र",+ "restrictions": "प्रतिबंध"},"statuses": {"active": "सक्रिय",- "revoked": "निरस्त"+ "revoked": "निरस्त",+ "expired": "समाप्त"},"empty": {"title": "कोई API कुंजी नहीं बनाई गई",@@ -668,7 +671,7 @@"copy": "कॉपी करें","revoke": "निरस्त करें","delete": "हटाएं",- "editSessions": "सत्र संपादित करें"+ "edit": "पहुँच संपादित करें"},"sessions": {"label": "सत्र पहुँच",@@ -676,10 +679,36 @@"all": "सभी सत्र","empty": "अभी कोई सत्र नहीं है। किसी के भी मौजूद होने पर यह कुंजी हर सत्र तक पहुँचने में सक्षम होगी।","restricted": "{{count}} चयनित",- "editTitle": "सत्र पहुँच संपादित करें","save": "सहेजें","choose": "सत्र चुनें","leaveAll": "सभी सत्रों तक पहुँच रहने दें"+ },+ "edit": {+ "title": "कुंजी पहुँच संपादित करें",+ "signedIn": "यह डैशबोर्ड इसी कुंजी से साइन इन है। इसकी भूमिका, IP पते, चैट या समाप्ति बदलने से आप साइन आउट हो सकते हैं।"+ },+ "restrictions": {+ "none": "कोई नहीं",+ "ips": "IP: {{count}}",+ "chats": "चैट: {{count}}",+ "expires": "{{date}} को समाप्त होगी",+ "expired": "{{date}} को समाप्त हुई"+ },+ "ips": {+ "label": "अनुमत IP पते (वैकल्पिक)",+ "hint": "हर पंक्ति में एक IP पता या CIDR रेंज। किसी भी पते को स्वीकार करने के लिए खाली छोड़ें।",+ "invalid": "यह IPv4 पता या CIDR रेंज नहीं है: {{value}}"+ },+ "chats": {+ "label": "चैट पहुँच (वैकल्पिक)",+ "hint": "हर पंक्ति में एक चैट: @g.us पर समाप्त होने वाली ग्रुप ID, @c.us या @lid पर समाप्त होने वाली संपर्क ID, या फ़ोन नंबर। सभी चैट के लिए खाली छोड़ें। चैट तक सीमित कुंजी केवल ऐसी कुंजियों के लिए खुले रूट उपयोग कर सकती है; इवेंट WebSocket और MCP उसे अस्वीकार करते हैं।",+ "invalid": "यह चैट ID या फ़ोन नंबर नहीं है: {{value}}"+ },+ "expiry": {+ "label": "समाप्ति समय (वैकल्पिक)",+ "hint": "इस ब्राउज़र के समय क्षेत्र में। कभी समाप्त न होने वाली कुंजी के लिए खाली छोड़ें।",+ "clear": "समाप्ति हटाएँ",+ "invalid": "वर्ष 9999 तक की पूरी तारीख और समय दर्ज करें, या कभी समाप्त न होने वाली कुंजी के लिए फ़ील्ड खाली करें।"}},"logs": {diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex bac66a731..d30b1fc70 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -631,6 +631,7 @@"createdTitle": "Chiave API Creata","createdHint": "Copia questa chiave ora. Non potrai più visualizzarla.","namePlaceholder": "es., Chiave di Produzione",+ "nameTooShort": "Usa almeno 3 caratteri.","rolesTitle": "Riferimento Ruoli","roles": {"admin": "Amministratore",@@ -649,11 +650,13 @@"status": "Stato","lastUsed": "Ultimo Utilizzo","actions": "Azioni",- "sessions": "Sessioni"+ "sessions": "Sessioni",+ "restrictions": "Restrizioni"},"statuses": {"active": "Attiva",- "revoked": "Revocata"+ "revoked": "Revocata",+ "expired": "Scaduta"},"empty": {"title": "Nessuna chiave API creata",@@ -674,7 +677,7 @@"copy": "Copia","revoke": "Revoca","delete": "Elimina",- "editSessions": "Modifica sessioni"+ "edit": "Modifica accesso"},"sessions": {"label": "Accesso alle sessioni",@@ -682,10 +685,36 @@"all": "Tutte le sessioni","empty": "Non ci sono ancora sessioni. Questa chiave potrà accedere a tutte quando esisteranno.","restricted": "{{count}} selezionate",- "editTitle": "Modifica accesso alle sessioni","save": "Salva","choose": "Scegli sessioni","leaveAll": "Lascia per tutte le sessioni"+ },+ "edit": {+ "title": "Modifica l'accesso della chiave",+ "signedIn": "Questa dashboard ha effettuato l'accesso con questa chiave. Modificarne ruolo, indirizzi IP, chat o scadenza può disconnetterti."+ },+ "restrictions": {+ "none": "Nessuna",+ "ips": "IP: {{count}}",+ "chats": "Chat: {{count}}",+ "expires": "Scade il {{date}}",+ "expired": "Scaduta il {{date}}"+ },+ "ips": {+ "label": "Indirizzi IP consentiti (facoltativo)",+ "hint": "Un indirizzo IP o un intervallo CIDR per riga. Lascia vuoto per accettare qualsiasi indirizzo.",+ "invalid": "Non è un indirizzo IPv4 né un intervallo CIDR: {{value}}"+ },+ "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 WebSocket degli eventi e MCP la rifiutano.",+ "invalid": "Non è un ID chat né un numero di telefono: {{value}}"+ },+ "expiry": {+ "label": "Scade il (facoltativo)",+ "hint": "Nel fuso orario di questo browser. Lascia vuoto per una chiave che non scade mai.",+ "clear": "Rimuovi scadenza",+ "invalid": "Inserisci data e ora complete, non oltre l'anno 9999, oppure svuota il campo per una chiave che non scade mai."}},"logs": {diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex be64525a7..ed5bdeee9 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -625,6 +625,7 @@"createdTitle": "API 키 생성 완료","createdHint": "지금 이 키를 복사해 두세요. 다시 확인할 수 없습니다.","namePlaceholder": "예: Production Key",+ "nameTooShort": "3자 이상 입력하세요.","rolesTitle": "역할 안내","roles": {"admin": "관리자",@@ -643,11 +644,13 @@"status": "상태","lastUsed": "마지막 사용","actions": "작업",- "sessions": "세션"+ "sessions": "세션",+ "restrictions": "제한"},"statuses": {"active": "활성",- "revoked": "폐기됨"+ "revoked": "폐기됨",+ "expired": "만료됨"},"empty": {"title": "생성된 API 키가 없습니다",@@ -668,7 +671,7 @@"copy": "복사","revoke": "폐기","delete": "삭제",- "editSessions": "세션 편집"+ "edit": "접근 편집"},"sessions": {"label": "세션 접근",@@ -676,10 +679,36 @@"all": "모든 세션","empty": "아직 세션이 없습니다. 세션이 생기면 이 키는 모두에 접근할 수 있습니다.","restricted": "{{count}}개 선택됨",- "editTitle": "세션 접근 편집","save": "저장","choose": "세션 선택","leaveAll": "모든 세션에 두기"+ },+ "edit": {+ "title": "키 접근 편집",+ "signedIn": "이 대시보드는 이 키로 로그인되어 있습니다. 역할, IP 주소, 채팅 또는 만료를 변경하면 로그아웃될 수 있습니다."+ },+ "restrictions": {+ "none": "없음",+ "ips": "IP: {{count}}",+ "chats": "채팅: {{count}}",+ "expires": "{{date}}에 만료",+ "expired": "{{date}}에 만료됨"+ },+ "ips": {+ "label": "허용된 IP 주소 (선택)",+ "hint": "한 줄에 IP 주소 또는 CIDR 범위 하나. 모든 주소를 허용하려면 비워 두세요.",+ "invalid": "IPv4 주소 또는 CIDR 범위가 아닙니다: {{value}}"+ },+ "chats": {+ "label": "채팅 접근 (선택)",+ "hint": "한 줄에 채팅 하나: @g.us로 끝나는 그룹 ID, @c.us 또는 @lid로 끝나는 연락처 ID, 또는 전화번호. 모든 채팅을 허용하려면 비워 두세요. 채팅이 제한된 키는 해당 키에 열린 경로만 사용할 수 있으며, 이벤트 WebSocket과 MCP는 이를 거부합니다.",+ "invalid": "채팅 ID 또는 전화번호가 아닙니다: {{value}}"+ },+ "expiry": {+ "label": "만료 시각 (선택)",+ "hint": "이 브라우저의 시간대 기준입니다. 만료되지 않는 키는 비워 두세요.",+ "clear": "만료 제거",+ "invalid": "9999년까지의 날짜와 시간을 모두 입력하거나, 만료되지 않는 키는 필드를 비우세요."}},"logs": {diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 2f0cf89e4..b9789d6b6 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -582,6 +582,7 @@"createdTitle": "Chave API criada","createdHint": "Copie esta chave agora. Você não poderá vê-la novamente.","namePlaceholder": "ex.: Chave de produção",+ "nameTooShort": "Use pelo menos 3 caracteres.","rolesTitle": "Referência de funções","roles": {"admin": "Administrador",@@ -600,11 +601,13 @@"status": "Status","lastUsed": "Último uso","actions": "Ações",- "sessions": "Sessões"+ "sessions": "Sessões",+ "restrictions": "Restrições"},"statuses": {"active": "Ativa",- "revoked": "Revogada"+ "revoked": "Revogada",+ "expired": "Expirada"},"empty": {"title": "Nenhuma chave API criada",@@ -625,7 +628,7 @@"copy": "Copiar","revoke": "Revogar","delete": "Excluir",- "editSessions": "Editar sessões"+ "edit": "Editar acesso"},"sessions": {"label": "Acesso às sessões",@@ -633,10 +636,36 @@"all": "Todas as sessões","empty": "Ainda não há sessões. Esta chave poderá acessar todas quando existirem.","restricted": "{{count}} selecionadas",- "editTitle": "Editar acesso às sessões","save": "Salvar","choose": "Escolher sessões","leaveAll": "Deixar para todas as sessões"+ },+ "edit": {+ "title": "Editar acesso da chave",+ "signedIn": "Este painel está conectado com esta chave. Alterar a função, os endereços IP, os chats ou a expiração pode desconectar você."+ },+ "restrictions": {+ "none": "Nenhuma",+ "ips": "IPs: {{count}}",+ "chats": "Chats: {{count}}",+ "expires": "Expira em {{date}}",+ "expired": "Expirou em {{date}}"+ },+ "ips": {+ "label": "Endereços IP permitidos (opcional)",+ "hint": "Um endereço IP ou intervalo CIDR por linha. Deixe em branco para aceitar qualquer endereço.",+ "invalid": "Não é um endereço IPv4 nem um intervalo CIDR: {{value}}"+ },+ "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 WebSocket de eventos e o MCP a recusam.",+ "invalid": "Não é um ID de chat nem um número de telefone: {{value}}"+ },+ "expiry": {+ "label": "Expira em (opcional)",+ "hint": "No fuso horário deste navegador. Deixe em branco para uma chave que nunca expira.",+ "clear": "Remover expiração",+ "invalid": "Informe data e hora completas, até o ano 9999, ou limpe o campo para uma chave que nunca expira."}},"logs": {diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex c0cfd60f9..0d6ec13ad 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -625,6 +625,7 @@"createdTitle": "API కీ సృష్టించబడింది","createdHint": "ఈ కీని ఇప్పుడే కాపీ చేసుకోండి. మీరు దీన్ని మళ్లీ చూడలేరు.","namePlaceholder": "ఉదాహరణకు, Production Key",+ "nameTooShort": "కనీసం 3 అక్షరాలు ఉపయోగించండి.","rolesTitle": "పాత్రల సూచిక (Roles Reference)","roles": {"admin": "అడ్మిన్",@@ -643,11 +644,13 @@"status": "స్థితి","lastUsed": "చివరిగా ఉపయోగించినది","actions": "చర్యలు",- "sessions": "సెషన్లు"+ "sessions": "సెషన్లు",+ "restrictions": "పరిమితులు"},"statuses": {"active": "యాక్టివ్",- "revoked": "రద్దు చేయబడింది"+ "revoked": "రద్దు చేయబడింది",+ "expired": "గడువు ముగిసింది"},"empty": {"title": "ఎలాంటి API కీలు సృష్టించబడలేదు",@@ -668,7 +671,7 @@"copy": "కాపీ","revoke": "రద్దు చేయి","delete": "తొలగించు",- "editSessions": "సెషన్లను సవరించు"+ "edit": "యాక్సెస్ సవరించు"},"sessions": {"label": "సెషన్ యాక్సెస్",@@ -676,10 +679,36 @@"all": "అన్ని సెషన్లు","empty": "ఇంకా సెషన్లు లేవు. సెషన్లు ఉన్న తర్వాత ఈ కీ అన్నింటికీ యాక్సెస్ పొందుతుంది.","restricted": "{{count}} ఎంచుకున్నారు",- "editTitle": "సెషన్ యాక్సెస్ను సవరించు","save": "సేవ్","choose": "సెషన్లను ఎంచుకోండి","leaveAll": "అన్ని సెషన్లకు వదిలేయండి"+ },+ "edit": {+ "title": "కీ యాక్సెస్ సవరించు",+ "signedIn": "ఈ డాష్బోర్డ్ ఈ కీతో సైన్ ఇన్ అయి ఉంది. దాని పాత్ర, IP చిరునామాలు, చాట్లు లేదా గడువును మార్చడం వల్ల మీరు సైన్ అవుట్ కావచ్చు."+ },+ "restrictions": {+ "none": "ఏదీ లేదు",+ "ips": "IPలు: {{count}}",+ "chats": "చాట్లు: {{count}}",+ "expires": "{{date}}న గడువు ముగుస్తుంది",+ "expired": "{{date}}న గడువు ముగిసింది"+ },+ "ips": {+ "label": "అనుమతించిన IP చిరునామాలు (ఐచ్ఛికం)",+ "hint": "ప్రతి పంక్తికి ఒక IP చిరునామా లేదా CIDR పరిధి. ఏ చిరునామానైనా అంగీకరించడానికి ఖాళీగా వదిలేయండి.",+ "invalid": "ఇది IPv4 చిరునామా లేదా CIDR పరిధి కాదు: {{value}}"+ },+ "chats": {+ "label": "చాట్ యాక్సెస్ (ఐచ్ఛికం)",+ "hint": "ప్రతి పంక్తికి ఒక చాట్: @g.us తో ముగిసే గ్రూప్ ID, @c.us లేదా @lid తో ముగిసే కాంటాక్ట్ ID, లేదా ఫోన్ నంబర్. అన్ని చాట్ల కోసం ఖాళీగా వదిలేయండి. చాట్లకు పరిమితమైన కీ అలాంటి కీలకు తెరిచిన రూట్లను మాత్రమే ఉపయోగించగలదు; ఈవెంట్స్ WebSocket మరియు MCP దాన్ని తిరస్కరిస్తాయి.",+ "invalid": "ఇది చాట్ ID లేదా ఫోన్ నంబర్ కాదు: {{value}}"+ },+ "expiry": {+ "label": "గడువు సమయం (ఐచ్ఛికం)",+ "hint": "ఈ బ్రౌజర్ టైమ్ జోన్లో. ఎప్పటికీ గడువు ముగియని కీ కోసం ఖాళీగా వదిలేయండి.",+ "clear": "గడువును తీసివేయండి",+ "invalid": "9999వ సంవత్సరం దాటని పూర్తి తేదీ మరియు సమయాన్ని నమోదు చేయండి, లేదా ఎప్పటికీ గడువు ముగియని కీ కోసం ఫీల్డ్ను ఖాళీ చేయండి."}},"logs": {diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.jsonindex 9380ca2e4..3e766d106 100644--- a/dashboard/src/i18n/locales/tr.json+++ b/dashboard/src/i18n/locales/tr.json@@ -625,6 +625,7 @@"createdTitle": "API Anahtarı Oluşturuldu","createdHint": "Bu anahtarı şimdi kopyalayın. Bir daha göremeyeceksiniz.","namePlaceholder": "ör. Prodüksiyon Anahtarı",+ "nameTooShort": "En az 3 karakter kullanın.","rolesTitle": "Roller Referansı","roles": {"admin": "Yönetici (Admin)",@@ -643,11 +644,13 @@"status": "Durum","lastUsed": "Son Kullanım","actions": "İşlemler",- "sessions": "Oturumlar"+ "sessions": "Oturumlar",+ "restrictions": "Kısıtlamalar"},"statuses": {"active": "Aktif",- "revoked": "Geçersiz Kılındı"+ "revoked": "Geçersiz Kılındı",+ "expired": "Süresi doldu"},"empty": {"title": "Oluşturulmuş API anahtarı yok",@@ -668,7 +671,7 @@"copy": "Kopyala","revoke": "Geçersiz Kıl","delete": "Sil",- "editSessions": "Oturumları düzenle"+ "edit": "Erişimi düzenle"},"sessions": {"label": "Oturum erişimi",@@ -676,10 +679,36 @@"all": "Tüm oturumlar","empty": "Henüz oturum yok. Oturumlar oluşunca bu anahtar hepsine erişebilir.","restricted": "{{count}} seçildi",- "editTitle": "Oturum erişimini düzenle","save": "Kaydet","choose": "Oturumları seç","leaveAll": "Tüm oturumlar için bırak"+ },+ "edit": {+ "title": "Anahtar erişimini düzenle",+ "signedIn": "Bu panel bu anahtarla oturum açtı. Rolünü, IP adreslerini, sohbetlerini veya son kullanma tarihini değiştirmek oturumunuzu kapatabilir."+ },+ "restrictions": {+ "none": "Yok",+ "ips": "IP'ler: {{count}}",+ "chats": "Sohbetler: {{count}}",+ "expires": "Son kullanma: {{date}}",+ "expired": "Süresi doldu: {{date}}"+ },+ "ips": {+ "label": "İzin verilen IP adresleri (isteğe bağlı)",+ "hint": "Her satıra bir IP adresi veya CIDR aralığı. Tüm adresleri kabul etmek için boş bırakın.",+ "invalid": "IPv4 adresi veya CIDR aralığı değil: {{value}}"+ },+ "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 onu reddeder.",+ "invalid": "Sohbet kimliği veya telefon numarası değil: {{value}}"+ },+ "expiry": {+ "label": "Son kullanma tarihi (isteğe bağlı)",+ "hint": "Bu tarayıcının saat diliminde. Süresi hiç dolmayan bir anahtar için boş bırakın.",+ "clear": "Son kullanma tarihini kaldır",+ "invalid": "9999 yılını geçmeyen eksiksiz bir tarih ve saat girin ya da süresi hiç dolmayan bir anahtar için alanı temizleyin."}},"logs": {diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex 528aee951..fbd0ba032 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -625,6 +625,7 @@"createdTitle": "API 密钥已创建","createdHint": "请立即复制此密钥。之后将无法再次查看。","namePlaceholder": "例如:Production Key",+ "nameTooShort": "请至少输入 3 个字符。","rolesTitle": "角色参考","roles": {"admin": "管理员",@@ -643,11 +644,13 @@"status": "状态","lastUsed": "上次使用","actions": "操作",- "sessions": "会话"+ "sessions": "会话",+ "restrictions": "限制"},"statuses": {"active": "活跃",- "revoked": "已撤销"+ "revoked": "已撤销",+ "expired": "已过期"},"empty": {"title": "尚未创建 API 密钥",@@ -668,7 +671,7 @@"copy": "复制","revoke": "撤销","delete": "删除",- "editSessions": "编辑会话"+ "edit": "编辑访问权限"},"sessions": {"label": "会话访问",@@ -676,10 +679,36 @@"all": "全部会话","empty": "暂无会话。创建会话后,此密钥将可以访问全部会话。","restricted": "已选 {{count}} 个",- "editTitle": "编辑会话访问","save": "保存","choose": "选择会话","leaveAll": "保留为全部会话"+ },+ "edit": {+ "title": "编辑密钥访问权限",+ "signedIn": "此仪表板正使用该密钥登录。更改其角色、IP 地址、聊天或过期时间可能会使你退出登录。"+ },+ "restrictions": {+ "none": "无",+ "ips": "IP:{{count}}",+ "chats": "聊天:{{count}}",+ "expires": "{{date}} 过期",+ "expired": "已于 {{date}} 过期"+ },+ "ips": {+ "label": "允许的 IP 地址(可选)",+ "hint": "每行一个 IP 地址或 CIDR 范围。留空则接受任意地址。",+ "invalid": "不是 IPv4 地址或 CIDR 范围:{{value}}"+ },+ "chats": {+ "label": "聊天访问(可选)",+ "hint": "每行一个聊天:以 @g.us 结尾的群组 ID、以 @c.us 或 @lid 结尾的联系人 ID,或电话号码。留空则允许所有聊天。受聊天限制的密钥只能使用对此类密钥开放的路由;事件 WebSocket 和 MCP 会拒绝它。",+ "invalid": "不是聊天 ID 或电话号码:{{value}}"+ },+ "expiry": {+ "label": "过期时间(可选)",+ "hint": "使用此浏览器的时区。留空则密钥永不过期。",+ "clear": "移除过期时间",+ "invalid": "请填写不晚于 9999 年的完整日期和时间,或清空此字段使密钥永不过期。"}},"logs": {diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex a924164ea..47e2cb544 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -625,6 +625,7 @@"createdTitle": "API 金鑰已建立","createdHint": "請立即複製此金鑰。之後將無法再次查看。","namePlaceholder": "例如:Production Key",+ "nameTooShort": "請至少輸入 3 個字元。","rolesTitle": "角色參考","roles": {"admin": "管理員",@@ -643,11 +644,13 @@"status": "狀態","lastUsed": "上次使用","actions": "操作",- "sessions": "工作階段"+ "sessions": "工作階段",+ "restrictions": "限制"},"statuses": {"active": "活躍",- "revoked": "已撤銷"+ "revoked": "已撤銷",+ "expired": "已過期"},"empty": {"title": "尚未建立 API 金鑰",@@ -668,7 +671,7 @@"copy": "複製","revoke": "撤銷","delete": "刪除",- "editSessions": "編輯工作階段"+ "edit": "編輯存取權限"},"sessions": {"label": "工作階段存取",@@ -676,10 +679,36 @@"all": "全部工作階段","empty": "尚未有工作階段。建立後,此密鑰便可存取全部工作階段。","restricted": "已選 {{count}} 個",- "editTitle": "編輯工作階段存取","save": "儲存","choose": "選擇工作階段","leaveAll": "保留為全部工作階段"+ },+ "edit": {+ "title": "編輯金鑰存取權限",+ "signedIn": "此控制台正以此金鑰登入。更改其角色、IP 位址、聊天或到期時間可能會令你登出。"+ },+ "restrictions": {+ "none": "無",+ "ips": "IP:{{count}}",+ "chats": "聊天:{{count}}",+ "expires": "{{date}} 到期",+ "expired": "已於 {{date}} 過期"+ },+ "ips": {+ "label": "允許的 IP 位址(選填)",+ "hint": "每行一個 IP 位址或 CIDR 範圍。留空則接受任何位址。",+ "invalid": "不是 IPv4 位址或 CIDR 範圍:{{value}}"+ },+ "chats": {+ "label": "聊天存取(選填)",+ "hint": "每行一個聊天:以 @g.us 結尾的群組 ID、以 @c.us 或 @lid 結尾的聯絡人 ID,或電話號碼。留空則允許所有聊天。受聊天限制的金鑰只可使用對此類金鑰開放的路由;事件 WebSocket 及 MCP 會拒絕它。",+ "invalid": "不是聊天 ID 或電話號碼:{{value}}"+ },+ "expiry": {+ "label": "到期時間(選填)",+ "hint": "使用此瀏覽器的時區。留空則金鑰永不過期。",+ "clear": "移除到期時間",+ "invalid": "請填寫不晚於 9999 年的完整日期和時間,或清空此欄位使金鑰永不過期。"}},"logs": {diff --git a/dashboard/src/pages/ApiKeys.css b/dashboard/src/pages/ApiKeys.cssindex 3aa8916e4..7c7cbe3f1 100644--- a/dashboard/src/pages/ApiKeys.css+++ b/dashboard/src/pages/ApiKeys.css@@ -359,6 +359,97 @@color: var(--text-primary);}+/* Key limit fields (IP allow-list, chats, expiry) in the create and edit modals. */+.api-keys-page .modal-body > textarea {+ width: 100%;+ padding: 0.625rem 1rem;+ border: 1px solid var(--border);+ border-radius: 8px;+ font-size: 0.875rem;+ font-family: 'JetBrains Mono Variable', 'JetBrains Mono', monospace;+ background: var(--bg-light);+ box-sizing: border-box;+ resize: vertical;+}++.api-keys-page .modal-body > select,+.api-keys-page .modal-body > textarea {+ margin-bottom: 0.25rem;+}++.api-keys-page .key-field-hint {+ display: block;+ font-size: 0.75rem;+ color: var(--text-muted);+ margin-bottom: 0.875rem;+}++.api-keys-page .key-field-hint.error {+ color: var(--error-text);+ margin-bottom: 0.25rem;+}++.api-keys-page .key-expiry-row {+ display: flex;+ gap: 0.5rem;+ align-items: center;+ margin-bottom: 0.25rem;+}++.api-keys-page .key-expiry-row input {+ flex: 1 1 auto;+}++.api-keys-page .key-expiry-row button {+ flex: none;+ white-space: nowrap;+}++.api-keys-page .key-signed-in-warning {+ display: flex;+ gap: 0.5rem;+ align-items: flex-start;+ margin: 0 0 1rem;+ padding: 0.625rem 0.75rem;+ border-radius: 8px;+ background: rgba(245, 158, 11, 0.12);+ color: var(--text-primary);+ font-size: 0.8125rem;+}++.api-keys-page .key-signed-in-warning svg {+ flex: none;+ margin-top: 0.125rem;+ color: var(--warning, #f59e0b);+}++.api-keys-page .restrictions-cell {+ display: inline-flex;+ flex-wrap: wrap;+ gap: 0.25rem;+ font-size: 0.8125rem;+}++.api-keys-page .restrictions-cell.none {+ color: var(--text-muted);+}++.api-keys-page .restriction-badge {+ font-size: 0.6875rem;+ padding: 0.125rem 0.5rem;+ border-radius: 9999px;+ background: var(--bg-light);+ border: 1px solid var(--border);+ color: var(--text-secondary);+ white-space: nowrap;+}++.api-keys-page .restriction-badge.expired {+ background: rgba(239, 68, 68, 0.12);+ border-color: transparent;+ color: var(--error-text);+}+/* Mobile Responsive *//* Status badges — must apply on DESKTOP too (they were stranded inside the mobile media query,leaving every Active/Revoked badge unstyled on wide screens). */@@ -467,6 +558,7 @@/* Role, sessions & status sit together as chips */.api-keys-page .keys-table tbody tr.table-row td:has(.permission-badge),.api-keys-page .keys-table tbody tr.table-row td:has(.sessions-cell),+ .api-keys-page .keys-table tbody tr.table-row td:has(.restrictions-cell),.api-keys-page .keys-table tbody tr.table-row td:has(.status-badge) {display: inline-block;order: 3;diff --git a/dashboard/src/pages/ApiKeys.test.ts b/dashboard/src/pages/ApiKeys.test.tsindex d1c7a96e1..ecf3bca5d 100644--- a/dashboard/src/pages/ApiKeys.test.ts+++ b/dashboard/src/pages/ApiKeys.test.ts@@ -11,31 +11,43 @@ function jsonResponse(data: unknown, status = 200): Response {return new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } });}-// The status GET /auth/api-keys answers with: 200 lists the key below.+// The status GET /auth/api-keys answers with: 200 lists `keyList`.let listStatus = 200;+const billingBot = {+ id: 'key-1',+ name: 'billing-bot',+ keyPrefix: 'owa_k1ab',+ role: 'operator',+ isActive: true,+ usageCount: 0,+ createdAt: '2026-01-01T00:00:00.000Z',+};+let keyList: Record<string, unknown>[] = [billingBot];+let createBody: Record<string, unknown> | undefined;+let updateBodies: Record<string, unknown>[] = [];+let updateStatus = 200;function installFetchStub(): void {- globalThis.fetch = ((input: RequestInfo | URL): Promise<Response> => {+ globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;const path = url.replace(/^https?:\/\/[^/]+/, '');if (path === '/api/sessions') return Promise.resolve(jsonResponse([]));+ if (init?.method === 'POST' && path === '/api/auth/api-keys') {+ createBody = JSON.parse(String(init.body));+ return Promise.resolve(jsonResponse({ ...billingBot, id: 'key-new', apiKey: 'owa_k1_new' }, 201));+ }+ if (init?.method === 'PUT' && path.startsWith('/api/auth/api-keys/')) {+ updateBodies.push(JSON.parse(String(init.body)));+ if (updateStatus === 409) {+ return Promise.resolve(jsonResponse({ message: 'Cannot remove the last active admin key' }, 409));+ }+ return Promise.resolve(jsonResponse(billingBot));+ }if (path === '/api/auth/api-keys') {if (listStatus !== 200) {return Promise.resolve(jsonResponse({ message: 'This API key cannot access this resource' }, listStatus));}- return Promise.resolve(- jsonResponse([- {- id: 'key-1',- name: 'billing-bot',- keyPrefix: 'owa_k1ab',- role: 'operator',- isActive: true,- usageCount: 0,- createdAt: '2026-01-01T00:00:00.000Z',- },- ]),- );+ return Promise.resolve(jsonResponse(keyList));}return Promise.resolve(jsonResponse({ message: `unstubbed ${path}` }, 404));}) as typeof fetch;@@ -62,6 +74,11 @@ afterEach(() => {queryClient?.clear();queryClient = undefined;listStatus = 200;+ keyList = [billingBot];+ createBody = undefined;+ updateBodies = [];+ updateStatus = 200;+ window.sessionStorage.removeItem('openwa_api_key');});function renderApiKeys(): void {@@ -106,3 +123,329 @@ test('a failed read shows the error instead of the empty state', async () => {await rtl.screen.findByText('Could not load API keys');assert.ok(!rtl.screen.queryByText('No API keys created'), 'a failed read rendered as an empty list');});++async function openCreate(): Promise<HTMLButtonElement> {+ renderApiKeys();+ await rtl.screen.findByText('owa_k1ab****');+ rtl.fireEvent.click(rtl.screen.getByRole('button', { name: 'Create API Key' }));+ return rtl.screen.getByRole<HTMLButtonElement>('button', { name: 'Create' });+}++test('a create sends the IP allow-list, chats and expiry only when filled in', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ let create = await openCreate();+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'ab' } });+ assert.equal(create.disabled, true, 'the gateway needs at least 3 characters');+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'crm-bot' } });+ fireEvent.click(create);+ await waitFor(() => assert.ok(createBody));+ assert.deepEqual(createBody, { name: 'crm-bot', role: 'operator', allowedSessions: [] });++ rtl.cleanup();+ createBody = undefined;+ create = await openCreate();+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'crm-bot' } });+ fireEvent.change(screen.getByLabelText('Allowed IP addresses (optional)'), {+ target: { value: ' 10.0.0.1 \n\n10.0.0.0/8\n' },+ });+ fireEvent.change(screen.getByLabelText('Chat access (optional)'), {+ target: { value: '6281234\[email protected]\[email protected]' },+ });+ fireEvent.change(screen.getByLabelText('Expires at (optional)'), { target: { value: '2027-06-01T09:30' } });+ fireEvent.click(create);+ await waitFor(() => assert.ok(createBody));+ assert.deepEqual(createBody, {+ name: 'crm-bot',+ role: 'operator',+ allowedSessions: [],+ allowedIps: ['10.0.0.1', '10.0.0.0/8'],+ allowedChats: ['[email protected]', '[email protected]'],+ expiresAt: new Date('2027-06-01T09:30').toISOString(),+ });+});++test('an IP or chat line the gateway would refuse keeps Create disabled and names the line', async () => {+ const { screen, fireEvent } = rtl;+ const create = await openCreate();+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'crm-bot' } });+ fireEvent.change(screen.getByLabelText('Allowed IP addresses (optional)'), {+ target: { value: '10.0.0.1\n10.0.0.0/33' },+ });+ assert.equal(create.disabled, true);+ screen.getByText('Not an IPv4 address or CIDR range: 10.0.0.0/33');++ fireEvent.change(screen.getByLabelText('Allowed IP addresses (optional)'), { target: { value: '10.0.0.1' } });+ fireEvent.change(screen.getByLabelText('Chat access (optional)'), { target: { value: 'sales-team' } });+ assert.equal(create.disabled, true);+ screen.getByText('Not a chat ID or phone number: sales-team');+ fireEvent.click(create);+ await new Promise(resolve => setTimeout(resolve, 50));+ assert.equal(createBody, undefined);+});++test('switching the new key to admin hides and drops the chat list', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ const create = await openCreate();+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'root-key' } });+ fireEvent.change(screen.getByLabelText('Chat access (optional)'), { target: { value: '[email protected]' } });+ fireEvent.change(screen.getByLabelText('Role'), { target: { value: 'admin' } });+ assert.equal(screen.queryByLabelText('Chat access (optional)'), null);+ fireEvent.click(create);+ await waitFor(() => assert.ok(createBody));+ assert.deepEqual(createBody, { name: 'root-key', role: 'admin' });+});++test('a key row shows its IP, chat and expiry limits, and an expired key is not badged active', async () => {+ keyList = [+ {+ ...billingBot,+ allowedIps: ['10.0.0.1', '10.0.0.0/8'],+ allowedChats: ['[email protected]'],+ expiresAt: '2020-01-01T00:00:00.000Z',+ },+ { ...billingBot, id: 'key-2', name: 'open-key', keyPrefix: 'owa_k1cd' },+ ];+ renderApiKeys();+ await rtl.screen.findByText('IPs: 2');+ rtl.screen.getByText('Chats: 1');+ rtl.screen.getByText(/^Expired .+/);+ const rows = Array.from(document.querySelectorAll('tbody tr'));+ assert.equal(rows[0].querySelector('.status-badge')?.textContent, 'Expired');+ assert.equal(rows[1].querySelector('.status-badge')?.textContent, 'Active');+ assert.equal(rows[1].querySelector('.restrictions-cell')?.textContent, 'None');+});++test('an active admin key can be edited; a revoked key cannot', async () => {+ keyList = [+ { ...billingBot, role: 'admin' },+ { ...billingBot, id: 'key-2', name: 'old-key', keyPrefix: 'owa_k1cd', isActive: false },+ ];+ renderApiKeys();+ await rtl.screen.findByText('owa_k1ab****');+ assert.equal(rtl.screen.getAllByTitle('Edit access').length, 1);+ rtl.fireEvent.click(rtl.screen.getByTitle('Edit access'));+ // Admin keys stay unscoped in the dashboard: no session or chat fields.+ assert.equal(rtl.screen.queryByLabelText('Chat access (optional)'), null);+ rtl.screen.getByLabelText('Allowed IP addresses (optional)');+});++async function openEdit(key: Record<string, unknown>): Promise<HTMLButtonElement> {+ keyList = [key];+ renderApiKeys();+ await rtl.screen.findByText(`${String(key.keyPrefix)}****`);+ rtl.fireEvent.click(rtl.screen.getByTitle('Edit access'));+ return rtl.screen.getByRole<HTMLButtonElement>('button', { name: 'Save' });+}++test('saving an untouched key sends nothing, even with an expiry and lists set', async () => {+ const save = await openEdit({+ ...billingBot,+ allowedIps: ['10.0.0.1'],+ allowedChats: ['[email protected]'],+ allowedSessions: ['sess-gone'],+ expiresAt: '2027-03-04T05:06:59.000Z',+ });+ rtl.fireEvent.click(save);+ await rtl.waitFor(() => assert.equal(rtl.screen.queryByRole('button', { name: 'Save' }), null));+ assert.deepEqual(updateBodies, []);+});++test('an edit sends only what changed', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ let save = await openEdit({ ...billingBot, expiresAt: '2027-03-04T05:06:59.000Z' });+ fireEvent.click(screen.getByRole('button', { name: 'Remove expiry' }));+ fireEvent.change(screen.getByLabelText('Chat access (optional)'), { target: { value: '6281234' } });+ fireEvent.click(save);+ await waitFor(() => assert.equal(updateBodies.length, 1));+ assert.deepEqual(updateBodies[0], { allowedChats: ['[email protected]'], expiresAt: null });++ rtl.cleanup();+ save = await openEdit({ ...billingBot, allowedSessions: ['sess-1'] });+ fireEvent.change(screen.getByLabelText('Role'), { target: { value: 'admin' } });+ fireEvent.click(save);+ await waitFor(() => assert.equal(updateBodies.length, 2));+ assert.deepEqual(updateBodies[1], { role: 'admin', allowedSessions: [] });+});++test('a bad IP line keeps Save disabled in the editor', async () => {+ const { screen, fireEvent } = rtl;+ const save = await openEdit(billingBot);+ fireEvent.change(screen.getByLabelText('Allowed IP addresses (optional)'), { target: { value: '::1' } });+ assert.equal(save.disabled, true);+ screen.getByText('Not an IPv4 address or CIDR range: ::1');+ fireEvent.click(save);+ await new Promise(resolve => setTimeout(resolve, 50));+ assert.deepEqual(updateBodies, []);+});++// A list stored before the gateway checked entries, or before a chat rule tightened, is not sent when+// left as it is, so its old entries must not block an unrelated edit.+test('an untouched list with an entry the form would refuse does not block Save', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ const save = await openEdit({+ ...billingBot,+ allowedIps: ['fd00::1', '10.0.0.1'],+ allowedChats: ['legacy-chat'],+ expiresAt: '2027-03-04T05:06:59.000Z',+ });+ assert.equal(save.disabled, false);+ fireEvent.click(screen.getByRole('button', { name: 'Remove expiry' }));+ fireEvent.click(save);+ await waitFor(() => assert.equal(updateBodies.length, 1));+ assert.deepEqual(updateBodies[0], { expiresAt: null });++ // Once the list is edited it is sent whole, so every entry is checked again.+ rtl.cleanup();+ const edited = await openEdit({ ...billingBot, allowedIps: ['fd00::1', '10.0.0.1'] });+ fireEvent.change(screen.getByLabelText('Allowed IP addresses (optional)'), { target: { value: 'fd00::1' } });+ assert.equal(edited.disabled, true);+ screen.getByText('Not an IPv4 address or CIDR range: fd00::1');+});++test('a refused update keeps the editor open and shows the reason', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ updateStatus = 409;+ const save = await openEdit({ ...billingBot, role: 'admin' });+ fireEvent.change(screen.getByLabelText('Role'), { target: { value: 'viewer' } });+ fireEvent.click(save);+ await screen.findByText('Cannot remove the last active admin key');+ await waitFor(() => assert.equal(save.disabled, false));+ screen.getByRole('button', { name: 'Save' });+});++test('editing the key the dashboard is signed in with warns before saving', async () => {+ window.sessionStorage.setItem('openwa_api_key', 'owa_k1abXXXXYYYYZZZZ');+ await openEdit(billingBot);+ rtl.screen.getByText(/This dashboard is signed in with this key/);+ rtl.cleanup();+ window.sessionStorage.setItem('openwa_api_key', 'owa_k1zzXXXXYYYYZZZZ');+ await openEdit(billingBot);+ assert.equal(rtl.screen.queryByText(/This dashboard is signed in with this key/), null);+});++// A datetime-local with a blank segment reports value '' (as an empty field does) and sets badInput.+// jsdom never sets badInput, so it is stubbed on the element. As in a browser, assigning the element's+// value from code wipes the leftover segments; the value fireEvent.change types goes through the+// prototype setter and leaves them.+function markExpiryIncomplete(): void {+ const input = rtl.screen.getByLabelText<HTMLInputElement>('Expires at (optional)');+ let incomplete = true;+ const own = Object.getOwnPropertyDescriptor(input, 'value');+ const proto = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');+ Object.defineProperty(input, 'value', {+ configurable: true,+ get: () => (own?.get ?? proto!.get!).call(input),+ set: (value: string) => {+ incomplete = false;+ (own?.set ?? proto!.set!).call(input, value);+ },+ });+ Object.defineProperty(input, 'validity', {+ configurable: true,+ get: () => ({ valid: !incomplete, badInput: incomplete }),+ });+}++const invalidExpiry =+ 'Enter a complete date and time no later than the year 9999, or clear the field for a key that never expires.';++test('a half-filled expiry blocks Create and Save instead of meaning no expiry', async () => {+ const { screen, fireEvent } = rtl;+ const create = await openCreate();+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'crm-bot' } });+ markExpiryIncomplete();+ fireEvent.click(create);+ await screen.findByText(invalidExpiry);+ assert.equal(createBody, undefined);++ rtl.cleanup();+ const save = await openEdit({ ...billingBot, expiresAt: '2027-03-04T05:06:59.000Z' });+ fireEvent.change(screen.getByLabelText('Expires at (optional)'), { target: { value: '' } });+ markExpiryIncomplete();+ fireEvent.click(save);+ await screen.findByText(invalidExpiry);+ assert.deepEqual(updateBodies, []);+});++test('Remove expiry clears a half-filled expiry so Save drops it', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ const save = await openEdit({ ...billingBot, expiresAt: '2027-03-04T05:06:59.000Z' });+ markExpiryIncomplete();+ // Deleting one segment turns the value to '' while the others stay filled.+ fireEvent.change(screen.getByLabelText('Expires at (optional)'), { target: { value: '' } });+ fireEvent.click(screen.getByRole('button', { name: 'Remove expiry' }));+ fireEvent.click(save);+ await waitFor(() => assert.equal(updateBodies.length, 1));+ assert.deepEqual(updateBodies[0], { expiresAt: null });++ rtl.cleanup();+ const create = await openCreate();+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'crm-bot' } });+ fireEvent.change(screen.getByLabelText('Expires at (optional)'), { target: { value: '2027-03-04T05:06' } });+ markExpiryIncomplete();+ fireEvent.change(screen.getByLabelText('Expires at (optional)'), { target: { value: '' } });+ fireEvent.click(screen.getByRole('button', { name: 'Remove expiry' }));+ fireEvent.click(create);+ await waitFor(() => assert.notEqual(createBody, undefined));+ assert.equal(createBody?.expiresAt, undefined);+});++// Typing part of a date into an empty field keeps the value at '', so the browser fires no change+// event; leaving the field (as clicking Create or Save does) must still offer Remove expiry.+test('Remove expiry appears for a partial expiry typed into an empty field', async () => {+ const { screen, fireEvent, waitFor } = rtl;+ const create = await openCreate();+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'crm-bot' } });+ markExpiryIncomplete();+ fireEvent.blur(screen.getByLabelText('Expires at (optional)'));+ fireEvent.click(create);+ await screen.findByText(invalidExpiry);+ assert.equal(createBody, undefined);+ fireEvent.click(screen.getByRole('button', { name: 'Remove expiry' }));+ fireEvent.click(create);+ await waitFor(() => assert.notEqual(createBody, undefined));+ assert.deepEqual(createBody, { name: 'crm-bot', role: 'operator', allowedSessions: [] });++ rtl.cleanup();+ const save = await openEdit(billingBot);+ markExpiryIncomplete();+ fireEvent.blur(screen.getByLabelText('Expires at (optional)'));+ fireEvent.click(save);+ await screen.findByText(invalidExpiry);+ assert.deepEqual(updateBodies, []);+ fireEvent.click(screen.getByRole('button', { name: 'Remove expiry' }));+ fireEvent.click(save);+ await waitFor(() => assert.equal(screen.queryByRole('button', { name: 'Save' }), null));+ assert.deepEqual(updateBodies, []);+});++// Chrome takes up to six year digits in a datetime-local without a max, and new Date() cannot parse a+// five-digit year, so such a value used to reach toISOString() and throw.+test('an expiry past the year 9999 blocks Create and Save with a message', async () => {+ const { screen, fireEvent } = rtl;+ const create = await openCreate();+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'crm-bot' } });+ fireEvent.change(screen.getByLabelText('Expires at (optional)'), { target: { value: '20266-01-01T00:00' } });+ fireEvent.click(create);+ await screen.findByText(invalidExpiry);+ assert.equal(createBody, undefined);++ rtl.cleanup();+ const save = await openEdit(billingBot);+ fireEvent.change(screen.getByLabelText('Expires at (optional)'), { target: { value: '20266-01-01T00:00' } });+ fireEvent.click(save);+ await screen.findByText(invalidExpiry);+ assert.deepEqual(updateBodies, []);+});++test('an expiry Save cannot convert ends in an error toast, not a silent no-op', async () => {+ const { screen, fireEvent } = rtl;+ const save = await openEdit(billingBot);+ const input = screen.getByLabelText<HTMLInputElement>('Expires at (optional)');+ fireEvent.change(input, { target: { value: '20266-01-01T00:00' } });+ // A browser that let the value through as valid.+ Object.defineProperty(input, 'validity', { value: { valid: true }, configurable: true });+ fireEvent.click(save);+ await screen.findByText('Invalid time value');+ assert.deepEqual(updateBodies, []);+});diff --git a/dashboard/src/pages/ApiKeys.tsx b/dashboard/src/pages/ApiKeys.tsxindex fb2d04404..f1bc5a8fe 100644--- a/dashboard/src/pages/ApiKeys.tsx+++ b/dashboard/src/pages/ApiKeys.tsx@@ -1,4 +1,4 @@-import { useState, useEffect, useMemo } from 'react';+import { useState, useEffect, useMemo, useRef, type RefObject } from 'react';import { Trans, useTranslation } from 'react-i18next';import {useTable,@@ -36,12 +36,151 @@ import { Modal } from '../components/Modal';import { SessionScopePicker } from '../components/SessionScopePicker';import { useToast } from '../hooks/useToast';import { copyToClipboard } from '../utils/clipboard';-import { canScopeSessions, sameSessionScope, sessionScopeNames } from '../utils/sessionScope';+import {+ apiKeyDraft,+ apiKeyPatch,+ canScopeSessions,+ invalidChatEntry,+ invalidIpEntry,+ isExpired,+ normalizeChatScope,+ parseScopeList,+ sameSessionScope,+ sessionScopeNames,+ type ApiKeyDraft,+} from '../utils/sessionScope';import './ApiKeys.css';const roleNames = ['admin', 'operator', 'viewer'] as const;-const emptyKeyForm = { name: '', role: 'operator', allowedSessions: [] as string[] };+const emptyKeyForm = { name: '', role: 'operator', allowedSessions: [] as string[], ips: '', chats: '', expires: '' };++// The key this dashboard signed in with: the list only carries each key's prefix, which is the first+// 12 characters of the raw key.+function isSignedInKey(apiKey: ApiKey): boolean {+ return !!apiKey.keyPrefix && !!sessionStorage.getItem('openwa_api_key')?.startsWith(apiKey.keyPrefix);+}++// 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.+function limitErrors(+ role: string,+ ips: string,+ chats: string,+ stored?: Pick<ApiKey, 'allowedIps' | 'allowedChats'>,+): { ip: string | null; chat: string | null } {+ const ipList = parseScopeList(ips);+ const chatList = normalizeChatScope(chats);+ const unchanged = (list: string[], storedList: string[] | undefined) =>+ !!stored && sameSessionScope(list, storedList ?? []);+ return {+ ip: unchanged(ipList, stored?.allowedIps) ? null : invalidIpEntry(ipList),+ chat: !canScopeSessions(role) || unchanged(chatList, stored?.allowedChats) ? null : invalidChatEntry(chatList),+ };+}++// IP, chat and expiry limits shared by the create and edit modals. Chats are offered only where+// sessions are: admin keys stay unscoped in the dashboard.+function KeyLimitFields({+ idPrefix,+ role,+ ips,+ chats,+ expires,+ errors,+ onChange,+ disabled,+ expiresRef,+}: {+ idPrefix: string;+ role: string;+ ips: string;+ chats: string;+ expires: string;+ errors: { ip: string | null; chat: string | null };+ onChange: (patch: { ips?: string; chats?: string; expires?: string }) => void;+ disabled?: boolean;+ expiresRef: RefObject<HTMLInputElement | null>;+}) {+ const { t } = useTranslation();+ // A datetime-local with a blank segment reports value '', like an empty field, so only badInput says+ // there are leftover segments to clear.+ const [partialExpiry, setPartialExpiry] = useState(false);+ return (+ <>+ <label htmlFor={`${idPrefix}-ips`}>{t('apiKeys.ips.label')}</label>+ <textarea+ id={`${idPrefix}-ips`}+ rows={2}+ spellCheck={false}+ value={ips}+ disabled={disabled}+ onChange={e => onChange({ ips: e.target.value })}+ />+ {errors.ip !== null && (+ <span className="key-field-hint error" role="alert">+ {t('apiKeys.ips.invalid', { value: errors.ip })}+ </span>+ )}+ <span className="key-field-hint">{t('apiKeys.ips.hint')}</span>+ {canScopeSessions(role) && (+ <>+ <label htmlFor={`${idPrefix}-chats`}>{t('apiKeys.chats.label')}</label>+ <textarea+ id={`${idPrefix}-chats`}+ rows={2}+ spellCheck={false}+ value={chats}+ disabled={disabled}+ onChange={e => onChange({ chats: e.target.value })}+ />+ {errors.chat !== null && (+ <span className="key-field-hint error" role="alert">+ {t('apiKeys.chats.invalid', { value: errors.chat })}+ </span>+ )}+ <span className="key-field-hint">{t('apiKeys.chats.hint')}</span>+ </>+ )}+ <label htmlFor={`${idPrefix}-expires`}>{t('apiKeys.expiry.label')}</label>+ <div className="key-expiry-row">+ <input+ id={`${idPrefix}-expires`}+ ref={expiresRef}+ type="datetime-local"+ max="9999-12-31T23:59"+ value={expires}+ disabled={disabled}+ onChange={e => {+ setPartialExpiry(e.target.validity.badInput);+ onChange({ expires: e.target.value });+ }}+ // A partial date typed into an empty field leaves the value at '' and fires no change, so+ // badInput is read again when focus leaves the field (clicking Create or Save does that).+ onBlur={e => setPartialExpiry(e.currentTarget.validity.badInput)}+ />+ {(expires || partialExpiry) && (+ <button+ type="button"+ className="btn-secondary"+ disabled={disabled}+ onClick={() => {+ // With the state already '', React writes nothing to the input, so the segments are+ // wiped here.+ if (expiresRef.current) expiresRef.current.value = '';+ setPartialExpiry(false);+ onChange({ expires: '' });+ }}+ >+ {t('apiKeys.expiry.clear')}+ </button>+ )}+ </div>+ <span className="key-field-hint">{t('apiKeys.expiry.hint')}</span>+ </>+ );+}function useWindowSize() {const [width, setWidth] = useState(window.innerWidth);@@ -75,7 +214,7 @@ export function ApiKeys() {const [createdKey, setCreatedKey] = useState<string | null>(null);const [copied, setCopied] = useState<string | null>(null);const [editingKey, setEditingKey] = useState<ApiKey | null>(null);- const [editSessions, setEditSessions] = useState<string[]>([]);+ const [editDraft, setEditDraft] = useState<ApiKeyDraft | null>(null);const [confirmAction, setConfirmAction] = useState<{ type: 'delete' | 'revoke'; id: string; name: string } | null>(null,);@@ -86,7 +225,7 @@ export function ApiKeys() {const [columnVisibility, setColumnVisibility] = useState<ColumnVisibilityState>({});useEffect(() => {- setColumnVisibility({ key: !isSmall, lastUsed: !isMobile });+ setColumnVisibility({ key: !isSmall, lastUsed: !isMobile, restrictions: !isMobile });}, [isMobile, isSmall]);const closeCreateModal = () => {@@ -95,13 +234,29 @@ export function ApiKeys() {setNewKey(emptyKeyForm);};+ // A datetime-local with a blank segment reports an empty value, the same as no expiry at all, and+ // fires no change while it stays incomplete. Only the input's own validity tells the two apart. It+ // also flags a year past the max, which new Date() cannot parse.+ const newExpiresRef = useRef<HTMLInputElement>(null);+ const editExpiresRef = useRef<HTMLInputElement>(null);+const handleCreate = async () => {- if (!newKey.name) return;+ if (!canCreate) return;+ if (newExpiresRef.current && !newExpiresRef.current.validity.valid) {+ toast.error(t('apiKeys.createBtn'), t('apiKeys.expiry.invalid'));+ return;+ }+ const scoped = canScopeSessions(newKey.role);+ const allowedIps = parseScopeList(newKey.ips);+ const allowedChats = scoped ? normalizeChatScope(newKey.chats) : [];try {const created = await createMutation.mutateAsync({name: newKey.name,role: newKey.role,- ...(canScopeSessions(newKey.role) ? { allowedSessions: newKey.allowedSessions } : {}),+ ...(scoped ? { allowedSessions: newKey.allowedSessions } : {}),+ ...(allowedIps.length > 0 ? { allowedIps } : {}),+ ...(allowedChats.length > 0 ? { allowedChats } : {}),+ ...(newKey.expires ? { expiresAt: new Date(newKey.expires).toISOString() } : {}),});setCreatedKey(created.apiKey || null);setNewKey(emptyKeyForm);@@ -111,33 +266,45 @@ export function ApiKeys() {}};- const openEditSessions = (apiKey: ApiKey) => {+ const openEdit = (apiKey: ApiKey) => {setEditingKey(apiKey);- setEditSessions(apiKey.allowedSessions ?? []);+ setEditDraft(apiKeyDraft(apiKey));};- const handleSaveSessions = async () => {- if (!editingKey) return;- // An unchanged Save must not be sent. The server writes `allowedSessions` whenever the field is- // present, and storing [] over a key that was never scoped reads back as an authorization- // change: it drops every live /events socket holding that key and writes an audit row saying- // the scope moved when it did not.- if (sameSessionScope(editSessions, editingKey.allowedSessions ?? [])) {- setEditingKey(null);+ const closeEdit = () => {+ setEditingKey(null);+ setEditDraft(null);+ };++ const handleSave = async () => {+ if (!editingKey || !editDraft || !canSave) return;+ if (editExpiresRef.current && !editExpiresRef.current.validity.valid) {+ toast.error(t('apiKeys.edit.title'), t('apiKeys.expiry.invalid'));return;}try {- await updateMutation.mutateAsync({- id: editingKey.id,- data: { allowedSessions: editSessions },- });- setEditingKey(null);+ // An unchanged Save is not sent at all (see apiKeyPatch).+ const data = apiKeyPatch(editingKey, editDraft);+ if (Object.keys(data).length === 0) {+ closeEdit();+ return;+ }+ await updateMutation.mutateAsync({ id: editingKey.id, data });+ closeEdit();} catch (err) {- console.error('Failed to update sessions:', err);- toast.error(t('apiKeys.sessions.editTitle'), err instanceof Error ? err.message : t('common.unknownError'));+ console.error('Failed to update key:', err);+ toast.error(t('apiKeys.edit.title'), err instanceof Error ? err.message : t('common.unknownError'));}};+ const newErrors = limitErrors(newKey.role, newKey.ips, newKey.chats);+ const editErrors =+ editDraft && editingKey ? limitErrors(editDraft.role, editDraft.ips, editDraft.chats, editingKey) : null;+ // The gateway requires a name of at least 3 characters.+ const canCreate =+ !createMutation.isPending && newKey.name.trim().length >= 3 && newErrors.ip === null && newErrors.chat === null;+ const canSave = !updateMutation.isPending && editErrors?.ip === null && editErrors.chat === null;+const handleRevoke = async (id: string) => {try {await revokeMutation.mutateAsync(id);@@ -205,13 +372,54 @@ export function ApiKeys() {return <span className="sessions-cell">{t('apiKeys.sessions.restricted', { count: names.length })}</span>;},}),+ columnHelper.display({+ id: 'restrictions',+ header: () => t('apiKeys.columns.restrictions'),+ cell: info => {+ const { allowedIps, allowedChats, expiresAt } = info.row.original;+ const badges = [];+ if (allowedIps?.length) {+ badges.push(+ <span key="ips" className="restriction-badge" title={allowedIps.join('\n')}>+ {t('apiKeys.restrictions.ips', { count: allowedIps.length })}+ </span>,+ );+ }+ if (allowedChats?.length) {+ badges.push(+ <span key="chats" className="restriction-badge" title={allowedChats.join('\n')}>+ {t('apiKeys.restrictions.chats', { count: allowedChats.length })}+ </span>,+ );+ }+ if (expiresAt) {+ const date = new Date(expiresAt).toLocaleString();+ badges.push(+ <span key="expiry" className={`restriction-badge ${isExpired(expiresAt) ? 'expired' : ''}`}>+ {isExpired(expiresAt)+ ? t('apiKeys.restrictions.expired', { date })+ : t('apiKeys.restrictions.expires', { date })}+ </span>,+ );+ }+ return badges.length > 0 ? (+ <span className="restrictions-cell">{badges}</span>+ ) : (+ <span className="restrictions-cell none">{t('apiKeys.restrictions.none')}</span>+ );+ },+ }),columnHelper.accessor('isActive', {header: () => t('apiKeys.columns.status'),- cell: info => (- <span className={`status-badge ${info.getValue() ? 'active' : 'inactive'}`}>- {info.getValue() ? t('apiKeys.statuses.active') : t('apiKeys.statuses.revoked')}- </span>- ),+ cell: info => {+ // A revoked key reads as revoked; an active one past its expiry is refused just the same.+ const status = !info.getValue() ? 'revoked' : isExpired(info.row.original.expiresAt) ? 'expired' : 'active';+ return (+ <span className={`status-badge ${status === 'active' ? 'active' : 'inactive'}`}>+ {t(`apiKeys.statuses.${status}`)}+ </span>+ );+ },}),columnHelper.accessor('lastUsedAt', {id: 'lastUsed',@@ -231,12 +439,8 @@ export function ApiKeys() {<span className="actions-cell">{/* No per-row copy: the full key only exists once (post-creation modal); the rowonly has the prefix, so a copy button here could only copy a useless fragment. */}- {canScopeSessions(apiKey.role) && apiKey.isActive && (- <button- className="icon-btn"- onClick={() => openEditSessions(apiKey)}- title={t('apiKeys.actions.editSessions')}- >+ {apiKey.isActive && (+ <button className="icon-btn" onClick={() => openEdit(apiKey)} title={t('apiKeys.actions.edit')}><Pencil size={16} /></button>)}@@ -315,11 +519,7 @@ export function ApiKeys() {<button className="btn-secondary" onClick={closeCreateModal}>{t('common.cancel')}</button>- <button- className="btn-primary"- onClick={handleCreate}- disabled={createMutation.isPending || !newKey.name}- >+ <button className="btn-primary" onClick={handleCreate} disabled={!canCreate}>{createMutation.isPending ? <Loader2 className="animate-spin" size={16} /> : t('common.create')}</button></>@@ -356,6 +556,9 @@ export function ApiKeys() {value={newKey.name}onChange={e => setNewKey({ ...newKey, name: e.target.value })}/>+ {newKey.name.length > 0 && newKey.name.trim().length < 3 && (+ <span className="key-field-hint">{t('apiKeys.nameTooShort')}</span>+ )}<label htmlFor="ak-2">{t('common.role')}</label><selectid="ak-2"@@ -365,6 +568,7 @@ export function ApiKeys() {...newKey,role: e.target.value,allowedSessions: canScopeSessions(e.target.value) ? newKey.allowedSessions : [],+ chats: canScopeSessions(e.target.value) ? newKey.chats : '',})}>@@ -382,27 +586,34 @@ export function ApiKeys() {disabled={createMutation.isPending}/>)}+ <KeyLimitFields+ idPrefix="ak-new"+ role={newKey.role}+ ips={newKey.ips}+ chats={newKey.chats}+ expires={newKey.expires}+ errors={newErrors}+ onChange={patch => setNewKey(prev => ({ ...prev, ...patch }))}+ disabled={createMutation.isPending}+ expiresRef={newExpiresRef}+ /></>)}</Modal>)}- {editingKey && (+ {editingKey && editDraft && (<Modalopen- onClose={() => setEditingKey(null)}- title={t('apiKeys.sessions.editTitle')}+ onClose={closeEdit}+ title={t('apiKeys.edit.title')}closeLabel={t('common.close')}footer={<>- <button className="btn-secondary" onClick={() => setEditingKey(null)}>+ <button className="btn-secondary" onClick={closeEdit}>{t('common.cancel')}</button>- <button- className="btn-primary"- onClick={() => void handleSaveSessions()}- disabled={updateMutation.isPending}- >+ <button className="btn-primary" onClick={() => void handleSave()} disabled={!canSave}>{updateMutation.isPending ? <Loader2 className="animate-spin" size={16} /> : t('apiKeys.sessions.save')}</button></>@@ -411,11 +622,43 @@ export function ApiKeys() {<p className="session-scope-edit-name"><strong>{editingKey.name}</strong></p>- <SessionScopePicker- sessions={sessions}- selectedIds={editSessions}- onChange={setEditSessions}+ {isSignedInKey(editingKey) && (+ <p className="key-signed-in-warning" role="note">+ <AlertTriangle size={16} />+ {t('apiKeys.edit.signedIn')}+ </p>+ )}+ <label htmlFor="ak-edit-role">{t('common.role')}</label>+ <select+ id="ak-edit-role"+ value={editDraft.role}+ disabled={updateMutation.isPending}+ onChange={e => setEditDraft({ ...editDraft, role: e.target.value })}+ >+ {roleNames.map(r => (+ <option key={r} value={r}>+ {t(`apiKeys.roles.${r}`)}+ </option>+ ))}+ </select>+ {canScopeSessions(editDraft.role) && (+ <SessionScopePicker+ sessions={sessions}+ selectedIds={editDraft.sessions}+ onChange={ids => setEditDraft({ ...editDraft, sessions: ids })}+ disabled={updateMutation.isPending}+ />+ )}+ <KeyLimitFields+ idPrefix="ak-edit"+ role={editDraft.role}+ ips={editDraft.ips}+ chats={editDraft.chats}+ expires={editDraft.expires}+ errors={editErrors ?? { ip: null, chat: null }}+ onChange={patch => setEditDraft(prev => (prev ? { ...prev, ...patch } : prev))}disabled={updateMutation.isPending}+ expiresRef={editExpiresRef}/></Modal>)}diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 14c57972f..1ab6e6e42 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -1019,7 +1019,8 @@ export const apiKeyApi = {role?: string;allowedIps?: string[];allowedSessions?: string[];- expiresAt?: string;+ /** null removes the expiry. */+ expiresAt?: string | null;allowedChats?: string[];},) =>diff --git a/dashboard/src/utils/sessionScope.test.ts b/dashboard/src/utils/sessionScope.test.tsindex b1b009f25..ceda53ba5 100644--- a/dashboard/src/utils/sessionScope.test.ts+++ b/dashboard/src/utils/sessionScope.test.ts@@ -1,8 +1,16 @@import { test } from 'node:test';import assert from 'node:assert/strict';import {+ apiKeyDraft,+ apiKeyPatch,canScopeSessions,+ invalidChatEntry,+ invalidIpEntry,+ isExpired,+ normalizeChatScope,+ parseScopeList,sameSessionScope,+ toDateTimeLocal,sessionPickerStartsExpanded,sessionScopeNames,sessionScopeRows,@@ -44,6 +52,8 @@ test('an unchanged selection is recognised so the save is skipped, and a reorderassert.equal(sameSessionScope(['a'], []), false);assert.equal(sameSessionScope([], ['a']), false);assert.equal(sameSessionScope(['a', 'b'], ['a', 'c']), false);+ assert.equal(sameSessionScope(['a'], ['a', 'a']), true);+ assert.equal(sameSessionScope(['a', 'a'], ['a', 'b']), false);});test('the picker lists a selected id whose session is gone, so it can be unticked', () => {@@ -64,3 +74,107 @@ test('the picker lists a selected id whose session is gone, so it can be unticke// does not swallow the only control that can clear it.assert.deepEqual(sessionScopeRows([], ['deleted']), [{ id: 'deleted' }]);});++test('a free-text list splits on lines and commas, trims, and drops blanks and repeats', () => {+ assert.deepEqual(parseScopeList(' 10.0.0.1 \n\n10.0.0.0/8, 10.0.0.1\n'), ['10.0.0.1', '10.0.0.0/8']);+ assert.deepEqual(parseScopeList(' \n'), []);+});++test('a chat list qualifies a bare phone number the way the gateway stores it', () => {+ assert.deepEqual(normalizeChatScope('6281234\[email protected]\[email protected], 555@lid'), [+ '[email protected]',+ '[email protected]',+ '555@lid',+ ]);+ // Too short to be a phone number: left for the gateway to refuse.+ assert.deepEqual(normalizeChatScope('1234'), ['1234']);+});++test('an expiry round-trips through the datetime-local value in local time', () => {+ const local = toDateTimeLocal('2027-03-04T05:06:59.000Z');+ assert.match(local, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/);+ assert.equal(new Date(local).getTime(), Date.parse('2027-03-04T05:06:00.000Z'));+ assert.equal(toDateTimeLocal(undefined), '');+ assert.equal(toDateTimeLocal(null), '');+});++test('a key is expired only once its expiry has passed', () => {+ const now = Date.parse('2027-01-01T00:00:00.000Z');+ assert.equal(isExpired(undefined, now), false);+ assert.equal(isExpired(null, now), false);+ assert.equal(isExpired('2026-12-31T23:59:59.000Z', now), true);+ assert.equal(isExpired('2027-01-01T00:00:01.000Z', now), false);+});++const operatorKey = {+ role: 'operator',+ allowedIps: ['10.0.0.1', '10.0.0.0/8'],+ allowedSessions: ['s1'],+ allowedChats: ['[email protected]'],+ expiresAt: '2027-03-04T05:06:59.000Z',+};++test('an untouched draft produces an empty patch', () => {+ assert.deepEqual(apiKeyPatch(operatorKey, apiKeyDraft(operatorKey)), {});+ assert.deepEqual(apiKeyPatch({ role: 'viewer' }, apiKeyDraft({ role: 'viewer' })), {});+});++test('reordered lists and a bare number for a stored contact are not changes', () => {+ const draft = { ...apiKeyDraft(operatorKey), ips: '10.0.0.0/8\n10.0.0.1', chats: ' 6281234 ' };+ assert.deepEqual(apiKeyPatch(operatorKey, draft), {});+});++test('a stored allow-list with a repeated entry is not re-sent when untouched', () => {+ const key = { role: 'operator', allowedIps: ['10.0.0.1', '10.0.0.1'] };+ assert.deepEqual(apiKeyPatch(key, apiKeyDraft(key)), {});+});++test('each changed field is sent on its own', () => {+ const draft = apiKeyDraft(operatorKey);+ assert.deepEqual(apiKeyPatch(operatorKey, { ...draft, chats: '6281234\[email protected]' }), {+ allowedChats: ['[email protected]', '[email protected]'],+ });+ assert.deepEqual(apiKeyPatch(operatorKey, { ...draft, ips: '' }), { allowedIps: [] });+ assert.deepEqual(apiKeyPatch(operatorKey, { ...draft, expires: '' }), { expiresAt: null });+ assert.deepEqual(apiKeyPatch(operatorKey, { ...draft, expires: '2028-01-02T03:04' }), {+ expiresAt: new Date('2028-01-02T03:04').toISOString(),+ });+ assert.deepEqual(apiKeyPatch(operatorKey, { ...draft, role: 'viewer' }), { role: 'viewer' });+});++test('promoting to admin clears session and chat scope; an admin keeps what the API set', () => {+ assert.deepEqual(apiKeyPatch(operatorKey, { ...apiKeyDraft(operatorKey), role: 'admin' }), {+ role: 'admin',+ allowedSessions: [],+ allowedChats: [],+ });+ const scopedAdmin = { role: 'admin', allowedSessions: ['s1'], allowedChats: ['[email protected]'] };+ assert.deepEqual(apiKeyPatch(scopedAdmin, apiKeyDraft(scopedAdmin)), {});+ assert.deepEqual(apiKeyPatch({ role: 'admin' }, { ...apiKeyDraft({ role: 'admin' }), role: 'operator' }), {+ role: 'operator',+ });+});++test('an IP entry must be an IPv4 address or an IPv4 CIDR range, as the gateway requires', () => {+ assert.equal(invalidIpEntry(['10.0.0.1', '10.0.0.0/8', '0.0.0.0/0', '192.168.1.0/32', '10.0.0.0/08']), null);+ for (const bad of ['10.0.0.0/33', '::1', '1.2.3', '256.1.1.1', '01.2.3.4', '10.0.0.0/', '10.0.0.0/8/8', 'host']) {+ assert.equal(invalidIpEntry(['10.0.0.1', bad]), bad, bad);+ }+});++test('a chat entry must be a phone number, a group or a contact id, as the gateway requires', () => {+ assert.equal(+ invalidChatEntry([+ '6281234',+ '[email protected]',+ '123456@lid',+ '[email protected]',+ '[email protected]',+ '6281234:[email protected]',+ ]),+ null,+ );+ for (const bad of ['1234', '[email protected]', '[email protected]', '[email protected]', 'someone']) {+ assert.equal(invalidChatEntry([bad]), bad, bad);+ }+});diff --git a/dashboard/src/utils/sessionScope.ts b/dashboard/src/utils/sessionScope.tsindex 8275d97e7..a17c6c33f 100644--- a/dashboard/src/utils/sessionScope.ts+++ b/dashboard/src/utils/sessionScope.ts@@ -13,16 +13,15 @@ export function sessionPickerStartsExpanded(selectedIds: readonly string[]): boo}/**- * Membership comparison, so an unchanged Save is not sent at all. `PUT /auth/api-keys/:id` writes- * `allowedSessions` whenever the field is present, and an empty array is not the same stored value- * as "never scoped": the server reads the write back as an authorization change and disconnects- * every live `/events` socket holding that key.+ * Membership comparison, so an unchanged Save is not sent at all. Every `PUT /auth/api-keys/:id`+ * writes an audit row, and on an admin key a scope or expiry that is merely re-sent still runs the+ * last-admin check, which can refuse a save that changed nothing. Repeats are ignored: the API can+ * store a list with a repeated entry, while the form's parsed list never has one.*/export function sameSessionScope(a: readonly string[], b: readonly string[]): boolean {- if (a.length !== b.length) return false;- const left = [...a].sort();- const right = [...b].sort();- return left.every((id, index) => id === right[index]);+ const left = new Set(a);+ const right = new Set(b);+ return left.size === right.size && [...left].every(id => right.has(id));}/**@@ -49,3 +48,133 @@ export function sessionScopeNames(const byId = new Map(sessions.map(session => [session.id, session.name]));return allowedSessions.map(id => byId.get(id) ?? id);}++/** A free-text list as the gateway takes it: one entry per line or comma, trimmed, blanks and repeats dropped. */+export function parseScopeList(text: string): string[] {+ return [+ ...new Set(+ text+ .split(/[\n,]/)+ .map(entry => entry.trim())+ .filter(entry => entry.length > 0),+ ),+ ];+}++/**+ * The chat allow-list in the form the gateway stores it (normalizeChatAllowList): a bare phone number+ * becomes `<digits>@c.us`. The gateway refuses a list with repeats before it normalizes, and compares+ * stored entries in this form, so both the request and the no-op check use it.+ */+export function normalizeChatScope(text: string): string[] {+ return [...new Set(parseScopeList(text).map(entry => (/^\d{5,}$/.test(entry) ? `${entry}@c.us` : entry)))];+}++/** 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 '';+ const date = new Date(iso);+ if (Number.isNaN(date.getTime())) return '';+ const pad = (n: number) => String(n).padStart(2, '0');+ return (+ `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` ++ `T${pad(date.getHours())}:${pad(date.getMinutes())}`+ );+}++const IPV4_OCTET = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)';+const IPV4 = new RegExp(`^${IPV4_OCTET}(?:\\.${IPV4_OCTET}){3}$`);++// The gateway's allowedIps rule (isIpOrCidr): an IPv4 address, optionally with a /0-32 prefix length.+function isIpOrCidr(entry: string): boolean {+ const [ip, bits, extra] = entry.split('/');+ if (extra !== undefined || !IPV4.test(ip)) return false;+ return bits === undefined || (/^\d{1,2}$/.test(bits) && Number(bits) <= 32);+}++// The gateway's allowedChats rule (isChatId) for a trimmed entry: a bare phone number, a group, or a contact.+function isChatId(entry: string): boolean {+ if (/^\d{5,}$/.test(entry)) return true;+ const at = entry.lastIndexOf('@');+ if (at === -1) return false;+ const user = entry.slice(0, at).split(':')[0];+ const domain = entry.slice(at + 1).toLowerCase();+ if (domain === 'g.us') return /^\d+(?:-\d+)?$/.test(user);+ return ['c.us', 's.whatsapp.net', 'lid'].includes(domain) && /^\d{5,}$/.test(user);+}++/**+ * The first entry the gateway would refuse, or null. Checked here because a production gateway+ * answers a bad entry with a bare "Bad Request" that does not say which line is wrong.+ */+export function invalidIpEntry(entries: readonly string[]): string | null {+ return entries.find(entry => !isIpOrCidr(entry)) ?? null;+}++export function invalidChatEntry(entries: readonly string[]): string | null {+ return entries.find(entry => !isChatId(entry)) ?? null;+}++export function isExpired(expiresAt: string | null | undefined, now = Date.now()): boolean {+ return !!expiresAt && new Date(expiresAt).getTime() <= now;+}++interface ScopedKey {+ role: string;+ allowedIps?: string[] | null;+ allowedSessions?: string[] | null;+ allowedChats?: string[] | null;+ expiresAt?: string | null;+}++/** The edit form's state for one key: lists as editable text, expiry as a `datetime-local` value. */+export interface ApiKeyDraft {+ role: string;+ sessions: string[];+ ips: string;+ chats: string;+ expires: string;+}++export interface ApiKeyPatch {+ role?: string;+ allowedIps?: string[];+ allowedSessions?: string[];+ allowedChats?: string[];+ expiresAt?: string | null;+}++export function apiKeyDraft(key: ScopedKey): ApiKeyDraft {+ return {+ role: key.role,+ sessions: key.allowedSessions ?? [],+ ips: (key.allowedIps ?? []).join('\n'),+ chats: (key.allowedChats ?? []).join('\n'),+ expires: toDateTimeLocal(key.expiresAt),+ };+}++/**+ * Only the fields that changed, for the reasons on sameSessionScope: a re-sent field writes an audit+ * row saying the access moved, and on an admin key can trip the last-admin check. Session and chat+ * scope are edited only on operator and viewer keys; an admin key keeps whatever the API gave it,+ * unless it is being promoted, which clears both so the new admin can manage keys.+ */+export function apiKeyPatch(key: ScopedKey, draft: ApiKeyDraft): ApiKeyPatch {+ const patch: ApiKeyPatch = {};+ const scoped = canScopeSessions(draft.role);+ if (draft.role !== key.role) patch.role = draft.role;+ if (scoped || draft.role !== key.role) {+ const sessions = scoped ? draft.sessions : [];+ const chats = scoped ? normalizeChatScope(draft.chats) : [];+ if (!sameSessionScope(sessions, key.allowedSessions ?? [])) patch.allowedSessions = sessions;+ if (!sameSessionScope(chats, key.allowedChats ?? [])) patch.allowedChats = chats;+ }+ const ips = parseScopeList(draft.ips);+ if (!sameSessionScope(ips, key.allowedIps ?? [])) patch.allowedIps = ips;+ // Compared as the form shows it, so an untouched expiry is not re-sent rounded to the minute.+ if (draft.expires !== toDateTimeLocal(key.expiresAt)) {+ patch.expiresAt = draft.expires ? new Date(draft.expires).toISOString() : null;+ }+ return patch;+}