1
0

warp.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. warpClientVer = "a-6.30-3596"
  23. )
  24. // warpAPIBase is the Cloudflare WARP registration API base URL. It is a var
  25. // (not a const) so integration tests can point it at a mock server.
  26. var warpAPIBase = "https://api.cloudflareclient.com/v0a4005"
  27. func (s *WarpService) GetWarpData() (string, error) {
  28. return s.GetWarp()
  29. }
  30. func (s *WarpService) DelWarpData() error {
  31. return s.SetWarp("")
  32. }
  33. func (s *WarpService) GetWarpConfig() (string, error) {
  34. warpData, err := s.loadWarpCreds()
  35. if err != nil {
  36. return "", err
  37. }
  38. url := fmt.Sprintf("%s/reg/%s", warpAPIBase, warpData["device_id"])
  39. req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil)
  40. if err != nil {
  41. return "", err
  42. }
  43. req.Header.Set("Authorization", "Bearer "+warpData["access_token"])
  44. body, err := s.doWarpRequest(req)
  45. if err != nil {
  46. return "", err
  47. }
  48. return string(body), nil
  49. }
  50. func (s *WarpService) RegWarp(secretKey string, publicKey string) (string, error) {
  51. hostName, _ := os.Hostname()
  52. reqBody, err := json.Marshal(map[string]any{
  53. "key": publicKey,
  54. "tos": time.Now().UTC().Format("2006-01-02T15:04:05.000Z"),
  55. "type": "PC",
  56. "model": "x-ui",
  57. "name": hostName,
  58. })
  59. if err != nil {
  60. return "", err
  61. }
  62. req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, warpAPIBase+"/reg", bytes.NewReader(reqBody))
  63. if err != nil {
  64. return "", err
  65. }
  66. req.Header.Set("CF-Client-Version", warpClientVer)
  67. req.Header.Set("Content-Type", "application/json")
  68. body, err := s.doWarpRequest(req)
  69. if err != nil {
  70. return "", err
  71. }
  72. var rsp map[string]any
  73. if err := json.Unmarshal(body, &rsp); err != nil {
  74. return "", err
  75. }
  76. deviceID, ok := rsp["id"].(string)
  77. if !ok {
  78. return "", common.NewError("warp register: missing 'id' in response")
  79. }
  80. token, ok := rsp["token"].(string)
  81. if !ok {
  82. return "", common.NewError("warp register: missing 'token' in response")
  83. }
  84. account, ok := rsp["account"].(map[string]any)
  85. if !ok {
  86. return "", common.NewError("warp register: missing 'account' in response")
  87. }
  88. license, ok := account["license"].(string)
  89. if !ok {
  90. return "", common.NewError("warp register: missing 'account.license' in response")
  91. }
  92. warpData := map[string]string{
  93. "access_token": token,
  94. "device_id": deviceID,
  95. "license_key": license,
  96. "private_key": secretKey,
  97. }
  98. if config, ok := rsp["config"].(map[string]any); ok {
  99. if clientID, ok := config["client_id"].(string); ok {
  100. warpData["client_id"] = clientID
  101. }
  102. }
  103. warpJSON, err := json.MarshalIndent(warpData, "", " ")
  104. if err != nil {
  105. return "", err
  106. }
  107. if err := s.SetWarp(string(warpJSON)); err != nil {
  108. return "", err
  109. }
  110. result, err := json.MarshalIndent(map[string]any{
  111. "data": warpData,
  112. "config": json.RawMessage(body),
  113. }, "", " ")
  114. if err != nil {
  115. return "", err
  116. }
  117. return string(result), nil
  118. }
  119. func (s *WarpService) SetWarpLicense(license string) (string, error) {
  120. warpData, err := s.loadWarpCreds()
  121. if err != nil {
  122. return "", err
  123. }
  124. url := fmt.Sprintf("%s/reg/%s/account", warpAPIBase, warpData["device_id"])
  125. reqBody, err := json.Marshal(map[string]string{"license": license})
  126. if err != nil {
  127. return "", err
  128. }
  129. req, err := http.NewRequestWithContext(context.Background(), http.MethodPut, url, bytes.NewReader(reqBody))
  130. if err != nil {
  131. return "", err
  132. }
  133. req.Header.Set("Authorization", "Bearer "+warpData["access_token"])
  134. req.Header.Set("Content-Type", "application/json")
  135. body, err := s.doWarpRequest(req)
  136. if err != nil {
  137. return "", err
  138. }
  139. var response map[string]any
  140. if err := json.Unmarshal(body, &response); err != nil {
  141. return "", err
  142. }
  143. if _, ok := response["id"].(string); !ok {
  144. return "", common.NewErrorf("warp set license failed: unexpected response: %s", string(body))
  145. }
  146. warpData["license_key"] = license
  147. newWarpData, err := json.MarshalIndent(warpData, "", " ")
  148. if err != nil {
  149. return "", err
  150. }
  151. if err := s.SetWarp(string(newWarpData)); err != nil {
  152. return "", err
  153. }
  154. return string(newWarpData), nil
  155. }
  156. func (s *WarpService) ChangeWarpIP() (string, error) {
  157. warpDataMap, err := s.loadWarpCreds()
  158. if err != nil {
  159. return "", err
  160. }
  161. privKey, pubKey, err := wireguard.GenerateWireguardKeypair()
  162. if err != nil {
  163. return "", err
  164. }
  165. result, err := s.RegWarp(privKey, pubKey)
  166. if err != nil {
  167. return "", err
  168. }
  169. var parsed struct {
  170. Data map[string]string `json:"data"`
  171. Config map[string]any `json:"config"`
  172. }
  173. if err := json.Unmarshal([]byte(result), &parsed); err != nil {
  174. return "", err
  175. }
  176. // RegWarp stores the new device's data, which for a fresh registration
  177. // carries an empty license_key. Re-apply the old license key to the stored
  178. // data BEFORE the remote upgrade attempt, so a failed re-apply can never
  179. // delete the saved key.
  180. var reapplyWarn error
  181. if license, ok := warpDataMap["license_key"]; ok && len(license) >= 26 {
  182. if parsed.Data == nil {
  183. parsed.Data = make(map[string]string)
  184. }
  185. parsed.Data["license_key"] = license
  186. if stored, err := json.MarshalIndent(parsed.Data, "", " "); err != nil {
  187. return "", err
  188. } else if err := s.SetWarp(string(stored)); err != nil {
  189. return "", err
  190. }
  191. }
  192. xraySvc := service.XraySettingService{}
  193. if err := xraySvc.UpdateWarpXraySetting(parsed.Data, parsed.Config); err != nil {
  194. return "", err
  195. }
  196. if license, ok := warpDataMap["license_key"]; ok && len(license) >= 26 {
  197. if _, licErr := s.SetWarpLicense(license); licErr != nil {
  198. // The key is already preserved in storage above; surface the
  199. // remote failure instead of silently downgrading to a free account.
  200. reapplyWarn = licErr
  201. logger.Warning("ChangeWarpIP: failed to re-apply WARP license (key preserved in storage): ", licErr)
  202. }
  203. }
  204. // Return the final stored data (with the preserved license key) instead of
  205. // RegWarp's snapshot, which always carries an empty license.
  206. response := map[string]any{
  207. "data": parsed.Data,
  208. "config": parsed.Config,
  209. }
  210. if reapplyWarn != nil {
  211. response["warning"] = fmt.Sprintf("failed to re-apply WARP license: %v", reapplyWarn)
  212. }
  213. resultJSON, err := json.MarshalIndent(response, "", " ")
  214. if err != nil {
  215. return "", err
  216. }
  217. return string(resultJSON), nil
  218. }
  219. // loadWarpCreds reads the stored warp JSON and ensures access_token + device_id are set.
  220. func (s *WarpService) loadWarpCreds() (map[string]string, error) {
  221. warp, err := s.GetWarp()
  222. if err != nil {
  223. return nil, err
  224. }
  225. var data map[string]string
  226. if err := json.Unmarshal([]byte(warp), &data); err != nil {
  227. return nil, err
  228. }
  229. if data["access_token"] == "" || data["device_id"] == "" {
  230. return nil, common.NewError("warp not registered: missing access_token or device_id")
  231. }
  232. return data, nil
  233. }
  234. // doWarpRequest sends the request and returns the response body on 2xx.
  235. // Non-2xx responses are returned as errors including the status code and body.
  236. func (s *WarpService) doWarpRequest(req *http.Request) ([]byte, error) {
  237. client := s.NewProxiedHTTPClient(15 * time.Second)
  238. resp, err := client.Do(req)
  239. if err != nil {
  240. return nil, err
  241. }
  242. defer resp.Body.Close()
  243. body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseSize))
  244. if err != nil {
  245. return nil, err
  246. }
  247. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  248. if msg := parseWarpError(body); msg != "" {
  249. return nil, common.NewError(msg)
  250. }
  251. return nil, common.NewErrorf("warp api %s %s returned status %d: %s",
  252. req.Method, req.URL.Path, resp.StatusCode, string(body))
  253. }
  254. return body, nil
  255. }
  256. func parseWarpError(body []byte) string {
  257. var env struct {
  258. Errors []struct {
  259. Message string `json:"message"`
  260. } `json:"errors"`
  261. }
  262. if err := json.Unmarshal(body, &env); err != nil {
  263. return ""
  264. }
  265. if len(env.Errors) == 0 || env.Errors[0].Message == "" {
  266. return ""
  267. }
  268. return env.Errors[0].Message
  269. }