json_service.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. externalProxies, ok := stream["externalProxy"].([]any)
  135. hasExternalProxy := ok && len(externalProxies) > 0
  136. if !hasExternalProxy {
  137. externalProxies = []any{
  138. map[string]any{
  139. "forceTls": "same",
  140. "dest": defaultDest,
  141. "port": float64(inbound.Port),
  142. "remark": "",
  143. },
  144. }
  145. }
  146. delete(stream, "externalProxy")
  147. for _, ep := range externalProxies {
  148. extPrxy := ep.(map[string]any)
  149. // Expand the host's {{VAR}} remark template for this client (no-op for
  150. // the synthetic/legacy entry) before it's used as the config remark.
  151. subReq.renderHostRemark(inbound, client, extPrxy)
  152. inbound.Listen = extPrxy["dest"].(string)
  153. inbound.Port = int(extPrxy["port"].(float64))
  154. newStream := cloneStreamForExternalProxy(stream)
  155. switch extPrxy["forceTls"].(string) {
  156. case "tls":
  157. if newStream["security"] != "tls" {
  158. newStream["security"] = "tls"
  159. newStream["tlsSettings"] = map[string]any{}
  160. }
  161. case "none":
  162. if newStream["security"] != "none" {
  163. newStream["security"] = "none"
  164. delete(newStream, "tlsSettings")
  165. }
  166. }
  167. security, _ := newStream["security"].(string)
  168. if hasExternalProxy {
  169. applyExternalProxyTLSToStream(extPrxy, newStream, security)
  170. }
  171. applyHostStreamOverrides(extPrxy, newStream)
  172. streamSettings, _ := json.MarshalIndent(newStream, "", " ")
  173. hostMux := hostMuxOverride(extPrxy)
  174. var newOutbounds []json_util.RawMessage
  175. switch inbound.Protocol {
  176. case "vmess":
  177. newOutbounds = append(newOutbounds, s.genVnext(inbound, streamSettings, client, hostMux))
  178. case "vless":
  179. newOutbounds = append(newOutbounds, s.genVless(inbound, streamSettings, client, hostMux))
  180. case "trojan", "shadowsocks":
  181. newOutbounds = append(newOutbounds, s.genServer(inbound, streamSettings, client, hostMux))
  182. case "hysteria":
  183. newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client))
  184. }
  185. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  186. newConfigJson := make(map[string]any)
  187. maps.Copy(newConfigJson, s.configJson)
  188. newConfigJson["outbounds"] = newOutbounds
  189. newConfigJson["remarks"] = subReq.endpointRemark(inbound, client.Email, extPrxy)
  190. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  191. newJsonArray = append(newJsonArray, newConfig)
  192. }
  193. return newJsonArray
  194. }
  195. func (s *SubJsonService) streamData(stream string) map[string]any {
  196. var streamSettings map[string]any
  197. json.Unmarshal([]byte(stream), &streamSettings)
  198. security, _ := streamSettings["security"].(string)
  199. switch security {
  200. case "tls":
  201. streamSettings["tlsSettings"] = s.tlsData(streamSettings["tlsSettings"].(map[string]any))
  202. case "reality":
  203. streamSettings["realitySettings"] = s.realityData(streamSettings["realitySettings"].(map[string]any))
  204. }
  205. delete(streamSettings, "sockopt")
  206. if s.finalMask != "" {
  207. s.applyGlobalFinalMask(streamSettings)
  208. }
  209. // remove proxy protocol
  210. network, _ := streamSettings["network"].(string)
  211. switch network {
  212. case "tcp":
  213. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  214. case "ws":
  215. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  216. case "httpupgrade":
  217. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  218. case "xhttp":
  219. streamSettings["xhttpSettings"] = s.removeAcceptProxy(streamSettings["xhttpSettings"])
  220. if xhttp, ok := streamSettings["xhttpSettings"].(map[string]any); ok {
  221. delete(xhttp, "noSSEHeader")
  222. delete(xhttp, "scMaxBufferedPosts")
  223. delete(xhttp, "scStreamUpServerSecs")
  224. delete(xhttp, "serverMaxHeaderBytes")
  225. // Values matching xray-core's own defaults stay off the wire:
  226. // old panels seeded them into every stored config and the
  227. // literal scMinPostsIntervalMs=30 is a DPI fingerprint (#5141).
  228. if v, _ := xhttp["scMaxEachPostBytes"].(string); v == "" || v == "1000000" {
  229. delete(xhttp, "scMaxEachPostBytes")
  230. }
  231. if v, _ := xhttp["scMinPostsIntervalMs"].(string); v == "" || v == "30" {
  232. delete(xhttp, "scMinPostsIntervalMs")
  233. }
  234. }
  235. }
  236. return streamSettings
  237. }
  238. func (s *SubJsonService) applyGlobalFinalMask(streamSettings map[string]any) {
  239. var fm map[string]any
  240. if err := json.Unmarshal([]byte(s.finalMask), &fm); err != nil || len(fm) == 0 {
  241. return
  242. }
  243. merged := mergeFinalMask(streamSettings["finalmask"], fm)
  244. if len(merged) > 0 {
  245. streamSettings["finalmask"] = merged
  246. }
  247. }
  248. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  249. netSettings, ok := setting.(map[string]any)
  250. if ok {
  251. delete(netSettings, "acceptProxyProtocol")
  252. }
  253. return netSettings
  254. }
  255. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  256. tlsData := make(map[string]any, 1)
  257. tlsClientSettings, _ := tData["settings"].(map[string]any)
  258. tlsData["serverName"] = tData["serverName"]
  259. tlsData["alpn"] = tData["alpn"]
  260. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  261. tlsData["fingerprint"] = fingerprint
  262. }
  263. if ech, ok := tlsClientSettings["echConfigList"].(string); ok && ech != "" {
  264. tlsData["echConfigList"] = ech
  265. }
  266. if pins, ok := tlsClientSettings["pinnedPeerCertSha256"].([]any); ok && len(pins) > 0 {
  267. tlsData["pinnedPeerCertSha256"] = pins
  268. }
  269. return tlsData
  270. }
  271. func (s *SubJsonService) realityData(rData map[string]any) map[string]any {
  272. rltyData := make(map[string]any, 1)
  273. rltyClientSettings, _ := rData["settings"].(map[string]any)
  274. rltyData["show"] = false
  275. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  276. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  277. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  278. // Set random data
  279. rltyData["spiderX"] = "/" + random.Seq(15)
  280. shortIds, ok := rData["shortIds"].([]any)
  281. if ok && len(shortIds) > 0 {
  282. rltyData["shortId"] = shortIds[random.Num(len(shortIds))].(string)
  283. } else {
  284. rltyData["shortId"] = ""
  285. }
  286. serverNames, ok := rData["serverNames"].([]any)
  287. if ok && len(serverNames) > 0 {
  288. rltyData["serverName"] = serverNames[random.Num(len(serverNames))].(string)
  289. } else {
  290. rltyData["serverName"] = ""
  291. }
  292. return rltyData
  293. }
  294. // jsonMux picks the per-host mux override when present, else the global mux.
  295. func jsonMux(global, override string) string {
  296. if override != "" {
  297. return override
  298. }
  299. return global
  300. }
  301. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, muxOverride string) json_util.RawMessage {
  302. outbound := Outbound{}
  303. outbound.Protocol = string(inbound.Protocol)
  304. outbound.Tag = "proxy"
  305. if mux := jsonMux(s.mux, muxOverride); mux != "" {
  306. outbound.Mux = json_util.RawMessage(mux)
  307. }
  308. outbound.StreamSettings = streamSettings
  309. security := client.Security
  310. if security == "" {
  311. security = "auto"
  312. }
  313. outbound.Settings = map[string]any{
  314. "address": inbound.Listen,
  315. "port": inbound.Port,
  316. "id": client.ID,
  317. "security": security,
  318. "level": 8,
  319. }
  320. result, _ := json.MarshalIndent(outbound, "", " ")
  321. return result
  322. }
  323. func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, muxOverride string) json_util.RawMessage {
  324. outbound := Outbound{}
  325. outbound.Protocol = string(inbound.Protocol)
  326. outbound.Tag = "proxy"
  327. if mux := jsonMux(s.mux, muxOverride); mux != "" {
  328. outbound.Mux = json_util.RawMessage(mux)
  329. }
  330. outbound.StreamSettings = streamSettings
  331. // Add encryption for VLESS outbound from inbound settings
  332. var inboundSettings map[string]any
  333. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  334. encryption, _ := inboundSettings["encryption"].(string)
  335. settings := map[string]any{
  336. "address": inbound.Listen,
  337. "port": inbound.Port,
  338. "id": client.ID,
  339. "encryption": encryption,
  340. "level": 8,
  341. }
  342. if client.Flow != "" {
  343. settings["flow"] = client.Flow
  344. }
  345. outbound.Settings = settings
  346. result, _ := json.MarshalIndent(outbound, "", " ")
  347. return result
  348. }
  349. func (s *SubJsonService) genServer(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, muxOverride string) json_util.RawMessage {
  350. outbound := Outbound{}
  351. serverData := make([]ServerSetting, 1)
  352. serverData[0] = ServerSetting{
  353. Address: inbound.Listen,
  354. Port: inbound.Port,
  355. Level: 8,
  356. Password: client.Password,
  357. }
  358. if inbound.Protocol == model.Shadowsocks {
  359. var inboundSettings map[string]any
  360. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  361. method, _ := inboundSettings["method"].(string)
  362. serverData[0].Method = method
  363. // server password in multi-user 2022 protocols
  364. if strings.HasPrefix(method, "2022") {
  365. if serverPassword, ok := inboundSettings["password"].(string); ok {
  366. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  367. }
  368. }
  369. }
  370. outbound.Protocol = string(inbound.Protocol)
  371. outbound.Tag = "proxy"
  372. if mux := jsonMux(s.mux, muxOverride); mux != "" {
  373. outbound.Mux = json_util.RawMessage(mux)
  374. }
  375. outbound.StreamSettings = streamSettings
  376. settings := map[string]any{
  377. "address": serverData[0].Address,
  378. "port": serverData[0].Port,
  379. "password": serverData[0].Password,
  380. "level": 8,
  381. }
  382. if inbound.Protocol == model.Shadowsocks {
  383. settings["method"] = serverData[0].Method
  384. }
  385. outbound.Settings = settings
  386. result, _ := json.MarshalIndent(outbound, "", " ")
  387. return result
  388. }
  389. func (s *SubJsonService) genHy(inbound *model.Inbound, newStream map[string]any, client model.Client) json_util.RawMessage {
  390. outbound := Outbound{}
  391. outbound.Protocol = string(inbound.Protocol)
  392. outbound.Tag = "proxy"
  393. if s.mux != "" {
  394. outbound.Mux = json_util.RawMessage(s.mux)
  395. }
  396. var settings, stream map[string]any
  397. json.Unmarshal([]byte(inbound.Settings), &settings)
  398. version, _ := settings["version"].(float64)
  399. outbound.Settings = map[string]any{
  400. "version": int(version),
  401. "address": inbound.Listen,
  402. "port": inbound.Port,
  403. }
  404. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  405. hyStream := stream["hysteriaSettings"].(map[string]any)
  406. outHyStream := map[string]any{
  407. "version": int(version),
  408. "auth": client.Auth,
  409. }
  410. if udpIdleTimeout, ok := hyStream["udpIdleTimeout"].(float64); ok {
  411. outHyStream["udpIdleTimeout"] = int(udpIdleTimeout)
  412. }
  413. if masquerade, ok := hyStream["masquerade"].(map[string]any); ok {
  414. outHyStream["masquerade"] = masquerade
  415. }
  416. newStream["hysteriaSettings"] = outHyStream
  417. if finalmask, ok := hyStream["finalmask"].(map[string]any); ok {
  418. newStream["finalmask"] = mergeFinalMask(newStream["finalmask"], finalmask)
  419. }
  420. newStream["network"] = "hysteria"
  421. newStream["security"] = "tls"
  422. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  423. result, _ := json.MarshalIndent(outbound, "", " ")
  424. return result
  425. }
  426. func mergeFinalMask(base any, extra map[string]any) map[string]any {
  427. merged := map[string]any{}
  428. if baseMap, ok := base.(map[string]any); ok {
  429. for key, value := range baseMap {
  430. switch key {
  431. case "tcp", "udp":
  432. if masks, ok := value.([]any); ok {
  433. merged[key] = append([]any(nil), masks...)
  434. }
  435. default:
  436. merged[key] = value
  437. }
  438. }
  439. }
  440. for key, value := range extra {
  441. switch key {
  442. case "tcp", "udp":
  443. baseMasks, _ := merged[key].([]any)
  444. extraMasks, _ := value.([]any)
  445. if len(extraMasks) > 0 {
  446. merged[key] = append(baseMasks, extraMasks...)
  447. }
  448. case "quicParams":
  449. if _, exists := merged[key]; !exists {
  450. merged[key] = value
  451. }
  452. default:
  453. merged[key] = value
  454. }
  455. }
  456. return merged
  457. }
  458. type Outbound struct {
  459. Protocol string `json:"protocol"`
  460. Tag string `json:"tag"`
  461. StreamSettings json_util.RawMessage `json:"streamSettings"`
  462. Mux json_util.RawMessage `json:"mux,omitempty"`
  463. Settings map[string]any `json:"settings,omitempty"`
  464. }
  465. type ServerSetting struct {
  466. Password string `json:"password"`
  467. Level int `json:"level"`
  468. Address string `json:"address"`
  469. Port int `json:"port"`
  470. Flow string `json:"flow,omitempty"`
  471. Method string `json:"method,omitempty"`
  472. }