clash_service_test.go 45 KB

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