1
0

clash_service.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  1. package sub
  2. import (
  3. "encoding/hex"
  4. "errors"
  5. "fmt"
  6. "maps"
  7. "net/netip"
  8. "slices"
  9. "strings"
  10. "github.com/goccy/go-json"
  11. yaml "github.com/goccy/go-yaml"
  12. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. "github.com/mhsanaei/3x-ui/v3/internal/tuic"
  15. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  16. )
  17. type SubClashService struct {
  18. enableRouting bool
  19. clashRules string
  20. SubService *SubService
  21. }
  22. var errNoLegacyClashProxies = errors.New("no Clash for Windows-compatible proxies found; use the Mihomo subscription for modern proxy types")
  23. func NewSubClashService(enableRouting bool, clashRules string, subService *SubService) *SubClashService {
  24. return &SubClashService{enableRouting: enableRouting, clashRules: clashRules, SubService: subService}
  25. }
  26. func (s *SubClashService) GetClash(subId string, host string) (string, string, error) {
  27. return s.getClash(subId, host, false)
  28. }
  29. func (s *SubClashService) GetClashLegacy(subId string, host string) (string, string, error) {
  30. return s.getClash(subId, host, true)
  31. }
  32. func (s *SubClashService) getClash(subId string, host string, legacy bool) (string, string, error) {
  33. subReq := s.SubService.ForRequest(host)
  34. subReq.subscriptionBody = true
  35. inbounds, err := subReq.getInboundsBySubId(subId)
  36. if err != nil {
  37. return "", "", err
  38. }
  39. externalLinks, err := subReq.getClientExternalLinksBySubId(subId)
  40. if err != nil {
  41. return "", "", err
  42. }
  43. if len(inbounds) == 0 && len(externalLinks) == 0 {
  44. return "", "", nil
  45. }
  46. var proxies []map[string]any
  47. var hasInactiveExternal bool
  48. var hasEnabledClient bool
  49. seenEmails := make(map[string]struct{})
  50. for _, inbound := range inbounds {
  51. clients := subReq.matchingClients(inbound, subId)
  52. if len(clients) == 0 {
  53. continue
  54. }
  55. if inbound.ExcludeFromSub {
  56. if countHiddenClients(clients, seenEmails) {
  57. hasEnabledClient = true
  58. }
  59. continue
  60. }
  61. subReq.projectThroughFallbackMaster(inbound)
  62. if hostEps := subReq.hostEndpoints(inbound, "clash"); len(hostEps) > 0 {
  63. injectExternalProxy(inbound, hostEps)
  64. }
  65. for _, client := range clients {
  66. if client.Enable {
  67. hasEnabledClient = true
  68. }
  69. seenEmails[client.Email] = struct{}{}
  70. proxies = append(proxies, s.getProxies(subReq, inbound, client, host)...)
  71. }
  72. }
  73. for _, ext := range externalLinks {
  74. if ext.Enable {
  75. hasEnabledClient = true
  76. }
  77. // Count the client even when no proxy comes out of this link, so the
  78. // quota header does not shrink because a node is unrepresentable in Clash.
  79. seenEmails[ext.Email] = struct{}{}
  80. if !ext.Active {
  81. hasInactiveExternal = true
  82. continue
  83. }
  84. for _, el := range expandEntry(ext) {
  85. name := el.Name
  86. if name == "" {
  87. name = ext.Email
  88. }
  89. if proxy := s.clashProxyFromExternal(el.Link, name); proxy != nil {
  90. proxies = append(proxies, proxy)
  91. }
  92. }
  93. }
  94. if len(proxies) == 0 && !hasInactiveExternal {
  95. return "", "", nil
  96. }
  97. if legacy {
  98. proxies = legacyClashProxies(proxies)
  99. if len(proxies) == 0 {
  100. return "", "", errNoLegacyClashProxies
  101. }
  102. }
  103. emails := make([]string, 0, len(seenEmails))
  104. for e := range seenEmails {
  105. emails = append(emails, e)
  106. }
  107. slices.Sort(emails)
  108. traffic, _ := subReq.AggregateTrafficByEmails(emails)
  109. traffic.Enable = hasEnabledClient
  110. header := subReq.subscriptionUserinfo(traffic)
  111. if mode, remark := subReq.resolveInfoNodeRemark(subId, emails, traffic, len(proxies) > 0); mode != infoNodeNone {
  112. dummyProxy := map[string]any{
  113. "name": remark,
  114. "type": "socks5",
  115. "server": "127.0.0.1",
  116. "port": 1080,
  117. }
  118. if mode == infoNodeExpired || mode == infoNodeDepleted {
  119. proxies = []map[string]any{dummyProxy}
  120. } else {
  121. proxies = append([]map[string]any{dummyProxy}, proxies...)
  122. }
  123. }
  124. if len(proxies) == 0 {
  125. return "", header, nil
  126. }
  127. ensureUniqueProxyNames(proxies)
  128. proxyNames := make([]string, 0, len(proxies)+1)
  129. for _, proxy := range proxies {
  130. if isDummyProxy(proxy) && len(proxies) > 1 {
  131. continue
  132. }
  133. if name, ok := proxy["name"].(string); ok && name != "" {
  134. proxyNames = append(proxyNames, name)
  135. }
  136. }
  137. proxyNames = append(proxyNames, "DIRECT")
  138. config := map[string]any{
  139. "proxies": proxies,
  140. "proxy-groups": []map[string]any{{
  141. "name": "PROXY",
  142. "type": "select",
  143. "proxies": proxyNames,
  144. }},
  145. "rules": []string{"MATCH,PROXY"},
  146. }
  147. // Custom Clash routing can inject Mihomo-only groups, rules, providers or a
  148. // top-level proxies key — exactly what the legacy filter just removed.
  149. if s.enableRouting && !legacy {
  150. resolved, remoteDocument, remote, resolveErr := resolveClashRoutingSource(s.clashRules)
  151. if resolveErr == nil && strings.TrimSpace(resolved) != "" {
  152. if remote {
  153. if err := mergeRemoteClashRules(config, remoteDocument); err != nil {
  154. return "", "", err
  155. }
  156. } else if err := mergeClashRulesYAML(config, resolved); err != nil {
  157. return "", "", err
  158. }
  159. }
  160. }
  161. finalYAML, err := marshalClashYAML(config)
  162. if err != nil {
  163. return "", "", err
  164. }
  165. return string(finalYAML), header, nil
  166. }
  167. func legacyClashProxies(proxies []map[string]any) []map[string]any {
  168. compatible := make([]map[string]any, 0, len(proxies))
  169. for _, proxy := range proxies {
  170. if filtered := legacyClashProxy(proxy); filtered != nil {
  171. compatible = append(compatible, filtered)
  172. }
  173. }
  174. return compatible
  175. }
  176. func legacyClashProxy(proxy map[string]any) map[string]any {
  177. proxyType, _ := proxy["type"].(string)
  178. network, _ := proxy["network"].(string)
  179. if _, reality := proxy["reality-opts"]; reality {
  180. return nil
  181. }
  182. var fields []string
  183. var cipher string
  184. switch proxyType {
  185. case "vmess":
  186. if !legacyClashNetwork(network) || !legacyVmessCipher(proxy["cipher"]) {
  187. return nil
  188. }
  189. fields = []string{
  190. "name", "type", "server", "port", "uuid", "alterId", "cipher", "udp",
  191. "network", "tls", "skip-cert-verify", "servername", "grpc-opts", "ws-opts",
  192. }
  193. case "trojan":
  194. tls, _ := proxy["tls"].(bool)
  195. if !tls || !legacyClashNetwork(network) {
  196. return nil
  197. }
  198. fields = []string{
  199. "name", "type", "server", "port", "password", "alpn", "sni", "skip-cert-verify",
  200. "udp", "network", "grpc-opts", "ws-opts",
  201. }
  202. case "ss":
  203. tls, _ := proxy["tls"].(bool)
  204. cipher = legacyShadowsocksCipher(proxy["cipher"])
  205. if (network != "" && network != "tcp") || tls || cipher == "" {
  206. return nil
  207. }
  208. fields = []string{"name", "type", "server", "port", "password", "cipher", "udp", "plugin", "plugin-opts"}
  209. default:
  210. return nil
  211. }
  212. filtered := make(map[string]any, len(fields))
  213. for _, field := range fields {
  214. if value, exists := proxy[field]; exists {
  215. filtered[field] = value
  216. }
  217. }
  218. if proxyType == "ss" {
  219. filtered["cipher"] = cipher
  220. }
  221. return filtered
  222. }
  223. func legacyClashNetwork(network string) bool {
  224. switch network {
  225. case "", "tcp", "ws", "grpc":
  226. return true
  227. default:
  228. return false
  229. }
  230. }
  231. func legacyVmessCipher(value any) bool {
  232. cipher, _ := value.(string)
  233. switch strings.ToLower(strings.TrimSpace(cipher)) {
  234. case "auto", "aes-128-gcm", "chacha20-poly1305", "none":
  235. return true
  236. default:
  237. return false
  238. }
  239. }
  240. func legacyShadowsocksCipher(value any) string {
  241. cipher, _ := value.(string)
  242. cipher = strings.ToLower(strings.TrimSpace(cipher))
  243. switch cipher {
  244. case "chacha20-poly1305":
  245. return "chacha20-ietf-poly1305"
  246. case "aes-128-gcm", "aes-192-gcm", "aes-256-gcm",
  247. "aes-128-cfb", "aes-192-cfb", "aes-256-cfb",
  248. "aes-128-ctr", "aes-192-ctr", "aes-256-ctr",
  249. "rc4-md5", "chacha20-ietf", "xchacha20",
  250. "chacha20-ietf-poly1305", "xchacha20-ietf-poly1305":
  251. return cipher
  252. default:
  253. return ""
  254. }
  255. }
  256. // ensureUniqueProxyNames keeps every proxy "name" non-empty and unique:
  257. // mihomo rejects the whole config on a duplicate name (the empty string
  258. // genRemark returns for a remark-less inbound counts), vanishing the Clash
  259. // profile on refresh. See issue #4641.
  260. func ensureUniqueProxyNames(proxies []map[string]any) {
  261. seen := make(map[string]struct{}, len(proxies))
  262. for i, proxy := range proxies {
  263. base, _ := proxy["name"].(string)
  264. if base == "" {
  265. base = fallbackProxyName(proxy, i)
  266. }
  267. name := base
  268. for n := 2; ; n++ {
  269. if _, dup := seen[name]; !dup {
  270. break
  271. }
  272. name = fmt.Sprintf("%s-%d", base, n)
  273. }
  274. seen[name] = struct{}{}
  275. proxy["name"] = name
  276. }
  277. }
  278. func isDummyProxy(proxy map[string]any) bool {
  279. typ, _ := proxy["type"].(string)
  280. server, _ := proxy["server"].(string)
  281. var port int
  282. switch p := proxy["port"].(type) {
  283. case int:
  284. port = p
  285. case float64:
  286. port = int(p)
  287. }
  288. return typ == "socks5" && server == "127.0.0.1" && port == 1080
  289. }
  290. func fallbackProxyName(proxy map[string]any, idx int) string {
  291. typ, _ := proxy["type"].(string)
  292. server, _ := proxy["server"].(string)
  293. if typ != "" && server != "" {
  294. return fmt.Sprintf("%s-%s-%v", typ, server, proxy["port"])
  295. }
  296. return fmt.Sprintf("proxy-%d", idx+1)
  297. }
  298. func (s *SubClashService) getProxies(subReq *SubService, inbound *model.Inbound, client model.Client, host string) []map[string]any {
  299. stream := s.streamData(inbound.StreamSettings)
  300. // For node-managed inbounds the Clash proxy "server" must be the
  301. // node's address, not the request host. resolveInboundAddress handles
  302. // the node→subscriber-host fallback chain.
  303. defaultDest := subReq.resolveInboundAddress(inbound)
  304. if defaultDest == "" {
  305. defaultDest = host
  306. }
  307. externalProxies, ok := stream["externalProxy"].([]any)
  308. hasExternalProxy := ok && len(externalProxies) > 0
  309. if !hasExternalProxy {
  310. externalProxies = []any{map[string]any{
  311. "forceTls": "same",
  312. "dest": defaultDest,
  313. "port": float64(inbound.Port),
  314. "remark": "",
  315. }}
  316. }
  317. delete(stream, "externalProxy")
  318. network, _ := stream["network"].(string)
  319. proxies := make([]map[string]any, 0, len(externalProxies))
  320. for _, ep := range externalProxies {
  321. extPrxy, ok := ep.(map[string]any)
  322. if !ok {
  323. continue
  324. }
  325. // Expand the host's {{VAR}} remark template for this client (no-op for
  326. // the synthetic/legacy entry) before it becomes the proxy name.
  327. subReq.renderHostRemark(inbound, client, extPrxy, network)
  328. workingInbound := *inbound
  329. // A Clash "server" is a bare host, not a URI authority, and the custom
  330. // share address stores IPv6 literals bracketed.
  331. dest, _ := extPrxy["dest"].(string)
  332. workingInbound.Listen = strings.Trim(dest, "[]")
  333. if port, ok := extPrxy["port"].(float64); ok {
  334. workingInbound.Port = int(port)
  335. }
  336. workingStream := cloneStreamForExternalProxy(stream)
  337. forceTls, _ := extPrxy["forceTls"].(string)
  338. switch forceTls {
  339. case "tls":
  340. if workingStream["security"] != "tls" {
  341. workingStream["security"] = "tls"
  342. workingStream["tlsSettings"] = map[string]any{}
  343. }
  344. case "none":
  345. if workingStream["security"] != "none" {
  346. workingStream["security"] = "none"
  347. delete(workingStream, "tlsSettings")
  348. delete(workingStream, "realitySettings")
  349. }
  350. }
  351. security, _ := workingStream["security"].(string)
  352. if hasExternalProxy {
  353. applyExternalProxyTLSToStream(extPrxy, workingStream, security)
  354. }
  355. applyHostStreamOverrides(extPrxy, workingStream)
  356. proxy := s.buildProxy(subReq, &workingInbound, client, workingStream, extPrxy)
  357. if len(proxy) > 0 {
  358. // Host-only mihomo knob: ip-version is a top-level proxy field, set
  359. // last so it cannot be clobbered. Absent for legacy externalProxy.
  360. if v, _ := extPrxy["mihomoIpVersion"].(string); v != "" {
  361. proxy["ip-version"] = v
  362. }
  363. proxies = append(proxies, proxy)
  364. }
  365. }
  366. return proxies
  367. }
  368. func (s *SubClashService) buildProxy(subReq *SubService, inbound *model.Inbound, client model.Client, stream map[string]any, ep map[string]any) map[string]any {
  369. // Hysteria has its own transport + TLS model, applyTransport /
  370. // applySecurity don't fit.
  371. if inbound.Protocol == model.Hysteria {
  372. return s.buildHysteriaProxy(subReq, inbound, client, ep)
  373. }
  374. if inbound.Protocol == model.WireGuard {
  375. return s.buildWireguardProxy(subReq, inbound, client, ep)
  376. }
  377. if inbound.Protocol == model.TUIC {
  378. return s.buildTuicProxy(subReq, inbound, client, ep)
  379. }
  380. if inbound.Protocol == model.AmneziaWG {
  381. return s.buildAmneziaWGProxy(subReq, inbound, client, ep)
  382. }
  383. network, _ := stream["network"].(string)
  384. proxy := map[string]any{
  385. "name": subReq.endpointRemark(inbound, client.Email, ep, network),
  386. "server": inbound.Listen,
  387. "port": inbound.Port,
  388. "udp": true,
  389. }
  390. if !s.applyTransport(proxy, network, stream) {
  391. return nil
  392. }
  393. switch inbound.Protocol {
  394. case model.VMESS:
  395. proxy["type"] = "vmess"
  396. proxy["uuid"] = client.ID
  397. proxy["alterId"] = 0
  398. proxy["cipher"] = normalizeVmessSecurity(client.Security)
  399. case model.VLESS:
  400. proxy["type"] = "vless"
  401. proxy["uuid"] = applyVlessRoute(client.ID, hostVlessRoute(ep))
  402. inboundSettings := subReq.linkSettings(inbound)
  403. streamSecurity, _ := stream["security"].(string)
  404. if client.Flow != "" && !inbound.DisableFlow && vlessFlowAllowed(network, streamSecurity, inboundSettings) {
  405. proxy["flow"] = client.Flow
  406. }
  407. if encryption, ok := inboundSettings["encryption"].(string); ok {
  408. encryption = strings.TrimSpace(encryption)
  409. if encryption != "" && encryption != "none" {
  410. proxy["encryption"] = encryption
  411. }
  412. }
  413. case model.Trojan:
  414. proxy["type"] = "trojan"
  415. proxy["password"] = client.Password
  416. case model.Shadowsocks:
  417. proxy["type"] = "ss"
  418. proxy["password"] = client.Password
  419. inboundSettings := subReq.linkSettings(inbound)
  420. method, _ := inboundSettings["method"].(string)
  421. if method == "" {
  422. return nil
  423. }
  424. proxy["cipher"] = method
  425. if strings.HasPrefix(method, "2022") {
  426. if serverPassword, ok := inboundSettings["password"].(string); ok && serverPassword != "" {
  427. proxy["password"] = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  428. }
  429. }
  430. default:
  431. return nil
  432. }
  433. security, _ := stream["security"].(string)
  434. if !s.applySecurity(proxy, security, stream) {
  435. return nil
  436. }
  437. return proxy
  438. }
  439. // buildHysteriaProxy produces a mihomo-compatible Clash entry for a
  440. // Hysteria (v1) or Hysteria2 inbound. It reads `inbound.StreamSettings`
  441. // directly instead of going through streamData/tlsData, because those
  442. // helpers prune fields (like `allowInsecure` / the salamander obfs
  443. // block) that the hysteria proxy wants preserved.
  444. func (s *SubClashService) buildHysteriaProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
  445. inboundSettings := subReq.linkSettings(inbound)
  446. proxyType := "hysteria2"
  447. authKey := "password"
  448. if v, ok := inboundSettings["version"].(float64); ok && int(v) == 1 {
  449. proxyType = "hysteria"
  450. authKey = "auth-str"
  451. }
  452. proxy := map[string]any{
  453. "name": subReq.endpointRemark(inbound, client.Email, ep, "quic"),
  454. "type": proxyType,
  455. "server": inbound.Listen,
  456. "port": inbound.Port,
  457. "udp": true,
  458. authKey: client.Auth,
  459. }
  460. var rawStream map[string]any
  461. _ = json.Unmarshal([]byte(inbound.StreamSettings), &rawStream)
  462. // TLS details — hysteria always uses TLS.
  463. if tlsSettings, ok := rawStream["tlsSettings"].(map[string]any); ok {
  464. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  465. proxy["sni"] = serverName
  466. }
  467. if alpnList, ok := tlsSettings["alpn"].([]any); ok && len(alpnList) > 0 {
  468. out := make([]string, 0, len(alpnList))
  469. for _, a := range alpnList {
  470. if s, ok := a.(string); ok && s != "" {
  471. out = append(out, s)
  472. }
  473. }
  474. if len(out) > 0 {
  475. proxy["alpn"] = out
  476. }
  477. }
  478. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  479. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  480. proxy["skip-cert-verify"] = true
  481. }
  482. if fp, ok := inner["fingerprint"].(string); ok && fp != "" {
  483. proxy["client-fingerprint"] = fp
  484. }
  485. if certFingerprint := mihomoCertFingerprint(inner["pinnedPeerCertSha256"]); certFingerprint != "" {
  486. proxy["fingerprint"] = certFingerprint
  487. }
  488. }
  489. }
  490. if insecure, ok := ep["allowInsecure"].(bool); ok && insecure {
  491. proxy["skip-cert-verify"] = true
  492. }
  493. if certFingerprint := mihomoCertFingerprint(ep["pinnedPeerCertSha256"]); certFingerprint != "" {
  494. proxy["fingerprint"] = certFingerprint
  495. }
  496. // Salamander obfs (Hysteria2). Read the same finalmask.udp[salamander]
  497. // block the subscription link generator uses.
  498. if finalmask, ok := rawStream["finalmask"].(map[string]any); ok {
  499. if udpMasks, ok := finalmask["udp"].([]any); ok {
  500. for _, m := range udpMasks {
  501. mask, _ := m.(map[string]any)
  502. if mask == nil || mask["type"] != "salamander" {
  503. continue
  504. }
  505. settings, _ := mask["settings"].(map[string]any)
  506. if pw, ok := settings["password"].(string); ok && pw != "" {
  507. proxy["obfs"] = "salamander"
  508. proxy["obfs-password"] = pw
  509. break
  510. }
  511. }
  512. }
  513. }
  514. // UDP port hopping. mihomo reads the range from a dedicated `ports`
  515. // field (the base `port` stays as the redirect target).
  516. if hopPorts := hysteriaHopPorts(rawStream); hopPorts != "" {
  517. proxy["ports"] = hopPorts
  518. }
  519. return proxy
  520. }
  521. // Mihomo supports only one certificate fingerprint, so mihomoCertFingerprint
  522. // converts the first valid SHA-256 pin to its colon-separated TLS form.
  523. func mihomoCertFingerprint(value any) string {
  524. var pins []string
  525. switch typed := value.(type) {
  526. case []any:
  527. for _, item := range typed {
  528. if pin, ok := item.(string); ok {
  529. pins = append(pins, pin)
  530. }
  531. }
  532. case []string:
  533. pins = typed
  534. case string:
  535. pins = strings.Split(typed, ",")
  536. }
  537. for _, pin := range pins {
  538. normalized := hysteriaPinHex(pin)
  539. if len(normalized) != 64 {
  540. continue
  541. }
  542. if _, err := hex.DecodeString(normalized); err != nil {
  543. continue
  544. }
  545. normalized = strings.ToUpper(normalized)
  546. var out strings.Builder
  547. out.Grow(95)
  548. for i := 0; i < len(normalized); i += 2 {
  549. if i > 0 {
  550. out.WriteByte(':')
  551. }
  552. out.WriteString(normalized[i : i+2])
  553. }
  554. return out.String()
  555. }
  556. return ""
  557. }
  558. // buildWireguardProxy produces a mihomo-compatible Clash entry for a native
  559. // WireGuard inbound, mirroring genWireguardLink: the peer public key is derived
  560. // from the inbound secretKey, while the private key, tunnel address, and
  561. // pre-shared key come from the client. Returns nil when the client has no key.
  562. func (s *SubClashService) buildWireguardProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
  563. if client.PrivateKey == "" {
  564. return nil
  565. }
  566. var inboundSettings map[string]any
  567. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  568. secretKey, _ := inboundSettings["secretKey"].(string)
  569. proxy := map[string]any{
  570. "name": subReq.endpointRemark(inbound, client.Email, ep, ""),
  571. "type": "wireguard",
  572. "server": inbound.Listen,
  573. "port": inbound.Port,
  574. "udp": true,
  575. "private-key": client.PrivateKey,
  576. }
  577. if secretKey != "" {
  578. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  579. proxy["public-key"] = pub
  580. }
  581. }
  582. if client.PreSharedKey != "" {
  583. proxy["pre-shared-key"] = client.PreSharedKey
  584. }
  585. if ka := client.KeepAliveSeconds(); ka > 0 {
  586. proxy["persistent-keepalive"] = ka
  587. }
  588. for _, addr := range client.AllowedIPs {
  589. ip := stripCIDR(addr)
  590. if ip == "" {
  591. continue
  592. }
  593. if strings.Contains(ip, ":") {
  594. proxy["ipv6"] = ip
  595. } else {
  596. proxy["ip"] = ip
  597. }
  598. }
  599. if mtu, ok := inboundSettings["mtu"].(float64); ok && mtu > 0 {
  600. proxy["mtu"] = int(mtu)
  601. }
  602. if dns, _ := inboundSettings["dns"].(string); dns != "" {
  603. servers := make([]string, 0)
  604. for server := range strings.SplitSeq(dns, ",") {
  605. if server = strings.TrimSpace(server); server != "" {
  606. servers = append(servers, server)
  607. }
  608. }
  609. if len(servers) > 0 {
  610. proxy["dns"] = servers
  611. }
  612. }
  613. return proxy
  614. }
  615. func (s *SubClashService) buildTuicProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
  616. inst, ok := tuic.InstanceFromInbound(inbound)
  617. if !ok {
  618. return nil
  619. }
  620. uuid := client.ID
  621. password := client.Password
  622. for _, c := range inst.Clients {
  623. if c.Email == client.Email {
  624. if uuid == "" {
  625. uuid = c.UUID
  626. }
  627. if password == "" {
  628. password = c.Password
  629. }
  630. break
  631. }
  632. }
  633. if uuid == "" || password == "" {
  634. return nil
  635. }
  636. server := inbound.Listen
  637. if server == "" || server == "0.0.0.0" || server == "::" {
  638. server = subReq.resolveInboundAddress(inbound)
  639. }
  640. proxy := map[string]any{
  641. "name": subReq.endpointRemark(inbound, client.Email, ep, "tuic"),
  642. "type": "tuic",
  643. "server": server,
  644. "port": inbound.Port,
  645. "uuid": uuid,
  646. "password": password,
  647. "congestion-controller": inst.CongestionControl,
  648. "udp-relay-mode": inst.UDPRelayMode,
  649. "reduce-rtt": inst.ZeroRTTHandshake,
  650. }
  651. if len(inst.ALPN) > 0 {
  652. proxy["alpn"] = inst.ALPN
  653. }
  654. if inst.SNI != "" {
  655. proxy["sni"] = inst.SNI
  656. }
  657. if sni, ok := externalProxySNI(ep); ok {
  658. proxy["sni"] = sni
  659. }
  660. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  661. proxy["alpn"] = strings.Split(alpn, ",")
  662. }
  663. if ai, ok := ep["allowInsecure"].(bool); ok && ai {
  664. proxy["skip-cert-verify"] = true
  665. }
  666. return proxy
  667. }
  668. // amneziaWGClientAddresses prefers this inbound's own settings entry over the
  669. // shared clients.wg_allowed_ips column, which for an identity attached to both
  670. // a wireguard and an amneziawg inbound holds the other one's address.
  671. func amneziaWGClientAddresses(settingsClients []model.Client, client model.Client) []string {
  672. for i := range settingsClients {
  673. if !strings.EqualFold(settingsClients[i].Email, client.Email) {
  674. continue
  675. }
  676. if len(settingsClients[i].AllowedIPs) > 0 {
  677. return settingsClients[i].AllowedIPs
  678. }
  679. break
  680. }
  681. return client.AllowedIPs
  682. }
  683. // allBareIPs reports whether every entry is a plain IP address — no port,
  684. // scheme, and no zone, which mihomo brackets into a udp:// URL it then rejects.
  685. func allBareIPs(servers []string) bool {
  686. for _, s := range servers {
  687. addr, err := netip.ParseAddr(s)
  688. if err != nil || addr.Zone() != "" {
  689. return false
  690. }
  691. }
  692. return true
  693. }
  694. // buildAmneziaWGProxy emits a mihomo Clash entry for an AmneziaWG inbound:
  695. // type stays "wireguard", the obfuscation rides in amnezia-wg-option.
  696. func (s *SubClashService) buildAmneziaWGProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
  697. if client.PrivateKey == "" {
  698. return nil
  699. }
  700. var parsed amneziawg.InboundSettings
  701. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed.Server == nil {
  702. return nil
  703. }
  704. server := parsed.Server
  705. proxy := map[string]any{
  706. "name": subReq.endpointRemark(inbound, client.Email, ep, ""),
  707. "type": "wireguard",
  708. "server": inbound.Listen,
  709. "port": inbound.Port,
  710. "udp": true,
  711. "private-key": client.PrivateKey,
  712. }
  713. if server.PublicKey != "" {
  714. proxy["public-key"] = server.PublicKey
  715. }
  716. if client.PreSharedKey != "" {
  717. proxy["pre-shared-key"] = client.PreSharedKey
  718. }
  719. if ka := client.KeepAliveSeconds(); ka > 0 {
  720. proxy["persistent-keepalive"] = ka
  721. }
  722. for _, addr := range amneziaWGClientAddresses(parsed.Clients, client) {
  723. ip := stripCIDR(addr)
  724. if ip == "" {
  725. continue
  726. }
  727. if strings.Contains(ip, ":") {
  728. proxy["ipv6"] = ip
  729. } else {
  730. proxy["ip"] = ip
  731. }
  732. }
  733. // Always emitted: mihomo's own 1408 default sits above the interface
  734. // amneziawgnet actually runs once s4 passes 12, so the tunnel fragments.
  735. proxy["mtu"] = amneziawg.EffectiveMTU(server.MTU, server.S4)
  736. var dns []string
  737. if server.PrimaryDNS != "" {
  738. dns = append(dns, server.PrimaryDNS)
  739. }
  740. if server.SecondaryDNS != "" {
  741. dns = append(dns, server.SecondaryDNS)
  742. }
  743. if len(dns) > 0 {
  744. proxy["dns"] = dns
  745. // mihomo ignores dns without this flag, but aborts the whole config on
  746. // a value its dns.ParseNameServer rejects, so only bare IPs opt in.
  747. if allBareIPs(dns) {
  748. proxy["remote-dns-resolve"] = true
  749. }
  750. }
  751. awg := map[string]any{}
  752. if server.Jc != 0 {
  753. awg["jc"] = server.Jc
  754. }
  755. if server.Jmin != 0 {
  756. awg["jmin"] = server.Jmin
  757. }
  758. if server.Jmax != 0 {
  759. awg["jmax"] = server.Jmax
  760. }
  761. if server.S1 != 0 {
  762. awg["s1"] = server.S1
  763. }
  764. if server.S2 != 0 {
  765. awg["s2"] = server.S2
  766. }
  767. if server.S3 != 0 {
  768. awg["s3"] = server.S3
  769. }
  770. if server.S4 != 0 {
  771. awg["s4"] = server.S4
  772. }
  773. if server.H1 != "" {
  774. awg["h1"] = server.H1
  775. }
  776. if server.H2 != "" {
  777. awg["h2"] = server.H2
  778. }
  779. if server.H3 != "" {
  780. awg["h3"] = server.H3
  781. }
  782. if server.H4 != "" {
  783. awg["h4"] = server.H4
  784. }
  785. for i, v := range []string{server.I1, server.I2, server.I3, server.I4, server.I5} {
  786. if v != "" {
  787. awg[fmt.Sprintf("i%d", i+1)] = v
  788. }
  789. }
  790. needsV3 := false
  791. if server.HeaderProtectionKey != "" {
  792. awg["header-protection-key"] = server.HeaderProtectionKey
  793. needsV3 = true
  794. }
  795. if server.ContentPaddingAddition != "" {
  796. awg["content-padding-addition"] = server.ContentPaddingAddition
  797. needsV3 = true
  798. }
  799. if server.RekeyAfterTime != "" {
  800. awg["rekey-after-time"] = server.RekeyAfterTime
  801. needsV3 = true
  802. }
  803. if server.RekeyTimeout != "" {
  804. awg["rekey-timeout"] = server.RekeyTimeout
  805. needsV3 = true
  806. }
  807. if server.RejectAfterTime != "" {
  808. awg["reject-after-time"] = server.RejectAfterTime
  809. needsV3 = true
  810. }
  811. if server.KeepaliveTimeout != "" {
  812. awg["keepalive-timeout"] = server.KeepaliveTimeout
  813. needsV3 = true
  814. }
  815. if server.MaxHandshakeAttempts != "" {
  816. awg["max-handshake-attempts"] = server.MaxHandshakeAttempts
  817. needsV3 = true
  818. }
  819. if server.RandomTrailers {
  820. awg["random-trailers"] = true
  821. needsV3 = true
  822. }
  823. if server.DisableCookies {
  824. awg["disable-cookies"] = true
  825. needsV3 = true
  826. }
  827. if needsV3 {
  828. awg["version"] = 3
  829. }
  830. if len(awg) > 0 {
  831. proxy["amnezia-wg-option"] = awg
  832. }
  833. return proxy
  834. }
  835. // buildXhttpClashOpts converts xhttpSettings from 3x-ui's camelCase JSON
  836. // storage into the kebab-case map that Mihomo expects under xhttp-opts.
  837. //
  838. // Only client-relevant fields are included (allowlist approach).
  839. // Server-only fields (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  840. // serverMaxHeaderBytes) are automatically excluded because they are not in
  841. // the mapping. This is intentional — when Mihomo adds new fields, the mapping
  842. // must be updated explicitly rather than leaking unverified fields to clients.
  843. //
  844. // Returns nil if no non-trivial fields are present.
  845. func buildXhttpClashOpts(xhttp map[string]any) map[string]any {
  846. if xhttp == nil {
  847. return nil
  848. }
  849. opts := map[string]any{}
  850. // Direct fields: path, mode
  851. if v, ok := xhttp["path"].(string); ok && v != "" {
  852. opts["path"] = v
  853. }
  854. if v, ok := xhttp["mode"].(string); ok && v != "" {
  855. opts["mode"] = v
  856. }
  857. // Host: explicit host field wins, then fall back to headers.Host
  858. host := ""
  859. if v, ok := xhttp["host"].(string); ok && v != "" {
  860. host = v
  861. } else if headers, ok := xhttp["headers"].(map[string]any); ok {
  862. host = searchHost(headers)
  863. }
  864. if host != "" {
  865. opts["host"] = host
  866. }
  867. type xhttpStringField struct{ src, dst, skipValue string }
  868. stringFields := []xhttpStringField{
  869. {"xPaddingBytes", "x-padding-bytes", ""},
  870. {"uplinkHTTPMethod", "uplink-http-method", ""},
  871. {"sessionIDPlacement", "session-id-placement", ""},
  872. {"sessionIDKey", "session-id-key", ""},
  873. {"sessionIDTable", "session-id-table", ""},
  874. {"sessionIDLength", "session-id-length", ""},
  875. {"seqPlacement", "seq-placement", ""},
  876. {"seqKey", "seq-key", ""},
  877. {"uplinkDataPlacement", "uplink-data-placement", ""},
  878. {"uplinkDataKey", "uplink-data-key", ""},
  879. {"scMaxEachPostBytes", "sc-max-each-post-bytes", "1000000"},
  880. {"scMinPostsIntervalMs", "sc-min-posts-interval-ms", "30"},
  881. }
  882. for _, f := range stringFields {
  883. if v, ok := xhttp[f.src].(string); ok && v != "" && (f.skipValue == "" || v != f.skipValue) {
  884. opts[f.dst] = v
  885. }
  886. }
  887. // Legacy inbounds (pre xray-core #6258) stored sessionPlacement/sessionKey.
  888. // Fall back to them so not-yet-resaved configs still map. Mirrors the
  889. // frontend migration.
  890. for _, f := range []xhttpStringField{
  891. {"sessionPlacement", "session-id-placement", ""},
  892. {"sessionKey", "session-id-key", ""},
  893. } {
  894. if _, exists := opts[f.dst]; exists {
  895. continue
  896. }
  897. if v, ok := xhttp[f.src].(string); ok && v != "" {
  898. opts[f.dst] = v
  899. }
  900. }
  901. // Bool fields (truthy only)
  902. if v, ok := xhttp["noGRPCHeader"].(bool); ok && v {
  903. opts["no-grpc-header"] = true
  904. }
  905. if v, ok := xhttp["xPaddingObfsMode"].(bool); ok && v {
  906. opts["x-padding-obfs-mode"] = true
  907. // Padding obfs gated fields
  908. for _, field := range []struct{ src, dst string }{
  909. {"xPaddingKey", "x-padding-key"},
  910. {"xPaddingHeader", "x-padding-header"},
  911. {"xPaddingPlacement", "x-padding-placement"},
  912. {"xPaddingMethod", "x-padding-method"},
  913. } {
  914. if v, ok := xhttp[field.src].(string); ok && v != "" {
  915. opts[field.dst] = v
  916. }
  917. }
  918. }
  919. // Non-zero value fields
  920. if v, ok := nonZeroShareValue(xhttp["uplinkChunkSize"]); ok {
  921. opts["uplink-chunk-size"] = v
  922. }
  923. // Nested object: xmux → reuse-settings
  924. if xmux, ok := xhttp["xmux"].(map[string]any); ok && len(xmux) > 0 {
  925. reuse := map[string]any{}
  926. for _, f := range []struct{ src, dst string }{
  927. {"maxConcurrency", "max-concurrency"},
  928. {"maxConnections", "max-connections"},
  929. {"cMaxReuseTimes", "c-max-reuse-times"},
  930. {"hMaxRequestTimes", "h-max-request-times"},
  931. {"hMaxReusableSecs", "h-max-reusable-secs"},
  932. } {
  933. if v, ok := xmux[f.src].(string); ok && v != "" {
  934. reuse[f.dst] = v
  935. }
  936. }
  937. if v, ok := nonZeroShareValue(xmux["hKeepAlivePeriod"]); ok {
  938. reuse["h-keep-alive-period"] = v
  939. }
  940. if len(reuse) > 0 {
  941. opts["reuse-settings"] = reuse
  942. }
  943. }
  944. // Headers (drop Host key)
  945. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  946. out := map[string]any{}
  947. for k, v := range rawHeaders {
  948. if strings.EqualFold(k, "host") {
  949. continue
  950. }
  951. out[k] = v
  952. }
  953. if len(out) > 0 {
  954. opts["headers"] = out
  955. }
  956. }
  957. if len(opts) == 0 {
  958. return nil
  959. }
  960. return opts
  961. }
  962. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  963. switch network {
  964. case "", "tcp":
  965. proxy["network"] = "tcp"
  966. tcp, _ := stream["tcpSettings"].(map[string]any)
  967. if tcp != nil {
  968. header, _ := tcp["header"].(map[string]any)
  969. if header != nil {
  970. typeStr, _ := header["type"].(string)
  971. if typeStr != "" && typeStr != "none" {
  972. return false
  973. }
  974. }
  975. }
  976. return true
  977. case "ws":
  978. proxy["network"] = "ws"
  979. ws, _ := stream["wsSettings"].(map[string]any)
  980. wsOpts := map[string]any{}
  981. if ws != nil {
  982. if path, ok := ws["path"].(string); ok && path != "" {
  983. wsOpts["path"] = path
  984. }
  985. host := ""
  986. if v, ok := ws["host"].(string); ok && v != "" {
  987. host = v
  988. } else if headers, ok := ws["headers"].(map[string]any); ok {
  989. host = searchHost(headers)
  990. }
  991. if host != "" {
  992. wsOpts["headers"] = map[string]any{"Host": host}
  993. }
  994. }
  995. if len(wsOpts) > 0 {
  996. proxy["ws-opts"] = wsOpts
  997. }
  998. return true
  999. case "grpc":
  1000. proxy["network"] = "grpc"
  1001. grpc, _ := stream["grpcSettings"].(map[string]any)
  1002. grpcOpts := map[string]any{}
  1003. if grpc != nil {
  1004. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  1005. grpcOpts["grpc-service-name"] = serviceName
  1006. }
  1007. }
  1008. if len(grpcOpts) > 0 {
  1009. proxy["grpc-opts"] = grpcOpts
  1010. }
  1011. return true
  1012. case "httpupgrade":
  1013. proxy["network"] = "httpupgrade"
  1014. hu, _ := stream["httpupgradeSettings"].(map[string]any)
  1015. opts := map[string]any{}
  1016. if hu != nil {
  1017. if path, ok := hu["path"].(string); ok && path != "" {
  1018. opts["path"] = path
  1019. }
  1020. host := ""
  1021. if v, ok := hu["host"].(string); ok && v != "" {
  1022. host = v
  1023. } else if headers, ok := hu["headers"].(map[string]any); ok {
  1024. host = searchHost(headers)
  1025. }
  1026. if host != "" {
  1027. opts["headers"] = map[string]any{"Host": host}
  1028. }
  1029. }
  1030. if len(opts) > 0 {
  1031. proxy["http-upgrade-opts"] = opts
  1032. }
  1033. return true
  1034. case "xhttp":
  1035. proxy["network"] = "xhttp"
  1036. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  1037. opts := buildXhttpClashOpts(xhttp)
  1038. if opts != nil {
  1039. proxy["xhttp-opts"] = opts
  1040. }
  1041. return true
  1042. default:
  1043. return false
  1044. }
  1045. }
  1046. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  1047. switch security {
  1048. case "", "none":
  1049. proxy["tls"] = false
  1050. return true
  1051. case "tls":
  1052. proxy["tls"] = true
  1053. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  1054. if tlsSettings != nil {
  1055. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  1056. proxy["servername"] = serverName
  1057. switch proxy["type"] {
  1058. case "trojan":
  1059. proxy["sni"] = serverName
  1060. }
  1061. }
  1062. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  1063. proxy["client-fingerprint"] = fingerprint
  1064. }
  1065. if alpn, ok := externalProxyALPNList(tlsSettings["alpn"]); ok {
  1066. out := make([]string, 0, len(alpn))
  1067. for _, item := range alpn {
  1068. if s, ok := item.(string); ok && s != "" {
  1069. out = append(out, s)
  1070. }
  1071. }
  1072. if len(out) > 0 {
  1073. proxy["alpn"] = out
  1074. }
  1075. }
  1076. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  1077. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  1078. proxy["skip-cert-verify"] = true
  1079. }
  1080. }
  1081. if pins, ok := tlsSettings["pin-sha256"].([]any); ok && len(pins) > 0 {
  1082. proxy["pin-sha256"] = pins
  1083. }
  1084. }
  1085. return true
  1086. case "reality":
  1087. proxy["tls"] = true
  1088. realitySettings, _ := stream["realitySettings"].(map[string]any)
  1089. if realitySettings == nil {
  1090. return false
  1091. }
  1092. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  1093. proxy["servername"] = serverName
  1094. }
  1095. realityOpts := map[string]any{}
  1096. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  1097. realityOpts["public-key"] = publicKey
  1098. }
  1099. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  1100. realityOpts["short-id"] = shortID
  1101. }
  1102. if len(realityOpts) > 0 {
  1103. // Xray 26.9.8+ rejects REALITY handshakes without an ML-KEM key share.
  1104. realityOpts["support-x25519mlkem768"] = true
  1105. proxy["reality-opts"] = realityOpts
  1106. }
  1107. proxy["client-fingerprint"] = "chrome"
  1108. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  1109. proxy["client-fingerprint"] = fingerprint
  1110. }
  1111. return true
  1112. default:
  1113. return false
  1114. }
  1115. }
  1116. func (s *SubClashService) streamData(stream string) map[string]any {
  1117. var streamSettings map[string]any
  1118. _ = json.Unmarshal([]byte(stream), &streamSettings)
  1119. security, _ := streamSettings["security"].(string)
  1120. switch security {
  1121. case "tls":
  1122. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  1123. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  1124. }
  1125. case "reality":
  1126. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  1127. streamSettings["realitySettings"] = s.realityData(realitySettings)
  1128. }
  1129. }
  1130. delete(streamSettings, "sockopt")
  1131. return streamSettings
  1132. }
  1133. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  1134. tlsData := make(map[string]any, 1)
  1135. tlsClientSettings, _ := tData["settings"].(map[string]any)
  1136. tlsData["serverName"] = tData["serverName"]
  1137. tlsData["alpn"] = tData["alpn"]
  1138. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  1139. tlsData["fingerprint"] = fingerprint
  1140. }
  1141. if pins, ok := tlsClientSettings["pinnedPeerCertSha256"].([]any); ok && len(pins) > 0 {
  1142. tlsData["pin-sha256"] = pins
  1143. }
  1144. return tlsData
  1145. }
  1146. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  1147. rDataOut := make(map[string]any, 1)
  1148. realityClientSettings, _ := rData["settings"].(map[string]any)
  1149. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  1150. rDataOut["publicKey"] = publicKey
  1151. }
  1152. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  1153. rDataOut["fingerprint"] = fingerprint
  1154. }
  1155. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  1156. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  1157. }
  1158. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  1159. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  1160. }
  1161. return rDataOut
  1162. }
  1163. func cloneMap(src map[string]any) map[string]any {
  1164. if src == nil {
  1165. return nil
  1166. }
  1167. dst := make(map[string]any, len(src))
  1168. maps.Copy(dst, src)
  1169. return dst
  1170. }
  1171. func mergeClashRulesYAML(base map[string]any, raw string) error {
  1172. raw = strings.TrimSpace(raw)
  1173. if raw == "" {
  1174. return nil
  1175. }
  1176. var custom any
  1177. if err := yaml.Unmarshal([]byte(raw), &custom); err != nil {
  1178. mergeClashRules(base, linesToClashRules(raw))
  1179. return nil
  1180. }
  1181. switch typed := custom.(type) {
  1182. case []any:
  1183. mergeClashRules(base, typed)
  1184. case map[string]any:
  1185. for key, value := range typed {
  1186. if key == "rules" {
  1187. if ruleList, ok := asAnySlice(value); ok {
  1188. mergeClashRules(base, ruleList)
  1189. }
  1190. continue
  1191. }
  1192. base[key] = value
  1193. }
  1194. default:
  1195. mergeClashRules(base, linesToClashRules(raw))
  1196. }
  1197. return nil
  1198. }
  1199. // mergeRemoteClashRules lets remote update only the route graph (see
  1200. // remoteClashAllowedKey) and never mutates remote: cached documents are shared.
  1201. func mergeRemoteClashRules(base map[string]any, remote map[string]any) error {
  1202. if len(remote) == 0 {
  1203. return fmt.Errorf("remote Clash routing source must be a YAML map")
  1204. }
  1205. for key, value := range remote {
  1206. if !remoteClashAllowedKey(key) {
  1207. continue
  1208. }
  1209. if err := validateRemoteClashValue(key, value); err != nil {
  1210. return err
  1211. }
  1212. switch key {
  1213. case "rules":
  1214. rules, _ := asAnySlice(value)
  1215. mergeClashRules(base, rules)
  1216. case "proxy-groups":
  1217. groups, _ := asAnySlice(value)
  1218. base["proxy-groups"] = mergeClashProxyGroups(base["proxy-groups"], groups)
  1219. default:
  1220. base[key] = value
  1221. }
  1222. }
  1223. return validateClashRouteGraph(base)
  1224. }
  1225. func validateRemoteClashValue(key string, value any) error {
  1226. switch key {
  1227. case "rules":
  1228. rules, ok := asAnySlice(value)
  1229. if !ok {
  1230. return fmt.Errorf("remote Clash rules must be a list")
  1231. }
  1232. for _, rule := range rules {
  1233. text, ok := rule.(string)
  1234. if !ok || strings.TrimSpace(text) == "" {
  1235. return fmt.Errorf("remote Clash rules must contain non-empty strings")
  1236. }
  1237. }
  1238. case "proxy-groups":
  1239. groups, ok := asAnySlice(value)
  1240. if !ok {
  1241. return fmt.Errorf("remote Clash proxy-groups must be a list")
  1242. }
  1243. seen := make(map[string]struct{}, len(groups))
  1244. for _, groupValue := range groups {
  1245. group, ok := groupValue.(map[string]any)
  1246. if !ok {
  1247. return fmt.Errorf("remote Clash proxy-groups must contain named group maps with a type")
  1248. }
  1249. name, nameOK := group["name"].(string)
  1250. groupType, typeOK := group["type"].(string)
  1251. if !nameOK || !typeOK || strings.TrimSpace(name) == "" || strings.TrimSpace(groupType) == "" {
  1252. return fmt.Errorf("remote Clash proxy-groups must contain named group maps with a type")
  1253. }
  1254. name = strings.TrimSpace(name)
  1255. if _, duplicate := seen[name]; duplicate {
  1256. return fmt.Errorf("remote Clash proxy-group name %q is duplicated", name)
  1257. }
  1258. seen[name] = struct{}{}
  1259. if useValue, exists := group["use"]; exists {
  1260. use, ok := asAnySlice(useValue)
  1261. if !ok || len(use) > 0 {
  1262. return fmt.Errorf("remote Clash proxy-group %q cannot use proxy-providers", name)
  1263. }
  1264. }
  1265. }
  1266. case "rule-providers":
  1267. providers, ok := value.(map[string]any)
  1268. if !ok {
  1269. return fmt.Errorf("remote Clash rule-providers must be a map")
  1270. }
  1271. for name, provider := range providers {
  1272. if strings.TrimSpace(name) == "" {
  1273. return fmt.Errorf("remote Clash rule-provider name must not be empty")
  1274. }
  1275. if _, ok := provider.(map[string]any); !ok {
  1276. return fmt.Errorf("remote Clash rule-provider %q must be a map", name)
  1277. }
  1278. }
  1279. }
  1280. return nil
  1281. }
  1282. func remoteClashAllowedKey(key string) bool {
  1283. switch key {
  1284. case "proxy-groups", "rule-providers", "rules":
  1285. return true
  1286. default:
  1287. return false
  1288. }
  1289. }
  1290. func validateClashRouteGraph(config map[string]any) error {
  1291. known := map[string]struct{}{
  1292. "DIRECT": {}, "REJECT": {}, "REJECT-DROP": {}, "REJECT-TINYGIF": {}, "PASS": {}, "GLOBAL": {},
  1293. }
  1294. if proxies, ok := asAnySlice(config["proxies"]); ok {
  1295. for _, value := range proxies {
  1296. proxy, ok := value.(map[string]any)
  1297. if !ok {
  1298. continue
  1299. }
  1300. if name, ok := proxy["name"].(string); ok && strings.TrimSpace(name) != "" {
  1301. known[strings.TrimSpace(name)] = struct{}{}
  1302. }
  1303. }
  1304. }
  1305. groups, _ := asAnySlice(config["proxy-groups"])
  1306. for _, value := range groups {
  1307. if name := clashProxyGroupName(value); name != "" {
  1308. known[name] = struct{}{}
  1309. }
  1310. }
  1311. for _, value := range groups {
  1312. group, ok := value.(map[string]any)
  1313. if !ok {
  1314. continue
  1315. }
  1316. name := clashProxyGroupName(group)
  1317. refs, exists := group["proxies"]
  1318. if !exists {
  1319. continue
  1320. }
  1321. proxies, ok := asAnySlice(refs)
  1322. if !ok {
  1323. return fmt.Errorf("Clash proxy-group %q proxies must be a list", name)
  1324. }
  1325. for _, refValue := range proxies {
  1326. ref, ok := refValue.(string)
  1327. if !ok || strings.TrimSpace(ref) == "" {
  1328. return fmt.Errorf("Clash proxy-group %q contains an invalid proxy reference", name)
  1329. }
  1330. ref = strings.TrimSpace(ref)
  1331. if _, exists := known[ref]; !exists {
  1332. return fmt.Errorf("Clash proxy-group %q references unknown proxy or group %q", name, ref)
  1333. }
  1334. }
  1335. }
  1336. providers, _ := config["rule-providers"].(map[string]any)
  1337. for providerName, value := range providers {
  1338. provider, ok := value.(map[string]any)
  1339. if !ok {
  1340. continue
  1341. }
  1342. via, ok := provider["proxy"].(string)
  1343. if !ok || strings.TrimSpace(via) == "" {
  1344. continue
  1345. }
  1346. via = strings.TrimSpace(via)
  1347. if _, exists := known[via]; !exists {
  1348. return fmt.Errorf("Clash rule-provider %q references unknown proxy or group %q", providerName, via)
  1349. }
  1350. }
  1351. rules, _ := asAnySlice(config["rules"])
  1352. for _, value := range rules {
  1353. rule, ok := value.(string)
  1354. if !ok || strings.TrimSpace(rule) == "" {
  1355. return errors.New("Clash rules must contain non-empty strings")
  1356. }
  1357. parts := strings.Split(rule, ",")
  1358. for i := range parts {
  1359. parts[i] = strings.TrimSpace(parts[i])
  1360. }
  1361. if len(parts) < 2 {
  1362. return fmt.Errorf("invalid Clash rule %q", rule)
  1363. }
  1364. if strings.EqualFold(parts[0], "RULE-SET") {
  1365. if len(parts) < 3 {
  1366. return fmt.Errorf("invalid Clash RULE-SET rule %q", rule)
  1367. }
  1368. if _, exists := providers[parts[1]]; !exists {
  1369. return fmt.Errorf("Clash rule references unknown rule-provider %q", parts[1])
  1370. }
  1371. }
  1372. targetIndex := len(parts) - 1
  1373. // Mihomo IP rules may carry trailing no-resolve / src option flags.
  1374. for targetIndex >= 1 && (strings.EqualFold(parts[targetIndex], "no-resolve") || strings.EqualFold(parts[targetIndex], "src")) {
  1375. targetIndex--
  1376. }
  1377. if targetIndex < 1 {
  1378. return fmt.Errorf("invalid Clash rule target in %q", rule)
  1379. }
  1380. target := parts[targetIndex]
  1381. if _, exists := known[target]; !exists {
  1382. return fmt.Errorf("Clash rule references unknown proxy or group %q", target)
  1383. }
  1384. }
  1385. return nil
  1386. }
  1387. func mergeClashProxyGroups(baseValue any, remoteGroups []any) []any {
  1388. baseGroups, _ := asAnySlice(baseValue)
  1389. baseByName := make(map[string]any, len(baseGroups))
  1390. baseOrder := make([]string, 0, len(baseGroups))
  1391. for _, group := range baseGroups {
  1392. name := clashProxyGroupName(group)
  1393. if name == "" {
  1394. continue
  1395. }
  1396. baseByName[name] = group
  1397. baseOrder = append(baseOrder, name)
  1398. }
  1399. merged := make([]any, 0, len(remoteGroups)+len(baseGroups))
  1400. seen := make(map[string]struct{}, len(remoteGroups)+len(baseGroups))
  1401. for _, group := range remoteGroups {
  1402. name := clashProxyGroupName(group)
  1403. if name == "" {
  1404. continue
  1405. }
  1406. if _, duplicate := seen[name]; duplicate {
  1407. continue
  1408. }
  1409. seen[name] = struct{}{}
  1410. merged = append(merged, group)
  1411. }
  1412. for _, name := range baseOrder {
  1413. if _, replaced := seen[name]; replaced {
  1414. continue
  1415. }
  1416. merged = append(merged, baseByName[name])
  1417. }
  1418. return merged
  1419. }
  1420. func clashProxyGroupName(value any) string {
  1421. group, ok := value.(map[string]any)
  1422. if !ok {
  1423. return ""
  1424. }
  1425. name, _ := group["name"].(string)
  1426. return strings.TrimSpace(name)
  1427. }
  1428. func mergeClashRules(base map[string]any, customRules []any) {
  1429. if len(customRules) == 0 {
  1430. return
  1431. }
  1432. baseRules, _ := asAnySlice(base["rules"])
  1433. if hasClashMatchRule(customRules) {
  1434. base["rules"] = customRules
  1435. return
  1436. }
  1437. merged := make([]any, 0, len(customRules)+len(baseRules))
  1438. merged = append(merged, customRules...)
  1439. merged = append(merged, baseRules...)
  1440. base["rules"] = merged
  1441. }
  1442. func asAnySlice(value any) ([]any, bool) {
  1443. switch typed := value.(type) {
  1444. case []any:
  1445. return typed, true
  1446. case []string:
  1447. out := make([]any, 0, len(typed))
  1448. for _, item := range typed {
  1449. out = append(out, item)
  1450. }
  1451. return out, true
  1452. case []map[string]any:
  1453. out := make([]any, 0, len(typed))
  1454. for _, item := range typed {
  1455. out = append(out, item)
  1456. }
  1457. return out, true
  1458. default:
  1459. return nil, false
  1460. }
  1461. }
  1462. func hasClashMatchRule(rules []any) bool {
  1463. for _, rule := range rules {
  1464. ruleText, ok := rule.(string)
  1465. if !ok {
  1466. continue
  1467. }
  1468. parts := strings.SplitN(ruleText, ",", 2)
  1469. if strings.EqualFold(strings.TrimSpace(parts[0]), "MATCH") {
  1470. return true
  1471. }
  1472. }
  1473. return false
  1474. }
  1475. func linesToClashRules(raw string) []any {
  1476. lines := strings.Split(raw, "\n")
  1477. rules := make([]any, 0, len(lines))
  1478. for _, line := range lines {
  1479. line = strings.TrimSpace(line)
  1480. if line == "" || strings.HasPrefix(line, "#") {
  1481. continue
  1482. }
  1483. rules = append(rules, line)
  1484. }
  1485. return rules
  1486. }