Skip to content

Commit b06b0df

Browse files
fix(desktop): simplify the Windows signature timeout retry
1 parent bf25d81 commit b06b0df

2 files changed

Lines changed: 58 additions & 80 deletions

File tree

‎apps/desktop/src/electron/ElectronUpdater.test.ts‎

Lines changed: 30 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { assert, describe, it } from "@effect/vitest";
22
import * as Effect from "effect/Effect";
3-
import type { Logger, VerifyUpdateCodeSignature } from "electron-updater";
3+
import type { VerifyUpdateCodeSignature } from "electron-updater";
44
import { beforeEach, vi } from "vite-plus/test";
55

66
const { autoUpdaterMock } = vi.hoisted(() => ({
@@ -14,12 +14,12 @@ const { autoUpdaterMock } = vi.hoisted(() => ({
1414
fullChangelog: false,
1515
checkForUpdates: vi.fn(() => Promise.resolve(null)),
1616
downloadUpdate: vi.fn(() => Promise.resolve([])),
17-
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } as Logger | null,
17+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
18+
verifyUpdateCodeSignature: undefined as VerifyUpdateCodeSignature | undefined,
1819
on: vi.fn(),
1920
quitAndInstall: vi.fn(),
2021
removeListener: vi.fn(),
2122
setFeedURL: vi.fn(),
22-
verifyUpdateCodeSignature: undefined as VerifyUpdateCodeSignature | undefined,
2323
},
2424
}));
2525

@@ -144,32 +144,32 @@ describe("ElectronUpdater", () => {
144144
describe("Windows update signature check", () => {
145145
const publisherNames = ["T3 Tools Inc"];
146146
const installerPath = "C:\\updater\\pending\\temp-T3-Code-x64.exe";
147-
// execFile rejects like this when electron-updater's 20 s PowerShell limit kills the check.
147+
// execFile marks the error killed when the verifier exceeds its 20-second timeout.
148148
const timedOut = () =>
149149
Object.assign(new Error("Command failed: powershell.exe"), { killed: true });
150150

151-
// NsisUpdater runs the verifier after the download and fails on any non-null result.
152-
const downloadVerifyingSignature = (verify = autoUpdaterMock.verifyUpdateCodeSignature) => {
153-
autoUpdaterMock.verifyUpdateCodeSignature = verify;
151+
const downloadVerifyingSignature = () => {
154152
autoUpdaterMock.downloadUpdate.mockImplementationOnce(async () => {
155-
const rejection = await autoUpdaterMock.verifyUpdateCodeSignature?.(
153+
const rejection = await autoUpdaterMock.verifyUpdateCodeSignature!(
156154
publisherNames,
157155
installerPath,
158156
);
159-
if (rejection != null) throw new Error(`not signed by the application owner: ${rejection}`);
157+
// NSIS accepts only null as a successful signature check.
158+
if (rejection !== null) throw new Error(`Invalid signature: ${rejection}`);
160159
return [];
161160
});
162161
return Effect.flatMap(ElectronUpdater.ElectronUpdater, (updater) => updater.downloadUpdate);
163162
};
164163

165-
it.effect("retries a signature check that timed out once", () =>
164+
it.effect("retries a timed-out signature check with the same verifier and installer", () =>
166165
Effect.gen(function* () {
167166
const verify = vi
168167
.fn<VerifyUpdateCodeSignature>()
169168
.mockRejectedValueOnce(timedOut())
170169
.mockResolvedValueOnce(null);
170+
autoUpdaterMock.verifyUpdateCodeSignature = verify;
171171

172-
yield* downloadVerifyingSignature(verify);
172+
yield* downloadVerifyingSignature();
173173

174174
assert.deepEqual(verify.mock.calls, [
175175
[publisherNames, installerPath],
@@ -178,52 +178,46 @@ describe("ElectronUpdater", () => {
178178
}).pipe(Effect.provide(ElectronUpdater.layer)),
179179
);
180180

181-
it.effect("does not retry a rejected signature, another failure or a second timeout", () =>
181+
it.effect("fails on invalid signatures, other errors and two timeouts on each download", () =>
182182
Effect.gen(function* () {
183-
const cases: ReadonlyArray<readonly [() => Promise<string | null>, number]> = [
184-
[() => Promise.resolve("publisherNames: T3 Tools Inc, raw info: {}"), 1],
185-
[() => Promise.reject(new Error("Cannot execute Get-AuthenticodeSignature")), 1],
186-
[() => Promise.reject(timedOut()), 2],
183+
const cases = [
184+
{ outcome: () => Promise.resolve("Invalid publisher"), calls: 1 },
185+
{ outcome: () => Promise.reject(new Error("Cannot execute PowerShell")), calls: 1 },
186+
{ outcome: () => Promise.reject(timedOut()), calls: 2 },
187187
];
188-
for (const [outcome, expectedCalls] of cases) {
188+
for (const { outcome, calls } of cases) {
189189
const verify = vi.fn<VerifyUpdateCodeSignature>(outcome);
190-
const error = yield* downloadVerifyingSignature(verify).pipe(Effect.flip);
191-
192-
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
193-
assert.equal(verify.mock.calls.length, expectedCalls);
190+
autoUpdaterMock.verifyUpdateCodeSignature = verify;
191+
192+
// Reusing the installed verifier must neither stack retries nor exhaust future retries.
193+
for (let download = 1; download <= 2; download++) {
194+
const error = yield* downloadVerifyingSignature().pipe(Effect.flip);
195+
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
196+
assert.equal(verify.mock.calls.length, calls * download);
197+
}
194198
}
195199
}).pipe(Effect.provide(ElectronUpdater.layer)),
196200
);
197201

198-
it.effect("rejects a retried check that electron-updater skipped", () =>
202+
it.effect("rejects a retry when the upstream capability probe skips verification", () =>
199203
Effect.gen(function* () {
200-
// After a failed check, electron-updater resolves null when its PowerShell probe also fails.
201204
const verify = vi
202205
.fn<VerifyUpdateCodeSignature>()
203206
.mockRejectedValueOnce(timedOut())
204207
.mockImplementationOnce(async () => {
205-
autoUpdaterMock.logger?.warn(
208+
// Upstream resolves null even though its failed capability probe skips verification.
209+
autoUpdaterMock.logger.warn(
206210
"Cannot execute ConvertTo-Json: spawnSync powershell.exe ETIMEDOUT. Ignoring signature validation due to unsupported powershell version. Please upgrade to powershell 3 or higher.",
207211
);
208212
return null;
209213
});
214+
autoUpdaterMock.verifyUpdateCodeSignature = verify;
210215

211-
const error = yield* downloadVerifyingSignature(verify).pipe(Effect.flip);
216+
const error = yield* downloadVerifyingSignature().pipe(Effect.flip);
212217

213218
assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError);
214219
assert.equal(verify.mock.calls.length, 2);
215220
}).pipe(Effect.provide(ElectronUpdater.layer)),
216221
);
217-
218-
it.effect("retries once per download when the verifier is reused", () =>
219-
Effect.gen(function* () {
220-
const verify = vi.fn<VerifyUpdateCodeSignature>(() => Promise.reject(timedOut()));
221-
222-
yield* downloadVerifyingSignature(verify).pipe(Effect.flip);
223-
yield* downloadVerifyingSignature().pipe(Effect.flip);
224-
225-
assert.equal(verify.mock.calls.length, 4);
226-
}).pipe(Effect.provide(ElectronUpdater.layer)),
227-
);
228222
});
229223
});

‎apps/desktop/src/electron/ElectronUpdater.ts‎

Lines changed: 28 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -81,57 +81,41 @@ export class ElectronUpdater extends Context.Service<
8181
}
8282
>()("@t3tools/desktop/electron/ElectronUpdater") {}
8383

84-
const isTimedOutChildProcess = (error: unknown) =>
85-
error instanceof Error && "killed" in error && error.killed === true;
86-
8784
const signatureChecksWithRetry = new WeakSet<VerifyUpdateCodeSignature>();
8885

89-
// When a check fails and its PowerShell capability probe fails too, electron-updater logs this,
90-
// skips the check and resolves null, which NsisUpdater accepts as a valid signature.
91-
const skippedSignatureCheck = "Ignoring signature validation";
92-
93-
// The retry follows a failed check, so it passes only on a null that was not a skipped check.
94-
const retryTimedOutSignatureCheck = async (
95-
verify: VerifyUpdateCodeSignature,
96-
publisherNames: string[],
97-
path: string,
98-
) => {
99-
const logger = autoUpdater.logger;
100-
let skipped = false;
101-
autoUpdater.logger = {
102-
info: (message) => logger?.info(message),
103-
warn: (message) => {
104-
skipped ||= String(message).includes(skippedSignatureCheck);
105-
logger?.warn(message);
106-
},
107-
error: (message) => logger?.error(message),
108-
debug: (message) => logger?.debug?.(message),
109-
};
110-
try {
111-
const result = await verify(publisherNames, path);
112-
if (typeof result === "string" || (result === null && !skipped)) return result;
113-
return "the signature could not be verified after a timed-out check was retried";
114-
} finally {
115-
autoUpdater.logger = logger;
116-
}
117-
};
118-
119-
// electron-updater's Windows signature check kills PowerShell after 20 s. Endpoint security
120-
// scanning a freshly downloaded installer can exceed that on the first check, while a repeat
121-
// check of the scanned file is fast. Retry a timed-out check once; any other outcome, including
122-
// a rejected signature, is returned unchanged.
12386
const retrySignatureCheckAfterTimeout = () => {
124-
// Only the Windows (NSIS) updater has a signature check.
87+
// Only the Windows NSIS updater exposes this hook; its PowerShell check times out after 20 s.
12588
const updater = autoUpdater as AutoUpdater &
12689
Partial<Pick<NsisUpdater, "verifyUpdateCodeSignature">>;
12790
const verify = updater.verifyUpdateCodeSignature;
12891
if (verify === undefined || signatureChecksWithRetry.has(verify)) return;
129-
const verifyWithRetry: VerifyUpdateCodeSignature = (publisherNames, path) =>
130-
verify(publisherNames, path).catch((error: unknown) =>
131-
isTimedOutChildProcess(error)
132-
? retryTimedOutSignatureCheck(verify, publisherNames, path)
133-
: Promise.reject(error),
134-
);
92+
93+
const verifyWithRetry: VerifyUpdateCodeSignature = async (publisherNames, path) => {
94+
try {
95+
return await verify(publisherNames, path);
96+
} catch (error) {
97+
if (!(error instanceof Error && "killed" in error && error.killed === true)) throw error;
98+
}
99+
100+
const logger = updater.logger;
101+
let skipped = false;
102+
updater.logger = {
103+
info: (message) => logger?.info(message),
104+
warn: (message) => {
105+
// A failed capability probe makes electron-updater warn and return null without checking.
106+
skipped ||= String(message).includes("Ignoring signature validation");
107+
logger?.warn(message);
108+
},
109+
error: (message) => logger?.error(message),
110+
debug: (message) => logger?.debug?.(message),
111+
};
112+
try {
113+
const result = await verify(publisherNames, path);
114+
return skipped ? "Signature validation was skipped after a timed-out check." : result;
115+
} finally {
116+
updater.logger = logger;
117+
}
118+
};
135119
signatureChecksWithRetry.add(verifyWithRetry);
136120
updater.verifyUpdateCodeSignature = verifyWithRetry;
137121
};

0 commit comments

Comments
 (0)