test-installer-nsh-smoke.mjs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. import { execFileSync } from "node:child_process";
  2. import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  3. import { createRequire } from "node:module";
  4. import { tmpdir } from "node:os";
  5. import { dirname, join, resolve } 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-nsh-smoke.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. function normalizeWindowsPath(value) {
  20. return resolve(value).replaceAll("/", "\\").toLowerCase();
  21. }
  22. function readInstallerLog(logPath) {
  23. const content = readFileSync(logPath);
  24. if (content.length >= 2 && content[0] === 0xff && content[1] === 0xfe) {
  25. return content.subarray(2).toString("utf16le");
  26. }
  27. return content.toString("utf8");
  28. }
  29. function assertInstallerLog(logPath, mode, role = "outer") {
  30. if (!existsSync(logPath)) {
  31. throw new Error(`installer log was not created: ${logPath}`);
  32. }
  33. const log = readInstallerLog(logPath);
  34. for (const marker of [
  35. `installer-process-started role=${role}`,
  36. `installer-initialized mode=${mode}`,
  37. "install-started",
  38. "cleanup-started",
  39. "cleanup-completed",
  40. "extract-started",
  41. "extract-completed",
  42. "shortcuts-started",
  43. "shortcuts-completed",
  44. "install-finalization-started",
  45. "install-completed",
  46. ]) {
  47. if (!log.includes(marker)) {
  48. throw new Error(`installer log is missing ${marker}: ${log}`);
  49. }
  50. }
  51. if (!/\[pid=[1-9]\d*\]/.test(log)) {
  52. throw new Error(`installer log is missing a positive PID: ${log}`);
  53. }
  54. }
  55. function readShortcutProperty(shortcutPath, propertyName) {
  56. const propertyExpression = {
  57. arguments: "$shortcut.Arguments",
  58. targetPath: "$shortcut.TargetPath",
  59. }[propertyName];
  60. if (!propertyExpression) {
  61. throw new Error(`Unsupported shortcut property: ${propertyName}`);
  62. }
  63. const command = [
  64. "$shell = New-Object -ComObject WScript.Shell",
  65. "$shortcut = $shell.CreateShortcut($env:ZCODE_SHORTCUT_PATH)",
  66. `[Console]::Out.Write(${propertyExpression})`,
  67. ].join("; ");
  68. return execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
  69. encoding: "utf-8",
  70. env: { ...process.env, ZCODE_SHORTCUT_PATH: shortcutPath },
  71. }).trim();
  72. }
  73. function compileFixture({
  74. makensisPath,
  75. nsisDir,
  76. nsisResourcesDir,
  77. outputPath,
  78. shortcutState,
  79. defaultLogPath,
  80. elevatedLogPath,
  81. forceElevatedInner = false,
  82. buildUninstaller = false,
  83. }) {
  84. const args = [
  85. "/V2",
  86. "/INPUTCHARSET",
  87. "UTF8",
  88. ...(buildUninstaller ? ["/WX", "/DBUILD_UNINSTALLER"] : []),
  89. `/DNSIS_INCLUDE_DIR=${resolve(nsisDir, "Include")}`,
  90. `/DELECTRON_BUILDER_NSIS_INCLUDE_DIR=${resolve(appBuilderLibDir, "templates/nsis/include")}`,
  91. `/DNSIS_PLUGIN_DIR=${resolve(nsisResourcesDir, "plugins/x86-unicode")}`,
  92. `/DZCODE_INSTALLER_NSH=${installerNshPath}`,
  93. `/DZCODE_INSTALLER_PROCESS_HELPER=${resolve(desktopDir, `bundled-tools/win32-${process.arch}/runtime-host/zcode-installer-process-helper.exe`)}`,
  94. `/DFIXTURE_EXE=${process.env.ComSpec ?? "C:\\Windows\\System32\\cmd.exe"}`,
  95. `/DOUTPUT_FILE=${outputPath}`,
  96. `/DDEFAULT_LOG_PATH=${defaultLogPath}`,
  97. `/DELEVATED_LOG_PATH=${elevatedLogPath}`,
  98. ...(forceElevatedInner ? ["/DFORCE_ELEVATED_INNER"] : []),
  99. ...(shortcutState !== "deleted" ? ["/DPRECREATE_SHORTCUTS"] : []),
  100. ...(shortcutState === "stale" ? ["/DSTALE_SHORTCUTS"] : []),
  101. fixturePath,
  102. ];
  103. execFileSync(makensisPath, args, {
  104. cwd: workspaceDir,
  105. encoding: "utf-8",
  106. stdio: ["ignore", "pipe", "pipe"],
  107. });
  108. }
  109. function runFixture(installerPath, installDir, customLogPath) {
  110. const args = ["/S"];
  111. if (customLogPath) args.push(`/LOG=${customLogPath}`);
  112. args.push(`/D=${installDir}`);
  113. execFileSync(installerPath, args, {
  114. encoding: "utf-8",
  115. stdio: ["ignore", "pipe", "pipe"],
  116. });
  117. }
  118. async function main() {
  119. if (process.platform !== "win32") {
  120. process.stdout.write("[installer-nsh-smoke] skipped: Windows only\n");
  121. return;
  122. }
  123. const [nsisDir, nsisResourcesDir] = await Promise.all([
  124. getBinFromUrl("nsis-3.0.4.1", "nsis-3.0.4.1.7z", NSIS_CHECKSUM),
  125. getBinFromUrl("nsis-resources-3.4.1", "nsis-resources-3.4.1.7z", NSIS_RESOURCES_CHECKSUM),
  126. ]);
  127. const makensisPath = resolve(nsisDir, "makensis.exe");
  128. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-installer-nsh-smoke-"));
  129. try {
  130. const uninstallerFixturePath = join(tempRoot, "uninstaller-fixture.exe");
  131. compileFixture({
  132. makensisPath,
  133. nsisDir,
  134. nsisResourcesDir,
  135. outputPath: uninstallerFixturePath,
  136. shortcutState: "deleted",
  137. defaultLogPath: join(tempRoot, "uninstaller-default.log"),
  138. elevatedLogPath: join(tempRoot, "uninstaller-elevated.log"),
  139. buildUninstaller: true,
  140. });
  141. const normalUninstallDir = join(tempRoot, "normal-uninstall");
  142. runFixture(uninstallerFixturePath, normalUninstallDir);
  143. if (existsSync(normalUninstallDir)) {
  144. throw new Error("normal uninstall left the installation directory behind");
  145. }
  146. for (const scenario of ["preserved", "stale", "deleted"]) {
  147. const installerPath = join(tempRoot, `${scenario}-fixture.exe`);
  148. const installDir = join(tempRoot, `${scenario}-install`);
  149. compileFixture({
  150. makensisPath,
  151. nsisDir,
  152. nsisResourcesDir,
  153. outputPath: installerPath,
  154. shortcutState: scenario,
  155. defaultLogPath: join(tempRoot, `${scenario}-default.log`),
  156. elevatedLogPath: join(tempRoot, `${scenario}-elevated.log`),
  157. });
  158. const customLogPath = scenario === "stale" ? join(tempRoot, "custom.log") : undefined;
  159. runFixture(installerPath, installDir, customLogPath);
  160. assertInstallerLog(customLogPath ?? join(tempRoot, `${scenario}-default.log`), "silent");
  161. const appExe = join(installDir, "ZCode.exe");
  162. const startMenuLink = join(installDir, "start-menu.lnk");
  163. const desktopLink = join(installDir, "desktop.lnk");
  164. const launchLink = readFileSync(join(installDir, "launch-link.txt"), "utf-8");
  165. if (normalizeWindowsPath(launchLink) !== normalizeWindowsPath(appExe)) {
  166. throw new Error(`${scenario}: launchLink did not resolve to appExe`);
  167. }
  168. if (scenario !== "deleted") {
  169. const readShortcutTargetResult = readFileSync(
  170. join(installDir, "read-shortcut-target.txt"),
  171. "utf-8",
  172. );
  173. const expectedInitialTarget =
  174. scenario === "preserved" ? appExe : join(installDir, "stale-target.exe");
  175. if (
  176. normalizeWindowsPath(readShortcutTargetResult) !==
  177. normalizeWindowsPath(expectedInitialTarget)
  178. ) {
  179. throw new Error(
  180. `${scenario}: installer could not read shortcut target: ${readShortcutTargetResult}`,
  181. );
  182. }
  183. for (const shortcutPath of [startMenuLink, desktopLink]) {
  184. if (!existsSync(shortcutPath)) {
  185. throw new Error(`${scenario}: expected shortcut was not recreated: ${shortcutPath}`);
  186. }
  187. const target = readShortcutProperty(shortcutPath, "targetPath");
  188. if (normalizeWindowsPath(target) !== normalizeWindowsPath(appExe)) {
  189. throw new Error(`${scenario}: shortcut target mismatch: ${target}`);
  190. }
  191. const shortcutArguments = readShortcutProperty(shortcutPath, "arguments");
  192. const expectedArguments = scenario === "preserved" ? "--preserved" : "";
  193. if (shortcutArguments !== expectedArguments) {
  194. throw new Error(`${scenario}: shortcut arguments mismatch: ${shortcutArguments}`);
  195. }
  196. }
  197. } else if (existsSync(startMenuLink) || existsSync(desktopLink)) {
  198. throw new Error(`${scenario}: a user-deleted shortcut was recreated`);
  199. }
  200. }
  201. const elevatedInstallerPath = join(tempRoot, "elevated-fixture.exe");
  202. const elevatedInstallDir = join(tempRoot, "elevated-install");
  203. const elevatedLogPath = join(tempRoot, "elevated.log");
  204. const attackerLogPath = join(tempRoot, "attacker.log");
  205. writeFileSync(attackerLogPath, "canary", "utf8");
  206. compileFixture({
  207. makensisPath,
  208. nsisDir,
  209. nsisResourcesDir,
  210. outputPath: elevatedInstallerPath,
  211. shortcutState: "deleted",
  212. defaultLogPath: join(tempRoot, "elevated-default.log"),
  213. elevatedLogPath,
  214. forceElevatedInner: true,
  215. });
  216. runFixture(elevatedInstallerPath, elevatedInstallDir, attackerLogPath);
  217. if (readFileSync(attackerLogPath, "utf8") !== "canary") {
  218. throw new Error("elevated installer modified caller-controlled /LOG path");
  219. }
  220. assertInstallerLog(elevatedLogPath, "silent", "elevated-inner");
  221. } finally {
  222. rmSync(tempRoot, { recursive: true, force: true });
  223. }
  224. process.stdout.write("[installer-nsh-smoke] passed\n");
  225. }
  226. await main();