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
@@ -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
}
+76 -62
View File
@@ -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
@@ -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")
}
}