1
0

warp.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. package service
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "os"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v2/util/common"
  11. )
  12. // WarpService provides business logic for Cloudflare WARP integration.
  13. // It manages WARP configuration and connectivity settings.
  14. type WarpService struct {
  15. SettingService
  16. }
  17. const (
  18. warpAPIBase = "https://api.cloudflareclient.com/v0a4005"
  19. warpClientVer = "a-6.30-3596"
  20. )
  21. var warpHTTPClient = &http.Client{Timeout: 15 * time.Second}
  22. func (s *WarpService) GetWarpData() (string, error) {
  23. return s.SettingService.GetWarp()
  24. }
  25. func (s *WarpService) DelWarpData() error {
  26. return s.SettingService.SetWarp("")
  27. }
  28. func (s *WarpService) GetWarpConfig() (string, error) {
  29. warpData, err := s.loadWarpCreds()
  30. if err != nil {
  31. return "", err
  32. }
  33. url := fmt.Sprintf("%s/reg/%s", warpAPIBase, warpData["device_id"])
  34. req, err := http.NewRequest(http.MethodGet, url, nil)
  35. if err != nil {
  36. return "", err
  37. }
  38. req.Header.Set("Authorization", "Bearer "+warpData["access_token"])
  39. body, err := doWarpRequest(req)
  40. if err != nil {
  41. return "", err
  42. }
  43. return string(body), nil
  44. }
  45. func (s *WarpService) RegWarp(secretKey string, publicKey string) (string, error) {
  46. hostName, _ := os.Hostname()
  47. reqBody, err := json.Marshal(map[string]any{
  48. "key": publicKey,
  49. "tos": time.Now().UTC().Format("2006-01-02T15:04:05.000Z"),
  50. "type": "PC",
  51. "model": "x-ui",
  52. "name": hostName,
  53. })
  54. if err != nil {
  55. return "", err
  56. }
  57. req, err := http.NewRequest(http.MethodPost, warpAPIBase+"/reg", bytes.NewReader(reqBody))
  58. if err != nil {
  59. return "", err
  60. }
  61. req.Header.Set("CF-Client-Version", warpClientVer)
  62. req.Header.Set("Content-Type", "application/json")
  63. body, err := doWarpRequest(req)
  64. if err != nil {
  65. return "", err
  66. }
  67. var rsp map[string]any
  68. if err := json.Unmarshal(body, &rsp); err != nil {
  69. return "", err
  70. }
  71. deviceID, ok := rsp["id"].(string)
  72. if !ok {
  73. return "", common.NewError("warp register: missing 'id' in response")
  74. }
  75. token, ok := rsp["token"].(string)
  76. if !ok {
  77. return "", common.NewError("warp register: missing 'token' in response")
  78. }
  79. account, ok := rsp["account"].(map[string]any)
  80. if !ok {
  81. return "", common.NewError("warp register: missing 'account' in response")
  82. }
  83. license, ok := account["license"].(string)
  84. if !ok {
  85. return "", common.NewError("warp register: missing 'account.license' in response")
  86. }
  87. warpData := map[string]string{
  88. "access_token": token,
  89. "device_id": deviceID,
  90. "license_key": license,
  91. "private_key": secretKey,
  92. }
  93. warpJSON, err := json.MarshalIndent(warpData, "", " ")
  94. if err != nil {
  95. return "", err
  96. }
  97. if err := s.SettingService.SetWarp(string(warpJSON)); err != nil {
  98. return "", err
  99. }
  100. result, err := json.MarshalIndent(map[string]any{
  101. "data": warpData,
  102. "config": json.RawMessage(body),
  103. }, "", " ")
  104. if err != nil {
  105. return "", err
  106. }
  107. return string(result), nil
  108. }
  109. func (s *WarpService) SetWarpLicense(license string) (string, error) {
  110. warpData, err := s.loadWarpCreds()
  111. if err != nil {
  112. return "", err
  113. }
  114. url := fmt.Sprintf("%s/reg/%s/account", warpAPIBase, warpData["device_id"])
  115. reqBody, err := json.Marshal(map[string]string{"license": license})
  116. if err != nil {
  117. return "", err
  118. }
  119. req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(reqBody))
  120. if err != nil {
  121. return "", err
  122. }
  123. req.Header.Set("Authorization", "Bearer "+warpData["access_token"])
  124. req.Header.Set("Content-Type", "application/json")
  125. body, err := doWarpRequest(req)
  126. if err != nil {
  127. return "", err
  128. }
  129. var response map[string]any
  130. if err := json.Unmarshal(body, &response); err != nil {
  131. return "", err
  132. }
  133. if success, _ := response["success"].(bool); !success {
  134. if errorArr, ok := response["errors"].([]any); ok && len(errorArr) > 0 {
  135. if errorObj, ok := errorArr[0].(map[string]any); ok {
  136. return "", common.NewError(errorObj["code"], errorObj["message"])
  137. }
  138. }
  139. return "", common.NewError("warp set license failed: unknown error")
  140. }
  141. warpData["license_key"] = license
  142. newWarpData, err := json.MarshalIndent(warpData, "", " ")
  143. if err != nil {
  144. return "", err
  145. }
  146. if err := s.SettingService.SetWarp(string(newWarpData)); err != nil {
  147. return "", err
  148. }
  149. return string(newWarpData), nil
  150. }
  151. // loadWarpCreds reads the stored warp JSON and ensures access_token + device_id are set.
  152. func (s *WarpService) loadWarpCreds() (map[string]string, error) {
  153. warp, err := s.SettingService.GetWarp()
  154. if err != nil {
  155. return nil, err
  156. }
  157. var data map[string]string
  158. if err := json.Unmarshal([]byte(warp), &data); err != nil {
  159. return nil, err
  160. }
  161. if data["access_token"] == "" || data["device_id"] == "" {
  162. return nil, common.NewError("warp not registered: missing access_token or device_id")
  163. }
  164. return data, nil
  165. }
  166. // doWarpRequest sends the request and returns the response body on 2xx.
  167. // Non-2xx responses are returned as errors including the status code and body.
  168. func doWarpRequest(req *http.Request) ([]byte, error) {
  169. resp, err := warpHTTPClient.Do(req)
  170. if err != nil {
  171. return nil, err
  172. }
  173. defer resp.Body.Close()
  174. body, err := io.ReadAll(resp.Body)
  175. if err != nil {
  176. return nil, err
  177. }
  178. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  179. return nil, common.NewErrorf("warp api %s %s returned status %d: %s",
  180. req.Method, req.URL.Path, resp.StatusCode, string(body))
  181. }
  182. return body, nil
  183. }