json_service.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. // Set per-request state on the shared SubService so any
  53. // resolveInboundAddress call inside picks node-aware host values.
  54. s.SubService.PrepareForRequest(host)
  55. inbounds, err := s.SubService.getInboundsBySubId(subId)
  56. if err != nil || len(inbounds) == 0 {
  57. return "", "", err
  58. }
  59. var header string
  60. var configArray []json_util.RawMessage
  61. seenEmails := make(map[string]struct{})
  62. // Prepare Inbounds
  63. for _, inbound := range inbounds {
  64. clients := s.SubService.matchingClients(inbound, subId)
  65. if len(clients) == 0 {
  66. continue
  67. }
  68. s.SubService.projectThroughFallbackMaster(inbound)
  69. for _, client := range clients {
  70. seenEmails[client.Email] = struct{}{}
  71. configArray = append(configArray, s.getConfig(inbound, client, host)...)
  72. }
  73. }
  74. if len(configArray) == 0 {
  75. return "", "", nil
  76. }
  77. emails := make([]string, 0, len(seenEmails))
  78. for e := range seenEmails {
  79. emails = append(emails, e)
  80. }
  81. traffic, _ := s.SubService.AggregateTrafficByEmails(emails)
  82. // Combile outbounds
  83. var finalJson []byte
  84. if len(configArray) == 1 {
  85. finalJson, _ = json.MarshalIndent(configArray[0], "", " ")
  86. } else {
  87. finalJson, _ = json.MarshalIndent(configArray, "", " ")
  88. }
  89. header = fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  90. return string(finalJson), header, nil
  91. }
  92. func (s *SubJsonService) getConfig(inbound *model.Inbound, client model.Client, host string) []json_util.RawMessage {
  93. var newJsonArray []json_util.RawMessage
  94. stream := s.streamData(inbound.StreamSettings)
  95. // When externalProxy is empty the JSON config falls back to a
  96. // synthetic one whose `dest` is the host the client connects to.
  97. // For node-managed inbounds we want the node's address — request
  98. // host won't reach the right xray. resolveInboundAddress already
  99. // implements the node→subscriber-host fallback chain.
  100. defaultDest := s.SubService.resolveInboundAddress(inbound)
  101. if defaultDest == "" {
  102. defaultDest = host
  103. }
  104. externalProxies, ok := stream["externalProxy"].([]any)
  105. hasExternalProxy := ok && len(externalProxies) > 0
  106. if !hasExternalProxy {
  107. externalProxies = []any{
  108. map[string]any{
  109. "forceTls": "same",
  110. "dest": defaultDest,
  111. "port": float64(inbound.Port),
  112. "remark": "",
  113. },
  114. }
  115. }
  116. delete(stream, "externalProxy")
  117. for _, ep := range externalProxies {
  118. extPrxy := ep.(map[string]any)
  119. inbound.Listen = extPrxy["dest"].(string)
  120. inbound.Port = int(extPrxy["port"].(float64))
  121. newStream := cloneStreamForExternalProxy(stream)
  122. switch extPrxy["forceTls"].(string) {
  123. case "tls":
  124. if newStream["security"] != "tls" {
  125. newStream["security"] = "tls"
  126. newStream["tlsSettings"] = map[string]any{}
  127. }
  128. case "none":
  129. if newStream["security"] != "none" {
  130. newStream["security"] = "none"
  131. delete(newStream, "tlsSettings")
  132. }
  133. }
  134. security, _ := newStream["security"].(string)
  135. if hasExternalProxy {
  136. applyExternalProxyTLSToStream(extPrxy, newStream, security)
  137. }
  138. streamSettings, _ := json.MarshalIndent(newStream, "", " ")
  139. var newOutbounds []json_util.RawMessage
  140. switch inbound.Protocol {
  141. case "vmess":
  142. newOutbounds = append(newOutbounds, s.genVnext(inbound, streamSettings, client))
  143. case "vless":
  144. newOutbounds = append(newOutbounds, s.genVless(inbound, streamSettings, client))
  145. case "trojan", "shadowsocks":
  146. newOutbounds = append(newOutbounds, s.genServer(inbound, streamSettings, client))
  147. case "hysteria":
  148. newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client))
  149. }
  150. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  151. newConfigJson := make(map[string]any)
  152. maps.Copy(newConfigJson, s.configJson)
  153. newConfigJson["outbounds"] = newOutbounds
  154. newConfigJson["remarks"] = s.SubService.genRemark(inbound, client.Email, extPrxy["remark"].(string))
  155. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  156. newJsonArray = append(newJsonArray, newConfig)
  157. }
  158. return newJsonArray
  159. }
  160. func (s *SubJsonService) streamData(stream string) map[string]any {
  161. var streamSettings map[string]any
  162. json.Unmarshal([]byte(stream), &streamSettings)
  163. security, _ := streamSettings["security"].(string)
  164. switch security {
  165. case "tls":
  166. streamSettings["tlsSettings"] = s.tlsData(streamSettings["tlsSettings"].(map[string]any))
  167. case "reality":
  168. streamSettings["realitySettings"] = s.realityData(streamSettings["realitySettings"].(map[string]any))
  169. }
  170. delete(streamSettings, "sockopt")
  171. if s.finalMask != "" {
  172. s.applyGlobalFinalMask(streamSettings)
  173. }
  174. // remove proxy protocol
  175. network, _ := streamSettings["network"].(string)
  176. switch network {
  177. case "tcp":
  178. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  179. case "ws":
  180. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  181. case "httpupgrade":
  182. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  183. case "xhttp":
  184. streamSettings["xhttpSettings"] = s.removeAcceptProxy(streamSettings["xhttpSettings"])
  185. if xhttp, ok := streamSettings["xhttpSettings"].(map[string]any); ok {
  186. delete(xhttp, "noSSEHeader")
  187. delete(xhttp, "scMaxBufferedPosts")
  188. delete(xhttp, "scStreamUpServerSecs")
  189. delete(xhttp, "serverMaxHeaderBytes")
  190. // Values matching xray-core's own defaults stay off the wire:
  191. // old panels seeded them into every stored config and the
  192. // literal scMinPostsIntervalMs=30 is a DPI fingerprint (#5141).
  193. if v, _ := xhttp["scMaxEachPostBytes"].(string); v == "" || v == "1000000" {
  194. delete(xhttp, "scMaxEachPostBytes")
  195. }
  196. if v, _ := xhttp["scMinPostsIntervalMs"].(string); v == "" || v == "30" {
  197. delete(xhttp, "scMinPostsIntervalMs")
  198. }
  199. }
  200. }
  201. return streamSettings
  202. }
  203. func (s *SubJsonService) applyGlobalFinalMask(streamSettings map[string]any) {
  204. var fm map[string]any
  205. if err := json.Unmarshal([]byte(s.finalMask), &fm); err != nil || len(fm) == 0 {
  206. return
  207. }
  208. merged := mergeFinalMask(streamSettings["finalmask"], fm)
  209. if len(merged) > 0 {
  210. streamSettings["finalmask"] = merged
  211. }
  212. }
  213. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  214. netSettings, ok := setting.(map[string]any)
  215. if ok {
  216. delete(netSettings, "acceptProxyProtocol")
  217. }
  218. return netSettings
  219. }
  220. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  221. tlsData := make(map[string]any, 1)
  222. tlsClientSettings, _ := tData["settings"].(map[string]any)
  223. tlsData["serverName"] = tData["serverName"]
  224. tlsData["alpn"] = tData["alpn"]
  225. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  226. tlsData["fingerprint"] = fingerprint
  227. }
  228. if ech, ok := tlsClientSettings["echConfigList"].(string); ok && ech != "" {
  229. tlsData["echConfigList"] = ech
  230. }
  231. if pins, ok := tlsClientSettings["pinnedPeerCertSha256"].([]any); ok && len(pins) > 0 {
  232. tlsData["pinnedPeerCertSha256"] = pins
  233. }
  234. return tlsData
  235. }
  236. func (s *SubJsonService) realityData(rData map[string]any) map[string]any {
  237. rltyData := make(map[string]any, 1)
  238. rltyClientSettings, _ := rData["settings"].(map[string]any)
  239. rltyData["show"] = false
  240. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  241. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  242. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  243. // Set random data
  244. rltyData["spiderX"] = "/" + random.Seq(15)
  245. shortIds, ok := rData["shortIds"].([]any)
  246. if ok && len(shortIds) > 0 {
  247. rltyData["shortId"] = shortIds[random.Num(len(shortIds))].(string)
  248. } else {
  249. rltyData["shortId"] = ""
  250. }
  251. serverNames, ok := rData["serverNames"].([]any)
  252. if ok && len(serverNames) > 0 {
  253. rltyData["serverName"] = serverNames[random.Num(len(serverNames))].(string)
  254. } else {
  255. rltyData["serverName"] = ""
  256. }
  257. return rltyData
  258. }
  259. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  260. outbound := Outbound{}
  261. outbound.Protocol = string(inbound.Protocol)
  262. outbound.Tag = "proxy"
  263. if s.mux != "" {
  264. outbound.Mux = json_util.RawMessage(s.mux)
  265. }
  266. outbound.StreamSettings = streamSettings
  267. security := client.Security
  268. if security == "" {
  269. security = "auto"
  270. }
  271. outbound.Settings = map[string]any{
  272. "address": inbound.Listen,
  273. "port": inbound.Port,
  274. "id": client.ID,
  275. "security": security,
  276. "level": 8,
  277. }
  278. result, _ := json.MarshalIndent(outbound, "", " ")
  279. return result
  280. }
  281. func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  282. outbound := Outbound{}
  283. outbound.Protocol = string(inbound.Protocol)
  284. outbound.Tag = "proxy"
  285. if s.mux != "" {
  286. outbound.Mux = json_util.RawMessage(s.mux)
  287. }
  288. outbound.StreamSettings = streamSettings
  289. // Add encryption for VLESS outbound from inbound settings
  290. var inboundSettings map[string]any
  291. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  292. encryption, _ := inboundSettings["encryption"].(string)
  293. settings := map[string]any{
  294. "address": inbound.Listen,
  295. "port": inbound.Port,
  296. "id": client.ID,
  297. "encryption": encryption,
  298. "level": 8,
  299. }
  300. if client.Flow != "" {
  301. settings["flow"] = client.Flow
  302. }
  303. outbound.Settings = settings
  304. result, _ := json.MarshalIndent(outbound, "", " ")
  305. return result
  306. }
  307. func (s *SubJsonService) genServer(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  308. outbound := Outbound{}
  309. serverData := make([]ServerSetting, 1)
  310. serverData[0] = ServerSetting{
  311. Address: inbound.Listen,
  312. Port: inbound.Port,
  313. Level: 8,
  314. Password: client.Password,
  315. }
  316. if inbound.Protocol == model.Shadowsocks {
  317. var inboundSettings map[string]any
  318. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  319. method, _ := inboundSettings["method"].(string)
  320. serverData[0].Method = method
  321. // server password in multi-user 2022 protocols
  322. if strings.HasPrefix(method, "2022") {
  323. if serverPassword, ok := inboundSettings["password"].(string); ok {
  324. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  325. }
  326. }
  327. }
  328. outbound.Protocol = string(inbound.Protocol)
  329. outbound.Tag = "proxy"
  330. if s.mux != "" {
  331. outbound.Mux = json_util.RawMessage(s.mux)
  332. }
  333. outbound.StreamSettings = streamSettings
  334. settings := map[string]any{
  335. "address": serverData[0].Address,
  336. "port": serverData[0].Port,
  337. "password": serverData[0].Password,
  338. "level": 8,
  339. }
  340. if inbound.Protocol == model.Shadowsocks {
  341. settings["method"] = serverData[0].Method
  342. }
  343. outbound.Settings = settings
  344. result, _ := json.MarshalIndent(outbound, "", " ")
  345. return result
  346. }
  347. func (s *SubJsonService) genHy(inbound *model.Inbound, newStream map[string]any, client model.Client) json_util.RawMessage {
  348. outbound := Outbound{}
  349. outbound.Protocol = string(inbound.Protocol)
  350. outbound.Tag = "proxy"
  351. if s.mux != "" {
  352. outbound.Mux = json_util.RawMessage(s.mux)
  353. }
  354. var settings, stream map[string]any
  355. json.Unmarshal([]byte(inbound.Settings), &settings)
  356. version, _ := settings["version"].(float64)
  357. outbound.Settings = map[string]any{
  358. "version": int(version),
  359. "address": inbound.Listen,
  360. "port": inbound.Port,
  361. }
  362. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  363. hyStream := stream["hysteriaSettings"].(map[string]any)
  364. outHyStream := map[string]any{
  365. "version": int(version),
  366. "auth": client.Auth,
  367. }
  368. if udpIdleTimeout, ok := hyStream["udpIdleTimeout"].(float64); ok {
  369. outHyStream["udpIdleTimeout"] = int(udpIdleTimeout)
  370. }
  371. if masquerade, ok := hyStream["masquerade"].(map[string]any); ok {
  372. outHyStream["masquerade"] = masquerade
  373. }
  374. newStream["hysteriaSettings"] = outHyStream
  375. if finalmask, ok := hyStream["finalmask"].(map[string]any); ok {
  376. newStream["finalmask"] = mergeFinalMask(newStream["finalmask"], finalmask)
  377. }
  378. newStream["network"] = "hysteria"
  379. newStream["security"] = "tls"
  380. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  381. result, _ := json.MarshalIndent(outbound, "", " ")
  382. return result
  383. }
  384. func mergeFinalMask(base any, extra map[string]any) map[string]any {
  385. merged := map[string]any{}
  386. if baseMap, ok := base.(map[string]any); ok {
  387. for key, value := range baseMap {
  388. switch key {
  389. case "tcp", "udp":
  390. if masks, ok := value.([]any); ok {
  391. merged[key] = append([]any(nil), masks...)
  392. }
  393. default:
  394. merged[key] = value
  395. }
  396. }
  397. }
  398. for key, value := range extra {
  399. switch key {
  400. case "tcp", "udp":
  401. baseMasks, _ := merged[key].([]any)
  402. extraMasks, _ := value.([]any)
  403. if len(extraMasks) > 0 {
  404. merged[key] = append(baseMasks, extraMasks...)
  405. }
  406. case "quicParams":
  407. if _, exists := merged[key]; !exists {
  408. merged[key] = value
  409. }
  410. default:
  411. merged[key] = value
  412. }
  413. }
  414. return merged
  415. }
  416. type Outbound struct {
  417. Protocol string `json:"protocol"`
  418. Tag string `json:"tag"`
  419. StreamSettings json_util.RawMessage `json:"streamSettings"`
  420. Mux json_util.RawMessage `json:"mux,omitempty"`
  421. Settings map[string]any `json:"settings,omitempty"`
  422. }
  423. type ServerSetting struct {
  424. Password string `json:"password"`
  425. Level int `json:"level"`
  426. Address string `json:"address"`
  427. Port int `json:"port"`
  428. Flow string `json:"flow,omitempty"`
  429. Method string `json:"method,omitempty"`
  430. }