Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(local-vm): compare rescued apps without a Unix-only executable

Afloat0e49aaf764c2
diff --git a/server/local-vm-app-compare.test.ts b/server/local-vm-app-compare.test.ts
new file mode 100644
index 0000000000..c066e29386
--- /dev/null
+++ b/server/local-vm-app-compare.test.ts
@@ -0,0 +1,84 @@
+import { cp, mkdtemp, mkdir, readFile, readdir, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { LocalVmTarget } from "./container-computer.ts";
+
+const { exec } = vi.hoisted(() => ({ exec: vi.fn() }));
+vi.mock("node:child_process", async (original) => ({ ...await original<typeof import("node:child_process")>(), execFile: exec }));
+import { rescueInstalledApps } from "./local-vm-profiles.ts";
+
+let root: string, copied: string, durable: string, target: LocalVmTarget;
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), "omb-app-compare-"));
+ copied = join(root, "old-apps");
+ const workspaceDir = join(root, "workspace");
+ durable = join(workspaceDir, ".desktop-apps", "local");
+ await mkdir(copied, { recursive: true });
+ await mkdir(durable, { recursive: true });
+ target = { key: "bot:fixture", containerName: "fixture", workspaceDir, viewerPort: null, label: "fixture" };
+ exec.mockReset().mockImplementation((command, args, _options, callback) => {
+ if (command !== "fixture-runtime") {
+ callback(Object.assign(new Error("executable is unavailable on this host"), { code: "ENOENT" }));
+ } else {
+ void cp(copied, args.at(-1), { recursive: true, verbatimSymlinks: true }).then(() => callback(null, { stdout: "", stderr: "" }), callback);
+ }
+ return {};
+ });
+});
+afterEach(async () => { await rm(root, { recursive: true, force: true }); });
+
+const both = async (name: string, content: string | Buffer) => {
+ for (const dir of [copied, durable]) await writeFile(join(dir, name), content);
+};
+
+describe("installed-app comparison on hosts without Unix diff", () => {
+ it("keeps identical nested applications, including files larger than a comparison buffer", async () => {
+ for (const dir of [copied, durable]) await mkdir(join(dir, "empty"));
+ const content = Buffer.alloc(192 * 1024 + 1, 17);
+ content[content.length - 1] = 23;
+ await both("application.bin", content);
+ expect(await rescueInstalledApps("fixture-runtime", target)).toBe("kept");
+ expect(await readFile(join(durable, "application.bin"))).toEqual(content);
+ expect(exec).toHaveBeenCalledTimes(1);
+ expect(await readdir(target.workspaceDir)).toEqual([".desktop-apps"]);
+ });
+
+ it.each([0, 192 * 1024])("refuses a same-size file differing at byte %i without changing the durable copy", async (offset) => {
+ const content = Buffer.alloc(192 * 1024 + 1, 17);
+ await both("application.bin", content);
+ const changed = Buffer.from(content);
+ changed[offset] = 23;
+ await writeFile(join(copied, "application.bin"), changed);
+ await expect(rescueInstalledApps("fixture-runtime", target)).rejects.toThrow(/durable app area differs/);
+ expect(await readFile(join(durable, "application.bin"))).toEqual(content);
+ expect(await readdir(target.workspaceDir)).toEqual([".desktop-apps"]);
+ });
+
+ it("does not discard a missing empty application directory", async () => {
+ await both("app", "same");
+ await mkdir(join(copied, "missing-empty-directory"));
+ await expect(rescueInstalledApps("fixture-runtime", target)).rejects.toThrow(/durable app area differs/);
+ });
+
+ it("refuses a directory that would replace an existing file", async () => {
+ await mkdir(join(copied, "app"));
+ await writeFile(join(durable, "app"), "keep");
+ await expect(rescueInstalledApps("fixture-runtime", target)).rejects.toThrow(/durable app area differs/);
+ expect(await readFile(join(durable, "app"), "utf8")).toBe("keep");
+ });
+
+ it.skipIf(process.platform === "win32")("compares identical symlinks by their target without following them", async () => {
+ for (const dir of [copied, durable]) await symlink("missing-app-target", join(dir, "app-link"));
+ expect(await rescueInstalledApps("fixture-runtime", target)).toBe("kept");
+ expect(exec).toHaveBeenCalledTimes(1);
+ });
+
+ it.skipIf(process.platform === "win32")("refuses different symlink targets even when both target files contain the same bytes", async () => {
+ await both("a", "same");
+ await both("b", "same");
+ await symlink("a", join(copied, "app-link"));
+ await symlink("b", join(durable, "app-link"));
+ await expect(rescueInstalledApps("fixture-runtime", target)).rejects.toThrow(/durable app area differs/);
+ });
+});
diff --git a/server/local-vm-profiles.ts b/server/local-vm-profiles.ts
index da32649d1c..0b488be39a 100644
--- a/server/local-vm-profiles.ts
+++ b/server/local-vm-profiles.ts
@@ -3,7 +3,7 @@
// Before such a desktop is removed, its Firefox profile is copied into the workspace, where the new image points ~/.mozilla.
import { execFile } from "node:child_process";
import { randomBytes } from "node:crypto";
-import { lstat, mkdir, readdir, rename, rm, rmdir } from "node:fs/promises";
+import { lstat, mkdir, open, readdir, readlink, rename, rm, rmdir, type FileHandle } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
@@ -36,6 +36,53 @@ async function isEmptyDirectory(path: string): Promise<boolean> {
}
}
+async function readChunk(file: FileHandle, buffer: Buffer): Promise<number> {
+ let filled = 0;
+ while (filled < buffer.length) {
+ const { bytesRead } = await file.read(buffer, filled, buffer.length - filled, null);
+ if (!bytesRead) break;
+ filled += bytesRead;
+ }
+ return filled;
+}
+
+async function sameFileBytes(a: string, b: string, deadline: number): Promise<boolean> {
+ const left = await open(a, "r");
+ try {
+ const right = await open(b, "r");
+ try {
+ const leftBuffer = Buffer.allocUnsafe(64 * 1024), rightBuffer = Buffer.allocUnsafe(64 * 1024);
+ for (;;) {
+ if (Date.now() > deadline) throw new Error("installed-app comparison timed out");
+ const [leftRead, rightRead] = await Promise.all([readChunk(left, leftBuffer), readChunk(right, rightBuffer)]);
+ if (leftRead !== rightRead || !leftBuffer.subarray(0, leftRead).equals(rightBuffer.subarray(0, rightRead))) return false;
+ if (!leftRead) return true;
+ }
+ } finally { await right.close(); }
+ } finally { await left.close(); }
+}
+
+async function sameAppTree(a: string, b: string): Promise<boolean> {
+ const pending: [string, string][] = [[a, b]];
+ const deadline = Date.now() + 5 * 60_000;
+ while (pending.length) {
+ if (Date.now() > deadline) throw new Error("installed-app comparison timed out");
+ const [left, right] = pending.pop()!;
+ const [ls, rs] = await Promise.all([lstat(left), lstat(right)]);
+ if (ls.isSymbolicLink() && rs.isSymbolicLink()) {
+ if (await readlink(left) !== await readlink(right)) return false;
+ } else if (ls.isDirectory() && rs.isDirectory()) {
+ const [leftNames, rightNames] = await Promise.all([readdir(left), readdir(right)]);
+ const names = new Set(rightNames);
+ if (leftNames.length !== rightNames.length || leftNames.some((name) => !names.has(name))) return false;
+ for (const name of leftNames) pending.push([join(left, name), join(right, name)]);
+ } else if (ls.isFile() && rs.isFile()) {
+ if (ls.size !== rs.size || !await sameFileBytes(left, right, deadline)) return false;
+ } else return false;
+ }
+ return true;
+}
+
/** Works on a stopped container. "kept": the workspace already has a Firefox profile, which is never overwritten.
* Any copy failure other than "no profile there" throws, so the caller keeps the old desktop rather than lose sign-ins. */
export async function rescueFirefoxProfile(runtime: string, target: LocalVmTarget): Promise<"rescued" | "kept" | "none"> {
@@ -100,7 +147,7 @@ export async function rescueInstalledApps(runtime: string, target: LocalVmTarget
if (!copied.isDirectory()) return "none";
if (existing && !(existing.isDirectory() && await isEmptyDirectory(durable))) {
try {
- await run("/usr/bin/diff", ["-qr", staging, durable], { timeout: 5 * 60_000, maxBuffer: 1024 * 1024 });
+ if (!await sameAppTree(staging, durable)) throw new Error("different app trees");
} catch {
throw new Error("could not preserve installed desktop apps because the durable app area differs from the old desktop");
}