auto-update-install-reentry-smoke.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. import assert from "node:assert/strict";
  2. import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
  3. import { createRequire } from "node:module";
  4. import { resolve } from "node:path";
  5. import { build } from "esbuild";
  6. import { _electron } from "playwright-core";
  7. const preparingDownloadFailure = process.argv.includes("--preparing-download-failure");
  8. const pendingCheck = process.argv.includes("--pending-check");
  9. const nativeInstallError = process.argv.includes("--native-install-error");
  10. const ordinaryQuit = process.argv.includes("--ordinary-quit");
  11. const linuxDeb = process.argv.includes("--linux-deb");
  12. const menuInstall = process.argv.includes("--menu-install");
  13. const sudoProbeAuthorized = process.argv.includes("--sudo-probe-authorized");
  14. const postponeLinuxAuthorization = process.argv.includes("--postpone-linux-authorization");
  15. // 真实 Electron 退出时序回归:替换安装器 IO,不接触用户应用、更新缓存或 ShipIt。
  16. if (process.platform !== "darwin") {
  17. console.log("auto-update install reentry smoke: macOS only (skipped)");
  18. process.exit(0);
  19. }
  20. const desktopDir = resolve(import.meta.dirname, "..");
  21. const repoRoot = resolve(desktopDir, "../..");
  22. const require = createRequire(resolve(desktopDir, "package.json"));
  23. await mkdir(resolve(desktopDir, ".e2e-artifacts"), { recursive: true });
  24. const artifactDir = await mkdtemp(resolve(desktopDir, ".e2e-artifacts/update-install-reentry-"));
  25. await mkdir(resolve(artifactDir, "user-data"));
  26. const entryPath = resolve(artifactDir, "main.cjs");
  27. await build({
  28. stdin: {
  29. resolveDir: desktopDir,
  30. sourcefile: "auto-update-install-reentry-fixture.mjs",
  31. contents: `
  32. import { app, BrowserWindow, dialog, ipcMain } from "electron";
  33. import { PlatformChannels } from "@zcode/shared";
  34. import { initAutoUpdater, downloadAvailableUpdate, getAutoUpdaterState, requestAutoUpdateCheckWithoutWindow } from "./src/main/autoUpdater.ts";
  35. (async () => {
  36. const autoUpdater = globalThis.__smokeUpdater;
  37. const nativeUpdater = autoUpdater.nativeUpdater;
  38. const order = [];
  39. let installCalls = 0;
  40. let prepareCalls = 0;
  41. let nativeInstallCalls = 0;
  42. let relaunchCalls = 0;
  43. const preparingDownloadFailure = ${JSON.stringify(preparingDownloadFailure)};
  44. const pendingCheck = ${JSON.stringify(pendingCheck)};
  45. const nativeInstallError = ${JSON.stringify(nativeInstallError)};
  46. const ordinaryQuit = ${JSON.stringify(ordinaryQuit)};
  47. const linuxDeb = ${JSON.stringify(linuxDeb)};
  48. const menuInstall = ${JSON.stringify(menuInstall)};
  49. const sudoProbeAuthorized = ${JSON.stringify(sudoProbeAuthorized)};
  50. const postponeLinuxAuthorization = ${JSON.stringify(postponeLinuxAuthorization)};
  51. let authorizationPrompts = 0;
  52. if (linuxDeb) {
  53. Object.defineProperty(process, "getuid", { value: () => 1000, configurable: true });
  54. dialog.showMessageBox = async () => {
  55. authorizationPrompts++;
  56. order.push("authorization-prompt");
  57. return { response: postponeLinuxAuthorization && authorizationPrompts === 1 ? 1 : 0 };
  58. };
  59. }
  60. let finishPreparation;
  61. const preparation = new Promise((resolve) => { finishPreparation = resolve; });
  62. app.setPath("userData", ${JSON.stringify(resolve(artifactDir, "user-data"))});
  63. Object.defineProperty(app, "isPackaged", { value: true });
  64. autoUpdater.checkForUpdates = () => pendingCheck ? new Promise(() => {}) : Promise.resolve(null);
  65. app.relaunch = () => { relaunchCalls++; order.push("relaunch"); };
  66. const originalExit = app.exit.bind(app);
  67. app.exit = (code) => {
  68. if (nativeInstallError) {
  69. order.push("recovery-exit");
  70. console.log("UPDATE_INSTALL_RESULT=" + JSON.stringify({ installCalls, prepareCalls, nativeInstallCalls, relaunchCalls, prevented: false, order }));
  71. }
  72. originalExit(code);
  73. };
  74. autoUpdater.squirrelDownloadedUpdate = false;
  75. const originalInstall = autoUpdater.quitAndInstall.bind(autoUpdater);
  76. autoUpdater.quitAndInstall = () => {
  77. installCalls++;
  78. order.push("install-entry");
  79. originalInstall();
  80. };
  81. if (linuxDeb) {
  82. autoUpdater.downloadedUpdateHelper = {
  83. file: "/tmp/zcode smoke/update.deb", downloadedFileInfo: { isAdminRightsRequired: false },
  84. };
  85. autoUpdater.hasCommand = (command) => ["dpkg", "pkexec"].includes(command);
  86. autoUpdater.spawnSyncLog = (command, args) => {
  87. order.push("command:" + command);
  88. if (command !== "pkexec" || args[0] !== "--disable-internal-agent" || !args.join(" ").includes("/bin/bash")) {
  89. throw new Error("expected Linux privilege escalation");
  90. }
  91. if (nativeInstallError) throw new Error("authorization cancelled");
  92. nativeInstallCalls++;
  93. return "";
  94. };
  95. } else {
  96. nativeUpdater.checkForUpdates = () => {
  97. // 根因发生在原生 staging 回调晚于安装入口返回时,不用超时猜测状态。
  98. setImmediate(() => {
  99. if (nativeInstallError) {
  100. order.push("native-error");
  101. nativeUpdater.emit("error", new Error("native staging failed"));
  102. } else {
  103. order.push("native-staged");
  104. nativeUpdater.emit("update-downloaded");
  105. }
  106. });
  107. };
  108. nativeUpdater.quitAndInstall = () => {
  109. if (nativeInstallCalls > 0) return;
  110. nativeInstallCalls++;
  111. order.push("native-install");
  112. setImmediate(() => app.quit());
  113. };
  114. }
  115. await app.whenReady();
  116. await initAutoUpdater({
  117. onBeforeQuitAndInstall: async () => {
  118. prepareCalls++;
  119. order.push("prepare");
  120. if (preparingDownloadFailure) await preparation;
  121. },
  122. });
  123. ipcMain.handle("smoke-background-download-failure", () => {
  124. autoUpdater.downloadUpdate = async () => { throw new Error("background download must not start"); };
  125. autoUpdater.emit("update-available", { version: "99.0.1" });
  126. autoUpdater.emit("update-downloaded", { version: "99.0.1" });
  127. downloadAvailableUpdate("smoke-background");
  128. order.push("background-target-locked");
  129. });
  130. ipcMain.handle("smoke-finish-preparation", () => { finishPreparation(); });
  131. ipcMain.handle("smoke-authorization-prompts", () => authorizationPrompts);
  132. ipcMain.handle("smoke-install-observation", () => ({
  133. state: getAutoUpdaterState(),
  134. prepareCalls,
  135. nativeInstallCalls,
  136. order: [...order],
  137. }));
  138. const triggerInstallMethod = menuInstall ? "send" : "invoke";
  139. const triggerInstallChannel = menuInstall
  140. ? "smoke-menu-install"
  141. : ordinaryQuit
  142. ? "smoke-ordinary-quit"
  143. : PlatformChannels.QuitAndInstallUpdate;
  144. const win = new BrowserWindow({
  145. width: 420, height: 200,
  146. webPreferences: { nodeIntegration: true, contextIsolation: false },
  147. });
  148. await win.loadURL("data:text/html," + encodeURIComponent(
  149. '<button id="install">Restart to update</button><script>' +
  150. 'document.getElementById("install").onclick = () => ' +
  151. 'require("electron").ipcRenderer[' + triggerInstallMethod + '](' + JSON.stringify(triggerInstallChannel) + ');' +
  152. '</script>'
  153. ));
  154. ipcMain.handle("smoke-ordinary-quit", () => { app.quit(); });
  155. ipcMain.on("smoke-menu-install", () => { requestAutoUpdateCheckWithoutWindow("smoke-menu"); });
  156. autoUpdater.emit("update-downloaded", { version: "99.0.0" });
  157. app.on("before-quit", (event) => {
  158. order.push("before-quit");
  159. console.log("UPDATE_INSTALL_RESULT=" + JSON.stringify({
  160. installCalls, prepareCalls, nativeInstallCalls, relaunchCalls,
  161. prevented: event.defaultPrevented, order,
  162. }));
  163. // 旧实现会拦截退出并重入;立即结束隔离夹具,避免无限循环。
  164. if (event.defaultPrevented) app.exit(2);
  165. });
  166. })().catch((error) => { console.error(error); app.exit(1); });
  167. `,
  168. },
  169. outfile: entryPath,
  170. bundle: true,
  171. platform: "node",
  172. format: "cjs",
  173. // 在 macOS 的真实 Electron 中执行 DebUpdater;只替换平台判断和系统命令边界。
  174. // 这验证 Linux 安装器调用顺序,不代表 Linux 实机文件替换验收。
  175. ...(linuxDeb ? { define: { "process.platform": '"linux"' } } : {}),
  176. banner: {
  177. js: `globalThis.__smokeUpdater = ${linuxDeb ? 'new (require("electron-updater").DebUpdater)()' : 'require("electron-updater").autoUpdater'};`,
  178. },
  179. external: ["electron", "electron-updater", "semver"],
  180. alias: { "@zcode/shared": resolve(repoRoot, "packages/shared/src/index.ts") },
  181. plugins: [
  182. {
  183. name: "isolated-sudo-probe",
  184. setup(buildApi) {
  185. buildApi.onResolve({ filter: /^node:child_process$/ }, (args) => {
  186. if (args.importer.endsWith("/src/main/autoUpdater.ts")) {
  187. return { path: "sudo-probe", namespace: "sudo-probe" };
  188. }
  189. });
  190. buildApi.onLoad({ filter: /.*/, namespace: "sudo-probe" }, () => ({
  191. contents: `
  192. export function execFile(_file, _args, _options, callback) {
  193. if (${JSON.stringify(sudoProbeAuthorized)}) {
  194. callback(null, "", "");
  195. return;
  196. }
  197. const error = Object.assign(new Error("sudo probe denied"), { code: 1 });
  198. callback(error, "", "");
  199. }
  200. `,
  201. loader: "js",
  202. }));
  203. },
  204. },
  205. {
  206. name: "isolated-smoke-updater",
  207. setup(buildApi) {
  208. buildApi.onResolve({ filter: /^electron-updater$/ }, (args) => {
  209. if (args.importer.endsWith("/src/main/autoUpdater.ts")) {
  210. return { path: "updater", namespace: "smoke-updater" };
  211. }
  212. });
  213. buildApi.onLoad({ filter: /.*/, namespace: "smoke-updater" }, () => ({
  214. contents:
  215. 'export { CancellationToken } from "electron-updater"; export default { autoUpdater: globalThis.__smokeUpdater };',
  216. resolveDir: desktopDir,
  217. }));
  218. },
  219. },
  220. {
  221. name: "isolated-smoke-logger",
  222. setup(buildApi) {
  223. buildApi.onResolve({ filter: /^\.\/logger\.js$/ }, (args) => {
  224. if (args.importer.endsWith("/src/main/autoUpdater.ts")) {
  225. return { path: "logger", namespace: "smoke" };
  226. }
  227. });
  228. buildApi.onLoad({ filter: /.*/, namespace: "smoke" }, () => ({
  229. contents:
  230. "export const logger = { info: console.log, warn: console.warn, error: console.error };",
  231. }));
  232. },
  233. },
  234. ],
  235. });
  236. const env = { ...process.env };
  237. delete env.ELECTRON_RUN_AS_NODE;
  238. let electronApp;
  239. let output = "";
  240. try {
  241. electronApp = await _electron.launch({
  242. executablePath: require("electron"),
  243. args: [entryPath],
  244. env,
  245. });
  246. const child = electronApp.process();
  247. for (const stream of [child.stdout, child.stderr]) {
  248. stream?.on("data", (chunk) => {
  249. output += chunk.toString();
  250. });
  251. }
  252. const exited = new Promise((resolveExit, rejectExit) => {
  253. child.once("exit", (code, signal) => resolveExit({ code, signal }));
  254. child.once("error", rejectExit);
  255. });
  256. const page = await electronApp.firstWindow();
  257. if (linuxDeb && postponeLinuxAuthorization && !sudoProbeAuthorized) {
  258. await page.locator("#install").click();
  259. const authorizationDeadline = Date.now() + 3_000;
  260. let authorizationPromptCount = 0;
  261. while (authorizationPromptCount < 1 && Date.now() < authorizationDeadline) {
  262. authorizationPromptCount = await page.evaluate(() =>
  263. require("electron").ipcRenderer.invoke("smoke-authorization-prompts"),
  264. );
  265. if (authorizationPromptCount < 1) {
  266. await new Promise((resolve) => setTimeout(resolve, 25));
  267. }
  268. }
  269. assert.equal(authorizationPromptCount, 1, output);
  270. const postponed = await page.evaluate(() =>
  271. require("electron").ipcRenderer.invoke("smoke-install-observation"),
  272. );
  273. assert.equal(postponed.state.kind, "update-downloaded", output);
  274. assert.equal(postponed.prepareCalls, 0, output);
  275. assert.equal(postponed.nativeInstallCalls, 0, output);
  276. assert.deepEqual(postponed.order, ["authorization-prompt"], output);
  277. assert.equal(
  278. await page.evaluate(() =>
  279. require("electron").ipcRenderer.invoke("smoke-authorization-prompts"),
  280. ),
  281. 1,
  282. output,
  283. );
  284. await page.locator("#install").click();
  285. } else {
  286. await page.locator("#install").click();
  287. }
  288. if (preparingDownloadFailure) {
  289. await page.evaluate(() =>
  290. require("electron").ipcRenderer.invoke("smoke-background-download-failure"),
  291. );
  292. await page.locator("#install").click();
  293. await page.evaluate(() => require("electron").ipcRenderer.invoke("smoke-finish-preparation"));
  294. }
  295. const expectedAuthorizationPromptCount =
  296. linuxDeb && !sudoProbeAuthorized ? (postponeLinuxAuthorization ? 2 : 1) : 0;
  297. const expectedAuthorizationOrder = Array.from(
  298. { length: expectedAuthorizationPromptCount },
  299. () => "authorization-prompt",
  300. );
  301. const timeout = AbortSignal.timeout(15_000);
  302. const result = await Promise.race([
  303. exited,
  304. new Promise((_, reject) =>
  305. timeout.addEventListener(
  306. "abort",
  307. () => reject(new Error("Electron did not exit after install")),
  308. { once: true },
  309. ),
  310. ),
  311. ]);
  312. assert.equal(result.code, 0, output);
  313. const reportLine = output.split("\n").find((line) => line.startsWith("UPDATE_INSTALL_RESULT="));
  314. assert.ok(reportLine, output);
  315. const report = JSON.parse(reportLine.slice("UPDATE_INSTALL_RESULT=".length));
  316. assert.deepEqual(report, {
  317. installCalls: ordinaryQuit ? 0 : 1,
  318. prepareCalls: ordinaryQuit ? 0 : 1,
  319. nativeInstallCalls: ordinaryQuit || nativeInstallError ? 0 : 1,
  320. relaunchCalls: ordinaryQuit ? 0 : nativeInstallError || linuxDeb ? 1 : 0,
  321. prevented: false,
  322. order: ordinaryQuit
  323. ? ["before-quit"]
  324. : [
  325. ...expectedAuthorizationOrder,
  326. "prepare",
  327. ...(preparingDownloadFailure ? ["background-target-locked"] : []),
  328. "install-entry",
  329. ...(linuxDeb
  330. ? nativeInstallError
  331. ? ["command:pkexec", "command:pkexec", "relaunch", "recovery-exit"]
  332. : ["command:pkexec", "relaunch", "before-quit"]
  333. : nativeInstallError
  334. ? ["native-error", "relaunch", "recovery-exit"]
  335. : ["native-staged", "native-install", "before-quit"]),
  336. ],
  337. });
  338. await writeFile(
  339. resolve(artifactDir, "result.json"),
  340. JSON.stringify({ ...result, ...report }, null, 2),
  341. );
  342. console.log("auto-update install reentry smoke: PASS", artifactDir);
  343. } finally {
  344. await writeFile(resolve(artifactDir, "electron.log"), output);
  345. await electronApp?.close().catch(() => {});
  346. }