1
0

clash_service_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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. "sessionIDPlacement": "query",
  304. "sessionIDKey": "sess",
  305. "sessionIDTable": "Base62",
  306. "sessionIDLength": "16-32",
  307. "seqPlacement": "header",
  308. "seqKey": "seq",
  309. "uplinkDataPlacement": "body",
  310. "uplinkDataKey": "udata",
  311. "uplinkChunkSize": "64-256",
  312. "noGRPCHeader": true,
  313. "scMaxEachPostBytes": "500000",
  314. "scMinPostsIntervalMs": "50",
  315. "xmux": map[string]any{
  316. "maxConcurrency": "16-32",
  317. "maxConnections": "4",
  318. "cMaxReuseTimes": "8",
  319. "hMaxRequestTimes": "600-900",
  320. "hMaxReusableSecs": "1800-3000",
  321. "hKeepAlivePeriod": float64(60),
  322. },
  323. "headers": map[string]any{
  324. "User-Agent": "chrome",
  325. "Host": "should-be-dropped.com",
  326. },
  327. }
  328. opts := buildXhttpClashOpts(xhttp)
  329. if opts == nil {
  330. t.Fatal("expected non-nil opts for full field mapping")
  331. }
  332. // Direct fields
  333. if opts["path"] != "/api/v1" {
  334. t.Errorf("path = %v, want /api/v1", opts["path"])
  335. }
  336. if opts["mode"] != "stream-up" {
  337. t.Errorf("mode = %v, want stream-up", opts["mode"])
  338. }
  339. if opts["host"] != "example.com" {
  340. t.Errorf("host = %v, want example.com", opts["host"])
  341. }
  342. // String fields
  343. if opts["x-padding-bytes"] != "100-1000" {
  344. t.Errorf("x-padding-bytes = %v", opts["x-padding-bytes"])
  345. }
  346. if opts["uplink-http-method"] != "POST" {
  347. t.Errorf("uplink-http-method = %v", opts["uplink-http-method"])
  348. }
  349. if opts["session-id-placement"] != "query" {
  350. t.Errorf("session-id-placement = %v", opts["session-id-placement"])
  351. }
  352. if opts["session-id-key"] != "sess" {
  353. t.Errorf("session-id-key = %v", opts["session-id-key"])
  354. }
  355. if opts["session-id-table"] != "Base62" {
  356. t.Errorf("session-id-table = %v", opts["session-id-table"])
  357. }
  358. if opts["session-id-length"] != "16-32" {
  359. t.Errorf("session-id-length = %v", opts["session-id-length"])
  360. }
  361. if opts["seq-placement"] != "header" {
  362. t.Errorf("seq-placement = %v", opts["seq-placement"])
  363. }
  364. if opts["seq-key"] != "seq" {
  365. t.Errorf("seq-key = %v", opts["seq-key"])
  366. }
  367. if opts["uplink-data-placement"] != "body" {
  368. t.Errorf("uplink-data-placement = %v", opts["uplink-data-placement"])
  369. }
  370. if opts["uplink-data-key"] != "udata" {
  371. t.Errorf("uplink-data-key = %v", opts["uplink-data-key"])
  372. }
  373. // DPI-filtered fields (non-default values should pass)
  374. if opts["sc-max-each-post-bytes"] != "500000" {
  375. t.Errorf("sc-max-each-post-bytes = %v", opts["sc-max-each-post-bytes"])
  376. }
  377. if opts["sc-min-posts-interval-ms"] != "50" {
  378. t.Errorf("sc-min-posts-interval-ms = %v", opts["sc-min-posts-interval-ms"])
  379. }
  380. // Bool fields
  381. if opts["no-grpc-header"] != true {
  382. t.Errorf("no-grpc-header = %v, want true", opts["no-grpc-header"])
  383. }
  384. if opts["x-padding-obfs-mode"] != true {
  385. t.Errorf("x-padding-obfs-mode = %v, want true", opts["x-padding-obfs-mode"])
  386. }
  387. // Padding obfs gated fields
  388. if opts["x-padding-key"] != "mykey" {
  389. t.Errorf("x-padding-key = %v", opts["x-padding-key"])
  390. }
  391. if opts["x-padding-header"] != "X-Trace-ID" {
  392. t.Errorf("x-padding-header = %v", opts["x-padding-header"])
  393. }
  394. if opts["x-padding-placement"] != "queryInHeader" {
  395. t.Errorf("x-padding-placement = %v", opts["x-padding-placement"])
  396. }
  397. if opts["x-padding-method"] != "tokenish" {
  398. t.Errorf("x-padding-method = %v", opts["x-padding-method"])
  399. }
  400. // Non-zero value fields
  401. if opts["uplink-chunk-size"] != "64-256" {
  402. t.Errorf("uplink-chunk-size = %v", opts["uplink-chunk-size"])
  403. }
  404. // Reuse-settings (xmux)
  405. reuse, ok := opts["reuse-settings"].(map[string]any)
  406. if !ok {
  407. t.Fatalf("reuse-settings missing or wrong type: %#v", opts["reuse-settings"])
  408. }
  409. if reuse["max-concurrency"] != "16-32" {
  410. t.Errorf("max-concurrency = %v", reuse["max-concurrency"])
  411. }
  412. if reuse["max-connections"] != "4" {
  413. t.Errorf("max-connections = %v", reuse["max-connections"])
  414. }
  415. if reuse["c-max-reuse-times"] != "8" {
  416. t.Errorf("c-max-reuse-times = %v", reuse["c-max-reuse-times"])
  417. }
  418. if reuse["h-max-request-times"] != "600-900" {
  419. t.Errorf("h-max-request-times = %v", reuse["h-max-request-times"])
  420. }
  421. if reuse["h-max-reusable-secs"] != "1800-3000" {
  422. t.Errorf("h-max-reusable-secs = %v", reuse["h-max-reusable-secs"])
  423. }
  424. if reuse["h-keep-alive-period"] != float64(60) {
  425. t.Errorf("h-keep-alive-period = %v, want 60", reuse["h-keep-alive-period"])
  426. }
  427. // Headers (Host should be dropped)
  428. headers, ok := opts["headers"].(map[string]any)
  429. if !ok {
  430. t.Fatalf("headers missing or wrong type: %#v", opts["headers"])
  431. }
  432. if headers["User-Agent"] != "chrome" {
  433. t.Errorf("headers[User-Agent] = %v", headers["User-Agent"])
  434. }
  435. if _, has := headers["Host"]; has {
  436. t.Error("headers should not contain Host key")
  437. }
  438. if _, has := headers["host"]; has {
  439. t.Error("headers should not contain host key (case-insensitive)")
  440. }
  441. }
  442. func TestBuildXhttpClashOpts_DPIDefaultsFiltered(t *testing.T) {
  443. xhttp := map[string]any{
  444. "path": "/",
  445. "mode": "stream-up",
  446. "scMaxEachPostBytes": "1000000",
  447. "scMinPostsIntervalMs": "30",
  448. }
  449. opts := buildXhttpClashOpts(xhttp)
  450. if opts == nil {
  451. t.Fatal("expected non-nil opts (path and mode should be present)")
  452. }
  453. if _, has := opts["sc-max-each-post-bytes"]; has {
  454. t.Error("sc-max-each-post-bytes should be filtered when value is 1000000")
  455. }
  456. if _, has := opts["sc-min-posts-interval-ms"]; has {
  457. t.Error("sc-min-posts-interval-ms should be filtered when value is 30")
  458. }
  459. }
  460. func TestBuildXhttpClashOpts_PaddingObfsGate(t *testing.T) {
  461. // Sub-test 1: obfs mode false — gated fields should not appear
  462. t.Run("ObfsModeFalse", func(t *testing.T) {
  463. xhttp := map[string]any{
  464. "path": "/",
  465. "xPaddingObfsMode": false,
  466. "xPaddingKey": "should-not-appear",
  467. }
  468. opts := buildXhttpClashOpts(xhttp)
  469. if opts == nil {
  470. t.Fatal("expected non-nil opts")
  471. }
  472. if _, has := opts["x-padding-obfs-mode"]; has {
  473. t.Error("x-padding-obfs-mode should not appear when false")
  474. }
  475. if _, has := opts["x-padding-key"]; has {
  476. t.Error("x-padding-key should not appear when obfs mode is false")
  477. }
  478. })
  479. // Sub-test 2: obfs mode absent — gated fields should not appear
  480. t.Run("ObfsModeAbsent", func(t *testing.T) {
  481. xhttp := map[string]any{
  482. "path": "/",
  483. "xPaddingKey": "should-not-appear",
  484. }
  485. opts := buildXhttpClashOpts(xhttp)
  486. if opts == nil {
  487. t.Fatal("expected non-nil opts")
  488. }
  489. if _, has := opts["x-padding-key"]; has {
  490. t.Error("x-padding-key should not appear when obfs mode is absent")
  491. }
  492. })
  493. // Sub-test 3: obfs mode true with no gated fields — only x-padding-obfs-mode appears
  494. t.Run("ObfsModeTrueNoGatedFields", func(t *testing.T) {
  495. xhttp := map[string]any{
  496. "path": "/",
  497. "xPaddingObfsMode": true,
  498. }
  499. opts := buildXhttpClashOpts(xhttp)
  500. if opts == nil {
  501. t.Fatal("expected non-nil opts")
  502. }
  503. if opts["x-padding-obfs-mode"] != true {
  504. t.Errorf("x-padding-obfs-mode = %v, want true", opts["x-padding-obfs-mode"])
  505. }
  506. if _, has := opts["x-padding-key"]; has {
  507. t.Error("x-padding-key should not appear when not set")
  508. }
  509. })
  510. }
  511. func TestBuildXhttpClashOpts_XmuxMapsToReuseSettings(t *testing.T) {
  512. // Sub-test 1: full xmux mapping
  513. t.Run("FullXmux", func(t *testing.T) {
  514. xhttp := map[string]any{
  515. "path": "/",
  516. "xmux": map[string]any{
  517. "maxConcurrency": "16-32",
  518. "maxConnections": "4",
  519. "cMaxReuseTimes": "8",
  520. "hMaxRequestTimes": "600-900",
  521. "hMaxReusableSecs": "1800-3000",
  522. "hKeepAlivePeriod": float64(60),
  523. },
  524. }
  525. opts := buildXhttpClashOpts(xhttp)
  526. if opts == nil {
  527. t.Fatal("expected non-nil opts")
  528. }
  529. reuse, ok := opts["reuse-settings"].(map[string]any)
  530. if !ok {
  531. t.Fatalf("reuse-settings missing or wrong type: %#v", opts["reuse-settings"])
  532. }
  533. if reuse["max-concurrency"] != "16-32" {
  534. t.Errorf("max-concurrency = %v", reuse["max-concurrency"])
  535. }
  536. if reuse["max-connections"] != "4" {
  537. t.Errorf("max-connections = %v", reuse["max-connections"])
  538. }
  539. if reuse["c-max-reuse-times"] != "8" {
  540. t.Errorf("c-max-reuse-times = %v", reuse["c-max-reuse-times"])
  541. }
  542. if reuse["h-max-request-times"] != "600-900" {
  543. t.Errorf("h-max-request-times = %v", reuse["h-max-request-times"])
  544. }
  545. if reuse["h-max-reusable-secs"] != "1800-3000" {
  546. t.Errorf("h-max-reusable-secs = %v", reuse["h-max-reusable-secs"])
  547. }
  548. if reuse["h-keep-alive-period"] != float64(60) {
  549. t.Errorf("h-keep-alive-period = %v, want 60", reuse["h-keep-alive-period"])
  550. }
  551. })
  552. // Sub-test 2: empty xmux map — no reuse-settings key
  553. t.Run("EmptyXmux", func(t *testing.T) {
  554. xhttp := map[string]any{
  555. "path": "/",
  556. "xmux": map[string]any{},
  557. }
  558. opts := buildXhttpClashOpts(xhttp)
  559. if opts == nil {
  560. t.Fatal("expected non-nil opts (path is present)")
  561. }
  562. if _, has := opts["reuse-settings"]; has {
  563. t.Error("reuse-settings should not appear for empty xmux")
  564. }
  565. })
  566. // Sub-test 3: hKeepAlivePeriod as int (not float64)
  567. t.Run("IntKeepAlivePeriod", func(t *testing.T) {
  568. xhttp := map[string]any{
  569. "path": "/",
  570. "xmux": map[string]any{
  571. "hKeepAlivePeriod": int(60),
  572. },
  573. }
  574. opts := buildXhttpClashOpts(xhttp)
  575. if opts == nil {
  576. t.Fatal("expected non-nil opts")
  577. }
  578. reuse, ok := opts["reuse-settings"].(map[string]any)
  579. if !ok {
  580. t.Fatalf("reuse-settings missing: %#v", opts["reuse-settings"])
  581. }
  582. if reuse["h-keep-alive-period"] != int(60) {
  583. t.Errorf("h-keep-alive-period = %v (%T), want 60 (int)", reuse["h-keep-alive-period"], reuse["h-keep-alive-period"])
  584. }
  585. })
  586. // Sub-test 4: hKeepAlivePeriod=0 should be filtered
  587. t.Run("ZeroKeepAlivePeriod", func(t *testing.T) {
  588. xhttp := map[string]any{
  589. "path": "/",
  590. "xmux": map[string]any{
  591. "hKeepAlivePeriod": float64(0),
  592. },
  593. }
  594. opts := buildXhttpClashOpts(xhttp)
  595. if opts == nil {
  596. t.Fatal("expected non-nil opts")
  597. }
  598. if _, has := opts["reuse-settings"]; has {
  599. t.Error("reuse-settings should not appear when only hKeepAlivePeriod=0")
  600. }
  601. })
  602. }
  603. func TestBuildXhttpClashOpts_ServerOnlyFieldsExcluded(t *testing.T) {
  604. xhttp := map[string]any{
  605. "path": "/",
  606. "noSSEHeader": true,
  607. "scMaxBufferedPosts": "100",
  608. "scStreamUpServerSecs": "5",
  609. "serverMaxHeaderBytes": "4096",
  610. }
  611. opts := buildXhttpClashOpts(xhttp)
  612. if opts == nil {
  613. t.Fatal("expected non-nil opts (path is present)")
  614. }
  615. if _, has := opts["no-sse-header"]; has {
  616. t.Error("noSSEHeader should not appear in Clash output (server-only)")
  617. }
  618. if _, has := opts["sc-max-buffered-posts"]; has {
  619. t.Error("scMaxBufferedPosts should not appear in Clash output (server-only)")
  620. }
  621. if _, has := opts["sc-stream-up-server-secs"]; has {
  622. t.Error("scStreamUpServerSecs should not appear in Clash output (server-only)")
  623. }
  624. if _, has := opts["server-max-header-bytes"]; has {
  625. t.Error("serverMaxHeaderBytes should not appear in Clash output (not in Mihomo)")
  626. }
  627. }
  628. func TestBuildXhttpClashOpts_NilInput(t *testing.T) {
  629. opts := buildXhttpClashOpts(nil)
  630. if opts != nil {
  631. t.Fatalf("expected nil for nil input, got %#v", opts)
  632. }
  633. }
  634. func TestBuildXhttpClashOpts_EmptyInput(t *testing.T) {
  635. opts := buildXhttpClashOpts(map[string]any{})
  636. if opts != nil {
  637. t.Fatalf("expected nil for empty input, got %#v", opts)
  638. }
  639. }
  640. func TestBuildXhttpClashOpts_HostFallbackFromHeaders(t *testing.T) {
  641. // Sub-test 1: host from headers.Host
  642. t.Run("HostFromHeaders", func(t *testing.T) {
  643. xhttp := map[string]any{
  644. "path": "/",
  645. "headers": map[string]any{"Host": "via-header.example.com"},
  646. }
  647. opts := buildXhttpClashOpts(xhttp)
  648. if opts == nil {
  649. t.Fatal("expected non-nil opts")
  650. }
  651. if opts["host"] != "via-header.example.com" {
  652. t.Errorf("host = %v, want via-header.example.com", opts["host"])
  653. }
  654. })
  655. // Sub-test 2: headers only contains Host — no headers key in output
  656. t.Run("HeadersOnlyHost", func(t *testing.T) {
  657. xhttp := map[string]any{
  658. "path": "/",
  659. "headers": map[string]any{"Host": "only-host.example.com"},
  660. }
  661. opts := buildXhttpClashOpts(xhttp)
  662. if opts == nil {
  663. t.Fatal("expected non-nil opts")
  664. }
  665. if _, has := opts["headers"]; has {
  666. t.Error("headers key should not appear when only Host is present (Host is extracted to top-level)")
  667. }
  668. })
  669. // Sub-test 3: case-insensitive Host drop
  670. t.Run("CaseInsensitiveHostDrop", func(t *testing.T) {
  671. xhttp := map[string]any{
  672. "path": "/",
  673. "host": "explicit.example.com",
  674. "headers": map[string]any{
  675. "host": "lowercase-host.example.com",
  676. "X-Custom": "value",
  677. },
  678. }
  679. opts := buildXhttpClashOpts(xhttp)
  680. if opts == nil {
  681. t.Fatal("expected non-nil opts")
  682. }
  683. if opts["host"] != "explicit.example.com" {
  684. t.Errorf("host = %v, want explicit.example.com (explicit host wins)", opts["host"])
  685. }
  686. headers, ok := opts["headers"].(map[string]any)
  687. if !ok {
  688. t.Fatal("headers should be present (X-Custom remains)")
  689. }
  690. if _, has := headers["host"]; has {
  691. t.Error("lowercase 'host' should be dropped from headers")
  692. }
  693. if headers["X-Custom"] != "value" {
  694. t.Errorf("X-Custom = %v, want value", headers["X-Custom"])
  695. }
  696. })
  697. }
  698. func TestBuildXhttpClashOpts_NoGRPCHeaderFalsey(t *testing.T) {
  699. // Sub-test 1: noGRPCHeader: false
  700. t.Run("ExplicitFalse", func(t *testing.T) {
  701. xhttp := map[string]any{
  702. "path": "/",
  703. "noGRPCHeader": false,
  704. }
  705. opts := buildXhttpClashOpts(xhttp)
  706. if opts == nil {
  707. t.Fatal("expected non-nil opts (path is present)")
  708. }
  709. if _, has := opts["no-grpc-header"]; has {
  710. t.Error("no-grpc-header should not appear when noGRPCHeader is false")
  711. }
  712. })
  713. // Sub-test 2: noGRPCHeader absent
  714. t.Run("Absent", func(t *testing.T) {
  715. xhttp := map[string]any{
  716. "path": "/",
  717. }
  718. opts := buildXhttpClashOpts(xhttp)
  719. if opts == nil {
  720. t.Fatal("expected non-nil opts")
  721. }
  722. if _, has := opts["no-grpc-header"]; has {
  723. t.Error("no-grpc-header should not appear when absent")
  724. }
  725. })
  726. }