1
0

subJsonService.go 14 KB

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