diff --git a/apps/desktop/src/electron/ElectronUpdater.test.ts b/apps/desktop/src/electron/ElectronUpdater.test.ts index e47c741bf3bd8..bc9312426b220 100644 --- a/apps/desktop/src/electron/ElectronUpdater.test.ts +++ b/apps/desktop/src/electron/ElectronUpdater.test.ts @@ -7,6 +7,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { autoUpdater } from "electron-updater"; +import type { VerifyUpdateCodeSignature } from "electron-updater"; import type * as NodeChildProcess from "node:child_process"; import * as NodeModule from "node:module"; import { vi } from "vite-plus/test"; @@ -116,3 +117,126 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")( ); }, ); + +describe("ElectronUpdater Windows signature check", () => { + const publisherNames = ["T3 Tools Inc"]; + const installerPath = "C:\\updater\\pending\\temp-T3-Code-x64.exe"; + // execFile marks the error killed when the verifier exceeds its 20-second timeout. + const timedOut = () => + Object.assign(new Error("Command failed: powershell.exe"), { killed: true }); + const updater = autoUpdater as typeof autoUpdater & { + verifyUpdateCodeSignature?: VerifyUpdateCodeSignature; + }; + + const downloadVerifyingSignature = () => + Effect.gen(function* () { + yield* Effect.acquireRelease( + Effect.sync(() => + vi.spyOn(autoUpdater, "downloadUpdate").mockImplementationOnce(async () => { + // NsisUpdater reads the current verifier and accepts only null as a valid signature. + const rejection = await updater.verifyUpdateCodeSignature!( + publisherNames, + installerPath, + ); + if (rejection !== null) throw new Error(`Invalid signature: ${rejection}`); + return []; + }), + ), + (spy) => Effect.sync(() => spy.mockRestore()), + ); + return yield* Effect.flatMap( + ElectronUpdater.ElectronUpdater, + (electronUpdater) => electronUpdater.downloadUpdate, + ); + }).pipe(Effect.scoped); + + const withVerifier = ( + verify: VerifyUpdateCodeSignature, + effect: Effect.Effect, + ) => + Effect.acquireUseRelease( + Effect.sync(() => { + updater.verifyUpdateCodeSignature = verify; + }), + () => effect, + () => + Effect.sync(() => { + delete updater.verifyUpdateCodeSignature; + }), + ); + + it.effect("downloads the update when the first Windows signature checks time out", () => { + const verify = vi + .fn() + .mockRejectedValueOnce(timedOut()) + .mockRejectedValueOnce(timedOut()) + .mockRejectedValueOnce(timedOut()) + .mockResolvedValueOnce(null); + return withVerifier( + verify, + Effect.gen(function* () { + yield* downloadVerifyingSignature(); + assert.deepEqual( + verify.mock.calls, + Array.from({ length: 4 }, () => [publisherNames, installerPath]), + ); + }), + ).pipe(Effect.provide(ElectronUpdater.layer)); + }); + + it.effect( + "fails on invalid signatures, other errors and repeated timeouts on each download", + () => + Effect.gen(function* () { + const cases = [ + { outcome: () => Promise.resolve("Invalid publisher"), calls: 1 }, + { outcome: () => Promise.reject(new Error("Cannot execute PowerShell")), calls: 1 }, + { outcome: () => Promise.reject(timedOut()), calls: 5 }, + ]; + for (const { outcome, calls } of cases) { + const verify = vi.fn(outcome); + yield* withVerifier( + verify, + Effect.gen(function* () { + // A second download must neither stack retries nor start with a spent budget. + for (let download = 1; download <= 2; download++) { + const error = yield* downloadVerifyingSignature().pipe(Effect.flip); + assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError); + assert.equal(verify.mock.calls.length, calls * download); + } + }), + ); + } + }).pipe(Effect.provide(ElectronUpdater.layer)), + ); + + it.effect("retries a check the upstream capability probe skipped, and never accepts one", () => + Effect.gen(function* () { + const skipped = async () => { + // electron-updater warns through the updater's logger, then resolves null unchecked. + autoUpdater.logger?.warn( + "Cannot execute ConvertTo-Json: spawnSync powershell.exe ETIMEDOUT. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.", + ); + return null; + }; + + const recovers = vi + .fn() + .mockRejectedValueOnce(timedOut()) + .mockImplementationOnce(skipped) + .mockResolvedValueOnce(null); + yield* withVerifier(recovers, downloadVerifyingSignature()); + assert.equal(recovers.mock.calls.length, 3); + + const alwaysSkipped = vi + .fn(skipped) + .mockRejectedValueOnce(timedOut()); + const error = yield* withVerifier( + alwaysSkipped, + downloadVerifyingSignature().pipe(Effect.flip), + ); + assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError); + assert.equal(alwaysSkipped.mock.calls.length, 5); + }).pipe(Effect.provide(ElectronUpdater.layer)), + ); +}); diff --git a/apps/desktop/src/electron/ElectronUpdater.ts b/apps/desktop/src/electron/ElectronUpdater.ts index 0cc22bb4b1633..08005cac99f8d 100644 --- a/apps/desktop/src/electron/ElectronUpdater.ts +++ b/apps/desktop/src/electron/ElectronUpdater.ts @@ -5,6 +5,7 @@ import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import { AppImageUpdater, autoUpdater } from "electron-updater"; +import type { NsisUpdater, VerifyUpdateCodeSignature } from "electron-updater"; type AutoUpdater = typeof autoUpdater; type SpawnLog = (cmd: string, args?: Array, ...rest: Array) => Promise; @@ -100,6 +101,59 @@ export class ElectronUpdater extends Context.Service< } >()("@t3tools/desktop/electron/ElectronUpdater") {} +// Each timed-out check costs at least 20 s; five outlast the ~55 s first check seen behind on-access antivirus. +const SIGNATURE_CHECK_ATTEMPTS = 5; + +const signatureChecksWithRetry = new WeakSet(); + +const isTimedOut = (error: unknown) => + typeof error === "object" && error !== null && "killed" in error && error.killed === true; + +const retrySignatureCheckOnTimeout = () => { + // Only the Windows NSIS updater has this hook; its PowerShell check is killed after 20 s. + const updater = autoUpdater as AutoUpdater & + Partial>; + const verify = updater.verifyUpdateCodeSignature; + if (verify === undefined || signatureChecksWithRetry.has(verify)) return; + + const verifyDetectingSkip = async (publisherNames: Array, path: string) => { + const logger = updater.logger; + let skipped = false; + updater.logger = { + info: (message) => logger?.info(message), + warn: (message) => { + // After a timeout, a failed capability probe makes electron-updater warn and resolve null unchecked. + skipped ||= String(message).includes("Ignoring signature validation"); + logger?.warn(message); + }, + error: (message) => logger?.error(message), + debug: (message) => logger?.debug?.(message), + }; + try { + const result = await verify(publisherNames, path); + return { result, skipped }; + } finally { + updater.logger = logger; + } + }; + + const verifyWithRetry: VerifyUpdateCodeSignature = async (publisherNames, path) => { + for (let attempt = 1; ; attempt++) { + const lastAttempt = attempt === SIGNATURE_CHECK_ATTEMPTS; + try { + if (attempt === 1) return await verify(publisherNames, path); + const { result, skipped } = await verifyDetectingSkip(publisherNames, path); + if (!skipped) return result; + if (lastAttempt) return "Signature validation was skipped after a timed-out check."; + } catch (error) { + if (!isTimedOut(error) || lastAttempt) throw error; + } + } + }; + signatureChecksWithRetry.add(verifyWithRetry); + updater.verifyUpdateCodeSignature = verifyWithRetry; +}; + /** @public */ export const make = ElectronUpdater.of({ setFeedURL: Effect.fn("ElectronUpdater.setFeedURL")(function (options) { @@ -161,6 +215,7 @@ export const make = ElectronUpdater.of({ }).pipe(Effect.asVoid); }), downloadUpdate: Effect.suspend(() => { + retrySignatureCheckOnTimeout(); const channel = autoUpdater.channel; return Effect.tryPromise({ try: () => autoUpdater.downloadUpdate(),