feat(wireguard): multi-client support

WireGuard inbounds now manage per-client peers using xray-core's native WireGuard users (AddUser/RemoveUser). Each client lives in settings.clients (canonical, like every other protocol) and is projected to peers[] only when emitting the xray config, at level 0 so the dispatcher's per-user traffic/online counters work with no extra plumbing.

Backend: internal/util/wireguard gains KeyToHex (base64 to hex for the gRPC path), PublicKeyFromPrivate and GenerateWireguardPSK; xray/api.go builds a wireguard account in AddUser with hex keys (RemoveUser already worked); client CRUD generates a keypair and allocates a unique tunnel address per client and never rotates keys on edit; an idempotent migration converts legacy settings.peers into managed clients; WireGuard is included in the raw subscription.

Frontend: WireGuard in the add-client modal with keys on the credential tab, client schema, per-client QR/link/.conf, inbound form reduced to server settings; i18n added across 13 locales.

Fix: guard the settings[clients] assertion in add/update so a legacy WireGuard inbound stored without a clients key no longer panics.
This commit is contained in:
MHSanaei
2026-06-28 00:44:38 +02:00
parent 33aada0c7c
commit 9c8cd08f90
50 changed files with 2160 additions and 258 deletions
+12
View File
@@ -212,6 +212,9 @@ export const EXAMPLES: Record<string, unknown> = {
"token": "new-token-string"
},
"Client": {
"allowedIPs": [
""
],
"auth": "",
"comment": "",
"created_at": 0,
@@ -221,8 +224,12 @@ export const EXAMPLES: Record<string, unknown> = {
"flow": "",
"group": "",
"id": "",
"keepAlive": 0,
"limitIp": 0,
"password": "",
"preSharedKey": "",
"privateKey": "",
"publicKey": "",
"reset": 0,
"reverse": null,
"security": "",
@@ -238,6 +245,7 @@ export const EXAMPLES: Record<string, unknown> = {
"inboundId": 0
},
"ClientRecord": {
"allowedIPs": "",
"auth": "",
"comment": "",
"createdAt": 0,
@@ -247,8 +255,12 @@ export const EXAMPLES: Record<string, unknown> = {
"flow": "",
"group": "",
"id": 0,
"keepAlive": 0,
"limitIp": 0,
"password": "",
"preSharedKey": "",
"privateKey": "",
"publicKey": "",
"reset": 0,
"reverse": null,
"security": "",
+38
View File
@@ -1058,6 +1058,12 @@ export const SCHEMAS: Record<string, unknown> = {
"Client": {
"description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.",
"properties": {
"allowedIPs": {
"items": {
"type": "string"
},
"type": "array"
},
"auth": {
"description": "Auth password (Hysteria)",
"type": "string"
@@ -1094,6 +1100,9 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Unique client identifier",
"type": "string"
},
"keepAlive": {
"type": "integer"
},
"limitIp": {
"description": "IP limit for this client",
"type": "integer"
@@ -1102,6 +1111,15 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Client password",
"type": "string"
},
"preSharedKey": {
"type": "string"
},
"privateKey": {
"type": "string"
},
"publicKey": {
"type": "string"
},
"reset": {
"description": "Reset period in days",
"type": "integer"
@@ -1175,6 +1193,9 @@ export const SCHEMAS: Record<string, unknown> = {
},
"ClientRecord": {
"properties": {
"allowedIPs": {
"type": "string"
},
"auth": {
"type": "string"
},
@@ -1202,12 +1223,24 @@ export const SCHEMAS: Record<string, unknown> = {
"id": {
"type": "integer"
},
"keepAlive": {
"type": "integer"
},
"limitIp": {
"type": "integer"
},
"password": {
"type": "string"
},
"preSharedKey": {
"type": "string"
},
"privateKey": {
"type": "string"
},
"publicKey": {
"type": "string"
},
"reset": {
"type": "integer"
},
@@ -1232,6 +1265,7 @@ export const SCHEMAS: Record<string, unknown> = {
}
},
"required": [
"allowedIPs",
"auth",
"comment",
"createdAt",
@@ -1241,8 +1275,12 @@ export const SCHEMAS: Record<string, unknown> = {
"flow",
"group",
"id",
"keepAlive",
"limitIp",
"password",
"preSharedKey",
"privateKey",
"publicKey",
"reset",
"reverse",
"security",
+10
View File
@@ -222,6 +222,7 @@ export interface ApiTokenView {
}
export interface Client {
allowedIPs?: string[];
auth?: string;
comment: string;
created_at?: number;
@@ -231,8 +232,12 @@ export interface Client {
flow?: string;
group?: string;
id?: string;
keepAlive?: number;
limitIp: number;
password?: string;
preSharedKey?: string;
privateKey?: string;
publicKey?: string;
reset: number;
reverse?: ClientReverse | null;
security: string;
@@ -250,6 +255,7 @@ export interface ClientInbound {
}
export interface ClientRecord {
allowedIPs: string;
auth: string;
comment: string;
createdAt: number;
@@ -259,8 +265,12 @@ export interface ClientRecord {
flow: string;
group: string;
id: number;
keepAlive: number;
limitIp: number;
password: string;
preSharedKey: string;
privateKey: string;
publicKey: string;
reset: number;
reverse: unknown;
security: string;
+10
View File
@@ -238,6 +238,7 @@ export const ApiTokenViewSchema = z.object({
export type ApiTokenView = z.infer<typeof ApiTokenViewSchema>;
export const ClientSchema = z.object({
allowedIPs: z.array(z.string()).optional(),
auth: z.string().optional(),
comment: z.string(),
created_at: z.number().int().optional(),
@@ -247,8 +248,12 @@ export const ClientSchema = z.object({
flow: z.string().optional(),
group: z.string().optional(),
id: z.string().optional(),
keepAlive: z.number().int().optional(),
limitIp: z.number().int(),
password: z.string().optional(),
preSharedKey: z.string().optional(),
privateKey: z.string().optional(),
publicKey: z.string().optional(),
reset: z.number().int(),
reverse: z.lazy(() => ClientReverseSchema).nullable().optional(),
security: z.string(),
@@ -268,6 +273,7 @@ export const ClientInboundSchema = z.object({
export type ClientInbound = z.infer<typeof ClientInboundSchema>;
export const ClientRecordSchema = z.object({
allowedIPs: z.string(),
auth: z.string(),
comment: z.string(),
createdAt: z.number().int(),
@@ -277,8 +283,12 @@ export const ClientRecordSchema = z.object({
flow: z.string(),
group: z.string(),
id: z.number().int(),
keepAlive: z.number().int(),
limitIp: z.number().int(),
password: z.string(),
preSharedKey: z.string(),
privateKey: z.string(),
publicKey: z.string(),
reset: z.number().int(),
reverse: z.unknown(),
security: z.string(),
+6 -10
View File
@@ -263,24 +263,20 @@ export interface WireguardInboundSeed {
mtu?: number;
secretKey?: string;
noKernelTun?: boolean;
peerPrivateKey?: string;
}
// WireGuard is multi-client now: a new inbound holds only the server identity
// (secretKey/mtu) and starts with no clients. Clients (peers) are added later
// through the client modal, which generates each one's keypair and a unique
// tunnel address. peers stays empty for backward-compatible parsing.
export function createDefaultWireguardInboundSettings(
seed: WireguardInboundSeed = {},
): WireguardInboundSettings {
const peerKp = seed.peerPrivateKey
? { privateKey: seed.peerPrivateKey, publicKey: Wireguard.generateKeypair(seed.peerPrivateKey).publicKey }
: Wireguard.generateKeypair();
return {
mtu: seed.mtu ?? 1420,
secretKey: seed.secretKey ?? Wireguard.generateKeypair().privateKey,
peers: [{
privateKey: peerKp.privateKey,
publicKey: peerKp.publicKey,
allowedIPs: ['10.0.0.2/32'],
keepAlive: 0,
}],
peers: [],
clients: [],
noKernelTun: seed.noKernelTun ?? false,
};
}
@@ -6,6 +6,7 @@ import {
TrojanClientSchema,
VlessClientSchema,
VmessClientSchema,
WireguardClientSchema,
} from '@/schemas/protocols/inbound';
import type { StreamSettings } from '@/schemas/api/inbound';
import type { Sniffing } from '@/schemas/primitives';
@@ -234,6 +235,7 @@ function clientSchemaForProtocol(protocol: string): z.ZodType | null {
case 'trojan': return TrojanClientSchema;
case 'shadowsocks': return ShadowsocksClientSchema;
case 'hysteria': return HysteriaClientSchema;
case 'wireguard': return WireguardClientSchema;
default: return null;
}
}
+23 -4
View File
@@ -1126,14 +1126,30 @@ export interface GenWireguardFanoutInput {
fallbackHostname: string;
}
// WireGuard is multi-client: each client is one accepted peer. The canonical
// store is settings.clients; legacy single-config inbounds (pre-migration) are
// still rendered from settings.peers. Both carry the privateKey/allowedIPs/
// preSharedKey/keepAlive the link and .conf need, so they project to the same
// peer shape and reuse genWireguardLink/genWireguardConfig unchanged.
function wgRenderPeers(settings: WireguardInboundSettings): WireguardInboundPeer[] {
const clients = settings.clients ?? [];
if (clients.length > 0) {
return clients.map((c) => ({ ...c, publicKey: c.publicKey ?? '' }));
}
return settings.peers;
}
export function genWireguardLinks(input: GenWireguardFanoutInput): string {
const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
if (inbound.protocol !== 'wireguard') return '';
const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
const sep = '-';
return inbound.settings.peers
const baseSettings = inbound.settings as WireguardInboundSettings;
const peers = wgRenderPeers(baseSettings);
const settings: WireguardInboundSettings = { ...baseSettings, peers };
return peers
.map((p, i) => genWireguardLink({
settings: inbound.settings as WireguardInboundSettings,
settings,
address: addr,
port: inbound.port,
remark: `${remark}${sep}${i + 1}${wgPeerCommentSuffix(p)}`,
@@ -1147,9 +1163,12 @@ export function genWireguardConfigs(input: GenWireguardFanoutInput): string {
if (inbound.protocol !== 'wireguard') return '';
const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
const sep = '-';
return inbound.settings.peers
const baseSettings = inbound.settings as WireguardInboundSettings;
const peers = wgRenderPeers(baseSettings);
const settings: WireguardInboundSettings = { ...baseSettings, peers };
return peers
.map((p, i) => genWireguardConfig({
settings: inbound.settings as WireguardInboundSettings,
settings,
address: addr,
port: inbound.port,
remark: `${remark}${sep}${i + 1}${wgPeerCommentSuffix(p)}`,
@@ -16,7 +16,7 @@ import { ClientBulkAddFormSchema, type ClientBulkAddFormValues } from '@/schemas
const FLOW_OPTIONS = Object.values(TLS_FLOW_CONTROL);
const MULTI_CLIENT_PROTOCOLS = new Set([
'shadowsocks', 'vless', 'vmess', 'trojan', 'hysteria',
'shadowsocks', 'vless', 'vmess', 'trojan', 'hysteria', 'wireguard',
]);
interface ClientBulkAddModalProps {
+75 -2
View File
@@ -22,7 +22,7 @@ import {
import { DeleteOutlined, EyeOutlined, PlusOutlined, ReloadOutlined, RetweetOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { HttpUtil, RandomUtil } from '@/utils';
import { HttpUtil, RandomUtil, Wireguard } from '@/utils';
import { formatInboundLabel } from '@/lib/inbounds/label';
import { normalizeClientIps, type ClientIpInfo } from '@/lib/clients/ip-log';
import { DateTimePicker, SelectAllClearButtons } from '@/components/form';
@@ -35,7 +35,7 @@ const FLOW_OPTIONS = Object.values(TLS_FLOW_CONTROL);
const VMESS_SECURITY_OPTIONS = ['auto', 'aes-128-gcm', 'chacha20-poly1305', 'none', 'zero'] as const;
const MULTI_CLIENT_PROTOCOLS = new Set([
'shadowsocks', 'vless', 'vmess', 'trojan', 'hysteria',
'shadowsocks', 'vless', 'vmess', 'trojan', 'hysteria', 'wireguard',
]);
const CLIENT_FORM_MODAL_Z_INDEX = 1000;
@@ -113,6 +113,10 @@ interface FormState {
enable: boolean;
inboundIds: number[];
externalLinks: ExternalLinkRow[];
wgPrivateKey: string;
wgPublicKey: string;
wgPreSharedKey: string;
wgAllowedIPs: string;
}
function emptyForm(): FormState {
@@ -137,6 +141,10 @@ function emptyForm(): FormState {
enable: true,
inboundIds: [],
externalLinks: [],
wgPrivateKey: '',
wgPublicKey: '',
wgPreSharedKey: '',
wgAllowedIPs: '',
};
}
@@ -237,6 +245,10 @@ export default function ClientFormModal({
enable: !!client.enable,
inboundIds: Array.isArray(attachedIds) ? [...attachedIds] : [],
externalLinks: toExternalLinkRows(attachedExternalLinks),
wgPrivateKey: client.privateKey || '',
wgPublicKey: client.publicKey || '',
wgPreSharedKey: client.preSharedKey || '',
wgAllowedIPs: client.allowedIPs || '',
};
if (et < 0) {
next.delayedStart = true;
@@ -250,6 +262,7 @@ export default function ClientFormModal({
setForm(next);
void loadIps();
} else {
const wgKeypair = Wireguard.generateKeypair();
setForm({
...emptyForm(),
email: RandomUtil.randomLowerAndNum(10),
@@ -257,6 +270,8 @@ export default function ClientFormModal({
subId: RandomUtil.randomLowerAndNum(16),
password: RandomUtil.randomLowerAndNum(16),
auth: RandomUtil.randomLowerAndNum(16),
wgPrivateKey: wgKeypair.privateKey,
wgPublicKey: wgKeypair.publicKey,
});
}
@@ -287,6 +302,14 @@ export default function ClientFormModal({
return ids;
}, [inbounds]);
const wireguardIds = useMemo(() => {
const ids = new Set<number>();
for (const row of inbounds || []) {
if (row && row.protocol === 'wireguard') ids.add(row.id);
}
return ids;
}, [inbounds]);
const ss2022Method = useMemo(() => {
for (const id of form.inboundIds || []) {
const ib = (inbounds || []).find((row) => row.id === id);
@@ -317,6 +340,16 @@ export default function ClientFormModal({
[form.inboundIds, vmessIds],
);
const showWireguard = useMemo(
() => (form.inboundIds || []).some((id) => wireguardIds.has(id)),
[form.inboundIds, wireguardIds],
);
function regenerateWireguardKeys() {
const kp = Wireguard.generateKeypair();
setForm((prev) => ({ ...prev, wgPrivateKey: kp.privateKey, wgPublicKey: kp.publicKey }));
}
useEffect(() => {
if (!showFlow && form.flow) {
@@ -453,6 +486,14 @@ export default function ClientFormModal({
clientPayload.reverse = { tag: reverseTag };
}
if (showWireguard) {
clientPayload.privateKey = form.wgPrivateKey;
clientPayload.publicKey = form.wgPublicKey;
if (form.wgPreSharedKey) {
clientPayload.preSharedKey = form.wgPreSharedKey;
}
}
const externalLinks: ExternalLinkInput[] = form.externalLinks
.map((r) => ({ kind: r.kind, value: r.value.trim(), remark: '' }))
.filter((r) => r.value !== '');
@@ -736,6 +777,38 @@ export default function ClientFormModal({
/>
</Form.Item>
)}
{showWireguard && (
<>
<Form.Item label={t('pages.clients.wireguardPrivateKey')}>
<Space.Compact style={{ display: 'flex' }}>
<Input
value={form.wgPrivateKey}
style={{ flex: 1 }}
onChange={(e) => {
const priv = e.target.value;
update('wgPrivateKey', priv);
update('wgPublicKey', priv ? Wireguard.generateKeypair(priv).publicKey : '');
}}
/>
<Button icon={<ReloadOutlined />} onClick={regenerateWireguardKeys} />
</Space.Compact>
</Form.Item>
<Form.Item label={t('pages.clients.wireguardPublicKey')}>
<Input value={form.wgPublicKey} disabled />
</Form.Item>
<Form.Item label={t('pages.clients.wireguardPreSharedKey')}>
<Input
value={form.wgPreSharedKey}
onChange={(e) => update('wgPreSharedKey', e.target.value)}
/>
</Form.Item>
{isEdit && form.wgAllowedIPs && (
<Form.Item label={t('pages.clients.wireguardAllowedIPs')}>
<Input value={form.wgAllowedIPs} disabled />
</Form.Item>
)}
</>
)}
</>
),
},
@@ -278,12 +278,6 @@ export default function InboundFormModal({
form.setFieldValue(['settings', 'secretKey'], kp.privateKey);
};
const regenWgPeerKeypair = (peerName: number) => {
const kp = Wireguard.generateKeypair();
form.setFieldValue(['settings', 'peers', peerName, 'privateKey'], kp.privateKey);
form.setFieldValue(['settings', 'peers', peerName, 'publicKey'], kp.publicKey);
};
const matchesVlessAuth = (
block: { id?: string; label?: string } | undefined | null,
authId: string,
@@ -695,7 +689,7 @@ export default function InboundFormModal({
const protocolTab = (
<>
{protocol === Protocols.WIREGUARD && <WireguardFields wgPubKey={wgPubKey} regenInboundWg={regenInboundWg} regenWgPeerKeypair={regenWgPeerKeypair} />}
{protocol === Protocols.WIREGUARD && <WireguardFields wgPubKey={wgPubKey} regenInboundWg={regenInboundWg} />}
{protocol === Protocols.TUN && <TunFields />}
@@ -1,44 +1,14 @@
import { useTranslation } from 'react-i18next';
import { Button, Divider, Form, Input, InputNumber, Select, Space, Switch } from 'antd';
import { MinusOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import { Wireguard } from '@/utils';
import { Button, Form, Input, InputNumber, Select, Space, Switch } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
interface WireguardFieldsProps {
wgPubKey: string;
regenInboundWg: () => void;
regenWgPeerKeypair: (name: number) => void;
}
function nextWgPeerAllowedIP(peers: Array<{ allowedIPs?: string[] }> | undefined): string {
const fallback = '10.0.0.2/32';
let maxInt = -1;
let prefix = 32;
for (const peer of peers ?? []) {
for (const ip of peer?.allowedIPs ?? []) {
const m = /^\s*(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?\s*$/.exec(String(ip));
if (!m) continue;
const octets = [Number(m[1]), Number(m[2]), Number(m[3]), Number(m[4])];
if (octets.some((o) => o > 255)) continue;
const asInt = octets[0] * 16777216 + octets[1] * 65536 + octets[2] * 256 + octets[3];
if (asInt > maxInt) {
maxInt = asInt;
prefix = m[5] !== undefined ? Math.min(Number(m[5]), 32) : 32;
}
}
}
if (maxInt < 0) return fallback;
const next = maxInt + 1;
const a = Math.floor(next / 16777216) % 256;
const b = Math.floor(next / 65536) % 256;
const c = Math.floor(next / 256) % 256;
const d = next % 256;
return `${a}.${b}.${c}.${d}/${prefix}`;
}
export default function WireguardFields({ wgPubKey, regenInboundWg, regenWgPeerKeypair }: WireguardFieldsProps) {
export default function WireguardFields({ wgPubKey, regenInboundWg }: WireguardFieldsProps) {
const { t } = useTranslation();
const form = Form.useFormInstance();
return (
<>
<Form.Item label={t('pages.xray.wireguard.secretKey')}>
@@ -74,96 +44,6 @@ export default function WireguardFields({ wgPubKey, regenInboundWg, regenWgPeerK
]}
/>
</Form.Item>
<Form.List name={['settings', 'peers']}>
{(fields, { add, remove }) => (
<>
<Form.Item label={t('pages.inbounds.form.peers')}>
<Button
size="small"
onClick={() => {
const kp = Wireguard.generateKeypair();
const peers = form.getFieldValue(['settings', 'peers']) as Array<{ allowedIPs?: string[] }> | undefined;
add({
privateKey: kp.privateKey,
publicKey: kp.publicKey,
allowedIPs: [nextWgPeerAllowedIP(peers)],
keepAlive: 0,
});
}}
>
<PlusOutlined /> {t('pages.inbounds.form.addPeer')}
</Button>
</Form.Item>
{fields.map((field, idx) => (
<div key={field.key} className="wg-peer">
<Divider titlePlacement="center">
<Space>
<span>{t('pages.inbounds.info.peerNumber', { n: idx + 1 })}</span>
<Form.Item noStyle shouldUpdate>
{() => {
const comment = form.getFieldValue(['settings', 'peers', field.name, 'comment']) as string | undefined;
return comment ? <span style={{ opacity: 0.65 }}> {comment}</span> : null;
}}
</Form.Item>
{fields.length > 1 && (
<Button
size="small"
danger
icon={<MinusOutlined />}
onClick={() => remove(field.name)}
/>
)}
</Space>
</Divider>
<Form.Item name={[field.name, 'comment']} label={t('comment')}>
<Input placeholder="e.g. Alice's laptop" />
</Form.Item>
<Form.Item label={t('pages.xray.wireguard.secretKey')}>
<Space.Compact block>
<Form.Item name={[field.name, 'privateKey']} noStyle>
<Input style={{ width: 'calc(100% - 32px)' }} />
</Form.Item>
<Button
icon={<ReloadOutlined />}
onClick={() => regenWgPeerKeypair(field.name)}
/>
</Space.Compact>
</Form.Item>
<Form.Item name={[field.name, 'publicKey']} label={t('pages.xray.wireguard.publicKey')}>
<Input />
</Form.Item>
<Form.Item name={[field.name, 'preSharedKey']} label="PSK">
<Input />
</Form.Item>
<Form.List name={[field.name, 'allowedIPs']}>
{(ipFields, { add: addIp, remove: removeIp }) => (
<Form.Item label={t('pages.xray.wireguard.allowedIPs')}>
<Button size="small" onClick={() => addIp('')}>
<PlusOutlined />
</Button>
{ipFields.map((ipField) => (
<Space.Compact key={ipField.key} block className="mt-4">
<Form.Item name={ipField.name} noStyle>
<Input />
</Form.Item>
{ipFields.length > 1 && (
<Button size="small" onClick={() => removeIp(ipField.name)}>
<MinusOutlined />
</Button>
)}
</Space.Compact>
))}
</Form.Item>
)}
</Form.List>
<Form.Item name={[field.name, 'keepAlive']} label={t('pages.inbounds.form.keepAlive')}>
<InputNumber min={0} />
</Form.Item>
</div>
))}
</>
)}
</Form.List>
</>
);
}
+5
View File
@@ -32,6 +32,11 @@ export const ClientRecordSchema = z.object({
inboundIds: nullableNumberArray.optional(),
traffic: ClientTrafficSchema.nullable().optional(),
reverse: z.object({ tag: z.string().optional() }).loose().nullable().optional(),
privateKey: z.string().optional(),
publicKey: z.string().optional(),
allowedIPs: z.string().optional(),
preSharedKey: z.string().optional(),
keepAlive: z.number().optional(),
createdAt: z.number().optional(),
updatedAt: z.number().optional(),
}).loose();
@@ -33,10 +33,36 @@ export const WireguardInboundPeerSchema = z.object({
});
export type WireguardInboundPeer = z.infer<typeof WireguardInboundPeerSchema>;
// A WireGuard inbound client (multi-client model). Each client is one peer the
// server accepts: the panel stores its keypair so it can render a full .conf/QR,
// and allowedIPs is the client's unique tunnel address (allocated server-side
// when left blank). Keys are optional on the wire — the backend generates them
// when absent.
export const WireguardClientSchema = z.object({
privateKey: z.string().optional(),
publicKey: z.string().optional(),
preSharedKey: z.string().optional(),
allowedIPs: z.array(z.string()).default([]),
keepAlive: optionalClearedInt(z.number().int().min(0)),
email: z.string().min(1),
limitIp: z.number().int().min(0).default(0),
totalGB: z.number().int().min(0).default(0),
expiryTime: z.number().int().default(0),
enable: z.boolean().default(true),
tgId: z.union([z.number(), z.string()]).transform((v) => Number(v) || 0).default(0),
subId: z.string().default(''),
comment: z.string().default(''),
reset: z.number().int().min(0).default(0),
created_at: z.number().int().optional(),
updated_at: z.number().int().optional(),
});
export type WireguardClient = z.infer<typeof WireguardClientSchema>;
export const WireguardInboundSettingsSchema = z.object({
mtu: optionalClearedInt(z.number().int().min(1)),
secretKey: z.string().min(1),
peers: z.array(WireguardInboundPeerSchema).default([]),
clients: z.array(WireguardClientSchema).default([]),
noKernelTun: z.boolean().default(false),
domainStrategy: WireguardDomainStrategySchema.optional(),
});
@@ -49,18 +49,10 @@ exports[`createDefault*InboundSettings factories > vmess 1`] = `
exports[`createDefault*InboundSettings factories > wireguard 1`] = `
{
"clients": [],
"mtu": 1420,
"noKernelTun": false,
"peers": [
{
"allowedIPs": [
"10.0.0.2/32",
],
"keepAlive": 0,
"privateKey": "cGVlci1maXh0dXJlLXByaXZhdGUta2V5LWZvci10ZXN0cw==",
"publicKey": "RNa/H++60PStnhoiiU/vIuwFimZUBuIkLkbrmEoDz34=",
},
],
"peers": [],
"secretKey": "QGVlb2dXc1ZTWGw0ZXBzZndsWmtMaUM5MUlNYjBHWFdYbz0=",
}
`;
@@ -608,6 +608,7 @@ exports[`InboundSchema (full) fixtures > parses wireguard-server byte-stably 1`]
"protocol": "wireguard",
"remark": "wg-server",
"settings": {
"clients": [],
"mtu": 1420,
"noKernelTun": false,
"peers": [
@@ -207,6 +207,7 @@ exports[`InboundSettingsSchema fixtures > parses wireguard-basic byte-stably 1`]
{
"protocol": "wireguard",
"settings": {
"clients": [],
"mtu": 1420,
"noKernelTun": false,
"peers": [
+2 -1
View File
@@ -142,10 +142,11 @@ describe('createDefault*InboundSettings factories', () => {
it('wireguard', () => {
const s = createDefaultWireguardInboundSettings({
secretKey: 'QGVlb2dXc1ZTWGw0ZXBzZndsWmtMaUM5MUlNYjBHWFdYbz0=',
peerPrivateKey: 'cGVlci1maXh0dXJlLXByaXZhdGUta2V5LWZvci10ZXN0cw==',
});
expect(s).toMatchSnapshot();
expect(WireguardInboundSettingsSchema.parse(s)).toEqual(s);
expect(s.peers).toEqual([]);
expect(s.clients).toEqual([]);
});
});
@@ -0,0 +1,86 @@
import { describe, expect, it } from 'vitest';
import { genWireguardConfigs, genWireguardLinks } from '@/lib/xray/inbound-link';
import { InboundSchema } from '@/schemas/api/inbound';
// Multi-client WireGuard renders one link/config per entry in settings.clients
// (the canonical store), not settings.peers. Each client carries its own
// privateKey + allowedIPs; the server public key is derived from secretKey.
function wgInbound() {
return InboundSchema.parse({
id: 90,
remark: 'wg-mc',
port: 51820,
protocol: 'wireguard',
settings: {
mtu: 1420,
secretKey: 'iJ2cBkrSGqRwIfYIDIxk7hr5RXfdR93MfJUL7yqkkH8=',
peers: [],
clients: [
{
email: 'alice',
privateKey: 'QGVlb2dXc1ZTWGw0ZXBzZndsWmtMaUM5MUlNYjBHWFdYbz0=',
publicKey: 'DGSYIcEKAUkA7HhzGSjxLZuV67BR3LeyU0BMLJzNVHQ=',
allowedIPs: ['10.0.0.2/32'],
keepAlive: 25,
},
{
email: 'bob',
privateKey: 'aGVsbG8td29ybGQtdGVzdC1wcml2YXRlLWtleS1ub3chIQ==',
publicKey: 'b3RoZXItcHVibGljLWtleS1mb3ItYm9iLXRlc3QtdmFsISE=',
allowedIPs: ['10.0.0.3/32'],
},
],
},
});
}
describe('wireguard multi-client link/config fan-out', () => {
it('emits one link per client from settings.clients', () => {
const out = genWireguardLinks({
inbound: wgInbound(),
remark: 'wg-mc',
fallbackHostname: 'wg.example.test',
});
const links = out.split('\r\n').filter(Boolean);
expect(links).toHaveLength(2);
expect(links[0]).toContain('wireguard://');
expect(links[0]).toContain('address=10.0.0.2%2F32');
expect(links[1]).toContain('address=10.0.0.3%2F32');
});
it('emits one .conf per client with its own address', () => {
const out = genWireguardConfigs({
inbound: wgInbound(),
remark: 'wg-mc',
fallbackHostname: 'wg.example.test',
});
const configs = out.split('\r\n[Interface]').length;
expect(out).toContain('Address = 10.0.0.2/32');
expect(out).toContain('Address = 10.0.0.3/32');
expect(configs).toBe(2);
});
it('falls back to settings.peers for legacy single-config inbounds', () => {
const legacy = InboundSchema.parse({
id: 91,
remark: 'wg-legacy',
port: 51820,
protocol: 'wireguard',
settings: {
secretKey: 'iJ2cBkrSGqRwIfYIDIxk7hr5RXfdR93MfJUL7yqkkH8=',
peers: [
{
privateKey: 'QGVlb2dXc1ZTWGw0ZXBzZndsWmtMaUM5MUlNYjBHWFdYbz0=',
publicKey: 'DGSYIcEKAUkA7HhzGSjxLZuV67BR3LeyU0BMLJzNVHQ=',
allowedIPs: ['10.0.0.9/32'],
},
],
},
});
const out = genWireguardLinks({ inbound: legacy, remark: 'wg-legacy', fallbackHostname: 'wg.example.test' });
const links = out.split('\r\n').filter(Boolean);
expect(links).toHaveLength(1);
expect(links[0]).toContain('address=10.0.0.9%2F32');
});
});