test-installer-nsh-smoke.mjs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. `/DFIXTURE_EXE=${process.env.ComSpec ?? "C:\\Windows\\System32\\cmd.exe"}`,
  94. `/DOUTPUT_FILE=${outputPath}`,
  95. `/DDEFAULT_LOG_PATH=${defaultLogPath}`,
  96. `/DELEVATED_LOG_PATH=${elevatedLogPath}`,
  97. ...(forceElevatedInner ? ["/DFORCE_ELEVATED_INNER"] : []),
  98. ...(shortcutState !== "deleted" ? ["/DPRECREATE_SHORTCUTS"] : []),
  99. ...(shortcutState === "stale" ? ["/DSTALE_SHORTCUTS"] : []),
  100. fixturePath,
  101. ];
  102. execFileSync(makensisPath, args, {
  103. cwd: workspaceDir,
  104. encoding: "utf-8",
  105. stdio: ["ignore", "pipe", "pipe"],
  106. });
  107. }
  108. function runFixture(installerPath, installDir, customLogPath) {
  109. const args = ["/S"];
  110. if (customLogPath) args.push(`/LOG=${customLogPath}`);
  111. args.push(`/D=${installDir}`);
  112. execFileSync(installerPath, args, {
  113. encoding: "utf-8",
  114. stdio: ["ignore", "pipe", "pipe"],
  115. });
  116. }
  117. async function main() {
  118. if (process.platform !== "win32") {
  119. process.stdout.write("[installer-nsh-smoke] skipped: Windows only\n");
  120. return;
  121. }
  122. const [nsisDir, nsisResourcesDir] = await Promise.all([
  123. getBinFromUrl("nsis-3.0.4.1", "nsis-3.0.4.1.7z", NSIS_CHECKSUM),
  124. getBinFromUrl("nsis-resources-3.4.1", "nsis-resources-3.4.1.7z", NSIS_RESOURCES_CHECKSUM),
  125. ]);
  126. const makensisPath = resolve(nsisDir, "makensis.exe");
  127. const tempRoot = mkdtempSync(join(tmpdir(), "zcode-installer-nsh-smoke-"));
  128. try {
  129. const uninstallerFixturePath = join(tempRoot, "uninstaller-fixture.exe");
  130. compileFixture({
  131. makensisPath,
  132. nsisDir,
  133. nsisResourcesDir,
  134. outputPath: uninstallerFixturePath,
  135. shortcutState: "deleted",
  136. defaultLogPath: join(tempRoot, "uninstaller-default.log"),
  137. elevatedLogPath: join(tempRoot, "uninstaller-elevated.log"),
  138. buildUninstaller: true,
  139. });
  140. const normalUninstallDir = join(tempRoot, "normal-uninstall");
  141. runFixture(uninstallerFixturePath, normalUninstallDir);
  142. if (existsSync(normalUninstallDir)) {
  143. throw new Error("normal uninstall left the installation directory behind");
  144. }
  145. for (const scenario of ["preserved", "stale", "deleted"]) {
  146. const installerPath = join(tempRoot, `${scenario}-fixture.exe`);
  147. const installDir = join(tempRoot, `${scenario}-install`);
  148. compileFixture({
  149. makensisPath,
  150. nsisDir,
  151. nsisResourcesDir,
  152. outputPath: installerPath,
  153. shortcutState: scenario,
  154. defaultLogPath: join(tempRoot, `${scenario}-default.log`),
  155. elevatedLogPath: join(tempRoot, `${scenario}-elevated.log`),
  156. });
  157. const customLogPath = scenario === "stale" ? join(tempRoot, "custom.log") : undefined;
  158. runFixture(installerPath, installDir, customLogPath);
  159. assertInstallerLog(customLogPath ?? join(tempRoot, `${scenario}-default.log`), "silent");
  160. const appExe = join(installDir, "ZCode.exe");
  161. const startMenuLink = join(installDir, "start-menu.lnk");
  162. const desktopLink = join(installDir, "desktop.lnk");
  163. const launchLink = readFileSync(join(installDir, "launch-link.txt"), "utf-8");
  164. if (normalizeWindowsPath(launchLink) !== normalizeWindowsPath(appExe)) {
  165. throw new Error(`${scenario}: launchLink did not resolve to appExe`);
  166. }
  167. if (scenario !== "deleted") {
  168. const readShortcutTargetResult = readFileSync(
  169. join(installDir, "read-shortcut-target.txt"),
  170. "utf-8",
  171. );
  172. const expectedInitialTarget =
  173. scenario === "preserved" ? appExe : join(installDir, "stale-target.exe");
  174. if (
  175. normalizeWindowsPath(readShortcutTargetResult) !==
  176. normalizeWindowsPath(expectedInitialTarget)
  177. ) {
  178. throw new Error(
  179. `${scenario}: installer could not read shortcut target: ${readShortcutTargetResult}`,
  180. );
  181. }
  182. for (const shortcutPath of [startMenuLink, desktopLink]) {
  183. if (!existsSync(shortcutPath)) {
  184. throw new Error(`${scenario}: expected shortcut was not recreated: ${shortcutPath}`);
  185. }
  186. const target = readShortcutProperty(shortcutPath, "targetPath");
  187. if (normalizeWindowsPath(target) !== normalizeWindowsPath(appExe)) {
  188. throw new Error(`${scenario}: shortcut target mismatch: ${target}`);
  189. }
  190. const shortcutArguments = readShortcutProperty(shortcutPath, "arguments");
  191. const expectedArguments = scenario === "preserved" ? "--preserved" : "";
  192. if (shortcutArguments !== expectedArguments) {
  193. throw new Error(`${scenario}: shortcut arguments mismatch: ${shortcutArguments}`);
  194. }
  195. }
  196. } else if (existsSync(startMenuLink) || existsSync(desktopLink)) {
  197. throw new Error(`${scenario}: a user-deleted shortcut was recreated`);
  198. }
  199. }
  200. const elevatedInstallerPath = join(tempRoot, "elevated-fixture.exe");
  201. const elevatedInstallDir = join(tempRoot, "elevated-install");
  202. const elevatedLogPath = join(tempRoot, "elevated.log");
  203. const attackerLogPath = join(tempRoot, "attacker.log");
  204. writeFileSync(attackerLogPath, "canary", "utf8");
  205. compileFixture({
  206. makensisPath,
  207. nsisDir,
  208. nsisResourcesDir,
  209. outputPath: elevatedInstallerPath,
  210. shortcutState: "deleted",
  211. defaultLogPath: join(tempRoot, "elevated-default.log"),
  212. elevatedLogPath,
  213. forceElevatedInner: true,
  214. });
  215. runFixture(elevatedInstallerPath, elevatedInstallDir, attackerLogPath);
  216. if (readFileSync(attackerLogPath, "utf8") !== "canary") {
  217. throw new Error("elevated installer modified caller-controlled /LOG path");
  218. }
  219. assertInstallerLog(elevatedLogPath, "silent", "elevated-inner");
  220. } finally {
  221. rmSync(tempRoot, { recursive: true, force: true });
  222. }
  223. process.stdout.write("[installer-nsh-smoke] passed\n");
  224. }
  225. await main();