test-installer-preserve-files.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import { execFileSync } from "node:child_process";
  2. import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
  3. import { createRequire } from "node:module";
  4. import { tmpdir } from "node:os";
  5. import { resolve, join, dirname } from "node:path";
  6. import { fileURLToPath } from "node:url";
  7. const require = createRequire(import.meta.url);
  8. const scriptDir = dirname(fileURLToPath(import.meta.url));
  9. const desktopDir = resolve(scriptDir, "..");
  10. const workspaceDir = resolve(desktopDir, "../..");
  11. const fixturePath = resolve(desktopDir, "test/fixtures/installer-preserve-files.nsi");
  12. const installerNshPath = resolve(desktopDir, "build/installer.nsh");
  13. const appBuilderLibDir = dirname(require.resolve("app-builder-lib/package.json"));
  14. const { getBinFromUrl } = require(resolve(appBuilderLibDir, "out/binDownload.js"));
  15. const NSIS_CHECKSUM =
  16. "VKMiizYdmNdJOWpRGz4trl4lD++BvYP2irAXpMilheUP0pc93iKlWAoP843Vlraj8YG19CVn0j+dCo/hURz9+Q==";
  17. const NSIS_RESOURCES_CHECKSUM =
  18. "Dqd6g+2buwwvoG1Vyf6BHR1b+25QMmPcwZx40atOT57gH27rkjOei1L0JTldxZu4NFoEmW4kJgZ3DlSWVON3+Q==";
  19. if (process.platform !== "win32") {
  20. process.stdout.write("[installer-preserve-files] skipped: Windows only\n");
  21. } else {
  22. const [nsisDir, nsisResourcesDir] = await Promise.all([
  23. getBinFromUrl("nsis-3.0.4.1", "nsis-3.0.4.1.7z", NSIS_CHECKSUM),
  24. getBinFromUrl("nsis-resources-3.4.1", "nsis-resources-3.4.1.7z", NSIS_RESOURCES_CHECKSUM),
  25. ]);
  26. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-preserve-files-"));
  27. try {
  28. const makensisPath = resolve(nsisDir, "makensis.exe");
  29. const uninstallerOutput = join(tempRoot, "uninstaller.exe");
  30. execFileSync(
  31. makensisPath,
  32. [
  33. "/V2",
  34. "/INPUTCHARSET",
  35. "UTF8",
  36. "/WX",
  37. "/DBUILD_UNINSTALLER",
  38. `/DNSIS_INCLUDE_DIR=${resolve(nsisDir, "Include")}`,
  39. `/DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${resolve(appBuilderLibDir, "templates/nsis/include")}`,
  40. `/DNSIS_PLUGIN_DIR=${resolve(nsisResourcesDir, "plugins/x86-unicode")}`,
  41. `/DZCODE_INSTALLER_NSH=${installerNshPath}`,
  42. `/DZCODE_INSTALLER_PROCESS_HELPER=${resolve(desktopDir, `bundled-tools/win32-${process.arch}/runtime-host/zcode-installer-process-helper.exe`)}`,
  43. // 夹具只校验文件字节,不执行该载荷;避免 32 位 NSIS 将 System32 重定向到 SysWOW64。
  44. `/DFIXTURE_EXE=${fixturePath}`,
  45. `/DOUTPUT_FILE=${uninstallerOutput}`,
  46. fixturePath,
  47. ],
  48. { cwd: workspaceDir, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] },
  49. );
  50. const legacySelfUninstaller = join(tempRoot, "legacy-self-uninstaller.exe");
  51. execFileSync(
  52. makensisPath,
  53. [
  54. "/V2",
  55. "/INPUTCHARSET",
  56. "UTF8",
  57. "/WX",
  58. `/DOUTPUT_FILE=${legacySelfUninstaller}`,
  59. resolve(desktopDir, "test/fixtures/legacy-self-manifest-uninstaller.nsi"),
  60. ],
  61. { cwd: workspaceDir, encoding: "utf8" },
  62. );
  63. for (const [scenario, omitManifest] of [
  64. ["manifest", false],
  65. ["legacy", true],
  66. ["self-manifest", false],
  67. ]) {
  68. const outputPath = join(tempRoot, `${scenario}.exe`);
  69. const installDir = join(tempRoot, scenario);
  70. const compileArgs = [
  71. "/V2",
  72. "/INPUTCHARSET",
  73. "UTF8",
  74. `/DNSIS_INCLUDE_DIR=${resolve(nsisDir, "Include")}`,
  75. `/DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${resolve(appBuilderLibDir, "templates/nsis/include")}`,
  76. `/DNSIS_PLUGIN_DIR=${resolve(nsisResourcesDir, "plugins/x86-unicode")}`,
  77. `/DZCODE_INSTALLER_NSH=${installerNshPath}`,
  78. `/DZCODE_INSTALLER_PROCESS_HELPER=${resolve(desktopDir, `bundled-tools/win32-${process.arch}/runtime-host/zcode-installer-process-helper.exe`)}`,
  79. `/DFIXTURE_EXE=${fixturePath}`,
  80. `/DOUTPUT_FILE=${outputPath}`,
  81. fixturePath,
  82. ];
  83. if (omitManifest) compileArgs.splice(-1, 0, "/DOMIT_MANIFEST");
  84. if (scenario === "self-manifest") compileArgs.splice(-1, 0, "/DSELF_MANIFEST");
  85. execFileSync(makensisPath, compileArgs, {
  86. cwd: workspaceDir,
  87. encoding: "utf-8",
  88. stdio: ["ignore", "pipe", "pipe"],
  89. });
  90. execFileSync(outputPath, ["/S", `/D=${installDir}`], { encoding: "utf-8" });
  91. const ownedFileExists = existsSync(join(installDir, "owned-by-zcode.txt"));
  92. if (omitManifest !== ownedFileExists) {
  93. throw new Error(`${scenario}: ownership fallback mismatch`);
  94. }
  95. if (!existsSync(join(installDir, "user-data.txt"))) {
  96. throw new Error(`${scenario}: unrelated file was removed`);
  97. }
  98. if (readFileSync(join(installDir, "ZCode.exe")).length === 0) {
  99. throw new Error(`${scenario}: application payload was not installed`);
  100. }
  101. }
  102. const failureOutputPath = join(tempRoot, "failure.exe");
  103. const failureInstallDir = join(tempRoot, "failure");
  104. const failureLogPath = join(tempRoot, "failure-uninstaller.log");
  105. const failureCompileArgs = [
  106. "/V2",
  107. "/INPUTCHARSET",
  108. "UTF8",
  109. "/WX",
  110. "/DBUILD_UNINSTALLER",
  111. `/DNSIS_INCLUDE_DIR=${resolve(nsisDir, "Include")}`,
  112. `/DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${resolve(appBuilderLibDir, "templates/nsis/include")}`,
  113. `/DNSIS_PLUGIN_DIR=${resolve(nsisResourcesDir, "plugins/x86-unicode")}`,
  114. `/DZCODE_INSTALLER_NSH=${installerNshPath}`,
  115. `/DZCODE_INSTALLER_PROCESS_HELPER=${resolve(desktopDir, `bundled-tools/win32-${process.arch}/runtime-host/zcode-installer-process-helper.exe`)}`,
  116. `/DFIXTURE_EXE=${fixturePath}`,
  117. `/DOUTPUT_FILE=${failureOutputPath}`,
  118. `/DZCODE_UNINSTALLER_LOG_PATH=${failureLogPath}`,
  119. "/DFAIL_DELETE",
  120. fixturePath,
  121. ];
  122. execFileSync(makensisPath, failureCompileArgs, {
  123. cwd: workspaceDir,
  124. encoding: "utf-8",
  125. stdio: ["ignore", "pipe", "pipe"],
  126. });
  127. let failureExitCode = 0;
  128. try {
  129. execFileSync(failureOutputPath, ["/S", `/D=${failureInstallDir}`], {
  130. encoding: "utf-8",
  131. });
  132. } catch (error) {
  133. failureExitCode = error.status ?? 0;
  134. }
  135. if (failureExitCode === 0) {
  136. throw new Error("manifest cleanup failure unexpectedly returned success");
  137. }
  138. const failureLog = readFileSync(failureLogPath, "utf8");
  139. for (const marker of [
  140. "cleanup-started",
  141. "cleanup-failed reason=delete-failed path=owned-by-zcode.txt win32-error=",
  142. ]) {
  143. if (!failureLog.includes(marker)) {
  144. throw new Error(`uninstaller log is missing ${marker}: ${failureLog}`);
  145. }
  146. }
  147. if (!/\[pid=[1-9]\d*\]/.test(failureLog)) {
  148. throw new Error(`uninstaller log is missing a positive PID: ${failureLog}`);
  149. }
  150. if (existsSync(join(failureInstallDir, "ZCode.exe"))) {
  151. throw new Error("old cleanup fixture did not reproduce the deleted application");
  152. }
  153. // 真正运行旧清理进程,分别验证完整恢复、可选备份失败和成功后的新载荷写入。
  154. for (const scenario of [
  155. "recovery",
  156. "backup-failure",
  157. "backup-and-uninstall-failure",
  158. "restore-failure",
  159. "backup-delete-failure",
  160. "backup-delete-success",
  161. "self-manifest-recovery",
  162. "self-manifest-success",
  163. ]) {
  164. const installSucceeds = [
  165. "backup-failure",
  166. "backup-delete-success",
  167. "self-manifest-success",
  168. ].includes(scenario);
  169. const backupFails =
  170. scenario === "backup-failure" || scenario === "backup-and-uninstall-failure";
  171. const deleteFails =
  172. scenario === "backup-delete-failure" || scenario === "backup-delete-success";
  173. const recoveryOutputPath = join(tempRoot, `${scenario}.exe`);
  174. const recoveryInstallDir = join(tempRoot, scenario);
  175. const installerLogPath = join(tempRoot, `${scenario}-installer.log`);
  176. const recoveryArgs = failureCompileArgs.filter(
  177. (arg) =>
  178. arg !== "/DBUILD_UNINSTALLER" &&
  179. arg !== "/DFAIL_DELETE" &&
  180. arg !== "/WX" &&
  181. !arg.startsWith("/DOUTPUT_FILE=") &&
  182. arg !== fixturePath,
  183. );
  184. recoveryArgs.push(
  185. `/DOUTPUT_FILE=${recoveryOutputPath}`,
  186. "/DRECOVERY_TEST",
  187. `/DZCODE_INSTALLER_DEFAULT_LOG_PATH=${installerLogPath}`,
  188. `/DOLD_CLEANUP_EXE=${installSucceeds ? legacySelfUninstaller : failureOutputPath}`,
  189. );
  190. if (scenario.startsWith("self-manifest")) recoveryArgs.push("/DSELF_MANIFEST");
  191. if (backupFails) recoveryArgs.push("/DBACKUP_FAILURE");
  192. if (scenario === "restore-failure") recoveryArgs.push("/DRESTORE_FAILURE");
  193. if (deleteFails) recoveryArgs.push("/DBACKUP_DELETE_FAILURE");
  194. recoveryArgs.push(fixturePath);
  195. execFileSync(makensisPath, recoveryArgs, { cwd: workspaceDir, encoding: "utf8" });
  196. let recoveryExitCode = 0;
  197. try {
  198. execFileSync(recoveryOutputPath, ["/S", `/D=${recoveryInstallDir}`], { encoding: "utf8" });
  199. } catch (error) {
  200. recoveryExitCode = error.status ?? 0;
  201. }
  202. const expectedExitCode = installSucceeds ? 0 : 2;
  203. if (recoveryExitCode !== expectedExitCode)
  204. throw new Error(
  205. `${scenario}: exit code ${recoveryExitCode}, expected ${expectedExitCode}; fixture=${tempRoot}`,
  206. );
  207. const backupDirPath = join(recoveryInstallDir, "backup-dir.txt");
  208. if (!existsSync(backupDirPath)) {
  209. throw new Error(`${scenario}: backup directory marker missing`);
  210. }
  211. const backupDir = readFileSync(backupDirPath, "utf8");
  212. if (backupFails && backupDir !== "") {
  213. throw new Error(`${scenario}: partial backup is still available for recovery`);
  214. }
  215. const shouldRetainBackup = scenario === "restore-failure" || deleteFails;
  216. if ((backupDir !== "" && existsSync(backupDir)) !== shouldRetainBackup) {
  217. throw new Error(`${scenario}: wrong backup retention state`);
  218. }
  219. if (
  220. scenario === "restore-failure" &&
  221. readFileSync(join(backupDir, "ZCode.exe"), "utf8") !== "old application payload"
  222. ) {
  223. throw new Error(`${scenario}: recoverable application backup was lost`);
  224. }
  225. const installerLog = readFileSync(installerLogPath, "utf8");
  226. // 重试耗尽的提示按是否存在完整备份切换;recoverable 标志验证提示分支与文件状态一致。
  227. if (
  228. !installSucceeds &&
  229. !installerLog.includes(
  230. `cleanup-retries-exhausted exit-code=2 recoverable=${backupFails ? "0" : "1"}`,
  231. )
  232. ) {
  233. throw new Error(`${scenario}: retry prompt recoverable flag mismatch`);
  234. }
  235. if (backupFails) {
  236. if (
  237. !installerLog.includes("cleanup-backup-completed failed=1") ||
  238. !installerLog.includes("cleanup-backup-skipped")
  239. ) {
  240. throw new Error(`${scenario}: backup failure was not logged`);
  241. }
  242. if (installerLog.includes("cleanup-restore-completed")) {
  243. throw new Error(`${scenario}: attempted recovery without a complete backup`);
  244. }
  245. }
  246. if (deleteFails && !installerLog.includes(`cleanup-backup-delete-failed path=${backupDir}`)) {
  247. throw new Error(`${scenario}: cleanup failure path was not logged`);
  248. }
  249. const installMarker = join(recoveryInstallDir, "remove-result.txt");
  250. if (existsSync(installMarker) !== installSucceeds) {
  251. throw new Error(`${scenario}: wrong new-payload installation state`);
  252. }
  253. if (installSucceeds) {
  254. if (
  255. !readFileSync(join(recoveryInstallDir, "ZCode.exe")).equals(readFileSync(fixturePath)) ||
  256. readFileSync(installMarker, "utf8") !== "removed"
  257. ) {
  258. throw new Error(`${scenario}: new application payload was not installed after cleanup`);
  259. }
  260. } else if (scenario === "backup-and-uninstall-failure") {
  261. if (existsSync(join(recoveryInstallDir, "ZCode.exe"))) {
  262. throw new Error(`${scenario}: partial backup was incorrectly restored`);
  263. }
  264. } else if (
  265. scenario !== "restore-failure" &&
  266. readFileSync(join(recoveryInstallDir, "ZCode.exe"), "utf8") !== "old application payload"
  267. ) {
  268. throw new Error(`${scenario}: original application bytes were lost`);
  269. }
  270. if (
  271. scenario === "self-manifest-recovery" &&
  272. readFileSync(join(recoveryInstallDir, ".zcode-install-manifest"), "utf8") !==
  273. "ZCode.exe\r\nowned-by-zcode.txt\r\n.zcode-install-manifest\r\n..\\user-data.txt\r\n"
  274. ) {
  275. throw new Error("self-manifest-recovery: original manifest bytes changed");
  276. }
  277. if (readFileSync(join(recoveryInstallDir, "user-data.txt"), "utf8") !== "keep me") {
  278. throw new Error(`${scenario}: recovery changed unrelated data`);
  279. }
  280. }
  281. process.stdout.write("[installer-preserve-files] passed\n");
  282. } finally {
  283. if (process.env.ZCODE_KEEP_INSTALLER_FIXTURE !== "1") {
  284. rmSync(tempRoot, { recursive: true, force: true });
  285. }
  286. }
  287. }