json_service.go 15 KB

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