json_service.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  1. package sub
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "fmt"
  6. "maps"
  7. "net/url"
  8. "slices"
  9. "sort"
  10. "strings"
  11. "sync"
  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/json_util"
  17. "github.com/mhsanaei/3x-ui/v3/internal/util/maskcompat"
  18. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  19. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  20. )
  21. //go:embed default.json
  22. var defaultJson string
  23. // SubJsonService handles JSON subscription configuration generation and management.
  24. type SubJsonService struct {
  25. configJson map[string]any
  26. defaultOutbounds []json_util.RawMessage
  27. finalMask string
  28. mux string
  29. observatory subBalancerObservatoryConfig
  30. // bakedRouting is re-resolved per request: a remote URL may be cold at
  31. // construction time and warm up later via the cron job.
  32. routingRules string
  33. bakedRoutingMu sync.Mutex
  34. bakedRouting *bakedRoutingState
  35. // dnsBlock is the panel DNS override, fixed for the service's lifetime.
  36. dnsBlock map[string]any
  37. SubService *SubService
  38. }
  39. type bakedRoutingState struct {
  40. spec jsonRoutingSpec
  41. configJson map[string]any
  42. }
  43. // NewSubJsonService creates a new JSON subscription service with the given configuration.
  44. func NewSubJsonService(mux string, rules string, finalMask string, routingRules string, subService *SubService) *SubJsonService {
  45. var configJson map[string]any
  46. var defaultOutbounds []json_util.RawMessage
  47. _ = json.Unmarshal([]byte(defaultJson), &configJson)
  48. if outboundSlices, ok := configJson["outbounds"].([]any); ok {
  49. for _, defaultOutbound := range outboundSlices {
  50. jsonBytes, _ := json.Marshal(defaultOutbound)
  51. defaultOutbounds = append(defaultOutbounds, jsonBytes)
  52. }
  53. }
  54. // A baked routing profile replaces the template's dns and routing subtrees
  55. // outright; the legacy simple-rules setting only applies without a profile.
  56. if routingRules == "" && rules != "" {
  57. var newRules []any
  58. routing, _ := configJson["routing"].(map[string]any)
  59. defaultRules, _ := routing["rules"].([]any)
  60. _ = json.Unmarshal([]byte(rules), &newRules)
  61. defaultRules = append(newRules, defaultRules...)
  62. routing["rules"] = defaultRules
  63. configJson["routing"] = routing
  64. }
  65. return &SubJsonService{
  66. configJson: configJson,
  67. defaultOutbounds: defaultOutbounds,
  68. finalMask: finalMask,
  69. mux: mux,
  70. routingRules: routingRules,
  71. observatory: defaultSubBalancerObservatoryConfig(),
  72. SubService: subService,
  73. }
  74. }
  75. // Re-resolved per call so an upstream edit reaches the documents without a
  76. // restart; a failed resolve keeps the last good template.
  77. func (s *SubJsonService) bakedTemplate() map[string]any {
  78. if s.routingRules == "" && s.dnsBlock == nil {
  79. return s.configJson
  80. }
  81. spec := resolveJsonRoutingSpec(s.routingRules)
  82. s.bakedRoutingMu.Lock()
  83. defer s.bakedRoutingMu.Unlock()
  84. if s.bakedRouting != nil {
  85. if spec.empty() || spec.equal(s.bakedRouting.spec) {
  86. return s.bakedRouting.configJson
  87. }
  88. } else if spec.empty() && s.dnsBlock == nil {
  89. return s.configJson
  90. }
  91. template := make(map[string]any, len(s.configJson)+2)
  92. maps.Copy(template, s.configJson)
  93. if !spec.empty() {
  94. applyJsonRouting(template, spec)
  95. }
  96. // The panel-level DNS block is an explicit choice, so it also replaces the
  97. // dns subtree a routing profile would otherwise bake in.
  98. if s.dnsBlock != nil {
  99. template["dns"] = s.dnsBlock
  100. }
  101. s.bakedRouting = &bakedRoutingState{spec: spec, configJson: template}
  102. return template
  103. }
  104. // GetJson generates a JSON subscription configuration for the given subscription ID and host.
  105. func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bool) (string, string, error) {
  106. subReq := s.SubService.ForRequest(host)
  107. subReq.subscriptionBody = true
  108. inbounds, err := subReq.getInboundsBySubId(subId)
  109. if err != nil {
  110. return "", "", err
  111. }
  112. externalLinks, err := subReq.getClientExternalLinksBySubId(subId)
  113. if err != nil {
  114. return "", "", err
  115. }
  116. if len(inbounds) == 0 && len(externalLinks) == 0 {
  117. return "", "", nil
  118. }
  119. var header string
  120. var hasInactiveExternal bool
  121. var hasEnabledClient bool
  122. seenEmails := make(map[string]struct{})
  123. entries := make([]subConfigEntry, 0, len(inbounds))
  124. // Prepare Inbounds
  125. for _, inbound := range inbounds {
  126. clients := subReq.matchingClients(inbound, subId)
  127. if len(clients) == 0 {
  128. continue
  129. }
  130. if inbound.ExcludeFromSub {
  131. if countHiddenClients(clients, seenEmails) {
  132. hasEnabledClient = true
  133. }
  134. continue
  135. }
  136. subReq.projectThroughFallbackMaster(inbound)
  137. if hostEps := subReq.hostEndpoints(inbound, "json"); len(hostEps) > 0 {
  138. injectExternalProxy(inbound, hostEps)
  139. }
  140. var inboundConfigs []json_util.RawMessage
  141. for _, client := range clients {
  142. if client.Enable {
  143. hasEnabledClient = true
  144. }
  145. seenEmails[client.Email] = struct{}{}
  146. inboundConfigs = append(inboundConfigs, s.getConfig(subReq, inbound, client, host)...)
  147. }
  148. if len(inboundConfigs) > 0 {
  149. entries = append(entries, subConfigEntry{
  150. sortIndex: inbound.SubSortIndex,
  151. id: inbound.Id,
  152. configs: inboundConfigs,
  153. })
  154. }
  155. }
  156. entries = s.appendBalancerEntries(entries)
  157. // Inbounds arrive sorted by (sub_sort_index, id); balancers interleave by
  158. // the same key and, on an equal number, follow the inbound group.
  159. sort.SliceStable(entries, func(i, j int) bool {
  160. if entries[i].sortIndex != entries[j].sortIndex {
  161. return entries[i].sortIndex < entries[j].sortIndex
  162. }
  163. if entries[i].kind != entries[j].kind {
  164. return entries[i].kind < entries[j].kind
  165. }
  166. return entries[i].id < entries[j].id
  167. })
  168. var configArray []json_util.RawMessage
  169. for _, entry := range entries {
  170. configArray = append(configArray, entry.configs...)
  171. }
  172. for _, ext := range externalLinks {
  173. if ext.Enable {
  174. hasEnabledClient = true
  175. }
  176. if !ext.Active {
  177. seenEmails[ext.Email] = struct{}{}
  178. hasInactiveExternal = true
  179. continue
  180. }
  181. for _, el := range expandEntry(ext) {
  182. outbound := parsedExternalOutbound(el.Link)
  183. if outbound == nil {
  184. continue
  185. }
  186. seenEmails[ext.Email] = struct{}{}
  187. remark := el.Name
  188. if remark == "" {
  189. remark = ext.Email
  190. }
  191. newOutbounds := []json_util.RawMessage{outbound}
  192. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  193. newConfigJson := make(map[string]any)
  194. maps.Copy(newConfigJson, s.bakedTemplate())
  195. newConfigJson["outbounds"] = newOutbounds
  196. newConfigJson["remarks"] = remark
  197. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  198. configArray = append(configArray, newConfig)
  199. }
  200. }
  201. if len(configArray) == 0 && !hasInactiveExternal {
  202. return "", "", nil
  203. }
  204. emails := make([]string, 0, len(seenEmails))
  205. for e := range seenEmails {
  206. emails = append(emails, e)
  207. }
  208. slices.Sort(emails)
  209. traffic, _ := subReq.AggregateTrafficByEmails(emails)
  210. traffic.Enable = hasEnabledClient
  211. header = subReq.subscriptionUserinfo(traffic)
  212. if mode, remark := subReq.resolveInfoNodeRemark(subId, emails, traffic, len(configArray) > 0); mode != infoNodeNone {
  213. dummyConfig := s.genDummySocksConfig(remark)
  214. if mode == infoNodeExpired || mode == infoNodeDepleted {
  215. configArray = []json_util.RawMessage{dummyConfig}
  216. } else {
  217. configArray = append([]json_util.RawMessage{dummyConfig}, configArray...)
  218. }
  219. }
  220. if len(configArray) == 0 {
  221. return "", header, nil
  222. }
  223. var finalJson []byte
  224. if len(configArray) == 1 && !alwaysReturnArray {
  225. finalJson, _ = json.MarshalIndent(configArray[0], "", " ")
  226. } else {
  227. finalJson, _ = json.MarshalIndent(configArray, "", " ")
  228. }
  229. return string(finalJson), header, nil
  230. }
  231. // subConfigEntry is one ordered block of the JSON subscription: an inbound's
  232. // configs (kind 0) or a balancer config (kind 1).
  233. type subConfigEntry struct {
  234. sortIndex int
  235. kind int
  236. id int
  237. configs []json_util.RawMessage
  238. }
  239. const (
  240. subBalancerTag = "balancer"
  241. subBalancerProbeURL = "https://www.google.com/generate_204"
  242. )
  243. // subBalancerObservatoryConfig is the panel-wide burstObservatory ping config
  244. // emitted into every client-side balancer doc (subJsonObservatory setting).
  245. type subBalancerObservatoryConfig struct {
  246. Destination string `json:"destination"`
  247. Connectivity string `json:"connectivity"`
  248. Interval string `json:"interval"`
  249. Sampling int `json:"sampling"`
  250. Timeout string `json:"timeout"`
  251. HTTPMethod string `json:"httpMethod"`
  252. }
  253. func defaultSubBalancerObservatoryConfig() subBalancerObservatoryConfig {
  254. return subBalancerObservatoryConfig{
  255. Destination: subBalancerProbeURL,
  256. Connectivity: "",
  257. Interval: "1m",
  258. Sampling: 2,
  259. Timeout: "5s",
  260. HTTPMethod: "HEAD",
  261. }
  262. }
  263. // SetObservatoryConfig overrides defaults from the panel JSON setting. An empty
  264. // cfg keeps all defaults; invalid values fall back with a warning, never panic.
  265. func (s *SubJsonService) SetObservatoryConfig(cfg string) {
  266. s.observatory = defaultSubBalancerObservatoryConfig()
  267. if cfg == "" {
  268. return
  269. }
  270. var parsed subBalancerObservatoryConfig
  271. if err := json.Unmarshal([]byte(cfg), &parsed); err != nil {
  272. logger.Warningf("subJsonObservatory: invalid JSON %q, using defaults: %v", cfg, err)
  273. return
  274. }
  275. if parsed.Destination != "" {
  276. if validProbeURL(parsed.Destination) {
  277. s.observatory.Destination = parsed.Destination
  278. } else {
  279. logger.Warningf("subJsonObservatory: invalid destination %q, keeping default %q", parsed.Destination, s.observatory.Destination)
  280. }
  281. }
  282. if parsed.Connectivity != "" {
  283. if validProbeURL(parsed.Connectivity) {
  284. s.observatory.Connectivity = parsed.Connectivity
  285. } else {
  286. logger.Warningf("subJsonObservatory: invalid connectivity %q, keeping default (skip)", parsed.Connectivity)
  287. }
  288. }
  289. if parsed.Interval != "" {
  290. if _, err := time.ParseDuration(parsed.Interval); err == nil {
  291. s.observatory.Interval = parsed.Interval
  292. } else {
  293. logger.Warningf("subJsonObservatory: invalid interval %q, keeping default %q", parsed.Interval, s.observatory.Interval)
  294. }
  295. }
  296. if parsed.Sampling > 0 {
  297. s.observatory.Sampling = parsed.Sampling
  298. }
  299. if parsed.Timeout != "" {
  300. if _, err := time.ParseDuration(parsed.Timeout); err == nil {
  301. s.observatory.Timeout = parsed.Timeout
  302. } else {
  303. logger.Warningf("subJsonObservatory: invalid timeout %q, keeping default %q", parsed.Timeout, s.observatory.Timeout)
  304. }
  305. }
  306. if parsed.HTTPMethod == "HEAD" || parsed.HTTPMethod == "GET" {
  307. s.observatory.HTTPMethod = parsed.HTTPMethod
  308. }
  309. }
  310. // validProbeURL accepts only absolute http(s) URLs so a malformed probe or
  311. // connectivity value can't slip into the emitted burstObservatory.
  312. func validProbeURL(s string) bool {
  313. u, err := url.Parse(s)
  314. if err != nil || u == nil {
  315. return false
  316. }
  317. return u.Scheme == "http" || u.Scheme == "https"
  318. }
  319. func (s *SubJsonService) balancerObservatory(prefix string) map[string]any {
  320. o := s.observatory
  321. return map[string]any{
  322. "subjectSelector": []string{prefix},
  323. "pingConfig": map[string]any{
  324. "destination": o.Destination,
  325. "connectivity": o.Connectivity,
  326. "interval": o.Interval,
  327. "sampling": o.Sampling,
  328. "timeout": o.Timeout,
  329. "httpMethod": o.HTTPMethod,
  330. },
  331. }
  332. }
  333. // appendBalancerEntries appends one entry per enabled balancer that has at
  334. // least one member outbound among the inbound entries.
  335. func (s *SubJsonService) appendBalancerEntries(entries []subConfigEntry) []subConfigEntry {
  336. balancers := getEnabledSubBalancers()
  337. if len(balancers) == 0 {
  338. return entries
  339. }
  340. // Pre-pass: pull each inbound doc's proxy outbound once so every balancer
  341. // reuses it instead of re-unmarshalling the whole document per balancer.
  342. entryProxies := make([][]map[string]any, len(entries))
  343. for i, entry := range entries {
  344. if entry.kind != 0 {
  345. continue
  346. }
  347. for _, config := range entry.configs {
  348. if proxy := extractProxyOutbound(config); proxy != nil {
  349. entryProxies[i] = append(entryProxies[i], proxy)
  350. }
  351. }
  352. }
  353. for i := range balancers {
  354. config := s.buildBalancerConfig(&balancers[i], entries, entryProxies)
  355. if config == nil {
  356. continue
  357. }
  358. entries = append(entries, subConfigEntry{
  359. sortIndex: balancers[i].SortOrder,
  360. kind: 1,
  361. id: balancers[i].Id,
  362. configs: []json_util.RawMessage{config},
  363. })
  364. }
  365. return entries
  366. }
  367. // extractProxyOutbound returns the first outbound of a document when it is the
  368. // proxy (tag == "proxy"), else nil — the only member shape a balancer retags.
  369. func extractProxyOutbound(config json_util.RawMessage) map[string]any {
  370. var doc map[string]any
  371. if json.Unmarshal(config, &doc) != nil {
  372. return nil
  373. }
  374. outbounds, _ := doc["outbounds"].([]any)
  375. if len(outbounds) == 0 {
  376. return nil
  377. }
  378. outbound, _ := outbounds[0].(map[string]any)
  379. if outbound == nil || outbound["tag"] != "proxy" {
  380. return nil
  381. }
  382. return outbound
  383. }
  384. func getEnabledSubBalancers() []model.SubBalancer {
  385. var balancers []model.SubBalancer
  386. if err := database.GetDB().Model(&model.SubBalancer{}).
  387. Where("enabled = ?", true).
  388. Order("sort_order asc, id asc").Find(&balancers).Error; err != nil {
  389. logger.Error("SubJsonService - getEnabledSubBalancers:", err)
  390. return nil
  391. }
  392. return balancers
  393. }
  394. // Suffix by proxy protocol, not transport network — a vmess/tcp member used to
  395. // be mislabelled "vless".
  396. func balancerMemberSuffix(protocol string) string {
  397. if protocol == "" {
  398. return "other"
  399. }
  400. return protocol
  401. }
  402. // balMember is one retagged member outbound and the inbound it came from.
  403. type balMember struct {
  404. tag string
  405. inboundId int
  406. }
  407. // leastLoadCosts builds xray's static strategy costs: higher value = picked
  408. // less often; nil unless a member carries an explicit weight (all-1.0 bloat).
  409. func leastLoadCosts(balancer *model.SubBalancer, members []balMember) []any {
  410. if balancer.Strategy != "leastLoad" || len(members) == 0 || len(balancer.MemberWeights) == 0 {
  411. return nil
  412. }
  413. costs := make([]any, 0, len(members))
  414. configured := false
  415. for _, m := range members {
  416. value := 1.0
  417. if weight, ok := balancer.MemberWeights[m.inboundId]; ok && weight > 0 {
  418. value = weight
  419. configured = true
  420. }
  421. // Anchored regexp: plain cost matching is substring-based in xray, so
  422. // an unanchored "bal-1-vless" would also swallow "bal-1-vless-2".
  423. costs = append(costs, map[string]any{
  424. "regexp": true,
  425. "match": "^" + m.tag + "$",
  426. "value": value,
  427. })
  428. }
  429. if !configured {
  430. return nil
  431. }
  432. return costs
  433. }
  434. // buildBalancerConfig assembles the balancer profile: members retagged under a
  435. // per-balancer prefix, a routing.balancers entry, and (for leastPing/leastLoad) an observatory.
  436. func (s *SubJsonService) buildBalancerConfig(balancer *model.SubBalancer, entries []subConfigEntry, entryProxies [][]map[string]any) json_util.RawMessage {
  437. prefix := fmt.Sprintf("bal-%d-", balancer.Id)
  438. usedTags := make(map[string]bool)
  439. var proxies []json_util.RawMessage
  440. // Members in emission order with their owning inbound, so costs[] can
  441. // reference the exact retagged tags assigned here.
  442. var members []balMember
  443. var firstTag string
  444. // entryProxies is the pre-extracted proxy outbounds per entry; kind!=0 rows
  445. // have none. Clone before retagging so the cached map stays reusable.
  446. for i, entry := range entries {
  447. if entry.kind != 0 || !slices.Contains(balancer.InboundIds, entry.id) {
  448. continue
  449. }
  450. for _, outbound := range entryProxies[i] {
  451. protocol, _ := outbound["protocol"].(string)
  452. base := prefix + balancerMemberSuffix(protocol)
  453. tag := base
  454. for suffix := 2; usedTags[tag]; suffix++ {
  455. tag = fmt.Sprintf("%s-%d", base, suffix)
  456. }
  457. usedTags[tag] = true
  458. member := maps.Clone(outbound)
  459. member["tag"] = tag
  460. if raw, err := json.MarshalIndent(member, "", " "); err == nil {
  461. members = append(members, balMember{tag: tag, inboundId: entry.id})
  462. if firstTag == "" {
  463. firstTag = tag
  464. }
  465. proxies = append(proxies, raw)
  466. }
  467. }
  468. }
  469. if len(proxies) == 0 {
  470. return nil
  471. }
  472. outbounds := append([]json_util.RawMessage{}, proxies...)
  473. outbounds = append(outbounds, s.defaultOutbounds...)
  474. // One template per document: two resolves could straddle a profile refresh
  475. // and pair this document's dns with the other revision's routing.
  476. template := s.bakedTemplate()
  477. // Clone the shared routing subtree (and each rule map) before pointing
  478. // rules at the balancer.
  479. baseRouting, _ := template["routing"].(map[string]any)
  480. routing := make(map[string]any, len(baseRouting)+1)
  481. maps.Copy(routing, baseRouting)
  482. baseRules, _ := baseRouting["rules"].([]any)
  483. rules := make([]any, 0, len(baseRules)+1)
  484. for _, rule := range baseRules {
  485. ruleMap, ok := rule.(map[string]any)
  486. if !ok {
  487. rules = append(rules, rule)
  488. continue
  489. }
  490. ruleMap = maps.Clone(ruleMap)
  491. if ruleMap["outboundTag"] == "proxy" {
  492. delete(ruleMap, "outboundTag")
  493. ruleMap["balancerTag"] = subBalancerTag
  494. }
  495. rules = append(rules, ruleMap)
  496. }
  497. routing["rules"] = rules
  498. isObservatory := balancer.Strategy == "leastPing" || balancer.Strategy == "leastLoad"
  499. strategyEntry := map[string]any{"type": balancer.Strategy}
  500. if costs := leastLoadCosts(balancer, members); costs != nil {
  501. strategyEntry["settings"] = map[string]any{"costs": costs}
  502. }
  503. balancerEntry := map[string]any{
  504. "tag": subBalancerTag,
  505. "selector": []string{prefix},
  506. "strategy": strategyEntry,
  507. }
  508. if isObservatory && firstTag != "" {
  509. // With all probes failing, route to the first member instead of
  510. // failing dispatch.
  511. balancerEntry["fallbackTag"] = firstTag
  512. }
  513. routing["balancers"] = []any{balancerEntry}
  514. newConfigJson := make(map[string]any, len(template)+2)
  515. maps.Copy(newConfigJson, template)
  516. newConfigJson["outbounds"] = outbounds
  517. newConfigJson["remarks"] = balancer.Remark
  518. newConfigJson["routing"] = routing
  519. // leastPing/leastLoad require a burst observatory (Xray refuses to start
  520. // them without one); fallbackTag above covers the probe-outage case.
  521. if isObservatory {
  522. newConfigJson["burstObservatory"] = s.balancerObservatory(prefix)
  523. }
  524. config, _ := json.MarshalIndent(newConfigJson, "", " ")
  525. return config
  526. }
  527. func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, client model.Client, host string) []json_util.RawMessage {
  528. var newJsonArray []json_util.RawMessage
  529. stream := s.streamData(inbound.StreamSettings, subKey(client))
  530. // When externalProxy is empty the JSON config falls back to a
  531. // synthetic one whose `dest` is the host the client connects to.
  532. // For node-managed inbounds we want the node's address — request
  533. // host won't reach the right xray. resolveInboundAddress already
  534. // implements the node→subscriber-host fallback chain.
  535. defaultDest := subReq.resolveInboundAddress(inbound)
  536. if defaultDest == "" {
  537. defaultDest = host
  538. }
  539. // Per-inbound xmux takes precedence over the global subJsonMux.
  540. // When xmux is present inside xhttpSettings, XHTTP multiplexing
  541. // is handled by xmux — don't also set the legacy outbound.Mux.
  542. mux := s.mux
  543. if xhttp, ok := stream["xhttpSettings"].(map[string]any); ok {
  544. if _, hasXmux := xhttp["xmux"]; hasXmux {
  545. mux = ""
  546. }
  547. }
  548. externalProxies, ok := stream["externalProxy"].([]any)
  549. hasExternalProxy := ok && len(externalProxies) > 0
  550. if !hasExternalProxy {
  551. externalProxies = []any{
  552. map[string]any{
  553. "forceTls": "same",
  554. "dest": defaultDest,
  555. "port": float64(inbound.Port),
  556. "remark": "",
  557. },
  558. }
  559. }
  560. delete(stream, "externalProxy")
  561. network, _ := stream["network"].(string)
  562. for _, ep := range externalProxies {
  563. extPrxy, ok := ep.(map[string]any)
  564. if !ok {
  565. continue
  566. }
  567. // Expand the host's {{VAR}} remark template for this client (no-op for
  568. // the synthetic/legacy entry) before it's used as the config remark.
  569. subReq.renderHostRemark(inbound, client, extPrxy, network)
  570. inbound.Listen, _ = extPrxy["dest"].(string)
  571. if port, ok := extPrxy["port"].(float64); ok {
  572. inbound.Port = int(port)
  573. }
  574. newStream := cloneStreamForExternalProxy(stream)
  575. forceTls, _ := extPrxy["forceTls"].(string)
  576. switch forceTls {
  577. case "tls":
  578. if newStream["security"] != "tls" {
  579. newStream["security"] = "tls"
  580. newStream["tlsSettings"] = map[string]any{}
  581. }
  582. case "none":
  583. if newStream["security"] != "none" {
  584. newStream["security"] = "none"
  585. delete(newStream, "tlsSettings")
  586. }
  587. }
  588. security, _ := newStream["security"].(string)
  589. if hasExternalProxy {
  590. applyExternalProxyTLSToStream(extPrxy, newStream, security)
  591. liftHostTLSVerification(newStream)
  592. }
  593. applyHostStreamOverrides(extPrxy, newStream)
  594. if finalmask, ok := newStream["finalmask"].(map[string]any); ok {
  595. newStream["finalmask"] = withLegacyFragmentRanges(finalmask)
  596. }
  597. // A host's legacy hop still needs the mask; the last-merged hop, the host's, wins.
  598. maskcompat.UpgradeLegacyUDPHop(newStream["finalmask"])
  599. maskcompat.NormalizeUDPHop(newStream["finalmask"])
  600. streamSettings, _ := json.MarshalIndent(newStream, "", " ")
  601. hostMux := hostMuxOverride(extPrxy)
  602. var newOutbounds []json_util.RawMessage
  603. switch inbound.Protocol {
  604. case "vmess":
  605. newOutbounds = append(newOutbounds, s.genVnext(inbound, streamSettings, client, jsonMux(mux, hostMux)))
  606. case "vless":
  607. vc := client
  608. vc.ID = applyVlessRoute(client.ID, hostVlessRoute(extPrxy))
  609. // Same gate the raw link and the Clash proxy apply: a flow left
  610. // over from a transport Vision supported produces an outbound
  611. // xray refuses to start.
  612. newNetwork, _ := newStream["network"].(string)
  613. if vc.Flow != "" && !vlessFlowAllowed(newNetwork, security, subReq.linkSettings(inbound)) {
  614. vc.Flow = ""
  615. }
  616. newOutbounds = append(newOutbounds, s.genVless(subReq, inbound, streamSettings, vc, jsonMux(mux, hostMux)))
  617. case "trojan", "shadowsocks":
  618. newOutbounds = append(newOutbounds, s.genServer(subReq, inbound, streamSettings, client, jsonMux(mux, hostMux)))
  619. case "hysteria":
  620. newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client, jsonMux(mux, hostMux)))
  621. case "masque":
  622. newOutbounds = append(newOutbounds, s.genMasque(inbound, newStream, client))
  623. case "wireguard":
  624. wgOutbound := s.genWireguard(inbound, client)
  625. if wgOutbound == nil {
  626. continue
  627. }
  628. newOutbounds = append(newOutbounds, wgOutbound)
  629. case "amneziawg", "tuic":
  630. continue
  631. }
  632. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  633. newConfigJson := make(map[string]any)
  634. maps.Copy(newConfigJson, s.bakedTemplate())
  635. transport, _ := newStream["network"].(string)
  636. newConfigJson["outbounds"] = newOutbounds
  637. newConfigJson["remarks"] = subReq.endpointRemark(inbound, client.Email, extPrxy, transport)
  638. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  639. newJsonArray = append(newJsonArray, newConfig)
  640. }
  641. return newJsonArray
  642. }
  643. func (s *SubJsonService) streamData(stream string, clientKey string) map[string]any {
  644. var streamSettings map[string]any
  645. if err := json.Unmarshal([]byte(stream), &streamSettings); err != nil || streamSettings == nil {
  646. streamSettings = map[string]any{}
  647. }
  648. security, _ := streamSettings["security"].(string)
  649. switch security {
  650. case "tls":
  651. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  652. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  653. } else {
  654. delete(streamSettings, "tlsSettings")
  655. }
  656. case "reality":
  657. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  658. streamSettings["realitySettings"] = s.realityData(realitySettings, clientKey)
  659. } else {
  660. delete(streamSettings, "realitySettings")
  661. }
  662. }
  663. delete(streamSettings, "sockopt")
  664. // The inbound's own hop range becomes a mask first, so the global default yields to it.
  665. maskcompat.UpgradeLegacyUDPHop(streamSettings["finalmask"])
  666. if s.finalMask != "" {
  667. s.applyGlobalFinalMask(streamSettings)
  668. }
  669. // remove proxy protocol
  670. network, _ := streamSettings["network"].(string)
  671. switch network {
  672. case "tcp":
  673. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  674. case "ws":
  675. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  676. case "httpupgrade":
  677. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  678. case "xhttp":
  679. streamSettings["xhttpSettings"] = s.removeAcceptProxy(streamSettings["xhttpSettings"])
  680. if xhttp, ok := streamSettings["xhttpSettings"].(map[string]any); ok {
  681. delete(xhttp, "noSSEHeader")
  682. delete(xhttp, "scMaxBufferedPosts")
  683. delete(xhttp, "scStreamUpServerSecs")
  684. delete(xhttp, "serverMaxHeaderBytes")
  685. // Values matching xray-core's own defaults stay off the wire:
  686. // old panels seeded them into every stored config and the
  687. // literal scMinPostsIntervalMs=30 is a DPI fingerprint (#5141).
  688. if v, _ := xhttp["scMaxEachPostBytes"].(string); v == "" || v == "1000000" {
  689. delete(xhttp, "scMaxEachPostBytes")
  690. }
  691. if v, _ := xhttp["scMinPostsIntervalMs"].(string); v == "" || v == "30" {
  692. delete(xhttp, "scMinPostsIntervalMs")
  693. }
  694. }
  695. }
  696. return streamSettings
  697. }
  698. func (s *SubJsonService) applyGlobalFinalMask(streamSettings map[string]any) {
  699. var fm map[string]any
  700. if err := json.Unmarshal([]byte(s.finalMask), &fm); err != nil || len(fm) == 0 {
  701. return
  702. }
  703. // The global hop range is a default: an inbound that advertises its own keeps it.
  704. if maskcompat.HasUDPHopMask(streamSettings["finalmask"]) {
  705. fm = maskcompat.WithoutUDPHop(fm)
  706. }
  707. merged := mergeFinalMask(streamSettings["finalmask"], fm)
  708. if len(merged) > 0 {
  709. streamSettings["finalmask"] = merged
  710. }
  711. }
  712. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  713. netSettings, ok := setting.(map[string]any)
  714. if ok {
  715. delete(netSettings, "acceptProxyProtocol")
  716. }
  717. return netSettings
  718. }
  719. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  720. tlsData := make(map[string]any, 1)
  721. tlsClientSettings, _ := tData["settings"].(map[string]any)
  722. tlsData["serverName"] = tData["serverName"]
  723. tlsData["alpn"] = tData["alpn"]
  724. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  725. tlsData["fingerprint"] = fingerprint
  726. }
  727. if cs, ok := tData["cipherSuites"].(string); ok && cs != "" {
  728. tlsData["cipherSuites"] = cs
  729. }
  730. putClientTLSVerification(tlsData, tlsClientSettings)
  731. return tlsData
  732. }
  733. // liftHostTLSVerification moves the host overrides applyExternalProxyTLSToStream
  734. // wrote into the panel-shaped tlsSettings.settings up to where xray reads them.
  735. func liftHostTLSVerification(stream map[string]any) {
  736. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  737. inner, ok := tlsSettings["settings"].(map[string]any)
  738. if !ok {
  739. return
  740. }
  741. delete(tlsSettings, "settings")
  742. putClientTLSVerification(tlsSettings, inner)
  743. }
  744. func putClientTLSVerification(tlsData map[string]any, tlsClientSettings map[string]any) {
  745. if ech, ok := tlsClientSettings["echConfigList"].(string); ok && ech != "" {
  746. tlsData["echConfigList"] = ech
  747. }
  748. if vcn, ok := verifyPeerCertByNameValue(tlsClientSettings); ok {
  749. tlsData["verifyPeerCertByName"] = vcn
  750. }
  751. // xray-core now parses pinnedPeerCertSha256 as a comma-separated string, not
  752. // an array; emit the joined form so v2ray clients can import the config (#5401).
  753. if pins, ok := pinnedSha256List(tlsClientSettings); ok {
  754. tlsData["pinnedPeerCertSha256"] = strings.Join(pins, ",")
  755. }
  756. }
  757. func (s *SubJsonService) realityData(rData map[string]any, clientKey string) map[string]any {
  758. rltyData := make(map[string]any, 1)
  759. rltyClientSettings, _ := rData["settings"].(map[string]any)
  760. rltyData["show"] = false
  761. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  762. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  763. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  764. seed, _ := rltyClientSettings["spiderX"].(string)
  765. rltyData["spiderX"] = deriveSpiderX(seed, clientKey)
  766. shortIds, ok := rData["shortIds"].([]any)
  767. if ok && len(shortIds) > 0 {
  768. rltyData["shortId"], _ = shortIds[random.Num(len(shortIds))].(string)
  769. } else {
  770. rltyData["shortId"] = ""
  771. }
  772. serverNames, ok := rData["serverNames"].([]any)
  773. if ok && len(serverNames) > 0 {
  774. rltyData["serverName"], _ = serverNames[random.Num(len(serverNames))].(string)
  775. } else {
  776. rltyData["serverName"] = ""
  777. }
  778. return rltyData
  779. }
  780. // jsonMux picks the per-host mux override when present, else the global mux.
  781. func jsonMux(global, override string) string {
  782. if override != "" {
  783. return override
  784. }
  785. return global
  786. }
  787. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  788. outbound := Outbound{
  789. Protocol: string(inbound.Protocol),
  790. Tag: "proxy",
  791. }
  792. if mux != "" {
  793. outbound.Mux = json_util.RawMessage(mux)
  794. }
  795. outbound.StreamSettings = streamSettings
  796. security := normalizeVmessSecurity(client.Security)
  797. outbound.Settings = map[string]any{
  798. "address": inbound.Listen,
  799. "port": inbound.Port,
  800. "id": client.ID,
  801. "security": security,
  802. "level": 8,
  803. }
  804. result, _ := json.MarshalIndent(outbound, "", " ")
  805. return result
  806. }
  807. func (s *SubJsonService) genVless(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  808. outbound := Outbound{
  809. Protocol: string(inbound.Protocol),
  810. Tag: "proxy",
  811. }
  812. if mux != "" {
  813. outbound.Mux = json_util.RawMessage(mux)
  814. }
  815. outbound.StreamSettings = streamSettings
  816. settings := map[string]any{
  817. "address": inbound.Listen,
  818. "port": inbound.Port,
  819. "id": client.ID,
  820. "encryption": vlessClientEncryption(subReq.linkSettings(inbound)),
  821. "level": 8,
  822. }
  823. if client.Flow != "" && !inbound.DisableFlow {
  824. settings["flow"] = client.Flow
  825. outbound.Mux = muxWithoutTCP(mux)
  826. }
  827. outbound.Settings = settings
  828. result, _ := json.MarshalIndent(outbound, "", " ")
  829. return result
  830. }
  831. // XTLS flows reject TCP mux.cool ("unexpected network TCP"); concurrency -1
  832. // turns only that off and keeps the XUDP keys (Xray reads them under enabled).
  833. func muxWithoutTCP(mux string) json_util.RawMessage {
  834. if mux == "" {
  835. return nil
  836. }
  837. var m map[string]any
  838. if err := json.Unmarshal([]byte(mux), &m); err != nil || m == nil {
  839. return nil
  840. }
  841. m["concurrency"] = -1
  842. out, err := json.Marshal(m)
  843. if err != nil {
  844. return nil
  845. }
  846. return json_util.RawMessage(out)
  847. }
  848. func (s *SubJsonService) genServer(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  849. outbound := Outbound{}
  850. serverData := make([]ServerSetting, 1)
  851. serverData[0] = ServerSetting{
  852. Address: inbound.Listen,
  853. Port: inbound.Port,
  854. Level: 8,
  855. Password: client.Password,
  856. }
  857. if inbound.Protocol == model.Shadowsocks {
  858. inboundSettings := subReq.linkSettings(inbound)
  859. method, _ := inboundSettings["method"].(string)
  860. serverData[0].Method = method
  861. // server password in multi-user 2022 protocols
  862. if strings.HasPrefix(method, "2022") {
  863. if serverPassword, ok := inboundSettings["password"].(string); ok {
  864. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  865. }
  866. }
  867. }
  868. outbound.Protocol = string(inbound.Protocol)
  869. outbound.Tag = "proxy"
  870. if mux != "" {
  871. outbound.Mux = json_util.RawMessage(mux)
  872. }
  873. outbound.StreamSettings = streamSettings
  874. // Wrap the endpoint in a "servers" array (the standard Xray schema for
  875. // Shadowsocks/Trojan outbounds). The flat top-level form only parses on very
  876. // recent xray-core; older bundled cores (e.g. in v2rayN) reject it, so SS
  877. // links fail to connect. See genVnext/genVless for the VMess/VLESS shape.
  878. server := map[string]any{
  879. "address": serverData[0].Address,
  880. "port": serverData[0].Port,
  881. "password": serverData[0].Password,
  882. "level": 8,
  883. }
  884. if inbound.Protocol == model.Shadowsocks {
  885. server["method"] = serverData[0].Method
  886. }
  887. outbound.Settings = map[string]any{
  888. "servers": []any{server},
  889. }
  890. result, _ := json.MarshalIndent(outbound, "", " ")
  891. return result
  892. }
  893. func (s *SubJsonService) genHy(inbound *model.Inbound, newStream map[string]any, client model.Client, mux string) json_util.RawMessage {
  894. outbound := Outbound{
  895. Protocol: string(inbound.Protocol),
  896. Tag: "proxy",
  897. }
  898. if mux != "" {
  899. outbound.Mux = json_util.RawMessage(mux)
  900. }
  901. var settings, stream map[string]any
  902. _ = json.Unmarshal([]byte(inbound.Settings), &settings)
  903. version, _ := settings["version"].(float64)
  904. outbound.Settings = map[string]any{
  905. "version": int(version),
  906. "address": inbound.Listen,
  907. "port": inbound.Port,
  908. }
  909. _ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  910. hyStream, _ := stream["hysteriaSettings"].(map[string]any)
  911. outHyStream := map[string]any{
  912. "version": int(version),
  913. "auth": client.Auth,
  914. }
  915. if udpIdleTimeout, ok := hyStream["udpIdleTimeout"].(float64); ok {
  916. outHyStream["udpIdleTimeout"] = int(udpIdleTimeout)
  917. }
  918. if masquerade, ok := hyStream["masquerade"].(map[string]any); ok {
  919. outHyStream["masquerade"] = masquerade
  920. }
  921. newStream["hysteriaSettings"] = outHyStream
  922. if finalmask, ok := hyStream["finalmask"].(map[string]any); ok {
  923. newStream["finalmask"] = mergeFinalMask(newStream["finalmask"], finalmask)
  924. }
  925. maskcompat.UpgradeLegacyUDPHop(newStream["finalmask"])
  926. maskcompat.NormalizeUDPHop(newStream["finalmask"])
  927. newStream["network"] = "hysteria"
  928. newStream["security"] = "tls"
  929. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  930. result, _ := json.MarshalIndent(outbound, "", " ")
  931. return result
  932. }
  933. // genMasque builds the client side of a MASQUE inbound: the server reads only the
  934. // path, and authenticates the CONNECT-IP request by the client's email and password.
  935. func (s *SubJsonService) genMasque(inbound *model.Inbound, newStream map[string]any, client model.Client) json_util.RawMessage {
  936. outbound := Outbound{
  937. Protocol: string(inbound.Protocol),
  938. Tag: "proxy",
  939. Settings: map[string]any{
  940. "address": inbound.Listen,
  941. "port": inbound.Port,
  942. },
  943. }
  944. masqueSettings := map[string]any{"user": client.Email, "pass": client.Password}
  945. if server, ok := newStream["masqueSettings"].(map[string]any); ok {
  946. if path, ok := server["path"].(string); ok && path != "" {
  947. masqueSettings["path"] = path
  948. }
  949. }
  950. newStream["masqueSettings"] = masqueSettings
  951. newStream["network"] = "masque"
  952. newStream["security"] = "tls"
  953. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  954. result, _ := json.MarshalIndent(outbound, "", " ")
  955. return result
  956. }
  957. // genWireguard builds an Xray wireguard outbound for a native WireGuard inbound,
  958. // mirroring genWireguardLink: the peer public key is derived from the inbound
  959. // secretKey, the client owns the private key / tunnel address / pre-shared key,
  960. // and the peer routes the full tunnel. Returns nil when the client has no key.
  961. func (s *SubJsonService) genWireguard(inbound *model.Inbound, client model.Client) json_util.RawMessage {
  962. if client.PrivateKey == "" {
  963. return nil
  964. }
  965. var inboundSettings map[string]any
  966. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  967. secretKey, _ := inboundSettings["secretKey"].(string)
  968. peer := map[string]any{
  969. "endpoint": joinHostPort(inbound.Listen, inbound.Port),
  970. "allowedIPs": []string{"0.0.0.0/0", "::/0"},
  971. }
  972. if secretKey != "" {
  973. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  974. peer["publicKey"] = pub
  975. }
  976. }
  977. if client.PreSharedKey != "" {
  978. peer["preSharedKey"] = client.PreSharedKey
  979. }
  980. if ka := client.KeepAliveSeconds(); ka > 0 {
  981. peer["keepAlive"] = ka
  982. }
  983. settings := map[string]any{
  984. "secretKey": client.PrivateKey,
  985. "peers": []any{peer},
  986. }
  987. if len(client.AllowedIPs) > 0 {
  988. settings["address"] = client.AllowedIPs
  989. }
  990. if mtu, ok := inboundSettings["mtu"].(float64); ok && mtu > 0 {
  991. settings["mtu"] = int(mtu)
  992. }
  993. outbound := map[string]any{
  994. "protocol": string(inbound.Protocol),
  995. "tag": "proxy",
  996. "settings": settings,
  997. }
  998. result, _ := json.MarshalIndent(outbound, "", " ")
  999. return result
  1000. }
  1001. func (s *SubJsonService) genDummySocksConfig(remark string) json_util.RawMessage {
  1002. outbound := map[string]any{
  1003. "protocol": "socks",
  1004. "tag": "proxy",
  1005. "settings": map[string]any{
  1006. "servers": []any{
  1007. map[string]any{
  1008. "address": "127.0.0.1",
  1009. "port": 1080,
  1010. },
  1011. },
  1012. },
  1013. }
  1014. rawOutbound, _ := json.Marshal(outbound)
  1015. newOutbounds := []json_util.RawMessage{rawOutbound}
  1016. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  1017. newConfigJson := make(map[string]any)
  1018. maps.Copy(newConfigJson, s.configJson)
  1019. if s.dnsBlock != nil {
  1020. newConfigJson["dns"] = s.dnsBlock
  1021. }
  1022. newConfigJson["outbounds"] = newOutbounds
  1023. newConfigJson["remarks"] = remark
  1024. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  1025. return newConfig
  1026. }
  1027. func mergeFinalMask(base any, extra map[string]any) map[string]any {
  1028. merged := map[string]any{}
  1029. if baseMap, ok := base.(map[string]any); ok {
  1030. for key, value := range baseMap {
  1031. switch key {
  1032. case "tcp", "udp":
  1033. if masks, ok := value.([]any); ok {
  1034. merged[key] = append([]any(nil), masks...)
  1035. }
  1036. default:
  1037. merged[key] = value
  1038. }
  1039. }
  1040. }
  1041. for key, value := range extra {
  1042. switch key {
  1043. case "tcp", "udp":
  1044. baseMasks, _ := merged[key].([]any)
  1045. extraMasks, _ := value.([]any)
  1046. if len(extraMasks) > 0 {
  1047. merged[key] = append(baseMasks, extraMasks...)
  1048. }
  1049. case "quicParams":
  1050. if _, exists := merged[key]; !exists {
  1051. merged[key] = value
  1052. }
  1053. default:
  1054. merged[key] = value
  1055. }
  1056. }
  1057. return merged
  1058. }
  1059. type Outbound struct {
  1060. Protocol string `json:"protocol"`
  1061. Tag string `json:"tag"`
  1062. StreamSettings json_util.RawMessage `json:"streamSettings"`
  1063. Mux json_util.RawMessage `json:"mux,omitempty"`
  1064. Settings map[string]any `json:"settings,omitempty"`
  1065. }
  1066. type ServerSetting struct {
  1067. Password string `json:"password"`
  1068. Level int `json:"level"`
  1069. Address string `json:"address"`
  1070. Port int `json:"port"`
  1071. Flow string `json:"flow,omitempty"`
  1072. Method string `json:"method,omitempty"`
  1073. }