warp.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package integration
  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/internal/logger"
  11. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  12. "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  13. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  14. )
  15. // WarpService provides business logic for Cloudflare WARP integration.
  16. // It manages WARP configuration and connectivity settings.
  17. type WarpService struct {
  18. service.SettingService
  19. }
  20. const (
  21. warpAPIBase = "https://api.cloudflareclient.com/v0a4005"
  22. warpClientVer = "a-6.30-3596"
  23. )
  24. func (s *WarpService) GetWarpData() (string, error) {
  25. return s.SettingService.GetWarp()
  26. }
  27. func (s *WarpService) DelWarpData() error {
  28. return s.SettingService.SetWarp("")
  29. }
  30. func (s *WarpService) GetWarpConfig() (string, error) {
  31. warpData, err := s.loadWarpCreds()
  32. if err != nil {
  33. return "", err
  34. }
  35. url := fmt.Sprintf("%s/reg/%s", warpAPIBase, warpData["device_id"])
  36. req, err := http.NewRequest(http.MethodGet, url, nil)
  37. if err != nil {
  38. return "", err
  39. }
  40. req.Header.Set("Authorization", "Bearer "+warpData["access_token"])
  41. body, err := s.doWarpRequest(req)
  42. if err != nil {
  43. return "", err
  44. }
  45. return string(body), nil
  46. }
  47. func (s *WarpService) RegWarp(secretKey string, publicKey string) (string, error) {
  48. hostName, _ := os.Hostname()
  49. reqBody, err := json.Marshal(map[string]any{
  50. "key": publicKey,
  51. "tos": time.Now().UTC().Format("2006-01-02T15:04:05.000Z"),
  52. "type": "PC",
  53. "model": "x-ui",
  54. "name": hostName,
  55. })
  56. if err != nil {
  57. return "", err
  58. }
  59. req, err := http.NewRequest(http.MethodPost, warpAPIBase+"/reg", bytes.NewReader(reqBody))
  60. if err != nil {
  61. return "", err
  62. }
  63. req.Header.Set("CF-Client-Version", warpClientVer)
  64. req.Header.Set("Content-Type", "application/json")
  65. body, err := s.doWarpRequest(req)
  66. if err != nil {
  67. return "", err
  68. }
  69. var rsp map[string]any
  70. if err := json.Unmarshal(body, &rsp); err != nil {
  71. return "", err
  72. }
  73. deviceID, ok := rsp["id"].(string)
  74. if !ok {
  75. return "", common.NewError("warp register: missing 'id' in response")
  76. }
  77. token, ok := rsp["token"].(string)
  78. if !ok {
  79. return "", common.NewError("warp register: missing 'token' in response")
  80. }
  81. account, ok := rsp["account"].(map[string]any)
  82. if !ok {
  83. return "", common.NewError("warp register: missing 'account' in response")
  84. }
  85. license, ok := account["license"].(string)
  86. if !ok {
  87. return "", common.NewError("warp register: missing 'account.license' in response")
  88. }
  89. warpData := map[string]string{
  90. "access_token": token,
  91. "device_id": deviceID,
  92. "license_key": license,
  93. "private_key": secretKey,
  94. }
  95. if config, ok := rsp["config"].(map[string]any); ok {
  96. if clientID, ok := config["client_id"].(string); ok {
  97. warpData["client_id"] = clientID
  98. }
  99. }
  100. warpJSON, err := json.MarshalIndent(warpData, "", " ")
  101. if err != nil {
  102. return "", err
  103. }
  104. if err := s.SettingService.SetWarp(string(warpJSON)); err != nil {
  105. return "", err
  106. }
  107. result, err := json.MarshalIndent(map[string]any{
  108. "data": warpData,
  109. "config": json.RawMessage(body),
  110. }, "", " ")
  111. if err != nil {
  112. return "", err
  113. }
  114. return string(result), nil
  115. }
  116. func (s *WarpService) SetWarpLicense(license string) (string, error) {
  117. warpData, err := s.loadWarpCreds()
  118. if err != nil {
  119. return "", err
  120. }
  121. url := fmt.Sprintf("%s/reg/%s/account", warpAPIBase, warpData["device_id"])
  122. reqBody, err := json.Marshal(map[string]string{"license": license})
  123. if err != nil {
  124. return "", err
  125. }
  126. req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(reqBody))
  127. if err != nil {
  128. return "", err
  129. }
  130. req.Header.Set("Authorization", "Bearer "+warpData["access_token"])
  131. req.Header.Set("Content-Type", "application/json")
  132. body, err := s.doWarpRequest(req)
  133. if err != nil {
  134. return "", err
  135. }
  136. var response map[string]any
  137. if err := json.Unmarshal(body, &response); err != nil {
  138. return "", err
  139. }
  140. if _, ok := response["id"].(string); !ok {
  141. return "", common.NewErrorf("warp set license failed: unexpected response: %s", string(body))
  142. }
  143. warpData["license_key"] = license
  144. newWarpData, err := json.MarshalIndent(warpData, "", " ")
  145. if err != nil {
  146. return "", err
  147. }
  148. if err := s.SettingService.SetWarp(string(newWarpData)); err != nil {
  149. return "", err
  150. }
  151. return string(newWarpData), nil
  152. }
  153. func (s *WarpService) ChangeWarpIP() (string, error) {
  154. warpDataMap, err := s.loadWarpCreds()
  155. if err != nil {
  156. return "", err
  157. }
  158. privKey, pubKey, err := wireguard.GenerateWireguardKeypair()
  159. if err != nil {
  160. return "", err
  161. }
  162. result, err := s.RegWarp(privKey, pubKey)
  163. if err != nil {
  164. return "", err
  165. }
  166. var parsed struct {
  167. Data map[string]string `json:"data"`
  168. Config map[string]interface{} `json:"config"`
  169. }
  170. if err := json.Unmarshal([]byte(result), &parsed); err != nil {
  171. return "", err
  172. }
  173. xraySvc := service.XraySettingService{}
  174. if err := xraySvc.UpdateWarpXraySetting(parsed.Data, parsed.Config); err != nil {
  175. return "", err
  176. }
  177. if license, ok := warpDataMap["license_key"]; ok && len(license) >= 26 {
  178. if _, licErr := s.SetWarpLicense(license); licErr != nil {
  179. logger.Warning("ChangeWarpIP: failed to re-apply WARP license: ", licErr)
  180. }
  181. }
  182. return result, nil
  183. }
  184. // loadWarpCreds reads the stored warp JSON and ensures access_token + device_id are set.
  185. func (s *WarpService) loadWarpCreds() (map[string]string, error) {
  186. warp, err := s.SettingService.GetWarp()
  187. if err != nil {
  188. return nil, err
  189. }
  190. var data map[string]string
  191. if err := json.Unmarshal([]byte(warp), &data); err != nil {
  192. return nil, err
  193. }
  194. if data["access_token"] == "" || data["device_id"] == "" {
  195. return nil, common.NewError("warp not registered: missing access_token or device_id")
  196. }
  197. return data, nil
  198. }
  199. // doWarpRequest sends the request and returns the response body on 2xx.
  200. // Non-2xx responses are returned as errors including the status code and body.
  201. func (s *WarpService) doWarpRequest(req *http.Request) ([]byte, error) {
  202. client := s.NewProxiedHTTPClient(15 * time.Second)
  203. resp, err := client.Do(req)
  204. if err != nil {
  205. return nil, err
  206. }
  207. defer resp.Body.Close()
  208. body, err := io.ReadAll(resp.Body)
  209. if err != nil {
  210. return nil, err
  211. }
  212. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  213. if msg := parseWarpError(body); msg != "" {
  214. return nil, common.NewError(msg)
  215. }
  216. return nil, common.NewErrorf("warp api %s %s returned status %d: %s",
  217. req.Method, req.URL.Path, resp.StatusCode, string(body))
  218. }
  219. return body, nil
  220. }
  221. func parseWarpError(body []byte) string {
  222. var env struct {
  223. Errors []struct {
  224. Message string `json:"message"`
  225. } `json:"errors"`
  226. }
  227. if err := json.Unmarshal(body, &env); err != nil {
  228. return ""
  229. }
  230. if len(env.Errors) == 0 || env.Errors[0].Message == "" {
  231. return ""
  232. }
  233. return env.Errors[0].Message
  234. }