From f25cecfb4020fd4dc284b62dc928c7652dcdee37 Mon Sep 17 00:00:00 2001 From: Artem K <51025000+artemk1337@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:46:16 +0300 Subject: [PATCH] feat(wireguard): support multiple devices per client (#7143) A WireGuard client had one key pair and one tunnel address, so an operator who gave the same config to a phone and a laptop saw the two fight over the peer endpoint. One client can now own extra devices, up to a per-client limit: each has its own keys and address, shares the client's quota, expiry and switch, and gets its own config, QR code and subscription. Devices become extra peers under the client's email, built by the same core-user map the other paths use, and a device change is applied to the running inbound in place instead of rebuilding it. Nodes advertise a wg-devices capability; the master refuses a device for a node that would ignore it, before storing it and again when pushing the inbound. --- .../content/docs/en/reference/api/clients.mdx | 47 +- docs/public/openapi.json | 518 +++++++++++++++++- frontend/public/openapi.json | 518 +++++++++++++++++- frontend/src/generated/examples.ts | 43 +- frontend/src/generated/schemas.ts | 60 +- frontend/src/generated/types.ts | 14 + frontend/src/generated/zod.ts | 15 + .../src/hooks/useClientWireguardDevices.ts | 56 ++ frontend/src/pages/api-docs/endpoints.ts | 90 +++ .../src/pages/clients/ClientFormModal.tsx | 30 + .../src/pages/clients/ClientInfoModal.tsx | 62 +-- frontend/src/pages/clients/ClientQrModal.tsx | 44 +- .../pages/clients/ClientWireguardDevices.tsx | 190 +++++++ frontend/src/pages/clients/wireguardConfig.ts | 58 ++ frontend/src/schemas/client.ts | 25 + .../client-form-wireguard-devices.test.tsx | 93 ++++ .../test/multi-tunnel-client-config.test.tsx | 4 +- .../src/test/wireguard-client-config.test.ts | 143 ++++- frontend/src/test/wireguard-devices.test.tsx | 102 ++++ .../database/model/model-wireguard-devices.go | 73 +++ internal/database/model/model.go | 138 ++--- .../model/model_wireguard_devices_test.go | 66 +++ internal/sub/clash_service.go | 5 +- internal/sub/controller.go | 18 +- internal/sub/json_service.go | 10 +- internal/sub/service.go | 40 +- internal/sub/wireguard-device.go | 58 ++ internal/sub/wireguard_device_test.go | 181 ++++++ internal/util/wirecodec/wirecodec.go | 5 +- .../controller/client-wireguard-devices.go | 57 ++ internal/web/controller/client.go | 5 + .../client_wireguard_devices_test.go | 72 +++ internal/web/node_contract_test.go | 3 + internal/web/runtime/local.go | 75 ++- .../runtime/local_wireguard_devices_test.go | 128 +++++ internal/web/runtime/remote.go | 45 ++ internal/web/runtime/remote_envelope_test.go | 39 ++ .../web/service/client-wireguard-devices.go | 301 ++++++++++ .../service/client-wireguard-validation.go | 154 ++++++ internal/web/service/client_bulk.go | 1 + internal/web/service/client_crud.go | 17 + internal/web/service/client_inbound_apply.go | 46 +- internal/web/service/client_link.go | 28 +- internal/web/service/client_wireguard.go | 10 +- .../service/client_wireguard_devices_test.go | 225 ++++++++ .../service/client_wireguard_readd_test.go | 50 ++ .../client_wireguard_validation_test.go | 148 +++++ internal/web/service/inbound.go | 16 +- internal/web/service/inbound_node_claims.go | 2 +- internal/web/service/inbound_traffic.go | 25 +- .../web/service/wireguard_hot_apply_test.go | 139 +++++ internal/web/service/xray.go | 16 +- .../web/service/xray_wireguard_config_test.go | 34 ++ internal/web/translation/ar-EG.json | 11 + internal/web/translation/en-US.json | 11 + internal/web/translation/es-ES.json | 11 + internal/web/translation/fa-IR.json | 11 + internal/web/translation/id-ID.json | 11 + internal/web/translation/ja-JP.json | 11 + internal/web/translation/pt-BR.json | 11 + internal/web/translation/ru-RU.json | 11 + internal/web/translation/sk-SK.json | 11 + internal/web/translation/tr-TR.json | 11 + internal/web/translation/uk-UA.json | 11 + internal/web/translation/vi-VN.json | 11 + internal/web/translation/zh-CN.json | 11 + internal/web/translation/zh-TW.json | 11 + internal/xray/api.go | 23 + internal/xray/api_wireguard_devices_test.go | 72 +++ internal/xray/hot-diff-wireguard.go | 80 +++ internal/xray/hot_diff.go | 13 +- tools/openapigen/main.go | 1 + 72 files changed, 4489 insertions(+), 196 deletions(-) create mode 100644 frontend/src/hooks/useClientWireguardDevices.ts create mode 100644 frontend/src/pages/clients/ClientWireguardDevices.tsx create mode 100644 frontend/src/test/client-form-wireguard-devices.test.tsx create mode 100644 frontend/src/test/wireguard-devices.test.tsx create mode 100644 internal/database/model/model-wireguard-devices.go create mode 100644 internal/database/model/model_wireguard_devices_test.go create mode 100644 internal/sub/wireguard-device.go create mode 100644 internal/sub/wireguard_device_test.go create mode 100644 internal/web/controller/client-wireguard-devices.go create mode 100644 internal/web/controller/client_wireguard_devices_test.go create mode 100644 internal/web/runtime/local_wireguard_devices_test.go create mode 100644 internal/web/service/client-wireguard-devices.go create mode 100644 internal/web/service/client-wireguard-validation.go create mode 100644 internal/web/service/client_wireguard_devices_test.go create mode 100644 internal/web/service/client_wireguard_readd_test.go create mode 100644 internal/web/service/client_wireguard_validation_test.go create mode 100644 internal/web/service/wireguard_hot_apply_test.go create mode 100644 internal/xray/api_wireguard_devices_test.go create mode 100644 internal/xray/hot-diff-wireguard.go diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx index 3f9a13218..4fd2153cf 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -82,6 +82,21 @@ _openapi: emitted on future subscription fetches; credentials already imported by an app remain valid until the external provider revokes them. url: '#replace-a-clients-external-links-and-external-subscriptions-sends-the-full-set-the-server-replaces-all-rows-disabled-rows-stay-saved-for-editing-but-are-not-emitted-in-generated-subscriptions-the-owning-clients-disabled-or-expired-state-also-stops-these-rows-from-being-emitted-on-future-subscription-fetches-credentials-already-imported-by-an-app-remain-valid-until-the-external-provider-revokes-them' + - depth: 2 + title: List WireGuard devices and their per-inbound addresses. + url: '#list-wireguard-devices-and-their-per-inbound-addresses' + - depth: 2 + title: Create a WireGuard device on every attached WireGuard inbound. + url: '#create-a-wireguard-device-on-every-attached-wireguard-inbound' + - depth: 2 + title: Set the maximum number of WireGuard devices. + url: '#set-the-maximum-number-of-wireguard-devices' + - depth: 2 + title: Rename or enable a WireGuard device. + url: '#rename-or-enable-a-wireguard-device' + - depth: 2 + title: Delete an additional WireGuard device and release its address. + url: '#delete-an-additional-wireguard-device-and-release-its-address' - depth: 2 title: Reset the up/down counters for every client globally. Quotas and expiry are not affected. Triggers an Xray restart if any counter actually @@ -400,6 +415,16 @@ _openapi: emitted on future subscription fetches; credentials already imported by an app remain valid until the external provider revokes them. id: replace-a-clients-external-links-and-external-subscriptions-sends-the-full-set-the-server-replaces-all-rows-disabled-rows-stay-saved-for-editing-but-are-not-emitted-in-generated-subscriptions-the-owning-clients-disabled-or-expired-state-also-stops-these-rows-from-being-emitted-on-future-subscription-fetches-credentials-already-imported-by-an-app-remain-valid-until-the-external-provider-revokes-them + - content: List WireGuard devices and their per-inbound addresses. + id: list-wireguard-devices-and-their-per-inbound-addresses + - content: Create a WireGuard device on every attached WireGuard inbound. + id: create-a-wireguard-device-on-every-attached-wireguard-inbound + - content: Set the maximum number of WireGuard devices. + id: set-the-maximum-number-of-wireguard-devices + - content: Rename or enable a WireGuard device. + id: rename-or-enable-a-wireguard-device + - content: Delete an additional WireGuard device and release its address. + id: delete-an-additional-wireguard-device-and-release-its-address - content: Reset the up/down counters for every client globally. Quotas and expiry are not affected. Triggers an Xray restart if any counter actually moved. @@ -778,6 +803,26 @@ _openapi: still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.' heading: detach-a-client-from-one-or-more-inbounds-without-deleting-the-client + - content: The original credentials remain the primary device. Additional devices + share their parent client email, traffic quota, expiry and enable + state. Keep each device configuration on one device. Device-specific + subscriptions use the existing subscription URL with the wgDevice + query parameter set to the device ID. + heading: list-wireguard-devices-and-their-per-inbound-addresses + - content: Keys are generated once and each inbound allocates an available tunnel + address. All inbounds commit together. The default limit is 5 devices + including primary. + heading: create-a-wireguard-device-on-every-attached-wireguard-inbound + - content: The limit includes primary and disabled devices. Choose 1 to 32. Values + below the current device count are rejected. + heading: set-the-maximum-number-of-wireguard-devices + - content: The primary device is managed through the parent client. Disabled + additional devices retain their reserved addresses. + heading: rename-or-enable-a-wireguard-device + - content: The device is removed from every attached WireGuard inbound. Its + previously downloaded configuration loses access after the + configuration is applied. + heading: delete-an-additional-wireguard-device-and-release-its-address --- {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} @@ -787,7 +832,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 7218bb091..48febad12 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -2151,6 +2151,15 @@ "description": "Last update timestamp", "format": "int64", "type": "integer" + }, + "wgDeviceLimit": { + "type": "integer" + }, + "wireguardDevices": { + "items": { + "$ref": "#/components/schemas/WireguardDevice" + }, + "type": "array" } }, "required": [ @@ -2365,6 +2374,15 @@ }, "uuid": { "type": "string" + }, + "wgDeviceLimit": { + "type": "integer" + }, + "wireguardDevices": { + "items": { + "$ref": "#/components/schemas/WireguardDevice" + }, + "type": "array" } }, "required": [ @@ -2400,7 +2418,9 @@ "trafficReset", "trafficResetDay", "updatedAt", - "uuid" + "uuid", + "wgDeviceLimit", + "wireguardDevices" ], "type": "object" }, @@ -5433,6 +5453,44 @@ ], "type": "object" }, + "WireguardDevice": { + "description": "WireguardDevice is an additional peer sharing its client's quota and lifecycle.\nThe original client credentials remain the primary device for compatibility.", + "properties": { + "allowedIPs": { + "items": { + "type": "string" + }, + "type": "array" + }, + "enable": { + "type": "boolean" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "preSharedKey": { + "type": "string" + }, + "privateKey": { + "type": "string" + }, + "publicKey": { + "type": "string" + } + }, + "required": [ + "allowedIPs", + "enable", + "id", + "name", + "privateKey", + "publicKey" + ], + "type": "object" + }, "WebSocketEnvelope": { "type": "object", "required": [ @@ -10022,6 +10080,464 @@ } } }, + "/panel/api/clients/wireguardDevices": { + "get": { + "tags": [ + "Clients" + ], + "summary": "List WireGuard devices and their per-inbound addresses.", + "operationId": "get_panel_api_clients_wireguardDevices", + "description": "The original credentials remain the primary device. Additional devices share their parent client email, traffic quota, expiry and enable state. Keep each device configuration on one device. Device-specific subscriptions use the existing subscription URL with the wgDevice query parameter set to the device ID.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "obj": { + "limit": 5, + "inbounds": [ + { + "inboundId": 3, + "devices": [ + { + "id": "primary", + "name": "", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.2/32" + ] + }, + { + "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d", + "name": "Phone", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.3/32" + ] + } + ] + } + ] + } + } + } + } + } + } + }, + "post": { + "tags": [ + "Clients" + ], + "summary": "Create a WireGuard device on every attached WireGuard inbound.", + "operationId": "post_panel_api_clients_wireguardDevices", + "description": "Keys are generated once and each inbound allocates an available tunnel address. All inbounds commit together. The default limit is 5 devices including primary.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Device name with 1 to 64 characters on one line." + } + }, + "required": [ + "name" + ] + }, + "example": { + "name": "Phone" + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "obj": { + "limit": 5, + "inbounds": [ + { + "inboundId": 3, + "devices": [ + { + "id": "primary", + "name": "", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.2/32" + ] + }, + { + "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d", + "name": "Phone", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.3/32" + ] + } + ] + } + ] + } + } + } + } + } + } + } + }, + "/panel/api/clients/wireguardDevices/limit": { + "put": { + "tags": [ + "Clients" + ], + "summary": "Set the maximum number of WireGuard devices.", + "operationId": "put_panel_api_clients_wireguardDevices_limit", + "description": "The limit includes primary and disabled devices. Choose 1 to 32. Values below the current device count are rejected.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "limit": { + "type": "integer", + "default": 5, + "description": "Maximum device count including primary." + } + }, + "required": [ + "limit" + ] + }, + "example": { + "limit": 5 + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "obj": { + "limit": 5, + "inbounds": [ + { + "inboundId": 3, + "devices": [ + { + "id": "primary", + "name": "", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.2/32" + ] + }, + { + "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d", + "name": "Phone", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.3/32" + ] + } + ] + } + ] + } + } + } + } + } + } + } + }, + "/panel/api/clients/wireguardDevices/{deviceId}": { + "patch": { + "tags": [ + "Clients" + ], + "summary": "Rename or enable a WireGuard device.", + "operationId": "patch_panel_api_clients_wireguardDevices_deviceId", + "description": "The primary device is managed through the parent client. Disabled additional devices retain their reserved addresses.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email.", + "schema": { + "type": "string" + } + }, + { + "name": "deviceId", + "in": "path", + "required": true, + "description": "Additional device UUID.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "New device name." + }, + "enable": { + "type": "boolean", + "description": "Whether the device can connect." + } + } + }, + "example": { + "name": "Work phone", + "enable": true + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "obj": { + "limit": 5, + "inbounds": [ + { + "inboundId": 3, + "devices": [ + { + "id": "primary", + "name": "", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.2/32" + ] + }, + { + "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d", + "name": "Phone", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.3/32" + ] + } + ] + } + ] + } + } + } + } + } + } + }, + "delete": { + "tags": [ + "Clients" + ], + "summary": "Delete an additional WireGuard device and release its address.", + "operationId": "delete_panel_api_clients_wireguardDevices_deviceId", + "description": "The device is removed from every attached WireGuard inbound. Its previously downloaded configuration loses access after the configuration is applied.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email.", + "schema": { + "type": "string" + } + }, + { + "name": "deviceId", + "in": "path", + "required": true, + "description": "Additional device UUID.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "obj": { + "limit": 5, + "inbounds": [ + { + "inboundId": 3, + "devices": [ + { + "id": "primary", + "name": "", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.2/32" + ] + }, + { + "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d", + "name": "Phone", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.3/32" + ] + } + ] + } + ] + } + } + } + } + } + } + } + }, "/panel/api/clients/resetAllTraffics": { "post": { "tags": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 7218bb091..48febad12 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -2151,6 +2151,15 @@ "description": "Last update timestamp", "format": "int64", "type": "integer" + }, + "wgDeviceLimit": { + "type": "integer" + }, + "wireguardDevices": { + "items": { + "$ref": "#/components/schemas/WireguardDevice" + }, + "type": "array" } }, "required": [ @@ -2365,6 +2374,15 @@ }, "uuid": { "type": "string" + }, + "wgDeviceLimit": { + "type": "integer" + }, + "wireguardDevices": { + "items": { + "$ref": "#/components/schemas/WireguardDevice" + }, + "type": "array" } }, "required": [ @@ -2400,7 +2418,9 @@ "trafficReset", "trafficResetDay", "updatedAt", - "uuid" + "uuid", + "wgDeviceLimit", + "wireguardDevices" ], "type": "object" }, @@ -5433,6 +5453,44 @@ ], "type": "object" }, + "WireguardDevice": { + "description": "WireguardDevice is an additional peer sharing its client's quota and lifecycle.\nThe original client credentials remain the primary device for compatibility.", + "properties": { + "allowedIPs": { + "items": { + "type": "string" + }, + "type": "array" + }, + "enable": { + "type": "boolean" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "preSharedKey": { + "type": "string" + }, + "privateKey": { + "type": "string" + }, + "publicKey": { + "type": "string" + } + }, + "required": [ + "allowedIPs", + "enable", + "id", + "name", + "privateKey", + "publicKey" + ], + "type": "object" + }, "WebSocketEnvelope": { "type": "object", "required": [ @@ -10022,6 +10080,464 @@ } } }, + "/panel/api/clients/wireguardDevices": { + "get": { + "tags": [ + "Clients" + ], + "summary": "List WireGuard devices and their per-inbound addresses.", + "operationId": "get_panel_api_clients_wireguardDevices", + "description": "The original credentials remain the primary device. Additional devices share their parent client email, traffic quota, expiry and enable state. Keep each device configuration on one device. Device-specific subscriptions use the existing subscription URL with the wgDevice query parameter set to the device ID.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "obj": { + "limit": 5, + "inbounds": [ + { + "inboundId": 3, + "devices": [ + { + "id": "primary", + "name": "", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.2/32" + ] + }, + { + "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d", + "name": "Phone", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.3/32" + ] + } + ] + } + ] + } + } + } + } + } + } + }, + "post": { + "tags": [ + "Clients" + ], + "summary": "Create a WireGuard device on every attached WireGuard inbound.", + "operationId": "post_panel_api_clients_wireguardDevices", + "description": "Keys are generated once and each inbound allocates an available tunnel address. All inbounds commit together. The default limit is 5 devices including primary.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Device name with 1 to 64 characters on one line." + } + }, + "required": [ + "name" + ] + }, + "example": { + "name": "Phone" + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "obj": { + "limit": 5, + "inbounds": [ + { + "inboundId": 3, + "devices": [ + { + "id": "primary", + "name": "", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.2/32" + ] + }, + { + "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d", + "name": "Phone", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.3/32" + ] + } + ] + } + ] + } + } + } + } + } + } + } + }, + "/panel/api/clients/wireguardDevices/limit": { + "put": { + "tags": [ + "Clients" + ], + "summary": "Set the maximum number of WireGuard devices.", + "operationId": "put_panel_api_clients_wireguardDevices_limit", + "description": "The limit includes primary and disabled devices. Choose 1 to 32. Values below the current device count are rejected.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "limit": { + "type": "integer", + "default": 5, + "description": "Maximum device count including primary." + } + }, + "required": [ + "limit" + ] + }, + "example": { + "limit": 5 + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "obj": { + "limit": 5, + "inbounds": [ + { + "inboundId": 3, + "devices": [ + { + "id": "primary", + "name": "", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.2/32" + ] + }, + { + "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d", + "name": "Phone", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.3/32" + ] + } + ] + } + ] + } + } + } + } + } + } + } + }, + "/panel/api/clients/wireguardDevices/{deviceId}": { + "patch": { + "tags": [ + "Clients" + ], + "summary": "Rename or enable a WireGuard device.", + "operationId": "patch_panel_api_clients_wireguardDevices_deviceId", + "description": "The primary device is managed through the parent client. Disabled additional devices retain their reserved addresses.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email.", + "schema": { + "type": "string" + } + }, + { + "name": "deviceId", + "in": "path", + "required": true, + "description": "Additional device UUID.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "New device name." + }, + "enable": { + "type": "boolean", + "description": "Whether the device can connect." + } + } + }, + "example": { + "name": "Work phone", + "enable": true + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "obj": { + "limit": 5, + "inbounds": [ + { + "inboundId": 3, + "devices": [ + { + "id": "primary", + "name": "", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.2/32" + ] + }, + { + "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d", + "name": "Phone", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.3/32" + ] + } + ] + } + ] + } + } + } + } + } + } + }, + "delete": { + "tags": [ + "Clients" + ], + "summary": "Delete an additional WireGuard device and release its address.", + "operationId": "delete_panel_api_clients_wireguardDevices_deviceId", + "description": "The device is removed from every attached WireGuard inbound. Its previously downloaded configuration loses access after the configuration is applied.", + "parameters": [ + { + "name": "email", + "in": "query", + "required": true, + "description": "Client email.", + "schema": { + "type": "string" + } + }, + { + "name": "deviceId", + "in": "path", + "required": true, + "description": "Additional device UUID.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + }, + "example": { + "success": true, + "obj": { + "limit": 5, + "inbounds": [ + { + "inboundId": 3, + "devices": [ + { + "id": "primary", + "name": "", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.2/32" + ] + }, + { + "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d", + "name": "Phone", + "enable": true, + "privateKey": "...", + "publicKey": "...", + "allowedIPs": [ + "10.0.0.3/32" + ] + } + ] + } + ] + } + } + } + } + } + } + } + }, "/panel/api/clients/resetAllTraffics": { "post": { "tags": [ diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 39a5cca61..1ae15a8ee 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -506,7 +506,21 @@ export const EXAMPLES: Record = { "totalGB": 0, "trafficReset": "never", "trafficResetDay": 1, - "updated_at": 0 + "updated_at": 0, + "wgDeviceLimit": 0, + "wireguardDevices": [ + { + "allowedIPs": [ + "" + ], + "enable": false, + "id": "", + "name": "", + "preSharedKey": "", + "privateKey": "", + "publicKey": "" + } + ] }, "ClientInbound": { "clientId": 0, @@ -601,7 +615,21 @@ export const EXAMPLES: Record = { "trafficReset": "", "trafficResetDay": 0, "updatedAt": 0, - "uuid": "" + "uuid": "", + "wgDeviceLimit": 0, + "wireguardDevices": [ + { + "allowedIPs": [ + "" + ], + "enable": false, + "id": "", + "name": "", + "preSharedKey": "", + "privateKey": "", + "publicKey": "" + } + ] }, "ClientRenewalPreview": { "canRenew": true, @@ -1350,5 +1378,16 @@ export const EXAMPLES: Record = { "id": 0, "password": "", "username": "" + }, + "WireguardDevice": { + "allowedIPs": [ + "" + ], + "enable": false, + "id": "", + "name": "", + "preSharedKey": "", + "privateKey": "", + "publicKey": "" } }; diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 9212e25f3..11ef0e993 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -2125,6 +2125,15 @@ export const SCHEMAS: Record = { "description": "Last update timestamp", "format": "int64", "type": "integer" + }, + "wgDeviceLimit": { + "type": "integer" + }, + "wireguardDevices": { + "items": { + "$ref": "#/components/schemas/WireguardDevice" + }, + "type": "array" } }, "required": [ @@ -2339,6 +2348,15 @@ export const SCHEMAS: Record = { }, "uuid": { "type": "string" + }, + "wgDeviceLimit": { + "type": "integer" + }, + "wireguardDevices": { + "items": { + "$ref": "#/components/schemas/WireguardDevice" + }, + "type": "array" } }, "required": [ @@ -2374,7 +2392,9 @@ export const SCHEMAS: Record = { "trafficReset", "trafficResetDay", "updatedAt", - "uuid" + "uuid", + "wgDeviceLimit", + "wireguardDevices" ], "type": "object" }, @@ -5406,5 +5426,43 @@ export const SCHEMAS: Record = { "username" ], "type": "object" + }, + "WireguardDevice": { + "description": "WireguardDevice is an additional peer sharing its client's quota and lifecycle.\nThe original client credentials remain the primary device for compatibility.", + "properties": { + "allowedIPs": { + "items": { + "type": "string" + }, + "type": "array" + }, + "enable": { + "type": "boolean" + }, + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "preSharedKey": { + "type": "string" + }, + "privateKey": { + "type": "string" + }, + "publicKey": { + "type": "string" + } + }, + "required": [ + "allowedIPs", + "enable", + "id", + "name", + "privateKey", + "publicKey" + ], + "type": "object" } }; diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 558c1dcb7..269aefccc 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -501,6 +501,8 @@ export interface Client { trafficReset?: string; trafficResetDay?: number; updated_at?: number; + wgDeviceLimit?: number; + wireguardDevices?: WireguardDevice[]; } export interface ClientInbound { @@ -555,6 +557,8 @@ export interface ClientRecord { trafficResetDay: number; updatedAt: number; uuid: string; + wgDeviceLimit: number; + wireguardDevices: WireguardDevice[]; } export interface ClientRenewalPreview { @@ -1235,3 +1239,13 @@ export interface User { username: string; } +export interface WireguardDevice { + allowedIPs: string[]; + enable: boolean; + id: string; + name: string; + preSharedKey?: string; + privateKey: string; + publicKey: string; +} + diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 6b65791f1..f59eb9e08 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -520,6 +520,8 @@ export const ClientSchema = z.object({ trafficReset: z.enum(['never', 'hourly', 'daily', 'weekly', 'monthly']).optional(), trafficResetDay: z.number().int().min(1).max(31).optional(), updated_at: z.number().int().optional(), + wgDeviceLimit: z.number().int().optional(), + wireguardDevices: z.array(z.lazy(() => WireguardDeviceSchema)).optional(), }); export type Client = z.infer; @@ -577,6 +579,8 @@ export const ClientRecordSchema = z.object({ trafficResetDay: z.number().int(), updatedAt: z.number().int(), uuid: z.string(), + wgDeviceLimit: z.number().int(), + wireguardDevices: z.array(z.lazy(() => WireguardDeviceSchema)), }); export type ClientRecord = z.infer; @@ -1310,3 +1314,14 @@ export const UserSchema = z.object({ }); export type User = z.infer; +export const WireguardDeviceSchema = z.object({ + allowedIPs: z.array(z.string()), + enable: z.boolean(), + id: z.string(), + name: z.string(), + preSharedKey: z.string().optional(), + privateKey: z.string(), + publicKey: z.string(), +}); +export type WireguardDevice = z.infer; + diff --git a/frontend/src/hooks/useClientWireguardDevices.ts b/frontend/src/hooks/useClientWireguardDevices.ts new file mode 100644 index 000000000..049bf75a4 --- /dev/null +++ b/frontend/src/hooks/useClientWireguardDevices.ts @@ -0,0 +1,56 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { keys } from '@/api/queryKeys'; +import { httpRequest } from '@/api/http-init'; +import { HttpUtil } from '@/utils'; +import { WireguardDevicesSchema } from '@/schemas/client'; + +export function useClientWireguardDevices(email: string | undefined, active: boolean) { + const queryClient = useQueryClient(); + const queryKey = ['clients', 'wireguardDevices', email]; + const path = '/panel/api/clients/wireguardDevices'; + const emailQuery = `?email=${encodeURIComponent(email ?? '')}`; + const query = useQuery({ + queryKey, + enabled: active && !!email, + queryFn: async () => { + const msg = await HttpUtil.get(path + emailQuery); + if (!msg.success) throw new Error(msg.msg); + return WireguardDevicesSchema.parse(msg.obj); + }, + }); + const mutation = useMutation({ + mutationFn: async ({ + method, + suffix, + body, + }: { + method: string; + suffix: string; + body?: unknown; + }) => { + const response = await httpRequest(method, path + suffix + emailQuery, body, { + headers: { 'Content-Type': 'application/json' }, + }); + const msg = HttpUtil._respToMsg(response); + HttpUtil._handleMsg(msg); + if (!msg.success) throw new Error(msg.msg); + }, + onSuccess: () => queryClient.invalidateQueries({ queryKey: keys.clients.root() }), + }); + return { + data: query.data, + loading: query.isLoading, + error: query.error, + pending: mutation.isPending, + mutationError: mutation.error, + create: (name: string) => mutation.mutate({ method: 'POST', suffix: '', body: { name } }), + update: (id: string, body: { name?: string; enable?: boolean }) => + mutation.mutate({ + method: 'PATCH', + suffix: `/${encodeURIComponent(id)}`, + body, + }), + remove: (id: string) => + mutation.mutate({ method: 'DELETE', suffix: `/${encodeURIComponent(id)}` }), + }; +} diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index ce092af6b..fa7d37da2 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -1403,6 +1403,96 @@ export const sections: readonly Section[] = [ body: '{\n "externalLinks": [\n { "kind": "link", "value": "vless://uuid@host:443?...#srv", "remark": "DE", "enable": true, "expiryTime": 0 },\n { "kind": "subscription", "value": "https://provider.example/sub/abc", "remark": "Provider", "enable": false, "expiryTime": 1767225600000, "namePrefix": "[zjh] " }\n ]\n}', response: '{\n "success": true\n}', }, + { + method: 'GET', + path: '/panel/api/clients/wireguardDevices', + summary: 'List WireGuard devices and their per-inbound addresses.', + description: + 'The original credentials remain the primary device. Additional devices share their parent client email, traffic quota, expiry and enable state. Keep each device configuration on one device. Device-specific subscriptions use the existing subscription URL with the wgDevice query parameter set to the device ID.', + params: [{ name: 'email', in: 'query', type: 'string', desc: 'Client email.' }], + response: + '{\n "success": true,\n "obj": {\n "limit": 5,\n "inbounds": [\n {\n "inboundId": 3,\n "devices": [\n {\n "id": "primary",\n "name": "",\n "enable": true,\n "privateKey": "...",\n "publicKey": "...",\n "allowedIPs": [\n "10.0.0.2/32"\n ]\n },\n {\n "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d",\n "name": "Phone",\n "enable": true,\n "privateKey": "...",\n "publicKey": "...",\n "allowedIPs": [\n "10.0.0.3/32"\n ]\n }\n ]\n }\n ]\n }\n}', + }, + { + method: 'POST', + path: '/panel/api/clients/wireguardDevices', + summary: 'Create a WireGuard device on every attached WireGuard inbound.', + description: + 'Keys are generated once and each inbound allocates an available tunnel address. All inbounds commit together. The default limit is 5 devices including primary.', + params: [ + { name: 'email', in: 'query', type: 'string', desc: 'Client email.' }, + { + name: 'name', + in: 'body (json)', + type: 'string', + desc: 'Device name with 1 to 64 characters on one line.', + }, + ], + body: '{\n "name": "Phone"\n}', + response: + '{\n "success": true,\n "obj": {\n "limit": 5,\n "inbounds": [\n {\n "inboundId": 3,\n "devices": [\n {\n "id": "primary",\n "name": "",\n "enable": true,\n "privateKey": "...",\n "publicKey": "...",\n "allowedIPs": [\n "10.0.0.2/32"\n ]\n },\n {\n "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d",\n "name": "Phone",\n "enable": true,\n "privateKey": "...",\n "publicKey": "...",\n "allowedIPs": [\n "10.0.0.3/32"\n ]\n }\n ]\n }\n ]\n }\n}', + }, + { + method: 'PUT', + path: '/panel/api/clients/wireguardDevices/limit', + summary: 'Set the maximum number of WireGuard devices.', + description: + 'The limit includes primary and disabled devices. Choose 1 to 32. Values below the current device count are rejected.', + params: [ + { name: 'email', in: 'query', type: 'string', desc: 'Client email.' }, + { + name: 'limit', + in: 'body (json)', + type: 'integer', + desc: 'Maximum device count including primary.', + defaultValue: 5, + }, + ], + body: '{\n "limit": 5\n}', + response: + '{\n "success": true,\n "obj": {\n "limit": 5,\n "inbounds": [\n {\n "inboundId": 3,\n "devices": [\n {\n "id": "primary",\n "name": "",\n "enable": true,\n "privateKey": "...",\n "publicKey": "...",\n "allowedIPs": [\n "10.0.0.2/32"\n ]\n },\n {\n "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d",\n "name": "Phone",\n "enable": true,\n "privateKey": "...",\n "publicKey": "...",\n "allowedIPs": [\n "10.0.0.3/32"\n ]\n }\n ]\n }\n ]\n }\n}', + }, + { + method: 'PATCH', + path: '/panel/api/clients/wireguardDevices/:deviceId', + summary: 'Rename or enable a WireGuard device.', + description: + 'The primary device is managed through the parent client. Disabled additional devices retain their reserved addresses.', + params: [ + { name: 'email', in: 'query', type: 'string', desc: 'Client email.' }, + { name: 'deviceId', in: 'path', type: 'string', desc: 'Additional device UUID.' }, + { + name: 'name', + in: 'body (json)', + type: 'string', + optional: true, + desc: 'New device name.', + }, + { + name: 'enable', + in: 'body (json)', + type: 'boolean', + optional: true, + desc: 'Whether the device can connect.', + }, + ], + body: '{\n "name": "Work phone",\n "enable": true\n}', + response: + '{\n "success": true,\n "obj": {\n "limit": 5,\n "inbounds": [\n {\n "inboundId": 3,\n "devices": [\n {\n "id": "primary",\n "name": "",\n "enable": true,\n "privateKey": "...",\n "publicKey": "...",\n "allowedIPs": [\n "10.0.0.2/32"\n ]\n },\n {\n "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d",\n "name": "Phone",\n "enable": true,\n "privateKey": "...",\n "publicKey": "...",\n "allowedIPs": [\n "10.0.0.3/32"\n ]\n }\n ]\n }\n ]\n }\n}', + }, + { + method: 'DELETE', + path: '/panel/api/clients/wireguardDevices/:deviceId', + summary: 'Delete an additional WireGuard device and release its address.', + description: + 'The device is removed from every attached WireGuard inbound. Its previously downloaded configuration loses access after the configuration is applied.', + params: [ + { name: 'email', in: 'query', type: 'string', desc: 'Client email.' }, + { name: 'deviceId', in: 'path', type: 'string', desc: 'Additional device UUID.' }, + ], + response: + '{\n "success": true,\n "obj": {\n "limit": 5,\n "inbounds": [\n {\n "inboundId": 3,\n "devices": [\n {\n "id": "primary",\n "name": "",\n "enable": true,\n "privateKey": "...",\n "publicKey": "...",\n "allowedIPs": [\n "10.0.0.2/32"\n ]\n },\n {\n "id": "e3550bd1-0ba0-48b2-8a91-e57263a23d9d",\n "name": "Phone",\n "enable": true,\n "privateKey": "...",\n "publicKey": "...",\n "allowedIPs": [\n "10.0.0.3/32"\n ]\n }\n ]\n }\n ]\n }\n}', + }, { method: 'POST', path: '/panel/api/clients/resetAllTraffics', diff --git a/frontend/src/pages/clients/ClientFormModal.tsx b/frontend/src/pages/clients/ClientFormModal.tsx index b5073c872..24916789c 100644 --- a/frontend/src/pages/clients/ClientFormModal.tsx +++ b/frontend/src/pages/clients/ClientFormModal.tsx @@ -120,6 +120,7 @@ interface ClientFormModalProps { type Values = ClientFormValues & { expiryDate: number; limitHwid: number; + wgDeviceLimit: number; externalLinks: ExternalLinkRow[]; clientHostRuleIds: number[]; wgPrivateKey: string; @@ -155,6 +156,7 @@ const EMPTY: Values = { trafficResetDay: 1, limitIp: 0, limitHwid: 0, + wgDeviceLimit: 5, tgId: 0, group: '', comment: '', @@ -251,6 +253,7 @@ export default function ClientFormModal({ const uid = useId(); const [messageApi, messageContextHolder] = message.useMessage(); const isEdit = mode === 'edit'; + const minWireguardDeviceLimit = Math.max(1, (client?.wireguardDevices?.length ?? 0) + 1); const methods = useForm({ defaultValues: EMPTY }); const inboundIds = useWatch({ control: methods.control, name: 'inboundIds' }); @@ -359,6 +362,7 @@ export default function ClientFormModal({ trafficResetDay: Number(client.trafficResetDay) || 1, limitIp: client.limitIp || 0, limitHwid: client.limitHwid || 0, + wgDeviceLimit: client.wgDeviceLimit || 5, tgId: Number(client.tgId) || 0, group: client.group || '', comment: client.comment || '', @@ -677,6 +681,7 @@ export default function ClientFormModal({ async function onSubmit() { await methods.trigger('externalLinks'); const values = methods.getValues(); + if (showWireguard && !(await methods.trigger('wgDeviceLimit'))) return; const externalValidation = await ExternalLinksFormSchema.safeParseAsync(values); if (!externalValidation.success) { for (const issue of externalValidation.error.issues) { @@ -772,6 +777,7 @@ export default function ClientFormModal({ comment: values.comment, enable: !!values.enable, }; + if (showWireguard) clientPayload.wgDeviceLimit = values.wgDeviceLimit; // Sent even when empty, so clearing the tag never rests on how the server // reads an omitted key. const reverseTagValue = showReverseTag ? (values.reverseTag || '').trim() : ''; @@ -1033,6 +1039,30 @@ export default function ClientFormModal({ + {showWireguard && ( + + Number(value) }} + rules={{ + validate: (value) => + (Number.isInteger(value) && + value >= minWireguardDeviceLimit && + value <= 32) || + `${t('pages.clients.wgDevices.limit')} (${minWireguardDeviceLimit}–32)`, + }} + > + + + + )} diff --git a/frontend/src/pages/clients/ClientInfoModal.tsx b/frontend/src/pages/clients/ClientInfoModal.tsx index 646ab052c..0419d50f6 100644 --- a/frontend/src/pages/clients/ClientInfoModal.tsx +++ b/frontend/src/pages/clients/ClientInfoModal.tsx @@ -1,3 +1,5 @@ +import ClientWireguardDevices from './ClientWireguardDevices'; +import { useClientWireguardDevices } from '@/hooks/useClientWireguardDevices'; import { useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Button, Divider, Modal, Popover, Tag, Tooltip, message } from 'antd'; @@ -21,7 +23,7 @@ import { QrPanel } from '@/pages/inbounds/qr'; import ClientHwidListModal from '@/components/clients/ClientHwidList'; import ConfigBlock from '@/components/clients/ConfigBlock'; import { - buildWireguardClientConfig, + buildWireguardDeviceConfigs, findWireguardInbounds, isWireguardClient, } from './wireguardConfig'; @@ -193,21 +195,20 @@ export default function ClientInfoModal({ () => findWireguardInbounds(client, inboundsById), [client, inboundsById], ); + const wireguardDevices = useClientWireguardDevices(client?.email, open && wgInbounds.length > 0); const wgConfigs = useMemo(() => { if (!client || !isWireguardClient(client)) return []; - const host = window.location.hostname; - const publicHost = subSettings?.publicHost ?? ''; - return wgInbounds - .flatMap((ib) => { - const address = tunnelAllowedIPs?.[ib.id] ?? ''; - return tunnelConfigEndpoints(ib, hosts, host, publicHost).map((ep) => ({ - inbound: ib, - endpoint: tunnelEndpointLabel(ep), - text: buildWireguardClientConfig(client, ib, host, publicHost, address, ep), - })); - }) - .filter((c) => !!c.text); - }, [client, wgInbounds, tunnelAllowedIPs, subSettings?.publicHost, hosts]); + return buildWireguardDeviceConfigs( + client, + wgInbounds, + wireguardDevices.data, + tunnelAllowedIPs, + hosts, + window.location.hostname, + subSettings.publicHost ?? '', + true, + ); + }, [client, wgInbounds, wireguardDevices.data, tunnelAllowedIPs, subSettings.publicHost, hosts]); const awgInbounds = useMemo( () => findAmneziaWGInbounds(client, inboundsById), @@ -216,7 +217,7 @@ export default function ClientInfoModal({ const awgConfigs = useMemo(() => { if (!client || !isAmneziaWGClient(client)) return []; const host = window.location.hostname; - const publicHost = subSettings?.publicHost ?? ''; + const publicHost = subSettings.publicHost ?? ''; return awgInbounds .flatMap((ib) => { const address = tunnelAllowedIPs?.[ib.id] ?? ''; @@ -227,7 +228,7 @@ export default function ClientInfoModal({ })); }) .filter((c) => !!c.text); - }, [client, awgInbounds, tunnelAllowedIPs, subSettings?.publicHost, hosts]); + }, [client, awgInbounds, tunnelAllowedIPs, subSettings.publicHost, hosts]); async function copyValue(text: string) { if (!text) return; @@ -798,28 +799,13 @@ export default function ClientInfoModal({ )} - {wgConfigs.length > 0 && client && ( - <> - {t('pages.clients.wireguardConfig')} - {wgConfigs.map(({ inbound, endpoint, text }) => { - const meta = formatTunnelConfigMeta( - inbound, - client.email, - wgConfigs.length, - endpoint, - ); - return ( - - ); - })} - + {wgInbounds.length > 0 && client && ( + )} {awgConfigs.length > 0 && client && ( diff --git a/frontend/src/pages/clients/ClientQrModal.tsx b/frontend/src/pages/clients/ClientQrModal.tsx index 2ff5a1698..ecfd9b414 100644 --- a/frontend/src/pages/clients/ClientQrModal.tsx +++ b/frontend/src/pages/clients/ClientQrModal.tsx @@ -1,3 +1,4 @@ +import { useClientWireguardDevices } from '@/hooks/useClientWireguardDevices'; import { useCallback, useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router'; @@ -12,7 +13,7 @@ import { QrPanel } from '@/pages/inbounds/qr'; import type { ClientRecord, InboundOption } from '@/hooks/useClients'; import { formatTunnelConfigMeta } from '@/lib/inbounds/label'; import { - buildWireguardClientConfig, + buildWireguardDeviceConfigs, findWireguardInbounds, isWireguardClient, } from './wireguardConfig'; @@ -330,21 +331,20 @@ function ClientQrModalContent({ () => findWireguardInbounds(client, inboundsById), [client, inboundsById], ); + const wireguardDevices = useClientWireguardDevices(client?.email, open && wgInbounds.length > 0); const wgConfigs = useMemo(() => { if (!client || !isWireguardClient(client)) return []; - const host = window.location.hostname; - const publicHost = subSettings.publicHost ?? ''; - return wgInbounds - .flatMap((ib) => { - const address = tunnelAllowedIPs?.[ib.id] ?? ''; - return tunnelConfigEndpoints(ib, hosts, host, publicHost).map((ep) => ({ - inbound: ib, - endpoint: tunnelEndpointLabel(ep), - text: buildWireguardClientConfig(client, ib, host, publicHost, address, ep), - })); - }) - .filter((c) => !!c.text); - }, [client, wgInbounds, tunnelAllowedIPs, subSettings.publicHost, hosts]); + return buildWireguardDeviceConfigs( + client, + wgInbounds, + wireguardDevices.data, + tunnelAllowedIPs, + hosts, + window.location.hostname, + subSettings.publicHost ?? '', + true, + ); + }, [client, wgInbounds, wireguardDevices.data, tunnelAllowedIPs, subSettings.publicHost, hosts]); const awgInbounds = useMemo( () => findAmneziaWGInbounds(client, inboundsById), @@ -472,7 +472,7 @@ function ClientQrModalContent({ ), }); }); - wgConfigs.forEach(({ inbound, endpoint, text }) => { + wgConfigs.forEach(({ inbound, deviceId, endpoint, text }) => { const meta = formatTunnelConfigMeta(inbound, client?.email, wgConfigs.length, endpoint); const label = ( @@ -483,9 +483,19 @@ function ClientQrModalContent({ ); out.push({ - key: `wg-config-${inbound.id}-${endpoint}`, + key: `wg-config-${inbound.id}-${deviceId}-${endpoint}`, label, - children: , + children: ( + + ), }); }); awgConfigs.forEach(({ inbound, endpoint, text }) => { diff --git a/frontend/src/pages/clients/ClientWireguardDevices.tsx b/frontend/src/pages/clients/ClientWireguardDevices.tsx new file mode 100644 index 000000000..5b8046597 --- /dev/null +++ b/frontend/src/pages/clients/ClientWireguardDevices.tsx @@ -0,0 +1,190 @@ +import { useState } from 'react'; +import { Alert, Button, Divider, Dropdown, Modal, Popover, Tag, Tooltip, message } from 'antd'; +import { + CheckOutlined, + CopyOutlined, + DownloadOutlined, + MoreOutlined, + PlusOutlined, + QrcodeOutlined, +} from '@ant-design/icons'; +import { useTranslation } from 'react-i18next'; +import { ClipboardManager, FileManager } from '@/utils'; +import { formatTunnelConfigMeta } from '@/lib/inbounds/label'; +import { QrPanel } from '@/pages/inbounds/qr'; +import PromptModal from '@/components/feedback/PromptModal'; +import type { useClientWireguardDevices } from '@/hooks/useClientWireguardDevices'; +import type { buildWireguardDeviceConfigs } from './wireguardConfig'; + +type DevicesState = ReturnType; + +export default function ClientWireguardDevices({ + state, + subLink, + clientEmail, + configs, +}: { + state: DevicesState; + subLink: string; + clientEmail: string; + configs: ReturnType; +}) { + const { t } = useTranslation(); + const [modal, modalContext] = Modal.useModal(); + const [messageApi, messageContext] = message.useMessage(); + const [prompt, setPrompt] = useState<{ id: string; name: string } | null>(null); + const deviceCount = state.data?.inbounds[0]?.devices.length ?? 0; + + async function copy(text: string) { + if (await ClipboardManager.copyText(text)) messageApi.success(t('copied')); + } + + function copySubscription(id: string) { + const url = new URL(subLink, window.location.href); + if (id !== 'primary') url.searchParams.set('wgDevice', id); + void copy(url.toString()); + } + + return ( + <> + {modalContext} + {messageContext} + {t('pages.clients.wgDevices.title')} + {configs.map((config) => { + const { inbound, deviceId, deviceName, text, enabled } = config; + const name = deviceName || t('pages.clients.wgDevices.primary'); + const meta = formatTunnelConfigMeta(inbound, clientEmail, configs.length, config.endpoint); + const label = + meta.label || [inbound.remark || inbound.tag, name].filter(Boolean).join(' · '); + const device = state.data?.inbounds + .find((entry) => entry.inboundId === inbound.id) + ?.devices.find((entry) => entry.id === deviceId); + const items = [ + ...(deviceId !== 'primary' + ? [ + { key: 'rename', label: t('edit') }, + { + key: 'enable', + label: t('pages.clients.wgDevices.enabled'), + icon: device?.enable ? : null, + }, + ] + : []), + ...(subLink + ? [{ key: 'subscription', label: t('pages.clients.wgDevices.subscription') }] + : []), + ...(deviceId !== 'primary' + ? [{ key: 'delete', label: t('pages.clients.wgDevices.remove'), danger: true }] + : []), + ]; + return ( +
+ + + WG + + + + {label} + +
+ +
+
+ ); + })} + + {state.error && } + {state.mutationError && } + setPrompt(null)} + onConfirm={(value) => { + const name = value.trim(); + if (!name || !prompt) return; + if (prompt.id) state.update(prompt.id, { name }); + else state.create(name); + setPrompt(null); + }} + /> + + ); +} diff --git a/frontend/src/pages/clients/wireguardConfig.ts b/frontend/src/pages/clients/wireguardConfig.ts index a58297d3e..c4a5b277e 100644 --- a/frontend/src/pages/clients/wireguardConfig.ts +++ b/frontend/src/pages/clients/wireguardConfig.ts @@ -1,3 +1,4 @@ +import { tunnelConfigEndpoints, tunnelEndpointLabel } from './tunnelEndpoints'; import type { HostEndpoint } from '@/lib/hosts/host-link'; import { formatInboundLabel } from '@/lib/inbounds/label'; import { joinConfLines } from '@/lib/xray/conf-lines'; @@ -57,3 +58,60 @@ export function buildWireguardClientConfig( lines.push(`PersistentKeepalive = ${client.keepAlive}`); return joinConfLines(lines); } + +export function buildWireguardDeviceConfigs( + client: ClientRecord, + inbounds: InboundOption[], + devices: import('@/schemas/client').WireguardDevices | undefined, + addresses: Record | undefined, + hosts: import('@/schemas/api/host').HostRecord[], + host: string, + publicHost: string, + includeDisabled = false, +) { + return inbounds.flatMap((inbound) => { + const entries = devices?.inbounds.find((entry) => entry.inboundId === inbound.id)?.devices; + const identities = entries + ? entries + .filter((device) => includeDisabled || device.enable) + .map((device) => ({ + id: device.id, + name: device.name, + enabled: device.enable, + client: { + ...client, + privateKey: device.privateKey, + publicKey: device.publicKey, + preSharedKey: device.preSharedKey, + allowedIPs: device.allowedIPs.join(', '), + }, + address: device.allowedIPs.join(', '), + })) + : [ + { + id: 'primary', + name: '', + enabled: client.enable !== false, + client, + address: addresses?.[inbound.id] ?? '', + }, + ]; + return identities.flatMap((device) => + tunnelConfigEndpoints(inbound, hosts, host, publicHost).map((endpoint) => ({ + inbound, + deviceId: device.id, + deviceName: device.name, + enabled: device.enabled, + endpoint: [device.name, tunnelEndpointLabel(endpoint)].filter(Boolean).join(' - '), + text: buildWireguardClientConfig( + device.client, + inbound, + host, + publicHost, + device.address, + endpoint, + ), + })), + ); + }); +} diff --git a/frontend/src/schemas/client.ts b/frontend/src/schemas/client.ts index d777e82bf..77c14623b 100644 --- a/frontend/src/schemas/client.ts +++ b/frontend/src/schemas/client.ts @@ -51,6 +51,8 @@ export const ClientRecordSchema = z inboundIds: nullableNumberArray.optional(), traffic: ClientTrafficSchema.nullable().optional(), reverse: z.object({ tag: z.string().optional() }).loose().nullable().optional(), + wireguardDevices: z.array(z.unknown()).nullable().optional(), + wgDeviceLimit: z.number().int().optional(), privateKey: z.string().optional(), publicKey: z.string().optional(), allowedIPs: z.string().optional(), @@ -427,3 +429,26 @@ export type ClientBulkAddFormValues = z.infer; export type ClientBulkAdjustFormValues = z.infer; export type ClientFormValues = z.infer; export type GroupSummary = z.infer; + +export const WireguardDeviceSchema = z.object({ + id: z.string(), + name: z.string(), + enable: z.boolean(), + privateKey: z.string(), + publicKey: z.string(), + allowedIPs: z.array(z.string()), + preSharedKey: z.string().optional().default(''), +}); + +export const WireguardDevicesSchema = z.object({ + limit: z.number().int(), + inbounds: z.array( + z.object({ + inboundId: z.number().int(), + devices: z.array(WireguardDeviceSchema), + }), + ), +}); + +export type WireguardDevice = z.infer; +export type WireguardDevices = z.infer; diff --git a/frontend/src/test/client-form-wireguard-devices.test.tsx b/frontend/src/test/client-form-wireguard-devices.test.tsx new file mode 100644 index 000000000..fdbcd7ffb --- /dev/null +++ b/frontend/src/test/client-form-wireguard-devices.test.tsx @@ -0,0 +1,93 @@ +import { describe, it, expect, vi } from 'vitest'; +import { fireEvent, screen, waitFor } from '@testing-library/react'; + +import ClientFormModal from '@/pages/clients/ClientFormModal'; +import type { ClientRecord, InboundOption } from '@/hooks/useClients'; +import { renderWithProviders } from './test-utils'; + +const WIREGUARD_INBOUND = { + id: 7, + port: 51820, + protocol: 'wireguard', + tag: 'wireguard-test', + enable: true, +} as InboundOption; + +const CLIENT = { + email: 'wireguard-user', + uuid: '11111111-1111-1111-1111-111111111111', + subId: 'wireguard-sub', + enable: true, +} as ClientRecord; + +function renderForm(client: ClientRecord | null, inbound = WIREGUARD_INBOUND) { + const save = vi.fn().mockResolvedValue({ success: true }); + renderWithProviders( + {}} + />, + ); + return save; +} + +describe('ClientFormModal WireGuard device limit', () => { + it('saves the chosen limit through the normal client update', async () => { + const save = renderForm({ ...CLIENT, wgDeviceLimit: 8 }); + const input = await screen.findByRole('spinbutton', { name: 'WireGuard · Device limit' }); + expect((input as HTMLInputElement).value).toBe('8'); + fireEvent.change(input, { target: { value: '12' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(save).toHaveBeenCalled()); + expect(save.mock.calls[0][0]).toHaveProperty('wgDeviceLimit', 12); + }); + + it('defaults legacy clients to five devices', async () => { + const save = renderForm(CLIENT); + const input = await screen.findByRole('spinbutton', { name: 'WireGuard · Device limit' }); + expect((input as HTMLInputElement).value).toBe('5'); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(save).toHaveBeenCalled()); + expect(save.mock.calls[0][0]).toHaveProperty('wgDeviceLimit', 5); + }); + + it('includes the limit when creating a WireGuard client', async () => { + const save = renderForm(null); + fireEvent.click(screen.getByRole('button', { name: 'Select all' })); + const input = await screen.findByRole('spinbutton', { name: 'WireGuard · Device limit' }); + expect((input as HTMLInputElement).value).toBe('5'); + fireEvent.change(input, { target: { value: '4' } }); + fireEvent.click(screen.getByRole('button', { name: 'Create' })); + await waitFor(() => expect(save).toHaveBeenCalled()); + expect(save.mock.calls[0][0]).toHaveProperty('client.wgDeviceLimit', 4); + }); + + it('keeps the limit above the existing device count', async () => { + renderForm({ ...CLIENT, wgDeviceLimit: 6, wireguardDevices: [{}, {}] }); + const input = await screen.findByRole('spinbutton', { name: 'WireGuard · Device limit' }); + expect(input.getAttribute('aria-valuemin')).toBe('3'); + expect(input.getAttribute('aria-valuemax')).toBe('32'); + }); + + it('requires a limit before saving', async () => { + const save = renderForm({ ...CLIENT, wgDeviceLimit: 6, wireguardDevices: [{}, {}] }); + const input = await screen.findByRole('spinbutton', { name: 'WireGuard · Device limit' }); + fireEvent.change(input, { target: { value: '' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await screen.findByText('Device limit (3–32)'); + expect(save).not.toHaveBeenCalled(); + }); + + it('hides the setting for clients attached only to other protocols', async () => { + const save = renderForm(CLIENT, { ...WIREGUARD_INBOUND, protocol: 'vless' }); + expect(screen.queryByRole('spinbutton', { name: 'WireGuard · Device limit' })).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(save).toHaveBeenCalled()); + expect(save.mock.calls[0][0]).not.toHaveProperty('wgDeviceLimit'); + }); +}); diff --git a/frontend/src/test/multi-tunnel-client-config.test.tsx b/frontend/src/test/multi-tunnel-client-config.test.tsx index d7b34eebf..f384be774 100644 --- a/frontend/src/test/multi-tunnel-client-config.test.tsx +++ b/frontend/src/test/multi-tunnel-client-config.test.tsx @@ -135,7 +135,7 @@ describe('Multi-tunnel Client Modals', () => { expect(document.querySelectorAll('.config-block')).toHaveLength(2); }); - it('renders distinct labeled ConfigBlocks in ClientInfoModal for multiple WireGuard inbounds', () => { + it('renders distinct labeled connection rows in ClientInfoModal for multiple WireGuard inbounds', () => { renderWithProviders( { expect(screen.getAllByText('US · New York')).toHaveLength(2); expect(screen.getByText('EU · Frankfurt')).toBeTruthy(); - expect(document.querySelectorAll('.config-block')).toHaveLength(2); + expect(document.querySelectorAll('.link-row')).toHaveLength(2); }); it('renders single default-labeled ConfigBlock in ClientInfoModal for single inbound', () => { diff --git a/frontend/src/test/wireguard-client-config.test.ts b/frontend/src/test/wireguard-client-config.test.ts index 2796fbae9..2a079ee72 100644 --- a/frontend/src/test/wireguard-client-config.test.ts +++ b/frontend/src/test/wireguard-client-config.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest'; -import { buildWireguardClientConfig } from '@/pages/clients/wireguardConfig'; +import { + buildWireguardClientConfig, + buildWireguardDeviceConfigs, +} from '@/pages/clients/wireguardConfig'; import type { ClientRecord, InboundOption } from '@/hooks/useClients'; const client: ClientRecord = { @@ -125,3 +128,141 @@ describe('buildWireguardClientConfig', () => { expect(cfg).not.toContain('Endpoint = :51820'); }); }); + +describe('buildWireguardDeviceConfigs', () => { + it('keeps device keys and per-inbound addresses separate', () => { + const devices = { + limit: 5, + inbounds: [ + { + inboundId: 90, + devices: [ + { + id: 'primary', + name: 'Primary', + enable: true, + privateKey: 'primary-key', + publicKey: 'pub1', + preSharedKey: '', + allowedIPs: ['10.0.0.2/32'], + }, + { + id: 'phone', + name: 'Phone', + enable: true, + privateKey: 'phone-key', + publicKey: 'pub2', + preSharedKey: 'phone-psk', + allowedIPs: ['10.0.0.3/32'], + }, + { + id: 'disabled', + name: 'Disabled', + enable: false, + privateKey: 'disabled-key', + publicKey: 'pub3', + preSharedKey: '', + allowedIPs: ['10.0.0.4/32'], + }, + ], + }, + ], + }; + const configs = buildWireguardDeviceConfigs( + client, + [inbound], + devices, + { 90: '10.0.0.99/32' }, + [], + 'example.com', + '', + ); + expect(configs).toHaveLength(2); + expect(configs[0].text).toContain('PrivateKey = primary-key'); + expect(configs[0].text).toContain('Address = 10.0.0.2/32'); + expect(configs[1].text).toContain('PrivateKey = phone-key'); + expect(configs[1].text).toContain('Address = 10.0.0.3/32'); + expect(configs[1].text).toContain('PresharedKey = phone-psk'); + expect(configs[1].deviceId).toBe('phone'); + expect(configs[1].endpoint).toContain('Phone'); + }); + + it('preserves the existing configuration until the device list is available', () => { + const configs = buildWireguardDeviceConfigs( + client, + [inbound], + undefined, + { 90: '10.0.0.8/32' }, + [], + 'example.com', + '', + ); + expect(configs).toHaveLength(1); + expect(configs[0].deviceId).toBe('primary'); + expect(configs[0].text).toContain(`PrivateKey = ${client.privateKey}`); + expect(configs[0].text).toContain('Address = 10.0.0.8/32'); + }); + + it('does not substitute a primary config for an inbound with no devices', () => { + const configs = buildWireguardDeviceConfigs( + client, + [inbound], + { limit: 5, inbounds: [{ inboundId: 90, devices: [] }] }, + undefined, + [], + 'example.com', + '', + ); + expect(configs).toEqual([]); + }); + + it('includes the primary config of a disabled client when requested', () => { + const disabledClient = { ...client, enable: false }; + const devices = { + limit: 5, + inbounds: [ + { + inboundId: 90, + devices: [ + { + id: 'primary', + name: '', + enable: false, + privateKey: 'disabled-key', + publicKey: 'disabled-public-key', + preSharedKey: '', + allowedIPs: ['10.0.0.4/32'], + }, + ], + }, + ], + }; + + expect( + buildWireguardDeviceConfigs( + disabledClient, + [inbound], + devices, + undefined, + [], + 'example.com', + '', + ), + ).toEqual([]); + + const configs = buildWireguardDeviceConfigs( + disabledClient, + [inbound], + devices, + undefined, + [], + 'example.com', + '', + true, + ); + expect(configs).toHaveLength(1); + expect(configs[0]).toMatchObject({ deviceId: 'primary', enabled: false }); + expect(configs[0].text).toContain('PrivateKey = disabled-key'); + expect(configs[0].text).toContain('Address = 10.0.0.4/32'); + }); +}); diff --git a/frontend/src/test/wireguard-devices.test.tsx b/frontend/src/test/wireguard-devices.test.tsx new file mode 100644 index 000000000..ebaba7d81 --- /dev/null +++ b/frontend/src/test/wireguard-devices.test.tsx @@ -0,0 +1,102 @@ +import { fireEvent, render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import ClientWireguardDevices from '@/pages/clients/ClientWireguardDevices'; +import { buildWireguardDeviceConfigs } from '@/pages/clients/wireguardConfig'; +import type { InboundOption } from '@/hooks/useClients'; + +vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) })); + +function deviceState() { + return { + data: { + limit: 2, + inbounds: [ + { + inboundId: 90, + devices: [ + { + id: 'primary', + name: '', + enable: true, + privateKey: 'key', + publicKey: 'pub', + preSharedKey: '', + allowedIPs: ['10.0.0.2/32'], + }, + { + id: 'phone', + name: 'Phone', + enable: false, + privateKey: 'key2', + publicKey: 'pub2', + preSharedKey: '', + allowedIPs: ['10.0.0.3/32'], + }, + ], + }, + ], + }, + loading: false, + error: null, + pending: false, + mutationError: null, + create: vi.fn(), + update: vi.fn(), + remove: vi.fn(), + setLimit: vi.fn(), + }; +} + +function showDevices(state = deviceState()) { + const configs = buildWireguardDeviceConfigs( + { email: 'alexander' }, + [{ id: 90, protocol: 'wireguard', port: 51820, tag: 'WG' } as InboundOption], + state.data, + undefined, + [], + 'localhost', + '', + true, + ); + render( + , + ); +} + +describe('WireGuard device rows', () => { + it('allows reenabling an additional device from its row menu', async () => { + const state = deviceState(); + showDevices(state); + fireEvent.click(screen.getByRole('button', { name: 'Phone more' })); + fireEvent.click( + await screen.findByRole('menuitem', { name: 'pages.clients.wgDevices.enabled' }), + ); + expect(state.update).toHaveBeenCalledWith('phone', { enable: true }); + }); + + it('keeps the limit editor out of the card and disables connections for disabled devices', () => { + showDevices(); + expect(screen.queryByRole('spinbutton')).toBeNull(); + expect( + screen.getByRole('button', { name: /pages.clients.wgDevices.add/ }).hasAttribute('disabled'), + ).toBe(true); + expect( + screen + .getByRole('button', { name: 'pages.clients.wgDevices.primary copy' }) + .hasAttribute('disabled'), + ).toBe(false); + expect(screen.getByRole('button', { name: 'Phone copy' }).hasAttribute('disabled')).toBe(true); + }); + + it('creates a named device through the platform prompt dialog', async () => { + const state = deviceState(); + state.data.limit = 3; + showDevices(state); + fireEvent.click(screen.getByRole('button', { name: /pages.clients.wgDevices.add/ })); + fireEvent.change(await screen.findByRole('textbox', { name: 'pages.clients.wgDevices.name' }), { + target: { value: 'Laptop' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'confirm' })); + expect(state.create).toHaveBeenCalledWith('Laptop'); + }); +}); diff --git a/internal/database/model/model-wireguard-devices.go b/internal/database/model/model-wireguard-devices.go new file mode 100644 index 000000000..ec7c2b546 --- /dev/null +++ b/internal/database/model/model-wireguard-devices.go @@ -0,0 +1,73 @@ +package model + +import "slices" + +const ( + DefaultWireguardDeviceLimit = 5 + MaxWireguardDevices = 32 +) + +// WireguardDevice is an additional peer sharing its client's quota and lifecycle. +// The original client credentials remain the primary device for compatibility. +type WireguardDevice struct { + Id string `json:"id"` + Name string `json:"name"` + Enable bool `json:"enable"` + PrivateKey string `json:"privateKey"` + PublicKey string `json:"publicKey"` + PreSharedKey string `json:"preSharedKey,omitempty"` + AllowedIPs []string `json:"allowedIPs"` +} + +func CloneWireguardDevices(devices []WireguardDevice) []WireguardDevice { + result := slices.Clone(devices) + for i := range result { + result[i].AllowedIPs = slices.Clone(result[i].AllowedIPs) + } + return result +} + +func EffectiveWireguardDeviceLimit(limit int) int { + if limit <= 0 { + return DefaultWireguardDeviceLimit + } + return limit +} + +// WireguardClients expands enabled peers while retaining parent attribution. +// Callers enforce the parent client's enable and traffic/expiry limits. +func WireguardClients(c Client) []Client { + devices := c.WireguardDevices + c.WireguardDevices = nil + clients := []Client{c} + for _, device := range devices { + if !device.Enable { + continue + } + peer := c + peer.PrivateKey = device.PrivateKey + peer.PublicKey = device.PublicKey + peer.PreSharedKey = device.PreSharedKey + peer.AllowedIPs = slices.Clone(device.AllowedIPs) + clients = append(clients, peer) + } + return clients +} + +func WireguardPeersFromClient(c Client) []any { + clients := WireguardClients(c) + peers := make([]any, 0, len(clients)) + for _, client := range clients { + peers = append(peers, WireguardPeerFromClient(client)) + } + return peers +} + +// WireguardAllowedIPs includes disabled devices because their IPs stay reserved. +func WireguardAllowedIPs(c Client) []string { + addresses := slices.Clone(c.AllowedIPs) + for _, device := range c.WireguardDevices { + addresses = append(addresses, device.AllowedIPs...) + } + return addresses +} diff --git a/internal/database/model/model.go b/internal/database/model/model.go index d555d0930..e9c3ce0ac 100644 --- a/internal/database/model/model.go +++ b/internal/database/model/model.go @@ -584,7 +584,7 @@ func WireguardClientsToPeers(settings string) (string, bool) { if err := json.Unmarshal(encoded, &c); err != nil { continue } - peers = append(peers, WireguardPeerFromClient(c)) + peers = append(peers, WireguardPeersFromClient(c)...) } delete(parsed, "clients") parsed["peers"] = peers @@ -982,15 +982,17 @@ type ClientReverse struct { // Client represents a client configuration for Xray inbounds with traffic limits and settings. type Client struct { - ID string `json:"id,omitempty"` // Unique client identifier - Security string `json:"security"` // Security method (e.g., "auto", "aes-128-gcm") - Password string `json:"password,omitempty"` // Client password - Flow string `json:"flow,omitempty"` // Flow control (XTLS) - Reverse *ClientReverse `json:"reverse,omitempty"` // VLESS simple reverse proxy settings - Auth string `json:"auth,omitempty"` // Auth password (Hysteria) - PrivateKey string `json:"privateKey,omitempty"` - PublicKey string `json:"publicKey,omitempty"` - AllowedIPs []string `json:"allowedIPs,omitempty"` + ID string `json:"id,omitempty"` // Unique client identifier + Security string `json:"security"` // Security method (e.g., "auto", "aes-128-gcm") + Password string `json:"password,omitempty"` // Client password + Flow string `json:"flow,omitempty"` // Flow control (XTLS) + Reverse *ClientReverse `json:"reverse,omitempty"` // VLESS simple reverse proxy settings + Auth string `json:"auth,omitempty"` // Auth password (Hysteria) + WireguardDevices []WireguardDevice `json:"wireguardDevices,omitempty"` + WgDeviceLimit int `json:"wgDeviceLimit,omitempty"` + PrivateKey string `json:"privateKey,omitempty"` + PublicKey string `json:"publicKey,omitempty"` + AllowedIPs []string `json:"allowedIPs,omitempty"` // ClientHostRuleIds binds the client to these host rules, one link each; nil preserves, empty // clears, and bindings with no usable host leave that inbound out of the subscription. ClientHostRuleIds []int `json:"clientHostRuleIds,omitempty" example:"[1,2]"` @@ -1028,42 +1030,44 @@ type Client struct { } type ClientRecord struct { - Id int `json:"id" gorm:"primaryKey;autoIncrement"` - Email string `json:"email" gorm:"uniqueIndex;not null"` - SubID string `json:"subId" gorm:"index;column:sub_id"` - UUID string `json:"uuid" gorm:"column:uuid"` - Password string `json:"password"` - Auth string `json:"auth"` - Flow string `json:"flow"` - Security string `json:"security"` - Reverse string `json:"reverse" gorm:"column:reverse"` - ClientHostRuleIds []int `json:"clientHostRuleIds,omitempty" gorm:"serializer:json;column:client_host_rule_ids" example:"[1,2]"` - PrivateKey string `json:"privateKey" gorm:"column:wg_private_key"` - PublicKey string `json:"publicKey" gorm:"column:wg_public_key"` - AllowedIPs string `json:"allowedIPs" gorm:"column:wg_allowed_ips"` - PreSharedKey string `json:"preSharedKey" gorm:"column:wg_pre_shared_key"` - KeepAlive KeepAliveValue `json:"keepAlive" gorm:"-"` // Numeric values or AmneziaWG ranges. - KeepAliveLegacy int `json:"-" gorm:"column:wg_keep_alive;default:0"` - KeepAliveRange KeepAliveValue `json:"-" gorm:"column:wg_keep_alive_range;type:text;default:''"` - ForwardedPorts string `json:"forwardedPorts" gorm:"column:wg_forwarded_ports"` - Secret string `json:"secret" gorm:"column:secret"` - AdTag string `json:"adTag" gorm:"column:ad_tag;default:''"` - LimitIP int `json:"limitIp" gorm:"column:limit_ip"` - LimitHwid int `json:"limitHwid" gorm:"column:limit_hwid;default:0"` - TotalGB int64 `json:"totalGB" gorm:"column:total_gb"` - ExpiryTime int64 `json:"expiryTime" gorm:"column:expiry_time"` - Enable bool `json:"enable" gorm:"default:true"` - TgID int64 `json:"tgId" gorm:"column:tg_id;index:idx_clients_tg_id"` - Group string `json:"group" gorm:"column:group_name;default:'';index:idx_client_record_group"` - Comment string `json:"comment"` - Reset int `json:"reset" gorm:"default:0"` - ResetDay int `json:"resetDay" gorm:"column:reset_day;default:0"` - ResetWeekday int `json:"resetWeekday" gorm:"column:reset_weekday;default:0"` - ResetMax int `json:"resetMax" gorm:"column:reset_max;default:0"` - TrafficReset string `json:"trafficReset" gorm:"column:traffic_reset;default:never;index:idx_clients_traffic_reset"` - TrafficResetDay int `json:"trafficResetDay" gorm:"column:traffic_reset_day;default:1"` - CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"` - UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"` + Id int `json:"id" gorm:"primaryKey;autoIncrement"` + Email string `json:"email" gorm:"uniqueIndex;not null"` + SubID string `json:"subId" gorm:"index;column:sub_id"` + UUID string `json:"uuid" gorm:"column:uuid"` + Password string `json:"password"` + Auth string `json:"auth"` + Flow string `json:"flow"` + Security string `json:"security"` + Reverse string `json:"reverse" gorm:"column:reverse"` + ClientHostRuleIds []int `json:"clientHostRuleIds,omitempty" gorm:"serializer:json;column:client_host_rule_ids" example:"[1,2]"` + WireguardDevices []WireguardDevice `json:"wireguardDevices" gorm:"serializer:json;column:wg_devices"` + WgDeviceLimit int `json:"wgDeviceLimit" gorm:"column:wg_device_limit;default:0"` + PrivateKey string `json:"privateKey" gorm:"column:wg_private_key"` + PublicKey string `json:"publicKey" gorm:"column:wg_public_key"` + AllowedIPs string `json:"allowedIPs" gorm:"column:wg_allowed_ips"` + PreSharedKey string `json:"preSharedKey" gorm:"column:wg_pre_shared_key"` + KeepAlive KeepAliveValue `json:"keepAlive" gorm:"-"` // Numeric values or AmneziaWG ranges. + KeepAliveLegacy int `json:"-" gorm:"column:wg_keep_alive;default:0"` + KeepAliveRange KeepAliveValue `json:"-" gorm:"column:wg_keep_alive_range;type:text;default:''"` + ForwardedPorts string `json:"forwardedPorts" gorm:"column:wg_forwarded_ports"` + Secret string `json:"secret" gorm:"column:secret"` + AdTag string `json:"adTag" gorm:"column:ad_tag;default:''"` + LimitIP int `json:"limitIp" gorm:"column:limit_ip"` + LimitHwid int `json:"limitHwid" gorm:"column:limit_hwid;default:0"` + TotalGB int64 `json:"totalGB" gorm:"column:total_gb"` + ExpiryTime int64 `json:"expiryTime" gorm:"column:expiry_time"` + Enable bool `json:"enable" gorm:"default:true"` + TgID int64 `json:"tgId" gorm:"column:tg_id;index:idx_clients_tg_id"` + Group string `json:"group" gorm:"column:group_name;default:'';index:idx_client_record_group"` + Comment string `json:"comment"` + Reset int `json:"reset" gorm:"default:0"` + ResetDay int `json:"resetDay" gorm:"column:reset_day;default:0"` + ResetWeekday int `json:"resetWeekday" gorm:"column:reset_weekday;default:0"` + ResetMax int `json:"resetMax" gorm:"column:reset_max;default:0"` + TrafficReset string `json:"trafficReset" gorm:"column:traffic_reset;default:never;index:idx_clients_traffic_reset"` + TrafficResetDay int `json:"trafficResetDay" gorm:"column:traffic_reset_day;default:1"` + CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"` + UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime:milli"` // Owned solely by the node-snapshot sweep, which soft-orphans instead of // deleting; orphans from any other cause stay at zero and are never reaped. SyncOrphanedAt int64 `json:"-" gorm:"column:sync_orphaned_at;default:0"` @@ -1370,14 +1374,16 @@ func (c *Client) ToRecord() *ClientRecord { CreatedAt: c.CreatedAt, UpdatedAt: c.UpdatedAt, - PrivateKey: c.PrivateKey, - PublicKey: c.PublicKey, - AllowedIPs: strings.Join(c.AllowedIPs, ","), - PreSharedKey: c.PreSharedKey, - KeepAlive: keepAliveValue(c.KeepAlive), - ForwardedPorts: c.ForwardedPortsSpec(), - Secret: c.Secret, - AdTag: c.AdTag, + WireguardDevices: CloneWireguardDevices(c.WireguardDevices), + WgDeviceLimit: c.WgDeviceLimit, + PrivateKey: c.PrivateKey, + PublicKey: c.PublicKey, + AllowedIPs: strings.Join(c.AllowedIPs, ","), + PreSharedKey: c.PreSharedKey, + KeepAlive: keepAliveValue(c.KeepAlive), + ForwardedPorts: c.ForwardedPortsSpec(), + Secret: c.Secret, + AdTag: c.AdTag, } if c.Reverse != nil { if b, err := json.Marshal(c.Reverse); err == nil { @@ -1430,14 +1436,16 @@ func (r *ClientRecord) ToClient() *Client { CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt, - PrivateKey: r.PrivateKey, - PublicKey: r.PublicKey, - AllowedIPs: splitWireguardAllowedIPs(r.AllowedIPs), - PreSharedKey: r.PreSharedKey, - KeepAlive: keepAlivePtr(r.KeepAlive), - ForwardedPorts: nonEmptyForwardedPorts(r.ForwardedPorts), - Secret: r.Secret, - AdTag: r.AdTag, + WireguardDevices: CloneWireguardDevices(r.WireguardDevices), + WgDeviceLimit: r.WgDeviceLimit, + PrivateKey: r.PrivateKey, + PublicKey: r.PublicKey, + AllowedIPs: splitWireguardAllowedIPs(r.AllowedIPs), + PreSharedKey: r.PreSharedKey, + KeepAlive: keepAlivePtr(r.KeepAlive), + ForwardedPorts: nonEmptyForwardedPorts(r.ForwardedPorts), + Secret: r.Secret, + AdTag: r.AdTag, } if r.Reverse != "" { var rev ClientReverse @@ -1711,6 +1719,12 @@ func MergeClientRecord(existing *ClientRecord, incoming *ClientRecord) []ClientM existing.Reverse = incoming.Reverse } } + if incoming.WireguardDevices != nil && (incomingNewer || existing.WireguardDevices == nil) { + existing.WireguardDevices = CloneWireguardDevices(incoming.WireguardDevices) + } + if incoming.WgDeviceLimit > 0 && (incomingNewer || existing.WgDeviceLimit == 0) { + existing.WgDeviceLimit = incoming.WgDeviceLimit + } if existing.PrivateKey != incoming.PrivateKey && incoming.PrivateKey != "" { if incomingNewer || existing.PrivateKey == "" { existing.PrivateKey = incoming.PrivateKey diff --git a/internal/database/model/model_wireguard_devices_test.go b/internal/database/model/model_wireguard_devices_test.go new file mode 100644 index 000000000..11997c9cd --- /dev/null +++ b/internal/database/model/model_wireguard_devices_test.go @@ -0,0 +1,66 @@ +package model + +import ( + "encoding/json" + "reflect" + "testing" +) + +func TestWireguardDevicesRoundTripAndClone(t *testing.T) { + client := Client{Email: "owner", WgDeviceLimit: 3, WireguardDevices: []WireguardDevice{{Id: "device", Name: "Phone", Enable: true, PrivateKey: "private", PublicKey: "public", AllowedIPs: []string{"10.0.0.3/32"}}}} + record := client.ToRecord() + if got := record.ToClient(); !reflect.DeepEqual(got.WireguardDevices, client.WireguardDevices) || got.WgDeviceLimit != 3 { + t.Fatalf("round trip lost devices: %+v", got) + } + record.WireguardDevices[0].AllowedIPs[0] = "10.0.0.4/32" + if client.WireguardDevices[0].AllowedIPs[0] != "10.0.0.3/32" { + t.Fatal("ToRecord shares device addresses") + } + if CloneWireguardDevices(nil) != nil || CloneWireguardDevices([]WireguardDevice{}) == nil { + t.Fatal("clone lost nil versus explicit empty distinction") + } +} + +func TestWireguardDevicesExpandCorePeers(t *testing.T) { + client := Client{Email: "owner", Enable: true, PublicKey: "primary", AllowedIPs: []string{"10.0.0.2/32"}, WireguardDevices: []WireguardDevice{ + {Id: "phone", Name: "Phone", Enable: true, PrivateKey: "secret", PublicKey: "phone-public", AllowedIPs: []string{"10.0.0.3/32"}}, + {Id: "laptop", Name: "Laptop", Enable: false, PublicKey: "laptop-public", AllowedIPs: []string{"10.0.0.4/32"}}, + }} + encoded, err := json.Marshal(map[string]any{"clients": []Client{client}}) + if err != nil { + t.Fatal(err) + } + converted, ok := WireguardClientsToPeers(string(encoded)) + if !ok { + t.Fatal("settings did not convert") + } + var settings struct { + Peers []map[string]any `json:"peers"` + } + if err := json.Unmarshal([]byte(converted), &settings); err != nil { + t.Fatal(err) + } + if len(settings.Peers) != 2 || settings.Peers[1]["publicKey"] != "phone-public" { + t.Fatalf("unexpected peers: %+v", settings.Peers) + } + for _, peer := range settings.Peers { + if peer["email"] != client.Email || peer["privateKey"] != nil || peer["wireguardDevices"] != nil { + t.Fatalf("peer leaked credentials or lost parent attribution: %+v", peer) + } + } + if got := WireguardAllowedIPs(client); len(got) != 3 { + t.Fatalf("disabled device address was not reserved: %v", got) + } +} + +func TestWireguardDeviceMergePreservesOmittedAndClearsExplicitEmpty(t *testing.T) { + existing := ClientRecord{Email: "owner", UpdatedAt: 10, WgDeviceLimit: 3, WireguardDevices: []WireguardDevice{{Id: "phone"}}} + MergeClientRecord(&existing, &ClientRecord{Email: "owner", UpdatedAt: 20}) + if len(existing.WireguardDevices) != 1 || existing.WgDeviceLimit != 3 { + t.Fatal("older snapshot erased devices") + } + MergeClientRecord(&existing, &ClientRecord{Email: "owner", UpdatedAt: 30, WgDeviceLimit: 2, WireguardDevices: []WireguardDevice{}}) + if existing.WireguardDevices == nil || len(existing.WireguardDevices) != 0 || existing.WgDeviceLimit != 2 { + t.Fatal("explicit empty snapshot failed to clear devices") + } +} diff --git a/internal/sub/clash_service.go b/internal/sub/clash_service.go index 3291fd8a7..7f73aff56 100644 --- a/internal/sub/clash_service.go +++ b/internal/sub/clash_service.go @@ -62,7 +62,7 @@ func (s *SubClashService) getClash(subId string, host string, legacy bool) (stri seenEmails := make(map[string]struct{}) for _, inbound := range inbounds { - clients := subReq.matchingClients(inbound, subId) + clients := subReq.matchingWireguardDeviceClients(inbound, subId) if len(clients) == 0 { continue } @@ -120,6 +120,9 @@ func (s *SubClashService) getClash(subId string, host string, legacy bool) (stri proxies = append(proxies, render()...) } } + if err := subReq.validateWireguardDevice(); err != nil { + return "", "", err + } for _, ext := range externalLinks { if ext.Enable { hasEnabledClient = true diff --git a/internal/sub/controller.go b/internal/sub/controller.go index ac077857f..098ae568d 100644 --- a/internal/sub/controller.go +++ b/internal/sub/controller.go @@ -40,7 +40,7 @@ const ( // client, never-existed id) and becomes 404. A real error becomes 500. No // body — VPN clients only look at the status. func writeSubError(c *gin.Context, err error) { - if err == nil { + if err == nil || errors.Is(err, errWireguardDeviceUnavailable) { c.Status(http.StatusNotFound) return } @@ -460,6 +460,7 @@ func (a *SUBController) buildSubPageData(c *gin.Context) (PageData, bool) { subId := c.Param("subid") _, host, _, hostHeader := a.subService.ResolveRequest(c) subReq := a.subService.ForRequest(host) + subReq.wireguardDevice = c.Query("wgDevice") subReq.subscriptionBody = false subs, emails, lastOnline, traffic, err := subReq.getSubs(subId) if err != nil || subs == nil { @@ -534,6 +535,7 @@ func (a *SUBController) subs(c *gin.Context) { subId := c.Param("subid") scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c) subReq := a.subService.ForRequest(host) + subReq.wireguardDevice = c.Query("wgDevice") subReq.subscriptionBody = true subReq.omitServerDescription = !IsHappClient(userAgent) && !IsIncyClient(userAgent) subReq.ss2022Base64Userinfo = IsShadowrocketClient(userAgent) @@ -881,7 +883,7 @@ func (a *SUBController) serveJson(c *gin.Context, alwaysReturnArray bool, conten func (a *SUBController) serveJsonBody(c *gin.Context, alwaysReturnArray bool, contentType string, rawDownload bool) bool { subId := c.Param("subid") scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c) - jsonSub, header, err := a.subJsonService.GetJson(subId, host, alwaysReturnArray) + jsonSub, header, err := a.subJsonService.GetJson(subId, host, alwaysReturnArray, c.Query("wgDevice")) if err != nil { writeSubError(c, err) return true @@ -941,10 +943,12 @@ func (a *SUBController) serveClashBody(c *gin.Context, rawDownload bool, legacy scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c) var clashSub, header string var err error + clashService := *a.subClashService + clashService.SubService = a.subClashService.SubService.ForWireguardDevice(c.Query("wgDevice")) if legacy { - clashSub, header, err = a.subClashService.GetClashLegacy(subId, host) + clashSub, header, err = clashService.GetClashLegacy(subId, host) } else { - clashSub, header, err = a.subClashService.GetClash(subId, host) + clashSub, header, err = clashService.GetClash(subId, host) } if err != nil { if errors.Is(err, errNoLegacyClashProxies) { @@ -977,7 +981,11 @@ func (a *SUBController) serveClashBody(c *gin.Context, rawDownload bool, legacy func builtinProfileURL(c *gin.Context, scheme, hostWithPort string) string { // Drop download/format selectors so the opt-in link always opens the HTML page. - return fmt.Sprintf("%s://%s%s?html=1", scheme, hostWithPort, c.Request.URL.EscapedPath()) + profileURL := fmt.Sprintf("%s://%s%s?html=1", scheme, hostWithPort, c.Request.URL.EscapedPath()) + if device := c.Query("wgDevice"); device != "" { + profileURL += "&wgDevice=" + url.QueryEscape(device) + } + return profileURL } // ApplyCommonHeaders sets common HTTP headers for subscription responses including user info, update interval, and profile title. diff --git a/internal/sub/json_service.go b/internal/sub/json_service.go index dd2c37f81..6f6a64331 100644 --- a/internal/sub/json_service.go +++ b/internal/sub/json_service.go @@ -115,8 +115,11 @@ func (s *SubJsonService) bakedTemplate() map[string]any { } // GetJson generates a JSON subscription configuration for the given subscription ID and host. -func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bool) (string, string, error) { +func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bool, wireguardDevice ...string) (string, string, error) { subReq := s.SubService.ForRequest(host) + if len(wireguardDevice) > 0 { + subReq.wireguardDevice = wireguardDevice[0] + } subReq.subscriptionBody = true inbounds, err := subReq.getInboundsBySubId(subId) if err != nil { @@ -144,7 +147,7 @@ func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bo var hidden []subConfigEntry // Prepare Inbounds for _, inbound := range inbounds { - clients := subReq.matchingClients(inbound, subId) + clients := subReq.matchingWireguardDeviceClients(inbound, subId) if len(clients) == 0 { continue } @@ -239,6 +242,9 @@ func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bo } } } + if err := subReq.validateWireguardDevice(); err != nil { + return "", "", err + } entries = s.appendBalancerEntries(entries, hidden, balancers) // Inbounds arrive sorted by (sub_sort_index, id); balancers interleave by diff --git a/internal/sub/service.go b/internal/sub/service.go index a61935099..3333832f9 100644 --- a/internal/sub/service.go +++ b/internal/sub/service.go @@ -37,9 +37,11 @@ var salamanderWarningSeen sync.Map // SubService provides business logic for generating subscription links and managing subscription data. type SubService struct { - address string - remarkTemplate string - datepicker string + address string + remarkTemplate string + datepicker string + wireguardDevice string + wireguardDeviceSelected bool // subscriptionBody is true only when rendering the actual subscription // content a client app imports (raw /sub fetch, /json, /clash). The remark // template's per-client info is emitted there (on the first link); every @@ -133,6 +135,14 @@ func (s *SubService) ForRequest(host string) *SubService { return &req } +// ForWireguardDevice selects one device without changing the shared service. +// Empty and primary retain the existing subscription identity. +func (s *SubService) ForWireguardDevice(id string) *SubService { + req := *s + req.wireguardDevice = id + return &req +} + // PrepareForRequest sets per-request state (host + nodes map) on this // SubService instance. HTTP handlers should call ForRequest instead so the // controller's shared base service is never mutated by concurrent requests. @@ -157,6 +167,7 @@ func (s *SubService) PrepareForRequest(host string) { s.hostGroupOrders = nil s.sharedGroupSni = nil s.rendered = 0 + s.wireguardDeviceSelected = false mode, _ := s.settingService.GetSubHostSortMode() s.hostsFirst = mode == "hosts-first" s.loadNodes() @@ -466,6 +477,7 @@ func (s *SubService) overlayInboundTunnelIdentity(inbound *model.Inbound, client client.PrivateKey = peer.PrivateKey client.PublicKey = peer.PublicKey client.PreSharedKey = peer.PreSharedKey + client.WireguardDevices = peer.WireguardDevices // append onto nil copies a non-empty list and clears a shared address when settings omit one. client.AllowedIPs = append([]string(nil), peer.AllowedIPs...) if peer.KeepAlive == nil { @@ -579,7 +591,7 @@ func (s *SubService) getSubs(subId string) ([]string, []string, int64, xray.Clie seenEmails := make(map[string]struct{}) for _, inbound := range inbounds { - clients := s.matchingClients(inbound, subId) + clients := s.matchingWireguardDeviceClients(inbound, subId) if len(clients) == 0 { continue } @@ -649,6 +661,9 @@ func (s *SubService) getSubs(subId string) ([]string, []string, int64, xray.Clie } } } + if err := s.validateWireguardDevice(); err != nil { + return nil, nil, 0, traffic, err + } for _, ext := range externalLinks { if ext.Enable { hasEnabledClient = true @@ -3491,10 +3506,23 @@ func (s *SubService) extractBaseFromURI(uri string) string { // buildSingleURL constructs a single URL using configured URI or base components func (s *SubService) buildSingleURL(configuredURI, base, basePath, subId string) string { + var result string if configuredURI != "" { - return s.joinPathWithID(configuredURI, subId) + result = s.joinPathWithID(configuredURI, subId) + } else { + result = s.joinPathWithID(base+basePath, subId) } - return s.joinPathWithID(base+basePath, subId) + if s.wireguardDevice == "" { + return result + } + parsed, err := url.Parse(result) + if err != nil { + return result + } + query := parsed.Query() + query.Set("wgDevice", s.wireguardDevice) + parsed.RawQuery = query.Encode() + return parsed.String() } // joinPathWithID safely joins a base path with a subscription ID diff --git a/internal/sub/wireguard-device.go b/internal/sub/wireguard-device.go new file mode 100644 index 000000000..d47c16969 --- /dev/null +++ b/internal/sub/wireguard-device.go @@ -0,0 +1,58 @@ +package sub + +import ( + "errors" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +var errWireguardDeviceUnavailable = errors.New("wireguard device unavailable") + +func selectWireguardDevice(client model.Client, id string) (model.Client, error) { + if id == "" || id == "primary" { + return client, nil + } + for _, device := range client.WireguardDevices { + if device.Id != id { + continue + } + if !device.Enable { + return model.Client{}, errWireguardDeviceUnavailable + } + client.PrivateKey = device.PrivateKey + client.PublicKey = device.PublicKey + client.PreSharedKey = device.PreSharedKey + client.AllowedIPs = append([]string(nil), device.AllowedIPs...) + return client, nil + } + return model.Client{}, errWireguardDeviceUnavailable +} + +func (s *SubService) matchingWireguardDeviceClients(inbound *model.Inbound, subID string) []model.Client { + clients := s.matchingClients(inbound, subID) + if inbound.Protocol != model.WireGuard || s.wireguardDevice == "" || s.wireguardDevice == "primary" { + return clients + } + selectedClients := make([]model.Client, 0, len(clients)) + for _, client := range clients { + selected, err := selectWireguardDevice(client, s.wireguardDevice) + if err != nil { + // A shared subscription may also contain unrelated clients. + // Request-level validation rejects selectors absent everywhere. + continue + } + s.wireguardDeviceSelected = true + selectedClients = append(selectedClients, selected) + if inbound.Id > 0 { + s.clientsByInbound[inbound.Id][client.Email] = selected + } + } + return selectedClients +} + +func (s *SubService) validateWireguardDevice() error { + if s.wireguardDevice != "" && s.wireguardDevice != "primary" && !s.wireguardDeviceSelected { + return errWireguardDeviceUnavailable + } + return nil +} diff --git a/internal/sub/wireguard_device_test.go b/internal/sub/wireguard_device_test.go new file mode 100644 index 000000000..a8836de8b --- /dev/null +++ b/internal/sub/wireguard_device_test.go @@ -0,0 +1,181 @@ +package sub + +import ( + "errors" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/goccy/go-json" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestSelectWireguardDeviceKeepsParentLifecycle(t *testing.T) { + client := model.Client{ + Email: "parent", Enable: false, TotalGB: 100, ExpiryTime: 1234, + PrivateKey: "primary", AllowedIPs: []string{"10.0.0.2/32"}, + WireguardDevices: []model.WireguardDevice{{ + Id: "phone", Enable: true, PrivateKey: "phone-key", PublicKey: "phone-public", + PreSharedKey: "phone-psk", AllowedIPs: []string{"10.0.0.3/32"}, + }}, + } + selected, err := selectWireguardDevice(client, "phone") + if err != nil { + t.Fatal(err) + } + if selected.Enable || selected.Email != client.Email || selected.TotalGB != client.TotalGB || selected.ExpiryTime != client.ExpiryTime { + t.Fatalf("parent lifecycle changed: %+v", selected) + } + if selected.PrivateKey != "phone-key" || selected.PublicKey != "phone-public" || selected.PreSharedKey != "phone-psk" || selected.AllowedIPs[0] != "10.0.0.3/32" { + t.Fatalf("device credentials were not selected: %+v", selected) + } + selected.AllowedIPs[0] = "changed" + if client.WireguardDevices[0].AllowedIPs[0] != "10.0.0.3/32" { + t.Fatal("selection mutated stored addresses") + } + for _, id := range []string{"", "primary"} { + primary, err := selectWireguardDevice(client, id) + if err != nil || primary.PrivateKey != "primary" { + t.Fatalf("primary selection = %+v, %v", primary, err) + } + } + client.WireguardDevices[0].Enable = false + for _, id := range []string{"phone", "missing"} { + if _, err := selectWireguardDevice(client, id); !errors.Is(err, errWireguardDeviceUnavailable) { + t.Fatalf("selection %q error = %v", id, err) + } + } +} + +func TestWireguardDeviceURLsRetainSelection(t *testing.T) { + service := NewSubService("").ForWireguardDevice("phone id") + link, err := url.Parse(service.buildSingleURL("https://example.com/sub/", "", "", "subscriber")) + if err != nil { + t.Fatal(err) + } + if link.Path != "/sub/subscriber" || link.Query().Get("wgDevice") != "phone id" { + t.Fatalf("subscription URL = %s", link) + } + context, _ := gin.CreateTestContext(httptest.NewRecorder()) + context.Request = httptest.NewRequest(http.MethodGet, "https://example.com/sub/subscriber?wgDevice=phone+id&view=raw", nil) + profile, err := url.Parse(builtinProfileURL(context, "https", "example.com")) + if err != nil { + t.Fatal(err) + } + if profile.Query().Get("wgDevice") != "phone id" || profile.Query().Get("html") != "1" || profile.Query().Has("view") { + t.Fatalf("profile URL = %s", profile) + } +} + +func TestWireguardDeviceSubscriptionFormats(t *testing.T) { + initSubDB(t) + db := database.GetDB() + serverPrivate, _ := mustWireguardKeypair(t) + primaryPrivate, primaryPublic := mustWireguardKeypair(t) + phonePrivate, phonePublic := mustWireguardKeypair(t) + const subID = "device-sub" + client := model.Client{ + Email: "devices@example.com", SubID: subID, Enable: true, + PrivateKey: primaryPrivate, PublicKey: primaryPublic, AllowedIPs: []string{"10.0.0.2/32"}, + WireguardDevices: []model.WireguardDevice{{ + Id: "phone", Name: "Phone", Enable: true, PrivateKey: phonePrivate, PublicKey: phonePublic, + AllowedIPs: []string{"10.0.0.3/32"}, + }}, + } + otherPrivate, otherPublic := mustWireguardKeypair(t) + other := model.Client{ + Email: "other@example.com", SubID: subID, Enable: true, + PrivateKey: otherPrivate, PublicKey: otherPublic, AllowedIPs: []string{"10.0.0.4/32"}, + } + settings, err := json.Marshal(map[string]any{"secretKey": serverPrivate, "clients": []model.Client{client, other}}) + if err != nil { + t.Fatal(err) + } + inbound := model.Inbound{ + UserId: 1, Tag: "wg-devices", Protocol: model.WireGuard, Enable: true, + Listen: "203.0.113.7", Port: 51820, Remark: "WG", Settings: string(settings), + } + if err := db.Create(&inbound).Error; err != nil { + t.Fatal(err) + } + record := model.ClientRecord{Email: client.Email, SubID: subID, Enable: true, PrivateKey: primaryPrivate, AllowedIPs: "10.0.0.2/32"} + if err := db.Create(&record).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&model.ClientInbound{ClientId: record.Id, InboundId: inbound.Id}).Error; err != nil { + t.Fatal(err) + } + otherRecord := model.ClientRecord{Email: other.Email, SubID: subID, Enable: true} + if err := db.Create(&otherRecord).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&model.ClientInbound{ClientId: otherRecord.Id, InboundId: inbound.Id}).Error; err != nil { + t.Fatal(err) + } + gin.SetMode(gin.TestMode) + router := gin.New() + NewSUBController(router.Group("/"), WithSUBEncryption(false), WithSUBJsonEnabled(true), WithSUBClashEnabled(true)) + for _, path := range []string{"/sub/", "/json/", "/clash/"} { + t.Run(path, func(t *testing.T) { + for _, tc := range []struct { + query string + key string + addr string + }{ + {"?wgDevice=phone", phonePrivate, "10.0.0.3"}, + {"", primaryPrivate, "10.0.0.2"}, + {"?wgDevice=primary", primaryPrivate, "10.0.0.2"}, + } { + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path+subID+tc.query, nil)) + if response.Code != http.StatusOK { + t.Fatalf("%s%s: status %d, body %s", path, tc.query, response.Code, response.Body.String()) + } + body := response.Body.String() + if path == "/sub/" { + found := false + for line := range strings.SplitSeq(strings.TrimSpace(body), "\n") { + link := parseWireguardSubLink(t, line) + if tc.query == "?wgDevice=phone" && link.User.Username() == otherPrivate { + t.Fatal("device subscription included another client's WireGuard identity") + } + found = found || (link.User.Username() == tc.key && strings.Contains(link.Query().Get("address"), tc.addr)) + } + if !found { + t.Fatalf("wrong device in link: %s", body) + } + } else if !strings.Contains(body, tc.key) || !strings.Contains(body, tc.addr) { + t.Fatalf("wrong device in %s: %s", path, body) + } + if tc.query == "?wgDevice=phone" && strings.Contains(body, otherPrivate) { + t.Fatal("device subscription included another client's WireGuard identity") + } + } + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path+subID+"?wgDevice=missing", nil)) + if response.Code != http.StatusNotFound { + t.Fatalf("unknown device status = %d", response.Code) + } + }) + } + client.WireguardDevices[0].Enable = false + settings, err = json.Marshal(map[string]any{"secretKey": serverPrivate, "clients": []model.Client{client, other}}) + if err != nil { + t.Fatal(err) + } + if err := db.Model(&inbound).Update("settings", string(settings)).Error; err != nil { + t.Fatal(err) + } + for _, path := range []string{"/sub/", "/json/", "/clash/"} { + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path+subID+"?wgDevice=phone", nil)) + if response.Code != http.StatusNotFound { + t.Fatalf("disabled device %s status = %d", path, response.Code) + } + } +} diff --git a/internal/util/wirecodec/wirecodec.go b/internal/util/wirecodec/wirecodec.go index 7aae9389c..b4a66b24a 100644 --- a/internal/util/wirecodec/wirecodec.go +++ b/internal/util/wirecodec/wirecodec.go @@ -28,8 +28,11 @@ const ( CapAmneziaWGKernel = "awg-kernel" // CapPreserveClientTraffic marks a node that supports inbound-only scheduled resets. CapPreserveClientTraffic = "preserve-client-traffic" + // CapWireguardDevices marks a node that serves a WireGuard client's extra devices; + // an older node ignores them and keeps only the client's first peer. + CapWireguardDevices = "wg-devices" // NodeCaps is the full CapsHeader value this build advertises. - NodeCaps = CapZstd + "," + CapAmneziaWGKernel + "," + CapPreserveClientTraffic + NodeCaps = CapZstd + "," + CapAmneziaWGKernel + "," + CapPreserveClientTraffic + "," + CapWireguardDevices // maxDecodeBytes bounds in-memory decompression to defuse a zstd bomb from // an (authenticated) node-API caller. diff --git a/internal/web/controller/client-wireguard-devices.go b/internal/web/controller/client-wireguard-devices.go new file mode 100644 index 000000000..71cba07be --- /dev/null +++ b/internal/web/controller/client-wireguard-devices.go @@ -0,0 +1,57 @@ +package controller + +import ( + "github.com/gin-gonic/gin" + + "github.com/mhsanaei/3x-ui/v3/internal/web/service" +) + +func (a *ClientController) wireguardDevices(c *gin.Context) { + devices, err := a.clientService.WireguardDevices(c.Query("email")) + jsonObj(c, devices, err) +} + +func (a *ClientController) finishWireguardDeviceWrite(c *gin.Context, err error) { + if err != nil { + jsonObj(c, nil, err) + return + } + a.xrayService.SetToNeedReconcile() + notifyClientsChanged() + a.wireguardDevices(c) +} + +func (a *ClientController) addWireguardDevice(c *gin.Context) { + var body struct { + Name string `json:"name"` + } + if err := c.ShouldBindJSON(&body); err != nil { + jsonObj(c, nil, err) + return + } + a.finishWireguardDeviceWrite(c, a.clientService.AddWireguardDevice(c.Query("email"), body.Name)) +} + +func (a *ClientController) updateWireguardDevice(c *gin.Context) { + var patch service.WireguardDevicePatch + if err := c.ShouldBindJSON(&patch); err != nil { + jsonObj(c, nil, err) + return + } + a.finishWireguardDeviceWrite(c, a.clientService.UpdateWireguardDevice(c.Query("email"), c.Param("deviceId"), patch)) +} + +func (a *ClientController) deleteWireguardDevice(c *gin.Context) { + a.finishWireguardDeviceWrite(c, a.clientService.DeleteWireguardDevice(c.Query("email"), c.Param("deviceId"))) +} + +func (a *ClientController) setWireguardDeviceLimit(c *gin.Context) { + var body struct { + Limit int `json:"limit"` + } + if err := c.ShouldBindJSON(&body); err != nil { + jsonObj(c, nil, err) + return + } + a.finishWireguardDeviceWrite(c, a.clientService.SetWireguardDeviceLimit(c.Query("email"), body.Limit)) +} diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go index edf63cfe8..07a936bee 100644 --- a/internal/web/controller/client.go +++ b/internal/web/controller/client.go @@ -71,6 +71,11 @@ func (a *ClientController) initRouter(g *gin.RouterGroup) { g.POST("/:email/attach", a.attach) g.POST("/:email/detach", a.detach) g.POST("/:email/externalLinks", a.setExternalLinks) + g.GET("/wireguardDevices", a.wireguardDevices) + g.POST("/wireguardDevices", a.addWireguardDevice) + g.PUT("/wireguardDevices/limit", a.setWireguardDeviceLimit) + g.PATCH("/wireguardDevices/:deviceId", a.updateWireguardDevice) + g.DELETE("/wireguardDevices/:deviceId", a.deleteWireguardDevice) g.GET("/export", a.export) g.POST("/import", a.importClients) g.POST("/delOrphans", a.delOrphans) diff --git a/internal/web/controller/client_wireguard_devices_test.go b/internal/web/controller/client_wireguard_devices_test.go new file mode 100644 index 000000000..40e6341d1 --- /dev/null +++ b/internal/web/controller/client_wireguard_devices_test.go @@ -0,0 +1,72 @@ +package controller + +import ( + "encoding/json" + "net/http" + "net/url" + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard" + "github.com/mhsanaei/3x-ui/v3/internal/web/service" +) + +func TestWireguardDevicesQueryEmailRoundTrip(t *testing.T) { + for _, email := range []string{".", "..", "alice@example.com", "legacy/name"} { + t.Run(email, func(t *testing.T) { + router, record, inbound := seedLegacyDotClient(t, email) + privateKey, publicKey, err := wgutil.GenerateWireguardKeypair() + if err != nil { + t.Fatal(err) + } + client := *record.ToClient() + client.PrivateKey, client.PublicKey = privateKey, publicKey + client.AllowedIPs = []string{"10.0.0.2/32"} + settings, err := json.Marshal(map[string]any{"clients": []model.Client{client}}) + if err != nil { + t.Fatal(err) + } + if err := database.GetDB().Model(&model.Inbound{}).Where("id = ?", inbound.Id).Updates(map[string]any{"protocol": model.WireGuard, "settings": string(settings)}).Error; err != nil { + t.Fatal(err) + } + query := "?email=" + url.QueryEscape(email) + read := func() service.WireguardDeviceList { + t.Helper() + response := dotClientRequest(t, router, http.MethodGet, "wireguardDevices"+query, nil) + assertDotClientSuccess(t, response) + var message struct { + Obj service.WireguardDeviceList `json:"obj"` + } + if err := json.Unmarshal(response.Body.Bytes(), &message); err != nil { + t.Fatal(err) + } + return message.Obj + } + initial := read() + if len(initial.Inbounds) != 1 || len(initial.Inbounds[0].Devices) != 1 { + t.Fatal("primary device is missing") + } + response := dotClientRequest(t, router, http.MethodPut, "wireguardDevices/limit"+query, map[string]any{"limit": 2}) + assertDotClientSuccess(t, response) + response = dotClientRequest(t, router, http.MethodPost, "wireguardDevices"+query, map[string]any{"name": "Phone"}) + assertDotClientSuccess(t, response) + created := read() + if created.Limit != 2 || len(created.Inbounds[0].Devices) != 2 { + t.Fatal("device creation did not persist") + } + id := created.Inbounds[0].Devices[1].Id + response = dotClientRequest(t, router, http.MethodPatch, "wireguardDevices/"+id+query, map[string]any{"name": "Laptop", "enable": false}) + assertDotClientSuccess(t, response) + patched := read().Inbounds[0].Devices[1] + if patched.Enable || patched.Name != "Laptop" { + t.Fatal("device patch did not persist") + } + response = dotClientRequest(t, router, http.MethodDelete, "wireguardDevices/"+id+query, nil) + assertDotClientSuccess(t, response) + if len(read().Inbounds[0].Devices) != 1 { + t.Fatal("device deletion did not persist") + } + }) + } +} diff --git a/internal/web/node_contract_test.go b/internal/web/node_contract_test.go index 2958d9b82..6ad27ce9f 100644 --- a/internal/web/node_contract_test.go +++ b/internal/web/node_contract_test.go @@ -187,6 +187,9 @@ func TestMasterNodeContract(t *testing.T) { {"CheckPreserveClientTraffic reads the node's reset capability", []string{"CheckPreserveClientTraffic"}, func() error { return master.CheckPreserveClientTraffic(ctx) }, nil}, + {"CheckWireguardDevices reads the node's device capability", []string{"CheckWireguardDevices"}, func() error { + return master.CheckWireguardDevices(ctx) + }, nil}, {"AddInbound creates the inbound with its clients", []string{"AddInbound"}, func() error { return master.AddInbound(ctx, masterInbound("added", true, "c0", "c1")) }, func(t *testing.T) { diff --git a/internal/web/runtime/local.go b/internal/web/runtime/local.go index f130921ce..7db656833 100644 --- a/internal/web/runtime/local.go +++ b/internal/web/runtime/local.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "maps" "strconv" "strings" "sync" @@ -284,6 +285,35 @@ func (l *Local) AddUser(_ context.Context, ib *model.Inbound, userMap map[string return nil } return l.withAPI(func(api *xray.XrayAPI) error { + if ib.Protocol == model.WireGuard { + if keepAlive, ok := userMap["keepAlive"].(string); ok { + userMap = maps.Clone(userMap) + delete(userMap, "keepAlive") + if keepAlive != "" { + value := model.KeepAliveValue(keepAlive) + if err := value.Validate(false); err != nil { + return err + } + userMap["keepAlive"] = value.Seconds() + } + } + data, err := json.Marshal(userMap) + if err != nil { + return err + } + var client model.Client + if err := json.Unmarshal(data, &client); err != nil { + return err + } + for _, peer := range model.WireguardClients(client) { + user := model.WireguardPeerFromClient(peer) + user["keepAlive"] = wgKeepAlive(peer.KeepAliveSeconds()) + if err := api.AddUser(string(ib.Protocol), ib.Tag, user); err != nil { + return err + } + } + return nil + } return api.AddUser(string(ib.Protocol), ib.Tag, userMap) }) } @@ -299,6 +329,9 @@ func (l *Local) RemoveUser(_ context.Context, ib *model.Inbound, email string) e return nil } return l.withAPI(func(api *xray.XrayAPI) error { + if ib.Protocol == model.WireGuard { + return api.RemoveWireguardUsers(ib.Tag, email) + } return api.RemoveUser(ib.Tag, email) }) } @@ -308,16 +341,17 @@ func (l *Local) AddClient(ctx context.Context, ib *model.Inbound, client model.C return nil } user := map[string]any{ - "email": client.Email, - "id": client.ID, - "security": client.Security, - "flow": client.Flow, - "auth": client.Auth, - "password": client.Password, - "publicKey": client.PublicKey, - "allowedIPs": client.AllowedIPs, - "preSharedKey": client.PreSharedKey, - "keepAlive": wgKeepAlive(client.KeepAliveSeconds()), + "email": client.Email, + "id": client.ID, + "security": client.Security, + "flow": client.Flow, + "auth": client.Auth, + "password": client.Password, + "publicKey": client.PublicKey, + "allowedIPs": client.AllowedIPs, + "preSharedKey": client.PreSharedKey, + "keepAlive": wgKeepAlive(client.KeepAliveSeconds()), + "wireguardDevices": client.WireguardDevices, } return l.AddUser(ctx, ib, user) } @@ -349,16 +383,17 @@ func (l *Local) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail stri return nil } user := map[string]any{ - "email": payload.Email, - "id": payload.ID, - "security": payload.Security, - "flow": payload.Flow, - "auth": payload.Auth, - "password": payload.Password, - "publicKey": payload.PublicKey, - "allowedIPs": payload.AllowedIPs, - "preSharedKey": payload.PreSharedKey, - "keepAlive": wgKeepAlive(payload.KeepAliveSeconds()), + "email": payload.Email, + "id": payload.ID, + "security": payload.Security, + "flow": payload.Flow, + "auth": payload.Auth, + "password": payload.Password, + "publicKey": payload.PublicKey, + "allowedIPs": payload.AllowedIPs, + "preSharedKey": payload.PreSharedKey, + "keepAlive": wgKeepAlive(payload.KeepAliveSeconds()), + "wireguardDevices": payload.WireguardDevices, } return l.AddUser(ctx, ib, user) } diff --git a/internal/web/runtime/local_wireguard_devices_test.go b/internal/web/runtime/local_wireguard_devices_test.go new file mode 100644 index 000000000..95258cbc3 --- /dev/null +++ b/internal/web/runtime/local_wireguard_devices_test.go @@ -0,0 +1,128 @@ +package runtime + +import ( + "bytes" + "context" + "encoding/base64" + "net" + "testing" + + "github.com/xtls/xray-core/app/proxyman/command" + "github.com/xtls/xray-core/common/protocol" + "github.com/xtls/xray-core/proxy/wireguard" + "google.golang.org/grpc" + "google.golang.org/protobuf/proto" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +type wireguardDeviceServer struct { + command.UnimplementedHandlerServiceServer + users chan *protocol.User +} + +func (s *wireguardDeviceServer) AlterInbound(_ context.Context, request *command.AlterInboundRequest) (*command.AlterInboundResponse, error) { + operation := new(command.AddUserOperation) + if err := proto.Unmarshal(request.Operation.Value, operation); err != nil { + return nil, err + } + s.users <- operation.User + return &command.AlterInboundResponse{}, nil +} + +func newWireguardDeviceRuntime(t *testing.T) (*Local, *wireguardDeviceServer) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + core := &wireguardDeviceServer{users: make(chan *protocol.User, 3)} + server := grpc.NewServer() + command.RegisterHandlerServiceServer(server, core) + go func() { _ = server.Serve(listener) }() + t.Cleanup(server.Stop) + port := listener.Addr().(*net.TCPAddr).Port + local := NewLocal(LocalDeps{APIPort: func() int { return port }}) + return local, core +} + +func wireguardDeviceClient(keepAlive *model.KeepAliveValue) model.Client { + key := func(seed byte) string { + return base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{seed}, 32)) + } + return model.Client{ + Email: "owner", Enable: true, PublicKey: key(1), AllowedIPs: []string{"10.0.0.2/32"}, + KeepAlive: keepAlive, + WireguardDevices: []model.WireguardDevice{ + {Id: "phone", Enable: true, PublicKey: key(2), AllowedIPs: []string{"10.0.0.3/32"}}, + {Id: "off", Enable: false, PublicKey: key(3), AllowedIPs: []string{"10.0.0.4/32"}}, + }, + } +} + +func assertWireguardDevicePeers(t *testing.T, core *wireguardDeviceServer, keepAlive string) { + t.Helper() + if len(core.users) != 2 { + t.Fatalf("added %d peers, want primary and enabled phone", len(core.users)) + } + for i := range 2 { + user := <-core.users + if user.Email != "owner" { + t.Fatalf("peer attribution = %q", user.Email) + } + peer := new(wireguard.PeerConfig) + if err := proto.Unmarshal(user.Account.Value, peer); err != nil { + t.Fatal(err) + } + if peer.KeepAlive != keepAlive || peer.AllowedIps[0] != []string{"10.0.0.2/32", "10.0.0.3/32"}[i] { + t.Fatalf("unexpected peer %v", peer) + } + } +} + +func TestLocalWireguardAddsEveryEnabledDevice(t *testing.T) { + for _, test := range []struct { + name string + keepAlive *model.KeepAliveValue + want string + }{ + {name: "omitted"}, + {name: "zero", keepAlive: model.KeepAlivePtr(0)}, + {name: "positive", keepAlive: model.KeepAlivePtr(25), want: "25"}, + } { + t.Run(test.name, func(t *testing.T) { + local, core := newWireguardDeviceRuntime(t) + if err := local.AddClient(context.Background(), &model.Inbound{Tag: "wg", Protocol: model.WireGuard}, wireguardDeviceClient(test.keepAlive)); err != nil { + t.Fatal(err) + } + assertWireguardDevicePeers(t, core, test.want) + }) + } +} + +func TestLocalWireguardAddUserAcceptsLegacyKeepAliveStrings(t *testing.T) { + for _, keepAlive := range []string{"", "0", "25"} { + t.Run("keepAlive="+keepAlive, func(t *testing.T) { + local, core := newWireguardDeviceRuntime(t) + client := wireguardDeviceClient(nil) + user := map[string]any{ + "email": client.Email, + "publicKey": client.PublicKey, + "allowedIPs": client.AllowedIPs, + "wireguardDevices": client.WireguardDevices, + "keepAlive": keepAlive, + } + if err := local.AddUser(context.Background(), &model.Inbound{Tag: "wg", Protocol: model.WireGuard}, user); err != nil { + t.Fatal(err) + } + want := keepAlive + if keepAlive == "0" { + want = "" + } + assertWireguardDevicePeers(t, core, want) + if user["keepAlive"] != keepAlive { + t.Fatal("AddUser changed the caller's keepAlive value") + } + }) + } +} diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index 250ccc59d..9c72b5081 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -183,12 +183,57 @@ func (r *Remote) checkInboundCapabilities(ctx context.Context, ib *model.Inbound if err := r.requireAmneziaWGKernel(ctx, ib); err != nil { return err } + if inboundHasWireguardDevices(ib) { + if err := r.requireWireguardDevices(ctx); err != nil { + return err + } + } if !ib.PreservesClientTraffic() || !ib.HasTrafficResetSchedule() { return nil } return r.requirePreserveClientTraffic(ctx) } +func inboundHasWireguardDevices(ib *model.Inbound) bool { + if ib.Protocol != model.WireGuard { + return false + } + var settings struct { + Clients []struct { + WireguardDevices []json.RawMessage `json:"wireguardDevices"` + } `json:"clients"` + } + if json.Unmarshal([]byte(ib.Settings), &settings) != nil { + return false + } + for _, client := range settings.Clients { + if len(client.WireguardDevices) > 0 { + return true + } + } + return false +} + +// CheckWireguardDevices probes the current node build before the master stores a +// client's first extra device; learned caps go stale across an upgrade or rollback. +func (r *Remote) CheckWireguardDevices(ctx context.Context) error { + if _, err := r.do(ctx, http.MethodGet, "panel/api/server/status", nil); err != nil { + return fmt.Errorf("cannot verify WireGuard device support on node %s: %w", r.node.Name, err) + } + return r.requireWireguardDevices(ctx) +} + +func (r *Remote) requireWireguardDevices(ctx context.Context) error { + supported, err := r.nodeSupports(ctx, wirecodec.CapWireguardDevices) + if err != nil { + return err + } + if !supported { + return fmt.Errorf("node %s does not support WireGuard client devices; upgrade its panel before adding devices", r.node.Name) + } + return nil +} + // CheckPreserveClientTraffic probes the current node build before the master // commits an opt-in. An upgrade or rollback can make previously learned caps stale. func (r *Remote) CheckPreserveClientTraffic(ctx context.Context) error { diff --git a/internal/web/runtime/remote_envelope_test.go b/internal/web/runtime/remote_envelope_test.go index 21cd51a64..2edd32672 100644 --- a/internal/web/runtime/remote_envelope_test.go +++ b/internal/web/runtime/remote_envelope_test.go @@ -120,6 +120,45 @@ func TestRemoteRequiresSupportForInboundOnlyScheduledReset(t *testing.T) { } } +// An older node ignores wireguardDevices and serves only each client's first peer, so +// the master must not push device configs that node would never back. +func TestRemoteRequiresSupportForWireguardDevices(t *testing.T) { + const older = wirecodec.CapZstd + "," + wirecodec.CapAmneziaWGKernel + "," + wirecodec.CapPreserveClientTraffic + const withDevices = `{"clients":[{"email":"a","wireguardDevices":[{"id":"d1"}]}]}` + cases := []struct { + name, caps, settings string + wantPushed bool + }{ + {"capable node", wirecodec.NodeCaps, withDevices, true}, + {"older node, client with devices", older, withDevices, false}, + {"older node, no devices", older, `{"clients":[{"email":"a","wireguardDevices":[]}]}`, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var pushed bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(wirecodec.CapsHeader, tc.caps) + w.Header().Set("Content-Type", "application/json") + if r.Method == http.MethodPost { + pushed = true + } + _, _ = w.Write([]byte(`{"success":true,"obj":[]}`)) + })) + defer srv.Close() + + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + err := r.AddInbound(context.Background(), &model.Inbound{Protocol: model.WireGuard, Settings: tc.settings}) + if tc.wantPushed { + if err != nil || !pushed { + t.Fatalf("pushed = %v, error = %v", pushed, err) + } + } else if pushed || err == nil || !strings.Contains(err.Error(), "does not support WireGuard client devices") { + t.Fatalf("pushed = %v, error = %v", pushed, err) + } + }) + } +} + // TestRemoteRefusesKernelAmneziaWGOnNodeWithoutCap: an older node drops the // kernelMode flag and silently runs the inbound on the embedded datapath. func TestRemoteRefusesKernelAmneziaWGOnNodeWithoutCap(t *testing.T) { diff --git a/internal/web/service/client-wireguard-devices.go b/internal/web/service/client-wireguard-devices.go new file mode 100644 index 000000000..feae593c5 --- /dev/null +++ b/internal/web/service/client-wireguard-devices.go @@ -0,0 +1,301 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +type WireguardDeviceInbound struct { + InboundId int `json:"inboundId"` + Devices []model.WireguardDevice `json:"devices"` +} + +type WireguardDeviceList struct { + Limit int `json:"limit"` + Inbounds []WireguardDeviceInbound `json:"inbounds"` +} + +type WireguardDevicePatch struct { + Name *string `json:"name"` + Enable *bool `json:"enable"` +} + +func wireguardDeviceInbounds(tx *gorm.DB, email string) ([]model.Inbound, error) { + var inbounds []model.Inbound + err := tx.Model(&model.Inbound{}). + Joins("JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id"). + Joins("JOIN clients ON clients.id = client_inbounds.client_id"). + Where("clients.email = ? AND inbounds.protocol = ?", email, model.WireGuard). + Order("inbounds.id ASC").Find(&inbounds).Error + return inbounds, err +} + +func (s *ClientService) WireguardDevices(email string) (WireguardDeviceList, error) { + result := WireguardDeviceList{Inbounds: []WireguardDeviceInbound{}} + err := database.GetDB().Transaction(func(tx *gorm.DB) error { + record, err := s.GetRecordByEmail(tx, email) + if err != nil { + return err + } + result.Limit = model.EffectiveWireguardDeviceLimit(record.WgDeviceLimit) + inbounds, err := wireguardDeviceInbounds(tx, email) + if err != nil { + return err + } + for _, inbound := range inbounds { + clients, err := ParseInboundSettingsClients(inbound.Settings) + if err != nil { + return err + } + for _, client := range clients { + if client.Email != email { + continue + } + devices := []model.WireguardDevice{{Id: "primary", Name: "", Enable: client.Enable, PrivateKey: client.PrivateKey, PublicKey: client.PublicKey, AllowedIPs: client.AllowedIPs, PreSharedKey: client.PreSharedKey}} + devices = append(devices, client.WireguardDevices...) + result.Inbounds = append(result.Inbounds, WireguardDeviceInbound{InboundId: inbound.Id, Devices: devices}) + } + } + return nil + }) + return result, err +} + +func validWireguardDeviceName(name string) (string, error) { + name = strings.TrimSpace(name) + if name == "" || len([]rune(name)) > 64 || strings.ContainsAny(name, "\r\n") { + return "", errors.New("device name must contain 1 to 64 characters on one line") + } + return name, nil +} + +// nodeWireguardDeviceChecker is the node runtime's probe; the local one serves devices itself. +type nodeWireguardDeviceChecker interface { + CheckWireguardDevices(ctx context.Context) error +} + +// requireNodesServeWireguardDevices runs before the write: a device an older node ignores +// would be handed out as a working config and leave that node pending a push it refuses. +func requireNodesServeWireguardDevices(email string) error { + inbounds, err := wireguardDeviceInbounds(database.GetDB(), email) + if err != nil { + return err + } + mgr := runtime.GetManager() + checked := make(map[int]struct{}) + for _, inbound := range inbounds { + if inbound.NodeID == nil || mgr == nil { + continue + } + if _, done := checked[*inbound.NodeID]; done { + continue + } + checked[*inbound.NodeID] = struct{}{} + rt, err := mgr.RuntimeFor(inbound.NodeID) + if err != nil { + return err + } + checker, ok := rt.(nodeWireguardDeviceChecker) + if !ok { + continue + } + ctx, cancel := nodePushContext() + err = checker.CheckWireguardDevices(ctx) + cancel() + if err != nil { + return err + } + } + return nil +} + +func (s *ClientService) AddWireguardDevice(email, name string) error { + name, err := validWireguardDeviceName(name) + if err != nil { + return err + } + privateKey, publicKey, err := wgutil.GenerateWireguardKeypair() + if err != nil { + return err + } + device := model.WireguardDevice{Id: uuid.NewString(), Name: name, Enable: true, PrivateKey: privateKey, PublicKey: publicKey} + if err := requireNodesServeWireguardDevices(email); err != nil { + return err + } + return s.mutateWireguardDevices(email, func(client *model.Client) error { + if len(client.WireguardDevices)+1 >= model.EffectiveWireguardDeviceLimit(client.WgDeviceLimit) { + return errors.New("WireGuard device limit reached") + } + client.WireguardDevices = append(model.CloneWireguardDevices(client.WireguardDevices), device) + return nil + }) +} + +func (s *ClientService) UpdateWireguardDevice(email, id string, patch WireguardDevicePatch) error { + if patch.Name != nil { + name, err := validWireguardDeviceName(*patch.Name) + if err != nil { + return err + } + patch.Name = &name + } + return s.mutateWireguardDevices(email, func(client *model.Client) error { + for i := range client.WireguardDevices { + device := &client.WireguardDevices[i] + if device.Id != id { + continue + } + if patch.Name != nil { + device.Name = *patch.Name + } + if patch.Enable != nil { + device.Enable = *patch.Enable + } + return nil + } + return errors.New("WireGuard device not found") + }) +} + +func (s *ClientService) DeleteWireguardDevice(email, id string) error { + return s.mutateWireguardDevices(email, func(client *model.Client) error { + for i, device := range client.WireguardDevices { + if device.Id == id { + client.WireguardDevices = append(client.WireguardDevices[:i:i], client.WireguardDevices[i+1:]...) + if client.WireguardDevices == nil { + client.WireguardDevices = []model.WireguardDevice{} + } + return nil + } + } + return errors.New("WireGuard device not found") + }) +} + +func (s *ClientService) SetWireguardDeviceLimit(email string, limit int) error { + if limit < 1 || limit > 32 { + return errors.New("WireGuard device limit must be between 1 and 32") + } + return s.mutateWireguardDevices(email, func(client *model.Client) error { + if len(client.WireguardDevices)+1 > limit { + return errors.New("device limit is below the current device count") + } + client.WgDeviceLimit = limit + return nil + }) +} + +// All inbounds commit together. The serialized writer also protects address allocation. +func (s *ClientService) mutateWireguardDevices(email string, change func(*model.Client) error) error { + inbounds, err := wireguardDeviceInbounds(database.GetDB(), email) + if err != nil { + return err + } + for _, inbound := range inbounds { + lock := lockInbound(inbound.Id) + defer lock.Unlock() + } + err = runSerializedTx(func(tx *gorm.DB) error { + record, err := s.GetRecordByEmail(tx, email) + if err != nil { + return err + } + current, err := wireguardDeviceInbounds(tx, email) + if err != nil { + return err + } + if len(current) == 0 { + return errors.New("client has no WireGuard inbounds") + } + if len(current) != len(inbounds) { + return errors.New("client attachments changed, retry the device operation") + } + for i := range current { + if current[i].Id != inbounds[i].Id { + return errors.New("client attachments changed, retry the device operation") + } + } + for _, inbound := range current { + clients, err := ParseInboundSettingsClients(inbound.Settings) + if err != nil { + return err + } + var settings map[string]json.RawMessage + if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil { + return err + } + var entries []map[string]json.RawMessage + if err := json.Unmarshal(settings["clients"], &entries); err != nil { + return err + } + found := false + for i := range clients { + client := &clients[i] + if client.Email != email { + continue + } + found = true + client.WgDeviceLimit = record.WgDeviceLimit + if err := change(client); err != nil { + return err + } + others := append([]model.Client(nil), clients[:i]...) + others = append(others, clients[i+1:]...) + crossUsed, err := s.otherTunnelAllowedIPs(tx, &InboundService{}, inbound.Id, map[string]struct{}{strings.ToLower(email): {}}) + if err != nil { + return err + } + if err := validateWireguardDevices(inbound.Settings, others, client, crossUsed); err != nil { + return fmt.Errorf("inbound %d: %w", inbound.Id, err) + } + entries[i]["wireguardDevices"], err = json.Marshal(client.WireguardDevices) + if err != nil { + return err + } + entries[i]["wgDeviceLimit"], err = json.Marshal(client.WgDeviceLimit) + if err != nil { + return err + } + if err := s.ApplyInboundClientDelta(tx, inbound.Id, []model.Client{*client}, nil); err != nil { + return err + } + } + if !found { + return errors.New("WireGuard client settings are missing") + } + settings["clients"], err = json.Marshal(entries) + if err != nil { + return err + } + encoded, err := json.Marshal(settings) + if err != nil { + return err + } + if err := tx.Model(&model.Inbound{}).Where("id = ?", inbound.Id).Update("settings", string(encoded)).Error; err != nil { + return err + } + if inbound.NodeID != nil { + if err := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); err != nil { + return err + } + } + } + return tx.Model(&model.ClientRecord{}).Where("id = ?", record.Id).Update("updated_at", time.Now().UnixMilli()).Error + }) + if err == nil { + InvalidateSubData() + } + return err +} diff --git a/internal/web/service/client-wireguard-validation.go b/internal/web/service/client-wireguard-validation.go new file mode 100644 index 000000000..fcf9af259 --- /dev/null +++ b/internal/web/service/client-wireguard-validation.go @@ -0,0 +1,154 @@ +package service + +import ( + "encoding/json" + "fmt" + "net/netip" + "strings" + + "github.com/google/uuid" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard" +) + +func encodeWireguardDevices(devices []model.WireguardDevice) string { + encoded, _ := json.Marshal(devices) + return string(encoded) +} + +// Attached devices keep their identity while the target inbound may allocate +// addresses from a different configured subnet. +func prepareWireguardDeviceAddresses(client *model.Client, inbound *model.Inbound) { + if inbound.Protocol != model.WireGuard { + return + } + client.WireguardDevices = model.CloneWireguardDevices(client.WireguardDevices) + prefix, err := netip.ParsePrefix(explicitWireguardSubnetBase(inbound.Settings)) + if err != nil { + return + } + for i := range client.WireguardDevices { + for _, address := range client.WireguardDevices[i].AllowedIPs { + if !prefix.Contains(wireguardHostAddr(address)) { + client.WireguardDevices[i].AllowedIPs = nil + break + } + } + } +} + +func defaultWireguardDeviceIdentity(device *model.WireguardDevice) error { + if device.Id == "" { + device.Id = uuid.NewString() + } + if device.PrivateKey == "" && device.PublicKey == "" { + privateKey, publicKey, err := wgutil.GenerateWireguardKeypair() + if err != nil { + return err + } + device.PrivateKey, device.PublicKey = privateKey, publicKey + } + if device.PrivateKey != "" { + publicKey, err := wgutil.PublicKeyFromPrivate(device.PrivateKey) + if err != nil { + return fmt.Errorf("wireguard: invalid device private key: %w", err) + } + derived, _ := wgutil.KeyToHex(publicKey) + provided, err := wgutil.KeyToHex(device.PublicKey) + if err != nil || (provided != "" && provided != derived) { + return fmt.Errorf("wireguard: device public key does not match private key") + } + device.PublicKey = publicKey + } + return nil +} + +// validateWireguardDevices allocates and validates additional devices. The +// caller owns the inbound lock and rechecks occupancy in the serialized writer. +func validateWireguardDevices(settings string, existing []model.Client, client *model.Client, crossUsed map[string]string) error { + if client.WgDeviceLimit < 0 || client.WgDeviceLimit > model.MaxWireguardDevices { + return fmt.Errorf("wireguard: device limit must be between 1 and %d", model.MaxWireguardDevices) + } + if len(client.WireguardDevices)+1 > model.EffectiveWireguardDeviceLimit(client.WgDeviceLimit) { + return fmt.Errorf("wireguard: device limit reached (%d)", model.EffectiveWireguardDeviceLimit(client.WgDeviceLimit)) + } + used := append([]string(nil), client.AllowedIPs...) + keys := make(map[string]bool) + primaryKey, _ := wgutil.KeyToHex(client.PublicKey) + if primaryKey != "" { + keys[primaryKey] = true + } + for _, other := range existing { + if strings.EqualFold(other.Email, client.Email) { + continue + } + used = append(used, model.WireguardAllowedIPs(other)...) + peers := model.WireguardClients(other) + // Disabled devices keep both their keys and addresses reserved. + for _, device := range other.WireguardDevices { + if !device.Enable { + peers = append(peers, model.Client{PublicKey: device.PublicKey}) + } + } + for _, peer := range peers { + if key, err := wgutil.KeyToHex(peer.PublicKey); err == nil && key != "" { + if key == primaryKey { + return fmt.Errorf("wireguard: client public key is already in use") + } + keys[key] = true + } + } + } + base := explicitWireguardSubnetBase(settings) + if base == "" { + base = wireguardAllocationBase(used, defaultWireguardBase) + } + for address := range crossUsed { + used = append(used, address) + } + ids := make(map[string]bool) + for i := range client.WireguardDevices { + device := &client.WireguardDevices[i] + name, err := validWireguardDeviceName(device.Name) + if err != nil { + return err + } + device.Name = name + if err := defaultWireguardDeviceIdentity(device); err != nil { + return err + } + if _, err := uuid.Parse(device.Id); err != nil || ids[device.Id] { + return fmt.Errorf("wireguard: invalid or duplicate device id") + } + ids[device.Id] = true + key, err := wgutil.KeyToHex(device.PublicKey) + if err != nil || key == "" { + return fmt.Errorf("wireguard: invalid device public key") + } + if keys[key] { + return fmt.Errorf("wireguard: device public key is already in use") + } + keys[key] = true + if _, err := wgutil.KeyToHex(device.PreSharedKey); err != nil { + return fmt.Errorf("wireguard: invalid device preshared key: %w", err) + } + if len(device.AllowedIPs) == 0 { + address, err := allocateWireguardAddress(used, base, true) + if err != nil { + return err + } + device.AllowedIPs = []string{address} + } + addresses, err := normalizeWireguardAllowedIPs(device.AllowedIPs) + if err != nil || len(addresses) == 0 { + return fmt.Errorf("wireguard: invalid device allowedIPs") + } + if entry, taken := wireguardAllowedIPsOverlap(addresses, used); taken != "" { + return fmt.Errorf("wireguard: device allowedIPs entry %s overlaps %s", entry, taken) + } + device.AllowedIPs = addresses + used = append(used, addresses...) + } + return nil +} diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go index 8f905261f..6049b8e27 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -114,6 +114,7 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, client := *rec.ToClient() // Forwards are set per inbound; see Attach. client.ForwardedPorts = nil + prepareWireguardDeviceAddresses(&client, inbound) if flow, ok := flowsByEmail[rec.Email]; ok && flow != "" { client.Flow = flow } diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 08ff8ba56..524da9b88 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -486,6 +486,13 @@ func (s *ClientService) fillProtocolDefaultsAgainstExisting(c *model.Client, ib return err } switch ib.Protocol { + case model.WireGuard: + c.WireguardDevices = model.CloneWireguardDevices(c.WireguardDevices) + for i := range c.WireguardDevices { + if err := defaultWireguardDeviceIdentity(&c.WireguardDevices[i]); err != nil { + return err + } + } case model.VMESS, model.VLESS: if c.ID == "" { c.ID = uuid.NewString() @@ -860,6 +867,9 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model return false, err } clientForInbound := updated + if inbound.Protocol == model.WireGuard && tunnelCount > 1 { + clientForInbound.WireguardDevices = nil + } if keepInboundFlows { clientForInbound.Flow = inboundFlows[ibId] } @@ -934,6 +944,8 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model "flow": merged.Flow, "security": merged.Security, "client_host_rule_ids": model.EncodeClientHostRuleIds(merged.ClientHostRuleIds), + "wg_devices": encodeWireguardDevices(merged.WireguardDevices), + "wg_device_limit": merged.WgDeviceLimit, "wg_private_key": merged.PrivateKey, "wg_public_key": merged.PublicKey, "wg_allowed_ips": merged.AllowedIPs, @@ -1229,6 +1241,10 @@ func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds [] // the same address on both. if !s.hasTunnelAttachment(inboundSvc, currentIds) { clientWire.AllowedIPs = nil + clientWire.WireguardDevices = model.CloneWireguardDevices(clientWire.WireguardDevices) + for i := range clientWire.WireguardDevices { + clientWire.WireguardDevices[i].AllowedIPs = nil + } } adds := make([]*model.Inbound, 0, len(inboundIds)) @@ -1244,6 +1260,7 @@ func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds [] // A forward is a listener on the target inbound's host, set per inbound: carried over, it // would let a node-reported client choose ports on this host. copyClient.ForwardedPorts = nil + prepareWireguardDeviceAddresses(©Client, inbound) if !addressesFitAmneziaWGInbound(copyClient.AllowedIPs, inbound) { copyClient.AllowedIPs = nil } diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index 28be1a1d0..9ecfdcf7b 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -364,7 +364,7 @@ func (s *ClientService) otherTunnelAllowedIPs(db *gorm.DB, inboundSvc *InboundSe if _, self := selfEmails[strings.ToLower(c.Email)]; self { continue } - for _, addr := range c.AllowedIPs { + for _, addr := range model.WireguardAllowedIPs(c) { used[addr] = label } } @@ -629,7 +629,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model crossAddrs = append(crossAddrs, addr) } for i := range clients { - if entry, taken := wireguardAllowedIPsOverlap(clients[i].AllowedIPs, crossAddrs); taken != "" { + if entry, taken := wireguardAllowedIPsOverlap(model.WireguardAllowedIPs(clients[i]), crossAddrs); taken != "" { return common.NewError("allowedIPs entry", entry, "overlaps", taken, "used by a client on", crossUsed[taken]) } } @@ -830,6 +830,12 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo // forward so the settings JSON and the running peer keep the client's identity. if (oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG) && clientIndex >= 0 && clientIndex < len(oldClients) { old := oldClients[clientIndex] + if clients[0].WireguardDevices == nil { + clients[0].WireguardDevices = model.CloneWireguardDevices(old.WireguardDevices) + } + if clients[0].WgDeviceLimit == 0 { + clients[0].WgDeviceLimit = old.WgDeviceLimit + } if clients[0].PrivateKey == "" { clients[0].PrivateKey = old.PrivateKey } @@ -851,7 +857,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if i == clientIndex { continue } - peers = append(peers, oldClients[i].AllowedIPs...) + peers = append(peers, model.WireguardAllowedIPs(oldClients[i])...) } if entry, taken := wireguardAllowedIPsOverlap(withoutKeptDefaultRoutes(normalized, old.AllowedIPs), peers); taken != "" { return false, common.NewError("wireguard: allowedIPs entry", entry, "overlaps", taken, "used by another client") @@ -870,6 +876,21 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo clients[0].ForwardedPorts = old.ForwardedPorts } } + if oldInbound.Protocol == model.WireGuard { + crossUsed, err := s.otherTunnelAllowedIPs(database.GetDB(), inboundSvc, oldInbound.Id, map[string]struct{}{strings.ToLower(oldEmail): {}}) + if err != nil { + return false, err + } + peers := make([]model.Client, 0, len(oldClients)) + for i := range oldClients { + if i != clientIndex { + peers = append(peers, oldClients[i]) + } + } + if err := validateWireguardDevices(oldInbound.Settings, peers, &clients[0], crossUsed); err != nil { + return false, err + } + } if err := validateAmneziaWGClientWrite(oldInbound, clients, oldEmail); err != nil { return false, err } @@ -925,6 +946,10 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo newMap["privateKey"] = clients[0].PrivateKey newMap["publicKey"] = clients[0].PublicKey newMap["allowedIPs"] = clients[0].AllowedIPs + if oldInbound.Protocol == model.WireGuard { + newMap["wireguardDevices"] = clients[0].WireguardDevices + newMap["wgDeviceLimit"] = clients[0].WgDeviceLimit + } if clients[0].PreSharedKey != "" { newMap["preSharedKey"] = clients[0].PreSharedKey } @@ -1014,6 +1039,21 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if txErr := runSerializedTx(func(tx *gorm.DB) error { // Same re-check-inside-the-writer rule as AddInboundClient (#6225): // the pre-tx pass can race a concurrent writer on another inbound. + if oldInbound.Protocol == model.WireGuard { + crossUsed, err := s.otherTunnelAllowedIPs(tx, inboundSvc, oldInbound.Id, map[string]struct{}{strings.ToLower(oldEmail): {}}) + if err != nil { + return err + } + others := make([]model.Client, 0, len(oldClients)) + for i := range oldClients { + if i != clientIndex { + others = append(others, oldClients[i]) + } + } + if err := validateWireguardDevices(oldInbound.Settings, others, &clients[0], crossUsed); err != nil { + return err + } + } if oldInbound.Protocol == model.AmneziaWG { txPortCtx, pErr := inboundSvc.loadPortConflictContext(tx, oldInbound.NodeID) if pErr != nil { diff --git a/internal/web/service/client_link.go b/internal/web/service/client_link.go index 141e84c3c..a2588b55c 100644 --- a/internal/web/service/client_link.go +++ b/internal/web/service/client_link.go @@ -59,6 +59,12 @@ func applyClientRecordMerge(row *model.ClientRecord, incoming *model.ClientRecor if incoming.AllowedIPs != "" { row.AllowedIPs = incoming.AllowedIPs } + if incoming.WireguardDevices != nil { + row.WireguardDevices = model.CloneWireguardDevices(incoming.WireguardDevices) + } + if incoming.WgDeviceLimit > 0 { + row.WgDeviceLimit = incoming.WgDeviceLimit + } row.PreSharedKey = incoming.PreSharedKey if incoming.KeepAlive != "" { row.KeepAlive = incoming.KeepAlive @@ -154,16 +160,21 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ } isTunnel := inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG - var onLowerTunnel map[int]struct{} + var onLowerTunnel, onLowerWireguard map[int]struct{} if isTunnel && len(existing) > 0 { ids := make([]int, 0, len(existing)) for _, row := range existing { ids = append(ids, row.Id) } var err error - if onLowerTunnel, err = clientsOnLowerTunnel(tx, inboundId, inbound.NodeID, ids); err != nil { + if onLowerTunnel, err = clientsOnLowerTunnel(tx, inboundId, inbound.NodeID, ids, []model.Protocol{model.WireGuard, model.AmneziaWG}); err != nil { return err } + if inbound.Protocol == model.WireGuard { + if onLowerWireguard, err = clientsOnLowerTunnel(tx, inboundId, inbound.NodeID, ids, []model.Protocol{model.WireGuard}); err != nil { + return err + } + } } idByEmail := make(map[string]int, len(emails)) @@ -192,7 +203,8 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ before := *row applyClientRecordMerge(row, incoming) _, outranked := onLowerTunnel[row.Id] - keepLinkOwnedFields(row, &before, isTunnel && !outranked) + _, wireguardOutranked := onLowerWireguard[row.Id] + keepLinkOwnedFields(row, &before, isTunnel && !outranked, inbound.Protocol == model.WireGuard && !wireguardOutranked) preservedUpdatedAt := max(incoming.UpdatedAt, row.UpdatedAt) row.UpdatedAt = preservedUpdatedAt @@ -413,8 +425,12 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wanted // keepLinkOwnedFields undoes the merge of the record fields one inbound cannot decide // alone, or syncing a client's inbounds in turn rewrites the record back and forth. -func keepLinkOwnedFields(row, before *model.ClientRecord, ownsTunnelPeer bool) { +func keepLinkOwnedFields(row, before *model.ClientRecord, ownsTunnelPeer, ownsWireguardDevices bool) { row.Flow = before.Flow + if !ownsWireguardDevices { + row.WireguardDevices = model.CloneWireguardDevices(before.WireguardDevices) + row.WgDeviceLimit = before.WgDeviceLimit + } if ownsTunnelPeer { return } @@ -427,7 +443,7 @@ func keepLinkOwnedFields(row, before *model.ClientRecord, ownsTunnelPeer bool) { // clientsOnLowerTunnel returns the clients also attached to a higher-ranked WireGuard/AmneziaWG // inbound, which owns their record's peer fields: a master-local one first, then the lowest id. -func clientsOnLowerTunnel(tx *gorm.DB, inboundId int, nodeID *int, clientIds []int) (map[int]struct{}, error) { +func clientsOnLowerTunnel(tx *gorm.DB, inboundId int, nodeID *int, clientIds []int, protocols []model.Protocol) (map[int]struct{}, error) { outranks := "inbounds.node_id IS NULL AND client_inbounds.inbound_id < ?" if nodeID != nil { outranks = "(inbounds.node_id IS NULL OR client_inbounds.inbound_id < ?)" @@ -438,7 +454,7 @@ func clientsOnLowerTunnel(tx *gorm.DB, inboundId int, nodeID *int, clientIds []i if err := tx.Table("client_inbounds"). Joins("JOIN inbounds ON inbounds.id = client_inbounds.inbound_id"). Where("client_inbounds.client_id IN ? AND inbounds.protocol IN ?", - batch, []model.Protocol{model.WireGuard, model.AmneziaWG}). + batch, protocols). Where(outranks, inboundId). Distinct().Pluck("client_inbounds.client_id", &ids).Error; err != nil { return nil, err diff --git a/internal/web/service/client_wireguard.go b/internal/web/service/client_wireguard.go index b7188fae2..d208dcc1b 100644 --- a/internal/web/service/client_wireguard.go +++ b/internal/web/service/client_wireguard.go @@ -282,7 +282,7 @@ func withoutKeptDefaultRoutes(entries, stored []string) []string { func defaultWireguardClients(settingsJSON string, existing, clients []model.Client, interfaceClients []any, crossInboundUsed map[string]string) error { used := make([]string, 0) for i := range existing { - used = append(used, existing[i].AllowedIPs...) + used = append(used, model.WireguardAllowedIPs(existing[i])...) } base := explicitWireguardSubnetBase(settingsJSON) if base == "" { @@ -329,13 +329,19 @@ func defaultWireguardClients(settingsJSON string, existing, clients []model.Clie } c.AllowedIPs = normalized } - used = append(used, c.AllowedIPs...) + others := append(append([]model.Client(nil), existing...), clients[:i]...) + if err := validateWireguardDevices(settingsJSON, others, c, crossInboundUsed); err != nil { + return err + } + used = append(used, model.WireguardAllowedIPs(*c)...) if i < len(interfaceClients) { if m, ok := interfaceClients[i].(map[string]any); ok { m["privateKey"] = c.PrivateKey m["publicKey"] = c.PublicKey m["allowedIPs"] = c.AllowedIPs + m["wireguardDevices"] = c.WireguardDevices + m["wgDeviceLimit"] = c.WgDeviceLimit if c.PreSharedKey != "" { m["preSharedKey"] = c.PreSharedKey } diff --git a/internal/web/service/client_wireguard_devices_test.go b/internal/web/service/client_wireguard_devices_test.go new file mode 100644 index 000000000..3a951479d --- /dev/null +++ b/internal/web/service/client_wireguard_devices_test.go @@ -0,0 +1,225 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "sync" + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func setupWireguardDeviceClient(t *testing.T, email string, ports ...int) (*ClientService, []int) { + t.Helper() + setupBulkDB(t) + svc := &ClientService{} + ids := []int{} + for _, port := range ports { + ib := mkInbound(t, port, model.WireGuard, wgServerSettings()) + payload := &model.Inbound{Id: ib.Id, Settings: clientsSettings(t, []model.Client{{Email: email, Enable: true}})} + if len(ids) == 0 { + if _, err := svc.AddInboundClient(&InboundService{}, payload); err != nil { + t.Fatal(err) + } + } else if _, err := svc.AttachByEmail(&InboundService{}, email, []int{ib.Id}); err != nil { + t.Fatal(err) + } + ids = append(ids, ib.Id) + } + return svc, ids +} + +func TestWireguardDevicesCRUDAndLimit(t *testing.T) { + svc, _ := setupWireguardDeviceClient(t, "devices@wg", 51910, 51911) + initial, err := svc.WireguardDevices("devices@wg") + if err != nil { + t.Fatal(err) + } + if initial.Limit != 5 || len(initial.Inbounds) != 2 { + t.Fatalf("initial list: %+v", initial) + } + primary := initial.Inbounds[0].Devices[0] + if err := svc.SetWireguardDeviceLimit("devices@wg", 2); err != nil { + t.Fatal(err) + } + if err := svc.AddWireguardDevice("devices@wg", "Phone"); err != nil { + t.Fatal(err) + } + if err := svc.AddWireguardDevice("devices@wg", "Laptop"); err == nil { + t.Fatal("device limit was bypassed") + } + devices, err := svc.WireguardDevices("devices@wg") + if err != nil { + t.Fatal(err) + } + device := devices.Inbounds[0].Devices[1] + if device.Id == "" || device.PublicKey == primary.PublicKey || device.PrivateKey == primary.PrivateKey { + t.Fatal("device needs its own identity") + } + if device.AllowedIPs[0] == primary.AllowedIPs[0] { + t.Fatal("device address collided with primary") + } + if devices.Inbounds[1].Devices[1].Id != device.Id { + t.Fatal("device identity differs between inbounds") + } + if err := svc.SetWireguardDeviceLimit("devices@wg", 1); err == nil { + t.Fatal("lowered limit below current count") + } + enabled := false + name := "Work phone" + if err := svc.UpdateWireguardDevice("devices@wg", device.Id, WireguardDevicePatch{Name: &name, Enable: &enabled}); err != nil { + t.Fatal(err) + } + updated, err := svc.WireguardDevices("devices@wg") + if err != nil { + t.Fatal(err) + } + for _, ib := range updated.Inbounds { + if ib.Devices[1].Enable || ib.Devices[1].Name != name { + t.Fatal("device patch was not applied to every inbound") + } + } + if err := svc.DeleteWireguardDevice("devices@wg", device.Id); err != nil { + t.Fatal(err) + } + if err := svc.AddWireguardDevice("devices@wg", "Laptop"); err != nil { + t.Fatal("deleted device did not release its slot:", err) + } + final, err := svc.WireguardDevices("devices@wg") + if err != nil { + t.Fatal(err) + } + if final.Inbounds[0].Devices[0].PrivateKey != primary.PrivateKey { + t.Fatal("legacy primary config changed") + } + if final.Inbounds[0].Devices[1].AllowedIPs[0] != device.AllowedIPs[0] { + t.Fatal("deleted address was not reusable") + } +} + +func TestWireguardDeviceWritesRollbackAcrossInbounds(t *testing.T) { + svc, ids := setupWireguardDeviceClient(t, "rollback@wg", 51912, 51913) + // A stale attachment must roll back the first inbound too. + var ib model.Inbound + if err := database.GetDB().First(&ib, ids[0]).Error; err != nil { + t.Fatal(err) + } + original := ib.Settings + if err := database.GetDB().Model(&model.Inbound{}).Where("id = ?", ids[1]).Update("settings", `{"clients":[]}`).Error; err != nil { + t.Fatal(err) + } + if err := svc.AddWireguardDevice("rollback@wg", "Phone"); err == nil { + t.Fatal("missing settings client was accepted") + } + if err := database.GetDB().First(&ib, ids[0]).Error; err != nil { + t.Fatal(err) + } + if ib.Settings != original { + t.Fatal("failed fanout left a partially created device") + } +} + +func TestWireguardDeviceConcurrentAddsRespectLimit(t *testing.T) { + svc, _ := setupWireguardDeviceClient(t, "concurrent@wg", 51914) + if err := svc.SetWireguardDeviceLimit("concurrent@wg", 2); err != nil { + t.Fatal(err) + } + var group sync.WaitGroup + results := make(chan error, 8) + for range 8 { + group.Go(func() { results <- svc.AddWireguardDevice("concurrent@wg", "Phone") }) + } + group.Wait() + close(results) + successes := 0 + for err := range results { + if err == nil { + successes++ + } + } + if successes != 1 { + t.Fatalf("got %d successful adds, want 1", successes) + } +} + +func TestWireguardDeviceMetadataEditPreservesDevices(t *testing.T) { + svc, ids := setupWireguardDeviceClient(t, "metadata@wg", 51915) + if err := svc.AddWireguardDevice("metadata@wg", "Phone"); err != nil { + t.Fatal(err) + } + before, err := svc.WireguardDevices("metadata@wg") + if err != nil { + t.Fatal(err) + } + payload := &model.Inbound{Id: ids[0], Settings: clientsSettings(t, []model.Client{{Email: "metadata@wg", Enable: true, Comment: "updated"}})} + if _, err := svc.UpdateInboundClient(&InboundService{}, payload, "metadata@wg"); err != nil { + t.Fatal(err) + } + after, err := svc.WireguardDevices("metadata@wg") + if err != nil { + t.Fatal(err) + } + a, _ := json.Marshal(before.Inbounds[0].Devices) + b, _ := json.Marshal(after.Inbounds[0].Devices) + if string(a) != string(b) { + t.Fatalf("metadata update changed devices") + } +} + +// oldNodeRuntime is a node whose build ignores a client's extra WireGuard devices. +type oldNodeRuntime struct{ fakeNodeRuntime } + +const oldNodeRefusal = "node old does not support WireGuard client devices" + +func (*oldNodeRuntime) CheckWireguardDevices(context.Context) error { + return errors.New(oldNodeRefusal) +} + +// A device the node would never serve must be refused before it is stored: saved, the +// panel would hand out its config and leave the node waiting for a push it rejects. +func TestWireguardDeviceRefusedBeforeSaveOnNodeWithoutSupport(t *testing.T) { + svc, ids := setupWireguardDeviceClient(t, "node@wg", 51930) + mgr := useTestRuntimeManager(t) + db := database.GetDB() + node := &model.Node{Name: "old", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true, Status: "online"} + if err := db.Create(node).Error; err != nil { + t.Fatal(err) + } + if err := db.Model(&model.Inbound{}).Where("id = ?", ids[0]).Update("node_id", node.Id).Error; err != nil { + t.Fatal(err) + } + deviceCount := func() int { + t.Helper() + list, err := svc.WireguardDevices("node@wg") + if err != nil { + t.Fatal(err) + } + return len(list.Inbounds[0].Devices) + } + nodeDirty := func() bool { + t.Helper() + _, _, dirty, _, err := (&NodeService{}).NodeSyncState(node.Id) + if err != nil { + t.Fatal(err) + } + return dirty + } + + mgr.SetRuntimeOverride(node.Id, &oldNodeRuntime{}) + if err := svc.AddWireguardDevice("node@wg", "Phone"); err == nil || err.Error() != oldNodeRefusal { + t.Fatalf("add on an old node: err = %v, want %q", err, oldNodeRefusal) + } + if got := deviceCount(); got != 1 || nodeDirty() { + t.Fatalf("refused add left %d devices, node dirty = %v; want 1 and false", got, nodeDirty()) + } + + mgr.SetRuntimeOverride(node.Id, &fakeNodeRuntime{}) + if err := svc.AddWireguardDevice("node@wg", "Phone"); err != nil { + t.Fatalf("add on a current node: %v", err) + } + if got := deviceCount(); got != 2 || !nodeDirty() { + t.Fatalf("accepted add left %d devices, node dirty = %v; want 2 and true", got, nodeDirty()) + } +} diff --git a/internal/web/service/client_wireguard_readd_test.go b/internal/web/service/client_wireguard_readd_test.go new file mode 100644 index 000000000..cebb9832c --- /dev/null +++ b/internal/web/service/client_wireguard_readd_test.go @@ -0,0 +1,50 @@ +package service + +import ( + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestWireguardReEnableRetainsAllDeviceCredentials(t *testing.T) { + for _, bulk := range []bool{true, false} { + t.Run(map[bool]string{true: "bulk", false: "traffic-reset"}[bulk], func(t *testing.T) { + setupConflictDB(t) + manager := useTestRuntimeManager(t) + probe := new(reverseUserProbe) + manager.SetLocalRuntimeOverride(probe) + client := model.Client{ + Email: "wireguard-devices", Enable: !bulk, PublicKey: "primary", AllowedIPs: []string{"10.0.0.2/32"}, + PreSharedKey: "psk", KeepAlive: model.KeepAlivePtr(25), + WireguardDevices: []model.WireguardDevice{{Id: "phone", Enable: true, PublicKey: "phone-key", AllowedIPs: []string{"10.0.0.3/32"}}}, + } + seedInboundConflict(t, "wg-readd", "0.0.0.0", 50079, model.WireGuard, "", clientsSettings(t, []model.Client{client})) + inbound := loadInboundByTag(t, "wg-readd") + if err := (&ClientService{}).SyncInbound(nil, inbound.Id, []model.Client{client}); err != nil { + t.Fatal(err) + } + if bulk { + if _, _, err := (&ClientService{}).BulkSetEnable(&InboundService{}, []string{client.Email}, true); err != nil { + t.Fatal(err) + } + } else { + depleteClientTraffic(t, inbound.Id, client.Email) + if _, err := (&InboundService{}).ResetClientTraffic(inbound.Id, client.Email); err != nil { + t.Fatal(err) + } + } + users := probe.recorded() + if len(users) != 1 { + t.Fatalf("runtime received %d users, want one parent with devices", len(users)) + } + user := users[0] + devices, ok := user["wireguardDevices"].([]model.WireguardDevice) + if !ok || len(devices) != 1 || devices[0].PublicKey != "phone-key" { + t.Fatalf("lost device credentials: %v", user) + } + if user["publicKey"] != "primary" || user["preSharedKey"] != "psk" || user["keepAlive"] != "25" { + t.Fatalf("lost primary credentials: %v", user) + } + }) + } +} diff --git a/internal/web/service/client_wireguard_validation_test.go b/internal/web/service/client_wireguard_validation_test.go new file mode 100644 index 000000000..6b66240a6 --- /dev/null +++ b/internal/web/service/client_wireguard_validation_test.go @@ -0,0 +1,148 @@ +package service + +import ( + "fmt" + "reflect" + "testing" + + "github.com/google/uuid" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard" +) + +func TestValidateWireguardDevicesAllocatesDistinctReservedAddresses(t *testing.T) { + client := model.Client{Email: "owner", AllowedIPs: []string{"10.0.0.2/32"}, WireguardDevices: []model.WireguardDevice{ + {Name: "Phone", Enable: true}, {Name: "Laptop", Enable: false}, + }} + if err := validateWireguardDevices("", nil, &client, map[string]string{"10.0.0.3/32": "other inbound"}); err != nil { + t.Fatal(err) + } + if client.WireguardDevices[0].AllowedIPs[0] != "10.0.0.4/32" || client.WireguardDevices[1].AllowedIPs[0] != "10.0.0.5/32" { + t.Fatalf("unexpected allocation: %+v", client.WireguardDevices) + } + if client.WireguardDevices[0].PublicKey == client.WireguardDevices[1].PublicKey { + t.Fatal("device keys collided") + } + before := model.CloneWireguardDevices(client.WireguardDevices) + if err := validateWireguardDevices("", nil, &client, nil); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(before, client.WireguardDevices) { + t.Fatal("validation rotated device identity") + } +} + +func TestWireguardDevicesGenericCreateKeepsIdentityAcrossInbounds(t *testing.T) { + for _, bulk := range []bool{false, true} { + t.Run(fmt.Sprintf("bulk=%v", bulk), func(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + ids := []int{} + for i := range 2 { + settings := fmt.Sprintf(`{"secretKey":%q,"subnetIp":"10.100.%d.0","subnetCidr":24,"clients":[]}`, wgTestSecretKey(), i+1) + ids = append(ids, mkInbound(t, 51926+i, model.WireGuard, settings).Id) + } + payload := ClientCreatePayload{Client: model.Client{Email: "generic@wg", Enable: true, WireguardDevices: []model.WireguardDevice{{Name: "Phone", Enable: true}}}, InboundIds: ids} + if bulk { + result, _, err := svc.BulkCreate(&InboundService{}, []ClientCreatePayload{payload}) + if err != nil || result.Created != 1 { + t.Fatalf("BulkCreate: %+v %v", result, err) + } + } else if _, err := svc.Create(&InboundService{}, &payload); err != nil { + t.Fatal(err) + } + devices, err := svc.WireguardDevices("generic@wg") + if err != nil || len(devices.Inbounds) != 2 { + t.Fatalf("devices: %+v %v", devices, err) + } + first := devices.Inbounds[0].Devices[1] + second := devices.Inbounds[1].Devices[1] + if first.Id != second.Id || first.PrivateKey != second.PrivateKey || first.PublicKey != second.PublicKey { + t.Fatal("generic create generated independent device identities") + } + if first.AllowedIPs[0] != "10.100.1.3/32" || second.AllowedIPs[0] != "10.100.2.3/32" { + t.Fatalf("device allocation lost inbound subnet: %v / %v", first.AllowedIPs, second.AllowedIPs) + } + }) + } +} + +func TestWireguardDeviceLimitIndependentOfAmneziaPeerOwner(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + awg := mkInbound(t, 51928, model.AmneziaWG, `{"server":{"subnetIp":"10.8.1.0","subnetCidr":24},"clients":[]}`) + wg := mkInbound(t, 51929, model.WireGuard, wgServerSettings()) + if _, err := svc.Create(&InboundService{}, &ClientCreatePayload{Client: model.Client{Email: "mixed@wg", Enable: true}, InboundIds: []int{awg.Id, wg.Id}}); err != nil { + t.Fatal(err) + } + if err := svc.SetWireguardDeviceLimit("mixed@wg", 1); err != nil { + t.Fatal(err) + } + if err := svc.AddWireguardDevice("mixed@wg", "Phone"); err == nil { + t.Fatal("AmneziaWG peer ownership bypassed WireGuard device limit") + } + record := lookupClientRecord(t, "mixed@wg") + if record.WgDeviceLimit != 1 { + t.Fatalf("WireGuard limit did not persist: %d", record.WgDeviceLimit) + } +} + +func TestValidateWireguardDevicesRejectsConflictsAndLimit(t *testing.T) { + privateKey, publicKey, err := wgutil.GenerateWireguardKeypair() + if err != nil { + t.Fatal(err) + } + base := model.Client{Email: "owner", PublicKey: publicKey, AllowedIPs: []string{"10.0.0.2/32"}} + for _, tc := range []struct { + name string + limit int + device model.WireguardDevice + }{ + {name: "duplicate key", device: model.WireguardDevice{Name: "Phone", PrivateKey: privateKey}}, + {name: "duplicate address", device: model.WireguardDevice{Name: "Phone", AllowedIPs: []string{"10.0.0.2/32"}}}, + {name: "limit", limit: 1, device: model.WireguardDevice{Name: "Phone"}}, + {name: "invalid limit", limit: 33}, + {name: "invalid id", device: model.WireguardDevice{Id: "primary", Name: "Phone"}}, + {name: "invalid name", device: model.WireguardDevice{Name: "Phone\nLaptop"}}, + } { + t.Run(tc.name, func(t *testing.T) { + client := base + client.WgDeviceLimit = tc.limit + client.WireguardDevices = []model.WireguardDevice{tc.device} + if err := validateWireguardDevices("", nil, &client, nil); err == nil { + t.Fatal("invalid device was accepted") + } + }) + } +} + +func TestDefaultWireguardClientsReservesDisabledDevice(t *testing.T) { + existing := []model.Client{{Email: "other", AllowedIPs: []string{"10.0.0.2/32"}, WireguardDevices: []model.WireguardDevice{{Id: uuid.NewString(), Enable: false, AllowedIPs: []string{"10.0.0.3/32"}}}}} + clients := []model.Client{{Email: "new", Enable: true}} + if err := defaultWireguardClients("", existing, clients, nil, nil); err != nil { + t.Fatal(err) + } + if clients[0].AllowedIPs[0] != "10.0.0.4/32" { + t.Fatalf("disabled device address reused: %v", clients[0].AllowedIPs) + } +} + +func TestWireguardMetadataUpdatePreservesDevices(t *testing.T) { + setupBulkDB(t) + svc := &ClientService{} + ib := mkInbound(t, 51925, model.WireGuard, wgServerSettings()) + client := model.Client{Email: "metadata@wg", Enable: true, WgDeviceLimit: 3, WireguardDevices: []model.WireguardDevice{{Name: "Phone", Enable: true}}} + if _, err := svc.AddInboundClient(&InboundService{}, &model.Inbound{Id: ib.Id, Settings: clientsSettings(t, []model.Client{client})}); err != nil { + t.Fatal(err) + } + before := lookupClientRecord(t, client.Email) + update := model.Client{Email: client.Email, Enable: true, Comment: "updated"} + if _, err := svc.UpdateInboundClient(&InboundService{}, &model.Inbound{Id: ib.Id, Settings: clientsSettings(t, []model.Client{update})}, client.Email); err != nil { + t.Fatal(err) + } + after := lookupClientRecord(t, client.Email) + if !reflect.DeepEqual(before.WireguardDevices, after.WireguardDevices) || after.WgDeviceLimit != 3 { + t.Fatal("metadata edit lost devices") + } +} diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 044108b1b..5a1faec16 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -2341,7 +2341,6 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, } postCommitApply = func() { if runningInbound != nil && applyInboundUserOps(rt, runningInbound, runtimeInbound) { - logger.Debug("Inbound clients updated in place on", rt.Name(), ":", oldInbound.Tag) return } if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil { @@ -2425,13 +2424,23 @@ func servedOutsideXray(protocol model.Protocol) bool { return protocol == model.MTProto || protocol == model.TUIC || protocol == model.AmneziaWG } -// applyInboundUserOps reports whether per-user core ops moved running to next, so -// its listener and live connections survive; false means rebuild the handler. +// applyInboundUserOps handles client-only changes in place, or returns false +// when the handler must be rebuilt. func applyInboundUserOps(rt runtime.Runtime, running, next *model.Inbound) bool { diff, ok := xray.InboundUserOps(running.GenXrayInboundConfig(), next.GenXrayInboundConfig()) if !ok { return false } + if next.Protocol == model.WireGuard { + if diff.DropsUsers() { + return false + } + if !diff.Empty() { + // Reconcile peers and the Xray config snapshot together. + (&XrayService{}).SetToNeedReconcile() + } + return true + } ctx := context.Background() for _, u := range diff.RemovedUsers { if err := rt.RemoveUser(ctx, next, u.Email); err != nil && !xray.IsMissingUserErr(err) { @@ -2451,6 +2460,7 @@ func applyInboundUserOps(rt runtime.Runtime, running, next *model.Inbound) bool return false } } + logger.Debug("Inbound clients updated in place on", rt.Name(), ":", next.Tag) return true } diff --git a/internal/web/service/inbound_node_claims.go b/internal/web/service/inbound_node_claims.go index 86074208b..1e655a591 100644 --- a/internal/web/service/inbound_node_claims.go +++ b/internal/web/service/inbound_node_claims.go @@ -296,7 +296,7 @@ func sharedRecordWouldChange(rec *model.ClientRecord, reported *model.Client) bo incoming.CreatedAt = 0 merged := *rec applyClientRecordMerge(&merged, incoming) - keepLinkOwnedFields(&merged, rec, false) + keepLinkOwnedFields(&merged, rec, false, false) return !reflect.DeepEqual(merged, *rec) } diff --git a/internal/web/service/inbound_traffic.go b/internal/web/service/inbound_traffic.go index e4e022d1b..ffbd90a30 100644 --- a/internal/web/service/inbound_traffic.go +++ b/internal/web/service/inbound_traffic.go @@ -364,18 +364,19 @@ func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.Cl // peers fail it without publicKey/allowedIPs, and a failed add restarts Xray. func coreUserFromClient(c *model.Client, cipher string) map[string]any { return map[string]any{ - "email": c.Email, - "id": c.ID, - "auth": c.Auth, - "security": c.Security, - "flow": c.Flow, - "password": c.Password, - "cipher": cipher, - "publicKey": c.PublicKey, - "allowedIPs": c.AllowedIPs, - "preSharedKey": c.PreSharedKey, - "keepAlive": keepAliveStr(c.KeepAliveSeconds()), - "reverse": c.Reverse, + "email": c.Email, + "id": c.ID, + "auth": c.Auth, + "security": c.Security, + "flow": c.Flow, + "password": c.Password, + "cipher": cipher, + "publicKey": c.PublicKey, + "allowedIPs": c.AllowedIPs, + "preSharedKey": c.PreSharedKey, + "keepAlive": keepAliveStr(c.KeepAliveSeconds()), + "reverse": c.Reverse, + "wireguardDevices": c.WireguardDevices, } } diff --git a/internal/web/service/wireguard_hot_apply_test.go b/internal/web/service/wireguard_hot_apply_test.go new file mode 100644 index 000000000..c07f3c738 --- /dev/null +++ b/internal/web/service/wireguard_hot_apply_test.go @@ -0,0 +1,139 @@ +package service + +import ( + "maps" + "net" + "slices" + "strings" + "testing" + + "github.com/xtls/xray-core/app/proxyman/command" + "github.com/xtls/xray-core/proxy/wireguard" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func TestWireguardDeviceChangesKeepOtherCorePeers(t *testing.T) { + newKey := func() (string, string) { + t.Helper() + private, public, err := wgutil.GenerateWireguardKeypair() + if err != nil { + t.Fatal(err) + } + return private, public + } + serverKey, _ := newKey() + _, primary := newKey() + _, phone := newKey() + _, other := newKey() + udp, err := net.ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := udp.LocalAddr().(*net.UDPAddr).Port + _ = udp.Close() + inbound := model.Inbound{Tag: "wg-hot", Listen: "127.0.0.1", Port: port, Protocol: model.WireGuard} + clients := []model.Client{ + {Email: "owner", Enable: true, PublicKey: primary, AllowedIPs: []string{"10.0.0.2/32"}, KeepAlive: model.KeepAlivePtr(25)}, + {Email: "other", Enable: true, PublicKey: other, AllowedIPs: []string{"10.0.0.3/32"}}, + } + render := func() *xray.InboundConfig { + inbound.Settings = string(mustJSON(t, map[string]any{ + "secretKey": serverKey, "address": []string{"10.0.0.1/24"}, "clients": clients, + })) + return inbound.GenXrayInboundConfig() + } + initial := isolationConfig(t, *render()) + api := startIsolationCore(t, initial) + + device := model.WireguardDevice{ + Id: "phone", Enable: true, PublicKey: phone, AllowedIPs: []string{"10.0.0.4/32"}, + } + disabled := device + disabled.Enable = false + previous := initial + for _, step := range []struct { + name string + devices []model.WireguardDevice + active bool + }{ + {name: "add", devices: []model.WireguardDevice{device}, active: true}, + {name: "disable", devices: []model.WireguardDevice{disabled}}, + {name: "enable", devices: []model.WireguardDevice{device}, active: true}, + {name: "delete"}, + } { + clients[0].WireguardDevices = step.devices + next := *previous + next.InboundConfigs = slices.Clone(previous.InboundConfigs) + next.InboundConfigs[len(next.InboundConfigs)-1] = *render() + diff, ok := xray.ComputeHotDiff(previous, &next) + if !ok || diff.DropsUsers() || len(diff.RemovedInboundTags)+len(diff.AddedInbounds) != 0 || + len(diff.AddedUsers) != 1 || diff.AddedUsers[0].Email != "owner" || + diff.AddedUsers[0].User["keepAlive"] != "25" { + t.Fatalf("%s: expected only owner peer changes, got %+v", step.name, diff) + } + if step.active && len(diff.RemovedUsers) != 0 || + !step.active && (len(diff.RemovedUsers) != 1 || diff.RemovedUsers[0].Email != "owner") { + t.Fatalf("%s: unexpected removals: %+v", step.name, diff.RemovedUsers) + } + if !applyXrayHotDiff(api, diff) { + t.Fatalf("%s: peer update failed", step.name) + } + users, err := (*api.HandlerServiceClient).GetInboundUsers(t.Context(), &command.GetInboundUserRequest{Tag: inbound.Tag}) + if err != nil { + t.Fatal(err) + } + got := make(map[string]string) + for _, user := range users.GetUsers() { + account, err := user.GetAccount().GetInstance() + if err != nil { + t.Fatal(err) + } + got[account.(*wireguard.PeerConfig).GetPublicKey()] = user.GetEmail() + } + primaryHex, _ := wgutil.KeyToHex(primary) + otherHex, _ := wgutil.KeyToHex(other) + phoneHex, _ := wgutil.KeyToHex(phone) + want := map[string]string{primaryHex: "owner", otherHex: "other"} + if step.active { + want[phoneHex] = "owner" + } + if !maps.Equal(got, want) { + t.Fatalf("%s: core peers = %v, want %v", step.name, got, want) + } + previous = &next + } +} + +func TestNodeWireguardDevicePushSchedulesReconcile(t *testing.T) { + setupConflictDB(t) + wasPending := isNeedXrayReconcile.Swap(false) + t.Cleanup(func() { isNeedXrayReconcile.Store(wasPending) }) + probe := &inboundOpsProbe{} + useTestRuntimeManager(t).SetLocalRuntimeOverride(probe) + + client := model.Client{ + Email: "wg-owner", Enable: true, PublicKey: strings.Repeat("01", 32), + AllowedIPs: []string{"10.0.0.2/32"}, + } + seedInboundConflict(t, "wg-node", "127.0.0.1", 50091, model.WireGuard, "", clientsSettings(t, []model.Client{client})) + stored := loadInboundByTag(t, "wg-node") + if err := (&ClientService{}).SyncInbound(nil, stored.Id, []model.Client{client}); err != nil { + t.Fatal(err) + } + mkTraffic(t, stored.Id, client.Email, 0, 0, 0, 0, true) + + client.WireguardDevices = []model.WireguardDevice{{ + Id: "phone", Enable: true, PublicKey: strings.Repeat("02", 32), AllowedIPs: []string{"10.0.0.3/32"}, + }} + pushed := *stored + pushed.Settings = clientsSettings(t, []model.Client{client}) + if _, restart, err := (&InboundService{FromNodeSync: true}).UpdateInbound(&pushed); err != nil || restart { + t.Fatalf("device push returned restart=%t, err=%v", restart, err) + } + if ops := probe.recorded(); len(ops) != 0 || !isNeedXrayReconcile.Load() { + t.Fatalf("expected scheduled reconciliation, got runtime ops %q", ops) + } +} diff --git a/internal/web/service/xray.go b/internal/web/service/xray.go index 600952258..779d66cfd 100644 --- a/internal/web/service/xray.go +++ b/internal/web/service/xray.go @@ -309,6 +309,7 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) { c.AllowedIPs = inboundClient.AllowedIPs c.PreSharedKey = inboundClient.PreSharedKey c.PublicKey = inboundClient.PublicKey + c.WireguardDevices = inboundClient.WireguardDevices // #6731: a nil settings keepalive must not keep the other tunnel's value. if inboundClient.KeepAlive == nil { c.KeepAlive = nil @@ -317,7 +318,7 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) { c.KeepAlive = &keepalive } } - wgPeers = append(wgPeers, model.WireguardPeerFromClient(c)) + wgPeers = append(wgPeers, model.WireguardPeersFromClient(c)...) continue } finalClients = append(finalClients, entry) @@ -1706,7 +1707,16 @@ func applyXrayHotDiff(hotAPI *xray.XrayAPI, diff *xray.HotDiff) bool { // Removals first so changed handlers and port swaps never collide with // the additions that follow. for _, u := range diff.RemovedUsers { - if err := hotAPI.RemoveUser(u.Tag, u.Email); err != nil && !xray.IsMissingHandlerErr(err) { + var err error + if u.Protocol == string(model.WireGuard) { + err = hotAPI.RemoveWireguardUsers(u.Tag, u.Email) + } else { + err = hotAPI.RemoveUser(u.Tag, u.Email) + if xray.IsMissingHandlerErr(err) { + continue + } + } + if err != nil { logger.Info("hot apply: remove user [", u.Email, "] from [", u.Tag, "] failed:", err) return false } @@ -1762,7 +1772,7 @@ func persistHotConfig(process *xray.Process) { // already applied through the runtime API) replaces the existing user instead. func addUserReconciling(api *xray.XrayAPI, u xray.UserOp) error { err := api.AddUser(u.Protocol, u.Tag, u.User) - if err == nil || !xray.IsUserExistsErr(err) { + if err == nil || u.Protocol == string(model.WireGuard) || !xray.IsUserExistsErr(err) { return err } if delErr := api.RemoveUser(u.Tag, u.Email); delErr != nil && !xray.IsMissingHandlerErr(delErr) { diff --git a/internal/web/service/xray_wireguard_config_test.go b/internal/web/service/xray_wireguard_config_test.go index eef8d3093..ee416e84c 100644 --- a/internal/web/service/xray_wireguard_config_test.go +++ b/internal/web/service/xray_wireguard_config_test.go @@ -195,6 +195,40 @@ func TestGetXrayConfigWireGuardDisabledClientExcluded(t *testing.T) { } } +func TestGetXrayConfigWireGuardDevicesUseInboundIdentityAndParentLifecycle(t *testing.T) { + client := model.Client{ + Email: "devices@wg.test", Enable: true, PublicKey: "primary", AllowedIPs: []string{"10.0.0.2/32"}, + WireguardDevices: []model.WireguardDevice{{Id: "stale", Enable: true, PublicKey: "stale-shared-key", AllowedIPs: []string{"10.9.0.3/32"}}}, + } + seedWGInbound(t, "wg-devices", 51829, []model.Client{client}) + client.WireguardDevices = []model.WireguardDevice{ + {Id: "phone", Enable: true, PublicKey: "phone-key", AllowedIPs: []string{"10.0.0.3/32"}}, + {Id: "disabled", Enable: false, PublicKey: "disabled-key", AllowedIPs: []string{"10.0.0.4/32"}}, + } + settings, err := json.Marshal(map[string]any{"secretKey": wgTestSecretKey(), "clients": []model.Client{client}}) + if err != nil { + t.Fatal(err) + } + if err := database.GetDB().Model(&model.Inbound{}).Where("tag = ?", "wg-devices").Update("settings", string(settings)).Error; err != nil { + t.Fatal(err) + } + peers := wgPeerList(t, wgInboundEmittedSettings(t, "wg-devices")) + if len(peers) != 2 || peers[1]["publicKey"] != "phone-key" { + t.Fatalf("expected inbound-local primary and phone peers: %v", peers) + } + for _, peer := range peers { + if peer["email"] != client.Email { + t.Fatalf("lost common traffic attribution: %v", peer) + } + } + if err := database.GetDB().Model(&model.ClientRecord{}).Where("email = ?", client.Email).Update("enable", false).Error; err != nil { + t.Fatal(err) + } + if peers := wgPeerList(t, wgInboundEmittedSettings(t, "wg-devices")); len(peers) != 0 { + t.Fatalf("disabled parent retained device peers: %v", peers) + } +} + func TestGetXrayConfigWireGuardUsesInboundLocalTunnelFields(t *testing.T) { email := seedDualTunnelClient(t, true, model.KeepAlivePtr(15)) diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index ddce6630b..f9e609b79 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -816,6 +816,17 @@ "tabBasics": "أساسي", "tabCredentials": "بيانات الاعتماد", "tabLinks": "الروابط", + "wgDevices": { + "title": "أجهزة WireGuard", + "limit": "الحد الأقصى للأجهزة", + "primary": "الجهاز الأساسي", + "enabled": "مفعّل", + "subscription": "نسخ رابط الاشتراك", + "deleteConfirm": "هل تريد حذف هذا الجهاز وتحرير عنوانه؟", + "remove": "حذف", + "name": "اسم الجهاز", + "add": "إضافة جهاز" + }, "wireguardConfig": "إعدادات WireGuard", "config": "الإعداد", "linksHint": "أضف روابط مشاركة من جهات خارجية وعناوين اشتراك خارجية لتضمينها في اشتراك هذا العميل.", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index a186871de..fed43cf1b 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -816,6 +816,17 @@ "tabBasics": "Basics", "tabCredentials": "Credentials", "tabLinks": "Links", + "wgDevices": { + "title": "WireGuard devices", + "limit": "Device limit", + "primary": "Primary device", + "enabled": "Enabled", + "subscription": "Copy subscription", + "deleteConfirm": "Delete this device and release its address?", + "remove": "Delete", + "name": "Device name", + "add": "Add device" + }, "wireguardConfig": "WireGuard config", "config": "Config", "linksHint": "Add third-party share links and remote subscription URLs to include in this client's subscription.", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index ad87610d5..fcc67e0f4 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -816,6 +816,17 @@ "tabBasics": "Básico", "tabCredentials": "Credenciales", "tabLinks": "Enlaces", + "wgDevices": { + "title": "Dispositivos WireGuard", + "limit": "Límite de dispositivos", + "primary": "Dispositivo principal", + "enabled": "Activado", + "subscription": "Copiar suscripción", + "deleteConfirm": "¿Eliminar este dispositivo y liberar su dirección?", + "remove": "Eliminar", + "name": "Nombre del dispositivo", + "add": "Añadir dispositivo" + }, "wireguardConfig": "Configuración de WireGuard", "config": "Configuración", "linksHint": "Añade enlaces de terceros y URLs de suscripción remotas para incluirlos en la suscripción de este cliente.", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index aa581f786..5a66ec7d6 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -816,6 +816,17 @@ "tabBasics": "پایه", "tabCredentials": "اطلاعات اتصال", "tabLinks": "لینک‌ها", + "wgDevices": { + "title": "دستگاه‌های WireGuard", + "limit": "حداکثر تعداد دستگاه‌ها", + "primary": "دستگاه اصلی", + "enabled": "فعال", + "subscription": "کپی پیوند اشتراک", + "deleteConfirm": "این دستگاه حذف و نشانی آن آزاد شود؟", + "remove": "حذف", + "name": "نام دستگاه", + "add": "افزودن دستگاه" + }, "wireguardConfig": "پیکربندی WireGuard", "config": "پیکربندی", "linksHint": "لینک‌های اشتراک شخص‌ثالث و آدرس سابسکریپشن‌های خارجی را اضافه کنید تا در سابسکریپشن این کاربر قرار گیرند.", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 0164f5fd7..3385ccd0b 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -816,6 +816,17 @@ "tabBasics": "Dasar", "tabCredentials": "Kredensial", "tabLinks": "Tautan", + "wgDevices": { + "title": "Perangkat WireGuard", + "limit": "Batas perangkat", + "primary": "Perangkat utama", + "enabled": "Aktif", + "subscription": "Salin langganan", + "deleteConfirm": "Hapus perangkat ini dan bebaskan alamatnya?", + "remove": "Hapus", + "name": "Nama perangkat", + "add": "Tambah perangkat" + }, "wireguardConfig": "Konfigurasi WireGuard", "config": "Konfigurasi", "linksHint": "Tambahkan tautan berbagi pihak ketiga dan URL langganan jarak jauh untuk disertakan dalam langganan klien ini.", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 96245f9b4..0d388a370 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -816,6 +816,17 @@ "tabBasics": "基本", "tabCredentials": "認証情報", "tabLinks": "リンク", + "wgDevices": { + "title": "WireGuardデバイス", + "limit": "デバイス数の上限", + "primary": "メインデバイス", + "enabled": "有効", + "subscription": "サブスクリプションをコピー", + "deleteConfirm": "このデバイスを削除してアドレスを解放しますか?", + "remove": "削除", + "name": "デバイス名", + "add": "デバイスを追加" + }, "wireguardConfig": "WireGuard 設定", "config": "設定", "linksHint": "サードパーティの共有リンクやリモートのサブスクリプションURLを追加して、このクライアントのサブスクリプションに含めます。", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index 081d1e2a1..54c1d3e47 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -816,6 +816,17 @@ "tabBasics": "Básico", "tabCredentials": "Credenciais", "tabLinks": "Links", + "wgDevices": { + "title": "Dispositivos WireGuard", + "limit": "Limite de dispositivos", + "primary": "Dispositivo principal", + "enabled": "Ativado", + "subscription": "Copiar assinatura", + "deleteConfirm": "Excluir este dispositivo e liberar seu endereço?", + "remove": "Excluir", + "name": "Nome do dispositivo", + "add": "Adicionar dispositivo" + }, "wireguardConfig": "Configuração do WireGuard", "config": "Configuração", "linksHint": "Adicione links de terceiros e URLs de assinatura remotas para incluir na assinatura deste cliente.", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 579f48eeb..4e1c6f838 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -816,6 +816,17 @@ "tabBasics": "Основные", "tabCredentials": "Учетные данные", "tabLinks": "Ссылки", + "wgDevices": { + "title": "Устройства WireGuard", + "limit": "Лимит устройств", + "primary": "Основное устройство", + "enabled": "Включено", + "subscription": "Копировать подписку", + "deleteConfirm": "Удалить устройство и освободить его адрес?", + "remove": "Удалить", + "name": "Название устройства", + "add": "Добавить устройство" + }, "wireguardConfig": "Конфигурация WireGuard", "config": "Конфигурация", "linksHint": "Добавьте сторонние ссылки и URL удалённых подписок, чтобы включить их в подписку этого клиента.", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index 2520238c8..94959c9cf 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -816,6 +816,17 @@ "tabBasics": "Základné údaje", "tabCredentials": "Prihlasovacie údaje", "tabLinks": "Odkazy", + "wgDevices": { + "title": "Zariadenia WireGuard", + "limit": "Limit zariadení", + "primary": "Hlavné zariadenie", + "enabled": "Zapnuté", + "subscription": "Kopírovať odber", + "deleteConfirm": "Odstrániť toto zariadenie a uvoľniť jeho adresu?", + "remove": "Odstrániť", + "name": "Názov zariadenia", + "add": "Pridať zariadenie" + }, "wireguardConfig": "Konfigurácia WireGuard", "config": "Konfigurácia", "linksHint": "Pridajte externé odkazy na pripojenie a vzdialené odbery konfigurácií, ktoré sa majú zahrnúť do odberu tohto klienta.", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index f7308ad23..e58322d80 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -816,6 +816,17 @@ "tabBasics": "Temel", "tabCredentials": "Kimlik Bilgileri", "tabLinks": "Bağlantılar", + "wgDevices": { + "title": "WireGuard cihazları", + "limit": "Cihaz sınırı", + "primary": "Ana cihaz", + "enabled": "Etkin", + "subscription": "Aboneliği kopyala", + "deleteConfirm": "Bu cihaz silinsin ve adresi serbest bırakılsın mı?", + "remove": "Sil", + "name": "Cihaz adı", + "add": "Cihaz ekle" + }, "wireguardConfig": "WireGuard yapılandırması", "config": "Yapılandırma", "linksHint": "Bu istemcinin aboneliğine dahil etmek için üçüncü taraf paylaşım bağlantıları ve uzak abonelik URL'leri ekleyin.", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index 8fe77fac2..eb7427314 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -816,6 +816,17 @@ "tabBasics": "Основні", "tabCredentials": "Облікові дані", "tabLinks": "Посилання", + "wgDevices": { + "title": "Пристрої WireGuard", + "limit": "Ліміт пристроїв", + "primary": "Основний пристрій", + "enabled": "Увімкнено", + "subscription": "Копіювати підписку", + "deleteConfirm": "Видалити пристрій і звільнити його адресу?", + "remove": "Видалити", + "name": "Назва пристрою", + "add": "Додати пристрій" + }, "wireguardConfig": "Конфігурація WireGuard", "config": "Конфігурація", "linksHint": "Додайте сторонні посилання та URL віддалених підписок, щоб включити їх до підписки цього клієнта.", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 62da3bec7..c0c68b121 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -816,6 +816,17 @@ "tabBasics": "Cơ bản", "tabCredentials": "Thông tin xác thực", "tabLinks": "Liên kết", + "wgDevices": { + "title": "Thiết bị WireGuard", + "limit": "Giới hạn thiết bị", + "primary": "Thiết bị chính", + "enabled": "Đã bật", + "subscription": "Sao chép liên kết đăng ký", + "deleteConfirm": "Xóa thiết bị này và giải phóng địa chỉ của thiết bị?", + "remove": "Xóa", + "name": "Tên thiết bị", + "add": "Thêm thiết bị" + }, "wireguardConfig": "Cấu hình WireGuard", "config": "Cấu hình", "linksHint": "Thêm liên kết chia sẻ của bên thứ ba và URL đăng ký từ xa để đưa vào đăng ký của khách hàng này.", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index bdbffdd1d..cba0ba8b8 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -816,6 +816,17 @@ "tabBasics": "基本", "tabCredentials": "凭据", "tabLinks": "链接", + "wgDevices": { + "title": "WireGuard 设备", + "limit": "设备数量上限", + "primary": "主设备", + "enabled": "已启用", + "subscription": "复制订阅", + "deleteConfirm": "删除此设备并释放其地址?", + "remove": "删除", + "name": "设备名称", + "add": "添加设备" + }, "wireguardConfig": "WireGuard 配置", "config": "配置", "linksHint": "添加第三方分享链接和远程订阅地址,将其包含在该客户端的订阅中。", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index ac8087a40..6dbd71d3a 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -816,6 +816,17 @@ "tabBasics": "基本", "tabCredentials": "認證資訊", "tabLinks": "連結", + "wgDevices": { + "title": "WireGuard 裝置", + "limit": "裝置數量上限", + "primary": "主要裝置", + "enabled": "已啟用", + "subscription": "複製訂閱", + "deleteConfirm": "刪除此裝置並釋放其位址?", + "remove": "刪除", + "name": "裝置名稱", + "add": "新增裝置" + }, "wireguardConfig": "WireGuard 設定", "config": "設定", "linksHint": "新增第三方分享連結和遠端訂閱網址,將其包含在此用戶端的訂閱中。", diff --git a/internal/xray/api.go b/internal/xray/api.go index 81555fdc7..ba56492f2 100644 --- a/internal/xray/api.go +++ b/internal/xray/api.go @@ -1002,6 +1002,29 @@ func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]an return err } +// RemoveWireguardUsers removes every peer belonging to an email. WireGuard's +// core user manager indexes peers by public key and removes one peer per call. +func (x *XrayAPI) RemoveWireguardUsers(inboundTag, email string) error { + if x.HandlerServiceClient == nil { + return common.NewError("xray HandlerServiceClient is not initialized") + } + ctx, cancel := context.WithTimeout(context.Background(), handlerRPCTimeout) + defer cancel() + response, err := (*x.HandlerServiceClient).GetInboundUsers(ctx, &command.GetInboundUserRequest{Tag: inboundTag}) + if err != nil { + return fmt.Errorf("list wireguard peers: %w", err) + } + for _, user := range response.GetUsers() { + if user.GetEmail() != email { + continue + } + if err := x.RemoveUser(inboundTag, email); err != nil { + return err + } + } + return nil +} + // RemoveUser removes a user from an inbound in the Xray core by email. func (x *XrayAPI) RemoveUser(inboundTag, email string) error { if x.HandlerServiceClient == nil { diff --git a/internal/xray/api_wireguard_devices_test.go b/internal/xray/api_wireguard_devices_test.go new file mode 100644 index 000000000..9047c3728 --- /dev/null +++ b/internal/xray/api_wireguard_devices_test.go @@ -0,0 +1,72 @@ +package xray + +import ( + "context" + "errors" + "testing" + + "github.com/xtls/xray-core/app/proxyman/command" + "github.com/xtls/xray-core/common/protocol" + "google.golang.org/grpc" + "google.golang.org/protobuf/proto" +) + +type wireguardUsersClient struct { + command.HandlerServiceClient + users []*protocol.User + removed []string + listErr error + removeErr error +} + +func (c *wireguardUsersClient) GetInboundUsers(_ context.Context, request *command.GetInboundUserRequest, _ ...grpc.CallOption) (*command.GetInboundUserResponse, error) { + if request.Tag != "wg" || request.Email != "" { + return nil, errors.New("expected every user of the WireGuard inbound") + } + return &command.GetInboundUserResponse{Users: c.users}, c.listErr +} + +func (c *wireguardUsersClient) AlterInbound(_ context.Context, request *command.AlterInboundRequest, _ ...grpc.CallOption) (*command.AlterInboundResponse, error) { + operation := new(command.RemoveUserOperation) + if err := proto.Unmarshal(request.Operation.Value, operation); err != nil { + return nil, err + } + c.removed = append(c.removed, operation.Email) + return &command.AlterInboundResponse{}, c.removeErr +} + +func TestRemoveWireguardUsersRemovesEveryPeerOfClient(t *testing.T) { + core := &wireguardUsersClient{users: []*protocol.User{ + {Email: "client"}, {Email: "other"}, {Email: "client"}, nil, {Email: "client"}, + }} + var handler command.HandlerServiceClient = core + api := XrayAPI{HandlerServiceClient: &handler} + if err := api.RemoveWireguardUsers("wg", "client"); err != nil { + t.Fatal(err) + } + if len(core.removed) != 3 { + t.Fatalf("removed %v, want all three client peers", core.removed) + } + for _, email := range core.removed { + if email != "client" { + t.Fatalf("removed another client's peer: %q", email) + } + } +} + +func TestRemoveWireguardUsersPropagatesCoreFailures(t *testing.T) { + for _, failList := range []bool{true, false} { + core := &wireguardUsersClient{users: []*protocol.User{{Email: "client"}}} + failure := errors.New("core unavailable") + if failList { + core.listErr = failure + } else { + core.removeErr = failure + } + var handler command.HandlerServiceClient = core + api := XrayAPI{HandlerServiceClient: &handler} + if err := api.RemoveWireguardUsers("wg", "client"); !errors.Is(err, failure) { + t.Fatalf("failure not propagated: %v", err) + } + } +} diff --git a/internal/xray/hot-diff-wireguard.go b/internal/xray/hot-diff-wireguard.go new file mode 100644 index 000000000..3f0ff4ee6 --- /dev/null +++ b/internal/xray/hot-diff-wireguard.go @@ -0,0 +1,80 @@ +package xray + +import ( + "bytes" + "encoding/json" + + "github.com/mhsanaei/3x-ui/v3/internal/util/json_util" + wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard" +) + +func splitWireguardPeers(raw json_util.RawMessage) (map[string]clientEntry, []byte, bool) { + var settings map[string]any + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + if err := decoder.Decode(&settings); err != nil { + return nil, nil, false + } + peers, ok := settings["peers"].([]any) + if !ok { + return nil, nil, false + } + byKey := make(map[string]clientEntry, len(peers)) + for _, peer := range peers { + user, ok := peer.(map[string]any) + if !ok { + return nil, nil, false + } + email, _ := user["email"].(string) + publicKey, _ := user["publicKey"].(string) + key, err := wgutil.KeyToHex(publicKey) + if err != nil || key == "" || email == "" { + return nil, nil, false + } + if _, duplicate := byKey[key]; duplicate { + return nil, nil, false + } + + // The inbound user API can apply panel-managed peers with default level. + level, endpoint := user["level"], user["endpoint"] + if (level != nil && level != json.Number("0")) || (endpoint != nil && endpoint != "") || + len(collectStringSlice(user["allowedIPs"])) == 0 { + return nil, nil, false + } + norm, err := json.Marshal(user) + if err != nil { + return nil, nil, false + } + if keepAlive, ok := user["keepAlive"].(json.Number); ok { + user["keepAlive"] = keepAlive.String() + } + byKey[key] = clientEntry{user: user, norm: norm} + } + delete(settings, "peers") + rest, err := json.Marshal(settings) + return byKey, rest, err == nil +} + +func diffWireguardPeers(oldIb, newIb *InboundConfig, diff *HotDiff) bool { + oldPeers, oldRest, oldOK := splitWireguardPeers(oldIb.Settings) + newPeers, newRest, newOK := splitWireguardPeers(newIb.Settings) + if !oldOK || !newOK || !bytes.Equal(oldRest, newRest) { + return false + } + replaced := make(map[string]bool) + for key, peer := range oldPeers { + email := peer.user["email"].(string) + if !replaced[email] && !bytes.Equal(peer.norm, newPeers[key].norm) { + diff.RemovedUsers = append(diff.RemovedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email}) + replaced[email] = true + } + } + // Xray removes by email, so restore the surviving peers of this client. + for key, peer := range newPeers { + email := peer.user["email"].(string) + if replaced[email] || !bytes.Equal(peer.norm, oldPeers[key].norm) { + diff.AddedUsers = append(diff.AddedUsers, UserOp{Tag: newIb.Tag, Protocol: newIb.Protocol, Email: email, User: peer.user}) + } + } + return true +} diff --git a/internal/xray/hot_diff.go b/internal/xray/hot_diff.go index 8e0af1ea1..ce2184767 100644 --- a/internal/xray/hot_diff.go +++ b/internal/xray/hot_diff.go @@ -252,20 +252,23 @@ func InboundUserOps(oldIb, newIb *InboundConfig) (*HotDiff, bool) { var userDiffableProtocols = map[string]struct{}{"vless": {}, "vmess": {}, "trojan": {}, "hysteria": {}, "masque": {}, "shadowsocks": {}} -// diffInboundUsers emits per-user AlterInbound ops when two same-tag inbounds -// differ only in settings.clients, so the handler (and its listener) survives. +// diffInboundUsers emits AlterInbound ops for changes to users or WireGuard peers +// while keeping the existing handler and listener. func diffInboundUsers(oldIb, newIb *InboundConfig, diff *HotDiff) bool { if oldIb.Port != newIb.Port || oldIb.Protocol != newIb.Protocol || oldIb.Tag != newIb.Tag { return false } - if _, ok := userDiffableProtocols[oldIb.Protocol]; !ok { - return false - } if !rawEqualNormalized(oldIb.Listen, newIb.Listen) || !rawEqualNormalized(oldIb.StreamSettings, newIb.StreamSettings) || !rawEqualNormalized(oldIb.Sniffing, newIb.Sniffing) { return false } + if oldIb.Protocol == "wireguard" { + return diffWireguardPeers(oldIb, newIb, diff) + } + if _, ok := userDiffableProtocols[oldIb.Protocol]; !ok { + return false + } oldClients, oldRest, ok := splitSettingsClients(oldIb.Settings) if !ok { return false diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index e34746ed1..eed5d1861 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -34,6 +34,7 @@ func run(root, outDir string) error { "Setting", "Node", "ClientReverse", + "WireguardDevice", "Client", "ClientRecord", "ClientInbound",