clash_service_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. package sub
  2. import (
  3. "reflect"
  4. "testing"
  5. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  6. )
  7. func TestEnsureUniqueProxyNames(t *testing.T) {
  8. proxies := []map[string]any{
  9. {"name": "", "type": "vless", "server": "a.com", "port": 443},
  10. {"name": "", "type": "vmess", "server": "b.com", "port": 8443},
  11. {"name": "node"},
  12. {"name": "node"},
  13. {"name": ""},
  14. }
  15. ensureUniqueProxyNames(proxies)
  16. seen := map[string]bool{}
  17. for i, p := range proxies {
  18. name, _ := p["name"].(string)
  19. if name == "" {
  20. t.Fatalf("proxy %d still has an empty name (mihomo would reject the config, #4641)", i)
  21. }
  22. if seen[name] {
  23. t.Fatalf("proxy %d has duplicate name %q (mihomo rejects the whole config, #4641)", i, name)
  24. }
  25. seen[name] = true
  26. }
  27. if got := proxies[0]["name"]; got != "vless-a.com-443" {
  28. t.Errorf("empty name fallback = %q, want vless-a.com-443", got)
  29. }
  30. if proxies[2]["name"] == proxies[3]["name"] {
  31. t.Errorf("duplicate %q was not disambiguated", proxies[2]["name"])
  32. }
  33. if got := proxies[4]["name"]; got != "proxy-5" {
  34. t.Errorf("typeless empty name fallback = %q, want proxy-5", got)
  35. }
  36. }
  37. // TestBuildProxy_VLESSRealityFieldsForClash locks the reality field mapping in
  38. // applySecurity (clash_service.go ~488): a regression that drops servername,
  39. // public-key, short-id, or client-fingerprint would hand mihomo a broken reality
  40. // proxy. The existing clash tests don't assert any of these.
  41. func TestBuildProxy_VLESSRealityFieldsForClash(t *testing.T) {
  42. svc := &SubClashService{SubService: &SubService{}}
  43. inbound := &model.Inbound{Listen: "203.0.113.1", Port: 443, Protocol: model.VLESS, Remark: "r", Settings: `{"encryption":"none"}`}
  44. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  45. stream := map[string]any{
  46. "network": "tcp",
  47. "security": "reality",
  48. "tcpSettings": map[string]any{"header": map[string]any{"type": "none"}},
  49. "realitySettings": map[string]any{"serverName": "reality.example.com", "publicKey": "PBKvalue", "shortId": "ab12", "fingerprint": "chrome"},
  50. }
  51. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  52. if proxy == nil {
  53. t.Fatal("buildProxy returned nil for a valid reality stream")
  54. }
  55. if proxy["tls"] != true {
  56. t.Fatalf("tls = %v, want true", proxy["tls"])
  57. }
  58. if proxy["servername"] != "reality.example.com" {
  59. t.Fatalf("servername = %v, want reality.example.com", proxy["servername"])
  60. }
  61. if proxy["client-fingerprint"] != "chrome" {
  62. t.Fatalf("client-fingerprint = %v, want chrome", proxy["client-fingerprint"])
  63. }
  64. opts, _ := proxy["reality-opts"].(map[string]any)
  65. if opts == nil {
  66. t.Fatal("reality-opts missing")
  67. }
  68. if opts["public-key"] != "PBKvalue" {
  69. t.Fatalf("public-key = %v, want PBKvalue", opts["public-key"])
  70. }
  71. if opts["short-id"] != "ab12" {
  72. t.Fatalf("short-id = %v, want ab12", opts["short-id"])
  73. }
  74. }
  75. // TestApplyTransport_TCPHeader pins the tcp-header validation (clash_service.go ~359):
  76. // plain tcp and a "none" header are representable in clash; a non-none obfs header is
  77. // not, so applyTransport must reject it (returning false drops it from the YAML).
  78. func TestApplyTransport_TCPHeader(t *testing.T) {
  79. svc := &SubClashService{}
  80. if !svc.applyTransport(map[string]any{}, "tcp", map[string]any{}) {
  81. t.Fatal("plain tcp must be buildable")
  82. }
  83. noneStream := map[string]any{"tcpSettings": map[string]any{"header": map[string]any{"type": "none"}}}
  84. if !svc.applyTransport(map[string]any{}, "tcp", noneStream) {
  85. t.Fatal("tcp + header type none must be buildable")
  86. }
  87. httpStream := map[string]any{"tcpSettings": map[string]any{"header": map[string]any{"type": "http"}}}
  88. if svc.applyTransport(map[string]any{}, "tcp", httpStream) {
  89. t.Fatal("tcp + non-none (http) header is not representable in clash and must be rejected")
  90. }
  91. }
  92. func TestApplyTransport_XHTTP(t *testing.T) {
  93. svc := &SubClashService{}
  94. proxy := map[string]any{}
  95. stream := map[string]any{
  96. "xhttpSettings": map[string]any{
  97. "path": "/xh",
  98. "host": "example.com",
  99. "mode": "auto",
  100. },
  101. }
  102. if !svc.applyTransport(proxy, "xhttp", stream) {
  103. t.Fatalf("applyTransport returned false for xhttp (#4531: would drop the inbound and yield an empty Clash YAML)")
  104. }
  105. if proxy["network"] != "xhttp" {
  106. t.Fatalf("network = %v, want xhttp", proxy["network"])
  107. }
  108. opts, ok := proxy["xhttp-opts"].(map[string]any)
  109. if !ok {
  110. t.Fatalf("xhttp-opts missing or wrong type: %#v", proxy["xhttp-opts"])
  111. }
  112. want := map[string]any{"path": "/xh", "host": "example.com", "mode": "auto"}
  113. if !reflect.DeepEqual(opts, want) {
  114. t.Fatalf("xhttp-opts = %#v, want %#v", opts, want)
  115. }
  116. }
  117. func TestApplyTransport_XHTTP_HostFromHeaders(t *testing.T) {
  118. svc := &SubClashService{}
  119. proxy := map[string]any{}
  120. stream := map[string]any{
  121. "xhttpSettings": map[string]any{
  122. "path": "/xh",
  123. "headers": map[string]any{"Host": "via-header.example.com"},
  124. },
  125. }
  126. if !svc.applyTransport(proxy, "xhttp", stream) {
  127. t.Fatalf("applyTransport returned false for xhttp")
  128. }
  129. opts, _ := proxy["xhttp-opts"].(map[string]any)
  130. if opts["host"] != "via-header.example.com" {
  131. t.Fatalf("host should fall back to headers.Host, got %v", opts["host"])
  132. }
  133. }
  134. func TestApplyTransport_XHTTP_NoSettings(t *testing.T) {
  135. svc := &SubClashService{}
  136. proxy := map[string]any{}
  137. stream := map[string]any{}
  138. if !svc.applyTransport(proxy, "xhttp", stream) {
  139. t.Fatalf("applyTransport returned false for xhttp with no xhttpSettings")
  140. }
  141. if proxy["network"] != "xhttp" {
  142. t.Fatalf("network = %v, want xhttp", proxy["network"])
  143. }
  144. if _, exists := proxy["xhttp-opts"]; exists {
  145. t.Fatalf("xhttp-opts should be absent when xhttpSettings is missing, got %#v", proxy["xhttp-opts"])
  146. }
  147. }
  148. func TestApplyTransport_HTTPUpgrade(t *testing.T) {
  149. svc := &SubClashService{}
  150. proxy := map[string]any{}
  151. stream := map[string]any{
  152. "httpupgradeSettings": map[string]any{
  153. "path": "/hu",
  154. "host": "example.com",
  155. },
  156. }
  157. if !svc.applyTransport(proxy, "httpupgrade", stream) {
  158. t.Fatalf("applyTransport returned false for httpupgrade")
  159. }
  160. if proxy["network"] != "httpupgrade" {
  161. t.Fatalf("network = %v, want httpupgrade", proxy["network"])
  162. }
  163. opts, ok := proxy["http-upgrade-opts"].(map[string]any)
  164. if !ok {
  165. t.Fatalf("http-upgrade-opts missing: %#v", proxy["http-upgrade-opts"])
  166. }
  167. if opts["path"] != "/hu" {
  168. t.Fatalf("path = %v, want /hu", opts["path"])
  169. }
  170. headers, _ := opts["headers"].(map[string]any)
  171. if headers["Host"] != "example.com" {
  172. t.Fatalf("headers.Host = %v, want example.com", headers["Host"])
  173. }
  174. }
  175. func TestBuildProxy_VLESSPostQuantumEncryptionUsesMihomoEncryptionField(t *testing.T) {
  176. svc := &SubClashService{SubService: &SubService{}}
  177. encryption := "mlkem768x25519plus.native.0rtt.client"
  178. inbound := &model.Inbound{
  179. Listen: "203.0.113.1",
  180. Port: 443,
  181. Protocol: model.VLESS,
  182. Remark: "pq",
  183. Settings: `{"encryption":"` + encryption + `"}`,
  184. }
  185. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  186. stream := map[string]any{
  187. "network": "xhttp",
  188. "xhttpSettings": map[string]any{
  189. "path": "/",
  190. "mode": "auto",
  191. },
  192. "security": "reality",
  193. "realitySettings": map[string]any{
  194. "publicKey": "pub",
  195. "serverName": "example.com",
  196. "shortId": "abcd",
  197. },
  198. }
  199. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  200. if proxy["encryption"] != encryption {
  201. t.Fatalf("encryption = %v, want %q", proxy["encryption"], encryption)
  202. }
  203. }
  204. func TestBuildProxy_VLESSFlowXhttpRealityVlessenc(t *testing.T) {
  205. svc := &SubClashService{SubService: &SubService{}}
  206. encryption := "mlkem768x25519plus.native.0rtt.client"
  207. inbound := &model.Inbound{
  208. Listen: "203.0.113.1",
  209. Port: 443,
  210. Protocol: model.VLESS,
  211. Remark: "pq-flow",
  212. Settings: `{"encryption":"` + encryption + `"}`,
  213. }
  214. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Flow: "xtls-rprx-vision"}
  215. stream := map[string]any{
  216. "network": "xhttp",
  217. "xhttpSettings": map[string]any{
  218. "path": "/",
  219. "mode": "auto",
  220. },
  221. "security": "reality",
  222. "realitySettings": map[string]any{
  223. "publicKey": "pub",
  224. "serverName": "example.com",
  225. "shortId": "abcd",
  226. },
  227. }
  228. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  229. if proxy["flow"] != "xtls-rprx-vision" {
  230. t.Fatalf("xhttp+reality+vlessenc Clash proxy must carry the vision flow (#5232): %#v", proxy)
  231. }
  232. }
  233. func TestBuildProxy_VLESSFlowDroppedWithoutVisionSupport(t *testing.T) {
  234. svc := &SubClashService{SubService: &SubService{}}
  235. inbound := &model.Inbound{
  236. Listen: "203.0.113.1",
  237. Port: 443,
  238. Protocol: model.VLESS,
  239. Remark: "plain-flow",
  240. Settings: `{"encryption":"none"}`,
  241. }
  242. client := model.Client{ID: "11111111-2222-4333-8444-555555555555", Flow: "xtls-rprx-vision"}
  243. stream := map[string]any{
  244. "network": "tcp",
  245. "security": "none",
  246. "tcpSettings": map[string]any{
  247. "header": map[string]any{"type": "none"},
  248. },
  249. }
  250. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  251. if _, ok := proxy["flow"]; ok {
  252. t.Fatalf("tcp without tls/reality must not carry a flow: %#v", proxy)
  253. }
  254. }
  255. func TestBuildProxy_VLESSNoneEncryptionOmittedForClash(t *testing.T) {
  256. svc := &SubClashService{SubService: &SubService{}}
  257. inbound := &model.Inbound{
  258. Listen: "203.0.113.1",
  259. Port: 443,
  260. Protocol: model.VLESS,
  261. Remark: "plain",
  262. Settings: `{"encryption":"none"}`,
  263. }
  264. client := model.Client{ID: "11111111-2222-4333-8444-555555555555"}
  265. stream := map[string]any{
  266. "network": "tcp",
  267. "security": "none",
  268. "tcpSettings": map[string]any{
  269. "header": map[string]any{"type": "none"},
  270. },
  271. }
  272. proxy := svc.buildProxy(svc.SubService, inbound, client, stream, nil)
  273. if _, ok := proxy["encryption"]; ok {
  274. t.Fatalf("plain vless encryption should be omitted for mihomo: %#v", proxy)
  275. }
  276. // The rest of the proxy must still be well-formed — otherwise a mutant that
  277. // drops encryption *and* corrupts a core field passes the absence check alone.
  278. if proxy["type"] != "vless" {
  279. t.Fatalf("type = %v, want vless", proxy["type"])
  280. }
  281. if proxy["server"] != "203.0.113.1" {
  282. t.Fatalf("server = %v, want 203.0.113.1", proxy["server"])
  283. }
  284. if proxy["port"] != 443 {
  285. t.Fatalf("port = %v, want 443", proxy["port"])
  286. }
  287. if proxy["uuid"] != client.ID {
  288. t.Fatalf("uuid = %v, want %v", proxy["uuid"], client.ID)
  289. }
  290. }
  291. func TestBuildXhttpClashOpts_FullFieldMapping(t *testing.T) {
  292. xhttp := map[string]any{
  293. "path": "/api/v1",
  294. "mode": "stream-up",
  295. "host": "example.com",
  296. "xPaddingBytes": "100-1000",
  297. "xPaddingObfsMode": true,
  298. "xPaddingKey": "mykey",
  299. "xPaddingHeader": "X-Trace-ID",
  300. "xPaddingPlacement": "queryInHeader",
  301. "xPaddingMethod": "tokenish",
  302. "uplinkHTTPMethod": "POST",
  303. "sessionPlacement": "query",
  304. "sessionKey": "sess",
  305. "seqPlacement": "header",
  306. "seqKey": "seq",
  307. "uplinkDataPlacement": "body",
  308. "uplinkDataKey": "udata",
  309. "uplinkChunkSize": "64-256",
  310. "noGRPCHeader": true,
  311. "scMaxEachPostBytes": "500000",
  312. "scMinPostsIntervalMs": "50",
  313. "xmux": map[string]any{
  314. "maxConcurrency": "16-32",
  315. "maxConnections": "4",
  316. "cMaxReuseTimes": "8",
  317. "hMaxRequestTimes": "600-900",
  318. "hMaxReusableSecs": "1800-3000",
  319. "hKeepAlivePeriod": float64(60),
  320. },
  321. "headers": map[string]any{
  322. "User-Agent": "chrome",
  323. "Host": "should-be-dropped.com",
  324. },
  325. }
  326. opts := buildXhttpClashOpts(xhttp)
  327. if opts == nil {
  328. t.Fatal("expected non-nil opts for full field mapping")
  329. }
  330. // Direct fields
  331. if opts["path"] != "/api/v1" {
  332. t.Errorf("path = %v, want /api/v1", opts["path"])
  333. }
  334. if opts["mode"] != "stream-up" {
  335. t.Errorf("mode = %v, want stream-up", opts["mode"])
  336. }
  337. if opts["host"] != "example.com" {
  338. t.Errorf("host = %v, want example.com", opts["host"])
  339. }
  340. // String fields
  341. if opts["x-padding-bytes"] != "100-1000" {
  342. t.Errorf("x-padding-bytes = %v", opts["x-padding-bytes"])
  343. }
  344. if opts["uplink-http-method"] != "POST" {
  345. t.Errorf("uplink-http-method = %v", opts["uplink-http-method"])
  346. }
  347. if opts["session-placement"] != "query" {
  348. t.Errorf("session-placement = %v", opts["session-placement"])
  349. }
  350. if opts["session-key"] != "sess" {
  351. t.Errorf("session-key = %v", opts["session-key"])
  352. }
  353. if opts["seq-placement"] != "header" {
  354. t.Errorf("seq-placement = %v", opts["seq-placement"])
  355. }
  356. if opts["seq-key"] != "seq" {
  357. t.Errorf("seq-key = %v", opts["seq-key"])
  358. }
  359. if opts["uplink-data-placement"] != "body" {
  360. t.Errorf("uplink-data-placement = %v", opts["uplink-data-placement"])
  361. }
  362. if opts["uplink-data-key"] != "udata" {
  363. t.Errorf("uplink-data-key = %v", opts["uplink-data-key"])
  364. }
  365. // DPI-filtered fields (non-default values should pass)
  366. if opts["sc-max-each-post-bytes"] != "500000" {
  367. t.Errorf("sc-max-each-post-bytes = %v", opts["sc-max-each-post-bytes"])
  368. }
  369. if opts["sc-min-posts-interval-ms"] != "50" {
  370. t.Errorf("sc-min-posts-interval-ms = %v", opts["sc-min-posts-interval-ms"])
  371. }
  372. // Bool fields
  373. if opts["no-grpc-header"] != true {
  374. t.Errorf("no-grpc-header = %v, want true", opts["no-grpc-header"])
  375. }
  376. if opts["x-padding-obfs-mode"] != true {
  377. t.Errorf("x-padding-obfs-mode = %v, want true", opts["x-padding-obfs-mode"])
  378. }
  379. // Padding obfs gated fields
  380. if opts["x-padding-key"] != "mykey" {
  381. t.Errorf("x-padding-key = %v", opts["x-padding-key"])
  382. }
  383. if opts["x-padding-header"] != "X-Trace-ID" {
  384. t.Errorf("x-padding-header = %v", opts["x-padding-header"])
  385. }
  386. if opts["x-padding-placement"] != "queryInHeader" {
  387. t.Errorf("x-padding-placement = %v", opts["x-padding-placement"])
  388. }
  389. if opts["x-padding-method"] != "tokenish" {
  390. t.Errorf("x-padding-method = %v", opts["x-padding-method"])
  391. }
  392. // Non-zero value fields
  393. if opts["uplink-chunk-size"] != "64-256" {
  394. t.Errorf("uplink-chunk-size = %v", opts["uplink-chunk-size"])
  395. }
  396. // Reuse-settings (xmux)
  397. reuse, ok := opts["reuse-settings"].(map[string]any)
  398. if !ok {
  399. t.Fatalf("reuse-settings missing or wrong type: %#v", opts["reuse-settings"])
  400. }
  401. if reuse["max-concurrency"] != "16-32" {
  402. t.Errorf("max-concurrency = %v", reuse["max-concurrency"])
  403. }
  404. if reuse["max-connections"] != "4" {
  405. t.Errorf("max-connections = %v", reuse["max-connections"])
  406. }
  407. if reuse["c-max-reuse-times"] != "8" {
  408. t.Errorf("c-max-reuse-times = %v", reuse["c-max-reuse-times"])
  409. }
  410. if reuse["h-max-request-times"] != "600-900" {
  411. t.Errorf("h-max-request-times = %v", reuse["h-max-request-times"])
  412. }
  413. if reuse["h-max-reusable-secs"] != "1800-3000" {
  414. t.Errorf("h-max-reusable-secs = %v", reuse["h-max-reusable-secs"])
  415. }
  416. if reuse["h-keep-alive-period"] != float64(60) {
  417. t.Errorf("h-keep-alive-period = %v, want 60", reuse["h-keep-alive-period"])
  418. }
  419. // Headers (Host should be dropped)
  420. headers, ok := opts["headers"].(map[string]any)
  421. if !ok {
  422. t.Fatalf("headers missing or wrong type: %#v", opts["headers"])
  423. }
  424. if headers["User-Agent"] != "chrome" {
  425. t.Errorf("headers[User-Agent] = %v", headers["User-Agent"])
  426. }
  427. if _, has := headers["Host"]; has {
  428. t.Error("headers should not contain Host key")
  429. }
  430. if _, has := headers["host"]; has {
  431. t.Error("headers should not contain host key (case-insensitive)")
  432. }
  433. }
  434. func TestBuildXhttpClashOpts_DPIDefaultsFiltered(t *testing.T) {
  435. xhttp := map[string]any{
  436. "path": "/",
  437. "mode": "stream-up",
  438. "scMaxEachPostBytes": "1000000",
  439. "scMinPostsIntervalMs": "30",
  440. }
  441. opts := buildXhttpClashOpts(xhttp)
  442. if opts == nil {
  443. t.Fatal("expected non-nil opts (path and mode should be present)")
  444. }
  445. if _, has := opts["sc-max-each-post-bytes"]; has {
  446. t.Error("sc-max-each-post-bytes should be filtered when value is 1000000")
  447. }
  448. if _, has := opts["sc-min-posts-interval-ms"]; has {
  449. t.Error("sc-min-posts-interval-ms should be filtered when value is 30")
  450. }
  451. }
  452. func TestBuildXhttpClashOpts_PaddingObfsGate(t *testing.T) {
  453. // Sub-test 1: obfs mode false — gated fields should not appear
  454. t.Run("ObfsModeFalse", func(t *testing.T) {
  455. xhttp := map[string]any{
  456. "path": "/",
  457. "xPaddingObfsMode": false,
  458. "xPaddingKey": "should-not-appear",
  459. }
  460. opts := buildXhttpClashOpts(xhttp)
  461. if opts == nil {
  462. t.Fatal("expected non-nil opts")
  463. }
  464. if _, has := opts["x-padding-obfs-mode"]; has {
  465. t.Error("x-padding-obfs-mode should not appear when false")
  466. }
  467. if _, has := opts["x-padding-key"]; has {
  468. t.Error("x-padding-key should not appear when obfs mode is false")
  469. }
  470. })
  471. // Sub-test 2: obfs mode absent — gated fields should not appear
  472. t.Run("ObfsModeAbsent", func(t *testing.T) {
  473. xhttp := map[string]any{
  474. "path": "/",
  475. "xPaddingKey": "should-not-appear",
  476. }
  477. opts := buildXhttpClashOpts(xhttp)
  478. if opts == nil {
  479. t.Fatal("expected non-nil opts")
  480. }
  481. if _, has := opts["x-padding-key"]; has {
  482. t.Error("x-padding-key should not appear when obfs mode is absent")
  483. }
  484. })
  485. // Sub-test 3: obfs mode true with no gated fields — only x-padding-obfs-mode appears
  486. t.Run("ObfsModeTrueNoGatedFields", func(t *testing.T) {
  487. xhttp := map[string]any{
  488. "path": "/",
  489. "xPaddingObfsMode": true,
  490. }
  491. opts := buildXhttpClashOpts(xhttp)
  492. if opts == nil {
  493. t.Fatal("expected non-nil opts")
  494. }
  495. if opts["x-padding-obfs-mode"] != true {
  496. t.Errorf("x-padding-obfs-mode = %v, want true", opts["x-padding-obfs-mode"])
  497. }
  498. if _, has := opts["x-padding-key"]; has {
  499. t.Error("x-padding-key should not appear when not set")
  500. }
  501. })
  502. }
  503. func TestBuildXhttpClashOpts_XmuxMapsToReuseSettings(t *testing.T) {
  504. // Sub-test 1: full xmux mapping
  505. t.Run("FullXmux", func(t *testing.T) {
  506. xhttp := map[string]any{
  507. "path": "/",
  508. "xmux": map[string]any{
  509. "maxConcurrency": "16-32",
  510. "maxConnections": "4",
  511. "cMaxReuseTimes": "8",
  512. "hMaxRequestTimes": "600-900",
  513. "hMaxReusableSecs": "1800-3000",
  514. "hKeepAlivePeriod": float64(60),
  515. },
  516. }
  517. opts := buildXhttpClashOpts(xhttp)
  518. if opts == nil {
  519. t.Fatal("expected non-nil opts")
  520. }
  521. reuse, ok := opts["reuse-settings"].(map[string]any)
  522. if !ok {
  523. t.Fatalf("reuse-settings missing or wrong type: %#v", opts["reuse-settings"])
  524. }
  525. if reuse["max-concurrency"] != "16-32" {
  526. t.Errorf("max-concurrency = %v", reuse["max-concurrency"])
  527. }
  528. if reuse["max-connections"] != "4" {
  529. t.Errorf("max-connections = %v", reuse["max-connections"])
  530. }
  531. if reuse["c-max-reuse-times"] != "8" {
  532. t.Errorf("c-max-reuse-times = %v", reuse["c-max-reuse-times"])
  533. }
  534. if reuse["h-max-request-times"] != "600-900" {
  535. t.Errorf("h-max-request-times = %v", reuse["h-max-request-times"])
  536. }
  537. if reuse["h-max-reusable-secs"] != "1800-3000" {
  538. t.Errorf("h-max-reusable-secs = %v", reuse["h-max-reusable-secs"])
  539. }
  540. if reuse["h-keep-alive-period"] != float64(60) {
  541. t.Errorf("h-keep-alive-period = %v, want 60", reuse["h-keep-alive-period"])
  542. }
  543. })
  544. // Sub-test 2: empty xmux map — no reuse-settings key
  545. t.Run("EmptyXmux", func(t *testing.T) {
  546. xhttp := map[string]any{
  547. "path": "/",
  548. "xmux": map[string]any{},
  549. }
  550. opts := buildXhttpClashOpts(xhttp)
  551. if opts == nil {
  552. t.Fatal("expected non-nil opts (path is present)")
  553. }
  554. if _, has := opts["reuse-settings"]; has {
  555. t.Error("reuse-settings should not appear for empty xmux")
  556. }
  557. })
  558. // Sub-test 3: hKeepAlivePeriod as int (not float64)
  559. t.Run("IntKeepAlivePeriod", func(t *testing.T) {
  560. xhttp := map[string]any{
  561. "path": "/",
  562. "xmux": map[string]any{
  563. "hKeepAlivePeriod": int(60),
  564. },
  565. }
  566. opts := buildXhttpClashOpts(xhttp)
  567. if opts == nil {
  568. t.Fatal("expected non-nil opts")
  569. }
  570. reuse, ok := opts["reuse-settings"].(map[string]any)
  571. if !ok {
  572. t.Fatalf("reuse-settings missing: %#v", opts["reuse-settings"])
  573. }
  574. if reuse["h-keep-alive-period"] != int(60) {
  575. t.Errorf("h-keep-alive-period = %v (%T), want 60 (int)", reuse["h-keep-alive-period"], reuse["h-keep-alive-period"])
  576. }
  577. })
  578. // Sub-test 4: hKeepAlivePeriod=0 should be filtered
  579. t.Run("ZeroKeepAlivePeriod", func(t *testing.T) {
  580. xhttp := map[string]any{
  581. "path": "/",
  582. "xmux": map[string]any{
  583. "hKeepAlivePeriod": float64(0),
  584. },
  585. }
  586. opts := buildXhttpClashOpts(xhttp)
  587. if opts == nil {
  588. t.Fatal("expected non-nil opts")
  589. }
  590. if _, has := opts["reuse-settings"]; has {
  591. t.Error("reuse-settings should not appear when only hKeepAlivePeriod=0")
  592. }
  593. })
  594. }
  595. func TestBuildXhttpClashOpts_ServerOnlyFieldsExcluded(t *testing.T) {
  596. xhttp := map[string]any{
  597. "path": "/",
  598. "noSSEHeader": true,
  599. "scMaxBufferedPosts": "100",
  600. "scStreamUpServerSecs": "5",
  601. "serverMaxHeaderBytes": "4096",
  602. }
  603. opts := buildXhttpClashOpts(xhttp)
  604. if opts == nil {
  605. t.Fatal("expected non-nil opts (path is present)")
  606. }
  607. if _, has := opts["no-sse-header"]; has {
  608. t.Error("noSSEHeader should not appear in Clash output (server-only)")
  609. }
  610. if _, has := opts["sc-max-buffered-posts"]; has {
  611. t.Error("scMaxBufferedPosts should not appear in Clash output (server-only)")
  612. }
  613. if _, has := opts["sc-stream-up-server-secs"]; has {
  614. t.Error("scStreamUpServerSecs should not appear in Clash output (server-only)")
  615. }
  616. if _, has := opts["server-max-header-bytes"]; has {
  617. t.Error("serverMaxHeaderBytes should not appear in Clash output (not in Mihomo)")
  618. }
  619. }
  620. func TestBuildXhttpClashOpts_NilInput(t *testing.T) {
  621. opts := buildXhttpClashOpts(nil)
  622. if opts != nil {
  623. t.Fatalf("expected nil for nil input, got %#v", opts)
  624. }
  625. }
  626. func TestBuildXhttpClashOpts_EmptyInput(t *testing.T) {
  627. opts := buildXhttpClashOpts(map[string]any{})
  628. if opts != nil {
  629. t.Fatalf("expected nil for empty input, got %#v", opts)
  630. }
  631. }
  632. func TestBuildXhttpClashOpts_HostFallbackFromHeaders(t *testing.T) {
  633. // Sub-test 1: host from headers.Host
  634. t.Run("HostFromHeaders", func(t *testing.T) {
  635. xhttp := map[string]any{
  636. "path": "/",
  637. "headers": map[string]any{"Host": "via-header.example.com"},
  638. }
  639. opts := buildXhttpClashOpts(xhttp)
  640. if opts == nil {
  641. t.Fatal("expected non-nil opts")
  642. }
  643. if opts["host"] != "via-header.example.com" {
  644. t.Errorf("host = %v, want via-header.example.com", opts["host"])
  645. }
  646. })
  647. // Sub-test 2: headers only contains Host — no headers key in output
  648. t.Run("HeadersOnlyHost", func(t *testing.T) {
  649. xhttp := map[string]any{
  650. "path": "/",
  651. "headers": map[string]any{"Host": "only-host.example.com"},
  652. }
  653. opts := buildXhttpClashOpts(xhttp)
  654. if opts == nil {
  655. t.Fatal("expected non-nil opts")
  656. }
  657. if _, has := opts["headers"]; has {
  658. t.Error("headers key should not appear when only Host is present (Host is extracted to top-level)")
  659. }
  660. })
  661. // Sub-test 3: case-insensitive Host drop
  662. t.Run("CaseInsensitiveHostDrop", func(t *testing.T) {
  663. xhttp := map[string]any{
  664. "path": "/",
  665. "host": "explicit.example.com",
  666. "headers": map[string]any{
  667. "host": "lowercase-host.example.com",
  668. "X-Custom": "value",
  669. },
  670. }
  671. opts := buildXhttpClashOpts(xhttp)
  672. if opts == nil {
  673. t.Fatal("expected non-nil opts")
  674. }
  675. if opts["host"] != "explicit.example.com" {
  676. t.Errorf("host = %v, want explicit.example.com (explicit host wins)", opts["host"])
  677. }
  678. headers, ok := opts["headers"].(map[string]any)
  679. if !ok {
  680. t.Fatal("headers should be present (X-Custom remains)")
  681. }
  682. if _, has := headers["host"]; has {
  683. t.Error("lowercase 'host' should be dropped from headers")
  684. }
  685. if headers["X-Custom"] != "value" {
  686. t.Errorf("X-Custom = %v, want value", headers["X-Custom"])
  687. }
  688. })
  689. }
  690. func TestBuildXhttpClashOpts_NoGRPCHeaderFalsey(t *testing.T) {
  691. // Sub-test 1: noGRPCHeader: false
  692. t.Run("ExplicitFalse", func(t *testing.T) {
  693. xhttp := map[string]any{
  694. "path": "/",
  695. "noGRPCHeader": false,
  696. }
  697. opts := buildXhttpClashOpts(xhttp)
  698. if opts == nil {
  699. t.Fatal("expected non-nil opts (path is present)")
  700. }
  701. if _, has := opts["no-grpc-header"]; has {
  702. t.Error("no-grpc-header should not appear when noGRPCHeader is false")
  703. }
  704. })
  705. // Sub-test 2: noGRPCHeader absent
  706. t.Run("Absent", func(t *testing.T) {
  707. xhttp := map[string]any{
  708. "path": "/",
  709. }
  710. opts := buildXhttpClashOpts(xhttp)
  711. if opts == nil {
  712. t.Fatal("expected non-nil opts")
  713. }
  714. if _, has := opts["no-grpc-header"]; has {
  715. t.Error("no-grpc-header should not appear when absent")
  716. }
  717. })
  718. }