Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team Cloud: each person's own apps use the team's Composio key (#5337)
Milind Soni06ee082f2338
diff --git a/docs/composio.md b/docs/composio.mdindex 84c647e914..5eb48e2b2a 100644--- a/docs/composio.md+++ b/docs/composio.md@@ -62,7 +62,11 @@ schedule that checks the app, or a webhook, does the job instead.**`OMB_COMPOSIO_BROKER=off`** in the environment of the desktop app, a server or a Cloud home turns the service off whether or not a key is saved: no registration, check-in, tool calls or app events. Connected apps then need your own key, and show the setup message until there is one. A saved installation is kept for if the switch is removed. `OMB_COMPOSIO_BROKER_URL` is not a switch: left blank it means the default service.-Still on the service with a key saved: a Team Cloud's per-person apps (**each person connects their own**). With the switch off those are unavailable, and connecting one says so.+A Team Cloud's per-person apps (**each person connects their own**) follow the same rule. With the team's key saved, each member is their own Composio user in the team's project (`omb_member_…`, made from the team's id and a hash of the person, never their address), and their connect links, connections, tool calls and disconnects go to Composio with the team's key. A member who leaves has that user's connections removed from the project; if Composio can't be reached then, it is tried again at the next start. App events are not available for them, as for the team's own apps with a key.++Connections do not carry between the service and a project, or between two projects. After the team saves, removes or changes its key, a member's app shows as not connected, their page and their bot say to connect it again, and nothing is an error. An installation a member made on the service before the key was saved is left there, unused and not erased, and is theirs again if the key is removed; the Admin's signed read counts them (`appsLeftOnService`). Connections made in a project stay in that project when its key is removed or replaced.++With the switch off and no key, a member's own apps can't be connected: their page and their bot say an admin needs to add the team's Composio key.## Scoped key permissionsdiff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 73786c8ec5..c910f9d2b7 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -277,7 +277,9 @@ their team page in MausBot Cloud (the Admin's Cloud page calls the routes belowasked in is only where the result is ("Done. The result is in Clerk's chat with Ada."), never the result: a private chatnever reaches a room or the team (server/host/room-access.ts).- **Apps.** A member's own apps are their own installation on the connected-apps service (their own Composio user),- registered the first time they press Connect. Their turn gets a second bridge, `own_apps`, beside the team's+ registered the first time they press Connect. While the team has its own Composio project key they are instead the+ member's own Composio user in the team's project, and nothing of theirs goes to the service+ ([composio.md](composio.md), "Keeping traffic off the managed service"); who gets them is the same. Their turn gets a second bridge, `own_apps`, beside the team's`composio`; the relay checks every frame again: the team's bridge refuses a `person` app (and code that calls appswhile the team's own installation still holds one), a member's bridge refuses a team app and anything outside theirown turn. A connection card for a `person` app is never shown: the bot gets one plain line to say, *"Connect your@@ -292,14 +294,15 @@ their team page in MausBot Cloud (the Admin's Cloud page calls the routes belowused, else `Authorization: Bearer`) or their own sign-in; one not mounted is named to the bot with why and the fix. Both are pinned to the server's address: re-pointed, they aren't sent.Removing the server forgets every member's key and sign-in for it.- **Storage.** `team-connection-scopes.json` (no secret, carried by backups) and `people-connections/` (0700; each- member's installation token, keys and sign-ins, 0600), which no backup carries and no bot box binds. Nothing a route+ member's installation token, keys and sign-ins, 0600; with the team's own key, `project-apps.json`: each member's+ Composio user and Session ids and a short hash of the key, never the key), which no backup carries and no bot box binds. Nothing a routeanswers carries a key, a token or more of an address than its host.| Route | Who | ||---|---|---|| `PUT /api/team/connection-scopes { kind: "app" \| "mcp", id, scope: "team" \| "person" }` | admin | `{ scopes: { apps, mcp } }`; recorded in admin activity |-| `GET /api/team/my-connections` | the member | `{ team, link, email, apps: [{ slug, name, connected, accounts }], mcp: [{ name, host, connected, how, offers }] }` |-| `POST /api/team/my-connections/apps/:slug/connect` | the member | `{ url }`, the app's own sign-in (a new tab) |+| `GET /api/team/my-connections` | the member | `{ team, link, email, apps: [{ slug, name, connected, accounts, reconnect? }], mcp: [{ name, host, connected, how, offers }], ownApps? }`; `reconnect: true` on an app they connected before the team changed its Composio key, to connect again; `ownApps: "needs-key"` when the connected-apps service is off and the team has no key |+| `POST /api/team/my-connections/apps/:slug/connect` | the member | `{ url }`, the app's own sign-in (a new tab); 409 `own_apps_need_key` when an admin must add the team's key first || `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, url? }` | the member | write-only; with `url`, returns 409 if the server URL changed |@@ -869,9 +872,12 @@ opens the team's page on the Cloud site (`/cloud/team/<id>`), not a chat. Nothin(the team's), whichever chat wrote them; a routine is its place's (above, "Routines"). The Owner's whole-machineexport leaves every member's private chats out (above), the Owner's own too: an export is the team's, never anyone'salone.-- **Own apps with the team's own Composio project.** A member's own apps always use OpenMausBot's connected-apps- service, even when the team connected a Composio project key of its own; an app that needs the project's own auth- config can't be connected by each person.+- **Own apps after the team changes its Composio key.** Saving, removing or replacing the team's key leaves every+ member's own apps to be connected again. What they connected before stays where it was made (the connected-apps+ service, or the earlier project) and is not erased from here.+- **A member who leaves a team on the connected-apps service.** Their installation's token is forgotten here, but the+ installation and its connections are not erased at the service. With the team's own key their connections are+ removed from the project.## The desktop app and a team it was invited todiff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex c3dc4e6fab..26a753ae05 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -87,6 +87,7 @@ export const VITEST_SUBSETS = {"server/cloud-team-mausbot-reach.e2e.test.ts","server/cloud-team-new-chat-private.e2e.test.ts","server/cloud-team-open-reach.e2e.test.ts",+ "server/cloud-team-own-key-apps.e2e.test.ts","server/cloud-team-owners.e2e.test.ts","server/cloud-team-people.e2e.test.ts","server/cloud-team-per-person.e2e.test.ts",diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 70c5c13b05..fa507406c6 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -224,6 +224,7 @@ describe("CI outputs", () => {"server/cloud-team-mausbot-reach.e2e.test.ts","server/cloud-team-new-chat-private.e2e.test.ts","server/cloud-team-open-reach.e2e.test.ts",+ "server/cloud-team-own-key-apps.e2e.test.ts","server/cloud-team-owners.e2e.test.ts","server/cloud-team-people.e2e.test.ts","server/cloud-team-per-person.e2e.test.ts",diff --git a/scripts/testing/file-size-ratchet.test.ts b/scripts/testing/file-size-ratchet.test.tsindex 6270fb6935..3b2bd236e4 100644--- a/scripts/testing/file-size-ratchet.test.ts+++ b/scripts/testing/file-size-ratchet.test.ts@@ -34,7 +34,7 @@ const LINES: Record<string, number> = {"src/components/LocalComputerSection.tsx": 1452,"src/components/CursorAvatar.tsx": 1324,"server/skills.ts": 1380,- "server/composio.ts": 1045,+ "server/composio.ts": 1038,"server/vps-computer.ts": 1292,"scripts/mcp-server.ts": 1412,"server/boat.ts": 1258,diff --git a/server/cloud-team-own-key-apps.e2e.test.ts b/server/cloud-team-own-key-apps.e2e.test.tsnew file mode 100644index 0000000000..b90db64577--- /dev/null+++ b/server/cloud-team-own-key-apps.e2e.test.ts@@ -0,0 +1,118 @@+// A real Team Cloud (OMB_CLOUD_ROLE=team) whose admin saved the team's own Composio project key: a loopback project+// stands in for Composio (OMB_COMPOSIO_API), and the managed connected-apps service is a loopback address that records+// whatever reaches it. Ada's own Gmail is her own Composio user in the team's project, used only by her own request in+// her private chat, and removed from the project when she leaves; the service hears nothing. The engine is the+// synthetic Claude CLI, calling the connected-apps bridges it was launched with.+import { randomBytes } from "node:crypto";+import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { join } from "node:path";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { personKey } from "./person-key.ts";+import { memberComposioUser } from "./team-connections.ts";+import { startFakeComposioProject, type FakeComposioProject } from "./testing/fake-composio-project.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const TOKEN = `ops_fake-team-${randomBytes(8).toString("hex")}`;+const KEY = "ak_team_project_key";+const TEAM_ID = "team-acme-1";+const OWNER = { email: "[email protected]", role: "owner" as const };+const ADA = { email: "[email protected]", role: "member" as const };+const CLEO = { email: "[email protected]", role: "member" as const };+const ADA_USER = memberComposioUser(TEAM_ID, personKey({ id: "", email: ADA.email }));+const ENGINE = `process.env.FAKE_CLAUDE_DUMP = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/dump.json";+process.env.FAKE_CLAUDE_TOOL_CALLS_FILE = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/tool-calls.json";`;++let fx: CloudSendFixture, team: CloudTeamFixture, project: FakeComposioProject;+let service: Server, serviceRequests: string[] = [];+let owner = "", ada = "", cleo = "";+let bot: { id: string };+let adaThread = "", cleoThread = "", adaAccount = "";++beforeAll(async () => {+ project = await startFakeComposioProject(KEY);+ service = createServer((req, res) => { serviceRequests.push(`${req.method} ${req.url}`); res.writeHead(503); res.end(); });+ await new Promise<void>((resolve) => service.listen(0, "127.0.0.1", resolve));+ fx = await launchCloudSendFixture({ onePasswordToken: TOKEN, team: { id: TEAM_ID, name: "Acme", engine: ENGINE, env: {+ OMB_BOT_BOX: "0", COMPOSIO_API_KEY: KEY, OMB_COMPOSIO_API: project.api, OMB_COMPOSIO_BROKER_URL: `http://127.0.0.1:${(service.address() as AddressInfo).port}`,+ } } });+ team = fx.team!;+ owner = (await team.pair(OWNER)).token!;+ ada = (await team.pair(ADA)).token!;+ cleo = (await team.pair(CLEO)).token!;+ const created = await team.as(owner, "POST", "/api/bots", { name: "Scout" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ bot = created.body.bot;+ expect((await team.as(owner, "PUT", "/api/team/connection-scopes", { kind: "app", id: "gmail", scope: "person" })).body).toEqual({ scopes: { apps: ["gmail"], mcp: [] } });+ adaThread = await newThread(ada, "Ada and Scout");+ cleoThread = await newThread(cleo, "Cleo and Scout");+}, hostTimeout(120_000));++afterAll(async () => {+ await fx?.close();+ await project?.close();+ service?.closeAllConnections();+ await new Promise<void>((resolve) => service.close(() => resolve()));+});++const scriptToolCalls = (calls: unknown[] | null) => {+ const file = join(team.home, "tool-calls.json");+ if (calls) writeFileSync(file, JSON.stringify(calls)); else rmSync(file, { force: true });+};+const gmailCall = (server: "composio" | "own_apps") => ({ name: "COMPOSIO_MULTI_EXECUTE_TOOL", server, input: { tools: [{ tool_slug: "GMAIL_FETCH_EMAILS", arguments: { max_results: 1 } }] } });+const messages = async (token: string, threadId: string) => team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`);+const idle = async (token: string) => ((await team.as(token, "GET", "/api/bots")).body.bots as Array<{ activity?: string; busy?: boolean }>)+ .every((entry) => entry.activity !== "working" && !entry.busy);+async function newThread(token: string, title: string) {+ const created = await team.as(token, "POST", `/api/bots/${bot.id}/tasks`, { title });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ return created.body.task.threadId as string;+}+async function turn(token: string, threadId: string, text: string, calls: unknown[]) {+ scriptToolCalls(calls);+ rmSync(join(team.home, "dump.json"), { force: true });+ const before = ((await messages(token, threadId)).body.messages as unknown[]).length;+ const sent = await team.as(token, "POST", `/api/bots/${bot.id}/messages`, { text, threadId });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ await expect.poll(async () => await idle(token) && ((await messages(token, threadId)).body.messages as unknown[]).length >= before + 2 && existsSync(join(team.home, "dump.json")),+ { timeout: 60_000, interval: 100 }).toBe(true);+ const seen = JSON.parse(readFileSync(join(team.home, "dump.json"), "utf8")) as { mcpConfig: { mcpServers: Record<string, unknown> } };+ return { servers: Object.keys(seen.mcpConfig?.mcpServers ?? {}), thread: JSON.stringify((await messages(token, threadId)).body) };+}+const gmailCallsBy = (user: string) => project.toolCalls.filter((call) => call.user === user && call.slugs.includes("GMAIL_FETCH_EMAILS")).length;++it("connects Ada's own Gmail as her own Composio user in the team's project", async () => {+ const started = await team.as(ada, "POST", "/api/team/my-connections/apps/gmail/connect", {});+ expect(started.status, JSON.stringify(started.body)).toBe(200);+ expect(started.body.url).toMatch(/^https:\/\/backend\.composio\.dev\/link\//);+ expect(project.links).toEqual([{ user: ADA_USER, toolkit: "gmail" }]);+ adaAccount = project.connect(ADA_USER, "gmail");+ expect((await team.as(ada, "GET", "/api/team/my-connections")).body.apps).toEqual([{ slug: "gmail", name: "Gmail", connected: true, accounts: [{ id: adaAccount, alias: null, status: "ACTIVE" }] }]);+ expect((await team.as(cleo, "GET", "/api/team/my-connections")).body.apps[0].connected).toBe(false);+ const read = await team.signed("GET", "/api/cloud/team/admin");+ expect(read.body.people.apps).toEqual({ gmail: [ADA.email] });+ expect(JSON.stringify(read.body)).not.toContain(ADA_USER);+ expect(readFileSync(join(team.home, ".openmausbot", "config.json"), "utf8"), "the team's saved Composio user is never a member's").not.toContain(ADA_USER);+}, hostTimeout(60_000));++it("runs her Gmail only for her own request in her own chat, as her", async () => {+ const mine = await turn(ada, adaThread, "Summarize my inbox.", [gmailCall("own_apps")]);+ expect(mine.servers).toEqual(expect.arrayContaining(["composio", "own_apps"]));+ expect(gmailCallsBy(ADA_USER)).toBe(1);+ expect(mine.thread).toContain(`"whose":{"person":"${ADA.email}","app":"Gmail"}`);++ const cleos = await turn(cleo, cleoThread, "Check Ada's inbox.", [gmailCall("own_apps"), gmailCall("composio")]);+ expect(cleos.servers).not.toContain("own_apps");+ expect(gmailCallsBy(ADA_USER), "nobody else's turn reached her Gmail").toBe(1);+ expect(project.toolCalls.filter((call) => call.slugs.includes("GMAIL_FETCH_EMAILS")).map((call) => call.user), "the team's own bridge never ran a person's app").toEqual([ADA_USER]);+}, hostTimeout(180_000));++it("removes her connections from the team's project when she leaves, and never spoke to the managed service", async () => {+ const left = await team.signed("POST", "/api/cloud/team/member-left", { email: ADA.email });+ expect(left.status, JSON.stringify(left.body)).toBe(200);+ expect(project.accounts.map((account) => account.id)).not.toContain(adaAccount);+ expect(project.requests.every((request) => request.apiKey === KEY)).toBe(true);+ expect(serviceRequests).toEqual([]);+}, hostTimeout(60_000));diff --git a/server/composio-project.ts b/server/composio-project.tsindex f3cb769690..0dede99299 100644--- a/server/composio-project.ts+++ b/server/composio-project.ts@@ -338,3 +338,21 @@ export async function listConnectedAccounts(}throw new Error("Composio account inventory exceeded the pagination safety limit");}++export async function deleteConnectedAccount(apiKey: string, id: string) {+ const removed = await fetch(+ `${apiBase()}/connected_accounts/${encodeURIComponent(id)}?revoke_on_delete=true`,+ { method: "DELETE", headers: projectHeaders(apiKey), signal: AbortSignal.timeout(30_000) },+ );+ if (!removed.ok) throw new Error(await responseError(removed, `Composio disconnect: HTTP ${removed.status}`));+}++/** Revokes and deletes every connected account of one Composio user in the project; how many went. */+export async function removeUserConnections(apiKey: string, userId: string): Promise<number> {+ const accounts = await listConnectedAccounts(apiKey, userId, []);+ // Security: only an account Composio names as this user's is deleted.+ if (accounts.some((account) => account.user_id !== userId)) throw new Error("Composio listed a connected account without naming this user as its owner");+ let removed = 0;+ for (const { id } of accounts) if (id) { await deleteConnectedAccount(apiKey, id); removed += 1; }+ return removed;+}diff --git a/server/composio-session.ts b/server/composio-session.tsindex 37defb7d65..8b6f90c1de 100644--- a/server/composio-session.ts+++ b/server/composio-session.ts@@ -214,6 +214,15 @@ export async function prepareProjectSession(return { apiKey: trimmed, userId, sessionId };}+type SessionIds = { userId: string; sessionId: string };+const sessionKeepers = new WeakMap<object, (ids: SessionIds) => void>();++/** Keeps the Session of a `composio` that is not the saved config's (a Team Cloud member's own Composio user in the+ * team's project) with `keep`, never in config.json. */+export function keepSessionWith(composio: NonNullable<AppConfig["composio"]>, keep: (ids: SessionIds) => void): void {+ sessionKeepers.set(composio, keep);+}+async function adoptProjectSession(composio: NonNullable<AppConfig["composio"]>,apiKey: string,@@ -223,7 +232,8 @@ async function adoptProjectSession(multiAccountUpgradeAttempted.add(sessionId);composio.userId = userId;composio.sessionId = sessionId;- saveConfig({ composio: { userId, sessionId } });+ const keep = sessionKeepers.get(composio);+ if (keep) keep({ userId, sessionId }); else saveConfig({ composio: { userId, sessionId } });const created = await getProjectSession(apiKey, sessionId);if (!created) throw new Error("Composio Session disappeared after creation");return created;@@ -250,15 +260,19 @@ export async function ensureProjectSession(cfg: AppConfig, wanted?: AuthConfigMaconst apiKey = projectApiKey(cfg);if (!composio || !apiKey) throw new Error("No Composio project key configured");const configs = wanted ?? (await projectAuthConfigs(apiKey)).configs;+ const member = sessionKeepers.has(composio);if (composio.sessionId) {const existing = await getProjectSession(apiKey, composio.sessionId);- if (existing && (supportsMultiAccount(existing) || multiAccountUpgradeAttempted.has(existing.session_id))) {+ // Security: a member's Session is used only while it is their own Composio user's, never the team's or another member's.+ if (member && existing?.config?.user_id && existing.config.user_id !== composio.userId) delete composio.sessionId;+ else if (existing && (supportsMultiAccount(existing) || multiAccountUpgradeAttempted.has(existing.session_id))) {if (authConfigsReady(existing, configs)) return existing;const named = await nameAuthConfigsInPlace(apiKey, existing, configs);if (named) return named;}}const prepared = await prepareProjectSession(apiKey, composio, configs);+ if (member && prepared.userId !== composio.userId) throw new Error("Composio returned a Session for another user");return adoptProjectSession(composio, apiKey, prepared.userId, prepared.sessionId);}diff --git a/server/composio.ts b/server/composio.tsindex b194b9457d..7860266965 100644--- a/server/composio.ts+++ b/server/composio.ts@@ -8,6 +8,7 @@ import {DEFAULT_BACKEND_ORIGIN,apiBase,canonicalToolkitSlug,+ deleteConnectedAccount,inputError,keepAuthConfigPick,listConnectedAccounts,@@ -528,7 +529,7 @@ let connectorToolsCache: { at: number; identity: string; services: Record<string/** Cache key per backend, so a config switch never serves the previous backend's tools. */function connectorToolsIdentity(cfg: AppConfig, as?: BrokerAccess): string {const apiKey = as ? null : projectApiKey(cfg);- if (apiKey) return backendFingerprint("project-tools", apiBase(), apiKey);+ if (apiKey) return backendFingerprint("project-tools", `${apiBase()}\0${cfg.composio?.userId ?? ""}`, apiKey);const broker = as ?? brokerAccess();return broker ? backendFingerprint("managed-tools", broker.url, broker.token) : "none";}@@ -729,14 +730,6 @@ export async function removeService(cfg: AppConfig, slug: string, as?: BrokerAccreturn { removed: 1 };}-async function deleteConnectedAccount(apiKey: string, id: string) {- const removed = await fetch(- `${apiBase()}/connected_accounts/${encodeURIComponent(id)}?revoke_on_delete=true`,- { method: "DELETE", headers: projectHeaders(apiKey), signal: AbortSignal.timeout(30_000) },- );- if (!removed.ok) throw new Error(await responseError(removed, `Composio disconnect: HTTP ${removed.status}`));-}-/** Disconnect exactly one account after proving it belongs to this user/toolkit. */export async function removeAccount(cfg: AppConfig, slug: string, accountId: string) {if (!validAccountId(accountId)) throw inputError("Invalid connected-account ID");diff --git a/server/host/login-mail-codes.ts b/server/host/login-mail-codes.tsindex d191951411..b1b3460065 100644--- a/server/host/login-mail-codes.ts+++ b/server/host/login-mail-codes.ts@@ -18,7 +18,7 @@ import type { EmailBot } from "../email/host.ts";import type { EmailAccount } from "../email/store.ts";import { waitForEmailCode, type CodeMailbox } from "../email-code.ts";import type { EmailCodeAnswer, EmailCodeAsk } from "../login-fill.ts";-import type { BrokerAccess } from "../team-connections.ts";+import { asPerson, type BrokerAccess, type PersonAppsAccess } from "../team-connections.ts";import type { ConnectorCardAnswer } from "./connector-cards.ts";export const MAIL_CARD_FILE = "email-code-card.json";@@ -41,7 +41,7 @@ export interface LoginMailCodesDeps {personApps(): readonly string[];/** The member this turn may use the own connections of, or null. */turnPerson(threadId: string, generation: string): string | null;- appsAccess(person: string): BrokerAccess | null;+ appsAccess(person: string): PersonAppsAccess | null;appAllowed(slug: string): boolean;/** The IMAP mailboxes this bot may read. */imapAccounts(bot: Bot): readonly EmailAccount[];@@ -88,13 +88,14 @@ export function createLoginMailCodes(deps: LoginMailCodesDeps) {}async function appBoxes(turn: Turn, app: MailApp): Promise<CodeMailbox[]> {- const cfg = deps.cfg();+ let cfg = deps.cfg();let access: BrokerAccess | undefined;if (deps.personApps().includes(app)) {const person = deps.turnPerson(turn.threadId, turn.generation);if (!person) return [];- access = deps.appsAccess(person) ?? undefined;- if (!access) return [];+ const own = deps.appsAccess(person);+ if (!own) return [];+ [cfg, access] = asPerson(cfg, own);}const state = (await deps.composio.connectedServices(cfg, access))[app];if (!state?.connected) return [];diff --git a/server/host/person-calendar.ts b/server/host/person-calendar.tsindex 31e5e80a47..167c7f1f6b 100644--- a/server/host/person-calendar.ts+++ b/server/host/person-calendar.ts@@ -2,14 +2,14 @@// Calendar connection, made when Google Calendar is an app each person connects for themselves; never the team's.// Security: only start and end times leave this module, never a title, a place, a description or who is invited.import { createConnectedReads, type CalendarEvent, type ConnectedReadDeps } from "../connected-reads.ts";-import type { BrokerAccess } from "../team-connections.ts";+import type { PersonAppsAccess } from "../team-connections.ts";import type { Busy } from "./representative.ts";-export interface PersonCalendarDeps {+export interface PersonCalendarDeps<Access = PersonAppsAccess> {/** The member's own connected-apps access while Google Calendar is each person's own here; null otherwise. */- access(person: string): BrokerAccess | null;- connected(access: BrokerAccess): Promise<boolean>;- relay(payload: unknown, transportSessionId: string | undefined, signal: AbortSignal, access: BrokerAccess): ReturnType<ConnectedReadDeps["relay"]>;+ access(person: string): Access | null;+ connected(access: Access): Promise<boolean>;+ relay(payload: unknown, transportSessionId: string | undefined, signal: AbortSignal, access: Access): ReturnType<ConnectedReadDeps["relay"]>;}/** Busy times, merged where they touch: every event the person did not decline and that is not cancelled. A day-long@@ -26,7 +26,7 @@ export function busyTimes(events: readonly CalendarEvent[]): Busy[] {return merged;}-export function createPersonCalendar(deps: PersonCalendarDeps) {+export function createPersonCalendar<Access = PersonAppsAccess>(deps: PersonCalendarDeps<Access>) {return {/** Null when the person connected no calendar of their own. */async busy(person: string, fromMs: number, toMs: number): Promise<Busy[] | null> {diff --git a/server/host/team-connections-host.ts b/server/host/team-connections-host.tsindex ada9c69181..14fa663235 100644--- a/server/host/team-connections-host.ts+++ b/server/host/team-connections-host.ts@@ -19,7 +19,9 @@ import { serviceSlugFor } from "../connector-verdict.ts";import { type McpOAuthManager, type McpRefreshOutcome, type McpSignInPhase, withMcpSignIn, withoutPendingSignIn } from "../mcp-oauth.ts";import { isRemoteMcpServer, parseStoredMcpServer, type McpOAuthClientConfig } from "../mcp-registry.ts";import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";-import { appLabel, ConnectionScopes, PeopleConnections, personAppOf, SCOPES_FILE, type BrokerAccess } from "../team-connections.ts";+import { managedComposioBrokerOff } from "../composio-broker-access.ts";+import { projectApiKey } from "../composio-session.ts";+import { appLabel, asPerson, ConnectionScopes, isProjectAccess, PeopleConnections, personAppOf, SCOPES_FILE, type PersonAppsAccess } from "../team-connections.ts";import { APP_TOOL_NAMES_ENV, APP_TOOLS_ENV, appToolsFor } from "../connector-app-tools.ts";import type { ConnectorScopes } from "../../shared/connector-scopes.ts";@@ -82,6 +84,7 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {const people = new PeopleConnections({dataDir: deps.dataDir,brokerUrl: deps.brokerUrl,+ ...(team ? { teamId: team.id, projectKey: () => projectApiKey(deps.cfg()) } : {}),clients: (name, url) => { const server = teamServer(name); return server && isRemoteMcpServer(server) && server.url === url ? (server.oauth && deps.oauthClient ? deps.oauthClient(name, server.oauth) : server.oauth) : undefined; },isOwnerLive: deps.isOwnerLive,...(deps.onSettled ? { onSettled: deps.onSettled } : {}),@@ -89,16 +92,19 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {...(deps.onPersonChanged ? { onChanged: deps.onPersonChanged } : {}),});const personApps = () => (team ? scopes.person("app") : []);+ const via = (access?: PersonAppsAccess | null) => asPerson(deps.cfg(), access);+ /** With the connected-apps service switched off and no key of the team's, nobody can connect an app of their own. */+ const ownAppsNeedKey = () => Boolean(team) && managedComposioBrokerOff() && !projectApiKey(deps.cfg());/** The apps connected for an installation, the team's or a member's own. A turn never waits on a refresh: what is known* is used at once, and read again in the background once it is a minute old. Only an installation's first answer is* waited for, at most a few seconds, and a failed first read is tried again soon; `primeApps` reads the team's at start. */const connectedApps = new Map<string, { at: number; apps: string[] | null; reading: Promise<void> | null }>();- const appsConnected = async (as?: BrokerAccess): Promise<string[]> => {- const key = as ? createHash("sha256").update(as.url).update("\u0000").update(as.token).digest("hex") : "";+ const appsConnected = async (as?: PersonAppsAccess): Promise<string[]> => {+ const key = isProjectAccess(as) ? `project\u0000${as.composio.userId}` : as ? createHash("sha256").update(as.url).update("\u0000").update(as.token).digest("hex") : "";const entry = connectedApps.get(key) ?? { at: -Infinity, apps: null, reading: null };connectedApps.set(key, entry);if (!entry.reading && Date.now() - entry.at >= (entry.apps ? APPS_FRESH_MS : APPS_RETRY_MS)) {- entry.reading = deps.composio.connectedServices(deps.cfg(), as).then((services) => {+ entry.reading = deps.composio.connectedServices(...via(as)).then((services) => {entry.apps = Object.entries(services).filter(([, state]) => state.connected).map(([slug]) => slug);}, () => {}).finally(() => { entry.at = Date.now(); entry.reading = null; });}@@ -107,7 +113,7 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {}return entry.apps ?? [];};- const withAppTools = async (bridge: Integration, bot: Bot, names: "dotted" | "plain", as?: BrokerAccess): Promise<Integration> => {+ const withAppTools = async (bridge: Integration, bot: Bot, names: "dotted" | "plain", as?: PersonAppsAccess): Promise<Integration> => {const tools = appToolsFor(bot, await appsConnected(as));return tools.length ? { ...bridge, env: { ...bridge.env, [APP_TOOLS_ENV]: JSON.stringify(tools), [APP_TOOL_NAMES_ENV]: names } } : bridge;};@@ -117,7 +123,7 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {const ownAppsServices = () => {if (!ownAppsRead || Date.now() - ownAppsRead.at >= OWN_APPS_READ_MS) {ownAppsRead = { at: Date.now(), read: Promise.all(people.appsPeople().map(async ({ person, email, access }) => ({- person, email, services: await deps.composio.connectedServices(deps.cfg(), access).catch(() => null),+ person, email, services: await deps.composio.connectedServices(...via(access)).catch(() => null),}))) };}return ownAppsRead.read;@@ -150,9 +156,14 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {const lines = {connect: (name: string, person: string) => {+ if (ownAppsNeedKey()) {+ return `${name} is connected by each person in ${teamName()}, and that isn't available here until an admin adds the team's Composio key. ${noWorkaround} Reply with this one line and nothing more about it: `+ + `"${name} can't be connected on ${teamName()} yet. Ask an admin to add the team's Composio key."`;+ }const where = ownPage(person);- return `${name} is connected by each person in ${teamName()}, and ${nameOf(person)} hasn't connected theirs. ${noWorkaround} Reply with this one line and nothing more about it: `- + (where ? `"Connect your ${name} here: ${where}"` : `"Connect your own ${name} on your team's page in MausBot Cloud."`);+ const again = people.appsElsewhere(person);+ return `${name} is connected by each person in ${teamName()}, and ${nameOf(person)} ${again ? `needs to connect theirs again: ${teamName()} changed where its apps connect, and connections don't carry over` : "hasn't connected theirs"}. ${noWorkaround} Reply with this one line and nothing more about it: `+ + (where ? `"Connect your ${name} ${again ? "again " : ""}here: ${where}"` : `"Connect your own ${name} ${again ? "again " : ""}on your team's page in MausBot Cloud."`);},/** No one person's own request is behind this work: say so, and how to get it done. */nobody: (name: string) => {@@ -221,6 +232,8 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {link,turnPerson,nameOf,+ via,+ ownAppsNeedKey,/** Off a Team Cloud, always; on one, the person this turn acts for is its owner or an admin, as Settings requires. */actsForAdmin(threadId: string, generation?: string): boolean {if (!team) return true;@@ -236,6 +249,9 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {/** At start: the team's installation's apps are read now, so the first turn need not wait for them. */primeApps(): void {if (deps.composio.configured(deps.cfg())) void appsConnected();+ const left = people.appsLeftOnService();+ if (left) console.log(`[team connections] ${left} member installation(s) made before the team saved its own Composio key are still on the connected-apps service; nothing is sent there while the key is saved`);+ void people.finishRemovals();},/** The connected-apps bridges of a turn: the team's, and in a turn that acts for a member their own beside it.@@ -249,7 +265,8 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {const person = personApps().length ? turnPerson(threadId, generation) : null;const access = person ? people.appsAccess(person) : null;if (person && access) {- const own = await deps.composio.mcpIntegration(cfg, { ...base, as: access, commsToken: deps.mint({ botId: bot.id, threadId, generation, connectorsFor: person }) });+ const [ownCfg, as] = via(access);+ const own = await deps.composio.mcpIntegration(ownCfg, { ...base, ...(as ? { as } : {}), commsToken: deps.mint({ botId: bot.id, threadId, generation, connectorsFor: person }) });if (own) out.composioOwn = await withAppTools(own, bot, names, access);}return out;@@ -257,7 +274,7 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {/** Whose installation a relayed frame goes to: the team's (none named), or the member's own after checking the turn* still acts for them. A refusal is the plain line the bot gets back. */- relayActor(capability: { threadId: string; generation: string; connectorsFor?: string }): { access?: BrokerAccess; refusal?: string } {+ relayActor(capability: { threadId: string; generation: string; connectorsFor?: string }): { access?: PersonAppsAccess; refusal?: string } {const own = capability.connectorsFor;if (!own) return {};if (turnPerson(capability.threadId, capability.generation) !== own) return { refusal: lines.ownOnly(nameOf(own)) };@@ -408,8 +425,9 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {ownAppsServices,/** A person who left the team (host/team-member-left.ts): every connection, key and sign-in of theirs goes. */forgetPerson: (person: string) => people.forgetPerson(person),- /** For the Admin's signed read: what is `person`, and who has connected each (addresses, never a secret). */- async adminExtras(): Promise<{ scopes: { apps: string[]; mcp: string[] }; people: { apps: Record<string, string[]>; mcp: Record<string, string[]> } } | Record<string, never>> {+ /** For the Admin's signed read: what is `person`, and who has connected each (addresses, never a secret).+ * `appsLeftOnService`: members' installations made before the team saved its own key, still on the service. */+ async adminExtras(): Promise<{ scopes: { apps: string[]; mcp: string[] }; people: { apps: Record<string, string[]>; mcp: Record<string, string[]> }; appsLeftOnService?: number } | Record<string, never>> {if (!team) return {};const apps = personApps(), servers = personMcp();const byApp: Record<string, string[]> = Object.fromEntries(apps.map((slug) => [slug, [] as string[]]));@@ -426,7 +444,8 @@ export function createTeamConnectionsHost(deps: TeamConnectionsHostDeps) {byServer[name] = [...new Set(who.map((entry) => entry.email).filter(Boolean))].sort();}for (const slug of apps) byApp[slug]!.sort();- return { scopes: { apps, mcp: servers }, people: { apps: byApp, mcp: byServer } };+ const left = people.appsLeftOnService();+ return { scopes: { apps, mcp: servers }, people: { apps: byApp, mcp: byServer }, ...(left ? { appsLeftOnService: left } : {}) };},};}diff --git a/server/host/team-member-left.ts b/server/host/team-member-left.tsindex 4c6e3b878d..d9cb111dfe 100644--- a/server/host/team-member-left.ts+++ b/server/host/team-member-left.ts@@ -53,7 +53,7 @@ export interface TeamMemberLeftDeps {deleteAttachment(name: string): void;eraseBrowsers(audience: Audience): Promise<boolean>;/** Their own connections, keys and MCP sign-ins (team-connections.ts). */- forgetConnections(person: string): void;+ forgetConnections(person: string): void | Promise<void>;/** Every routine: `home` is the person whose private chat it lives in (routine-home.ts), `writer` who last wrote it,* `files` the attachments/ names it carries. */routines(): ReadonlyArray<{ id: string; name: string; botId: string; home: string | null; writer: string | undefined; files: readonly string[] }>;@@ -143,7 +143,7 @@ export function createTeamMemberLeft(deps: TeamMemberLeftDeps): (email: string)}rmSync(join(deps.dataDir, "people", person), { recursive: true, force: true });rmSync(audienceHome(deps.dataDir, memberAudience(person)), { recursive: true, force: true });- deps.forgetConnections(person);+ await Promise.resolve(deps.forgetConnections(person)).catch((error: unknown) => { console.warn(`[team] a leaving member's connections were not all removed: ${error instanceof Error ? error.message : String(error)}`); });const browsers = await deps.eraseBrowsers(memberAudience(person)).catch(() => false);// Counts of shared things only: nothing here says what was theirs alone.deps.record({ category: "people", action: "member.left", target: { kind: "person", name: address }, after: { botsHandedBack, routinesHandedOver: written.length } });diff --git a/server/host/team-own-key-person-apps.test.ts b/server/host/team-own-key-person-apps.test.tsnew file mode 100644index 0000000000..1de1105d50--- /dev/null+++ b/server/host/team-own-key-person-apps.test.ts@@ -0,0 +1,316 @@+// A Team Cloud with its own Composio project key: each person's own apps go to that project as their own Composio user,+// and nothing reaches the managed connected-apps service. The real Composio client code (server/composio.ts) runs against+// a loopback project (OMB_COMPOSIO_API) beside a loopback service that records whatever reaches it.+import { mkdtempSync, readFileSync } from "node:fs";+import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";+import type { AddressInfo } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import type { Audience } from "../audience.ts";+import * as composio from "../composio.ts";+import type { AppConfig } from "../config.ts";+import { McpOAuthManager } from "../mcp-oauth.ts";+import { personKey } from "../person-key.ts";+import type { RequestAuth } from "../request-auth.ts";+import { createTeamConnectionRoutes } from "../routes/team-connections.ts";+import { memberComposioUser } from "../team-connections.ts";+import { startFakeComposioProject, type FakeComposioProject } from "../testing/fake-composio-project.ts";+import { createTeamConnectionsHost } from "./team-connections-host.ts";++const TEAM = { id: "team-acme-1", name: "Acme" };+const KEY = "ak_team_project_key";+const ADA = personKey({ id: "", email: EMAILS.ada }), CLEO = personKey({ id: "", email: EMAILS.cleo }), BEN = personKey({ id: "", email: EMAILS.ben });+const ADA_USER = memberComposioUser(TEAM.id, ADA), CLEO_USER = memberComposioUser(TEAM.id, CLEO);+const SERVICE_TOKEN = "5".repeat(64), ADA_SERVICE_TOKEN = "a".repeat(64);+const AUDIENCES: Record<string, Audience> = { "ada-chat": `member:${ADA}`, "cleo-chat": `member:${CLEO}`, "room-chat": "room:launch", "main-chat": "team" };+const GMAIL_CALL = { jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "COMPOSIO_MULTI_EXECUTE_TOOL", arguments: { tools: [{ tool_slug: "GMAIL_FETCH_EMAILS", arguments: {} }] } } };++let project: FakeComposioProject;+let service: { url: string; requests: string[]; server: Server };+let fetched: string[] = [];+const realFetch = globalThis.fetch;++beforeAll(async () => {+ project = await startFakeComposioProject(KEY);+ const requests: string[] = [];+ let installs = 0;+ const server = createServer((req: IncomingMessage, res: ServerResponse) => {+ requests.push(`${req.method} ${req.url}`);+ res.writeHead(200, { "content-type": "application/json" });+ if (req.url === "/v1/installations") return res.end(JSON.stringify({ installationId: `inst-${++installs}`, token: String(installs).repeat(64).slice(0, 64) }));+ if (req.url?.endsWith("/authorize")) return res.end(JSON.stringify({ url: "https://backend.composio.dev/link/lk_service" }));+ return res.end(JSON.stringify({ services: {} }));+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ service = { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, requests, server };+});++afterAll(async () => {+ await project.close();+ service.server.closeAllConnections();+ await new Promise<void>((resolve) => service.server.close(() => resolve()));+});++beforeEach(() => {+ fetched = [];+ service.requests.length = 0;+ project.requests.length = 0; project.toolCalls.length = 0; project.links.length = 0; project.accounts.length = 0; project.down = false;+ vi.stubEnv("OMB_COMPOSIO_API", project.api);+ vi.stubGlobal("fetch", (input: Parameters<typeof fetch>[0], init?: RequestInit) => {+ fetched.push(input instanceof Request ? input.url : String(input));+ return realFetch(input, init);+ });+ // The installation a Team Cloud made on the service before its admin saved a key is still held.+ composio.setManagedBrokerAccess({ url: service.url, token: SERVICE_TOKEN });+});++afterEach(() => {+ composio.setManagedBrokerAccess(null);+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+});++function setup(options: { key?: string | null; dataDir?: string; requester?: Record<string, string>; refuse?: string } = {}) {+ const dataDir = options.dataDir ?? mkdtempSync(join(tmpdir(), "omb-team-own-key-"));+ const cfg = { composio: options.key === null ? {} : { apiKey: options.key ?? KEY, userId: "openmausbot_team" } } as AppConfig;+ const requester: Record<string, string> = { "ada-chat": ADA, "cleo-chat": CLEO, "room-chat": ADA, "main-chat": ADA, ...options.requester };+ const host = createTeamConnectionsHost({+ team: TEAM, dataDir, cfg: () => cfg, adminOrigin: "https://cloud.example.test", harnessUrl: "http://127.0.0.1:1",+ audienceOf: (threadId) => AUDIENCES[threadId] ?? "team",+ requester: (threadId) => requester[threadId] ?? null,+ roster: () => [{ person: BEN, email: EMAILS.ben, role: "admin" as const }, { person: ADA, email: EMAILS.ada, role: "member" as const }, { person: CLEO, email: EMAILS.cleo, role: "member" as const }],+ mint: (capability) => `tok-${capability.threadId}-${capability.connectorsFor ?? "team"}`,+ mcpOAuth: new McpOAuthManager({ file: join(dataDir, "mcp-oauth.json") }),+ botMcp: () => ({}), isOwnerLive: () => true, brokerUrl: () => service.url, composio,+ });+ host.scopes.set("app", "gmail", "person");+ const route = createTeamConnectionRoutes({+ host, cfg: () => cfg, composio, publicOrigin: null,+ policy: { appRefusal: () => options.refuse, mcpRefusal: () => undefined },+ });+ const as = async (email: string, method: string, path: string) => {+ const auth: RequestAuth = { kind: "session", via: "bearer", scopes: ["client"], session: {+ id: `s-${email}`, tokenHash: "0".repeat(64), label: "Desktop", scopes: ["client"], createdAt: 1, lastSeenAt: 1, expiresAt: 9_000,+ email, teamRole: "member", membershipAuthority: "team",+ } };+ let answer: { status: number; body: any } | undefined;+ await route({+ req: {} as IncomingMessage, res: {} as ServerResponse, url: new URL(`http://localhost${path}`), path, method, auth,+ json: (_res, status, body) => { answer = { status, body }; }, readBody: async () => ({}),+ });+ return answer!;+ };+ /** One tool call through a member's own bridge, as the relay makes it once `relayActor` let it through. */+ const ownCall = async (threadId: string, person: string) => {+ const actor = host.relayActor({ threadId, generation: "g", connectorsFor: person });+ if (actor.refusal) return { refusal: actor.refusal };+ const [asThem, installation] = host.via(actor.access);+ const answer = await composio.relayMcp(asThem, GMAIL_CALL, undefined, undefined, undefined, installation);+ return { text: new TextDecoder().decode(answer.bytes) };+ };+ const stored = () => JSON.parse(readFileSync(join(dataDir, "people-connections", "project-apps.json"), "utf8")) as { people: Record<string, { userId: string; sessionId?: string; again?: true }>; removals: string[] };+ /** As a member's installation on the service was saved, before the team had a key. */+ const onService = (person: string, email: string, token: string) => (host.people as unknown as { write(name: string, value: unknown): void })+ .write("apps.json", { v: 1, brokerUrl: service.url, people: { [person]: { email, installationId: `inst-${email}`, token } } });+ const connect = async (email: string, user: string) => {+ const started = await as(email, "POST", "/api/team/my-connections/apps/gmail/connect");+ expect(started.status, JSON.stringify(started.body)).toBe(200);+ return project.connect(user, "gmail");+ };+ const myGmail = async (email: string) => (await as(email, "GET", "/api/team/my-connections")).body.apps[0] as { connected: boolean; reconnect?: true };+ return { host, cfg, dataDir, as, ownCall, stored, onService, connect, myGmail };+}++const offService = () => {+ expect(service.requests, "requests that reached the managed connected-apps service").toEqual([]);+ expect(fetched.filter((url) => !url.startsWith(project.origin)), "requests that left for anywhere but the team's project").toEqual([]);+};++describe("each person's own apps with the team's own Composio key", () => {+ it("connects, lists, calls, disconnects and removes on leaving in the team's project, and sends the service nothing", async () => {+ const { host, cfg, as, ownCall, connect, myGmail } = setup();+ expect(ADA_USER).toMatch(/^omb_member_[0-9a-f]{32}$/);+ expect(ADA_USER).not.toBe(CLEO_USER);+ expect(await myGmail(EMAILS.ada)).toEqual({ slug: "gmail", name: "Gmail", connected: false, accounts: [] });++ const started = await as(EMAILS.ada, "POST", "/api/team/my-connections/apps/gmail/connect");+ expect(started).toMatchObject({ status: 200, body: { url: expect.stringMatching(/^https:\/\/backend\.composio\.dev\/link\//) } });+ expect(project.links).toEqual([{ user: ADA_USER, toolkit: "gmail" }]);+ const adaAccount = project.connect(ADA_USER, "gmail");+ const cleoAccount = await connect(EMAILS.cleo, CLEO_USER);+ const teamAccount = project.connect("openmausbot_team", "slack");++ expect(await myGmail(EMAILS.ada)).toMatchObject({ connected: true, accounts: [{ id: adaAccount, status: "ACTIVE" }] });+ expect(await myGmail(EMAILS.cleo)).toMatchObject({ connected: true, accounts: [{ id: cleoAccount, status: "ACTIVE" }] });+ expect((await host.adminExtras()).people).toMatchObject({ apps: { gmail: [EMAILS.ada, EMAILS.cleo] } });++ expect((await ownCall("ada-chat", ADA)).text).toContain(adaAccount);+ expect((await ownCall("cleo-chat", CLEO)).text).toContain(cleoAccount);+ expect(project.toolCalls.map((call) => call.user)).toEqual([ADA_USER, CLEO_USER]);+ // The team's own bridge is the team's Composio user: it holds neither member's Gmail.+ const team = new TextDecoder().decode((await composio.relayMcp(cfg, GMAIL_CALL)).bytes);+ expect(team).toContain(teamAccount);+ expect(team).not.toContain(adaAccount);+ expect(Object.keys(await composio.connectedServices(cfg))).toEqual(["slack"]);+ expect(cfg.composio?.userId, "the team's saved Composio user is never a member's").toBe("openmausbot_team");++ expect(await as(EMAILS.ada, "DELETE", "/api/team/my-connections/apps/gmail")).toEqual({ status: 200, body: { ok: true } });+ expect(project.accounts.map((account) => account.id).sort()).toEqual([cleoAccount, teamAccount].sort());+ expect((await myGmail(EMAILS.ada)).connected).toBe(false);++ const again = project.connect(ADA_USER, "gmail");+ await host.forgetPerson(ADA);+ expect(project.accounts.map((account) => account.id), "her connections left the project with her").not.toContain(again);+ expect(project.accounts.map((account) => account.id).sort()).toEqual([cleoAccount, teamAccount].sort());+ expect(host.relayActor({ threadId: "ada-chat", generation: "g", connectorsFor: ADA }).refusal).toMatch(/own apps aren't connected here any more/);++ expect(project.requests.every((request) => request.apiKey === KEY)).toBe(true);+ offService();+ });++ it("never uses one member's connection for another member, an admin, a shared chat or work that acts for nobody", async () => {+ const { host, ownCall, connect } = setup();+ const adaAccount = await connect(EMAILS.ada, ADA_USER);+ await connect(EMAILS.cleo, CLEO_USER);++ for (const [thread, person, why] of [["cleo-chat", ADA, "her bridge in Cleo's chat"], ["ada-chat", CLEO, "Cleo's bridge in her chat"], ["room-chat", ADA, "a room reads it"], ["main-chat", ADA, "the bot's main chat"]] as const) {+ expect((await ownCall(thread, person)).refusal, why).toMatch(/no longer acts for/);+ }+ const admin = setup({ requester: { "ada-chat": BEN } });+ await admin.host.people.ensureAppsAccess(ADA, EMAILS.ada);+ expect((await admin.ownCall("ada-chat", ADA)).refusal, "an admin writing in her chat").toMatch(/no longer acts for/);+ const routine = setup({ requester: { "ada-chat": "" } });+ await routine.host.people.ensureAppsAccess(ADA, EMAILS.ada);+ expect((await routine.ownCall("ada-chat", ADA)).refusal, "a routine in her chat").toMatch(/no longer acts for/);+ expect(project.toolCalls, "no refused call reached Composio").toEqual([]);++ const bot = { id: "scout", name: "Scout" };+ expect((await host.appsIntegrations(bot, "ada-chat", "g")).composioOwn).toBeDefined();+ for (const thread of ["room-chat", "main-chat"]) expect((await host.appsIntegrations(bot, thread, "g")).composioOwn, thread).toBeUndefined();+ expect((await admin.host.appsIntegrations(bot, "ada-chat", "g")).composioOwn).toBeUndefined();++ expect((await ownCall("cleo-chat", CLEO)).text).not.toContain(adaAccount);+ expect(project.toolCalls.map((call) => call.user)).toEqual([CLEO_USER]);+ offService();+ });++ it("uses a member's Session only while it is their own Composio user's", async () => {+ const first = setup();+ const adaAccount = await first.connect(EMAILS.ada, ADA_USER);+ const teamAccount = project.connect("openmausbot_team", "gmail");+ await composio.relayMcp(first.cfg, GMAIL_CALL);+ const teamSession = [...project.sessions].find(([, user]) => user === "openmausbot_team")![0];+ const file = first.stored();+ file.people[ADA]!.sessionId = teamSession;+ (first.host.people as unknown as { write(name: string, value: unknown): void }).write("project-apps.json", file);++ const restarted = setup({ dataDir: first.dataDir });+ const answer = (await restarted.ownCall("ada-chat", ADA)).text!;+ expect(answer).toContain(adaAccount);+ expect(answer).not.toContain(teamAccount);+ expect(project.sessions.get(restarted.stored().people[ADA]!.sessionId!)).toBe(ADA_USER);+ });++ it("removes a leaver's connections later when Composio can't be reached as they leave, and before they can connect again", async () => {+ const { host, stored, connect, as } = setup();+ const account = await connect(EMAILS.ada, ADA_USER);+ project.down = true;+ await host.forgetPerson(ADA);+ expect(stored()).toMatchObject({ people: {}, removals: [ADA_USER] });+ expect(project.accounts.map((entry) => entry.id)).toEqual([account]);+ // She joins again while Composio is still away: no link until what she left is gone.+ expect((await as(EMAILS.ada, "POST", "/api/team/my-connections/apps/gmail/connect")).status).toBe(502);+ project.down = false;+ host.primeApps();+ await expect.poll(() => project.accounts.length).toBe(0);+ await expect.poll(() => stored().removals).toEqual([]);+ offService();+ });++ it("refuses an app the team's rules don't allow before anything is asked of Composio", async () => {+ const { as } = setup({ refuse: "Acme does not allow Gmail. Ask a team admin." });+ expect(await as(EMAILS.ada, "POST", "/api/team/my-connections/apps/gmail/connect")).toEqual({ status: 403, body: { error: "Acme does not allow Gmail. Ask a team admin.", code: "managed_policy" } });+ expect(project.requests).toEqual([]);+ offService();+ });+});++describe("a team that changes where its apps connect", () => {+ it("asks a member who connected on the service to connect again once the team saves a key, and leaves the service alone", async () => {+ const { host, cfg, onService, myGmail, as } = setup();+ onService(ADA, EMAILS.ada, ADA_SERVICE_TOKEN);+ expect(host.people.appsAccess(ADA)).toBeNull();+ expect(await myGmail(EMAILS.ada)).toEqual({ slug: "gmail", name: "Gmail", connected: false, reconnect: true, accounts: [] });+ expect((await myGmail(EMAILS.cleo)).reconnect, "Cleo never connected anything").toBeUndefined();+ const line = await host.callRefusal({ threadId: "ada-chat", generation: "g" }, [{ slug: "GMAIL_FETCH_EMAILS" }]);+ expect(line).toMatch(/needs to connect theirs again: Acme changed where its apps connect/);+ expect(line).toContain('"Connect your Gmail again here: https://cloud.example.test/cloud/team/team-acme-1"');+ expect(await host.adminExtras()).toMatchObject({ appsLeftOnService: 1 });+ offService();++ expect((await as(EMAILS.ada, "POST", "/api/team/my-connections/apps/gmail/connect")).status).toBe(200);+ project.connect(ADA_USER, "gmail");+ expect(await myGmail(EMAILS.ada)).toMatchObject({ connected: true });+ expect((await myGmail(EMAILS.ada)).reconnect).toBeUndefined();+ offService();++ // The key is removed: her installation on the service was kept, so it is hers again.+ cfg.composio = { ...cfg.composio, apiKey: "" };+ expect(host.people.appsAccess(ADA)).toEqual({ url: service.url, token: ADA_SERVICE_TOKEN });+ expect((await host.adminExtras() as { appsLeftOnService?: number }).appsLeftOnService).toBeUndefined();+ });++ it("asks a member who connected in the team's project to connect again once the key is removed or names another project", async () => {+ const { host, cfg, connect, myGmail, stored } = setup();+ await connect(EMAILS.ada, ADA_USER);+ expect(stored().people[ADA]?.sessionId).toBeTruthy();++ cfg.composio = { ...cfg.composio, apiKey: "" };+ expect(host.people.appsAccess(ADA)).toBeNull();+ expect(await myGmail(EMAILS.ada)).toMatchObject({ connected: false, reconnect: true });+ expect(service.requests, "nothing is asked of the service for someone with no installation there").toEqual([]);++ cfg.composio = { ...cfg.composio, apiKey: KEY };+ expect(await myGmail(EMAILS.ada), "the same key again: the same Composio user, still connected").toMatchObject({ connected: true });++ cfg.composio = { ...cfg.composio, apiKey: "ak_another_project" };+ expect(host.people.appsElsewhere(ADA)).toBe(true);+ expect(stored().people[ADA]).toEqual({ email: EMAILS.ada, userId: ADA_USER, again: true });+ });++ it("works with the service switched off and a key, and says an admin must add a key without one", async () => {+ vi.stubEnv("OMB_COMPOSIO_BROKER", "off");+ const keyed = setup();+ await keyed.connect(EMAILS.ada, ADA_USER);+ expect(await keyed.myGmail(EMAILS.ada)).toMatchObject({ connected: true });+ expect((await keyed.ownCall("ada-chat", ADA)).text).toContain(ADA_USER);+ expect((await keyed.as(EMAILS.ada, "GET", "/api/team/my-connections")).body.ownApps).toBeUndefined();+ offService();++ const before = project.requests.length;+ const bare = setup({ key: null });+ expect(await bare.as(EMAILS.ada, "POST", "/api/team/my-connections/apps/gmail/connect")).toEqual({ status: 409, body: {+ error: "Your own apps can't be connected on Acme yet. Ask an admin to add the team's Composio key.",+ errorKey: "serverError.team.ownAppsNeedKey", errorParams: { team: "Acme" }, code: "own_apps_need_key",+ } });+ expect((await bare.as(EMAILS.ada, "GET", "/api/team/my-connections")).body).toMatchObject({ ownApps: "needs-key", apps: [{ slug: "gmail", connected: false }] });+ expect(await bare.host.callRefusal({ threadId: "ada-chat", generation: "g" }, [{ slug: "GMAIL_FETCH_EMAILS" }]))+ .toContain(`"Gmail can't be connected on Acme yet. Ask an admin to add the team's Composio key."`);+ expect(project.requests.length).toBe(before);+ offService();+ });++ it("keeps a member's apps on the service while the team has no key", async () => {+ const { as, host, dataDir } = setup({ key: null });+ const started = await as(EMAILS.ada, "POST", "/api/team/my-connections/apps/gmail/connect");+ expect(started).toEqual({ status: 200, body: { url: "https://backend.composio.dev/link/lk_service" } });+ expect(service.requests).toEqual(["POST /v1/installations", "POST /v1/connectors/gmail/authorize"]);+ expect(host.people.appsAccess(ADA)).toMatchObject({ url: service.url });+ expect((await as(EMAILS.ada, "GET", "/api/team/my-connections")).body).not.toHaveProperty("ownApps");+ expect(() => readFileSync(join(dataDir, "people-connections", "project-apps.json"))).toThrow();+ expect(project.requests).toEqual([]);+ });+});diff --git a/server/index.ts b/server/index.tsindex 4c44aa2bfd..207302f4e4 100644--- a/server/index.ts+++ b/server/index.ts@@ -2818,7 +2818,7 @@ const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, leconst { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPersonStop({store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, stopping: (botId, threadId) => idleThreads.stopping(botId, threadId), clearUnattended,stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId, by) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId), by), working: (botId, threadId) => threadBusy(botId, threadId) || coordinator.activeDirect(threadId), asking: (threadId) => coordinator.awaitingAnswer(threadId) || Boolean(openPersonCard(threadId)), language: threadLanguage, stopRefusal: (threadId, by) => runOwners.stopRefusal(threadId, by),-}); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, waiting: () => personWaits.waiting(), send: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); }, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayAnswer: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow") === null, viewer: (auth) => placeInboxViewer(auth, { personal: CLOUD_PERSONAL, owner: cloudOwnerSession, personOf: personKey }), guestOf: (threadId) => { if (!CLOUD_PERSONAL || !cloudGuestDriven(threadId)) return null; const person = [...cloudThreadStarters(threadId), threadPersonKey(threadId)].find((one) => one && one !== CLOUD_OUTSIDE_KEY && !cloudOwnerPerson(one)); return person ?? null; }, guestName: (threadId) => guestNameIn(store.messagesFor(threadId)), handedBy: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.botId ?? store.botByThread(from.threadId)?.id ?? null : null; } }), team: CLOUD_TEAM, dataDir: DATA_DIR, store, confined: (threadId) => cloudGuestDriven(threadId), people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, delivered: (item, delivery) => teamAway.delivered(item, delivery), changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null, opened: (made) => void mausbotOwnChat.claim(made) }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });+}); const teamMessages = createTeamMessages({ place: CLOUD_TEAM ? null : createPlaceInbox({ dataDir: DATA_DIR, store, openCards: openCardRows, waiting: () => personWaits.waiting(), send: (notification) => { broadcast({ kind: "notify", notification: logNotification(notification) }); }, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), mayAnswer: (auth, threadId, requestId) => cardAnswerRefusal(auth, threadId, requestId, "allow") === null, viewer: (auth) => placeInboxViewer(auth, { personal: CLOUD_PERSONAL, owner: cloudOwnerSession, personOf: personKey }), guestOf: (threadId) => { if (!CLOUD_PERSONAL || !cloudGuestDriven(threadId)) return null; const person = [...cloudThreadStarters(threadId), threadPersonKey(threadId)].find((one) => one && one !== CLOUD_OUTSIDE_KEY && !cloudOwnerPerson(one)); return person ?? null; }, guestName: (threadId) => guestNameIn(store.messagesFor(threadId)), handedBy: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.botId ?? store.botByThread(from.threadId)?.id ?? null : null; } }), team: CLOUD_TEAM, dataDir: DATA_DIR, store, confined: (threadId) => cloudGuestDriven(threadId), people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, delivered: (item, delivery) => teamAway.delivered(item, delivery), changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null, opened: (made) => void mausbotOwnChat.claim(made) }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(...teamConnections.via(access))).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(teamConnections.via(access)[0], payload as never, session, undefined, signal, teamConnections.via(access)[1]) }).busy } } });const imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });@@ -12301,7 +12301,7 @@ const taskRoutes = createTaskRoutes({revokeInternalCapabilitiesForThread,stagedSkillCleanupsForThread,rejectDeletedThreadSkillStages,-}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { teamConnections.forgetPerson(person); connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); }, ...teamRoutines.leaving, forgetOnBots: (email) => forgetMember(store, email, (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access)).length, ownerOf: (botId) => { const bot = store.bot(botId); return bot ? botOwner(bot) : null; }, record: (row) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: "MausBot Cloud" } }) }) : null;+}); ROUTES.push(taskRoutes); const leaveTeam = CLOUD_TEAM ? createTeamMemberLeft({ dataDir: DATA_DIR, store, openedBy: (person) => threadStarters.threadsOf(person, 50_000), privateTo: teamHost.privateTo, revokeSessions: (email) => sessions.revokeMember(email), busy: threadBusy, stop: (botId, threadId) => interruptDirectThread(botId, threadId, "The person left the team"), deleteTasks: taskRoutes.deleteTasks, stopBot: (botId) => memberOwnBot.stopWork(botId, "The person left the team"), deleteBot: memberOwnBot.remove, threadsReferencing, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), eraseBrowsers: eraseAudienceBrowsers, forgetConnections: (person) => { connectionHealth.forgetPerson(person); personRooms.reads?.forgetPerson(person); return teamConnections.forgetPerson(person); }, ...teamRoutines.leaving, forgetOnBots: (email) => forgetMember(store, email, (bot, access) => writeAccess({ store, publicGroupState, broadcast, audienceChanged }, bot, access)).length, ownerOf: (botId) => { const bot = store.bot(botId); return bot ? botOwner(bot) : null; }, record: (row) => appendAdminAction(DATA_DIR, { ...row, actor: { kind: "session", sessionId: "", label: "MausBot Cloud" } }) }) : null;ROUTES.push(createTeamRoutes({store,cfg,@@ -14403,7 +14403,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}if (call.kind === "tools") {// Real connected-service slugs, so an underscored service (bland_ai) is not captured by a plain-prefix grant (bland).- serviceSlugs = await composio.connectedServiceSlugs(cfg, actor.access);+ serviceSlugs = await composio.connectedServiceSlugs(...teamConnections.via(actor.access));requireActiveInternalCapability();currentSender = store.bot(internalCapability.botId);if (!currentSender || currentSender.composio === false || !composio.configured(cfg)) return json(res, 403, { error: "connected apps are no longer enabled for this bot" });@@ -14496,7 +14496,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {};let upstream: Awaited<ReturnType<typeof composio.relayMcp>>;try { upstream = await composio.relayMcp(- cfg,+ teamConnections.via(actor.access)[0],body,Array.isArray(req.headers["mcp-session-id"])? req.headers["mcp-session-id"][0]@@ -14526,7 +14526,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}}for (const key of nextDrafts) reservedDrafts.add(key);- }, undefined, actor.access,+ }, undefined, teamConnections.via(actor.access)[1],); } catch (error) {if (dispatchRefusal) return refuseOutbound(dispatchRefusal);throw error;diff --git a/server/routes/team-connections.ts b/server/routes/team-connections.tsindex 1749eef67d..def1e6739a 100644--- a/server/routes/team-connections.ts+++ b/server/routes/team-connections.ts@@ -75,20 +75,22 @@ export function createTeamConnectionRoutes(deps: TeamConnectionRouteDeps): Routeif (!member || auth.kind !== "session") return json(res, 403, { error: `Sign in to ${team.name} to connect your own apps.` });const person = personKey({ id: "", email: member.member.email });const email = member.member.email;- const cfg = deps.cfg();if (path === MY_CONNECTIONS_PATH) {if (method !== "GET") return json(res, 405, { error: "method not allowed" });const apps = deps.host.personApps();const access = deps.host.people.appsAccess(person);- const states = access && apps.length ? await deps.composio.connectedServices(cfg, access).catch(() => null) : null;+ const states = access && apps.length ? await deps.composio.connectedServices(...deps.host.via(access)).catch(() => null) : null;+ const again = apps.length > 0 && deps.host.people.appsElsewhere(person);return json(res, 200, {team: { id: team.id, name: team.name },link: deps.host.link(),email,+ ...(deps.host.ownAppsNeedKey() ? { ownApps: "needs-key" as const } : {}),apps: apps.map((slug) => {const state = states?.[slug];return { slug, name: appLabel(slug), connected: state?.connected === true,+ ...(again && state?.connected !== true ? { reconnect: true as const } : {}),accounts: (state?.accounts ?? []).map((account) => ({ id: account.id, alias: account.alias?.trim() || null, status: account.status })) };}),mcp: deps.host.personMcp().flatMap((name) => {@@ -111,10 +113,12 @@ export function createTeamConnectionRoutes(deps: TeamConnectionRouteDeps): Routeif (app[2] && method === "POST") {const refused = deps.policy?.appRefusal(slug);if (refused) return json(res, 403, { error: refused, code: "managed_policy" });- const access = await deps.host.people.ensureAppsAccess(person, email);- if (!access) return json(res, 503, { error: "Connected apps aren't available on this Cloud right now. Try again in a minute." });+ if (deps.host.ownAppsNeedKey()) return json(res, 409, { ...userError("serverError.team.ownAppsNeedKey", { team: team.name }), code: "own_apps_need_key" });try {- const started = await deps.composio.authorizeService(cfg, slug, null, access);+ const access = await deps.host.people.ensureAppsAccess(person, email);+ if (!access) return json(res, 503, { error: "Connected apps aren't available on this Cloud right now. Try again in a minute." });+ const [asThem, installation] = deps.host.via(access);+ const started = await deps.composio.authorizeService(asThem, slug, null, installation);deps.host.people.appConnecting(person, slug);return json(res, 200, started);} catch (error) {@@ -124,7 +128,7 @@ export function createTeamConnectionRoutes(deps: TeamConnectionRouteDeps): Route}if (!app[2] && method === "DELETE") {const access = deps.host.people.appsAccess(person);- if (access) await deps.composio.removeService(cfg, slug, access);+ if (access) { const [asThem, installation] = deps.host.via(access); await deps.composio.removeService(asThem, slug, installation); }return json(res, 200, { ok: true });}return json(res, 405, { error: "method not allowed" });diff --git a/server/team-connections.ts b/server/team-connections.tsindex b7d4a82bc9..c257e7ae75 100644--- a/server/team-connections.ts+++ b/server/team-connections.ts@@ -3,15 +3,21 @@// only in that member's own turns in their private chat.// - team-connection-scopes.json: which apps and servers are `person` (no secret; backups carry it);// - people-connections/: each member's own installation on the connected-apps service (their own Composio user), their-// own MCP keys and their own MCP sign-ins.+// own MCP keys and their own MCP sign-ins. While the team has its own Composio project key, a member's apps are+// their own Composio user in that project instead (project-apps.json: a user id and a Session id, no secret), and+// nothing of theirs is sent to the connected-apps service.// Security: 0600 files in a 0700 folder that no backup carries and no bot box binds; a member's key and sign-in are pinned// to the server's address, so an admin re-pointing a server never sends them on.+import { createHash } from "node:crypto";import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";import { join } from "node:path";import { z } from "zod";import { ensureManagedComposioCredentials, managedComposioAccess } from "../electron/managed-composio.mjs";import { writeFileAtomic } from "./atomic.ts";+import type { AppConfig } from "./config.ts";+import { removeUserConnections } from "./composio-project.ts";+import { keepSessionWith } from "./composio-session.ts";import { McpOAuthManager, type McpRefreshOutcome, type McpSignInPhase } from "./mcp-oauth.ts";import type { McpOAuthClientConfig } from "./mcp-registry.ts";@@ -84,15 +90,46 @@ const keysSchema = z.object({servers: z.record(z.string(), z.object({ url: z.string(), header: z.string(), value: z.string() })).default({}),})).default({}),});+const projectAppsSchema = z.object({+ v: z.literal(1),+ /** Which project key the Sessions and waiting removals below were made with: a short hash, never the key. */+ keyMark: z.string(),+ people: z.record(z.string(), z.object({ email: z.string(), userId: z.string().min(1), sessionId: z.string().optional(), again: z.literal(true).optional() })).default({}),+ /** Composio users of people who left, whose connections in the project are still to be removed. */+ removals: z.array(z.string()).default([]),+});+type ProjectAppsFile = z.infer<typeof projectAppsSchema>;type AppsFile = z.infer<typeof appsSchema>;type KeysFile = z.infer<typeof keysSchema>;export interface PersonKey { url: string; header: string; value: string }export interface BrokerAccess { url: string; token: string }+/** A member's own Composio user in the team's project: what `cfg.composio` is for a call made as them. */+export interface ProjectAccess { composio: { apiKey: string; userId: string; sessionId?: string } }+/** A member's own apps: their installation on the connected-apps service, or with the team's own key their Composio user. */+export type PersonAppsAccess = BrokerAccess | ProjectAccess;+export const isProjectAccess = (access: PersonAppsAccess | null | undefined): access is ProjectAccess => Boolean(access && "composio" in access);++/** How a connected-apps call is made as a member: with the team's own key, the team's config with their Composio user+ * in place of the team's; else the team's config and their installation. */+export const asPerson = (cfg: AppConfig, access?: PersonAppsAccess | null): [AppConfig, BrokerAccess | undefined] =>+ isProjectAccess(access) ? [{ ...cfg, composio: access.composio }, undefined] : [cfg, access ?? undefined];++const keyMarkOf = (apiKey: string) => createHash("sha256").update("omb-project-apps\0").update(apiKey).digest("hex").slice(0, 16);++/** A member's Composio user id in the team's project: the same at every start, from the team's id and the person key (a+ * hash), so Composio is given no address.+ * Security: never `openmausbot_…`, the prefix a personal installation on the same key may adopt as its own user. */+export function memberComposioUser(teamId: string, person: string): string {+ return `omb_member_${createHash("sha256").update("omb-team-member\0").update(teamId).update("\0").update(person).digest("hex").slice(0, 32)}`;+}export interface PeopleConnectionsOptions {dataDir: string;/** The connected-apps service a member's own installation is made on (the Cloud home's own); null: none here. */brokerUrl: () => string | null;+ /** The team's id and its own Composio project key, when it has one: members' apps then live in that project. */+ teamId?: string;+ projectKey?: () => string | null;/** The team server's sign-in app for an MCP server, when an admin set one (config.json `oauth`). */clients: (name: string, url: string) => McpOAuthClientConfig | undefined;isOwnerLive: (owner: string) => boolean;@@ -110,6 +147,7 @@ export class PeopleConnections {readonly dir: string;private readonly managers = new Map<string, McpOAuthManager>();private readonly registering = new Map<string, Promise<BrokerAccess | null>>();+ private readonly projectUsers = new Map<string, ProjectAccess["composio"]>();private readonly options: PeopleConnectionsOptions;constructor(options: PeopleConnectionsOptions) {this.options = options;@@ -137,15 +175,101 @@ export class PeopleConnections {return this.read<KeysFile>("mcp-keys.json", keysSchema, { v: 1, people: {} });}- /** The member's own installation, when they have made one. */- appsAccess(person: string): BrokerAccess | null {+ private projectKey(): string | null {+ return this.options.teamId ? this.options.projectKey?.() ?? null : null;+ }+ private stored<T>(name: string, schema: z.ZodType<T>): T | null {+ try { return schema.parse(JSON.parse(readFileSync(join(this.dir, name), "utf8"))); } catch { return null; }+ }+ /** What is kept for the project this key opens. Under another key the Sessions are gone, everyone connects again, and+ * a removal still waiting can't be done any more: the earlier project's connections are out of reach. */+ private projectApps(apiKey: string): ProjectAppsFile {+ const keyMark = keyMarkOf(apiKey);+ const file = this.stored("project-apps.json", projectAppsSchema);+ if (!file) return { v: 1, keyMark, people: {}, removals: [] };+ if (file.keyMark === keyMark) return file;+ if (file.removals.length) console.warn(`[team connections] the Composio project key changed: ${file.removals.length} member(s) who left still have connections in the earlier project, which can't be removed from here`);+ this.projectUsers.clear();+ const moved: ProjectAppsFile = { v: 1, keyMark, removals: [], people: Object.fromEntries(Object.entries(file.people).map(([person, record]) => [person, { email: record.email, userId: record.userId, again: true as const }])) };+ this.write("project-apps.json", moved);+ return moved;+ }+ private projectAccess(person: string, apiKey: string): ProjectAccess | null {+ const record = this.projectApps(apiKey).people[person];+ if (!record) return null;+ let composio = this.projectUsers.get(person);+ if (!composio || composio.userId !== record.userId) {+ composio = { apiKey, userId: record.userId, ...(record.sessionId ? { sessionId: record.sessionId } : {}) };+ this.projectUsers.set(person, composio);+ keepSessionWith(composio, ({ sessionId }) => {+ const file = this.projectApps(apiKey), own = file.people[person];+ if (!own || own.userId !== record.userId) return;+ file.people[person] = { ...own, sessionId };+ this.write("project-apps.json", file);+ });+ }+ composio.apiKey = apiKey;+ return { composio };+ }+ private async ensureProjectAccess(person: string, email: string, apiKey: string): Promise<ProjectAccess | null> {+ const userId = memberComposioUser(this.options.teamId!, person);+ if (this.projectApps(apiKey).removals.includes(userId)) await this.removeLeftUser(apiKey, userId);+ const file = this.projectApps(apiKey), held = file.people[person];+ if (!held || held.again) {+ file.people[person] = { email, userId, ...(held?.sessionId ? { sessionId: held.sessionId } : {}) };+ this.write("project-apps.json", file);+ this.remember(person, email);+ }+ return this.projectAccess(person, apiKey);+ }+ private async removeLeftUser(apiKey: string, userId: string): Promise<void> {+ await removeUserConnections(apiKey, userId);+ const file = this.projectApps(apiKey);+ if (!file.removals.includes(userId)) return;+ file.removals = file.removals.filter((left) => left !== userId);+ this.write("project-apps.json", file);+ }+ /** Removes what people who left still have connected in the team's project; a failure waits for the next call. */+ async finishRemovals(): Promise<void> {+ const apiKey = this.projectKey();+ if (!apiKey) return;+ for (const userId of this.projectApps(apiKey).removals) {+ await this.removeLeftUser(apiKey, userId).catch((error: unknown) => {+ console.warn(`[team connections] a member who left still has connections in the team's Composio project (${userId}): ${error instanceof Error ? error.message : String(error)}`);+ });+ }+ }+ /** Whether the person connected apps where the team's apps no longer go (the connected-apps service before the team+ * saved its own key, or the reverse, or another project): nothing carries over, so they connect again. */+ appsElsewhere(person: string): boolean {+ const apiKey = this.projectKey();+ if (apiKey) {+ const record = this.projectApps(apiKey).people[person];+ return record ? record.again === true : Boolean(this.stored("apps.json", appsSchema)?.people[person]);+ }+ return !this.appsAccess(person) && Boolean(this.stored("project-apps.json", projectAppsSchema)?.people[person]);+ }+ /** How many members' installations are still on the connected-apps service while the team uses its own key. */+ appsLeftOnService(): number {+ return this.projectKey() ? Object.keys(this.stored("apps.json", appsSchema)?.people ?? {}).length : 0;+ }++ /** The member's own apps, when they have connected any: their Composio user in the team's project while the team has+ * its own key, else their installation on the connected-apps service. */+ appsAccess(person: string): PersonAppsAccess | null {+ const apiKey = this.projectKey();+ return apiKey ? this.projectAccess(person, apiKey) : this.serviceAccess(person);+ }+ private serviceAccess(person: string): BrokerAccess | null {const file = this.apps(), record = file.people[person];return record ? managedComposioAccess(file.brokerUrl, { composioBrokerToken: record.token }) : null;}- /** The member's own installation, made now if they have none (the first time they connect an app). */- ensureAppsAccess(person: string, email: string): Promise<BrokerAccess | null> {+ /** The member's own apps, made now if they have none (the first time they connect an app). */+ ensureAppsAccess(person: string, email: string): Promise<PersonAppsAccess | null> {if (!PERSON.test(person)) return Promise.resolve(null);- const held = this.appsAccess(person);+ const apiKey = this.projectKey();+ if (apiKey) return this.ensureProjectAccess(person, email, apiKey);+ const held = this.serviceAccess(person);if (held) return Promise.resolve(held);const brokerUrl = this.options.brokerUrl();if (!brokerUrl) return Promise.resolve(null);@@ -163,13 +287,20 @@ export class PeopleConnections {this.remember(person, email);},});- return this.appsAccess(person);+ return this.serviceAccess(person);})().finally(() => this.registering.delete(person));this.registering.set(person, made);return made;}- /** Everyone with an installation, with their address (for "who has connected"). */- appsPeople(): Array<{ person: string; email: string; access: BrokerAccess }> {+ /** Everyone with apps of their own, with their address (for "who has connected"). */+ appsPeople(): Array<{ person: string; email: string; access: PersonAppsAccess }> {+ const apiKey = this.projectKey();+ if (apiKey) {+ return Object.entries(this.projectApps(apiKey).people).flatMap(([person, record]) => {+ const access = this.projectAccess(person, apiKey);+ return access ? [{ person, email: record.email, access }] : [];+ });+ }const file = this.apps();return Object.entries(file.people).flatMap(([person, record]) => {const access = managedComposioAccess(file.brokerUrl, { composioBrokerToken: record.token });@@ -265,15 +396,24 @@ export class PeopleConnections {if (PERSON.test(person)) this.oauth(person).forget(name);}}- /** Test seam and deletion: everything a person connected here. */- forgetPerson(person: string): void {+ /** Test seam and deletion: everything a person connected here. What they connected in the team's own Composio project+ * is removed there too, at once when Composio answers, else by `finishRemovals`. */+ async forgetPerson(person: string): Promise<void> {const apps = this.apps();if (apps.people[person]) { delete apps.people[person]; this.write("apps.json", apps); }+ const project = this.stored("project-apps.json", projectAppsSchema);+ const left = project?.people[person];+ if (project && left) {+ delete project.people[person];+ this.write("project-apps.json", { ...project, removals: [...new Set([...project.removals, left.userId])] });+ this.projectUsers.delete(person);+ }const keys = this.keys();if (keys.people[person]) { delete keys.people[person]; this.write("mcp-keys.json", keys); }this.managers.get(person)?.dispose();this.managers.delete(person);rmSync(join(this.dir, "mcp-oauth", `${person}.json`), { force: true });+ if (left) await this.finishRemovals();}}diff --git a/server/testing/fake-composio-project.ts b/server/testing/fake-composio-project.tsnew file mode 100644index 0000000000..83e7270713--- /dev/null+++ b/server/testing/fake-composio-project.ts@@ -0,0 +1,122 @@+// A loopback stand-in for a team's own Composio project, as OMB_COMPOSIO_API names it: Tool Router Sessions, connect+// links, connected accounts and each Session's MCP endpoint, kept per Composio user. Every request is recorded with the+// user it was made for, so a test can say whose connection a call used. Nothing leaves the machine.+import { createServer, type IncomingMessage } from "node:http";+import type { AddressInfo } from "node:net";++export interface FakeComposioAccount { id: string; user_id: string; toolkit: { slug: string }; status: string; updated_at: string }++export interface FakeComposioProject {+ /** What OMB_COMPOSIO_API is set to. */+ api: string;+ origin: string;+ accounts: FakeComposioAccount[];+ /** Session id → the Composio user it was made for. */+ sessions: Map<string, string>;+ /** Every request, in order: `user` is the Composio user it named or whose Session it used. */+ requests: Array<{ method: string; path: string; apiKey: string | null; user?: string }>;+ /** Each tools/call that reached a Session's MCP endpoint. */+ toolCalls: Array<{ user: string; tool: string; slugs: string[] }>;+ /** Each connect link asked for. */+ links: Array<{ user: string; toolkit: string }>;+ /** The person finished the sign-in: an active account for that user. */+ connect(userId: string, toolkit: string): string;+ /** While true, every request answers 503. */+ down: boolean;+ close(): Promise<void>;+}++async function json(req: IncomingMessage): Promise<Record<string, unknown>> {+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(chunk as Buffer);+ try { return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}") as Record<string, unknown>; } catch { return {}; }+}++export async function startFakeComposioProject(apiKey: string): Promise<FakeComposioProject> {+ let serial = 0;+ const fake: Omit<FakeComposioProject, "api" | "origin" | "close"> = {+ accounts: [], sessions: new Map(), requests: [], toolCalls: [], links: [], down: false,+ connect(userId, toolkit) {+ const id = `ca_fake${String(++serial).padStart(4, "0")}`;+ fake.accounts.push({ id, user_id: userId, toolkit: { slug: toolkit }, status: "ACTIVE", updated_at: new Date(serial * 1000).toISOString() });+ return id;+ },+ };+ let origin = "";+ const session = (id: string) => ({+ session_id: id, mcp: { type: "http", url: `${origin}/mcp/${id}` },+ config: { user_id: fake.sessions.get(id), multi_account: { enable: true, max_accounts_per_toolkit: 5, require_explicit_selection: true } },+ });++ const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", origin);+ const path = url.pathname.replace(/^\/api\/v3\.1/, "");+ const key = typeof req.headers["x-api-key"] === "string" ? req.headers["x-api-key"] : null;+ const record: FakeComposioProject["requests"][number] = { method: req.method ?? "GET", path, apiKey: key };+ fake.requests.push(record);+ const send = (status: number, body: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };+ if (fake.down) return send(503, { message: "Composio is unavailable" });+ if (key !== apiKey) return send(401, { message: "Invalid API key" });+ const body = req.method === "POST" || req.method === "PATCH" ? await json(req) : {};++ if (path === "/auth_configs") return send(200, { items: [] });+ if (path === "/tool_router/session" && req.method === "POST") {+ const id = `trs_fake${++serial}`;+ record.user = String(body.user_id);+ fake.sessions.set(id, record.user);+ return send(201, session(id));+ }+ const routed = /^\/tool_router\/session\/([^/]+)(\/toolkits|\/link)?$/.exec(path);+ if (routed) {+ const id = decodeURIComponent(routed[1]!), user = fake.sessions.get(id);+ if (!user) return send(404, { message: "Session not found" });+ record.user = user;+ if (!routed[2]) return send(200, session(id));+ if (routed[2] === "/link") {+ fake.links.push({ user, toolkit: String(body.toolkit) });+ return send(200, { redirect_url: `https://backend.composio.dev/link/lk_fake${++serial}` });+ }+ const wanted = url.searchParams.get("toolkits")?.split(",").filter(Boolean);+ const items = fake.accounts.filter((account) => account.user_id === user && (!wanted || wanted.includes(account.toolkit.slug)))+ .map((account) => ({ slug: account.toolkit.slug, connected_account: { id: account.id, status: account.status } }));+ return send(200, { items });+ }+ if (path === "/connected_accounts" && req.method === "GET") {+ const user = url.searchParams.get("user_ids"), slugs = url.searchParams.get("toolkit_slugs")?.split(",").filter(Boolean);+ if (user) record.user = user;+ return send(200, { items: fake.accounts.filter((account) => (!user || account.user_id === user) && (!slugs || slugs.includes(account.toolkit.slug))) });+ }+ const account = /^\/connected_accounts\/([^/]+)$/.exec(path);+ if (account && req.method === "DELETE") {+ const index = fake.accounts.findIndex((entry) => entry.id === decodeURIComponent(account[1]!));+ if (index < 0) return send(404, { message: "Connected account not found" });+ record.user = fake.accounts[index]!.user_id;+ fake.accounts.splice(index, 1);+ return send(200, { success: true });+ }+ const mcp = /^\/mcp\/([^/]+)$/.exec(url.pathname);+ if (mcp && req.method === "POST") {+ const user = fake.sessions.get(decodeURIComponent(mcp[1]!));+ if (!user) return send(404, { message: "Session not found" });+ record.user = user;+ const frame = body as { id?: unknown; method?: string; params?: { name?: string; arguments?: { tools?: Array<{ tool_slug?: string }> } } };+ if (frame.id === undefined) { res.writeHead(202); return res.end(); }+ if (frame.method === "initialize") return send(200, { jsonrpc: "2.0", id: frame.id, result: { protocolVersion: "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "fake-composio", version: "1" } } });+ if (frame.method === "tools/list") return send(200, { jsonrpc: "2.0", id: frame.id, result: { tools: [{ name: "COMPOSIO_MULTI_EXECUTE_TOOL", inputSchema: { type: "object" } }] } });+ if (frame.method === "tools/call") {+ const slugs = (frame.params?.arguments?.tools ?? []).map((tool) => String(tool.tool_slug));+ fake.toolCalls.push({ user, tool: String(frame.params?.name), slugs });+ const mine = fake.accounts.filter((entry) => entry.user_id === user).map((entry) => entry.id);+ return send(200, { jsonrpc: "2.0", id: frame.id, result: { content: [{ type: "text", text: JSON.stringify({ successful: true, data: { as: user, accounts: mine } }) }] } });+ }+ return send(200, { jsonrpc: "2.0", id: frame.id, error: { code: -32601, message: "Method not found" } });+ }+ return send(404, { message: `no fake for ${req.method} ${path}` });+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ return Object.assign(fake, {+ api: `${origin}/api/v3.1`, origin,+ close: () => new Promise<void>((resolve) => { server.closeAllConnections(); server.close(() => resolve()); }),+ });+}diff --git a/server/user-errors.ts b/server/user-errors.tsindex 0fb1f85da4..1db6a862fa 100644--- a/server/user-errors.ts+++ b/server/user-errors.ts@@ -31,6 +31,7 @@ export const USER_ERROR = {"serverError.team.personalMove": "Moving a computer's bots, chats and logins goes to My Cloud only. Nothing personal comes into {team}.","serverError.team.memberLogin": "On {team} only an admin can save a login, and it is then used by every bot in {team}.","serverError.team.signInFirst": "Sign in to {team} in the app first.",+ "serverError.team.ownAppsNeedKey": "Your own apps can't be connected on {team} yet. Ask an admin to add the team's Composio key.","serverError.chat.ownerOrAdmin": "Only the owner or an admin can do that.","serverError.routine.checks": "Choose checks from calendar, mail and runs","serverError.routine.checksRepeat": "Checks need a bot routine that repeats",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 7d0b48c95b..d1ac4dc176 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -9126,6 +9126,7 @@"serverError.team.personalMove": "Moving a computer's bots, chats and logins goes to My Cloud only. Nothing personal comes into {team}.","serverError.team.memberLogin": "On {team} only an admin can save a login, and it is then used by every bot in {team}.","serverError.team.signInFirst": "Sign in to {team} in the app first.",+ "serverError.team.ownAppsNeedKey": "Your own apps can't be connected on {team} yet. Ask an admin to add the team's Composio key.","serverError.chat.ownerOrAdmin": "Only the owner or an admin can do that.","serverError.routine.checks": "Choose checks from calendar, mail and runs","serverError.routine.checksRepeat": "Checks need a bot routine that repeats",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex b9f3bb2be7..e2e309cbdf 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -9082,6 +9082,7 @@"serverError.team.personalMove": "Os bots, as conversas e os logins de um computador só podem ir para o Cloud. Nada pessoal entra em {team}.","serverError.team.memberLogin": "Em {team}, só um admin pode salvar um login. Todos os bots de {team} passam a usar esse login.","serverError.team.signInFirst": "Primeiro, faça login em {team} no app.",+ "serverError.team.ownAppsNeedKey": "Ainda não dá para conectar seus próprios apps em {team}. Peça a um admin para adicionar a chave do Composio da equipe.","serverError.chat.ownerOrAdmin": "Só o dono ou um admin pode fazer isso.","serverError.routine.checks": "Escolha o que verificar: agenda, e-mail e execuções.","serverError.routine.checksRepeat": "As verificações precisam de uma rotina de bot que se repita.",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex 79ae055839..89bcbf783a 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -32510,6 +32510,7 @@"serverError.team.personalMove": "14183b232a83737432ff1bf827f42c48f2470482bae7651062f74b39b890733f","serverError.team.memberLogin": "5dd9928759fc504e20d8fb96149540b933672d7bdbb053051970fe17f6846abd","serverError.team.signInFirst": "57b3710b48a3cafe6fbe9187b7e7813caf7013b9c154dba8bd380135f12e3464",+ "serverError.team.ownAppsNeedKey": "4d48b8af60bdde2c81cd631441328bd6be57a15aa5d05971d79a778d62194f76","serverError.chat.ownerOrAdmin": "dc59e0b9afbf73a927e2ca509f146e450dfa5e37acba6b71ab882a120a86a51c","serverError.routine.checks": "e46bf10296c403ff91f6f7591a0f313f8741f92b9a81bd5e72d3e2b3d381d23b","serverError.routine.checksRepeat": "9a0cfea31637dae47c766b895467c37928a7b32e8b044b223aaa57f2ec7cce81",