Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(desktop): refresh pending Windows update targets (#776)

tianma-iff2a4fa3bb3b1
diff --git a/apps/desktop/src/main/desktop-update-flow.test.mjs b/apps/desktop/src/main/desktop-update-flow.test.mjs
index 3f3baa06..acc94758 100644
--- a/apps/desktop/src/main/desktop-update-flow.test.mjs
+++ b/apps/desktop/src/main/desktop-update-flow.test.mjs
@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
import { describe, expect, test } from "bun:test";
const mainSource = readFileSync(new URL("./index.mjs", import.meta.url), "utf8");
+const windowsUpdateSource = readFileSync(new URL("./windows-update-controller.mjs", import.meta.url), "utf8");
const preloadSource = readFileSync(new URL("../preload/index.cjs", import.meta.url), "utf8");
const noticeSource = readFileSync(new URL("../../../web/src/components/DesktopUpdateNotice.tsx", import.meta.url), "utf8");
const systemInfoSource = readFileSync(new URL("../../../web/src/components/settings/SystemInfoPanel.tsx", import.meta.url), "utf8");
@@ -18,19 +19,20 @@ describe("desktop update flow", () => {
});
test("downloads updates in the background and relaunches after installation", () => {
- expect(mainSource).toContain('autoUpdater.autoDownload = process.platform !== "win32"');
+ expect(mainSource).toContain("autoUpdater.autoDownload = true");
+ expect(windowsUpdateSource).toContain("void download(reason)");
expect(mainSource).toContain("autoUpdater.autoRunAppAfterInstall = true");
expect(mainSource).toContain('autoUpdater.quitAndInstall(process.platform === "win32", true)');
expect(mainSource).toContain("result?.downloadPromise");
- expect(mainSource).toContain("downloadTrustedDesktopUpdate(reason)");
+ expect(mainSource).toContain("windowsUpdateController.download(reason)");
});
- test("fails closed around unsigned Windows automatic updates", () => {
- expect(mainSource).toContain("fetchTrustedWindowsUpdate({");
- expect(mainSource).toContain("verifyDownloadedWindowsUpdate({");
- expect(mainSource).toContain('autoUpdater.autoInstallOnAppQuit = process.platform !== "win32"');
- expect(mainSource).toContain("windowsDownloadedUpdateVerified = true");
- expect(mainSource).toContain('writeDiagnostic("update.windows-package-blocked"');
+ test("routes Windows through the serialized, signed update controller", () => {
+ expect(mainSource).toContain('if (process.platform === "win32") {\n windowsUpdateController = createWindowsUpdateController({');
+ expect(mainSource).toContain("fetchTrustedWindowsUpdate({ ...options, fetchImpl: net.fetch })");
+ expect(mainSource).toContain("verifyWindowsPackage: verifyDownloadedWindowsUpdate");
+ expect(mainSource).toContain("windowsUpdateController.check(reason)");
+ expect(mainSource).toContain("windowsUpdateController.install(expectedVersion)");
expect(mainSource).toContain('downloadTrustedDesktopUpdate("manual-download")');
});
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index c5e2eb94..fbf719bf 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -60,6 +60,7 @@ import {
verifyDownloadedWindowsUpdate,
} from "./windows-update-trust.mjs";
import electronUpdater from "electron-updater";
+import { createWindowsUpdateController } from "./windows-update-controller.mjs";
import { createUpdateDiagnostic } from "./update-diagnostics.mjs";
import { createUpdateNetworkDiagnostics } from "./update-network-diagnostics.mjs";
import { normalizeUpdateProgress } from "./update-progress.mjs";
@@ -156,12 +157,11 @@ let updateError = null;
let updateProgress = null;
let updateCheckInFlight = null;
let updateDownloadInFlight = null;
+let windowsUpdateController = null;
let updateCheckTimer = null;
let lastUpdateCheckAt = 0;
let downloadedUpdateVersion = null;
let promptedUpdateVersion = null;
-let trustedWindowsUpdate = null;
-let windowsDownloadedUpdateVerified = false;
let sidecarScopeKey = "anonymous";
let activeAccountId = null;
let shutdownCleanupStarted = false;
@@ -1249,11 +1249,9 @@ const publishDesktopUpdateStatus = () => {
mainWindow.webContents.send("desktop:update-status-changed", desktopUpdateStatus());
};
-const installDownloadedUpdate = () => {
- if (
- updateState !== "downloaded" ||
- (process.platform === "win32" && !windowsDownloadedUpdateVerified)
- ) return { started: false };
+const installDownloadedUpdate = (expectedVersion) => {
+ if (windowsUpdateController) return windowsUpdateController.install(expectedVersion);
+ if (updateState !== "downloaded") return { started: false };
// The normal window close handler hides the app. Mark this as a real quit
// before electron-updater closes windows so installation can proceed.
isQuitting = true;
@@ -1268,7 +1266,6 @@ const trackDesktopUpdateDownload = (downloadPromise, reason) => {
updateState = "idle";
updateProgress = null;
downloadedUpdateVersion = null;
- windowsDownloadedUpdateVerified = false;
refreshTrayMenu();
recordUpdateError(error, "download");
publishDesktopUpdateStatus();
@@ -1279,10 +1276,8 @@ const trackDesktopUpdateDownload = (downloadPromise, reason) => {
};
const downloadTrustedDesktopUpdate = (reason) => {
+ if (windowsUpdateController) return windowsUpdateController.download(reason);
if (updateDownloadInFlight) return updateDownloadInFlight;
- if (process.platform === "win32" && !trustedWindowsUpdate) {
- return Promise.reject(new Error("Windows update metadata has not passed the signature gate"));
- }
updateNetworkDiagnostics.setStage("download");
return trackDesktopUpdateDownload(autoUpdater.downloadUpdate(), reason);
};
@@ -1304,14 +1299,19 @@ const promptForDownloadedUpdate = async (version) => {
noLink: true,
});
if (result.response === 0) {
- void writeDiagnostic("update.install-confirmed", { version });
- installDownloadedUpdate();
+ if (!windowsUpdateController) void writeDiagnostic("update.install-confirmed", { version });
+ void installDownloadedUpdate(version);
} else {
void writeDiagnostic("update.install-deferred", { version });
}
};
const checkForDesktopUpdate = (reason, { force = false, throwOnError = false } = {}) => {
+ if (windowsUpdateController) {
+ if (!force && Date.now() - lastUpdateCheckAt < updateCheckFocusThrottleMs) return Promise.resolve(null);
+ const result = windowsUpdateController.check(reason);
+ return throwOnError ? result : result.catch(() => null);
+ }
if (!app.isPackaged || process.env.EDGE_EVER_DISABLE_AUTO_UPDATE === "1" || updateState === "downloaded") {
return Promise.resolve(null);
}
@@ -1325,25 +1325,10 @@ const checkForDesktopUpdate = (reason, { force = false, throwOnError = false } =
updateError = null;
updateNetworkDiagnostics.beginCheck();
publishDesktopUpdateStatus();
- let diagnosticStage = "check";
+ const diagnosticStage = "check";
void writeDiagnostic("update.check-started", { reason });
updateCheckInFlight = autoUpdater.checkForUpdates()
.then(async (result) => {
- if (process.platform === "win32" && result?.isUpdateAvailable) {
- diagnosticStage = "verify-windows-metadata";
- updateNetworkDiagnostics.setStage(diagnosticStage);
- trustedWindowsUpdate = await fetchTrustedWindowsUpdate({
- version: result.updateInfo.version,
- updateInfo: result.updateInfo,
- fetchImpl: net.fetch,
- });
- windowsDownloadedUpdateVerified = false;
- void writeDiagnostic("update.windows-manifest-verified", {
- version: trustedWindowsUpdate.version,
- keyId: trustedWindowsUpdate.keyId,
- });
- void downloadTrustedDesktopUpdate(reason);
- }
if (result?.downloadPromise) {
updateNetworkDiagnostics.setStage("download");
trackDesktopUpdateDownload(result.downloadPromise, reason);
@@ -1354,8 +1339,6 @@ const checkForDesktopUpdate = (reason, { force = false, throwOnError = false } =
updateState = "idle";
updateProgress = null;
downloadedUpdateVersion = null;
- trustedWindowsUpdate = null;
- windowsDownloadedUpdateVerified = false;
refreshTrayMenu();
recordUpdateError(error, diagnosticStage);
publishDesktopUpdateStatus();
@@ -1395,96 +1378,104 @@ const configureAutoUpdater = () => {
appImage: process.env.APPIMAGE || null,
});
}
- autoUpdater.autoDownload = process.platform !== "win32";
- autoUpdater.autoInstallOnAppQuit = process.platform !== "win32";
- autoUpdater.autoRunAppAfterInstall = true;
- autoUpdater.on("update-available", (info) => {
- updateState = "available";
- updateProgress = null;
- downloadedUpdateVersion = info?.version || null;
- if (process.platform === "win32") {
- trustedWindowsUpdate = null;
- windowsDownloadedUpdateVerified = false;
- }
- refreshTrayMenu();
- publishDesktopUpdateStatus();
- void writeDiagnostic("update.available", { version: info?.version });
- });
- autoUpdater.on("update-not-available", () => {
- updateState = "idle";
- updateProgress = null;
- downloadedUpdateVersion = null;
- trustedWindowsUpdate = null;
- windowsDownloadedUpdateVerified = false;
- refreshTrayMenu();
- publishDesktopUpdateStatus();
- const diagnosticWritten = writeDiagnostic("update.not-available");
- if (linuxUpdateTestMode) {
- void diagnosticWritten.finally(() => setTimeout(() => app.quit(), 100));
- }
- });
- autoUpdater.on("download-progress", (progress) => {
- updateProgress = normalizeUpdateProgress(progress);
- publishDesktopUpdateStatus();
- void writeDiagnostic("update.download-progress", { percent: progress.percent });
- });
- autoUpdater.on("update-downloaded", (info) => {
- void (async () => {
- if (process.platform === "win32") {
- if (!trustedWindowsUpdate || trustedWindowsUpdate.version !== info?.version) {
- throw new Error("Downloaded Windows update has no matching trusted manifest");
- }
- await verifyDownloadedWindowsUpdate({
- path: info.downloadedFile,
- manifest: trustedWindowsUpdate,
+ if (process.platform === "win32") {
+ windowsUpdateController = createWindowsUpdateController({
+ updater: autoUpdater,
+ fetchWindowsMetadata: (options) => fetchTrustedWindowsUpdate({ ...options, fetchImpl: net.fetch }),
+ verifyWindowsPackage: verifyDownloadedWindowsUpdate,
+ onStatus: (status) => {
+ updateState = status.state;
+ downloadedUpdateVersion = status.version;
+ updateProgress = status.progress ? normalizeUpdateProgress(status.progress) : null;
+ updateError = null;
+ refreshTrayMenu();
+ publishDesktopUpdateStatus();
+ },
+ onError: (error, stage) => {
+ isQuitting = false;
+ recordUpdateError(error, stage);
+ publishDesktopUpdateStatus();
+ },
+ onCheckStarted: (reason) => {
+ lastUpdateCheckAt = Date.now();
+ updateError = null;
+ updateNetworkDiagnostics.beginCheck();
+ publishDesktopUpdateStatus();
+ void writeDiagnostic("update.check-started", { reason });
+ },
+ onStage: (stage) => updateNetworkDiagnostics.setStage(stage),
+ onSettled: () => updateNetworkDiagnostics.stop(),
+ log: (event, details) => { void writeDiagnostic(event, details); },
+ beforeInstall: () => { isQuitting = true; },
+ onDownloaded: (version) => {
+ void promptForDownloadedUpdate(version).catch((error) => {
+ promptedUpdateVersion = null;
+ void writeDiagnostic("update.prompt-failed", { message: error.message });
});
- windowsDownloadedUpdateVerified = true;
- autoUpdater.autoInstallOnAppQuit = true;
- }
- updateState = "downloaded";
+ },
+ });
+ } else {
+ autoUpdater.autoDownload = true;
+ autoUpdater.autoInstallOnAppQuit = true;
+ autoUpdater.autoRunAppAfterInstall = true;
+ autoUpdater.on("update-available", (info) => {
+ updateState = "available";
+ updateProgress = null;
+ downloadedUpdateVersion = info?.version || null;
+ refreshTrayMenu();
+ publishDesktopUpdateStatus();
+ void writeDiagnostic("update.available", { version: info?.version });
+ });
+ autoUpdater.on("update-not-available", () => {
+ updateState = "idle";
updateProgress = null;
- updateError = null;
- downloadedUpdateVersion = info?.version || downloadedUpdateVersion;
+ downloadedUpdateVersion = null;
refreshTrayMenu();
publishDesktopUpdateStatus();
- await writeDiagnostic("update.downloaded", { version: downloadedUpdateVersion });
+ const diagnosticWritten = writeDiagnostic("update.not-available");
if (linuxUpdateTestMode) {
- installDownloadedUpdate();
- return;
+ void diagnosticWritten.finally(() => setTimeout(() => app.quit(), 100));
}
- await promptForDownloadedUpdate(downloadedUpdateVersion).catch((error) => {
- promptedUpdateVersion = null;
- void writeDiagnostic("update.prompt-failed", { message: error.message });
- });
- })().catch(async (error) => {
- if (process.platform !== "win32") {
+ });
+ autoUpdater.on("download-progress", (progress) => {
+ updateProgress = normalizeUpdateProgress(progress);
+ publishDesktopUpdateStatus();
+ void writeDiagnostic("update.download-progress", { percent: progress.percent });
+ });
+ autoUpdater.on("update-downloaded", (info) => {
+ void (async () => {
+ updateState = "downloaded";
+ updateProgress = null;
+ updateError = null;
+ downloadedUpdateVersion = info?.version || downloadedUpdateVersion;
+ refreshTrayMenu();
+ publishDesktopUpdateStatus();
+ await writeDiagnostic("update.downloaded", { version: downloadedUpdateVersion });
+ if (linuxUpdateTestMode) {
+ installDownloadedUpdate();
+ return;
+ }
+ await promptForDownloadedUpdate(downloadedUpdateVersion).catch((error) => {
+ promptedUpdateVersion = null;
+ void writeDiagnostic("update.prompt-failed", { message: error.message });
+ });
+ })().catch(async (error) => {
await writeDiagnostic("update.download-handler-failed", { message: error.message });
- return;
+ });
+ });
+ autoUpdater.on("error", (error) => {
+ isQuitting = false;
+ if (updateState !== "downloaded") {
+ updateState = "idle";
+ updateProgress = null;
+ downloadedUpdateVersion = null;
}
- autoUpdater.autoInstallOnAppQuit = false;
- updateState = "idle";
- updateProgress = null;
- downloadedUpdateVersion = null;
- windowsDownloadedUpdateVerified = false;
refreshTrayMenu();
- recordUpdateError(error, "verify-windows-package");
+ recordUpdateError(error, updateDownloadInFlight ? "download" : "check");
publishDesktopUpdateStatus();
- await writeDiagnostic("update.windows-package-blocked", { message: error.message });
+ void writeDiagnostic("update.error", { message: error.message });
});
- });
- autoUpdater.on("error", (error) => {
- isQuitting = false;
- if (updateState !== "downloaded") {
- updateState = "idle";
- updateProgress = null;
- downloadedUpdateVersion = null;
- windowsDownloadedUpdateVerified = false;
- }
- refreshTrayMenu();
- recordUpdateError(error, updateDownloadInFlight ? "download" : "check");
- publishDesktopUpdateStatus();
- void writeDiagnostic("update.error", { message: error.message });
- });
+ }
void checkForDesktopUpdate("startup", { force: true });
updateCheckTimer = setInterval(() => {
void checkForDesktopUpdate("interval", { force: true });
diff --git a/apps/desktop/src/main/windows-update-controller.mjs b/apps/desktop/src/main/windows-update-controller.mjs
new file mode 100644
index 00000000..03c66f24
--- /dev/null
+++ b/apps/desktop/src/main/windows-update-controller.mjs
@@ -0,0 +1,194 @@
+import { isDeepStrictEqual } from "node:util";
+
+// electron-updater owns one mutable download/install target. Keep checks,
+// downloads and package verification serialized around that target.
+export const createWindowsUpdateController = ({
+ updater, fetchWindowsMetadata, verifyWindowsPackage,
+ onStatus, onError, onDownloaded, beforeInstall,
+ onStage = () => {}, onCheckStarted = () => {}, onSettled = () => {},
+ log = () => {},
+}) => {
+ let status = { state: "idle", version: null, progress: null };
+ let target = null;
+ let ready = null;
+ let checkInFlight = null;
+ let downloadInFlight = null;
+ let verificationInFlight = null;
+ let installInFlight = null;
+ let installing = false;
+ const publish = (next) => { status = { ...status, ...next }; onStatus({ ...status }); };
+ const packageMatches = (candidate) => Boolean(candidate && (
+ candidate.manifest?.version === candidate.info.version &&
+ candidate.path && updater.installerPath === candidate.path
+ ));
+ const refreshQuitInstall = () => {
+ updater.autoInstallOnAppQuit = !checkInFlight && !downloadInFlight &&
+ !verificationInFlight && ready === target && packageMatches(ready);
+ if (updater.autoInstallOnAppQuit) {
+ // BaseUpdater normally registers this during update-downloaded, before
+ // our async hash verification completes. Register only after trust is
+ // established; its quit callback reads autoInstallOnAppQuit again.
+ updater.addQuitHandler();
+ }
+ };
+ const invalidate = () => {
+ updater.autoInstallOnAppQuit = false;
+ ready = null;
+ target = null;
+ };
+ const fail = (error, stage) => {
+ invalidate();
+ publish({ state: "idle", version: null, progress: null });
+ onError(error, stage);
+ };
+
+ // Downloads are still automatic, but start only after metadata selection
+ // (and Windows signature verification), never inside checkForUpdates().
+ updater.autoDownload = false;
+ updater.autoInstallOnAppQuit = false;
+ updater.autoRunAppAfterInstall = true;
+ updater.on("download-progress", (progress) => {
+ if (downloadInFlight) {
+ publish({ progress });
+ log("update.download-progress", { percent: progress.percent });
+ }
+ });
+ updater.on("error", (error) => {
+ // check/download promises report their own errors with the correct stage.
+ if (!checkInFlight && !downloadInFlight) {
+ installing = false;
+ fail(error, "install");
+ }
+ });
+ updater.on("update-downloaded", (info) => {
+ const candidate = target;
+ if (!downloadInFlight || verificationInFlight) {
+ fail(new Error("Unexpected update download completion"), "verify-windows-package");
+ return;
+ }
+ verificationInFlight = Promise.resolve().then(async () => {
+ if (!candidate || candidate.info.version !== info?.version) {
+ throw new Error("Downloaded update does not match the selected target");
+ }
+ onStage("verify-windows-package");
+ if (!candidate.manifest || candidate.manifest.version !== info.version ||
+ !info.downloadedFile || updater.installerPath !== info.downloadedFile) {
+ throw new Error("Downloaded Windows update has no matching trusted installer");
+ }
+ await verifyWindowsPackage({ path: info.downloadedFile, manifest: candidate.manifest });
+ if (target !== candidate) throw new Error("Update target changed during package verification");
+ candidate.path = info.downloadedFile;
+ candidate.verified = true;
+ });
+ // The event may precede downloadUpdate()'s promise settlement.
+ void verificationInFlight.catch(() => {});
+ });
+
+ const download = (reason) => {
+ if (downloadInFlight) return downloadInFlight;
+ const candidate = target;
+ if (!candidate || !candidate.manifest) {
+ return Promise.reject(new Error("Update metadata has not passed the signature gate"));
+ }
+ if (ready === candidate && packageMatches(ready)) return Promise.resolve();
+ updater.autoInstallOnAppQuit = false;
+ downloadInFlight = Promise.resolve().then(async () => {
+ onStage("download");
+ await updater.downloadUpdate();
+ await verificationInFlight;
+ if (target !== candidate || !candidate.verified || !packageMatches(candidate)) {
+ throw new Error("Downloaded package does not match the selected update target");
+ }
+ ready = candidate;
+ publish({ state: "downloaded", version: candidate.info.version, progress: null });
+ log("update.downloaded", { version: candidate.info.version });
+ }).catch((error) => {
+ fail(error, verificationInFlight ? "verify-windows-package" : "download");
+ log(verificationInFlight ? "update.windows-package-blocked" : "update.download-failed", {
+ reason, message: error.message,
+ });
+ }).finally(() => {
+ downloadInFlight = null;
+ verificationInFlight = null;
+ refreshQuitInstall();
+ if (!checkInFlight) onSettled();
+ if (ready === candidate) onDownloaded(candidate.info.version);
+ });
+ return downloadInFlight;
+ };
+
+ const check = (reason) => {
+ if (installing) return Promise.resolve(null);
+ if (checkInFlight) return checkInFlight;
+ // In particular, do not change updater.updateInfoAndProvider while a
+ // Windows package is still being hashed after its download has finished.
+ if (downloadInFlight) return Promise.resolve(null);
+ updater.autoInstallOnAppQuit = false;
+ let stage = "check";
+ checkInFlight = Promise.resolve().then(async () => {
+ onCheckStarted(reason);
+ const result = await updater.checkForUpdates();
+ if (!result?.isUpdateAvailable) {
+ invalidate();
+ publish({ state: "idle", version: null, progress: null });
+ log("update.not-available");
+ return result;
+ }
+ const info = result.updateInfo;
+ if (ready && isDeepStrictEqual(ready.info, info) && packageMatches(ready)) {
+ publish({ state: "downloaded", version: ready.info.version, progress: null });
+ return result;
+ }
+ // Revoke installation of the previous package before awaiting trust of
+ // a replacement. A failed replacement must never install the old file.
+ invalidate();
+ target = { info, manifest: null, path: null, verified: false };
+ publish({ state: "available", version: info.version, progress: null });
+ log("update.available", { version: info.version });
+ stage = "verify-windows-metadata";
+ onStage(stage);
+ target.manifest = await fetchWindowsMetadata({ version: info.version, updateInfo: info });
+ if (target.manifest.version !== info.version) throw new Error("Windows manifest target mismatch");
+ log("update.windows-manifest-verified", { version: info.version, keyId: target.manifest.keyId });
+ void download(reason);
+ return result;
+ }).catch((error) => {
+ // A failed check leaves the old package on disk, but does not authorize
+ // installation without a successful check and (on Windows) verification.
+ fail(error, stage);
+ log("update.check-failed", { reason, message: error.message });
+ throw error;
+ }).finally(() => {
+ checkInFlight = null;
+ refreshQuitInstall();
+ if (!downloadInFlight) onSettled();
+ });
+ return checkInFlight;
+ };
+
+ const install = (expectedVersion) => {
+ if (installInFlight) return installInFlight;
+ if (!ready || installing) return Promise.resolve({ started: false });
+ installInFlight = Promise.resolve().then(async () => {
+ await check("before-install");
+ if (downloadInFlight) await downloadInFlight;
+ if (!ready || ready !== target || !ready.verified || !packageMatches(ready) ||
+ checkInFlight || downloadInFlight || verificationInFlight ||
+ (expectedVersion && expectedVersion !== ready.info.version)) {
+ return { started: false };
+ }
+ installing = true;
+ log("update.install-confirmed", { version: ready.info.version });
+ beforeInstall();
+ updater.quitAndInstall(true, true);
+ return { started: true };
+ }).catch((error) => {
+ installing = false;
+ if (status.state !== "idle") fail(error, "install");
+ return { started: false };
+ }).finally(() => { installInFlight = null; });
+ return installInFlight;
+ };
+
+ return { check, download, install, snapshot: () => ({ ...status }) };
+};
diff --git a/apps/desktop/src/main/windows-update-controller.test.mjs b/apps/desktop/src/main/windows-update-controller.test.mjs
new file mode 100644
index 00000000..e3ed8512
--- /dev/null
+++ b/apps/desktop/src/main/windows-update-controller.test.mjs
@@ -0,0 +1,319 @@
+import { createRequire } from "node:module";
+import { createHash, generateKeyPairSync, sign } from "node:crypto";
+import { mkdtemp, writeFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, test } from "bun:test";
+import { createWindowsUpdateController } from "./windows-update-controller.mjs";
+import { WINDOWS_UPDATE_KEY_ID, verifyWindowsUpdateMetadata, verifyDownloadedWindowsUpdate } from "./windows-update-trust.mjs";
+
+// Exercise the installed electron-updater's real check, download promise and
+// quit-handler behavior. Replace only network/package acquisition and process
+// spawning; no Electron app or Windows installer is launched by these tests.
+const require = createRequire(new URL("../../package.json", import.meta.url));
+const { BaseUpdater } = require("electron-updater/out/BaseUpdater.js");
+
+const deferred = () => {
+ let resolve, reject;
+ const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
+ return { promise, resolve, reject };
+};
+const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve(); };
+const directories = [];
+afterEach(async () => {
+ await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true })));
+});
+
+const harness = async () => {
+ const directory = await mkdtemp(join(tmpdir(), "edgeever-update-target-"));
+ directories.push(directory);
+ const keys = generateKeyPairSync("ed25519");
+ const releases = new Map();
+ for (const version of ["2.17.0", "2.18.0", "2.19.0"]) {
+ const bytes = Buffer.from(`installer ${version}`);
+ const name = `EdgeEver-${version}-windows-x64.exe`;
+ const path = join(directory, name);
+ await writeFile(path, bytes);
+ const manifest = {
+ schemaVersion: 1, keyId: WINDOWS_UPDATE_KEY_ID, version, platform: "win32", arch: "x64",
+ releaseDate: "2026-11-03T00:00:00.000Z",
+ file: {
+ name, size: bytes.length,
+ sha512: createHash("sha512").update(bytes).digest("base64"),
+ sha256: createHash("sha256").update(bytes).digest("hex"),
+ },
+ };
+ const info = { version, files: [{ url: name, size: bytes.length, sha512: manifest.file.sha512 }] };
+ const manifestBytes = Buffer.from(JSON.stringify(manifest));
+ const signatureBytes = Buffer.from(JSON.stringify({ schemaVersion: 1, keyId: WINDOWS_UPDATE_KEY_ID,
+ signature: sign(null, manifestBytes, keys.privateKey).toString("base64") }));
+ releases.set(version, { path, info, manifest, manifestBytes, signatureBytes });
+ }
+ const h = { latest: "2.17.0", checks: 0, downloads: [], installs: [], errors: [], notices: [], statuses: [],
+ checkGate: null, metadataGate: null, downloadGate: null, hashGate: null,
+ checkError: null, metadataError: null, downloadError: null, eventVersion: null, packagePath: null,
+ corruptSignature: false, corruptMetadata: false };
+ const updater = new BaseUpdater(null, {
+ version: "2.16.1", isPackaged: true,
+ onQuit: (handler) => { h.quitHandler = handler; },
+ });
+ updater.logger = null;
+ updater.getUpdateInfoAndProvider = async () => {
+ h.checks++;
+ if (h.checkGate) await h.checkGate.promise;
+ if (h.checkError) throw h.checkError;
+ if (!h.latest) return { info: { version: "2.16.1" }, provider: {} };
+ const info = structuredClone(releases.get(h.latest).info);
+ if (h.corruptMetadata) info.files[0].sha512 = "invalid";
+ updater.selected = info;
+ return { info, provider: {} };
+ };
+ updater.doDownloadUpdate = async () => {
+ const version = updater.selected.version;
+ h.downloads.push(version);
+ if (h.downloadGate) await h.downloadGate.promise;
+ if (h.downloadError) throw h.downloadError;
+ updater.downloadedUpdateHelper = {
+ file: h.packagePath || releases.get(version).path,
+ downloadedFileInfo: { isAdminRightsRequired: false },
+ };
+ updater.dispatchUpdateDownloaded({ version: h.eventVersion || version, downloadedFile: updater.installerPath });
+ updater.addQuitHandler();
+ return [updater.installerPath];
+ };
+ updater.doInstall = ({ isSilent, isForceRunAfter }) => {
+ h.installs.push({ version: updater.selected.version, path: updater.installerPath, silent: isSilent, forceRun: isForceRunAfter });
+ return true;
+ };
+ updater.quitAndInstall = (silent, forceRun) => updater.install(silent, forceRun);
+ const controller = createWindowsUpdateController({
+ updater,
+ fetchWindowsMetadata: async ({ version, updateInfo }) => {
+ if (h.metadataGate) await h.metadataGate.promise;
+ if (h.metadataError) throw h.metadataError;
+ const release = releases.get(version);
+ return verifyWindowsUpdateMetadata({ ...release, expectedVersion: version, updateInfo,
+ signatureBytes: h.corruptSignature ? Buffer.from(JSON.stringify({
+ schemaVersion: 1, keyId: WINDOWS_UPDATE_KEY_ID, signature: Buffer.alloc(64).toString("base64"),
+ })) : release.signatureBytes,
+ trustedPublicKeys: { [WINDOWS_UPDATE_KEY_ID]: keys.publicKey } });
+ },
+ verifyWindowsPackage: async (options) => {
+ if (h.hashGate) await h.hashGate.promise;
+ await verifyDownloadedWindowsUpdate(options);
+ },
+ onStatus: (status) => h.statuses.push(status),
+ onError: (error, stage) => h.errors.push({ error, stage }),
+ onDownloaded: (version) => h.notices.push(version),
+ beforeInstall: () => {},
+ });
+ // Await the download and hash work without timers or polling the filesystem.
+ const settle = async () => { await controller.download("test-wait").catch(() => {}); await flush(); };
+ const ready = async () => { await controller.check("startup"); await settle(); };
+ return Object.assign(h, { updater, controller, releases, settle, ready });
+};
+
+describe("desktop update target lifecycle (#776)", () => {
+ test("replaces a downloaded intermediate version with the newest release", async () => {
+ const h = await harness();
+ await h.ready();
+ h.latest = "2.19.0";
+ await h.controller.check("interval");
+ await h.settle();
+ expect(h.downloads).toEqual(["2.17.0", "2.19.0"]);
+ expect(h.controller.snapshot().version).toBe("2.19.0");
+ expect(await h.controller.install()).toEqual({ started: true });
+ expect(h.installs).toEqual([{ version: "2.19.0", path: h.releases.get("2.19.0").path, silent: true, forceRun: true }]);
+ });
+
+ test("checks again at installation time and installs the latest directly", async () => {
+ const h = await harness();
+ await h.ready();
+ h.latest = "2.18.0";
+ expect(await h.controller.install()).toEqual({ started: true });
+ expect(h.downloads).toEqual(["2.17.0", "2.18.0"]);
+ expect(h.installs.map((entry) => entry.version)).toEqual(["2.18.0"]);
+ });
+
+ test("an unchanged release does not download or prompt again", async () => {
+ const h = await harness();
+ await h.ready();
+ await h.controller.check("manual");
+ expect(h.checks).toBe(2);
+ expect(h.downloads).toEqual(["2.17.0"]);
+ expect(h.notices).toEqual(["2.17.0"]);
+ expect(h.updater.autoInstallOnAppQuit).toBe(true);
+ });
+
+ test("an old native dialog cannot approve installing a replacement version", async () => {
+ const h = await harness();
+ await h.ready();
+ h.latest = "2.18.0";
+ expect(await h.controller.install("2.17.0")).toEqual({ started: false });
+ expect(h.installs).toEqual([]);
+ expect(h.notices).toEqual(["2.17.0", "2.18.0"]);
+ expect(await h.controller.install("2.18.0")).toEqual({ started: true });
+ });
+
+ test("blocks quit installation during a check and coalesces manual installation requests", async () => {
+ const h = await harness();
+ await h.ready();
+ h.checkGate = deferred();
+ const check = h.controller.check("interval");
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+ const first = h.controller.install();
+ const second = h.controller.install();
+ expect(first).toBe(second);
+ await flush();
+ expect(h.installs).toEqual([]);
+ h.checkGate.resolve();
+ await check;
+ await first;
+ expect(h.checks).toBe(2);
+ expect(h.installs).toHaveLength(1);
+ });
+
+ test("serializes checks and installation around asynchronous Windows hashing", async () => {
+ const h = await harness();
+ await h.ready();
+ h.latest = "2.18.0";
+ h.hashGate = deferred();
+ await h.controller.check("manual");
+ await flush();
+ h.latest = "2.19.0";
+ await h.controller.check("resume");
+ expect(h.checks).toBe(2);
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+ h.quitHandler(0);
+ expect(h.installs).toEqual([]);
+ expect(await h.controller.install()).toEqual({ started: false });
+ h.hashGate.resolve();
+ await h.settle();
+ expect(h.controller.snapshot()).toMatchObject({ state: "downloaded", version: "2.18.0" });
+ expect(h.updater.autoInstallOnAppQuit).toBe(true);
+ });
+
+ for (const failure of ["check", "metadata", "download", "signature", "metadata-digest", "package-digest", "event-version"]) {
+ test(`a replacement ${failure} failure never installs the old or unverified package`, async () => {
+ const h = await harness();
+ await h.ready();
+ h.latest = "2.18.0";
+ if (failure === "check") h.checkError = new Error("offline");
+ if (failure === "metadata") h.metadataError = new Error("metadata unavailable");
+ if (failure === "download") h.downloadError = new Error("download failed");
+ if (failure === "signature") h.corruptSignature = true;
+ if (failure === "metadata-digest") h.corruptMetadata = true;
+ if (failure === "package-digest") await writeFile(h.releases.get(h.latest).path, "tampered! 2.18.0");
+ if (failure === "event-version") h.eventVersion = "2.17.0";
+ await h.controller.check("interval").catch(() => {});
+ await h.settle();
+ expect(await h.controller.install()).toEqual({ started: false });
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+ expect(h.installs).toEqual([]);
+ expect(h.errors.length).toBeGreaterThan(0);
+ expect(h.controller.snapshot().state).toBe("idle");
+ });
+ }
+
+ test("does not download a replacement until its signature gate completes", async () => {
+ const h = await harness();
+ await h.ready();
+ h.latest = "2.18.0";
+ h.metadataGate = deferred();
+ const check = h.controller.check("manual");
+ expect(h.controller.check("resume")).toBe(check);
+ await flush();
+ expect(h.downloads).toEqual(["2.17.0"]);
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+ expect(await h.controller.install()).toEqual({ started: false });
+ h.metadataGate.resolve();
+ await check;
+ await h.settle();
+ expect(h.downloads).toEqual(["2.17.0", "2.18.0"]);
+ });
+
+ test("does not replace the updater target during a pending download", async () => {
+ const h = await harness();
+ await h.ready();
+ h.latest = "2.18.0";
+ h.downloadGate = deferred();
+ await h.controller.check("manual");
+ h.latest = "2.19.0";
+ await h.controller.check("resume");
+ expect(h.checks).toBe(2);
+ expect(h.updater.selected.version).toBe("2.18.0");
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+ h.downloadGate.resolve();
+ await h.settle();
+ expect(h.controller.snapshot().version).toBe("2.18.0");
+ });
+
+ test("a changed digest at the same version cannot reuse the old verified target", async () => {
+ const h = await harness();
+ await h.ready();
+ h.corruptMetadata = true;
+ await expect(h.controller.check("interval")).rejects.toThrow("does not match the signed manifest");
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+ expect(await h.controller.install()).toEqual({ started: false });
+ expect(h.installs).toEqual([]);
+ });
+
+ test("a withdrawn release revokes installation of the downloaded package", async () => {
+ const h = await harness();
+ await h.ready();
+ h.latest = null;
+ await h.controller.check("interval");
+ expect(h.controller.snapshot().state).toBe("idle");
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+ expect(await h.controller.install()).toEqual({ started: false });
+ });
+
+ test("registers the real updater quit hook only after hashing and revokes it during replacement", async () => {
+ const h = await harness();
+ h.hashGate = deferred();
+ await h.controller.check("startup");
+ await flush();
+ expect(h.quitHandler).toBeUndefined();
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+ h.hashGate.resolve();
+ await h.settle();
+ expect(typeof h.quitHandler).toBe("function");
+ h.latest = "2.18.0";
+ h.metadataGate = deferred();
+ const check = h.controller.check("interval");
+ h.quitHandler(0);
+ expect(h.installs).toEqual([]);
+ h.metadataGate.resolve();
+ await check;
+ await h.settle();
+ h.quitHandler(0);
+ expect(h.installs).toEqual([{ version: "2.18.0", path: h.releases.get("2.18.0").path, silent: true, forceRun: false }]);
+ });
+
+ test("a failed check can recover and reauthorize a verified cached package", async () => {
+ const h = await harness();
+ await h.ready();
+ h.checkError = new Error("offline");
+ await expect(h.controller.check("interval")).rejects.toThrow("offline");
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+ h.checkError = null;
+ await h.ready();
+ expect(h.controller.snapshot().state).toBe("downloaded");
+ expect(await h.controller.install()).toEqual({ started: true });
+ });
+
+ test("requires the installed Windows file to be the verified file", async () => {
+ const h = await harness();
+ await h.ready();
+ h.updater.downloadedUpdateHelper.file = h.releases.get("2.18.0").path;
+ h.metadataGate = deferred();
+ const install = h.controller.install();
+ await flush();
+ expect(h.updater.autoInstallOnAppQuit).toBe(false);
+ expect(h.installs).toEqual([]);
+ h.metadataError = new Error("cannot authorize replacement");
+ h.metadataGate.resolve();
+ expect(await install).toEqual({ started: false });
+ });
+
+});