Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Keep connected-app traffic off the managed service with an own key or OMB_COMPOSIO_BROKER=off (#5277)

Milind Sonia72598ba7f97
diff --git a/docs/composio.md b/docs/composio.md
index c35f3c7661..84c647e914 100644
--- a/docs/composio.md
+++ b/docs/composio.md
@@ -22,7 +22,7 @@ A MausBot Cloud plan includes connected apps: there is no key to add. At every s
- Every later start serves that token at once and checks it with `GET /v1/me`. Only a refusal (401) registers a new installation; an outage or a rate limit keeps the token, so the Cloud's connected accounts are never stranded.
- While the Cloud has no token (the service is down or refuses new registrations), the server keeps booting and serving, Connected apps says the service is temporarily unavailable, and it tries again after 30 seconds, then 1, 2, 5, 10 and every 30 minutes, with some jitter.
- The file never goes into a backup or a move to another computer, and a restore keeps the Cloud's own (`server/workspace-backup-policy.ts`): its connected accounts belong to that installation.
-- A Composio project key the owner saves under **Self-host connected apps** still wins; clearing it returns to the included service.
+- A Composio project key the owner saves under **Self-host connected apps** still wins, and while it is saved the server sends the service nothing, not even its start-up check. Clearing it returns to the included service, within about a minute.
The built image uses the default service; `OMB_COMPOSIO_BROKER_URL` names another (a staging service, or a closed port in CI). The server run from source registers only with an explicitly named service, so development and tests never create installations on the real one.
@@ -56,6 +56,14 @@ Gmail and other polled apps are checked every 15 minutes, the minimum for Compos
that uses its own Composio project key cannot watch apps yet: `trigger_info` (`action: "events"`) and the editor say so, and a
schedule that checks the app, or a webhook, does the job instead.
+## Keeping traffic off the managed service
+
+**With your own project key saved**, the desktop app and a Cloud home do not register or check in with OpenMausBot's managed service, and connected apps go to Composio directly. An app-event automation made before the key was saved can still be paused, deleted or restored, but only here: its copy on the service is left alone and removed if you later go back to the service.
+
+**`OMB_COMPOSIO_BROKER=off`** in the environment of the desktop app, a server or a Cloud home turns the service off whether or not a key is saved: no registration, check-in, tool calls or app events. Connected apps then need your own key, and show the setup message until there is one. A saved installation is kept for if the switch is removed. `OMB_COMPOSIO_BROKER_URL` is not a switch: left blank it means the default service.
+
+Still on the service with a key saved: a Team Cloud's per-person apps (**each person connects their own**). With the switch off those are unavailable, and connecting one says so.
+
## Scoped key permissions
A default project API key works without additional configuration. For a least-privilege scoped key, grant:
diff --git a/electron/main.mjs b/electron/main.mjs
index a3a150b9bb..aa6d9e5f10 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -48,10 +48,10 @@ import { appPermissionHandlers, externalLinkUrl } from "./app-permissions.mjs";
import { appFrameNavigationAllowed } from "./app-frame-guard.mjs";
import { writeClipboardText } from "./clipboard-write.mjs";
import {
- ensureManagedComposioCredentials,
managedComposioAccess,
managedComposioBrokerUrl,
managedComposioChildEnvironment,
+ registerManagedComposio,
} from "./managed-composio.mjs";
import {
createManagedCompanionTunnel,
@@ -1220,6 +1220,11 @@ async function startServerPackaged() {
return false;
}
+function checkInManagedComposio() {
+ if (desktopRemoteAccess || !app.isPackaged || credentialStoreUnavailable) return;
+ void registerManagedComposio({ brokerUrl: composioBrokerUrl(), updateCredentials: updateSecureCredentialDocument, log: slog }).finally(syncManagedComposioCredentials);
+}
+
function syncManagedComposioCredentials() {
if (!serverProc) return;
try {
@@ -2765,7 +2770,7 @@ async function saveWorkspaceCredential(name, value) {
if (!app.isPackaged) return applyToHarness();
// Commit the encrypted value before the server makes it live; a failed reload rolls credentials.bin back.
- return updateSecureCredentialDocument(
+ const saved = await updateSecureCredentialDocument(
(credentials) => {
if (secret) credentials[name] = secret;
else delete credentials[name];
@@ -2773,6 +2778,8 @@ async function saveWorkspaceCredential(name, value) {
},
applyToHarness,
);
+ if (name === "composioApiKey" && !secret) checkInManagedComposio();
+ return saved;
}
installCredentialStoreIpc({ ipcMain, localOnly, dialog, windowFor: (sender) => BrowserWindow.fromWebContents(sender), t: nativeT, appName: () => app.name, unreadable: () => credentialStoreUnavailable, quitting: () => desktopShutdownStarted, moveAside: () => fs.renameSync(CREDENTIALS_FILE, `${CREDENTIALS_FILE}.unreadable-${Date.now()}`), log: slog, relaunch: relaunchAfterDesktopRemoteChange });
@@ -3074,17 +3081,7 @@ app.whenReady().then(async () => {
if (credentialStoreUnavailable) {
slog("skipping connected-apps registration: the credential store was unreadable this launch");
}
- if (!desktopRemoteAccess && app.isPackaged && composioBrokerUrl() && !credentialStoreUnavailable) {
- void updateSecureCredentialDocument(async (credentials) => {
- await ensureManagedComposioCredentials({
- brokerUrl: composioBrokerUrl(),
- credentials,
- saveCredentials: async () => {},
- log: slog,
- });
- return credentials;
- }).finally(syncManagedComposioCredentials);
- }
+ checkInManagedComposio();
startUpdater(quietSignals({ powerMonitor, window: () => mainWindow, lastInput: oneHome.lastInput, local: localServerRequest, place: () => homeWindow.placeOrigin(), cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), busy: () => ((oneHome.oneHome.busy() || ownHome?.busy()) && "move") || (computerSharing?.busy() && "lending") || (talk.busy() && "talk") || (companyBackupController || companyRestoreCommitting ? "backup" : null) }));
refreshApplicationMenu();
openWindowForLink = () => {
diff --git a/electron/managed-composio.d.mts b/electron/managed-composio.d.mts
index 497a0d6fa9..ca10a24539 100644
--- a/electron/managed-composio.d.mts
+++ b/electron/managed-composio.d.mts
@@ -7,6 +7,8 @@ export interface ManagedComposioCredentials {
export interface ManagedComposioAccess { url: string; token: string }
export declare const DEFAULT_MANAGED_COMPOSIO_BROKER_URL: string;
+export declare function managedComposioBrokerOff(environment?: Record<string, string | undefined>): boolean;
+export declare function ownComposioKey(credentials: ManagedComposioCredentials | null | undefined, environment?: Record<string, string | undefined>): boolean;
export declare function managedComposioBrokerUrl(configured: string | undefined, shipped: boolean): string;
export declare function normalizeManagedComposioBrokerUrl(value: unknown): string;
export declare function managedComposioAccess(
@@ -30,3 +32,10 @@ export declare function ensureManagedComposioCredentials<T extends ManagedCompos
existingCredentialTimeoutMs?: number;
registrationTimeoutMs?: number;
}): Promise<T>;
+/** The desktop app's check-in: nothing is sent while the person's own Composio project key is saved. */
+export declare function registerManagedComposio<T extends ManagedComposioCredentials>(options: {
+ brokerUrl: string;
+ updateCredentials: (derive: (credentials: T) => Promise<T>) => Promise<unknown>;
+ fetchImpl?: typeof fetch;
+ log?: (line: string) => void;
+}): Promise<unknown>;
diff --git a/electron/managed-composio.mjs b/electron/managed-composio.mjs
index ff279c430e..769449ab98 100644
--- a/electron/managed-composio.mjs
+++ b/electron/managed-composio.mjs
@@ -3,8 +3,19 @@ const TOKEN = /^[0-9a-f]{64}$/;
/** OpenMausBot's connected-apps service (cloudflare/composio-broker): the packaged desktop app and a Cloud home use it. */
export const DEFAULT_MANAGED_COMPOSIO_BROKER_URL = "https://openmausbot-composio.milindsoni201.workers.dev";
+/** OMB_COMPOSIO_BROKER=off: nothing reaches the managed service, whatever else is set. */
+export function managedComposioBrokerOff(environment = process.env) {
+ return /^(off|0|false|no)$/i.test(environment.OMB_COMPOSIO_BROKER?.trim() ?? "");
+}
+
+export function ownComposioKey(credentials, environment = process.env) {
+ const saved = credentials?.composioApiKey;
+ return Boolean((typeof saved === "string" && saved.trim()) || environment.COMPOSIO_API_KEY?.trim());
+}
+
/** An explicit URL wins; otherwise the default, only for a shipped build, so development and tests never register. */
export function managedComposioBrokerUrl(configured, shipped) {
+ if (managedComposioBrokerOff()) return "";
const explicit = typeof configured === "string" ? configured.trim() : "";
return normalizeManagedComposioBrokerUrl(explicit || (shipped ? DEFAULT_MANAGED_COMPOSIO_BROKER_URL : ""));
}
@@ -24,6 +35,7 @@ export function normalizeManagedComposioBrokerUrl(value) {
}
export function managedComposioAccess(brokerUrl, credentials) {
+ if (managedComposioBrokerOff()) return null;
const url = normalizeManagedComposioBrokerUrl(brokerUrl);
const token = credentials?.composioBrokerToken;
if (!url || !TOKEN.test(token ?? "")) return null;
@@ -52,6 +64,7 @@ export async function ensureManagedComposioCredentials({
existingCredentialTimeoutMs = 8_000,
registrationTimeoutMs = 15_000,
}) {
+ if (managedComposioBrokerOff()) return credentials;
const url = normalizeManagedComposioBrokerUrl(brokerUrl);
if (!url) {
if (brokerUrl) log("connected-apps broker URL rejected: HTTPS or a loopback HTTP URL is required");
@@ -95,3 +108,13 @@ export async function ensureManagedComposioCredentials({
}
return credentials;
}
+
+export function registerManagedComposio({ brokerUrl, updateCredentials, fetchImpl, log }) {
+ if (!brokerUrl) return Promise.resolve();
+ return updateCredentials(async (credentials) => {
+ if (!ownComposioKey(credentials)) {
+ await ensureManagedComposioCredentials({ brokerUrl, credentials, fetchImpl, saveCredentials: async () => {}, log });
+ }
+ return credentials;
+ });
+}
diff --git a/electron/managed-composio.test.mjs b/electron/managed-composio.test.mjs
index 3ef605482f..96763e54fc 100644
--- a/electron/managed-composio.test.mjs
+++ b/electron/managed-composio.test.mjs
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
DEFAULT_MANAGED_COMPOSIO_BROKER_URL,
ensureManagedComposioCredentials,
@@ -6,6 +6,8 @@ import {
managedComposioBrokerUrl,
managedComposioChildEnvironment,
normalizeManagedComposioBrokerUrl,
+ ownComposioKey,
+ registerManagedComposio,
} from "./managed-composio.mjs";
const TOKEN = "a".repeat(64);
@@ -152,3 +154,58 @@ describe("managed Composio desktop registration", () => {
expect(saveCredentials).not.toHaveBeenCalled();
});
});
+
+afterEach(() => vi.unstubAllEnvs());
+
+describe("keeping the desktop app off the managed service", () => {
+ const launch = async (credentials) => {
+ const fetchImpl = vi.fn(async () => new Response("{}", { status: 200 }));
+ await registerManagedComposio({
+ brokerUrl: "https://broker.example",
+ fetchImpl,
+ updateCredentials: async (derive) => derive(credentials),
+ });
+ return fetchImpl;
+ };
+
+ it("with no key and no switch, checks in as before", async () => {
+ vi.stubEnv("COMPOSIO_API_KEY", "");
+ const fetchImpl = await launch({ composioBrokerToken: TOKEN });
+ expect(fetchImpl).toHaveBeenCalledOnce();
+ expect(String(fetchImpl.mock.calls[0][0])).toBe("https://broker.example/v1/me");
+ });
+
+ it("sends nothing while the person's own project key is saved or set in the environment", async () => {
+ expect(await launch({ composioApiKey: "ak_owner", composioBrokerToken: TOKEN })).not.toHaveBeenCalled();
+ expect(await launch({ composioApiKey: "ak_owner" })).not.toHaveBeenCalled();
+ vi.stubEnv("COMPOSIO_API_KEY", "ak_from_env");
+ expect(await launch({ composioBrokerToken: TOKEN })).not.toHaveBeenCalled();
+ });
+
+ it("treats a blank key as no key", () => {
+ vi.stubEnv("COMPOSIO_API_KEY", " ");
+ expect(ownComposioKey({ composioApiKey: " " })).toBe(false);
+ expect(ownComposioKey({ composioApiKey: "ak_owner" })).toBe(true);
+ });
+
+ it("OMB_COMPOSIO_BROKER=off stops registration, check-in and the token handed to the server, with or without a key", async () => {
+ vi.stubEnv("OMB_COMPOSIO_BROKER", " Off ");
+ vi.stubEnv("COMPOSIO_API_KEY", "");
+ expect(managedComposioBrokerUrl(undefined, true)).toBe("");
+ expect(managedComposioBrokerUrl("https://broker.example", true)).toBe("");
+ expect(managedComposioAccess("https://broker.example", { composioBrokerToken: TOKEN })).toBeNull();
+ expect(managedComposioChildEnvironment("https://broker.example", { composioBrokerToken: TOKEN }, {
+ PATH: "/usr/bin", OMB_COMPOSIO_BROKER: "off", OMB_COMPOSIO_BROKER_URL: "https://broker.example", OMB_COMPOSIO_BROKER_TOKEN: TOKEN,
+ })).toEqual({ PATH: "/usr/bin", OMB_COMPOSIO_BROKER: "off" });
+
+ expect(await launch({ composioBrokerToken: TOKEN })).not.toHaveBeenCalled();
+ expect(await launch({})).not.toHaveBeenCalled();
+ expect(await launch({ composioApiKey: "ak_owner" })).not.toHaveBeenCalled();
+ await expect(registerManagedComposio({ brokerUrl: managedComposioBrokerUrl(undefined, true), updateCredentials: vi.fn() })).resolves.toBeUndefined();
+ });
+
+ it("any other value of the switch leaves the service on", () => {
+ vi.stubEnv("OMB_COMPOSIO_BROKER", "on");
+ expect(managedComposioBrokerUrl(undefined, true)).toBe(DEFAULT_MANAGED_COMPOSIO_BROKER_URL);
+ });
+});
diff --git a/server/app-trigger-host.ts b/server/app-trigger-host.ts
index 991e1183ce..64509cfd04 100644
--- a/server/app-trigger-host.ts
+++ b/server/app-trigger-host.ts
@@ -8,6 +8,7 @@ import { appEventCatalog, appLabel } from "./app-event-catalog.ts";
import { brokerClient, type AppTriggerBroker, type BrokerAccess } from "./app-trigger-broker.ts";
import { AppTriggerRequestService, type AppTriggerRequestStore } from "./app-trigger-requests.ts";
import { AppTriggerError, AppTriggerManager, type AppTriggerPatch } from "./app-triggers.ts";
+import { managedComposioBrokerOff } from "./composio-broker-access.ts";
import type { RosterMember } from "./peer-roster.ts";
import type { RequestAuth } from "./request-auth.ts";
import type { Routine, RoutineManager } from "./routines.ts";
@@ -65,6 +66,7 @@ export function createAppTriggerHost(deps: AppTriggerHostDeps) {
const service = () => {
const mode = deps.connectionMode();
if (mode === "self-hosted") return { available: false as const, reason: "self-hosted" as const };
+ if (managedComposioBrokerOff()) return { available: false as const, reason: "off" as const };
return mode === "managed" && deps.access() ? { available: true as const } : { available: false as const, reason: "unavailable" as const };
};
const manager = new AppTriggerManager({
@@ -84,7 +86,7 @@ export function createAppTriggerHost(deps: AppTriggerHostDeps) {
});
const requests = new AppTriggerRequestService({ store: deps.store, triggers: manager, botName: (botId) => deps.store.bot(botId)?.name ?? "the bot" });
- const unavailableText = (reason: "self-hosted" | "unavailable") => reason === "self-hosted"
+ const unavailableText = (reason: "self-hosted" | "unavailable" | "off") => reason === "self-hosted"
? "App events need OpenMausBot's connected apps. This server uses its own Composio key, so a bot cannot watch apps here yet: use a schedule that checks the app, or a webhook."
: "Connected apps are not set up here, so a bot cannot watch apps yet.";
diff --git a/server/app-triggers.test.ts b/server/app-triggers.test.ts
index 81a73d2d9c..66494142bf 100644
--- a/server/app-triggers.test.ts
+++ b/server/app-triggers.test.ts
@@ -316,3 +316,91 @@ describe("instructions in the person's words", () => {
.toContain("The email, message or record these instructions mean is in the UNTRUSTED APP EVENT DATA below.");
});
});
+
+describe("automations made before the owner kept the managed service out", () => {
+ type Service = ReturnType<AppTriggerManagerOptions["service"]>;
+
+ function spied() {
+ let service: Service = { available: true };
+ const fetches: string[] = [];
+ const triggers = manager({
+ service: () => service,
+ broker: brokerClient(() => ({ url: broker.url, token: owner.token }), (input, init) => {
+ fetches.push(`${init?.method ?? "GET"} ${new URL(String(input)).pathname}`);
+ return fetch(input, init);
+ }),
+ });
+ return { triggers, fetches, setService: (next: Service) => { service = next; fetches.length = 0; } };
+ }
+
+ it.each(["self-hosted", "off"] as const)("%s: pausing, deleting, restoring and syncing change this server's copy and call nothing", async (reason) => {
+ const { triggers, fetches, setService } = spied();
+ const trigger = await gmailTrigger(triggers);
+ const copy = trigger.remote.triggerId!;
+ setService({ available: false, reason });
+
+ expect(await triggers.update(trigger.id, { enabled: false })).toMatchObject({ enabled: false, remote: { triggerId: copy, state: "active" } });
+ expect(await triggers.update(trigger.id, { restoreConfig: { query: "from:other.com" } })).toMatchObject({ config: { query: "from:other.com" }, remote: { state: "pending" } });
+ await triggers.reconcile();
+ expect(await triggers.remove(trigger.id)).toBe(true);
+ expect(triggers.get(trigger.id)).toBeNull();
+ const restored = await triggers.restore(trigger.id);
+ expect(restored).toMatchObject({ id: trigger.id, remote: { state: "pending" } });
+ expect(restored?.remote.triggerId).toBeUndefined();
+ await triggers.reconcile();
+ expect(fetches).toEqual([]);
+ await expect(triggers.create({ botId: "bot-1", name: "New", prompt: "Tell me.", app: "gmail", event: "GMAIL_NEW_GMAIL_MESSAGE" })).rejects.toMatchObject({ status: 409 });
+ expect(fetches).toEqual([]);
+ expect(triggers.snapshot().service).toEqual({ available: false, reason });
+ });
+
+ it("when the managed service comes back, the automation is made again and the old copy is removed", async () => {
+ const { triggers, fetches, setService } = spied();
+ const trigger = await gmailTrigger(triggers);
+ const copy = trigger.remote.triggerId!;
+ setService({ available: false, reason: "self-hosted" });
+ await triggers.update(trigger.id, { restoreConfig: { query: "from:other.com" } });
+ setService({ available: true });
+ await triggers.reconcile();
+ expect(triggers.get(trigger.id)).toMatchObject({ remote: { state: "active" } });
+ expect(triggers.get(trigger.id)?.remote.triggerId).not.toBe(copy);
+ expect(fetches).toContain(`DELETE /v1/triggers/${encodeURIComponent(copy)}`);
+ });
+
+ it("with no key and no switch, a service not reached yet still gets the calls, and a failed delete is retried", async () => {
+ const { triggers, fetches, setService } = spied();
+ const trigger = await gmailTrigger(triggers);
+ const copy = trigger.remote.triggerId!;
+ setService({ available: false, reason: "unavailable" });
+ await triggers.update(trigger.id, { enabled: false });
+ expect(fetches).toEqual([`PATCH /v1/triggers/${encodeURIComponent(copy)}`]);
+ fetches.length = 0;
+ await triggers.remove(trigger.id);
+ expect(fetches).toEqual([`DELETE /v1/triggers/${encodeURIComponent(copy)}`]);
+ fetches.length = 0;
+ const restored = await triggers.restore(trigger.id);
+ expect(fetches).toContain("POST /v1/triggers");
+ expect(restored?.remote.state).toBe("active");
+ });
+
+ it("the host reports the switch as off, for the app and for a bot's event list, and calls nothing", async () => {
+ vi.stubEnv("OMB_COMPOSIO_BROKER", "off");
+ try {
+ const { createAppTriggerHost } = await import("./app-trigger-host.ts");
+ const fetches = vi.fn();
+ const host = createAppTriggerHost({
+ file: join(dir, "off-app-triggers.json"),
+ store: { bot: () => undefined } as never,
+ connectionMode: () => "unavailable", access: () => ({ url: broker.url, token: owner.token }),
+ connectedApps: async () => connected, routines: () => routines, webhooks: { list: () => [] } as never,
+ webhookBase: () => "http://127.0.0.1:8800", botState: () => "ready", timeZone: () => "UTC", visibleBot: () => true,
+ emit: () => {}, audit: () => {}, broker: brokerClient(() => null, fetches as unknown as typeof fetch),
+ });
+ expect(host.manager.service()).toEqual({ available: false, reason: "off" });
+ await host.manager.reconcile();
+ expect(fetches).not.toHaveBeenCalled();
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+});
diff --git a/server/app-triggers.ts b/server/app-triggers.ts
index b75844e806..f353797f39 100644
--- a/server/app-triggers.ts
+++ b/server/app-triggers.ts
@@ -55,7 +55,7 @@ export interface AppTriggerManagerOptions {
now?: () => number;
broker: AppTriggerBroker;
/** Whether app events can work here at all, and why not. Checked on every loop, since access arrives late. */
- service: () => { available: true } | { available: false; reason: "self-hosted" | "unavailable" };
+ service: () => { available: true } | { available: false; reason: "self-hosted" | "unavailable" | "off" };
connectedApps: () => Promise<ConnectedApps>;
botState: (botId: string) => "ready" | "busy" | "missing";
runs: {
@@ -618,7 +618,7 @@ export class AppTriggerManager {
if (!binding || binding.remote?.state === "missing") {
trigger.remote = { state: "pending" };
await this.bind(trigger);
- if (!trigger.enabled) await this.options.broker.setEnabled(trigger.remote.triggerId!, false);
+ if (!trigger.enabled && trigger.remote.triggerId) await this.options.broker.setEnabled(trigger.remote.triggerId, false);
return;
}
trigger.remote = { triggerId: binding.triggerId, state: "active", syncedAt: this.now() };
@@ -669,6 +669,7 @@ export class AppTriggerManager {
}
private async bind(trigger: StoredTrigger): Promise<void> {
+ if (this.serviceOutOfReach()) return;
const { triggerId } = await this.options.broker.create({ slug: trigger.event, connectedAccountId: trigger.accountId, config: trigger.config });
trigger.remote = { triggerId, state: "active", syncedAt: this.now() };
if (trigger.problem?.kind === "error") delete trigger.problem;
@@ -677,11 +678,21 @@ export class AppTriggerManager {
/** Several automations with the same settings share one service copy; it goes only when the last one does. */
private async release(triggerId: string | undefined): Promise<void> {
if (!triggerId || this.triggers.some((trigger) => trigger.remote.triggerId === triggerId)) return;
+ if (this.serviceOutOfReach()) {
+ this.releasePending = true;
+ return;
+ }
await this.options.broker.remove(triggerId);
}
private async applyEnabled(triggerId: string | undefined): Promise<void> {
- if (triggerId) await this.options.broker.setEnabled(triggerId, this.wantsEnabled(triggerId));
+ if (triggerId && !this.serviceOutOfReach()) await this.options.broker.setEnabled(triggerId, this.wantsEnabled(triggerId));
+ }
+
+ /** The owner's own key, or the service switched off. A service merely not reached yet still gets its calls and retries. */
+ private serviceOutOfReach(): boolean {
+ const service = this.options.service();
+ return !service.available && service.reason !== "unavailable";
}
private wantsEnabled(triggerId: string): boolean {
diff --git a/server/cloud-connected-apps.e2e.test.ts b/server/cloud-connected-apps.e2e.test.ts
index b9db2ff99e..79adc3bbe6 100644
--- a/server/cloud-connected-apps.e2e.test.ts
+++ b/server/cloud-connected-apps.e2e.test.ts
@@ -48,7 +48,7 @@ async function api(method: string, path: string, options: { body?: unknown; remo
return { status: response.status, body: await response.json().catch(() => null) as any };
}
-async function boot(): Promise<void> {
+async function boot(env: Record<string, string> = {}): Promise<void> {
// Offline but for the stand-in service, so the server reaches nothing else.
const prelude = `data:text/javascript,${encodeURIComponent(`const real = globalThis.fetch;
globalThis.fetch = async (input, init) => {
@@ -66,6 +66,7 @@ globalThis.fetch = async (input, init) => {
OMB_CLOUD_BOOTSTRAP_SECRET: secret, OMB_PUBLIC_URL: `https://${HOST}`,
// From source the server registers nowhere unless told where, as here.
OMB_COMPOSIO_BROKER_URL: brokerUrl,
+ ...env,
},
stdio: ["ignore", "pipe", "pipe"],
});
@@ -200,4 +201,30 @@ describe("connected apps on a Cloud home", { timeout: 90_000 }, () => {
expect(reply.status).toBe(200);
expect(reply.body).toMatchObject({ configured: false, mode: "unavailable", setup: "service-unavailable" });
});
+
+ async function bootOffTheService(env: Record<string, string>) {
+ await waitForExit(child!, { signal: "SIGTERM" });
+ child = null;
+ registrationOpen = true;
+ writeFileSync(join(dataDir, CLOUD_CONNECTED_APPS_FILE), JSON.stringify({ version: 1, brokerUrl, installationId: "install-cloud", token: brokerToken }), { mode: 0o600 });
+ brokerCalls.length = 0;
+ await boot(env);
+ }
+
+ it("with the owner's own key, starts without a word to the service, not even its token check", async () => {
+ await bootOffTheService({ COMPOSIO_API_KEY: "ak_owner_project", OMB_CLOUD_CONNECTED_APPS_GRANT: "grant" });
+ await expect.poll(async () => (await api("GET", "/api/connectors/catalog")).body?.mode, { timeout: 15_000, interval: 150 }).toBe("self-hosted");
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
+ expect(brokerCalls).toEqual([]);
+ });
+
+ it("with OMB_COMPOSIO_BROKER=off, starts without a word to the service and asks for a key", async () => {
+ await bootOffTheService({ OMB_COMPOSIO_BROKER: "off", OMB_CLOUD_CONNECTED_APPS_GRANT: "grant" });
+ const reply = await api("GET", "/api/connectors/catalog");
+ expect(reply.status).toBe(200);
+ expect(reply.body).toMatchObject({ configured: false, mode: "unavailable", setup: "needs-setup" });
+ await new Promise((resolve) => setTimeout(resolve, 1_500));
+ expect(brokerCalls).toEqual([]);
+ expect(log).toContain("connected-apps service is switched off");
+ });
});
diff --git a/server/cloud-connected-apps.test.ts b/server/cloud-connected-apps.test.ts
index 5b7562c3cc..ceae8a6c47 100644
--- a/server/cloud-connected-apps.test.ts
+++ b/server/cloud-connected-apps.test.ts
@@ -3,8 +3,9 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { CLOUD_CONNECTED_APPS_FILE, startCloudConnectedApps, type CloudConnectedAppsOptions } from "./cloud-connected-apps.ts";
-import { connectionMode, connectorSetup, listToolkits, setManagedBrokerAccess } from "./composio.ts";
+import { cloudConnectedAppsBrokerUrl, CLOUD_CONNECTED_APPS_FILE, startCloudConnectedApps, startCloudHomeConnectedApps, stopCloudHomeConnectedApps, type CloudConnectedAppsOptions } from "./cloud-connected-apps.ts";
+import { brokerAccess, connectionMode, connectorSetup, listToolkits, setManagedBrokerAccess } from "./composio.ts";
+import { PeopleConnections } from "./team-connections.ts";
import { removeTempDir } from "./testing/cleanup.ts";
const BROKER = "https://broker.example.test";
@@ -49,6 +50,9 @@ beforeEach(() => {
});
afterEach(async () => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ stopCloudHomeConnectedApps();
setManagedBrokerAccess(null);
await removeTempDir(dataDir);
});
@@ -320,3 +324,93 @@ describe("a paid Cloud's grant", () => {
expect(applied).toEqual([{ url: BROKER, token: OLD }]);
});
});
+
+describe("a Cloud kept off the managed service", () => {
+ const GRANT = "signed-grant";
+
+ it("with the owner's own key, sends nothing at start, not even its token check or its plan, until the key is cleared", async () => {
+ store(OLD);
+ let ownKey = true;
+ const broker = fakeBroker({ "GET /v1/me": [json(200, {})], "PUT /v1/installation/cloud": [json(200, {})] });
+ await start(broker.fetchImpl, { ownKey: () => ownKey, cloudGrant: GRANT }).settled();
+ expect(broker.calls).toEqual([]);
+ expect(applied).toEqual([{ url: BROKER, token: OLD }]);
+ expect(existsSync(file())).toBe(true);
+
+ timers.shift()!.run();
+ expect(broker.calls).toEqual([]);
+
+ ownKey = false;
+ const apps = start(broker.fetchImpl, { ownKey: () => ownKey, cloudGrant: GRANT });
+ await apps.settled();
+ expect(broker.calls.map((call) => `${call.method} ${call.path}`)).toEqual(["GET /v1/me", "PUT /v1/installation/cloud"]);
+ });
+
+ it("a Cloud that started on its own key registers once the key is cleared, without a restart", async () => {
+ let ownKey = true;
+ const broker = fakeBroker({ "POST /v1/installations": [registered(NEW)] });
+ const apps = start(broker.fetchImpl, { ownKey: () => ownKey });
+ await apps.settled();
+ expect(broker.registrations()).toBe(0);
+ ownKey = false;
+ timers.shift()!.run();
+ await apps.settled();
+ expect(broker.registrations()).toBe(1);
+ expect(applied.at(-1)).toEqual({ url: BROKER, token: NEW });
+ });
+
+ it("with no key and no switch, registers as before", async () => {
+ const broker = fakeBroker({ "POST /v1/installations": [registered(NEW)] });
+ await start(broker.fetchImpl, { ownKey: () => false }).settled();
+ expect(broker.registrations()).toBe(1);
+ });
+
+ it("OMB_COMPOSIO_BROKER=off: a Cloud home registers nothing and shows the needs-a-key state, even with a token on the volume", async () => {
+ store(OLD);
+ const fetchSpy = vi.fn(async () => new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetchSpy);
+ vi.stubEnv("OMB_COMPOSIO_BROKER_URL", BROKER);
+ vi.stubEnv("OMB_COMPOSIO_BROKER", "off");
+ const apply = vi.fn();
+ startCloudHomeConnectedApps({ cloudHome: true, dataDir, apply, cloudGrant: GRANT });
+ expect(apply).not.toHaveBeenCalled();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(fetchSpy).not.toHaveBeenCalled();
+ expect(existsSync(file())).toBe(true);
+
+ expect(cloudConnectedAppsBrokerUrl()).toBe("");
+ setManagedBrokerAccess({ url: BROKER, token: OLD });
+ expect(brokerAccess()).toBeNull();
+ expect(connectionMode({})).toBe("unavailable");
+ expect(connectorSetup({}, true)).toBe("needs-setup");
+ expect(connectionMode({ composio: { apiKey: "ak_owner_project" } })).toBe("self-hosted");
+ expect(connectorSetup({ composio: { apiKey: "ak_owner_project" } }, true)).toBe("ready");
+ });
+
+ it("the switch also wins over a token named in the server's environment", async () => {
+ vi.stubEnv("OMB_COMPOSIO_BROKER_URL", BROKER);
+ vi.stubEnv("OMB_COMPOSIO_BROKER_TOKEN", OLD);
+ vi.resetModules();
+ const fresh = await import("./composio-broker-access.ts");
+ expect(fresh.brokerAccess()).toEqual({ url: BROKER, token: OLD });
+ vi.stubEnv("OMB_COMPOSIO_BROKER", "off");
+ expect(fresh.brokerAccess()).toBeNull();
+ });
+
+ it("OMB_COMPOSIO_BROKER=off: a Team Cloud member's own apps report unavailable, and the member's installation is kept", async () => {
+ const person = `p_${"a".repeat(22)}`;
+ const fetchImpl = vi.fn(async () => json(201, { installationId: "install-p", token: NEW }));
+ const people = new PeopleConnections({ dataDir, brokerUrl: () => BROKER, clients: () => undefined, isOwnerLive: () => true, fetchImpl: fetchImpl as unknown as typeof fetch });
+ await expect(people.ensureAppsAccess(person, "[email protected]")).resolves.toEqual({ url: BROKER, token: NEW });
+ expect(fetchImpl).toHaveBeenCalledOnce();
+
+ vi.stubEnv("OMB_COMPOSIO_BROKER", "off");
+ expect(people.appsAccess(person)).toBeNull();
+ expect(people.appsPeople()).toEqual([]);
+ await expect(people.ensureAppsAccess(`p_${"b".repeat(22)}`, "[email protected]")).resolves.toBeNull();
+ expect(fetchImpl).toHaveBeenCalledOnce();
+
+ vi.unstubAllEnvs();
+ expect(people.appsAccess(person)).toEqual({ url: BROKER, token: NEW });
+ });
+});
diff --git a/server/cloud-connected-apps.ts b/server/cloud-connected-apps.ts
index e40d6b8a63..d8f3dd116d 100644
--- a/server/cloud-connected-apps.ts
+++ b/server/cloud-connected-apps.ts
@@ -8,6 +8,7 @@ import { z } from "zod";
import {
ensureManagedComposioCredentials,
managedComposioAccess,
+ managedComposioBrokerOff,
type ManagedComposioAccess,
type ManagedComposioCredentials,
} from "../electron/managed-composio.mjs";
@@ -19,6 +20,9 @@ export const CLOUD_CONNECTED_APPS_FILE = "connected-apps-installation.json";
/** Between attempts while the Cloud holds no token, each with up to a fifth of jitter; the last one repeats. */
export const CLOUD_CONNECTED_APPS_RETRY_MS: readonly number[] = [30_000, 60_000, 120_000, 300_000, 600_000, 1_800_000];
+/** How often a Cloud on its owner's Composio key looks whether the key is still saved; nothing leaves the server. */
+const OWN_KEY_CHECK_MS = 60_000;
+
const TOKEN = /^[0-9a-f]{64}$/;
const storedSchema = z.object({
version: z.number(),
@@ -37,6 +41,8 @@ export interface CloudConnectedAppsOptions {
apply(access: ManagedComposioAccess | null): void;
/** OMB_CLOUD_CONNECTED_APPS_GRANT: the Admin's proof that this is a paid Cloud, which raises its daily app-event limit. */
cloudGrant?: string;
+ /** Whether the owner's own Composio project key is saved; while it is, nothing is sent to the service. */
+ ownKey?: () => boolean;
fetchImpl?: typeof fetch;
log?: (line: string) => void;
retryDelaysMs?: readonly number[];
@@ -101,12 +107,16 @@ export function startCloudConnectedApps(options: CloudConnectedAppsOptions): Clo
}
};
+ const retryAfter = (ms: number) => {
+ timer = setTimer(() => { timer = null; current = attempt(); }, ms);
+ timer.unref?.();
+ };
+
const retryLater = () => {
if (stopped) return;
const base = delays[Math.min(failures, delays.length - 1)] ?? 1_800_000;
failures += 1;
- timer = setTimer(() => { timer = null; current = attempt(); }, Math.round(base * (1 + 0.2 * random())));
- timer.unref?.();
+ retryAfter(Math.round(base * (1 + 0.2 * random())));
};
/** Settled once the service took the grant or refused it for good (4xx, including a service without the route);
@@ -137,6 +147,10 @@ export function startCloudConnectedApps(options: CloudConnectedAppsOptions): Clo
const attempt = async (): Promise<void> => {
try {
+ if (options.ownKey?.()) {
+ if (!stopped) retryAfter(OWN_KEY_CHECK_MS);
+ return;
+ }
const stored = readStored(file, options.brokerUrl);
if (stored.kind === "kept") {
log(`connected apps: ${CLOUD_CONNECTED_APPS_FILE} is left as it is, since ${stored.why}; trying again later`);
@@ -193,15 +207,19 @@ let cloudHome: CloudConnectedApps | null = null;
export const cloudConnectedAppsBrokerUrl = (): string => managedComposioBrokerUrl(process.env.OMB_COMPOSIO_BROKER_URL, !import.meta.url.endsWith(".ts"));
/** A Cloud home's plan includes the connected-apps service, so it registers itself. */
-export function startCloudHomeConnectedApps(input: { cloudHome: boolean; dataDir: string; apply: CloudConnectedAppsOptions["apply"]; cloudGrant?: string }): void {
+export function startCloudHomeConnectedApps(input: { cloudHome: boolean; dataDir: string; apply: CloudConnectedAppsOptions["apply"]; cloudGrant?: string; ownKey?: () => boolean }): void {
if (!input.cloudHome || cloudHome) return;
+ if (managedComposioBrokerOff()) {
+ console.log("cloud home: the connected-apps service is switched off (OMB_COMPOSIO_BROKER)");
+ return;
+ }
const configured = process.env.OMB_COMPOSIO_BROKER_URL;
const brokerUrl = cloudConnectedAppsBrokerUrl();
if (!brokerUrl) {
if (configured?.trim()) console.warn("cloud home: connected-apps service URL rejected: HTTPS or a loopback HTTP URL is required");
return;
}
- cloudHome = startCloudConnectedApps({ dataDir: input.dataDir, brokerUrl, apply: input.apply, cloudGrant: input.cloudGrant, log: (line) => console.log(`cloud home: ${line}`) });
+ cloudHome = startCloudConnectedApps({ dataDir: input.dataDir, brokerUrl, apply: input.apply, cloudGrant: input.cloudGrant, ownKey: input.ownKey, log: (line) => console.log(`cloud home: ${line}`) });
}
export function stopCloudHomeConnectedApps(): void {
diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.ts
index 204e29210f..ce3bdbe3b7 100644
--- a/server/cloud-home-start.ts
+++ b/server/cloud-home-start.ts
@@ -37,7 +37,7 @@ const SERVER_ENV_NAMES = new Set([
"AGENT_BROWSER_EXECUTABLE_PATH", "OMB_STATIC_DIR", "OMB_DATA_DIR", "OMB_DUCKDB_DIR",
"OMB_CLOUD_ROLE", "OMB_CLOUD_MACHINE_ID", "OMB_CLOUD_ADMIN_URL", "OMB_CLOUD_IMAGE", "OMB_PUBLIC_URL", "OMB_WEBHOOK_PUBLIC_URL",
"OMB_CLOUD_TEAM_ID", "OMB_CLOUD_TEAM_NAME", "OMB_CLOUD_BOAT_URL", "OMB_CLOUD_VOICE_URL", "OMB_CLOUD_DECIDER_URL", "OMB_CLOUD_AI_URL", "OMB_CLOUD_X_URL", "OMB_TTS_DEFAULT_VOICE",
- "OMB_COMPOSIO_BROKER_URL",
+ "OMB_COMPOSIO_BROKER_URL", "OMB_COMPOSIO_BROKER",
// The addresses a home answered at before it moved to another provider, which still forward to it.
"OMB_CLOUD_LEGACY_ORIGINS",
// The bot box switch (server/bot-box/detect.ts): the Admin may turn a home's box off for support.
diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.ts
index 3015d2f127..4499e15361 100644
--- a/server/cloud-home.test.ts
+++ b/server/cloud-home.test.ts
@@ -505,14 +505,14 @@ it("gives the server only an allow-listed environment: a secret added later, a t
const config = cloudHomeConfiguration(contract())!;
const env = { ...contract(), PATH: "/usr/bin", LANG: "C.UTF-8", LC_ALL: "C.UTF-8", NODE_ENV: "production", OMB_STATIC_DIR: "/app/dist",
OMB_CLOUD_BOAT_URL: "https://cloud.example.test/boat", OMB_TTS_DEFAULT_VOICE: "alloy", OMB_CLOUD_AI_URL: "https://cloud.example.test/api/cloud/services/ai",
- OMB_COMPOSIO_BROKER_URL: "https://broker.example.test", OMB_COMPOSIO_BROKER_TOKEN: "b".repeat(64),
+ OMB_COMPOSIO_BROKER_URL: "https://broker.example.test", OMB_COMPOSIO_BROKER_TOKEN: "b".repeat(64), OMB_COMPOSIO_BROKER: "off",
OMB_CLOUD_FUTURE_SECRET: "later", OMB_TEST_CLOUD_LEFT_BEHIND_KEY: "k".repeat(43), FLY_API_TOKEN: "fly", SOME_TOKEN: "t", HOME: "/root" };
const { server, dropped } = cloudHomeChildEnvironments(config, env, "/data");
expect(server).toMatchObject({ PATH: "/usr/bin", LANG: "C.UTF-8", LC_ALL: "C.UTF-8", NODE_ENV: "production", OMB_STATIC_DIR: "/app/dist",
OMB_CLOUD_ROLE: "home", OMB_CLOUD_MACHINE_ID: machineId, OMB_CLOUD_ADMIN_URL: "https://cloud.example.test",
OMB_CLOUD_BOAT_URL: "https://cloud.example.test/boat", OMB_TTS_DEFAULT_VOICE: "alloy", OMB_CLOUD_AI_URL: "https://cloud.example.test/api/cloud/services/ai", HOME: "/data",
// A staging Cloud may name its connected-apps service; the Cloud registers its own token, never one from outside.
- OMB_COMPOSIO_BROKER_URL: "https://broker.example.test" });
+ OMB_COMPOSIO_BROKER_URL: "https://broker.example.test", OMB_COMPOSIO_BROKER: "off" });
for (const name of ["OMB_CLOUD_FUTURE_SECRET", "OMB_TEST_CLOUD_LEFT_BEHIND_KEY", "FLY_API_TOKEN", "SOME_TOKEN", "OMB_COMPOSIO_BROKER_TOKEN"]) {
expect(server).not.toHaveProperty(name);
expect(dropped).toContain(name);
diff --git a/server/composio-broker-access.ts b/server/composio-broker-access.ts
index b741edb139..1fd827a5ba 100644
--- a/server/composio-broker-access.ts
+++ b/server/composio-broker-access.ts
@@ -3,6 +3,10 @@
// them from the environment). `composio.ts` re-exports these.
import { z } from "zod";
+import { managedComposioBrokerOff } from "../electron/managed-composio.mjs";
+
+export { managedComposioBrokerOff };
+
let managedBrokerAccess: { url: string; token: string } | null | undefined;
const managedBrokerMessageSchema = z.record(z.string(), z.unknown());
@@ -44,6 +48,7 @@ export function setManagedBrokerAccess(access: unknown): void {
export type BrokerAccess = { url: string; token: string }; // `as` below: a Team Cloud member's own installation, never a project key
export function brokerAccess(): BrokerAccess | null {
+ if (managedComposioBrokerOff()) return null;
if (managedBrokerAccess !== undefined) return managedBrokerAccess;
const url = process.env.OMB_COMPOSIO_BROKER_URL?.trim();
const token = process.env.OMB_COMPOSIO_BROKER_TOKEN?.trim();
diff --git a/server/composio.ts b/server/composio.ts
index b08e2f0752..b194b9457d 100644
--- a/server/composio.ts
+++ b/server/composio.ts
@@ -33,7 +33,7 @@ import {
} from "./connector-advertisement.ts";
import { connectedAppGrantSlugs, serviceSlugFor, serviceSlugForCandidates } from "./connector-verdict.ts";
import { parseMcpResponse, withToolsListFallback } from "./connector-tools-list.ts";
-import { brokerAccess, type BrokerAccess } from "./composio-broker-access.ts";
+import { brokerAccess, managedComposioBrokerOff, type BrokerAccess } from "./composio-broker-access.ts";
export { applyManagedBrokerMessage, brokerAccess, setManagedBrokerAccess, type BrokerAccess } from "./composio-broker-access.ts";
export { prepareProjectSession, trustedSessionMcpUrl } from "./composio-session.ts";
@@ -165,7 +165,7 @@ export function connectorSetup(
managedHost: boolean = process.env.OMB_DESKTOP_PARENT === "1",
): ConnectorSetup {
if (configured(cfg)) return "ready";
- return managedHost ? "service-unavailable" : "needs-setup";
+ return managedHost && !managedComposioBrokerOff() ? "service-unavailable" : "needs-setup";
}
async function brokerRequest(path: string, init?: RequestInit, broker = brokerAccess()): Promise<Response> {
diff --git a/server/index.ts b/server/index.ts
index 7be7f9289b..d0723dcff7 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -15436,7 +15436,7 @@ if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATA
server.listen(PORT, listenHost(server), async () => {
companyRuntimeReady(); cloudHealth?.speed.ready();
console.log(`openmausbot server on http://127.0.0.1:${PORT}`);
- personWaits.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); startCloudTeamRoster({ cloudHome: CLOUD_HOME, 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() }); } });
+ personWaits.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); startCloudTeamRoster({ cloudHome: CLOUD_HOME, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, ownKey: () => composio.connectionMode(cfg) === "self-hosted", apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });
void afterFirstEngineRead().then(() => { if (builtInBrowserEnabled(cfg)) chromeLauncher.start(); });
followupsReady = true; engineUpdates.start();
drainQueuedSends();
diff --git a/shared/app-triggers.ts b/shared/app-triggers.ts
index 42cf1dfb6f..edbc8273f9 100644
--- a/shared/app-triggers.ts
+++ b/shared/app-triggers.ts
@@ -79,9 +79,9 @@ export interface AppEventAttempt {
}
export interface AppTriggerService {
- /** "self-hosted": this server uses its own Composio key, which app events do not support. */
+ /** "self-hosted": this server uses its own Composio key, which app events do not support. "off": OMB_COMPOSIO_BROKER=off. */
available: boolean;
- reason?: "self-hosted" | "unavailable";
+ reason?: "self-hosted" | "unavailable" | "off";
plan?: "desktop" | "cloud";
eventsPerDay?: number;
eventsToday?: number;