warp.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. 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 _, ok := response["id"].(string); !ok {
  134. return "", common.NewErrorf("warp set license failed: unexpected response: %s", string(body))
  135. }
  136. warpData["license_key"] = license
  137. newWarpData, err := json.MarshalIndent(warpData, "", " ")
  138. if err != nil {
  139. return "", err
  140. }
  141. if err := s.SettingService.SetWarp(string(newWarpData)); err != nil {
  142. return "", err
  143. }
  144. return string(newWarpData), nil
  145. }
  146. // loadWarpCreds reads the stored warp JSON and ensures access_token + device_id are set.
  147. func (s *WarpService) loadWarpCreds() (map[string]string, error) {
  148. warp, err := s.SettingService.GetWarp()
  149. if err != nil {
  150. return nil, err
  151. }
  152. var data map[string]string
  153. if err := json.Unmarshal([]byte(warp), &data); err != nil {
  154. return nil, err
  155. }
  156. if data["access_token"] == "" || data["device_id"] == "" {
  157. return nil, common.NewError("warp not registered: missing access_token or device_id")
  158. }
  159. return data, nil
  160. }
  161. // doWarpRequest sends the request and returns the response body on 2xx.
  162. // Non-2xx responses are returned as errors including the status code and body.
  163. func doWarpRequest(req *http.Request) ([]byte, error) {
  164. resp, err := warpHTTPClient.Do(req)
  165. if err != nil {
  166. return nil, err
  167. }
  168. defer resp.Body.Close()
  169. body, err := io.ReadAll(resp.Body)
  170. if err != nil {
  171. return nil, err
  172. }
  173. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  174. if msg := parseWarpError(body); msg != "" {
  175. return nil, common.NewError(msg)
  176. }
  177. return nil, common.NewErrorf("warp api %s %s returned status %d: %s",
  178. req.Method, req.URL.Path, resp.StatusCode, string(body))
  179. }
  180. return body, nil
  181. }
  182. func parseWarpError(body []byte) string {
  183. var env struct {
  184. Errors []struct {
  185. Message string `json:"message"`
  186. } `json:"errors"`
  187. }
  188. if err := json.Unmarshal(body, &env); err != nil {
  189. return ""
  190. }
  191. if len(env.Errors) == 0 || env.Errors[0].Message == "" {
  192. return ""
  193. }
  194. return env.Errors[0].Message
  195. }