Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(composio): per-end-user session with the credential its MCP endpoint needs (#142)

Abdurrahman Fakhrulb70a08ef8682
diff --git a/app/api/v1/integrations/composio/session/route.test.ts b/app/api/v1/integrations/composio/session/route.test.ts
new file mode 100644
index 00000000..b49f4d65
--- /dev/null
+++ b/app/api/v1/integrations/composio/session/route.test.ts
@@ -0,0 +1,115 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { NextRequest } from "next/server";
+
+const mocks = { session: vi.fn(), limited: vi.fn(() => false), audit: vi.fn() };
+const SESSION_ID = "trs_route_session";
+const MCP_URL = `https://backend.composio.dev/tool_router/v3/${SESSION_ID}/mcp`;
+vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: mocks.session }));
+vi.mock("@/lib/host/limits-api", () => ({ rateLimited: mocks.limited }));
+vi.mock("@/lib/host/audit-api", () => ({ audit: mocks.audit }));
+
+let root = "", route: typeof import("./route");
+const owner = { role: "owner", session: { device_id: "device-1" } };
+const request = (body?: unknown) => new NextRequest("http://localhost/api/v1/integrations/composio/session", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+});
+
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-composio-route-"));
+ const state = {
+ version: 2, instanceId: "instance-1", defaultUser: "lara",
+ users: { lara: { id: "lara", uid: "uid-1", label: "Lara", defaults: { composio: "project" }, connections: { composio: { project: { id: "project", uid: "conn-1", label: "Project", provider: "composio", source: "direct", authMethod: "project", scope: "account", revision: 1, values: { apiKey: "ak_project_synthetic" }, createdAt: 0, updatedAt: 0 } } } } },
+ bindings: [],
+ };
+ await fs.writeFile(path.join(root, "infra.json"), JSON.stringify(state), { mode: 0o600 });
+ vi.stubEnv("OS_INFRA_STORE", path.join(root, "infra.json"));
+ vi.resetModules();
+ mocks.session.mockResolvedValue(owner);
+ mocks.limited.mockReturnValue(false);
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
+ session_id: SESSION_ID, mcp: { type: "http", url: MCP_URL, headers: { "x-api-key": "ak_returned_credential_value" } },
+ }), { status: 201 })));
+ route = await import("./route");
+});
+afterEach(async () => {
+ vi.unstubAllEnvs(); vi.unstubAllGlobals(); mocks.session.mockReset(); mocks.limited.mockReset(); await fs.rm(root, { recursive: true, force: true }); vi.resetModules();
+});
+
+describe("POST /api/v1/integrations/composio/session", () => {
+ it("returns the MCP URL and never the session headers", async () => {
+ const response = await route.POST(request({}));
+ expect(response.status).toBe(200);
+ const body = await response.json();
+ expect(body).toEqual({ mcpUrl: MCP_URL });
+ expect(JSON.stringify(body)).not.toContain("ak_returned_credential_value");
+ expect(JSON.stringify(body)).not.toContain("ak_project_synthetic");
+ expect(response.headers.get("cache-control")).toBe("no-store, private");
+ });
+
+ it("refuses a non-owner session", async () => {
+ mocks.session.mockResolvedValue({ ...owner, role: "operator" });
+ expect((await route.POST(request({}))).status).toBe(403);
+ mocks.session.mockResolvedValue(null);
+ expect((await route.POST(request({}))).status).toBe(403);
+ });
+
+ it("refuses to take a userId from the body", async () => {
+ const response = await route.POST(request({ user: "sams" }));
+ expect(response.status).toBe(400);
+ expect((await response.json()).error).toBe("invalid_session_fields");
+ });
+
+ it("is rate limited", async () => {
+ mocks.limited.mockReturnValue(true);
+ const response = await route.POST(request({}));
+ expect(response.status).toBe(429);
+ expect(mocks.limited).toHaveBeenCalledWith("composio.session:device-1", 10, 60_000);
+ });
+
+ it("reuses the stored session on a second call", async () => {
+ await route.POST(request({}));
+ await route.POST(request({}));
+ expect(vi.mocked(fetch)).toHaveBeenCalledTimes(1);
+ });
+
+ it("never leaks the composed credential when upstream returns no headers", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ session_id: SESSION_ID, mcp: { type: "http", url: MCP_URL } }), { status: 201 })));
+ const response = await route.POST(request({}));
+ expect(response.status).toBe(200);
+ const text = JSON.stringify(await response.json());
+ expect(text).toBe(JSON.stringify({ mcpUrl: MCP_URL }));
+ expect(text).not.toContain("ak_project_synthetic");
+ expect(text).not.toContain("x-api-key");
+ });
+
+ it("does not expose the credential when upstream fails", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ error: { message: "key ak_project_synthetic rejected", slug: "APIKey_InvalidAPIKey" } }), { status: 401 })));
+ const response = await route.POST(request({}));
+ expect(response.status).toBe(401);
+ const text = JSON.stringify(await response.json());
+ expect(text).not.toContain("ak_project_synthetic");
+ });
+});
+
+describe("GET /api/v1/integrations/composio/session", () => {
+ it("reports only the key kind for the form", async () => {
+ const response = await route.GET();
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ keyKind: "project" });
+ });
+
+ it("reports a Connect key as connect, so the UI offers Project MCP instead", async () => {
+ await fs.writeFile(path.join(root, "infra.json"), JSON.stringify({
+ version: 2, instanceId: "instance-1", defaultUser: "lara",
+ users: { lara: { id: "lara", uid: "uid-1", label: "Lara", defaults: { composio: "c" }, connections: { composio: { c: { id: "c", uid: "conn-2", label: "Connect", provider: "composio", source: "direct", authMethod: "project", scope: "account", revision: 1, values: { apiKey: "ck_consumer_key" }, createdAt: 0, updatedAt: 0 } } } } },
+ bindings: [],
+ }), { mode: 0o600 });
+ expect(await (await route.GET()).json()).toEqual({ keyKind: "connect" });
+ });
+});
diff --git a/app/api/v1/integrations/composio/session/route.ts b/app/api/v1/integrations/composio/session/route.ts
new file mode 100644
index 00000000..c2429151
--- /dev/null
+++ b/app/api/v1/integrations/composio/session/route.ts
@@ -0,0 +1,61 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getSessionContext } from "@/lib/auth/require-session";
+import { rateLimited } from "@/lib/host/limits-api";
+import { audit } from "@/lib/host/audit-api";
+import { readRequestJson, RequestBodyError } from "@/lib/security/request-body";
+import { IntegrationError } from "@/lib/infra/identity";
+import { currentIntegrationSelection } from "@/lib/infra/connection-service";
+import { readInfraProvider } from "@/lib/infra/store";
+import { composioKeyKind } from "@/lib/infra/composio";
+import { composioSessionForUser } from "@/lib/infra/composio-session";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+const headers = { "Cache-Control": "no-store, private", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff" };
+
+/**
+ * Key kind only, never a key: the browser needs to know whether to offer the agent
+ * session action (Platform key) or the Project MCP guidance (ck_ Connect key).
+ */
+export async function GET() {
+ const context = await getSessionContext();
+ if (context?.role !== "owner") return NextResponse.json({ error: "owner_required" }, { status: 403, headers });
+ try {
+ return NextResponse.json({ keyKind: composioKeyKind(await readInfraProvider("composio")) }, { headers });
+ } catch {
+ return NextResponse.json({ keyKind: null }, { headers });
+ }
+}
+
+/**
+ * POST creates-or-reuses the Composio session for the CURRENT credential owner.
+ * The owner comes from the server-side selection (session context / folder binding),
+ * never from the body. Response carries only the MCP URL and expiry: `mcp.headers`
+ * is the session credential and must stay server-side.
+ */
+export async function POST(req: NextRequest) {
+ const context = await getSessionContext();
+ if (context?.role !== "owner") return NextResponse.json({ error: "owner_required" }, { status: 403, headers });
+ if (rateLimited(`composio.session:${context.session.device_id ?? "unknown"}`, 10, 60_000)) {
+ return NextResponse.json({ error: "rate_limited" }, { status: 429, headers });
+ }
+ try {
+ // Body is optional and may only ask for a refresh; identity and key material stay server-owned.
+ const input = req.body && req.headers.get("content-length") !== "0" ? await readRequestJson(req, 4096) : {};
+ if (Object.keys(input).some((key) => key !== "refresh")) throw new IntegrationError("invalid_session_fields", 400);
+ const values = await readInfraProvider("composio");
+ const session = await composioSessionForUser({
+ values,
+ user: currentIntegrationSelection().user,
+ refresh: input.refresh === true,
+ });
+ void audit({ action: "infra.write", actor: context.session.device_id, target: "composio", ok: true, detail: `composio.session.${session.reused ? "reuse" : "create"}` });
+ return NextResponse.json({
+ mcpUrl: session.mcpUrl,
+ ...(session.expiresAt !== undefined ? { expiresAt: session.expiresAt } : {}),
+ }, { headers });
+ } catch (error) {
+ const safe = error instanceof IntegrationError || error instanceof RequestBodyError ? error : new IntegrationError("composio_session_failed", 502);
+ return NextResponse.json({ error: safe.message }, { status: safe.status, headers });
+ }
+}
diff --git a/bin/mso.test.ts b/bin/mso.test.ts
index 7611ee58..e27dbabb 100644
--- a/bin/mso.test.ts
+++ b/bin/mso.test.ts
@@ -122,6 +122,8 @@ describe("bin/mso", () => {
// `mso oauth <provider> start|poll` covers it.
const browserOnly = [
"POST /api/v1/integrations/transfer", // File/passphrase input belongs to the authenticated browser, opened by mso integrations transfer.
+ // Per-owner Composio session (both methods); its MCP headers are the credential.
+ "/api/v1/integrations/composio/session",
// Credential input is delegated to a write-only browser capability; the
// named CLI setup verb opens that form without placing keys in shell/tool JSON.
"POST /api/integrations/setup",
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index cd548e4b..943bd7f3 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -4924,3 +4924,7 @@ Screenshot evidence previously lived in unrelated scratch directories or only in
- The browser route and embedded MCP Page now share a responsive service rail, real connection-readiness summary, compact account cards, and contextual setup/actions. Setup guides and maintenance controls use progressive disclosure; account switching remains explicit.
- Integration snapshots no longer repeat the complete provider catalog, which is already embedded in the shared manager. The explicit catalog query remains available; compact snapshots prevent bounded MCP responses from truncating the Page.
- Validation: 26 browser assertions at 320/390/768/1440/1920 px in light/dark themes, account isolation, service search, setup focus, auto identifiers and Verify feedback; full verify passes.
+
+### 2026-10-22 — Composio session MCP credential
+- `POST /api/v3.1/tool_router/session` has no `mcp` request field and its 201 response carries `mcp.url` without headers, so a stored session previously had no credential and could never be called. `mcpHeaders` is now the exact header `composioAuthHeader` returned for the credential that authenticated that same create call (`x-api-key` project, `x-user-api-key` user, `x-org-api-key` org), matching `docs/sessions-via-mcp`. A future response `mcp.headers` still wins verbatim.
+- The session MCP URL host is validated against the existing Composio redirect allowlist plus `app.composio.dev` (the spec example host); any other host fails closed with `invalid_composio_mcp_host`. Header values stay server-side: the route still returns only `mcpUrl`.
diff --git a/frontend/slices/integrations/app.tsx b/frontend/slices/integrations/app.tsx
index 436f6a81..2d248730 100644
--- a/frontend/slices/integrations/app.tsx
+++ b/frontend/slices/integrations/app.tsx
@@ -3,6 +3,7 @@
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { syncIntegrationFrameTokens } from "./frame-theme";
+import { ComposioSessionPanel } from "./composio-session-panel";
/** Preserve transfer/setup deep links without putting private capabilities in React state. */
export function managerLocation(search: string, hash = "") {
@@ -46,6 +47,7 @@ export default function IntegrationsApp() {
</p>
{status === "error" && <Button variant="secondary" onClick={() => { setStatus("loading"); setRetry(n => n + 1); }}>Retry</Button>}
</div>}
+ <ComposioSessionPanel />
<iframe ref={frame} title="MSO native Integrations manager" className="min-h-0 w-full flex-1 border-0"
referrerPolicy="no-referrer" onLoad={() => { if (frame.current?.getAttribute("src")) { syncIntegrationFrameTokens(frame.current); setStatus("ready"); } }}
onError={() => setStatus("error")} />
diff --git a/frontend/slices/integrations/composio-session-panel.tsx b/frontend/slices/integrations/composio-session-panel.tsx
new file mode 100644
index 00000000..53bb3555
--- /dev/null
+++ b/frontend/slices/integrations/composio-session-panel.tsx
@@ -0,0 +1,81 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+
+const SESSION_PATH = "/api/v1/integrations/composio/session";
+type KeyKind = "organization" | "user" | "project" | "connect" | null;
+
+/**
+ * Composio agent session, shown for a Platform key only. The session credential
+ * (`mcp.headers`) never leaves the server: only the MCP URL is displayed, and it is
+ * the URL of the session belonging to this signed-in credential owner.
+ */
+export function ComposioSessionPanel() {
+ const [kind, setKind] = useState<KeyKind | undefined>(undefined);
+ const [mcpUrl, setMcpUrl] = useState("");
+ const [status, setStatus] = useState("");
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ let live = true;
+ fetch(SESSION_PATH, { headers: { accept: "application/json" }, cache: "no-store" })
+ .then(response => response.ok ? response.json() : { keyKind: null })
+ .then((body: { keyKind?: KeyKind }) => { if (live) setKind(body.keyKind ?? null); })
+ .catch(() => { if (live) setKind(null); });
+ return () => { live = false; };
+ }, []);
+
+ const create = useCallback(async (refresh: boolean) => {
+ setBusy(true);
+ setStatus("Creating the agent session…");
+ try {
+ const response = await fetch(SESSION_PATH, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(refresh ? { refresh: true } : {}),
+ });
+ const body = await response.json().catch(() => ({}));
+ if (!response.ok || typeof body.mcpUrl !== "string") {
+ setStatus(String(body.error ?? "The session could not be created."));
+ return;
+ }
+ setMcpUrl(body.mcpUrl);
+ setStatus(refresh ? "Fresh agent session created." : "Agent session ready.");
+ } catch {
+ setStatus("The session could not be created.");
+ } finally { setBusy(false); }
+ }, []);
+
+ if (kind === undefined) return null;
+ if (kind === "connect") {
+ return (
+ <section className="border-b p-3" aria-label="Composio Connect key">
+ <p className="text-sm text-muted-foreground">
+ This is a Composio Connect consumer key (ck_…). It belongs to Project MCP with the endpoint
+ https://connect.composio.dev/mcp, and cannot create a per-user agent session.
+ </p>
+ </section>
+ );
+ }
+ if (kind === null) return null;
+
+ return (
+ <section className="border-b p-3" aria-label="Composio agent session">
+ <div className="flex flex-wrap items-center gap-3">
+ <Button variant="secondary" disabled={busy} onClick={() => void create(false)}>Create agent session</Button>
+ {mcpUrl && <Button variant="ghost" disabled={busy} onClick={() => void create(true)}>Refresh session</Button>}
+ </div>
+ <p className="mt-2 text-sm text-muted-foreground">
+ Tools run as this credential owner. The session credential stays on the MSO server.
+ </p>
+ {mcpUrl && (
+ <label className="mt-2 block text-sm">
+ Hosted MCP endpoint
+ <input readOnly value={mcpUrl} className="mt-1 w-full rounded border bg-background p-2 font-mono text-xs" onFocus={event => event.currentTarget.select()} />
+ </label>
+ )}
+ {status && <p role="status" className="mt-2 text-sm text-muted-foreground">{status}</p>}
+ </section>
+ );
+}
diff --git a/lib/infra/composio-session.test.ts b/lib/infra/composio-session.test.ts
new file mode 100644
index 00000000..55edb31f
--- /dev/null
+++ b/lib/infra/composio-session.test.ts
@@ -0,0 +1,235 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { randomUUID } from "node:crypto";
+import { COMPOSIO_CONNECT_KEY_MESSAGE } from "./composio";
+
+type Mod = typeof import("./composio-session");
+let root = "", storeFile = "", mod: Mod;
+const SESSION_ID = "trs_1a2b3c4d5e6f";
+const MCP_URL = "https://backend.composio.dev/tool_router/v3/trs_1a2b3c4d5e6f/mcp";
+
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-composio-session-"));
+ storeFile = path.join(path.dirname(path.join(root, "infra.json")), "composio-sessions.json");
+ vi.stubEnv("OS_INFRA_STORE", path.join(root, "infra.json"));
+ vi.resetModules();
+ mod = await import("./composio-session");
+});
+afterEach(async () => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ await fs.rm(root, { recursive: true, force: true });
+ vi.resetModules();
+});
+
+const okResponse = (overrides: Record<string, unknown> = {}, mcpExtra: Record<string, unknown> = {}) =>
+ new Response(JSON.stringify({
+ session_id: SESSION_ID,
+ mcp: { type: "http", url: MCP_URL, ...mcpExtra },
+ tool_router_tools: [],
+ config: { user_id: "mso:test" },
+ config_version: 1,
+ ...overrides,
+ }), { status: 201, headers: { "content-type": "application/json" } });
+
+describe("composio session creation", () => {
+ it("refuses a ck_ Connect key with the existing Project MCP message and makes no request", async () => {
+ const fetchMock = vi.fn(async () => okResponse());
+ vi.stubGlobal("fetch", fetchMock);
+ await expect(mod.createComposioSession({ values: { apiKey: "ck_consumer_key" }, userId: "mso:test" }))
+ .rejects.toThrow(COMPOSIO_CONNECT_KEY_MESSAGE);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("composes the project-key credential the SDK exports when upstream returns no headers", async () => {
+ let captured = "";
+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
+ captured = new Headers(init?.headers).get("x-api-key") ?? "";
+ expect(JSON.parse(String(init?.body))).toEqual({ user_id: "mso:instance-1:uid-1" });
+ return okResponse({}, { headers: {} });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const session = await mod.createComposioSession({ values: { apiKey: "ak_project_synthetic" }, userId: "mso:instance-1:uid-1" });
+ expect(session).toEqual({ sessionId: SESSION_ID, mcpUrl: MCP_URL, mcpHeaders: { "x-api-key": "ak_project_synthetic" } });
+ expect(String(fetchMock.mock.calls[0]?.[0])).toBe("https://backend.composio.dev/api/v3.1/tool_router/session");
+ // Same-origin proof: the stored value is the exact header that authenticated the create call.
+ expect(session.mcpHeaders["x-api-key"]).toBe(captured);
+ expect(captured).toBe("ak_project_synthetic");
+ });
+
+ it("composes x-user-api-key for a uak_ user key and x-org-api-key for an org key", async () => {
+ let captured = new Headers();
+ vi.stubGlobal("fetch", vi.fn(async (_i: RequestInfo | URL, init?: RequestInit) => { captured = new Headers(init?.headers); return okResponse(); }));
+ const user = await mod.createComposioSession({ values: { apiKey: "uak_user_synthetic" }, userId: "mso:u" });
+ expect(user.mcpHeaders).toEqual({ "x-user-api-key": "uak_user_synthetic" });
+ expect(user.mcpHeaders["x-user-api-key"]).toBe(captured.get("x-user-api-key"));
+ expect(captured.get("x-api-key")).toBeNull();
+
+ const org = await mod.createComposioSession({ values: { apiKey: "ak_project_synthetic", orgApiKey: "ak_org_synthetic" }, userId: "mso:u" });
+ expect(org.mcpHeaders).toEqual({ "x-org-api-key": "ak_org_synthetic" });
+ expect(org.mcpHeaders["x-org-api-key"]).toBe(captured.get("x-org-api-key"));
+ expect(captured.get("x-api-key")).toBeNull();
+ });
+
+ it("prefers returned mcp.headers over the composed credential", async () => {
+ const returned = { "x-api-key": "ak_returned_synthetic", "x-project-id": "proj_123" };
+ vi.stubGlobal("fetch", vi.fn(async () => okResponse({}, { headers: returned })));
+ const session = await mod.createComposioSession({ values: { apiKey: "ak_project_synthetic" }, userId: "mso:u" });
+ expect(session.mcpHeaders).toEqual(returned);
+ expect(JSON.stringify(session.mcpHeaders)).not.toContain("ak_project_synthetic");
+ });
+
+ it("accepts the app.composio.dev host from the spec example and rejects any other host", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => okResponse({}, { url: `https://app.composio.dev/tool_router/v3/${SESSION_ID}/mcp` })));
+ const session = await mod.createComposioSession({ values: { apiKey: "ak_project_synthetic" }, userId: "mso:u" });
+ expect(session.mcpUrl).toBe(`https://app.composio.dev/tool_router/v3/${SESSION_ID}/mcp`);
+
+ vi.stubGlobal("fetch", vi.fn(async () => okResponse({}, { url: "https://evil.example.com/tool_router/v3/x/mcp" })));
+ await expect(mod.createComposioSession({ values: { apiKey: "ak_project_synthetic" }, userId: "mso:u" }))
+ .rejects.toThrow("invalid_composio_mcp_host");
+ });
+
+ it("redacts the credential an upstream error body echoes", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(
+ JSON.stringify({ error: { message: "bad key ak_project_synthetic leaked", slug: "APIKey_InvalidAPIKey" } }),
+ { status: 401 },
+ )));
+ const error = await mod.createComposioSession({ values: { apiKey: "ak_project_synthetic" }, userId: "mso:u" }).catch((e: Error) => e);
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).not.toContain("ak_project_synthetic");
+ expect((error as Error).message).toContain("APIKey_InvalidAPIKey");
+ });
+
+ it("rejects a non-HTTPS MCP URL", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => okResponse({}, { url: "http://backend.composio.dev/tool_router/v3/x/mcp" })));
+ await expect(mod.createComposioSession({ values: { apiKey: "ak_project_synthetic" }, userId: "mso:u" }))
+ .rejects.toThrow("invalid_composio_mcp_endpoint");
+ });
+
+ it("rejects a session id or header set that is not what the API documents", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => okResponse({ session_id: "../../etc" })));
+ await expect(mod.createComposioSession({ values: { apiKey: "ak_project_synthetic" }, userId: "mso:u" }))
+ .rejects.toThrow("invalid_composio_session_response");
+ vi.stubGlobal("fetch", vi.fn(async () => okResponse({}, { headers: { "x-api-key": "v", "bad header": "v" } })));
+ await expect(mod.createComposioSession({ values: { apiKey: "ak_project_synthetic" }, userId: "mso:u" }))
+ .rejects.toThrow("invalid_composio_session_headers");
+ });
+});
+
+describe("composio session persistence", () => {
+ it("writes 0600 in a 0700 directory and keeps the header value readable only by the owner", async () => {
+ const state = { version: 2, instanceId: "instance-1", defaultUser: "lara", users: { lara: { id: "lara", uid: "uid-1", label: "Lara", defaults: {}, connections: {} } }, bindings: [] };
+ await fs.mkdir(path.dirname(path.join(root, "infra.json")), { recursive: true });
+ await fs.writeFile(path.join(root, "infra.json"), JSON.stringify(state), { mode: 0o600 });
+ const fetchMock = vi.fn(async (_i: RequestInfo | URL, init?: RequestInit) => {
+ expect(JSON.parse(String(init?.body)).user_id).toBe("mso:instance-1:uid-1");
+ return okResponse({}, { headers: { "x-api-key": "ak_returned_credential_value" } });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ await mod.composioSessionForUser({ values: { apiKey: "ak_project_synthetic" }, user: "lara" });
+
+ // One handle: the mode we assert and the bytes we read are the same object.
+ const handle = await fs.open(storeFile, "r");
+ try {
+ const file = await handle.stat();
+ expect(file.mode & 0o777).toBe(0o600);
+ expect(await handle.readFile("utf8")).toContain("ak_returned_credential_value");
+ } finally {
+ await handle.close();
+ }
+ const dir = await fs.stat(path.dirname(storeFile));
+ expect(dir.mode & 0o777).toBe(0o700);
+
+ // A second MSO user cannot read it: any permissive mode is refused when reading.
+ await fs.chmod(storeFile, 0o644);
+ await expect(mod.readComposioSessions()).rejects.toThrow("unsafe_composio_session_store");
+ await fs.chmod(storeFile, 0o600);
+ await expect(mod.readComposioSessions()).resolves.toMatchObject({ version: 1 });
+ });
+
+ it("reuses a stored session instead of creating a second one", async () => {
+ const state = { version: 2, instanceId: "instance-1", defaultUser: "lara", users: { lara: { id: "lara", uid: "uid-1", label: "Lara", defaults: {}, connections: {} } }, bindings: [] };
+ await fs.mkdir(path.dirname(path.join(root, "infra.json")), { recursive: true });
+ await fs.writeFile(path.join(root, "infra.json"), JSON.stringify(state), { mode: 0o600 });
+ const fetchMock = vi.fn(async () => okResponse({}, { headers: { "x-api-key": "ak_returned_credential_value" } }));
+ vi.stubGlobal("fetch", fetchMock);
+ const first = await mod.composioSessionForUser({ values: { apiKey: "ak_project_synthetic" }, user: "lara" });
+ const second = await mod.composioSessionForUser({ values: { apiKey: "ak_project_synthetic" }, user: "lara" });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(first.reused).toBe(false);
+ expect(second.reused).toBe(true);
+ expect(second.sessionId).toBe(first.sessionId);
+ expect(second.mcpHeaders).toEqual({ "x-api-key": "ak_returned_credential_value" });
+ });
+
+ it("creates a new session when the caller explicitly refreshes", async () => {
+ const state = { version: 2, instanceId: "instance-1", defaultUser: "lara", users: { lara: { id: "lara", uid: "uid-1", label: "Lara", defaults: {}, connections: {} } }, bindings: [] };
+ await fs.mkdir(path.dirname(path.join(root, "infra.json")), { recursive: true });
+ await fs.writeFile(path.join(root, "infra.json"), JSON.stringify(state), { mode: 0o600 });
+ const fetchMock = vi.fn(async () => okResponse({}, { headers: {} }));
+ vi.stubGlobal("fetch", fetchMock);
+ await mod.composioSessionForUser({ values: { apiKey: "ak_project_synthetic" }, user: "lara" });
+ const refreshed = await mod.composioSessionForUser({ values: { apiKey: "ak_project_synthetic" }, user: "lara", refresh: true });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(refreshed.reused).toBe(false);
+ });
+
+ it("never returns a stored session belonging to another user", async () => {
+ const state = {
+ version: 2, instanceId: "instance-1", defaultUser: "lara",
+ users: {
+ lara: { id: "lara", uid: "uid-1", label: "Lara", defaults: {}, connections: {} },
+ sams: { id: "sams", uid: "uid-2", label: "Sams", defaults: {}, connections: {} },
+ },
+ bindings: [],
+ };
+ await fs.mkdir(path.dirname(path.join(root, "infra.json")), { recursive: true });
+ await fs.writeFile(path.join(root, "infra.json"), JSON.stringify(state), { mode: 0o600 });
+ const fetchMock = vi.fn(async (_i: RequestInfo | URL, init?: RequestInit) => {
+ expect(JSON.parse(String(init?.body)).user_id).toBe("mso:instance-1:uid-1");
+ return okResponse({}, { headers: {} });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ await mod.composioSessionForUser({ values: { apiKey: "ak_project_synthetic" }, user: "lara" });
+
+ // Sams must not see Lara's row, and asking for it creates Sams' own session.
+ expect(await mod.readComposioSession("instance-1", "uid-2")).toBeNull();
+ const fetchSams = vi.fn(async (_i: RequestInfo | URL, init?: RequestInit) => {
+ expect(JSON.parse(String(init?.body)).user_id).toBe("mso:instance-1:uid-2");
+ return new Response(JSON.stringify({ session_id: "trs_sams_session", mcp: { type: "http", url: "https://backend.composio.dev/tool_router/v3/trs_sams_session/mcp" } }), { status: 201 });
+ });
+ vi.stubGlobal("fetch", fetchSams);
+ const sams = await mod.composioSessionForUser({ values: { apiKey: "ak_project_synthetic" }, user: "sams" });
+ expect(sams.sessionId).toBe("trs_sams_session");
+ expect(sams.reused).toBe(false);
+ });
+
+ it("ignores an expired stored session", async () => {
+ const key = "instance-1:uid-1";
+ await fs.mkdir(path.dirname(storeFile), { recursive: true, mode: 0o700 });
+ await fs.writeFile(storeFile, JSON.stringify({
+ version: 1,
+ sessions: {
+ [key]: { sessionId: SESSION_ID, mcpUrl: MCP_URL, mcpHeaders: {}, instanceId: "instance-1", userUid: "uid-1", createdAt: 1, expiresAt: Date.now() - 1 },
+ },
+ }), { mode: 0o600 });
+ expect(await mod.readComposioSession("instance-1", "uid-1")).toBeNull();
+ });
+
+ it("refuses to read a store that parses as an unknown format", async () => {
+ await fs.mkdir(path.dirname(storeFile), { recursive: true, mode: 0o700 });
+ await fs.writeFile(storeFile, JSON.stringify({ version: 9, sessions: {} }), { mode: 0o600 });
+ await expect(mod.readComposioSessions()).rejects.toThrow("invalid_composio_session_store");
+ });
+
+ it("keeps the store keyed by instance and owner uid, so the same uid in another instance is separate", async () => {
+ const row = { sessionId: randomUUID(), mcpUrl: MCP_URL, mcpHeaders: {}, instanceId: "instance-1", userUid: "uid-1", createdAt: Date.now() };
+ await fs.mkdir(path.dirname(storeFile), { recursive: true, mode: 0o700 });
+ await fs.writeFile(storeFile, JSON.stringify({ version: 1, sessions: { "instance-1:uid-1": row } }), { mode: 0o600 });
+ expect((await mod.readComposioSession("instance-1", "uid-1"))?.sessionId).toBe(row.sessionId);
+ expect(await mod.readComposioSession("instance-2", "uid-1")).toBeNull();
+ });
+});
diff --git a/lib/infra/composio-session.ts b/lib/infra/composio-session.ts
new file mode 100644
index 00000000..d2d439ff
--- /dev/null
+++ b/lib/infra/composio-session.ts
@@ -0,0 +1,269 @@
+import { constants, promises as fs } from "node:fs";
+import { randomUUID } from "node:crypto";
+import path from "node:path";
+import { pinSecurityStorePath } from "@/lib/security-store-path";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { normalizeMcpEndpoint } from "./mcp-policy";
+import { request, obj } from "./http";
+import { COMPOSIO_API_BASE, COMPOSIO_CONNECT_KEY_MESSAGE, composioAuthHeader } from "./composio";
+import { INFRA_STORE_PATH, readIntegrationState } from "./connection-storage";
+import { IntegrationError, resolveUser } from "./identity";
+import { currentIntegrationSelection } from "./connection-service";
+import type { InfraProviderValues } from "./types";
+
+/**
+ * Per-end-user Composio session and its hosted MCP endpoint.
+ *
+ * Verified against the live Platform API surface (`POST /api/v3.1/tool_router/session`
+ * in `backend.composio.dev/api/v3.1/openapi.json`, spec 3.1.0):
+ *
+ * - The REQUEST schema has no `mcp` field (props: user_id, toolkits, auth_configs,
+ * connected_accounts, instant, manage_connections, tools, tags, workbench,
+ * proxy_execute, multi_account, experimental, preload, hooks, search, execute).
+ * `mcp: true` in the SDKs is client-side sugar only.
+ * - The 201 RESPONSE carries `mcp: {type, url}` and no `headers` member.
+ *
+ * Therefore the MCP endpoint has no credential of its own to hand out: the client
+ * credential IS the session credential. `docs/sessions-via-mcp` says
+ * `session.mcp.headers` holds exactly "the credential the SDK used to create or load
+ * the session, and nothing else. No other default header and no ambient
+ * COMPOSIO_API_KEY is copied in", and maps it per key kind: project → `x-api-key`,
+ * user → `x-user-api-key`, org → `x-org-api-key`. That is byte-for-byte what
+ * `composioAuthHeader` returns for the credential that authenticated this very create
+ * call, so the composed header is derived from that one `auth` object - never from an
+ * environment variable, never re-resolved, never a different key. If a future API
+ * version does return `mcp.headers`, those win verbatim.
+ *
+ * `mcpHeaders` stays server-side: the HTTP route returns the URL only.
+ */
+const SESSION_URL = `${COMPOSIO_API_BASE}/tool_router/session`;
+/** Same allowlist as Composio redirect links, plus the host the spec example returns. */
+export const COMPOSIO_MCP_HOSTS = ["connect.composio.dev", "backend.composio.dev", "platform.composio.dev", "app.composio.dev"];
+const MAX_STORE_BYTES = 256 * 1024;
+const MAX_HEADERS = 32;
+const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}$/;
+const KEY_PART = /^[A-Za-z0-9:_.-]{1,200}$/;
+
+export type ComposioSession = {
+ sessionId: string;
+ mcpUrl: string;
+ /** The credential the SDK exports for this session URL: composed from the key that authenticated the create call. Server-side only. */
+ mcpHeaders: Record<string, string>;
+ expiresAt?: number;
+};
+
+export type ComposioSessionResolution = ComposioSession & { reused: boolean; user: string };
+
+type StoredSession = ComposioSession & { instanceId: string; userUid: string; createdAt: number };
+type Store = { version: 1; sessions: Record<string, StoredSession> };
+
+/** Owner-only, beside `infra-providers.json`: 0700 parent, 0600 file, O_NOFOLLOW, uid-checked. */
+export const composioSessionStorePath = () => path.join(path.dirname(INFRA_STORE_PATH), "composio-sessions.json");
+
+/** One helper for every message this module throws: an upstream body can echo a credential. */
+export function redactComposioMessage(message: string, secrets: (string | undefined)[]): string {
+ let out = message;
+ for (const secret of secrets) if (secret && secret.length >= 6) out = out.split(secret).join("[redacted]");
+ return out;
+}
+
+function connectKeyRefusal(): IntegrationError {
+ const error = new IntegrationError("composio_connect_key_wrong_provider", 409);
+ error.message = COMPOSIO_CONNECT_KEY_MESSAGE;
+ return error;
+}
+
+function headerMap(value: unknown): Record<string, string> {
+ const raw = obj(value);
+ const entries = Object.entries(raw);
+ if (entries.length > MAX_HEADERS) throw new IntegrationError("invalid_composio_session_headers", 502);
+ const headers: Record<string, string> = {};
+ for (const [name, entry] of entries) {
+ if (!HEADER_NAME.test(name) || typeof entry !== "string" || !entry || entry.length > 4096 || /[\r\n\0]/.test(entry)) {
+ throw new IntegrationError("invalid_composio_session_headers", 502);
+ }
+ headers[name] = entry;
+ }
+ return headers;
+}
+
+/** Fail closed on a session URL pointing anywhere the session could not live. */
+function composioMcpUrl(raw: string): string {
+ let href: string;
+ try { href = normalizeMcpEndpoint(raw); } catch { throw new IntegrationError("invalid_composio_mcp_endpoint", 502); }
+ if (!COMPOSIO_MCP_HOSTS.includes(new URL(href).hostname)) throw new IntegrationError("invalid_composio_mcp_host", 502);
+ return href;
+}
+
+/**
+ * POST a session for one end user. Server-side only: the caller's credential is sent
+ * in the same header `composioAuthHeader` already selects, and a ck_ key is refused
+ * before any request is made.
+ */
+export async function createComposioSession(input: {
+ values: InfraProviderValues;
+ userId: string;
+ toolkits?: string[];
+ authConfigs?: Record<string, string>;
+ fetchImpl?: (value: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
+}): Promise<ComposioSession> {
+ const secrets = [input.values.apiKey, input.values.orgApiKey];
+ if (!/^[\x20-\x7e]{1,200}$/.test(input.userId) || !input.userId.trim()) throw new IntegrationError("invalid_composio_user_id", 400);
+ // composioAuthHeader is the single key-detection path: it throws for a ck_ Connect
+ // key before any request, and the Platform API would answer that key with a
+ // misleading 401.
+ let auth;
+ try { auth = composioAuthHeader(input.values); }
+ catch { throw connectKeyRefusal(); }
+ if (!auth) throw new IntegrationError("composio_project_key_required", 409);
+
+ const body: Record<string, unknown> = { user_id: input.userId };
+ if (input.toolkits?.length) body.toolkits = { enable: input.toolkits };
+ if (input.authConfigs && Object.keys(input.authConfigs).length) body.auth_configs = input.authConfigs;
+
+ let response;
+ try {
+ response = await request(SESSION_URL, {
+ method: "POST",
+ headers: { ...auth.header, accept: "application/json", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }, undefined, input.fetchImpl);
+ } catch (error) {
+ throw new IntegrationError(redactComposioMessage(`composio_session_unreachable: ${(error as Error).message}`, secrets), 502);
+ }
+ if (!response.ok) {
+ const slug = String(obj(obj(response.body).error).slug ?? "");
+ const safe = /^[A-Za-z0-9_]{1,80}$/.test(slug) ? ` ${slug}` : "";
+ // The response body is not echoed: it can contain the credential the request carried.
+ throw new IntegrationError(redactComposioMessage(`composio_session_failed (${response.status})${safe}`, secrets), response.status === 401 || response.status === 403 ? 401 : 502);
+ }
+
+ const payload = obj(response.body);
+ const mcp = obj(payload.mcp);
+ const sessionId = typeof payload.session_id === "string" ? payload.session_id.trim() : "";
+ if (!/^[A-Za-z0-9_-]{1,200}$/.test(sessionId)) throw new IntegrationError("invalid_composio_session_response", 502);
+ const mcpUrl = composioMcpUrl(String(mcp.url ?? ""));
+ // Response wins; composed credential is the documented fallback.
+ let mcpHeaders: Record<string, string>;
+ try {
+ const returned = headerMap(mcp.headers);
+ mcpHeaders = Object.keys(returned).length ? returned : { ...auth.header };
+ } catch (error) { throw new IntegrationError(redactComposioMessage((error as Error).message, [...secrets, ...Object.values(obj(mcp.headers)) as string[]]), 502); }
+ return { sessionId, mcpUrl, mcpHeaders };
+}
+
+function parseStore(value: unknown): Store {
+ const raw = obj(value);
+ const bad = (): never => { throw new IntegrationError("invalid_composio_session_store"); };
+ if (raw.version !== 1 || !raw.sessions || typeof raw.sessions !== "object" || Array.isArray(raw.sessions)) bad();
+ const sessions: Record<string, StoredSession> = {};
+ for (const [key, entry] of Object.entries(raw.sessions as Record<string, unknown>)) {
+ const row = obj(entry);
+ const keyParts = key.split(":");
+ if (keyParts.length !== 2 || keyParts.some((part) => !KEY_PART.test(part))) bad();
+ const { sessionId, instanceId, userUid, createdAt, expiresAt, mcpUrl: rawUrl } = row;
+ const id = typeof sessionId === "string" && /^[A-Za-z0-9_-]{1,200}$/.test(sessionId) ? sessionId : bad();
+ const instance = typeof instanceId === "string" ? instanceId : bad();
+ const uid = typeof userUid === "string" ? userUid : bad();
+ const created = Number.isSafeInteger(createdAt) ? createdAt as number : bad();
+ let mcpUrl: string;
+ try {
+ mcpUrl = normalizeMcpEndpoint(String(rawUrl ?? ""));
+ if (!COMPOSIO_MCP_HOSTS.includes(new URL(mcpUrl).hostname)) return bad();
+ } catch { return bad(); }
+ sessions[key] = {
+ sessionId: id, mcpUrl, mcpHeaders: headerMap(row.mcpHeaders),
+ instanceId: instance, userUid: uid, createdAt: created,
+ ...(Number.isFinite(expiresAt) ? { expiresAt: Number(expiresAt) } : {}),
+ };
+ }
+ return { version: 1, sessions };
+}
+
+export async function readComposioSessions(): Promise<Store> {
+ const pinned = await pinSecurityStorePath(composioSessionStorePath());
+ let handle;
+ try {
+ handle = await fs.open(pinned.file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size < 1 || stat.size > MAX_STORE_BYTES || (stat.mode & 0o077) || stat.uid !== process.getuid?.()) throw new IntegrationError("unsafe_composio_session_store");
+ return parseStore(JSON.parse(await handle.readFile("utf8")));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { version: 1, sessions: {} };
+ if (error instanceof IntegrationError) throw error;
+ throw new IntegrationError("invalid_composio_session_store");
+ } finally { await handle?.close(); await pinned.directory.close(); }
+}
+
+async function writeComposioSessions(store: Store): Promise<void> {
+ const pinned = await pinSecurityStorePath(composioSessionStorePath());
+ const text = JSON.stringify(parseStore(store), null, 2) + "\n";
+ try {
+ if (Buffer.byteLength(text) > MAX_STORE_BYTES) throw new IntegrationError("composio_session_store_capacity", 409);
+ const temporary = `${pinned.file}.${randomUUID()}.tmp`;
+ try {
+ const handle = await fs.open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
+ try { await handle.writeFile(text); await handle.sync(); } finally { await handle.close(); }
+ await fs.rename(temporary, pinned.file);
+ } finally { await fs.unlink(temporary).catch(() => undefined); }
+ await pinned.directory.sync();
+ } finally { await pinned.directory.close(); }
+}
+
+const storeKey = (instanceId: string, userUid: string) => {
+ if (!KEY_PART.test(instanceId) || !KEY_PART.test(userUid) || instanceId.includes(":") || userUid.includes(":")) throw new IntegrationError("invalid_composio_session_key");
+ return `${instanceId}:${userUid}`;
+};
+
+/** Never returns another MSO user's session: the key is (instance, credential-owner uid). */
+export async function readComposioSession(instanceId: string, userUid: string): Promise<StoredSession | null> {
+ const key = storeKey(instanceId, userUid);
+ const row = (await readComposioSessions()).sessions[key];
+ if (!row || row.instanceId !== instanceId || row.userUid !== userUid) return null;
+ if (row.expiresAt !== undefined && row.expiresAt <= Date.now()) return null;
+ return row;
+}
+
+export function composioRemoteUserId(instanceId: string, userUid: string): string {
+ storeKey(instanceId, userUid);
+ return `mso:${instanceId}:${userUid}`;
+}
+
+/**
+ * Create-or-reuse for the credential owner selected server-side. Composio bills and
+ * rate-limits per session and the session MCP endpoint is per-session, so a stored
+ * session is reused until `refresh`. Sessions do not expire upstream, so a stored
+ * row stays valid; a session deleted upstream surfaces when an agent calls it.
+ */
+export async function composioSessionForUser(input: {
+ values: InfraProviderValues;
+ user?: string;
+ refresh?: boolean;
+ toolkits?: string[];
+ authConfigs?: Record<string, string>;
+ fetchImpl?: (value: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
+}): Promise<ComposioSessionResolution> {
+ const state = await readIntegrationState();
+ const user = input.user ?? resolveUser(state, currentIntegrationSelection());
+ const profile = state.users[user];
+ if (!profile) throw new IntegrationError("user_not_found", 404);
+ const instanceId = state.instanceId, userUid = profile.uid;
+ if (!input.refresh) {
+ const stored = await readComposioSession(instanceId, userUid);
+ if (stored) return { sessionId: stored.sessionId, mcpUrl: stored.mcpUrl, mcpHeaders: stored.mcpHeaders, ...(stored.expiresAt !== undefined ? { expiresAt: stored.expiresAt } : {}), reused: true, user };
+ }
+ const created = await createComposioSession({
+ values: input.values,
+ userId: composioRemoteUserId(instanceId, userUid),
+ toolkits: input.toolkits,
+ authConfigs: input.authConfigs,
+ fetchImpl: input.fetchImpl,
+ });
+ const key = storeKey(instanceId, userUid);
+ await withSecurityStoreLock(composioSessionStorePath(), async () => {
+ const store = await readComposioSessions();
+ store.sessions[key] = { ...created, instanceId, userUid, createdAt: Date.now() };
+ await writeComposioSessions(store);
+ });
+ return { ...created, reused: false, user };
+}
diff --git a/lib/infra/composio.test.ts b/lib/infra/composio.test.ts
index fd7a390c..ea9bc7e8 100644
--- a/lib/infra/composio.test.ts
+++ b/lib/infra/composio.test.ts
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("server-only", () => ({}));
-import { composioAuthHeader, doctorComposio } from "./composio";
+import { composioAuthHeader, composioKeyKind, doctorComposio } from "./composio";
afterEach(() => vi.unstubAllGlobals());
@@ -36,4 +36,12 @@ describe("composio connect consumer keys", () => {
expect(() => composioAuthHeader({ orgApiKey: "ck_consumer_key" })).toThrow(/Project MCP/);
expect(() => composioAuthHeader({ apiKey: "ak_project" })).not.toThrow();
});
+
+ it("reports the key kind for a form without exposing the value", () => {
+ expect(composioKeyKind({ apiKey: "ak_project" })).toBe("project");
+ expect(composioKeyKind({ apiKey: "uak_user" })).toBe("user");
+ expect(composioKeyKind({ orgApiKey: "org_admin" })).toBe("organization");
+ expect(composioKeyKind({ apiKey: "ck_consumer_key" })).toBe("connect");
+ expect(composioKeyKind({})).toBeNull();
+ });
});
diff --git a/lib/infra/composio.ts b/lib/infra/composio.ts
index c4341b24..6a3b0652 100644
--- a/lib/infra/composio.ts
+++ b/lib/infra/composio.ts
@@ -2,7 +2,8 @@ import type { InfraProviderValues } from "./types";
import { readInfraProvider } from "./store";
import { request } from "./http";
-const API = "https://backend.composio.dev/api/v3.1";
+export const COMPOSIO_API_BASE = "https://backend.composio.dev/api/v3.1";
+const API = COMPOSIO_API_BASE;
/**
* Composio keys live on two different products and only one of them is this
@@ -31,6 +32,15 @@ export function composioAuthHeader(values: InfraProviderValues): { header: Recor
return { header: { "x-api-key": key }, kind: "project" };
}
+/** Which Platform key kind is stored. Safe for a UI: it never touches the key value. */
+export function composioKeyKind(values: InfraProviderValues): "organization" | "user" | "project" | "connect" | null {
+ if (composioConnectKey(values.orgApiKey) || composioConnectKey(values.apiKey)) return "connect";
+ if (values.orgApiKey?.trim()) return "organization";
+ const key = values.apiKey?.trim();
+ if (!key) return null;
+ return key.startsWith("uak_") ? "user" : "project";
+}
+
export async function doctorComposio(candidate?: InfraProviderValues): Promise<string | null> {
const values = candidate ?? await readInfraProvider("composio");
const auth = composioAuthHeader(values);