Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Team Clouds enforce their team's rules, fetched from the Admin (#4176)
Milind Sonic355f2f6cebc
diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 0d48f5fea0..4ef04c53bd 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -41,6 +41,8 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes tmap's "Who reports to whom", a card's "Asking Ada", the @ list, a "Told Bob" chip, a Needs you line from them) it showstheir picture, or their initial when they have none; the picture is served to the team's signed-in members only(below), never off the team.+- **Rules.** A team's Owner and Admins choose the AI engines and computers its bots may use, whether bots may add MCP servers+ of their own, and whether it opens on a phone or with a link (below, "Rules"). What they restrict shows as *Managed by Acme*.- **Connected apps.** The team's connections (Composio, HighLevel, MCP sign-ins, an AI key an Admin saved) belong to theTeam Cloud and serve every member's turn through the broker. An Admin can instead make an app or an MCP server *eachperson's own* (below): then every member connects their own, and only their own chats use it. A person's@@ -62,6 +64,33 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes t- **Never asleep, kept across restarts.** A Team Cloud refuses the Admin's sleep request (`busy: ["team"]`) and keepsevery member's session across a restart; a My Cloud revokes every session that is not its owner's at each boot.+## Rules++The team's rules live on the Admin (openmaus-cloud `docs/team-cloud.md` "Rules"): one document, `{ schema: 1, limits }`, that+only restricts. `server/cloud-team-policy.ts` fetches it at boot, every 5 minutes and when the Admin's signed `POST+/api/cloud/team/policy-changed` nudges it, signed with the bootstrap secret (`POST /api/cloud/machines/team-policy`), and each+request reports the fingerprint in force here. A change applies without a restart.++- **One enforcement.** The document is projected into the one policy object (`server/managed-policy.ts`) every refusal site+ and every "Managed by" screen already reads. Nothing restricted: no object at all, as on a team with no rules. Admins are not exempt.+- **What passes through it.** Every turn start, direct or in a group chat, whoever or whatever asked: a person, a routine, a+ webhook, another bot, a retry, a backup engine and every side job meet `policyModelRefusal`. Every computer claim meets+ `bindTurnComputer`, and a lent computer's request is refused too (nobody's Mac serves a team anyway). A turn's MCP servers+ all come through `mcpServersHost.mounted`, which drops what isn't allowed, whoever connected it; adding or signing in to one is+ refused. `allowedMcpServers: "team"` is the plain form: admins add servers as ever, a bot can't add one, a bot's own doesn't+ start and an engine's own user settings aren't read. Every connected-apps tool crosses `POST /api/internal/connectors/mcp`, which refuses a tool of an app that isn't+ allowed, and code that could reach any app; connecting one is refused, and HighLevel isn't mounted.+- **Remote access** on a Team Cloud is what a member's own code opens: "Open on your phone" is refused, codes already made stop+ working and phones already open sign out. The Admin-signed pairing stays: it is how every member's app and the Admin reach+ this machine, so a rule never locks the team out.+- **Kept rules.** The last valid document stays in `team-policy.json` (0600, bound to this team, in no backup) and applies at+ boot before anything starts. It never lapses: an Admin that can't be reached leaves it in force. With `requireFreshPolicy`,+ new turns are refused in plain words once the Admin hasn't confirmed it for 15 minutes. A document this version can't read+ (a newer schema, a key it can't enforce) leaves the last good one in force and is reported; the Rules page says so. Only the+ Admin's own JSON answer, no rules or a 404 (an older Admin, or its switch off), lifts them.+- **Constrain only.** A rule never runs anything on a member's computer and never asks anyone to approve anything. It is not a+ security boundary against the team's own admins: the Admin holds it, and an engine's own managed settings are separate.+## The role`OMB_CLOUD_ROLE=team` with `OMB_CLOUD_TEAM_ID` (the Admin's id) and `OMB_CLOUD_TEAM_NAME` (1 to 80 characters), besidediff --git a/scripts/testing/cloud-send-fixture.ts b/scripts/testing/cloud-send-fixture.tsindex ad393bfada..7554d2aa5f 100644--- a/scripts/testing/cloud-send-fixture.ts+++ b/scripts/testing/cloud-send-fixture.ts@@ -131,7 +131,7 @@ export interface CloudTeamFixture {/** The Admin's signed power request (the sleep handshake). */signed(method: string, path: string, body?: unknown): Promise<{ status: number; body: any }>;/** A turn's own bearer for the internal routes, as the harness gives a bot's tools. */- capability(botId: string, threadId: string): Promise<string>;+ capability(botId: string, threadId: string, kind?: string): Promise<string>;/** The server stopped and started again on the same data (a deploy). */relaunch(env?: NodeJS.ProcessEnv): Promise<void>;}@@ -201,7 +201,7 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl...Object.fromEntries(["codex", "cursor", "githubCopilot", "openaiCompat", "qwen", "hermes", "pi", "grok"].map((id) => [id, { driver: "not-a-real-driver" }])),claude: { driver: "claudeAgent", displayName: "Claude", config: { cli } },} }));- const offline = `data:text/javascript,${encodeURIComponent('const real = globalThis.fetch; globalThis.fetch = async (url, init) => String(url).startsWith("http://127.0.0.1:") ? real(url, init) : new Response("offline fixture", { status: 503 });')}`;+ const offline = `data:text/javascript,${encodeURIComponent('const real = globalThis.fetch; const admin = process.env.FIXTURE_ADMIN_STAND_IN; globalThis.fetch = async (url, init) => admin && String(url).startsWith("https://cloud.example.test/") ? real(admin + String(url).slice(26), init) : String(url).startsWith("http://127.0.0.1:") ? real(url, init) : new Response("offline fixture", { status: 503 });')}`;const child = spawn(process.execPath, ["--import", offline, ...extra, join(SERVER_DIR, "index.ts")], {cwd: join(SERVER_DIR, ".."),env: { PATH: process.env.PATH, ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}), HOME: home, USERPROFILE: home, OMB_DATA_DIR: dataDir,@@ -312,9 +312,9 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl},as,signed: (method, path, body) => signedRequest(teamBase, method, path, body === undefined ? "" : JSON.stringify(body)),- async capability(botId, threadId) {+ async capability(botId, threadId, kind) {// A loopback caller with the private key, as the harness mints one: never through the edge.- const minted = await fetch(`${teamBase}/api/testing/internal-capability`, { method: "POST", headers: { "content-type": "application/json", "x-openmausbot-test-capability": CAPABILITY_KEY }, body: JSON.stringify({ botId, threadId }) });+ const minted = await fetch(`${teamBase}/api/testing/internal-capability`, { method: "POST", headers: { "content-type": "application/json", "x-openmausbot-test-capability": CAPABILITY_KEY }, body: JSON.stringify({ botId, threadId, ...(kind ? { kind } : {}) }) });const answer = parse(await minted.text());if (minted.status !== 200 && minted.status !== 201) throw new Error(`no test capability: ${minted.status} ${JSON.stringify(answer)}`);return answer.token as string;diff --git a/server/cloud-team-policy.test.ts b/server/cloud-team-policy.test.tsnew file mode 100644index 0000000000..b0e6d377a6--- /dev/null+++ b/server/cloud-team-policy.test.ts@@ -0,0 +1,286 @@+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import { remoteAccessPaths, startTeamPolicyClient, TEAM_POLICY_ADMIN_PATH, TEAM_POLICY_FILE, TEAM_POLICY_FRESH_MS, TEAM_POLICY_REFRESH_MS, teamManagedPolicy, teamPolicyDocumentSchema, teamPolicyFingerprint, teamPolicySignature, type TeamPolicyClient } from "./cloud-team-policy.ts";+import { ManagedDesktopPolicy, type ManagedPolicy } from "./managed-policy.ts";+import { excludedWorkspaceAuthPath } from "./workspace-backup-policy.ts";++const TEAM = { id: "11111111-1111-4111-8111-111111111111", name: "Acme" };+const doc = (limits: Record<string, unknown>) => ({ schema: 1, limits });+const answer = (document: unknown, version = 1) => Response.json({ policy: { version, fingerprint: teamPolicyFingerprint(document), document } });++const dirs: string[] = [], clients: TeamPolicyClient[] = [];+afterEach(() => { for (const client of clients.splice(0)) client.stop(); for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++function world(fetchImpl: (body: { loaded: { fingerprint: string } | null; problem: string | null }, init: RequestInit, url: string) => Response | Promise<Response>, options: { dataDir?: string; now?: () => number } = {}) {+ const dataDir = options.dataDir ?? mkdtempSync(join(tmpdir(), "omb-team-policy-"));+ if (!options.dataDir) dirs.push(dataDir);+ const applied: (ManagedPolicy | null)[] = [], logs: string[] = [], timers: { run: () => void; ms: number }[] = [], reports: { loaded: { fingerprint: string } | null; problem: string | null }[] = [];+ const client = startTeamPolicyClient({+ team: TEAM, machineId: "cm-test-home", adminOrigin: "https://cloud.example.test", secret: "s".repeat(43), dataDir, random: () => 0,+ apply: (policy) => { applied.push(policy); }, log: (line) => logs.push(line), ...(options.now ? { now: options.now } : {}),+ setTimer: (run, ms) => { const timer = { run, ms, unref() {} }; timers.push(timer); return timer; }, clearTimer: (timer) => { timers.splice(timers.indexOf(timer as never), 1); },+ fetchImpl: (async (url: string, init: RequestInit) => {+ const body = JSON.parse(String(init.body));+ reports.push(body);+ return fetchImpl(body, init, url);+ }) as typeof fetch,+ });+ clients.push(client);+ return { client, dataDir, applied, logs, timers, reports };+}++describe("the document", () => {+ it("computes the fingerprint and signature exactly as openmaus-cloud's server/cloud-team-policy.ts does", () => {+ // The same vectors are pinned in openmaus-cloud tests/cloud-team-policy.test.ts.+ expect(teamPolicyFingerprint({ schema: 1, limits: { remoteAccess: "off", allowedEngines: ["claudeAgent", "codex"] } })).toBe("8341e89f9d7fc734");+ expect(teamPolicyFingerprint({ limits: { allowedEngines: ["claudeAgent", "codex"], remoteAccess: "off" }, schema: 1 })).toBe("8341e89f9d7fc734");+ expect(teamPolicySignature("s".repeat(43), "cm-test-home", "1792670400", "nonce-nonce-nonce-1", '{"v":1,"loaded":null,"problem":null}')).toBe("ZNkIYIIuPldLp7gQ4cy7s1zQJpBiWkyP8DOyRtRz03w");+ });++ it("accepts explicitly permissive values, and refuses a key it can't enforce", () => {+ expect(teamPolicyDocumentSchema.safeParse(doc({ allowedEngines: "all", allowedApps: "all", allowedMcpServers: "all", allowedComputers: "all", remoteAccess: "allowed", requireFreshPolicy: false })).success).toBe(true);+ expect(teamPolicyDocumentSchema.safeParse(doc({ somethingNew: 1 })).success).toBe(false);+ expect(teamPolicyDocumentSchema.safeParse({ schema: 2, limits: {} }).success).toBe(false);+ });++ it("restricting nothing is no policy at all, whichever way it is said", () => {+ expect(teamManagedPolicy(teamPolicyDocumentSchema.parse(doc({})), TEAM, 1)).toBeNull();+ expect(teamManagedPolicy(teamPolicyDocumentSchema.parse(doc({ allowedEngines: "all", allowedApps: "all", allowedMcpServers: "all", allowedComputers: "all", remoteAccess: "allowed", requireFreshPolicy: false })), TEAM, 1)).toBeNull();+ });++ it("projects into the one strict shape every refusal reads, which never lapses and is never company-only", () => {+ const policy = teamManagedPolicy(teamPolicyDocumentSchema.parse(doc({ allowedEngines: ["codex"], allowedApps: ["gmail"], allowedMcpServers: ["orders"], allowedComputers: ["vps"], remoteAccess: "off", requireFreshPolicy: true })), TEAM, 4)!;+ expect(policy).toEqual({ organizationId: TEAM.id, organizationName: "Acme", expiresAt: null, version: 4, companyModelsOnly: false, allowedEngines: ["codex"],+ mcp: { allowCustom: false, allowlist: ["orders"] }, apps: { allowAll: false, allowlist: ["gmail"] }, computers: { thisComputer: false, localVm: false, box: false, vps: true }, remoteAccess: false, team: { requireFresh: true, ownMcpOnly: false } });+ const managed = new ManagedDesktopPolicy();+ managed.apply(policy);+ expect(managed.current()).not.toBeNull();+ managed.close();+ });++ it("on a Team Cloud, the pairing every member's app uses is never remote access; off a team it still is", () => {+ expect(remoteAccessPaths(true)).not.toContain("/api/auth/pair");+ expect(remoteAccessPaths(true)).toEqual(expect.arrayContaining(["/api/auth/pairing", "/api/team/phone-pairing"]));+ expect(remoteAccessPaths(false)).toEqual(expect.arrayContaining(["/api/auth/pair", "/api/pair", "/api/auth/pairing", "/api/auth/email/start", "/api/auth/email/verify"]));+ });++ it("no backup carries the kept rules", () => {+ expect(excludedWorkspaceAuthPath(TEAM_POLICY_FILE)).toBe(true);+ expect(excludedWorkspaceAuthPath(`${TEAM_POLICY_FILE}.123.aa-bb.tmp`)).toBe(true);+ });+});++describe("the fetch", () => {+ it("signs its request, applies the rules, keeps them 0600 and reports them in force at once", async () => {+ const document = doc({ allowedEngines: ["codex"] });+ const { client, applied, dataDir, reports, timers } = world((_body, init, url) => {+ expect(url).toBe(`https://cloud.example.test${TEAM_POLICY_ADMIN_PATH}`);+ expect(init.redirect).toBe("error");+ const headers = init.headers as Record<string, string>;+ expect(headers["x-omb-cloud-signature"]).toBe(`v1=${teamPolicySignature("s".repeat(43), "cm-test-home", headers["x-omb-cloud-timestamp"]!, headers["x-omb-cloud-nonce"]!, String(init.body))}`);+ return answer(document);+ });+ await client.settled();+ expect(applied).toHaveLength(1);+ expect(applied[0]).toMatchObject({ organizationName: "Acme", allowedEngines: ["codex"], expiresAt: null });+ expect(reports.map((report) => report.loaded?.fingerprint ?? null)).toEqual([null, teamPolicyFingerprint(document)]);+ const file = join(dataDir, TEAM_POLICY_FILE);+ expect(JSON.parse(readFileSync(file, "utf8"))).toMatchObject({ teamId: TEAM.id, version: 1, document });+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);+ expect(timers.map((timer) => timer.ms)).toEqual([TEAM_POLICY_REFRESH_MS]);+ });++ it("a change applies with no restart: at the next timer, or at once when nudged", async () => {+ let document = doc({ allowedEngines: ["codex"] });+ const { client, applied, timers } = world(() => answer(document));+ await client.settled();+ document = doc({ allowedEngines: ["claudeAgent"] });+ timers.pop()!.run();+ await client.settled();+ expect(applied.at(-1)).toMatchObject({ allowedEngines: ["claudeAgent"] });+ document = doc({ allowedEngines: ["grokAgent"] });+ client.nudge();+ await client.settled();+ expect(applied.at(-1)).toMatchObject({ allowedEngines: ["grokAgent"] });+ });++ it("a kept copy applies before any answer, and an Admin that can't be reached never lapses it", async () => {+ const document = doc({ allowedEngines: ["codex"] }), good = world(() => answer(document));+ await good.client.settled();+ good.client.stop();+ for (const failure of [() => { throw new TypeError("fetch failed"); }, () => new Response("down", { status: 503 }), () => new Response(null, { status: 401, headers: { "content-type": "application/json" } }), () => new Response("<html>", { status: 404, headers: { "content-type": "text/html" } }), () => new Response("not json", { status: 200, headers: { "content-type": "application/json" } })]) {+ const down = world(failure, { dataDir: good.dataDir });+ expect(down.applied).toHaveLength(1);+ expect(down.applied[0]).toMatchObject({ allowedEngines: ["codex"] });+ await down.client.settled();+ expect(down.applied).toHaveLength(1);+ expect(existsSync(join(good.dataDir, TEAM_POLICY_FILE))).toBe(true);+ down.client.stop();+ }+ });++ it("another team's copy, or a copy that fails validation, is ignored", async () => {+ const document = doc({ allowedEngines: ["codex"] }), good = world(() => answer(document));+ await good.client.settled();+ good.client.stop();+ const file = join(good.dataDir, TEAM_POLICY_FILE), kept = JSON.parse(readFileSync(file, "utf8"));+ for (const copy of [{ ...kept, teamId: "someone-else" }, { ...kept, document: doc({}) }, { ...kept, document: doc({ somethingNew: 1 }) }, "not json at all"]) {+ writeFileSync(file, typeof copy === "string" ? copy : JSON.stringify(copy));+ const later = world(() => new Response("down", { status: 503 }), { dataDir: good.dataDir });+ await later.client.settled();+ expect(later.applied).toEqual([]);+ later.client.stop();+ }+ });++ it("an unknown schema or a failed validation never crashes it: it keeps the last good rules and reports why, once", async () => {+ let body: () => Response = () => answer(doc({ allowedEngines: ["codex"] }));+ const { client, applied, reports } = world(() => body());+ await client.settled();+ const good = applied.length;+ body = () => answer({ schema: 2, limits: {}, settings: {} }, 2);+ client.nudge();+ await client.settled();+ expect(applied).toHaveLength(good);+ expect(client.status()).toMatchObject({ fingerprint: teamPolicyFingerprint(doc({ allowedEngines: ["codex"] })), problem: "rules of a newer kind (schema 2)" });+ expect(reports.at(-1)).toMatchObject({ problem: "rules of a newer kind (schema 2)" });+ body = () => answer(doc({ somethingNew: 1 }), 3);+ client.nudge();+ await client.settled();+ expect(reports.at(-1)?.problem).toMatch(/limits\.somethingNew can't be read/);+ // A document that doesn't match its fingerprint is no better.+ body = () => Response.json({ policy: { version: 4, fingerprint: "0".repeat(16), document: doc({}) } });+ client.nudge();+ await client.settled();+ expect(applied).toHaveLength(good);+ expect(reports.at(-1)?.problem).toMatch(/fingerprint/);+ // A good one again clears it.+ body = () => answer(doc({ allowedEngines: ["claudeAgent"] }), 5);+ client.nudge();+ await client.settled();+ expect(client.status().problem).toBeNull();+ expect(applied.at(-1)).toMatchObject({ allowedEngines: ["claudeAgent"] });+ });++ it("the Admin's word that there are none, a null or a JSON 404, lifts them and forgets the copy", async () => {+ for (const none of [() => Response.json({ policy: null }), () => Response.json({ error: "Not found." }, { status: 404 })]) {+ let body: () => Response = () => answer(doc({ allowedEngines: ["codex"] }));+ const { client, applied, dataDir } = world(() => body());+ await client.settled();+ body = none;+ client.nudge();+ await client.settled();+ expect(applied.at(-1)).toBeNull();+ expect(existsSync(join(dataDir, TEAM_POLICY_FILE))).toBe(false);+ }+ });++ it("a Cloud with no rules and an older Admin behaves as it always did", async () => {+ const { client, applied, reports } = world(() => Response.json({ error: "Not found." }, { status: 404 }));+ await client.settled();+ expect(applied).toEqual([null]);+ expect(reports).toHaveLength(1);+ });++ it("fresh: only while the Admin confirmed lately; a stale read asks again, at most so often", async () => {+ let at = 1_000_000, up = true;+ const { client, reports } = world(() => up ? answer(doc({ requireFreshPolicy: true })) : new Response("down", { status: 503 }), { now: () => at });+ await client.settled();+ expect(client.fresh()).toBe(true);+ at += TEAM_POLICY_FRESH_MS;+ expect(client.fresh()).toBe(true);+ up = false;+ at += 1;+ const before = reports.length;+ expect(client.fresh()).toBe(false);+ expect(client.fresh()).toBe(false);+ await client.settled();+ expect(reports.length).toBe(before + 1);+ up = true;+ at += 30_000;+ expect(client.fresh()).toBe(false);+ await client.settled();+ expect(client.fresh()).toBe(true);+ });+});++describe("the managed policy with a team's rules", () => {+ const managedWith = (limits: Record<string, unknown>) => {+ const managed = new ManagedDesktopPolicy();+ managed.apply(teamManagedPolicy(teamPolicyDocumentSchema.parse(doc(limits)), TEAM, 1));+ return managed;+ };+ it("never lapses, however long the Cloud runs", () => {+ vi.useFakeTimers();+ try {+ const managed = managedWith({ allowedEngines: ["codex"] });+ vi.advanceTimersByTime(400 * 86_400_000);+ expect(managed.current()).not.toBeNull();+ expect(managed.modelRefusal({ driverKind: "claudeAgent", displayName: "Claude" }, false)).toBeDefined();+ managed.close();+ } finally { vi.useRealTimers(); }+ });+ it("each refusal names the team and says to ask an admin", () => {+ const managed = managedWith({ allowedEngines: ["codex"], allowedApps: ["gmail"], allowedMcpServers: ["orders"], allowedComputers: ["vps"], remoteAccess: "off" });+ expect(managed.modelRefusal({ driverKind: "claudeAgent", displayName: "Claude" }, false)).toBe("Acme does not allow the Claude engine. Choose another model for this bot, or ask a team admin.");+ expect(managed.mcpRefusal("other")).toBe("Acme allows only MCP servers it has approved. Ask a team admin to add this one.");+ expect(managed.computerRefusal("box")).toBe("Acme does not allow bots to use cloud computers. Ask a team admin.");+ expect(managed.remoteAccessRefusal()).toBe("Acme does not allow opening this Cloud on a phone or with a link. Ask a team admin.");+ expect(managed.appRefusal("google_sheets")).toBe("Acme does not allow bots to use Google Sheets. Ask a team admin.");+ for (const line of [managed.modelRefusal({ driverKind: "claudeAgent", displayName: "Claude" }, false)!, managed.computerRefusal("thisComputer")!, managed.remoteAccessRefusal()!]) {+ expect(line.length).toBeLessThanOrEqual(160);+ expect(line).not.toMatch(/\bserver\b/i);+ }+ managed.close();+ });+ it("apps: a tool runs only for an allowed app, a batch is refused whole, code that could reach any app is refused, and a longer slug isn't captured", () => {+ const managed = managedWith({ allowedApps: ["gmail", "bland"] });+ expect(managed.appsCallRefusal([{ slug: "GMAIL_SEND_EMAIL" }])).toBeUndefined();+ expect(managed.appsCallRefusal([{ slug: "GMAIL_SEND_EMAIL" }, { slug: "SLACK_POST" }])).toMatch(/does not allow bots to use Slack/);+ expect(managed.appsCallRefusal([{ slug: "COMPOSIO_PROXY_EXECUTE" }])).toMatch(/can't run code/);+ expect(managed.appsCallRefusal([{ slug: "BLAND_AI_CALL" }], ["bland_ai"])).toMatch(/Bland Ai/);+ expect(managed.appsCallRefusal([{ slug: "BLAND_CALL" }], ["bland_ai"])).toBeUndefined();+ expect(managed.appsConnectRefusal(["gmail", "notion"])).toMatch(/Notion/);+ expect(managed.appAllowed("highlevel")).toBe(false);+ managed.close();+ const open = managedWith({ allowedEngines: ["codex"] });+ expect(open.appsCallRefusal([{ slug: "SLACK_POST" }, { slug: "COMPOSIO_PROXY_EXECUTE" }])).toBeUndefined();+ expect(open.appAllowed("slack")).toBe(true);+ open.close();+ });+ it("only the team's own servers: what an admin adds stays, a bot's own doesn't start, and a bot can't add one", () => {+ const managed = managedWith({ allowedMcpServers: "team" });+ expect(managed.summary()!.mcp).toEqual({ allowCustom: true, allowlist: [] });+ expect(managed.mcpRefusal("orders", "https://mcp.example.com")).toBeUndefined();+ expect(managed.restrictsMcp()).toBe(true);+ expect(Object.keys(managed.filterMcp({ orders: { url: "https://mcp.example.com" }, mine: { command: "mine", bot: "b1" } }))).toEqual(["orders"]);+ expect(managed.botMcpRefusal()).toBe("Acme uses only the MCP servers its admins add. Ask a team admin.");+ managed.close();+ const open = managedWith({ allowedEngines: ["codex"] });+ expect(open.botMcpRefusal()).toBeUndefined();+ expect(Object.keys(open.filterMcp({ mine: { command: "mine", bot: "b1" } }))).toEqual(["mine"]);+ open.close();+ });+ it("requires fresh rules only of a team that said so", () => {+ const required = managedWith({ requireFreshPolicy: true });+ required.setFreshness(() => false);+ expect(required.modelRefusal({ driverKind: "claudeAgent" }, false)).toMatch(/^Acme requires up-to-date rules/);+ required.setFreshness(() => true);+ expect(required.modelRefusal({ driverKind: "claudeAgent" }, false)).toBeUndefined();+ required.close();+ const not = managedWith({ allowedEngines: ["claudeAgent"] });+ not.setFreshness(() => false);+ expect(not.modelRefusal({ driverKind: "claudeAgent" }, false)).toBeUndefined();+ not.close();+ });+ it("the renderer's view says it is a team's, and holds no id or date", () => {+ const managed = managedWith({ allowedEngines: ["codex"] });+ const summary = managed.summary()!;+ expect(summary.team).toBe(true);+ expect(summary).not.toHaveProperty("organizationId");+ expect(summary).not.toHaveProperty("expiresAt");+ managed.close();+ });+});diff --git a/server/cloud-team-policy.ts b/server/cloud-team-policy.tsnew file mode 100644index 0000000000..9a650b4f3e--- /dev/null+++ b/server/cloud-team-policy.ts@@ -0,0 +1,298 @@+// A Team Cloud's rules: one document the team's Owner and Admins keep on the Admin (openmaus-cloud docs/team-cloud.md+// "Rules"). The Cloud fetches it signed with its bootstrap secret at boot, on a timer and when the Admin nudges it,+// keeps the last valid one on its volume, and feeds the one enforcement every caller already passes (managed-policy.ts).+// Security invariants: the rules only restrict, and a change applies without a restart. Kept rules never lapse: an Admin+// that can't be reached leaves them in force. A document this version can't read leaves the last good one in force.+// The cache is 0600, no backup carries it, it is bound to this team and ignored unless it validates, and it holds nothing+// that could redirect a fetch.+import { createHash, createHmac, randomBytes } from "node:crypto";+import { readFileSync, rmSync } from "node:fs";+import { join } from "node:path";+import { z } from "zod";+import { writeFileAtomic } from "./atomic.ts";+import type { CloudHomeConfig } from "./cloud-home.ts";+import type { CloudTeam } from "./cloud-team.ts";+import type { ManagedDesktopPolicy, ManagedPolicy } from "./managed-policy.ts";+import { TEAM_PHONE_PAIRING_PATH } from "./routes/team-phone.ts";+import type { SessionRegistry } from "./sessions.ts";++export const TEAM_POLICY_SCHEMA = 1;+/** On the Admin; must match openmaus-cloud's TEAM_POLICY_MACHINE_PATH. */+export const TEAM_POLICY_ADMIN_PATH = "/api/cloud/machines/team-policy";+/** The Admin's signed word that the rules changed: `{}`, fetched at once rather than at the next timer. */+export const CLOUD_TEAM_POLICY_CHANGED_PATH = "/api/cloud/team/policy-changed";+/** In the data folder; excluded from backups (workspace-backup-policy.ts): a restored Cloud asks the Admin. */+export const TEAM_POLICY_FILE = "team-policy.json";+export const TEAM_POLICY_REFRESH_MS = 5 * 60_000;+/** A team that requires fresh rules refuses new turns once the last good fetch is this old: three missed refreshes. */+export const TEAM_POLICY_FRESH_MS = 15 * 60_000;+const FETCH_TIMEOUT_MS = 15_000, KICK_GAP_MS = 30_000, ANSWER_MAX_BYTES = 256 * 1024;++const allowed = <T extends z.ZodType>(entry: T, max: number) => z.union([z.literal("all"), z.array(entry).max(max)]);+/** Omitted, or a permissive value: allowed. Only an explicit restriction restricts, and nothing can force anything on. */+const limitsSchema = z.object({+ allowedEngines: allowed(z.string().regex(/^[A-Za-z][A-Za-z0-9-]{0,63}$/), 64).optional(),+ allowedApps: allowed(z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/), 200).optional(),+ /** `"team"`: only what the team's admins add; a list: only those, whoever adds them. */+ allowedMcpServers: z.union([z.literal("team"), allowed(z.string().trim().min(1).max(200), 100)]).optional(),+ allowedComputers: allowed(z.enum(["cloudDesktop", "vps", "memberComputer"]), 3).optional(),+ remoteAccess: z.enum(["allowed", "off"]).optional(),+ requireFreshPolicy: z.boolean().optional(),+}).strict();+/** Unknown keys are refused here too: a key this version can't enforce must not look enforced. */+export const teamPolicyDocumentSchema = z.object({ schema: z.literal(TEAM_POLICY_SCHEMA), limits: limitsSchema }).strict();+export type TeamPolicyDocument = z.infer<typeof teamPolicyDocumentSchema>;++const fingerprintSchema = z.string().regex(/^[0-9a-f]{16}$/);+const answerSchema = z.object({+ policy: z.object({ version: z.number().int().min(0).max(2_147_483_647), fingerprint: fingerprintSchema, document: z.unknown() }).nullable(),+});+const storedSchema = z.object({ v: z.literal(1), teamId: z.string(), version: z.number().int().min(0).max(2_147_483_647), fingerprint: fingerprintSchema, document: teamPolicyDocumentSchema, fetchedAt: z.number() });+type Stored = z.infer<typeof storedSchema>;++function canonical(value: unknown): string {+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;+ if (value && typeof value === "object") {+ return `{${Object.entries(value).filter(([, item]) => item !== undefined).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;+ }+ return JSON.stringify(value);+}+/** Must match openmaus-cloud's teamPolicyFingerprint: its keys sorted, sixteen hex digits of its SHA-256. */+export function teamPolicyFingerprint(document: unknown): string {+ return createHash("sha256").update(canonical(document)).digest("hex").slice(0, 16);+}+/** Must match openmaus-cloud's teamPolicySignature. */+export function teamPolicySignature(secret: string, machineId: string, timestamp: string, nonce: string, body: string): string {+ const bodyHash = createHash("sha256").update(body).digest("base64url");+ return createHmac("sha256", secret).update(`omb-team-policy-v1\n${machineId}\n${timestamp}\n${nonce}\n${bodyHash}`).digest("base64url");+}++/** The document in the one shape every refusal site reads. Null when it restricts nothing, as with no document at all. */+export function teamManagedPolicy(document: TeamPolicyDocument, team: Pick<CloudTeam, "id" | "name">, version: number): ManagedPolicy | null {+ const { allowedEngines = "all", allowedApps = "all", allowedMcpServers = "all", allowedComputers = "all", remoteAccess = "allowed", requireFreshPolicy = false } = document.limits;+ if (allowedEngines === "all" && allowedApps === "all" && allowedMcpServers === "all" && allowedComputers === "all" && remoteAccess === "allowed" && !requireFreshPolicy) return null;+ const computer = (kind: "cloudDesktop" | "vps" | "memberComputer") => allowedComputers === "all" || allowedComputers.includes(kind);+ return {+ organizationId: team.id, organizationName: team.name, expiresAt: null, version, companyModelsOnly: false,+ allowedEngines,+ mcp: allowedMcpServers === "all" || allowedMcpServers === "team" ? { allowCustom: true, allowlist: [] } : { allowCustom: false, allowlist: allowedMcpServers },+ apps: allowedApps === "all" ? { allowAll: true, allowlist: [] } : { allowAll: false, allowlist: allowedApps },+ computers: { thisComputer: computer("memberComputer"), localVm: computer("memberComputer"), box: computer("cloudDesktop"), vps: computer("vps") },+ remoteAccess: remoteAccess !== "off",+ team: { requireFresh: requireFreshPolicy, ownMcpOnly: allowedMcpServers === "team" },+ };+}++/** The POST paths the remote-access limit refuses. On a Team Cloud the Admin-signed pairing is how every member's app, and+ * the Admin itself, reach it, so refusing `/api/auth/pair` would lock the whole team out: there, only what a member's own+ * code opens counts as remote access (the sessions of those codes end when the limit lands: `closeMemberPhones`). */+export function remoteAccessPaths(team: boolean): readonly string[] {+ return team ? ["/api/auth/pairing", TEAM_PHONE_PAIRING_PATH] : ["/api/auth/pair", "/api/pair", "/api/auth/pairing", "/api/auth/email/start", "/api/auth/email/verify"];+}++/** What a document's refusal says of itself, for the Rules page: which key, never a value. */+function documentProblem(document: unknown): string {+ const parsed = teamPolicyDocumentSchema.safeParse(document);+ if (parsed.success) return "";+ const schema = (document as { schema?: unknown } | null)?.schema;+ if (schema !== TEAM_POLICY_SCHEMA) return `rules of a newer kind (schema ${typeof schema === "number" ? schema : "unknown"})`;+ const issue = parsed.error.issues[0], keys = (issue as { keys?: string[] } | undefined)?.keys;+ return `${[...(issue?.path ?? []).map(String), ...(keys?.length ? [keys[0]] : [])].join(".") || "the document"} can't be read`;+}++interface Timer { unref?(): unknown }++export interface TeamPolicyClientOptions {+ team: Pick<CloudTeam, "id" | "name">;+ machineId: string;+ adminOrigin: string;+ secret: string;+ dataDir: string;+ apply(policy: ManagedPolicy | null): void;+ fetchImpl?: typeof fetch;+ log?: (line: string) => void;+ now?: () => number;+ random?: () => number;+ setTimer?: (run: () => void, ms: number) => Timer;+ clearTimer?: (timer: Timer) => void;+}++export interface TeamPolicyClient {+ /** Fetch now, at once if none is in flight, else right after it. */+ nudge(): void;+ /** Whether the Admin confirmed the rules recently. */+ fresh(): boolean;+ /** The fetch in flight or last finished; it never rejects. */+ settled(): Promise<void>;+ status(): { fingerprint: string | null; version: number | null; problem: string | null; fetchedAt: number | null };+ stop(): void;+}++export function startTeamPolicyClient(options: TeamPolicyClientOptions): TeamPolicyClient {+ const file = join(options.dataDir, TEAM_POLICY_FILE);+ const now = options.now ?? Date.now, log = options.log ?? (() => {}), random = options.random ?? Math.random;+ const fetcher = options.fetchImpl ?? globalThis.fetch;+ const setTimer = options.setTimer ?? ((run, ms) => setTimeout(run, ms));+ const clearTimer = options.clearTimer ?? ((timer) => clearTimeout(timer as ReturnType<typeof setTimeout>));+ let held: Stored | null = null, problem: string | null = null, fetchedAt: number | null = null;+ let timer: Timer | null = null, stopped = false, running = false, again = false, lastKick = 0;+ let current: Promise<void> = Promise.resolve();++ /** False when the rules could not be put in force: the last good ones stay, and the Admin hears why. */+ const putInForce = (next: Stored | null): boolean => {+ try {+ options.apply(next ? teamManagedPolicy(next.document, options.team, next.version) : null);+ return true;+ } catch (error) {+ log(`team rules: could not apply them: ${error instanceof Error ? error.message : String(error)}`);+ return false;+ }+ };+ const save = (stored: Stored) => {+ try { writeFileAtomic(file, `${JSON.stringify(stored)}\n`, { mode: 0o600 }); } catch (error) {+ log(`team rules: could not keep them on this Cloud: ${(error as NodeJS.ErrnoException).code ?? "error"}`);+ }+ };++ const read = (): Stored | null => {+ let raw: string;+ try { raw = readFileSync(file, "utf8"); } catch { return null; }+ let parsed: z.ZodSafeParseResult<Stored>;+ try { parsed = storedSchema.safeParse(JSON.parse(raw)); } catch { log("team rules: the kept copy can't be read; asking the Admin"); return null; }+ if (!parsed.success || parsed.data.teamId !== options.team.id || teamPolicyFingerprint(parsed.data.document) !== parsed.data.fingerprint) {+ log("team rules: the kept copy can't be used; asking the Admin");+ return null;+ }+ return parsed.data;+ };++ const lift = () => {+ if (held || problem) log("team rules: the Admin holds none now; nothing is restricted");+ if (putInForce(null)) { held = null; problem = null; }+ rmSync(file, { force: true });+ };++ /** One signed ask, which also reports what is in force here. A failure changes nothing: what is held stays. */+ const ask = async (): Promise<void> => {+ const body = JSON.stringify({ v: 1, loaded: held ? { fingerprint: held.fingerprint, version: held.version } : null, problem });+ const timestamp = String(Math.floor(now() / 1000)), nonce = randomBytes(18).toString("base64url");+ let response: Response;+ try {+ response = await fetcher(`${options.adminOrigin}${TEAM_POLICY_ADMIN_PATH}`, { method: "POST", redirect: "error", cache: "no-store", body, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), headers: {+ accept: "application/json", "content-type": "application/json", "x-omb-cloud-machine": options.machineId, "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce,+ "x-omb-cloud-signature": `v1=${teamPolicySignature(options.secret, options.machineId, timestamp, nonce, body)}`,+ } });+ } catch (error) {+ log(`team rules: the Admin can't be reached (${error instanceof Error ? error.name : "error"}); keeping the last rules`);+ return;+ }+ // An older Admin, or the Admin's own switch off, says so in JSON; anything else in the way is not its word.+ const json = /^application\/json\b/i.test(response.headers.get("content-type") ?? "");+ if (response.status === 404 && json) { await response.body?.cancel().catch(() => {}); fetchedAt = now(); lift(); return; }+ if (response.status !== 200 || !json) {+ await response.body?.cancel().catch(() => {});+ log(`team rules: the Admin answered HTTP ${response.status}; keeping the last rules`);+ return;+ }+ const text = await response.text().catch(() => "");+ let parsed: z.ZodSafeParseResult<z.infer<typeof answerSchema>>;+ try { parsed = text.length > ANSWER_MAX_BYTES ? answerSchema.safeParse(null) : answerSchema.safeParse(JSON.parse(text)); } catch { parsed = answerSchema.safeParse(null); }+ if (!parsed.success) { log("team rules: the Admin's answer can't be read; keeping the last rules"); return; }+ const policy = parsed.data.policy;+ if (!policy) { fetchedAt = now(); lift(); return; }+ const document = teamPolicyDocumentSchema.safeParse(policy.document);+ if (!document.success || teamPolicyFingerprint(policy.document) !== policy.fingerprint) {+ const why = document.success ? "they don't match their fingerprint" : documentProblem(policy.document);+ if (problem !== why) log(`team rules: ${why}; keeping the last rules`);+ problem = why;+ return;+ }+ fetchedAt = now();+ const next: Stored = { v: 1, teamId: options.team.id, version: policy.version, fingerprint: policy.fingerprint, document: document.data, fetchedAt };+ if (held?.fingerprint === next.fingerprint) {+ problem = null;+ if (held.version !== next.version || next.document.limits.requireFreshPolicy) { held = next; save(next); }+ return;+ }+ if (!putInForce(next)) { problem = "they could not be applied"; return; }+ held = next; problem = null;+ save(next);+ log(`team rules: version ${next.version} (${next.fingerprint}) in force`);+ };++ const told = () => `${held?.fingerprint ?? ""}\n${problem ?? ""}`;+ const schedule = () => {+ if (stopped) return;+ if (timer) clearTimer(timer);+ timer = setTimer(() => { timer = null; run(); }, Math.round(TEAM_POLICY_REFRESH_MS * (1 + 0.2 * random())));+ timer.unref?.();+ };+ const fetchRound = async (): Promise<void> => {+ try {+ // A change is reported at once, so the Rules page can say it is in force without waiting for the next refresh.+ for (let round = 0; round < 2 && !stopped; round++) {+ const before = told();+ await ask();+ if (told() === before) break;+ }+ } catch (error) {+ log(`team rules: ${error instanceof Error ? error.message : String(error)}`);+ }+ };+ const run = () => {+ if (stopped) return;+ if (running) { again = true; return; }+ running = true;+ current = (async () => {+ do { again = false; await fetchRound(); } while (again && !stopped);+ running = false;+ schedule();+ })();+ };++ const kept = read();+ if (kept && putInForce(kept)) { held = kept; fetchedAt = kept.fetchedAt; }+ run();++ return {+ nudge: run,+ fresh() {+ const isFresh = fetchedAt !== null && now() - fetchedAt <= TEAM_POLICY_FRESH_MS;+ // A Cloud that was asleep past its timer asks now, so the person's next try can pass.+ if (!isFresh && now() - lastKick >= KICK_GAP_MS) { lastKick = now(); run(); }+ return isFresh;+ },+ settled: () => current,+ status: () => ({ fingerprint: held?.fingerprint ?? null, version: held?.version ?? null, problem, fetchedAt }),+ stop() {+ stopped = true;+ if (timer) clearTimer(timer);+ timer = null;+ },+ };+}++let cloudTeam: TeamPolicyClient | null = null;++/** A Team Cloud only; a My Cloud has no team, no rules and no fetch. */+export function startCloudTeamPolicy(input: { cloudHome: CloudHomeConfig | null; dataDir: string; managed: ManagedDesktopPolicy; sessions: Pick<SessionRegistry, "closeMemberPhones"> }): void {+ const { cloudHome, managed, sessions } = input;+ if (!cloudHome?.team || cloudTeam) return;+ cloudTeam = startTeamPolicyClient({+ team: cloudHome.team, machineId: cloudHome.machineId, adminOrigin: cloudHome.adminOrigin, secret: cloudHome.bootstrapSecret, dataDir: input.dataDir,+ log: (line) => console.log(`team cloud: ${line}`),+ apply: (policy) => {+ managed.apply(policy);+ if (policy && !policy.remoteAccess) sessions.closeMemberPhones();+ },+ });+ const client = cloudTeam;+ managed.setFreshness(() => client.fresh());+}++export function nudgeCloudTeamPolicy(): void { cloudTeam?.nudge(); }++export function stopCloudTeamPolicy(): void {+ cloudTeam?.stop();+ cloudTeam = null;+}diff --git a/server/cloud-team-rules.e2e.test.ts b/server/cloud-team-rules.e2e.test.tsnew file mode 100644index 0000000000..e8496d79f2--- /dev/null+++ b/server/cloud-team-rules.e2e.test.ts@@ -0,0 +1,334 @@+// A Team Cloud with its team's rules, from the Admin's signed answer to the turn. A stand-in Admin holds the document and+// checks each request's signature. A chat turn, a routine, one bot asking another, a person connecting something and+// a lent computer all meet the same refusal, for an Admin as for a User, and all pass again once the rule lifts, with no+// restart. Disposable homes, a synthetic Claude CLI; nothing leaves this machine.+import { createHash } 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 { TEAM_POLICY_ADMIN_PATH, TEAM_POLICY_FILE, teamPolicyFingerprint } from "./cloud-team-policy.ts";+import { startBrokerFake, type BrokerFake } from "./testing/broker-fake.ts";+import { startFakeHttpMcp, type FakeHttpMcp } from "./testing/fake-http-mcp-server.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const OWNER = { email: "[email protected]", role: "owner" as const };+const ADA = { email: "[email protected]", role: "member" as const };+const ENGINE = `process.env.FAKE_CLAUDE_DUMP = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/dump.json";`;++type Limits = Record<string, unknown>;+const admin = {+ answer: { status: 200, body: { policy: null } as unknown, type: "application/json" },+ reports: [] as { loaded: { fingerprint: string; version: number } | null; problem: string | null }[],+ signed: [] as boolean[],+ version: 0,+};+let adminServer: Server, gateway: FakeHttpMcp, relay: Server, broker: BrokerFake, fx: CloudSendFixture, team: CloudTeamFixture;+let owner = "", ada = "";+let botId = "", peerId = "";++function publish(limits: Limits | null) {+ if (!limits) { admin.answer = { status: 200, body: { policy: null }, type: "application/json" }; return null; }+ const document = { schema: 1, limits };+ const policy = { version: ++admin.version, fingerprint: teamPolicyFingerprint(document), document };+ admin.answer = { status: 200, body: { policy }, type: "application/json" };+ return policy;+}+/** The Admin's nudge, as it sends one after a save; then the Cloud's report that the rules are in force. */+async function nudged(fingerprint: string | null) {+ const nudge = await team.signed("POST", "/api/cloud/team/policy-changed", {});+ expect(nudge.status, JSON.stringify(nudge.body)).toBe(200);+ await expect.poll(() => admin.reports.at(-1)?.loaded?.fingerprint ?? null, { timeout: 15_000, interval: 50 }).toBe(fingerprint);+}+async function rules(limits: Limits | null) {+ const policy = publish(limits);+ await nudged(policy?.fingerprint ?? null);+}++async function dumped(token: string, text: string, until: (messages: string) => boolean) {+ const thread = await team.as(token, "POST", `/api/bots/${botId}/tasks`, { title: text });+ expect(thread.status, JSON.stringify(thread.body)).toBe(201);+ const threadId = thread.body.task.threadId as string;+ rmSync(join(team.home, "dump.json"), { force: true });+ const sent = await team.as(token, "POST", `/api/bots/${botId}/messages`, { text, threadId });+ const messages = async () => JSON.stringify((await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`)).body);+ if (sent.status === 202) await expect.poll(async () => until(await messages()), { timeout: 60_000, interval: 150 }).toBe(true);+ return { sent, threadId, messages: await messages() };+}+const engineRan = () => existsSync(join(team.home, "dump.json"));+const engineSaw = () => JSON.parse(readFileSync(join(team.home, "dump.json"), "utf8")) as { mcpConfig?: { mcpServers?: Record<string, unknown> } };++/** One routine run by hand, as an Admin starts one: what it answered, and the finished run's words. */+async function routineRun(name: string) {+ const created = await team.as(owner, "POST", "/api/routines", { name, prompt: `Run ${name}.`, botId, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ rmSync(join(team.home, "dump.json"), { force: true });+ const started = await team.as(owner, "POST", `/api/routines/${created.body.routine.id}/run`);+ if (started.status !== 201) return { status: started.status, words: JSON.stringify(started.body) };+ const runId = started.body.run.id as string, deadline = Date.now() + 60_000;+ for (;;) {+ const run = ((await team.as(owner, "GET", "/api/routines")).body.runs as { id: string; status: string; threadId: string }[]).find((candidate) => candidate.id === runId)!;+ if (!["queued", "running", "starting", "waiting", "pending"].includes(run.status)) {+ const messages = await team.as(owner, "GET", `/api/threads/${run.threadId}/messages?limit=200`);+ return { status: started.status, words: `${JSON.stringify(run)} ${JSON.stringify(messages.body)}` };+ }+ if (Date.now() > deadline) throw new Error(`routine did not finish: ${JSON.stringify(run)}`);+ await new Promise((resolve) => setTimeout(resolve, 150));+ }+}++beforeAll(async () => {+ adminServer = createServer((req, res) => {+ const chunks: Buffer[] = [];+ req.on("data", (chunk) => chunks.push(chunk));+ req.on("end", () => {+ const body = Buffer.concat(chunks).toString("utf8");+ expect(req.url).toBe(TEAM_POLICY_ADMIN_PATH);+ const headers = req.headers as Record<string, string>;+ admin.signed.push(/^v1=[\w-]{43}$/.test(headers["x-omb-cloud-signature"] ?? "") && Boolean(headers["x-omb-cloud-machine"]) && createHash("sha256").update(body).digest().length === 32);+ admin.reports.push(JSON.parse(body));+ res.writeHead(admin.answer.status, { "content-type": admin.answer.type });+ res.end(typeof admin.answer.body === "string" ? admin.answer.body : JSON.stringify(admin.answer.body));+ });+ });+ await new Promise<void>((resolve) => adminServer.listen(0, "127.0.0.1", resolve));+ relay = createServer((_req, res) => { res.writeHead(404, { "content-type": "application/json" }); res.end("{}"); });+ await new Promise<void>((resolve) => relay.listen(0, "127.0.0.1", resolve));+ gateway = await startFakeHttpMcp({ tools: [{ name: "lookup_order", inputSchema: { type: "object", properties: {} } }], callResult: () => ({ content: [{ type: "text", text: "ok" }] }) });+ broker = await startBrokerFake();+ const relayBase = `http://127.0.0.1:${(relay.address() as AddressInfo).port}`;+ fx = await launchCloudSendFixture({ onePasswordToken: "ops_fake-rules", broker, team: { id: "team-acme-1", name: "Acme", engine: ENGINE, env: {+ OMB_BOT_BOX: "0", FIXTURE_ADMIN_STAND_IN: `http://127.0.0.1:${(adminServer.address() as AddressInfo).port}`,+ OMB_CLOUD_BOAT_URL: `${relayBase}/relay/api/box/v1`, OMB_CLOUD_BOAT_TOKEN: "box_omb_rules",+ } } });+ team = fx.team!;+ owner = (await team.pair(OWNER)).token!;+ ada = (await team.pair(ADA)).token!;+ const created = await team.as(owner, "POST", "/api/bots", { name: "Scout" });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ botId = created.body.bot.id;+ peerId = (await team.as(owner, "POST", "/api/bots", { name: "Helper" })).body.bot.id;+ expect((await team.as(owner, "POST", "/api/mcp/servers", { name: "orders", type: "http", url: gateway.url })).status).toBe(201);+ expect((await team.as(owner, "PATCH", "/api/mcp/servers/orders", { enabled: true })).status).toBe(200);+}, hostTimeout(120_000));++afterAll(async () => {+ await fx?.close();+ await gateway?.close();+ await broker?.close();+ await new Promise((resolve) => adminServer?.close(resolve));+ await new Promise((resolve) => relay?.close(resolve));+});++it("with no rules, everything is as it was and nobody sees a badge; the fetch is signed", async () => {+ await rules(null);+ expect(admin.signed.every(Boolean)).toBe(true);+ expect((await team.as(ada, "GET", "/api/config")).body.managedPolicy).toBeNull();+ const { messages } = await dumped(owner, "before any rule", (text) => text.includes("\"role\":\"bot\"") || text.includes("before any rule") && engineRan());+ expect(messages).not.toContain("Acme");+ await expect.poll(engineRan, { timeout: 30_000, interval: 100 }).toBe(true);+ await expect.poll(() => engineSaw().mcpConfig?.mcpServers?.orders !== undefined, { timeout: 10_000 }).toBe(true);+}, hostTimeout(90_000));++it("a blocked engine is refused for a chat turn and a routine, for an Admin and a User, naming the team; it passes again once the rule lifts, with no restart", async () => {+ await rules({ allowedEngines: ["codex"] });+ const summary = (await team.as(ada, "GET", "/api/config")).body.managedPolicy;+ expect(summary).toMatchObject({ organizationName: "Acme", allowedEngines: ["codex"], companyModelsOnly: false, team: true });++ for (const token of [owner, ada]) {+ const { sent } = await dumped(token, "blocked engine", () => true);+ expect(sent.status, JSON.stringify(sent.body)).toBe(409);+ expect(sent.body.error).toMatch(/^Acme does not allow the Claude engine\. .*ask a team admin\.$/);+ expect(engineRan()).toBe(false);+ }+ const routine = await routineRun("Blocked engine");+ expect(routine.words).toMatch(/Acme does not allow the Claude engine/);+ expect(engineRan()).toBe(false);+ // One bot asking another: the same refusal, and the engine never starts.+ const thread = await team.as(owner, "POST", `/api/bots/${botId}/tasks`, { title: "asks a teammate" });+ const capability = await team.capability(botId, thread.body.task.threadId);+ rmSync(join(team.home, "dump.json"), { force: true });+ const asked = await fetch(`${team.base}/api/internal/coordinate-bots`, { method: "POST", headers: { authorization: `Bearer ${capability}`, "content-type": "application/json" }, body: JSON.stringify({ botIds: [peerId], message: "Please check this.", reply: "none", thread: "fresh" }) });+ const askedWords = await asked.text();+ expect(asked.status, askedWords).toBeLessThan(500);+ const peerWords = async () => {+ const bots = (await team.as(owner, "GET", "/api/bots")).body.bots as { id: string; threadId?: string; tasks: { threadId: string }[] }[];+ const threads = bots.filter((bot) => bot.id === peerId || bot.id === botId).flatMap((bot) => [...(bot.threadId ? [bot.threadId] : []), ...bot.tasks.map((task) => task.threadId)]);+ const lines = await Promise.all(threads.map(async (id) => JSON.stringify((await team.as(owner, "GET", `/api/threads/${id}/messages?limit=200`)).body)));+ return lines.join(" ") + askedWords;+ };+ await expect.poll(peerWords, { timeout: 15_000, interval: 200 }).toMatch(/Acme does not allow the Claude engine/);+ expect(engineRan()).toBe(false);+ // The engine stays listed, with the reason: never hidden.+ const claude = (await team.as(owner, "GET", "/api/instances")).body.instances.find((instance: { instanceId: string }) => instance.instanceId === "claude");+ expect(claude.policy).toMatchObject({ organizationName: "Acme", team: true });++ await rules(null);+ expect((await team.as(ada, "GET", "/api/config")).body.managedPolicy).toBeNull();+ await dumped(ada, "engine allowed again", () => engineRan());+ expect(engineRan()).toBe(true);+ const again = await routineRun("Engine allowed again");+ expect(again.words).not.toMatch(/Acme does not allow/);+ expect(engineRan()).toBe(true);+}, hostTimeout(180_000));++it("a blocked MCP server never reaches a chat turn or a routine, and can't be added; it returns once the rule lifts", async () => {+ await rules({ allowedMcpServers: ["approved"] });+ await dumped(owner, "blocked server", () => engineRan());+ expect(engineSaw().mcpConfig?.mcpServers?.orders).toBeUndefined();+ await routineRun("Blocked server");+ expect(engineRan()).toBe(true);+ expect(engineSaw().mcpConfig?.mcpServers?.orders).toBeUndefined();+ const listed = await team.as(owner, "GET", "/api/mcp/servers");+ expect(listed.body.managed).toMatchObject({ organizationName: "Acme", allowlist: ["approved"] });+ expect(listed.body.servers.find((server: { name: string }) => server.name === "orders")).toMatchObject({ managedBy: "Acme" });+ const added = await team.as(owner, "POST", "/api/mcp/servers", { name: "other", type: "http", url: gateway.url });+ expect([added.status, added.body.code]).toEqual([403, "managed_policy"]);+ expect(added.body.error).toMatch(/^Acme allows only MCP servers it has approved\. Ask a team admin/);++ await rules({ allowedMcpServers: ["orders"] });+ await dumped(owner, "approved server", () => engineRan());+ expect(engineSaw().mcpConfig?.mcpServers?.orders).toBeDefined();+ await rules(null);+ await routineRun("Server allowed again");+ expect(engineSaw().mcpConfig?.mcpServers?.orders).toBeDefined();+}, hostTimeout(180_000));++it("only the team's own servers: an admin still adds one, a bot can't, and a turn keeps the team's", async () => {+ await rules({ allowedMcpServers: "team" });+ const added = await team.as(owner, "POST", "/api/mcp/servers", { name: "second", type: "http", url: gateway.url });+ expect(added.status, JSON.stringify(added.body)).toBe(201);+ expect((await team.as(owner, "DELETE", "/api/mcp/servers/second")).status).toBe(200);+ await dumped(ada, "the team's own", () => engineRan());+ expect(engineSaw().mcpConfig?.mcpServers?.orders).toBeDefined();+ const thread = await team.as(owner, "POST", `/api/bots/${botId}/tasks`, { title: "adds a server" });+ const capability = await team.capability(botId, thread.body.task.threadId);+ const byBot = await fetch(`${team.base}/api/internal/mcp-servers`, { method: "POST", headers: { authorization: `Bearer ${capability}`, "content-type": "application/json" }, body: JSON.stringify({ action: "add", name: "mine", type: "http", url: gateway.url }) });+ expect([byBot.status, (await byBot.json() as { error?: string }).error]).toEqual([403, "Acme uses only the MCP servers its admins add. Ask a team admin."]);+ await rules(null);+}, hostTimeout(90_000));++it("a connected app the rules don't allow: its tools and its sign-in are refused, whatever the bot asks; it lifts", async () => {+ await rules({ allowedApps: ["gmail"] });+ const thread = await team.as(owner, "POST", `/api/bots/${botId}/tasks`, { title: "uses an app" });+ const capability = await team.capability(botId, thread.body.task.threadId, "connectors");+ const call = async (name: string, args: unknown = {}) => {+ const answer = await fetch(`${team.base}/api/internal/connectors/mcp`, { method: "POST", headers: { authorization: `Bearer ${capability}`, "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) });+ return JSON.stringify(await answer.json());+ };+ expect(await call("SLACK_SEND_MESSAGE")).toContain("Acme does not allow bots to use Slack. Ask a team admin.");+ expect(await call("COMPOSIO_MULTI_EXECUTE_TOOL", { tools: [{ tool_slug: "GMAIL_FETCH_EMAILS" }, { tool_slug: "SLACK_SEND_MESSAGE" }] })).toContain("Acme does not allow bots to use Slack.");+ expect(await call("COMPOSIO_REMOTE_WORKBENCH", { code: "run()" })).toContain("can't run code");+ expect(await call("GMAIL_FETCH_EMAILS")).not.toContain("Acme does not allow");+ const signIn = await team.as(owner, "POST", "/api/connectors/slack/authorize", {});+ expect([signIn.status, signIn.body.code]).toEqual([403, "managed_policy"]);+ await rules(null);+ expect(await call("SLACK_SEND_MESSAGE")).not.toContain("Acme does not allow");+}, hostTimeout(60_000));++it("a blocked cloud desktop is refused for a chat turn and a routine; a lent computer is refused too; both lift", async () => {+ const setComputer = await team.as(owner, "PATCH", `/api/bots/${botId}`, { computer: "cloud" });+ expect(setComputer.status, JSON.stringify(setComputer.body)).toBe(200);+ await rules({ allowedComputers: ["vps"] });+ const { sent, messages } = await dumped(owner, "blocked computer", (text) => /Acme does not allow bots to use cloud computers/.test(text));+ expect(`${JSON.stringify(sent.body)} ${messages}`).toMatch(/Acme does not allow bots to use cloud computers\. Ask a team admin\./);+ const routine = await routineRun("Blocked computer");+ expect(routine.words).toMatch(/Acme does not allow bots to use cloud computers/);++ const thread = await team.as(owner, "POST", `/api/bots/${botId}/tasks`, { title: "lent" });+ const capability = await team.capability(botId, thread.body.task.threadId);+ const lent = await fetch(`${team.base}/api/internal/shared-computers`, { method: "POST", headers: { authorization: `Bearer ${capability}`, "content-type": "application/json" }, body: JSON.stringify({ action: "list_files", computer_id: "7c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f" }) });+ const lentBody = await lent.json() as { error?: string };+ expect([lent.status, lentBody.error]).toEqual([403, "Acme does not allow bots to use a member's own computer. Ask a team admin."]);++ await rules(null);+ const after = await dumped(owner, "computer allowed again", () => engineRan());+ expect(after.messages).not.toMatch(/Acme does not allow/);+ expect((await team.as(owner, "PATCH", `/api/bots/${botId}`, { computer: null })).status).toBe(200);+}, hostTimeout(180_000));++it("remote access off refuses a phone code and signs phones out, while every member's app still pairs; it lifts", async () => {+ const code = await team.as(ada, "POST", "/api/team/phone-pairing", {});+ expect(code.status, JSON.stringify(code.body)).toBe(200);+ const phone = await fetch(`${team.base}/api/auth/pair`, { method: "POST", headers: { ...fx.edge, "content-type": "application/json" }, body: JSON.stringify({ code: code.body.code, label: "Phone" }) });+ const phoneToken = ((await phone.json()) as { token: string }).token;+ expect((await team.as(phoneToken, "GET", "/api/config")).status).toBe(200);+ const unused = await team.as(ada, "POST", "/api/team/phone-pairing", {});+ expect(unused.status).toBe(200);++ await rules({ remoteAccess: "off" });+ const refused = await team.as(ada, "POST", "/api/team/phone-pairing", {});+ expect([refused.status, refused.body.code]).toEqual([403, "managed_policy"]);+ expect(refused.body.error).toBe("Acme does not allow opening this Cloud on a phone or with a link. Ask a team admin.");+ expect((await team.as(phoneToken, "GET", "/api/config")).status).toBe(401);+ // A code made before the rule stops working too.+ const late = await fetch(`${team.base}/api/auth/pair`, { method: "POST", headers: { ...fx.edge, "content-type": "application/json" }, body: JSON.stringify({ code: unused.body.code }) });+ expect(late.status).toBe(401);+ // The Admin's signed pairing is how every member's app reaches the Cloud: a rule never locks the team out.+ const app = await team.pair(ADA);+ expect(app.status, JSON.stringify(app.body)).toBe(200);+ ada = app.token!;++ await rules(null);+ expect((await team.as(ada, "POST", "/api/team/phone-pairing", {})).status).toBe(200);+}, hostTimeout(60_000));++it("a kept policy applies at once after a restart with the Admin unreachable, and never lapses; a document it can't read keeps the last good one and says so", async () => {+ const policy = publish({ allowedEngines: ["codex"] })!;+ await nudged(policy.fingerprint);+ const kept = JSON.parse(readFileSync(join(team.home, ".openmausbot", TEAM_POLICY_FILE), "utf8"));+ expect(kept).toMatchObject({ teamId: team.id, fingerprint: policy.fingerprint, version: policy.version });++ admin.answer = { status: 503, body: "down", type: "text/plain" };+ await team.relaunch();+ owner = (await team.pair(OWNER)).token!;+ expect((await team.as(owner, "GET", "/api/config")).body.managedPolicy).toMatchObject({ organizationName: "Acme", allowedEngines: ["codex"] });+ expect((await dumped(owner, "while the Admin is down", () => true)).sent.status).toBe(409);++ // A proxy's 404 is not the Admin's word: only JSON from it lifts the rules.+ admin.answer = { status: 404, body: "<html>not found</html>", type: "text/html" };+ await team.signed("POST", "/api/cloud/team/policy-changed", {});+ await new Promise((resolve) => setTimeout(resolve, 500));+ expect((await team.as(owner, "GET", "/api/config")).body.managedPolicy).not.toBeNull();++ // A newer kind of document: it stays alive, keeps the last good rules and reports that.+ const newer = { schema: 2, limits: {}, settings: {} };+ admin.answer = { status: 200, body: { policy: { version: ++admin.version, fingerprint: teamPolicyFingerprint(newer), document: newer } }, type: "application/json" };+ await team.signed("POST", "/api/cloud/team/policy-changed", {});+ await expect.poll(() => admin.reports.at(-1)?.problem ?? null, { timeout: 15_000, interval: 50 }).toMatch(/newer kind/);+ expect(admin.reports.at(-1)?.loaded?.fingerprint).toBe(policy.fingerprint);+ expect((await team.as(owner, "GET", "/api/config")).body.managedPolicy).toMatchObject({ allowedEngines: ["codex"] });++ // An older Admin, or its switch off: a JSON 404 is no policy.+ admin.answer = { status: 404, body: { error: "Not found." }, type: "application/json" };+ await team.signed("POST", "/api/cloud/team/policy-changed", {});+ await expect.poll(async () => (await team.as(owner, "GET", "/api/config")).body.managedPolicy, { timeout: 15_000, interval: 100 }).toBeNull();+ expect(existsSync(join(team.home, ".openmausbot", TEAM_POLICY_FILE))).toBe(false);+}, hostTimeout(120_000));++it("require a fresh policy: with none to be had, new turns are refused in plain words; a good fetch lets them through", async () => {+ const policy = publish({ requireFreshPolicy: true })!;+ await nudged(policy.fingerprint);+ await dumped(owner, "fresh rules", () => engineRan());+ expect(engineRan()).toBe(true);++ // A restart long after the last good fetch, with the Admin down: the kept rules say a fresh one is required.+ const file = join(team.home, ".openmausbot", TEAM_POLICY_FILE);+ admin.answer = { status: 503, body: "down", type: "text/plain" };+ await team.relaunch();+ writeFileSync(file, JSON.stringify({ ...JSON.parse(readFileSync(file, "utf8")), fetchedAt: Date.now() - 3_600_000 }));+ await team.relaunch();+ owner = (await team.pair(OWNER)).token!;+ const { sent } = await dumped(owner, "stale rules", () => true);+ expect(sent.status, JSON.stringify(sent.body)).toBe(409);+ expect(sent.body.error).toBe("Acme requires up-to-date rules, and this Cloud can't confirm them right now. Try again in a few minutes, or ask a team admin.");++ publish(null);+ await team.signed("POST", "/api/cloud/team/policy-changed", {});+ await expect.poll(async () => (await team.as(owner, "GET", "/api/config")).body.managedPolicy, { timeout: 15_000, interval: 100 }).toBeNull();+ await dumped(owner, "rules lifted", () => engineRan());+ expect(engineRan()).toBe(true);+}, hostTimeout(120_000));diff --git a/server/host/cloud-signed-host.ts b/server/host/cloud-signed-host.tsindex 4c799ebae8..959cf68296 100644--- a/server/host/cloud-signed-host.ts+++ b/server/host/cloud-signed-host.ts@@ -20,6 +20,8 @@ export interface CloudSignedHostDeps {teamAdmin?: { summary(): Promise<TeamAdminSummary> };/** A Team Cloud's member left (the Admin's signed request): delete what was theirs alone. */memberLeft?: (email: string) => Promise<Record<string, unknown>>;+ /** A Team Cloud's rules changed on the Admin (its signed nudge): fetch them now. */+ policyChanged?: () => void;/** The plan was cancelled, or renews again (the Admin's signed request): routines wait while it is cancelled. */plan?: (cancelled: boolean) => void;}@@ -29,7 +31,7 @@ export function createCloudSignedHost(deps: CloudSignedHostDeps): { cloudHealth:const cloudSigned = deps.cloudHome && cloudHealth? createCloudSignedRoutes({ secret: deps.cloudHome.bootstrapSecret, sessions: deps.sessions, team: deps.cloudHome.team, health: cloudHealth, power: deps.power, box: deps.box,...(deps.cloudHome.team && deps.teamAdmin ? { teamAdmin: deps.teamAdmin } : {}),- ...(deps.cloudHome.team && deps.memberLeft ? { memberLeft: deps.memberLeft } : {}), ...(deps.plan ? { plan: deps.plan } : {}) })+ ...(deps.cloudHome.team && deps.memberLeft ? { memberLeft: deps.memberLeft } : {}), ...(deps.cloudHome.team && deps.policyChanged ? { policyChanged: deps.policyChanged } : {}), ...(deps.plan ? { plan: deps.plan } : {}) }): null;return { cloudHealth, cloudSigned };}diff --git a/server/host/mcp-chat.ts b/server/host/mcp-chat.tsindex 2ae6f7a640..20f6b4792c 100644--- a/server/host/mcp-chat.ts+++ b/server/host/mcp-chat.ts@@ -89,7 +89,7 @@ export function createMcpChat(deps: McpChatDeps) {canUse: (name) => canUseMcpServer(sender.toolScope, name),config: deps.mcpConfig(), cfg: () => cfg, personal: () => teamConnections.personMcp(),authState: (name, url) => mcpOAuth.authState(name, url),- managedBy: mcpManagedBy, policyRefusal: mcpPolicyRefusal,+ managedBy: mcpManagedBy, policyRefusal: mcpPolicyRefusal, addRefusal: () => managedPolicy.botMcpRefusal(),signOut: async (name, url) => { await mcpOAuth.signOut(name, url); broadcast({ kind: "mcp.changed" }); },testAs: (name, url) => {const person = teamConnections.turnPerson(threadId, generation);@@ -127,7 +127,7 @@ export function createMcpChat(deps: McpChatDeps) {}/** The organisation whose policy leaves this server out, if one does. */function mcpManagedBy(name: string, server: object): string | undefined {- return managedPolicy.mcpAllowed(name, mcpServerUrl(server)) ? undefined : managedPolicy.current()?.organizationName;+ return managedPolicy.mcpAllowed(name, mcpServerUrl(server), "bot" in server && Boolean(server.bot)) ? undefined : managedPolicy.current()?.organizationName;}return { mcpRequests, mcpSignInCards, mcpServerDeps, resolveAndSendMcp, mcpServerResponse, mcpPolicyRefusal };diff --git a/server/index.ts b/server/index.tsindex ccfbe79bcc..89ed47e333 100644--- a/server/index.ts+++ b/server/index.ts@@ -271,7 +271,7 @@ import { EventBus } from "./harness/bus.ts";import { engineMemory, enginesByUse, ProviderRegistry } from "./harness/registry.ts"; import { afterFirstEngineRead, holdUntilFirstEngineRead } from "./first-engine-read.ts";import { ManagedDesktopProviders } from "./managed-desktop.ts";import { mainThread, wasOldestThread } from "./main-thread.ts";-import { computerKindForResource, ManagedDesktopPolicy, type ComputerKind } from "./managed-policy.ts";+import { computerKindForResource, ManagedDesktopPolicy, type ComputerKind } from "./managed-policy.ts"; import { nudgeCloudTeamPolicy, remoteAccessPaths, startCloudTeamPolicy, stopCloudTeamPolicy } from "./cloud-team-policy.ts";import { hostedModelPolicy, HOSTED_MODEL_POLICY_HEADER } from "./hosted-models.ts";import { CLOUD_HOME_SECRET_KEYS, CLOUD_IGNORED_KEYS, cloudHomeConfiguration, cloudHomeOffersPlace, cloudHomePlaceRefusal, firstCloudTurnPatch } from "./cloud-home.ts";import { botBox, startBotBoxAtBoot } from "./bot-box/boot.ts"; import { brokerPath } from "./bot-box/broker-probe.ts";@@ -2464,7 +2464,7 @@ function dataIntegration(botId: string, turn: { threadId: string; generation: st}/** Only with a connection and for a bot allowed to use it (connected apps on; scopes and grants name highlevel). */function highlevelIntegration(bot: BotRecord, turn: { threadId: string; generation: string }) {- return highlevelHost.integration(bot, () => mintInternalCapability({ botId: bot.id, ...turn, kind: "highlevel", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }), `http://127.0.0.1:${PORT}`);+ return !managedPolicy.appAllowed("highlevel") ? null : highlevelHost.integration(bot, () => mintInternalCapability({ botId: bot.id, ...turn, kind: "highlevel", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }), `http://127.0.0.1:${PORT}`);}let browserEngineInstall: Promise<void> | null = null;@@ -2887,7 +2887,7 @@ const phones = createPhones({active: (turn) => internalCapabilityIsActive(turn as InternalCapability),});let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.-const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), plan: (cancelled) => routineHolds?.plan(cancelled), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,+const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, plan: (cancelled) => routineHolds?.plan(cancelled), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),connectors: () => highlevelHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });@@ -12008,7 +12008,7 @@ async function describeInstances() {...(ownReady && described.snapshot.state === "available" ? { snapshot: { state: "unavailable" as const, reason: TRIAL_CREDIT_OWN_AI } } : {}),};const policyReason = policyModelRefusal(instance);- const policy = policyReason ? { policy: { organizationName: managedPolicy.current()!.organizationName, reason: policyReason } } : {};+ const policy = policyReason ? { policy: { organizationName: managedPolicy.current()!.organizationName, reason: policyReason, ...(managedPolicy.current()!.team ? { team: true } : {}) } } : {};if (managedDesktop.owns(instance.instanceId)) return {...described, ...policy, readOnly: true, managed: managedDesktop.info(instance.instanceId),install: undefined, authentication: undefined, cli: undefined, cliCandidates: [],@@ -12344,7 +12344,7 @@ ROUTES.push(createBotMemoryRoutes({const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (auth, threadId) => { if (ownerOrAdmin(auth) && store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: teamMessages.arrived } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => publicUrl() ?? (auth.kind === "session" ? requestOrigin(req) : null) }),- createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: { error: memberLoginRefusal(CLOUD_TEAM) } }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId) }));+ createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: { error: memberLoginRefusal(CLOUD_TEAM) } }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId) }));ROUTES.push(createRoomHoldRoutes({group: (id) => store.group(id),groupFor: personRooms.groupForAuth,@@ -12721,7 +12721,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return json(res, 503, { error: "Workspace sign-in is unavailable." });}}- if (method === "POST" && ["/api/auth/pair", "/api/pair", "/api/auth/pairing", "/api/auth/email/start", "/api/auth/email/verify"].includes(path)) {+ if (method === "POST" && remoteAccessPaths(CLOUD_TEAM !== null).includes(path)) {const refusal = managedPolicy.remoteAccessRefusal();if (refusal) return json(res, 403, { error: refusal, code: "managed_policy" });}@@ -13372,7 +13372,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return json(res, 403, { error: "This bot has no computer. Change its Computer setting to use a shared computer's apps and screen." });}const principal = sharedComputerPrincipal(internalCapability);- const why = CLOUD_HOME && !principal ? cloudLendingRefusalNotice(internalCapability) : null;+ const why = (CLOUD_TEAM ? managedPolicy.computerRefusal("thisComputer") : null) ?? (CLOUD_HOME && !principal ? cloudLendingRefusalNotice(internalCapability) : null);if (why) return json(res, 403, { error: why });return json(res, 200, { result: lentScreenResult(parsed.data, await sharedComputers.request(parsed.data, principal, () => lendingEnabled() && internalCapabilityIsActive(internalCapability))) });}@@ -14654,7 +14654,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {? connectorCallsIn(rpcParams.name, rpcParams.arguments): [];if (proactive.fence.refusesConnectorCall(currentSender, internalCapability.threadId, body)) return refuseOutbound(READ_AND_DRAFT_REFUSAL);- const scopeRefusal = await teamConnections.callRefusal(internalCapability, connectorCalls); if (scopeRefusal) return refuseOutbound(scopeRefusal);+ const scopeRefusal = managedPolicy.appsCallRefusal(connectorCalls, serviceSlugs) ?? await teamConnections.callRefusal(internalCapability, connectorCalls); if (scopeRefusal) return refuseOutbound(scopeRefusal);const access = connectorAccessDecision(currentSender.connectorScopes, connectorCalls, serviceSlugs);if (!access.ok) {const described = describeTool(access.slug);@@ -14695,7 +14695,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {() => {requireActiveInternalCapability();const fresh = store.bot(internalCapability.botId);- if (!fresh || fresh.composio === false || !composio.configured(cfg)) refuseDispatch("Connected apps were disabled while this call waited.");+ if (!fresh || fresh.composio === false || !composio.configured(cfg) || managedPolicy.appsCallRefusal(connectorCalls, serviceSlugs)) refuseDispatch("Connected apps were disabled while this call waited.");const freshAccess = connectorAccessDecision(fresh.connectorScopes, connectorCalls, serviceSlugs);if (!freshAccess.ok || (opaque && fresh.connectorTools !== undefined) ||(call.kind === "tools" && !evaluateConnectorTools(call.names, fresh.connectorTools, serviceSlugs).allowed) ||@@ -14760,7 +14760,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return json(res, 403, { error: `${owner.bot.name} has not been given access to ${outside}; allow it under the bot's Access settings first` });}}- const scopedLine = teamConnections.connectRefusal(internalCapability, slugs); if (scopedLine) return json(res, 409, { error: scopedLine });+ const scopedLine = managedPolicy.appsConnectRefusal(slugs) ?? teamConnections.connectRefusal(internalCapability, slugs); if (scopedLine) return json(res, 409, { error: scopedLine });const authConfigNote = await composio.prepareConnectionAuthConfigs(cfg, items);const connectionState: Record<string, { connected?: boolean }> = await composio.connectionStatus(cfg, slugs).catch(() => ({}));requireActiveInternalCapability();@@ -15295,7 +15295,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}m = path.match(/^\/api\/connectors\/([\w-]+)\/authorize$/);if (m && method === "POST") {- const body = await readBody(req);+ const body = await readBody(req); const refused = managedPolicy.appRefusal(m[1]); if (refused) return json(res, 403, { error: refused, code: "managed_policy" });const started = await composio.authorizeService(cfg, m[1], body.alias); void routineHolds?.connections("added"); return json(res, 200, started);}m = path.match(/^\/api\/connectors\/([\w-]+)\/accounts\/([A-Za-z0-9][A-Za-z0-9_-]{0,127})$/);@@ -15318,7 +15318,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const connector = message.connector;// Members reach authorize for an MCP server's Sign in card; connecting an app stays an admin's.if (m[3] === "authorize" && !auth.scopes.includes("admin")) return json(res, 403, { error: "forbidden: this session lacks the admin scope" });- if (m[3] === "authorize" && method === "POST") {+ if (m[3] === "authorize" && method === "POST") { const refused = managedPolicy.appRefusal(connector.slug); if (refused) return json(res, 403, { error: refused, code: "managed_policy" });const alias = composio.normalizeAccountAlias(typeof body.alias === "string" ? body.alias : undefined) ?? connector.alias;store.patchMessage(threadId, message.id, { connector: { ...connector, alias, status: "authorizing", error: undefined, dismissed: false } });try {@@ -15651,7 +15651,7 @@ if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATAserver.listen(PORT, "127.0.0.1", async () => {companyRuntimeReady();console.log(`openmausbot server on http://127.0.0.1:${PORT}`);- browserSweep.start(); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });+ browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });void afterFirstEngineRead().then(() => { if (builtInBrowserEnabled(cfg)) chromeLauncher.start(); });followupsReady = true;drainQueuedSends();@@ -15714,7 +15714,7 @@ const gracefulShutdown = createGracefulShutdown({if (workspaceAccessTimer) clearInterval(workspaceAccessTimer);// Invalidate turn bearers before any cleanup reaches an await: child MCP processes and the listener may outlive it.revokeAllInternalCapabilities();- sharedComputers.close(); deviceLinks.close();+ sharedComputers.close(); deviceLinks.close(); stopCloudTeamPolicy();phones.close();sharedComputerControl.close();browserLive.closeAll();diff --git a/server/managed-policy.ts b/server/managed-policy.tsindex 3b9c142f6d..38ee7f3833 100644--- a/server/managed-policy.ts+++ b/server/managed-policy.ts@@ -1,10 +1,14 @@import { z } from "zod";+import { serviceSlugFor, serviceSlugForCandidates } from "./connector-verdict.ts";+import { appLabel } from "./team-connections.ts";-/** Received only over Electron's private port and held in memory: never merged into config.json, and adds no prompts. */+/** Received over Electron's private port, or on a Team Cloud from the Admin (cloud-team-policy.ts), and held in memory:+ * never merged into config.json, and adds no prompts. */const policySchema = z.object({- organizationId: z.string().uuid(),+ organizationId: z.string().trim().min(1).max(128),organizationName: z.string().trim().min(1).max(100),- expiresAt: z.number().int().positive(),+ /** Null: a Team Cloud's rules, which never lapse; they stay in force until the team changes them. */+ expiresAt: z.number().int().positive().nullable(),version: z.number().int().min(0).max(2_147_483_647),companyModelsOnly: z.boolean(),allowedEngines: z.union([z.literal("all"), z.array(z.string().regex(/^[A-Za-z][A-Za-z0-9-]{0,63}$/)).max(64)]),@@ -12,16 +16,23 @@ const policySchema = z.object({// "box" is Boat's historical key in the org-policy schema shared with the desktop parent.computers: z.object({ thisComputer: z.boolean(), localVm: z.boolean(), box: z.boolean(), vps: z.boolean() }).strict(),remoteAccess: z.boolean(),+ /** Connected apps by service slug. Absent: this policy says nothing about them. */+ apps: z.object({ allowAll: z.boolean(), allowlist: z.array(z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/)).max(200) }).strict().optional(),+ /** Present on a Team Cloud's rules. `requireFresh`: new turns wait while the rules can't be confirmed with the Admin.+ * `ownMcpOnly`: bots get only what the team's admins added; a bot can't add one, and a bot's own doesn't start. */+ team: z.object({ requireFresh: z.boolean(), ownMcpOnly: z.boolean() }).strict().optional(),}).strict();export type ManagedPolicy = z.infer<typeof policySchema>;export type ComputerKind = keyof ManagedPolicy["computers"];const computerLabels: Record<ComputerKind, string> = { thisComputer: "this computer", localVm: "local virtual machines", box: "cloud computers", vps: "VPS computers" };+const teamComputerLabels: Record<ComputerKind, string> = { ...computerLabels, thisComputer: "a member's own computer", localVm: "a member's own computer" };+const ASK_ADMIN = "Ask a team admin.";export function parseManagedPolicy(raw: unknown, now = Date.now()): ManagedPolicy | null {if (raw === null) return null;const parsed = policySchema.safeParse(raw);if (!parsed.success) throw new Error("Invalid organisation policy from the desktop parent.");- return parsed.data.expiresAt > now ? parsed.data : null;+ return parsed.data.expiresAt === null || parsed.data.expiresAt > now ? parsed.data : null;}/** `*` stands for one or more whole labels, never part of one. */@@ -62,49 +73,61 @@ export class ManagedDesktopPolicy {private timer: ReturnType<typeof setTimeout> | undefined;private readonly now: () => number;private readonly onChange: () => void;+ private fresh: () => boolean = () => true;constructor(options: { now?: () => number; onChange?: () => void } = {}) {this.now = options.now ?? Date.now; this.onChange = options.onChange ?? (() => {});}+ /** Whether a Team Cloud's rules are confirmed with the Admin now; read only for a team that requires it. */+ setFreshness(fresh: () => boolean): void { this.fresh = fresh; }apply(raw: unknown): void {const next = parseManagedPolicy(raw, this.now());const changed = JSON.stringify(next) !== JSON.stringify(this.policy);this.policy = next;clearTimeout(this.timer);- // The last applied policy holds only as long as the device credential.- if (next) {+ // The last applied policy holds only as long as the device credential; a Team Cloud's rules have none to outlive.+ if (next?.expiresAt) {this.timer = setTimeout(() => this.apply(null), Math.min(2_147_483_647, Math.max(1, next.expiresAt - this.now())));this.timer.unref?.();}if (changed) this.onChange();}current(): ManagedPolicy | null {- return this.policy && this.policy.expiresAt > this.now() ? this.policy : null;+ return this.policy && (this.policy.expiresAt === null || this.policy.expiresAt > this.now()) ? this.policy : null;}close() { clearTimeout(this.timer); this.policy = null; }modelRefusal(instance: { driverKind: string; displayName?: string }, company: boolean): string | undefined {const policy = this.current();if (!policy) return;+ if (policy.team?.requireFresh && !this.fresh()) return `${policy.organizationName} requires up-to-date rules, and this Cloud can't confirm them right now. Try again in a few minutes, or ask a team admin.`;if (policy.companyModelsOnly && !company) return `${policy.organizationName} allows only company models on this computer. Choose a Company model for this bot.`;if (policy.allowedEngines !== "all" && !policy.allowedEngines.includes(instance.driverKind)) {+ if (policy.team) return `${policy.organizationName} does not allow the ${instance.displayName ?? instance.driverKind} engine. Choose another model for this bot, or ask a team admin.`;return `${policy.organizationName} does not allow the ${instance.displayName ?? instance.driverKind} engine on this computer. Choose another model for this bot.`;}}- mcpAllowed(name: string, url?: string): boolean {+ mcpAllowed(name: string, url?: string, botOwn = false): boolean {const policy = this.current();+ if (botOwn && policy?.team?.ownMcpOnly) return false;return !policy || policy.mcp.allowCustom || policy.mcp.allowlist.some(entry => mcpEntryMatches(entry, name, url));}filterMcp<T extends object>(servers: Record<string, T>): Record<string, T> {if (!this.restrictsMcp()) return servers;return Object.fromEntries(Object.entries(servers).filter(([name, server]) =>- this.mcpAllowed(name, "url" in server && typeof server.url === "string" ? server.url : undefined)));+ this.mcpAllowed(name, "url" in server && typeof server.url === "string" ? server.url : undefined, "bot" in server && Boolean(server.bot))));+ }+ restrictsMcp(): boolean { const policy = this.current(); return Boolean(policy && (!policy.mcp.allowCustom || policy.team?.ownMcpOnly)); }+ /** A bot adding a server of its own. An admin adding one for the team is `mcpRefusal`'s to answer. */+ botMcpRefusal(): string | undefined {+ const policy = this.current();+ if (policy?.team?.ownMcpOnly) return `${policy.organizationName} uses only the MCP servers its admins add. ${ASK_ADMIN}`;}- restrictsMcp(): boolean { const policy = this.current(); return Boolean(policy && !policy.mcp.allowCustom); }mcpRefusal(name: string, url?: string): string | undefined {const policy = this.current();if (!policy || this.mcpAllowed(name, url)) return;+ if (policy.team) return `${policy.organizationName} allows only MCP servers it has approved. Ask a team admin to add this one.`;return `${policy.organizationName} allows only MCP servers it has approved. Ask your administrator to add this server to the approved list.`;}@@ -112,20 +135,48 @@ export class ManagedDesktopPolicy {computerRefusal(kind: ComputerKind): string | undefined {const policy = this.current();if (!policy || policy.computers[kind]) return;+ if (policy.team) return `${policy.organizationName} does not allow bots to use ${teamComputerLabels[kind]}. ${ASK_ADMIN}`;return `${policy.organizationName} does not allow bots to use ${computerLabels[kind]}.`;}remoteAccessRefusal(): string | undefined {const policy = this.current();if (!policy || policy.remoteAccess) return;+ if (policy.team) return `${policy.organizationName} does not allow opening this Cloud on a phone or with a link. ${ASK_ADMIN}`;return `${policy.organizationName} does not allow remote access to this computer.`;}+ appAllowed(slug: string): boolean {+ const apps = this.current()?.apps;+ return !apps || apps.allowAll || apps.allowlist.includes(slug);+ }+ appRefusal(slug: string): string | undefined {+ const policy = this.current();+ if (!policy || this.appAllowed(slug)) return;+ return `${policy.organizationName} does not allow bots to use ${appLabel(slug)}. ${ASK_ADMIN}`;+ }+ /** Apps a turn wants to connect: the first one refused. */+ appsConnectRefusal(slugs: readonly string[]): string | undefined {+ for (const slug of slugs) { const refusal = this.appRefusal(slug); if (refusal) return refusal; }+ }+ /** Tools a connected-apps call would run, as shared/outbound.ts names them; `connected`: the service slugs in use, since a+ * slug may hold an underscore. A call that runs code (`COMPOSIO_PROXY_EXECUTE`) could reach any app, so it is refused. */+ appsCallRefusal(calls: ReadonlyArray<{ slug: string }>, connected: readonly string[] = []): string | undefined {+ const policy = this.current(), apps = policy?.apps;+ if (!policy || !apps || apps.allowAll) return;+ for (const { slug } of calls) {+ if (slug === "COMPOSIO_PROXY_EXECUTE") return `${policy.organizationName} allows only the apps it has approved, so bots can't run code against them. ${ASK_ADMIN}`;+ const app = serviceSlugForCandidates(slug, [...apps.allowlist, ...connected]) ?? serviceSlugFor(slug) ?? slug;+ const refusal = this.appRefusal(app);+ if (refusal) return refusal;+ }+ }+/** Read-only view for the renderer; carries nothing secret. */summary() {const policy = this.current();if (!policy) return null;- const { organizationId: _id, expiresAt: _expires, ...visible } = policy;- return visible;+ const { organizationId: _id, expiresAt: _expires, team, ...visible } = policy;+ return { ...visible, ...(team ? { team: true as const } : {}) };}}diff --git a/server/routes/cloud-signed.ts b/server/routes/cloud-signed.tsindex 3245f735ce..fb9ca9969d 100644--- a/server/routes/cloud-signed.ts+++ b/server/routes/cloud-signed.ts@@ -8,6 +8,7 @@ import { boxSummary } from "../cloud-health.ts";import { CLOUD_HEALTH_PATH, CLOUD_PAIRING_PATH, createCloudPairing, createCloudRequestVerifier, readSignedBody } from "../cloud-home.ts";import { teamMemberEmail, type CloudTeam } from "../cloud-team.ts";import { CLOUD_TEAM_ADMIN_PATH, type TeamAdminSummary } from "../cloud-team-admin.ts";+import { CLOUD_TEAM_POLICY_CHANGED_PATH } from "../cloud-team-policy.ts";import type { CloudHealth } from "../cloud-health.ts";import { CLOUD_IDLE_ACTIVITY_MS, CLOUD_POWER_PATH, CLOUD_POWER_SLEEP_PATH, type CloudPower } from "../cloud-power.ts";import { json } from "../harness/http.ts";@@ -41,6 +42,8 @@ export function createCloudSignedRoutes(deps: {teamAdmin?: { summary(): Promise<TeamAdminSummary> } | null;/** A Team Cloud's member left: delete what was theirs alone; absent on a My Cloud. */memberLeft?: ((email: string) => Promise<Record<string, unknown>>) | null;+ /** A Team Cloud's rules changed on the Admin: fetch them now; absent on a My Cloud. */+ policyChanged?: (() => void) | null;/** The plan was cancelled (true) or renews again (false); absent on a server that is not a Cloud home. */plan?: ((cancelled: boolean) => void) | null;now?: () => number;@@ -53,13 +56,15 @@ export function createCloudSignedRoutes(deps: {const teamAdminReads = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });const memberLeftRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });const planRequests = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });+ const policyNudges = createCloudRequestVerifier({ secret: deps.secret, now: deps.now });/** True when the request was one of these and has been answered. */return async ({ req, res, url, path, method }: CloudSignedRequest): Promise<boolean> => {const power = path === CLOUD_POWER_PATH || path === CLOUD_POWER_SLEEP_PATH ? deps.power?.() ?? null : null;const teamAdmin = path === CLOUD_TEAM_ADMIN_PATH && deps.team ? deps.teamAdmin ?? null : null;const memberLeft = path === CLOUD_TEAM_MEMBER_LEFT_PATH && deps.team ? deps.memberLeft ?? null : null;const plan = path === CLOUD_PLAN_PATH ? deps.plan ?? null : null;- if (path !== CLOUD_PAIRING_PATH && path !== CLOUD_HEALTH_PATH && path !== CLOUD_BOX_PATH && !power && !teamAdmin && !memberLeft && !plan) return false;+ const policyChanged = path === CLOUD_TEAM_POLICY_CHANGED_PATH && deps.team ? deps.policyChanged ?? null : null;+ if (path !== CLOUD_PAIRING_PATH && path !== CLOUD_HEALTH_PATH && path !== CLOUD_BOX_PATH && !power && !teamAdmin && !memberLeft && !plan && !policyChanged) return false;res.setHeader("cache-control", "no-store");const source = requestSource(req);const header = (name: string) => { const value = req.headers[name]; return typeof value === "string" ? value : undefined; };@@ -107,6 +112,14 @@ export function createCloudSignedRoutes(deps: {json(res, 200, { ok: true, ...(await memberLeft(email)) });return true;}+ if (policyChanged) {+ if (method !== "POST") { json(res, 405, { error: "method_not_allowed" }); return true; }+ const verdict = policyNudges.verify({ ...signed, method, target: `${path}${url.search}`, body: await readSignedBody(req) });+ if (!verdict.ok) { console.warn(`team rules nudge refused from ${source}: ${verdict.error}`); json(res, verdict.status, { error: verdict.error }); return true; }+ policyChanged();+ json(res, 200, { ok: true });+ return true;+ }if (plan) {if (method !== "POST") { json(res, 405, { error: "method_not_allowed" }); return true; }if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) { json(res, 415, { error: "send the request as JSON (content-type: application/json)" }); return true; }diff --git a/server/routes/internal-mcp.ts b/server/routes/internal-mcp.tsindex 05f50183ac..f528499193 100644--- a/server/routes/internal-mcp.ts+++ b/server/routes/internal-mcp.ts@@ -52,6 +52,8 @@ export interface InternalMcpDeps {authState(name: string, url: string): McpAuthState;managedBy(name: string, server: StoredMcpServer): string | undefined;policyRefusal(name: string, server: StoredMcpServer): string | undefined;+ /** A team that uses only the servers its admins add: no server is added from a chat, whoever asks. */+ addRefusal?(): string | undefined;signOut(name: string, url: string): Promise<void>;/** The person this turn acts for, testing their own connection to a personal server. */testAs(name: string, url: string): { oauth: McpOAuthManager; key?: { header: string; value: string } } | null;@@ -192,6 +194,8 @@ function list(deps: Deps): Outcome {}async function add(deps: Deps, name: string, fields: Record<string, unknown>, signal: AbortSignal): Promise<Outcome> {+ const managed = deps.addRefusal?.();+ if (managed) return { status: 403, error: managed };if (!deps.teamAdmin()) return { status: 403, error: ASK_ADMIN };if (Object.hasOwn(deps.cfg().mcpServers ?? {}, name)) return { status: 409, error: `${name} already exists. Use update, or pick another name.` };const redeemed = deps.redeem(trimmedRefs({ name, ...fields }));diff --git a/server/routes/team-connections.ts b/server/routes/team-connections.tsindex eadae101b4..7b3024e689 100644--- a/server/routes/team-connections.ts+++ b/server/routes/team-connections.ts@@ -29,6 +29,8 @@ export interface TeamConnectionRouteDeps {composio: Pick<typeof Composio, "configured" | "connectedServices" | "authorizeService" | "removeService">;/** This server's own https address, where a member's MCP sign-in comes back. */publicOrigin: string | null;+ /** The team's rules: an app or server they don't allow can't be connected by anyone. */+ policy?: { appRefusal(slug: string): string | undefined; mcpRefusal(name: string, url?: string): string | undefined };/** An admin's change, for the team's admin activity. */record?(auth: RequestAuth, row: Omit<AdminActionRow, "at" | "actor">): void;}@@ -106,6 +108,8 @@ export function createTeamConnectionRoutes(deps: TeamConnectionRouteDeps): Routereturn json(res, 409, { error: `${appLabel(slug)} is ${team.name}'s, connected once for everyone by an admin.` });}if (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." });try {@@ -130,6 +134,10 @@ export function createTeamConnectionRoutes(deps: TeamConnectionRouteDeps): Routereturn json(res, 409, { error: `${name} is ${team.name}'s, connected once for everyone by an admin.` });}deps.host.people.remember(person, email);+ if ((mcp[2] === "/sign-in" || mcp[2] === "/key") && method !== "DELETE") {+ const refused = deps.policy?.mcpRefusal(name, stored.url);+ if (refused) return json(res, 403, { error: refused, code: "managed_policy" });+ }if (mcp[2] === "/sign-in" && method === "POST") {const origin = mcpCallbackOrigin(provesSameOrigin(req) ? requestOrigin(req) : null, [deps.publicOrigin]);try {diff --git a/server/sessions.ts b/server/sessions.tsindex 6d5c288464..7c133d4112 100644--- a/server/sessions.ts+++ b/server/sessions.ts@@ -589,6 +589,12 @@ export class SessionRegistry {return this.sessions.filter((s) => s.membershipAuthority === "team" && s.memberCheckedAt !== undefined).map(publicSession);}+ /** Every code a member made for a phone stops working, and every phone such a code opened signs out. Never an Admin-signed pairing (an app). */+ closeMemberPhones(): number {+ this.pairings = this.pairings.filter((pairing) => !(pairing.member && pairing.memberCheckedAt !== undefined));+ return this.memberPhones().filter((phone) => this.revoke(phone.id)).length;+ }+/** A person who left a Team Cloud: every session of theirs (app windows, phones) ends now, and no open code of theirs* can open another. With `keepRole` (the Admin vouched for them at that role), only those at another role end. Returns* how many sessions ended. */diff --git a/server/workspace-backup-policy.ts b/server/workspace-backup-policy.tsindex f09bd16316..f76ed6b510 100644--- a/server/workspace-backup-policy.ts+++ b/server/workspace-backup-policy.ts@@ -44,6 +44,8 @@ export function excludedWorkspaceAuthPath(path: string): boolean {if (/^(?:highlevel\.json\.enc|highlevel-key)(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;// A Cloud home's connected-apps installation: its connected accounts belong to it, so a copy would share them.if (/^connected-apps-installation\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;+ // A Team Cloud's kept rules: a restored Cloud asks the Admin for the ones in force now.+ if (/^team-policy\.json(?:$|\.\d+\.[0-9a-f-]+\.tmp$)/.test(path)) return true;// A Team Cloud member's own installation, keys and sign-ins: theirs, never in the team's backup.if (/^people-connections(?:\/|$)/.test(path)) return true;return /^(?:(?:providers|caddy|chrome-profile|\.agent-browser)(?:\/|$)|workspace-credentials\.json$|external-runtimes\.json$|browser-engine-key$)/.test(path) ||diff --git a/src/components/ModelPicker.tsx b/src/components/ModelPicker.tsxindex 68afa834a6..8a4b9f992c 100644--- a/src/components/ModelPicker.tsx+++ b/src/components/ModelPicker.tsx@@ -799,7 +799,7 @@ export function ModelPicker({{railInstance.policy ? (<div data-policy-blocked className="min-h-0 flex-1 overflow-y-auto px-3.5 pb-3 pt-1 text-[13px] leading-[18px] text-ink-secondary"><p className="font-medium text-ink">{t("policy.managedBy", { organization: railInstance.policy.organizationName })}</p>- <p className="mt-1">{t("policy.modelBlocked", { organization: railInstance.policy.organizationName })}</p>+ <p className="mt-1">{t(railInstance.policy.team ? "policy.teamModelBlocked" : "policy.modelBlocked", { organization: railInstance.policy.organizationName })}</p></div>) : blocked ? (<div className="min-h-0 flex-1 overflow-y-auto px-2 pb-3 pt-1">diff --git a/src/components/PluginsPanel.tsx b/src/components/PluginsPanel.tsxindex 775db60a98..94826e0f20 100644--- a/src/components/PluginsPanel.tsx+++ b/src/components/PluginsPanel.tsx@@ -798,9 +798,8 @@ export function PluginsPanel() {const reconnect = pending ? undefined : accountToReconnect(serviceStatus);const addingAccount = aliasSlug === card.slug && !included;const busy = busySlug === card.slug;- const unavailableReason = managedConnectorUnavailableReason(mode, card.slug)- ? t("connectors.selfHostOnlyReason")- : null;+ const policy = state.config?.managedPolicy, unavailableReason = policy?.apps && !policy.apps.allowAll && !policy.apps.allowlist.includes(card.slug) ? t("policy.managedBy", { organization: policy.organizationName })+ : managedConnectorUnavailableReason(mode, card.slug) ? t("connectors.selfHostOnlyReason") : null;const usedBy = connected || included ? botsUsingService(state.bots, state.instances, card.slug) : [];const description = unavailableReason ?? (pendingdiff --git a/src/components/ServerPairingCard.tsx b/src/components/ServerPairingCard.tsxindex 266fb95bfe..cbc130368d 100644--- a/src/components/ServerPairingCard.tsx+++ b/src/components/ServerPairingCard.tsx@@ -49,7 +49,7 @@ export function shownDevices(devices: PairedDevice[], cloudHome: boolean): Paireconst button = "ui-button ui-button-primary";const quiet = "ui-button";-export function ServerPairingCard({ initialSession = null, initialPairingCodes = true, cloudHome = false, focusRequest = 0, team, simple = false }: { initialSession?: SessionState | null; initialPairingCodes?: boolean; cloudHome?: boolean; focusRequest?: number; team?: string; simple?: boolean }) {+export function ServerPairingCard({ initialSession = null, initialPairingCodes = true, cloudHome = false, focusRequest = 0, team, teamPhoneBlocked = null, simple = false }: { initialSession?: SessionState | null; initialPairingCodes?: boolean; cloudHome?: boolean; focusRequest?: number; team?: string; teamPhoneBlocked?: string | null; simple?: boolean }) {const [session, setSession] = useState<SessionState | null>(initialSession);const [pairingCodes, setPairingCodes] = useState(initialPairingCodes);const [scope, setScope] = useState<"admin" | "client">("admin");@@ -97,7 +97,7 @@ export function ServerPairingCard({ initialSession = null, initialPairingCodes =if (team && session?.kind === "session" && session.team) {return (<div ref={root} tabIndex={-1} data-phone-pairing="server" className="scroll-mt-4 rounded-xl focus:outline-none">- <TeamPhoneCard team={team} />+ <TeamPhoneCard team={team} blocked={teamPhoneBlocked} /></div>);}diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsxindex 907ea8ea38..fd8ecd5611 100644--- a/src/components/SettingsModal.tsx+++ b/src/components/SettingsModal.tsx@@ -313,7 +313,7 @@ export function SettingsModal() {client: <RemoteComputerSection hideWhenUnavailable={!advanced} />,domain: remoteActive ? null : <CustomDomainSettings />,// Security: the server decides who may pair (an owner or admin session), not this gate.- pairing: <ServerPairingCard cloudHome={state.config?.cloudHome === true} focusRequest={computerPairs ? 0 : phoneFocus} team={state.config?.team?.name} simple={!advanced} />,+ pairing: <ServerPairingCard cloudHome={state.config?.cloudHome === true} focusRequest={computerPairs ? 0 : phoneFocus} team={state.config?.team?.name} teamPhoneBlocked={state.config?.managedPolicy?.remoteAccess === false ? t("policy.teamRemoteBlocked", { organization: state.config.managedPolicy.organizationName }) : null} simple={!advanced} />,companion: remoteActive ? null : <CompanionSection profileEmail={state.config?.profile?.email} focusRequest={computerPairs ? phoneFocus : 0} />,};diff --git a/src/components/SimpleModelMenu.tsx b/src/components/SimpleModelMenu.tsxindex 244b8fe6b4..c5ed5186da 100644--- a/src/components/SimpleModelMenu.tsx+++ b/src/components/SimpleModelMenu.tsx@@ -82,7 +82,7 @@ function GroupBody({ group, props }: { group: MenuGroup; props: SimpleModelMenuPreturn (<div data-simple-policy className="flex flex-col gap-0.5 py-1 pl-8 pr-2"><p className="text-[13px] leading-[18px] text-ink-secondary">{t("policy.managedBy", { organization: body.organization })}</p>- <p className="text-[12px] leading-4 text-ink-tertiary">{t("policy.modelBlocked", { organization: body.organization })}</p>+ <p className="text-[12px] leading-4 text-ink-tertiary">{t(body.team ? "policy.teamModelBlocked" : "policy.modelBlocked", { organization: body.organization })}</p></div>);case "setUp":diff --git a/src/components/TeamPhoneCard.tsx b/src/components/TeamPhoneCard.tsxindex 5b80ea067c..60a89bc172 100644--- a/src/components/TeamPhoneCard.tsx+++ b/src/components/TeamPhoneCard.tsx@@ -20,7 +20,7 @@ function phoneRow(phone: Pick<TeamPhone, "label" | "email">): string {}/** A Team Cloud's "Open on your phone", for every member: one code, made for whoever is signed in, and the phones it opened. */-export function TeamPhoneCard({ team }: { team: string }) {+export function TeamPhoneCard({ team, blocked }: { team: string; blocked?: string | null }) {const [offer, setOffer] = useState<TeamPhoneCode | null>(null);const [phones, setPhones] = useState<TeamPhone[] | null>(null);const [current, setCurrent] = useState<string | null>(null);@@ -81,10 +81,11 @@ export function TeamPhoneCard({ team }: { team: string }) {return (<Card title={t("teamPhone.title")} subtitle={t("teamPhone.subtitle", { team })}><div className="mt-3 flex flex-wrap items-center gap-3">- <button type="button" data-phone-pairing-action onClick={() => void create()} disabled={busy} className="ui-button ui-button-primary">+ <button type="button" data-phone-pairing-action onClick={() => void create()} disabled={busy || Boolean(blocked)} title={blocked ?? undefined} className="ui-button ui-button-primary">{busy ? t("remote.serverPairing.creating") : t("remote.serverPairing.create")}</button></div>+ {blocked ? <p role="status" data-team-phone-blocked className="mt-3 text-[13px] text-ink-secondary">{blocked}</p> : null}{offer ? (<div data-team-phone-code className="mt-4 rounded-lg border border-hairline/40 bg-inset p-4">{expired ? <p className="text-[13px] text-ink-secondary">{t("remote.serverPairing.expired")}</p> : (diff --git a/src/lib/simple-model-menu.ts b/src/lib/simple-model-menu.tsindex 2191463e76..666395e991 100644--- a/src/lib/simple-model-menu.ts+++ b/src/lib/simple-model-menu.ts@@ -23,7 +23,7 @@ export interface MenuModelRow {}export type MenuGroupBody =- | { kind: "policy"; organization: string }+ | { kind: "policy"; organization: string; team?: boolean }| { kind: "setUp" }| { kind: "signIn" }| { kind: "empty"; loading: boolean }@@ -152,7 +152,7 @@ export function simpleModelMenu(input: SimpleMenuInput): SimpleMenu {const current = ordered.find((instance) => instance.instanceId === selection.instanceId);function groupBody(instance: InstanceInfo, provider: string): MenuGroupBody | null {- if (instance.policy) return query ? null : { kind: "policy", organization: instance.policy.organizationName };+ if (instance.policy) return query ? null : { kind: "policy", organization: instance.policy.organizationName, ...(instance.policy.team ? { team: true } : {}) };if (needsCli(instance)) return query ? null : { kind: "setUp" };const { signedOut, own, all } = models.get(instance.instanceId)!;if (all.length === 0) return query ? null : signedOut ? { kind: "signIn" } : { kind: "empty", loading: input.refreshing === instance.instanceId };diff --git a/src/locales/en.json b/src/locales/en.jsonindex f7efb1b0b4..a51191b057 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1483,6 +1483,8 @@"policy.mcpRestricted": "Managed by {organization}: only MCP servers your organization has approved reach bots.","policy.mcpBlocked": "Not approved by {organization}; bots do not get this server.","policy.remoteBlocked": "Managed by {organization}: remote access to this computer is turned off.",+ "policy.teamModelBlocked": "{organization} doesn't let bots use this AI. Choose another, or ask a team admin.",+ "policy.teamRemoteBlocked": "Managed by {organization}: opening this Cloud on a phone is turned off. Ask a team admin.","organization.licenseExpired": "Your organization's OpenMaus Admin license has expired. Contact your admin.","organization.companyModelsUnavailable": "Unavailable until the licence is renewed","organization.reopen": "Open the sign-in page again",diff --git a/src/state/config-status.ts b/src/state/config-status.tsindex e6a6406777..337c057f67 100644--- a/src/state/config-status.ts+++ b/src/state/config-status.ts@@ -148,6 +148,10 @@ export interface ManagedPolicySummary {mcp: { allowCustom: boolean; allowlist: string[] };computers: { thisComputer: boolean; localVm: boolean; box: boolean; vps: boolean };remoteAccess: boolean;+ /** Connected apps by service slug; absent from an older Team Cloud and from an organisation's policy. */+ apps?: { allowAll: boolean; allowlist: string[] };+ /** A Team Cloud's rules rather than an organisation's. */+ team?: true;}export interface BrowserEngineSummary {diff --git a/src/state/store.tsx b/src/state/store.tsxindex b5fbfed2b1..5f35a7c275 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -460,7 +460,7 @@ export interface InstanceInfo {readOnly?: boolean;trialCredit?: "active" | "used_up" | "ended";managed?: { organizationId: string; organizationName: string };- policy?: { organizationName: string; reason: string };+ policy?: { organizationName: string; reason: string; team?: boolean };snapshot: {state: "available" | "unavailable";reason?: string;