warp.go 6.5 KB

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