1
0

warp.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. func (s *WarpService) GetWarpData() (string, error) {
  22. return s.SettingService.GetWarp()
  23. }
  24. func (s *WarpService) DelWarpData() error {
  25. return s.SettingService.SetWarp("")
  26. }
  27. func (s *WarpService) GetWarpConfig() (string, error) {
  28. warpData, err := s.loadWarpCreds()
  29. if err != nil {
  30. return "", err
  31. }
  32. url := fmt.Sprintf("%s/reg/%s", warpAPIBase, warpData["device_id"])
  33. req, err := http.NewRequest(http.MethodGet, url, nil)
  34. if err != nil {
  35. return "", err
  36. }
  37. req.Header.Set("Authorization", "Bearer "+warpData["access_token"])
  38. body, err := s.doWarpRequest(req)
  39. if err != nil {
  40. return "", err
  41. }
  42. return string(body), nil
  43. }
  44. func (s *WarpService) RegWarp(secretKey string, publicKey string) (string, error) {
  45. hostName, _ := os.Hostname()
  46. reqBody, err := json.Marshal(map[string]any{
  47. "key": publicKey,
  48. "tos": time.Now().UTC().Format("2006-01-02T15:04:05.000Z"),
  49. "type": "PC",
  50. "model": "x-ui",
  51. "name": hostName,
  52. })
  53. if err != nil {
  54. return "", err
  55. }
  56. req, err := http.NewRequest(http.MethodPost, warpAPIBase+"/reg", bytes.NewReader(reqBody))
  57. if err != nil {
  58. return "", err
  59. }
  60. req.Header.Set("CF-Client-Version", warpClientVer)
  61. req.Header.Set("Content-Type", "application/json")
  62. body, err := s.doWarpRequest(req)
  63. if err != nil {
  64. return "", err
  65. }
  66. var rsp map[string]any
  67. if err := json.Unmarshal(body, &rsp); err != nil {
  68. return "", err
  69. }
  70. deviceID, ok := rsp["id"].(string)
  71. if !ok {
  72. return "", common.NewError("warp register: missing 'id' in response")
  73. }
  74. token, ok := rsp["token"].(string)
  75. if !ok {
  76. return "", common.NewError("warp register: missing 'token' in response")
  77. }
  78. account, ok := rsp["account"].(map[string]any)
  79. if !ok {
  80. return "", common.NewError("warp register: missing 'account' in response")
  81. }
  82. license, ok := account["license"].(string)
  83. if !ok {
  84. return "", common.NewError("warp register: missing 'account.license' in response")
  85. }
  86. warpData := map[string]string{
  87. "access_token": token,
  88. "device_id": deviceID,
  89. "license_key": license,
  90. "private_key": secretKey,
  91. }
  92. if config, ok := rsp["config"].(map[string]any); ok {
  93. if clientID, ok := config["client_id"].(string); ok {
  94. warpData["client_id"] = clientID
  95. }
  96. }
  97. warpJSON, err := json.MarshalIndent(warpData, "", " ")
  98. if err != nil {
  99. return "", err
  100. }
  101. if err := s.SettingService.SetWarp(string(warpJSON)); err != nil {
  102. return "", err
  103. }
  104. result, err := json.MarshalIndent(map[string]any{
  105. "data": warpData,
  106. "config": json.RawMessage(body),
  107. }, "", " ")
  108. if err != nil {
  109. return "", err
  110. }
  111. return string(result), nil
  112. }
  113. func (s *WarpService) SetWarpLicense(license string) (string, error) {
  114. warpData, err := s.loadWarpCreds()
  115. if err != nil {
  116. return "", err
  117. }
  118. url := fmt.Sprintf("%s/reg/%s/account", warpAPIBase, warpData["device_id"])
  119. reqBody, err := json.Marshal(map[string]string{"license": license})
  120. if err != nil {
  121. return "", err
  122. }
  123. req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(reqBody))
  124. if err != nil {
  125. return "", err
  126. }
  127. req.Header.Set("Authorization", "Bearer "+warpData["access_token"])
  128. req.Header.Set("Content-Type", "application/json")
  129. body, err := s.doWarpRequest(req)
  130. if err != nil {
  131. return "", err
  132. }
  133. var response map[string]any
  134. if err := json.Unmarshal(body, &response); err != nil {
  135. return "", err
  136. }
  137. if _, ok := response["id"].(string); !ok {
  138. return "", common.NewErrorf("warp set license failed: unexpected response: %s", string(body))
  139. }
  140. warpData["license_key"] = license
  141. newWarpData, err := json.MarshalIndent(warpData, "", " ")
  142. if err != nil {
  143. return "", err
  144. }
  145. if err := s.SettingService.SetWarp(string(newWarpData)); err != nil {
  146. return "", err
  147. }
  148. return string(newWarpData), nil
  149. }
  150. // loadWarpCreds reads the stored warp JSON and ensures access_token + device_id are set.
  151. func (s *WarpService) loadWarpCreds() (map[string]string, error) {
  152. warp, err := s.SettingService.GetWarp()
  153. if err != nil {
  154. return nil, err
  155. }
  156. var data map[string]string
  157. if err := json.Unmarshal([]byte(warp), &data); err != nil {
  158. return nil, err
  159. }
  160. if data["access_token"] == "" || data["device_id"] == "" {
  161. return nil, common.NewError("warp not registered: missing access_token or device_id")
  162. }
  163. return data, nil
  164. }
  165. // doWarpRequest sends the request and returns the response body on 2xx.
  166. // Non-2xx responses are returned as errors including the status code and body.
  167. func (s *WarpService) doWarpRequest(req *http.Request) ([]byte, error) {
  168. client := s.NewProxiedHTTPClient(15 * time.Second)
  169. resp, err := client.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. }