1
0

subJsonService.go 14 KB

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