diff --git a/README.md b/README.md index 36d3f61..d65ac5c 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,9 @@ Configuration is done via environment variables. The following environment varia | `MU_NODE_ID` | Required stable node identity; bound to the state file | `node-1` | | `MU_STATE_FILE` | Private persistent state file (default `data/mu-state.json`) | `/var/lib/mu/state.json` | | `MU_TROJAN_ADDRS` | Comma-separated list of Trojan server addresses | `trojan1.example.com,trojan2.example.com` | -| `MU_V2FLY_ADDRS` | Comma-separated list of V2Fly server addresses | `v2fly1.example.com,v2fly2.example.com` | +| `MU_V2FLY_ADDRS` | Comma-separated list of V2Fly server addresses (VMess inbound, tag `proxy`) | `v2fly1.example.com,v2fly2.example.com` | +| `MU_VLESS_ADDRS` | Comma-separated list of V2Fly server addresses with a VLESS inbound | `vless1.example.com,vless2.example.com` | +| `MU_VLESS_INBOUND_TAG` | Tag of the VLESS inbound on those servers (default `vless`) | `vless` | ### API failure diagnostics @@ -68,6 +70,10 @@ export MU_TROJAN_ADDRS="trojan1.example.com,trojan2.example.com" # Set V2Fly server addresses export MU_V2FLY_ADDRS="v2fly1.example.com,v2fly2.example.com" + +# Set V2Fly servers hosting a VLESS inbound (optional) +export MU_VLESS_ADDRS="vless1.example.com" +export MU_VLESS_INBOUND_TAG="vless" ``` ## Docker Compose @@ -89,6 +95,7 @@ services: - MU_STATE_FILE=/var/lib/mu/state.json - MU_TROJAN_ADDRS=trojan1.example.com,trojan2.example.com - MU_V2FLY_ADDRS=v2fly1.example.com,v2fly2.example.com + - MU_VLESS_ADDRS=vless1.example.com volumes: - mu-state:/var/lib/mu networks: @@ -127,6 +134,24 @@ identities reject the affected snapshot before authorization changes. `enable` m MU must be the sole user manager for each configured Trojan instance and V2Ray `proxy` inbound. The APIs use plaintext gRPC: keep them on a trusted private network and do not expose them publicly. +### VLESS support + +`MU_VLESS_ADDRS` manages a **VLESS** inbound (tag `MU_VLESS_INBOUND_TAG`, default `vless`) on a +v2fly (`v2ray-core` v5) instance through the same gRPC `HandlerService`/`StatsService` API as V2Fly. +Xray is not supported. Users are the same `GetUsers` snapshot and the same UUID as for VMess; +`alter_id` is ignored and the account uses empty flow and `none` encryption. + +- **Backend email suffix.** V2Ray statistics are keyed by email only, so VLESS users are installed + with the backend email `#vless`. This keeps VLESS and VMess counters of one V2Ray instance + disjoint, so a VMess and a VLESS inbound can share an instance without double billing. Each syncer + ignores the other protocol's counters. Emails ending in `#vless` (case-insensitive) are reserved and + reject the whole snapshot for the V2Fly and VLESS backends. +- **Inbound requirements.** The VLESS inbound must have its own tag (do not reuse `proxy`), MU must be + its sole user manager, and it must start with an empty user list, as for VMess. Enable per-user + statistics (`statsUserUplink`/`statsUserDownlink`) for the user's policy level. +- **Traffic type.** VLESS traffic is uploaded as `TRAFFIC_TYPE_V2FLY`; use the `vless` sync label in + metrics to tell it apart. State is kept under a separate `vless::` key. + ### Persistent state is required - Put `MU_STATE_FILE` on a persistent volume. Its parent must be writable by the MU process. diff --git a/internal/mu/app/app.go b/internal/mu/app/app.go index 968cb61..92f3b8b 100644 --- a/internal/mu/app/app.go +++ b/internal/mu/app/app.go @@ -81,6 +81,13 @@ func (a *App) Init() (err error) { } a.userSync = append(a.userSync, syncer) } + for _, addr := range a.config.VlessAddrs { + syncer, err := newVlessSync(addr, a.config.VlessInboundTag, a.state) + if err != nil { + return err + } + a.userSync = append(a.userSync, syncer) + } return nil } func (a *App) initTracing() error { diff --git a/internal/mu/app/config.go b/internal/mu/app/config.go index 565d3eb..bcc2a8b 100644 --- a/internal/mu/app/config.go +++ b/internal/mu/app/config.go @@ -16,6 +16,9 @@ type Config struct { TrojanAddrs []string V2flyAddrs []string + VlessAddrs []string + // VlessInboundTag is the V2Ray inbound tag of the VLESS inbound (default "vless"). + VlessInboundTag string // Metrics 配置 MetricsEnabled bool @@ -32,6 +35,8 @@ type Config struct { // - MU_NODE_ID: Node identifier // - MU_TROJAN_ADDRS: Comma-separated list of Trojan addresses // - MU_V2FLY_ADDRS: Comma-separated list of V2Fly addresses +// - MU_VLESS_ADDRS: Comma-separated list of V2Fly addresses hosting a VLESS inbound +// - MU_VLESS_INBOUND_TAG: Tag of the VLESS inbound (default "vless") func ConfigFromEnv() *Config { v := viper.New() @@ -42,6 +47,8 @@ func ConfigFromEnv() *Config { v.SetDefault("NODE_ID", "") v.SetDefault("TROJAN_ADDRS", "") v.SetDefault("V2FLY_ADDRS", "") + v.SetDefault("VLESS_ADDRS", "") + v.SetDefault("VLESS_INBOUND_TAG", "vless") v.SetDefault("STATE_FILE", "data/mu-state.json") // Metrics defaults @@ -66,13 +73,14 @@ func ConfigFromEnv() *Config { // Create a config struct with values from environment variables config := &Config{ - MuAPIBaseURL: v.GetString("API_BASE_URL"), - MuAPIToken: v.GetString("API_TOKEN"), - MuAPIDebug: v.GetBool("API_DEBUG"), - MuNodeID: v.GetString("NODE_ID"), - StateFile: v.GetString("STATE_FILE"), - MetricsEnabled: v.GetBool("METRICS_ENABLED"), - MetricsPort: v.GetString("METRICS_PORT"), + MuAPIBaseURL: v.GetString("API_BASE_URL"), + MuAPIToken: v.GetString("API_TOKEN"), + MuAPIDebug: v.GetBool("API_DEBUG"), + MuNodeID: v.GetString("NODE_ID"), + StateFile: v.GetString("STATE_FILE"), + VlessInboundTag: v.GetString("VLESS_INBOUND_TAG"), + MetricsEnabled: v.GetBool("METRICS_ENABLED"), + MetricsPort: v.GetString("METRICS_PORT"), Tracing: tracing.Config{ Enabled: v.GetBool("TRACING_ENABLED"), ServiceName: v.GetString("TRACING_SERVICE_NAME"), @@ -91,6 +99,10 @@ func ConfigFromEnv() *Config { config.V2flyAddrs = parseAddresses(v2flyAddrsStr) } + if vlessAddrsStr := v.GetString("VLESS_ADDRS"); vlessAddrsStr != "" { + config.VlessAddrs = parseAddresses(vlessAddrsStr) + } + return config } diff --git a/internal/mu/app/config_test.go b/internal/mu/app/config_test.go index 8ce0b01..2431ca1 100644 --- a/internal/mu/app/config_test.go +++ b/internal/mu/app/config_test.go @@ -22,11 +22,13 @@ func defaultTracing() tracing.Config { func TestConfigFromEnv(t *testing.T) { // Save original environment variables to restore later originalEnvVars := map[string]string{ - "MU_API_BASE_URL": os.Getenv("MU_API_BASE_URL"), - "MU_API_TOKEN": os.Getenv("MU_API_TOKEN"), - "MU_NODE_ID": os.Getenv("MU_NODE_ID"), - "MU_TROJAN_ADDRS": os.Getenv("MU_TROJAN_ADDRS"), - "MU_V2FLY_ADDRS": os.Getenv("MU_V2FLY_ADDRS"), + "MU_API_BASE_URL": os.Getenv("MU_API_BASE_URL"), + "MU_API_TOKEN": os.Getenv("MU_API_TOKEN"), + "MU_NODE_ID": os.Getenv("MU_NODE_ID"), + "MU_TROJAN_ADDRS": os.Getenv("MU_TROJAN_ADDRS"), + "MU_V2FLY_ADDRS": os.Getenv("MU_V2FLY_ADDRS"), + "MU_VLESS_ADDRS": os.Getenv("MU_VLESS_ADDRS"), + "MU_VLESS_INBOUND_TAG": os.Getenv("MU_VLESS_INBOUND_TAG"), } // Restore environment variables after test @@ -48,64 +50,74 @@ func TestConfigFromEnv(t *testing.T) { { name: "Empty environment", envVars: map[string]string{ - "MU_API_BASE_URL": "", - "MU_API_TOKEN": "", - "MU_NODE_ID": "", - "MU_TROJAN_ADDRS": "", - "MU_V2FLY_ADDRS": "", + "MU_API_BASE_URL": "", + "MU_API_TOKEN": "", + "MU_NODE_ID": "", + "MU_TROJAN_ADDRS": "", + "MU_V2FLY_ADDRS": "", + "MU_VLESS_ADDRS": "", + "MU_VLESS_INBOUND_TAG": "", }, expected: &Config{ - MuAPIBaseURL: "", - MuAPIToken: "", - MuNodeID: "", - StateFile: "data/mu-state.json", - TrojanAddrs: nil, - V2flyAddrs: nil, - MetricsEnabled: true, - MetricsPort: "9090", - Tracing: defaultTracing(), + MuAPIBaseURL: "", + MuAPIToken: "", + MuNodeID: "", + StateFile: "data/mu-state.json", + TrojanAddrs: nil, + V2flyAddrs: nil, + VlessInboundTag: "vless", + MetricsEnabled: true, + MetricsPort: "9090", + Tracing: defaultTracing(), }, }, { name: "Full configuration", envVars: map[string]string{ - "MU_API_BASE_URL": "https://api.example.com", - "MU_API_TOKEN": "test-token", - "MU_NODE_ID": "node-1", - "MU_TROJAN_ADDRS": "trojan1.example.com,trojan2.example.com", - "MU_V2FLY_ADDRS": "v2fly1.example.com,v2fly2.example.com", + "MU_API_BASE_URL": "https://api.example.com", + "MU_API_TOKEN": "test-token", + "MU_NODE_ID": "node-1", + "MU_TROJAN_ADDRS": "trojan1.example.com,trojan2.example.com", + "MU_V2FLY_ADDRS": "v2fly1.example.com,v2fly2.example.com", + "MU_VLESS_ADDRS": "vless1.example.com, vless2.example.com,vless1.example.com", + "MU_VLESS_INBOUND_TAG": "edge-vless", }, expected: &Config{ - MuAPIBaseURL: "https://api.example.com", - MuAPIToken: "test-token", - MuNodeID: "node-1", - StateFile: "data/mu-state.json", - TrojanAddrs: []string{"trojan1.example.com", "trojan2.example.com"}, - V2flyAddrs: []string{"v2fly1.example.com", "v2fly2.example.com"}, - MetricsEnabled: true, - MetricsPort: "9090", - Tracing: defaultTracing(), + MuAPIBaseURL: "https://api.example.com", + MuAPIToken: "test-token", + MuNodeID: "node-1", + StateFile: "data/mu-state.json", + TrojanAddrs: []string{"trojan1.example.com", "trojan2.example.com"}, + V2flyAddrs: []string{"v2fly1.example.com", "v2fly2.example.com"}, + VlessAddrs: []string{"vless1.example.com", "vless2.example.com"}, + VlessInboundTag: "edge-vless", + MetricsEnabled: true, + MetricsPort: "9090", + Tracing: defaultTracing(), }, }, { name: "Partial configuration", envVars: map[string]string{ - "MU_API_BASE_URL": "https://api.example.com", - "MU_API_TOKEN": "test-token", - "MU_NODE_ID": "node-2", - "MU_TROJAN_ADDRS": "", - "MU_V2FLY_ADDRS": "v2fly.example.com", + "MU_API_BASE_URL": "https://api.example.com", + "MU_API_TOKEN": "test-token", + "MU_NODE_ID": "node-2", + "MU_TROJAN_ADDRS": "", + "MU_V2FLY_ADDRS": "v2fly.example.com", + "MU_VLESS_ADDRS": "", + "MU_VLESS_INBOUND_TAG": "", }, expected: &Config{ - MuAPIBaseURL: "https://api.example.com", - MuAPIToken: "test-token", - MuNodeID: "node-2", - StateFile: "data/mu-state.json", - TrojanAddrs: nil, - V2flyAddrs: []string{"v2fly.example.com"}, - MetricsEnabled: true, - MetricsPort: "9090", - Tracing: defaultTracing(), + MuAPIBaseURL: "https://api.example.com", + MuAPIToken: "test-token", + MuNodeID: "node-2", + StateFile: "data/mu-state.json", + TrojanAddrs: nil, + V2flyAddrs: []string{"v2fly.example.com"}, + VlessInboundTag: "vless", + MetricsEnabled: true, + MetricsPort: "9090", + Tracing: defaultTracing(), }, }, } diff --git a/internal/mu/app/sync.go b/internal/mu/app/sync.go index ea9b549..a5d4a89 100644 --- a/internal/mu/app/sync.go +++ b/internal/mu/app/sync.go @@ -13,6 +13,7 @@ import ( const protocolTrojan = "trojan" const protocolV2Fly = "v2fly" +const protocolVLESS = "vless" // GetTraffic durably queues deltas in the shared state before returning them for metrics. // Sync also takes a final snapshot before changing authorization. Neither operation resets counters. @@ -35,7 +36,8 @@ func desiredUsers(users []*pb.User, protocol string) (map[string]managedUser, ma v := user.V2RayUser uuidKey := v.Uuid id := common.SHA224String(v.Uuid) - if protocol == protocolV2Fly { + backendEmail := v.Email + if protocol == protocolV2Fly || protocol == protocolVLESS { parsed, err := uuid.ParseString(v.Uuid) if err != nil { return nil, nil, fmt.Errorf("invalid V2Ray UUID at index %d", index) @@ -44,7 +46,14 @@ func desiredUsers(users []*pb.User, protocol string) (map[string]managedUser, ma if strings.TrimSpace(v.Email) == "" || strings.TrimSpace(v.Email) != v.Email || strings.Contains(v.Email, ">>>") { return nil, nil, fmt.Errorf("invalid V2Ray email at index %d", index) } - id = strings.ToLower(v.Email) + // The suffix is reserved for VLESS backend identities; reject it so protocols cannot collide. + if hasVlessSuffix(v.Email) { + return nil, nil, fmt.Errorf("V2Ray email at index %d uses reserved suffix %q", index, vlessEmailSuffix) + } + if protocol == protocolVLESS { + backendEmail += vlessEmailSuffix + } + id = strings.ToLower(backendEmail) if emails[id] { return nil, nil, errors.New("duplicate V2Ray email in snapshot") } @@ -54,7 +63,7 @@ func desiredUsers(users []*pb.User, protocol string) (map[string]managedUser, ma return nil, nil, errors.New("duplicate user UUID in snapshot") } uuids[uuidKey] = true - record := managedUser{ID: user.Id, UUID: v.Uuid, Email: v.Email, Level: v.Level, AlterID: v.AlterId} + record := managedUser{ID: user.Id, UUID: v.Uuid, Email: backendEmail, Level: v.Level, AlterID: v.AlterId} all[id] = record if user.Enable == 1 { enabled[id] = record diff --git a/internal/mu/app/sync_validation_test.go b/internal/mu/app/sync_validation_test.go index 6f0222f..0f8c045 100644 --- a/internal/mu/app/sync_validation_test.go +++ b/internal/mu/app/sync_validation_test.go @@ -34,7 +34,7 @@ func TestInvalidSnapshotsAreRejectedBeforeBackendCalls(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - backends := []UserSync{&v2flySync{}} + backends := []UserSync{&v2flySync{}, &v2flySync{name: protocolVLESS}} if !tt.v2Only { backends = append(backends, &trojanSync{}) } diff --git a/internal/mu/app/v2fly_sync.go b/internal/mu/app/v2fly_sync.go index ebf472a..557f3bc 100644 --- a/internal/mu/app/v2fly_sync.go +++ b/internal/mu/app/v2fly_sync.go @@ -14,10 +14,16 @@ import ( const tag = "proxy" +// vlessEmailSuffix is appended to the MU email to form the V2Ray backend email of VLESS users. +// V2Ray statistics are keyed by email only, so this keeps VLESS and VMess counters of one +// V2Ray instance disjoint and prevents the same traffic from being billed by both syncers. +const vlessEmailSuffix = "#vless" + type v2flySync struct { manager *v2fly.Manager state *syncState key string + name string } func newV2flySync(addr string, state *syncState) (*v2flySync, error) { @@ -28,9 +34,48 @@ func newV2flySync(addr string, state *syncState) (*v2flySync, error) { if err != nil { return nil, err } - return &v2flySync{manager: manager, state: state, key: "v2fly:" + addr + ":" + tag}, nil + return &v2flySync{manager: manager, state: state, key: "v2fly:" + addr + ":" + tag, name: protocolV2Fly}, nil +} + +// newVlessSync manages a VLESS inbound of a v2fly instance. Backend emails carry vlessEmailSuffix. +func newVlessSync(addr, inboundTag string, state *syncState) (*v2flySync, error) { + if state == nil { + return nil, errors.New("synchronization state is required") + } + if strings.TrimSpace(inboundTag) == "" { + return nil, errors.New("VLESS inbound tag is required") + } + manager, err := v2fly.NewManager(addr, inboundTag, v2fly.WithProtocol(v2fly.ProtocolVLESS)) + if err != nil { + return nil, err + } + return &v2flySync{manager: manager, state: state, key: "vless:" + addr + ":" + inboundTag, name: protocolVLESS}, nil +} +func (v *v2flySync) Name() string { + if v.name == "" { + return protocolV2Fly + } + return v.name +} + +// userList returns the traffic identities that belong to this syncer's protocol. Counters of the +// other protocol sharing the same V2Ray instance are ignored. +func (v *v2flySync) userList(ctx context.Context) ([]v2fly.UserData, error) { + list, err := v.manager.GetUserList(ctx, false) + if err != nil { + return nil, err + } + own := list[:0:0] + for _, entry := range list { + if hasVlessSuffix(entry.User.GetEmail()) == (v.Name() == protocolVLESS) { + own = append(own, entry) + } + } + return own, nil +} +func hasVlessSuffix(email string) bool { + return strings.HasSuffix(strings.ToLower(email), vlessEmailSuffix) } -func (v *v2flySync) Name() string { return protocolV2Fly } func (v *v2flySync) Close() error { return v.manager.Close() } func (v *v2flySync) capture(users map[string]managedUser, snapshot []v2fly.UserData) ([]*pb.UserTrafficLog, error) { samples := make(map[string]trafficSample, len(snapshot)) @@ -47,7 +92,7 @@ func (v *v2flySync) Sync(ctx context.Context, users []*pb.User) error { return err } var errs []error - snapshot, statsErr := v.manager.GetUserList(ctx, false) + snapshot, statsErr := v.userList(ctx) if statsErr != nil { // Authorization must not depend on the stats service. Non-reset counters can be collected later. errs = append(errs, statsErr) @@ -140,7 +185,7 @@ func (v *v2flySync) GetTraffic(ctx context.Context, users []*pb.User) ([]*pb.Use if err != nil { return nil, err } - snapshot, err := v.manager.GetUserList(ctx, false) + snapshot, err := v.userList(ctx) if err != nil { return nil, err } diff --git a/internal/mu/app/vless_sync_test.go b/internal/mu/app/vless_sync_test.go new file mode 100644 index 0000000..524e1dc --- /dev/null +++ b/internal/mu/app/vless_sync_test.go @@ -0,0 +1,196 @@ +package app + +import ( + "context" + "net" + "strings" + "testing" + + pb "github.com/icebase/mu/proto/v1" + core "github.com/v2fly/v2ray-core/v5" + "github.com/v2fly/v2ray-core/v5/app/proxyman" + handlercmd "github.com/v2fly/v2ray-core/v5/app/proxyman/command" + inboundmanager "github.com/v2fly/v2ray-core/v5/app/proxyman/inbound" + statsmanager "github.com/v2fly/v2ray-core/v5/app/stats" + statscmd "github.com/v2fly/v2ray-core/v5/app/stats/command" + "github.com/v2fly/v2ray-core/v5/common/protocol" + "github.com/v2fly/v2ray-core/v5/common/serial" + "github.com/v2fly/v2ray-core/v5/proxy/vless" + vlessinbound "github.com/v2fly/v2ray-core/v5/proxy/vless/inbound" + "google.golang.org/grpc" +) + +// vlessRPCServer forwards AlterInbound user operations to a real VLESS inbound handler. +type vlessRPCServer struct { + handlercmd.UnimplementedHandlerServiceServer + handler *vlessinbound.Handler +} + +func (s *vlessRPCServer) AlterInbound(ctx context.Context, req *handlercmd.AlterInboundRequest) (*handlercmd.AlterInboundResponse, error) { + op, err := serial.GetInstanceOf(req.Operation) + if err != nil { + return nil, err + } + switch v := op.(type) { + case *handlercmd.AddUserOperation: + user, err := v.User.ToMemoryUser() + if err != nil { + return nil, err + } + return &handlercmd.AlterInboundResponse{}, s.handler.AddUser(ctx, user) + case *handlercmd.RemoveUserOperation: + return &handlercmd.AlterInboundResponse{}, s.handler.RemoveUser(ctx, v.Email) + } + return &handlercmd.AlterInboundResponse{}, nil +} + +func realVLESS(t *testing.T) (*v2flySync, *vlessinbound.Handler, *statsmanager.Manager) { + t.Helper() + instance, err := core.New(&core.Config{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = instance.Close() }) + inboundManager, err := inboundmanager.New(context.Background(), &proxyman.InboundConfig{}) + if err != nil { + t.Fatal(err) + } + if err := instance.AddFeature(inboundManager); err != nil { + t.Fatal(err) + } + raw, err := core.CreateObject(instance, &vlessinbound.Config{}) + if err != nil { + t.Fatal(err) + } + handler := raw.(*vlessinbound.Handler) + t.Cleanup(func() { _ = handler.Close() }) + stats, err := statsmanager.NewManager(context.Background(), &statsmanager.Config{}) + if err != nil { + t.Fatal(err) + } + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + handlercmd.RegisterHandlerServiceServer(server, &vlessRPCServer{handler: handler}) + statscmd.RegisterStatsServiceServer(server, statscmd.NewStatsServer(stats)) + t.Cleanup(server.Stop) + go func() { _ = server.Serve(listener) }() + syncer, err := newVlessSync(listener.Addr().String(), "vless", newMemoryState()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = syncer.Close() }) + return syncer, handler, stats +} + +func vlessMemoryUser(t *testing.T, email, uuid string) *protocol.MemoryUser { + t.Helper() + raw := &protocol.User{Email: email, Account: serial.ToTypedMessage(&vless.Account{Id: uuid, Encryption: "none"})} + user, err := raw.ToMemoryUser() + if err != nil { + t.Fatal(err) + } + return user +} + +func TestVlessSyncInstallsSuffixedUserAndRevokesIt(t *testing.T) { + syncer, handler, _ := realVLESS(t) + ctx := context.Background() + email := "alice@example.test" + users := []*pb.User{{Id: 7, Enable: 1, V2RayUser: &pb.VUser{Uuid: fixtureUUID, Email: email}}} + if err := syncer.Sync(ctx, users); err != nil { + t.Fatal(err) + } + // The backend identity carries the suffix; the bare MU email must not exist in the inbound. + if err := handler.AddUser(ctx, vlessMemoryUser(t, email+vlessEmailSuffix, "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); err == nil || !strings.HasSuffix(err.Error(), " already exists.") { + t.Fatalf("suffixed user was not installed: %v", err) + } + if err := handler.AddUser(ctx, vlessMemoryUser(t, email, "cccccccc-cccc-4ccc-8ccc-cccccccccccc")); err != nil { + t.Fatalf("unsuffixed email was installed: %v", err) + } + if err := handler.RemoveUser(ctx, email); err != nil { + t.Fatal(err) + } + // Idempotent re-sync, then disabling revokes the account. + if err := syncer.Sync(ctx, users); err != nil { + t.Fatal(err) + } + users[0].Enable = 0 + if err := syncer.Sync(ctx, users); err != nil { + t.Fatal(err) + } + if err := handler.AddUser(ctx, vlessMemoryUser(t, email+vlessEmailSuffix, fixtureUUID)); err != nil { + t.Fatalf("user still authorized after being disabled: %v", err) + } +} + +func TestVlessSyncBillsOnlySuffixedCountersAsV2FlyTraffic(t *testing.T) { + syncer, _, stats := realVLESS(t) + ctx := context.Background() + email := "alice@example.test" + users := []*pb.User{{Id: 7, Enable: 1, V2RayUser: &pb.VUser{Uuid: fixtureUUID, Email: email}}} + if err := syncer.Sync(ctx, users); err != nil { + t.Fatal(err) + } + vlessUp, err := stats.RegisterCounter("user>>>" + email + vlessEmailSuffix + ">>>traffic>>>uplink") + if err != nil { + t.Fatal(err) + } + // A VMess counter for the same MU email in the same V2Ray instance must not be billed by VLESS. + vmessUp, err := stats.RegisterCounter("user>>>" + email + ">>>traffic>>>uplink") + if err != nil { + t.Fatal(err) + } + vlessUp.Set(100) + vmessUp.Set(5000) + if _, err := syncer.GetTraffic(ctx, users); err != nil { // establishes the baseline + t.Fatal(err) + } + vlessUp.Set(160) + vmessUp.Set(9000) + logs, err := syncer.GetTraffic(ctx, users) + if err != nil { + t.Fatal(err) + } + if len(logs) != 1 || logs[0].UserId != 7 || logs[0].U != 60 || logs[0].Uuid != fixtureUUID || + logs[0].TrafficType != int32(pb.TrafficType_TRAFFIC_TYPE_V2FLY) { + t.Fatalf("unexpected traffic logs: %v", logs) + } +} + +func TestV2FlySyncIgnoresVlessCounters(t *testing.T) { + syncer, _, stats := reviewRealVMess(t) + ctx := context.Background() + email := "alice@example.test" + users := []*pb.User{{Id: 7, Enable: 1, V2RayUser: &pb.VUser{Uuid: fixtureUUID, Email: email}}} + if err := syncer.Sync(ctx, users); err != nil { + t.Fatal(err) + } + vmessUp, _ := stats.RegisterCounter("user>>>" + email + ">>>traffic>>>uplink") + vlessUp, _ := stats.RegisterCounter("user>>>" + email + vlessEmailSuffix + ">>>traffic>>>uplink") + vmessUp.Set(10) + vlessUp.Set(1000) + if _, err := syncer.GetTraffic(ctx, users); err != nil { + t.Fatal(err) + } + vmessUp.Set(30) + vlessUp.Set(3000) + logs, err := syncer.GetTraffic(ctx, users) + if err != nil { + t.Fatal(err) + } + if len(logs) != 1 || logs[0].U != 20 { + t.Fatalf("VMess syncer billed VLESS counters: %v", logs) + } +} + +func TestDesiredUsersRejectsReservedVlessSuffix(t *testing.T) { + users := []*pb.User{{Id: 1, Enable: 1, V2RayUser: &pb.VUser{Uuid: fixtureUUID, Email: "alice" + strings.ToUpper(vlessEmailSuffix)}}} + for _, protocol := range []string{protocolV2Fly, protocolVLESS} { + if _, _, err := desiredUsers(users, protocol); err == nil { + t.Fatalf("%s accepted an email using the reserved suffix", protocol) + } + } +} diff --git a/pkg/v2fly/client.go b/pkg/v2fly/client.go index a02c361..fb40845 100644 --- a/pkg/v2fly/client.go +++ b/pkg/v2fly/client.go @@ -13,10 +13,12 @@ import ( statscmd "github.com/v2fly/v2ray-core/v5/app/stats/command" "github.com/v2fly/v2ray-core/v5/common/protocol" "github.com/v2fly/v2ray-core/v5/common/serial" + "github.com/v2fly/v2ray-core/v5/proxy/vless" "github.com/v2fly/v2ray-core/v5/proxy/vmess" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/anypb" ) const requestTimeout = 5 * time.Second @@ -32,18 +34,51 @@ type Manager struct { client command.HandlerServiceClient statsClient statscmd.StatsServiceClient inBoundTag string + protocol Protocol } + +// Protocol selects the account type installed into the inbound. +type Protocol int + +const ( + // ProtocolVMess installs vmess.Account users. It is the default. + ProtocolVMess Protocol = iota + // ProtocolVLESS installs vless.Account users. + ProtocolVLESS +) + +// Option customizes a Manager. +type Option func(*Manager) + +// WithProtocol selects the inbound protocol managed by the Manager. +func WithProtocol(p Protocol) Option { return func(m *Manager) { m.protocol = p } } + type TrafficInfo struct { Up, Down int64 HasUp, HasDown bool } -func NewManager(addr, tag string) (*Manager, error) { +func NewManager(addr, tag string, opts ...Option) (*Manager, error) { conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { return nil, errors.New("invalid V2Ray API address") } - return &Manager{conn: conn, client: command.NewHandlerServiceClient(conn), statsClient: statscmd.NewStatsServiceClient(conn), inBoundTag: tag}, nil + m := &Manager{conn: conn, client: command.NewHandlerServiceClient(conn), statsClient: statscmd.NewStatsServiceClient(conn), inBoundTag: tag} + for _, opt := range opts { + opt(m) + } + return m, nil +} + +func (m *Manager) account(u User) *anypb.Any { + if m.protocol == ProtocolVLESS { + // Flow is left empty and Encryption is "none": the v2fly VLESS inbound supports nothing else. + return serial.ToTypedMessage(&vless.Account{Id: u.GetUUID(), Encryption: "none"}) + } + return serial.ToTypedMessage(&vmess.Account{ + Id: u.GetUUID(), AlterId: u.GetAlterID(), + SecuritySettings: &protocol.SecurityConfig{Type: protocol.SecurityType_AUTO}, + }) } func (m *Manager) Close() error { return m.conn.Close() } func (m *Manager) AddUser(ctx context.Context, u User) (bool, error) { @@ -53,10 +88,7 @@ func (m *Manager) AddUser(ctx context.Context, u User) (bool, error) { Tag: m.inBoundTag, Operation: serial.ToTypedMessage(&command.AddUserOperation{User: &protocol.User{ Level: u.GetLevel(), Email: u.GetEmail(), - Account: serial.ToTypedMessage(&vmess.Account{ - Id: u.GetUUID(), AlterId: u.GetAlterID(), - SecuritySettings: &protocol.SecurityConfig{Type: protocol.SecurityType_AUTO}, - }), + Account: m.account(u), }}), }) if IsAlreadyExistsError(err) {