From 19e88c4610132488dba7fcfb63b802fbad0df88a Mon Sep 17 00:00:00 2001 From: Sanaei Date: Mon, 25 May 2026 00:08:06 +0200 Subject: [PATCH] fix: address open bug reports (#4539, #4538, #4535, #4531, #4515) (#4545) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: hash-storage panic on SIGHUP and seeder dup-key on cold restart (#4539) Two bugs that combine into an unrecoverable crash loop after a user enables the Telegram bot in settings on a fresh install. 1. CheckHashStorageJob.Run panics with a nil pointer dereference. The cron job is scheduled whenever settings say the bot is enabled, but the package-level hash storage is only initialized inside Tgbot.Start, which StartPanelOnly intentionally skips (startTgBot=false). Toggling the bot on via the panel triggers SIGHUP, the storage stays nil, and the cron fires 2 minutes later and panics, exiting 2. 2. seedClientsFromInboundJSON is not idempotent. The fresh-install early-return path recorded only UserPasswordHash + ApiTokensTable, never ClientsTable. After the admin adds clients via the panel (which writes to the clients table through SyncInbound), the next start runs the seeder for the first time, finds matching emails already in the table, and fails with SQLSTATE 23505 on idx_clients_email, turning the panic above into an unrecoverable crash loop on PostgreSQL. Fixes: - web/job/check_hash_storage.go: nil-check the storage before calling RemoveExpiredHashes. - database/db.go: in the fresh-install early-return path, also record ClientsTable so the seeder never re-runs against panel-added data. - database/db.go: hydrate seedClientsFromInboundJSON's byEmail cache from existing rows so it merges instead of inserting when a row with the same email already lives in the clients table. Regression tests cover both paths. Closes #4539 * fix(clients): preserve protocol-specific credentials across multi-inbound syncs (#4538) fillProtocolDefaults only populates the credential relevant to the inbound's protocol (c.ID for VLESS, c.Auth for Hysteria, c.Password for Trojan/Shadowsocks). Each inbound's settings.clients JSON therefore carries the same client with only one of those fields set. SyncInbound's update path was unconditionally copying every credential column from incoming to the existing clients row, so the second sync (e.g. Hysteria after VLESS) would write UUID="" over a valid VLESS UUID and Auth="" the other way around. The next GetXrayConfig then emitted VLESS client entries with no "id" field, and xray-core crashed on startup with "common/uuid: invalid UUID:". Guard UUID/Password/Auth/Flow/Security/Reverse against empty overwrites so each protocol's sync only writes the credentials it actually owns. Other fields (LimitIP, TotalGB, Comment, etc.) keep the existing copy-everything behavior so admins can still clear them through the panel. Regression test in client_sync_multiprotocol_test.go. Closes #4538 * fix(expiry): show delayed-start countdown in subscribe and client info (#4535) A client with "start after first use" expiry stores the duration as a negative number of milliseconds (e.g. -86400000 = 1 day after first connect). The clients page row already renders this correctly as "Delayed start: 1d", but two other surfaces treated negative values as zero and rendered them as unlimited: - Subscription header: the index==0 / index>0 branches in subService, subClashService and subJsonService only carried ExpiryTime forward when > 0, so traffic.ExpiryTime stayed at zero and the header sent expire=0. Every imported client appeared to have no expiry, and the built-in subscribe page rendered the "unlimited" tag. - ClientInfoModal: both the expiryLabel helper and the rendering check treated <= 0 as the "no expiry" branch, so the modal showed an infinity tag instead of "Delayed start: Nd". Add subscriptionExpiryFromClient to map negative durations onto a "now + |value|" timestamp so subscription clients see an actual expiry they can count down from. Update ClientInfoModal's helper and render to match the clients-page convention. Regression test in subService_test.go covers the helper. Refs #4535 * feat(clash): emit xhttp and httpupgrade transports in subscription (#4531) applyTransport's switch only covered tcp/ws/grpc; xhttp and httpupgrade inbounds fell through to the default branch and returned false. buildProxy then returned a nil map and the inbound was dropped from the Clash subscription. When the subscription only contained xhttp/httpupgrade inbounds, the proxies list ended up empty and the client saw a 404 (or an "Error!" body on older builds), then refused to parse. Add a case for each, mapping the inbound's stream settings onto the Mihomo-format opts blocks: xhttp -> xhttp-opts: { path, host, mode } httpupgrade -> http-upgrade-opts: { path, headers: { Host } } Host falls back to the headers map when the dedicated `host` field is empty, matching the existing ws behavior. Closes #4531 * fix(online): refresh online-clients list even when no WS frontend is connected (#4515) XrayTrafficJob and NodeTrafficSyncJob both gated the entire post-traffic-write block behind websocket.HasClients() to skip expensive broadcasts when no browser is open. The block included the RefreshOnlineClientsFromMap call that keeps the in-memory p.onlineClients list current. Several non-WS consumers read that same list: - Telegram bot (tgbot.go calls p.GetOnlineClients in 3 places) - REST GET /panel/api/onlines (returned to API callers) - Internal alerts that check whether a client is online When no browser was watching the dashboard, the list went stale and stayed empty, so the bot reported "nobody online" and the onlines API returned [] even when xray had active sessions. Move RefreshOnlineClientsFromMap above the HasClients guard so the in-memory list is always fresh. Only the actual BroadcastTraffic / BroadcastClientStats / BroadcastOutbounds calls (and the GetAllClientTraffics / GetInboundsTrafficSummary work that feeds them) remain gated by HasClients. Closes #4515 * fix: address copilot review on #4545 Two issues raised by the Copilot review: 1) subscriptionExpiryFromClient called time.Now() per invocation. Two clients with the same delayed-start duration normalized to timestamps a few milliseconds apart, so the aggregator's "if normalized != traffic.ExpiryTime" check tripped and the subscription header expire= dropped back to 0 — the exact bug the helper was meant to fix, just one client later. Take nowMs as a parameter; each of GetSubs / GetClash / GetConfig captures one timestamp per request and reuses it. 2) Guarding Flow against empty incoming values in SyncInbound prevented a user from ever clearing a VLESS flow via the panel. FlowOverride on client_inbounds is the per-inbound mechanism that already preserves flow correctly across protocols, so the guard on the shared clients.flow column is the wrong place. Drop the Flow guard, keep the rest (UUID/Password/Auth/Security/ Reverse — none of which have a per-inbound override column). Adds a regression test that asserts clearing flow on the owning inbound makes ListForInbound return flow="". The existing cross-protocol test is rewritten to assert on the user-visible behavior (ListForInbound flow) instead of the shared clients.flow column. --- database/db.go | 18 ++- database/db_seed_test.go | 71 +++++++++++ .../src/pages/clients/ClientInfoModal.tsx | 15 ++- sub/subClashService.go | 56 ++++++++- sub/subClashService_test.go | 81 +++++++++++++ sub/subJsonService.go | 9 +- sub/subService.go | 19 ++- sub/subService_test.go | 17 +++ web/job/check_hash_storage.go | 7 +- web/job/check_hash_storage_test.go | 12 ++ web/job/node_traffic_sync_job.go | 8 +- web/job/xray_traffic_job.go | 28 +---- web/service/client.go | 20 +++- web/service/client_sync_multiprotocol_test.go | 113 ++++++++++++++++++ 14 files changed, 417 insertions(+), 57 deletions(-) create mode 100644 database/db_seed_test.go create mode 100644 sub/subClashService_test.go create mode 100644 web/job/check_hash_storage_test.go create mode 100644 web/service/client_sync_multiprotocol_test.go diff --git a/database/db.go b/database/db.go index fba55a3c..10e729c3 100644 --- a/database/db.go +++ b/database/db.go @@ -142,11 +142,11 @@ func runSeeders(isUsersEmpty bool) error { } if empty && isUsersEmpty { - hashSeeder := &model.HistoryOfSeeders{ - SeederName: "UserPasswordHash", - } - if err := db.Create(hashSeeder).Error; err != nil { - return err + seeders := []string{"UserPasswordHash", "ClientsTable"} + for _, name := range seeders { + if err := db.Create(&model.HistoryOfSeeders{SeederName: name}).Error; err != nil { + return err + } } return seedApiTokens() } @@ -237,6 +237,14 @@ func seedClientsFromInboundJSON() error { return db.Transaction(func(tx *gorm.DB) error { byEmail := map[string]*model.ClientRecord{} + var existing []model.ClientRecord + if err := tx.Find(&existing).Error; err != nil { + return err + } + for i := range existing { + byEmail[existing[i].Email] = &existing[i] + } + for _, inbound := range inbounds { if strings.TrimSpace(inbound.Settings) == "" { continue diff --git a/database/db_seed_test.go b/database/db_seed_test.go new file mode 100644 index 00000000..d648774b --- /dev/null +++ b/database/db_seed_test.go @@ -0,0 +1,71 @@ +package database + +import ( + "encoding/json" + "path/filepath" + "testing" + + "github.com/mhsanaei/3x-ui/v3/database/model" +) + +func TestSeedClientsFromInboundJSON_IsIdempotentAgainstExistingClients(t *testing.T) { + dbDir := t.TempDir() + t.Setenv("XUI_DB_FOLDER", dbDir) + if err := InitDB(filepath.Join(dbDir, "3x-ui.db")); err != nil { + t.Fatalf("InitDB failed: %v", err) + } + t.Cleanup(func() { _ = CloseDB() }) + + settings, err := json.Marshal(map[string]any{ + "clients": []any{ + map[string]any{ + "id": "ce8d33df-3a64-4f10-8f9b-91c3a8e0c001", + "email": "alice@example.com", + "enable": true, + "flow": "", + "subId": "alice-sub", + "comment": "from-inbound-json", + }, + }, + }) + if err != nil { + t.Fatalf("marshal settings: %v", err) + } + inbound := model.Inbound{ + UserId: 1, + Port: 12345, + Protocol: model.VLESS, + Settings: string(settings), + Tag: "test-inbound", + } + if err := db.Create(&inbound).Error; err != nil { + t.Fatalf("seed inbound: %v", err) + } + + preExisting := &model.ClientRecord{ + Email: "alice@example.com", + UUID: "ce8d33df-3a64-4f10-8f9b-91c3a8e0c001", + SubID: "alice-sub", + Enable: true, + Comment: "added-via-api", + } + if err := db.Create(preExisting).Error; err != nil { + t.Fatalf("seed client row: %v", err) + } + + if err := db.Where("seeder_name = ?", "ClientsTable").Delete(&model.HistoryOfSeeders{}).Error; err != nil { + t.Fatalf("clear ClientsTable history: %v", err) + } + + if err := seedClientsFromInboundJSON(); err != nil { + t.Fatalf("seedClientsFromInboundJSON should be idempotent against existing rows, got: %v", err) + } + + var count int64 + if err := db.Model(&model.ClientRecord{}).Where("email = ?", "alice@example.com").Count(&count).Error; err != nil { + t.Fatalf("count clients: %v", err) + } + if count != 1 { + t.Fatalf("alice@example.com should resolve to exactly one row, got %d", count) + } +} diff --git a/frontend/src/pages/clients/ClientInfoModal.tsx b/frontend/src/pages/clients/ClientInfoModal.tsx index 7e827ddb..eea4fe85 100644 --- a/frontend/src/pages/clients/ClientInfoModal.tsx +++ b/frontend/src/pages/clients/ClientInfoModal.tsx @@ -40,9 +40,16 @@ export default function ClientInfoModal({ onOpenChange, }: ClientInfoModalProps) { const { datepicker } = useDatepicker(); - const expiryLabel = (ts?: number) => (!ts || ts <= 0 ? '∞' : IntlUtil.formatDate(ts, datepicker)); - const dateLabel = (ts?: number) => (!ts || ts <= 0 ? '-' : IntlUtil.formatDate(ts, datepicker)); const { t } = useTranslation(); + const expiryLabel = (ts?: number) => { + if (!ts) return '∞'; + if (ts < 0) { + const days = Math.round(ts / -86400000); + return `${t('pages.clients.delayedStart')}: ${days}d`; + } + return IntlUtil.formatDate(ts, datepicker); + }; + const dateLabel = (ts?: number) => (!ts || ts <= 0 ? '-' : IntlUtil.formatDate(ts, datepicker)); const [messageApi, messageContextHolder] = message.useMessage(); const [links, setLinks] = useState([]); @@ -195,9 +202,9 @@ export default function ClientInfoModal({ {t('pages.inbounds.expireDate')} - {!client.expiryTime || client.expiryTime <= 0 + {!client.expiryTime ? - : {expiryLabel(client.expiryTime)}} + : {expiryLabel(client.expiryTime)}} {(client.expiryTime ?? 0) > 0 && ( {IntlUtil.formatRelativeTime(client.expiryTime)} )} diff --git a/sub/subClashService.go b/sub/subClashService.go index 68f0c3bc..a138faec 100644 --- a/sub/subClashService.go +++ b/sub/subClashService.go @@ -4,6 +4,7 @@ import ( "fmt" "maps" "strings" + "time" "github.com/goccy/go-json" yaml "github.com/goccy/go-yaml" @@ -63,14 +64,13 @@ func (s *SubClashService) GetClash(subId string, host string) (string, string, e return "", "", nil } + now := time.Now().UnixMilli() for index, clientTraffic := range clientTraffics { if index == 0 { traffic.Up = clientTraffic.Up traffic.Down = clientTraffic.Down traffic.Total = clientTraffic.Total - if clientTraffic.ExpiryTime > 0 { - traffic.ExpiryTime = clientTraffic.ExpiryTime - } + traffic.ExpiryTime = subscriptionExpiryFromClient(now, clientTraffic.ExpiryTime) } else { traffic.Up += clientTraffic.Up traffic.Down += clientTraffic.Down @@ -79,7 +79,8 @@ func (s *SubClashService) GetClash(subId string, host string) (string, string, e } else { traffic.Total += clientTraffic.Total } - if clientTraffic.ExpiryTime != traffic.ExpiryTime { + normalized := subscriptionExpiryFromClient(now, clientTraffic.ExpiryTime) + if normalized != traffic.ExpiryTime { traffic.ExpiryTime = 0 } } @@ -364,6 +365,53 @@ func (s *SubClashService) applyTransport(proxy map[string]any, network string, s proxy["grpc-opts"] = grpcOpts } return true + case "httpupgrade": + proxy["network"] = "httpupgrade" + hu, _ := stream["httpupgradeSettings"].(map[string]any) + opts := map[string]any{} + if hu != nil { + if path, ok := hu["path"].(string); ok && path != "" { + opts["path"] = path + } + host := "" + if v, ok := hu["host"].(string); ok && v != "" { + host = v + } else if headers, ok := hu["headers"].(map[string]any); ok { + host = searchHost(headers) + } + if host != "" { + opts["headers"] = map[string]any{"Host": host} + } + } + if len(opts) > 0 { + proxy["http-upgrade-opts"] = opts + } + return true + case "xhttp": + proxy["network"] = "xhttp" + xhttp, _ := stream["xhttpSettings"].(map[string]any) + opts := map[string]any{} + if xhttp != nil { + if path, ok := xhttp["path"].(string); ok && path != "" { + opts["path"] = path + } + host := "" + if v, ok := xhttp["host"].(string); ok && v != "" { + host = v + } else if headers, ok := xhttp["headers"].(map[string]any); ok { + host = searchHost(headers) + } + if host != "" { + opts["host"] = host + } + if mode, ok := xhttp["mode"].(string); ok && mode != "" { + opts["mode"] = mode + } + } + if len(opts) > 0 { + proxy["xhttp-opts"] = opts + } + return true default: return false } diff --git a/sub/subClashService_test.go b/sub/subClashService_test.go new file mode 100644 index 00000000..49e7788a --- /dev/null +++ b/sub/subClashService_test.go @@ -0,0 +1,81 @@ +package sub + +import ( + "reflect" + "testing" +) + +func TestApplyTransport_XHTTP(t *testing.T) { + svc := &SubClashService{} + proxy := map[string]any{} + stream := map[string]any{ + "xhttpSettings": map[string]any{ + "path": "/xh", + "host": "example.com", + "mode": "auto", + }, + } + + if !svc.applyTransport(proxy, "xhttp", stream) { + t.Fatalf("applyTransport returned false for xhttp (#4531: would drop the inbound and yield an empty Clash YAML)") + } + if proxy["network"] != "xhttp" { + t.Fatalf("network = %v, want xhttp", proxy["network"]) + } + opts, ok := proxy["xhttp-opts"].(map[string]any) + if !ok { + t.Fatalf("xhttp-opts missing or wrong type: %#v", proxy["xhttp-opts"]) + } + want := map[string]any{"path": "/xh", "host": "example.com", "mode": "auto"} + if !reflect.DeepEqual(opts, want) { + t.Fatalf("xhttp-opts = %#v, want %#v", opts, want) + } +} + +func TestApplyTransport_XHTTP_HostFromHeaders(t *testing.T) { + svc := &SubClashService{} + proxy := map[string]any{} + stream := map[string]any{ + "xhttpSettings": map[string]any{ + "path": "/xh", + "headers": map[string]any{"Host": "via-header.example.com"}, + }, + } + + if !svc.applyTransport(proxy, "xhttp", stream) { + t.Fatalf("applyTransport returned false for xhttp") + } + opts, _ := proxy["xhttp-opts"].(map[string]any) + if opts["host"] != "via-header.example.com" { + t.Fatalf("host should fall back to headers.Host, got %v", opts["host"]) + } +} + +func TestApplyTransport_HTTPUpgrade(t *testing.T) { + svc := &SubClashService{} + proxy := map[string]any{} + stream := map[string]any{ + "httpupgradeSettings": map[string]any{ + "path": "/hu", + "host": "example.com", + }, + } + + if !svc.applyTransport(proxy, "httpupgrade", stream) { + t.Fatalf("applyTransport returned false for httpupgrade") + } + if proxy["network"] != "httpupgrade" { + t.Fatalf("network = %v, want httpupgrade", proxy["network"]) + } + opts, ok := proxy["http-upgrade-opts"].(map[string]any) + if !ok { + t.Fatalf("http-upgrade-opts missing: %#v", proxy["http-upgrade-opts"]) + } + if opts["path"] != "/hu" { + t.Fatalf("path = %v, want /hu", opts["path"]) + } + headers, _ := opts["headers"].(map[string]any) + if headers["Host"] != "example.com" { + t.Fatalf("headers.Host = %v, want example.com", headers["Host"]) + } +} diff --git a/sub/subJsonService.go b/sub/subJsonService.go index 28a1a9ff..e26b60ea 100644 --- a/sub/subJsonService.go +++ b/sub/subJsonService.go @@ -6,6 +6,7 @@ import ( "fmt" "maps" "strings" + "time" "github.com/mhsanaei/3x-ui/v3/database/model" "github.com/mhsanaei/3x-ui/v3/logger" @@ -125,14 +126,13 @@ func (s *SubJsonService) GetJson(subId string, host string) (string, string, err } // Prepare statistics + now := time.Now().UnixMilli() for index, clientTraffic := range clientTraffics { if index == 0 { traffic.Up = clientTraffic.Up traffic.Down = clientTraffic.Down traffic.Total = clientTraffic.Total - if clientTraffic.ExpiryTime > 0 { - traffic.ExpiryTime = clientTraffic.ExpiryTime - } + traffic.ExpiryTime = subscriptionExpiryFromClient(now, clientTraffic.ExpiryTime) } else { traffic.Up += clientTraffic.Up traffic.Down += clientTraffic.Down @@ -141,7 +141,8 @@ func (s *SubJsonService) GetJson(subId string, host string) (string, string, err } else { traffic.Total += clientTraffic.Total } - if clientTraffic.ExpiryTime != traffic.ExpiryTime { + normalized := subscriptionExpiryFromClient(now, clientTraffic.ExpiryTime) + if normalized != traffic.ExpiryTime { traffic.ExpiryTime = 0 } } diff --git a/sub/subService.go b/sub/subService.go index 49a05938..306d724f 100644 --- a/sub/subService.go +++ b/sub/subService.go @@ -108,15 +108,13 @@ func (s *SubService) GetSubs(subId string, host string) ([]string, int64, xray.C } } - // Prepare statistics + now := time.Now().UnixMilli() for index, clientTraffic := range clientTraffics { if index == 0 { traffic.Up = clientTraffic.Up traffic.Down = clientTraffic.Down traffic.Total = clientTraffic.Total - if clientTraffic.ExpiryTime > 0 { - traffic.ExpiryTime = clientTraffic.ExpiryTime - } + traffic.ExpiryTime = subscriptionExpiryFromClient(now, clientTraffic.ExpiryTime) } else { traffic.Up += clientTraffic.Up traffic.Down += clientTraffic.Down @@ -125,7 +123,8 @@ func (s *SubService) GetSubs(subId string, host string) ([]string, int64, xray.C } else { traffic.Total += clientTraffic.Total } - if clientTraffic.ExpiryTime != traffic.ExpiryTime { + normalized := subscriptionExpiryFromClient(now, clientTraffic.ExpiryTime) + if normalized != traffic.ExpiryTime { traffic.ExpiryTime = 0 } } @@ -134,6 +133,16 @@ func (s *SubService) GetSubs(subId string, host string) ([]string, int64, xray.C return result, lastOnline, traffic, nil } +func subscriptionExpiryFromClient(nowMs, expiryTime int64) int64 { + if expiryTime > 0 { + return expiryTime + } + if expiryTime < 0 { + return nowMs + (-expiryTime) + } + return 0 +} + func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) { db := database.GetDB() var inbounds []*model.Inbound diff --git a/sub/subService_test.go b/sub/subService_test.go index 91512d7f..d87a198c 100644 --- a/sub/subService_test.go +++ b/sub/subService_test.go @@ -9,6 +9,23 @@ import ( "github.com/mhsanaei/3x-ui/v3/database/model" ) +func TestSubscriptionExpiryFromClient(t *testing.T) { + const now = int64(1_700_000_000_000) + const oneDayMs = int64(86_400_000) + if got := subscriptionExpiryFromClient(now, 0); got != 0 { + t.Fatalf("zero expiry should stay zero, got %d", got) + } + if got := subscriptionExpiryFromClient(now, 1_700_000_000_000); got != 1_700_000_000_000 { + t.Fatalf("positive expiry should pass through, got %d", got) + } + if got := subscriptionExpiryFromClient(now, -oneDayMs); got != now+oneDayMs { + t.Fatalf("delayed-start expiry should be now+|value|, got %d, want %d", got, now+oneDayMs) + } + if a, b := subscriptionExpiryFromClient(now, -oneDayMs), subscriptionExpiryFromClient(now, -oneDayMs); a != b { + t.Fatalf("same now+value should be deterministic across calls, got %d vs %d (#4545 review)", a, b) + } +} + func TestFindClientIndex(t *testing.T) { clients := []model.Client{ {Email: "a@example.com"}, diff --git a/web/job/check_hash_storage.go b/web/job/check_hash_storage.go index 1489217e..ce836831 100644 --- a/web/job/check_hash_storage.go +++ b/web/job/check_hash_storage.go @@ -16,6 +16,9 @@ func NewCheckHashStorageJob() *CheckHashStorageJob { // Run removes expired hash entries from the Telegram bot's hash storage. func (j *CheckHashStorageJob) Run() { - // Remove expired hashes from storage - j.tgbotService.GetHashStorage().RemoveExpiredHashes() + storage := j.tgbotService.GetHashStorage() + if storage == nil { + return + } + storage.RemoveExpiredHashes() } diff --git a/web/job/check_hash_storage_test.go b/web/job/check_hash_storage_test.go new file mode 100644 index 00000000..e324bcb8 --- /dev/null +++ b/web/job/check_hash_storage_test.go @@ -0,0 +1,12 @@ +package job + +import "testing" + +func TestCheckHashStorageJob_RunWithoutPanicWhenStorageNil(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Fatalf("CheckHashStorageJob.Run panicked when storage is nil: %v", r) + } + }() + NewCheckHashStorageJob().Run() +} diff --git a/web/job/node_traffic_sync_job.go b/web/job/node_traffic_sync_job.go index 63de5018..1cf32323 100644 --- a/web/job/node_traffic_sync_job.go +++ b/web/job/node_traffic_sync_job.go @@ -101,10 +101,6 @@ func (j *NodeTrafficSyncJob) Run() { j.structural.set() } - if !websocket.HasClients() { - return - } - lastOnline, err := j.inboundService.GetClientsLastOnline() if err != nil { logger.Warning("node traffic sync: get last-online failed:", err) @@ -115,6 +111,10 @@ func (j *NodeTrafficSyncJob) Run() { j.inboundService.RefreshOnlineClientsFromMap(lastOnline) + if !websocket.HasClients() { + return + } + online := j.inboundService.GetOnlineClients() if online == nil { online = []string{} diff --git a/web/job/xray_traffic_job.go b/web/job/xray_traffic_job.go index 7a471b4c..583c5995 100644 --- a/web/job/xray_traffic_job.go +++ b/web/job/xray_traffic_job.go @@ -65,18 +65,6 @@ func (j *XrayTrafficJob) Run() { j.xrayService.SetToNeedRestart() } - // If no frontend client is connected, skip all WebSocket broadcasting - // routines — including the active-client DB query and JSON marshaling. - if !websocket.HasClients() { - return - } - - // Online presence + traffic deltas — small payload, always fits in WS. - // Force non-nil slice/map so JSON marshalling produces [] / {} instead of - // `null` when everyone is offline. The frontend's traffic handler treats - // a missing/null onlineClients field as "no update", so without this the - // "everyone went offline" transition was silently dropped — stale online - // users lingered in the list and the online filter kept showing them. lastOnlineMap, err := j.inboundService.GetClientsLastOnline() if err != nil { logger.Warning("get clients last online failed:", err) @@ -84,13 +72,12 @@ func (j *XrayTrafficJob) Run() { if lastOnlineMap == nil { lastOnlineMap = make(map[string]int64) } - - // Determine online clients from lastOnline timestamps with a 5-second - // grace period instead of just the current 5-second traffic poll. This - // prevents idle-but-connected clients from randomly disappearing from - // the UI between polling windows. j.inboundService.RefreshOnlineClientsFromMap(lastOnlineMap) + if !websocket.HasClients() { + return + } + onlineClients := j.inboundService.GetOnlineClients() if onlineClients == nil { onlineClients = []string{} @@ -102,11 +89,6 @@ func (j *XrayTrafficJob) Run() { "lastOnlineMap": lastOnlineMap, }) - // Full snapshot every cycle: absolute per-client counters and inbound - // totals. Frontend overwrites both in place. The previous delta path - // (activeEmails -> GetActiveClientTraffics) silently omitted the - // clients array whenever nobody moved bytes in the cycle, leaving the - // client rows in the UI stuck at stale traffic/remained/all-time. clientStatsPayload := map[string]any{} if stats, err := j.inboundService.GetAllClientTraffics(); err != nil { logger.Warning("get all client traffics for websocket failed:", err) @@ -122,8 +104,6 @@ func (j *XrayTrafficJob) Run() { websocket.BroadcastClientStats(clientStatsPayload) } - // Outbounds list is small (one row per outbound, no per-client expansion) - // so the full snapshot still fits comfortably in WS. if updatedOutbounds, err := j.outboundService.GetOutboundsTraffic(); err == nil && updatedOutbounds != nil { websocket.BroadcastOutbounds(updatedOutbounds) } else if err != nil { diff --git a/web/service/client.go b/web/service/client.go index a464029e..0bdf6cc2 100644 --- a/web/service/client.go +++ b/web/service/client.go @@ -213,12 +213,22 @@ func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model. } row = incoming } else { - row.UUID = incoming.UUID - row.Password = incoming.Password - row.Auth = incoming.Auth + if incoming.UUID != "" { + row.UUID = incoming.UUID + } + if incoming.Password != "" { + row.Password = incoming.Password + } + if incoming.Auth != "" { + row.Auth = incoming.Auth + } row.Flow = incoming.Flow - row.Security = incoming.Security - row.Reverse = incoming.Reverse + if incoming.Security != "" { + row.Security = incoming.Security + } + if incoming.Reverse != "" { + row.Reverse = incoming.Reverse + } row.SubID = incoming.SubID row.LimitIP = incoming.LimitIP row.TotalGB = incoming.TotalGB diff --git a/web/service/client_sync_multiprotocol_test.go b/web/service/client_sync_multiprotocol_test.go new file mode 100644 index 00000000..cb4e1f37 --- /dev/null +++ b/web/service/client_sync_multiprotocol_test.go @@ -0,0 +1,113 @@ +package service + +import ( + "path/filepath" + "testing" + + "github.com/mhsanaei/3x-ui/v3/database" + "github.com/mhsanaei/3x-ui/v3/database/model" +) + +func TestSyncInbound_PreservesCredentialsAcrossProtocols(t *testing.T) { + dbDir := t.TempDir() + t.Setenv("XUI_DB_FOLDER", dbDir) + if err := database.InitDB(filepath.Join(dbDir, "3x-ui.db")); err != nil { + t.Fatalf("InitDB: %v", err) + } + t.Cleanup(func() { _ = database.CloseDB() }) + + db := database.GetDB() + + vlessInbound := &model.Inbound{Tag: "vless-in", Enable: true, Port: 10001, Protocol: model.VLESS} + if err := db.Create(vlessInbound).Error; err != nil { + t.Fatalf("create vless inbound: %v", err) + } + hysteriaInbound := &model.Inbound{Tag: "hy-in", Enable: true, Port: 10002, Protocol: model.Hysteria2} + if err := db.Create(hysteriaInbound).Error; err != nil { + t.Fatalf("create hysteria inbound: %v", err) + } + + svc := ClientService{} + const sharedEmail = "shared@example.com" + const wantUUID = "ce8d33df-3a64-4f10-8f9b-91c3a8e0c001" + const wantAuth = "h2-auth-token" + const wantFlow = "xtls-rprx-vision" + + vlessClient := model.Client{Email: sharedEmail, ID: wantUUID, Enable: true, Flow: wantFlow} + if err := svc.SyncInbound(nil, vlessInbound.Id, []model.Client{vlessClient}); err != nil { + t.Fatalf("vless SyncInbound: %v", err) + } + + hysteriaClient := model.Client{Email: sharedEmail, Auth: wantAuth, Enable: true} + if err := svc.SyncInbound(nil, hysteriaInbound.Id, []model.Client{hysteriaClient}); err != nil { + t.Fatalf("hysteria SyncInbound: %v", err) + } + + var row model.ClientRecord + if err := db.Where("email = ?", sharedEmail).First(&row).Error; err != nil { + t.Fatalf("lookup client row: %v", err) + } + if row.UUID != wantUUID { + t.Errorf("UUID was clobbered by Hysteria sync: got %q, want %q", row.UUID, wantUUID) + } + if row.Auth != wantAuth { + t.Errorf("Auth not persisted: got %q, want %q", row.Auth, wantAuth) + } + + vlessList, err := svc.ListForInbound(nil, vlessInbound.Id) + if err != nil { + t.Fatalf("ListForInbound(vless): %v", err) + } + if len(vlessList) != 1 || vlessList[0].Flow != wantFlow { + t.Errorf("VLESS inbound should still report flow=%q via FlowOverride, got %#v", wantFlow, vlessList) + } + + hysteriaList, err := svc.ListForInbound(nil, hysteriaInbound.Id) + if err != nil { + t.Fatalf("ListForInbound(hysteria): %v", err) + } + if len(hysteriaList) != 1 || hysteriaList[0].Flow != "" { + t.Errorf("Hysteria inbound should report empty flow, got %#v", hysteriaList) + } +} + +func TestSyncInbound_AllowsClearingFlow(t *testing.T) { + dbDir := t.TempDir() + t.Setenv("XUI_DB_FOLDER", dbDir) + if err := database.InitDB(filepath.Join(dbDir, "3x-ui.db")); err != nil { + t.Fatalf("InitDB: %v", err) + } + t.Cleanup(func() { _ = database.CloseDB() }) + + db := database.GetDB() + + vless := &model.Inbound{Tag: "vless-in", Enable: true, Port: 10003, Protocol: model.VLESS} + if err := db.Create(vless).Error; err != nil { + t.Fatalf("create vless inbound: %v", err) + } + + svc := ClientService{} + const email = "alice@example.com" + const uid = "ce8d33df-3a64-4f10-8f9b-91c3a8e0c002" + + withFlow := model.Client{Email: email, ID: uid, Enable: true, Flow: "xtls-rprx-vision"} + if err := svc.SyncInbound(nil, vless.Id, []model.Client{withFlow}); err != nil { + t.Fatalf("vless SyncInbound (set flow): %v", err) + } + + cleared := model.Client{Email: email, ID: uid, Enable: true, Flow: ""} + if err := svc.SyncInbound(nil, vless.Id, []model.Client{cleared}); err != nil { + t.Fatalf("vless SyncInbound (clear flow): %v", err) + } + + list, err := svc.ListForInbound(nil, vless.Id) + if err != nil { + t.Fatalf("ListForInbound: %v", err) + } + if len(list) != 1 { + t.Fatalf("expected 1 client, got %d", len(list)) + } + if list[0].Flow != "" { + t.Errorf("flow should be clearable on the owning inbound, got %q (Copilot review on #4545)", list[0].Flow) + } +}