WarpModal.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import { useCallback, useEffect, useMemo, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import {
  4. Alert,
  5. Button,
  6. Collapse,
  7. Divider,
  8. Form,
  9. Input,
  10. message,
  11. Modal,
  12. Tag,
  13. } from 'antd';
  14. import { ApiOutlined, SyncOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
  15. import { HttpUtil, SizeFormatter, ObjectUtil, Wireguard } from '@/utils';
  16. import './WarpModal.css';
  17. interface WarpModalProps {
  18. open: boolean;
  19. templateSettings: { outbounds?: { tag?: string }[] } | null;
  20. onClose: () => void;
  21. onAddOutbound: (outbound: Record<string, unknown>) => void;
  22. onResetOutbound: (payload: { index: number; outbound: Record<string, unknown> }) => void;
  23. onRemoveOutbound: (tag: string) => void;
  24. }
  25. interface WarpData {
  26. access_token?: string;
  27. device_id?: string;
  28. license_key?: string;
  29. private_key?: string;
  30. client_id?: string;
  31. }
  32. interface WarpConfig {
  33. name?: string;
  34. model?: string;
  35. enabled?: boolean;
  36. config?: {
  37. client_id?: string;
  38. interface?: { addresses?: { v4?: string; v6?: string } };
  39. peers?: { public_key?: string; endpoint?: { host?: string } }[];
  40. };
  41. account?: {
  42. account_type?: string;
  43. role?: string;
  44. premium_data?: number;
  45. quota?: number;
  46. usage?: number;
  47. };
  48. }
  49. function addressesFor(addrs: { v4?: string; v6?: string }): string[] {
  50. const out: string[] = [];
  51. if (addrs.v4) out.push(`${addrs.v4}/32`);
  52. if (addrs.v6) out.push(`${addrs.v6}/128`);
  53. return out;
  54. }
  55. function reservedFor(clientId?: string): number[] {
  56. if (!clientId) return [];
  57. const decoded = atob(clientId);
  58. const out: number[] = [];
  59. for (let i = 0; i < decoded.length; i += 1) out.push(decoded.charCodeAt(i));
  60. return out;
  61. }
  62. export default function WarpModal({
  63. open,
  64. templateSettings,
  65. onClose,
  66. onAddOutbound,
  67. onResetOutbound,
  68. onRemoveOutbound,
  69. }: WarpModalProps) {
  70. const { t } = useTranslation();
  71. const [messageApi, messageContextHolder] = message.useMessage();
  72. const [loading, setLoading] = useState(false);
  73. const [warpData, setWarpData] = useState<WarpData | null>(null);
  74. const [warpConfig, setWarpConfig] = useState<WarpConfig | null>(null);
  75. const [warpPlus, setWarpPlus] = useState('');
  76. const [licenseError, setLicenseError] = useState('');
  77. const [stagedOutbound, setStagedOutbound] = useState<Record<string, unknown> | null>(null);
  78. const warpOutboundIndex = useMemo(() => {
  79. const list = templateSettings?.outbounds;
  80. if (!list) return -1;
  81. return list.findIndex((o) => o?.tag === 'warp');
  82. }, [templateSettings?.outbounds]);
  83. const collectConfig = useCallback((data: WarpData | null, config: WarpConfig | null) => {
  84. const cfg = config?.config;
  85. if (!cfg?.peers?.length) return;
  86. const peer = cfg.peers[0];
  87. setStagedOutbound({
  88. tag: 'warp',
  89. protocol: 'wireguard',
  90. settings: {
  91. mtu: 1420,
  92. secretKey: data?.private_key,
  93. address: addressesFor(cfg.interface?.addresses || {}),
  94. reserved: reservedFor(cfg.client_id ?? data?.client_id),
  95. domainStrategy: 'ForceIP',
  96. peers: [{ publicKey: peer.public_key, endpoint: peer.endpoint?.host }],
  97. noKernelTun: false,
  98. },
  99. });
  100. }, []);
  101. const fetchData = useCallback(async () => {
  102. setLoading(true);
  103. try {
  104. const msg = await HttpUtil.post<string>('/panel/xray/warp/data');
  105. if (msg?.success) {
  106. const raw = msg.obj;
  107. setWarpData(raw && raw.length > 0 ? JSON.parse(raw) : null);
  108. }
  109. } finally {
  110. setLoading(false);
  111. }
  112. }, []);
  113. useEffect(() => {
  114. if (!open) return;
  115. setWarpConfig(null);
  116. setStagedOutbound(null);
  117. setLicenseError('');
  118. fetchData();
  119. }, [open, fetchData]);
  120. async function register() {
  121. setLoading(true);
  122. try {
  123. const keys = Wireguard.generateKeypair();
  124. const msg = await HttpUtil.post<string>('/panel/xray/warp/reg', keys);
  125. if (msg?.success && msg.obj) {
  126. const resp = JSON.parse(msg.obj);
  127. setWarpData(resp.data);
  128. setWarpConfig(resp.config);
  129. collectConfig(resp.data, resp.config);
  130. }
  131. } finally {
  132. setLoading(false);
  133. }
  134. }
  135. async function getConfig() {
  136. setLoading(true);
  137. try {
  138. const msg = await HttpUtil.post<string>('/panel/xray/warp/config');
  139. if (msg?.success && msg.obj) {
  140. const parsed = JSON.parse(msg.obj);
  141. setWarpConfig(parsed);
  142. collectConfig(warpData, parsed);
  143. }
  144. } finally {
  145. setLoading(false);
  146. }
  147. }
  148. async function updateLicense() {
  149. if (warpPlus.length < 26) return;
  150. setLoading(true);
  151. setLicenseError('');
  152. try {
  153. const msg = await HttpUtil.post<string>('/panel/xray/warp/license', { license: warpPlus });
  154. if (msg?.success && msg.obj) {
  155. setWarpData(JSON.parse(msg.obj));
  156. setWarpConfig(null);
  157. setWarpPlus('');
  158. } else {
  159. setLicenseError(msg?.msg || t('pages.xray.warp.licenseError'));
  160. }
  161. } finally {
  162. setLoading(false);
  163. }
  164. }
  165. async function delConfig() {
  166. setLoading(true);
  167. try {
  168. const msg = await HttpUtil.post('/panel/xray/warp/del');
  169. if (msg?.success) {
  170. setWarpData(null);
  171. setWarpConfig(null);
  172. setStagedOutbound(null);
  173. onRemoveOutbound('warp');
  174. onClose();
  175. }
  176. } finally {
  177. setLoading(false);
  178. }
  179. }
  180. function addOutbound() {
  181. if (!stagedOutbound) {
  182. messageApi.warning(t('pages.xray.warp.fetchFirst'));
  183. return;
  184. }
  185. onAddOutbound(stagedOutbound);
  186. onClose();
  187. }
  188. function resetOutbound() {
  189. if (!stagedOutbound) return;
  190. onResetOutbound({ index: warpOutboundIndex, outbound: stagedOutbound });
  191. onClose();
  192. }
  193. const hasWarp = !ObjectUtil.isEmpty(warpData);
  194. const hasConfig = !ObjectUtil.isEmpty(warpConfig);
  195. return (
  196. <>
  197. {messageContextHolder}
  198. <Modal open={open} title="Cloudflare WARP" footer={null} onCancel={onClose}>
  199. {!hasWarp ? (
  200. <Button type="primary" loading={loading} icon={<ApiOutlined />} onClick={register}>
  201. {t('pages.xray.warp.createAccount')}
  202. </Button>
  203. ) : (
  204. <>
  205. <table className="warp-data-table">
  206. <tbody>
  207. <tr className="row-odd">
  208. <td>{t('pages.xray.warp.accessToken')}</td>
  209. <td>{warpData?.access_token}</td>
  210. </tr>
  211. <tr>
  212. <td>{t('pages.xray.warp.deviceId')}</td>
  213. <td>{warpData?.device_id}</td>
  214. </tr>
  215. <tr className="row-odd">
  216. <td>{t('pages.xray.warp.licenseKey')}</td>
  217. <td>{warpData?.license_key}</td>
  218. </tr>
  219. <tr>
  220. <td>{t('pages.xray.warp.privateKey')}</td>
  221. <td>{warpData?.private_key}</td>
  222. </tr>
  223. </tbody>
  224. </table>
  225. <Button loading={loading} type="primary" danger className="mt-8" icon={<DeleteOutlined />} onClick={delConfig}>
  226. {t('pages.xray.warp.deleteAccount')}
  227. </Button>
  228. <Divider className="zero-margin">{t('pages.xray.warp.settings')}</Divider>
  229. <Collapse
  230. className="my-10"
  231. items={[
  232. {
  233. key: '1',
  234. label: t('pages.xray.warp.licenseKeyLabel'),
  235. children: (
  236. <Form colon={false} labelCol={{ md: { span: 6 } }} wrapperCol={{ md: { span: 14 } }}>
  237. <Form.Item label={t('pages.xray.warp.key')}>
  238. <Input
  239. value={warpPlus}
  240. placeholder={t('pages.xray.warp.keyPlaceholder')}
  241. onChange={(e) => {
  242. setWarpPlus(e.target.value);
  243. setLicenseError('');
  244. }}
  245. />
  246. <div className="license-actions mt-8">
  247. <Button
  248. type="primary"
  249. disabled={warpPlus.length < 26}
  250. loading={loading}
  251. onClick={updateLicense}
  252. >
  253. {t('update')}
  254. </Button>
  255. {licenseError && (
  256. <Alert title={licenseError} type="error" showIcon className="license-error" />
  257. )}
  258. </div>
  259. </Form.Item>
  260. </Form>
  261. ),
  262. },
  263. ]}
  264. />
  265. <Divider className="zero-margin">{t('pages.xray.warp.accountInfo')}</Divider>
  266. <Button className="my-8" loading={loading} type="primary" icon={<SyncOutlined />} onClick={getConfig}>
  267. {t('refresh')}
  268. </Button>
  269. {hasConfig && (
  270. <>
  271. <table className="warp-data-table">
  272. <tbody>
  273. <tr className="row-odd">
  274. <td>{t('pages.xray.warp.deviceName')}</td>
  275. <td>{warpConfig?.name}</td>
  276. </tr>
  277. <tr>
  278. <td>{t('pages.xray.warp.deviceModel')}</td>
  279. <td>{warpConfig?.model}</td>
  280. </tr>
  281. <tr className="row-odd">
  282. <td>{t('pages.xray.warp.deviceEnabled')}</td>
  283. <td>{String(warpConfig?.enabled)}</td>
  284. </tr>
  285. {warpConfig?.account && (
  286. <>
  287. <tr>
  288. <td>{t('pages.xray.warp.accountType')}</td>
  289. <td>{warpConfig.account.account_type}</td>
  290. </tr>
  291. <tr className="row-odd">
  292. <td>{t('pages.xray.warp.role')}</td>
  293. <td>{warpConfig.account.role}</td>
  294. </tr>
  295. <tr>
  296. <td>{t('pages.xray.warp.warpPlusData')}</td>
  297. <td>{SizeFormatter.sizeFormat(warpConfig.account.premium_data)}</td>
  298. </tr>
  299. <tr className="row-odd">
  300. <td>{t('pages.xray.warp.quota')}</td>
  301. <td>{SizeFormatter.sizeFormat(warpConfig.account.quota)}</td>
  302. </tr>
  303. {warpConfig.account.usage != null && (
  304. <tr>
  305. <td>{t('pages.xray.warp.usage')}</td>
  306. <td>{SizeFormatter.sizeFormat(warpConfig.account.usage)}</td>
  307. </tr>
  308. )}
  309. </>
  310. )}
  311. </tbody>
  312. </table>
  313. <Divider className="my-10">{t('pages.xray.outbound.outboundStatus')}</Divider>
  314. {warpOutboundIndex >= 0 ? (
  315. <>
  316. <Tag color="green">{t('enabled')}</Tag>
  317. <Button type="primary" danger loading={loading} className="ml-8" onClick={resetOutbound}>
  318. {t('reset')}
  319. </Button>
  320. </>
  321. ) : (
  322. <>
  323. <Tag color="orange">{t('disabled')}</Tag>
  324. <Button type="primary" loading={loading} className="ml-8" icon={<PlusOutlined />} onClick={addOutbound}>
  325. {t('pages.xray.warp.addOutbound')}
  326. </Button>
  327. </>
  328. )}
  329. </>
  330. )}
  331. </>
  332. )}
  333. </Modal>
  334. </>
  335. );
  336. }