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.
This commit is contained in:
Artem K
2026-11-24 21:46:16 +03:00
committed by GitHub
parent 3cb5bb7187
commit f25cecfb40
72 changed files with 4489 additions and 196 deletions
+41 -2
View File
@@ -506,7 +506,21 @@ export const EXAMPLES: Record<string, unknown> = {
"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<string, unknown> = {
"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<string, unknown> = {
"id": 0,
"password": "",
"username": ""
},
"WireguardDevice": {
"allowedIPs": [
""
],
"enable": false,
"id": "",
"name": "",
"preSharedKey": "",
"privateKey": "",
"publicKey": ""
}
};
+59 -1
View File
@@ -2125,6 +2125,15 @@ export const SCHEMAS: Record<string, unknown> = {
"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<string, unknown> = {
},
"uuid": {
"type": "string"
},
"wgDeviceLimit": {
"type": "integer"
},
"wireguardDevices": {
"items": {
"$ref": "#/components/schemas/WireguardDevice"
},
"type": "array"
}
},
"required": [
@@ -2374,7 +2392,9 @@ export const SCHEMAS: Record<string, unknown> = {
"trafficReset",
"trafficResetDay",
"updatedAt",
"uuid"
"uuid",
"wgDeviceLimit",
"wireguardDevices"
],
"type": "object"
},
@@ -5406,5 +5426,43 @@ export const SCHEMAS: Record<string, unknown> = {
"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"
}
};
+14
View File
@@ -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;
}
+15
View File
@@ -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<typeof ClientSchema>;
@@ -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<typeof ClientRecordSchema>;
@@ -1310,3 +1314,14 @@ export const UserSchema = z.object({
});
export type User = z.infer<typeof UserSchema>;
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<typeof WireguardDeviceSchema>;
@@ -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)}` }),
};
}
+90
View File
@@ -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',
@@ -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<Values>({ 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({
</span>
</Form.Item>
</Col>
{showWireguard && (
<Col xs={24} md={12}>
<FormField
name="wgDeviceLimit"
label={`WireGuard · ${t('pages.clients.wgDevices.limit')}`}
tooltip={t('pages.clients.wgDevices.title')}
transform={{ output: (value) => Number(value) }}
rules={{
validate: (value) =>
(Number.isInteger(value) &&
value >= minWireguardDeviceLimit &&
value <= 32) ||
`${t('pages.clients.wgDevices.limit')} (${minWireguardDeviceLimit}–32)`,
}}
>
<InputNumber
min={minWireguardDeviceLimit}
max={32}
precision={0}
style={{ width: '100%' }}
/>
</FormField>
</Col>
)}
</Row>
<Row gutter={16}>
+24 -38
View File
@@ -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 && (
<>
<Divider>{t('pages.clients.wireguardConfig')}</Divider>
{wgConfigs.map(({ inbound, endpoint, text }) => {
const meta = formatTunnelConfigMeta(
inbound,
client.email,
wgConfigs.length,
endpoint,
);
return (
<ConfigBlock
key={`wg-${inbound.id}-${endpoint}`}
label={meta.label || t('pages.clients.config')}
text={text}
fileName={meta.fileName}
qrRemark={meta.qrRemark}
tagColor="cyan"
/>
);
})}
</>
{wgInbounds.length > 0 && client && (
<ClientWireguardDevices
state={wireguardDevices}
subLink={subLink}
clientEmail={client.email}
configs={wgConfigs}
/>
)}
{awgConfigs.length > 0 && client && (
+27 -17
View File
@@ -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 = (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
@@ -483,9 +483,19 @@ function ClientQrModalContent({
</span>
);
out.push({
key: `wg-config-${inbound.id}-${endpoint}`,
key: `wg-config-${inbound.id}-${deviceId}-${endpoint}`,
label,
children: <QrPanel value={text} remark={meta.qrRemark} downloadName={meta.fileName} />,
children: (
<QrPanel
value={text}
remark={meta.qrRemark}
downloadName={
deviceId === 'primary'
? meta.fileName
: meta.fileName.replace(/\.conf$/, `-${deviceId}.conf`)
}
/>
),
});
});
awgConfigs.forEach(({ inbound, endpoint, text }) => {
@@ -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<typeof useClientWireguardDevices>;
export default function ClientWireguardDevices({
state,
subLink,
clientEmail,
configs,
}: {
state: DevicesState;
subLink: string;
clientEmail: string;
configs: ReturnType<typeof buildWireguardDeviceConfigs>;
}) {
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}
<Divider>{t('pages.clients.wgDevices.title')}</Divider>
{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 ? <CheckOutlined aria-hidden /> : null,
},
]
: []),
...(subLink
? [{ key: 'subscription', label: t('pages.clients.wgDevices.subscription') }]
: []),
...(deviceId !== 'primary'
? [{ key: 'delete', label: t('pages.clients.wgDevices.remove'), danger: true }]
: []),
];
return (
<div className="link-row" key={`${inbound.id}-${deviceId}-${config.endpoint}`}>
<Tooltip title={enabled ? 'WireGuard' : t('disabled')}>
<Tag color={enabled ? 'cyan' : 'default'} className="link-row-tag">
WG
</Tag>
</Tooltip>
<span
className="link-row-title"
title={`${label} — ${device?.allowedIPs.join(', ') ?? ''}`}
>
{label}
</span>
<div className="link-row-actions">
<Tooltip title={t('copy')}>
<Button
size="small"
aria-label={`${name} ${t('copy')}`}
icon={<CopyOutlined aria-hidden />}
disabled={!enabled}
onClick={() => void copy(text)}
/>
</Tooltip>
<Tooltip title={t('download')}>
<Button
size="small"
aria-label={`${name} ${t('download')}`}
icon={<DownloadOutlined aria-hidden />}
disabled={!enabled}
onClick={() =>
FileManager.downloadTextFile(
text,
deviceId === 'primary'
? meta.fileName
: meta.fileName.replace(/\.conf$/, `-${deviceId}.conf`),
)
}
/>
</Tooltip>
<Popover
trigger="click"
placement="left"
destroyOnHidden
content={<QrPanel value={text} remark={meta.qrRemark || label} size={220} />}
>
<Tooltip title={t('pages.clients.qrCode')}>
<Button
size="small"
aria-label={`${name} ${t('pages.clients.qrCode')}`}
icon={<QrcodeOutlined aria-hidden />}
disabled={!enabled}
/>
</Tooltip>
</Popover>
{items.length > 0 && (
<Dropdown
trigger={['click']}
menu={{
items,
onClick: ({ key }) => {
if (key === 'rename') setPrompt({ id: deviceId, name: deviceName });
if (key === 'enable') state.update(deviceId, { enable: !device?.enable });
if (key === 'subscription') copySubscription(deviceId);
if (key === 'delete')
modal.confirm({
title: t('pages.clients.wgDevices.deleteConfirm'),
onOk: () => state.remove(deviceId),
});
},
}}
>
<Button
size="small"
aria-label={`${name} ${t('more')}`}
icon={<MoreOutlined aria-hidden />}
disabled={state.pending}
/>
</Dropdown>
)}
</div>
</div>
);
})}
<Button
size="small"
icon={<PlusOutlined aria-hidden />}
loading={state.pending}
disabled={!state.data || deviceCount >= state.data.limit}
onClick={() => setPrompt({ id: '', name: '' })}
>
{t('pages.clients.wgDevices.add')}
</Button>
{state.error && <Alert type="error" title={state.error.message} />}
{state.mutationError && <Alert type="error" title={state.mutationError.message} />}
<PromptModal
open={prompt !== null}
title={t('pages.clients.wgDevices.name')}
initialValue={prompt?.name ?? ''}
loading={state.pending}
onClose={() => 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);
}}
/>
</>
);
}
@@ -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<number, string> | 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,
),
})),
);
});
}
+25
View File
@@ -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<typeof ClientBulkAddFormSchema>;
export type ClientBulkAdjustFormValues = z.infer<typeof ClientBulkAdjustFormSchema>;
export type ClientFormValues = z.infer<typeof ClientFormSchema>;
export type GroupSummary = z.infer<typeof GroupSummarySchema>;
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<typeof WireguardDeviceSchema>;
export type WireguardDevices = z.infer<typeof WireguardDevicesSchema>;
@@ -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(
<ClientFormModal
open
mode={client ? 'edit' : 'add'}
client={client}
inbounds={[inbound]}
attachedIds={client ? [inbound.id] : []}
save={save}
onOpenChange={() => {}}
/>,
);
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');
});
});
@@ -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(
<ClientInfoModal
open
@@ -149,7 +149,7 @@ describe('Multi-tunnel Client Modals', () => {
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', () => {
@@ -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');
});
});
@@ -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(
<ClientWireguardDevices state={state} subLink="" clientEmail="alexander" configs={configs} />,
);
}
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');
});
});