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
+55 -20
View File
@@ -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)
}
@@ -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")
}
})
}
}
+45
View File
@@ -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 {
@@ -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) {