check.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. import fs from "fs-extra";
  2. import zlib from "zlib";
  3. import tar from "tar";
  4. import path from "path";
  5. import AdmZip from "adm-zip";
  6. import fetch from "node-fetch";
  7. import proxyAgent from "https-proxy-agent";
  8. import { execSync } from "child_process";
  9. const cwd = process.cwd();
  10. const TEMP_DIR = path.join(cwd, "node_modules/.verge");
  11. const FORCE = process.argv.includes("--force");
  12. /* ======= clash =======
  13. const CLASH_STORAGE_PREFIX = "https://release.dreamacro.workers.dev/";
  14. const CLASH_URL_PREFIX =
  15. "https://github.com/Dreamacro/clash/releases/download/premium/";
  16. const CLASH_LATEST_DATE = "latest";
  17. const CLASH_BACKUP_URL_PREFIX =
  18. "https://github.com/zhongfly/Clash-premium-backup/releases/download/";
  19. const CLASH_BACKUP_LATEST_DATE = "2023-09-05-gdcc8d87";
  20. //https://github.com/zhongfly/Clash-premium-backup/releases/download/2023-09-05-gdcc8d87/clash-windows-amd64-2023-09-05-gdcc8d87.zip
  21. //https://github.com/zhongfly/Clash-premium-backup/releases/download/2023-09-05-gdcc8d87/clash-windows-amd64-n2023-09-05-gdcc8d87.zip
  22. const CLASH_MAP = {
  23. "win32-x64": "clash-windows-amd64",
  24. "darwin-x64": "clash-darwin-amd64",
  25. "darwin-arm64": "clash-darwin-arm64",
  26. "linux-x64": "clash-linux-amd64",
  27. "linux-arm64": "clash-linux-arm64",
  28. };
  29. */
  30. /* ======= clash meta ======= */
  31. const VERSION_URL =
  32. "https://github.com/MetaCubeX/mihomo/releases/download/Prerelease-Alpha/version.txt";
  33. const META_URL_PREFIX = `https://github.com/MetaCubeX/mihomo/releases/download/Prerelease-Alpha`;
  34. let META_VERSION;
  35. const META_MAP = {
  36. "win32-x64": "mihomo-windows-amd64",
  37. "win32-arm64": "mihomo-windows-arm64",
  38. "darwin-x64": "mihomo-darwin-amd64",
  39. "darwin-arm64": "mihomo-darwin-arm64",
  40. "linux-x64": "mihomo-linux-amd64",
  41. "linux-arm64": "mihomo-linux-arm64",
  42. };
  43. /*
  44. * check available
  45. */
  46. const PLATFORM_MAP = {
  47. "x86_64-pc-windows-msvc": "win32",
  48. "aarch64-pc-windows-msvc": "win32",
  49. "x86_64-apple-darwin": "darwin",
  50. "aarch64-apple-darwin": "darwin",
  51. "x86_64-unknown-linux-gnu": "linux",
  52. "aarch64-unknown-linux-gnu": "linux",
  53. };
  54. const ARCH_MAP = {
  55. "x86_64-pc-windows-msvc": "x64",
  56. "aarch64-pc-windows-msvc": "arm64",
  57. "x86_64-apple-darwin": "x64",
  58. "aarch64-apple-darwin": "arm64",
  59. "x86_64-unknown-linux-gnu": "x64",
  60. "aarch64-unknown-linux-gnu": "arm64",
  61. };
  62. /**
  63. * Fetch the latest release version from the version.txt file
  64. */
  65. async function getLatestVersion() {
  66. try {
  67. const response = await fetch(VERSION_URL, { method: "GET" });
  68. let v = await response.text();
  69. META_VERSION = v.trim(); // Trim to remove extra whitespaces
  70. console.log(`Latest release version: ${META_VERSION}`);
  71. } catch (error) {
  72. console.error("Error fetching latest release version:", error.message);
  73. process.exit(1);
  74. }
  75. }
  76. const target = process.argv.slice(2)[0];
  77. const { platform, arch } = target
  78. ? { platform: PLATFORM_MAP[target], arch: ARCH_MAP[target] }
  79. : process;
  80. const SIDECAR_HOST = target
  81. ? target
  82. : execSync("rustc -vV")
  83. .toString()
  84. .match(/(?<=host: ).+(?=\s*)/g)[0];
  85. /*
  86. if (!CLASH_MAP[`${platform}-${arch}`]) {
  87. throw new Error(`clash unsupported platform "${platform}-${arch}"`);
  88. }
  89. */
  90. if (!META_MAP[`${platform}-${arch}`]) {
  91. throw new Error(`clash meta unsupported platform "${platform}-${arch}"`);
  92. }
  93. /*
  94. function clash() {
  95. const name = CLASH_MAP[`${platform}-${arch}`];
  96. const isWin = platform === "win32";
  97. const urlExt = isWin ? "zip" : "gz";
  98. const downloadURL = `${CLASH_URL_PREFIX}${name}-${CLASH_LATEST_DATE}.${urlExt}`;
  99. const exeFile = `${name}${isWin ? ".exe" : ""}`;
  100. const zipFile = `${name}.${urlExt}`;
  101. return {
  102. name: "clash",
  103. targetFile: `clash-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
  104. exeFile,
  105. zipFile,
  106. downloadURL,
  107. };
  108. }
  109. function clashBackup() {
  110. const name = CLASH_MAP[`${platform}-${arch}`];
  111. const isWin = platform === "win32";
  112. const urlExt = isWin ? "zip" : "gz";
  113. const downloadURL = `${CLASH_BACKUP_URL_PREFIX}${CLASH_BACKUP_LATEST_DATE}/${name}-n${CLASH_BACKUP_LATEST_DATE}.${urlExt}`;
  114. const exeFile = `${name}${isWin ? ".exe" : ""}`;
  115. const zipFile = `${name}.${urlExt}`;
  116. return {
  117. name: "clash",
  118. targetFile: `clash-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
  119. exeFile,
  120. zipFile,
  121. downloadURL,
  122. };
  123. }
  124. function clashS3() {
  125. const name = CLASH_MAP[`${platform}-${arch}`];
  126. const isWin = platform === "win32";
  127. const urlExt = isWin ? "zip" : "gz";
  128. const downloadURL = `${CLASH_STORAGE_PREFIX}${CLASH_LATEST_DATE}/${name}-${CLASH_LATEST_DATE}.${urlExt}`;
  129. const exeFile = `${name}${isWin ? ".exe" : ""}`;
  130. const zipFile = `${name}.${urlExt}`;
  131. return {
  132. name: "clash",
  133. targetFile: `clash-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
  134. exeFile,
  135. zipFile,
  136. downloadURL,
  137. };
  138. }
  139. */
  140. function clashMeta() {
  141. const name = META_MAP[`${platform}-${arch}`];
  142. const isWin = platform === "win32";
  143. const urlExt = isWin ? "zip" : "gz";
  144. const downloadURL = `${META_URL_PREFIX}/${name}-${META_VERSION}.${urlExt}`;
  145. const exeFile = `${name}${isWin ? ".exe" : ""}`;
  146. const zipFile = `${name}-${META_VERSION}.${urlExt}`;
  147. return {
  148. name: "clash-meta",
  149. targetFile: `clash-meta-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
  150. exeFile,
  151. zipFile,
  152. downloadURL,
  153. };
  154. }
  155. /**
  156. * download sidecar and rename
  157. */
  158. async function resolveSidecar(binInfo) {
  159. const { name, targetFile, zipFile, exeFile, downloadURL } = binInfo;
  160. const sidecarDir = path.join(cwd, "src-tauri", "sidecar");
  161. const sidecarPath = path.join(sidecarDir, targetFile);
  162. await fs.mkdirp(sidecarDir);
  163. if (!FORCE && (await fs.pathExists(sidecarPath))) return;
  164. const tempDir = path.join(TEMP_DIR, name);
  165. const tempZip = path.join(tempDir, zipFile);
  166. const tempExe = path.join(tempDir, exeFile);
  167. await fs.mkdirp(tempDir);
  168. try {
  169. if (!(await fs.pathExists(tempZip))) {
  170. await downloadFile(downloadURL, tempZip);
  171. }
  172. if (zipFile.endsWith(".zip")) {
  173. const zip = new AdmZip(tempZip);
  174. zip.getEntries().forEach((entry) => {
  175. console.log(`[DEBUG]: "${name}" entry name`, entry.entryName);
  176. });
  177. zip.extractAllTo(tempDir, true);
  178. await fs.rename(tempExe, sidecarPath);
  179. console.log(`[INFO]: "${name}" unzip finished`);
  180. } else if (zipFile.endsWith(".tgz")) {
  181. // tgz
  182. await fs.mkdirp(tempDir);
  183. await tar.extract({
  184. cwd: tempDir,
  185. file: tempZip,
  186. //strip: 1, // 可能需要根据实际的 .tgz 文件结构调整
  187. });
  188. const files = await fs.readdir(tempDir);
  189. console.log(`[DEBUG]: "${name}" files in tempDir:`, files);
  190. const extractedFile = files.find((file) => file.startsWith("虚空终端-"));
  191. if (extractedFile) {
  192. const extractedFilePath = path.join(tempDir, extractedFile);
  193. await fs.rename(extractedFilePath, sidecarPath);
  194. console.log(`[INFO]: "${name}" file renamed to "${sidecarPath}"`);
  195. execSync(`chmod 755 ${sidecarPath}`);
  196. console.log(`[INFO]: "${name}" chmod binary finished`);
  197. } else {
  198. throw new Error(`Expected file not found in ${tempDir}`);
  199. }
  200. } else {
  201. // gz
  202. const readStream = fs.createReadStream(tempZip);
  203. const writeStream = fs.createWriteStream(sidecarPath);
  204. await new Promise((resolve, reject) => {
  205. const onError = (error) => {
  206. console.error(`[ERROR]: "${name}" gz failed:`, error.message);
  207. reject(error);
  208. };
  209. readStream
  210. .pipe(zlib.createGunzip().on("error", onError))
  211. .pipe(writeStream)
  212. .on("finish", () => {
  213. console.log(`[INFO]: "${name}" gunzip finished`);
  214. execSync(`chmod 755 ${sidecarPath}`);
  215. console.log(`[INFO]: "${name}" chmod binary finished`);
  216. resolve();
  217. })
  218. .on("error", onError);
  219. });
  220. }
  221. } catch (err) {
  222. // 需要删除文件
  223. await fs.remove(sidecarPath);
  224. throw err;
  225. } finally {
  226. // delete temp dir
  227. await fs.remove(tempDir);
  228. }
  229. }
  230. /**
  231. * prepare clash core
  232. * if the core version is not updated in time, use S3 storage as a backup.
  233. */
  234. async function resolveClash() {
  235. try {
  236. return await resolveSidecar(clash());
  237. } catch {
  238. console.log(`[WARN]: clash core needs to be updated`);
  239. return await resolveSidecar(clashS3());
  240. }
  241. }
  242. /**
  243. * only Windows
  244. * get the wintun.dll (not required)
  245. async function resolveWintun() {
  246. const { platform } = process;
  247. if (platform !== "win32") return;
  248. const url = "https://www.wintun.net/builds/wintun-0.14.1.zip";
  249. const tempDir = path.join(TEMP_DIR, "wintun");
  250. const tempZip = path.join(tempDir, "wintun.zip");
  251. const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
  252. const targetPath = path.join(cwd, "src-tauri/resources", "wintun.dll");
  253. if (!FORCE && (await fs.pathExists(targetPath))) return;
  254. await fs.mkdirp(tempDir);
  255. if (!(await fs.pathExists(tempZip))) {
  256. await downloadFile(url, tempZip);
  257. }
  258. // unzip
  259. const zip = new AdmZip(tempZip);
  260. zip.extractAllTo(tempDir, true);
  261. if (!(await fs.pathExists(wintunPath))) {
  262. throw new Error(`path not found "${wintunPath}"`);
  263. }
  264. await fs.rename(wintunPath, targetPath);
  265. await fs.remove(tempDir);
  266. console.log(`[INFO]: resolve wintun.dll finished`);
  267. }
  268. */
  269. /**
  270. * download the file to the resources dir
  271. */
  272. async function resolveResource(binInfo) {
  273. const { file, downloadURL } = binInfo;
  274. const resDir = path.join(cwd, "src-tauri/resources");
  275. const targetPath = path.join(resDir, file);
  276. if (!FORCE && (await fs.pathExists(targetPath))) return;
  277. await fs.mkdirp(resDir);
  278. await downloadFile(downloadURL, targetPath);
  279. console.log(`[INFO]: ${file} finished`);
  280. }
  281. /**
  282. * download file and save to `path`
  283. */
  284. async function downloadFile(url, path) {
  285. const options = {};
  286. const httpProxy =
  287. process.env.HTTP_PROXY ||
  288. process.env.http_proxy ||
  289. process.env.HTTPS_PROXY ||
  290. process.env.https_proxy;
  291. if (httpProxy) {
  292. options.agent = proxyAgent(httpProxy);
  293. }
  294. const response = await fetch(url, {
  295. ...options,
  296. method: "GET",
  297. headers: { "Content-Type": "application/octet-stream" },
  298. });
  299. const buffer = await response.arrayBuffer();
  300. await fs.writeFile(path, new Uint8Array(buffer));
  301. console.log(`[INFO]: download finished "${url}"`);
  302. }
  303. /**
  304. * main
  305. */
  306. const SERVICE_URL =
  307. "https://github.com/zzzgydi/clash-verge-service/releases/download/latest";
  308. const resolveService = () =>
  309. resolveResource({
  310. file: "clash-verge-service.exe",
  311. downloadURL: `${SERVICE_URL}/clash-verge-service.exe`,
  312. });
  313. const resolveInstall = () =>
  314. resolveResource({
  315. file: "install-service.exe",
  316. downloadURL: `${SERVICE_URL}/install-service.exe`,
  317. });
  318. const resolveUninstall = () =>
  319. resolveResource({
  320. file: "uninstall-service.exe",
  321. downloadURL: `${SERVICE_URL}/uninstall-service.exe`,
  322. });
  323. const resolveMmdb = () =>
  324. resolveResource({
  325. file: "Country.mmdb",
  326. downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/country.mmdb`,
  327. });
  328. const resolveGeosite = () =>
  329. resolveResource({
  330. file: "geosite.dat",
  331. downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geosite.dat`,
  332. });
  333. const resolveGeoIP = () =>
  334. resolveResource({
  335. file: "geoip.dat",
  336. downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.dat`,
  337. });
  338. const resolveEnableLoopback = () =>
  339. resolveResource({
  340. file: "enableLoopback.exe",
  341. downloadURL: `https://github.com/Kuingsmile/uwp-tool/releases/download/latest/enableLoopback.exe`,
  342. });
  343. const tasks = [
  344. // { name: "clash", func: resolveClash, retry: 5 },
  345. {
  346. name: "clash-meta",
  347. func: () => getLatestVersion().then(() => resolveSidecar(clashMeta())),
  348. retry: 5,
  349. },
  350. // { name: "wintun", func: resolveWintun, retry: 5, winOnly: true },
  351. { name: "service", func: resolveService, retry: 5, winOnly: true },
  352. { name: "install", func: resolveInstall, retry: 5, winOnly: true },
  353. { name: "uninstall", func: resolveUninstall, retry: 5, winOnly: true },
  354. { name: "mmdb", func: resolveMmdb, retry: 5 },
  355. { name: "geosite", func: resolveGeosite, retry: 5 },
  356. { name: "geoip", func: resolveGeoIP, retry: 5 },
  357. {
  358. name: "enableLoopback",
  359. func: resolveEnableLoopback,
  360. retry: 5,
  361. winOnly: true,
  362. },
  363. ];
  364. async function runTask() {
  365. const task = tasks.shift();
  366. if (!task) return;
  367. if (task.winOnly && process.platform !== "win32") return runTask();
  368. for (let i = 0; i < task.retry; i++) {
  369. try {
  370. await task.func();
  371. break;
  372. } catch (err) {
  373. console.error(`[ERROR]: task::${task.name} try ${i} ==`, err.message);
  374. if (i === task.retry - 1) throw err;
  375. }
  376. }
  377. return runTask();
  378. }
  379. runTask();
  380. runTask();