Skip to content

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

Drop #7857 from the train: main fixed the same desktop-token race with #7935

milind-soni2d8c4bc596be
diff --git a/electron/company-backup-main.node-test.mjs b/electron/company-backup-main.node-test.mjs
index aba10c3102..77c85aa1cc 100644
--- a/electron/company-backup-main.node-test.mjs
+++ b/electron/company-backup-main.node-test.mjs
@@ -17,7 +17,7 @@ function section(start, end) {
assert.ok(from >= 0 && to > from, `Main-process test section moved: ${start}`);
return mainSource.slice(from, to);
}
-const functions = section("function ensureManagedDesktop()", "const savePhoneSecretOnce =");
+const functions = section("function ensureManagedDesktop()", "function syncDesktopMutationToken(");
const registrations = section("const workspaceOnly =", "const savedWorkspace =");
const ORIGIN = "http://127.0.0.1:48799";
const STAGE = "11111111-1111-4111-8111-111111111111";
diff --git a/electron/main.mjs b/electron/main.mjs
index c979f372b0..17b10163ec 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -25,7 +25,7 @@ import {
import { migrateWorkspaceConfigFile, workspaceCredentialEnv } from "./workspace-credentials.mjs";
import { evictStartupCacheOnce } from "./startup-cache-eviction.mjs"; import { desktopLaunchAnalytics } from "./launch-analytics.mjs";
import { activateExistingWindow, releaseSingleInstanceLock } from "./single-instance.mjs";
-import { bootFailureMessage, confirmDesktopAuthorization, listeningSignal, pollServerIdentity, SERVER_BOOT_TIMEOUT_MS, SERVER_LISTENING_GRACE_MS } from "./server-boot-probe.mjs";
+import { bootFailureMessage, listeningSignal, pollServerIdentity, SERVER_BOOT_TIMEOUT_MS, SERVER_LISTENING_GRACE_MS } from "./server-boot-probe.mjs";
import { createServerSupervisor } from "./server-supervisor.mjs";
import { serverChildLaunch } from "./server-child-launch.mjs";
import { packageUrlFromCommandLine, packageUrlFromDeepLink } from "./package-link.mjs";
@@ -1073,6 +1073,18 @@ async function runCompanyBackup(kind, input, scheduled = null) {
}
}
+function syncDesktopMutationToken(proc) {
+ try {
+ proc.postMessage({
+ type: "openmausbot:desktop-mutation-token",
+ token: desktopMutationToken,
+ companionToken: companionMutationToken,
+ });
+ } catch (error) {
+ slog(`desktop mutation capability sync failed: ${error?.message ?? error}`);
+ }
+}
+
const savePhoneSecretOnce = createPhoneSecretSaveCoordinator((target, value) =>
saveWorkspaceCredential(target, value),
);
@@ -1147,7 +1159,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmen
proc.once("spawn", () => {
slog(`spawned pid=${proc.pid}`); launchAnalytics.stage("server_spawned"); launchRecord.mark("serverSpawned");
if (!serverSupervisor.isCurrent(proc)) return;
- void tailnetShare.attach(proc, port, companionSettings().routes.tailscale);
+ syncDesktopMutationToken(proc); void tailnetShare.attach(proc, port, companionSettings().routes.tailscale);
syncPhoneSecretKey(proc); grantLocalComputer(proc, (child) => serverSupervisor.isCurrent(child)); browserPanes.attach(proc);
});
let exited = false;
@@ -1159,7 +1171,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmen
slog(`exited code=${code}`);
});
serverSupervisor.watch(proc);
- let identity = await pollServerIdentity({
+ const identity = await pollServerIdentity({
port,
pid: () => proc.pid,
bootTimeoutMs: SERVER_BOOT_TIMEOUT_MS,
@@ -1167,11 +1179,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmen
isListening: listening.heard, listened: listening.announced,
listeningGraceMs: SERVER_LISTENING_GRACE_MS,
});
- if (identity.outcome === "ready" && serverSupervisor.isCurrent(proc) && !desktopShutdownStarted) {
- const authorized = await confirmDesktopAuthorization(proc, { token: desktopMutationToken, companionToken: companionMutationToken });
- if (authorized && serverSupervisor.isCurrent(proc) && !desktopShutdownStarted) return { proc };
- if (!authorized) identity = { outcome: "owner-auth-unavailable" };
- }
+ if (identity.outcome === "ready" && serverSupervisor.isCurrent(proc)) return { proc };
slog(bootFailureMessage(port, identity));
const stopped = await stopUtilityServer(proc);
if (!stopped) {
diff --git a/electron/server-boot-probe.mjs b/electron/server-boot-probe.mjs
index 35c44dded3..3579913ead 100644
--- a/electron/server-boot-probe.mjs
+++ b/electron/server-boot-probe.mjs
@@ -30,33 +30,9 @@ export function bootFailureMessage(port, identity) {
if (identity.outcome === "exited") return `child on port ${port} exited before answering /api/health`;
if (identity.outcome === "foreign-owner") return `port ${port} answered health checks from another process`;
if (identity.outcome === "ready") return `child on port ${port} answered after it stopped being the current server`;
- if (identity.outcome === "owner-auth-unavailable") return `child on port ${port} could not confirm desktop authorization`;
return `child on port ${port} did not answer /api/health within ${Math.round((identity.waitedMs ?? 0) / 1000)}s`;
}
-export function confirmDesktopAuthorization(proc, { token, companionToken, timeoutMs = 5_000 }) {
- return new Promise((resolve) => {
- const finish = (accepted) => {
- clearTimeout(timer);
- proc.off("message", onMessage);
- proc.off("exit", onExit);
- resolve(accepted);
- };
- const onMessage = (message) => {
- if (message?.type === "openmausbot:desktop-mutation-token-accepted") finish(true);
- };
- const onExit = () => finish(false);
- const timer = setTimeout(onExit, timeoutMs);
- proc.on("message", onMessage);
- proc.once("exit", onExit);
- try {
- proc.postMessage({ type: "openmausbot:desktop-mutation-token", token, companionToken });
- } catch {
- finish(false);
- }
- });
-}
-
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/**
diff --git a/electron/server-boot-probe.node-test.mjs b/electron/server-boot-probe.node-test.mjs
index 7cbf1f4be7..d0f04369f4 100644
--- a/electron/server-boot-probe.node-test.mjs
+++ b/electron/server-boot-probe.node-test.mjs
@@ -1,5 +1,4 @@
import assert from "node:assert/strict";
-import { EventEmitter } from "node:events";
import test from "node:test";
import {
@@ -7,60 +6,10 @@ import {
BOOT_PROBE_FAST_WINDOW_MS,
BOOT_PROBE_INTERVAL_MS,
bootFailureMessage,
- confirmDesktopAuthorization,
listeningSignal,
pollServerIdentity,
} from "./server-boot-probe.mjs";
-const ownerCapability = { token: "owner-fixture", companionToken: "companion-fixture", timeoutMs: 30 };
-const ownerAccepted = { type: "openmausbot:desktop-mutation-token-accepted" };
-
-test("registers the private acknowledgement listener before sending the credential", async () => {
- const child = new EventEmitter();
- const sent = [];
- child.postMessage = (message) => {
- sent.push(message);
- child.emit("message", ownerAccepted);
- };
-
- assert.equal(await confirmDesktopAuthorization(child, ownerCapability), true);
- assert.deepEqual(sent, [{
- type: "openmausbot:desktop-mutation-token",
- token: ownerCapability.token,
- companionToken: ownerCapability.companionToken,
- }]);
- assert.equal(child.listenerCount("message"), 0);
- assert.equal(child.listenerCount("exit"), 0);
-});
-
-test("a different child or an unrelated message cannot confirm desktop authorization", async () => {
- const child = new EventEmitter();
- const other = new EventEmitter();
- child.postMessage = () => {
- other.emit("message", ownerAccepted);
- child.emit("message", { type: "health-ready" });
- };
-
- assert.equal(await confirmDesktopAuthorization(child, ownerCapability), false);
- child.emit("message", ownerAccepted);
- assert.equal(child.listenerCount("message"), 0);
- assert.equal(child.listenerCount("exit"), 0);
-});
-
-test("a child that exits or cannot receive its credential fails closed", async () => {
- const exited = new EventEmitter();
- exited.postMessage = () => exited.emit("exit", 1);
- const disconnected = new EventEmitter();
- disconnected.postMessage = () => { throw new Error("closed pipe"); };
-
- for (const child of [exited, disconnected]) {
- assert.equal(await confirmDesktopAuthorization(child, ownerCapability), false);
- assert.equal(child.listenerCount("message"), 0);
- assert.equal(child.listenerCount("exit"), 0);
- }
- assert.match(bootFailureMessage(8799, { outcome: "owner-auth-unavailable" }), /could not confirm desktop authorization/);
-});
-
const OUR_BODY = () => ({ app: "openmausbot", pid: 4242, static: true });
function okFetch({ body = OUR_BODY(), status = 200 } = {}) {
diff --git a/scripts/smoke-login-handoff.cjs b/scripts/smoke-login-handoff.cjs
index 6073f981d3..2b1c37964b 100644
--- a/scripts/smoke-login-handoff.cjs
+++ b/scripts/smoke-login-handoff.cjs
@@ -61,7 +61,7 @@ app.whenReady().then(async () => {
return { status: response.status, body: await response.json() };
};
await until(() => fetch(`http://127.0.0.1:${port}/api/health`).then((response) => response.ok).catch(() => false));
- harness.postMessage({ type: "openmausbot:desktop-mutation-token", token: owner, companionToken: randomBytes(32).toString("base64url") });
+ harness.postMessage({ type: "openmausbot:desktop-mutation-token", token: owner });
await until(() => api("/api/logins").then((answer) => answer.status === 200).catch(() => false));
const saved = await api("/api/logins", "POST", { site: "https://accounts.example.test/login", username: "alice", password, totp: "JBSWY3DPEHPK3PXP" });
assert.equal(saved.status, 201);
diff --git a/scripts/testing/cloud-send-fixture.ts b/scripts/testing/cloud-send-fixture.ts
index 3fcfcde5b9..4bf1fea91e 100644
--- a/scripts/testing/cloud-send-fixture.ts
+++ b/scripts/testing/cloud-send-fixture.ts
@@ -280,7 +280,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl
const startDesktop = async (dataDir?: string) => {
const child = await start("desktop", { OMB_DESKTOP_PARENT: "1", ...(dataDir ? { OMB_DATA_DIR: dataDir } : {}),
...(broker && desktopInstallation ? { OMB_COMPOSIO_BROKER_URL: broker.url, OMB_COMPOSIO_BROKER_TOKEN: desktopInstallation.token } : {}) }, desktopPort, ["--import", parentPort], true, onePasswordToken, toolCalls, desktopEngine);
- child.send({ type: "openmausbot:desktop-mutation-token", token: ownerCapability, companionToken: randomBytes(32).toString("base64url") });
+ child.send({ type: "openmausbot:desktop-mutation-token", token: ownerCapability });
return child;
};
let desktop = await startDesktop();
@@ -503,7 +503,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl
const capability = randomBytes(32).toString("base64url");
const startIt = async () => {
const child = await start(name, { OMB_DESKTOP_PARENT: "1", OMB_ENVIRONMENT_LABEL: label }, deskPort, ["--import", parentPort], true, onePasswordToken, toolCalls, desktopEngine);
- child.send({ type: "openmausbot:desktop-mutation-token", token: capability, companionToken: randomBytes(32).toString("base64url") });
+ child.send({ type: "openmausbot:desktop-mutation-token", token: capability });
return child;
};
let child = await startIt();
diff --git a/scripts/testing/own-home-fixture.ts b/scripts/testing/own-home-fixture.ts
index cf6e0292da..4a0de7edbb 100644
--- a/scripts/testing/own-home-fixture.ts
+++ b/scripts/testing/own-home-fixture.ts
@@ -110,7 +110,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl
const desktopBase = `http://127.0.0.1:${desktopPort}`;
const startDesktop = async () => {
const child = await start("desktop", { OMB_DESKTOP_PARENT: "1", OMB_ENVIRONMENT_LABEL: "Work laptop" }, desktopPort, ["--import", parentPort], true);
- child.send({ type: "openmausbot:desktop-mutation-token", token: capability, companionToken: randomBytes(32).toString("base64url") });
+ child.send({ type: "openmausbot:desktop-mutation-token", token: capability });
return child;
};
let desktop = await startDesktop();
diff --git a/server/desktop-mutation-capabilities.test.ts b/server/desktop-mutation-capabilities.test.ts
deleted file mode 100644
index 18377edac4..0000000000
--- a/server/desktop-mutation-capabilities.test.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { expect, it } from "vitest";
-
-import { desktopMutationCapabilities } from "./desktop-mutation-capabilities.ts";
-
-it("accepts a complete owner and companion capability pair", () => {
- const token = "a".repeat(43);
- const companionToken = "b".repeat(43);
- const type = "openmausbot:desktop-mutation-token";
- expect(desktopMutationCapabilities({ type, token, companionToken })).toEqual({ token, companionToken });
- expect(desktopMutationCapabilities({ type, token })).toBeNull();
- expect(desktopMutationCapabilities({ type, token, companionToken: "invalid" })).toBeNull();
- expect(desktopMutationCapabilities({ type, companionToken })).toBeNull();
- expect(desktopMutationCapabilities({ type: "other", token, companionToken })).toBeNull();
-});
diff --git a/server/desktop-mutation-capabilities.ts b/server/desktop-mutation-capabilities.ts
deleted file mode 100644
index 577be09965..0000000000
--- a/server/desktop-mutation-capabilities.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-const capabilityPattern = /^[A-Za-z0-9_-]{43}$/;
-
-export function desktopMutationCapabilities(message: unknown) {
- if (!message || typeof message !== "object" || Array.isArray(message)) return null;
- const { type, token, companionToken } = message as Record<string, unknown>;
- if (type !== "openmausbot:desktop-mutation-token" ||
- typeof token !== "string" || !capabilityPattern.test(token) ||
- typeof companionToken !== "string" || !capabilityPattern.test(companionToken)) return null;
- return { token, companionToken };
-}
diff --git a/server/index.ts b/server/index.ts
index d97a0c5995..5767a3e402 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -525,7 +525,6 @@ import { createCustomDomainVerifier, customDomainIpv4, normalizeCustomDomain } f
import { allowedScopes, createEmailSignIn, parseAllowList } from "./account-signin.ts";
import { pairingLinkBase, signInMailTarget } from "./pairing-base.ts"; import { lanUrl, listenHost } from "./lan-address.ts"; import { createTailnetShare } from "./tailnet-listener.ts";
import { ProviderAuthSessions } from "./provider-auth-sessions.ts"; import { createSignInTrace } from "./sign-in-trace.ts";
-import { desktopMutationCapabilities } from "./desktop-mutation-capabilities.ts";
import {
clearSessionCookie,
isLoopbackHost,
@@ -1406,8 +1405,6 @@ type UtilityParentPort = {
// Only Electron's utility process supplies parentPort, private to the desktop main process; plain Node leaves it absent.
const utilityParentPort = (process as NodeJS.Process & { parentPort?: UtilityParentPort }).parentPort; const linkLimits = createLinkLimits({ cloud: () => Boolean(CLOUD_HOME) || botLink.link.role() === "acceptor", node: (id) => coordinator.node(id), confinable: (bot) => registry.get(store.bot(bot.id)?.modelSelection.instanceId ?? "")?.adapter.capabilities.guestTurns === "confined" });
type DesktopPrivateMessage = BrowserCleanupWireRequest | import("./login-handoff.ts").LoginHandoffResult | {
- type: "openmausbot:desktop-mutation-token-accepted";
-} | {
type: "openmausbot:browser-control";
botId: string;
held: true;
@@ -1445,12 +1442,15 @@ function postDesktopPrivateMessage(message: DesktopPrivateMessage): boolean {
}
function applyDesktopMutationTokenMessage(raw: unknown): boolean {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
- if ((raw as Record<string, unknown>).type !== "openmausbot:desktop-mutation-token") return false;
- const capabilities = desktopMutationCapabilities(raw);
- if (!capabilities) throw new Error("invalid desktop mutation capabilities");
- desktopMutationToken = capabilities.token;
- companionMutationToken = capabilities.companionToken;
- postDesktopPrivateMessage({ type: "openmausbot:desktop-mutation-token-accepted" });
+ const message = raw as Record<string, unknown>;
+ if (message.type !== "openmausbot:desktop-mutation-token") return false;
+ if (typeof message.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(message.token)) {
+ throw new Error("invalid desktop mutation capability");
+ }
+ desktopMutationToken = message.token;
+ if (typeof message.companionToken === "string" && /^[A-Za-z0-9_-]{43}$/.test(message.companionToken)) {
+ companionMutationToken = message.companionToken;
+ }
return true;
}
const browserCleanup: BrowserCleanupCoordinator = new BrowserCleanupCoordinator({
diff --git a/server/places/place-proxy.ts b/server/places/place-proxy.ts
index 01b7a64154..5e9c1aad8f 100644
--- a/server/places/place-proxy.ts
+++ b/server/places/place-proxy.ts
@@ -16,7 +16,6 @@ import { timingSafeEqual } from "node:crypto";
import type { ServerResponse } from "node:http";
import { intoPlace, isPlaceId, outOfPlace, ownId, PLACE_FILE_PREFIX, PLACE_KEY } from "../../shared/place-ids.ts";
-import { desktopMutationCapabilities } from "../desktop-mutation-capabilities.ts";
import { fromOwnPage } from "../request-auth.ts";
import { userError, type UserErrorKey } from "../user-errors.ts";
import { PASS, type RouteContext, type RouteHandler } from "../routes/table.ts";
@@ -448,8 +447,7 @@ export function listenPlacePort(port: Port | undefined, proxy: PlaceProxy = plac
const message = event.data;
const session = parsePlaceSession(message);
if (session !== undefined) { proxy.setSession(session); return; }
- const capabilities = desktopMutationCapabilities(message);
- if (capabilities) proxy.setOwnerToken(capabilities.token);
+ if (record(message) && message.type === "openmausbot:desktop-mutation-token" && typeof message.token === "string") proxy.setOwnerToken(message.token);
});
}
listenPlacePort((process as NodeJS.Process & { parentPort?: Port }).parentPort);
diff --git a/server/testing/desktop-parent.mjs b/server/testing/desktop-parent.mjs
index 8a1375d5eb..1caa27330e 100644
--- a/server/testing/desktop-parent.mjs
+++ b/server/testing/desktop-parent.mjs
@@ -5,11 +5,9 @@
// OMB_TEST_DESKTOP_TAILNET_SHARE: the share on the tailnet the app asks its server for, as JSON.
// OMB_TEST_DESKTOP_CUA_CONNECTION: a file holding the app's driver record; the app hands it to its own server, and again
// each time the file changes, as the real app does each time its driver changes.
-import { randomBytes } from "node:crypto";
import { readFileSync, unwatchFile, watchFile } from "node:fs";
const token = process.env.OMB_TEST_DESKTOP_OWNER_TOKEN;
-const companionToken = randomBytes(32).toString("base64url");
const pages = process.env.OMB_TEST_DESKTOP_PAGES_ACCESS;
const cuaFile = process.env.OMB_TEST_DESKTOP_CUA_CONNECTION;
const tailnetShare = process.env.OMB_TEST_DESKTOP_TAILNET_SHARE;
@@ -40,7 +38,7 @@ if (token || cuaFile) {
on(event, listener) {
if (event !== "message") return;
listeners.push(listener);
- if (token) queueMicrotask(() => listener({ data: { type: "openmausbot:desktop-mutation-token", token, companionToken } }));
+ if (token) queueMicrotask(() => listener({ data: { type: "openmausbot:desktop-mutation-token", token } }));
if (pages) queueMicrotask(() => listener({ data: { type: "openmausbot:included-pages", access: JSON.parse(pages) } }));
if (cuaFile) queueMicrotask(() => listener({ data: cuaGrant() }));
if (tailnetShare) queueMicrotask(() => listener({ data: { type: "openmausbot:tailnet-share", share: JSON.parse(tailnetShare) } }));