Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(sessions): add per-session proxy configuration in dashboard UI
Victor Andrade18aed88c9c86
diff --git a/dashboard/src/hooks/useSessionCreateForm.ts b/dashboard/src/hooks/useSessionCreateForm.tsindex f8aa3eefc..9137d2cdd 100644--- a/dashboard/src/hooks/useSessionCreateForm.ts+++ b/dashboard/src/hooks/useSessionCreateForm.ts@@ -1,6 +1,6 @@import { useState } from 'react';import { useTranslation } from 'react-i18next';-import { sessionApi, type Session } from '../services/api';+import { sessionApi, type Session, type SessionProxyType } from '../services/api';import { useToast } from './useToast';export interface UseSessionCreateFormArgs {@@ -13,6 +13,12 @@ export interface SessionCreateForm {setShowCreateModal: (open: boolean) => void;newSessionName: string;setNewSessionName: (name: string) => void;+ useProxy: boolean;+ setUseProxy: (enabled: boolean) => void;+ proxyUrl: string;+ setProxyUrl: (url: string) => void;+ proxyType: SessionProxyType;+ setProxyType: (type: SessionProxyType) => void;creating: boolean;handleCreate: () => Promise<void>;}@@ -29,14 +35,29 @@ export function useSessionCreateForm({ onCreated, onFailed }: UseSessionCreateFoconst toast = useToast();const [showCreateModal, setShowCreateModal] = useState(false);const [newSessionName, setNewSessionName] = useState('');+ const [useProxy, setUseProxy] = useState(false);+ const [proxyUrl, setProxyUrl] = useState('');+ const [proxyType, setProxyType] = useState<SessionProxyType>('http');const [creating, setCreating] = useState(false);+ const resetProxyFields = () => {+ setUseProxy(false);+ setProxyUrl('');+ setProxyType('http');+ };+const handleCreate = async () => {if (!newSessionName.trim()) return;try {setCreating(true);- const newSession = await sessionApi.create(newSessionName);+ const newSession = await sessionApi.create(+ newSessionName,+ useProxy && proxyUrl.trim()+ ? { proxyUrl: proxyUrl.trim(), proxyType }+ : undefined,+ );setNewSessionName('');+ resetProxyFields();setShowCreateModal(false);toast.success(t('sessions.create.successTitle'), t('sessions.create.successDesc', { name: newSession.name }));onCreated(newSession);@@ -49,5 +70,18 @@ export function useSessionCreateForm({ onCreated, onFailed }: UseSessionCreateFo}};- return { showCreateModal, setShowCreateModal, newSessionName, setNewSessionName, creating, handleCreate };+ return {+ showCreateModal,+ setShowCreateModal,+ newSessionName,+ setNewSessionName,+ useProxy,+ setUseProxy,+ proxyUrl,+ setProxyUrl,+ proxyType,+ setProxyType,+ creating,+ handleCreate,+ };}diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 3323755ad..3e342a0a0 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -11,6 +11,7 @@"cancel": "إلغاء","delete": "حذف","create": "إنشاء",+ "save": "Save","close": "إغلاق","showApiKey": "إظهار مفتاح API","hideApiKey": "إخفاء مفتاح API",@@ -216,6 +217,9 @@"phone": "رقم الهاتف","status": "الحالة","lastActive": "آخر نشاط",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","actions": "إجراءات"},"noSessions": "لم يتم العثور على جلسات. أنشئ جلسة للبدء.",@@ -314,8 +318,27 @@"autoRejectCalls": "الرفض التلقائي للمكالمات","autoRejectCallsHint": "يتم رفض المكالمات الواردة فور رنينها. ولا يزال الويب هوك call.received يُرسل قبل ذلك. يسري على المكالمة التالية — دون الحاجة إلى إعادة التشغيل."},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "عرض",+ "proxy": "Proxy","start": "بدء","stop": "إيقاف","reconnect": "إعادة الاتصال",@@ -902,6 +925,7 @@"title": "المثيلات","description": "أنشئ مثيلات لكل حساب لهذا التكامل. كل مثيل له مفتاح توقيع سري وعنوان دخول خاص به.","create": "إنشاء مثيل",+ "save": "Save","empty": "لا توجد مثيلات بعد. أنشئ مثيلًا للحصول على عنوان دخول ومفتاح سري.","loadError": "فشل تحميل المثيلات.","allSessions": "جميع الجلسات",diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex 4542b1e67..ce65c2591 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -11,6 +11,7 @@"cancel": "Abbrechen","delete": "Löschen","create": "Erstellen",+ "save": "Save","close": "Schließen","showApiKey": "API-Schlüssel anzeigen","hideApiKey": "API-Schlüssel ausblenden",@@ -205,6 +206,9 @@"phone": "Telefonnummer","status": "Status","lastActive": "Zuletzt aktiv",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","actions": "Aktionen"},"noSessions": "Keine Sitzungen gefunden. Erstelle eine, um zu beginnen.",@@ -303,8 +307,27 @@"autoRejectCalls": "Anrufe automatisch ablehnen","autoRejectCallsHint": "Eingehende Anrufe werden abgelehnt, sobald sie klingeln. Der Webhook call.received wird trotzdem zuerst ausgelöst. Gilt ab dem nächsten Anruf — kein Neustart nötig."},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "Ansehen",+ "proxy": "Proxy","start": "Starten","stop": "Stoppen","reconnect": "Erneut verbinden",@@ -887,6 +910,7 @@"title": "Instanzen","description": "Erstelle kontobezogene Instanzen für diese Integration. Jede Instanz besitzt ein eigenes Signaturgeheimnis und eine eigene Ingress-URL.","create": "Instanz erstellen",+ "save": "Save","empty": "Noch keine Instanzen vorhanden. Erstelle eine, um eine Ingress-URL und ein Geheimnis zu erhalten.","loadError": "Instanzen konnten nicht geladen werden.","allSessions": "Alle Sitzungen",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex f4b323e61..61e3e8fe8 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -11,6 +11,7 @@"cancel": "Cancel","delete": "Delete","create": "Create",+ "save": "Save","close": "Close","showApiKey": "Show API key","hideApiKey": "Hide API key",@@ -307,8 +308,27 @@"autoRejectCalls": "Auto-reject calls","autoRejectCallsHint": "Incoming calls are declined as soon as they ring. The call.received webhook still fires first. Applies to the next call — no restart needed."},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "View",+ "proxy": "Proxy","start": "Start","stop": "Stop","reconnect": "Reconnect",@@ -330,6 +350,9 @@"phone": "Phone","sessionId": "Session ID","lastActive": "Last Active",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","error": "Error","restriction": "Restriction"},diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex a6c7c347c..e510223f8 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -11,6 +11,7 @@"cancel": "Cancelar","delete": "Eliminar","create": "Crear",+ "save": "Save","close": "Cerrar","search": "Buscar","status": "Estado",@@ -205,6 +206,9 @@"phone": "Número de teléfono","status": "Estado","lastActive": "Última actividad",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","actions": "Acciones"},"noSessions": "No se encontraron sesiones. Crea una para empezar.",@@ -303,8 +307,27 @@"autoRejectCalls": "Rechazar llamadas automáticamente","autoRejectCallsHint": "Las llamadas entrantes se rechazan en cuanto suenan. El webhook call.received se envía igualmente antes. Se aplica a la próxima llamada; no hace falta reiniciar."},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "Ver",+ "proxy": "Proxy","start": "Iniciar","stop": "Detener","reconnect": "Reconectar",@@ -887,6 +910,7 @@"title": "Instancias","description": "Aprovisiona instancias por cuenta para esta integración. Cada instancia tiene su propio secreto de firma y URL de entrada.","create": "Crear instancia",+ "save": "Save","empty": "Aún no hay instancias. Crea una para obtener una URL de entrada y un secreto.","loadError": "Error al cargar las instancias.","allSessions": "Todas las sesiones",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex 1b80b8ed9..99a06f64b 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -11,6 +11,7 @@"cancel": "Annuler","delete": "Supprimer","create": "Créer",+ "save": "Save","close": "Fermer","showApiKey": "Afficher la clé API","hideApiKey": "Masquer la clé API",@@ -205,6 +206,9 @@"phone": "Numéro de téléphone","status": "Statut","lastActive": "Dernière activité",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","actions": "Actions"},"noSessions": "Aucune session trouvée. Créez-en une pour commencer.",@@ -303,8 +307,27 @@"autoRejectCalls": "Rejeter automatiquement les appels","autoRejectCallsHint": "Les appels entrants sont refusés dès qu'ils sonnent. Le webhook call.received est tout de même émis avant. S'applique au prochain appel — aucun redémarrage nécessaire."},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "Voir",+ "proxy": "Proxy","start": "Démarrer","stop": "Arrêter","reconnect": "Reconnecter",@@ -887,6 +910,7 @@"title": "Instances","description": "Provisionnez des instances par compte pour cette intégration. Chaque instance dispose de son propre secret de signature et de sa propre URL d'entrée.","create": "Créer une instance",+ "save": "Save","empty": "Aucune instance pour le moment. Créez-en une pour obtenir une URL d'entrée et un secret.","loadError": "Échec du chargement des instances.","allSessions": "Toutes les sessions",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex e82baf561..15c360dff 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -11,6 +11,7 @@"cancel": "ביטול","delete": "מחיקה","create": "יצירה",+ "save": "Save","close": "סגירה","showApiKey": "הצג מפתח API","hideApiKey": "הסתר מפתח API",@@ -212,6 +213,9 @@"phone": "מספר טלפון","status": "סטטוס","lastActive": "פעילות אחרונה",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","actions": "פעולות"},"noSessions": "לא נמצאו Sessions. יש ליצור אחד כדי להתחיל.",@@ -310,8 +314,27 @@"autoRejectCalls": "דחיית שיחות אוטומטית","autoRejectCallsHint": "שיחות נכנסות נדחות ברגע שהן מצלצלות. ה-webhook call.received עדיין נשלח לפני כן. חל מהשיחה הבאה — ללא צורך בהפעלה מחדש."},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "צפייה",+ "proxy": "Proxy","start": "הפעלה","stop": "עצירה","reconnect": "התחברות מחדש",@@ -896,6 +919,7 @@"title": "מופעים","description": "הקצו מופעים לכל חשבון עבור אינטגרציה זו. לכל מופע יש מפתח חתימה סודי וכתובת URL לקליטה משלו.","create": "יצירת מופע",+ "save": "Save","empty": "אין עדיין מופעים. צרו מופע כדי לקבל כתובת URL וסוד.","loadError": "טעינת המופעים נכשלה.","allSessions": "כל ה-Sessions",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex 8196a0c5b..8311866cf 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -11,6 +11,7 @@"cancel": "Annulla","delete": "Elimina","create": "Crea",+ "save": "Save","close": "Chiudi","showApiKey": "Mostra la chiave API","hideApiKey": "Nascondi la chiave API",@@ -205,6 +206,9 @@"phone": "Numero di Telefono","status": "Stato","lastActive": "Ultima Attività",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","actions": "Azioni"},"noSessions": "Nessuna sessione trovata. Creane una per iniziare.",@@ -303,8 +307,27 @@"autoRejectCalls": "Rifiuta automaticamente le chiamate","autoRejectCallsHint": "Le chiamate in arrivo vengono rifiutate appena squillano. Il webhook call.received viene comunque inviato prima. Si applica alla prossima chiamata — nessun riavvio necessario."},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "Visualizza",+ "proxy": "Proxy","start": "Avvia","stop": "Ferma","reconnect": "Riconnetti",@@ -887,6 +910,7 @@"title": "Istanze","description": "Effettua il provisioning di istanze per account per questa integrazione. Ogni istanza ha il proprio segreto di firma e URL di ingresso.","create": "Crea istanza",+ "save": "Save","empty": "Nessuna istanza ancora. Creane una per ottenere un URL di ingresso e un segreto.","loadError": "Impossibile caricare le istanze.","allSessions": "Tutte le sessioni",diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex 41ba479cf..f5f729719 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -11,6 +11,7 @@"cancel": "취소","delete": "삭제","create": "생성",+ "save": "Save","close": "닫기","showApiKey": "API 키 표시","hideApiKey": "API 키 숨기기",@@ -205,6 +206,9 @@"phone": "전화번호","status": "상태","lastActive": "마지막 활동",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","actions": "작업"},"noSessions": "세션이 없습니다. 세션을 생성해 시작하세요.",@@ -303,8 +307,27 @@"autoRejectCalls": "통화 자동 거절","autoRejectCallsHint": "수신 통화가 울리는 즉시 거절됩니다. call.received 웹훅은 그전에 그대로 전송됩니다. 다음 통화부터 적용되며 재시작이 필요하지 않습니다."},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "보기",+ "proxy": "Proxy","start": "시작","stop": "중지","reconnect": "재연결",@@ -887,6 +910,7 @@"title": "인스턴스","description": "이 연동을 위해 계정별 인스턴스를 프로비저닝하세요. 각 인스턴스는 고유한 서명 시크릿과 인그레스 URL을 가집니다.","create": "인스턴스 생성",+ "save": "Save","empty": "아직 인스턴스가 없습니다. 인스턴스를 만들면 인그레스 URL과 시크릿을 받을 수 있습니다.","loadError": "인스턴스를 불러오지 못했습니다.","allSessions": "모든 세션",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 01f28ece6..d2473dcde 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -11,6 +11,7 @@"cancel": "Cancelar","delete": "Excluir","create": "Criar",+ "save": "Save","close": "Fechar","search": "Pesquisar","status": "Status",@@ -205,6 +206,9 @@"phone": "Número de telefone","status": "Status","lastActive": "Última atividade",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","actions": "Ações"},"noSessions": "Nenhuma sessão encontrada. Crie uma para começar.",@@ -303,8 +307,27 @@"autoRejectCalls": "Rejeitar chamadas automaticamente","autoRejectCallsHint": "As chamadas recebidas são recusadas assim que tocam. O webhook call.received continua sendo enviado antes. Vale a partir da próxima chamada — sem reiniciar."},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "Ver",+ "proxy": "Proxy","start": "Iniciar","stop": "Parar","reconnect": "Reconectar",@@ -887,6 +910,7 @@"title": "Instâncias","description": "Provisione instâncias por conta para esta integração. Cada instância tem seu próprio segredo de assinatura e URL de entrada.","create": "Criar instância",+ "save": "Save","empty": "Ainda não há instâncias. Crie uma para obter uma URL de entrada e um segredo.","loadError": "Falha ao carregar as instâncias.","allSessions": "Todas as sessões",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex df2eae15e..d0d3b12c3 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -11,6 +11,7 @@"cancel": "రద్దు చేయి","delete": "తొలగించు","create": "సృష్టించు",+ "save": "Save","close": "మూసివేయి","showApiKey": "API కీని చూపు","hideApiKey": "API కీని దాచు",@@ -205,6 +206,9 @@"phone": "ఫోన్ నంబర్","status": "స్థితి","lastActive": "చివరిసారి యాక్టివ్",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","actions": "చర్యలు"},"noSessions": "ఎలాంటి సెషన్లు కనుగొనబడలేదు. ప్రారంభించడానికి ఒకదాన్ని సృష్టించండి.",@@ -303,8 +307,27 @@"autoRejectCalls": "కాల్లను ఆటోమేటిక్గా తిరస్కరించు","autoRejectCallsHint": "ఇన్కమింగ్ కాల్లు మోగిన వెంటనే తిరస్కరించబడతాయి. call.received వెబ్హుక్ మాత్రం ముందుగా పంపబడుతుంది. తదుపరి కాల్ నుండి వర్తిస్తుంది — పునఃప్రారంభం అవసరం లేదు."},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "చూడు",+ "proxy": "Proxy","start": "ప్రారంభించు","stop": "ఆపివేయి","reconnect": "మళ్లీ కనెక్ట్ చేయి",@@ -887,6 +910,7 @@"title": "ఇన్స్టాన్స్లు","description": "ఈ ఇంటిగ్రేషన్ కోసం ఖాతా వారీగా ఇన్స్టాన్స్లను ప్రొవిజన్ చేయండి. ప్రతి ఇన్స్టాన్స్కు దాని స్వంత సైనింగ్ సీక్రెట్ మరియు ఇన్గ్రెస్ URL ఉంటుంది.","create": "ఇన్స్టాన్స్ను సృష్టించండి",+ "save": "Save","empty": "ఇంకా ఇన్స్టాన్స్లు లేవు. ఇన్గ్రెస్ URL మరియు సీక్రెట్ పొందడానికి ఒకటి సృష్టించండి.","loadError": "ఇన్స్టాన్స్లను లోడ్ చేయడం విఫలమైంది.","allSessions": "అన్ని సెషన్లు",diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.jsonindex 4a3700198..5a5ac2fae 100644--- a/dashboard/src/i18n/locales/tr.json+++ b/dashboard/src/i18n/locales/tr.json@@ -11,6 +11,7 @@"cancel": "İptal","delete": "Sil","create": "Oluştur",+ "save": "Save","close": "Kapat","showApiKey": "API anahtarını göster","hideApiKey": "API anahtarını gizle",@@ -205,6 +206,9 @@"phone": "Telefon Numarası","status": "Durum","lastActive": "Son Görülme",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","actions": "İşlemler"},"noSessions": "Oturum bulunamadı. Başlamak için bir tane oluşturun.",@@ -307,8 +311,27 @@"autoRejectCalls": "Aramaları otomatik reddet","autoRejectCallsHint": "Gelen aramalar çaldığı anda reddedilir. call.received webhook'u yine de ilk olarak tetiklenir. Bir sonraki arama için geçerlidir — yeniden başlatma gerekmez."},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "Görüntüle",+ "proxy": "Proxy","start": "Başlat","stop": "Durdur","reconnect": "Yeniden Bağlan",@@ -887,6 +910,7 @@"title": "Örnekler (Instances)","description": "Bu entegrasyon için hesap başına örnekler tanımlayın. Her örneğin kendi imzalama gizli anahtarı ve giriş URL'si vardır.","create": "Örnek oluştur",+ "save": "Save","empty": "Henüz örnek yok. Giriş URL'si ve gizli anahtar almak için bir tane oluşturun.","loadError": "Örnekler yüklenemedi.","allSessions": "Tüm oturumlar",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex 3441f04c0..f62a5ad08 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -11,6 +11,7 @@"cancel": "取消","delete": "删除","create": "创建",+ "save": "Save","close": "关闭","showApiKey": "显示 API 密钥","hideApiKey": "隐藏 API 密钥",@@ -205,6 +206,9 @@"phone": "电话号码","status": "状态","lastActive": "上次活跃",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","actions": "操作"},"noSessions": "未找到会话。创建一个即可开始。",@@ -303,8 +307,27 @@"autoRejectCalls": "自动拒接来电","autoRejectCallsHint": "来电响铃后立即拒接。call.received webhook 仍会先行触发。下一通来电起生效,无需重启。"},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "查看",+ "proxy": "Proxy","start": "启动","stop": "停止","reconnect": "重新连接",@@ -887,6 +910,7 @@"title": "实例","description": "为此集成按账户配置实例。每个实例都有自己的签名密钥和接入 URL。","create": "创建实例",+ "save": "Save","empty": "暂无实例。创建一个以获取接入 URL 和密钥。","loadError": "加载实例失败。","allSessions": "所有会话",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex ad176393f..ee464eafd 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -11,6 +11,7 @@"cancel": "取消","delete": "刪除","create": "建立",+ "save": "Save","close": "關閉","showApiKey": "顯示 API 金鑰","hideApiKey": "隱藏 API 金鑰",@@ -205,6 +206,9 @@"phone": "電話號碼","status": "狀態","lastActive": "上次活躍",+ "proxy": "Proxy",+ "proxyEnabled": "{{type}} · {{host}}",+ "proxyDisabled": "None","actions": "操作"},"noSessions": "找不到工作階段。建立一個即可開始。",@@ -303,8 +307,27 @@"autoRejectCalls": "自動拒接來電","autoRejectCallsHint": "來電響鈴後即時拒接。call.received webhook 仍會先行觸發。下一通來電起生效,無需重新啟動。"},+ "proxy": {+ "title": "Proxy Configuration",+ "status": "Current",+ "enabled": "Use proxy",+ "url": "Proxy URL",+ "urlPlaceholder": "http://user:[email protected]:8080",+ "urlKeepPlaceholder": "Enter new URL to replace {{host}} (credentials not shown)",+ "type": "Proxy type",+ "configured": "{{host}} ({{type}})",+ "noProxy": "No proxy configured",+ "hasCredentials": "Credentials are stored but not shown. Enter a full URL to change them.",+ "hint": "Changes apply on the next session start, not to a running connection. The proxy must be real and reachable — an unreachable value blocks QR delivery and start returns 504.",+ "createHint": "Only needed when your network cannot reach WhatsApp directly. Must be a real, reachable proxy.",+ "invalidUrl": "Enter a valid http, https, socks4, or socks5 proxy URL.",+ "saveSuccessTitle": "Proxy Saved",+ "saveSuccess": "Proxy settings saved. They apply on the next session start.",+ "saveError": "Failed to save proxy settings"+ },"actions": {"view": "查看",+ "proxy": "Proxy","start": "啟動","stop": "停止","reconnect": "重新連線",@@ -887,6 +910,7 @@"title": "執行個體","description": "為此整合按帳戶佈建執行個體。每個執行個體都有專屬的簽署密鑰和連入 URL。","create": "建立執行個體",+ "save": "Save","empty": "尚無執行個體。建立一個即可取得連入 URL 和密鑰。","loadError": "載入執行個體失敗。","allSessions": "所有工作階段",diff --git a/dashboard/src/pages/Sessions.css b/dashboard/src/pages/Sessions.cssindex 8942500a0..fc1a556e5 100644--- a/dashboard/src/pages/Sessions.css+++ b/dashboard/src/pages/Sessions.css@@ -86,6 +86,12 @@margin-bottom: 1.25rem;}+.sessions-page .session-card .session-proxy {+ margin: -0.75rem 0 1rem;+ padding-bottom: 0.75rem;+ border-bottom: 1px solid var(--border);+}+.sessions-page .card-header h3 {/* Inherits from H3 */margin: 0;@@ -862,3 +868,23 @@outline: 2px solid var(--primary);outline-offset: 2px;}++.sessions-page .proxy-form-section {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+ margin-top: 1rem;+ padding-top: 1rem;+ border-top: 1px solid var(--border);+}++.sessions-page .proxy-form-section input[type='text'] {+ width: 100%;+ padding: 0.625rem 0.75rem;+ border: 1px solid var(--border);+ border-radius: var(--radius);+ background: var(--bg-white);+ color: var(--text-primary);+ font-size: 0.9375rem;+ box-sizing: border-box;+}diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.tsindex 61240d4d0..1b74cd86f 100644--- a/dashboard/src/pages/Sessions.test.ts+++ b/dashboard/src/pages/Sessions.test.ts@@ -27,6 +27,9 @@ const SESSION_QR: Session = {status: 'qr_ready',engineLoaded: true,phone: null,+ proxyEnabled: true,+ proxyType: 'http',+ proxyHost: 'proxy.internal:8080',createdAt: '2026-01-01T00:00:00.000Z',updatedAt: '2026-01-01T00:00:00.000Z',};@@ -41,6 +44,9 @@ const SESSION_STALE_ENGINE: Session = {status: 'disconnected',engineLoaded: true,phone: '15550009999',+ proxyEnabled: false,+ proxyType: null,+ proxyHost: null,createdAt: '2026-01-01T00:00:00.000Z',updatedAt: '2026-01-01T00:00:00.000Z',};@@ -78,6 +84,7 @@ const fetchCalls: FetchCall[] = [];function resetFetchCalls(): void {fetchCalls.length = 0;+ sessionProxy = { enabled: false, proxyType: null, proxyHost: null, hasCredentials: false };}function findFetchCall(method: string, path: string): FetchCall | undefined {@@ -91,6 +98,12 @@ function findFetchCall(method: string, path: string): FetchCall | undefined {// Mutable so a test can set the starting value and observe what a PATCH wrote back.let sessionConfig = { autoRejectCalls: false, maxReconnectAttempts: null as number | null, reconnectBaseDelay: 5000 };let configPatchFails = false;+let sessionProxy = {+ enabled: false,+ proxyType: null as string | null,+ proxyHost: null as string | null,+ hasCredentials: false,+};function installFetchStub(): void {globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {@@ -111,7 +124,17 @@ function installFetchStub(): void {if (method === 'GET' && path === '/api/sessions') return Promise.resolve(jsonResponse(SESSIONS));if (method === 'POST' && path === '/api/sessions') {- const name = (body as { name?: string } | undefined)?.name ?? 'unnamed';+ const payload = body as { name?: string; proxyUrl?: string; proxyType?: string } | undefined;+ const name = payload?.name ?? 'unnamed';+ let proxyEnabled = false;+ let proxyType: string | null = null;+ let proxyHost: string | null = null;+ if (payload?.proxyUrl) {+ const parsed = new URL(payload.proxyUrl);+ proxyEnabled = true;+ proxyType = payload.proxyType ?? 'http';+ proxyHost = parsed.host;+ }return Promise.resolve(jsonResponse({id: `sess-new-${name}`,@@ -119,6 +142,9 @@ function installFetchStub(): void {status: 'created',createdAt: '2026-01-01T00:00:00.000Z',updatedAt: '2026-01-01T00:00:00.000Z',+ proxyEnabled,+ proxyType,+ proxyHost,}),);}@@ -146,6 +172,28 @@ function installFetchStub(): void {}}+ const proxyMatch = path.match(/^\/api\/sessions\/([^/]+)\/proxy$/);+ if (proxyMatch) {+ if (method === 'GET') return Promise.resolve(jsonResponse({ ...sessionProxy }));+ if (method === 'PATCH') {+ const payload = body as { proxyUrl?: string | null; proxyType?: string | null } | undefined;+ if (payload?.proxyUrl === null) {+ sessionProxy = { enabled: false, proxyType: null, proxyHost: null, hasCredentials: false };+ } else if (payload?.proxyUrl) {+ const parsed = new URL(payload.proxyUrl);+ sessionProxy = {+ enabled: true,+ proxyType: payload.proxyType ?? 'http',+ proxyHost: parsed.host,+ hasCredentials: !!(parsed.username || parsed.password),+ };+ } else if (payload?.proxyType && sessionProxy.enabled) {+ sessionProxy = { ...sessionProxy, proxyType: payload.proxyType };+ }+ return Promise.resolve(jsonResponse({ ...sessionProxy }));+ }+ }+const qrMatch = path.match(/^\/api\/sessions\/([^/]+)\/qr$/);if (method === 'GET' && qrMatch) {const found = SESSIONS.find(s => s.id === qrMatch[1]);@@ -241,6 +289,19 @@ test('the session list renders, and action buttons gate on engineLoaded rather tconst qrCard = screen.getByText('new-device').closest('.session-card') as HTMLElement;within(qrCard).getByRole('button', { name: 'Show QR' });+ within(qrCard).getByRole('button', { name: 'Proxy' });+});++test('the card body shows configured proxy status from the list payload', async () => {+ const { screen, within } = rtl;+ resetFetchCalls();+ renderSessions();++ const qrCard = (await screen.findByText('new-device')).closest('.session-card') as HTMLElement;+ within(qrCard).getByText('HTTP · proxy.internal:8080');++ const staleCard = screen.getByText('stale-engine').closest('.session-card') as HTMLElement;+ within(staleCard).getByText('None');});test('creating a session issues POST /api/sessions with the entered name', async () => {@@ -265,6 +326,48 @@ test('creating a session issues POST /api/sessions with the entered name', asyncawait screen.findByText('backup-bot');});+test('opening the proxy modal fetches GET /api/sessions/:id/proxy', async () => {+ const { screen, fireEvent, within, waitFor } = rtl;+ resetFetchCalls();+ renderSessions();++ await screen.findByText('new-device');+ const qrCard = screen.getByText('new-device').closest('.session-card') as HTMLElement;+ fireEvent.click(within(qrCard).getByRole('button', { name: 'Proxy' }));++ await screen.findByRole('dialog');+ await waitFor(() => {+ assert.ok(findFetchCall('GET', '/api/sessions/sess-qr-1/proxy'), 'expected a GET to /proxy');+ });+});++test('saving proxy settings issues PATCH /api/sessions/:id/proxy', async () => {+ const { screen, fireEvent, within, waitFor } = rtl;+ resetFetchCalls();+ renderSessions();++ await screen.findByText('new-device');+ const qrCard = screen.getByText('new-device').closest('.session-card') as HTMLElement;+ fireEvent.click(within(qrCard).getByRole('button', { name: 'Proxy' }));++ const dialog = await screen.findByRole('dialog');+ const toggle = within(dialog).getByRole('checkbox');+ fireEvent.click(toggle);+ fireEvent.change(within(dialog).getByLabelText('Proxy URL'), {+ target: { value: 'http://user:[email protected]:8080' },+ });+ fireEvent.click(within(dialog).getByRole('button', { name: 'Save' }));++ await waitFor(() => {+ const call = findFetchCall('PATCH', '/api/sessions/sess-qr-1/proxy');+ assert.ok(call, 'expected a PATCH to /proxy');+ assert.deepEqual(call!.body, {+ proxyUrl: 'http://user:[email protected]:8080',+ proxyType: 'http',+ });+ });+});+test('a typed pairing phone number survives toggling to the QR tab and back', async () => {const { screen, fireEvent, within } = rtl;resetFetchCalls();diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex 6d940daf3..2dcd07987 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -14,8 +14,16 @@ import {Filter,Skull,Unlink,+ Globe,} from 'lucide-react';-import { sessionApi, type Session, type SessionConfig, type AccountRestriction } from '../services/api';+import {+ sessionApi,+ type Session,+ type SessionConfig,+ type SessionProxy,+ type SessionProxyType,+ type AccountRestriction,+} from '../services/api';import { queryKeys } from '../hooks/queries';import { useDocumentTitle } from '../hooks/useDocumentTitle';import {@@ -26,7 +34,7 @@ import {replaceSession,} from '../utils/sessionActions';import { invalidateSessionQueries, reconcileSessionCache } from '../utils/sessionMutation';-import { canCreateSession, filterSessions, isValidPairingPhone, sessionNameIssues } from '../utils/sessionForm';+import { canCreateSession, filterSessions, isValidPairingPhone, isValidProxyUrl, sessionNameIssues } from '../utils/sessionForm';import { useToast } from '../hooks/useToast';import { useRole } from '../hooks/useRole';import { useSessionPairing } from '../hooks/useSessionPairing';@@ -51,6 +59,13 @@ function restrictionTitle(restriction: AccountRestriction, t: TFunction): stringreturn parts.join(' · ');}+const PROXY_TYPE_OPTIONS: { value: SessionProxyType; label: string }[] = [+ { value: 'http', label: 'HTTP' },+ { value: 'https', label: 'HTTPS' },+ { value: 'socks4', label: 'SOCKS4' },+ { value: 'socks5', label: 'SOCKS5' },+];+export function Sessions() {const { t } = useTranslation();useDocumentTitle(t('sessions.title'));@@ -73,6 +88,14 @@ export function Sessions() {// fetched per session when the detail modal opens rather than N times to render the list.const [sessionConfig, setSessionConfig] = useState<SessionConfig | null>(null);const [savingConfig, setSavingConfig] = useState(false);+ const [proxySession, setProxySession] = useState<Session | null>(null);+ const [proxyInfo, setProxyInfo] = useState<SessionProxy | null>(null);+ const [proxyLoading, setProxyLoading] = useState(false);+ const [proxySaving, setProxySaving] = useState(false);+ const [proxyEnabled, setProxyEnabled] = useState(false);+ const [proxyUrl, setProxyUrl] = useState('');+ const [proxyType, setProxyType] = useState<SessionProxyType>('http');+ const [proxyUrlError, setProxyUrlError] = useState<string | null>(null);const fetchSessions = useCallback(async (): Promise<Session[]> => {try {@@ -125,8 +148,20 @@ export function Sessions() {dismissQrForSession,} = useSessionPairing({ sessions, sessionsRef, reloadSessions: fetchSessions });- const { showCreateModal, setShowCreateModal, newSessionName, setNewSessionName, creating, handleCreate } =- useSessionCreateForm({+ const {+ showCreateModal,+ setShowCreateModal,+ newSessionName,+ setNewSessionName,+ useProxy,+ setUseProxy,+ proxyUrl: createProxyUrl,+ setProxyUrl: setCreateProxyUrl,+ proxyType: createProxyType,+ setProxyType: setCreateProxyType,+ creating,+ handleCreate,+ } = useSessionCreateForm({onCreated: newSession => {// Functional append: never capture a stale `sessions` (a WS or fetch between the await and the// setState would otherwise drop a row). Then invalidate the prefix so stats/groups/chats refresh.@@ -308,6 +343,87 @@ export function Sessions() {}};+ const proxySessionId = proxySession?.id ?? null;+ useEffect(() => {+ setProxyInfo(null);+ setProxyEnabled(false);+ setProxyUrl('');+ setProxyType('http');+ setProxyUrlError(null);+ if (!proxySessionId) return;+ let cancelled = false;+ setProxyLoading(true);+ sessionApi+ .getProxy(proxySessionId)+ .then(data => {+ if (cancelled) return;+ setProxyInfo(data);+ setProxyEnabled(data.enabled);+ setProxyType(data.proxyType ?? 'http');+ })+ .catch(err => {+ if (!cancelled) {+ toast.error(t('sessions.proxy.saveError'), err instanceof Error ? err.message : t('common.unknownError'));+ }+ })+ .finally(() => {+ if (!cancelled) setProxyLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, [proxySessionId, t, toast]);++ const handleProxySave = async () => {+ if (!proxySession) return;+ if (proxyEnabled) {+ const trimmed = proxyUrl.trim();+ if (!trimmed && !proxyInfo?.enabled) {+ setProxyUrlError(t('sessions.proxy.invalidUrl'));+ return;+ }+ if (trimmed && !isValidProxyUrl(trimmed)) {+ setProxyUrlError(t('sessions.proxy.invalidUrl'));+ return;+ }+ }+ setProxyUrlError(null);+ setProxySaving(true);+ try {+ let updatedProxy;+ if (!proxyEnabled) {+ updatedProxy = await sessionApi.updateProxy(proxySession.id, { proxyUrl: null });+ } else if (proxyUrl.trim()) {+ updatedProxy = await sessionApi.updateProxy(proxySession.id, { proxyUrl: proxyUrl.trim(), proxyType });+ } else if (proxyInfo?.enabled) {+ updatedProxy = await sessionApi.updateProxy(proxySession.id, { proxyType });+ } else {+ return;+ }+ setSessions(current =>+ current.map(s =>+ s.id === proxySession.id+ ? {+ ...s,+ proxyEnabled: updatedProxy.enabled,+ proxyType: updatedProxy.proxyType,+ proxyHost: updatedProxy.proxyHost,+ }+ : s,+ ),+ );+ toast.success(t('sessions.proxy.saveSuccessTitle'), t('sessions.proxy.saveSuccess'));+ setProxySession(null);+ } catch (err) {+ toast.error(+ t('sessions.proxy.saveError'),+ err instanceof Error ? err.message : t('common.unknownError'),+ );+ } finally {+ setProxySaving(false);+ }+ };+const handleStop = async (id: string) => {try {const updated = await sessionApi.stop(id);@@ -378,6 +494,9 @@ export function Sessions() {const existingSessionNames = sessions.map(s => s.name);// Empty is a disabled button, not a message: the form stays quiet until the user types something.const nameIssues = newSessionName ? sessionNameIssues(newSessionName, existingSessionNames) : [];+ const createProxyInvalid =+ useProxy &&+ (!createProxyUrl.trim() || (createProxyUrl.trim() && !isValidProxyUrl(createProxyUrl.trim())));if (loading) {return (@@ -459,7 +578,11 @@ export function Sessions() {<buttonclassName="btn-primary"onClick={handleCreate}- disabled={creating || !canCreateSession(newSessionName, existingSessionNames)}+ disabled={+ creating ||+ !canCreateSession(newSessionName, existingSessionNames) ||+ createProxyInvalid+ }>{creating ? <Loader2 className="animate-spin" size={16} /> : t('common.create')}</button>@@ -486,6 +609,39 @@ export function Sessions() {<p className="input-error">{t('sessions.create.tooLong', { length: newSessionName.length })}</p>)}{nameIssues.includes('duplicate') && <p className="input-error">{t('sessions.create.duplicate')}</p>}+ <div className="proxy-form-section">+ <label className="detail-toggle-row" htmlFor="create-use-proxy">+ <span>{t('sessions.proxy.enabled')}</span>+ <input+ id="create-use-proxy"+ type="checkbox"+ checked={useProxy}+ onChange={e => setUseProxy(e.target.checked)}+ />+ </label>+ {useProxy && (+ <>+ <label htmlFor="create-proxy-url">{t('sessions.proxy.url')}</label>+ <input+ id="create-proxy-url"+ type="text"+ placeholder={t('sessions.proxy.urlPlaceholder')}+ value={createProxyUrl}+ onChange={e => setCreateProxyUrl(e.target.value)}+ />+ <label htmlFor="create-proxy-type">{t('sessions.proxy.type')}</label>+ <CustomSelect+ value={createProxyType}+ onChange={value => setCreateProxyType(value as SessionProxyType)}+ options={PROXY_TYPE_OPTIONS}+ />+ {createProxyInvalid && createProxyUrl.trim() && (+ <p className="input-error">{t('sessions.proxy.invalidUrl')}</p>+ )}+ <p className="input-hint">{t('sessions.proxy.createHint')}</p>+ </>+ )}+ </div></Modal>)}@@ -695,6 +851,108 @@ export function Sessions() {</Modal>)}+ {proxySession && (+ <Modal+ open+ onClose={() => setProxySession(null)}+ title={+ <span className="modal-title">+ {t('sessions.proxy.title')}+ <span className="session-name">{proxySession.name}</span>+ </span>+ }+ closeLabel={t('common.close')}+ footer={+ <>+ <button className="btn-secondary" onClick={() => setProxySession(null)}>+ {t('common.cancel')}+ </button>+ {canWrite && (+ <button className="btn-primary" onClick={() => void handleProxySave()} disabled={proxySaving || proxyLoading}>+ {proxySaving ? <Loader2 className="animate-spin" size={16} /> : t('common.save')}+ </button>+ )}+ </>+ }+ >+ {proxyLoading ? (+ <div style={{ display: 'flex', justifyContent: 'center', padding: '2rem' }}>+ <Loader2 className="animate-spin" size={24} />+ </div>+ ) : (+ <div className="detail-grid proxy-form-section">+ <div className="detail-item">+ <span className="detail-label">{t('sessions.proxy.status')}</span>+ <span className="detail-value">+ {proxyInfo?.enabled+ ? t('sessions.proxy.configured', {+ host: proxyInfo.proxyHost ?? '—',+ type: proxyInfo.proxyType ?? 'http',+ })+ : t('sessions.proxy.noProxy')}+ </span>+ {proxyInfo?.hasCredentials ? (+ <small className="detail-hint">{t('sessions.proxy.hasCredentials')}</small>+ ) : null}+ </div>+ <div className="detail-item detail-item-toggle">+ <div className="detail-toggle-row">+ <span className="detail-label" id="proxy-enabled-label">+ {t('sessions.proxy.enabled')}+ </span>+ <label className="toggle-switch">+ <input+ type="checkbox"+ aria-labelledby="proxy-enabled-label"+ checked={proxyEnabled}+ disabled={!canWrite || proxySaving}+ onChange={e => setProxyEnabled(e.target.checked)}+ />+ <span className="toggle-slider"></span>+ </label>+ </div>+ </div>+ {proxyEnabled && (+ <>+ <div className="detail-item">+ <label className="detail-label" htmlFor="proxy-url">+ {t('sessions.proxy.url')}+ </label>+ <input+ id="proxy-url"+ type="text"+ placeholder={+ proxyInfo?.enabled+ ? t('sessions.proxy.urlKeepPlaceholder', { host: proxyInfo.proxyHost ?? '' })+ : t('sessions.proxy.urlPlaceholder')+ }+ value={proxyUrl}+ disabled={!canWrite || proxySaving}+ onChange={e => {+ setProxyUrl(e.target.value);+ setProxyUrlError(null);+ }}+ />+ {proxyUrlError ? <p className="input-error">{proxyUrlError}</p> : null}+ </div>+ <div className="detail-item">+ <label className="detail-label" htmlFor="proxy-type">+ {t('sessions.proxy.type')}+ </label>+ <CustomSelect+ value={proxyType}+ onChange={value => setProxyType(value as SessionProxyType)}+ options={PROXY_TYPE_OPTIONS}+ />+ </div>+ </>+ )}+ <p className="input-hint">{t('sessions.proxy.hint')}</p>+ </div>+ )}+ </Modal>+ )}+{deleteConfirmId && (<Modalopen@@ -801,6 +1059,18 @@ export function Sessions() {<span className={`status-pill ${session.status}`}>{formatStatus(session.status)}</span></div>+ <div className="info-row session-proxy">+ <span className="info-label">{t('sessions.card.proxy')}</span>+ <span className="info-value" title={session.proxyEnabled ? session.proxyHost ?? undefined : undefined}>+ {session.proxyEnabled+ ? t('sessions.card.proxyEnabled', {+ type: (session.proxyType ?? 'http').toUpperCase(),+ host: session.proxyHost ?? '—',+ })+ : t('sessions.card.proxyDisabled')}+ </span>+ </div>+{session.status === 'initializing' || session.status === 'qr_ready' ? (<div className="qr-placeholder"><QrCode size={80} className="qr-icon" />@@ -854,6 +1124,10 @@ export function Sessions() {<Eye size={16} />{t('sessions.actions.view')}</button>+ <button className="btn-action" onClick={() => setProxySession(session)}>+ <Globe size={16} />+ {t('sessions.actions.proxy')}+ </button>{canWrite && isSessionStarted(session) ? (<button className="btn-action" onClick={() => handleStop(session.id)}><Square size={16} />diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex a0fded4cc..415c494e1 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -33,6 +33,20 @@ export interface SessionConfig {reconnectBaseDelay: number;}+export type SessionProxyType = 'http' | 'https' | 'socks4' | 'socks5';++export interface SessionProxy {+ enabled: boolean;+ proxyType: SessionProxyType | null;+ proxyHost: string | null;+ hasCredentials: boolean;+}++export interface CreateSessionOptions {+ proxyUrl?: string;+ proxyType?: SessionProxyType;+}+export interface Session {id: string;name: string;@@ -69,6 +83,11 @@ export interface Session {* dashboard can be served by a gateway that predates the field.*/restriction?: AccountRestriction | null;+ /** Whether a per-session egress proxy is configured. Optional for gateways predating the field. */+ proxyEnabled?: boolean;+ proxyType?: SessionProxyType | null;+ /** host:port only — credentials are never returned. */+ proxyHost?: string | null;}/** One participant's presence within a chat. */@@ -755,10 +774,13 @@ async function requestBlob(endpoint: string): Promise<Blob> {export const sessionApi = {list: () => request<Session[]>('/sessions'),get: (id: string) => request<Session>(`/sessions/${id}`),- create: (name: string) =>+ create: (name: string, options?: CreateSessionOptions) =>request<Session>('/sessions', {method: 'POST',- body: JSON.stringify({ name }),+ body: JSON.stringify({+ name,+ ...(options?.proxyUrl ? { proxyUrl: options.proxyUrl, proxyType: options.proxyType ?? 'http' } : {}),+ }),}),delete: (id: string) => request<void>(`/sessions/${id}`, { method: 'DELETE' }),getConfig: (id: string) => request<SessionConfig>(`/sessions/${id}/config`),@@ -768,6 +790,15 @@ export const sessionApi = {method: 'PATCH',body: JSON.stringify(patch),}),+ getProxy: (id: string) => request<SessionProxy>(`/sessions/${id}/proxy`),+ updateProxy: (+ id: string,+ patch: { proxyUrl?: string | null; proxyType?: SessionProxyType | null },+ ) =>+ request<SessionProxy>(`/sessions/${id}/proxy`, {+ method: 'PATCH',+ body: JSON.stringify(patch),+ }),start: (id: string) => request<Session>(`/sessions/${id}/start`, { method: 'POST' }),stop: (id: string) => request<Session>(`/sessions/${id}/stop`, { method: 'POST' }),logout: (id: string) => request<Session>(`/sessions/${id}/logout`, { method: 'POST' }),diff --git a/dashboard/src/utils/sessionForm.ts b/dashboard/src/utils/sessionForm.tsindex c4864eb83..808db3ad1 100644--- a/dashboard/src/utils/sessionForm.ts+++ b/dashboard/src/utils/sessionForm.ts@@ -40,6 +40,17 @@ export function isValidPairingPhone(phone: string): boolean {return /^[0-9]{6,15}$/.test(phone.trim());}+const PROXY_PROTOCOLS = new Set(['http:', 'https:', 'socks4:', 'socks5:']);++/** Matches the gateway's accepted per-session proxy URL schemes. */+export function isValidProxyUrl(url: string): boolean {+ try {+ return PROXY_PROTOCOLS.has(new URL(url.trim()).protocol);+ } catch {+ return false;+ }+}+/*** The status filter's groups do not map one-to-one onto engine statuses — they are the operator's* mental model, not the engine's. `connecting` covers the three transient states, and `inactive`diff --git a/src/modules/session/dto/index.ts b/src/modules/session/dto/index.tsindex ceb019f79..b08eb83a4 100644--- a/src/modules/session/dto/index.ts+++ b/src/modules/session/dto/index.ts@@ -1,5 +1,6 @@export * from './create-session.dto';export * from './session-config.dto';+export * from './session-proxy.dto';export * from './session-response.dto';export * from './mark-chat-read.dto';export * from './mark-chat-unread.dto';diff --git a/src/modules/session/dto/session-proxy.dto.spec.ts b/src/modules/session/dto/session-proxy.dto.spec.tsnew file mode 100644index 000000000..b5bf6cc93--- /dev/null+++ b/src/modules/session/dto/session-proxy.dto.spec.ts@@ -0,0 +1,72 @@+import { validateSync } from 'class-validator';+import { plainToInstance } from 'class-transformer';+import { UpdateSessionProxyDto, projectSessionProxy } from './session-proxy.dto';++describe('UpdateSessionProxyDto proxyUrl validation', () => {+ const errs = (body: Record<string, unknown>): ReturnType<typeof validateSync> =>+ validateSync(plainToInstance(UpdateSessionProxyDto, body));++ it.each([+ 'http://proxy.example.com:8080',+ 'http://user:[email protected]:8080',+ 'https://proxy.example.com:8443',+ 'socks5://proxy.example.com:1080',+ 'socks4://proxy.example.com:1080',+ 'http://localhost:8080',+ 'http://squid:3128',+ 'socks5://proxy:1080',+ 'http://10.0.0.1:8080',+ ])('accepts a valid proxy URL: %s', url => {+ expect(errs({ proxyUrl: url })).toHaveLength(0);+ });++ it.each(['not a url', 'proxy.example.com:8080', 'ftp://proxy.example.com:21', 'javascript:alert(1)'])(+ 'rejects an invalid / non-proxy-scheme proxyUrl: %s',+ url => {+ expect(errs({ proxyUrl: url }).length).toBeGreaterThan(0);+ },+ );++ it('allows null proxyUrl (clear proxy)', () => {+ expect(errs({ proxyUrl: null })).toHaveLength(0);+ });++ it('allows an omitted proxyUrl', () => {+ expect(errs({ proxyType: 'http' })).toHaveLength(0);+ });+});++describe('projectSessionProxy', () => {+ it('reports disabled when no proxy is stored', () => {+ expect(projectSessionProxy({ proxyUrl: null, proxyType: null })).toEqual({+ enabled: false,+ proxyType: null,+ proxyHost: null,+ hasCredentials: false,+ });+ });++ it('returns host:port without credentials', () => {+ expect(+ projectSessionProxy({+ proxyUrl: 'http://user:[email protected]:8080',+ proxyType: 'http',+ }),+ ).toEqual({+ enabled: true,+ proxyType: 'http',+ proxyHost: 'proxy.internal:8080',+ hasCredentials: true,+ });+ });++ it('never includes the full proxyUrl in the projection', () => {+ const result = projectSessionProxy({+ proxyUrl: 'socks5://proxy.example.com:1080',+ proxyType: 'socks5',+ });+ expect(result).not.toHaveProperty('proxyUrl');+ expect(result.proxyHost).toBe('proxy.example.com:1080');+ expect(result.hasCredentials).toBe(false);+ });+});diff --git a/src/modules/session/dto/session-proxy.dto.ts b/src/modules/session/dto/session-proxy.dto.tsnew file mode 100644index 000000000..3c96b1c2f--- /dev/null+++ b/src/modules/session/dto/session-proxy.dto.ts@@ -0,0 +1,89 @@+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';+import { IsString, IsOptional, MaxLength, IsIn, IsUrl } from 'class-validator';+import type { Session } from '../entities/session.entity';++export type SessionProxyType = 'http' | 'https' | 'socks4' | 'socks5';++export class SessionProxyResponseDto {+ @ApiProperty({ description: 'Whether a proxy URL is configured for this session', example: true })+ enabled!: boolean;++ @ApiProperty({+ description: 'Configured proxy protocol',+ enum: ['http', 'https', 'socks4', 'socks5'],+ nullable: true,+ example: 'http',+ })+ proxyType!: SessionProxyType | null;++ @ApiProperty({+ description: 'Proxy host:port parsed from the stored URL — credentials are never returned',+ nullable: true,+ example: 'proxy.example.com:8080',+ })+ proxyHost!: string | null;++ @ApiProperty({+ description: 'Whether the stored proxy URL embeds username/password credentials',+ example: false,+ })+ hasCredentials!: boolean;+}++export class UpdateSessionProxyDto {+ @ApiPropertyOptional({+ description:+ 'Per-session egress proxy URL (http/https/socks4/socks5; credentialed form allowed). Send ' ++ '`null` to clear the proxy. Must be a real, reachable proxy — an unreachable value blocks the ' ++ 'WhatsApp WebSocket and session start times out (~30s).',+ nullable: true,+ example: 'http://user:[email protected]:8080',+ })+ @IsOptional()+ @IsString()+ @MaxLength(255)+ @IsUrl(+ {+ protocols: ['http', 'https', 'socks4', 'socks5'],+ require_protocol: true,+ require_tld: false,+ allow_underscores: true,+ },+ { message: 'proxyUrl must be a valid http(s)/socks4/socks5 URL' },+ )+ proxyUrl?: string | null;++ @ApiPropertyOptional({+ description: 'Proxy protocol. Defaults to `http` when `proxyUrl` is set and this is omitted.',+ enum: ['http', 'https', 'socks4', 'socks5'],+ nullable: true,+ example: 'http',+ })+ @IsOptional()+ @IsIn(['http', 'https', 'socks4', 'socks5'])+ proxyType?: SessionProxyType | null;+}++/** Project stored proxy columns onto a safe response — never returns credentials. */+export function projectSessionProxy(session: Pick<Session, 'proxyUrl' | 'proxyType'>): SessionProxyResponseDto {+ if (!session.proxyUrl) {+ return { enabled: false, proxyType: null, proxyHost: null, hasCredentials: false };+ }++ try {+ const parsed = new URL(session.proxyUrl);+ return {+ enabled: true,+ proxyType: session.proxyType,+ proxyHost: parsed.host,+ hasCredentials: !!(parsed.username || parsed.password),+ };+ } catch {+ return {+ enabled: true,+ proxyType: session.proxyType,+ proxyHost: null,+ hasCredentials: false,+ };+ }+}diff --git a/src/modules/session/dto/session-response.dto.ts b/src/modules/session/dto/session-response.dto.tsindex 83138fa39..441a6cc78 100644--- a/src/modules/session/dto/session-response.dto.ts+++ b/src/modules/session/dto/session-response.dto.ts@@ -1,6 +1,7 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';import type { Session } from '../entities/session.entity';import { SessionStatus } from '../entities/session.entity';+import { projectSessionProxy } from './session-proxy.dto';export class AccountRestrictionDto {@ApiProperty({@@ -94,6 +95,28 @@ export class SessionResponseDto {})engineLoaded!: boolean;+ @ApiProperty({+ description: 'Whether a per-session egress proxy is configured',+ example: false,+ })+ proxyEnabled!: boolean;++ @ApiPropertyOptional({+ enum: ['http', 'https', 'socks4', 'socks5'],+ description: 'Configured proxy protocol when `proxyEnabled` is true',+ nullable: true,+ example: 'http',+ })+ proxyType!: 'http' | 'https' | 'socks4' | 'socks5' | null;++ @ApiPropertyOptional({+ type: String,+ description: 'Proxy host:port parsed from the stored URL — credentials are never returned',+ nullable: true,+ example: 'proxy.example.com:8080',+ })+ proxyHost!: string | null;+/*** Map a Session entity to the public response shape, stripping sensitive* engine config fields (`config`, `proxyUrl`, `proxyType`) that must not@@ -105,6 +128,7 @@ export class SessionResponseDto {* any future caller) and the dashboard would then offer Start to a running session.*/static fromEntity(session: Session, engineLoaded: boolean): SessionResponseDto {+ const proxy = projectSessionProxy(session);return {id: session.id,name: session.name,@@ -126,6 +150,9 @@ export class SessionResponseDto {}: null,engineLoaded,+ proxyEnabled: proxy.enabled,+ proxyType: proxy.proxyType,+ proxyHost: proxy.proxyHost,};}}diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.tsindex cf3f6a995..a392f9889 100644--- a/src/modules/session/session.controller.spec.ts+++ b/src/modules/session/session.controller.spec.ts@@ -51,7 +51,6 @@ describe('SessionController — create() response contract', () => {expect(result).not.toHaveProperty('config');expect(result).not.toHaveProperty('proxyUrl');- expect(result).not.toHaveProperty('proxyType');expect(result).not.toHaveProperty('lastActiveAt');});@@ -71,6 +70,9 @@ describe('SessionController — create() response contract', () => {lastError: null,restriction: null,engineLoaded: false,+ proxyEnabled: true,+ proxyType: 'http',+ proxyHost: 'proxy.internal:8080',});});@@ -342,3 +344,54 @@ describe('SessionController — pinChat', () => {expect(sessionService.pinChat).toHaveBeenCalledWith('sess-uuid-1', '[email protected]', false);});});++describe('SessionController — proxy() response contract', () => {+ const proxyProjection = {+ enabled: true,+ proxyType: 'http' as const,+ proxyHost: 'proxy.internal:8080',+ hasCredentials: true,+ };++ let sessionService: { getProxy: jest.Mock; updateProxy: jest.Mock };+ let auditService: { logInfo: jest.Mock };+ let controller: SessionController;++ beforeEach(() => {+ sessionService = {+ getProxy: jest.fn().mockResolvedValue(proxyProjection),+ updateProxy: jest.fn().mockResolvedValue(proxyProjection),+ };+ auditService = { logInfo: jest.fn().mockResolvedValue(undefined) };+ controller = new SessionControllerClass(+ sessionService as unknown as SessionService,+ auditService as unknown as AuditService,+ );+ });++ it('getProxy returns the masked projection without proxyUrl', async () => {+ const result = await controller.getProxy('sess-uuid-1');++ expect(result).toEqual(proxyProjection);+ expect(result).not.toHaveProperty('proxyUrl');+ });++ it('updateProxy audits the masked state, not the request body', async () => {+ await controller.updateProxy('sess-uuid-1', {+ proxyUrl: 'http://user:[email protected]:8080',+ proxyType: 'http',+ });++ expect(auditService.logInfo).toHaveBeenCalledWith(+ AuditAction.SESSION_CONFIG_UPDATED,+ expect.objectContaining({+ sessionId: 'sess-uuid-1',+ metadata: {+ proxyEnabled: true,+ proxyType: 'http',+ proxyHost: 'proxy.internal:8080',+ },+ }),+ );+ });+});diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 507b7f7c9..6916ab686 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -18,6 +18,8 @@ import {CreateSessionDto,SessionConfigResponseDto,UpdateSessionConfigDto,+ SessionProxyResponseDto,+ UpdateSessionProxyDto,SessionResponseDto,QRCodeResponseDto,MarkChatReadDto,@@ -166,6 +168,47 @@ export class SessionController {return config;}+ @Get(':sessionId/proxy')+ @ApiOperation({ summary: 'Get the per-session egress proxy configuration (credentials masked)' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({+ status: 200,+ description: 'Effective proxy configuration',+ type: SessionProxyResponseDto,+ })+ @ApiResponse({ status: 404, description: 'Session not found' })+ async getProxy(@Param('sessionId', ParseUUIDPipe) id: string): Promise<SessionProxyResponseDto> {+ return this.sessionService.getProxy(id);+ }++ @Patch(':sessionId/proxy')+ @RequireRole(ApiKeyRole.OPERATOR)+ @ApiOperation({+ summary: 'Update the per-session egress proxy configuration',+ description:+ 'Sets or clears the proxy URL and type. Credentials in `proxyUrl` are stored but never ' ++ 'returned by GET. No restart is performed — changes apply on the next session start.',+ })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiResponse({+ status: 200,+ description: 'Updated proxy configuration',+ type: SessionProxyResponseDto,+ })+ @ApiResponse({ status: 400, description: 'Invalid proxyUrl or proxyType' })+ @ApiResponse({ status: 404, description: 'Session not found' })+ async updateProxy(+ @Param('sessionId', ParseUUIDPipe) id: string,+ @Body() dto: UpdateSessionProxyDto,+ ): Promise<SessionProxyResponseDto> {+ const proxy = await this.sessionService.updateProxy(id, dto);+ await this.auditService.logInfo(AuditAction.SESSION_CONFIG_UPDATED, {+ sessionId: id,+ metadata: { proxyEnabled: proxy.enabled, proxyType: proxy.proxyType, proxyHost: proxy.proxyHost },+ });+ return proxy;+ }+@Delete(':sessionId')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.NO_CONTENT)diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 3162a1a45..0c2af5ec5 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -6338,4 +6338,70 @@ describe('SessionService', () => {});});});++ describe('session proxy', () => {+ beforeEach(() => {+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ });++ it('reports disabled when no proxy is configured', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());++ await expect(service.getProxy('sess-uuid-1')).resolves.toEqual({+ enabled: false,+ proxyType: null,+ proxyHost: null,+ hasCredentials: false,+ });+ });++ it('masks credentials and returns host:port only', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(+ createMockSession({+ proxyUrl: 'http://user:[email protected]:8080',+ proxyType: 'http',+ }),+ );++ await expect(service.getProxy('sess-uuid-1')).resolves.toEqual({+ enabled: true,+ proxyType: 'http',+ proxyHost: 'proxy.internal:8080',+ hasCredentials: true,+ });+ });++ it('persists a new proxy URL and defaults proxyType to http', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());++ const result = await service.updateProxy('sess-uuid-1', {+ proxyUrl: 'http://proxy.internal:8080',+ });++ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', {+ proxyUrl: 'http://proxy.internal:8080',+ proxyType: 'http',+ });+ expect(result).toEqual({+ enabled: true,+ proxyType: 'http',+ proxyHost: 'proxy.internal:8080',+ hasCredentials: false,+ });+ });++ it('clears both columns when proxyUrl is null', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(+ createMockSession({ proxyUrl: 'http://proxy.internal:8080', proxyType: 'http' }),+ );++ const result = await service.updateProxy('sess-uuid-1', { proxyUrl: null });++ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', {+ proxyUrl: null,+ proxyType: null,+ });+ expect(result.enabled).toBe(false);+ });+ });});diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex a4b3290c4..bbdd0dc42 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -16,7 +16,14 @@ import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntityimport { setTimeout } from 'node:timers/promises';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { Session, SessionStatus } from './entities/session.entity';-import { CreateSessionDto, SessionConfigResponseDto, UpdateSessionConfigDto } from './dto';+import {+ CreateSessionDto,+ SessionConfigResponseDto,+ UpdateSessionConfigDto,+ SessionProxyResponseDto,+ UpdateSessionProxyDto,+ projectSessionProxy,+} from './dto';import { EngineRegistry } from '../../engine/engine-registry.service';import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';import { SessionErrorStore } from './session-error-store.service';@@ -390,6 +397,39 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn this.projectConfig(config);}+ async getProxy(id: string): Promise<SessionProxyResponseDto> {+ const session = await this.findOne(id);+ return projectSessionProxy(session);+ }++ /**+ * Persist per-session proxy settings. No engine restart — proxy is read at initializeEngine() on+ * the next start(), matching the reconnect settings on PATCH /config.+ */+ async updateProxy(id: string, dto: UpdateSessionProxyDto): Promise<SessionProxyResponseDto> {+ const session = await this.findOne(id);++ if (dto.proxyUrl === null) {+ await this.sessionRepository.update(id, { proxyUrl: null, proxyType: null });+ return projectSessionProxy({ proxyUrl: null, proxyType: null });+ }++ const nextUrl = dto.proxyUrl !== undefined ? dto.proxyUrl : session.proxyUrl;+ let nextType: Session['proxyType'] = dto.proxyType !== undefined ? dto.proxyType : session.proxyType;++ if (nextUrl) {+ if (!nextType) nextType = 'http';+ } else {+ nextType = null;+ }++ if (dto.proxyUrl !== undefined || dto.proxyType !== undefined) {+ await this.sessionRepository.update(id, { proxyUrl: nextUrl ?? null, proxyType: nextType });+ }++ return projectSessionProxy({ proxyUrl: nextUrl ?? null, proxyType: nextType });+ }+/** Record removal + engine retirement + credential purge: owned by the lifecycle service. */async delete(id: string): Promise<void> {// Set the tearing-down mark SYNCHRONOUSLY, before the ownership fence's awaited query. The