Skip to content

Commit 4e41d35

Browse files
fix(desktop): stage and verify AppImage replacements
Rebuilt from #20117 by MarMarLabs to preserve the installed AppImage until a verified replacement can be committed.
1 parent 1451e7c commit 4e41d35

2 files changed

Lines changed: 318 additions & 1 deletion

File tree

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - electron-updater installs synchronously while the app quits.
2+
import * as NodeCrypto from "node:crypto";
3+
import * as NodeFS from "node:fs";
4+
import * as NodePath from "node:path";
5+
6+
import type { AppImageUpdater } from "electron-updater";
7+
8+
type CopyFile = (from: string, to: string) => void;
9+
10+
function syncPath(path: string): void {
11+
const fd = NodeFS.openSync(path, "r");
12+
try {
13+
NodeFS.fsyncSync(fd);
14+
} finally {
15+
NodeFS.closeSync(fd);
16+
}
17+
}
18+
19+
function verifyAndSyncStage(path: string, sourceSize: number, sha512: string): void {
20+
const fd = NodeFS.openSync(path, "r");
21+
try {
22+
if (NodeFS.fstatSync(fd).size !== sourceSize) {
23+
throw new Error("The copied AppImage update has an invalid size.");
24+
}
25+
const hash = NodeCrypto.createHash("sha512");
26+
const buffer = Buffer.allocUnsafe(1024 * 1024);
27+
let read: number;
28+
while ((read = NodeFS.readSync(fd, buffer, 0, buffer.length, null)) > 0) {
29+
hash.update(buffer.subarray(0, read));
30+
}
31+
if (hash.digest("base64") !== sha512) {
32+
throw new Error("The copied AppImage update has an invalid SHA-512 digest.");
33+
}
34+
NodeFS.fchmodSync(fd, 0o755);
35+
NodeFS.fsyncSync(fd);
36+
} finally {
37+
NodeFS.closeSync(fd);
38+
}
39+
}
40+
41+
export function installAppImageUpdate(input: {
42+
readonly appImageFile: string;
43+
readonly installerPath: string;
44+
readonly sha512: string;
45+
readonly size?: number | undefined;
46+
readonly logger?: NonNullable<AppImageUpdater["logger"]> | undefined;
47+
readonly copyFile?: CopyFile;
48+
}): string {
49+
const installedName = NodePath.basename(input.appImageFile);
50+
// Match electron-updater: retain custom names, but advance versioned filenames.
51+
const destination = /\d+\.\d+\.\d+/.test(installedName)
52+
? NodePath.join(NodePath.dirname(input.appImageFile), NodePath.basename(input.installerPath))
53+
: input.appImageFile;
54+
const sourceSize = NodeFS.statSync(input.installerPath).size;
55+
if (sourceSize === 0 || (input.size !== undefined && sourceSize !== input.size)) {
56+
throw new Error("The downloaded AppImage update has an invalid size.");
57+
}
58+
59+
const bestEffort = (operation: () => void) => {
60+
try {
61+
operation();
62+
} catch (error) {
63+
try {
64+
input.logger?.warn(`AppImage update cleanup or directory sync failed: ${String(error)}`);
65+
} catch {
66+
// Logging must not turn a committed replacement into an installation failure.
67+
}
68+
}
69+
};
70+
const removeObsolete = (path: string) =>
71+
bestEffort(() => {
72+
const file = NodeFS.statSync(path, { bigint: true });
73+
const installed = NodeFS.statSync(destination, { bigint: true });
74+
// realpath covers symlinks; device/inode identity also covers bind mounts.
75+
if (
76+
NodeFS.realpathSync(path) === NodeFS.realpathSync(destination) ||
77+
(file.dev === installed.dev && file.ino === installed.ino)
78+
) {
79+
return;
80+
}
81+
NodeFS.rmSync(path, { force: true });
82+
});
83+
84+
// A private stage on the destination filesystem allows an atomic rename. Its
85+
// fixed-length name also accommodates AppImage names near the filename limit.
86+
const stageDirectory = NodeFS.mkdtempSync(
87+
NodePath.join(NodePath.dirname(destination), ".t3code-update-"),
88+
);
89+
const staged = NodePath.join(stageDirectory, "update.AppImage");
90+
try {
91+
if (input.copyFile) {
92+
input.copyFile(input.installerPath, staged);
93+
} else {
94+
NodeFS.copyFileSync(input.installerPath, staged, NodeFS.constants.COPYFILE_EXCL);
95+
}
96+
verifyAndSyncStage(staged, sourceSize, input.sha512);
97+
NodeFS.renameSync(staged, destination);
98+
} finally {
99+
bestEffort(() => NodeFS.rmSync(stageDirectory, { recursive: true, force: true }));
100+
}
101+
102+
bestEffort(() => syncPath(NodePath.dirname(destination)));
103+
if (destination !== input.appImageFile) removeObsolete(input.appImageFile);
104+
removeObsolete(input.installerPath);
105+
return destination;
106+
}

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

Lines changed: 212 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,24 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - Exercises AppImage replacement on a real temporary filesystem.
2+
import * as NodeCrypto from "node:crypto";
3+
import * as NodeFS from "node:fs";
4+
import * as NodeOS from "node:os";
5+
import * as NodePath from "node:path";
6+
17
import { assert, describe, it } from "@effect/vitest";
8+
import * as HostProcess from "@t3tools/shared/HostProcess";
29
import * as Effect from "effect/Effect";
3-
import { beforeEach, vi } from "vite-plus/test";
10+
import { afterEach, beforeEach, vi } from "vite-plus/test";
11+
12+
vi.mock("node:fs", async (importOriginal) => {
13+
const actual = await importOriginal<typeof NodeFS>();
14+
return {
15+
...actual,
16+
fsyncSync: vi.fn(actual.fsyncSync),
17+
renameSync: vi.fn(actual.renameSync),
18+
realpathSync: vi.fn(actual.realpathSync),
19+
rmSync: vi.fn(actual.rmSync),
20+
};
21+
});
422

523
const { autoUpdaterMock } = vi.hoisted(() => ({
624
autoUpdaterMock: {
@@ -25,6 +43,7 @@ vi.mock("electron-updater", () => ({
2543
}));
2644

2745
import * as ElectronUpdater from "./ElectronUpdater.ts";
46+
import { installAppImageUpdate } from "./AppImageInstall.ts";
2847

2948
describe("ElectronUpdater", () => {
3049
beforeEach(() => {
@@ -137,3 +156,195 @@ describe("ElectronUpdater", () => {
137156
}).pipe(Effect.provide(ElectronUpdater.layer)),
138157
);
139158
});
159+
160+
describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("installAppImageUpdate", () => {
161+
const oldAppImage = "#!/bin/sh\n# old build\nexit 0\n";
162+
const newAppImage = `#!/bin/sh\n# new build\nexit 0\n#${"x".repeat(4096)}\n`;
163+
const sha512 = (content: string) =>
164+
NodeCrypto.createHash("sha512").update(content).digest("base64");
165+
const directories: Array<string> = [];
166+
167+
function fixture(appImageName = "T3-Code.AppImage") {
168+
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-appimage-install-"));
169+
directories.push(root);
170+
const applications = NodePath.join(root, "Applications");
171+
const pending = NodePath.join(root, "cache", "pending");
172+
NodeFS.mkdirSync(applications);
173+
NodeFS.mkdirSync(pending, { recursive: true });
174+
const appImageFile = NodePath.join(applications, appImageName);
175+
const installerPath = NodePath.join(pending, "T3-Code-1.2.3-x86_64.AppImage");
176+
NodeFS.writeFileSync(appImageFile, oldAppImage, { mode: 0o755 });
177+
NodeFS.writeFileSync(installerPath, newAppImage, { mode: 0o644 });
178+
return { root, applications, appImageFile, installerPath };
179+
}
180+
181+
afterEach(() => {
182+
vi.mocked(NodeFS.fsyncSync).mockReset();
183+
vi.mocked(NodeFS.renameSync).mockReset();
184+
vi.mocked(NodeFS.realpathSync).mockReset();
185+
vi.mocked(NodeFS.rmSync).mockReset();
186+
for (const directory of directories.splice(0)) {
187+
NodeFS.rmSync(directory, { recursive: true, force: true });
188+
}
189+
});
190+
191+
it.each([
192+
{ installed: "T3-Code.AppImage", destination: "T3-Code.AppImage", releaseSize: undefined },
193+
{
194+
installed: "T3-Code-1.2.2-x86_64.AppImage",
195+
destination: "T3-Code-1.2.3-x86_64.AppImage",
196+
releaseSize: Buffer.byteLength(newAppImage),
197+
},
198+
])("replaces $installed with a verified executable at $destination", (names) => {
199+
const input = fixture(names.installed);
200+
const destination = installAppImageUpdate({
201+
...input,
202+
sha512: sha512(newAppImage),
203+
size: names.releaseSize,
204+
copyFile: (from, to) => {
205+
assert.equal(NodeFS.readFileSync(input.appImageFile, "utf8"), oldAppImage);
206+
const stageDirectory = NodePath.dirname(to);
207+
assert.equal(NodePath.dirname(stageDirectory), input.applications);
208+
assert.equal(NodeFS.statSync(stageDirectory).mode & 0o777, 0o700);
209+
NodeFS.copyFileSync(from, to, NodeFS.constants.COPYFILE_EXCL);
210+
},
211+
});
212+
213+
assert.equal(destination, NodePath.join(input.applications, names.destination));
214+
assert.equal(NodeFS.readFileSync(destination, "utf8"), newAppImage);
215+
assert.equal(NodeFS.statSync(destination).mode & 0o777, 0o755);
216+
assert.deepEqual(NodeFS.readdirSync(input.applications), [names.destination]);
217+
assert.isFalse(NodeFS.existsSync(input.installerPath));
218+
});
219+
220+
it("keeps the installed app and cached download when a partial copy runs out of space", () => {
221+
const input = fixture();
222+
223+
assert.throws(
224+
() =>
225+
installAppImageUpdate({
226+
...input,
227+
sha512: sha512(newAppImage),
228+
copyFile: (from, to) => {
229+
NodeFS.writeFileSync(to, NodeFS.readFileSync(from).subarray(0, 1024));
230+
throw Object.assign(new Error("ENOSPC: no space left on device"), { code: "ENOSPC" });
231+
},
232+
}),
233+
/ENOSPC/,
234+
);
235+
236+
assert.equal(NodeFS.readFileSync(input.appImageFile, "utf8"), oldAppImage);
237+
assert.equal(NodeFS.readFileSync(input.installerPath, "utf8"), newAppImage);
238+
assert.deepEqual(NodeFS.readdirSync(input.applications), [
239+
NodePath.basename(input.appImageFile),
240+
]);
241+
});
242+
243+
it("rejects empty, truncated, wrong-size and same-length corrupt updates before replacing the app", () => {
244+
const cases = [
245+
{ source: "", stage: "", digest: sha512(""), size: undefined },
246+
{ source: newAppImage, stage: "", digest: sha512(""), size: undefined },
247+
{ source: newAppImage, stage: "short", digest: sha512("short"), size: undefined },
248+
{
249+
source: newAppImage,
250+
stage: newAppImage,
251+
digest: sha512(newAppImage),
252+
size: Buffer.byteLength(newAppImage) + 1,
253+
},
254+
{
255+
source: newAppImage,
256+
stage: newAppImage.replace("new", "bad"),
257+
digest: sha512(newAppImage),
258+
size: undefined,
259+
},
260+
];
261+
for (const { source, stage, digest, size } of cases) {
262+
const input = fixture();
263+
NodeFS.writeFileSync(input.installerPath, source);
264+
265+
assert.throws(() =>
266+
installAppImageUpdate({
267+
...input,
268+
sha512: digest,
269+
size,
270+
copyFile: (_from, to) => NodeFS.writeFileSync(to, stage),
271+
}),
272+
);
273+
274+
assert.equal(NodeFS.readFileSync(input.appImageFile, "utf8"), oldAppImage);
275+
assert.equal(NodeFS.readFileSync(input.installerPath, "utf8"), source);
276+
assert.deepEqual(NodeFS.readdirSync(input.applications), [
277+
NodePath.basename(input.appImageFile),
278+
]);
279+
}
280+
});
281+
282+
it.each(["fsyncSync", "renameSync"] as const)(
283+
"keeps the old app when %s fails before commit",
284+
(operation) => {
285+
const input = fixture();
286+
vi.mocked(NodeFS[operation]).mockImplementationOnce(() => {
287+
throw new Error("cannot commit update");
288+
});
289+
290+
assert.throws(
291+
() => installAppImageUpdate({ ...input, sha512: sha512(newAppImage) }),
292+
/cannot commit update/,
293+
);
294+
295+
assert.equal(NodeFS.readFileSync(input.appImageFile, "utf8"), oldAppImage);
296+
assert.equal(NodeFS.readFileSync(input.installerPath, "utf8"), newAppImage);
297+
assert.deepEqual(NodeFS.readdirSync(input.applications), [
298+
NodePath.basename(input.appImageFile),
299+
]);
300+
},
301+
);
302+
303+
it.each(["same path", "symlink", "mount alias"] as const)(
304+
"keeps the committed destination when the cache reaches it through %s",
305+
(aliasKind) => {
306+
const input = fixture("T3-Code-1.2.2-x86_64.AppImage");
307+
let cacheDirectory = input.applications;
308+
if (aliasKind !== "same path") {
309+
cacheDirectory = NodePath.join(input.root, "alias");
310+
NodeFS.symlinkSync(input.applications, cacheDirectory);
311+
}
312+
const installerPath = NodePath.join(cacheDirectory, NodePath.basename(input.installerPath));
313+
NodeFS.renameSync(input.installerPath, installerPath);
314+
if (aliasKind === "mount alias") {
315+
// Bind mounts share directory entries without realpath resolving their aliases.
316+
vi.mocked(NodeFS.realpathSync).mockImplementation(((path: NodeFS.PathLike) =>
317+
NodePath.resolve(String(path))) as typeof NodeFS.realpathSync);
318+
}
319+
320+
const destination = installAppImageUpdate({
321+
...input,
322+
installerPath,
323+
sha512: sha512(newAppImage),
324+
});
325+
326+
assert.equal(
327+
destination,
328+
NodePath.join(input.applications, NodePath.basename(installerPath)),
329+
);
330+
assert.equal(NodeFS.readFileSync(destination, "utf8"), newAppImage);
331+
assert.equal(NodeFS.readFileSync(installerPath, "utf8"), newAppImage);
332+
assert.deepEqual(NodeFS.readdirSync(input.applications), [NodePath.basename(installerPath)]);
333+
},
334+
);
335+
336+
it("still succeeds when removing the cached download fails after commit", () => {
337+
const input = fixture();
338+
const remove = vi.mocked(NodeFS.rmSync).getMockImplementation()!;
339+
vi.mocked(NodeFS.rmSync).mockImplementation((path, options) => {
340+
if (path === input.installerPath) throw new Error("cache cleanup failed");
341+
remove(path, options);
342+
});
343+
344+
const destination = installAppImageUpdate({ ...input, sha512: sha512(newAppImage) });
345+
346+
assert.equal(NodeFS.readFileSync(destination, "utf8"), newAppImage);
347+
assert.equal(NodeFS.readFileSync(input.installerPath, "utf8"), newAppImage);
348+
assert.deepEqual(NodeFS.readdirSync(input.applications), [NodePath.basename(destination)]);
349+
});
350+
});

0 commit comments

Comments
 (0)