clash_service.go 41 KB

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