Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

Allow operator and viewer API keys to be scoped to chosen sessions

Sebastián Thiererd5e74173abf9
diff --git a/README.md b/README.md
index 9635af7e0..3238cdce5 100644
--- a/README.md
+++ b/README.md
@@ -43,6 +43,16 @@ Built on a **pluggable architecture**, OpenWA lets you select database engines (
| 🧩 **Official Plugins** | Chatwoot, Typebot & more as sandboxed plugins on the Integration Fabric — [OpenWA-plugins](https://github.com/rmyndharis/OpenWA-plugins) |
| 🔗 **n8n Integration** | Community nodes for workflow automation |
| 🧩 **Community Adapters** | Third-party integrations (e.g. ioBroker) — see [docs](./docs/23-community-integrations.md) |
+| 🔐 **Session-scoped keys** | Operator and viewer (reader) tokens can be limited to chosen sessions — or all sessions if none are selected |
+
+### Session-scoped operator & viewer tokens
+
+When you create or edit an **operator** or **viewer** API key in the dashboard, you can tick the WhatsApp sessions that key may use.
+
+- **No sessions selected** — the key can access every session, including ones created later.
+- **One or more sessions selected** — the key can only list, read, and (for operator) manage those sessions. Requests to any other session return `401`.
+
+Admin keys stay unscoped in the dashboard so they can keep managing other API keys. The HTTP API still accepts `allowedSessions` on any role if you need that from a client.
---
diff --git a/dashboard/src/components/SessionScopePicker.tsx b/dashboard/src/components/SessionScopePicker.tsx
new file mode 100644
index 000000000..3e4dd8829
--- /dev/null
+++ b/dashboard/src/components/SessionScopePicker.tsx
@@ -0,0 +1,77 @@
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import type { Session } from '../services/api';
+import { sessionPickerStartsExpanded } from '../utils/sessionScope';
+
+interface SessionScopePickerProps {
+ sessions: Session[];
+ selectedIds: string[];
+ onChange: (ids: string[]) => void;
+ disabled?: boolean;
+}
+
+export function SessionScopePicker({ sessions, selectedIds, onChange, disabled }: SessionScopePickerProps) {
+ const { t } = useTranslation();
+ const [expanded, setExpanded] = useState(() => sessionPickerStartsExpanded(selectedIds));
+
+ const toggle = (id: string) => {
+ onChange(selectedIds.includes(id) ? selectedIds.filter(current => current !== id) : [...selectedIds, id]);
+ };
+
+ const chooseSessions = () => setExpanded(true);
+ const leaveForAll = () => {
+ onChange([]);
+ setExpanded(false);
+ };
+
+ return (
+ <div className="session-scope-picker" role="group">
+ {expanded ? (
+ <>
+ <button
+ type="button"
+ className="session-scope-toggle"
+ onClick={leaveForAll}
+ disabled={disabled}
+ aria-expanded="true"
+ >
+ {t('apiKeys.sessions.leaveAll')}
+ </button>
+ <p className="session-scope-hint">{t('apiKeys.sessions.hint')}</p>
+ {sessions.length === 0 ? (
+ <p className="session-scope-empty">{t('apiKeys.sessions.empty')}</p>
+ ) : (
+ <ul className="session-scope-list">
+ {sessions.map(session => (
+ <li key={session.id}>
+ <label className="session-scope-option">
+ <input
+ type="checkbox"
+ checked={selectedIds.includes(session.id)}
+ onChange={() => toggle(session.id)}
+ disabled={disabled}
+ />
+ <span className="session-scope-meta">
+ <span className="session-scope-name">{session.name}</span>
+ {session.phone ? <span className="session-scope-phone">{session.phone}</span> : null}
+ </span>
+ </label>
+ </li>
+ ))}
+ </ul>
+ )}
+ </>
+ ) : (
+ <button
+ type="button"
+ className="session-scope-toggle"
+ onClick={chooseSessions}
+ disabled={disabled}
+ aria-expanded="false"
+ >
+ {t('apiKeys.sessions.choose')}
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/dashboard/src/hooks/queries.ts b/dashboard/src/hooks/queries.ts
index a182051cc..d75b6d8e0 100644
--- a/dashboard/src/hooks/queries.ts
+++ b/dashboard/src/hooks/queries.ts
@@ -198,6 +198,28 @@ export function useCreateApiKeyMutation() {
});
}
+export function useUpdateApiKeyMutation() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: ({
+ id,
+ data,
+ }: {
+ id: string;
+ data: {
+ name?: string;
+ role?: string;
+ allowedIps?: string[];
+ allowedSessions?: string[];
+ expiresAt?: string;
+ };
+ }) => apiKeyApi.update(id, data),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: queryKeys.apiKeys });
+ },
+ });
+}
+
export function useDeleteApiKeyMutation() {
const queryClient = useQueryClient();
return useMutation({
diff --git a/dashboard/src/i18n/locales.test.ts b/dashboard/src/i18n/locales.test.ts
index d27d879dc..3adcc67f3 100644
--- a/dashboard/src/i18n/locales.test.ts
+++ b/dashboard/src/i18n/locales.test.ts
@@ -30,6 +30,20 @@ const resources = Object.fromEntries(
const i18n = i18next.createInstance();
await i18n.init({ lng: 'en', resources, fallbackLng: false, interpolation: { escapeValue: false } });
+const SESSION_SCOPE_KEYS = [
+ 'apiKeys.columns.sessions',
+ 'apiKeys.sessions.label',
+ 'apiKeys.sessions.hint',
+ 'apiKeys.sessions.all',
+ 'apiKeys.sessions.empty',
+ 'apiKeys.sessions.restricted',
+ 'apiKeys.sessions.editTitle',
+ 'apiKeys.sessions.save',
+ 'apiKeys.sessions.choose',
+ 'apiKeys.sessions.leaveAll',
+ 'apiKeys.actions.editSessions',
+];
+
const NEW_PLUGIN_KEYS = [
'plugins.catalog.empty',
'plugins.catalog.install',
@@ -86,6 +100,22 @@ test('Hebrew dual + Arabic plural categories resolve for the filter badge', () =
assert.equal(i18n.t('webhooks.filters.badge', { lng: 'ar', count: 3 }), '3 عوامل تصفية');
});
+test('every session-scope API key string resolves in every locale', () => {
+ for (const lng of LOCALE_IDS) {
+ for (const key of SESSION_SCOPE_KEYS) {
+ const value = i18n.t(key, { lng, count: 2 });
+ assert.ok(value && value !== key, `${lng}: ${key} missing from catalog (component would show a raw fallback)`);
+ }
+ }
+});
+
+test('English session-scope copy explains the empty-allowlist default', () => {
+ assert.equal(i18n.t('apiKeys.sessions.all'), 'All sessions');
+ assert.equal(i18n.t('apiKeys.sessions.choose'), 'Choose sessions');
+ assert.equal(i18n.t('apiKeys.sessions.leaveAll'), 'Leave for all sessions');
+ assert.match(i18n.t('apiKeys.sessions.restricted', { count: 3 }), /3/);
+});
+
test('every new plugins.* key resolves in every locale', () => {
for (const lng of LOCALE_IDS) {
for (const key of NEW_PLUGIN_KEYS) {
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index 3323755ad..19a5d108f 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -548,7 +548,8 @@
"role": "الدور",
"status": "الحالة",
"lastUsed": "آخر استخدام",
- "actions": "إجراءات"
+ "actions": "إجراءات",
+ "sessions": "الجلسات"
},
"statuses": {
"active": "نشط",
@@ -569,7 +570,19 @@
"actions": {
"copy": "نسخ",
"revoke": "إلغاء",
- "delete": "حذف"
+ "delete": "حذف",
+ "editSessions": "تعديل الجلسات"
+ },
+ "sessions": {
+ "label": "الوصول إلى الجلسات",
+ "hint": "اختر الجلسات التي يمكن لهذا المفتاح استخدامها.",
+ "all": "كل الجلسات",
+ "empty": "لا توجد جلسات بعد. سيتمكن هذا المفتاح من الوصول إلى كل الجلسات عند إنشائها.",
+ "restricted": "{{count}} محددة",
+ "editTitle": "تعديل الوصول إلى الجلسات",
+ "save": "حفظ",
+ "choose": "اختيار الجلسات",
+ "leaveAll": "تركها لجميع الجلسات"
}
},
"logs": {
diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json
index 4542b1e67..74e6ebf5b 100644
--- a/dashboard/src/i18n/locales/de.json
+++ b/dashboard/src/i18n/locales/de.json
@@ -533,7 +533,8 @@
"role": "Rolle",
"status": "Status",
"lastUsed": "Zuletzt verwendet",
- "actions": "Aktionen"
+ "actions": "Aktionen",
+ "sessions": "Sitzungen"
},
"statuses": {
"active": "Aktiv",
@@ -554,7 +555,19 @@
"actions": {
"copy": "Kopieren",
"revoke": "Widerrufen",
- "delete": "Löschen"
+ "delete": "Löschen",
+ "editSessions": "Sitzungen bearbeiten"
+ },
+ "sessions": {
+ "label": "Sitzungszugriff",
+ "hint": "Wählen Sie die Sitzungen, die dieser Schlüssel nutzen darf.",
+ "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"
}
},
"logs": {
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index f4b323e61..2a2d35d68 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -533,7 +533,8 @@
"role": "Role",
"status": "Status",
"lastUsed": "Last Used",
- "actions": "Actions"
+ "actions": "Actions",
+ "sessions": "Sessions"
},
"statuses": {
"active": "Active",
@@ -554,7 +555,19 @@
"actions": {
"copy": "Copy",
"revoke": "Revoke",
- "delete": "Delete"
+ "delete": "Delete",
+ "editSessions": "Edit sessions"
+ },
+ "sessions": {
+ "label": "Session access",
+ "hint": "Select the sessions this key may use.",
+ "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"
}
},
"logs": {
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index a6c7c347c..763e23574 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -487,7 +487,8 @@
"role": "Rol",
"status": "Estado",
"lastUsed": "Último uso",
- "actions": "Acciones"
+ "actions": "Acciones",
+ "sessions": "Sesiones"
},
"statuses": {
"active": "Activa",
@@ -508,7 +509,19 @@
"actions": {
"copy": "Copiar",
"revoke": "Revocar",
- "delete": "Eliminar"
+ "delete": "Eliminar",
+ "editSessions": "Editar sesiones"
+ },
+ "sessions": {
+ "label": "Acceso a sesiones",
+ "hint": "Elige las sesiones que podrá usar esta clave.",
+ "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"
}
},
"logs": {
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index 1b80b8ed9..17054095f 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -533,7 +533,8 @@
"role": "Rôle",
"status": "Statut",
"lastUsed": "Dernière utilisation",
- "actions": "Actions"
+ "actions": "Actions",
+ "sessions": "Sessions"
},
"statuses": {
"active": "Active",
@@ -554,7 +555,19 @@
"actions": {
"copy": "Copier",
"revoke": "Révoquer",
- "delete": "Supprimer"
+ "delete": "Supprimer",
+ "editSessions": "Modifier les sessions"
+ },
+ "sessions": {
+ "label": "Accès aux sessions",
+ "hint": "Sélectionnez les sessions que cette clé peut utiliser.",
+ "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"
}
},
"logs": {
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index e82baf561..349a3443c 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -542,7 +542,8 @@
"role": "תפקיד",
"status": "סטטוס",
"lastUsed": "שימוש אחרון",
- "actions": "פעולות"
+ "actions": "פעולות",
+ "sessions": "סשנים"
},
"statuses": {
"active": "פעיל",
@@ -563,7 +564,19 @@
"actions": {
"copy": "העתקה",
"revoke": "ביטול",
- "delete": "מחיקה"
+ "delete": "מחיקה",
+ "editSessions": "עריכת סשנים"
+ },
+ "sessions": {
+ "label": "גישה לסשנים",
+ "hint": "בחרו את הסשנים שהמפתח הזה יוכל להשתמש בהם.",
+ "all": "כל הסשנים",
+ "empty": "עדיין אין סשנים. המפתח הזה יוכל לגשת לכולם ברגע שיהיו.",
+ "restricted": "{{count}} נבחרו",
+ "editTitle": "עריכת גישה לסשנים",
+ "save": "שמירה",
+ "choose": "בחירת סשנים",
+ "leaveAll": "להשאיר לכל הסשנים"
}
},
"logs": {
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index 8196a0c5b..f97e14182 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -533,7 +533,8 @@
"role": "Ruolo",
"status": "Stato",
"lastUsed": "Ultimo Utilizzo",
- "actions": "Azioni"
+ "actions": "Azioni",
+ "sessions": "Sessioni"
},
"statuses": {
"active": "Attiva",
@@ -554,7 +555,19 @@
"actions": {
"copy": "Copia",
"revoke": "Revoca",
- "delete": "Elimina"
+ "delete": "Elimina",
+ "editSessions": "Modifica sessioni"
+ },
+ "sessions": {
+ "label": "Accesso alle sessioni",
+ "hint": "Seleziona le sessioni che questa chiave può usare.",
+ "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"
}
},
"logs": {
diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.json
index 41ba479cf..e2b2a260a 100644
--- a/dashboard/src/i18n/locales/ko.json
+++ b/dashboard/src/i18n/locales/ko.json
@@ -533,7 +533,8 @@
"role": "역할",
"status": "상태",
"lastUsed": "마지막 사용",
- "actions": "작업"
+ "actions": "작업",
+ "sessions": "세션"
},
"statuses": {
"active": "활성",
@@ -554,7 +555,19 @@
"actions": {
"copy": "복사",
"revoke": "폐기",
- "delete": "삭제"
+ "delete": "삭제",
+ "editSessions": "세션 편집"
+ },
+ "sessions": {
+ "label": "세션 접근",
+ "hint": "이 키가 사용할 세션을 선택하세요.",
+ "all": "모든 세션",
+ "empty": "아직 세션이 없습니다. 세션이 생기면 이 키는 모두에 접근할 수 있습니다.",
+ "restricted": "{{count}}개 선택됨",
+ "editTitle": "세션 접근 편집",
+ "save": "저장",
+ "choose": "세션 선택",
+ "leaveAll": "모든 세션에 두기"
}
},
"logs": {
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index 01f28ece6..3de70e97b 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -487,7 +487,8 @@
"role": "Função",
"status": "Status",
"lastUsed": "Último uso",
- "actions": "Ações"
+ "actions": "Ações",
+ "sessions": "Sessões"
},
"statuses": {
"active": "Ativa",
@@ -508,7 +509,19 @@
"actions": {
"copy": "Copiar",
"revoke": "Revogar",
- "delete": "Excluir"
+ "delete": "Excluir",
+ "editSessions": "Editar sessões"
+ },
+ "sessions": {
+ "label": "Acesso às sessões",
+ "hint": "Selecione as sessões que esta chave poderá usar.",
+ "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"
}
},
"logs": {
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index df2eae15e..564f58780 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -533,7 +533,8 @@
"role": "పాత్ర",
"status": "స్థితి",
"lastUsed": "చివరిగా ఉపయోగించినది",
- "actions": "చర్యలు"
+ "actions": "చర్యలు",
+ "sessions": "సెషన్లు"
},
"statuses": {
"active": "యాక్టివ్",
@@ -554,7 +555,19 @@
"actions": {
"copy": "కాపీ",
"revoke": "రద్దు చేయి",
- "delete": "తొలగించు"
+ "delete": "తొలగించు",
+ "editSessions": "సెషన్లను సవరించు"
+ },
+ "sessions": {
+ "label": "సెషన్ యాక్సెస్",
+ "hint": "ఈ కీ ఉపయోగించగల సెషన్లను ఎంచుకోండి.",
+ "all": "అన్ని సెషన్లు",
+ "empty": "ఇంకా సెషన్లు లేవు. సెషన్లు ఉన్న తర్వాత ఈ కీ అన్నింటికీ యాక్సెస్ పొందుతుంది.",
+ "restricted": "{{count}} ఎంచుకున్నారు",
+ "editTitle": "సెషన్ యాక్సెస్‌ను సవరించు",
+ "save": "సేవ్",
+ "choose": "సెషన్లను ఎంచుకోండి",
+ "leaveAll": "అన్ని సెషన్లకు వదిలేయండి"
}
},
"logs": {
diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.json
index 4a3700198..c24393b4c 100644
--- a/dashboard/src/i18n/locales/tr.json
+++ b/dashboard/src/i18n/locales/tr.json
@@ -533,7 +533,8 @@
"role": "Rol",
"status": "Durum",
"lastUsed": "Son Kullanım",
- "actions": "İşlemler"
+ "actions": "İşlemler",
+ "sessions": "Oturumlar"
},
"statuses": {
"active": "Aktif",
@@ -554,7 +555,19 @@
"actions": {
"copy": "Kopyala",
"revoke": "Geçersiz Kıl",
- "delete": "Sil"
+ "delete": "Sil",
+ "editSessions": "Oturumları düzenle"
+ },
+ "sessions": {
+ "label": "Oturum erişimi",
+ "hint": "Bu anahtarın kullanabileceği oturumları seçin.",
+ "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"
}
},
"logs": {
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 3441f04c0..f31cb8b8d 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -533,7 +533,8 @@
"role": "角色",
"status": "状态",
"lastUsed": "上次使用",
- "actions": "操作"
+ "actions": "操作",
+ "sessions": "会话"
},
"statuses": {
"active": "活跃",
@@ -554,7 +555,19 @@
"actions": {
"copy": "复制",
"revoke": "撤销",
- "delete": "删除"
+ "delete": "删除",
+ "editSessions": "编辑会话"
+ },
+ "sessions": {
+ "label": "会话访问",
+ "hint": "选择此密钥可以使用的会话。",
+ "all": "全部会话",
+ "empty": "暂无会话。创建会话后,此密钥将可以访问全部会话。",
+ "restricted": "已选 {{count}} 个",
+ "editTitle": "编辑会话访问",
+ "save": "保存",
+ "choose": "选择会话",
+ "leaveAll": "保留为全部会话"
}
},
"logs": {
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index ad176393f..c100061ea 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -533,7 +533,8 @@
"role": "角色",
"status": "狀態",
"lastUsed": "上次使用",
- "actions": "操作"
+ "actions": "操作",
+ "sessions": "工作階段"
},
"statuses": {
"active": "活躍",
@@ -554,7 +555,19 @@
"actions": {
"copy": "複製",
"revoke": "撤銷",
- "delete": "刪除"
+ "delete": "刪除",
+ "editSessions": "編輯工作階段"
+ },
+ "sessions": {
+ "label": "工作階段存取",
+ "hint": "選擇此密鑰可以使用的工作階段。",
+ "all": "全部工作階段",
+ "empty": "尚未有工作階段。建立後,此密鑰便可存取全部工作階段。",
+ "restricted": "已選 {{count}} 個",
+ "editTitle": "編輯工作階段存取",
+ "save": "儲存",
+ "choose": "選擇工作階段",
+ "leaveAll": "保留為全部工作階段"
}
},
"logs": {
diff --git a/dashboard/src/pages/ApiKeys.css b/dashboard/src/pages/ApiKeys.css
index c9021d74c..26af2c575 100644
--- a/dashboard/src/pages/ApiKeys.css
+++ b/dashboard/src/pages/ApiKeys.css
@@ -117,6 +117,114 @@
color: var(--primary-text);
}
+.api-keys-page .sessions-cell {
+ font-size: 0.8125rem;
+ color: var(--text-secondary);
+ max-width: 16rem;
+ display: inline-block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.api-keys-page .sessions-cell.all {
+ color: var(--text-muted);
+}
+
+.api-keys-page .session-scope-picker {
+ margin: 0.75rem 0 0.5rem;
+}
+
+.api-keys-page .session-scope-toggle {
+ display: inline;
+ padding: 0;
+ border: none;
+ border-radius: 0;
+ background: none;
+ color: var(--primary-text);
+ font-size: 0.875rem;
+ font-weight: 600;
+ line-height: 1.4;
+ cursor: pointer;
+ text-decoration: none;
+}
+
+.api-keys-page .session-scope-toggle:hover:not(:disabled) {
+ text-decoration: underline;
+}
+
+.api-keys-page .session-scope-toggle:disabled {
+ cursor: not-allowed;
+ opacity: 0.6;
+}
+
+.api-keys-page .session-scope-hint,
+.api-keys-page .session-scope-empty {
+ margin: 0 0 0.75rem;
+ font-size: 0.8125rem;
+ font-weight: 400;
+ color: var(--text-muted);
+ line-height: 1.45;
+ text-transform: none;
+ letter-spacing: normal;
+}
+
+.api-keys-page .session-scope-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 0.375rem;
+ max-height: 14rem;
+ overflow-y: auto;
+}
+
+.api-keys-page .session-scope-option {
+ display: flex;
+ align-items: flex-start;
+ gap: 0.625rem;
+ margin: 0;
+ padding: 0.625rem 0.75rem;
+ background: var(--bg-light);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ font-size: 0.875rem;
+ font-weight: 500;
+ color: var(--text-primary);
+ cursor: pointer;
+ text-transform: none;
+ letter-spacing: normal;
+}
+
+.api-keys-page .session-scope-option:has(input:checked) {
+ border-color: rgba(37, 211, 102, 0.45);
+ background: rgba(37, 211, 102, 0.08);
+}
+
+.api-keys-page .session-scope-meta {
+ display: flex;
+ flex-direction: column;
+ gap: 0.125rem;
+ min-width: 0;
+}
+
+.api-keys-page .session-scope-name {
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.api-keys-page .session-scope-phone {
+ font-size: 0.75rem;
+ font-weight: 400;
+ color: var(--text-muted);
+}
+
+.api-keys-page .session-scope-edit-name {
+ margin: 0 0 1rem;
+ color: var(--text-secondary);
+}
+
.api-keys-page .actions-cell {
display: flex;
gap: 0.25rem;
@@ -349,15 +457,18 @@
white-space: normal;
}
- /* Role & Status - wrapper for badges */
- .api-keys-page .keys-table tbody tr.table-row td:nth-child(3),
- .api-keys-page .keys-table tbody tr.table-row td:nth-child(4) {
+ /* 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(.status-badge) {
display: inline-block;
order: 3;
+ margin-right: 0.5rem;
}
- .api-keys-page .keys-table tbody tr.table-row td:nth-child(3) {
- margin-right: 0.5rem;
+ .api-keys-page .sessions-cell {
+ max-width: 100%;
+ white-space: normal;
}
/* Actions cell - bottom with separator */
diff --git a/dashboard/src/pages/ApiKeys.tsx b/dashboard/src/pages/ApiKeys.tsx
index ed31c6736..07fc88787 100644
--- a/dashboard/src/pages/ApiKeys.tsx
+++ b/dashboard/src/pages/ApiKeys.tsx
@@ -21,6 +21,7 @@ import {
KeyRound,
AlertTriangle,
AlertCircle,
+ Pencil,
} from 'lucide-react';
import type { ApiKey } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
@@ -29,15 +30,21 @@ import {
useCreateApiKeyMutation,
useDeleteApiKeyMutation,
useRevokeApiKeyMutation,
+ useSessionsQuery,
+ useUpdateApiKeyMutation,
} from '../hooks/queries';
import { PageHeader } from '../components/PageHeader';
import { Modal } from '../components/Modal';
+import { SessionScopePicker } from '../components/SessionScopePicker';
import { useToast } from '../hooks/useToast';
import { copyToClipboard } from '../utils/clipboard';
+import { canScopeSessions, sessionScopeNames } from '../utils/sessionScope';
import './ApiKeys.css';
const roleNames = ['admin', 'operator', 'viewer'] as const;
+const emptyKeyForm = { name: '', role: 'operator', allowedSessions: [] as string[] };
+
function useWindowSize() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
@@ -60,14 +67,18 @@ export function ApiKeys() {
const toast = useToast();
useDocumentTitle(t('apiKeys.title'));
const { data: apiKeys = [], isLoading: loading, isError: apiKeysError } = useApiKeysQuery();
+ const { data: sessions = [] } = useSessionsQuery();
const createMutation = useCreateApiKeyMutation();
+ const updateMutation = useUpdateApiKeyMutation();
const deleteMutation = useDeleteApiKeyMutation();
const revokeMutation = useRevokeApiKeyMutation();
const [visibleKeys, setVisibleKeys] = useState<Set<string>>(new Set());
const [showModal, setShowModal] = useState(false);
- const [newKey, setNewKey] = useState({ name: '', role: 'operator' });
+ const [newKey, setNewKey] = useState(emptyKeyForm);
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 [confirmAction, setConfirmAction] = useState<{ type: 'delete' | 'revoke'; id: string; name: string } | null>(
null,
);
@@ -81,18 +92,47 @@ export function ApiKeys() {
setColumnVisibility({ key: !isSmall, lastUsed: !isMobile });
}, [isMobile, isSmall]);
+ const closeCreateModal = () => {
+ setShowModal(false);
+ setCreatedKey(null);
+ setNewKey(emptyKeyForm);
+ };
+
const handleCreate = async () => {
if (!newKey.name) return;
try {
- const created = await createMutation.mutateAsync({ name: newKey.name, role: newKey.role });
+ const created = await createMutation.mutateAsync({
+ name: newKey.name,
+ role: newKey.role,
+ ...(canScopeSessions(newKey.role) ? { allowedSessions: newKey.allowedSessions } : {}),
+ });
setCreatedKey(created.apiKey || null);
- setNewKey({ name: '', role: 'operator' });
+ setNewKey(emptyKeyForm);
} catch (err) {
console.error('Failed to create:', err);
toast.error(t('apiKeys.createBtn'), err instanceof Error ? err.message : t('common.unknownError'));
}
};
+ const openEditSessions = (apiKey: ApiKey) => {
+ setEditingKey(apiKey);
+ setEditSessions(apiKey.allowedSessions ?? []);
+ };
+
+ const handleSaveSessions = async () => {
+ if (!editingKey) return;
+ try {
+ await updateMutation.mutateAsync({
+ id: editingKey.id,
+ data: { allowedSessions: editSessions },
+ });
+ setEditingKey(null);
+ } catch (err) {
+ console.error('Failed to update sessions:', err);
+ toast.error(t('apiKeys.sessions.editTitle'), err instanceof Error ? err.message : t('common.unknownError'));
+ }
+ };
+
const handleRevoke = async (id: string) => {
try {
await revokeMutation.mutateAsync(id);
@@ -164,6 +204,20 @@ export function ApiKeys() {
header: () => t('apiKeys.columns.role'),
cell: info => <span className="permission-badge">{info.getValue()}</span>,
}),
+ columnHelper.accessor('allowedSessions', {
+ id: 'sessions',
+ header: () => t('apiKeys.columns.sessions'),
+ cell: info => {
+ const names = sessionScopeNames(info.getValue(), sessions);
+ if (!names) {
+ return <span className="sessions-cell all">{t('apiKeys.sessions.all')}</span>;
+ }
+ if (names.length <= 2) {
+ return <span className="sessions-cell">{names.join(', ')}</span>;
+ }
+ return <span className="sessions-cell">{t('apiKeys.sessions.restricted', { count: names.length })}</span>;
+ },
+ }),
columnHelper.accessor('isActive', {
header: () => t('apiKeys.columns.status'),
cell: info => (
@@ -190,6 +244,15 @@ export function ApiKeys() {
<span className="actions-cell">
{/* No per-row copy: the full key only exists once (post-creation modal); the row
only 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')}
+ >
+ <Pencil size={16} />
+ </button>
+ )}
{apiKey.isActive && (
<button
className="icon-btn"
@@ -211,7 +274,7 @@ export function ApiKeys() {
},
}),
]),
- [visibleKeys, t],
+ [visibleKeys, t, sessions],
);
const table = useTable({
@@ -256,16 +319,13 @@ export function ApiKeys() {
{showModal && (
<Modal
open
- onClose={() => {
- setShowModal(false);
- setCreatedKey(null);
- }}
+ onClose={closeCreateModal}
title={createdKey ? t('apiKeys.createdTitle') : t('apiKeys.modalTitle')}
closeLabel={t('common.close')}
footer={
!createdKey ? (
<>
- <button className="btn-secondary" onClick={() => setShowModal(false)}>
+ <button className="btn-secondary" onClick={closeCreateModal}>
{t('common.cancel')}
</button>
<button
@@ -310,18 +370,69 @@ export function ApiKeys() {
onChange={e => setNewKey({ ...newKey, name: e.target.value })}
/>
<label htmlFor="ak-2">{t('common.role')}</label>
- <select id="ak-2" value={newKey.role} onChange={e => setNewKey({ ...newKey, role: e.target.value })}>
+ <select
+ id="ak-2"
+ value={newKey.role}
+ onChange={e =>
+ setNewKey({
+ ...newKey,
+ role: e.target.value,
+ allowedSessions: canScopeSessions(e.target.value) ? newKey.allowedSessions : [],
+ })
+ }
+ >
{roleNames.map(r => (
<option key={r} value={r}>
{t(`apiKeys.roles.${r}`)}
</option>
))}
</select>
+ {canScopeSessions(newKey.role) && (
+ <SessionScopePicker
+ sessions={sessions}
+ selectedIds={newKey.allowedSessions}
+ onChange={ids => setNewKey({ ...newKey, allowedSessions: ids })}
+ disabled={createMutation.isPending}
+ />
+ )}
</>
)}
</Modal>
)}
+ {editingKey && (
+ <Modal
+ open
+ onClose={() => setEditingKey(null)}
+ title={t('apiKeys.sessions.editTitle')}
+ closeLabel={t('common.close')}
+ footer={
+ <>
+ <button className="btn-secondary" onClick={() => setEditingKey(null)}>
+ {t('common.cancel')}
+ </button>
+ <button
+ className="btn-primary"
+ onClick={() => void handleSaveSessions()}
+ disabled={updateMutation.isPending}
+ >
+ {updateMutation.isPending ? <Loader2 className="animate-spin" size={16} /> : t('apiKeys.sessions.save')}
+ </button>
+ </>
+ }
+ >
+ <p className="session-scope-edit-name">
+ <strong>{editingKey.name}</strong>
+ </p>
+ <SessionScopePicker
+ sessions={sessions}
+ selectedIds={editSessions}
+ onChange={setEditSessions}
+ disabled={updateMutation.isPending}
+ />
+ </Modal>
+ )}
+
<div className="api-keys-content">
<div className="keys-table-container">
{apiKeys.length === 0 ? (
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index a0fded4cc..9ef2d5d14 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -940,6 +940,20 @@ export const apiKeyApi = {
method: 'POST',
body: JSON.stringify(data),
}),
+ update: (
+ id: string,
+ data: {
+ name?: string;
+ role?: string;
+ allowedIps?: string[];
+ allowedSessions?: string[];
+ expiresAt?: string;
+ },
+ ) =>
+ request<ApiKey>(`/auth/api-keys/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data),
+ }),
delete: (id: string) => request<void>(`/auth/api-keys/${id}`, { method: 'DELETE' }),
revoke: (id: string) => request<ApiKey>(`/auth/api-keys/${id}/revoke`, { method: 'POST' }),
};
diff --git a/dashboard/src/utils/sessionScope.test.ts b/dashboard/src/utils/sessionScope.test.ts
new file mode 100644
index 000000000..f69eb28ea
--- /dev/null
+++ b/dashboard/src/utils/sessionScope.test.ts
@@ -0,0 +1,33 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { canScopeSessions, sessionPickerStartsExpanded, sessionScopeNames } from './sessionScope.ts';
+
+test('only operator and viewer keys can be session-scoped in the dashboard', () => {
+ assert.equal(canScopeSessions('operator'), true);
+ assert.equal(canScopeSessions('viewer'), true);
+ assert.equal(canScopeSessions('admin'), false);
+ assert.equal(canScopeSessions(''), false);
+});
+
+test('an empty or missing allowlist means every session', () => {
+ const sessions = [
+ { id: 'a', name: 'Sales' },
+ { id: 'b', name: 'Support' },
+ ];
+ assert.equal(sessionScopeNames(undefined, sessions), null);
+ assert.equal(sessionScopeNames(null, sessions), null);
+ assert.equal(sessionScopeNames([], sessions), null);
+});
+
+test('the session picker stays collapsed until sessions are already chosen', () => {
+ assert.equal(sessionPickerStartsExpanded([]), false);
+ assert.equal(sessionPickerStartsExpanded(['a']), true);
+});
+
+test('a selected allowlist resolves to session names, falling back to the id', () => {
+ const sessions = [
+ { id: 'a', name: 'Sales' },
+ { id: 'b', name: 'Support' },
+ ];
+ assert.deepEqual(sessionScopeNames(['b', 'missing'], sessions), ['Support', 'missing']);
+});
diff --git a/dashboard/src/utils/sessionScope.ts b/dashboard/src/utils/sessionScope.ts
new file mode 100644
index 000000000..68bb54b04
--- /dev/null
+++ b/dashboard/src/utils/sessionScope.ts
@@ -0,0 +1,22 @@
+/**
+ * Operator and viewer (reader) API keys may be limited to an explicit session
+ * allowlist. An empty or missing list means the key can reach every session,
+ * including ones created later. Admin keys stay unscoped in the dashboard UI.
+ */
+export function canScopeSessions(role: string): boolean {
+ return role === 'operator' || role === 'viewer';
+}
+
+/** The picker starts open only when the key already has an explicit allowlist. */
+export function sessionPickerStartsExpanded(selectedIds: readonly string[]): boolean {
+ return selectedIds.length > 0;
+}
+
+export function sessionScopeNames(
+ allowedSessions: string[] | undefined | null,
+ sessions: ReadonlyArray<{ id: string; name: string }>,
+): string[] | null {
+ if (!allowedSessions || allowedSessions.length === 0) return null;
+ const byId = new Map(sessions.map(session => [session.id, session.name]));
+ return allowedSessions.map(id => byId.get(id) ?? id);
+}