Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(desktop): Remove a paired phone while phone access is asleep
AdityaUmale93ecb2196a66
diff --git a/electron/companion-revoke.node-test.mjs b/electron/companion-revoke.node-test.mjsnew file mode 100644index 0000000000..d8086a2e5b--- /dev/null+++ b/electron/companion-revoke.node-test.mjs@@ -0,0 +1,50 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import vm from "node:vm";++/** companionRevoke alone, with the sidecar, its store and the transition queue stubbed. */+function revokeWith({ running, removeAtRest = () => true, control = async () => ({}) }) {+ const source = readFileSync(new URL("./companion.mjs", import.meta.url), "utf8");+ const start = source.indexOf("export async function companionRevoke");+ const end = source.indexOf("\n}\n", start);+ assert.ok(start >= 0 && end > start);+ const calls = [];+ const context = vm.createContext({+ proc: running ? {} : null,+ serialize: (work) => { calls.push(["serialize"]); return Promise.resolve().then(work); },+ removePairedDeviceAtRest: (id) => { calls.push(["at rest", id]); return removeAtRest(id); },+ control: async (...args) => { calls.push(args); return control(...args); },+ companionState: async () => ({ enabled: running }),+ e2eHooks: { changed: () => {} },+ });+ vm.runInContext(source.slice(start, end + 2).replace("export ", ""), context);+ return { revoke: context.companionRevoke, calls };+}++test("Remove with the phone link asleep takes the phone out of the store it loads at start", async () => {+ const { revoke, calls } = revokeWith({ running: false });+ await revoke("phone-1");+ assert.deepEqual(calls, [["serialize"], ["at rest", "phone-1"]]);+});++test("a removal that could not be saved while asleep is an error, never a quiet success", async () => {+ const { revoke } = revokeWith({ running: false, removeAtRest: () => { throw new Error("could not save"); } });+ await assert.rejects(revoke("phone-1"), /could not save/);+});++test("Remove with the phone link running goes to the sidecar, and its failure reaches the page", async () => {+ const { revoke, calls } = revokeWith({ running: true });+ await revoke("phone-1");+ assert.deepEqual(calls, [["DELETE", "/devices/phone-1"]]);+ const failing = revokeWith({ running: true, control: async () => { throw new Error("companion control 500"); } });+ await assert.rejects(failing.revoke("phone-1"), /companion control 500/);+});++test("an id that could shape a path is refused in both states", async () => {+ for (const running of [false, true]) {+ const { revoke, calls } = revokeWith({ running });+ for (const id of ["../other", "phone?all=1", "a".repeat(65), "", undefined]) await revoke(id);+ assert.deepEqual(calls, []);+ }+});diff --git a/electron/companion-settings.mjs b/electron/companion-settings.mjsindex 2ac06f4be9..8a262e189c 100644--- a/electron/companion-settings.mjs+++ b/electron/companion-settings.mjs@@ -104,6 +104,26 @@ export function readPairedDevices(file = companionDevicesFile()) {export const countPairedPhones = (file) => readPairedDevices(file)?.length ?? null;+/** Takes one device out of the companion's own store while its sidecar is not running, the store it loads when it+ * starts. False when nothing matched. Throws when the store cannot be read or saved: an unreadable store is never+ * overwritten, and the person never sees a removal that did not happen. */+export function removePairedDeviceAtRest(id, file = companionDevicesFile()) {+ const devices = readPairedDevices(file);+ if (devices === null) throw new Error("the paired devices could not be read");+ const kept = devices.filter((device) => device?.id !== id);+ if (kept.length === devices.length) return false;+ const temporary = `${file}.${process.pid}.tmp`;+ try {+ // The store holds token hashes: private to this user, as the sidecar writes it.+ fs.writeFileSync(temporary, JSON.stringify({ devices: kept }, null, 2), { mode: 0o600 });+ fs.renameSync(temporary, file);+ } catch (error) {+ fs.rmSync(temporary, { force: true });+ throw error;+ }+ return true;+}+/** Looks at this computer's interfaces only: Tailscale's own interface (`tailscale0`, "Tailscale", or the utun that* carries a fd7a:115c:a1e0::/48 address). A 100.64/10 address alone is not Tailscale: carrier NAT and other VPNs use it. */export function hasTailnetAddress(interfaces = os.networkInterfaces()) {diff --git a/electron/companion-settings.node-test.mjs b/electron/companion-settings.node-test.mjsindex b03427634d..ff6e947ad0 100644--- a/electron/companion-settings.node-test.mjs+++ b/electron/companion-settings.node-test.mjs@@ -1,12 +1,12 @@import assert from "node:assert/strict";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import path from "node:path";import test from "node:test";import {COMPANION_SETTINGS_VERSION, RECENT_DEVICE_MS, anyRouteOn, companionDevicesFile, countPairedPhones, defaultCompanionSettings, directRoutesOn,- hasTailnetAddress, phoneLinkShouldSleep, phoneLinkStartsAtLaunch, readCompanionSettings, setRoute,+ hasTailnetAddress, phoneLinkShouldSleep, phoneLinkStartsAtLaunch, readCompanionSettings, readPairedDevices, removePairedDeviceAtRest, setRoute,} from "./companion-settings.mjs";const NOW = 1_800_000_000_000;@@ -94,6 +94,25 @@ test("paired devices are read from the companion's own store", () => {}});+test("a paired device is removed from the store while the phone link is asleep", () => {+ const dir = mkdtempSync(path.join(tmpdir(), "omb-companion-settings-"));+ try {+ const file = companionDevicesFile({ OMB_COMPANION_DIR: dir });+ assert.equal(removePairedDeviceAtRest("a", file), false, "nothing paired yet");+ writeFileSync(file, JSON.stringify({ devices: [{ id: "a", tokenHash: "x" }, { id: "b", tokenHash: "y" }] }));+ assert.equal(removePairedDeviceAtRest("a", file), true);+ assert.deepEqual(readPairedDevices(file), [{ id: "b", tokenHash: "y" }]);+ assert.equal(removePairedDeviceAtRest("a", file), false, "already gone");+ assert.deepEqual(readdirSync(dir), ["devices.json"], "no temporary file left behind");+ if (process.platform !== "win32") assert.equal(statSync(file).mode & 0o777, 0o600, "token hashes stay private to this user");+ writeFileSync(file, "{not json");+ assert.throws(() => removePairedDeviceAtRest("b", file), /could not be read/);+ assert.equal(readFileSync(file, "utf8"), "{not json", "an unreadable store is never overwritten");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});+test("Tailscale is seen by its own interface, never by a 100.64/10 address alone", () => {assert.equal(hasTailnetAddress({ en0: [{ family: "IPv4", address: "192.168.1.4" }] }), false);assert.equal(hasTailnetAddress({ utun4: [{ family: "IPv4", address: "100.101.2.3" }] }), false, "carrier NAT or another VPN");diff --git a/electron/companion.mjs b/electron/companion.mjsindex 914ec09fe8..0df370a287 100644--- a/electron/companion.mjs+++ b/electron/companion.mjs@@ -4,7 +4,7 @@ import { randomBytes } from "node:crypto";import fs from "node:fs";import path from "node:path";import { resolveCompanionEntry } from "./companion-entry.mjs";-import { anyRouteOn, COMPANION_SETTINGS_VERSION, countPairedPhones, directRoutesOn, hasTailnetAddress, phoneLinkStartsAtLaunch, readCompanionSettings, readPairedDevices, setRoute } from "./companion-settings.mjs";+import { anyRouteOn, COMPANION_SETTINGS_VERSION, countPairedPhones, directRoutesOn, hasTailnetAddress, phoneLinkStartsAtLaunch, readCompanionSettings, readPairedDevices, removePairedDeviceAtRest, setRoute } from "./companion-settings.mjs";import {cleanupCompanionOriginEndpoint,companionOriginHealth,@@ -434,10 +434,13 @@ export async function companionPairing(open, expectedToken) {}export async function companionRevoke(deviceId) {- if (!proc) return companionState();// the id came from the renderer, so it does not get to shape a pathif (!/^[\w-]{1,64}$/.test(String(deviceId ?? ""))) return companionState();- await control("DELETE", `/devices/${deviceId}`).catch(() => {});+ // Asleep, nothing listens: the phone leaves the store the sidecar loads when it starts. In the transition queue, so+ // a start never loads the store halfway through; a start that got there first takes the removal itself.+ if (!proc && await serialize(() => (proc ? false : (removePairedDeviceAtRest(deviceId), true)))) return companionState();+ // A removal that failed is an error on the page, never a quiet "Removed".+ await control("DELETE", `/devices/${deviceId}`);e2eHooks.changed();return companionState();}