fix(subscriptions): avoid shared mutable state during generation (#5270)

* fix(subscriptions): avoid shared mutable state during generation

* fix(subscriptions): serve external-link-only subs in JSON/Clash; load remark settings per request

The ForRequest refactor added an early `len(inbounds) == 0` return to
GetJson/GetClash that fired before external links were fetched, so a
subscription whose only entries are external links (or whose inbounds are
all disabled) rendered empty in the JSON and Clash formats. Drop the
premature check — the existing inbounds+externalLinks empty guard already
covers the truly-empty case.

Also load datepicker/emailInRemark in PrepareForRequest rather than only in
getSubs, so JSON and Clash remarks honor these settings instead of seeing
the zero values (emailInRemark previously depended on the shared-state leak
this PR fixes).

Add a regression test covering an external-link-only sub across both formats.

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
This commit is contained in:
n0ctalandSanaei authored and GitHub committed 2026-06-15 16:23:47 +02:00 Unverified
1 parent 71616b7cf2
commit ac8cb505d1
7 files changed
+139 -52

No files matched your search

+21
View File
@@ -70,6 +70,27 @@ func TestBuildURLs_EmptySubId(t *testing.T) {
}
}
func TestForRequestDoesNotMutateSharedService(t *testing.T) {
initSubDB(t)
base := &SubService{}
first := base.ForRequest("first.example.com")
second := base.ForRequest("second.example.com")
if base.address != "" || base.nodesByID != nil {
t.Fatalf("ForRequest mutated the shared service: address=%q nodes=%v", base.address, base.nodesByID)
}
firstURL, _, _ := first.BuildURLs("/sub/", "/json/", "/clash/", "ABC")
secondURL, _, _ := second.BuildURLs("/sub/", "/json/", "/clash/", "ABC")
if !strings.Contains(firstURL, "first.example.com") {
t.Fatalf("first request URL = %q, want first.example.com", firstURL)
}
if !strings.Contains(secondURL, "second.example.com") {
t.Fatalf("second request URL = %q, want second.example.com", secondURL)
}
}
// A subscriber arriving via a reverse proxy (subURI configured with full
// HTTPS URL) must see the same scheme+host in the JSON and Clash Copy
// URLs as in the main subURL — not the raw sub-server port 2096.
+15 -16
View File
@@ -22,13 +22,12 @@ func NewSubClashService(enableRouting bool, clashRules string, subService *SubSe
}
func (s *SubClashService) GetClash(subId string, host string) (string, string, error) {
// Set per-request state so resolveInboundAddress sees the node map.
s.SubService.PrepareForRequest(host)
inbounds, err := s.SubService.getInboundsBySubId(subId)
subReq := s.SubService.ForRequest(host)
inbounds, err := subReq.getInboundsBySubId(subId)
if err != nil {
return "", "", err
}
externalLinks, err := s.SubService.getClientExternalLinksBySubId(subId)
externalLinks, err := subReq.getClientExternalLinksBySubId(subId)
if err != nil {
return "", "", err
}
@@ -40,14 +39,14 @@ func (s *SubClashService) GetClash(subId string, host string) (string, string, e
seenEmails := make(map[string]struct{})
for _, inbound := range inbounds {
clients := s.SubService.matchingClients(inbound, subId)
clients := subReq.matchingClients(inbound, subId)
if len(clients) == 0 {
continue
}
s.SubService.projectThroughFallbackMaster(inbound)
subReq.projectThroughFallbackMaster(inbound)
for _, client := range clients {
seenEmails[client.Email] = struct{}{}
proxies = append(proxies, s.getProxies(inbound, client, host)...)
proxies = append(proxies, s.getProxies(subReq, inbound, client, host)...)
}
}
for _, ext := range externalLinks {
@@ -73,7 +72,7 @@ func (s *SubClashService) GetClash(subId string, host string) (string, string, e
for e := range seenEmails {
emails = append(emails, e)
}
traffic, _ := s.SubService.AggregateTrafficByEmails(emails)
traffic, _ := subReq.AggregateTrafficByEmails(emails)
proxyNames := make([]string, 0, len(proxies)+1)
for _, proxy := range proxies {
@@ -140,12 +139,12 @@ func fallbackProxyName(proxy map[string]any, idx int) string {
return fmt.Sprintf("proxy-%d", idx+1)
}
func (s *SubClashService) getProxies(inbound *model.Inbound, client model.Client, host string) []map[string]any {
func (s *SubClashService) getProxies(subReq *SubService, inbound *model.Inbound, client model.Client, host string) []map[string]any {
stream := s.streamData(inbound.StreamSettings)
// For node-managed inbounds the Clash proxy "server" must be the
// node's address, not the request host. resolveInboundAddress handles
// the node→subscriber-host fallback chain.
defaultDest := s.SubService.resolveInboundAddress(inbound)
defaultDest := subReq.resolveInboundAddress(inbound)
if defaultDest == "" {
defaultDest = host
}
@@ -187,7 +186,7 @@ func (s *SubClashService) getProxies(inbound *model.Inbound, client model.Client
applyExternalProxyTLSToStream(extPrxy, workingStream, security)
}
proxy := s.buildProxy(&workingInbound, client, workingStream, extPrxy["remark"].(string))
proxy := s.buildProxy(subReq, &workingInbound, client, workingStream, extPrxy["remark"].(string))
if len(proxy) > 0 {
proxies = append(proxies, proxy)
}
@@ -195,15 +194,15 @@ func (s *SubClashService) getProxies(inbound *model.Inbound, client model.Client
return proxies
}
func (s *SubClashService) buildProxy(inbound *model.Inbound, client model.Client, stream map[string]any, extraRemark string) map[string]any {
func (s *SubClashService) buildProxy(subReq *SubService, inbound *model.Inbound, client model.Client, stream map[string]any, extraRemark string) map[string]any {
// Hysteria has its own transport + TLS model, applyTransport /
// applySecurity don't fit.
if inbound.Protocol == model.Hysteria {
return s.buildHysteriaProxy(inbound, client, extraRemark)
return s.buildHysteriaProxy(subReq, inbound, client, extraRemark)
}
proxy := map[string]any{
"name": s.SubService.genRemark(inbound, client.Email, extraRemark),
"name": subReq.genRemark(inbound, client.Email, extraRemark),
"server": inbound.Listen,
"port": inbound.Port,
"udp": true,
@@ -274,7 +273,7 @@ func (s *SubClashService) buildProxy(inbound *model.Inbound, client model.Client
// directly instead of going through streamData/tlsData, because those
// helpers prune fields (like `allowInsecure` / the salamander obfs
// block) that the hysteria proxy wants preserved.
func (s *SubClashService) buildHysteriaProxy(inbound *model.Inbound, client model.Client, extraRemark string) map[string]any {
func (s *SubClashService) buildHysteriaProxy(subReq *SubService, inbound *model.Inbound, client model.Client, extraRemark string) map[string]any {
var inboundSettings map[string]any
_ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
@@ -286,7 +285,7 @@ func (s *SubClashService) buildHysteriaProxy(inbound *model.Inbound, client mode
}
proxy := map[string]any{
"name": s.SubService.genRemark(inbound, client.Email, extraRemark),
"name": subReq.genRemark(inbound, client.Email, extraRemark),
"type": proxyType,
"server": inbound.Listen,
"port": inbound.Port,
+5 -5
View File
@@ -56,7 +56,7 @@ func TestBuildProxy_VLESSRealityFieldsForClash(t *testing.T) {
"realitySettings": map[string]any{"serverName": "reality.example.com", "publicKey": "PBKvalue", "shortId": "ab12", "fingerprint": "chrome"},
}
proxy := svc.buildProxy(inbound, client, stream, "")
proxy := svc.buildProxy(svc.SubService, inbound, client, stream, "")
if proxy == nil {
t.Fatal("buildProxy returned nil for a valid reality stream")
}
@@ -199,7 +199,7 @@ func TestBuildProxy_VLESSPostQuantumEncryptionUsesMihomoEncryptionField(t *testi
},
}
proxy := svc.buildProxy(inbound, client, stream, "")
proxy := svc.buildProxy(svc.SubService, inbound, client, stream, "")
if proxy["encryption"] != encryption {
t.Fatalf("encryption = %v, want %q", proxy["encryption"], encryption)
@@ -231,7 +231,7 @@ func TestBuildProxy_VLESSFlowXhttpRealityVlessenc(t *testing.T) {
},
}
proxy := svc.buildProxy(inbound, client, stream, "")
proxy := svc.buildProxy(svc.SubService, inbound, client, stream, "")
if proxy["flow"] != "xtls-rprx-vision" {
t.Fatalf("xhttp+reality+vlessenc Clash proxy must carry the vision flow (#5232): %#v", proxy)
@@ -256,7 +256,7 @@ func TestBuildProxy_VLESSFlowDroppedWithoutVisionSupport(t *testing.T) {
},
}
proxy := svc.buildProxy(inbound, client, stream, "")
proxy := svc.buildProxy(svc.SubService, inbound, client, stream, "")
if _, ok := proxy["flow"]; ok {
t.Fatalf("tcp without tls/reality must not carry a flow: %#v", proxy)
@@ -281,7 +281,7 @@ func TestBuildProxy_VLESSNoneEncryptionOmittedForClash(t *testing.T) {
},
}
proxy := svc.buildProxy(inbound, client, stream, "")
proxy := svc.buildProxy(svc.SubService, inbound, client, stream, "")
if _, ok := proxy["encryption"]; ok {
t.Fatalf("plain vless encryption should be omitted for mihomo: %#v", proxy)
Loaded 3 of 7 files, more files were not shown because too many files have changed in this diff. Show more