From 7db85005b4135dfd5df991f11c5ad973c71e2742 Mon Sep 17 00:00:00 2001 From: mjbe71 Date: Tue, 24 Nov 2026 03:48:41 +0330 Subject: [PATCH] fix(sub): let balancers select inbounds that are hidden from the subscription (#7098) An inbound marked Exclude from subscriptions was skipped before its configs were built, and a balancer only reads the entries that reach the output. A hidden inbound could therefore never be a balancer member, although the balancer form lists it, and a balancer of only hidden inbounds never reached the subscriber. A hidden inbound that an enabled balancer selects is now rendered into a list that never reaches the output, and balancers draw members from both lists. It still gets no document of its own, its clients still count in the usage header, and rendering it spends neither the response budget nor the first-link remark tokens. An inbound that is already hidden and already selected in a balancer appears inside that balancer after the upgrade. --- internal/sub/json_service.go | 77 ++++++++++++---- internal/sub/sub_balancer_hidden_test.go | 109 +++++++++++++++++++++++ 2 files changed, 171 insertions(+), 15 deletions(-) create mode 100644 internal/sub/sub_balancer_hidden_test.go diff --git a/internal/sub/json_service.go b/internal/sub/json_service.go index e1cef2c30..99a72c269 100644 --- a/internal/sub/json_service.go +++ b/internal/sub/json_service.go @@ -138,17 +138,31 @@ func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bo seenEmails := make(map[string]struct{}) entries := make([]subConfigEntry, 0, len(inbounds)) var ordered []orderedSubEntry[func() subConfigEntry] + balancers := getEnabledSubBalancers() + balancerInbounds := balancerInboundIds(balancers) + // Hidden inbounds that a balancer selects: their configs only feed balancer members. + var hidden []subConfigEntry // Prepare Inbounds for _, inbound := range inbounds { clients := subReq.matchingClients(inbound, subId) if len(clients) == 0 { continue } + hiddenMember := false if inbound.ExcludeFromSub { if countHiddenClients(clients, seenEmails) { hasEnabledClient = true } - continue + if !balancerInbounds[inbound.Id] { + continue + } + hiddenMember = true + } + renderConfigs := func(inbound *model.Inbound, client model.Client) []json_util.RawMessage { + if hiddenMember { + return s.hiddenMemberConfig(subReq, inbound, client, host) + } + return s.budgetedConfig(subReq, inbound, client, host) } subReq.projectThroughFallbackMaster(inbound) var baseEps []map[string]any @@ -175,12 +189,18 @@ func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bo } if subReq.hostsFirst { variants, closed := subReq.clientHostVariants(&baseInbound, client, "json") - hasBoundClosed = hasBoundClosed || closed + hasBoundClosed = hasBoundClosed || (closed && !hiddenMember) for _, variant := range variants { render := func() subConfigEntry { - configs := s.budgetedConfig(subReq, variant.inbound(subReq, inbound), client, host) + configs := renderConfigs(variant.inbound(subReq, inbound), client) return subConfigEntry{sortIndex: inbound.SubSortIndex, id: inbound.Id, configs: configs, hostOrder: variant.order} } + if hiddenMember { + if entry := render(); len(entry.configs) > 0 { + hidden = append(hidden, entry) + } + continue + } ordered = append(ordered, orderedSubEntry[func() subConfigEntry]{variant.order, render}) } continue @@ -188,7 +208,7 @@ func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bo effective := inbound if effectiveEps, bound := subReq.clientHostEndpoints(&baseInbound, client, "json", baseEps); bound { if len(effectiveEps) == 0 { - hasBoundClosed = true + hasBoundClosed = hasBoundClosed || !hiddenMember continue } clone := baseInbound @@ -196,14 +216,19 @@ func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bo injectExternalProxy(&clone, effectiveEps) effective = &clone } - inboundConfigs = append(inboundConfigs, s.budgetedConfig(subReq, effective, client, host)...) + inboundConfigs = append(inboundConfigs, renderConfigs(effective, client)...) } if len(inboundConfigs) > 0 { - entries = append(entries, subConfigEntry{ + entry := subConfigEntry{ sortIndex: inbound.SubSortIndex, id: inbound.Id, configs: inboundConfigs, - }) + } + if hiddenMember { + hidden = append(hidden, entry) + } else { + entries = append(entries, entry) + } } } if subReq.hostsFirst { @@ -214,7 +239,7 @@ func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bo } } } - entries = s.appendBalancerEntries(entries) + entries = s.appendBalancerEntries(entries, hidden, balancers) // Inbounds arrive sorted by (sub_sort_index, id); balancers interleave by // the same key and, on an equal number, follow the inbound group. @@ -424,17 +449,39 @@ func (s *SubJsonService) balancerObservatory(prefix string) map[string]any { } } -// appendBalancerEntries appends one entry per enabled balancer that has at -// least one member outbound among the inbound entries. -func (s *SubJsonService) appendBalancerEntries(entries []subConfigEntry) []subConfigEntry { - balancers := getEnabledSubBalancers() +// balancerInboundIds is the set of inbound ids any of the balancers selects. +func balancerInboundIds(balancers []model.SubBalancer) map[int]bool { + ids := make(map[int]bool) + for _, balancer := range balancers { + for _, id := range balancer.InboundIds { + ids[id] = true + } + } + return ids +} + +// hiddenMemberConfig renders a hidden inbound's configs for balancer members only: none of it +// reaches the response, so it neither spends the render budget nor the first-link remark tokens. +func (s *SubJsonService) hiddenMemberConfig(subReq *SubService, inbound *model.Inbound, client model.Client, host string) []json_util.RawMessage { + if subReq.rendered.spent() { + return nil + } + usageShown := maps.Clone(subReq.usageShown) + defer func() { subReq.usageShown = usageShown }() + return s.getConfig(subReq, inbound, client, host) +} + +// appendBalancerEntries appends one entry per balancer that has at least one member outbound +// among the inbound entries; hidden inbounds' entries are members but never output themselves. +func (s *SubJsonService) appendBalancerEntries(entries, hidden []subConfigEntry, balancers []model.SubBalancer) []subConfigEntry { if len(balancers) == 0 { return entries } + sources := append(slices.Clip(entries), hidden...) // Pre-pass: pull each inbound doc's proxy outbound once so every balancer // reuses it instead of re-unmarshalling the whole document per balancer. - entryProxies := make([][]map[string]any, len(entries)) - for i, entry := range entries { + entryProxies := make([][]map[string]any, len(sources)) + for i, entry := range sources { if entry.kind != 0 { continue } @@ -445,7 +492,7 @@ func (s *SubJsonService) appendBalancerEntries(entries []subConfigEntry) []subCo } } for i := range balancers { - config := s.buildBalancerConfig(&balancers[i], entries, entryProxies) + config := s.buildBalancerConfig(&balancers[i], sources, entryProxies) if config == nil { continue } diff --git a/internal/sub/sub_balancer_hidden_test.go b/internal/sub/sub_balancer_hidden_test.go new file mode 100644 index 000000000..e4f3d86aa --- /dev/null +++ b/internal/sub/sub_balancer_hidden_test.go @@ -0,0 +1,109 @@ +package sub + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func hideInbound(t *testing.T, ib *model.Inbound) { + t.Helper() + if err := database.GetDB().Model(ib).Update("exclude_from_sub", true).Error; err != nil { + t.Fatalf("hide inbound: %v", err) + } +} + +func docsMentioning(t *testing.T, docs []map[string]any, needle string) []string { + t.Helper() + var remarks []string + for _, doc := range docs { + raw, err := json.Marshal(doc) + if err != nil { + t.Fatalf("marshal doc: %v", err) + } + if strings.Contains(string(raw), needle) { + remarks = append(remarks, doc["remarks"].(string)) + } + } + return remarks +} + +// A balancer may select an inbound that is hidden from the subscription: the +// inbound contributes a member outbound to the balancer doc only. +func TestSubJson_BalancerMemberFromHiddenInbound(t *testing.T) { + for _, mode := range []string{"legacy", "hosts-first"} { + t.Run(mode, func(t *testing.T) { + seedSubDB(t) + setHostSortMode(t, mode) + shown := seedSubInbound(t, "s1", "shown", 4711, 2, tcpTLSStream) + hidden := seedSubInbound(t, "s1", "hidden", 4712, 1, wsTLSStream) + hideInbound(t, hidden) + seedSubBalancer(t, &model.SubBalancer{ + Remark: "auto", Strategy: "random", InboundIds: []int{shown.Id, hidden.Id}, SortOrder: 1, Enabled: true, + }) + + out, _, err := NewSubJsonService("", "", "", "", NewSubService("")).GetJson("s1", "req.example.com", true) + if err != nil { + t.Fatalf("GetJson: %v", err) + } + docs := parseSubJsonDocs(t, out) + if len(docs) != 2 { + t.Fatalf("docs = %d, want 2 (shown inbound + balancer):\n%s", len(docs), out) + } + balancerDoc := findDocByRemarks(docs, "auto") + if balancerDoc == nil { + t.Fatalf("balancer doc missing:\n%s", out) + } + if tags := strings.Join(docOutboundTags(balancerDoc), ","); tags != "bal-1-vless,bal-1-vless-2,direct,block" { + t.Fatalf("balancer outbound tags = %s, want both members", tags) + } + if holders := docsMentioning(t, docs, "4712"); len(holders) != 1 || holders[0] != "auto" { + t.Fatalf("hidden inbound must appear only inside the balancer doc, found in %v", holders) + } + }) + } +} + +// A balancer whose only member is hidden still renders. +func TestSubJson_BalancerOfOnlyHiddenInbound(t *testing.T) { + seedSubDB(t) + hidden := seedSubInbound(t, "s1", "hidden", 4715, 1, tcpTLSStream) + hideInbound(t, hidden) + seedSubBalancer(t, &model.SubBalancer{ + Remark: "solo", Strategy: "random", InboundIds: []int{hidden.Id}, SortOrder: 1, Enabled: true, + }) + + out, _, err := NewSubJsonService("", "", "", "", NewSubService("")).GetJson("s1", "req.example.com", true) + if err != nil { + t.Fatalf("GetJson: %v", err) + } + docs := parseSubJsonDocs(t, out) + if len(docs) != 1 || docs[0]["remarks"] != "solo" { + t.Fatalf("want only the balancer doc, got:\n%s", out) + } +} + +// Rendering a hidden member must not use up the first-link-only remark tokens: +// the first inbound the client actually sees still carries them. +func TestSubJson_HiddenBalancerMemberKeepsFirstLinkRemark(t *testing.T) { + seedSubDB(t) + hidden := seedSubInbound(t, "s1", "hidden", 4716, 1, tcpTLSStream) + seedSubInbound(t, "s1", "shown", 4717, 2, wsTLSStream) + hideInbound(t, hidden) + seedSubBalancer(t, &model.SubBalancer{ + Remark: "auto", Strategy: "random", InboundIds: []int{hidden.Id}, SortOrder: 9, Enabled: true, + }) + + svc := NewSubService("{{INBOUND}}-{{EMAIL}}") + out, _, err := NewSubJsonService("", "", "", "", svc).GetJson("s1", "req.example.com", true) + if err != nil { + t.Fatalf("GetJson: %v", err) + } + shownDoc := findDocByRemarks(parseSubJsonDocs(t, out), "shown-shown@e") + if shownDoc == nil { + t.Fatalf("shown inbound lost its first-link remark (email token spent on the hidden member):\n%s", out) + } +}