test-installer-preserve-files.mjs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. "/WX",
  35. "/DBUILD_UNINSTALLER",
  36. `/DNSIS_INCLUDE_DIR=${resolve(nsisDir, "Include")}`,
  37. `/DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${resolve(appBuilderLibDir, "templates/nsis/include")}`,
  38. `/DNSIS_PLUGIN_DIR=${resolve(nsisResourcesDir, "plugins/x86-unicode")}`,
  39. `/DZCODE_INSTALLER_NSH=${installerNshPath}`,
  40. // 夹具只校验文件字节,不执行该载荷;避免 32 位 NSIS 将 System32 重定向到 SysWOW64。
  41. `/DFIXTURE_EXE=${fixturePath}`,
  42. `/DOUTPUT_FILE=${uninstallerOutput}`,
  43. fixturePath,
  44. ],
  45. { cwd: workspaceDir, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] },
  46. );
  47. const legacySelfUninstaller = join(tempRoot, "legacy-self-uninstaller.exe");
  48. execFileSync(
  49. makensisPath,
  50. [
  51. "/V2",
  52. "/WX",
  53. `/DOUTPUT_FILE=${legacySelfUninstaller}`,
  54. resolve(desktopDir, "test/fixtures/legacy-self-manifest-uninstaller.nsi"),
  55. ],
  56. { cwd: workspaceDir, encoding: "utf8" },
  57. );
  58. for (const [scenario, omitManifest] of [
  59. ["manifest", false],
  60. ["legacy", true],
  61. ["self-manifest", false],
  62. ]) {
  63. const outputPath = join(tempRoot, `${scenario}.exe`);
  64. const installDir = join(tempRoot, scenario);
  65. const compileArgs = [
  66. "/V2",
  67. `/DNSIS_INCLUDE_DIR=${resolve(nsisDir, "Include")}`,
  68. `/DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${resolve(appBuilderLibDir, "templates/nsis/include")}`,
  69. `/DNSIS_PLUGIN_DIR=${resolve(nsisResourcesDir, "plugins/x86-unicode")}`,
  70. `/DZCODE_INSTALLER_NSH=${installerNshPath}`,
  71. `/DFIXTURE_EXE=${fixturePath}`,
  72. `/DOUTPUT_FILE=${outputPath}`,
  73. fixturePath,
  74. ];
  75. if (omitManifest) compileArgs.splice(-1, 0, "/DOMIT_MANIFEST");
  76. if (scenario === "self-manifest") compileArgs.splice(-1, 0, "/DSELF_MANIFEST");
  77. execFileSync(makensisPath, compileArgs, {
  78. cwd: workspaceDir,
  79. encoding: "utf-8",
  80. stdio: ["ignore", "pipe", "pipe"],
  81. });
  82. execFileSync(outputPath, ["/S", `/D=${installDir}`], { encoding: "utf-8" });
  83. const ownedFileExists = existsSync(join(installDir, "owned-by-zcode.txt"));
  84. if (omitManifest !== ownedFileExists) {
  85. throw new Error(`${scenario}: ownership fallback mismatch`);
  86. }
  87. if (!existsSync(join(installDir, "user-data.txt"))) {
  88. throw new Error(`${scenario}: unrelated file was removed`);
  89. }
  90. if (readFileSync(join(installDir, "ZCode.exe")).length === 0) {
  91. throw new Error(`${scenario}: application payload was not installed`);
  92. }
  93. }
  94. const failureOutputPath = join(tempRoot, "failure.exe");
  95. const failureInstallDir = join(tempRoot, "failure");
  96. const failureLogPath = join(tempRoot, "failure-uninstaller.log");
  97. const failureCompileArgs = [
  98. "/V2",
  99. "/WX",
  100. "/DBUILD_UNINSTALLER",
  101. `/DNSIS_INCLUDE_DIR=${resolve(nsisDir, "Include")}`,
  102. `/DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${resolve(appBuilderLibDir, "templates/nsis/include")}`,
  103. `/DNSIS_PLUGIN_DIR=${resolve(nsisResourcesDir, "plugins/x86-unicode")}`,
  104. `/DZCODE_INSTALLER_NSH=${installerNshPath}`,
  105. `/DFIXTURE_EXE=${fixturePath}`,
  106. `/DOUTPUT_FILE=${failureOutputPath}`,
  107. `/DZCODE_UNINSTALLER_LOG_PATH=${failureLogPath}`,
  108. "/DFAIL_DELETE",
  109. fixturePath,
  110. ];
  111. execFileSync(makensisPath, failureCompileArgs, {
  112. cwd: workspaceDir,
  113. encoding: "utf-8",
  114. stdio: ["ignore", "pipe", "pipe"],
  115. });
  116. let failureExitCode = 0;
  117. try {
  118. execFileSync(failureOutputPath, ["/S", `/D=${failureInstallDir}`], {
  119. encoding: "utf-8",
  120. });
  121. } catch (error) {
  122. failureExitCode = error.status ?? 0;
  123. }
  124. if (failureExitCode === 0) {
  125. throw new Error("manifest cleanup failure unexpectedly returned success");
  126. }
  127. const failureLog = readFileSync(failureLogPath, "utf8");
  128. for (const marker of ["cleanup-started", "cleanup-failed reason=permission-or-disk-space"]) {
  129. if (!failureLog.includes(marker)) {
  130. throw new Error(`uninstaller log is missing ${marker}: ${failureLog}`);
  131. }
  132. }
  133. if (!/\[pid=[1-9]\d*\]/.test(failureLog)) {
  134. throw new Error(`uninstaller log is missing a positive PID: ${failureLog}`);
  135. }
  136. if (existsSync(join(failureInstallDir, "ZCode.exe"))) {
  137. throw new Error("old cleanup fixture did not reproduce the deleted application");
  138. }
  139. // 真正运行旧清理进程:先删主程序,再因独占文件句柄失败;新安装器必须补回主程序。
  140. for (const scenario of [
  141. "recovery",
  142. "backup-failure",
  143. "restore-failure",
  144. "self-manifest-recovery",
  145. "self-manifest-success",
  146. ]) {
  147. const recoveryOutputPath = join(tempRoot, `${scenario}.exe`);
  148. const recoveryInstallDir = join(tempRoot, scenario);
  149. const recoveryArgs = failureCompileArgs.filter(
  150. (arg) =>
  151. arg !== "/DBUILD_UNINSTALLER" &&
  152. arg !== "/DFAIL_DELETE" &&
  153. arg !== "/WX" &&
  154. !arg.startsWith("/DOUTPUT_FILE=") &&
  155. arg !== fixturePath,
  156. );
  157. recoveryArgs.push(
  158. `/DOUTPUT_FILE=${recoveryOutputPath}`,
  159. "/DRECOVERY_TEST",
  160. `/DOLD_CLEANUP_EXE=${scenario === "self-manifest-success" ? legacySelfUninstaller : failureOutputPath}`,
  161. );
  162. if (scenario.startsWith("self-manifest")) recoveryArgs.push("/DSELF_MANIFEST");
  163. if (scenario === "backup-failure") recoveryArgs.push("/DBACKUP_FAILURE");
  164. if (scenario === "restore-failure") recoveryArgs.push("/DRESTORE_FAILURE");
  165. recoveryArgs.push(fixturePath);
  166. execFileSync(makensisPath, recoveryArgs, { cwd: workspaceDir, encoding: "utf8" });
  167. let recoveryExitCode = 0;
  168. try {
  169. execFileSync(recoveryOutputPath, ["/S", `/D=${recoveryInstallDir}`], { encoding: "utf8" });
  170. } catch (error) {
  171. recoveryExitCode = error.status ?? 0;
  172. }
  173. const expectedExitCode = scenario === "self-manifest-success" ? 0 : 2;
  174. if (recoveryExitCode !== expectedExitCode)
  175. throw new Error(`${scenario}: exit code ${recoveryExitCode}`);
  176. if (scenario !== "backup-failure") {
  177. const backupDir = readFileSync(join(recoveryInstallDir, "backup-dir.txt"), "utf8");
  178. if (existsSync(backupDir) !== (scenario === "restore-failure")) {
  179. throw new Error(`${scenario}: wrong backup retention state`);
  180. }
  181. if (
  182. scenario === "restore-failure" &&
  183. !readFileSync(join(backupDir, "ZCode.exe")).equals(readFileSync(fixturePath))
  184. ) {
  185. throw new Error(`${scenario}: recoverable application backup was lost`);
  186. }
  187. }
  188. if (
  189. scenario !== "restore-failure" &&
  190. !readFileSync(join(recoveryInstallDir, "ZCode.exe")).equals(readFileSync(fixturePath))
  191. ) {
  192. throw new Error(`${scenario}: original application bytes were lost`);
  193. }
  194. if (
  195. scenario === "self-manifest-recovery" &&
  196. readFileSync(join(recoveryInstallDir, ".zcode-install-manifest"), "utf8") !==
  197. "ZCode.exe\r\nowned-by-zcode.txt\r\n.zcode-install-manifest\r\n..\\user-data.txt\r\n"
  198. ) {
  199. throw new Error("self-manifest-recovery: original manifest bytes changed");
  200. }
  201. if (readFileSync(join(recoveryInstallDir, "user-data.txt"), "utf8") !== "keep me") {
  202. throw new Error(`${scenario}: recovery changed unrelated data`);
  203. }
  204. }
  205. process.stdout.write("[installer-preserve-files] passed\n");
  206. } finally {
  207. rmSync(tempRoot, { recursive: true, force: true });
  208. }
  209. }