Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep a bot's new MCP server behind the card unless it is at a public address
milind-soni0c86711c3412
diff --git a/server/index.test.ts b/server/index.test.tsindex 298d206034..e3fa0d8375 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -8590,7 +8590,7 @@ describe("harness HTTP API", () => {expect(after).toEqual({ status: 200, body: { servers: [] } });});- it("lets a bot below Full access file a command server only as a disabled row, and turns a URL server on", async () => {+ it("lets a bot below Full access file a command server or a URL on the person's network only as a disabled row", async () => {const bot = (await api("POST", "/api/bots")).body.bot;expect((await api("PATCH", `/api/bots/${bot.id}`, { approvalMode: "ask" })).status).toBe(200);const token = await mintTestCapability(BASE, bot.id, bot.threadId);@@ -8625,27 +8625,27 @@ describe("harness HTTP API", () => {const remote = await fileServer({name: "botdocs",- url: "https://docs.example/mcp",+ url: "https://docs.internal/mcp",type: "sse",headers: { Authorization: headerSecret },oauth: { clientId: "corp-app", clientSecret: oauthSecret },});const remoteBody = await remote.json() as { text: string };expect(remote.status).toBe(201);- expect(remoteBody.text).toMatch(/^Added MCP server botdocs and turned it on\./);+ expect(remoteBody.text).toMatch(/^Saved MCP server botdocs switched off\./);const remoteText = JSON.stringify(remoteBody);expect(remoteText).not.toContain(headerSecret);expect(remoteText).not.toContain(oauthSecret);const savedRemote = JSON.parse(readFileSync(configFile, "utf8")).mcpServers.botdocs;expect(savedRemote).toEqual({- type: "sse", url: "https://docs.example/mcp", headers: { Authorization: headerSecret },- oauth: { clientId: "corp-app", clientSecret: oauthSecret }, enabled: true,+ type: "sse", url: "https://docs.internal/mcp", headers: { Authorization: headerSecret },+ oauth: { clientId: "corp-app", clientSecret: oauthSecret }, enabled: false,});const listed = await api("GET", "/api/mcp/servers");expect(listed.body.servers).toEqual(expect.arrayContaining([expect.objectContaining({ name: "botnotes", enabled: false, envKeys: ["NOTES_TOKEN"] }),- expect.objectContaining({ name: "botdocs", enabled: true, headerKeys: ["Authorization"] }),+ expect.objectContaining({ name: "botdocs", enabled: false, headerKeys: ["Authorization"] }),]));expect(JSON.stringify(listed.body)).not.toContain(secret);expect(JSON.stringify(listed.body)).not.toContain(headerSecret);diff --git a/server/mcp-public-url.test.ts b/server/mcp-public-url.test.tsnew file mode 100644index 0000000000..5248ad7814--- /dev/null+++ b/server/mcp-public-url.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it, vi } from "vitest";++import { publicMcpUrl, type HostLookup } from "./mcp-public-url.ts";++const table: Record<string, string[]> = {+ "mcp.example.com": ["34.117.59.81", "2606:4700:4700::1111"],+ "intranet.example.com": ["10.1.2.3"],+ "mixed.example.com": ["34.117.59.81", "127.0.0.1"],+ "empty.example.com": [],+};+const lookup: HostLookup = vi.fn(async (host: string) => {+ const addresses = table[host];+ if (!addresses) throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${host}`), { code: "ENOTFOUND" });+ return addresses.map((address) => ({ address }));+});++describe("publicMcpUrl", () => {+ it.each([+ "https://mcp.example.com/mcp",+ "https://mcp.example.com./mcp?team=acme",+ "https://34.117.59.81/mcp",+ "https://[2606:4700:4700::1111]/mcp",+ ])("counts %s as public", async (url) => {+ await expect(publicMcpUrl(url, lookup)).resolves.toBe(true);+ });++ it.each([+ "http://mcp.example.com/mcp",+ "http://localhost:3000/mcp",+ "https://localhost/mcp",+ "https://app.localhost/mcp",+ "https://127.0.0.1:8799/mcp",+ "https://192.168.1.5/mcp",+ "https://[::1]/mcp",+ "https://[::ffff:127.0.0.1]/mcp",+ "https://printer.local/mcp",+ "https://wiki.internal/mcp",+ "https://nas.lan/mcp",+ "https://router.home.arpa/mcp",+ "https://box.tail1234.ts.net/mcp",+ "https://intranet.example.com/mcp",+ "https://mixed.example.com/mcp",+ "https://empty.example.com/mcp",+ "https://unknown.example.com/mcp",+ "not a url",+ ])("keeps %s behind the person's yes", async (url) => {+ await expect(publicMcpUrl(url, lookup)).resolves.toBe(false);+ });++ it("decides a local name or an address literal without asking DNS", async () => {+ vi.mocked(lookup).mockClear();+ for (const url of ["https://printer.local/mcp", "https://192.168.1.5/mcp", "https://34.117.59.81/mcp", "http://mcp.example.com/mcp"]) await publicMcpUrl(url, lookup);+ expect(lookup).not.toHaveBeenCalled();+ });+});diff --git a/server/mcp-public-url.ts b/server/mcp-public-url.tsnew file mode 100644index 0000000000..9c86c40ddb--- /dev/null+++ b/server/mcp-public-url.ts@@ -0,0 +1,28 @@+// Whether an MCP server's address is out on the public internet. Below Full access a bot may turn on such a server+// itself, since it only connects to an address anyone could reach; one on the person's own computer or network (loopback,+// a LAN address, a local name) stays behind the person's yes. Anything unclear counts as not public, so it keeps the card.+import { lookup as dnsLookup } from "node:dns/promises";+import { isIP } from "node:net";++import { isPublicDomainAddress } from "./custom-domain.ts";++/** Every address a host name resolves to. */+export type HostLookup = (host: string) => Promise<ReadonlyArray<{ address: string }>>;++const LOCAL_NAME = /(?:^|\.)(?:localhost|local|internal|lan|home\.arpa|ts\.net)$/;+const lookupAll: HostLookup = (host) => dnsLookup(host, { all: true, verbatim: true });++export async function publicMcpUrl(raw: string, lookup: HostLookup = lookupAll): Promise<boolean> {+ let url: URL;+ try { url = new URL(raw); } catch { return false; }+ if (url.protocol !== "https:") return false;+ const host = url.hostname.replace(/^\[|\]$/g, "").replace(/\.$/, "").toLowerCase();+ if (!host || LOCAL_NAME.test(host)) return false;+ if (isIP(host)) return isPublicDomainAddress(host);+ try {+ const addresses = await lookup(host);+ return addresses.length > 0 && addresses.every((entry) => isPublicDomainAddress(entry.address));+ } catch {+ return false;+ }+}diff --git a/server/routes/internal-mcp.test.ts b/server/routes/internal-mcp.test.tsindex 22f028f982..2a3a2644aa 100644--- a/server/routes/internal-mcp.test.ts+++ b/server/routes/internal-mcp.test.ts@@ -32,6 +32,8 @@ const PATH_TOKEN = "Zk9QxW2mT7aBcD4eF6gH8jK1";const USER_TOKEN = "tok3n9876userinfo";const zapier = { type: "http", url: `https://mcp.zapier.com/api/mcp/s/${PATH_TOKEN}/mcp`, headers: { "X-Api-Key": "zap-header-value" }, enabled: true };const userinfo = `https://ada:${USER_TOKEN}@mcp.example.com/mcp-server-production/mcp`;+/** The fixture's DNS: a public name, a name on the person's network, and one that resolves to both. Others fail. */+const DNS: Record<string, string[]> = { "mcp.linear.app": ["34.117.59.81"], "intranet.example": ["10.0.0.5"], "split.example": ["34.117.59.81", "192.168.1.9"] };interface Options {full?: boolean;@@ -124,6 +126,11 @@ function fixture(options: Options = {}) {},...(options.lender !== undefined ? { lender: () => options.lender ?? null } : {}),...(options.place ? { place: options.place } : {}),+ lookupHost: async (host) => {+ const addresses = DNS[host];+ if (!addresses) throw Object.assign(new Error(`getaddrinfo ENOTFOUND ${host}`), { code: "ENOTFOUND" });+ return addresses.map((address) => ({ address }));+ },};const route = createInternalMcpRoutes(deps);const ref = (value: string) => vault.saveRef(owner, `card-${value}`, "Key", value);@@ -652,6 +659,22 @@ describe("internal mcp_server route, below Full access", () => {expect(chat).toHaveLength(0);});+ it.each([+ "http://localhost:3000/mcp", "https://192.168.1.5/mcp", "http://docs.example/mcp", "https://127.0.0.1:8799/mcp",+ "https://printer.local/mcp", "https://intranet.example/mcp", "https://split.example/mcp", "https://nowhere.example/mcp",+ ])("a non-Full add of %s, not a public https address, saves it off and posts a Turn on card", async (url) => {+ const probe = probeWith({ ok: true, tools: [] });+ const { post, stored, chat, card, decided } = fixture({ full: false });+ const { status, body } = await post({ action: "add", name: "local", type: "http", url });+ expect(status).toBe(201);+ expect(stored("local")?.enabled).toBe(false);+ expect(probe).not.toHaveBeenCalled();+ expect(body.text).toContain(PROPOSED);+ expect(decided).toEqual([]);+ expect(chat).toHaveLength(1);+ expect(card()).toMatchObject({ title: "Turn on local?", options: ["Turn on", "Cancel"], mcpRequest: { action: "enable", name: "local" } });+ });+it("a non-Full add of a command server saves it off and posts a Turn on card, since turning it on runs a program", async () => {const probe = probeWith({ ok: true, tools: [] });const { post, stored, lines, chat, card } = fixture({ full: false });diff --git a/server/routes/internal-mcp.ts b/server/routes/internal-mcp.tsindex b017cd8be1..ad9336591f 100644--- a/server/routes/internal-mcp.ts+++ b/server/routes/internal-mcp.ts@@ -11,6 +11,7 @@ import type { BotKept, BotMcpServerAdd } from "../mcp-bot-servers.ts";import { BOT_STRIPPED_KEYS, botChangeLines, botListing, botMayChange, botServerTarget, isSecretRef, mcpOwner, mergeBotUpdate } from "../mcp-bot-rules.ts";import type { McpAuthState, McpOAuthManager } from "../mcp-oauth.ts";import type { McpProbeResult } from "../mcp-probe.ts";+import { publicMcpUrl, type HostLookup } from "../mcp-public-url.ts";import { isRemoteMcpServer, parseMcpServerMutation, parseStoredMcpServer, type StoredMcpServer, type StoredRemoteMcpServer, type StoredStdioMcpServer } from "../mcp-registry.ts";import { serverLine, type ServerLineKey } from "../server-lines.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -80,6 +81,8 @@ export interface InternalMcpDeps {/** A server this bot adds that needs the person's own computer, marked as running on the one of theirs lent now* (`computer`: the one the bot names, by its name), or why it can't be added yet. */place?(server: StoredMcpServer, computer: string | undefined): Promise<{ ok: true; server: StoredMcpServer } | { ok: false; error: string }>;+ /** Resolves a server's host name to tell a public address from the person's own network; DNS when left out. */+ lookupHost?: HostLookup;}type Deps = Omit<InternalMcpDeps, "readBody">;@@ -218,9 +221,10 @@ async function add(deps: Deps, name: string, fields: Record<string, unknown>, siredeemed.commit();const where = folderText(deps, server, added.moved ?? []);- // Security: below Full access, turning on a command server (it runs a program) or a server on the person's own- // computer needs their yes; a URL server elsewhere only connects to an address.- if (!deps.fullAccess() && (!isRemoteMcpServer(server) || server.runsOn)) {+ // Security: below Full access, only a server at a public https address turns on without the person's yes. A command+ // server runs a program, and a URL on their computer or network (loopback, a LAN address, a local name) reaches it.+ const open = deps.fullAccess() || (isRemoteMcpServer(server) && !server.runsOn && await publicMcpUrl(server.url, deps.lookupHost));+ if (!open) {say(deps, { action: "add", name }, ["server.mcp.added", { name }], ["server.mcp.switchedOff"]);const card = deps.requestApproval({ action: "enable", name, subtitle: turnOnText(deps, server), targetHash: targetHash(server) });return { status: 201, text: `Saved MCP server ${name} switched off.${where} ${card.text}` };