1
0

outbound_subscription.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database"
  14. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  15. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  16. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  17. "github.com/mhsanaei/3x-ui/v3/internal/util/link"
  18. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  19. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  20. )
  21. // filterOutboundsRejectedByCore drops outbounds the vendored xray-core config
  22. // loader refuses to build — since v26.7.11 that includes unencrypted
  23. // vless/trojan outbounds to public addresses — because one such outbound in
  24. // the merged config would keep the whole core from starting.
  25. func filterOutboundsRejectedByCore(label string, outbounds []any) ([]any, []string) {
  26. kept := make([]any, 0, len(outbounds))
  27. var dropped []string
  28. for _, ob := range outbounds {
  29. raw, err := json.Marshal(ob)
  30. if err == nil {
  31. if buildErr := xray.ValidateOutboundConfig(raw); buildErr != nil {
  32. tag := ""
  33. if m, ok := ob.(map[string]any); ok {
  34. tag, _ = m["tag"].(string)
  35. }
  36. logger.Warningf("%s: dropping outbound %q rejected by xray-core: %v", label, tag, buildErr)
  37. dropped = append(dropped, fmt.Sprintf("%s: %v", tag, buildErr))
  38. continue
  39. }
  40. }
  41. kept = append(kept, ob)
  42. }
  43. return kept, dropped
  44. }
  45. // maxOutboundSubscriptionBytes caps a single outbound subscription response.
  46. // It is larger than the 2 MiB user-facing subscription cap because an outbound
  47. // subscription may aggregate many upstream outbounds into one document.
  48. const maxOutboundSubscriptionBytes int64 = 8 << 20
  49. var errOutboundSubscriptionBodyTooLarge = errors.New("outbound subscription response body exceeds size limit")
  50. func readBoundedOutboundSubscriptionBody(r io.Reader) ([]byte, error) {
  51. body, err := io.ReadAll(io.LimitReader(r, maxOutboundSubscriptionBytes+1))
  52. if err != nil {
  53. return nil, err
  54. }
  55. if int64(len(body)) > maxOutboundSubscriptionBytes {
  56. return nil, fmt.Errorf("%w (limit: %d bytes)", errOutboundSubscriptionBodyTooLarge, maxOutboundSubscriptionBytes)
  57. }
  58. return body, nil
  59. }
  60. // OutboundSubscriptionService manages remote outbound subscriptions.
  61. type OutboundSubscriptionService struct {
  62. settingService SettingService
  63. }
  64. // NewOutboundSubscriptionService returns a service for managing outbound subscriptions.
  65. func NewOutboundSubscriptionService() *OutboundSubscriptionService {
  66. return &OutboundSubscriptionService{}
  67. }
  68. // List returns all subscriptions (newest first).
  69. func (s *OutboundSubscriptionService) List() ([]*model.OutboundSubscription, error) {
  70. db := database.GetDB()
  71. var subs []*model.OutboundSubscription
  72. if err := db.Model(&model.OutboundSubscription{}).Order("priority asc, id asc").Find(&subs).Error; err != nil {
  73. return nil, err
  74. }
  75. for _, sub := range subs {
  76. sub.OutboundCount = countOutbounds(sub.LastFetchedOutbounds)
  77. // Don't ship the heavy raw blobs to the list view.
  78. sub.LastFetchedOutbounds = ""
  79. sub.LinkIdentities = ""
  80. }
  81. return subs, nil
  82. }
  83. // countOutbounds returns the number of outbounds in a stored LastFetchedOutbounds
  84. // JSON array (0 for empty/invalid).
  85. func countOutbounds(raw string) int {
  86. if strings.TrimSpace(raw) == "" {
  87. return 0
  88. }
  89. var arr []any
  90. if json.Unmarshal([]byte(raw), &arr) != nil {
  91. return 0
  92. }
  93. return len(arr)
  94. }
  95. // Get returns a single subscription by id.
  96. func (s *OutboundSubscriptionService) Get(id int) (*model.OutboundSubscription, error) {
  97. db := database.GetDB()
  98. var sub model.OutboundSubscription
  99. if err := db.First(&sub, id).Error; err != nil {
  100. return nil, err
  101. }
  102. return &sub, nil
  103. }
  104. // Create persists a new subscription. It does not fetch immediately; the caller
  105. // can call Refresh on the returned id if desired.
  106. var defaultPrefixRe = regexp.MustCompile(`^sub(\d+)-$`)
  107. // defaultPrefixNumber returns the smallest positive integer N that is not already
  108. // in use as a "subN-" tag prefix among the given subscriptions. This is used to
  109. // auto-name a subscription's outbounds when the user leaves the prefix blank, so
  110. // deleting a subscription frees its number for reuse instead of letting the
  111. // number grow forever with the auto-increment DB id. A subscription with a blank
  112. // prefix reserves its own id (it falls back to id-based "sub<id>-" tags).
  113. func defaultPrefixNumber(subs []*model.OutboundSubscription, excludeId int) int {
  114. used := map[int]bool{}
  115. for _, sub := range subs {
  116. if sub.Id == excludeId {
  117. continue
  118. }
  119. if sub.TagPrefix == "" {
  120. used[sub.Id] = true
  121. continue
  122. }
  123. if m := defaultPrefixRe.FindStringSubmatch(sub.TagPrefix); m != nil {
  124. if n, err := strconv.Atoi(m[1]); err == nil {
  125. used[n] = true
  126. }
  127. }
  128. }
  129. n := 1
  130. for used[n] {
  131. n++
  132. }
  133. return n
  134. }
  135. // nextDefaultSubPrefix builds the default "subN-" prefix for a new/edited
  136. // subscription, picking the smallest free N (excludeId skips a subscription's
  137. // own current prefix when editing).
  138. func (s *OutboundSubscriptionService) nextDefaultSubPrefix(excludeId int) string {
  139. var subs []*model.OutboundSubscription
  140. _ = database.GetDB().Find(&subs).Error
  141. return fmt.Sprintf("sub%d-", defaultPrefixNumber(subs, excludeId))
  142. }
  143. func (s *OutboundSubscriptionService) Create(remark, rawURL, tagPrefix string, enabled bool, updateInterval int, allowPrivate, prepend bool) (*model.OutboundSubscription, error) {
  144. cleanURL, err := SanitizePublicHTTPURL(rawURL, allowPrivate)
  145. if err != nil {
  146. return nil, common.NewError("invalid subscription URL:", err)
  147. }
  148. if cleanURL == "" {
  149. return nil, common.NewError("subscription URL is required")
  150. }
  151. if updateInterval <= 0 {
  152. updateInterval = 600
  153. }
  154. prefix := strings.TrimSpace(tagPrefix)
  155. if prefix == "" {
  156. prefix = s.nextDefaultSubPrefix(0)
  157. }
  158. // New subscriptions go to the end of the priority order.
  159. var count int64
  160. database.GetDB().Model(&model.OutboundSubscription{}).Count(&count)
  161. sub := &model.OutboundSubscription{
  162. Remark: strings.TrimSpace(remark),
  163. Url: cleanURL,
  164. Enabled: enabled,
  165. AllowPrivate: allowPrivate,
  166. Prepend: prepend,
  167. Priority: int(count),
  168. TagPrefix: prefix,
  169. UpdateInterval: updateInterval,
  170. }
  171. if err := database.GetDB().Create(sub).Error; err != nil {
  172. return nil, err
  173. }
  174. return sub, nil
  175. }
  176. // Update updates editable fields.
  177. func (s *OutboundSubscriptionService) Update(id int, remark, rawURL, tagPrefix string, enabled bool, updateInterval int, allowPrivate, prepend bool) error {
  178. sub, err := s.Get(id)
  179. if err != nil {
  180. return err
  181. }
  182. cleanURL, err := SanitizePublicHTTPURL(rawURL, allowPrivate)
  183. if err != nil {
  184. return common.NewError("invalid subscription URL:", err)
  185. }
  186. if cleanURL == "" {
  187. return common.NewError("subscription URL is required")
  188. }
  189. if updateInterval <= 0 {
  190. updateInterval = 600
  191. }
  192. prefix := strings.TrimSpace(tagPrefix)
  193. if prefix == "" {
  194. prefix = s.nextDefaultSubPrefix(sub.Id)
  195. }
  196. sub.Remark = strings.TrimSpace(remark)
  197. sub.Url = cleanURL
  198. sub.Enabled = enabled
  199. sub.AllowPrivate = allowPrivate
  200. sub.Prepend = prepend
  201. sub.TagPrefix = prefix
  202. sub.UpdateInterval = updateInterval
  203. return database.GetDB().Save(sub).Error
  204. }
  205. // Delete removes a subscription.
  206. func (s *OutboundSubscriptionService) Delete(id int) error {
  207. return database.GetDB().Delete(&model.OutboundSubscription{}, id).Error
  208. }
  209. // GetLastOutbounds returns the last successfully fetched outbounds for a subscription
  210. // (as raw interface slice ready for JSON merge). Returns nil slice when none.
  211. func (s *OutboundSubscriptionService) GetLastOutbounds(id int) ([]any, error) {
  212. sub, err := s.Get(id)
  213. if err != nil {
  214. return nil, err
  215. }
  216. if strings.TrimSpace(sub.LastFetchedOutbounds) == "" {
  217. return nil, nil
  218. }
  219. var arr []any
  220. if err := json.Unmarshal([]byte(sub.LastFetchedOutbounds), &arr); err != nil {
  221. return nil, err
  222. }
  223. return arr, nil
  224. }
  225. // Refresh fetches the subscription URL, parses the links, assigns stable tags,
  226. // persists the results, and returns the generated outbounds.
  227. func (s *OutboundSubscriptionService) Refresh(id int) ([]any, error) {
  228. sub, err := s.Get(id)
  229. if err != nil {
  230. return nil, err
  231. }
  232. outbounds, err := s.fetchAndStore(sub)
  233. return outbounds, err
  234. }
  235. // RefreshAllEnabled fetches every enabled subscription whose due time has passed
  236. // (lastUpdated + updateInterval <= now). It returns the number of subscriptions
  237. // that were actually refreshed.
  238. func (s *OutboundSubscriptionService) RefreshAllEnabled() (int, error) {
  239. db := database.GetDB()
  240. var subs []*model.OutboundSubscription
  241. if err := db.Where("enabled = ?", true).Find(&subs).Error; err != nil {
  242. return 0, err
  243. }
  244. now := time.Now().Unix()
  245. refreshed := 0
  246. for _, sub := range subs {
  247. due := sub.LastUpdated + int64(sub.UpdateInterval)
  248. if sub.LastUpdated == 0 || due <= now {
  249. if _, err := s.fetchAndStore(sub); err != nil {
  250. logger.Warningf("outbound sub %d (%s) refresh failed: %v", sub.Id, sub.Remark, err)
  251. // continue with others
  252. } else {
  253. refreshed++
  254. }
  255. }
  256. }
  257. return refreshed, nil
  258. }
  259. // subscriptionFetchClient builds the HTTP client used to fetch a subscription.
  260. // A configured panel egress proxy dials the loopback SOCKS bridge (xray handles
  261. // the real egress), so its localhost dial must not be SSRF-blocked. A direct
  262. // fetch dials the target itself and re-resolves the hostname at dial time, so it
  263. // goes through the SSRF-guarded dialer, which resolves, checks and dials the same
  264. // IP atomically — closing the DNS-rebinding gap left by validating the hostname
  265. // separately from the dial.
  266. func (s *OutboundSubscriptionService) subscriptionFetchClient(timeout time.Duration) *http.Client {
  267. if s.settingService.PanelEgressProxyURL() != "" {
  268. return s.settingService.NewProxiedHTTPClient(timeout)
  269. }
  270. return &http.Client{
  271. Timeout: timeout,
  272. Transport: &http.Transport{DialContext: netsafe.SSRFGuardedDialContext},
  273. }
  274. }
  275. // fetchAndStore does the actual network + parse + stability + persist work.
  276. func (s *OutboundSubscriptionService) fetchAndStore(sub *model.OutboundSubscription) ([]any, error) {
  277. // Re-sanitize on every fetch (handles legacy rows + defense in depth against
  278. // any direct DB tampering). Private targets are blocked unless this
  279. // subscription was explicitly created with AllowPrivate.
  280. cleanURL, err := SanitizePublicHTTPURL(sub.Url, sub.AllowPrivate)
  281. if err != nil {
  282. s.recordError(sub, err)
  283. return nil, err
  284. }
  285. if cleanURL == "" {
  286. return nil, common.NewError("subscription has no valid URL")
  287. }
  288. sub.Url = cleanURL // persist the cleaned version
  289. client := s.subscriptionFetchClient(30 * time.Second)
  290. // Re-validate every redirect hop: the initial host is checked above, but a
  291. // redirect could still point at a private/internal address (SSRF). Cap the
  292. // redirect chain as well.
  293. client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  294. if len(via) >= 10 {
  295. return fmt.Errorf("stopped after 10 redirects")
  296. }
  297. if sub.AllowPrivate {
  298. return nil
  299. }
  300. ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second)
  301. defer cancel()
  302. return rejectPrivateHost(ctx, req.URL.Hostname())
  303. }
  304. reqCtx := netsafe.ContextWithAllowPrivate(context.Background(), sub.AllowPrivate)
  305. req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, sub.Url, nil)
  306. if err != nil {
  307. s.recordError(sub, err)
  308. return nil, err
  309. }
  310. req.Header.Set("User-Agent", "3x-ui-outbound-sub/1.0")
  311. resp, err := client.Do(req)
  312. if err != nil {
  313. s.recordError(sub, err)
  314. return nil, err
  315. }
  316. defer resp.Body.Close()
  317. if resp.StatusCode != http.StatusOK {
  318. err := fmt.Errorf("http %d", resp.StatusCode)
  319. s.recordError(sub, err)
  320. return nil, err
  321. }
  322. body, err := readBoundedOutboundSubscriptionBody(resp.Body)
  323. if err != nil {
  324. s.recordError(sub, err)
  325. return nil, err
  326. }
  327. parsed, identities, err := link.ParseSubscriptionBody(body)
  328. if err != nil {
  329. s.recordError(sub, err)
  330. return nil, err
  331. }
  332. // Load previous identities -> tags for stability
  333. prev := map[string]string{}
  334. if strings.TrimSpace(sub.LinkIdentities) != "" {
  335. _ = json.Unmarshal([]byte(sub.LinkIdentities), &prev)
  336. }
  337. // Also load previous outbounds so we can reuse tags even for identities we
  338. // temporarily lost (defensive).
  339. prevTagByIndex := map[int]string{}
  340. if strings.TrimSpace(sub.LastFetchedOutbounds) != "" {
  341. var prevObs []any
  342. if json.Unmarshal([]byte(sub.LastFetchedOutbounds), &prevObs) == nil {
  343. for i, o := range prevObs {
  344. if m, ok := o.(map[string]any); ok {
  345. if tag, _ := m["tag"].(string); tag != "" {
  346. prevTagByIndex[i] = tag
  347. }
  348. }
  349. }
  350. }
  351. }
  352. // Assign tags with stability (identity reuse, positional fallback, then a
  353. // fresh allocation), keeping tags unique within this batch. Extracted into a
  354. // pure function so it can be unit-tested without network/DB. Tags are written
  355. // back into the parsed outbounds in place.
  356. assigned := assignStableTags(parsed, identities, prev, prevTagByIndex, sub.Id, sub.TagPrefix)
  357. // Persist identities for next time
  358. newIdent := map[string]string{}
  359. for i, id := range identities {
  360. newIdent[id] = assigned[i]
  361. }
  362. identJSON, _ := json.Marshal(newIdent)
  363. asAny := make([]any, len(parsed))
  364. for i := range parsed {
  365. asAny[i] = map[string]any(parsed[i])
  366. }
  367. kept, droppedByCore := filterOutboundsRejectedByCore(fmt.Sprintf("outbound sub %d", sub.Id), asAny)
  368. // Persist the outbounds (as compact JSON array)
  369. obsJSON, _ := json.Marshal(kept)
  370. sub.LastFetchedOutbounds = string(obsJSON)
  371. sub.LinkIdentities = string(identJSON)
  372. sub.LastUpdated = time.Now().Unix()
  373. sub.LastError = ""
  374. if len(droppedByCore) > 0 {
  375. sub.LastError = fmt.Sprintf("dropped %d outbound(s) the xray core rejects: %s", len(droppedByCore), droppedByCore[0])
  376. }
  377. if err := database.GetDB().Save(sub).Error; err != nil {
  378. return nil, err
  379. }
  380. return kept, nil
  381. }
  382. func (s *OutboundSubscriptionService) recordError(sub *model.OutboundSubscription, err error) {
  383. sub.LastError = err.Error()
  384. _ = database.GetDB().Model(sub).Update("last_error", sub.LastError).Error
  385. }
  386. // assignStableTags assigns a tag to each parsed outbound, preferring stability:
  387. // 1. reuse the tag previously mapped to the link's identity (prev),
  388. // 2. else reuse the tag at the same position from the last fetch (prevTagByIndex),
  389. // 3. else allocate a fresh tag from the prefix + remark (link.SuggestTag).
  390. //
  391. // Tags are kept unique within the batch by appending "-N" on collision, and are
  392. // written back into parsed[i]["tag"]. The returned slice holds the assigned tags
  393. // in order. When tagPrefix is empty a "sub<subID>-" prefix is used for fresh tags.
  394. func assignStableTags(parsed []link.Outbound, identities []string, prev map[string]string, prevTagByIndex map[int]string, subID int, tagPrefix string) []string {
  395. used := map[string]bool{} // uniqueness within this refresh batch
  396. assigned := make([]string, len(parsed))
  397. for i := range parsed {
  398. id := ""
  399. if i < len(identities) {
  400. id = identities[i]
  401. }
  402. candidate := ""
  403. if old, ok := prev[id]; ok && old != "" {
  404. candidate = old
  405. }
  406. if candidate == "" {
  407. // try to reuse by rough positional match from previous fetch (best effort)
  408. if old, ok := prevTagByIndex[i]; ok && old != "" {
  409. candidate = old
  410. }
  411. }
  412. if candidate == "" {
  413. // fresh allocation
  414. prefix := tagPrefix
  415. if prefix == "" {
  416. prefix = fmt.Sprintf("sub%d-", subID)
  417. }
  418. remark := ""
  419. if m, ok := parsed[i]["tag"].(string); ok {
  420. remark = m
  421. }
  422. candidate = link.SuggestTag(prefix, remark, i)
  423. }
  424. // ensure local uniqueness inside this batch
  425. final := candidate
  426. for k := 1; used[final]; k++ {
  427. final = fmt.Sprintf("%s-%d", candidate, k)
  428. }
  429. used[final] = true
  430. assigned[i] = final
  431. // write back the tag into the outbound
  432. parsed[i]["tag"] = final
  433. }
  434. return assigned
  435. }
  436. // AllActiveOutbounds returns the concatenation of the last-fetched outbounds
  437. // for every enabled subscription. This is the set that should be merged into
  438. // the final Xray config. Order: subscription creation order (by id asc) so
  439. // that later subscriptions can shadow earlier ones if the admin uses colliding
  440. // prefixes (last writer wins inside xray, but we try to keep tags unique).
  441. func (s *OutboundSubscriptionService) AllActiveOutbounds() ([]any, error) {
  442. prepend, appendList, err := s.activeOutboundsSplit()
  443. if err != nil {
  444. return nil, err
  445. }
  446. return append(prepend, appendList...), nil
  447. }
  448. // activeOutboundsSplit returns the active subscription outbounds split into those
  449. // that should be placed BEFORE the manual template outbounds (Prepend) and those
  450. // placed AFTER. Within each group, subscriptions are ordered by Priority (then id)
  451. // so the admin can control the merged order.
  452. func (s *OutboundSubscriptionService) activeOutboundsSplit() (prepend []any, appendList []any, err error) {
  453. db := database.GetDB()
  454. var subs []*model.OutboundSubscription
  455. if err := db.Where("enabled = ?", true).Order("priority asc, id asc").Find(&subs).Error; err != nil {
  456. return nil, nil, err
  457. }
  458. for _, sub := range subs {
  459. if strings.TrimSpace(sub.LastFetchedOutbounds) == "" {
  460. continue
  461. }
  462. var arr []any
  463. if err := json.Unmarshal([]byte(sub.LastFetchedOutbounds), &arr); err != nil {
  464. logger.Warningf("outbound sub %d has corrupt LastFetchedOutbounds: %v", sub.Id, err)
  465. continue
  466. }
  467. arr, _ = filterOutboundsRejectedByCore(fmt.Sprintf("outbound sub %d", sub.Id), arr)
  468. if sub.Prepend {
  469. prepend = append(prepend, arr...)
  470. } else {
  471. appendList = append(appendList, arr...)
  472. }
  473. }
  474. return prepend, appendList, nil
  475. }
  476. // Move shifts a subscription one step up or down in the priority order and
  477. // re-normalizes all priorities to a 0..n-1 sequence.
  478. func (s *OutboundSubscriptionService) Move(id int, up bool) error {
  479. db := database.GetDB()
  480. var subs []*model.OutboundSubscription
  481. if err := db.Order("priority asc, id asc").Find(&subs).Error; err != nil {
  482. return err
  483. }
  484. idx := -1
  485. for i, sub := range subs {
  486. if sub.Id == id {
  487. idx = i
  488. break
  489. }
  490. }
  491. if idx == -1 {
  492. return common.NewError("subscription not found")
  493. }
  494. swap := idx + 1
  495. if up {
  496. swap = idx - 1
  497. }
  498. if swap < 0 || swap >= len(subs) {
  499. return nil // already at the edge
  500. }
  501. subs[idx], subs[swap] = subs[swap], subs[idx]
  502. for i, sub := range subs {
  503. if sub.Priority != i {
  504. if err := db.Model(sub).Update("priority", i).Error; err != nil {
  505. return err
  506. }
  507. }
  508. }
  509. return nil
  510. }
  511. // AllActiveOutboundTags returns only the tags of active subscription outbounds.
  512. // Useful for populating balancer / routing selectors without shipping full objects.
  513. func (s *OutboundSubscriptionService) AllActiveOutboundTags() ([]string, error) {
  514. obs, err := s.AllActiveOutbounds()
  515. if err != nil {
  516. return nil, err
  517. }
  518. tags := make([]string, 0, len(obs))
  519. for _, o := range obs {
  520. if m, ok := o.(map[string]any); ok {
  521. if t, _ := m["tag"].(string); t != "" {
  522. tags = append(tags, t)
  523. }
  524. }
  525. }
  526. return tags, nil
  527. }
  528. /*
  529. Tag stability strategy (important for balancers and routing rules)
  530. When a subscription is refreshed we try very hard to keep the *same* tag for the
  531. same logical outbound so that existing balancers and routing rules keep working.
  532. How we do it:
  533. - On every successful parse we compute a stable "identity" for each link
  534. (the core of the URI with the remark fragment removed, or for vmess the inner
  535. JSON without the "ps" field).
  536. - We persist a map identity -> tag in the LinkIdentities column.
  537. - On the next refresh, if we see the same identity again we reuse the previous tag,
  538. even if the remark changed or minor parameters moved.
  539. - Only when we have never seen the identity before do we allocate a fresh tag
  540. using the user-supplied TagPrefix + slug(remark) (or an index fallback).
  541. - Within one refresh we still deduplicate with -N suffixes.
  542. Consequences for balancers / routing:
  543. - If you use an *exact* tag in a balancer selector or a routing rule, that
  544. specific server will continue to be used after refreshes (as long as the
  545. provider still returns a link that produces the same identity).
  546. - If you use a *prefix/wildcard* selector (e.g. "hk-*", "sg-.*"), then any
  547. *new* servers that the subscription later returns will automatically be
  548. eligible for that balancer on the next Xray reload — this is the recommended
  549. way to "subscribe to a pool".
  550. - When a server disappears from the subscription, its tag simply stops
  551. existing in the final outbounds array. The balancer will have fewer
  552. candidates. If you configured a `fallbackTag` on the balancer, Xray will use
  553. it. Otherwise connections that would have used the missing member may fail
  554. or be routed by the next rule.
  555. - If the provider rotates credentials/UUIDs/hosts for a server, the identity
  556. changes → we treat it as a brand new outbound and give it a new tag. Any
  557. balancer/rule that referenced the *old* tag will no longer see it. This is
  558. an inherent limitation of subscription-based outbounds.
  559. We deliberately do *not* mutate the saved xrayTemplateConfig. Subscription
  560. outbounds are always injected at runtime in GetXrayConfig.
  561. */