Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(updater): retain the app when Windows elevation is declined
EtienneLescota2d4489d8974
diff --git a/electron/auto-updater.test.ts b/electron/auto-updater.test.tsindex 6dfa89e4c..d6059c405 100644--- a/electron/auto-updater.test.ts+++ b/electron/auto-updater.test.ts@@ -24,10 +24,12 @@ const mocks = vi.hoisted(() => ({quitAndInstall: vi.fn(),},app: { isPackaged: true, getVersion: vi.fn(() => "1.9.2") },+ installWindowsUpdate: vi.fn(),}));vi.mock("electron", () => ({ app: mocks.app }));vi.mock("electron-updater", () => ({ autoUpdater: mocks.autoUpdater }));+vi.mock("./windows-update", () => ({ installWindowsUpdate: mocks.installWindowsUpdate }));// `reg query` finds no install, so the handover below is the same on every platform.vi.mock("node:child_process", () => ({ spawnSync: vi.fn(() => ({ status: 1 })) }));@@ -84,6 +86,7 @@ describe("self-update flow", () => {mocks.autoUpdater.checkForUpdates.mockReset();mocks.autoUpdater.downloadUpdate.mockReset();mocks.autoUpdater.quitAndInstall.mockReset();+ mocks.installWindowsUpdate.mockReset();});it("never touches the updater on a channel a package manager owns", async () => {@@ -155,11 +158,20 @@ describe("self-update flow", () => {expect(result).toMatchObject({ error: { message: "connection reset" } });});- // isSilent=true so Windows shows only UAC, not the NSIS wizard (#1437). isForceRunAfter=true- // so the app comes back.- it("hands over to the installer silently and relaunches", async () => {- await installSelfUpdate();+ // Other platforms retain electron-updater's own quit/relaunch handoff.+ it("retains quitAndInstall on macOS and Linux", async () => {+ const platform = Object.getOwnPropertyDescriptor(process, "platform");+ try {+ for (const value of ["darwin", "linux"]) {+ Object.defineProperty(process, "platform", { value });+ await installSelfUpdate();+ }+ } finally {+ if (platform) Object.defineProperty(process, "platform", platform);+ }+ expect(mocks.autoUpdater.quitAndInstall).toHaveBeenCalledTimes(2);expect(mocks.autoUpdater.quitAndInstall).toHaveBeenCalledWith(true, true);+ expect(mocks.installWindowsUpdate).not.toHaveBeenCalled();});it("hands over to the wizard on Windows when both installs answer", async () => {@@ -173,6 +185,69 @@ describe("self-update flow", () => {vi.mocked(spawnSync).mockReturnValue({ status: 1 } as ReturnType<typeof spawnSync>);}expect(mocks.autoUpdater.quitAndInstall).toHaveBeenCalledWith(false, true);+ expect(mocks.installWindowsUpdate).not.toHaveBeenCalled();+ });++ it("waits for the Windows installer without quitting before the UAC decision", async () => {+ const platform = Object.getOwnPropertyDescriptor(process, "platform");+ let finish: (() => void) | undefined;+ mocks.installWindowsUpdate.mockImplementation(async (download: () => Promise<string[]>) => {+ await download();+ await new Promise<void>((resolve) => {+ finish = resolve;+ });+ });+ mocks.autoUpdater.downloadUpdate.mockResolvedValue(["verified-installer.exe"]);+ vi.mocked(spawnSync)+ .mockReturnValueOnce({ status: 0 } as ReturnType<typeof spawnSync>)+ .mockReturnValueOnce({ status: 1 } as ReturnType<typeof spawnSync>)+ .mockReturnValue({ status: 0 } as ReturnType<typeof spawnSync>);+ Object.defineProperty(process, "platform", { value: "win32" });+ try {+ let settled = false;+ const install = installSelfUpdate().then(() => {+ settled = true;+ });+ await vi.waitFor(() => expect(mocks.autoUpdater.downloadUpdate).toHaveBeenCalledOnce());+ expect(settled).toBe(false);+ expect(mocks.installWindowsUpdate).toHaveBeenCalledWith(expect.any(Function));+ expect(mocks.autoUpdater.quitAndInstall).not.toHaveBeenCalled();+ finish?.();+ await install;+ } finally {+ finish?.();+ if (platform) Object.defineProperty(process, "platform", platform);+ vi.mocked(spawnSync).mockReturnValue({ status: 1 } as ReturnType<typeof spawnSync>);+ }+ });++ it("does not request elevation for a per-user Windows update", async () => {+ const platform = Object.getOwnPropertyDescriptor(process, "platform");+ Object.defineProperty(process, "platform", { value: "win32" });+ try {+ await installSelfUpdate();+ } finally {+ if (platform) Object.defineProperty(process, "platform", platform);+ }+ expect(mocks.autoUpdater.quitAndInstall).toHaveBeenCalledWith(true, true);+ expect(mocks.installWindowsUpdate).not.toHaveBeenCalled();+ });++ it("does not force elevation when the machine install cannot be confirmed", async () => {+ const platform = Object.getOwnPropertyDescriptor(process, "platform");+ Object.defineProperty(process, "platform", { value: "win32" });+ vi.mocked(spawnSync)+ .mockReturnValueOnce({ status: null } as ReturnType<typeof spawnSync>)+ .mockReturnValueOnce({ status: 1 } as ReturnType<typeof spawnSync>)+ .mockReturnValue({ status: null } as ReturnType<typeof spawnSync>);+ try {+ await installSelfUpdate();+ } finally {+ if (platform) Object.defineProperty(process, "platform", platform);+ vi.mocked(spawnSync).mockReturnValue({ status: 1 } as ReturnType<typeof spawnSync>);+ }+ expect(mocks.autoUpdater.quitAndInstall).toHaveBeenCalledWith(true, true);+ expect(mocks.installWindowsUpdate).not.toHaveBeenCalled();});});diff --git a/electron/auto-updater.ts b/electron/auto-updater.tsindex 41c17584a..6b26e5a51 100644--- a/electron/auto-updater.ts+++ b/electron/auto-updater.ts@@ -87,12 +87,16 @@ export async function downloadSelfUpdate(): Promise<UpdateOutcome> {* under HKLM per machine and HKCU per user. auto-updater.test.ts pins it to the appId. */export const NSIS_INSTALL_KEY = "Software\\5b412b41-8d8b-5faf-b557-de4fe681e5fc";-function hasNsisInstall(hive: "HKLM" | "HKCU"): boolean {+function nsisInstallStatus(hive: "HKLM" | "HKCU"): number | null {const key = `${hive}\\${NSIS_INSTALL_KEY}`;const args = ["query", key, "/v", "InstallLocation", "/reg:64"];+ return spawnSync("reg", args, { windowsHide: true }).status;+}++function hasNsisInstall(hive: "HKLM" | "HKCU"): boolean {// Exit 1 is reg's "key not found". Anything else, reg itself failing to run included, counts// as present, so a doubt keeps the wizard rather than risking the wrong copy.- return spawnSync("reg", args, { windowsHide: true }).status !== 1;+ return nsisInstallStatus(hive) !== 1;}/** Whether the installer can run with /S. Without it the assisted NSIS installer shows its whole@@ -107,9 +111,15 @@ export function installsSilently(return platform !== "win32" || !(hasInstall("HKLM") && hasInstall("HKCU"));}-/** Quit and hand over to the installer. Callers MUST have checked `blockedFromInstalling`. */+/** Hand over to the installer. Callers MUST have checked `blockedFromInstalling`. */export async function installSelfUpdate(): Promise<void> {const autoUpdater = await getUpdater();+ const silent = installsSilently();+ if (process.platform === "win32" && silent && nsisInstallStatus("HKLM") === 0) {+ const { installWindowsUpdate } = await import("./windows-update");+ await installWindowsUpdate(() => autoUpdater.downloadUpdate());+ return;+ }// isForceRunAfter=true so the app comes back up.- autoUpdater.quitAndInstall(installsSilently(), true);+ autoUpdater.quitAndInstall(silent, true);}diff --git a/electron/windows-update.test.ts b/electron/windows-update.test.tsnew file mode 100644index 000000000..465a7c07d--- /dev/null+++ b/electron/windows-update.test.ts@@ -0,0 +1,114 @@+import { type ChildProcess, spawn } from "node:child_process";+import { EventEmitter } from "node:events";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { installWindowsUpdate } from "./windows-update";++const mocks = vi.hoisted(() => ({+ quit: vi.fn(),+ window: {+ isEnabled: vi.fn(() => true),+ setEnabled: vi.fn(),+ isDestroyed: vi.fn(() => false),+ },+}));+vi.mock("electron", () => ({+ app: { quit: mocks.quit },+ BrowserWindow: { getAllWindows: () => [mocks.window] },+}));+vi.mock("node:child_process", () => ({ spawn: vi.fn() }));++describe("installWindowsUpdate", () => {+ let child: EventEmitter & { unref: ReturnType<typeof vi.fn> };+ let download: ReturnType<typeof vi.fn<() => Promise<string[]>>>;+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.window.isEnabled.mockReturnValue(true);+ mocks.window.isDestroyed.mockReturnValue(false);+ child = Object.assign(new EventEmitter(), { unref: vi.fn() });+ vi.mocked(spawn).mockReturnValue(child as unknown as ChildProcess);+ download = vi.fn(async () => ["C:\\update\\installer.exe"]);+ });++ it("retains the app and controls after No, and permits retry", async () => {+ const install = installWindowsUpdate(download);+ await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce());+ expect(mocks.quit).not.toHaveBeenCalled();+ expect(mocks.window.setEnabled.mock.calls).toEqual([[false]]);+ expect(child.unref).toHaveBeenCalledOnce();+ child.emit("exit", 1223);+ await install;+ expect(mocks.quit).not.toHaveBeenCalled();+ expect(mocks.window.setEnabled.mock.calls).toEqual([[false], [true]]);+ const retry = installWindowsUpdate(download);+ await vi.waitFor(() => expect(spawn).toHaveBeenCalledTimes(2));+ child.emit("exit", 1223);+ await retry;+ });++ it("quits normally only after elevation succeeds, with controls disabled until quit", async () => {+ const install = installWindowsUpdate(download);+ await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce());+ expect(mocks.quit).not.toHaveBeenCalled();+ child.emit("exit", 0);+ await install;+ expect(mocks.quit).toHaveBeenCalledOnce();+ expect(mocks.window.setEnabled.mock.calls).toEqual([[false]]);+ });++ it("passes the verified installer as a literal without shell interpolation", async () => {+ download.mockResolvedValue(["C:\\update\\it's $a`b.exe"]);+ const install = installWindowsUpdate(download);+ await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce());+ const [executable, args, options] = vi.mocked(spawn).mock.calls[0];+ expect(executable).toMatch(/powershell\.exe$/);+ expect(args).toEqual([+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-EncodedCommand",+ expect.any(String),+ ]);+ const script = Buffer.from((args as string[])[4], "base64").toString("utf16le");+ expect(script).toContain("-FilePath 'C:\\update\\it''s $a`b.exe'");+ expect(script).toContain("@('--updated', '/S', '--force-run') -Verb RunAs");+ expect(script).toContain("NativeErrorCode -eq 1223");+ expect(options).toEqual({ detached: true, stdio: "ignore", windowsHide: true });+ child.emit("exit", 1223);+ await install;+ });++ it("restores an already disabled window after a spawn error", async () => {+ mocks.window.isEnabled.mockReturnValue(false);+ const install = installWindowsUpdate(download);+ const rejection = expect(install).rejects.toThrow("spawn failed");+ await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce());+ child.emit("error", new Error("spawn failed"));+ await rejection;+ expect(mocks.window.setEnabled.mock.calls).toEqual([[false], [false]]);+ expect(mocks.quit).not.toHaveBeenCalled();+ });++ it("restores the app if verifying the cached download fails", async () => {+ download.mockRejectedValue(new Error("checksum mismatch"));+ await expect(installWindowsUpdate(download)).rejects.toThrow("checksum mismatch");+ expect(spawn).not.toHaveBeenCalled();+ expect(mocks.window.setEnabled.mock.calls).toEqual([[false], [true]]);+ });++ it("refuses to launch without a verified installer", async () => {+ download.mockResolvedValue([]);+ await expect(installWindowsUpdate(download)).rejects.toThrow("No downloaded");+ expect(spawn).not.toHaveBeenCalled();+ });++ it("reports failure without quitting or touching a closed window", async () => {+ const install = installWindowsUpdate(download);+ const rejection = expect(install).rejects.toThrow("failed (1)");+ await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce());+ mocks.window.isDestroyed.mockReturnValue(true);+ child.emit("exit", 1);+ await rejection;+ expect(mocks.window.setEnabled.mock.calls).toEqual([[false]]);+ expect(mocks.quit).not.toHaveBeenCalled();+ });+});diff --git a/electron/windows-update.ts b/electron/windows-update.tsnew file mode 100644index 000000000..6f6603561--- /dev/null+++ b/electron/windows-update.ts@@ -0,0 +1,71 @@+import { spawn } from "node:child_process";+import path from "node:path";+import { app, BrowserWindow } from "electron";++/** Elevate the verified per-machine installer before quitting (#1461). Start-Process+ * returns after ShellExecute's UAC decision, without waiting for the installation.+ * The prompt names the installer itself; no elevated shell or probe is launched. */+export async function installWindowsUpdate(+ downloadInstaller: () => Promise<string[]>,+): Promise<void> {+ const windows = BrowserWindow.getAllWindows().map((window) => ({+ window,+ enabled: window.isEnabled(),+ }));+ let handedOver = false;+ try {+ // Prevent a new take while elevation is pending, including the gap after accepting it.+ for (const { window } of windows) window.setEnabled(false);+ // The public API reuses and verifies the cached installer.+ const [installerPath] = await downloadInstaller();+ if (!installerPath) throw new Error("No downloaded Windows update installer");+ const quotedPath = `'${installerPath.replace(/'/g, "''")}'`;+ const script = `+$ErrorActionPreference = 'Stop'+try {+ Start-Process -FilePath ${quotedPath} -ArgumentList @('--updated', '/S', '--force-run') -Verb RunAs -WindowStyle Hidden -PassThru | Out-Null+ exit 0+} catch {+ $errorCause = $_.Exception+ while ($errorCause -and $errorCause -isnot [System.ComponentModel.Win32Exception]) {+ $errorCause = $errorCause.InnerException+ }+ if ($errorCause -and $errorCause.NativeErrorCode -eq 1223) { exit 1223 }+ exit 1+}`;+ const powershell = path.join(+ process.env.SystemRoot ?? "C:\\Windows",+ "System32",+ "WindowsPowerShell",+ "v1.0",+ "powershell.exe",+ );+ const exitCode = await new Promise<number | null>((resolve, reject) => {+ const child = spawn(+ powershell,+ [+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-EncodedCommand",+ Buffer.from(script, "utf16le").toString("base64"),+ ],+ { detached: true, stdio: "ignore", windowsHide: true },+ );+ child.once("error", reject);+ child.once("exit", resolve);+ child.unref();+ });+ if (exitCode === 1223) return; // User declined: retain the app and ready update badge.+ if (exitCode !== 0) throw new Error(`Windows update elevation failed (${exitCode})`);+ // Preserve normal before-quit cleanup; NSIS is already elevated and waiting for files.+ app.quit();+ handedOver = true;+ } finally {+ if (!handedOver) {+ for (const { window, enabled } of windows) {+ if (!window.isDestroyed()) window.setEnabled(enabled);+ }+ }+ }+}