json_service.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. package sub
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "fmt"
  6. "maps"
  7. "strings"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  9. "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
  10. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  11. )
  12. //go:embed default.json
  13. var defaultJson string
  14. // SubJsonService handles JSON subscription configuration generation and management.
  15. type SubJsonService struct {
  16. configJson map[string]any
  17. defaultOutbounds []json_util.RawMessage
  18. finalMask string
  19. mux string
  20. SubService *SubService
  21. }
  22. // NewSubJsonService creates a new JSON subscription service with the given configuration.
  23. func NewSubJsonService(mux string, rules string, finalMask string, subService *SubService) *SubJsonService {
  24. var configJson map[string]any
  25. var defaultOutbounds []json_util.RawMessage
  26. json.Unmarshal([]byte(defaultJson), &configJson)
  27. if outboundSlices, ok := configJson["outbounds"].([]any); ok {
  28. for _, defaultOutbound := range outboundSlices {
  29. jsonBytes, _ := json.Marshal(defaultOutbound)
  30. defaultOutbounds = append(defaultOutbounds, jsonBytes)
  31. }
  32. }
  33. if rules != "" {
  34. var newRules []any
  35. routing, _ := configJson["routing"].(map[string]any)
  36. defaultRules, _ := routing["rules"].([]any)
  37. json.Unmarshal([]byte(rules), &newRules)
  38. defaultRules = append(newRules, defaultRules...)
  39. routing["rules"] = defaultRules
  40. configJson["routing"] = routing
  41. }
  42. return &SubJsonService{
  43. configJson: configJson,
  44. defaultOutbounds: defaultOutbounds,
  45. finalMask: finalMask,
  46. mux: mux,
  47. SubService: subService,
  48. }
  49. }
  50. // GetJson generates a JSON subscription configuration for the given subscription ID and host.
  51. func (s *SubJsonService) GetJson(subId string, host string) (string, string, error) {
  52. subReq := s.SubService.ForRequest(host)
  53. subReq.subscriptionBody = true
  54. inbounds, err := subReq.getInboundsBySubId(subId)
  55. if err != nil {
  56. return "", "", err
  57. }
  58. externalLinks, err := subReq.getClientExternalLinksBySubId(subId)
  59. if err != nil {
  60. return "", "", err
  61. }
  62. if len(inbounds) == 0 && len(externalLinks) == 0 {
  63. return "", "", nil
  64. }
  65. var header string
  66. var configArray []json_util.RawMessage
  67. seenEmails := make(map[string]struct{})
  68. // Prepare Inbounds
  69. for _, inbound := range inbounds {
  70. clients := subReq.matchingClients(inbound, subId)
  71. if len(clients) == 0 {
  72. continue
  73. }
  74. subReq.projectThroughFallbackMaster(inbound)
  75. if hostEps := subReq.hostEndpoints(inbound, "json"); len(hostEps) > 0 {
  76. injectExternalProxy(inbound, hostEps)
  77. }
  78. for _, client := range clients {
  79. seenEmails[client.Email] = struct{}{}
  80. configArray = append(configArray, s.getConfig(subReq, inbound, client, host)...)
  81. }
  82. }
  83. for _, ext := range externalLinks {
  84. for _, el := range expandEntry(ext) {
  85. outbound := parsedExternalOutbound(el.Link)
  86. if outbound == nil {
  87. continue
  88. }
  89. seenEmails[ext.Email] = struct{}{}
  90. remark := el.Name
  91. if remark == "" {
  92. remark = ext.Email
  93. }
  94. newOutbounds := []json_util.RawMessage{outbound}
  95. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  96. newConfigJson := make(map[string]any)
  97. maps.Copy(newConfigJson, s.configJson)
  98. newConfigJson["outbounds"] = newOutbounds
  99. newConfigJson["remarks"] = remark
  100. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  101. configArray = append(configArray, newConfig)
  102. }
  103. }
  104. if len(configArray) == 0 {
  105. return "", "", nil
  106. }
  107. emails := make([]string, 0, len(seenEmails))
  108. for e := range seenEmails {
  109. emails = append(emails, e)
  110. }
  111. traffic, _ := subReq.AggregateTrafficByEmails(emails)
  112. // Combile outbounds
  113. var finalJson []byte
  114. if len(configArray) == 1 {
  115. finalJson, _ = json.MarshalIndent(configArray[0], "", " ")
  116. } else {
  117. finalJson, _ = json.MarshalIndent(configArray, "", " ")
  118. }
  119. header = fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  120. return string(finalJson), header, nil
  121. }
  122. func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, client model.Client, host string) []json_util.RawMessage {
  123. var newJsonArray []json_util.RawMessage
  124. stream := s.streamData(inbound.StreamSettings)
  125. // When externalProxy is empty the JSON config falls back to a
  126. // synthetic one whose `dest` is the host the client connects to.
  127. // For node-managed inbounds we want the node's address — request
  128. // host won't reach the right xray. resolveInboundAddress already
  129. // implements the node→subscriber-host fallback chain.
  130. defaultDest := subReq.resolveInboundAddress(inbound)
  131. if defaultDest == "" {
  132. defaultDest = host
  133. }
  134. // Per-inbound xmux takes precedence over the global subJsonMux.
  135. // When xmux is present inside xhttpSettings, XHTTP multiplexing
  136. // is handled by xmux — don't also set the legacy outbound.Mux.
  137. mux := s.mux
  138. if xhttp, ok := stream["xhttpSettings"].(map[string]any); ok {
  139. if _, hasXmux := xhttp["xmux"]; hasXmux {
  140. mux = ""
  141. }
  142. }
  143. externalProxies, ok := stream["externalProxy"].([]any)
  144. hasExternalProxy := ok && len(externalProxies) > 0
  145. if !hasExternalProxy {
  146. externalProxies = []any{
  147. map[string]any{
  148. "forceTls": "same",
  149. "dest": defaultDest,
  150. "port": float64(inbound.Port),
  151. "remark": "",
  152. },
  153. }
  154. }
  155. delete(stream, "externalProxy")
  156. network, _ := stream["network"].(string)
  157. for _, ep := range externalProxies {
  158. extPrxy := ep.(map[string]any)
  159. // Expand the host's {{VAR}} remark template for this client (no-op for
  160. // the synthetic/legacy entry) before it's used as the config remark.
  161. subReq.renderHostRemark(inbound, client, extPrxy, network)
  162. inbound.Listen = extPrxy["dest"].(string)
  163. inbound.Port = int(extPrxy["port"].(float64))
  164. newStream := cloneStreamForExternalProxy(stream)
  165. switch extPrxy["forceTls"].(string) {
  166. case "tls":
  167. if newStream["security"] != "tls" {
  168. newStream["security"] = "tls"
  169. newStream["tlsSettings"] = map[string]any{}
  170. }
  171. case "none":
  172. if newStream["security"] != "none" {
  173. newStream["security"] = "none"
  174. delete(newStream, "tlsSettings")
  175. }
  176. }
  177. security, _ := newStream["security"].(string)
  178. if hasExternalProxy {
  179. applyExternalProxyTLSToStream(extPrxy, newStream, security)
  180. }
  181. applyHostStreamOverrides(extPrxy, newStream)
  182. streamSettings, _ := json.MarshalIndent(newStream, "", " ")
  183. hostMux := hostMuxOverride(extPrxy)
  184. var newOutbounds []json_util.RawMessage
  185. switch inbound.Protocol {
  186. case "vmess":
  187. newOutbounds = append(newOutbounds, s.genVnext(inbound, streamSettings, client, jsonMux(mux, hostMux)))
  188. case "vless":
  189. newOutbounds = append(newOutbounds, s.genVless(inbound, streamSettings, client, jsonMux(mux, hostMux)))
  190. case "trojan", "shadowsocks":
  191. newOutbounds = append(newOutbounds, s.genServer(inbound, streamSettings, client, jsonMux(mux, hostMux)))
  192. case "hysteria":
  193. newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client, jsonMux(mux, hostMux)))
  194. }
  195. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  196. newConfigJson := make(map[string]any)
  197. maps.Copy(newConfigJson, s.configJson)
  198. transport, _ := newStream["network"].(string)
  199. newConfigJson["outbounds"] = newOutbounds
  200. newConfigJson["remarks"] = subReq.endpointRemark(inbound, client.Email, extPrxy, transport)
  201. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  202. newJsonArray = append(newJsonArray, newConfig)
  203. }
  204. return newJsonArray
  205. }
  206. func (s *SubJsonService) streamData(stream string) map[string]any {
  207. var streamSettings map[string]any
  208. json.Unmarshal([]byte(stream), &streamSettings)
  209. security, _ := streamSettings["security"].(string)
  210. switch security {
  211. case "tls":
  212. streamSettings["tlsSettings"] = s.tlsData(streamSettings["tlsSettings"].(map[string]any))
  213. case "reality":
  214. streamSettings["realitySettings"] = s.realityData(streamSettings["realitySettings"].(map[string]any))
  215. }
  216. delete(streamSettings, "sockopt")
  217. if s.finalMask != "" {
  218. s.applyGlobalFinalMask(streamSettings)
  219. }
  220. // remove proxy protocol
  221. network, _ := streamSettings["network"].(string)
  222. switch network {
  223. case "tcp":
  224. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  225. case "ws":
  226. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  227. case "httpupgrade":
  228. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  229. case "xhttp":
  230. streamSettings["xhttpSettings"] = s.removeAcceptProxy(streamSettings["xhttpSettings"])
  231. if xhttp, ok := streamSettings["xhttpSettings"].(map[string]any); ok {
  232. delete(xhttp, "noSSEHeader")
  233. delete(xhttp, "scMaxBufferedPosts")
  234. delete(xhttp, "scStreamUpServerSecs")
  235. delete(xhttp, "serverMaxHeaderBytes")
  236. // Values matching xray-core's own defaults stay off the wire:
  237. // old panels seeded them into every stored config and the
  238. // literal scMinPostsIntervalMs=30 is a DPI fingerprint (#5141).
  239. if v, _ := xhttp["scMaxEachPostBytes"].(string); v == "" || v == "1000000" {
  240. delete(xhttp, "scMaxEachPostBytes")
  241. }
  242. if v, _ := xhttp["scMinPostsIntervalMs"].(string); v == "" || v == "30" {
  243. delete(xhttp, "scMinPostsIntervalMs")
  244. }
  245. }
  246. }
  247. return streamSettings
  248. }
  249. func (s *SubJsonService) applyGlobalFinalMask(streamSettings map[string]any) {
  250. var fm map[string]any
  251. if err := json.Unmarshal([]byte(s.finalMask), &fm); err != nil || len(fm) == 0 {
  252. return
  253. }
  254. merged := mergeFinalMask(streamSettings["finalmask"], fm)
  255. if len(merged) > 0 {
  256. streamSettings["finalmask"] = merged
  257. }
  258. }
  259. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  260. netSettings, ok := setting.(map[string]any)
  261. if ok {
  262. delete(netSettings, "acceptProxyProtocol")
  263. }
  264. return netSettings
  265. }
  266. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  267. tlsData := make(map[string]any, 1)
  268. tlsClientSettings, _ := tData["settings"].(map[string]any)
  269. tlsData["serverName"] = tData["serverName"]
  270. tlsData["alpn"] = tData["alpn"]
  271. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  272. tlsData["fingerprint"] = fingerprint
  273. }
  274. if ech, ok := tlsClientSettings["echConfigList"].(string); ok && ech != "" {
  275. tlsData["echConfigList"] = ech
  276. }
  277. // xray-core now parses pinnedPeerCertSha256 as a comma-separated string, not
  278. // an array; emit the joined form so v2ray clients can import the config (#5401).
  279. if pins, ok := pinnedSha256List(tlsClientSettings); ok {
  280. tlsData["pinnedPeerCertSha256"] = strings.Join(pins, ",")
  281. }
  282. return tlsData
  283. }
  284. func (s *SubJsonService) realityData(rData map[string]any) map[string]any {
  285. rltyData := make(map[string]any, 1)
  286. rltyClientSettings, _ := rData["settings"].(map[string]any)
  287. rltyData["show"] = false
  288. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  289. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  290. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  291. // Set random data
  292. rltyData["spiderX"] = "/" + random.Seq(15)
  293. shortIds, ok := rData["shortIds"].([]any)
  294. if ok && len(shortIds) > 0 {
  295. rltyData["shortId"] = shortIds[random.Num(len(shortIds))].(string)
  296. } else {
  297. rltyData["shortId"] = ""
  298. }
  299. serverNames, ok := rData["serverNames"].([]any)
  300. if ok && len(serverNames) > 0 {
  301. rltyData["serverName"] = serverNames[random.Num(len(serverNames))].(string)
  302. } else {
  303. rltyData["serverName"] = ""
  304. }
  305. return rltyData
  306. }
  307. // jsonMux picks the per-host mux override when present, else the global mux.
  308. func jsonMux(global, override string) string {
  309. if override != "" {
  310. return override
  311. }
  312. return global
  313. }
  314. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  315. outbound := Outbound{}
  316. outbound.Protocol = string(inbound.Protocol)
  317. outbound.Tag = "proxy"
  318. if mux != "" {
  319. outbound.Mux = json_util.RawMessage(mux)
  320. }
  321. outbound.StreamSettings = streamSettings
  322. security := client.Security
  323. if security == "" {
  324. security = "auto"
  325. }
  326. outbound.Settings = map[string]any{
  327. "address": inbound.Listen,
  328. "port": inbound.Port,
  329. "id": client.ID,
  330. "security": security,
  331. "level": 8,
  332. }
  333. result, _ := json.MarshalIndent(outbound, "", " ")
  334. return result
  335. }
  336. func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  337. outbound := Outbound{}
  338. outbound.Protocol = string(inbound.Protocol)
  339. outbound.Tag = "proxy"
  340. if mux != "" {
  341. outbound.Mux = json_util.RawMessage(mux)
  342. }
  343. outbound.StreamSettings = streamSettings
  344. // Add encryption for VLESS outbound from inbound settings
  345. var inboundSettings map[string]any
  346. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  347. encryption, _ := inboundSettings["encryption"].(string)
  348. settings := map[string]any{
  349. "address": inbound.Listen,
  350. "port": inbound.Port,
  351. "id": client.ID,
  352. "encryption": encryption,
  353. "level": 8,
  354. }
  355. if client.Flow != "" {
  356. settings["flow"] = client.Flow
  357. }
  358. outbound.Settings = settings
  359. result, _ := json.MarshalIndent(outbound, "", " ")
  360. return result
  361. }
  362. func (s *SubJsonService) genServer(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  363. outbound := Outbound{}
  364. serverData := make([]ServerSetting, 1)
  365. serverData[0] = ServerSetting{
  366. Address: inbound.Listen,
  367. Port: inbound.Port,
  368. Level: 8,
  369. Password: client.Password,
  370. }
  371. if inbound.Protocol == model.Shadowsocks {
  372. var inboundSettings map[string]any
  373. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  374. method, _ := inboundSettings["method"].(string)
  375. serverData[0].Method = method
  376. // server password in multi-user 2022 protocols
  377. if strings.HasPrefix(method, "2022") {
  378. if serverPassword, ok := inboundSettings["password"].(string); ok {
  379. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  380. }
  381. }
  382. }
  383. outbound.Protocol = string(inbound.Protocol)
  384. outbound.Tag = "proxy"
  385. if mux != "" {
  386. outbound.Mux = json_util.RawMessage(mux)
  387. }
  388. outbound.StreamSettings = streamSettings
  389. // Wrap the endpoint in a "servers" array (the standard Xray schema for
  390. // Shadowsocks/Trojan outbounds). The flat top-level form only parses on very
  391. // recent xray-core; older bundled cores (e.g. in v2rayN) reject it, so SS
  392. // links fail to connect. See genVnext/genVless for the VMess/VLESS shape.
  393. server := map[string]any{
  394. "address": serverData[0].Address,
  395. "port": serverData[0].Port,
  396. "password": serverData[0].Password,
  397. "level": 8,
  398. }
  399. if inbound.Protocol == model.Shadowsocks {
  400. server["method"] = serverData[0].Method
  401. }
  402. outbound.Settings = map[string]any{
  403. "servers": []any{server},
  404. }
  405. result, _ := json.MarshalIndent(outbound, "", " ")
  406. return result
  407. }
  408. func (s *SubJsonService) genHy(inbound *model.Inbound, newStream map[string]any, client model.Client, mux string) json_util.RawMessage {
  409. outbound := Outbound{}
  410. outbound.Protocol = string(inbound.Protocol)
  411. outbound.Tag = "proxy"
  412. if mux != "" {
  413. outbound.Mux = json_util.RawMessage(mux)
  414. }
  415. var settings, stream map[string]any
  416. json.Unmarshal([]byte(inbound.Settings), &settings)
  417. version, _ := settings["version"].(float64)
  418. outbound.Settings = map[string]any{
  419. "version": int(version),
  420. "address": inbound.Listen,
  421. "port": inbound.Port,
  422. }
  423. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  424. hyStream := stream["hysteriaSettings"].(map[string]any)
  425. outHyStream := map[string]any{
  426. "version": int(version),
  427. "auth": client.Auth,
  428. }
  429. if udpIdleTimeout, ok := hyStream["udpIdleTimeout"].(float64); ok {
  430. outHyStream["udpIdleTimeout"] = int(udpIdleTimeout)
  431. }
  432. if masquerade, ok := hyStream["masquerade"].(map[string]any); ok {
  433. outHyStream["masquerade"] = masquerade
  434. }
  435. newStream["hysteriaSettings"] = outHyStream
  436. if finalmask, ok := hyStream["finalmask"].(map[string]any); ok {
  437. newStream["finalmask"] = mergeFinalMask(newStream["finalmask"], finalmask)
  438. }
  439. newStream["network"] = "hysteria"
  440. newStream["security"] = "tls"
  441. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  442. result, _ := json.MarshalIndent(outbound, "", " ")
  443. return result
  444. }
  445. func mergeFinalMask(base any, extra map[string]any) map[string]any {
  446. merged := map[string]any{}
  447. if baseMap, ok := base.(map[string]any); ok {
  448. for key, value := range baseMap {
  449. switch key {
  450. case "tcp", "udp":
  451. if masks, ok := value.([]any); ok {
  452. merged[key] = append([]any(nil), masks...)
  453. }
  454. default:
  455. merged[key] = value
  456. }
  457. }
  458. }
  459. for key, value := range extra {
  460. switch key {
  461. case "tcp", "udp":
  462. baseMasks, _ := merged[key].([]any)
  463. extraMasks, _ := value.([]any)
  464. if len(extraMasks) > 0 {
  465. merged[key] = append(baseMasks, extraMasks...)
  466. }
  467. case "quicParams":
  468. if _, exists := merged[key]; !exists {
  469. merged[key] = value
  470. }
  471. default:
  472. merged[key] = value
  473. }
  474. }
  475. return merged
  476. }
  477. type Outbound struct {
  478. Protocol string `json:"protocol"`
  479. Tag string `json:"tag"`
  480. StreamSettings json_util.RawMessage `json:"streamSettings"`
  481. Mux json_util.RawMessage `json:"mux,omitempty"`
  482. Settings map[string]any `json:"settings,omitempty"`
  483. }
  484. type ServerSetting struct {
  485. Password string `json:"password"`
  486. Level int `json:"level"`
  487. Address string `json:"address"`
  488. Port int `json:"port"`
  489. Flow string `json:"flow,omitempty"`
  490. Method string `json:"method,omitempty"`
  491. }