diff --git a/internal/web/service/outbound_subscription.go b/internal/web/service/outbound_subscription.go index bc9115639..5b77f4541 100644 --- a/internal/web/service/outbound_subscription.go +++ b/internal/web/service/outbound_subscription.go @@ -216,6 +216,19 @@ func (s *OutboundSubscriptionService) Create(remark, rawURL, tagPrefix, userAgen return sub, nil } +// normalizedSubscriptionPrefix is what link.SuggestTag puts in front of every tag of the +// subscription: the prefix with one trailing dash, or nothing for a dash-only prefix. +func normalizedSubscriptionPrefix(subID int, tagPrefix string) string { + prefix := strings.TrimSpace(tagPrefix) + if prefix == "" { + prefix = fmt.Sprintf("sub%d-", subID) + } + if p := strings.TrimSuffix(prefix, "-"); p != "" { + return p + "-" + } + return "" +} + // Update updates editable fields. func (s *OutboundSubscriptionService) Update(id int, remark, rawURL, tagPrefix, userAgent string, enabled bool, updateInterval int, allowPrivate, prepend, allowInsecure bool) error { sub, err := s.Get(id) @@ -233,15 +246,18 @@ func (s *OutboundSubscriptionService) Update(id int, remark, rawURL, tagPrefix, updateInterval = 600 } prefix := strings.TrimSpace(tagPrefix) - if prefix == "" { + if prefix == "" && sub.TagPrefix != "" { prefix, err = s.nextDefaultSubPrefix(sub.Id) if err != nil { return err } } + oldEffective := normalizedSubscriptionPrefix(sub.Id, sub.TagPrefix) + newEffective := normalizedSubscriptionPrefix(sub.Id, prefix) + // Only the editable columns: a whole-row save would put back fetch results that a // refresh stored meanwhile, or re-create a row deleted meanwhile. - return database.GetDB().Model(&model.OutboundSubscription{}).Where("id = ?", sub.Id).Updates(map[string]any{ + updates := map[string]any{ "remark": strings.TrimSpace(remark), "url": cleanURL, "enabled": enabled, @@ -251,7 +267,74 @@ func (s *OutboundSubscriptionService) Update(id int, remark, rawURL, tagPrefix, "prepend": prepend, "tag_prefix": prefix, "update_interval": updateInterval, - }).Error + } + if oldEffective != newEffective { + s.rewriteStoredPrefix(sub, oldEffective, newEffective, updates) + } + return database.GetDB().Model(&model.OutboundSubscription{}).Where("id = ?", sub.Id).Updates(updates).Error +} + +// rewriteStoredPrefix moves the stored tags and identities to the new prefix at edit time, +// so the panel shows them at once and the next refresh finds nothing stale to reuse. +func (s *OutboundSubscriptionService) rewriteStoredPrefix(sub *model.OutboundSubscription, oldPrefix, newPrefix string, updates map[string]any) { + if strings.TrimSpace(sub.LinkIdentities) == "" && strings.TrimSpace(sub.LastFetchedOutbounds) == "" { + return + } + externalUsed := s.reservedExternalTags(sub.Id) + used := make(map[string]bool) + renamed := make(map[string]string) + + allocate := func(oldTag string) string { + if oldTag == "" { + return "" + } + if mapped, ok := renamed[oldTag]; ok { + return mapped + } + base := oldTag + if strings.HasPrefix(oldTag, oldPrefix) { + rest := strings.TrimPrefix(oldTag, oldPrefix) + if rest != "" { + base = newPrefix + rest + } + } + final := base + for k := 1; used[final] || externalUsed[final]; k++ { + final = fmt.Sprintf("%s-%d", base, k) + } + used[final] = true + renamed[oldTag] = final + return final + } + + if strings.TrimSpace(sub.LastFetchedOutbounds) != "" { + var obs []any + if json.Unmarshal([]byte(sub.LastFetchedOutbounds), &obs) == nil { + for _, item := range obs { + if m, ok := item.(map[string]any); ok { + if t, _ := m["tag"].(string); t != "" { + m["tag"] = allocate(t) + } + } + } + if b, err := json.Marshal(obs); err == nil { + updates["last_fetched_outbounds"] = string(b) + } + } + } + if strings.TrimSpace(sub.LinkIdentities) != "" { + var prev map[string]string + if json.Unmarshal([]byte(sub.LinkIdentities), &prev) == nil { + for id, t := range prev { + if t != "" { + prev[id] = allocate(t) + } + } + if b, err := json.Marshal(prev); err == nil { + updates["link_identities"] = string(b) + } + } + } } // Delete removes a subscription. @@ -507,11 +590,13 @@ func (s *OutboundSubscriptionService) fetchOutbounds(sub *model.OutboundSubscrip keptIdentities = append(keptIdentities, identities[i]) } - // Assign tags with stability (identity reuse, positional fallback, then a - // fresh allocation), keeping tags unique within this batch. Extracted into a - // pure function so it can be unit-tested without network/DB. Tags are written - // back into the parsed outbounds in place. - assigned := assignStableTags(keptLinks, keptIdentities, prev, prevTagByIndex, sub.Id, sub.TagPrefix) + // Identity reuse, positional fallback, then a fresh allocation; tags stay unique in the + // batch and against the template and the other subscriptions. + var externalUsed map[string]bool + if sub.Id > 0 { + externalUsed = s.reservedExternalTags(sub.Id) + } + assigned := assignStableTagsWithExternal(keptLinks, keptIdentities, prev, prevTagByIndex, sub.Id, sub.TagPrefix, externalUsed) // Persist identities for next time newIdent := map[string]string{} @@ -601,10 +686,23 @@ func (s *OutboundSubscriptionService) recordError(sub *model.OutboundSubscriptio // written back into parsed[i]["tag"]. The returned slice holds the assigned tags // in order. When tagPrefix is empty a "sub-" prefix is used for fresh tags. func assignStableTags(parsed []link.Outbound, identities []string, prev map[string]string, prevTagByIndex map[int]string, subID int, tagPrefix string) []string { + return assignStableTagsWithExternal(parsed, identities, prev, prevTagByIndex, subID, tagPrefix, nil) +} + +func assignStableTagsWithExternal(parsed []link.Outbound, identities []string, prev map[string]string, prevTagByIndex map[int]string, subID int, tagPrefix string, externalUsed map[string]bool) []string { + prefix := tagPrefix + if prefix == "" { + prefix = fmt.Sprintf("sub%d-", subID) + } + expectedPrefix := normalizedSubscriptionPrefix(subID, prefix) + reservedStableTags := map[string]bool{} for i := range parsed { if i < len(identities) && prev[identities[i]] != "" { - reservedStableTags[prev[identities[i]]] = true + tag := prev[identities[i]] + if strings.HasPrefix(tag, expectedPrefix) && !externalUsed[tag] { + reservedStableTags[tag] = true + } } } @@ -617,31 +715,27 @@ func assignStableTags(parsed []link.Outbound, identities []string, prev map[stri } candidate := "" identityTag := "" - if old, ok := prev[id]; ok && old != "" { + if old, ok := prev[id]; ok && old != "" && strings.HasPrefix(old, expectedPrefix) { candidate = old identityTag = old } if candidate == "" { // try to reuse by rough positional match from previous fetch (best effort) - if old, ok := prevTagByIndex[i]; ok && old != "" && !reservedStableTags[old] { + if old, ok := prevTagByIndex[i]; ok && old != "" && strings.HasPrefix(old, expectedPrefix) && !reservedStableTags[old] { candidate = old } } if candidate == "" { // fresh allocation - prefix := tagPrefix - if prefix == "" { - prefix = fmt.Sprintf("sub%d-", subID) - } remark := "" if m, ok := parsed[i]["tag"].(string); ok { remark = m } candidate = link.SuggestTag(prefix, remark, i) } - // ensure local uniqueness inside this batch + // ensure uniqueness inside this batch and against template / other subscriptions final := candidate - for k := 1; used[final] || (reservedStableTags[final] && final != identityTag); k++ { + for k := 1; used[final] || externalUsed[final] || (reservedStableTags[final] && final != identityTag); k++ { final = fmt.Sprintf("%s-%d", candidate, k) } used[final] = true @@ -653,11 +747,104 @@ func assignStableTags(parsed []link.Outbound, identities []string, prev map[stri return assigned } +// templateOutboundTags is the set of tags the stored Xray template's own outbounds use. +func (s *OutboundSubscriptionService) templateOutboundTags() map[string]bool { + used := make(map[string]bool) + if database.GetDB() == nil { + return used + } + tpl, err := s.settingService.GetXrayConfigTemplate() + if err != nil || strings.TrimSpace(tpl) == "" { + return used + } + var cfg xray.Config + if err := json.Unmarshal([]byte(tpl), &cfg); err != nil || len(cfg.OutboundConfigs) == 0 { + return used + } + var templateOutbounds []any + if err := json.Unmarshal(cfg.OutboundConfigs, &templateOutbounds); err != nil { + return used + } + for _, item := range templateOutbounds { + if ob, ok := item.(map[string]any); ok { + if tag, _ := ob["tag"].(string); tag != "" { + used[tag] = true + } + } + } + return used +} + +// reservedExternalTags is every tag the template and the other subscriptions hold, so a +// refresh or prefix edit stores tags that already collide with none of them. +func (s *OutboundSubscriptionService) reservedExternalTags(excludeSubID int) map[string]bool { + used := s.templateOutboundTags() + db := database.GetDB() + if db == nil { + return used + } + var subs []*model.OutboundSubscription + if err := db.Where("id <> ?", excludeSubID).Order("priority asc, id asc").Find(&subs).Error; err != nil { + return used + } + for _, sub := range subs { + if strings.TrimSpace(sub.LastFetchedOutbounds) == "" { + continue + } + var arr []any + if json.Unmarshal([]byte(sub.LastFetchedOutbounds), &arr) != nil { + continue + } + for _, item := range arr { + if ob, ok := item.(map[string]any); ok { + if tag, _ := ob["tag"].(string); tag != "" { + used[tag] = true + } + } + } + } + return used +} + +// dedupeSubscriptionOutboundList gives a colliding outbound a "-N" tag on a copy; Xray +// refuses to start on a duplicate tag ("existing tag found"). +func dedupeSubscriptionOutboundList(list []any, usedTags map[string]bool) []any { + out := make([]any, len(list)) + for i, item := range list { + ob, ok := item.(map[string]any) + if !ok { + out[i] = item + continue + } + tag, _ := ob["tag"].(string) + if tag == "" { + out[i] = item + continue + } + if !usedTags[tag] { + usedTags[tag] = true + out[i] = item + continue + } + cloned := make(map[string]any, len(ob)) + for k, v := range ob { + cloned[k] = v + } + final := tag + for k := 1; usedTags[final]; k++ { + final = fmt.Sprintf("%s-%d", tag, k) + } + usedTags[final] = true + cloned["tag"] = final + logger.Debugf("outbound subscription tag %q collides with an existing outbound, renamed to %q", tag, final) + out[i] = cloned + } + return out +} + // AllActiveOutbounds returns the concatenation of the last-fetched outbounds // for every enabled subscription. This is the set that should be merged into -// the final Xray config. Order: subscription creation order (by id asc) so -// that later subscriptions can shadow earlier ones if the admin uses colliding -// prefixes (last writer wins inside xray, but we try to keep tags unique). +// the final Xray config. func (s *OutboundSubscriptionService) AllActiveOutbounds() ([]any, error) { prepend, appendList, err := s.activeOutboundsSplit() if err != nil { @@ -708,6 +895,9 @@ func (s *OutboundSubscriptionService) activeOutboundsSplit() (prepend []any, app appendList = append(appendList, arr...) } } + usedTags := s.templateOutboundTags() + prepend = dedupeSubscriptionOutboundList(prepend, usedTags) + appendList = dedupeSubscriptionOutboundList(appendList, usedTags) return prepend, appendList, nil } diff --git a/internal/web/service/outbound_subscription_test.go b/internal/web/service/outbound_subscription_test.go index b4f340d06..62ca9583e 100644 --- a/internal/web/service/outbound_subscription_test.go +++ b/internal/web/service/outbound_subscription_test.go @@ -387,6 +387,35 @@ func TestAssignStableTags(t *testing.T) { t.Fatalf("got[1] = %q, want %q", got[1], base+"-1") } }) + + t.Run("regenerates tags with new prefix when tagPrefix changed (#7110)", func(t *testing.T) { + parsed := []link.Outbound{{"tag": "canada-1"}} + prev := map[string]string{"id-canada": "gh-canada-1"} + prevPos := map[int]string{0: "gh-canada-1"} + got := assignStableTags(parsed, []string{"id-canada"}, prev, prevPos, 1, "gh1-") + want := "gh1-canada-1" + if got[0] != want { + t.Fatalf("got %q, want %q (old tag with old prefix must not be preserved)", got[0], want) + } + }) + + t.Run("keeps an identity's tag when its remark shrinks to a suffix of the old one", func(t *testing.T) { + parsed := []link.Outbound{{"tag": "DE"}} + prev := map[string]string{"id-1": "gh-premium-de"} + got := assignStableTags(parsed, []string{"id-1"}, prev, map[int]string{0: "gh-premium-de"}, 1, "gh-") + if got[0] != "gh-premium-de" { + t.Fatalf("got %q, want gh-premium-de: a renamed remark must not move the tag routing rules name", got[0]) + } + }) + + t.Run("a dash-only prefix adds nothing, so stored tags keep matching", func(t *testing.T) { + parsed := []link.Outbound{{"tag": "Tokyo-2"}} + prev := map[string]string{"id-1": "tokyo"} + got := assignStableTags(parsed, []string{"id-1"}, prev, nil, 1, "-") + if got[0] != "tokyo" { + t.Fatalf("got %q, want tokyo", got[0]) + } + }) } // TestOutboundsContainTag covers the guard that ensures the outbound under test @@ -733,3 +762,119 @@ func TestOutboundSubscriptionRefreshDropsXhttpDownloadSettingsTheCorePanicsOn(t t.Fatalf("tags by address = %v, want %v", got, want) } } + +func TestOutboundSubscriptionUpdateRewritesShortenedPrefixAndPreservesLegacyBlankPrefix(t *testing.T) { + setupSettingTestDB(t) + svc := &OutboundSubscriptionService{} + + // 1. Shortening TagPrefix ("eu-de-" -> "eu-") updates stored tags immediately + // and keeps the shortened prefix across subsequent refreshes. + subID := serveOutboundSubscription(t, "eu-de-", func(int) string { + return "vless://00000000-0000-4000-8000-000000000000@8.8.8.8:443?security=tls&type=tcp#Frankfurt\n" + }) + if err := database.GetDB().Model(&model.OutboundSubscription{}).Where("id = ?", subID).Update("enabled", true).Error; err != nil { + t.Fatalf("enable: %v", err) + } + tags, _ := refreshOutboundTags(t, subID) + if !slices.Equal(tags, []string{"eu-de-frankfurt"}) { + t.Fatalf("initial tags = %v, want [eu-de-frankfurt]", tags) + } + subBefore, err := svc.Get(subID) + if err != nil { + t.Fatalf("Get: %v", err) + } + if err := svc.Update(subID, "DE", subBefore.Url, "eu-", "", true, 600, true, false, false); err != nil { + t.Fatalf("Update shortened prefix: %v", err) + } + activeTags, err := svc.AllActiveOutboundTags() + if err != nil || !slices.Equal(activeTags, []string{"eu-frankfurt"}) { + t.Fatalf("AllActiveOutboundTags after Update = %v (%v), want [eu-frankfurt]", activeTags, err) + } + tagsAfterRefresh, _ := refreshOutboundTags(t, subID) + if !slices.Equal(tagsAfterRefresh, []string{"eu-frankfurt"}) { + t.Fatalf("tags after Refresh with shortened prefix = %v, want [eu-frankfurt]", tagsAfterRefresh) + } + + // 2. Editing a legacy blank-prefix subscription (where sub.Id != 1 and sub1- is free) + // without touching the blank prefix must keep its sub- tags unchanged. + legacyID := serveOutboundSubscription(t, "", func(int) string { + return "vless://00000000-0000-4000-8000-000000000001@8.8.4.4:443?security=tls&type=tcp#Tokyo\n" + }) + if legacyID == 1 { + t.Fatalf("expected legacy subscription id > 1, got %d", legacyID) + } + wantLegacyTag := fmt.Sprintf("sub%d-tokyo", legacyID) + legacyTags, _ := refreshOutboundTags(t, legacyID) + if !slices.Equal(legacyTags, []string{wantLegacyTag}) { + t.Fatalf("initial legacy tags = %v, want [%s]", legacyTags, wantLegacyTag) + } + legacySub, err := svc.Get(legacyID) + if err != nil { + t.Fatalf("Get legacy: %v", err) + } + if err := svc.Update(legacyID, "edited-remark", legacySub.Url, "", "", true, 900, true, false, false); err != nil { + t.Fatalf("Update legacy subscription: %v", err) + } + legacyAfterUpdate, err := svc.Get(legacyID) + if err != nil { + t.Fatalf("Get legacy after Update: %v", err) + } + if legacyAfterUpdate.TagPrefix != "" { + t.Fatalf("legacy TagPrefix = %q, want empty string preserved", legacyAfterUpdate.TagPrefix) + } + legacyTagsAfterRefresh, _ := refreshOutboundTags(t, legacyID) + if !slices.Equal(legacyTagsAfterRefresh, []string{wantLegacyTag}) { + t.Fatalf("legacy tags after Update+Refresh = %v, want [%s] preserved", legacyTagsAfterRefresh, wantLegacyTag) + } +} + +func TestOutboundSubscriptionCrossSubscriptionCollisionPersistsAndMatchesPanelSurfaces(t *testing.T) { + setupSettingTestDB(t) + svc := &OutboundSubscriptionService{} + + sub1 := serveOutboundSubscription(t, "gh-", func(int) string { + return "vless://00000000-0000-4000-8000-000000000011@1.1.1.1:443?security=tls&type=tcp#canada-1\n" + }) + sub2 := serveOutboundSubscription(t, "gh-", func(int) string { + return "vless://00000000-0000-4000-8000-000000000022@8.8.8.8:443?security=tls&type=tcp#canada-1\n" + }) + for idx, id := range []int{sub1, sub2} { + if err := database.GetDB().Model(&model.OutboundSubscription{}).Where("id = ?", id).Updates(map[string]any{ + "enabled": true, + "priority": idx, + }).Error; err != nil { + t.Fatalf("enable sub %d: %v", id, err) + } + } + + tags1, _ := refreshOutboundTags(t, sub1) + tags2, _ := refreshOutboundTags(t, sub2) + if !slices.Equal(tags1, []string{"gh-canada-1"}) { + t.Fatalf("sub1 persisted tags = %v, want [gh-canada-1]", tags1) + } + if !slices.Equal(tags2, []string{"gh-canada-1-1"}) { + t.Fatalf("sub2 persisted tags = %v, want [gh-canada-1-1]", tags2) + } + + // Panel surfaces (AllActiveOutboundTags) must list both distinct tags. + panelTags, err := svc.AllActiveOutboundTags() + if err != nil || !slices.Equal(panelTags, []string{"gh-canada-1", "gh-canada-1-1"}) { + t.Fatalf("AllActiveOutboundTags = %v (%v), want [gh-canada-1 gh-canada-1-1]", panelTags, err) + } + + // Reordering subscription priorities or disabling sub1 must not swap sub2's persisted tag. + if err := svc.Move(sub2, true); err != nil { + t.Fatalf("Move: %v", err) + } + panelTagsAfterMove, err := svc.AllActiveOutboundTags() + if err != nil || !slices.Equal(panelTagsAfterMove, []string{"gh-canada-1-1", "gh-canada-1"}) { + t.Fatalf("AllActiveOutboundTags after Move = %v (%v), want [gh-canada-1-1 gh-canada-1]", panelTagsAfterMove, err) + } + if err := database.GetDB().Model(&model.OutboundSubscription{}).Where("id = ?", sub1).Update("enabled", false).Error; err != nil { + t.Fatalf("disable sub1: %v", err) + } + panelTagsAfterDisable, err := svc.AllActiveOutboundTags() + if err != nil || !slices.Equal(panelTagsAfterDisable, []string{"gh-canada-1-1"}) { + t.Fatalf("AllActiveOutboundTags after disabling sub1 = %v (%v), want [gh-canada-1-1]", panelTagsAfterDisable, err) + } +} diff --git a/internal/web/service/xray.go b/internal/web/service/xray.go index 1109dc9c2..f6a743765 100644 --- a/internal/web/service/xray.go +++ b/internal/web/service/xray.go @@ -1141,10 +1141,24 @@ func mergeSubscriptionOutbounds(cfg *xray.Config, prepend, appendList []any) { return } } + + // Template outbounds take tag priority (must not be altered by injected subscriptions). + usedTags := make(map[string]bool) + for _, item := range templateOutbounds { + if ob, ok := item.(map[string]any); ok { + if tag, _ := ob["tag"].(string); tag != "" { + usedTags[tag] = true + } + } + } + + prependClean := dedupeSubscriptionOutboundList(prepend, usedTags) + appendClean := dedupeSubscriptionOutboundList(appendList, usedTags) + var merged []any - merged = append(merged, prepend...) + merged = append(merged, prependClean...) merged = append(merged, templateOutbounds...) - merged = append(merged, appendList...) + merged = append(merged, appendClean...) combined, err := json.MarshalIndent(merged, "", " ") if err != nil { return diff --git a/internal/web/service/xray_config_inject_test.go b/internal/web/service/xray_config_inject_test.go index f5433d101..322a25169 100644 --- a/internal/web/service/xray_config_inject_test.go +++ b/internal/web/service/xray_config_inject_test.go @@ -1085,3 +1085,36 @@ func TestInjectAmneziawgV6Egress_OutboundBlocksPrivateEgress(t *testing.T) { } t.Fatalf("no outbound tagged %q in %s", amneziawgV6EgressTag(1, "a@x"), cfg.OutboundConfigs) } + +func TestMergeSubscriptionOutboundsDeduplicatesDuplicateTags(t *testing.T) { + cfg := &xray.Config{ + OutboundConfigs: json_util.RawMessage(`[{"tag":"direct","protocol":"freedom"}]`), + } + prepend := []any{ + map[string]any{"tag": "gh-canada-1", "protocol": "vmess"}, + } + appendList := []any{ + map[string]any{"tag": "gh-canada-1", "protocol": "vmess"}, + map[string]any{"tag": "direct", "protocol": "vmess"}, + } + mergeSubscriptionOutbounds(cfg, prepend, appendList) + + var outbounds []map[string]any + if err := json.Unmarshal(cfg.OutboundConfigs, &outbounds); err != nil { + t.Fatal(err) + } + tags := make([]string, 0, len(outbounds)) + seen := make(map[string]bool) + for _, o := range outbounds { + tag, _ := o["tag"].(string) + if seen[tag] { + t.Fatalf("found duplicate outbound tag %q in merged config: %v", tag, outbounds) + } + seen[tag] = true + tags = append(tags, tag) + } + // template tag "direct" must be preserved as "direct" + if tags[1] != "direct" { + t.Fatalf("template tag altered: %v", tags) + } +}