clash_service_test.go 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  1. package sub
  2. import (
  3. "fmt"
  4. "reflect"
  5. "testing"
  6. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  9. )
  10. func TestEnsureUniqueProxyNames(t *testing.T) {
  11. proxies := []map[string]any{
  12. {"name": "", "type": "vless", "server": "a.com", "port": 443},
  13. {"name": "", "type": "vmess", "server": "b.com", "port": 8443},
  14. {"name": "node"},
  15. {"name": "node"},
  16. {"name": ""},
  17. }
  18. ensureUniqueProxyNames(proxies)
  19. seen := map[string]bool{}
  20. for i, p := range proxies {
  21. name, _ := p["name"].(string)
  22. if name == "" {
  23. t.Fatalf("proxy %d still has an empty name (mihomo would reject the config, #4641)", i)
  24. }
  25. if seen[name] {
  26. t.Fatalf("proxy %d has duplicate name %q (mihomo rejects the whole config, #4641)", i, name)
  27. }
  28. seen[name] = true
  29. }
  30. if got := proxies[0]["name"]; got != "vless-a.com-443" {
  31. t.Errorf("empty name fallback = %q, want vless-a.com-443", got)
  32. }
  33. if proxies[2]["name"] == proxies[3]["name"] {
  34. t.Errorf("duplicate %q was not disambiguated", proxies[2]["name"])
  35. }
  36. if got := proxies[4]["name"]; got != "proxy-5" {
  37. t.Errorf("typeless empty name fallback = %q, want proxy-5", got)
  38. }
  39. }
  40. func TestLegacyClashProxyCompatibility(t *testing.T) {
  41. t.Run("keeps legacy vmess fields", func(t *testing.T) {
  42. proxy := map[string]any{
  43. "name": "vm", "type": "vmess", "server": "vm.example.com", "port": 443,
  44. "uuid": "11111111-2222-4333-8444-555555555555", "alterId": 0, "cipher": "auto",
  45. "udp": true, "network": "ws", "tls": true, "servername": "sni.example.com",
  46. "ws-opts": map[string]any{"path": "/ws"}, "client-fingerprint": "chrome", "alpn": []string{"h2"},
  47. }
  48. got := legacyClashProxy(proxy)
  49. if got == nil || got["type"] != "vmess" || got["network"] != "ws" {
  50. t.Fatalf("legacy vmess was filtered or changed: %#v", got)
  51. }
  52. for _, field := range []string{"client-fingerprint", "alpn"} {
  53. if _, exists := got[field]; exists {
  54. t.Fatalf("Mihomo-only field %q leaked into legacy vmess: %#v", field, got)
  55. }
  56. }
  57. })
  58. t.Run("keeps legacy trojan fields", func(t *testing.T) {
  59. proxy := map[string]any{
  60. "name": "tr", "type": "trojan", "server": "tr.example.com", "port": 443,
  61. "password": "secret", "udp": true, "network": "grpc", "tls": true,
  62. "sni": "sni.example.com", "servername": "sni.example.com", "alpn": []string{"h2"},
  63. "grpc-opts": map[string]any{"grpc-service-name": "svc"},
  64. }
  65. got := legacyClashProxy(proxy)
  66. if got == nil || got["type"] != "trojan" || got["sni"] != "sni.example.com" {
  67. t.Fatalf("legacy trojan was filtered or changed: %#v", got)
  68. }
  69. for _, field := range []string{"tls", "servername"} {
  70. if _, exists := got[field]; exists {
  71. t.Fatalf("field %q is not part of the legacy Trojan schema: %#v", field, got)
  72. }
  73. }
  74. withoutTLS := cloneMap(proxy)
  75. withoutTLS["tls"] = false
  76. if got := legacyClashProxy(withoutTLS); got != nil {
  77. t.Fatalf("Trojan without TLS must not reach Clash for Windows: %#v", got)
  78. }
  79. })
  80. t.Run("keeps only legacy shadowsocks ciphers", func(t *testing.T) {
  81. legacy := map[string]any{
  82. "name": "ss", "type": "ss", "server": "ss.example.com", "port": 443,
  83. "password": "secret", "cipher": "aes-256-gcm", "udp": true, "network": "tcp", "tls": false,
  84. }
  85. got := legacyClashProxy(legacy)
  86. if got == nil || got["type"] != "ss" {
  87. t.Fatalf("legacy Shadowsocks proxy was filtered: %#v", got)
  88. }
  89. for _, field := range []string{"network", "tls"} {
  90. if _, exists := got[field]; exists {
  91. t.Fatalf("field %q is not part of the legacy Shadowsocks schema: %#v", field, got)
  92. }
  93. }
  94. ss2022 := cloneMap(legacy)
  95. ss2022["cipher"] = "2022-blake3-aes-256-gcm"
  96. if got := legacyClashProxy(ss2022); got != nil {
  97. t.Fatalf("SS-2022 must not reach Clash for Windows: %#v", got)
  98. }
  99. })
  100. for _, proxy := range []map[string]any{
  101. {"name": "vl", "type": "vless"},
  102. {"name": "hy", "type": "hysteria2"},
  103. {"name": "xh", "type": "vmess", "cipher": "auto", "network": "xhttp"},
  104. {"name": "reality", "type": "vmess", "cipher": "auto", "network": "tcp", "reality-opts": map[string]any{}},
  105. } {
  106. if got := legacyClashProxy(proxy); got != nil {
  107. t.Fatalf("modern proxy reached Clash for Windows: %#v", got)
  108. }
  109. }
  110. }
  111. // TestBuildProxy_VLESSRealityFieldsForClash locks the reality field mapping in
  112. // applySecurity (clash_service.go ~488): a regression that drops servername,
  113. // public-key, short-id, or client-fingerprint would hand mihomo a broken reality
  114. // proxy. The existing clash tests don't assert any of these.
  115. func TestBuildProxy_VLESSRealityFieldsForClash(t *testing.T) {
  116. svc := &SubClashService{SubService: &SubService{}}
  117. inbound := &model.Inbound{Listen: "203.0.113.1", Port: 443, Protocol: model.VLESS, Remark: "r", Settings: `{"encryption":"none"}`}
  118. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  119. stream := map[string]any{
  120. "network": "tcp",
  121. "security": "reality",
  122. "tcpSettings": map[string]any{"header": map[string]any{"type": "none"}},
  123. "realitySettings": map[string]any{"serverName": "reality.example.com", "publicKey": "PBKvalue", "shortId": "ab12", "fingerprint": "chrome"},
  124. }
  125. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  126. if proxy == nil {
  127. t.Fatal("buildProxy returned nil for a valid reality stream")
  128. }
  129. if proxy["tls"] != true {
  130. t.Fatalf("tls = %v, want true", proxy["tls"])
  131. }
  132. if proxy["servername"] != "reality.example.com" {
  133. t.Fatalf("servername = %v, want reality.example.com", proxy["servername"])
  134. }
  135. if proxy["client-fingerprint"] != "chrome" {
  136. t.Fatalf("client-fingerprint = %v, want chrome", proxy["client-fingerprint"])
  137. }
  138. opts, _ := proxy["reality-opts"].(map[string]any)
  139. if opts == nil {
  140. t.Fatal("reality-opts missing")
  141. }
  142. if opts["public-key"] != "PBKvalue" {
  143. t.Fatalf("public-key = %v, want PBKvalue", opts["public-key"])
  144. }
  145. if opts["short-id"] != "ab12" {
  146. t.Fatalf("short-id = %v, want ab12", opts["short-id"])
  147. }
  148. if opts["support-x25519mlkem768"] != true {
  149. t.Fatalf("ML-KEM support = %v, want true", opts["support-x25519mlkem768"])
  150. }
  151. }
  152. func TestClashRealityMLKEMAcrossSources(t *testing.T) {
  153. svc := NewSubClashService(false, "", &SubService{})
  154. for _, security := range []string{"reality", "tls", "none"} {
  155. for _, fingerprint := range []string{"", "chrome", "firefox"} {
  156. t.Run(security+"/"+fingerprint, func(t *testing.T) {
  157. inbound := &model.Inbound{Listen: "example.com", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`}
  158. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  159. stream := svc.streamData(fmt.Sprintf(`{"network":"tcp","security":%q,"realitySettings":{"serverNames":["example.com"],"shortIds":["ab12"],"settings":{"publicKey":"PBKvalue","fingerprint":%q}}}`, security, fingerprint))
  160. link := "vless://" + client.ID + "@example.com:443?type=tcp&security=" + security + "&sni=example.com&pbk=PBKvalue&sid=ab12&fp=" + fingerprint
  161. for source, proxy := range map[string]map[string]any{
  162. "inbound": svc.buildProxy(svc.SubService, inbound, client, stream, nil),
  163. "external": svc.clashProxyFromExternal(link, "external"),
  164. } {
  165. if proxy == nil {
  166. t.Fatalf("%s: missing proxy", source)
  167. }
  168. opts, exists := proxy["reality-opts"].(map[string]any)
  169. if security != "reality" {
  170. if exists {
  171. t.Fatalf("%s: REALITY options leaked into %s: %#v", source, security, opts)
  172. }
  173. continue
  174. }
  175. if opts["support-x25519mlkem768"] != true || opts["public-key"] != "PBKvalue" || opts["short-id"] != "ab12" {
  176. t.Fatalf("%s: incorrect REALITY options: %#v", source, opts)
  177. }
  178. wantFingerprint := fingerprint
  179. if wantFingerprint == "" {
  180. wantFingerprint = "chrome"
  181. }
  182. if proxy["client-fingerprint"] != wantFingerprint {
  183. t.Fatalf("%s: fingerprint = %v, want %s", source, proxy["client-fingerprint"], wantFingerprint)
  184. }
  185. if legacyClashProxy(proxy) != nil {
  186. t.Fatalf("%s: REALITY must stay excluded from legacy Clash", source)
  187. }
  188. }
  189. })
  190. }
  191. }
  192. }
  193. // TestApplyTransport_TCPHeader pins the tcp-header validation (clash_service.go ~359):
  194. // plain tcp and a "none" header are representable in clash; a non-none obfs header is
  195. // not, so applyTransport must reject it (returning false drops it from the YAML).
  196. func TestApplyTransport_TCPHeader(t *testing.T) {
  197. svc := &SubClashService{}
  198. if !svc.applyTransport(map[string]any{}, "tcp", map[string]any{}) {
  199. t.Fatal("plain tcp must be buildable")
  200. }
  201. noneStream := map[string]any{"tcpSettings": map[string]any{"header": map[string]any{"type": "none"}}}
  202. if !svc.applyTransport(map[string]any{}, "tcp", noneStream) {
  203. t.Fatal("tcp + header type none must be buildable")
  204. }
  205. httpStream := map[string]any{"tcpSettings": map[string]any{"header": map[string]any{"type": "http"}}}
  206. if svc.applyTransport(map[string]any{}, "tcp", httpStream) {
  207. t.Fatal("tcp + non-none (http) header is not representable in clash and must be rejected")
  208. }
  209. }
  210. func TestApplyTransport_XHTTP(t *testing.T) {
  211. svc := &SubClashService{}
  212. proxy := map[string]any{}
  213. stream := map[string]any{
  214. "xhttpSettings": map[string]any{
  215. "path": "/xh",
  216. "host": "example.com",
  217. "mode": "auto",
  218. },
  219. }
  220. if !svc.applyTransport(proxy, "xhttp", stream) {
  221. t.Fatalf("applyTransport returned false for xhttp (#4531: would drop the inbound and yield an empty Clash YAML)")
  222. }
  223. if proxy["network"] != "xhttp" {
  224. t.Fatalf("network = %v, want xhttp", proxy["network"])
  225. }
  226. opts, ok := proxy["xhttp-opts"].(map[string]any)
  227. if !ok {
  228. t.Fatalf("xhttp-opts missing or wrong type: %#v", proxy["xhttp-opts"])
  229. }
  230. want := map[string]any{"path": "/xh", "host": "example.com", "mode": "auto"}
  231. if !reflect.DeepEqual(opts, want) {
  232. t.Fatalf("xhttp-opts = %#v, want %#v", opts, want)
  233. }
  234. }
  235. func TestApplyTransport_XHTTP_HostFromHeaders(t *testing.T) {
  236. svc := &SubClashService{}
  237. proxy := map[string]any{}
  238. stream := map[string]any{
  239. "xhttpSettings": map[string]any{
  240. "path": "/xh",
  241. "headers": map[string]any{"Host": "via-header.example.com"},
  242. },
  243. }
  244. if !svc.applyTransport(proxy, "xhttp", stream) {
  245. t.Fatalf("applyTransport returned false for xhttp")
  246. }
  247. opts, _ := proxy["xhttp-opts"].(map[string]any)
  248. if opts["host"] != "via-header.example.com" {
  249. t.Fatalf("host should fall back to headers.Host, got %v", opts["host"])
  250. }
  251. }
  252. func TestApplyTransport_XHTTP_NoSettings(t *testing.T) {
  253. svc := &SubClashService{}
  254. proxy := map[string]any{}
  255. stream := map[string]any{}
  256. if !svc.applyTransport(proxy, "xhttp", stream) {
  257. t.Fatalf("applyTransport returned false for xhttp with no xhttpSettings")
  258. }
  259. if proxy["network"] != "xhttp" {
  260. t.Fatalf("network = %v, want xhttp", proxy["network"])
  261. }
  262. if _, exists := proxy["xhttp-opts"]; exists {
  263. t.Fatalf("xhttp-opts should be absent when xhttpSettings is missing, got %#v", proxy["xhttp-opts"])
  264. }
  265. }
  266. func TestApplyTransport_HTTPUpgrade(t *testing.T) {
  267. svc := &SubClashService{}
  268. proxy := map[string]any{}
  269. stream := map[string]any{
  270. "httpupgradeSettings": map[string]any{
  271. "path": "/hu",
  272. "host": "example.com",
  273. },
  274. }
  275. if !svc.applyTransport(proxy, "httpupgrade", stream) {
  276. t.Fatalf("applyTransport returned false for httpupgrade")
  277. }
  278. if proxy["network"] != "httpupgrade" {
  279. t.Fatalf("network = %v, want httpupgrade", proxy["network"])
  280. }
  281. opts, ok := proxy["http-upgrade-opts"].(map[string]any)
  282. if !ok {
  283. t.Fatalf("http-upgrade-opts missing: %#v", proxy["http-upgrade-opts"])
  284. }
  285. if opts["path"] != "/hu" {
  286. t.Fatalf("path = %v, want /hu", opts["path"])
  287. }
  288. headers, _ := opts["headers"].(map[string]any)
  289. if headers["Host"] != "example.com" {
  290. t.Fatalf("headers.Host = %v, want example.com", headers["Host"])
  291. }
  292. }
  293. func TestBuildProxy_VLESSPostQuantumEncryptionUsesMihomoEncryptionField(t *testing.T) {
  294. svc := &SubClashService{SubService: &SubService{}}
  295. encryption := "mlkem768x25519plus.native.0rtt.client"
  296. inbound := &model.Inbound{
  297. Listen: "203.0.113.1",
  298. Port: 443,
  299. Protocol: model.VLESS,
  300. Remark: "pq",
  301. Settings: `{"encryption":"` + encryption + `"}`,
  302. }
  303. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  304. stream := map[string]any{
  305. "network": "xhttp",
  306. "xhttpSettings": map[string]any{
  307. "path": "/",
  308. "mode": "auto",
  309. },
  310. "security": "reality",
  311. "realitySettings": map[string]any{
  312. "publicKey": "pub",
  313. "serverName": "example.com",
  314. "shortId": "abcd",
  315. },
  316. }
  317. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  318. if proxy["encryption"] != encryption {
  319. t.Fatalf("encryption = %v, want %q", proxy["encryption"], encryption)
  320. }
  321. }
  322. func TestBuildProxy_VLESSFlowXhttpRealityVlessenc(t *testing.T) {
  323. svc := &SubClashService{SubService: &SubService{}}
  324. encryption := "mlkem768x25519plus.native.0rtt.client"
  325. inbound := &model.Inbound{
  326. Listen: "203.0.113.1",
  327. Port: 443,
  328. Protocol: model.VLESS,
  329. Remark: "pq-flow",
  330. Settings: `{"encryption":"` + encryption + `"}`,
  331. }
  332. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Flow: "xtls-rprx-vision"}
  333. stream := map[string]any{
  334. "network": "xhttp",
  335. "xhttpSettings": map[string]any{
  336. "path": "/",
  337. "mode": "auto",
  338. },
  339. "security": "reality",
  340. "realitySettings": map[string]any{
  341. "publicKey": "pub",
  342. "serverName": "example.com",
  343. "shortId": "abcd",
  344. },
  345. }
  346. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  347. if proxy["flow"] != "xtls-rprx-vision" {
  348. t.Fatalf("xhttp+reality+vlessenc Clash proxy must carry the vision flow (#5232): %#v", proxy)
  349. }
  350. }
  351. func TestBuildProxy_VLESSFlowSuppressedByDisableFlow(t *testing.T) {
  352. svc := &SubClashService{SubService: &SubService{}}
  353. inbound := &model.Inbound{
  354. Listen: "203.0.113.1",
  355. Port: 443,
  356. Protocol: model.VLESS,
  357. Remark: "disabled-flow",
  358. Settings: `{"encryption":"` + testMlkemEncryption + `"}`,
  359. DisableFlow: true,
  360. }
  361. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Flow: "xtls-rprx-vision"}
  362. stream := map[string]any{
  363. "network": "xhttp",
  364. "xhttpSettings": map[string]any{"path": "/", "mode": "auto"},
  365. "security": "reality",
  366. "realitySettings": map[string]any{"publicKey": "pub", "serverName": "example.com", "shortId": "abcd"},
  367. }
  368. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  369. if _, ok := proxy["flow"]; ok {
  370. t.Fatalf("DisableFlow inbound must not carry a flow in the Clash proxy: %#v", proxy)
  371. }
  372. }
  373. func TestBuildProxy_VLESSFlowDroppedWithoutVisionSupport(t *testing.T) {
  374. svc := &SubClashService{SubService: &SubService{}}
  375. inbound := &model.Inbound{
  376. Listen: "203.0.113.1",
  377. Port: 443,
  378. Protocol: model.VLESS,
  379. Remark: "plain-flow",
  380. Settings: `{"encryption":"none"}`,
  381. }
  382. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Flow: "xtls-rprx-vision"}
  383. stream := map[string]any{
  384. "network": "tcp",
  385. "security": "none",
  386. "tcpSettings": map[string]any{
  387. "header": map[string]any{"type": "none"},
  388. },
  389. }
  390. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  391. if _, ok := proxy["flow"]; ok {
  392. t.Fatalf("tcp without tls/reality must not carry a flow: %#v", proxy)
  393. }
  394. }
  395. func TestBuildProxy_VLESSNoneEncryptionOmittedForClash(t *testing.T) {
  396. svc := &SubClashService{SubService: &SubService{}}
  397. inbound := &model.Inbound{
  398. Listen: "203.0.113.1",
  399. Port: 443,
  400. Protocol: model.VLESS,
  401. Remark: "plain",
  402. Settings: `{"encryption":"none"}`,
  403. }
  404. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  405. stream := map[string]any{
  406. "network": "tcp",
  407. "security": "none",
  408. "tcpSettings": map[string]any{
  409. "header": map[string]any{"type": "none"},
  410. },
  411. }
  412. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  413. if _, ok := proxy["encryption"]; ok {
  414. t.Fatalf("plain vless encryption should be omitted for mihomo: %#v", proxy)
  415. }
  416. // The rest of the proxy must still be well-formed — otherwise a mutant that
  417. // drops encryption *and* corrupts a core field passes the absence check alone.
  418. if proxy["type"] != "vless" {
  419. t.Fatalf("type = %v, want vless", proxy["type"])
  420. }
  421. if proxy["server"] != "203.0.113.1" {
  422. t.Fatalf("server = %v, want 203.0.113.1", proxy["server"])
  423. }
  424. if proxy["port"] != 443 {
  425. t.Fatalf("port = %v, want 443", proxy["port"])
  426. }
  427. if proxy["uuid"] != client.ID {
  428. t.Fatalf("uuid = %v, want %v", proxy["uuid"], client.ID)
  429. }
  430. }
  431. func TestBuildXhttpClashOpts_FullFieldMapping(t *testing.T) {
  432. xhttp := map[string]any{
  433. "path": "/api/v1",
  434. "mode": "stream-up",
  435. "host": "example.com",
  436. "xPaddingBytes": "100-1000",
  437. "xPaddingObfsMode": true,
  438. "xPaddingKey": "mykey",
  439. "xPaddingHeader": "X-Trace-ID",
  440. "xPaddingPlacement": "queryInHeader",
  441. "xPaddingMethod": "tokenish",
  442. "uplinkHTTPMethod": "POST",
  443. "sessionIDPlacement": "query",
  444. "sessionIDKey": "sess",
  445. "sessionIDTable": "Base62",
  446. "sessionIDLength": "16-32",
  447. "seqPlacement": "header",
  448. "seqKey": "seq",
  449. "uplinkDataPlacement": "body",
  450. "uplinkDataKey": "udata",
  451. "uplinkChunkSize": "64-256",
  452. "noGRPCHeader": true,
  453. "scMaxEachPostBytes": "500000",
  454. "scMinPostsIntervalMs": "50",
  455. "xmux": map[string]any{
  456. "maxConcurrency": "16-32",
  457. "maxConnections": "4",
  458. "cMaxReuseTimes": "8",
  459. "hMaxRequestTimes": "600-900",
  460. "hMaxReusableSecs": "1800-3000",
  461. "hKeepAlivePeriod": float64(60),
  462. },
  463. "headers": map[string]any{
  464. "User-Agent": "chrome",
  465. "Host": "should-be-dropped.com",
  466. },
  467. }
  468. opts := buildXhttpClashOpts(xhttp)
  469. if opts == nil {
  470. t.Fatal("expected non-nil opts for full field mapping")
  471. }
  472. // Direct fields
  473. if opts["path"] != "/api/v1" {
  474. t.Errorf("path = %v, want /api/v1", opts["path"])
  475. }
  476. if opts["mode"] != "stream-up" {
  477. t.Errorf("mode = %v, want stream-up", opts["mode"])
  478. }
  479. if opts["host"] != "example.com" {
  480. t.Errorf("host = %v, want example.com", opts["host"])
  481. }
  482. // String fields
  483. if opts["x-padding-bytes"] != "100-1000" {
  484. t.Errorf("x-padding-bytes = %v", opts["x-padding-bytes"])
  485. }
  486. if opts["uplink-http-method"] != "POST" {
  487. t.Errorf("uplink-http-method = %v", opts["uplink-http-method"])
  488. }
  489. if opts["session-id-placement"] != "query" {
  490. t.Errorf("session-id-placement = %v", opts["session-id-placement"])
  491. }
  492. if opts["session-id-key"] != "sess" {
  493. t.Errorf("session-id-key = %v", opts["session-id-key"])
  494. }
  495. if opts["session-id-table"] != "Base62" {
  496. t.Errorf("session-id-table = %v", opts["session-id-table"])
  497. }
  498. if opts["session-id-length"] != "16-32" {
  499. t.Errorf("session-id-length = %v", opts["session-id-length"])
  500. }
  501. if opts["seq-placement"] != "header" {
  502. t.Errorf("seq-placement = %v", opts["seq-placement"])
  503. }
  504. if opts["seq-key"] != "seq" {
  505. t.Errorf("seq-key = %v", opts["seq-key"])
  506. }
  507. if opts["uplink-data-placement"] != "body" {
  508. t.Errorf("uplink-data-placement = %v", opts["uplink-data-placement"])
  509. }
  510. if opts["uplink-data-key"] != "udata" {
  511. t.Errorf("uplink-data-key = %v", opts["uplink-data-key"])
  512. }
  513. // DPI-filtered fields (non-default values should pass)
  514. if opts["sc-max-each-post-bytes"] != "500000" {
  515. t.Errorf("sc-max-each-post-bytes = %v", opts["sc-max-each-post-bytes"])
  516. }
  517. if opts["sc-min-posts-interval-ms"] != "50" {
  518. t.Errorf("sc-min-posts-interval-ms = %v", opts["sc-min-posts-interval-ms"])
  519. }
  520. // Bool fields
  521. if opts["no-grpc-header"] != true {
  522. t.Errorf("no-grpc-header = %v, want true", opts["no-grpc-header"])
  523. }
  524. if opts["x-padding-obfs-mode"] != true {
  525. t.Errorf("x-padding-obfs-mode = %v, want true", opts["x-padding-obfs-mode"])
  526. }
  527. // Padding obfs gated fields
  528. if opts["x-padding-key"] != "mykey" {
  529. t.Errorf("x-padding-key = %v", opts["x-padding-key"])
  530. }
  531. if opts["x-padding-header"] != "X-Trace-ID" {
  532. t.Errorf("x-padding-header = %v", opts["x-padding-header"])
  533. }
  534. if opts["x-padding-placement"] != "queryInHeader" {
  535. t.Errorf("x-padding-placement = %v", opts["x-padding-placement"])
  536. }
  537. if opts["x-padding-method"] != "tokenish" {
  538. t.Errorf("x-padding-method = %v", opts["x-padding-method"])
  539. }
  540. // Non-zero value fields
  541. if opts["uplink-chunk-size"] != "64-256" {
  542. t.Errorf("uplink-chunk-size = %v", opts["uplink-chunk-size"])
  543. }
  544. // Reuse-settings (xmux)
  545. reuse, ok := opts["reuse-settings"].(map[string]any)
  546. if !ok {
  547. t.Fatalf("reuse-settings missing or wrong type: %#v", opts["reuse-settings"])
  548. }
  549. if reuse["max-concurrency"] != "16-32" {
  550. t.Errorf("max-concurrency = %v", reuse["max-concurrency"])
  551. }
  552. if reuse["max-connections"] != "4" {
  553. t.Errorf("max-connections = %v", reuse["max-connections"])
  554. }
  555. if reuse["c-max-reuse-times"] != "8" {
  556. t.Errorf("c-max-reuse-times = %v", reuse["c-max-reuse-times"])
  557. }
  558. if reuse["h-max-request-times"] != "600-900" {
  559. t.Errorf("h-max-request-times = %v", reuse["h-max-request-times"])
  560. }
  561. if reuse["h-max-reusable-secs"] != "1800-3000" {
  562. t.Errorf("h-max-reusable-secs = %v", reuse["h-max-reusable-secs"])
  563. }
  564. if reuse["h-keep-alive-period"] != float64(60) {
  565. t.Errorf("h-keep-alive-period = %v, want 60", reuse["h-keep-alive-period"])
  566. }
  567. // Headers (Host should be dropped)
  568. headers, ok := opts["headers"].(map[string]any)
  569. if !ok {
  570. t.Fatalf("headers missing or wrong type: %#v", opts["headers"])
  571. }
  572. if headers["User-Agent"] != "chrome" {
  573. t.Errorf("headers[User-Agent] = %v", headers["User-Agent"])
  574. }
  575. if _, has := headers["Host"]; has {
  576. t.Error("headers should not contain Host key")
  577. }
  578. if _, has := headers["host"]; has {
  579. t.Error("headers should not contain host key (case-insensitive)")
  580. }
  581. }
  582. func TestBuildXhttpClashOpts_DPIDefaultsFiltered(t *testing.T) {
  583. xhttp := map[string]any{
  584. "path": "/",
  585. "mode": "stream-up",
  586. "scMaxEachPostBytes": "1000000",
  587. "scMinPostsIntervalMs": "30",
  588. }
  589. opts := buildXhttpClashOpts(xhttp)
  590. if opts == nil {
  591. t.Fatal("expected non-nil opts (path and mode should be present)")
  592. }
  593. if _, has := opts["sc-max-each-post-bytes"]; has {
  594. t.Error("sc-max-each-post-bytes should be filtered when value is 1000000")
  595. }
  596. if _, has := opts["sc-min-posts-interval-ms"]; has {
  597. t.Error("sc-min-posts-interval-ms should be filtered when value is 30")
  598. }
  599. }
  600. func TestBuildXhttpClashOpts_PaddingObfsGate(t *testing.T) {
  601. // Sub-test 1: obfs mode false — gated fields should not appear
  602. t.Run("ObfsModeFalse", func(t *testing.T) {
  603. xhttp := map[string]any{
  604. "path": "/",
  605. "xPaddingObfsMode": false,
  606. "xPaddingKey": "should-not-appear",
  607. }
  608. opts := buildXhttpClashOpts(xhttp)
  609. if opts == nil {
  610. t.Fatal("expected non-nil opts")
  611. }
  612. if _, has := opts["x-padding-obfs-mode"]; has {
  613. t.Error("x-padding-obfs-mode should not appear when false")
  614. }
  615. if _, has := opts["x-padding-key"]; has {
  616. t.Error("x-padding-key should not appear when obfs mode is false")
  617. }
  618. })
  619. // Sub-test 2: obfs mode absent — gated fields should not appear
  620. t.Run("ObfsModeAbsent", func(t *testing.T) {
  621. xhttp := map[string]any{
  622. "path": "/",
  623. "xPaddingKey": "should-not-appear",
  624. }
  625. opts := buildXhttpClashOpts(xhttp)
  626. if opts == nil {
  627. t.Fatal("expected non-nil opts")
  628. }
  629. if _, has := opts["x-padding-key"]; has {
  630. t.Error("x-padding-key should not appear when obfs mode is absent")
  631. }
  632. })
  633. // Sub-test 3: obfs mode true with no gated fields — only x-padding-obfs-mode appears
  634. t.Run("ObfsModeTrueNoGatedFields", func(t *testing.T) {
  635. xhttp := map[string]any{
  636. "path": "/",
  637. "xPaddingObfsMode": true,
  638. }
  639. opts := buildXhttpClashOpts(xhttp)
  640. if opts == nil {
  641. t.Fatal("expected non-nil opts")
  642. }
  643. if opts["x-padding-obfs-mode"] != true {
  644. t.Errorf("x-padding-obfs-mode = %v, want true", opts["x-padding-obfs-mode"])
  645. }
  646. if _, has := opts["x-padding-key"]; has {
  647. t.Error("x-padding-key should not appear when not set")
  648. }
  649. })
  650. }
  651. func TestBuildXhttpClashOpts_XmuxMapsToReuseSettings(t *testing.T) {
  652. // Sub-test 1: full xmux mapping
  653. t.Run("FullXmux", func(t *testing.T) {
  654. xhttp := map[string]any{
  655. "path": "/",
  656. "xmux": map[string]any{
  657. "maxConcurrency": "16-32",
  658. "maxConnections": "4",
  659. "cMaxReuseTimes": "8",
  660. "hMaxRequestTimes": "600-900",
  661. "hMaxReusableSecs": "1800-3000",
  662. "hKeepAlivePeriod": float64(60),
  663. },
  664. }
  665. opts := buildXhttpClashOpts(xhttp)
  666. if opts == nil {
  667. t.Fatal("expected non-nil opts")
  668. }
  669. reuse, ok := opts["reuse-settings"].(map[string]any)
  670. if !ok {
  671. t.Fatalf("reuse-settings missing or wrong type: %#v", opts["reuse-settings"])
  672. }
  673. if reuse["max-concurrency"] != "16-32" {
  674. t.Errorf("max-concurrency = %v", reuse["max-concurrency"])
  675. }
  676. if reuse["max-connections"] != "4" {
  677. t.Errorf("max-connections = %v", reuse["max-connections"])
  678. }
  679. if reuse["c-max-reuse-times"] != "8" {
  680. t.Errorf("c-max-reuse-times = %v", reuse["c-max-reuse-times"])
  681. }
  682. if reuse["h-max-request-times"] != "600-900" {
  683. t.Errorf("h-max-request-times = %v", reuse["h-max-request-times"])
  684. }
  685. if reuse["h-max-reusable-secs"] != "1800-3000" {
  686. t.Errorf("h-max-reusable-secs = %v", reuse["h-max-reusable-secs"])
  687. }
  688. if reuse["h-keep-alive-period"] != float64(60) {
  689. t.Errorf("h-keep-alive-period = %v, want 60", reuse["h-keep-alive-period"])
  690. }
  691. })
  692. // Sub-test 2: empty xmux map — no reuse-settings key
  693. t.Run("EmptyXmux", func(t *testing.T) {
  694. xhttp := map[string]any{
  695. "path": "/",
  696. "xmux": map[string]any{},
  697. }
  698. opts := buildXhttpClashOpts(xhttp)
  699. if opts == nil {
  700. t.Fatal("expected non-nil opts (path is present)")
  701. }
  702. if _, has := opts["reuse-settings"]; has {
  703. t.Error("reuse-settings should not appear for empty xmux")
  704. }
  705. })
  706. // Sub-test 3: hKeepAlivePeriod as int (not float64)
  707. t.Run("IntKeepAlivePeriod", func(t *testing.T) {
  708. xhttp := map[string]any{
  709. "path": "/",
  710. "xmux": map[string]any{
  711. "hKeepAlivePeriod": int(60),
  712. },
  713. }
  714. opts := buildXhttpClashOpts(xhttp)
  715. if opts == nil {
  716. t.Fatal("expected non-nil opts")
  717. }
  718. reuse, ok := opts["reuse-settings"].(map[string]any)
  719. if !ok {
  720. t.Fatalf("reuse-settings missing: %#v", opts["reuse-settings"])
  721. }
  722. if reuse["h-keep-alive-period"] != int(60) {
  723. t.Errorf("h-keep-alive-period = %v (%T), want 60 (int)", reuse["h-keep-alive-period"], reuse["h-keep-alive-period"])
  724. }
  725. })
  726. // Sub-test 4: hKeepAlivePeriod=0 should be filtered
  727. t.Run("ZeroKeepAlivePeriod", func(t *testing.T) {
  728. xhttp := map[string]any{
  729. "path": "/",
  730. "xmux": map[string]any{
  731. "hKeepAlivePeriod": float64(0),
  732. },
  733. }
  734. opts := buildXhttpClashOpts(xhttp)
  735. if opts == nil {
  736. t.Fatal("expected non-nil opts")
  737. }
  738. if _, has := opts["reuse-settings"]; has {
  739. t.Error("reuse-settings should not appear when only hKeepAlivePeriod=0")
  740. }
  741. })
  742. }
  743. func TestBuildXhttpClashOpts_ServerOnlyFieldsExcluded(t *testing.T) {
  744. xhttp := map[string]any{
  745. "path": "/",
  746. "noSSEHeader": true,
  747. "scMaxBufferedPosts": "100",
  748. "scStreamUpServerSecs": "5",
  749. "serverMaxHeaderBytes": "4096",
  750. }
  751. opts := buildXhttpClashOpts(xhttp)
  752. if opts == nil {
  753. t.Fatal("expected non-nil opts (path is present)")
  754. }
  755. if _, has := opts["no-sse-header"]; has {
  756. t.Error("noSSEHeader should not appear in Clash output (server-only)")
  757. }
  758. if _, has := opts["sc-max-buffered-posts"]; has {
  759. t.Error("scMaxBufferedPosts should not appear in Clash output (server-only)")
  760. }
  761. if _, has := opts["sc-stream-up-server-secs"]; has {
  762. t.Error("scStreamUpServerSecs should not appear in Clash output (server-only)")
  763. }
  764. if _, has := opts["server-max-header-bytes"]; has {
  765. t.Error("serverMaxHeaderBytes should not appear in Clash output (not in Mihomo)")
  766. }
  767. }
  768. func TestBuildXhttpClashOpts_NilInput(t *testing.T) {
  769. opts := buildXhttpClashOpts(nil)
  770. if opts != nil {
  771. t.Fatalf("expected nil for nil input, got %#v", opts)
  772. }
  773. }
  774. func TestBuildXhttpClashOpts_EmptyInput(t *testing.T) {
  775. opts := buildXhttpClashOpts(map[string]any{})
  776. if opts != nil {
  777. t.Fatalf("expected nil for empty input, got %#v", opts)
  778. }
  779. }
  780. func TestBuildXhttpClashOpts_HostFallbackFromHeaders(t *testing.T) {
  781. // Sub-test 1: host from headers.Host
  782. t.Run("HostFromHeaders", func(t *testing.T) {
  783. xhttp := map[string]any{
  784. "path": "/",
  785. "headers": map[string]any{"Host": "via-header.example.com"},
  786. }
  787. opts := buildXhttpClashOpts(xhttp)
  788. if opts == nil {
  789. t.Fatal("expected non-nil opts")
  790. }
  791. if opts["host"] != "via-header.example.com" {
  792. t.Errorf("host = %v, want via-header.example.com", opts["host"])
  793. }
  794. })
  795. // Sub-test 2: headers only contains Host — no headers key in output
  796. t.Run("HeadersOnlyHost", func(t *testing.T) {
  797. xhttp := map[string]any{
  798. "path": "/",
  799. "headers": map[string]any{"Host": "only-host.example.com"},
  800. }
  801. opts := buildXhttpClashOpts(xhttp)
  802. if opts == nil {
  803. t.Fatal("expected non-nil opts")
  804. }
  805. if _, has := opts["headers"]; has {
  806. t.Error("headers key should not appear when only Host is present (Host is extracted to top-level)")
  807. }
  808. })
  809. // Sub-test 3: case-insensitive Host drop
  810. t.Run("CaseInsensitiveHostDrop", func(t *testing.T) {
  811. xhttp := map[string]any{
  812. "path": "/",
  813. "host": "explicit.example.com",
  814. "headers": map[string]any{
  815. "host": "lowercase-host.example.com",
  816. "X-Custom": "value",
  817. },
  818. }
  819. opts := buildXhttpClashOpts(xhttp)
  820. if opts == nil {
  821. t.Fatal("expected non-nil opts")
  822. }
  823. if opts["host"] != "explicit.example.com" {
  824. t.Errorf("host = %v, want explicit.example.com (explicit host wins)", opts["host"])
  825. }
  826. headers, ok := opts["headers"].(map[string]any)
  827. if !ok {
  828. t.Fatal("headers should be present (X-Custom remains)")
  829. }
  830. if _, has := headers["host"]; has {
  831. t.Error("lowercase 'host' should be dropped from headers")
  832. }
  833. if headers["X-Custom"] != "value" {
  834. t.Errorf("X-Custom = %v, want value", headers["X-Custom"])
  835. }
  836. })
  837. }
  838. func TestBuildXhttpClashOpts_NoGRPCHeaderFalsey(t *testing.T) {
  839. // Sub-test 1: noGRPCHeader: false
  840. t.Run("ExplicitFalse", func(t *testing.T) {
  841. xhttp := map[string]any{
  842. "path": "/",
  843. "noGRPCHeader": false,
  844. }
  845. opts := buildXhttpClashOpts(xhttp)
  846. if opts == nil {
  847. t.Fatal("expected non-nil opts (path is present)")
  848. }
  849. if _, has := opts["no-grpc-header"]; has {
  850. t.Error("no-grpc-header should not appear when noGRPCHeader is false")
  851. }
  852. })
  853. // Sub-test 2: noGRPCHeader absent
  854. t.Run("Absent", func(t *testing.T) {
  855. xhttp := map[string]any{
  856. "path": "/",
  857. }
  858. opts := buildXhttpClashOpts(xhttp)
  859. if opts == nil {
  860. t.Fatal("expected non-nil opts")
  861. }
  862. if _, has := opts["no-grpc-header"]; has {
  863. t.Error("no-grpc-header should not appear when absent")
  864. }
  865. })
  866. }
  867. func TestBuildWireguardProxyForClash(t *testing.T) {
  868. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  869. if err != nil {
  870. t.Fatalf("server keypair: %v", err)
  871. }
  872. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  873. if err != nil {
  874. t.Fatalf("client keypair: %v", err)
  875. }
  876. svc := &SubClashService{SubService: &SubService{}}
  877. inbound := &model.Inbound{
  878. Listen: "203.0.113.9",
  879. Port: 51820,
  880. Protocol: model.WireGuard,
  881. Remark: "wg",
  882. Settings: `{"secretKey":"` + serverPriv + `","mtu":1420,"dns":"1.1.1.1, 8.8.8.8"}`,
  883. }
  884. client := model.Client{
  885. Email: "user",
  886. PrivateKey: clientPriv,
  887. PreSharedKey: "psk-value",
  888. KeepAlive: model.KeepAlivePtr(25),
  889. AllowedIPs: []string{"10.0.0.2/32", "fd00::2/128"},
  890. }
  891. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  892. if proxy == nil {
  893. t.Fatal("buildProxy returned nil for a valid wireguard client")
  894. }
  895. if proxy["type"] != "wireguard" {
  896. t.Fatalf("type = %v, want wireguard", proxy["type"])
  897. }
  898. if proxy["server"] != "203.0.113.9" {
  899. t.Fatalf("server = %v, want 203.0.113.9", proxy["server"])
  900. }
  901. if proxy["port"] != 51820 {
  902. t.Fatalf("port = %v, want 51820", proxy["port"])
  903. }
  904. if proxy["private-key"] != clientPriv {
  905. t.Fatalf("private-key = %v, want %v", proxy["private-key"], clientPriv)
  906. }
  907. if proxy["public-key"] != serverPub {
  908. t.Fatalf("public-key = %v, want %v (derived from inbound secretKey)", proxy["public-key"], serverPub)
  909. }
  910. if proxy["pre-shared-key"] != "psk-value" {
  911. t.Fatalf("pre-shared-key = %v, want psk-value", proxy["pre-shared-key"])
  912. }
  913. if proxy["persistent-keepalive"] != 25 {
  914. t.Fatalf("persistent-keepalive = %v, want 25", proxy["persistent-keepalive"])
  915. }
  916. if proxy["ip"] != "10.0.0.2" {
  917. t.Fatalf("ip = %v, want 10.0.0.2", proxy["ip"])
  918. }
  919. if proxy["ipv6"] != "fd00::2" {
  920. t.Fatalf("ipv6 = %v, want fd00::2", proxy["ipv6"])
  921. }
  922. if proxy["mtu"] != 1420 {
  923. t.Fatalf("mtu = %v, want 1420", proxy["mtu"])
  924. }
  925. if proxy["udp"] != true {
  926. t.Fatalf("udp = %v, want true", proxy["udp"])
  927. }
  928. if dns, ok := proxy["dns"].([]string); !ok || !reflect.DeepEqual(dns, []string{"1.1.1.1", "8.8.8.8"}) {
  929. t.Fatalf("dns = %v, want [1.1.1.1 8.8.8.8]", proxy["dns"])
  930. }
  931. }
  932. func TestBuildWireguardProxyForClashNoKey(t *testing.T) {
  933. svc := &SubClashService{SubService: &SubService{}}
  934. inbound := &model.Inbound{Listen: "203.0.113.9", Port: 51820, Protocol: model.WireGuard, Settings: `{}`}
  935. client := model.Client{Email: "user"}
  936. if proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil); proxy != nil {
  937. t.Fatalf("buildProxy = %v, want nil for a keyless wireguard client", proxy)
  938. }
  939. }
  940. func TestBuildAmneziaWGProxyForClash(t *testing.T) {
  941. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  942. if err != nil {
  943. t.Fatalf("server keypair: %v", err)
  944. }
  945. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  946. if err != nil {
  947. t.Fatalf("client keypair: %v", err)
  948. }
  949. settings := `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub + `","mtu":1420,"primaryDns":"8.8.8.8","secondaryDns":"8.8.4.4","jc":3,"jmin":66,"jmax":150,"s1":147,"s2":146,"s3":28,"s4":27,"h1":"364198942-470015235","h2":"1041963382-1068354159","h3":"1313106728-1361756201","h4":"1801896583-1875457201","i1":"10-20","i2":"30-40"}}`
  950. svc := &SubClashService{SubService: &SubService{}}
  951. inbound := &model.Inbound{
  952. Listen: "203.0.113.7",
  953. Port: 51820,
  954. Protocol: model.AmneziaWG,
  955. Remark: "amneziawg",
  956. Settings: settings,
  957. }
  958. client := model.Client{
  959. Email: "user",
  960. PrivateKey: clientPriv,
  961. PreSharedKey: "psk-value",
  962. KeepAlive: model.KeepAlivePtr(25),
  963. AllowedIPs: []string{"10.8.1.2/32", "fd00::2/128"},
  964. }
  965. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  966. if proxy == nil {
  967. t.Fatal("buildProxy returned nil for a valid amneziawg client")
  968. }
  969. if proxy["type"] != "wireguard" {
  970. t.Fatalf("type = %v, want wireguard", proxy["type"])
  971. }
  972. if proxy["server"] != "203.0.113.7" {
  973. t.Fatalf("server = %v, want 203.0.113.7", proxy["server"])
  974. }
  975. if proxy["port"] != 51820 {
  976. t.Fatalf("port = %v, want 51820", proxy["port"])
  977. }
  978. if proxy["private-key"] != clientPriv {
  979. t.Fatalf("private-key = %v, want %v", proxy["private-key"], clientPriv)
  980. }
  981. if proxy["public-key"] != serverPub {
  982. t.Fatalf("public-key = %v, want %v", proxy["public-key"], serverPub)
  983. }
  984. if proxy["pre-shared-key"] != "psk-value" {
  985. t.Fatalf("pre-shared-key = %v, want psk-value", proxy["pre-shared-key"])
  986. }
  987. if proxy["persistent-keepalive"] != 25 {
  988. t.Fatalf("persistent-keepalive = %v, want 25", proxy["persistent-keepalive"])
  989. }
  990. if proxy["ip"] != "10.8.1.2" {
  991. t.Fatalf("ip = %v, want 10.8.1.2", proxy["ip"])
  992. }
  993. if proxy["ipv6"] != "fd00::2" {
  994. t.Fatalf("ipv6 = %v, want fd00::2", proxy["ipv6"])
  995. }
  996. if proxy["mtu"] != 1420 {
  997. t.Fatalf("mtu = %v, want 1420", proxy["mtu"])
  998. }
  999. if proxy["udp"] != true {
  1000. t.Fatalf("udp = %v, want true", proxy["udp"])
  1001. }
  1002. if dns, ok := proxy["dns"].([]string); !ok || !reflect.DeepEqual(dns, []string{"8.8.8.8", "8.8.4.4"}) {
  1003. t.Fatalf("dns = %v, want [8.8.8.8 8.8.4.4]", proxy["dns"])
  1004. }
  1005. awg, ok := proxy["amnezia-wg-option"].(map[string]any)
  1006. if !ok {
  1007. t.Fatal("amnezia-wg-option missing")
  1008. }
  1009. if awg["jc"] != 3 {
  1010. t.Fatalf("jc = %v, want 3", awg["jc"])
  1011. }
  1012. if awg["jmin"] != 66 {
  1013. t.Fatalf("jmin = %v, want 66", awg["jmin"])
  1014. }
  1015. if awg["jmax"] != 150 {
  1016. t.Fatalf("jmax = %v, want 150", awg["jmax"])
  1017. }
  1018. if awg["s1"] != 147 {
  1019. t.Fatalf("s1 = %v, want 147", awg["s1"])
  1020. }
  1021. if awg["s2"] != 146 {
  1022. t.Fatalf("s2 = %v, want 146", awg["s2"])
  1023. }
  1024. if awg["s3"] != 28 {
  1025. t.Fatalf("s3 = %v, want 28", awg["s3"])
  1026. }
  1027. if awg["s4"] != 27 {
  1028. t.Fatalf("s4 = %v, want 27", awg["s4"])
  1029. }
  1030. if awg["h1"] != "364198942-470015235" {
  1031. t.Fatalf("h1 = %v, want 364198942-470015235", awg["h1"])
  1032. }
  1033. if awg["h2"] != "1041963382-1068354159" {
  1034. t.Fatalf("h2 = %v, want 1041963382-1068354159", awg["h2"])
  1035. }
  1036. if awg["h3"] != "1313106728-1361756201" {
  1037. t.Fatalf("h3 = %v, want 1313106728-1361756201", awg["h3"])
  1038. }
  1039. if awg["h4"] != "1801896583-1875457201" {
  1040. t.Fatalf("h4 = %v, want 1801896583-1875457201", awg["h4"])
  1041. }
  1042. if awg["i1"] != "10-20" {
  1043. t.Fatalf("i1 = %v, want 10-20", awg["i1"])
  1044. }
  1045. if awg["i2"] != "30-40" {
  1046. t.Fatalf("i2 = %v, want 30-40", awg["i2"])
  1047. }
  1048. // v1.0 fields must NOT set version
  1049. if _, ok := awg["version"]; ok {
  1050. t.Fatalf("version should not be set for v1.0 obfuscation fields")
  1051. }
  1052. }
  1053. func TestBuildAmneziaWGProxyForClashV3(t *testing.T) {
  1054. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  1055. if err != nil {
  1056. t.Fatalf("server keypair: %v", err)
  1057. }
  1058. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  1059. if err != nil {
  1060. t.Fatalf("client keypair: %v", err)
  1061. }
  1062. settings := `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub + `","mtu":1280,"primaryDns":"1.1.1.1","jc":3,"jmin":66,"jmax":150,"s1":147,"s2":146,"s3":28,"s4":27,"h1":"364198942-470015235","h2":"1041963382-1068354159","h3":"1313106728-1361756201","h4":"1801896583-1875457201","headerProtectionKey":"DmVT7JtmJM8YoHiA2Wp3xPKI5dTXFx83y2JUQkKg1p8=","contentPaddingAddition":"9-31","rekeyAfterTime":"105-125","rekeyTimeout":"3-5","rejectAfterTime":"176-239","keepaliveTimeout":"11-16","maxHandshakeAttempts":"24-41","randomTrailers":true,"disableCookies":true}}`
  1063. svc := &SubClashService{SubService: &SubService{}}
  1064. inbound := &model.Inbound{
  1065. Listen: "203.0.113.7",
  1066. Port: 51820,
  1067. Protocol: model.AmneziaWG,
  1068. Remark: "amneziawg",
  1069. Settings: settings,
  1070. }
  1071. client := model.Client{
  1072. Email: "user",
  1073. PrivateKey: clientPriv,
  1074. AllowedIPs: []string{"10.8.1.2/32"},
  1075. }
  1076. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  1077. if proxy == nil {
  1078. t.Fatal("buildProxy returned nil for a valid amneziawg v3 client")
  1079. }
  1080. awg, ok := proxy["amnezia-wg-option"].(map[string]any)
  1081. if !ok {
  1082. t.Fatal("amnezia-wg-option missing")
  1083. }
  1084. if awg["version"] != 3 {
  1085. t.Fatalf("version = %v, want 3", awg["version"])
  1086. }
  1087. if awg["header-protection-key"] != "DmVT7JtmJM8YoHiA2Wp3xPKI5dTXFx83y2JUQkKg1p8=" {
  1088. t.Fatalf("header-protection-key = %v", awg["header-protection-key"])
  1089. }
  1090. if awg["content-padding-addition"] != "9-31" {
  1091. t.Fatalf("content-padding-addition = %v", awg["content-padding-addition"])
  1092. }
  1093. if awg["rekey-after-time"] != "105-125" {
  1094. t.Fatalf("rekey-after-time = %v", awg["rekey-after-time"])
  1095. }
  1096. if awg["rekey-timeout"] != "3-5" {
  1097. t.Fatalf("rekey-timeout = %v", awg["rekey-timeout"])
  1098. }
  1099. if awg["reject-after-time"] != "176-239" {
  1100. t.Fatalf("reject-after-time = %v", awg["reject-after-time"])
  1101. }
  1102. if awg["keepalive-timeout"] != "11-16" {
  1103. t.Fatalf("keepalive-timeout = %v", awg["keepalive-timeout"])
  1104. }
  1105. if awg["max-handshake-attempts"] != "24-41" {
  1106. t.Fatalf("max-handshake-attempts = %v", awg["max-handshake-attempts"])
  1107. }
  1108. if awg["random-trailers"] != true {
  1109. t.Fatalf("random-trailers = %v, want true", awg["random-trailers"])
  1110. }
  1111. if awg["disable-cookies"] != true {
  1112. t.Fatalf("disable-cookies = %v, want true", awg["disable-cookies"])
  1113. }
  1114. }
  1115. func TestBuildAmneziaWGProxyForClashNoKey(t *testing.T) {
  1116. svc := &SubClashService{SubService: &SubService{}}
  1117. settings := `{"server":{"privateKey":"abc","publicKey":"def","jc":3,"jmin":66,"jmax":150}}`
  1118. inbound := &model.Inbound{
  1119. Listen: "203.0.113.7",
  1120. Port: 51820,
  1121. Protocol: model.AmneziaWG,
  1122. Settings: settings,
  1123. }
  1124. client := model.Client{Email: "user"}
  1125. if proxy := svc.buildAmneziaWGProxy(svc.SubService, inbound, client, nil); proxy != nil {
  1126. t.Fatalf("buildAmneziaWGProxy = %v, want nil for a keyless amneziawg client", proxy)
  1127. }
  1128. }
  1129. // TestBuildAmneziaWGProxyForClashPerInboundAddress pins the tunnel address to
  1130. // this inbound's own settings.clients[] entry, the one InstanceFromInbound
  1131. // turns into the running peer's AllowedIPs. model.Client here is what
  1132. // matchingClients hands buildProxy: the shared clients.wg_allowed_ips column,
  1133. // which for an identity attached to both wireguard and amneziawg holds the
  1134. // other protocol's address.
  1135. func TestBuildAmneziaWGProxyForClashPerInboundAddress(t *testing.T) {
  1136. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  1137. if err != nil {
  1138. t.Fatalf("server keypair: %v", err)
  1139. }
  1140. clientPriv, clientPub, err := wgutil.GenerateWireguardKeypair()
  1141. if err != nil {
  1142. t.Fatalf("client keypair: %v", err)
  1143. }
  1144. settings := `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub +
  1145. `","jc":3,"jmin":66,"jmax":150},"clients":[{"email":"dual@x","publicKey":"` + clientPub +
  1146. `","allowedIPs":["10.8.1.5/32","fd00::5/128"],"enable":true}]}`
  1147. svc := &SubClashService{SubService: &SubService{}}
  1148. inbound := &model.Inbound{
  1149. Listen: "203.0.113.7",
  1150. Port: 51820,
  1151. Protocol: model.AmneziaWG,
  1152. Remark: "amneziawg",
  1153. Settings: settings,
  1154. }
  1155. client := model.Client{
  1156. Email: "dual@x",
  1157. PrivateKey: clientPriv,
  1158. AllowedIPs: []string{"10.0.0.5/32"},
  1159. }
  1160. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  1161. if proxy == nil {
  1162. t.Fatal("buildProxy returned nil for a valid amneziawg client")
  1163. }
  1164. if proxy["ip"] != "10.8.1.5" {
  1165. t.Fatalf("ip = %v, want 10.8.1.5 (this inbound's own address, not the shared column's 10.0.0.5)", proxy["ip"])
  1166. }
  1167. if proxy["ipv6"] != "fd00::5" {
  1168. t.Fatalf("ipv6 = %v, want fd00::5", proxy["ipv6"])
  1169. }
  1170. }
  1171. // TestBuildAmneziaWGProxyForClashFallsBackToClientAddress covers an inbound
  1172. // whose settings.clients[] has no entry for this email: the shared column is
  1173. // then the only address there is.
  1174. func TestBuildAmneziaWGProxyForClashFallsBackToClientAddress(t *testing.T) {
  1175. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  1176. if err != nil {
  1177. t.Fatalf("server keypair: %v", err)
  1178. }
  1179. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  1180. if err != nil {
  1181. t.Fatalf("client keypair: %v", err)
  1182. }
  1183. settings := `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub +
  1184. `","jc":3,"jmin":66,"jmax":150},"clients":[{"email":"someone-else@x","allowedIPs":["10.8.1.9/32"]}]}`
  1185. svc := &SubClashService{SubService: &SubService{}}
  1186. inbound := &model.Inbound{
  1187. Listen: "203.0.113.7",
  1188. Port: 51820,
  1189. Protocol: model.AmneziaWG,
  1190. Settings: settings,
  1191. }
  1192. client := model.Client{Email: "user@x", PrivateKey: clientPriv, AllowedIPs: []string{"10.8.1.2/32"}}
  1193. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  1194. if proxy == nil {
  1195. t.Fatal("buildProxy returned nil for a valid amneziawg client")
  1196. }
  1197. if proxy["ip"] != "10.8.1.2" {
  1198. t.Fatalf("ip = %v, want 10.8.1.2", proxy["ip"])
  1199. }
  1200. }
  1201. // TestBuildAmneziaWGProxyForClashRemoteDNSResolve pins the flag mihomo gates
  1202. // its `dns` list on, and the guard that keeps a non-IP entry from turning an
  1203. // inert key into a whole-config parse abort.
  1204. func TestBuildAmneziaWGProxyForClashRemoteDNSResolve(t *testing.T) {
  1205. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  1206. if err != nil {
  1207. t.Fatalf("server keypair: %v", err)
  1208. }
  1209. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  1210. if err != nil {
  1211. t.Fatalf("client keypair: %v", err)
  1212. }
  1213. build := func(t *testing.T, primary, secondary string) map[string]any {
  1214. t.Helper()
  1215. settings := `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub +
  1216. `","primaryDns":"` + primary + `","secondaryDns":"` + secondary + `"}}`
  1217. svc := &SubClashService{SubService: &SubService{}}
  1218. inbound := &model.Inbound{
  1219. Listen: "203.0.113.7",
  1220. Port: 51820,
  1221. Protocol: model.AmneziaWG,
  1222. Settings: settings,
  1223. }
  1224. client := model.Client{Email: "user", PrivateKey: clientPriv, AllowedIPs: []string{"10.8.1.2/32"}}
  1225. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  1226. if proxy == nil {
  1227. t.Fatal("buildProxy returned nil for a valid amneziawg client")
  1228. }
  1229. return proxy
  1230. }
  1231. t.Run("bare IPs", func(t *testing.T) {
  1232. proxy := build(t, "8.8.8.8", "fd00::1")
  1233. if proxy["remote-dns-resolve"] != true {
  1234. t.Fatalf("remote-dns-resolve = %v, want true: mihomo ignores dns without it", proxy["remote-dns-resolve"])
  1235. }
  1236. })
  1237. // netip.ParseAddr accepts a zone, but mihomo brackets the address into a
  1238. // udp:// URL whose url.Parse then rejects "%eth0" as a bad escape.
  1239. t.Run("zoned IPv6", func(t *testing.T) {
  1240. proxy := build(t, "8.8.8.8", "fe80::1%eth0")
  1241. if _, ok := proxy["remote-dns-resolve"]; ok {
  1242. t.Fatalf("remote-dns-resolve must stay unset for a zoned address, got %v", proxy["remote-dns-resolve"])
  1243. }
  1244. })
  1245. t.Run("non-IP entry", func(t *testing.T) {
  1246. proxy := build(t, "8.8.8.8", "dns.example.com")
  1247. if dns, ok := proxy["dns"].([]string); !ok || !reflect.DeepEqual(dns, []string{"8.8.8.8", "dns.example.com"}) {
  1248. t.Fatalf("dns = %v, want both entries kept", proxy["dns"])
  1249. }
  1250. if _, ok := proxy["remote-dns-resolve"]; ok {
  1251. t.Fatalf("remote-dns-resolve must stay unset when an entry is not a bare IP, got %v", proxy["remote-dns-resolve"])
  1252. }
  1253. })
  1254. t.Run("no DNS", func(t *testing.T) {
  1255. proxy := build(t, "", "")
  1256. if _, ok := proxy["remote-dns-resolve"]; ok {
  1257. t.Fatal("remote-dns-resolve must stay unset when there is no dns list")
  1258. }
  1259. })
  1260. }
  1261. // TestGetProxies_CustomIPv6ShareAddrIsUnbracketed pins that a Clash "server" is a
  1262. // bare host: the custom share address stores IPv6 literals bracketed, and mihomo
  1263. // rejects "[2001:db8::1]" there.
  1264. func TestGetProxies_CustomIPv6ShareAddrIsUnbracketed(t *testing.T) {
  1265. svc := &SubClashService{SubService: &SubService{}}
  1266. inbound := &model.Inbound{
  1267. Protocol: model.VLESS,
  1268. Port: 443,
  1269. Remark: "r",
  1270. Settings: `{"encryption":"none"}`,
  1271. StreamSettings: `{"network":"tcp","security":"none"}`,
  1272. ShareAddrStrategy: "custom",
  1273. ShareAddr: "[2001:db8::1]",
  1274. }
  1275. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Email: "[email protected]"}
  1276. proxies := svc.getProxies(svc.SubService, inbound, client, "panel.example.com")
  1277. if len(proxies) != 1 {
  1278. t.Fatalf("getProxies returned %d proxies, want 1", len(proxies))
  1279. }
  1280. if got := proxies[0]["server"]; got != "2001:db8::1" {
  1281. t.Fatalf("server = %v, want 2001:db8::1", got)
  1282. }
  1283. }
  1284. // TestBuildAmneziaWGProxyForClashEffectiveMTU pins the Clash mtu to the same
  1285. // amneziawg.EffectiveMTU every other emitter uses -- the running interface
  1286. // (amneziawgnet), the vpn:// .conf and both TS builders. Omitting the key
  1287. // leaves mihomo on its own 1408 default, above the tunnel once s4 > 12.
  1288. func TestBuildAmneziaWGProxyForClashEffectiveMTU(t *testing.T) {
  1289. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  1290. if err != nil {
  1291. t.Fatalf("server keypair: %v", err)
  1292. }
  1293. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  1294. if err != nil {
  1295. t.Fatalf("client keypair: %v", err)
  1296. }
  1297. build := func(t *testing.T, mtu, s4 int) map[string]any {
  1298. t.Helper()
  1299. settings := fmt.Sprintf(
  1300. `{"server":{"privateKey":%q,"publicKey":%q,"mtu":%d,"s4":%d}}`,
  1301. serverPriv, serverPub, mtu, s4)
  1302. svc := &SubClashService{SubService: &SubService{}}
  1303. inbound := &model.Inbound{
  1304. Listen: "203.0.113.7",
  1305. Port: 51820,
  1306. Protocol: model.AmneziaWG,
  1307. Settings: settings,
  1308. }
  1309. client := model.Client{Email: "user", PrivateKey: clientPriv, AllowedIPs: []string{"10.8.1.2/32"}}
  1310. proxy := svc.buildProxy(svc.SubService, inbound, client, nil, nil)
  1311. if proxy == nil {
  1312. t.Fatal("buildProxy returned nil for a valid amneziawg client")
  1313. }
  1314. return proxy
  1315. }
  1316. t.Run("unset MTU falls back to 1420-s4", func(t *testing.T) {
  1317. proxy := build(t, 0, 27)
  1318. want := amneziawg.EffectiveMTU(0, 27)
  1319. if proxy["mtu"] != want {
  1320. t.Fatalf("mtu = %v, want %d (amneziawg.EffectiveMTU)", proxy["mtu"], want)
  1321. }
  1322. })
  1323. t.Run("explicit MTU wins", func(t *testing.T) {
  1324. proxy := build(t, 1380, 27)
  1325. if proxy["mtu"] != 1380 {
  1326. t.Fatalf("mtu = %v, want 1380", proxy["mtu"])
  1327. }
  1328. })
  1329. }
  1330. func TestBuildHysteriaProxyIncludesCertificateFingerprint(t *testing.T) {
  1331. const pin = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
  1332. const want = "00:01:02:03:04:05:06:07:08:09:0A:0B:0C:0D:0E:0F:10:11:12:13:14:15:16:17:18:19:1A:1B:1C:1D:1E:1F"
  1333. const externalPin = "ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100"
  1334. const wantExternal = "FF:EE:DD:CC:BB:AA:99:88:77:66:55:44:33:22:11:00:FF:EE:DD:CC:BB:AA:99:88:77:66:55:44:33:22:11:00"
  1335. svc := &SubClashService{}
  1336. subReq := &SubService{}
  1337. inbound := &model.Inbound{
  1338. Protocol: model.Hysteria,
  1339. Listen: "192.0.2.1",
  1340. Port: 443,
  1341. Remark: "hysteria 2",
  1342. Settings: `{"version":2}`,
  1343. StreamSettings: `{
  1344. "tlsSettings": {
  1345. "alpn": ["h3"],
  1346. "settings": {
  1347. "fingerprint": "chrome",
  1348. "pinnedPeerCertSha256": ["` + pin + `"]
  1349. }
  1350. }
  1351. }`,
  1352. }
  1353. client := model.Client{Email: "client", Auth: "secret", Enable: true}
  1354. proxy := svc.buildHysteriaProxy(subReq, inbound, client, nil)
  1355. if got := proxy["fingerprint"]; got != want {
  1356. t.Fatalf("fingerprint = %v, want %s", got, want)
  1357. }
  1358. if got := proxy["client-fingerprint"]; got != "chrome" {
  1359. t.Fatalf("client-fingerprint = %v, want chrome", got)
  1360. }
  1361. externalProxy := svc.buildHysteriaProxy(subReq, inbound, client, map[string]any{
  1362. "pinnedPeerCertSha256": []any{externalPin},
  1363. })
  1364. if got := externalProxy["fingerprint"]; got != wantExternal {
  1365. t.Fatalf("external fingerprint = %v, want %s", got, wantExternal)
  1366. }
  1367. }
  1368. func TestMihomoCertFingerprintUsesFirstValidPin(t *testing.T) {
  1369. const firstPin = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
  1370. const secondPin = "ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100"
  1371. const wantFirst = "00:01:02:03:04:05:06:07:08:09:0A:0B:0C:0D:0E:0F:10:11:12:13:14:15:16:17:18:19:1A:1B:1C:1D:1E:1F"
  1372. const wantSecond = "FF:EE:DD:CC:BB:AA:99:88:77:66:55:44:33:22:11:00:FF:EE:DD:CC:BB:AA:99:88:77:66:55:44:33:22:11:00"
  1373. tests := []struct {
  1374. name string
  1375. pins any
  1376. want string
  1377. }{
  1378. {
  1379. name: "invalid first pin uses second",
  1380. pins: []any{"not-a-certificate-pin", secondPin},
  1381. want: wantSecond,
  1382. },
  1383. {
  1384. name: "two valid pins use first",
  1385. pins: []any{firstPin, secondPin},
  1386. want: wantFirst,
  1387. },
  1388. }
  1389. for _, tt := range tests {
  1390. t.Run(tt.name, func(t *testing.T) {
  1391. if got := mihomoCertFingerprint(tt.pins); got != tt.want {
  1392. t.Fatalf("mihomoCertFingerprint() = %q, want %q", got, tt.want)
  1393. }
  1394. })
  1395. }
  1396. }