warp.go 6.7 KB

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