Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Lent MCP: never reach the computer's own ports or a system port
aivsomkare20182ba484c
diff --git a/electron/computer-sharing.d.mts b/electron/computer-sharing.d.mtsindex 2f715e9e2f..e6cb85979e 100644--- a/electron/computer-sharing.d.mts+++ b/electron/computer-sharing.d.mts@@ -118,6 +118,8 @@ export function createComputerSharing(options: {WebSocket?: typeof globalThis.WebSocket;/** The Chrome door's options, for tests: an object with `open` stands in for the door. */chrome?: Parameters<typeof import("./device-chrome.mjs").createChromeDoor>[0];+ /** The ports this app's own OpenMausBot server is on now: a lent MCP server is never reached there. */+ serverPorts?: () => number[];/** This computer's own check on each connection, for tests: how it looks names up and connects. */egress?: Omit<NonNullable<Parameters<typeof import("./device-egress.mjs").createDeviceEgress>[0]>, "seenAs">;/** The saved server that is the person's own My Cloud: the move's project folders are lent to it. */diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjsindex 8394aab5a2..e8cd5a9f4b 100644--- a/electron/computer-sharing.mjs+++ b/electron/computer-sharing.mjs@@ -5,7 +5,7 @@ import os from "node:os";import { randomBytes, randomUUID } from "node:crypto";import { setTimeout as delay } from "node:timers/promises";import { createSharedCua, executeSharedOperation, personalSecretPaths, sharedComputerError, validCommandSeconds } from "./shared-computer-access.mjs";-import { createLentMcp, LENT_MCP_ACTIONS, validLentMcpServer } from "./lent-mcp.mjs";+import { createLentMcp, LENT_MCP_ACTIONS, ownPorts, validLentMcpServer } from "./lent-mcp.mjs";import { sharedCuaConnection } from "./shared-cua-connection.mjs";export { sharedCuaConnection };import { createLendingActivity, describeSharedOperation } from "./lending-activity.mjs";@@ -213,7 +213,7 @@ const BROWSE_NOTE_MS = 10 * 60_000;* own prompt, `startScreen()` starts computer control again (its state after), and `confirmTerminal()` turns on* running commands once the person confirms it here. */export function createComputerSharing({ file, fetch: fetchImpl, environments, localEnvironments = () => [], cuaConnection, hostControl, screenLocked = () => false, idleSeconds = () => null, protectedPaths = [], enabled = async () => false, home = os.homedir(), activityFile, cloud = () => null, onChange = () => {}, reconnect = null, now = Date.now, power = createCloudPowerGate(),- linkHeaders = () => ({}), WebSocket: linkSocket = globalThis.WebSocket, egress = {}, chrome = {}, myCloud = () => null, ownClouds = () => [], screen = () => false, askForScreen = () => {}, cloudPower = () => null,+ linkHeaders = () => ({}), WebSocket: linkSocket = globalThis.WebSocket, egress = {}, chrome = {}, serverPorts = () => [], myCloud = () => null, ownClouds = () => [], screen = () => false, askForScreen = () => {}, cloudPower = () => null,prompt = async () => null, startScreen = async () => null, confirmTerminal = async () => false, log = () => {}, t = nativeText.englishText.t }) {const protectedRoots = [path.dirname(file), ...protectedPaths.filter(entry => typeof entry === "string" && entry), ...personalSecretPaths(home)];const activity = createLendingActivity(activityFile ?? path.join(path.dirname(file), "lending-activity.jsonl"));@@ -521,7 +521,7 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, lolive.cua = createSharedCua(mcp, { t });}return live.cua;- }, () => (live.mcp ??= createLentMcp()));+ }, () => (live.mcp ??= createLentMcp({ ports: () => ownPorts({ serverPorts: serverPorts() }) })));} catch (error) { result = sharedComputerError(error); live.cua?.close(); live.cua = null; }finally {clearInterval(heartbeat); ended = true;diff --git a/electron/lent-mcp.d.mts b/electron/lent-mcp.d.mtsindex 025c204b11..55b03a9e08 100644--- a/electron/lent-mcp.d.mts+++ b/electron/lent-mcp.d.mts@@ -6,12 +6,15 @@ export function validLentMcpServer(server: unknown): server is LentMcpServer;export function isLoopbackAddress(url: string): boolean;export function lentMcpRefusal(grant: { cloud?: unknown; terminal?: boolean }, server: LentMcpServer): string | null;export function ownEnvironmentIds(dataDirs: ReadonlyArray<string | null | undefined>): string[];+export function ownPorts(options?: { serverPorts?: number[]; dirs?: string[]; readFile?: (file: string, encoding: "utf8") => Promise<string> }): Promise<number[]>;export function inheritedEnvironment(env?: NodeJS.ProcessEnv): Record<string, string>;export function windowsLaunch(command: string, args: string[], env: Record<string, string | undefined>, exists?: (file: string) => boolean): { file: string; args: string[]; verbatim: boolean } | null;export function createLentMcp(options?: {environment?: () => Record<string, string> | Promise<Record<string, string>>;home?: string;fetch?: typeof fetch;+ /** The ports a URL server is refused on: this computer's own. */+ ports?: () => Promise<number[]>;}): {call(operation: { action: "mcp_tools" | "mcp_call"; server: LentMcpServer; tool_name?: string; arguments?: Record<string, unknown> }, signal: AbortSignal): Promise<unknown>;close(): Promise<void>;diff --git a/electron/lent-mcp.mjs b/electron/lent-mcp.mjsindex b0dca6c46f..15c9faf8de 100644--- a/electron/lent-mcp.mjs+++ b/electron/lent-mcp.mjs@@ -8,6 +8,8 @@ import fs from "node:fs";import os from "node:os";import path from "node:path";import readline from "node:readline";+import { chromeDataDirs, DEVTOOLS_FILE, parseDevtoolsActivePort } from "./device-chrome.mjs";+import { DESKTOP_PORTS } from "./desktop-ports.mjs";import { commandPath } from "./shell-path.mjs";export const LENT_MCP_ACTIONS = new Set(["mcp_tools", "mcp_call"]);@@ -24,6 +26,9 @@ const IDLE_MS = 10 * 60_000;const RESULT_LIMIT = 3_900_000;const MAX_PAGES = 10;const PROTOCOL = "2025-03-26";+/** Security: a port under 1024 is a system service's, and this computer's own OpenMausBot server and Chrome's DevTools+ * take commands from any local caller, so a lent address on one of them would hand a Cloud's bot this computer. */+const OWN_PORT = "Only an MCP server on its own port (1024 or higher) at this computer's address can be reached, never this computer's own OpenMausBot or Chrome ports";/** What a lent server inherits from this app: where things live, never a key. */const INHERITED = ["HOME", "USERPROFILE", "USER", "LOGNAME", "SHELL", "LANG", "TMPDIR", "TEMP", "TMP", "PATHEXT", "SystemRoot", "SystemDrive", "windir", "ComSpec", "APPDATA", "LOCALAPPDATA", "ProgramData"];@@ -57,9 +62,16 @@ export function lentMcpRefusal(grant, server) {if ("command" in server) return grant.terminal === true ? null : "Running commands is not enabled for this server";if (!isLoopbackAddress(server.url)) return "Only an MCP server at this computer's own address (127.0.0.1, localhost or ::1) can be reached";if (server.type === "sse") return "This MCP server uses the older SSE transport, which lending doesn't carry yet";+ if (Number(new URL(server.url).port) < 1024) return OWN_PORT;return null;}+/** This computer's own ports: its OpenMausBot servers', and Chrome's DevTools port while Chrome is running. */+export async function ownPorts({ serverPorts = [], dirs = chromeDataDirs({ platform: process.platform, home: os.homedir(), localAppData: process.env.LOCALAPPDATA }), readFile = fs.promises.readFile } = {}) {+ const chrome = await Promise.all(dirs.map(dir => readFile(path.join(dir, DEVTOOLS_FILE), "utf8").then(parseDevtoolsActivePort, () => null)));+ return [...DESKTOP_PORTS, ...serverPorts, ...chrome.flatMap(found => (found ? [found.port] : []))];+}+/** This computer's own OpenMausBot installs, by the environment id each keeps in its data folder. */export function ownEnvironmentIds(dataDirs) {const ids = new Set();@@ -229,7 +241,7 @@ function httpClient(server, { fetch: fetchImpl }) {/** The servers one lent Cloud keeps here, each started once and kept between calls; a change to one starts it anew, and* one unused for ten minutes is stopped. */-export function createLentMcp({ environment = async () => ({ ...inheritedEnvironment(), PATH: await commandPath() }), home = os.homedir(), fetch: fetchImpl = globalThis.fetch } = {}) {+export function createLentMcp({ environment = async () => ({ ...inheritedEnvironment(), PATH: await commandPath() }), home = os.homedir(), fetch: fetchImpl = globalThis.fetch, ports = ownPorts } = {}) {const running = new Map();const stop = name => {const live = running.get(name);@@ -272,6 +284,7 @@ export function createLentMcp({ environment = async () => ({ ...inheritedEnvironreturn {async call(operation, signal) {const { server } = operation;+ if ("url" in server && (await ports()).includes(Number(new URL(server.url).port))) throw failure(OWN_PORT);if (operation.action === "mcp_tools") {return use(server, signal, async client => {const tools = [];diff --git a/electron/lent-mcp.node-test.mjs b/electron/lent-mcp.node-test.mjsindex ca41dbdf09..bce15345cd 100644--- a/electron/lent-mcp.node-test.mjs+++ b/electron/lent-mcp.node-test.mjs@@ -5,7 +5,7 @@ import { mkdtemp, mkdir, realpath, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import { randomUUID } from "node:crypto";-import { createLentMcp, inheritedEnvironment, isLoopbackAddress, lentMcpRefusal, ownEnvironmentIds, validLentMcpServer, windowsLaunch } from "./lent-mcp.mjs";+import { createLentMcp, inheritedEnvironment, isLoopbackAddress, lentMcpRefusal, ownEnvironmentIds, ownPorts, validLentMcpServer, windowsLaunch } from "./lent-mcp.mjs";import { executeSharedOperation } from "./shared-computer-access.mjs";import { validSharedOperation } from "./computer-sharing.mjs";@@ -70,6 +70,36 @@ test("security: only the person's own Cloud, a command only with the terminal leassert.match(lentMcpRefusal(cloud, { ...http("http://127.0.0.1:1/sse"), type: "sse" }), /older SSE transport/);});+const OWN_PORT = /^Only an MCP server on its own port \(1024 or higher\) at this computer's address can be reached, never this computer's own OpenMausBot or Chrome ports$/;++test("security: an address only on its own port, 1024 or higher, never one left to its default", () => {+ const cloud = { cloud: { accountId: "a", origin: "https://x" }, terminal: false };+ for (const url of ["http://127.0.0.1/mcp", "http://127.0.0.1:80/mcp", "https://localhost/mcp", "http://localhost:443/mcp", "http://[::1]:1023/mcp", "http://[::1]/mcp", "http://127.0.0.1:0/mcp"]) {+ assert.match(lentMcpRefusal(cloud, http(url)) ?? "", OWN_PORT, url);+ }+ for (const url of ["http://127.0.0.1:19501/mcp", "http://localhost:19501/mcp", "http://[::1]:19501/mcp", "https://127.0.0.1:1024/mcp"]) assert.equal(lentMcpRefusal(cloud, http(url)), null, url);+});++test("security: never this computer's own OpenMausBot ports or Chrome's DevTools port, and nothing is fetched", async t => {+ const dir = await realpath(await mkdtemp(path.join(tmpdir(), "omb-lent-mcp-ports-")));+ t.after(() => rm(dir, { recursive: true, force: true }));+ const chrome = path.join(dir, "Google", "Chrome");+ await mkdir(chrome, { recursive: true });+ await writeFile(path.join(chrome, "DevToolsActivePort"), "9333\n/devtools/browser/0b1c2d3e-aaaa-4bbb-8ccc-0123456789ab");+ const ports = await ownPorts({ serverPorts: [41234], dirs: [chrome, path.join(dir, "Brave")] });+ assert.deepEqual([...ports].sort((a, b) => a - b), [8799, 9333, 18799, 28799, 41234]);+ let fetched = 0;+ const fetch = async () => { fetched++; throw new Error("never fetched"); };+ const lent = createLentMcp({ ports: () => ownPorts({ serverPorts: [41234], dirs: [chrome] }), fetch });+ for (const url of ["http://127.0.0.1:8799/mcp", "http://localhost:18799/mcp", "http://[::1]:41234/mcp", "http://127.0.0.1:9333/json/new"]) {+ await assert.rejects(lent.call({ action: "mcp_tools", server: http(url) }, signal()), error => OWN_PORT.test(error.message), url);+ }+ await assert.rejects(createLentMcp({ fetch }).call({ action: "mcp_call", server: http("http://127.0.0.1:8799/api/config"), tool_name: "x" }, signal()), error => OWN_PORT.test(error.message), "the desktop's ports by default");+ assert.equal(fetched, 0);+ await assert.rejects(lent.call({ action: "mcp_tools", server: http("http://127.0.0.1:19501/mcp") }, signal()), /local is not answering/);+ assert.equal(fetched, 1, "a port of its own is reached");+});+test("the executor refuses before anything starts when the grant doesn't allow it", async () => {let started = 0;const grant = { enabled: true, folders: [], terminal: false, computer: false, cloud: { accountId: "a", origin: "https://x" } };diff --git a/electron/main.mjs b/electron/main.mjsindex e8622dbd0f..35bf4ced81 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -1444,7 +1444,7 @@ function sharingController() {protectedPaths: [desktopDataDir(), cleanWorkspaceDir(desktopDataDir()), profilesDir(desktopDataDir())],fetch: (...args) => session.defaultSession.fetch(...args),environments: () => environmentsState.environments, localEnvironments: () => ownEnvironmentIds([desktopDataDir(), runningDataDir]),- enabled: refreshSharedComputersAllowed, t: nativeT,+ enabled: refreshSharedComputersAllowed, t: nativeT, serverPorts: () => [SERVER_PORT],cloud: lendingTarget.cloud, myCloud: lendingTarget.environment, ownClouds: lendingTarget.places, screen: screenControl.now, askForScreen, power: cloudPower, cloudPower: origin => cloudAccount?.powerOf?.(origin) ?? null, reconnect: reconnectCloud,prompt: createAskPrompt({ t: nativeT, dialog, window: () => mainWindow, idleSeconds: () => powerMonitor.getSystemIdleState(1) === "unknown" ? null : powerMonitor.getSystemIdleTime() }), startScreen: screenControl.start, confirmTerminal: () => lendingDialogs.lendTerminal(true, () => sharingController().lendTerminal(true)), log: slog,linkHeaders: async env => ({ cookie: (await session.defaultSession.cookies.get({ url: env.origin })).map(cookie => `${cookie.name}=${cookie.value}`).join("; ") }),diff --git a/server/lent-mcp.test.ts b/server/lent-mcp.test.tsindex 8e12202f53..cc321f5428 100644--- a/server/lent-mcp.test.ts+++ b/server/lent-mcp.test.ts@@ -104,6 +104,18 @@ describe("a server that runs on the person's computer, in a turn", () => {expect(say({})).toEqual([["local"], { notes: "notes starts a program on your Mac (Ada's Mac), which doesn't let My Cloud run programs right now: turn on \"Let Clouds run commands on this Mac\" from the OpenMausBot icon on that Mac." }]);});+ it("an address with no port of its own, 1024 or higher, is refused here in plain words before any job goes out", async () => {+ const line = (name: string) => `${name} runs on your Mac (Ada's Mac), which reaches only an MCP server on its own port, 1024 or higher, at that Mac's address: save ${name} with the port its server listens on.`;+ const servers = { local, web: { ...local, url: "http://127.0.0.1/mcp" }, tls: { ...local, url: "https://localhost/mcp" }, low: { ...local, url: "http://[::1]:1023/mcp" } };+ const { lent, requests } = fixture({ servers });+ expect(Object.keys(lent.mounts({ id: "kiwi" }, TURN))).toEqual(["local"]);+ expect(Object.fromEntries(lent.lines({ id: "kiwi" }, TURN))).toEqual({ web: line("web"), tls: line("tls"), low: line("low") });+ const called = await route(lent, `${LENT_MCP_PATH}web`, rpc("tools/call", { name: "search" }));+ expect(called.json.mock.calls[0]![2].result).toEqual({ content: [{ type: "text", text: line("web") }], isError: true });+ expect(await lent.test("low", servers.low, "cloud-home", new AbortController().signal)).toEqual({ status: 409, error: line("low") });+ expect(requests.map((request) => (request.operation.server as { url: string }).url)).toEqual(["http://127.0.0.1:19501/mcp"]);+ });+it("a bot with no server on another computer costs its turn nothing: the lending gate isn't asked", () => {const asked = vi.fn(() => "cloud-home");const lent = createLentMcp({ cfg: () => ({ mcpServers: { web: { type: "http", url: "https://mcp.example.com/mcp", headers: {}, enabled: true } } }), computers: { runsOn: vi.fn(), mcpLenders: vi.fn(), request: vi.fn() } as unknown as LentMcpDeps["computers"],@@ -203,6 +215,14 @@ describe("Test, and adding a server that needs the person's computer", () => {expect(await fixture().lent.place(address, { principal: "cloud-home" }), "nothing lent now: it stays as added").toEqual({ ok: true, server: address });});+ it("refuses a loopback address for the lent computer on a port below 1024 or with none, saying how to add it", async () => {+ const one = fixture({ lenders: [lender("Ada's Mac", "s-mac", MAC.environmentId, 2)] });+ for (const url of ["http://127.0.0.1/mcp", "http://localhost:80/mcp", "https://[::1]/mcp", "http://127.0.0.1:1023/mcp"]) {+ expect(await one.lent.place({ ...address, url }, { principal: "cloud-home" }), url).toEqual({ ok: false, error: "This server runs on the person's own computer, which reaches only an MCP server on its own port, 1024 or higher: add it again with the port its server listens on in its address." });+ }+ expect(await one.lent.place({ ...address, url: "http://localhost:19501/mcp" }, { principal: "cloud-home" })).toMatchObject({ ok: true, server: { runsOn: MAC } });+ });+it("with several lent: the one named, else the one the adder is on, else the newest for the person, else the bot asks", async () => {const studio = "33333333-3333-4333-8333-333333333333";const { lent } = fixture({ lenders: [lender("Studio", "s-studio", studio, 3), lender("Ada's Mac", "s-mac", MAC.environmentId, 2)] });diff --git a/server/lent-mcp.ts b/server/lent-mcp.tsindex af6ea951be..b68406f825 100644--- a/server/lent-mcp.ts+++ b/server/lent-mcp.ts@@ -36,6 +36,12 @@ export function isLoopbackUrl(url: string): boolean {} catch { return false; }}+/** Security: a lent computer reaches a URL server only on a port of its own, 1024 or higher; one left to its default is a+ * system service's. */+function onItsOwnPort(url: string): boolean {+ try { return Number(new URL(url).port) >= 1024; } catch { return false; }+}+export interface HereChecks {exists(path: string): boolean;/** A program by its bare name is on this server's PATH. */@@ -93,13 +99,14 @@ export function elsewhereServers(cfg: Pick<AppConfig, "mcpServers">, bot: Bot):export type LentState =| { kind: "ready"; computerId: string }- | { kind: "offline" | "stopped" | "never" | "outdated" | "no-terminal"; computer: string; device: "Mac" | "PC" | "computer" };+ | { kind: "offline" | "stopped" | "never" | "outdated" | "no-terminal" | "port"; computer: string; device: "Mac" | "PC" | "computer" };export function lentState(computers: Pick<SharedComputers, "runsOn">, principal: string | null, server: ElsewhereServer): LentState {const { online, known } = computers.runsOn(principal, server.runsOn);const at = (platform: LentPlatform | null | undefined, name: string) => ({ computer: name, device: deviceWord(platform) });if (online) {if (!online.mcpServers) return { kind: "outdated", ...at(online.platform, online.name) };+ if (isRemoteMcpServer(server) && !onItsOwnPort(server.url)) return { kind: "port", ...at(online.platform, online.name) };if (!isRemoteMcpServer(server) && !online.terminal) return { kind: "no-terminal", ...at(online.platform, online.name) };return { kind: "ready", computerId: online.id };}@@ -116,6 +123,7 @@ export function lentLine(name: string, state: Exclude<LentState, { kind: "ready"case "stopped": return `${name} runs on ${theirs}, which no longer lends itself to ${place}: OpenMausBot on it is paused or signed out.`;case "never": return `${name} runs on ${theirs}, which isn't lent to ${place}: it works once OpenMausBot is open on that computer and signed in to ${place}.`;case "outdated": return `${name} runs on ${theirs}, whose OpenMausBot is too old to run it for ${place}: update OpenMausBot on that ${device}.`;+ case "port": return `${name} runs on ${theirs}, which reaches only an MCP server on its own port, 1024 or higher, at that ${device}'s address: save ${name} with the port its server listens on.`;case "no-terminal": return `${name} starts a program on ${theirs}, which doesn't let ${place} run programs right now: turn on "Let Clouds run commands on this ${device}" from the OpenMausBot icon on that ${device}.`;}}@@ -277,6 +285,7 @@ export function createLentMcp(deps: LentMcpDeps) {if (server.runsOn || !who.principal) return { ok: true, server };const lenders = deps.computers.mcpLenders(who.principal);if (!lenders.length || !(await needsTheirComputer(server, here))) return { ok: true, server };+ if (isRemoteMcpServer(server) && !onItsOwnPort(server.url)) return { ok: false, error: "This server runs on the person's own computer, which reaches only an MCP server on its own port, 1024 or higher: add it again with the port its server listens on in its address." };const asked = who.computer?.trim().toLowerCase();const named = asked ? lenders.find((lender) => lender.name.toLowerCase() === asked) : undefined;const names = lenders.map((lender) => lender.name).join(", ");