json_service.go 16 KB

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