outbound_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. package link
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "net/url"
  6. "strings"
  7. "testing"
  8. )
  9. func TestParseVmessLink(t *testing.T) {
  10. // vmess:// + base64 of:
  11. // {"v":"2","ps":"test","add":"1.2.3.4","port":443,"id":"uuid","aid":"0","net":"ws","type":"","host":"ex.com","path":"/","tls":"tls"}
  12. link := "vmess://eyJ2IjoiMiIsInBzIjoidGVzdCIsImFkZCI6IjEuMi4zLjQiLCJwb3J0Ijo0NDMsImlkIjoidXVpZCIsImFpZCI6IjAiLCJuZXQiOiJ3cyIsInR5cGUiOiIiLCJob3N0IjoiZXguY29tIiwicGF0aCI6Ii8iLCJ0bHMiOiJ0bHMifQ=="
  13. res, err := ParseLink(link)
  14. if err != nil {
  15. t.Fatalf("parse vmess: %v", err)
  16. }
  17. if res.Outbound["protocol"] != "vmess" {
  18. t.Errorf("expected vmess protocol, got %v", res.Outbound["protocol"])
  19. }
  20. if res.Outbound["tag"] != "test" {
  21. t.Errorf("expected tag 'test', got %v", res.Outbound["tag"])
  22. }
  23. }
  24. func TestLinkIdentityKeepsTLSServerName(t *testing.T) {
  25. a, errA := ParseLink("vless://[email protected]:443?type=ws&security=tls&sni=a.example.com#node")
  26. b, errB := ParseLink("vless://[email protected]:443?type=ws&security=tls&sni=b.example.com#node")
  27. if errA != nil || errB != nil {
  28. t.Fatalf("parse vless: %v, %v", errA, errB)
  29. }
  30. if a.Identity == b.Identity {
  31. t.Fatalf("TLS links for different SNIs share identity %q", a.Identity)
  32. }
  33. }
  34. func TestParseVlessLink(t *testing.T) {
  35. link := "vless://[email protected]:443?type=ws&security=tls&path=/&host=ex.com#node1"
  36. res, err := ParseLink(link)
  37. if err != nil {
  38. t.Fatalf("parse vless: %v", err)
  39. }
  40. if res.Outbound["protocol"] != "vless" {
  41. t.Fatalf("bad protocol")
  42. }
  43. if res.Outbound["tag"] != "node1" {
  44. t.Errorf("tag mismatch: %v", res.Outbound["tag"])
  45. }
  46. }
  47. func TestParseVlessLink_FinalMaskQuicParamsSanitized(t *testing.T) {
  48. fm := url.QueryEscape(`{"mask":"dtls","quicParams":{"keepAlivePeriod":"10s","maxIdleTimeout":"30","initStreamReceiveWindow":524288,"maxIncomingStreams":true,"brutalUp":"100 mbps"}}`)
  49. res, err := ParseLink("vless://[email protected]:443?type=tcp&security=none&fm=" + fm + "#node1")
  50. if err != nil {
  51. t.Fatalf("parse vless with fm: %v", err)
  52. }
  53. stream, ok := res.Outbound["streamSettings"].(map[string]any)
  54. if !ok {
  55. t.Fatalf("missing streamSettings: %v", res.Outbound)
  56. }
  57. finalmask, ok := stream["finalmask"].(map[string]any)
  58. if !ok {
  59. t.Fatalf("missing finalmask: %v", stream)
  60. }
  61. if finalmask["mask"] != "dtls" {
  62. t.Errorf("mask changed: %v", finalmask["mask"])
  63. }
  64. qp, ok := finalmask["quicParams"].(map[string]any)
  65. if !ok {
  66. t.Fatalf("missing quicParams: %v", finalmask)
  67. }
  68. if got := qp["keepAlivePeriod"]; got != int64(10) {
  69. t.Errorf("keepAlivePeriod: expected 10, got %v (%T)", got, got)
  70. }
  71. if got := qp["maxIdleTimeout"]; got != int64(30) {
  72. t.Errorf("maxIdleTimeout: expected 30, got %v (%T)", got, got)
  73. }
  74. if got := qp["initStreamReceiveWindow"]; got != int64(524288) {
  75. t.Errorf("initStreamReceiveWindow: expected 524288, got %v (%T)", got, got)
  76. }
  77. if _, exists := qp["maxIncomingStreams"]; exists {
  78. t.Errorf("maxIncomingStreams should be dropped, got %v", qp["maxIncomingStreams"])
  79. }
  80. if got := qp["brutalUp"]; got != "100 mbps" {
  81. t.Errorf("brutalUp should stay a string, got %v (%T)", got, got)
  82. }
  83. }
  84. // A panel older than xray-core 26.9.30 shares its xdns mask in the string lists the
  85. // core no longer parses; imported verbatim, the outbound would fail the whole config.
  86. func TestParseLink_UpgradesLegacyXdnsFinalMask(t *testing.T) {
  87. fm := url.QueryEscape(`{"udp":[{"type":"xdns","settings":{"resolvers":["t.example.com+udp://8.8.8.8:53"]}}]}`)
  88. res, err := ParseLink("vless://[email protected]:53?type=kcp&security=none&fm=" + fm + "#dns")
  89. if err != nil {
  90. t.Fatalf("parse vless with fm: %v", err)
  91. }
  92. stream, _ := res.Outbound["streamSettings"].(map[string]any)
  93. got, err := json.Marshal(stream["finalmask"])
  94. if err != nil {
  95. t.Fatalf("marshal finalmask: %v", err)
  96. }
  97. want := `{"udp":[{"settings":{"domains":[{"edns0":1232,"name":"t.example.com","types":[16]}],"resolvers":[{"settings":{"addr":"8.8.8.8:53"},"type":"udp"}]},"type":"xdns"}]}`
  98. if string(got) != want {
  99. t.Fatalf("imported finalmask\n got: %s\nwant: %s", got, want)
  100. }
  101. }
  102. func TestSanitizeFinalMaskQuicParams_ClampsAndRejects(t *testing.T) {
  103. cases := []struct {
  104. name string
  105. key string
  106. in any
  107. want any
  108. }{
  109. {"infinite string dropped", "keepAlivePeriod", "inf", nil},
  110. {"nan string dropped", "keepAlivePeriod", "NaN", nil},
  111. {"negative dropped", "maxStreamReceiveWindow", float64(-5), nil},
  112. {"negative duration dropped", "keepAlivePeriod", "-10s", nil},
  113. {"absurd magnitude dropped", "initConnectionReceiveWindow", float64(1e30), nil},
  114. {"keepAlive clamped up", "keepAlivePeriod", "1s", int64(2)},
  115. {"keepAlive clamped down", "keepAlivePeriod", "90s", int64(60)},
  116. {"idle clamped up", "maxIdleTimeout", float64(1), int64(4)},
  117. {"idle clamped down", "maxIdleTimeout", "10m", int64(120)},
  118. {"streams clamped up", "maxIncomingStreams", float64(4), int64(8)},
  119. {"zero means unset and survives", "maxIdleTimeout", float64(0), int64(0)},
  120. {"window passes through", "initStreamReceiveWindow", float64(524288), int64(524288)},
  121. }
  122. for _, c := range cases {
  123. t.Run(c.name, func(t *testing.T) {
  124. parsed := map[string]any{"quicParams": map[string]any{c.key: c.in}}
  125. sanitizeFinalMaskQuicParams(parsed)
  126. qp := parsed["quicParams"].(map[string]any)
  127. got, exists := qp[c.key]
  128. if c.want == nil {
  129. if exists {
  130. t.Fatalf("%s: expected key dropped, got %v (%T)", c.key, got, got)
  131. }
  132. return
  133. }
  134. if !exists || got != c.want {
  135. t.Fatalf("%s: expected %v, got %v (%T)", c.key, c.want, got, got)
  136. }
  137. })
  138. }
  139. }
  140. func salamanderPassword(t *testing.T, res *ParseResult) (string, bool) {
  141. t.Helper()
  142. stream, ok := res.Outbound["streamSettings"].(map[string]any)
  143. if !ok {
  144. t.Fatalf("missing streamSettings: %v", res.Outbound)
  145. }
  146. finalmask, ok := stream["finalmask"].(map[string]any)
  147. if !ok {
  148. return "", false
  149. }
  150. udp, ok := finalmask["udp"].([]any)
  151. if !ok {
  152. return "", false
  153. }
  154. for _, m := range udp {
  155. mask, _ := m.(map[string]any)
  156. if mask == nil || mask["type"] != "salamander" {
  157. continue
  158. }
  159. settings, _ := mask["settings"].(map[string]any)
  160. pw, _ := settings["password"].(string)
  161. return pw, true
  162. }
  163. return "", false
  164. }
  165. func finalmaskUDP(t *testing.T, res *ParseResult) []any {
  166. t.Helper()
  167. stream, _ := res.Outbound["streamSettings"].(map[string]any)
  168. finalmask, _ := stream["finalmask"].(map[string]any)
  169. udp, _ := finalmask["udp"].([]any)
  170. return udp
  171. }
  172. func hopMask(t *testing.T, res *ParseResult) (map[string]any, bool) {
  173. t.Helper()
  174. for _, rawMask := range finalmaskUDP(t, res) {
  175. mask, _ := rawMask.(map[string]any)
  176. if maskType, _ := mask["type"].(string); maskType == "udphop" {
  177. settings, _ := mask["settings"].(map[string]any)
  178. return settings, true
  179. }
  180. }
  181. return nil, false
  182. }
  183. func hopPorts(t *testing.T, res *ParseResult) (string, bool) {
  184. t.Helper()
  185. settings, ok := hopMask(t, res)
  186. if !ok {
  187. return "", false
  188. }
  189. ports, _ := settings["remotePorts"].(string)
  190. return ports, true
  191. }
  192. func TestParseHysteria2_Obfs(t *testing.T) {
  193. cases := []struct {
  194. name string
  195. query string
  196. wantPw string
  197. wantSet bool
  198. }{
  199. {"standard", "obfs=salamander&obfs-password=s3cr3t", "s3cr3t", true},
  200. {"snake-case alias", "obfs=salamander&obfs_password=aliaspw", "aliaspw", true},
  201. {"camel-case alias", "obfs=salamander&obfsPassword=camelpw", "camelpw", true},
  202. {"case-insensitive type", "obfs=Salamander&obfs-password=mixed", "mixed", true},
  203. {"no obfs", "sni=ex.com", "", false},
  204. {"obfs without password", "obfs=salamander", "", false},
  205. {"unknown obfs type", "obfs=random&obfs-password=x", "", false},
  206. }
  207. for _, c := range cases {
  208. t.Run(c.name, func(t *testing.T) {
  209. res, err := ParseLink("hysteria2://[email protected]:443?security=tls&" + c.query + "#node")
  210. if err != nil {
  211. t.Fatalf("parse hysteria2: %v", err)
  212. }
  213. if res.Outbound["protocol"] != "hysteria" {
  214. t.Fatalf("bad protocol: %v", res.Outbound["protocol"])
  215. }
  216. pw, ok := salamanderPassword(t, res)
  217. if ok != c.wantSet {
  218. t.Fatalf("salamander mask present = %v, want %v (stream: %v)", ok, c.wantSet, res.Outbound["streamSettings"])
  219. }
  220. if pw != c.wantPw {
  221. t.Errorf("salamander password: got %q, want %q", pw, c.wantPw)
  222. }
  223. })
  224. }
  225. }
  226. func TestParseHysteria2_ObfsFinalMaskPrecedence(t *testing.T) {
  227. cases := []struct {
  228. name string
  229. fm string
  230. obfsPw string
  231. wantPw string
  232. wantUDPLen int
  233. }{
  234. {
  235. name: "fm password wins over obfs",
  236. fm: `{"udp":[{"type":"salamander","settings":{"password":"fromfm"}}]}`,
  237. obfsPw: "fromobfs",
  238. wantPw: "fromfm",
  239. wantUDPLen: 1,
  240. },
  241. {
  242. name: "obfs fills password-less fm mask",
  243. fm: `{"udp":[{"type":"salamander","settings":{}}]}`,
  244. obfsPw: "fromobfs",
  245. wantPw: "fromobfs",
  246. wantUDPLen: 1,
  247. },
  248. {
  249. name: "obfs appends alongside a non-salamander mask",
  250. fm: `{"udp":[{"type":"mkcp-legacy","settings":{"header":"srtp"}}]}`,
  251. obfsPw: "fromobfs",
  252. wantPw: "fromobfs",
  253. wantUDPLen: 2,
  254. },
  255. }
  256. for _, c := range cases {
  257. t.Run(c.name, func(t *testing.T) {
  258. link := "hysteria2://[email protected]:443?security=tls&fm=" + url.QueryEscape(c.fm) +
  259. "&obfs=salamander&obfs-password=" + c.obfsPw + "#node"
  260. res, err := ParseLink(link)
  261. if err != nil {
  262. t.Fatalf("parse hysteria2: %v", err)
  263. }
  264. pw, ok := salamanderPassword(t, res)
  265. if !ok {
  266. t.Fatalf("salamander mask missing: %v", res.Outbound["streamSettings"])
  267. }
  268. if pw != c.wantPw {
  269. t.Errorf("salamander password: got %q, want %q", pw, c.wantPw)
  270. }
  271. if udp := finalmaskUDP(t, res); len(udp) != c.wantUDPLen {
  272. t.Errorf("udp mask count: got %d, want %d (%v)", len(udp), c.wantUDPLen, udp)
  273. }
  274. })
  275. }
  276. }
  277. func TestParseHysteria2_Mport(t *testing.T) {
  278. cases := []struct {
  279. name string
  280. query string
  281. wantPorts string
  282. wantHop bool
  283. }{
  284. {"standard mport", "mport=20000-50000", "20000-50000", true},
  285. {"no mport", "sni=ex.com", "", false},
  286. {
  287. name: "fm udphop mask wins over mport",
  288. query: "mport=1-2&fm=" + url.QueryEscape(`{"udp":[{"type":"udphop","settings":{"mode":"intervalremote","interval":"7-9","remotePorts":"30000-40000"}}]}`),
  289. wantPorts: "30000-40000",
  290. wantHop: true,
  291. },
  292. {
  293. name: "legacy fm quicParams.udpHop no longer suppresses mport",
  294. query: "mport=1-2&fm=" + url.QueryEscape(`{"quicParams":{"udpHop":{"ports":"30000-40000","interval":"7-9"}}}`),
  295. wantPorts: "1-2",
  296. wantHop: true,
  297. },
  298. }
  299. for _, c := range cases {
  300. t.Run(c.name, func(t *testing.T) {
  301. res, err := ParseLink("hysteria2://[email protected]:443?security=tls&" + c.query + "#node")
  302. if err != nil {
  303. t.Fatalf("parse hysteria2: %v", err)
  304. }
  305. ports, ok := hopPorts(t, res)
  306. if ok != c.wantHop {
  307. t.Fatalf("udpHop present = %v, want %v (stream: %v)", ok, c.wantHop, res.Outbound["streamSettings"])
  308. }
  309. if ports != c.wantPorts {
  310. t.Errorf("hop ports: got %q, want %q", ports, c.wantPorts)
  311. }
  312. })
  313. }
  314. }
  315. // xray-core 26.9.9 rejects a udphop mask whose mode is empty or unknown, so
  316. // the mport importer must emit a mode the core's UDPHop.Build() accepts.
  317. func TestParseHysteria2_MportEmitsCoreAcceptedMask(t *testing.T) {
  318. res, err := ParseLink("hysteria2://[email protected]:443?security=tls&mport=20000-50000#node")
  319. if err != nil {
  320. t.Fatalf("parse hysteria2: %v", err)
  321. }
  322. settings, ok := hopMask(t, res)
  323. if !ok {
  324. t.Fatalf("no udphop mask (stream: %v)", res.Outbound["streamSettings"])
  325. }
  326. if got, _ := settings["mode"].(string); got != "intervalremote" {
  327. t.Errorf("mode = %q, want %q", got, "intervalremote")
  328. }
  329. if got, _ := settings["interval"].(string); got != "5-10" {
  330. t.Errorf("interval = %q, want %q", got, "5-10")
  331. }
  332. stream, _ := res.Outbound["streamSettings"].(map[string]any)
  333. finalmask, _ := stream["finalmask"].(map[string]any)
  334. if quicParams, ok := finalmask["quicParams"].(map[string]any); ok {
  335. if _, dead := quicParams["udpHop"]; dead {
  336. t.Error("importer still writes the quicParams.udpHop key the core ignores")
  337. }
  338. }
  339. }
  340. func TestParseShadowsocks(t *testing.T) {
  341. modernUser := base64.StdEncoding.EncodeToString([]byte("aes-256-gcm:secretpass"))
  342. legacyBody := base64.StdEncoding.EncodeToString([]byte("aes-256-gcm:[email protected]:8388"))
  343. cases := []struct {
  344. name string
  345. link string
  346. host string
  347. port int
  348. method string
  349. pass string
  350. }{
  351. {
  352. name: "modern",
  353. link: "ss://" + modernUser + "@1.2.3.4:8388#node",
  354. host: "1.2.3.4",
  355. port: 8388,
  356. method: "aes-256-gcm",
  357. pass: "secretpass",
  358. },
  359. {
  360. name: "modern with plugin query",
  361. link: "ss://" + modernUser + "@1.2.3.4:8388?plugin=v2ray-plugin#node",
  362. host: "1.2.3.4",
  363. port: 8388,
  364. method: "aes-256-gcm",
  365. pass: "secretpass",
  366. },
  367. {
  368. name: "modern sip002 slash query",
  369. link: "ss://" + modernUser + "@1.2.3.4:8388/?plugin=obfs-local%3Bobfs%3Dhttp#node",
  370. host: "1.2.3.4",
  371. port: 8388,
  372. method: "aes-256-gcm",
  373. pass: "secretpass",
  374. },
  375. {
  376. name: "legacy",
  377. link: "ss://" + legacyBody + "#node",
  378. host: "1.2.3.4",
  379. port: 8388,
  380. method: "aes-256-gcm",
  381. pass: "secretpass",
  382. },
  383. {
  384. name: "base64url userinfo with plugin and trailing slash",
  385. link: "ss://" + base64.RawURLEncoding.EncodeToString([]byte("aes-128-gcm:pa+ss/word")) + "@1.2.3.4:8388/?plugin=obfs-local%3Bobfs%3Dhttp#node",
  386. host: "1.2.3.4",
  387. port: 8388,
  388. method: "aes-128-gcm",
  389. pass: "pa+ss/word",
  390. },
  391. {
  392. name: "sip022 percent-encoded userinfo",
  393. link: "ss://2022-blake3-aes-256-gcm:YctPZ6U7xPPcU%2Bgp3u%2B0tx%2FtRizJN9K8y%2BuKlW2qjlI%[email protected]:8888#Example3",
  394. host: "example.com",
  395. port: 8888,
  396. method: "2022-blake3-aes-256-gcm",
  397. pass: "YctPZ6U7xPPcU+gp3u+0tx/tRizJN9K8y+uKlW2qjlI=",
  398. },
  399. {
  400. name: "sip022 dual-key password with type query preserves inner colon",
  401. link: "ss://2022-blake3-aes-256-gcm:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%3D:BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB%[email protected]:9999?type=tcp#node",
  402. host: "1.2.3.4",
  403. port: 9999,
  404. method: "2022-blake3-aes-256-gcm",
  405. pass: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=:BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=",
  406. },
  407. }
  408. for _, c := range cases {
  409. t.Run(c.name, func(t *testing.T) {
  410. res, err := ParseLink(c.link)
  411. if err != nil {
  412. t.Fatalf("parse ss: %v", err)
  413. }
  414. if res.Outbound["protocol"] != "shadowsocks" {
  415. t.Fatalf("protocol = %v, want shadowsocks", res.Outbound["protocol"])
  416. }
  417. srv := res.Outbound["settings"].(map[string]any)["servers"].([]any)[0].(map[string]any)
  418. if srv["address"] != c.host {
  419. t.Errorf("address = %v, want %v", srv["address"], c.host)
  420. }
  421. if srv["port"] != c.port {
  422. t.Errorf("port = %v, want %v", srv["port"], c.port)
  423. }
  424. if srv["method"] != c.method {
  425. t.Errorf("method = %v, want %v", srv["method"], c.method)
  426. }
  427. if srv["password"] != c.pass {
  428. t.Errorf("password = %v, want %v", srv["password"], c.pass)
  429. }
  430. })
  431. }
  432. }
  433. func TestParseShadowsocksTLSQueryRoundTrip(t *testing.T) {
  434. user := base64.RawURLEncoding.EncodeToString([]byte("chacha20-ietf-poly1305:secretpass"))
  435. link := "ss://" + user + "@example.com:443?alpn=h2%2Chttp%2F1.1&fp=firefox&security=tls&sni=example.com&type=tcp#user"
  436. res, err := ParseLink(link)
  437. if err != nil {
  438. t.Fatalf("parse ss tls: %v", err)
  439. }
  440. srv := res.Outbound["settings"].(map[string]any)["servers"].([]any)[0].(map[string]any)
  441. if srv["address"] != "example.com" || srv["port"] != 443 {
  442. t.Fatalf("server = %v", srv)
  443. }
  444. if srv["method"] != "chacha20-ietf-poly1305" || srv["password"] != "secretpass" {
  445. t.Fatalf("creds = %v", srv)
  446. }
  447. stream, ok := res.Outbound["streamSettings"].(map[string]any)
  448. if !ok {
  449. t.Fatalf("missing streamSettings: %v", res.Outbound)
  450. }
  451. if stream["network"] != "tcp" {
  452. t.Errorf("network = %v, want tcp", stream["network"])
  453. }
  454. if stream["security"] != "tls" {
  455. t.Errorf("security = %v, want tls", stream["security"])
  456. }
  457. tls, ok := stream["tlsSettings"].(map[string]any)
  458. if !ok {
  459. t.Fatalf("missing tlsSettings: %v", stream)
  460. }
  461. if tls["serverName"] != "example.com" {
  462. t.Errorf("sni = %v, want example.com", tls["serverName"])
  463. }
  464. if tls["fingerprint"] != "firefox" {
  465. t.Errorf("fp = %v, want firefox", tls["fingerprint"])
  466. }
  467. alpn, _ := tls["alpn"].([]string)
  468. if len(alpn) != 2 || alpn[0] != "h2" || alpn[1] != "http/1.1" {
  469. t.Errorf("alpn = %v, want [h2 http/1.1]", alpn)
  470. }
  471. }
  472. func TestParseShadowsocksBadPort(t *testing.T) {
  473. user := base64.StdEncoding.EncodeToString([]byte("aes-256-gcm:secretpass"))
  474. cases := map[string]string{
  475. "modern": "ss://" + user + "@1.2.3.4:notaport#node",
  476. "legacy": "ss://" + base64.StdEncoding.EncodeToString([]byte("aes-256-gcm:[email protected]:notaport")) + "#node",
  477. }
  478. for name, link := range cases {
  479. t.Run(name, func(t *testing.T) {
  480. if _, err := ParseLink(link); err == nil {
  481. t.Errorf("expected parse error for non-numeric port, got nil")
  482. }
  483. })
  484. }
  485. }
  486. func TestParseSubscriptionBody_Base64(t *testing.T) {
  487. // base64 of the two joined links:
  488. // vless://u@h:443?type=tcp#A\nvless://u2@h2:443?type=tcp#B
  489. b64 := "dmxlc3M6Ly91QGg6NDQzP3R5cGU9dGNwI0EKdmxlc3M6Ly91MkBoMjo0NDM/dHlwZT10Y3AjQg=="
  490. obs, ids, err := ParseSubscriptionBody([]byte(b64))
  491. if err != nil {
  492. t.Fatalf("parse sub body: %v", err)
  493. }
  494. if len(obs) != 2 {
  495. t.Fatalf("expected 2 outbounds, got %d", len(obs))
  496. }
  497. if !strings.HasPrefix(ids[0], "vless:") || !strings.HasPrefix(ids[1], "vless:") {
  498. t.Errorf("bad identities: %v", ids)
  499. }
  500. }
  501. func TestSlugAndSuggest(t *testing.T) {
  502. if SlugRemark("Hello World!") != "hello-world" {
  503. t.Errorf("slug failed")
  504. }
  505. tag := SuggestTag("hk-", " SG 01 !! ", 0)
  506. if tag != "hk-sg-01" {
  507. t.Errorf("suggest tag got %q", tag)
  508. }
  509. // Non-ASCII letters/digits are preserved rather than stripped.
  510. if got := SlugRemark("Москва 🇷🇺 01"); got != "москва-01" {
  511. t.Errorf("unicode slug got %q", got)
  512. }
  513. if got := SuggestTag("ru-", "Сервер 2", 0); got != "ru-сервер-2" {
  514. t.Errorf("unicode suggest tag got %q", got)
  515. }
  516. }
  517. // The obfs-local plugin the panel exports carries the only description of
  518. // shadowsocks tcp/http obfuscation, so it has to become that header.
  519. func TestParseShadowsocksObfsLocalPlugin(t *testing.T) {
  520. user := base64.RawURLEncoding.EncodeToString([]byte("aes-256-gcm:secretpass"))
  521. const httpObfs = "obfs-local;obfs=http;obfs-host=obfs.example.com"
  522. for _, tc := range []struct {
  523. name, query, wantHeader, wantHost string
  524. }{
  525. {"http obfs becomes the tcp header", "plugin=" + url.QueryEscape(httpObfs), "http", "obfs.example.com"},
  526. {"unencoded separators map the same way", "plugin=" + httpObfs, "http", "obfs.example.com"},
  527. {"tls obfs has no xray header", "plugin=" + url.QueryEscape("obfs-local;obfs=tls"), "none", ""},
  528. {"an unrelated plugin is left alone", "plugin=v2ray-plugin", "none", ""},
  529. } {
  530. t.Run(tc.name, func(t *testing.T) {
  531. res, err := ParseLink("ss://" + user + "@1.2.3.4:8388/?" + tc.query + "#node")
  532. if err != nil {
  533. t.Fatalf("parse ss: %v", err)
  534. }
  535. raw, err := json.Marshal(res.Outbound["streamSettings"])
  536. if err != nil {
  537. t.Fatalf("marshal stream: %v", err)
  538. }
  539. var stream map[string]any
  540. _ = json.Unmarshal(raw, &stream)
  541. tcp, _ := stream["tcpSettings"].(map[string]any)
  542. header, _ := tcp["header"].(map[string]any)
  543. if header == nil || header["type"] != tc.wantHeader {
  544. t.Fatalf("header = %v, want type %q", header, tc.wantHeader)
  545. }
  546. request, _ := header["request"].(map[string]any)
  547. headers, _ := request["headers"].(map[string]any)
  548. hosts, _ := headers["Host"].([]any)
  549. got := ""
  550. if len(hosts) > 0 {
  551. got, _ = hosts[0].(string)
  552. }
  553. if got != tc.wantHost {
  554. t.Errorf("host = %q, want %q", got, tc.wantHost)
  555. }
  556. })
  557. }
  558. }