Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sessions): address proxy API review feedback
Victor Andradeb807a038309d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 47379aa3d..51e78566c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [Unreleased]++### Added++- `GET` and `PATCH /api/sessions/{sessionId}/proxy` — read and update per-session egress proxy+ settings (masked; credentials never returned). Changes apply on the next session start. Closes+ [#1474](https://github.com/rmyndharis/OpenWA/issues/1474).+## [0.23.3] - 2026-08-24### Addeddiff --git a/dashboard/src/hooks/useSessionCreateForm.ts b/dashboard/src/hooks/useSessionCreateForm.tsindex 9137d2cdd..585011a73 100644--- a/dashboard/src/hooks/useSessionCreateForm.ts+++ b/dashboard/src/hooks/useSessionCreateForm.ts@@ -52,9 +52,7 @@ export function useSessionCreateForm({ onCreated, onFailed }: UseSessionCreateFosetCreating(true);const newSession = await sessionApi.create(newSessionName,- useProxy && proxyUrl.trim()- ? { proxyUrl: proxyUrl.trim(), proxyType }- : undefined,+ useProxy && proxyUrl.trim() ? { proxyUrl: proxyUrl.trim(), proxyType } : undefined,);setNewSessionName('');resetProxyFields();diff --git a/dashboard/src/pages/Sessions.test.ts b/dashboard/src/pages/Sessions.test.tsindex 1b74cd86f..b34a7a574 100644--- a/dashboard/src/pages/Sessions.test.ts+++ b/dashboard/src/pages/Sessions.test.ts@@ -27,9 +27,6 @@ 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',};@@ -44,9 +41,6 @@ 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',};@@ -126,15 +120,6 @@ function installFetchStub(): void {if (method === 'POST' && path === '/api/sessions') {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}`,@@ -142,9 +127,6 @@ function installFetchStub(): void {status: 'created',createdAt: '2026-01-01T00:00:00.000Z',updatedAt: '2026-01-01T00:00:00.000Z',- proxyEnabled,- proxyType,- proxyHost,}),);}@@ -176,19 +158,18 @@ function installFetchStub(): void {if (proxyMatch) {if (method === 'GET') return Promise.resolve(jsonResponse({ ...sessionProxy }));if (method === 'PATCH') {- const payload = body as { proxyUrl?: string | null; proxyType?: string | null } | undefined;+ const payload = body as { proxyUrl?: 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);+ const scheme = parsed.protocol.replace(':', '');sessionProxy = {enabled: true,- proxyType: payload.proxyType ?? 'http',+ proxyType: scheme,proxyHost: parsed.host,hasCredentials: !!(parsed.username || parsed.password),};- } else if (payload?.proxyType && sessionProxy.enabled) {- sessionProxy = { ...sessionProxy, proxyType: payload.proxyType };}return Promise.resolve(jsonResponse({ ...sessionProxy }));}@@ -292,18 +273,6 @@ test('the session list renders, and action buttons gate on engineLoaded rather twithin(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 () => {const { screen, fireEvent, waitFor, within } = rtl;resetFetchCalls();@@ -363,7 +332,6 @@ test('saving proxy settings issues PATCH /api/sessions/:id/proxy', async () => {assert.ok(call, 'expected a PATCH to /proxy');assert.deepEqual(call!.body, {proxyUrl: 'http://user:[email protected]:8080',- proxyType: 'http',});});});diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex 2dcd07987..5aedafac5 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -34,7 +34,13 @@ import {replaceSession,} from '../utils/sessionActions';import { invalidateSessionQueries, reconcileSessionCache } from '../utils/sessionMutation';-import { canCreateSession, filterSessions, isValidPairingPhone, isValidProxyUrl, 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';@@ -94,7 +100,6 @@ export function Sessions() {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[]> => {@@ -162,14 +167,14 @@ export function Sessions() {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.- setSessions(current => [...current, newSession]);- void invalidateSessionQueries(queryClient, queryKeys.sessions);- },- onFailed: msg => setError(msg),- });+ 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.+ setSessions(current => [...current, newSession]);+ void invalidateSessionQueries(queryClient, queryKeys.sessions);+ },+ onFailed: msg => setError(msg),+ });// Reconcile the LOCAL view with an authoritative Session response. The previous handlers discarded// the response and fabricated `{ status: 'disconnected' }`, losing phone:null, timestamps, and other@@ -348,7 +353,6 @@ export function Sessions() {setProxyInfo(null);setProxyEnabled(false);setProxyUrl('');- setProxyType('http');setProxyUrlError(null);if (!proxySessionId) return;let cancelled = false;@@ -359,7 +363,6 @@ export function Sessions() {if (cancelled) return;setProxyInfo(data);setProxyEnabled(data.enabled);- setProxyType(data.proxyType ?? 'http');}).catch(err => {if (!cancelled) {@@ -390,35 +393,20 @@ export function Sessions() {setProxyUrlError(null);setProxySaving(true);try {- let updatedProxy;if (!proxyEnabled) {- updatedProxy = await sessionApi.updateProxy(proxySession.id, { proxyUrl: null });+ await sessionApi.updateProxy(proxySession.id, { proxyUrl: null });} else if (proxyUrl.trim()) {- updatedProxy = await sessionApi.updateProxy(proxySession.id, { proxyUrl: proxyUrl.trim(), proxyType });+ await sessionApi.updateProxy(proxySession.id, { proxyUrl: proxyUrl.trim() });} else if (proxyInfo?.enabled) {- updatedProxy = await sessionApi.updateProxy(proxySession.id, { proxyType });+ setProxySession(null);+ return;} 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'),- );+ toast.error(t('sessions.proxy.saveError'), err instanceof Error ? err.message : t('common.unknownError'));} finally {setProxySaving(false);}@@ -495,8 +483,7 @@ export function Sessions() {// 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())));+ useProxy && (!createProxyUrl.trim() || (createProxyUrl.trim() && !isValidProxyUrl(createProxyUrl.trim())));if (loading) {return (@@ -578,11 +565,7 @@ export function Sessions() {<buttonclassName="btn-primary"onClick={handleCreate}- disabled={- creating ||- !canCreateSession(newSessionName, existingSessionNames) ||- createProxyInvalid- }+ disabled={creating || !canCreateSession(newSessionName, existingSessionNames) || createProxyInvalid}>{creating ? <Loader2 className="animate-spin" size={16} /> : t('common.create')}</button>@@ -868,7 +851,11 @@ export function Sessions() {{t('common.cancel')}</button>{canWrite && (- <button className="btn-primary" onClick={() => void handleProxySave()} disabled={proxySaving || proxyLoading}>+ <button+ className="btn-primary"+ onClick={() => void handleProxySave()}+ disabled={proxySaving || proxyLoading}+ >{proxySaving ? <Loader2 className="animate-spin" size={16} /> : t('common.save')}</button>)}@@ -935,16 +922,6 @@ export function Sessions() {/>{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>@@ -1059,18 +1036,6 @@ 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" />diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 415c494e1..ae114e46c 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -83,11 +83,6 @@ 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. */@@ -791,10 +786,7 @@ export const sessionApi = {body: JSON.stringify(patch),}),getProxy: (id: string) => request<SessionProxy>(`/sessions/${id}/proxy`),- updateProxy: (- id: string,- patch: { proxyUrl?: string | null; proxyType?: SessionProxyType | null },- ) =>+ updateProxy: (id: string, patch: { proxyUrl?: string | null }) =>request<SessionProxy>(`/sessions/${id}/proxy`, {method: 'PATCH',body: JSON.stringify(patch),diff --git a/docs/04-security-design.md b/docs/04-security-design.mdold mode 100755new mode 100644index 4dacc7265..79e5aa088--- a/docs/04-security-design.md+++ b/docs/04-security-design.md@@ -171,14 +171,14 @@ OpenWA serves plain HTTP on its port; terminate **TLS at your reverse proxy / lo> **There is currently no application-level encryption at rest.** API keys are stored **hashed** (one-way), but other sensitive values are stored as plaintext in the database / on disk and are protected by filesystem and database permissions, not by encryption. Encryption at rest for these fields is a roadmap item, not a shipped feature — do not assume it.-| Data | At rest | How it is protected |-| ----------------------------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |-| API keys | **Hashed** — SHA-256 with an optional `API_KEY_PEPPER` HMAC; never reversible | A database leak alone cannot recover the keys; with a pepper set, hashes can't be precomputed offline. See §4.2. |-| Session auth state (WhatsApp credentials) | Plaintext on disk (the engine's auth store under the data volume) | Filesystem permissions on the data volume — keep it private. |-| Webhook secrets | Plaintext — `webhooks.secret` (`varchar`) | Database access control; never returned by the webhook read DTOs (write-only) and omitted from `GET /api/infra/export-data` webhook rows. |-| Proxy credentials | Plaintext — `sessions.proxyUrl` may embed `user:pass` | Database access control; never returned by the session read DTOs — only masked `proxyHost` and `hasCredentials` on `GET/PATCH /proxy`, and `proxyEnabled`/`proxyType`/`proxyHost` on session list/get. |-| Generated config (`data/.env.generated`) | Plaintext file, written `0600` | Owner-only file permissions. |-| Message content | Plaintext in the `messages` table | Database access control. |+| Data | At rest | How it is protected |+| ----------------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| API keys | **Hashed** — SHA-256 with an optional `API_KEY_PEPPER` HMAC; never reversible | A database leak alone cannot recover the keys; with a pepper set, hashes can't be precomputed offline. See §4.2. |+| Session auth state (WhatsApp credentials) | Plaintext on disk (the engine's auth store under the data volume) | Filesystem permissions on the data volume — keep it private. |+| Webhook secrets | Plaintext — `webhooks.secret` (`varchar`) | Database access control; never returned by the webhook read DTOs (write-only) and omitted from `GET /api/infra/export-data` webhook rows. |+| Proxy credentials | Plaintext — `sessions.proxyUrl` may embed `user:pass` | Database access control; never returned by the session read DTOs — only masked `proxyHost`, `proxyType` (derived from the URL scheme), and `hasCredentials` on `GET/PATCH /proxy`. |+| Generated config (`data/.env.generated`) | Plaintext file, written `0600` | Owner-only file permissions. |+| Message content | Plaintext in the `messages` table | Database access control. |**Hardening you can apply today:** set `API_KEY_PEPPER`; restrict the data volume and database to the app's user; and encrypt at the infrastructure layer (LUKS / cloud-provider encrypted volumes / an encrypted managed Postgres) rather than relying on application-level field encryption, which is not implemented.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdold mode 100755new mode 100644index ce68d455d..3a8a6d41a--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -191,7 +191,7 @@ Every path below is prefixed with `/api`. Unless marked **public**, send `X-API-### 6.4.1 Sessions-Base path `/api/sessions`. All routes that return a session return data shaped by `SessionResponseDto.fromEntity` (via `transformSession`), which **strips** `config` and the raw credential-bearing `proxyUrl` column, renames the entity field `lastActiveAt` to `lastActive`, and **projects** masked proxy fields (`proxyEnabled`, `proxyType`, `proxyHost`). Session `status` wire values are lowercase: `created | initializing | qr_ready | authenticating | ready | disconnected | action_required | failed`.+Base path `/api/sessions`. All routes that return a session return data shaped by `SessionResponseDto.fromEntity` (via `transformSession`), which **strips** `config` and the raw credential-bearing `proxyUrl` / `proxyType` columns and renames the entity field `lastActiveAt` to `lastActive`. Masked proxy details are available from `GET/PATCH /api/sessions/:sessionId/proxy` only. Session `status` wire values are lowercase: `created | initializing | qr_ready | authenticating | ready | disconnected | action_required | failed`.#### GET /api/sessions@@ -222,15 +222,12 @@ List all sessions, scoped to the API key's `allowedSessions`, ordered `createdAt"updatedAt": "2026-06-25T09:01:55.000Z","lastError": null,"restriction": null,- "engineLoaded": true,- "proxyEnabled": false,- "proxyType": null,- "proxyHost": null+ "engineLoaded": true}]```-`lastError` is non-null only when `status` is `failed` or `action_required`; any other status clears it. `config` and the raw `proxyUrl` column are not present (stripped by `fromEntity`); masked proxy fields (`proxyEnabled`, `proxyType`, `proxyHost`) are included instead.+`lastError` is non-null only when `status` is `failed` or `action_required`; any other status clears it. `config` and the raw `proxyUrl` / `proxyType` columns are not present (stripped by `fromEntity`).`restriction` reports a limit **WhatsApp itself** has placed on the account, as opposed to `lastError`, which describes a fault on the gateway's side of the link. It is `null` when there is none, and otherwise `{ kind, code, expiresAt }`:@@ -272,10 +269,7 @@ Get a single session by ID."createdAt": "2026-06-20T11:30:00.000Z","updatedAt": "2026-06-25T09:01:55.000Z","lastError": null,- "engineLoaded": true,- "proxyEnabled": true,- "proxyType": "http",- "proxyHost": "proxy.example.com:8080"+ "engineLoaded": true}```@@ -341,7 +335,7 @@ and therefore apply on the next start, leaving a reconnect sequence already in f#### GET /api/sessions/:sessionId/proxy-Read a session's masked proxy configuration. Credentials embedded in the stored `proxyUrl` are **never** returned — only the parsed `proxyHost:port` and a `hasCredentials` flag.+Read a session's masked proxy configuration. Credentials embedded in the stored `proxyUrl` are **never** returned — only the parsed `proxyHost:port`, a `proxyType` derived from the URL scheme, and a `hasCredentials` flag.**Auth:** API key · **Scope:** session-scoped@@ -380,18 +374,17 @@ Update per-session proxy settings. No restart is required or performed — chang**Request body** — `UpdateSessionProxyDto` (any subset; each key also accepts `null`)-| Field | Type | Constraints | Description |-| ----------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `proxyUrl` | string | `@IsOptional`; `@IsString`; max 255; `@IsUrl` (protocols `http`/`https`/`socks4`/`socks5`, `require_protocol`, `require_tld:false`, `allow_underscores`) | Per-session proxy egress; credentialed `http://user:pass@host` and single-label hosts allowed. Send `null` to clear. ⚠ **Must be a real, reachable proxy** when set — an unreachable value blocks the WhatsApp WebSocket on start (~30s timeout). |-| `proxyType` | `http` \| `https` \| `socks4` \| `socks5` | `@IsOptional`; `@IsIn([...])` | Proxy protocol; defaults to `http` when `proxyUrl` is set and this is omitted. |+| Field | Type | Constraints | Description |+| ---------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `proxyUrl` | string | `@IsOptional`; `@IsString`; max 255; `@IsUrl` (protocols `http`/`https`/`socks4`/`socks5`, `require_protocol`, `require_tld:false`, `allow_underscores`) | Per-session proxy egress; credentialed `http://user:pass@host` and single-label hosts allowed. Send `null` to clear. ⚠ **Must be a real, reachable proxy** when set — an unreachable value blocks the WhatsApp WebSocket on start (~30s timeout). |```json-{ "proxyUrl": "http://user:[email protected]:8080", "proxyType": "http" }+{ "proxyUrl": "http://user:[email protected]:8080" }```**Response** `200` — the resulting `SessionProxyResponseDto` (same shape as the GET above).-**Errors:** `400` validation (bad `proxyUrl`/`proxyType`) · `401` missing/invalid key, or key not scoped to this session · `403` key lacks OPERATOR role · `404` session not found+**Errors:** `400` validation (bad `proxyUrl`) · `401` missing/invalid key, or key not scoped to this session · `403` key lacks OPERATOR role · `404` session not found#### GET /api/sessions/:sessionId/qrdiff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdold mode 100755new mode 100644index b14e76c62..f2f0f5749--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -135,7 +135,7 @@ Update per-session proxy settings (OPERATOR). No restart — changes apply on thcurl -X PATCH "$BASE/api/sessions/$SESSION_ID/proxy" \-H "X-API-Key: $API_KEY" \-H "Content-Type: application/json" \- -d '{ "proxyUrl": "http://user:[email protected]:8080", "proxyType": "http" }'+ -d '{ "proxyUrl": "http://user:[email protected]:8080" }'```#### POST /api/sessions/:sessionId/startdiff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdold mode 100755new mode 100644index 518bcdfe0..ebeaf130e--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -28,7 +28,7 @@ All five SDKs expose the same fluent surface:| Resource | Methods || ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `sessions` | list, get, getConfig, updateConfig, getProxy, updateProxy, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, setOnlinePresence, stats |+| `sessions` | list, get, getConfig, updateConfig, getProxy, updateProxy, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, setOnlinePresence, stats || `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, votePoll, sendBulk, batchStatus, cancelBatch || `contacts` | list, get, check, profilePicture, profilePictures, phone, upsert, delete, block, unblock, listBlocked || `groups` | list, get, create, joinInfo, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, getGroupSettings, updateGroupSettings, leave, getPicture, setPicture, deletePicture, inviteCode, revokeInviteCode, getMembershipRequests, approveMembershipRequests, rejectMembershipRequests |diff --git a/openapi.json b/openapi.jsonindex 0c6ac4ff7..1a2c398ce 100644--- a/openapi.json+++ b/openapi.json@@ -562,6 +562,88 @@]}},+ "/api/sessions/{sessionId}/proxy": {+ "get": {+ "operationId": "SessionController_getProxy",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Effective proxy configuration",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SessionProxyResponseDto"+ }+ }+ }+ },+ "404": {+ "description": "Session not found"+ }+ },+ "summary": "Get the per-session egress proxy configuration (credentials masked)",+ "tags": [+ "sessions"+ ]+ },+ "patch": {+ "description": "Sets or clears the proxy URL. Credentials in `proxyUrl` are stored but never returned by GET. No restart is performed — changes apply on the next session start.",+ "operationId": "SessionController_updateProxy",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateSessionProxyDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Updated proxy configuration",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SessionProxyResponseDto"+ }+ }+ }+ },+ "400": {+ "description": "Invalid proxyUrl"+ },+ "404": {+ "description": "Session not found"+ }+ },+ "summary": "Update the per-session egress proxy configuration",+ "tags": [+ "sessions"+ ]+ }+ },"/api/sessions/{sessionId}/start": {"post": {"operationId": "SessionController_start",@@ -10120,6 +10202,56 @@}}},+ "SessionProxyResponseDto": {+ "type": "object",+ "properties": {+ "enabled": {+ "type": "boolean",+ "description": "Whether a proxy URL is configured for this session",+ "example": true+ },+ "proxyType": {+ "type": "string",+ "description": "Proxy protocol derived from the stored URL scheme",+ "enum": [+ "http",+ "https",+ "socks4",+ "socks5"+ ],+ "nullable": true,+ "example": "http"+ },+ "proxyHost": {+ "type": "object",+ "description": "Proxy host:port parsed from the stored URL — credentials are never returned",+ "nullable": true,+ "example": "proxy.example.com:8080"+ },+ "hasCredentials": {+ "type": "boolean",+ "description": "Whether the stored proxy URL embeds username/password credentials",+ "example": false+ }+ },+ "required": [+ "enabled",+ "proxyType",+ "proxyHost",+ "hasCredentials"+ ]+ },+ "UpdateSessionProxyDto": {+ "type": "object",+ "properties": {+ "proxyUrl": {+ "type": "object",+ "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"+ }+ }+ },"QRCodeResponseDto": {"type": "object","properties": {diff --git a/scripts/check-contract-shapes.mjs b/scripts/check-contract-shapes.mjsindex d763da72f..bd7d68661 100644--- a/scripts/check-contract-shapes.mjs+++ b/scripts/check-contract-shapes.mjs@@ -119,6 +119,7 @@ const MAPPINGS = {SendVideoStatusRequest: 'SendVideoStatusDto',SendVoiceStatusRequest: 'SendVoiceStatusDto',SessionResponse: 'SessionResponseDto',+ SessionProxy: 'SessionProxyResponseDto',SetGroupPictureRequest: 'SetGroupPictureDto',SetOwnPresenceRequest: 'SetOwnPresenceDto',SetProfileNameRequest: 'SetProfileNameDto',@@ -129,6 +130,7 @@ const MAPPINGS = {TransferChannelOwnershipRequest: 'TransferChannelOwnershipDto',UnpinMessageRequest: 'UnpinMessageDto',UpdateSessionConfigRequest: 'UpdateSessionConfigDto',+ UpdateSessionProxyRequest: 'UpdateSessionProxyDto',UpsertContactRequest: 'UpsertContactDto',UpsertLabelRequest: 'UpsertLabelDto',VotePollRequest: 'VotePollDto',@@ -155,6 +157,7 @@ const MAPPINGS = {SearchHit: 'SearchHitDto',Session: 'SessionResponseDto',SessionConfig: 'SessionConfigResponseDto',+ SessionProxy: 'SessionProxyResponseDto',Webhook: 'WebhookResponseDto',},};@@ -166,11 +169,11 @@ const MAPPINGS = {* these floors as pairs are added makes the shrink loud.*/const MINIMUM_MAPPED = {- 'sdk/javascript/src/types.ts': 80,- 'dashboard/src/services/api.ts': 20,- 'sdk/python/openwa/types.py': 75,- 'sdk/go': 76,- 'sdk/java': 80,+ 'sdk/javascript/src/types.ts': 82,+ 'dashboard/src/services/api.ts': 21,+ 'sdk/python/openwa/types.py': 77,+ 'sdk/go': 78,+ 'sdk/java': 82,};/** Known drift, deliberately not gated yet — each line is a to-adjudicate follow-up. */@@ -264,6 +267,7 @@ const PYTHON_MAPPING = {SendVideoStatusRequest: 'SendVideoStatusDto',SendVoiceStatusRequest: 'SendVoiceStatusDto',SessionResponse: 'SessionResponseDto',+ SessionProxy: 'SessionProxyResponseDto',SetGroupPictureRequest: 'SetGroupPictureDto',SetOwnPresenceRequest: 'SetOwnPresenceDto',SetProfileNameRequest: 'SetProfileNameDto',@@ -274,6 +278,7 @@ const PYTHON_MAPPING = {TransferChannelOwnershipRequest: 'TransferChannelOwnershipDto',UnpinMessageRequest: 'UnpinMessageDto',UpdateSessionConfigRequest: 'UpdateSessionConfigDto',+ UpdateSessionProxyRequest: 'UpdateSessionProxyDto',UpdateWebhookRequest: 'UpdateWebhookDto',UpsertContactRequest: 'UpsertContactDto',UpsertLabelRequest: 'UpsertLabelDto',@@ -344,6 +349,7 @@ const GO_MAPPING = {SendVideoStatusRequest: 'SendVideoStatusDto',SendVoiceStatusRequest: 'SendVoiceStatusDto',SessionResponse: 'SessionResponseDto',+ SessionProxy: 'SessionProxyResponseDto',SetGroupPictureRequest: 'SetGroupPictureDto',SetOwnPresenceRequest: 'SetOwnPresenceDto',SetProfileNameRequest: 'SetProfileNameDto',@@ -354,6 +360,7 @@ const GO_MAPPING = {TransferChannelOwnershipRequest: 'TransferChannelOwnershipDto',UnpinMessageRequest: 'UnpinMessageDto',UpdateSessionConfigRequest: 'UpdateSessionConfigDto',+ UpdateSessionProxyRequest: 'UpdateSessionProxyDto',UpdateWebhookRequest: 'UpdateWebhookDto',UpsertContactRequest: 'UpsertContactDto',UpsertLabelRequest: 'UpsertLabelDto',@@ -428,6 +435,7 @@ const JAVA_MAPPING = {SendVideoStatusRequest: 'SendVideoStatusDto',SendVoiceStatusRequest: 'SendVoiceStatusDto',SessionResponse: 'SessionResponseDto',+ SessionProxy: 'SessionProxyResponseDto',SetGroupPictureRequest: 'SetGroupPictureDto',SetOwnPresenceRequest: 'SetOwnPresenceDto',SetProfileNameRequest: 'SetProfileNameDto',@@ -438,6 +446,7 @@ const JAVA_MAPPING = {TransferChannelOwnershipRequest: 'TransferChannelOwnershipDto',UnpinMessageRequest: 'UnpinMessageDto',UpdateSessionConfigRequest: 'UpdateSessionConfigDto',+ UpdateSessionProxyRequest: 'UpdateSessionProxyDto',UpdateWebhookRequest: 'UpdateWebhookDto',UpsertContactRequest: 'UpsertContactDto',UpsertLabelRequest: 'UpsertLabelDto',diff --git a/sdk/README.md b/sdk/README.mdold mode 100755new mode 100644index a8700a462..8c4d8e988--- a/sdk/README.md+++ b/sdk/README.md@@ -24,7 +24,7 @@ All five SDKs expose the same fluent resource surface:| Resource | Methods || ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `sessions` | list, get, getConfig, updateConfig, getProxy, updateProxy, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, setOnlinePresence, stats |+| `sessions` | list, get, getConfig, updateConfig, getProxy, updateProxy, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, setOnlinePresence, stats || `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, votePoll, sendBulk, batchStatus, cancelBatch || `contacts` | list, get, check, profilePicture, profilePictures, phone, upsert, delete, block, unblock, listBlocked || `groups` | list, get, create, joinGroup, joinInfo, add/remove/promote/demoteParticipants, setSubject, setDescription, get/updateGroupSettings, leave, getPicture, setPicture, deletePicture, inviteCode, revokeInviteCode, getMembershipRequests, approveMembershipRequests, rejectMembershipRequests |diff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.goold mode 100755new mode 100644diff --git a/sdk/go/sessions.go b/sdk/go/sessions.goold mode 100755new mode 100644diff --git a/sdk/go/types_session.go b/sdk/go/types_session.goold mode 100755new mode 100644index d7d1cf43f..695120239--- a/sdk/go/types_session.go+++ b/sdk/go/types_session.go@@ -163,12 +163,6 @@ type SessionResponse struct {// "disconnected" covers both a session mid automatic-reconnect (engine present) and one stopped// with no engine. Nil from a gateway that predates the field.EngineLoaded bool `json:"engineLoaded"`- // ProxyEnabled reports whether a per-session egress proxy is configured.- ProxyEnabled bool `json:"proxyEnabled"`- // ProxyType is the configured proxy protocol when ProxyEnabled is true.- ProxyType *ProxyType `json:"proxyType,omitempty"`- // ProxyHost is host:port parsed from the stored proxy URL -- credentials are never returned.- ProxyHost *string `json:"proxyHost,omitempty"`}// ProxyType is the scheme of a session proxy.@@ -201,8 +195,7 @@ type SessionProxy struct {// UpdateSessionProxyRequest updates per-session proxy settings. Send ProxyURL as a JSON null to// clear. Changes apply on the next start, not to a running engine.type UpdateSessionProxyRequest struct {- ProxyURL *string `json:"proxyUrl,omitempty"`- ProxyType *ProxyType `json:"proxyType,omitempty"`+ ProxyURL *string `json:"proxyUrl,omitempty"`}// QrCodeResponse carries the current QR code for a session awaiting scan.diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionProxy.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionProxy.javaold mode 100755new mode 100644diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionResponse.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionResponse.javaold mode 100755new mode 100644index cc1b389f8..f3475d93e--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionResponse.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionResponse.java@@ -24,13 +24,4 @@ public record SessionResponse(* session mid automatic-reconnect (engine present) and one stopped with no engine. {@code null}* from a gateway older than the field.*/- Boolean engineLoaded,- /**- * Whether a per-session egress proxy is configured. {@code null} from a gateway older than the- * field.- */- Boolean proxyEnabled,- /** Configured proxy protocol when {@code proxyEnabled} is true. */- ProxyType proxyType,- /** Parsed host:port from the stored proxy URL — credentials are never returned. */- String proxyHost) {}+ Boolean engineLoaded) {}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpdateSessionProxyRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpdateSessionProxyRequest.javaold mode 100755new mode 100644index 06cb350c6..bf28877b4--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpdateSessionProxyRequest.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpdateSessionProxyRequest.java@@ -4,7 +4,4 @@ package com.rmyndharis.openwa.model;* Update per-session proxy settings. Send {@code proxyUrl: null} to clear.* Changes apply on the next start, not to a running engine.*/-public record UpdateSessionProxyRequest(- String proxyUrl,- ProxyType proxyType-) {}+public record UpdateSessionProxyRequest(String proxyUrl) {}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SessionsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SessionsResource.javaold mode 100755new mode 100644diff --git a/sdk/javascript/src/resources/sessions.ts b/sdk/javascript/src/resources/sessions.tsold mode 100755new mode 100644diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsold mode 100755new mode 100644index 280402f75..5c2561363--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -80,12 +80,6 @@ export interface SessionResponse {* with no engine. Absent from a gateway that predates the field.*/engineLoaded: boolean;- /** Whether a per-session egress proxy is configured. */- proxyEnabled: boolean;- /** Configured proxy protocol when `proxyEnabled` is true; otherwise `null`. */- proxyType?: 'http' | 'https' | 'socks4' | 'socks5' | null;- /** Parsed host:port from the stored proxy URL — credentials are never returned. */- proxyHost?: string | null;}/**@@ -196,7 +190,6 @@ export interface SessionProxy {/** Update per-session proxy settings. Send `proxyUrl: null` to clear. Applies on the next start. */export interface UpdateSessionProxyRequest {proxyUrl?: string | null;- proxyType?: 'http' | 'https' | 'socks4' | 'socks5' | null;}export interface CreateSessionRequest {diff --git a/sdk/php/src/Resources/SessionsResource.php b/sdk/php/src/Resources/SessionsResource.phpold mode 100755new mode 100644diff --git a/sdk/python/openwa/resources/sessions.py b/sdk/python/openwa/resources/sessions.pyold mode 100755new mode 100644diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyold mode 100755new mode 100644index 9ebea4673..86b6a0ad7--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -233,9 +233,6 @@ class SessionResponse(TypedDict):# session mid automatic-reconnect (engine present) and one stopped with no engine. Absent from a# gateway that predates the field (the TypedDict is total=False).engineLoaded: bool- proxyEnabled: bool- proxyType: NotRequired[ProxyType | None]- proxyHost: NotRequired[str | None]class SessionProxy(TypedDict):@@ -251,7 +248,6 @@ class UpdateSessionProxyRequest(TypedDict, total=False):"""Update per-session proxy settings. Send proxyUrl=null to clear. Applies on the next start."""proxyUrl: str | None- proxyType: ProxyType | Noneclass SessionConfig(TypedDict):diff --git a/src/modules/session/dto/session-proxy.dto.spec.ts b/src/modules/session/dto/session-proxy.dto.spec.tsindex b5bf6cc93..26ae7d0f1 100644--- a/src/modules/session/dto/session-proxy.dto.spec.ts+++ b/src/modules/session/dto/session-proxy.dto.spec.ts@@ -31,14 +31,14 @@ describe('UpdateSessionProxyDto proxyUrl validation', () => {expect(errs({ proxyUrl: null })).toHaveLength(0);});- it('allows an omitted proxyUrl', () => {- expect(errs({ proxyType: 'http' })).toHaveLength(0);+ it('allows an empty body', () => {+ expect(errs({})).toHaveLength(0);});});describe('projectSessionProxy', () => {it('reports disabled when no proxy is stored', () => {- expect(projectSessionProxy({ proxyUrl: null, proxyType: null })).toEqual({+ expect(projectSessionProxy({ proxyUrl: null })).toEqual({enabled: false,proxyType: null,proxyHost: null,@@ -50,7 +50,6 @@ describe('projectSessionProxy', () => {expect(projectSessionProxy({proxyUrl: 'http://user:[email protected]:8080',- proxyType: 'http',}),).toEqual({enabled: true,@@ -60,10 +59,22 @@ describe('projectSessionProxy', () => {});});+ it('derives proxyType from the URL scheme, not the stored column', () => {+ expect(+ projectSessionProxy({+ proxyUrl: 'socks5://proxy.example.com:1080',+ }),+ ).toEqual({+ enabled: true,+ proxyType: 'socks5',+ proxyHost: 'proxy.example.com:1080',+ hasCredentials: false,+ });+ });+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');diff --git a/src/modules/session/dto/session-proxy.dto.ts b/src/modules/session/dto/session-proxy.dto.tsindex 3c96b1c2f..b1f96baea 100644--- a/src/modules/session/dto/session-proxy.dto.ts+++ b/src/modules/session/dto/session-proxy.dto.ts@@ -1,15 +1,26 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';-import { IsString, IsOptional, MaxLength, IsIn, IsUrl } from 'class-validator';+import { IsString, IsOptional, MaxLength, IsUrl } from 'class-validator';import type { Session } from '../entities/session.entity';export type SessionProxyType = 'http' | 'https' | 'socks4' | 'socks5';+const PROTOCOL_TO_PROXY_TYPE: Record<string, SessionProxyType> = {+ 'http:': 'http',+ 'https:': 'https',+ 'socks4:': 'socks4',+ 'socks5:': 'socks5',+};++function proxyTypeFromProtocol(protocol: string): SessionProxyType | null {+ return PROTOCOL_TO_PROXY_TYPE[protocol] ?? null;+}+export class SessionProxyResponseDto {@ApiProperty({ description: 'Whether a proxy URL is configured for this session', example: true })enabled!: boolean;@ApiProperty({- description: 'Configured proxy protocol',+ description: 'Proxy protocol derived from the stored URL scheme',enum: ['http', 'https', 'socks4', 'socks5'],nullable: true,example: 'http',@@ -52,20 +63,10 @@ export class UpdateSessionProxyDto {{ 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 {+export function projectSessionProxy(session: Pick<Session, 'proxyUrl'>): SessionProxyResponseDto {if (!session.proxyUrl) {return { enabled: false, proxyType: null, proxyHost: null, hasCredentials: false };}@@ -74,14 +75,14 @@ export function projectSessionProxy(session: Pick<Session, 'proxyUrl' | 'proxyTyconst parsed = new URL(session.proxyUrl);return {enabled: true,- proxyType: session.proxyType,+ proxyType: proxyTypeFromProtocol(parsed.protocol),proxyHost: parsed.host,hasCredentials: !!(parsed.username || parsed.password),};} catch {return {enabled: true,- proxyType: session.proxyType,+ proxyType: null,proxyHost: null,hasCredentials: false,};diff --git a/src/modules/session/dto/session-response.dto.ts b/src/modules/session/dto/session-response.dto.tsindex 441a6cc78..83138fa39 100644--- a/src/modules/session/dto/session-response.dto.ts+++ b/src/modules/session/dto/session-response.dto.ts@@ -1,7 +1,6 @@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({@@ -95,28 +94,6 @@ 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@@ -128,7 +105,6 @@ 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,@@ -150,9 +126,6 @@ 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 a392f9889..327153793 100644--- a/src/modules/session/session.controller.spec.ts+++ b/src/modules/session/session.controller.spec.ts@@ -70,9 +70,6 @@ describe('SessionController — create() response contract', () => {lastError: null,restriction: null,engineLoaded: false,- proxyEnabled: true,- proxyType: 'http',- proxyHost: 'proxy.internal:8080',});});@@ -379,7 +376,6 @@ describe('SessionController — proxy() response contract', () => {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(diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 6916ab686..6a8c8dc71 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -186,8 +186,8 @@ export class SessionController {@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.',+ 'Sets or clears the proxy URL. 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({@@ -195,7 +195,7 @@ export class SessionController {description: 'Updated proxy configuration',type: SessionProxyResponseDto,})- @ApiResponse({ status: 400, description: 'Invalid proxyUrl or proxyType' })+ @ApiResponse({ status: 400, description: 'Invalid proxyUrl' })@ApiResponse({ status: 404, description: 'Session not found' })async updateProxy(@Param('sessionId', ParseUUIDPipe) id: string,diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 0c2af5ec5..9ab2ca11d 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -6371,7 +6371,7 @@ describe('SessionService', () => {});});- it('persists a new proxy URL and defaults proxyType to http', async () => {+ it('persists a new proxy URL without writing proxyType', async () => {(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());const result = await service.updateProxy('sess-uuid-1', {@@ -6380,7 +6380,7 @@ describe('SessionService', () => {expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', {proxyUrl: 'http://proxy.internal:8080',- proxyType: 'http',+ proxyType: null,});expect(result).toEqual({enabled: true,@@ -6390,6 +6390,20 @@ describe('SessionService', () => {});});+ it('derives socks5 from the URL scheme after update', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());++ const result = await service.updateProxy('sess-uuid-1', {+ proxyUrl: 'socks5://proxy.internal:1080',+ });++ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', {+ proxyUrl: 'socks5://proxy.internal:1080',+ proxyType: null,+ });+ expect(result.proxyType).toBe('socks5');+ });+it('clears both columns when proxyUrl is null', async () => {(repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ proxyUrl: 'http://proxy.internal:8080', proxyType: 'http' }),diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex bbdd0dc42..6bcca6423 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -411,23 +411,15 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatif (dto.proxyUrl === null) {await this.sessionRepository.update(id, { proxyUrl: null, proxyType: null });- return projectSessionProxy({ proxyUrl: null, proxyType: null });+ return projectSessionProxy({ proxyUrl: 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 });+ if (dto.proxyUrl !== undefined) {+ await this.sessionRepository.update(id, { proxyUrl: dto.proxyUrl, proxyType: null });+ return projectSessionProxy({ proxyUrl: dto.proxyUrl });}- return projectSessionProxy({ proxyUrl: nextUrl ?? null, proxyType: nextType });+ return projectSessionProxy(session);}/** Record removal + engine retirement + credential purge: owned by the lifecycle service. */