Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: bind personal MCP key saves to the expected URL
Sebastian B56ed71f758f0
diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 0bb8c934d5..564c3f56c7 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -130,7 +130,7 @@ their team page in MausBot Cloud (the Admin's Cloud page calls the routes below| `POST /api/team/my-connections/apps/:slug/connect` | the member | `{ url }`, the app's own sign-in (a new tab) || `DELETE /api/team/my-connections/apps/:slug` | the member | || `POST /api/team/my-connections/mcp/:name/sign-in` | the member | `{ auth }`; it comes back to this server's `/mcp-oauth/callback` |-| `PUT /api/team/my-connections/mcp/:name/key { value }` | the member | write-only |+| `PUT /api/team/my-connections/mcp/:name/key { value, url }` | the member | write-only; requires the expected server URL; returns 409 if it changed || `DELETE /api/team/my-connections/mcp/:name` | the member | |The signed read (`GET /api/cloud/team/admin`) adds `scopes: { apps, mcp }` and `people: { apps: { <slug>: [address] },diff --git a/server/cloud-team-connections.e2e.test.ts b/server/cloud-team-connections.e2e.test.tsindex 397c9ddf93..aa90429909 100644--- a/server/cloud-team-connections.e2e.test.ts+++ b/server/cloud-team-connections.e2e.test.ts@@ -135,7 +135,7 @@ it("lets Ada connect her own Gmail and mail key, and nobody reads them back", asadaUser = broker.userFor(broker.installationIds().at(-1)!);expect(adaUser).not.toBe(teamUser);broker.account(adaUser, "gmail", "[email protected]");- expect((await team.as(ada, "PUT", "/api/team/my-connections/mcp/mail/key", { value: ADA_KEY })).body).toEqual({ ok: true });+ expect((await team.as(ada, "PUT", "/api/team/my-connections/mcp/mail/key", { value: ADA_KEY, url: mail.url })).body).toEqual({ ok: true });// A team app is not hers to connect, and Slack is the team's.expect((await team.as(ada, "POST", "/api/team/my-connections/apps/slack/connect", {})).status).toBe(409);@@ -298,7 +298,7 @@ it("skips automatic personal MCP probes after setup and restart while still probconst own = { type: "http", url: personal.url, headers: { Authorization: "" } };expect((await team.as(owner, "POST", "/api/mcp/servers", { name: "personal_probe", ...own })).status).toBe(201);expect((await team.as(owner, "PUT", "/api/team/connection-scopes", { kind: "mcp", id: "personal_probe", scope: "person" })).status).toBe(200);- expect((await team.as(owner, "PUT", "/api/team/my-connections/mcp/personal_probe/key", { value: ownAuthorization })).status).toBe(200);+ expect((await team.as(owner, "PUT", "/api/team/my-connections/mcp/personal_probe/key", { value: ownAuthorization, url: personal.url })).status).toBe(200);expect((await team.as(owner, "PUT", "/api/mcp/servers/personal_probe", { ...own, enabled: false })).status).toBe(200);const tested = await team.as(owner, "POST", "/api/mcp/servers/personal_probe/test", {});expect(tested.status).toBe(200);diff --git a/server/cloud-team-gateway-mcp.e2e.test.ts b/server/cloud-team-gateway-mcp.e2e.test.tsindex e7a9440411..dca687b116 100644--- a/server/cloud-team-gateway-mcp.e2e.test.ts+++ b/server/cloud-team-gateway-mcp.e2e.test.ts@@ -148,7 +148,7 @@ it("rejects shared header values on a personal OAuth-to-key edit and accepts a pexpect(JSON.stringify(saved())).not.toContain(own);}expect((await as(admin, "PUT", "/api/mcp/servers/private-mail", shared)).status).toBe(200);- expect((await as(admin, "PUT", "/api/team/my-connections/mcp/private-mail/key", { value: own })).body).toEqual({ ok: true });+ expect((await as(admin, "PUT", "/api/team/my-connections/mcp/private-mail/key", { value: own, url: mail.url })).body).toEqual({ ok: true });expect(saved().mcpServers["private-mail"]).toMatchObject({ headers: { Authorization: "" } });expect(saved().mcpServers["private-mail"].oauth).toBeUndefined();const seen = mail.seenHeaders.length;@@ -163,6 +163,27 @@ it("rejects shared header values on a personal OAuth-to-key edit and accepts a p}}, hostTimeout(60_000));+it("rejects a personal key when another admin changes the URL between the shared save and the key save", async () => {+ const otherAdmin = (await team.pair({ email: "[email protected]", role: "admin" })).token!;+ const original = { type: "http", url: "https://mail.example.com/mcp", headers: { Authorization: "" }, enabled: false };+ const changed = { ...original, url: "https://other.example.com/mcp" };+ const own = "Bearer raced-personal-key-5521";+ try {+ expect((await as(admin, "POST", "/api/mcp/servers", { name: "raced-mail", ...original })).status).toBe(201);+ expect((await as(admin, "PUT", "/api/team/connection-scopes", { kind: "mcp", id: "raced-mail", scope: "person" })).status).toBe(200);+ expect((await as(admin, "PUT", "/api/mcp/servers/raced-mail", original)).status).toBe(200);+ expect((await as(otherAdmin, "PUT", "/api/mcp/servers/raced-mail", changed)).status).toBe(200);+ const refused = await as(admin, "PUT", "/api/team/my-connections/mcp/raced-mail/key", { value: own, url: original.url });+ expect(refused.status).toBe(409);+ expect(refused.body.error).toMatch(/address changed/i);+ expect((await as(admin, "GET", "/api/team/my-connections")).body.mcp).toContainEqual(expect.objectContaining({ name: "raced-mail", connected: false }));+ const keysFile = join(team.home, ".openmausbot/people-connections/mcp-keys.json");+ expect(existsSync(keysFile) ? readFileSync(keysFile, "utf8") : "").not.toContain(own);+ } finally {+ await as(admin, "DELETE", "/api/mcp/servers/raced-mail");+ }+}, hostTimeout(30_000));+it("keeps a one-key server Only for me: the admin's own chat gets it with their key, a member's chat doesn't", async () => {let own = "Bearer ben-own-key-5521";const mail = await startFakeHttpMcp({ tools: [{ name: "read_inbox" }], acceptBearer: (authorization) => authorization === own });@@ -170,7 +191,7 @@ it("keeps a one-key server Only for me: the admin's own chat gets it with theirconst shared = { type: "http", url: mail.url, headers: { Authorization: "" }, enabled: false };expect((await as(admin, "POST", "/api/mcp/servers", { name: "mail", ...shared })).status).toBe(201);expect((await as(admin, "PUT", "/api/team/connection-scopes", { kind: "mcp", id: "mail", scope: "person" })).body).toEqual({ scopes: { apps: [], mcp: ["mail"] } });- expect((await as(admin, "PUT", "/api/team/my-connections/mcp/mail/key", { value: own })).body).toEqual({ ok: true });+ expect((await as(admin, "PUT", "/api/team/my-connections/mcp/mail/key", { value: own, url: mail.url })).body).toEqual({ ok: true });expect((await as(admin, "PUT", "/api/mcp/servers/mail", shared)).status).toBe(200);const saved = () => JSON.parse(readFileSync(join(team.home, ".openmausbot/config.json"), "utf8"));expect(saved().mcpServers.mail.headers).toEqual({ Authorization: "" });@@ -180,7 +201,7 @@ it("keeps a one-key server Only for me: the admin's own chat gets it with theirfor (const replacement of ["Bearer edited-own-key-6612", "Bearer fixed-own-key-7734"]) {own = replacement;expect((await as(admin, "PUT", "/api/mcp/servers/mail", shared)).status).toBe(200);- expect((await as(admin, "PUT", "/api/team/my-connections/mcp/mail/key", { value: replacement })).body).toEqual({ ok: true });+ expect((await as(admin, "PUT", "/api/team/my-connections/mcp/mail/key", { value: replacement, url: mail.url })).body).toEqual({ ok: true });expect(saved().mcpServers.mail.headers).toEqual({ Authorization: "" });const seen = mail.seenHeaders.length;expect((await as(admin, "POST", "/api/mcp/servers/mail/test")).body).toMatchObject({ ok: true });diff --git a/server/routes/team-connections.test.ts b/server/routes/team-connections.test.tsnew file mode 100644index 0000000000..f46bec360d--- /dev/null+++ b/server/routes/team-connections.test.ts@@ -0,0 +1,68 @@+import { randomUUID } from "node:crypto";+import type { IncomingMessage, ServerResponse } from "node:http";+import { join } from "node:path";+import { expect, it } from "vitest";++import { DATA_DIR, type AppConfig } from "../config.ts";+import type { TeamConnectionsHost } from "../host/team-connections-host.ts";+import { personKey } from "../person-key.ts";+import type { RequestAuth } from "../request-auth.ts";+import { PeopleConnections } from "../team-connections.ts";+import { createTeamConnectionRoutes, type TeamConnectionRouteDeps } from "./team-connections.ts";++const URL_A = "https://mail.example.com/mcp";+const URL_B = "https://other.example.com/mcp";+const EMAIL = "[email protected]";+const PERSON = personKey({ id: "", email: EMAIL });+const KEY = "Bearer personal-key-12345";++function setup() {+ const cfg = { mcpServers: { mail: { type: "http", url: URL_A, headers: { Authorization: "" } } } } as unknown as AppConfig;+ const people = new PeopleConnections({ dataDir: join(DATA_DIR, randomUUID()), brokerUrl: () => null, clients: () => undefined, isOwnerLive: () => true });+ const route = createTeamConnectionRoutes({+ cfg: () => cfg,+ host: { team: { id: "team-acme-1", name: "Acme" }, people, personMcp: () => ["mail"] } as TeamConnectionsHost,+ composio: {} as TeamConnectionRouteDeps["composio"], publicOrigin: null,+ });+ const auth: RequestAuth = { kind: "session", via: "bearer", scopes: ["client"], session: {+ id: "s-ada", tokenHash: "0".repeat(64), label: "Desktop", scopes: ["client"], createdAt: 1, lastSeenAt: 1, expiresAt: 9_000,+ email: EMAIL, teamRole: "member", membershipAuthority: "team",+ } };+ const save = async (body: Record<string, unknown>, duringBodyRead = () => {}) => {+ const answers: Array<{ status: number; body: unknown }> = [];+ const path = "/api/team/my-connections/mcp/mail/key";+ await route({+ req: {} as IncomingMessage, res: {} as ServerResponse, url: new URL(`http://localhost${path}`), path, method: "PUT", auth,+ json: (_res, status, answer) => { answers.push({ status, body: answer }); },+ readBody: async () => { duringBodyRead(); return body; },+ });+ return answers[0]!;+ };+ return { cfg, people, save };+}++it.each(["before request", "during body read"])("rejects a personal key when the URL changes %s", async (when) => {+ const { cfg, people, save } = setup();+ people.putKey(PERSON, EMAIL, "mail", { url: URL_A, header: "Authorization", value: "Bearer kept-key-67890" });+ const changeUrl = () => { cfg.mcpServers = { mail: { type: "http", url: URL_B, headers: { Authorization: "" } } }; };+ if (when === "before request") changeUrl();+ const answer = await save({ value: KEY, url: URL_A }, when === "during body read" ? changeUrl : undefined);++ expect(answer.status).toBe(409);+ expect(answer.body).toMatchObject({ error: expect.stringMatching(/address changed/i) });+ expect(people.key(PERSON, "mail", URL_B)).toBeNull();+ expect(people.key(PERSON, "mail", URL_A)?.value).toBe("Bearer kept-key-67890");+});++it("saves a personal key for the matching URL", async () => {+ const { people, save } = setup();+ expect(await save({ value: KEY, url: URL_A })).toEqual({ status: 200, body: { ok: true } });+ expect(people.key(PERSON, "mail", URL_A)).toEqual({ url: URL_A, header: "Authorization", value: KEY });+ expect(people.key(PERSON, "mail", URL_B)).toBeNull();+});++it.each([undefined, "", 123])("requires the expected URL instead of pinning a key to the current address (%s)", async (url) => {+ const { people, save } = setup();+ expect((await save({ value: KEY, url })).status).toBe(400);+ expect(people.key(PERSON, "mail", URL_A)).toBeNull();+});diff --git a/server/routes/team-connections.ts b/server/routes/team-connections.tsindex 54ba28814c..20c8c54ffb 100644--- a/server/routes/team-connections.ts+++ b/server/routes/team-connections.ts@@ -4,7 +4,7 @@// POST /api/team/my-connections/apps/:slug/connect → { url } their own sign-in to the app (a new tab)// DELETE /api/team/my-connections/apps/:slug// POST /api/team/my-connections/mcp/:name/sign-in → { auth } their own sign-in to the server (a new tab)-// PUT /api/team/my-connections/mcp/:name/key { value } their own key, never read back+// PUT /api/team/my-connections/mcp/:name/key { value, url } their own key, never read back// DELETE /api/team/my-connections/mcp/:name// The Admin's Cloud page calls these with a session it opened for the person asking (a User's is a client session).// Every one acts on the session's own person only, and none answers with a key, a token or a path of an address.@@ -146,8 +146,11 @@ export function createTeamConnectionRoutes(deps: TeamConnectionRouteDeps): Routeconst body = await readBody(req, 4096);const value = typeof body?.value === "string" ? body.value.trim() : "";if (value.length < 8 || value.length > 512 || !/^[\x21-\x7e]+(?: [\x21-\x7e]+)?$/.test(value)) return json(res, 400, { error: "Paste the key alone." });- const headerKeys = Object.keys(stored.headers);- deps.host.people.putKey(person, email, name, { url: stored.url, ...personKeyHeader(headerKeys, value) });+ if (typeof body?.url !== "string" || !body.url) return json(res, 400, { error: "Include the MCP server address for this key." });+ const current = server(name);+ if (!current || !isRemoteMcpServer(current) || current.url !== body.url) return json(res, 409, { error: "The MCP server address changed. Reload the server and try again." });+ const headerKeys = Object.keys(current.headers);+ deps.host.people.putKey(person, email, name, { url: current.url, ...personKeyHeader(headerKeys, value) });return json(res, 200, { ok: true });}if (!mcp[2] && method === "DELETE") {diff --git a/src/components/McpServersPanel.add.test.ts b/src/components/McpServersPanel.add.test.tsindex 1de04cdef3..ca6ab5d6c0 100644--- a/src/components/McpServersPanel.add.test.ts+++ b/src/components/McpServersPanel.add.test.ts@@ -255,7 +255,7 @@ describe("Adding an MCP server on a Team Cloud", () => {expect(calls("POST", "/api/mcp/servers")[0]?.body.headers).toEqual({ [header]: "" });expect(calls("PUT")).toEqual([{ url: "/api/team/connection-scopes", body: { kind: "mcp", id: "mail", scope: "person" } },- { url: "/api/team/my-connections/mcp/mail/key", body: { value: "Bearer mail-key-12345" } },+ { url: "/api/team/my-connections/mcp/mail/key", body: { value: "Bearer mail-key-12345", url: "https://mail.example.com/mcp" } },{ url: "/api/mcp/servers/mail", body: { type: "http", url: "https://mail.example.com/mcp", headers: { [header]: "" }, enabled: false } },]);expect(fixture.sharedHeaders.mail).toEqual({ [header]: "" });@@ -291,7 +291,7 @@ describe("Adding an MCP server on a Team Cloud", () => {expect(calls("PUT", "/api/mcp/servers/mail")[0]?.body.headers).toEqual({ [header]: "" });expect(calls("PUT", "/api/team/my-connections/mcp/mail/key")).toEqual([- { url: "/api/team/my-connections/mcp/mail/key", body: { value: "Bearer replacement-key-67890" } },+ { url: "/api/team/my-connections/mcp/mail/key", body: { value: "Bearer replacement-key-67890", url: "https://mail.example.com/mcp" } },]);expect(fixture.sharedHeaders.mail).toEqual({ [header]: "" });expect(fixture.personalKeys.mail).toBe("Bearer replacement-key-67890");@@ -302,6 +302,34 @@ describe("Adding an MCP server on a Team Cloud", () => {expect(host.querySelector("[data-mcp-editor]")).toBeNull();});+ it.each(["edit", "fix"])("shows the URL conflict and keeps the editor open on %s", async (action) => {+ fixture.servers = [{ name: "mail", type: "http", url: "https://mail.example.com/mcp", headerKeys: ["Authorization"], enabled: true }];+ fixture.personalMcp = ["mail"];+ fixture.personalKeys.mail = "Bearer kept-key-12345";+ await act(async () => host.querySelector<HTMLButtonElement>("[aria-label='Refresh MCP servers']")!.click());+ await settle();+ if (action === "fix") {+ fixture.test = { ok: false, reason: "keys", status: 401 };+ await click("Test");+ await click("Fix the keys");+ } else {+ await act(async () => host.querySelector<HTMLButtonElement>("[aria-label='Edit mail']")!.click());+ }+ const previous = fixture.api.getMockImplementation()!;+ fixture.api.mockImplementation(async (path: string, init?: RequestInit) => {+ if (path === "/api/team/my-connections/mcp/mail/key") throw new Error("The MCP server address changed. Reload the server and try again.");+ return previous(path, init);+ });+ await type("input[aria-label='Authorization']", "Bearer replacement-key-67890");+ fixture.api.mockClear();+ await click("Save");++ expect(host.textContent).toContain("The MCP server address changed. Reload the server and try again.");+ expect(host.querySelector("[data-mcp-editor]")).not.toBeNull();+ expect(fixture.personalKeys.mail).toBe("Bearer kept-key-12345");+ expect(calls("POST")).toEqual([]);+ });+it.each(["Authorization", "X-Api-Key"])("keeps an OAuth-to-key edit private with %s", async (header) => {fixture.servers = [{name: "mail", type: "http", url: "https://mail.example.com/mcp", headerKeys: [], enabled: true,diff --git a/src/components/McpServersPanel.tsx b/src/components/McpServersPanel.tsxindex fa814c133f..46d45b6b7e 100644--- a/src/components/McpServersPanel.tsx+++ b/src/components/McpServersPanel.tsx@@ -190,7 +190,7 @@ export function McpServersPanel({ embedded = false, whopCard = false, hideWhop =latest = listed((await api("/api/mcp/servers", { method: "POST", body: JSON.stringify({ name: item.name, ...body }) })).servers);if (item.ownKey) {await api("/api/team/connection-scopes", { method: "PUT", body: JSON.stringify({ kind: "mcp", id: item.name, scope: "person" }) });- await api(`/api/team/my-connections/mcp/${encodeURIComponent(item.name)}/key`, { method: "PUT", body: JSON.stringify({ value: item.ownKey }) });+ await api(`/api/team/my-connections/mcp/${encodeURIComponent(item.name)}/key`, { method: "PUT", body: JSON.stringify({ value: item.ownKey, url: body.url }) });latest = listed((await api(`/api/mcp/servers/${encodeURIComponent(item.name)}`, {method: "PUT", body: JSON.stringify({ ...body, enabled: false }),})).servers);@@ -232,7 +232,7 @@ export function McpServersPanel({ embedded = false, whopCard = false, hideWhop =}}listed((await api(`/api/mcp/servers/${encodeURIComponent(item.name)}`, { method: "PUT", body: JSON.stringify({ ...body, enabled: existing.enabled }) })).servers);- if (ownKey) await api(`/api/team/my-connections/mcp/${encodeURIComponent(item.name)}/key`, { method: "PUT", body: JSON.stringify({ value: ownKey }) });+ if (ownKey) await api(`/api/team/my-connections/mcp/${encodeURIComponent(item.name)}/key`, { method: "PUT", body: JSON.stringify({ value: ownKey, url: body.url }) });closeEditor();} catch (cause) {setError(cause instanceof Error ? cause.message : String(cause));