Files
mirror-3x-ui/internal/sub/wireguard-device.go
T
Artem K f25cecfb40 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.
2026-11-24 22:16:16 +03:30

59 lines
1.7 KiB
Go

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
}