Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(remote): never overwrite remote-hosts.json while it cannot be read

liuzixiange8b8984dcfd4
diff --git a/apps/desktop/electron/main/remote/remote-host-registry.ts b/apps/desktop/electron/main/remote/remote-host-registry.ts
index b367438df..c1da759a3 100644
--- a/apps/desktop/electron/main/remote/remote-host-registry.ts
+++ b/apps/desktop/electron/main/remote/remote-host-registry.ts
@@ -95,27 +95,87 @@ function fileNotFound(error: unknown): boolean {
return typeof error === "object" && error !== null && (error as { code?: string }).code === "ENOENT";
}
+/**
+ * What the last read of the registry file found. Writes may only proceed
+ * from `ok`, `absent`, and `corrupt` (after quarantine) — every other
+ * outcome means the on-disk records may exist but cannot be seen, and
+ * overwriting them would destroy pairing data the user cannot rebuild
+ * without re-pairing every host.
+ */
+type RegistryRead =
+ | { kind: "ok"; hosts: SerializedRecord[] }
+ | { kind: "absent" }
+ | { kind: "unreadable"; error: unknown }
+ | { kind: "corrupt"; error: unknown }
+ | { kind: "unsupportedVersion" };
+
export function createRemoteHostRegistry(
options: RemoteHostRegistryOptions,
): RemoteHostRegistry {
const log = options.log ?? (() => undefined);
const filePath = join(options.dataDir, options.fileName ?? "remote-hosts.json");
- const readFileContents = async (): Promise<SerializedFile> => {
+ const readFileState = async (): Promise<RegistryRead> => {
+ let raw: string;
try {
- const raw = await readFile(filePath, "utf8");
- const parsed = JSON.parse(raw) as Partial<SerializedFile>;
- if (parsed.version !== CURRENT_VERSION || !Array.isArray(parsed.hosts)) {
- log("warn", "remote-hosts.json shape rejected; treating as empty", { file: filePath });
- return { version: CURRENT_VERSION, hosts: [] };
- }
- return { version: CURRENT_VERSION, hosts: parsed.hosts };
+ raw = await readFile(filePath, "utf8");
} catch (error) {
- if (fileNotFound(error)) return { version: CURRENT_VERSION, hosts: [] };
+ if (fileNotFound(error)) return { kind: "absent" };
log("error", "remote-hosts.json read failed", { error: String(error) });
- // A corrupt file must not delete records the user cannot see; the
- // caller reads an empty list and any upsert would overwrite it.
- return { version: CURRENT_VERSION, hosts: [] };
+ return { kind: "unreadable", error };
+ }
+ let parsed: Partial<SerializedFile>;
+ try {
+ parsed = JSON.parse(raw) as Partial<SerializedFile>;
+ } catch (error) {
+ log("error", "remote-hosts.json is corrupt", { file: filePath, error: String(error) });
+ return { kind: "corrupt", error };
+ }
+ if (parsed.version !== CURRENT_VERSION || !Array.isArray(parsed.hosts)) {
+ log("warn", "remote-hosts.json shape rejected", { file: filePath });
+ return { kind: "unsupportedVersion" };
+ }
+ return { kind: "ok", hosts: parsed.hosts };
+ };
+
+ /**
+ * The hosts a read-modify-write may start from. A corrupt file is
+ * quarantined (renamed aside, bytes preserved) so pairing stays available
+ * while the old records remain recoverable; a file that cannot be read or
+ * was written by a newer app version makes the write throw instead of
+ * silently replacing records the caller never saw.
+ */
+ const writableHosts = async (): Promise<SerializedRecord[]> => {
+ const state = await readFileState();
+ switch (state.kind) {
+ case "ok":
+ return state.hosts;
+ case "absent":
+ return [];
+ case "corrupt": {
+ const quarantine = `${filePath}.corrupt-${new Date().toISOString().replace(/[:.]/g, "-")}`;
+ try {
+ await rename(filePath, quarantine);
+ } catch {
+ // The file cannot be moved aside, so it cannot be safely replaced.
+ throw Object.assign(
+ new Error("remote-hosts.json is corrupt and could not be quarantined; refusing to overwrite"),
+ { errorCode: "REMOTE_REGISTRY_UNWRITABLE" },
+ );
+ }
+ log("warn", "quarantined corrupt remote-hosts.json", { quarantine });
+ return [];
+ }
+ case "unreadable":
+ throw Object.assign(
+ new Error("remote-hosts.json could not be read; refusing to overwrite the paired-host records"),
+ { errorCode: "REMOTE_REGISTRY_UNWRITABLE" },
+ );
+ case "unsupportedVersion":
+ throw Object.assign(
+ new Error("remote-hosts.json was written by a newer app version; refusing to overwrite"),
+ { errorCode: "REMOTE_REGISTRY_VERSION_UNSUPPORTED" },
+ );
}
};
@@ -128,9 +188,12 @@ export function createRemoteHostRegistry(
return {
async list() {
- const file = await readFileContents();
+ // Reads stay permissive: while the file is unreadable or unsupported
+ // the UI shows an empty list (as before), but nothing on disk changes.
+ const state = await readFileState();
+ const hosts = state.kind === "ok" ? state.hosts : [];
const decoded: RemoteHostRecord[] = [];
- for (const record of file.hosts) {
+ for (const record of hosts) {
try {
const buffer = Buffer.from(record.encryptedDeviceToken, "base64");
const deviceToken = options.encryption.decryptString(buffer);
@@ -178,7 +241,7 @@ export function createRemoteHostRegistry(
errorCode: "REMOTE_STORAGE_UNAVAILABLE",
});
}
- const file = await readFileContents();
+ const hosts = await writableHosts();
const ciphertext = options.encryption.encryptString(record.deviceToken).toString("base64");
const serialized: SerializedRecord = {
hostKey: record.hostKey,
@@ -194,14 +257,14 @@ export function createRemoteHostRegistry(
: {}),
...(record.metadata ? { metadata: record.metadata } : {}),
};
- const next = file.hosts.filter((existing) => existing.hostKey !== record.hostKey);
+ const next = hosts.filter((existing) => existing.hostKey !== record.hostKey);
next.push(serialized);
await persist({ version: CURRENT_VERSION, hosts: next });
},
async remove(hostKey) {
- const file = await readFileContents();
- const next = file.hosts.filter((existing) => existing.hostKey !== hostKey);
- if (next.length === file.hosts.length) return;
+ const hosts = await writableHosts();
+ const next = hosts.filter((existing) => existing.hostKey !== hostKey);
+ if (next.length === hosts.length) return;
if (next.length === 0) {
try {
await unlink(filePath);
diff --git a/apps/desktop/test/remote-host-registry.test.mjs b/apps/desktop/test/remote-host-registry.test.mjs
index 0aef7df32..ebca01c9b 100644
--- a/apps/desktop/test/remote-host-registry.test.mjs
+++ b/apps/desktop/test/remote-host-registry.test.mjs
@@ -181,3 +181,63 @@ test("a shape-mismatched file is treated as empty and preserved on disk until re
assert.ok(still.includes("oops"));
await cleanup();
});
+
+test("upsert and remove refuse to overwrite while the file cannot be read", async () => {
+ const { dir, cleanup } = await tmpDir();
+ const fs = await import("node:fs/promises");
+ // A directory at the registry path makes readFile fail with EISDIR — the
+ // transient-unreadable case (AV lock, ACL) without platform tricks.
+ await fs.mkdir(join(dir, "remote-hosts.json"));
+ const registry = createRemoteHostRegistry({ dataDir: dir, encryption: reversibleEncryption() });
+ await assert.rejects(
+ registry.upsert({ hostKey: "a", label: "A", url: "wss://a", deviceToken: "t-a" }),
+ /refusing to overwrite/,
+ );
+ await assert.rejects(registry.remove("a"), /refusing to overwrite/);
+ // Reads stay permissive, and nothing replaced the blocked file.
+ assert.deepEqual(await registry.list(), []);
+ const stat = await fs.stat(join(dir, "remote-hosts.json"));
+ assert.ok(stat.isDirectory());
+ await cleanup();
+});
+
+test("a future-version file is listed as empty but never overwritten", async () => {
+ const { dir, cleanup } = await tmpDir();
+ const raw = JSON.stringify({ version: 99, hosts: [{ hostKey: "from-the-future" }] });
+ await writeFile(join(dir, "remote-hosts.json"), raw, "utf8");
+ const registry = createRemoteHostRegistry({ dataDir: dir, encryption: reversibleEncryption() });
+ assert.deepEqual(await registry.list(), []);
+ await assert.rejects(
+ registry.upsert({ hostKey: "a", label: "A", url: "wss://a", deviceToken: "t-a" }),
+ /newer app version/,
+ );
+ await assert.rejects(registry.remove("from-the-future"), /newer app version/);
+ assert.equal(await readFile(join(dir, "remote-hosts.json"), "utf8"), raw);
+ await cleanup();
+});
+
+test("a corrupt file is quarantined with its bytes preserved, then pairing continues", async () => {
+ const { dir, cleanup } = await tmpDir();
+ const garbage = '{"version": 1, "hosts": [{"hostKey": "tru';
+ await writeFile(join(dir, "remote-hosts.json"), garbage, "utf8");
+ const warnings = [];
+ const registry = createRemoteHostRegistry({
+ dataDir: dir,
+ encryption: reversibleEncryption(),
+ log: (level, message) => warnings.push({ level, message }),
+ });
+ // list() shows empty (undecryptable bytes), the file survives reads…
+ assert.deepEqual(await registry.list(), []);
+ assert.ok((await readFile(join(dir, "remote-hosts.json"), "utf8")) === garbage);
+ // …and the next pairing moves the broken file aside instead of erasing it.
+ await registry.upsert({ hostKey: "a", label: "A", url: "wss://a", deviceToken: "t-a" });
+ const entries = await (await import("node:fs/promises")).readdir(dir);
+ const quarantine = entries.find((name) => name.startsWith("remote-hosts.json.corrupt-"));
+ assert.ok(quarantine, "quarantine copy must exist");
+ assert.ok((await readFile(join(dir, quarantine), "utf8")) === garbage);
+ const rows = await registry.list();
+ assert.equal(rows.length, 1);
+ assert.equal(rows[0].hostKey, "a");
+ assert.ok(warnings.some((entry) => /quarantined corrupt/.test(entry.message)));
+ await cleanup();
+});