build_urls_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package sub
  2. import (
  3. "path/filepath"
  4. "strings"
  5. "testing"
  6. "github.com/mhsanaei/3x-ui/v3/database"
  7. )
  8. func initSubDB(t *testing.T) {
  9. t.Helper()
  10. if err := database.InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
  11. t.Fatalf("InitDB: %v", err)
  12. }
  13. // Close the handle before t.TempDir cleanup so Windows doesn't refuse to
  14. // remove the still-open sqlite file.
  15. t.Cleanup(func() { _ = database.CloseDB() })
  16. }
  17. // The subscription page's Copy URL must be built from the same host the
  18. // subscriber reached the page on (after PrepareForRequest normalizes away a
  19. // loopback/bind address) — never the raw listen IP. A subscriber that hit a
  20. // loopback bind should see "localhost", not "127.0.0.1".
  21. func TestBuildURLs_NormalizesListenIP(t *testing.T) {
  22. initSubDB(t)
  23. s := &SubService{}
  24. s.PrepareForRequest("127.0.0.1")
  25. subURL, _, _ := s.BuildURLs("/sub/", "/json/", "/clash/", "ABC")
  26. if strings.Contains(subURL, "127.0.0.1") {
  27. t.Fatalf("listen IP leaked into Copy URL: %q", subURL)
  28. }
  29. if !strings.Contains(subURL, "localhost") {
  30. t.Fatalf("Copy URL = %q, want a localhost host", subURL)
  31. }
  32. if !strings.HasSuffix(subURL, "/sub/ABC") {
  33. t.Fatalf("Copy URL = %q, want it to end with /sub/ABC", subURL)
  34. }
  35. }
  36. // A subscriber arriving on a real domain gets that exact domain in the Copy
  37. // URL, with the configured sub port — matching the Client Information page.
  38. func TestBuildURLs_UsesSubscriberDomain(t *testing.T) {
  39. initSubDB(t)
  40. s := &SubService{}
  41. s.PrepareForRequest("sub.example.com")
  42. subURL, jsonURL, clashURL := s.BuildURLs("/sub/", "/json/", "/clash/", "ABC")
  43. if subURL != "http://sub.example.com:2096/sub/ABC" {
  44. t.Fatalf("subURL = %q", subURL)
  45. }
  46. if jsonURL != "http://sub.example.com:2096/json/ABC" {
  47. t.Fatalf("jsonURL = %q", jsonURL)
  48. }
  49. if clashURL != "http://sub.example.com:2096/clash/ABC" {
  50. t.Fatalf("clashURL = %q", clashURL)
  51. }
  52. }
  53. func TestBuildURLs_EmptySubId(t *testing.T) {
  54. initSubDB(t)
  55. s := &SubService{}
  56. s.PrepareForRequest("sub.example.com")
  57. a, b, c := s.BuildURLs("/sub/", "/json/", "/clash/", "")
  58. if a != "" || b != "" || c != "" {
  59. t.Fatalf("empty subId must yield empty URLs, got %q %q %q", a, b, c)
  60. }
  61. }