1
0

warp.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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/v3/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. if config, ok := rsp["config"].(map[string]any); ok {
  94. if clientID, ok := config["client_id"].(string); ok {
  95. warpData["client_id"] = clientID
  96. }
  97. }
  98. warpJSON, err := json.MarshalIndent(warpData, "", " ")
  99. if err != nil {
  100. return "", err
  101. }
  102. if err := s.SettingService.SetWarp(string(warpJSON)); err != nil {
  103. return "", err
  104. }
  105. result, err := json.MarshalIndent(map[string]any{
  106. "data": warpData,
  107. "config": json.RawMessage(body),
  108. }, "", " ")
  109. if err != nil {
  110. return "", err
  111. }
  112. return string(result), nil
  113. }
  114. func (s *WarpService) SetWarpLicense(license string) (string, error) {
  115. warpData, err := s.loadWarpCreds()
  116. if err != nil {
  117. return "", err
  118. }
  119. url := fmt.Sprintf("%s/reg/%s/account", warpAPIBase, warpData["device_id"])
  120. reqBody, err := json.Marshal(map[string]string{"license": license})
  121. if err != nil {
  122. return "", err
  123. }
  124. req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(reqBody))
  125. if err != nil {
  126. return "", err
  127. }
  128. req.Header.Set("Authorization", "Bearer "+warpData["access_token"])
  129. req.Header.Set("Content-Type", "application/json")
  130. body, err := doWarpRequest(req)
  131. if err != nil {
  132. return "", err
  133. }
  134. var response map[string]any
  135. if err := json.Unmarshal(body, &response); err != nil {
  136. return "", err
  137. }
  138. if _, ok := response["id"].(string); !ok {
  139. return "", common.NewErrorf("warp set license failed: unexpected response: %s", string(body))
  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. if msg := parseWarpError(body); msg != "" {
  180. return nil, common.NewError(msg)
  181. }
  182. return nil, common.NewErrorf("warp api %s %s returned status %d: %s",
  183. req.Method, req.URL.Path, resp.StatusCode, string(body))
  184. }
  185. return body, nil
  186. }
  187. func parseWarpError(body []byte) string {
  188. var env struct {
  189. Errors []struct {
  190. Message string `json:"message"`
  191. } `json:"errors"`
  192. }
  193. if err := json.Unmarshal(body, &env); err != nil {
  194. return ""
  195. }
  196. if len(env.Errors) == 0 || env.Errors[0].Message == "" {
  197. return ""
  198. }
  199. return env.Errors[0].Message
  200. }